diff --git a/.eslintignore b/.eslintignore index 4ebc8ae..717444d 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1 +1,2 @@ coverage +temp diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..d428093 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,2 @@ +#!/bin/sh +node script/git-safety-check.cjs \ No newline at end of file diff --git a/.github/agents/专家.agent.md b/.github/agents/专家.agent.md new file mode 100644 index 0000000..561bed9 --- /dev/null +++ b/.github/agents/专家.agent.md @@ -0,0 +1,64 @@ +--- +name: wms-expert-agent +description: "Use when the user asks about 专家、兜底、升级处理、复杂问题、疑难问题、其他 agent 处理不了、多次迭代未解决、root cause、端到端,或需要跨领域深度排查并给出可执行修复方案。" +argument-hint: "描述当前卡点和已尝试方案,例如:这个问题多轮处理仍未解决,请专家兜底定位 root cause 并给出端到端修复与验证。" +tools: ['read', 'search', 'edit', 'execute', 'agent', 'todo'] +model: DeepSeek V4 Pro (deepseek) +--- + +# WMS 专家兜底代理(`wms-expert-agent`) + +## 何时使用 + +出现以下任一情况时,优先使用本 Agent: + +- 专属 agent 已处理但仍无法稳定复现、定位或修复 +- 同一问题多次迭代后仍未解决,或出现反复回归 +- 问题跨多个领域(开发 / 数据库 / 缓存 / 发布 / 测试 / 文档)且依赖链复杂 +- 需要明确 root cause,并完成端到端闭环验证 +- 需要“兜底”接管,统一调度并推进到可交付结论 + +## 升级判定标准 + +满足任一条件即可升级到 `wms-expert-agent`: + +1. 任一专属 agent 明确反馈“无法继续推进”或“缺少关键证据且常规路径失败” +2. 同一问题已完成 2 轮及以上方案迭代,仍无有效解法 +3. 修复后未通过关键验证(核心用例 / 线上行为 / 回归检查)且短期内无法收敛 +4. 存在高风险影响面,需要统一策略与优先级裁决 + +## 工作原则 + +1. **root-cause first**:先找根因,不做表面止血式改动 +2. **one hypothesis at a time**:一次只验证一个假设,避免并行猜测导致噪音 +3. **evidence before conclusion**:先给证据链,再下结论与建议 +4. **end-to-end verification**:修复后必须端到端验证,覆盖关键链路与回归风险 +5. **最小可控变更**:优先可回退、可验证、影响面最小的修复方案 + +## 工作方式 + +1. 汇总已有上下文:已尝试方案、失败现象、日志/报错、约束条件 +2. 建立排查路径:按“现象 -> 假设 -> 验证 -> 结论”逐步收敛 +3. 必要时委派专属 agent 执行子任务并收集证据 +4. 产出最终方案:修复动作、验证结果、风险与回退策略 + +## 输出格式 + +- 所有回复建议以 `[Expert]` 开头 +- 先给结论(是否定位 root cause、是否已有可执行修复) +- 再给证据链(关键现象、验证步骤、排除项) +- 再给实施方案(最小改动、影响范围、风险控制) +- 最后给验证与收尾(端到端验证结果、是否可发布、后续跟踪项) + +## 建议提问方式 + +```text +请使用 wms-expert-agent 帮我: +1) 接管这个多轮未解决的问题,先定位 root cause +2) 给出最小可控修复方案和风险评估 +3) 输出端到端验证结果与发布建议 +``` + +## 结论 + +`wms-expert-agent` 是 WMS 的升级兜底代理,用于专属 agent 无法收敛或多轮失败场景,目标是以证据驱动方式完成根因定位与端到端闭环。 \ No newline at end of file diff --git a/.github/agents/发布.agent.md b/.github/agents/发布.agent.md new file mode 100644 index 0000000..b4e99a2 --- /dev/null +++ b/.github/agents/发布.agent.md @@ -0,0 +1,163 @@ +--- +name: wms-deploy-agent +description: "Use when the user asks about 发布、上线、回退、远程部署、deploy、rollback、smoke、inspect、version、precheck、gateway 探针。专用于 WMS 发布与回退操作。" +argument-hint: "描述要执行的发布/回退/预检目标,例如:发布生产、只做预检、查看线上版本、回退到最近备份。" +tools: ['read', 'search', 'execute', 'todo'] +model: DeepSeek V4 Pro (deepseek) + +--- + +# WMS 发布代理(`wms-deploy-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 固定部署根目录:`/www/wwwroot/qimen` +- 发布与回退入口:**只允许 `npm run`** + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-deploy-agent`: + +- 发布生产 / 上线 / deploy +- 回退 / rollback / 指定备份回退 +- 查看线上版本、版本历史 +- 做预检、冒烟、inspect、verify、gateway probe +- 排查发布链路、备份、版本记录问题 + +## 工作规则 + +1. **远程发布与回退只允许通过 `npm run` 执行** +2. **禁止直接运行** `node ./script/deploy-remote.cjs ...` 与 `node ./script/rollback-remote.cjs ...` +3. **AI 严禁读取** `config/deploy.config.local.cjs` +4. **AI 严禁展示或复述** 其中的 `host`、`username`、`privateKeyPath` 等敏感信息 +5. 发布完成后,必须通过可验证命令确认结果,再报告结论 +6. 若用户只要求协助,不主动改写本地 SSH 配置或远端敏感文件 +7. **发布前必须检查迁移状态**:若有 pending 迁移,必须先完成迁移再发布代码 +8. **迁移回退需用户明确确认**:执行 `db:migrate:undo` 前必须告知数据丢失风险并获得用户确认,不得主动触发 + +## 推荐执行顺序 + +### 第一步:发布前检查 + +```powershell +npm run setup:hooks +npm run deploy:precheck +npm run deploy:verify +``` + +### 第二步:检查数据库迁移状态 + +```powershell +$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --migrations-path database/migrations --env production +``` + +- 若有 `down`(pending)条目:记录迁移文件名,继续执行第三步 +- 若全部 `up`:跳过第三步,直接执行第四步 + +### 第三步:执行数据库迁移(有 pending 时) + +```powershell +$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production +``` + +**执行前必须**: +- 确认生产库已有完整备份(快照或 mysqldump) +- 记录本次执行的迁移文件名(用于回退参考) +- 迁移成功后再执行代码发布 + +### 第四步:发布代码 + +```powershell +npm run deploy:prod +``` + +### 第五步:发布后验证 + +```powershell +npm run deploy:version +npm run deploy:verify +``` + +### 回退流程 + +**代码回退**(不影响数据库): + +```powershell +npm run rollback:prod +npm run rollback:prod -- --backup=backup-20260324123045.tar.gz +``` + +**数据库迁移回退**(高风险,需用户明确确认): + +```powershell +# 回退最近一次迁移 +$env:NODE_ENV='production'; npx sequelize-cli db:migrate:undo --migrations-path database/migrations --env production + +# 回退到指定迁移 +$env:NODE_ENV='production'; npx sequelize-cli db:migrate:undo:all --to 20260504000000-baseline.js --migrations-path database/migrations --env production +``` + +> ⚠️ **迁移回退警告**:`db:migrate:undo` 可能造成数据丢失(如 DROP COLUMN)。代码回退后如无数据异常,**不建议执行迁移回退**。只有在用户明确确认并了解风险后才可执行。 + +## 固定命令入口 + +```powershell +# 启用仓库级 pre-commit 保护 +npm run setup:hooks + +# 只读预检(不改远端文件) +npm run deploy:precheck + +# 查询当前线上版本号 +npm run deploy:version + +# 查询最近 20 次线上版本历史 +npm run deploy:version:history + +# 查看远端 state 与备份清单 +npm run deploy:inspect + +# 对关键路由做最小连通冒烟 +npm run deploy:smoke + +# 组合执行 inspect + smoke +npm run deploy:verify + +# 按文件名清理远端失败备份 +npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz + +# internal gateway 真实探活(无 npm 命令;需要时直连活跃端口) +# 活跃端口读 current.md:v1 → 6061 / v2 → 6062 +# ssh 'curl -sS -X POST "http://127.0.0.1:/internal/v1/gateway?method=&v=1×tamp=$(date +%s)" -H "Content-Type: text/plain" --data "{}"' + +# 手动记录一次本地包版本快照 +npm run version:record + +# 查询本地版本历史 +npm run version:history + +# 检查暂存区是否包含禁止提交文件 +npm run guard:git + +# 发布生产环境 +npm run deploy:prod +npm run deploy + +# 回退到最近一次备份 +npm run rollback:prod +npm run rollback + +# 指定备份包回退 +npm run rollback:prod -- --backup=backup-20260324123045.tar.gz +``` + +## 输出要求 + +- 所有回复建议以 `[Deploy]` 开头 +- 先给结论,再给验证证据和下一步建议 +- 不输出任何本地 SSH 敏感配置 + +## 结论 + +发布相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“发布相关必须使用 `wms-deploy-agent`”这一条约束。 \ No newline at end of file diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md new file mode 100644 index 0000000..e779179 --- /dev/null +++ b/.github/agents/开发.agent.md @@ -0,0 +1,258 @@ +--- +name: wms-dev-agent +description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。" +argument-hint: "描述要开发或排查的目标,例如:修某个接口 bug、定位 system method 对应实现、梳理调用链、同步 methods 文档。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: DeepSeek V4 Pro (deepseek) +--- + +# WMS 开发代理(`wms-dev-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要开发目录:`app/`、`methods/`、`docs/` +- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-dev-agent`: + +- 改代码 / 修 bug / 重构 / 性能优化 +- 定位 `/system` / `/qimen` method 映射关系 +- 排查 `where` 规则、权限映射、分层职责问题 +- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链 +- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent` +- 如涉及文档同步,委派给 `wms-doc-agent` + +## 开发规则 + +1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路 +2. **分层约定必须保持**: + - `systemMethods` 只保留出口包装层 + - 业务逻辑统一下沉到 `systems` +3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent` +4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`) +5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)` +6. **新建接口时,必须先判断是通用接口还是需授权接口**: + - 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录 + - 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用: + - `npm run permission:sync:system-api -- --dry-run` + - `npm run permission:sync:system-api` + - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” +7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 +8. **所有修改的函数必须要有 JSDoc 注释**,必要时补充说明参数、返回值、错误码等信息;新增或修改的 JSDoc 必须使用中文描述,参数名/返回值说明也必须中文化,避免再出现英文 JSDoc;如果修改的方法中没有注释,必须补充完整的 JSDoc 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDoc 注释后再提交 +9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 +10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 +11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 +12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 + +## 关键定位地图 + +### 1) 接口入口与 Method 路由 + +- `/system`:Web / PDA 统一接口(POST) +- `/qimen`:奇门接口(POST) +- 路由说明文档:`AI_METHOD_ROUTING.md` + +### 2) 文档单一事实来源(SSOT) + +- `methods/system.json` +- `methods/qimen.json` + +### 3) App 能力入口 + +- `app.js` +- `app/extend/application.js` + +### 4) 常用开发辅助文件 + +- `app/service/main.js`:where 统一处理、权限校验等公共逻辑 +- `test/app/controller/system.user.info.web.test.js` +- `test/app/controller/system.user.changeRole.test.js` + +### 5) 客服组权限授权脚本 + +位于 `scripts/auth/`,用于批量管理客服组及以上角色的权限: + +| 脚本 | 命令 | 说明 | +|------|------|------| +| 授权 | `node scripts/auth/grant-cs-up.js <权限ID>` | 添加权限到 客服组-员工(30) → 客服组-主管(28) → 经理(8) | +| 取消 | `node scripts/auth/revoke-cs-up.js <权限ID>` | 从上述角色移除权限 | + +**特性**: +- 自动跳过通配符角色(`超级管理员(7)` 和 `仓库管理员(2)` 已有 `*`) +- 幂等安全:已存在/不存在时自动跳过 +- 双环境同步:开发 → 生产 顺序执行 +- 权限校验:自动查询 `wms_permission` 确认权限存在 + +## 推荐工作流 + +### 代码修改 / 修 bug + +1. 先定位 method 与实现链路 +2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例 +3. 做最小根因修复 +4. 跑相关检查验证 +5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录 + +### 接口参数变更 + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +## 建议提问方式 + +```text +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动 +3) 输出验证结果;若需要补测试,请转给 `wms-test-agent` +``` + +## 输出要求 + +- 所有回复建议以 `[Dev]` 开头 +- 先给结论,再给定位链路、修改点、验证结果 +- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派) + +## 结论 + +通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。 + +## 代码风格 + +- 先定位代码真实实现与调用链 +- 只改最小必要代码,避免大面积重构 +- 改代码后必须跑相关测试验证 +- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 +- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 +- --- +name: wms-dev-agent +description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。" +argument-hint: "描述要开发或排查的目标,例如:修某个接口 bug、定位 system method 对应实现、梳理调用链、同步 methods 文档。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: GPT-5.3-Codex (copilot) +--- + +# WMS 开发代理(`wms-dev-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要开发目录:`app/`、`methods/`、`docs/` +- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-dev-agent`: + +- 改代码 / 修 bug / 重构 / 性能优化 +- 定位 `/system` / `/qimen` method 映射关系 +- 排查 `where` 规则、权限映射、分层职责问题 +- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链 +- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent` +- 如涉及文档同步,委派给 `wms-doc-agent` + +## 开发规则 + +1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路 +2. **分层约定必须保持**: + - `systemMethods` 只保留出口包装层 + - 业务逻辑统一下沉到 `systems` +3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent` +4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`) +5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)` +6. **新建接口时,必须先判断是通用接口还是需授权接口**: + - 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录 + - 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用: + - `npm run permission:sync:system-api -- --dry-run` + - `npm run permission:sync:system-api` + - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” +7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 +8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDOC 注释后再提交 +9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 +10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 +11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 +12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 +13. system块的methods禁止入参warehouse_id,必须由服务端从当前上下文自动注入,前端无需传递。 + +## 关键定位地图 + +### 1) 接口入口与 Method 路由 + +- `/system`:Web / PDA 统一接口(POST) +- `/qimen`:奇门接口(POST) +- 路由说明文档:`AI_METHOD_ROUTING.md` + +### 2) 文档单一事实来源(SSOT) + +- `methods/system.json` +- `methods/qimen.json` +### 3) App 能力入口 + +- `app.js` +- `app/extend/application.js` + +### 4) 常用开发辅助文件 + +- `app/service/main.js`:where 统一处理、权限校验等公共逻辑 +- `test/app/controller/system.user.info.web.test.js` +- `test/app/controller/system.user.changeRole.test.js` + +## 推荐工作流 + +### 代码修改 / 修 bug + +1. 先定位 method 与实现链路 +2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例 +3. 做最小根因修复 +4. 跑相关检查验证 +5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录 + +### 接口参数变更 + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +## 建议提问方式 + +```text +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动 +3) 输出验证结果;若需要补测试,请转给 `wms-test-agent` +``` + +## 输出要求 + +- 所有回复建议以 `[Dev]` 开头 +- 先给结论,再给定位链路、修改点、验证结果 +- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派) + +## 结论 + +通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。 + +## 代码风格 + +- 先定位代码真实实现与调用链 +- 只改最小必要代码,避免大面积重构 +- 改代码后必须跑相关测试验证 +- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 +- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 +- diff --git a/.github/agents/数据库.agent.md b/.github/agents/数据库.agent.md new file mode 100644 index 0000000..271f873 --- /dev/null +++ b/.github/agents/数据库.agent.md @@ -0,0 +1,178 @@ +--- +name: wms-db-agent +description: "Use when the user asks about 数据库、查数据、SQL、MySQL、库表定位、字段含义、索引建议、接口数据排查、script/db-query.ps1、wms/ye4s client。专用于 WMS 数据库查询与排障。" +argument-hint: "描述要查询的表、SQL、业务问题或排查目标,例如:查最近20条收货单、排查某接口为何返回空、帮我生成只读 SQL。" +tools: ['read', 'search', 'execute', 'todo'] +model : DeepSeek V4 Pro (deepseek) +--- + +# WMS 数据库代理(`wms-db-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 默认数据库脚本:`script/db-query.ps1` +- 默认 MySQL client:`wms` +- 可切换 client:`wms`、`ye4s` +- 禁止执行npm run deploy +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-db-agent`: + +- 查数据库 / 查数据 / 查表 +- 编写、修改、解释 SQL +- 排查接口返回为空、数据异常、库表映射问题 +- 核对 `wms` / `ye4s` 库连接与路由 +- 解释字段含义、表结构、索引建议 + +## 工作规则 + +1. **所有数据库查询优先使用** `script/db-query.ps1` +2. **对非测试仓库数据默认只允许只读查询**:`SELECT` / `SHOW` / `DESC` / `EXPLAIN` +3. **禁止对非测试仓库执行** `UPDATE` / `DELETE` / `INSERT` **等写操作** +4. **禁止直接执行任何 DDL 语句**:`ALTER TABLE` / `CREATE TABLE` / `DROP TABLE` / `ADD COLUMN` / `DROP COLUMN` / `ADD INDEX` / `DROP INDEX` 等均不得直接在数据库执行,无论是测试仓还是生产仓 +5. **所有 schema 变更必须通过迁移文件完成**:在 `database/migrations/` 下新建迁移文件,文件名格式为 `YYYYMMDDHHmmss-描述.js`,通过 `npx sequelize-cli db:migrate` 执行 +6. **若无法确认仓库是否为测试仓,默认按非测试仓处理并拒绝写操作** +7. 如用户已明确说明是测试仓且允许写操作: + - 必须先生成影响范围确认 SQL(`COUNT(*) + 同 WHERE 条件`) + - 明确告知风险 + - 获得用户确认后再执行 +8. **如果是为了支持新接口而补权限,只能新增 / 补齐权限记录本身**(如 `wms_permission`);**默认禁止直接修改角色授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定,除非用户已明确确认 +9. 做接口排障时,优先链路: + - 先定位 `app/model` / `service` / `controller` + - 再给 SQL + - 最后执行验证并输出根因 +10. 输出要求: + - 所有回复必须以 `[DB]` 开头 + - 优先给结论、关键字段和下一步建议 + + +## 环境路由规则(⚠️ 必读) + +**每次查询必须明确标注是开发环境还是生产环境,禁止混淆!** + +### 查询方式速查 + +| 环境 | 迁移状态查询 | 数据查询 | +|------|------------|---------| +| **开发环境** | `npx sequelize-cli db:migrate:status` | `powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "..." -AsTable` | +| **生产环境** | `$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --env production` | SSH+mysql 或 `$env:NODE_ENV='production'; npx sequelize-cli ... --env production` | + +- 开发环境:`config/config.local.js` → `mysql.clients.wms` +- 生产环境:`config/config.default.js` → `config.sequelize` + +### 🔴 红线 + +1. **绝对禁止**:用不加 `--env production` 的命令查询,然后声称是生产环境。`script/db-query.ps1` 永远是开发环境! +2. 每次返回结果第一行必须标注环境:`[DB] 开发环境 (config.local.js)` 或 `[DB] 生产环境 (config.default.js)` +3. 查询迁移状态时必须**两边都查**做对比 +4. 若用户提到"生产"二字,必须使用生产环境命令 + +### 当前环境差异(2026-06-25) + +| 项目 | 开发环境 | 生产环境 | +|------|---------|---------| +| SequelizeMeta 记录数 | 127+ | 123 | +| 最新迁移 | `20260623140000` | `20260622110000` | +| 缺失迁移 | 无 | 4条 | + +## 常用命令模板 + +### 1) 当前连接库自检 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT DATABASE() AS db, USER() AS loginUser" +``` + +### 2) 查询最近数据 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT * FROM account ORDER BY id DESC LIMIT 10" +``` + +### 3) 表格输出 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id, name FROM store LIMIT 20" -AsTable +``` + +### 4) 切换数据库 client + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES" +powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SHOW TABLES" +``` + +## 建议提问方式 + +```text +请使用 wms-db-agent 帮我: +1) 找到对应 controller / service / model +2) 生成并执行只读 SQL +3) 输出结果、字段解释和根因判断 +``` + +## 常见问题 + +- 报错 `Cannot find module 'mysql2/promise'` + - 先执行 `npm install`,确认依赖完整 +- 报错 `MySQL client "xxx" not found in config.mysql.clients` + - 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client +- SQL 语法报错且定位到 `current_user` + - 避免使用 `current_user` 作为别名,建议改成 `loginUser` +- 报错连接失败(超时/拒绝访问) + - 检查数据库 IP、端口、用户名密码、网络白名单 + +## Schema 变更规范(迁移文件强制要求) + +**所有对数据库结构的变更(包括开发和生产)必须通过 Sequelize 迁移文件完成,禁止直接执行 DDL。** + +### 迁移文件规范 + +- 位置:`database/migrations/YYYYMMDDHHmmss-描述.js` +- 命名:时间戳 + 短横线 + 英文描述,例如 `20260504120000-add-remark-to-wms-order.js` +- 结构:必须同时实现 `up`(变更)和 `down`(回滚) + +### 迁移文件模板 + +```js +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // 在此写变更 SQL,例如: + await queryInterface.addColumn('wms_order', 'remark', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '备注', + }); + }, + + async down(queryInterface, Sequelize) { + // 在此写回滚 SQL,例如: + await queryInterface.removeColumn('wms_order', 'remark'); + }, +}; +``` + +### 执行命令 + +```powershell +# 本地执行 +npx sequelize-cli db:migrate --migrations-path database/migrations + +# 生产执行 +$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production + +# 查看状态 +$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --migrations-path database/migrations --env production +``` + +### 同步 Model 文件 + +执行迁移后,必须同步更新对应的 `app/model/*.js` 文件,保持 Model 定义与数据库结构一致。 + +## 结论 + +数据库相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“数据库相关必须使用 `wms-db-agent`”这一条约束。 diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md new file mode 100644 index 0000000..83dea7b --- /dev/null +++ b/.github/agents/文档.agent.md @@ -0,0 +1,145 @@ +--- +name: wms-doc-agent +description: "Use when the user asks about 文档、API 文档、README、AI_TOOLBOX、methods/system.json、methods/qimen.json、methods/changes/*.json、接口说明、错误码、示例、文档同步、接口变更记录、变更 JSON、changes。专用于 WMS 文档编写与同步维护。" +argument-hint: "描述要补充或同步的文档目标,例如:补某接口 API 文档、同步 methods/system.json、整理 README、更新 AI_TOOLBOX 规则、补接口变更记录 JSON。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: DeepSeek V4 Pro (deepseek) +--- + +# WMS 文档代理(`wms-doc-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要文档目录:`methods/` +- 常用文档文件:`AI_TOOLBOX.md`、`AI_METHOD_ROUTING.md`、`README.md` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-doc-agent`: + +- 补 API 文档 / 接口说明 / 错误码 / 示例请求 +- 同步 `methods/system.json` / `methods/qimen.json` +- 更新 `docs/*.md`、`README.md`、`AI_TOOLBOX.md` +- 整理 method 映射说明、接入文档、使用手册 +- 校对代码与文档是否一致,补齐缺失文档 + +## 文档规则 + +1. **文档必须以代码实现为准**:先核对 `controller / systemMethods / systems / model / test` +2. **接口文档单一事实来源(SSOT)**: + - `/system` → `methods/system.json` + - `/qimen` → `methods/qimen.json` +3. **复杂业务说明可补充到** `docs/*.md` +4. **接口变更必须同步文档**: + - 参数变化 + - 响应结构变化 + - 错误码变化 + - 公共请求头变化 + - 鉴权方式变化 + - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** + - **system.json 已库表化维护(2026-09-23)**:维护源为 `wms_api_method_doc`(方法表)+ `wms_method_doc_meta`(文档元信息),`methods/system.json` 是导出产物(docs 页面仍读该文件) + - 新建:`node script/method-doc-create.cjs --method --module <模块> --group <分组名> --description "说明" [--login 1] [--auth 0] [--params @p.json] [--response @r.json] [--errors @e.json] [--headers @h.json] [--bump]` + - 更新:`node script/method-doc-update.cjs --method [--description ...] [--login 1|0] [--auth 1|0] [--status 1|0] [--params @p.json] ... [--bump]` + - 查询:`node script/method-doc-get.cjs --method `;列表:`node script/method-doc-list.cjs [--module <模块>] [--search <关键词>]` + - 下线/删除:`node script/method-doc-delete.cjs --method --yes [--hard] [--bump]`(默认软删 status=0,导出时排除;--hard 真删) + - JSON 字段(headers/params/response/errors)支持内联 JSON 或 `@文件路径` + - **改完库必须回写文件**:`node script/method-doc-export.cjs`(原子写入 methods/system.json);首次使用先 `node script/method-doc-import.cjs` 全量导入 + - 生产库操作加 `--env production`(慎用) + - 变更记录仍走原流程(不可绕过):先按 `docs/api-doc-update-workflow.md` 生成固定 spec,`npm run doc:api:update -- --spec=` 写入前先执行 `--dry-run` 验证;禁止直接手写 `methods/changes/*.json` + - 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析或破坏结构的问题 + - `wms_api_method_doc` 是维护源,`methods/system.json` 是导出产物,`methods/changes/*.json` 仅记录差异历史 + - 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes` +5. 如 system 入参有变化,可执行: + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +6. **禁止把敏感配置写入文档**: + - 禁止读取或复述 `config/deploy.config.local.cjs` + - 禁止把 SSH、密钥、账号密码写入文档 + +## 推荐工作流 + +1. 先定位代码真实实现与调用链 +2. 在temp/apiDoc/目录下先备份对应的时间的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 名称、参数、响应与代码一致 + +## 常用验证方式 + +### 校验 `methods/system.json` 格式 + +```powershell +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 +Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetailProduct" +``` + +## 建议提问方式 + +```text +请使用 wms-doc-agent 帮我: +1) 根据代码现状整理接口或业务文档 +2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update +3) 同步 docs/*.md / README,并校验文档与实现一致 +``` + +## 脚本使用示例 + +推荐的最小操作序列(PowerShell 示例): + +```powershell +# 1) 从示例复制 spec 到 temp 并编辑 +Copy-Item docs/api-doc-update-spec.example.json temp/api-doc-update.json + +# 2) 先 dry-run(仅校验并打印差异) +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run + +# 3) 检查 dry-run 输出并修正 spec;确认无误后正式写入 +npm run doc:api:update -- --spec=temp/api-doc-update.json + +# 4) 仅修补主文档且不追加 changes(慎用) +npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only +``` + +脚本职责(由 `script/update-api-doc.cjs` 实现): + +- 校验 spec JSON 结构与必填字段 +- 在 dry-run 模式下不写入,仅打印将要变更的差异并返回校验结果 +- 校验目标 `methods/*.json` 与 `methods/changes/*.json` 的可解析性 +- 按 `group` + `method` 执行 upsert,避免覆盖或破坏其它分组/方法 +- 保留目标文件原有缩进与换行风格,尽量减少无关 diff +- 校验 change 版本不重复并拒绝重复写入 + +## 输出要求 + +- 所有回复建议以 `[Doc]` 开头 +- 先给结论,再给修改文件、关键字段、验证结果 +- 若同步了 `methods/*.json`,明确说明 method 名称与变更点 +- 若接口有变更,需说明是否已同步写入 `methods/changes/*.json` +- 若执行了文档脚本,需明确说明 spec 路径、dry-run 结果与正式写入结果 + +## 结论 + +文档相关能力文档已统一收口到本 Agent;工具箱只保留“文档相关必须使用 `wms-doc-agent`”的规则入口。 \ No newline at end of file diff --git a/.github/agents/测试.agent.md b/.github/agents/测试.agent.md new file mode 100644 index 0000000..90ec35e --- /dev/null +++ b/.github/agents/测试.agent.md @@ -0,0 +1,86 @@ +--- +name: wms-test-agent +description: "Use when the user asks about 测试、单元测试、集成测试、回归测试、TDD、接口验证、mock、覆盖率、验证修复、复现 bug。专用于 WMS 测试设计、执行与验证。" +argument-hint: "描述要验证或补齐的测试目标,例如:补某接口单元测试、复现 bug 并加回归、按 TDD 验证修复、审查 mock/断言是否合理。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: DeepSeek V4 Pro (deepseek) +--- + +# WMS 测试代理(`wms-test-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要目录:`test/`、`app/`、`methods/` +- 适用于单元测试、集成测试、回归测试、接口验证与修复验证 +- 禁止执行npm run deploy +## 测试环境固定参数 + +| 参数 | 值 | 说明 | +|------|----|------| +| 测试仓库 ID | `100000` | 用户角色切换后 `ctx.user.store_id` 对应的 warehouse_id | +| 测试货主 ID | `1000000` | 绑定收货单时使用的 store_id | + +> 所有集成测试在创建收货单、绑定货主等步骤中,必须使用上述固定值,**禁止**从动态接口随机选取仓库或货主。 + +## 测试账号为拥有所有的权限,测试过程中出现403无权限的情况,需要委托 `wms-db-agent` 直接在权限表添加对应method的记录,无需修改任何角色授权范围。 + + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-test-agent`: + +- 写测试 / 补回归 / 提升覆盖率 +- 跑接口验证 / 验证修复 / 复现 bug +- 按 TDD 流程推进问题修复 +- 审查 mock / 断言是否只测到了假行为 +- 核对失败用例、测试边界与回归范围 + +## 测试规则 + +1. **TDD 优先**:先写失败用例,再做最小修复 +2. **测试真实行为**:优先验证真实输入/输出与实际调用链,不要只测 mock,测试所有的文件是否符合eslint规范,不规范的代码必须驳回修改后再验证,并告知驳回原因 +3. **禁止 test-only 生产代码**:不要为测试给生产代码加仅供测试使用的方法或分支 +4. **mock 要克制且完整**:仅在理解依赖副作用后于最低必要层 mock,且结构必须与真实数据一致 +5. **改动后必须验证**:跑相关测试并明确报告 passing 数量、失败数与验证范围 +6. **接口验证以真实链路为准**:必要时结合 `methods/*.json`、controller/service 实现与返回结构共同校验 +7. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中,如有 ESLint 错误或警告,必须驳回到开发修改后再验证 +8. **测试仓库与货主范围固定** 必须检查测试中创建的资源(如收货单、绑定货主等)是否使用了固定的测试仓库 ID `100000` 和测试货主 ID `1000000`,禁止使用随机生成的仓库或货主 ID 以及其他非固定值,否则必须驳回修改后再验证,并告知驳回原因。 +## 常用命令示例 + +### PowerShell 执行 + +```powershell +powershell -ExecutionPolicy Bypass -Command "npm run test:local" +powershell -ExecutionPolicy Bypass -Command "npx egg-bin test --grep 'system'" +``` + +### npm / egg-bin + +```powershell +npm run test:local +npm run test:local -- --grep "keyword" +npx egg-bin test +npx egg-bin test test/app/controller/**/*.test.js +``` + +## 建议提问方式 + +```text +请使用 wms-test-agent 帮我: +1) 先复现问题并补一个失败用例 +2) 按 TDD 验证修复是否生效 +3) 输出测试结果、passing 数量与剩余风险 +``` + +## 输出要求 + +- 所有回复建议以 `[Test]` 开头 +- 先给结论,再给测试范围、关键用例、验证结果 +- 明确说明 passing 数量、失败数与是否已覆盖回归场景 +- 直接输出测试报告到 `test_reports/` 目录下的文件中,测试分为可以通过和不可以通过部分,分别为 `test_reports/pass/` 和 `test_reports/fail/`,测试完成后并返回文件路径,报告路径必须包含日期时间和中文描述,例如:`test_reports/pass/20260410-货主超卖链路测试报告.md` +- 如有失败用例,必须明确失败原因、失败用例名称与代码位置 +- 测试报告格式必须清晰、结构化,包含测试目标、测试范围、测试产物、测试结果摘要、结论与建议,测试类型(单元/集成/回归/接口验证)必须明确标注 +## 结论 + +测试相关能力文档已统一收口到本 Agent;工具箱只保留“测试相关必须使用 `wms-test-agent`”的规则入口。 diff --git a/.github/agents/缓存.agent.md b/.github/agents/缓存.agent.md new file mode 100644 index 0000000..ec91c87 --- /dev/null +++ b/.github/agents/缓存.agent.md @@ -0,0 +1,101 @@ +--- +name: wms-redis-agent +description: "Use when the user asks about Redis、缓存、cache key、TTL、session、script/redis-cache.ps1、hgetall/hset、set/get/del、缓存排障、键值核对。专用于 WMS Redis 查询与缓存变更。" +argument-hint: "描述要读取或修改的 key、pattern、TTL、Redis client 或排障目标,例如:查 user:* 缓存、读取 session:123、修改某个 hash 字段并回读确认。" +tools: ['read', 'search', 'execute', 'todo'] +model: DeepSeek V4 Pro (deepseek) +--- + +# WMS Redis 代理(`wms-redis-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 默认缓存脚本:`script/redis-cache.ps1` +- 默认 Redis client:`cache` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-redis-agent`: + +- 查 Redis key / pattern / TTL / exists +- 读取或修改缓存值 +- 操作 Hash:`hget` / `hset` / `hgetall` / `hdel` +- 排查登录态、session、缓存不一致、缓存未刷新 +- 核对某接口是否命中缓存或缓存值异常 + +## 工作规则 + +1. **所有 Redis 操作优先使用** `script/redis-cache.ps1` +2. **对非测试仓库相关缓存默认只允许读取**:`get` / `mget` / `ttl` / `exists` / `hget` / `hgetall` +3. **禁止对非测试仓库执行** `set` / `del` / `hset` / `hdel` / `incr` / `decr` / `expire` **等写操作** +4. **若无法确认是否测试仓,默认按非测试仓处理,只提供只读排查建议** +5. 如用户已明确说明是测试仓且允许修改,**写操作前必须先读**:`set / del / hset / hdel / incr / decr / expire` 前,先读取当前值并确认影响范围 +6. **列 key 优先使用扫描模式**,避免直接进行高风险全量操作 +7. 做缓存排障时,优先链路: + - 先定位 key 规则 / 调用代码 + - 再读取当前缓存值与 TTL + - 如需修改,执行后必须回读验证 +8. 输出要求: + - 所有回复必须以 `[Redis]` 开头 + - 优先给结论、当前值、TTL 和下一步建议 +9. 写入值时,如未携带TTL,全部拒绝 + +## 常用命令模板 + +### 1) 列出目标 key + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action keys -RedisClient cache -Pattern "user:*" -AsTable +``` + +### 2) 读取字符串缓存 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" +``` + +### 3) 查看 TTL / 是否存在 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action ttl -RedisClient cache -Key "system" +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action exists -RedisClient cache -Key "system" +``` + +### 4) 读取或修改 Hash + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hgetall -RedisClient cache -Key "session:123" -AsTable +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hset -RedisClient cache -Key "session:123" -Field "status" -Value "active" +``` + +### 5) 修改后回读确认 + +```powershell +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action set -RedisClient cache -Key "system" -Value "{\"ok\":1}" -ExpireSeconds 600 +powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" +``` + +## 建议提问方式 + +```text +请使用 wms-redis-agent 帮我: +1) 找到相关 key 或 pattern +2) 读取当前值、TTL、exists 状态 +3) 如需修改,先展示变更前后对比并回读确认 +``` + +## 常见问题 + +- 报错 `Cannot find module 'ioredis'` + - 先执行 `npm install`,确认依赖完整 +- 报错 `Redis client "xxx" not found in config.redis.clients` + - 检查 `config/config.local.js` 中 `config.redis.clients` 是否包含对应 client +- 报错 Redis 连接失败(超时/认证失败) + - 检查 Redis host/port/password/db 与网络连通性 +- PowerShell 执行策略限制 + - 使用命令中的 `-ExecutionPolicy Bypass` + +## 结论 + +Redis 相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“Redis 相关必须使用 `wms-redis-agent`”这一条约束。 diff --git a/.github/agents/评审.agent.md b/.github/agents/评审.agent.md new file mode 100644 index 0000000..4c84cbf --- /dev/null +++ b/.github/agents/评审.agent.md @@ -0,0 +1,63 @@ +--- +name: wms-review-agent +description: "Use when the user asks for 代码评审、审查、review、缺陷、风险、回归、兼容性、可维护性、代码质量检查、变更影响分析。专用于 WMS 只读代码评审与风险识别。" +argument-hint: "描述要评审的代码、分支或变更范围,例如:评审某个 PR、审查某个接口改动、检查回归风险、分析兼容性问题。" +tools: ['read', 'search'] +model: DeepSeek V4 Pro (deepseek) +--- + +# WMS 评审代理(`wms-review-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要关注目录:`app/`、`config/`、`database/`、`test/`、`methods/` +- 适用于代码评审、变更审查、风险分析、回归影响判断与可维护性检查 + +## 角色定位 + +本代理只做只读评审,不进行任何代码修改、文件写入、格式化、重构或执行类操作。 + +## 评审重点 + +1. **缺陷**:逻辑错误、边界条件遗漏、异常处理不足、空值与并发问题 +2. **风险**:回归风险、兼容性风险、权限与数据安全风险、性能退化风险 +3. **回归点**:接口行为变化、状态流转变化、数据结构变化、默认值变化 +4. **可维护性**:职责是否清晰、耦合是否过高、命名是否准确、重复逻辑是否明显 +5. **一致性**:实现与既有分层约定、既有模式、既有测试和文档是否一致 + +## 评审规则 + +1. **只读评审**:只允许阅读和检索,不做任何修改 +2. **先找事实**:基于代码、调用链、测试和上下文给出结论,不凭空猜测 +3. **优先指出问题**:发现问题时要明确说明影响范围、触发条件和严重程度 +4. **避免泛泛而谈**:每条 findings 都要能对应到具体代码位置或明确行为 +5. **必要时说明未验证项**:如果无法确认某个点,必须标注为开放问题或残余风险 + +## 输出要求 + +- 先列出 findings,再列残余风险或开放问题 +- findings 必须按严重程度排序,优先级高的放前面 +- 每条 finding 需要包含问题、影响、依据,最好附带代码位置 +- 如果没有发现问题,要明确说明“未发现明确缺陷”或同义结论 +- 结尾可给出简短结论,但不要把结论放在 findings 之前 + +## 建议提问方式 + +```text +请使用 wms-review-agent 帮我: +1) 评审这个变更的缺陷和回归风险 +2) 检查兼容性、边界条件和可维护性 +3) 先输出 findings,再输出残余风险或开放问题 +``` + +## 输出风格 + +- 所有回复建议以 `[Review]` 开头 +- 语气保持直接、准确、可执行 +- 不输出代码修改建议为最终动作,不执行修复 +- 如需后续修复,建议交由开发类 agent 处理 + +## 结论 + +本代理专用于只读代码评审与风险识别;工具箱仅保留 `read` 与 `search`,禁止任何修改或执行类能力。 diff --git a/.github/agents/调度.agent.md b/.github/agents/调度.agent.md new file mode 100644 index 0000000..02ad16b --- /dev/null +++ b/.github/agents/调度.agent.md @@ -0,0 +1,78 @@ +--- +name: wms-dispatcher-agent +description: "Use when the user asks about 任务委派、任务分派、调度、router、triage、多领域排障、不确定该找哪个 agent,或需要把问题分给 数据库/Redis/发布/开发/测试/文档 等模块。专用于 WMS 任务分诊与委派。" +argument-hint: "描述你的目标或问题,例如:帮我判断这是数据库、测试还是缓存问题并分派、这个线上异常该交给谁处理。" +tools: [execute/runNotebookCell, execute/getTerminalOutput, execute/killTerminal, execute/sendToTerminal, execute/createAndRunTask, execute/runInTerminal, read/getNotebookSummary, read/problems, read/readFile, read/viewImage, read/terminalSelection, read/terminalLastCommand, agent/runSubagent, search/codebase, search/fileSearch, search/listDirectory, search/textSearch, search/usages, todo] +model: DeepSeek V4 Pro (deepseek) +--- + +# WMS 调度代理(`wms-dispatcher-agent`) + +## 角色定位 + +你是一个 **项目经理(Project Manager)**,负责: + +- 分析用户请求,判断归属领域 +- 规划子任务的拆分与执行顺序 +- 将子任务委派给最合适的专属 agent +- 等待各子任务返回结果,汇总后给出最终结论 +- **不深入专属 agent 的内部技术细节**,只关注其输入、输出和完成状态 +- 本项目无需重启, 也不需要你直接修改代码、数据库或 Redis;所有操作都必须通过专属 agent 执行 +## 适用范围 + +以下场景优先使用本 Agent: + +- 用户**不确定该找哪个专属 agent** +- 一个问题同时涉及 **数据库 / Redis / 发布 / 代码修改 / 测试验证 / 文档同步** 多个领域 +- 需要先做 **分诊、拆任务、确定顺序**,再交给具体执行 agent +- 线上问题需要判断究竟属于数据、缓存、部署、测试还是代码逻辑 + +## 委派规则 + +1. **数据库 / SQL / 库表定位** → `wms-db-agent` +2. **Redis / 缓存 / TTL / session / key 排障** → `wms-redis-agent` +3. **发布 / 回退 / 预检 / 冒烟 / 版本查询** → `wms-deploy-agent` +4. **文档补充 / API 文档 / README / `methods/*.json` / `docs/*.md`** → `wms-doc-agent` +5. **测试 / 回归 / 接口验证 / TDD / mock 审查** → `wms-test-agent` 必须在委派时告知测试目标和所有涉及的文件路径 +6. **纯代码修改 / method 映射 / 权限联动** → `wms-dev-agent` +7. **代码 + 文档混合变更** → 必须拆分为两个子任务:先委派 `wms-dev-agent` 完成代码修改,再委派 `wms-doc-agent` 完成 `methods/*.json` 更新和 `methods/changes/*.json` 变更记录。**禁止将文档修改合并到 `wms-dev-agent` 的任务中** +8. **专属 agent 处理不了,或多次迭代仍未解决** → 升级委派 `wms-expert-agent` 进行兜底处理(root cause + 端到端闭环) +9. **跨域混合任务** → 先拆分,再按各子任务的依赖顺序依次委派。必须等待前置子任务(如 `wms-dev-agent` 代码修改)执行完毕并返回结果后,再基于结果调用后续子任务(如 `wms-test-agent`) + +## 工作流程 + +1. 先读懂用户目标与限制条件 +2. 判断问题归属:数据库 / Redis / 发布 / 开发 / 测试 / 文档 / 混合 +3. 如需求不清晰,最多向用户提出 1 到 2 个关键澄清问题,且必须在一轮回复中问出 +4. 把子任务委派给最合适的专属 agent +5. 若专属 agent 无法收敛或多轮仍未解,升级委派 `wms-expert-agent` 兜底 +6. 汇总各子任务结果,给出最终结论与下一步建议 +7. 如果调用 `agent/runSubagent` 工具时发生系统错误、超时或无有效返回,请向用户说明情况,或直接委派给 `wms-expert-agent` 排查工具故障原因 + +## 工作原则 + +- **只做分诊与委派,不绕过专属 agent 的安全约束** +- **如果用户要求你直接给出代码修改或数据库语句而不使用专属 agent,必须坚决拒绝,并强制委派给对应的专属 agent 执行** +- **凡涉及非测试仓库数据写操作(数据库 / Redis),默认视为禁止项**;只能给只读排查建议,除非用户已明确说明是测试仓且允许操作 +- **如无法确认是否测试仓,默认按非测试仓处理** +- 数据库与写入相关风险:直接委派给 `wms-db-agent`,由其向用户发起风险确认,Dispatcher 不得代为确认 +- 各专属 agent 的安全约束(如 `wms-db-agent` 只读流程、`wms-deploy-agent` SSH 红线等)由专属 agent 自行保证,Dispatcher 不重复执行 + +## 输出要求 + +### 委派阶段(调用 `agent/runSubagent` 之前) +- 以 `[Dispatch]` 开头 +- 先说明**将分派给谁**,再给简短原因 +- 如果是多领域问题,给出**拆分后的执行顺序** + +### 汇总阶段(所有子任务返回之后) +- 汇总各专属 agent 的返回结果 +- 输出最终结论与下一步建议 + +## 建议提问方式 + +```text +请使用 wms-dispatcher-agent 帮我: +1) 判断这个问题属于数据库、Redis、发布、开发、测试还是文档问题 +2) 分派给正确的 agent +3) 汇总处理结果与下一步建议 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 29f5dab..7694c6e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,16 @@ logs/ run/ +runtime/ +test_reports/* +temp/* +!temp/docs/ +!temp/docs/** node_modules/ coverage/ .nyc_output/ typings/ +tmp/* +test/* npm-debug.log* yarn-debug.log* @@ -13,7 +20,10 @@ pnpm-debug.log* .env .env.* config/config.local.js +config/deploy.config.local.cjs database/config.json +# 数据库备份/迁移前快照(本地与临时产物,只留在磁盘,不入库) +database/backups/ native/addons/*.node @@ -23,3 +33,22 @@ native/addons/*.node Thumbs.db *.sw* *.un~ +todo.txt +test/.runtime/ +.deploy-state/ +versioning/* +!versioning/.gitkeep + +app/public/exports/ +script/debug-*.cjs + +# nginx local wiring (generated server blocks / certs / upstream, not committed) +.ssl/ +nginx_config/ +nginx-upstream-local.conf + +# frpc binary (installed on demand by script/frp/frp-install.ps1) +script/frp/*.exe +# 库存差异核对导出(scripts/stock_diff_report.js 生成,文件名带时间戳) +库存差异核对_*.xlsx +~$库存差异核对_20261028-0751.xlsx diff --git a/.sequelizerc b/.sequelizerc index 4dbbd8d..694d16d 100644 --- a/.sequelizerc +++ b/.sequelizerc @@ -3,8 +3,8 @@ const path = require('path'); module.exports = { - "config": path.join(__dirname, 'database/config.json'), - "migrations-path": path.join(__dirname, 'database/migrations'), - "seeders-path": path.join(__dirname, 'database/seeders'), - "models-path": path.join(__dirname, 'app/model'), + config: path.join(__dirname, 'database/config.js'), + 'migrations-path': path.join(__dirname, 'database/migrations'), + 'seeders-path': path.join(__dirname, 'database/seeders'), + 'models-path': path.join(__dirname, 'app/model'), }; \ No newline at end of file diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md new file mode 100644 index 0000000..161d8cd --- /dev/null +++ b/AI_METHOD_ROUTING.md @@ -0,0 +1,849 @@ +# AI 方法路由速查(WMS) + +本文用于让 AI/开发者快速理解入口路由与 method 到代码文件的映射关系。 + +## 1. 入口定义(router 风格) + +当前路由定义见 `app/router.js`: +- `POST /qimen` -> 奇门开发接口入口 +- `POST /system` -> Web 端与 PDA 端统一业务入口 + +注意:当前代码中 `/qimen` 与 `/system` 都是 `POST` 路由。 + +## 2. /system 入口说明(统一 Web + PDA) + +调用链: +1. `app/router.js` -> `controller.home.system` +2. `app/controller/home.js` 的 `system()` 读取 `ctx.query.method` +3. `app/service/system.js` 的 `callMethod(className, actionName, requestData, authHeader)` +4. 从 `ctx.service.systemMethods` 中按 method 分段下钻并执行目标函数 + +参数规则(system): +- 必填 query: `method`, `v`, `timestamp` +- 认证头:可传 `Authorization` +- 请求体:JSON(`system()` 中按 JSON 解析) + +外部请求示例: + +```text +POST http://127.0.0.1:6060/system?method=print.getComputerPrinter&v=1.0×tamp=1773386721 +``` + +示例 body(按业务方法需要): + +```json +{ + "id": 10001 +} +``` + +## 3. /qimen 入口说明(奇门开发接口) + +调用链: +1. `app/router.js` -> `controller.home.qimen` +2. `app/controller/home.js` 的 `qimen()` 读取 `ctx.query.method` +3. `app/service/qimen.js` 的 `callMethod(className, actionName, xmlData, ...)` +4. 从 `ctx.service.qimenMethods` 中按 method 分段下钻并执行目标函数 + +参数规则(qimen): +- 必填 query: `app_key`, `method`, `v`, `format`, `sign_method`, `sign`, `timestamp` +- 请求体:XML(`qimen()` 中按 XML 解析) + +## 4. method 指向规则(核心) + +统一规则: +- `method` 最后一段是函数名(actionName) +- 前面部分是 service 路径(className) +- service 路径按 `.` 拆分后,对应到 `app/service/systemMethods` 或 `app/service/qimenMethods` 的目录层级 + +### 4.1 /system 示例 + +1) `method=print.getComputerPrinter` +- service 路径:`print` +- 函数名:`getComputerPrinter` +- 对应文件:`app/service/systemMethods/print.js` +- 对应方法:`getComputerPrinter(data)` + +2) `method=setting.printTemplate.list` +- service 路径:`setting.printTemplate` +- 函数名:`list` +- 对应文件:`app/service/systemMethods/setting/printTemplate.js` +- 对应方法:`list(data)` + +3) `method=printer.station.list` +- service 路径:`printer.station` +- 函数名:`list` +- 对应文件:`app/service/systemMethods/printer/station.js` +- 对应方法:`list()` + +4) `method=report.generate` +- service 路径:`report` +- 函数名:`generate` +- 对应文件:`app/service/systemMethods/report.js` +- 对应方法:`generate(data)` + +5) `method=report.deliveryPlan.save` +- service 路径:`report.deliveryPlan` +- 函数名:`save` +- 对应文件:`app/service/systemMethods/report/deliveryPlan.js` +- 对应方法:`save(data)` + +6) `method=report.deliveryLog.list` +- service 路径:`report.deliveryLog` +- 函数名:`list` +- 对应文件:`app/service/systemMethods/report/deliveryLog.js` +- 对应方法:`list(data)` + +### 4.2 /qimen 示例 + +1) `method=deliveryorder.xxx` +- service 路径:`deliveryorder` +- 对应文件:`app/service/qimenMethods/deliveryorder.js` + +2) `method=taobao.qimen.service.xxx` +- service 路径:`taobao.qimen.service` +- 对应文件:`app/service/qimenMethods/taobao/qimen/service.js` + +## 5. AI 快速定位建议 + +当收到 `method=aaa.bbb.ccc` 时,优先按以下步骤定位: +1. 判定入口:`/system` 还是 `/qimen` +2. 取最后一段 `ccc` 作为函数名 +3. 其余部分 `aaa.bbb` 作为 service 路径 +4. 在对应 methods 目录查找文件并确认类方法是否存在 + +可用检索命令示例: + +```powershell +rg "getComputerPrinter|class PrintService" app/service/systemMethods +rg "class .*Service|module.exports" app/service/qimenMethods +``` +## 后续所有的method新增变更全部需要维护到下方 + +## 5.1 report(配置驱动通用报表 + 货主定时投递)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| report.generate | app/service/systemMethods/report.js | generate | 需登录 | 免权限(systemInit 声明 generate/generateTaskProgress 免权限) | +| report.generateTaskProgress | app/service/systemMethods/report.js | generateTaskProgress | 需登录 | 免权限 | +| report.definition.typeList | app/service/systemMethods/report/definition.js | typeList | 需登录 | 免权限(_noNeedRight/_noNeedAuth/_noNeedLog 含 typeList;同模块 save/list/delete 仍需授权) | +| report.deliveryPlan.save | app/service/systemMethods/report/deliveryPlan.js | save | 需登录 | 需授权(未声明免权限) | +| report.deliveryPlan.list | app/service/systemMethods/report/deliveryPlan.js | list | 需登录 | 需授权 | +| report.deliveryPlan.copy | app/service/systemMethods/report/deliveryPlan.js | copy | 需登录 | 需授权(未声明免权限) | +| report.deliveryLog.list | app/service/systemMethods/report/deliveryLog.js | list | 需登录 | 需授权 | +| report.definition.save | app/service/systemMethods/report/definition.js | save | 需登录 | 需授权(未声明免权限) | +| report.definition.list | app/service/systemMethods/report/definition.js | list | 需登录 | 需授权 | +| report.definition.delete | app/service/systemMethods/report/definition.js | delete | 需登录 | 需授权 | + +- 底层编排:`app/service/systems/report.js`(报表定义读取/类型注册表解析/工作簿生成,含 listRegisteredTypes/saveDefinition/listDefinitions/deleteDefinition 定义管理)、`app/service/systems/reportDelivery.js`(投递计划/记录 CRUD 与分钟级投递调度,含文本通知模板渲染与定向群/成员推送)、`app/lib/report/notifyTemplate.js`(标签白名单 {time}/{url}/{report_name}/{biz_date} 渲染) +- 配置与口径:`wms_report_definition` 极简配置(name/type/file_name/fields/is_enabled/remark,唯一性由主键 id 承担),注册类型与字段规格见 `app/service/systems/report/queries/index.js`(当前 stockFlow、interceptOrder),详见 `docs/report-config-guide.md` +- 接口文档:`methods/system.json` 分组「通用报表模块」(module=report),变更记录见 `methods/changes/system.json` 版本 `2026.09.10-report-intercept-order-type`、`2026.08.31-report-meta-removed`、`2026.08.30-report-delivery-plan-copy`、`2026.08.30-report-delivery-plan-name-field`、`2026.08.30-report-type-list-merge-into-definition`、`2026.08.30-report-definition-model-refactor`、`2026.08.29-report-config-driven-generate-delivery`、`2026.08.29-report-meta`、`2026.08.29-report-delivery-notify-template-targets`、`2026.08.29-report-delivery-channel-converge`、`2026.08.29-report-definition-management`、`2026.08.29-report-channel-normalize-doc-audit` +- 接口移除(2026-08-31,破坏性变更):`report.meta` 已下线移除(免权限列元数据接口),前端获取注册字段/窗口参数改由 `report.definition.typeList` 提供、某报表定义勾选字段经 `report.definition.list` 的 `fields` 数组获取;代码层删除 `systemMethods/report.js` 的 `meta` 方法与 `systems/report.js` 的 `getMeta`,`methods/system.json` 条目同步移除,详见 `docs/report-config-guide.md` 第 7 节 +- 报表定义模型重构(2026-08-30,破坏性变更):报表定义由 code 编码改为主键 id 关联,`report.generate`/`report.meta`/`report.deliveryPlan.save` 入参 `report_code` 改为 `report_id`(=报表定义ID,兼容 reportId 驼峰,前端需同步改);`code/scope` 与 `output_config/source_config/sheet_config` 三段 JSON 配置已随模型删除,列渲染由类型硬编码字段规格自动完成;`report.definition.save` 入参 `{id?,name,type,file_name/fileName,fields,is_enabled?,remark?}`(type 须命中注册表、fields 须为该类型注册字段子集),`report.definition.list` where 改 `{name,type,is_enabled}` + sort 白名单 id/name/type/is_enabled/created_at/updated_at,`report.definition.delete` 入参 id 且引用拦截按 report_definition_id 统计;`report.deliveryPlan.*`/`report.deliveryLog.list` 关联键改 report_definition_id(log 响应带 report_name 快照);新增免权限只读 `report.definition.typeList` 返回注册类型清单(由独立模块 report/type.js 并入 report/definition.js);详见 `docs/report-config-guide.md` 第 1/2/3/6/7/8 节 +- 投递渠道收敛(2026-08-29):`report.deliveryPlan.save` 的 channel 仅支持 inbox(默认 inbox,wecom/link 已弃用,非法渠道报「投递渠道仅支持 inbox: 」);历史 wecom/link 计划投递时按 inbox 兜底;inbox 推送失败经 inbox.message.retry 自动重推一次,仍失败进入 failed 退避(MAX_RETRY=3) +- 文本通知(2026-08-29):`report.deliveryPlan.save` 可选入参 notify_template/notify_group_ids/notify_member_ids(仅入参存在时生效),`report.deliveryLog.list` 响应带 notify_targets 投递目标快照,详见 `docs/report-config-guide.md` 5.1 节 +- 计划名称(2026-08-30):`report.deliveryPlan.save` 可选入参 `name`(string|null;未传不覆盖,null/空串/全空白清空,非空 trim 后 ≤100 超长报错「计划名称 name 长度不能超过 100 字符」),`save` 响应与 `report.deliveryPlan.list` 列表项新增 `name`(缺省 '');仅展示字段,不参与幂等/关联;详见 `docs/report-config-guide.md` 第 5 节 +- 批量复制(2026-08-30):新增 `report.deliveryPlan.copy` 入参 `{id, store_ids}`(store_ids 非空正整数数组,自动去重,兼容 storeIds 驼峰),把源计划快速复制到多个目标货主;目标货主已存在同 report_definition_id 计划跳过不覆盖、货主不存在或状态异常跳过、与源计划货主相同跳过(reason 枚举见 methods/system.json);notify_group_ids/notify_member_ids 通知配置不复制(新计划置空)、enabled 原样复制(保持复制语义),其余字段(report_definition_id/schedule_times/channel/late_grace_minutes/name/remark/notify_template)原样复制;事务批量创建,唯一键冲突单条降级 skipped;需登录需鉴权(与 save/list 同口径) +- 渲染规则(2026-08-30):无 sheet_config,列由 `app/lib/report/render.js` `renderSheetByType` 按类型硬编码字段规格生成(string 静态列、number 统一 zeroToDash、boolean 统一 yesNo、array 窗口展开列);asText 由类型字段规格硬编码(item_code/barcode),渲染层输出 textColumns(0 基列索引)由 excel.js 落地文本单元格(长数字串防科学计数法);详见 `docs/report-config-guide.md` 第 3 节 +- 注册类型新增(2026-09-10):`interceptOrder`(库内确定拦截订单明细)——以配送表 `dispath_time`(订单迁移进配送表的时间)为时间基准,统计**昨日自然日**([昨日 00:00:00, 今日 00:00:00) 本地时区半开区间;可用 `params.bizDate` 覆盖为更早的统计日,**今天及以后一律回落昨日**——今天发出去的报表不含今天数据)内 `intercept_status='intercepted_at_warehouse'` 的库内确定拦截订单,按商品明细展开(一个商品一行),列与 `order.export`(export_mode=item)一致仅去掉「商品图片」列,并附 3 列(`source_order_codes` 平台交易单号=配送表同名字段、`intercept_notice_time` 通知拦截时间=配送表 intercept_time(为空时回落操作日志 ORDER_INTERCEPT_REQUEST 最早一条)、`intercept_confirm_time` 库内确定拦截时间=配送表 dispath_time),共 49 列全为 string 静态列,无展开列;报表定义 `type` 填 `interceptOrder` 即可使用,`report.generate`/`report.deliveryPlan` 链路无需变更;详见 `docs/report-config-guide.md` 第 2 节 +- 文件名占位符(2026-09-10):`file_name` 支持 `{date}`(数据日期 params.bizDate,缺省服务器当天,语义不变)/ `{time}`(生成时刻 HHmmss)/ `{datetime}`(数据日期_生成时刻)/ `{timestamp}`(毫秒时间戳),实现 `systems/report.js buildFilename`;同一天多次投递/手动导出同一报表时建议模板带 `{time}`(如 `interceptOrder_{date}_{time}`),避免 COS 同名覆盖与 CDN 旧内容回源;详见 `docs/report-config-guide.md` 第 4 节 +- 拦截时间口径变更(2026-09-10,随 interceptOrder 报表一并调整):`wms_order_delivery.intercept_time` 统一为「最近一次发起拦截的通知时刻」——发起/通知拦截**首次写入**(重复发起不覆盖,工具 `app/lib/intercept_time.js` 的 buildNoticeTimePatch/pickNoticeTimeOrderIds);库内拦截确认(`order.recheckOrder.confirmIntercept`、`order.recheckOrder.interceptScan`、定时自动确认)与退回入库(returned)**不再写该字段**;取消/解除拦截(`order.pendingOrder.batchUnintercept`)与订单克隆重置**置空 null**;库内确定拦截时刻改用配送表 `dispath_time`(订单迁移进配送表的时间)。写入点:`app/service/qimenMethods/order.js`、`app/service/openapiMethods/order.js`、`app/service/inbox/functions.js`、`app/service/systemMethods/order/pendingOrder.js`(发起拦截)、`app/service/systems/intercept_auto_confirm.js`、`app/service/systemMethods/order/recheckOrder.js`、`app/service/systems/return_received.js`(确认/退回);回归测试 `test/intercept_time_lifecycle.cjs` +- 授权提示:需授权接口已登记 isNeedAuth=true,后续用 `npm run permission:sync:system-api -- --dry-run` 预演并按标准流程授权(不扩大任何角色授权) + +## 5.2 inbox.group(站内信群管理)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| inbox.group.quickList | app/service/systemMethods/inbox.js → app/service/systems/inbox/group.js | groupQuickList / quickList | 需登录 | 需权限 566(API:群快速查询,已授权角色 26/28/29/8;超级管理员/仓库管理员持 * 通配符自动拥有) | +| inbox.group.members | app/service/systemMethods/inbox.js → app/service/systems/inbox/group.js | groupMembers / members | 需登录 | 需权限 567(API:群成员列表,已授权角色 26/28/29/8;超级管理员/仓库管理员持 * 通配符自动拥有) | + +- 底层实现:`app/service/systems/inbox/group.js` quickList(双维度可选过滤:store_id=货主维度(对应 wms_inbox_group.store_id 列)/ warehouse_id=仓库维度(对应 wms_inbox_group.warehouse_id 列),两者均可选、可同时传(AND 关系)、也可都不传(返回所有仓库/货主的群),非法值分别报「store_id 无效」「warehouse_id 无效」;keyword 同时模糊匹配 group_name/group_id、groupType 筛选 store/warehouse/express、limit 默认20上限100,无分页,按 created_at 倒序,软删自动排除)、members(groupIds 必填(非空数组,每个元素为正整数),先按内部主键ID数组+仓库批量校验群存在,再聚合多群外部群ID(去重、剔空),在 wms_inbox_message 按外部群ID集合聚合去重取每个 user_id 最新一条 user_name(多群共享同一 500 条聚合池,user_id 为 NULL/空串的消息被排除),keyword 对聚合结果小写包含过滤 user_name/user_id 后截断;外部群ID集合为空返回空列表) +- 仓库口径(2026-08-30 变更):quickList 透传前端入参 `store_id`(货主维度)/`warehouse_id`(仓库维度),不再从登录上下文注入任何仓库值;members 的 warehouseId 仍从 `ctx.user.store_id` 服务端注入,不信任前端传值 +- 多群聚合(2026-08-30 破坏性入参变更):inbox.group.members 入参由单个 `groupId` 改为 `groupIds`(数组,必填,非空,每个元素为正整数),一次查询多个群的成员并跨群按 user_id 去重;多群共享同一 500 条消息聚合池(更早消息中的成员不会出现在结果中);移除 `groupId` 入参,调用方需同步升级 +- 权限:迁移 `database/migrations/20260829180000-add-inbox-group-select-permissions.js`(固定权限 ID 566/567、type=api、INSERT IGNORE 幂等);inbox systemMethods 未声明 systemInit 免权限,两接口走标准 API 权限校验 +- 接口文档:`methods/system.json` 分组「站内信」(module=inbox),变更记录见 `methods/changes/system.json` 版本 `2026.08.30-inbox-group-members-groupids-array`、`2026.08.30-inbox-group-quicklist-dual-dim-filter`(修正/取代 `2026.08.30-inbox-group-quicklist-store-id`)、`2026.08.29-inbox-group-quick-list-members` +- 索引迁移(待发布时执行):`database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js` 为 wms_inbox_group.store_id 新增索引 idx_store_id(幂等 up/down,尚未执行) + +## 5.3 workbench(工作台绑定码 / 登录码 / token)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| index.getWorkbenchBindCode | app/service/systemMethods/index.js → app/service/systems/workbench.js | getWorkbenchBindCode / getWorkbenchBindCode | 免登录 | 免权限(systemInit 声明) | +| workbench.bind | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | bind / bindWorkbench | 需登录 | 需权限(未声明免权限) | +| workbench.getWorkbenchInfo | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | getWorkbenchInfo / getWorkbenchInfoByToken | 免登录 | 免权限(systemInit 声明) | +| index.LoginWorkbenchByCode | app/service/systemMethods/index.js → app/service/systems/workbench.js | LoginWorkbenchByCode / loginWorkbenchByCode | 免登录 | 免权限(systemInit 声明) | +| workbench.resetLoginCode | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | resetLoginCode / resetLoginCode | 需登录 | 需权限(未声明免权限) | +| workbench.removeMember | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | removeMember / removeWorkbenchMember | 免登录 | 免权限(systemInit 声明) | +| workbench.bindMember | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | bindMember / bindWorkbenchMember | 免登录 | 免权限(systemInit 声明) | +| workbench.packOrder | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | packOrder / packOrderByToken | 免登录 | 免权限(systemInit 声明) | +| workbench.finishPack | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | finishPack / finishPackByToken | 免登录 | 免权限(systemInit 声明) | +| workbench.sendWeight | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | sendWeight / sendWeightByToken | 免登录 | 免权限(systemInit 声明) | +| workbench.queryOrder | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | queryOrder / queryOrderByToken | 免登录 | 免权限(systemInit 声明) | + +- 绑定流程:设备调 `index.getWorkbenchBindCode` 拿 client_code + 绑定码(缓存 `workbench:bind:client:{clientCode}` / `workbench:bind:code:{code}`,TTL 120s)→ 管理员调 `workbench.bind`(code + 工作台ID)写入随机 64 位 token 并删除旧 `workbench:token:{旧token}` 缓存 → 设备侧长轮询(60s 超时,每秒轮询)拿到 token;超时/缓存失效时重新生成绑定码后才返回 +- token 登录:`index.LoginWorkbenchByCode` 以 `wms_workbench.login_code` 换取 token(无匹配返回 code=403 业务失败;工作台无 token 时自动生成持久化);`workbench.getWorkbenchInfo` 以 token 获取工作台信息(缓存优先、查库兜底、无信息返回 code=403 业务失败) +- 字段:`wms_workbench` 新增 `login_code`(前缀 wblc + 随机段共 64 位,全局唯一索引 uk_login_code)、`token`(随机 64 位,索引 idx_token);`workbench.create` 自动生成 login_code;`workbench.update` 不受理 login_code/token 传入;`workbench.list` 返回 login_code、不返回 token +- 成员副表:`wms_workbench_member`(工作台成员/用户登录,user_id 可空兼容非系统账号用户、user_name 名称快照、软删除);`workbench.bindMember` 免登录免鉴权(入参 userId 可空 + userName 姓名必填 + 工作台 token)新增成员行;`workbench.removeMember` 免登录免鉴权(入参行 ids + 工作台 token)按 token 解析工作台后仅软删除归属该工作台的成员行,移除后该工作台已无任何成员时自动结束其所有未结束打包任务(wms_pack_task status<2 置 2 并写 end_time,同步回写订单打包状态与补确认打印状态、写完成操作日志、复位摄像头 OSD、失效 token 缓存,与 finishPack 语义一致,响应附 auto_finished_pack{finished,task_ids},2026-09-21 补充) +- 401/403 口径:/system 网关不支持方法内设置 HTTP 状态码,按现有惯例返回 `flag=failure、code=XXX` 业务失败(与 stock/warehouse.js 同款);公共 token 校验方法 `resolveWorkbenchContext(token)`(app/service/systems/workbench.js):无 token 统一返回 code=401(消息「工作台 token 不能为空」,2026-09-06 由 400 调整)、token 无效/工作台不存在(含软删除)返回 403(保持原口径),解析成功后写入 ctx.workbenchToken/ctx.workbenchId/ctx.workbenchWarehouseId 供后续方法使用(仓库限定,禁止跨仓库);`workbench.getWorkbenchInfo`/`workbench.bindMember`/`workbench.removeMember` 均统一走该校验(无 token 返回 401,bindMember/removeMember token 优先校验) +- 打包/称重三接口(2026-09-06 新增):`workbench.packOrder`(打包上报,推荐 key 模式:前端先扫码 `workbench.queryOrder` 拿 key(20 分钟有效),打包只传 token + key(除 token、key 外不再接收任何订单相关信息,body 其它字段一律忽略,防篡改;不传 key 时旧参数模式过渡兼容,后续版本移除),参数由后端从 Redis 缓存 workbench:packctx:{key} 拉取(含订单号/波次号/运单号),跨仓/跨台消费他人 key 返回 403、缺 key 或过期返回 400;响应 task_id/order_id/delivery_order_code/wave_no/isSandan/pack_mode/status,团购附 batch)、`workbench.finishPack`(打包完成,入参 token,响应 workbench_id/finished/task_id/order_id/end_time,无未结束任务 finished=false)、`workbench.sendWeight`(称重上报,入参 token/barcode/weight(单位克),散单响应 barcode/waybill_code/order_id/weighing_weight/items_weight/mode=single,团购波次响应另附 wave_id/wave_no/total_weight/order_count/mode=wave)均免登录/免权限/免鉴权,靠工作台 token 自校验;仓库与工作台均由服务端从 token 解析注入,body 传入 warehouse_id/workbench_id 一律忽略(禁止前端传值);三接口保留系统日志(systemInit 未声明免日志) +- 打包运单维度(2026-09-21 修复一单多号):`workbench.packOrder` 传运单号时按「订单+运单号」维度写入 wms_pack_task.waybill_code 并散单去重(同时清理同订单历史 waybill_code 为空的旧流水),主单号/子单号流水互不覆盖,未传保持订单维度(兼容旧设备端);团购为波次维度不使用运单号;打包人一律由服务端取该工作台绑定成员回填(wms_workbench_member,users 入参已移除、旧设备端传 users 被忽略,2026-09-21);business 旧链路(workbench.business 的 packOrder 分支)支持传入 users 上报打包人(未上报回填成员,2026-09-21 恢复) +- 条码查单接口(2026-09-06 新增):`workbench.queryOrder`(条码查订单,入参 token/barcode,响应 barcode/waybill_code/isSandan/store_remark/express/order/items/source_table,散单 order 附 intercept_flag/pack_flag 0/1 标志、团购附 batch 波次总量信息;items 逐项合并 stock 详情含 need_recheck 是否需要复核(Y=需要 N=不需要(免验),2026-09-19 补充);pack_flag 按运单维度判定(该运单号已有打包流水 wms_pack_task.waybill_code 命中或历史订单级流水 waybill_code 为空兜底时为 1,否则 0,主单号/子单号互不影响,流水查询异常降级订单级 pack_status 判定,2026-09-21 调整);查询成功时响应另附 key(打包上下文 key,wpck 前缀 + 随机段,Redis 缓存 workbench:packctx:{key} TTL 20 分钟,内容含订单号/波次号/运单号/归属仓库与工作台,供 workbench.packOrder 消费防篡改,2026-09-21 新增))免登录/免权限/免鉴权,靠工作台 token 自校验;仓库与工作台均由服务端从 token 解析注入,body 传入 warehouse_id/workbench_id 一律忽略(禁止前端传值);只读查询不涉及缓存失效;保留系统日志(systemInit 未声明免日志) +- 接口文档:`methods/system.json` 分组「工作台模块」(module=workbench)与「基础模块」(module=index),变更记录见 `methods/changes/system.json` 版本 `2026.09.03-workbench-login-code-token`、`2026.09.03-workbench-member-remove`、`2026.09.03-workbench-member-bind`、`2026.09.06-workbench-getWorkbenchInfo-members`、`2026.09.06-workbench-getWorkbenchInfo-current-packing`、`2026.09.06-workbench-getWorkbenchInfo-wave-items-total`、`2026.09.06-workbench-pack-order-finish-pack-send-weight`、`2026.09.06-workbench-queryOrder`、`2026.09.19-workbench-getWorkbenchInfo-order-items`、`2026.09.19-workbench-order-items-need-recheck`、`2026.09.19-workbench-getWorkbenchInfo-wave-items-summary`、`2026.09.21-workbench.packOrder-waybill-dimension`、`2026.09.21-workbench.removeMember-auto-finish-pack`、`2026.09.21-workbench.packOrder-remove-users-param`、`2026.09.21-workbench.packOrder-key-mode`、`2026.09.21-workbench.packOrder-key-only`、`2026.09.21-workbench.packOrder-legacy-compat`、`2026.09.21-workbench.packOrder-key-forward-fix`、`2026.09.21-workbench.getWorkbenchInfo-order-fields`、`2026.09.21-workbench.packOrder-business-users-restore` +- 当前打包信息:`workbench.getWorkbenchInfo` 响应 data 另含 `current_wave`(当前正在打包的团购波次,来自 wms_pack_task 最新一条 pack_mode=2 未结束任务,无则为空对象;含 order_count 波次订单数与 items_total 波次商品总件数,均按 current+dispatch 分表实时统计、15s 短缓存兜底)与 `current_orders`(未结束打包任务对应订单数组,逐单按 current→dispatch 分表补发货单号/order_type/store_id/items_count/items_total,另附任务表 item_quantity/sku_count/waybill_code,散单任务(pack_mode=1)附 items 商品明细数组(复用 _fetchOrderItemsDetail 公共方法,与 workbench.queryOrder 的 items 同源,含条码/图片/包装要求/need_recheck 是否需要复核),另补货主备注 store_remark 与运单信息 express(物流公司/称重重量/包材名称,与 queryOrder 口径一致,2026-09-21 补充),团购任务(pack_mode=2)items 为波次商品 SKU 聚合汇总(_fetchWaveItemsSummary,波次内全部未拦截订单按 SKU 聚合计划数量并合并 stock 详情,15s 短缓存兜底,元素另附 is_wave_summary=true),无则为空数组);打包信息随 `workbench:token:{token}` 缓存(TTL 300s)一并缓存,packOrder/finishPack 状态变更后主动失效缓存,查询异常降级为空对象/空数组(单笔商品明细异常仅 items 降级为空数组) +- 迁移:`database/migrations/20260903100000-add-login-code-token-to-wms-workbench.js`(幂等 up/down,已在开发库执行;生产库待发布时按标准流程执行) + +## 5.4 index.queryUserByToken(ye4s token 查询用户)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| index.queryUserByToken | app/service/systemMethods/index.js(method 内直接查询 ye4s 库 ye4s_user 表) | queryUserByToken | 免登录 | 免鉴权(systemInit 声明) | + +- 语义:入参 `token`(ye4s 登录临时码,对应 ye4s 库 ye4s_user 表 tmp_code 字段)查询用户;命中返回 flag=success、code=200 与 real_name(用户真实姓名)、wms_account_id(WMS 账号 ID,未绑定为 null);未命中返回 code=404「用户不存在」;数据库异常返回 code=500;token 为空返回 code=400「token 不能为空」 +- 接口文档:`methods/system.json` 分组「基础模块」(module=index),变更记录见 `methods/changes/system.json` 版本 `2026.09.06-index.queryUserByToken` + +## 5.5 openapi.stockout(开放 API 出库单)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| stockout.create | app/service/openapiMethods/stockout.js → app/service/systems/stockout_order.js | create / create | 免登录 | 免方法级权限(/openapi 入口按 app_key 合约 + 签名校验,合约须绑定货主) | +| stockout.query | app/service/openapiMethods/stockout.js → app/service/systems/stockout_order.js | query / query | 免登录 | 同上 | + +- 语义:开放 API 出库单创建/查询,与奇门 `stockout.create` / `stockout.query` 共用同一份领域实现(`app/service/systems/stockout_order.js`),差异只在来源标识:开放 API 落库 `wms_order_stockout.source_type=API`(回传走 OpenAPI 回调 `event=stockout.confirm`),奇门落库 `source_type=QM`(回传调用 `taobao.qimen.stockout.confirm`) +- 入参:开放 API 为扁平结构 `body.deliveryOrder` / `body.orderLines.orderLine` / `body.deliveryOrderCode`;奇门为 `request.deliveryOrder` / `request.orderLines.orderLine`。字段口径详见 `methods/openapi.json` 分组「出库单模块」(module=stockout) +- 库存:创建时事务内按 `planQty` 锁定库存(锁标记 `QM_STOCKOUT`,与 `storage.stockout.cancel/confirm/toOrder` 释放口径一致);非订单出库单能力另见 `storage.stockout.*` +- 接口文档:`methods/openapi.json` 分组「出库单模块」(module=stockout),变更记录见 `methods/changes/openapi.json` 版本 `2026.09.12-openapi-stockout-create-query` + +## 5.6 OpenAPI 出站回调 method 规范(2026-09-12 / 2026-09-13 破坏性变更) + +> 破坏性协议变更(2026-09-12):OpenAPI 出站回调的 `method`(query)由 snake_case 事件名统一改为 `模块.动作`(与奇门 method 去掉 `taobao.qimen.` 前缀后对齐)。旧事件名已全部废弃,无新旧兼容、无双发,接收方必须同步改造。 +> +> 破坏性协议变更(2026-09-13):报文体由 `{ event, data, metadata }` 改为奇门同层级的 `{ request: {...} }`,发送端不再发送数据/元数据,`event` 仅出现在 query 的 `method`;`deliveryorder.confirm` 由一次批量汇总通知改为逐单发送(每单在同步时发送,**回调成功才扣减库存并置 `sync_status='fin'`**,失败置 `error` + 待处理异常、不扣减库存;成功 N 单 = N 次回调)。接收方必须按新报文结构改造。 + +### 5.6.1 method 命名规范 +- 格式:`模块.动作`(如 `entryorder.confirm`、`stockout.confirm`) +- 与 `/openapi` 入站入口校验一致:`app/service/openapiEntry.js#validateOpenapiParams` 要求 `method` 必须包含 `.`,否则 400「参数缺失或错误: method/v/timestamp」 +- 与奇门的对应关系(注册表已声明的):`entryorder.confirm` ↔ `taobao.qimen.entryorder.confirm`、`stockout.confirm` ↔ `taobao.qimen.stockout.confirm`(见 `app/service/openapi/callbackRegistry.js` 描述) + +### 5.6.2 method 映射表(旧事件名 → 新 method → 触发场景 → 实现文件) + +| 旧(事件名,已废弃) | 新(method) | 触发场景 | 实现文件 | +|---|---|---|---| +| `entry_order_direct_inbound_completed` | `entryorder.confirm` | 直入入库(API 来源,`source_type=API`)完成后回传 | `app/service/systems/inbound_direct_log.js`(`qimenEntrySync` → `_sendOpenApiCallback`,约 1470 行) | +| `entry_order_receiving_matched` | `entryorder.match` | 入库单匹配收货单完成后回传(API 来源) | `app/service/systems/receiving_entry_match.js`(`_sendCallback` → `_sendOpenApiCallback`,约 1864 行) | +| `order_completed` | `deliveryorder.confirm` | API 渠道订单同步时逐单发送(同一个 `finalizeLocalChannelOrdersInternal` 分发循环,`DISPATCH_BATCH_SIZE=20` 批内并行):每单先组装报文(缺 ownerCode → 失败)→ 解析 appKey → `sendByAppKey` 发送(最多 4 次尝试)→ **回调成功才扣减库存并置 `sync_status='fin'`**;失败统一置 `sync_status='error'` + 待处理异常、不扣减库存、可重新派发(成功 N 单 = N 次回调)。发送用 appKey 优先取调用上下文 `context.appKey`,缺失时按订单货主(`store_id`+`warehouse_id`)合约反查 `wms_store_warehouse(auth_status=2)` → `wms_api_app(is_enabled=1 且 callback_url 非空)` 的 `self_app_key`(同批次按货主缓存);解析不到 appKey(缺 store_id / 无授权关系 / 无可用 ApiApp)**不再静默跳过**,按失败处理(此前 routeContext 缺 appKey 导致该回调从未发出,2026-09-13 已修复) | `app/service/systems/order_async.js`(`finalizeLocalChannelOrdersInternal` → `processApiOrderInternal`) | +| `stockout_completed` | `stockout.confirm` | 出库单确认回传(API 来源,`source_type=API`) | `app/service/systems/order_async.js`(`notifyStockoutExternalInternal` → `buildStockoutConfirmDataInternal`) | +| `order_cancelled` | `deliveryorder.cancel` | 订单取消成功后触发(fire-and-forget;出站事件名与入站方法 `order.cancel` 区分,避免 `callback_url` 误指向 `/openapi` 时被路由到取消单据接口;**无奇门对应接口**,按 `deliveryOrder` 节点约定自定义,`status` 固定 `CANCELED`) | `app/service/openapiMethods/order.js`(`cancel`,约 296 行) | + +### 5.6.3 协议要点 +- 出站请求:`POST {callbackUrl}?method={模块.动作}&v=1.0×tamp={timestamp}&app_key={selfAppKey}&sign={md5}` + - `timestamp` 为**秒级(10 位字符串)规范值**:`String(Math.floor(Date.now()/1000))`,发送端(`callback.js#sendWithRetry`)与回调调试页(`openapiCallback.js#nowTimestamp`)已统一;与 `/openapi` 入站时效校验一致(`openapiEntry.js`,秒级 ±600 秒窗口)。此前「毫秒/秒口径不一致、待统一」的已知问题已修复 +- 请求头:`Content-Type: application/json` +- 请求体:`{ "request": {…} }`(奇门同层级);`event` 不出现在报文体内,仅拼入 query 的 `method`;发送端固定包装 `body = { request: request || {} }`(`app/service/openapi/callback.js#sendWithRetry`) +- 5 个事件的 `request` 顶层结构速查表: + +| method | `request` 顶层结构 | 组装实现 | +|---|---|---| +| `entryorder.confirm` | `{ entryOrder: {…}, orderLines: […] }` | `app/service/systems/inbound_direct_log.js#buildEntryOrderConfirmRequest`(QM/API 共用) | +| `entryorder.match` | `{ entryOrder: {…}, orderLines: […] }`(`outBizCode` 前缀 `RECEIVING_MATCH_`,`remark` 为「匹配收货单{收货单号}自动回传」) | `app/service/systems/receiving_entry_match.js#buildEntryOrderConfirmRequest`(QM/API 共用) | +| `deliveryorder.confirm` | `{ deliveryOrder: {…}, packages: {package:[…]}, orderLines: […] }`(逐单发送) | `app/service/systems/order_async.js#buildQimenDeliveryOrderConfirmDataInternal` | +| `stockout.confirm` | `{ deliveryOrder: {…}, packages: {package:[…]}, orderLines: […] }` | `app/service/systems/order_async.js#buildStockoutConfirmDataInternal` | +| `deliveryorder.cancel` | `{ deliveryOrder: { deliveryOrderCode, orderType, status: 'CANCELED' } }`(无奇门对应接口,自定义约定) | `app/service/openapiMethods/order.js#cancel` | + +各层字段口径详见 `methods/openapi_callback.json` / `docs/openapi-callback-events.md`(与 `callbackRegistry.js` 的 `request` 模板一致) +- 签名(`app/lib/api_sign.js#signRequest`):`sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body)))`;`canonicalQuery` 为除 `sign`/`signature` 外 query 按 key 字母序 `key=value&…` 拼接(签名用未 URL 编码原值,实际 URL 中 `method`/`app_key` 做 `encodeURIComponent`);`bodySign` 基于 `{ request }` 完整报文 +- 重试(`app/service/openapi/callback.js#sendWithRetry`):非 2xx 或网络错误最多重试 3 次(`MAX_RETRY=3`),间隔 2s → 5s → 15s,单次超时 30s;每次尝试写 `[OpenapiCallback]` 日志(`logCallback`);`deliveryorder.confirm` 单订单 4 次尝试后仍失败 ⇒ 该订单同步判定失败(`sync_status='error'` + 待处理异常,不扣减库存,可重新派发) +- 事件注册表:`app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS`(5 条,每条含 `name`/`label`/`description`/`request`,`request` 为奇门同层级报文模板),回调调试页 `GET /docs/api/openapi/callback-test`(`app/controller/openapiCallback.js`)直接消费该注册表,并按注册表自动预填完整报文体 `{ request: {...} }` +- 完整协议文档:`docs/openapi-callback-events.md` + +## 5.7 camera(摄像头 OSD / 云台 PTZ)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| camera.setOsd | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/osd_client.js | setOsd | 需登录 | 免权限(systemInit 声明 setOsd) | +| camera.ptzControl | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/ptz_client.js | ptzControl / control | 需登录 | 免权限(systemInit 声明 ptzControl) | +| camera.ptzStop | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/ptz_client.js | ptzStop / stop | 需登录 | 免权限(systemInit 声明 ptzStop) | +| camera.ptzPresetGoto | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/ptz_client.js | ptzPresetGoto / presetGoto | 需登录 | 免权限(systemInit 声明 ptzPresetGoto) | +| camera.ptzPresetSet | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/ptz_client.js | ptzPresetSet / presetSet | 需登录 | 免权限(systemInit 声明 ptzPresetSet) | + +- 云台方向 action 枚举(8 个位置,服务端转小写校验,非法值报 400):`up` 上、`down` 下、`left` 左、`right` 右、`upleft` 左上、`upright` 右上、`downleft` 左下、`downright` 右下(常量见 `app/lib/ptz_client.js#PTZ_ACTION_LIST`,文档已写入 `methods/system.json#camera.ptzControl.params[].action.list`) +- 交互口径:按下 `camera.ptzControl`(参数 `id`/`action`,可选 `speed` 1-7 默认 4)→ 松手 `camera.ptzStop`(`action` 必须与按下时一致);预置点存点 `camera.ptzPresetSet`(`presetId` 1-256,把当前机位存为该编号,重复设置即覆盖)与跳转 `camera.ptzPresetGoto`(`presetId` 1-256)均是一次性动作,无需 stop +- 下发通道:**独立端点,与 setOSD 同风格,不需要 computerId** —— `POST {printService.url}/camera/ptzControl` / `/camera/ptzStop` / `/camera/ptzPresetGoto` / `/camera/ptzPresetSet`,请求体依次为 `{ warehouse_id, cameraId, rtspUrl, action, speed }` / `{ warehouse_id, cameraId, rtspUrl, action }` / `{ warehouse_id, cameraId, rtspUrl, presetId }` / `{ warehouse_id, cameraId, rtspUrl, presetId }`(`warehouse_id` 为字符串、`cameraId` 为数值型 `wms_camera.id`;`_send` 统一拼接) +- `rtspUrl` 由服务端组装(`rtsp://{username}:{password}@{ip}:554/stream{channel_id}`,与 `osd_client.buildRtspUrl` 同口径),前端不传 +- 失败口径:参数非法 → 400(`摄像头ID不能为空`/`云台方向不合法,仅支持:…`/`云台转速需为 1-7 的整数`/`预置点编号…`);摄像头不存在或跨仓库 → 404;打印服务 HTTP 非 2xx 或回包 `status=fail`/`success=false` → 500 `打印服务请求失败: …` +- 接口文档:`methods/system.json` 分组「摄像头模块」(module=camera),变更记录见 `methods/changes/system.json` 版本 `2026.09.15-camera-ptz-control`(首次登记)、`2026.09.15-camera-ptz-wms-endpoint`(改独立端点)、`2026.09.15-camera-ptz-preset-set`(新增存点)、`2026.09.15-camera-ptz-camera-id`(请求体带 cameraId) + +## 5.8 afterSale(售后类型/子类型配置 CRUD)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| afterSale.typeList | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | typeList / getTypeList | 需登录 | 免权限、免仓库有效期校验、免日志 | +| afterSale.typeCreate | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | typeCreate / createType | 需登录 | 免权限、免仓库有效期校验、记日志 | +| afterSale.typeUpdate | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | typeUpdate / updateType | 需登录 | 免权限、免仓库有效期校验、记日志 | +| afterSale.typeDelete | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | typeDelete / deleteType | 需登录 | 免权限、免仓库有效期校验、记日志 | +| afterSale.subTypeList | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | subTypeList / getSubTypeList | 需登录 | 免权限、免仓库有效期校验、免日志 | +| afterSale.subTypeCreate | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | subTypeCreate / createSubType | 需登录 | 免权限、免仓库有效期校验、记日志 | +| afterSale.subTypeUpdate | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | subTypeUpdate / updateSubType | 需登录 | 免权限、免仓库有效期校验、记日志 | +| afterSale.subTypeDelete | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | subTypeDelete / deleteSubType | 需登录 | 免权限、免仓库有效期校验、记日志 | + +- 仓库维度隔离:列表返回系统级(warehouse_id=null、is_system=1,全部仓库可读)+ 当前仓库自定义(is_system=0)合并;创建仅允许仓库自定义;改/删仅命中 `id + warehouse_id=当前仓库 + is_system=0` +- 系统级保护:is_system=1 的类型/子类型不允许编辑/删除,未命中统一 404「不存在、无权操作或为系统预设类型」 +- 编码规则:type/sub_type 仅允许 `/^[a-z0-9_]+$/`(小写字母/数字/下划线);type≤20 字符、sub_type≤50、name≤50;创建时校验编码不与系统级重复、同仓库内唯一(409),MySQL 唯一索引 `uk_type_warehouse` / `uk_type_subtype_warehouse` 兜底 +- 编码不可变:update 仅允许 name/is_enabled/sort_order,不允许改 type/sub_type 编码 +- 删除策略(拒绝,不做级联):typeDelete 在该类型下存在本仓库自定义子类型时拒绝(409);subTypeDelete 在 wms_after_sale 存在该 type/sub_type 引用时拒绝(409「已被售后单使用」) +- 错误码:400(参数/编码格式错误)、404(不存在/无权/系统预设)、409(编码重复/存在子类型/被引用) +- 数据表:wms_after_sale_type / wms_after_sale_sub_type(app/model/after_sale_type.js、after_sale_sub_type.js) +- 接口文档:methods/system.json 分组「售后模块」(module=afterSale),变更记录见 methods/changes/system.json 版本 2026.09.16-after-sale-type-subtype-crud + +## 5.9 index.uploadClientErrorLog(客户端错误日志上报)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| index.uploadClientErrorLog | app/service/systemMethods/index.js → app/service/systems/client_error_log.js | uploadClientErrorLog / upload | 免登录 | 免权限、免鉴权(systemInit 声明) | + +- 语义:设备端(android/ios/web)将运行时错误日志批量上报暂存到新表 wms_client_error_log,供后台查询分析;免登录、免权限、免鉴权,保留系统日志(不在 INDEX_NO_NEED_LOG_METHODS 清单;index 模块日志口径已由通配符改为显式清单) +- 入口:POST /system?method=index.uploadClientErrorLog&v=1×tamp=<数字时间戳>,请求头需 platform/project(根 headers 已声明),无需 Authorization/token +- 入参三种形态:单条对象 / 数组 / { logs: [...] }(单次最多 50 条,超限 code=400);字段 snake_case 为主、兼容 camelCase 别名(clientType/appVersion/deviceId/osVersion/deviceModel/errorType/errorMessage/errorStack/reportUuid/clientTime);error_message 与 error_stack 至少一项有值(超长截断 5000/65535)、extra 截断 65535、字符串列宽 client_type 32 / app_version 64 / device_id 128 / os_version 64 / device_model 128 / error_type 64 / report_uuid 64 超出截断;client_time 支持毫秒/秒时间戳与日期字符串(非法存 null,仅参考) +- 幂等:report_uuid 唯一索引 uk_report_uuid;重复上报 duplicated +1、静默成功不产生重复行;客户端未传时服务端生成 srv-{uuid}(此时不保证幂等);created_at/updated_at 由 Sequelize 统一取服务器时间 +- 出参:成功 { flag:'success', code:200, message:'上报成功', success:true, total, accepted, duplicated, rejected, rejected_reasons(≤10 条,每条 { index, reason }), timestamp };失败 400/500 为 HTTP 200 + { flag:'failure', code, message, timestamp } +- 表结构:wms_client_error_log(迁移 database/migrations/20260925100000-create-wms-client-error-log.js、模型 app/model/client_error_log.js);索引 uk_report_uuid(唯一)、idx_created_at、idx_client_type_app_version、idx_device_id +- 接口文档:methods/system.json 分组「基础模块」(module=index),变更记录见 methods/changes/system.json 版本 `2026.09.25-index-upload-client-error-log` + +## 5.10 order.deliveryOrder.summary(配送订单每日汇总)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| order.deliveryOrder.summary | app/service/systemMethods/order/deliveryOrder.js → app/service/systems/deliveryOrderSummary.js | summary / queryDailySummary | 需登录 | 免权限、免鉴权(只读接口,systemInit 的 _noNeedRight/_noNeedAuth 与 list/quickSearch 同口径) | + +- 语义:以自然日(yyyy-MM-dd)为维度汇总配送订单,仓库取自登录上下文 `ctx.user.store_id`(禁止传 warehouse_id),可选 `store_id` 按货主过滤;缺省最近 7 个自然日(含今天),单次最多 90 天,区间内无数据日期补 0 +- 数据源:订单常用表 + 配送表(`OrderDeliveryFactory.getCurrentModel` / `getDispatchModel`);订单出库迁移进配送表时删除源行,两表无重叠直接相加;归档表 history、委托外仓 outsourced 不参与 +- 日期分组:`DATE(CONVERT_TZ(字段, Sequelize 时区, 服务器本地时区))`,避免数据库 UTC 存储导致自然日偏移 8 小时;区间过滤仍由 Sequelize 按连接时区转义 Date 参数 +- 指标口径(各指标按自身时间字段落入统计日):`order_count`=create_at(排除 cancel);`dispatch_count`=配送表 dispath_time;`shipped_count`/`shipped_items_total`/`shipped_amount`=delivery_time(排除 cancel);`intercepted_count`=intercept_time 且 intercept_status != none;`intercepted_at_warehouse_count`=配送表 dispath_time 且 intercept_status=intercepted_at_warehouse;`cancelled_count`=updated_at 且 status=cancel(取消操作刷新 updated_at) +- 入参:`start_date`/`end_date`(兼容 startDate/start_time、endDate/end_time)、`store_id`(兼容 storeId) +- 响应:`warehouse_id` / `store_id` / `start_date` / `end_date` / `day_count` / `list`(逐日指标,按日期升序)/ `summary`(区间合计) +- 纯函数:app/lib/delivery_order_summary.js(区间解析、日期展开、聚合合并,无 egg 依赖);测试 test/delivery_order_summary.cjs、test/app/service/systemMethods/order/deliveryOrder.summary.test.js +- 接口文档:methods/system.json 分组「订单配送模块」(module=order.deliveryOrder),变更记录见 methods/changes/system.json 版本 `2026.10.21-order-delivery-summary` + +## method结束 + +## 6. 全量 Service Method 能力清单(自动扫描) + +维护说明: +- 扫描范围:app/service/**/*.js +- 本节内容由脚本生成,新增/修改 service 后请同步刷新。 +- 刷新命令:node .\temp\tmp-gen-service-method-inventory.cjs -> node .\temp\tmp-update-ai-method-routing.cjs +- 临时清单输出:temp/tmp-service-method-inventory.md +- 扫描器注意:括号计数前会先遮蔽字符串/模板/注释/正则内容(maskLiteralsAndComments);若移除该遮蔽,字符串里的未配对花括号(如 startsWith('{'))会让其后方法被整体漏扫。 + + +自动生成时间: 2026-09-27T17:16:56.519Z + +扫描范围: app/service/**/*.js +文件数: 219 + +- app/service/api.js (1) + - callMethod +- app/service/apiMethods/print.js (5) + - getPrinterRedis, normalizeBindValue, getEmployeePermissions, getBindInfo, bindByTempCode +- app/service/apiMethods/test.js (3) + - playbackRequest, fibonacci, fibonacciRecursive +- app/service/apiMethods/user.js (2) + - getUserByTempCode, bindAccountByTempCode +- app/service/dispatcher.js (3) + - buildMap, getMethodMap, invoke +- app/service/im.js (3) + - ping, ssoCodeToId, getStoreEmployees +- app/service/inbox/ai.js (3) + - callDeepSeek, getConversationHistory, processWithAI +- app/service/inbox/functions.js (4) + - registerBuiltinFunctions, notifyStoreReceiving, register, callFunction +- app/service/inbox/groups.js (4) + - resolveActiveGroups, isFunctionAvailable, getFunctionList, buildFunctionListText +- app/service/inbox/index.js (5) + - list, detail, thread, reply, stats +- app/service/inbox/message.js (10) + - list, _normalizeIds, _normalizeStrings, detail, thread, stats, retry, _repush, retryFailed, retryFailedByWarehouse +- app/service/inbox/processor.js (17) + - _loadGroupInfo, isStaleMessage, process, handleApiMessage, tryBindGroup, writeOutboundReply, isWarehouseGroup, loadBlockedUserIds, isBlocked, invalidateBlockCache, getApiAppCallbackConfig, getApiAppCallbackUrl, pushSystemNotification, extractWarehouseId, extractStoreId, getWarehouseIdFromContext, getStoreIdFromContext +- app/service/inbox/receiver.js (1) + - receive +- app/service/inbox/rules.js (3) + - handle, buildReply, formatStock +- app/service/inbox/tools.js (2) + - getRecordingComputerId, buildVideoUrl +- app/service/inbox/v2/config.js (3) + - load, invalidate, build +- app/service/inbox/v2/functionSync.js (1) + - sync +- app/service/inbox/v2/rules.js (8) + - handle, _matchKeywords, _groupAllowed, _extractNumbers, _buildParams, _noNumberHint, _buildOutcome, _renderReply +- app/service/main.js (18) + - success, fail, normalizeDate, setInfo, getInfo, isPlainObject, normalizeWhereCondition, normalizeWhereParams, extractWhereValues, prepareWhereContext, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, extractApiPermissionState, collectApiPermissionValue, setUserContext, systemInit +- app/service/openapi/callback.js (5) + - signCallback, sendWithRetry, sendByAppKey, _formatResponsePayload, logCallback +- app/service/openapi/callbackRegistry.js (0) + - +- app/service/openapiEntry.js (8) + - resolveOpenapiMethod, getOpenapiMethodService, resolveOpenapiContract, dispatchOpenapiMethod, validateOpenapiParams, parseJsonBody, normalizeSignFields, processRequest +- app/service/openapiMethods/callback.js (2) + - resolveAppInfo, test +- app/service/openapiMethods/deliveryorder.js (2) + - query, create +- app/service/openapiMethods/entryorder.js (2) + - create, query +- app/service/openapiMethods/index.js (2) + - ping, health +- app/service/openapiMethods/inventory.js (1) + - query +- app/service/openapiMethods/order.js (2) + - cancel, releaseStockLockForCancel +- app/service/openapiMethods/ping.js (1) + - echo +- app/service/openapiMethods/singleitem.js (2) + - synchronize, query +- app/service/openapiMethods/stockout.js (2) + - create, query +- app/service/pda.js (3) + - callMethod, validateParams, saveLog +- app/service/qimen.js (12) + - validateApi, getErpName, parseXmlToArray, cleanXmlString, callMethod, formatResponse, xmlResponse, buildXmlNode, escapeXml, saveQimenLog, saveQimenLogResult, saveQimenLogBody +- app/service/qimenMethods/deliveryorder.js (3) + - query, create, batchcreate +- app/service/qimenMethods/entryorder.js (2) + - create, query +- app/service/qimenMethods/inventory.js (1) + - query +- app/service/qimenMethods/order.js (5) + - getInterceptExpressInfo, sendCancelInterceptNotice, cancel, releaseStorageLockForCancel, pending +- app/service/qimenMethods/returnorder.js (2) + - create, query +- app/service/qimenMethods/singleitem.js (2) + - synchronize, query +- app/service/qimenMethods/stockout.js (2) + - create, query +- app/service/qimenMethods/taobao/qimen/service.js (1) + - heartbeat +- app/service/system.js (4) + - callMethod, validateParams, validateRequestContext, saveLog +- app/service/systemMethods/afterSale.js (30) + - workList, _resolveAfterSaleBlockRoleGroups, workCount, auditList, detail, create, _resolveRedundantFields, transfer, handleWorkOrder, batchSetPendingFeedback, batchClose, registerClaim, export, exportTaskProgress, generateAfterSaleNo, _getCurrentDatePart, _buildOperatorSnapshot, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, typeList, typeCreate, typeUpdate, typeDelete, subTypeList, subTypeCreate, subTypeUpdate, subTypeDelete +- app/service/systemMethods/apiApp.js (6) + - list, detail, create, update, delete, regenerateSecret +- app/service/systemMethods/camera.js (10) + - list, detail, create, update, setOsd, ptzControl, ptzStop, ptzPresetGoto, ptzPresetSet, delete +- app/service/systemMethods/cameraServer.js (5) + - list, detail, create, update, delete +- app/service/systemMethods/comboGoods.js (5) + - list, create, update, delete, search +- app/service/systemMethods/config.js (1) + - list +- app/service/systemMethods/dashboard.js (28) + - storeStats, storeSideStoreStats, queryWarehouseStats, mergeStoreStats, emptyStoreStats, warehouseStats, hot_order_rank, storeSideHotOrderRank, queryWarehouseHotOrderRank, queryHotOrderRankWindowRows, buildHotOrderRankMap, buildHotOrderRankKeyFilter, mergeHotOrderRank, loadHotOrderRankStockInfo, resolveHotOrderRankProduct, maskHotOrderRankName, formatHotOrderRank, emptyHotOrderRank, express_ratio, storeSideExpressRatio, queryWarehouseExpressRatio, mergeChartData, formatChartData, emptyChartData, platform_distribution, storeSidePlatformDistribution, queryWarehousePlatformDistribution, order_trend +- app/service/systemMethods/frontConfig.js (9) + - getFrontConfigService, getByDomain, getInfo, getCert, saveInfo, saveCert, setDomain, getDomain, checkDomain +- app/service/systemMethods/inbox.js (13) + - group, message, v2, bindCode, groupList, groupQuickList, groupMembers, groupDisable, groupUpdate, groupReset, groupMessages, retry, reply +- app/service/systemMethods/index.js (61) + - fastWhereTree, loadStores, loadWarehouses, loadExpressInterfaces, getCOSUploadConfig, getImages, uploadSuccessNotify, recognizeLicensePlate, ReferenceFile, getMessageDetail, test, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, searchSpaces, listInterfaceTypes, getLocationTypeList, getQimenAppList, getExpressList, getExpressProductTypeList, getPlatformList, getPrintPlatformList, ensureShopPrintPlatformExists, buildShopPrintPlatformInclude, getShopList, requestPddWaybillSearch, requestPddStdTemplates, requestTbWaybillSearch, requestTbCainiaoStdTemplates, requestPolyStdTemplates, getShopExpressList, getCainiaoStfTemplates, normalizeTemplatePlatformCode, normalizeTemplateExpressCode, getExpressPlatformFieldName, getTemplateAllowedExpressCodeSet, filterPrintPlatformTemplateResponseData, getPrintPlatformTemplateCacheKey, requestPrintPlatformTemplateList, resolvePddTemplateWpCodeCandidates, requestPddTemplateSourceList, getPrintPlatformTemplateList, isPlatformOauthReservationDuplicateError, getPlatformOauthReservationCodePrefix, hasPlatformOauthReservationCodePrefix, normalizePlatformOauthReservationCode, generatePlatformOauthReservationCode, createPlatformOauthReservation, getPlatformOauthLink, listenPlatformOauthBind, loginToIm, polyapiAuthorizeUrl, toOrder, getWorkbenchBindCode, LoginWorkbenchByCode, queryUserByToken, parseWechatBadgeCode, queryUserByWechatBadge, uploadClientErrorLog +- app/service/systemMethods/order/archiveOrder.js (2) + - list, detail +- app/service/systemMethods/order/base.js (56) + - maskListSensitiveValue, isInterceptedOrderStatus, isLockedOrderStatus, assertOrderNotIntercepted, getWarehouseId, getOrderLogOperator, getOrderLogWarehouseId, normalizePagination, normalizeWhereInput, normalizeOrderIds, isMergeableWhereCondition, mergeWhereObjects, getModuleConfig, getDefaultWhere, getBadgeCountCacheKey, formatBadgeCountValue, formatWeightTypeLabel, formatCreateChannelLabel, normalizeWaveScanResult, normalizeWaveStrategyVersion, normalizeLockStatusFlag, normalizeOrderListItem, getBadgeCountByModule, getOrderModel, resolveOrderTableType, getOrderModelByTableType, getOrderItemsModelByTableType, getOrderExpressesByOrderId, normalizeOrderListRow, attachOrderExpressNumbers, attachOrderWaveIndex, extractOrderListExpressVirtualFilter, extractBuyerMessageHasVirtualFilter, extractStockQueryVirtualFilter, extractWaveIndexVirtualFilter, extractWaveScopeVirtualFilter, findOrderIdsByWaveIndexCondition, buildWaveScopeFilterCondition, buildBuyerMessageHasCondition, appendConditionToWhere, normalizeExpressFilterValues, findOrderIdsByExpressNumbers, findOrderIdsByStockQuery, appendOrderIdsFilterToWhere, buildListOrder, buildWhere, listByModule, detail, attachStockDetailsToOrderItems, getOrderOperationLogs, resolveReviewStep, normalizeReviewOrderIds, buildOrderWhere, buildReviewOrderWhere, updateReviewOrder, updateOrderInspectionState +- app/service/systemMethods/order/deliveryExpectionOrder.js (2) + - list, detail +- app/service/systemMethods/order/deliveryOrder.js (5) + - list, detail, quickSearch, buildWaybillItem, fetchOrderMapByIds +- app/service/systemMethods/order/entrustOrder.js (2) + - list, detail +- app/service/systemMethods/order/expectionOrder.js (2) + - list, resolveException +- app/service/systemMethods/order/index.js (16) + - export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, list, manualOutboundOrder, badgeCount, queryOrderLogs, queryOrderLogList, updateExpressWeighingWeight, bindExpressPackageMaterial, bindExpressPackageMaterialByWaybill, pullReviewDataByWaybill +- app/service/systemMethods/order/outboundOrder.js (2) + - list, manualOutboundOrder +- app/service/systemMethods/order/packing.js (11) + - list, get, setEndTime, forceRecord, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/order/pendingOrder.js (89) + - list, detail, reverseReviewOrder, assertOrdersWithoutWaybill, syncWavesAfterReverseReview, allocateStorage, allocateStorageProgress, normalizeAllocateStorageTaskProgress, normalizeAllocateStorageTaskCount, normalizeAllocateStorageTaskCounts, normalizeAllocateStorageRequestId, getAllocateStorageTaskCacheKey, setAllocateStorageTaskProgress, getAllocateStorageTaskProgress, getAllocateExpressTaskCacheKey, normalizeAllocateExpressTaskId, setAllocateExpressTaskProgress, getAllocateExpressTaskProgress, getSyncOrderIdsTaskCacheKey, normalizeSyncOrderIdsRequestId, setSyncOrderIdsTaskProgress, getSyncOrderIdsTaskProgress, cancelAllocateStorage, syncOrderIds, syncOrderIdsProgress, allocateExpressCode, allocateExpressCodeTaskProgress, markPendingOutboundOrder, cancelOrder, normalizePendingOutboundOrderIds, normalizePendingCancelOrderIds, isCancelablePendingOrder, updateOrderPlatform, updateOrderExpress, updateAddress, updateRemark, cloneOrder, parseAddress, parseAddressLocal, createOrder, downloadCreateTemplate, normalizeIdsInput, batchIntercept, batchInterceptTaskProgress, generateBatchInterceptTaskId, normalizeBatchInterceptTaskId, normalizeBatchInterceptOrderIds, getBatchInterceptTaskCacheKey, setBatchInterceptTaskProgress, getBatchInterceptTaskProgress, runBatchInterceptTask, batchLock, batchLockTaskProgress, generateBatchLockTaskId, normalizeBatchLockTaskId, normalizeBatchLockOrderIds, getBatchLockTaskCacheKey, setBatchLockTaskProgress, getBatchLockTaskProgress, runBatchLockTask, batchUnlock, batchUnlockTaskProgress, generateBatchUnlockTaskId, normalizeBatchUnlockTaskId, normalizeBatchUnlockOrderIds, getBatchUnlockTaskCacheKey, setBatchUnlockTaskProgress, getBatchUnlockTaskProgress, runBatchUnlockTask, batchUnintercept, batchUninterceptTaskProgress, generateBatchUninterceptTaskId, normalizeBatchUninterceptTaskId, normalizeBatchUninterceptOrderIds, getBatchUninterceptTaskCacheKey, setBatchUninterceptTaskProgress, getBatchUninterceptTaskProgress, runBatchUninterceptTask, manualWaybill, releaseCreationLockForCancel, allocateSubOrderNumber, writeAllocateSubOrderErrorFlag, writeAllocateSubOrderLog, allocateSubOrderNumberProgress, getAllocateSubOrderTaskCacheKey, setAllocateSubOrderTaskProgress, getAllocateSubOrderTaskProgress, buildSubOrderDetails, batchMarkPrinted +- app/service/systemMethods/order/print.js (4) + - getWavePlatformPrintData, getOrderPrintData, getPrintDataByWaybillCodes, unlockWavePlatformPrintDataByGroup +- app/service/systemMethods/order/recheckOrder.js (59) + - scanOrder, markWaveRecheckStart, scanTask, buildSingleWaveScanView, buildSingleWaveView, buildGroupWaveList, getPickModeByWaveId, getTaskIdByWaveId, getWaveOrdersBasic, batchQueryPackageMaterialRecommendation, enrichOrdersWithStock, getPickerInfoByWaveId, getPickerInfoByTaskId, getWaveStrategyInfo, scanWaybill, confirmRecheck, confirmRecheckByWaveId, _writeRecheckActionLog, updateTaskOrderReviewAndTryUnbindCart, _resolveTaskIdByWaveFallback, _checkTaskOrdersAllReviewed, updateTaskOrdersReviewBatch, unbindCartForTask, resolveOrderId, resolveScanKeyword, pickOrderMatchByKeyword, pickOrderIdByWaybill, pickOrderIdByCartCode, pickWaveMatchContextByWaveNo, pickCartMatchContextByCartCode, getTableColumnSet, resolvePickModeName, buildWaveMatchView, buildCartMatchView, flattenCartMatchOrders, enrichTaskOrderRows, groupTaskOrdersByWaveId, groupTaskOrdersByPickStatus, groupTaskOrdersByBoxNo, groupTaskOrders, buildRecheckReviewNo, assertOrderCanRecheck, recheckOrderList, queryRecheckOrderSingleList, queryRecheckOrderGroupList, resolveModelTableName, confirmIntercept, interceptScan, batchQuickRecheck, normalizeWaveIds, batchQuickRecheckByWave, _completePickForOrder, _markRecheckForOrder, _tryCompleteWaveIfAllOrdersRechecked, _tryCompleteWaveInTransaction, removeUnprintedInterceptedOrdersFromWave, _updateTaskOrderReviewInTransaction, _unbindCartForTaskInTransaction, _writeRecheckActionLogInTransaction +- app/service/systemMethods/order/reviewOrder.js (2) + - list, reviewOrder +- app/service/systemMethods/order/storageAllocation.js (0) + - +- app/service/systemMethods/order/wave.js (243) + - buildBatchAllocateExpressTraceId, buildOrderOperationLogRows, batchCreateOrderOperationLogs, buildMachineStructureToken, parseMachineStructureToken, getOrderItemPart, getDefaultWaveQuantity, getMinGroupOrderFetchQuantity, getGroupWavePrefix, getSingleFetchByIdsWavePrefix, getWarehouseSubjectConfig, getWarehouseSubjectConfigValue, normalizeFetchStructureRequests, generateWaveId, getCurrentDatePart, getNextWaveNoSequence, buildWaveNo, getWaveCreator, extractInsertId, extractLastInsertId, isDuplicateEntryError, resolveWaveScopeByWaveMeta, createWaveBatchReady, buildFetchWhere, fetchSingleStructure, normalizeBoolean, normalizePositiveInteger, normalizeRequiredPositiveInteger, normalizeIdsInput, normalizePagination, normalizeWaveStatusList, normalizeBatchListStorageAssignmentStatusFilter, normalizeBatchListExpressAssignmentStatusFilter, normalizeBatchListPrintAssignmentStatusFilter, normalizeBatchListConfirmPrintAssignmentStatusFilter, normalizeBatchListClaimAssignmentStatusFilter, normalizeBatchListReviewAssignmentStatusFilter, normalizeBatchListSyncAssignmentStatusFilter, getBatchListAssignmentFilterSchema, normalizeBatchListAssignmentStatusFilterByType, normalizeBatchListAssignmentStatusFilter, getModelTableSqlName, buildBatchListStorageAssignmentFilterClause, buildBatchListExpressAssignmentFilterClause, buildBatchListPrintAssignmentFilterClause, buildBatchListConfirmPrintAssignmentFilterClause, buildBatchListClaimAssignmentFilterClause, buildBatchListReviewAssignmentFilterClause, buildBatchListSyncAssignmentFilterClause, buildBatchListAssignmentStatusFilterClauseByType, buildBatchListAssignmentStatusFilterClause, isEmptyBatchListWhereValue, resolveBatchListFieldCondition, buildBatchListFieldConditionSql, normalizeBatchListDistinguishExpressValue, normalizeBatchListStoreIdCondition, buildBatchListWhereClause, normalizeWavePickTaskListPagination, normalizeWavePickTaskListRequest, buildWavePickTaskListWhereClause, resolveAssignmentStatus, normalizeSkuText, normalizeShopName, parseItemSnapshot, normalizeOrderItemRow, mergeOrderItemDetails, buildItemSummary, buildOrderItemSnapshot, buildItemSnapshotKey, orderMatchesIncludeSku, buildCoarseGroupKey, buildStatusSummary, buildGroupKey, groupOrderFetchList, singleOrderFetchList, fetchableOrderCount, waveStrategyList, getWaveStrategyNextFetchOrderCountMap, getWaveStrategyDebugFetchOrderListMap, previewWaveStrategyNextFetchOrderCount, getWaveStrategyMatchedOrderCountFilteredMap, getWaveStrategyMatchedOrderCountTotal, waveStrategyCreate, waveStrategyUpdate, bumpWaveStrategyVersionAndInvalidateCache, getWaveStrategyModel, normalizeWaveStrategyId, normalizeWaveStrategyUpsertPayload, normalizeWaveStrategyWavePrefix, resolveWaveStrategyFetchWavePrefix, patchWaveStrategyIntegerField, validateWaveStrategyAllowedOwners, validateWaveStrategyAllowedExpresses, getWaveStrategyAvailableOwnerSet, getWaveStrategyAvailableExpressSet, applyWaveStrategyMaxSameStructureConstraint, normalizeWaveStrategyFallbackOrderListWhere, resolveWaveStrategyFallbackTrackingNo, resolveWaveStrategyFallbackStoreName, resolveWaveStrategyFallbackSysLogisticsName, buildWaveStrategyFallbackOrderListItem, waveStrategyFallbackOrderList, resolveWaveBatchOwnerStoreNameMap, batchList, getConfirmPrintUnclaimedVersionKey, bumpConfirmPrintUnclaimedWaveVersion, getConfirmPrintUnclaimedWaveVersion, queryConfirmPrintUnclaimedWaveCount, confirmPrintScan, confirmPrintUnclaimedWaveCount, wavePickTaskList, batchCancel, batchCancelTaskProgress, batchAllocateExpress, batchAllocateExpressTaskProgress, batchAllocateStorage, batchAllocateStorageTaskProgress, submitWaveStrategyQuickScanForWarehouse, waveStrategyQuickScan, waveStrategyQuickScanTaskProgress, buildWaveStrategyQuickScanOrderWhere, getWaveStrategyQuickScanStrategyRows, getWaveStrategyQuickScanMatchModel, syncWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds, enqueueWaveStrategyQuickScanPostOrderChange, executeWaveStrategyQuickScan, runWaveStrategyQuickScanTask, batchUpdateWaveStrategyQuickScanOrders, generateWaveStrategyQuickScanTaskId, normalizeWaveStrategyQuickScanTaskId, getWaveStrategyQuickScanTaskCacheKey, setWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanWarehouseLockCacheKey, setWaveStrategyQuickScanWarehouseLock, getWaveStrategyQuickScanWarehouseLock, clearWaveStrategyQuickScanWarehouseLock, normalizeWaveStrategyQuickScanVersion, normalizeWaveStrategyQuickScanList, normalizeWaveStrategyQuickScanNumberOrNull, normalizeWaveStrategyQuickScanBoolean, normalizeWaveStrategyQuickScanStringList, getWaveStrategyQuickScanStructureKey, getWaveStrategyQuickScanExpressKey, filterCandidateOrdersByRequireSameExpress, isWaveStrategyQuickScanOrderMatched, getWaveStrategyQuickScanMatchedStrategyIds, isWaveStrategyQuickScanOrderMatchedSingleStrategy, isWaveStrategyQuickScanValueInRange, resolveGroupCandidateOrderIdsForSingleFetch, singleFetchByIds, batchRemoveOrders, resortWaveIndex, batchRemoveExceptionOrders, batchRemoveExceptionOrdersTaskProgress, generateBatchCancelTaskId, normalizeBatchCancelTaskId, generateBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersWaveIds, getBatchRemoveExceptionOrdersTaskCacheKey, setBatchRemoveExceptionOrdersTaskProgress, getBatchRemoveExceptionOrdersTaskProgress, isExceptionRemovableOrder, runBatchRemoveExceptionOrdersTask, normalizeBatchCancelWaveIds, getBatchCancelTaskCacheKey, setBatchCancelTaskProgress, getBatchCancelTaskProgress, runBatchCancelTask, generateBatchAllocateExpressTaskId, normalizeBatchAllocateExpressTaskId, normalizeBatchAllocateExpressWaveIds, getBatchAllocateExpressTaskCacheKey, setBatchAllocateExpressTaskProgress, getBatchAllocateExpressTaskProgress, generateBatchAllocateStorageTaskId, normalizeBatchAllocateStorageTaskId, normalizeBatchAllocateStorageWaveIds, normalizeBatchAllocateStorageTaskCount, buildBatchAllocateStorageRunningProgressPayload, normalizeBatchAllocateStorageOrderIds, getBatchAllocateStorageTaskCacheKey, getBatchAllocateStorageWarehouseLockKey, tryAcquireBatchAllocateStorageWarehouseLock, releaseBatchAllocateStorageWarehouseLock, setBatchAllocateStorageTaskProgress, getBatchAllocateStorageTaskProgress, isMissingBusinessKeyColumnError, runBatchAllocateExpressTask, runBatchAllocateStorageTask, batchAutoGrouping, batchFinishAutoGrouping, generateFetchTaskId, normalizeFetchTaskId, getFetchTaskCacheKey, setFetchTaskProgress, getFetchTaskProgress, fetchTaskProgress, runFetchTask, submitFetchTask, groupFetch, singleFetch, resolveWaveStrategyFetchPickMode, buildWaveStrategyFetchBoxAssignments, prepareWaveStrategyFetchPlan, ensureNoActiveWavePickTaskForOperator, normalizeWaveStrategyFetchCreatedBefore, buildWaveStrategyFetchTodayStart, getWaveStrategyFetchCandidateOrders, groupWaveStrategyFetchCandidateOrdersByStructure, buildWaveStrategyFetchOrderSkuMap, selectWaveStrategyFetchOrdersBySkuLimit, createWaveBatchByOrderIdsInTransaction, mergeWaveStrategyFirstPoolSameStructureOrders, autoPopulateWaveStrategyFetchSelections, executeWaveStrategyDirectFetch, createWavePickTaskFromPlan, buildTaskCreatePayload, buildTaskWaveRows, buildTaskOrderRows, buildTaskSkuRows, buildTaskBoxRows, bindPickCartForTask, initTaskCheckpointAndLogs, ensurePickCartAvailable, generateWavePickTaskNo, createWavePickTaskWithRetry, isTaskNoDuplicateError, bulkInsertRows, parseWaveStrategyExistingTaskInfo, waveStrategyFetchPda, cancelWavePickTasksInternal, wavePickTaskCancel, wavePickTaskCancelSelf, waveStrategyFetchAdmin, deleteOrderWaveIndexByOrderIds, deleteOrderWaveIndexByWaveIds, rebuildOrderWaveIndex, replaceOrderWaveIndexByWaveIds, fetch +- app/service/systemMethods/outbound.js (1) + - autoOutbound +- app/service/systemMethods/pick.js (16) + - normalizeBoolean, getOrderModelByWarehouse, generatePickTaskNo, createWavePickTask, resolveLocationSortedOrderIds, query, wavePickTaskDetail, wavePickTaskCurrent, wavePickTaskSubmit, wavePickComplete, wavePickTaskComplete, getWavePickModeByWaveId, getWaveClaimGateStats, bumpConfirmPrintUnclaimedWaveVersionSafe, backfillWaveClaimTime, waveClaimScan +- app/service/systemMethods/pickCart.js (9) + - scan, bindTaskCart, create, update, delete, batchDelete, detail, list, codeDuplicateCheck +- app/service/systemMethods/print.js (57) + - buildPrintSendInputSummary, summarizeExpressPayload, extractExpressTaskCodeFromPayload, buildPrintTaskCodeForRecord, buildPendingPrintRecordPayload, buildSentPrintRecordUpdatePayload, buildSendFailedPrintRecordUpdatePayload, normalizeOrderIds, collectOrderIdsFromPlatformGroup, collectOrderIdsFromCustomizeData, normalizeExpressPlatformCode, extractOrderIdsFromPrintRecordData, updateOrderPrintStatusByCallback, getPrintTaskCodeRetryConfig, getPrintTaskCodeWritebackRetryConfig, generateAtomicPrintTaskCode, isDuplicateKeyError, calculateBackoffDelayMs, sleep, reserveUniquePrintTaskCode, bindTaskCodeToPrintRecord, bindTaskCodeToPrintRecordWithRetry, send, validateExpressSendInput, loadExpressPrintStation, buildExpressPrintRecordFields, collectExpressPlatformCodes, extractUniqueWaveIds, collectOrderIdsFromWaveGroups, extractOrderIdsFromNotifyLockPayload, buildNotifyLockInputSummary, getPrintOrderOperationOperator, writePrintOrderOperationLogsByOrderIds, notifyLock, notify_lock, resolveBatchOrderIdsByWaveFallback, markWavePrintStatus, confirmWavePrint, lockOrderDeliveryAfterPrintSentSuccess, loadExpressPlatformComponents, validateExpressComponentsOnline, resolveExpressPrinterName, sendExpressWaveGroups, parsePrintCallbackTime, handlePrintCallback, getPrintResult, getPrintRecordItem, getList, getItem, add, hasName, updateItem, del, getComputer, getComputerPrinter, savePrinters, tryUnbindCartAfterPrintComplete +- app/service/systemMethods/printComputer.js (5) + - list, update, setRecording, cancelRecording, delete +- app/service/systemMethods/printer/station.js (1) + - list +- app/service/systemMethods/report.js (7) + - generate, generateTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/report/definition.js (4) + - typeList, save, list, delete +- app/service/systemMethods/report/deliveryLog.js (1) + - list +- app/service/systemMethods/report/deliveryPlan.js (3) + - save, copy, list +- app/service/systemMethods/returnReceived.js (12) + - _call, create, list, detail, delete, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/returnUnpack.js (21) + - _call, create, transferByWaybills, addDetail, updateDetail, removeDetail, cancel, submit, forceRecord, list, detailList, videoList, detail, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, delete +- app/service/systemMethods/returnWaybill.js (6) + - _call, create, update, list, detail, delete +- app/service/systemMethods/setting/account.js (7) + - callSystemAccount, list, add, delete, update, getBindWechatCode, unbindWechat +- app/service/systemMethods/setting/express.js (8) + - callSystemExpress, list, listBase, create, checkCodeUnique, update, resolveDeleteIds, delete +- app/service/systemMethods/setting/expressInterface.js (6) + - callSystemExpressInterface, list, listByWarehousePlatformCode, create, update, delete +- app/service/systemMethods/setting/packageMaterial.js (8) + - callSystemPackageMaterial, resolveDeleteIds, get, list, search, create, update, delete +- app/service/systemMethods/setting/packageSupplier.js (7) + - callSystemPackageSupplier, resolveDeleteIds, get, list, create, update, delete +- app/service/systemMethods/setting/permission.js (5) + - callSystemPermission, list, add, delete, update +- app/service/systemMethods/setting/platform.js (6) + - callSystemPlatform, list, create, update, resolveDeleteIds, delete +- app/service/systemMethods/setting/printTemplate.js (6) + - list, normalizeAndValidateBusinessType, save, create, delete, listTemplatesByType +- app/service/systemMethods/setting/role.js (6) + - callSystemRole, list, permission, add, delete, update +- app/service/systemMethods/setting/store_warehouse.js (0) + - +- app/service/systemMethods/setting/warehouse.js (4) + - getSettings, getFieldMeta, saveSettings, getweChatApp +- app/service/systemMethods/shops.js (6) + - callShopsSystem, list, add, del, edit, GetAuthorizeSessionKey +- app/service/systemMethods/stock/combo.js (0) + - +- app/service/systemMethods/stock/index.js (1) + - stockWarehouse +- app/service/systemMethods/stock/report.js (10) + - search, searchStore, exportStore, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/stock/store.js (0) + - +- app/service/systemMethods/stock/transaction.js (10) + - list, storeList, export, exportStore, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/stock/warehouse.js (37) + - normalizeWarehouseRecycleWhere, list, externalList, externalExport, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, import, _normalizeWarehouseImportRows, _normalizeWarehouseImportRow, _normalizeNeedRecheckValue, _normalizeBarcodeField, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search, getStockDetail +- app/service/systemMethods/storage/delivery.js (3) + - list, toOrder, listItems +- app/service/systemMethods/storage/entry.js (26) + - list, listStore, get, getStore, cancel, addItem, commit, removeItem, bindReceiving, unbindReceiving, quickInbound, getPrintData, receivingCompare, queryEntryLogs, getReceivingDetailsForBind, containerList, reviewEntry, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, storeExport, storeExportTaskProgress +- app/service/systemMethods/storage/expiry.js (1) + - list +- app/service/systemMethods/storage/inventory.js (16) + - transferLocation, transferByProduct, updateExpiry, extractStockQueryVirtualFilter, list, listByStockId, listBySpaceId, quickPutaway, directPutaway, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/storage/management.js (1) + - replenishmentDemand +- app/service/systemMethods/storage/receiving.js (29) + - getReceivingList, getStoreReceivingList, getReceivingDetail, batchCancelReceiving, create, bindStore, bindDetailProduct, addItem, removeItem, save, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving, rejectReceiving, reviewReceiving, queryReceivingLogs, scanDetail, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, storeExport, storeExportTaskProgress +- app/service/systemMethods/storage/stockout.js (10) + - list, toOrder, _restoreStockoutLocks, _writeStockoutOperationLog, listItems, listLogs, confirm, cancel, updateExpress, updateInfo +- app/service/systemMethods/storage/transaction.js (9) + - _parseListFilters, list, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/store_express_binding_policy.js (5) + - callSystem, list, add, edit, del +- app/service/systemMethods/store.js (6) + - createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply +- app/service/systemMethods/storeWarehouse.js (0) + - +- app/service/systemMethods/storeWarehouse/store.js (27) + - list, sign, confirmSign, rename, unbind, adjustPrintQuantity, queryPrintQuantityLogs, getPolicyConfig, getPolicyConfigFields, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, openAccount, createUser, export, exportTaskProgress, exportPrintQuantityLogs, exportPrintQuantityLogsTaskProgress, queryStorePrintQuantityLogs, exportStorePrintQuantityLogs, exportStorePrintQuantityLogsTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/storeWarehouse/warehouse.js (3) + - list, sign, confirmSign +- app/service/systemMethods/user.js (12) + - login, loginByCode, getBindWechatCode, getLoginWechatCode, unbindWechat, logout, info, getAccountInfo, updateUsername, changePassword, changeRole, register +- app/service/systemMethods/warehouse.js (25) + - getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo, getBatchFieldValue, hasBatchField, normalizeBatchString, getCurrentWarehouseCode, batchUpdateSpaceInfo, exportRackSpaces +- app/service/systemMethods/waybill/warehouse.js (9) + - list, detail, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/wechat.js (21) + - getMyLoginCode, getAuthUrl, loginByCode, bindUser, bindByEmployee, getUserAgreementText, getUserAgreement, setUserAgreement, getAgreementVersion, pushLoginCode, queryauth, wxaauth, getAuthorizerInfo, registerMiniprogram, updateInfo, uploadHeadimg, getTemplateList, commit, getTrialQRCode, submitAudit, userList +- app/service/systemMethods/workbench.js (17) + - list, detail, create, update, delete, business, bindCamera, bind, getWorkbenchInfo, resetLoginCode, removeMember, bindMember, packOrder, finishPack, sendWeight, queryOrder, getWorkbenchCount +- app/service/systems/account_platform.js (11) + - getActiveInclude, getPrimaryRoleBinding, formatActiveContext, switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext +- app/service/systems/afterSale.js (46) + - list, countPending, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder, getDetail, _enrichAfterSaleDetail, _resolveOrderDetail, _resolveStoreContractNote, _resolveWaybillDetail, _enrichStepsWithAttachments, create, _enrichListStoreNames, update, _formatAfterSaleRow, addStep, bindAttachments, transfer, handleWorkOrder, createInterceptWorkOrdersAndNotify, _resolveFollowupHours, _tryParseHours, batchSetPendingFeedback, batchClose, registerClaim, exportAfterSales, _generateAndUploadExcel, _getCreateChannelLabel, _createAfterSaleTypeConfigError, _validateAfterSaleTypeCode, _normalizeAfterSaleTypeSortOrder, _normalizeAfterSaleTypeEnabled, _formatAfterSaleTypeConfigRow, _buildAfterSaleTypeListWhere, _buildAfterSaleTypeListOrder, _buildAfterSaleSubTypeListWhere, _buildAfterSaleSubTypeListOrder, getTypeList, createType, updateType, deleteType, getSubTypeList, createSubType, updateSubType, deleteSubType +- app/service/systems/api_sign.js (4) + - getApiAppCacheKey, getApiAppConfigByAppKey, getApiAppSecretByAppKey, verifyRequestSignByAppKey +- app/service/systems/apiApp.js (8) + - generateAppKey, generateAppSecret, getDefaultInterfaceTypeId, list, create, update, delete, regenerateSecret +- app/service/systems/auth/role_permission.js (7) + - normalizeTypeFilter, normalizePermissionSet, toApiPermissionIds, serializePermissionSet, getPermissionIdsForRoles, assignPermissions, removePermissionsFromAllRoles +- app/service/systems/auth/user.js (70) + - getMenuTypeWhereByPlatform, getCurrentAccountId, getWechatBindCacheKey, getWechatBindCodeCacheKey, getWechatBindScanCacheKey, getWechatLoginClientCacheKey, getWechatLoginCodeCacheKey, getWechatLoginEventChannel, createWechatBindCodeCandidate, createUniqueSixCode, createWechatBindCode, createWechatLoginCode, createWechatLoginClientCode, parseWechatBindCode, formatBindWechatData, formatLoginWechatData, getRemainingSecondsByExpiresAt, setWechatBindCache, setWechatBindCodeCache, setWechatBindScanCache, getWechatBindScanCache, setWechatLoginClientCache, setWechatLoginCodeCache, findYe4sBindingByAccountId, getWechatBindEventChannel, getWechatLongPollTimeoutMs, shouldUseWechatBindLongPoll, publishWechatBindEvent, publishWechatLoginEvent, waitForWechatBindEvent, refreshWechatBindState, login, loginByYe4sCode, waitForLoginCodeRefresh, isTransientWechatLoginError, extractYe4sUserIdFromLoginEvent, waitForWechatLoginEvent, loginByYe4sUserId, tryBuildWechatLoginTokenFromState, refreshWechatLoginState, getLoginWechatCode, getBindWechatCode, getBindWechatCodeByAccountId, getUserByTempCode, bindAccountByTempCode, unbindWechat, unbindWechatByAccountId, buildLoginResult, changeRole, info, getAccountInfo, updateUsername, changePassword, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register +- app/service/systems/camera.js (12) + - list, detail, create, update, setOsd, _findCameraForControl, _assertPtzSuccess, ptzControl, ptzStop, ptzPresetGoto, ptzPresetSet, delete +- app/service/systems/cameraServer.js (5) + - list, detail, create, update, delete +- app/service/systems/client_error_log.js (5) + - _pick, _toText, _parseClientTime, _normalizeItem, upload +- app/service/systems/comboGoods.js (15) + - fetchStockInfoMap, buildSimpleNotation, buildNameNotation, validateItems, getTargetStoreIdFromMap, checkCustomCodeUniqueForCreate, checkCustomCodeUniqueForUpdate, list, buildListWhere, create, update, delete, search, searchByIdOrCode, enrichComboList +- app/service/systems/delivery_order.js (55) + - getStoreSubjectConfigCacheKey, normalizeStoreSubjectConfig, getStoreSubjectConfig, findCodeOption, getOptionName, appendOrderOperationLog, getOrderLogOperator, getOrderLogWarehouseId, flushOrderOperationLogs, findPlatformOptionByCode, getPlatformSnapshotCode, getPlatformSnapshotName, resolvePlatformSnapshot, resolveExpressCodeFromSetting, resolveExpressSettingSnapshot, resolveEnableExternalExpressCode, resolveExpressSnapshot, normalizeNeedOmsWaybill, addOrder, buildOrderStats, isRetryableLockError, isPrimaryKeyDuplicate, formatOrderCreateError, resolveOrderStep, generateItemsHash, calculateCRC32, normalizeOrderFromKey, resolveOperatorName, prepareOrderData, addOrderLines, buildOrderItemSnapshot, safeParseFloat, withPatchedCtxUser, buildAsyncProcessContext, buildExpressAllocateRequest, enqueueAutoWaybillAllocation, buildStorageAllocateRequest, getStoreWarehousePolicyConfig, normalizePolicyFlag, resolveCutoffOrderConfig, isPastCutoffTime, isAllocationWindowClosed, buildAutoGroupingStructure, findAutoGroupingWaveId, appendOrderToWave, countCandidateGroupOrders, createGroupingWave, markWaveAutoGrouping, finishAutoGroupingIfNeeded, runAutoGrouping, runAsyncProcessStep, findAutoExpressExcludedRemark, appendAutoExpressSkipLog, appendNeedOmsWaybillWaitLog, asyncProcessOrderCreated +- app/service/systems/deliveryOrderSummary.js (3) + - queryDailySummary, queryDailyCount, queryDailyShipped +- app/service/systems/entry_order.js (16) + - addOrder, getLineCount, received, success, fail, findByOrderCode, findByStatus, getStatsByWarehouse, updateSyncStatus, updateOrderStatus, calculateReceivedQuantities, batchUpdateReceived, getOrderProgress, tryCreateEntryOrder, addItems, reviewEntry +- app/service/systems/excel.js (26) + - getContentType, sanitizeSheetName, normalizeHeaders, normalizeColumns, prepareSheetData, hasEmbeddedImages, buildWorksheet, buildWorkbook, buildExcelJsWorkbook, inferImageExtension, resolveImageSource, mergeCellStyle, applyStyledRows, applyTextColumnsToSheetJs, applyTextColumnsToExcelJs, addEmbeddedImages, generateBuffer, writeFile, writeAtomicBufferFile, sanitizeFilename, buildUploadKey, generateAndUpload, sendFile, parseBuffer, parseFile, workbookToJSON +- app/service/systems/express_platform.js (16) + - getOrderLogOperator, buildOrderExpressVerPatch, buildExpressPlatformTraceId, cleanupFailedWaybillOrders, warnExpressCodeMismatch, buildFailedOrderCleanupList, polyapi, cainiao, parsePlatformPrintData, stringifyPlatformPrintData, buildWaybillOrderMetaMap, buildWaybillSettlementRelationMap, lockAndDeductWaybillSettlement, persistWaybillSuccessUpdates, normalizePddExtData, pdd +- app/service/systems/express_policy.js (10) + - getWarehousePolicyCacheKey, getWarehousePolicyCacheTTL, clearWarehousePolicyCache, fetchWarehousePoliciesFromDB, getWarehousePolicies, _matchAnyToken, _matchAnyIntersect, _matchValueInArray, _isStoreOnlyPolicy, matchPolicy +- app/service/systems/express.js (71) + - getExpressListCacheKey, getCurrentWarehouseId, buildWaybillTraceId, getOrderLogOperator, getOrderLogWarehouseId, createAllocateExpressFailureLogs, normalizeWaybillBusinessKeys, normalizeWaybillCreatePlatformCode, normalizeWaybillPolicyConfig, buildWaybillBalanceExceptionText, normalizeWaybillCreateOrders, buildWaybillCreateRelationGroups, collectWaybillRelationProcessingState, buildWaybillRelationLockMap, lockWaybillRelationBalance, markWaybillOrdersAsException, writeWaybillOrderExceptions, writeDispatchOrderFlags, markWaybillAsyncOrdersAsError, buildMergedExpressLabel, normalizeExpressSettingRow, loadExpressSettingListFromDatabase, buildExpressSettingCustomCodeList, buildMergedExpressList, getExpressProductTypeListCacheKey, normalizeExpressProductTypeRow, normalizeExpressCodeKey, isSfExpressCode, extractExpressProductTypesFromTypeDesc, collectPddSfTimedDeliveryProductTypes, clearExpressProductTypeCache, upsertExpressProductTypeList, syncPddSfTimedDeliveryExpressProductTypes, normalizeExpressRow, loadExpressList, loadExpressListFromCache, loadExpressListFromDatabase, getSystemExpressList, loadExpressProductTypeListFromDatabase, getExpressList, getExpressProductTypeList, normalizeWaybillPrintPlatformCode, loadWaybillPrintPlatformCodeMap, loadWaybillAsyncRequestPlatformCodeMap, resolveWaybillAsyncRequestPlatformCode, resolveWaybillGroupPrintPlatformCode, groupWaybillOrdersByPlatformAndLogistics, splitWaybillOrdersIntoBatches, pickWaybillExpressInterface, resolveWaybillAsyncPlatformCode, groupWaybillAsyncOrdersByPlatform, buildWaybillOrderDeliveryMap, normalizeWaybillAsyncText, normalizeWaybillAsyncNumber, formatWaybillAsyncDate, normalizeWaybillAsyncItems, buildWaybillAsyncRouteInfo, buildWaybillAsyncOrderInfo, buildWaybillAsyncReceiverInfo, buildWaybillAsyncSettlementInfo, buildWaybillAsyncItemsSummary, buildWaybillAsyncOrderListItem, buildWaybillAsyncBizcontentSkeleton, shouldDispatchWaybillAsyncPerOrder, dispatchWaybillAsyncPlatform, resolveWaybillAsyncDispatchPlatformCode, hardDeleteWaybillAsyncOrderExpressRows, getWaybillAsyncOrderDeliveryModel, createWaybillCodePipeline, asyncTask, createWaybillCode +- app/service/systems/fast_where.js (13) + - buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete +- app/service/systems/file.js (2) + - getImages, ReferenceFile +- app/service/systems/frontConfig.js (49) + - createError, getCurrentWarehouseId, deleteCacheByKey, normalizeText, normalizeTheme, assertDomainUnique, getRecordField, sanitizeErrorText, getDomainVerifyConfig, resolveDohUrls, getCnameTarget, buildDomainVerifyCode, parseTxtAnswerData, extractTxtValuesFromAnswers, queryDohEndpoint, resolveTxtByDoh, resolveTxtBySystem, resolveTxtValues, verifyDomainRecord, isUnknownColumnError, findVerifiedDomainRecord, verifyPendingDomains, buildInfoOutput, buildCertOutput, getInfo, getCert, getDomain, setDomain, promotePendingDomain, checkPendingDomainRecord, checkDomain, buildDomainOutput, buildResolvedValues, describeDomainStatus, getDomainCacheKey, buildPublicOutput, clearDomainCache, clearDomainCaches, buildPendingClearPatch, getByDomain, normalizePem, parseCertPem, assertCertValid, collectCertNames, certCoversDomain, validateKeyPem, assertWarehouseSubject, saveInfo, saveCert +- app/service/systems/inbound_direct_log.js (14) + - getItems, _addSingleItem, _bindReceivingDetail, addItem, removeItem, commit, notifyEntryOrderCompleted, _queryCompletedEntryItems, _buildCompletedItemLines, buildEntryOrderConfirmRequest, _sendOpenApiCallback, qimenEntrySync, _syncReceivingStorageStatus, _applyReceivingStockOccupancy +- app/service/systems/inbox/group.js (11) + - list, quickList, members, disable, update, reset, validateExpressInterfaces, validateSystemExpressCode, findGroupsByExpress, findStoreAfterSalesGroups, findStoreGroups +- app/service/systems/inbox/v2.js (41) + - wid, _invalidate, _op, _assertWritableSubType, _findSubType, _page, type, _typeList, _typeCreate, _typeUpdate, _typeDelete, subType, _subTypeList, _subTypeCreate, _subTypeUpdate, _subTypeDelete, keyword, _keywordList, _keywordDupDescribe, _keywordCreate, _keywordUpdate, _keywordDelete, numberRule, _numberRuleList, function, _functionList, _functionUpdate, reply, _replySave, _replyRestore, _replyMerged, _replyCreate, _replyUpdate, _replyDelete, relation, _relFunctionList, _relFunctionSet, _relRuleList, _relRuleSet, _relGroupList, _relGroupSet +- app/service/systems/intercept_auto_confirm.js (9) + - withPatchedCtxUser, listCurrentWarehouseIds, buildCandidateWhereSql, matchesAutoConfirmCriteria, Date, resolveCurrentTableName, scanCandidateOrderIds, confirmInterceptForOrderIds, runAutoConfirm +- app/service/systems/license_plate.js (7) + - getTencentCloudConfig, getTencentCloudRegion, normalizeBase64Image, buildTencentCloudRequest, sendTencentCloudRequest, recognizeLicensePlate, formatLicensePlateResult +- app/service/systems/location_space.js (16) + - create, batchCreate, list, detail, update, delete, toggleStatus, updateStatus, findAvailableSpaces, findByCode, findByBarcode, getWarehouseStats, getZoneStats, validateAllocation, validateTransferOut, _validateReferences +- app/service/systems/location_zone.js (24) + - collectZoneSubtree, assertSpacesNotOccupied, getWarehouseLevelZones, getZoneTreeByWarehouse, getChildrenByZoneId, isLeafNode, createZone, validateBasicFields, validateByZoneType, validateParentElement, validateZoneOverlap, isOverlap, generateZoneCodeByType, getDefaultColorByType, getZoneTypeText, updateZone, deleteZone, checkZoneOverlap, getZoneDetail, toggleZoneActive, getZonePath, generateSpacesForRack, getSpaceInfo, checkBarcodeUnique +- app/service/systems/location.js (10) + - createRackWithSpaces, _generateSpacesForRack, _calculateAreaRackOrder, _calculatePickPathForWarehouse, _updateSpacePickSequence, _calculatePickPriority, updateRackPosition, getPickPath, updateNeighborRelations, _findNeighborRacks +- app/service/systems/notice/drivers/generic.js (1) + - send +- app/service/systems/notice/drivers/wecom.js (4) + - buildTextContent, buildMarkdownContent, buildRequestData, send +- app/service/systems/notice/index.js (28) + - getDriver, normalizeMessageType, toObject, normalizeEventList, matchesEvents, buildTraceId, getRegisteredEventCodes, isValidEventCode, assertEventRegistered, getRetryDelays, sleep, isSuccessfulResponse, getFailureMessage, persistFailureLog, sendWithRetry, getStoreInfoCacheKey, resolveStoreInfo, resolveSubjectConfig, normalizePayload, buildOutgoingPayload, getWebhookLimit, findMatchedWebhooks, getFixedGroupTargets, findSubscribedGroups, resolveStoreLabelInternal, sendToWarehouseChannel, send, sendViaWebhooks +- app/service/systems/operation_log.js (14) + - buildOperationLogData, buildBusinessLogWhere, formatOperationLogRows, createOperationLog, createOperationLogs, queryLogsByBusinessType, queryStockLogs, queryOrderLogs, queryAllOrderLogs, queryAllLogsByBusinessType, queryReceivingLogs, queryEntryOrderLogs, queryStockoutLogs, getMessageDetail +- app/service/systems/order_async.js (9) + - finalizeSuccessfulQimenSync, syncQmOrders, syncManualOrders, flushDeferredOrderSyncNotices, syncApiOrders, syncStockoutOrders, buildStockoutConfirmRequest, notifyStockoutExternal, resolveOpenApiAppByStore +- app/service/systems/order_auto_outbound.js (17) + - getEnabledAutoOutboundWarehouses, isAutoOutboundEnabled, resolveAutoOutboundRules, normalizeSubjectConfigForAutoOutbound, buildAutoOutboundWhere, findAutoOutboundOrderIds, resolveSameDayTime, resolveSameDayDeadlineTime, resolveSameDayReleaseTime, buildBeijingDayStartUtc, buildSameDayOutboundHoldWindows, buildSameDayOutboundRecheckCondition, findOrderIdsWithWeigh, processWarehouseAutoOutbound, writeAutoOutboundOperationLogs, buildAutoOutboundRuleSummary, executeAutoOutbound +- app/service/systems/order_delivery_archive.js (16) + - getArchiveDefaults, buildArchiveOptions, buildArchiveThresholds, normalizeWarehouseIds, listDispatchWarehouseIds, getArchiveModels, buildCandidateWhere, buildQueryOptions, buildHistoryOrderRow, buildHistoryItemRow, getArchiveErrorInfo, rollbackQuietly, archiveDispatchBatch, archiveDispatchOrdersForWarehouse, resolveFailureCursor, archiveDispatchOrdersToHistory +- app/service/systems/order_delivery_migration.js (15) + - syncOutboundOrdersToDelivery, retryTimeoutOutboundOrdersToDelivery, syncOutboundOrdersByStatus, normalizeWarehouseIds, listCurrentWarehouseIds, normalizeOutboundStatuses, buildMigrationQueryOptions, getOutboundMigrationErrorInfo, markOutboundOrdersTimeout, buildDispatchKey, buildDispatchRow, buildDispatchItemRow, getMigrationModels, buildTargetOrderIdMap, syncOutboundOrdersForWarehouse +- app/service/systems/order_export.js (14) + - getExportPageSize, normalizeExportModuleName, getSortModuleNameByTableType, resolveExportTarget, getOrderExportColumns, normalizeExportColumns, buildOrderExportFilename, buildUploadKey, toPlainRow, normalizeExportCellValue, mapOrderExportRow, uploadOrderExportFile, buildOrderExportPage, exportOrders +- app/service/systems/order_express.js (34) + - createBusinessError, normalizeOrderId, normalizeWaybillCode, normalizePackageMaterialCode, normalizePackageMaterialId, normalizeBindOrderId, getCurrentWarehouseId, findActivePackageMaterialById, findActivePackageMaterialByCode, findValidOrderExpressByOrderAndWaybill, findOrderInterceptStatus, assertOrderNotIntercepted, findOrderWaveAndPackStatus, isSingleWeighRequirePack, assertSingleOrderPackedForWeigh, buildWeighPackBlockedMessage, normalizeWeighingWeight, findValidOrderExpressRows, updateWeighingWeight, updateWeighingWeightByWaybill, _updateWaveAllOrdersWeight, _buildWaveWeighingSummary, _getStoreName, _getWaveSysLogisticsName, _updateSingleOrderWeight, _updateWaveOrderWeight, _writeWeighActionLog, _tryWaveCompatibility, _upsertPackageMaterialItemRelation, bindExpressPackageMaterial, bindExpressPackageMaterialByWaybill, _bindSingleExpressPackageMaterial, _bindWavePackageMaterialByBusinessKey, _writePackageMaterialActionLog +- app/service/systems/order_outbound.js (1) + - markOutboundOrder +- app/service/systems/order_packing.js (10) + - _getRecordingComputerId, _buildVideoUrl, createBusinessError, _buildListWhere, _buildListOrder, list, exportPackTask, get, setEndTime, forceRecord +- app/service/systems/order_pending_exception.js (2) + - markPendingException, reversePendingException +- app/service/systems/order_print.js (55) + - isOrderLocked, buildLockedWavePlatformResult, buildLockedOrderPlatformPrintItem, shouldLoadPickingDetails, normalizeItemSnapshot, getFirstNonEmptyFieldText, buildPrintItemAggregationKey, buildPrintOrderRowMapWithPicking, normalizeContractPolicyConfig, getWavePlatformPrintData, getOrderPrintData, getPrintDataByWaybillCodes, queryWaybillsByCodes, getMainWaybillMapByOrderIds, normalizeUnlockGroupRules, isOrderMatchedByUnlockGroupRule, unlockWavePlatformPrintDataByGroup, normalizeWaveIds, normalizeOrderIds, getContextWarehouseId, resolveWarehouseId, queryWavesByIds, queryOrdersByWaveIds, queryOrdersByIds, queryOrderExpressByOrderIds, queryWaveOrderIndexMapByOrderIds, querySmallGroupBoxNoMap, queryWaveTotalOrderCountMap, assertBusinessWaybillCompleteness, buildOrderExpressMap, isCainiaoPlatformCode, isJdPlatformCode, isPddPlatformCode, isDouyinPlatformCode, collectCainiaoExpressLookupCodes, queryCainiaoCpCodeMap, queryCainiaoExpressInterfaceList, queryJdExpressInterfaceList, queryPddExpressInterfaceList, queryDouyinExpressInterfaceList, pickCainiaoExpressInterface, pickJdExpressInterface, pickPddExpressInterface, pickDouyinExpressInterface, enrichCainiaoOrderExpressRows, enrichJdOrderExpressRows, enrichPddDyOrderExpressRows, getPolicyConfigMapByStore, resolvePrintPlatformCode, loadTemplateSampleByPlatform, buildOrderPlatformPrintItem, extractSinglePlatformPrintData, groupOrderPrintItemsByPlatform, groupOrderPrintItemsByWaveAndPlatform, filterFullyAssignedExpressWaves +- app/service/systems/order_review.js (14) + - createBusinessError, normalizeWaybillCode, isLockedStatus, isInterceptStatus, toPlainRecord, parseItemSnapshot, findOrderExpressByWaybill, findOrderById, findOrderItems, loadBarcodesByStockIds, loadImagesByStockIds, findWaveById, buildGroupInterceptList, pullReviewDataByWaybill +- app/service/systems/order_storage_allocation.js (5) + - allocatePicking, allocateStorage, syncOrderIds, cancelAllocateStorage, releaseInterceptLocksByOrderIds +- app/service/systems/pack_task_auto_finish.js (1) + - executeAutoFinishPackTasks +- app/service/systems/pick_compensation.js (8) + - executeCompensation, compensateWarehouse, getPendingOrderIds, findPendingPickingForDispatchOrders, findPendingPickingForCancelledOrders, releaseCancelledInTransaction, compensateInTransaction, createBusinessError +- app/service/systems/pick.js (37) + - getOrderModel, createBusinessError, getTableColumnSet, loadOrderItemMap, parseItemSnapshot, buildPickingSummary, getPickModeViewMeta, loadOrderWaveMap, buildPickingView, resolveWaveInfo, isOrderReviewed, buildWaveOrderWhere, queryPickingInfo, queryByOrder, wavePickTaskCurrent, wavePickTaskDetail, resolveOperatorContext, normalizePickCartStatus, buildPickCartDetail, getPickCartById, getPickCartByCode, pickCartCodeDuplicateCheck, assertPickCartCodeUnique, getOwnedTask, getTaskPickProgress, wavePickTaskSubmit, wavePickTaskComplete, _afterSkipInterceptedPostActions, _writePickCompleteActionLog, pickCartScan, wavePickTaskBindCart, pickCartCreate, pickCartUpdate, pickCartDelete, pickCartBatchDelete, pickCartDetail, pickCartList +- app/service/systems/pickCart.js (9) + - scan, bindTaskCart, create, update, delete, batchDelete, detail, list, codeDuplicateCheck +- app/service/systems/platform.js (38) + - getCurrentWarehouseId, normalizePlatformOauthBindCode, getPlatformOauthBindSuccessCacheKey, getPlatformOauthBindFailCacheKey, getPlatformOauthBindEventChannel, getPlatformOauthLongPollTimeoutMs, shouldUsePlatformOauthLongPoll, getPlatformOauthBindState, publishPlatformOauthBindEvent, waitForPlatformOauthBindEvent, listenPlatformOauthBind, getPlatformFullAttributes, getPlatformSettingFullAttributes, getPrintPlatformModel, toPlainRow, normalizePrintPlatformId, loadPrintPlatformCodeMap, loadPrintPlatformPlatidMap, resolveDefaultExpressInterface, resolveRoutePlatformCode, getPlatformListCacheKey, isFullPlatformCacheSchemaStale, buildMergedPlatformLabel, normalizePlatformRow, loadPlatformSettingListFromDatabase, normalizePlatformSettingRow, normalizeFullPlatformRow, normalizeFullPlatformSettingRow, buildMergedPlatformList, loadPlatformListFromDatabase, getSystemPlatformList, getPlatformList, checkPlatformExists, getPlatformInfo, clearPlatformCache, getPlatformSettingDetail, batchCheckPlatforms, createPlatformSetting +- app/service/systems/polo_api.js (3) + - request, get, kuaishou +- app/service/systems/print/index.js (2) + - sendToComputer, test +- app/service/systems/print/printData.js (1) + - getPrintData +- app/service/systems/printComputer.js (6) + - notifyRefreshInfo, list, update, setRecording, cancelRecording, delete +- app/service/systems/qimen_query.js (3) + - qimenClient, send, sendRequest +- app/service/systems/receiving_entry_match.js (27) + - matchAfterEntryCompleted, _bindEntryOrderReceiving, bindEntryOrderReceiving, _bindReceivingsWithStorageSync, _bindOneReceivingAndSyncStorage, _syncReceivingStorageByEntryItems, _parseLedgerMap, _serializeLedgerMap, _buildLegacyBaselineLedger, _bindingAllocationByStock, _recalcReceivingStorageStatus, _reconcileEntryReceivedQuantity, recordLedgerAllocation, setLedgerAllocation, rollbackEntryOrderBindings, _rollbackOneBindingStorage, _getRecentReceivingOrders, _findReceivingByRemark, _compareDetails, _queryEntryOrderLines, buildEntryOrderConfirmRequest, _sendCallback, _sendQimenCallback, _sendOpenApiCallback, _markReceivingPartialStorage, _commitBinding, unbindEntryOrderReceiving +- app/service/systems/receiving_pending_notice.js (16) + - getMemoryDailyLocks, getWarehouseNoticeConfigs, findPendingReceivings, groupByStore, buildRowLine, formatDateOnly, buildTemplateVariables, buildContent, resolveNoticeSendMethod, sendPendingNotice, sendCustomerServiceFallback, notifyWarehouse, getRedisClient, acquireDailyLock, releaseDailyLock, execute +- app/service/systems/report.js (16) + - getDefinition, parseFieldsField, definitionToView, resolveTypeEntry, resolveQuerier, listRegisteredTypes, validateTypeFields, resolveOrderedFields, buildFilename, buildWorkbookSheets, generate, generateBuffer, saveDefinition, findDefinitionById, listDefinitions, deleteDefinition +- app/service/systems/report/queries/index.js (0) + - +- app/service/systems/report/queries/interceptOrder.js (0) + - +- app/service/systems/report/queries/sevenDayStockFlow.js (0) + - +- app/service/systems/reportDelivery.js (28) + - normalizeScheduleTimes, parseJsonArray, readJsonArray, readJsonObject, normalizeNotifyTemplate, normalizePlanName, normalizeNotifyGroupIds, normalizeNotifyMemberIds, validateNotifyGroupExists, savePlan, copyPlan, planToView, listPlans, listLogs, hitTimePoints, bizDateOfTrigger, bizDateOfTimePoint, resolveStoreWarehouse, markDelivered, markFailed, markExporting, buildMessageContent, resolveNotifyGroups, deliverByChannel, sendNotifyIfConfigured, processOne, parseScheduleTimes, dispatch +- app/service/systems/return_received.js (19) + - createBusinessError, create, _isUrgentReturnQuery, notifyPending, _handleInterceptAfterSale, _updateOrderInterceptStatus, list, exportList, _generateExportExcel, detail, delete, _findByIdChecked, _enrichReturn, _resolveStoreRemark, _resolveStoreRemarkMap, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder +- app/service/systems/return_unpack.js (49) + - _getRecordingComputerId, _buildVideoUrl, createBusinessError, create, transferByWaybills, addDetail, updateDetail, removeDetail, cancel, _resolveSubmitEndTime, submit, _notifyUnpacked, forceRecord, list, detailList, videoList, exportUnpack, _resolveStoreNameMap, _resolveExpressNameMap, _extractDetailColor, detail, _buildWaybillMatch, _findWaybillFlexible, queryByWaybill, _resolveWarehouseName, _resolveStoreIdByWaybill, _resolveReturnOrderInfo, delete, _insertMainWithRetry, _transferOneWaybill, _backfillDetailsFromOrder, _countDetails, _resolveReturnReceivedId, _buildTransferDetailRows, _findByIdChecked, _assertUnpacking, _findDetailChecked, _recalcMain, _enrichRow, _flattenVideos, _enrichDetailsWithStock, _resolveStoreRemark, _generateUnpackNo, _buildListWhere, _buildDetailListWhere, _buildVideoListWhere, _buildVideoListOrder, _resolveConditionValue, _buildListOrder +- app/service/systems/return_waybill.js (12) + - createBusinessError, create, update, list, detail, delete, _findByIdChecked, _assertStoreContract, _formatRow, _buildListWhere, _resolveConditionValue, _buildListOrder +- app/service/systems/setting/account.js (31) + - getListWhereSpecialFieldMap, createError, getCurrentStoreId, getCurrentEmployeeId, normalizeAccountId, getWmsClient, normalizePhone, isValidPhone, normalizeName, normalizeUsername, generateUsername, findRawAccountByPhone, findRawAccountByUsername, getAvatarMeta, resolveRoleId, normalizeRoleIds, flattenRoleTreeMeta, resolveAssignableRoleScope, pruneDescendantRoleIds, resolveRequestedRoleIds, replaceEmployeeRoles, buildEmployeeRoleGroupMap, buildWechatBindingMap, getOperableEmployeeByAccountId, formatEmployeeRow, list, add, delete, update, getBindWechatCode, unbindWechat +- app/service/systems/setting/express.js (26) + - createError, getCurrentStoreId, getExpressListCacheKey, deleteCacheByKey, clearExpressListCache, normalizeDeleteIds, normalizeText, normalizeCode, normalizePage, getListWhereSpecialFieldMap, getSystemExpressList, getSystemExpressMap, normalizeSettingRow, findSettingById, findCodeConflict, ensureSystemExpressExists, ensureCodeAvailable, resolveListWhere, list, listBase, checkCodeUnique, create, update, findSettingsForDelete, ensureDeleteCodesNotReferenced, delete +- app/service/systems/setting/expressInterface.js (43) + - createError, getCurrentStoreId, getWarehousePlatformCacheKey, deleteCacheByKey, clearWarehousePlatformCache, normalizePlatformCode, normalizeText, normalizeOptionalText, normalizeOptionalJson, normalizeInteger, normalizeFlag, normalizePage, getListWhereSpecialFieldMap, resolveListWhere, getInterfaceInclude, getInterfaceFullAttributes, ensureModelFieldExists, resolveShopBinding, clonePlainValue, normalizeExpressRow, resolveIsSystemExpressCodeFlag, getPlatformExpressColumn, ensureSystemExpressCodeExists, ensurePrintPlatformExists, normalizePrintPlatformRow, getPrintPlatformList, resolveSysExpressCode, normalizeInterfaceRow, normalizeFullInterfaceRow, hasWarehousePlatformShopData, normalizeFullInterfaceRows, resolveWarehousePlatformTarget, findInterfaceById, findCodeConflict, findInterfaceConflict, ensureCodeAvailable, ensureInterfaceAvailable, list, listByWarehousePlatformCode, create, update, delete, loadExpressInterfaces +- app/service/systems/setting/packageMaterial.js (18) + - createError, getCurrentStoreId, normalizeRequiredText, normalizeOptionalText, normalizeOptionalDecimal, normalizeStatus, normalizePage, normalizeDeleteIds, getListWhereSpecialFieldMap, resolveListWhere, normalizeMaterialRow, ensureMaterialCodeUnique, findMaterialById, create, update, delete, get, search +- app/service/systems/setting/packageSupplier.js (16) + - createError, getCurrentStoreId, normalizeRequiredText, normalizeOptionalText, normalizeStatus, normalizePage, normalizeDeleteIds, getListWhereSpecialFieldMap, resolveListWhere, normalizeSupplierRow, ensureSupplierCodeUnique, findSupplierById, create, update, delete, get +- app/service/systems/setting/permission.js (26) + - createError, getCurrentStoreId, getCurrentEmployeeId, toPositiveNumber, getRole, getPermission, normalizePermissionType, normalizeOptionalString, normalizeParentId, normalizeSort, normalizeStatus, normalizeBooleanFlag, getAvailablePermissionIdSet, ensureParentPermissionExists, ensurePermissionsExist, normalizePermissionIds, normalizeIds, validatePermissions, clearRoleUsersCache, getCurrentEmployeePermissionIds, getCurrentRoleId, resolveVisiblePermissionRows, list, add, delete, update +- app/service/systems/setting/platform.js (26) + - createError, getCurrentStoreId, normalizeDeleteIds, getPlatformListCacheKey, getPlatformDetailCacheKey, getPlatformExistsCacheKey, deleteCacheByKey, clearPlatformCaches, normalizeRequiredText, normalizeOptionalText, normalizeInteger, normalizePage, getListWhereSpecialFieldMap, resolveListWhere, buildPlatformLabel, normalizePlatformRow, findSettingById, findCodeConflict, findPlatformCodeConflict, ensurePlatformExists, ensureCodeAvailable, ensurePlatformCodeAvailable, list, create, update, delete +- app/service/systems/setting/print_template.js (17) + - normalizeAndValidateBusinessType, listTemplatesByType, getTree, getTemplatesByType, save, createTemplate, deleteTemplate, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable +- app/service/systems/setting/role.js (25) + - createError, getCurrentStoreId, getCurrentEmployeeId, toPositiveNumber, getEmployee, normalizeRoleIds, findAssignableRoles, clearEmployeeCache, getCurrentEmployeeRoleIds, collectDescendantRoleIds, buildRolePermissionMap, buildRoleTree, normalizeStoreScope, isRoleVisibleInScope, normalizePermissionIds, normalizePid, getManageableRole, validatePermissionSet, replaceRolePermissions, clearRoleUsersCache, list, permission, add, delete, update +- app/service/systems/setting/store_warehouse.js (35) + - createError, getCurrentStoreId, getCurrentAccountId, toPositiveNumber, normalizePage, normalizeStatusFlag, normalizeAuthStatus, normalizeNonNegativeInteger, normalizeText, normalizeDate, normalizeSignAction, normalizeTempCode, getTempCodeCacheKey, createTempCode, pickRemaskField, resolveRemaskValue, buildCurrentRemaskPatch, requireCurrentRemaskPatch, saveTempSignPayload, getTempSignPayload, clearTempSignPayload, buildTempSignView, getCurrentSubject, getCounterparty, buildListWhere, getRelationIncludes, resolvePairIds, serializeRelation, findScopedRelation, list, sign, trimContract, confirmSign, rename, unbind +- app/service/systems/setting/warehouse.js (13) + - getDefaultCodeFieldOptionsMap, normalizeWaveStrategyVersion, normalizeSubjectConfigInternalFields, sanitizeSubjectConfigForOutput, createError, getCurrentWarehouseId, deleteCacheByKey, clearWarehouseSettingCache, getFieldMeta, getSettings, validateDefaultLocation, saveSettings, getWechatApp +- app/service/systems/shops.js (20) + - generatePendingShopName, createError, getCurrentWarehouseId, normalizeText, normalizeInteger, ensureShopPrintPlatformExists, getListWhereSpecialFieldMap, buildListWhere, normalizePagination, buildShopPrintPlatformInclude, formatShopRow, list, ensureShopNameUnique, add, findShopById, del, edit, generateAuthorizeRandomCode, createOrReuseAuthorizeReservation, getAuthorizeSessionKey +- app/service/systems/sign.js (10) + - Constants, toXml, signTopRequest, verifyTopRequest, verifyAndExtractParams, generateSignedParams, encryptHMAC, encryptHMACSHA256, encryptMD5, byte2hex +- app/service/systems/space.js (3) + - _searchByKeyword, searchSpace, searchSpaces +- app/service/systems/stock_store.js (45) + - create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, _runWithTransaction, getStoreWarehousePolicyByStoreAndWarehouse, getStoreWarehousePolicyConfigByStockId, updateLockedQuantity, lockItemStorages, inbound, normalizeOutboundMeta, getPickingRowsForOutbound, getPickingBatchMap, buildOutboundTransactionPayloads, outbound, checkAndCreateWarehouseStock, getWarehouseStock, exportWarehouseStock, exportExternalWarehouseStock, buildSequelizeCondition, processConditionValue, normalizeDate, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search, getStockDetail +- app/service/systems/stock_transaction.js (10) + - normalizeInboundOrderId, isOrderOutboundTransaction, resolveOutboundOrderReference, create, list, _buildStorageTransactionWhere, _resolveKeywordToStockIds, queryList, exportList, exportStorageList +- app/service/systems/stock_warehouse.js (3) + - _buildStockDetailCacheKey, getStockDetails, invalidateStockDetailCache +- app/service/systems/stockout_order.js (5) + - resolveStockoutExpress, create, query, cancel, _writeStockoutOperationLog +- app/service/systems/storage/entry.js (26) + - normalizeExpenseRecordValue, normalizeExpenseRecordCondition, normalizeFilterValues, buildEntryStockTransactionExistsCondition, buildHasReceivingCondition, preprocessEntryListWhere, list, get, enrichItemsWithAvailableReceivingDetails, normalizeCancelEntryOrderIds, getOwnedEntryOrderById, cancel, _guardCancelEntryOrder, _doCancelEntryOrder, _rollbackReceivingStorageStatus, addItem, commit, removeItem, getReceivingDetailsForBind, containerList, _applyReceivingInboundUsage, quickInbound, receivingCompare, _buildMergedComparison, exportEntryOrders, exportStoreEntryOrders +- app/service/systems/storage/expiry.js (1) + - list +- app/service/systems/storage/index.js (14) + - findByStockAndBatch, findBySpace, findAvailableByWarehouse, findExpiringSoon, updateQuantity, lockQuantity, unlockQuantity, allocateQuantity, interceptLockQuantity, interceptReceiveQuantity, interceptUnlockQuantity, offsetGapOnInbound, getStockSummary, getSpaceUsage +- app/service/systems/storage/inventory.js (16) + - createTransferStockTransactions, transferLocation, transferByProduct, updateExpiry, resolveStockQueryToStockIds, getInventoryList, getStorageListByStockId, getStorageListBySpaceId, _aggregateStorageRowsByStock, _aggregateStorageRowsBySpace, _loadInventoryWarningRanges, _formatBatchStorageRows, quickPutaway, directPutaway, exportInventoryList, _generateEntryOrderCode +- app/service/systems/storage/management.js (1) + - replenishmentDemand +- app/service/systems/storage/receiving.js (43) + - getReceivingList, _resolveStockQueryReceivingIds, _resolveReceivingStoreNameMap, getStoreReceivingList, getReceivingDetail, batchCancelReceiving, rejectReceiving, reviewReceiving, buildReviewReportSheets, sendStoreBoundNotice, resolveReceivingCreatorName, sendReviewNotice, resolveReviewDetailItemCodeMap, isEmptyValue, buildSequelizeCondition, processConditionValue, buildReceivingNumberPrefix, generateNextReceivingNumber, isReceivingNumberDuplicateError, create, save, bindStore, get, addDetail, bindDetailProduct, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, formatReportDate, formatDeliveryMethod, getCompletionContactFields, buildCompletionReportSheets, uploadCompletionExcelReport, sendCompletionNotice, sendStoreUnmatchedNotice, completeReceiving, _syncProductDataFromReceiving, scanDetail, exportReceivingList, exportStoreReceivingList +- app/service/systems/storage/report.js (5) + - loadReportReferenceMaps, buildExportFilename, export, _resolveKeywordToStockIds, search +- app/service/systems/storage/stock_warehouse.js (3) + - _buildStockDetailCacheKey, getStockDetails, invalidateStockDetailCache +- app/service/systems/store_express_binding_policy.js (17) + - getCurrentWarehouseId, createError, normalizeText, normalizeInteger, normalizeWeightType, normalizeJsonArray, ensureExpressExists, getListWhereSpecialFieldMap, buildListWhere, normalizePagination, formatPolicyRow, list, ensureCustomNameUnique, add, findPolicyById, edit, del +- app/service/systems/store_warehouse.js (80) + - createError, getCurrentStoreId, getCurrentAccountId, toPositiveNumber, normalizePage, normalizeStatusFlag, normalizeAuthStatus, normalizeNonNegativeInteger, normalizeInteger, normalizeText, normalizeIntegerRange, normalizeEmail, getPolicyConfigFieldList, getPolicyConfigFieldMetaList, normalizePolicyConfig, getPolicyConfigCacheKey, hasPolicyConfigColumn, loadPolicyConfigByContractId, savePolicyConfigByContractId, getPolicyConfigDefaults, mergePolicyConfigWithDefaults, getEffectivePolicyConfigByContractId, ensureWarehouseSubject, getNoticeService, sendPrintQuantityAdjustNotice, resolveRelationId, normalizeDate, normalizeSignAction, normalizeTempCode, getTempCodeCacheKey, createTempCode, pickRemaskField, resolveRemaskValue, buildCurrentRemaskPatch, requireCurrentRemaskPatch, saveTempSignPayload, getTempSignPayload, clearTempSignPayload, buildTempSignView, getCurrentSubject, getCounterparty, buildListWhereByStoreId, buildListWhere, getRelationIncludes, getQimenContractCacheKey, clearQimenContractCache, getApiInterfaceType, getQimenInterfaceType, resolveQimenCustomerIdByAppKey, getQimenErpNameMapByAppKeys, serializeQimenConfig, getQimenConfigMap, getSingleQimenConfig, resolvePairIds, serializeRelation, findScopedRelation, buildListForStoreWhere, listForStore, exportListForStore, listForWarehouse, list, sign, trimContract, confirmSign, rename, adjustPrintQuantity, queryPrintQuantityLogs, exportPrintQuantityLogs, getPolicyConfigFields, getPolicyConfig, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, unbind, getContractConfigCacheKey, invalidateContractConfigCache, getContractConfig, openAccount, createUser +- app/service/systems/store.js (22) + - normalizeSubjectConfigInput, validateStoreData, checkCompanyNameExists, findByAccountId, findAllEnabled, findAllWarehouses, getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, ensureEmployeeRoleBinding, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores, loadWarehouses, bindCode +- app/service/systems/upload.js (18) + - getTencentCloudConfig, getCosConfig, initCOS, getUploadParams, generatePolicyAndSignature, resolveUploadMaxSizeBytes, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, uploadBuffer, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback +- app/service/systems/video_record_request.js (14) + - _getRecordingComputer, _isComputerOnline, _resetVideoRecords, _withinReuseWindow, _markFailed, requestPackVideo, requestUnpackVideo, requestFor, syncByVideos, settleStatuses, notifyResults, _buildResultMessage, _notifyManualHandling, _replyResult +- app/service/systems/warehouseNotify.js (6) + - truncateLogBody, getCallbackConfig, buildSignature, writeLog, push, pushSystemMessage +- app/service/systems/wave_batch_closure.js (4) + - closeFinishedWaves, normalizeConfirmIntervalMs, readEmptyConfirmState, writeEmptyConfirmState +- app/service/systems/waybill.js (5) + - toOrder, list, detail, export, buildWaybillExportFile +- app/service/systems/wechat.js (34) + - getAuthUrl, resolveWechatApp, loginByCode, getMyLoginCode, bindUser, buildBindResult, bindByEmployee, getUserAgreementText, getUserAgreement, setUserAgreement, findWarehouseWechatApp, findLatestAgreementVersion, getAgreementVersion, cleanupUnusedAgreementVersions, pushLoginCode, queryauth, wxaauth, resolveBodyMedia, resolveMediaValue, downloadFromUrl, resolveMediaFilename, registerMiniprogram, updateInfo, buildHeadimgKey, uploadHeadimg, getTemplateList, hasFuncScope, buildAuthorizerPatch, getAuthorizerInfo, commit, submitAudit, buildTrialQrCodeKey, getTrialQRCode, userList +- app/service/systems/workbench.js (75) + - list, detail, create, update, delete, bindCamera, business, _loadPackCtx, _countWaveOrders, _countWaveOrdersCached, _sumWaveItemsTotal, _sumWaveItemsTotalCached, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _resetPackOsd, _sendWeight, _assertSingleWeighPackedForWeigh, _writeWeighOpLog, _aggregateWaveItems, _fetchWaveItemsSummary, _fetchOrderItemsDetail, _countCurrentPackMembers, _getBigGroupPackCoefficient, _queryOrder, generatePackCtxKey, getWorkbenchPackCtxCacheKey, getWorkbenchBindClientCacheKey, getWorkbenchBindCodeCacheKey, getWorkbenchTokenCacheKey, generateRandomChars, generateWorkbenchToken, generateWorkbenchLoginCode, normalizeWorkbenchBindCode, generateUniqueWorkbenchLoginCode, createUniqueWorkbenchClientCode, createUniqueWorkbenchBindCode, buildWorkbenchBindState, getWorkbenchBindRemainingSeconds, setWorkbenchBindState, createWorkbenchBindSession, refreshWorkbenchBindCode, formatWorkbenchBindData, waitForWorkbenchBindComplete, getWorkbenchBindCode, formatWorkbenchTokenInfo, listWorkbenchMembers, listCurrentPackTasks, buildCurrentPackingInfo, invalidateWorkbenchTokenCacheByWorkbenchId, buildWorkbenchTokenInfo, bindWorkbench, getWorkbenchInfoByToken, _round2, _formatPackCountTime, buildWorkbenchPackCountTimeRange, getWorkbenchCountByToken, loginWorkbenchByCode, resetLoginCode, clearExpiredWorkbenchTokens, resolveWorkbenchContext, resolveWorkbenchByToken, packOrderByToken, finishPackByToken, sendWeightByToken, queryOrderByToken, normalizeWorkbenchMemberIds, _finishAllPackTasksByMemberLogout, removeWorkbenchMember, bindWorkbenchMember +- app/service/warehouse.js (7) + - resolveWarehouseMethod, getWarehouseMethodService, dispatchWarehouseMethod, validateWarehouseParams, parseJsonBody, normalizeSignFields, processRequest +- app/service/warehouseMethods/inbox.js (2) + - push, parseSendTime +- app/service/warehouseMethods/index.js (1) + - ping +- app/service/warehouseMethods/store.js (1) + - list + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md new file mode 100644 index 0000000..36e13f6 --- /dev/null +++ b/AI_TOOLBOX.md @@ -0,0 +1,268 @@ +# AI 工具箱(WMS) + + +## 🤖 AI阅读优先级 +1. **必读**:第2节(数据库 agent 入口)、第4节(Redis agent 入口)、第7节(开发 agent 入口)、第8节(文档 agent 入口)、第9节(测试 agent 入口)- 最常用 +2. **重要**:第3节(提问模板)、第6节(安全约束)、第10节(发布 agent 入口) +3. **按需**:第11节(开发细节移交说明)、第16节(消息通知) +4. **红线**:10(发布必须走 agent)、6(SQL安全) + + +## Agent配置文件位置 + +GitHub Copilot 读取 `.github/agents/*.agent.md`;Cursor 使用 `.cursor/agents/wms-*-agent.md`(Subagent,YAML 为 Cursor 格式:`model` / `readonly` / `is_background` 等)。两处业务规则应保持一致。 + +| Agent名称 | GitHub Copilot | Cursor | +|-----------|----------------|--------| +| wms-db-agent | `.github/agents/数据库.agent.md` | `.cursor/agents/wms-db-agent.md` | +| wms-redis-agent | `.github/agents/缓存.agent.md` | `.cursor/agents/wms-redis-agent.md` | +| wms-deploy-agent | `.github/agents/发布.agent.md` | `.cursor/agents/wms-deploy-agent.md` | +| wms-dev-agent | `.github/agents/开发.agent.md` | `.cursor/agents/wms-dev-agent.md` | +| wms-test-agent | `.github/agents/测试.agent.md` | `.cursor/agents/wms-test-agent.md` | +| wms-doc-agent | `.github/agents/文档.agent.md` | `.cursor/agents/wms-doc-agent.md` | +| wms-dispatcher-agent | `.github/agents/调度.agent.md` | `.cursor/agents/wms-dispatcher-agent.md` | +| wms-expert-agent | `.github/agents/专家.agent.md` | `.cursor/agents/wms-expert-agent.md` | +| wms-review-agent | `.github/agents/评审.agent.md` | `.cursor/agents/wms-review-agent.md` | + + +## 快速响应规则 +- 用户要求查数据库/查数据/写 SQL → **必须使用 `wms-db-agent`** +- 用户要求查缓存/改缓存/Redis 排障 → **必须使用 `wms-redis-agent`** +- 用户要求发布/回退/查线上版本/做冒烟 → **必须使用 `wms-deploy-agent`** +- 用户要求改代码/修 bug/定位 method → **必须使用 `wms-dev-agent`** +- 用户要求写测试/补回归/跑接口验证/TDD/验证修复 → **必须使用 `wms-test-agent`** +- 用户要求补文档/同步 `methods/*.json` / 更新 `docs/*.md` / README → **必须使用 `wms-doc-agent`** +- 用户不确定该找哪个 agent,或问题横跨多个领域 → **必须使用 `wms-dispatcher-agent`** +- **全局安全红线(适用于所有 AI)**:**禁止删改处理非测试仓库的数据,包括数据库和缓存**;对非测试仓库默认只读;无法确认是否测试仓时,默认按非测试仓处理并拒绝写操作 +- 所有回复结尾加"喵~" + +## 1. 适用范围 + +- 项目根目录:D:\\wms +- 主要用途:本地调试、数据库取数、问题定位 +- 默认环境:PowerShell + Node.js + +## 2. 数据库能力移交规则 + +数据库相关能力文档已统一移交给 `wms-db-agent`。 + +适用场景: +- 查数据库 / 查数据 / 查表 +- 编写或审查 SQL +- 排查接口与数据库数据不一致 +- 核对 `wms` / `ye4s` client 路由 +- 输出字段含义、异常数据判断、索引建议 + +执行要求(强制): +- **涉及数据库的任何问题,必须使用 `wms-db-agent`** +- 默认 agent 不再在本文件重复维护数据库命令细节 +- 具体命令、示例、输出格式、安全约束统一见:`.github/agents/数据库.agent.md` + +## 3. AI 协助时建议使用的提问模板 + +### 3.1 数据库类请求(强制走 Agent) + +```text +请使用 wms-db-agent 帮我: +1) 定位相关 controller / service / model +2) 生成并执行只读 SQL +3) 输出结果、字段解释和结论 +``` + +### 3.2 Redis 类请求(强制走 Agent) + +```text +请使用 wms-redis-agent 帮我: +1) 找到相关 key 或 pattern +2) 读取当前值、TTL、exists 状态 +3) 如需修改,先展示变更前后对比并回读确认 +``` + +### 3.3 开发类请求(强制走 Dev Agent) + +```text +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动方案 +3) 给出验证结果与后续开发建议 +``` + +### 3.4 测试类请求(强制走 Test Agent) + +```text +请使用 wms-test-agent 帮我: +1) 先复现问题并补一个失败用例 +2) 按 TDD 跑回归或接口验证 +3) 输出 passing 数量、失败数和修复验证结论 +``` + +### 3.5 文档类请求(强制走 Doc Agent) + +```text +请使用 wms-doc-agent 帮我: +1) 根据代码现状整理接口或业务文档 +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) + +```text +请使用 wms-dispatcher-agent 帮我: +1) 判断这个问题属于数据库、Redis、发布、开发、测试还是文档问题 +2) 分派给正确的 agent +3) 汇总处理结果与下一步建议 +``` + +## 4. Redis 能力移交规则 + +Redis 相关能力文档已统一移交给 `wms-redis-agent`。 + +适用场景: +- 查 Redis key / pattern / TTL / exists +- 读取或修改缓存值 +- 排查 session、登录态、缓存不一致问题 +- 核对某接口是否命中缓存或缓存值异常 + +执行要求(强制): +- **涉及 Redis / 缓存的任何问题,必须使用 `wms-redis-agent`** +- 默认 agent 不再在本文件重复维护 Redis 命令细节 +- 具体命令、示例、输出格式、安全约束统一见:`.github/agents/缓存.agent.md` + +## 5. 常见问题 + +- 数据库相关报错、SQL 问题、连接路由问题 + - 统一转给 `wms-db-agent` 处理 + +- Redis 相关报错、key 排查、TTL 问题、缓存变更 + - 统一转给 `wms-redis-agent` 处理 + +- 发布相关报错、预检失败、回退、版本查询、冒烟验证 + - 统一转给 `wms-deploy-agent` 处理 + +- 开发相关问题:代码修改、method 路由、权限联动 + - 统一转给 `wms-dev-agent` 处理 + +- 测试相关问题:写单元测试、补回归、接口验证、TDD、验证修复、审查 mock / 断言 + - 统一转给 `wms-test-agent` 处理 + +- 文档相关问题:API 文档、README、`methods/system.json`(已库表化:`wms_api_method_doc` + `script/method-doc-*.cjs` 维护并导出回写)、`docs/*.md`、使用说明 + - 统一转给 `wms-doc-agent` 处理 + +- 不确定该用哪个 agent,或问题横跨数据库 / Redis / 发布 / 代码 / 测试 / 文档 + - 统一转给 `wms-dispatcher-agent` 处理 + +- PowerShell 执行策略限制 + - 使用命令中的 `-ExecutionPolicy Bypass`(仅本次命令生效) + +## 6. 安全约束 + +- **全局安全红线(适用于所有 AI)**:禁止删改处理非测试仓库的数据,包括数据库和缓存;对非测试仓库默认只读;无法确认是否测试仓时,默认按非测试仓处理并拒绝 `UPDATE` / `DELETE` / `INSERT`、`set` / `del` / `hset` / `hdel` / `incr` / `decr` / `expire` 等写操作 +- 数据库相关操作必须使用 `wms-db-agent`,并按该 agent 内的只读/确认流程执行 +- Redis 相关操作必须使用 `wms-redis-agent`,并按该 agent 内的先读后改/回读确认流程执行 +- 发布相关操作必须使用 `wms-deploy-agent`,并坚持仅走 `npm run` 固定入口;禁止读取 `config/deploy.config.local.cjs` +- 开发相关操作必须使用 `wms-dev-agent`,并坚持“先定位、后修改、再验证”的流程 +- 测试相关操作必须使用 `wms-test-agent`,并坚持“先写失败用例、再修复、后跑相关测试并报告 passing 数量”;禁止只测 mock 或给生产代码加 test-only 方法 +- 文档相关操作必须使用 `wms-doc-agent`,并坚持“先核对代码与测试,再更新文档;禁止写入敏感配置”的流程 +- 涉及生产数据时,优先在测试环境验证 + + +## 7. 开发能力移交规则 + +通用开发能力文档已统一移交给 `wms-dev-agent`。 + +适用场景: +- 改代码 / 修 bug / 重构 / 性能优化 +- 定位 `/system` / `/qimen` method 映射关系 +- 排查 `where` 规则、权限映射、分层职责问题 + +执行要求(强制): +- **涉及代码开发的任何问题,必须使用 `wms-dev-agent`** +- 默认 agent 不再在本文件重复维护开发细节 +- 如诉求重点是测试设计、补回归、接口验证、TDD 或验证修复,转给 `wms-test-agent` +- 如需同步 API 文档、`methods/*.json`、`docs/*.md`,转给 `wms-doc-agent` +- 具体目录地图、联动规则统一见:`.github/agents/开发.agent.md` + +## 8. 文档能力移交规则 + +文档相关能力文档已统一移交给 `wms-doc-agent`。 + +适用场景: +- 补 API 文档 / 接口说明 / 错误码 / 示例请求 +- 同步 `methods/system.json` / `methods/qimen.json` +- 更新 `docs/*.md`、`README.md`、`AI_TOOLBOX.md` +- 整理 method 映射说明、接入文档、使用手册 + +执行要求(强制): +- **涉及文档编写或同步的任何问题,必须使用 `wms-doc-agent`** +- 文档必须以代码实现、测试结果和现有 JSON 文档为准,不得凭空编写 +- 默认禁止直接手写 `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. 测试能力移交规则 + +测试相关能力文档已统一移交给 `wms-test-agent`。 + +适用场景: +- 写测试 / 单元测试 / 集成测试 / 补回归 +- 跑接口验证 / 复现 bug / 验证修复 +- 按 TDD 流程推进开发修复 +- 审查 mock / 断言规范与覆盖率范围 + +执行要求(强制): +- **涉及测试设计、回归验证、接口验证、TDD 的任何问题,必须使用 `wms-test-agent`** +- 必须坚持先写失败用例再修复,不允许只测 mock 行为 +- 不得为生产代码添加 test-only 方法或分支 +- 改动后必须跑相关测试并报告 passing 数量 +- 具体命令与测试规范统一见:`.github/agents/测试.agent.md` + +## 10. 发布能力移交规则 + +发布相关能力文档已统一移交给 `wms-deploy-agent`。 + +适用场景: +- 发布生产 / 上线 / deploy +- 回退 / rollback / 指定备份回退 +- 查询线上版本、版本历史 +- 做预检、inspect、smoke、verify、gateway probe +- 排查发布链路、备份、版本记录问题 + +执行要求(强制): +- **涉及发布 / 回退 / 线上验证的任何问题,必须使用 `wms-deploy-agent`** +- 固定入口只允许 `npm run ...`,禁止直接运行底层 `node ./script/deploy-remote.cjs ...` / `rollback-remote.cjs ...` +- AI 禁止读取 `config/deploy.config.local.cjs` +- 具体命令、回退规则、版本管理、安全红线统一见:`.github/agents/发布.agent.md` + +## 11. 开发细节移交说明 + +以下开发细节文档已统一移交给 `wms-dev-agent`: + +- App 能力地图(`app.js`、`app/extend/application.js`) +- Web 用户信息与角色切换测试链路 +- `setting.account` 接口分层约定 +- `where` 参数统一规范 +- `system API` 权限映射规则 + +执行要求(强制): +- **涉及代码开发、接口联动的任何问题,必须使用 `wms-dev-agent`** +- 如需测试设计、补回归、接口验证或验证修复,转给 `wms-test-agent` +- 若涉及文档更新,转给 `wms-doc-agent` +- 具体定位地图、命令与工作流统一见:`.github/agents/开发.agent.md` + +## 16. 通知能力路由(notice / WebHook / 事件注册) + +- 详细能力说明统一沉淀在: + - `docs/notification-webhook-capability.md` + - `docs/notification-event-api.md` +- 工具箱只保留入口与分工,不再重复维护 notice 的字段、payload、重试和示例细节。 +- 若其他 agent 或开发任务遇到“**新功能需要通知**”,按以下路由处理: + 1. **代码接入** → 使用 `wms-dev-agent`:在业务 service 中接入 `ctx.service.systems.notice.send(options)`,并完成事件注册与最小回归验证 + 2. **文档同步** → 使用 `wms-doc-agent`:同步通知能力文档、事件文档及必要的接口说明 +- 当前统一入口:`ctx.service.systems.notice.send(options)` +- 当前代码位置:`app/service/systems/notice/index.js` +- 配置底线:`wms_store.subject_config.max_notice_webhook_count` + - 默认值:`5` + - 合法范围:`0 ~ 5` + - 创建/更新主体与 WebHook 分发时都必须遵守该上限 diff --git a/Apifox/print.json b/Apifox/print.json deleted file mode 100644 index 3081377..0000000 --- a/Apifox/print.json +++ /dev/null @@ -1,143 +0,0 @@ -{ - "openapi": "3.0.1", - "info": { - "title": "打印相关接口", - "description": "print service methods", - "version": "1.0.0" - }, - "paths": { - "/system": { - "post": { - "summary": "打印台相关接口", - "operationId": "printStationOperations", - "description": "根据method参数执行不同的打印台操作", - "parameters": [ - { - "name": "method", - "in": "query", - "description": "调用方法名,如print.getList、print.getItem、print.updateItem、print.del、print.getComputer、print.getComputerPrinter、print.savePrinters", - "required": true, - "schema": { - "type": "string", - "enum": [ - "print.getList", - "print.getItem", - "print.updateItem", - "print.del", - "print.getComputer", - "print.getComputerPrinter", - "print.savePrinters" - ] - } - }, - { - "name": "v", - "in": "query", - "description": "版本号", - "required": false, - "schema": { - "type": "string", - "example": "2.0" - } - }, - { - "name": "timestamp", - "in": "query", - "description": "时间戳", - "required": false, - "schema": { - "type": "string", - "example": "1646908800000" - } - } - ], - "requestBody": { - "required": false, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "page": { "type": "integer", "example": 1 }, - "pageSize": { "type": "integer", "example": 20 }, - "where": { - "type": "object", - "example": { "name": "A台" } - }, - "id": { "type": "integer", "example": 1 }, - "name": { "type": "string", "example": "A台" }, - "computer_id": { "type": "integer", "example": 2 }, - "custom_barcode": { "type": "string", "example": "123456" }, - "ids": { - "type": "array", - "items": { "type": "integer" }, - "example": [1,2] - }, - "default": { "type": "string", "example": "打印机名称" }, - "express": { - "type": "array", - "items": { - "type": "object", - "properties": { - "express_id": { "type": "integer" }, - "name": { "type": "string" } - } - }, - "example": [{ "express_id": 1, "name": "顺丰" }] - }, - "print_station_id": { "type": "integer", "example": 1 } - } - } - } - } - }, - "responses": { - "200": { - "description": "成功响应", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "code": { "type": "integer", "description": "状态码" }, - "message": { "type": "string", "description": "返回信息" }, - "data": { "type": "object", "description": "返回数据" } - } - } - } - } - }, - "400": { - "description": "错误请求", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "code": { "type": "integer" }, - "message": { "type": "string" } - } - } - } - } - }, - "401": { - "description": "未授权" - } - }, - "security": [ - { "bearer": [] } - ] - } - } - }, - "components": { - "securitySchemes": { - "bearer": { - "type": "http", - "scheme": "bearer", - "bearerFormat": "JWT" - } - } - } -} \ No newline at end of file diff --git a/Apifox/test.json b/Apifox/test.json deleted file mode 100644 index 48134e5..0000000 --- a/Apifox/test.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "openapi": "3.0.1", - "info": { - "title": "默认模块", - "description": "", - "version": "1.0.0" - }, - "tags": [], - "paths": { - "/system": { - "post": { - "summary": "未命名接口", - "deprecated": false, - "description": "", - "tags": [], - "parameters": [ - { - "name": "method", - "in": "query", - "description": "", - "required": false, - "example": "user.login", - "schema": { - "type": "string" - } - }, - { - "name": "v", - "in": "query", - "description": "", - "required": false, - "example": "2.0", - "schema": { - "type": "string" - } - }, - { - "name": "timestamp", - "in": "query", - "description": "", - "required": false, - "example": "{{$date.now}}", - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "userName": { - "type": "string" - }, - "passWord": { - "type": "string" - } - }, - "required": [ - "userName", - "passWord" - ] - }, - "example": { - "userName": "夫立伟", - "passWord": "Ut cillum veniam" - } - } - } - }, - "responses": { - "200": { - "description": "", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": {} - } - } - }, - "headers": {} - } - }, - "security": [ - { - "bearer": [] - } - ] - } - } - }, - "components": { - "schemas": {}, - "responses": {}, - "securitySchemes": { - "bearer": { - "type": "http", - "scheme": "bearer" - } - } - }, - "servers": [], - "security": [] -} \ No newline at end of file diff --git a/INBOX_V2_HTTP_TEST_REPORT.md b/INBOX_V2_HTTP_TEST_REPORT.md new file mode 100644 index 0000000..6e0b4d5 --- /dev/null +++ b/INBOX_V2_HTTP_TEST_REPORT.md @@ -0,0 +1,447 @@ +# 站内信 v2 可配置回信引擎 —— HTTP 覆盖测试报告 + +> 生成时间:2026-09-17T14:44:55.082Z | 执行方式:真实 HTTP 链路(POST /warehouse?method=inbox.push) + +## 1. 测试环境 + +| 项 | 值 | +|---|---| +| 服务 | http://127.0.0.1:6060(本地 egg 服务,运行中) | +| 回调接收服务 | http://127.0.0.1:9001/ack(本地 ack 服务,返回 {code:200}) | +| 数据库 | 127.0.0.1:3307/wms(本地库) | +| API 应用 | wms_api_app id=3,app_key=APP2025011514315678,warehouse_id=100000 | +| 原 callback_url | `http://localhost:6061/push` → 测试期间改为本地 ack 服务(**未自动恢复**) | +| 新 v2 测试群 | `httpv2:1789656295082`(首推自动登记后开启 store/after_sales + ai_enabled=1 + template_reply_enabled=1) | +| 新 express 测试群 | `httpv2expr:1789656295082`(express/after_sales,开启 v2) | +| 模块优先测试群 | `httpv2aioff:1789656295082`(ai_enabled=0 + template_reply_enabled=1) | + +## 2. 链路 + +```mermaid +flowchart LR + A[测试脚本] -->|POST /warehouse inbox.push 验签| B[warehouseMethods/inbox.push] + B --> C[receiver.receive 幂等写库 + 自动登记群] + C -->|source_type=api setImmediate| D[processor.handleApiMessage] + D --> E{群校验 ai_enabled / group_type / 历史消息} + E -->|template_reply_enabled=1| F[inbox.v2.rules 可配置引擎] + F --> G[关键词→白名单→取号→callFunction→回复表] + G --> H[writeOutboundReply] + H -->|POST notify.reply| I[本地 ack 服务 9001] + I --> J[push_status=2] +``` + +## 3. 用例结果总览 + +- 总计:**11** 用例,通过:**11**,失败:**0** + +| # | 用例 | 内容 | 结果 | +|---|---|---|---| +| TC01 | 破损建单(新 v2 群) | `破损 SF1234567890123` | ✅ PASS | +| TC02 | 改地址 | `改地址 SF1234567890123` | ✅ PASS | +| TC03 | 换快递(express 取号) | `改快递 SF1234567890123 圆通` | ✅ PASS | +| TC04 | 拦截 | `拦截 SF1234567890123` | ✅ PASS | +| TC05 | 揽收(上门取件) | `上门取件 SF1234567890123` | ✅ PASS | +| TC06 | 取号失败引导语 | `破损` | ✅ PASS | +| TC07 | v2 未命中静默(模块接管) | `今天天气怎么样` | ✅ PASS | +| TC08 | 历史消息静默跳过 | `破损 SF1234567890123` | ✅ PASS | +| TC09 | 幂等(同 requestId 两次推送) | `破损 SF9999999999999` | ✅ PASS | +| TC10 | express 群白名单放行但函数越权拦截(静默) | `破损 SF1234567890123` | ✅ PASS | +| TC11 | 模块优先(ai_enabled=0 但 template_reply_enabled=1) | `破损 SF1234567890123` | ✅ PASS | + +## 4. 用例明细 + +### TC01 破损建单(新 v2 群) ✅ PASS + +- 消息:`破损 SF1234567890123` +- ext_id:`api:APP2025011514315678:httpv2-01-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| 入站消息入库 | ✅ | id=2118 | +| v2 命中轨迹写入 ai_thoughts(function=handleStoreFeedback) | ✅ | [{"round":0,"action":"rule","params":{"keyword":"SF1234567890123","issue_type":"damaged"},"reason":"v2 关键词命中: 破损","function":"handleStoreFeedback","functionResult":{"error":"未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试","success":false}}] | +| 出站回执存在(sys:ack) | ✅ | sys:ack:api:APP2025011514315678:httpv2-01-1789656298793 | +| 出站 push_status=2(回调 200) | ✅ | push_status=2 | +| 本地 ack 服务收到 notify.reply(type=ai) | ✅ | type=ai | +| 出站日志 wms_warehouse_log 记录 notify.reply | ✅ | http_status=200 | +| 无工单时函数返回可见(出站文案非空) | ✅ | 本地无该运单,函数返回文案: 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | + +- 入站消息 id=2118,ai_thoughts: + +```json +[ + { + "round": 0, + "action": "rule", + "params": { + "keyword": "SF1234567890123", + "issue_type": "damaged" + }, + "reason": "v2 关键词命中: 破损", + "function": "handleStoreFeedback", + "functionResult": { + "error": "未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试", + "success": false + } + } +] +``` + +- 出站回执: + +| ext_id | content | push_status | +|---|---|---| +| `sys:ack:api:APP2025011514315678:httpv2-01-1789656298793` | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | 2 | + +- 本地 ack 服务收到 notify.reply:type=ai + +- wms_warehouse_log notify.reply 日志:http_status=200 + +### TC02 改地址 ✅ PASS + +- 消息:`改地址 SF1234567890123` +- ext_id:`api:APP2025011514315678:httpv2-02-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| v2 命中 changeAddr | ✅ | | +| 出站回执存在 | ✅ | push_status=2 | +| 函数已执行(工单或错误文案) | ✅ | \| 未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试 | + +- 入站消息 id=2120,ai_thoughts: + +```json +[ + { + "round": 0, + "action": "rule", + "params": { + "keyword": "SF1234567890123,1234567890123", + "issue_type": "addr" + }, + "reason": "v2 关键词命中: 改地址", + "function": "changeAddr", + "functionResult": { + "error": "未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试", + "success": false + } + } +] +``` + +- 出站回执: + +| ext_id | content | push_status | +|---|---|---| +| `sys:ack:api:APP2025011514315678:httpv2-02-1789656298793` | 未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试 | 2 | + +- 本地 ack 服务收到 notify.reply:type=ai + +- wms_warehouse_log notify.reply 日志:http_status=200 + +### TC03 换快递(express 取号) ✅ PASS + +- 消息:`改快递 SF1234567890123 圆通` +- ext_id:`api:APP2025011514315678:httpv2-03-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| v2 命中 changeExpress | ✅ | | +| 取号含 express=圆通 | ✅ | thoughts 含 express 字段 | +| 出站回执存在 | ✅ | 未找到订单:SF1234567890123、1234567890123 | + +- 入站消息 id=2122,ai_thoughts: + +```json +[ + { + "round": 0, + "action": "rule", + "params": { + "express": "圆通", + "keyword": "SF1234567890123,1234567890123" + }, + "reason": "v2 关键词命中: 改快递", + "function": "changeExpress", + "functionResult": { + "data": { + "changed": 0, + "express": "圆通快递", + "message": "未找到订单:SF1234567890123、1234567890123", + "allocated": 0, + "not_found": 2, + "direct_reply": true, + "not_in_pending": 0 + }, + "success": true + } + } +] +``` + +- 出站回执: + +| ext_id | content | push_status | +|---|---|---| +| `sys:ack:api:APP2025011514315678:httpv2-03-1789656298793` | 未找到订单:SF1234567890123、1234567890123 | 2 | + +- 本地 ack 服务收到 notify.reply:type=ai + +- wms_warehouse_log notify.reply 日志:http_status=200 + +### TC04 拦截 ✅ PASS + +- 消息:`拦截 SF1234567890123` +- ext_id:`api:APP2025011514315678:httpv2-04-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| v2 命中 interceptWaybill | ✅ | | +| 出站回执存在 | ✅ | 请提供运单号 | + +- 入站消息 id=2124,ai_thoughts: + +```json +[ + { + "round": 0, + "action": "rule", + "params": {}, + "reason": "v2 关键词命中: 拦截", + "function": "interceptWaybill", + "functionResult": { + "error": "请提供运单号", + "success": false + } + } +] +``` + +- 出站回执: + +| ext_id | content | push_status | +|---|---|---| +| `sys:ack:api:APP2025011514315678:httpv2-04-1789656298793` | 请提供运单号 | 2 | + +- 本地 ack 服务收到 notify.reply:type=ai + +- wms_warehouse_log notify.reply 日志:http_status=200 + +### TC05 揽收(上门取件) ✅ PASS + +- 消息:`上门取件 SF1234567890123` +- ext_id:`api:APP2025011514315678:httpv2-05-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| v2 命中 requestPickup | ✅ | | +| 出站回执存在 | ✅ | 请提供运单号 | + +- 入站消息 id=2126,ai_thoughts: + +```json +[ + { + "round": 0, + "action": "rule", + "params": {}, + "reason": "v2 关键词命中: 上门取件", + "function": "requestPickup", + "functionResult": { + "error": "请提供运单号", + "success": false + } + } +] +``` + +- 出站回执: + +| ext_id | content | push_status | +|---|---|---| +| `sys:ack:api:APP2025011514315678:httpv2-05-1789656298793` | 请提供运单号 | 2 | + +- 本地 ack 服务收到 notify.reply:type=ai + +- wms_warehouse_log notify.reply 日志:http_status=200 + +### TC06 取号失败引导语 ✅ PASS + +- 消息:`破损` +- ext_id:`api:APP2025011514315678:httpv2-06-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| 出站回执为取号引导语 | ✅ | 请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔) | +| 未建工单(取号失败不调用函数) | ✅ | | + +- 入站消息 id=2128,ai_thoughts: + +```json +[ + { + "round": 0, + "action": "rule", + "params": {}, + "reason": "v2 关键词命中: 破损,取号失败-引导提示", + "function": "handleStoreFeedback", + "functionResult": null + } +] +``` + +- 出站回执: + +| ext_id | content | push_status | +|---|---|---| +| `sys:ack:api:APP2025011514315678:httpv2-06-1789656298793` | 请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔) | 2 | + +- 本地 ack 服务收到 notify.reply:type=ai + +- wms_warehouse_log notify.reply 日志:http_status=200 + +### TC07 v2 未命中静默(模块接管) ✅ PASS + +- 消息:`今天天气怎么样` +- ext_id:`api:APP2025011514315678:httpv2-07-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| 无出站回执(静默) | ✅ | | +| 无 ai_thoughts 轨迹 | ✅ | 空 | +| 无新工单 | ✅ | 0 条 | + +- 入站消息 id=2130,ai_thoughts: + +```json +null +``` + +### TC08 历史消息静默跳过 ✅ PASS + +- 消息:`破损 SF1234567890123` +- ext_id:`api:APP2025011514315678:httpv2-08-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| 入站仍入库 | ✅ | id=2131 | +| 无出站回执(静默跳过) | ✅ | | +| 无新工单 | ✅ | 0 条 | + +- 入站消息 id=2131,ai_thoughts: + +```json +null +``` + +### TC09 幂等(同 requestId 两次推送) ✅ PASS + +- 消息:`破损 SF9999999999999` +- ext_id:`api:APP2025011514315678:httpv2-09-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| 两次推送均返回成功(flag=success) | ✅ | 第一次 flag=success,第二次 flag=success | +| 入站仅 1 条 | ✅ | 1 -> 1 | +| 出站仅 1 条(不重复处理) | ✅ | 出站条数 1 -> 1 | + +- 入站消息 id=2132,ai_thoughts: + +```json +[ + { + "round": 0, + "action": "rule", + "params": { + "keyword": "SF9999999999999", + "issue_type": "damaged" + }, + "reason": "v2 关键词命中: 破损", + "function": "handleStoreFeedback", + "functionResult": { + "error": "未找到当前货主在仓库中的运单「SF9999999999999」,请核实单号后重试", + "success": false + } + } +] +``` + +- 出站回执: + +| ext_id | content | push_status | +|---|---|---| +| `sys:ack:api:APP2025011514315678:httpv2-09-1789656298793` | 未找到当前货主在仓库中的运单「SF9999999999999」,请核实单号后重试 | 2 | + +- 本地 ack 服务收到 notify.reply:type=ai + +- wms_warehouse_log notify.reply 日志:http_status=200 + +### TC10 express 群白名单放行但函数越权拦截(静默) ✅ PASS + +- 消息:`破损 SF1234567890123` +- ext_id:`api:APP2025011514315678:httpv2-10-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| 入站消息入库 | ✅ | id=2134 | +| 无出站回执(静默) | ✅ | | +| 白名单行存在(express/after_sales 允许 damage 子类型) | ✅ | 行数=1 | +| 函数越权拦截(handleStoreFeedback 仅 store 群可用 → 无轨迹) | ✅ | 无轨迹 | + +- 入站消息 id=2134,ai_thoughts: + +```json +null +``` + +### TC11 模块优先(ai_enabled=0 但 template_reply_enabled=1) ✅ PASS + +- 消息:`破损 SF1234567890123` +- ext_id:`api:APP2025011514315678:httpv2-11-1789656298793` + +| 校验项 | 结果 | 详情 | +|---|---|---| +| 不依赖 ai_enabled,仍走 v2(轨迹含 v2 关键词命中) | ✅ | [{"round":0,"action":"rule","params":{"keyword":"SF1234567890123","issue_type":"damaged"},"reason":"v2 关键词命中: 破损","function":"handleStoreFeedback","functionResult":{"error":"未找到当前货主在仓库中的运单「SF123456789 | +| 出站回执存在 | ✅ | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | + +- 入站消息 id=2135,ai_thoughts: + +```json +[ + { + "round": 0, + "action": "rule", + "params": { + "keyword": "SF1234567890123", + "issue_type": "damaged" + }, + "reason": "v2 关键词命中: 破损", + "function": "handleStoreFeedback", + "functionResult": { + "error": "未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试", + "success": false + } + } +] +``` + +- 出站回执: + +| ext_id | content | push_status | +|---|---|---| +| `sys:ack:api:APP2025011514315678:httpv2-11-1789656298793` | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | 2 | + +- 本地 ack 服务收到 notify.reply:type=ai + +- wms_warehouse_log notify.reply 日志:http_status=200 + +## 5. 说明与后续 + +1. 测试产生的入站/出站消息、工单等数据**已保留**(未自动清理),可直接在库中核对。 +2. `wms_api_app` id=3 的 callback_url 测试期间被改为本地 ack 服务,如需恢复: + +```sql +UPDATE wms_api_app SET callback_url = 'http://localhost:6061/push' WHERE id = 3; +``` + +3. 测试脚本与明细数据位于 `temp/inbox_v2_http_test/`(`run_http_test.js`、`ack_server.js`、`report.json`)。 + diff --git a/INBOX_V2_TEST_GUIDE.md b/INBOX_V2_TEST_GUIDE.md new file mode 100644 index 0000000..2860b13 --- /dev/null +++ b/INBOX_V2_TEST_GUIDE.md @@ -0,0 +1,333 @@ +# 站内信 v2 可配置回信引擎 —— 端到端测试流程指南 + +> 适用对象:开发/测试人员。覆盖消息 HTTP 推送进入、群类型创建、回传数据接收、 +> 校验准则、涉及表的状态变化与特殊流程边界。 +> 所有示例基于本地环境(服务 `127.0.0.1:6060`,MySQL `127.0.0.1:3307/wms`), +> 生产环境仅做只读核对,禁止写操作。 + +## 测试范围(重要) + +- **只测 v2 链路**:`template_reply_enabled=1` 的群走 `inbox.v2.rules` 可配置引擎; +- **v1 链路不需要测试**:processor 分叉为 `else` 分支原样保留,v1 规则表 + (`inbox/rules.js` 静态规则)与 AI 兜底逻辑零改动,无需回归; +- 自动化验证已覆盖:`test/inbox/v2_rules_engine.test.js`(引擎 9 用例)、 + `test/inbox/v2_processor_fork.test.js`(分叉 3 用例)、 + `test/inbox/v2_function_sync.test.js`(函数同步 4 用例)。 + +--- + +## 0. 总体链路 + +```mermaid +flowchart LR + A[外部适配器] -->|POST /warehouse inbox.push 验签| B[warehouseMethods/inbox.push] + B --> C[receiver.receive 幂等写库
wms_inbox_message inbound] + C -->|自动登记群| D[wms_inbox_group] + C -->|source_type=api 异步| E[processor.handleApiMessage] + E --> F{群校验: group_type / ai_enabled} + F -->|未通过| G[静默跳过] + F -->|通过| H{规则引擎} + H -->|v1| I[rules.handle] + H -->|template_reply_enabled=1| J[inbox.v2.rules 引擎
模块接管]| + I --> K[callFunction 代码越权校验] + K --> L[writeOutboundReply 出站回执] + L -->|POST notify.reply| M[回调 URL
wms_api_app.callback_url] + L --> N[wms_inbox_message outbound + wms_warehouse_log] +``` + +--- + +## 1. 消息 HTTP 推送进入(inbox.push) + +### 1.1 入口 + +``` +POST http://127.0.0.1:6060/warehouse?method=inbox.push&v=1.0×tamp={秒级时间戳}&app_key={appKey}&sign={sign} +Content-Type: application/json +``` + +- `warehouse_id` 由验签后的 `wms_api_app` 上下文注入,**禁止外部传入**; +- `ext_id` 由服务端组合:`api:{appKey}:{requestId}`,用于幂等去重。 + +### 1.2 签名算法(app/lib/api_sign.js) + +``` +bodySign = md5(stableStringify(body)) // 对象键按字母序排序后序列化 +canonical = query 参数按 key 字母序拼接 "k=v&k2=v2"(排除 sign/signature) +sign = md5(canonical + self_app_secret + bodySign) +``` + +- `self_app_secret` 来自 `wms_api_app.self_app_secret`(按 `app_key` 查询); +- `app_key` 对应仓库的 API 应用需存在且已启用。 + +### 1.3 请求体字段 + +| 字段 | 必填 | 说明 | +|---|---|---| +| `requestId` | ✅ | 来源请求唯一 ID,与 appKey 组成 `ext_id` | +| `content` | - | 消息正文(触发规则引擎的输入) | +| `groupId` | - | 外部群 ID,用于关联群与货主路由 | +| `groupName` | - | 群名称(首次推送会自动登记群) | +| `userId` / `userName` | - | 外部用户 ID / 名称 | +| `parentId` | - | 关联消息 ID(回信时形成对话链) | +| `targetType` | - | `im` / `api` / `webhook`,默认 `im` | +| `extData` | - | 透传 JSON,WMS 不解析,回信原样带回 | +| `sendTime` | - | 消息原始发送时间(毫秒/秒/ISO),用于历史消息过滤 | +| `flags` | - | `{skipAi:true}` 显式跳过 AI;`{send_time:ms}` 等价 sendTime | + +### 1.4 响应与幂等 + +- 成功:`{code:0, message:'ok', data:{ok:true, id, ext_id}}`; +- 相同 `ext_id` 重复推送:直接返回已存在记录,**不重复入库、不重复触发处理**。 + +--- + +## 2. 创建特定群类型 + +### 2.1 自动登记(首次推送即建群) + +首次推送含 `groupName` 的消息时,`receiver.receive` 自动在 `wms_inbox_group` +创建群记录(按 `group_id + warehouse_id` 唯一): +- `ai_enabled=0`、`group_type/sub_type=NULL`、`store_id` 取自绑定的货主; +- 群名变化只更新名称,不重复建群。 + +### 2.2 配置群类型(管理接口) + +``` +POST http://127.0.0.1:6060/system?method=inbox.group.update&v=1.0×tamp={ts} +Authorization: Bearer {登录 token} +Content-Type: application/json + +{ "id": {群记录ID}, "groupType": "store", "subType": "after_sales", + "storeId": 1000000, "aiEnabled": 1 } +``` + +- `groupType`:`store`(货主)/ `warehouse`(仓库)/ `express`(快递); +- `subType`(群子类型): + - store:`after_sales` / `finance` / `receiving` + - warehouse:`receiving` / `production` / `stockout` / `finance` / `all` / `customer_service` / `exception` + - express:`pickup` / `after_sales` +- `aiEnabled=1` 才会进入规则引擎(第 5 步开关); +- `inbox.group.reset`:清空群类型配置并重置 AI 开关。 + +### 2.3 v2 回信开关(开启即接管链路) + +v2 引擎开关 `template_reply_enabled`(管理接口未上线前用 SQL 设置): + +```sql +UPDATE wms_inbox_group SET template_reply_enabled = 1 +WHERE group_id = '{测试群ID}' AND warehouse_id = {仓库ID}; +``` + +- `template_reply_enabled=1` 的群在第 6 步自动走 `inbox.v2.rules.handle`(已接入); +- **模块优先语义**:`template_reply_enabled=1` 即为模块总开关,开启时不依赖 `ai_enabled` + (两个开关同开时也走 v2 不走 v1/AI;`ai_enabled` 只约束未开启模板开关的群); +- **模块接管模式**:v2 开启群的未命中消息直接静默,不走 v1 规则、不走 AI 兜底; +- 群信息每条消息实时查库(`_loadGroupInfo` 不缓存),SQL 改动对下一条消息立即生效; +- v2 配置数据(关键词/白名单/函数/取号/回复)有 300s 缓存,改动后需 + `ctx.service.inbox.v2.config.invalidate(warehouseId)` 或等 TTL 过期。 + +--- + +## 3. 接收回传数据 + +### 3.1 出站回执方向(WMS → 外部) + +规则处理完成后,`processor.writeOutboundReply` 向 `wms_api_app.callback_url` +POST 回执(`notify.reply`): + +``` +POST {callback_url}?app_key={k}&method=notify.reply×tamp={秒}&sign={md5(appSecret + timestamp + bodyJson)} +``` + +回执 body 关键字段: +- `data.type`:`ai`(规则/AI 自动回复)、`system`、`bind`、`balance`、`error`; +- `data.content`:回复内容;`data.ext_data`:入站 `extData` 原样带回; +- `data.ext_id`:出站消息记录 ID;`data.group_id` / `user_id` / `user_name`:目标群与用户。 + +### 3.2 测试接收方法 + +方式 A(推荐):临时把本地库 `wms_api_app.callback_url` 指向本地 HTTP 接收服务, +观察收到的 `notify.reply` 报文并返回 `{code:200}`: + +```sql +UPDATE wms_api_app SET callback_url = 'http://127.0.0.1:9001/ack' +WHERE app_key = '{测试app_key}'; +``` + +方式 B(不落回执服务):直接核对库表: +- `wms_inbox_message`:`direction='outbound'`、`ext_id='sys:ack:{入站ext_id}'`; +- `wms_warehouse_log`:`method='notify.reply'` 的出站通知日志(含 http_status/body/result)。 + +### 3.3 推送状态核对 + +| push_status | 含义 | +|---|---| +| 0/1 | 未推送 / 待推送 | +| 2 | 回调返回 HTTP 200 且 `code=200` → 推送成功 | +| 3 | 回调非 200 / 无回调地址 / 异常 → 推送失败(可 `inbox.message.retry` 重推) | + +--- + +## 4. 校验准则 + +| # | 校验项 | 准则 | +|---|---|---| +| 1 | 幂等 | 相同 `ext_id` 只入库一次、只处理一次 | +| 2 | 群类型 | `group_type` 为空 → 跳过处理(未绑定任务类型) | +| 3 | AI 开关 | `ai_enabled != 1` → 跳过(快递群默认 0,需手动开) | +| 4 | 历史消息 | `send_time` 距今 > 10 分钟(`config.inbox.historyMessageMaxAgeMs` 可调)→ 跳过,不回复不建工单 | +| 5 | 屏蔽 | 屏蔽用户/群 → 跳过处理(`blockUser` 函数 / `wms_inbox_block`) | +| 6 | 关键词命中 | 长词优先;命中后先过防误判守卫(如"拦截" vs "查物流") | +| 7 | 函数越权 | `callFunction` 按群活跃分组校验,越权返回错误(DB 配置只做可见性,代码是最终权威) | +| 8 | 取号失败 | 子类型关联了取号规则但未提取到值 → 回复引导语(`no_number_hint` → target 专属 → 默认),**不调用函数** | +| 9 | 回复决策 | 回复完全由回复配置控制:`is_reply=1` 且模板渲染非空 → 回复;`is_reply=0` → 静默(函数仍执行);无配置/模板渲染为空 → **默认不回复**(函数已执行,仅不出回执) | +| 10 | 快递群 | express 群仅执行函数,**不回信** | +| 11 | 出站回执 | 回执 `ext_id='sys:ack:{入站ext_id}'` 唯一,重复处理不重复出站 | +| 12 | 缓存 | v2 配置缓存 `inbox:v2:cfg:{warehouseId}` TTL 300s;配置变更后必须 `invalidate`,否则 5 分钟内不生效 | + +--- + +## 5. 涉及表的状态变化 + +### 5.1 消息链路表 + +| 表 | 变化 | +|---|---| +| `wms_inbox_message` | 入站:`direction='inbound'`、`push_status=0`;规则命中后写 `ai_thoughts`(轨迹 JSON)。出站:`direction='outbound'`、`ext_id='sys:ack:{ext_id}'`、`parent_id=入站ID`;推送后 `push_status=2/3`、`push_response`、`pushed_at` | +| `wms_inbox_group` | 首次推送自动登记(`ai_enabled=0`);`group.update` 写 `group_type/sub_type/store_id/ai_enabled`;群名变化只更新名称 | +| `wms_warehouse_log` | 每次出站 `notify.reply` 写一条(`method/url/http_status/body/result/use_time`) | + +### 5.2 业务函数表(v1 与 v2 共用函数) + +| 表 | 变化(以函数为准) | +|---|---| +| `wms_after_sale` | `interceptWaybill`(type=order, sub_type=intercept, status=pending)、`changeAddr`(change_address/rejected/urge)、`handleStoreFeedback`(mis_shipment/damage/extra_item/missing_item)、`weishoudao`(verify_delivery)、`requestPickup`(pickup)等创建售后工单 | +| `wms_order_express` | 拦截成功后写 `intercept_status='requested'` 与 `intercept_time`(值域见 `intercept-status-values` 约定) | +| `wms_order_delivery_{warehouseId}` | `createPostnum` 分配运单号后写 `logistics_*`/`post_status`;`changeExpress` 修改快递分配 | + +### 5.3 v2 配置表(全部只读,引擎启动时一次性同步函数表) + +| 表 | 变化 | +|---|---| +| `wms_after_sale_function` | 启动时 `functionSync.sync()` 幂等 upsert(只增改不删、不覆盖 `is_enabled/sort_order`) | +| `wms_after_sale_type` / `wms_after_sale_sub_type` | 系统级 + 仓库级(`warehouse_id NULL` 全局可见) | +| `wms_after_sale_keyword` | 关键词 → 子类型映射(长词优先、`sort_order` 同长时生效) | +| `wms_after_sale_sub_type_group` | 子类型 × 群类型 × 群子类型白名单(`uk(sub_type_id, group_type, sub_group)`) | +| `wms_after_sale_sub_type_function` | 子类型 → 处理函数(`function_id` + `sort_order`) | +| `wms_after_sale_sub_type_rule` + `wms_inbox_number_rule` | 子类型 → 取号规则(`target/regexp/sort_order`) | +| `wms_after_sale_reply` | 仓库级(`warehouse_id` 非空)覆盖系统级;`is_reply=0` 静默、`no_number_hint` 引导语、`create_work_order=0` 函数照常执行但内部跳过工单登记 | + +--- + +## 6. 特殊流程边界 + +### 6.1 开关与分叉边界 + +- **AI 开关**:`ai_enabled != 1` 一律跳过(安全默认,快递群默认关闭); + 例外:`template_reply_enabled=1` 的群不依赖 AI 开关(模块优先); +- **群未绑定**:`group_type` 为空跳过;`store` 群无 `store_id` 归属时主分组不激活(`resolveActiveGroups`); +- **v1/v2 分叉**(已接入):`template_reply_enabled=1` 走 `inbox.v2.rules.handle`, + 否则走 `inbox.rules.handle`(v1 分支原逻辑零改动); +- **模块接管**:v2 开启群的未命中消息直接静默 return,不回落到 v1 规则与 AI 兜底。 + +### 6.2 v2 引擎边界(已接入 processor) + +- **关键词命中**:长词优先;同长多个子类型均按序尝试; +- **白名单过滤**:`(group_type, sub_group)` 双维度;群 `sub_type` 为空时**只按主类型放行** + (随后由 `callFunction` groups 校验兜底收紧); +- **取号正则安全三件套**:保存时校验 + 长度 ≤ 500 + 每次 `new RegExp`(非法正则跳过并告警); +- **入参组装**:`waybill_no/order_no/source_order_codes/receiving_no/entry_order_no/stockout_no` + 合并去重 join 逗号 → `keyword`;`express_name→express`; + 子类型转译 `issue_type`(damage→damaged、change_address→addr、rejected→return、urge→urge 等); +- **多函数子类型**:按 `sort_order` 依次执行,任一失败立即返回失败文案; +- **回复优先级**:回复表(仓库级 > 系统级);模板渲染为空或无配置时**默认不回复**(函数照常执行); + `{back_text}` 占位符由 help 函数提供,业务函数无该内容时渲染为空 → 不回复; +- **缓存失效**:管理接口增删改配置后必须调用 `ctx.service.inbox.v2.config.invalidate(warehouseId)`; + 启动时**不清** v2 缓存(防雪崩)。 + +### 6.3 消息边界 + +- **历史/补推消息**:`sendTime` 超阈值 → 静默跳过(不回复、不建工单); +- **屏蔽**:屏蔽用户(`wms_inbox_block`)/ 屏蔽群(`is_blocked=1`)→ 跳过处理; +- **express 群**:函数照常执行(如 `handleExpressFeedback`),但**不回信**; +- **幂等回执**:`sys:ack:{ext_id}` 保证同一入站消息只产生一条出站回执; +- **多条回复**:引擎返回数组时逐条出站,`ext_id` 追加 `:r0/:r1` 避免唯一键冲突; +- **渠道校正**:回执 `ext_data.source` 按群 ID 格式校正(`@chatroom→wx`、纯数字→qiwe),防止投递到错误渠道。 + +### 6.4 数据层已知状态(2026-09-17 已修复) + +1. ✅ `change_carrier`(换快递)已补 `express_name` 取号规则关联(迁移 `20260917130000`), + "改快递 {单号} 圆通" 可完整组装 `keyword + express`; +2. ✅ 关键词表已补 `intercept`(拦截/退回/召回/追回/取消快递)与 `pickup`(揽收/上门取件/取件/退货取件)共 9 条; +3. ⚠️ `wrong_sku`/`quality_issue` 无群白名单关联行(预期内,引擎白名单过滤后跳过)。 + +--- + +## 7. v2 链路测试步骤(本地) + +> v1 链路不需要测试(分叉 else 分支原样保留)。以下步骤专测 v2。 + +### 7.1 前置:准备好一个 v2 开启的测试群 + +```sql +-- 1) 确保群存在(可由首次推送自动登记,或手动插入) +-- 2) 配置群类型 + 开关(管理接口未上线前用 SQL) +UPDATE wms_inbox_group +SET group_type='store', sub_type='after_sales', + store_id={货主ID}, ai_enabled=1, template_reply_enabled=1 +WHERE group_id='{测试群ID}' AND warehouse_id={仓库ID}; +``` + +v2 链路只需三个条件(模板开关优先,不依赖 AI 开关):`group_type` 非空 → +`template_reply_enabled=1` → 消息内容命中 v2 关键词;`ai_enabled` 开或关都不影响 v2。 + +### 7.2 推送消息并核对(HTTP 入口) + +```powershell +# 1) 推送入站消息:POST /warehouse?method=inbox.push(签名见 1.2) +# body: {"requestId":"v2-001","content":"破损 SF1234567890123", +# "groupId":"{测试群ID}","groupName":"{群名}", +# "userId":"u1","userName":"测试用户"} +# 2) 核对入站: +# SELECT id, direction, ai_thoughts FROM wms_inbox_message +# WHERE ext_id='api:{appKey}:v2-001'; +# → direction='inbound',ai_thoughts 含 v2 轨迹(action=rule、function=handleStoreFeedback) +# 3) 核对出站回执: +# SELECT id, ext_id, direction, content, push_status FROM wms_inbox_message +# WHERE ext_id='sys:ack:api:{appKey}:v2-001'; +# → direction='outbound'、push_status=2(回调可用时)/3(未配置回调) +# 4) 核对工单: +# SELECT after_sale_no, type, sub_type, status FROM wms_after_sale +# WHERE warehouse_id={仓库ID} ORDER BY id DESC LIMIT 5; +# → sub_type='damage'、status='pending' +# 5) 核对出站日志: +# SELECT method, http_status, result FROM wms_warehouse_log +# WHERE warehouse_id={仓库ID} AND method='notify.reply' ORDER BY id DESC LIMIT 5; +``` + +### 7.3 推荐用例集(全部走 v2 群) + +| 用例 | 消息 | 预期 | +|---|---|---| +| 破损建单 | `破损 SF1234567890123` | `handleStoreFeedback(issue_type=damaged)` + damage 工单 + 回执 | +| 改地址 | `改地址 SF1234567890123` | `changeAddr(issue_type=addr)` + change_address 工单 | +| 换快递 | `改快递 SF1234567890123 圆通` | `changeExpress(keyword=..., express=圆通)` | +| 拦截 | `拦截 SF1234567890123` | `interceptWaybill` + intercept 工单(`wms_order_express.intercept_status='requested'`) | +| 揽收 | `上门取件 SF1234567890123` | `requestPickup` + pickup 工单 | +| 取号失败 | `破损` | 回复引导语,**不建工单** | +| v2 未命中 | `今天天气怎么样` | 模块接管静默:无函数调用、无回执记录 | +| 模块优先 | 同破损内容 + `ai_enabled=0`(`template_reply_enabled=1` 不变) | 仍走 v2 并回执(不依赖 AI 开关) | +| 历史消息 | 同破损内容 + `sendTime` 为 30 分钟前 | 静默跳过:无回执、无工单 | + +> 所有用例的群必须 `template_reply_enabled=1`;**不测** `template_reply_enabled=0` 的 v1 场景。 + +### 7.4 边界补充 + +- 快递群(express)命中 v2:函数照常执行,但**不回信**(复用现有回执逻辑); +- 相同 `requestId` 重复推送:幂等,只处理一次; +- 回复表 `is_reply=0`:函数执行但静默(可临时插行验证,见 `wms_after_sale_reply`)。 + +> 补充:egg 测试环境运行 DB 相关测试必须 +> `$env:DISPATCH_FACTORY_TEST_MYSQL='1'; $env:EGG_SERVER_ENV='local'; npx egg-bin test {文件}` +> (默认 unittest 环境禁用 sequelize 且 `config.default.js` 指向生产库,禁止裸跑)。 diff --git a/README.md b/README.md index f28ea49..9e5b84b 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,259 @@ -# qimen +# 奇门WMS(qimen-wms) -奇门wms +基于 Egg.js 的仓储管理系统(WMS),支持支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。 -## QuickStart +## 文档导航 - +- 项目协作工具箱:`AI_TOOLBOX.md` +- Method 路由映射说明:`AI_METHOD_ROUTING.md` +- system 接口文档源:`methods/system.json` +- qimen 接口文档源:`methods/qimen.json` +- 配置驱动报表配置说明:`docs/report-config-guide.md` +- 日报:`day.log` -see [egg docs][egg] for more detail. +## 项目目录结构 -### Development +```text +├── app/ # 业务主目录(controller, service, model, router 等) +│ ├── controller/ # 控制器(API、文档、模板、认证等) +│ ├── service/ # 业务服务(system/qimen/print 等) +│ ├── model/ # Sequelize 模型 +│ ├── dict/ # 业务字典 +│ ├── view/ # 前端模板 +│ └── router.js # 路由定义 +├── config/ # 配置(poloapi、redis、数据库等) +├── database/ # 迁移与数据库配置 +├── methods/ # 接口文档数据源(JSON) +├── script/ # 调试与文档生成脚本 +├── logs/ # 日志 +├── run/ # 运行时/元数据 +├── test/ # 单元测试 +├── app.js # 应用入口 +├── package.json # 依赖与脚本 +└── README.md # 项目说明 +``` + +## 文档结构 + +- `README.md`:项目入口文档,提供整体说明与规范入口。 +- `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。 +- `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 +- `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 +- `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 +- `docs/report-config-guide.md`:配置驱动通用报表(wms_report_definition 三段 JSON 配置、内置查询器口径)与货主定时投递说明。 +- `day.log`:每日工作留痕。 + +## 快速开始 ```bash -npm i +npm install npm run dev -open http://localhost:7001/ ``` -### Deploy +默认访问地址:`http://localhost:6060/` + +## 运行命令 + +- `npm run dev`:本地开发 +- `npm start`:启动生产服务 +- `npm stop`:停止生产服务 +- `npm run lint`:代码风格检查 +- `npm test`:单元测试 + +## 主要依赖 + +- egg.js 3.x +- egg-sequelize、egg-mysql、egg-redis +- egg-jwt、egg-cors、egg-view-ejs +- fast-xml-parser、cos-js-sdk-v5、qiniu-js、soap + +## 接口入口 + +- `GET /`:健康检查 +- `POST /qimen`:奇门接口 +- `POST /system`:system 统一入口 +- `POST /api/v1`:旧版 API +- `POST /api/v2`:新版 API +- `GET /template/xml/:id`:打印模板 +- `GET|POST /auth/printSetting/:code`:打印台设置 + +## API 文档与调试 + +- `GET /api/docs`:默认文档页 +- `GET /api/docs/:docName`:按文档名查看(如 `system`、`qimen`) +- `GET /api/docs/:docName/raw`:查看原始 JSON + +文档页能力: + +- 分组折叠与 method 搜索 +- 全局 Authorization 设置 +- 全局业务 Header(如 `platform`、`project`)设置 +- 方法级在线 POST 调试 + +## 接口文档联动维护(强制) + +当出现以下任一变更时,必须同步更新 `methods` 下对应文档: + +1. 新增接口 method +2. 修改接口参数(新增/删除/重命名/必填变化) +3. 修改公共 Header(如 `platform`、`project`、`Authorization`) +4. 修改响应结构或错误码 + +建议流程: + +1. 先完成代码改动(controller/service/model) +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. 先执行: + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run +``` + +5. 确认无误后执行正式写入,再补充自动提取无法覆盖的信息(description/response/errors/枚举约束) + +## 配置说明 + +- 主要配置文件在 `config/`(如 `config.default.js`、`config.local.js`、`poloapi.js`) +- 数据库、Redis、平台配置在对应配置文件中维护 +- 敏感信息不要提交到仓库 + +## 发布与运维(deploy / 证书同步 / 看门狗) + +### 部署根布局(生产 `deployRoot` 默认 `/www/wwwroot/qimen`) + +```text +/ +├── current.md # 当前活跃版本(v1 | v2) +├── nginx-upstream.conf # 发布时改写:proxy_pass 指向活跃版本端口(v1:6061 / v2:6062) +├── front.conf # 站点内容片段(root / 伪静态),运维维护、脚本绝不覆盖 +├── .ssl/ # 证书目录(cron 写入 {store_id}_{domain}.pem|.key,私钥 0600) +├── nginx_config/ # nginx server 块目录(cron 写入 {domain}-.conf,如 web.wms.gztbyc.com-1.conf) +├── script/ +│ ├── warehouse-cert-sync.sh # 证书同步薄包装(cron 每分钟入口) +│ ├── warehouse-cert-sync.cjs # 证书同步主脚本(读库→写证书/conf→nginx -t+reload→回写状态) +│ ├── warehouse-cert-sync.config.prod.json # 生产运行时配置(服务器自管:仅首次放置,永不覆盖) +│ └── qimen-watchdog.sh # 接口服务看门狗(/etc/cron.d 每 5 分钟) +├── database/config.js # 上述脚本自用的 DB 配置(install 时上传) +├── .deploy/ # 发布状态 / 暂存 / 备份 +└── v1/ v2/ # 版本实例目录(发布与回退只清理这里) +``` + +### 目录约定(**硬约定**:只随 `deployRoot` 变,不随版本切换变) + +| 用途 | 路径 | 配置来源 | +|------|------|----------| +| 证书 | `/.ssl` | `script/warehouse-cert-sync.config.prod.json` → `"certDir": "./.ssl"`(开发 `D:/wms/.ssl`) | +| nginx server 块 | `/nginx_config` | 同上 → `"confDir": "./nginx_config"`(开发 `D:/wms/nginx_config`) | +| 站点内容片段 | `upstreamInclude` 指向的片段文件(生产 `/front.conf`) | 同上 → `"upstreamInclude"`(**绝对路径**,**运维维护**) | + +- 相对路径按 **cwd=部署根** 解析(薄包装先 `cd `),目录不存在时脚本自动递归创建。 +- 这两个目录都在**部署根一级**(非版本目录):发布/回退只清理 `v1|v2`,不会触碰它们。 +- **server 块命名含 `-`**:文件名为 `-.conf`(suffix 仅当域名清洗后与原名不一致时出现),版本键 `ver` 在运行时配置里(`"ver": "1"`),可用 CLI `--ver` / 环境变量 `CERT_SYNC_VER` 临时覆盖;nginx 主配置 `include /nginx_config/*.conf;` 与新命名兼容,无需改 nginx。 +- **每轮声明式对账 + 自愈**:cron 每分钟把库内「期望集合」(domain 非空且已验证)逐行与磁盘核对,证书 / 私钥 / server 块缺失、被改坏或**命名过期**(旧的无后缀命名、旧 `-`、手工改名)都会自动重建 / 清理后 reload;内容一致时零写入、零 reload。不再只依赖后台“重新上传证书”触发同步。 +- **失败态(`sync_status=2`)同样收敛,不是「终态豁免」**:失败行也参与文件层对账——盘上证书 / 私钥 / server 块缺失或与库不一致就按库内容重建,本轮 `nginx -t`/reload 通过后自动回写 `sync_status=1`(日志 `[RECOVER]` / `[RECOVERED]`)。所以「手工删掉 `.ssl`、`nginx_config`」「早期遗留的失败行」都能自动恢复,**无需人工重传证书**。唯一需要人工的情形:库内 `cert_pem`/`cert_key` 为空或非法(无内容可写,日志 `[BLOCKED]`,需在后台上传证书)。 +- **nginx 全局失败不写行失败**:`nginx -t` / reload 失败属环境问题(主配置、片段 include、目录),此时待同步行保持 `sync_status=0`、已同步行保持 `1`、失败行保持 `2`,只落 `last_sync_error` 并下一轮自动重试,避免「运维修好配置后行却卡死在 2、必须人工重传证书」。 +- **下线 = 配置差集(不需要两阶段切换的额外机制)**:期望集合 = 库内「已配置 + 已验证 + 证书就绪」的行,且**每个仓库只取一条**(同一 `store_id` 多行时按 id 最小者生效,其余行 WARN 后忽略)。`nginx_config/`、`.ssl/` 中属于本系统命名规则、但域名已不在期望集合内的文件会被删除并 reload(日志 `DELETE … 原因=orphan`)。所以**换域名不需要人工下线**:旧域名在提升后已不是该行的 `domain`,下一轮即被清掉;`retired_domain` / `retired_at` 仅作应用侧审计留痕,脚本不读取、不写回。 +- **证书没配置就不写配置**:`cert_pem` / `cert_key` 为空的行**不生成** server 块,也不作为文件保留依据(其遗留 conf / 证书会被差集回收——conf 引用不存在的证书会让 `nginx -t` 全局失败),行状态回写 `sync_status=0` 待同步;证书非空但非法(或域名形态非法)才记行级失败(`sync_status=2`)。 +- **ver 轮转步骤**:改服务器 `warehouse-cert-sync.config.prod.json` 的 `"ver"`(或临时 `--ver`)→ 下一轮 cron 自动生成新命名 `-<新ver>.conf`、删除旧命名并 reload;无需清空库、无需重传证书(证书文件名不含 ver,不受影响)。 +- **站点内容单一片段**:生成的 server 块 = 证书骨架 + `include ;`;站点内容(root / 伪静态 或 反代)统一由 `upstreamInclude` 指向的片段文件提供(生产 `/www/wwwroot/qimen/front.conf`),**由运维维护、脚本绝不覆盖**;前端个性化在运行时由配置接口按域名完成,nginx 侧无需按域名区分站点内容。 + - ⚠️ **`upstreamInclude` 必须写绝对路径,且片段文件必须先存在**:nginx 解析 `include` 相对路径的基准是 **nginx prefix**(宝塔为 `/www/server/nginx/conf`),**不是脚本 cwd(部署根)**;写相对路径会让生成的 server 块 include 到不存在的文件 → `nginx -t` 失败 → 整轮变更回滚(连本轮写入的证书一起被当孤儿回收)。脚本启动即校验,不满足直接 `exit 1`(致命退出、不写盘、不改库)。 +- **改名/搬迁必须同步三处**:① nginx 主配置的 `include /nginx_config/*.conf;`;② 服务器上的 `warehouse-cert-sync.config.prod.json`;③ 库表 `wms_warehouse_front_config.cert_path/key_path`(触发一次重同步即可刷新)。 +- 安全:`.ssl/` 与 `nginx_config/` 已在 `.gitignore` 忽略,且列入发布默认排除(`deploy-lib.cjs` 的 `DEFAULT_EXCLUDE_PATHS`),私钥不会进仓库或发布包。 + +### 定时任务 + +| 任务 | 载体 | 频率 | 入口与日志 | +|------|------|------|-----------| +| 证书/站点配置同步 | root crontab(**宝塔「计划任务」里看不到**,它是直接写入 crontab 的裸命令) | 每分钟(`flock` 锁 `/var/lock/warehouse-cert-sync.lock`) | `/script/warehouse-cert-sync.sh` → `/var/log/warehouse-cert-sync.log` | +| 接口服务看门狗 | `/etc/cron.d/qimen-watchdog`(**刻意不放 root crontab**:宝塔面板会整体重写 root crontab) | 每 5 分钟 | `/script/qimen-watchdog.sh` → `/www/wwwlogs/wms/qimen-watchdog.log` | + +### 运维命令 ```bash -npm start -npm stop +npm run deploy:precheck / deploy:authcheck / deploy:inspect / deploy:smoke / deploy:verify +npm run deploy:version / deploy:version:history / deploy:cleanup-backups +npm run deploy # 发布(= deploy:prod);npm run rollback # 回退 +npm run deploy:cert-sync:install / npm run deploy:cert-sync:uninstall +npm run deploy:watchdog:install / npm run deploy:watchdog:uninstall ``` -### npm scripts +- **部署配置**:`config/deploy.config.local.cjs`(**本地文件、已被 `.gitignore` 忽略**;模板 `config/deploy.config.example.cjs`)。键:`host / port / username / privateKeyPath / deployRoot / sharedDirs / preserveDirs / keepBackups / preDeployCommands / postDeployCommands / healthCheckUrl / deployIncludePaths / deployExcludePaths / sshOptions`;缺省值在 `script/deploy-lib.cjs`。查看归一化后的生效配置: + ```bash + node -e "console.log(JSON.stringify(require('./script/deploy-lib.cjs').loadDeployConfig('production'),null,2))" + ``` +- **证书同步运行时配置**:`script/warehouse-cert-sync.config.prod.json`(生产)/ `.dev.json`(开发)。生产那份是**服务器自管**(`deploy:cert-sync:install` 仅首次放置,之后永不覆盖)——改生产运行参数请在**服务器上**直接改它,改本地仓库无效。 +- **安装位置**:`deploy:cert-sync:install` 与 `deploy:watchdog:install` 都装到 `/script/`;覆盖前会留 `.prev-<时间戳>` 备份,历史根目录副本会被一次性挪成 `<名>.legacy-<时间戳>`。 +- **卸载**(`deploy:cert-sync:uninstall`):先备份再删除——备份到服务器 `/tmp/wms-cert-sync-uninstall-<时间戳>/`(`cp -a` 保留权限/时间),删除包装脚本、主脚本、双环境配置、`database/config.js`、历史位置与 `.prev-*`/`.legacy-*` 备份、crontab 中 `warehouse-cert-sync` 行;支持 `--dry-run` 只打印计划。**不删**证书与生成的 server 块(nginx 仍在 include,删了会立断 443,由运维自行决定)、不删 `/var/log/warehouse-cert-sync.log`(默认保留作排查线索)、不碰任何 watchdog 相关文件/任务。 +- **卸载(watchdog)**(`deploy:watchdog:uninstall [--dry-run]`):备份到 `/tmp/qimen-watchdog-uninstall-<时间戳>/` 后**注销调度**——删除 `/etc/cron.d/qimen-watchdog`,并清理 root crontab 中残留的 `qimen-watchdog` 行(历史手工安装可能留过,双跑会并发 kill/start 同一实例);再删除服务器副本 `/script/qimen-watchdog.sh`(含 `.prev-*` / `.legacy-*` 与历史根目录副本)。**不删** `/www/wwwlogs/wms/qimen-watchdog.log`(留作排查线索)、锁文件与接口服务进程;`deploy:watchdog:install` 会先只读打印一份目标机环境快照。 +- **运行期手动排查**:仍可直接执行服务器上的 `/script/warehouse-cert-sync.sh --dry-run`(主脚本 CLI 不变:`--cleanup-only --dry-run` / `--cleanup-only` / `--env production`)。 -- Use `npm run lint` to check code style. -- Use `npm test` to run unit test. +## 功能模块 -[egg]: https://eggjs.org +- 多快递平台对接(快手/PolyAPI 等) +- 订单管理与履约 +- 打印与打印台管理 +- 仓库/门店管理 +- 权限与角色管理 +- Excel 表格生成、导入与解析 + +## Excel 服务能力 + +系统已提供服务类:`app/service/systems/excel.js`,可通过 `ctx.service.systems.excel` 调用。 + +支持能力: + +- 生成单 sheet / 多 sheet Excel +- 按 `columns + rows` 输出表格 +- 输出 `Buffer`、写入本地文件、直接作为下载响应返回 +- 解析 `.xlsx` / `.xls` 文件内容为 JSON +- 自动处理空表头、重复表头 + +常用方法: + +- `generateBuffer(options)`:生成 Excel 二进制内容 +- `writeFile(filePath, options)`:写入本地文件 +- `sendFile({ filename, sheets })`:HTTP 下载输出 +- `parseBuffer(buffer, options)`:解析上传后的文件流 +- `parseFile(filePath, options)`:解析本地 Excel 文件 + +示例: + +```js +const buffer = await ctx.service.systems.excel.generateBuffer({ + sheets: [ + { + name: '入库单', + columns: [ + { header: '单号', key: 'order_no', width: 20 }, + { header: '货主', key: 'owner_name', width: 18 }, + ], + rows: [ + { order_no: 'RK20260404001', owner_name: '测试货主' }, + ], + }, + ], +}); + +const parsed = await ctx.service.systems.excel.parseFile('D:/tmp/demo.xlsx'); +``` + +## 常见问题 + +- 启动端口默认 6060,可在配置中调整 +- 数据库/Redis 连接失败优先检查 `config/config.local.js` +- 接口路由映射可查阅 `AI_METHOD_ROUTING.md` + +## 日报维护 + +- 日报统一记录在 `day.log` +- 每次更新日报内容时,需同步更新 `day.log` + +## 参考 + +- Egg.js 官方文档:https://v3.eggjs.org/ diff --git a/app.js b/app.js index b48fb1a..d45750e 100644 --- a/app.js +++ b/app.js @@ -1,82 +1,79 @@ // app.js const path = require('path'); +const LocalFileWriter = require('./app/lib/file_writer'); +const QimenClient = require('./app/lib/qimen_client'); -const businessDict = require('./app/dict/businessDict.js'); - -// 直接导出函数,而不是类 +/** + * 挂载应用级扩展能力。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {void} + */ module.exports = app => { // 设置全局应用根目录 global.APP_ROOT = path.resolve(__dirname, './'); - app.appRoot = APP_ROOT; - // ========== 挂载字典到 app ========== - app.businessDict = businessDict; - - // 添加字典工具方法 - app.getBusinessTypeName = code => { - const dict = app.businessDict.BUSINESS_TYPE || {}; - for (const key in dict) { - if (dict[key].code === code) { - return dict[key].name; - } - } - return code; - }; - - app.getOperationCodeName = code => { - return app.businessDict.OPERATION_CODE?.[code] || code; - }; - app.getPlatformName = code => { - return app.businessDict.PLATFORM_CODE?.[code] || code; - }; - - app.getExternalLogTypeName = type => { - return app.businessDict.EXTERNAL_LOG_TYPE?.[type] || type; - }; - - app.logger.info('✅ 业务字典已挂载到 app'); + app.appRoot = global.APP_ROOT; + app.fileWriter = new LocalFileWriter(app); + app.qimenClient = new QimenClient(app); + app.logger.info('✅ Application 扩展能力已加载'); + app.logger.info('✅ fileWriter 已挂载到 app.fileWriter'); + app.logger.info('✅ qimenClient 已挂载到 app.qimenClient'); // 初始化工厂 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('✅ 工厂类初始化完成'); } catch (error) { - app.logger.error('❌ 工厂类初始化失败:', error); } + + // 启动初检:异步为已有分表的仓库确保订单 id 序列表存在且水位正确。 + // 只做建表 + 水位抬升,不迁移数据(位置指针回填由 backfill-order-id-location 脚本负责); + // 异步执行不阻塞启动,失败仅告警,后续建单/迁移触发时还会再次 ensure。 + setImmediate(() => { + const factory = app.model && app.model.OrderDeliveryFactory; + if (factory && typeof factory.ensureAllLocationSequenceTables === 'function') { + factory.ensureAllLocationSequenceTables().catch(error => { + app.logger.warn(`[启动初检] 序列表初检异常: ${error && error.message ? error.message : error}`); + }); + } + }); + + // 售后函数表启动同步(v2 可配置回信引擎): + // 把 inbox functions 代码注册表幂等 upsert 到 wms_after_sale_function, + // 只增改不删、不覆盖管理端 is_enabled/sort_order;失败仅告警,不影响启动。 + try { + const ctx = app.createAnonymousContext(); + if (ctx && ctx.service && ctx.service.inbox + && ctx.service.inbox.v2 && ctx.service.inbox.v2.functionSync) { + const stats = await ctx.service.inbox.v2.functionSync.sync(); + app.logger.info(`✅ 售后函数表同步完成: ${JSON.stringify(stats)}`); + } + } catch (error) { + app.logger.warn(`⚠️ 售后函数表同步失败(不影响启动): ${error && error.message ? error.message : 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); }); - // 扩展 Date 原型 - Date.prototype.format = function(formatStr = 'YYYY-MM-DD HH:mm:ss') { - const year = this.getFullYear(); - const month = String(this.getMonth() + 1).padStart(2, '0'); - const day = String(this.getDate()).padStart(2, '0'); - const hours = String(this.getHours()).padStart(2, '0'); - const minutes = String(this.getMinutes()).padStart(2, '0'); - const seconds = String(this.getSeconds()).padStart(2, '0'); - - return formatStr - .replace('YYYY', year) - .replace('MM', month) - .replace('DD', day) - .replace('HH', hours) - .replace('mm', minutes) - .replace('ss', seconds); - }; }; diff --git a/app/controller/api_v2.js b/app/controller/api_v2.js deleted file mode 100644 index 3f7a33e..0000000 --- a/app/controller/api_v2.js +++ /dev/null @@ -1,169 +0,0 @@ -const { Controller } = require('egg'); - -class ApiV2Controller extends Controller { - async index() { - const { ctx, service } = this; - ctx.query_count = 1; - const startTime = Date.now(); - const logData = { - method: '', - v: '', - url: ctx.request.href, - created_at: new Date(), - body: '', - headers: JSON.stringify(ctx.headers), - result: '', - use_time: 0, - auth: '', - store_id: null, - }; - - try { - const getParams = ctx.query; - logData.method = getParams.method || ''; - logData.v = getParams.v || ''; - // 验证必要参数 - if (!service.system.validateParams(getParams)) { - const errorMsg = '参数缺失或错误'; - const response = this.errorResponse(errorMsg, 'json'); - logData.result = response; - service.system.saveLog(logData, startTime); - ctx.body = response; - ctx.type = 'application/json'; - return; - } - const authHeader = ctx.headers.authorization; - ctx.device = ctx.headers.device; - ctx.project = ctx.headers.project; - - // 处理method参数 - const method = getParams.method; - const methods = method.split('.'); - const actionName = methods.pop(); - const className = methods - .map((item, index) => - (index === methods.length - 1 ? item : item) - ) - .join('.'); - - // 获取JSON数据 - let jsonData = ''; - if (ctx.request.rawBody) { - jsonData = ctx.request.rawBody; - } else { - jsonData = await new Promise((resolve, reject) => { - let data = ''; - ctx.req.on('data', chunk => { - data += chunk; - }); - ctx.req.on('end', () => { - resolve(data); - }); - ctx.req.on('error', reject); - }); - } - - jsonData = jsonData ? String(jsonData) : ''; - logData.body = jsonData; - if (!jsonData || jsonData.trim() === '') { - throw new Error('json数据为空'); - } - try { - jsonData = JSON.parse(jsonData); - } catch (e) { - throw new Error('json数据解析错误'); - } - - // 调用扁平 dispatcher 服务 - const { isLog, result } = await service.dispatcher.invoke( - getParams.method, - jsonData, - authHeader, - ctx - ); - logData.result = typeof result === 'string' ? result : JSON.stringify(result); - if (ctx.user) { - logData.auth = JSON.stringify(ctx.user); - logData.store_id = ctx.user.store_id; - } - // 保存原来的日志逻辑仍然通过 system.saveLog - if (isLog) { - service.system.saveLog(logData, startTime); - } - if (result.status && result.status !== 200) { - // propagate failure message - ctx.body = result.message ? { message: result.message } : result.data; - } else { - ctx.body = result.data; - } - ctx.type = 'application/json'; - ctx.status = result.status || 200; - } catch (error) { - ctx.status = 500; - console.log(error); - const response = this.errorResponse('接口错误: ' + error.message, 'json'); - logData.result = typeof response === 'string' ? response : JSON.stringify(response); - service.system.saveLog(logData, startTime); - ctx.body = response; - ctx.type = 'application/json'; - } - } - - validateParams(params) { - const required = [ 'method', 'v', 'format', 'timestamp' ]; - - for (const field of required) { - if (!params[field]) { - return false; - } - } - - if (typeof params.method !== 'string' || !params.method.includes('.')) { - return false; - } - - return true; - } - - errorResponse(message, format = 'json') { - const timestamp = Math.floor(Date.now() / 1000); - - if (format.toLowerCase() === 'xml') { - return ` - - failure - 0 - ${this.escapeXml(message)} -`; - } - - return { - flag: false, - message, - code: 0, - timestamp, - }; - } - - escapeXml(unsafe) { - if (!unsafe) return ''; - return unsafe.replace(/[<>&'\"]/g, c => { - switch (c) { - case '<': - return '<'; - case '>': - return '>'; - case '&': - return '&'; - case "'": - return '''; - case '"': - return '"'; - default: - return c; - } - }); - } -} - -module.exports = ApiV2Controller; diff --git a/app/controller/auth.js b/app/controller/auth.js index a7c51ab..8c270af 100644 --- a/app/controller/auth.js +++ b/app/controller/auth.js @@ -4,115 +4,115 @@ const Controller = require('egg').Controller; class AuthController extends Controller { - async printerSetting() { - const { ctx } = this; - const redis = this.app.redis; - if (ctx.method === 'GET') { - const code = ctx.params.code || ''; - if (!code) { - ctx.body = { error: '缺少code参数' }; - return; - } - const bindValue = await redis.get('printer').get(`bind:${code}`); - if (!bindValue) { - ctx.body = { error: '无效code或未绑定' }; - return; - } - await redis.get('printer').setex(`binding:${code}`, 300, bindValue); - await ctx.render('printer_setting.html', { - title: '打印台设置', - code, - bindValue, - }); - } else if (ctx.method === 'POST') { - const { code, printer, warehouse } = ctx.request.body; - if (!code || !printer || !warehouse) { - ctx.body = { success: false, error: '参数缺失' }; - return; - } - // 获取临时binding:code - const bindingValue = await redis.get('printer').get(`binding:${code}`); - if (!bindingValue) { - ctx.body = { success: false, error: '超时或未绑定' }; - return; - } - // 反序列化bindingValue - let bindingValueObj = bindingValue; - try { - bindingValueObj = JSON.parse(bindingValue); - } catch (e) { - bindingValueObj = bindingValue; - } - // 使用 Store model 校验仓库id - const Store = ctx.model.Store; - const warehouseInfo = await Store.findOne({ where: { id: warehouse } }); - console.log('warehouseInfo:', warehouseInfo); - if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { - ctx.body = { success: false, error: '仓库id校验失败' }; - return; - } - // 查找仓库id下是否有重名的电脑 - const PrintComputer = ctx.model.PrintComputer; - let computerId = null; - const existComputer = await PrintComputer.findOne({ where: { warehouse_id: warehouse, name: printer } }); - if (existComputer) { - if (existComputer.status === 1) { - ctx.body = { success: false, error: '该仓库下打印台名称已存在且可用' }; - return; - } else { - computerId = existComputer.id; - } - } else { - // 创建新打印电脑 - console.log('创建新打印电脑:', { warehouse_id: warehouse, name: printer, status: 0 }); - const newComputer = await PrintComputer.create({ warehouse_id: warehouse, name: printer, status: 0 }); - console.log('newComputer:', newComputer); - computerId = newComputer.id; - } - // 调用打印服务 /auth/bind,使用egg内置curl - const printServiceUrl = ctx.app.config.printService.url; - let printServiceResult = null; - try { - const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { - method: 'POST', - contentType: 'json', - data: { code, printer, warehouse, roomId: bindingValueObj.uniqueId, computerId }, - dataType: 'json', - }); - printServiceResult = res.data; - } catch (err) { - console.log('调用打印服务失败:', err); - printServiceResult = { success: false, error: '打印服务通讯失败' }; - } - console.log('printServiceResult:', printServiceResult); - // 判断打印服务返回结果 - if (printServiceResult && printServiceResult.status === 'fail') { - ctx.body = { - success: false, - msg: printServiceResult.message || '打印服务失败', - code, - printer, - warehouse, - bindingValue: bindingValueObj, - printServiceResult - }; - return; - } - console.log('printServiceResult:', printServiceResult); - ctx.body = { - success: true, - msg: '参数已接收', - code, - printer, - warehouse, - bindingValue: bindingValueObj, - computerId, - printServiceResult - }; - } else { - ctx.body = { msg: '不支持的请求方法' }; + async printerSetting() { + const { ctx } = this; + const redis = this.app.redis; + if (ctx.method === 'GET') { + const code = ctx.params.code || ''; + if (!code) { + ctx.body = { error: '缺少code参数' }; + return; + } + const bindValue = await redis.get('printer').get(`bind:${code}`); + if (!bindValue) { + ctx.body = { error: '无效code或未绑定' }; + return; + } + await redis.get('printer').setex(`binding:${code}`, 300, bindValue); + await ctx.render('printer_setting.html', { + title: '打印台设置', + code, + bindValue, + }); + } else if (ctx.method === 'POST') { + const { code, printer, warehouse } = ctx.request.body; + if (!code || !printer || !warehouse) { + ctx.body = { success: false, error: '参数缺失' }; + return; + } + // 获取临时binding:code + const bindingValue = await redis.get('printer').get(`binding:${code}`); + if (!bindingValue) { + ctx.body = { success: false, error: '超时或未绑定' }; + return; + } + // 反序列化bindingValue + let bindingValueObj = bindingValue; + try { + bindingValueObj = JSON.parse(bindingValue); + } catch (e) { + bindingValueObj = bindingValue; + } + // 使用 Store model 校验仓库id + const Store = ctx.model.Store; + const warehouseInfo = await Store.findOne({ where: { id: warehouse } }); + console.log('warehouseInfo:', warehouseInfo); + if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { + ctx.body = { success: false, error: '仓库id校验失败' }; + return; + } + // 查找仓库id下是否有重名的电脑 + const PrintComputer = ctx.model.PrintComputer; + let computerId = null; + const existComputer = await PrintComputer.findOne({ where: { warehouse_id: warehouse, name: printer } }); + if (existComputer) { + if (existComputer.status === 1) { + ctx.body = { success: false, error: '该仓库下打印台名称已存在且可用' }; + return; } + computerId = existComputer.id; + + } else { + // 创建新打印电脑 + console.log('创建新打印电脑:', { warehouse_id: warehouse, name: printer, status: 0 }); + const newComputer = await PrintComputer.create({ warehouse_id: warehouse, name: printer, status: 0 }); + console.log('newComputer:', newComputer); + computerId = newComputer.id; + } + // 调用打印服务 /auth/bind,使用egg内置curl + const printServiceUrl = ctx.app.config.printService.url; + let printServiceResult = null; + try { + const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { + method: 'POST', + contentType: 'json', + data: { code, printer, warehouse, roomId: bindingValueObj.uniqueId, computerId }, + dataType: 'json', + }); + printServiceResult = res.data; + } catch (err) { + console.log('调用打印服务失败:', err); + printServiceResult = { success: false, error: '打印服务通讯失败' }; + } + console.log('printServiceResult:', printServiceResult); + // 判断打印服务返回结果 + if (printServiceResult && printServiceResult.status === 'fail') { + ctx.body = { + success: false, + msg: printServiceResult.message || '打印服务失败', + code, + printer, + warehouse, + bindingValue: bindingValueObj, + printServiceResult, + }; + return; + } + console.log('printServiceResult:', printServiceResult); + ctx.body = { + success: true, + msg: '参数已接收', + code, + printer, + warehouse, + bindingValue: bindingValueObj, + computerId, + printServiceResult, + }; + } else { + ctx.body = { msg: '不支持的请求方法' }; } + } } -module.exports = AuthController; \ No newline at end of file +module.exports = AuthController; diff --git a/app/controller/docs.js b/app/controller/docs.js new file mode 100644 index 0000000..f5c5d27 --- /dev/null +++ b/app/controller/docs.js @@ -0,0 +1,2302 @@ +const { + Controller, +} = require('egg'); +const fs = require('fs').promises; +const path = require('path'); + +function escapeHtml(value) { + return String(value || '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .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 : []; +} + +function slugify(value) { + return String(value || '') + .toLowerCase() + .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-') + .replace(/(^-|-$)/g, ''); +} + +function isValidDocName(docName) { + return /^[a-zA-Z0-9_-]+$/.test(docName || ''); +} + +function getDocFilePath(app, docName) { + return path.join(app.baseDir, 'methods', `${docName}.json`); +} + +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 => ({ + groupName: group.groupName || group.module || 'Default', + module: group.module || '', + list: toArray(group.list), + })); + } + + if (docData && Array.isArray(docData.endpoints)) { + return [{ + groupName: docData.groupName || 'Endpoints', + module: docData.module || '', + list: docData.endpoints, + }]; + } + + return []; +} + +/** + * 解析文档对应的统一入口路径,优先使用文档内声明的 http.path。 + * 只要 http.path 是非空字符串就原样返回,允许 `{ApiApp.callback_url}` + * 这类出站回调占位符原样展示;http.path 为 null/空串时回落到模块默认入口。 + * @param {object} docData 文档 JSON 数据。 + * @return {string} 统一入口路径。 + */ +function resolveDocEntryPath(docData) { + const httpPath = String(docData?.http?.path || '').trim(); + if (httpPath) { + return httpPath; + } + + if (docData?.module === 'qimen') { + return '/qimen'; + } + + if (docData?.module === 'gateway') { + return '/internal/v1/gateway'; + } + + return '/system'; +} + +/** + * 渲染 seeAlso 交叉引用链接。 + * @param {Array<{name: string, path: string, description: string}>|undefined} seeAlso 交叉引用列表。 + * @return {string} HTML 片段。 + */ +function renderSeeAlsoLinks(seeAlso) { + if (!Array.isArray(seeAlso) || seeAlso.length === 0) return ''; + const links = seeAlso.map(item => { + const href = `/api/docs/${(item.path || '').replace(/^\/?methods\//, '').replace(/\.json$/, '')}`; + return `${escapeHtml(item.name)}`; + }).join(''); + return `
    关联文档:${links}
    `; +} + +/** + * 渲染键值表格。 + * @param {Array} items 数据项列表。 + * @param {{ name: string, type: string, required: string, description: string }} keyMap 字段映射。 + * @return {string} 表格行 HTML。 + */ +function renderKeyValueRows(items, keyMap) { + if (!items.length) { + return '暂无数据'; + } + + return items.map(item => { + return ` + ${escapeHtml(item[keyMap.name] || '')} + ${escapeHtml(item[keyMap.type] || '')} + ${item[keyMap.required] ? '是' : '否'} + ${renderTextWithWindowTags(item[keyMap.description] || '')} + `; + }).join(''); +} + +/** + * 渲染全局 Header 控件区域。 + * @param {Array} globalHeaders 全局 Header 定义。 + * @return {string} HTML 片段。 + */ +function renderGlobalHeadersControls(globalHeaders) { + const headers = toArray(globalHeaders); + if (!headers.length) { + return '

    当前文档未定义额外全局 Header

    '; + } + + return `
    ${headers.map(item => { + const name = item.name || ''; + const type = item.type || 'string'; + const required = !!item.required; + const description = item.description || ''; + const options = toArray(item.list); + + const field = options.length + ? `` + : ``; + + 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); + const response = toArray(item.response); + const errors = toArray(item.errors); + const methodName = item.method || item.name || 'unknown'; + const description = item.description || ''; + const isQimen = moduleName === 'qimen'; + const isOpenapi = moduleName === 'openapi'; + const isWarehouse = moduleName === 'warehouse' || moduleName === 'warehouse_notify'; + const isExternalApi = isOpenapi || isWarehouse; + const queryHint = isQimen + ? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000' + : isExternalApi + ? `app_key=&method=${methodName}&v=1.0×tamp=1700000000` + : `method=${methodName}&v=1.0×tamp=1700000000`; + const queryLabel = isExternalApi ? 'Query 参数(自动生成)' : 'Query 参数'; + const queryReadonlyAttr = isExternalApi ? ' readonly data-auto-generated="true" aria-label="自动生成"' : ''; + + return `
    +
    +
    +

    ${escapeHtml(methodName)}

    +

    ${renderTextWithWindowTags(description)}

    +
    +
    + 入口: ${escapeHtml(entryPath)} + 鉴权: ${item.isNeedAuth ? '是' : '否'} + 登录: ${item.isNeedLogin ? '是' : '否'} +
    +
    + +
    + Headers (${headers.length}) + + + ${renderKeyValueRows(headers, { + name: 'name', + type: 'type', + required: 'required', + description: 'description', + })} +
    名称类型必填说明
    +
    + +
    + Params (${params.length}) + + + ${renderKeyValueRows(params, { + name: 'name', + type: 'type', + required: 'required', + description: 'description', + })} +
    名称类型必填说明
    +
    + +
    + Response (${response.length}) + + + ${renderKeyValueRows(response, { + name: 'name', + type: 'type', + required: 'required', + description: 'description', + })} +
    名称类型必填说明
    +
    + +
    + Errors (${errors.length}) + + + ${renderKeyValueRows(errors, { + name: 'code', + type: 'type', + required: 'required', + description: 'message', + })} +
    名称类型必填说明
    +
    + + ${moduleName === 'warehouse_notify' ? `
    + 模拟推送 +
    + + + + + + + + +
    + + 模拟 WMS 向 notify_url 推送通知,sign 在浏览器端 MD5 计算 +
    +
    点击发送后显示响应
    +
    +
    ` : `
    + 在线调试 +
    + + + + ${isExternalApi ? ` + + + ` : ''} + + + + +
    + + ${item.isNeedLogin ? '该接口需要登录,未设置 Token 将阻止请求' : '该接口无需登录,可不设置 Token 直接调试'} +
    + +
    点击发送后显示响应
    +
    +
    `} +
    `; +} + +/** + * 渲染 API 文档页面。 + * @param {{ docName: string, docData: object, groups: Array, docs: Array, entryPath: string }} options 渲染参数。 + * @return {string} HTML 文档。 + */ +function renderHtmlPage({ + docName, + docData, + groups, + docs, + entryPath, +}) { + const isOpenapi = docData.module === 'openapi'; + const isOpenapiCallback = docData.module === 'openapi_callback'; + const isWarehouse = docData.module === 'warehouse' || docData.module === 'warehouse_notify'; + const isExternalApi = isOpenapi || isOpenapiCallback || isWarehouse; + const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); + const globalHeaders = toArray(docData.headers); + const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); + const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`; + const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`; + const navHtml = isExternalApi ? '' : docs.filter(name => name !== 'openapi' && name !== 'warehouse' && name !== 'warehouse_notify').map(name => { + const activeClass = name === docName ? 'active' : ''; + return `${escapeHtml(name)}`; + }).join(''); + + const sidebarHtml = groups.map((group, index) => { + const list = toArray(group.list); + const groupKey = slugify(group.module || group.groupName || `group-${index}`) || `group-${index}`; + const methodsHtml = list.map(item => { + const methodName = item.method || item.name || 'unknown'; + const desc = item.description || ''; + return ``; + }).join(''); + + return ``; + }).join(''); + + const groupHtml = groups.map(group => { + const list = toArray(group.list); + const groupKey = slugify(group.module || group.groupName) || 'group'; + const cards = list.map(item => renderMethodCard(item, entryPath, docData.module)).join(''); + return `
    +

    ${escapeHtml(group.groupName)} ${escapeHtml(group.module || '')}

    + ${cards || '

    该分组暂无方法定义

    '} +
    `; + }).join(''); + + return ` + + + + + ${escapeHtml(docName)} API 文档 + + + +
    +
    +

    ${escapeHtml(docData.module || docName)} API 文档

    +
    + 说明: ${escapeHtml(docData.description || '无')} + 版本: ${escapeHtml(docData.version || 'N/A')} + 更新: ${escapeHtml(docData.updatedAt || 'N/A')} + 方法数: ${methodsCount} + 统一入口: ${escapeHtml(entryPath)} + ${renderSeeAlsoLinks(docData.seeAlso)} +
    +
    + ${navHtml} + 查看变更记录 + 查看 JSON +
    + ${isExternalApi ? '' : `
    +

    全局 Authorization

    +
    + + +
    +

    设置后会自动注入所有“在线调试”请求头,保存在浏览器本地。

    +

    全局业务 Header

    + ${globalHeadersControls} +

    来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。

    +
    `} + ${isExternalApi ? '' : `
    +

    文档资源

    +
    + ${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')} + ${renderWindowElement('打开原文 JSON', rawUrl, 'doc-resource-link')} + + +
    +
    点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。
    +
    `} + ${isOpenapi || isWarehouse ? (docData.module === 'warehouse_notify' ? `
    +

    请求方式

    +
    POST {notify_url}?app_key={app_key}&method={方法名}&timestamp={时间戳}&sign={签名}
    +Content-Type: application/json
    +
    +{
    +  "code": 200,
    +  "data": { ... }
    +}
    + +

    签名算法(MD5)

    +
    sign = MD5(self_app_secret + timestamp + bodyJson).toLowerCase()
    +
    +其中:
    +  self_app_secret = 平台分配的密钥
    +  timestamp = Unix 秒级时间戳
    +  bodyJson = JSON.stringify(请求体)
    +
    +示例(假设 self_app_secret=abc123,请求体={"code":200,"data":{...}}):
    +  bodyJson = {"code":200,"data":{...}}
    +  timestamp = 1700000000
    +  signText = abc1231700000000{"code":200,"data":{...}}
    +  sign = md5(signText).toLowerCase() = ...
    + +

    注意事项(外部系统接收方)

    +
      +
    • 通知由 WMS 主动推送到您配置的 notify_url,外部系统接收并返回 HTTP 200即可
    • +
    • 根据 query 中的 method 字段路由到不同处理逻辑(notify.ping / notify.reply)
    • +
    • 根据 data.type 区分消息类别(ai / bind / balance / error)
    • +
    • 验签时从 query 取 sign,本地计算 MD5(self_app_secret + timestamp + bodyJson) 比对
    • +
    • 时间戳 timestamp 为 Unix 秒级时间戳,校验 ±10 分钟时效
    • +
    • 签名结果为 32 位小写十六进制字符串
    • +
    • 接收成功返回 {"code":200},非 200 或 HTTP 状态码非 200 视为推送失败
    • +
    • WMS 推送超时 10 秒,失败不重试,仅记录日志
    • +
    +
    ` : `
    +

    请求方式

    +
    POST ${isOpenapi ? '/openapi' : '/warehouse'}?method={方法名}&v=1.0×tamp={时间戳}&app_key={app_key}&sign={签名}
    +Content-Type: application/json
    +
    +{请求体 JSON}
    + +

    签名算法(MD5)

    +
    参与签名字符串 = canonicalQuery + self_app_secret + bodySign
    +最终签名 sign = md5(参与签名字符串).toLowerCase()
    +
    +其中:
    +  canonicalQuery = 将 query 参数(排除 sign/signature)按 key 字母序升序排列,
    +                   拼接为 key1=value1&key2=value2 格式。
    +                   参数值序列化规则:undefined/null → 空字符串,
    +                   对象类型 → stableStringify 序列化,其他 → String(value)。
    +  bodySign = md5(stableStringify(请求体))
    +  stableStringify = 递归排序对象 key 的稳定序列化:
    +                   - 对普通对象,按 key 字母序递归序列化每个字段
    +                   - 对数组,按顺序递归序列化每个元素
    +                   - 对非普通对象(Date 等),使用 JSON.stringify
    +                   - undefined 返回空字符串,null 返回 "null"
    +  self_app_secret = 平台分配的密钥
    +
    +示例(假设 self_app_secret=abc123,请求体={"id":1}):
    +  query: app_key=myapp&method=index.ping&timestamp=1700000000&v=1.0
    +  canonicalQuery = app_key=myapp&method=index.ping&timestamp=1700000000&v=1.0
    +  stableStringify({"id":1}) = {"id":1}
    +  bodySign = md5({"id":1}) = 0a5b3e...
    +  signText = app_key=myapp&method=index.ping&timestamp=1700000000&v=1.0abc1230a5b3e...
    +  sign = md5(signText) = ...
    + +

    注意事项

    +
      +
    • method 格式为 模块.方法,如 index.ping
    • +
    • app_key / self_app_secret 由仓库申请配置,请联系仓库管理员获取
    • +
    • 请求体必须为合法 JSON,空 body 传 {}
    • +
    • 时间戳 timestamp 为 Unix 秒级时间戳(数字类型)
    • +
    • 时间戳 timestamp 时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),超时返回 400
    • +
    • 签名结果为 32 位小写十六进制字符串
    • +
    + ${isOpenapi ? `

    + → 回调测试工具 + (模拟接收回调通知,验证回调链路) +

    +

    + → 出站回调文档 + (WMS → 外部的回调事件定义,共 5 个) +

    ` : ''} +
    `) : ''} +
    + +
    + + +
    + ${groupHtml || '

    暂无可展示的方法定义

    '} +
    +
    +
    + + +`; +} + +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 { + const docs = await this.getDocNames(); + if (!docs.length) { + ctx.status = 404; + ctx.body = { + code: 404, + message: 'methods 目录下没有可用的 JSON 文档', + }; + return; + } + + const fallback = docs.includes('system') ? 'system' : docs[0]; + await this.renderDoc(fallback); + } catch (error) { + ctx.status = 500; + ctx.body = { + code: 500, + message: '读取文档失败', + error: error.message, + }; + } + } + + async api() { + await this.list(); + } + + /** + * 渲染 OpenAPI 文档独立页面。 + * @return {Promise} 无返回值。 + */ + async openapi() { + await this.renderDoc('openapi'); + } + + /** + * 渲染 OpenAPI 出站回调文档独立页面。 + * @return {Promise} 无返回值。 + */ + async openapiCallbackEvents() { + await this.renderDoc('openapi_callback'); + } + + /** + * 渲染仓库开放 API 文档独立页面。 + * @return {Promise} 无返回值。 + */ + async warehouse() { + await this.renderDoc('warehouse'); + } + + async detail() { + const { ctx } = this; + const docName = ctx.params.docName; + await this.renderDoc(docName); + } + + async raw() { + const { ctx } = this; + const docName = ctx.params.docName; + + if (!isValidDocName(docName)) { + ctx.status = 400; + ctx.body = { code: 400, message: '无效文档名' }; + return; + } + + const filePath = getDocFilePath(this.app, docName); + + try { + const content = await fs.readFile(filePath, 'utf8'); + ctx.type = 'application/json; charset=utf-8'; + ctx.body = content; + } catch (error) { + ctx.status = 404; + ctx.body = { + code: 404, + message: `未找到文档: ${docName}`, + }; + } + } + + async changes() { + const { ctx } = this; + const docName = ctx.params.docName; + + if (!isValidDocName(docName)) { + ctx.status = 400; + ctx.body = { code: 400, message: '无效文档名' }; + return; + } + + const filePath = getDocChangesFilePath(this.app, docName); + + try { + const content = await fs.readFile(filePath, 'utf8'); + ctx.type = 'application/json; charset=utf-8'; + ctx.body = toArray(JSON.parse(content)); + } catch (error) { + if (error.code === 'ENOENT') { + ctx.type = 'application/json; charset=utf-8'; + ctx.body = []; + return; + } + + ctx.status = 500; + ctx.body = { + code: 500, + message: `读取变更记录失败: ${docName}`, + error: error.message, + }; + } + } + + async getDocNames() { + const docsDir = path.join(this.app.baseDir, 'methods'); + const entries = await fs.readdir(docsDir, { withFileTypes: true }); + + return entries + .filter(entry => entry.isFile() && entry.name.endsWith('.json')) + .map(entry => entry.name.replace(/\.json$/i, '')) + .sort(); + } + + /** + * 渲染指定 API 文档详情页。 + * @param {string} docName 文档名称(不含 .json 后缀)。 + * @return {Promise} 无返回值。 + */ + async renderDoc(docName) { + const { ctx, app } = this; + + if (!isValidDocName(docName)) { + ctx.status = 400; + ctx.body = { code: 400, message: '无效文档名' }; + return; + } + + const filePath = getDocFilePath(app, docName); + + try { + const [ content, docs ] = await Promise.all([ + fs.readFile(filePath, 'utf8'), + this.getDocNames(), + ]); + + const docData = JSON.parse(content); + const groups = normalizeGroups(docData); + const entryPath = resolveDocEntryPath(docData); + const html = renderHtmlPage({ + docName, + docData, + groups, + docs, + entryPath, + }); + + ctx.type = 'text/html; charset=utf-8'; + ctx.body = html; + } catch (error) { + ctx.status = 404; + ctx.body = { + code: 404, + message: `未找到文档或 JSON 格式错误: ${docName}`, + error: error.message, + }; + } + } +} + +module.exports = DocsController; diff --git a/app/controller/gateway.js b/app/controller/gateway.js new file mode 100644 index 0000000..820133c --- /dev/null +++ b/app/controller/gateway.js @@ -0,0 +1,118 @@ +'use strict'; + +const { Controller } = require('egg'); +const { toSuccess, toFailure } = require('../lib/api_response'); + +class GatewayController extends Controller { + validateParams(params) { + const required = [ 'method', 'v', 'timestamp' ]; + + for (const field of required) { + if (!params[field]) { + return false; + } + } + + if (typeof params.method !== 'string' || !params.method.includes('.')) { + return false; + } + + return true; + } + + normalizeResult(result) { + if (result && typeof result === 'object' && Object.prototype.hasOwnProperty.call(result, 'success') && Object.prototype.hasOwnProperty.call(result, 'code')) { + if (result.success === false || Number(result.code) <= 0) { + return { + httpStatus: 200, + body: toFailure({ + message: result.message || '请求失败', + httpStatus: 200, + code: typeof result.code === 'number' ? result.code : 0, + data: result.data || null, + }), + }; + } + + return { + httpStatus: 200, + body: toSuccess({ + flag: 'success', + code: result.code, + message: result.message || 'ok', + data: result.data || null, + }), + }; + } + + return { + httpStatus: 200, + body: toSuccess(result), + }; + } + + async internal() { + const { ctx, service } = this; + + try { + const getParams = ctx.query; + if (!this.validateParams(getParams)) { + ctx.status = 400; + ctx.body = toFailure({ + message: '参数缺失或错误: method/v/timestamp', + httpStatus: 400, + code: 400, + }); + ctx.type = 'application/json'; + return; + } + + const methods = String(getParams.method).split('.'); + const actionName = methods.pop(); + const className = methods.join('.'); + + let jsonData = ''; + if (ctx.request.rawBody) { + jsonData = ctx.request.rawBody; + } else { + jsonData = await new Promise((resolve, reject) => { + let data = ''; + ctx.req.on('data', chunk => { + data += chunk; + }); + ctx.req.on('end', () => { + resolve(data); + }); + ctx.req.on('error', reject); + }); + } + + jsonData = jsonData ? String(jsonData) : ''; + if (!jsonData || jsonData.trim() === '') { + throw new Error('json数据为空'); + } + + try { + jsonData = JSON.parse(jsonData); + } catch (error) { + throw new Error('json数据解析错误'); + } + + const result = await service.api.callMethod(className, actionName, jsonData); + const normalized = this.normalizeResult(result); + ctx.status = normalized.httpStatus; + ctx.body = normalized.body; + ctx.type = 'application/json'; + } catch (error) { + ctx.status = 500; + ctx.body = toFailure({ + message: '接口错误: ' + error.message, + httpStatus: 500, + code: 500, + }); + ctx.type = 'application/json'; + } + } +} + +module.exports = GatewayController; diff --git a/app/controller/home.js b/app/controller/home.js index 03786b0..e32027e 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -1,118 +1,1168 @@ +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); +const XLSX = require('xlsx'); const { Controller, } = require('egg'); +const { toSuccess, toFailure } = require('../lib/api_response'); + +// 扫描记录 Excel 追加串行队列(临时联调用,避免并发读写冲突) +let scanExcelWriteQueue = Promise.resolve(); class HomeController extends Controller { - async testSendData(){ + /** + * 规范化平台编码。 + * @param {*} platformCode 平台编码原始值。 + * @return {string} 标准化后的平台编码。 + */ + normalizePlatformCode(platformCode) { + return String(platformCode || '').trim().toUpperCase(); + } + + /** + * 判断店铺记录的平台编码是否与目标平台一致。 + * @param {object|null|undefined} shop 店铺记录。 + * @param {string} platformCode 目标平台编码。 + * @return {boolean} 是否一致。 + */ + isMatchedShopPlatform(shop, platformCode) { + return this.normalizePlatformCode(shop && shop.platform_code) === this.normalizePlatformCode(platformCode); + } + + /** + * 解析绑定授权回调 state 并提取业务编码。 + * + * 仅支持以 bind_ 开头的 state,去掉前缀后的剩余整段即业务 code。 + * + * @param {string} state 授权回调中的 state 原始值。 + * @return {string} 解析得到的业务 code,无法解析时返回空字符串。 + */ + parsePlatformOauthBindBusinessCode(state) { + const bindStatePrefix = 'bind_'; + + if (typeof state !== 'string') { + return ''; + } + + const normalizedState = state.trim(); + + if (!normalizedState.startsWith(bindStatePrefix)) { + return ''; + } + + return normalizedState.slice(bindStatePrefix.length).trim(); + } + + /** + * 渲染平台绑定授权的简易结果页。 + * + * 成功场景仅展示简洁成功文案;失败场景仅展示简洁失败文案并提示重新授权。 + * + * @param {boolean} isSuccess 是否成功。 + * @return {Promise} 无返回值。 + */ + async renderPlatformOauthBindResultPage(isSuccess) { + const title = isSuccess ? '绑定成功' : '绑定失败'; + const message = isSuccess ? '绑定成功' : '绑定失败,请重新授权'; + const color = isSuccess ? '#2f7d32' : '#c62828'; + const html = ` + + + + + ${title} + + + +
    +

    ${title}

    +

    ${message}

    +
    + +`; + + this.ctx.status = isSuccess ? 200 : 400; + this.ctx.type = 'text/html; charset=utf-8'; + this.ctx.body = html; + } + + /** + * 解析平台授权回调 state,提取平台编码与授权随机码。 + * @param {string} state 回调原始 state。 + * @param {string} reservationCodePrefix 配置的预留前缀。 + * @return {{normalizedState: string, platformCode: string, authRandomCode: string}|null} 解析结果,失败时返回 null。 + */ + parsePlatformOauthState(state, reservationCodePrefix) { + const normalizedState = reservationCodePrefix && state.startsWith(reservationCodePrefix) + ? state.slice(reservationCodePrefix.length) + : state; + const separatorIndex = normalizedState.indexOf('_'); + + if (separatorIndex <= 0 || separatorIndex === normalizedState.length - 1) { + return null; + } + + const platformCode = normalizedState.slice(0, separatorIndex).trim(); + const authRandomCode = normalizedState.slice(separatorIndex + 1).trim(); + + if (!platformCode || !authRandomCode) { + return null; + } + + return { + normalizedState, + platformCode, + authRandomCode, + }; + } + + /** + * 组装平台授权回调页面展示数据。 + * @param {object} payload 页面数据参数。 + * @param {string} payload.code 平台回调返回的授权码。 + * @param {string} payload.state 平台回调返回的原始 state。 + * @param {{normalizedState: string, platformCode: string, authRandomCode: string}|null} payload.parsedState 解析后的 state 数据。 + * @param {import('sequelize').Model|null} payload.shop 店铺记录。 + * @param {string} payload.errorMessage 预校验失败提示。 + * @return {object} 页面渲染数据。 + */ + buildPlatformOauthCallbackViewData({ code, state, parsedState, shop, errorMessage }) { + const platformCode = parsedState ? parsedState.platformCode : ''; + const authRandomCode = parsedState ? parsedState.authRandomCode : ''; + const normalizedState = parsedState ? parsedState.normalizedState : ''; + const hasShop = Boolean(shop); + const isProcessed = hasShop ? Number(shop.status) === 1 : null; + const isPlatformMatched = hasShop && parsedState + ? this.isMatchedShopPlatform(shop, platformCode) + : null; + let resultLevel = 'error'; + let resultText = errorMessage || '授权回调校验失败'; + + if (!errorMessage && !hasShop) { + resultText = '预授权码不存在'; + } else if (!errorMessage && isPlatformMatched === false) { + resultText = '平台不匹配'; + } else if (!errorMessage && isProcessed === true) { + resultLevel = 'warning'; + resultText = '该预授权码已处理'; + } else if (!errorMessage && isProcessed === false && isPlatformMatched === true) { + resultLevel = 'success'; + resultText = '预授权码有效,平台匹配且尚未处理'; + } + + return { + title: '平台授权回调结果', + resultLevel, + resultText, + code, + state, + normalizedState, + platformCode, + authRandomCode, + isProcessed, + isProcessedText: hasShop + ? (isProcessed ? '是(已处理)' : '否(未处理)') + : '无法判断', + isPlatformMatched, + isPlatformMatchedText: hasShop + ? (isPlatformMatched ? '是' : '否') + : '无法判断', + shopPlatformCode: hasShop ? String(shop.platform_code || '') : '', + shopStatus: hasShop ? Number(shop.status) : null, + hasShop, + }; + } + + /** + * 将淘宝授权接口返回的奇门响应归一化为可读取的对象。 + * @param {object|Array|null|undefined} xmlArray 奇门返回中的 xmlArray 字段。 + * @return {object|null} 归一化后的响应对象,无法识别时返回 null。 + */ + normalizeTbOauthQimenResponse(xmlArray) { + if (!xmlArray || typeof xmlArray !== 'object' || Array.isArray(xmlArray)) { + return null; + } + + const response = xmlArray.response && typeof xmlArray.response === 'object' + ? xmlArray.response + : xmlArray; + + if (response.top_auth_token_create_response && typeof response.top_auth_token_create_response === 'object') { + return response.top_auth_token_create_response; + } + + return response; + } + + /** + * 从淘宝授权接口的奇门返回中提取 access_token。 + * @param {object|Array|null|undefined} xmlArray 奇门返回中的 xmlArray 字段。 + * @return {string} 提取出的 access_token,失败时返回空字符串。 + */ + extractTbOauthAccessToken(xmlArray) { + if (Array.isArray(xmlArray)) { + const tokenCreateResponse = xmlArray.find(item => item && typeof item === 'object' && item.name === 'top_auth_token_create_response'); + const tokenCreateChildren = Array.isArray(tokenCreateResponse && tokenCreateResponse.children) + ? tokenCreateResponse.children + : []; + const tokenCreateResult = tokenCreateChildren.find(item => item && typeof item === 'object' && item.name === 'result'); + const resultChildren = Array.isArray(tokenCreateResult && tokenCreateResult.children) + ? tokenCreateResult.children + : []; + const accessTokenItem = resultChildren.find(item => item && typeof item === 'object' && item.name === 'access_token'); + + return accessTokenItem && accessTokenItem.value !== undefined && accessTokenItem.value !== null + ? String(accessTokenItem.value).trim() + : ''; + } + + const response = this.normalizeTbOauthQimenResponse(xmlArray); + const result = response && response.result && typeof response.result === 'object' + ? response.result + : null; + const accessTokenValue = result && result.access_token !== undefined && result.access_token !== null + ? result.access_token + : response && response.access_token !== undefined && response.access_token !== null + ? response.access_token + : ''; + + return accessTokenValue ? String(accessTokenValue).trim() : ''; + } + + async testSendData() { await this.ctx.service.systems.print.index.test(); this.ctx.body = 'ok'; } + + /** + * 读取原始请求报文文本。 + * + * 优先取 koa-bodyparser 已解析的 rawBody;若上游未携带可识别的 + * Content-Type(bodyParser 未消费请求流),则直接从请求流中读取。 + * @return {Promise} 报文文本,读取失败时返回空字符串。 + */ + async readRawRequestText() { + const { ctx } = this; + const rawBody = ctx.request.rawBody; + + if (rawBody !== undefined && rawBody !== null) { + return Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : String(rawBody); + } + + const chunks = []; + + try { + for await (const chunk of ctx.req) { + chunks.push(chunk); + } + } catch (err) { + ctx.logger.error('[scan] 读取请求流失败', err && err.message || String(err)); + } + + return Buffer.concat(chunks.map(chunk => (Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)))).toString('utf8'); + } + + /** + * 生成格式化的当前时间字符串。 + * @param {Date} date 时间对象。 + * @return {string} YYYY-MM-DD HH:mm:ss。 + */ + formatScanRecordTime(date = new Date()) { + const pad = value => String(value).padStart(2, '0'); + + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; + } + + /** + * 将一次扫描记录(时间 + 条码)追加写入项目根目录的 scan_records.xlsx。 + * + * 临时联调用途:文件不存在则新建(含表头),存在则读取全部已有行后追加。 + * 写入复用 ExcelService 的原子写(临时文件 + rename),避免写坏文件。 + * + * @param {string} barcode 扫描到的条码内容。 + * @return {Promise<{filePath: string, timeText: string, barcode: string, totalRows: number}>} 追加结果。 + */ + async appendScanRecordToExcel(barcode) { + const filePath = path.join(this.app.baseDir, 'scan_records.xlsx'); + const timeText = this.formatScanRecordTime(); + const headerRow = [ '时间', '条码' ]; + let rows = [ headerRow ]; + + if (fs.existsSync(filePath)) { + try { + const workbook = XLSX.readFile(filePath); + const firstSheetName = workbook.SheetNames && workbook.SheetNames[0]; + + if (firstSheetName) { + const sheet = workbook.Sheets[firstSheetName]; + const parsedRows = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false }); + const existingRows = parsedRows.filter(row => Array.isArray(row) && row.length); + + if (existingRows.length) { + rows = existingRows; + } + } + } catch (error) { + this.ctx.logger.error('[scan] 读取根目录 scan_records.xlsx 失败,将重建文件', error && error.message || String(error)); + rows = [ headerRow ]; + } + } + + rows.push([ timeText, barcode ]); + + const workbook = XLSX.utils.book_new(); + const sheet = XLSX.utils.aoa_to_sheet(rows); + XLSX.utils.book_append_sheet(workbook, sheet, 'scan_records'); + + const buffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }); + await this.ctx.service.systems.excel.writeAtomicBufferFile(filePath, Buffer.from(buffer)); + + return { + filePath, + timeText, + barcode, + totalRows: rows.length - 1, + }; + } + + /** + * 扫描报文接收入口(POST /scan)。 + * + * 联调阶段:接收上游报文并原样打日志、回显,同时把扫描到的条码与时间 + * 追加写入项目根目录 scan_records.xlsx。 + */ + async scan() { + const { ctx } = this; + const rawBody = await this.readRawRequestText(); + const barcode = rawBody ? rawBody.trim() : ''; + let body = null; + let parseError = ''; + let excelRecord = null; + + if (rawBody) { + const trimmed = rawBody.trim(); + + if (trimmed.startsWith('{') || trimmed.startsWith('[')) { + try { + body = JSON.parse(trimmed); + } catch (err) { + parseError = err && err.message || String(err); + body = rawBody; + } + } else { + body = rawBody; + } + } + + if (barcode) { + excelRecord = await (scanExcelWriteQueue = scanExcelWriteQueue + .catch(() => {}) + .then(() => this.appendScanRecordToExcel(barcode))); + } + + ctx.logger.info('[scan] 收到请求报文', { + method: ctx.method, + url: ctx.url, + contentType: ctx.get('content-type'), + query: ctx.query, + headers: ctx.headers, + rawBody, + rawBodyHex: rawBody ? Buffer.from(rawBody, 'utf8').toString('hex') : '', + body, + parseError, + barcode, + excelRecord, + }); + + ctx.body = toSuccess({ + contentType: ctx.get('content-type'), + rawBody, + body, + parseError, + barcode, + excelRecord, + }); + } + async index() { const { ctx, } = this; ctx.body = 'pong'; } - async v1() { - const { - ctx, - service, - } = this; - const startTime = Date.now(); - // 初始化日志数据 - const logData = { - app_key: '', - method: '', - sign: '', - costomer_id: '', - v: '', - url: ctx.request.href, - created_at: new Date(), - body: '', - result: '', - use_time: 0, - }; + + /** + * 使用授权码请求拼多多开放平台换取授权结果,并返回结构化处理结果。 + * @param {string} code 平台回调返回的授权码。 + * @return {Promise<{success: boolean, message?: string, result: object|null}>} 请求处理结果。 + */ + async pdd(code) { + const pddConfig = this.app.config.pdd || {}; + try { - const getParams = ctx.query; - logData.method = getParams.method || ''; - logData.v = getParams.v || ''; - // 验证必要参数 - if (!this.validateParams(getParams)) { - const errorMsg = '参数缺失或错误'; - const response = this.errorResponse(errorMsg, 'json'); - logData.result = response; - await this.saveLog(logData, startTime); + const result = await this.ctx.curl('https://open-api.pinduoduo.com/oauth/token', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + dataType: 'json', + data: { + client_id: pddConfig.client_id || '', + code, + grant_type: 'authorization_code', + client_secret: pddConfig.client_secret || '', + }, + }); - ctx.body = response; - ctx.type = 'application/json'; - return; + console.log(result); + + if (result && result.data && result.data.error_response) { + const errorMessage = result.data.error_response.error_msg || '未知错误'; + + return { + success: false, + message: `拼多多授权失败:${errorMessage}`, + result, + }; } - // 处理method参数 - const method = getParams.method; - const methods = method.split('.'); - const actionName = methods.pop(); - const className = methods.map((item, index) => - (index === methods.length - 1 ? item : item) - ).join('.'); - - // 获取XML数据 - let jsonData = ''; - if (ctx.request.rawBody) { - // 使用 rawBody 获取原始请求体 - jsonData = ctx.request.rawBody; - } else { - // 如果没有 rawBody,尝试从流中读取 - jsonData = await new Promise((resolve, reject) => { - let data = ''; - ctx.req.on('data', chunk => { - data += chunk; - }); - ctx.req.on('end', () => { - resolve(data); - }); - ctx.req.on('error', reject); - }); - } - - // 确保 xmlData 是字符串 - jsonData = jsonData ? String(jsonData) : ''; - logData.body = jsonData; - if (!jsonData || jsonData.trim() === '') { - throw new Error('json数据为空'); - } - try { - jsonData = JSON.parse(jsonData); - } catch (e) { - throw new Error('json数据解析错误'); - } - // 调用业务方法 - const result = await service.api.callMethod(className, actionName, jsonData, getParams.format); - - // 记录成功响应 - logData.result = typeof result === 'string' ? result : JSON.stringify(result); - await this.saveLog(logData, startTime); - - ctx.body = result; - ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json'; + return { + success: true, + result, + }; } catch (error) { - ctx.logger.error('调用接口失败返回数据', error); - const response = this.errorResponse('接口错误: ' + error.message, ctx.query.format || 'json'); - logData.result = typeof response === 'string' ? response : JSON.stringify(response); - await this.saveLog(logData, startTime); - ctx.body = response; - ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json'; + this.ctx.logger.error('[platform-oauth][PDD] oauth/token 请求异常: %s', error); + + return { + success: false, + message: `拼多多授权请求异常:${error.message}`, + result: null, + }; } } + + /** + * 使用授权码请求菜鸟授权结果,并按淘宝 OAuth 协议解析返回值。 + * @param {string} code 平台回调返回的授权码。 + * @return {Promise<{success: boolean, message?: string, result: object|null}>} 请求处理结果。 + */ + async cainiao(code) { + const qimenConfig = this.app.config.qimen || {}; + const redirectUri = 'http://39.100.57.68/'; + const requestPayload = { + code, + grant_type: 'authorization_code', + client_id: qimenConfig.appKey || '', + client_secret: qimenConfig.security || '', + redirect_uri: redirectUri, + }; + const formBody = new URLSearchParams(requestPayload).toString(); + + try { + const result = await this.ctx.curl('https://oauth.taobao.com/token', { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + dataType: 'json', + content: formBody, + }); + + console.log(result); + + const responseData = result && result.data ? result.data : null; + const hasTaobaoStandardError = !!( + responseData + && (responseData.error !== undefined || responseData.error_description !== undefined) + ); + + if (responseData && (responseData.error_response || hasTaobaoStandardError)) { + const errorMessage = responseData.error_response && responseData.error_response.error_msg + ? responseData.error_response.error_msg + : responseData.error_description || responseData.error || '未知错误'; + + return { + success: false, + message: `菜鸟授权失败:${errorMessage}`, + result, + }; + } + + return { + success: true, + result, + }; + } catch (error) { + this.ctx.logger.error('[platform-oauth][CAINIAO] oauth/token 请求异常: %s', error); + + return { + success: false, + message: `菜鸟授权请求异常:${error.message}`, + result: null, + }; + } + } + /** + * 构建拼多多授权店铺回写字段。 + * @param {object|null|undefined} oauthData 拼多多授权返回数据。 + * @return {object} 可直接用于店铺模型回写的字段对象。 + */ + buildPddOauthShopUpdatePayload(oauthData) { + const toDateFromUnixSeconds = value => { + const seconds = Number(value); + + if (!Number.isFinite(seconds) || seconds <= 0) { + return null; + } + + return new Date(seconds * 1000); + }; + const updatePayload = { + owner_id: oauthData && oauthData.owner_id !== undefined ? oauthData.owner_id : null, + access_token: oauthData && oauthData.access_token !== undefined ? oauthData.access_token : null, + refresh_token: oauthData && oauthData.refresh_token !== undefined ? oauthData.refresh_token : null, + token_expires_at: toDateFromUnixSeconds(oauthData && oauthData.expires_at), + refresh_token_expires_at: toDateFromUnixSeconds(oauthData && oauthData.refresh_token_expires_at), + auth_expire_at: toDateFromUnixSeconds(oauthData && oauthData.expires_at), + scope: oauthData && oauthData.scope !== undefined ? oauthData.scope : null, + status: 1, + }; + + if (oauthData && oauthData.owner_name) { + updatePayload.shop_name = oauthData.owner_name; + } + + return updatePayload; + } + + /** + * 安全解码淘宝店铺昵称,解码失败时保留原值。 + * @param {string|null|undefined} taobaoUserNick 淘宝返回的店铺昵称。 + * @return {string|null|undefined} 解码后的店铺昵称,失败时返回原值。 + */ + decodeTbShopName(taobaoUserNick) { + if (typeof taobaoUserNick !== 'string') { + return taobaoUserNick; + } + + try { + return decodeURIComponent(taobaoUserNick); + } catch (error) { + return taobaoUserNick; + } + } + + /** + * 构建菜鸟授权店铺回写字段。 + * @param {object|null|undefined} oauthData 菜鸟授权返回数据,字段仍遵循淘宝 OAuth 协议。 + * @return {object} 可直接用于店铺模型回写的字段对象。 + */ + buildCainiaoOauthShopUpdatePayload(oauthData) { + const toDateFromUnixMilliseconds = value => { + const milliseconds = Number(value); + + if (!Number.isFinite(milliseconds) || milliseconds <= 0) { + return null; + } + + return new Date(milliseconds); + }; + + const updatePayload = { + owner_id: oauthData && oauthData.taobao_user_id !== undefined ? oauthData.taobao_user_id : null, + access_token: oauthData && oauthData.access_token !== undefined ? oauthData.access_token : null, + refresh_token: oauthData && oauthData.refresh_token !== undefined ? oauthData.refresh_token : null, + token_expires_at: toDateFromUnixMilliseconds(oauthData && oauthData.expire_time), + refresh_token_expires_at: toDateFromUnixMilliseconds(oauthData && oauthData.refresh_token_valid_time), + auth_expire_at: toDateFromUnixMilliseconds(oauthData && oauthData.expire_time), + scope: oauthData && oauthData.scope !== undefined ? oauthData.scope : null, + status: 1, + }; + + if (oauthData && oauthData.taobao_user_nick != null) { + updatePayload.shop_name = this.decodeTbShopName(oauthData.taobao_user_nick); + } + + return updatePayload; + } + + /** + * 按仓库、平台与授权标识查找已授权的旧店铺记录。 + * @param {import('sequelize').Model} shop 当前预申请店铺记录。 + * @param {string|number|null|undefined} ownerId 平台主体标识。 + * @param {string|null|undefined} shopName 店铺名称。 + * @param {import('sequelize').Transaction} transaction 当前事务对象。 + * @return {Promise} 命中的已授权店铺记录。 + */ + async findAuthorizedOauthShop(shop, ownerId, shopName, transaction) { + const { Op } = this.app.Sequelize; + const normalizedOwnerId = ownerId !== undefined && ownerId !== null + ? String(ownerId).trim() + : ''; + const normalizedShopName = shopName !== undefined && shopName !== null + ? String(shopName).trim() + : ''; + const matchConditions = []; + + if (normalizedOwnerId) { + matchConditions.push({ owner_id: ownerId }); + } + + if (normalizedShopName) { + matchConditions.push({ shop_name: shopName }); + } + + if (!matchConditions.length) { + return null; + } + + return await this.ctx.model.Shop.findOne({ + where: { + warehouse_id: shop.warehouse_id, + platform_code: shop.platform_code, + status: 1, + id: { + [Op.ne]: shop.id, + }, + [Op.or]: matchConditions, + }, + transaction, + }); + } + + /** + * 查找与待更新店铺存在唯一约束冲突的店铺记录(不限授权状态)。 + * 用于乐观重试场景:当前预授权店铺 save 触发 uk_warehouse_platform_shop_name + * 冲突时,回退到此方法查找冲突记录并尝试合并。 + * @param {import('sequelize').Model} shop 当前预申请店铺记录。 + * @param {object} updatePayload 待回写的字段对象,需包含 shop_name。 + * @param {import('sequelize').Transaction} transaction 当前事务对象。 + * @return {Promise} 冲突的店铺记录,未找到返回 null。 + */ + async findConflictShopForOauth(shop, updatePayload, transaction) { + const { Op } = this.app.Sequelize; + const normalizedShopName = updatePayload.shop_name != null + ? String(updatePayload.shop_name).trim() + : ''; + + if (!normalizedShopName) { + return null; + } + + return await this.ctx.model.Shop.findOne({ + where: { + warehouse_id: shop.warehouse_id, + platform_code: shop.platform_code, + shop_name: normalizedShopName, + id: { + [Op.ne]: shop.id, + }, + }, + transaction, + }); + } + + /** + * 按仓库、平台与授权标识查找已授权的旧店铺记录。 + * @param {import('sequelize').Model} shop 当前预申请店铺记录。 + * @param {object|null|undefined} oauthData 拼多多授权返回数据。 + * @param {import('sequelize').Transaction} transaction 当前事务对象。 + * @return {Promise} 命中的已授权店铺记录。 + */ + async findAuthorizedPddOauthShop(shop, oauthData, transaction) { + const ownerId = oauthData && oauthData.owner_id !== undefined && oauthData.owner_id !== null + ? String(oauthData.owner_id).trim() + : ''; + const ownerName = oauthData && oauthData.owner_name !== undefined && oauthData.owner_name !== null + ? String(oauthData.owner_name).trim() + : ''; + + return await this.findAuthorizedOauthShop(shop, ownerId ? oauthData.owner_id : null, ownerName, transaction); + } + + /** + * 将拼多多授权成功后的关键字段回写到店铺记录。 + * @param {import('sequelize').Model} shop 店铺模型实例。 + * @param {object|null|undefined} oauthData 拼多多授权返回数据。 + * @return {Promise} 已保存的店铺模型实例。 + */ + async updatePddOauthShop(shop, oauthData) { + const updatePayload = this.buildPddOauthShopUpdatePayload(oauthData); + const saveFields = [ + 'owner_id', + 'shop_name', + 'access_token', + 'refresh_token', + 'token_expires_at', + 'refresh_token_expires_at', + 'auth_expire_at', + 'scope', + 'status', + ]; + + return await this.ctx.model.transaction(async transaction => { + const authorizedShop = await this.findAuthorizedPddOauthShop(shop, oauthData, transaction); + + if (authorizedShop) { + authorizedShop.set(updatePayload); + await authorizedShop.save({ + fields: saveFields, + transaction, + }); + await shop.destroy({ transaction }); + + return authorizedShop; + } + + shop.set(updatePayload); + await shop.save({ + fields: saveFields, + transaction, + }); + + return shop; + }); + } + + /** + * 将菜鸟授权成功后的关键字段回写到店铺记录。 + * @param {import('sequelize').Model} shop 店铺模型实例。 + * @param {object|null|undefined} oauthData 菜鸟授权返回数据,字段仍遵循淘宝 OAuth 协议。 + * @return {Promise} 已保存的店铺模型实例。 + */ + async updateCainiaoOauthShop(shop, oauthData) { + const updatePayload = this.buildCainiaoOauthShopUpdatePayload(oauthData); + const saveFields = [ + 'owner_id', + 'shop_name', + 'access_token', + 'refresh_token', + 'token_expires_at', + 'refresh_token_expires_at', + 'auth_expire_at', + 'scope', + 'status', + ]; + + // 兜底:若 OAuth 响应未返回 shop_name,沿用数据库已有值,避免 save 时触发 allowNull 校验 + if (!('shop_name' in updatePayload) || updatePayload.shop_name == null) { + updatePayload.shop_name = shop.shop_name; + } + + try { + return await this.ctx.model.transaction(async transaction => { + const authorizedShop = await this.findAuthorizedOauthShop( + shop, + updatePayload.owner_id, + updatePayload.shop_name, + transaction + ); + + if (authorizedShop) { + authorizedShop.set(updatePayload); + await authorizedShop.save({ + fields: saveFields, + transaction, + }); + await shop.destroy({ transaction }); + + return authorizedShop; + } + + shop.set(updatePayload); + await shop.save({ + fields: saveFields, + transaction, + }); + + return shop; + }); + } catch (error) { + // 记录 Sequelize 验证错误的详细信息,包括每个字段的失败原因 + if (error.name === 'SequelizeValidationError' && Array.isArray(error.errors)) { + const fieldErrors = error.errors.map(e => `${e.path}: ${e.message}`).join('; '); + this.ctx.logger.error( + '[platform-oauth][CAINIAO] 店铺保存校验失败,shop_id=%s,字段详情:%s', + shop && shop.id, + fieldErrors + ); + throw error; + } + + // 唯一约束冲突:尝试乐观重试,查找冲突记录并合并 + if (error.name === 'SequelizeUniqueConstraintError') { + const conflictFields = error.fields ? Object.keys(error.fields).join(', ') : 'unknown'; + const conflictValues = error.fields ? JSON.stringify(error.fields) : 'unknown'; + this.ctx.logger.error( + '[platform-oauth][CAINIAO] 店铺保存唯一约束冲突,shop_id=%s,冲突字段:%s,冲突值:%s', + shop && shop.id, + conflictFields, + conflictValues + ); + + // 乐观重试:在新事务中查找冲突记录并尝试合并 + try { + return await this.ctx.model.transaction(async transaction => { + const conflictShop = await this.findConflictShopForOauth( + shop, + updatePayload, + transaction + ); + + if (conflictShop) { + conflictShop.set(updatePayload); + await conflictShop.save({ + fields: saveFields, + transaction, + }); + await shop.destroy({ transaction }); + this.ctx.logger.info( + '[platform-oauth][CAINIAO] 乐观重试成功,冲突店铺已合并,conflict_shop_id=%s,pre_auth_shop_id=%s', + conflictShop.id, + shop.id + ); + return conflictShop; + } + + // 未找到冲突记录则返回 null,由上层展示友好提示 + this.ctx.logger.warn( + '[platform-oauth][CAINIAO] 乐观重试未找到冲突记录,shop_id=%s,shop_name=%s', + shop && shop.id, + updatePayload.shop_name + ); + return null; + }); + } catch (retryError) { + this.ctx.logger.error( + '[platform-oauth][CAINIAO] 乐观重试失败,shop_id=%s,错误:%s', + shop && shop.id, + retryError.message || retryError + ); + return null; + } + } + + throw error; + } + } + + /** + * 处理平台授权回调请求,解析 query 中的 code 与 state。 + * 内部使用 try-catch 兜底,确保即使处理过程中抛出未捕获异常也能渲染错误页面而非 500。 + * @return {Promise} 无返回值。 + */ + async platformOauthCallback() { + const { + ctx, + app, + } = this; + const code = typeof ctx.query.code === 'string' ? ctx.query.code.trim() : ''; + const state = typeof ctx.query.state === 'string' ? ctx.query.state.trim() : ''; + const reservationCodePrefix = app.config.platformOauthReservationCodePrefix || ''; + const parsedState = state ? this.parsePlatformOauthState(state, reservationCodePrefix) : null; + let errorMessage = ''; + let shop = null; + + try { + if (!code) { + errorMessage = 'code不能为空'; + } else if (!state) { + errorMessage = 'state不能为空'; + } else if (!parsedState) { + errorMessage = 'state解析失败'; + } else { + switch (parsedState.platformCode) { + case 'PDD': + { + const pddResult = await this.pdd(code); + + if (pddResult.success === false) { + errorMessage = pddResult.message; + break; + } + + shop = await ctx.model.Shop.findOne({ + where: { + auth_random_code: parsedState.authRandomCode, + }, + }); + + if (shop && this.isMatchedShopPlatform(shop, parsedState.platformCode)) { + const oauthData = pddResult.result && pddResult.result.data + ? pddResult.result.data + : pddResult.result; + + shop = await this.updatePddOauthShop(shop, oauthData); + } + } + break; + case 'CAINIAO': + { + const cainiaoOauthResult = await this.cainiao(code); + + if (!cainiaoOauthResult || cainiaoOauthResult.success === false) { + errorMessage = cainiaoOauthResult && cainiaoOauthResult.message + ? cainiaoOauthResult.message + : '菜鸟授权失败:未知错误'; + break; + } + + shop = await ctx.model.Shop.findOne({ + where: { + auth_random_code: parsedState.authRandomCode, + }, + }); + + if (shop && this.isMatchedShopPlatform(shop, parsedState.platformCode)) { + const oauthData = cainiaoOauthResult.result && cainiaoOauthResult.result.data + ? cainiaoOauthResult.result.data + : cainiaoOauthResult.result; + + shop = await this.updateCainiaoOauthShop(shop, oauthData); + if (!shop) { + errorMessage = '店铺名称已存在,请先在系统中解绑同名店铺后重试'; + } + } + + break; + } + default: + errorMessage = '暂未接入该平台授权回调处理'; + break; + } + } + } catch (error) { + ctx.logger.error('[platform-oauth] 回调处理异常: %s', error.stack || error.message || error); + errorMessage = `系统内部错误:${error.message || '未知异常'}`; + // 发生异常后不再信任 shop 状态,置空以避免渲染误导信息 + shop = null; + } + + const viewData = this.buildPlatformOauthCallbackViewData({ + code, + state, + parsedState, + shop, + errorMessage, + }); + + ctx.status = viewData.resultLevel === 'error' ? 400 : 200; + await ctx.render('platform_oauth_callback.html', viewData); + } + + /** + * 处理拼多多绑定授权回调。 + * + * 流程:校验 code/state -> 解析业务 code -> 复用 pdd(code) 换取 access_token + * -> 写入缓存 bind_pdd_code:{业务code} -> 返回简易成功/失败页。 + * + * @return {Promise} 无返回值。 + */ + async platformOauthBind() { + const { service } = this.ctx; + const code = typeof this.ctx.query.code === 'string' ? this.ctx.query.code.trim() : ''; + const state = typeof this.ctx.query.state === 'string' ? this.ctx.query.state.trim() : ''; + const businessCode = this.parsePlatformOauthBindBusinessCode(state); + const failCacheKey = businessCode ? `bind_pdd_code_fail:${businessCode}` : ''; + + const markBindFailed = async reason => { + if (!businessCode || !failCacheKey) { + return; + } + try { + await this.app.setCacheAsync(failCacheKey, { + status: 'failed', + message: reason || '绑定失败,请重新授权', + }); + await service.systems.platform.publishPlatformOauthBindEvent(businessCode, { + status: 'failed', + message: reason || '绑定失败,请重新授权', + }); + } catch (error) { + this.ctx.logger.error('[platform-oauth-bind] 失败标记写入异常: %s', error && error.message ? error.message : error); + } + }; + + if (!code || !state) { + await markBindFailed('绑定失败,请重新授权'); + await this.renderPlatformOauthBindResultPage(false); + return; + } + + if (!businessCode) { + await this.renderPlatformOauthBindResultPage(false); + return; + } + + const pddResult = await this.pdd(code); + + if (!pddResult || pddResult.success === false) { + await markBindFailed('绑定失败,请重新授权'); + await this.renderPlatformOauthBindResultPage(false); + return; + } + + const oauthData = pddResult.result && pddResult.result.data + ? pddResult.result.data + : pddResult.result; + const accessToken = oauthData && typeof oauthData.access_token === 'string' + ? oauthData.access_token.trim() + : ''; + + if (!accessToken) { + await markBindFailed('绑定失败,请重新授权'); + await this.renderPlatformOauthBindResultPage(false); + return; + } + + try { + await this.app.setCacheAsync(`bind_pdd_code:${businessCode}`, accessToken); + if (typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(failCacheKey); + } else { + await this.app.setCacheAsync(failCacheKey, null, 1); + } + await service.systems.platform.publishPlatformOauthBindEvent(businessCode, { + status: 'success', + access_token: accessToken, + }); + } catch (error) { + this.ctx.logger.error('[platform-oauth-bind] 缓存写入失败: %s', error && error.message ? error.message : error); + await markBindFailed('绑定失败,请重新授权'); + await this.renderPlatformOauthBindResultPage(false); + return; + } + + await this.renderPlatformOauthBindResultPage(true); + } + + /** + * 查询拼多多绑定授权码的轮询状态。 + * + * 根据 code 先查成功缓存,再查失败标记,最终返回 success / failed / pending 三态。 + * + * @return {Promise} 无返回值。 + */ + async queryPddCode() { + const code = this.ctx.params && typeof this.ctx.params.code === 'string' + ? this.ctx.params.code.trim() + : ''; + + if (!code) { + this.ctx.status = 400; + this.ctx.body = toFailure({ + httpStatus: 400, + message: 'code不能为空', + data: { + status: 'failed', + message: 'code不能为空', + }, + }); + return; + } + + const successCacheKey = `bind_pdd_code:${code}`; + const failCacheKey = `bind_pdd_code_fail:${code}`; + let accessToken = ''; + + try { + const cachedToken = await this.app.getCacheAsync(successCacheKey); + + accessToken = typeof cachedToken === 'string' ? cachedToken.trim() : ''; + } catch (error) { + this.ctx.logger.error('[query-pdd-code] 查询 access_token 缓存异常: %s', error && error.message ? error.message : error); + } + + if (accessToken) { + this.ctx.body = toSuccess({ + status: 'success', + access_token: accessToken, + }); + return; + } + + let failedCacheValue = null; + + try { + failedCacheValue = await this.app.getCacheAsync(failCacheKey); + } catch (error) { + this.ctx.logger.error('[query-pdd-code] 查询失败标记缓存异常: %s', error && error.message ? error.message : error); + } + + if (failedCacheValue !== null && failedCacheValue !== undefined && failedCacheValue !== '') { + const failedMessage = '绑定失败,请重新授权'; + + this.ctx.status = 200; + this.ctx.body = toFailure({ + httpStatus: 200, + message: failedMessage, + data: { + status: 'failed', + message: failedMessage, + }, + }); + return; + } + + const failedMessage = '绑定失败,请重新授权'; + + this.ctx.status = 200; + this.ctx.body = toFailure({ + httpStatus: 200, + message: failedMessage, + data: { + status: 'failed', + message: failedMessage, + }, + }); + } + + /** + * 处理奇门统一入口请求,完成参数校验、XML 解析、仓库编码提取与方法分发。 + * @return {Promise} 无返回值。 + */ async qimen() { const { ctx, service, } = this; const startTime = Date.now(); + const logId = 'QL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'); + ctx.qimenLogId = logId; // 初始化日志数据 const logData = { + log_id: logId, from_key: '', to_key: this.app.config.qimen.appKey, method: '', @@ -132,14 +1182,12 @@ class HomeController extends Controller { logData.sign = getParams.sign || ''; logData.costomer_id = getParams.customerId || getParams.customer_id || ''; logData.v = getParams.v || ''; - ctx.qimenLogId = await service.qimen.saveQimenLog(logData, startTime); try { // 验证必要参数 if (!this.validateQimenParams(getParams)) { const errorMsg = '参数缺失或错误'; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); ctx.body = response; ctx.type = 'application/xml'; return; @@ -185,49 +1233,43 @@ class HomeController extends Controller { // 解析XML数据 const xmlArray = await service.qimen.parseXmlToArray(xmlData); xmlArray.app_key = appkey; - let warehouseCode = xmlArray.request.warehouseCode || ''; - const ownerCode = customerId; + const warehouseCode = this.getQimenWarehouseCode(xmlArray); - await service.qimen.saveQimenLogBody(xmlData); + 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); let api_info = { warehouseCode: '', ownerCode: '', }; - if (!warehouseCode || !customerId) { - // 入库单提取 - try { - warehouseCode = xmlArray.request?.entryOrder?.warehouseCode || - xmlArray.request?.deliveryOrder?.warehouseCode || - ''; - } catch (e) {} - } if (warehouseCode && customerId) { // 验证接口是否存在且启用 api_info = await service.qimen.validateApi(appkey, customerId, warehouseCode); if (!api_info) { const errorMsg = `奇门${erpName}客户编码${customerId}仓库编码${warehouseCode}未绑定到你的货主或未启用,请联系仓库绑定`; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; } - if (api_info.contract_auth_status != 2) { + if (api_info.contract_auth_status !== 2) { const errorMsg = `货主与仓库签约状态异常,请到WMS核实签约状态${api_info.contract_auth_status}`; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; } - if (api_info.warehouse_status == 0) { + if (api_info.warehouse_status === 0) { const errorMsg = '仓库状态异常,请联系仓库核实WMS状态'; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; @@ -238,8 +1280,6 @@ class HomeController extends Controller { if (authEndTime2 < currentTime) { const errorMsg = '与仓库合约过期,请到WMS重新发起仓库续约'; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; @@ -247,8 +1287,6 @@ class HomeController extends Controller { if (authEndTime < currentTime) { const errorMsg = '仓库订阅过期,请联系仓库核实状态'; const response = this.errorResponse(errorMsg, 'xml'); - await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; @@ -258,20 +1296,141 @@ class HomeController extends Controller { // 调用业务方法 const result = await service.qimen.callMethod(className, actionName, xmlArray, api_info.store_id, api_info.warehouse_id, appkey, customerId, warehouseCode, getParams.format); - // 记录成功响应 - const logData_result = typeof result === 'string' ? result : JSON.stringify(result); - await service.qimen.saveQimenLogResult(logData_result); ctx.body = result; ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json'; } catch (error) { const response = this.errorResponse('奇门接口错误: ' + error.message, ctx.query.format || 'xml'); - await service.qimen.saveQimenLogResult(response); ctx.body = response; ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json'; + } finally { + // 统一写入日志文件队列 + logData.use_time = Date.now() - startTime; + logData.result = typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body); + if (logData.body && logData.body.length > 65535) { + logData.body = logData.body.substring(0, 65535); + } + if (logData.result && logData.result.length > 65535) { + logData.result = logData.result.substring(0, 65535); + } + // 日志落盘改为异步投递,避免阻塞主请求响应。 + Promise.resolve(this.app.fileWriter.writeRecord('qimen-logs', logData)).catch(writeErr => { + ctx.logger.error('[qimen-log-sink] 写入文件失败: ' + writeErr.message); + ctx.logger.info('[qimen-log-sink] 日志数据: ', JSON.stringify(logData)); + }); } } + /** + * 归一化奇门字段值,过滤空白内容和占位符字符串。 + * @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' ]; @@ -344,42 +1503,6 @@ class HomeController extends Controller { }); } - async saveLog(logData, startTime) { - const { - ctx, - } = this; - - try { - // 限制日志内容长度 - if (logData.body && logData.body.length > 65535) { - logData.body = logData.body.substring(0, 65535); - } - - if (logData.result && logData.result.length > 65535) { - logData.result = logData.result.substring(0, 65535); - } - - logData.use_time = Date.now() - startTime; - - // 使用 egg-mysql 保存日志到数据库 - const result = await ctx.app.mysql.get('wms').insert('wms_api_log', { - method: logData.method || '', - v: logData.v || '', - url: logData.url || '', - created_at: ctx.app.mysql.get('wms').literals.now, - body: logData.body || '', - result: logData.result || '', - use_time: logData.use_time || 0, - }); - - return result; - - } catch (error) { - ctx.logger.error('保存奇门接口日志失败: ' + error.message); - // 可以选择记录到文件日志作为备用 - ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData)); - } - } async pda() { const { ctx, @@ -403,13 +1526,17 @@ class HomeController extends Controller { const getParams = ctx.query; logData.method = getParams.method || ''; logData.v = getParams.v || ''; - // 验证必要参数 - if (!service.system.validateParams(getParams)) { - const errorMsg = '参数缺失或错误'; - const response = this.errorResponse(errorMsg, 'json'); + const requestCheck = service.system.validateRequestContext(getParams, ctx.headers); + if (!requestCheck.ok) { + const response = toFailure({ + message: requestCheck.message, + httpStatus: requestCheck.status, + code: requestCheck.code, + }); logData.result = response; service.system.saveLog(logData, startTime); ctx.body = response; + ctx.status = requestCheck.status; ctx.type = 'application/json'; return; } @@ -464,24 +1591,31 @@ class HomeController extends Controller { if (isLog) { service.system.saveLog(logData, startTime); } - ctx.body = result.data; + if (result.status && result.status !== 200) { + ctx.body = toFailure({ + message: result.message || '请求失败', + httpStatus: result.status, + code: result.code, + data: result.data || null, + }); + } else { + ctx.body = toSuccess(result.data); + } ctx.type = 'application/json'; ctx.status = result.status || 200; } catch (error) { ctx.status = 500; console.log(error); - const response = this.errorResponse('接口错误: ' + error.message, 'json'); + const response = toFailure({ + message: '接口错误: ' + error.message, + httpStatus: 500, + code: 500, + }); logData.result = typeof response === 'string' ? response : JSON.stringify(response); service.system.saveLog(logData, startTime); ctx.body = response; ctx.type = 'application/json'; } - } - async store() { - - } - async warehouse() { - } async system() { const { @@ -506,13 +1640,17 @@ class HomeController extends Controller { const getParams = ctx.query; logData.method = getParams.method || ''; logData.v = getParams.v || ''; - // 验证必要参数 - if (!service.system.validateParams(getParams)) { - const errorMsg = '参数缺失或错误'; - const response = this.errorResponse(errorMsg, 'json'); + const requestCheck = service.system.validateRequestContext(getParams, ctx.headers); + if (!requestCheck.ok) { + const response = toFailure({ + message: requestCheck.message, + httpStatus: requestCheck.status, + code: requestCheck.code, + }); logData.result = response; service.system.saveLog(logData, startTime); ctx.body = response; + ctx.status = requestCheck.status; ctx.type = 'application/json'; return; } @@ -569,13 +1707,26 @@ class HomeController extends Controller { if (isLog) { service.system.saveLog(logData, startTime); } - ctx.body = result.data; + if (result.status && result.status !== 200) { + ctx.body = toFailure({ + message: result.message || '请求失败', + httpStatus: result.status, + code: result.code, + data: result.data || null, + }); + } else { + ctx.body = toSuccess(result.data); + } ctx.type = 'application/json'; ctx.status = result.status || 200; } catch (error) { ctx.status = 500; console.log(error); - const response = this.errorResponse('接口错误: ' + error.message, 'json'); + const response = toFailure({ + message: '接口错误: ' + error.message, + httpStatus: 500, + code: 500, + }); logData.result = typeof response === 'string' ? response : JSON.stringify(response); service.system.saveLog(logData, startTime); ctx.body = response; diff --git a/app/controller/im.js b/app/controller/im.js new file mode 100644 index 0000000..34bd87f --- /dev/null +++ b/app/controller/im.js @@ -0,0 +1,68 @@ +const { Controller } = require('egg'); +const crypto = require('crypto'); + +// 统一的返回格式 +const result = { + code: 0, + message: '接口错误', + data: null, +}; + +module.exports = class ImController extends Controller { + async index() { + const { ctx } = this; + + // GET请求参数sign + const queryData = ctx.query; + const receivedSign = queryData.sign; + + // 解析POST请求的body数据 + const requestData = ctx.request.body; + const im_secret = this.config.im.secret; + + // 验证签名:将请求体的base64字符串与预设的密钥进行拼接后进行sha256哈希 + if (!receivedSign) { + ctx.body = { ...result, message: 'Missing signature parameter' }; + return; + } + + // 将请求体转换为base64字符串 + let bodyBase64; + try { + bodyBase64 = Buffer.from(JSON.stringify(requestData)).toString('base64'); + } catch (err) { + ctx.body = { ...result, message: 'Invalid request body' }; + return; + } + + // 计算期望的签名 + const expectedSign = crypto + .createHash('sha256') + .update(bodyBase64 + im_secret) + .digest('hex'); + + // 比对签名(使用时间恒定的比较方法防止时序攻击) + if (!crypto.timingSafeEqual(Buffer.from(receivedSign), Buffer.from(expectedSign))) { + ctx.body = { ...result, message: 'Invalid signature' }; + return; + } + + console.log('Received IM query data:', queryData); + console.log('Received IM request data:', requestData); + + const { method, data: data_data } = requestData || {}; + + // 通配method调用service层im的不同方法 + if (method && this.service.im[method]) { + try { + const { code, message, data } = await this.service.im[method](data_data); + ctx.body = { code, message, data }; + } catch (error) { + ctx.logger.error('IM service error:', error); + ctx.body = { ...result, message: 'Service execution failed' }; + } + } else { + ctx.body = { ...result, message: 'Invalid method' }; + } + } +}; diff --git a/app/controller/openapi.js b/app/controller/openapi.js new file mode 100644 index 0000000..24a959b --- /dev/null +++ b/app/controller/openapi.js @@ -0,0 +1,56 @@ +'use strict'; + +const { Controller } = require('egg'); +const { toSuccess, toFailure } = require('../lib/api_response'); + +class OpenapiController extends Controller { + /** + * 输出 openapi 统一失败响应。 + * @param {number} httpStatus HTTP 状态码。 + * @param {string} message 错误消息。 + * @param {number} [code=httpStatus] 业务错误码。 + * @return {void} 无返回值。 + */ + writeFailureResponse(httpStatus, message, code = httpStatus) { + const { ctx } = this; + ctx.status = httpStatus; + ctx.body = toFailure({ + message, + httpStatus, + code, + }); + ctx.type = 'application/json'; + } + + /** + * OpenAPI 统一入口,仅负责转发到 openapi service 并输出标准响应。 + * @return {Promise} 无返回值,结果写入 ctx.body。 + */ + async index() { + const { ctx } = this; + + try { + const result = await ctx.service.openapiEntry.processRequest(); + if (result.ok) { + ctx.status = Number(result.httpStatus) || 200; + ctx.body = toSuccess(result.data, result.message || 'ok'); + ctx.type = 'application/json'; + return; + } + + this.writeFailureResponse( + Number(result.httpStatus) || 500, + String(result.message || '请求失败'), + Number(result.code) || Number(result.httpStatus) || 500 + ); + ctx.type = 'application/json'; + return; + } catch (error) { + const message = String(error && error.message || '请求失败'); + this.writeFailureResponse(500, `接口错误: ${message}`, 500); + ctx.type = 'application/json'; + } + } +} + +module.exports = OpenapiController; diff --git a/app/controller/openapiCallback.js b/app/controller/openapiCallback.js new file mode 100644 index 0000000..a0c4c89 --- /dev/null +++ b/app/controller/openapiCallback.js @@ -0,0 +1,282 @@ +'use strict'; +const { Controller } = require('egg'); +const { CALLBACK_EVENTS } = require('../service/openapi/callbackRegistry'); + +/** + * OpenAPI 回调测试控制器。 + * 提供独立的回调调试页面,用于模拟回调推送并查看响应结果。 + */ +class OpenapiCallbackController extends Controller { + /** + * 渲染回调测试页面。 + * 页面支持选择已注册的回调事件,选中后自动填充与真实回调完全一致的 + * 完整报文体 { request: {...} }(奇门同层级,可编辑)、填入测试 URL 和密钥, + * 前端计算 MD5 签名后 POST 到目标 URL 并展示完整请求/响应。 + */ + async testPage() { + const { ctx } = this; + + const eventsJson = JSON.stringify(CALLBACK_EVENTS); + + ctx.type = 'text/html; charset=utf-8'; + ctx.body = ` + + + + + OpenAPI 回调测试 + + + +
    +
    +

    OpenAPI 回调测试

    +

    选择已注册的回调事件,自动填充与真实回调完全一致的完整报文体(奇门同层级 { request },可编辑),填入测试 URL 模拟推送。

    +

    + ← 返回 API 文档 +  |  + → 出站回调文档 +

    +
    + +
    + + +

    + +
    +
    + + +
    +
    + + +
    +
    + + + + + + + + + +
    点击发送后显示响应
    +
    +
    + + + +`; + } +} + +module.exports = OpenapiCallbackController; diff --git a/app/controller/tempFileWriter.js b/app/controller/tempFileWriter.js new file mode 100644 index 0000000..bb12dab --- /dev/null +++ b/app/controller/tempFileWriter.js @@ -0,0 +1,61 @@ +'use strict'; + +const { + Controller, +} = require('egg'); +const { toFailure, toSuccess } = require('../lib/api_response'); + +class TempFileWriterController extends Controller { + /** + * 触发一次临时 fileWriter 消费,并返回本次消费结果。 + * @return {Promise} 无返回值,结果写入响应体。 + */ + async consume() { + const { ctx, app } = this; + const { businessName, consumerName } = ctx.query; + + if (!businessName) { + ctx.status = 400; + ctx.body = toFailure({ + httpStatus: 400, + message: 'businessName 不能为空', + }); + return; + } + + const progressFilePath = app.fileWriter.getProgressFilePath( + businessName, + null, + consumerName || 'temp-http-consumer' + ); + const consumedRecords = []; + + try { + const result = await app.fileWriter.consumeFiles({ + businessName, + progressFilePath, + parseJson: ctx.query.parseJson !== 'false', + onRecord: async record => { + consumedRecords.push(record); + }, + }); + + ctx.body = toSuccess({ + businessName, + progressFilePath, + consumedRecords, + processedCount: result.processedCount, + progress: result.progress, + dataFiles: result.dataFiles, + }); + } catch (error) { + ctx.status = error && error.message === 'businessName 不能为空' ? 400 : 500; + ctx.body = toFailure({ + httpStatus: ctx.status, + message: error.message, + }); + } + } +} + +module.exports = TempFileWriterController; diff --git a/app/controller/template.js b/app/controller/template.js index 33c5868..fdc767b 100644 --- a/app/controller/template.js +++ b/app/controller/template.js @@ -8,5 +8,6 @@ class TemplateController extends Controller { const result = await service.systems.setting.printTemplate.getXmlByTemplate(ctx.params.id); ctx.body = result; } + } module.exports = TemplateController; diff --git a/app/controller/warehouse.js b/app/controller/warehouse.js new file mode 100644 index 0000000..d34a440 --- /dev/null +++ b/app/controller/warehouse.js @@ -0,0 +1,109 @@ +'use strict'; + +const { Controller } = require('egg'); +const crypto = require('crypto'); +const { toSuccess, toFailure } = require('../lib/api_response'); + +/** 日志内容长度上限 */ +const LOG_BODY_MAX = 65535; + +class WarehouseController extends Controller { + /** + * 输出仓库 API 统一失败响应。 + * @param {number} httpStatus HTTP 状态码。 + * @param {string} message 错误消息。 + * @param {number} [code=httpStatus] 业务错误码。 + * @return {void} 无返回值。 + */ + writeFailureResponse(httpStatus, message, code = httpStatus) { + const { ctx } = this; + ctx.status = httpStatus; + ctx.body = toFailure({ + message, + httpStatus, + code, + }); + ctx.type = 'application/json'; + } + + /** + * 截断日志内容到上限长度。 + * @param {string} value 原始字符串。 + * @return {string} 截断后的字符串。 + */ + truncateLogBody(value) { + const str = typeof value === 'string' ? value : JSON.stringify(value); + if (str.length > LOG_BODY_MAX) { + return str.substring(0, LOG_BODY_MAX); + } + return str; + } + + /** + * 仓库 API 统一入口,记录请求日志并转发到 warehouse service。 + * @return {Promise} 无返回值,结果写入 ctx.body。 + */ + async index() { + const { ctx, app } = this; + const startTime = Date.now(); + const logId = 'WL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'); + + const query = ctx.query || {}; + let result; + + try { + result = await ctx.service.warehouse.processRequest(); + + if (result.ok) { + ctx.status = Number(result.httpStatus) || 200; + ctx.body = toSuccess(result.data, result.message || 'ok'); + ctx.type = 'application/json'; + return; + } + + this.writeFailureResponse( + Number(result.httpStatus) || 500, + String(result.message || '请求失败'), + Number(result.code) || Number(result.httpStatus) || 500 + ); + ctx.type = 'application/json'; + return; + } catch (error) { + const message = String(error && error.message || '请求失败'); + this.writeFailureResponse(500, `接口错误: ${message}`, 500); + ctx.type = 'application/json'; + // 异常情况下 result 为 undefined,构造一个 fallback + result = { + ok: false, + httpStatus: 500, + message: error.message || '未知错误', + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, + }; + } finally { + // 异步写日志,不阻塞响应 + try { + const logData = { + log_id: logId, + app_key: (result && result.appKey) || String(query.app_key || '').trim() || null, + method: String(query.method || '').trim() || null, + warehouse_id: (result && result.warehouseId) || null, + url: ctx.request.href || null, + http_status: ctx.status || (result && result.httpStatus) || null, + body: this.truncateLogBody(ctx.request.rawBody || JSON.stringify(ctx.request.body || {})), + result: this.truncateLogBody(typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body || {})), + use_time: Date.now() - startTime, + created_at: new Date(), + }; + + app.fileWriter.writeRecord('warehouse-logs', logData).catch(writeErr => { + ctx.logger.error('[warehouse-log-sink] 写入文件失败: ' + writeErr.message); + }); + } catch (logErr) { + ctx.logger.error('[warehouse-log] 日志记录异常: ' + logErr.message); + } + } + } +} + +module.exports = WarehouseController; diff --git a/app/controller/wechatOpen.js b/app/controller/wechatOpen.js new file mode 100644 index 0000000..cd2c4bb --- /dev/null +++ b/app/controller/wechatOpen.js @@ -0,0 +1,754 @@ +'use strict'; + +const Controller = require('egg').Controller; +const wechatOpenCrypt = require('../lib/wechat_open_crypt'); +const WechatOpenClient = require('../lib/wechat_open_client'); + +/** + * 微信全网发布检测专用测试号(官方文档 5 组随机分配),用于日志标注公众号/小程序场景。 + * 步骤2=公众号被动回复;步骤3=公众号客服消息;步骤4=小程序客服消息。 + */ +const WECHAT_TEST_ACCOUNTS = { + mp: new Set([ + 'wx570bc396a51b8ff8', 'wx9252c5e0bb1836fc', 'wx8e1097c5bc82cde9', + 'wx14550af28c71a144', 'wxa35b9c23cfe664eb', + ]), + mini: new Set([ + 'wxd101a85aa106f53e', 'wxc39235c15087f6f3', 'wx7720d01d4b2a4500', + 'wx05d483572dcd5d8b', 'wx5910277cae6fd970', + ]), +}; + +/** + * 判断 appid 属于公众号/小程序测试号(用于日志标注,未知账号不影响处理)。 + * @param {string} appid 授权方 AppID。 + * @return {string} '公众号' | '小程序' | '未知账号'。 + */ +function detectAccountType(appid) { + if (WECHAT_TEST_ACCOUNTS.mp.has(appid)) return '公众号'; + if (WECHAT_TEST_ACCOUNTS.mini.has(appid)) return '小程序'; + return '未知账号'; +} + +/** + * autoReply 返回该值表示「显式不回复,响应体回空串」: + * 官方检测步骤3要求 5 秒内返回空串表明暂时不回复(不能回 success)。 + */ +const EMPTY_REPLY = '__EMPTY_REPLY__'; + +/** + * 微信开放平台第三方平台回调 Controller。 + * 接收微信服务器推送的授权事件(组件票据/授权成功/授权更新/取消授权), + * 对应路由 GET|POST /Authorization。 + */ +class WechatOpenController extends Controller { + /** + * 读取原始请求体(微信推送为 text/xml,bodyParser 默认不解析)。 + * @return {Promise} 原始请求体字符串。 + */ + async readRawBody() { + const { ctx } = this; + if (ctx.request.rawBody) { + return String(ctx.request.rawBody); + } + return await new Promise((resolve, reject) => { + let data = ''; + ctx.req.on('data', chunk => { + data += chunk; + }); + ctx.req.on('end', () => resolve(data)); + ctx.req.on('error', reject); + }); + } + + /** + * 授权事件接收入口(GET=URL 验证,POST=事件推送)。 + * @return {Promise} + */ + async authorization() { + const { ctx, app } = this; + const config = (app.config && app.config.wechatOpen) || {}; + + const signature = String(ctx.query.signature || ''); + const timestamp = String(ctx.query.timestamp || ''); + const nonce = String(ctx.query.nonce || ''); + const echostr = String(ctx.query.echostr || ''); + const msgSignature = String(ctx.query.msg_signature || ''); + const state = String(ctx.query.state || ''); + const authCode = String(ctx.query.auth_code || ''); + + // ─── URL 有效性验证(首次配置服务器地址时) ─────────────── + if (echostr) { + const valid = wechatOpenCrypt.verifyUrlSignature(config.token, signature, timestamp, nonce); + ctx.logger.info(`[wechatOpen] URL 验证 ${valid ? '通过' : '失败'}`); + ctx.body = valid ? echostr : '签名验证失败'; + return; + } + + // ─── 授权回跳(微信授权完成后重定向 GET,带 state/auth_code;state 缺失同样走 view 提示) ─── + if (ctx.method === 'GET') { + await this.handleAuthCallback(state, authCode); + return; + } + + try { + const rawBody = await this.readRawBody(); + if (!rawBody || !rawBody.trim()) { + ctx.logger.error('[wechatOpen] 接收到的推送体为空'); + ctx.body = 'fail'; + return; + } + + const decryptResult = wechatOpenCrypt.decryptMsg({ + token: config.token, + encodingAesKey: config.encoding_aes_key, + componentAppid: config.component_appid, + msgSignature, + timestamp, + nonce, + encryptedXml: rawBody, + }); + + if (decryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) { + ctx.logger.error(`[wechatOpen] 消息解密失败 code=${decryptResult.code} msg=${decryptResult.msg}`); + ctx.body = 'fail'; + return; + } + + const msgObj = wechatOpenCrypt.parseXml(decryptResult.msg); + const infoType = String(msgObj.InfoType || ''); + const event = String(msgObj.Event || ''); + ctx.logger.info(`[wechatOpen] 收到推送 InfoType=${infoType} Event=${event}`); + + // 小程序事件(如审核结果)用 Event 字段分发,组件事件用 InfoType 分发 + await this.handleEvent(event || infoType, msgObj); + + // 微信要求回显 success 表示处理成功 + ctx.body = 'success'; + } catch (e) { + ctx.logger.error(`[wechatOpen] 处理异常: ${e.message}`, e); + ctx.body = 'fail'; + } + } + + /** + * 授权回跳处理:凭 state 取回仓库信息,用 auth_code 换取令牌并落库绑定仓库。 + * @param {string} state 发起授权时缓存的随机 state。 + * @param {string} authCode 微信回跳携带的授权码。 + * @return {Promise} + */ + async handleAuthCallback(state, authCode) { + const { ctx, app } = this; + const client = new WechatOpenClient(ctx); + const render = viewData => ctx.render('wechat_auth_callback.html', viewData); + + if (!state) { + return render({ title: '微信授权结果', resultLevel: 'error', resultText: '缺少 state 参数,请从系统重新发起授权' }); + } + + const stateInfo = await client.getAuthState(state); + if (!stateInfo) { + return render({ title: '微信授权结果', resultLevel: 'error', resultText: '授权链接已过期或不存在,请重新发起授权' }); + } + if (!authCode) { + return render({ title: '微信授权结果', resultLevel: 'error', resultText: '缺少 auth_code 参数' }); + } + + try { + // 用授权码换取授权方令牌(不依赖 authorized 事件时序) + const authorizationInfo = await client.queryAuth(authCode); + const authorizerAppid = authorizationInfo.authorizer_appid; + if (!authorizerAppid) throw new Error('授权信息缺少 authorizer_appid'); + + const nowSec = Math.floor(Date.now() / 1000); + const fields = { + warehouse_id: stateInfo.warehouse_id || null, + authorizer_refresh_token: authorizationInfo.authorizer_refresh_token || null, + auth_time: nowSec, + func_info: JSON.stringify(authorizationInfo.func_info || []), + is_enabled: 1, + }; + + // 拉取授权方完整信息(昵称/头像/原始ID/认证类型/主体等),失败不阻断 + try { + const detail = await client.getAuthorizerDetail(authorizerAppid); + if (detail) { + Object.assign( + fields, + ctx.service.systems.wechat.buildAuthorizerPatch( + detail.authorizer_info, + detail.authorization_info || {} + ) + ); + } + } catch (e) { + ctx.logger.warn(`[wechatOpen] 获取授权方信息失败: ${e.message}`); + } + + const existing = await app.model.WechatApp.findOne({ where: { appid: authorizerAppid } }); + if (existing) { + await existing.update(fields); + } else { + await app.model.WechatApp.create({ appid: authorizerAppid, ...fields }); + // 首次授权:写入系统默认用户须知作为第一版(幂等) + await ctx.service.systems.wechat.ensureDefaultAgreementVersion(authorizerAppid); + } + + // 令牌写入 Redis 缓存(不落库) + await client.cacheSet( + `App:${authorizerAppid}:AuthorizerAccessToken`, + authorizationInfo.authorizer_access_token, + Math.max((authorizationInfo.expires_in || 7200) - 300, 60) + ); + await client.cacheSet( + `App:${authorizerAppid}:authorizer_refresh_token`, + authorizationInfo.authorizer_refresh_token, + 30 * 24 * 3600 + ); + + // state 一次性消费 + await client.clearAuthState(state); + + ctx.logger.info(`[wechatOpen] 授权回调成功 appid=${authorizerAppid} warehouse_id=${fields.warehouse_id}`); + return render({ + title: '微信授权结果', + resultLevel: 'success', + resultText: '授权成功,小程序已绑定仓库', + appid: authorizerAppid, + nickname: fields.nickname || '', + warehouseId: fields.warehouse_id || null, + }); + } catch (e) { + ctx.logger.error(`[wechatOpen] 授权回调处理失败: ${e.message}`, e); + return render({ + title: '微信授权结果', + resultLevel: 'error', + resultText: `授权处理失败:${e.message}`, + appid: '', + nickname: '', + warehouseId: null, + }); + } + } + + /** + * 按 InfoType 分发处理授权事件。 + * @param {string} infoType 事件类型。 + * @param {object} msgObj 解密后的消息对象。 + * @return {Promise} + */ + async handleEvent(infoType, msgObj) { + const { ctx, app } = this; + const client = new WechatOpenClient(ctx); + + switch (infoType) { + case 'component_verify_ticket': { + // 组件票据:每 10 分钟推送一次,缓存后用于换取 component_access_token + const ticket = String(msgObj.ComponentVerifyTicket || ''); + if (!ticket) { + ctx.logger.error('[wechatOpen] component_verify_ticket 事件缺少 ComponentVerifyTicket'); + return; + } + await client.saveComponentVerifyTicket(ticket); + ctx.logger.info(`[wechatOpen] 已保存 ComponentVerifyTicket(AppId: ${msgObj.AppId})`); + break; + } + + case 'authorized': + case 'updateauthorized': { + const authorizerAppid = String(msgObj.AuthorizerAppid || ''); + const authorizationCode = String(msgObj.AuthorizationCode || ''); + if (!authorizerAppid || !authorizationCode) { + ctx.logger.error(`[wechatOpen] ${infoType} 事件缺少 AuthorizerAppid/AuthorizationCode`); + return; + } + + // 暂存授权码(供后续换取令牌使用) + await client.saveAuthorizationCode(authorizerAppid, authorizationCode); + + // 用授权码换取授权方令牌与权限集合。 + // 注意:同一 authorization_code 只能 queryAuth 成功一次。微信全网发布检测时, + // authorized 事件与 QUERY_AUTH_CODE 文本消息几乎同时推送(实测仅差 1 秒), + // 文本分支也会用同一 code 调 queryAuth——谁先到谁消费。此处失败不抛错重试, + // 令牌可由文本分支/授权回跳链路换得,保证「授权成功」检测项始终响应 success。 + let authorizationInfo = null; + try { + authorizationInfo = await client.queryAuth(authorizationCode); + } catch (e) { + ctx.logger.warn(`[wechatOpen] ${infoType} 换取授权方令牌失败(可能已被 QUERY_AUTH_CODE 文本消费): ${e.message}`); + return; + } + const nowSec = Math.floor(Date.now() / 1000); + const fields = { + authorizer_refresh_token: authorizationInfo.authorizer_refresh_token || null, + auth_time: nowSec, + func_info: JSON.stringify(authorizationInfo.func_info || []), + is_enabled: 1, + }; + + // authorizer_access_token 存入 Redis 缓存(自动过期),不落库 + await client.cacheSet( + `App:${authorizerAppid}:AuthorizerAccessToken`, + authorizationInfo.authorizer_access_token, + Math.max((authorizationInfo.expires_in || 7200) - 300, 60) + ); + await client.cacheSet( + `App:${authorizerAppid}:authorizer_refresh_token`, + authorizationInfo.authorizer_refresh_token, + 30 * 24 * 3600 + ); + + // 拉取授权方完整信息(昵称/头像/原始ID/认证类型/主体等),失败不阻断 + try { + const detail = await client.getAuthorizerDetail(authorizerAppid); + if (detail) { + Object.assign( + fields, + ctx.service.systems.wechat.buildAuthorizerPatch( + detail.authorizer_info, + detail.authorization_info || {} + ) + ); + } + } catch (e) { + ctx.logger.warn(`[wechatOpen] 获取授权方信息失败: ${e.message}`); + } + + const existing = await app.model.WechatApp.findOne({ where: { appid: authorizerAppid } }); + if (existing) { + await existing.update(fields); + ctx.logger.info(`[wechatOpen] 已更新授权记录 appid=${authorizerAppid}`); + } else { + await app.model.WechatApp.create({ appid: authorizerAppid, ...fields }); + // 首次授权:写入系统默认用户须知作为第一版(幂等) + await ctx.service.systems.wechat.ensureDefaultAgreementVersion(authorizerAppid); + ctx.logger.info(`[wechatOpen] 已新增授权记录 appid=${authorizerAppid}`); + } + break; + } + + case 'unauthorized': { + const authorizerAppid = String(msgObj.AuthorizerAppid || ''); + if (!authorizerAppid) { + ctx.logger.error('[wechatOpen] unauthorized 事件缺少 AuthorizerAppid'); + return; + } + // 清理令牌缓存 + await client.clearAuthorizerCache(authorizerAppid); + // 停用授权记录(保留记录供追溯) + await app.model.WechatApp.update( + { is_enabled: 0 }, + { where: { appid: authorizerAppid } } + ); + ctx.logger.info(`[wechatOpen] 已停用授权记录 appid=${authorizerAppid}`); + break; + } + + case 'weapp_audit_success': { + // 代码审核通过:按小程序原始ID(ToUserName=gh_xxx)定位记录,状态置 2 + const originalId = String(msgObj.ToUserName || '').trim(); + if (!originalId) { + ctx.logger.error('[wechatOpen] weapp_audit_success 缺少 ToUserName'); + return; + } + await app.model.WechatApp.update( + { audit_status: 2, audit_reason: '' }, + { where: { user_name: originalId } } + ); + ctx.logger.info(`[wechatOpen] 审核通过 originalId=${originalId}`); + break; + } + + case 'weapp_audit_fail': { + // 代码审核驳回:状态置 3 并记录驳回原因 + const originalId = String(msgObj.ToUserName || '').trim(); + if (!originalId) { + ctx.logger.error('[wechatOpen] weapp_audit_fail 缺少 ToUserName'); + return; + } + await app.model.WechatApp.update( + { audit_status: 3, audit_reason: String(msgObj.Reason || '') }, + { where: { user_name: originalId } } + ); + ctx.logger.info(`[wechatOpen] 审核驳回 originalId=${originalId} reason=${msgObj.Reason || ''}`); + break; + } + + default: + ctx.logger.info(`[wechatOpen] 未处理的 InfoType: ${infoType}`); + break; + } + } + + /** + * 授权方(小程序/公众号)消息与事件推收入口,参考 PHP /index/index/events/appid/$APPID$。 + * GET=服务器地址 URL 有效性验证(echostr),POST=消息/事件推送(组件密钥加密)。 + * @return {Promise} + */ + async events() { + const { ctx, app } = this; + const { params } = ctx; + const appid = String((params && params.appid) || '').trim(); + const config = app.config.wechatOpen || {}; + + if (!appid) { + ctx.logger.error('[wechatOpen.events] 缺少 appid 参数'); + ctx.body = 'success'; + return; + } + + const signature = String(ctx.query.signature || ''); + const timestamp = String(ctx.query.timestamp || ''); + const nonce = String(ctx.query.nonce || ''); + const echostr = String(ctx.query.echostr || ''); + const msgSignature = String(ctx.query.msg_signature || ''); + + // ─── URL 有效性验证(首次配置服务器地址时) ─────────────── + if (echostr) { + ctx.body = await this.verifyEventUrl(appid, signature, timestamp, nonce, echostr); + return; + } + + // ─── 消息/事件推送 ─────────────────────────────────────── + try { + const rawBody = await this.readRawBody(); + if (!rawBody || !rawBody.trim()) { + ctx.logger.error(`[wechatOpen.events] 事件推送数据为空 appid=${appid}`); + ctx.body = 'success'; + return; + } + + const decryptResult = wechatOpenCrypt.decryptMsg({ + token: config.token, + encodingAesKey: config.encoding_aes_key, + componentAppid: config.component_appid, + msgSignature, + timestamp, + nonce, + encryptedXml: rawBody, + }); + + if (decryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) { + ctx.logger.error(`[wechatOpen.events] 消息解密失败 appid=${appid} code=${decryptResult.code} msg=${decryptResult.msg}`); + ctx.body = 'success'; + return; + } + + const data = wechatOpenCrypt.parseXml(decryptResult.msg); + ctx.logger.info(`[wechatOpen.events] 事件推送 appid=${appid}: ${decryptResult.msg}`); + + const msgType = String(data.MsgType || ''); + const event = String(data.Event || ''); + + // 文本消息全量落盘(WARN 级):生产日志只落 WARN+,用于检测场景定位回复问题 + if (msgType === 'text') { + ctx.logger.warn(`[wechatOpen.events] 收到文本消息 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} content=${JSON.stringify(String(data.Content || ''))}`); + } + + switch (msgType) { + case 'event': + await this.handlePushEvent(appid, event, data); + break; + + case 'text': { + // 记录文本消息并自动回复(被动回复返回加密 XML;客服消息场景返回空串) + const reply = await this.autoReply(appid, data, nonce); + if (reply === EMPTY_REPLY) { + // 官方检测步骤3/4:5 秒内返回空串表明暂时不回复,客服消息在后台异步发送 + ctx.logger.warn(`[wechatOpen.events] 返回空串响应(客服消息后台发送中) appid=${appid} type=${detectAccountType(appid)}`); + ctx.body = ''; + return; + } + if (reply) { + ctx.logger.warn(`[wechatOpen.events] 被动回复已返回 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} length=${reply.length}`); + ctx.type = 'application/xml'; + ctx.body = reply; + return; + } + break; + } + + case 'image': + await this.recordUserAction(appid, data, 'image'); + break; + + default: + ctx.logger.info(`[wechatOpen.events] 未处理的消息类型 appid=${appid} MsgType=${msgType}`); + break; + } + + // 微信要求回显 success 表示处理成功 + ctx.body = 'success'; + } catch (e) { + ctx.logger.error(`[wechatOpen.events] 处理异常 appid=${appid}: ${e.message}`, e); + ctx.body = 'success'; + } + } + + /** + * 验证事件推送服务器 URL(参考 PHP verifyEventUrl)。 + * 签名使用第三方平台(组件)Token 校验(与 /Authorization 的 URL 验证一致)。 + * appid 记录不存在时不阻断验证:首次配置服务器地址、微信全网发布检测等场景下, + * 微信会先发 echostr 验证 URL,此时可能尚无授权记录,仍按组件 Token 验签回显。 + * @param {string} appid 授权方 AppID。 + * @param {string} signature 微信回传签名。 + * @param {string} timestamp 时间戳。 + * @param {string} nonce 随机串。 + * @param {string} echostr 回显串。 + * @return {Promise} 验证通过返回 echostr,否则返回错误提示。 + */ + async verifyEventUrl(appid, signature, timestamp, nonce, echostr) { + const { ctx, app } = this; + + // 对应小程序应已授权登记;未登记仅告警,不阻断 URL 验证 + const record = await app.model.WechatApp.findOne({ where: { appid } }); + if (!record) { + ctx.logger.warn(`[wechatOpen.events] URL 验证:appid 尚无授权记录(首次配置或检测场景),仍按组件 Token 验签 appid=${appid}`); + } + + const config = app.config.wechatOpen || {}; + const valid = wechatOpenCrypt.verifyUrlSignature(config.token, signature, timestamp, nonce); + ctx.logger.info(`[wechatOpen.events] URL 验证 appid=${appid} ${valid ? '通过' : '失败'}`); + return valid ? echostr : '验证失败'; + } + + /** + * 处理事件类型推送(MsgType=event,参考 PHP handleEvent)。 + * @param {string} appid 授权方 AppID。 + * @param {string} event 事件类型(subscribe/unsubscribe/SCAN/CLICK/VIEW/TEMPLATESENDJOBFINISH)。 + * @param {object} data 解密后的消息对象。 + * @return {Promise} + */ + async handlePushEvent(appid, event, data) { + const { ctx } = this; + const openid = String(data.FromUserName || ''); + + switch (event) { + case 'subscribe': + // 关注事件:记录行为并发送欢迎消息(客服消息,非被动回复) + await this.recordUserAction(appid, data, 'subscribe'); + await this.sendWelcomeMessage(appid, openid); + break; + + case 'unsubscribe': + await this.recordUserAction(appid, data, 'unsubscribe'); + break; + + case 'SCAN': + case 'CLICK': + case 'VIEW': + case 'TEMPLATESENDJOBFINISH': + await this.recordUserAction(appid, data, event); + break; + + default: + ctx.logger.info(`[wechatOpen.events] 未处理的事件类型 appid=${appid} Event=${event}`); + break; + } + } + + /** + * 文本消息自动回复(参考 PHP autoReply):先记录用户行为, + * 关键词命中生成被动回复并加密;QUERY_AUTH_CODE 场景改为客服消息直发、不被动回复。 + * @param {string} appid 授权方 AppID。 + * @param {object} data 解密后的消息对象。 + * @param {string} nonce 微信回传随机串(用于回复签名)。 + * @return {Promise} 加密回复 XML;无需被动回复时返回空串。 + */ + async autoReply(appid, data, nonce) { + const { ctx, app } = this; + const config = app.config.wechatOpen || {}; + + const openid = String(data.FromUserName || ''); + const appName = String(data.ToUserName || ''); + const content = String(data.Content || ''); + + // 记录用户文本消息 + await this.recordUserAction(appid, data, 'text'); + + try { + const lowerContent = content.toLowerCase(); + let replyContent = ''; + + // 关键词回复(与参考实现保持一致) + if (content.includes('你好') || lowerContent.includes('hello')) { + replyContent = '你好!有什么可以帮您的吗?'; + } else if (content.includes('帮助') || lowerContent.includes('help')) { + replyContent = '输入以下关键词获取帮助:\n1. 功能 - 查看功能列表\n2. 关于 - 了解更多信息'; + } else if (content.includes('TESTCOMPONENT_MSG_TYPE_TEXT')) { + replyContent = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback'; + ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤2-公众号被动回复 appid=${appid} type=${detectAccountType(appid)}`); + } else if (content.includes('QUERY_AUTH_CODE')) { + // 微信全网发布检测场景(官方步骤3=公众号客服/步骤4=小程序客服):文本携带授权码 + // (QUERY_AUTH_CODE:)。处理:响应体直接回空串(官方要求「5 秒内返回空串 + // 表明暂时不回复」),客服消息由后台异步发送(含前缀/去前缀双发)。 + const authCode = content.replace('QUERY_AUTH_CODE:', '').trim(); + const accountType = detectAccountType(appid); + ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤3/4-客服消息回复 appid=${appid} type=${accountType} code=${authCode}`); + + // 官方要求:不被动回复,响应体回空串;客服消息流程放入后台异步执行 + ctx.runInBackground(async () => { + const client = new WechatOpenClient(ctx); + let refreshToken = null; + let tokenSource = ''; + + // 1) 优先使用已存储的 refresh_token(authorized 事件已换取):Redis → DB。 + // 真实业务中用户消息不带 code,只能依赖存储的令牌(与 PHP 参考实现一致)。 + refreshToken = await client.cacheGet(`App:${appid}:authorizer_refresh_token`); + if (refreshToken) { + tokenSource = 'redis'; + } else { + try { + const record = await app.model.WechatApp.findOne({ where: { appid } }); + if (record && record.authorizer_refresh_token) { + refreshToken = String(record.authorizer_refresh_token); + tokenSource = 'db'; + } + } catch (e) { + ctx.logger.warn(`[wechatOpen.events] 读取授权记录失败: ${e.message}`); + } + } + + // 2) 存储令牌不存在(文本消息先于 authorized 事件到达),用文本携带的授权码换取(官方检测意图) + if (!refreshToken && authCode) { + try { + const authorizationInfo = await client.queryAuth(authCode); + refreshToken = authorizationInfo.authorizer_refresh_token || null; + if (refreshToken) { + tokenSource = 'query_auth'; + await client.cacheSet(`App:${appid}:authorizer_refresh_token`, refreshToken, 30 * 24 * 3600); + if (authorizationInfo.authorizer_access_token) { + await client.cacheSet( + `App:${appid}:AuthorizerAccessToken`, + authorizationInfo.authorizer_access_token, + Math.max((authorizationInfo.expires_in || 7200) - 300, 60) + ); + } + } + } catch (e) { + ctx.logger.warn(`[wechatOpen.events] QUERY_AUTH_CODE 换取令牌失败: ${e.message}`); + } + } + + ctx.logger.warn(`[wechatOpen.events] 客服回复令牌来源 source=${tokenSource || 'none'} appid=${appid} has_token=${!!refreshToken}`); + + // 客服消息双发兼容:官方文档字面要求回复 _from_api; + // 检测脚本可能按「去掉 queryauthcode@@@ 标记前缀的真实 code」核对,两条都发确保命中。 + const codeValue = authCode.trim(); + const pureCode = codeValue.startsWith('queryauthcode@@@') + ? codeValue.slice('queryauthcode@@@'.length) + : codeValue; + try { + await this.sendMessage(appid, openid, `${codeValue}_from_api`, refreshToken); + if (pureCode && pureCode !== codeValue) { + await this.sendMessage(appid, openid, `${pureCode}_from_api`, refreshToken); + } + } catch (e) { + ctx.logger.error(`[wechatOpen.events] 客服消息发送异常: ${e.message}`); + } + }); + + // 响应体回空串(不被动回复,与 PHP 参考实现一致) + return EMPTY_REPLY; + } else { + replyContent = `收到您的消息:${content}\n我会尽快回复您!`; + } + + // 组装明文回复 XML(ToUserName=用户 openid,FromUserName=公众号原始 ID) + const plainXml = '' + + `` + + `` + + `${Math.floor(Date.now() / 1000)}` + + '' + + `` + + ''; + + const encryptResult = wechatOpenCrypt.encryptMsg({ + token: config.token, + encodingAesKey: config.encoding_aes_key, + componentAppid: config.component_appid, + plainXml, + nonce, + }); + + if (encryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) { + ctx.logger.error(`[wechatOpen.events] 回复消息加密失败 code=${encryptResult.code}`); + return ''; + } + return encryptResult.encryptedXml; + } catch (e) { + ctx.logger.error(`[wechatOpen.events] 自动回复失败: ${e.message}`); + return ''; + } + } + + /** + * 记录用户行为到 Redis(参考 PHP recordUserAction)。 + * @param {string} appid 授权方 AppID。 + * @param {object} data 解密后的消息对象。 + * @param {string} action 行为类型(subscribe/unsubscribe/SCAN/CLICK/VIEW/text/image 等)。 + * @return {Promise} + */ + async recordUserAction(appid, data, action) { + const { ctx } = this; + const client = new WechatOpenClient(ctx); + const openid = String(data.FromUserName || ''); + if (!openid) return; + + const nowSec = Math.floor(Date.now() / 1000); + const key = `UserAction:${appid}:${openid}:${nowSec}`; + await client.cacheSet(key, JSON.stringify({ + appid, + openid, + action, + data, + time: nowSec, + }), 86400); + } + + /** + * 发送客服文本消息(refreshToken 优先,其次从 DB 兜底读取,避免 Redis 丢失导致失败)。 + * @param {string} appid 授权方 AppID。 + * @param {string} openid 用户 openid。 + * @param {string} content 文本内容。 + * @param {string} [refreshToken] 授权方刷新令牌(调用方已获取时传入)。 + * @return {Promise} 微信原始响应。 + */ + async sendMessage(appid, openid, content, refreshToken) { + const { ctx, app } = this; + const client = new WechatOpenClient(ctx); + + // Redis 中的 refresh token 可能丢失,从 wms_wechat_app 兜底读取 + let token = refreshToken || null; + try { + const record = await app.model.WechatApp.findOne({ where: { appid } }); + if (record && record.authorizer_refresh_token) { + token = String(record.authorizer_refresh_token); + } + } catch (e) { + ctx.logger.warn(`[wechatOpen.events] 读取授权记录失败 appid=${appid}: ${e.message}`); + } + + ctx.logger.warn(`[wechatOpen.events] 发送客服消息 appid=${appid} openid=${openid} content=${JSON.stringify(content)} has_token=${!!token}`); + const result = await client.sendCustomMessage(appid, openid, content, token); + ctx.logger.warn(`[wechatOpen.events] 客服消息发送结果: ${JSON.stringify(result)}`); + return result; + } + + /** + * 发送关注欢迎消息(失败仅记录日志,不阻断事件处理)。 + * @param {string} appid 授权方 AppID。 + * @param {string} openid 用户 openid。 + * @return {Promise} + */ + async sendWelcomeMessage(appid, openid) { + const { ctx } = this; + try { + await this.sendMessage(appid, openid, '欢迎关注!感谢您的支持!'); + } catch (e) { + ctx.logger.error(`[wechatOpen.events] 发送欢迎消息失败: ${e.message}`); + } + } +} + +module.exports = WechatOpenController; diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 38e3fab..7a26592 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -21,6 +21,8 @@ module.exports = { LOCATION: { code: 'location', name: '库位管理' }, USER: { code: 'user', name: '用户管理' }, SYSTEM: { code: 'system', name: '系统管理' }, + ENTRY: { code: 'entry', name: '入库管理' }, + STORE: { code: 'store', name: '货主管理' }, }, /** @@ -56,8 +58,50 @@ module.exports = { ORDER_PACKED: '订单打包', ORDER_SHIPPED: '订单发货', ORDER_COMPLETE: '订单完成', + ORDER_UPDATE_PLATFORM: '更新平台', + ORDER_UPDATE_EXPRESS: '更新快递', + ORDER_UPDATE_ADDRESS: '更新地址', + ORDER_CLONE_SOURCE: '克隆来源订单', + ORDER_CLONE_TARGET: '克隆目标订单', + ORDER_MANUAL_WAYBILL: '手工录入运单号', + ORDER_RESOLVE_EXCEPTION: '处理异常', + ORDER_INTERCEPT_CONFIRM: '确认拦截', + ORDER_PLATFORM_FALLBACK: '平台降级', + ORDER_EXPRESS_FALLBACK: '快递降级', + ORDER_EXPRESS_POLICY_MATCH: '策略命中', + ORDER_WAVE_UPDATE: '更新波次', + ORDER_WAVE_ASSIGN: '分配波次', + ORDER_WAVE_REMOVE: '移出波次', + ORDER_WAVE_CANCEL: '取消波次', + ORDER_WAVE_GRAB: '抓取波次', + ORDER_WAVE_AUTO_GROUP: '自动加团', + ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次', + ORDER_WAVE_CLAIM: '领取波次', + ORDER_CONFIRM_PRINT: '确认打印', + ORDER_AUTO_EXPRESS_SKIP: '跳过自动分配快递', + ORDER_PICK_COMPLETE: '拣货完成', + ORDER_RECHECK: '订单复核', + ORDER_RECHECK_BATCH: '批量复核', + ORDER_SYNC: '同步订单', + ORDER_WEIGH: '称重', + ORDER_PACKAGE_MATERIAL_BIND: '绑定包材', + ORDER_STORAGE_ALLOCATE_SUCCESS: '分配储位成功', + ORDER_STORAGE_ALLOCATE_FAILED: '分配储位失败', + ORDER_STORAGE_UNALLOCATE_SUCCESS: '取消分配储位成功', + ORDER_STORAGE_UNALLOCATE_FAILED: '取消分配储位失败', + ORDER_EXPRESS_ALLOCATE_SUBMITTED: '分配快递任务已提交', + ORDER_EXPRESS_ALLOCATE_FAILED: '分配快递失败', + ORDER_INTERCEPT_REQUEST: '请求订单拦截', + ORDER_INTERCEPT_CANCEL: '解除订单拦截', + ORDER_RETURN_RECEIVED: '退回收到', + ORDER_LOCK: '订单锁定', + ORDER_UNLOCK: '订单解锁', + ORDER_AUTO_OUTBOUND: '自动出库', // 库存管理 + STORAGE_TRANSFER_LOCATION: '库位调拨', + STORAGE_TRANSFER_BY_PRODUCT: '商品调拨', + STORAGE_UPDATE_EXPIRY: '维护库存效期', STOCK_IN: '商品入库', STOCK_OUT: '商品出库', STOCK_ADJUST: '库存调整', @@ -103,6 +147,35 @@ module.exports = { UPDATE_IMAGES: '更新图片', UPDATE_BARCODE: '更新条码', BIND: '绑定', + + // 入库管理 + QUICK_PUTAWAY: '快捷入库', + + // 收货管理 + RECEIVING_CREATE: '创建收货单', + RECEIVING_COMPLETE: '完成收货', + RECEIVING_CANCEL: '作废收货单', + RECEIVING_BATCH_CANCEL: '批量作废收货单', + RECEIVING_BIND_STORE: '绑定货主', + RECEIVING_ADD_DETAIL: '新增收货明细', + RECEIVING_DELETE_DETAIL: '删除收货明细', + RECEIVING_BIND_PRODUCT: '绑定商品', + RECEIVING_UPDATE_DETAIL: '修改收货明细', + RECEIVING_UPDATE: '修改收货单', + RECEIVING_REVIEW: '审核收货单', + RECEIVING_REJECT: '驳回收货单', + + // 货主管理 + STORE_CREATE: '创建货主', + STORE_CREATE_WAREHOUSE: '创建仓库', + STORE_SIGN: '签约货主', + STORE_OPEN_ACCOUNT: '仓库代开户', + STORE_RENAME: '修改签约备注', + STORE_UNBIND: '解绑签约', + STORE_SAVE_POLICY_CONFIG: '保存签约策略配置', + STORE_SAVE_API_CONFIG: '保存接口配置', + STORE_DELETE_API_CONFIG: '删除接口配置', + STORE_ADJUST_PRINT_QUANTITY: '调整面单余额', }, /** @@ -125,6 +198,9 @@ module.exports = { SUCCESS: '成功', FAILED: '失败', PROCESSING: '处理中', + SUBMITTED: '已提交', + RUNNING: '进行中', + NOT_FOUND: '未找到', }, /** @@ -161,7 +237,7 @@ module.exports = { /** * 获取指定业务类型的操作编码 - * @param businessType + * @param {string} businessType 业务类型 */ getOperationCodesByBusinessType(businessType) { const prefix = businessType.toUpperCase() + '_'; @@ -178,8 +254,8 @@ module.exports = { /** * 验证操作编码是否属于指定业务类型 - * @param code - * @param businessType + * @param {string} code 操作编码 + * @param {string} businessType 业务类型 */ validateOperationCode(code, businessType) { if (!businessType) return true; diff --git a/app/extend/application.js b/app/extend/application.js index 04e6d89..7a0c99e 100644 --- a/app/extend/application.js +++ b/app/extend/application.js @@ -1,14 +1,296 @@ -class MessageClass { - async action() { +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); +} + +/** + * 使用超时保护执行 Redis 命令,避免 Redis 卡顿拖慢接口响应。 + * + * @param {Object} app 应用实例。 + * @param {Promise<*>} commandPromise Redis 命令 Promise。 + * @param {string} commandName Redis 命令名。 + * @return {Promise<*>} Redis 命令执行结果。 + */ +async function withRedisCommandTimeout(app, commandPromise, commandName) { + const timeoutConfig = Number(app && app.config ? app.config.cacheRedisCommandTimeoutMs : 0); + const timeoutMs = Number.isFinite(timeoutConfig) && timeoutConfig > 0 ? timeoutConfig : 800; + + let timeoutId = null; + + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + const timeoutError = new Error(`Redis 命令执行超时: ${commandName}, timeout=${timeoutMs}ms`); + timeoutError.code = 'CACHE_REDIS_TIMEOUT'; + reject(timeoutError); + }, timeoutMs); + + if (timeoutId && typeof timeoutId.unref === 'function') { + timeoutId.unref(); + } + }); + + try { + return await Promise.race([ commandPromise, timeoutPromise ]); + } finally { + if (timeoutId) { + clearTimeout(timeoutId); + } } } -const soap = require('soap'); -const MESSAGE_CLASS = Symbol('Application#Message'); module.exports = { + get businessDict() { + return businessDict; + }, + getBusinessTypeName(code) { + const dict = this.businessDict.BUSINESS_TYPE || {}; + for (const key in dict) { + if (dict[key].code === code) { + return dict[key].name; + } + } + return code; + }, + getOperationCodeName(code) { + return this.businessDict.OPERATION_CODE?.[code] || code; + }, + getPlatformName(code) { + return this.businessDict.PLATFORM_CODE?.[code] || code; + }, + getExternalLogTypeName(type) { + return this.businessDict.EXTERNAL_LOG_TYPE?.[type] || type; + }, + 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); + }, async wsdl(methodName, args) { try { - const wsdlUrl = "http://ye4s.com/webservice/ws?wsdl"; + const wsdlUrl = 'http://ye4s.com/webservice/ws?wsdl'; const obj = {}; args.forEach((value, index) => { obj['arg' + index] = value; @@ -17,47 +299,111 @@ 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 withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del'); + } 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 withRedisCommandTimeout(this, cacheRedis.setex(cacheKey, ttl, JSON.stringify(data)), 'setex'); + + 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); - } - return null; - } catch (error) { - this.logger.error('[CacheGetError] Failed to get cache', error.message, cacheKey); - return null; - } + setLocalCacheValue(this, cacheKey, data, ttl); }, - get Message() { - if (!this[MESSAGE_CLASS]) { - // 返回类本身,不是实例 - this[MESSAGE_CLASS] = MessageClass; + /** + * 删除缓存。 + * + * Redis 可用时优先删除 Redis;无论 Redis 是否可用,都会同步清理进程内缓存。 + * + * @param {string} cacheKey 缓存键。 + * @return {Promise} + */ + async delCacheAsync(cacheKey) { + if (!cacheKey) { + return; } - return this[MESSAGE_CLASS]; + + const cacheRedis = getRedisCacheClient(this); + + if (cacheRedis && typeof cacheRedis.del === 'function') { + try { + await withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del'); + } catch (error) { + const logger = getCacheLogger(this); + if (logger && typeof logger.warn === 'function') { + logger.warn('[CacheRedisDeleteError] Redis 删除缓存失败', error.message, cacheKey); + } + } + } + + deleteLocalCacheValue(this, cacheKey); + }, + /** + * 读取缓存。 + * + * 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 withRedisCommandTimeout(this, cacheRedis.get(cacheKey), 'get'); + 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 getLocalCacheValue(this, cacheKey); }, }; diff --git a/app/lib/api_log_sink.js b/app/lib/api_log_sink.js new file mode 100644 index 0000000..3e7876a --- /dev/null +++ b/app/lib/api_log_sink.js @@ -0,0 +1,190 @@ +// app/lib/api_log_sink.js +'use strict'; + +/** + * 接口日志落盘器:接口流水经 Egg 日志写出(`wms_system_log` 表已下线删除)。 + * + * 设计要点: + * 1. 只使用 Egg 自带 logger(`app.getLogger('apiLog')`),不自行操作 fs —— + * egg-logger 的 FileTransport 以 O_APPEND 追加写、多 worker 共写同一文件、 + * 自动创建目录并按天轮转,避免自建写流带来的「轮转后句柄失效 / ENOSPC 崩进程 / + * 每请求建流导致 fd 泄漏 / 退出前未 flush」等问题。 + * 2. 一行一条记录,形如 `HH:mm:ss {JSON}`: + * 前缀是**本地时区的时分秒**,只给人眼定位用(tail/grep 时有个时间锚点), + * 机器解析请用行内的 `created_at`(ISO 8601 UTC,无时区歧义,与前缀为同一时刻); + * 前缀之后是沿用旧 `wms_system_log` 表结构的平铺 JSON(不嵌套,首字符是 `{`), + * 可直接用 grep 搜索;用 jq 时先剥前缀:`jq -R 'sub("^[0-9:]+ "; "") | fromjson'`。 + * 3. 写入失败绝不影响接口返回:异常由调用方兜底,只记 app logger。 + */ + +/** body / result 截断长度:沿用旧 wms_system_log 入库时的长文本上限(65535) */ +const TEXT_LIMIT = 65535; + +/** customLogger.apiLog 缺失的告警只打一次,避免每请求刷屏 */ +let warnedApiLogMissing = false; + +/** + * 归一化为字符串,必要时截断。 + * @param {*} value 原始值。 + * @param {number} [limit] 截断长度(正数才生效),默认不截断。 + * @return {string} 字符串结果。 + */ +function toText(value, limit) { + if (value === undefined || value === null) { + return ''; + } + // 对象/数组一律 JSON 序列化:调用方若漏了 JSON.stringify(例如 controller 直接把 + // 响应对象塞进 logData.result),String() 会得到 "[object Object]" 而丢掉内容。 + let text; + if (typeof value === 'string') { + text = value; + } else if (typeof value === 'object') { + try { + text = JSON.stringify(value); + } catch (e) { + text = String(value); + } + } else { + text = String(value); + } + if (Number(limit) > 0 && text.length > Number(limit)) { + return text.substring(0, Number(limit)); + } + return text; +} + +/** + * 构造一行平铺记录。 + * + * 字段与顺序沿用旧 `wms_system_log` 入库时的入参: + * method / v / url / headers / auth / created_at / body / result / use_time / store_id / device。 + * `created_at` 统一写 ISO 8601(UTC,带 Z):与原入库是同一时刻,但没有时区歧义。 + * + * @param {object} logData 原始日志数据。 + * @param {object} [options] 选项。 + * @param {number} [options.startTime] 请求开始时间戳(ms),用于计算 use_time。 + * @param {number} [options.useTime] 直接指定耗时(ms),优先于 startTime。 + * @param {string} [options.device] 设备标识。 + * @param {Date} [options.createdAt] 记录时间,默认当前时间。 + * @return {object} 平铺记录对象。 + */ +function buildRecord(logData, options = {}) { + const source = logData && typeof logData === 'object' ? logData : {}; + const createdAt = options.createdAt instanceof Date ? options.createdAt : new Date(); + + let useTime = 0; + if (options.useTime !== undefined) { + useTime = Number(options.useTime); + } else if (Number(options.startTime) > 0) { + useTime = Date.now() - Number(options.startTime); + } + if (!Number.isFinite(useTime) || useTime < 0) { + useTime = 0; + } + + return { + method: toText(source.method), + v: toText(source.v), + url: toText(source.url), + headers: toText(source.headers), + auth: toText(source.auth), + created_at: createdAt.toISOString(), + body: toText(source.body, TEXT_LIMIT), + result: toText(source.result, TEXT_LIMIT), + use_time: useTime, + store_id: source.store_id || null, + device: toText(options.device), + }; +} + +/** + * customLogger.apiLog 缺失时的显式告警(每个 worker 只打一次)。 + * + * egg 的 `app.getLogger(name)` 对未声明的 name 返回 null 而不抛错, + * 若不处理就会「日志静默消失、且无任何报错」。 + * 生产 config 不参与 deploy,「代码已上线、配套配置没上」极易发生,故必须显式报出来。 + * + * @param {Egg.Application} app Egg 应用实例。 + * @return {void} + */ +function warnApiLogMissing(app) { + if (warnedApiLogMissing) { + return; + } + warnedApiLogMissing = true; + const logger = app && typeof app.getLogger === 'function' ? app.getLogger('logger') : null; + if (logger && typeof logger.error === 'function') { + logger.error( + '[api_log_sink] config.customLogger.apiLog 未配置,接口日志不会落盘!' + + '请在 config.default.js 补上 customLogger.apiLog' + + '(生产 config 不参与 deploy,需手工同步到线上)。' + ); + } +} + +/** + * 两位补零。 + * @param {number} value 待补零的数字。 + * @return {string} 补零后的字符串。 + */ +function pad2(value) { + return String(value).padStart(2, '0'); +} + +/** + * 生成日志行的时间前缀(本地时区 `HH:mm:ss`)。 + * + * 整行内容本身是完整 JSON(首字符是 `{`),直接 tail/grep 时没有时间锚点, + * 故在行首加一个本地时间的时分秒前缀。前缀只给人看: + * 它与行内 `created_at` 取同一时刻,仅表达方式不同(本地 `HH:mm:ss` vs UTC ISO 8601)。 + * 日期无需前缀 —— 日志按天轮转为 `wms-api.log.YYYY-MM-DD`,日期由文件名提供。 + * + * @param {Date|string} [value] 记录时间;缺省或非法时回退当前时间。 + * @return {string} `HH:mm:ss` 形式的前缀。 + */ +function formatTimePrefix(value) { + const parsed = value instanceof Date ? value : new Date(value || Date.now()); + const date = Number.isNaN(parsed.getTime()) ? new Date() : parsed; + return `${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`; +} + +/** + * 写出接口日志。 + * + * 只落 Egg 日志文件(`config.customLogger.apiLog`);wms_system_log 表已下线, + * 不再存在任何入库分支。 + * + * @param {Egg.Application} app Egg 应用实例。 + * @param {object} payload 负载。 + * @param {object} payload.logData 原始日志数据。 + * @param {number} [payload.startTime] 请求开始时间戳(ms)。 + * @param {number} [payload.useTime] 直接指定耗时(ms)。 + * @param {string} [payload.device] 设备标识。 + * @param {Date} [payload.createdAt] 记录时间。 + * @return {Promise} 实际写出的平铺记录。 + */ +async function write(app, payload = {}) { + const record = buildRecord(payload.logData, { + startTime: payload.startTime, + useTime: payload.useTime, + device: payload.device, + createdAt: payload.createdAt, + }); + + const logger = app && typeof app.getLogger === 'function' ? app.getLogger('apiLog') : null; + if (logger) { + // 一行一条:`HH:mm:ss {完整 JSON}`,前缀与行内 created_at 是同一时刻 + logger.info(`${formatTimePrefix(record.created_at)} ${JSON.stringify(record)}`); + } else { + warnApiLogMissing(app); + } + + return record; +} + +module.exports = { + TEXT_LIMIT, + buildRecord, + formatTimePrefix, + write, +}; diff --git a/app/lib/api_response.js b/app/lib/api_response.js new file mode 100644 index 0000000..a6ebac4 --- /dev/null +++ b/app/lib/api_response.js @@ -0,0 +1,59 @@ +'use strict'; + +function nowTimestamp() { + return Math.floor(Date.now() / 1000); +} + +function isObject(value) { + return value && typeof value === 'object' && !Array.isArray(value); +} + +function isStandardPayload(payload) { + return isObject(payload) + && Object.prototype.hasOwnProperty.call(payload, 'flag') + && Object.prototype.hasOwnProperty.call(payload, 'code') + && Object.prototype.hasOwnProperty.call(payload, 'message'); +} + +function toSuccess(payload, message = 'ok') { + if (isStandardPayload(payload)) { + const normalized = { + ...payload, + flag: payload.flag === true || payload.flag === 'success' ? 'success' : payload.flag, + }; + if (!Object.prototype.hasOwnProperty.call(normalized, 'timestamp')) { + normalized.timestamp = nowTimestamp(); + } + return normalized; + } + + return { + flag: 'success', + code: 1, + message, + data: payload ?? null, + timestamp: nowTimestamp(), + }; +} + +function toFailure(options = {}) { + const { + message = '请求失败', + httpStatus = 500, + code, + data = null, + } = options; + + return { + flag: 'failure', + code: typeof code === 'number' ? code : httpStatus, + message, + data, + timestamp: nowTimestamp(), + }; +} + +module.exports = { + toSuccess, + toFailure, +}; diff --git a/app/lib/api_sign.js b/app/lib/api_sign.js new file mode 100644 index 0000000..68fa0be --- /dev/null +++ b/app/lib/api_sign.js @@ -0,0 +1,195 @@ +'use strict'; + +const crypto = require('crypto'); + +const DEFAULT_IGNORE_KEYS = [ 'sign', 'signature' ]; + +/** + * 判断输入是否为普通对象。 + * @param {*} value 任意输入值。 + * @return {boolean} 是否为普通对象。 + */ +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * 将忽略字段列表归一化为小写集合。 + * @param {string[]} [ignoreKeys=[]] 忽略字段数组。 + * @return {Set} 小写忽略字段集合。 + */ +function normalizeIgnoreKeySet(ignoreKeys = []) { + const rawKeys = Array.isArray(ignoreKeys) + ? ignoreKeys + : []; + + return new Set(rawKeys.map(key => String(key).toLowerCase())); +} + +/** + * 对任意值做稳定序列化,确保对象键顺序固定。 + * @param {*} value 待序列化值。 + * @return {string} 稳定序列化后的字符串。 + */ +function stableStringify(value) { + if (value === undefined) { + return ''; + } + + if (value === null || typeof value !== 'object') { + return JSON.stringify(value); + } + + if (Array.isArray(value)) { + const serializedItems = value.map(item => stableStringify(item)); + return `[${serializedItems.join(',')}]`; + } + + if (!isPlainObject(value)) { + return JSON.stringify(value); + } + + const keys = Object.keys(value).sort(); + const serializedFields = keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`); + return `{${serializedFields.join(',')}}`; +} + +/** + * 归一化参数值为可拼接字符串。 + * @param {*} value 参数值。 + * @return {string} 归一化后的字符串。 + */ +function normalizeParamValue(value) { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + return stableStringify(value); + } + + return String(value); +} + +/** + * 构建按 key 字母序排列的 query 参数串。 + * @param {Object} [params={}] 请求 query 参数对象。 + * @param {string[]} [ignoreKeys=[]] 需要忽略的字段名列表。 + * @return {string} 规范化后的 query 串,格式为 key=value&key2=value2。 + */ +function buildCanonicalQuery(params = {}, ignoreKeys = []) { + if (!isPlainObject(params)) { + throw new Error('query 参数必须是对象'); + } + + const ignoreKeySet = normalizeIgnoreKeySet(ignoreKeys); + const keys = Object.keys(params) + .filter(key => !ignoreKeySet.has(String(key).toLowerCase())) + .filter(key => params[key] !== undefined) + .sort(); + + return keys.map(key => `${key}=${normalizeParamValue(params[key])}`).join('&'); +} + +/** + * 构建请求体签名,算法为 md5(稳定序列化后的 body)。 + * @param {*} body 请求体,可为对象、数组、字符串或空值。 + * @return {string} 小写十六进制 body 签名。 + */ +function buildBodySign(body) { + const serializedBody = typeof body === 'string' + ? body + : stableStringify(body); + + return crypto.createHash('md5').update(serializedBody, 'utf8').digest('hex') + .toLowerCase(); +} + +/** + * 计算请求签名。 + * 参与签名字符串 = canonicalQuery + selfAppSecret + bodySign。 + * 最终签名 = md5(参与签名字符串)。 + * @param {Object} options 签名参数。 + * @param {Object} [options.query={}] 请求 query 参数。 + * @param {*} [options.body] 请求体。 + * @param {string} options.selfAppSecret 密钥。 + * @param {string[]} [options.ignoreKeys] 需要忽略的 query 字段。 + * @return {{ canonicalQuery: string, bodySign: string, sign: string }} 计算结果。 + */ +function signRequest({ query = {}, body, selfAppSecret, ignoreKeys } = {}) { + const normalizedSecret = String(selfAppSecret || '').trim(); + if (!normalizedSecret) { + throw new Error('selfAppSecret 不能为空'); + } + + const mergedIgnoreKeys = [ ...DEFAULT_IGNORE_KEYS, ...(Array.isArray(ignoreKeys) ? ignoreKeys : []) ]; + const canonicalQuery = buildCanonicalQuery(query, mergedIgnoreKeys); + const bodySign = buildBodySign(body); + const signText = `${canonicalQuery}${normalizedSecret}${bodySign}`; + const sign = crypto.createHash('md5').update(signText, 'utf8').digest('hex') + .toLowerCase(); + + return { + canonicalQuery, + bodySign, + sign, + }; +} + +/** + * 验证请求签名。 + * @param {Object} options 验签参数。 + * @param {Object} [options.query={}] 请求 query 参数。 + * @param {*} [options.body] 请求体。 + * @param {string} options.providedSign 调用方提供的签名。 + * @param {string} options.selfAppSecret 密钥。 + * @param {string[]} [options.ignoreKeys] 需要忽略的 query 字段。 + * @return {{ ok: boolean, expectedSign: string, providedSign: string, message: string }} 验签结果。 + */ +function verifyRequestSign({ query = {}, body, providedSign, selfAppSecret, ignoreKeys } = {}) { + const normalizedProvidedSign = String(providedSign || '').trim().toLowerCase(); + if (!normalizedProvidedSign) { + return { + ok: false, + expectedSign: '', + providedSign: '', + message: 'providedSign 不能为空', + }; + } + + let expected; + try { + expected = signRequest({ query, body, selfAppSecret, ignoreKeys }).sign; + } catch (error) { + return { + ok: false, + expectedSign: '', + providedSign: normalizedProvidedSign, + message: error.message, + }; + } + + if (expected !== normalizedProvidedSign) { + return { + ok: false, + expectedSign: expected, + providedSign: normalizedProvidedSign, + message: '签名不匹配', + }; + } + + return { + ok: true, + expectedSign: expected, + providedSign: normalizedProvidedSign, + message: '签名验证通过', + }; +} + +module.exports = { + DEFAULT_IGNORE_KEYS, + buildCanonicalQuery, + buildBodySign, + signRequest, + verifyRequestSign, +}; diff --git a/app/lib/callback_functions.js b/app/lib/callback_functions.js new file mode 100644 index 0000000..4a4f507 --- /dev/null +++ b/app/lib/callback_functions.js @@ -0,0 +1,38 @@ +'use strict'; + +/** + * 出站回调 method 注册表(代码注册,管理端多选列表经拉取接口透出)。 + * + * method 即出站路由键:wms_api_app.callback_functions 勾选后, + * 出站回调按 warehouse_id + method 自动路由到承接该 method 的应用; + * callback_functions 为空/未勾选 = 不承接任何回调。 + * + * 新增出站回调能力时在此登记 method,管理端接口自动可见。 + */ +const CALLBACK_FUNCTIONS = [ + { + method: 'notify.reply', + name: '站内信通知回执', + description: '站内信/系统通知/回执出站推送(warehouseNotify 与 inbox 回执共用)', + }, + { + method: 'waybill.getreceive', + name: '运单揽收状态查询', + description: '按运单号批量查询是否已揽收:请求 { waybill_codes: [...] },' + + '外部返回 [{ waybill_code, is_galaxy_receive: 1|0 }],回写 wms_order_express.is_galaxy_receive', + }, + { + method: 'waybill.getTrace', + name: '运单物流轨迹查询', + description: '按运单号查询物流轨迹(实时回源,不落库):请求 { waybill_codes: [运单号] },' + + '外部返回 [{ waybillNo, trace: { opTime, outBizCode, memo, opOrgCityName, weight, scanType } }]', + }, +]; + +/** method 合法值集合(供管理端 create/update 校验) */ +const CALLBACK_METHOD_SET = new Set(CALLBACK_FUNCTIONS.map(item => item.method)); + +module.exports = { + CALLBACK_FUNCTIONS, + CALLBACK_METHOD_SET, +}; diff --git a/app/lib/delivery_order_summary.js b/app/lib/delivery_order_summary.js new file mode 100644 index 0000000..0370520 --- /dev/null +++ b/app/lib/delivery_order_summary.js @@ -0,0 +1,330 @@ +'use strict'; + +/** + * 配送订单每日汇总纯函数工具(无 egg / DB 依赖,可单测)。 + * + * 口径约定: + * 1. 日期维度为本地时区自然日(yyyy-MM-dd),区间左闭右开 [start, end+1day); + * 2. 缺省统计区间为「结束日往前 7 个自然日」(含结束日); + * 3. 单次最多 {@link MAX_DAY_COUNT} 天,避免跨过订单归档边界(history 分表不参与统计); + * 4. 每日指标缺失时补 0,保证前端按日绘图的连续性。 + */ + +const DAY_MS = 24 * 60 * 60 * 1000; +const DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/; + +/** 缺省统计天数(含结束日)。 */ +const DEFAULT_DAY_COUNT = 7; +/** 单次查询最大天数。 */ +const MAX_DAY_COUNT = 90; + +/** 每日指标字段清单(顺序即响应字段顺序)。 */ +const METRIC_FIELDS = Object.freeze([ + 'order_count', + 'dispatch_count', + 'shipped_count', + 'shipped_items_total', + 'shipped_amount', + 'intercepted_count', + 'intercepted_at_warehouse_count', + 'cancelled_count', +]); + +/** + * 两位补零。 + * @param {number} value 数值。 + * @return {string} 补零字符串。 + */ +function pad2(value) { + return String(value).padStart(2, '0'); +} + +/** + * 本地时区格式化为 yyyy-MM-dd。 + * @param {Date} date 日期对象。 + * @return {string} 格式化结果。 + */ +function formatDate(date) { + return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`; +} + +/** + * 构造日期偏移(按本地年月日加减,规避夏令时步进偏差)。 + * @param {Date} date 基准日期。 + * @param {number} days 偏移天数(可为负)。 + * @return {Date} 偏移后的日期(00:00:00.000)。 + */ +function addDays(date, days) { + return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days); +} + +/** + * 计算两个日期相差的自然日数量(按 UTC 年月日归一化,忽略时分秒)。 + * @param {Date} start 开始日期。 + * @param {Date} end 结束日期。 + * @return {number} 相差天数(end - start)。 + */ +function diffDays(start, end) { + const startDay = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate()) / DAY_MS; + const endDay = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate()) / DAY_MS; + return endDay - startDay; +} + +/** + * 解析 yyyy-MM-dd(兼容 yyyy-MM-dd HH:mm:ss 等带时间后缀的入参)。 + * @param {*} value 待解析值(字符串 / Date)。 + * @return {Date|null} 本地时区 00:00:00.000 的日期;无法解析时返回 null。 + */ +function parseDateOnly(value) { + if (value instanceof Date) { + return Number.isNaN(value.getTime()) + ? null + : new Date(value.getFullYear(), value.getMonth(), value.getDate()); + } + + const text = String(value === null || value === undefined ? '' : value).trim(); + if (!text) { + return null; + } + + const matched = DATE_PATTERN.exec(text.slice(0, 10)); + if (!matched) { + return null; + } + + const year = Number(matched[1]); + const month = Number(matched[2]); + const day = Number(matched[3]); + const candidate = new Date(year, month - 1, day); + if ( + candidate.getFullYear() !== year + || candidate.getMonth() !== month - 1 + || candidate.getDate() !== day + ) { + return null; + } + return candidate; +} + +/** + * 构造统计区间非法错误。 + * @param {string} message 错误文案。 + * @return {Error} 带 INVALID_SUMMARY_RANGE 错误码的异常。 + */ +function buildRangeError(message) { + const error = new Error(message); + error.code = 'INVALID_SUMMARY_RANGE'; + return error; +} + +/** + * 解析并校验统计区间。 + * + * 规则: + * - 仅传 endDate:startDate = endDate - (DEFAULT_DAY_COUNT - 1) 天; + * - 仅传 startDate:endDate = 今天; + * - 都不传:最近 DEFAULT_DAY_COUNT 个自然日(含今天); + * - startDate 晚于 endDate、区间超过 MAX_DAY_COUNT 天、格式非法均抛错。 + * + * @param {Object} [options={}] 入参。 + * @param {*} [options.startDate] 开始日期(yyyy-MM-dd)。 + * @param {*} [options.endDate] 结束日期(yyyy-MM-dd)。 + * @param {Date} [options.now=new Date()] 当前时间(便于单测注入)。 + * @return {{start: Date, end: Date, endExclusive: Date, startDate: string, endDate: string, dayCount: number}} 区间信息。 + */ +function resolveSummaryRange({ startDate = null, endDate = null, now = new Date() } = {}) { + const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + const hasStart = String(startDate === null || startDate === undefined ? '' : startDate).trim() !== ''; + const hasEnd = String(endDate === null || endDate === undefined ? '' : endDate).trim() !== ''; + const parsedStart = parseDateOnly(startDate); + const parsedEnd = parseDateOnly(endDate); + + if (hasStart && !parsedStart) { + throw buildRangeError('开始日期格式不正确,应为 yyyy-MM-dd'); + } + if (hasEnd && !parsedEnd) { + throw buildRangeError('结束日期格式不正确,应为 yyyy-MM-dd'); + } + + const end = parsedEnd || todayStart; + const start = parsedStart || addDays(end, -(DEFAULT_DAY_COUNT - 1)); + + if (start.getTime() > end.getTime()) { + throw buildRangeError('开始日期不能晚于结束日期'); + } + + const dayCount = diffDays(start, end) + 1; + if (dayCount > MAX_DAY_COUNT) { + throw buildRangeError(`汇总天数不能超过 ${MAX_DAY_COUNT} 天`); + } + + return { + start, + end, + endExclusive: addDays(end, 1), + startDate: formatDate(start), + endDate: formatDate(end), + dayCount, + }; +} + +/** + * 生成区间内逐日日期键(含首尾)。 + * @param {Date} start 开始日期。 + * @param {Date} end 结束日期(含)。 + * @return {Array} yyyy-MM-dd 列表。 + */ +function buildDateKeys(start, end) { + const total = diffDays(start, end) + 1; + const keys = []; + for (let index = 0; index < total; index += 1) { + keys.push(formatDate(addDays(start, index))); + } + return keys; +} + +/** + * 创建全零的每日指标对象。 + * @return {Object} 指标对象。 + */ +function createEmptyMetrics() { + const metrics = {}; + for (const field of METRIC_FIELDS) { + metrics[field] = 0; + } + return metrics; +} + +/** + * 按日期键初始化每日指标映射。 + * @param {Array} dateKeys 日期键列表。 + * @return {Map} 日期键到指标对象的映射。 + */ +function buildDailyMap(dateKeys) { + const dailyMap = new Map(); + for (const key of dateKeys) { + dailyMap.set(key, createEmptyMetrics()); + } + return dailyMap; +} + +/** + * 归一化聚合行返回的日期值(MySQL DATE() 可能返回字符串或 Date 实例)。 + * @param {*} value 原始日期值。 + * @return {string} yyyy-MM-dd;无法识别时返回空串。 + */ +function normalizeRowDate(value) { + if (value instanceof Date) { + return Number.isNaN(value.getTime()) ? '' : formatDate(value); + } + const text = String(value === null || value === undefined ? '' : value).trim(); + return text.slice(0, 10); +} + +/** + * 数值安全转换。 + * @param {*} value 原始值。 + * @return {number} 数值;非法值按 0 处理。 + */ +function toNumber(value) { + const num = Number(value); + return Number.isFinite(num) ? num : 0; +} + +/** + * 金额保留两位小数。 + * @param {*} value 原始值。 + * @return {number} 保留两位小数的金额。 + */ +function roundAmount(value) { + return Math.round(toNumber(value) * 100) / 100; +} + +/** + * 合并按日计数的聚合行到每日映射(区间外日期忽略)。 + * @param {Map} dailyMap 每日映射。 + * @param {Array} rows 聚合行(date / count)。 + * @param {string} field 目标指标字段。 + * @return {Map} 同一映射。 + */ +function addCountRows(dailyMap, rows, field) { + const list = Array.isArray(rows) ? rows : []; + for (const row of list) { + const target = dailyMap.get(normalizeRowDate(row && row.date)); + if (target) { + target[field] += toNumber(row.count); + } + } + return dailyMap; +} + +/** + * 合并发货聚合行(订单数 / 商品件数 / 金额)到每日映射。 + * @param {Map} dailyMap 每日映射。 + * @param {Array} rows 聚合行(date / count / items_total / amount)。 + * @return {Map} 同一映射。 + */ +function addShippedRows(dailyMap, rows) { + const list = Array.isArray(rows) ? rows : []; + for (const row of list) { + const target = dailyMap.get(normalizeRowDate(row && row.date)); + if (!target) { + continue; + } + target.shipped_count += toNumber(row.count); + target.shipped_items_total += toNumber(row.items_total); + target.shipped_amount += toNumber(row.amount); + } + return dailyMap; +} + +/** + * 按日期顺序输出每日行,金额统一保留两位小数。 + * @param {Array} dateKeys 日期键列表。 + * @param {Map} dailyMap 每日映射。 + * @return {Array} 每日汇总行。 + */ +function finalizeDailyRows(dateKeys, dailyMap) { + return dateKeys.map(date => { + const metrics = dailyMap.get(date) || createEmptyMetrics(); + return { + date, + ...metrics, + shipped_amount: roundAmount(metrics.shipped_amount), + }; + }); +} + +/** + * 汇总每日行,输出区间合计。 + * @param {Array} rows 每日汇总行。 + * @return {Object} 合计指标。 + */ +function summarizeRows(rows) { + const summary = createEmptyMetrics(); + for (const row of (Array.isArray(rows) ? rows : [])) { + for (const field of METRIC_FIELDS) { + summary[field] += toNumber(row && row[field]); + } + } + summary.shipped_amount = roundAmount(summary.shipped_amount); + return summary; +} + +module.exports = { + DEFAULT_DAY_COUNT, + MAX_DAY_COUNT, + METRIC_FIELDS, + formatDate, + addDays, + parseDateOnly, + resolveSummaryRange, + buildDateKeys, + createEmptyMetrics, + buildDailyMap, + normalizeRowDate, + addCountRows, + addShippedRows, + finalizeDailyRows, + summarizeRows, +}; diff --git a/app/lib/express_print_payload_builder.js b/app/lib/express_print_payload_builder.js new file mode 100644 index 0000000..9a5e2ac --- /dev/null +++ b/app/lib/express_print_payload_builder.js @@ -0,0 +1,303 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const PrinterDataBuilder = require('./printer_data_builder'); + +const TEMPLATE_CACHE = new Map(); + +/** + * 判断是否为普通对象。 + * @param {any} value 待判断值。 + * @return {boolean} 判断结果。 + */ +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * 以 JSON 方式做深拷贝,避免污染模板缓存对象。 + * @param {Object} source 原对象。 + * @return {Object} 深拷贝结果。 + */ +function deepClone(source) { + return JSON.parse(JSON.stringify(source)); +} + +/** + * 请求内 ID 生成器。 + */ +class RequestScopedPrintIdGenerator { + /** + * @param {string} requestCode 前端请求参数码。 + */ + constructor(requestCode) { + this.requestCode = String(requestCode || '').trim(); + this.sequence = 0; + } + + /** + * 生成请求 ID。 + * @return {string} 唯一请求 ID。 + */ + nextRequestId() { + return this.next('request'); + } + + /** + * 生成任务 ID。 + * @return {string} 唯一任务 ID。 + */ + nextTaskId() { + return this.next('task'); + } + + /** + * 生成文档 ID。 + * @return {string} 唯一文档 ID。 + */ + nextDocumentId() { + return this.next('document'); + } + + /** + * 生成带前缀的递增 ID。 + * @param {string} prefix ID 前缀。 + * @return {string} 生成结果。 + */ + next(prefix) { + this.sequence += 1; + return `${this.requestCode}_${prefix}_${this.sequence}`; + } +} + +/** + * 快递打印请求组装器。 + */ +class ExpressPrintPayloadBuilder { + /** + * @param {Object} options 初始化参数。 + * @param {string} options.baseDir 项目根目录。 + */ + constructor(options = {}) { + const requestOptions = isPlainObject(options) ? options : {}; + this.baseDir = String(requestOptions.baseDir || process.cwd()); + this.templateDir = path.join(this.baseDir, 'printer_data_template'); + } + + /** + * 组装平台快递打印 payload。 + * @param {Object} options 组装参数。 + * @param {string} options.platform 平台编码。 + * @param {string} options.printerName 打印机名称。 + * @param {Array} options.orders 外部传入的订单打印数据数组。 + * @param {RequestScopedPrintIdGenerator} options.idGenerator 请求内 ID 生成器。 + * @return {Object} 可直接发送给打印服务的 payload。 + */ + buildPayload(options = {}) { + const requestOptions = isPlainObject(options) ? options : {}; + const platform = String(requestOptions.platform || '').trim(); + const normalizedPlatform = this.normalizePlatform(platform); + if (!platform) { + throw new Error('快递打印缺少平台标识'); + } + + const idGenerator = requestOptions.idGenerator; + if (!idGenerator || typeof idGenerator.nextRequestId !== 'function') { + throw new Error('快递打印缺少请求 ID 生成器'); + } + + const printerName = String(requestOptions.printerName || '').trim(); + if (!printerName) { + throw new Error('快递打印缺少打印机名称'); + } + + const orders = Array.isArray(requestOptions.orders) ? requestOptions.orders : []; + if (orders.length === 0) { + throw new Error('快递打印缺少订单数据'); + } + + const payload = this.loadTemplate(platform); + + const requestId = idGenerator.nextRequestId(); + this.applyRequestId(payload, requestId); + payload.printer = printerName; + + if (Array.isArray(payload.taskList)) { + payload.taskList.forEach(item => { + if (isPlainObject(item)) { + item.printer = printerName; + } + }); + } + + if (normalizedPlatform === 'sph') { + payload.taskList = this.buildTaskListFromOrders(orders, idGenerator); + } else { + if (!isPlainObject(payload.task)) { + payload.task = {}; + } + payload.task.taskID = idGenerator.nextTaskId(); + payload.task.printer = printerName; + payload.task.documents = this.buildDocumentsFromOrders(orders, idGenerator); + } + + if (normalizedPlatform === 'jd') { + this.mergeJdParametersContents(payload, printerName); + } + + return payload; + } + + /** + * 将京东平台模板参数中的 contents 替换为订单实际内容。 + * @param {Object} payload 打印请求 payload。 + * @param {string} printerName 打印机名称。 + */ + mergeJdParametersContents(payload, printerName) { + if (!isPlainObject(payload.parameters)) { + payload.parameters = {}; + } + + payload.parameters.printName = printerName; + + const documents = Array.isArray(payload.task && payload.task.documents) ? payload.task.documents : []; + payload.parameters.contents = documents.map(document => { + if (!isPlainObject(document) || !Array.isArray(document.contents) || !document.contents[0]) { + return {}; + } + return deepClone(document.contents[0]); + }); + } + + /** + * 将 orders 映射为 SPH taskList 项。 + * SPH 的 task item 结构(taskID / printInfo / customInfo / extendData 等)与通用 document 结构不兼容, + * 因此需要独立的构建方法,但处理模式与 buildDocumentsFromOrders 一致: + * 遍历 orders → deepClone → 分配唯一 ID → 放入数组。 + * + * @param {Array} orders 订单数组,每个元素直接是 SPH task item 对象。 + * @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。 + * @return {Array} taskList 数组。 + */ + buildTaskListFromOrders(orders, idGenerator) { + const taskList = []; + for (const order of orders) { + if (order && typeof order === 'object' && !Array.isArray(order)) { + const taskItem = deepClone(order); + taskItem.taskID = idGenerator.nextTaskId(); + taskList.push(taskItem); + } + } + return taskList; + } + + /** + * 将 orders 映射为 documents。 + * @param {Array} orders 订单数组。 + * @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。 + * @return {Array} documents 数组。 + */ + buildDocumentsFromOrders(orders, idGenerator) { + return orders.map((order, index) => { + const sourceDocument = this.resolveOrderDocument(order, index); + const document = deepClone(sourceDocument); + if (!Array.isArray(document.contents)) { + document.contents = []; + } + document.documentID = idGenerator.nextDocumentId(); + return document; + }); + } + + /** + * 解析单个订单对应的 document。 + * @param {Object} order 订单对象。 + * @param {number} index 订单索引。 + * @return {Object} document 对象。 + */ + resolveOrderDocument(order, index) { + if (!isPlainObject(order)) { + throw new Error(`orders[${index}] 必须是对象`); + } + + const printData = isPlainObject(order.print_data) ? order.print_data : order; + if (!isPlainObject(printData)) { + throw new Error(`orders[${index}] 缺少 print_data`); + } + + const hasDocumentShape = Object.prototype.hasOwnProperty.call(printData, 'documentID') + || Array.isArray(printData.contents); + if (!hasDocumentShape) { + throw new Error(`orders[${index}] 的 print_data 不是有效 document 结构`); + } + + return printData; + } + + /** + * 写入请求 ID,兼容 requestID / requetID 两种字段。 + * @param {Object} payload 请求 payload。 + * @param {string} requestId 请求 ID。 + */ + applyRequestId(payload, requestId) { + const hasRequestId = Object.prototype.hasOwnProperty.call(payload, 'requestID'); + const hasRequetId = Object.prototype.hasOwnProperty.call(payload, 'requetID'); + + if (hasRequestId) { + payload.requestID = requestId; + } + if (hasRequetId) { + payload.requetID = requestId; + } + if (!hasRequestId && !hasRequetId) { + payload.requestID = requestId; + } + } + + /** + * 加载并缓存平台模板,然后返回深拷贝对象。 + * @param {string} platform 平台编码。 + * @return {Object} 模板拷贝。 + */ + loadTemplate(platform) { + const normalizedPlatform = this.normalizePlatform(platform); + const templatePath = path.join(this.templateDir, `${normalizedPlatform}.json`); + if (!TEMPLATE_CACHE.has(templatePath)) { + let templateContent = ''; + try { + templateContent = fs.readFileSync(templatePath, 'utf8'); + } catch (error) { + throw new Error(`未找到平台模板: ${normalizedPlatform}.json`); + } + + let templateData; + try { + templateData = JSON.parse(templateContent); + } catch (error) { + throw new Error(`平台模板 JSON 解析失败: ${normalizedPlatform}.json`); + } + TEMPLATE_CACHE.set(templatePath, templateData); + } + + return deepClone(TEMPLATE_CACHE.get(templatePath)); + } + + /** + * 规范化平台编码。 + * @param {string} platform 平台编码或别名。 + * @return {string} 规范化平台编码。 + */ + normalizePlatform(platform) { + const normalized = PrinterDataBuilder.normalizePlatformAlias(platform); + if (normalized && normalized.platform) { + return normalized.platform; + } + return String(platform || '').trim().toLowerCase(); + } +} + +module.exports = { + ExpressPrintPayloadBuilder, + RequestScopedPrintIdGenerator, +}; diff --git a/app/lib/file_writer.js b/app/lib/file_writer.js new file mode 100644 index 0000000..4747a20 --- /dev/null +++ b/app/lib/file_writer.js @@ -0,0 +1,1574 @@ +'use strict'; + +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); + +const DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024; +const DEFAULT_MAX_FILE_LINES = 2000; +const DEFAULT_MAX_CONSUME_RECORDS_PER_WINDOW = 1000; +const DEFAULT_WRITE_WINDOW_SECONDS = 1; +const DEFAULT_MAX_WRITE_RECORDS_PER_WINDOW = 2000; +const DEFAULT_RETENTION_DAYS = 7; +const DEFAULT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000; +const DEFAULT_STATE_MAP_MAX_ENTRIES = 256; +const DEFAULT_WRITE_WINDOW_BUCKET_COUNT = 8; + +/** + * 本地文件队列写入器。 + * 负责把业务数据按 JSON Lines 追加到本地文件,并保证单条写入串行、fsync 落盘和自动轮转。 + */ +class LocalFileWriter { + /** + * 创建本地文件写入器实例。 + * @param {Egg.Application} app Egg 应用实例。 + */ + constructor(app) { + this.app = app; + this.config = app.config.fileWriter || {}; + this.baseDir = path.resolve(this.config.baseDir || path.join(app.baseDir, 'runtime', 'file-writer')); + this.maxFileSize = this.normalizeSize(this.config.maxFileSize, DEFAULT_MAX_FILE_SIZE); + this.maxFileLines = this.normalizePositiveInteger(this.config.maxFileLines, DEFAULT_MAX_FILE_LINES); + this.maxConsumeRecordsPerWindow = this.normalizePositiveInteger( + this.config.maxConsumeRecordsPerWindow + ?? this.config.maxConsumeRecordsPerRun + ?? app.config.maxConsumeRecordsPerWindow + ?? app.config.maxConsumeRecordsPerRun, + DEFAULT_MAX_CONSUME_RECORDS_PER_WINDOW + ); + this.maxConsumeRecordsPerRun = this.maxConsumeRecordsPerWindow; + this.writeWindowSeconds = this.normalizeInteger( + this.config.writeWindowSeconds + ?? app.config.writeWindowSeconds, + DEFAULT_WRITE_WINDOW_SECONDS + ); + this.maxWriteRecordsPerWindow = this.normalizeInteger( + this.config.maxWriteRecordsPerWindow + ?? app.config.maxWriteRecordsPerWindow, + DEFAULT_MAX_WRITE_RECORDS_PER_WINDOW + ); + this.writeWindowStartedAt = 0; + this.writeWindowRecordCount = 0; + this.writeWindowBucketCount = this.normalizePositiveInteger( + this.config.writeWindowBucketCount + ?? app.config.writeWindowBucketCount, + DEFAULT_WRITE_WINDOW_BUCKET_COUNT + ); + this.preferredBucket = this.hashStringToIndex(this.workerId + '-' + this.pid, this.writeWindowBucketCount); + this.retentionDays = this.normalizeInteger(this.config.retentionDays, DEFAULT_RETENTION_DAYS); + this.cleanupIntervalMs = this.normalizeInteger(this.config.cleanupIntervalMs, DEFAULT_CLEANUP_INTERVAL_MS); + this.machineId = this.sanitizeSegment(this.config.machineId || os.hostname() || 'machine'); + this.workerId = this.sanitizeSegment(this.config.workerId || process.env.EGG_WORKER_ID || 'worker'); + this.pid = process.pid; + this.processTag = `${this.machineId}-${this.workerId}-p${this.pid}`; + this.sequenceWidth = this.normalizeInteger(this.config.sequenceWidth, 4); + this.stateMapMaxEntries = this.normalizePositiveInteger(this.config.stateMapMaxEntries, DEFAULT_STATE_MAP_MAX_ENTRIES); + this.fileExtension = this.normalizeExtension(this.config.fileExtension, '.log'); + this.progressExtension = this.normalizeExtension(this.config.progressExtension, '.progress'); + this.doneExtension = this.normalizeExtension(this.config.doneExtension, '.done'); + this.stateMap = new Map(); + this.queue = Promise.resolve(); + this.lastCleanupAt = 0; + } + + /** + * 将写入任务串行排队执行。 + * @param {Function} task 需要排队执行的异步任务。 + * @return {Promise<*>} 任务执行结果。 + */ + enqueue(task) { + const currentTask = this.queue.then(() => task()); + this.queue = currentTask.then(() => undefined, () => undefined); + return currentTask; + } + + /** + * 等待当前队列里的所有写入完成。 + * @return {Promise} 等待完成的 Promise。 + */ + async flush() { + await this.queue; + } + + /** + * 把业务数据写入本地 JSON Lines 文件。 + * @param {string} businessName 业务名称。 + * @param {*} record 需要写入的数据。 + * @param {Object} [options] 写入选项。 + * @param {Date|string|number} [options.date] 指定归档日期,默认使用当前时间。 + * @return {Promise} 写入结果。 + */ + async writeRecord(businessName, record, options = {}) { + return this.enqueue(async () => { + const windowCheck = await this.atomicCheckAndIncrementWriteWindow(); + this.writeWindowStartedAt = windowCheck.counter.startedAt; + this.writeWindowRecordCount = windowCheck.counter.recordCount; + + if (!windowCheck.allowed) { + const writeWindowMs = this.writeWindowSeconds * 1000; + const resumeAt = new Date(windowCheck.counter.startedAt + writeWindowMs).toISOString(); + return { + throttled: true, + businessName, + resumeAt, + writeWindowSeconds: this.writeWindowSeconds, + writeWindowRecordCount: windowCheck.counter.recordCount, + maxWriteRecordsPerWindow: this.maxWriteRecordsPerWindow, + }; + } + + const partitionState = await this.getPartitionState(businessName, options.date); + const jsonLine = this.stringifyRecord(record); + const payload = `${jsonLine}\n`; + const payloadSize = Buffer.byteLength(payload); + + if ( + partitionState.currentLineCount >= this.maxFileLines + || (partitionState.currentSize > 0 && partitionState.currentSize + payloadSize > this.maxFileSize) + ) { + partitionState.sequence += 1; + partitionState.currentFilePath = this.buildDataFilePath(partitionState, partitionState.sequence); + partitionState.currentSize = 0; + partitionState.currentLineCount = 0; + } + + await this.ensureParentDirectory(partitionState.partitionDir); + + const handle = await fsp.open(partitionState.currentFilePath, 'a'); + try { + await handle.write(payload); + await handle.sync(); + } finally { + await handle.close(); + } + + partitionState.currentSize += payloadSize; + partitionState.currentLineCount += 1; + await this.maybeCleanup(); + + return { + businessName: partitionState.businessName, + dateKey: partitionState.dateKey, + filePath: partitionState.currentFilePath, + size: partitionState.currentSize, + lineCount: partitionState.currentLineCount, + bytesWritten: payloadSize, + sequence: partitionState.sequence, + machineId: this.machineId, + workerId: this.workerId, + pid: this.pid, + throttled: false, + writeWindowRecordCount: windowCheck.counter.recordCount, + maxWriteRecordsPerWindow: this.maxWriteRecordsPerWindow, + }; + }); + } + + /** + * 写入方法别名,便于业务侧直接调用。 + * @param {string} businessName 业务名称。 + * @param {*} record 需要写入的数据。 + * @param {Object} [options] 写入选项。 + * @return {Promise} 写入结果。 + */ + async write(businessName, record, options = {}) { + return this.writeRecord(businessName, record, options); + } + + /** + * 获取某个业务在指定日期下的目录信息。 + * @param {string} businessName 业务名称。 + * @param {Date|string|number} [date] 指定日期。 + * @return {Object} 目录信息。 + */ + getPartitionInfo(businessName, date = new Date()) { + const businessSegment = this.sanitizeSegment(businessName || 'default'); + const dateParts = this.getDateParts(date); + const partitionDir = path.join(this.baseDir, businessSegment, dateParts.year, dateParts.month, dateParts.day); + + return { + businessName, + businessSegment, + dateKey: dateParts.dateKey, + partitionDir, + filePrefix: `${businessSegment}-${this.processTag}`, + processTag: this.processTag, + }; + } + + /** + * 获取消费进度文件路径。 + * @param {string} businessName 业务名称。 + * @param {Date|string|number|null} [date] 指定日期;传空时使用业务级共享进度文件。 + * @param {string} [consumerName] 消费者名称。 + * @return {string} 进度文件路径。 + */ + getProgressFilePath(businessName, date = new Date(), consumerName = 'default') { + const businessSegment = this.sanitizeSegment(businessName || 'default'); + const safeConsumerName = this.sanitizeSegment(consumerName || 'default'); + if (date == null) { + return path.join(this.baseDir, businessSegment, `.${safeConsumerName}${this.progressExtension}`); + } + + const partitionInfo = this.getPartitionInfo(businessName, date); + return path.join(partitionInfo.partitionDir, `.${safeConsumerName}${this.progressExtension}`); + } + + /** + * 获取某个数据文件的消费完成标记路径。 + * @param {string} filePath 数据文件路径。 + * @return {string} 完成标记路径。 + */ + getDoneFilePath(filePath) { + const resolvedFilePath = path.resolve(filePath); + return `${resolvedFilePath}${this.doneExtension}`; + } + + /** + * 列出某个业务日期分区下的所有日志文件。 + * @param {string} businessName 业务名称。 + * @param {Date|string|number|null} [date] 指定日期;传空时递归列出业务目录下所有日志文件。 + * @return {Promise>} 排序后的文件路径列表。 + */ + async listDataFiles(businessName, date = new Date()) { + const businessSegment = this.sanitizeSegment(businessName || 'default'); + const businessDir = path.join(this.baseDir, businessSegment); + const targetDir = date == null ? businessDir : this.getPartitionInfo(businessName, date).partitionDir; + const files = await this.collectDataFiles(targetDir); + + return files + .sort((left, right) => { + return this.compareDataFileSortKey(left.sortKey, right.sortKey); + }) + .map(entry => entry.filePath); + } + + /** + * 读取单个日志文件中的 JSON Lines 数据。 + * @param {string} filePath 日志文件路径。 + * @param {Object} [options] 读取选项。 + * @param {number} [options.startOffset=0] 起始字节偏移量。 + * @param {number} [options.maxRecords=0] 最大读取条数,0 或不传不限制。 + * @param {boolean} [options.parseJson=true] 是否自动解析 JSON。 + * @return {Promise} 读取结果。 + */ + async readRecords(filePath, options = {}) { + const resolvedFilePath = path.resolve(filePath); + const startOffset = this.normalizeInteger(options.startOffset, 0); + const maxRecords = this.normalizeInteger(options.maxRecords, 0); + const parseJson = options.parseJson !== false; + const records = []; + let nextOffset = startOffset; + let lineNumber = 0; + + try { + for await (const lineEntry of this.iterateJsonLines(resolvedFilePath, startOffset)) { + lineNumber = lineEntry.lineNumber; + nextOffset = lineEntry.nextOffset; + + if (!lineEntry.line.trim()) { + continue; + } + + if (!parseJson) { + records.push(lineEntry.line); + + if (maxRecords > 0 && records.length >= maxRecords) { + break; + } + + continue; + } + + try { + records.push(JSON.parse(lineEntry.line)); + + if (maxRecords > 0 && records.length >= maxRecords) { + break; + } + } catch (parseError) { + parseError.message = `解析文件 ${resolvedFilePath} 第 ${lineNumber} 行失败: ${parseError.message}`; + throw parseError; + } + } + } catch (error) { + if (error.code === 'ENOENT') { + return { + filePath: resolvedFilePath, + records: [], + nextOffset: startOffset, + lineNumber: 0, + }; + } + + throw error; + } + + return { + filePath: resolvedFilePath, + records, + nextOffset, + lineNumber, + }; + } + + /** + * 消费某个文件,并在每条记录处理完成后更新进度文件。 + * @param {string} filePath 日志文件路径。 + * @param {Object} options 消费选项。 + * @param {string} options.progressFilePath 进度文件路径。 + * @param {Function} options.onRecord 每条记录的处理函数。 + * @param {number} [options.startOffset=0] 起始偏移量。 + * @param {boolean} [options.parseJson=true] 是否自动解析 JSON。 + * @param {number} [options.maxConsumeRecordsPerWindow] 单次最大消费条数。 + * @param {number} [options.maxConsumeRecordsPerRun] 兼容旧字段的单次最大消费条数。 + * @param {Object|null} [options.progress] 已加载的进度数据,供内部复用。 + * @return {Promise} 消费结果,包含 filePath、processedCount、nextOffset、limitReached、maxConsumeRecordsPerWindow。 + */ + async consumeFile(filePath, options = {}) { + const progressFilePath = options.progressFilePath; + const onRecord = options.onRecord; + + if (!progressFilePath) { + throw new Error('progressFilePath 不能为空'); + } + + if (typeof onRecord !== 'function') { + throw new Error('onRecord 必须是函数'); + } + + const progress = options.progress || await this.loadProgress(progressFilePath); + const consumeLimit = this.normalizePositiveInteger( + options.maxConsumeRecordsPerWindow ?? options.maxConsumeRecordsPerRun, + this.maxConsumeRecordsPerWindow + ); + + const resolvedFilePath = path.resolve(filePath); + const startOffset = this.resolveConsumeStartOffset(progress, resolvedFilePath, options); + const parseJson = options.parseJson !== false; + + let offset = startOffset; + let processedCount = 0; + let lineNumber = 0; + let limitReached = false; + + try { + for await (const lineEntry of this.iterateJsonLines(resolvedFilePath, startOffset)) { + if (consumeLimit > 0 && processedCount >= consumeLimit) { + limitReached = true; + break; + } + + lineNumber = lineEntry.lineNumber; + offset = lineEntry.nextOffset; + + if (!lineEntry.line.trim()) { + continue; + } + + let record = lineEntry.line; + if (parseJson) { + try { + record = JSON.parse(lineEntry.line); + } catch (parseError) { + parseError.message = `解析文件 ${resolvedFilePath} 第 ${lineNumber} 行失败: ${parseError.message}`; + throw parseError; + } + } + + await onRecord(record, { + filePath: resolvedFilePath, + offset, + index: processedCount, + }); + processedCount += 1; + + const progressData = { + filePath: resolvedFilePath, + offset, + processedCount, + updatedAt: new Date().toISOString(), + }; + await this.saveProgress(progressFilePath, progressData); + + if (consumeLimit > 0 && processedCount >= consumeLimit) { + limitReached = true; + break; + } + } + } catch (error) { + if (error.code === 'ENOENT') { + return { + filePath: resolvedFilePath, + processedCount: 0, + nextOffset: startOffset, + limitReached: false, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + throw error; + } + + if (limitReached) { + return { + filePath: resolvedFilePath, + processedCount, + nextOffset: offset, + limitReached: true, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + const completionData = { + filePath: resolvedFilePath, + offset, + processedCount, + completedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }; + + await this.saveProgress(progressFilePath, completionData); + await this.saveCompletionMarker(resolvedFilePath, completionData); + + return { + filePath: resolvedFilePath, + processedCount, + nextOffset: offset, + limitReached: false, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + /** + * 按业务目录消费所有日志文件,支持断点续传。 + * @param {Object} options 消费选项。 + * @param {string} options.businessName 业务名称。 + * @param {string} options.progressFilePath 进度文件路径。 + * @param {Function} options.onRecord 每条记录的处理函数。 + * @param {boolean} [options.parseJson=true] 是否自动解析 JSON。 + * @param {number} [options.maxConsumeRecordsPerWindow] 单次最大消费条数。 + * @param {number} [options.maxConsumeRecordsPerRun] 兼容旧字段的单次最大消费条数。 + * @return {Promise} 消费结果,包含 businessName、dataFiles、processedCount、progress、limitReached、maxConsumeRecordsPerWindow。 + */ + async consumeFiles(options = {}) { + const businessName = options.businessName; + const progressFilePath = options.progressFilePath; + const onRecord = options.onRecord; + + if (!businessName) { + throw new Error('businessName 不能为空'); + } + + if (!progressFilePath) { + throw new Error('progressFilePath 不能为空'); + } + + if (typeof onRecord !== 'function') { + throw new Error('onRecord 必须是函数'); + } + + const progress = await this.loadProgress(progressFilePath); + const consumeLimit = this.normalizePositiveInteger( + options.maxConsumeRecordsPerWindow ?? options.maxConsumeRecordsPerRun, + this.maxConsumeRecordsPerWindow + ); + + const dataFiles = await this.listDataFiles(businessName, null); + + if (dataFiles.length === 0) { + return { + businessName, + dataFiles, + processedCount: 0, + progress, + limitReached: false, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + let startIndex = 0; + let startOffset = 0; + let limitReached = false; + + if (progress && progress.filePath) { + const matchedIndex = dataFiles.findIndex(filePath => path.resolve(filePath) === path.resolve(progress.filePath)); + if (matchedIndex >= 0) { + startIndex = matchedIndex; + startOffset = this.normalizeInteger(progress.offset, 0); + } else { + const progressSortKey = this.getDataFileSortKey(progress.filePath); + const fallbackIndex = dataFiles.findIndex(filePath => this.compareDataFileSortKey( + this.getDataFileSortKey(filePath), + progressSortKey + ) > 0); + if (fallbackIndex >= 0) { + startIndex = fallbackIndex; + startOffset = 0; + } else { + startIndex = dataFiles.length; + } + } + } + + let processedCount = 0; + let currentProgress = progress; + let totalConsumedCount = 0; + + for (let index = startIndex; index < dataFiles.length; index += 1) { + if (consumeLimit > 0 && totalConsumedCount >= consumeLimit) { + limitReached = true; + break; + } + + const filePath = dataFiles[index]; + const completion = await this.loadCompletionMarker(filePath); + if (completion && path.resolve(completion.filePath || filePath) === path.resolve(filePath)) { + currentProgress = { + ...completion, + filePath: completion.filePath || filePath, + updatedAt: new Date().toISOString(), + }; + await this.saveProgress(progressFilePath, currentProgress); + continue; + } + + const remainingLimit = consumeLimit > 0 ? consumeLimit - totalConsumedCount : consumeLimit; + const fileResult = await this.consumeFile(filePath, { + progressFilePath, + onRecord, + startOffset: index === startIndex ? startOffset : 0, + parseJson: options.parseJson, + maxConsumeRecordsPerWindow: remainingLimit, + progress, + }); + processedCount += fileResult.processedCount; + totalConsumedCount += fileResult.processedCount; + currentProgress = { + filePath, + offset: fileResult.nextOffset, + processedCount, + updatedAt: new Date().toISOString(), + }; + await this.saveProgress(progressFilePath, currentProgress); + + if (fileResult.limitReached) { + limitReached = true; + break; + } + } + + return { + businessName, + dataFiles, + processedCount, + progress: currentProgress, + limitReached, + maxConsumeRecordsPerRun: consumeLimit, + maxConsumeRecordsPerWindow: consumeLimit, + }; + } + + /** + * 递归收集目录下的所有数据文件,并记录用于排序的分区日期与序号。 + * @param {string} dirPath 目录路径。 + * @param {Array} [result=[]] 累积结果。 + * @return {Promise>} 收集结果。 + */ + async collectDataFiles(dirPath, result = []) { + let entries; + try { + entries = await fsp.readdir(dirPath, { withFileTypes: true }); + } catch (error) { + if (error.code === 'ENOENT') { + return result; + } + + throw error; + } + + for (const entry of entries) { + const entryPath = path.join(dirPath, entry.name); + if (entry.isDirectory()) { + await this.collectDataFiles(entryPath, result); + continue; + } + + if (!entry.isFile() || !entry.name.endsWith(this.fileExtension)) { + continue; + } + + result.push({ + filePath: entryPath, + sortKey: this.getDataFileSortKey(entryPath), + }); + } + + return result; + } + + /** + * 解析数据文件的消费顺序键,按分区日期和文件序号排序。 + * @param {string} filePath 数据文件路径。 + * @return {Object} 排序键。 + */ + getDataFileSortKey(filePath) { + const resolvedFilePath = path.resolve(filePath); + const relativeParts = path.relative(this.baseDir, resolvedFilePath).split(path.sep).filter(Boolean); + const fileName = path.basename(resolvedFilePath); + const sequenceMatch = fileName.match(/-(\d+)\.[^.]+$/); + + let partitionDateKey = ''; + if (relativeParts.length >= 5) { + const year = relativeParts[1]; + const month = relativeParts[2]; + const day = relativeParts[3]; + + if (/^\d+$/.test(year) && /^\d+$/.test(month) && /^\d+$/.test(day)) { + partitionDateKey = `${year.padStart(4, '0')}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`; + } + } + + return { + partitionDateKey, + sequence: sequenceMatch ? Number.parseInt(sequenceMatch[1], 10) : Number.MAX_SAFE_INTEGER, + filePath: resolvedFilePath, + }; + } + + /** + * 比较两个数据文件的排序键。 + * @param {Object} left 左侧排序键。 + * @param {Object} right 右侧排序键。 + * @return {number} 排序结果。 + */ + compareDataFileSortKey(left, right) { + if (left.partitionDateKey !== right.partitionDateKey) { + return left.partitionDateKey.localeCompare(right.partitionDateKey, 'en'); + } + + if (left.sequence !== right.sequence) { + return left.sequence - right.sequence; + } + + return left.filePath.localeCompare(right.filePath, 'en', { numeric: true }); + } + + /** + * 读取进度文件。 + * @param {string} progressFilePath 进度文件路径。 + * @return {Promise} 进度内容。 + */ + async loadProgress(progressFilePath) { + const resolvedPath = path.resolve(progressFilePath); + try { + const content = await fsp.readFile(resolvedPath, 'utf8'); + if (!content.trim()) { + return null; + } + + return this.normalizeProgressData(JSON.parse(content), resolvedPath); + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + + if (error instanceof SyntaxError) { + this.app.logger.warn('[fileWriter.loadProgress] 忽略损坏的进度文件', resolvedPath, error.message); + return null; + } + + throw error; + } + } + + /** + * 保存进度文件。 + * @param {string} progressFilePath 进度文件路径。 + * @param {Object} progressData 进度数据。 + * @return {Promise} 保存后的进度数据。 + */ + async saveProgress(progressFilePath, progressData) { + const resolvedPath = path.resolve(progressFilePath); + const payload = `${JSON.stringify({ + ...progressData, + updatedAt: progressData.updatedAt || new Date().toISOString(), + }, null, 2)}\n`; + + await this.writeAtomicTextFile(resolvedPath, payload); + + return { + ...progressData, + updatedAt: progressData.updatedAt || new Date().toISOString(), + }; + } + + /** + * 保存消费完成标记。 + * @param {string} filePath 数据文件路径。 + * @param {Object} completionData 完成数据。 + * @return {Promise} 保存后的完成数据。 + */ + async saveCompletionMarker(filePath, completionData) { + const resolvedFilePath = path.resolve(filePath); + const doneFilePath = this.getDoneFilePath(resolvedFilePath); + const payload = `${JSON.stringify({ + ...completionData, + filePath: resolvedFilePath, + completedAt: completionData.completedAt || new Date().toISOString(), + }, null, 2)}\n`; + + await this.writeAtomicTextFile(doneFilePath, payload); + + return { + ...completionData, + filePath: resolvedFilePath, + completedAt: completionData.completedAt || new Date().toISOString(), + }; + } + + /** + * 读取消费完成标记。 + * @param {string} filePath 数据文件路径。 + * @return {Promise} 完成标记内容。 + */ + async loadCompletionMarker(filePath) { + const resolvedFilePath = path.resolve(filePath); + const doneFilePath = this.getDoneFilePath(resolvedFilePath); + try { + const content = await fsp.readFile(doneFilePath, 'utf8'); + if (!content.trim()) { + return null; + } + + return this.normalizeCompletionData(JSON.parse(content), resolvedFilePath); + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + + if (error instanceof SyntaxError) { + this.app.logger.warn('[fileWriter.loadCompletionMarker] 忽略损坏的完成标记', doneFilePath, error.message); + return null; + } + + throw error; + } + } + + /** + * 清理超过保留期的日志文件与进度文件。 + * @return {Promise} 清理结果。 + */ + async cleanupExpiredFiles() { + if (!this.retentionDays || this.retentionDays <= 0) { + return { + removedFiles: 0, + removedDirectories: 0, + }; + } + + const cutoffTime = Date.now() - (this.retentionDays * 24 * 60 * 60 * 1000); + const result = { + removedFiles: 0, + removedDirectories: 0, + }; + + await this.walkAndCleanup(this.baseDir, cutoffTime, result); + return result; + } + + /** + * 规范化日期并返回目录分段。 + * @param {Date|string|number} date 日期。 + * @return {Object} 日期分段。 + */ + getDateParts(date = new Date()) { + const targetDate = date instanceof Date ? date : new Date(date); + if (Number.isNaN(targetDate.getTime())) { + throw new Error(`无效的日期参数: ${date}`); + } + + const year = String(targetDate.getFullYear()); + const month = String(targetDate.getMonth() + 1).padStart(2, '0'); + const day = String(targetDate.getDate()).padStart(2, '0'); + + return { + year, + month, + day, + dateKey: `${year}-${month}-${day}`, + }; + } + + /** + * 获取写入分区状态。 + * @param {string} businessName 业务名称。 + * @param {Date|string|number} [date] 指定日期。 + * @return {Promise} 分区状态。 + */ + async getPartitionState(businessName, date = new Date()) { + const partitionInfo = this.getPartitionInfo(businessName, date); + const stateKey = `${partitionInfo.businessSegment}:${partitionInfo.dateKey}`; + + if (this.stateMap.has(stateKey)) { + const existingState = this.stateMap.get(stateKey); + this.stateMap.delete(stateKey); + this.stateMap.set(stateKey, existingState); + return existingState; + } + + await this.ensureParentDirectory(partitionInfo.partitionDir); + + const state = { + businessName, + businessSegment: partitionInfo.businessSegment, + dateKey: partitionInfo.dateKey, + partitionDir: partitionInfo.partitionDir, + filePrefix: partitionInfo.filePrefix, + sequence: 1, + currentSize: 0, + currentLineCount: 0, + currentFilePath: this.buildDataFilePath({ + partitionDir: partitionInfo.partitionDir, + filePrefix: partitionInfo.filePrefix, + }, 1), + }; + + const latestDataFileState = await this.loadLatestDataFileState(partitionInfo.partitionDir, partitionInfo.filePrefix); + if (latestDataFileState) { + state.sequence = latestDataFileState.sequence; + state.currentSize = latestDataFileState.currentSize; + state.currentLineCount = latestDataFileState.currentLineCount; + state.currentFilePath = latestDataFileState.currentFilePath; + } + + this.evictOldestStateIfNeeded(); + this.stateMap.set(stateKey, state); + return state; + } + + /** + * 读取分区中最新数据文件的大小与行数,用于恢复写入状态。 + * @param {string} partitionDir 分区目录。 + * @param {string} filePrefix 文件前缀。 + * @return {Promise} 最新文件状态。 + */ + async loadLatestDataFileState(partitionDir, filePrefix) { + const dataFiles = await this.collectDataFiles(partitionDir); + if (dataFiles.length === 0) { + return null; + } + + dataFiles.sort((left, right) => this.compareDataFileSortKey(left.sortKey, right.sortKey)); + const latestFile = dataFiles[dataFiles.length - 1]; + const stat = await fsp.stat(latestFile.filePath); + const currentLineCount = await this.countFileLines(latestFile.filePath); + + return { + filePrefix, + sequence: latestFile.sortKey.sequence > 0 ? latestFile.sortKey.sequence : 1, + currentFilePath: latestFile.filePath, + currentSize: stat.size, + currentLineCount, + }; + } + + /** + * 统计文件中的行数。 + * @param {string} filePath 文件路径。 + * @return {Promise} 行数。 + */ + async countFileLines(filePath) { + let lineCount = 0; + let lastByte = null; + const stream = fs.createReadStream(filePath); + + try { + for await (const chunk of stream) { + lastByte = chunk.length > 0 ? chunk[chunk.length - 1] : lastByte; + for (let i = 0; i < chunk.length; i += 1) { + if (chunk[i] === 0x0A) { + lineCount += 1; + } + } + } + } finally { + stream.destroy(); + } + + if (lineCount === 0) { + return 0; + } + + if (lastByte !== 0x0A) { + lineCount += 1; + } + + return lineCount; + } + + /** + * 逐行读取 JSON Lines 文件,并返回每行的精确字节偏移。 + * @param {string} filePath 文件路径。 + * @param {number} [startOffset=0] 起始字节偏移量。 + * @return {AsyncGenerator} 逐行迭代器。 + */ + async* iterateJsonLines(filePath, startOffset = 0) { + const stream = fs.createReadStream(filePath, { + start: startOffset, + }); + + let buffer = Buffer.alloc(0); + let offset = startOffset; + let lineNumber = 0; + + try { + for await (const chunk of stream) { + buffer = Buffer.concat([ buffer, chunk ]); + + while (buffer.length > 0) { + const lineFeedIndex = buffer.indexOf(0x0A); + if (lineFeedIndex < 0) { + break; + } + + const lineEndIndex = lineFeedIndex > 0 && buffer[lineFeedIndex - 1] === 0x0D + ? lineFeedIndex - 1 + : lineFeedIndex; + const consumedBytes = lineFeedIndex + 1; + const lineBuffer = buffer.slice(0, lineEndIndex); + + lineNumber += 1; + offset += consumedBytes; + buffer = buffer.slice(consumedBytes); + + yield { + lineNumber, + line: lineBuffer.toString('utf8'), + nextOffset: offset, + }; + } + } + + if (buffer.length > 0) { + lineNumber += 1; + offset += buffer.length; + + yield { + lineNumber, + line: buffer.toString('utf8'), + nextOffset: offset, + }; + } + } finally { + stream.destroy(); + } + } + + /** + * 归一化进度文件内容,兼容损坏或旧字段。 + * @param {*} progressData 原始进度内容。 + * @param {string} [fallbackFilePath] 兜底文件路径。 + * @return {Object|null} 归一化后的进度内容。 + */ + normalizeProgressData(progressData, fallbackFilePath = null) { + if (!progressData || typeof progressData !== 'object') { + return null; + } + + const filePath = typeof progressData.filePath === 'string' && progressData.filePath.trim() + ? path.resolve(progressData.filePath) + : (fallbackFilePath || null); + const offset = this.normalizeInteger(progressData.offset ?? progressData.nextOffset, 0); + const processedCount = this.normalizeInteger(progressData.processedCount ?? progressData.processed ?? progressData.count, 0); + + return { + ...progressData, + filePath, + offset, + processedCount, + updatedAt: typeof progressData.updatedAt === 'string' && progressData.updatedAt.trim() + ? progressData.updatedAt + : undefined, + completedAt: typeof progressData.completedAt === 'string' && progressData.completedAt.trim() + ? progressData.completedAt + : undefined, + }; + } + + /** + * 归一化完成标记内容,兼容损坏或旧字段。 + * @param {*} completionData 原始完成标记内容。 + * @param {string} fallbackFilePath 兜底文件路径。 + * @return {Object|null} 归一化后的完成标记内容。 + */ + normalizeCompletionData(completionData, fallbackFilePath) { + if (!completionData || typeof completionData !== 'object') { + return null; + } + + const filePath = typeof completionData.filePath === 'string' && completionData.filePath.trim() + ? path.resolve(completionData.filePath) + : fallbackFilePath; + if (!filePath) { + return null; + } + + const completedAtMs = this.resolveTimestamp(completionData.completedAt ?? completionData.updatedAt); + + return { + ...completionData, + filePath, + completedAt: this.formatTimestamp(completedAtMs), + updatedAt: typeof completionData.updatedAt === 'string' && completionData.updatedAt.trim() + ? completionData.updatedAt + : undefined, + }; + } + + /** + * 回收最旧的分区状态,避免 stateMap 无界增长。 + * @return {void} + */ + evictOldestStateIfNeeded() { + if (this.stateMap.size < this.stateMapMaxEntries) { + return; + } + + const oldestKey = this.stateMap.keys().next().value; + if (oldestKey !== undefined) { + this.stateMap.delete(oldestKey); + } + } + + /** + * 构建日志文件路径。 + * @param {Object} partitionState 分区状态。 + * @param {number} sequence 序号。 + * @return {string} 文件路径。 + */ + buildDataFilePath(partitionState, sequence) { + const sequenceText = String(sequence).padStart(this.sequenceWidth, '0'); + const fileName = `${partitionState.filePrefix}-${sequenceText}${this.fileExtension}`; + return path.join(partitionState.partitionDir, fileName); + } + + /** + * 把要写入的记录转换为 JSON 字符串。 + * @param {*} record 记录内容。 + * @return {string} JSON 字符串。 + */ + stringifyRecord(record) { + const json = JSON.stringify(record, this.jsonReplacer); + if (json === undefined) { + throw new Error('写入内容无法被序列化为 JSON'); + } + + return json; + } + + /** + * JSON 序列化时处理 BigInt。 + * @param {string} key 属性名。 + * @param {*} value 属性值。 + * @return {*} 序列化后的值。 + */ + jsonReplacer(key, value) { + if (typeof value === 'bigint') { + return value.toString(); + } + + return value; + } + + /** + * 规范化目录片段,避免路径穿越。 + * @param {*} value 待处理值。 + * @return {string} 安全片段。 + */ + sanitizeSegment(value) { + const normalized = String(value || '').trim(); + if (!normalized) { + return 'default'; + } + + const safeValue = Array.from(normalized).map(character => { + const code = character.charCodeAt(0); + if (code < 32 || '<>:"/\\|?*'.includes(character)) { + return '_'; + } + + return character; + }).join(''); + + return safeValue + .replace(/\s+/g, '_') + .replace(/\.+/g, '.') + .replace(/^\.+|\.+$/g, '') + .replace(/_+/g, '_') + .slice(0, 80) || 'default'; + } + + /** + * 规范化扩展名。 + * @param {*} value 扩展名。 + * @param {string} fallback 回退扩展名。 + * @return {string} 规范化后的扩展名。 + */ + normalizeExtension(value, fallback) { + const raw = String(value || fallback || '').trim(); + if (!raw) { + return fallback; + } + + return raw.startsWith('.') ? raw : `.${raw}`; + } + + /** + * 规范化数字。 + * @param {*} value 数值或字符串。 + * @param {number} fallback 回退值。 + * @return {number} 规范化后的整数。 + */ + normalizeInteger(value, fallback) { + const parsed = Number.parseInt(value, 10); + return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback; + } + + /** + * 规范化大小配置。 + * @param {*} value 大小配置。 + * @param {number} fallback 回退值。 + * @return {number} 字节数。 + */ + normalizeSize(value, fallback) { + if (typeof value === 'number' && Number.isFinite(value) && value > 0) { + return Math.floor(value); + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + const match = trimmed.match(/^(\d+(?:\.\d+)?)([kKmMgGtT]?)$/); + if (match) { + const number = Number.parseFloat(match[1]); + const unit = match[2].toLowerCase(); + const unitMap = { + '': 1, + k: 1024, + m: 1024 * 1024, + g: 1024 * 1024 * 1024, + t: 1024 * 1024 * 1024 * 1024, + }; + return Math.floor(number * (unitMap[unit] || 1)); + } + } + + return fallback; + } + + /** + * 规范化正整数。 + * @param {*} value 数值或字符串。 + * @param {number} fallback 回退值。 + * @return {number} 规范化后的正整数。 + */ + normalizePositiveInteger(value, fallback) { + const parsed = Number.parseInt(value, 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; + } + + /** + * 解析时间值并返回毫秒时间戳。 + * @param {Date|string|number} [value] 时间值。 + * @return {number} 毫秒时间戳。 + */ + resolveTimestamp(value) { + if (value == null) { + return 0; + } + + if (value instanceof Date) { + return value.getTime(); + } + + if (typeof value === 'number' && Number.isFinite(value)) { + return value; + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return 0; + } + + if (/^\d+$/.test(trimmed)) { + return Number.parseInt(trimmed, 10); + } + + const parsed = Date.parse(trimmed); + if (!Number.isNaN(parsed)) { + return parsed; + } + } + + return 0; + } + + /** + * 把毫秒时间戳转换为 ISO 字符串。 + * @param {number} timestamp 毫秒时间戳。 + * @return {string|null} ISO 字符串。 + */ + formatTimestamp(timestamp) { + if (!Number.isFinite(timestamp) || timestamp <= 0) { + return null; + } + + return new Date(timestamp).toISOString(); + } + + /** + * 获取本次消费限额。 + * @param {Object} [options] 消费选项。 + * @param {number} [options.maxConsumeRecordsPerWindow] 单次最大消费条数。 + * @param {number} [options.maxConsumeRecordsPerRun] 兼容旧字段的单次最大消费条数。 + * @return {number} 当前消费限额。 + */ + getConsumeLimit(options = {}) { + return this.normalizePositiveInteger( + options.maxConsumeRecordsPerWindow ?? options.maxConsumeRecordsPerRun, + this.maxConsumeRecordsPerWindow + ); + } + + /** + * 解析消费起始偏移量。 + * @param {Object|null} progress 进度数据。 + * @param {string} filePath 当前文件路径。 + * @param {Object} [options] 消费选项。 + * @param {number} [options.startOffset] 显式起始偏移量。 + * @return {number} 起始偏移量。 + */ + resolveConsumeStartOffset(progress, filePath, options = {}) { + if (options.startOffset != null) { + return this.normalizeInteger(options.startOffset, 0); + } + + if (progress && progress.filePath && path.resolve(progress.filePath) === path.resolve(filePath)) { + return this.normalizeInteger(progress.offset, 0); + } + + return 0; + } + + /** + * 获取某个桶的共享写入窗口计数器文件路径。 + * @param {number} bucketIndex 桶索引。 + * @return {string} 计数器文件路径。 + */ + getWriteWindowCounterPath(bucketIndex = 0) { + return path.join(this.baseDir, `.write-window-counter-${bucketIndex}.json`); + } + + /** + * 多桶分片原子限流。 + * 将总限额均分到 N 个桶,从首选桶开始尝试,竞争失败或桶满时自动漂移到下一个桶。 + * @return {Promise} { allowed: boolean, counter: { startedAt, recordCount }, source: 'file' }。 + */ + async atomicCheckAndIncrementWriteWindow() { + if (this.maxWriteRecordsPerWindow <= 0) { + return { allowed: true, counter: { startedAt: 0, recordCount: 0 } }; + } + + const bucketCount = this.writeWindowBucketCount; + const perBucketLimit = Math.ceil(this.maxWriteRecordsPerWindow / bucketCount); + const writeWindowMs = this.writeWindowSeconds * 1000; + const now = Date.now(); + + await this.ensureParentDirectory(this.baseDir); + + let lastCounter = null; + + for (let i = 0; i < bucketCount; i++) { + const bucketIndex = (this.preferredBucket + i) % bucketCount; + const counterPath = this.getWriteWindowCounterPath(bucketIndex); + const lockPath = `${counterPath}.lock`; + + let lockHandle = null; + try { + // eslint-disable-next-line no-bitwise + lockHandle = await fsp.open(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY); + } catch (error) { + if (error.code === 'EEXIST' || error.code === 'EPERM') { + continue; + } + throw error; + } + + try { + const counter = { startedAt: 0, recordCount: 0 }; + try { + const content = await fsp.readFile(counterPath, 'utf8'); + if (content.trim()) { + const data = JSON.parse(content); + counter.startedAt = typeof data.startedAt === 'number' && Number.isFinite(data.startedAt) ? data.startedAt : 0; + counter.recordCount = typeof data.recordCount === 'number' && Number.isFinite(data.recordCount) ? data.recordCount : 0; + } + } catch (error) { + if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) { + throw error; + } + } + + if (counter.startedAt > 0 && now - counter.startedAt >= writeWindowMs) { + counter.startedAt = now; + counter.recordCount = 0; + } + + if (counter.startedAt === 0) { + counter.startedAt = now; + } + + lastCounter = counter; + + if (counter.recordCount >= perBucketLimit) { + continue; + } + + counter.recordCount += 1; + await fsp.writeFile(counterPath, `${JSON.stringify(counter)}\n`, 'utf8'); + return { allowed: true, counter, source: 'file' }; + } finally { + await lockHandle.close(); + await fsp.rm(lockPath, { force: true }); + } + } + + return { allowed: false, counter: lastCounter || { startedAt: now, recordCount: 0 }, source: 'file' }; + } + + /** + * 获取当前写入窗口状态(汇总所有桶)。 + * @return {Promise} 写入窗口状态。 + */ + async getWriteWindowState() { + const writeWindowMs = this.writeWindowSeconds * 1000; + const now = Date.now(); + let totalRecordCount = 0; + let earliestStartedAt = 0; + + for (let i = 0; i < this.writeWindowBucketCount; i++) { + try { + const content = await fsp.readFile(this.getWriteWindowCounterPath(i), 'utf8'); + if (content.trim()) { + const data = JSON.parse(content); + const startedAt = typeof data.startedAt === 'number' && Number.isFinite(data.startedAt) ? data.startedAt : 0; + const recordCount = typeof data.recordCount === 'number' && Number.isFinite(data.recordCount) ? data.recordCount : 0; + if (startedAt > 0 && now - startedAt < writeWindowMs) { + totalRecordCount += recordCount; + if (earliestStartedAt === 0 || startedAt < earliestStartedAt) { + earliestStartedAt = startedAt; + } + } + } + } catch { /* ignore missing/corrupt counter files */ } + } + + const windowExpired = earliestStartedAt > 0 && now - earliestStartedAt >= writeWindowMs; + const resumeAt = earliestStartedAt > 0 + ? new Date(earliestStartedAt + writeWindowMs).toISOString() + : null; + + return { + writeWindowSeconds: this.writeWindowSeconds, + maxWriteRecordsPerWindow: this.maxWriteRecordsPerWindow, + writeWindowBucketCount: this.writeWindowBucketCount, + writeWindowRecordCount: totalRecordCount, + writeWindowStartedAt: earliestStartedAt > 0 + ? new Date(earliestStartedAt).toISOString() + : null, + windowExpired, + resumeAt: windowExpired ? null : resumeAt, + source: 'file', + }; + } + + /** + * 将字符串映射到 [0, max) 范围内的索引。 + * @param {string} str 输入字符串。 + * @param {number} max 范围上限。 + * @return {number} 索引。 + */ + hashStringToIndex(str, max) { + let hash = 0; + for (let i = 0; i < str.length; i++) { + // eslint-disable-next-line no-bitwise + hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0; + } + return ((hash % max) + max) % max; + } + + /** + * 确保目录存在。 + * @param {string} dirPath 目录路径。 + * @return {Promise} Promise。 + */ + async ensureParentDirectory(dirPath) { + await fsp.mkdir(dirPath, { recursive: true }); + } + + /** + * 判断是否需要执行清理。 + * @return {Promise} Promise。 + */ + async maybeCleanup() { + if (!this.cleanupIntervalMs || this.cleanupIntervalMs <= 0) { + return; + } + + const now = Date.now(); + if (now - this.lastCleanupAt < this.cleanupIntervalMs) { + return; + } + + this.lastCleanupAt = now; + try { + await this.cleanupExpiredFiles(); + } catch (error) { + this.app.logger.warn('[fileWriter.cleanup] 清理本地文件失败', error.message); + } + } + + /** + * 递归清理目录中的过期文件。 + * @param {string} dirPath 当前目录。 + * @param {number} cutoffTime 过期时间戳。 + * @param {Object} result 清理统计。 + * @return {Promise} Promise。 + */ + async walkAndCleanup(dirPath, cutoffTime, result) { + let entries; + try { + entries = await fsp.readdir(dirPath, { withFileTypes: true }); + } catch (error) { + if (error.code === 'ENOENT') { + return; + } + + throw error; + } + + for (const entry of entries) { + const entryPath = path.join(dirPath, entry.name); + if (entry.isDirectory()) { + await this.walkAndCleanup(entryPath, cutoffTime, result); + await this.removeEmptyDirectory(entryPath, result); + continue; + } + + if (!entry.isFile()) { + continue; + } + + if (!entry.name.endsWith(this.fileExtension)) { + // 【风险点】清理只覆盖数据文件,.progress 文件不会被清理,长期会残留陈旧进度文件。 + continue; + } + + const completion = await this.loadCompletionMarker(entryPath); + if (!completion || path.resolve(completion.filePath || entryPath) !== path.resolve(entryPath)) { + continue; + } + + const stat = await fsp.stat(entryPath).catch(error => { + if (error.code === 'ENOENT') { + return null; + } + + throw error; + }); + + if (!stat || stat.mtimeMs >= cutoffTime) { + continue; + } + + await fsp.rm(entryPath, { force: true }); + await fsp.rm(this.getDoneFilePath(entryPath), { force: true }); + result.removedFiles += 1; + + const siblingEntries = await fsp.readdir(dirPath, { withFileTypes: true }); + for (const siblingEntry of siblingEntries) { + if (!siblingEntry.isFile() || !siblingEntry.name.endsWith(this.progressExtension)) { + continue; + } + + const progressPath = path.join(dirPath, siblingEntry.name); + const progressData = await this.loadProgress(progressPath); + if (!progressData || !progressData.completedAt) { + continue; + } + + if (path.resolve(progressData.filePath || '') !== path.resolve(entryPath)) { + continue; + } + + await fsp.rm(progressPath, { force: true }); + } + } + } + + /** + * 原子写入文本文件。 + * @param {string} targetPath 目标文件路径。 + * @param {string} content 文件内容。 + * @return {Promise} Promise。 + */ + async writeAtomicTextFile(targetPath, content) { + const directory = path.dirname(targetPath); + const tempPath = `${targetPath}.${this.pid}.${Date.now()}.tmp`; + + await this.ensureParentDirectory(directory); + + const handle = await fsp.open(tempPath, 'w'); + try { + await handle.write(content); + await handle.sync(); + } finally { + await handle.close(); + } + + await fsp.rename(tempPath, targetPath); + } + + /** + * 删除空目录。 + * @param {string} dirPath 目录路径。 + * @param {Object} result 清理统计。 + * @return {Promise} Promise。 + */ + async removeEmptyDirectory(dirPath, result) { + try { + const entries = await fsp.readdir(dirPath); + if (entries.length > 0) { + return; + } + + await fsp.rmdir(dirPath); + result.removedDirectories += 1; + } catch (error) { + if (error.code === 'ENOENT' || error.code === 'ENOTEMPTY') { + return; + } + + throw error; + } + } +} + +module.exports = LocalFileWriter; diff --git a/app/lib/inbox_channel.js b/app/lib/inbox_channel.js new file mode 100644 index 0000000..66b80af --- /dev/null +++ b/app/lib/inbox_channel.js @@ -0,0 +1,54 @@ +'use strict'; + +/** + * 站内信 IM 渠道来源工具。 + * + * 群ID 格式与渠道来源一一对应(生产 11 万+ 入站消息 100% 满足该对应关系): + * - `xxx@chatroom` 结尾 → wx(个人微信) + * - 纯数字(如 10845468709699144)→ qiwe(企业微信) + * + * ext_data.source 决定回执/通知透传给哪个桥接渠道;一旦与群ID格式不符, + * 回执会被投递到错误渠道(典型现象:wx 群用 qiwe 渠道投递 → "qiwe offline" 503)。 + */ + +/** 个人微信群ID 后缀 */ +const WX_GROUP_ID_SUFFIX = '@chatroom'; + +/** + * 按群ID格式推导渠道来源。 + * @param {string} groupId 外部群ID。 + * @return {string|null} wx / qiwe;无法判定时返回 null。 + */ +function resolveChannelSource(groupId) { + const id = String(groupId || '').trim(); + if (!id) return null; + if (id.endsWith(WX_GROUP_ID_SUFFIX)) return 'wx'; + if (/^\d+$/.test(id)) return 'qiwe'; + return null; +} + +/** + * 按群ID格式校正 ext_data.source(不修改入参)。 + * 仅在 ext_data 已带 source 且与群ID格式不符时返回新对象; + * 无 ext_data / 无 source / 群ID无法判定 / 已一致时原样返回。 + * @param {string} groupId 外部群ID。 + * @param {Object|null} extData 原始透传数据。 + * @return {Object|null} 校正后的透传数据。 + */ +function normalizeExtDataSource(groupId, extData) { + if (!extData || typeof extData !== 'object' || Array.isArray(extData)) { + return extData || null; + } + const expected = resolveChannelSource(groupId); + const current = extData.source; + if (!expected || !current || current === expected) { + return extData; + } + return { ...extData, source: expected }; +} + +module.exports = { + WX_GROUP_ID_SUFFIX, + resolveChannelSource, + normalizeExtDataSource, +}; diff --git a/app/lib/intercept_guard.js b/app/lib/intercept_guard.js new file mode 100644 index 0000000..4f63408 --- /dev/null +++ b/app/lib/intercept_guard.js @@ -0,0 +1,200 @@ +'use strict'; + +/** + * 订单拦截状态共享定义。 + * + * wms_order_delivery.intercept_status 枚举(order_delivery.js / order_delivery_factory.js)实际取值为: + * none / requesting / requested / intercepting / intercepted_in_transit / intercepted_at_warehouse / + * returning / returned / delivered_by_mistake / timeout / cancelled / failed / exception。 + * + * 业务约定:拦截状态只要不是 'none'(即任意进入拦截流程/拦截结果的状态),一律视为"已拦截", + * 禁止继续执行仓储作业(分配波次/分配储位/分配快递/打印/抓取波次/拣货/复核/打包/称重/绑定包材等), + * 被拦截订单一律跳过。 + */ +const INTERCEPT_STATUS_NONE = 'none'; + +/** + * 判断订单拦截状态是否属于"已拦截"。 + * 空值/NULL 归一化为 none 处理;除此之外任何非 none 状态(含 requested/intercepting/intercepted_*、 + * returning/returned/cancelled/failed/exception 等)均视为已拦截。 + * @param {*} status 拦截状态值。 + * @return {boolean} 是否已拦截。 + */ +function isInterceptedOrderStatus(status) { + const normalizedStatus = String(status || '').trim() || INTERCEPT_STATUS_NONE; + return normalizedStatus !== INTERCEPT_STATUS_NONE; +} + +/** 团购波次类型。 */ +const WAVE_TYPE_GROUP_BUY = 1; + +/** 散单波次类型。 */ +const WAVE_TYPE_SCATTER = 2; + +/** + * 返回不允许写入拦截请求状态(requested / intercepting)的阻断原因文案;空字符串表示允许写入。 + * + * 规则: + * - 团购波次(wave_type=1):inspection_status === 'fin'(已复核)→ 不允许写入拦截请求状态; + * - 散单波次(wave_type=2):weighing_weight > 0(已称重)→ 不允许写入拦截请求状态; + * - 其余情况(无波次 / 其他波次类型 / 未复核 / 未称重)不阻断。 + * + * @param {Object} params 参数。 + * @param {number|string} [params.waveType] 波次类型。 + * @param {string} [params.inspectionStatus] 订单复核状态。 + * @param {number|string} [params.weighingWeight] 散单称重重量。 + * @return {string} 阻断原因;空字符串表示允许写入。 + */ +function getInterceptRequestBlockReason({ waveType, inspectionStatus, weighingWeight } = {}) { + const normalizedWaveType = Number(waveType || 0); + if (normalizedWaveType === WAVE_TYPE_GROUP_BUY) { + return String(inspectionStatus || '').trim() === 'fin' ? '团购单已复核' : ''; + } + if (normalizedWaveType === WAVE_TYPE_SCATTER) { + return Number(weighingWeight || 0) > 0 ? '散单已称重' : ''; + } + return ''; +} + +/** + * 判断订单是否因「团购已复核 / 散单已称重」而不允许写入拦截请求状态。 + * + * @param {Object} params 参数,同 getInterceptRequestBlockReason。 + * @return {boolean} true 表示不允许写入拦截请求状态。 + */ +function isInterceptRequestBlockedByRecheckOrWeigh(params = {}) { + return getInterceptRequestBlockReason(params) !== ''; +} + +/** + * 拉取单订单的拦截请求前置校验信息(波次类型 + 散单称重重量)。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} params 参数。 + * @param {number|string} params.orderId 订单 ID。 + * @param {number|string} [params.waveId] 波次 ID。 + * @param {number|string} params.warehouseId 仓库 ID。 + * @param {Object} [params.transaction] 可选事务对象。 + * @return {Promise<{ waveType: number, weighingWeight: number }>} 校验信息。 + */ +async function resolveInterceptRequestGuardInfo(ctx, params = {}) { + const { orderId, waveId, warehouseId, transaction } = params; + let waveType = 0; + if (Number(waveId || 0) > 0 && ctx && ctx.model && ctx.model.WaveBatch) { + try { + const waveRow = await ctx.model.WaveBatch.findOne({ + where: { wave_id: Number(waveId), warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_type' ], + raw: true, + transaction, + }); + waveType = Number(waveRow && waveRow.wave_type || 0); + } catch (error) { /* 查询失败不阻断主流程,按无波次处理 */ } + } + + let weighingWeight = 0; + if (ctx && ctx.model && ctx.model.OrderExpress) { + try { + // 强制同仓校验:读取称重重量必须同时带订单ID与仓库ID,禁止跨仓串读 + const expressRows = await ctx.model.OrderExpress.findAll({ + where: { + order_id: Number(orderId || 0), + warehouse_id: warehouseId, + }, + attributes: [ 'weighing_weight' ], + raw: true, + transaction, + }); + for (const row of (Array.isArray(expressRows) ? expressRows : [])) { + weighingWeight = Math.max(weighingWeight, Number(row && row.weighing_weight || 0)); + } + } catch (error) { /* 查询失败不阻断主流程,按未称重处理 */ } + } + + return { waveType, weighingWeight }; +} + +/** + * 批量拉取订单的拦截请求前置校验信息(波次类型 + 散单称重重量)。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} params 参数。 + * @param {Array} params.orderRows 订单行数组(需含 id、wave_id 字段)。 + * @param {number|string} params.warehouseId 仓库 ID。 + * @param {Object} [params.transaction] 可选事务对象。 + * @return {Promise>} 按订单 ID 索引的校验信息。 + */ +async function resolveInterceptRequestGuardInfoMap(ctx, params = {}) { + const orderRows = Array.isArray(params.orderRows) ? params.orderRows : []; + const { warehouseId, transaction } = params; + + const infoMap = new Map(); + if (orderRows.length === 0 || !ctx) { + return infoMap; + } + + const orderIds = orderRows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + const waveIds = [ ...new Set(orderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + for (const orderId of orderIds) { + infoMap.set(orderId, { waveType: 0, weighingWeight: 0 }); + } + + if (waveIds.length > 0 && ctx.model && ctx.model.WaveBatch) { + try { + const { Op } = ctx.app && ctx.app.Sequelize || {}; + const waves = await ctx.model.WaveBatch.findAll({ + where: { wave_id: { [Op.in]: waveIds }, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_type' ], + raw: true, + transaction, + }); + const waveTypeMap = new Map((Array.isArray(waves) ? waves : []) + .map(wave => [ Number(wave && wave.wave_id || 0), Number(wave && wave.wave_type || 0) ])); + for (const row of orderRows) { + const info = infoMap.get(Number(row.id)); + if (info) { + info.waveType = waveTypeMap.get(Number(row.wave_id || 0)) || 0; + } + } + } catch (error) { /* 查询失败不阻断主流程,按无波次处理 */ } + } + + if (orderIds.length > 0 && ctx.model && ctx.model.OrderExpress) { + try { + const { Op } = ctx.app && ctx.app.Sequelize || {}; + const expressRows = await ctx.model.OrderExpress.findAll({ + where: { order_id: { [Op.in]: orderIds }, warehouse_id: warehouseId }, + attributes: [ 'order_id', 'weighing_weight' ], + raw: true, + transaction, + }); + for (const expressRow of (Array.isArray(expressRows) ? expressRows : [])) { + const info = infoMap.get(Number(expressRow && expressRow.order_id || 0)); + if (info) { + info.weighingWeight = Math.max( + info.weighingWeight, + Number(expressRow && expressRow.weighing_weight || 0) + ); + } + } + } catch (error) { /* 查询失败不阻断主流程,按未称重处理 */ } + } + + return infoMap; +} + +module.exports = { + INTERCEPT_STATUS_NONE, + isInterceptedOrderStatus, + WAVE_TYPE_GROUP_BUY, + WAVE_TYPE_SCATTER, + getInterceptRequestBlockReason, + isInterceptRequestBlockedByRecheckOrWeigh, + resolveInterceptRequestGuardInfo, + resolveInterceptRequestGuardInfoMap, +}; diff --git a/app/lib/intercept_time.js b/app/lib/intercept_time.js new file mode 100644 index 0000000..12d584d --- /dev/null +++ b/app/lib/intercept_time.js @@ -0,0 +1,82 @@ +'use strict'; + +/** + * 通知拦截时间(wms_order_delivery.intercept_time)字段口径工具(纯函数,无 ctx 依赖,可单测)。 + * + * 背景:`intercept_time` 语义原为「进入拦截流程/库内拦截确认时写入」, + * 确认拦截会覆盖发起时刻,导致「通知拦截时间」丢失、且无法与「库内确定拦截时刻」区分。 + * + * 自 2026-09-10 起统一为「最近一次发起拦截的通知时刻」: + * 1. 发起/通知拦截:**首次写入**(当前时间);重复发起**不覆盖**已有值; + * 2. 库内拦截确认(confirmIntercept / 拦截扫描 / 自动确认)、退回入库(returned):**不写该字段**(不覆盖); + * 3. 取消/解除拦截(batchUnintercept)与订单克隆重置:**置空 null**; + * 4. 因此「库内确定拦截时刻」不再使用本字段,改用配送表 `dispath_time`(订单迁移进配送表的时间, + * 库内确定拦截后基本都会走迁移)。 + */ + +/** 字段名常量 */ +const INTERCEPT_TIME_FIELD = 'intercept_time'; + +/** + * 判断通知拦截时间是否为空(null/undefined/空串)。 + * @param {*} value 字段值 + * @return {boolean} 是否为空 + */ +function isEmptyInterceptTime(value) { + return value === null || value === undefined || value === ''; +} + +/** + * 构造发起拦截时的更新片段:仅当当前值为空时才写入通知拦截时间(首次写入,不覆盖)。 + * + * 用法(实例更新,实例行需能取到 intercept_time): + * ```js + * await order.update({ intercept_status: 'requested', ...buildNoticeTimePatch(order.intercept_time), updated_at: now }); + * ``` + * + * @param {*} currentValue 订单当前 intercept_time + * @param {Date} [now=new Date()] 本次通知时刻 + * @return {Object} 需要写入的字段片段;已有值时返回空对象(不覆盖) + */ +function buildNoticeTimePatch(currentValue, now = new Date()) { + return isEmptyInterceptTime(currentValue) ? { [INTERCEPT_TIME_FIELD]: now } : {}; +} + +/** + * 从订单行中筛出「尚未写入通知拦截时间」的订单ID(批量写入用)。 + * + * 用法(批量更新):主更新不写 intercept_time,随后仅对返回的订单ID写一次通知时刻: + * ```js + * const fillIds = pickNoticeTimeOrderIds(orderRows); + * await model.update({ intercept_status: 'requested', updated_at: now }, { where: { id: { [Op.in]: ids } } }); + * if (fillIds.length > 0) { + * await model.update({ intercept_time: now }, { where: { id: { [Op.in]: fillIds } } }); + * } + * ``` + * + * @param {Array} rows 订单行(需含 id 与 intercept_time) + * @return {Array} 需要写入通知拦截时间的订单ID(正整数,保序去重) + */ +function pickNoticeTimeOrderIds(rows = []) { + const seen = new Set(); + const orderIds = []; + for (const row of (Array.isArray(rows) ? rows : [])) { + if (!row || !isEmptyInterceptTime(row[INTERCEPT_TIME_FIELD])) { + continue; + } + const orderId = Number(row.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0 || seen.has(orderId)) { + continue; + } + seen.add(orderId); + orderIds.push(orderId); + } + return orderIds; +} + +module.exports = { + INTERCEPT_TIME_FIELD, + isEmptyInterceptTime, + buildNoticeTimePatch, + pickNoticeTimeOrderIds, +}; diff --git a/app/lib/jd_client.js b/app/lib/jd_client.js new file mode 100644 index 0000000..8878b9c --- /dev/null +++ b/app/lib/jd_client.js @@ -0,0 +1,522 @@ +'use strict'; + +const crypto = require('node:crypto'); +const http = require('node:http'); +const https = require('node:https'); + +/** 京东物流开放平台默认网关 */ +const DEFAULT_BASE_URI = 'https://api.jdl.com'; + +/** 京东物流开放平台协议版本 */ +const DEFAULT_VERSION = '2.0'; + +/** 默认签名算法(md5(content) 小写十六进制) */ +const DEFAULT_ALGORITHM = 'md5-salt'; + +/** 单次请求默认超时时间(毫秒) */ +const DEFAULT_TIMEOUT = 15000; + +/** 标识调用方 HTTP 客户端(与京东示例一致,仅作统计用途) */ +const DEFAULT_USER_AGENT = 'lop-http/nodejs'; + +/** HMac 系列算法名 → node:crypto 摘要名 */ +const HMAC_ALGORITHMS = { + HMacMD5: 'md5', + HMacSHA1: 'sha1', + HMacSHA256: 'sha256', + HMacSHA512: 'sha512', +}; + +/** 只能在 request() 传入的请求级参数(init 里传会被忽略,因此显式报错) */ +const REQUEST_ONLY_KEYS = [ 'path', 'method', 'body', 'query', 'headers', 'timestamp', 'now', 'raw' ]; + +/** + * 判断输入是否为普通对象。 + * @param {*} value 任意输入值。 + * @return {boolean} 是否为普通对象。 + */ +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * 按京东开放平台规则生成签名。 + * @param {string} algorithm 算法名:md5-salt / HMacMD5 / HMacSHA1 / HMacSHA256 / HMacSHA512。 + * @param {string} data 待签名原文(见 buildSignContent)。 + * @param {string} [secret] 密钥(仅 HMac 系列使用)。 + * @return {string} 签名值:md5-salt 为小写十六进制,HMac 系列为 base64。 + * @throws {Error} 算法不支持时抛出。 + */ +function sign(algorithm, data, secret) { + const name = String(algorithm || DEFAULT_ALGORITHM); + const text = String(data === undefined || data === null ? '' : data); + + if (name === 'md5-salt') { + return crypto.createHash('md5').update(text, 'utf8').digest('hex'); + } + + const hmacName = HMAC_ALGORITHMS[name]; + if (!hmacName) { + throw new Error(`Algorithm ${name} not supported yet`); + } + + return crypto.createHmac(hmacName, String(secret === undefined || secret === null ? '' : secret)) + .update(text, 'utf8') + .digest('base64'); +} + +/** + * 格式化签名为 `YYYY-MM-DD HH:mm:ss`(服务器本地时区,与京东 PHP 示例 date() 口径一致)。 + * @param {Date} [date] 时间对象,默认当前时间。 + * @return {string} 格式化后的时间戳。 + */ +function formatTimestamp(date = new Date()) { + const pad = num => String(num).padStart(2, '0'); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; +} + +/** + * 格式化当前时区相对 UTC 的小时数,用于 lop-tz 请求头(东八区为 '8')。 + * @param {Date} [date] 时间对象,默认当前时间。 + * @return {string} 时区小时数(如 '8'、'5.5'、'-5')。 + */ +function formatTimezoneOffset(date = new Date()) { + return String(-date.getTimezoneOffset() / 60); +} + +/** + * 拼接签名原文。 + * + * 与京东 PHP 示例完全一致: + * `secret + 'access_token' + token + 'app_key' + key + 'method' + path + + * 'param_json' + body + 'timestamp' + ts + 'v' + version + secret` + * + * @param {Object} options 签名要素。 + * @param {string} options.appSecret 应用密钥。 + * @param {string} [options.accessToken] 访问令牌。 + * @param {string} options.appKey 应用 AppKey。 + * @param {string} options.method 接口路径(京东协议中 method 即 path)。 + * @param {string} [options.paramJson] 业务报文原文。 + * @param {string} options.timestamp 请求时间戳。 + * @param {string} options.version 协议版本。 + * @return {string} 签名原文。 + */ +function buildSignContent({ appSecret, accessToken, appKey, method, paramJson, timestamp, version }) { + const toString = value => String(value === undefined || value === null ? '' : value); + return [ + toString(appSecret), + 'access_token', toString(accessToken), + 'app_key', toString(appKey), + 'method', toString(method), + 'param_json', toString(paramJson), + 'timestamp', toString(timestamp), + 'v', toString(version), + toString(appSecret), + ].join(''); +} + +/** + * 京东物流开放平台客户端(api.jdl.com)。 + * + * 使用方式: + * ```js + * const jdClient = require('./jd_client'); + * jdClient.init(appKey, appSecret, { accessToken }); + * const res = await jdClient.request({ + * path: '/jd/tracking/query', + * domain: 'Tracking_JD', + * body: [{ referenceNumber: 'JDAP20626092313', referenceType: '20000', phone: '7068' }], + * }); + * ``` + */ +class JdClient { + /** + * @param {Object} [options={}] 默认配置。 + */ + constructor(options = {}) { + this.options = { + baseUri: DEFAULT_BASE_URI, + version: DEFAULT_VERSION, + algorithm: DEFAULT_ALGORITHM, + timeout: DEFAULT_TIMEOUT, + userAgent: DEFAULT_USER_AGENT, + appKey: '', + appSecret: '', + accessToken: '', + domain: '', + logger: null, + ...options, + }; + } + + /** + * 初始化凭据与默认配置(可重复调用覆盖)。 + * + * 只能传「请求之间不变」的配置;`path` / `body` / `method` / `query` / `headers` / + * `timestamp` 等请求级参数请传给 request(),误传到这里会直接报错。 + * + * @param {string} appKey 应用 AppKey。 + * @param {string} appSecret 应用 AppSecret。 + * @param {Object} [options={}] 可选默认配置。 + * @param {string} [options.accessToken] 访问令牌,也可后续用 setAccessToken 设置。 + * @param {string} [options.domain] 接口域(LOP-DN),如 Tracking_JD。 + * @param {string} [options.baseUri] 网关地址,默认 https://api.jdl.com。 + * @param {string} [options.version] 协议版本,默认 2.0。 + * @param {string} [options.algorithm] 签名算法,默认 md5-salt。 + * @param {number} [options.timeout] 超时毫秒数,默认 15000。 + * @param {string} [options.userAgent] UA,默认 lop-http/nodejs。 + * @param {Object} [options.logger] 可选日志器(需实现 warn)。 + * @return {JdClient} 当前实例(便于链式调用)。 + * @throws {Error} options 里出现请求级参数时抛出。 + */ + init(appKey, appSecret, options = {}) { + const safeOptions = isPlainObject(options) ? options : {}; + const invalidKeys = Object.keys(safeOptions).filter(key => REQUEST_ONLY_KEYS.includes(key)); + if (invalidKeys.length > 0) { + throw new Error( + `init 不支持请求级参数:${invalidKeys.join(', ')},请在 request() 中传入` + ); + } + + this.options = { + ...this.options, + ...safeOptions, + appKey: String(appKey || '').trim(), + appSecret: String(appSecret || '').trim(), + }; + return this; + } + + /** + * 更新访问令牌。 + * @param {string} accessToken 访问令牌。 + * @return {JdClient} 当前实例。 + */ + setAccessToken(accessToken) { + this.options.accessToken = String(accessToken || '').trim(); + return this; + } + + /** + * 解析本次请求的凭据与配置(请求级参数优先于 init 默认值)。 + * @param {Object} [options={}] 请求参数。 + * @return {Object} 解析后的配置。 + */ + resolveOptions(options = {}) { + const source = isPlainObject(options) ? options : {}; + const pick = key => (source[key] === undefined || source[key] === null + ? this.options[key] + : source[key]); + + const appKey = String(pick('appKey') || '').trim(); + const appSecret = String(pick('appSecret') || '').trim(); + if (!appKey || !appSecret) { + throw new Error('京东开放平台 appKey / appSecret 未配置'); + } + + return { + appKey, + appSecret, + accessToken: String(pick('accessToken') || '').trim(), + domain: String(pick('domain') || '').trim(), + baseUri: String(pick('baseUri') || DEFAULT_BASE_URI).replace(/\/+$/, ''), + version: String(pick('version') || DEFAULT_VERSION), + algorithm: String(pick('algorithm') || DEFAULT_ALGORITHM), + timeout: Number(pick('timeout')) || DEFAULT_TIMEOUT, + userAgent: String(pick('userAgent') || DEFAULT_USER_AGENT), + logger: pick('logger') || null, + }; + } + + /** + * 序列化业务报文:字符串原样使用(签名与发送必须完全一致),其余按 JSON 序列化。 + * @param {*} body 业务报文。 + * @return {string} param_json 原文。 + */ + normalizeParamJson(body) { + if (body === undefined || body === null) return ''; + if (typeof body === 'string') return body; + return JSON.stringify(body); + } + + /** + * 构建已签名的请求参数(不发请求,便于日志与单测)。 + * @param {Object} [options={}] 请求参数。 + * @param {string} options.path 接口路径(如 /jd/tracking/query),京东协议中同时作为签名 method。 + * @param {string} [options.method='POST'] HTTP 方法。 + * @param {*} [options.body] 业务报文(对象/数组/字符串),序列化后作为 param_json。 + * @param {Object} [options.query={}] 额外查询参数(如京东要求的业务 query 参数)。 + * @param {Object} [options.headers={}] 额外请求头。 + * @param {string} [options.timestamp] 指定时间戳(默认当前本地时间),便于复现。 + * @param {Date} [options.now] 指定当前时间对象(影响时间戳与 lop-tz)。 + * @return {Object} { url, method, headers, body, paramJson, sign, timestamp, content, query }。 + */ + buildRequestOptions(options = {}) { + const { + path: apiPath, + method = 'POST', + body, + query: extraQuery = {}, + headers: extraHeaders = {}, + timestamp, + now, + } = options; + + const config = this.resolveOptions(options); + const path = String(apiPath || '').trim(); + if (!path) { + throw new Error('京东接口 path 不能为空'); + } + + const httpMethod = String(method || 'POST').toUpperCase(); + const paramJson = this.normalizeParamJson(body); + const nowDate = now instanceof Date ? now : new Date(); + const requestTimestamp = timestamp ? String(timestamp) : formatTimestamp(nowDate); + + const content = buildSignContent({ + appSecret: config.appSecret, + accessToken: config.accessToken, + appKey: config.appKey, + method: path, + paramJson, + timestamp: requestTimestamp, + version: config.version, + }); + const signValue = sign(config.algorithm, content, config.appSecret); + + const queryPairs = []; + if (config.domain) queryPairs.push([ 'LOP-DN', config.domain ]); + queryPairs.push([ 'app_key', config.appKey ]); + queryPairs.push([ 'access_token', config.accessToken ]); + queryPairs.push([ 'timestamp', requestTimestamp ]); + queryPairs.push([ 'v', config.version ]); + queryPairs.push([ 'sign', signValue ]); + queryPairs.push([ 'algorithm', config.algorithm ]); + if (httpMethod === 'GET' && paramJson) { + queryPairs.push([ 'param_json', paramJson ]); + } + for (const [ key, value ] of Object.entries(isPlainObject(extraQuery) ? extraQuery : {})) { + if (value === undefined || value === null) continue; + queryPairs.push([ key, String(value) ]); + } + + const search = new URLSearchParams(); + for (const [ key, value ] of queryPairs) { + search.append(key, value); + } + + const url = `${config.baseUri}${path}${search.toString() ? `?${search.toString()}` : ''}`; + const headers = { + 'content-type': 'application/json;charset=utf-8', + 'lop-tz': formatTimezoneOffset(nowDate), + 'user-agent': config.userAgent, + ...(isPlainObject(extraHeaders) ? extraHeaders : {}), + }; + const requestBody = httpMethod === 'GET' ? null : paramJson; + if (requestBody !== null && headers['content-length'] === undefined) { + headers['content-length'] = String(Buffer.byteLength(requestBody, 'utf8')); + } + + return { + url, + method: httpMethod, + headers, + body: requestBody, + paramJson, + sign: signValue, + timestamp: requestTimestamp, + content, + query: Object.fromEntries(queryPairs), + timeout: config.timeout, + }; + } + + /** + * 调用京东开放平台接口。 + * @param {Object} [options={}] 请求参数,见 buildRequestOptions。 + * @param {boolean} [options.raw=false] 为 true 时返回 { status, headers, text } 原始响应。 + * @return {Promise} 默认返回 { success, status, headers, data, text, url }。 + */ + async request(options = {}) { + const prepared = this.buildRequestOptions(options); + const response = await this.send(prepared); + const text = response.text; + let data = null; + try { + data = text ? JSON.parse(text) : null; + } catch (_e) { + data = text; + } + + const result = { + success: response.status >= 200 && response.status < 300, + status: response.status, + headers: response.headers, + data, + text, + url: prepared.url, + }; + + if (options && options.raw === true) { + return { status: response.status, headers: response.headers, text, url: prepared.url }; + } + return result; + } + + /** + * 发送 HTTP 请求(内置 http/https,不依赖第三方请求库)。 + * @param {Object} prepared buildRequestOptions 的返回值。 + * @return {Promise<{status: number, headers: Object, text: string}>} 响应。 + */ + send(prepared) { + return new Promise((resolve, reject) => { + const target = new URL(prepared.url); + const transport = target.protocol === 'http:' ? http : https; + const req = transport.request({ + protocol: target.protocol, + hostname: target.hostname, + port: target.port || (target.protocol === 'http:' ? 80 : 443), + path: `${target.pathname}${target.search}`, + method: prepared.method, + headers: prepared.headers, + timeout: prepared.timeout, + }, res => { + const chunks = []; + res.on('data', chunk => chunks.push(chunk)); + res.on('end', () => { + resolve({ + status: Number(res.statusCode) || 0, + headers: res.headers, + text: Buffer.concat(chunks).toString('utf8'), + }); + }); + res.on('error', reject); + }); + + req.on('timeout', () => { + req.destroy(new Error(`京东接口请求超时(${prepared.timeout}ms)`)); + }); + req.on('error', reject); + if (prepared.body !== null && prepared.body !== undefined) { + req.write(prepared.body); + } + req.end(); + }); + } + + /** + * 驱动式调用:兼容 `execute({ url, body })` 写法(与其它快递驱动保持一致)。 + * + * - `url` 可传完整地址(自动拆成 baseUri + path + query),也可只传 path; + * - `body` 为对象/数组时自动 JSON.stringify,字符串原样使用(签名与发送同一份); + * - 返回类 fetch 响应对象,支持 `await res.text()` / `await res.json()`。 + * + * @param {Object} [request={}] 请求参数。 + * @param {string} request.url 接口地址(完整 URL 或 path)。 + * @param {*} [request.body] 业务报文。 + * @param {string} [request.method='POST'] HTTP 方法。 + * @param {Object} [request.query] 额外 query 参数。 + * @param {Object} [request.headers] 额外请求头。 + * @param {string} [request.domain] 接口域(LOP-DN)。 + * @param {string} [request.accessToken] 覆盖默认 access_token。 + * @return {Promise} { ok, status, statusText, headers, url, data, text(), json() }。 + */ + async execute(request = {}) { + const safeRequest = isPlainObject(request) ? request : {}; + const targetUrl = String(safeRequest.url || '').trim(); + if (!targetUrl) { + throw new Error('京东接口 url 不能为空'); + } + + const isAbsolute = /^https?:\/\//i.test(targetUrl); + const parsed = isAbsolute ? new URL(targetUrl) : null; + const urlQuery = {}; + if (parsed) { + for (const [ key, value ] of parsed.searchParams.entries()) { + urlQuery[key] = value; + } + } + + const result = await this.request({ + ...safeRequest, + baseUri: parsed ? `${parsed.protocol}//${parsed.host}` : safeRequest.baseUri, + path: parsed ? parsed.pathname : targetUrl, + query: { ...urlQuery, ...(isPlainObject(safeRequest.query) ? safeRequest.query : {}) }, + }); + + const text = result.text === undefined || result.text === null ? '' : String(result.text); + return { + ok: result.success, + status: result.status, + statusText: result.success ? 'OK' : 'ERROR', + headers: result.headers || {}, + url: result.url, + data: result.data, + text: async () => text, + json: async () => { + if (text) return JSON.parse(text); + return null; + }, + }; + } +} + +const defaultClient = new JdClient(); + +module.exports = { + JdClient, + buildSignContent, + formatTimestamp, + formatTimezoneOffset, + sign, + /** + * 初始化默认客户端。 + * @param {string} appKey 应用 AppKey。 + * @param {string} appSecret 应用 AppSecret。 + * @param {Object} [options={}] 默认配置。 + * @return {JdClient} 默认客户端实例。 + */ + init(appKey, appSecret, options) { + return defaultClient.init(appKey, appSecret, options); + }, + /** + * 更新默认客户端的访问令牌。 + * @param {string} accessToken 访问令牌。 + * @return {JdClient} 默认客户端实例。 + */ + setAccessToken(accessToken) { + return defaultClient.setAccessToken(accessToken); + }, + /** + * 用默认客户端构建签名请求参数。 + * @param {Object} [options={}] 请求参数。 + * @return {Object} 已签名请求参数。 + */ + buildRequestOptions(options) { + return defaultClient.buildRequestOptions(options); + }, + /** + * 用默认客户端调用接口。 + * @param {Object} [options={}] 请求参数。 + * @return {Promise} 响应。 + */ + request(options) { + return defaultClient.request(options); + }, + /** + * 用默认客户端做驱动式调用(兼容 execute({ url, body }))。 + * @param {Object} [request={}] 请求参数。 + * @return {Promise} 类 fetch 响应(支持 text() / json())。 + */ + execute(request) { + return defaultClient.execute(request); + }, + /** + * 默认客户端实例。 + * @return {JdClient} 实例。 + */ + get client() { + return defaultClient; + }, +}; diff --git a/app/lib/lock_guard.js b/app/lib/lock_guard.js new file mode 100644 index 0000000..d1ef960 --- /dev/null +++ b/app/lib/lock_guard.js @@ -0,0 +1,29 @@ +'use strict'; + +/** + * 订单锁定状态共享定义。 + * + * wms_order_delivery.lock_status 枚举(order_delivery.js / order_delivery_factory.js)实际取值为: + * none / warehouse / store。 + * + * 业务约定:锁定状态只要不是 'none'(即被仓库或货主锁定的订单),一律视为"已锁定", + * 禁止继续执行仓储作业(分配储位/分配快递/抓取波次/自动加团等), + * 已锁定订单一律跳过。 + */ +const LOCK_STATUS_NONE = 'none'; + +/** + * 判断订单锁定状态是否属于"已锁定"。 + * 空值/NULL 归一化为 none 处理;除此之外任何非 none 状态(含 warehouse/store)均视为已锁定。 + * @param {*} status 锁定状态值。 + * @return {boolean} 是否已锁定。 + */ +function isLockedOrderStatus(status) { + const normalizedStatus = String(status || '').trim() || LOCK_STATUS_NONE; + return normalizedStatus !== LOCK_STATUS_NONE; +} + +module.exports = { + LOCK_STATUS_NONE, + isLockedOrderStatus, +}; diff --git a/app/lib/order_lookup.js b/app/lib/order_lookup.js new file mode 100644 index 0000000..901949f --- /dev/null +++ b/app/lib/order_lookup.js @@ -0,0 +1,105 @@ +'use strict'; + +/** + * 订单分表跨表查询共享工具。 + * + * 订单按仓库分表且按生命周期流转于多张物理表之间: + * current(待出库)→ dispatch(配送)→ history(历史归档),另有 outsourced(外包)。 + * 各分表唯一索引均为 (delivery_order_code, store_id, warehouse_id),跨表间约束独立。 + * 任何"按单号判断订单是否存在/可用"的场景都必须跨表遍历,否则会误判 + * (如订单已流转到 dispatch 后,仅查 current 会返回"未找到订单",诱导调用方重推)。 + * + * 注意事项: + * - 分表模型首次获取可能执行 DDL(隐式提交),因此必须在事务外调用 preloadOrderModels + * 完成模型预取,再在事务内用 findOrderAcrossTables 查询; + * - findOrderByCodeAcrossTables 内部会预取模型,仅适用于非事务场景。 + */ + +/** 默认跨表查找顺序:current → dispatch → history → outsourced。 */ +const TABLE_TYPE_ORDER = [ 'current', 'dispatch', 'history', 'outsourced' ]; + +/** 表位 → OrderDeliveryFactory 模型获取方法名。 */ +const MODEL_GETTER_BY_TYPE = { + current: 'getCurrentModel', + dispatch: 'getDispatchModel', + history: 'getHistoryModel', + outsourced: 'getOutsourcedModel', +}; + +/** + * 预取订单分表模型。 + * 必须在事务外调用:模型首次获取可能执行 DDL(隐式提交)。 + * + * @param {Object} ctx egg ctx。 + * @param {string|number} warehouseId 仓库ID(分表后缀)。 + * @param {string[]} [tableTypes] 需要预取的表位,默认四表。 + * @return {Promise} 表位 → 模型 的映射(缺失模型不会出现在结果中)。 + */ +async function preloadOrderModels(ctx, warehouseId, tableTypes = TABLE_TYPE_ORDER) { + const factory = ctx && ctx.model && ctx.model.OrderDeliveryFactory; + if (!factory) { + throw new Error('OrderDeliveryFactory 不可用,无法跨表查询订单'); + } + const models = {}; + for (const tableType of tableTypes) { + const getter = MODEL_GETTER_BY_TYPE[tableType]; + if (!getter || typeof factory[getter] !== 'function') { + continue; + } + const model = await factory[getter](warehouseId); + if (model && typeof model.findOne === 'function') { + models[tableType] = model; + } + } + return models; +} + +/** + * 跨表按条件查找订单,按 tableTypes 顺序命中即停。 + * + * @param {Object} models preloadOrderModels 返回的表位 → 模型映射。 + * @param {Object} where 查询条件(findOne where,例如 delivery_order_code + store_id + warehouse_id)。 + * @param {Object} [options] 可选配置。 + * @param {string[]} [options.tableTypes] 查找表位顺序,默认四表。 + * @param {Object} [options.findOptions] 透传给 findOne 的其余选项(transaction/lock/attributes 等)。 + * @return {Promise<{ order: Object|null, location: string|null }>} 命中订单与所在表位;未命中 order=null。 + */ +async function findOrderAcrossTables(models, where, options = {}) { + const { tableTypes = TABLE_TYPE_ORDER, findOptions = {} } = options; + for (const tableType of tableTypes) { + const model = models && models[tableType]; + if (!model || typeof model.findOne !== 'function') { + continue; + } + const order = await model.findOne({ + where, + ...findOptions, + }); + if (order) { + return { order, location: tableType }; + } + } + return { order: null, location: null }; +} + +/** + * 便捷入口:预取模型后按条件跨表查找(仅限非事务场景)。 + * 事务内请使用 preloadOrderModels + findOrderAcrossTables。 + * + * @param {Object} ctx egg ctx。 + * @param {string|number} warehouseId 仓库ID。 + * @param {Object} where 查询条件。 + * @param {Object} [options] 同 findOrderAcrossTables 的 options,另支持 tableTypes 用于预取过滤。 + * @return {Promise<{ order: Object|null, location: string|null }>} 命中订单与所在表位;未命中 order 为 null。 + */ +async function findOrderByCodeAcrossTables(ctx, warehouseId, where, options = {}) { + const models = await preloadOrderModels(ctx, warehouseId, options.tableTypes); + return findOrderAcrossTables(models, where, options); +} + +module.exports = { + TABLE_TYPE_ORDER, + preloadOrderModels, + findOrderAcrossTables, + findOrderByCodeAcrossTables, +}; diff --git a/app/lib/osd_client.js b/app/lib/osd_client.js new file mode 100644 index 0000000..ac78c33 --- /dev/null +++ b/app/lib/osd_client.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * OSD(屏幕菜单叠加)客户端模块。 + * 负责组装 RTSP URL 并调用打印服务设置摄像头 OSD 文字叠加。 + * + * 使用方式: + * const osdClient = new (require('../lib/osd_client'))(ctx); + * await osdClient.setOsd({ camera, warehouseId, text, x, y }); + */ +class OsdClient { + constructor(ctx) { + this.ctx = ctx; + this.logger = ctx.logger || console; + } + + /** + * 组装摄像头 RTSP 地址 + * 格式: rtsp://{username}:{password}@{ip}:554/stream{channelId} + * + * @param {Object} camera - 摄像头记录(含 ip/username/password/channel_id) + * @return {string} RTSP URL + */ + buildRtspUrl(camera) { + const ip = camera.ip; + if (!ip) { + throw new Error('摄像头未配置IP地址,无法组装RTSP地址'); + } + + const username = camera.username || 'admin'; + const password = camera.password || ''; + const channelId = camera.channel_id; + const rtspPort = 554; + + return `rtsp://${username}:${password}@${ip}:${rtspPort}/stream${channelId}`; + } + + /** + * 发送 OSD 叠加指令到打印服务 + * + * @param {Object} options - 配置选项 + * @param {Object} options.camera - 摄像头记录 + * @param {Object} [options.server] - 关联的录像服务器(fallback 认证信息) + * @param {number} options.warehouseId - 仓库ID + * @param {string} options.text - OSD 叠加文字 + * @param {number} [options.x] - X 坐标(-1 到 1,默认 -0.9) + * @param {number} [options.y] - Y 坐标(-1 到 1,默认 0.8) + * @return {Promise} 打印服务响应 { status, data, error } + */ + async setOsd(options = {}) { + const { ctx } = this; + const { camera, warehouseId, text, x, y } = options; + + if (!camera) throw new Error('摄像头信息不能为空'); + if (!text) throw new Error('OSD文字不能为空'); + if (warehouseId === undefined || warehouseId === null) throw new Error('仓库ID不能为空'); + + const rtspUrl = this.buildRtspUrl(camera); + const printServiceUrl = ctx.app.config.printService.url; + + const requestData = { + warehouse_id: String(warehouseId), + rtspUrl, + text, + x: x !== undefined ? x : -0.9, + y: y !== undefined ? y : 0.8, + }; + + const targetUrl = `${printServiceUrl}/camera/setOSD`; + ctx.logger.info('[OSD] 发送设置请求', { url: targetUrl, body: requestData }); + + let response = null; + let error = null; + try { + const res = await ctx.curl(targetUrl, { + method: 'POST', + contentType: 'json', + data: requestData, + dataType: 'json', + timeout: 10000, + }); + response = { + status: res.status, + headers: res.headers, + data: res.data, + }; + ctx.logger.info('[OSD] 打印服务回信', { status: res.status, data: res.data }); + } catch (err) { + error = err.message; + ctx.logger.warn('[OSD] 打印服务请求失败', { camera_id: camera.id, error: err.message }); + } + + return { + success: !error && response && response.status >= 200 && response.status < 300, + error, + response, + request: requestData, + }; + } +} + +module.exports = OsdClient; diff --git a/app/lib/pdd_client.js b/app/lib/pdd_client.js new file mode 100644 index 0000000..3f354e4 --- /dev/null +++ b/app/lib/pdd_client.js @@ -0,0 +1,150 @@ +'use strict'; + +const pddSign = require('./pdd_sign'); + +const DEFAULT_BASE_URL = 'https://gw-api.pinduoduo.com/api/router'; + +/** + * 判断输入是否为普通对象。 + * @param {*} value 任意输入值。 + * @return {boolean} 是否为普通对象。 + */ +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * 获取当前秒级时间戳。 + * @return {string} 秒级 UNIX 时间戳。 + */ +function nowSec() { + return String(Math.floor(Date.now() / 1000)); +} + +/** + * 拼多多开放平台 API 客户端。 + * 负责组装请求体、生成签名、发送请求。 + */ +class PddClient { + /** + * @param {object} ctx - Egg 上下文对象。 + * @param {object} [options={}] - 客户端默认配置。 + */ + constructor(ctx, options = {}) { + this.ctx = ctx; + this.options = options; + } + + /** + * 解析客户端凭据。 + * @param {object} [options={}] 请求级配置。 + * @return {{ clientId: string, clientSecret: string }} 凭据。 + */ + resolveCredentials(options = {}) { + const config = (this.ctx && this.ctx.app && this.ctx.app.config && this.ctx.app.config.pdd) || {}; + + const clientId = options.clientId + ?? this.options.clientId + ?? config.client_id + ?? config.clientId + ?? ''; + const clientSecret = options.clientSecret + ?? this.options.clientSecret + ?? config.client_secret + ?? config.clientSecret + ?? ''; + + return { + clientId: String(clientId || '').trim(), + clientSecret: String(clientSecret || '').trim(), + }; + } + + /** + * 构建请求体。 + * @param {object} [options={}] 请求参数。 + * @return {{ requestBody: object, signText: string, sortedPairs: Array<[string, string]> }} 请求体和签名信息。 + */ + buildRequest(options = {}) { + const { + type, + bizParams = {}, + request = {}, + accessToken, + dataType = 'JSON', + version, + timestamp = nowSec(), + } = options; + + const { clientId, clientSecret } = this.resolveCredentials(options); + const payload = isPlainObject(bizParams) ? { ...bizParams } : {}; + if (isPlainObject(request)) { + Object.assign(payload, request); + } + + const signed = pddSign.buildRequestBody({ + type, + clientId, + timestamp, + dataType, + accessToken, + version, + bizParams: payload, + clientSecret, + }); + + return signed; + } + + /** + * 发起拼多多 API 请求。 + * @param {object} [options={}] 请求参数。 + * @return {Promise} 接口响应。 + */ + async request(options = {}) { + const { + baseUrl = DEFAULT_BASE_URL, + headers = {}, + timeout, + responseType = 'json', + } = options; + + if (!baseUrl) { + throw new Error('baseUrl 不能为空'); + } + + const { requestBody } = this.buildRequest(options); + const response = await this.ctx.curl(String(baseUrl), { + method: 'POST', + dataType: responseType, + timeout, + headers: { + 'Content-Type': 'application/json', + ...(headers || {}), + }, + data: requestBody, + }); + + return response && response.data !== undefined ? response.data : response; + } + + /** + * 同步调用接口,和 request 等价。 + * @param {object} [options={}] 请求参数。 + * @return {Promise} 接口响应。 + */ + async syncInvoke(options = {}) { + return this.request(options); + } + + /** + * 异步调用接口,和 request 等价。 + * @param {object} [options={}] 请求参数。 + * @return {Promise} 接口响应。 + */ + async asyncInvoke(options = {}) { + return this.request(options); + } +} + +module.exports = PddClient; diff --git a/app/lib/pdd_sign.js b/app/lib/pdd_sign.js new file mode 100644 index 0000000..e3c32c2 --- /dev/null +++ b/app/lib/pdd_sign.js @@ -0,0 +1,189 @@ +'use strict'; + +const crypto = require('node:crypto'); + +/** + * 判断输入是否为普通对象。 + * @param {*} value 任意输入值。 + * @return {boolean} 是否为普通对象。 + */ +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * 将对象按 key 排序后稳定序列化。 + * @param {*} value 待序列化值。 + * @return {string} 稳定序列化字符串。 + */ +function stableStringify(value) { + if (value === undefined) { + return 'null'; + } + + if (value === null || typeof value !== 'object') { + return JSON.stringify(value); + } + + if (Array.isArray(value)) { + return `[${value.map(item => stableStringify(item)).join(',')}]`; + } + + if (!isPlainObject(value)) { + return JSON.stringify(value); + } + + const keys = Object.keys(value) + .filter(key => value[key] !== undefined) + .sort(); + return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`; +} + +/** + * 归一化参数值为可拼接字符串。 + * @param {*} value 参数值。 + * @return {string} 归一化后的字符串。 + */ +function normalizeValue(value) { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + return stableStringify(value); + } + + return String(value); +} + +/** + * 归一化密钥值。 + * @param {string} clientSecret 客户端密钥。 + * @return {string} 归一化后的密钥。 + */ +function normalizeSecret(clientSecret) { + return String(clientSecret || '').trim(); +} + +/** + * 归一化并排序请求参数。 + * @param {Object} [params={}] 请求参数。 + * @return {Array<[string, string]>} 排序后的键值对。 + */ +function buildSortedPairs(params = {}) { + if (!isPlainObject(params)) { + throw new Error('params 必须是对象'); + } + + return Object.keys(params) + .filter(key => params[key] !== undefined) + .sort() + .map(key => [ key, normalizeValue(params[key]) ]); +} + +/** + * 构建拼多多签名原文。 + * @param {Object} [params={}] 所有参与签名的参数。 + * @param {string} clientSecret 客户端密钥。 + * @return {{ signText: string, sortedPairs: Array<[string, string]> }} 签名原文与排序结果。 + */ +function buildSignText(params = {}, clientSecret) { + const secret = normalizeSecret(clientSecret); + if (!secret) { + throw new Error('clientSecret 不能为空'); + } + + const sortedPairs = buildSortedPairs(params); + const signText = secret + sortedPairs.map(([ key, value ]) => key + value).join('') + secret; + + return { + signText, + sortedPairs, + }; +} + +/** + * 生成拼多多 API 签名。 + * @param {Object} [params={}] 所有参与签名的参数。 + * @param {string} clientSecret 客户端密钥。 + * @return {{ sign: string, signText: string, sortedPairs: Array<[string, string]> }} 签名结果。 + */ +function sign(params = {}, clientSecret) { + const { signText, sortedPairs } = buildSignText(params, clientSecret); + + return { + signText, + sortedPairs, + sign: crypto.createHash('md5').update(signText, 'utf8').digest('hex') + .toUpperCase(), + }; +} + +/** + * 构建拼多多接口请求体,并自动补充 sign。 + * @param {Object} [options={}] 请求选项。 + * @param {string} options.type API 接口名。 + * @param {string|number} options.clientId 应用 client_id。 + * @param {string|number} options.timestamp UNIX 时间戳。 + * @param {string} [options.dataType='JSON'] 返回数据格式。 + * @param {string} [options.accessToken] 用户授权令牌。 + * @param {string} [options.version] API 版本。 + * @param {Object} [options.bizParams={}] 业务参数。 + * @param {string} options.clientSecret 客户端密钥。 + * @return {{ requestBody: Object, signText: string, sortedPairs: Array<[string, string]> }} 请求结果。 + */ +function buildRequestBody(options = {}) { + const { + type, + clientId, + timestamp, + dataType = 'JSON', + accessToken, + version, + bizParams = {}, + clientSecret, + } = options; + + const requestBody = { + ...(isPlainObject(bizParams) ? bizParams : {}), + type, + client_id: clientId, + timestamp, + data_type: dataType, + access_token: accessToken, + version, + }; + + Object.keys(requestBody).forEach(key => { + if (requestBody[key] === undefined || requestBody[key] === null || requestBody[key] === '') { + delete requestBody[key]; + } + }); + + // PDD 路由参数验签以字符串值为准,复杂参数需与签名使用同一序列化结果。 + Object.keys(requestBody).forEach(key => { + if (requestBody[key] && typeof requestBody[key] === 'object') { + requestBody[key] = normalizeValue(requestBody[key]); + } + }); + + const signed = sign(requestBody, clientSecret); + + return { + requestBody: { + ...requestBody, + sign: signed.sign, + }, + signText: signed.signText, + sortedPairs: signed.sortedPairs, + }; +} + +module.exports = { + buildRequestBody, + buildSignText, + normalizeSecret, + normalizeValue, + sign, + stableStringify, +}; diff --git a/app/lib/polo_api_client.js b/app/lib/polo_api_client.js new file mode 100644 index 0000000..f400c75 --- /dev/null +++ b/app/lib/polo_api_client.js @@ -0,0 +1,218 @@ +'use strict'; + +const crypto = require('crypto'); + +/** + * PolyAPI 底层 HTTP 客户端。 + * 封装签名、表单编码、请求发送等通用逻辑,与业务无关。 + */ +class PoloApiClient { + /** + * @param {object} ctx - Egg 上下文对象。 + */ + constructor(ctx) { + this.ctx = ctx; + this.contenttype = 'json'; + } + + /** + * 发起 PolyAPI 表单 POST 请求。 + * + * @param {object} options - 请求参数。 + * @param {string} options.method - 远端接口方法名。 + * @param {number|string} options.platid - 平台 ID。 + * @param {object|string} [options.bizcontent={}] - 业务参数内容。 + * @return {Promise} 接口响应 data。 + */ + async request(options = {}) { + const { + method, + bizcontent = {}, + config = {}, + token, + } = options; + if (!config || !config.interface_url) { + throw new Error('[PoloApiClient.request] 未提供有效的 config,无法发送请求'); + } + const configWithToken = config; + if (token) { + configWithToken.token = token; + } + console.log('configWithToken', configWithToken); + const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent); + console.log('signMap', signMap); + const signText = this._getSignText(signMap, config.app_secret); + const sign = this._md5(signText); + // const formBody = this._encodeForm({ ...signMap, sign }); + signMap.sign = sign; + const formBody = Object.keys(signMap) + .map(key => `${key}=${encodeURIComponent(signMap[key])}`) + .join('&'); + console.log('查询菠萝派平台数据,接口URL:', config.interface_url, '入参bizcontent:', JSON.stringify(bizcontent)); + + await this.ctx.app.setCacheAsync('PoloApiquery', '查询菠萝派平台数据,接口URL:' + config.interface_url + ',入参bizcontent:' + formBody, 3600); + + 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, + }); + + console.log('formBody', formBody); + let result; + if (Buffer.isBuffer(response.data)) { + // 如果是 Buffer,转字符串再解析 + const str = response.data.toString('utf8'); + result = JSON.parse(str); + } else if (typeof response.data === 'string') { + result = JSON.parse(response.data); + } else { + result = response.data; + } + await this.ctx.app.setCacheAsync('PoloApiresult', JSON.stringify(result), 3600); + return result; + } + + /** + * 发起 PolyAPI GET 请求。 + * + * @param {object} options - 请求参数。 + * @param {string} options.method - 远端接口方法名。 + * @param {object|string} [options.bizcontent={}] - 业务参数内容。 + * @param {object} [options.config={}] - 平台配置。 + * @param {string} [options.token] - 可选 token,传入时优先覆盖配置 token。 + * @return {Promise} 接口响应 data。 + */ + async get(options = {}) { + const { + method, + bizcontent = {}, + config = {}, + token, + } = options; + if (!config || !config.interface_url) { + throw new Error('[PoloApiClient.get] 未提供有效的 config,无法发送请求'); + } + const configWithToken = { ...config, token: token || config.token }; + const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent); + const signText = this._getSignText(signMap, config.app_secret); + const sign = this._md5(signText); + const formBody = this._encodeForm({ ...signMap, sign }); + const requestUrl = `http://39.98.7.126/OpenApi/Do?${formBody}`; + + const response = await this.ctx.curl(requestUrl, { + method: 'GET', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + }, + }); + let result; + if (Buffer.isBuffer(response.data)) { + // 如果是 Buffer,转字符串再解析 + const str = response.data.toString('utf8'); + console.log('菠萝派平台接口响应原始数据', str); + result = JSON.parse(str); + } else if (typeof response.data === 'string') { + result = JSON.parse(response.data); + } else { + result = response.data; + } + return result; + + } + // ── 内部方法 ── + + /** + * 组装签名所需的请求参数。 + * @param {object} config 平台配置对象。 + * @param {string} method 接口方法名。 + * @param {number|string} platid 平台 ID。 + * @param {object|string} bizcontent 业务参数。 + * @return {object} 签名参数映射。 + */ + _buildSignMap(config, method, platid, bizcontent) { + const normalizedBizcontent = bizcontent && typeof bizcontent === 'object' + ? JSON.stringify(bizcontent) + : (bizcontent === undefined || bizcontent === null ? '' : bizcontent); + const res = { + method, + appkey: config.appkey, + platid, + version: config.version, + contenttype: this.contenttype, + bizcontent: normalizedBizcontent, + timestamp: this._formatDate(new Date()), + }; + if (config.token) { + res.token = config.token; + } + return res; + } + + /** + * 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。 + * @param {object} signMap 待签名参数映射。 + * @param {string} secret 签名密钥。 + * @return {string} 转小写后的签名原文字符串。 + */ + _getSignText(signMap, secret) { + let sb = '' + secret; + Object.keys(signMap).sort().forEach(key => { + sb += key + signMap[key]; + }); + sb += secret; + return sb.toLowerCase(); + } + + /** + * MD5 摘要。 + * @param {string} text 待摘要文本。 + * @param {BufferEncoding} [encoding='utf8'] 文本编码。 + * @return {string} 十六进制 MD5 值。 + */ + _md5(text, encoding = 'utf8') { + return crypto.createHash('md5').update(text, encoding).digest('hex'); + } + + /** + * 将参数编码为 application/x-www-form-urlencoded。 + * @param {object} map 表单参数映射。 + * @return {string} URL 编码后的查询串。 + */ + _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。 + * @param {Date} date 日期对象。 + * @return {string} 格式化后的时间字符串。 + */ + _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()); + } + + /** + * 格式化取件日期。 + * @param {number} year 年。 + * @param {number} month 月。 + * @param {number} day 日。 + * @return {string} 取件日期时间字符串。 + */ + _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/printer_data_builder.js b/app/lib/printer_data_builder.js new file mode 100644 index 0000000..c253dab --- /dev/null +++ b/app/lib/printer_data_builder.js @@ -0,0 +1,2737 @@ +'use strict'; + +/** + * 打印数据中间态组装器。 + * + * 入参说明(buildPlatformRequestSkeleton): + * - input.platform: 平台标识,支持 cainiao、douyin、jd、kuaishou、pdd、sph、xhs 及其常见别名。 + * - input.order_express: 订单快递对象(建议来自 wms_order_express)。 + * - input.order_delivery: 订单对象(建议来自 wms_order_delivery_xxxxxx 分表模型查询结果)。 + * - input.store_contract / input.policy_config: 货主-仓库签约配置,至少应包含 policy_config。 + * - input.template_sample: 平台模板样例对象(建议读取 printer_data_template/*.json 后传入)。 + * - input.options: 可选配置,如 requestId/taskId/documentId/printer/preview。 + * + * 出参说明: + * - platform: 归一化后的平台编码。 + * - platform_meta: 平台映射元信息(名称、别名、模板文件名等)。 + * - base_data: 通用打印基础数据(sender/receiver/items/channel/template)。 + * - request_skeleton: 平台请求骨架(中间态,不直接可发)。 + * - missing_fields: 缺失字段列表(按 path 标注)。 + * - warnings: 风险与提示信息列表。 + * + * 哪些信息“足够”: + * - 收发件人基础字段、订单商品、运单号、平台编码、模板 URL(若样例里存在)通常足够构建中间态骨架。 + * + * 哪些信息“不足”: + * - encryptedData / signature / sign / encryptedtoken / encryptprintinfo 等平台私有密文或签名字段, + * 无法仅靠订单与模板样例安全生成,必须由上游平台适配器(持有密钥/签名算法)补齐。 + */ + +/** + * 平台硬编码映射。 + * @type {Object} + */ +const PLATFORM_MAP = Object.freeze({ + cainiao: Object.freeze({ + name: '菜鸟', + aliases: [ 'cn', 'cainiao', 'taobao', 'tb' ], + template_file: 'cainiao.json', + }), + douyin: Object.freeze({ + name: '抖音', + aliases: [ 'douyin', 'dy', 'tiktok' ], + template_file: 'douyin.json', + }), + jd: Object.freeze({ + name: '京东', + aliases: [ 'jd', 'jingdong' ], + template_file: 'jd.json', + }), + kuaishou: Object.freeze({ + name: '快手', + aliases: [ 'kuaishou', 'ks' ], + template_file: 'kuaishou.json', + }), + pdd: Object.freeze({ + name: '拼多多', + aliases: [ 'pdd', 'pinduoduo' ], + template_file: 'pdd.json', + }), + sph: Object.freeze({ + name: '视频号', + aliases: [ 'sph', 'shipinhao', 'wechatvideo' ], + template_file: 'sph.json', + }), + xhs: Object.freeze({ + name: '小红书', + aliases: [ 'xhs', 'xiaohongshu', 'red' ], + template_file: 'xhs.json', + }), +}); + +const PRIVATE_PAYLOAD_FIELDS = Object.freeze([ + 'encryptedData', + 'signature', + 'sign', + 'encryptedtoken', + 'encryptprintinfo', +]); + +/** + * 换行符映射,供不同平台分支复用。 + * @type {Object} + */ +const LINE_BREAK_MAP = Object.freeze({ + LF: '\n', + CR: '\r', + CRLF: '\r\n', +}); + +/** 快手加密密钥(wms_order_express.encryptprintinfo)长度上限:实测 172 字符,密文为数千字符。 */ +const KUAISHOU_ENCRYPT_KEY_MAX_LENGTH = 512; + +/** + * 拼多多自定义区默认模板地址。 + * @type {string} + */ +const DEFAULT_PDD_CUSTOM_TEMPLATE_URL = 'http://www.ye4s.com/mb/pdd.xml'; +/** + * 小红书自定义区默认模板地址。 + * @type {string} + */ +const DEFAULT_XHS_CUSTOM_TEMPLATE_URL = 'https://cloudprint.xiaohongshu.com/template/standard/7/2'; +const WAYBILL_CUSTOM_DISPLAY_FIELD = 'waybill_custom_display_type'; +const WAYBILL_CUSTOM_DISPLAY_TYPES = Object.freeze({ + HIDE: '1', + ITEM_NAME_QTY: '2', + PICK_LOCATION_BARCODE_QTY: '3', + PICK_LOCATION_BARCODE_LAST5_QTY: '4', + PICK_LOCATION_NAME_BARCODE_QTY: '5', +}); + +/** + * 视频号(SPH)自定义区最大行数:超出部分全部舍弃。 + * 视频号面单自定义区仅可容纳 8 行文本,超过后客户端会出现溢出/错版。 + * @type {number} + */ +const SPH_CUSTOM_INFO_MAX_LINES = 8; + +/** + * 视频号(SPH)自定义区文本行分隔标记。 + * @type {string} + */ +const SPH_CUSTOM_INFO_LINE_BREAK = '
    '; + +const ARRAY_STYLE_KEYS = new Set([ + 'documents', + 'taskList', + 'contents', +]); + +const TEMPLATE_LEAF_KEEP_KEYS = Object.freeze(new Set([ + 'cmd', + 'command', + 'orderType', + 'requestID', + 'requetID', + 'version', + 'taskID', + 'documentID', + 'printer', + 'preview', + 'templateURL', + 'templateUrl', + 'tempUrl', + 'customTempUrl', + 'templateId', + 'templateID', + 'key', + 'ERPId', + 'userid', + 'userId', + 'ver', + 'printType', +])); + +/** + * 判断值是否为普通对象。 + * @param {any} value 待判断值。 + * @return {boolean} 是否普通对象。 + */ +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * 统一换行符表示。 + * + * @param {any} value 原始值。 + * @param {string} [lineBreak=LINE_BREAK_MAP.LF] 目标换行符。 + * @return {string} 规范化后的字符串。 + */ +function normalizeLineBreak(value, lineBreak = LINE_BREAK_MAP.LF) { + const text = String(value === undefined || value === null ? '' : value); + + if (lineBreak === LINE_BREAK_MAP.CRLF) { + return text.replace(/\r\n|\r|\n/g, LINE_BREAK_MAP.CRLF); + } + + if (lineBreak === LINE_BREAK_MAP.CR) { + return text.replace(/\r\n|\r|\n/g, LINE_BREAK_MAP.CR); + } + + return text.replace(/\r\n|\r/g, LINE_BREAK_MAP.LF); +} + +/** + * 安全转换字符串并去空白。 + * @param {any} value 原始值。 + * @return {string} 转换后的字符串。 + */ +function toTrimmedString(value) { + return normalizeLineBreak(value).trim(); +} + +/** + * 安全转换数值。 + * @param {any} value 原始值。 + * @param {number} fallback 默认值。 + * @return {number} 转换后的数值。 + */ +function toNumber(value, fallback = 0) { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : fallback; +} + +/** + * 规范化平台别名。 + * @param {string} inputPlatform 入参平台。 + * @return {{platform: string, meta: Object|null, raw: string}} 规范化结果。 + */ +function normalizePlatformAlias(inputPlatform) { + const raw = toTrimmedString(inputPlatform).toLowerCase(); + + if (!raw) { + return { platform: '', meta: null, raw }; + } + + for (const platform of Object.keys(PLATFORM_MAP)) { + const meta = PLATFORM_MAP[platform]; + if (platform === raw || meta.aliases.includes(raw)) { + return { platform, meta, raw }; + } + } + + return { platform: raw, meta: null, raw }; +} + +/** + * 解析订单商品数据。 + * @param {any} rawItems 原始 items 字段(字符串或数组)。 + * @return {Array} 商品列表。 + */ +function parseItems(rawItems) { + if (Array.isArray(rawItems)) { + return rawItems; + } + + if (isPlainObject(rawItems)) { + for (const key of Object.keys(rawItems)) { + if (Array.isArray(rawItems[key])) { + return rawItems[key]; + } + } + + const candidates = [ + rawItems.items, + rawItems.list, + rawItems.goods, + rawItems.products, + rawItems.product_list, + rawItems.rows, + ]; + + for (const candidate of candidates) { + if (Array.isArray(candidate)) { + return candidate; + } + } + + return []; + } + + if (typeof rawItems === 'string') { + const text = rawItems.trim(); + if (!text) { + return []; + } + + try { + const parsed = JSON.parse(text); + return parseItems(parsed); + } catch (error) { + const isNoiseQuantityOnlyText = value => { + const sample = String(value || '').trim(); + if (!sample) { + return true; + } + + return /^(?:\[?\s*\d+(?:\.\d+)?\s*\]?|【\s*\d+(?:\.\d+)?\s*】)(?:\s+0+)?$/.test(sample); + }; + + const parseLooseItemText = rawText => { + const normalizedText = String(rawText || '').replace(/[;;]+$/g, '').trim(); + if (!normalizedText || isNoiseQuantityOnlyText(normalizedText)) { + return null; + } + + let quantity = '1'; + let workingText = normalizedText; + + const qtyBracketMatch = workingText.match(/【\s*(\d+(?:\.\d+)?)\s*】/); + if (qtyBracketMatch) { + quantity = String(qtyBracketMatch[1] || '1').trim() || '1'; + workingText = workingText.replace(qtyBracketMatch[0], ' ').trim(); + } else { + const qtyTailMatch = workingText.match(/(?:[xX×*]\s*(\d+(?:\.\d+)?))\s*$/); + if (qtyTailMatch) { + quantity = String(qtyTailMatch[1] || '1').trim() || '1'; + workingText = workingText.slice(0, qtyTailMatch.index).trim(); + } + } + + const barcodeMatch = workingText.match(/(?:^|[;;\s])(\d{5,})(?!\d)/); + const barcode = barcodeMatch ? String(barcodeMatch[1] || '').trim() : ''; + + let pickLocation = ''; + let itemName = workingText; + const locationMatch = workingText.match(/^([^\s;;]+(?:[-_][^\s;;]+)*)\s+/); + if (locationMatch) { + pickLocation = String(locationMatch[1] || '').trim(); + itemName = workingText.slice(locationMatch[0].length).trim(); + } + + if (barcode) { + itemName = itemName.replace(new RegExp(`(?:^|[;;\\s])${barcode}(?:$|[;;\\s])`), ' ').trim(); + } + itemName = itemName.replace(/[;;]+/g, ' ').trim(); + + if (isNoiseQuantityOnlyText(itemName)) { + itemName = ''; + } + + return { + pick_location: pickLocation, + item_name: itemName || workingText, + barcode, + quantity, + raw_text: normalizedText, + }; + }; + + const itemTextList = text + .split(/\||\r\n|\n|\r/) + .map(part => String(part || '').trim()) + .filter(Boolean); + + if (itemTextList.length === 0) { + return []; + } + + const parsedItems = itemTextList + .map(itemText => parseLooseItemText(itemText)) + .filter(item => isPlainObject(item)); + return parsedItems; + } + } + + return []; +} + +/** + * 解析自定义区商品来源,优先兼容 order_delivery 与 order_express 双来源。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @return {Array} 商品列表。 + */ +function resolveCustomComposeItems(orderExpress, orderDelivery) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const deliveryItems = parseItems(safeOrderDelivery.items); + if (deliveryItems.length > 0) { + return deliveryItems; + } + + return parseItems(safeOrderExpress.items); +} + +/** + * 在候选键中读取首个非空字段。 + * @param {Object} item 商品对象。 + * @param {Array} keyList 候选键列表。 + * @return {string} 文本值。 + */ +function getFirstNonEmptyText(item, keyList = []) { + if (!isPlainObject(item)) { + return ''; + } + + for (const key of keyList) { + const value = item[key]; + if (value === undefined || value === null) { + continue; + } + + const text = String(value).trim(); + if (text) { + return text; + } + } + + return ''; +} + +/** + * 读取条码文本,支持数组与多种命名。 + * @param {Object} item 商品对象。 + * @return {string} 条码文本。 + */ +function resolveItemBarcodeText(item) { + if (!isPlainObject(item)) { + return ''; + } + + const barcodeList = []; + const arrayBarcodes = [ item.barcodes, item.barcode_list ]; + for (const barcodes of arrayBarcodes) { + if (!Array.isArray(barcodes)) { + continue; + } + + for (const code of barcodes) { + const codeText = String(code === undefined || code === null ? '' : code).trim(); + if (codeText) { + barcodeList.push(codeText); + } + } + } + + if (barcodeList.length > 0) { + return barcodeList.join(';'); + } + + return getFirstNonEmptyText(item, [ + 'barcode', + 'bar_code', + 'item_barcode', + 'item_code', + 'sku_code', + 'sku', + ]); +} + +/** + * 读取数量文本。 + * @param {Object} item 商品对象。 + * @return {{qtyText: string, qtyNumber: number}} 数量文本与数值。 + */ +function resolveItemQuantity(item) { + if (!isPlainObject(item)) { + return { qtyText: '0', qtyNumber: 0 }; + } + + const qtyKeyList = [ + 'quantity', + 'qty', + 'num', + 'plan_qty', + 'actual_quantity', + 'buy_amount', + ]; + + for (const key of qtyKeyList) { + if (!Object.prototype.hasOwnProperty.call(item, key)) { + continue; + } + + const rawValue = item[key]; + const qtyText = String(rawValue === undefined || rawValue === null ? '' : rawValue).trim(); + if (!qtyText) { + continue; + } + + const qtyNumber = Number(qtyText); + return { + qtyText, + qtyNumber: Number.isFinite(qtyNumber) ? qtyNumber : 0, + }; + } + + return { qtyText: '0', qtyNumber: 0 }; +} + +/** + * 根据货主配置构建面单自定义区商品信息。 + * @param {Array} items 商品列表。 + * @param {Object} policyConfig 策略配置。 + * @param {Object} options 附加选项。 + * @param {string} [options.waveNo] 波次号。 + * @param {number} [options.wave_total_orders] 波次总订单数。 + * @param {number} [options.wave_index] 当前波次内序号。 + * @param {number} [options.platforms_index] 平台内序号。 + * @param {string} [options.expressInterfaceName] 快递渠道显示名。 + * @param {number} [options.fallbackTotalQty] 订单级商品总数(items_total),优先于商品明细数量累加。 + * @param {number} [options.fallbackItemsCount] 订单级商品种类数(items_count),仅当商品总数与明细累加均为 0 时兜底。 + * @param {number} [options.waveSource] 波次来源(wms_wave_batch.source),与 waveType 共同决定商品明细行尾是否追加「波次总单数×数量」。 + * @param {number} [options.waveType] 波次类型(wms_wave_batch.wave_type)。 + * @param {number} [options.boxNo] 小团购篮号(box_no),waveType=1 且 waveSource∈{1,2}(策略任务波次)时前置到波次号前。 + * @param {string} [options.packageMaterialName] 推荐包材名称,非空时追加到波次号前。 + * @return {Array} 自定义区文本行数组。首行头部分在快递渠道名后追加 商品总数【n】(优先取订单级商品总数 items_total,其次商品明细数量累加,最后 items_count 兜底); + * 当 waveSource=0 且 waveType=1 时,商品明细行尾追加「波次总单数×该行商品数量」; + * 小团购(waveType=1 且 waveSource∈{1,2})时波次号前追加篮号「{boxNo}-」。 + */ +function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) { + const safeItems = Array.isArray(items) ? items : []; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const safeOptions = isPlainObject(options) ? options : {}; + const hasDisplayType = Object.prototype.hasOwnProperty.call(safePolicyConfig, WAYBILL_CUSTOM_DISPLAY_FIELD); + const displayType = hasDisplayType + ? String(safePolicyConfig[WAYBILL_CUSTOM_DISPLAY_FIELD] || '').trim() + : WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_NAME_BARCODE_QTY; + + const isHideMode = displayType === WAYBILL_CUSTOM_DISPLAY_TYPES.HIDE; + + // 波次总单数、来源与类型:wave.source=0(普通波次)且 wave_type=1 时, + // 商品明细行尾追加「波次总单数 × 该行商品数量」(如 500 单 × 3 件 = 1500) + const waveTotalOrders = toNumber(safeOptions.wave_total_orders, 0); + const waveSource = toNumber(safeOptions.waveSource, 0); + const waveType = toNumber(safeOptions.waveType, 0); + const shouldAppendWaveMultiply = waveSource === 0 && waveType === 1 && waveTotalOrders > 0; + + const detailLines = []; + + // HIDE 模式下跳过商品明细行构建,但仍保留 headerLine(波次号、快递渠道等)的输出 + if (!isHideMode) { + for (const item of safeItems) { + if (!isPlainObject(item)) { + continue; + } + + const itemName = getFirstNonEmptyText(item, [ 'item_name', 'product_name', 'name', 'title' ]); + const pickLocation = getFirstNonEmptyText(item, [ + 'pick_location', + 'pick_location_code', + 'location_code', + 'space_code', + 'bin_code', + 'storage_code', + ]); + const barcode = resolveItemBarcodeText(item); + const { qtyText, qtyNumber } = resolveItemQuantity(item); + + let line = ''; + switch (displayType) { + case WAYBILL_CUSTOM_DISPLAY_TYPES.ITEM_NAME_QTY: + line = `${itemName} 【${qtyText}】`.trim(); + break; + case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_BARCODE_QTY: + line = `${pickLocation} ${barcode} 【${qtyText}】`.trim(); + break; + case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_BARCODE_LAST5_QTY: { + const barcodeLast5 = barcode ? barcode.slice(-5) : ''; + if (!pickLocation && !barcodeLast5) { + line = ''; + break; + } + line = `${pickLocation} ${barcodeLast5} 【${qtyText}】`.trim(); + break; + } + case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_NAME_BARCODE_QTY: + line = `${pickLocation} ${itemName} ${barcode} 【${qtyText}】`.trim(); + break; + default: + line = ''; + break; + } + + if (line) { + line = line.replace(/\s{2,}/g, ' '); + // wave.source=0 且 wave_type=1:行尾追加 波次总单数 × 该行商品数量(数量与乘数之间以两个空格分隔) + if (shouldAppendWaveMultiply && qtyNumber > 0) { + line += ` ${waveTotalOrders * qtyNumber}`; + } + detailLines.push(line); + } + } + } + + const waveNo = String(safeOptions.waveNo || '').trim(); + const waveIndex = toNumber(safeOptions.wave_index, 0); + const platformsIndex = toNumber(safeOptions.platforms_index, 0); + const expressInterfaceName = String(safeOptions.expressInterfaceName || '').trim(); + void platformsIndex; + const hasWaveCustomPrefix = waveTotalOrders > 0 + && waveIndex > 0 + && Boolean(waveNo); + // 小团购波次(wave_type=1 且 source∈{1,2} 策略任务):篮号前置到波次号前,其他波次类型不动 + const boxNo = toNumber(safeOptions.boxNo, 0); + const isSmallGroupWave = waveType === 1 && (waveSource === 1 || waveSource === 2) && boxNo > 0; + const packageMaterialName = String(safeOptions.packageMaterialName || '').trim(); + const packageMaterialLabel = packageMaterialName ? `【${packageMaterialName}】` : ''; + const waveBodyText = hasWaveCustomPrefix + ? `${waveNo} [${waveTotalOrders}-${waveIndex}]` + : waveNo; + const waveHeaderText = isSmallGroupWave + ? packageMaterialLabel + `${boxNo}-${waveBodyText}` + : packageMaterialLabel + waveBodyText; + + // 商品总数:优先取订单级商品总数(items_total,权威字段), + // 其次累加所有商品明细的数量,最后用商品种类数(items_count)兜底。 + // 订单 items 快照可能是宽松文本(stock_id+数量)甚至陈旧不完整,不能无条件信任明细累加结果 + const computedTotalQty = safeItems.reduce((total, item) => { + if (!isPlainObject(item)) { + return total; + } + const { qtyNumber } = resolveItemQuantity(item); + return total + (Number.isFinite(qtyNumber) && qtyNumber > 0 ? qtyNumber : 0); + }, 0); + const fallbackTotalQty = toNumber(safeOptions.fallbackTotalQty, 0); + const fallbackItemsCount = toNumber(safeOptions.fallbackItemsCount, 0); + const totalQty = fallbackTotalQty > 0 + ? fallbackTotalQty + : (computedTotalQty > 0 ? computedTotalQty : fallbackItemsCount); + const totalQtyLabel = totalQty > 0 ? `商品总数【${totalQty}】` : ''; + + const headerParts = [ waveHeaderText, expressInterfaceName, totalQtyLabel ].filter(Boolean); + const headerLine = headerParts.join(' '); + + if (detailLines.length === 0) { + return [ headerLine ]; + } + + return [ headerLine, ...detailLines ]; +} + +/** + * 向已有的自定义区文本追加额外行。 + * @param {string} customText 已有的自定义区文本。 + * @param {Array} extraLines 额外文本行数组。 + * @param {string} [lineBreak='\n'] 换行符。 + * @return {string} 追加后的文本。 + */ +function appendExtraCustomLines(customText, extraLines, lineBreak = '\n') { + const safeLines = Array.isArray(extraLines) ? extraLines.filter(line => String(line || '').trim() !== '') : []; + if (safeLines.length === 0) { + return customText; + } + const prefix = safeLines.join(lineBreak); + const base = String(customText || '').trim(); + return base ? `${prefix}${lineBreak}${base}` : prefix; +} + +/** + * 将自定义文本行按平台换行符合并为字符串。 + * @param {Array} lines 文本行数组。 + * @param {Object} options 合并选项。 + * @param {string} [options.lineBreak=LINE_BREAK_MAP.LF] 换行符。 + * @param {boolean} [options.trailingLineBreak=false] 是否追加末尾换行。 + * @return {string} 合并后的文本。 + */ +function mergeWaybillCustomLines(lines = [], options = {}) { + const safeLines = Array.isArray(lines) ? lines.filter(line => String(line || '').trim() !== '') : []; + if (safeLines.length === 0) { + return ''; + } + + const safeOptions = isPlainObject(options) ? options : {}; + const lineBreak = safeOptions.lineBreak || LINE_BREAK_MAP.LF; + const trailingLineBreak = Boolean(safeOptions.trailingLineBreak); + let text = normalizeLineBreak(safeLines.join(LINE_BREAK_MAP.LF), lineBreak); + if (trailingLineBreak) { + text += lineBreak; + } + return text; +} + +/** + * 截断视频号(SPH)自定义区文本行。 + * + * 视频号面单自定义区最多打印 8 行,第 9 行起全部舍弃。 + * 统计口径为最终文本的全部分行(含首行头部与子单号行),空白行同样计入行数,不做过滤。 + * + * @param {string} text 自定义区文本(以 `
    ` 分隔行)。 + * @return {string} 截断后的文本。 + */ +function truncateSphCustomInfoLines(text) { + const safeText = String(text === undefined || text === null ? '' : text); + if (!safeText) { + return safeText; + } + + const lines = safeText.split(SPH_CUSTOM_INFO_LINE_BREAK); + if (lines.length <= SPH_CUSTOM_INFO_MAX_LINES) { + return safeText; + } + + return lines.slice(0, SPH_CUSTOM_INFO_MAX_LINES).join(SPH_CUSTOM_INFO_LINE_BREAK); +} + +/** + * 构建数组字段的精简骨架。 + * + * @param {any} value 原始字段值。 + * @param {string[]} warnings 警告列表。 + * @param {string} currentKey 当前字段名。 + * @return {Array<*>} 数组骨架。 + */ +function buildArraySkeleton(value, warnings, currentKey) { + if (Array.isArray(value)) { + if (!value.length) { + return []; + } + + return [ sanitizeTemplatePrivateFields(value[0], warnings, currentKey) ]; + } + + if (value === undefined || value === null) { + return []; + } + + return [ sanitizeTemplatePrivateFields(value, warnings, currentKey) ]; +} + +/** + * 从快手模板样例中提取自定义区默认模板地址。 + * + * 优先扫描 template_sample.task.documents,其次扫描 template_sample.documents 和 template_sample.taskList, + * 找到第一个同时包含 customData 与 templateURL 的内容对象后返回其 templateURL。 + * + * @param {Object} templateSample 模板样例对象。 + * @return {string} 默认模板地址。 + */ +function resolveKuaishouCustomDataTemplateURL(templateSample) { + const sample = isPlainObject(templateSample) ? templateSample : {}; + const documentGroups = [ + sample.task && sample.task.documents, + sample.documents, + sample.taskList, + ]; + + for (const documents of documentGroups) { + if (!Array.isArray(documents) || documents.length === 0) { + continue; + } + + for (const document of documents) { + if (!isPlainObject(document) || !Array.isArray(document.contents)) { + continue; + } + + for (const content of document.contents) { + if (!isPlainObject(content) || !isPlainObject(content.customData)) { + continue; + } + + if (Object.prototype.hasOwnProperty.call(content, 'templateURL')) { + return toTrimmedString(content.templateURL); + } + } + } + } + + return ''; +} + +/** + * 从菜鸟模板样例中提取自定义区模板地址。 + * + * 优先扫描 template_sample.task.documents,其次扫描 template_sample.documents 和 template_sample.taskList, + * 找到第一个 data.CustomControl 字段对应的内容对象后返回其 templateURL。 + * + * @param {Object} templateSample 模板样例对象。 + * @return {string} 自定义区模板地址。 + */ +function resolveCainiaoCustomControlTemplateURL(templateSample) { + const sample = isPlainObject(templateSample) ? templateSample : {}; + const documentGroups = [ + sample.task && sample.task.documents, + sample.documents, + sample.taskList, + ]; + + for (const documents of documentGroups) { + if (!Array.isArray(documents) || documents.length === 0) { + continue; + } + + for (const document of documents) { + if (!isPlainObject(document) || !Array.isArray(document.contents)) { + continue; + } + + for (const content of document.contents) { + if (!isPlainObject(content) || !isPlainObject(content.data)) { + continue; + } + + if (!Object.prototype.hasOwnProperty.call(content.data, 'CustomControl')) { + continue; + } + + if (Object.prototype.hasOwnProperty.call(content, 'templateURL')) { + return toTrimmedString(content.templateURL); + } + } + } + } + + return ''; +} + +/** + * 深拷贝普通对象/数组,避免直接复用上游引用。 + * + * @param {any} value 原始值。 + * @return {any} 拷贝后的值。 + */ +function cloneStructuredValue(value) { + if (Array.isArray(value)) { + return value.map(item => cloneStructuredValue(item)); + } + + if (!isPlainObject(value)) { + return value; + } + + const cloned = {}; + for (const key of Object.keys(value)) { + cloned[key] = cloneStructuredValue(value[key]); + } + + return cloned; +} + +/** + * 将可能为 JSON 字符串的值解析为对象。 + * + * 仅在值为字符串时尝试解析;解析失败时按需记录警告。 + * + * @param {any} value 原始值。 + * @param {string[]} [warnings=[]] 风险提示列表。 + * @param {boolean} [warnOnFailure=false] 解析失败时是否记录警告。 + * @return {Object|null} 解析后的对象;非对象或解析失败返回 null。 + */ +function parseCainiaoPrintinfoObject(value, warnings = [], warnOnFailure = false) { + const safeWarnings = Array.isArray(warnings) ? warnings : []; + let payload = value; + + if (typeof payload === 'string') { + const text = payload.trim(); + if (!text) { + return null; + } + + try { + payload = JSON.parse(text); + } catch (error) { + if (warnOnFailure) { + safeWarnings.push('菜鸟 printinfo JSON 解析失败,已回退模板骨架'); + } + return null; + } + } + + return isPlainObject(payload) ? payload : null; +} + +/** + * 将候选值归一化为菜鸟主面单 content。 + * + * 支持三类输入: + * - 主 content 对象:{ templateURL, data, signature, ... } + * - 纯主 content 对象:{ encryptedData, signature, templateURL, ver, ... } + * - 旧 data 对象:{ cpCode, recipient, waybillCode, ... } + * + * 同时兼容 `data` 为 JSON 字符串的场景,仅解析一层。 + * + * @param {any} candidate 候选值。 + * @return {Object|null} 归一化后的主面单 content;无法识别返回 null。 + */ +function normalizeCainiaoMainContentCandidate(candidate) { + const normalizedCandidate = parseCainiaoPrintinfoObject(candidate); + if (!normalizedCandidate) { + return null; + } + + const normalizeTemplateUrlField = value => { + if (!Object.prototype.hasOwnProperty.call(value, 'templateURL') + && Object.prototype.hasOwnProperty.call(value, 'templateUrl')) { + value.templateURL = toTrimmedString(value.templateUrl); + delete value.templateUrl; + } + + return value; + }; + + const candidateData = parseCainiaoPrintinfoObject(normalizedCandidate.data) || normalizedCandidate.data; + if (isPlainObject(candidateData) && Object.keys(candidateData).length > 0) { + const normalizedContent = cloneStructuredValue(normalizedCandidate); + normalizedContent.data = cloneStructuredValue(candidateData); + + return normalizeTemplateUrlField(normalizedContent); + } + + if (Object.keys(normalizedCandidate).length === 0) { + return null; + } + + const directContentFieldList = [ 'templateURL', 'templateUrl', 'encryptedData', 'signature', 'ver', 'addData' ]; + const hasDirectContent = directContentFieldList.some(field => { + return Object.prototype.hasOwnProperty.call(normalizedCandidate, field); + }); + + if (hasDirectContent) { + return normalizeTemplateUrlField(cloneStructuredValue(normalizedCandidate)); + } + + const directDataFieldList = [ 'cpCode', 'recipient', 'waybillCode' ]; + const hasDirectData = directDataFieldList.some(field => { + return Object.prototype.hasOwnProperty.call(normalizedCandidate, field); + }); + + if (!hasDirectData) { + return null; + } + + const normalizedData = cloneStructuredValue(normalizedCandidate); + const normalizedContent = {}; + + if (Object.prototype.hasOwnProperty.call(normalizedData, 'templateURL')) { + normalizedContent.templateURL = toTrimmedString(normalizedData.templateURL); + delete normalizedData.templateURL; + } + + if (Object.prototype.hasOwnProperty.call(normalizedData, 'templateUrl')) { + normalizedContent.templateURL = toTrimmedString(normalizedData.templateUrl); + delete normalizedData.templateUrl; + } + + normalizedContent.data = normalizedData; + return normalizedContent; +} + +/** + * 收集菜鸟 printinfo 中可能承载主面单的候选值。 + * + * 仅按已知包装路径做有限展开,避免过度泛化: + * - payload 本身 + * - payload.data(若可解析为对象) + * - payload.contents[0] + * - payload.documents[0].contents[0] + * - payload.task.documents[0].contents[0] + * + * @param {Object} payload 顶层 printinfo 对象。 + * @return {Array} 候选值列表。 + */ +function collectCainiaoMainContentCandidates(payload) { + const candidateList = []; + const pushCandidate = value => { + if (value === undefined || value === null) { + return; + } + + candidateList.push(value); + }; + + const rootDataPayload = parseCainiaoPrintinfoObject(payload.data); + const rootPayloadList = [ payload ]; + if (rootDataPayload) { + rootPayloadList.push(rootDataPayload); + } + + for (const currentPayload of rootPayloadList) { + if (!isPlainObject(currentPayload)) { + continue; + } + + pushCandidate(currentPayload); + + if (Array.isArray(currentPayload.contents)) { + pushCandidate(currentPayload.contents[0]); + } + + if (Array.isArray(currentPayload.documents) && isPlainObject(currentPayload.documents[0])) { + pushCandidate(currentPayload.documents[0].contents && currentPayload.documents[0].contents[0]); + } + + if (isPlainObject(currentPayload.task) + && Array.isArray(currentPayload.task.documents) + && isPlainObject(currentPayload.task.documents[0])) { + pushCandidate(currentPayload.task.documents[0].contents && currentPayload.task.documents[0].contents[0]); + } + } + + return candidateList; +} + +/** + * 用平铺密文字段回拼菜鸟加密面单主 content。 + * + * 部分来源(如 OMS 取号)把菜鸟面单拆成 `encryptprintinfo` / `signature` / `ver` 平铺返回, + * `printinfo` 为空或只放了裸密文;此处回拼成与 printinfo 整包同构的 + * `{ encryptedData, signature, ver }`,避免打印退化成模板兜底。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {Object|null} 加密面单主 content;缺少密文时返回 null。 + */ +function buildCainiaoEncryptContentFromOrderExpress(orderExpress = {}) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const encryptedData = toTrimmedString(safeOrderExpress.encryptprintinfo); + if (!encryptedData) { + return null; + } + + const content = { encryptedData }; + const signature = toTrimmedString(safeOrderExpress.signature); + if (signature) { + content.signature = signature; + } + const version = toTrimmedString(safeOrderExpress.ver); + if (version) { + content.ver = version; + } + + return content; +} + +/** + * 解析菜鸟 printinfo 并归一化主面单 content。 + * + * 兼容以下形态: + * - 形态 A:主 content 对象:{ templateURL, data, signature, ... } + * - 形态 B:纯主 content 对象:{ encryptedData, signature, templateURL, ver, ... } + * - 形态 C:旧 data 对象:{ cpCode, recipient, waybillCode, ... } + * - 形态 D:包装对象:{ contents: [ { templateURL, data, ... } ] } + * - 形态 E:包装对象:{ documents: [ { contents: [ ... ] } ] } + * - 形态 F:包装对象:{ task: { documents: [ { contents: [ ... ] } ] } } + * - 形态 G:`data` 为 JSON 字符串时解析一层 + * + * @param {any} printinfo 原始 printinfo。 + * @param {string[]} warnings 风险提示列表。 + * @param {boolean} [warnOnFailure=true] printinfo 解析失败时是否记录告警(调用方另有兜底时可关闭)。 + * @return {Object|null} 解析后的主面单 content;失败返回 null。 + */ +function resolveCainiaoMainContentFromPrintinfo(printinfo, warnings = [], warnOnFailure = true) { + const payload = parseCainiaoPrintinfoObject(printinfo, warnings, warnOnFailure); + if (!payload) { + return null; + } + + const candidateList = collectCainiaoMainContentCandidates(payload); + for (const candidate of candidateList) { + const resolvedContent = normalizeCainiaoMainContentCandidate(candidate); + if (resolvedContent) { + return resolvedContent; + } + } + + return null; +} + +/** + * 清洗菜鸟主面单 data 中的模板占位符,避免将 `__SAMPLE__` 原样下发。 + * + * @param {any} value 原始主面单 data。 + * @return {any} 清洗后的主面单 data。 + */ +function sanitizeCainiaoMainDataPlaceholders(value) { + if (Array.isArray(value)) { + return value.map(item => sanitizeCainiaoMainDataPlaceholders(item)); + } + + if (isPlainObject(value)) { + const result = {}; + for (const key of Object.keys(value)) { + result[key] = sanitizeCainiaoMainDataPlaceholders(value[key]); + } + return result; + } + + if (typeof value === 'string') { + const text = toTrimmedString(value); + return text === '__SAMPLE__' ? '' : text; + } + + return value; +} + +/** + * 解析菜鸟主面单使用的快递公司编码。 + * + * 优先使用上游补齐的菜鸟编码;缺失时再回退到原有物流编码来源,保持兼容。 + * + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @return {string} 菜鸟快递公司编码。 + */ +function resolveCainiaoCpCode(orderExpress, orderDelivery) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + + return toTrimmedString( + safeOrderExpress.cainiao_cp_code + || safeOrderExpress.logistics_code + || safeOrderDelivery.logistics_code + || safeOrderDelivery.sys_logistics_code + ); +} + +/** + * 解析菜鸟主面单模板地址。 + * + * 仅主面单使用该来源,自定义区模板地址仍沿用原有样例解析逻辑。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {string} 主面单模板地址。 + */ +function resolveCainiaoMainTemplateURL(orderExpress) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + return toTrimmedString(safeOrderExpress.cainiao_template_url); +} + +/** + * 解析拼多多主面单模板地址。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {string} 拼多多主面单模板地址。 + */ +function resolvePddMainTemplateURL(orderExpress) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + return toTrimmedString(safeOrderExpress.pdd_template_url); +} + +/** + * 解析抖音主面单模板地址。 + * + * 兼容 dy 与 douyin 两种字段命名,优先读取 dy_template_url。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {string} 抖音主面单模板地址。 + */ +function resolveDouyinMainTemplateURL(orderExpress) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + return toTrimmedString(safeOrderExpress.dy_template_url || safeOrderExpress.douyin_template_url); +} + +/** + * 当菜鸟 printinfo 缺失或无效时,仅基于模板骨架构建最小主面单 data。 + * + * 不再使用订单、策略等业务字段回填 sender/recipient/packageInfo 等主面单信息。 + * + * @param {Object} templateMainData 模板主面单 data。 + * @return {Object} 清洗占位符后的最小主面单 data。 + */ +function buildCainiaoFallbackMainData(templateMainData) { + return isPlainObject(templateMainData) + ? sanitizeCainiaoMainDataPlaceholders(templateMainData) + : {}; +} + +/** + * 固定菜鸟主面单 data 来源标记。 + * + * @param {Object} mainData 菜鸟主面单 data。 + * @param {string} source 数据来源标记。 + * @return {Object} 已补齐 `_dataFrom` 的主面单 data。 + */ +function ensureCainiaoMainDataSource(mainData, source) { + const normalizedMainData = isPlainObject(mainData) ? mainData : {}; + normalizedMainData._dataFrom = toTrimmedString(source) || 'printinfo'; + return normalizedMainData; +} + +/** + * 归一化签约策略配置。 + * @param {Object} input 入参对象。 + * @return {Object} 统一 policy_config 对象。 + */ +function resolvePolicyConfig(input) { + if (isPlainObject(input.policy_config)) { + return input.policy_config; + } + + if (isPlainObject(input.store_contract) && isPlainObject(input.store_contract.policy_config)) { + return input.store_contract.policy_config; + } + + return {}; +} + +/** + * 归一化仓库主体配置(subject_config),用于发件人兜底。 + * @param {Object} input 入参对象。 + * @return {Object} 统一 subject_config 对象。 + */ +function resolveSubjectConfig(input) { + if (isPlainObject(input.subject_config)) { + return input.subject_config; + } + return {}; +} + +/** + * 发件人相关字段集合,用于签约策略 → 仓库主体的按字段兜底。 + */ +const SENDER_FALLBACK_FIELDS = Object.freeze([ + 'sender_name', + 'sender_tel', + 'province_name', + 'city_name', + 'district_name', + 'town_name', + 'address', +]); + +/** + * 解析发件人兜底配置:签约策略 policy_config 非空值优先,空值回退仓库主体 subject_config。 + * + * 注意:getContractConfig 会把策略默认值合并进 policy_config(发件人字段默认为空字符串), + * 因此不能用对象浅合并(空串会覆盖 subject_config 的有效值),必须按字段回退。 + * + * @param {Object} policyConfig 签约策略配置。 + * @param {Object} subjectConfig 仓库主体配置。 + * @return {Object} 兜底后的策略配置对象。 + */ +function resolveSenderFallbackConfig(policyConfig, subjectConfig) { + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const safeSubjectConfig = isPlainObject(subjectConfig) ? subjectConfig : {}; + const merged = { ...safePolicyConfig }; + + for (const key of SENDER_FALLBACK_FIELDS) { + if (!toTrimmedString(merged[key])) { + const fallbackValue = toTrimmedString(safeSubjectConfig[key]); + if (fallbackValue) { + merged[key] = fallbackValue; + } + } + } + + return merged; +} + +/** + * 构建基础数据中间态。 + * @param {Object} input 输入对象。 + * @param {string} platform 归一化平台。 + * @param {Object|null} platformMeta 平台元信息。 + * @return {{base_data: Object, missing_fields: Array, warnings: string[]}} 组装结果。 + */ +function buildBaseData(input, platform, platformMeta) { + const orderExpress = isPlainObject(input.order_express) ? input.order_express : {}; + const orderDelivery = isPlainObject(input.order_delivery) ? input.order_delivery : {}; + const policyConfig = resolvePolicyConfig(input); + const subjectConfig = resolveSubjectConfig(input); + const templateSample = isPlainObject(input.template_sample) ? input.template_sample : {}; + + // 三级兜底:货主 policy_config → 仓库 subject_config → 缺失标记 + const missingSenderFields = []; + const senderField = key => { + const val = toTrimmedString(policyConfig[key]) || toTrimmedString(subjectConfig[key]); + if (!val) { + missingSenderFields.push(key); + } + return val || '仓库未配置发件人'; + }; + + const sender = { + name: senderField('sender_name'), + tel: senderField('sender_tel'), + province: senderField('province_name'), + city: senderField('city_name'), + district: senderField('district_name'), + town: senderField('town_name'), + address: senderField('address'), + }; + + const receiver = { + name: toTrimmedString(orderDelivery.name), + mobile: toTrimmedString(orderDelivery.mobile), + tel: toTrimmedString(orderDelivery.tel), + province: toTrimmedString(orderDelivery.province), + city: toTrimmedString(orderDelivery.city), + district: toTrimmedString(orderDelivery.area), + town: toTrimmedString(orderDelivery.town), + address: toTrimmedString(orderDelivery.detail_address), + zip_code: toTrimmedString(orderDelivery.zip_code), + }; + + const items = parseItems(orderDelivery.items); + const channel = { + platform, + source_platform_code: toTrimmedString(orderDelivery.source_platform_code || orderExpress.platform_code), + sys_platform_code: toTrimmedString(orderDelivery.sys_platform_code), + logistics_code: toTrimmedString(orderExpress.logistics_code || orderDelivery.logistics_code), + logistics_name: toTrimmedString(orderExpress.logistics_name || orderDelivery.logistics_name), + waybill_code: toTrimmedString(orderExpress.waybill_code), + business_key: toNumber(orderExpress.business_key, 0), + }; + + const template = { + file: platformMeta ? platformMeta.template_file : '', + cmd: toTrimmedString(templateSample.cmd), + version: toTrimmedString(templateSample.version), + request_id: toTrimmedString(templateSample.requetID || templateSample.requestID), + }; + + const missingFields = []; + const warnings = []; + + // 将三级兜底中仍然缺失的字段挂载到 sender 上供下游感知 + sender._missing = [ ...missingSenderFields ]; + + const requiredChecks = [ + { path: 'sender.name', value: sender.name === '仓库未配置发件人' ? '' : sender.name, reason: '缺少发件人姓名(policy_config.sender_name / subject_config.sender_name)' }, + { path: 'sender.tel', value: sender.tel === '仓库未配置发件人' ? '' : sender.tel, reason: '缺少发件人电话(policy_config.sender_tel / subject_config.sender_tel)' }, + { path: 'sender.address', value: sender.address === '仓库未配置发件人' ? '' : sender.address, reason: '缺少发件详细地址(policy_config.address / subject_config.address)' }, + { path: 'receiver.name', value: receiver.name, reason: '缺少收件人姓名(order_delivery.name)' }, + { path: 'receiver.mobile|tel', value: receiver.mobile || receiver.tel, reason: '缺少收件联系方式(order_delivery.mobile/tel)' }, + { path: 'receiver.address', value: receiver.address, reason: '缺少收件详细地址(order_delivery.detail_address)' }, + { path: 'channel.waybill_code', value: channel.waybill_code, reason: '缺少运单号(order_express.waybill_code)' }, + ]; + + for (const check of requiredChecks) { + if (!check.value) { + missingFields.push({ path: check.path, reason: check.reason }); + } + } + + if (!items.length) { + warnings.push('order_delivery.items 为空或解析失败,已输出空商品列表'); + } + + if (!platformMeta) { + warnings.push(`平台 ${platform || '(empty)'} 未命中硬编码映射,已按原值输出`); + } + + return { + base_data: { + sender, + receiver, + items, + channel, + template, + }, + missing_fields: missingFields, + warnings, + }; +} + +/** + * 清洗模板样例,保留结构并裁切样例噪声。 + * @param {any} value 原始对象。 + * @param {string[]} warnings 警告列表。 + * @param {string} [currentKey=''] 当前字段名。 + * @return {any} 清洗后的对象。 + */ +function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') { + if (Array.isArray(value)) { + if (ARRAY_STYLE_KEYS.has(currentKey)) { + return buildArraySkeleton(value, warnings, currentKey); + } + + return value.map(item => sanitizeTemplatePrivateFields(item, warnings, currentKey)); + } + + if (!isPlainObject(value)) { + if (ARRAY_STYLE_KEYS.has(currentKey)) { + return buildArraySkeleton(value, warnings, currentKey); + } + + if (TEMPLATE_LEAF_KEEP_KEYS.has(currentKey)) { + if (typeof value === 'string') { + return toTrimmedString(value); + } + + return value; + } + + if (typeof value === 'string') { + const text = toTrimmedString(value); + return text ? '__SAMPLE__' : ''; + } + + if (typeof value === 'number') { + return Number.isFinite(value) ? 0 : value; + } + + if (typeof value === 'boolean') { + return value; + } + + return value; + } + + const result = {}; + for (const key of Object.keys(value)) { + const current = value[key]; + if (PRIVATE_PAYLOAD_FIELDS.includes(key)) { + result[key] = '__UPSTREAM_REQUIRED__'; + warnings.push(`模板字段 ${key} 为平台私有密文字段,已替换为占位符`); + continue; + } + + result[key] = sanitizeTemplatePrivateFields(current, warnings, key); + } + + return result; +} + +/** + * 快手平台密文字段回填。 + * + * 规则: + * - wms_order_express.printinfo -> encryptedData + * - wms_order_express.signature -> signature + * - wms_order_express.encryptprintinfo -> key + * + * 仅在平台为 kuaishou 时生效,避免影响其他平台。 + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {string[]} warnings 风险提示列表。 + * @param {Object} policyConfig 策略配置对象。 + * @param {string} customDataTemplateURL 自定义区模板地址默认值。 + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 + */ +function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL, extraCustomLines = []) { + if (platform !== 'kuaishou') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents) + ? safeSkeleton.task.documents + : []; + + if (documents.length === 0) { + return; + } + + const encryptedData = toTrimmedString(safeOrderExpress.printinfo); + const signature = toTrimmedString(safeOrderExpress.signature); + const key = toTrimmedString(safeOrderExpress.encryptprintinfo); + const version = toTrimmedString(safeOrderExpress.ver); + const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), + boxNo: Number(safeOrderDelivery.box_no || 0), + } + ); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }), + extraCustomLines, + LINE_BREAK_MAP.LF + ); + + for (const document of documents) { + if (!isPlainObject(document)) { + continue; + } + + if (waybillCode) { + document.documentID = waybillCode; + document.waybillCode = waybillCode; + } + + if (!Array.isArray(document.contents)) { + document.contents = []; + } + const contents = document.contents; + + for (const content of contents) { + if (!isPlainObject(content)) { + continue; + } + + // 快手发件信息回填,确保对象结构存在后再覆盖策略字段。 + content.addData = isPlainObject(content.addData) ? content.addData : {}; + content.addData.senderInfo = isPlainObject(content.addData.senderInfo) ? content.addData.senderInfo : {}; + content.addData.senderInfo.address = isPlainObject(content.addData.senderInfo.address) + ? content.addData.senderInfo.address + : {}; + content.addData.senderInfo.contact = isPlainObject(content.addData.senderInfo.contact) + ? content.addData.senderInfo.contact + : {}; + + content.addData.senderInfo.address.provinceName = toTrimmedString(safePolicyConfig.province_name); + content.addData.senderInfo.address.cityName = toTrimmedString(safePolicyConfig.city_name); + content.addData.senderInfo.address.districtName = toTrimmedString(safePolicyConfig.district_name); + content.addData.senderInfo.address.detailAddress = toTrimmedString(safePolicyConfig.address); + content.addData.senderInfo.address.countryCode = 'CHN'; + content.addData.senderInfo.contact.name = toTrimmedString(safePolicyConfig.sender_name); + content.addData.senderInfo.contact.mobile = toTrimmedString(safePolicyConfig.sender_tel); + + const hasKuaishouEncryptedPayloadField = ( + Object.prototype.hasOwnProperty.call(content, 'encryptedData') + || Object.prototype.hasOwnProperty.call(content, 'signature') + || Object.prototype.hasOwnProperty.call(content, 'key') + ); + if (!hasKuaishouEncryptedPayloadField) { + continue; + } + + content.encryptedData = encryptedData || '__UPSTREAM_REQUIRED__'; + content.signature = signature || '__UPSTREAM_REQUIRED__'; + content.key = key || '__UPSTREAM_REQUIRED__'; + if (version) { + content.ver = version; + } + } + + const customDataContent = contents.find(content => { + return isPlainObject(content) && isPlainObject(content.customData); + }); + if (customDataContent) { + if (!Object.prototype.hasOwnProperty.call(customDataContent, 'templateURL')) { + customDataContent.templateURL = customDataTemplateURL || ''; + } + customDataContent.customData.productInfo = customProductInfo; + } else { + contents.push({ + templateURL: customDataTemplateURL || '', + customData: { + productInfo: customProductInfo, + }, + }); + } + } + + if (!encryptedData) { + warnings.push('快手模板字段 encryptedData 缺失映射源(order_express.printinfo)'); + } + if (!signature) { + warnings.push('快手模板字段 signature 缺失映射源(order_express.signature)'); + } + if (!key) { + warnings.push('快手模板字段 key 缺失映射源(order_express.encryptprintinfo)'); + } else if (key.length > KUAISHOU_ENCRYPT_KEY_MAX_LENGTH || key === encryptedData) { + // 快手密钥为逐单短串(实测 172 字符),密文是数 KB 的十六进制串; + // 命中说明上游把密文写进了 encryptprintinfo、且没有返回真正的 key + warnings.push('快手模板字段 key 疑似为密文而非密钥(上游未返回 key),打印可能失败'); + } +} + +/** + * 拼多多平台密文字段回填。 + * + * 规则: + * - wms_order_express.encryptprintinfo -> encryptedData + * - wms_order_express.signature -> signature + * - policy_config 面单发货信息 -> content.addData.sender + * + * 仅在平台为 pdd 时生效,避免影响其他平台。 + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 + */ +function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) { + if (platform !== 'pdd') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents) + ? safeSkeleton.task.documents + : []; + + if (documents.length === 0) { + return; + } + + const encryptedData = toTrimmedString(safeOrderExpress.encryptprintinfo); + const signature = toTrimmedString(safeOrderExpress.signature); + const version = toTrimmedString(safeOrderExpress.ver); + const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); + const pddMainTemplateURL = resolvePddMainTemplateURL(safeOrderExpress); + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), + boxNo: Number(safeOrderDelivery.box_no || 0), + } + ); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.CR, + trailingLineBreak: true, + }), + extraCustomLines, + LINE_BREAK_MAP.CR + ); + + /** + * 判断内容对象是否属于拼多多自定义区。 + * + * @param {Object} content 内容对象。 + * @return {boolean} 是否为自定义区内容对象。 + */ + function isPddCustomContent(content) { + if (!isPlainObject(content)) { + return false; + } + + return Boolean( + isPlainObject(content.customData) + || (isPlainObject(content.data) && Array.isArray(content.data.list)) + ); + } + + /** + * 构建拼多多默认自定义区内容对象。 + * + * @param {string} templateURL 自定义模板地址。 + * @return {Object} 默认自定义区内容对象。 + */ + function buildPddDefaultCustomContent(templateURL) { + return { + templateURL: toTrimmedString(templateURL || DEFAULT_PDD_CUSTOM_TEMPLATE_URL), + data: { + height: 240, + list: [{ + fontSize: 28, + left: 2.08, + text: customProductInfo, + top: 2.08, + width: 550, + }], + waterdata: { + text: '', + }, + width: 560, + }, + }; + } + + for (const document of documents) { + if (!isPlainObject(document)) { + continue; + } + + document.documentID = waybillCode; + + if (!Array.isArray(document.contents)) { + document.contents = []; + } + + if (!isPlainObject(document.contents[0])) { + document.contents[0] = {}; + } + if (pddMainTemplateURL) { + document.contents[0].templateURL = pddMainTemplateURL; + } + + for (const content of document.contents) { + if (!isPlainObject(content)) { + continue; + } + + content.addData = isPlainObject(content.addData) ? content.addData : {}; + content.addData.sender = isPlainObject(content.addData.sender) ? content.addData.sender : {}; + content.addData.sender.address = isPlainObject(content.addData.sender.address) + ? content.addData.sender.address + : {}; + + content.addData.sender.address.province = toTrimmedString(safePolicyConfig.province_name); + content.addData.sender.address.city = toTrimmedString(safePolicyConfig.city_name); + content.addData.sender.address.district = toTrimmedString(safePolicyConfig.district_name); + content.addData.sender.address.detail = toTrimmedString(safePolicyConfig.address); + content.addData.sender.mobile = toTrimmedString(safePolicyConfig.sender_tel); + content.addData.sender.name = toTrimmedString(safePolicyConfig.sender_name); + content.encryptedData = encryptedData; + content.signature = signature; + if (version) { + content.ver = version; + } + } + + const customContent = document.contents.find(isPddCustomContent); + if (customContent) { + if (!toTrimmedString(customContent.templateURL)) { + customContent.templateURL = DEFAULT_PDD_CUSTOM_TEMPLATE_URL; + } + + if (isPlainObject(customContent.data) && Array.isArray(customContent.data.list) && customContent.data.list[0]) { + customContent.data.list[0].text = customProductInfo; + } + } else { + document.contents.push(buildPddDefaultCustomContent()); + } + } +} + +/** + * 获取抖音 params(从预取的 dy_params 字段读取)。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {string} params 字符串。 + */ +// eslint-disable-next-line no-unused-vars +function resolveDouyinParams(orderExpress) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + return toTrimmedString(safeOrderExpress.dy_params) || ''; +} + +/** + * 抖音平台主面单模板地址、密文、发件人地址与自定义区字段回填。 + * + * 规则: + * - wms_order_express.signature -> signature(签名) + * - wms_order_express.encryptprintinfo -> encryptedData(加密面单数据) + * - params 不赋值,保留模板占位符(由上游平台适配器另算) + * - wms_order_express.dy_template_url / douyin_template_url -> templateURL + * - 发件人地址优先从 policyConfig 读取(province_name / city_name / district_name / sender_address), + * 其次从 orderDelivery 读取;countryCode 固定为 CHN + * - 自定义区(contents[1])根据拣货信息填充 productInfo + * + * 仅在平台为 douyin 时生效。 + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + * @param {string[]} extraCustomLines 额外的自定义文本行。 + * @param {string} customAreaBaseUrl 自定义区模板出口域名。 + */ +function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = [], customAreaBaseUrl = '') { + if (platform !== 'douyin') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const douyinMainTemplateURL = resolveDouyinMainTemplateURL(safeOrderExpress); + + const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents) + ? safeSkeleton.task.documents + : []; + if (documents.length === 0) { + return; + } + + // 密文回填 + const encryptPrintinfo = toTrimmedString(safeOrderExpress.encryptprintinfo); + const signature = toTrimmedString(safeOrderExpress.signature); + + // 发件人信息 — 优先从 policyConfig 读取,其次从 orderDelivery + const senderName = toTrimmedString(safePolicyConfig.sender_name); + const senderTel = toTrimmedString(safePolicyConfig.sender_tel); + const senderProvince = toTrimmedString(safePolicyConfig.province_name || safeOrderDelivery.province_name); + const senderCity = toTrimmedString(safePolicyConfig.city_name || safeOrderDelivery.city_name); + const senderDistrict = toTrimmedString(safePolicyConfig.district_name || safeOrderDelivery.district_name); + const senderAddress = toTrimmedString(safePolicyConfig.sender_address || safePolicyConfig.address); + + // 自定义区拣货信息 + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), + boxNo: Number(safeOrderDelivery.box_no || 0), + } + ); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { lineBreak: '\n' }), + extraCustomLines, + '\n' + ); + + for (const document of documents) { + if (!isPlainObject(document)) { + continue; + } + + if (!Array.isArray(document.contents)) { + document.contents = []; + } + + const contents = document.contents; + + // 主面单(contents[0])回填 + const mainContent = contents[0]; + if (isPlainObject(mainContent)) { + if (douyinMainTemplateURL) { + mainContent.templateURL = douyinMainTemplateURL; + } + if (encryptPrintinfo) { + mainContent.encryptedData = encryptPrintinfo; + } + if (signature) { + mainContent.signature = signature; + } + + // senderInfo + mainContent.addData = isPlainObject(mainContent.addData) ? mainContent.addData : {}; + mainContent.addData.senderInfo = isPlainObject(mainContent.addData.senderInfo) + ? mainContent.addData.senderInfo : {}; + if (senderName) { + mainContent.addData.senderInfo.contact = isPlainObject(mainContent.addData.senderInfo.contact) + ? mainContent.addData.senderInfo.contact : {}; + mainContent.addData.senderInfo.contact.name = senderName; + } + if (senderTel) { + mainContent.addData.senderInfo.contact = isPlainObject(mainContent.addData.senderInfo.contact) + ? mainContent.addData.senderInfo.contact : {}; + mainContent.addData.senderInfo.contact.mobile = senderTel; + } + mainContent.addData.senderInfo.address = isPlainObject(mainContent.addData.senderInfo.address) + ? mainContent.addData.senderInfo.address : {}; + if (senderProvince) mainContent.addData.senderInfo.address.provinceName = senderProvince; + if (senderCity) mainContent.addData.senderInfo.address.cityName = senderCity; + if (senderDistrict) mainContent.addData.senderInfo.address.districtName = senderDistrict; + if (senderAddress) mainContent.addData.senderInfo.address.detailAddress = senderAddress; + mainContent.addData.senderInfo.address.countryCode = 'CHN'; + + // params 占位实现 — 调试:无条件覆盖 + mainContent.params = resolveDouyinParams(safeOrderExpress); + } + + // 自定义区 — 模板构建时 contents 被 buildArraySkeleton 截断为 1 个元素,需手动重建 + if (contents.length < 2) { + contents.push({}); + } + const customContent = contents[1]; + if (!toTrimmedString(customContent.templateURL)) { + const baseUrl = toTrimmedString(customAreaBaseUrl) || 'http://qimen.wms.gztbyc.com'; + customContent.templateURL = baseUrl + '/mb/douyin.xml'; + } + customContent.data = isPlainObject(customContent.data) ? customContent.data : {}; + customContent.data.productInfo = customProductInfo || '无拣货信息'; + } +} + +/** + * 菜鸟平台主面单与自定义区字段回填。 + * + * 规则: + * - wms_order_express.printinfo(字符串/对象)解析后直接回填主 contents[0] + * - documentID 使用 wms_order_express.waybill_code + * - 若模板样例存在 data.CustomControl 对应模板地址,则补充菜鸟自定义区内容 + * + * 仅在平台为 cainiao 时生效;主面单优先直接使用 printinfo 解析结果,解析失败时仅回退模板骨架。 + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + * @param {string} customControlTemplateURL 菜鸟自定义区模板地址。 + * @param {string[]} warnings 风险提示列表。 + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 + */ +function applyCainiaoExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig, + customControlTemplateURL, + warnings, + extraCustomLines = [] +) { + if (platform !== 'cainiao') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents) + ? safeSkeleton.task.documents + : []; + + if (documents.length === 0) { + return; + } + + // printinfo 缺失或不是可识别的 JSON 时(OMS 取号只给平铺密文),用密文字段回拼加密面单 content + const cainiaoEncryptContent = buildCainiaoEncryptContentFromOrderExpress(safeOrderExpress); + // 有密文可回拼时不再报「回退模板骨架」,避免误导 + const cainiaoMainContent = resolveCainiaoMainContentFromPrintinfo( + safeOrderExpress.printinfo, + warnings, + !cainiaoEncryptContent + ); + const hasPrintinfoMainContent = isPlainObject(cainiaoMainContent); + + if (cainiaoEncryptContent && !hasPrintinfoMainContent) { + warnings.push('菜鸟 printinfo 缺失或非 JSON,已用 encryptprintinfo + signature + ver 回拼加密面单 content'); + } else if (!cainiaoEncryptContent && !hasPrintinfoMainContent) { + warnings.push('菜鸟 printinfo 为空且缺少 encryptprintinfo,已回退模板骨架'); + } + + const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); + const cainiaoCpCode = resolveCainiaoCpCode(safeOrderExpress, safeOrderDelivery); + const cainiaoMainTemplateURL = resolveCainiaoMainTemplateURL(safeOrderExpress); + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), + boxNo: Number(safeOrderDelivery.box_no || 0), + } + ); + const customControlText = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.CR, + }), + extraCustomLines, + LINE_BREAK_MAP.CR + ); + + for (const document of documents) { + if (!isPlainObject(document)) { + continue; + } + + if (waybillCode) { + document.documentID = waybillCode; + } + + if (!Array.isArray(document.contents)) { + document.contents = []; + } + + const contents = document.contents; + let mainContent = contents[0]; + if (!isPlainObject(mainContent)) { + mainContent = {}; + if (contents.length === 0) { + contents.push(mainContent); + } else { + contents[0] = mainContent; + } + } + + // 模板样例里的主面单模板地址:content 被整体替换(加密面单/模板兜底)后仍要保留兜底来源 + const skeletonMainTemplateURL = toTrimmedString(mainContent.templateURL || mainContent.templateUrl); + + if (hasPrintinfoMainContent) { + mainContent = cloneStructuredValue(cainiaoMainContent); + contents[0] = mainContent; + } else if (cainiaoEncryptContent) { + mainContent = cloneStructuredValue(cainiaoEncryptContent); + contents[0] = mainContent; + } else { + mainContent = cloneStructuredValue(mainContent); + contents[0] = mainContent; + } + + if (hasPrintinfoMainContent) { + if (isPlainObject(mainContent.data)) { + mainContent.data = ensureCainiaoMainDataSource(mainContent.data, 'printinfo'); + } + } else if (!cainiaoEncryptContent) { + mainContent.data = ensureCainiaoMainDataSource( + buildCainiaoFallbackMainData(mainContent.data), + 'template' + ); + } + + if (cainiaoCpCode && isPlainObject(mainContent.data)) { + mainContent.data.cpCode = cainiaoCpCode; + mainContent.data.realCpCode = cainiaoCpCode; + } + + if (cainiaoMainTemplateURL) { + mainContent.templateURL = cainiaoMainTemplateURL; + } else if (!toTrimmedString(mainContent.templateURL) && skeletonMainTemplateURL) { + // 接口未配置模板地址时退回模板样例地址,避免 content 无 templateURL 导致渲染失败 + mainContent.templateURL = skeletonMainTemplateURL; + } else if (!toTrimmedString(mainContent.templateURL)) { + warnings.push('菜鸟主面单缺少 templateURL(接口未配置 template_url 且模板样例为空)'); + } + + if (!toTrimmedString(customControlTemplateURL) || !customControlText) { + continue; + } + + const customControlContent = contents.find(content => { + return isPlainObject(content) + && isPlainObject(content.data) + && Object.prototype.hasOwnProperty.call(content.data, 'CustomControl'); + }); + + if (customControlContent) { + customControlContent.templateURL = toTrimmedString(customControlTemplateURL); + customControlContent.data.CustomControl = customControlText; + } else { + contents.push({ + templateURL: toTrimmedString(customControlTemplateURL), + data: { + CustomControl: customControlText, + }, + }); + } + } +} + +/** + * 解析小红书主面单 content。 + * + * 支持 printinfo 为 JSON 字符串或对象,并兼容以下包装结构: + * - contents[0] + * - documents[0].contents[0] + * - task.documents[0].contents[0] + * + * 若不命中包装结构,则回退为 printinfo 顶层对象本身。 + * + * @param {any} printinfo 原始 printinfo。 + * @param {string[]} [warnings=[]] 风险提示列表。 + * @return {Object|null} 主面单 content;无法解析返回 null。 + */ +function resolveXhsMainContentFromPrintinfo(printinfo, warnings = []) { + const safeWarnings = Array.isArray(warnings) ? warnings : []; + let payload = printinfo; + + if (typeof payload === 'string') { + const text = payload.trim(); + if (!text) { + return null; + } + + try { + payload = JSON.parse(text); + } catch (error) { + safeWarnings.push('小红书 printinfo JSON 解析失败,已回退模板骨架'); + return null; + } + } + + if (!isPlainObject(payload)) { + return null; + } + + if (!payload) { + return null; + } + + const wrapperCandidates = [ + payload.contents && payload.contents[0], + payload.documents && payload.documents[0] && payload.documents[0].contents && payload.documents[0].contents[0], + payload.task + && payload.task.documents + && payload.task.documents[0] + && payload.task.documents[0].contents + && payload.task.documents[0].contents[0], + ]; + + for (const candidate of wrapperCandidates) { + if (isPlainObject(candidate)) { + return cloneStructuredValue(candidate); + } + } + + return cloneStructuredValue(payload); +} + +/** + * 小红书平台主面单与自定义区字段回填。 + * + * 规则: + * - 主面单 contents[0] 直接使用 wms_order_express.printinfo(支持字符串/对象及包装结构) + * - 自定义区按模板结构处理,仅填充 contents[1].data.order[0] + * + * 仅在平台为 xhs 时生效。 + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + * @param {string[]} warnings 风险提示列表。 + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 + */ +function applyXhsExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig, + warnings, + extraCustomLines = [] +) { + if (platform !== 'xhs') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const safeWarnings = Array.isArray(warnings) ? warnings : []; + const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents) + ? safeSkeleton.task.documents + : []; + + if (documents.length === 0) { + return; + } + + const xhsMainContent = resolveXhsMainContentFromPrintinfo(safeOrderExpress.printinfo, safeWarnings); + const hasXhsMainContent = isPlainObject(xhsMainContent); + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), + boxNo: Number(safeOrderDelivery.box_no || 0), + } + ); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }), + extraCustomLines, + LINE_BREAK_MAP.LF + ); + + for (const document of documents) { + if (!isPlainObject(document)) { + continue; + } + + if (!Array.isArray(document.contents)) { + document.contents = []; + } + + const contents = document.contents; + + if (hasXhsMainContent) { + contents[0] = cloneStructuredValue(xhsMainContent); + } + + if (!isPlainObject(contents[1])) { + contents[1] = {}; + } + + const customContent = contents[1]; + if (!toTrimmedString(customContent.templateURL)) { + customContent.templateURL = DEFAULT_XHS_CUSTOM_TEMPLATE_URL; + } + customContent.data = isPlainObject(customContent.data) ? customContent.data : {}; + customContent.data.order = Array.isArray(customContent.data.order) ? customContent.data.order : []; + customContent.data.order[0] = customProductInfo; + } +} + +/** + * 视频号平台 taskList 字段回填。 + * + * 规则: + * - 仅在平台为 sph 时生效 + * - 基于 skeleton.taskList[0] 回填,不改模板默认的结构控制字段 + * - taskList[0].printInfo 使用 order_express.printinfo(非空时) + * - taskList[0].printNum.sumNum 使用 wave_total_orders,curNum 保持模板值,缺失时默认 1 + * - taskList[0].customInfo.data.description 使用现有商品汇总文本并按
    拼接 + * - taskList[0].customInfo.data.description 最多保留 8 行(含首行头部与子单号行),第 9 行起全部舍弃 + * - taskList[0].extendData.sender 使用 policy_config 发件人信息 + * - taskList[0].taskID 优先沿用 buildPlatformRequestSkeleton 现有 taskId + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 + */ +function applySphExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig, + extraCustomLines = [] +) { + if (platform !== 'sph') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const taskList = Array.isArray(safeSkeleton.taskList) ? safeSkeleton.taskList : []; + if (!isPlainObject(taskList[0])) { + return; + } + + const task = taskList[0]; + const printinfo = toTrimmedString(safeOrderExpress.printinfo); + if (printinfo) { + task.printInfo = printinfo; + } + + task.printNum = isPlainObject(task.printNum) ? task.printNum : {}; + // curNum 使用订单在波次内的实际序号(wave_index),与 sumNum(波次总单数)对应 + const waveIndex = toNumber(safeOrderDelivery.wave_index, 0); + const platformsIndex = toNumber(safeOrderDelivery.platforms_index, 0); + const templateCurNum = toNumber(task.printNum.curNum, 0); + const effectiveCurNum = waveIndex > 0 + ? waveIndex + : (platformsIndex > 0 ? platformsIndex : templateCurNum); + task.printNum.curNum = effectiveCurNum > 0 ? effectiveCurNum : 1; + task.printNum.sumNum = toNumber( + safeOrderDelivery.wave_total_orders, + toNumber(task.printNum.sumNum, 0) + ); + + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), + boxNo: Number(safeOrderDelivery.box_no || 0), + } + ); + // 视频号面单自定义区最多 8 行:子单号行 + 头部行 + 商品明细行合计截断,第 9 行起舍弃 + const customProductInfo = truncateSphCustomInfoLines( + appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }).replace(/\n/g, SPH_CUSTOM_INFO_LINE_BREAK), + extraCustomLines, + SPH_CUSTOM_INFO_LINE_BREAK + ) + ); + + task.customInfo = isPlainObject(task.customInfo) ? task.customInfo : {}; + task.customInfo.data = isPlainObject(task.customInfo.data) ? task.customInfo.data : {}; + task.customInfo.data.description = customProductInfo; + + task.extendData = isPlainObject(task.extendData) ? task.extendData : {}; + task.extendData.sender = isPlainObject(task.extendData.sender) ? task.extendData.sender : {}; + task.extendData.sender.address = isPlainObject(task.extendData.sender.address) + ? task.extendData.sender.address + : {}; + task.extendData.sender.address.provinceName = toTrimmedString(safePolicyConfig.province_name); + task.extendData.sender.address.cityName = toTrimmedString(safePolicyConfig.city_name); + task.extendData.sender.address.countyName = toTrimmedString(safePolicyConfig.district_name); + task.extendData.sender.address.detailInfo = toTrimmedString(safePolicyConfig.address); + task.extendData.sender.userName = toTrimmedString(safePolicyConfig.sender_name); + task.extendData.sender.telNumber = toTrimmedString(safePolicyConfig.sender_tel); + + const existingTaskId = toTrimmedString(safeSkeleton.task && safeSkeleton.task.taskID); + if (existingTaskId) { + task.taskID = existingTaskId; + } +} + +/** + * 从京东模板样例中提取主面单 content 原型。 + * + * 优先使用 input.template_sample.parameters.contents[0], + * 缺失时回退为 {},避免影响骨架构建流程。 + * + * @param {Object} templateSample 模板样例对象。 + * @return {Object} 主面单 content 原型。 + */ +function resolveJdTemplateContentPrototype(templateSample) { + const sample = isPlainObject(templateSample) ? templateSample : {}; + + if (!isPlainObject(sample.parameters) || !Array.isArray(sample.parameters.contents)) { + return {}; + } + + const firstContent = sample.parameters.contents[0]; + return isPlainObject(firstContent) ? cloneStructuredValue(firstContent) : {}; +} + +/** + * 读取京东主模板地址。 + * + * @param {Object} orderExpress 快递单对象。 + * @return {string} 京东主模板地址。 + */ +function resolveJdTemplateUrlFromOrderExpress(orderExpress) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + return toTrimmedString(safeOrderExpress.jd_template_url); +} + +/** + * 京东平台主面单字段回填。 + * + * 规则: + * - 仅在平台为 jd 时生效 + * - 主面单原型来源于 template_sample.parameters.contents[0] + * - 保证 skeleton.task.documents[0] 存在并回填 documentID、contents[0] + * - order_express.printinfo 回填 contents[0].printData + * - policy_config 发件人信息回填到 contents[0].addData.sender + * - 自定义区商品信息写入 contents[0].customData.GoodsInfo + * + * @param {string} platform 归一化平台编码。 + * @param {Object} skeleton 打印请求骨架。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @param {Object} policyConfig 策略配置对象。 + * @param {Object} templateSample 模板样例对象。 + * @param {string[]} warnings 风险提示列表。 + * @param {string[]} extraCustomLines 追加到自定义区的额外文本行数组。 + */ +function applyJdExpressFieldMapping( + platform, + skeleton, + orderExpress, + orderDelivery, + policyConfig, + templateSample, + warnings, + extraCustomLines = [] +) { + if (platform !== 'jd') { + return; + } + + const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; + const safeWarnings = Array.isArray(warnings) ? warnings : []; + const contentPrototype = resolveJdTemplateContentPrototype(templateSample); + + safeSkeleton.task = isPlainObject(safeSkeleton.task) ? safeSkeleton.task : {}; + safeSkeleton.task.documents = Array.isArray(safeSkeleton.task.documents) + ? safeSkeleton.task.documents + : []; + + if (!isPlainObject(safeSkeleton.task.documents[0])) { + if (safeSkeleton.task.documents.length === 0) { + safeSkeleton.task.documents.push({}); + } else { + safeSkeleton.task.documents[0] = {}; + } + } + + const document = safeSkeleton.task.documents[0]; + const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); + if (waybillCode) { + document.documentID = waybillCode; + } + + document.contents = Array.isArray(document.contents) ? document.contents : []; + document.contents[0] = cloneStructuredValue(contentPrototype); + + const content = isPlainObject(document.contents[0]) ? document.contents[0] : {}; + document.contents[0] = content; + + const jdTemplateUrl = resolveJdTemplateUrlFromOrderExpress(safeOrderExpress); + if (jdTemplateUrl) { + content.tempUrl = jdTemplateUrl; + } + + const printinfo = toTrimmedString(safeOrderExpress.printinfo); + if (printinfo) { + content.printData = printinfo; + } else { + safeWarnings.push('京东 printinfo 为空,已保留模板 printData 默认值'); + } + + const senderAddress = [ + toTrimmedString(safePolicyConfig.province_name), + toTrimmedString(safePolicyConfig.city_name), + toTrimmedString(safePolicyConfig.district_name), + toTrimmedString(safePolicyConfig.town_name), + toTrimmedString(safePolicyConfig.address), + ].filter(Boolean).join(''); + + content.addData = isPlainObject(content.addData) ? content.addData : {}; + content.addData.sender = isPlainObject(content.addData.sender) ? content.addData.sender : {}; + content.addData.sender.name = toTrimmedString(safePolicyConfig.sender_name); + content.addData.sender.mobile = toTrimmedString(safePolicyConfig.sender_tel); + content.addData.sender.address = senderAddress; + + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, + safePolicyConfig, + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_total || 0), + fallbackItemsCount: Number(safeOrderDelivery.items_count || 0), + waveSource: Number(safeOrderDelivery.wave_source || 0), + waveType: Number(safeOrderDelivery.wave_type || 0), + boxNo: Number(safeOrderDelivery.box_no || 0), + } + ); + const customProductInfo = appendExtraCustomLines( + mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + trailingLineBreak: true, + }), + extraCustomLines, + LINE_BREAK_MAP.LF + ); + + content.customData = isPlainObject(content.customData) ? content.customData : {}; + content.customData.GoodsInfo = customProductInfo; +} + +/** + * 构建平台请求骨架。 + * @param {Object} input 输入对象。 + * @return {{platform: string, platform_meta: Object|null, base_data: Object, request_skeleton: Object, missing_fields: Array, warnings: string[]}} 中间态结果。 + */ +function buildPlatformRequestSkeleton(input = {}) { + const normalized = normalizePlatformAlias( + input.platform + || (isPlainObject(input.order_express) ? input.order_express.platform_code : '') + || (isPlainObject(input.order_delivery) ? input.order_delivery.source_platform_code : '') + ); + + const baseResult = buildBaseData(input, normalized.platform, normalized.meta); + const options = isPlainObject(input.options) ? input.options : {}; + const extraCustomLines = Array.isArray(options.extraCustomLines) ? options.extraCustomLines : []; + const policyConfig = resolvePolicyConfig(input); + const subjectConfig = resolveSubjectConfig(input); + // 发件人兜底:签约策略 policy_config 非空值优先,空值回退仓库主体 subject_config。 + // 与 buildBaseData 的三级兜底语义保持一致,避免签约策略未配发件人时 + // 平台面单(快手/拼多多/抖音等)senderInfo/sender 输出为空。 + const policyConfigWithSenderFallback = resolveSenderFallbackConfig(policyConfig, subjectConfig); + const orderExpressForCompose = isPlainObject(input.order_express) + ? { ...input.order_express } + : {}; + const orderDeliveryForCompose = isPlainObject(input.order_delivery) + ? { ...input.order_delivery, package_material_name: String(options.packageMaterialName || '').trim() } + : {}; + if (!orderExpressForCompose.items && orderDeliveryForCompose.items) { + orderExpressForCompose.items = orderDeliveryForCompose.items; + } + const templateSample = isPlainObject(input.template_sample) ? input.template_sample : {}; + + const warnings = [ ...baseResult.warnings ]; + const cleanedTemplateSample = sanitizeTemplatePrivateFields(templateSample, warnings); + const customDataTemplateURL = resolveKuaishouCustomDataTemplateURL(templateSample); + const cainiaoCustomControlTemplateURL = resolveCainiaoCustomControlTemplateURL(templateSample); + + const requestId = toTrimmedString(options.requestId || templateSample.requetID || templateSample.requestID); + const taskId = toTrimmedString(options.taskId || requestId); + const sampleDocumentSources = [ + templateSample.task && templateSample.task.documents, + templateSample.documents, + templateSample.taskList, + ]; + let sampleDocumentId = ''; + + for (const documents of sampleDocumentSources) { + if (!Array.isArray(documents) || documents.length === 0) { + continue; + } + + const firstDocument = documents[0]; + if (isPlainObject(firstDocument) && firstDocument.documentID) { + sampleDocumentId = firstDocument.documentID; + break; + } + } + + const documentId = toTrimmedString( + options.documentId || sampleDocumentId + ); + + const sampleTaskDocuments = cleanedTemplateSample.task && Object.prototype.hasOwnProperty.call(cleanedTemplateSample.task, 'documents') + ? buildArraySkeleton(cleanedTemplateSample.task.documents, warnings, 'documents') + : []; + + const skeleton = { + cmd: toTrimmedString(templateSample.cmd || 'print'), + requestID: requestId, + version: toTrimmedString(templateSample.version || '1.0'), + task: { + taskID: taskId, + preview: options.preview === undefined ? false : !!options.preview, + printer: toTrimmedString(options.printer), + }, + }; + + if (sampleTaskDocuments.length > 0) { + skeleton.task.documents = sampleTaskDocuments; + + if (skeleton.task.documents[0] && isPlainObject(skeleton.task.documents[0])) { + if (documentId) { + skeleton.task.documents[0].documentID = toTrimmedString(documentId); + } + + if (!Array.isArray(skeleton.task.documents[0].contents)) { + skeleton.task.documents[0].contents = []; + } + } + } else if (cleanedTemplateSample.task && Object.prototype.hasOwnProperty.call(cleanedTemplateSample.task, 'documents')) { + skeleton.task.documents = []; + } + + if (Object.prototype.hasOwnProperty.call(cleanedTemplateSample, 'documents')) { + skeleton.documents = buildArraySkeleton(cleanedTemplateSample.documents, warnings, 'documents'); + } + + if (Object.prototype.hasOwnProperty.call(cleanedTemplateSample, 'taskList')) { + skeleton.taskList = buildArraySkeleton(cleanedTemplateSample.taskList, warnings, 'taskList'); + } + + if (cleanedTemplateSample.task && Object.prototype.hasOwnProperty.call(cleanedTemplateSample.task, 'documents') && sampleTaskDocuments.length === 0) { + warnings.push('template_sample.task.documents 为空或未能解析,已输出空 documents 数组'); + } + + applyCainiaoExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfigWithSenderFallback, + cainiaoCustomControlTemplateURL, + warnings, + extraCustomLines + ); + + applyKuaishouExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + warnings, + policyConfigWithSenderFallback, + customDataTemplateURL, + extraCustomLines + ); + + applyPddExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfigWithSenderFallback, + extraCustomLines + ); + + applyDouyinExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfigWithSenderFallback, + extraCustomLines, + options.customAreaBaseUrl + ); + + applyJdExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfigWithSenderFallback, + templateSample, + warnings, + extraCustomLines + ); + + applyXhsExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfigWithSenderFallback, + warnings, + extraCustomLines + ); + + applySphExpressFieldMapping( + normalized.platform, + skeleton, + orderExpressForCompose, + orderDeliveryForCompose, + policyConfigWithSenderFallback, + extraCustomLines + ); + + return { + platform: normalized.platform, + platform_meta: normalized.meta, + base_data: baseResult.base_data, + request_skeleton: skeleton, + missing_fields: baseResult.missing_fields, + warnings, + }; +} + +class PrinterDataBuilder { + /** + * 获取平台硬编码映射。 + * @return {Object} 平台映射对象。 + */ + static getPlatformMap() { + return PLATFORM_MAP; + } + + /** + * 获取换行符映射。 + * @return {Object} 换行符映射对象。 + */ + static getLineBreakMap() { + return LINE_BREAK_MAP; + } + + /** + * 平台别名归一化。 + * @param {string} platform 平台别名。 + * @return {{platform: string, meta: Object|null, raw: string}} 归一化结果。 + */ + static normalizePlatformAlias(platform) { + return normalizePlatformAlias(platform); + } + + /** + * 组装基础打印数据。 + * @param {Object} input 输入对象。 + * @return {{base_data: Object, missing_fields: Array, warnings: string[]}} 组装结果。 + */ + static buildBaseData(input = {}) { + const normalized = normalizePlatformAlias( + input.platform + || (isPlainObject(input.order_express) ? input.order_express.platform_code : '') + || (isPlainObject(input.order_delivery) ? input.order_delivery.source_platform_code : '') + ); + + return buildBaseData(input, normalized.platform, normalized.meta); + } + + /** + * 组装平台请求骨架(中间态)。 + * @param {Object} input 输入对象。 + * @return {{platform: string, platform_meta: Object|null, base_data: Object, request_skeleton: Object, missing_fields: Array, warnings: string[]}} 组装结果。 + */ + static buildPlatformRequestSkeleton(input = {}) { + return buildPlatformRequestSkeleton(input); + } +} + +module.exports = PrinterDataBuilder; diff --git a/app/lib/ptz_client.js b/app/lib/ptz_client.js new file mode 100644 index 0000000..1bede20 --- /dev/null +++ b/app/lib/ptz_client.js @@ -0,0 +1,325 @@ +'use strict'; + +/** + * PTZ(云台控制)客户端模块。 + * 负责组装 RTSP URL 并调用打印服务的云台端点下发控制指令。 + * 与 `lib/osd_client.js` 同风格:独立端点 + 独立请求体,**不带 computerId** + * (打印服务按 rtspUrl 定位摄像头,无需房间路由)。 + * + * 端点与请求体(warehouse_id 为字符串、cameraId 为摄像头ID,与 setOSD 口径一致): + * - /camera/ptzControl :按下(按方向持续转动),松手时必须配对调用 stop + * { warehouse_id, cameraId, rtspUrl, action, speed } + * - /camera/ptzStop :松手(停止转动),action 必须与按下时一致 + * { warehouse_id, cameraId, rtspUrl, action } + * - /camera/ptzPresetGoto :跳转预置点,一次调用即可,无需 stop + * { warehouse_id, cameraId, rtspUrl, presetId } + * - /camera/ptzPresetSet :设置预置点(把当前机位存为指定编号),一次调用即可 + * { warehouse_id, cameraId, rtspUrl, presetId } + * + * 使用方式: + * const PtzClient = require('../lib/ptz_client'); + * const ptzClient = new PtzClient(ctx); + * await ptzClient.control({ camera, warehouseId, action, speed }); + */ + +/** 打印服务云台端点路径 */ +const PTZ_PATH = { + CONTROL: '/camera/ptzControl', + STOP: '/camera/ptzStop', + PRESET_GOTO: '/camera/ptzPresetGoto', + PRESET_SET: '/camera/ptzPresetSet', +}; + +/** 云台方向枚举(与打印服务约定的 8 个位置,顺序固定) */ +const PTZ_ACTION_LIST = [ + { value: 'up', name: '上' }, + { value: 'down', name: '下' }, + { value: 'left', name: '左' }, + { value: 'right', name: '右' }, + { value: 'upleft', name: '左上' }, + { value: 'upright', name: '右上' }, + { value: 'downleft', name: '左下' }, + { value: 'downright', name: '右下' }, +]; + +/** 云台方向值列表 */ +const PTZ_ACTIONS = PTZ_ACTION_LIST.map(item => item.value); + +/** 默认转速 */ +const PTZ_DEFAULT_SPEED = 4; +/** 转速下限 */ +const PTZ_MIN_SPEED = 1; +/** 转速上限 */ +const PTZ_MAX_SPEED = 7; +/** 预置点编号下限 */ +const PTZ_MIN_PRESET_ID = 1; +/** 预置点编号上限 */ +const PTZ_MAX_PRESET_ID = 256; +/** 打印服务请求超时(毫秒) */ +const PTZ_REQUEST_TIMEOUT = 10000; + +class PtzClient { + constructor(ctx) { + this.ctx = ctx; + this.logger = ctx.logger || console; + } + + /** + * 云台方向枚举(供文档/校验共用)。 + * @return {Array} [{ value, name }] + */ + static getActionList() { + return PTZ_ACTION_LIST.map(item => ({ ...item })); + } + + /** + * 组装摄像头 RTSP 地址。 + * 与 `lib/osd_client.js#buildRtspUrl` 保持同口径(打印服务以该地址定位摄像头)。 + * + * @param {Object} camera - 摄像头记录(含 ip/username/password/channel_id) + * @return {string} RTSP URL + */ + buildRtspUrl(camera) { + const ip = camera && camera.ip; + if (!ip) { + throw new Error('摄像头未配置IP地址,无法组装RTSP地址'); + } + + const username = camera.username || 'admin'; + const password = camera.password || ''; + const channelId = camera.channel_id; + const rtspPort = 554; + + return `rtsp://${username}:${password}@${ip}:${rtspPort}/stream${channelId}`; + } + + /** + * 校验并归一化云台方向。 + * + * @param {string} action - 云台方向 + * @param {string} [label] - 报错文案中的字段名 + * @return {string} 归一化后的方向值 + */ + static normalizeAction(action, label = '云台方向') { + const value = String(action === undefined || action === null ? '' : action).trim().toLowerCase(); + if (!value) throw new Error(`${label}不能为空`); + if (!PTZ_ACTIONS.includes(value)) { + throw new Error(`${label}不合法,仅支持:${PTZ_ACTIONS.join('/')}`); + } + return value; + } + + /** + * 校验并归一化云台转速(缺省 4)。 + * + * @param {number|string} speed - 转速 + * @return {number} 归一化后的转速 + */ + static normalizeSpeed(speed) { + if (speed === undefined || speed === null || speed === '') return PTZ_DEFAULT_SPEED; + const value = Number(speed); + if (!Number.isInteger(value) || value < PTZ_MIN_SPEED || value > PTZ_MAX_SPEED) { + throw new Error(`云台转速需为 ${PTZ_MIN_SPEED}-${PTZ_MAX_SPEED} 的整数`); + } + return value; + } + + /** + * 校验并归一化预置点编号。 + * + * @param {number|string} presetId - 预置点编号 + * @return {number} 归一化后的预置点编号 + */ + static normalizePresetId(presetId) { + if (presetId === undefined || presetId === null || presetId === '') { + throw new Error('预置点编号不能为空'); + } + const value = Number(presetId); + if (!Number.isInteger(value) || value < PTZ_MIN_PRESET_ID || value > PTZ_MAX_PRESET_ID) { + throw new Error(`预置点编号需为 ${PTZ_MIN_PRESET_ID}-${PTZ_MAX_PRESET_ID} 的整数`); + } + return value; + } + + /** + * 下发云台指令到打印服务(独立端点,与 setOSD 同风格,不带 computerId)。 + * 请求体统一携带 warehouse_id(字符串)与 cameraId(摄像头ID)。 + * + * @param {Object} options - 指令参数 + * @param {Object} options.camera - 摄像头记录(取 id 作为 cameraId,并用于日志) + * @param {string} options.path - 打印服务端点路径 + * @param {number} options.warehouseId - 仓库ID + * @param {Object} options.data - 请求体业务字段 + * @return {Promise} { success, error, response, request } + */ + async _send(options = {}) { + const { ctx } = this; + const { camera, path: targetPath, warehouseId, data } = options; + + if (!targetPath) throw new Error('打印服务端点路径不能为空'); + if (!camera) throw new Error('摄像头信息不能为空'); + + const warehouseValue = Number(warehouseId); + if (!Number.isInteger(warehouseValue) || warehouseValue <= 0) { + throw new Error('仓库ID不合法'); + } + const cameraValue = Number(camera.id); + if (!Number.isInteger(cameraValue) || cameraValue <= 0) { + throw new Error('摄像头ID不合法'); + } + + const printServiceUrl = ctx.app.config.printService.url; + const targetUrl = `${printServiceUrl}${targetPath}`; + const requestData = { + warehouse_id: String(warehouseValue), + cameraId: cameraValue, + ...data, + }; + + ctx.logger.info('[PTZ] 发送云台指令', { url: targetUrl, body: requestData }); + + let response = null; + let error = null; + try { + const res = await ctx.curl(targetUrl, { + method: 'POST', + contentType: 'json', + data: requestData, + dataType: 'json', + timeout: PTZ_REQUEST_TIMEOUT, + }); + response = { + status: res.status, + headers: res.headers, + data: res.data, + }; + ctx.logger.info('[PTZ] 打印服务回信', { status: res.status, data: res.data }); + } catch (err) { + error = err.message; + ctx.logger.warn('[PTZ] 打印服务请求失败', { + camera_id: camera && camera.id, + url: targetUrl, + error: err.message, + }); + } + + const httpOk = !!response && response.status >= 200 && response.status < 300; + const body = response && response.data; + if (!error && httpOk && body && typeof body === 'object' + && (body.status === 'fail' || body.success === false)) { + error = body.message || body.error || '打印服务返回失败'; + } + + return { + success: !error && httpOk, + error, + response, + request: requestData, + }; + } + + /** + * 按下:按指定方向转动云台。 + * + * @param {Object} options - 参数 + * @param {Object} options.camera - 摄像头记录 + * @param {number} options.warehouseId - 仓库ID + * @param {string} options.action - 云台方向(up/down/left/right/upleft/upright/downleft/downright) + * @param {number} [options.speed] - 转速(1-7,默认 4) + * @return {Promise} 打印服务响应 + */ + async control(options = {}) { + const { camera, warehouseId, action, speed } = options; + if (!camera) throw new Error('摄像头信息不能为空'); + + return await this._send({ + camera, + path: PTZ_PATH.CONTROL, + warehouseId, + data: { + rtspUrl: this.buildRtspUrl(camera), + action: PtzClient.normalizeAction(action), + speed: PtzClient.normalizeSpeed(speed), + }, + }); + } + + /** + * 松手:停止云台转动。 + * + * @param {Object} options - 参数 + * @param {Object} options.camera - 摄像头记录 + * @param {number} options.warehouseId - 仓库ID + * @param {string} options.action - 云台方向(必须与按下时一致) + * @return {Promise} 打印服务响应 + */ + async stop(options = {}) { + const { camera, warehouseId, action } = options; + if (!camera) throw new Error('摄像头信息不能为空'); + + return await this._send({ + camera, + path: PTZ_PATH.STOP, + warehouseId, + data: { + rtspUrl: this.buildRtspUrl(camera), + action: PtzClient.normalizeAction(action), + }, + }); + } + + /** + * 跳转预置点(一次调用即可,无需 stop)。 + * + * @param {Object} options - 参数 + * @param {Object} options.camera - 摄像头记录 + * @param {number} options.warehouseId - 仓库ID + * @param {number|string} options.presetId - 预置点编号(1-256) + * @return {Promise} 打印服务响应 + */ + async presetGoto(options = {}) { + const { camera, warehouseId, presetId } = options; + if (!camera) throw new Error('摄像头信息不能为空'); + + return await this._send({ + camera, + path: PTZ_PATH.PRESET_GOTO, + warehouseId, + data: { + rtspUrl: this.buildRtspUrl(camera), + presetId: PtzClient.normalizePresetId(presetId), + }, + }); + } + + /** + * 设置预置点:把摄像头当前机位保存为指定预置点编号(一次调用即可)。 + * + * @param {Object} options - 参数 + * @param {Object} options.camera - 摄像头记录 + * @param {number} options.warehouseId - 仓库ID + * @param {number|string} options.presetId - 预置点编号(1-256) + * @return {Promise} 打印服务响应 + */ + async presetSet(options = {}) { + const { camera, warehouseId, presetId } = options; + if (!camera) throw new Error('摄像头信息不能为空'); + + return await this._send({ + camera, + path: PTZ_PATH.PRESET_SET, + warehouseId, + data: { + rtspUrl: this.buildRtspUrl(camera), + presetId: PtzClient.normalizePresetId(presetId), + }, + }); + } +} + +module.exports = PtzClient; +module.exports.PTZ_PATH = PTZ_PATH; +module.exports.PTZ_ACTIONS = PTZ_ACTIONS; +module.exports.PTZ_DEFAULT_SPEED = PTZ_DEFAULT_SPEED; +module.exports.PTZ_MAX_SPEED = PTZ_MAX_SPEED; +module.exports.PTZ_MAX_PRESET_ID = PTZ_MAX_PRESET_ID; diff --git a/app/lib/qimen_client.js b/app/lib/qimen_client.js new file mode 100644 index 0000000..1bf62f9 --- /dev/null +++ b/app/lib/qimen_client.js @@ -0,0 +1,315 @@ +'use strict'; + +const crypto = require('crypto'); +const http = require('http'); +const https = require('https'); + +class QimenClient { + constructor(app) { + this.app = app; + } + + resolveRuntime(runtime = {}) { + const ctx = runtime.ctx || {}; + const qimenService = ctx.service && ctx.service.qimen ? ctx.service.qimen : null; + const signService = ctx.service && ctx.service.systems && ctx.service.systems.sign ? ctx.service.systems.sign : null; + + return { + ctx, + toXml: runtime.toXml || (signService && typeof signService.toXml === 'function' + ? signService.toXml.bind(signService) + : qimenService && typeof qimenService.formatResponse === 'function' + ? qimenService.formatResponse.bind(qimenService) + : null), + parseXmlToArray: runtime.parseXmlToArray || (qimenService && typeof qimenService.parseXmlToArray === 'function' + ? qimenService.parseXmlToArray.bind(qimenService) + : null), + saveQimenLog: runtime.saveQimenLog || (qimenService && typeof qimenService.saveQimenLog === 'function' + ? qimenService.saveQimenLog.bind(qimenService) + : async () => null), + signTopRequest: runtime.signTopRequest || (signService && typeof signService.signTopRequest === 'function' + ? signService.signTopRequest.bind(signService) + : null), + formatDate: runtime.formatDate || ctx.app?.formatDate || this.app.formatDate || (date => (date && typeof date.toISOString === 'function' ? date.toISOString() : String(date))), + }; + } + + normalizeRequestPayload(data) { + if (!data || typeof data !== 'object' || Array.isArray(data)) { + return { request: data }; + } + + if (Object.prototype.hasOwnProperty.call(data, 'request')) { + return data; + } + + return { request: data }; + } + + /** + * 生成出站奇门请求的唯一日志 ID。 + * 不复用入站请求的 ctx.qimenLogId,避免与入站文件队列落库产生唯一索引冲突。 + * @return {string} 唯一日志 ID。 + */ + generateLogId() { + return `QL-${Date.now()}-${crypto.randomBytes(3).toString('hex')}`; + } + + replaceXmlTagsWithString(xmlString, oldTag, newTag) { + const startTagRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?>`, 'gi'); + const endTagRegex = new RegExp(`<\\s*/\\s*${oldTag}\\s*>`, 'gi'); + const selfClosingRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?\\s*/>`, 'gi'); + + return xmlString + .replace(startTagRegex, (match, attributes = '') => `<${newTag}${attributes}>`) + .replace(endTagRegex, ``) + .replace(selfClosingRegex, (match, attributes = '') => `<${newTag}${attributes}/>`); + } + + replaceDeliveryConfirmSnListTags(xmlString) { + const snListBlockRegex = /<\s*snList(\s+[^>]*)?>[\s\S]*?<\s*\/\s*snList\s*>/gi; + + return String(xmlString || '').replace(snListBlockRegex, block => { + // 奇门 deliveryorder.confirm 要求 snList 下为 子节点,而 buildXmlNode 对标量数组统一输出 + return this.replaceXmlTagsWithString(block, 'item', 'sn'); + }); + } + + replaceDeliveryConfirmOrderLineTags(xmlString) { + const orderLinesBlockRegex = /<\s*orderLines(\s+[^>]*)?>[\s\S]*?<\s*\/\s*orderLines\s*>/gi; + + return String(xmlString || '').replace(orderLinesBlockRegex, block => { + // 先修正 snList 内的 ,否则会被下面的 item→orderLine 替换误伤 + const withSnList = this.replaceDeliveryConfirmSnListTags(block); + return this.replaceXmlTagsWithString(withSnList, 'item', 'orderLine'); + }); + } + + replaceDeliveryConfirmPackageTags(xmlString) { + const packagesBlockRegex = /<\s*packages(\s+[^>]*)?>([\s\S]*?)<\s*\/\s*packages\s*>/gi; + + return String(xmlString || '').replace(packagesBlockRegex, (match, attributes = '', inner = '') => { + // buildXmlNode 把 packages.package 数组序列化成 …, + // 奇门要求 …:去掉数组容器,再把每个 改名为 , + // 否则一单多运单号(多个包裹)时标签会错位成 / + const withoutContainer = String(inner) + .replace(/^\s*<\s*package\s*>/, '') + .replace(/<\s*\/\s*package\s*>\s*$/, ''); + + // 下的 是包裹内商品明细,必须保留原名;先占位保护,改名后再还原 + const innerItemsBlocks = []; + const protectedInner = withoutContainer.replace(/<\s*items(\s+[^>]*)?>[\s\S]*?<\s*\/\s*items\s*>/gi, block => { + innerItemsBlocks.push(block); + return `@@PACKAGE_ITEMS_${innerItemsBlocks.length - 1}@@`; + }); + + const renamed = this.replaceXmlTagsWithString(protectedInner, 'item', 'package'); + const restored = renamed.replace(/@@PACKAGE_ITEMS_(\d+)@@/g, + (placeholder, index) => innerItemsBlocks[Number(index)] || placeholder); + + return `${restored}`; + }); + } + + replaceDeliveryConfirmPayloadTags(xmlString) { + const withPackages = this.replaceDeliveryConfirmPackageTags(xmlString); + return this.replaceDeliveryConfirmOrderLineTags(withPackages); + } + + addSign(baseQueryParams, sign) { + return Object.assign({}, baseQueryParams, { sign }); + } + + /** + * 构建奇门请求查询参数。 + * @param {string} method 接口方法名 + * @param {string} appKey 应用 Key + * @param {string} version 接口版本 + * @param {?string} customerId 货主标识 + * @param {Function} formatDate 时间格式化函数 + * @return {Object} 查询参数对象 + */ + getQueryParams(method, appKey, version, customerId, formatDate) { + const queryParams = { + method, + format: 'xml', + app_key: appKey, + v: version, + sign_method: 'md5', + timestamp: formatDate(new Date()), + }; + + if (customerId != null) { + queryParams.customerId = customerId; + } + + return queryParams; + } + + generateUrlWithParams(baseUrl, params) { + if (!params || Object.keys(params).length === 0) { + return baseUrl; + } + + const queryString = Object.keys(params) + .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) + .join('&'); + + const separator = baseUrl.includes('?') ? '&' : '?'; + return `${baseUrl}${separator}${queryString}`; + } + + /** + * 发送奇门请求并记录请求日志。 + * @param {string} method 接口方法名 + * @param {?string} customerId 货主标识 + * @param {Object} data 业务请求数据 + * @param {Object} runtime 运行时依赖 + * @return {Promise<{queryId: *, xmlArray: *}>} 查询结果 + */ + async send(method, customerId, data, runtime = {}) { + const helpers = this.resolveRuntime(runtime); + + if (!helpers.toXml) { + throw new Error('缺少奇门 XML 转换器'); + } + + if (!helpers.parseXmlToArray) { + throw new Error('缺少奇门响应解析器'); + } + + if (!helpers.signTopRequest) { + throw new Error('缺少奇门签名器'); + } + + const wmsAppKey = this.app.config.qimen.appKey; + const baseQueryParams = this.getQueryParams(method, wmsAppKey, '2.0', customerId, helpers.formatDate); + const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service'; + const requestPayload = this.normalizeRequestPayload(data); + const xmlData = await helpers.toXml(requestPayload); + const queryData = method === 'taobao.qimen.deliveryorder.confirm' || method === 'taobao.qimen.stockout.confirm' + ? this.replaceDeliveryConfirmPayloadTags(xmlData) + : this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine'); + const sign = await helpers.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5'); + const queryParams = this.addSign(baseQueryParams, sign); + const url = this.generateUrlWithParams(baseUrl, queryParams); + const logData = { + from_key: this.app.config.qimen.appKey, + to_key: wmsAppKey, + method, + sign, + v: '2.0', + url, + created_at: new Date(), + body: '', + result: '', + use_time: 0, + }; + + if (customerId != null) { + logData.costomer_id = customerId; + } + console.log('发送奇门请求,URL:', url, '请求数据:', queryData); + const result = await this.sendRequest(url, queryData, logData, helpers); + console.log('奇门请求响应:', result); + const xmlArray = await helpers.parseXmlToArray(result.res); + return { queryId: result.queryId, xmlArray }; + } + + /** + * 发送出站奇门 HTTP 请求,并把出站请求日志直接落库。 + * 出站日志使用独立生成的 log_id,不复用入站请求的 ctx.qimenLogId, + * 避免与入站日志的文件队列落库路径产生 log_id 唯一索引冲突。 + * @param {string} url 请求地址。 + * @param {Object|string} requestData 请求数据(对象或 XML 字符串)。 + * @param {Object} [logData={}] 日志附加字段。 + * @param {Object} [runtime={}] 运行时依赖。 + * @return {Promise<{queryId: number|undefined, res: string}>} 查询 ID 与响应内容。 + */ + async sendRequest(url, requestData, logData = {}, runtime = {}) { + const helpers = this.resolveRuntime(runtime); + const startTime = Date.now(); + // 出站请求不复用入站 ctx.qimenLogId:入站日志统一由文件队列异步落库, + // log_id 唯一索引下共用同一 ID 会触发 Duplicate entry 冲突。 + const requestLogData = Object.assign({ + body: requestData, + result: '', + log_id: this.generateLogId(), + }, logData); + + requestLogData.body = requestLogData.body || requestData; + requestLogData.result = requestLogData.result || ''; + requestLogData.log_id = requestLogData.log_id || this.generateLogId(); + + const httpquery = url.indexOf('https://') > -1 ? https : http; + let requestXml; + + try { + if (typeof requestData === 'string') { + requestXml = requestData; + if (requestXml.trim() === '') { + throw new Error('请求数据为空字符串'); + } + } else { + requestXml = await helpers.toXml(requestData); + } + + if (!requestXml || requestXml.trim() === '') { + throw new Error('XML内容为空'); + } + } catch (error) { + requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`; + await helpers.saveQimenLog(requestLogData, startTime); + throw error; + } + + const header = { + 'Content-Type': 'application/xml', + 'Content-Length': Buffer.byteLength(requestXml, 'utf8'), + 'User-Agent': 'EggJS Client', + }; + + const options = { + method: 'POST', + headers: header, + }; + + 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.write(requestXml); + req.end(); + }); + } catch (error) { + requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`; + await helpers.saveQimenLog(requestLogData, startTime); + throw error; + } + + requestLogData.result = res; + const queryId = await helpers.saveQimenLog(requestLogData, startTime); + return { queryId, res }; + } +} + +module.exports = QimenClient; diff --git a/app/lib/query_condition_parser.js b/app/lib/query_condition_parser.js new file mode 100644 index 0000000..81a9b8e --- /dev/null +++ b/app/lib/query_condition_parser.js @@ -0,0 +1,333 @@ +'use strict'; + +function isPlainObject(value) { + return value && typeof value === 'object' && !Array.isArray(value); +} + +function isEmptyValue(value) { + if (value === undefined || value === null) { + return true; + } + + if (typeof value === 'string' && value.trim() === '') { + return true; + } + + if (Array.isArray(value) && value.length === 0) { + return true; + } + + return false; +} + +function formatLocalDateTime(date, isEnd = false) { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${year}-${month}-${day} ${isEnd ? '23:59:59' : '00:00:00'}`; +} + +function normalizeDate(value, options = {}) { + const { isEnd = false } = options; + + if (value === undefined || value === null) { + return value; + } + + if (value instanceof Date) { + if (isNaN(value.getTime())) return value; + return formatLocalDateTime(value, isEnd); + } + + if (typeof value === 'number') { + const date = new Date(value); + if (isNaN(date.getTime())) return value; + return formatLocalDateTime(date, isEnd); + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return trimmed; + } + + if (/^\d+$/.test(trimmed)) { + const date = new Date(Number(trimmed)); + if (!isNaN(date.getTime())) { + return formatLocalDateTime(date, isEnd); + } + return trimmed; + } + + const parsed = new Date(trimmed); + if (!isNaN(parsed.getTime())) { + return formatLocalDateTime(parsed, isEnd); + } + + return trimmed; + } + + return value; +} + +function processConditionValue(value, type) { + if (value === undefined || value === null) { + return value; + } + + switch (type) { + case 'boolean': + if (value === true || value === 'true' || value === 'Y' || value === 'y') { + return 'Y'; + } + if (value === false || value === 'false' || value === 'N' || value === 'n') { + return 'N'; + } + return value; + + case 'date': + return normalizeDate(value, { isEnd: false }); + + case 'daterange': + if (Array.isArray(value)) { + return value.map((v, index) => normalizeDate(v, { isEnd: index === value.length - 1 })); + } + return normalizeDate(value, { isEnd: false }); + + case 'number': { + const num = parseFloat(value); + return isNaN(num) ? value : num; + } + + case 'text': + if (Array.isArray(value)) { + return value.map(item => String(item).trim()).filter(Boolean); + } + return String(value).split(',').map(item => item.trim()) + .filter(Boolean); + + default: + return value; + } +} + +function buildSequelizeCondition(fieldKey, condition, app) { + if (!isPlainObject(condition)) { + return { ok: false, reason: 'condition 必须是对象' }; + } + + const { Sequelize } = app; + const { + operator = 'eq', value, type, + } = condition; + + const fieldName = condition.field || fieldKey; + const processedValue = processConditionValue(value, type); + const op = String(operator || 'eq').toLowerCase(); + + switch (op) { + case 'eq': + return { ok: true, condition: { [fieldName]: processedValue } }; + + case 'ne': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.ne]: processedValue } } }; + + case 'contains': + case 'like': + if (Array.isArray(processedValue) && processedValue.length > 0) { + return { + ok: true, + condition: { + [Sequelize.Op.or]: processedValue.map(val => ({ + [fieldName]: { + [Sequelize.Op.like]: `%${val}%`, + }, + })), + }, + }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}%` } } }; + + case 'notlike': + if (Array.isArray(processedValue) && processedValue.length > 0) { + return { + ok: true, + condition: { + [Sequelize.Op.and]: processedValue.map(val => ({ + [fieldName]: { + [Sequelize.Op.notLike]: `%${val}%`, + }, + })), + }, + }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notLike]: `%${processedValue}%` } } }; + + case 'startswith': + if (Array.isArray(processedValue) && processedValue.length > 0) { + return { + ok: true, + condition: { + [Sequelize.Op.or]: processedValue.map(val => ({ + [fieldName]: { + [Sequelize.Op.like]: `${val}%`, + }, + })), + }, + }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `${processedValue}%` } } }; + + case 'endswith': + if (Array.isArray(processedValue) && processedValue.length > 0) { + return { + ok: true, + condition: { + [Sequelize.Op.or]: processedValue.map(val => ({ + [fieldName]: { + [Sequelize.Op.like]: `%${val}`, + }, + })), + }, + }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}` } } }; + + case 'gt': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.gt]: processedValue } } }; + + case 'lt': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.lt]: processedValue } } }; + + case 'ge': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.gte]: processedValue } } }; + + case 'le': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.lte]: processedValue } } }; + + case 'in': + if (!Array.isArray(processedValue)) { + return { ok: false, reason: `${fieldName} 的 in 操作符要求 value 为数组` }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.in]: processedValue } } }; + + case 'notin': + if (!Array.isArray(processedValue)) { + return { ok: false, reason: `${fieldName} 的 notin 操作符要求 value 为数组` }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notIn]: processedValue } } }; + + case 'between': + if (!Array.isArray(processedValue) || processedValue.length !== 2) { + return { ok: false, reason: `${fieldName} 的 between 操作符要求 value 为长度为2的数组` }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.between]: processedValue } } }; + + case 'notbetween': + if (!Array.isArray(processedValue) || processedValue.length !== 2) { + return { ok: false, reason: `${fieldName} 的 notbetween 操作符要求 value 为长度为2的数组` }; + } + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notBetween]: processedValue } } }; + + case 'isnull': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.is]: null } } }; + + case 'isnotnull': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.not]: null } } }; + + case 'regexp': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.regexp]: processedValue } } }; + + case 'notregexp': + return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notRegexp]: processedValue } } }; + + default: + return { ok: true, condition: { [fieldName]: processedValue } }; + } +} + +function parseWhereConditions(options = {}) { + const { + where, + app, + specialFieldMap = {}, + } = options; + + if (where === undefined || where === null) { + return { + ok: true, + result: { + dynamicConditions: [], + bucketConditions: {}, + bucketFlags: {}, + rawConditionsByField: {}, + }, + }; + } + + if (!isPlainObject(where)) { + return { ok: false, reason: 'where 必须是对象' }; + } + + const dynamicConditions = []; + const bucketConditions = {}; + const bucketFlags = {}; + const rawConditionsByField = {}; + + for (const [ fieldKey, condition ] of Object.entries(where)) { + if (!isPlainObject(condition)) { + return { ok: false, reason: `字段 ${fieldKey} 条件必须是对象` }; + } + + if (isEmptyValue(condition.value)) { + continue; + } + + const mapped = specialFieldMap[fieldKey] || {}; + const normalizedCondition = { + ...condition, + }; + + if (mapped.field) { + normalizedCondition.field = mapped.field; + } + + const built = buildSequelizeCondition(fieldKey, normalizedCondition, app); + if (!built.ok) { + return { + ok: false, + reason: `字段 ${fieldKey} 解析失败: ${built.reason}`, + }; + } + + if (mapped.bucket) { + if (!bucketConditions[mapped.bucket]) { + bucketConditions[mapped.bucket] = []; + } + bucketConditions[mapped.bucket].push(built.condition); + bucketFlags[mapped.bucket] = true; + rawConditionsByField[fieldKey] = normalizedCondition; + continue; + } + + dynamicConditions.push(built.condition); + } + + return { + ok: true, + result: { + dynamicConditions, + bucketConditions, + bucketFlags, + rawConditionsByField, + }, + }; +} + +module.exports = { + isEmptyValue, + normalizeDate, + processConditionValue, + buildSequelizeCondition, + parseWhereConditions, +}; diff --git a/app/lib/report/day_window.js b/app/lib/report/day_window.js new file mode 100644 index 0000000..9b30a27 --- /dev/null +++ b/app/lib/report/day_window.js @@ -0,0 +1,171 @@ +'use strict'; + +/** + * 报表「日窗口」纯函数工具模块(无 ctx 依赖,可单测)。 + * + * 日窗口定义:[D 07:00, D+1 07:00) 半开区间(毫秒时间戳), + * 与旧 PHP《7日出入库数据》(Wms.php putout_putin_storage7) 的 + * 07:00 切日口径保持一致,统一使用服务器本地时区(不依赖 UTC)。 + */ + +const DEFAULT_DAY_COUNT = 7; +const DEFAULT_CUTOVER_HOUR = 7; + +/** + * 数字补零为两位字符串。 + * @param {number} value 数值 + * @return {string} 补零后的两位字符串 + */ +function pad2(value) { + return String(value).padStart(2, '0'); +} + +/** + * 按本地时区构建连续的日窗口列表(最旧在前)。 + * + * 规则: + * 1. 每个窗口为 [D 07:00, D+1 07:00)(cutoverHour 可配置),start 含、end 不含; + * 2. 最新窗口是「包含 now 的窗口」:now 当日已过切点时从今日切点起算, + * 未过切点时从昨日切点起算; + * 3. 窗口共 dayCount 个,按时间从旧到新排列; + * 4. 通过 `new Date(y, m, d + offset, hour)` 构造,规避夏令时导致的 24h 步进偏差。 + * + * @param {Object} [options={}] 构建选项 + * @param {number} [options.dayCount=7] 窗口数量 + * @param {number} [options.cutoverHour=7] 切点小时(0-23) + * @param {number|Date} [options.now=Date.now()] 参考时刻 + * @return {Array<{start: number, end: number}>} 日窗口列表(毫秒,最旧在前) + */ +function buildDayWindows({ dayCount = DEFAULT_DAY_COUNT, cutoverHour = DEFAULT_CUTOVER_HOUR, now = Date.now() } = {}) { + const normalizedCount = Math.max(1, Math.floor(Number(dayCount) || DEFAULT_DAY_COUNT)); + const normalizedHour = Math.min(23, Math.max(0, Math.floor(Number(cutoverHour) || 0))); + const current = new Date(Number(now) || Date.now()); + + // 今天切点:本地时区当日 07:00 + let anchor = new Date( + current.getFullYear(), + current.getMonth(), + current.getDate(), + normalizedHour, + 0, + 0, + 0 + ); + + // 未到今日切点:最新窗口尚未开始,从昨日切点起算 + if (current.getTime() < anchor.getTime()) { + anchor = new Date( + anchor.getFullYear(), + anchor.getMonth(), + anchor.getDate() - 1, + normalizedHour, + 0, + 0, + 0 + ); + } + + const windows = []; + for (let index = 0; index < normalizedCount; index += 1) { + // 最旧在前:dayOffset 从 -(count-1) 递增到 0 + const dayOffset = index - (normalizedCount - 1); + const start = new Date( + anchor.getFullYear(), + anchor.getMonth(), + anchor.getDate() + dayOffset, + normalizedHour, + 0, + 0, + 0 + ); + const end = new Date( + anchor.getFullYear(), + anchor.getMonth(), + anchor.getDate() + dayOffset + 1, + normalizedHour, + 0, + 0, + 0 + ); + windows.push({ + start: start.getTime(), + end: end.getTime(), + }); + } + + return windows; +} + +/** + * 按 PHP date() 风格的 token 格式化窗口开始日期(本地时区,无前导零)。 + * + * 支持的 token: + * Y=四位年;y=两位年;m=补零月;n=无前导零月;d=补零日;j=无前导零日; + * H=补零小时;i=补零分钟;s=补零秒。其余字符原样保留。 + * + * @param {Array<{start: number, end: number}>} windows 日窗口列表 + * @param {number} index 窗口下标 + * @param {string} [pattern='Y/n/j'] 日期格式模板(如 '2026/8/23') + * @return {string} 格式化后的日期字符串 + */ +function formatWindowStart(windows, index, pattern = 'Y/n/j') { + const windowItem = Array.isArray(windows) ? windows[index] : null; + if (!windowItem || !Number.isFinite(Number(windowItem.start))) { + return ''; + } + + const date = new Date(Number(windowItem.start)); + const tokens = { + Y: String(date.getFullYear()), + y: String(date.getFullYear()).slice(2), + m: pad2(date.getMonth() + 1), + n: String(date.getMonth() + 1), + d: pad2(date.getDate()), + j: String(date.getDate()), + H: pad2(date.getHours()), + i: pad2(date.getMinutes()), + s: pad2(date.getSeconds()), + }; + + return String(pattern || 'Y/n/j').replace(/[YymndjHis]/g, character => tokens[character]); +} + +/** + * 取时刻的本地 'HH:mm'(补零)。 + * @param {Date|number} date 日期对象或毫秒时间戳 + * @return {string} 'HH:mm' 格式字符串 + */ +function hhmmOf(date) { + const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now()); + return `${pad2(normalizedDate.getHours())}:${pad2(normalizedDate.getMinutes())}`; +} + +/** + * 取时刻的本地自然日('YYYY-MM-DD')。 + * @param {Date|number} date 日期对象或毫秒时间戳 + * @return {string} 'YYYY-MM-DD' 格式字符串 + */ +function scheduleDateOf(date) { + const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now()); + return `${normalizedDate.getFullYear()}-${pad2(normalizedDate.getMonth() + 1)}-${pad2(normalizedDate.getDate())}`; +} + +/** + * 从窗口参数对象解析 dayCount/cutoverHour,供查询器与元数据接口共用。 + * 口径与查询器保持一致:dayCount 缺省 7(<=0 视为 7),cutoverHour 缺省 7 且钳制到 0-23。 + * @param {Object} [params={}] 窗口参数(支持 dayCount/day_count、cutoverHour/cutover_hour) + * @return {{dayCount: number, cutoverHour: number}} 归一化窗口参数 + */ +function resolveWindowConfig(params = {}) { + const dayCount = Math.max(1, Math.floor(Number(params.dayCount || params.day_count || 7))); + const cutoverHour = Math.min(23, Math.max(0, Math.floor(Number(params.cutoverHour ?? params.cutover_hour ?? 7)))); + return { dayCount, cutoverHour }; +} + +module.exports = { + buildDayWindows, + formatWindowStart, + hhmmOf, + scheduleDateOf, + resolveWindowConfig, +}; diff --git a/app/lib/report/formatters.js b/app/lib/report/formatters.js new file mode 100644 index 0000000..4d1b61d --- /dev/null +++ b/app/lib/report/formatters.js @@ -0,0 +1,167 @@ +'use strict'; + +/** + * 报表单元格格式化器注册表(纯函数模块,无 ctx 依赖,可单测)。 + * + * 设计约定: + * 1. 所有格式化器首参为单元格原始值(value),其余参数为格式化参数; + * 2. 数值计算统一走「截断取整」(等价旧 PHP 的 intval 语义,向零取整); + * 3. 低库存补偿口径与旧 PHP《7日出入库数据》保持一致: + * 可用库存 < 20 且 7 日入库 < 20 时视为低库存,触发补偿与预警。 + */ + +/** + * 安全转数值:非有限数值一律按 0 处理。 + * @param {*} value 原始值 + * @return {number} 数值 + */ +function toFiniteNumber(value) { + const number = Number(value); + return Number.isFinite(number) ? number : 0; +} + +/** + * 截断取整(PHP intval 语义,向零取整)。 + * @param {*} value 原始值 + * @return {number} 整数 + */ +function integer(value) { + return Math.trunc(toFiniteNumber(value)); +} + +/** + * 零值占位:0 / '0' / null / undefined / '' 统一显示为 '-'。 + * 说明:'0' 一并转 '-',与 PHP empty('0') 为真的旧口径保持一致。 + * @param {*} value 原始值 + * @return {*} 非零原值或 '-' + */ +function zeroToDash(value) { + if (value === 0 || value === '0' || value === null || value === undefined || value === '') { + return '-'; + } + return value; +} + +/** + * 布尔转中文:真值 → '是',假值 → '否'。 + * 说明:''、0、'0'、null、undefined、false 均视为假,与 PHP 布尔语义对齐。 + * @param {*} flag 原始值 + * @return {string} '是' 或 '否' + */ +function yesNo(flag) { + const falsy = flag === false + || flag === null + || flag === undefined + || flag === '' + || flag === 0 + || flag === '0' + || String(flag).toLowerCase() === 'false'; + return falsy ? '否' : '是'; +} + +/** + * 7 日日均 ×10 取整(保留一位小数但避免浮点误差)。 + * 公式:int(total / days * 10),与旧 PHP intval($ck / 7 * 10) 一致。 + * @param {*} value 周期合计值 + * @param {*} days 天数 + * @return {number} 日均×10 的整数 + */ +function avgDaysPerWeek(value, days) { + const total = toFiniteNumber(value); + const dayCount = toFiniteNumber(days); + if (dayCount <= 0) { + return 0; + } + return Math.trunc((total / dayCount) * 10); +} + +/** + * 建议补货量(含低库存补偿): + * 基础值 int(ck_total / 7 * 10);仅当低库存(available < 20 且 rk_total < 20)时 + * 补偿到不低于 30(保证低库存货主获得最小补货建议)。 + * @param {*} ckTotal 7 日总出库 + * @param {*} available 可用库存 + * @param {*} rkTotal 7 日总入库 + * @return {number} 建议补货量 + */ +function suggestWithCompensate(ckTotal, available, rkTotal) { + const base = Math.trunc((toFiniteNumber(ckTotal) / 7) * 10); + const availableNumber = toFiniteNumber(available); + const rkNumber = toFiniteNumber(rkTotal); + if (availableNumber < 20 && rkNumber < 20) { + return Math.max(base, 30); + } + return base; +} + +/** + * 库存预警判定(布尔): + * 1. 按 7 日均出库 ×4 折算的周转阈值高于可用库存(int(ck/7*4) - available > 0); + * 2. 或处于低库存状态(available < 20 且 rk_total < 20)。 + * 展示时建议叠加 yesNo 格式化器转中文。 + * @param {*} ckTotal 7 日总出库 + * @param {*} available 可用库存 + * @param {*} rkTotal 7 日总入库 + * @return {boolean} 是否预警 + */ +function warnOf(ckTotal, available, rkTotal) { + const threshold = Math.trunc((toFiniteNumber(ckTotal) / 7) * 4); + return threshold - toFiniteNumber(available) > 0 + || (toFiniteNumber(available) < 20 && toFiniteNumber(rkTotal) < 20); +} + +/** + * 文本前缀工厂:返回一个给文本加前缀的格式化函数。 + * 典型用法:`'` 前缀防科学计数法(Excel 将长数字串强制按文本展示)。 + * @param {string} [prefix=''] 前缀 + * @return {Function} 格式化函数 (value) => `${prefix}${value}` + */ +function textPrefix(prefix = '') { + return value => `${String(prefix || '')}${value === null || value === undefined ? '' : String(value)}`; +} + +/** + * 格式化器注册表(配置驱动报表按名称引用)。 + * @type {Object} + */ +const FORMATTERS = Object.freeze({ + textPrefix: (value, prefix) => textPrefix(prefix)(value), + zeroToDash, + yesNo, + integer, + avgDaysPerWeek, + suggestWithCompensate, + warnOf, +}); + +/** + * 按名称应用格式化器。 + * @param {string} name 格式化器名称 + * @param {*} value 单元格原始值 + * @param {...*} args 格式化器额外参数 + * @return {*} 格式化结果 + * @throws {Error} 未知格式化器名称时抛出 + */ +function applyFormat(name, value, ...args) { + const formatterName = String(name || '').trim(); + if (!formatterName) { + return value; + } + const formatter = FORMATTERS[formatterName]; + if (typeof formatter !== 'function') { + throw new Error(`未知的报表格式化器: ${formatterName}`); + } + return formatter(value, ...args); +} + +module.exports = { + FORMATTERS, + applyFormat, + textPrefix, + zeroToDash, + yesNo, + integer, + avgDaysPerWeek, + suggestWithCompensate, + warnOf, +}; diff --git a/app/lib/report/notifyTemplate.js b/app/lib/report/notifyTemplate.js new file mode 100644 index 0000000..e3b0149 --- /dev/null +++ b/app/lib/report/notifyTemplate.js @@ -0,0 +1,101 @@ +'use strict'; + +/** + * 货主报表文本通知模板渲染器(纯函数模块,无 ctx 依赖,可单测)。 + * + * 标签白名单(其余 {xxx} 一律不替换,保存入口由 reportDelivery.savePlan 校验拦截): + * - {time} 发送时间,格式 YYYY-MM-DD HH:mm + * - {url} 报表文件下载链接(url 为空时替换为兜底文案) + * - {report_name} 报表名称 + * - {biz_date} 数据日期 YYYY-MM-DD + */ + +/** 模板标签白名单 */ +const ALLOWED_TAGS = Object.freeze([ 'time', 'url', 'report_name', 'biz_date' ]); + +/** + * url 为空时的兜底文案。 + * 理由:生成结果 url 可能因异步上传尚未就绪,以占位文案保证通知可达, + * 避免因链接缺失引发整链路失败重试风暴;实际链接可在投递记录中查看。 + */ +const EMPTY_URL_FALLBACK = '文件生成中,稍后可在投递记录中查看'; + +/** 模板标签匹配正则:{xxx} 占位 */ +const TAG_PATTERN = /\{([^{}]+)\}/g; + +/** + * 提取模板中出现过的全部标签名(按出现顺序,含重复项)。 + * @param {string} template 模板字符串 + * @return {Array} 标签名数组 + */ +function extractTagNames(template) { + const names = []; + const source = String(template || ''); + let match = TAG_PATTERN.exec(source); + while (match) { + names.push(String(match[1]).trim()); + match = TAG_PATTERN.exec(source); + } + return names; +} + +/** + * 校验模板标签是否全部位于白名单内(未知标签不替换、保存时拒绝)。 + * @param {string} template 模板字符串 + * @return {{valid: boolean, invalidTags: Array}} 校验结果(invalidTags 已去重) + */ +function validateNotifyTemplate(template) { + const names = extractTagNames(template); + const invalidSet = new Set(); + for (const name of names) { + if (!ALLOWED_TAGS.includes(name)) { + invalidSet.add(name); + } + } + return { valid: invalidSet.size === 0, invalidTags: [ ...invalidSet ] }; +} + +/** + * 渲染通知模板:仅替换白名单标签,未知标签原样保留(保存入口已校验拦截)。 + * @param {string} template 模板字符串 + * @param {Object} [context={}] 渲染上下文 + * @param {string} [context.time=''] 发送时间(YYYY-MM-DD HH:mm) + * @param {string} [context.url=''] 报表文件下载链接(空则替换为兜底文案) + * @param {string} [context.reportName=''] 报表名称 + * @param {string} [context.bizDate=''] 数据日期(YYYY-MM-DD) + * @return {string} 渲染后的通知文本 + */ +function renderNotifyTemplate(template, context = {}) { + const url = String((context && context.url) || '').trim() || EMPTY_URL_FALLBACK; + const replacements = { + time: String((context && context.time) || ''), + url, + report_name: String((context && context.reportName) || ''), + biz_date: String((context && context.bizDate) || ''), + }; + return String(template || '').replace(TAG_PATTERN, (raw, name) => { + const key = String(name).trim(); + return Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : raw; + }); +} + +/** + * 格式化发送时间为 YYYY-MM-DD HH:mm(服务器本地时区)。 + * @param {Date} [date=new Date()] 时刻 + * @return {string} 格式化后的时间字符串 + */ +function formatNotifyTime(date) { + const target = date instanceof Date ? date : new Date(); + const pad = value => String(value).padStart(2, '0'); + return `${target.getFullYear()}-${pad(target.getMonth() + 1)}-${pad(target.getDate())} ` + + `${pad(target.getHours())}:${pad(target.getMinutes())}`; +} + +module.exports = { + ALLOWED_TAGS, + EMPTY_URL_FALLBACK, + extractTagNames, + validateNotifyTemplate, + renderNotifyTemplate, + formatNotifyTime, +}; diff --git a/app/lib/report/render.js b/app/lib/report/render.js new file mode 100644 index 0000000..1b82da8 --- /dev/null +++ b/app/lib/report/render.js @@ -0,0 +1,233 @@ +'use strict'; + +const { applyFormat } = require('./formatters'); +const { formatWindowStart } = require('./day_window'); + +/** + * 报表渲染翻译层(纯函数模块,无 ctx 依赖,可单测)。 + * + * 输入:报表类型 type 的硬编码字段注册清单(fields,按勾选顺序)+ 查询器产出的数据 rows; + * 输出:适配 `app/service/systems/excel.js` 的 sheets 参数结构 + * ({ name, columns, rows, merges, styledRows, textColumns? })。 + * + * 约定(与 excel.js 的 buildExcelJsWorkbook 对齐): + * 1. 数据以 AOA(二维数组)形式输出,表头行内联在 rows 首位,columns 恒传空数组; + * 2. merges 统一输出 {s:{r,c}, e:{r,c}} 结构(excel.js 两套构建器均支持); + * 3. textColumns 输出 0 基列索引,由 excel.js 落地为文本单元格。 + * + * 列规则(全部由字段注册清单硬编码决定,无 sheet_config 自定义): + * 1. string 字段 → 静态列(header=label),asText=true 时加入 textColumns; + * 2. number 字段 → 静态列,统一 zeroToDash(0/''/null 显示 '-'); + * 3. boolean 字段 → 静态列,统一 yesNo(真→是,假→否); + * 4. array 字段 → 窗口展开列:per=窗口数,pair=children keys,表头第 1 行按窗口 + * 输出 '{date}' 日期(Y/n/j 无前导零)并在每窗口 pair.length>1 时横向合并, + * 表头第 2 行按 children label 填充;子字段为 number 时单元格统一 zeroToDash; + * 5. 存在展开列时启用两行表头,其余列表头纵向合并(如 A1:A2)。 + */ + +/** + * 判断字段是否为普通对象。 + * @param {*} field 待判断字段 + * @return {boolean} 是否普通对象 + */ +function isPlainObject(field) { + return Boolean(field) && typeof field === 'object' && !Array.isArray(field); +} + +/** + * 规范化字段注册清单:仅保留含 key 的对象,key 统一为字符串。 + * @param {Array} fields 字段清单(注册表 fields,按勾选顺序) + * @return {Array} 规范化字段清单 + */ +function normalizeFields(fields) { + if (!Array.isArray(fields)) { + return []; + } + return fields + .filter(field => isPlainObject(field) && String(field.key || '').trim()) + .map(field => ({ ...field, key: String(field.key).trim() })); +} + +/** + * 按类型字段清单构建列计划(含窗口展开与表头合并)。 + * @param {Object} [options={}] 构建选项 + * @param {Array} [options.fields=[]] 字段注册清单(按勾选顺序) + * @param {Array} [options.windows=[]] 日窗口列表(展开列 per 取窗口数) + * @return {{columns: Array, headerRowCount: number, generatedMerges: Array}} 列计划 + */ +function buildColumnPlan({ fields = [], windows = [] } = {}) { + const safeFields = normalizeFields(fields); + const safeWindows = Array.isArray(windows) ? windows : []; + const expandPer = Math.max(1, safeWindows.length || 7); + + const columns = []; + const generatedMerges = []; + let expandStartColumn = -1; + + for (const field of safeFields) { + if (field.type === 'array') { + const children = Array.isArray(field.children) ? field.children : []; + const pair = children.length > 0 ? children : [{ key: 'value', label: '值', type: 'string' }]; + expandStartColumn = columns.length; + for (let windowIndex = 0; windowIndex < expandPer; windowIndex += 1) { + for (let pairIndex = 0; pairIndex < pair.length; pairIndex += 1) { + columns.push({ + type: 'expand', + windowIndex, + pairIndex, + pair: pair[pairIndex] && isPlainObject(pair[pairIndex]) ? pair[pairIndex] : {}, + headerRow1Template: '{date}', + headerRow2List: pair.map(child => String((child && child.label) || '')), + }); + } + if (pair.length > 1) { + // 每窗口多列表头横向合并(如 D1:E1 … P1:Q1) + const groupStart = expandStartColumn + windowIndex * pair.length; + generatedMerges.push({ + s: { r: 0, c: groupStart }, + e: { r: 0, c: groupStart + pair.length - 1 }, + }); + } + } + continue; + } + columns.push({ + type: field.type === 'array' ? 'static' : (field.type || 'string'), + header: String(field.label || field.key || ''), + field: field.key, + asText: field.asText === true, + }); + } + + const hasExpandColumn = columns.some(column => column.type === 'expand'); + const headerRowCount = hasExpandColumn ? 2 : 1; + + // 两行表头下,非展开列按列纵向合并(A1:A2 等) + if (headerRowCount === 2) { + columns.forEach((column, columnIndex) => { + if (column.type !== 'expand') { + generatedMerges.push({ + s: { r: 0, c: columnIndex }, + e: { r: 1, c: columnIndex }, + }); + } + }); + } + + return { + columns, + headerRowCount, + generatedMerges, + }; +} + +/** + * 构建表头第 1 行(展开列按窗口开始日期输出 'Y/n/j' 无前导零)。 + * @param {Array} columns 列计划 + * @param {Array} windows 日窗口列表 + * @return {Array} 表头第 1 行 + */ +function buildHeaderRow1(columns, windows = []) { + return columns.map(column => { + if (column.type === 'expand') { + return formatWindowStart(windows, column.windowIndex, 'Y/n/j'); + } + return column.header; + }); +} + +/** + * 构建表头第 2 行(单行表头模式下返回 null;展开列按 pair label 填充)。 + * @param {Array} columns 列计划 + * @param {number} headerRowCount 表头行数 + * @return {Array|null} 表头第 2 行 + */ +function buildHeaderRow2(columns, headerRowCount) { + if (headerRowCount !== 2) { + return null; + } + return columns.map(column => { + if (column.type === 'expand') { + const list = column.headerRow2List; + return list.length > 0 ? list[column.pairIndex % list.length] || '' : ''; + } + return ''; + }); +} + +/** + * 渲染单个单元格(按列类型与字段类型硬编码格式化口径)。 + * @param {Object} column 列计划 + * @param {Object} row 数据行 + * @return {*} 单元格值 + */ +function renderCell(column, row = {}) { + if (column.type === 'expand') { + const daily = Array.isArray(row.daily) ? row.daily : []; + const day = daily[column.windowIndex]; + const value = day && typeof day === 'object' ? day[column.pair.key] : 0; + return applyFormat(column.pair.type === 'number' ? 'zeroToDash' : '', value); + } + + const value = row[column.field]; + if (column.type === 'boolean') { + return applyFormat('yesNo', value); + } + if (column.type === 'number') { + return applyFormat('zeroToDash', value); + } + return value; +} + +/** + * 按类型字段注册清单渲染 sheet(配置极简:无 sheet_config 自定义列/合并/样式)。 + * + * @param {Object} [options={}] 渲染选项 + * @param {string} [options.type=''] 报表类型(查询器注册 key,仅透传不参与渲染口径) + * @param {string} [options.title='报表'] sheet 名称(报表标题) + * @param {Array} [options.fields=[]] 字段注册清单(按勾选顺序) + * @param {Array} [options.rows=[]] 查询器产出的数据行 + * @param {Array} [options.windows=[]] 日窗口列表 + * @return {Object} excel.js sheet 参数 + * ({name, columns, rows, merges, styledRows},存在 asText 列时附带 textColumns) + */ +function renderSheetByType({ type = '', title = '报表', fields = [], rows = [], windows = [] } = {}) { + void type; + const plan = buildColumnPlan({ fields, windows }); + const safeRows = Array.isArray(rows) ? rows : []; + + const headerRow1 = buildHeaderRow1(plan.columns, windows); + const headerRow2 = buildHeaderRow2(plan.columns, plan.headerRowCount); + + const aoaRows = [ headerRow1 ]; + if (headerRow2) { + aoaRows.push(headerRow2); + } + for (const row of safeRows) { + aoaRows.push(plan.columns.map(column => renderCell(column, row))); + } + + // asText 列收集为 0 基列索引,交由 excel.js 落地文本单元格(无 asText 时不输出) + const textColumns = plan.columns + .map((column, columnIndex) => (column.asText ? columnIndex : -1)) + .filter(columnIndex => columnIndex >= 0); + + const result = { + name: String(title || '报表'), + columns: [], + rows: aoaRows, + merges: plan.generatedMerges, + styledRows: [], + }; + + if (textColumns.length > 0) { + result.textColumns = textColumns; + } + + return result; +} + +module.exports = { + renderSheetByType, + buildColumnPlan, +}; diff --git a/app/lib/shop_soft_delete.js b/app/lib/shop_soft_delete.js new file mode 100644 index 0000000..9112b08 --- /dev/null +++ b/app/lib/shop_soft_delete.js @@ -0,0 +1,53 @@ +'use strict'; + +const DELETED_SHOP_NAME_PREFIX = 'DELETED_SHOP_'; + +/** + * 判断店铺名是否为软删除墓碑名。 + * + * @param {*} shopName 店铺名称 + * @return {boolean} 是否为已软删除店铺 + */ +function isDeletedShopName(shopName) { + return String(shopName || '').trim().startsWith(DELETED_SHOP_NAME_PREFIX); +} + +/** + * 判断店铺记录是否为软删除状态。 + * + * @param {Object} shop 店铺记录或模型实例 + * @return {boolean} 是否已软删除 + */ +function isSoftDeletedShop(shop) { + if (!shop || typeof shop !== 'object') { + return false; + } + + const plainShop = typeof shop.get === 'function' + ? shop.get({ plain: true }) + : shop; + + return isDeletedShopName(plainShop && plainShop.shop_name); +} + +/** + * 构建排除软删除店铺的 Sequelize where 条件。 + * + * @param {import('egg').Application} app Egg 应用实例 + * @param {string} [fieldName='shop_name'] 店铺名字段名 + * @return {Object} Sequelize where 条件 + */ +function buildNotDeletedShopWhere(app, fieldName = 'shop_name') { + return { + [fieldName]: { + [app.Sequelize.Op.notLike]: `${DELETED_SHOP_NAME_PREFIX}%`, + }, + }; +} + +module.exports = { + DELETED_SHOP_NAME_PREFIX, + isDeletedShopName, + isSoftDeletedShop, + buildNotDeletedShopWhere, +}; diff --git a/app/lib/stop_current_egg.js b/app/lib/stop_current_egg.js new file mode 100644 index 0000000..34f4216 --- /dev/null +++ b/app/lib/stop_current_egg.js @@ -0,0 +1,147 @@ +'use strict'; + +const { execFileSync } = require('node:child_process'); + +const isWin = process.platform === 'win32'; +const appRoot = process.cwd(); + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +function listNodeProcesses() { + if (isWin) { + try { + const output = execFileSync('wmic', [ 'Path', 'win32_process', 'Where', "Name = 'node.exe'", 'Get', 'CommandLine,ProcessId' ], { + encoding: 'utf8', + stdio: [ 'ignore', 'pipe', 'pipe' ], + }); + + return output + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean) + .map(line => { + const match = line.match(/^(.*)\s+(\d+)$/); + if (!match) { + return null; + } + return { + pid: Number(match[2]), + cmd: match[1], + }; + }) + .filter(Boolean); + } catch (error) { + if (error.code !== 'ENOENT') { + throw error; + } + + const output = execFileSync('powershell', [ + '-NoProfile', + '-Command', + "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Select-Object ProcessId, CommandLine | ConvertTo-Json -Compress", + ], { + encoding: 'utf8', + stdio: [ 'ignore', 'pipe', 'pipe' ], + }).trim(); + + if (!output) { + return []; + } + + const parsed = JSON.parse(output); + const items = Array.isArray(parsed) ? parsed : [ parsed ]; + return items + .map(item => ({ + pid: Number(item.ProcessId), + cmd: String(item.CommandLine || ''), + })) + .filter(item => item.pid && item.cmd); + } + } + + const output = execFileSync('ps', [ '-eo', 'pid=,args=' ], { + encoding: 'utf8', + stdio: [ 'ignore', 'pipe', 'pipe' ], + }); + + return output + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean) + .map(line => { + const match = line.match(/^(\d+)\s+(.*)$/); + if (!match) { + return null; + } + return { + pid: Number(match[1]), + cmd: match[2], + }; + }) + .filter(Boolean); +} + +function isMasterProcess(cmd) { + return cmd.includes('start-cluster'); +} + +function isWorkerProcess(cmd) { + return cmd.includes('egg-cluster/lib/app_worker.js') + || cmd.includes('egg-cluster/lib/agent_worker.js') + || cmd.includes('egg-cluster\\lib\\app_worker.js') + || cmd.includes('egg-cluster\\lib\\agent_worker.js'); +} + +function matchesCurrentApp(processInfo) { + if (!processInfo || !processInfo.cmd || !processInfo.pid) { + return false; + } + + if (processInfo.pid === process.pid) { + return false; + } + + return processInfo.cmd.includes(appRoot) && (isMasterProcess(processInfo.cmd) || isWorkerProcess(processInfo.cmd)); +} + +function killPids(pids, signal) { + for (const pid of pids) { + try { + process.kill(pid, signal); + } catch (error) { + if (error.code !== 'ESRCH') { + throw error; + } + } + } +} + +async function main() { + const processList = listNodeProcesses().filter(matchesCurrentApp); + const masterPids = processList.filter(item => isMasterProcess(item.cmd)).map(item => item.pid); + + if (masterPids.length > 0) { + console.log(`stopping current egg masters: ${masterPids.join(', ')}`); + killPids(masterPids, 'SIGTERM'); + await sleep(5000); + } else { + console.log('no current egg master process found'); + } + + const remainingWorkers = listNodeProcesses() + .filter(matchesCurrentApp) + .filter(item => isWorkerProcess(item.cmd)) + .map(item => item.pid); + + if (remainingWorkers.length > 0) { + console.log(`killing remaining current egg workers: ${remainingWorkers.join(', ')}`); + killPids(remainingWorkers, 'SIGKILL'); + } +} + +main().catch(error => { + console.error(error.message || error); + process.exitCode = 1; +}); 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/lib/wave_strategy_quick_scan_runner.js b/app/lib/wave_strategy_quick_scan_runner.js new file mode 100644 index 0000000..872078c --- /dev/null +++ b/app/lib/wave_strategy_quick_scan_runner.js @@ -0,0 +1,195 @@ +'use strict'; + +/** + * 执行波次策略快速扫描通用流程。 + * + * @param {Object} [options={}] 扫描参数。 + * @param {Array} [options.orders] 订单数组。 + * @param {Array} [options.strategyList] 策略数组。 + * @param {Function} [options.getStructureKey] 获取订单结构 key。 + * @param {Function} [options.getExpressKey] 获取订单快递 key。 + * @param {Function} [options.isOrderMatched] 判断订单是否命中策略。 + * @param {Function} [options.getMatchedStrategyIds] 获取订单命中策略ID数组。 + * @param {Function} [options.onProgress] 异步进度回调。 + * @return {Promise<{totalOrderCount:number, processedOrderCount:number, matchedOrderIds:Array, unmatchedOrderIds:Array, matchedStrategyIdsByOrder:Object}>} 扫描结果。 + */ +async function runWaveStrategyQuickScanRunner(options = {}) { + const normalizedOptions = options && typeof options === 'object' ? options : {}; + const normalizedOrders = Array.isArray(normalizedOptions.orders) ? normalizedOptions.orders : []; + const strategyList = Array.isArray(normalizedOptions.strategyList) ? normalizedOptions.strategyList : []; + const getStructureKey = typeof normalizedOptions.getStructureKey === 'function' + ? normalizedOptions.getStructureKey + : () => ''; + const getExpressKey = typeof normalizedOptions.getExpressKey === 'function' + ? normalizedOptions.getExpressKey + : () => ''; + const isOrderMatched = typeof normalizedOptions.isOrderMatched === 'function' + ? normalizedOptions.isOrderMatched + : () => false; + const getMatchedStrategyIds = typeof normalizedOptions.getMatchedStrategyIds === 'function' + ? normalizedOptions.getMatchedStrategyIds + : null; + const onProgress = typeof normalizedOptions.onProgress === 'function' + ? normalizedOptions.onProgress + : null; + + const structureStoreSetMap = new Map(); + const structureOwnerCountMap = new Map(); + const structureExpressCountMap = new Map(); + + for (const order of normalizedOrders) { + const structureKey = String(getStructureKey(order) || '').trim(); + if (!structureKey) { + continue; + } + + const storeId = String(order && order.store_id || '').trim().toLowerCase(); + if (!structureStoreSetMap.has(structureKey)) { + structureStoreSetMap.set(structureKey, new Set()); + } + if (!structureOwnerCountMap.has(structureKey)) { + structureOwnerCountMap.set(structureKey, new Map()); + } + if (!structureExpressCountMap.has(structureKey)) { + structureExpressCountMap.set(structureKey, new Map()); + } + if (storeId) { + structureStoreSetMap.get(structureKey).add(storeId); + const ownerCountMap = structureOwnerCountMap.get(structureKey); + ownerCountMap.set(storeId, Number(ownerCountMap.get(storeId) || 0) + 1); + } + + const expressKey = String(getExpressKey(order) || '').trim().toLowerCase(); + if (expressKey) { + const expressCountMap = structureExpressCountMap.get(structureKey); + expressCountMap.set(expressKey, Number(expressCountMap.get(expressKey) || 0) + 1); + } + } + + const structurePrimaryOwnerMap = new Map(); + for (const [ structureKey, ownerCountMap ] of structureOwnerCountMap.entries()) { + if (!(ownerCountMap instanceof Map) || ownerCountMap.size === 0) { + continue; + } + + let primaryOwner = ''; + let maxCount = 0; + for (const [ storeId, count ] of ownerCountMap.entries()) { + const normalizedStoreId = String(storeId || '').trim().toLowerCase(); + const normalizedCount = Number(count || 0); + if (!normalizedStoreId || normalizedCount <= 0) { + continue; + } + + if ( + normalizedCount > maxCount + || (normalizedCount === maxCount && (!primaryOwner || normalizedStoreId < primaryOwner)) + ) { + maxCount = normalizedCount; + primaryOwner = normalizedStoreId; + } + } + + if (primaryOwner) { + structurePrimaryOwnerMap.set(structureKey, primaryOwner); + } + } + + const structurePrimaryExpressMap = new Map(); + for (const [ structureKey, expressCountMap ] of structureExpressCountMap.entries()) { + if (!(expressCountMap instanceof Map) || expressCountMap.size === 0) { + continue; + } + + let primaryExpressKey = ''; + let maxCount = 0; + for (const [ expressKey, count ] of expressCountMap.entries()) { + const normalizedExpressKey = String(expressKey || '').trim().toLowerCase(); + const normalizedCount = Number(count || 0); + if (!normalizedExpressKey || normalizedCount <= 0) { + continue; + } + + if ( + normalizedCount > maxCount + || (normalizedCount === maxCount && (!primaryExpressKey || normalizedExpressKey < primaryExpressKey)) + ) { + maxCount = normalizedCount; + primaryExpressKey = normalizedExpressKey; + } + } + + if (primaryExpressKey) { + structurePrimaryExpressMap.set(structureKey, primaryExpressKey); + } + } + + const matchedOrderIds = []; + const unmatchedOrderIds = []; + const matchedStrategyIdsByOrder = {}; + const totalOrderCount = normalizedOrders.length; + let processedOrderCount = 0; + + for (const order of normalizedOrders) { + const context = { + structureStoreSetMap, + structureOwnerCountMap, + structurePrimaryOwnerMap, + structureExpressCountMap, + structurePrimaryExpressMap, + }; + const orderId = Number(order && order.id || 0); + let matched = false; + + if (getMatchedStrategyIds) { + const rawMatchedStrategyIds = getMatchedStrategyIds(order, strategyList, context); + const matchedStrategyIds = [ ...new Set((Array.isArray(rawMatchedStrategyIds) ? rawMatchedStrategyIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + matched = matchedStrategyIds.length > 0; + + if (Number.isInteger(orderId) && orderId > 0) { + matchedStrategyIdsByOrder[orderId] = matchedStrategyIds; + } + } else { + matched = Boolean(isOrderMatched(order, strategyList, context)); + } + + if (Number.isInteger(orderId) && orderId > 0) { + if (matched) { + matchedOrderIds.push(orderId); + } else { + unmatchedOrderIds.push(orderId); + } + } + + processedOrderCount += 1; + if (onProgress && (processedOrderCount % 200 === 0 || processedOrderCount === totalOrderCount)) { + await onProgress({ + totalOrderCount, + processedOrderCount, + matchedOrderCount: matchedOrderIds.length, + unmatchedOrderCount: unmatchedOrderIds.length, + }); + } + } + + if (onProgress && totalOrderCount === 0) { + await onProgress({ + totalOrderCount, + processedOrderCount, + matchedOrderCount: 0, + unmatchedOrderCount: 0, + }); + } + + return { + totalOrderCount, + processedOrderCount, + matchedOrderIds, + unmatchedOrderIds, + matchedStrategyIdsByOrder, + }; +} + +module.exports = runWaveStrategyQuickScanRunner; diff --git a/app/lib/waybill_code.js b/app/lib/waybill_code.js new file mode 100644 index 0000000..d5dee3c --- /dev/null +++ b/app/lib/waybill_code.js @@ -0,0 +1,35 @@ +'use strict'; + +/** + * 运单号公共工具。 + * 统一处理一单多件分段单号(如 JDX057941864338-1-1-)的包裹序号后缀剥离与 like 通配符转义, + * 保证「剥离后缀后主体运单号必须等值匹配」的业务规则在各扫描入口保持一致。 + */ + +/** + * 剥离运单号尾部的包裹序号段(一单多件分段格式:-包裹序号-总件数[-])。 + * 例如 'JDX057941864338-1-1-' → 'JDX057941864338'; + * 'JDX057941864338' 无分段后缀时原样返回。 + * + * @param {string} waybillCode 运单号 + * @return {string} 剥离分段后缀后的主体运单号 + */ +function stripWaybillSegmentSuffix(waybillCode) { + return String(waybillCode || '').trim().replace(/(?:-\d+){2,}-?$/, ''); +} + +/** + * 转义 like 匹配中的通配符(% _ \),避免用户输入中的特殊字符扩大匹配范围。 + * 用于「主体运单号 + -%」前缀匹配场景,确保主体部分被等值比较。 + * + * @param {string} value 待转义的字符串 + * @return {string} 转义后的字符串 + */ +function escapeLikeWildcards(value) { + return String(value || '').replace(/[%_\\]/g, m => `\\${m}`); +} + +module.exports = { + stripWaybillSegmentSuffix, + escapeLikeWildcards, +}; diff --git a/app/lib/wechat_open_client.js b/app/lib/wechat_open_client.js new file mode 100644 index 0000000..710564d --- /dev/null +++ b/app/lib/wechat_open_client.js @@ -0,0 +1,724 @@ +'use strict'; + +/** + * 微信开放平台第三方平台 API 客户端。 + * 封装组件级接口调用与 token 管理(Redis 缓存,Key 与参考实现一致): + * - component_access_token:调用授权方接口的组件凭证(约 2 小时)。 + * - App:{appid}:authorization_code:授权码(authorized 事件推送后暂存)。 + * - App:{appid}:authorizer_refresh_token:授权方刷新令牌(长期)。 + * - App:{appid}:AuthorizerAccessToken:授权方接口调用凭证(约 2 小时)。 + * + * 配置读取 app.config.wechatOpen: + * - component_appid / component_secret / token / encoding_aes_key / api_base + */ + +const DEFAULT_API_BASE = 'https://api.weixin.qq.com'; + +/** 缓存预留提前量(秒):token 在过期前提前失效,避免临界调用失败。 */ +const EXPIRE_MARGIN = 300; + +class WechatOpenClient { + /** + * @param {object} ctx Egg 上下文。 + */ + constructor(ctx) { + this.ctx = ctx; + this.app = ctx.app; + this.config = (this.app && this.app.config && this.app.config.wechatOpen) || {}; + } + + /** + * 获取 Redis 客户端(cache 库),不可用时返回 null。 + * @return {object|null} ioredis 客户端。 + */ + redis() { + return this.app && this.app.redis && typeof this.app.redis.get === 'function' + ? this.app.redis.get('cache') + : null; + } + + /** + * 读取缓存。 + * @param {string} key Redis key。 + * @return {Promise} 缓存值。 + */ + async cacheGet(key) { + const redis = this.redis(); + if (!redis) return null; + return redis.get(key); + } + + /** + * 写入缓存。 + * @param {string} key Redis key。 + * @param {string} value 值。 + * @param {number} ttl 过期秒数。 + * @return {Promise} + */ + async cacheSet(key, value, ttl) { + const redis = this.redis(); + if (!redis) return; + await redis.set(key, value, 'EX', ttl); + } + + /** + * 删除缓存。 + * @param {...string} keys Redis keys。 + * @return {Promise} + */ + async cacheDel(...keys) { + const redis = this.redis(); + if (!redis || keys.length === 0) return; + await redis.del(...keys); + } + + /** + * 发起微信 API POST 请求(JSON)。 + * @param {string} path API 路径(不含 base)。 + * @param {object} body 请求体。 + * @param {string} [token] component_access_token(作为 URL query 拼接)。 + * @return {Promise} 响应 JSON。 + */ + async apiPost(path, body, token) { + const base = this.config.api_base || DEFAULT_API_BASE; + let url = base.replace(/\/$/, '') + path; + if (token) { + url += `${url.includes('?') ? '&' : '?'}component_access_token=${encodeURIComponent(token)}`; + } + const response = await this.ctx.curl(url, { + method: 'POST', + dataType: 'json', + timeout: 30000, + headers: { 'Content-Type': 'application/json' }, + data: body, + }); + return response && response.data !== undefined ? response.data : response; + } + + /** + * 携带 component_access_token 发起 POST 请求;遇 40001(invalid credential,token 被别处刷新顶掉) + * 时自动清除缓存 token、重取后重试一次。 + * + * @param {string} path API 路径(不含 base)。 + * @param {object} body 请求体。 + * @return {Promise} 响应 JSON(必要时重试后)。 + */ + async apiPostWithComponentToken(path, body) { + let result = await this.apiPost(path, body, await this.getComponentAccessToken()); + if (result && Number(result.errcode) === 40001) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn(`[wechatOpen] component_access_token 失效(40001),清除缓存重试: ${path}`); + } + await this.cacheDel('component_access_token'); + result = await this.apiPost(path, body, await this.getComponentAccessToken()); + } + return result; + } + + /** + * 保存 ComponentVerifyTicket(component_verify_ticket 事件推送后调用)。 + * @param {string} ticket 推送的 Ticket。 + * @return {Promise} + */ + async saveComponentVerifyTicket(ticket) { + // 微信每 10 分钟推送一次,ticket 有效期 12 小时。 + // 缓存 12 小时:异常未及时收到推送时,继续用上一次可用 ticket 换取 component_access_token(官方建议)。 + await this.cacheSet('ComponentVerifyTicket', ticket, 12 * 3600); + } + + /** + * 获取组件接口调用凭证 component_access_token(缓存优先)。 + * @return {Promise} component_access_token。 + */ + async getComponentAccessToken() { + const cached = await this.cacheGet('component_access_token'); + if (cached) return cached; + + const ticket = await this.cacheGet('ComponentVerifyTicket'); + if (!ticket) { + throw new Error('ComponentVerifyTicket 不存在,请等待微信推送后重试'); + } + + const result = await this.apiPost('/cgi-bin/component/api_component_token', { + component_appid: this.config.component_appid, + component_appsecret: this.config.component_secret, + component_verify_ticket: ticket, + }); + + if (result && result.component_access_token) { + const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN; + await this.cacheSet('component_access_token', result.component_access_token, Math.max(ttl, 60)); + return result.component_access_token; + } + throw new Error(`获取 component_access_token 失败: ${JSON.stringify(result)}`); + } + + /** + * 保存授权码(authorized/updateauthorized 事件推送后调用)。 + * @param {string} authorizerAppid 授权方小程序 AppID。 + * @param {string} authorizationCode 授权码。 + * @return {Promise} + */ + async saveAuthorizationCode(authorizerAppid, authorizationCode) { + // 授权码有效期 1 小时 + await this.cacheSet(`App:${authorizerAppid}:authorization_code`, authorizationCode, 3600); + } + + /** + * 使用授权码换取授权方令牌(api_query_auth)。 + * @param {string} authorizationCode 授权码。 + * @return {Promise} authorization_info(含 authorizer_refresh_token/ + * authorizer_access_token/expires_in/func_info 等)。 + */ + async queryAuth(authorizationCode) { + const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_query_auth', { + component_appid: this.config.component_appid, + authorization_code: authorizationCode, + }); + if (result && result.authorization_info) { + return result.authorization_info; + } + throw new Error(`获取 authorizer_refresh_token 失败: ${JSON.stringify(result)}`); + } + + /** + * 获取/刷新授权方接口调用凭证 authorizer_access_token(缓存优先)。 + * @param {string} appid 授权方小程序 AppID。 + * @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取)。 + * @return {Promise} { authorizerAccessToken, authorizerRefreshToken }。 + */ + async getAuthorizerAccessToken(appid, refreshToken) { + const tokenKey = `App:${appid}:AuthorizerAccessToken`; + const cached = await this.cacheGet(tokenKey); + if (cached) { + return { authorizerAccessToken: cached, authorizerRefreshToken: refreshToken || null }; + } + + let token = refreshToken || (await this.cacheGet(`App:${appid}:authorizer_refresh_token`)); + if (!token) { + throw new Error(`App:${appid} 的 authorizer_refresh_token 不存在`); + } + + const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_authorizer_token', { + component_appid: this.config.component_appid, + authorizer_appid: appid, + authorizer_refresh_token: token, + }); + + if (result && result.authorizer_access_token) { + const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN; + await this.cacheSet(tokenKey, result.authorizer_access_token, Math.max(ttl, 60)); + if (result.authorizer_refresh_token) { + token = result.authorizer_refresh_token; + await this.cacheSet(`App:${appid}:authorizer_refresh_token`, token, 30 * 24 * 3600); + } + return { authorizerAccessToken: result.authorizer_access_token, authorizerRefreshToken: token }; + } + throw new Error(`获取 authorizer_access_token 失败: ${JSON.stringify(result)}`); + } + + /** + * 获取授权方基本信息(api_get_authorizer_info:昵称/头像/原始ID)。 + * @param {string} appid 授权方小程序 AppID。 + * @return {Promise} authorizer_info。 + */ + async getAuthorizerInfo(appid) { + const detail = await this.getAuthorizerDetail(appid); + if (detail && detail.authorizer_info) { + return detail.authorizer_info; + } + throw new Error(`获取授权方信息失败: ${JSON.stringify(detail)}`); + } + + /** + * 获取授权账号详情(api_get_authorizer_info 完整返回:authorizer_info + authorization_info)。 + * @param {string} appid 授权方小程序 AppID。 + * @return {Promise} { authorizer_info, authorization_info }。 + */ + async getAuthorizerDetail(appid) { + const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_get_authorizer_info', { + component_appid: this.config.component_appid, + authorizer_appid: appid, + }); + if (result && (result.authorizer_info || result.authorization_info)) { + return result; + } + throw new Error(`获取授权账号详情失败: ${JSON.stringify(result)}`); + } + + /** + * 创建预授权码(用于生成授权链接)。 + * @return {Promise} pre_auth_code。 + */ + async createPreAuthCode() { + const cached = await this.cacheGet('preauthcode'); + if (cached) return cached; + + const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_create_preauthcode', { + component_appid: this.config.component_appid, + }); + if (result && result.pre_auth_code) { + await this.cacheSet('preauthcode', result.pre_auth_code, result.expires_in || 1800); + return result.pre_auth_code; + } + throw new Error(`创建预授权码失败: ${JSON.stringify(result)}`); + } + + /** + * 查询小程序认证进度(POST wxa/sec/queryauth,使用 authorizer_access_token 代商家调用,权限集 18)。 + * + * @param {string} appid 小程序 AppID。 + * @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取,Redis 丢失可用 DB 值兜底)。 + * @param {string} taskid 认证任务 id(发起认证接口返回)。 + * @return {Promise} 微信原始响应(errcode/errmsg/task_status/apply_status/orderid/auth_url 等)。 + */ + async queryMiniProgramAuth(appid, refreshToken, taskid) { + const request = async () => { + const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); + const base = this.config.api_base || DEFAULT_API_BASE; + const url = `${base.replace(/\/$/, '')}/wxa/sec/queryauth` + + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; + const response = await this.ctx.curl(url, { + method: 'POST', + dataType: 'json', + timeout: 30000, + headers: { 'Content-Type': 'application/json' }, + data: { taskid }, + }); + return response && response.data !== undefined ? response.data : response; + }; + + let result = await request(); + // authorizer_access_token 失效(40001/40014)时清缓存重试一次 + if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn(`[wechatOpen] wxa/sec/queryauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); + } + await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); + result = await request(); + } + return result; + } + + /** + * 发起小程序认证(POST wxa/sec/wxaauth,使用 authorizer_access_token 代商家调用,权限集 18)。 + * + * ⚠ 微信已下线旧接口 /wxa/sec/wxaapi/wxaauth(调用返回 40066 invalid url); + * 现行接口路径为 /wxa/sec/wxaauth,请求体为 { auth_data: {...} }(由业务层组装)。 + * + * @param {string} appid 小程序 AppID。 + * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 + * @param {object} body 认证请求体({ auth_data: {...} },字段见业务层白名单)。 + * @return {Promise} 微信原始响应(errcode/errmsg/taskid/auth_url)。 + */ + async wxaauth(appid, refreshToken, body) { + const request = async () => { + const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); + const base = this.config.api_base || DEFAULT_API_BASE; + const url = `${base.replace(/\/$/, '')}/wxa/sec/wxaauth` + + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; + const response = await this.ctx.curl(url, { + method: 'POST', + dataType: 'json', + timeout: 60000, + headers: { 'Content-Type': 'application/json' }, + data: body, + }); + return response && response.data !== undefined ? response.data : response; + }; + + let result = await request(); + // authorizer_access_token 失效(40001/40014)时清缓存重试一次 + if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn(`[wechatOpen] wxa/sec/wxaauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); + } + await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); + result = await request(); + } + return result; + } + + /** + * 上传认证材料图片到微信换取 mediaid(POST wxa/sec/uploadauthmaterial, + * authorizer_access_token 代商家调用,权限集 18)。 + * + * ⚠ 微信已下线旧接口 /wxa/sec/wxaapi/uploadmedia;现行接口为 /wxa/sec/uploadauthmaterial, + * 仅 media 一个 multipart 字段(图片 ≤2M,PNG/JPEG/JPG/GIF),成功返回 mediaid + * (本方法归一化为 media_id 供上层使用)。 + * + * @param {string} appid 小程序 AppID。 + * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 + * @param {Buffer} buffer 图片内容。 + * @param {string} filename 文件名(含扩展名,如 idcard.jpg)。 + * @return {Promise} 微信原始响应(errcode/errmsg/media_id/mediaid)。 + */ + async uploadAuthMedia(appid, refreshToken, buffer, filename) { + const fs = require('node:fs'); + const os = require('node:os'); + const path = require('node:path'); + + const tmpFile = path.join( + os.tmpdir(), + `wxauth-${Date.now()}-${Math.random().toString(36).slice(2, 10)}-${path.basename(filename || 'image.jpg')}` + ); + await fs.promises.writeFile(tmpFile, buffer); + + const request = async () => { + const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); + const base = this.config.api_base || DEFAULT_API_BASE; + const url = `${base.replace(/\/$/, '')}/wxa/sec/uploadauthmaterial` + + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; + const response = await this.ctx.curl(url, { + method: 'POST', + dataType: 'json', + timeout: 60000, + files: { media: tmpFile }, + }); + return response && response.data !== undefined ? response.data : response; + }; + + try { + let result = await request(); + // authorizer_access_token 失效(40001/40014)时清缓存重试一次 + if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn(`[wechatOpen] wxa/sec/uploadauthmaterial token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); + } + await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); + result = await request(); + } + // 现行接口成功返回字段为 mediaid,归一化为 media_id 供上层使用 + if (result && Number(result.errcode) === 0 && !result.media_id && result.mediaid) { + result = { ...result, media_id: result.mediaid }; + } + return result; + } finally { + await fs.promises.unlink(tmpFile).catch(() => {}); + } + } + + /** + * 获取小程序模板列表(wxa/gettemplatelist,仅支持 component_access_token,GET 请求)。 + * + * @param {number} [templateType] 0=普通模板、1=标准模板,不传返回全部。 + * @return {Promise} 微信原始响应(errcode/errmsg/template_list)。 + */ + async getTemplateList(templateType) { + const request = async () => { + const componentAccessToken = await this.getComponentAccessToken(); + const base = this.config.api_base || DEFAULT_API_BASE; + const url = `${base.replace(/\/$/, '')}/wxa/gettemplatelist`; + const response = await this.ctx.curl(url, { + method: 'GET', + dataType: 'json', + timeout: 30000, + data: { + access_token: componentAccessToken, + ...(templateType !== undefined && templateType !== null ? { template_type: templateType } : {}), + }, + }); + return response && response.data !== undefined ? response.data : response; + }; + + let result = await request(); + if (result && Number(result.errcode) === 40001) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn('[wechatOpen] gettemplatelist 40001 component_access_token 失效,清除缓存重试'); + } + await this.cacheDel('component_access_token'); + result = await request(); + } + return result; + } + + /** + * 提交代码审核(wxa/submit_audit,使用 authorizer_access_token 代商家调用,权限集 18)。 + * + * @param {string} appid 小程序 AppID。 + * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 + * @param {object} body 请求体(item_list/version_desc 等,均为可选)。 + * @return {Promise} 微信原始响应(errcode/errmsg/auditid)。 + */ + async submitAudit(appid, refreshToken, body) { + const request = async () => { + const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); + const base = this.config.api_base || DEFAULT_API_BASE; + const url = `${base.replace(/\/$/, '')}/wxa/submit_audit` + + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; + const response = await this.ctx.curl(url, { + method: 'POST', + dataType: 'json', + timeout: 60000, + headers: { 'Content-Type': 'application/json' }, + data: body, + }); + return response && response.data !== undefined ? response.data : response; + }; + + let result = await request(); + if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn(`[wechatOpen] wxa/submit_audit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); + } + await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); + result = await request(); + } + return result; + } + + /** + * 获取体验版二维码(wxa/get_qrcode,使用 authorizer_access_token 代商家调用,权限集 18/86)。 + * + * 成功返回图片二进制(contentType=image/jpeg),失败返回微信 JSON(errcode/errmsg)。 + * + * @param {string} appid 小程序 AppID。 + * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 + * @param {string} [path] 二维码扫码进入的页面路径(可选,自动 urlencode)。 + * @return {Promise} { errcode, errmsg } 或 { errcode: 0, contentType, buffer }。 + */ + async getTrialQRCode(appid, refreshToken, path) { + const request = async () => { + const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); + const base = this.config.api_base || DEFAULT_API_BASE; + let url = `${base.replace(/\/$/, '')}/wxa/get_qrcode` + + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; + if (path) { + url += `&path=${encodeURIComponent(path)}`; + } + const response = await this.ctx.curl(url, { + method: 'GET', + timeout: 30000, + }); + const contentType = String((response.headers && response.headers['content-type']) || ''); + if (contentType.includes('image')) { + return { errcode: 0, errmsg: 'ok', contentType, buffer: response.data }; + } + return response && response.data !== undefined ? response.data : response; + }; + + let result = await request(); + // authorizer_access_token 失效(40001/40014)时清缓存重试一次 + if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn(`[wechatOpen] wxa/get_qrcode token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); + } + await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); + result = await request(); + } + return result; + } + + /** + * 上传代码并生成体验版(wxa/commit,使用 authorizer_access_token 代商家调用,权限集 18)。 + * + * @param {string} appid 小程序 AppID。 + * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 + * @param {object} body { template_id, ext_json, user_version, user_desc }。 + * @return {Promise} 微信原始响应(errcode/errmsg)。 + */ + async commitTemplate(appid, refreshToken, body) { + const request = async () => { + const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); + const base = this.config.api_base || DEFAULT_API_BASE; + const url = `${base.replace(/\/$/, '')}/wxa/commit` + + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; + const response = await this.ctx.curl(url, { + method: 'POST', + dataType: 'json', + timeout: 60000, + headers: { 'Content-Type': 'application/json' }, + data: body, + }); + return response && response.data !== undefined ? response.data : response; + }; + + let result = await request(); + // authorizer_access_token 失效(40001/40014)时清缓存重试一次 + if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn(`[wechatOpen] wxa/commit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); + } + await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); + result = await request(); + } + return result; + } + + /** + * 快速注册企业小程序(fastregisterweapp,仅支持第三方平台 component_access_token)。 + * + * @param {string} action create=创建小程序 / search=查询创建任务状态。 + * @param {object} body 请求体。 + * @return {Promise} 微信原始响应(errcode/errmsg)。 + */ + async fastRegisterWeapp(action, body) { + const request = async () => { + const componentAccessToken = await this.getComponentAccessToken(); + const base = this.config.api_base || DEFAULT_API_BASE; + const url = `${base.replace(/\/$/, '')}/cgi-bin/component/fastregisterweapp` + + `?action=${encodeURIComponent(action)}` + + `&component_access_token=${encodeURIComponent(componentAccessToken)}`; + const response = await this.ctx.curl(url, { + method: 'POST', + dataType: 'json', + timeout: 30000, + headers: { 'Content-Type': 'application/json' }, + data: body, + }); + return response && response.data !== undefined ? response.data : response; + }; + + let result = await request(); + if (result && Number(result.errcode) === 40001) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn('[wechatOpen] fastregisterweapp 40001 component_access_token 失效,清除缓存重试'); + } + await this.cacheDel('component_access_token'); + result = await request(); + } + return result; + } + + /** + * 小程序登录凭证校验(jscode2session):第三方平台代小程序实现登录。 + * @param {string} appid 小程序 AppID。 + * @param {string} jsCode wx.login 获取的 code。 + * @return {Promise} { openid, session_key, unionid }。 + */ + async jscode2session(appid, jsCode) { + const request = async () => { + const componentAccessToken = await this.getComponentAccessToken(); + const base = this.config.api_base || DEFAULT_API_BASE; + const url = `${base.replace(/\/$/, '')}/sns/component/jscode2session` + + `?appid=${encodeURIComponent(appid)}` + + '&grant_type=authorization_code' + + `&component_appid=${encodeURIComponent(this.config.component_appid)}` + + `&component_access_token=${encodeURIComponent(componentAccessToken)}` + + `&js_code=${encodeURIComponent(jsCode)}`; + const response = await this.ctx.curl(url, { + method: 'GET', + dataType: 'json', + timeout: 30000, + }); + return response && response.data !== undefined ? response.data : response; + }; + + let result = await request(); + + // 40001:component_access_token 被别处刷新顶掉(not latest),清除缓存重取后重试一次 + if (result && Number(result.errcode) === 40001) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn('[wechatOpen] jscode2session 40001 component_access_token 失效,清除缓存重试'); + } + await this.cacheDel('component_access_token'); + result = await request(); + } + + // 调试:打印微信原始返回报文(仅 openid/session_key/unionid,无昵称头像) + if (this.ctx && this.ctx.logger) { + this.ctx.logger.info(`[wechatOpen] jscode2session appid=${appid} 返回: ${JSON.stringify(result)}`); + } + + if (result && result.openid) { + return result; + } + throw new Error(`jscode2session 失败: ${JSON.stringify(result)}`); + } + + /** + * 清理授权方相关缓存(unauthorized 取消授权事件后调用)。 + * @param {string} appid 授权方小程序 AppID。 + * @return {Promise} + */ + async clearAuthorizerCache(appid) { + await this.cacheDel( + `App:${appid}:authorization_code`, + `App:${appid}:authorizer_refresh_token`, + `App:${appid}:AuthorizerAccessToken` + ); + } + + /** + * 保存授权 state(发起授权时缓存仓库信息,回跳时凭 state 取回)。 + * @param {string} state 随机 state。 + * @param {number|string} warehouseId 仓库ID。 + * @param {number} [ttl=600] 过期秒数。 + * @return {Promise} + */ + async saveAuthState(state, warehouseId, ttl = 600) { + await this.cacheSet( + `wechat_auth_state:${state}`, + JSON.stringify({ warehouse_id: warehouseId, created_at: Math.floor(Date.now() / 1000) }), + ttl + ); + } + + /** + * 读取授权 state 对应的仓库信息。 + * @param {string} state 随机 state。 + * @return {Promise} { warehouse_id, created_at },不存在/过期返回 null。 + */ + async getAuthState(state) { + const cached = await this.cacheGet(`wechat_auth_state:${state}`); + if (!cached) return null; + try { + return JSON.parse(cached); + } catch (e) { + return null; + } + } + + /** + * 删除授权 state 缓存(回调消费后调用,保证一次性)。 + * @param {string} state 随机 state。 + * @return {Promise} + */ + async clearAuthState(state) { + await this.cacheDel(`wechat_auth_state:${state}`); + } + + /** + * 发送客服文本消息(POST cgi-bin/message/custom/send,使用 authorizer_access_token + * 代授权方调用,用于用户关注欢迎语、关键词自动回复等场景)。 + * + * @param {string} appid 授权方(小程序/公众号)AppID。 + * @param {string} touser 用户 openid。 + * @param {string} content 文本内容。 + * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 + * @return {Promise} 微信原始响应(errcode/errmsg)。 + */ + async sendCustomMessage(appid, touser, content, refreshToken) { + const request = async () => { + const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); + const base = this.config.api_base || DEFAULT_API_BASE; + const url = `${base.replace(/\/$/, '')}/cgi-bin/message/custom/send` + + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; + const response = await this.ctx.curl(url, { + method: 'POST', + dataType: 'json', + timeout: 30000, + headers: { 'Content-Type': 'application/json' }, + data: { + touser, + msgtype: 'text', + text: { content }, + }, + }); + return response && response.data !== undefined ? response.data : response; + }; + + let result = await request(); + // authorizer_access_token 失效(40001/40014)时清缓存重试一次 + if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { + if (this.ctx && this.ctx.logger) { + this.ctx.logger.warn(`[wechatOpen] message/custom/send token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); + } + await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); + result = await request(); + } + return result; + } +} + +module.exports = WechatOpenClient; diff --git a/app/lib/wechat_open_crypt.js b/app/lib/wechat_open_crypt.js new file mode 100644 index 0000000..2390787 --- /dev/null +++ b/app/lib/wechat_open_crypt.js @@ -0,0 +1,304 @@ +'use strict'; + +const crypto = require('node:crypto'); +const { XMLParser } = require('fast-xml-parser'); + +/** + * 微信开放平台第三方平台消息加解密工具(Node 版 WXBizMsgCrypt)。 + * 对应微信官方示例(PHP WXBizMsgCrypt)能力: + * - URL 有效性验证(首次配置服务器地址时的 echostr 校验) + * - 事件推送消息解密(AES-256-CBC + PKCS#7,密文格式: + * 16 字节随机串 + 4 字节大端消息长度 + 明文 XML + component_appid) + * + * 错误码沿用微信官方定义: + * -40001 签名验证错误 / -40004 encodingAesKey 非法 / -40005 appid 校验错误 / + * -40007 AES 解密失败 / -40008 解密后 buffer 非法 / -40010 base64 解码失败。 + */ + +const ERROR_CODES = { + OK: 0, + VALIDATE_SIGNATURE_ERROR: -40001, + ILLEGAL_AES_KEY: -40004, + VALIDATE_APPID_ERROR: -40005, + DECRYPT_AES_ERROR: -40007, + ILLEGAL_BUFFER: -40008, + DECODE_BASE64_ERROR: -40010, +}; + +/** + * 计算 SHA1(hex)。 + * @param {string} input 输入字符串。 + * @return {string} SHA1 摘要。 + */ +function sha1(input) { + return crypto.createHash('sha1').update(input, 'utf8').digest('hex'); +} + +/** + * 生成消息签名:sha1(sort(token, timestamp, nonce, encrypt))。 + * @param {string} token 第三方平台消息校验 Token。 + * @param {string} timestamp 时间戳。 + * @param {string} nonce 随机串。 + * @param {string} [encrypt=''] 加密内容(URL 验证时为空)。 + * @return {string} 签名。 + */ +function getSignature(token, timestamp, nonce, encrypt = '') { + const arr = [ token, String(timestamp), String(nonce), String(encrypt || '') ].sort(); + return sha1(arr.join('')); +} + +/** + * 校验 URL 有效性签名:signature === sha1(sort(token, timestamp, nonce))。 + * @param {string} token 第三方平台消息校验 Token。 + * @param {string} signature 微信回传的 signature。 + * @param {string} timestamp 时间戳。 + * @param {string} nonce 随机串。 + * @return {boolean} 是否通过。 + */ +function verifyUrlSignature(token, signature, timestamp, nonce) { + if (!token || !signature || timestamp === undefined || timestamp === null || nonce === undefined || nonce === null) { + return false; + } + const expected = getSignature(token, timestamp, nonce); + return expected === String(signature); +} + +/** + * 解析加密推送 XML,提取 内容。 + * @param {string} encryptedXml 微信推送的加密 XML。 + * @return {string} Encrypt 密文(base64 字符串)。 + */ +function extractEncrypt(encryptedXml) { + if (!encryptedXml) return ''; + const parser = new XMLParser({ + ignoreAttributes: false, + parseTagValue: false, + parseAttributeValue: false, + trimValues: false, + }); + let parsed; + try { + parsed = parser.parse(encryptedXml.trim()); + } catch (e) { + return ''; + } + return (parsed && parsed.xml && parsed.xml.Encrypt) || ''; +} + +/** + * PKCS#7 去除填充。 + * @param {Buffer} buf 解密后的带填充 buffer。 + * @return {Buffer} 去填充后的 buffer。 + */ +function pkcs7Decode(buf) { + const pad = buf[buf.length - 1]; + if (pad >= 1 && pad <= 32) { + return buf.subarray(0, buf.length - pad); + } + return buf; +} + +/** + * PKCS#7 填充(微信 AES 块大小为 32 字节)。 + * @param {Buffer} buf 原始 buffer。 + * @return {Buffer} 填充后的 buffer。 + */ +function pkcs7Encode(buf) { + const blockSize = 32; + const pad = blockSize - (buf.length % blockSize); + const result = Buffer.alloc(buf.length + pad); + buf.copy(result); + result.fill(pad, buf.length); + return result; +} + +/** + * AES-256-CBC 解密微信密文。 + * @param {string} encrypted base64 密文。 + * @param {Buffer} aesKey 32 字节 AES Key。 + * @return {{ code: number, buf: Buffer }} 解密结果(失败时 buf 为空 Buffer)。 + */ +function aesDecrypt(encrypted, aesKey) { + const encryptedBuf = Buffer.from(String(encrypted), 'base64'); + if (!encryptedBuf.length) { + return { code: ERROR_CODES.DECODE_BASE64_ERROR, buf: Buffer.alloc(0) }; + } + try { + const iv = aesKey.subarray(0, 16); + const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, iv); + decipher.setAutoPadding(false); + const decoded = pkcs7Decode(Buffer.concat([ decipher.update(encryptedBuf), decipher.final() ])); + return { code: ERROR_CODES.OK, buf: decoded }; + } catch (e) { + return { code: ERROR_CODES.DECRYPT_AES_ERROR, buf: Buffer.alloc(0) }; + } +} + +/** + * 解密事件推送消息(完整流程:签名校验 → base64/AES 解密 → 报文解析 → appid 校验)。 + * @param {object} opts 参数。 + * @param {string} opts.token 第三方平台消息校验 Token。 + * @param {string} opts.encodingAesKey 第三方平台消息加解密 Key(43 位)。 + * @param {string} opts.componentAppid 第三方平台 AppID。 + * @param {string} opts.msgSignature 消息签名 msg_signature。 + * @param {string|number} opts.timestamp 时间戳。 + * @param {string} opts.nonce 随机串。 + * @param {string} opts.encryptedXml 微信推送的加密 XML。 + * @return {{ code: number, msg: string }} code=0 时 msg 为解密后的明文 XML。 + */ +function decryptMsg(opts) { + const { + token, + encodingAesKey, + componentAppid, + msgSignature, + timestamp, + nonce, + encryptedXml, + } = opts || {}; + + const encrypt = extractEncrypt(encryptedXml); + if (!encrypt) { + return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '加密 XML 中未找到 Encrypt 内容' }; + } + + // 1. 校验消息签名 + const expectedSignature = getSignature(token, timestamp, nonce, encrypt); + if (expectedSignature !== String(msgSignature)) { + return { code: ERROR_CODES.VALIDATE_SIGNATURE_ERROR, msg: '消息签名校验失败' }; + } + + // 2. AES Key(encodingAesKey 43 位补 '=' 后 base64 解码为 32 字节) + let aesKey; + try { + aesKey = Buffer.from(String(encodingAesKey) + '=', 'base64'); + } catch (e) { + return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 非法' }; + } + if (aesKey.length !== 32) { + return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 解码后长度不是 32 字节' }; + } + + // 3. AES 解密 + const decrypted = aesDecrypt(encrypt, aesKey); + if (decrypted.code !== ERROR_CODES.OK) { + return { code: decrypted.code, msg: 'AES 解密失败' }; + } + + // 4. 解析明文(二进制 buffer):16 字节随机串 + 4 字节大端长度 + 消息体 + appid + const content = decrypted.buf; + if (content.length < 20) { + return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后 buffer 长度非法' }; + } + const msgLen = content.readUInt32BE(16); + if (20 + msgLen > content.length) { + return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后消息长度非法' }; + } + const xmlContent = content.subarray(20, 20 + msgLen).toString('utf8'); + const fromAppid = content.subarray(20 + msgLen).toString('utf8'); + + // 5. 校验 appid + if (fromAppid !== String(componentAppid)) { + return { code: ERROR_CODES.VALIDATE_APPID_ERROR, msg: `appid 校验失败: ${fromAppid}` }; + } + + return { code: ERROR_CODES.OK, msg: xmlContent }; +} + +/** + * 解析明文 XML 为对象({ AppId, InfoType, ... })。 + * @param {string} xml 明文 XML。 + * @return {object} 解析后的对象(失败返回空对象)。 + */ +function parseXml(xml) { + if (!xml) return {}; + const parser = new XMLParser({ + ignoreAttributes: false, + parseTagValue: false, + parseAttributeValue: false, + trimValues: false, + }); + try { + const parsed = parser.parse(xml.trim()); + return (parsed && parsed.xml) || {}; + } catch (e) { + return {}; + } +} + +/** + * 加密被动回复消息(完整流程:明文组装 → PKCS#7 → AES-256-CBC → base64 → 签名 → 组装 XML)。 + * 用于第三方平台模式下回复授权方(小程序/公众号)用户消息: + * 16 字节随机串 + 4 字节大端消息长度 + 明文 XML + component_appid,密钥与推送解密共用组件密钥。 + * @param {object} opts 参数。 + * @param {string} opts.token 第三方平台消息校验 Token。 + * @param {string} opts.encodingAesKey 第三方平台消息加解密 Key(43 位)。 + * @param {string} opts.componentAppid 第三方平台 AppID。 + * @param {string} opts.plainXml 明文回复 XML。 + * @param {string} opts.nonce 微信回传的随机串(用于回复签名)。 + * @return {{ code: number, encryptedXml: string }} code=0 时 encryptedXml 为加密回复 XML。 + */ +function encryptMsg(opts) { + const { + token, + encodingAesKey, + componentAppid, + plainXml, + nonce, + } = opts || {}; + + if (!token || !encodingAesKey || !componentAppid || !plainXml) { + return { code: ERROR_CODES.ILLEGAL_BUFFER, encryptedXml: '' }; + } + + // 1. AES Key(encodingAesKey 43 位补 '=' 后 base64 解码为 32 字节) + let aesKey; + try { + aesKey = Buffer.from(String(encodingAesKey) + '=', 'base64'); + } catch (e) { + return { code: ERROR_CODES.ILLEGAL_AES_KEY, encryptedXml: '' }; + } + if (aesKey.length !== 32) { + return { code: ERROR_CODES.ILLEGAL_AES_KEY, encryptedXml: '' }; + } + + // 2. 组装明文:16 字节随机串 + 4 字节大端长度 + 明文 XML + component_appid + const random = crypto.randomBytes(16); + const plainBuf = Buffer.from(String(plainXml), 'utf8'); + const lenBuf = Buffer.alloc(4); + lenBuf.writeUInt32BE(plainBuf.length, 0); + const appidBuf = Buffer.from(String(componentAppid), 'utf8'); + const padded = pkcs7Encode(Buffer.concat([ random, lenBuf, plainBuf, appidBuf ])); + + // 3. AES-256-CBC 加密(iv = key 前 16 字节,手动填充) + let encrypt; + try { + const iv = aesKey.subarray(0, 16); + const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, iv); + cipher.setAutoPadding(false); + encrypt = Buffer.concat([ cipher.update(padded), cipher.final() ]).toString('base64'); + } catch (e) { + return { code: ERROR_CODES.DECRYPT_AES_ERROR, encryptedXml: '' }; + } + + // 4. 签名与组装回复 XML + const timestamp = Math.floor(Date.now() / 1000); + const signature = getSignature(token, timestamp, nonce, encrypt); + const encryptedXml = `` + + `` + + `${timestamp}` + + ``; + + return { code: ERROR_CODES.OK, encryptedXml }; +} + +module.exports = { + ERROR_CODES, + sha1, + getSignature, + verifyUrlSignature, + extractEncrypt, + decryptMsg, + parseXml, + encryptMsg, +}; diff --git a/app/model/account.js b/app/model/account.js index 184c5c5..b2199a2 100644 --- a/app/model/account.js +++ b/app/model/account.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, STRING, INTEGER, DATE, TINYINT, fn } = app.Sequelize; + const { BIGINT, STRING, DATE, TINYINT, fn } = app.Sequelize; const Account = app.model.define('account', { id: { @@ -74,6 +74,18 @@ module.exports = app => { }, comment: '状态:0-封号,1-启用', }, + is_custom_password: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + validate: { + isIn: { + args: [[ 0, 1 ]], + msg: '自定义密码标记值不合法,0-否,1-是', + }, + }, + comment: '是否自定义密码:0-否,1-是', + }, last_login_at: { type: DATE, allowNull: true, @@ -131,14 +143,11 @@ module.exports = app => { }); // 关联关系 - Account.associate = function(models) { + Account.associate = function() { const { AccountStoreEmployee, AccountPlatformActive } = app.model; - /* if (models.AccountStoreRole) { - - }*/ Account.hasMany(AccountStoreEmployee, { foreignKey: 'account_id', - as: 'accountStoreRoles', + as: 'accountStoreEmployees', }); Account.hasMany(AccountPlatformActive, { foreignKey: 'account_id', diff --git a/app/model/account_platform_active.js b/app/model/account_platform_active.js index c5b72e9..9142143 100644 --- a/app/model/account_platform_active.js +++ b/app/model/account_platform_active.js @@ -75,7 +75,7 @@ module.exports = app => { }); // 关联关系 - 注释掉或删除,统一在 app.js 中处理 - AccountPlatformActive.associate = function(models) { + AccountPlatformActive.associate = function() { const { Account, AccountStoreEmployee } = app.model; AccountPlatformActive.belongsTo(Account, { foreignKey: 'account_id', diff --git a/app/model/account_store_employee.js b/app/model/account_store_employee.js index b8c96e2..5cfe23e 100644 --- a/app/model/account_store_employee.js +++ b/app/model/account_store_employee.js @@ -78,8 +78,8 @@ module.exports = app => { }); // 关联关系 - AccountStoreEmployee.associate = function(models) { - const { Account, Store, Role, AccountPlatformActive, EmployeeRole, Receiving } = app.model; + AccountStoreEmployee.associate = function() { + const { Account, Store, AccountPlatformActive, EmployeeRole, Receiving } = app.model; AccountStoreEmployee.belongsTo(Account, { foreignKey: 'account_id', as: 'account', @@ -94,7 +94,7 @@ module.exports = app => { }); AccountStoreEmployee.hasMany(EmployeeRole, { foreignKey: 'employee_id', - as: 'employeeRole', + as: 'employeeRoles', }); AccountStoreEmployee.hasMany(Receiving, { foreignKey: 'creator_id', diff --git a/app/model/after_sale.js b/app/model/after_sale.js new file mode 100644 index 0000000..bfb1930 --- /dev/null +++ b/app/model/after_sale.js @@ -0,0 +1,424 @@ +'use strict'; + +/** + * 售后主表 Model,基于 `wms_after_sale` 表。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 售后 Model(含常量挂载) + */ +module.exports = app => { + const { STRING, BIGINT, INTEGER, DECIMAL, TEXT, TINYINT, DATE } = app.Sequelize; + + // ============================ + // 枚举常量定义 + // ============================ + + /** + * 售后类型 + 子类型枚举,按业务单据维度分类。 + * @type {Array<{name: string, type: string, subType: Array<{name: string, value: string}>}>} + */ + const AFTER_SALE_TYPES = [ + { + name: '订单', + type: 'order', + subType: [ + { name: '破损', value: 'damage' }, + { name: '少发', value: 'missing_item' }, + { name: '错发', value: 'mis_shipment' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '发货延迟', value: 'delivery_delay' }, + { name: '物流异常', value: 'logistics_issue' }, + { name: '客户拒收', value: 'rejected' }, + { name: '拦截', value: 'intercept' }, + { name: '取消拦截', value: 'cancel_intercept' }, + { name: '核实签收', value: 'verify_delivery' }, + { name: '催件', value: 'urge' }, + { name: '多发', value: 'extra_item' }, + { name: '改地址', value: 'change_address' }, + { name: '换快递', value: 'change_carrier' }, + { name: '揽收', value: 'pickup' }, + { name: '重量异常', value: 'weight_issue' }, + { name: '运费争议', value: 'freight_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '收货单', + type: 'receiving', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '入库单', + type: 'entry', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '出库单', + type: 'stockout', + subType: [ + { name: '退货异常', value: 'return_issue' }, + { name: '错发', value: 'wrong_outbound' }, + { name: '少发', value: 'shortage' }, + { name: '其他', value: 'other' }, + ], + }, + ]; + + /** + * 售后处理角色组枚举。 + * @type {{customer_service: string, warehouse: string, finance: string}} + */ + const AFTER_SALE_ROLE_GROUPS = { + customer_service: '客服组', + warehouse: '仓库组', + finance: '财务组', + }; + + /** + * 售后单状态枚举。 + * @type {{pending: string, processing: string, waiting: string, completed: string, closed: string, cancelled: string}} + */ + const AFTER_SALE_STATUS = { + pending: '待处理', + processing: '处理中', + pending_feedback: '等待外部反馈', + completed: '已完成', + closed: '已关闭', + cancelled: '已取消', + }; + + /** + * 理赔状态枚举(仓库理赔 & 运方理赔通用)。 + * @type {{pending: string, reviewing: string, approved: string, paid: string, monthly: string, rejected: string}} + */ + const CLAIM_STATUS = { + pending: '待理赔', + reviewing: '审核中', + approved: '已通过', + paid: '已打款', + monthly: '月结', + rejected: '已拒绝', + }; + + // ============================ + // Model 定义 + // ============================ + + const AfterSale = app.model.define('after_sale', { + /** 主键 */ + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + /** 仓库ID */ + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + /** 货主ID */ + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + /** 售后单号,唯一 */ + after_sale_no: { + type: STRING(50), + allowNull: false, + comment: '售后单号,唯一。生成规则:前缀AS + 日期YYYYMMDD + 6位序号', + }, + /** 售后类型 */ + type: { + type: STRING(20), + allowNull: false, + comment: '售后类型:order=订单, receiving=收货单, entry=入库单, stockout=出库单', + }, + /** 售后子类型 */ + sub_type: { + type: STRING(50), + allowNull: false, + comment: '售后子类型,与 type 组成二级分类', + }, + /** 售后状态 */ + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '售后状态:pending=待处理, processing=处理中, pending_feedback=等待外部反馈, completed=已完成, closed=已关闭, cancelled=已取消', + }, + /** 优先级 */ + priority: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先(0=普通,10=紧急)', + }, + /** 售后标题 */ + title: { + type: STRING(200), + allowNull: false, + comment: '售后标题(简要描述)', + }, + /** 售后详细描述 */ + description: { + type: TEXT, + allowNull: true, + comment: '售后详细描述', + }, + /** 创建人账户ID */ + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人账户ID(关联 accounts 表)', + }, + /** 关联站内信消息ID */ + inbox_message_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_inbox_message.id,为空表示无关联信息', + }, + /** 当前处理角色组 */ + role_group: { + type: STRING(50), + allowNull: true, + comment: '当前处理角色组:customer_service=客服组, warehouse=仓库组, finance=财务组。NULL 表示未分配', + }, + /** 最终处理结果说明 */ + resolution: { + type: TEXT, + allowNull: true, + comment: '最终处理结果说明', + }, + /** 完结时间 */ + resolved_at: { + type: DATE, + allowNull: true, + comment: '完结时间(状态变为 completed 时写入)', + }, + /** 下次跟进时间 */ + followup_at: { + type: DATE, + allowNull: true, + comment: '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进', + }, + /** 仓库理赔标记 */ + claim_needed: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '仓库理赔标记:0=不需要,1=需要', + }, + /** 仓库理赔金额(元) */ + claim_amount: { + type: DECIMAL(12, 2), + allowNull: true, + comment: '仓库理赔金额,单位:人民币(元),claim_needed=1 时可填写', + }, + /** 仓库理赔状态 */ + claim_status: { + type: STRING(20), + allowNull: true, + comment: '仓库理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝', + }, + /** 运方理赔标记 */ + carrier_claim_needed: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '运方理赔标记:0=不需要,1=需要', + }, + /** 运方理赔金额(元) */ + carrier_claim_amount: { + type: DECIMAL(12, 2), + allowNull: true, + comment: '运方理赔金额,单位:人民币(元),carrier_claim_needed=1 时可填写', + }, + /** 运方理赔状态 */ + carrier_claim_status: { + type: STRING(20), + allowNull: true, + comment: '运方理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝', + }, + // ========== 单据关联字段(替代旧版多态关联) ========== + /** 运单ID */ + waybill_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '运单ID(关联 wms_order_express.id)', + }, + /** 运单号(冗余) */ + waybill_no: { + type: STRING(50), + allowNull: true, + comment: '运单号(冗余字段,方便查询展示)', + }, + /** 订单ID */ + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID(关联 wms_order_delivery.id)', + }, + /** 入库单ID */ + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库单ID(关联 wms_entry_order.id)', + }, + /** 入库单号(冗余) */ + entry_order_no: { + type: STRING(50), + allowNull: true, + comment: '入库单号(冗余字段)', + }, + /** 出库单/退货出库单ID */ + order_stockout_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '出库单/退货出库单ID(关联 wms_order_stockout.id)', + }, + /** 出库单号(冗余) */ + order_stockout_no: { + type: STRING(50), + allowNull: true, + comment: '出库单号(冗余字段)', + }, + /** 收货单ID */ + receiving_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '收货单ID(关联 wms_receiving.id)', + }, + /** 收货单号(冗余) */ + receiving_no: { + type: STRING(50), + allowNull: true, + comment: '收货单号(冗余字段)', + }, + /** 创建时间 */ + created_at: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + /** 更新时间 */ + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + /** 软删除时间 */ + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_after_sale', + comment: '售后主表', + timestamps: false, + indexes: [ + { + name: 'uk_after_sale_no', + unique: true, + fields: [ 'after_sale_no' ], + }, + { + name: 'idx_warehouse_status', + fields: [ 'warehouse_id', 'status', 'deleted_at' ], + }, + { + name: 'idx_warehouse_type', + fields: [ 'warehouse_id', 'type', 'deleted_at' ], + }, + { + name: 'idx_type_subtype', + fields: [ 'warehouse_id', 'type', 'sub_type', 'deleted_at' ], + }, + { + name: 'idx_store_id', + fields: [ 'store_id', 'deleted_at' ], + }, + { + name: 'idx_creator_id', + fields: [ 'creator_id', 'deleted_at' ], + }, + { + name: 'idx_role_group', + fields: [ 'role_group', 'status', 'deleted_at' ], + }, + { + name: 'idx_created_at', + fields: [ 'warehouse_id', 'created_at' ], + }, + { + name: 'idx_waybill_id', + fields: [ 'waybill_id' ], + }, + { + name: 'idx_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, + { + name: 'idx_order_stockout_id', + fields: [ 'order_stockout_id' ], + }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'idx_carrier_claim_status', + fields: [ 'carrier_claim_status' ], + }, + { + name: 'idx_inbox_message_id', + fields: [ 'inbox_message_id' ], + }, + ], + }); + + // ============================ + // 关联关系 + // ============================ + + AfterSale.associate = function() { + const { AfterSale, AfterSaleDetail } = app.model; + + // 关联售后进度步骤(一对多) + AfterSale.hasMany(AfterSaleDetail, { + foreignKey: 'after_sale_id', + as: 'details', + }); + }; + + // ============================ + // 常量挂载到 Model + // ============================ + + AfterSale.AFTER_SALE_TYPES = AFTER_SALE_TYPES; + AfterSale.AFTER_SALE_ROLE_GROUPS = AFTER_SALE_ROLE_GROUPS; + AfterSale.AFTER_SALE_STATUS = AFTER_SALE_STATUS; + AfterSale.CLAIM_STATUS = CLAIM_STATUS; + + return AfterSale; +}; diff --git a/app/model/after_sale_detail.js b/app/model/after_sale_detail.js new file mode 100644 index 0000000..f623b96 --- /dev/null +++ b/app/model/after_sale_detail.js @@ -0,0 +1,144 @@ +'use strict'; + +/** + * 售后进度步骤表 Model,基于 `wms_after_sale_detail` 表。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 售后进度步骤 Model(含常量挂载) + */ +module.exports = app => { + const { STRING, BIGINT, TEXT, DATE } = app.Sequelize; + + // ============================ + // 枚举常量定义 + // ============================ + + /** + * 步骤状态枚举(与 wms_after_sale.status 一致)。 + */ + const STEP_STATUS = { + pending: '待处理', + processing: '处理中', + pending_feedback: '等待外部反馈', + completed: '已完成', + closed: '已关闭', + cancelled: '已取消', + }; + + // ============================ + // Model 定义 + // ============================ + + const AfterSaleDetail = app.model.define('after_sale_detail', { + /** 主键 */ + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + /** 关联售后主表ID */ + after_sale_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联售后主表ID(wms_after_sale.id)', + }, + /** 步骤记录时售后主表的状态 */ + step_status: { + type: STRING(20), + allowNull: false, + defaultValue: 'processing', + comment: '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled', + }, + /** 操作人账户ID */ + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人账户ID(关联 accounts 表);外部系统回调/自动触发的步骤可为空', + }, + /** 操作人信息快照 */ + operator_snapshot: { + type: TEXT, + allowNull: true, + comment: '操作人信息快照(JSON),如 {"name":"张三","role":"客服"},防止账户删除后历史丢失', + }, + /** 操作动作描述 */ + action: { + type: STRING(100), + allowNull: true, + comment: '操作动作描述,如"确认收货"、"审核驳回"、"发起退款"', + }, + /** 处理备注 */ + remark: { + type: TEXT, + allowNull: true, + comment: '处理备注', + }, + /** 步骤开始时间 */ + started_at: { + type: DATE, + allowNull: true, + comment: '步骤开始时间', + }, + /** 步骤完成时间 */ + completed_at: { + type: DATE, + allowNull: true, + comment: '步骤完成时间', + }, + /** 创建时间 */ + created_at: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + /** 更新时间 */ + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + /** 软删除时间 */ + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_after_sale_detail', + comment: '售后进度步骤表', + timestamps: false, + indexes: [ + { + name: 'idx_after_sale_id', + fields: [ 'after_sale_id' ], + }, + { + name: 'idx_operator_id', + fields: [ 'operator_id' ], + }, + ], + }); + + // ============================ + // 关联关系 + // ============================ + + AfterSaleDetail.associate = function() { + const { AfterSale, AfterSaleDetail } = app.model; + + // 关联售后主表(多对一) + AfterSaleDetail.belongsTo(AfterSale, { + foreignKey: 'after_sale_id', + as: 'afterSale', + }); + }; + + // ============================ + // 常量挂载到 Model + // ============================ + + AfterSaleDetail.STEP_STATUS = STEP_STATUS; + + return AfterSaleDetail; +}; diff --git a/app/model/after_sale_function.js b/app/model/after_sale_function.js new file mode 100644 index 0000000..61bacec --- /dev/null +++ b/app/model/after_sale_function.js @@ -0,0 +1,67 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize; + + const AfterSaleFunction = app.model.define('afterSaleFunction', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + function_code: { + type: STRING(50), + allowNull: false, + comment: '处理函数编码(与 inbox functions registry 注册名一致)', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '处理函数名称', + }, + description: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '处理函数说明', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + sort_order: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序值,越小越靠前', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_after_sale_function', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '售后处理函数表(子类型处理链路)', + indexes: [ + { + unique: true, + fields: [ 'function_code' ], + name: 'uk_function_code', + }, + ], + }); + + return AfterSaleFunction; +}; diff --git a/app/model/after_sale_keyword.js b/app/model/after_sale_keyword.js new file mode 100644 index 0000000..e0dbbd7 --- /dev/null +++ b/app/model/after_sale_keyword.js @@ -0,0 +1,81 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize; + + const AfterSaleKeyword = app.model.define('afterSaleKeyword', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义,仅该仓库可见)', + }, + sub_type_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + keyword: { + type: STRING(100), + allowNull: false, + comment: '关键词,命中即映射到对应售后子类型', + }, + is_system: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否系统级:1=系统级(全部仓库可读,不允许编辑/删除),0=仓库自定义', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + sort_order: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '匹配优先级,数值小者优先(同长度命中时生效)', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_after_sale_keyword', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '售后关键词表(关键词 → 售后子类型映射)', + indexes: [ + { + unique: true, + fields: [ 'keyword', 'warehouse_id' ], + name: 'uk_keyword_warehouse', + }, + { + fields: [ 'sub_type_id' ], + name: 'idx_sub_type_id', + }, + { + fields: [ 'warehouse_id' ], + name: 'idx_warehouse_id', + }, + ], + }); + + return AfterSaleKeyword; +}; diff --git a/app/model/after_sale_reply.js b/app/model/after_sale_reply.js new file mode 100644 index 0000000..bb842eb --- /dev/null +++ b/app/model/after_sale_reply.js @@ -0,0 +1,87 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, TINYINT, TEXT, DATE } = app.Sequelize; + + const AfterSaleReply = app.model.define('afterSaleReply', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID(NULL=系统级默认回复;非NULL=仓库级自定义回复,覆盖系统级)', + }, + sub_type_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + reply: { + type: TEXT, + allowNull: false, + comment: '自定义回复文案(支持换行,可含占位符)', + }, + is_reply: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否回复:1=命中后回复,0=静默不回复', + }, + create_work_order: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否登记工单:1=执行函数处理(可能建工单,默认),0=仅回复不执行函数', + }, + no_number_hint: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '未取到单据号时的引导语(如:请提供运单号;为空则用默认引导语)', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用(停用视为未设置,回退系统级)', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_after_sale_reply', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '售后自定义回复表(仓库级覆盖系统级)', + indexes: [ + { + unique: true, + fields: [ 'warehouse_id', 'sub_type_id' ], + name: 'uk_warehouse_sub_type', + }, + { + fields: [ 'sub_type_id' ], + name: 'idx_sub_type_id', + }, + { + fields: [ 'is_enabled' ], + name: 'idx_is_enabled', + }, + ], + }); + + return AfterSaleReply; +}; diff --git a/app/model/after_sale_sub_type.js b/app/model/after_sale_sub_type.js new file mode 100644 index 0000000..407c75d --- /dev/null +++ b/app/model/after_sale_sub_type.js @@ -0,0 +1,86 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize; + + const AfterSaleSubType = app.model.define('afterSaleSubType', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义)', + }, + type: { + type: STRING(20), + allowNull: false, + comment: '所属售后类型编码(对应 wms_after_sale_type.type)', + }, + sub_type: { + type: STRING(50), + allowNull: false, + comment: '售后子类型编码(与 wms_after_sale.sub_type 对应)', + }, + name: { + type: STRING(50), + allowNull: false, + comment: '售后子类型名称', + }, + is_system: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否系统级:1=系统级(不可编辑/删除),0=仓库自定义', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + sort_order: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序值,越小越靠前', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_after_sale_sub_type', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '售后子类型表(系统级 + 仓库自定义)', + indexes: [ + { + unique: true, + fields: [ 'type', 'sub_type', 'warehouse_id' ], + name: 'uk_type_subtype_warehouse', + }, + { + fields: [ 'warehouse_id' ], + name: 'idx_warehouse_id', + }, + { + fields: [ 'is_system' ], + name: 'idx_is_system', + }, + ], + }); + + return AfterSaleSubType; +}; diff --git a/app/model/after_sale_sub_type_function.js b/app/model/after_sale_sub_type_function.js new file mode 100644 index 0000000..5c33ec1 --- /dev/null +++ b/app/model/after_sale_sub_type_function.js @@ -0,0 +1,59 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, INTEGER, DATE } = app.Sequelize; + + const AfterSaleSubTypeFunction = app.model.define('afterSaleSubTypeFunction', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + sub_type_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + function_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '处理函数ID(关联 wms_after_sale_function.id)', + }, + sort_order: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '同子类型下处理函数执行顺序,数值小者优先', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_after_sale_sub_type_function', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '售后子类型-处理函数关联表(多对多)', + indexes: [ + { + unique: true, + fields: [ 'sub_type_id', 'function_id' ], + name: 'uk_sub_type_function', + }, + { + fields: [ 'function_id' ], + name: 'idx_function_id', + }, + ], + }); + + return AfterSaleSubTypeFunction; +}; diff --git a/app/model/after_sale_sub_type_group.js b/app/model/after_sale_sub_type_group.js new file mode 100644 index 0000000..909f1a9 --- /dev/null +++ b/app/model/after_sale_sub_type_group.js @@ -0,0 +1,70 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize; + + const AfterSaleSubTypeGroup = app.model.define('afterSaleSubTypeGroup', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + sub_type_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + group_type: { + type: STRING(20), + allowNull: false, + comment: '群类型:store=货主群 / warehouse=仓库群 / express=快递群', + }, + sub_group: { + type: STRING(20), + allowNull: false, + comment: '群子类型:store(after_sales/finance/receiving)、warehouse(customer_service/...)、express(pickup/after_sales)', + }, + is_system: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否系统预设关联:1=系统级子类型默认分配(锁定不可改),0=自定义', + }, + sort_order: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序值,越小越靠前', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_after_sale_sub_type_group', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '群类型-售后子类型关联表(多对多)', + indexes: [ + { + unique: true, + fields: [ 'sub_type_id', 'group_type', 'sub_group' ], + name: 'uk_sub_type_group', + }, + { + fields: [ 'group_type', 'sub_group' ], + name: 'idx_group_type', + }, + ], + }); + + return AfterSaleSubTypeGroup; +}; diff --git a/app/model/after_sale_sub_type_rule.js b/app/model/after_sale_sub_type_rule.js new file mode 100644 index 0000000..067e59d --- /dev/null +++ b/app/model/after_sale_sub_type_rule.js @@ -0,0 +1,59 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, INTEGER, DATE } = app.Sequelize; + + const AfterSaleSubTypeRule = app.model.define('afterSaleSubTypeRule', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + sub_type_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + number_rule_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '取号规则ID(关联 wms_inbox_number_rule.id)', + }, + sort_order: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '同一子类型下规则的提取顺序,数值小者优先', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_after_sale_sub_type_rule', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '售后子类型-取号规则关联表(多对多)', + indexes: [ + { + unique: true, + fields: [ 'sub_type_id', 'number_rule_id' ], + name: 'uk_sub_type_rule', + }, + { + fields: [ 'number_rule_id' ], + name: 'idx_number_rule_id', + }, + ], + }); + + return AfterSaleSubTypeRule; +}; diff --git a/app/model/after_sale_type.js b/app/model/after_sale_type.js new file mode 100644 index 0000000..5dae9d5 --- /dev/null +++ b/app/model/after_sale_type.js @@ -0,0 +1,81 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize; + + const AfterSaleType = app.model.define('afterSaleType', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义)', + }, + type: { + type: STRING(20), + allowNull: false, + comment: '售后类型编码:order/receiving/entry/stockout,仓库自定义可自定义编码', + }, + name: { + type: STRING(50), + allowNull: false, + comment: '售后类型名称', + }, + is_system: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否系统级:1=系统级(不可编辑/删除),0=仓库自定义', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + sort_order: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序值,越小越靠前', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_after_sale_type', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '售后类型表(系统级 + 仓库自定义)', + indexes: [ + { + unique: true, + fields: [ 'type', 'warehouse_id' ], + name: 'uk_type_warehouse', + }, + { + fields: [ 'warehouse_id' ], + name: 'idx_warehouse_id', + }, + { + fields: [ 'is_system' ], + name: 'idx_is_system', + }, + ], + }); + + return AfterSaleType; +}; diff --git a/app/model/api_app.js b/app/model/api_app.js index 2273d52..bd61d4a 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -65,6 +65,16 @@ module.exports = app => { allowNull: true, comment: '自身IP白名单', }, + callback_url: { + type: STRING(500), + allowNull: true, + comment: 'API回调通知URL', + }, + callback_functions: { + type: JSON, + allowNull: true, + comment: '承接的出站回调 method 列表(空/未勾选=不承接任何回调;按 method 自动路由)', + }, qimen_app_key: { type: STRING(100), allowNull: true, @@ -103,10 +113,10 @@ module.exports = app => { allowNull: true, defaultValue: 'md5', validate: { - isIn: [[ 'md5', 'hmac', 'sha256' ]], + isIn: [[ 'md5' ]], len: [ 0, 50 ], }, - comment: '签名方法', + comment: '签名方法(当前仅支持 md5)', }, rate_limit: { type: INTEGER(11), @@ -177,6 +187,7 @@ module.exports = app => { freezeTableName: true, underscored: true, timestamps: true, + paranoid: false, createdAt: 'created_at', updatedAt: 'updated_at', comment: 'API应用配置表', @@ -194,7 +205,7 @@ module.exports = app => { { name: 'uk_interface_warehouse', unique: true, - fields: [ 'qimen_app_key', 'qimen_customer_id' ], + fields: [ 'qimen_app_key', 'qimen_warehouse_code' ], }, { name: 'uk_interface_contract', @@ -226,7 +237,7 @@ module.exports = app => { // 定义关联关系 ApiApp.associate = function() { - const { InterfaceType, StoreWarehouse, Store, InterfaceLog } = app.model; + const { InterfaceType, StoreWarehouse, Store } = app.model; // 关联接口类型 ApiApp.belongsTo(InterfaceType, { @@ -288,22 +299,5 @@ module.exports = app => { return generatedSignature === signature; }; - // 类方法 - 根据AppKey查找 - ApiApp.findByAppKey = async function(appKey) { - return await this.findOne({ - where: { self_app_key: appKey }, - }); - }; - - // 类方法 - 根据奇门配置查找 - ApiApp.findByQimenConfig = async function(appKey, customerId) { - return await this.findOne({ - where: { - qimen_app_key: appKey, - qimen_customer_id: customerId, - }, - }); - }; - return ApiApp; }; diff --git a/app/model/camera.js b/app/model/camera.js new file mode 100644 index 0000000..04fa30e --- /dev/null +++ b/app/model/camera.js @@ -0,0 +1,125 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, INTEGER, DATE, TINYINT } = app.Sequelize; + + const Camera = app.model.define('camera', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + server_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属录像服务器ID,关联 wms_camera_server.id', + }, + channel_id: { + type: INTEGER.UNSIGNED, + allowNull: false, + comment: '通道编号(DVR/NVR 上的物理通道号)', + }, + channel_name: { + type: STRING(100), + allowNull: true, + comment: '通道原始名称', + }, + ip: { + type: STRING(50), + allowNull: true, + comment: '摄像头IP地址', + }, + port: { + type: INTEGER.UNSIGNED, + allowNull: true, + comment: 'SDK管理端口(通常2020/8000)', + }, + model: { + type: STRING(100), + allowNull: true, + comment: '摄像头型号', + }, + serial_number: { + type: STRING(100), + allowNull: true, + comment: '摄像头序列号', + }, + stream_type: { + type: STRING(20), + allowNull: true, + comment: '码流类型(auto/main/sub)', + }, + username: { + type: STRING(100), + allowNull: true, + comment: '摄像头登录用户名', + }, + password: { + type: STRING(100), + allowNull: true, + comment: '摄像头登录密码', + }, + custom_name: { + type: STRING(100), + allowNull: true, + comment: '自定义摄像头名称', + }, + status: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_camera', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '摄像头表', + indexes: [ + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_server_id', fields: [ 'server_id' ] }, + { name: 'uk_server_channel', unique: true, fields: [ 'server_id', 'channel_id', 'deleted_at' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + Camera.associate = () => { + app.model.Camera.belongsTo(app.model.CameraServer, { + foreignKey: 'server_id', + targetKey: 'id', + as: 'server', + }); + }; + + return Camera; +}; diff --git a/app/model/camera_server.js b/app/model/camera_server.js new file mode 100644 index 0000000..900a202 --- /dev/null +++ b/app/model/camera_server.js @@ -0,0 +1,100 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, INTEGER, DATE, TINYINT } = app.Sequelize; + + const CameraServer = app.model.define('camera_server', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '服务器名称', + }, + brand: { + type: STRING(50), + allowNull: true, + comment: '品牌(如 Hikvision/Dahua)', + }, + public_ip: { + type: STRING(50), + allowNull: true, + comment: '公网IP', + }, + internal_ip: { + type: STRING(50), + allowNull: true, + comment: '内网IP', + }, + public_port: { + type: INTEGER.UNSIGNED, + allowNull: true, + comment: '远程/公网端口', + }, + internal_port: { + type: INTEGER.UNSIGNED, + allowNull: true, + comment: '本地/内网端口', + }, + username: { + type: STRING(100), + allowNull: true, + comment: '登录账号', + }, + password: { + type: STRING(200), + allowNull: true, + comment: '登录密码', + }, + status: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_camera_server', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '录像服务器表', + indexes: [ + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return CameraServer; +}; diff --git a/app/model/client_error_log.js b/app/model/client_error_log.js new file mode 100644 index 0000000..516b329 --- /dev/null +++ b/app/model/client_error_log.js @@ -0,0 +1,112 @@ +'use strict'; + +/** + * 客户端错误日志暂存表模型(wms_client_error_log)。 + * + * Android/iOS/Web 等设备端通过 index.uploadClientErrorLog 上报的运行时错误日志暂存, + * 仅做数据落库供人工/后台查询分析;report_uuid 唯一索引承担幂等去重(重复上报静默成功)。 + * created_at/updated_at 由 Sequelize 时间戳统一取服务器当前时间,不采信客户端时间。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE, TEXT } = app.Sequelize; + + const ClientErrorLog = app.model.define('client_error_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + client_type: { + type: STRING(32), + allowNull: false, + defaultValue: '', + comment: '客户端类型:android/ios/web 等', + }, + app_version: { + type: STRING(64), + allowNull: false, + defaultValue: '', + comment: '客户端版本号', + }, + device_id: { + type: STRING(128), + allowNull: false, + defaultValue: '', + comment: '设备唯一标识', + }, + os_version: { + type: STRING(64), + allowNull: false, + defaultValue: '', + comment: '操作系统版本', + }, + device_model: { + type: STRING(128), + allowNull: false, + defaultValue: '', + comment: '设备型号', + }, + error_type: { + type: STRING(64), + allowNull: false, + defaultValue: '', + comment: '错误类型/等级', + }, + error_message: { + type: TEXT, + allowNull: true, + comment: '错误信息(服务端截断上限 5000 字符)', + }, + error_stack: { + type: TEXT('medium'), + allowNull: true, + comment: '错误堆栈(服务端截断上限 65535 字符)', + }, + extra: { + type: TEXT, + allowNull: true, + comment: '附加上下文(JSON 字符串,服务端截断上限 65535 字符)', + }, + report_uuid: { + type: STRING(64), + allowNull: false, + defaultValue: '', + comment: '客户端上报幂等ID(唯一索引,重复上报静默成功)', + }, + client_time: { + type: DATE, + allowNull: true, + comment: '客户端错误发生时间(仅参考,不作为记录时间)', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '服务端写入时间(统一取服务器当前时间)', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_client_error_log', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '客户端错误日志暂存表(设备端运行时错误上报暂存)', + indexes: [ + { name: 'uk_report_uuid', unique: true, fields: [ 'report_uuid' ] }, + { name: 'idx_created_at', fields: [ 'created_at' ] }, + { name: 'idx_client_type_app_version', fields: [ 'client_type', 'app_version' ] }, + { name: 'idx_device_id', fields: [ 'device_id' ] }, + ], + }); + + return ClientErrorLog; +}; diff --git a/app/model/container.js b/app/model/container.js new file mode 100644 index 0000000..910c43c --- /dev/null +++ b/app/model/container.js @@ -0,0 +1,81 @@ +'use strict'; + +/** + * 容器(篮筐)资产登记表 Model。 + * + * 对应数据库表 `wms_container`,登记仓库的物理容器(篮筐)资产: + * 容器编号、使用状态、是否损坏、损坏说明、备注等。 + * 同一仓库内容器编号唯一,通过 warehouse_id 做数据隔离维度。 + * 后续散单拣货把购物车商品临时转移到容器时,通过 status 标记占用/空闲。 + * @param {import('egg').Application} app - Egg 应用实例 + */ +module.exports = app => { + const { BIGINT, STRING, ENUM } = app.Sequelize; + + const Container = app.model.define('wms_container', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + container_no: { + type: STRING(50), + allowNull: false, + comment: '容器编号(篮筐编号)', + }, + status: { + type: ENUM('idle', 'in_use'), + allowNull: false, + defaultValue: 'idle', + comment: '使用状态:idle=空闲 in_use=占用(散单商品临时转移)', + }, + is_damaged: { + type: ENUM('Y', 'N'), + allowNull: false, + defaultValue: 'N', + comment: '是否损坏:Y=损坏 N=正常', + }, + damage_remark: { + type: STRING(255), + allowNull: true, + comment: '损坏说明', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '登记人账户ID', + }, + creator_name: { + type: STRING(50), + allowNull: true, + comment: '登记人名称快照', + }, + }, { + tableName: 'wms_container', + comment: '容器(篮筐)资产登记表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'uk_warehouse_container_no', unique: true, fields: [ 'warehouse_id', 'container_no' ] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + { name: 'idx_is_damaged', fields: [ 'is_damaged' ] }, + ], + }); + + return Container; +}; diff --git a/app/model/embargo_policy.js b/app/model/embargo_policy.js new file mode 100644 index 0000000..bfce9c9 --- /dev/null +++ b/app/model/embargo_policy.js @@ -0,0 +1,107 @@ +// app/model/embargo_policy.js +'use strict'; + +module.exports = app => { + const { INTEGER, STRING, ENUM, TEXT, DATEONLY, DATE, BOOLEAN, BIGINT } = app.Sequelize; + + const EmbargoPolicy = app.model.define('wms_embargo_policies', { + id: { + type: INTEGER.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: 'ID', + }, + policy_name: { + type: STRING(100), + allowNull: false, + comment: '策略名称', + }, + status: { + type: ENUM('ACTIVE', 'INACTIVE', 'PENDING', 'EXPIRED'), + allowNull: true, + defaultValue: 'PENDING', + comment: '状态', + }, + embargo_scope: { + type: TEXT, + allowNull: true, + comment: '禁运范围(数组)', + }, + start_date: { + type: DATEONLY, + allowNull: false, + comment: '生效开始日期', + }, + end_date: { + type: DATEONLY, + allowNull: true, + defaultValue: null, + comment: '结束日期', + }, + is_permanent: { + type: BOOLEAN, + allowNull: true, + defaultValue: false, + comment: '是否永久有效', + }, + description: { + type: TEXT, + allowNull: true, + comment: '策略描述', + }, + created_by: { + type: STRING(50), + allowNull: true, + comment: '创建人', + }, + updated_by: { + type: STRING(50), + allowNull: true, + comment: '更新人', + }, + created_at: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID', + }, + }, { + tableName: 'wms_embargo_policies', + timestamps: false, + underscored: false, + comment: '禁运策略主表', + indexes: [ + { + name: 'idx_status', + fields: [ 'status' ], + }, + { + name: 'idx_dates', + fields: [ 'start_date', 'end_date' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + { + name: 'warehouse_id', + fields: [ 'warehouse_id' ], + }, + ], + }); + + return EmbargoPolicy; +}; diff --git a/app/model/entry_items.js b/app/model/entry_items.js index 5eb9cb1..e213358 100644 --- a/app/model/entry_items.js +++ b/app/model/entry_items.js @@ -128,6 +128,8 @@ module.exports = app => { foreignKey: 'stock_id', as: 'stock', }); + + }; // 实例方法 - 验证收货数量 @@ -191,76 +193,8 @@ module.exports = app => { }; }; - // 静态方法 - 批量更新收货数量(带验证) - EntryItems.batchUpdateReceived = async function(app, updates, options = {}) { - const transaction = options.transaction || await app.model.transaction(); - - try { - // 先检查所有更新是否合法 - for (const update of updates) { - const { id, quantity } = update; - const item = await app.model.EntryItems.findByPk(id, { transaction }); - - if (!item) { - throw new Error(`入库明细 ${id} 不存在`); - } - - // 验证数量 - item.validateReceiveQuantity(quantity); - } - - // 执行更新 - for (const update of updates) { - const { id, quantity } = update; - const item = await app.model.EntryItems.findByPk(id, { transaction }); - - const newReceived = (item.received_quantity || 0) + quantity; - await item.update({ - received_quantity: newReceived, - }, { transaction }); - } - - if (!options.transaction) { - await transaction.commit(); - } - - return { success: true }; - } catch (error) { - if (!options.transaction) { - await transaction.rollback(); - } - throw error; - } - }; - - // 静态方法 - 获取入库单总进度 - EntryItems.getOrderProgress = async function(app, orderId) { - const items = await app.model.EntryItems.findAll({ - where: { order_id: orderId }, - attributes: [ - [ app.Sequelize.fn('SUM', app.Sequelize.col('count')), 'total_plan' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('received_quantity')), 'total_received' ], - [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'item_count' ], - ], - raw: true, - }); - - const result = items[0] || {}; - const totalPlan = parseInt(result.total_plan) || 0; - const totalReceived = parseInt(result.total_received) || 0; - - return { - total_plan: totalPlan, - total_received: totalReceived, - total_remaining: Math.max(0, totalPlan - totalReceived), - item_count: parseInt(result.item_count) || 0, - progress_percent: totalPlan > 0 ? Math.min(100, Math.round((totalReceived / totalPlan) * 100)) : 0, - is_completed: totalReceived >= totalPlan, - }; - }; - // 钩子函数 - 保存前验证 - EntryItems.beforeSave(async (instance, options) => { + EntryItems.beforeSave(async instance => { const received = instance.received_quantity || 0; const plan = instance.count || 0; @@ -278,7 +212,7 @@ module.exports = app => { }); // 钩子函数 - 更新前验证 - EntryItems.beforeUpdate(async (instance, options) => { + EntryItems.beforeUpdate(async instance => { // 如果更新了received_quantity,进行验证 if (instance.changed('received_quantity')) { const received = instance.received_quantity || 0; diff --git a/app/model/entry_order.js b/app/model/entry_order.js index 6de6b95..5c63bf6 100644 --- a/app/model/entry_order.js +++ b/app/model/entry_order.js @@ -19,7 +19,7 @@ module.exports = app => { }, }, order_type: { - type: ENUM('SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK'), + type: ENUM('SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK', 'SHRK'), allowNull: false, comment: '业务类型', }, @@ -81,10 +81,10 @@ module.exports = app => { comment: '来源类型', }, order_status: { - type: ENUM('PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED', 'CREATED', 'CREATING'), + type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'), allowNull: false, - defaultValue: 'PENDING', - comment: '订单状态', + defaultValue: 'CREATED', + comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废', }, sync_status: { type: ENUM('PENDING', 'SUCCESS', 'FAILED'), @@ -137,6 +137,18 @@ module.exports = app => { allowNull: true, comment: 'ERP备注', }, + expense_record: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '费用是否记录', + }, + is_virtual_inbound: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否虚拟入库:0=否 1=是', + }, store_name: { type: STRING(200), allowNull: true, @@ -209,7 +221,7 @@ module.exports = app => { // 关联关系 EntryOrder.associate = function() { - const { EntryOrder, Store, EntryItems } = app.model; + const { EntryOrder, Store, EntryItems, EntryOrderReceiving } = app.model; // 关联仓库 EntryOrder.belongsTo(Store, { @@ -228,15 +240,21 @@ module.exports = app => { foreignKey: 'order_id', as: 'items', }); + + // 关联入库单-收货单绑定记录 + EntryOrder.hasMany(EntryOrderReceiving, { + foreignKey: 'entry_order_id', + as: 'receivingBindings', + }); }; // 实例方法 - EntryOrder.prototype.isPending = function() { - return this.order_status === 'PENDING'; + EntryOrder.prototype.isCreated = function() { + return this.order_status === 'CREATED'; }; - EntryOrder.prototype.isConfirmed = function() { - return this.order_status === 'CONFIRMED'; + EntryOrder.prototype.isPending = function() { + return this.order_status === 'PENDING'; }; EntryOrder.prototype.isCompleted = function() { @@ -247,20 +265,16 @@ module.exports = app => { return this.order_status === 'CANCELLED'; }; - EntryOrder.prototype.isPartialReceived = function() { - return this.order_status === 'PARTIAL_RECEIVED'; - }; - EntryOrder.prototype.canConfirm = function() { - return [ 'PENDING', 'CREATED' ].includes(this.order_status); + return [ 'CREATED', 'PENDING' ].includes(this.order_status); }; EntryOrder.prototype.canCancel = function() { - return [ 'PENDING', 'CONFIRMED', 'CREATED' ].includes(this.order_status); + return [ 'CREATED', 'PENDING' ].includes(this.order_status); }; EntryOrder.prototype.canComplete = function() { - return [ 'CONFIRMED', 'PARTIAL_RECEIVED' ].includes(this.order_status); + return [ 'PENDING' ].includes(this.order_status); }; EntryOrder.prototype.isSyncSuccess = function() { @@ -275,237 +289,5 @@ module.exports = app => { return this.is_enabled === 1 && !this.deleted_at; }; - // 静态方法 - EntryOrder.findByOrderCode = async function(app, entryOrderCode, warehouseId, storeId) { - return await app.model.EntryOrder.findOne({ - where: { - entry_order_code: entryOrderCode, - warehouse_id: warehouseId, - store_id: storeId, - is_enabled: 1, - deleted_at: null, - }, - include: [ - { - model: app.model.Store, - as: 'warehouse', - attributes: [ 'store_name', 'store_code' ], - }, - { - model: app.model.Store, - as: 'store', - attributes: [ 'store_name' ], - }, - { - model: app.model.EntryItems, - as: 'items', - include: [{ - model: app.model.StockWarehouse, - as: 'stock', - attributes: [ 'product_code', 'product_name' ], - }], - }, - ], - }); - }; - - EntryOrder.findByStatus = async function(app, status, params = {}) { - const { warehouse_id, store_id, start_date, end_date, page = 1, pageSize = 20 } = params; - - const where = { - order_status: status, - is_enabled: 1, - deleted_at: null, - }; - - if (warehouse_id) { - where.warehouse_id = warehouse_id; - } - - if (store_id) { - where.store_id = store_id; - } - - if (start_date || end_date) { - where.created_at = {}; - if (start_date) { - where.created_at[app.Sequelize.Op.gte] = start_date; - } - if (end_date) { - where.created_at[app.Sequelize.Op.lte] = end_date; - } - } - - const { count, rows } = await app.model.EntryOrder.findAndCountAll({ - where, - include: [ - { - model: app.model.Store, - as: 'warehouse', - attributes: [ 'store_name' ], - }, - { - model: app.model.Store, - as: 'store', - attributes: [ 'store_name' ], - }, - ], - order: [[ 'created_at', 'DESC' ]], - offset: (page - 1) * pageSize, - limit: parseInt(pageSize), - distinct: true, - }); - - return { - list: rows, - pagination: { - page: parseInt(page), - pageSize: parseInt(pageSize), - total: count, - totalPages: Math.ceil(count / pageSize), - }, - }; - }; - - EntryOrder.getStatsByWarehouse = async function(app, warehouseId, startDate, endDate) { - const where = { - warehouse_id: warehouseId, - is_enabled: 1, - deleted_at: null, - }; - - if (startDate || endDate) { - where.created_at = {}; - if (startDate) { - where.created_at[app.Sequelize.Op.gte] = startDate; - } - if (endDate) { - where.created_at[app.Sequelize.Op.lte] = endDate; - } - } - - const result = await app.model.EntryOrder.findAll({ - attributes: [ - 'order_status', - [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'count' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('total_order_lines')), 'total_lines' ], - ], - where, - group: [ 'order_status' ], - raw: true, - }); - - const stats = { - pending: 0, - confirmed: 0, - partial_received: 0, - completed: 0, - cancelled: 0, - total: 0, - total_lines: 0, - }; - - result.forEach(item => { - const status = item.order_status.toLowerCase(); - if (stats[status] !== undefined) { - stats[status] = parseInt(item.count) || 0; - } - stats.total += parseInt(item.count) || 0; - stats.total_lines += parseInt(item.total_lines) || 0; - }); - - return stats; - }; - - EntryOrder.updateSyncStatus = async function(app, orderId, status, message = null) { - const order = await app.model.EntryOrder.findByPk(orderId); - - if (!order) { - throw new Error('入库单不存在'); - } - - const updateData = { - sync_status: status, - }; - - if (message !== null) { - updateData.sync_message = message; - } - - return await order.update(updateData); - }; - - EntryOrder.updateOrderStatus = async function(app, orderId, status) { - const order = await app.model.EntryOrder.findByPk(orderId); - - if (!order) { - throw new Error('入库单不存在'); - } - - const validTransitions = { - PENDING: [ 'CONFIRMED', 'CANCELLED' ], - CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ], - PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ], - CREATED: [ 'PENDING', 'CANCELLED' ], - CREATING: [ 'PENDING', 'CANCELLED' ], - }; - - const allowedTransitions = validTransitions[order.order_status]; - if (!allowedTransitions || !allowedTransitions.includes(status)) { - throw new Error(`状态从${order.order_status}转换到${status}不被允许`); - } - - return await order.update({ order_status: status }); - }; - - EntryOrder.calculateReceivedQuantities = async function(app, orderId) { - // 这里需要根据实际业务逻辑计算已收货数量 - // 通常需要查询入库明细和实际收货记录 - - // 示例:查询入库明细 - const items = await app.model.EntryItems.findAll({ - where: { order_id: orderId }, - attributes: [ - 'id', - 'count', - [ app.Sequelize.literal('(SELECT SUM(quantity) FROM wms_storage WHERE inbound_order_no = wms_entry_order.entry_order_code AND item_id = wms_entry_items.item_id)'), 'received' ], - ], - include: [{ - model: app.model.EntryOrder, - as: 'order', - attributes: [ 'entry_order_code' ], - }], - }); - - let totalExpected = 0; - let totalReceived = 0; - let allReceived = true; - let anyReceived = false; - - items.forEach(item => { - const expected = item.count || 0; - const received = item.received || 0; - - totalExpected += expected; - totalReceived += received; - - if (expected > 0 && received < expected) { - allReceived = false; - } - - if (received > 0) { - anyReceived = true; - } - }); - - return { - total_expected: totalExpected, - total_received: totalReceived, - all_received: allReceived, - any_received: anyReceived, - percentage: totalExpected > 0 ? Math.round((totalReceived / totalExpected) * 100) : 0, - }; - }; - return EntryOrder; }; diff --git a/app/model/entry_order_receiving.js b/app/model/entry_order_receiving.js new file mode 100644 index 0000000..4fbdd46 --- /dev/null +++ b/app/model/entry_order_receiving.js @@ -0,0 +1,82 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const EntryOrderReceiving = app.model.define('wms_entry_order_receiving', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '入库单ID,关联 wms_entry_order.id', + }, + receiving_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '收货单ID,关联 wms_receiving.id', + }, + allocated_quantity: { + type: JSON_TYPE, + allowNull: true, + defaultValue: null, + comment: '数量台账:收货明细ID→已分配数量(JSON对象,如 {"123":8});null 表示旧数据未初始化', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_entry_order_receiving', + comment: '入库单-收货单主表级绑定关系表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + indexes: [ + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'uk_entry_order_receiving', + unique: true, + fields: [ 'entry_order_id', 'receiving_id' ], + }, + ], + }); + + // 关联关系 + EntryOrderReceiving.associate = function() { + const { EntryOrderReceiving, EntryOrder, Receiving } = app.model; + + // 关联入库单 + EntryOrderReceiving.belongsTo(EntryOrder, { + foreignKey: 'entry_order_id', + as: 'entryOrder', + }); + + // 关联收货单 + EntryOrderReceiving.belongsTo(Receiving, { + foreignKey: 'receiving_id', + as: 'receiving', + }); + }; + + return EntryOrderReceiving; +}; diff --git a/app/model/entry_receiving_binding.js b/app/model/entry_receiving_binding.js new file mode 100644 index 0000000..1f7fffc --- /dev/null +++ b/app/model/entry_receiving_binding.js @@ -0,0 +1,99 @@ +'use strict'; + +module.exports = app => { + const { INTEGER, BIGINT, ENUM, DATE } = app.Sequelize; + + const EntryReceivingBinding = app.model.define('wms_entry_receiving_binding', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + entry_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '入库明细ID', + }, + receiving_detail_id: { + type: INTEGER, + allowNull: false, + comment: '收货明细ID', + }, + allocated_quantity: { + type: INTEGER, + allowNull: false, + comment: '预分配数量', + validate: { + min: 1, + }, + }, + status: { + type: ENUM('pending', 'committed', 'released'), + allowNull: false, + defaultValue: 'pending', + comment: '绑定状态:pending-待提交 committed-已提交 released-已释放', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人ID', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_entry_receiving_binding', + comment: '入库单明细-收货明细绑定关系表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + indexes: [ + { + name: 'idx_entry_item_id', + fields: [ 'entry_item_id' ], + }, + { + name: 'idx_receiving_detail_id', + fields: [ 'receiving_detail_id' ], + }, + { + name: 'idx_status', + fields: [ 'status' ], + }, + { + name: 'uk_entry_receiving', + unique: true, + fields: [ 'entry_item_id', 'receiving_detail_id', 'status' ], + }, + ], + }); + + // 关联关系 + EntryReceivingBinding.associate = function() { + const { EntryReceivingBinding, EntryItems, ReceivingDetail } = app.model; + + // 关联入库明细 + EntryReceivingBinding.belongsTo(EntryItems, { + foreignKey: 'entry_item_id', + as: 'entryItem', + }); + + // 关联收货明细 + EntryReceivingBinding.belongsTo(ReceivingDetail, { + foreignKey: 'receiving_detail_id', + as: 'receivingDetail', + }); + }; + + return EntryReceivingBinding; +}; diff --git a/app/model/express.js b/app/model/express.js new file mode 100644 index 0000000..3da646e --- /dev/null +++ b/app/model/express.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 定义快递基础信息模型。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 快递模型 + */ +module.exports = app => { + const { STRING, JSON } = app.Sequelize; + + const Express = app.model.define('express', { + code: { + type: STRING(50), + primaryKey: true, + allowNull: false, + comment: '快递编码', + }, + name: { + type: STRING(255), + allowNull: true, + comment: '快递名称', + }, + KS: { + type: STRING(255), + field: 'KS', + allowNull: true, + comment: '快手编码', + }, + polyapi_extra_info: { + type: JSON, + allowNull: true, + comment: '聚合接口扩展信息', + }, + PDD: { + field: 'PDD', + type: STRING(255), + allowNull: true, + comment: '拼多多编码', + }, + DY: { + field: 'DY', + type: STRING(255), + allowNull: true, + comment: '抖音编码', + }, + CAINIAO: { + field: 'CAINIAO', + type: STRING(255), + allowNull: true, + comment: '菜鸟编码', + }, + SPH: { + field: 'SPH', + type: STRING(255), + allowNull: true, + comment: 'SPH编码', + }, + XHS: { + field: 'XHS', + type: STRING(255), + allowNull: true, + comment: '小红书编码', + }, + DW: { + field: 'DW', + type: STRING(255), + allowNull: true, + comment: 'DW编码', + }, + JD: { + field: 'JD', + type: STRING(255), + allowNull: true, + comment: '京东编码', + }, + }, { + tableName: 'wms_express', + freezeTableName: true, + underscored: true, + timestamps: false, + paranoid: false, + comment: '快递基础信息表', + }); + + return Express; +}; diff --git a/app/model/express_interface.js b/app/model/express_interface.js new file mode 100644 index 0000000..b849d6e --- /dev/null +++ b/app/model/express_interface.js @@ -0,0 +1,260 @@ +'use strict'; + +/** + * 定义快递接口配置模型。 + * @param {Object} app Egg 应用对象。 + * @return {Object} 快递接口配置模型。 + */ +module.exports = app => { + const { INTEGER, STRING, BIGINT, TINYINT, JSON } = app.Sequelize; + + const ExpressInterface = app.model.define('express_interface', { + id: { + type: INTEGER(11).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + name: { + type: STRING(255), + allowNull: true, + comment: '接口名称', + }, + express_code: { + type: STRING(255), + allowNull: false, + comment: '快递编码', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '平台编码', + }, + sys_express_code: { + type: STRING(50), + allowNull: false, + comment: '系统快递编码', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '仓库编码', + }, + shop_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '店铺ID', + }, + platform_shop_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '平台店铺ID', + }, + template_id: { + type: STRING(50), + allowNull: true, + comment: '模板ID', + }, + paymode: { + type: INTEGER(11), + allowNull: true, + comment: '付款方式', + }, + brandno: { + type: STRING(255), + allowNull: true, + comment: '品牌编码', + }, + providertype: { + type: STRING(50), + allowNull: true, + comment: '服务商类型编码', + }, + providerid: { + type: INTEGER(11), + allowNull: true, + comment: '服务商ID', + }, + sender_name: { + type: STRING(50), + allowNull: true, + comment: '寄件人', + }, + sender_tel: { + type: STRING(11), + allowNull: true, + comment: '寄件电话', + }, + weight: { + type: INTEGER(11), + allowNull: true, + comment: '排序', + }, + token: { + type: STRING(500), + allowNull: true, + comment: '令牌', + }, + viewer: { + type: STRING(50), + allowNull: true, + comment: '验视员', + }, + client_id: { + type: STRING(50), + allowNull: true, + comment: '客户id', + }, + is_share: { + type: TINYINT(1), + allowNull: true, + defaultValue: 0, + comment: '是否分享接口', + }, + share_id: { + type: INTEGER(11).UNSIGNED, + allowNull: true, + comment: '分享id', + }, + can_use_count: { + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '可用数量', + }, + province_name: { + type: STRING(255), + allowNull: true, + comment: '寄件人名称', + }, + city_name: { + type: STRING(255), + allowNull: true, + comment: '寄件人城市', + }, + district_name: { + type: STRING(255), + allowNull: true, + comment: '寄件人区/县', + }, + site_code: { + type: STRING(255), + allowNull: true, + comment: '网点编码', + }, + product_type: { + type: STRING(50), + allowNull: true, + comment: '产品编码', + }, + weight_type: { + type: INTEGER(10), + allowNull: true, + comment: '重量类型', + }, + shop_name: { + type: STRING(255), + allowNull: true, + comment: '平台店铺', + }, + address: { + type: STRING(255), + allowNull: true, + comment: '地址', + }, + town_name: { + type: STRING(255), + allowNull: true, + comment: '寄件人街道', + }, + ispickup: { + type: TINYINT(1), + allowNull: true, + defaultValue: 0, + comment: '是否上门取件', + }, + is_hide_goods: { + type: TINYINT(1), + allowNull: true, + defaultValue: 0, + comment: '是否隐藏物品信息', + }, + is_enabled: { + type: TINYINT(1), + allowNull: true, + defaultValue: 1, + comment: '是否启用(1=启用,0=停用)', + }, + shipperno: { + type: STRING(255), + allowNull: true, + comment: '寄件网点编码', + }, + template_url: { + type: STRING(500), + allowNull: true, + comment: '打印模板链接', + }, + ext_data: { + type: JSON, + allowNull: true, + comment: '扩展信息', + }, + }, { + tableName: 'wms_express_interface', + freezeTableName: true, + underscored: true, + timestamps: false, + paranoid: false, + comment: '快递接口配置表', + indexes: [ + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + ], + }); + + /** + * 定义快递接口与系统快递、店铺、打印平台的关联关系。 + * + * 说明: + * - `wms_express_interface.sys_express_code` 对应 `wms_express.code` + * - `wms_express_interface.shop_id` 对应 `wms_shops.id` + * - `wms_express_interface.platform_code` 对应 `wms_print_platform.platform_code` + */ + ExpressInterface.associate = function() { + const { Express, Shop, PrintPlatform } = app.model; + + if (Express && typeof ExpressInterface.belongsTo === 'function') { + ExpressInterface.belongsTo(Express, { + foreignKey: 'sys_express_code', + targetKey: 'code', + as: 'express', + constraints: false, + }); + } + + if (Shop && typeof ExpressInterface.belongsTo === 'function') { + ExpressInterface.belongsTo(Shop, { + foreignKey: 'shop_id', + targetKey: 'id', + as: 'shop', + constraints: false, + }); + } + + if (PrintPlatform && typeof ExpressInterface.belongsTo === 'function') { + ExpressInterface.belongsTo(PrintPlatform, { + foreignKey: 'platform_code', + targetKey: 'platform_code', + as: 'printPlatform', + constraints: false, + }); + } + + }; + + return ExpressInterface; +}; diff --git a/app/model/express_print_record.js b/app/model/express_print_record.js new file mode 100644 index 0000000..3125a68 --- /dev/null +++ b/app/model/express_print_record.js @@ -0,0 +1,229 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE, TEXT, JSON } = app.Sequelize; + + const ExpressPrintRecord = app.model.define('express_print_record', { + id: { + type: BIGINT(20), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_id: { + type: BIGINT(20), + allowNull: false, + comment: '快递记录ID', + }, + order_id: { + type: STRING(50), + allowNull: false, + comment: '订单ID', + }, + express_no: { + type: STRING(50), + allowNull: false, + comment: '快递单号', + }, + platform: { + type: STRING(50), + allowNull: false, + comment: '平台编码', + }, + template_id: { + type: BIGINT(20), + allowNull: false, + comment: '模板ID', + }, + template_url: { + type: STRING(500), + allowNull: true, + comment: '模板URL', + }, + printer_name: { + type: STRING(100), + allowNull: true, + comment: '打印机名称', + }, + printer_config_id: { + type: BIGINT(20), + allowNull: true, + comment: '打印配置ID', + }, + print_data: { + type: JSON, + allowNull: false, + comment: '打印请求数据', + }, + encrypted_data: { + type: TEXT, + allowNull: true, + comment: '加密数据', + }, + signature: { + type: STRING(500), + allowNull: true, + comment: '签名', + }, + add_data: { + type: JSON, + allowNull: true, + comment: '附加数据', + }, + custom_data: { + type: JSON, + allowNull: true, + comment: '自定义数据', + }, + print_status: { + type: STRING(20), + allowNull: false, + defaultValue: 'PENDING', + comment: '打印状态', + }, + print_count: { + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '打印次数', + }, + last_print_time: { + type: DATE, + allowNull: true, + comment: '最近打印时间', + }, + next_retry_time: { + type: DATE, + allowNull: true, + comment: '下次重试时间', + }, + request_id: { + type: STRING(100), + allowNull: true, + comment: '请求ID', + }, + document_id: { + type: STRING(100), + allowNull: true, + comment: '文档ID', + }, + batch_no: { + type: STRING(50), + allowNull: true, + comment: '批次号', + }, + print_result: { + type: TEXT, + allowNull: true, + comment: '打印结果', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '错误信息', + }, + print_cost_time: { + type: INTEGER(11), + allowNull: true, + comment: '打印耗时(ms)', + }, + create_interface: { + type: STRING(100), + allowNull: true, + comment: '创建接口名', + }, + print_interface: { + type: STRING(100), + allowNull: true, + comment: '打印接口名', + }, + operator_id: { + type: BIGINT(20), + allowNull: true, + comment: '操作人ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '仓库ID', + }, + create_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + print_time: { + type: DATE, + allowNull: true, + comment: '打印时间', + }, + update_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_express_print_record', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '快递面单打印记录表', + indexes: [ + { + unique: true, + name: 'uk_express_print', + fields: [ 'express_id', 'print_status' ], + }, + { + unique: true, + name: 'uk_request_id', + fields: [ 'request_id' ], + }, + { + name: 'idx_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_express_no', + fields: [ 'express_no' ], + }, + { + name: 'idx_platform', + fields: [ 'platform' ], + }, + { + name: 'idx_print_status', + fields: [ 'print_status' ], + }, + { + name: 'idx_create_time', + fields: [ 'create_time' ], + }, + { + name: 'idx_batch_no', + fields: [ 'batch_no' ], + }, + { + name: 'idx_template_id', + fields: [ 'template_id' ], + }, + { + name: 'idx_printer_config_id', + fields: [ 'printer_config_id' ], + }, + { + name: 'idx_print_time', + fields: [ 'print_time' ], + }, + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + ], + }); + + return ExpressPrintRecord; +}; diff --git a/app/model/express_product_type.js b/app/model/express_product_type.js new file mode 100644 index 0000000..d26a0c8 --- /dev/null +++ b/app/model/express_product_type.js @@ -0,0 +1,44 @@ +'use strict'; + +/** + * 定义快递产品类型模型。 + * @param {Object} app Egg 应用对象。 + * @return {Object} 快递产品类型模型。 + */ +module.exports = app => { + const { INTEGER, STRING } = app.Sequelize; + + const ExpressProductType = app.model.define('express_product_type', { + id: { + type: INTEGER(11).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + name: { + type: STRING(255), + allowNull: true, + comment: '产品名称', + }, + express_code: { + type: STRING(50), + allowNull: true, + comment: '物流编码', + }, + code: { + type: STRING(50), + allowNull: true, + comment: '产品编码', + }, + }, { + tableName: 'wms_express_product_type', + freezeTableName: true, + underscored: true, + timestamps: false, + paranoid: false, + comment: '快递产品类型表', + }); + + return ExpressProductType; +}; diff --git a/app/model/express_setting.js b/app/model/express_setting.js new file mode 100644 index 0000000..4568e19 --- /dev/null +++ b/app/model/express_setting.js @@ -0,0 +1,58 @@ +'use strict'; + +module.exports = app => { + const { INTEGER, STRING, BIGINT, DATE } = app.Sequelize; + + const ExpressSetting = app.model.define('express_setting', { + id: { + type: INTEGER(11), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_code: { + type: STRING(50), + allowNull: false, + comment: '系统快递编码', + }, + code: { + type: STRING(50), + allowNull: false, + comment: '自设编码', + }, + name: { + type: STRING(50), + allowNull: false, + comment: '别名', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库主体ID', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + tableName: 'wms_express_setting', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '快递配置表', + indexes: [ + { + name: 'idx_express_code', + fields: [ 'express_code' ], + }, + { + name: 'idx_warehouse_deleted_at', + fields: [ 'warehouse_id', 'deleted_at' ], + }, + ], + }); + + return ExpressSetting; +}; diff --git a/app/model/file.js b/app/model/file.js index ab10e36..785def8 100644 --- a/app/model/file.js +++ b/app/model/file.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, INTEGER, STRING, TEXT, DATE, BOOLEAN } = app.Sequelize; + const { BIGINT, INTEGER, STRING, DATE, BOOLEAN } = app.Sequelize; const File = app.model.define('wms_file', { id: { @@ -102,6 +102,12 @@ module.exports = app => { defaultValue: null, comment: '更新时间', }, + expire_time: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '过期时间,为空表示永不过期', + }, is_deleted: { type: BOOLEAN, allowNull: false, diff --git a/app/model/file_reference.js b/app/model/file_reference.js index b90a8db..fe4ebec 100644 --- a/app/model/file_reference.js +++ b/app/model/file_reference.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, INTEGER, STRING, TEXT, DATE, BOOLEAN, JSON: JSON_TYPE } = app.Sequelize; + const { BIGINT, INTEGER, STRING, DATE } = app.Sequelize; const FileReference = app.model.define('wms_file_reference', { id: { diff --git a/app/model/i18n_key.js b/app/model/i18n_key.js index eb96cbc..4516877 100644 --- a/app/model/i18n_key.js +++ b/app/model/i18n_key.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, DATE } = app.Sequelize; + const { STRING, INTEGER } = app.Sequelize; const I18nKey = app.model.define('wms_i18n_key', { id: { diff --git a/app/model/i18n_translation.js b/app/model/i18n_translation.js index 0e20141..b8fe0e6 100644 --- a/app/model/i18n_translation.js +++ b/app/model/i18n_translation.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, DATE, Op } = app.Sequelize; + const { STRING, INTEGER } = app.Sequelize; // 直接在文件中定义常量 const CONSTANTS = { @@ -60,123 +60,5 @@ module.exports = app => { // 挂载常量到模型(可选) I18nTranslation.CONSTANTS = CONSTANTS; - /** - * 获取翻译 - * @param keyId - * @param language - */ - I18nTranslation.getTranslation = async function(keyId, language) { - return await this.findOne({ - where: { key_id: keyId, language }, - include: [{ - model: app.model.I18nKey, - as: 'key', - }], - }); - }; - - /** - * 批量获取翻译 - * @param keyIds - * @param language - */ - I18nTranslation.batchGetTranslations = async function(keyIds, language) { - const records = await this.findAll({ - where: { - key_id: keyIds, - language, - }, - include: [{ - model: app.model.I18nKey, - as: 'key', - attributes: [ 'key_name' ], - }], - }); - - // 返回键值对 - const result = {}; - records.forEach(record => { - if (record.key) { - result[record.key.key_name] = record.translation || record.key.key_name; - } - }); - - return result; - }; - - /** - * 获取项目翻译 - * @param project - * @param language - */ - I18nTranslation.getProjectTranslations = async function(project, language) { - const records = await this.findAll({ - include: [{ - model: app.model.I18nKey, - as: 'key', - where: { project }, - attributes: [ 'key_name' ], - }], - where: { language }, - }); - - const result = {}; - records.forEach(record => { - if (record.key && record.key.key_name) { - result[record.key.key_name] = record.translation || record.key.key_name; - } - }); - - return result; - }; - - /** - * 创建或更新翻译 - * @param keyId - * @param language - * @param translation - */ - I18nTranslation.upsertTranslation = async function(keyId, language, translation) { - const [ record, created ] = await this.findOrCreate({ - where: { key_id: keyId, language }, - defaults: { - key_id: keyId, - language, - translation: translation || null, - translation_status: translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED, - }, - }); - - if (!created) { - record.translation = translation || null; - record.translation_status = translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED; - await record.save(); - } - - return record; - }; - - /** - * 获取未翻译列表 - * @param language - * @param project - */ - I18nTranslation.getUntranslated = async function(language, project) { - return await this.findAll({ - include: [{ - model: app.model.I18nKey, - as: 'key', - where: { project }, - }], - where: { - language, - [Op.or]: [ - { translation: null }, - { translation: '' }, - ], - }, - }); - }; - return I18nTranslation; }; diff --git a/app/model/inbound_direct_log.js b/app/model/inbound_direct_log.js new file mode 100644 index 0000000..918af8b --- /dev/null +++ b/app/model/inbound_direct_log.js @@ -0,0 +1,166 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, DATE } = app.Sequelize; + + const InboundDirectLog = app.model.define('wms_inbound_direct_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + stock_id: { + type: BIGINT(20), + allowNull: false, + comment: '商品SKU ID,关联 wms_stock_warehouse.id', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + comment: '入库数量', + }, + inbound_type: { + type: ENUM('import', 'pda'), + allowNull: false, + comment: '入库方式:import-导入入库 pda-PDA入库', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID(可选),关联 wms_entry_order.id', + }, + entry_order_code: { + type: STRING(50), + allowNull: true, + comment: '入库单号(冗余,方便查询)', + }, + entry_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库明细ID', + }, + receiving_detail_id: { + type: INTEGER, + allowNull: true, + comment: '收货明细ID,绑定收货时使用', + }, + status: { + type: ENUM('pending', 'committed', 'released'), + allowNull: true, + comment: '绑定状态:pending=待提交 committed=已提交 released=已释放,非绑定模式为NULL', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注(如导入文件名、PDA操作备注等)', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '存放库位ID,关联 wms_location_space.id', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: STRING(50), + allowNull: true, + comment: '操作人名称', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_inbound_direct_log', + comment: '非收货单途径入库直接记录表(导入/PDA入库)', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + indexes: [ + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'idx_stock_id', + fields: [ 'stock_id' ], + }, + { + name: 'idx_inbound_type', + fields: [ 'inbound_type' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + { + name: 'idx_entry_item_id', + fields: [ 'entry_item_id' ], + }, + { + name: 'idx_receiving_detail_id', + fields: [ 'receiving_detail_id' ], + }, + { + name: 'idx_status', + fields: [ 'status' ], + }, + { + name: 'uk_entry_receiving_binding', + unique: true, + fields: [ 'entry_item_id', 'receiving_detail_id', 'status' ], + }, + ], + }); + + // 关联关系 + InboundDirectLog.associate = function() { + const { InboundDirectLog, EntryItems, ReceivingDetail } = app.model; + + // 关联入库明细 + InboundDirectLog.belongsTo(EntryItems, { + foreignKey: 'entry_item_id', + as: 'entryItem', + }); + + // 关联收货明细 + InboundDirectLog.belongsTo(ReceivingDetail, { + foreignKey: 'receiving_detail_id', + as: 'receivingDetail', + }); + }; + + return InboundDirectLog; +}; diff --git a/app/model/inbox_arrival_register.js b/app/model/inbox_arrival_register.js new file mode 100644 index 0000000..2fef56a --- /dev/null +++ b/app/model/inbox_arrival_register.js @@ -0,0 +1,71 @@ +'use strict'; + +/** + * 到货登记 Model。 + * 货主/仓库群发送"到货+车牌号"时,AI 提取车牌号并登记, + * 记录货主ID、仓库ID、登记时间(created_at)、车牌号。 + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING } = app.Sequelize; + + const InboxArrivalRegister = app.model.define('inbox_arrival_register', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '货主ID(仓库群登记时无货主,允许为空)', + }, + license_plate: { + type: STRING(20), + allowNull: false, + comment: '车牌号', + }, + consumed: { + type: app.Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否已消费(离场登记)0=未消费 1=已消费', + }, + consumed_at: { + type: app.Sequelize.DATE, + allowNull: true, + comment: '消费时间(离场时间)', + }, + created_at: { + type: app.Sequelize.DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '登记时间', + }, + updated_at: { + type: app.Sequelize.DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_inbox_arrival_register', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + // 表无 deleted_at 列,必须显式关闭全局 define 的 paranoid 默认值, + // 否则 findAll/findOne 会拼出 deleted_at 字段导致 Unknown column 报错 + paranoid: false, + comment: '到货登记表(货主ID、仓库ID、登记时间、车牌号)', + }); + + return InboxArrivalRegister; +}; diff --git a/app/model/inbox_block.js b/app/model/inbox_block.js new file mode 100644 index 0000000..e2fefba --- /dev/null +++ b/app/model/inbox_block.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * 站内信屏蔽表 Model。 + * 按群ID+用户ID维度屏蔽,后续来自该群+用户的消息不再触发 AI 回信。 + * group_id 和 user_id 均为 NULL 时表示全局屏蔽(预留)。 + * + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; + + const InboxBlock = app.model.define('inbox_block', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: INTEGER(10), + allowNull: false, + comment: '仓库ID', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '群ID', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '用户ID', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_inbox_block', + timestamps: false, + comment: '站内信屏蔽表', + indexes: [ + { + name: 'uk_warehouse_group_user', + unique: true, + fields: [ 'warehouse_id', 'group_id', 'user_id' ], + }, + ], + }); + + return InboxBlock; +}; diff --git a/app/model/inbox_group.js b/app/model/inbox_group.js new file mode 100644 index 0000000..2381ab5 --- /dev/null +++ b/app/model/inbox_group.js @@ -0,0 +1,122 @@ +'use strict'; + +/** + * 站内信群表 Model。 + * 记录与 WMS 交互的群信息,支持按仓库屏蔽。 + * + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const InboxGroup = app.model.define('inbox_group', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: STRING(100), + allowNull: false, + comment: '群名称', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '外部群ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + group_type: { + type: app.Sequelize.ENUM('store', 'warehouse', 'express'), + allowNull: true, + comment: '群类型: store=货主 warehouse=仓库 express=快递', + }, + sub_type: { + type: STRING(20), + allowNull: true, + comment: '群子类型: 货主(售后/财务/收货) 仓库(收货/普通/生产) 快递(揽收/售后)', + }, + source_type: { + type: STRING(20), + allowNull: true, + comment: '来源类型:im / api / system', + }, + source_extra: { + type: STRING(100), + allowNull: true, + comment: '来源附加信息', + }, + is_blocked: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否屏蔽 0=否 1=是', + }, + ai_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }, + template_reply_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否启用模板消息回复: 0=关闭(普通文本回复) 1=开启(模板消息回复)', + }, + express_interfaces: { + type: STRING(500), + allowNull: true, + comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)', + }, + system_express_code: { + type: STRING(50), + allowNull: true, + comment: '系统快递编码(仅群类型为 express 时必填)', + }, + ext_data: { + type: JSON_TYPE, + allowNull: true, + comment: '群扩展数据(IM平台信息等)', + }, + 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_inbox_group', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '站内信群表', + indexes: [ + // 群唯一性以 (warehouse_id, group_id) 为准,群名称变化只更新不建新 + { name: 'uk_warehouse_group_id', unique: true, fields: [ 'warehouse_id', 'group_id' ] }, + { name: 'idx_group_id', fields: [ 'group_id' ] }, + ], + }); + + return InboxGroup; +}; diff --git a/app/model/inbox_message.js b/app/model/inbox_message.js new file mode 100644 index 0000000..151a3b4 --- /dev/null +++ b/app/model/inbox_message.js @@ -0,0 +1,196 @@ +'use strict'; + +/** + * 站内信消息 Model。 + * 统一管理消息推送状态追踪:谁发来的、要推到哪、推送状态。 + * inbound(外部→WMS)与 outbound(WMS→外部)共表,direction + parent_id 形成对话链。 + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE, INTEGER, JSON: JSON_TYPE } = app.Sequelize; + + const InboxMessage = app.model.define('inbox_message', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + ext_id: { + type: STRING(128), + allowNull: false, + comment: '外部唯一消息主键(IM msgId / API requestId 等),用于幂等去重', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + direction: { + type: STRING(10), + allowNull: false, + defaultValue: 'inbound', + validate: { + isIn: { + args: [[ 'inbound', 'outbound' ]], + msg: 'direction 必须是 inbound 或 outbound', + }, + }, + comment: '消息方向:inbound=外部→WMS收件 / outbound=WMS→外部回信', + }, + parent_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联消息ID(回信时指向原消息,形成对话链)', + }, + source_type: { + type: STRING(20), + allowNull: false, + validate: { + isIn: { + args: [[ 'im', 'api', 'system' ]], + msg: 'source_type 必须是 im、api 或 system', + }, + }, + comment: '来源类型:im / api / system', + }, + source_extra: { + type: STRING(100), + allowNull: true, + comment: '来源附加信息(IM 平台 / API app_id)', + }, + target_type: { + type: STRING(20), + allowNull: false, + validate: { + isIn: { + args: [[ 'im', 'api', 'webhook' ]], + msg: 'target_type 必须是 im、api 或 webhook', + }, + }, + comment: '目标类型:im / api / webhook', + }, + group_name: { + type: STRING(100), + allowNull: true, + comment: '群名称(外部传入)', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '用户名称(外部传入)', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '外部群ID', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '外部用户ID', + }, + content: { + type: app.Sequelize.TEXT, + allowNull: true, + comment: '消息正文/摘要,用于列表展示和关键词搜索', + }, + ext_data: { + type: JSON_TYPE, + allowNull: true, + comment: '外部透传数据,外部传入任意JSON,WMS不解析,回信时原样返回', + }, + extend_props: { + type: JSON_TYPE, + allowNull: true, + comment: '回执扩展属性(notify.reply 的 extend_props),重推时原样带回', + }, + flags: { + type: JSON_TYPE, + allowNull: true, + comment: '处理标记,外部传入控制WMS处理行为', + }, + ai_thoughts: { + type: JSON_TYPE, + allowNull: true, + comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]', + }, + push_status: { + type: TINYINT(4), + allowNull: false, + defaultValue: 0, + validate: { + isIn: { + args: [[ 0, 1, 2, 3 ]], + msg: 'push_status 必须是 0(待推送)、1(推送中)、2(已送达)、3(失败)', + }, + }, + comment: '推送状态:0=待推送 1=推送中 2=已送达 3=失败', + }, + push_started_at: { + type: DATE, + allowNull: true, + comment: '开始推送时间(僵尸检测:超5分钟仍为1则重置为0)', + }, + retry_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '已重试次数', + }, + push_response: { + type: JSON_TYPE, + allowNull: true, + comment: '目标响应(http_status, body, error)', + }, + pushed_at: { + type: DATE, + allowNull: true, + comment: '推送完成时间', + }, + work_order_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联工单ID(预留)', + }, + work_order_no: { + type: STRING(50), + allowNull: true, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_inbox_message', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '站内信消息推送状态追踪表', + }); + + return InboxMessage; +}; diff --git a/app/model/inbox_number_rule.js b/app/model/inbox_number_rule.js new file mode 100644 index 0000000..d7b244a --- /dev/null +++ b/app/model/inbox_number_rule.js @@ -0,0 +1,64 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, DATE } = app.Sequelize; + + const InboxNumberRule = app.model.define('inboxNumberRule', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '规则名称,如:运单号提取/收货单号提取/平台订单号提取', + }, + target: { + type: STRING(50), + allowNull: false, + comment: '提取目标类型:waybill_no/receiving_no/entry_order_no/stockout_no/order_no/source_order_codes/express_name/plate_no', + }, + regexp: { + type: STRING(500), + allowNull: false, + comment: '取号正则(JS 正则源字符串,不含首尾斜杠,支持全局匹配)', + }, + sort_order: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '规则尝试顺序,数值小者优先', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_inbox_number_rule', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '取号规则表(站内信消息中正则提取单据号)', + indexes: [ + { + unique: true, + fields: [ 'name' ], + name: 'uk_name', + }, + { + fields: [ 'target' ], + name: 'idx_target', + }, + ], + }); + + return InboxNumberRule; +}; diff --git a/app/model/interface_type.js b/app/model/interface_type.js index fc63789..c0d64d5 100644 --- a/app/model/interface_type.js +++ b/app/model/interface_type.js @@ -76,6 +76,7 @@ module.exports = app => { freezeTableName: true, underscored: true, timestamps: true, + paranoid: false, createdAt: 'created_at', updatedAt: 'updated_at', comment: '接口类型配置表', @@ -104,24 +105,13 @@ module.exports = app => { ], }); + InterfaceType.associate = function() { + const { ApiApp } = app.model; - // 类方法 - 根据接口编码查找 - InterfaceType.findByCode = async function(interfaceCode) { - return await this.findOne({ - where: { interface_code: interfaceCode }, - }); - }; - - // 类方法 - 获取启用的接口列表 - InterfaceType.findEnabled = async function(category = null) { - const where = { is_enabled: 1 }; - if (category) { - where.interface_category = category; - } - - return await this.findAll({ - where, - order: [[ 'interface_name', 'ASC' ]], + InterfaceType.hasMany(ApiApp, { + foreignKey: 'interface_type_id', + sourceKey: 'id', + as: 'api_apps', }); }; diff --git a/app/model/location_space.js b/app/model/location_space.js index 875299a..fe29b50 100644 --- a/app/model/location_space.js +++ b/app/model/location_space.js @@ -81,9 +81,10 @@ module.exports = app => { comment: '体积(m³)', }, max_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, - comment: '最大承重(kg)', + defaultValue: 0, + comment: '最大承重(g)', }, space_status: { type: ENUM('AVAILABLE', 'OCCUPIED', 'RESERVED', 'MAINTENANCE', 'DISABLED'), @@ -110,10 +111,10 @@ module.exports = app => { comment: '当前库存数量', }, current_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, defaultValue: 0, - comment: '当前重量(kg)', + comment: '当前重量(g)', }, current_volume: { type: DECIMAL(10, 2), @@ -209,7 +210,7 @@ module.exports = app => { unique: true, fields: [ 'warehouse_id', 'space_code', 'deleted_at' ], }, - { name: 'uk_custom_barcode', unique: true, fields: [ 'custom_barcode' ] }, + { name: 'uk_warehouse_custom_barcode', unique: true, fields: [ 'warehouse_id', 'custom_barcode', 'deleted_at' ] }, { fields: [ 'warehouse_id', 'zone_id' ] }, { fields: [ 'location_type_id' ] }, { fields: [ 'space_status' ] }, diff --git a/app/model/notification_send_log.js b/app/model/notification_send_log.js new file mode 100644 index 0000000..df28263 --- /dev/null +++ b/app/model/notification_send_log.js @@ -0,0 +1,129 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE, INTEGER, JSON: JSON_TYPE } = app.Sequelize; + + const NotificationSendLog = app.model.define('notification_send_log', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + trace_id: { + type: STRING(100), + allowNull: false, + comment: '通知追踪ID', + }, + webhook_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: 'Webhook 配置ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '触发主体ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '仓库ID', + }, + owner_store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + business_name: { + type: STRING(100), + allowNull: false, + comment: '业务名称', + }, + event: { + type: STRING(100), + allowNull: false, + comment: '事件名', + }, + hook_type: { + type: STRING(50), + allowNull: true, + comment: 'Webhook 类型', + }, + hook_url: { + type: STRING(500), + allowNull: true, + comment: 'Webhook 地址', + }, + request_payload: { + type: JSON_TYPE, + allowNull: true, + comment: '请求载荷', + }, + response_payload: { + type: JSON_TYPE, + allowNull: true, + comment: '返回载荷', + }, + http_status: { + type: INTEGER(11), + allowNull: true, + comment: 'HTTP 状态码', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'failed', + comment: '发送状态', + }, + error_message: { + type: STRING(1000), + allowNull: true, + comment: '失败原因', + }, + retry_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + created_by: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '创建人', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_notification_send_log', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '统一通知发送失败日志表', + indexes: [ + { + name: 'idx_notification_send_log_trace_id', + fields: [ 'trace_id' ], + }, + { + name: 'idx_notification_send_log_event_status', + fields: [ 'event', 'status' ], + }, + { + name: 'idx_notification_send_log_webhook_id', + fields: [ 'webhook_id' ], + }, + { + name: 'idx_notification_send_log_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + return NotificationSendLog; +}; diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js new file mode 100644 index 0000000..10f0967 --- /dev/null +++ b/app/model/notification_webhook.js @@ -0,0 +1,324 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE, JSON: JSON_TYPE, Op } = app.Sequelize; + + const normalizeJsonObject = (value, fieldName, { allowArray = false } = {}) => { + if (value === undefined || value === null || value === '') { + return value; + } + + if (typeof value === 'string') { + try { + const parsed = JSON.parse(value); + return normalizeJsonObject(parsed, fieldName, { allowArray }); + } catch (error) { + throw new Error(`${fieldName} 必须是合法 JSON`); + } + } + + if (Array.isArray(value)) { + if (allowArray) { + return value; + } + throw new Error(`${fieldName} 必须是对象`); + } + + if (typeof value !== 'object') { + throw new Error(`${fieldName} 必须是对象`); + } + + return value; + }; + + const SPECIAL_EVENT_CODES = new Set([ 'all', '*' ]); + const EVENT_CODE_PATTERN = /^[a-z_][a-z0-9_]*$/; + const isValidEventCode = value => SPECIAL_EVENT_CODES.has(value) || EVENT_CODE_PATTERN.test(value); + + const AVAILABLE_EVENTS = Object.freeze([ + 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: 'receiving_rejected', name: '收货驳回', business: 'receiving', description: '收货单被驳回并恢复为收货中后的通知' }), + Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }), + Object.freeze({ code: 'receiving_store_bound', name: '收货单创建/绑定货主', business: 'receiving', description: '收货单创建或首次绑定货主时的通知(展示车牌号/快递单号登记状态,未登记显示无)' }), + Object.freeze({ code: 'receiving_store_unmatched', name: '收货完成未匹配商品提醒', business: 'receiving', description: '收货单完成时存在未匹配商品明细,通知货主核实商品资料' }), + Object.freeze({ code: 'receiving_pending_inbound', name: '收货未入库超时提醒', business: 'receiving', description: '定时扫描创建超时仍未完成入库的收货单:绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群' }), + Object.freeze({ code: 'entry_order_completed', name: '入库单完成入库', business: 'entry_order', description: '入库单完成入库后的通知,提示货主入库单已完成入库请注意查收' }), + Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }), + Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }), + Object.freeze({ code: 'wave_strategy_quick_scan_failed', name: '波次策略兜底扫描失败', business: 'order', description: '定时兜底扫描任务在仓库维度触发失败时通知' }), + Object.freeze({ + code: 'store_warehouse_print_quantity_adjusted', + name: '货主面单余额调整', + business: 'store_warehouse', + description: '货主-仓库签约下的面单余额被人工调整后的通知', + }), + Object.freeze({ + code: 'storage_transfer_completed', + name: '移库操作完成', + business: 'storage', + description: '库存库位转移操作完成后的通知', + }), + ]); + const AVAILABLE_EVENT_CODE_SET = new Set(AVAILABLE_EVENTS.map(item => item.code)); + + const getAvailableEvents = () => AVAILABLE_EVENTS.map(item => ({ ...item })); + + const normalizeEvents = value => { + if (value === undefined || value === null || value === '') { + return []; + } + + if (Array.isArray(value)) { + return value.map(item => String(item || '').trim()).filter(Boolean); + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return []; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== value) { + return normalizeEvents(parsed); + } + } catch (_) { + // ignore parse failure and continue with string split + } + + return trimmed.split(/[\s,;|]+/).map(item => item.trim()).filter(Boolean); + } + + if (typeof value === 'object') { + if (value.all === true) { + return [ 'all' ]; + } + return normalizeEvents(value.include || value.events || []); + } + + throw new Error('events 必须是字符串数组或对象'); + }; + + const validateEvents = value => { + if (value === undefined || value === null || value === '') { + return; + } + + normalizeJsonObject(value, 'events', { allowArray: true }); + const normalizedEvents = normalizeEvents(value); + const invalidFormatEvents = normalizedEvents.filter(item => !isValidEventCode(item)); + if (invalidFormatEvents.length > 0) { + throw new Error(`events 中包含非法事件编码(仅支持小写字母、数字、下划线,且首字符不能为数字): ${invalidFormatEvents.join(', ')}`); + } + + const invalidEvents = normalizedEvents.filter(item => !AVAILABLE_EVENT_CODE_SET.has(item)); + if (invalidEvents.length > 0) { + throw new Error(`events 中包含不支持的事件: ${invalidEvents.join(', ')}`); + } + }; + + AVAILABLE_EVENTS.forEach(item => { + if (!isValidEventCode(item.code)) { + throw new Error(`通知事件编码不合法: ${item.code}`); + } + }); + + const NotificationWebhook = app.model.define('notification_webhook', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '主体ID,对应 wms_store.id', + references: { + model: 'store', + key: 'id', + }, + }, + hook_name: { + type: STRING(100), + allowNull: true, + comment: 'Webhook 名称', + }, + hook_type: { + type: STRING(50), + allowNull: false, + validate: { + notEmpty: { + msg: 'hook_type 不能为空', + }, + len: { + args: [ 1, 50 ], + msg: 'hook_type 长度应在1-50个字符之间', + }, + }, + comment: 'Webhook 类型,用于区分回调通道,当前支持 customize / wecom', + }, + hook_url: { + type: STRING(500), + allowNull: false, + validate: { + notEmpty: { + msg: 'hook_url 不能为空', + }, + len: { + args: [ 1, 500 ], + msg: 'hook_url 长度应在1-500个字符之间', + }, + }, + comment: 'Webhook 链接地址', + }, + events: { + type: JSON_TYPE, + allowNull: true, + comment: '订阅事件列表,可从 NotificationWebhook.getAvailableEvents() 拉取', + validate: { + isValidEvents(value) { + validateEvents(value); + }, + }, + }, + status: { + type: TINYINT(4), + allowNull: false, + defaultValue: 1, + validate: { + isIn: { + args: [[ 0, 1 ]], + msg: '状态值不合法,0-禁用,1-启用', + }, + }, + comment: '状态:0-禁用,1-启用', + }, + remark: { + type: STRING(255), + allowNull: true, + comment: '备注', + }, + created_by: { + type: BIGINT.UNSIGNED, + allowNull: true, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + validate: { + async withinStoreWebhookLimit() { + const storeId = Number(this.store_id || 0); + if (!Number.isFinite(storeId) || storeId <= 0) { + return; + } + + const store = await app.model.Store.findByPk(storeId, { + attributes: [ 'subject_config' ], + }); + const subjectConfig = app.model.Store && typeof app.model.Store.normalizeSubjectConfig === 'function' + ? app.model.Store.normalizeSubjectConfig(store && store.subject_config) + : { + max_notice_webhook_count: 5, + default_express_code: 'STO', + default_platform_code: 'TB', + }; + const maxWebhookCount = Number(subjectConfig.max_notice_webhook_count || 5); + + const where = { + store_id: storeId, + }; + if (this.id) { + where.id = { + [Op.ne]: this.id, + }; + } + + const currentCount = await app.model.NotificationWebhook.count({ where }); + if (currentCount >= maxWebhookCount) { + throw new Error(`当前主体最多允许绑定 ${maxWebhookCount} 个消息推送接口`); + } + }, + }, + tableName: 'wms_notification_webhook', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '外部通知 WebHook 配置表', + indexes: [ + { + name: 'idx_notification_webhook_store_id', + fields: [ 'store_id' ], + }, + { + name: 'idx_notification_webhook_hook_type', + fields: [ 'hook_type' ], + }, + { + name: 'idx_notification_webhook_status', + fields: [ 'status' ], + }, + { + name: 'idx_notification_webhook_store_type', + fields: [ 'store_id', 'hook_type' ], + }, + { + name: 'uk_notification_webhook_store_type_url', + unique: true, + fields: [ 'store_id', 'hook_type', 'hook_url' ], + }, + ], + }); + + NotificationWebhook.associate = function() { + const { Store, Account } = app.model; + + NotificationWebhook.belongsTo(Store, { + foreignKey: 'store_id', + targetKey: 'id', + as: 'store', + }); + + NotificationWebhook.belongsTo(Account, { + foreignKey: 'created_by', + targetKey: 'id', + as: 'creator', + constraints: false, + }); + }; + + NotificationWebhook.AVAILABLE_EVENTS = getAvailableEvents(); + NotificationWebhook.getAvailableEvents = getAvailableEvents; + NotificationWebhook.getAvailableEventCodes = () => getAvailableEvents().map(item => item.code); + NotificationWebhook.normalizeEvents = normalizeEvents; + + NotificationWebhook.prototype.isEnabled = function() { + return Number(this.status) === 1; + }; + + return NotificationWebhook; +}; diff --git a/app/model/number_sequence.js b/app/model/number_sequence.js new file mode 100644 index 0000000..d6aab1e --- /dev/null +++ b/app/model/number_sequence.js @@ -0,0 +1,55 @@ +'use strict'; + +/** + * 业务单号序列表模型。 + * 按「仓库 + 业务类型 + 日期」维度原子分配序号, + * 取号使用 INSERT ... ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(current_seq + 1), + * 避免「查当日最大序号+1」在并发下的撞号问题。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, CHAR } = app.Sequelize; + + const NumberSequence = app.model.define('wms_number_sequence', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(序号隔离维度)', + }, + biz_type: { + type: STRING(30), + allowNull: false, + comment: '业务类型,如 return_unpack(退回拆包单号)', + }, + date_part: { + type: CHAR(8), + allowNull: false, + comment: '日期片段 YYYYMMDD', + }, + current_seq: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '当前已分配序号(原子递增)', + }, + }, { + tableName: 'wms_number_sequence', + comment: '业务单号序列表(原子取号)', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'uk_warehouse_biz_date', unique: true, fields: [ 'warehouse_id', 'biz_type', 'date_part' ] }, + ], + }); + + return NumberSequence; +}; diff --git a/app/model/operation_log.js b/app/model/operation_log.js index 850b44d..e72fca3 100644 --- a/app/model/operation_log.js +++ b/app/model/operation_log.js @@ -3,7 +3,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, BIGINT, DATE, ENUM, JSON } = app.Sequelize; + const { STRING, BIGINT, DATE, ENUM, JSON, TEXT } = app.Sequelize; const OperationLog = app.model.define('operation_log', { id: { @@ -49,8 +49,8 @@ module.exports = app => { comment: '外部日志ID', }, warehouse_id: { - type: INTEGER(11), - allowNull: true, + type: BIGINT(20).UNSIGNED, + allowNull: false, comment: '仓库ID', }, before_changes: { @@ -69,6 +69,11 @@ module.exports = app => { defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), comment: '创建时间', }, + message: { + type: TEXT, + allowNull: true, + comment: '日志信息', + }, }, { tableName: 'wms_operation_log', // 数据库中的实际表名 timestamps: false, // 不使用默认的 createdAt 和 updatedAt diff --git a/app/model/order_b2b.js b/app/model/order_b2b.js new file mode 100644 index 0000000..a99c526 --- /dev/null +++ b/app/model/order_b2b.js @@ -0,0 +1,100 @@ +'use strict'; + +/** + * B2B 订单作业明细表 Model。 + * + * 对应数据库表 `wms_order_b2b`,与发货单(订单)分表 wms_order_delivery_% 一对一, + * 记录 B2B 订单的备货/提货作业信息:总箱数、提货车牌、备货备注、备货用时、 + * 备货完成时间、是否提货等。 + * + * 不分表(不按仓库分表),关联读统一使用 warehouse_id + order_id(分表 id 按仓库 + * 各自发号,跨仓可能重叠,故不单独依赖 order_id)。取消 B2B 时物理删除行,不做软删除。 + * @param {import('egg').Application} app - Egg 应用实例 + */ +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, DATE } = app.Sequelize; + + const OrderB2b = app.model.define('wms_order_b2b', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID,关联 wms_order_delivery 分表 id', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + total_box_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '总箱数', + }, + pickup_plate_number: { + type: STRING(20), + allowNull: true, + comment: '提货车牌', + }, + prep_remark: { + type: STRING(500), + allowNull: true, + comment: '备货备注', + }, + prep_duration_seconds: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '备货用时(秒)', + }, + prep_at: { + type: DATE, + allowNull: true, + comment: '备货完成时间', + }, + is_picked_up: { + type: ENUM('Y', 'N'), + allowNull: false, + defaultValue: 'N', + comment: '是否提货:Y=已提货 N=未提货', + }, + picked_up_at: { + type: DATE, + allowNull: true, + comment: '提货时间', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + }, { + tableName: 'wms_order_b2b', + comment: 'B2B订单作业明细表', + timestamps: false, + indexes: [ + { + name: 'uk_warehouse_order', + unique: true, + fields: [ 'warehouse_id', 'order_id' ], + }, + { + name: 'idx_pickup_plate_number', + fields: [ 'pickup_plate_number' ], + }, + { + name: 'idx_is_picked_up', + fields: [ 'is_picked_up' ], + }, + ], + }); + + return OrderB2b; +}; diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 3b654ae..c391349 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -2,20 +2,23 @@ module.exports = app => { const { Sequelize, model } = app; - const { STRING, BIGINT, DECIMAL, TEXT, ENUM, DATE, INTEGER, CHAR, SMALLINT } = Sequelize; + const { STRING, BIGINT, DECIMAL, TEXT, ENUM, DATE, INTEGER, CHAR, SMALLINT, TINYINT, JSON } = Sequelize; // 状态机枚举定义 const StatusEnum = { - STATUS: [ 'pedding', 'created', 'cancel', 'error' ], + STATUS: [ 'pedding', 'created', 'cancel', 'error', 'finished' ], SYNC_STATUS: [ 'padding', 'fin', 'error' ], POST_STATUS: [ 'padding', 'fin', 'timeout', 'error', 'none' ], STORAGE_STATUS: [ 'padding', 'fin', 'error', 'none' ], PICK_STATUS: [ 'padding', 'fin', 'error', 'none' ], PACK_STATUS: [ 'none', 'padding', 'fin', 'error' ], + SENDED_STATUS: [ 'none', 'padding', 'fin', 'error' ], INSPECTION_STATUS: [ 'none', 'padding', 'running', 'fin', 'error' ], PRINT_STATUS: [ 'none', 'padding', 'fin', 'error' ], + CONFIRM_PRINT_STATUS: [ 'none', 'fin' ], + PRINT_LOCK_STATUS: [ 'none', 'warehouse' ], 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', @@ -60,10 +63,15 @@ module.exports = app => { comment: '仓库编码', }, order_flag: { - type: STRING(200), + type: TEXT('long'), allowNull: true, comment: '订单标记', }, + extend_props: { + type: JSON, + allowNull: true, + comment: '订单扩展属性', + }, source_platform_code: { type: STRING(50), allowNull: true, @@ -74,6 +82,38 @@ module.exports = app => { allowNull: true, comment: '来源平台名称', }, + oaid_order_source_code: { + type: STRING(50), + allowNull: true, + comment: 'OAID订单来源编码', + }, + create_channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'MANUAL', + comment: '创建来源渠道', + }, + need_oms_waybill: { + type: TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '是否需要回OMS取号:0不需要 1需要(仅openapi创建来源使用,其他默认0)', + }, + source_order_codes: { + type: TEXT, + 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, @@ -100,7 +140,7 @@ module.exports = app => { comment: '支付时间', }, pay_no: { - type: STRING(50), + type: TEXT, allowNull: true, comment: '支付单号', }, @@ -119,11 +159,31 @@ module.exports = app => { allowNull: true, comment: 'ERP审核时间', }, + delivery_time: { + type: DATE, + allowNull: true, + comment: '发货时间', + }, shop_nick: { type: STRING(200), allowNull: true, comment: '店铺名称', }, + buyer_message: { + type: STRING(500), + allowNull: true, + comment: '买家留言', + }, + seller_message: { + type: STRING(500), + allowNull: true, + comment: '卖家留言', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, seller_nick: { type: STRING(200), allowNull: true, @@ -179,6 +239,22 @@ module.exports = app => { allowNull: true, comment: '物流公司名称', }, + sys_logistics_code: { + type: STRING(50), + allowNull: true, + comment: '系统物流公司编码', + }, + sys_logistics_name: { + type: STRING(200), + allowNull: true, + comment: '系统物流公司名称', + }, + + basket_number: { + type: STRING(50), + allowNull: true, + comment: '筐号', + }, express_code: { type: STRING(50), allowNull: true, @@ -194,12 +270,30 @@ module.exports = app => { allowNull: true, comment: '发货服务类型', }, + weight_type: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '重量类型:0常规、1轻货、2重货、3冷链', + }, is_urgency: { type: ENUM(...StatusEnum.URGENCY), allowNull: true, defaultValue: 'N', comment: '是否紧急', }, + is_b2b: { + type: ENUM('Y', 'N'), + allowNull: true, + defaultValue: 'N', + comment: '是否B2B:Y是 N否', + }, + has_sn_item: { + type: ENUM('Y', 'N'), + allowNull: true, + defaultValue: 'N', + comment: '是否含序列号管理商品:Y是 N否(按订单明细 stock_warehouse.is_sn_mgmt 聚合)', + }, invoice_flag: { type: ENUM(...StatusEnum.INVOICE), allowNull: true, @@ -263,7 +357,7 @@ module.exports = app => { comment: '镇', }, detail_address: { - type: STRING(255), + type: TEXT, allowNull: true, comment: '详细地址', }, @@ -299,9 +393,9 @@ module.exports = app => { comment: '仓库ID', }, from_key: { - type: INTEGER(11), + type: STRING(100), allowNull: true, - comment: '来源键', + comment: '来源键(上游对接应用 appKey:QM=wms_qimen_apps.app_key,API=wms_api_app.self_app_key)', }, items: { type: TEXT, @@ -321,10 +415,16 @@ module.exports = app => { comment: '商品总数', }, items_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: false, - defaultValue: 0.00, - comment: '总重量(kg)', + defaultValue: 0, + comment: '总重量(g)', + }, + packages_weight: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '所有包裹总重量(g)', }, items_hash: { type: CHAR(32), @@ -344,6 +444,54 @@ module.exports = app => { defaultValue: 0, comment: '波次ID,0表示未分配', }, + wave_no: { + type: STRING(50), + allowNull: false, + defaultValue: '', + comment: '波次号,空字符串表示未分配', + }, + wave_scope: { + type: TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '波次范围:0未分配波次 1大团购 2散单 3小团购 4单品单件', + }, + grab_operator_id: { + type: BIGINT(20), + allowNull: true, + defaultValue: null, + comment: '抓取人工号ID', + }, + grab_operator: { + type: STRING(50), + allowNull: true, + defaultValue: null, + comment: '抓取人', + }, + claim_operator_id: { + type: BIGINT(20), + allowNull: true, + defaultValue: null, + comment: '领料人工号ID', + }, + claim_operator: { + type: STRING(50), + allowNull: true, + defaultValue: null, + comment: '领料人', + }, + wave_strategy_version: { + type: INTEGER(10), + allowNull: false, + defaultValue: 0, + comment: '波次策略版本号', + }, + wave_scan_result: { + type: INTEGER(10), + allowNull: false, + defaultValue: 0, + comment: '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合', + }, // 状态机字段 post_status: { type: ENUM(...StatusEnum.POST_STATUS), @@ -369,18 +517,47 @@ module.exports = app => { defaultValue: 'none', comment: '打包状态机', }, + sended_status: { + type: ENUM(...StatusEnum.SENDED_STATUS), + allowNull: true, + defaultValue: 'none', + comment: '发货状态机', + }, inspection_status: { type: ENUM(...StatusEnum.INSPECTION_STATUS), allowNull: true, defaultValue: 'none', comment: '检验状态机', }, + recheck_status: { + type: STRING(20), + allowNull: true, + defaultValue: 'none', + comment: '复核状态', + }, + recheck_time: { + type: DATE, + allowNull: true, + comment: '复核时间', + }, + step: { + type: INTEGER(10), + allowNull: false, + defaultValue: 0, + comment: '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + }, print_status: { type: ENUM(...StatusEnum.PRINT_STATUS), allowNull: true, - defaultValue: null, + defaultValue: 'none', comment: '打印状态机', }, + confirm_print_status: { + type: ENUM(...StatusEnum.CONFIRM_PRINT_STATUS), + allowNull: true, + defaultValue: 'none', + comment: '确认打印状态机(打印完成后真实扫描面单确认)', + }, claim_status: { type: ENUM(...StatusEnum.CLAIM_STATUS), allowNull: true, @@ -396,15 +573,27 @@ module.exports = app => { lock_status: { type: ENUM(...StatusEnum.LOCK_STATUS), allowNull: true, - defaultValue: null, + defaultValue: 'none', comment: '锁定状态机', }, + print_lock_status: { + type: ENUM(...StatusEnum.PRINT_LOCK_STATUS), + allowNull: true, + defaultValue: 'none', + comment: '打印锁定状态机', + }, intercept_status: { type: ENUM(...StatusEnum.INTERCEPT_STATUS), allowNull: true, - defaultValue: null, + defaultValue: 'none', comment: '拦截状态机', }, + intercept_time: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '拦截时间(进入拦截流程/库内拦截确认时写入)', + }, }; // 主表模型 @@ -428,8 +617,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 27a217d..c820542 100644 --- a/app/model/order_delivery_factory.js +++ b/app/model/order_delivery_factory.js @@ -1,18 +1,179 @@ // 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, + buildColumnLine, + buildColumnLines, + buildIndexLines, + isColumnDefinitionDifferent, + parseManagedTableName, + AUTO_INCREMENT_SAFE_MARGIN, +} = 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 => { - const { Sequelize, model } = app; class OrderDeliveryFactory { constructor() { this.modelCache = new Map(); + this.inflightInitCache = new Map(); + this.locationTableReady = new Map(); this.app = app; } + /** + * 复用并发中的模型初始化,避免重复执行建模与结构自检。 + * @param {string} lockKey 并发锁键。 + * @param {Function} initializer 初始化函数。 + * @return {Promise} 模型实例。 + */ + async runModelInitializer(lockKey, initializer) { + if (this.inflightInitCache.has(lockKey)) { + return await this.inflightInitCache.get(lockKey); + } + + const initPromise = (async () => { + try { + return await initializer(); + } finally { + this.inflightInitCache.delete(lockKey); + } + })(); + + this.inflightInitCache.set(lockKey, initPromise); + return await initPromise; + } + + /** + * 获取配送域车道常量。 + * @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 warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 当前表模型 */ async getCurrentModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'current'); @@ -20,174 +181,256 @@ module.exports = app => { /** * 获取历史表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 历史表模型 */ async getHistoryModel(warehouseId) { 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 tableName + * @param {string} tableName 表名 + * @return {Promise} 动态模型 */ async getModelByTableName(tableName) { const cacheKey = `table_${tableName}`; + const lockKey = `init_table_${tableName}`; if (this.modelCache.has(cacheKey)) { return this.modelCache.get(cacheKey); } - try { - const tableExists = await this.checkTableExists(tableName); - if (!tableExists) { - throw new Error(`表 ${tableName} 不存在`); + return await this.runModelInitializer(lockKey, async () => { + if (this.modelCache.has(cacheKey)) { + return this.modelCache.get(cacheKey); } - const baseAttributes = this.app.model.OrderDelivery.rawAttributes; - const DynamicModel = this.app.model.define(tableName, baseAttributes, { - tableName, - timestamps: false, - comment: tableName.includes('_history') ? '仓库发货单历史表' : '仓库发货单常用表', - }); + try { + const parsed = parseManagedTableName(tableName); + if (!parsed) { + throw new Error(`表 ${tableName} 不是订单工厂管理表`); + } - this.modelCache.set(cacheKey, DynamicModel); - return DynamicModel; + const tableExists = await this.checkTableExists(tableName); + if (!tableExists) { + throw new Error(`表 ${tableName} 不存在`); + } - } catch (error) { - this.app.logger.error(`获取模型失败 ${tableName}:`, error); - throw error; - } + 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; + + } catch (error) { + this.app.logger.error(`获取模型失败 ${tableName}:`, error); + throw error; + } + }); } /** * 获取或创建模型 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @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}`; + const tableCacheKey = `table_${tableName}`; + // 与 getModelByTableName 统一使用“物理表名锁”,避免不同入口并发重复初始化同一张表 + const lockKey = `init_table_${tableName}`; // 检查缓存 if (this.modelCache.has(cacheKey)) { return this.modelCache.get(cacheKey); } - try { - // 检查表是否存在,不存在则创建 - const tableExists = await this.checkTableExists(tableName); - if (!tableExists) { - await this.createPhysicalTable(warehouseId, type); + return await this.runModelInitializer(lockKey, async () => { + if (this.modelCache.has(cacheKey)) { + return this.modelCache.get(cacheKey); } - // 创建模型实例 - const baseAttributes = this.app.model.OrderDelivery.rawAttributes; - const modelOptions = this.getModelOptions(tableName, warehouseId, type); + try { + const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName); + await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel); - const DynamicModel = this.app.model.define(tableName, baseAttributes, modelOptions); + // 设置关联关系 + this.setupAssociations(DynamicModel, warehouseIdStr, modelType); - // 设置关联关系 - this.setupAssociations(DynamicModel, warehouseId, type); + // 缓存模型(按业务键和表名键双写,避免跨入口重复初始化) + this.modelCache.set(cacheKey, DynamicModel); + this.modelCache.set(tableCacheKey, DynamicModel); + this.app.logger.info(`创建动态模型成功: ${tableName}`); - // 缓存模型 - this.modelCache.set(cacheKey, DynamicModel); - this.app.logger.info(`创建动态模型成功: ${tableName}`); + return DynamicModel; - return DynamicModel; - - } catch (error) { - this.app.logger.error(`创建动态模型失败 ${tableName}:`, error); - throw error; - } + } catch (error) { + this.app.logger.error(`创建动态模型失败 ${tableName}:`, error); + throw error; + } + }); } /** * 获取模型配置选项 - * @param tableName - * @param warehouseId - * @param type + * @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); } /** * 获取索引配置 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @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_${warehouseIdStr}_dispatch`; + } + + /** + * 获取配送域表列定义行。 + * @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 DynamicModel - * @param warehouseId - * @param type + * @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) @@ -231,7 +474,8 @@ module.exports = app => { /** * 检查表是否存在 - * @param tableName + * @param {string} tableName 表名 + * @return {Promise} 是否存在 */ async checkTableExists(tableName) { const sequelize = this.app.model; @@ -257,112 +501,671 @@ module.exports = app => { } /** - * 创建物理表 - * @param warehouseId - * @param type + * 判断目标表是否需要进行结构同步。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {boolean|null} [tableExists=null] 是否已确认表存在。 + * @return {Promise} 是否需要同步。 */ - async createPhysicalTable(warehouseId, type = 'current') { - const tableName = this.generateTableName(warehouseId, type); - const tableComment = type === 'history' - ? `仓库${warehouseId}发货单历史表` - : `仓库${warehouseId}发货单常用表`; + async needsTableSchemaSync(tableName, type, warehouseId, tableExists = null) { + const queryInterface = this.app.model.getQueryInterface(); + const managedTableExists = typeof tableExists === 'boolean' + ? tableExists + : await this.checkTableExists(tableName); - // 添加历史表特有的字段 - const historyFields = type === 'history' ? - ',\n`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : ''; + if (!managedTableExists) { + return true; + } - // 状态机枚举值 - const statusEnums = this.getStatusEnumValues(); + const [ tables, indexes ] = await Promise.all([ + queryInterface.describeTable(tableName), + typeof queryInterface.showIndex === 'function' + ? queryInterface.showIndex(tableName) + : Promise.resolve([]), + ]); - 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审核时间', - \`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 '检验状态机', - \`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}'; - `; + const expectedAttributes = this.getTableAttributes(type); + const expectedAttributeNames = Object.keys(expectedAttributes); + const actualAttributeNames = Object.keys(tables || {}); - await this.app.model.query(createTableSQL); - this.app.logger.info(`创建物理表成功: ${tableName}`); + 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) { + if (isColumnDefinitionDifferent(columnName, expectedAttributes[columnName], tables[columnName])) { + 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 || {})); + const quotedTableName = quoteIdentifier(tableName); + + // 收集需要检查的列 + const notNullColumns = []; + const numericColumns = []; + + for (const columnName of Object.keys(expectedAttributes)) { + if (!columnNames.has(columnName)) { + continue; + } + + const expectedAttribute = expectedAttributes[columnName]; + + if (expectedAttribute.allowNull === false) { + notNullColumns.push(columnName); + } + + const numericConstraint = parseNumericConstraint(expectedAttribute); + if (numericConstraint) { + numericColumns.push({ columnName, numericConstraint }); + } + } + + // 一条 SQL 检查所有 NOT NULL 约束 + if (notNullColumns.length > 0) { + const conditions = notNullColumns + .map(col => `${quoteIdentifier(col)} IS NULL`) + .join(' OR '); + const selectCols = notNullColumns + .map(col => `MAX(CASE WHEN ${quoteIdentifier(col)} IS NULL THEN 1 ELSE 0 END) AS ${quoteIdentifier(col)}`) + .join(', '); + const [ nullRows ] = await sequelize.query( + `SELECT ${selectCols} FROM ${quotedTableName} WHERE ${conditions} LIMIT 1` + ); + + if (Array.isArray(nullRows) && nullRows.length > 0) { + const row = nullRows[0]; + for (const columnName of notNullColumns) { + if (row[columnName] === 1) { + throw buildManagedTableConstraintError(tableName, columnName, 'NOT_NULL'); + } + } + } + } + + // 一条 SQL 检查所有数值范围约束 + if (numericColumns.length > 0) { + const selectCols = numericColumns + .map(({ columnName, numericConstraint }) => { + const qCol = quoteIdentifier(columnName); + return `MAX(CASE WHEN ${qCol} IS NOT NULL AND (${qCol} < ${numericConstraint.min} OR ${qCol} > ${numericConstraint.max}) THEN 1 ELSE 0 END) AS ${quoteIdentifier(columnName)}`; + }) + .join(', '); + const conditions = numericColumns + .map(({ columnName, numericConstraint }) => { + const qCol = quoteIdentifier(columnName); + return `(${qCol} IS NOT NULL AND (${qCol} < ${numericConstraint.min} OR ${qCol} > ${numericConstraint.max}))`; + }) + .join(' OR '); + const [ rangeRows ] = await sequelize.query( + `SELECT ${selectCols} FROM ${quotedTableName} WHERE ${conditions} LIMIT 1` + ); + + if (Array.isArray(rangeRows) && rangeRows.length > 0) { + const row = rangeRows[0]; + for (const { columnName, numericConstraint } of numericColumns) { + if (row[columnName] === 1) { + throw buildManagedTableConstraintError( + tableName, + columnName, + 'NUMERIC_RANGE', + `expected=[${numericConstraint.min}, ${numericConstraint.max}]` + ); + } + } + } + } + } + + /** + * 获取同仓库共享 id 序列的全部分表的 MAX(id) 基线。 + * + * 多表共用 id 契约:订单迁移到配送表时显式复制源 id,因此新分配的 + * id 必须大于所有分表已占用的 id。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 最大 id,无任何分表时返回 0。 + */ + async getSharedIdBaseline(warehouseId) { + const tables = [ + buildManagedTableName(warehouseId, 'current'), + buildManagedTableName(warehouseId, 'dispatch'), + buildManagedTableName(warehouseId, 'history'), + buildManagedTableName(warehouseId, 'outsourced'), + ]; + + let existingTableSet = null; + try { + existingTableSet = new Set(await this.app.model.getQueryInterface().showAllTables()); + } catch (error) { + existingTableSet = null; + } + + let baseline = 0; + for (const relatedTable of tables) { + const exists = existingTableSet + ? existingTableSet.has(relatedTable) + : await this.checkTableExists(relatedTable); + + if (!exists) { + continue; + } + + const [ rows ] = await this.app.model.query( + `SELECT COALESCE(MAX(id), 0) AS maxId FROM ${quoteIdentifier(relatedTable)}` + ); + const maxId = Number(rows && rows[0] && rows[0].maxId || 0); + + if (Number.isFinite(maxId) && maxId > baseline) { + baseline = maxId; + } + } + + return baseline; + } + + /** + * 核对并修复表自增水位,确保 AUTO_INCREMENT 大于同仓库共享 id 序列 + * 的全部分表(current/dispatch/history/outsourced)的 MAX(id)。 + * + * 多表共用 id 契约:订单迁移到配送表时显式复制源 id。因此 current 表的 + * 自增序列必须全局单调——新分配的 id 不能与任何分表已占用的 id 重叠。 + * 若高 id 订单已迁走(current 表 MAX(id) 变小),表重建会把水位重置为 + * current.MAX(id)+1,与配送表已占用的 id 重叠,后续迁移显式插入会撞主键。 + * 所以水位基准必须取所有分表的最大 MAX(id)。 + * + * @param {string} tableName 表名。 + * @return {Promise} + */ + async ensureAutoIncrementWatermark(tableName) { + const parsed = parseManagedTableName(tableName); + if (!parsed) { + return; + } + + const baseline = await this.getSharedIdBaseline(parsed.warehouseId); + if (!Number.isFinite(baseline) || baseline <= 0) { + return; + } + + const autoIncrement = await this.getTableAutoIncrement(tableName); + if (autoIncrement === null || autoIncrement > baseline) { + return; + } + + // 修复目标加安全余量:防止读取 MAX(id) 与 SET 之间的并发插入抢先占号, + // 导致修复后水位再次低于已分配 id(MySQL 不会把计数器降到当前已分配值以下, + // 余量仅作为并发窗口的缓冲) + const safeTarget = baseline + AUTO_INCREMENT_SAFE_MARGIN; + await this.app.model.query(`ALTER TABLE ${quoteIdentifier(tableName)} AUTO_INCREMENT = ${safeTarget}`); + this.app.logger.warn( + `订单工厂表 ${tableName} 自增水位低于共享 id 序列最大 id(auto=${autoIncrement}, max=${baseline}),已修复为 ${safeTarget}` + ); + } + + /** + * 确保单个目标表与模型结构一致。 + * @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 (!tableExists) { + await dynamicModel.sync({ force: false }); + return true; + } + + if (needsSync) { + await this.assertManagedTableDataConstraints(tableName, modelType); + await this.alterManagedTableSchema(tableName, modelType, warehouseId); + } + + // 无论是否同步结构,都核对自增水位(表重建/迁移/手工修复都可能破坏水位) + await this.ensureAutoIncrementWatermark(tableName); + return needsSync; + } + + /** + * 读取表的当前 AUTO_INCREMENT 水位。 + * @param {string} tableName 表名。 + * @return {Promise} 自增水位,非自增表返回 null。 + */ + async getTableAutoIncrement(tableName) { + const [ rows ] = await this.app.model.query( + 'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', + { replacements: [ tableName ] } + ); + + const rawValue = rows && rows[0] && rows[0].autoIncrement; + const value = Number(rawValue); + return Number.isFinite(value) ? value : null; + } + + /** + * 获取仓库订单 id 序列表名。 + * + * 每仓库一张序列表:id 自增发号,location 记录订单数据当前所在表位。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 序列表名。 + */ + getLocationSequenceTableName(warehouseId) { + return `wms_order_id_location_${warehouseId}`; + } + + /** + * 确保仓库订单 id 序列表存在,并将其自增水位抬升到同仓库所有 + * 订单分表 MAX(id) 之上(避开存量订单 id)。 + * + * 注意:本方法可能执行 DDL(隐式提交),必须在事务外调用。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} + */ + async ensureLocationSequenceTable(warehouseId) { + const tableName = this.getLocationSequenceTableName(warehouseId); + + // 进程内已初始化过则跳过:避免每次建单都重复 showAllTables + 分表 MAX 核对 + if (this.locationTableReady.get(warehouseId)) { + return; + } + + // 并发去重:同一仓库并发的 ensure 共享同一个初始化 Promise, + // 保证「建表 + 抬水位」只执行一次,其余调用等待完成后直接返回。 + return await this.runModelInitializer(`init_seq_${warehouseId}`, async () => { + if (this.locationTableReady.get(warehouseId)) { + return; + } + + // 先算基线再建表:建表语句直接携带正确水位。 + // 消除「先建表(水位=1)再 ALTER」之间的发号窗口——否则窗口内 + // 并发建单/多 worker 发号会拿到 1,与存量订单 id 冲突。 + const baseline = await this.getSharedIdBaseline(warehouseId); + const safeTarget = baseline > 0 ? baseline + AUTO_INCREMENT_SAFE_MARGIN : 0; + + const exists = await this.checkTableExists(tableName); + + if (!exists) { + const autoIncrementClause = safeTarget > 0 ? ` AUTO_INCREMENT = ${safeTarget}` : ''; + try { + await this.app.model.query( + `CREATE TABLE ${quoteIdentifier(tableName)} ( + \`id\` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + \`location\` VARCHAR(20) NOT NULL DEFAULT 'current', + PRIMARY KEY (\`id\`) + ) ENGINE=InnoDB${autoIncrementClause} DEFAULT CHARSET=utf8mb4 COMMENT='仓库订单全局id序列与位置索引(极简,不迁移)'` + ); + this.app.logger.info(`创建订单 id 序列表成功: ${tableName}${safeTarget > 0 ? `, 初始水位=${safeTarget}` : ''}`); + } catch (createError) { + const errorCode = createError + && ((createError.original && createError.original.code) + || (createError.parent && createError.parent.code) + || createError.code); + if (errorCode !== 'ER_TABLE_EXISTS') { + throw createError; + } + // 并发窗口:其他 worker 已建表,转入下方已存在核对分支 + this.app.logger.warn(`订单 id 序列表 ${tableName} 已被并发创建,转入水位核对`); + } + } + + // 表已存在(或刚被并发创建):核对并抬升水位 + if (safeTarget > 0) { + const autoIncrement = await this.getTableAutoIncrement(tableName); + // ai 为 null(MariaDB 新建表/计数器未初始化)同样视为需要抬升 + if (autoIncrement === null || autoIncrement <= baseline) { + await this.app.model.query( + `ALTER TABLE ${quoteIdentifier(tableName)} AUTO_INCREMENT = ${safeTarget}` + ); + this.app.logger.warn( + `订单 id 序列表 ${tableName} 水位抬升至 ${safeTarget}(分表最大 id=${baseline},原水位=${autoIncrement ?? 'null'})` + ); + } + } + + this.locationTableReady.set(warehouseId, true); + }); + } + + /** + * 启动初检:为当前库中已存在的订单分表仓库确保序列表存在且水位正确。 + * + * 仅做「建表 + 水位抬升」,不迁移任何数据——存量订单的位置指针回填由 + * `script/backfill-order-id-location.cjs` 脚本负责。单个仓库失败仅告警, + * 不影响其他仓库与服务启动。 + * + * @return {Promise} 完成初检的仓库数。 + */ + async ensureAllLocationSequenceTables() { + const managedTableNames = await this.listManagedTableNames(); + const warehouseIds = Array.from(new Set( + managedTableNames + .map(tableName => { + const parsed = parseManagedTableName(tableName); + return parsed ? parsed.warehouseId : null; + }) + .filter(Boolean) + )); + + let checkedCount = 0; + for (const warehouseId of warehouseIds) { + try { + await this.ensureLocationSequenceTable(warehouseId); + checkedCount += 1; + } catch (error) { + this.app.logger.warn(`[启动初检] 仓库 ${warehouseId} 序列表初始化失败: ${error.message}`); + } + } + + if (warehouseIds.length > 0) { + this.app.logger.info(`[启动初检] 订单 id 序列表初检完成: ${checkedCount}/${warehouseIds.length} 个仓库`); + } + return checkedCount; + } + + /** + * 从仓库序列表分配全局订单 id(在调用方事务内执行,随事务回滚)。 + * + * 调用方必须在事务外先调用 ensureLocationSequenceTable 完成建表。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @param {string} [location='current'] 初始位置(current/dispatch/history/outsourced)。 + * @return {Promise} 新分配的订单 id。 + */ + async allocateOrderId(warehouseId, transaction = null, location = 'current') { + const tableName = this.getLocationSequenceTableName(warehouseId); + + if (!this.locationTableReady.get(warehouseId)) { + const exists = await this.checkTableExists(tableName); + if (!exists) { + // 不允许在事务内隐式 DDL,交给调用方在事务外初始化 + throw new Error(`订单 id 序列表 ${tableName} 不存在,请先调用 ensureLocationSequenceTable`); + } + this.locationTableReady.set(warehouseId, true); + } + + const options = transaction ? { transaction } : {}; + const queryResult = await this.app.model.query( + `INSERT INTO ${quoteIdentifier(tableName)} (\`location\`) VALUES (?)`, + { replacements: [ location ], ...options } + ); + // sequelize.query 对 INSERT 的返回形态随驱动不同,兼容解析: + // - mysql2: [ insertId, affectedRows ](首个元素是数字) + // - 其他包装: [{ insertId, affectedRows }, ...] + const raw = Array.isArray(queryResult) ? queryResult[0] : queryResult; + let insertId = 0; + if (typeof raw === 'number') { + insertId = raw; + } else if (raw && typeof raw === 'object' && !Array.isArray(raw)) { + insertId = Number(raw.insertId || 0); + } else if (Array.isArray(raw) && raw.length > 0 && typeof raw[0] === 'number') { + insertId = Number(raw[0]); + } + if (!Number.isFinite(insertId) || insertId <= 0) { + throw new Error('订单 id 分配失败'); + } + + return insertId; + } + + /** + * 更新订单在序列表中的位置指针(迁移时调用)。 + * + * 存量订单(序列表无记录)以显式 id 补录;显式插入值大于当前水位时 + * MySQL 会自动推进序列表自增,保证后续发号不与存量 id 冲突。 + * + * @param {number|string} orderId 订单ID。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} location 新位置。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise} + */ + async updateOrderLocation(orderId, warehouseId, location, transaction = null) { + const tableName = this.getLocationSequenceTableName(warehouseId); + const options = transaction ? { transaction } : {}; + + await this.app.model.query( + `INSERT INTO ${quoteIdentifier(tableName)} (\`id\`, \`location\`) VALUES (?, ?) ON DUPLICATE KEY UPDATE \`location\` = VALUES(\`location\`)`, + { replacements: [ Number(orderId), location ], ...options } + ); + } + + /** + * 查询单个订单当前所在表位。 + * + * @param {number|string} orderId 订单ID。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise} 位置(current/dispatch/history/outsourced), + * 无记录返回 null(存量订单未回填)。 + */ + async getOrderLocation(orderId, warehouseId, transaction = null) { + const tableName = this.getLocationSequenceTableName(warehouseId); + if (!this.locationTableReady.get(warehouseId)) { + const exists = await this.checkTableExists(tableName); + if (!exists) { + return null; + } + this.locationTableReady.set(warehouseId, true); + } + + const options = transaction ? { transaction } : {}; + const [ rows ] = await this.app.model.query( + `SELECT \`location\` FROM ${quoteIdentifier(tableName)} WHERE \`id\` = ? LIMIT 1`, + { replacements: [ Number(orderId) ], ...options } + ); + return rows && rows[0] ? String(rows[0].location) : null; + } + + /** + * 批量查询订单当前所在表位。 + * + * @param {Array} orderIds 订单ID列表。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise>} orderId → location; + * 无记录的订单不在 Map 中(存量订单未回填)。 + */ + async getOrderLocations(orderIds, warehouseId, transaction = null) { + const result = new Map(); + const normalizedIds = Array.from(new Set( + (Array.isArray(orderIds) ? orderIds : [ orderIds ]) + .map(id => Number(id)) + .filter(id => Number.isFinite(id) && id > 0) + )); + if (normalizedIds.length === 0) { + return result; + } + + const tableName = this.getLocationSequenceTableName(warehouseId); + if (!this.locationTableReady.get(warehouseId)) { + const exists = await this.checkTableExists(tableName); + if (!exists) { + return result; + } + this.locationTableReady.set(warehouseId, true); + } + + const options = transaction ? { transaction } : {}; + const placeholders = normalizedIds.map(() => '?').join(','); + const [ rows ] = await this.app.model.query( + `SELECT \`id\`, \`location\` FROM ${quoteIdentifier(tableName)} WHERE \`id\` IN (${placeholders})`, + { replacements: normalizedIds, ...options } + ); + + for (const row of rows || []) { + result.set(Number(row.id), String(row.location)); + } + return result; + } + + /** + * 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。 + * + * 自增保护:对自增主键 id 列不做 CHANGE——对 AUTO_INCREMENT 列重新声明 + * 列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为 + * MAX(id)+1。待处理表的高 id 订单已迁移删除,重置会使自增水位回退到历史 + * 低值,与配送表已复制的 id 重叠,导致后续迁移主键冲突。 + * + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} + */ + async alterManagedTableSchema(tableName, type, warehouseId) { + const queryInterface = this.app.model.getQueryInterface(); + const sequelize = this.app.model; + const actualColumns = await queryInterface.describeTable(tableName); + const expectedAttributes = this.getTableAttributes(type); + const quotedTableName = quoteIdentifier(tableName); + const actualColumnNames = new Set(Object.keys(actualColumns || {})); + const expectedColumnNames = Object.keys(expectedAttributes); + const clauses = []; + + // ADD 新增列 / CHANGE 差异列;id 主键列永不参与 CHANGE——对 AUTO_INCREMENT + // 列重新声明列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为 + // MAX(id)+1。待处理表的高 id 订单已迁移删除,重置会使自增水位回退到历史低值, + // 与配送表已复制的 id 重叠,导致后续迁移主键冲突。 + for (const columnName of expectedColumnNames) { + const expectedAttribute = expectedAttributes[columnName]; + + if (columnName === 'id') { + continue; + } + + const columnDef = buildColumnLine(columnName, expectedAttribute); + + if (!actualColumnNames.has(columnName)) { + clauses.push(`ADD COLUMN ${columnDef}`); + } else if (isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumns[columnName])) { + clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`); + } + } + + // DROP 多余列(现有表有但期望模型没有的列;id 必在期望模型中,不会被 DROP) + const expectedColumnSet = new Set(expectedColumnNames); + for (const columnName of actualColumnNames) { + if (!expectedColumnSet.has(columnName)) { + clauses.push(`DROP COLUMN ${quoteIdentifier(columnName)}`); + } + } + + const previousAutoIncrement = await this.getTableAutoIncrement(tableName); + + if (clauses.length > 0) { + await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`); + } + + // 若 ALTER 触发表重建并把自增水位重置到历史低值,恢复原水位 + const currentAutoIncrement = await this.getTableAutoIncrement(tableName); + if (previousAutoIncrement !== null + && currentAutoIncrement !== null + && currentAutoIncrement < previousAutoIncrement) { + await sequelize.query(`ALTER TABLE ${quotedTableName} AUTO_INCREMENT = ${previousAutoIncrement}`); + this.app.logger.warn( + `订单工厂表 ${tableName} 自增水位被 ALTER 重置(${previousAutoIncrement} → ${currentAutoIncrement}),已恢复为 ${previousAutoIncrement}` + ); + } + + // 索引同步不再使用 sync({ alter: true }):历史事故表明它会重建表并重置自增水位, + // 且无法可靠检测 AUTO_INCREMENT 属性差异。改为仅补齐缺失索引,不重建、不删除已有索引。 + const existingIndexNames = new Set((await queryInterface.showIndex(tableName)) + .map(index => index.Key_name || index.name || '') + .filter(Boolean)); + + for (const indexDef of this.getIndexes(warehouseId, type)) { + if (existingIndexNames.has(indexDef.name)) { + continue; + } + + await queryInterface.addIndex(tableName, indexDef.fields, { + name: indexDef.name, + unique: Boolean(indexDef.unique), + }); + } + } + + /** + * 获取当前库中已存在的订单工厂目标表。 + * @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) { + const modelType = this.resolveModelType(type); + const tableName = this.generateTableName(warehouseId, modelType); + const dynamicModel = this.buildManagedModel(warehouseId, modelType, tableName); + + // 统一走差异检测 + 自增水位保护的同步路径,不再使用 sync({ alter: true }) + await this.ensureManagedTableSchema(tableName, modelType, warehouseId, dynamicModel); + this.app.logger.info(`创建/同步物理表成功: ${tableName}`); } /** @@ -377,9 +1180,12 @@ module.exports = app => { pick_status: [ 'padding', 'fin', 'error', 'none' ], pack_status: [ 'none', 'padding', 'fin', 'error' ], inspection_status: [ 'none', 'padding', 'running', 'fin', 'error' ], + step: [ 0, 1 ], print_status: [ 'none', 'padding', 'fin', 'error' ], + confirm_print_status: [ 'none', 'fin' ], + print_lock_status: [ 'none', 'warehouse' ], 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', @@ -392,12 +1198,23 @@ module.exports = app => { /** * 生成表名 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @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); } /** @@ -405,6 +1222,8 @@ module.exports = app => { */ clearCache() { this.modelCache.clear(); + this.inflightInitCache.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..f64a805 --- /dev/null +++ b/app/model/order_delivery_table_schema.js @@ -0,0 +1,854 @@ +'use strict'; + +const MANAGED_TYPES = Object.freeze({ + CURRENT: 'current', + HISTORY: 'history', + DISPATCH: 'dispatch', + OUTSOURCED: 'outsourced', +}); + +/** + * 自增水位修复时的安全余量。 + * + * 修复水位时会读取各分表 MAX(id) 作为基准,但读取与 SET 之间存在并发窗口: + * 其他请求可能正在抢号分配更大的 id。若 SET 值刚好是 MAX(id)+1,并发插入 + * 提交后表内 max 可能再次超过水位。预留余量(跳过若干 id)可避免该竞态, + * BIGINT 空间下跳过几十个 id 无实际影响。 + */ +const AUTO_INCREMENT_SAFE_MARGIN = 50; + +/** + * 列表排序索引名称后缀。 + * + * 列表接口固定带 warehouse_id 等值条件且默认按 updated_at / delivery_time 排序, + * 对应的索引在 dispatch 分表中需要额外携带 dispatch_lane 才能覆盖 count 统计 + * (否则统计仍需逐行回表核对 dispatch_lane),因此 dispatch 分支需要识别并 + * 剔除从 current 继承来的同名后缀索引,改用自身版本,避免同一张表维护两份功能重叠的索引。 + * + * 带 `_list_logistics_code_` 前缀的是「物流公司编码等值过滤 + 排序」变体(见 buildListSortIndexes), + * 带 `_list_is_b2b_` 前缀的是「B2B 标记等值过滤 + 排序」变体(B2B 域列表专用), + * 同样需要按分表类型区分版本,故一并登记后缀。 + */ +const LIST_SORT_INDEX_SUFFIXES = Object.freeze([ + '_list_updated_at', + '_list_delivery_time', + '_list_logistics_code_updated_at', + '_list_logistics_code_delivery_time', + '_list_is_b2b_updated_at', + '_list_is_b2b_delivery_time', +]); + +const TABLE_PATTERNS = Object.freeze([ + { + type: MANAGED_TYPES.DISPATCH, + pattern: /^wms_order_delivery_(\d+)_dispatch$/, + }, + { + 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; +} + +/** + * 判断索引名是否属于列表排序索引。 + * @param {string} name 索引名。 + * @return {boolean} 是否为列表排序索引。 + */ +function isListSortIndexName(name) { + const normalizedName = String(name || ''); + + return LIST_SORT_INDEX_SUFFIXES.some(suffix => normalizedName.endsWith(suffix)); +} + +/** + * 判断索引名是否为「复核时间」面板统计索引(current / outsourced 版本)。 + * + * dispatch 分表的复核统计多带 dispatch_lane,索引独立命名 + * (idx_dispatch_{warehouseId}_panel_recheck),因此 dispatch 不继承该索引。 + * + * @param {string} name 索引名。 + * @return {boolean} 是否为复核时间统计索引。 + */ +function isPanelRecheckIndexName(name) { + return /^idx_\d+_(?:current|outsourced)_recheck_time$/.test(String(name || '')); +} + +/** + * 判断是否为 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') { + const rawSql = String(defaultValue.toSql()); + // Sequelize.NOW 的 toSql() 返回 'NOW',MySQL/MariaDB 的 DATETIME 列 + // 默认值必须写成 CURRENT_TIMESTAMP,否则生成 DEFAULT NOW 非法语法 + return rawSql.trim().toUpperCase() === 'NOW' ? 'CURRENT_TIMESTAMP' : rawSql; + } + + 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, "''")}'`; +} + +/** + * 生成属性的类型 SQL 片段。 + * @param {Object} attribute Sequelize 属性定义。 + * @return {string} 类型 SQL 片段。 + */ +function buildColumnTypeSql(attribute) { + let typeSql; + + if (attribute.type && Array.isArray(attribute.type.values)) { + // ENUM 类型:type.toSql() 内部调 this.sequelize.escape(),sequelize 引用可能未绑定 + // 直接用安全转义构造,避免依赖 sequelize 实例 + const escaped = attribute.type.values.map(v => `'${String(v).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`).join(', '); + typeSql = `ENUM(${escaped})`; + } else if (attribute.type && typeof attribute.type.toSql === 'function') { + typeSql = attribute.type.toSql(); + } else { + typeSql = String(attribute.type || ''); + } + + // 无 dialect 绑定时 DataTypes.DATE 序列化为 'DATE', + // 但 MySQL 实际列类型是 DATETIME;DDL 若输出 DATE 会把时间部分截断 + if (typeSql && String(typeSql).trim().toUpperCase() === 'DATE') { + typeSql = 'DATETIME'; + } + + return typeSql; +} + +/** + * 归一化列类型 SQL,用于模型定义与实际表结构的语义比对。 + * + * 消除不会影响语义的差异,避免比对恒真而反复执行 ALTER: + * - INTEGER 与 INT 在 MySQL 中是同义词; + * - 整型 display width(如 BIGINT(20)、INT(11))不影响语义, + * 且 MySQL 8.0.19+ 的 information_schema 不再返回 display width; + * - 大小写与空格差异。 + * + * @param {string} sql 类型 SQL。 + * @return {string} 归一化后的类型 SQL。 + */ +function normalizeColumnTypeSql(sql) { + let normalized = String(sql || '') + .trim() + .replace(/\s+/g, ' ') + .toUpperCase(); + + normalized = normalized.replace(/^INTEGER\b/, 'INT'); + normalized = normalized.replace(/^(TINYINT|SMALLINT|MEDIUMINT|INT|BIGINT)\s*\(\s*\d+\s*\)/, '$1'); + + // Sequelize 无 dialect 绑定时 DATE 序列化为 'DATE',而 MySQL 实际列类型为 DATETIME + if (normalized === 'DATE') { + normalized = 'DATETIME'; + } + + // 删除逗号两侧空格(ENUM 值列表、DECIMAL(18, 2) 等) + normalized = normalized.replace(/\s*,\s*/g, ','); + + return normalized; +} + +/** + * 判断列定义是否与模型期望存在语义差异。 + * + * 与 needsTableSchemaSync / alterManagedTableSchema 共用同一套比较规则, + * 保证“判定需要同步”与“生成 ALTER 子句”不会漂移。 + * + * @param {string} columnName 列名。 + * @param {Object} expectedAttribute 模型期望的属性定义。 + * @param {Object} actualColumn describeTable 返回的实际列定义。 + * @return {boolean} 是否存在语义差异。 + */ +function isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumn) { + const expectedType = normalizeColumnTypeSql(buildColumnTypeSql(expectedAttribute)); + const actualType = normalizeColumnTypeSql(actualColumn && (actualColumn.type || actualColumn.Type) || ''); + + if (expectedType && actualType && expectedType !== actualType) { + return true; + } + + // 主键/自增列在建表时由 Sequelize 自动补 NOT NULL, + // 即使模型定义未显式声明 allowNull: false,实际列也是 NOT NULL + const expectedAllowNull = expectedAttribute.primaryKey || expectedAttribute.autoIncrement + ? false + : expectedAttribute.allowNull !== false; + const actualAllowNull = (actualColumn && actualColumn.allowNull) !== false; + + if (expectedAllowNull !== actualAllowNull) { + return true; + } + + const expectedDefault = Object.prototype.hasOwnProperty.call(expectedAttribute, 'defaultValue') + ? expectedAttribute.defaultValue + : undefined; + const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn || {}, 'defaultValue') + ? actualColumn.defaultValue + : undefined; + + // Sequelize.literal(如 CURRENT_TIMESTAMP)提取其原始表达式参与比较; + // Sequelize.NOW 的 val 为 'NOW',与表内实际 DEFAULT CURRENT_TIMESTAMP 归一 + const extractDefaultValue = value => { + if (value && typeof value === 'object' && typeof value.val === 'string') { + return String(value.val).trim().toUpperCase() === 'NOW' ? 'CURRENT_TIMESTAMP' : value.val; + } + return value; + }; + + const normalizedExpectedDefault = extractDefaultValue(expectedDefault) == null + ? null + : String(extractDefaultValue(expectedDefault)); + const normalizedActualDefault = extractDefaultValue(actualDefault) == null + ? null + : String(extractDefaultValue(actualDefault)); + + if (normalizedExpectedDefault === normalizedActualDefault) { + return false; + } + + // 数字默认值允许不同文本表示(如 '0' 与 '0.00'),只要数值相等即视为一致 + if (normalizedExpectedDefault !== null && normalizedActualDefault !== null) { + const expectedNumber = Number(normalizedExpectedDefault); + const actualNumber = Number(normalizedActualDefault); + + if (normalizedExpectedDefault !== '' + && normalizedActualDefault !== '' + && Number.isFinite(expectedNumber) + && Number.isFinite(actualNumber) + && expectedNumber === actualNumber) { + return false; + } + } + + return true; +} + +/** + * 将 Sequelize 属性定义转换为 DDL 列片段。 + * @param {string} columnName 列名。 + * @param {Object} attribute Sequelize 属性定义。 + * @return {string} DDL 列片段。 + */ +function buildColumnLine(columnName, attribute) { + const typeSql = buildColumnTypeSql(attribute); + const parts = [ `\`${columnName}\``, typeSql ]; + + 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); + + // 分表 id 统一由仓库序列表显式分配,分表自身不再携带自增序列。 + // 保留两套发号序列(分表自增 + 序列表)会在降级等场景产生区间重叠的冲突 id, + // 这里从模型层移除 autoIncrement:新建分表不再带 AUTO_INCREMENT; + // 已有分表结构保持不变(不执行任何 id 列变更),显式 id 插入不受影响。 + attributes.id = { ...attributes.id, autoIncrement: false }; + + if (isDispatchType(modelType)) { + const { ENUM, DATE } = app.Sequelize; + attributes.dispatch_lane = { + type: ENUM('m4', 'm5'), + field: 'dispatch_lane', + allowNull: false, + defaultValue: 'm4', + comment: '配送工作台子域(M4正常/M5异常)', + }; + attributes.dispath_time = { + type: DATE, + field: 'dispath_time', + allowNull: true, + comment: '订单迁移进配送表的时间', + }; + } + + 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_${warehouseId}_dispatch`; + } + + 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; +} + +/** + * 构建列表排序索引选项。 + * + * 工作台订单列表(listByModule)的 SQL 形态固定为 + * `WHERE warehouse_id = ? [AND dispatch_lane = ?] ORDER BY DESC, id DESC LIMIT ?` + * 且并行执行同条件的 COUNT(*)。若没有与「过滤列前缀 + 排序列」一致的索引: + * - 排序需要全表扫描 + filesort; + * - COUNT(*) 需要逐行回表核对不在索引中的过滤列。 + * 生产 wms_order_delivery_1000028_dispatch(59 万行 / 1.1GB)实测单请求因此达到 2 秒, + * 故在此显式声明 updated_at(前端请求的实际排序字段)与 delivery_time(deliveryOrder 模块默认排序字段)两份索引。 + * + * 除无条件列表外,工作台列表还常带 logistics_code 等值过滤(如 order.deliveryOrder.list 的 + * `where.logistics_code = 'JD'`)。该列区分度很低(几十个承运商编码覆盖整表),单列索引 + * 会把大面积行捞出来再逐行回表核对仓库/子域,反而比全表扫更慢;因此把等值列插在 scopeFields + * 与排序列之间,让「等值过滤 + 排序」命中同一个索引:过滤区间内索引天然按排序列有序, + * 列表无需 filesort,COUNT(*) 也退化为纯索引范围扫描。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {Array} 列表排序索引选项。 + */ +function buildListSortIndexes(warehouseId, type) { + const modelType = normalizeManagedType(type); + const dispatchType = isDispatchType(modelType); + const namePrefix = dispatchType ? `idx_dispatch_${warehouseId}` : `idx_${warehouseId}_${modelType}`; + // dispatch 分表的 where 恒定带 dispatch_lane(m4/m5),把该常量列放进索引前缀 + // 才能让 COUNT(*) 变成纯索引扫描;非 dispatch 分表没有该列。 + const scopeFields = dispatchType ? [ 'warehouse_id', 'dispatch_lane' ] : [ 'warehouse_id' ]; + const sortFields = [ 'updated_at', 'delivery_time' ]; + + const indexes = sortFields.map(sortField => ({ + name: `${namePrefix}_list_${sortField}`, + fields: [ ...scopeFields, sortField, 'id' ], + })); + + for (const sortField of sortFields) { + indexes.push({ + name: `${namePrefix}_list_logistics_code_${sortField}`, + fields: [ ...scopeFields, 'logistics_code', sortField, 'id' ], + }); + } + + // B2B 列表(order.pendingOrder2b.list / order.deliveryOrder2b.list)恒定带 + // is_b2b='Y' 等值条件,索引形态同上:等值列插在 scopeFields 与排序列之间, + // 让「B2B 过滤 + 排序 + 分页」命中同一索引,避免把整表 B2B 行捞出后 filesort。 + // B2B 列表只查 current / dispatch 分表,history / outsourced 不声明该索引, + // 避免在归档表上补建无查询场景的索引。 + if (modelType === MANAGED_TYPES.CURRENT || dispatchType) { + for (const sortField of sortFields) { + indexes.push({ + name: `${namePrefix}_list_is_b2b_${sortField}`, + fields: [ ...scopeFields, 'is_b2b', sortField, 'id' ], + }); + } + } + + return indexes; +} + +/** + * 构建索引选项。 + * @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' ], + }; + // 继承 current 的索引,但剔除列表排序索引:current 版本的前缀不含 dispatch_lane, + // 在 dispatch 分表上无法覆盖 count,须改用带 dispatch_lane 的版本(追加在末尾) + const inheritedIndexes = baseIndexes + .slice(3) + .filter(index => !isListSortIndexName(index.name) && !isPanelRecheckIndexName(index.name)); + + return [ + baseIndexes[0], + baseIndexes[1], + baseIndexes[2], + dispatchLaneIndex, + ...inheritedIndexes, + ...buildListSortIndexes(warehouseId, modelType), + // 大屏面板计数索引:面板 count 不携带 warehouse_id 条件(分表名已隐含仓库), + // 列表排序索引的前缀 warehouse_id+dispatch_lane 无法使用;且全表 dispatch_lane + // 仅有 m4 一个值,无选择性。以 delivery_time 作为前导列做范围裁剪(一个业务日 + // 窗口约 1.6 万行 vs 全表 106 万行),outbound_status 作为第二列由 ICP 在索引 + // 内过滤(所有阶段卡片均带 outbound_status='fin')。 + { + name: `idx_dispatch_${warehouseId}_panel_fulfillment`, + fields: [ 'delivery_time', 'outbound_status' ], + }, + // 大屏「今日复核数」计数索引:面板按 recheck_time 区间统计(该列原先无任何索引, + // 全表扫描 140 万行实测单次 35.8s)。比 current 版本多带 dispatch_lane + // (WHERE 恒为 IN ('m4','m5')),带上该列后 count(*) 可完全走索引不回表。 + { + name: `idx_dispatch_${warehouseId}_panel_recheck`, + fields: [ 'recheck_time', 'status', 'dispatch_lane' ], + }, + ]; + } + + 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' ], + }, + // wave_id 前导索引仅 current 分表需要:dispatch 通过 baseIndexes 自动继承; + // history/outsourced 分表未在迁移中加该索引,模型不得生成预期定义, + // 否则运行时 drift 同步会向其自动补建索引,造成模型与实际库不一致。 + ...(modelType === MANAGED_TYPES.CURRENT + ? [ + { + name: `idx_${prefix}_wave_id`, + fields: [ 'wave_id' ], + }, + ] + : []), + { + name: `idx_${prefix}_wave`, + fields: [ 'status', 'wave_id' ], + }, + // 波次号是列表高频过滤条件(如 order.deliveryOrder.list 的 where.wave_no 等值查询), + // 而 idx_{prefix}_wave 的前导列 status 不在谓词中,无法支撑 wave_no 过滤; + // wave_no 在表内近似唯一(生产 1000028_dispatch 约 1.49M 行 / 10.25 万个波次号), + // 单列索引即可把「扫半个表再逐行过滤」降为十几行的点查。 + { + name: `idx_${prefix}_wave_no`, + fields: [ 'wave_no' ], + }, + { + 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' ], + }); + } else { + // 报表类时间窗查询(如工作台热销商品排行 dashboard.hot_order_rank)以 + // `create_at` 区间 + status/delete_at 过滤订单,再按 id 关联明细汇总。 + // 缺该索引时优化器只能先全扫明细表再逐行回表核对时间窗(生产 1000028_dispatch + // 140 万行实测 38.9s);把过滤列一并放进索引后,窗口裁剪与状态过滤都在索引内完成, + // 无需回表即可完成 INNER JOIN。历史表按 archive_time 归档检索,故不补建该索引。 + indexes.push({ + name: `idx_${prefix}_create_at`, + fields: [ 'create_at', 'status', 'delete_at' ], + }); + + // 大屏「今日复核数」按 recheck_time 区间 + status 统计 + // (warehouse_panel.queryFulfillment)。该列原先无任何索引,dispatch 分表 + // 140 万行只能全表扫描(实测单次 35.8s);以时间区间做前导列裁剪, + // status 作为第二列在索引内过滤(抽样 20 万行:recheck_time 非空 97.9%、 + // 非取消 98.8%,时间窗口是唯一有效过滤条件)。 + indexes.push({ + name: `idx_${prefix}_recheck_time`, + fields: [ 'recheck_time', 'status' ], + }); + } + + // 列表排序索引统一追加在末尾:已有索引的下标位置保持不变(dispatch 分支按 + // 下标继承 current 的前 3 个索引,测试与运行时缓存均依赖该顺序)。 + indexes.push(...buildListSortIndexes(warehouseId, modelType)); + + 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, + AUTO_INCREMENT_SAFE_MARGIN, + normalizeManagedType, + isDispatchType, + isHistoryType, + isOutsourcedType, + normalizeIndexField, + normalizeIndexDefinition, + parseNumericConstraint, + buildTableAttributes, + buildTableName, + buildListSortIndexes, + isListSortIndexName, + buildTableComment, + buildTableOptions, + buildIndexOptions, + buildColumnTypeSql, + normalizeColumnTypeSql, + isColumnDefinitionDifferent, + buildColumnLine, + buildColumnLines, + buildIndexLines, + parseManagedTableName, +}; diff --git a/app/model/order_express.js b/app/model/order_express.js new file mode 100644 index 0000000..3baa396 --- /dev/null +++ b/app/model/order_express.js @@ -0,0 +1,201 @@ +'use strict'; + +/** + * 订单快递信息模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE, ENUM, INTEGER, TINYINT, TEXT } = app.Sequelize; + + const OrderExpress = app.model.define('order_express', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + waybill_code: { + type: STRING(50), + allowNull: true, + comment: '运单号', + }, + order_id: { + type: BIGINT(20), + allowNull: true, + comment: '订单ID', + }, + create_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + delete_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + is_galaxy_receive: { + type: ENUM('Y', 'N'), + allowNull: true, + defaultValue: 'N', + comment: '是否揽收', + }, + is_back: { + type: ENUM('Y', 'N'), + allowNull: true, + defaultValue: 'N', + comment: '是否退回', + }, + is_intercept: { + type: ENUM('Y', 'N'), + allowNull: true, + defaultValue: 'N', + comment: '是否拦截', + }, + logistics_code: { + type: STRING(50), + allowNull: true, + comment: '物流编码', + }, + logistics_interface_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '物流接口ID', + }, + logistics_name: { + type: STRING(50), + allowNull: true, + comment: '物流名称', + }, + logistics_interface_name: { + type: STRING(50), + allowNull: true, + comment: '物流接口名称', + }, + platform_code: { + type: STRING(50), + allowNull: true, + comment: '平台编码', + }, + business_key: { + type: INTEGER(3), + allowNull: true, + comment: '业务键', + }, + status: { + type: TINYINT(1), + allowNull: true, + defaultValue: 0, + comment: '状态', + }, + retry_count: { + type: TINYINT(3), + allowNull: true, + comment: '重试次数', + }, + printinfo: { + type: TEXT('long'), + allowNull: true, + comment: '打印信息', + }, + signature: { + type: TEXT, + allowNull: true, + comment: '签名信息', + }, + encryptprintinfo: { + type: TEXT, + allowNull: true, + comment: '加密打印信息', + }, + ver: { + type: STRING(50), + allowNull: true, + comment: '打印版本号', + }, + encryptedtoken: { + type: TEXT, + allowNull: true, + comment: '加密令牌', + }, + print_history_id: { + type: STRING(64), + allowNull: true, + comment: 'OMS 打印记录ID(打印前换新 params 用)', + }, + cai_niao_auth_info_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '菜鸟授权网点ID(OMS 取号返回,打印按店铺分组用)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + delivery_order_code: { + type: STRING(50), + allowNull: true, + comment: '发货单号', + }, + source_order_codes: { + type: TEXT, + allowNull: true, + comment: '来源订单号集合', + }, + package_material_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID', + }, + package_material_name_snapshot: { + type: STRING(128), + allowNull: true, + comment: '包材名称快照', + }, + weighing_weight: { + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '称重重量(g)', + }, + }, { + tableName: 'wms_order_express', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单快递信息表', + indexes: [ + { + name: 'uk_order_id_business_key', + unique: true, + fields: [ 'order_id', 'business_key' ], + }, + { + name: 'idx_waybill_code', + fields: [ 'waybill_code' ], + }, + { + name: 'idx_create_at', + fields: [ 'create_at' ], + }, + { + name: 'idx_wms_order_express_package_material_id', + fields: [ 'package_material_id' ], + }, + { + name: 'idx_warehouse_store', + fields: [ 'store_id', 'warehouse_id' ], + }, + ], + }); + + return OrderExpress; +}; diff --git a/app/model/order_express_print_data.js b/app/model/order_express_print_data.js new file mode 100644 index 0000000..8f68d14 --- /dev/null +++ b/app/model/order_express_print_data.js @@ -0,0 +1,54 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, DATE, TEXT } = app.Sequelize; + + const OrderExpressPrintData = app.model.define('order_express_print_data', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '快递记录ID', + }, + data: { + type: TEXT, + allowNull: true, + comment: '打印数据', + }, + create_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + delete_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + update_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + }, { + tableName: 'wms_order_express_print_data', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单快递打印数据表', + indexes: [ + { + name: 'idx_express_id', + fields: [ 'express_id' ], + }, + ], + }); + + return OrderExpressPrintData; +}; diff --git a/app/model/order_item_sn.js b/app/model/order_item_sn.js new file mode 100644 index 0000000..9c298f7 --- /dev/null +++ b/app/model/order_item_sn.js @@ -0,0 +1,120 @@ +// app/model/order_item_sn.js +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; + + const OrderItemSn = app.model.define('wms_order_item_sn', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID(复核落库时从订单冗余,便于按货主隔离查询)', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID,逻辑关联分仓订单主表,不做物理外键', + }, + order_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID,逻辑关联分仓订单明细表,不做物理外键', + }, + sn_code: { + type: STRING(512), + allowNull: false, + comment: 'SN编码(支持链接/二维码内容,最长512字符)', + }, + sn_status: { + type: STRING(32), + allowNull: false, + defaultValue: 'BOUND', + comment: 'SN状态:BOUND/VERIFIED/RETURNED/REISSUED/INVALID', + }, + verify_status: { + type: STRING(32), + allowNull: false, + defaultValue: 'UNVERIFIED', + comment: '核验状态:UNVERIFIED/PASS/FAIL', + }, + bound_at: { + type: DATE, + allowNull: true, + comment: '绑定时间', + }, + verified_at: { + type: DATE, + allowNull: true, + comment: '核验时间', + }, + returned_at: { + type: DATE, + allowNull: true, + comment: '退回时间', + }, + reissued_at: { + type: DATE, + allowNull: true, + comment: '重发时间', + }, + version: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + 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 ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_order_item_sn', + timestamps: false, + comment: '订单明细SN当前关系与状态表', + indexes: [ + { + name: 'uk_wms_order_item_sn_warehouse_sn_code', + unique: true, + fields: [ 'warehouse_id', 'sn_code' ], + }, + { + name: 'idx_wms_order_item_sn_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_wms_order_item_sn_order_item_id', + fields: [ 'order_item_id' ], + }, + { + name: 'idx_wms_order_item_sn_sn_code', + fields: [ 'sn_code' ], + }, + { + name: 'idx_wms_order_item_sn_store_id', + fields: [ 'store_id' ], + }, + ], + }); + + return OrderItemSn; +}; diff --git a/app/model/order_item_sn_log.js b/app/model/order_item_sn_log.js new file mode 100644 index 0000000..506e4bb --- /dev/null +++ b/app/model/order_item_sn_log.js @@ -0,0 +1,113 @@ +// app/model/order_item_sn_log.js +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const OrderItemSnLog = app.model.define('wms_order_item_sn_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + sn_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_order_item_sn.id,不做物理外键', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID,逻辑关联分仓订单主表,不做物理外键', + }, + order_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID,逻辑关联分仓订单明细表,不做物理外键', + }, + sn_code: { + type: STRING(512), + allowNull: false, + comment: 'SN编码(支持链接/二维码内容,最长512字符)', + }, + from_sn_status: { + type: STRING(32), + allowNull: true, + comment: '变更前SN状态', + }, + to_sn_status: { + type: STRING(32), + allowNull: false, + comment: '变更后SN状态', + }, + verify_status: { + type: STRING(32), + allowNull: true, + comment: '本次状态变更后的核验状态', + }, + action_type: { + type: STRING(32), + allowNull: false, + comment: '动作类型:BIND/VERIFY/RETURN/REISSUE/UNBIND', + }, + remark: { + type: STRING(255), + allowNull: true, + comment: '备注', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人ID', + }, + operated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + 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 ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_order_item_sn_log', + timestamps: false, + comment: '订单明细SN状态变更流水表', + indexes: [ + { + name: 'idx_wms_order_item_sn_log_sn_id', + fields: [ 'sn_id' ], + }, + { + name: 'idx_wms_order_item_sn_log_sn_code', + fields: [ 'sn_code' ], + }, + { + name: 'idx_wms_order_item_sn_log_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_wms_order_item_sn_log_order_item_id', + fields: [ 'order_item_id' ], + }, + ], + }); + + return OrderItemSnLog; +}; diff --git a/app/model/order_items.js b/app/model/order_items.js index a1a971a..f3905cc 100644 --- a/app/model/order_items.js +++ b/app/model/order_items.js @@ -3,7 +3,7 @@ module.exports = app => { const { Sequelize, model } = app; - const { STRING, BIGINT, DECIMAL, TEXT, INTEGER, JSON } = Sequelize; + const { STRING, BIGINT, DECIMAL, INTEGER, JSON, TEXT } = Sequelize; const OrderItems = model.define('wms_order_items', { id: { @@ -28,7 +28,7 @@ module.exports = app => { comment: '零售价格', }, ext_code: { - type: STRING(50), + type: TEXT, allowNull: true, comment: '外部编码', }, @@ -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 61d41d4..93a3683 100644 --- a/app/model/order_items_factory.js +++ b/app/model/order_items_factory.js @@ -1,8 +1,117 @@ // order_items_factory.js 'use strict'; +const { + ensureShardWarehouseId, + clearShardWarehouseValidationCache, +} = require('../lib/warehouse_shard_guard'); +const { + isColumnDefinitionDifferent, + buildColumnLine, + AUTO_INCREMENT_SAFE_MARGIN, +} = require('./order_delivery_table_schema'); + +/** + * 转义 SQL 标识符。 + * @param {string} identifier 标识符。 + * @return {string} 转义后的标识符。 + */ +function quoteIdentifier(identifier) { + return `\`${String(identifier).replace(/`/g, '``')}\``; +} + +/** + * 克隆模型属性定义。 + * @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, model } = app; + const { Sequelize } = app; class OrderItemsFactory { constructor() { @@ -13,7 +122,8 @@ module.exports = app => { /** * 获取当前表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 当前表模型 */ async getCurrentModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'current'); @@ -21,26 +131,38 @@ module.exports = app => { /** * 获取历史表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 历史表模型 */ async getHistoryModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'history'); } + /** + * 获取配送表模型。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 配送表模型 + */ + async getDispatchModel(warehouseId) { + return await this.getOrCreateModel(warehouseId, 'dispatch'); + } + /** * 获取或创建模型 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @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 { // 防止并发创建表 @@ -49,7 +171,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; @@ -65,43 +187,22 @@ module.exports = app => { /** * 带重试的模型创建 - * @param warehouseId - * @param type - * @param tableName - * @param cacheKey - * @param retryCount + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @param {string} tableName 表名 + * @param {string} cacheKey 缓存键 + * @param {number} retryCount 重试次数 + * @return {Promise} 动态模型 */ 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); @@ -120,8 +221,8 @@ module.exports = app => { /** * 复制关联关系 - * @param sourceModel - * @param targetModel + * @param {Object} sourceModel 源模型 + * @param {Object} targetModel 目标模型 */ copyAssociations(sourceModel, targetModel) { if (sourceModel.associations) { @@ -147,11 +248,65 @@ module.exports = app => { } /** - * 生成索引配置 - * @param warehouseId + * 构建订单商品动态模型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @param {string} tableName 表名。 + * @return {Object} 动态模型。 */ - generateIndexes(warehouseId) { - return [ + 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, type), + comment: modelComment, + }); + } + + /** + * 获取订单商品模型属性定义。 + * @param {string} type 模型类型。 + * @return {Object} 属性定义。 + */ + getTableAttributes(type) { + const mainModel = this.app.model.OrderItems; + const attributes = cloneAttributes(mainModel && mainModel.rawAttributes); + // 模型 timestamps:true 会向 rawAttributes 注入 createdAt/updatedAt + // (与显式定义的 created_at/updated_at 指向同一列),结构对齐时会被 + // 误判为缺失列而 ADD COLUMN,导致重复列与无默认值报错,剔除这两个注入属性。 + delete attributes.createdAt; + delete attributes.updatedAt; + // 保留 id 字段的 autoIncrement,与 order_delivery_factory 行为一致, + // 确保分表 wms_order_items_{warehouseId} 的 bulkCreate 能正常自增生成 id + + 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 + * @param {string} [type] 模型类型(current/dispatch/history),history 额外补归档时间索引 + */ + generateIndexes(warehouseId, type = null) { + const indexes = [ { name: `idx_${warehouseId}_order_id`, fields: [ 'order_id' ], @@ -185,11 +340,22 @@ module.exports = app => { fields: [ 'created_at' ], }, ]; + + // 历史表独有 archive_time(归档时间)列:归档库按归档时间检索, + // 缺索引时只能全表扫描,故为 history 分表补建该索引(其余分表无此列)。 + if (type === 'history') { + indexes.push({ + name: `idx_${warehouseId}_history_archive_time`, + fields: [ 'archive_time' ], + }); + } + + return indexes; } /** * 检查表是否存在 - * @param tableName + * @param {string} tableName 表名 */ async checkTableExists(tableName) { try { @@ -202,7 +368,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; @@ -210,75 +378,304 @@ module.exports = app => { } /** - * 创建物理表 - * @param warehouseId - * @param type + * 判断目标表是否需要进行结构同步。 + * @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) { + if (isColumnDefinitionDifferent(columnName, expectedAttributes[columnName], tables[columnName])) { + return true; + } + } + + const expectedIndexes = this.generateIndexes(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; + } + + /** + * 读取表的当前 AUTO_INCREMENT 水位。 + * @param {string} tableName 表名。 + * @return {Promise} 自增水位,非自增表返回 null。 + */ + async getTableAutoIncrement(tableName) { + const [ rows ] = await this.app.model.query( + 'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', + { replacements: [ tableName ] } + ); + + const rawValue = rows && rows[0] && rows[0].autoIncrement; + const value = Number(rawValue); + return Number.isFinite(value) ? value : null; + } + + /** + * 核对并修复表自增水位,确保 AUTO_INCREMENT 大于同仓库共享 id 序列 + * 的全部分表(current/dispatch/history)的 MAX(id)。 + * + * 明细迁移到配送明细表时同样显式复制源 id,因此 current 明细表的 + * 自增序列必须全局单调,水位基准取所有分表的最大 MAX(id)。 + * + * @param {string} tableName 表名。 + * @return {Promise} + */ + async ensureAutoIncrementWatermark(tableName) { + const sequelize = this.app.model; + const matched = /^wms_order_items_(\d+)(?:_(dispatch|history))?$/.exec(tableName); + const relatedTables = matched + ? [ + tableName, + `wms_order_items_${matched[1]}`, + `wms_order_items_${matched[1]}_dispatch`, + `wms_order_items_${matched[1]}_history`, + ] + : [ tableName ]; + + let existingTableSet = null; + try { + existingTableSet = new Set(await sequelize.getQueryInterface().showAllTables()); + } catch (error) { + existingTableSet = null; + } + + let baseline = 0; + for (const relatedTable of new Set(relatedTables)) { + const exists = existingTableSet + ? existingTableSet.has(relatedTable) + : await this.checkTableExists(relatedTable); + + if (!exists) { + continue; + } + + const [ rows ] = await sequelize.query( + `SELECT COALESCE(MAX(id), 0) AS maxId FROM \`${relatedTable}\`` + ); + const maxId = Number(rows && rows[0] && rows[0].maxId || 0); + + if (Number.isFinite(maxId) && maxId > baseline) { + baseline = maxId; + } + } + + if (!Number.isFinite(baseline) || baseline <= 0) { + return; + } + + const autoIncrement = await this.getTableAutoIncrement(tableName); + if (autoIncrement === null || autoIncrement > baseline) { + return; + } + + // 修复目标加安全余量:防止读取 MAX(id) 与 SET 之间的并发插入抢先占号 + const safeTarget = baseline + AUTO_INCREMENT_SAFE_MARGIN; + await sequelize.query(`ALTER TABLE \`${tableName}\` AUTO_INCREMENT = ${safeTarget}`); + this.app.logger.warn( + `订单商品工厂表 ${tableName} 自增水位低于共享 id 序列最大 id(auto=${autoIncrement}, max=${baseline}),已修复为 ${safeTarget}` + ); + } + + /** + * 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。 + * + * 自增保护:对自增主键 id 列不做 CHANGE——对 AUTO_INCREMENT 列重新声明 + * 列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为 + * MAX(id)+1,与 dispatch/history 已复制的 id 重叠,导致后续迁移主键冲突。 + * 索引同步仅补齐缺失索引,不重建、不删除已有索引。 + * + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} + */ + async alterManagedTableSchema(tableName, type, warehouseId) { + const sequelize = this.app.model; + const queryInterface = sequelize.getQueryInterface(); + const actualColumns = await queryInterface.describeTable(tableName); + const expectedAttributes = this.getTableAttributes(type); + const quotedTableName = quoteIdentifier(tableName); + const actualColumnNames = new Set(Object.keys(actualColumns || {})); + const expectedColumnNames = Object.keys(expectedAttributes); + const clauses = []; + + // ADD 新增列 / CHANGE 差异列;id 主键列永不参与 CHANGE,避免重建表重置自增水位 + for (const columnName of expectedColumnNames) { + const expectedAttribute = expectedAttributes[columnName]; + + if (columnName === 'id') { + continue; + } + + const columnDef = buildColumnLine(columnName, expectedAttribute); + + if (!actualColumnNames.has(columnName)) { + clauses.push(`ADD COLUMN ${columnDef}`); + } else if (isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumns[columnName])) { + clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`); + } + } + + // DROP 多余列(现有表有但期望模型没有的列;id 必在期望模型中,不会被 DROP) + const expectedColumnSet = new Set(expectedColumnNames); + for (const columnName of actualColumnNames) { + if (!expectedColumnSet.has(columnName)) { + clauses.push(`DROP COLUMN ${quoteIdentifier(columnName)}`); + } + } + + const previousAutoIncrement = await this.getTableAutoIncrement(tableName); + + if (clauses.length > 0) { + await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`); + } + + // 若 ALTER 触发表重建并把自增水位重置到历史低值,恢复原水位 + const currentAutoIncrement = await this.getTableAutoIncrement(tableName); + if (previousAutoIncrement !== null + && currentAutoIncrement !== null + && currentAutoIncrement < previousAutoIncrement) { + await sequelize.query(`ALTER TABLE ${quotedTableName} AUTO_INCREMENT = ${previousAutoIncrement}`); + this.app.logger.warn( + `订单商品工厂表 ${tableName} 自增水位被 ALTER 重置(${previousAutoIncrement} → ${currentAutoIncrement}),已恢复为 ${previousAutoIncrement}` + ); + } + + // 仅补齐缺失索引,不重建、不删除已有索引 + const existingIndexNames = new Set((await queryInterface.showIndex(tableName)) + .map(index => index.Key_name || index.name || '') + .filter(Boolean)); + + for (const indexDef of this.generateIndexes(warehouseId, type)) { + if (existingIndexNames.has(indexDef.name)) { + continue; + } + + await queryInterface.addIndex(tableName, indexDef.fields, { + name: indexDef.name, + unique: Boolean(indexDef.unique), + }); + } + } + + /** + * 确保目标表与模型结构一致。 + * @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 (!tableExists) { + await dynamicModel.sync({ force: false }); + return true; + } + + if (needsSync) { + // 结构同步不再使用 sync({ alter: true }):历史事故表明它会重建表并重置 + // 自增水位(与 dispatch/history 已复制 id 重叠,后续迁移主键冲突)。 + // 改为手工差异 ALTER + 补齐索引,并跳过 id 列 CHANGE。 + await this.alterManagedTableSchema(tableName, type, warehouseId); + } + + // 无论是否同步结构,都核对自增水位(表重建/迁移/手工修复都可能破坏水位) + await this.ensureAutoIncrementWatermark(tableName); + return needsSync; + } + + /** + * 创建物理表。 + * @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}`); + // 统一走差异检测 + 自增水位保护的同步路径,不再直接 sync({ alter: true }) + await this.ensureManagedTableSchema(tableName, type, warehouseId, dynamicModel); + this.app.logger.info(`创建/同步订单商品物理表成功: ${tableName}`); } /** * 生成表名 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @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}`; } /** * 清除缓存 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 */ clearCache(warehouseId, type) { const cacheKey = `${warehouseId}_${type}`; this.modelCache.delete(cacheKey); + this.creatingTables.delete(cacheKey); + clearShardWarehouseValidationCache(this.app); } /** @@ -286,11 +683,13 @@ module.exports = app => { */ clearAllCache() { this.modelCache.clear(); + this.creatingTables.clear(); + clearShardWarehouseValidationCache(this.app); } /** * 休眠函数 - * @param ms + * @param {number} ms 毫秒数 */ sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); diff --git a/app/model/order_stockout.js b/app/model/order_stockout.js new file mode 100644 index 0000000..66f6c17 --- /dev/null +++ b/app/model/order_stockout.js @@ -0,0 +1,366 @@ +'use strict'; + +/** + * 出库单主表 Model。 + * + * 对应数据库表 `wms_order_stockout`,存储奇门 stockout.create 接口下发的出库单信息。 + * + * 业务类型枚举值: + * - JYCK:一般交易出库 + * - HHCK:换货出库 + * - BFCK:补发出库 + * - QTCK:其他出库 + * @param {import('egg').Application} app - Egg 应用实例 + */ +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, TEXT, TINYINT, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const OrderStockout = app.model.define('wms_order_stockout', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + stockout_order_code: { + type: STRING(50), + allowNull: false, + comment: '出库单号(对应奇门 deliveryOrderCode)', + validate: { + notEmpty: true, + }, + }, + order_type: { + type: STRING(50), + allowNull: false, + comment: '业务类型(JYCK一般交易出库/HHCK换货出库/BFCK补发出库/QTCK其他出库等)', + validate: { + notEmpty: true, + }, + }, + total_order_lines: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '单据总行数', + }, + order_create_time: { + type: DATE, + allowNull: true, + comment: '订单创建时间(对应奇门 createTime)', + }, + source_type: { + type: ENUM('WMS', 'API', 'QM'), + allowNull: false, + defaultValue: 'QM', + comment: '来源类型', + }, + order_status: { + type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED', 'TRANSFERRED'), + allowNull: false, + defaultValue: 'CREATED', + comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废, TRANSFERRED=已转订单', + }, + sync_status: { + type: ENUM('PENDING', 'SUCCESS', 'FAILED'), + allowNull: false, + defaultValue: 'PENDING', + comment: '同步状态', + }, + sync_message: { + type: TEXT, + allowNull: true, + comment: '同步返回信息', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + store_name: { + type: STRING(200), + allowNull: true, + comment: '货主名称快照', + }, + warehouse_name: { + type: STRING(200), + allowNull: true, + comment: '仓库名称快照', + }, + qimen_owner_code: { + type: STRING(100), + allowNull: true, + comment: '奇门货主code(对应 ownerCode)', + }, + qimen_warehouse_code: { + type: STRING(100), + allowNull: true, + comment: '奇门仓库code(对应 warehouseCode)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + receiver_company: { + type: STRING(200), + allowNull: true, + comment: '收件人公司名称(receiverInfo.company)', + }, + receiver_name: { + type: STRING(50), + allowNull: true, + comment: '收件人姓名(receiverInfo.name)', + }, + receiver_zip_code: { + type: STRING(50), + allowNull: true, + comment: '收件人邮编(receiverInfo.zipCode)', + }, + receiver_tel: { + type: STRING(50), + allowNull: true, + comment: '收件人固定电话(receiverInfo.tel)', + }, + receiver_mobile: { + type: STRING(50), + allowNull: true, + comment: '收件人移动电话(receiverInfo.mobile)', + }, + receiver_email: { + type: STRING(50), + allowNull: true, + comment: '收件人电子邮箱(receiverInfo.email)', + }, + receiver_country_code: { + type: STRING(50), + allowNull: true, + comment: '收件人国家二字码(receiverInfo.countryCode)', + }, + receiver_province: { + type: STRING(50), + allowNull: true, + comment: '收件人省份(receiverInfo.province)', + }, + receiver_city: { + type: STRING(50), + allowNull: true, + comment: '收件人城市(receiverInfo.city)', + }, + receiver_area: { + type: STRING(50), + allowNull: true, + comment: '收件人区域(receiverInfo.area)', + }, + receiver_town: { + type: STRING(50), + allowNull: true, + comment: '收件人村镇(receiverInfo.town)', + }, + receiver_detail_address: { + type: STRING(200), + allowNull: true, + comment: '收件人详细地址(receiverInfo.detailAddress)', + }, + receiver_id: { + type: STRING(50), + allowNull: true, + comment: '收件人证件号(receiverInfo.id)', + }, + source_platform_code: { + type: STRING(50), + allowNull: true, + comment: '来源平台编码(转订单时优先使用,为空时兜底平台)', + }, + source_platform_name: { + type: STRING(200), + allowNull: true, + comment: '来源平台名称快照', + }, + express_code: { + type: STRING(50), + allowNull: true, + comment: '快递公司编码(如 SF、STO,用于出站回传 logisticsCode)', + }, + express_name: { + type: STRING(200), + allowNull: true, + comment: '快递公司名称(由 express_code 自动解析,如 顺丰、申通)', + }, + waybill_code: { + type: STRING(50), + allowNull: true, + comment: '运单号', + }, + waybill_codes: { + type: JSON_TYPE, + allowNull: true, + comment: '运单号列表(JSON 数组,支持多包裹场景)', + }, + express_codes: { + type: JSON_TYPE, + allowNull: true, + comment: '@deprecated 运单号列表,请使用 waybill_codes', + }, + extend_props: { + type: JSON_TYPE, + allowNull: true, + comment: '扩展属性', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_order_stockout', + comment: '出库单主表', + timestamps: false, + indexes: [ + { + name: 'uk_stockout_order_code', + unique: true, + fields: [ 'stockout_order_code', 'warehouse_id', 'store_id' ], + }, + { + name: 'idx_order_type', + fields: [ 'order_type' ], + }, + { + name: 'idx_order_status', + fields: [ 'order_status' ], + }, + { + name: 'idx_sync_status', + fields: [ 'sync_status' ], + }, + { + name: 'idx_source_type', + fields: [ 'source_type' ], + }, + { + name: 'idx_warehouse_store', + fields: [ 'warehouse_id', 'store_id' ], + }, + { + name: 'idx_order_create_time', + fields: [ 'order_create_time' ], + }, + { + name: 'idx_is_enabled', + fields: [ 'is_enabled' ], + }, + { + name: 'idx_deleted_at', + fields: [ 'deleted_at' ], + }, + ], + }); + + /** + * 关联关系定义。 + * - 关联货主 / 仓库(均通过 Store 表) + * - 关联出库明细表 + */ + OrderStockout.associate = function() { + const { OrderStockout, Store, OrderStockoutItems } = app.model; + + // 关联仓库 + OrderStockout.belongsTo(Store, { + foreignKey: 'warehouse_id', + as: 'warehouse', + }); + + // 关联货主 + OrderStockout.belongsTo(Store, { + foreignKey: 'store_id', + as: 'store', + }); + + // 关联出库明细 + OrderStockout.hasMany(OrderStockoutItems, { + foreignKey: 'order_id', + as: 'items', + }); + }; + + // ---------- 状态机辅助方法 ---------- + + /** 判断订单是否处于"已创建"状态 */ + OrderStockout.prototype.isCreated = function() { + return this.order_status === 'CREATED'; + }; + + /** 判断订单是否处于"已审核"状态 */ + OrderStockout.prototype.isPending = function() { + return this.order_status === 'PENDING'; + }; + + /** 判断订单是否已完成 */ + OrderStockout.prototype.isCompleted = function() { + return this.order_status === 'COMPLETED'; + }; + + /** 判断订单是否已作废 */ + OrderStockout.prototype.isCancelled = function() { + return this.order_status === 'CANCELLED'; + }; + + /** 判断订单是否已转销售订单 */ + OrderStockout.prototype.isTransferred = function() { + return this.order_status === 'TRANSFERRED'; + }; + + /** 当前订单是否允许审核 */ + OrderStockout.prototype.canConfirm = function() { + return [ 'CREATED', 'PENDING' ].includes(this.order_status); + }; + + /** 当前订单是否允许取消 */ + OrderStockout.prototype.canCancel = function() { + return [ 'CREATED', 'PENDING' ].includes(this.order_status); + }; + + /** 当前订单是否允许完成 */ + OrderStockout.prototype.canComplete = function() { + return [ 'PENDING' ].includes(this.order_status); + }; + + /** 同步是否成功 */ + OrderStockout.prototype.isSyncSuccess = function() { + return this.sync_status === 'SUCCESS'; + }; + + /** 同步是否失败 */ + OrderStockout.prototype.isSyncFailed = function() { + return this.sync_status === 'FAILED'; + }; + + /** 是否启用(未软删除) */ + OrderStockout.prototype.isEnabled = function() { + return this.is_enabled === 1 && !this.deleted_at; + }; + + return OrderStockout; +}; diff --git a/app/model/order_stockout_items.js b/app/model/order_stockout_items.js new file mode 100644 index 0000000..c8780bb --- /dev/null +++ b/app/model/order_stockout_items.js @@ -0,0 +1,145 @@ +'use strict'; + +/** + * 出库单明细表 Model。 + * + * 对应数据库表 `wms_order_stockout_items`,存储奇门 stockout.create 接口中 + * 每个 节点的明细数据。 + * + * 与主表 `wms_order_stockout` 通过 `order_id` 外键关联(CASCADE 删除)。 + * 与库存表 `wms_stock_warehouse` 通过 `stock_id` 外键关联(RESTRICT 删除)。 + * @param {import('egg').Application} app - Egg 应用实例 + */ +module.exports = app => { + const { STRING, INTEGER, BIGINT, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const OrderStockoutItems = app.model.define('wms_order_stockout_items', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '出库单ID,外键关联 wms_order_stockout.id', + }, + out_biz_code: { + type: STRING(255), + allowNull: true, + comment: '外部业务编码(幂等键)', + }, + order_line_no: { + type: STRING(50), + allowNull: false, + comment: '订单行号(对应奇门 orderLineNo)', + }, + owner_code: { + type: STRING(50), + allowNull: true, + comment: '货主编码(对应奇门 ownerCode)', + }, + item_code: { + type: STRING(50), + allowNull: true, + comment: '商品编码(对应奇门 itemCode)', + }, + item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: 'WMS商品ID(对应奇门 itemId)', + }, + item_name: { + type: STRING(200), + allowNull: true, + comment: '商品名称', + }, + plan_qty: { + type: INTEGER(12), + allowNull: true, + comment: '计划数量(对应奇门 planQty)', + }, + actual_qty: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实发数量', + }, + inventory_type: { + type: STRING(50), + allowNull: true, + comment: '库存类型(ZP正品/CC残次等)', + }, + stock_id: { + type: BIGINT(20), + allowNull: true, + comment: '库存ID,外键关联 wms_stock_warehouse.id', + }, + extend_props: { + type: JSON_TYPE, + allowNull: true, + comment: '扩展属性', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_order_stockout_items', + comment: '出库明细表', + timestamps: false, + indexes: [ + { + name: 'uk_order_line_no', + unique: true, + fields: [ 'order_id', 'order_line_no' ], + }, + { + name: 'idx_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_stock_id', + fields: [ 'stock_id' ], + }, + { + name: 'idx_item_code', + fields: [ 'item_code' ], + }, + { + name: 'idx_out_biz_code', + fields: [ 'out_biz_code' ], + }, + ], + }); + + /** + * 关联关系定义。 + * - 关联出库单主表 + * - 关联商品 SKU(wms_stock_warehouse) + */ + OrderStockoutItems.associate = function() { + const { OrderStockoutItems, OrderStockout, StockWarehouse } = app.model; + + // 关联出库单 + OrderStockoutItems.belongsTo(OrderStockout, { + foreignKey: 'order_id', + as: 'order', + }); + + // 关联商品 SKU + OrderStockoutItems.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stock', + }); + }; + + return OrderStockoutItems; +}; diff --git a/app/model/order_wave_index.js b/app/model/order_wave_index.js new file mode 100644 index 0000000..c1ba3c1 --- /dev/null +++ b/app/model/order_wave_index.js @@ -0,0 +1,63 @@ +'use strict'; + +/** + * 订单波次顺序定位副表模型。 + * 表结构:database/migrations/20260513113000-create-wms_order_wave_index.js + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, DATE } = app.Sequelize; + + const OrderWaveIndex = app.model.define('wms_order_wave_index', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单ID', + }, + wave_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '波次ID', + }, + wave_index: { + type: INTEGER(10).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单在波次中的全局顺序', + }, + platforms_index: { + type: INTEGER(10).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单在平台分组内顺序', + }, + create_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + }, { + tableName: 'wms_order_wave_index', + timestamps: false, + underscored: true, + comment: '订单波次顺序定位副表', + }); + + return OrderWaveIndex; +}; diff --git a/app/model/order_wave_strategy_match.js b/app/model/order_wave_strategy_match.js new file mode 100644 index 0000000..972dcc2 --- /dev/null +++ b/app/model/order_wave_strategy_match.js @@ -0,0 +1,53 @@ +// app/model/order_wave_strategy_match.js +'use strict'; + +module.exports = app => { + const { BIGINT, INTEGER, DATE } = app.Sequelize; + + const OrderWaveStrategyMatch = app.model.define('wms_order_wave_strategy_match', { + id: { + type: BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: INTEGER(10), + allowNull: false, + comment: '仓库ID', + }, + order_id: { + type: BIGINT, + allowNull: false, + comment: '订单ID,逻辑关联分仓主表,不做物理外键', + }, + strategy_id: { + type: INTEGER(10), + allowNull: false, + comment: '命中的波次策略ID', + }, + create_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '写入时间', + }, + }, { + tableName: 'wms_order_wave_strategy_match', + timestamps: false, + comment: '订单波次策略命中明细表,记录每个订单命中的全部策略', + indexes: [ + { + name: 'idx_warehouse_order', + fields: [ 'warehouse_id', 'order_id' ], + }, + { + name: 'idx_warehouse_strategy', + fields: [ 'warehouse_id', 'strategy_id' ], + }, + ], + }); + + return OrderWaveStrategyMatch; +}; diff --git a/app/model/org_unit.js b/app/model/org_unit.js new file mode 100644 index 0000000..05d3a51 --- /dev/null +++ b/app/model/org_unit.js @@ -0,0 +1,170 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE, TINYINT, INTEGER, JSON: JSON_TYPE } = app.Sequelize; + + const OrgUnit = app.model.define('org_unit', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属仓库ID,关联 wms_store.id', + }, + parent_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '父部门ID,NULL=根部门;必须与 warehouse_id 同仓', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '部门名称', + }, + code: { + type: STRING(50), + allowNull: true, + comment: '部门编码(仓库内唯一)', + }, + leader_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '部门管理员账号ID,关联 wms_account.id', + }, + admin_role_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '管理员默认角色集,关联 wms_role.id,如 [3,8];任命管理员时自动分配', + }, + default_role_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '部门默认角色集,关联 wms_role.id,如 [3,8];成员入职挂本部门时自动分配', + }, + path: { + type: STRING(500), + allowNull: true, + comment: '层级路径,如 /1/5/9/(根部门为 /{id}/),用于一次查询整棵子树', + }, + sort: { + type: INTEGER, + allowNull: false, + defaultValue: 0, + comment: '同级排序,越小越靠前', + }, + status: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-停用 1-启用', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_org_unit', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '组织架构表(部门/子部门层级、部门管理员、管理员与成员默认角色)', + indexes: [ + { + name: 'idx_warehouse_parent', + fields: [ 'warehouse_id', 'parent_id' ], + }, + { + name: 'idx_parent_id', + fields: [ 'parent_id' ], + }, + { + name: 'uk_warehouse_code', + unique: true, + fields: [ 'warehouse_id', 'code' ], + }, + { + name: 'idx_path', + fields: [ 'path' ], + }, + { + name: 'idx_status', + fields: [ 'status' ], + }, + ], + }); + + // 关联关系 + OrgUnit.associate = function() { + const { Account, Store } = app.model; + + // 所属仓库 + OrgUnit.belongsTo(Store, { + foreignKey: 'warehouse_id', + targetKey: 'id', + as: 'warehouse', + }); + + // 部门管理员 + OrgUnit.belongsTo(Account, { + foreignKey: 'leader_id', + targetKey: 'id', + as: 'leader', + }); + + // 上级部门 + OrgUnit.belongsTo(OrgUnit, { + foreignKey: 'parent_id', + targetKey: 'id', + as: 'parent', + }); + + // 下级部门 + OrgUnit.hasMany(OrgUnit, { + foreignKey: 'parent_id', + sourceKey: 'id', + as: 'children', + }); + }; + + // 实例方法:是否根部门 + OrgUnit.prototype.isRoot = function() { + return !this.parent_id; + }; + + // 实例方法:是否启用 + OrgUnit.prototype.isEnabled = function() { + return this.status === 1; + }; + + // 实例方法:管理员默认角色ID列表 + OrgUnit.prototype.getAdminRoleIds = function() { + return this.admin_role_ids || []; + }; + + // 实例方法:部门默认角色ID列表(成员入职自动分配) + OrgUnit.prototype.getDefaultRoleIds = function() { + return this.default_role_ids || []; + }; + + return OrgUnit; +}; diff --git a/app/model/pack_task.js b/app/model/pack_task.js new file mode 100644 index 0000000..3b8fa45 --- /dev/null +++ b/app/model/pack_task.js @@ -0,0 +1,172 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, INTEGER, DATE, TINYINT, TEXT, JSON: JSON_TYPE } = app.Sequelize; + + const PackTask = app.model.define('pack_task', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }, + workbench_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '工作台ID,关联 wms_workbench.id', + }, + wave_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '波次ID', + }, + wave_no: { + type: STRING(50), + allowNull: true, + comment: '波次号', + }, + wave_scope: { + type: TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '波次范围:0未分配波次 1大团购 2散单 3小团购 4单品单件', + }, + waybill_code: { + type: STRING(50), + allowNull: true, + comment: '运单号', + }, + pack_quantity: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '打包数量(件数)', + }, + item_quantity: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品总数量', + }, + sku_count: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品种类数(SKU数)', + }, + pack_mode: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '打包模式:1=散单 2=团购', + }, + status: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0=待处理 1=打包中 2=已完成 3=异常', + }, + start_time: { + type: DATE, + allowNull: true, + comment: '开始打包时间', + }, + end_time: { + type: DATE, + allowNull: true, + comment: '结束打包时间', + }, + operator_text: { + type: TEXT, + allowNull: true, + comment: '作业人员(自由文本,如多人逗号分隔)', + }, + device_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '设备ID列表,如 [1,2,3]', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + meta: { + type: JSON_TYPE, + allowNull: true, + comment: '扩展信息JSON', + }, + create_time: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + tableName: 'wms_pack_task', + timestamps: true, + createdAt: 'create_time', + updatedAt: 'update_time', + paranoid: true, + deletedAt: 'deleted_at', + comment: '打包任务表(含作业记录)', + indexes: [ + { name: 'idx_order_id', fields: [ 'order_id' ] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_warehouse_create_time', fields: [ 'warehouse_id', 'create_time' ] }, + { name: 'idx_workbench_id', fields: [ 'workbench_id' ] }, + { name: 'idx_workbench_create_time', fields: [ 'workbench_id', 'create_time' ] }, + { name: 'idx_wave_id', fields: [ 'wave_id' ] }, + { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, + { name: 'idx_pack_mode_status', fields: [ 'pack_mode', 'status' ] }, + { name: 'idx_start_time', fields: [ 'start_time' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + ], + }); + + PackTask.associate = () => { + app.model.PackTask.belongsTo(app.model.Workbench, { + foreignKey: 'workbench_id', + targetKey: 'id', + as: 'workbench', + }); + app.model.PackTask.hasMany(app.model.PackTaskVideo, { + foreignKey: 'pack_task_id', + sourceKey: 'id', + as: 'videos', + }); + app.model.PackTask.hasMany(app.model.PackTaskPacker, { + foreignKey: 'pack_task_id', + sourceKey: 'id', + as: 'packers', + }); + app.model.PackTask.hasMany(app.model.OrderExpress, { + foreignKey: 'order_id', + sourceKey: 'order_id', + as: 'expresses', + }); + }; + + return PackTask; +}; diff --git a/app/model/pack_task_packer.js b/app/model/pack_task_packer.js new file mode 100644 index 0000000..f645979 --- /dev/null +++ b/app/model/pack_task_packer.js @@ -0,0 +1,78 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, DATE, TINYINT } = app.Sequelize; + + const PackTaskPacker = app.model.define('pack_task_packer', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + pack_task_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '打包任务ID,关联 wms_pack_task.id', + }, + account_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '账号ID,关联 wms_account.id;未知账号为 NULL(唯一索引对 NULL 不生效,允许多名无账号打包人)', + }, + account_name: { + type: STRING(128), + allowNull: false, + comment: '账号姓名快照', + }, + seq: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '排序序号', + }, + create_time: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + tableName: 'wms_pack_task_packer', + timestamps: true, + createdAt: 'create_time', + updatedAt: 'update_time', + paranoid: true, + deletedAt: 'deleted_at', + comment: '打包任务-打包人关系表', + indexes: [ + { name: 'uix_pack_task_account', fields: [ 'pack_task_id', 'account_id' ], unique: true }, + { name: 'idx_account_id', fields: [ 'account_id' ] }, + { name: 'idx_pack_task_id', fields: [ 'pack_task_id' ] }, + ], + }); + + PackTaskPacker.associate = () => { + app.model.PackTaskPacker.belongsTo(app.model.PackTask, { + foreignKey: 'pack_task_id', + targetKey: 'id', + as: 'packTask', + }); + app.model.PackTaskPacker.belongsTo(app.model.Account, { + foreignKey: 'account_id', + targetKey: 'id', + as: 'account', + }); + }; + + return PackTaskPacker; +}; diff --git a/app/model/pack_task_video.js b/app/model/pack_task_video.js new file mode 100644 index 0000000..1296917 --- /dev/null +++ b/app/model/pack_task_video.js @@ -0,0 +1,83 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, DATE } = app.Sequelize; + + const PackTaskVideo = app.model.define('pack_task_video', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + pack_task_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '打包任务ID,关联 wms_pack_task.id', + }, + camera_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '摄像头设备ID,关联 wms_camera.id', + }, + video_url: { + type: STRING(500), + allowNull: false, + comment: '视频地址(录像回放URL)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'created', + comment: '状态:created-已创建 recording-录制中 completed-已完成 failed-失败', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_pack_task_video', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '打包任务视频记录表', + indexes: [ + { name: 'idx_pack_task_id', fields: [ 'pack_task_id' ] }, + { name: 'idx_camera_id', fields: [ 'camera_id' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + PackTaskVideo.associate = () => { + app.model.PackTaskVideo.belongsTo(app.model.PackTask, { + foreignKey: 'pack_task_id', + targetKey: 'id', + as: 'packTask', + }); + app.model.PackTaskVideo.belongsTo(app.model.Camera, { + foreignKey: 'camera_id', + targetKey: 'id', + as: 'camera', + }); + }; + + return PackTaskVideo; +}; diff --git a/app/model/package_material.js b/app/model/package_material.js new file mode 100644 index 0000000..15f9e35 --- /dev/null +++ b/app/model/package_material.js @@ -0,0 +1,115 @@ +'use strict'; + +/** + * 包材信息模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DECIMAL, TINYINT, INTEGER, DATE } = app.Sequelize; + + const PackageMaterial = app.model.define('package_material', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + material_code: { + type: STRING(64), + allowNull: false, + comment: '包材编码', + }, + material_name: { + type: STRING(128), + allowNull: false, + comment: '包材名称', + }, + material_type: { + type: STRING(32), + allowNull: true, + comment: '包材类型', + }, + spec: { + type: STRING(128), + allowNull: true, + comment: '规格描述', + }, + length: { + type: DECIMAL(10, 2), + allowNull: true, + comment: '长度(cm)', + }, + width: { + type: DECIMAL(10, 2), + allowNull: true, + comment: '宽度(cm)', + }, + height: { + type: DECIMAL(10, 2), + allowNull: true, + comment: '高度(cm)', + }, + weight: { + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '重量(g)', + }, + cost_price: { + type: DECIMAL(10, 2), + allowNull: true, + comment: '成本单价', + }, + status: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:0=禁用,1=启用', + }, + version: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_package_material', + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: false, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '包材信息表', + indexes: [ + { + name: 'idx_wms_package_material_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'uk_wms_package_material_warehouse_material_code', + unique: true, + fields: [ 'warehouse_id', 'material_code' ], + }, + ], + }); + + return PackageMaterial; +}; diff --git a/app/model/package_material_item_relation.js b/app/model/package_material_item_relation.js new file mode 100644 index 0000000..55f64d7 --- /dev/null +++ b/app/model/package_material_item_relation.js @@ -0,0 +1,130 @@ +'use strict'; + +/** + * 商品结构-包材绑定关系模型。 + * 记录订单商品结构指纹与包材的绑定历史,支持智能推荐。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { STRING, CHAR, INTEGER, BIGINT, DECIMAL, TINYINT, DATE } = app.Sequelize; + + const PackageMaterialItemRelation = app.model.define('package_material_item_relation', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + items_hash: { + type: CHAR(32), + allowNull: false, + comment: '订单商品结构MD5指纹', + }, + items_crc: { + type: INTEGER.UNSIGNED, + allowNull: false, + comment: '订单商品结构CRC32校验', + }, + package_material_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '包材ID', + }, + package_material_code: { + type: STRING(64), + allowNull: false, + comment: '包材编码(快照)', + }, + package_material_name: { + type: STRING(128), + allowNull: false, + comment: '包材名称(快照)', + }, + package_material_spec: { + type: STRING(128), + defaultValue: '', + comment: '规格(快照)', + }, + package_material_type: { + type: STRING(32), + defaultValue: '', + comment: '类型(快照)', + }, + length: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '长(cm)快照', + }, + width: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '宽(cm)快照', + }, + height: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '高(cm)快照', + }, + weight: { + type: INTEGER(11), + defaultValue: 0, + comment: '重量(g)快照', + }, + bind_count: { + type: INTEGER.UNSIGNED, + defaultValue: 1, + comment: '累计绑定次数', + }, + last_order_id: { + type: BIGINT(20).UNSIGNED, + comment: '最近订单ID', + }, + last_waybill_code: { + type: STRING(50), + defaultValue: '', + comment: '最近运单号', + }, + last_bind_user_id: { + type: BIGINT(20).UNSIGNED, + comment: '最近操作用户ID', + }, + last_bind_at: { + type: DATE, + comment: '最近绑定时间', + }, + is_active: { + type: TINYINT, + defaultValue: 1, + comment: '包材当前是否启用', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + delete_at: { + type: DATE, + comment: '软删除时间', + }, + }, { + tableName: 'wms_package_material_item_relation', + underscored: true, + paranoid: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'delete_at', + }); + + return PackageMaterialItemRelation; +}; diff --git a/app/model/package_supplier.js b/app/model/package_supplier.js new file mode 100644 index 0000000..1306ed1 --- /dev/null +++ b/app/model/package_supplier.js @@ -0,0 +1,89 @@ +'use strict'; + +/** + * 包材供应商模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, INTEGER, DATE } = app.Sequelize; + + const PackageSupplier = app.model.define('package_supplier', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + supplier_code: { + type: STRING(64), + allowNull: false, + comment: '供应商编码', + }, + supplier_name: { + type: STRING(128), + allowNull: false, + comment: '供应商名称', + }, + contact_name: { + type: STRING(64), + allowNull: true, + comment: '联系人', + }, + contact_phone: { + type: STRING(32), + allowNull: true, + comment: '联系电话', + }, + status: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:0=禁用,1=启用', + }, + version: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_package_supplier', + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: false, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '包材供应商表', + indexes: [ + { + name: 'idx_wms_package_supplier_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'uk_wms_package_supplier_warehouse_supplier_code', + unique: true, + fields: [ 'warehouse_id', 'supplier_code' ], + }, + ], + }); + + return PackageSupplier; +}; diff --git a/app/model/permission.js b/app/model/permission.js index ead44a8..63dfb2e 100644 --- a/app/model/permission.js +++ b/app/model/permission.js @@ -72,8 +72,11 @@ module.exports = app => { }, parent_id: { type: INTEGER, - allowNull: false, - defaultValue: 0, + allowNull: true, + defaultValue: null, + set(value) { + this.setDataValue('parent_id', value === 0 ? null : value); + }, comment: '父级ID', }, sort: { @@ -105,10 +108,10 @@ module.exports = app => { comment: '更新时间', }, type: { - type: ENUM('web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block'), + type: ENUM('web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block', 'workerstation_pages'), allowNull: false, defaultValue: 'web_pages', - comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块)', + comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块,workerstation_pages:工作台菜单)', }, }, { tableName: 'wms_permission', @@ -132,8 +135,8 @@ module.exports = app => { }); // 关联关系 - 自关联,构建树形结构 - Permission.associate = function(models) { - const { Role, Permission, RolePermission } = app.model; + Permission.associate = function() { + const { Permission } = app.model; // 子权限 Permission.hasMany(Permission, { foreignKey: 'parent_id', @@ -149,13 +152,6 @@ module.exports = app => { as: 'parent', }); - // 角色权限关联 - Permission.belongsToMany(Role, { - through: RolePermission, - foreignKey: 'permission_id', - otherKey: 'role_id', - as: 'roles', - }); }; // 实例方法:获取类型对应的中文名称 @@ -167,6 +163,7 @@ module.exports = app => { api: '接口权限', miniprogram_pages: '小程序页面', block: '功能模块', + workerstation_pages: '工作台菜单', }; return typeMap[this.type] || this.type; }; @@ -242,7 +239,7 @@ module.exports = app => { permissions.forEach(permission => { const node = permissionMap.get(permission.id); - if (permission.parent_id === 0) { + if (!permission.parent_id) { rootPermissions.push(node); } else { const parent = permissionMap.get(permission.parent_id); diff --git a/app/model/picking.js b/app/model/picking.js new file mode 100644 index 0000000..f731c97 --- /dev/null +++ b/app/model/picking.js @@ -0,0 +1,154 @@ +'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', + }, + warehouse_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', + }, + stock_id: { + type: BIGINT(20), + allowNull: true, + comment: '商品SKU 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_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + 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' ], + }, + { + name: 'idx_wms_picking_warehouse_stock', + fields: [ 'warehouse_id', 'stock_id' ], + }, + ], + }); + + Picking.associate = function() { + const { OrderItems, Storage, LocationSpace, StockWarehouse } = 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, + }); + } + + if (StockWarehouse) { + Picking.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stock', + constraints: false, + }); + } + }; + + return Picking; +}; diff --git a/app/model/picking_strategy.js b/app/model/picking_strategy.js new file mode 100644 index 0000000..bf9b067 --- /dev/null +++ b/app/model/picking_strategy.js @@ -0,0 +1,177 @@ +// app/model/picking_strategy.js +'use strict'; + +/** + * 波次策略模型定义。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 波次策略模型 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, TINYINT, BOOLEAN, JSON, TEXT, DATE } = app.Sequelize; + + const WaveStrategy = app.model.define('wms_wave_strategy', { + id: { + type: INTEGER, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '策略ID', + }, + strategy_name: { + type: STRING(100), + allowNull: false, + comment: '策略名称', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + strategy_type: { + type: TINYINT, + allowNull: false, + comment: '策略类型:1-散单 2-团购 3-SN(序列号管理,固定先拣后分)', + }, + status: { + type: TINYINT, + allowNull: true, + defaultValue: 1, + comment: '状态:1-启用 0-停用', + }, + order_min_sku: { + type: INTEGER, + allowNull: true, + defaultValue: 1, + comment: '订单最小SKU种类数', + }, + order_max_sku: { + type: INTEGER, + allowNull: true, + defaultValue: 999, + comment: '订单最大SKU种类数', + }, + order_min_qty: { + type: INTEGER, + allowNull: true, + defaultValue: 1, + comment: '订单最小商品总数', + }, + order_max_qty: { + type: INTEGER, + allowNull: true, + defaultValue: 999, + comment: '订单最大商品总数', + }, + min_same_structure: { + type: INTEGER, + allowNull: true, + defaultValue: 1, + comment: '最小相同结构订单数', + }, + max_same_structure: { + type: INTEGER, + allowNull: true, + defaultValue: 999, + comment: '最大相同结构订单数', + }, + require_same_express: { + type: BOOLEAN, + allowNull: true, + defaultValue: false, + comment: '是否要求相同快递', + }, + allow_cross_owner: { + type: BOOLEAN, + allowNull: true, + defaultValue: true, + comment: '是否允许跨货主', + }, + batch_mode: { + type: TINYINT, + allowNull: false, + comment: '拣货模式:1-单品单件 2-先拣后分 3-边拣边分 4-边拣边分H型 5-播种墙 6-流利架', + }, + batch_max_orders: { + type: INTEGER, + allowNull: true, + defaultValue: 20, + comment: '批次最大订单数', + }, + batch_max_skus: { + type: INTEGER, + allowNull: true, + defaultValue: 50, + comment: '批次最大SKU总数', + }, + group_batch_max_orders: { + type: INTEGER, + allowNull: true, + defaultValue: 1, + comment: '团购批次最大订单数(相同结构)', + }, + wave_prefix: { + type: STRING(5), + allowNull: true, + comment: '波次前缀(为空时回退仓库前缀)', + }, + allowed_owners: { + type: JSON, + allowNull: true, + comment: '允许的货主ID列表', + }, + allowed_expresses: { + type: JSON, + allowNull: true, + comment: '允许的快递编码列表', + }, + allowed_provinces: { + type: JSON, + allowNull: true, + comment: '允许的省份列表', + }, + allowed_platforms: { + type: JSON, + allowNull: true, + comment: '允许的平台列表', + }, + description: { + type: TEXT, + allowNull: true, + comment: '策略描述', + }, + creator_name: { + type: STRING(50), + allowNull: true, + comment: '创建人姓名', + }, + create_time: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_wave_strategy', + timestamps: false, + underscored: false, + comment: '波次策略配置表', + indexes: [ + { + name: 'idx_warehouse_type', + fields: [ 'warehouse_id', 'strategy_type', 'status' ], + }, + { + name: 'idx_batch_mode', + fields: [ 'batch_mode', 'strategy_type' ], + }, + ], + }); + + return WaveStrategy; +}; diff --git a/app/model/platform.js b/app/model/platform.js index 4ca97b4..ee16114 100644 --- a/app/model/platform.js +++ b/app/model/platform.js @@ -1,7 +1,12 @@ 'use strict'; +/** + * 平台表模型定义。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 平台模型 + */ module.exports = app => { - const { STRING } = app.Sequelize; + const { STRING, BIGINT } = app.Sequelize; const Platform = app.model.define('platform', { code: { @@ -12,13 +17,53 @@ module.exports = app => { }, name: { type: STRING(255), - allowNull: false, + allowNull: true, comment: '平台名称', }, - default_express_interface: { + interface_url: { + type: STRING(255), + allowNull: true, + comment: '接口地址', + }, + appkey: { + type: STRING(255), + allowNull: true, + comment: '应用Key', + }, + app_secret: { + type: STRING(255), + allowNull: true, + comment: '应用密钥', + }, + token: { + type: STRING(255), + allowNull: true, + comment: '访问令牌', + }, + version: { + type: STRING(255), + allowNull: true, + comment: '接口版本', + }, + shoptype: { type: STRING(50), - allowNull: false, - comment: '默认快递接口', + allowNull: true, + comment: '店铺类型', + }, + ordersource: { + type: STRING(50), + allowNull: true, + comment: '订单来源', + }, + component: { + type: STRING(255), + allowNull: true, + comment: '打印组件标识', + }, + print_platform_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联打印平台ID', }, }, { tableName: 'wms_platform', @@ -28,8 +73,5 @@ module.exports = app => { comment: '平台表', }); - // 移除 associate 方法,稍后在单独的初始化文件中定义关联 - // 或者在控制器中动态定义关联 - return Platform; }; diff --git a/app/model/platform_print_config.js b/app/model/platform_print_config.js new file mode 100644 index 0000000..0afc346 --- /dev/null +++ b/app/model/platform_print_config.js @@ -0,0 +1,96 @@ +// app/model/platform_print_config.js +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; + + const PlatformPrintConfig = app.model.define('wms_platform_print_config', { + id: { + type: BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + platform: { + type: STRING(50), + allowNull: false, + unique: true, + comment: '平台名称', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '平台代码', + }, + print_port: { + type: STRING(20), + allowNull: false, + comment: '打印服务端口', + }, + print_url: { + type: STRING(200), + allowNull: true, + comment: '打印服务URL', + }, + protocol_type: { + type: STRING(20), + allowNull: true, + defaultValue: 'WEBSOCKET', + comment: '协议类型:WEBSOCKET,HTTP', + }, + status: { + type: STRING(20), + allowNull: true, + defaultValue: 'ACTIVE', + comment: '状态:ACTIVE-启用,DISABLED-禁用', + }, + retry_count: { + type: INTEGER, + allowNull: true, + defaultValue: 3, + comment: '重试次数', + }, + timeout_seconds: { + type: INTEGER, + allowNull: true, + defaultValue: 30, + comment: '超时时间(秒)', + }, + description: { + type: STRING(200), + allowNull: true, + comment: '描述', + }, + create_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_platform_print_config', + timestamps: false, + underscored: false, + comment: '平台打印端口配置表', + indexes: [ + { + name: 'uk_platform', + unique: true, + fields: [ 'platform' ], + }, + { + name: 'idx_platform_code', + fields: [ 'platform_code' ], + }, + ], + }); + + return PlatformPrintConfig; +}; diff --git a/app/model/platform_setting.js b/app/model/platform_setting.js index 7ad3dc1..1cb52dd 100644 --- a/app/model/platform_setting.js +++ b/app/model/platform_setting.js @@ -1,9 +1,14 @@ -'use strict'; +'use strict'; +/** + * 平台设置模型定义。 + * + * @param {Egg.Application} app 应用实例 + * @return {Object} 平台设置模型 + */ module.exports = app => { const { STRING, BIGINT, INTEGER } = app.Sequelize; - // 修改这里的变量名,与文件名一致 const PlatformSetting = app.model.define('platform_setting', { id: { type: INTEGER(11), @@ -22,10 +27,15 @@ module.exports = app => { allowNull: false, comment: '设置代码', }, + name: { + type: STRING(100), + allowNull: false, + comment: '别名', + }, warehouse_id: { type: BIGINT(20), - allowNull: false, - comment: '仓库ID', + allowNull: true, + comment: '仓库ID,NULL表示系统级设置', }, }, { tableName: 'wms_platfrom_setting', @@ -34,33 +44,40 @@ module.exports = app => { comment: '平台设置表', indexes: [ { - name: 'platform_code', + name: 'uk_platform_setting_warehouse_platform_code', unique: true, fields: [ 'platform_code', 'warehouse_id' ], }, { - name: 'warehouse_id', + name: 'uk_platform_setting_warehouse_code', + unique: true, + fields: [ 'code', 'warehouse_id' ], + }, + { + name: 'idx_platform_setting_warehouse_id', fields: [ 'warehouse_id' ], }, ], }); - // 定义关联关系 + + /** + * 定义平台设置关联关系。 + */ PlatformSetting.associate = function() { const { Store, Platform } = app.model; - // 关联仓库 PlatformSetting.belongsTo(Platform, { foreignKey: 'platform_code', targetKey: 'code', as: 'platform', }); - // 关联仓库 + PlatformSetting.belongsTo(Store, { foreignKey: 'warehouse_id', targetKey: 'id', as: 'warehouse', }); }; - // 返回正确的变量名 + return PlatformSetting; }; diff --git a/app/model/print_computer.js b/app/model/print_computer.js index c7a1e5f..2d8c463 100644 --- a/app/model/print_computer.js +++ b/app/model/print_computer.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { INTEGER, BIGINT, STRING } = app.Sequelize; + const { INTEGER, BIGINT, STRING, DATE, BOOLEAN } = app.Sequelize; const PrintComputer = app.model.define('print_computer', { id: { @@ -27,6 +27,41 @@ module.exports = app => { defaultValue: 1, comment: '状态,1-已激活,0-未激活', }, + last_login_time: { + type: DATE, + allowNull: true, + comment: '上次登录时间', + }, + is_recording: { + type: BOOLEAN, + allowNull: false, + defaultValue: false, + comment: '是否作为录制电脑,1-是,0-否', + }, + recording_size_value: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }, + recording_size_unit: { + type: STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }, + recording_directory: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径', + }, + deleted_at: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, }, { tableName: 'wms_print_computer', freezeTableName: true, diff --git a/app/model/print_item.js b/app/model/print_item.js index 4f15350..16bf6cc 100644 --- a/app/model/print_item.js +++ b/app/model/print_item.js @@ -1,6 +1,7 @@ // app/model/print_item.js module.exports = app => { - const { STRING, INTEGER, BOOLEAN, TEXT, JSON, DATE } = app.Sequelize; + const { STRING, INTEGER, BOOLEAN, JSON, DATE } = app.Sequelize; + const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ]; const PrintItem = app.model.define('print_item', { id: { @@ -15,6 +16,7 @@ module.exports = app => { comment: '业务类型', validate: { notEmpty: true, + isIn: [ SUPPORTED_BUSINESS_TYPES ], }, }, platform: { @@ -232,37 +234,6 @@ module.exports = app => { return this.table_config; }; - // 类方法:获取指定业务类型的分组字段 - PrintItem.getGroupFields = async function(businessType, platform) { - return await this.findAll({ - where: { - business_type: businessType, - platform: platform || 'default', - group_field: { - [app.Sequelize.Op.ne]: null, - }, - status: 1, - }, - order: [ - [ 'group_sort', 'ASC' ], - [ 'sort_order', 'ASC' ], - ], - }); - }; - - // 类方法:获取指定业务类型的表格配置 - PrintItem.getTableConfigs = async function(businessType, platform) { - return await this.findAll({ - where: { - business_type: businessType, - platform: platform || 'default', - is_table: true, - status: 1, - }, - order: [[ 'sort_order', 'ASC' ]], - }); - }; - // 关联方法 PrintItem.associate = function() { // 如果需要关联其他表,在这里添加 diff --git a/app/model/print_log.js b/app/model/print_log.js new file mode 100644 index 0000000..dc0a3e1 --- /dev/null +++ b/app/model/print_log.js @@ -0,0 +1,98 @@ +// app/model/print_log.js +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, TEXT, JSON, DATE } = app.Sequelize; + + const PrintLog = app.model.define('wms_print_log', { + id: { + type: BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + print_record_id: { + type: BIGINT, + allowNull: false, + comment: '打印记录ID', + }, + log_type: { + type: STRING(20), + allowNull: false, + comment: '日志类型:CONNECT-连接,PRINT-打印,RETRY-重试,ERROR-错误,SUCCESS-成功', + }, + log_level: { + type: STRING(10), + allowNull: true, + defaultValue: 'INFO', + comment: '日志级别:INFO,WARN,ERROR', + }, + log_content: { + type: TEXT, + allowNull: false, + comment: '日志内容', + }, + request_data: { + type: JSON, + allowNull: true, + comment: '请求数据', + }, + response_data: { + type: JSON, + allowNull: true, + comment: '响应数据', + }, + websocket_status: { + type: STRING(20), + allowNull: true, + comment: 'WebSocket状态', + }, + error_code: { + type: STRING(50), + allowNull: true, + comment: '错误代码', + }, + ip_address: { + type: STRING(50), + allowNull: true, + comment: 'IP地址', + }, + user_agent: { + type: STRING(500), + allowNull: true, + comment: '用户代理', + }, + create_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_print_log', + timestamps: false, + underscored: false, + comment: '打印日志表', + indexes: [ + { + name: 'idx_print_record', + fields: [ 'print_record_id' ], + }, + { + name: 'idx_log_type', + fields: [ 'log_type' ], + }, + { + name: 'idx_create_time', + fields: [ 'create_time' ], + }, + { + name: 'idx_error_code', + fields: [ 'error_code' ], + }, + ], + }); + + return PrintLog; +}; diff --git a/app/model/print_platform.js b/app/model/print_platform.js new file mode 100644 index 0000000..bb45df8 --- /dev/null +++ b/app/model/print_platform.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * 打印平台元数据模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 打印平台元数据模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE, TINYINT, INTEGER, TEXT } = app.Sequelize; + + const PrintPlatform = app.model.define('print_platform', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '打印平台编码', + }, + platform_name: { + type: STRING(100), + allowNull: false, + comment: '打印平台名称', + }, + platid: { + type: INTEGER(11), + allowNull: true, + comment: '平台ID', + }, + request_platform_code: { + type: STRING(50), + allowNull: true, + comment: '请求平台编码', + }, + need_callback_url: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否需要回调地址:0-否,1-是', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'ACTIVE', + comment: '状态', + }, + remark: { + type: STRING(255), + allowNull: true, + comment: '备注', + }, + auth_base_url: { + type: TEXT, + allowNull: true, + comment: '授权基础地址', + }, + get_auth_platform_name: { + type: STRING(100), + allowNull: true, + comment: '获取授权平台名称', + }, + create_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted: { + type: TINYINT, + allowNull: false, + defaultValue: 0, + comment: '软删除标记:0-未删除,1-已删除', + }, + }, { + tableName: 'wms_print_platform', + timestamps: false, + comment: '打印平台元数据表', + indexes: [ + { + name: 'uk_platform_code', + unique: true, + fields: [ 'platform_code' ], + }, + { + name: 'idx_status', + fields: [ 'status' ], + }, + ], + }); + + return PrintPlatform; +}; diff --git a/app/model/print_record.js b/app/model/print_record.js index 3a33609..e43b05a 100644 --- a/app/model/print_record.js +++ b/app/model/print_record.js @@ -1,85 +1,179 @@ -"use strict"; +'use strict'; module.exports = app => { - const { BIGINT, STRING, JSON, ENUM, TEXT, DATE } = app.Sequelize; - const PrintRecord = app.model.define("PrintRecord", { + const { BIGINT, STRING, JSON, ENUM, TEXT, DATE, INTEGER } = app.Sequelize; + const PrintRecord = app.model.define('PrintRecord', { id: { type: BIGINT.UNSIGNED, autoIncrement: true, primaryKey: true, - comment: "主键ID", + comment: '主键ID', }, warehouse_id: { type: BIGINT.UNSIGNED, allowNull: false, - comment: "仓库ID", + comment: '仓库ID', }, computer_id: { type: BIGINT.UNSIGNED, allowNull: false, - comment: "电脑ID", + comment: '电脑ID', }, printer: { type: STRING(100), allowNull: false, - comment: "打印机名称/标识", + comment: '打印机名称/标识', }, type: { type: STRING(50), allowNull: false, - comment: "打印类型", + comment: '打印类型', }, data: { type: JSON, allowNull: true, - comment: "打印数据(JSON格式)", + comment: '打印数据(JSON格式)', }, status: { - type: ENUM("pending", "sent", "success", "failed"), + type: ENUM('pending', 'sent', 'success', 'failed'), allowNull: false, - defaultValue: "pending", - comment: "打印状态:pending-待发送,sent-已发送,success-打印成功,failed-打印失败", + defaultValue: 'pending', + comment: '打印状态:pending-待发送,sent-已发送,success-打印成功,failed-打印失败', + }, + send_status: { + type: STRING(32), + allowNull: false, + defaultValue: 'pending', + comment: '发送状态', + }, + print_status: { + type: STRING(32), + allowNull: false, + defaultValue: 'unknown', + comment: '打印状态', + }, + retry_count: { + type: INTEGER, + allowNull: false, + defaultValue: 0, + comment: '已重试次数', + }, + max_retry_count: { + type: INTEGER, + allowNull: false, + defaultValue: 3, + comment: '最大重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次重试时间', + }, + last_retry_at: { + type: DATE, + allowNull: true, + comment: '最后重试时间', + }, + fail_code: { + type: STRING(64), + allowNull: true, + comment: '失败编码', + }, + retry_of_print_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '补偿来源打印记录ID', }, error_message: { type: TEXT, allowNull: true, - comment: "错误信息", + comment: '错误信息', + }, + print_task_code: { + type: TEXT, + allowNull: true, + comment: '自定义打印任务编码,多个编码以逗号分隔', + }, + request_code: { + type: STRING(128), + allowNull: true, + comment: '请求参数码', + }, + wave_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '波次ID', + }, + wave_no: { + type: STRING(64), + allowNull: true, + comment: '波次号', + }, + platform_code: { + type: STRING(32), + allowNull: true, + comment: '平台编码', + }, + platform_name: { + type: STRING(64), + allowNull: true, + comment: '平台名称', + }, + sys_logistics_code: { + type: STRING(32), + allowNull: true, + comment: '系统快递编码', + }, + sys_logistics_name: { + type: STRING(64), + allowNull: true, + comment: '系统快递名称', }, sent_time: { type: DATE, allowNull: true, - comment: "发送时间", + comment: '发送时间', }, print_time: { type: DATE, allowNull: true, - comment: "打印完成时间", + comment: '打印完成时间', }, created_at: { type: DATE, allowNull: false, - defaultValue: app.Sequelize.literal("CURRENT_TIMESTAMP"), - comment: "创建时间", + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', }, updated_at: { type: DATE, allowNull: false, - defaultValue: app.Sequelize.literal("CURRENT_TIMESTAMP"), - comment: "更新时间", + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', }, }, { - tableName: "wms_print_record", + tableName: 'wms_print_record', freezeTableName: true, underscored: false, timestamps: false, indexes: [ - { name: "idx_warehouse_id", fields: ["warehouse_id"] }, - { name: "idx_computer_id", fields: ["computer_id"] }, - { name: "idx_status", fields: ["status"] }, - { name: "idx_created_at", fields: ["created_at"] }, - { name: "idx_sent_time", fields: ["sent_time"] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_computer_id', fields: [ 'computer_id' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + { name: 'idx_created_at', fields: [ 'created_at' ] }, + { name: 'idx_sent_time', fields: [ 'sent_time' ] }, + { name: 'idx_send_status', fields: [ 'send_status' ] }, + { name: 'idx_print_status', fields: [ 'print_status' ] }, + { name: 'idx_next_retry_at', fields: [ 'next_retry_at' ] }, + { name: 'idx_retry_of_print_id', fields: [ 'retry_of_print_id' ] }, + { name: 'idx_print_status_next_retry', fields: [ 'print_status', 'next_retry_at' ] }, + { name: 'idx_request_code', fields: [ 'request_code' ] }, + { name: 'idx_wave_id', fields: [ 'wave_id' ] }, + { name: 'idx_platform_code', fields: [ 'platform_code' ] }, + { name: 'idx_sys_logistics_code', fields: [ 'sys_logistics_code' ] }, + { name: 'idx_wave_platform_status', fields: [ 'wave_id', 'platform_code', 'status' ] }, ], - comment: "打印记录表", + comment: '打印记录表', }); return PrintRecord; diff --git a/app/model/print_station_express.js b/app/model/print_station_express.js deleted file mode 100644 index eb6457a..0000000 --- a/app/model/print_station_express.js +++ /dev/null @@ -1,86 +0,0 @@ -"use strict"; - -module.exports = app => { - const { INTEGER, BIGINT, STRING, DATE, TINYINT } = app.Sequelize; - const PrintStationExpress = app.model.define('print_station_express', { - id: { - type: INTEGER.UNSIGNED, - autoIncrement: true, - primaryKey: true, - comment: '自增主键ID', - }, - print_station_id: { - type: STRING(32), - allowNull: false, - comment: '打印台ID,关联wms_print_stations表的print_station_id', - }, - express_id: { - type: STRING(32), - allowNull: false, - comment: '快递ID', - }, - express_name: { - type: STRING(50), - allowNull: false, - comment: '快递名称,冗余字段,便于查询', - }, - printer_name: { - type: STRING(100), - allowNull: false, - comment: '绑定的打印机名称', - }, - creator_id: { - type: BIGINT.UNSIGNED, - allowNull: false, - comment: '创建人工号ID', - }, - creator_name: { - type: STRING(50), - allowNull: false, - comment: '创建人名称', - }, - create_at: { - type: DATE, - allowNull: false, - comment: '创建时间', - }, - update_at: { - type: DATE, - allowNull: false, - comment: '更新时间', - }, - deleted: { - type: TINYINT, - allowNull: false, - defaultValue: 0, - comment: '软删除标记:0-未删除,1-已删除', - }, - }, { - tableName: 'wms_print_station_express', - freezeTableName: true, - underscored: false, - timestamps: false, - indexes: [ - { - unique: true, - name: 'uk_print_station_express', - fields: ['print_station_id', 'express_id', 'deleted'], - }, - { - name: 'idx_print_station_id', - fields: ['print_station_id'], - }, - { - name: 'idx_express_id', - fields: ['express_id'], - }, - { - name: 'idx_creator_id', - fields: ['creator_id'], - }, - ], - comment: '打印台快递-打印机绑定关系表', - }); - - return PrintStationExpress; -}; diff --git a/app/model/print_stations.js b/app/model/print_stations.js index 877d5ce..eb4c5b0 100644 --- a/app/model/print_stations.js +++ b/app/model/print_stations.js @@ -1,7 +1,83 @@ -"use strict"; +'use strict'; module.exports = app => { - const { INTEGER, BIGINT, STRING, DATE, TINYINT } = app.Sequelize; + const { INTEGER, BIGINT, STRING, DATE, TINYINT, JSON: JSON_TYPE } = app.Sequelize; + + const DEFAULT_SUBJECT_CONFIG = Object.freeze({ + express_bind_printer: Object.freeze([]), + }); + + /** + * 规范化快递绑定打印机配置。 + * + * @param {Array|null|undefined|string} rawList 原始快递绑定打印机配置。 + * @return {Array} 规范化后的快递绑定打印机配置。 + */ + const normalizeExpressBindPrinter = rawList => { + if (rawList === undefined || rawList === null || rawList === '') { + return []; + } + + if (!Array.isArray(rawList)) { + throw new Error('subject_config.express_bind_printer 必须是数组'); + } + + return rawList.map((item, index) => { + const basePath = `subject_config.express_bind_printer[${index}]`; + if (!item || typeof item !== 'object' || Array.isArray(item)) { + throw new Error(`${basePath} 必须是对象`); + } + + const printerName = String(item.printer_name === undefined || item.printer_name === null ? '' : item.printer_name).trim(); + if (!printerName) { + throw new Error(`${basePath}.printer_name 不能为空`); + } + + const expressCode = String(item.express_code === undefined || item.express_code === null ? '' : item.express_code).trim(); + if (!expressCode) { + throw new Error(`${basePath}.express_code 不能为空`); + } + + return { + printer_name: printerName, + express_code: expressCode, + }; + }); + }; + + /** + * 规范化打印台主体配置。 + * + * @param {Object|string|null|undefined} rawValue 原始主体配置。 + * @return {Object} 规范化后的主体配置。 + */ + const normalizeSubjectConfig = rawValue => { + if (rawValue === undefined || rawValue === null || rawValue === '') { + return { + ...DEFAULT_SUBJECT_CONFIG, + express_bind_printer: [], + }; + } + + let parsed = rawValue; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + throw new Error('subject_config 必须是合法 JSON 对象'); + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error('subject_config 必须是对象'); + } + + return { + ...parsed, + express_bind_printer: normalizeExpressBindPrinter(parsed.express_bind_printer), + }; + }; + const PrintStations = app.model.define('print_stations', { id: { type: INTEGER.UNSIGNED, @@ -14,10 +90,10 @@ module.exports = app => { allowNull: false, comment: '仓库ID', }, - default_printer_name:{ - type: STRING(50), - allowNull: true, - comment: '默认打印机名称', + default_printer_name: { + type: STRING(50), + allowNull: true, + comment: '默认打印机名称', }, name: { type: STRING(100), @@ -60,6 +136,29 @@ module.exports = app => { defaultValue: 0, comment: '软删除标记:0-未删除,1-已删除', }, + deleted_at: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + subject_config: { + type: JSON_TYPE, + allowNull: true, + defaultValue: { ...DEFAULT_SUBJECT_CONFIG, express_bind_printer: [] }, + comment: '打印台主体配置', + get() { + return normalizeSubjectConfig(this.getDataValue('subject_config')); + }, + set(value) { + this.setDataValue('subject_config', normalizeSubjectConfig(value)); + }, + validate: { + isValidSubjectConfig(value) { + normalizeSubjectConfig(value); + }, + }, + }, }, { tableName: 'wms_print_stations', freezeTableName: true, @@ -69,35 +168,38 @@ module.exports = app => { { unique: true, name: 'uk_print_station_id', - fields: ['print_station_id'], + fields: [ 'print_station_id' ], }, { name: 'idx_warehouse_id', - fields: ['warehouse_id'], + fields: [ 'warehouse_id' ], }, { name: 'idx_computer_id', - fields: ['computer_id'], + fields: [ 'computer_id' ], }, { name: 'idx_name', - fields: ['name'], + fields: [ 'name' ], }, { name: 'idx_custom_barcode', - fields: ['custom_barcode'], + fields: [ 'custom_barcode' ], }, { name: 'idx_creator_id', - fields: ['creator_id'], + fields: [ 'creator_id' ], }, { name: 'idx_create_at', - fields: ['create_at'], + fields: [ 'create_at' ], }, ], comment: '打印台信息表', }); + PrintStations.DEFAULT_SUBJECT_CONFIG = DEFAULT_SUBJECT_CONFIG; + PrintStations.normalizeSubjectConfig = normalizeSubjectConfig; + return PrintStations; }; diff --git a/app/model/print_task_map.js b/app/model/print_task_map.js new file mode 100644 index 0000000..0789488 --- /dev/null +++ b/app/model/print_task_map.js @@ -0,0 +1,59 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const PrintTaskMap = app.model.define('PrintTaskMap', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_code: { + type: STRING(128), + allowNull: false, + comment: '打印任务编码', + }, + print_record_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联打印记录ID', + }, + provider: { + type: STRING(64), + allowNull: true, + comment: 'provider返回任务ID或标识', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_print_task_map', + freezeTableName: true, + underscored: false, + timestamps: false, + comment: '打印任务唯一映射表', + indexes: [ + { + name: 'uix_task_code', + unique: true, + fields: [ 'task_code' ], + }, + { + name: 'idx_print_record_id', + fields: [ 'print_record_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + return PrintTaskMap; +}; diff --git a/app/model/print_template.js b/app/model/print_template.js index fa08f22..c4c781c 100644 --- a/app/model/print_template.js +++ b/app/model/print_template.js @@ -3,6 +3,7 @@ module.exports = app => { const { BIGINT, STRING, INTEGER, BOOLEAN, JSON, DATE, DATEONLY } = app.Sequelize; + const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ]; const PrintTemplate = app.model.define('print_template', { id: { @@ -46,7 +47,7 @@ module.exports = app => { comment: '页面高度(mm)', }, warehouse_id: { - type: BIGINT(20), + type: BIGINT(20).UNSIGNED, comment: '关联仓库ID', }, is_default: { @@ -75,6 +76,10 @@ module.exports = app => { type: STRING(10), allowNull: false, comment: '类型', + validate: { + notEmpty: true, + isIn: [ SUPPORTED_BUSINESS_TYPES ], + }, }, delete_at: { type: DATEONLY, diff --git a/app/model/qimen_app.js b/app/model/qimen_app.js index 70164fb..57a85d3 100644 --- a/app/model/qimen_app.js +++ b/app/model/qimen_app.js @@ -1,5 +1,10 @@ 'use strict'; +/** + * 定义奇门应用配置模型。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 奇门应用配置模型 + */ module.exports = app => { const { INTEGER, STRING, DATE } = app.Sequelize; @@ -28,6 +33,14 @@ module.exports = app => { }, comment: '应用密钥', }, + customer_id: { + type: STRING(100), + allowNull: true, + validate: { + len: [ 0, 100 ], + }, + comment: '客户标识', + }, created_at: { type: DATE, allowNull: false, @@ -59,7 +72,10 @@ module.exports = app => { ], }); - // 定义实例方法 + /** + * 输出模型的 JSON 数据。 + * @return {object} 当前实例的普通对象数据 + */ QimenApp.prototype.toJSON = function() { const values = { ...this.get() }; return values; diff --git a/app/model/qimen_log.js b/app/model/qimen_log.js index 7f9ed9e..a844adb 100644 --- a/app/model/qimen_log.js +++ b/app/model/qimen_log.js @@ -3,7 +3,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, BIGINT, TEXT, DATE, BOOLEAN } = app.Sequelize; + const { STRING, INTEGER, BIGINT, TEXT, DATE } = app.Sequelize; const QimenLog = app.model.define('qimen_log', { id: { @@ -11,6 +11,12 @@ module.exports = app => { primaryKey: true, autoIncrement: true, }, + log_id: { + type: STRING(32), + allowNull: true, + unique: true, + field: 'log_id', + }, from_key: { type: INTEGER(10), allowNull: true, diff --git a/app/model/receiving.js b/app/model/receiving.js index f659bf7..71ae988 100644 --- a/app/model/receiving.js +++ b/app/model/receiving.js @@ -1,6 +1,6 @@ // app/model/receiving.js module.exports = app => { - const { STRING, INTEGER, DATE, DECIMAL, TEXT, BOOLEAN, ENUM } = app.Sequelize; + const { STRING, INTEGER, BIGINT, DATE, TEXT, BOOLEAN, ENUM, TINYINT } = app.Sequelize; const Receiving = app.model.define('wms_receiving', { id: { @@ -38,10 +38,10 @@ module.exports = app => { comment: '明细匹配状态:all_matched-全部匹配, partial_matched-部分匹配, unmatched-未匹配', }, storage_status: { - type: ENUM('none', 'partial', 'all'), + type: ENUM('none', 'waiting', 'partial', 'all'), defaultValue: 'none', allowNull: false, - comment: '入库状态:none-未入库, partial-部分入库, all-全部入库', + comment: '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库', }, delivery_method: { type: ENUM('truck', 'express', 'air_freight', 'sea_freight', 'other'), @@ -108,6 +108,22 @@ module.exports = app => { type: DATE, comment: '收货结束时间', }, + is_review: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否已审核:0-未审核,1-已审核', + }, + reviewer_name: { + type: STRING(50), + allowNull: true, + comment: '审核人姓名', + }, + reviewer_employee_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '审核人员工ID,关联 wms_account_store_employee.id', + }, is_deleted: { type: BOOLEAN, defaultValue: false, @@ -144,7 +160,7 @@ module.exports = app => { // 关联定义 Receiving.associate = function() { - const { ReceivingDetail, Store, AccountStoreEmployee, Storage, StoreWarehouse } = app.model; + const { ReceivingDetail, Store, AccountStoreEmployee, StoreWarehouse, EntryOrderReceiving } = app.model; // 关联收货明细 Receiving.hasMany(ReceivingDetail, { foreignKey: 'receiving_id', @@ -163,15 +179,18 @@ module.exports = app => { as: 'creator', }); - // 关联入库记录 - Receiving.hasMany(Storage, { - foreignKey: 'receiving_id', - as: 'storage_records', - }); + // wms_storage 无 receiving_id 字段,避免声明无效关联。 Receiving.belongsTo(StoreWarehouse, { foreignKey: 'store_id', // 当前表的外键字段 - targetKey: 'store_id', // 关联表的主键字段 + targetKey: 'store_id', // 关联表的业务键字段(非主键) as: 'store', + constraints: false, + }); + + // 关联入库单-收货单绑定记录 + Receiving.hasMany(EntryOrderReceiving, { + foreignKey: 'receiving_id', + as: 'entryOrderBindings', }); }; diff --git a/app/model/receiving_detail.js b/app/model/receiving_detail.js index d13d902..6dafaef 100644 --- a/app/model/receiving_detail.js +++ b/app/model/receiving_detail.js @@ -1,6 +1,6 @@ // app/model/receiving_detail.js module.exports = app => { - const { STRING, INTEGER, DATE, DECIMAL, TEXT, ENUM, BOOLEAN, BIGINT } = app.Sequelize; + const { STRING, INTEGER, DATE, DECIMAL, TEXT, ENUM, BIGINT } = app.Sequelize; const ReceivingDetail = app.model.define('wms_receiving_detail', { id: { @@ -61,9 +61,9 @@ module.exports = app => { comment: '收货状态', }, storage_status: { - type: ENUM('none', 'partial', 'all'), + type: ENUM('none', 'waiting', 'partial', 'all'), defaultValue: 'none', - comment: '入库状态:none-未入库, partial-部分入库, all-全部入库', + comment: '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库', }, stored_quantity: { type: INTEGER, @@ -105,7 +105,22 @@ module.exports = app => { type: DECIMAL(10, 2), }, weight: { + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '重量(g)', + }, + box_remainder: { type: INTEGER, + allowNull: false, + defaultValue: 0, + comment: '箱余数', + }, + box_weight: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '箱重量(g)', }, }, { tableName: 'wms_receiving_detail', @@ -143,7 +158,7 @@ module.exports = app => { }); ReceivingDetail.associate = function() { - const { Receiving, StockWarehouse, Storage, LocationSpace } = app.model; + const { Receiving, StockWarehouse, LocationSpace } = app.model; // 关联主表 ReceivingDetail.belongsTo(Receiving, { foreignKey: 'receiving_id', @@ -156,12 +171,6 @@ module.exports = app => { as: 'system_product', }); - // 关联入库记录 - ReceivingDetail.hasMany(Storage, { - foreignKey: 'receiving_detail_id', - as: 'storage_details', - }); - // 关联系统商品 ReceivingDetail.belongsTo(LocationSpace, { foreignKey: 'space_id', diff --git a/app/model/report_definition.js b/app/model/report_definition.js new file mode 100644 index 0000000..823924c --- /dev/null +++ b/app/model/report_definition.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 报表模板定义 Model。 + * 报表采用「配置驱动」:name/type(注册方法 key)/file_name(导出文件名模板)/fields(勾选字段), + * 唯一性由主键 id 承担,新报表只需加配置行,免发版。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + + const ReportDefinition = app.model.define('report_definition', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '报表名称', + }, + type: { + type: STRING(50), + allowNull: false, + comment: '报表类型(内置查询器注册 key,如 stockFlow)', + }, + file_name: { + type: STRING(200), + allowNull: false, + comment: '导出文件名模板(支持 {date}/{time}/{datetime}/{timestamp} 占位,如 7日出入库_{date}.xlsx)', + }, + fields: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '勾选的字段 key 数组(列头/合并/样式/格式化由类型硬编码字段规格决定)', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + remark: { + type: STRING(500), + allowNull: true, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_report_definition', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '报表模板定义表', + indexes: [ + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return ReportDefinition; +}; diff --git a/app/model/report_delivery_log.js b/app/model/report_delivery_log.js new file mode 100644 index 0000000..29a68a4 --- /dev/null +++ b/app/model/report_delivery_log.js @@ -0,0 +1,134 @@ +'use strict'; + +/** + * 报表投递记录 Model。 + * 状态机 pending → exporting → delivered/failed/cancelled; + * 失败按退避重试(retry_count/next_retry_at),幂等键 + * uk_store_report_biz_time 保证同一货主同一报表定义同一数据日期同一时间点不重复投递; + * report_definition_id 关联报表定义,report_name 为投递时报表名称快照(审计回放)。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, DATE, DATEONLY } = app.Sequelize; + + const ReportDeliveryLog = app.model.define('report_delivery_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID(生成报表时注入的仓库维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_definition_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '报表定义ID(wms_report_definition.id)', + }, + report_name: { + type: STRING(100), + allowNull: true, + comment: '报表名称快照(投递时的定义 name,审计回放)', + }, + biz_date: { + type: DATEONLY, + allowNull: false, + comment: '数据日期(T-1 自然日)', + }, + time_point: { + type: STRING(5), + allowNull: false, + comment: '命中的投递时间点(HH:mm)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/exporting/delivered/failed/cancelled', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道快照:inbox=站内信群(wecom/link 已弃用)', + }, + file_url: { + type: STRING(500), + allowNull: true, + comment: '报表文件下载链接(COS 带有效期)', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可投递时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + delivered_at: { + type: DATE, + allowNull: true, + comment: '投递成功时间', + }, + notify_targets: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '投递目标快照:{group_ids:[],member_ids:[]}(本次实际发送的群/成员,审计回放)', + }, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_report_delivery_log', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '报表投递记录表', + indexes: [ + { name: 'uk_store_report_biz_time', unique: true, fields: [ 'store_id', 'report_definition_id', 'biz_date', 'time_point', 'deleted_at' ] }, + { name: 'idx_status_id', fields: [ 'status', 'id' ] }, + { name: 'idx_status_updated_at', fields: [ 'status', 'updated_at' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return ReportDeliveryLog; +}; diff --git a/app/model/report_delivery_plan.js b/app/model/report_delivery_plan.js new file mode 100644 index 0000000..83b3cf0 --- /dev/null +++ b/app/model/report_delivery_plan.js @@ -0,0 +1,115 @@ +'use strict'; + +/** + * 货主报表投递计划 Model。 + * 每个货主(store_id)对每个报表定义(report_definition_id)可配置每日多个投递时间点 + * (schedule_times JSON 数组),由分钟级扫描调度按 HH:mm 命中后生成并投递报表。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, TINYINT, DATE } = app.Sequelize; + + const ReportDeliveryPlan = app.model.define('report_delivery_plan', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_definition_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '报表定义ID(wms_report_definition.id)', + }, + name: { + type: STRING(100), + allowNull: true, + comment: '计划名称(前端展示用,缺省时可用报表名称兜底)', + }, + schedule_times: { + type: app.Sequelize.JSON, + allowNull: false, + comment: '每日投递时间点数组,如 ["08:30","17:00"](HH:mm)', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道:inbox=站内信群(wecom/link 已弃用)', + }, + enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + late_grace_minutes: { + type: INTEGER(11), + allowNull: false, + defaultValue: 60, + comment: '补投宽限分钟:重启/漏跑后在该窗口内补投,超窗作废', + }, + notify_template: { + type: STRING(500), + allowNull: true, + comment: '文本通知模板,支持 {time}/{url}/{report_name}/{biz_date} 标签', + }, + notify_group_ids: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '通知群ID数组(wms_inbox_group.id,多选;空=不指定群)', + }, + notify_member_ids: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '通知成员ID数组(外部IM用户ID,多选;目标侧支持数组)', + }, + remark: { + type: STRING(500), + allowNull: true, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_report_delivery_plan', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '货主报表投递计划表', + indexes: [ + { name: 'uk_store_report_definition', unique: true, fields: [ 'store_id', 'report_definition_id', 'deleted_at' ] }, + { name: 'idx_enabled_deleted', fields: [ 'enabled', 'deleted_at' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return ReportDeliveryPlan; +}; diff --git a/app/model/return_query_log.js b/app/model/return_query_log.js new file mode 100644 index 0000000..e3de87c --- /dev/null +++ b/app/model/return_query_log.js @@ -0,0 +1,85 @@ +'use strict'; + +/** + * 退回查询记录表模型(货主未退回、但做过查询退回的运单号)。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT } = app.Sequelize; + + const ReturnQueryLog = app.model.define('wms_return_query_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(隔离维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(隔离维度)', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '查询过的运单号', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '触发查询的群ID(站内信外部群ID)', + }, + group_name: { + type: STRING(100), + allowNull: true, + comment: '触发查询的群名称', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '触发查询的用户ID(站内信外部用户ID)', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '触发查询的用户名称', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + is_notified: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否已通知:0=未通知,1=已通知', + }, + is_back: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否退回:0=未退回,1=已退回', + }, + }, { + tableName: 'wms_return_query_log', + comment: '退回查询记录表(货主未退回但查询过的运单号)', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'idx_warehouse_store_waybill', fields: [ 'warehouse_id', 'store_id', 'waybill_code' ] }, + { name: 'idx_warehouse_store', fields: [ 'warehouse_id', 'store_id' ] }, + { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, + ], + }); + + return ReturnQueryLog; +}; diff --git a/app/model/return_received.js b/app/model/return_received.js new file mode 100644 index 0000000..afc8eb7 --- /dev/null +++ b/app/model/return_received.js @@ -0,0 +1,114 @@ +'use strict'; + +/** + * 退回收到登记表模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const ReturnReceived = app.model.define('wms_return_received', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '退回收件运单号(扫描到的退回包裹单号)', + }, + scan_date: { + type: DATE, + allowNull: false, + comment: '扫描收到日期', + }, + scanner_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '扫描人员工号ID,关联 wms_account_store_employee.id(employees_id)', + }, + scanner_name: { + type: STRING(50), + allowNull: false, + comment: '扫描人员工号名称快照(employees_name / real_name)', + }, + order_express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '运单表关联字段,关联 wms_order_express.id;原单退回时回填,非原单退回/非本仓库件时为空', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID,方便快速匹配;非原单退回时为空', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,原单退回时回填,用于查货主备注 wms_store_warehouse.store_remask', + }, + return_received_task_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '收件任务ID,关联 wms_return_received_task.id;默认 1=系统预设「历史收件」', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + is_notified: { + type: app.Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '登记是否已通知货主群:0=未通知,1=已通知', + }, + }, { + tableName: 'wms_return_received', + comment: '退回收到登记表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'idx_warehouse_waybill_scan_date', fields: [ 'warehouse_id', 'waybill_code', 'scan_date' ] }, + { name: 'idx_warehouse_scan_date', fields: [ 'warehouse_id', 'scan_date' ] }, + { name: 'idx_warehouse_created_at', fields: [ 'warehouse_id', 'created_at' ] }, + { name: 'idx_scanner_id', fields: [ 'scanner_id' ] }, + { name: 'idx_order_express_id', fields: [ 'order_express_id' ] }, + { name: 'idx_store_id', fields: [ 'store_id' ] }, + { name: 'idx_return_received_task_id', fields: [ 'return_received_task_id' ] }, + ], + }); + + // 关联定义 + ReturnReceived.associate = function() { + const { Store, AccountStoreEmployee, OrderExpress } = app.model; + // 关联仓库(wms_store 主体表) + ReturnReceived.belongsTo(Store, { + foreignKey: 'warehouse_id', + as: 'warehouse', + }); + // 关联扫描人员工号 + ReturnReceived.belongsTo(AccountStoreEmployee, { + foreignKey: 'scanner_id', + as: 'scanner', + }); + // 关联原运单 + ReturnReceived.belongsTo(OrderExpress, { + foreignKey: 'order_express_id', + as: 'orderExpress', + }); + }; + + return ReturnReceived; +}; diff --git a/app/model/return_received_task.js b/app/model/return_received_task.js new file mode 100644 index 0000000..ef37ec3 --- /dev/null +++ b/app/model/return_received_task.js @@ -0,0 +1,70 @@ +'use strict'; + +/** + * 收件任务 Model(退回收件任务分组)。 + * 记录批次号、仓库ID、创建人、创建时间;主键 id 自增从 10000 开始(由迁移设置 AUTO_INCREMENT)。 + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const ReturnReceivedTask = app.model.define('return_received_task', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID(自增从10000开始)', + }, + batch_no: { + type: STRING(50), + allowNull: false, + comment: '批次号', + }, + title: { + type: STRING(100), + allowNull: false, + defaultValue: '', + comment: '标题(任务名称,如系统预设「历史收件」)', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + creator_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '创建人账户ID', + }, + creator_name: { + type: STRING(50), + allowNull: true, + 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_return_received_task', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + // 表无 deleted_at 列,必须显式关闭全局 define 的 paranoid 默认值, + // 否则 findAll/findOne 会拼出 deleted_at 字段导致 Unknown column 报错 + paranoid: false, + comment: '收件任务表(批次号、仓库ID、创建人、创建时间)', + }); + + return ReturnReceivedTask; +}; diff --git a/app/model/return_unpack.js b/app/model/return_unpack.js new file mode 100644 index 0000000..ab50212 --- /dev/null +++ b/app/model/return_unpack.js @@ -0,0 +1,177 @@ +'use strict'; + +/** + * 退回拆包主表模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const ReturnUnpack = app.model.define('wms_return_unpack', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + unpack_no: { + type: STRING(50), + allowNull: false, + unique: true, + comment: '拆包单号,RP+YYYYMMDD+6位序号', + }, + return_received_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联退回收到表 wms_return_received.id;非必填', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '拆包的运单号(退回包裹运单号)', + }, + unpack_date: { + type: DATE, + allowNull: false, + comment: '拆包日期', + }, + start_time: { + type: DATE, + allowNull: true, + comment: '拆包开始时间(参考打包表 start_time)', + }, + end_time: { + type: DATE, + allowNull: true, + comment: '拆包结束时间(参考打包表 end_time)', + }, + unpacker_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '拆包人员工号ID,关联 wms_account_store_employee.id(employees_id)', + }, + unpacker_name: { + type: STRING(50), + allowNull: false, + comment: '拆包人员工号名称快照(employees_name / real_name)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'unpacking', + comment: '拆包状态:unpacking/completed/cancelled', + }, + detail_status: { + type: STRING(30), + allowNull: false, + defaultValue: 'none_recognized', + comment: '明细识别状态:none_recognized/partial_recognized/all_recognized', + }, + total_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '物品种类数(明细行数)', + }, + total_quantity: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '物品总数量(明细数量合计)', + }, + order_express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '原运单ID,关联 wms_order_express.id;原单退回时回填', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '原订单ID,便于快速匹配;原单退回时回填', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,原单退回/识别到系统商品时回填', + }, + source_order_codes: { + type: STRING(500), + allowNull: true, + comment: '平台交易单号快照(原单退回时回填)', + }, + shop_name: { + type: STRING(50), + allowNull: true, + comment: '店铺名称快照(货主自定义店铺名称 store_remask)', + }, + camera_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '摄像头ID列表,如 [1,2,3](参考 wms_pack_task.device_ids)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + }, { + tableName: 'wms_return_unpack', + comment: '退回拆包主表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'uk_unpack_no', unique: true, fields: [ 'unpack_no' ] }, + { name: 'idx_warehouse_unpack_date', fields: [ 'warehouse_id', 'unpack_date' ] }, + { name: 'idx_warehouse_created_at', fields: [ 'warehouse_id', 'created_at' ] }, + { name: 'idx_return_received_id', fields: [ 'return_received_id' ] }, + { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, + { name: 'idx_order_express_id', fields: [ 'order_express_id' ] }, + { name: 'idx_unpacker_id', fields: [ 'unpacker_id' ] }, + { name: 'idx_start_time', fields: [ 'start_time' ] }, + { name: 'idx_store_id', fields: [ 'store_id' ] }, + ], + }); + + ReturnUnpack.associate = function() { + const { Store, AccountStoreEmployee, ReturnReceived, ReturnUnpackDetail, ReturnUnpackVideo, OrderExpress } = app.model; + // 关联仓库(wms_store 主体表) + ReturnUnpack.belongsTo(Store, { + foreignKey: 'warehouse_id', + as: 'warehouse', + }); + // 关联拆包人员工号 + ReturnUnpack.belongsTo(AccountStoreEmployee, { + foreignKey: 'unpacker_id', + as: 'unpacker', + }); + // 关联退回收到单(非必填) + ReturnUnpack.belongsTo(ReturnReceived, { + foreignKey: 'return_received_id', + as: 'returnReceived', + }); + // 关联原运单 + ReturnUnpack.belongsTo(OrderExpress, { + foreignKey: 'order_express_id', + as: 'orderExpress', + }); + // 明细 / 视频 + ReturnUnpack.hasMany(ReturnUnpackDetail, { + foreignKey: 'unpack_id', + as: 'details', + }); + ReturnUnpack.hasMany(ReturnUnpackVideo, { + foreignKey: 'unpack_id', + as: 'videos', + }); + }; + + return ReturnUnpack; +}; diff --git a/app/model/return_unpack_detail.js b/app/model/return_unpack_detail.js new file mode 100644 index 0000000..91709e6 --- /dev/null +++ b/app/model/return_unpack_detail.js @@ -0,0 +1,111 @@ +'use strict'; + +/** + * 退回拆包明细表模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, TEXT, TINYINT } = app.Sequelize; + + const ReturnUnpackDetail = app.model.define('wms_return_unpack_detail', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + unpack_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联拆包主表 wms_return_unpack.id', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + barcode: { + type: STRING(100), + allowNull: true, + comment: '扫描条码(前端可选传入,仅作记录;后端不用于识别)', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_stock_warehouse.id;识别到系统商品时回填,非识别为空', + }, + is_recognized: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否识别:1=识别到系统商品,0=非识别物品', + }, + item_code: { + type: STRING(50), + allowNull: true, + comment: '商品编码快照(识别时回填)', + }, + item_name: { + type: STRING(255), + allowNull: true, + comment: '物品名称(识别时回填;非识别时可手工补录)', + }, + spec: { + type: STRING(100), + allowNull: true, + comment: '规格快照(sku_property)', + }, + quantity: { + type: INTEGER(11), + allowNull: false, + defaultValue: 1, + comment: '数量', + }, + product_status: { + type: STRING(20), + allowNull: false, + defaultValue: 'normal', + comment: '产品状态:normal-正常,damaged-破损', + }, + product_snapshot: { + type: TEXT, + allowNull: true, + comment: '商品信息快照(JSON),识别时回填,防止商品资料变更后历史丢失', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + }, { + tableName: 'wms_return_unpack_detail', + comment: '退回拆包明细表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'idx_unpack_id', fields: [ 'unpack_id' ] }, + { name: 'idx_warehouse_barcode', fields: [ 'warehouse_id', 'barcode' ] }, + { name: 'idx_stock_id', fields: [ 'stock_id' ] }, + { name: 'idx_barcode', fields: [ 'barcode' ] }, + ], + }); + + ReturnUnpackDetail.associate = function() { + const { ReturnUnpack, StockWarehouse } = app.model; + // 关联拆包主表 + ReturnUnpackDetail.belongsTo(ReturnUnpack, { + foreignKey: 'unpack_id', + as: 'unpack', + }); + // 关联系统商品(识别到系统商品时命中) + ReturnUnpackDetail.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stockWarehouse', + }); + }; + + return ReturnUnpackDetail; +}; diff --git a/app/model/return_unpack_video.js b/app/model/return_unpack_video.js new file mode 100644 index 0000000..4eb1219 --- /dev/null +++ b/app/model/return_unpack_video.js @@ -0,0 +1,89 @@ +'use strict'; + +/** + * 退回拆包视频记录表模型(参考 wms_pack_task_video)。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const ReturnUnpackVideo = app.model.define('wms_return_unpack_video', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + unpack_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联拆包主表 wms_return_unpack.id', + }, + camera_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '摄像头设备ID,关联 wms_camera.id', + }, + video_url: { + type: STRING(500), + allowNull: false, + comment: '视频地址(录像回放URL)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'created', + comment: '状态:created-已创建 recording-录制中 completed-已完成 failed-失败', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_return_unpack_video', + comment: '退回拆包视频记录表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + indexes: [ + { name: 'idx_unpack_id', fields: [ 'unpack_id' ] }, + { name: 'idx_camera_id', fields: [ 'camera_id' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + ReturnUnpackVideo.associate = function() { + const { ReturnUnpack, Camera } = app.model; + // 关联拆包主表 + ReturnUnpackVideo.belongsTo(ReturnUnpack, { + foreignKey: 'unpack_id', + as: 'unpack', + }); + // 关联摄像头 + ReturnUnpackVideo.belongsTo(Camera, { + foreignKey: 'camera_id', + as: 'camera', + }); + }; + + return ReturnUnpackVideo; +}; diff --git a/app/model/role.js b/app/model/role.js index cb94c33..05521c2 100644 --- a/app/model/role.js +++ b/app/model/role.js @@ -49,6 +49,11 @@ module.exports = app => { allowNull: true, comment: '角色描述', }, + permissions: { + type: TEXT, + allowNull: true, + comment: '角色权限集,JSON数组;* 表示所有权限', + }, role_type: { type: TINYINT(4), allowNull: false, @@ -117,6 +122,12 @@ module.exports = app => { allowNull: true, comment: '所属仓库ID', }, + pid: { + type: BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '父级角色ID,顶级为0', + }, }, { tableName: 'wms_role', freezeTableName: true, @@ -143,12 +154,16 @@ module.exports = app => { name: 'idx_status', fields: [ 'status' ], }, + { + name: 'idx_pid', + fields: [ 'pid' ], + }, ], }); // 关联关系 - Role.associate = function(models) { - const { Account, Store, Permission, AccountStoreRole, RolePermission, EmployeeRole } = app.model; + Role.associate = function() { + const { Account, Store, EmployeeRole } = app.model; // 创建人 Role.belongsTo(Account, { foreignKey: 'created_by', @@ -161,17 +176,10 @@ module.exports = app => { as: 'store', }); - // 权限关联 - Role.belongsToMany(Permission, { - through: RolePermission, - foreignKey: 'role_id', - otherKey: 'permission_id', - as: 'permissions', - }); Role.hasMany(EmployeeRole, { foreignKey: 'role_id', sourceKey: 'id', - as: 'employeeRole', + as: 'employeeRoles', }); }; @@ -195,75 +203,5 @@ module.exports = app => { return this.scope === 1 ? '全局' : '指定仓库'; }; - // 实例方法:为角色分配权限 - Role.prototype.assignPermissions = async function(permissionIds) { - const { ctx } = this; - - // 先清除现有权限 - await ctx.model.RolePermission.destroy({ - where: { role_id: this.id }, - }); - - // 批量添加新权限 - if (permissionIds && permissionIds.length > 0) { - const rolePermissions = permissionIds.map(permissionId => ({ - role_id: this.id, - permission_id: permissionId, - })); - - await ctx.model.RolePermission.bulkCreate(rolePermissions); - } - - return true; - }; - - // 实例方法:获取角色的所有权限(树形结构) - Role.prototype.getPermissionTree = async function(permissionType = null) { - const { ctx } = this; - - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { role_id: this.id }, - include: [{ - model: ctx.model.Permission, - as: 'permission', - where: { status: 1 }, - required: true, - }], - }); - - // 提取权限ID - const permissionIds = rolePermissions.map(rp => rp.permission.id); - - // 获取权限详情 - const where = { - id: permissionIds, - status: 1, - }; - - if (permissionType) { - where.type = permissionType; - } - - const permissions = await ctx.model.Permission.findAll({ - where, - order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], - }); - - // 构建树形结构 - return ctx.model.Permission.buildPermissionTree(permissions); - }; - - // 实例方法:获取角色的权限ID列表 - Role.prototype.getPermissionIds = async function() { - const { ctx } = this; - - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { role_id: this.id }, - attributes: [ 'permission_id' ], - }); - - return rolePermissions.map(rp => rp.permission_id); - }; - return Role; }; diff --git a/app/model/role_permission.js b/app/model/role_permission.js deleted file mode 100644 index 2b0a4bc..0000000 --- a/app/model/role_permission.js +++ /dev/null @@ -1,145 +0,0 @@ -'use strict'; - -module.exports = app => { - const { BIGINT, DATE } = app.Sequelize; - - const RolePermission = app.model.define('role_permission', { - id: { - type: BIGINT.UNSIGNED, - primaryKey: true, - autoIncrement: true, - allowNull: false, - comment: '关联ID', - }, - role_id: { - type: BIGINT.UNSIGNED, - allowNull: false, - comment: '角色ID', - }, - permission_id: { - type: BIGINT.UNSIGNED, - allowNull: false, - comment: '权限ID', - }, - created_at: { - type: DATE, - allowNull: false, - comment: '创建时间', - }, - }, { - tableName: 'wms_role_permission', - freezeTableName: true, - underscored: true, - timestamps: true, - paranoid: false, // 明确禁用软删除 - createdAt: 'created_at', - updatedAt: false, - comment: '角色权限关联表', - indexes: [ - { - name: 'uk_role_permission', - fields: [ 'role_id', 'permission_id' ], - unique: true, - }, - { - name: 'idx_role_id', - fields: [ 'role_id' ], - }, - { - name: 'idx_permission_id', - fields: [ 'permission_id' ], - }, - ], - }); - - // 关联关系 - RolePermission.associate = function(models) { - const { Role, Permission } = app.model; - // 关联角色 - RolePermission.belongsTo(Role, { - foreignKey: 'role_id', - as: 'role', - }); - - // 关联权限 - RolePermission.belongsTo(Permission, { - foreignKey: 'permission_id', - as: 'permission', - }); - }; - - // 实例方法:检查关联是否有效 - RolePermission.prototype.isValid = function() { - // 这里可以添加更多的有效性检查 - return this.role_id && this.permission_id; - }; - - // 类方法:批量创建角色权限关联 - RolePermission.bulkAssign = async function(roleId, permissionIds) { - const { ctx } = this; - - if (!permissionIds || permissionIds.length === 0) { - return []; - } - - const rolePermissions = permissionIds.map(permissionId => ({ - role_id: roleId, - permission_id: permissionId, - })); - - try { - return await ctx.model.RolePermission.bulkCreate(rolePermissions, { - ignoreDuplicates: true, // 忽略重复项 - }); - } catch (error) { - // 处理批量创建中的错误 - console.error('批量创建角色权限关联失败:', error); - throw error; - } - }; - - // 类方法:删除角色的所有权限 - RolePermission.clearRolePermissions = async function(roleId) { - const { ctx } = this; - - return await ctx.model.RolePermission.destroy({ - where: { role_id: roleId }, - }); - }; - - // 类方法:获取角色的权限列表 - RolePermission.getRolePermissions = async function(roleId, includePermissionDetails = false) { - const { ctx } = this; - - const options = { - where: { role_id: roleId }, - }; - - if (includePermissionDetails) { - options.include = [{ - model: ctx.model.Permission, - as: 'permission', - where: { status: 1 }, - required: false, - }]; - } - - return await ctx.model.RolePermission.findAll(options); - }; - - // 类方法:检查角色是否拥有某个权限 - RolePermission.hasPermission = async function(roleId, permissionId) { - const { ctx } = this; - - const rolePermission = await ctx.model.RolePermission.findOne({ - where: { - role_id: roleId, - permission_id: permissionId, - }, - }); - - return !!rolePermission; - }; - - return RolePermission; -}; diff --git a/app/model/shop.js b/app/model/shop.js new file mode 100644 index 0000000..533cda6 --- /dev/null +++ b/app/model/shop.js @@ -0,0 +1,156 @@ +'use strict'; + +/** + * 店铺模型定义。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 店铺模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE, TINYINT, JSON } = app.Sequelize; + + const Shop = app.model.define('shops', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '平台编码', + }, + shop_name: { + type: STRING(100), + allowNull: false, + comment: '店铺名称', + }, + custom_name: { + type: STRING(100), + allowNull: true, + comment: '店铺自定义名称', + }, + status: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + validate: { + isIn: { + args: [[ 0, 1 ]], + msg: '状态值不合法,0=未授权,1=已授权', + }, + }, + comment: '授权状态:0=未授权,1=已授权', + }, + auth_expire_at: { + type: DATE, + allowNull: true, + comment: '授权到期时间', + }, + auth_random_code: { + type: STRING(128), + allowNull: true, + comment: '授权随机码', + }, + owner_id: { + type: STRING(64), + allowNull: true, + comment: '平台店铺/主体ID', + }, + access_token: { + type: STRING(255), + allowNull: true, + comment: '访问令牌', + }, + refresh_token: { + type: STRING(255), + allowNull: true, + comment: '刷新令牌', + }, + token_expires_at: { + type: DATE, + allowNull: true, + comment: '访问令牌过期时间', + }, + refresh_token_expires_at: { + type: DATE, + allowNull: true, + comment: '刷新令牌过期时间', + }, + scope: { + type: JSON, + allowNull: true, + comment: '授权范围', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_shops', + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: false, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '店铺表', + indexes: [ + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'idx_platform_code', + fields: [ 'platform_code' ], + }, + { + name: 'idx_status', + fields: [ 'status' ], + }, + { + name: 'uk_warehouse_platform_shop_name', + unique: false, + fields: [ 'warehouse_id', 'platform_code', 'shop_name' ], + }, + { + name: 'uk_auth_random_code', + unique: true, + fields: [ 'auth_random_code' ], + }, + ], + }); + + /** + * 定义店铺与打印平台的关联关系。 + * + * 说明: + * - `wms_shops.platform_code` 对应 `wms_print_platform.platform_code` + */ + Shop.associate = function() { + const { PrintPlatform } = app.model; + + if (PrintPlatform && typeof Shop.belongsTo === 'function') { + Shop.belongsTo(PrintPlatform, { + foreignKey: 'platform_code', + targetKey: 'platform_code', + as: 'printPlatform', + constraints: false, + }); + } + }; + + return Shop; +}; diff --git a/app/model/stock_barcode.js b/app/model/stock_barcode.js index 21e7b86..f34f960 100644 --- a/app/model/stock_barcode.js +++ b/app/model/stock_barcode.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { STRING, BIGINT, DATE, TEXT } = app.Sequelize; + const { STRING, BIGINT, DATE } = app.Sequelize; const StockBarcode = app.model.define('stock_barcodes', { id: { @@ -68,6 +68,49 @@ module.exports = app => { ], }); + /** + * 商品详情缓存 key 前缀。 + * 与 app/service/systems/stock_warehouse.js 中保持一致。 + */ + const STOCK_DETAIL_CACHE_PREFIX = 'cache:stock_detail'; + + /** + * 构建商品详情缓存 key。 + * @param {number} warehouseId 仓库ID + * @param {number} stockId 仓库商品ID + * @return {string} 缓存 key + */ + function buildStockDetailCacheKey(warehouseId, stockId) { + return `${STOCK_DETAIL_CACHE_PREFIX}:${warehouseId}:${stockId}`; + } + + /** + * 条码变更后自动清除关联的商品详情缓存。 + * 直接在 hook 中使用 async/await,缓存删除很快不会阻塞主流程。 + * @param {Object} instance Sequelize 模型实例 + * @return {Promise} + */ + async function invalidateStockDetailCacheForBarcode(instance) { + try { + const warehouseId = instance.get('warehouse_id'); + const stockId = instance.get('stock_id'); + if (warehouseId && stockId) { + const cacheKey = buildStockDetailCacheKey(warehouseId, stockId); + if (typeof app.delCacheAsync === 'function') { + await app.delCacheAsync(cacheKey); + app.logger.info(`[StockBarcode] 已清除商品详情缓存: ${cacheKey}`); + } + } + } catch (err) { + app.logger.error(`[StockBarcode] 清除商品详情缓存失败: ${err.message}`); + } + } + + // 注册 hooks:条码新增/更新/删除时自动清除关联商品详情缓存 + StockBarcode.addHook('afterCreate', 'invalidateStockDetailCache', invalidateStockDetailCacheForBarcode); + StockBarcode.addHook('afterUpdate', 'invalidateStockDetailCache', invalidateStockDetailCacheForBarcode); + StockBarcode.addHook('afterDestroy', 'invalidateStockDetailCache', invalidateStockDetailCacheForBarcode); + // 定义关联关系 StockBarcode.associate = function() { const { StockWarehouse } = app.model; diff --git a/app/model/stock_check.js b/app/model/stock_check.js new file mode 100644 index 0000000..83afcb3 --- /dev/null +++ b/app/model/stock_check.js @@ -0,0 +1,141 @@ +'use strict'; + +/** + * 库存盘点主表模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, TINYINT, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const StockCheck = app.model.define('wms_stock_check', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + check_no: { + type: STRING(50), + allowNull: false, + comment: '盘点单号,唯一,生成规则:PD+YYYYMMDD+6位序号', + }, + title: { + type: STRING(200), + allowNull: true, + comment: '盘点名称/主题,非必填', + }, + type: { + type: STRING(20), + allowNull: false, + defaultValue: 'location', + comment: '盘点范围类型:location=按库位(未传库位时自动全盘),store=按货主,goods=按商品', + }, + mode: { + type: STRING(20), + allowNull: false, + defaultValue: 'open', + comment: '盘点方式:open=明盘(可见账面数量),blind=盲盘(不可见账面数量)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,按货主盘点时必填(type=store)', + }, + is_static: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否静态盘点(1=静态盘点(静态定式创建或创建时开启),0=普通盘点)', + }, + scope_snapshot: { + type: JSON_TYPE, + allowNull: true, + comment: '盘点范围条件快照(JSON),如商品ID列表/库位ID列表,供盘点对比与追溯', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '盘点状态:pending=待盘点,in_progress=盘点中,checked=已盘待确认,confirmed=已确认,completed=已完成,cancelled=已取消', + }, + detail_status: { + type: STRING(30), + allowNull: false, + defaultValue: 'none_checked', + comment: '明细盘点进度:none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘', + }, + start_time: { + type: DATE, + allowNull: true, + comment: '盘点开始时间(第一个盘点明细写入的时间)', + }, + end_time: { + type: DATE, + allowNull: true, + comment: '盘点结束时间(完成盘点的时间)', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人账户ID', + }, + creator_name: { + type: STRING(50), + allowNull: true, + comment: '创建人名称快照', + }, + total_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '明细行数(盘点任务总行数)', + }, + checked_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '已盘行数', + }, + diff_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '差异行数(账面与实盘不一致的行数)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + }, { + tableName: 'wms_stock_check', + comment: '库存盘点主表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'uk_check_no', unique: true, fields: [ 'check_no' ] }, + { name: 'idx_warehouse_status', fields: [ 'warehouse_id', 'status' ] }, + { name: 'idx_store_id', fields: [ 'store_id' ] }, + { name: 'idx_creator_id', fields: [ 'creator_id' ] }, + ], + }); + + StockCheck.associate = function() { + const { StockCheckDetail } = app.model; + // 一个盘点单对应多条盘点明细 + StockCheck.hasMany(StockCheckDetail, { + foreignKey: 'check_id', + as: 'details', + }); + }; + + return StockCheck; +}; diff --git a/app/model/stock_check_detail.js b/app/model/stock_check_detail.js new file mode 100644 index 0000000..58be00d --- /dev/null +++ b/app/model/stock_check_detail.js @@ -0,0 +1,119 @@ +'use strict'; + +/** + * 库存盘点明细表模型(盘点范围行:商品或库位)。 + * 商品行(scope_type=goods):stock_id + 商品快照 + 账面数量快照; + * 库位行(scope_type=location):location_id/location_code + stock_id/item_code 为空。 + * 库位/数量等盘点作业信息存放在 wms_stock_check_record。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER } = app.Sequelize; + + const StockCheckDetail = app.model.define('wms_stock_check_detail', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + check_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点主表 wms_stock_check.id', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + scope_type: { + type: STRING(20), + allowNull: false, + defaultValue: 'goods', + comment: '盘点范围类型:goods=商品,location=库位', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库存商品ID,关联 wms_stock_warehouse.id;库位盘点行为空', + }, + location_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID,关联 wms_location_space.id;库位盘点行为空', + }, + location_code: { + type: STRING(50), + allowNull: true, + comment: '库位编码(space_code);库位盘点行为空', + }, + item_code: { + type: STRING(50), + allowNull: true, + comment: '商品编码快照;库位盘点行为空', + }, + item_name: { + type: STRING(255), + allowNull: true, + comment: '商品名称快照', + }, + spec: { + type: STRING(100), + allowNull: true, + comment: '规格快照(sku_property)', + }, + batch_no: { + type: STRING(100), + allowNull: true, + comment: '批次号,批次管理商品时记录', + }, + system_quantity: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '账面数量快照(生成盘点明细时的系统库存,用于差异对比;库位行固定为 0,账面按 wms_storage 现算)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + }, { + tableName: 'wms_stock_check_detail', + comment: '库存盘点明细表(盘点范围行:商品或库位)', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'idx_check_id', fields: [ 'check_id' ] }, + { name: 'idx_warehouse_stock', fields: [ 'warehouse_id', 'stock_id' ] }, + { name: 'idx_stock_id', fields: [ 'stock_id' ] }, + { name: 'uk_check_stock_location', unique: true, fields: [ 'check_id', 'stock_id', 'location_id' ] }, + { name: 'idx_check_location', fields: [ 'check_id', 'location_code' ] }, + ], + }); + + StockCheckDetail.associate = function() { + const { StockCheck, StockWarehouse, StockCheckRecord } = app.model; + // 关联盘点主表 + StockCheckDetail.belongsTo(StockCheck, { + foreignKey: 'check_id', + as: 'check', + }); + // 关联库存商品 + StockCheckDetail.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stockWarehouse', + }); + // 一条明细对应多条盘点作业记录 + StockCheckDetail.hasMany(StockCheckRecord, { + foreignKey: 'detail_id', + as: 'records', + }); + }; + + return StockCheckDetail; +}; diff --git a/app/model/stock_check_record.js b/app/model/stock_check_record.js new file mode 100644 index 0000000..f556d71 --- /dev/null +++ b/app/model/stock_check_record.js @@ -0,0 +1,131 @@ +'use strict'; + +/** + * 库存盘点作业记录表模型(存储盘点的库位、数量信息)。 + * 一个盘点明细(商品行或库位行)可在多个库位/商品维度多次上报,每次上报一条记录; + * 覆盖式语义为「同明细 + 同商品 + 同库位」(uk_detail_stock_location 唯一索引); + * 支持未知商品(仿收货明细口径):stock_id 为空(NULL)+ barcode + item_name, + * 唯一索引中 NULL 不参与唯一约束,未知商品查重由应用层保证。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE, BOOLEAN } = app.Sequelize; + + const StockCheckRecord = app.model.define('wms_stock_check_record', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + check_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点主表 wms_stock_check.id(冗余,便于按任务查记录)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + detail_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点明细 wms_stock_check_detail.id', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id;NULL=未知商品', + }, + barcode: { + type: STRING(100), + allowNull: true, + comment: '扫描到的条码/编码(未知商品上报使用;已知商品可为空)', + }, + item_name: { + type: STRING(255), + allowNull: true, + comment: '未知商品名称快照(缺省为条码);已知商品为空', + }, + is_empty: { + type: BOOLEAN, + allowNull: false, + defaultValue: false, + comment: '是否空库位标记(true=确认库位为空,stock_id/barcode/item_name 均为空、quantity=0)', + }, + location_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID,关联 wms_location_space.id;库位编码匹配时回填,未匹配为空', + }, + location_code: { + type: STRING(50), + allowNull: false, + defaultValue: '', + comment: '库位编码(盘点上报的库位,空串表示无库位分组)', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实盘数量(不小于0的整数)', + }, + checker_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '盘点人账户ID', + }, + checker_name: { + type: STRING(50), + allowNull: true, + comment: '盘点人名称快照', + }, + checked_at: { + type: DATE, + allowNull: true, + comment: '上报时间', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + }, { + tableName: 'wms_stock_check_record', + comment: '库存盘点作业记录表(库位+数量)', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'idx_check_id', fields: [ 'check_id' ] }, + { name: 'idx_detail_id', fields: [ 'detail_id' ] }, + { name: 'idx_stock_id', fields: [ 'stock_id' ] }, + { name: 'idx_warehouse_location', fields: [ 'warehouse_id', 'location_code' ] }, + { name: 'uk_detail_stock_location', unique: true, fields: [ 'detail_id', 'stock_id', 'location_code' ] }, + ], + }); + + StockCheckRecord.associate = function() { + const { StockCheck, StockCheckDetail, StockWarehouse } = app.model; + // 关联盘点主表 + StockCheckRecord.belongsTo(StockCheck, { + foreignKey: 'check_id', + as: 'check', + }); + // 关联盘点明细 + StockCheckRecord.belongsTo(StockCheckDetail, { + foreignKey: 'detail_id', + as: 'detail', + }); + // 关联库存商品 + StockCheckRecord.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stockWarehouse', + }); + }; + + return StockCheckRecord; +}; diff --git a/app/model/stock_static_check_task.js b/app/model/stock_static_check_task.js new file mode 100644 index 0000000..440509b --- /dev/null +++ b/app/model/stock_static_check_task.js @@ -0,0 +1,57 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, DATE } = app.Sequelize; + + const StockStaticCheckTask = app.model.define('stock_static_check_task', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品ID,关联 wms_stock_warehouse.id', + }, + task_time: { + type: DATE, + allowNull: false, + comment: '创建盘点任务时间(有记录即表示已为该静态商品创建过盘点任务)', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + defaultValue: null, + comment: '软删除时间', + }, + }, { + tableName: 'wms_stock_static_check_task', + freezeTableName: true, + timestamps: false, + paranoid: true, + comment: '静态商品盘点任务关联表(记录是否已为静态商品创建盘点任务,避免重复创建)', + indexes: [ + { + name: 'idx_stock_task_time', + fields: [ 'stock_id', 'task_time' ], + }, + { + name: 'idx_task_time', + fields: [ 'task_time' ], + }, + ], + }); + + return StockStaticCheckTask; +}; diff --git a/app/model/stock_static_notice.js b/app/model/stock_static_notice.js new file mode 100644 index 0000000..1480ce0 --- /dev/null +++ b/app/model/stock_static_notice.js @@ -0,0 +1,57 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, DATE } = app.Sequelize; + + const StockStaticNotice = app.model.define('stock_static_notice', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品ID,关联 wms_stock_warehouse.id', + }, + notice_time: { + type: DATE, + allowNull: false, + comment: '通知时间', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + defaultValue: null, + comment: '软删除时间', + }, + }, { + tableName: 'wms_stock_static_notice', + freezeTableName: true, + timestamps: false, + paranoid: true, + comment: '静态商品通知关联表(记录静态商品已通知时间,避免重复通知)', + indexes: [ + { + name: 'idx_stock_notice_time', + fields: [ 'stock_id', 'notice_time' ], + }, + { + name: 'idx_notice_time', + fields: [ 'notice_time' ], + }, + ], + }); + + return StockStaticNotice; +}; diff --git a/app/model/stock_store.js b/app/model/stock_store.js index 9cbc91e..3dcce32 100644 --- a/app/model/stock_store.js +++ b/app/model/stock_store.js @@ -130,22 +130,16 @@ module.exports = app => { comment: '体积', }, gross_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, - defaultValue: 0.00, - validate: { - min: 0, - }, - comment: '毛重', + defaultValue: 0, + comment: '毛重(g)', }, net_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, - defaultValue: 0.00, - validate: { - min: 0, - }, - comment: '净重', + defaultValue: 0, + comment: '净重(g)', }, category_id: { type: INTEGER(11), @@ -362,45 +356,6 @@ module.exports = app => { }); }; - // 类方法 - 根据商品编码查找 - StockStore.findByItemCode = async function(itemCode, options = {}) { - const where = { item_code: itemCode, is_valid: 'Y' }; - - if (options.warehouse_id) { - where.warehouse_id = options.warehouse_id; - } - - if (options.store_id) { - where.store_id = options.store_id; - } - - return await this.findOne({ - where, - include: options.include || [], - }); - }; - - // 类方法 - 获取商家的商品列表 - StockStore.findByStore = async function(storeId, options = {}) { - const where = { store_id: storeId, is_valid: 'Y' }; - - if (options.warehouse_id) { - where.warehouse_id = options.warehouse_id; - } - - if (options.owner_code) { - where.owner_code = options.owner_code; - } - - return await this.findAll({ - where, - include: options.include || [], - order: options.order || [[ 'create_time', 'DESC' ]], - limit: options.limit, - offset: options.offset, - }); - }; - // 实例方法 - 检查商品是否有效 StockStore.prototype.isValid = function() { return this.is_valid === 'Y' && !this.delete_at; diff --git a/app/model/stock_transaction.js b/app/model/stock_transaction.js new file mode 100644 index 0000000..9fc9d84 --- /dev/null +++ b/app/model/stock_transaction.js @@ -0,0 +1,155 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, DATE, TEXT } = app.Sequelize; + + const StockTransaction = app.model.define('stock_transaction', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + transaction_type: { + type: ENUM('INBOUND', 'OUTBOUND', 'LOCK', 'UNLOCK'), + allowNull: false, + comment: '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定 UNLOCK取消锁定', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品库存ID,关联 wms_stock_warehouse.id', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + comment: '变动数量(正数)', + }, + before_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }, + after_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }, + before_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }, + after_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }, + batch_no: { + type: STRING(100), + allowNull: true, + comment: '批次号', + }, + order_type: { + type: STRING(50), + allowNull: true, + comment: '关联单据类型(如 SCRK=收货入库, MATCH=匹配入库, CGTH=采购退货等)', + }, + order_no: { + type: TEXT, + allowNull: true, + comment: '关联单据号', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联单据ID', + }, + receiving_id: { + type: INTEGER, + allowNull: true, + comment: '关联收货单ID', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID', + }, + operator_id: { + type: STRING(100), + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: STRING(100), + allowNull: true, + comment: '操作人名称', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_stock_transaction', + freezeTableName: true, + timestamps: false, + comment: '出入库流水记录表', + indexes: [ + { + name: 'idx_stock_id', + fields: [ 'stock_id' ], + }, + { + name: 'idx_warehouse_time', + fields: [ 'warehouse_id', 'created_at' ], + }, + { + name: 'idx_order', + fields: [ 'order_type', 'order_id' ], + }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + { + name: 'idx_store_transaction_type', + fields: [ 'store_id', 'transaction_type' ], + }, + ], + }); + + StockTransaction.associate = function() { + const { StockWarehouse } = app.model; + StockTransaction.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stockItem', + }); + }; + + return StockTransaction; +}; diff --git a/app/model/stock_unit.js b/app/model/stock_unit.js index 44b0d1c..849eb9b 100644 --- a/app/model/stock_unit.js +++ b/app/model/stock_unit.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, DATE } = app.Sequelize; + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; const StockUnit = app.model.define('wms_stock_unit', { id: { @@ -12,7 +12,7 @@ module.exports = app => { comment: '主键ID', }, warehouse_id: { - type: INTEGER, + type: BIGINT(20).UNSIGNED, allowNull: true, defaultValue: null, comment: '仓库ID,NULL表示系统默认', diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index 048b61f..a43a97a 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { STRING, BIGINT, DECIMAL, TEXT, DATE, CHAR, INTEGER, ENUM, TINYINT } = app.Sequelize; + const { STRING, BIGINT, DECIMAL, TEXT, DATE, CHAR, INTEGER, ENUM, TINYINT, JSON } = app.Sequelize; const StockWarehouse = app.model.define('stock_warehouse', { id: { @@ -43,6 +43,20 @@ module.exports = app => { type: TEXT, comment: '打包要求', }, + pick_requirements: { + type: TEXT, + comment: '拣货要求', + }, + recheck_requirements: { + type: TEXT, + comment: '眼球复核要求', + }, + merge_requirements: { + type: CHAR(1), + allowNull: false, + defaultValue: 'Y', + comment: '要求是否合并:Y=合并(拣货/复核要求统一输出打包要求),N=不合并', + }, brand_name: { type: STRING(100), @@ -72,14 +86,14 @@ module.exports = app => { comment: '体积', }, gross_weight: { - type: DECIMAL(10, 2), - defaultValue: 0.00, - comment: '毛重', + type: INTEGER(11), + defaultValue: 0, + comment: '毛重(g)', }, net_weight: { - type: DECIMAL(10, 2), - defaultValue: 0.00, - comment: '净重', + type: INTEGER(11), + defaultValue: 0, + comment: '净重(g)', }, item_type: { type: STRING(10), @@ -101,6 +115,12 @@ module.exports = app => { defaultValue: 'N', comment: '是否序列号管理', }, + sn_code_rules: { + type: JSON, + allowNull: true, + defaultValue: null, + comment: 'SN码规则(JSON数组):match_type=prefix|suffix、match_value=前缀/后缀、keep_mode=full|strip', + }, is_shelf_life_mgmt: { type: CHAR(1), defaultValue: 'N', @@ -111,6 +131,12 @@ module.exports = app => { defaultValue: 'N', comment: '是否批次管理', }, + need_recheck: { + type: CHAR(1), + allowNull: false, + defaultValue: 'Y', + comment: '是否需要复核:Y=需要复核,N=不需要复核', + }, create_at: { type: DATE, allowNull: false, @@ -146,15 +172,20 @@ module.exports = app => { comment: '删除时间', }, quantity: { - type: INTEGER(11).UNSIGNED, + type: INTEGER(11), defaultValue: 0, comment: '库存数量', }, locked_quantity: { - type: INTEGER(11).UNSIGNED, + type: INTEGER(11), defaultValue: 0, comment: '锁定数量', }, + warning_quantity: { + type: INTEGER(11), + defaultValue: 0, + comment: '库存预警数量', + }, prohibited_id: { type: INTEGER.UNSIGNED, comment: '违禁品类型id', @@ -170,10 +201,12 @@ module.exports = app => { box_gross_weight: { type: INTEGER(11), defaultValue: 0, + comment: '箱毛重(g)', }, box_net_weight: { type: INTEGER(11), defaultValue: 0, + comment: '箱净重(g)', }, box_height: { type: DECIMAL(10, 2), @@ -191,6 +224,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, @@ -222,13 +275,55 @@ module.exports = app => { ], }); - StockWarehouse.associate = function(models) { - const { StoreWarehouse, StockBarcode, ProhibitedType, StockImage, StockStore, Storage } = app.model; - // 授权关系属于商家 - 修正:需要确认StoreWarehouse模型是否有store_id字段 + /** + * 商品详情缓存 key 前缀。 + * 与 app/service/systems/stock_warehouse.js 中保持一致。 + */ + const STOCK_DETAIL_CACHE_PREFIX = 'cache:stock_detail'; + + /** + * 构建商品详情缓存 key。 + * @param {number} warehouseId 仓库ID + * @param {number} stockId 仓库商品ID + * @return {string} 缓存 key + */ + function buildStockDetailCacheKey(warehouseId, stockId) { + return `${STOCK_DETAIL_CACHE_PREFIX}:${warehouseId}:${stockId}`; + } + + /** + * 资料变更后自动清除商品详情缓存。 + * 直接在 afterUpdate hook 中使用 async/await,缓存删除很快不会阻塞主流程。 + * @param {Object} instance Sequelize 模型实例 + * @return {Promise} + */ + async function invalidateStockDetailCacheAfterUpdate(instance) { + try { + const warehouseId = instance.get('warehouse_id'); + const stockId = instance.get('id'); + if (warehouseId && stockId) { + const cacheKey = buildStockDetailCacheKey(warehouseId, stockId); + if (typeof app.delCacheAsync === 'function') { + await app.delCacheAsync(cacheKey); + app.logger.info(`[StockWarehouse.afterUpdate] 已清除商品详情缓存: ${cacheKey}`); + } + } + } catch (err) { + app.logger.error(`[StockWarehouse.afterUpdate] 清除商品详情缓存失败: ${err.message}`); + } + } + + // 注册 afterUpdate hook:商品资料更新时自动清除详情缓存 + StockWarehouse.addHook('afterUpdate', 'invalidateStockDetailCache', invalidateStockDetailCacheAfterUpdate); + + StockWarehouse.associate = function() { + const { StoreWarehouse, StockBarcode, ProhibitedType, StockStore, Storage } = app.model; + // store_stock 关联依赖 store_id + warehouse_id 复合语义,单列关联仅作为 include 入口。 StockWarehouse.belongsTo(StoreWarehouse, { foreignKey: 'store_id', // 当前表的外键字段 - targetKey: 'store_id', // 关联表的主键字段 + targetKey: 'store_id', // 关联表业务键(非主键) as: 'store_stock', + constraints: false, }); StockWarehouse.hasMany(StockBarcode, { foreignKey: 'stock_id', // StockBarcodes表中的外键字段 @@ -249,6 +344,12 @@ module.exports = app => { as: 'storage', }); + const { StockTransaction } = app.model; + StockWarehouse.hasMany(StockTransaction, { + foreignKey: 'stock_id', + as: 'transactions', + }); + }; return StockWarehouse; diff --git a/app/model/storage.js b/app/model/storage.js index 98bd61a..8dd7a9d 100644 --- a/app/model/storage.js +++ b/app/model/storage.js @@ -72,6 +72,12 @@ module.exports = app => { defaultValue: 0, comment: '锁定数量', }, + intercept_locked_quantity: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '拦截锁定数量', + }, available_quantity: { type: INTEGER(12), allowNull: false, @@ -101,6 +107,24 @@ module.exports = app => { notEmpty: true, }, }, + receiving_id: { + type: INTEGER, + allowNull: true, + comment: '收货单ID', + references: { + model: 'wms_receiving', + key: 'id', + }, + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库单ID', + references: { + model: 'wms_entry_order', + key: 'id', + }, + }, supplier_id: { type: BIGINT(20).UNSIGNED, allowNull: true, @@ -138,6 +162,8 @@ module.exports = app => { tableName: 'wms_storage', comment: '库存表', timestamps: false, + paranoid: true, + deletedAt: 'delete_at', indexes: [ { name: 'uk_location_sku_batch_type', @@ -164,6 +190,14 @@ module.exports = app => { name: 'idx_inbound_order', fields: [ 'inbound_order_no' ], }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, { name: 'idx_store_id', fields: [ 'store_id' ], @@ -215,11 +249,29 @@ module.exports = app => { as: 'stock', }); + // 关联收货单 + Storage.belongsTo(app.model.Receiving, { + foreignKey: 'receiving_id', + as: 'receiving', + }); + + // 关联入库单 + Storage.belongsTo(app.model.EntryOrder, { + foreignKey: 'entry_order_id', + as: 'entryOrder', + }); + }; - // 实例方法 + /** + * 计算当前记录的可用数量(统一口径)。 + * + * 可用数量口径:可用数量 = 库存数量 - 锁定数量 - 拦截锁定数量。 + * + * @return {number} 可用数量。 + */ Storage.prototype.getAvailableQuantity = function() { - return this.quantity - this.locked_quantity; + return this.quantity - this.locked_quantity - Number(this.intercept_locked_quantity || 0); }; Storage.prototype.isAvailable = function() { @@ -247,222 +299,5 @@ module.exports = app => { return new Date(this.expiry_date) < new Date(); }; - // 静态方法 - Storage.findByStockAndBatch = async function(app, stockId, batchNo, inventoryType = 'ZP') { - return await app.model.Storage.findOne({ - where: { - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - include: [ - { - model: app.model.LocationSpace, - as: 'space', - attributes: [ 'space_code', 'custom_name' ], - }, - { - model: app.model.Store, - as: 'warehouse', - attributes: [ 'store_name' ], - }, - ], - }); - }; - - Storage.findBySpace = async function(app, spaceId) { - return await app.model.Storage.findAll({ - where: { - space_id: spaceId, - is_enabled: 1, - delete_at: null, - }, - include: [ - { - model: app.model.StockWarehouse, - as: 'stock', - attributes: [ 'product_code', 'product_name' ], - }, - ], - order: [[ 'inbound_time', 'ASC' ]], - }); - }; - - Storage.findAvailableByWarehouse = async function(app, warehouseId, stockId = null) { - const where = { - warehouse_id: warehouseId, - is_enabled: 1, - delete_at: null, - available_quantity: { [app.Sequelize.Op.gt]: 0 }, - }; - - if (stockId) { - where.stock_id = stockId; - } - - return await app.model.Storage.findAll({ - where, - include: [ - { - model: app.model.LocationSpace, - as: 'space', - attributes: [ 'space_code', 'custom_name' ], - }, - { - model: app.model.StockWarehouse, - as: 'stock', - attributes: [ 'product_code', 'product_name' ], - }, - ], - order: [ - [ 'expiry_date', 'ASC' ], - [ 'inbound_time', 'ASC' ], - ], - }); - }; - - Storage.findExpiringSoon = async function(app, days = 30) { - const expiryDate = new Date(); - expiryDate.setDate(expiryDate.getDate() + days); - - return await app.model.Storage.findAll({ - where: { - expiry_date: { - [app.Sequelize.Op.between]: [ new Date(), expiryDate ], - }, - is_enabled: 1, - delete_at: null, - quantity: { [app.Sequelize.Op.gt]: 0 }, - }, - include: [ - { - model: app.model.Store, - as: 'warehouse', - attributes: [ 'store_name' ], - }, - { - model: app.model.StockWarehouse, - as: 'stock', - attributes: [ 'product_code', 'product_name' ], - }, - ], - order: [[ 'expiry_date', 'ASC' ]], - }); - }; - - Storage.updateQuantity = async function(app, id, quantityChange, lockedChange = 0) { - const storage = await app.model.Storage.findByPk(id); - - if (!storage) { - throw new Error('库存记录不存在'); - } - - const newQuantity = storage.quantity + quantityChange; - const newLocked = storage.locked_quantity + lockedChange; - - if (newQuantity < 0) { - throw new Error('库存数量不能为负数'); - } - - if (newLocked < 0 || newLocked > newQuantity) { - throw new Error('锁定数量无效'); - } - - const updateData = { - quantity: newQuantity, - locked_quantity: newLocked, - available_quantity: newQuantity - newLocked, - updated_at: new Date(), - }; - - await storage.update(updateData); - return storage; - }; - - Storage.lockQuantity = async function(app, id, quantity) { - return await Storage.updateQuantity(app, id, 0, quantity); - }; - - Storage.unlockQuantity = async function(app, id, quantity) { - return await Storage.updateQuantity(app, id, 0, -quantity); - }; - - Storage.allocateQuantity = async function(app, id, quantity) { - const storage = await app.model.Storage.findByPk(id); - - if (!storage) { - throw new Error('库存记录不存在'); - } - - if (storage.available_quantity < quantity) { - throw new Error('可用数量不足'); - } - - return await Storage.updateQuantity(app, id, 0, quantity); - }; - - Storage.getStockSummary = async function(app, warehouseId) { - return await app.model.Storage.findAll({ - attributes: [ - 'stock_id', - 'inventory_type', - [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ], - ], - where: { - warehouse_id: warehouseId, - is_enabled: 1, - delete_at: null, - }, - group: [ 'stock_id', 'inventory_type' ], - raw: true, - }); - }; - - Storage.getSpaceUsage = async function(app, spaceId) { - const result = await app.model.Storage.findAll({ - attributes: [ - 'inventory_type', - [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'record_count' ], - [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], - ], - where: { - space_id: spaceId, - is_enabled: 1, - delete_at: null, - }, - group: [ 'inventory_type' ], - raw: true, - }); - - const usage = { - normal: 0, - defective: 0, - damaged: 0, - frozen: 0, - total: 0, - }; - - result.forEach(item => { - let type; - switch (item.inventory_type) { - case 'ZP': type = 'normal'; break; - case 'CC': type = 'defective'; break; - case 'JS': - case 'XS': type = 'damaged'; break; - case 'DJ': type = 'frozen'; break; - default: return; - } - - usage[type] = parseInt(item.total_quantity) || 0; - usage.total += usage[type]; - }); - - return usage; - }; - return Storage; }; diff --git a/app/model/storage_transaction.js b/app/model/storage_transaction.js new file mode 100644 index 0000000..4db3d92 --- /dev/null +++ b/app/model/storage_transaction.js @@ -0,0 +1,164 @@ +'use strict'; + +/** + * 库位维度出入库流水模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, DATE, TEXT } = app.Sequelize; + + const StorageTransaction = app.model.define('storage_transaction', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + transaction_type: { + type: ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN', 'LOCK', 'UNLOCK'), + allowNull: false, + comment: '出入库类型', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品库存ID,关联 wms_stock_warehouse.id', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位库存ID,关联 wms_storage.id', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + comment: '变动数量(正数)', + }, + before_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }, + after_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }, + before_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }, + after_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }, + before_intercept_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前拦截锁定数量', + }, + after_intercept_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后拦截锁定数量', + }, + batch_no: { + type: STRING(100), + allowNull: true, + comment: '批次号', + }, + inventory_type: { + type: ENUM('ZP', 'CC', 'JS', 'XS', 'ZT', 'DJ', 'FP'), + defaultValue: 'ZP', + comment: '库存类型', + }, + order_type: { + type: STRING(50), + allowNull: true, + comment: '关联单据类型', + }, + order_no: { + type: TEXT, + allowNull: true, + comment: '关联单据号', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联单据ID', + }, + source_order_codes: { + type: TEXT, + allowNull: true, + comment: '来源订单号集合', + }, + operator_id: { + type: STRING(100), + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: STRING(100), + allowNull: true, + comment: '操作人名称', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_storage_transaction', + freezeTableName: true, + timestamps: false, + comment: '库位维度出入库流水记录表', + indexes: [ + { + name: 'idx_storage_id', + fields: [ 'storage_id' ], + }, + { + name: 'idx_stock_id', + fields: [ 'stock_id' ], + }, + { + name: 'idx_warehouse_time', + fields: [ 'warehouse_id', 'created_at' ], + }, + { + name: 'idx_order', + fields: [ 'order_type', 'order_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + return StorageTransaction; +}; diff --git a/app/model/store.js b/app/model/store.js index 89bafc9..1c5e8d0 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -1,7 +1,758 @@ 'use strict'; module.exports = app => { - const { BIGINT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize; + const { BIGINT, STRING, DATE, TINYINT, JSON: JSON_TYPE } = app.Sequelize; + const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; + const DEFAULT_MAX_WAVE_QUANTITY = 500; + const INVENTORY_WARNING_RULE_COLOR_MAP = Object.freeze({ + 1: '#ff4d4f', + 2: '#ff7a45', + 3: '#faad14', + 4: '#fadb14', + 5: '#95de64', + 6: '#52c41a', + }); + const DEFAULT_INVENTORY_WARNING_RULES = Object.freeze([ + Object.freeze({ name: '01级', key: INVENTORY_WARNING_RULE_COLOR_MAP[1], expire_days: 0, tip_text: '立即报废' }), + Object.freeze({ name: '02级', key: INVENTORY_WARNING_RULE_COLOR_MAP[2], expire_days: 30, tip_text: '优先处理' }), + Object.freeze({ name: '03级', key: INVENTORY_WARNING_RULE_COLOR_MAP[3], expire_days: 90, tip_text: '尽快处理' }), + Object.freeze({ name: '04级', key: INVENTORY_WARNING_RULE_COLOR_MAP[4], expire_days: 180, tip_text: '建议处理' }), + Object.freeze({ name: '05级', key: INVENTORY_WARNING_RULE_COLOR_MAP[5], expire_days: 365, tip_text: '库存关注' }), + Object.freeze({ name: '06级', key: INVENTORY_WARNING_RULE_COLOR_MAP[6], expire_days: 999999, tip_text: '常规监控' }), + ]); + + /** + * 获取库存预警默认规则(深拷贝)。 + * + * @return {Array} 默认库存预警规则。 + */ + const getDefaultInventoryWarningRules = () => DEFAULT_INVENTORY_WARNING_RULES.map(rule => ({ ...rule })); + + const DEFAULT_SAME_DAY_OUTBOUND_DEADLINE_TIME = '06:00'; + const DEFAULT_SAME_DAY_OUTBOUND_RELEASE_TIME = '22:00'; + + // 自动出库开关:独立字段,默认关闭 + const DEFAULT_AUTO_OUTBOUND_ENABLED = false; + // 自动出库规则:数组,默认空数组(空数组 = 不出库任何订单);每项规则独立判断,任一命中即出库 + const DEFAULT_AUTO_OUTBOUND_RULES = Object.freeze([]); + + /** + * 获取自动出库规则默认值(新数组,避免共享冻结数组引用)。 + * + * @return {Array} 默认自动出库规则数组。 + */ + const getDefaultAutoOutboundRules = () => []; + + const DEFAULT_CUTOFF_ORDER_TIME = '18:00'; + const CUTOFF_ORDER_TIME_MIN = '00:00'; + const CUTOFF_ORDER_TIME_MAX = '23:59'; + const DEFAULT_ALLOCATE_START_TIME = '08:00'; + const ALLOCATE_START_TIME_MIN = '00:00'; + const ALLOCATE_START_TIME_MAX = '23:59'; + // 自然日开始时间(业务日分界点):今日统计窗口 = [该时间点, 次日该时间点) + const DEFAULT_DAY_START_TIME = '06:00'; + const DAY_START_TIME_MIN = '00:00'; + const DAY_START_TIME_MAX = '23:59'; + + // 收货未入库提醒:默认关闭,开启后每天按 notice_time 扫描超时未入库的收货单 + const DEFAULT_PENDING_RECEIVING_NOTICE_TIME = '08:30'; + const DEFAULT_PENDING_RECEIVING_MIN_HOURS = 24; + const DEFAULT_PENDING_RECEIVING_MAX_HOURS = 48; + const PENDING_RECEIVING_NOTICE_TEMPLATE_MAX_LENGTH = 500; + const DEFAULT_PENDING_RECEIVING_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:'; + const DEFAULT_PENDING_RECEIVING_STORE_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:'; + const DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE = Object.freeze({ + enabled: false, + notice_time: DEFAULT_PENDING_RECEIVING_NOTICE_TIME, + min_hours: DEFAULT_PENDING_RECEIVING_MIN_HOURS, + max_hours: DEFAULT_PENDING_RECEIVING_MAX_HOURS, + notice_template: DEFAULT_PENDING_RECEIVING_NOTICE_TEMPLATE, + store_notice_template: DEFAULT_PENDING_RECEIVING_STORE_NOTICE_TEMPLATE, + }); + + // 站内信推送失败自动重发:默认关闭(未配置的仓库不重发,需在仓库设置中显式开启); + // 开启后仅重发「失败时间在 window_minutes 内」的消息(超窗口不再补发) + const DEFAULT_INBOX_PUSH_RETRY = Object.freeze({ + enabled: false, + window_minutes: 30, + }); + const INBOX_PUSH_RETRY_WINDOW_MINUTES_MIN = 1; + const INBOX_PUSH_RETRY_WINDOW_MINUTES_MAX = 1440; + + const DEFAULT_SUBJECT_CONFIG = Object.freeze({ + max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, + max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY, + min_group_order_fetch_quantity: 13, + auto_allocate_express_exclude_remarks: [], + default_express_code: 'STO', + default_platform_code: 'TB', + sender_name: '', + sender_tel: '', + province_name: '', + city_name: '', + district_name: '', + town_name: '', + address: '', + receiver_address: '', + group_wave_prefix: 'B', + delete_order_wave_prefix: 'A', + default_location_id: null, + single_order_pack_max_minutes: 3, + group_order_pack_max_minutes: 40, + big_group_pack_coefficient: 3, + single_weigh_require_pack: false, + stock_warning_enabled: false, + stock_warning_quantity: 0, + stock_static_hours: 168, + return_unpack_max_record_minutes: 5, + inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, + auto_outbound_enabled: DEFAULT_AUTO_OUTBOUND_ENABLED, + auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES, + cutoff_order_enabled: 1, + cutoff_order_time: DEFAULT_CUTOFF_ORDER_TIME, + allocate_start_time: DEFAULT_ALLOCATE_START_TIME, + day_start_time: DEFAULT_DAY_START_TIME, + receiving_pending_inbound_notice: DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE, + inbox_push_retry: DEFAULT_INBOX_PUSH_RETRY, + }); + + 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; + } + + if ([ true, 1, '1', 'true' ].includes(value)) { + return true; + } + + if ([ false, 0, '0', 'false' ].includes(value)) { + return false; + } + + throw new Error(`${fieldName} 必须是布尔值`); + }; + + /** + * 规范化库存预警规则配置。 + * + * @param {Array|null|undefined|string} rawRules 原始库存预警规则。 + * @return {Array} 规范化后的库存预警规则数组。 + */ + const normalizeInventoryWarningRules = rawRules => { + if (rawRules === undefined || rawRules === null || rawRules === '') { + return getDefaultInventoryWarningRules(); + } + + if (!Array.isArray(rawRules)) { + throw new Error('subject_config.inventory_warning_rules 必须是数组'); + } + + return rawRules.map((rule, index) => { + const basePath = `subject_config.inventory_warning_rules[${index}]`; + if (!rule || typeof rule !== 'object' || Array.isArray(rule)) { + throw new Error(`${basePath} 必须是对象`); + } + + const name = String(rule.name === undefined || rule.name === null ? '' : rule.name).trim(); + if (!name) { + throw new Error(`${basePath}.name 不能为空`); + } + + const key = String(rule.key === undefined || rule.key === null ? '' : rule.key).trim(); + if (!key) { + throw new Error(`${basePath}.key 不能为空`); + } + + const rawExpireDays = rule.expire_days; + if (rawExpireDays === undefined || rawExpireDays === null || rawExpireDays === '') { + throw new Error(`${basePath}.expire_days 必须是非负整数`); + } + const expireDays = Number(rawExpireDays); + if (!Number.isInteger(expireDays) || expireDays < 0) { + throw new Error(`${basePath}.expire_days 必须是非负整数`); + } + + const tipText = rule.tip_text === undefined || rule.tip_text === null ? '' : String(rule.tip_text); + + return { + name, + key, + expire_days: expireDays, + tip_text: tipText, + }; + }); + }; + + /** + * 规范化 HH:mm 时间文本(支持跨天:小时最大 maxHour)。 + * 缺省或格式非法(含超出 maxHour)时回退指定默认值。 + * + * @param {string|undefined|null} value 原始时间文本。 + * @param {string} defaultValue 默认 HH:mm。 + * @param {number} [maxHour=23] 允许的最大小时(放开时间用 47,表示可跨到次日)。 + * @return {string} 规范化后的 HH:mm 文本。 + */ + const normalizeHourMinuteTime = (value, defaultValue, maxHour = 23) => { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const text = String(value).trim(); + const match = /^(\d{1,2}):([0-5]\d)$/.exec(text); + if (!match || Number(match[1]) > maxHour) { + return defaultValue; + } + return `${String(Number(match[1])).padStart(2, '0')}:${match[2]}`; + }; + + /** + * 将 HH:mm 文本解析为总分钟数(支持跨天,用于时间先后比较)。 + * + * @param {string} timeText HH:mm 文本(小时可超过 23)。 + * @return {number} 总分钟数。 + */ + const parseHourMinuteToMinutes = timeText => { + const match = /^(\d{1,2}):(\d{2})$/.exec(String(timeText || '').trim()); + if (!match) return 0; + return Number(match[1]) * 60 + Number(match[2]); + }; + + /** + * 规范化「允许当天出库最后时间」配置(HH:mm,当天内 00:00~23:59)。 + * 缺省或格式非法时回退默认 06:00。 + * + * @param {string|undefined|null} value 原始时间文本。 + * @return {string} 规范化后的 HH:mm 文本。 + */ + const normalizeSameDayOutboundDeadlineTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_DEADLINE_TIME, 23); + + /** + * 规范化「放行时间」配置(HH:mm,支持跨天 00:00~47:59,如 27:00 = 次日 03:00)。 + * 缺省或格式非法时回退默认 22:00。 + * + * @param {string|undefined|null} value 原始时间文本。 + * @return {string} 规范化后的 HH:mm 文本。 + */ + const normalizeSameDayOutboundReleaseTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_RELEASE_TIME, 47); + + /** + * 规范化单条自动出库规则。 + * 字段:require_pack(需已打包) / require_weigh(需已称重) / require_sync(需已同步) + * / exclude_same_day_outbound(不出库当天订单) / same_day_outbound_deadline_time + * / same_day_outbound_release_time。 + * 三个 require_* 沿用「非 false 即 true(缺省开启)」口径;非对象项、时间越界抛错。 + * + * @param {Object} rawRule 原始单条规则。 + * @param {number} index 规则下标(用于报错定位)。 + * @return {Object} 规范化后的单条规则。 + */ + const normalizeAutoOutboundRule = (rawRule, index) => { + const basePath = `subject_config.auto_outbound_rules[${index}]`; + + if (!rawRule || typeof rawRule !== 'object' || Array.isArray(rawRule)) { + throw new Error(`${basePath} 必须是对象`); + } + + const sameDayOutboundDeadlineTime = normalizeSameDayOutboundDeadlineTime(rawRule.same_day_outbound_deadline_time); + const sameDayOutboundReleaseTime = normalizeSameDayOutboundReleaseTime(rawRule.same_day_outbound_release_time); + + // 保存时校验:允许当天出库最后时间不能大于当天放开时间 + if (parseHourMinuteToMinutes(sameDayOutboundDeadlineTime) > parseHourMinuteToMinutes(sameDayOutboundReleaseTime)) { + throw new Error(`自动出库规则第 ${index + 1} 条:允许当天出库最后时间不能大于当天放开时间`); + } + + return { + require_pack: rawRule.require_pack !== false, + require_weigh: rawRule.require_weigh !== false, + require_sync: rawRule.require_sync !== false, + exclude_same_day_outbound: normalizeBooleanFlag( + rawRule.exclude_same_day_outbound, + `${basePath}.exclude_same_day_outbound` + ) !== false, + same_day_outbound_deadline_time: sameDayOutboundDeadlineTime, + same_day_outbound_release_time: sameDayOutboundReleaseTime, + }; + }; + + /** + * 规范化自动出库规则数组。 + * 旧版本的对象结构(含 enabled/require_recheck/require_print/require_pick)不兼容: + * 一律按默认(空数组)处理,需重新配置。 + * + * @param {Array|Object|string|undefined|null} rawRules 原始自动出库规则。 + * @return {Array} 规范化后的自动出库规则数组。 + */ + const normalizeAutoOutboundRules = rawRules => { + if (rawRules === undefined || rawRules === null || rawRules === '') { + return []; + } + + let parsed = rawRules; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + return []; + } + } + + if (!Array.isArray(parsed)) { + return []; + } + + return parsed.map((rule, index) => normalizeAutoOutboundRule(rule, index)); + }; + + /** + * 规范化正整数字段(小于等于 0 或非整数时抛错)。 + * + * @param {*} value 原始值,空值返回默认值。 + * @param {number} defaultValue 默认值。 + * @param {string} fieldName 字段全名(用于报错)。 + * @return {number} 规范化后的正整数。 + */ + const normalizePositiveInteger = (value, defaultValue, fieldName) => { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0) { + throw new Error(`${fieldName} 必须是大于 0 的整数`); + } + + return normalized; + }; + + /** + * 规范化通知短语:空值回退默认短语,非字符串转字符串,超长报错。 + * + * @param {*} value 原始短语。 + * @param {string} defaultValue 默认短语。 + * @param {string} fieldName 字段全名(用于报错)。 + * @return {string} 规范化后的短语。 + */ + const normalizeNoticeTemplateText = (value, defaultValue, fieldName) => { + if (value === undefined || value === null) { + return defaultValue; + } + + const normalized = String(value).trim(); + if (!normalized) { + return defaultValue; + } + + if (normalized.length > PENDING_RECEIVING_NOTICE_TEMPLATE_MAX_LENGTH) { + throw new Error(`${fieldName} 长度不能超过 ${PENDING_RECEIVING_NOTICE_TEMPLATE_MAX_LENGTH} 字符`); + } + + return normalized; + }; + + /** + * 规范化「收货未入库提醒」配置。 + * 字段:enabled(是否启用,默认否) / notice_time(提醒时间 HH:mm,默认 08:30) + * / min_hours(超时下限小时,默认 24) / max_hours(超时上限小时,默认 48) + * / notice_template(仓库客服群通知短语) / store_notice_template(货主群通知短语)。 + * 非法结构(非对象/非法 JSON)回退默认值;时间格式、小时数越界、短语超长抛错。 + * + * @param {Object|string|null|undefined} rawValue 原始配置。 + * @return {Object} 规范化后的配置对象。 + */ + const normalizeReceivingPendingInboundNotice = rawValue => { + if (rawValue === undefined || rawValue === null || rawValue === '') { + return { ...DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE }; + } + + let parsed = rawValue; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + return { ...DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE }; + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { ...DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE }; + } + + const noticeTime = normalizeSubjectConfigText(parsed.notice_time, DEFAULT_PENDING_RECEIVING_NOTICE_TIME); + if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(noticeTime)) { + throw new Error('subject_config.receiving_pending_inbound_notice.notice_time 格式必须为 HH:mm(如 08:30)'); + } + + const minHours = normalizePositiveInteger( + parsed.min_hours, + DEFAULT_PENDING_RECEIVING_MIN_HOURS, + 'subject_config.receiving_pending_inbound_notice.min_hours' + ); + const maxHours = normalizePositiveInteger( + parsed.max_hours, + DEFAULT_PENDING_RECEIVING_MAX_HOURS, + 'subject_config.receiving_pending_inbound_notice.max_hours' + ); + if (minHours >= maxHours) { + throw new Error('subject_config.receiving_pending_inbound_notice.min_hours 必须小于 max_hours'); + } + + return { + enabled: normalizeBooleanFlag(parsed.enabled, 'subject_config.receiving_pending_inbound_notice.enabled') === true, + notice_time: noticeTime, + min_hours: minHours, + max_hours: maxHours, + notice_template: normalizeNoticeTemplateText( + parsed.notice_template, + DEFAULT_PENDING_RECEIVING_NOTICE_TEMPLATE, + 'subject_config.receiving_pending_inbound_notice.notice_template' + ), + store_notice_template: normalizeNoticeTemplateText( + parsed.store_notice_template, + DEFAULT_PENDING_RECEIVING_STORE_NOTICE_TEMPLATE, + 'subject_config.receiving_pending_inbound_notice.store_notice_template' + ), + }; + }; + + /** + * 规范化「站内信推送失败自动重发」配置(subject_config.inbox_push_retry)。 + * 字段:enabled(是否启用,默认否) / window_minutes(重发时间范围分钟,默认 30,范围 1-1440)。 + * 非法结构(非对象/非法 JSON)回退默认值;enabled 非布尔值、window_minutes 越界抛错。 + * + * @param {Object|string|null|undefined} rawValue 原始配置。 + * @return {Object} 规范化后的配置对象。 + */ + const normalizeInboxPushRetry = rawValue => { + if (rawValue === undefined || rawValue === null || rawValue === '') { + return { ...DEFAULT_INBOX_PUSH_RETRY }; + } + + let parsed = rawValue; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + return { ...DEFAULT_INBOX_PUSH_RETRY }; + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { ...DEFAULT_INBOX_PUSH_RETRY }; + } + + const rawWindowMinutes = parsed.window_minutes; + let windowMinutes = DEFAULT_INBOX_PUSH_RETRY.window_minutes; + if (!(rawWindowMinutes === undefined || rawWindowMinutes === null || rawWindowMinutes === '')) { + const value = Number(rawWindowMinutes); + if (!Number.isInteger(value) + || value < INBOX_PUSH_RETRY_WINDOW_MINUTES_MIN + || value > INBOX_PUSH_RETRY_WINDOW_MINUTES_MAX) { + throw new Error( + `subject_config.inbox_push_retry.window_minutes 必须是 ${INBOX_PUSH_RETRY_WINDOW_MINUTES_MIN}-${INBOX_PUSH_RETRY_WINDOW_MINUTES_MAX} 的整数(分钟)` + ); + } + windowMinutes = value; + } + + return { + enabled: normalizeBooleanFlag(parsed.enabled, 'subject_config.inbox_push_retry.enabled') === true, + window_minutes: windowMinutes, + }; + }; + + /** + * 规范化主体配置,确保默认值与字段约束一致。 + * + * @param {Object|string|null|undefined} rawValue 主体配置原始值。 + * @return {Object} 规范化后的主体配置对象。 + */ + + const normalizeSubjectConfig = rawValue => { + if (rawValue === undefined || rawValue === null || rawValue === '') { + return { + ...DEFAULT_SUBJECT_CONFIG, + inventory_warning_rules: getDefaultInventoryWarningRules(), + auto_outbound_rules: getDefaultAutoOutboundRules(), + }; + } + + let parsed = rawValue; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + throw new Error('subject_config 必须是合法 JSON 对象'); + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error('subject_config 必须是对象'); + } + + const normalized = { + ...parsed, + }; + + const rawLimit = parsed.max_notice_webhook_count; + if (rawLimit === undefined || rawLimit === null || rawLimit === '') { + normalized.max_notice_webhook_count = DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; + } else { + const limit = Number(rawLimit); + if (!Number.isInteger(limit) || limit < 0 || limit > DEFAULT_MAX_NOTICE_WEBHOOK_COUNT) { + throw new Error(`subject_config.max_notice_webhook_count 必须是 0-${DEFAULT_MAX_NOTICE_WEBHOOK_COUNT} 的整数`); + } + normalized.max_notice_webhook_count = limit; + } + + const rawMaxWaveQuantity = parsed.max_wave_quantity; + if (rawMaxWaveQuantity === undefined || rawMaxWaveQuantity === null || rawMaxWaveQuantity === '') { + normalized.max_wave_quantity = DEFAULT_MAX_WAVE_QUANTITY; + } else { + const maxWaveQuantity = Number(rawMaxWaveQuantity); + if (!Number.isInteger(maxWaveQuantity) || maxWaveQuantity <= 0) { + throw new Error('subject_config.max_wave_quantity 必须是大于 0 的整数'); + } + normalized.max_wave_quantity = maxWaveQuantity; + } + + const rawMinGroupOrderFetchQuantity = parsed.min_group_order_fetch_quantity; + if (rawMinGroupOrderFetchQuantity === undefined || rawMinGroupOrderFetchQuantity === null || rawMinGroupOrderFetchQuantity === '') { + normalized.min_group_order_fetch_quantity = DEFAULT_SUBJECT_CONFIG.min_group_order_fetch_quantity; + } else { + const minGroupOrderFetchQuantity = Number(rawMinGroupOrderFetchQuantity); + if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) { + throw new Error('subject_config.min_group_order_fetch_quantity 必须是大于 0 的整数'); + } + normalized.min_group_order_fetch_quantity = minGroupOrderFetchQuantity; + } + + const rawSingleOrderPackMaxMinutes = parsed.single_order_pack_max_minutes; + if (rawSingleOrderPackMaxMinutes === undefined || rawSingleOrderPackMaxMinutes === null || rawSingleOrderPackMaxMinutes === '') { + normalized.single_order_pack_max_minutes = DEFAULT_SUBJECT_CONFIG.single_order_pack_max_minutes; + } else { + const singleOrderPackMaxMinutes = Number(rawSingleOrderPackMaxMinutes); + if (!Number.isInteger(singleOrderPackMaxMinutes) || singleOrderPackMaxMinutes <= 0) { + throw new Error('subject_config.single_order_pack_max_minutes 必须是大于 0 的整数'); + } + normalized.single_order_pack_max_minutes = singleOrderPackMaxMinutes; + } + + const rawGroupOrderPackMaxMinutes = parsed.group_order_pack_max_minutes; + if (rawGroupOrderPackMaxMinutes === undefined || rawGroupOrderPackMaxMinutes === null || rawGroupOrderPackMaxMinutes === '') { + normalized.group_order_pack_max_minutes = DEFAULT_SUBJECT_CONFIG.group_order_pack_max_minutes; + } else { + const groupOrderPackMaxMinutes = Number(rawGroupOrderPackMaxMinutes); + if (!Number.isInteger(groupOrderPackMaxMinutes) || groupOrderPackMaxMinutes <= 0) { + throw new Error('subject_config.group_order_pack_max_minutes 必须是大于 0 的整数'); + } + normalized.group_order_pack_max_minutes = groupOrderPackMaxMinutes; + } + + const rawBigGroupPackCoefficient = parsed.big_group_pack_coefficient; + if (rawBigGroupPackCoefficient === undefined || rawBigGroupPackCoefficient === null || rawBigGroupPackCoefficient === '') { + normalized.big_group_pack_coefficient = DEFAULT_SUBJECT_CONFIG.big_group_pack_coefficient; + } else { + const bigGroupPackCoefficient = Number(rawBigGroupPackCoefficient); + if (!Number.isFinite(bigGroupPackCoefficient) || bigGroupPackCoefficient <= 0) { + throw new Error('subject_config.big_group_pack_coefficient 必须是大于 0 的数字'); + } + normalized.big_group_pack_coefficient = bigGroupPackCoefficient; + } + + // 散单称重是否需要打包:默认关闭(未配置的仓库不校验打包状态) + if (Object.prototype.hasOwnProperty.call(parsed, 'single_weigh_require_pack')) { + normalized.single_weigh_require_pack = normalizeBooleanFlag( + parsed.single_weigh_require_pack, + 'subject_config.single_weigh_require_pack' + ); + } + + // 是否开启库存预警:默认关闭 + if (Object.prototype.hasOwnProperty.call(parsed, 'stock_warning_enabled')) { + normalized.stock_warning_enabled = normalizeBooleanFlag( + parsed.stock_warning_enabled, + 'subject_config.stock_warning_enabled' + ); + } + + const rawStockWarningQuantity = parsed.stock_warning_quantity; + if (rawStockWarningQuantity === undefined || rawStockWarningQuantity === null || rawStockWarningQuantity === '') { + normalized.stock_warning_quantity = DEFAULT_SUBJECT_CONFIG.stock_warning_quantity; + } else { + const stockWarningQuantity = Number(rawStockWarningQuantity); + if (!Number.isInteger(stockWarningQuantity) || stockWarningQuantity < 0) { + throw new Error('subject_config.stock_warning_quantity 必须是非负整数'); + } + normalized.stock_warning_quantity = stockWarningQuantity; + } + + const rawStockStaticHours = parsed.stock_static_hours; + if (rawStockStaticHours === undefined || rawStockStaticHours === null || rawStockStaticHours === '') { + normalized.stock_static_hours = DEFAULT_SUBJECT_CONFIG.stock_static_hours; + } else { + const stockStaticHours = Number(rawStockStaticHours); + if (!Number.isFinite(stockStaticHours) || stockStaticHours <= 0) { + throw new Error('subject_config.stock_static_hours 必须是大于 0 的数字(小时)'); + } + normalized.stock_static_hours = stockStaticHours; + } + + const rawReturnUnpackMaxRecordMinutes = parsed.return_unpack_max_record_minutes; + if (rawReturnUnpackMaxRecordMinutes === undefined || rawReturnUnpackMaxRecordMinutes === null || rawReturnUnpackMaxRecordMinutes === '') { + normalized.return_unpack_max_record_minutes = DEFAULT_SUBJECT_CONFIG.return_unpack_max_record_minutes; + } else { + const returnUnpackMaxRecordMinutes = Number(rawReturnUnpackMaxRecordMinutes); + if (!Number.isInteger(returnUnpackMaxRecordMinutes) || returnUnpackMaxRecordMinutes <= 0) { + throw new Error('subject_config.return_unpack_max_record_minutes 必须是大于 0 的整数'); + } + normalized.return_unpack_max_record_minutes = returnUnpackMaxRecordMinutes; + } + + const rawExcludeRemarks = parsed.auto_allocate_express_exclude_remarks; + if (rawExcludeRemarks === undefined || rawExcludeRemarks === null || rawExcludeRemarks === '') { + normalized.auto_allocate_express_exclude_remarks = []; + } else { + if (!Array.isArray(rawExcludeRemarks)) { + throw new Error('subject_config.auto_allocate_express_exclude_remarks 必须是字符串数组'); + } + normalized.auto_allocate_express_exclude_remarks = rawExcludeRemarks + .map((item, index) => { + if (item === undefined || item === null || item === '') { + return null; + } + const trimmed = String(item).trim(); + if (trimmed === '') { + throw new Error(`subject_config.auto_allocate_express_exclude_remarks[${index}] 不能为空字符串`); + } + return trimmed; + }) + .filter(Boolean); + } + + 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 + ); + + const rawGroupWavePrefix = parsed.group_wave_prefix; + if (rawGroupWavePrefix === undefined || rawGroupWavePrefix === null || rawGroupWavePrefix === '') { + normalized.group_wave_prefix = DEFAULT_SUBJECT_CONFIG.group_wave_prefix; + } else { + const groupWavePrefix = String(rawGroupWavePrefix).trim(); + if (groupWavePrefix === '') { + normalized.group_wave_prefix = DEFAULT_SUBJECT_CONFIG.group_wave_prefix; + } else { + if (groupWavePrefix.length > 5) { + throw new Error('subject_config.group_wave_prefix 最多 5 个字符'); + } + normalized.group_wave_prefix = groupWavePrefix; + } + } + + const rawDeleteOrderWavePrefix = parsed.delete_order_wave_prefix; + if (rawDeleteOrderWavePrefix === undefined || rawDeleteOrderWavePrefix === null || rawDeleteOrderWavePrefix === '') { + normalized.delete_order_wave_prefix = DEFAULT_SUBJECT_CONFIG.delete_order_wave_prefix; + } else { + const deleteOrderWavePrefix = String(rawDeleteOrderWavePrefix).trim(); + if (deleteOrderWavePrefix === '') { + normalized.delete_order_wave_prefix = DEFAULT_SUBJECT_CONFIG.delete_order_wave_prefix; + } else { + if (deleteOrderWavePrefix.length > 5) { + throw new Error('subject_config.delete_order_wave_prefix 最多 5 个字符'); + } + normalized.delete_order_wave_prefix = deleteOrderWavePrefix; + } + } + + normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules); + normalized.auto_outbound_enabled = normalizeBooleanFlag( + parsed.auto_outbound_enabled, + 'subject_config.auto_outbound_enabled' + ) === true; + normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules); + normalized.receiving_pending_inbound_notice = normalizeReceivingPendingInboundNotice( + parsed.receiving_pending_inbound_notice + ); + normalized.inbox_push_retry = normalizeInboxPushRetry(parsed.inbox_push_retry); + + const rawDefaultLocationId = parsed.default_location_id; + if (rawDefaultLocationId === undefined || rawDefaultLocationId === null || rawDefaultLocationId === '') { + normalized.default_location_id = null; + } else { + const defaultLocationId = Number(rawDefaultLocationId); + if (!Number.isInteger(defaultLocationId) || defaultLocationId <= 0) { + throw new Error('subject_config.default_location_id 必须是正整数库位ID'); + } + normalized.default_location_id = defaultLocationId; + } + + if (Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_enabled')) { + normalized.cutoff_order_enabled = normalizeBooleanFlag(parsed.cutoff_order_enabled, 'subject_config.cutoff_order_enabled'); + } + + if (Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_time')) { + const cutoffTime = normalizeSubjectConfigText(parsed.cutoff_order_time, DEFAULT_CUTOFF_ORDER_TIME); + if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(cutoffTime)) { + throw new Error('subject_config.cutoff_order_time 格式必须为 HH:mm(如 18:00)'); + } + if (cutoffTime < CUTOFF_ORDER_TIME_MIN || cutoffTime > CUTOFF_ORDER_TIME_MAX) { + normalized.cutoff_order_time = DEFAULT_CUTOFF_ORDER_TIME; + } else { + normalized.cutoff_order_time = cutoffTime; + } + } + + if (Object.prototype.hasOwnProperty.call(parsed, 'allocate_start_time')) { + const allocateStartTime = normalizeSubjectConfigText(parsed.allocate_start_time, DEFAULT_ALLOCATE_START_TIME); + if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(allocateStartTime)) { + throw new Error('subject_config.allocate_start_time 格式必须为 HH:mm(如 08:00)'); + } + if (allocateStartTime < ALLOCATE_START_TIME_MIN || allocateStartTime > ALLOCATE_START_TIME_MAX) { + normalized.allocate_start_time = DEFAULT_ALLOCATE_START_TIME; + } else { + normalized.allocate_start_time = allocateStartTime; + } + } else { + // 旧数据补齐默认开始自动分配时间 + normalized.allocate_start_time = DEFAULT_ALLOCATE_START_TIME; + } + + if (Object.prototype.hasOwnProperty.call(parsed, 'day_start_time')) { + const dayStartTime = normalizeSubjectConfigText(parsed.day_start_time, DEFAULT_DAY_START_TIME); + if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(dayStartTime)) { + throw new Error('subject_config.day_start_time 格式必须为 HH:mm(如 06:00)'); + } + if (dayStartTime < DAY_START_TIME_MIN || dayStartTime > DAY_START_TIME_MAX) { + normalized.day_start_time = DEFAULT_DAY_START_TIME; + } else { + normalized.day_start_time = dayStartTime; + } + } else { + // 旧数据补齐默认自然日开始时间 + normalized.day_start_time = DEFAULT_DAY_START_TIME; + } + + // 跨字段校验:仅当显式同时提交两个时间字段且相等时拒绝(自动分配窗口为空) + if (Object.prototype.hasOwnProperty.call(parsed, 'allocate_start_time') + && Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_time') + && normalized.allocate_start_time === normalized.cutoff_order_time) { + throw new Error('subject_config.allocate_start_time 不能等于 subject_config.cutoff_order_time(自动分配窗口为空)'); + } + + return normalized; + }; const Store = app.model.define('store', { id: { @@ -114,21 +865,11 @@ module.exports = app => { defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), comment: '更新时间', }, - logo_url: { - type: STRING(255), - allowNull: true, - comment: 'logo链接', - }, project: { type: STRING(20), allowNull: true, comment: '应用', }, - domain: { - type: STRING(100), - allowNull: true, - comment: '绑定域名', - }, auth_end: { type: DATE, allowNull: true, @@ -145,6 +886,23 @@ module.exports = app => { defaultValue: 107374182400, comment: '仓库文件存储配额', }, + subject_config: { + type: JSON_TYPE, + allowNull: true, + defaultValue: { ...DEFAULT_SUBJECT_CONFIG }, + comment: '主体配置JSON', + get() { + return normalizeSubjectConfig(this.getDataValue('subject_config')); + }, + set(value) { + this.setDataValue('subject_config', normalizeSubjectConfig(value)); + }, + validate: { + isValidSubjectConfig(value) { + normalizeSubjectConfig(value); + }, + }, + }, }, { tableName: 'wms_store', freezeTableName: true, @@ -179,7 +937,7 @@ module.exports = app => { // 关联关系 - 使用您推荐的方式 Store.associate = function() { - const { Account, Role, AccountStoreEmployee, ProhibitedType } = app.model; + const { Account, Role, AccountStoreEmployee, ProhibitedType, NotificationWebhook } = app.model; // 关联创建人 Store.belongsTo(Account, { @@ -199,18 +957,29 @@ module.exports = app => { as: 'roles', }); - // 关联商家拥有的账号角色关联 + // 关联商家拥有的账号员工关联 Store.hasMany(AccountStoreEmployee, { foreignKey: 'store_id', - as: 'accountStoreEmployee', + as: 'accountStoreEmployees', }); Store.hasMany(ProhibitedType, { foreignKey: 'warehouse_id', as: 'prohibitedTypes', }); + + Store.hasMany(NotificationWebhook, { + foreignKey: 'store_id', + as: 'notificationWebhooks', + }); }; + Store.DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; + Store.DEFAULT_INVENTORY_WARNING_RULES = DEFAULT_INVENTORY_WARNING_RULES; + Store.DEFAULT_SUBJECT_CONFIG = DEFAULT_SUBJECT_CONFIG; + Store.normalizeSubjectConfig = normalizeSubjectConfig; + Store.normalizeAutoOutboundRules = normalizeAutoOutboundRules; + // 实例方法:检查商家是否启用 Store.prototype.isEnabled = function() { return this.status === 1; @@ -246,80 +1015,5 @@ module.exports = app => { return emailRegex.test(this.contact_email); }; - // 类方法:根据账号ID查找商家 - Store.findByAccountId = async function(accountId) { - return await this.findOne({ - where: { - account_id: accountId, - status: 1, - }, - }); - }; - - // 类方法:获取所有启用的商家 - Store.findAllEnabled = async function() { - return await this.findAll({ - where: { - status: 1, - }, - order: [[ 'company_name', 'ASC' ]], - }); - }; - - // 类方法:获取所有仓库类型的商家 - Store.findAllWarehouses = async function() { - return await this.findAll({ - where: { - status: 1, - project: 'warehouse', - }, - order: [[ 'company_name', 'ASC' ]], - }); - }; - - // 类方法:检查公司名称是否存在 - Store.checkCompanyNameExists = async function(companyName, excludeId = null) { - const where = { - company_name: companyName, - }; - - if (excludeId) { - where.id = { - [app.Sequelize.Op.ne]: excludeId, - }; - } - - const store = await this.findOne({ where }); - return !!store; - }; - - // 类方法:创建商家时的数据验证 - Store.validateStoreData = function(data) { - const errors = []; - - // 必填字段检查 - const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ]; - for (const field of requiredFields) { - if (!data[field]) { - errors.push(`${field} 不能为空`); - } - } - - // 公司名称长度检查 - if (data.company_name && (data.company_name.length < 1 || data.company_name.length > 200)) { - errors.push('公司名称长度应在1-200个字符之间'); - } - - // 邮箱格式检查(如果提供了邮箱) - if (data.contact_email && data.contact_email.trim() !== '') { - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(data.contact_email)) { - errors.push('联系邮箱格式不正确'); - } - } - - return errors; - }; - return Store; }; diff --git a/app/model/store_express_binding_policy.js b/app/model/store_express_binding_policy.js new file mode 100644 index 0000000..0f53969 --- /dev/null +++ b/app/model/store_express_binding_policy.js @@ -0,0 +1,144 @@ +'use strict'; + +/** + * 订单自定义店铺-快递绑定策略模型。 + * + * 支持在仓库维度下,为用户自定义店铺标签配置快递绑定策略, + * 按优先级匹配,可附加商品、地区、重量等条件。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, TINYINT, DATE, TEXT, JSON: JSON_TYPE } = app.Sequelize; + + const StoreExpressBindingPolicy = app.model.define('store_express_binding_policy', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID,策略所属仓库', + }, + custom_name: { + type: STRING(100), + allowNull: false, + comment: '策略名称,便于人工识别', + }, + shop_name: { + type: JSON_TYPE, + allowNull: true, + comment: '包含店铺名称,字符串数组,如["旗舰店","奥莱店"],NULL=不限制', + }, + store_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '限定货主ID,数字数组,如[1000000,1000001],NULL=不限制', + }, + express_code: { + type: STRING(50), + allowNull: false, + comment: '绑定的快递编码(wms_express.code)', + }, + priority: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先匹配', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + validate: { + isIn: { + args: [[ 0, 1 ]], + msg: '启用状态不合法,0=停用,1=启用', + }, + }, + comment: '是否启用:0=停用,1=启用', + }, + regions: { + type: JSON_TYPE, + allowNull: true, + comment: '限定地区,字符串数组,如["广东省","广州市"],NULL=不限制', + }, + exclude_regions: { + type: JSON_TYPE, + allowNull: true, + comment: '排除地区,字符串数组,如["新疆维吾尔自治区"],NULL=不排除', + }, + min_weight_g: { + type: INTEGER, + allowNull: true, + comment: '最小重量(克),NULL=不限制', + }, + max_weight_g: { + type: INTEGER, + allowNull: true, + comment: '最大重量(克),NULL=不限制', + }, + weight_type: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + validate: { isIn: { args: [[ 0, 1, 2, 3 ]], msg: '重量类型不合法,0=常规/1=轻货/2=重货/3=冷链' } }, + comment: '重量段类型:0=常规/1=轻货/2=重货/3=冷链', + }, + prohibited_type_id: { + type: JSON_TYPE, + allowNull: true, + comment: '违禁品类型ID数组(关联 wms_prohibited_type.id),如[1,2],NULL=不限制违禁品', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注说明', + }, + creator_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '创建人账户ID(accounts.id)', + }, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_store_express_binding_policy', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单自定义店铺-快递绑定策略表', + indexes: [ + { + name: 'idx_warehouse_enabled', + fields: [ 'warehouse_id', 'is_enabled', 'deleted_at' ], + }, + { + name: 'idx_warehouse_express', + fields: [ 'warehouse_id', 'express_code', 'deleted_at' ], + }, + ], + }); + + return StoreExpressBindingPolicy; +}; diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 01df60f..0e81fc2 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -1,7 +1,478 @@ 'use strict'; module.exports = app => { - const { BIGINT, TEXT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize; + const { BIGINT, TEXT, STRING, DATE, TINYINT, INTEGER, JSON: JSON_TYPE } = app.Sequelize; + + const POLICY_CONFIG_FIELDS = Object.freeze([ + + Object.freeze({ + key: 'auto_allocate_bin', + name: '自动分配库位', + type: 'flag', + default: 0, + required: false, + description: '收货上架时是否自动推荐库位', + }), + Object.freeze({ + key: 'auto_allocate_express', + name: '是否自动分配快递', + type: 'flag', + default: 0, + required: false, + description: '控制该货主在当前仓库下是否自动分配快递', + }), + Object.freeze({ + key: 'auto_allocate_storage', + name: '是否自动分配储位', + type: 'flag', + default: 0, + required: false, + description: '控制该货主在当前仓库下是否自动分配储位', + }), + Object.freeze({ + key: 'allow_receiving_quick_putaway', + name: '收货单快捷入库', + type: 'flag', + default: 0, + required: false, + description: '控制该货主在当前仓库下是否允许使用收货单快捷入库', + }), + Object.freeze({ + key: 'allow_receiving_direct_putaway', + name: '收货单直入库存', + type: 'flag', + default: 0, + required: false, + description: '控制该货主在当前仓库下是否允许使用收货单直入库存(一步写库存并生成入库单)', + }), + Object.freeze({ + key: 'allow_mix_batch', + name: '允许混批', + type: 'flag', + default: 0, + required: false, + description: '是否允许不同批次混合存放', + }), + Object.freeze({ + key: 'allow_temp_storage', + name: '允许临时存放', + type: 'flag', + default: 0, + required: false, + description: '是否允许进入临时存放区', + }), + Object.freeze({ + key: 'storage_separation', + name: '是否存储分离', + type: 'flag', + default: 1, + required: false, + description: '控制该货主在当前仓库下是否按独立存储策略管理库存', + }), + Object.freeze({ + key: 'allow_oversell', + name: '允许超卖', + type: 'flag', + default: 0, + required: false, + description: '是否允许该货主在当前仓库下锁定超过可用库存', + }), + Object.freeze({ + key: 'express_quota', + name: '快递号额度', + type: 'integer', + default: 0, + required: false, + description: '允许在快递余额之外额外分配的快递号数量', + min: 0, + max: 1000000, + }), + Object.freeze({ + key: 'need_order_approval', + name: '推送订单需审批', + type: 'flag', + default: 1, + required: false, + description: '控制货主推送订单创建后是否必须进入审批流程', + }), + Object.freeze({ + key: 'auto_sync_back', + name: '自动同步回传', + type: 'flag', + default: 1, + required: false, + description: '快递号分配成功后是否自动同步订单信息到外部系统(奇门/API/手动)', + }), + Object.freeze({ + key: 'enable_external_express_code', + name: '启用外部快递编码', + type: 'flag', + default: 0, + required: false, + description: '控制该货主在当前仓库下是否允许使用外部快递编码,为否的时候默认使用下方的默认快递', + }), + Object.freeze({ + key: 'default_express_code', + name: '默认快递', + type: 'list', + default: 'STO', + required: false, + description: '货主在当前仓下默认使用的快递编码', + }), + Object.freeze({ + key: 'stockout_default_express_code', + name: '出库单默认快递', + type: 'list', + default: 'ZT', + required: false, + description: '货主在当前仓下出库单默认使用的快递编码,默认 ZT 自提', + }), + Object.freeze({ + key: 'default_platform_code', + name: '默认平台', + type: 'list', + default: 'TB', + required: false, + description: '货主在当前仓下默认使用的平台编码', + }), + Object.freeze({ + key: 'sender_name', + name: '发件人姓名', + type: 'string', + default: '', + required: false, + description: '货主在当前仓下面单的默认发件人姓名', + maxLength: 50, + }), + Object.freeze({ + key: 'sender_tel', + name: '发件人电话', + type: 'string', + default: '', + required: false, + description: '货主在当前仓下面单的默认发件人联系电话', + maxLength: 20, + }), + Object.freeze({ + key: 'province_name', + name: '省份', + type: 'string', + default: '', + required: false, + description: '货主在当前仓下面单的发件省份', + maxLength: 50, + }), + Object.freeze({ + key: 'city_name', + name: '城市', + type: 'string', + default: '', + required: false, + description: '货主在当前仓下面单的发件城市', + maxLength: 50, + }), + Object.freeze({ + key: 'district_name', + name: '区/县', + type: 'string', + default: '', + required: false, + description: '货主在当前仓下面单的发件区/县', + maxLength: 50, + }), + Object.freeze({ + key: 'town_name', + name: '镇/街道', + type: 'string', + default: '', + required: false, + description: '货主在当前仓下面单的发件镇/街道', + maxLength: 50, + }), + Object.freeze({ + key: 'address', + name: '详细地址', + type: 'string', + default: '', + required: false, + description: '货主在当前仓下面单的发件详细地址', + maxLength: 200, + }), + Object.freeze({ + key: 'waybill_custom_display_type', + name: '面单自定义显示类型', + type: 'enum', + default: '1', + required: false, + description: '控制面单自定义区商品信息展示内容', + options: [ + Object.freeze({ value: '1', label: '隐藏' }), + Object.freeze({ value: '2', label: '商品名称和数量' }), + Object.freeze({ value: '3', label: '拣货库位和条码和数量' }), + Object.freeze({ value: '4', label: '拣货库位和条码后5位和数量' }), + Object.freeze({ value: '5', label: '拣货库位商品名称条码和数量' }), + ], + }), + Object.freeze({ + key: 'cutoff_order_enabled', + name: '启用截单', + type: 'flag', + default: 1, + required: false, + description: '启用后,订单创建时间早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),不再自动分配快递和储位,不再自动加团', + }), + Object.freeze({ + key: 'allocate_start_time', + name: '开始自动分配时间', + type: 'string', + default: '08:00', + required: false, + maxLength: 5, + min: '00:00', + max: '23:59', + description: '开始自动分配时间,格式 HH:mm,如 08:00;早于该时间的订单与超过截单时间行为一致,不自动分配快递和储位,不自动加团;晚于截单时间时截单时间视为次日', + }), + Object.freeze({ + key: 'cutoff_order_time', + name: '截单时间', + type: 'string', + default: '18:00', + required: false, + maxLength: 5, + min: '00:00', + max: '23:59', + description: '截单时间,格式 HH:mm,如 16:00', + }), + Object.freeze({ + key: 'after_sale_followup_hours', + name: '售后跟进时间(h)', + type: 'integer', + default: 24, + required: false, + min: 1, + max: 720, + description: '售后单设为等待外部反馈后,默认多少小时需二次跟进。具体类型可在代码枚举中覆盖', + }), + Object.freeze({ + key: 'notify_manual_sync', + name: '是否通知手工单回传', + type: 'flag', + default: 0, + required: false, + description: '手工单同步回传后是否通知货主(订单同步完成通知),默认否', + }), + ]); + const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => { + result[field.key] = field; + 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, + type: field.type, + default: field.default, + required: field.required, + description: field.description, + ...(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 } : {}), + ...(field.step !== undefined ? { step: field.step } : {}), + ...(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 { + return JSON.parse(value); + } catch (error) { + throw new Error(`${fieldName} 不是合法JSON`); + } + } + return value; + }; + + const normalizePolicyConfig = (value, options = {}) => { + const { + fieldName = 'policy_config', + allowEmpty = false, + sanitizeOnly = false, + } = options; + + if (value === undefined || value === null || value === '') { + if (allowEmpty) { + return null; + } + throw new Error(`${fieldName} 参数不能为空`); + } + + const parsed = parsePolicyConfig(value, fieldName); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`${fieldName} 必须为对象`); + } + + const supportedKeys = Object.keys(POLICY_CONFIG_FIELD_MAP); + const unsupportedKeys = Object.keys(parsed).filter(key => !POLICY_CONFIG_FIELD_MAP[key]); + if (unsupportedKeys.length && !sanitizeOnly) { + throw new Error(`${fieldName} 包含不支持字段: ${unsupportedKeys.join(', ')};仅允许字段: ${supportedKeys.join(', ')}`); + } + + const normalized = {}; + for (const field of POLICY_CONFIG_FIELDS) { + if (!Object.prototype.hasOwnProperty.call(parsed, field.key)) { + continue; + } + + const rawValue = parsed[field.key]; + if (rawValue === undefined || rawValue === null || rawValue === '') { + if (field.type === 'string') { + normalized[field.key] = ''; + } + continue; + } + + try { + if (field.type === 'enum') { + const valueText = String(rawValue).trim(); + 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; + continue; + } + if (rawValue === false || rawValue === 0 || rawValue === '0') { + normalized[field.key] = 0; + continue; + } + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + + if (field.type === 'integer') { + const num = Number(rawValue); + if (!Number.isFinite(num) || num < field.min || num > field.max) { + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + normalized[field.key] = Math.floor(num); + continue; + } + + if (field.type === 'number') { + const num = Number(rawValue); + if (!Number.isFinite(num) || num < field.min || num > field.max) { + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + const precision = Number.isInteger(field.precision) ? field.precision : 2; + const factor = 10 ** precision; + normalized[field.key] = Math.round(num * factor) / factor; + continue; + } + + if (field.type === 'string') { + const text = String(rawValue).trim(); + if (text.length > field.maxLength) { + throw new Error(`${fieldName}.${field.key} 长度不能超过 ${field.maxLength}`); + } + // 时间类型字符串范围校验 + if (field.min !== undefined && field.max !== undefined && text !== '' && (text < field.min || text > field.max)) { + normalized[field.key] = field.default !== undefined ? String(field.default) : ''; + } else { + normalized[field.key] = text; + } + } + } catch (error) { + if (!sanitizeOnly) { + throw error; + } + } + } + + // 跨字段校验:开始自动分配时间与截单时间相同会导致自动分配窗口为空,保存时拒绝 + if (!sanitizeOnly) { + const startTimeField = POLICY_CONFIG_FIELD_MAP.allocate_start_time; + const cutoffTimeField = POLICY_CONFIG_FIELD_MAP.cutoff_order_time; + const startTimeForCheck = Object.prototype.hasOwnProperty.call(normalized, 'allocate_start_time') + ? String(normalized.allocate_start_time || '').trim() + : String(startTimeField && startTimeField.default || '08:00'); + const cutoffTimeForCheck = Object.prototype.hasOwnProperty.call(normalized, 'cutoff_order_time') + ? String(normalized.cutoff_order_time || '').trim() + : String(cutoffTimeField && cutoffTimeField.default || '18:00'); + if (startTimeForCheck && cutoffTimeForCheck && startTimeForCheck === cutoffTimeForCheck) { + throw new Error(`${fieldName}.allocate_start_time 不能等于 ${fieldName}.cutoff_order_time(自动分配窗口为空)`); + } + } + + return Object.keys(normalized).length ? normalized : null; + }; const StoreWarehouse = app.model.define('store_warehouse', { id: { @@ -54,10 +525,15 @@ module.exports = app => { comment: '申请时间', }, print_quantity: { - type: BIGINT(12), + type: INTEGER(11), allowNull: false, comment: '面单余额', }, + print_quantity_locked: { + type: INTEGER(11), + allowNull: false, + comment: '面单锁定余额', + }, review_time: { type: DATE, allowNull: true, @@ -93,6 +569,11 @@ module.exports = app => { allowNull: true, comment: '解除人', }, + initiator_subject_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '发起方主体ID(wms_store.id)', + }, created_at: { type: DATE, allowNull: false, @@ -119,10 +600,36 @@ module.exports = app => { }, comment: '仓库备注', }, - use_status: { + policy_config: { + type: JSON_TYPE, + allowNull: true, + defaultValue: null, + comment: '货主在仓库下的固定策略配置(JSON)', + get() { + return normalizePolicyConfig(this.getDataValue('policy_config'), { + fieldName: 'policy_config', + allowEmpty: true, + sanitizeOnly: true, + }); + }, + set(value) { + this.setDataValue('policy_config', normalizePolicyConfig(value, { + fieldName: 'policy_config', + allowEmpty: true, + })); + }, + }, + warehouse_use_status: { type: INTEGER(1), allowNull: false, - comment: '使用状态,0-不可用,1-可用(SKU可见,货主可见,即使解约了)', + defaultValue: 1, + comment: '仓库侧使用状态:0-不可用,1-可用', + }, + store_use_status: { + type: INTEGER(1), + allowNull: false, + defaultValue: 1, + comment: '货主侧使用状态:0-不可用,1-可用', }, }, { tableName: 'wms_store_warehouse', @@ -179,7 +686,7 @@ module.exports = app => { // 定义关联关系 StoreWarehouse.associate = function() { - const { Store, Account, StockWarehouse, Receiving } = app.model; + const { Store, Account, StockWarehouse, Receiving, StoreWarehousePrintQuantityLog } = app.model; // 授权关系属于商家 StoreWarehouse.belongsTo(Store, { @@ -209,10 +716,12 @@ module.exports = app => { as: 'reviewer', }); + // store_id 在业务上需要与 warehouse_id 联合约束,模型层不声明单列外键约束。 StoreWarehouse.hasMany(StockWarehouse, { foreignKey: 'store_id', targetKey: 'store_id', as: 'store_stock', + constraints: false, }); // 解除人 @@ -221,10 +730,134 @@ module.exports = app => { targetKey: 'id', as: 'end_user', }); + // receiving 同样依赖 store_id + warehouse_id 的复合语义。 StoreWarehouse.hasMany(Receiving, { foreignKey: 'store_id', as: 'receiving', + constraints: false, }); + + StoreWarehouse.hasMany(StoreWarehousePrintQuantityLog, { + foreignKey: 'contract_id', + sourceKey: 'id', + as: 'print_quantity_logs', + constraints: false, + }); + }; + + StoreWarehouse.getPolicyConfigFieldList = function() { + 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 || ''), + })), + stockout_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); + }; + + /** + * 统一构造复合键语义的 where 条件,避免 service 侧重复散落。 + * @param {Object} options 配置项 + * @param {number} [options.warehouseId] 仓库ID + * @param {number} [options.storeId] 货主ID + * @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约 + * @return {Object} 组装后的 where 条件对象 + */ + StoreWarehouse.buildScopedWhere = function(options = {}) { + const { + warehouseId, + storeId, + warehouseUseStatus = 1, + } = options; + + const where = { + warehouse_use_status: warehouseUseStatus, + }; + + if (warehouseId !== undefined && warehouseId !== null) { + where.warehouse_id = warehouseId; + } + + if (storeId !== undefined && storeId !== null) { + where.store_id = storeId; + } + + return where; + }; + + /** + * 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。 + * @param {Object} options 配置项 + * @param {number} [options.warehouseId] 仓库ID + * @param {number} [options.storeId] 货主ID + * @param {boolean} [options.required=false] 是否使用 INNER JOIN + * @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约 + * @param {Array} [options.attributes] 需要查询的字段 + * @return {Object} Sequelize include 对象 + */ + StoreWarehouse.buildStoreStockInclude = function(options = {}) { + const { + warehouseId, + storeId, + required = false, + warehouseUseStatus = 1, + attributes = [ 'store_id', 'store_remask' ], + } = options; + + return { + model: this, + as: 'store_stock', + attributes, + where: this.buildScopedWhere({ + warehouseId, + storeId, + warehouseUseStatus, + }), + required, + }; }; // 实例方法 - 检查授权是否有效 diff --git a/app/model/store_warehouse_print_quantity_log.js b/app/model/store_warehouse_print_quantity_log.js new file mode 100644 index 0000000..4417657 --- /dev/null +++ b/app/model/store_warehouse_print_quantity_log.js @@ -0,0 +1,175 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, TEXT, DATE, INTEGER } = app.Sequelize; + + const StoreWarehousePrintQuantityLog = app.model.define('store_warehouse_print_quantity_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + contract_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '签约关系ID,对应 wms_store_warehouse.id', + references: { + model: 'store_warehouse', + key: 'id', + }, + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID,对应 wms_store.id', + references: { + model: 'store', + key: 'id', + }, + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID,对应 wms_store.id', + references: { + model: 'store', + key: 'id', + }, + }, + change_type: { + type: STRING(50), + allowNull: false, + comment: '变更类型,如 manual_adjust / order_deduct', + }, + business_type: { + type: STRING(50), + allowNull: true, + comment: '业务来源类型,如 order_express', + }, + business_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '业务关联ID,预留关联 wms_order_express.id', + }, + change_quantity: { + type: BIGINT(20), + allowNull: false, + comment: '本次变更数量,整数,可正可负', + }, + balance_before: { + type: INTEGER(11), + allowNull: false, + comment: '本次变更数量,整数,可正可负', + }, + balance_after: { + type: INTEGER(11), + allowNull: false, + comment: '变更后余额', + }, + reason: { + type: TEXT, + allowNull: true, + comment: '变更缘由;人工调整时必填', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人账号ID', + }, + created_by: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人账号ID', + }, + 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_store_warehouse_print_quantity_log', + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: false, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '货主-仓库签约面单余额变更记录表', + indexes: [ + { + name: 'idx_sw_print_qty_log_contract_id', + fields: [ 'contract_id', 'id' ], + }, + { + name: 'idx_sw_print_qty_log_store_warehouse', + fields: [ 'store_id', 'warehouse_id' ], + }, + { + name: 'idx_sw_print_qty_log_business', + fields: [ 'business_type', 'business_id' ], + }, + { + name: 'idx_sw_print_qty_log_change_type', + fields: [ 'change_type' ], + }, + { + name: 'idx_sw_print_qty_log_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + StoreWarehousePrintQuantityLog.associate = function() { + const { StoreWarehouse, Store, Account, OrderExpress } = app.model; + + StoreWarehousePrintQuantityLog.belongsTo(StoreWarehouse, { + foreignKey: 'contract_id', + targetKey: 'id', + as: 'contract', + }); + + StoreWarehousePrintQuantityLog.belongsTo(Store, { + foreignKey: 'store_id', + targetKey: 'id', + as: 'store', + }); + + StoreWarehousePrintQuantityLog.belongsTo(Store, { + foreignKey: 'warehouse_id', + targetKey: 'id', + as: 'warehouse', + }); + + StoreWarehousePrintQuantityLog.belongsTo(Account, { + foreignKey: 'operator_id', + targetKey: 'id', + as: 'operator', + constraints: false, + }); + + StoreWarehousePrintQuantityLog.belongsTo(Account, { + foreignKey: 'created_by', + targetKey: 'id', + as: 'creator', + constraints: false, + }); + + StoreWarehousePrintQuantityLog.belongsTo(OrderExpress, { + foreignKey: 'business_id', + targetKey: 'id', + as: 'order_express', + constraints: false, + }); + }; + + return StoreWarehousePrintQuantityLog; +}; diff --git a/app/model/user_oauth.js b/app/model/user_oauth.js new file mode 100644 index 0000000..99cc5bf --- /dev/null +++ b/app/model/user_oauth.js @@ -0,0 +1,162 @@ +'use strict'; + +/** + * 用户第三方授权表模型。 + * 保存用户通过第三方厂商(微信等)OAuth 登录后的授权信息与令牌信息。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, TINYINT, DATE } = app.Sequelize; + + const UserOauth = app.model.define('userOauth', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + user_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '用户ID(关联 account.id)', + }, + app_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '微信应用ID(关联 wms_wechat_app.id),用于取对应应用 token 处理', + }, + provider: { + type: STRING(50), + allowNull: false, + comment: '厂商,如 wechat/mini_program', + }, + platform: { + type: STRING(50), + allowNull: true, + comment: '平台,如 h5/app/mp', + }, + unionid: { + type: STRING(50), + allowNull: true, + comment: '厂商统一ID(同一厂商跨应用唯一,部分平台无)', + }, + openid: { + type: STRING(50), + allowNull: false, + comment: '平台内唯一ID', + }, + nickname: { + type: STRING(255), + allowNull: true, + comment: '昵称', + }, + sex: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '性别:0=未知,1=男,2=女', + }, + country: { + type: STRING(50), + allowNull: true, + comment: '国家', + }, + province: { + type: STRING(50), + allowNull: true, + comment: '省', + }, + city: { + type: STRING(50), + allowNull: true, + comment: '市', + }, + headimgurl: { + type: STRING(500), + allowNull: true, + comment: '头像URL', + }, + login_time: { + type: INTEGER(11), + allowNull: true, + comment: '最近登录时间(unix秒级时间戳)', + }, + login_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '累计登录次数', + }, + expire_in: { + type: INTEGER(11), + allowNull: true, + comment: '令牌过期周期(秒)', + }, + expire_time: { + type: INTEGER(11), + allowNull: true, + comment: '令牌过期时间(unix秒级时间戳)', + }, + session_key: { + type: STRING(45), + allowNull: true, + comment: '会话密钥(微信小程序登录态)', + }, + refresh_token: { + type: STRING(110), + allowNull: true, + comment: '刷新令牌', + }, + access_token: { + type: STRING(110), + allowNull: true, + comment: '访问令牌', + }, + login_code: { + type: STRING(128), + allowNull: true, + comment: '登录码({uuid,id_6} JSON 的 base64,一次性消费)', + }, + agreement_version_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '协议版本ID(关联 wms_wechat_agreement_version.id,loginByCode 时自动更新到最新)', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_user_oauth', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '用户第三方授权表', + indexes: [ + { + unique: true, + fields: [ 'app_id', 'provider', 'openid' ], + name: 'uk_app_provider_openid', + }, + { + unique: true, + fields: [ 'login_code' ], + name: 'uk_login_code', + }, + { + fields: [ 'user_id' ], + name: 'idx_user_id', + }, + ], + }); + + return UserOauth; +}; diff --git a/app/model/video_record_request.js b/app/model/video_record_request.js new file mode 100644 index 0000000..a1b523a --- /dev/null +++ b/app/model/video_record_request.js @@ -0,0 +1,155 @@ +'use strict'; + +/** + * 视频补录请求记录表模型(wms_video_record_request)。 + * + * 站内信查询打包视频 / 退件拆包视频时发现"视频不可用"(无视频记录或全部 failed), + * 登记一条补录请求(状态机 pending → requested → recording → completed / failed), + * 同时向录制服务推送强制录制;后续查询命中可用视频时由业务层回写 completed + video_url。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, DATE, ENUM, TINYINT } = app.Sequelize; + + const VideoRecordRequest = app.model.define('video_record_request', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '货主ID,0=未知', + }, + biz_type: { + type: ENUM('pack', 'unpack'), + allowNull: false, + comment: '业务类型:pack-打包视频 unpack-退件拆包视频', + }, + biz_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '业务ID:pack=wms_pack_task.id,unpack=wms_return_unpack.id', + }, + waybill_code: { + type: STRING(64), + allowNull: true, + comment: '触发查询的运单号', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '触发查询的群ID(站内信外部群ID,回信必填)', + }, + group_name: { + type: STRING(100), + allowNull: true, + comment: '触发查询的群名称', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '触发查询的用户ID(站内信外部用户ID,回信必填)', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '触发查询的用户名称', + }, + source: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '触发来源:inbox-站内信查询', + }, + status: { + type: ENUM('pending', 'requested', 'recording', 'completed', 'failed'), + allowNull: false, + defaultValue: 'pending', + comment: '状态机:pending-待推送 requested-已推送 recording-录制中 completed-已完成 failed-失败', + }, + request_count: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '推送录制服务次数', + }, + last_request_at: { + type: DATE, + allowNull: true, + comment: '最近一次请求录制服务时间(含推送失败)', + }, + print_computer_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '录制电脑ID,关联 wms_print_computer.id', + }, + request_error: { + type: STRING(500), + allowNull: true, + comment: '推送失败原因(无录制电脑/电脑不在线/打印服务异常)', + }, + video_url: { + type: STRING(500), + allowNull: true, + comment: '录制完成后回写的视频地址', + }, + is_notified: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '录制结果是否已通知查询方:0=未通知,1=已通知', + }, + notified_at: { + type: DATE, + allowNull: true, + comment: '录制结果通知时间', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_video_record_request', + comment: '视频补录请求记录表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + indexes: [ + { name: 'idx_warehouse_biz', fields: [ 'warehouse_id', 'biz_type', 'biz_id' ] }, + { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, + { name: 'idx_status_notified_last_request', fields: [ 'status', 'is_notified', 'last_request_at' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return VideoRecordRequest; +}; diff --git a/app/model/warehouse_front_config.js b/app/model/warehouse_front_config.js new file mode 100644 index 0000000..ea32e5d --- /dev/null +++ b/app/model/warehouse_front_config.js @@ -0,0 +1,264 @@ +'use strict'; + +/** + * 仓库前端个性化配置模型(仓库伪独立部署,单表)。 + * - 每仓库一行(一仓一域一证书):保存仓库前端 Logo / 标题 / 登录页图 / + * 主题等个性化配置,以及证书元信息与证书 PEM 内容(cert_pem / cert_key,由定时 + * 任务读取后写文件部署,禁止写入日志/接口响应)。 + * - sync_status 状态机:0-待同步,1-同步成功,2-同步失败; + * 管理后台保存后置为待同步,由定时任务同步到 nginx 后回写状态。 + * - 证书启用/停用由整行删除或 sync_status 表达;证书到期由 cert_expire_at + * 判断,不单独保留证书 status 列。 + * - domain_status 状态机:0-未验证,1-已验证(DNS TXT 校验通过),2-验证失败; + * 未验证/验证失败的域名禁止上传证书与对外公共拉取,管理后台设置域名后回落到 0。 + * - 两阶段域名切换(方案 B):生效域名 domain 只在 DNS TXT 校验通过时由 + * frontConfig.promotePendingDomain 切换;frontConfig.setDomain 只把新域名登记在 + * pending_domain(+ pending_verify_host/token 校验码),旧域名全程可用(不会出现 + * 「页面能打开但公共配置 404」的中间态);提升时旧域名写入 retired_domain 下线队列 + * (由外部证书脚本删除其 nginx 配置与证书文件后置 NULL)、清空证书 5 列并重置同步 4 列 + * (域名已变,证书必须重新上传)。 + * - domain 唯一索引(uk_domain)为 MySQL 可空列唯一索引:允许多个 NULL, + * 应用层在写入非空 domain 前必须做唯一性校验,不能依赖数据库约束报错。 + * - store_id 唯一索引(uk_store_id):每仓一行,由数据库层保证。 + * - 不启用 paranoid:配置为"每仓库一行"的元数据,删除语义由业务层 + * (清空/停用配置)表达,表结构不含 deleted_at 列。 + * + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, TINYINT, DATE, TEXT, JSON: JSON_TYPE } = app.Sequelize; + + const WarehouseFrontConfig = app.model.define('warehouse_front_config', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'store', + key: 'id', + }, + comment: '仓库ID,关联 wms_store.id(is_warehouse=1),每仓一行', + }, + domain: { + type: STRING(100), + allowNull: true, + comment: '仓库自持域名;可空列唯一索引允许多个 NULL,非空值唯一性需应用层校验', + }, + domain_status: { + type: TINYINT, + allowNull: false, + defaultValue: 0, + validate: { + isIn: { + args: [[ 0, 1, 2 ]], + msg: '域名验证状态不合法:0-未验证,1-已验证,2-验证失败', + }, + }, + comment: '域名验证状态:0-未验证,1-已验证,2-验证失败', + }, + domain_verify_host: { + type: STRING(255), + allowNull: true, + comment: '待校验 TXT 记录主机名(wmsv-<随机码>.<域名>)', + }, + domain_verify_token: { + type: STRING(64), + allowNull: true, + comment: '待校验 TXT 记录值(32 位 hex)', + }, + domain_verified_at: { + type: DATE, + allowNull: true, + comment: '域名验证通过时间', + }, + domain_verify_attempts: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '域名验证尝试次数', + }, + domain_last_error: { + type: STRING(500), + allowNull: true, + comment: '最近一次域名验证失败原因', + }, + pending_domain: { + type: STRING(100), + allowNull: true, + comment: '待验证域名:setDomain 只登记到本列,TXT 校验通过后才提升为生效域名 domain', + }, + pending_verify_host: { + type: STRING(255), + allowNull: true, + comment: '待验证域名的 TXT 记录主机名(wmsv-<随机码>.<待验证域名>)', + }, + pending_verify_token: { + type: STRING(64), + allowNull: true, + comment: '待验证域名的 TXT 记录值(32 位 hex)', + }, + pending_verify_attempts: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '待验证域名校验尝试次数', + }, + pending_last_error: { + type: STRING(500), + allowNull: true, + comment: '待验证域名最近一次失败原因', + }, + pending_created_at: { + type: DATE, + allowNull: true, + comment: '发起域名切换的时间', + }, + retired_domain: { + type: STRING(100), + allowNull: true, + comment: '待下线旧域名:域名提升时写入,外部证书脚本删除其 nginx 配置与证书文件后置 NULL', + }, + retired_at: { + type: DATE, + allowNull: true, + comment: '旧域名进入下线队列的时间', + }, + title: { + type: STRING(100), + allowNull: true, + comment: '站点标题', + }, + logo_url: { + type: STRING(255), + allowNull: true, + comment: 'Logo地址', + }, + favicon_url: { + type: STRING(255), + allowNull: true, + comment: '站点 favicon 图标地址', + }, + login_bg_url: { + type: STRING(255), + allowNull: true, + comment: '登录页背景图地址', + }, + theme: { + type: JSON_TYPE, + allowNull: true, + defaultValue: null, + comment: '主题配置JSON(颜色/布局等)', + }, + cert_path: { + type: STRING(500), + allowNull: true, + comment: '证书文件路径(只存路径不存内容)', + }, + cert_pem: { + type: TEXT, + allowNull: true, + comment: '证书 PEM 内容(私钥不在内);内容仅由定时任务读取,禁止写入日志/接口响应', + }, + key_path: { + type: STRING(500), + allowNull: true, + comment: '私钥文件路径(只存路径不存内容)', + }, + cert_key: { + type: TEXT, + allowNull: true, + comment: '私钥 PEM 内容;内容仅由定时任务读取,禁止写入日志/接口响应', + }, + cert_expire_at: { + type: DATE, + allowNull: true, + comment: '证书到期时间', + }, + sync_status: { + type: TINYINT, + allowNull: false, + defaultValue: 0, + validate: { + isIn: { + args: [[ 0, 1, 2 ]], + msg: '同步状态不合法:0-待同步,1-同步成功,2-同步失败', + }, + }, + comment: '同步状态:0-待同步,1-同步成功,2-同步失败', + }, + sync_attempts: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '同步尝试次数', + }, + last_sync_error: { + type: STRING(500), + allowNull: true, + comment: '最近一次同步失败原因', + }, + last_synced_at: { + type: DATE, + allowNull: true, + 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_warehouse_front_config', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '仓库前端个性化配置表(含证书内容与元信息)', + indexes: [ + { + name: 'uk_store_id', + unique: true, + fields: [ 'store_id' ], + }, + { + name: 'uk_domain', + unique: true, + fields: [ 'domain' ], + }, + { + name: 'idx_sync_status', + fields: [ 'sync_status' ], + }, + { + name: 'idx_domain_status', + fields: [ 'domain_status' ], + }, + { + name: 'idx_pending_domain', + fields: [ 'pending_domain' ], + }, + { + name: 'idx_retired_domain', + fields: [ 'retired_domain' ], + }, + ], + }); + + return WarehouseFrontConfig; +}; diff --git a/app/model/warehouse_log.js b/app/model/warehouse_log.js new file mode 100644 index 0000000..7eb67b4 --- /dev/null +++ b/app/model/warehouse_log.js @@ -0,0 +1,111 @@ +// app/model/warehouse_log.js + +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, TEXT, DATE } = app.Sequelize; + + const WarehouseLog = app.model.define('warehouse_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + }, + log_id: { + type: STRING(32), + allowNull: false, + unique: true, + field: 'log_id', + comment: '日志唯一ID(WL-{timestamp}-{random})', + }, + app_key: { + type: STRING(64), + allowNull: true, + field: 'app_key', + comment: 'API 应用 AppKey', + }, + method: { + type: STRING(100), + allowNull: true, + comment: '请求方法名(如 inbox.push)', + }, + warehouse_id: { + type: INTEGER(10), + allowNull: true, + field: 'warehouse_id', + comment: '仓库 ID', + }, + url: { + type: TEXT, + allowNull: true, + comment: '请求 URL', + }, + http_status: { + type: INTEGER(5), + allowNull: true, + field: 'http_status', + comment: 'HTTP 状态码', + }, + body: { + type: TEXT('long'), + allowNull: true, + comment: '请求体(最大 65535 字符)', + }, + result: { + type: TEXT('long'), + allowNull: true, + comment: '响应体(最大 65535 字符)', + }, + use_time: { + type: INTEGER(12), + allowNull: true, + field: 'use_time', + comment: '耗时(毫秒)', + }, + created_at: { + type: DATE, + allowNull: true, + field: 'created_at', + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: true, + field: 'updated_at', + comment: '更新时间', + }, + }, { + tableName: 'wms_warehouse_log', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '仓库开放 API 请求日志表', + indexes: [ + { + name: 'uk_log_id', + unique: true, + fields: [ 'log_id' ], + }, + { + name: 'idx_app_key', + fields: [ 'app_key' ], + }, + { + name: 'idx_method', + fields: [ 'method' ], + }, + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + return WarehouseLog; +}; diff --git a/app/model/wave_batch.js b/app/model/wave_batch.js new file mode 100644 index 0000000..07ce0d1 --- /dev/null +++ b/app/model/wave_batch.js @@ -0,0 +1,201 @@ +// app/model/wave_batch.js +'use strict'; + +module.exports = app => { + const { BIGINT, INTEGER, STRING, TEXT, DATE, TINYINT, BOOLEAN } = app.Sequelize; + + const WaveBatch = app.model.define('wms_wave_batch', { + wave_id: { + type: BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '波次ID', + }, + wave_no: { + type: STRING(50), + allowNull: false, + comment: '波次编号,如WAVE202401001', + }, + wave_type: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '波次类型:1-团购 2-散单', + }, + wave_status: { + type: TINYINT, + allowNull: false, + defaultValue: 0, + comment: '波次状态:-1-已取消 0-自动加团中 1-已就绪 2-已打印 3-拣货中 4-拣货完成 5-复核完成 6-打包完成', + }, + total_orders: { + type: INTEGER, + allowNull: true, + defaultValue: 0, + comment: '总订单数', + }, + processed_orders: { + type: INTEGER, + allowNull: true, + defaultValue: 0, + comment: '已处理订单数', + }, + picking_operator: { + type: STRING(50), + allowNull: true, + comment: '拣货员', + }, + claim_operator: { + type: STRING(50), + allowNull: true, + comment: '领料人', + }, + claim_time: { + type: DATE, + allowNull: true, + comment: '领料时间', + }, + picking_start_time: { + type: DATE, + allowNull: true, + comment: '拣货开始时间', + }, + picking_end_time: { + type: DATE, + allowNull: true, + comment: '拣货结束时间', + }, + print_operator: { + type: STRING(50), + allowNull: true, + comment: '打印员', + }, + print_time: { + type: DATE, + allowNull: true, + comment: '打印时间', + }, + print_count: { + type: INTEGER, + allowNull: true, + defaultValue: 0, + comment: '打印次数', + }, + check_operator: { + type: STRING(50), + allowNull: true, + comment: '校验员', + }, + check_time: { + type: DATE, + allowNull: true, + comment: '校验时间', + }, + check_result: { + type: TINYINT, + allowNull: true, + comment: '校验结果', + }, + recheck_start_time: { + type: DATE, + allowNull: true, + comment: '复核开始时间', + }, + priority: { + type: TINYINT, + allowNull: true, + defaultValue: 5, + comment: '优先级 1-5', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + creator: { + type: STRING(50), + allowNull: false, + comment: '创建人', + }, + create_time: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + item_detail_machine: { + type: TEXT, + allowNull: true, + comment: '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key(TEXT 以容纳多商品订单的长结构标识)', + }, + item_part_type: { + type: STRING(32), + allowNull: true, + comment: '结构来源类型:items_hash/items', + }, + item_part: { + type: STRING(255), + allowNull: true, + comment: '结构主键(items_hash或items摘要)', + }, + distinguish_express: { + type: BOOLEAN, + allowNull: false, + defaultValue: 0, + comment: '是否区分快递 0否1是', + }, + logistics_name: { + type: STRING(128), + allowNull: true, + comment: '快递名称(区分快递时参与匹配)', + }, + item_snapshot_key: { + type: STRING(1024), + allowNull: true, + comment: '结构快照键(多商品订单的快照键,最长 1024)', + }, + }, { + tableName: 'wms_wave_batch', + timestamps: false, + underscored: false, + indexes: [ + { + name: 'idx_wave_status', + fields: [ 'wave_status', 'create_time' ], + }, + { + name: 'uniq_wave_no', + fields: [ 'wave_no' ], + unique: true, + }, + { + name: 'idx_warehouse', + fields: [ 'warehouse_id', 'wave_status' ], + }, + { + name: 'idx_creator', + fields: [ 'creator', 'create_time' ], + }, + { + name: 'idx_wave_fast_group', + fields: [ 'warehouse_id', 'wave_type', 'wave_status', 'item_part_type', 'item_part', 'distinguish_express', 'logistics_name' ], + }, + { + name: 'idx_wave_snapshot_key', + fields: [{ name: 'item_snapshot_key', length: 191 }], + }, + { + name: 'idx_wave_item_machine_prefix', + fields: [{ name: 'item_detail_machine', length: 191 }], + }, + ], + }); + + return WaveBatch; +}; diff --git a/app/model/waybill_allocate_queue.js b/app/model/waybill_allocate_queue.js new file mode 100644 index 0000000..b385541 --- /dev/null +++ b/app/model/waybill_allocate_queue.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * 订单创建后自动分配快递的消费队列模型。 + * + * 订单创建后的异步流程只入队(截单/未审核不入队),由定时任务 + * app/schedule/consume_waybill_allocate_queue.js 按仓库+货主串行批量消费, + * 避免高并发逐单取号时的 InnoDB AB-BA 死锁。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, DATE } = app.Sequelize; + + const WaybillAllocateQueue = app.model.define('waybill_allocate_queue', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID(关联订单分表)', + }, + business_key: { + type: INTEGER(3), + allowNull: false, + defaultValue: 1, + comment: '业务键(与 wms_order_express.business_key 一致)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(消费分组与数据隔离维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '货主ID(消费分组维度)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/processing/done/failed/waiting_oms(waiting_oms=需要回 OMS 取号,等待外部接入,终态不重试)', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可消费时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_waybill_allocate_queue', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单创建后自动分配快递消费队列', + indexes: [ + { + name: 'uk_order_id_business_key', + unique: true, + fields: [ 'order_id', 'business_key' ], + }, + { + name: 'idx_status_id', + fields: [ 'status', 'id' ], + }, + { + name: 'idx_status_updated_at', + fields: [ 'status', 'updated_at' ], + }, + ], + }); + + return WaybillAllocateQueue; +}; diff --git a/app/model/wechat_agreement_version.js b/app/model/wechat_agreement_version.js new file mode 100644 index 0000000..8329a3c --- /dev/null +++ b/app/model/wechat_agreement_version.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * 微信用户须知版本表模型(副表)。 + * 提交一次自动新增版本:version 为数字、同一 appid 内自动 +1;拉取只取最新版本。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, TEXT, DATE } = app.Sequelize; + + const WechatAgreementVersion = app.model.define('wechatAgreementVersion', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + appid: { + type: STRING(64), + allowNull: false, + comment: '小程序AppID(关联 wms_wechat_app.appid)', + }, + content: { + type: TEXT('long'), + allowNull: true, + defaultValue: null, + comment: '用户须知富文本内容', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_wechat_agreement_version', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '微信用户须知版本表(副表,提交一次新增一个版本)', + indexes: [ + { + fields: [ 'appid' ], + name: 'idx_appid', + }, + ], + }); + + return WechatAgreementVersion; +}; diff --git a/app/model/wechat_app.js b/app/model/wechat_app.js new file mode 100644 index 0000000..d65ace8 --- /dev/null +++ b/app/model/wechat_app.js @@ -0,0 +1,203 @@ +'use strict'; + +/** + * 微信开放平台授权小程序表模型。 + * 记录仓库(主体)授权的小程序信息与令牌,供业务按小程序维度调用微信接口。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, TINYINT, TEXT, DATE } = app.Sequelize; + + const WechatApp = app.model.define('wechatApp', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '仓库ID(绑定关系,NULL=已授权待绑定仓库)', + }, + appid: { + type: STRING(64), + allowNull: false, + comment: '小程序AppID', + }, + nickname: { + type: STRING(100), + allowNull: true, + comment: '小程序名称', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '小程序原始ID(gh_xxx)', + }, + head_img: { + type: STRING(500), + allowNull: true, + comment: '小程序头像URL', + }, + authorizer_refresh_token: { + type: STRING(255), + allowNull: true, + comment: '授权方刷新令牌(长期有效,防 Redis 丢失)', + }, + auth_time: { + type: INTEGER(11), + allowNull: true, + comment: '授权时间(unix秒级时间戳)', + }, + func_info: { + type: TEXT, + allowNull: true, + comment: '授权权限集合(JSON 字符串,来自 api_query_auth)', + }, + template_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '当前上传的代码模板ID(wxa/commit 成功后记录)', + }, + user_version: { + type: STRING(64), + allowNull: true, + defaultValue: null, + comment: '当前上传的代码版本号(wxa/commit 成功后记录)', + }, + audit_status: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '代码审核状态:0=未提交,1=审核中,2=审核通过,3=审核驳回', + }, + audit_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '微信审核单ID(wxa/submit_audit 返回的 auditid)', + }, + audit_reason: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '代码审核驳回原因', + }, + principal_name: { + type: STRING(100), + allowNull: true, + defaultValue: null, + comment: '主体名称', + }, + signature: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '小程序账号介绍', + }, + alias: { + type: STRING(100), + allowNull: true, + defaultValue: null, + comment: '微信号(可能为空)', + }, + qrcode_url: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '二维码图片URL', + }, + service_type_id: { + type: TINYINT, + allowNull: true, + defaultValue: null, + comment: '账号类型id(0 普通小程序等)', + }, + verify_type_id: { + type: TINYINT, + allowNull: true, + defaultValue: null, + comment: '认证类型id(-1 未认证,0 微信认证,1 新浪微博认证,3 资质通过未名称认证,4 同3+微博)', + }, + account_status: { + type: TINYINT, + allowNull: true, + defaultValue: null, + comment: '账号状态(1 正常,14 已注销,16 已封禁,18 已告警,19 已冻结)', + }, + register_type: { + type: TINYINT, + allowNull: true, + defaultValue: null, + comment: '小程序注册方式(0 普通,6 法人扫脸创建企业小程序等)', + }, + business_info: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '功能开通状况 JSON', + }, + mini_program_info: { + type: TEXT, + allowNull: true, + defaultValue: null, + comment: '小程序配置信息 JSON(network/categories/visit_status)', + }, + auth_task_id: { + type: STRING(64), + allowNull: true, + defaultValue: null, + comment: '微信认证任务ID(发起认证接口返回)', + }, + auth_task_status: { + type: TINYINT, + allowNull: true, + defaultValue: null, + comment: '认证任务流程状态(task_status 0-15)', + }, + auth_apply_status: { + type: TINYINT, + allowNull: true, + defaultValue: null, + comment: '认证审核单状态(apply_status 0-5)', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + created_at: { + type: DATE, + comment: '创建时间', + }, + updated_at: { + type: DATE, + comment: '更新时间', + }, + }, { + tableName: 'wms_wechat_app', + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + comment: '微信开放平台授权小程序表(仓库绑定)', + indexes: [ + { + unique: true, + fields: [ 'appid' ], + name: 'uk_appid', + }, + { + fields: [ 'warehouse_id' ], + name: 'idx_warehouse_id', + }, + ], + }); + + return WechatApp; +}; diff --git a/app/model/workbench.js b/app/model/workbench.js new file mode 100644 index 0000000..46b69b3 --- /dev/null +++ b/app/model/workbench.js @@ -0,0 +1,100 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, DATE, TINYINT, ENUM, JSON: JSON_TYPE } = app.Sequelize; + + const Workbench = app.model.define('workbench', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '工作台名称(用户自定义)', + }, + status: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + type: { + type: ENUM('personal', 'group'), + allowNull: false, + defaultValue: 'personal', + comment: '工作台类型:personal-个人工作台 group-团体工作台', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + device_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids', + }, + login_code: { + type: STRING(64), + allowNull: true, + comment: '工作台登录码(前缀+随机,64位,全局唯一)', + }, + token: { + type: STRING(64), + allowNull: true, + comment: '工作台令牌(随机64位,绑定后生成)', + }, + token_updated_at: { + type: DATE, + allowNull: true, + comment: '工作台 token 最后更新时间(无 token 时为 NULL)', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_workbench', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '工作台表', + indexes: [ + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'uk_login_code', unique: true, fields: [ 'login_code' ] }, + { name: 'idx_token', fields: [ 'token' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + Workbench.associate = () => { + app.model.Workbench.hasMany(app.model.WorkbenchMember, { + foreignKey: 'workbench_id', + sourceKey: 'id', + as: 'members', + }); + }; + + return Workbench; +}; diff --git a/app/model/workbench_member.js b/app/model/workbench_member.js new file mode 100644 index 0000000..81f019d --- /dev/null +++ b/app/model/workbench_member.js @@ -0,0 +1,71 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, DATE } = app.Sequelize; + + const WorkbenchMember = app.model.define('workbench_member', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + workbench_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '工作台ID,关联 wms_workbench.id', + }, + user_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '账号ID,关联 wms_account.id;非系统账号用户为 NULL', + }, + user_name: { + type: STRING(128), + allowNull: true, + comment: '成员名称快照(非系统账号用户显示名)', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_workbench_member', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '工作台成员/用户登录副表', + indexes: [ + { name: 'idx_workbench_id', fields: [ 'workbench_id' ] }, + { name: 'idx_user_id', fields: [ 'user_id' ] }, + ], + }); + + WorkbenchMember.associate = () => { + app.model.WorkbenchMember.belongsTo(app.model.Workbench, { + foreignKey: 'workbench_id', + targetKey: 'id', + as: 'workbench', + }); + app.model.WorkbenchMember.belongsTo(app.model.Account, { + foreignKey: 'user_id', + targetKey: 'id', + as: 'user', + }); + }; + + return WorkbenchMember; +}; diff --git a/app/router.js b/app/router.js index ec0efb8..a395b88 100644 --- a/app/router.js +++ b/app/router.js @@ -4,14 +4,80 @@ module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); + router.get('/auth/platformOauthCallback', controller.home.platformOauthCallback); + router.get('/auth/platformOauthBind', controller.home.platformOauthBind); + router.get('/query/pddCode/:code', controller.home.queryPddCode); + + // 微信开放平台第三方平台授权事件接收(GET=URL验证,POST=事件推送) + router.get('/Authorization', controller.wechatOpen.authorization); + router.post('/Authorization', controller.wechatOpen.authorization); + + // 授权方(小程序/公众号)消息与事件推送(GET=URL验证,POST=事件推送) + router.get('/events/appid/:appid', controller.wechatOpen.events); + router.post('/events/appid/:appid', controller.wechatOpen.events); + + // 内部网关接口 + router.post('/internal/v1/gateway', controller.gateway.internal); + + // 奇门接口 router.post('/qimen', controller.home.qimen); - router.post('/api/warehouse', controller.home.warehouse); - router.post('/api/store', controller.home.store); - router.post('/api/v1', controller.home.v1); + + // 系统接口 PDA/WEB 统一入口 router.post('/system', controller.home.system); - router.post('/api/v2', controller.apiV2.index); + + + // 仅开发环境可访问的内部api文档 + if (app.config.env === 'local') { + // api文档相关 + router.get('/api/docs', controller.docs.list); + router.get('/api/docs/:docName/raw', controller.docs.raw); + router.get('/api/docs/:docName/changes', controller.docs.changes); + router.get('/api/docs/:docName', controller.docs.detail); + + // 独立 docs 目录挂载 — 首页 + router.get('/docs', controller.docs.docsIndex); + } + + // OpenAPI 文档 — 所有环境均可访问,必须在通配路由之前注册 + router.get('/docs/api/openapi', controller.docs.openapi); + + // Warehouse 开放 API 文档 — 所有环境均可访问 + router.get('/docs/api/warehouse', controller.docs.warehouse); + + // OpenAPI 回调测试 — 所有环境均可访问的独立调试页面 + router.get('/docs/api/openapi/callback-test', controller.openapiCallback.testPage); + + // OpenAPI 出站回调文档 — 所有环境均可访问 + router.get('/docs/api/openapi_callback', controller.docs.openapiCallbackEvents); + + // 仅开发环境可访问的 docs 通配路由(静态文件),必须在 /docs/api/openapi 之后注册 + if (app.config.env === 'local') { + router.get('/docs/:relPath(.*)', controller.docs.docsFile); + } + + // OpenAPI 入口 + router.post('/openapi', controller.openapi.index); + + // 仓库 OpenAPI 入口 + router.post('/warehouse', controller.warehouse.index); + + // 打印模板 router.get('/template/xml/:id', controller.template.xml); + + + // 打印台设置 router.get('/auth/printSetting/:code', controller.auth.printerSetting); - router.get('/testSendData', controller.home.testSendData); router.post('/auth/printSetting/', controller.auth.printerSetting); + + // 临时 fileWriter 消费入口 + router.get('/__temp/file-writer/consume', controller.tempFileWriter.consume); + + // 测试接口 + router.get('/testSendData', controller.home.testSendData); + + // 扫描报文接收(联调入口,POST) + router.post('/scan', controller.home.scan); + + // IM交互入口 + router.post('/im', controller.im.index); }; diff --git a/app/schedule/archive_dispatch_orders_to_history.js b/app/schedule/archive_dispatch_orders_to_history.js new file mode 100644 index 0000000..27909cc --- /dev/null +++ b/app/schedule/archive_dispatch_orders_to_history.js @@ -0,0 +1,384 @@ +// app/schedule/archive_dispatch_orders_to_history.js +'use strict'; + +/** + * 配送表订单归档到历史表定时任务。 + * + * 默认每日凌晨 06:00:00(cron:秒 分 时 日 月 周)在单 worker 中执行一次, + * 把 `wms_order_delivery_{仓库}_dispatch` 中创建时间距今超过 4 个月 + * (或迁移进配送表时间距今超过 3 个月)的订单,连同商品明细一起归档到 + * `_history` 分表,并同步更新订单索引表 `wms_order_id_location_{仓库}` 的位置指针。 + * + * cron / 开关从 config.orderDeliveryArchive 读取(config.default.js 提供默认值), + * 本地环境可在 config.local.js 覆盖为短间隔以便快速验证,不影响生产 06:00 触发时间。 + * + * 中断与重跑安全(本任务每日只跑一轮,必须具备"断了也能接着跑"的性质): + * 1. 单批一个事务:写入历史表 + 更新位置指针 + 删除源行 全部成功或全部回滚, + * 不会出现"历史表有数据但配送表没删"的中间态; + * 2. 已迁移的行在提交时即从配送表删除,重新执行时查询不会命中 → 天然幂等续跑; + * 3. 单批失败(死锁等重试耗尽)只跳过该批并推进游标,不中断整轮,未迁移的行留待下一轮; + * 4. 跨进程互斥用 Redis 锁(NX + TTL),进程被杀后锁到期自动释放,下一轮可继续; + * 5. 每批进度写入 Redis(progress key),日志与进度缓存均可观察"跑到哪、迁了多少"。 + */ + + +/** 执行记录缓存 key(最近一次执行) */ +const EXECUTION_LOG_CACHE_KEY = 'schedule:archive_dispatch_to_history:last_execution'; +/** 执行记录缓存 TTL(秒) */ +const EXECUTION_LOG_CACHE_TTL = 300; +/** 执行历史缓存 key(保留最近 N 次) */ +const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:archive_dispatch_to_history:history'; +/** 执行历史保留条数 */ +const EXECUTION_LOG_HISTORY_MAX = 20; +/** 执行历史缓存 TTL(秒) */ +const EXECUTION_LOG_HISTORY_TTL = 86400; +/** 跨进程互斥锁 key */ +const LOCK_CACHE_KEY = 'schedule:archive_dispatch_to_history:lock'; +/** 进度缓存 key(供人工观察断点位置) */ +const PROGRESS_CACHE_KEY = 'schedule:archive_dispatch_to_history:progress'; +/** 进度缓存 TTL(秒):保留 2 天,便于次日对比上一轮跑到哪里 */ +const PROGRESS_CACHE_TTL = 2 * 24 * 60 * 60; +/** 默认 cron:每日凌晨 06:00 */ +const DEFAULT_CRON = '0 0 6 * * *'; +/** 默认互斥锁 TTL(秒),需覆盖单轮最长执行时间 */ +const DEFAULT_LOCK_TTL_SECONDS = 30 * 60; + +/** + * 获取 Redis cache 客户端。 + * + * @param {Object} app Egg 应用实例。 + * @return {Object|null} Redis 客户端或 null。 + */ +function getCacheRedisClient(app) { + if (!app || !app.redis || typeof app.redis.get !== 'function') { + return null; + } + + try { + return app.redis.get('cache') || null; + } catch (error) { + return null; + } +} + +/** + * 获取互斥锁(SET NX EX)。 + * + * @param {Object} ctx Egg 上下文。 + * @param {number} ttlSeconds 锁 TTL(秒)。 + * @return {Promise} 是否获取成功;Redis 不可用时返回 true(退化为进程内防重入)。 + */ +async function acquireLock(ctx, ttlSeconds) { + const redis = getCacheRedisClient(ctx.app); + + if (!redis || typeof redis.set !== 'function') { + ctx.logger.warn('[archive-dispatch-to-history] Redis 不可用,跨进程互斥降级为进程内防重入'); + return true; + } + + try { + const result = await redis.set(LOCK_CACHE_KEY, String(process.pid || ''), 'EX', ttlSeconds, 'NX'); + return result === 'OK'; + } catch (error) { + ctx.logger.warn(`[archive-dispatch-to-history] 获取互斥锁失败(按未加锁继续): ${error.message}`); + return true; + } +} + +/** + * 释放互斥锁。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ +async function releaseLock(ctx) { + const redis = getCacheRedisClient(ctx.app); + + if (!redis || typeof redis.del !== 'function') { + return; + } + + try { + await redis.del(LOCK_CACHE_KEY); + } catch (error) { + ctx.logger.warn(`[archive-dispatch-to-history] 释放互斥锁失败(等待 TTL 过期): ${error.message}`); + } +} + +/** + * 写入进度缓存。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} payload 进度内容。 + * @return {Promise} 无返回值。 + */ +async function writeProgress(ctx, payload) { + try { + if (ctx.app && typeof ctx.app.setCacheAsync === 'function') { + await ctx.app.setCacheAsync(PROGRESS_CACHE_KEY, { + ...payload, + updated_at: new Date().toISOString(), + }, PROGRESS_CACHE_TTL); + } + } catch (error) { + ctx.logger.warn(`[archive-dispatch-to-history] 写入进度缓存失败: ${error.message}`); + } +} + +/** + * 读取上一轮进度缓存(用于识别"上一轮被中断")。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 上一轮进度。 + */ +async function readProgress(ctx) { + try { + if (ctx.app && typeof ctx.app.getCacheAsync === 'function') { + const cached = await ctx.app.getCacheAsync(PROGRESS_CACHE_KEY); + return cached && typeof cached === 'object' ? cached : null; + } + } catch (error) { + ctx.logger.warn(`[archive-dispatch-to-history] 读取进度缓存失败: ${error.message}`); + } + + return null; +} + +/** + * 将本次执行日志写入缓存。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} 无返回值。 + */ +async function writeExecutionLogToCache(ctx, logEntry) { + try { + if (ctx.app && typeof ctx.app.setCacheAsync === 'function') { + await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL); + } + } catch (error) { + ctx.logger.warn(`[archive-dispatch-to-history] 写入执行日志缓存失败: ${error.message}`); + } +} + +/** + * 将本次执行日志追加到历史记录缓存(保留最近 N 次)。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} 无返回值。 + */ +async function appendExecutionHistory(ctx, logEntry) { + try { + if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') { + return; + } + + const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY); + const history = Array.isArray(rawHistory) ? rawHistory : []; + history.unshift(logEntry); + await ctx.app.setCacheAsync( + EXECUTION_LOG_HISTORY_CACHE_KEY, + history.slice(0, EXECUTION_LOG_HISTORY_MAX), + EXECUTION_LOG_HISTORY_TTL + ); + } catch (error) { + ctx.logger.warn(`[archive-dispatch-to-history] 写入执行历史缓存失败: ${error.message}`); + } +} + +/** + * 提取错误详情,方便定位问题位置。 + * + * @param {Error} error 错误对象。 + * @return {Object} 错误详情。 + */ +function extractErrorDetail(error) { + if (!error) return {}; + + const detail = { + name: error.name || '', + message: error.message || '', + code: error.code || '', + }; + + if (error.parent) { + detail.parent = { + name: error.parent.name || '', + message: error.parent.message || '', + code: error.parent.code || '', + sql: error.parent.sql || '', + }; + } + + if (error.stack) { + detail.stack_top = error.stack.split('\n').slice(0, 4).map(line => line.trim()); + } + + return detail; +} + +/** + * 每日凌晨 06:00 归档配送表超期订单到历史表。 + * + * @param {Object} app Egg 应用实例。 + * @return {Object} 定时任务定义(含 schedule 与 task)。 + */ +module.exports = app => { + const archiveConfig = (app.config && app.config.orderDeliveryArchive) || {}; + const archiveCron = typeof archiveConfig.cron === 'string' && archiveConfig.cron + ? archiveConfig.cron + : DEFAULT_CRON; + const lockTtlSeconds = Number(archiveConfig.lockTtlSeconds) > 0 + ? Number(archiveConfig.lockTtlSeconds) + : DEFAULT_LOCK_TTL_SECONDS; + + return { + schedule: { + cron: archiveCron, + type: 'worker', + immediate: false, + disable: archiveConfig.enable === false, + }, + + /** + * 执行配送表订单归档。 + * + * 任务失败只记录错误日志,不向上抛出,避免 schedule 崩溃; + * 未归档完成的订单保留在配送表,下一轮(或人工重跑)继续。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + const scheduleName = 'archive_dispatch_orders_to_history'; + + if (ctx.app._archiveDispatchOrdersToHistoryRunning) { + ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`); + return; + } + + const previousProgress = await readProgress(ctx); + if (previousProgress && previousProgress.status === 'running') { + ctx.logger.warn( + `[${scheduleName}] 检测到上一轮未正常结束(status=running, started_at=${previousProgress.started_at || '-'}),本轮按断点续跑:已迁移订单已从配送表移除,不会重复处理` + ); + } + + const lockAcquired = await acquireLock(ctx, lockTtlSeconds); + if (!lockAcquired) { + ctx.logger.info(`[${scheduleName}] 未获取到互斥锁,判定其他进程正在执行,本轮跳过`); + return; + } + + ctx.app._archiveDispatchOrdersToHistoryRunning = true; + + const startedAt = Date.now(); + const startedAtIso = new Date(startedAt).toISOString(); + let status = 'success'; + let errorMessage = ''; + let errorDetail = null; + let result = null; + + await writeProgress(ctx, { + status: 'running', + started_at: startedAtIso, + trigger: 'schedule', + pid: process.pid, + }); + + try { + result = await ctx.service.systems.orderDeliveryArchive.archiveDispatchOrdersToHistory({}, { + onBatch: async batch => { + await writeProgress(ctx, { + status: 'running', + started_at: startedAtIso, + trigger: 'schedule', + pid: process.pid, + warehouse_id: batch.warehouseId, + batch_index: batch.batchIndex, + last_id: batch.lastId, + total_selected: batch.summary.selectedCount, + total_archived: batch.summary.archivedCount, + total_items_archived: batch.summary.itemsArchivedCount, + failed_batches: batch.summary.failedBatches, + }); + }, + }); + + if (result.totalFailedBatches > 0) { + status = 'partial_failure'; + errorMessage = `failedBatches=${result.totalFailedBatches}, failedRows=${result.totalFailedCount}`; + ctx.logger.warn( + `[${scheduleName}] 本轮存在 ${result.totalFailedBatches} 个失败批次(共 ${result.totalFailedCount} 条订单未迁移),已跳过并保留在配送表,下一轮继续` + ); + } + + if (result.backlogRemaining) { + status = status === 'success' ? 'partial_budget_exhausted' : status; + ctx.logger.warn( + `[${scheduleName}] 单轮时长上限用尽,仍有仓库未处理完(elapsedMs=${result.elapsedMs}),剩余订单将在下一轮继续归档` + ); + } + + ctx.logger.info( + `[${scheduleName}] 本轮完成 archived=${result.totalArchived} alreadyArchived=${result.totalAlreadyArchived} itemsArchived=${result.totalItemsArchived} selected=${result.totalSelected} failedBatches=${result.totalFailedBatches} elapsedMs=${result.elapsedMs}` + ); + } catch (error) { + status = 'error'; + errorMessage = error.message; + errorDetail = extractErrorDetail(error); + ctx.logger.error(`[${scheduleName}] 归档失败: ${error.message}`, errorDetail); + } finally { + ctx.app._archiveDispatchOrdersToHistoryRunning = false; + await releaseLock(ctx); + } + + const logEntry = { + executed_at: new Date().toISOString(), + duration_ms: Date.now() - startedAt, + status, + error_message: errorMessage, + error_detail: errorDetail, + total_selected: result ? result.totalSelected : 0, + total_archived: result ? result.totalArchived : 0, + total_already_archived: result ? result.totalAlreadyArchived : 0, + total_items_archived: result ? result.totalItemsArchived : 0, + total_failed_batches: result ? result.totalFailedBatches : 0, + total_failed_count: result ? result.totalFailedCount : 0, + backlog_remaining: result ? Boolean(result.backlogRemaining) : false, + warehouse_ids: result ? result.warehouseIds : [], + warehouses: result + ? result.results.map(item => ({ + warehouse_id: item.warehouseId, + batches: item.batches, + archived: item.archivedCount, + items_archived: item.itemsArchivedCount, + failed_batches: item.failedBatches, + last_id: item.lastId, + stop_reason: item.stopReason, + })) + : [], + }; + + await writeExecutionLogToCache(ctx, logEntry); + await appendExecutionHistory(ctx, logEntry); + await writeProgress(ctx, { + status, + started_at: startedAtIso, + finished_at: new Date().toISOString(), + trigger: 'schedule', + pid: process.pid, + elapsed_ms: logEntry.duration_ms, + total_archived: logEntry.total_archived, + total_failed_batches: logEntry.total_failed_batches, + backlog_remaining: logEntry.backlog_remaining, + warehouses: logEntry.warehouses, + }); + + ctx.logger.info( + `[${scheduleName}] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY} history=${EXECUTION_LOG_HISTORY_CACHE_KEY} progress=${PROGRESS_CACHE_KEY}` + ); + }, + }; +}; diff --git a/app/schedule/auto_finish_pack_task.js b/app/schedule/auto_finish_pack_task.js new file mode 100644 index 0000000..e443059 --- /dev/null +++ b/app/schedule/auto_finish_pack_task.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * 打包任务自动结束定时任务。 + * 每小时在单 worker 中扫描一次 wms_pack_task 表: + * - 扫描所有未结束的任务(status < 2),区分散单(pack_mode=1)/ 团购(pack_mode=2); + * - 按仓库拉取 subject_config 中配置的打包最大时长 + * (散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes,单位分钟); + * - 当 当前时间 - 开始时间 > 配置时长 时自动结束, + * 将 end_time 置为 开始时间 + 上限时长,状态置为已完成(2); + * - 任务结束后同步将该工作台关联摄像头的 OSD 叠加复位为「无任务」。 + */ +module.exports = { + schedule: { + interval: '1h', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行打包任务自动结束任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._autoFinishPackTaskRunning) { + return; + } + + ctx.app._autoFinishPackTaskRunning = true; + + try { + const result = await ctx.service.systems.packTaskAutoFinish.executeAutoFinishPackTasks(); + + ctx.logger.info( + '[auto-finish-pack-task] 本轮扫描 %d 条未结束打包任务(涉及 %d 个仓库),自动结束 %d 条', + result && result.total_scanned || 0, + result && result.warehouse_count || 0, + result && result.auto_finished || 0 + ); + } catch (error) { + ctx.logger.error(`[auto-finish-pack-task] 打包任务自动结束执行失败: ${error.message}`); + } finally { + ctx.app._autoFinishPackTaskRunning = false; + } + }, +}; diff --git a/app/schedule/auto_outbound_order.js b/app/schedule/auto_outbound_order.js new file mode 100644 index 0000000..f52c4bc --- /dev/null +++ b/app/schedule/auto_outbound_order.js @@ -0,0 +1,59 @@ +'use strict'; + +/** + * 自动化出库定时任务。 + * 每分钟在单 worker 中扫描一次:当订单满足仓库配置的自动化出库规则时, + * 自动标记出库并将订单状态更新为已完成,同时写入订单操作日志(ORDER_AUTO_OUTBOUND)。 + * + * 开关与规则(仓库 subject_config): + * - auto_outbound_enabled:是否启用,默认 false(关闭); + * - auto_outbound_rules:规则数组(空数组时不自动出库),每项规则独立判断,任一命中即出库。 + * + * 固定基线条件:已复核(recheck_status='fin')+ 已分配储位(storage_status='fin'), + * 未复核订单一律不自动出库。 + * + * 单条规则可选条件(仅校验这三项): + * 1. 已打包:pack_status = 'fin'(require_pack) + * 2. 已称重:wms_order_express.weighing_weight > 0(require_weigh) + * 3. 已同步:sync_status = 'fin'(require_sync) + * + * 当天订单限制(exclude_same_day_outbound,默认 true,按规则独立生效): + * 开启时,在当天放开时间(same_day_outbound_release_time,默认北京时间 22:00)前, + * 北京时间当天「允许当天出库最后时间」(same_day_outbound_deadline_time,默认 06:00) + * 起复核(recheck_time)的订单不自动出库; + * 到达放开时间后当天复核订单恢复自动出库。关闭则全程不受限制。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行自动化出库任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._autoOutboundRunning) { + return; + } + + ctx.app._autoOutboundRunning = true; + + try { + const result = await ctx.service.systems.orderAutoOutbound.executeAutoOutbound(); + + ctx.logger.info( + `[auto-outbound-order] 本轮自动化出库完成,共处理 ${result && result.totalProcessed || 0} 条订单` + ); + } catch (error) { + ctx.logger.error(`[auto-outbound-order] 自动化出库任务执行失败: ${error.message}`); + } finally { + ctx.app._autoOutboundRunning = false; + } + }, +}; diff --git a/app/schedule/consume_qimen_logs.js b/app/schedule/consume_qimen_logs.js new file mode 100644 index 0000000..329aa90 --- /dev/null +++ b/app/schedule/consume_qimen_logs.js @@ -0,0 +1,77 @@ +'use strict'; + +const path = require('path'); + +/** + * 定时消费奇门日志文件队列,逐条幂等插入数据库。 + * 间隔 30 秒执行,type: worker(仅一个 worker 执行)。 + * 使用 fileWriter.consumeFiles 内置的逐条进度追踪, + * 任一记录插入失败即停止,下次从失败位置重试。 + * 同一 log_id 已落库时视为幂等命中直接跳过,避免唯一索引冲突卡死队列。 + */ +module.exports = { + schedule: { + interval: '30s', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 消费奇门日志队列任务入口。 + * @param {Egg.Context} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + // 防止重入 + if (ctx.app._consumeQimenLogsRunning) return; + ctx.app._consumeQimenLogsRunning = true; + + const fileWriter = ctx.app.fileWriter; + const mysql = ctx.app.mysql.get('wms'); + const progressFilePath = path.join(fileWriter.baseDir, 'qimen-logs', '.consume-progress'); + + try { + const result = await fileWriter.consumeFiles({ + businessName: 'qimen-logs', + progressFilePath, + maxConsumeRecordsPerWindow: 500, + parseJson: true, + onRecord: async record => { + const row = { + log_id: record.log_id || null, + from_key: record.from_key || '', + to_key: record.to_key || '', + method: record.method || '', + sign: record.sign || '', + costomer_id: record.costomer_id || '', + v: record.v || '', + url: record.url || '', + created_at: record.created_at ? new Date(record.created_at) : new Date(), + body: record.body || '', + result: record.result || '', + use_time: record.use_time || 0, + }; + try { + await mysql.insert('wms_qimen_log', row); + } catch (err) { + const isDuplicate = !!err && (err.code === 'ER_DUP_ENTRY' || err.errno === 1062); + if (!isDuplicate) { + throw err; + } + // 同一 log_id 已落库时视为幂等命中,跳过并继续推进消费进度 + ctx.logger.warn(`[consume-qimen-logs] 跳过重复日志 log_id=${row.log_id}`); + } + }, + }); + + if (result.processedCount > 0) { + ctx.logger.info(`[consume-qimen-logs] 消费 ${result.processedCount} 条日志`); + } + } catch (err) { + ctx.logger.error(`[consume-qimen-logs] 消费失败: ${err.message}`); + } finally { + ctx.app._consumeQimenLogsRunning = false; + } + }, +}; diff --git a/app/schedule/consume_warehouse_logs.js b/app/schedule/consume_warehouse_logs.js new file mode 100644 index 0000000..81deece --- /dev/null +++ b/app/schedule/consume_warehouse_logs.js @@ -0,0 +1,56 @@ +'use strict'; + +const path = require('path'); + +/** + * 定时消费仓库 API 日志文件队列,逐条插入数据库。 + * 间隔 30 秒执行,type: worker(仅一个 worker 执行)。 + */ +module.exports = { + schedule: { + interval: '30s', + type: 'worker', + immediate: false, + disable: false, + }, + + async task(ctx) { + if (ctx.app._consumeWarehouseLogsRunning) return; + ctx.app._consumeWarehouseLogsRunning = true; + + const fileWriter = ctx.app.fileWriter; + const mysql = ctx.app.mysql.get('wms'); + const progressFilePath = path.join(fileWriter.baseDir, 'warehouse-logs', '.consume-progress'); + + try { + const result = await fileWriter.consumeFiles({ + businessName: 'warehouse-logs', + progressFilePath, + maxConsumeRecordsPerWindow: 500, + parseJson: true, + onRecord: async record => { + await mysql.insert('wms_warehouse_log', { + log_id: record.log_id || null, + app_key: record.app_key || null, + method: record.method || null, + warehouse_id: record.warehouse_id || null, + url: record.url || null, + http_status: record.http_status || null, + body: record.body || null, + result: record.result || null, + use_time: record.use_time || 0, + created_at: record.created_at ? new Date(record.created_at) : new Date(), + }); + }, + }); + + if (result.processedCount > 0) { + ctx.logger.info(`[consume-warehouse-logs] 消费 ${result.processedCount} 条日志`); + } + } catch (err) { + ctx.logger.error(`[consume-warehouse-logs] 消费失败: ${err.message}`); + } finally { + ctx.app._consumeWarehouseLogsRunning = false; + } + }, +}; diff --git a/app/schedule/consume_waybill_allocate_queue.js b/app/schedule/consume_waybill_allocate_queue.js new file mode 100644 index 0000000..52400ec --- /dev/null +++ b/app/schedule/consume_waybill_allocate_queue.js @@ -0,0 +1,466 @@ +'use strict'; + +/** + * 定时消费订单创建时入队的自动分配快递队列(wms_waybill_allocate_queue)。 + * + * 背景:订单创建后的异步流程逐单直接取号,大批量订单创建时 N 条并发取号事务 + * 与结算事务产生 wms_store_warehouse / wms_order_express 的 AB-BA 死锁。 + * 本任务按仓库+货主串行消费,保证同一签约关系下同一时刻只有一个取号事务在跑。 + * + * 截单语义:订单创建时已判定(截单/未审核不入队),已入队的正常消费,消费侧不再校验截单。 + * 间隔 15 秒、type: worker(仅一个 worker 执行),带重入保护。 + */ + +const MAX_CONSUME_ROWS_PER_WINDOW = 200; +const MAX_RETRY_COUNT = 3; +const RETRY_BASE_DELAY_MS = 60 * 1000; +const PROCESSING_STALE_MS = 10 * 60 * 1000; +const WAITING_OMS_STALE_MS = 10 * 60 * 1000; +const MAX_ERROR_MESSAGE_LENGTH = 500; + +module.exports = { + schedule: { + interval: '15s', + type: 'worker', + immediate: false, + disable: false, + }, + + async task(ctx) { + // 防止重入 + if (ctx.app._consumeWaybillAllocateQueueRunning) return; + ctx.app._consumeWaybillAllocateQueueRunning = true; + + try { + await consumePendingRows(ctx); + } catch (err) { + ctx.logger.error(`[consume-waybill-allocate-queue] 消费异常: ${err.message}`, { stack: err.stack }); + } finally { + ctx.app._consumeWaybillAllocateQueueRunning = false; + } + }, +}; + +/** + * 批量更新队列行状态。 + * @param {Object} ctx Egg 上下文。 + * @param {Array} rows 队列行(含 id)。 + * @param {string} status 目标状态。 + * @param {string|null} errorMessage 失败原因。 + * @return {Promise} 无返回值。 + */ +async function updateQueueRowsStatus(ctx, rows, status, errorMessage) { + const queueModel = ctx.model && ctx.model.WaybillAllocateQueue; + if (!queueModel || !Array.isArray(rows) || rows.length === 0) { + return; + } + + const { Op } = ctx.app.Sequelize; + const ids = rows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (ids.length === 0) { + return; + } + + await queueModel.update({ + status, + error_message: errorMessage ? String(errorMessage).slice(0, MAX_ERROR_MESSAGE_LENGTH) : null, + updated_at: new Date(), + }, { + where: { + id: { + [Op.in]: ids, + }, + }, + }); +} + +/** + * 组消费失败或未完成时:重试次数+1,未超限退回 pending(带退避),超限转 failed。 + * @param {Object} ctx Egg 上下文。 + * @param {Array} rows 队列行。 + * @param {string} errorMessage 失败原因。 + * @param {boolean} failImmediately 是否立即判失败(如 warehouse_id 缺失,重试无意义)。 + * @return {Promise} 无返回值。 + */ +async function markGroupRetryOrFailed(ctx, rows, errorMessage, failImmediately) { + const queueModel = ctx.model && ctx.model.WaybillAllocateQueue; + if (!queueModel || !Array.isArray(rows) || rows.length === 0) { + return; + } + + const normalizedErrorMessage = String(errorMessage || '运单分配失败'); + + for (const row of rows) { + const rowId = Number(row.id); + if (!Number.isInteger(rowId) || rowId <= 0) { + continue; + } + + const retryCount = Number(row.retry_count) || 0; + if (failImmediately || retryCount + 1 >= MAX_RETRY_COUNT) { + await queueModel.update({ + status: 'failed', + retry_count: retryCount + 1, + error_message: normalizedErrorMessage.slice(0, MAX_ERROR_MESSAGE_LENGTH), + updated_at: new Date(), + }, { + where: { id: rowId }, + }); + } else { + const delay = (retryCount + 1) * RETRY_BASE_DELAY_MS; + await queueModel.update({ + status: 'pending', + retry_count: retryCount + 1, + next_retry_at: new Date(Date.now() + delay), + error_message: null, + updated_at: new Date(), + }, { + where: { id: rowId }, + }); + } + } +} + +/** + * 消费需要回 OMS 取号的队列行。 + * + * 这些订单被本地取号流水线整体跳过(不分配本地快递),改由 OMS 侧外部打单账号取号: + * - 成功:order_express 落运单号(status=1),队列行置 done; + * - 不可重试失败(订单取消/作废、编码未绑定、凭据缺失等):队列行置 failed,原因写入 error_message; + * - 可重试失败(网络、OMS 5xx、平台未返回运单号):按现有重试策略退回 pending。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} group 分组信息(warehouseId / storeId / rows)。 + * @param {Array} waitingRows 需要回 OMS 取号的队列行。 + * @return {Promise<{done: number, failed: number, retry: number}>} 处理统计。 + */ +async function consumeOmsWaybillRows(ctx, group, waitingRows) { + const summary = { done: 0, failed: 0, retry: 0 }; + const expressService = ctx.service && ctx.service.systems && ctx.service.systems.express; + const expressPlatformService = ctx.service && ctx.service.systems + && (ctx.service.systems.expressPlatform || ctx.service.systems.express_platform); + + if (!expressService || !expressPlatformService || typeof expressPlatformService.oms !== 'function') { + await markGroupRetryOrFailed(ctx, waitingRows, 'OMS 取号平台未实现(express_platform.oms)', true); + summary.failed = waitingRows.length; + return summary; + } + + const { Op } = ctx.app.Sequelize; + const orderIds = Array.from(new Set( + waitingRows + .map(row => Number(row.order_id)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0) + )); + + if (orderIds.length === 0) { + await markGroupRetryOrFailed(ctx, waitingRows, '队列数据缺少有效 order_id', true); + summary.failed = waitingRows.length; + return summary; + } + + const orderModel = await expressService.getWaybillAsyncOrderDeliveryModel(group.warehouseId); + const orderRows = orderModel && typeof orderModel.findAll === 'function' + ? await orderModel.findAll({ + where: { + warehouse_id: group.warehouseId, + id: { [Op.in]: orderIds }, + }, + attributes: [ + 'id', 'warehouse_id', 'store_id', 'delivery_order_code', + 'logistics_code', 'sys_logistics_code', 'source_order_codes', 'need_oms_waybill', 'from_key', + ], + raw: true, + }) + : []; + const orderMap = new Map( + (Array.isArray(orderRows) ? orderRows : []).map(row => [ Number(row.id), row ]) + ); + + const bizOrders = []; + const missingRows = []; + for (const row of waitingRows) { + const orderId = Number(row.order_id); + const order = orderMap.get(orderId); + + if (!order) { + missingRows.push(row); + continue; + } + + bizOrders.push({ + order_id: orderId, + business_key: Number(row.business_key) || 1, + order_delivery: order, + }); + } + + if (missingRows.length > 0) { + await updateQueueRowsStatus(ctx, missingRows, 'failed', '订单不存在或已流转到其它分表'); + summary.failed += missingRows.length; + } + + if (bizOrders.length === 0) { + return summary; + } + + let omsError = null; + try { + const omsPayload = { + warehouse_id: group.warehouseId, + store_id: group.storeId, + orders: bizOrders, + }; + + if (typeof expressService.dispatchWaybillAsyncPlatform === 'function') { + await expressService.dispatchWaybillAsyncPlatform('oms', omsPayload); + } else { + await expressPlatformService.oms(omsPayload); + } + } catch (error) { + // 部分成功时成功部分已在平台方法内落库,这里统一按 order_express 实际结果判定 + omsError = error; + } + + const orderExpressModel = ctx.model && ctx.model.OrderExpress; + const doneKeySet = new Set(); + if (orderExpressModel && typeof orderExpressModel.findAll === 'function') { + const doneRows = await orderExpressModel.findAll({ + where: { + warehouse_id: group.warehouseId, + [Op.or]: bizOrders.map(order => ({ + order_id: order.order_id, + business_key: order.business_key, + })), + status: 1, + }, + attributes: [ 'order_id', 'business_key' ], + raw: true, + }); + for (const doneRow of Array.isArray(doneRows) ? doneRows : []) { + doneKeySet.add(`${Number(doneRow.order_id)}:${Number(doneRow.business_key) || 1}`); + } + } + + const omsDoneRows = []; + const omsRestRows = []; + for (const row of waitingRows) { + if (missingRows.includes(row)) { + continue; + } + + const rowKey = `${Number(row.order_id)}:${Number(row.business_key) || 1}`; + if (doneKeySet.has(rowKey)) { + omsDoneRows.push(row); + } else { + omsRestRows.push(row); + } + } + + if (omsDoneRows.length > 0) { + await updateQueueRowsStatus(ctx, omsDoneRows, 'done', null); + summary.done += omsDoneRows.length; + } + + if (omsRestRows.length > 0) { + const retryable = !omsError || omsError.retryable !== false; + const errorMessage = omsError && omsError.message ? omsError.message : 'OMS 取号未完成'; + + if (omsError && typeof expressService.handleWaybillAllocateFailure === 'function') { + // 与本地平台失败口径一致:标记订单异常、写失败日志、清理未完成占位行 + await expressService.handleWaybillAllocateFailure( + omsRestRows.map(row => ({ + order_id: Number(row.order_id), + business_key: Number(row.business_key) || 1, + })), + { warehouse_id: group.warehouseId, sys_platform_code: 'oms' }, + errorMessage + ).catch(failureError => { + ctx.logger.error( + `[consume-waybill-allocate-queue] OMS 失败收尾处理异常: ${failureError && failureError.message}` + ); + }); + } + + if (retryable) { + await markGroupRetryOrFailed(ctx, omsRestRows, errorMessage, false); + summary.retry += omsRestRows.length; + } else { + await markGroupRetryOrFailed(ctx, omsRestRows, errorMessage, true); + summary.failed += omsRestRows.length; + } + } + + ctx.logger.info( + `[consume-waybill-allocate-queue] OMS 取号完成 warehouse_id=${group.warehouseId} store_id=${group.storeId} ` + + `total=${bizOrders.length} done=${summary.done} failed=${summary.failed} retry=${summary.retry}` + + `${omsError ? ` error=${omsError.message}` : ''}` + ); + + return summary; +} + +/** + * 拉取并消费待分配队列。 + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ +async function consumePendingRows(ctx) { + const queueModel = ctx.model && ctx.model.WaybillAllocateQueue; + const expressService = ctx.service && ctx.service.systems && ctx.service.systems.express; + if (!queueModel || typeof queueModel.findAll !== 'function' + || !expressService || typeof expressService.createWaybillCodePipeline !== 'function') { + return; + } + + const { Op } = ctx.app.Sequelize; + + // 1) 兜底恢复:上次运行中断遗留的 processing 行退回 pending + await queueModel.update({ + status: 'pending', + updated_at: new Date(), + }, { + where: { + status: 'processing', + updated_at: { + [Op.lt]: new Date(Date.now() - PROCESSING_STALE_MS), + }, + }, + }); + + // 1.1) 兜底恢复:OMS 取号中途进程中断遗留的 waiting_oms 行退回 pending 重新取号 + await queueModel.update({ + status: 'pending', + updated_at: new Date(), + }, { + where: { + status: 'waiting_oms', + updated_at: { + [Op.lt]: new Date(Date.now() - WAITING_OMS_STALE_MS), + }, + }, + }); + + // 2) 拉取待消费行 + const now = new Date(); + const pendingRows = await queueModel.findAll({ + where: { + status: 'pending', + [Op.or]: [ + { next_retry_at: null }, + { next_retry_at: { [Op.lte]: now } }, + ], + }, + order: [[ 'id', 'ASC' ]], + limit: MAX_CONSUME_ROWS_PER_WINDOW, + raw: true, + }); + + if (!Array.isArray(pendingRows) || pendingRows.length === 0) { + return; + } + + // 3) 标记消费中(单 worker + 重入保护下仅作状态记录) + const pendingIds = pendingRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (pendingIds.length > 0) { + await queueModel.update({ + status: 'processing', + updated_at: new Date(), + }, { + where: { + id: { + [Op.in]: pendingIds, + }, + }, + }); + } + + // 4) 按 warehouse_id + store_id 分组,逐组串行消费 + const groupMap = new Map(); + for (const row of pendingRows) { + const warehouseId = Number(row.warehouse_id) || 0; + const storeId = Number(row.store_id) || 0; + const groupKey = `${warehouseId}:${storeId}`; + if (!groupMap.has(groupKey)) { + groupMap.set(groupKey, { + warehouseId, + storeId, + rows: [], + }); + } + groupMap.get(groupKey).rows.push(row); + } + + const orderExpressModel = ctx.model && ctx.model.OrderExpress; + + for (const group of groupMap.values()) { + const orders = group.rows + .map(row => { + const orderId = Number(row.order_id); + const businessKey = Number(row.business_key) || 1; + return { order_id: orderId, business_key: businessKey }; + }) + .filter(order => Number.isInteger(order.order_id) && order.order_id > 0); + + if (group.warehouseId <= 0 || orders.length === 0) { + await markGroupRetryOrFailed(ctx, group.rows, '队列数据缺少有效 warehouse_id/order_id', true); + continue; + } + + try { + const pipelineResult = await expressService.createWaybillCodePipeline(orders, { + awaitTasks: true, + warehouseId: group.warehouseId, + }); + + // 需要回 OMS 取号的订单已由流水线分流:对应队列行不参与本地分配快递, + // 转由 express_platform.oms 调用 OMS deliveryorder.getwaybill 取号并回写运单。 + const needOmsWaybillOrderIdSet = new Set( + (pipelineResult && Array.isArray(pipelineResult.skipped_need_oms_waybill_order_ids) + ? pipelineResult.skipped_need_oms_waybill_order_ids + : []) + .map(orderId => Number(orderId)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0) + ); + const waitingRows = group.rows.filter(row => needOmsWaybillOrderIdSet.has(Number(row.order_id))); + const allocatableRows = group.rows.filter(row => !needOmsWaybillOrderIdSet.has(Number(row.order_id))); + let omsSummary = null; + if (waitingRows.length > 0) { + await updateQueueRowsStatus(ctx, waitingRows, 'waiting_oms', '等待外部OMS取号'); + ctx.logger.info(`[consume-waybill-allocate-queue] 组内订单需要回 OMS 取号,转 OMS 取号 warehouse_id=${group.warehouseId} store_id=${group.storeId} waiting=${waitingRows.length}`); + omsSummary = await consumeOmsWaybillRows(ctx, group, waitingRows); + } + + // 5) 判定结果:取到单号(status=1)的订单视为完成(仅统计参与本地取号的队列行) + const doneKeySet = new Set(); + if (orderExpressModel && typeof orderExpressModel.findAll === 'function') { + const doneRows = await orderExpressModel.findAll({ + where: { + warehouse_id: group.warehouseId, + [Op.or]: orders.map(order => ({ + order_id: order.order_id, + business_key: order.business_key, + })), + status: 1, + }, + attributes: [ 'order_id', 'business_key' ], + raw: true, + }); + for (const doneRow of Array.isArray(doneRows) ? doneRows : []) { + doneKeySet.add(`${Number(doneRow.order_id)}:${Number(doneRow.business_key)}`); + } + } + + const doneRows = allocatableRows.filter(row => doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`)); + const restRows = allocatableRows.filter(row => !doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`)); + + await updateQueueRowsStatus(ctx, doneRows, 'done', null); + await markGroupRetryOrFailed(ctx, restRows, '运单分配未完成', false); + + ctx.logger.info(`[consume-waybill-allocate-queue] 组消费完成 warehouse_id=${group.warehouseId} store_id=${group.storeId} total=${group.rows.length} done=${doneRows.length} rest=${restRows.length} waiting_oms=${waitingRows.length}${omsSummary ? ` oms_done=${omsSummary.done} oms_failed=${omsSummary.failed} oms_retry=${omsSummary.retry}` : ''}`); + } catch (error) { + ctx.logger.error(`[consume-waybill-allocate-queue] 组消费失败 warehouse_id=${group.warehouseId} store_id=${group.storeId}: ${error.message}`); + await markGroupRetryOrFailed(ctx, group.rows, error && error.message ? error.message : String(error), false); + } + } +} diff --git a/app/schedule/domain_verify_scan.js b/app/schedule/domain_verify_scan.js new file mode 100644 index 0000000..93b6064 --- /dev/null +++ b/app/schedule/domain_verify_scan.js @@ -0,0 +1,183 @@ +// app/schedule/domain_verify_scan.js +'use strict'; + +/** + * 域名验证扫描定时任务。 + * + * 按 config.frontConfig.domainVerify.interval 周期性触发(默认 10m), + * 扫描 wms_warehouse_front_config 中「已生成待校验 TXT 记录、且尚未通过验证」的行, + * 逐行解析 DNS TXT 记录并回写 domain_status / domain_verified_at / + * domain_verify_attempts / domain_last_error;只有通过验证的域名才会被公共拉取接口 + * 与 nginx server 块生成流程放行。 + * + * 并发控制(双保险): + * 1. 进程内重入标志 ctx.app._domainVerifyScanRunning:上一轮未结束时跳过本轮; + * 2. Redis 跨进程互斥锁 SET NX EX:多实例部署时同一轮只有一个实例执行, + * TTL 取 config.frontConfig.domainVerify.lockTtlSeconds(默认 600s); + * Redis 不可用或抛错时降级为「仅进程内防重入」并 WARN, + * 不因缓存故障中断域名验证。 + * + * 业务逻辑全部委托 service.systems.frontConfig.verifyPendingDomains(本文件不写 SQL); + * 任务失败只记录错误日志,不向上抛出,避免 schedule 崩溃。 + * + * 关闭方式:config.frontConfig.domainVerify.enable = false,此时 schedule + * 标记为 disable,Egg 不注册本任务(进程内不会执行)。 + */ + +/** @type {string} 跨进程互斥锁 key */ +const LOCK_CACHE_KEY = 'schedule:domain_verify_scan:lock'; +/** @type {string} 日志前缀 tag */ +const LOG_TAG = '[domain_verify_scan]'; +/** @type {number} 锁 TTL 兜底值(秒) */ +const DEFAULT_LOCK_TTL_SECONDS = 600; +/** @type {string} 扫描间隔兜底值 */ +const DEFAULT_INTERVAL = '10m'; + +/** + * 获取 Redis cache 客户端。 + * + * @param {Object} app Egg 应用实例。 + * @return {Object|null} Redis 客户端或 null。 + */ +function getCacheRedisClient(app) { + if (!app || !app.redis || typeof app.redis.get !== 'function') { + return null; + } + + try { + return app.redis.get('cache') || null; + } catch (error) { + return null; + } +} + +/** + * 获取跨进程互斥锁(SET NX EX)。 + * + * @param {Object} ctx Egg 上下文。 + * @param {number} ttlSeconds 锁 TTL(秒)。 + * @param {string} lockValue 锁持有者标识(pid + 时间戳)。 + * @return {Promise} 是否获取成功;Redis 不可用时返回 true(退化为进程内防重入)。 + */ +async function acquireLock(ctx, ttlSeconds, lockValue) { + const redis = getCacheRedisClient(ctx.app); + + if (!redis || typeof redis.set !== 'function') { + ctx.logger.warn(`${LOG_TAG} Redis 不可用,跨进程互斥降级为进程内防重入`); + return true; + } + + try { + const result = await redis.set(LOCK_CACHE_KEY, lockValue, 'EX', ttlSeconds, 'NX'); + return result === 'OK'; + } catch (error) { + ctx.logger.warn(`${LOG_TAG} 获取互斥锁失败(按未加锁继续): ${error.message}`); + return true; + } +} + +/** + * 释放跨进程互斥锁(GET 比对 value 后再 DEL,避免误删他人锁)。 + * + * 仍存在极小竞态窗口:本进程 GET 到自己的 value 后、DEL 之前锁恰好 TTL 到期 + * 并被其它实例抢到(value 为 pid + 时间戳,重复概率极低),最坏结果是提前释放 + * 一次锁,不会造成数据错误(service 层 update 自带 id + domain 防并发守卫), + * 因此接受该窗口而不引入 Lua 脚本。 + * + * @param {Object} ctx Egg 上下文。 + * @param {string} lockValue 锁持有者标识(与获取时一致)。 + * @return {Promise} 无返回值。 + */ +async function releaseLock(ctx, lockValue) { + const redis = getCacheRedisClient(ctx.app); + + if (!redis || typeof redis.get !== 'function' || typeof redis.del !== 'function') { + // Redis 不可用则跳过释放,等待 TTL 自然过期 + return; + } + + try { + const current = await redis.get(LOCK_CACHE_KEY); + if (current !== lockValue) { + return; + } + await redis.del(LOCK_CACHE_KEY); + } catch (error) { + ctx.logger.warn(`${LOG_TAG} 释放互斥锁失败(等待 TTL 过期): ${error.message}`); + } +} + +/** + * 域名验证扫描定时任务。 + * + * @param {Object} app Egg 应用实例。 + * @return {Object} 定时任务定义(含 schedule 与 task)。 + */ +module.exports = app => { + // 工厂内动态读取配置:interval / lockTtlSeconds / enable 变更后无需改代码 + const frontConfig = (app.config && app.config.frontConfig) || {}; + const domainVerify = frontConfig.domainVerify || {}; + const interval = typeof domainVerify.interval === 'string' && domainVerify.interval + ? domainVerify.interval + : DEFAULT_INTERVAL; + const lockTtlSeconds = Number(domainVerify.lockTtlSeconds) > 0 + ? Math.floor(Number(domainVerify.lockTtlSeconds)) + : DEFAULT_LOCK_TTL_SECONDS; + + return { + schedule: { + // 固定间隔触发;domainVerify.enable === false 时 disable 为 true, + // Egg 直接不注册本任务(不会进入 task,也不会占用 worker 周期) + interval, + type: 'worker', + immediate: false, + disable: domainVerify.enable === false, + }, + + /** + * 执行一轮域名验证扫描。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + // 进程内防重入:单实例上一轮未结束时不再叠加下一轮 + if (ctx.app._domainVerifyScanRunning) { + ctx.logger.info(`${LOG_TAG} 本轮任务跳过,上一轮尚未结束`); + return; + } + + const lockValue = `${process.pid}-${Date.now()}`; + const locked = await acquireLock(ctx, lockTtlSeconds, lockValue); + if (!locked) { + ctx.logger.info(`${LOG_TAG} 未获取到跨进程互斥锁,本轮跳过(其它实例正在执行)`); + return; + } + + ctx.app._domainVerifyScanRunning = true; + const startedAt = Date.now(); + + try { + // 业务逻辑一律委托 service,schedule 内不写 SQL + const summary = await ctx.service.systems.frontConfig.verifyPendingDomains({}); + + ctx.logger.info( + `${LOG_TAG} 本轮完成 scanned=${summary.scanned} verified=${summary.verified}` + + ` failed=${summary.failed} skipped=${summary.skipped}` + + ` errors=${summary.errors.length} duration=${Date.now() - startedAt}ms` + ); + + if (summary.errors.length > 0) { + ctx.logger.warn(`${LOG_TAG} 本轮错误摘要: ${summary.errors.slice(0, 5).join(' | ')}`); + } + } catch (error) { + // service 层已 fail-soft(迁移未执行时返回零统计),此处为最后兜底: + // 只记日志不上抛,避免 schedule 崩溃 + ctx.logger.error(`${LOG_TAG} 本轮执行异常: ${error && error.message ? error.message : String(error)}`); + } finally { + ctx.app._domainVerifyScanRunning = false; + await releaseLock(ctx, lockValue); + } + }, + }; +}; diff --git a/app/schedule/intercept_auto_confirm.js b/app/schedule/intercept_auto_confirm.js new file mode 100644 index 0000000..178e363 --- /dev/null +++ b/app/schedule/intercept_auto_confirm.js @@ -0,0 +1,116 @@ +// app/schedule/intercept_auto_confirm.js +'use strict'; + +const EXECUTION_LOG_CACHE_KEY = 'schedule:intercept_auto_confirm:last_execution'; +const EXECUTION_LOG_CACHE_TTL = 900; // 15 分钟 +const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:intercept_auto_confirm:history'; +const EXECUTION_LOG_HISTORY_MAX = 20; // 保留最近 20 次执行记录 +const EXECUTION_LOG_HISTORY_TTL = 86400; // 1 天 + +/** + * 将本次执行日志写入缓存。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} 无返回值。 + */ +async function writeExecutionLogToCache(ctx, logEntry) { + try { + if (ctx.app && typeof ctx.app.setCacheAsync === 'function') { + await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL); + } + } catch (err) { + ctx.logger.warn(`[intercept-auto-confirm] 写入执行日志缓存失败: ${err.message}`); + } +} + +/** + * 将本次执行日志追加到历史记录缓存(保留最近 N 次)。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} 无返回值。 + */ +async function appendExecutionHistory(ctx, logEntry) { + try { + if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') { + return; + } + + const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY); + const history = Array.isArray(rawHistory) ? rawHistory : []; + history.unshift(logEntry); + await ctx.app.setCacheAsync( + EXECUTION_LOG_HISTORY_CACHE_KEY, + history.slice(0, EXECUTION_LOG_HISTORY_MAX), + EXECUTION_LOG_HISTORY_TTL + ); + } catch (err) { + ctx.logger.warn(`[intercept-auto-confirm] 写入执行历史缓存失败: ${err.message}`); + } +} + +/** + * 每 1 小时在单 worker 中执行一次自动库内拦截确定。 + * + * 扫描待处理表(current 分表)中「拦截状态为请求拦截(intercept_status='requested') + * 且面单未打印(print_status='none')」的订单,满足拦截时间超 12 小时或 + * 创建时间超 36 小时任一条件时,自动执行库内拦截确定。 + */ +module.exports = { + schedule: { + interval: '1h', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行自动库内拦截确定任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._interceptAutoConfirmRunning) { + return; + } + + ctx.app._interceptAutoConfirmRunning = true; + + const startedAt = Date.now(); + let status = 'success'; + let errorMessage = ''; + let result = null; + + try { + result = await ctx.service.systems.interceptAutoConfirm.runAutoConfirm(); + } catch (error) { + status = 'error'; + errorMessage = error.message; + ctx.logger.error(`[intercept-auto-confirm] 执行失败: ${error.message}`); + } finally { + ctx.app._interceptAutoConfirmRunning = false; + } + + const logEntry = { + executed_at: new Date().toISOString(), + duration_ms: Date.now() - startedAt, + status, + error_message: errorMessage, + warehouse_count: result ? result.warehouse_count : 0, + candidate_count: result ? result.candidate_count : 0, + confirmed_count: result ? result.confirmed_count : 0, + failed_count: result ? result.failed_count : 0, + warehouse_ids: result ? result.warehouse_ids : [], + }; + await writeExecutionLogToCache(ctx, logEntry); + await appendExecutionHistory(ctx, logEntry); + + ctx.logger.info( + `[intercept-auto-confirm] 本轮完成 warehouses=${logEntry.warehouse_count}` + + ` candidate=${logEntry.candidate_count} confirmed=${logEntry.confirmed_count}` + + ` failed=${logEntry.failed_count} duration=${logEntry.duration_ms}ms` + ); + }, +}; diff --git a/app/schedule/notice_receiving_pending_inbound.js b/app/schedule/notice_receiving_pending_inbound.js new file mode 100644 index 0000000..a1b8810 --- /dev/null +++ b/app/schedule/notice_receiving_pending_inbound.js @@ -0,0 +1,54 @@ +'use strict'; + +/** + * 收货未入库提醒定时任务。 + * + * 每 5 分钟在单 worker 中扫描一次:对仓库设置中开启「收货未入库提醒」 + * (`subject_config.receiving_pending_inbound_notice.enabled`)的仓库, + * 在到达其配置的提醒时间(notice_time,默认 08:30)时执行当日提醒。 + * + * - 超时区间同样来自仓库设置:创建时间超过 min_hours(默认 24)且不足 max_hours(默认 48) + * 仍未完成入库的收货单会被提醒;提醒时间与区间均可在仓库设置中调整。 + * - 绑定了货主的收货单通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群。 + * - 提醒时间匹配带 10 分钟宽限(覆盖调度抖动),并用「仓库 + 日期」当日锁保证一天只提醒一次; + * 执行异常会释放当日锁,宽限窗口内的下一轮会重试。 + */ +module.exports = { + schedule: { + interval: '5m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行收货未入库提醒扫描。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._receivingPendingNoticeRunning) { + return; + } + + ctx.app._receivingPendingNoticeRunning = true; + + try { + const summary = await ctx.service.systems.receivingPendingNotice.execute(); + + // 无仓库命中提醒时间时不刷日志,避免每 5 分钟噪音 + if (summary && summary.executedWarehouseCount > 0) { + ctx.logger.info( + `[receiving-pending-notice] 本轮提醒完成:开启仓库 ${summary.checkedWarehouseCount},` + + `执行 ${summary.executedWarehouseCount},未入库 ${summary.pendingCount} 单,` + + `发送 ${summary.sentCount},失败 ${summary.failedCount},回退客服群 ${summary.fallbackCount || 0}` + ); + } + } catch (error) { + ctx.logger.error(`[receiving-pending-notice] 任务执行失败: ${error.message}`); + } finally { + ctx.app._receivingPendingNoticeRunning = false; + } + }, +}; diff --git a/app/schedule/notice_stock_remaining.js b/app/schedule/notice_stock_remaining.js new file mode 100644 index 0000000..a945716 --- /dev/null +++ b/app/schedule/notice_stock_remaining.js @@ -0,0 +1,779 @@ +'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 {object} record 仓库或货主关联记录对象 + * @return {string} 名称字符串,读取不到时返回空字符串 + */ +function readAssociatedName(record) { + return String(readRecordValue(record, [ 'company_name', 'companyName', 'name', 'custom_name' ]) || '').trim(); +} + +/** + * 生成“名称(ID)”形式的实体展示标签,名称缺失时优雅回退为 ID。 + * @param {string} label 实体标签前缀,如“仓库”“货主” + * @param {string} name 实体名称 + * @param {number} id 实体 ID + * @return {string} 展示标签 + */ +function buildEntityLabel(label, name, id) { + if (name) { + return id > 0 ? `${label}:${name}(ID:${id})` : `${label}:${name}`; + } + + return `${label}ID:${id > 0 ? id : '未知'}`; +} + +/** + * 将数值安全转换为数字。 + * @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(' / ') || '无'; + const warehouseRecord = readRecordValue(storageRecord, [ 'warehouse' ]) || storageRecord.warehouse || {}; + const storeRecord = readRecordValue(storageRecord, [ 'store' ]) || storageRecord.store || {}; + const warehouseName = readAssociatedName(warehouseRecord); + const storeName = readAssociatedName(storeRecord); + + return [ + `库存效期预警:${itemName}`, + `商品编码:${itemCode}`, + `库存ID:${storageId || '未知'}`, + `批次号:${batchNo}`, + buildEntityLabel('仓库', warehouseName, warehouseId), + buildEntityLabel('货主', storeName, 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.Store, + as: 'warehouse', + attributes: [ 'company_name' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'company_name' ], + required: false, + }, + { + 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 warehouseRecord = readRecordValue(storageRecord, [ 'warehouse' ]) || storageRecord.warehouse || {}; + const storeRecord = readRecordValue(storageRecord, [ 'store' ]) || storageRecord.store || {}; + const warehouseName = readAssociatedName(warehouseRecord); + const storeName = readAssociatedName(storeRecord); + 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: buildEntityLabel('仓库', warehouseName, warehouseId), + }, + businessName: 'storage', + event: NOTICE_EVENT, + title, + content, + businessId: stockId, + messageType: 'text', + metadata: { + cacheKey: stockDayCacheKey, + storageId, + stockId, + notifyKey, + businessId: stockId, + thresholdDays, + remainingDays, + warehouseId, + warehouseName, + storeId, + storeName, + 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/notify_return_received.js b/app/schedule/notify_return_received.js new file mode 100644 index 0000000..1a8be53 --- /dev/null +++ b/app/schedule/notify_return_received.js @@ -0,0 +1,40 @@ +'use strict'; + +/** + * 退回收件登记聚合通知定时任务。 + * 每分钟在单 worker 中扫描一次:对"登记时间超过防抖窗口(默认 5 分钟)且未通知"的登记, + * 只对货主查退回时登记过的运单,按 仓库+货主 聚合推送到货主售后群,并标记 is_notified=1。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行退回收件登记聚合通知。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._returnReceivedNotifyRunning) { + return; + } + + ctx.app._returnReceivedNotifyRunning = true; + + try { + const result = await ctx.service.systems.returnReceived.notifyPending(); + ctx.logger.info( + `[notify-return-received] 聚合通知完成 notified=${result && result.notified || 0} skipped=${result && result.skipped || 0}` + ); + } catch (error) { + ctx.logger.error(`[notify-return-received] 任务执行失败: ${error.message}`); + } finally { + ctx.app._returnReceivedNotifyRunning = false; + } + }, +}; diff --git a/app/schedule/notify_video_record_result.js b/app/schedule/notify_video_record_result.js new file mode 100644 index 0000000..f5cfb0d --- /dev/null +++ b/app/schedule/notify_video_record_result.js @@ -0,0 +1,60 @@ +'use strict'; + +/** + * 视频补录状态收敛 + 结果通知定时任务。 + * + * 每分钟在单 worker 中串行执行两段: + * 1) settleStatuses:把「在途且未通知」的补录请求收敛为终态 + * (视频已产出 → completed;录制服务失败 / 超过超时阈值 → failed),只改状态不通知; + * 2) notifyResults:扫「终态且未通知」的记录回信到触发查询的群 + * (有用户信息时定向回原用户),成功后标记 is_notified=1;失败记录额外转仓库客服群人工处理。 + * + * 单轮处理条数由 config.inbox.videoRecordNotifyLimit 控制(默认 10), + * 超时阈值由 config.inbox.videoRecordNotifyTimeoutMs 控制(默认 1 小时)。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行视频补录状态收敛与结果通知。 + * + * 两段串行,顺序不可颠倒: + * 1) settleStatuses:只把在途记录收敛为终态(completed / failed),不通知; + * 2) notifyResults:扫「终态且未通知」的记录回信(成功复用原查询链路文案,失败转人工)。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._videoRecordNotifyRunning) { + return; + } + + ctx.app._videoRecordNotifyRunning = true; + + try { + const settle = await ctx.service.systems.videoRecordRequest.settleStatuses(); + const result = await ctx.service.systems.videoRecordRequest.notifyResults(); + const settleChanged = settle + && (settle.completed > 0 || settle.failed > 0 || settle.timeout > 0 || settle.invalid > 0); + if (settleChanged || (result && (result.notified > 0 || result.skipped > 0))) { + ctx.logger.info( + `[notify-video-record] 本轮完成 settle(scanned=${settle && settle.scanned} completed=${settle && settle.completed} ` + + `failed=${settle && settle.failed} timeout=${settle && settle.timeout} invalid=${settle && settle.invalid}) ` + + `notify(scanned=${result && result.scanned} notified=${result && result.notified} ` + + `completed=${result && result.completed} failed=${result && result.failed} ` + + `timeout=${result && result.timeout} skipped=${result && result.skipped})` + ); + } + } catch (error) { + ctx.logger.error(`[notify-video-record] 任务执行失败: ${error.message}`); + } finally { + ctx.app._videoRecordNotifyRunning = false; + } + }, +}; diff --git a/app/schedule/order_sync_notice_flush.js b/app/schedule/order_sync_notice_flush.js new file mode 100644 index 0000000..de64a05 --- /dev/null +++ b/app/schedule/order_sync_notice_flush.js @@ -0,0 +1,51 @@ +'use strict'; + +const FLUSH_TASK_NAME = 'order_sync_notice_flush'; + +module.exports = { + schedule: { + interval: '30s', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 冲刷合并的订单同步通知。 + * 订单同步完成后不立即通知,等待 3 分钟去抖窗口结束, + * 由本任务把同一「仓库:货主」维度的订单合并为一条消息统一推送。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._orderSyncNoticeFlushRunning) { + ctx.logger.info(`[${FLUSH_TASK_NAME}] 任务仍在运行中,跳过本轮调度`); + return; + } + + ctx.app._orderSyncNoticeFlushRunning = true; + + try { + const orderAsyncService = ctx.service && ctx.service.systems && ctx.service.systems.orderAsync; + if (!orderAsyncService || typeof orderAsyncService.flushDeferredOrderSyncNotices !== 'function') { + ctx.logger.warn(`[${FLUSH_TASK_NAME}] orderAsync 服务不可用,跳过本轮`); + return; + } + + const result = await orderAsyncService.flushDeferredOrderSyncNotices(); + + ctx.logger.info(`[${FLUSH_TASK_NAME}] 本轮完成`, { + skipped: !!(result && result.skipped), + reason: result && result.reason, + flushedCount: result && result.flushedCount, + failedCount: result && result.failedCount, + skippedCount: result && result.skippedCount, + }); + } catch (error) { + ctx.logger.error(`[${FLUSH_TASK_NAME}] 执行失败: ${error && error.message || error}`); + } finally { + ctx.app._orderSyncNoticeFlushRunning = false; + } + }, +}; diff --git a/app/schedule/report_delivery_dispatch.js b/app/schedule/report_delivery_dispatch.js new file mode 100644 index 0000000..8f8ab29 --- /dev/null +++ b/app/schedule/report_delivery_dispatch.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 货主报表定时投递调度。 + * 每分钟在单 worker 中扫描一次 wms_report_delivery_plan, + * 命中投递时间点(含宽限)后幂等生成并投递报表(进程内布尔防重入)。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行报表投递调度。 + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._reportDeliveryDispatchRunning) { + return; + } + + ctx.app._reportDeliveryDispatchRunning = true; + + try { + const summary = await ctx.service.systems.reportDelivery.dispatch(); + + ctx.logger.info( + `[report-delivery-dispatch] 本轮投递完成:扫描 ${summary && summary.scanned || 0} 个计划,` + + `投递 ${summary && summary.delivered || 0},失败 ${summary && summary.failed || 0},` + + `跳过 ${summary && summary.skipped || 0}` + ); + } catch (error) { + ctx.logger.error(`[report-delivery-dispatch] 投递调度执行失败: ${error.message}`); + } finally { + ctx.app._reportDeliveryDispatchRunning = false; + } + }, +}; diff --git a/app/schedule/retry_inbox_push.js b/app/schedule/retry_inbox_push.js new file mode 100644 index 0000000..f69dac1 --- /dev/null +++ b/app/schedule/retry_inbox_push.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * 站内信出站推送失败自动重推定时任务。 + * + * 每 3 分钟在单 worker 中扫描一次,按仓库逐个处理(开关与时间范围均由「仓库设置」控制): + * - 只处理在仓库设置里**显式开启**「站内信推送失败自动重发」的仓库 + * (`subject_config.inbox_push_retry.enabled`,缺省/无法读取时为关闭,不重推); + * - 只重推该仓库「失败时间在 `subject_config.inbox_push_retry.window_minutes` + * (分钟,1-1440,缺省 30)内」的消息,超出范围不再补发; + * - 每仓单轮最多重推 config.inbox.pushRetryLimit 条(默认 20,硬上限 200)。 + * + * 推送结果仍回写到同一条记录(成功 2 / 失败 3),成功后不再被扫到,失败则由下一轮继续重试, + * 直到推送成功或滑出该仓库配置的时间窗;此外 config.inbox.pushRetryEnabled 可作为全局应急开关。 + * + * 典型失败原因是桥接离线(回调 HTTP 200 但 body code=503,如 wx offline / qiwe offline), + * 属可自愈的临时故障:桥接恢复后靠本任务补发,无需人工介入。 + */ +module.exports = { + schedule: { + interval: '3m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行出站推送失败消息重推。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._inboxPushRetryRunning) { + return; + } + + ctx.app._inboxPushRetryRunning = true; + + try { + const result = await ctx.service.inbox.message.retryFailedByWarehouse(); + // 无待重推记录时不刷日志,避免每 3 分钟噪音 + if (result && result.scanned > 0) { + ctx.logger.info( + `[retry-inbox-push] 本轮重推 仓库=${result.warehouses}` + + `(开启=${result.enabledWarehouses} 关闭=${result.disabledWarehouses} 跳过=${result.skippedWarehouses})` + + ` scanned=${result.scanned} retried=${result.retried} succeeded=${result.succeeded}` + + ` failed=${result.failed} skipped=${result.skipped}` + ); + } + } catch (error) { + ctx.logger.error(`[retry-inbox-push] 任务执行失败: ${error.message}`); + } finally { + ctx.app._inboxPushRetryRunning = false; + } + }, +}; diff --git a/app/schedule/sync_finished_wave_batch.js b/app/schedule/sync_finished_wave_batch.js new file mode 100644 index 0000000..0723abd --- /dev/null +++ b/app/schedule/sync_finished_wave_batch.js @@ -0,0 +1,127 @@ +// app/schedule/sync_finished_wave_batch.js +'use strict'; + +const EXECUTION_LOG_CACHE_KEY = 'schedule:sync_finished_wave_batch:last_execution'; +const EXECUTION_LOG_CACHE_TTL = 300; // 5 分钟 +const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:sync_finished_wave_batch:history'; +const EXECUTION_LOG_HISTORY_MAX = 20; // 保留最近 20 次执行记录 +const EXECUTION_LOG_HISTORY_TTL = 86400; // 1 天 + +/** + * 将本次执行日志写入缓存。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} + */ +async function writeExecutionLogToCache(ctx, logEntry) { + try { + if (ctx.app && typeof ctx.app.setCacheAsync === 'function') { + await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL); + } + } catch (err) { + ctx.logger.warn(`[sync-finished-wave-batch] 写入执行日志缓存失败: ${err.message}`); + } +} + +/** + * 将本次执行日志追加到历史记录缓存(保留最近 N 次)。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} + */ +async function appendExecutionHistory(ctx, logEntry) { + try { + if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') { + return; + } + + const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY); + const history = Array.isArray(rawHistory) ? rawHistory : []; + history.unshift(logEntry); + await ctx.app.setCacheAsync( + EXECUTION_LOG_HISTORY_CACHE_KEY, + history.slice(0, EXECUTION_LOG_HISTORY_MAX), + EXECUTION_LOG_HISTORY_TTL + ); + } catch (err) { + ctx.logger.warn(`[sync-finished-wave-batch] 写入执行历史缓存失败: ${err.message}`); + } +} + +/** + * 每 1 分钟在单 worker 中执行一次波次自动终结。 + * + * 将"订单已全部离开待处理表"的活动波次(wave_status IN (0,1))收敛为 + * wave_status=5(复核完成),修复遗留 0 单波次在 batchList 中展示的问题。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行波次自动终结任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._syncFinishedWaveBatchRunning) { + return; + } + + ctx.app._syncFinishedWaveBatchRunning = true; + + const startedAt = Date.now(); + let status = 'success'; + let errorMessage = ''; + let result = null; + + try { + result = await ctx.service.systems.waveBatchClosure.closeFinishedWaves(); + + if (result && result.closed_count > 0) { + ctx.logger.info( + `[sync-finished-wave-batch] 自动终结 ${result.closed_count} 个波次: ${JSON.stringify(result.closed_waves)}` + ); + } + } catch (error) { + status = 'error'; + errorMessage = error.message; + ctx.logger.error(`[sync-finished-wave-batch] 执行失败: ${error.message}`); + } finally { + ctx.app._syncFinishedWaveBatchRunning = false; + } + + const logEntry = { + executed_at: new Date().toISOString(), + duration_ms: Date.now() - startedAt, + status, + error_message: errorMessage, + candidate_count: result ? result.candidate_count : 0, + empty_count: result ? result.empty_count : 0, + closed_count: result ? result.closed_count : 0, + pending_confirm_count: result ? result.pending_confirm_count : 0, + unbound_count: result ? result.unbound_count : 0, + misread_count: result ? result.misread_count : 0, + probe_failed_count: result ? result.probe_failed_count : 0, + warehouse_ids: result ? result.warehouse_ids : [], + closed_waves: result ? result.closed_waves : [], + }; + await writeExecutionLogToCache(ctx, logEntry); + await appendExecutionHistory(ctx, logEntry); + + ctx.logger.info( + `[sync-finished-wave-batch] 本轮完成 closed=${result ? result.closed_count : 0} candidate=${result ? result.candidate_count : 0}` + + ` pendingConfirm=${result ? result.pending_confirm_count : 0}` + + ` unbound=${result ? result.unbound_count : 0} misread=${result ? result.misread_count : 0}` + + ` probeFailed=${result ? result.probe_failed_count : 0}` + + ` warehouses=${result ? result.warehouse_ids.length : 0}` + ); + }, +}; 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..ccaa005 --- /dev/null +++ b/app/schedule/sync_outbound_orders_to_delivery.js @@ -0,0 +1,178 @@ +'use strict'; + +const SHORT_TASK_QUERY_TIMEOUT_MS = 15000; +const SHORT_TASK_EXECUTION_TIMEOUT_MS = 30000; +const EXECUTION_LOG_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:last_execution'; +const EXECUTION_LOG_CACHE_TTL = 300; // 5 分钟 +const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:history'; +const EXECUTION_LOG_HISTORY_MAX = 20; // 保留最近 20 次执行记录 +const EXECUTION_LOG_HISTORY_TTL = 86400; // 1 天 + +/** + * 将本次执行日志写入缓存。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} + */ +async function writeExecutionLogToCache(ctx, logEntry) { + try { + if (ctx.app && typeof ctx.app.setCacheAsync === 'function') { + await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL); + } + } catch (err) { + // 缓存写入失败不影响主流程 + ctx.logger.warn(`[sync-outbound-orders-to-delivery] 写入执行日志缓存失败: ${err.message}`); + } +} + +/** + * 将本次执行日志追加到历史记录缓存(保留最近 N 次)。 + * + * 用于不翻日志文件也能观察定时任务每轮执行情况(selected/created/status/error), + * 便于排查「订单满足迁移条件但迟迟未切表」类问题。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} logEntry 日志条目。 + * @return {Promise} 无返回值。 + */ +async function appendExecutionHistory(ctx, logEntry) { + try { + if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') { + return; + } + + const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY); + const history = Array.isArray(rawHistory) ? rawHistory : []; + history.unshift(logEntry); + await ctx.app.setCacheAsync( + EXECUTION_LOG_HISTORY_CACHE_KEY, + history.slice(0, EXECUTION_LOG_HISTORY_MAX), + EXECUTION_LOG_HISTORY_TTL + ); + } catch (err) { + // 历史日志写入失败不影响主流程 + ctx.logger.warn(`[sync-outbound-orders-to-delivery] 写入执行历史缓存失败: ${err.message}`); + } +} + +/** + * 提取错误详情,方便定位问题位置。 + * + * @param {Error} error 错误对象。 + * @return {Object} 错误详情。 + */ +function extractErrorDetail(error) { + if (!error) return {}; + + const detail = { + name: error.name || '', + message: error.message || '', + code: error.code || '', + }; + + // Sequelize 父级错误(通常包含 SQL 信息) + if (error.parent) { + detail.parent = { + name: error.parent.name || '', + message: error.parent.message || '', + code: error.parent.code || '', + sql: error.parent.sql || '', + }; + } + + // SequelizeValidationError 的 fields 列表 + if (Array.isArray(error.errors)) { + detail.validation_errors = error.errors.map(e => ({ + message: e.message, + type: e.type, + path: e.path, + value: String(e.value ?? ''), + })); + } + + // 堆栈前 3 行(定位调用链) + if (error.stack) { + detail.stack_top = error.stack.split('\n').slice(0, 4).map(s => s.trim()); + } + + return detail; +} + +/** + * 每 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; + + const startedAt = Date.now(); + let status = 'success'; + let errorMessage = ''; + let errorDetail = null; + let result = null; + + try { + result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({ + queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS, + executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS, + }); + + if (result && result.retryableFailure) { + status = 'retryable_failure'; + errorMessage = `retryableFailureType=${result.retryableFailureType}, timeoutCount=${result.timeoutCount || 0}`; + 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} 条已出库订单`); + } + + // 始终输出汇总日志(含 0 条场景,确认定时任务在跑) + ctx.logger.info(`[sync-outbound-orders-to-delivery] 本轮完成 selected=${result ? result.totalSelected : 0} created=${result ? result.totalCreated : 0} skipped=${result ? result.totalSkipped : 0} timeout=${result ? result.totalTimeout : 0}`); + } catch (error) { + status = 'error'; + errorMessage = error.message; + errorDetail = extractErrorDetail(error); + ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`, errorDetail); + } finally { + ctx.app._syncOutboundOrdersToDeliveryRunning = false; + } + + // 写入执行日志到缓存 + const logEntry = { + executed_at: new Date().toISOString(), + duration_ms: Date.now() - startedAt, + status, + error_message: errorMessage, + error_detail: errorDetail, + total_selected: result ? result.totalSelected : 0, + total_created: result ? result.totalCreated : 0, + total_skipped: result ? result.totalSkipped : 0, + total_timeout: result ? result.totalTimeout : 0, + warehouse_ids: result ? result.warehouseIds : [], + }; + await writeExecutionLogToCache(ctx, logEntry); + await appendExecutionHistory(ctx, logEntry); + ctx.logger.info(`[sync-outbound-orders-to-delivery] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY} history=${EXECUTION_LOG_HISTORY_CACHE_KEY}`); + }, +}; 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/schedule/wave_strategy_quick_scan_fallback.js b/app/schedule/wave_strategy_quick_scan_fallback.js new file mode 100644 index 0000000..0ce27f0 --- /dev/null +++ b/app/schedule/wave_strategy_quick_scan_fallback.js @@ -0,0 +1,138 @@ +'use strict'; + +const FALLBACK_TASK_NAME = 'wave_strategy_quick_scan_fallback'; + +module.exports = { + schedule: { + interval: '10m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行波次策略快速扫描兜底任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._waveStrategyQuickScanFallbackRunning) { + ctx.logger.info(`[${FALLBACK_TASK_NAME}] 任务仍在运行中,跳过本轮调度`); + return; + } + + ctx.app._waveStrategyQuickScanFallbackRunning = true; + + let totalWarehouseCount = 0; + let submitSuccessCount = 0; + let reusedRunningTaskCount = 0; + let submitFailedCount = 0; + + try { + const storeRows = await ctx.model.Store.findAll({ + attributes: [ 'id' ], + where: { + status: 1, + project: 'warehouse', + }, + raw: true, + }); + + const warehouseIds = Array.isArray(storeRows) + ? storeRows.map(item => Number(item && item.id || 0)).filter(item => Number.isInteger(item) && item > 0) + : []; + totalWarehouseCount = warehouseIds.length; + + for (const warehouseId of warehouseIds) { + try { + const submitPayload = await ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse(warehouseId, { wait: true, forceRescan: true }); + const submitMessage = String(submitPayload && submitPayload.message || '').trim(); + const submitState = String(submitPayload && submitPayload.state || '').trim(); + const isReusedRunningTask = submitMessage.includes('已有快速扫描任务在运行中') + || [ 'running', 'submitted' ].includes(submitState) && submitMessage.includes('运行中'); + + if (isReusedRunningTask) { + reusedRunningTaskCount += 1; + } else { + submitSuccessCount += 1; + } + } catch (error) { + submitFailedCount += 1; + const errorMessage = error && error.message ? error.message : `${error}`; + + ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 仓库触发失败`, { + warehouseId, + error: errorMessage, + }); + + const noticeService = ctx.service + && ctx.service.systems + && ctx.service.systems.notice + && typeof ctx.service.systems.notice.send === 'function' + ? ctx.service.systems.notice + : (ctx.service + && ctx.service.systems + && ctx.service.systems.notice + && ctx.service.systems.notice.index + && typeof ctx.service.systems.notice.index.send === 'function' + ? ctx.service.systems.notice.index + : null); + + if (!noticeService) { + ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 通知服务不可用,跳过失败通知`, { + warehouseId, + error: errorMessage, + }); + continue; + } + + try { + await noticeService.send({ + event: 'wave_strategy_quick_scan_failed', + businessName: 'order', + warehouseId, + subjectId: warehouseId, + subject: { + id: warehouseId, + type: 'warehouse', + }, + title: `波次策略兜底扫描触发失败(仓库 ${warehouseId})`, + content: `兜底扫描任务触发失败,仓库 ${warehouseId},错误:${errorMessage}`, + data: { + warehouse_id: warehouseId, + error: errorMessage, + task: FALLBACK_TASK_NAME, + }, + metadata: { + warehouse_id: warehouseId, + error: errorMessage, + task: FALLBACK_TASK_NAME, + }, + sender: { + id: 0, + name: 'system', + }, + }); + } catch (noticeError) { + ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 发送失败通知异常`, { + warehouseId, + error: noticeError && noticeError.message ? noticeError.message : `${noticeError}`, + }); + } + } + } + + ctx.logger.info(`[${FALLBACK_TASK_NAME}] 任务完成`, { + totalWarehouseCount, + submitSuccessCount, + reusedRunningTaskCount, + submitFailedCount, + }); + } catch (error) { + ctx.logger.error(`[${FALLBACK_TASK_NAME}] 任务执行失败: ${error && error.message ? error.message : error}`); + } finally { + ctx.app._waveStrategyQuickScanFallbackRunning = false; + } + }, +}; diff --git a/app/schedule/wechat_agreement_cleanup.js b/app/schedule/wechat_agreement_cleanup.js new file mode 100644 index 0000000..074622a --- /dev/null +++ b/app/schedule/wechat_agreement_cleanup.js @@ -0,0 +1,71 @@ +// app/schedule/wechat_agreement_cleanup.js +'use strict'; + +/** + * 微信用户须知版本清理定时任务。 + * + * 默认每 1 小时整点(cron:秒 分 时 日 月 周 = 0 0 * * * *)在单 worker 中执行一次, + * 真实删除 wms_wechat_agreement_version 中「未被使用且不是对应 appid 最终版」的历史版本, + * 释放 MySQL 磁盘空间。保留规则:各 appid 最终版(version 最大)+ 被 + * wms_user_oauth.agreement_version_id 引用的版本。 + * cron 从 config.wechatAgreementCleanup.cron 读取(config.default.js 提供默认值), + * 本地环境可在 config.local.js 覆盖为短间隔以便快速验证;enable=false 时不注册本任务; + * 实际清理逻辑收敛在 service.systems.wechat.cleanupUnusedAgreementVersions。 + * + * @param {Object} app Egg 应用实例。 + * @return {Object} 定时任务定义(含 schedule 与 task)。 + */ +module.exports = app => { + const cleanupConfig = (app.config && app.config.wechatAgreementCleanup) || {}; + const cleanupCron = typeof cleanupConfig.cron === 'string' && cleanupConfig.cron + ? cleanupConfig.cron + : '0 0 * * * *'; + + return { + schedule: { + cron: cleanupCron, + type: 'worker', + immediate: false, + disable: cleanupConfig.enable === false, + }, + + /** + * 执行用户须知历史版本清理。 + * + * 采用单 worker 防重入:上一轮未结束时跳过本轮; + * 任务失败只记录错误日志,不向上抛出,避免导致 schedule 崩溃。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + const scheduleName = 'wechat_agreement_cleanup'; + + if (ctx.app._wechatAgreementCleanupRunning) { + ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`); + return; + } + + ctx.app._wechatAgreementCleanupRunning = true; + const startedAt = Date.now(); + try { + const config = ctx.app.config.wechatAgreementCleanup || {}; + const batchSize = Number(config.batchSize) > 0 + ? Math.floor(Number(config.batchSize)) + : 500; + + const summary = await ctx.service.systems.wechat.cleanupUnusedAgreementVersions(batchSize); + + ctx.logger.info( + `[${scheduleName}] 本轮完成 deleted=${summary.deleted} kept_latest=${summary.kept_latest}` + + ` kept_in_use=${summary.kept_in_use} total=${summary.total}` + + ` duration=${Date.now() - startedAt}ms` + ); + } catch (error) { + ctx.logger.error(`[${scheduleName}] 执行失败: ${error.message}`); + } finally { + ctx.app._wechatAgreementCleanupRunning = false; + } + }, + }; +}; diff --git a/app/schedule/workbench_token_expire.js b/app/schedule/workbench_token_expire.js new file mode 100644 index 0000000..3ac2706 --- /dev/null +++ b/app/schedule/workbench_token_expire.js @@ -0,0 +1,69 @@ +'use strict'; + +/** @type {number} 扫描间隔兜底默认值(毫秒):1 小时,配置缺失时使用 */ +const DEFAULT_SCAN_INTERVAL_MS = 60 * 60 * 1000; +/** @type {number} token 有效期兜底默认值(毫秒):3 个月(按 30 天/月折算),配置缺失时使用 */ +const DEFAULT_MAX_AGE_MS = 3 * 30 * 24 * 60 * 60 * 1000; +/** @type {number} 批处理兜底默认值(条) */ +const DEFAULT_BATCH_SIZE = 50; + +/** + * 工作台 token 超期强制下线定时任务。 + * 由 config.workbenchTokenExpire 控制: + * - enable=false 时不注册本任务; + * - scanIntervalMs 控制扫描间隔(毫秒),开发环境可覆盖为短循环便于测试; + * - maxAgeMs 控制 token 有效期阈值,token_updated_at 距今超过该时长即强制下线; + * - batchSize 控制单批处理条数。 + * 实际清理逻辑收敛在 service.systems.workbench.clearExpiredWorkbenchTokens。 + * @param {Object} app Egg 应用实例 + * @return {Object} 定时任务定义(含 schedule 与 task) + */ +module.exports = app => { + const workbenchTokenExpire = (app.config && app.config.workbenchTokenExpire) || {}; + const scanIntervalMs = Number(workbenchTokenExpire.scanIntervalMs) > 0 + ? Number(workbenchTokenExpire.scanIntervalMs) + : DEFAULT_SCAN_INTERVAL_MS; + + return { + schedule: { + interval: scanIntervalMs, + type: 'worker', + immediate: false, + disable: workbenchTokenExpire.enable === false, + }, + + /** + * 扫描并清理 token 超期未更新的工作台,使其强制下线。 + * 采用单 worker 防重入:上一轮未结束时跳过本轮。 + * @param {Object} ctx Egg 上下文 + * @return {Promise} 无返回值 + */ + async task(ctx) { + const scheduleName = 'workbench_token_expire'; + const config = ctx.app.config.workbenchTokenExpire || {}; + + if (ctx.app._workbenchTokenExpireRunning) { + ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`); + return; + } + + ctx.app._workbenchTokenExpireRunning = true; + try { + const maxAgeMs = Number(config.maxAgeMs) > 0 ? Number(config.maxAgeMs) : DEFAULT_MAX_AGE_MS; + const batchSize = Number(config.batchSize) > 0 ? Math.floor(Number(config.batchSize)) : DEFAULT_BATCH_SIZE; + const expiredBefore = new Date(Date.now() - maxAgeMs); + + const summary = await ctx.service.systems.workbench.clearExpiredWorkbenchTokens({ + expiredBefore, + batchSize, + }); + + ctx.logger.info(`[${scheduleName}] 本轮扫描完成:maxAgeMs=${maxAgeMs} expiredBefore=${expiredBefore.toISOString()} scanned=${summary.total_scanned} cleared=${summary.total_cleared} failed=${summary.total_failed}`); + } catch (error) { + ctx.logger.error(`[${scheduleName}] 执行失败: ${error.message}`); + } finally { + ctx.app._workbenchTokenExpireRunning = false; + } + }, + }; +}; diff --git a/app/service/api.js b/app/service/api.js index 544067c..aad17c5 100644 --- a/app/service/api.js +++ b/app/service/api.js @@ -1,17 +1,15 @@ 'use strict'; const Service = require('egg').Service; -const { XMLParser } = require('fast-xml-parser'); class ApiService extends Service { /** * 调用业务方法 - * @param className - * @param actionName - * @param jsonData - * @param format + * @param {string} className 服务类路径 + * @param {string} actionName 方法名 + * @param {Object} jsonData 请求数据 */ - async callMethod(className, actionName, jsonData, format = 'json') { + async callMethod(className, actionName, jsonData) { try { // 构建服务类路径 const servicePath = `${className}`; diff --git a/app/service/apiMethods/print.js b/app/service/apiMethods/print.js new file mode 100644 index 0000000..234da14 --- /dev/null +++ b/app/service/apiMethods/print.js @@ -0,0 +1,334 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('node:crypto'); + +class PrintApiService extends Service { + getPrinterRedis() { + return this.app.redis.get('printer'); + } + + normalizeBindValue(bindValue) { + let bindValueObj = bindValue; + try { + bindValueObj = JSON.parse(bindValue); + } catch (_) { + bindValueObj = bindValue; + } + return bindValueObj; + } + + async getEmployeePermissions(employeeId) { + const { ctx } = this; + const roleRows = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: employeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + if (!roleRows || roleRows.length === 0) { + return []; + } + + const roleIds = [ ...new Set(roleRows.map(item => item.role_id).filter(Boolean)) ]; + if (roleIds.length === 0) { + return []; + } + + const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, + }); + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + attributes: [ 'path' ], + where: { + id: { + [ctx.app.Sequelize.Op.in]: permissionIds, + }, + status: 1, + type: 'api', + }, + raw: true, + }); + + return permissions.map(item => item.path).filter(Boolean); + } + + async getBindInfo(data = {}) { + const { ctx } = this; + const accountId = Number(data.account_id || data.accountId || data.wms_account_id || data.wmsAccountId); + const code = String(data.code || '').trim(); + + if (!Number.isFinite(accountId) || accountId <= 0 || !code) { + return { + success: false, + code: 0, + data: null, + message: '缺少有效参数 account_id 或 code', + }; + } + + const account = await ctx.model.Account.findOne({ + where: { id: accountId }, + attributes: [ 'id', 'status' ], + raw: true, + }); + if (!account || Number(account.status) !== 1) { + return { + success: false, + code: 0, + data: null, + message: '账号不存在或已禁用', + }; + } + + const redis = this.getPrinterRedis(); + const bindValue = await redis.get(`bind:${code}`); + if (!bindValue) { + return { + success: false, + code: 0, + data: null, + message: '无效code或未绑定', + }; + } + + const employeeRows = await ctx.model.AccountStoreEmployee.findAll({ + where: { + account_id: accountId, + status: 1, + }, + include: [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status', 'auth_end' ], + where: { + status: 1, + project: 'warehouse', + }, + required: true, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + + const now = new Date(); + const warehouseMap = new Map(); + for (const employee of employeeRows) { + const permissions = await this.getEmployeePermissions(employee.id); + if (!permissions.includes('printer.bind')) { + continue; + } + + const store = employee.store; + if (!store) { + continue; + } + + if (store.auth_end && new Date(store.auth_end) < now) { + continue; + } + + warehouseMap.set(String(store.id), { + id: Number(store.id), + name: store.company_name, + }); + } + + const warehouses = Array.from(warehouseMap.values()); + if (warehouses.length === 0) { + return { + success: true, + code: 200, + data: { + warehouses: [], + }, + message: '无可绑定仓库', + }; + } + + const tempCode = crypto.randomBytes(16).toString('hex').toUpperCase(); + const tokenPayload = { + accountId, + code, + bindValue, + createdAt: new Date().toISOString(), + warehouses: warehouses.map(item => item.id), + }; + await redis.setex(`binding_token:${tempCode}`, 300, JSON.stringify(tokenPayload)); + + return { + success: true, + code: 200, + data: { + warehouses, + tempCode, + }, + message: '获取绑定信息成功', + }; + } + + async bindByTempCode(data = {}) { + const { ctx } = this; + const tempCode = String(data.temp_code || data.tempCode || '').trim(); + const printer = String(data.printer || data.workbench_name || data.workbenchName || '').trim(); + const warehouse = Number(data.warehouse || data.warehouse_id || data.warehouseId); + + if (!tempCode || !printer || !Number.isFinite(warehouse) || warehouse <= 0) { + return { + success: false, + code: 0, + data: null, + message: '参数缺失', + }; + } + + const redis = this.getPrinterRedis(); + const tokenText = await redis.get(`binding_token:${tempCode}`); + if (!tokenText) { + return { + success: false, + code: 0, + data: null, + message: '临时code无效或已过期', + }; + } + + let tokenData = null; + try { + tokenData = JSON.parse(tokenText); + } catch (_) { + tokenData = null; + } + + if (!tokenData || !tokenData.code || !Array.isArray(tokenData.warehouses)) { + return { + success: false, + code: 0, + data: null, + message: '临时code数据异常', + }; + } + + if (!tokenData.warehouses.includes(warehouse)) { + return { + success: false, + code: 0, + data: null, + message: '仓库无绑定权限', + }; + } + + const Store = ctx.model.Store; + const warehouseInfo = await Store.findOne({ + where: { + id: warehouse, + status: 1, + }, + raw: true, + }); + if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { + return { + success: false, + code: 0, + data: null, + message: '仓库id校验失败', + }; + } + + const PrintComputer = ctx.model.PrintComputer; + let computerId = null; + const existComputer = await PrintComputer.findOne({ + where: { + warehouse_id: warehouse, + name: printer, + }, + }); + if (existComputer) { + if (Number(existComputer.status) === 1) { + return { + success: false, + code: 0, + data: null, + message: '该仓库下打印台名称已存在且可用', + }; + } + computerId = existComputer.id; + } else { + const newComputer = await PrintComputer.create({ + warehouse_id: warehouse, + name: printer, + status: 0, + }); + computerId = newComputer.id; + } + + const bindValueObj = this.normalizeBindValue(tokenData.bindValue); + const printServiceUrl = ctx.app.config.printService.url; + let printServiceResult = null; + try { + const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { + method: 'POST', + contentType: 'json', + data: { + code: tokenData.code, + printer, + warehouse, + roomId: bindValueObj && bindValueObj.uniqueId ? bindValueObj.uniqueId : '', + computerId, + }, + dataType: 'json', + }); + printServiceResult = res.data; + } catch (err) { + printServiceResult = { success: false, error: '打印服务通讯失败' }; + } + + if (printServiceResult && printServiceResult.status === 'fail') { + return { + success: false, + code: 0, + data: { + printer, + warehouse, + printServiceResult, + }, + message: printServiceResult.message || '打印服务失败', + }; + } + + await redis.del(`binding_token:${tempCode}`); + + return { + success: true, + code: 200, + data: { + code: tokenData.code, + printer, + warehouse, + computerId, + printServiceResult, + }, + message: '绑定成功', + }; + } +} + +module.exports = PrintApiService; diff --git a/app/service/apiMethods/test.js b/app/service/apiMethods/test.js index 7630273..b9ab6b0 100644 --- a/app/service/apiMethods/test.js +++ b/app/service/apiMethods/test.js @@ -11,19 +11,13 @@ class testServer extends Service { this.addon = require(app.appRoot + '/native/addons/subset_selector.node'); this.addonLoaded = true; this.ctx.logger.info('[FibonacciService] C++插件加载成功'); - console.log(this.addon); } catch (error) { - this.addonLoaded = false; this.ctx.logger.error('[FibonacciService] C++插件加载失败:', error); } } - async entryorderConfirm(data) { - const { app, ctx } = this; - return await ctx.service.systems.entryOrder.entryorderConfirm(data.id, data.isCompleted); - } async playbackRequest(data) { const { app } = this; try { @@ -33,8 +27,9 @@ class testServer extends Service { }, }); if (entryOrder) { - console.log('entryOrder', entryOrder.body); - const body = await this.ctx.service.systems.qimenQuery.sendRequest(entryOrder.url, entryOrder.body); + const body = await this.app.qimenClient.sendRequest(entryOrder.url, entryOrder.body, {}, { + ctx: this.ctx, + }); return { body }; } throw new Error('无历史请求数据'); @@ -65,8 +60,6 @@ class testServer extends Service { raw: true, }); - console.log('查询到的订单ID数量:', deliveryResult.length); - if (deliveryResult.length === 0) { return { orderIds: [], @@ -93,8 +86,6 @@ class testServer extends Service { raw: true, }); - console.log('查询到的商品记录数量:', itemsResult.length); - // 4. 按订单分组商品 const itemsByOrder = {}; itemsResult.forEach(item => { @@ -116,8 +107,6 @@ class testServer extends Service { }; }).filter(order => order.skus.length > 0); // 过滤掉没有商品的订单 - console.log('有效订单数量:', orders.length); - if (orders.length === 0) { return { orderIds: [], diff --git a/app/service/apiMethods/user.js b/app/service/apiMethods/user.js new file mode 100644 index 0000000..f4cca86 --- /dev/null +++ b/app/service/apiMethods/user.js @@ -0,0 +1,15 @@ +'use strict'; + +const Service = require('egg').Service; + +class UserApiService extends Service { + async getUserByTempCode(data) { + return await this.ctx.service.systems.auth.user.getUserByTempCode(data); + } + + async bindAccountByTempCode(data) { + return await this.ctx.service.systems.auth.user.bindAccountByTempCode(data); + } +} + +module.exports = UserApiService; diff --git a/app/service/im.js b/app/service/im.js new file mode 100644 index 0000000..b8429dc --- /dev/null +++ b/app/service/im.js @@ -0,0 +1,172 @@ +'use strict'; +/** + * IM 相关服务 + * @author 刘付明仁 2026-05-01 创建 + * 返回通用格式:{ code: number, message: string, data: any } + * code: 200 表示成功,其他表示失败 + * message: 错误或成功消息 + * data: 具体数据内容,成功时通常包含请求结果,失败时可以为 null 或错误详情 + */ +const Service = require('egg').Service; + +class ImService extends Service { + async ping(data) { + const { requestId } = data || {}; + return { + code: 200, + message: 'pong', + data: { + requestId, + }, + }; + } + async ssoCodeToId(data) { + const { code } = data || {}; + const safeCode = String(code || '').trim(); + + if (!safeCode) { + return { + code: 400, + message: 'code不能为空', + data: null, + }; + } + // 测试例外,如果code以"test-"开头,则直接返回模拟数据 + if (safeCode.startsWith('test-')) { + return { + code: 200, + message: 'success', + data: { + employees_id: 4, + employees_name: '阿猫', + subject: { + id: 100000, + name: '测试仓', + type: 'warehouse', + }, + avatar: '', + }, + }; + } + const cacheKey = `im:sso:code:${safeCode}`; + const cachedUser = await this.app.getCacheAsync(cacheKey); + + if (!cachedUser || !cachedUser.employees_id || !cachedUser.employees_name || !cachedUser.subject) { + return { + code: 404, + message: 'code无效或已过期', + data: null, + }; + } + + await this.app.delCacheAsync(cacheKey); + const resultData = { + code: 200, + message: 'success', + data: { + employees_id: cachedUser.employees_id, + employees_name: cachedUser.employees_name, + subject: cachedUser.subject, + avatar: cachedUser.avatar, + }, + }; + console.log('SSO code converted to user info:', resultData); + return resultData; + } + /** + * 获取主体员工信息 + * @param {Object} data 请求数据,包含 store_id + * @return {Promise<{code: number, message: string, data: Array}>} 响应数据,包含员工列表 + */ + async getStoreEmployees(data) { + const { store_id } = data || {}; + const safeStoreId = Number(store_id); + if (!safeStoreId) { + return { + code: 400, + message: 'store_id不能为空或无效', + data: null, + }; + } + + const store = await this.ctx.model.Store.findByPk(safeStoreId, { + attributes: [ 'id', 'company_name', 'project' ], + raw: true, + }); + + if (!store) { + return { + code: 404, + message: '主体不存在', + data: null, + }; + } + + const employees = await this.ctx.model.AccountStoreEmployee.findAll({ + where: { + store_id: safeStoreId, + status: 1, + }, + attributes: [ 'id', 'real_name' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (!employees || employees.length === 0) { + return { + code: 200, + message: 'success', + data: [], + }; + } + + const employeeIds = employees.map(item => String(item.id)); + const avatarRefs = await this.ctx.model.FileReference.findAll({ + where: { + business_type: 'avater', + business_id: employeeIds, + }, + include: [{ + model: this.ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + attributes: [ 'business_id', 'created_at' ], + order: [[ 'created_at', 'DESC' ]], + }); + + const avatarMap = new Map(); + for (const ref of avatarRefs) { + const employeeId = String(ref.business_id || '').trim(); + if (!employeeId || avatarMap.has(employeeId)) { + continue; + } + avatarMap.set(employeeId, ref.file && ref.file.file_url ? ref.file.file_url : ''); + } + + const subject = { + id: String(store.id), + name: String(store.company_name || ''), + type: String(store.project || ''), + }; + + const list = employees.map(item => { + const employeeId = String(item.id); + return { + employees_id: employeeId, + employees_name: String(item.real_name || ''), + subject, + avatar: avatarMap.get(employeeId) || '', + }; + }); + + return { + code: 200, + message: 'success', + data: list, + }; + } +} + +module.exports = ImService; diff --git a/app/service/inbox/ai.js b/app/service/inbox/ai.js new file mode 100644 index 0000000..37d2ab4 --- /dev/null +++ b/app/service/inbox/ai.js @@ -0,0 +1,430 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * AI 推理引擎。 + * 负责调用 DeepSeek API 进行多轮推理:思考→调函数→评估→(重复或输出)。 + * 函数注册、分组管理等纯工具箱逻辑在 inbox/functions.js 中。 + */ +class InboxAIService extends Service { + + /** + * 调用 DeepSeek API。 + * + * @param {Array<{role: string, content: string}>} messages 消息列表。 + * @param {Object} [options] 额外选项。 + * @return {Promise} AI 返回的文本内容。 + */ + async callDeepSeek(messages, options = {}) { + const { ctx } = this; + const apiKey = ctx.app.config.deepseek.apiKey; + const baseUrl = ctx.app.config.deepseek.baseUrl || 'https://api.deepseek.com'; + + if (!apiKey) { + throw new Error('DeepSeek API Key 未配置'); + } + + const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + contentType: 'json', + dataType: 'json', + headers: { Authorization: `Bearer ${apiKey}` }, + data: { + model: 'deepseek-v4-pro', + messages, + temperature: options.temperature ?? 0, + max_tokens: options.maxTokens ?? 1000, + }, + timeout: options.timeout || 30000, + }); + + if (result.status !== 200 || !result.data) { + throw new Error(`DeepSeek 请求失败, HTTP ${result.status}`); + } + + let content = result.data.choices?.[0]?.message?.content || ''; + const reasoning = result.data.choices?.[0]?.message?.reasoning_content || ''; + const finishReason = result.data.choices?.[0]?.finish_reason || ''; + + // 推理模型会把 max_tokens 消耗在 reasoning 上,导致 content 为空(finish_reason=length) + if (!content.trim() && finishReason === 'length') { + ctx.logger.warn( + `[inbox ai] DeepSeek 输出被截断: reasoning=${reasoning.length} 字符, content 为空, finish_reason=length` + ); + throw new Error('DeepSeek 输出被截断(max_tokens 被推理过程占满),请提高 max_tokens'); + } + + // 清理 markdown 代码块 + content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); + content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); + return content.trim(); + } + + /** + * 获取智能对话历史上下文。 + * 同一群 + 同一用户 → 最近 N 条消息(含 AI 回复),用于多轮对话短期记忆。 + * 按创建时间升序排列,并为每条消息附加序号供 AI 追踪。 + * + * @param {Object} opts 查询选项。 + * @param {number} [opts.parentId] 当前消息的 parent_id(兼容旧参数)。 + * @param {number} [opts.maxMessages=5] 最大历史消息数。 + * @return {Promise>} 历史消息列表。 + */ + async getConversationHistory(opts = {}) { + const parentId = Number(opts.parentId) || 0; + const maxMessages = Math.min(10, Math.max(1, Number(opts.maxMessages) || 5)); + + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + const userId = String(ctx.inboxContext?.user_id || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + // 排除当前消息本身(parentId=当前消息id;recallHistory 时取上下文注入的入站消息id), + // 避免"当前请求"混入历史导致 AI 重复处理 + const excludeId = parentId || Number(ctx.inboxContext?.inbound_message_id) || 0; + + // 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯 + if (!groupId || !userId || !warehouseId) { + if (!parentId) return []; + try { + const history = []; + let currentId = parentId; + const visited = new Set(); + while (currentId && history.length < maxMessages) { + if (visited.has(currentId)) break; + visited.add(currentId); + const msg = await InboxMessage.findOne({ + attributes: [ 'id', 'parent_id', 'direction', 'content' ], + where: { id: currentId }, + raw: true, + }); + if (!msg) break; + history.unshift({ role: msg.direction === 'inbound' ? 'user' : 'assistant', content: msg.content || '' }); + currentId = msg.parent_id; + } + return history; + } catch (error) { + ctx.logger.warn(`[inbox ai] 对话历史回退查询失败: ${error.message}`); + return []; + } + } + + // 智能查询:同一群,最近 maxMessages 条(入站+出站混合,含所有成员) + try { + const messages = await InboxMessage.findAll({ + attributes: [ 'id', 'parent_id', 'direction', 'content', 'user_id', 'user_name', 'created_at' ], + where: { + warehouse_id: warehouseId, + group_id: groupId, + direction: { [Op.in]: [ 'inbound', 'outbound' ] }, + ...(excludeId ? { id: { [Op.ne]: excludeId } } : {}), + }, + order: [[ 'created_at', 'DESC' ]], + limit: maxMessages, + raw: true, + }); + + if (messages.length === 0) return []; + + // 升序排列,附加上下文信息供 AI 判断真人接管 + const blockedUsers = ctx.inboxContext?._blockedUserIds || new Set(); + return messages.reverse().map(msg => { + const u = String(msg.user_id || '').trim(); + const name = String(msg.user_name || '').trim(); + const isBlocked = u && blockedUsers.has(u); + return { + role: msg.direction === 'inbound' ? 'user' : 'assistant', + content: msg.content || '', + user_id: u || null, + user_name: name || null, + blocked: isBlocked, + }; + }); + } catch (error) { + ctx.logger.warn(`[inbox ai] 智能对话历史查询失败: ${error.message}`); + return []; + } + } + + /** + * DeepSeek 多轮推理:思考→调函数→评估→(重复或输出)。 + * + * 每轮 AI 返回 JSON,通过 action 字段决定行为: + * { "action": "call", "function": "函数名", "params": {...}, "reason": "..." } + * { "action": "reply", "reply": "最终回复内容" } + * + * 最多 MAX_ROUNDS 轮,防止无限循环。 + * + * @param {Object} data 消息数据。 + * @param {string} data.content 消息正文。 + * @param {Object} [data.ext_data] 透传数据。 + * @param {number} [data.parentId] 父消息ID。 + * @return {Promise<{reply: string, functionName: string|null, functionResult: Object|null}>} AI 回复。 + */ + async processWithAI(data = {}) { + const { ctx } = this; + const content = String(data.content || '').trim(); + if (!content) { + return { reply: '消息正文为空,无法处理', functionName: null, functionResult: null }; + } + + const funcSvc = ctx.service.inbox.functions; + const groupsSvc = ctx.service.inbox.groups; + const activeGroups = groupsSvc.resolveActiveGroups(); + ctx.logger.info(`[inbox ai] 当前活跃分组: ${activeGroups.join(', ')}`); + + const functionListText = groupsSvc.buildFunctionListText(activeGroups); + if (!functionListText) { + ctx.logger.info('[inbox ai] 当前上下文无可用的 AI 函数'); + return { reply: null, functionName: null, functionResult: null }; + } + + // 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文 + const history = await this.getConversationHistory({ + parentId: data.parentId, + maxMessages: 10, + }); + const historyContext = history.length > 0 + ? history.map(h => { + const tag = h.blocked ? '[已屏蔽]' : ''; + return `[历史]${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}${tag}: ${h.content}`; + }).join('\n') + : '(无历史)'; + + const MAX_ROUNDS = 5; + const executedFunctions = []; + const thoughts = []; + let finalReply = null; + let lastFunctionName = null; + let lastFunctionResult = null; + let jsonRetryNote = ''; + + const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 +已注册函数:\n${functionListText}\n +=== 群最近对话历史 === +${historyContext} +=== + +对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。 +如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。 + +【历史消息边界 - 最高优先级】 +- 以上带 [历史] 前缀的记录均为群历史消息,**全部已处理完毕**,仅作背景参考(判断是否有人已接管等),不是待处理请求 +- 严禁把历史记录中的运单号/订单号/地址/售后诉求等当作当前用户的新请求;严禁对历史记录中的请求重复调用函数或重复创建工单 +- 只有最后一条不带 [历史] 前缀的用户消息才是本次待处理请求,所有函数参数只能从这条当前消息中提取 +- 当前消息未提供运单号/订单号等必填参数时,必须先向用户确认,严禁从历史记录中拼凑参数 + +你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: + +如果还需要调用函数获取信息: +{ + "action": "call", + "function": "函数名", + "params": { "参数名": "参数值" }, + "reason": "为什么需要这个函数" +} + +如果信息充足可以回复用户了: +{ + "action": "reply", + "reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)" +} + +如果消息无需回复(用户只是确认、道谢、告别或表示自己处理): +{ + "action": "silent" +} + +真人接管判断规则(优先级最高,先于所有其他规则): +- 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent +- 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户 +- 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复 + +一般约束: +- 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复 +- 同一函数不要重复调用(除非参数不同) +- 信息中如果携带了@标记,说明信息是针对某个特定用户的,请注意是否需要回复该用户 +- 如果函数执行失败,换其他方式或直接告知用户 +- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 +- silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88") +- 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候 +- 【快递群专项】快递客服发出的进度/结果反馈("已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收"等)严禁 silent,必须先调用 handleExpressFeedback 记录反馈再回复 +- 无法判断时,宁可回复也不要 silent +- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定 +- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品 +- searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品 +- searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接 +- searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对 +- searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理 +- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,pick_requirements 为拣货要求、recheck_requirements 为眼球复核要求(merge_requirements=Y 要求合并时均与打包要求一致),用户问及时告知 +- searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户 +- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 +- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史 +- 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用 +- 【规则 - requestPickup】货主售后群/仓库客服群中客户要求上门揽收/取件(如"揽收""上门取件""退货取件""寄回""让快递来拿"等)且提供了运单号时,调用 requestPickup(keyword=运单号,多个用逗号分隔)。函数会创建揽收售后工单,并优先转发到对应快递的揽收群(未配置揽收群时回退到售后群);返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时必须给出运单号与处理结果,严禁把售后单号(AS 开头编号)回复给用户 +- 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - handleExpressFeedback】快递售后群中,快递客服反馈处理进度/结果(如"已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收""加急处理"等)且消息含运单号时,必须调用 handleExpressFeedback(keyword=运单号,多个用逗号分隔)。该函数会自动查找已有售后工单追加反馈并回信到相关群,无工单则自动创建。严禁把快递客服的进度/结果反馈判定为无需处理而 silent;若消息无运单号,先用 recallHistory 或询问确认运单号,严禁跳过 +- 【规则 - handleExpressFeedback 证据核实】快递售后群中快递方发消息要求"提供交易记录截图/未收到依据/核实签收/带日期单号"等证据类诉求且消息含运单号时,同样必须调用 handleExpressFeedback(as_sub_type=verify_delivery),由函数创建售后工单并回信到货主售后群;严禁仅回复"收到/已记录"等确认话术而不调用函数 +- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/催促退回/催件/催派送/尽快安排派送"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求,urge=催件/催派送类诉求;注意区分:"催退回/催促退回"用 return,"催件/催派送/尽快安排派送"用 urge,严禁把催件判定为 return);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - weishoudao】货主售后群中客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时,调用 weishoudao 创建核实签收售后工单,并把"运单号+核实签收"转发到对应快递群;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - changeExpress】货主售后群中客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时,调用 changeExpress(keyword=订单号,express=目标快递名称或编码);仅待处理表中未分配快递的订单可以修改,已分配快递或不在待处理表的订单不能修改;返回的 data.message 是模板消息必须原样回复;若消息中缺订单号或目标快递,先向客户确认再调用 +- 【规则 - queryPackVideo】用户询问"打包视频/打包录像/装箱视频"且提供了运单号时,调用 queryPackVideo 查询(散单按订单、团购单按波次找打包记录);仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - queryWeight】用户询问"查重/重量/核实重量/核重/称重"且提供了运单号时,调用 queryWeight 查询运单称重;重量为0时模板输出"未称重";仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用 +- 【规则 - createPostnum】货主售后群中客户要求"出单/打单/打印单/催发货/分配快递号"且提供了订单号时,调用 createPostnum(keyword=订单号,多个用逗号分隔);仅待处理表已审核且未分配快递号的订单可分配,函数会走分配流程并按结果返回"已分配+已回传"或"分配失败,等待客服人工处理"模板;返回的 data.message 是模板消息必须原样回复;若消息中无订单号,先向客户确认订单号再调用 +- 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明 +- 【规则 - queryWarehouseAddress】用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时,调用 queryWarehouseAddress 查询仓库配置中的 receiver_address;返回的 data.message 是模板消息必须原样回复 +- 【模板消息 - handleStoreFeedback】handleStoreFeedback 返回的 data.message 是已排版好的模板消息(运单号+问题类型+"稍后客服将人工核实跟进"),必须原样作为最终回复输出,禁止改写、删减或增补内容,严禁补充售后单号 +- 用户发送"查退回+运单号"时,调用 queryReturn 查询退回明细,不要误调 queryOrder 或 interceptWaybill +- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用 +- 【历史失败回复免疫】群历史中 AI 的历史回复(尤其含"失败""异常""无法处理"等字样的兜底回复)只是历史记录,不代表当前功能不可用;严禁模仿、引用这类历史回复,也严禁据此判断函数不可用而拒绝调用;登记/操作/查询类请求必须实际调用对应函数获取最新结果`; + + // 多轮推理循环 + for (let round = 1; round <= MAX_ROUNDS; round++) { + const contextLines = []; + if (executedFunctions.length > 0) { + contextLines.push('已执行的函数及结果:'); + executedFunctions.forEach((f, i) => { + contextLines.push( + ` ${i + 1}. ${f.name}(${JSON.stringify(f.params)}) → ${JSON.stringify(f.result)}` + ); + }); + } + + const messages = [ + { role: 'system', content: systemPrompt }, + ...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []), + { role: 'user', content: round === 1 + ? content + : (jsonRetryNote ? `${jsonRetryNote}\n` : '') + (executedFunctions.length > 0 + ? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮` + : `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`), + }, + ]; + + let raw = ''; + try { + // 推理模型(deepseek-v4-pro)需要充足 max_tokens:推理过程会先占用配额,过小会导致 content 被截断为空 + raw = await this.callDeepSeek(messages, { maxTokens: 4000 }); + ctx.logger.info(`[inbox ai] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`); + + const result = JSON.parse(raw); + + // 记录思考过程 + thoughts.push({ + round, + action: result.action || 'unknown', + function: result.function || null, + params: result.params || null, + reason: result.reason || null, + }); + + if (result.action === 'reply') { + finalReply = String(result.reply || '').trim(); + if (!finalReply) finalReply = '已处理完成'; + break; + } + + if (result.action === 'silent') { + // 已调用过操作类函数(非 recallHistory)→ 必须回复结果,不能 silent + const actionFunctions = executedFunctions.filter(f => f.name !== 'recallHistory'); + if (actionFunctions.length > 0) { + ctx.logger.info('[inbox ai] 已有操作类函数调用,忽略 silent 继续要求回复'); + continue; + } + ctx.logger.info('[inbox ai] AI 判定无需回复,跳过回执'); + return { reply: null, functionName: null, functionResult: null, thoughts, skip: true }; + } + + if (result.action === 'call' && result.function) { + const fnName = String(result.function).trim(); + const params = result.params || {}; + + if (fnName === 'none' || fnName === 'stop') { + finalReply = result.reply || '已处理完成'; + break; + } + + lastFunctionName = fnName; + lastFunctionResult = await funcSvc.callFunction(fnName, params); + executedFunctions.push({ name: fnName, params, result: lastFunctionResult }); + + // 补充函数执行结果到思考记录 + const lastThought = thoughts[thoughts.length - 1]; + if (lastThought) lastThought.functionResult = lastFunctionResult; + ctx.logger.info(`[inbox ai] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`); + + // 函数携带模板消息(direct_reply=true)→ 直接作为最终回复,不再交由 AI 改写 + // 允许 message 为空字符串(如开门:靠 extend_props 指令驱动,文案为空) + const hasDirectReply = !!(lastFunctionResult + && lastFunctionResult.data + && lastFunctionResult.data.direct_reply === true); + const directReply = hasDirectReply + ? String(lastFunctionResult.data.message || '') + : ''; + if (hasDirectReply) { + ctx.logger.info(`[inbox ai] 函数 ${fnName} 返回模板消息,直接回复 (length=${directReply.length})`); + finalReply = directReply; + break; + } + + // 最后一轮强制输出 + if (round === MAX_ROUNDS) { + finalReply = lastFunctionResult?.data?.message + || lastFunctionResult?.data?.greeting + || JSON.stringify(lastFunctionResult?.data || lastFunctionResult); + } + continue; + } + + // 无法解析 → 尝试提取 reply + finalReply = result.reply || result.message || '抱歉,暂时无法处理您的请求'; + break; + } catch (error) { + ctx.logger.warn(`[inbox ai] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`); + + // 模型输出疑似被截断的 JSON → 提醒后重试,避免把原始 JSON 当作回复发给用户 + if (error instanceof SyntaxError && raw) { + const trimmedRaw = String(raw).trim(); + if (trimmedRaw.startsWith('{') || trimmedRaw.startsWith('[')) { + jsonRetryNote = '上一轮模型输出不是合法 JSON(疑似截断),请重新输出完整合法的纯 JSON,不要包含任何额外文字'; + continue; + } + // 不是 JSON → 当作文本回复 + finalReply = trimmedRaw; + break; + } + + // 最后一轮兜底 + if (round === MAX_ROUNDS) { + finalReply = '抱歉,暂时无法处理您的请求,请稍后重试'; + } + continue; + } + } + + // 无回复的兜底(finalReply 为空串时保留,不覆盖——开门等指令允许空文案回执) + if ((finalReply === null || finalReply === undefined) && lastFunctionResult) { + finalReply = lastFunctionResult?.data?.message + || lastFunctionResult?.data?.greeting + || (lastFunctionResult?.success !== false ? '操作已完成' : lastFunctionResult?.error || '处理完成'); + } + if (finalReply === null || finalReply === undefined) { + finalReply = '抱歉,暂时无法处理您的请求'; + } + + ctx.logger.info(`[inbox ai] 最终回复: ${finalReply}`); + return { + reply: finalReply, + functionName: lastFunctionName, + functionResult: lastFunctionResult, + thoughts, + }; + } +} + +module.exports = InboxAIService; diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js new file mode 100644 index 0000000..dd89a18 --- /dev/null +++ b/app/service/inbox/functions.js @@ -0,0 +1,4766 @@ +'use strict'; + +const Service = require('egg').Service; + +// 群类型常量定义统一收口到 inbox/groups.js +const { GROUP } = require('./groups'); +const { pickNoticeTimeOrderIds } = require('../../lib/intercept_time'); + +/** + * 提取车牌号(与 wms_inbox_number_rule 车牌取号规则同版:支持蓝/黄牌、新能源绿牌、 + * 挂车、警/学/港澳牌及 ·/· 分隔符)。 + * 省份简称兼容简体与异体写法(如 粤/粵)。 + * 只取第一个匹配,无匹配返回空字符串。 + * @param {string} text 消息正文。 + * @return {string} 车牌号。 + */ +function extractLicensePlate(text) { + const raw = String(text || ''); + const m = raw.match(/[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤粵青藏川宁琼使领][A-HJ-NP-Z][·.]?(?:[DF][A-HJ-NP-Z0-9]{5}|[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])/); + return m ? m[0] : ''; +} + +/** + * 回复配置 create_work_order=0 时,v2 引擎注入 ctx.inboxContext.skip_work_order, + * 函数照常执行但建单前应跳过工单登记。 + * @param {Object} ctx Egg 上下文。 + * @return {boolean} 是否跳过工单登记。 + */ +function shouldSkipWorkOrder(ctx) { + return !!(ctx && ctx.inboxContext && ctx.inboxContext.skip_work_order === true); +} + +/** + * 拦截请求按取消订单处理(未同步订单/手工单规则): + * 订单状态置 cancel,释放 stock 建单锁与 storage 储位锁,不写拦截状态。 + * 已同步订单(sync=fin)取消时按订单明细回补 stock quantity(同步出库冲回), + * 保证取消后两层可用数守恒。 + * 整体在一个事务内执行,失败回滚并告警,不阻断主流程。 + * + * @param {Object} ctx Egg 上下文。 + * @param {Object} orderModel 当前仓库订单模型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} orderIds 订单ID数组。 + * @param {Array} syncedOrderIds 其中已同步的订单ID(取消时需回补 stock quantity)。 + * @param {Object} operator 操作人信息({ id, name })。 + * @return {Promise} + */ +async function cancelOrderForInterceptRequest(ctx, orderModel, warehouseId, orderIds, syncedOrderIds, operator) { + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return; + } + + const syncedIds = Array.isArray(syncedOrderIds) ? syncedOrderIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0) : []; + const now = new Date(); + const transaction = await ctx.model.transaction(); + + try { + await orderModel.update( + { status: 'cancel', step: 9, outbound_status: 'padding', updated_at: now }, + { where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, warehouse_id: warehouseId }, transaction } + ); + + // 释放储位分配(普通模式:解除锁定/返还实物) + await ctx.service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: orderIds, + transaction, + }); + + // 释放 stock 建单锁(仅未同步订单:已同步订单的建单锁已在同步出库时释放) + const unsyncedIds = orderIds + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0 && !syncedIds.includes(id)); + if (unsyncedIds.length > 0) { + await ctx.service.systemMethods.order.pendingOrder.releaseCreationLockForCancel({ + orderIds: unsyncedIds, + warehouseId, + transaction, + }); + } + + // 已同步订单:回补 stock quantity(同步出库冲回,货物回可用) + if (syncedIds.length > 0) { + const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const cancelOrderItems = await orderItemsModel.findAll({ + where: { order_id: { [ctx.app.Sequelize.Op.in]: syncedIds } }, + attributes: [ 'order_id', 'stock_id', 'plan_qty' ], + raw: true, + transaction, + }); + + for (const item of Array.isArray(cancelOrderItems) ? cancelOrderItems : []) { + const stockId = Number(item && item.stock_id) || 0; + const qty = Number(item && item.plan_qty) || 0; + if (stockId <= 0 || qty <= 0) { + continue; + } + const inboundResult = await ctx.service.systems.stockStore.inbound( + stockId, + qty, + transaction, + { stockId } + ); + if (!inboundResult || inboundResult.success !== true) { + throw new Error( + `未同步/手工单取消回补库存失败: stockId=${stockId}, qty=${qty}, ${(inboundResult && inboundResult.error) || '未知错误'}` + ); + } + } + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback().catch(() => {}); + ctx.logger.warn(`[inbox functions] 未同步/手工单按取消处理失败: ${error.message}`); + return; + } + + // 写入操作日志(失败不影响主流程) + try { + const logSvc = ctx.service?.systems?.operationLog; + if (logSvc && typeof logSvc.createOperationLogs === 'function') { + await logSvc.createOperationLogs( + orderIds.map(orderId => ({ + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_INTERCEPT_REQUEST_CANCELED', + operator: operator || { id: '0', name: 'AI系统' }, + extras: { + warehouseId, + orderId, + message: syncedIds.includes(Number(orderId)) + ? '已同步手工单拦截请求按取消订单处理(库存已回补)' + : '未同步订单拦截请求按取消订单处理', + externalLogType: 'NONE', + }, + })) + ); + } + } catch (logErr) { + ctx.logger.warn(`[inbox functions] 未同步/手工单按取消处理-操作日志失败: ${logErr.message}`); + } + + ctx.logger.info(`[inbox functions] 未同步/手工单按取消处理: ${orderIds.length} 个订单`); +} + +/** + * 站内信函数注册表。 + * 负责注册 AI 可调用的函数(含 handler),支持按分组声明可见性。 + * 分组匹配与筛选逻辑在 {@link InboxGroupsService} 中。 + */ +class InboxFunctionsService extends Service { + /** + * 初始化函数注册表。 + * @param {Object} ctx Egg.js 上下文。 + */ + constructor(ctx) { + super(ctx); + /** @type {Map} */ + this.registry = new Map(); + this.registerBuiltinFunctions(); + } + + /** + * 注册内置函数。 + */ + registerBuiltinFunctions() { + this.register('help', { + description: '帮助指令:枚举当前仓库当前群可见(按群类型白名单过滤)的售后类型与子类型(含关键词),返回可用指令清单(back_text),供回复模板 {back_text} 占位符渲染', + params: {}, + groups: [ GROUP.COMMON ], + weight: 0, + keywords: [ '指令', '帮助' ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + let cfg = null; + try { + cfg = await ctx.service.inbox.v2.config.load(warehouseId); + } catch (e) { + ctx.logger.warn(`[inbox functions] help 加载 v2 配置失败: ${e.message}`); + } + + // 类型名映射(含排序,帮助清单按类型 sort_order 分组输出) + let typeNameMap = {}; + let typeOrderMap = {}; + try { + const types = await ctx.model.AfterSaleType.findAll({ attributes: [ 'type', 'name', 'sort_order' ], raw: true }); + typeNameMap = {}; + typeOrderMap = {}; + for (const t of types) { + typeNameMap[t.type] = t.name; + typeOrderMap[t.type] = Number(t.sort_order) || 0; + } + } catch (e) { /* ignore */ } + + // 关键词按子类型聚合(可见配置) + const kwBySubType = {}; + if (cfg && Array.isArray(cfg.keywords)) { + for (const k of cfg.keywords) { + if (!kwBySubType[k.sub_type_id]) kwBySubType[k.sub_type_id] = []; + kwBySubType[k.sub_type_id].push(k.keyword); + } + } + + const lines = []; + const subTypes = (cfg && cfg.subTypes) ? Object.values(cfg.subTypes) : []; + // 群类型白名单过滤:仅展示当前群可见的子类型(复用 v2 规则引擎的白名单语义; + // 无群上下文时不过滤,兼容 AI 直调 help 的场景) + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const groupSubType = String(ctx.inboxContext?.sub_type || '').trim(); + const visibleSubTypes = groupType && cfg + ? subTypes.filter(st => ctx.service.inbox.v2.rules._groupAllowed(cfg, st.id, groupType, groupSubType)) + : subTypes; + // 按类型 sort_order → 子类型 sort_order → id 排序,保证清单顺序稳定 + visibleSubTypes.sort((a, b) => ( + (typeOrderMap[a.type] || 0) - (typeOrderMap[b.type] || 0) + || (Number(a.sort_order) || 0) - (Number(b.sort_order) || 0) + || (Number(a.id) || 0) - (Number(b.id) || 0) + )); + let lastType = null; + for (const st of visibleSubTypes) { + const tName = typeNameMap[st.type] || st.type; + const kws = kwBySubType[st.id] || []; + // 类型表头仅在该类型首次出现时输出一次 + if (tName !== lastType) { + lines.push(`${tName}:`); + lastType = tName; + } + lines.push(` ${st.name}:关键词:${kws.length > 0 ? kws.join(',') : '(未配置)'}`); + } + const backText = lines.length > 0 ? lines.join('\n') : '(当前仓库未配置可用指令)'; + + return { + success: true, + data: { back_text: backText }, + }; + }, + }); + + this.register('hello', { + description: '问候接口,返回欢迎信息。传入 name 参数可个性化问候', + params: { + name: { type: 'string', required: false, description: '用户名称' }, + }, + groups: [ GROUP.COMMON ], + weight: 0, + keywords: [ '你好', 'hi', 'hello', '在吗' ], + handler: async (params = {}) => { + const name = String(params.name || '').trim(); + const greeting = name ? `你好,${name}!欢迎使用 WMS 站内信服务` : '你好!欢迎使用 WMS 站内信服务'; + return { + success: true, + data: { greeting }, + }; + }, + }); + + this.register('queryPrintBalance', { + description: '查询当前货主的面单余额。根据上下文中的货主ID和仓库ID查询合约中的面单剩余量和锁定量', + params: {}, + groups: [ GROUP.BOUND_STORE_WILDCARD ], + weight: 80, + keywords: [ '面单余额', '打印余额', '快递单余额', '还剩多少单', '面单' ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!Number.isFinite(storeId) || storeId <= 0) { + return { + success: false, + error: '无法获取货主信息,请确认已在已签约的货主上下文中操作', + }; + } + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return { + success: false, + error: '无法获取仓库信息,请确认上下文已正确设置', + }; + } + + try { + const contract = await ctx.model.StoreWarehouse.findOne({ + attributes: [ + 'id', 'store_id', 'warehouse_id', + 'print_quantity', 'print_quantity_locked', + ], + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + raw: true, + }); + + if (!contract) { + return { + success: false, + error: `货主 ${storeId} 在仓库 ${warehouseId} 中无有效合约,请检查货主ID是否正确`, + }; + } + + const available = Math.max(0, contract.print_quantity - contract.print_quantity_locked); + + return { + success: true, + data: { + store_id: contract.store_id, + warehouse_id: contract.warehouse_id, + print_quantity: contract.print_quantity, + print_quantity_locked: contract.print_quantity_locked, + available, + }, + }; + } catch (error) { + return { + success: false, + error: `查询面单余额失败: ${error.message}`, + }; + } + }, + }); + this.register('createWaybill', { + description: '为指定平台单号创建快递单号。根据平台订单号查找发货单并分配快递单号', + params: { + order_code: { type: 'string', required: true, description: '平台订单号' }, + }, + groups: [ GROUP.BOUND_STORE_WILDCARD ], + weight: 90, + keywords: [ '创建快递单', '取号', '分配快递', '生成运单', '快递单号' ], + handler: async (params = {}) => { + const { ctx } = this; + const orderCode = String(params.order_code || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!orderCode) { + return { + success: false, + error: '未提供有效的平台单号,请提供订单编号', + }; + } + + if (!warehouseId || !storeId) { + return { + success: false, + error: '无法获取仓库或货主信息,请确认上下文已正确设置', + }; + } + + try { + const OrderDelivery = await ctx.service.systems.express.getWaybillAsyncOrderDeliveryModel(warehouseId); + if (!OrderDelivery) { + return { success: false, error: `仓库 ${warehouseId} 的发货单表不可用` }; + } + + const orderDelivery = await OrderDelivery.findOne({ + attributes: [ 'id', 'delivery_order_code', 'source_order_codes', 'store_id', 'warehouse_id', 'post_status' ], + where: { + source_order_codes: { [ctx.app.Sequelize.Op.like]: `%${orderCode}%` }, + warehouse_id: warehouseId, + store_id: storeId, + }, + raw: true, + }); + + if (!orderDelivery) { + return { + success: false, + error: `未找到平台单号 ${orderCode} 对应的发货单,请核实单号是否正确`, + }; + } + + // 查已有快递单号(强制同仓校验:同时匹配订单ID与仓库ID) + const existingExpress = await ctx.model.OrderExpress.findOne({ + attributes: [ 'waybill_code', 'logistics_name', 'status' ], + where: { order_id: orderDelivery.id, business_key: 1, warehouse_id: warehouseId }, + raw: true, + }); + + if (existingExpress && existingExpress.waybill_code) { + return { + success: true, + data: { + order_id: orderDelivery.id, + delivery_order_code: orderDelivery.delivery_order_code, + waybill_code: existingExpress.waybill_code, + logistics_name: existingExpress.logistics_name, + existed: true, + }, + }; + } + + // 触发取号 + await ctx.service.systemMethods.order.pendingOrder.allocateExpressCode({ + ids: [ orderDelivery.id ], + }); + + return { + success: true, + data: { + order_id: orderDelivery.id, + delivery_order_code: orderDelivery.delivery_order_code, + message: `已为订单 ${orderCode} 提交快递取号任务,请稍后查询`, + }, + }; + } catch (error) { + return { + success: false, + error: `创建快递单号失败: ${error.message}`, + }; + } + }, + }); + + this.register('searchStock', { + description: '搜索仓库商品(货主级)。返回商品ID/编码/名称/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求/拣货要求/眼球复核要求/要求合并', + params: { + keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, + }, + groups: [ GROUP.BOUND_STORE_WILDCARD ], + weight: 70, + keywords: [ '查商品', '搜商品', '找商品', '商品信息', '库存', '商品' ], + handler: async (params = {}) => { + const { ctx } = this; + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const keyword = String(params.keyword || '').trim(); + const { Op } = ctx.app.Sequelize; + + if (!keyword) return { success: false, error: '请提供搜索关键词' }; + if (!warehouseId || !storeId) return { success: false, error: '无法获取仓库或货主信息' }; + + try { + // 从 stock_barcodes 找匹配条码的 stock_id + const barcodeMatchIds = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id' ], + where: { barcode: { [Op.like]: `%${keyword}%` } }, + raw: true, + }); + const barcodeStockIds = [ ...new Set(barcodeMatchIds.map(b => b.stock_id)) ]; + + // 直接查 stock_warehouse(按货主过滤,不查 stock_store) + const orConditions = [ + { item_code: { [Op.like]: `%${keyword}%` } }, + { item_name: { [Op.like]: `%${keyword}%` } }, + ]; + if (barcodeStockIds.length > 0) { + orConditions.push({ id: { [Op.in]: barcodeStockIds } }); + } + + const items = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements' ], + where: { + store_id: storeId, + [Op.or]: orConditions, + }, + limit: 10, + raw: true, + }); + + if (items.length === 0) { + return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } }; + } + + // 批查条码 + const itemIds = items.map(i => i.id); + const barcodeMap = {}; + if (itemIds.length > 0) { + const barcodes = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id', 'barcode' ], + where: { stock_id: { [Op.in]: itemIds } }, + raw: true, + }); + for (const b of barcodes) { + if (!barcodeMap[b.stock_id]) barcodeMap[b.stock_id] = []; + barcodeMap[b.stock_id].push(b.barcode); + } + } + + // 批查违禁品 + const prohibitedIds = [ ...new Set(items.map(i => i.prohibited_id).filter(Boolean)) ]; + const prohibitedMap = {}; + if (prohibitedIds.length > 0) { + const pts = await ctx.model.ProhibitedType.findAll({ + attributes: [ 'id', 'type_name' ], + where: { id: { [Op.in]: prohibitedIds } }, + raw: true, + }); + for (const p of pts) prohibitedMap[p.id] = p.type_name || ''; + } + + // 批查商品图片(wms_file_reference + wms_file,与 stock.warehouse.list 一致) + const imageUrlMap = {}; + if (itemIds.length > 0) { + const refs = await ctx.model.FileReference.findAll({ + attributes: [ 'business_id' ], + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + where: { + business_type: 'stock', + business_id: { [Op.in]: itemIds.map(String) }, + }, + order: [[ 'display_order', 'ASC' ]], + raw: true, + }); + for (const r of refs) { + const sid = Number(r.business_id); + if (!imageUrlMap[sid]) imageUrlMap[sid] = []; + const url = (r['file.file_url'] && String(r['file.file_url']).trim()) || ''; + if (url) imageUrlMap[sid].push(url); + } + } + + return { + success: true, + data: { + total: items.length, + items: items.map(i => ({ + id: i.id, + item_code: i.item_code, + item_name: i.item_name, + barcode: barcodeMap[i.id]?.[0] || '', + brand_name: i.brand_name || '', + unit: i.stock_unit || '', + gross_weight: i.gross_weight || 0, + is_sn_mgmt: i.is_sn_mgmt === 'Y', + is_shelf_life_mgmt: i.is_shelf_life_mgmt === 'Y', + is_batch_mgmt: i.is_batch_mgmt === 'Y', + stock_qty: i.quantity || 0, + stock_locked: i.locked_quantity || 0, + stock_available: Math.max(0, (i.quantity || 0) - (i.locked_quantity || 0)), + has_images: i.is_images === 'Y', + image_url: imageUrlMap[i.id] || [], + barcodes: barcodeMap[i.id] || [], + box_spec: i.enable_box_spec ? { + length: i.box_length || 0, width: i.box_width || 0, height: i.box_height || 0, + volume: i.box_volume || 0, gross_weight: i.box_gross_weight || 0, + net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0, + } : null, + packing_requirements: i.packing_requirements || '', + pick_requirements: (i.merge_requirements || 'Y') === 'Y' + ? (i.packing_requirements || '') + : (i.pick_requirements || ''), + recheck_requirements: (i.merge_requirements || 'Y') === 'Y' + ? (i.packing_requirements || '') + : (i.recheck_requirements || ''), + merge_requirements: i.merge_requirements || 'Y', + prohibited_type: prohibitedMap[i.prohibited_id] || '', + })), + }, + }; + } catch (error) { + return { success: false, error: `商品搜索失败: ${error.message}` }; + } + }, + }); + + this.register('searchWarehouseStock', { + description: '搜索仓库商品(仓库级,不限货主)。返回商品ID/货主/编码/名称/条码/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求/拣货要求/眼球复核要求/要求合并', + params: { + keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, + }, + groups: [ GROUP.COMMON ], + weight: 60, + keywords: [ '仓库商品', '所有商品' ], + handler: async (params = {}) => { + const { ctx } = this; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const keyword = String(params.keyword || '').trim(); + const { Op } = ctx.app.Sequelize; + + if (!keyword) return { success: false, error: '请提供搜索关键词' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + try { + // 从 stock_barcodes 找匹配条码的 stock_id + const barcodeMatchIds = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id' ], + where: { barcode: { [Op.like]: `%${keyword}%` } }, + raw: true, + }); + const barcodeStockIds = [ ...new Set(barcodeMatchIds.map(b => b.stock_id)) ]; + + // 直接查 stock_warehouse + const orConditions = [ + { item_code: { [Op.like]: `%${keyword}%` } }, + { item_name: { [Op.like]: `%${keyword}%` } }, + ]; + if (barcodeStockIds.length > 0) { + orConditions.push({ id: { [Op.in]: barcodeStockIds } }); + } + + const items = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id', 'store_id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements' ], + where: { + [Op.or]: orConditions, + }, + limit: 10, + raw: true, + }); + + if (items.length === 0) { + return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } }; + } + + // 批查条码 + const itemIds = items.map(i => i.id); + const barcodeMap = {}; + const barcodes = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id', 'barcode' ], + where: { stock_id: { [Op.in]: itemIds } }, + raw: true, + }); + for (const b of barcodes) { + if (!barcodeMap[b.stock_id]) barcodeMap[b.stock_id] = []; + barcodeMap[b.stock_id].push(b.barcode); + } + + // 批查违禁品 + const prohibitedIds = [ ...new Set(items.map(i => i.prohibited_id).filter(Boolean)) ]; + const prohibitedMap = {}; + if (prohibitedIds.length > 0) { + const pts = await ctx.model.ProhibitedType.findAll({ + attributes: [ 'id', 'type_name' ], + where: { id: { [Op.in]: prohibitedIds } }, + raw: true, + }); + for (const p of pts) prohibitedMap[p.id] = p.type_name || ''; + } + + // 批查商品图片(与 stock.warehouse.list 一致) + const itemIds2 = items.map(i => i.id); + const imageUrlMap2 = {}; + if (itemIds2.length > 0) { + const refs2 = await ctx.model.FileReference.findAll({ + attributes: [ 'business_id' ], + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + where: { + business_type: 'stock', + business_id: { [Op.in]: itemIds2.map(String) }, + }, + order: [[ 'display_order', 'ASC' ]], + raw: true, + }); + for (const r of refs2) { + const sid = Number(r.business_id); + if (!imageUrlMap2[sid]) imageUrlMap2[sid] = []; + const url = (r['file.file_url'] && String(r['file.file_url']).trim()) || ''; + if (url) imageUrlMap2[sid].push(url); + } + } + + return { + success: true, + data: { + total: items.length, + items: items.map(i => ({ + id: i.id, + store_id: i.store_id, + item_code: i.item_code, + item_name: i.item_name, + barcode: barcodeMap[i.id]?.[0] || '', + brand_name: i.brand_name || '', + unit: i.stock_unit || '', + gross_weight: i.gross_weight || 0, + is_sn_mgmt: i.is_sn_mgmt === 'Y', + is_shelf_life_mgmt: i.is_shelf_life_mgmt === 'Y', + is_batch_mgmt: i.is_batch_mgmt === 'Y', + stock_qty: i.quantity || 0, + stock_locked: i.locked_quantity || 0, + stock_available: Math.max(0, (i.quantity || 0) - (i.locked_quantity || 0)), + has_images: i.is_images === 'Y', + image_url: imageUrlMap2[i.id] || [], + barcodes: barcodeMap[i.id] || [], + box_spec: i.enable_box_spec ? { + length: i.box_length || 0, width: i.box_width || 0, height: i.box_height || 0, + volume: i.box_volume || 0, gross_weight: i.box_gross_weight || 0, + net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0, + } : null, + packing_requirements: i.packing_requirements || '', + pick_requirements: (i.merge_requirements || 'Y') === 'Y' + ? (i.packing_requirements || '') + : (i.pick_requirements || ''), + recheck_requirements: (i.merge_requirements || 'Y') === 'Y' + ? (i.packing_requirements || '') + : (i.recheck_requirements || ''), + merge_requirements: i.merge_requirements || 'Y', + prohibited_type: prohibitedMap[i.prohibited_id] || '', + })), + }, + }; + } catch (error) { + return { success: false, error: `仓库商品搜索失败: ${error.message}` }; + } + }, + }); + + this.register('queryOrder', { + description: '查询订单。先精确匹配运单号,未命中则模糊搜索发货单号/平台单号。自动定位订单在待处理表/配送表/历史表中的位置,返回订单关键信息和重量。重量字段说明:items_weight 为订单商品总重量(g),waybills[].weighing_weight 为快递实际称重重量(g),仅已分配运单号时才有称重值', + params: { + keyword: { type: 'string', required: true, description: '搜索关键词:运单号(waybill_code,精确匹配)、发货单号(delivery_order_code,模糊)、平台单号(source_platform_code,模糊)' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + weight: 85, + keywords: [ '查订单', '搜订单', '订单详情', '运单号', '快递单号', '发货单' ], + handler: async (params = {}) => { + const { ctx } = this; + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const keyword = String(params.keyword || '').trim(); + const { Op } = ctx.app.Sequelize; + + if (!keyword) return { success: false, error: '请提供搜索关键词' }; + if (!warehouseId || !storeId) return { success: false, error: '无法获取仓库或货主信息' }; + + // 公共:三张订单表配置 + const attributes = [ + 'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes', + 'store_id', 'warehouse_id', 'status', 'step', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'items_count', 'items_total', 'items_weight', 'packages_weight', + 'express_code', 'logistics_name', 'logistics_code', + 'total_amount', 'freight', + 'create_at', 'updated_at', 'delivery_time', + ]; + const tableConfigs = [ + { key: 'current', label: '待处理表', getModel: (f, wid) => f.getCurrentModel(wid) }, + { key: 'dispatch', label: '配送表', getModel: (f, wid) => f.getDispatchModel(wid) }, + { key: 'history', label: '历史表', getModel: (f, wid) => f.getHistoryModel(wid) }, + ]; + const factory = ctx.model.OrderDeliveryFactory; + + /** + * 在三张订单表中查找匹配行 + * @param {Object} where WHERE 条件 + * @return {Object|null} 找到的行(含 table/key),或 null + */ + const findInDeliveryTables = async where => { + for (const cfg of tableConfigs) { + const model = await cfg.getModel(factory, warehouseId); + if (!model) continue; + const row = await model.findOne({ attributes, where, raw: true }); + if (row) return { table: cfg.key, table_label: cfg.label, ...row }; + } + return null; + }; + + try { + let found = null; + + // ========== 第一步:运单号精确匹配 ========== + const exactExpress = await ctx.model.OrderExpress.findOne({ + attributes: [ 'delivery_order_code', 'order_id' ], + where: { + waybill_code: keyword, + store_id: storeId, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (exactExpress && exactExpress.delivery_order_code) { + // 运单精确匹配:先通过序列表定位订单所在分表,命中只查一张表; + // 未命中(存量订单无指针)回退三表按单号遍历 + const exactOrderId = Number(exactExpress.order_id || 0); + if (exactOrderId > 0 && factory && typeof factory.getOrderLocation === 'function') { + try { + const locatedAt = await factory.getOrderLocation(exactOrderId, warehouseId); + if (locatedAt) { + const locatedCfg = tableConfigs.find(cfg => cfg.key === locatedAt); + if (locatedCfg) { + const locatedModel = await locatedCfg.getModel(factory, warehouseId); + if (locatedModel) { + const locatedRow = await locatedModel.findOne({ + attributes, + where: { id: exactOrderId, store_id: storeId }, + raw: true, + }); + if (locatedRow) { + found = { table: locatedCfg.key, table_label: locatedCfg.label, ...locatedRow }; + } + } + } + } + } catch (_err) { /* 定位失败,降级三表遍历 */ } + } + + if (!found && exactOrderId > 0) { + // 序列表未命中 → 三表按订单主键遍历(主键唯一,避免按发货单号跨货主串单) + for (const cfg of tableConfigs) { + const model = await cfg.getModel(factory, warehouseId); + if (!model) continue; + const row = await model.findOne({ + attributes, + where: { id: exactOrderId, store_id: storeId }, + raw: true, + }); + if (row) { + found = { table: cfg.key, table_label: cfg.label, ...row }; + break; + } + } + } + + if (!found && exactExpress.delivery_order_code) { + // 兼容历史运单(order_id 缺失)时按发货单号兜底;已限定 store_id,单号唯一 + found = await findInDeliveryTables({ + store_id: storeId, + delivery_order_code: exactExpress.delivery_order_code, + }); + } + } + + // ========== 第二步:运单未命中 → 模糊搜索发货单号 / 平台单号 ========== + if (!found) { + found = await findInDeliveryTables({ + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.like]: `%${keyword}%` } }, + { source_platform_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + if (!found) { + return { + success: false, + error: `未找到与「${keyword}」匹配的订单,请核实单号后重试(支持运单号精确匹配 / 发货单号模糊 / 平台单号模糊查询)`, + }; + } + + // ========== 第三步:查关联运单信息(按订单主键,不用发货单号)========== + const linkedExpress = await ctx.model.OrderExpress.findAll({ + attributes: [ 'waybill_code', 'logistics_name', 'weighing_weight', 'status', 'is_galaxy_receive' ], + where: { + order_id: found.id, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const hasWaybill = linkedExpress.length > 0; + + return { + success: true, + data: { + table: found.table, + table_label: found.table_label, + order_id: found.id, + delivery_order_code: found.delivery_order_code || '', + source_platform_code: found.source_platform_code || '', + source_order_codes: found.source_order_codes || '', + status: found.status, + step: found.step, + receiver_name: found.name || '', + receiver_mobile: found.mobile || '', + receiver_address: [ found.province, found.city, found.area, found.detail_address ] + .filter(Boolean).join(''), + items_count: found.items_count || 0, + items_total: found.items_total || 0, + // 重量信息(必须区分说明) + items_weight: found.items_weight || 0, + items_weight_note: '商品总重量(克),订单中所有商品SKU的合计重量', + packages_weight: found.packages_weight || 0, + packages_weight_note: '所有包裹总重量(克),订单全部运单称重重量之和', + has_waybill: hasWaybill, + has_waybill_note: hasWaybill ? '' : '该订单尚未分配运单号,无实际称重重量', + waybills: linkedExpress.map(e => ({ + waybill_code: e.waybill_code || '', + logistics_name: e.logistics_name || '', + weighing_weight: e.weighing_weight || 0, + weighing_weight_note: '快递实际称重重量(克),仅已分配运单号并完成称重时才有值', + status: e.status, + is_received: e.is_galaxy_receive === 'Y', + })), + express_code: found.express_code || '', + logistics_name: found.logistics_name || '', + total_amount: found.total_amount, + freight: found.freight, + created_at: found.create_at, + updated_at: found.updated_at, + delivery_time: found.delivery_time || null, + }, + }; + } catch (error) { + return { success: false, error: `订单查询失败: ${error.message}` }; + } + }, + }); + + this.register('recallHistory', { + description: '回顾当前群的最近对话历史(均为已处理完毕的历史记录,仅作背景参考,严禁把其中的运单号/诉求当成新请求)。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号', + params: { + limit: { type: 'number', required: false, description: '获取最近几条,默认5,最大10' }, + }, + groups: [ GROUP.COMMON ], + weight: 0, + keywords: [], + handler: async (params = {}) => { + const { ctx } = this; + const limit = Math.min(10, Math.max(1, Number(params.limit) || 5)); + const history = await ctx.service.inbox.ai.getConversationHistory({ maxMessages: limit }); + if (history.length === 0) { + return { success: true, data: { total: 0, messages: [], hint: '暂无对话历史' } }; + } + return { + success: true, + data: { + total: history.length, + hint: '以下均为已处理完毕的历史记录,仅作背景参考,严禁把其中的运单号/诉求当作新请求处理', + messages: history.map(h => ({ + role: h.role === 'user' ? '用户' : 'AI', + user: h.user_name || h.user_id || null, + blocked: h.blocked || false, + content: h.content || '', + })), + }, + }; + }, + }); + + this.register('createOrder', { + description: '创建发货订单。传入商品 stock_id(来自 searchStock)及数量、收件人信息,使用手工建单流程创建发货单', + weight: 90, + keywords: [ '建单', '创建订单', '下单', '发货', '新建订单' ], + params: { + items: { type: 'array', required: true, description: '商品列表 [{item_id: stock_id, plan_qty: 数量}]' }, + receiverName: { type: 'string', required: true, description: '收件人姓名' }, + receiverPhone: { type: 'string', required: true, description: '收件人电话' }, + receiverProvince: { type: 'string', required: false, description: '省份' }, + receiverCity: { type: 'string', required: false, description: '城市' }, + receiverDistrict: { type: 'string', required: false, description: '区县' }, + receiverAddress: { type: 'string', required: true, description: '详细地址' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const storeId = Number(ctx.inboxContext?.store_id || 0); + const items = Array.isArray(params.items) ? params.items : []; + const name = String(params.receiverName || '').trim(); + const mobile = String(params.receiverPhone || '').trim(); + const province = String(params.receiverProvince || '').trim(); + const city = String(params.receiverCity || '').trim(); + const area = String(params.receiverDistrict || '').trim(); + const detailAddress = String(params.receiverAddress || '').trim(); + + if (!storeId) return { success: false, error: '无法获取货主信息' }; + if (!name) return { success: false, error: '收件人姓名不能为空' }; + if (!mobile) return { success: false, error: '收件人电话不能为空' }; + if (!detailAddress) return { success: false, error: '详细地址不能为空' }; + if (!province) return { success: false, error: '省份不能为空' }; + if (items.length === 0) return { success: false, error: '请提供至少一个商品' }; + + try { + // 适配手工建单格式 + const orderItems = items.map((item, i) => ({ + item_id: Number(item.item_id), + plan_qty: Number(item.plan_qty) || 1, + item_code: String(item.item_code || '').trim(), + item_name: String(item.item_name || '').trim(), + order_line_no: String(i + 1), + })); + + const invalidItems = orderItems.filter(i => !i.item_id || i.item_id <= 0); + if (invalidItems.length > 0) { + return { success: false, error: '商品 item_id 必须为正整数(请先使用 searchStock 获取正确的商品ID)' }; + } + + const result = await ctx.service.systemMethods.order.pendingOrder.createOrder({ + store_id: storeId, + name, + mobile, + tel: '', + province, + city, + area, + detail_address: detailAddress, + items: orderItems, + }); + + return { + success: true, + data: { + deliveryOrderCode: result?.delivery_order_code || result?.deliveryOrderCode || '', + message: result?.message || '发货单创建成功', + }, + }; + } catch (error) { + return { success: false, error: `建单失败: ${error.message}` }; + } + }, + }); + + this.register('blockUser', { + description: '屏蔽用户消息。将当前群和用户加入屏蔽列表,后续不再回复', + params: {}, + groups: [ GROUP.COMMON ], + weight: 0, + keywords: [ '屏蔽', '不回复', '拉黑' ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + const userId = String(ctx.inboxContext?.user_id || '').trim(); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!warehouseId) { + return { success: false, error: '无法获取仓库信息,屏蔽操作失败' }; + } + + if (!groupId && !userId) { + return { + success: false, + error: '无法获取群ID或用户ID,屏蔽操作需要明确的群或用户身份', + }; + } + + try { + const { InboxBlock } = ctx.model; + await InboxBlock.create({ + warehouse_id: warehouseId, + group_id: groupId || null, + user_id: userId || null, + }); + + // 失效屏蔽缓存 + await ctx.service.inbox.processor.invalidateBlockCache(warehouseId); + + const scope = []; + if (groupName) scope.push(`群「${groupName}」`); + if (userName) scope.push(`用户「${userName}」`); + + return { + success: true, + data: { + message: `已屏蔽${scope.join('的')},后续将不再处理你的消息。如需解除屏蔽,请联系客服到WMS解除。`, + }, + }; + } catch (error) { + // 唯一键冲突 = 已屏蔽 + if (error.name === 'SequelizeUniqueConstraintError') { + return { + success: true, + data: { + message: '该群或用户已在屏蔽列表中,无需重复操作。如需解除屏蔽,请联系客服到WMS解除。', + }, + }; + } + return { + success: false, + error: `屏蔽操作失败: ${error.message}`, + }; + } + }, + }); + + this.register('interceptWaybill', { + description: '拦截运单(支持批量)。仅当用户明确要求"拦截/退回/召回/追回"快递运单时才调用。传入运单号(如SF123456),校验权限后批量创建售后工单,并合并通知对应快递的售后群。货主群需验store_id,仓库群无需。严禁:讨论已有售后工单(AS开头)不是拦截请求、询问物流进度不是拦截请求', + weight: 95, + keywords: [ '拦截', '退回', '召回', '追回', '取消快递', '不要了' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + reason: { type: 'string', required: false, description: '拦截原因' }, + }, + groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ], + /** + * 拦截运单处理器:批量创建售后工单,并按波次规则写入订单拦截状态 + * intercept_status='requested' 与拦截时间 intercept_time。 + * @param {Object} params 入参,包含 keyword(运单号)与 reason(拦截原因)。 + * @return {Promise} 处理结果,包含 success 与 data/error。 + */ + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const reason = String(params.reason || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + // 解析多个运单号(逗号/空格/换行分隔) + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:拒绝看起来像售后单号(AS...)的输入,防止误把售后讨论当拦截 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { + success: false, + error: `${asLikeList.join('、')} 看起来是售后工单号而非运单号,如需查询工单请用 queryOrder,如需拦截请提供运单号`, + }; + } + + try { + // 第一步:批量查询运单 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id', + ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (expressList.length === 0) { + return { success: false, error: `未找到运单号「${raw}」,请核实单号后重试` }; + } + + // 第二步:鉴权 + 过滤 + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { + skipped.push(e.waybill_code); + continue; + } + } + validList.push(e); + } + + if (validList.length === 0) { + return { + success: false, + error: `运单${skipped.join('、')}不属于当前货主,无法操作`, + }; + } + + // 第三步:幂等检查(批量查已有工单) + const validIds = validList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: validIds }, + type: 'order', + sub_type: 'intercept', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + + // 过滤掉已存在工单的 + const toCreate = validList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + // 已存在工单对应的运单号(去重):客户回信只给运单号,不暴露售后单号 + const alreadyExistWbs = [ ...new Set(existingASList.map(r => { + const hit = validList.find(v => Number(v.id) === Number(r.waybill_id)); + return hit ? hit.waybill_code : ''; + }).filter(Boolean)) ]; + + if (toCreate.length === 0) { + return { + success: true, + data: { + existed: true, + message: alreadyExistWbs.length > 0 + ? `运单${alreadyExistWbs.join('、')} 已有处理中的拦截申请` + : '拦截信息已登记过,无需重复提交', + after_sale_nos: alreadyExist, + }, + }; + } + + // 第四步:批量创建工单(初始状态 pending,后续根据通知结果升级) + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + // 获取原消息内容,写入工单明细 + let interceptMsgContent = ''; + try { + const iid = ctx.inboxContext?.inbound_message_id; + if (iid) { + const imsg = await ctx.model.InboxMessage.findByPk(iid, { attributes: [ 'content' ], raw: true }); + if (imsg && imsg.content) interceptMsgContent = String(imsg.content); + } + } catch (e) { /* ignore */ } + + const createdNos = []; + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `拦截原因: ${reason}` : '', + interceptMsgContent ? `原消息: ${interceptMsgContent}` : '', + ].filter(Boolean).join('\n'); + + if (shouldSkipWorkOrder(ctx)) { + ctx.logger.info(`[inbox functions] 拦截: skip_work_order,跳过工单登记 ${e.waybill_code}`); + return { success: true, data: { message: '已记录拦截诉求(本次不登记工单)', skipped_work_order: true } }; + } + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: 'intercept', + title: `[AI工单] 拦截请求 - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId || null, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + + ctx.logger.info( + `[inbox functions] 批量拦截: total=${keywords.length} found=${expressList.length} ` + + `valid=${validList.length} created=${createdNos.length} skipped=${skipped.length}` + ); + + // 第4.5步:波次感知拦截处理(仅操作待处理表中的订单) + const orderIds = toCreate.map(e => e.order_id).filter(id => id); + if (orderIds.length > 0) { + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + if (orderModel) { + const orders = await orderModel.findAll({ + attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time', 'sync_status', 'create_channel' ], + where: { + id: { [ctx.app.Sequelize.Op.in]: orderIds }, + step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] }, + }, + raw: true, + }); + + if (orders.length > 0) { + // 按 wave_id 分组查波次信息 + const waveIds = [ ...new Set(orders.map(o => o.wave_id).filter(id => id > 0)) ]; + let waveMap = {}; + if (waveIds.length > 0) { + const waves = await ctx.model.WaveBatch.findAll({ + attributes: [ 'wave_id', 'wave_type', 'wave_status', 'total_orders' ], + where: { wave_id: { [ctx.app.Sequelize.Op.in]: waveIds } }, + raw: true, + }); + waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ])); + } + + const interceptOrderIds = []; + // 未同步订单/手工单:拦截请求按取消订单处理(释放两层锁,不走拦截) + const cancelHandledOrderIds = []; + const syncedCancelOrderIds = []; + const kickOutOrderIds = []; + + // 批量查询散单的称重状态(wms_order_express.weighing_weight) + let weighingMap = {}; + const scatterOrderIds = orders + .filter(o => o.wave_id > 0 && waveMap[o.wave_id] && waveMap[o.wave_id].wave_type === 2) + .map(o => o.id); + if (scatterOrderIds.length > 0) { + const expressRows = await ctx.model.OrderExpress.findAll({ + attributes: [ 'order_id', 'weighing_weight' ], + where: { order_id: { [ctx.app.Sequelize.Op.in]: scatterOrderIds }, warehouse_id: warehouseId }, + raw: true, + }); + weighingMap = Object.fromEntries( + (Array.isArray(expressRows) ? expressRows : []) + .map(r => [ r.order_id, Number(r.weighing_weight || 0) ]) + ); + } + + for (const order of orders) { + const wave = waveMap[order.wave_id]; + const orderId = order.id; + + // 规则1:团购未复核 / 散单未称重 → 设置拦截 + let needIntercept = false; + if (order.wave_id > 0 && wave) { + if (wave.wave_type === 1) { + // 团购波次:未复核 → 拦截 + needIntercept = order.inspection_status !== 'fin'; + } else if (wave.wave_type === 2) { + // 散单波次:未称重 → 拦截(weighing_weight = 0 表示未称重) + const weight = weighingMap[orderId] ?? 0; + needIntercept = weight <= 0; + } + } else { + // 无波次订单:直接拦截 + needIntercept = true; + } + + if (needIntercept) { + const isManualOrder = String(order.create_channel || '').trim().toUpperCase() === 'MANUAL'; + const isUnsyncedOrder = String(order.sync_status || '').trim() !== 'fin'; + if (isManualOrder || isUnsyncedOrder) { + cancelHandledOrderIds.push(orderId); + if (!isUnsyncedOrder) { + syncedCancelOrderIds.push(orderId); + } + } else { + interceptOrderIds.push(orderId); + } + } + + // 规则2:有波次且未打印 + if (order.wave_id > 0 && wave && wave.wave_status < 2) { + const minGroupQty = 13; // 默认大团购阈值 + if (wave.wave_type === 1 && wave.total_orders >= minGroupQty) { + // 大团购:踢出波次 + kickOutOrderIds.push(orderId); + } + // 小团购/散单:仅拦截,不踢出(已在 interceptOrderIds 中处理) + } + } + + // 执行拦截状态设置(订单表 + 运单表;通知拦截时间只在首次发起时写入,不覆盖已有值) + if (interceptOrderIds.length > 0) { + const noticeNow = new Date(); + const interceptIdSet = new Set(interceptOrderIds.map(id => Number(id))); + const fillNoticeOrderIds = pickNoticeTimeOrderIds( + orders.filter(order => interceptIdSet.has(Number(order.id))) + ); + await orderModel.update( + { intercept_status: 'requested' }, + { where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } } + ); + if (fillNoticeOrderIds.length > 0) { + await orderModel.update( + { intercept_time: noticeNow }, + { where: { id: { [ctx.app.Sequelize.Op.in]: fillNoticeOrderIds } } } + ); + } + // 同步更新运单表拦截标记 + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } } + ); + // 写入操作日志(失败不影响主流程) + try { + const logService = ctx.service?.systems?.operationLog; + if (logService && typeof logService.createOperationLogs === 'function') { + await logService.createOperationLogs( + interceptOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(oid), + operationCode: 'ORDER_INTERCEPT_REQUEST', + operator: { id: '0', name: groupName || 'AI系统' }, + extras: { warehouseId, orderId: oid, newInterceptStatus: 'requested' }, + })) + ); + } + } catch (logErr) { + ctx.logger.warn(`[inbox functions] 写入拦截操作日志失败: ${logErr.message}`); + } + ctx.logger.info( + `[inbox functions] 设置拦截状态: ${interceptOrderIds.length} 个订单` + ); + } + + // 未同步/手工单:拦截请求按取消订单处理(释放两层锁) + if (cancelHandledOrderIds.length > 0) { + await cancelOrderForInterceptRequest( + ctx, + orderModel, + warehouseId, + cancelHandledOrderIds, + syncedCancelOrderIds, + { id: '0', name: groupName || 'AI系统' } + ); + } + + // 执行踢出波次 + if (kickOutOrderIds.length > 0) { + await ctx.service.systemMethods.order.wave.batchRemoveOrders({ + ids: kickOutOrderIds, + }); + ctx.logger.info( + `[inbox functions] 踢出大团购波次: ${kickOutOrderIds.length} 个订单` + ); + } + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 波次感知拦截处理失败: ${e.message}`); + } + } + + // 第五步:合并通知对应快递的售后群(按快递分组,每条消息包含该快递的所有运单) + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedTotal = 0; + const notifiedWaybillIds = new Set(); // 记录哪些运单成功通知了至少一个群 + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + + if (afterSalesGroups.length === 0) { + ctx.logger.info(`[inbox functions] 快递 ${code} 未配置售后群,跳过通知`); + continue; + } + + const notifyMsg = info.waybills.join('\n') + '\n拦截'; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: notifyMsg, + ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + // 有售后群即标记为已通知(推送是异步的,不计成败) + const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); + codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[inbox functions] 查售后群失败 code=${code}: ${e.message}`); + } + } + + // 第六步:有通知的工单升级为 pending_feedback + // 同时收集运单号:客户回信只给运单号 + 处理内容,不再暴露售后单号 + const notifiedAsNos = []; + const notNotifiedAsNos = []; + const notifiedWbs = []; + const notNotifiedWbs = []; + for (const e of toCreate) { + const asNo = waybillToAsNo[e.id]; + if (notifiedWaybillIds.has(e.id)) { + notifiedAsNos.push(asNo); + notifiedWbs.push(e.waybill_code); + } else { + notNotifiedAsNos.push(asNo); + notNotifiedWbs.push(e.waybill_code); + } + } + + if (notifiedAsNos.length > 0) { + // 与 handleWorkOrder 一致:设置追踪时间 + 分配客服组 + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, 'order', 'intercept' + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } } + ); + ctx.logger.info( + `[inbox functions] ${notifiedAsNos.length} 个工单已通知快递群,` + + `升级为 pending_feedback,${hours}h 后追踪` + ); + } + + // 构造返回消息(运单号 + 处理内容,不含售后单号) + const parts = []; + if (notifiedWbs.length > 0) { + parts.push(`运单${notifiedWbs.join('、')} 拦截信息已登记,已通知快递群`); + } + if (notNotifiedWbs.length > 0) { + parts.push(`运单${notNotifiedWbs.join('、')} 拦截信息已登记(未配置快递群,需人工跟进)`); + } + if (alreadyExistWbs.length > 0) { + parts.push(`运单${alreadyExistWbs.join('、')} 拦截信息已登记过`); + } + if (skipped.length > 0) { + parts.push(`无权操作: ${skipped.join('、')}`); + } + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + skipped: skipped.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + notified_as_nos: notifiedAsNos, + not_notified_as_nos: notNotifiedAsNos, + notified_groups: notifiedTotal, + waybills: validList.map(e => e.waybill_code), + message: parts.join(';'), + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 批量拦截失败: ${error.message}`); + return { success: false, error: `拦截操作失败: ${error.message}` }; + } + }, + }); + + this.register('requestPickup', { + description: '揽收处理(退货/寄件上门取件)。客户要求上门揽收/取件且提供了运单号时调用:创建揽收售后工单,并把客户原文转发到对应快递的揽收群;该快递未配置揽收群时回退发送到售后群。仅写工单与通知群,不修改订单表和快递表数据', + weight: 88, + keywords: [ '揽收', '上门取件', '取件', '退货取件', '寄回', '上门揽收', '让快递来拿' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + reason: { type: 'string', required: false, description: '揽收备注/原因' }, + }, + groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const reason = String(params.reason || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + // 解析多个运单号(逗号/空格/换行分隔) + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:拒绝看起来像售后单号(AS...)的输入 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { + success: false, + error: `${asLikeList.join('、')} 看起来是售后工单号而非运单号,请提供运单号`, + }; + } + + try { + // 第一步:批量查询运单(仅读取,不做任何修改) + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id', + ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (expressList.length === 0) { + return { success: false, error: `未找到运单号「${raw}」,请核实单号后重试` }; + } + + // 第二步:鉴权 + 过滤(与拦截一致:货主群需验 store_id) + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { + skipped.push(e.waybill_code); + continue; + } + } + validList.push(e); + } + + if (validList.length === 0) { + return { + success: false, + error: `运单${skipped.join('、')}不属于当前货主,无法操作`, + }; + } + + // 第三步:幂等检查(同子类型未完结工单不重复建单) + const validIds = validList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: validIds }, + type: 'order', + sub_type: 'pickup', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + + const toCreate = validList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + if (toCreate.length === 0) { + const replyLines = []; + const existedWbs = validList + .filter(e => existingWaybillIds.has(e.id)) + .map(e => e.waybill_code); + if (existedWbs.length > 0) { + replyLines.push(existedWbs.join('\n')); + replyLines.push('已登记过,无需重复'); + } + if (skipped.length > 0) replyLines.push(`无权操作:${skipped.join('\n')}`); + return { + success: true, + data: { + existed: true, + message: replyLines.join('\n'), + direct_reply: true, + after_sale_nos: alreadyExist, + }, + }; + } + + // 第四步:创建工单(初始状态 pending,后续根据通知结果升级) + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + // 获取原消息内容,写入工单明细与转发文本 + let originalText = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) originalText = String(m.content); + } + } catch (e) { /* ignore */ } + + const createdNos = []; + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `揽收备注: ${reason}` : '', + originalText ? `原文: ${originalText}` : '', + ].filter(Boolean).join('\n'); + + if (shouldSkipWorkOrder(ctx)) { + ctx.logger.info(`[inbox functions] 揽收: skip_work_order,跳过工单登记 ${e.waybill_code}`); + return { success: true, data: { message: '已记录揽收诉求(本次不登记工单)', skipped_work_order: true } }; + } + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: 'pickup', + title: `[AI工单] 揽收请求 - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId || null, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + + ctx.logger.info( + `[inbox functions] 批量揽收: total=${keywords.length} found=${expressList.length} ` + + `valid=${validList.length} created=${createdNos.length} skipped=${skipped.length}` + ); + + // 第五步:合并通知快递群(按快递分组)——优先揽收群,无揽收群回退售后群 + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedTotal = 0; + const notifiedWaybillIds = new Set(); // 记录哪些运单成功通知了至少一个群 + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups, pickupGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + + // 优先揽收群;未配置揽收群时回退售后群 + const targetGroups = pickupGroups.length > 0 ? pickupGroups : afterSalesGroups; + if (targetGroups.length === 0) { + ctx.logger.info(`[inbox functions] 快递 ${code} 未配置揽收群与售后群,跳过通知`); + continue; + } + + // 发给快递的模板:运单号(每个一行)+ 揽收 + const forwardMsg = info.waybills.join('\n') + '\n揽收'; + for (const g of targetGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: forwardMsg, + ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + // 有目标群即标记为已通知(推送是异步的,不计成败) + const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); + codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[inbox functions] 查快递群失败 code=${code}: ${e.message}`); + } + } + + // 第六步:有通知的工单升级为 pending_feedback + const notifiedAsNos = []; + const notNotifiedAsNos = []; + for (const e of toCreate) { + const asNo = waybillToAsNo[e.id]; + if (notifiedWaybillIds.has(e.id)) { + notifiedAsNos.push(asNo); + } else { + notNotifiedAsNos.push(asNo); + } + } + + if (notifiedAsNos.length > 0) { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, 'order', 'pickup' + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } } + ); + ctx.logger.info( + `[inbox functions] ${notifiedAsNos.length} 个揽收工单已通知快递群,` + + `升级为 pending_feedback,${hours}h 后追踪` + ); + } + + // 构造客户回信模板:多个快递号换行分隔,同类状态共用一行说明 + const replyLines = []; + const notifiedWbs = []; + const existedWbs = []; + const notNotifiedWbs = []; + for (const e of validList) { + if (notifiedWaybillIds.has(e.id)) { + notifiedWbs.push(e.waybill_code); + } else if (existingWaybillIds.has(e.id)) { + existedWbs.push(e.waybill_code); + } else { + notNotifiedWbs.push(e.waybill_code); + } + } + if (notifiedWbs.length > 0) { + replyLines.push(notifiedWbs.join('\n')); + replyLines.push('已通知运方,待处理后刷新轨迹'); + } + if (notNotifiedWbs.length > 0) { + replyLines.push(notNotifiedWbs.join('\n')); + replyLines.push('已登记(未配置快递群,需人工跟进)'); + } + if (existedWbs.length > 0) { + replyLines.push(existedWbs.join('\n')); + replyLines.push('已登记过,无需重复'); + } + if (skipped.length > 0) { + replyLines.push(`无权操作:${skipped.join('\n')}`); + } + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + skipped: skipped.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + notified_as_nos: notifiedAsNos, + not_notified_as_nos: notNotifiedAsNos, + notified_groups: notifiedTotal, + waybills: validList.map(e => e.waybill_code), + message: replyLines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 批量揽收失败: ${error.message}`); + return { success: false, error: `揽收操作失败: ${error.message}` }; + } + }, + }); + + this.register('queryReturn', { + description: '查询退回包裹明细(查退回)。用户发送"查退回+运单号"时调用,支持多行/多个运单号(换行、逗号、空格分隔),每个单号分别返回一条结果。传入运单号,查询退回收到/退回拆包/未退回登记状态:已拆包返回拆包明细与录像地址模板消息,未退回则自动登记到退回查询表。注意:仅查询退回状态使用,与 interceptWaybill 拦截、queryOrder 订单查询不同', + weight: 90, + keywords: [ '查退回', '查退件', '退回查询', '退回明细', '查拆包', '退件查询', '退回进度' ], + params: { + waybill_code: { type: 'string', required: true, description: '退回包裹运单号,支持多个(换行/逗号/空格分隔),如"查退回 465570943491370\nSF123456";v2 规则引擎将运单号归并进 keyword 键,函数内兼容两键读取' }, + }, + groups: [ GROUP.COMMON ], + /** + * 查退回处理器:按运单号查询退回收到/退回拆包/未退回登记状态, + * 已拆包返回拆包明细与录像地址,未退回自动登记到退回查询表。 + * v2 规则引擎会把取号结果写入 params.keyword(waybill_no → keyword 归并), + * 故入参键兼容 waybill_code 与 keyword 两种来源。 + * @param {Object} params 入参,包含 waybill_code 或 keyword(退回包裹运单号,可多单号)。 + * @return {Promise} 处理结果,包含 success 与 data(message/messages/direct_reply)。 + */ + handler: async (params = {}) => { + const { ctx } = this; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const storeId = Number(ctx.inboxContext?.store_id || 0); + + // v2 引擎兼容:取号结果可能落在 keyword 键(v1/AI 路径使用 waybill_code) + let raw = String(params.waybill_code || params.keyword || '').trim(); + if (!raw) return { success: false, error: '请提供退回包裹运单号' }; + + // 兼容把"查退回 123456"整体传入的情况 + const match = raw.match(/查退[回件]\s*[::]?\s*(.+)$/); + if (match) raw = String(match[1]).trim(); + + // 解析多个单号:换行/逗号/空格/常见中文标点分隔,去重保序 + const waybills = [ ...new Set( + raw.split(/[\s,,。;;]+/) + .map(s => s.trim()) + .filter(Boolean) + ) ]; + if (waybills.length === 0) return { success: false, error: '未解析到有效运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + try { + const messages = []; + const statuses = []; + for (const waybill of waybills) { + try { + const result = await ctx.service.systems.returnUnpack.queryByWaybill({ + waybill_code: waybill, + warehouse_id: warehouseId, + store_id: storeId, + group_id: ctx.inboxContext?.group_id, + group_name: ctx.inboxContext?.group_name, + user_id: ctx.inboxContext?.user_id, + user_name: ctx.inboxContext?.user_name, + }); + + const warehouseLabel = result.warehouse_name || '仓库'; + let message = ''; + + if (result.status === 'unpacked') { + const unpack = result.unpack || {}; + const details = result.details || []; + const videos = result.videos || []; + const orderInfo = result.order_info || {}; + + const lines = []; + lines.push(`${waybill}已在已退件中登记,登记信息为:`); + lines.push(''); + lines.push(`运单号:${waybill}`); + lines.push(`是否原单:${unpack.order_express_id ? '是' : '否'}`); + lines.push(`交易单号:${orderInfo.trade_no || ''}`); + lines.push(`快递:${orderInfo.express || ''}`); + lines.push(`店铺名称:${orderInfo.shop_name || ''}`); + lines.push(`${warehouseLabel}收到且已拆包,拆包明细为:`); + if (details.length > 0) { + for (const detail of details) { + lines.push(`商品名称:${detail.item_name || ''}`); + lines.push(`条码:${detail.barcode || ''}`); + lines.push(`数量:${detail.quantity || 0}`); + lines.push(`是否破损:${detail.product_status === 'damaged' ? '是' : '否'}`); + } + } else { + lines.push('暂无拆包明细,拆包完成后可再次查询'); + } + lines.push(''); + lines.push('退件录像地址为:'); + const unpackId = Number(unpack.id || 0); + if (videos.length > 0) { + for (const video of videos) { + if (!video.video_url) continue; + const cameraName = String(video.camera_name || '').trim(); + lines.push(cameraName ? `${cameraName}:${video.video_url}` : String(video.video_url)); + } + lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询'); + // 视频已可用:推进补录请求状态为 completed(回写视频地址) + if (unpackId > 0) { + try { + await ctx.service.systems.videoRecordRequest.syncByVideos({ + biz_type: 'unpack', + biz_id: unpackId, + videos, + }); + } catch (err) { + ctx.logger.warn(`[inbox functions] 拆包视频补录状态同步失败 unpack=${unpackId}: ${err.message}`); + } + } + } else if (unpackId > 0) { + // 视频不可用:登记补录请求并推送录制服务重新录制(录制服务不可用时仅登记,不阻断查询) + let inFlight = false; + try { + const req = await ctx.service.systems.videoRecordRequest.requestUnpackVideo({ + warehouse_id: warehouseId, + unpack_id: unpackId, + waybill_code: waybill, + store_id: Number(unpack.store_id || 0), + group_id: String(ctx.inboxContext?.group_id || '').trim(), + group_name: String(ctx.inboxContext?.group_name || '').trim(), + user_id: String(ctx.inboxContext?.user_id || '').trim(), + user_name: String(ctx.inboxContext?.user_name || '').trim(), + source: 'inbox', + }); + inFlight = Boolean(req && (req.pushed || (req.reused && req.status !== 'failed'))); + } catch (err) { + ctx.logger.warn(`[inbox functions] 拆包视频补录推送失败 unpack=${unpackId}: ${err.message}`); + } + lines.push(inFlight + ? '视频暂不可用,已推送重新录制,请稍等通知录制结果' + : '视频暂不可用,已登记补录,请稍后重试'); + } else { + lines.push('暂无'); + } + message = lines.join('\n'); + } else if (result.status === 'received') { + message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`; + } else if (result.status === 'not_returned') { + message = `${waybill}尚未退回仓库,已在未退回表中登记成功,等待包裹退件登记后,将自动发送通知包裹信息`; + } else { + message = `未查询到运单号${waybill}的退回信息,请核实单号后重试`; + } + + messages.push(message); + statuses.push(result.status); + } catch (error) { + ctx.logger.warn(`[inbox functions] 退回查询单号失败 ${waybill}: ${error.message}`); + messages.push(`${waybill}退回查询失败:${error.message}`); + statuses.push('error'); + } + } + + return { + success: true, + data: { + status: statuses[0], + waybill_code: waybills[0], + total: waybills.length, + message: messages[0], // 兼容单条回复(AI 兜底路径取首条) + messages, // 规则引擎多行回复:每个单号一条消息 + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 退回查询失败: ${error.message}`); + return { success: false, error: `退回查询失败: ${error.message}` }; + } + }, + }); + + this.register('cancelIntercept', { + description: '取消拦截运单(支持批量)。当用户要求"取消拦截/撤销拦截/不拦截了"时调用。先查已有售后工单,有则追加取消记录,无则按拦截规则创建工单。同时设置订单和运单拦截状态并通知快递群', + weight: 94, + keywords: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截了', '不用拦截' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔' }, + reason: { type: 'string', required: false, description: '取消拦截原因' }, + }, + groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ], + /** + * 取消拦截处理器:为运单创建/追加取消拦截工单,并按波次规则重新写入 + * 订单拦截状态 intercept_status='requested' 与拦截时间 intercept_time。 + * @param {Object} params 入参,包含 keyword(运单号)与 reason(取消拦截原因)。 + * @return {Promise} 处理结果,包含 success 与 data/error。 + */ + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const reason = String(params.reason || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + // 第一步:批量查询运单 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id' ], + where: { waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, warehouse_id: warehouseId }, + raw: true, + }); + if (expressList.length === 0) { + return { success: false, error: `未找到运单号「${raw}」,请核实单号后重试` }; + } + + // 第二步:鉴权 + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { skipped.push(e.waybill_code); continue; } + } + validList.push(e); + } + if (validList.length === 0) { + return { success: false, error: `运单${skipped.join('、')}不属于当前货主,无法操作` }; + } + + // 第三步:查已有工单(不限制状态,找到即追加取消记录) + const validIds = validList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'id', 'waybill_id', 'waybill_no', 'after_sale_no', 'status', 'store_id' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: validIds }, + type: 'order', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = validList.filter(e => !existingWaybillIds.has(e.id)); + + // 获取原消息内容用于反馈记录 + let cancelMsgContent = ''; + try { + const cid = ctx.inboxContext?.inbound_message_id; + if (cid) { + const cm = await ctx.model.InboxMessage.findByPk(cid, { attributes: [ 'content' ], raw: true }); + if (cm && cm.content) cancelMsgContent = String(cm.content); + } + } catch (e) { /* ignore */ } + + let feedbackCount = 0; + const feedbackWbs = []; + const cancelGroup = ctx.inboxContext?.group_name || '未知群'; + const cancelUser = ctx.inboxContext?.user_name || '未知用户'; + const cancelTime = new Date().toISOString().slice(0, 19) + .replace('T', ' '); + + // 已有工单:追加取消拦截记录 + for (const as of existingASList) { + try { + const remarkLines = [ + `群: ${cancelGroup}`, `用户: ${cancelUser}`, `时间: ${cancelTime}`, + ]; + if (cancelMsgContent) remarkLines.push(`原消息: ${cancelMsgContent}`); + if (reason) remarkLines.push(`取消原因: ${reason}`); + await ctx.service.systems.afterSale.addStep(as.id, { + step_status: 'processing', + action: '取消拦截', + remark: remarkLines.join('\n'), + }); + feedbackCount += 1; + if (as.waybill_no) feedbackWbs.push(as.waybill_no); + } catch (e) { + ctx.logger.warn(`[inbox functions] 取消拦截反馈失败 as_no=${as.after_sale_no}: ${e.message}`); + } + } + + const parts = []; + if (feedbackCount > 0) { + const wbs = [ ...new Set(feedbackWbs) ]; + parts.push(wbs.length > 0 + ? `运单${wbs.join('、')} 取消拦截信息已登记(已追加到处理中的工单)` + : `取消拦截信息已登记 ${feedbackCount} 个`); + } + + // 第四步:无工单的按拦截规则创建 + const createdNos = []; + if (toCreate.length > 0) { + if (shouldSkipWorkOrder(ctx)) { + ctx.logger.info('[inbox functions] 取消拦截: skip_work_order,跳过创建工单'); + return { success: true, data: { message: '取消拦截信息已登记(本次不创建工单)', skipped_work_order: true } }; + } + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `取消原因: ${reason}` : '', + '来源: 取消拦截', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, after_sale_no: afterSaleNo, + type: 'order', sub_type: 'intercept', + title: `[AI工单] 取消拦截 - ${e.waybill_code}`, + description: descParts, priority: 10, creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', status: 'pending', + waybill_id: e.id, waybill_no: e.waybill_code, + store_id: e.store_id || storeId || null, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + } + } + if (createdNos.length > 0) { + const wbs = toCreate.map(e => e.waybill_code).filter(Boolean); + parts.push(wbs.length > 0 + ? `运单${wbs.join('、')} 取消拦截信息已登记(已创建处理工单)` + : `取消拦截信息已登记 ${createdNos.length} 个`); + } + + ctx.logger.info( + `[inbox functions] 取消拦截: total=${keywords.length} ` + + `feedback=${feedbackCount} created=${createdNos.length} skipped=${skipped.length}` + ); + + // 第4.5步:波次感知拦截(与 interceptWaybill 相同) + const orderIds = toCreate.map(e => e.order_id).filter(id => id); + if (orderIds.length > 0) { + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + if (orderModel) { + const orders = await orderModel.findAll({ + attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time', 'sync_status', 'create_channel' ], + where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] } }, + raw: true, + }); + if (orders.length > 0) { + const waveIds = [ ...new Set(orders.map(o => o.wave_id).filter(id => id > 0)) ]; + let waveMap = {}; + if (waveIds.length > 0) { + const waves = await ctx.model.WaveBatch.findAll({ + attributes: [ 'wave_id', 'wave_type', 'wave_status', 'total_orders' ], + where: { wave_id: { [ctx.app.Sequelize.Op.in]: waveIds } }, raw: true, + }); + waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ])); + } + const interceptOrderIds = []; + // 未同步订单/手工单:拦截请求按取消订单处理(释放两层锁,不走拦截) + const cancelHandledOrderIds = []; + const syncedCancelOrderIds = []; + // 批量查询散单的称重状态 + const scatterIds = orders + .filter(o => o.wave_id > 0 && waveMap[o.wave_id] && waveMap[o.wave_id].wave_type === 2) + .map(o => o.id); + const wMap = {}; + if (scatterIds.length > 0) { + const er = await ctx.model.OrderExpress.findAll({ + attributes: [ 'order_id', 'weighing_weight' ], + where: { order_id: { [ctx.app.Sequelize.Op.in]: scatterIds }, warehouse_id: warehouseId }, + raw: true, + }); + for (const r of (Array.isArray(er) ? er : [])) { + wMap[r.order_id] = Number(r.weighing_weight || 0); + } + } + for (const order of orders) { + const wave = waveMap[order.wave_id]; + let needIntercept = false; + if (order.wave_id > 0 && wave) { + if (wave.wave_type === 1) { + needIntercept = order.inspection_status !== 'fin'; + } else { + needIntercept = (wMap[order.id] ?? 0) <= 0; + } + } else { + needIntercept = true; + } + if (needIntercept) { + const isManualOrder = String(order.create_channel || '').trim().toUpperCase() === 'MANUAL'; + const isUnsyncedOrder = String(order.sync_status || '').trim() !== 'fin'; + if (isManualOrder || isUnsyncedOrder) { + cancelHandledOrderIds.push(order.id); + if (!isUnsyncedOrder) { + syncedCancelOrderIds.push(order.id); + } + } else { + interceptOrderIds.push(order.id); + } + } + } + if (interceptOrderIds.length > 0) { + const noticeNow = new Date(); + const interceptIdSet = new Set(interceptOrderIds.map(id => Number(id))); + const fillNoticeOrderIds = pickNoticeTimeOrderIds( + orders.filter(order => interceptIdSet.has(Number(order.id))) + ); + await orderModel.update( + { intercept_status: 'requested' }, + { where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } } + ); + if (fillNoticeOrderIds.length > 0) { + await orderModel.update( + { intercept_time: noticeNow }, + { where: { id: { [ctx.app.Sequelize.Op.in]: fillNoticeOrderIds } } } + ); + } + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } } + ); + // 写入操作日志(失败不影响主流程) + try { + const logSvc = ctx.service?.systems?.operationLog; + if (logSvc && typeof logSvc.createOperationLogs === 'function') { + await logSvc.createOperationLogs( + interceptOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(oid), + operationCode: 'ORDER_INTERCEPT_REQUEST', + operator: { id: '0', name: groupName || 'AI系统' }, + extras: { warehouseId, orderId: oid, newInterceptStatus: 'requested' }, + })) + ); + } + } catch (logErr) { + ctx.logger.warn(`[inbox functions] 取消拦截-写入操作日志失败: ${logErr.message}`); + } + ctx.logger.info(`[inbox functions] 取消拦截-设置拦截状态: ${interceptOrderIds.length} 个订单`); + } + + // 未同步/手工单:拦截请求按取消订单处理(释放两层锁) + if (cancelHandledOrderIds.length > 0) { + await cancelOrderForInterceptRequest( + ctx, + orderModel, + warehouseId, + cancelHandledOrderIds, + syncedCancelOrderIds, + { id: '0', name: groupName || 'AI系统' } + ); + } + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 取消拦截-波次处理失败: ${e.message}`); + } + } + + // 第五步:通知快递群 + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + expressByCode[code].waybills.push(e.waybill_code); + } + let notifiedTotal = 0; + const notifiedNos = []; + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, expressCode: code, warehouseId, + }); + if (afterSalesGroups.length === 0) continue; + const notifyMsg = info.waybills.join('\n') + '\n取消拦截'; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, group_id: g.group_id, + group_name: g.group_name, content: notifyMsg, ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 取消拦截查快递群失败 code=${code}: ${e.message}`); + } + } + if (notifiedTotal > 0) parts.push(`已通知 ${notifiedTotal} 个快递群`); + + // 有通知的工单升级 pending_feedback + if (notifiedNos.length > 0) { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours(warehouseId, 'order', 'intercept'); + await ctx.model.AfterSale.update( + { status: 'pending_feedback', followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), role_group: 'customer_service' }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedNos }, warehouse_id: warehouseId } } + ); + } + + return { success: true, data: { feedback: feedbackCount, created: createdNos.length, skipped: skipped.length, notified_groups: notifiedTotal, message: parts.join(';') || '处理完成' } }; + } catch (error) { + ctx.logger.error(`[inbox functions] 取消拦截失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('handleStoreFeedback', { + description: '货主售后群问题反馈建工单。客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"等问题并提供了运单号时调用。校验货主权限后创建售后工单,初始状态为未开始处理(pending),不转发通知快递群', + weight: 88, + keywords: [ '错发', '发错', '破损', '坏了', '多发', '发多', '少发', '漏发', '发少' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + issue_type: { type: 'string', required: true, description: '问题类型:wrong(错发)/damaged(破损)/multiple(多发)/missing(少发)' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const issueTypeRaw = String(params.issue_type || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + // 问题类型 → 售后子类型映射(支持英文枚举与中文别名) + const ISSUE_TYPE_MAP = { + wrong: { sub_type: 'mis_shipment', label: '错发' }, + 错发: { sub_type: 'mis_shipment', label: '错发' }, + damaged: { sub_type: 'damage', label: '破损' }, + 破损: { sub_type: 'damage', label: '破损' }, + multiple: { sub_type: 'extra_item', label: '多发' }, + 多发: { sub_type: 'extra_item', label: '多发' }, + missing: { sub_type: 'missing_item', label: '少发' }, + 少发: { sub_type: 'missing_item', label: '少发' }, + }; + const issue = ISSUE_TYPE_MAP[issueTypeRaw]; + if (!issue) { + return { + success: false, + error: `不支持的问题类型「${issueTypeRaw || '空'}」,仅支持 wrong(错发)/damaged(破损)/multiple(多发)/missing(少发)`, + }; + } + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:拒绝看起来像售后单号(AS...)的输入 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + // 第一步:批量查询运单(限当前仓库 + 当前货主) + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'order_id' ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + store_id: storeId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + if (expressList.length === 0) { + return { success: false, error: `未找到当前货主在仓库中的运单「${raw}」,请核实单号后重试` }; + } + + // 第二步:幂等检查(同子类型未完结工单不重复建单) + const expressIds = expressList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, + type: 'order', + sub_type: issue.sub_type, + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + /** + * 组装客户回信模板:运单号 + 问题信息(不暴露售后单号)。 + * @param {Array<{waybill: string, as_no: string}>} pairs 运单号→工单号列表(as_no 仅内部使用)。 + * @return {string} 模板消息。 + */ + const buildReply = pairs => { + const lines = pairs.map(p => `运单${p.waybill} ${issue.label}问题已登记`); + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')},请核实单号`); + } + return `${lines.join('\n')},稍后客服将人工核实跟进`; + }; + + if (toCreate.length === 0) { + const existedPairs = expressList + .filter(e => existingWaybillIds.has(e.id)) + .map(e => { + const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id)); + return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' }; + }) + .filter(p => p.as_no); + return { + success: true, + data: { + existed: true, + message: buildReply(existedPairs), + direct_reply: true, + after_sale_nos: alreadyExist, + }, + }; + } + + // 第三步:创建工单(初始状态 pending=未开始处理,不转发通知快递群) + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + let msgContent = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) msgContent = String(m.content); + } + } catch (e) { /* ignore */ } + + const createdNos = []; + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + `问题类型: ${issue.label}`, + msgContent ? `原消息: ${msgContent}` : '', + ].filter(Boolean).join('\n'); + + if (shouldSkipWorkOrder(ctx)) { + ctx.logger.info(`[inbox functions] 问题反馈: skip_work_order,跳过工单登记 ${e.waybill_code}`); + return { success: true, data: { message: '已记录问题反馈(本次不登记工单)', skipped_work_order: true } }; + } + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: issue.sub_type, + title: `[AI工单] ${issue.label} - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + + ctx.logger.info( + `[inbox functions] 货主问题反馈建工单: sub_type=${issue.sub_type} ` + + `total=${keywords.length} found=${expressList.length} created=${createdNos.length} notFound=${notFound.length}` + ); + + // 构造返回数据(客户回信模板:单号+问题+工单,细节字段仅作内部记录) + const createdPairs = toCreate.map(e => ({ + waybill: e.waybill_code, + as_no: waybillToAsNo[e.id] || '', + })); + const existedPairs = expressList + .filter(e => existingWaybillIds.has(e.id)) + .map(e => { + const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id)); + return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' }; + }) + .filter(p => p.as_no); + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + not_found: notFound, + message: buildReply([ ...createdPairs, ...existedPairs ]), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 货主问题反馈建工单失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('changeAddr', { + description: '货主售后群改地址/催退回/催件处理。客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/催促退回/催件/催派送/尽快安排派送"等诉求且提供了运单号时调用:创建售后工单(改地址/催退回/催件),并将客户原文转发到对应快递的售后群通知快递处理', + weight: 89, + keywords: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机', '催退回', '催促退回', '催件', '催派送', '尽快安排派送' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + issue_type: { type: 'string', required: true, description: '诉求类型:addr(改地址类诉求)/return(催退回类诉求)/urge(催件/催派送类诉求),注意区分:催退回用 return,催件/催派送用 urge' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const issueTypeRaw = String(params.issue_type || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + // 诉求类型 → 售后子类型映射(支持英文枚举与中文别名) + const ISSUE_TYPE_MAP = { + addr: { sub_type: 'change_address', label: '改地址' }, + 改地址: { sub_type: 'change_address', label: '改地址' }, + return: { sub_type: 'rejected', label: '催退回' }, + 催退回: { sub_type: 'rejected', label: '催退回' }, + urge: { sub_type: 'urge', label: '催件' }, + 催件: { sub_type: 'urge', label: '催件' }, + }; + const issue = ISSUE_TYPE_MAP[issueTypeRaw] || ISSUE_TYPE_MAP.addr; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + // 原文(客户原始消息,用于转发快递群 + 工单明细) + let originalText = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) originalText = String(m.content); + } + } catch (e) { /* ignore */ } + + // 第一步:批量查询运单(限当前仓库 + 当前货主) + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'order_id', + 'logistics_interface_id', 'logistics_code' ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + store_id: storeId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + if (expressList.length === 0) { + return { success: false, error: `未找到当前货主在仓库中的运单「${raw}」,请核实单号后重试` }; + } + + // 第二步:幂等检查(同子类型未完结工单不重复建单) + const expressIds = expressList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, + type: 'order', + sub_type: issue.sub_type, + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + // 第三步:创建工单(含原文)并映射 waybill_id → 工单号 + const createdNos = []; + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射(新建 + 已存在) + for (const r of existingASList) { + waybillToAsNo[r.waybill_id] = r.after_sale_no; + } + if (shouldSkipWorkOrder(ctx)) { + ctx.logger.info('[inbox functions] 改地址/催件: skip_work_order,跳过工单登记'); + return { success: true, data: { message: '已记录诉求(本次不登记工单)', skipped_work_order: true } }; + } + if (toCreate.length > 0) { + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + `诉求类型: ${issue.label}`, + originalText ? `原文: ${originalText}` : '', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: issue.sub_type, + title: `[AI工单] ${issue.label} - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + } + + // 第四步:原文转发到对应快递的售后群(按快递分组) + // 新建与已存在的工单都转发:客户再次发来的原文是快递需要的最新诉求 + const expressByCode = {}; + for (const e of expressList) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedTotal = 0; + const notifiedWaybillIds = new Set(); + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + if (afterSalesGroups.length === 0) { + ctx.logger.info(`[inbox functions] 快递 ${code} 未配置售后群,跳过转发`); + continue; + } + + // 原文转发:仅客户原始消息(原文已含运单号) + const forwardMsg = originalText || raw; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: forwardMsg, + ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + expressList + .filter(e => (e.logistics_code || '__unknown__') === code) + .forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[inbox functions] 改地址/催退回查快递群失败 code=${code}: ${e.message}`); + } + } + + // 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限(新建与已有工单,仅 pending 状态升级) + const notifiedAsNos = expressList + .filter(e => notifiedWaybillIds.has(e.id)) + .map(e => waybillToAsNo[e.id]) + .filter(Boolean); + if (notifiedAsNos.length > 0) { + try { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, 'order', issue.sub_type + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { + where: { + after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos }, + status: 'pending', + }, + } + ); + } catch (e) { + ctx.logger.warn(`[inbox functions] 改地址/催退回更新工单状态失败: ${e.message}`); + } + } + + // 第六步:客户回信模板(单号+诉求,区分是否已通知快递) + // key 必须与 issue.sub_type 对齐(change_address/rejected/urge), + // 此前误用 addr/return 导致永远回退到改地址文案 + const REPLY_TEXT = { + change_address: { done: '修改地址已经登记', notify: '并已通知快递修改' }, + rejected: { done: '催退回已经登记', notify: '并已通知快递处理' }, + urge: { done: '催件已经登记', notify: '并已通知快递处理' }, + }; + const replyText = REPLY_TEXT[issue.sub_type] || REPLY_TEXT.change_address; + const lines = expressList.map(e => { + const head = `运单${e.waybill_code}${replyText.done}`; + return notifiedWaybillIds.has(e.id) + ? `${head}·${replyText.notify}` + : `${head},稍后客服将人工跟进`; + }); + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')},请核实单号`); + } + + ctx.logger.info( + `[inbox functions] 改地址/催退回: sub_type=${issue.sub_type} ` + + `total=${keywords.length} found=${expressList.length} created=${createdNos.length} notified=${notifiedTotal}` + ); + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + notified_groups: notifiedTotal, + not_found: notFound, + message: lines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 改地址/催退回处理失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('weishoudao', { + description: '货主售后群核实签收处理。客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时调用:创建核实签收售后工单(verify_delivery),并把"运单号+核实签收"转发到对应快递的售后群通知快递核实', + weight: 89, + keywords: [ '核实签收', '未收到', '是否发出', '是否已经发货', '没有找到快递' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + const issue = { sub_type: 'verify_delivery', label: '核实签收' }; + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + // 原文(客户原始消息,写入工单明细) + let originalText = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) originalText = String(m.content); + } + } catch (e) { /* ignore */ } + + // 第一步:批量查询运单(限当前仓库 + 当前货主) + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'order_id', + 'logistics_interface_id', 'logistics_code' ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + store_id: storeId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + if (expressList.length === 0) { + return { success: false, error: `未找到当前货主在仓库中的运单「${raw}」,请核实单号后重试` }; + } + + // 第二步:幂等检查(同子类型未完结工单不重复建单) + const expressIds = expressList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, + type: 'order', + sub_type: issue.sub_type, + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + const existedPairs = expressList + .filter(e => existingWaybillIds.has(e.id)) + .map(e => { + const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id)); + return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' }; + }) + .filter(p => p.as_no); + + // 第三步:创建工单(含原文)并映射 waybill_id → 工单号 + const createdNos = []; + const waybillToAsNo = {}; + if (shouldSkipWorkOrder(ctx)) { + ctx.logger.info('[inbox functions] 核实签收: skip_work_order,跳过工单登记'); + return { success: true, data: { message: '已记录核实签收诉求(本次不登记工单)', skipped_work_order: true } }; + } + if (toCreate.length > 0) { + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + `诉求类型: ${issue.label}`, + originalText ? `原文: ${originalText}` : '', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: issue.sub_type, + title: `[AI工单] ${issue.label} - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + } + + // 第四步:转发快递群(格式:运单号 + \n + 核实签收) + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedTotal = 0; + const notifiedWaybillIds = new Set(); + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + if (afterSalesGroups.length === 0) { + ctx.logger.info(`[inbox functions] 快递 ${code} 未配置售后群,跳过转发`); + continue; + } + + const forwardMsg = `${info.waybills.join('\n')}\n核实签收`; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: forwardMsg, + ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + toCreate + .filter(e => (e.logistics_code || '__unknown__') === code) + .forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[inbox functions] 核实签收查快递群失败 code=${code}: ${e.message}`); + } + } + + // 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限 + const notifiedAsNos = createdNos.filter((asNo, idx) => notifiedWaybillIds.has(toCreate[idx].id)); + if (notifiedAsNos.length > 0) { + try { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, 'order', issue.sub_type + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } } + ); + } catch (e) { + ctx.logger.warn(`[inbox functions] 核实签收更新工单状态失败: ${e.message}`); + } + } + + // 第六步:客户回信模板(运单号 + 诉求,不暴露售后单号) + const createdPairs = toCreate.map(e => ({ + waybill: e.waybill_code, + as_no: waybillToAsNo[e.id] || '', + })); + const lines = [ ...createdPairs, ...existedPairs ].map(p => `运单${p.waybill} ${issue.label}问题已登记`); + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')},请核实单号`); + } + + ctx.logger.info( + `[inbox functions] 核实签收: total=${keywords.length} found=${expressList.length} created=${createdNos.length} notified=${notifiedTotal}` + ); + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + notified_groups: notifiedTotal, + not_found: notFound, + message: `${lines.join('\n')},稍后客服将人工核实跟进`, + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 核实签收处理失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('changeExpress', { + description: '货主售后群改快递。客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时调用。仅待处理表中未分配快递(post_status=none)的订单可以修改快递;已分配快递或不在待处理表的订单不能修改', + weight: 87, + keywords: [ '改快递', '换快递', '改圆通', '改中通', '改申通', '改顺丰', '改极兔', '改韵达', '改京东', '改德邦' ], + params: { + keyword: { type: 'string', required: true, description: '订单号(发货单号或平台单号),多个用逗号或空格分隔' }, + express: { type: 'string', required: true, description: '目标快递名称或编码,如 圆通/中通/顺丰,或系统编码如 YTO/STO/SF' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const expressRaw = String(params.express || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供订单号' }; + if (!expressRaw) return { success: false, error: '请提供目标快递(名称或编码),如 圆通/中通/顺丰' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效订单号' }; + + // 前置拦截:AS 开头为售后工单号,不是订单号 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非订单号,请提供发货单号或平台单号` }; + } + + try { + const { Op } = ctx.app.Sequelize; + const factory = ctx.model.OrderDeliveryFactory; + + // 第一步:解析目标快递(兼容名称/别名/编码)。 + // 快递列表服务依赖 ctx.user.store_id 作为仓库上下文,临时注入后恢复。 + const originalUser = ctx.user; + ctx.user = { + ...(originalUser || {}), + store_id: warehouseId, + employees_id: 0, + employees_name: [ groupName, userName ].filter(Boolean).join('-') || 'AI系统', + }; + let expressList = []; + try { + expressList = await ctx.service.systems.express.getExpressList(); + } finally { + ctx.user = originalUser; + } + + const expressKey = expressRaw.toUpperCase(); + const list = Array.isArray(expressList) ? expressList : []; + + // 第一轮:精确匹配(编码/名称/别名/系统编码) + let expressItem = list.find(item => { + const code = String(item.code || item.value || '').trim().toUpperCase(); + const name = String(item.name || '').trim().toUpperCase(); + const alias = String(item.alias || '').trim().toUpperCase(); + const sysCode = String(item.express_code || '').trim().toUpperCase(); + return code === expressKey || name === expressKey || alias === expressKey || sysCode === expressKey; + }); + + // 第二轮:模糊匹配(如客户说"圆通",列表名为"圆通快递") + if (!expressItem && expressKey.length >= 2) { + const fuzzy = list.filter(item => { + const code = String(item.code || item.value || '').trim().toUpperCase(); + const name = String(item.name || '').trim().toUpperCase(); + const alias = String(item.alias || '').trim().toUpperCase(); + const fields = [ name, alias, code ].filter(Boolean); + return fields.some(f => f.includes(expressKey) || expressKey.includes(f)); + }); + if (fuzzy.length === 1) { + expressItem = fuzzy[0]; + } else if (fuzzy.length > 1) { + const names = fuzzy.slice(0, 10) + .map(item => `${item.name || item.code || ''}(${item.code || item.value || ''})`) + .join('、'); + return { + success: false, + error: `快递「${expressRaw}」匹配到多个结果,请明确:${names}`, + }; + } + } + + if (!expressItem) { + const names = list.slice(0, 20) + .map(item => `${item.name || item.code || ''}(${item.code || item.value || ''})`) + .join('、'); + return { + success: false, + error: `未找到快递「${expressRaw}」${names ? `,当前仓库可选快递:${names}` : ''}`, + }; + } + + // 第二步:查待处理表(仅当前货主) + const currentModel = await factory.getCurrentModel(warehouseId); + if (!currentModel) { + return { success: false, error: `仓库 ${warehouseId} 的待处理表不可用` }; + } + + const foundOrders = await currentModel.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes', + 'post_status', 'logistics_name', + ], + where: { + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.in]: keywords } }, + { source_platform_code: { [Op.in]: keywords } }, + ...keywords.map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })), + ], + }, + raw: true, + }); + + const foundCodes = new Set(); + for (const o of foundOrders) { + foundCodes.add(o.delivery_order_code); + foundCodes.add(o.source_platform_code); + for (const sc of String(o.source_order_codes || '').split(',')) { + if (sc.trim()) foundCodes.add(sc.trim()); + } + } + const missing = keywords.filter(k => !foundCodes.has(k)); + + // 第三步:未在待处理表找到的 → 查配送表/历史表,区分"不在待处理表"与"未找到" + const notInPending = []; + const notFound = []; + if (missing.length > 0) { + const tableConfigs = [ + { getModel: (f, wid) => f.getDispatchModel(wid) }, + { getModel: (f, wid) => f.getHistoryModel(wid) }, + ]; + const missingSet = new Set(missing); + for (const cfg of tableConfigs) { + if (missingSet.size === 0) break; + const model = await cfg.getModel(factory, warehouseId); + if (!model) continue; + const rows = await model.findAll({ + attributes: [ 'delivery_order_code', 'source_platform_code', 'source_order_codes' ], + where: { + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.in]: [ ...missingSet ] } }, + { source_platform_code: { [Op.in]: [ ...missingSet ] } }, + ...[ ...missingSet ].map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })), + ], + }, + raw: true, + }); + for (const r of rows) { + const codes = [ + r.delivery_order_code, + r.source_platform_code, + ...String(r.source_order_codes || '').split(','), + ].map(s => String(s || '').trim()).filter(Boolean); + for (const k of [ ...missingSet ]) { + if (codes.includes(k)) { + missingSet.delete(k); + notInPending.push(k); + } + } + } + } + for (const k of missingSet) notFound.push(k); + } + + // 第四步:区分可改(post_status=none)与已分配快递 + const eligible = foundOrders.filter(o => String(o.post_status || '').trim() === 'none'); + const allocated = foundOrders.filter(o => String(o.post_status || '').trim() !== 'none'); + + // 第五步:逐个改快递(复用 updateOrderExpress,内部自带 post_status=none 保护) + const expressCode = String(expressItem.code || expressItem.value || '').trim(); + const changed = []; + const unchanged = []; + for (const o of eligible) { + try { + const originalUser2 = ctx.user; + ctx.user = { + ...(originalUser2 || {}), + store_id: warehouseId, + employees_id: 0, + employees_name: [ groupName, userName ].filter(Boolean).join('-') || 'AI系统', + }; + let updateResult = null; + try { + updateResult = await ctx.service.systemMethods.order.pendingOrder.updateOrderExpress({ + order_ids: [ o.id ], + express_code: expressCode, + }); + } finally { + ctx.user = originalUser2; + } + const updated = Number(updateResult && updateResult.updated_count) || 0; + if (updated > 0) { + changed.push(o.delivery_order_code); + } else { + unchanged.push(o.delivery_order_code); + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 改快递失败 order=${o.delivery_order_code}: ${e.message}`); + unchanged.push(o.delivery_order_code); + } + } + + // 第六步:组装模板回复 + const expressName = String(expressItem.name || expressItem.code || expressRaw).trim(); + const lines = []; + if (changed.length > 0) { + lines.push(`已改快递为「${expressName}」:${changed.join('、')}`); + } + if (allocated.length > 0) { + lines.push(`已分配快递,不能修改:${allocated.map(o => `${o.delivery_order_code}(${o.logistics_name || '已取号'})`).join('、')}`); + } + if (unchanged.length > 0) { + lines.push(`改快递未生效(可能刚分配了快递),请核实:${unchanged.join('、')}`); + } + if (notInPending.length > 0) { + lines.push(`不在待处理表,不能修改:${notInPending.join('、')}`); + } + if (notFound.length > 0) { + lines.push(`未找到订单:${notFound.join('、')}`); + } + + ctx.logger.info( + `[inbox functions] 改快递: total=${keywords.length} eligible=${eligible.length} ` + + `changed=${changed.length} allocated=${allocated.length} notInPending=${notInPending.length} notFound=${notFound.length}` + ); + + return { + success: true, + data: { + changed: changed.length, + allocated: allocated.length, + not_in_pending: notInPending.length, + not_found: notFound.length, + express: expressName, + message: lines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 改快递失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('createPostnum', { + description: '分配快递号/出单(打单/催发货)。客户要求"出单/打单/打印单/催发货/分配快递号"且提供了订单号时调用。仅待处理表中已审核且未分配快递号的订单可分配;分配成功后同步回传平台并通知单号,失败则提示等待客服人工处理。仅创建运单,不创建售后工单', + weight: 86, + keywords: [ '出单', '打单', '打印单', '催发货', '分配快递号', '要单号' ], + params: { + keyword: { type: 'string', required: true, description: '订单号(发货单号或平台单号),多个用逗号或空格分隔' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供订单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效订单号' }; + + // 前置拦截:AS 开头为售后工单号,不是订单号 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非订单号,请提供发货单号或平台单号` }; + } + + try { + const { Op } = ctx.app.Sequelize; + const factory = ctx.model.OrderDeliveryFactory; + + // 第一步:查待处理表(仅当前货主) + const currentModel = await factory.getCurrentModel(warehouseId); + if (!currentModel) { + return { success: false, error: `仓库 ${warehouseId} 的待处理表不可用` }; + } + + const foundOrders = await currentModel.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes', + 'step', 'post_status', 'logistics_name', + ], + where: { + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.in]: keywords } }, + { source_platform_code: { [Op.in]: keywords } }, + ...keywords.map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })), + ], + }, + raw: true, + }); + + const foundCodes = new Set(); + for (const o of foundOrders) { + foundCodes.add(o.delivery_order_code); + foundCodes.add(o.source_platform_code); + for (const sc of String(o.source_order_codes || '').split(',')) { + if (sc.trim()) foundCodes.add(sc.trim()); + } + } + const missing = keywords.filter(k => !foundCodes.has(k)); + + // 第二步:未在待处理表找到的 → 查配送表/历史表区分"不在待处理表"与"未找到" + const notInPending = []; + const notFound = []; + if (missing.length > 0) { + const tableConfigs = [ + { getModel: (f, wid) => f.getDispatchModel(wid) }, + { getModel: (f, wid) => f.getHistoryModel(wid) }, + ]; + const missingSet = new Set(missing); + for (const cfg of tableConfigs) { + if (missingSet.size === 0) break; + const model = await cfg.getModel(factory, warehouseId); + if (!model) continue; + const rows = await model.findAll({ + attributes: [ 'delivery_order_code', 'source_platform_code', 'source_order_codes' ], + where: { + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.in]: [ ...missingSet ] } }, + { source_platform_code: { [Op.in]: [ ...missingSet ] } }, + ...[ ...missingSet ].map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })), + ], + }, + raw: true, + }); + for (const r of rows) { + const codes = [ + r.delivery_order_code, + r.source_platform_code, + ...String(r.source_order_codes || '').split(','), + ].map(s => String(s || '').trim()).filter(Boolean); + for (const k of [ ...missingSet ]) { + if (codes.includes(k)) { + missingSet.delete(k); + notInPending.push(k); + } + } + } + } + for (const k of missingSet) notFound.push(k); + } + + // 第三步:区分可分配(已审核 step>=1 且未分配快递号 post_status=none) + const eligible = foundOrders.filter( + o => Number(o.step) >= 1 && String(o.post_status || '').trim() === 'none' + ); + const notReviewed = foundOrders.filter( + o => Number(o.step) < 1 && String(o.post_status || '').trim() === 'none' + ); + const allocated = foundOrders.filter(o => String(o.post_status || '').trim() !== 'none'); + + // 第四步:提交分配任务并轮询结果(复用已有分配运单号流程) + const successLines = []; + const failLines = []; + if (eligible.length > 0) { + const eligibleIds = eligible.map(o => o.id); + const originalUser = ctx.user; + ctx.user = { + ...(originalUser || {}), + store_id: warehouseId, + employees_id: 0, + employees_name: [ groupName, userName ].filter(Boolean).join('-') || 'AI系统', + }; + let taskId = ''; + try { + const submitResult = await ctx.service.systemMethods.order.pendingOrder.allocateExpressCode({ + ids: eligibleIds, + }); + taskId = String((submitResult && submitResult.task_id) || '').trim(); + } catch (submitErr) { + ctx.logger.warn(`[inbox functions] 分配快递号提交失败: ${submitErr.message}`); + taskId = ''; + } + + if (taskId) { + // 轮询任务进度(最多 40 次 × 1.5s = 60s) + let taskStatus = 'running'; + for (let attempt = 0; attempt < 40; attempt++) { + await new Promise(resolve => setTimeout(resolve, 1500)); + try { + const progressResult = await ctx.service.systemMethods.order.pendingOrder.allocateExpressCodeTaskProgress({ + task_id: taskId, + }); + taskStatus = String(progressResult && progressResult.status || '').trim(); + if ([ 'success', 'failed', 'not_found' ].includes(taskStatus)) break; + } catch (pollErr) { + ctx.logger.warn(`[inbox functions] 查询分配进度失败: ${pollErr.message}`); + taskStatus = 'failed'; + break; + } + } + + if (taskStatus === 'success') { + // 第五步:回查运单号(business_key=1 且 status=1) + const expressRows = await ctx.model.OrderExpress.findAll({ + attributes: [ 'order_id', 'waybill_code' ], + where: { + order_id: { [Op.in]: eligibleIds }, + warehouse_id: warehouseId, + business_key: 1, + status: 1, + }, + raw: true, + }); + const waybillByOrder = new Map(); + for (const er of expressRows) { + if (er.waybill_code) waybillByOrder.set(Number(er.order_id), String(er.waybill_code)); + } + + for (const o of eligible) { + const wb = waybillByOrder.get(Number(o.id)); + if (wb) { + successLines.push(`订单${o.delivery_order_code} 已分配:${wb}\n已回传`); + } else { + failLines.push(`订单${o.delivery_order_code} 分配失败,等待客服人工处理`); + } + } + } else { + for (const o of eligible) { + failLines.push(`订单${o.delivery_order_code} 分配失败,等待客服人工处理`); + } + } + } else { + for (const o of eligible) { + failLines.push(`订单${o.delivery_order_code} 分配失败,等待客服人工处理`); + } + } + ctx.user = originalUser; + } + + // 第六步:组装模板消息 + const lines = []; + if (successLines.length > 0) lines.push(successLines.join('\n')); + if (failLines.length > 0) lines.push(failLines.join('\n')); + if (notReviewed.length > 0) { + lines.push(`未审核,不能分配:${notReviewed.map(o => o.delivery_order_code).join('、')}`); + } + if (allocated.length > 0) { + lines.push(`已分配快递号:${allocated.map(o => `${o.delivery_order_code}(${o.logistics_name || '已取号'})`).join('、')}`); + } + if (notInPending.length > 0) { + lines.push(`不在待处理表,不能分配:${notInPending.join('、')}`); + } + if (notFound.length > 0) { + lines.push(`未找到订单:${notFound.join('、')}`); + } + + ctx.logger.info( + `[inbox functions] 分配快递号: total=${keywords.length} eligible=${eligible.length} ` + + `success=${successLines.length} fail=${failLines.length} notReviewed=${notReviewed.length}` + ); + + return { + success: true, + data: { + success_count: successLines.length, + fail_count: failLines.length, + message: lines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 分配快递号失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('queryPackVideo', { + description: '打包视频查询。传入运单号,查询该运单对应的打包视频:散单按订单查打包记录,团购单按波次查打包记录。有视频返回视频地址;视频不可用时自动登记补录请求并向录制服务推送强制录制(回复“视频暂不可用,已推送重新录制,请稍等通知录制结果”,推送失败则“视频暂不可用,已登记补录,请稍后重试”);无打包记录提示无打包记录。仅查询,不创建工单', + weight: 86, + keywords: [ '打包视频', '打包录像', '装箱视频', '打包监控', '录像' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES, GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + // 触发查询的群/人员:写入补录请求,供后续录制结果回发原群、@原用户 + const inboxGroupId = String(ctx.inboxContext?.group_id || '').trim(); + const inboxGroupName = String(ctx.inboxContext?.group_name || '').trim(); + const inboxUserId = String(ctx.inboxContext?.user_id || '').trim(); + const inboxUserName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:AS 开头为售后工单号,不是运单号 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + const { Op } = ctx.app.Sequelize; + + // 第一步:批量查询运单 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'store_id', 'order_id', 'logistics_name' ], + where: { + waybill_code: { [Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + // 鉴权:货主群需验 store_id + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { + skipped.push(e.waybill_code); + continue; + } + } + validList.push(e); + } + + if (validList.length === 0) { + const parts = []; + if (notFound.length > 0) parts.push(`未找到运单:${notFound.join('、')}`); + if (skipped.length > 0) parts.push(`无权操作:${skipped.join('、')}`); + return { + success: false, + error: parts.join(';') || `未找到运单号「${raw}」,请核实单号后重试`, + }; + } + + const videoLines = []; + const noRecordWbs = []; + const orderMissingWbs = []; + // 视频不可用已推送重新录制 / 仅登记补录(推送失败) + const reRecordWbs = []; + const reRecordFailedWbs = []; + + for (const e of validList) { + // 第二步:查订单行(优先序列表定位,未命中回退 当前→历史→配送 遍历) + let orderRow = null; + const factory = ctx.model.OrderDeliveryFactory; + const tableGetters = [ + { location: 'current', getModel: (f, wid) => f.getCurrentModel(wid) }, + { location: 'history', getModel: (f, wid) => f.getHistoryModel(wid) }, + { location: 'dispatch', getModel: (f, wid) => f.getDispatchModel(wid) }, + ]; + + let location = null; + try { + if (factory && typeof factory.getOrderLocation === 'function') { + location = await factory.getOrderLocation(e.order_id, warehouseId); + } + } catch (err) { /* ignore */ } + + const orderedGetters = location + ? [ + ...tableGetters.filter(entry => entry.location === location), + ...tableGetters.filter(entry => entry.location !== location), + ] + : tableGetters; + + for (const entry of orderedGetters) { + try { + const model = await entry.getModel(factory, warehouseId); + if (!model) continue; + orderRow = await model.findOne({ + attributes: [ 'id', 'wave_id', 'wave_no', 'pack_status' ], + where: { id: e.order_id }, + raw: true, + }); + } catch (err) { /* ignore */ } + if (orderRow) break; + } + + if (!orderRow) { + orderMissingWbs.push(e.waybill_code); + continue; + } + + // 第三步:判断团购/散单(wave_type=1 为团购波次) + let isGroupBuy = false; + if (Number(orderRow.wave_id) > 0) { + try { + const wave = await ctx.model.WaveBatch.findOne({ + attributes: [ 'wave_id', 'wave_type' ], + where: { wave_id: orderRow.wave_id }, + raw: true, + }); + if (wave && Number(wave.wave_type) === 1) isGroupBuy = true; + } catch (err) { /* ignore */ } + } + + // 第四步:团购按波次、散单按订单找打包记录 + const packWhere = isGroupBuy + ? { wave_id: orderRow.wave_id, deleted_at: null } + : { order_id: e.order_id, deleted_at: null }; + const packTasks = await ctx.model.PackTask.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no', 'pack_mode', 'status' ], + where: packWhere, + raw: true, + }); + + if (packTasks.length === 0) { + noRecordWbs.push(e.waybill_code); + continue; + } + + // 第五步:查打包视频 + const taskIds = packTasks.map(t => t.id); + const videos = await ctx.model.PackTaskVideo.findAll({ + attributes: [ 'id', 'video_url', 'camera_id', 'status' ], + where: { + pack_task_id: { [Op.in]: taskIds }, + deleted_at: null, + }, + raw: true, + }); + // 视频地址拼接 CDN 域名(与 order.packing.list、queryReturn 对齐) + const inboxTools = ctx.service.inbox.tools; + const recordingComputerId = await inboxTools.getRecordingComputerId(warehouseId); + const urls = videos + .filter(v => String(v.status || '') !== 'failed') + .map(v => inboxTools.buildVideoUrl(warehouseId, recordingComputerId, v.video_url)) + .filter(Boolean); + + if (urls.length === 0) { + // 视频不可用:登记补录请求并推送录制服务重新录制(录制服务不可用时仅登记,不阻断查询) + let inFlight = 0; + for (const task of packTasks) { + try { + const req = await ctx.service.systems.videoRecordRequest.requestPackVideo({ + warehouse_id: warehouseId, + pack_task_id: task.id, + waybill_code: e.waybill_code, + store_id: Number(e.store_id || 0), + group_id: inboxGroupId, + group_name: inboxGroupName, + user_id: inboxUserId, + user_name: inboxUserName, + source: 'inbox', + }); + if (req && (req.pushed || (req.reused && req.status !== 'failed'))) inFlight += 1; + } catch (err) { + ctx.logger.warn(`[inbox functions] 打包视频补录推送失败 task=${task.id}: ${err.message}`); + } + } + if (inFlight > 0) { + reRecordWbs.push(e.waybill_code); + } else { + reRecordFailedWbs.push(e.waybill_code); + } + } else { + // 摄像头名称放链接前(系统设置的自定义名称优先,通道原始名称兜底) + const packCameraIds = [ ...new Set(videos.filter(v => v.camera_id).map(v => v.camera_id)) ]; + const packCameraNameMap = new Map(); + if (packCameraIds.length > 0) { + const packCameras = await ctx.model.Camera.findAll({ + attributes: [ 'id', 'custom_name', 'channel_name' ], + where: { id: { [Op.in]: packCameraIds } }, + raw: true, + }); + for (const c of packCameras) { + packCameraNameMap.set(Number(c.id), String(c.custom_name || c.channel_name || '').trim()); + } + } + const displayLines = videos + .filter(v => String(v.status || '') !== 'failed') + .map(v => { + const url = inboxTools.buildVideoUrl(warehouseId, recordingComputerId, v.video_url); + if (!url) return ''; + const cameraName = v.camera_id ? (packCameraNameMap.get(Number(v.camera_id)) || '') : ''; + return cameraName ? `${cameraName}:${url}` : url; + }) + .filter(Boolean); + videoLines.push(`${e.waybill_code}\n${displayLines.join('\n')}`); + // 视频已可用:推进补录请求状态为 completed(回写视频地址) + for (const task of packTasks) { + try { + await ctx.service.systems.videoRecordRequest.syncByVideos({ + biz_type: 'pack', + biz_id: task.id, + videos, + }); + } catch (err) { + ctx.logger.warn(`[inbox functions] 打包视频补录状态同步失败 task=${task.id}: ${err.message}`); + } + } + } + } + + // 第六步:组装模板消息(仅查询,不建工单) + const lines = []; + if (videoLines.length > 0) { + lines.push(videoLines.join('\n')); + } + if (reRecordWbs.length > 0) { + lines.push(reRecordWbs.join('\n')); + lines.push('视频暂不可用,已推送重新录制,请稍等通知录制结果'); + } + if (reRecordFailedWbs.length > 0) { + lines.push(reRecordFailedWbs.join('\n')); + lines.push('视频暂不可用,已登记补录,请稍后重试'); + } + if (noRecordWbs.length > 0) { + lines.push(noRecordWbs.join('\n')); + lines.push('无打包记录'); + } + if (orderMissingWbs.length > 0) { + lines.push(`未找到订单:${orderMissingWbs.join('、')}`); + } + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')}`); + } + if (skipped.length > 0) { + lines.push(`无权操作:${skipped.join('、')}`); + } + + ctx.logger.info( + `[inbox functions] 打包视频查询: total=${keywords.length} found=${validList.length} ` + + `video=${videoLines.length} reRecord=${reRecordWbs.length} reRecordFailed=${reRecordFailedWbs.length} ` + + `noRecord=${noRecordWbs.length}` + ); + + return { + success: true, + data: { + has_video: videoLines.length, + no_video: reRecordWbs.length + reRecordFailedWbs.length, + re_record: reRecordWbs.length, + re_record_failed: reRecordFailedWbs.length, + no_record: noRecordWbs.length, + message: lines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 打包视频查询失败: ${error.message}`); + return { success: false, error: `打包视频查询失败: ${error.message}` }; + } + }, + }); + + this.register('queryWeight', { + description: '查重(重量查询)。传入运单号,返回该运单的快递称重重量;重量为0或未称重时提示未称重。仅查询,不创建工单', + weight: 85, + keywords: [ '查重', '重量', '核实重量', '核重', '称重', '多重' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES, GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:AS 开头为售后工单号,不是运单号 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + const { Op } = ctx.app.Sequelize; + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'store_id', 'weighing_weight' ], + where: { + waybill_code: { [Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = keywords.filter(k => !foundCodes.has(k)); + + // 鉴权:货主群需验 store_id + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { + skipped.push(e.waybill_code); + continue; + } + } + validList.push(e); + } + + if (validList.length === 0) { + const parts = []; + if (notFound.length > 0) parts.push(`未找到运单:${notFound.join('、')}`); + if (skipped.length > 0) parts.push(`无权操作:${skipped.join('、')}`); + return { + success: false, + error: parts.join(';') || `未找到运单号「${raw}」,请核实单号后重试`, + }; + } + + // 组装模板:每个运单一行,只输出重量;重量为0 → 未称重 + const lines = []; + for (const e of validList) { + const weight = Number(e.weighing_weight) || 0; + lines.push(weight > 0 ? `${e.waybill_code}:${weight}g` : `${e.waybill_code}:未称重`); + } + if (notFound.length > 0) { + lines.push(`未找到运单:${notFound.join('、')}`); + } + if (skipped.length > 0) { + lines.push(`无权操作:${skipped.join('、')}`); + } + + ctx.logger.info( + `[inbox functions] 查重: total=${keywords.length} found=${validList.length} ` + + `notFound=${notFound.length} skipped=${skipped.length}` + ); + + return { + success: true, + data: { + waybills: validList.map(e => e.waybill_code), + message: lines.join('\n'), + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 查重失败: ${error.message}`); + return { success: false, error: `查重失败: ${error.message}` }; + } + }, + }); + + this.register('handleExpressFeedback', { + description: '快递群售后通用反馈。传入运单号,优先找已有售后工单追加记录,无工单则按运单查订单并自动创建售后工单。AI 可根据快递反馈内容传入售后类型和子类型', + weight: 90, + keywords: [ '已处理', '已联系', '已通知', '核实', '反馈' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔' }, + as_type: { type: 'string', required: false, description: '新建工单时的售后类型(order/receiving),默认 order' }, + as_sub_type: { type: 'string', required: false, description: '新建工单时的售后子类型,默认 logistics_issue。可选: logistics_issue(物流异常)/damage(破损)/missing_item(少发)/delivery_delay(发货延迟)/urge(催件)/verify_delivery(核实签收)/change_carrier(换快递)/rejected(拒收)/other(其他)' }, + }, + groups: [ GROUP.BOUND_EXPRESS_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const asType = String(params.as_type || 'order').trim() || 'order'; + const asSubType = String(params.as_sub_type || 'logistics_issue').trim() || 'logistics_issue'; + + // 工单详细描述中的售后类型/子类型显示中文名称(存储仍用英文编码) + const asTypesMeta = (ctx.model.AfterSale && ctx.model.AfterSale.AFTER_SALE_TYPES) || []; + const asTypeMeta = asTypesMeta.find(t => t.type === asType); + const asTypeName = (asTypeMeta && asTypeMeta.name) || asType; + const asSubTypeMeta = asTypeMeta && Array.isArray(asTypeMeta.subType) + ? asTypeMeta.subType.find(s => s.value === asSubType) + : null; + const asSubTypeName = (asSubTypeMeta && asSubTypeMeta.name) || asSubType; + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + try { + // 第一步:查已有售后工单 + const existingAS = await ctx.model.AfterSale.findAll({ + attributes: [ 'id', 'after_sale_no', 'waybill_no', 'status', 'warehouse_id', 'inbox_message_id', 'store_id' ], + where: { + waybill_no: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const hasAS = new Set(existingAS.map(r => r.waybill_no)); + let feedbackCount = 0; + let createdCount = 0; + const parts = []; + + // 已有工单:追加反馈 + // 获取原始消息内容用于反馈记录 + let feedbackMsgContent = ''; + try { + const fbMsgId = ctx.inboxContext?.inbound_message_id; + if (fbMsgId) { + const fbMsg = await ctx.model.InboxMessage.findByPk(fbMsgId, { + attributes: [ 'content' ], + raw: true, + }); + if (fbMsg && fbMsg.content) feedbackMsgContent = String(fbMsg.content); + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 获取原消息内容失败: ${e.message}`); + } + const feedbackGroup = ctx.inboxContext?.group_name || '未知群'; + const feedbackUser = ctx.inboxContext?.user_name || '未知用户'; + for (const as of existingAS) { + try { + const remarkLines = [ + `群: ${feedbackGroup}`, + `用户: ${feedbackUser}`, + `时间: ${new Date().toISOString().slice(0, 19) + .replace('T', ' ')}`, + ]; + if (feedbackMsgContent) { + remarkLines.push(`原消息: ${feedbackMsgContent}`); + } + await ctx.service.systems.afterSale.addStep(as.id, { + step_status: 'processing', + action: '快递反馈', + remark: remarkLines.join('\n'), + }); + feedbackCount += 1; + } catch (e) { + ctx.logger.warn(`[inbox functions] 快递反馈失败 as_no=${as.after_sale_no}: ${e.message}`); + } + } + if (feedbackCount > 0) { + parts.push(`已有工单追加反馈: ${feedbackCount}个`); + } + + // 第二步:无工单的运单,查订单并创建售后工单 + const needCreate = keywords.filter(k => !hasAS.has(k)); + let expressList = []; + const createdAsNos = []; + if (needCreate.length > 0) { + expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'warehouse_id', 'order_id' ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: needCreate }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = needCreate.filter(k => !foundCodes.has(k)); + + for (const e of expressList) { + try { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const title = `[AI工单] 快递反馈 - ${e.waybill_code}`; + const description = [ + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + `售后类型: ${asTypeName}.${asSubTypeName}`, + '来源: 快递群反馈', + feedbackMsgContent ? `原文: ${feedbackMsgContent}` : '', + ].filter(Boolean).join('\n'); + + if (shouldSkipWorkOrder(ctx)) { + ctx.logger.info(`[inbox functions] 快递反馈: skip_work_order,跳过工单登记 ${e.waybill_code}`); + return { success: true, data: { message: '已记录快递反馈(本次不登记工单)', skipped_work_order: true } }; + } + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: asType, + sub_type: asSubType, + title, + description, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || null, + order_id: e.order_id || null, + }); + createdAsNos.push(afterSaleNo); + createdCount += 1; + } catch (e) { + ctx.logger.warn(`[inbox functions] 快递反馈建单失败 wb=${e.waybill_code}: ${e.message}`); + } + } + if (createdCount > 0) { + parts.push(`已创建工单: ${createdCount}个`); + } + if (notFound.length > 0) { + parts.push(`未找到运单: ${notFound.join('、')}`); + } + } + + ctx.logger.info( + `[inbox functions] 快递反馈: total=${keywords.length} ` + + `feedback=${feedbackCount} created=${createdCount}` + ); + + // 第三步:排除回复检查(仓库配置 inbox_reply_exclude_keywords) + let skipReply = false; + try { + const inboundMsgId = ctx.inboxContext?.inbound_message_id; + if (inboundMsgId) { + const [ inboundMsg, store ] = await Promise.all([ + ctx.model.InboxMessage.findByPk(inboundMsgId, { + attributes: [ 'id', 'content' ], + raw: true, + }), + ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'subject_config' ], + raw: true, + }), + ]); + + const excludeKeywords = (store && store.subject_config + && Array.isArray(store.subject_config.inbox_reply_exclude_keywords)) + ? store.subject_config.inbox_reply_exclude_keywords.filter(k => typeof k === 'string' && k.trim()) + : []; + + if (excludeKeywords.length > 0 && inboundMsg && inboundMsg.content) { + const msgContent = String(inboundMsg.content); + const matched = excludeKeywords.find(kw => msgContent.includes(kw)); + if (matched) { + skipReply = true; + ctx.logger.info( + `[inbox functions] 消息命中排除关键词「${matched}」,仅记录不通知` + ); + } + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 排除回复检查失败: ${e.message}`); + } + + let replyTargets = new Map(); + if (!skipReply) { + // 第四步:回信路由 + // - 已有工单且带 inbox_message_id → 查原始消息获取群信息 → 回信到原群 + // - 无工单或无 inbox_message_id → 回信到货主售后群 + replyTargets = new Map(); // group_id → { group_id, group_name, user_id, ext_data } + // 未命中排除关键词 → 直接反馈原文(按目标货主过滤掉其他货主的运单号) + const baseContent = feedbackMsgContent || (parts.join(';') || '处理完成'); + + // 运单号 → 货主ID 映射(用于按货主过滤原文中的运单号) + const waybillStoreMap = new Map(); + for (const e of expressList) { + if (e.waybill_code) waybillStoreMap.set(e.waybill_code, e.store_id ? Number(e.store_id) : null); + } + for (const as of existingAS) { + if (as.waybill_no && !waybillStoreMap.has(as.waybill_no) && as.store_id) { + waybillStoreMap.set(as.waybill_no, Number(as.store_id)); + } + } + + /** + * 从反馈原文中移除属于其他货主的运单号。 + * @param {string} content 原始文本。 + * @param {number|null} targetStoreId 目标货主ID,为空则不过滤。 + * @return {string} 过滤后的文本。 + */ + const filterOtherStoreWaybills = (content, targetStoreId) => { + if (!content || !targetStoreId) return content || ''; + let text = String(content); + for (const [ wb, sid ] of waybillStoreMap) { + if (sid && sid !== targetStoreId) { + text = text.split(wb).join(''); + } + } + return text.replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim(); + }; + + // 4a. 已有工单带 inbox_message_id:回信到原消息所在群(排除快递群) + const asWithMsgId = existingAS.filter(as => as.inbox_message_id); + let expressGroupIds = new Set(); + if (asWithMsgId.length > 0) { + const msgIds = [ ...new Set(asWithMsgId.map(as => as.inbox_message_id)) ]; + try { + const messages = await ctx.model.InboxMessage.findAll({ + attributes: [ 'id', 'group_id', 'user_id', 'group_name', 'user_name' ], + where: { id: { [ctx.app.Sequelize.Op.in]: msgIds } }, + raw: true, + }); + // 过滤快递群:原消息来自快递群的,不回信到快递群,走 4b 货主售后群 + const candidateGroupIds = [ ...new Set(messages.map(m => m.group_id).filter(Boolean)) ]; + let groupStoreMap = {}; + if (candidateGroupIds.length > 0) { + const groupRows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id', 'group_type', 'store_id' ], + where: { + group_id: { [ctx.app.Sequelize.Op.in]: candidateGroupIds }, + warehouse_id: warehouseId, + is_blocked: 0, + }, + raw: true, + }); + expressGroupIds = new Set( + groupRows.filter(g => g.group_type === 'express').map(g => g.group_id) + ); + groupStoreMap = Object.fromEntries( + groupRows.filter(g => g.store_id).map(g => [ g.group_id, Number(g.store_id) ]) + ); + } + for (const msg of messages) { + if (msg.group_id && !replyTargets.has(msg.group_id) && !expressGroupIds.has(msg.group_id)) { + replyTargets.set(msg.group_id, { + group_id: msg.group_id, + group_name: msg.group_name || '', + user_id: msg.user_id || '', + user_name: msg.user_name || '', + ext_data: null, + store_id: groupStoreMap[msg.group_id] || null, + }); + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 查原消息群信息失败: ${e.message}`); + } + } + + // 4b. 已有工单无 inbox_message_id + 新建工单 + 原消息来自快递群:回信到货主售后群 + const storeIdsForReply = new Set(); + // 已有工单无 inbox_message_id 的 store_id + for (const as of existingAS) { + if (!as.inbox_message_id && as.store_id) { + storeIdsForReply.add(as.store_id); + } + } + // 已有工单 inbox_message_id 指向快递群的(4a 已排除),也走货主售后群 + if (expressGroupIds && expressGroupIds.size > 0) { + for (const as of asWithMsgId) { + if (as.store_id) storeIdsForReply.add(as.store_id); + } + } + // 新建工单的 store_id(来自 OrderExpress 记录) + for (const e of expressList) { + if (!hasAS.has(e.waybill_code) && e.store_id) { + storeIdsForReply.add(e.store_id); + } + } + + if (storeIdsForReply.size > 0) { + try { + const storeGroups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ + storeIds: [ ...storeIdsForReply ], + warehouseId, + }); + for (const g of storeGroups) { + if (g.group_id && !replyTargets.has(g.group_id)) { + replyTargets.set(g.group_id, { + group_id: g.group_id, + group_name: g.group_name || '', + user_id: '', + user_name: '', + ext_data: g.ext_data || null, + store_id: g.store_id || null, + }); + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 查货主售后群失败: ${e.message}`); + } + } + + // 3c. 发送回信(直接反馈原文,按目标货主过滤其他货主的运单号) + for (const [ , target ] of replyTargets) { + const content = filterOtherStoreWaybills(baseContent, target.store_id); + if (!content) continue; + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: target.group_id, + group_name: target.group_name, + content, + ext_data: target.ext_data, + store_id: target.store_id || null, + }); + } + + if (replyTargets.size > 0) { + parts.push(`已回信到 ${replyTargets.size} 个群`); + } + } // if (!skipReply) + + if (skipReply) { + parts.push('消息命中排除关键词,仅记录不通知'); + } + + // 第五步:更新新建工单状态 + // - 已回信 → pending_feedback(等待外部通知)+ 跟踪时间 + // - 未回信/排除关键词 → processing(处理中) + // 注意:已有工单仅追加反馈,不改变原有状态 + if (createdAsNos.length > 0) { + try { + if (!skipReply && replyTargets && replyTargets.size > 0) { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, asType, asSubType + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { + where: { + after_sale_no: { [ctx.app.Sequelize.Op.in]: createdAsNos }, + warehouse_id: warehouseId, + }, + } + ); + ctx.logger.info( + `[inbox functions] ${createdAsNos.length} 个工单已通知客户群,升级 pending_feedback,${hours}h 后追踪` + ); + } else { + await ctx.model.AfterSale.update( + { status: 'processing', role_group: 'customer_service' }, + { + where: { + after_sale_no: { [ctx.app.Sequelize.Op.in]: createdAsNos }, + warehouse_id: warehouseId, + }, + } + ); + ctx.logger.info( + `[inbox functions] ${createdAsNos.length} 个工单未通知客户群,状态设为 processing` + ); + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 更新工单状态失败: ${e.message}`); + } + } + + return { + success: true, + data: { + feedback: feedbackCount, + created: createdCount, + message: parts.join(';') || '处理完成', + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 快递反馈处理失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('queryWarehouseAddress', { + description: '查询仓库收货地址(退货/退件寄回地址)。读取仓库配置中的 receiver_address。用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时调用。仅货主群和仓库群可用,快递群不可用', + weight: 80, + keywords: [ '仓库地址', '收货地址', '退货地址', '退件地址', '寄回地址', '寄件地址' ], + params: {}, + groups: [ GROUP.BOUND_STORE_WILDCARD, GROUP.BOUND_WAREHOUSE_WILDCARD ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!warehouseId) { + return { success: false, error: '无法获取仓库信息' }; + } + + try { + const store = await ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + + if (!store) { + return { success: false, error: `仓库 ${warehouseId} 不存在` }; + } + + // 读取仓库配置 subject_config.receiver_address(兼容 JSON 字符串形态) + let config = store.subject_config; + if (typeof config === 'string') { + try { + config = JSON.parse(config); + } catch (e) { + config = null; + } + } + if (!config || typeof config !== 'object' || Array.isArray(config)) { + config = {}; + } + + const receiverAddress = String(config.receiver_address || '').trim(); + + if (!receiverAddress) { + return { + success: true, + data: { + warehouse_id: warehouseId, + receiver_address: '', + message: '当前仓库未配置收货地址,请联系仓管在仓库设置中维护「仓库收货地址」', + direct_reply: true, + }, + }; + } + + // 配置中可能存的是字面 \n,转成真实换行便于群消息阅读 + const displayAddress = receiverAddress + .replace(/\\r\\n/g, '\n') + .replace(/\\n/g, '\n') + .replace(/\\r/g, '\n'); + + return { + success: true, + data: { + warehouse_id: warehouseId, + receiver_address: receiverAddress, + message: `仓库收货地址:\n${displayAddress}`, + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 查询仓库收货地址失败: ${error.message}`); + return { success: false, error: `查询仓库地址失败: ${error.message}` }; + } + }, + }); + + this.register('listGroups', { + description: '查询当前仓库的群列表,包含屏蔽状态(仅内部仓库群可用)', + params: {}, + groups: [ GROUP.BOUND_WAREHOUSE ], + weight: 0, + keywords: [ '群列表', '有哪些群', '群组' ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!warehouseId) { + return { success: false, error: '无法获取仓库信息' }; + } + + try { + const groups = await ctx.model.InboxGroup.findAll({ + attributes: [ 'id', 'group_name', 'is_blocked', 'created_at' ], + where: { warehouse_id: warehouseId }, + order: [[ 'created_at', 'DESC' ]], + limit: 20, + raw: true, + }); + + return { + success: true, + data: { + warehouse_id: warehouseId, + total: groups.length, + groups: groups.map(g => ({ + name: g.group_name, + blocked: g.is_blocked === 1, + created_at: g.created_at, + })), + }, + }; + } catch (error) { + return { success: false, error: `查询群列表失败: ${error.message}` }; + } + }, + }); + + this.register('openDoor', { + description: '开门:仓库群收到"开门"指令时调用,触发大门开启动作。回复内容为空,由 extend_props 指令驱动开门', + params: {}, + groups: [ GROUP.BOUND_WAREHOUSE ], + weight: 90, + keywords: [ '开门' ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + ctx.logger.info('[inbox functions] 执行开门指令'); + return { + success: true, + data: { + message: '', + direct_reply: true, + extend_props: { do: 'openDoor' }, + }, + }; + }, + }); + + this.register('registerLicensePlate', { + description: '到货登记:从当前消息中提取车牌号并登记。货主/仓库群发送"到货+车牌号"时调用', + params: {}, + groups: [ GROUP.BOUND_STORE, GROUP.BOUND_WAREHOUSE ], + weight: 90, + keywords: [ '到货' ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + + // 读取原消息内容提取车牌号 + let originalText = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) originalText = String(m.content); + } + } catch (e) { /* ignore */ } + + const carnum = extractLicensePlate(originalText); + if (!carnum) { + return { + success: false, + error: '未识别到车牌号,请发送:到货+车牌号\n例:到货 粤A12345', + }; + } + + // 写库登记(失败不阻塞回执,仅告警) + try { + await ctx.model.InboxArrivalRegister.create({ + warehouse_id: Number(ctx.inboxContext?.warehouse_id) || 0, + store_id: Number(ctx.inboxContext?.store_id) || null, + license_plate: carnum, + }); + } catch (e) { + ctx.logger.warn(`[inbox functions] 到货登记写库失败: ${e.message}`); + } + + ctx.logger.info(`[inbox functions] 到货登记车牌: ${carnum}`); + return { + success: true, + data: { + message: `车牌${carnum}已登记,请在6小时内入场,超时请重新登记`, + direct_reply: true, + carnum, + extend_props: { do: 'registerLicensePlate', value: carnum }, + }, + }; + }, + }); + + this.register('departure', { + description: '离场登记:消息含"离场"时调用,提取车牌号,查6小时内未消费的到货登记,标记消费并通知对应货主(优先收货群,其次售后群,发送失败换下一个群);当前消息不回执', + params: {}, + groups: [ GROUP.BOUND_WAREHOUSE ], + weight: 90, + keywords: [ '离场' ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + + // 读取原消息内容提取车牌号 + let originalText = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) originalText = String(m.content); + } + } catch (e) { /* ignore */ } + + const carnum = extractLicensePlate(originalText); + if (!carnum) { + return { + success: false, + error: '未识别到车牌号,请发送:车牌号+离场\n例:粤A12345离场', + }; + } + + const warehouseId = Number(ctx.inboxContext?.warehouse_id) || 0; + if (!warehouseId) { + return { success: false, error: '无法获取仓库信息' }; + } + + const { Op } = ctx.app.Sequelize; + + // 第一步:查6小时内未消费的到货登记 + const record = await ctx.model.InboxArrivalRegister.findOne({ + attributes: [ 'id', 'store_id', 'license_plate' ], + where: { + warehouse_id: warehouseId, + license_plate: carnum, + consumed: 0, + created_at: { [Op.gte]: ctx.app.Sequelize.literal('DATE_SUB(NOW(), INTERVAL 6 HOUR)') }, + }, + order: [[ 'created_at', 'DESC' ]], + raw: true, + }); + if (!record) { + // 区分提示:6小时内已消费过 → 重复离场;否则无有效登记 + const consumedRecord = await ctx.model.InboxArrivalRegister.findOne({ + attributes: [ 'id' ], + where: { + warehouse_id: warehouseId, + license_plate: carnum, + consumed: 1, + created_at: { [Op.gte]: ctx.app.Sequelize.literal('DATE_SUB(NOW(), INTERVAL 6 HOUR)') }, + }, + raw: true, + }); + if (consumedRecord) { + // 已离过场:静默处理,不回执不通知 + ctx.logger.info(`[inbox functions] 离场登记: 车牌=${carnum} 已离过场,静默忽略`); + return { + success: true, + data: { carnum, consumed: false, duplicate: true }, + }; + } + return { + success: false, + error: `未查询到车牌 ${carnum} 6小时内的有效登记,离场失败`, + }; + } + + // 第二步:乐观标记消费(防并发重复离场) + const [ affected ] = await ctx.model.InboxArrivalRegister.update( + { consumed: 1, consumed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP') }, + { where: { id: record.id, consumed: 0 } } + ); + if (affected !== 1) { + // 并发重复离场:静默处理,不回执不通知 + ctx.logger.info(`[inbox functions] 离场登记: 车牌=${carnum} 并发重复离场,静默忽略`); + return { + success: true, + data: { carnum, consumed: false, duplicate: true }, + }; + } + + // 第三步:通知对应货主(优先收货群,其次售后群,发送失败换下一个群) + const notifyResult = await this.notifyStoreReceiving( + warehouseId, record.store_id, + `${carnum}已卸货离场,本次收货完成,在清点中,请耐心等待清点结果,天豹云仓竭诚为您服务。` + ); + const pushed = notifyResult.pushed; + const pushedGroup = notifyResult.pushedGroup; + + ctx.logger.info( + `[inbox functions] 离场登记: 车牌=${carnum} 消费成功 ` + + `store_id=${record.store_id || '-'} pushed=${pushed} group=${pushedGroup || '-'}` + ); + + // 当前消息不回执(data 不含 message/extend_props → 规则引擎无回复) + return { + success: true, + data: { carnum, consumed: true, pushed, pushed_group: pushedGroup }, + }; + }, + }); + + this.register('enter', { + description: '进场登记:消息含"进场"时调用,提取车牌号,查6小时内未消费的到货登记,通知对应货主收货群"车辆已入场,等待卸货"(优先收货群,其次售后群,发送失败换下一个群);当前消息不回执', + params: {}, + groups: [ GROUP.BOUND_WAREHOUSE ], + weight: 90, + keywords: [ '进场' ], + handler: async (params = {}) => { + const { ctx } = this; + void params; + + // 读取原消息内容提取车牌号 + let originalText = ''; + try { + const mid = ctx.inboxContext?.inbound_message_id; + if (mid) { + const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true }); + if (m && m.content) originalText = String(m.content); + } + } catch (e) { /* ignore */ } + + const carnum = extractLicensePlate(originalText); + if (!carnum) { + return { + success: false, + error: '未识别到车牌号,请发送:车牌号+进场\n例:粤A12345进场', + }; + } + + const warehouseId = Number(ctx.inboxContext?.warehouse_id) || 0; + if (!warehouseId) { + return { success: false, error: '无法获取仓库信息' }; + } + + const { Op } = ctx.app.Sequelize; + + // 查6小时内未消费的到货登记(进场不改消费状态,离场时才消费) + const record = await ctx.model.InboxArrivalRegister.findOne({ + attributes: [ 'id', 'store_id', 'license_plate' ], + where: { + warehouse_id: warehouseId, + license_plate: carnum, + consumed: 0, + created_at: { [Op.gte]: ctx.app.Sequelize.literal('DATE_SUB(NOW(), INTERVAL 6 HOUR)') }, + }, + order: [[ 'created_at', 'DESC' ]], + raw: true, + }); + if (!record) { + return { + success: false, + error: `未查询到车牌 ${carnum} 6小时内的有效登记,请先登记到货`, + }; + } + + // 通知对应货主(优先收货群,其次售后群,发送失败换下一个群) + const notifyResult = await this.notifyStoreReceiving( + warehouseId, record.store_id, + `车辆${carnum}已入场,等待卸货` + ); + const pushed = notifyResult.pushed; + const pushedGroup = notifyResult.pushedGroup; + + ctx.logger.info( + `[inbox functions] 进场登记: 车牌=${carnum} ` + + `store_id=${record.store_id || '-'} pushed=${pushed} group=${pushedGroup || '-'}` + ); + + // 当前消息不回执(data 不含 message/extend_props → 规则引擎无回复) + return { + success: true, + data: { carnum, entered: true, pushed, pushed_group: pushedGroup }, + }; + }, + }); + } + + /** + * 通知货主(优先收货群 receiving,其次售后群 after_sales,发送失败换下一个群)。 + * @param {number} warehouseId 仓库ID。 + * @param {number|null} storeId 货主ID(为空时直接返回未推送)。 + * @param {string} content 通知内容。 + * @return {Promise<{pushed: boolean, pushedGroup: string}>} 推送结果。 + */ + async notifyStoreReceiving(warehouseId, storeId, content) { + const { ctx } = this; + let pushed = false; + let pushedGroup = ''; + if (!storeId) return { pushed, pushedGroup }; + + try { + const groupSvc = ctx.service.systems.inbox.group; + const [ receivingGroups, afterSalesGroups ] = await Promise.all([ + groupSvc.findStoreGroups({ storeIds: [ storeId ], warehouseId, subTypes: [ 'receiving' ] }), + groupSvc.findStoreGroups({ storeIds: [ storeId ], warehouseId, subTypes: [ 'after_sales' ] }), + ]); + const candidates = [ ...receivingGroups, ...afterSalesGroups ]; + for (const g of candidates) { + if (!g.group_id) continue; + const ok = await ctx.service.inbox.processor.writeOutboundReply({ + warehouse_id: warehouseId, + ext_id: `sys:store-notify:${warehouseId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`, + parent_id: null, + ext_data: g.ext_data || null, + group_id: g.group_id, + user_id: '', + group_name: g.group_name || '', + user_name: '', + store_id: g.store_id || null, + }, content, 'system'); + if (ok) { + pushed = true; + pushedGroup = g.group_name || g.group_id; + break; + } + ctx.logger.warn(`[inbox functions] 通知货主群 ${g.group_name || g.group_id} 推送失败,尝试下一个`); + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 通知货主失败: ${e.message}`); + } + + return { pushed, pushedGroup }; + } + + /** + * 注册一个函数。 + * + * @param {string} name 函数名称。 + * @param {Object} def 函数定义。 + * @param {string} def.description 函数描述(供 AI 理解用途)。 + * @param {Object} def.params 参数定义。 + * @param {string[]} def.groups 所属分组列表,按 {主分组}:{子分组} 格式。 + * 例如 ['common'] 或 ['bound:store', 'bound:store:after_sales']。 + * @param {number} [def.weight=0] 权重,值越大优先级越高,用于 AI 多函数匹配时排序。 + * @param {string[]} [def.keywords] 触发关键词,用于 AI 快速匹配用户意图。 + * @param {Function} def.handler 函数实现,接收 params 对象,返回结果。 + */ + register(name, def) { + if (!name || typeof name !== 'string') { + throw new Error('函数名称必须是非空字符串'); + } + if (!def || typeof def.handler !== 'function') { + throw new Error(`函数 ${name} 必须提供 handler 实现`); + } + this.registry.set(name, { + name, + description: String(def.description || ''), + params: def.params || {}, + groups: Array.isArray(def.groups) && def.groups.length > 0 + ? def.groups + : [ GROUP.COMMON ], + weight: Number.isFinite(def.weight) ? def.weight : 0, + keywords: Array.isArray(def.keywords) ? def.keywords : [], + handler: def.handler, + }); + this.ctx.logger.info(`[inbox functions] 注册函数: ${name} groups=${this.registry.get(name).groups.join(',')}`); + } + + /** + * 执行已注册的函数。 + * + * @param {string} name 函数名称。 + * @param {Object} [params={}] 函数参数。 + * @return {Promise} 函数执行结果。 + */ + async callFunction(name, params = {}) { + const def = this.registry.get(name); + if (!def) { + return { + success: false, + error: `未注册的函数: ${name},可用函数: ${Array.from(this.registry.keys()).join(', ')}`, + }; + } + + // 群类型权限过滤:按当前群的活跃分组校验函数可用性, + // 防止货主群调用快递群专属函数(如 handleExpressFeedback)等越权调用。 + // 无 groups 服务的场景(单元测试直接实例化)跳过校验,由调用方保证上下文。 + const groupsSvc = this.ctx.service && this.ctx.service.inbox && this.ctx.service.inbox.groups; + if (groupsSvc && typeof groupsSvc.isFunctionAvailable === 'function') { + const activeGroups = groupsSvc.resolveActiveGroups(); + if (!groupsSvc.isFunctionAvailable(def, activeGroups)) { + this.ctx.logger.warn( + `[inbox functions] 越权调用被拦截: ${name} ` + + `groups=${(def.groups || []).join(',')} active=${activeGroups.join(',')}` + ); + return { + success: false, + error: `函数 ${name} 在当前群类型下不可用,请通过对应类型的群发起`, + }; + } + } + + try { + const result = await def.handler(params); + return result && typeof result === 'object' ? result : { success: true, data: result }; + } catch (error) { + return { + success: false, + error: `函数 ${name} 执行异常: ${error.message}`, + }; + } + } +} + +module.exports = InboxFunctionsService; diff --git a/app/service/inbox/groups.js b/app/service/inbox/groups.js new file mode 100644 index 0000000..acfa82b --- /dev/null +++ b/app/service/inbox/groups.js @@ -0,0 +1,226 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * ## 群类型统一定义(唯一数据源) + * + * 所有 AI 函数分组常量(GROUP)、合法子类型映射(VALID_SUB_TYPES)、 + * 通配展开(WILDCARD_EXPAND)均由此结构自动派生,修改群类型只需维护此处。 + * + * @constant {Array<{type: string, label: string, mainGroup: string, wildcardGroup: string|null, subTypes: Array<{key: string, label: string}>}>} + */ +const GROUP_TYPES = [ + { + type: 'store', + label: '货主群', + mainGroup: 'bound:store', + wildcardGroup: 'bound:store:*', + subTypes: [ + { key: 'after_sales', label: '售后' }, + { key: 'finance', label: '财务' }, + { key: 'receiving', label: '收货' }, + ], + }, + { + type: 'warehouse', + label: '仓库群', + mainGroup: 'bound:warehouse', + wildcardGroup: 'bound:warehouse:*', + subTypes: [ + { key: 'receiving', label: '收货' }, + { key: 'production', label: '生产' }, + { key: 'stockout', label: '出库' }, + { key: 'finance', label: '财务' }, + { key: 'all', label: '全体' }, + { key: 'customer_service', label: '客服' }, + { key: 'exception', label: '异常' }, + ], + }, + { + type: 'express', + label: '快递群', + mainGroup: 'bound:express', + wildcardGroup: null, + subTypes: [ + { key: 'pickup', label: '揽收' }, + { key: 'after_sales', label: '售后' }, + ], + }, +]; + +// ========== 以下均为 GROUP_TYPES 的派生值,禁止手动修改 ========== + +/** + * AI 函数分组常量,由 {@link GROUP_TYPES} 自动生成。 + * @constant {Record} + */ +const GROUP = (() => { + const map = { COMMON: 'common' }; + for (const gt of GROUP_TYPES) { + const prefix = gt.mainGroup.split(':').pop(); + const upper = prefix.toUpperCase(); + map[`BOUND_${upper}`] = gt.mainGroup; + if (gt.wildcardGroup) { + map[`BOUND_${upper}_WILDCARD`] = gt.wildcardGroup; + } + for (const st of gt.subTypes) { + map[`BOUND_${upper}_${st.key.toUpperCase()}`] = `${gt.mainGroup}:${st.key}`; + } + } + return Object.freeze(map); +})(); + +/** + * 各群类型下合法的子类型 key → GROUP 常量映射,由 {@link GROUP_TYPES} 自动生成。 + * @constant {Record>} + */ +const VALID_SUB_TYPES = (() => { + const map = {}; + for (const gt of GROUP_TYPES) { + if (gt.subTypes.length === 0) continue; + const sub = {}; + for (const st of gt.subTypes) { + const prefix = gt.mainGroup.split(':').pop().toUpperCase(); + sub[st.key] = GROUP[`BOUND_${prefix}_${st.key.toUpperCase()}`]; + } + map[gt.type] = sub; + } + return Object.freeze(map); +})(); + +/** + * 通配展开映射,由 {@link GROUP_TYPES} 自动生成。 + * @constant {Record} + */ +const WILDCARD_EXPAND = (() => { + const map = {}; + for (const gt of GROUP_TYPES) { + if (!gt.wildcardGroup) continue; + const prefix = gt.mainGroup.split(':').pop().toUpperCase(); + const list = [ GROUP[`BOUND_${prefix}`] ]; + for (const st of gt.subTypes) { + list.push(GROUP[`BOUND_${prefix}_${st.key.toUpperCase()}`]); + } + map[gt.wildcardGroup] = list; + } + return Object.freeze(map); +})(); + +/** + * 群分组匹配服务。 + * 负责根据当前上下文解析可用分组、判断函数可见性、构建函数列表。 + * 纯策略/匹配逻辑,不涉及函数注册与执行。 + */ +class InboxGroupsService extends Service { + + /** + * 根据当前上下文解析可用分组集合。 + * + * - 始终包含 `common`(通用分组)。 + * - 根据 `groupType` + `subType` 查询 VALID_SUB_TYPES 激活对应的子分组。 + * - 只有 VALID_SUB_TYPES 中声明的 subType 才会生效,防止越界激活。 + * + * @param {Object} [opts] 可选覆盖参数。 + * @param {string} [opts.groupType] 群类型(store / warehouse / express)。 + * @param {string} [opts.subType] 子类型。 + * @return {string[]} 当前上下文中可用的分组列表。 + */ + resolveActiveGroups(opts = {}) { + const { ctx } = this; + const groups = [ GROUP.COMMON ]; + + const groupType = String( + opts.groupType || ctx.inboxContext?.group_type || '' + ).trim(); + const subType = String( + opts.subType || ctx.inboxContext?.sub_type || '' + ).trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + + const gtDef = GROUP_TYPES.find(gt => gt.type === groupType); + // warehouse/express 群不绑定货主(store_id 允许为空),无条件激活主分组; + // store 群必须有货主归属(storeId > 0)才激活,防止未绑定货主的群越权调用函数。 + if (gtDef && (groupType === 'express' || groupType === 'warehouse' || storeId > 0)) { + groups.push(gtDef.mainGroup); + const subMap = VALID_SUB_TYPES[groupType]; + if (subMap && subMap[subType]) { + groups.push(subMap[subType]); + } + } + + return groups; + } + + /** + * 判断某个函数在当前活跃分组集合中是否可用。 + * + * @param {Object} def 函数定义对象(含 `groups` 字段)。 + * @param {string[]} activeGroups 当前上下文的活跃分组列表。 + * @return {boolean} 该函数在当前分组中是否可用。 + */ + isFunctionAvailable(def, activeGroups) { + if (!Array.isArray(def.groups) || def.groups.length === 0) return true; + + const expanded = []; + for (const g of def.groups) { + if (WILDCARD_EXPAND[g]) { + expanded.push(...WILDCARD_EXPAND[g]); + } else { + expanded.push(g); + } + } + + return expanded.some(g => g === GROUP.COMMON || activeGroups.includes(g)); + } + + /** + * 获取指定分组下的函数列表。 + * + * @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部已注册函数。 + * @return {Array<{name: string, description: string, params: Object}>} 函数列表。 + */ + getFunctionList(activeGroups) { + const { ctx } = this; + const funcSvc = ctx.service.inbox.functions; + const list = []; + for (const [ name, def ] of funcSvc.registry) { + if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue; + list.push({ + name, + description: def.description, + params: def.params, + }); + } + return list; + } + + /** + * 构建函数列表的文本描述,供 AI prompt 使用。 + * + * @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部。 + * @return {string} 函数列表文本。 + */ + buildFunctionListText(activeGroups) { + const { ctx } = this; + const funcSvc = ctx.service.inbox.functions; + const lines = []; + for (const [ name, def ] of funcSvc.registry) { + if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue; + const paramEntries = Object.entries(def.params); + const paramStr = paramEntries.length > 0 + ? paramEntries.map(([ k, v ]) => `${k}(${v.type || 'string'}, ${v.required ? '必填' : '可选'}): ${v.description}`).join(', ') + : '无参数'; + const weightStr = def.weight ? ` [权重:${def.weight}]` : ''; + const keywordStr = def.keywords && def.keywords.length > 0 + ? ` [触发词:${def.keywords.join(',')}]` + : ''; + lines.push(`- ${name}${weightStr}${keywordStr}: ${def.description}。参数: ${paramStr}`); + } + return lines.join('\n'); + } +} + +module.exports = InboxGroupsService; +module.exports.GROUP_TYPES = GROUP_TYPES; +module.exports.GROUP = GROUP; diff --git a/app/service/inbox/index.js b/app/service/inbox/index.js new file mode 100644 index 0000000..e2cfd53 --- /dev/null +++ b/app/service/inbox/index.js @@ -0,0 +1,309 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('crypto'); + +/** + * 站内信查询/管理服务。 + * 提供消息列表、详情、对话链、回复、重推、统计等管理功能。 + */ +class InboxService extends Service { + /** + * 消息列表(按仓库/状态/方向/群筛选,分页)。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {string} [params.groupId] 按群ID筛选(精确匹配,用于群消息列表)。 + * @param {string} [params.direction] 消息方向筛选:inbound / outbound。 + * @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。 + * @param {string} [params.targetChannel] 目标渠道筛选。 + * @param {string} [params.keyword] 关键词搜索(ext_id / content)。 + * @param {number} [params.page=1] 页码。 + * @param {number} [params.pageSize=20] 每页数量。 + * @return {Promise<{list: Array, pagination: Object}>} 分页结果。 + */ + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + const page = Math.max(1, Number(params.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20)); + + const where = { + warehouse_id: warehouseId, + deleted_at: null, + }; + + // 按群ID筛选 + if (params.groupId && typeof params.groupId === 'string') { + const gid = params.groupId.trim(); + if (gid) where.group_id = gid; + } + + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') { + const status = Number(params.pushStatus); + if ([ 0, 1, 2, 3 ].includes(status)) { + where.push_status = status; + } + } + + if (params.keyword && typeof params.keyword === 'string') { + const keyword = `%${params.keyword.trim()}%`; + where[Op.or] = [ + { ext_id: { [Op.like]: keyword } }, + { content: { [Op.like]: keyword } }, + ]; + } + + const { count: total, rows } = await InboxMessage.findAndCountAll({ + attributes: { + exclude: [ 'ext_data', 'push_response' ], + }, + where, + order: [[ 'created_at', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + return { + list: rows, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < total, + }, + }; + } + + /** + * 消息详情(含 push_response)。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 消息详情。 + */ + async detail(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + const record = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + + if (!record) { + throw new Error('消息不存在或无权访问'); + } + + return record; + } + + /** + * 对话链查询(原消息 + 所有回信),按 parent_id 递归。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 对话链列表。 + */ + async thread(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + // 查找根消息 + const root = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!root) { + throw new Error('消息不存在或无权访问'); + } + + // 收集对话链:从根到叶 + const MAX_THREAD_DEPTH = 50; + const thread = [ root ]; + const visited = new Set([ root.id ]); + + // 查找所有回信(以 root.id 为 parent_id) + const replies = await InboxMessage.findAll({ + where: { + warehouse_id: warehouseId, + parent_id: root.id, + deleted_at: null, + }, + order: [[ 'created_at', 'ASC' ]], + }); + + for (const reply of replies) { + if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(reply.id); + thread.push(reply); + } + } + + // 如果当前消息不是根(有 parent_id),也向上查找原消息 + if (root.parent_id) { + const parent = await InboxMessage.findOne({ + where: { + id: root.parent_id, + warehouse_id: warehouseId, + deleted_at: null, + }, + }); + + if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(parent.id); + thread.unshift(parent); + } + } + + return thread; + } + + /** + * 系统回信:写入 outbound 记录。 + * @param {Object} data 回信数据。 + * @param {number} data.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {number} data.parentId 原消息ID。 + * @param {string} [data.content] 消息正文。 + * @param {Object} [data.extData] 透传数据。 + * @param {Object} [data.flags] 处理标记。 + * @return {Promise} 回信结果。 + */ + async reply(data = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(data.warehouseId); + const parentId = Number(data.parentId); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(parentId) || parentId <= 0) { + throw new Error('parentId 无效'); + } + + // 查找原消息 + const parent = await InboxMessage.findOne({ + where: { id: parentId, warehouse_id: warehouseId, deleted_at: null }, + }); + + if (!parent) { + throw new Error('原消息不存在或无权访问'); + } + + const extId = `sys:${crypto.randomUUID()}`; + + const result = await ctx.service.inbox.receiver.receive({ + ext_id: extId, + warehouse_id: warehouseId, + store_id: parent.store_id, + direction: 'outbound', + parent_id: parentId, + source_type: 'system', + source_extra: null, + content: data.content || null, + ext_data: data.extData || parent.ext_data, + flags: data.flags || {}, + }); + + return result; + } + + /** + * 推送统计(按仓库 + 方向汇总)。 + * @param {Object} params 统计参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {string} [params.direction] 消息方向筛选。 + * @return {Promise} 统计结果。 + */ + async stats(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + const where = { + warehouse_id: warehouseId, + }; + + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + // 按方向统计 + const directionStats = await InboxMessage.findAll({ + attributes: [ + 'direction', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'direction' ], + raw: true, + }); + + // 按推送状态统计 + const statusStats = await InboxMessage.findAll({ + attributes: [ + 'push_status', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'push_status' ], + raw: true, + }); + + // 最近24小时统计 + const recentWhere = { + ...where, + created_at: { + [Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000), + }, + }; + + const recentCount = await InboxMessage.count({ where: recentWhere }); + + return { + total_by_direction: directionStats, + total_by_status: statusStats, + recent_24h_count: recentCount, + }; + } +} + +module.exports = InboxService; diff --git a/app/service/inbox/message.js b/app/service/inbox/message.js new file mode 100644 index 0000000..8703ae8 --- /dev/null +++ b/app/service/inbox/message.js @@ -0,0 +1,780 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../lib/query_condition_parser'); + +/** 出站推送失败自动重推:默认失败时间窗(毫秒,30 分钟)——仓库未配置时兜底,超窗口的消息不再补推 */ +const DEFAULT_PUSH_RETRY_WINDOW_MS = 30 * 60 * 1000; +/** 出站推送失败自动重推:默认单轮最多重推条数(定时任务每 3 分钟扫一次) */ +const DEFAULT_PUSH_RETRY_LIMIT = 20; +/** 出站推送失败自动重推:单轮条数硬上限 */ +const MAX_PUSH_RETRY_LIMIT = 200; + +/** 仓库设置字段:站内信推送失败自动重发(嵌套对象,与「收货未入库提醒」同结构) */ +const PUSH_RETRY_FIELD = 'inbox_push_retry'; +/** 重发时间范围(分钟)上下限:与仓库设置字段元信息 setting/warehouse.js 保持一致 */ +const PUSH_RETRY_WINDOW_MINUTES_MIN = 1; +const PUSH_RETRY_WINDOW_MINUTES_MAX = 1440; +/** 重发时间范围默认值(分钟):仓库未配置时兜底 30 分钟 */ +const DEFAULT_PUSH_RETRY_WINDOW_MINUTES = 30; + +/** + * 从仓库设置(wms_store.subject_config)读取「站内信推送失败自动重发」配置。 + * + * 结构:`subject_config.inbox_push_retry = { enabled, window_minutes }`(同「收货未入库提醒」的嵌套口径)。 + * + * 兼容 JSON 字符串与缺失字段,**缺省即兜底 = 关闭**(未配置的仓库不重发): + * - 开关仅显式传入真值(true / 1 / '1' / 'true')才开启,其余情况(缺失/非法/假值)均为关闭; + * - 时间范围缺省/非法 → 30 分钟(仅接受 1-1440 的整数,单位分钟)。 + * + * @param {Object|string|null|undefined} rawSubjectConfig 原始 subject_config(raw 查询可能为字符串)。 + * @return {{enabled: boolean, windowMinutes: number}} 规范化后的配置。 + */ +function readPushRetryConfig(rawSubjectConfig) { + let parsed = rawSubjectConfig; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + parsed = null; + } + } + + const section = parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? parsed[PUSH_RETRY_FIELD] + : null; + + if (!section || typeof section !== 'object' || Array.isArray(section)) { + return { enabled: false, windowMinutes: DEFAULT_PUSH_RETRY_WINDOW_MINUTES }; + } + + // 兜底为关闭:只有显式开启才开启(不再把“缺失/无法识别”当作开启) + const rawEnabled = section.enabled; + const enabled = [ true, 1, '1', 'true' ].includes(rawEnabled); + + const rawWindowMinutes = Number(section.window_minutes); + const windowMinutes = Number.isInteger(rawWindowMinutes) + && rawWindowMinutes >= PUSH_RETRY_WINDOW_MINUTES_MIN + && rawWindowMinutes <= PUSH_RETRY_WINDOW_MINUTES_MAX + ? rawWindowMinutes + : DEFAULT_PUSH_RETRY_WINDOW_MINUTES; + + return { enabled, windowMinutes }; +} + +/** + * 站内信消息查询/管理服务。 + * 提供消息列表、详情、对话链、回复、统计等管理功能。 + */ +class InboxMessageService extends Service { + /** + * 消息列表(多条件筛选,分页)。 + * 支持两种参数风格: + * 1. 扁平风格:{ warehouseId, storeId, keyword, page, pageSize, ... } + * 2. 结构化风格:{ pagination: { page, pageSize }, where: { field: { operator, value } } } + * 时间字段使用 app.formatDate 统一格式化输出。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {Object} [params.pagination] 分页对象(结构化风格)。 + * @param {Object} [params.where] 结构化 where 条件,字段映射同 DB 列名。 + * @param {string|string[]} [params.storeId] 货主ID筛选。 + * @param {string|string[]} [params.groupId] 群ID筛选。 + * @param {string} [params.groupName] 群名称模糊搜索。 + * @param {string} [params.userName] 用户名模糊搜索。 + * @param {string} [params.content] 正文/keyword 模糊搜索。 + * @param {string} [params.sourceType] 来源类型:im / api / system。 + * @param {string} [params.direction] 消息方向:inbound / outbound。 + * @param {number} [params.pushStatus] 推送状态:0/1/2/3。 + * @param {string} [params.startDate] 开始日期。 + * @param {string} [params.endDate] 结束日期。 + * @param {number} [params.page=1] 页码。 + * @param {number} [params.pageSize=20] 每页数量。 + * @return {Promise<{list: Array, pagination: Object}>} 分页结果。 + */ + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + // 分页:优先取 pagination 对象,兜底扁平参数 + const pag = params.pagination || {}; + const page = Math.max(1, Number(pag.page || params.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pag.pageSize || params.pageSize) || 20)); + + // 基础条件 + const where = { + warehouse_id: warehouseId, + deleted_at: null, + }; + + // ── 结构化 where(operator 模式)── + if (params.where && typeof params.where === 'object') { + const parsed = parseWhereConditions({ + where: params.where, + app: ctx.app, + specialFieldMap: {}, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + // 合并解析出的条件 + if (Array.isArray(parsed.result.dynamicConditions)) { + Object.assign(where, ...parsed.result.dynamicConditions); + } + + // 前端约定:store_id = 0 视为无货主消息 → IS NULL + if (where.store_id !== undefined && where.store_id !== null) { + const sid = where.store_id; + // Sequelize 将 [0] 展开为 IN (0),需转为 IS NULL + if (Array.isArray(sid) && sid.length === 1 && sid[0] === 0) { + where.store_id = { [Op.is]: null }; + } else if (sid === 0 || sid === '0') { + where.store_id = { [Op.is]: null }; + } + } + } + + // ── 扁平参数(向后兼容,结构化 where 已设置的字段会被覆盖)── + + // 货主ID(-1 = 无货主消息,即 store_id IS NULL) + const rawStoreId = params.storeId; + if (rawStoreId === -1 || rawStoreId === '-1') { + where.store_id = { [Op.is]: null }; + } else { + const storeIds = this._normalizeIds(rawStoreId); + if (storeIds.length > 0) { + where.store_id = { [Op.in]: storeIds }; + } + } + + // 群ID + const groupIds = this._normalizeStrings(params.groupId); + if (groupIds.length > 0) { + where.group_id = { [Op.in]: groupIds }; + } + + // 群名称 + const groupName = String(params.groupName || '').trim(); + if (groupName) { + where.group_name = { [Op.like]: `%${groupName}%` }; + } + + // 用户名 + const userName = String(params.userName || '').trim(); + if (userName) { + where.user_name = { [Op.like]: `%${userName}%` }; + } + + // 关键词:content + group_name + user_name + const rawKw = params.content || params.keyword; + const keyword = Array.isArray(rawKw) + ? String(rawKw.filter(Boolean)[0] || '').trim() + : String(rawKw || '').trim(); + if (keyword) { + const like = { [Op.like]: `%${keyword}%` }; + where[Op.or] = [ + { content: like }, + { group_name: like }, + { user_name: like }, + ]; + } + + // 来源类型 + const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ]; + const sourceType = String(params.sourceType || '').trim(); + if (sourceType && VALID_SOURCE_TYPES.includes(sourceType)) { + where.source_type = sourceType; + } + + // 日期范围(扁平参数兜底,结构化 where 已通过 created_at 处理) + if (!where.created_at) { + const startDate = params.startDate || params.start_date; + const endDate = params.endDate || params.end_date; + if (startDate || endDate) { + where.created_at = {}; + if (startDate) where.created_at[Op.gte] = new Date(startDate); + if (endDate) where.created_at[Op.lte] = new Date(endDate); + } + } + + // 方向 + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + // 推送状态 + if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') { + const status = Number(params.pushStatus); + if ([ 0, 1, 2, 3 ].includes(status)) { + where.push_status = status; + } + } + + const { count: total, rows } = await InboxMessage.findAndCountAll({ + attributes: { + exclude: [ 'ext_data', 'push_response', 'target_channel' ], + }, + where, + order: [[ 'created_at', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + // 批量查货主备注名称(StoreWarehouse.store_remask) + const storeIdsInResult = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ]; + const storeNameMap = {}; + if (storeIdsInResult.length > 0) { + const contracts = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { + store_id: { [Op.in]: storeIdsInResult }, + warehouse_id: warehouseId, + }, + raw: true, + }); + for (const c of contracts) { + storeNameMap[c.store_id] = c.store_remask || ''; + } + } + + const formatDate = ctx.app.formatDate; + const list = rows.map(row => { + const obj = row && typeof row.toJSON === 'function' ? row.toJSON() : row; + return { + ...obj, + store_name: storeNameMap[obj.store_id] || '', + created_at: obj.created_at ? formatDate(obj.created_at) : '', + updated_at: obj.updated_at ? formatDate(obj.updated_at) : '', + pushed_at: obj.pushed_at ? formatDate(obj.pushed_at) : '', + }; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < total, + }, + }; + } + + /** + * 将入参统一为数字ID数组。 + * 支持逗号分隔字符串 "1,2,3" 或数组 [1,2,3]。 + * @param {string|string[]|number[]|undefined} val 入参。 + * @return {number[]} 去重后的数字数组。 + */ + _normalizeIds(val) { + if (val === undefined || val === null) return []; + const arr = Array.isArray(val) ? val : String(val).split(','); + return [ ...new Set(arr.map(Number).filter(v => Number.isFinite(v) && v > 0)) ]; + } + + /** + * 将入参统一为字符串数组(去重去空)。 + * @param {string|string[]|undefined} val 入参。 + * @return {string[]} 去重后的非空字符串数组。 + */ + _normalizeStrings(val) { + if (val === undefined || val === null) return []; + const arr = Array.isArray(val) ? val : String(val).split(','); + return [ ...new Set(arr.map(String).map(s => s.trim()).filter(Boolean)) ]; + } + + /** + * 消息详情(含 push_response)。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 消息详情。 + */ + async detail(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + const record = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + + if (!record) { + throw new Error('消息不存在或无权访问'); + } + + return record; + } + + /** + * 对话链查询(原消息 + 所有回信),按 parent_id 递归。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 对话链列表。 + */ + async thread(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + // 查找根消息 + const root = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!root) { + throw new Error('消息不存在或无权访问'); + } + + // 收集对话链:从根到叶 + const MAX_THREAD_DEPTH = 50; + const thread = [ root ]; + const visited = new Set([ root.id ]); + + // 查找所有回信(以 root.id 为 parent_id) + const replies = await InboxMessage.findAll({ + where: { + warehouse_id: warehouseId, + parent_id: root.id, + deleted_at: null, + }, + order: [[ 'created_at', 'ASC' ]], + }); + + for (const reply of replies) { + if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(reply.id); + thread.push(reply); + } + } + + // 如果当前消息不是根(有 parent_id),也向上查找原消息 + if (root.parent_id) { + const parent = await InboxMessage.findOne({ + where: { + id: root.parent_id, + warehouse_id: warehouseId, + deleted_at: null, + }, + }); + + if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(parent.id); + thread.unshift(parent); + } + } + + return thread; + } + + /** + * 推送统计(按仓库 + 方向汇总)。 + * @param {Object} params 统计参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @return {Promise} 统计结果。 + */ + async stats(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + const where = { + warehouse_id: warehouseId, + }; + + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + // 按方向统计 + const directionStats = await InboxMessage.findAll({ + attributes: [ + 'direction', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'direction' ], + raw: true, + }); + + // 按推送状态统计 + const statusStats = await InboxMessage.findAll({ + attributes: [ + 'push_status', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'push_status' ], + raw: true, + }); + + // 最近24小时统计 + const recentWhere = { + ...where, + created_at: { + [Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000), + }, + }; + + const recentCount = await InboxMessage.count({ where: recentWhere }); + + return { + total_by_direction: directionStats, + total_by_status: statusStats, + recent_24h_count: recentCount, + }; + } + + /** + * 手动重推失败(push_status=3)的站内信消息。 + * 重置为待推送状态(push_status=0)并触发异步推送; + * 推送结果回写到同一记录(复用原记录,不新建回执记录)。 + * @param {Object} params 重推参数。 + * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {number} params.id 消息ID。 + * @return {Promise} { ok, id, ext_id, message }。 + */ + async retry(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + const record = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + + if (!record) { + throw new Error('消息不存在或无权访问'); + } + if (record.push_status !== 3) { + throw new Error('仅失败状态的消息可以手动重推'); + } + + // 重置为待推送状态 + await InboxMessage.update( + { push_status: 0, push_response: null, push_started_at: null }, + { where: { id } } + ); + + // 触发异步推送(复用原记录回写推送结果) + setImmediate(() => { + this._repush(record).catch(async err => { + ctx.logger.error(`[inbox] 手动重推异步推送异常 id=${id}: ${err.message}`); + // 推送前校验失败时回写失败状态,避免消息卡在待推送 + try { + await InboxMessage.update( + { push_status: 3, push_response: { error: err.message } }, + { where: { id } } + ); + } catch (updateErr) { + ctx.logger.error(`[inbox] 重推失败状态回写异常 id=${id}: ${updateErr.message}`); + } + }); + }); + + return { + ok: true, + id: record.id, + ext_id: record.ext_id, + message: '已重置为待推送状态,正在异步重推', + }; + } + + /** + * 重推一条已存在的出站消息记录(推送结果回写到该记录本身,不新建记录)。 + * + * 与直接调用 processor.writeOutboundReply 的区别: + * - 传 reuse_message_id,让其跳过按 `sys:ack:{ext_id}` 查建,直接复用该记录; + * - 否则 sys:notice:* 类型(warehouseNotify 系统通知)会被另建一条 sys:ack:sys:notice:* + * 记录推送,原记录状态永远停留在失败/待推送,重推也无法继续。 + * 本方法推送期间不改动记录状态:推送完成由推送链路回写 2/3,进程中断则保持 3 等下一轮。 + * + * @param {Object} record 消息记录(InboxMessage 行,Sequelize 实例或 raw 对象)。 + * @return {Promise} 推送完成(结果已回写)。 + */ + async _repush(record) { + const { ctx } = this; + const extId = String(record.ext_id || ''); + // 回执记录 ext_id 形如 sys:ack:{原消息ext_id},反解出原消息 ext_id 以复用推送链路 + const originalExtId = extId.startsWith('sys:ack:') ? extId.slice(8) : extId; + const hasUser = Boolean(record.user_id && record.user_name); + + await ctx.service.inbox.processor.writeOutboundReply({ + warehouse_id: Number(record.warehouse_id) || 0, + ext_id: originalExtId, + parent_id: record.parent_id || null, + group_id: record.group_id || '', + group_name: record.group_name || '', + user_id: record.user_id || '', + user_name: record.user_name || '', + ext_data: record.ext_data || null, + reuse_message_id: Number(record.id) || 0, + }, record.content || '', hasUser ? 'ai_reply' : 'system', record.extend_props || null); + } + + /** + * 批量重推「推送失败」的出站消息(供定时任务调用)。 + * + * 规则: + * 1. 只处理失败时间(created_at)在窗口内的记录,默认 30 分钟;超窗口不再补推; + * 2. 逐条串行重推并等待结果回写,单条异常不影响其余记录; + * 3. 重推期间记录保持失败状态,进程中断时下一轮仍能被扫到(不丢消息); + * 4. 缺少 warehouse_id / group_id / group_name / content 的记录无法重放,跳过并计数。 + * + * @param {Object} [params] 查询参数。 + * @param {number} [params.warehouseId] 仓库ID:传入时只处理该仓库的失败消息(定时任务按仓库逐个处理)。 + * @param {number} [params.windowMs] 失败时间窗(毫秒),默认 config.inbox.pushRetryWindowMs。 + * @param {number} [params.limit] 单轮最多重推条数,默认 config.inbox.pushRetryLimit。 + * @return {Promise} { scanned, retried, succeeded, failed, skipped }。 + */ + async retryFailed(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const { InboxMessage } = ctx.model; + + const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {}; + const warehouseId = Number(params.warehouseId) > 0 ? Number(params.warehouseId) : 0; + const configuredWindow = Number(inboxConfig.pushRetryWindowMs); + const windowMs = Number(params.windowMs) > 0 + ? Number(params.windowMs) + : (configuredWindow > 0 ? configuredWindow : DEFAULT_PUSH_RETRY_WINDOW_MS); + const configuredLimit = Number(inboxConfig.pushRetryLimit); + const rawLimit = Number(params.limit) > 0 + ? Number(params.limit) + : (configuredLimit > 0 ? configuredLimit : DEFAULT_PUSH_RETRY_LIMIT); + const limit = Math.min(MAX_PUSH_RETRY_LIMIT, Math.max(1, Math.trunc(rawLimit))); + + // 先补早失败的消息(更快接近时间窗边界) + const where = { + direction: 'outbound', + push_status: 3, + created_at: { [Op.gte]: new Date(Date.now() - windowMs) }, + }; + // 仓库维度(定时任务逐仓处理):只扫该仓库的失败消息 + if (warehouseId > 0) { + where.warehouse_id = warehouseId; + } + + const rows = await InboxMessage.findAll({ + where, + attributes: [ + 'id', 'warehouse_id', 'ext_id', 'parent_id', + 'group_id', 'group_name', 'user_id', 'user_name', + 'ext_data', 'content', 'extend_props', + ], + order: [[ 'created_at', 'ASC' ], [ 'id', 'ASC' ]], + limit, + raw: true, + }); + + const summary = { scanned: rows.length, retried: 0, succeeded: 0, failed: 0, skipped: 0 }; + + for (const row of rows) { + // 空文案但含 extend_props 的回执(如开门指令)可重放;两者皆空才跳过 + if (!(Number(row.warehouse_id) > 0) || !row.group_id || !row.group_name + || (!row.content && !row.extend_props)) { + summary.skipped++; + ctx.logger.warn(`[inbox] 自动重推跳过消息 id=${row.id}(缺少 warehouse_id/group_id/group_name/content+extend_props,无法重放)`); + continue; + } + + try { + await this._repush(row); + summary.retried++; + + const fresh = await InboxMessage.findOne({ + where: { id: row.id }, + attributes: [ 'push_status' ], + raw: true, + }); + if (fresh && Number(fresh.push_status) === 2) { + summary.succeeded++; + } else { + summary.failed++; + } + + // 已重试次数仅作观测;失败不影响主流程 + try { + await InboxMessage.increment('retry_count', { where: { id: row.id } }); + } catch (countErr) { + ctx.logger.warn(`[inbox] 自动重推计数失败 id=${row.id}: ${countErr.message}`); + } + } catch (error) { + summary.failed++; + ctx.logger.warn(`[inbox] 自动重推异常 id=${row.id}: ${error.message}`); + } + } + + return summary; + } + + /** + * 按仓库设置批量重推「推送失败」的出站消息(定时任务入口)。 + * + * 流程: + * 1. 全局总开关(config.inbox.pushRetryEnabled)关闭时直接返回,支持运维应急停发; + * 2. 先找出「近 1440 分钟(时间范围上限)内存在推送失败消息」的仓库,只对这些仓库读设置, + * 避免每轮全仓扫描; + * 3. 逐仓判断仓库设置 `subject_config.inbox_push_retry.enabled`(缺省关闭,仅显式开启才重推):关闭则跳过; + * 4. 开启的仓库按 `subject_config.inbox_push_retry.window_minutes`(缺省 30 分钟) + * 调 retryFailed 只补该窗口内的失败消息。 + * + * @param {Object} [params] 调用参数。 + * @param {number} [params.limit] 单仓单轮最多重推条数,默认 config.inbox.pushRetryLimit。 + * @return {Promise} { warehouses, enabledWarehouses, disabledWarehouses, skippedWarehouses, + * scanned, retried, succeeded, failed, skipped, disabledGlobally }。 + */ + async retryFailedByWarehouse(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const { InboxMessage, Store } = ctx.model; + + const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {}; + const summary = { + warehouses: 0, + enabledWarehouses: 0, + disabledWarehouses: 0, + skippedWarehouses: 0, + scanned: 0, + retried: 0, + succeeded: 0, + failed: 0, + skipped: 0, + disabledGlobally: false, + }; + + // 全局总开关:仓库维度开关在仓库设置里 + if (inboxConfig.pushRetryEnabled === false) { + summary.disabledGlobally = true; + ctx.logger.warn('[inbox] 自动重推已被全局开关(config.inbox.pushRetryEnabled)关闭'); + return summary; + } + + // 候选仓库:时间范围上限内存在失败消息的仓库(去重),只查有失败的仓库 + const maxWindowMs = PUSH_RETRY_WINDOW_MINUTES_MAX * 60 * 1000; + const warehouseRows = await InboxMessage.findAll({ + where: { + direction: 'outbound', + push_status: 3, + created_at: { [Op.gte]: new Date(Date.now() - maxWindowMs) }, + }, + attributes: [ 'warehouse_id' ], + group: [ 'warehouse_id' ], + raw: true, + }); + const warehouseIds = (Array.isArray(warehouseRows) ? warehouseRows : []) + .map(row => Number(row && row.warehouse_id) || 0) + .filter(id => id > 0); + summary.warehouses = warehouseIds.length; + + if (warehouseIds.length === 0) { + return summary; + } + + const storeModel = Store; + if (!storeModel || typeof storeModel.findAll !== 'function') { + ctx.logger.warn('[inbox] Store 模型不可用,跳过自动重推'); + summary.skippedWarehouses = warehouseIds.length; + return summary; + } + + // 批量取仓库设置(raw 行避免脏配置触发模型 getter 抛错); + // 不按 status 过滤:wms_store.status 是启用/审核中状态(非仓库标识), + // 且仓库设置里的开关才是唯一控制项,避免审核中/停用仓库的回信被静默跳过而永久丢失 + const storeRows = await storeModel.findAll({ + where: { id: { [Op.in]: warehouseIds }, deleted_at: null }, + attributes: [ 'id', 'company_name', 'subject_config' ], + raw: true, + }); + const configMap = new Map(); + for (const storeRow of Array.isArray(storeRows) ? storeRows : []) { + const id = Number(storeRow && storeRow.id) || 0; + if (id > 0) { + configMap.set(id, storeRow); + } + } + + for (const warehouseId of warehouseIds) { + const storeRow = configMap.get(warehouseId); + if (!storeRow) { + summary.skippedWarehouses++; + ctx.logger.warn(`[inbox] 自动重推跳过仓库 ${warehouseId}(wms_store 无该仓库记录,无法读取仓库设置)`); + continue; + } + + const retryConfig = readPushRetryConfig(storeRow.subject_config); + if (!retryConfig.enabled) { + summary.disabledWarehouses++; + continue; + } + summary.enabledWarehouses++; + + const result = await this.retryFailed({ + warehouseId, + windowMs: retryConfig.windowMinutes * 60 * 1000, + limit: params.limit, + }); + + summary.scanned += result.scanned; + summary.retried += result.retried; + summary.succeeded += result.succeeded; + summary.failed += result.failed; + summary.skipped += result.skipped; + + if (result.scanned > 0) { + ctx.logger.info( + `[inbox] 仓库 ${warehouseId}(${String(storeRow.company_name || '').trim() || '-'})自动重推:` + + `窗口 ${retryConfig.windowMinutes} 分钟 scanned=${result.scanned} retried=${result.retried} ` + + `succeeded=${result.succeeded} failed=${result.failed} skipped=${result.skipped}` + ); + } + } + + return summary; + } +} + +module.exports = InboxMessageService; diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js new file mode 100644 index 0000000..19e13ff --- /dev/null +++ b/app/service/inbox/processor.js @@ -0,0 +1,1183 @@ +'use strict'; + +const Service = require('egg').Service; +const { normalizeExtDataSource } = require('../../lib/inbox_channel'); + +const WAREHOUSE_INTERFACE_TYPE_ID = 3; + +/** 历史消息过滤默认阈值:发送时间距今超过 10 分钟视为历史/补推消息,跳过 AI(可用 config.inbox.historyMessageMaxAgeMs 覆盖) */ +const DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS = 10 * 60 * 1000; + +/** + * 站内信内容处理器。 + * 负责解析入站消息正文,按 source_type 分流处理, + * 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。 + */ +class InboxProcessorService extends Service { + + /** + * 从数据库拉取群信息(不缓存)。 + * Egg Service 按请求实例化,进程内缓存无法跨请求共享, + * 直接查库可保证 inbox.group.update/reset 修改群配置后下一条消息立即生效。 + * 若群 ext_data 为空且消息携带 ext_data,自动写回群配置。 + * @param {string} groupId 外部群ID + * @param {number} warehouseId 仓库ID + * @param {Object|null} msgExtData 入站消息的 ext_data + * @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, template_reply_enabled: number, ext_data: Object|null}>} 群类型/子类型/AI开关/模板回信开关/扩展数据 + */ + async _loadGroupInfo(groupId, warehouseId, msgExtData) { + const { ctx } = this; + + let group = null; + try { + group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_type', 'sub_type', 'ai_enabled', 'template_reply_enabled', 'ext_data' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + } catch (e) { + ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); + } + + const info = { + group_type: (group && group.group_type) || '', + sub_type: (group && group.sub_type) || '', + ai_enabled: group ? group.ai_enabled : 0, + template_reply_enabled: group ? group.template_reply_enabled : 0, + ext_data: (group && group.ext_data) || null, + }; + + // 群存在但 ext_data 为空,且入站消息带有 ext_data → 写回群配置 + // 写回前按群ID格式校正渠道来源,避免把错误渠道固化进群配置 + if (group && !info.ext_data && msgExtData && typeof msgExtData === 'object' && Object.keys(msgExtData).length > 0) { + try { + const normalizedExt = normalizeExtDataSource(groupId, msgExtData); + await ctx.model.InboxGroup.update( + { ext_data: normalizedExt }, + { where: { group_id: groupId, warehouse_id: warehouseId } } + ); + info.ext_data = normalizedExt; + ctx.logger.info(`[inbox processor] 群 ext_data 写回成功: ${groupId}`); + } catch (e) { + ctx.logger.warn(`[inbox processor] 群 ext_data 写回失败: ${e.message}`); + // 写回失败不阻塞,直接返回 info(ext_data 仍为空) + return info; + } + } + + return info; + } + + /** + * 判断消息是否为历史消息(发送时间距今超过阈值)。 + * - flags.skipAi === true:外部显式要求跳过 AI。 + * - flags.send_time 距今超过 config.inbox.historyMessageMaxAgeMs:视为历史/补推消息。 + * - 未携带发送时间:按实时消息处理(向后兼容)。 + * @param {Object} data 入站消息数据。 + * @return {boolean} 是否应跳过 AI 处理。 + */ + isStaleMessage(data = {}) { + const flags = data.flags || {}; + if (flags.skipAi === true) return true; + + const sendTime = Number(flags.send_time || 0); + if (!Number.isFinite(sendTime) || sendTime <= 0) return false; + + const maxAgeMs = Number(this.app.config.inbox?.historyMessageMaxAgeMs); + const threshold = Number.isFinite(maxAgeMs) && maxAgeMs > 0 + ? maxAgeMs + : DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS; + + return Date.now() - sendTime > threshold; + } + /** + * 处理入站消息内容。 + * 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。 + * + * @param {Object} data 入站消息数据。 + * @param {string} data.content 消息正文。 + * @param {number} [data.warehouse_id] 仓库ID(优先使用显式传入值)。 + * @param {number} [data.store_id] 货主ID(优先使用显式传入值)。 + * @return {Promise<{warehouse_id: number|null, store_id: number|null, content: string}>} 处理结果。 + */ + async process(data = {}) { + const { ctx } = this; + + const content = String(data.content || '').trim(); + if (!content) { + throw new Error('消息正文 content 不能为空'); + } + + // warehouse_id:优先取显式传入,否则尝试从 content 中解析 + let warehouseId = data.warehouse_id != null ? Number(data.warehouse_id) : null; + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + warehouseId = this.extractWarehouseId(content) || this.getWarehouseIdFromContext(); + } + + // store_id:优先取显式传入,否则尝试从 content 中解析 + let storeId = data.store_id != null ? Number(data.store_id) : null; + if (!Number.isFinite(storeId) || storeId <= 0) { + storeId = this.extractStoreId(content) || this.getStoreIdFromContext(); + } + + // 写入 ctx 上下文,供下游使用 + if (!ctx.inboxContext) { + ctx.inboxContext = {}; + } + ctx.inboxContext.warehouse_id = warehouseId || null; + ctx.inboxContext.store_id = storeId || null; + ctx.inboxContext.group_name = data.group_name || null; + ctx.inboxContext.user_name = data.user_name || null; + ctx.inboxContext.group_id = data.group_id || null; + ctx.inboxContext.user_id = data.user_id || null; + + ctx.logger.info( + '[inbox processor] 内容处理完成 ' + + `warehouse_id=${ctx.inboxContext.warehouse_id} ` + + `store_id=${ctx.inboxContext.store_id} ` + + `content_length=${content.length}` + ); + + return { + warehouse_id: ctx.inboxContext.warehouse_id, + store_id: ctx.inboxContext.store_id, + content, + }; + } + + /** + * API 来源消息异步回执。 + * 处理消息正文后,向仓库 ApiApp 回调地址 POST 确认回执。 + * 回执内容为"收到",ext_data 原路带回。 + * 异步执行,不阻塞入站响应。 + * + * @param {Object} data 入站消息数据。 + * @param {number} data.warehouse_id 仓库ID。 + * @param {number} [data.store_id] 货主ID。 + * @param {number} [data.parent_id] 入站消息记录ID(回执的 parent_id)。 + * @param {Object} [data.ext_data] 原始透传数据。 + * @param {string} [data.ext_id] 外部消息ID。 + * @param {string} [data.content] 消息正文。 + * @return {Promise} 无返回值,异常仅记日志不抛出。 + */ + async handleApiMessage(data = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(data.warehouse_id) || 0; + const extId = String(data.ext_id || ''); + const parentId = Number(data.parent_id) || null; + + try { + // 1. 处理消息正文,挂载上下文 + await this.process(data); + + // 2. 屏蔽检查 + const isBlocked = await this.isBlocked(); + if (isBlocked) { + ctx.logger.info(`[inbox processor] 已屏蔽,跳过回执 ext_id=${extId}`); + return; + } + + // 2.5 历史消息过滤:发送时间距今超过阈值的历史/补推消息不触发绑群与 AI,防止误建工单 + if (this.isStaleMessage(data)) { + ctx.logger.info(`[inbox processor] 历史消息,跳过 AI 处理 ext_id=${extId}`); + return; + } + + // 3. 绑群码识别:消息匹配"授权:CODE"时执行绑群 + const bindHandled = await this.tryBindGroup(data); + if (bindHandled) return; + + // 4. 加载群的 group_type / sub_type / ai_enabled / ext_data(带缓存 + 自动写回) + if (ctx.inboxContext.ai_enabled === undefined) { + const groupId = String(ctx.inboxContext.group_id || '').trim(); + if (groupId) { + const info = await this._loadGroupInfo(groupId, warehouseId, data.ext_data || null); + ctx.inboxContext.group_type = info.group_type; + ctx.inboxContext.sub_type = info.sub_type; + ctx.inboxContext.ai_enabled = info.ai_enabled; + ctx.inboxContext.template_reply_enabled = info.template_reply_enabled; + ctx.inboxContext.group_ext_data = info.ext_data; + } else { + ctx.inboxContext.ai_enabled = 0; + } + } + + // 4.5 群未绑定任务类型 → 跳过 AI 处理 + const groupType = String(ctx.inboxContext.group_type || '').trim(); + if (!groupType) { + ctx.logger.info(`[inbox processor] 群未绑定任务类型,跳过 AI ext_id=${extId}`); + return; + } + + // 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认) + // 快递群默认 ai_enabled=0,需手动开启后才会走 AI 处理 + // v2 例外:模板回信引擎(template_reply_enabled=1)优先于原链路, + // 即使 ai_enabled=0 也进入第 6 步走 v2;两开关同开时仍走 v2 不走 v1/AI。 + const v2Enabled = ctx.inboxContext.template_reply_enabled === 1; + if (ctx.inboxContext.ai_enabled !== 1 && !v2Enabled) { + ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); + return; + } + + // 5.1 加载屏蔽用户列表,注入上下文供 AI 判断真人接管 + if (!ctx.inboxContext._blockedUserIds) { + try { + ctx.inboxContext._blockedUserIds = await this.loadBlockedUserIds(warehouseId); + } catch (e) { + ctx.logger.warn(`[inbox processor] 加载屏蔽用户列表失败: ${e.message}`); + ctx.inboxContext._blockedUserIds = new Set(); + } + } + + // 5.2 注入入站消息ID,供下游函数(如 interceptWaybill)关联工单 + ctx.inboxContext.inbound_message_id = parentId || null; + + // 6. 关键词规则引擎(主回复路径,不走 AI,节省推理费用) + // v2 分叉:群开启模板回信引擎(template_reply_enabled=1)时走 v2 可配置引擎, + // 模块接管模式——v2 未命中直接静默返回,不再走 v1 规则与 AI 兜底。 + const text = String(data.content || '').trim(); + const ruleResult = v2Enabled + ? await ctx.service.inbox.v2.rules.handle(text) + : await ctx.service.inbox.rules.handle(text); + if (ruleResult.handled) { + // 记录规则命中轨迹到入站消息,便于排查 + if (ruleResult.thoughts && ruleResult.thoughts.length > 0) { + try { + await InboxMessage.update( + { ai_thoughts: ruleResult.thoughts }, + { where: { ext_id: extId } } + ); + } catch (e) { + ctx.logger.warn(`[inbox processor] 保存规则处理记录失败: ${e.message}`); + } + } + + if (ruleResult.silent) { + ctx.logger.info(`[inbox processor] 规则静默(无需回复) ext_id=${extId}`); + return; + } + + if (ruleResult.reply || (ruleResult.result && ruleResult.result.data && ruleResult.result.data.extend_props)) { + // 支持多条回复(如查退回多单号):逐条独立回信; + // 也支持空文案回执(如开门:content 为空,仅靠 extend_props 指令驱动) + const ruleExtendProps = ruleResult.result && ruleResult.result.data && ruleResult.result.data.extend_props; + const replies = Array.isArray(ruleResult.reply) ? ruleResult.reply : [ ruleResult.reply || '' ]; + ctx.logger.info( + `[inbox processor] 规则引擎处理完成 ext_id=${extId} ` + + `fn=${ruleResult.fn || '-'} key=${ruleResult.matchedKey || '-'} replies=${replies.length}` + ); + // 快递群:仅执行函数,不回信 + if (groupType === 'express') { + ctx.logger.info(`[inbox processor] 快递群规则处理完成(不回信) ext_id=${extId}`); + return; + } + for (let idx = 0; idx < replies.length; idx++) { + const replyContent = replies[idx]; + // 多条回复时每条独立 ext_id,避免回执唯一键冲突 + const replyExtId = replies.length > 1 ? `${extId}:r${idx}` : extId; + await this.writeOutboundReply({ + warehouse_id: warehouseId, + ext_id: replyExtId, + parent_id: parentId, + ext_data: data.ext_data || null, + group_id: ctx.inboxContext?.group_id || data.group_id || null, + user_id: ctx.inboxContext?.user_id || data.user_id || null, + group_name: ctx.inboxContext?.group_name || data.group_name || null, + user_name: ctx.inboxContext?.user_name || data.user_name || null, + }, replyContent, 'rule_reply', ruleExtendProps); + } + } else { + ctx.logger.info(`[inbox processor] 规则已执行但无回复内容 ext_id=${extId} fn=${ruleResult.fn || '-'}`); + } + return; + } + + // 6.1 v2 模块接管:开启模板回信引擎的群,未命中后直接静默,不走 v1 规则与 AI 兜底 + if (v2Enabled) { + ctx.logger.info( + `[inbox processor] v2 引擎未命中,静默(模板回信群不走 v1/AI) ext_id=${extId} ` + + `content=${text.slice(0, 80)}` + ); + return; + } + + // 6.5 AI 兜底(默认关闭,config.inbox.aiFallback=true 时启用) + const aiFallback = !!(this.app.config.inbox && this.app.config.inbox.aiFallback); + if (!aiFallback) { + ctx.logger.info( + `[inbox processor] 规则未命中且AI兜底关闭,静默 ext_id=${extId} ` + + `content=${String(data.content || '').slice(0, 80)}` + ); + return; + } + + // 7. DeepSeek 两步交互(AI 兜底,内部自行判断真人接管) + const aiResult = await ctx.service.inbox.ai.processWithAI({ + content: data.content || '', + ext_data: data.ext_data || null, + parentId: data.parent_id || null, + }); + + // 无回复且无函数调用 → 跳过,节约资源 + // AI 显式指示跳过(silent 动作)→ 同上 + if (aiResult.skip || (!aiResult.reply && (!aiResult.functionName || aiResult.functionName === 'none'))) { + ctx.logger.info(`[inbox processor] 无回复且未匹配函数,跳过回执 ext_id=${extId}`); + // 保存 AI 思考过程到入站消息,便于排查 + if (aiResult.thoughts && aiResult.thoughts.length > 0) { + try { + await InboxMessage.update( + { ai_thoughts: aiResult.thoughts }, + { where: { ext_id: extId } } + ); + } catch (e) { + ctx.logger.warn(`[inbox processor] 保存 AI 思考记录失败: ${e.message}`); + } + } + return; + } + + const replyContent = typeof aiResult.reply === 'string' ? aiResult.reply : '已处理完成'; + const aiExtendProps = aiResult.functionResult + && aiResult.functionResult.data && aiResult.functionResult.data.extend_props; + ctx.logger.info( + `[inbox processor] AI 处理完成 ext_id=${extId} ` + + `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` + ); + + // 7.1 AI 推理写入入站消息(便于排查) + if (aiResult.thoughts && aiResult.thoughts.length > 0) { + try { + await InboxMessage.update( + { ai_thoughts: aiResult.thoughts }, + { where: { ext_id: extId } } + ); + } catch (e) { + ctx.logger.warn(`[inbox processor] 保存 AI 思考记录失败: ${e.message}`); + } + } + + // 8. 快递群:仅执行函数,不回信(AI 兜底分支) + if (groupType === 'express') { + ctx.logger.info(`[inbox processor] 快递群AI处理完成(不回信) ext_id=${extId}`); + return; + } + + // 9. 统一回信(AI 兜底分支) + await this.writeOutboundReply({ + warehouse_id: warehouseId, + ext_id: extId, + parent_id: parentId, + ext_data: data.ext_data || null, + group_id: ctx.inboxContext?.group_id || data.group_id || null, + user_id: ctx.inboxContext?.user_id || data.user_id || null, + group_name: ctx.inboxContext?.group_name || data.group_name || null, + user_name: ctx.inboxContext?.user_name || data.user_name || null, + }, replyContent, 'ai_reply', aiExtendProps); + } catch (error) { + ctx.logger.warn(`[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}`); + } + } + + /** + * 尝试识别并执行绑群操作。 + * 匹配"授权:CODE",从缓存读取绑群信息并绑定货主到群。 + * + * @param {Object} data 消息数据。 + * @return {Promise} 是否已处理绑群。 + */ + async tryBindGroup(data = {}) { + const { ctx } = this; + const content = String(data.content || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + + const bindMatch = content.match(/授权[::]\s*([A-Z0-9]{6,20})/i); + if (!bindMatch || !groupId || !warehouseId) return false; + + const code = bindMatch[1].toUpperCase(); + + // 查群是否已绑定(直接查 DB,避免 ctx 上下文被仓库ID污染) + try { + const existingGroup = await ctx.model.InboxGroup.findOne({ + attributes: [ 'store_id' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + if (existingGroup && existingGroup.store_id) { + await this.writeOutboundReply(data, '已在绑定状态,无需重复操作', 'bind_confirm'); + return true; + } + } catch (e) { + ctx.logger.warn(`[inbox processor] 查群绑定状态异常: ${e.message}`); + } + + const cacheKey = `chat:bind:${warehouseId}:${code}`; + + try { + const cacheValue = await ctx.app.getCacheAsync(cacheKey); + if (!cacheValue || !cacheValue.store_id) { + await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成', 'bind_confirm'); + return true; + } + + let storeName = `货主${cacheValue.store_id}`; + try { + const store = await ctx.model.Store.findOne({ + attributes: [ 'store_name' ], + where: { id: cacheValue.store_id }, + raw: true, + }); + if (store && store.store_name) storeName = store.store_name; + } catch (e) { /* ignore */ } + + await ctx.model.InboxGroup.update( + { + store_id: cacheValue.store_id, + group_type: cacheValue.group_type || 'store', + sub_type: cacheValue.sub_type || null, + }, + { where: { group_id: groupId, warehouse_id: warehouseId } } + ); + + ctx.inboxContext.store_id = cacheValue.store_id; + ctx.inboxContext.group_type = cacheValue.group_type || 'store'; + ctx.inboxContext.sub_type = cacheValue.sub_type || null; + await ctx.app.setCacheAsync(cacheKey, null, 0); + + ctx.logger.info( + `[inbox processor] 绑群成功 group_id=${groupId} store=${storeName}` + ); + + await this.writeOutboundReply(data, `绑定「${storeName}」成功`, 'bind_confirm'); + + // 绑定成功后自动查询面单余额 + try { + const balanceResult = await ctx.service.inbox.functions.callFunction('queryPrintBalance', {}); + const balanceMsg = balanceResult?.success + ? `面单余额:总量 ${balanceResult.data.print_quantity},已锁定 ${balanceResult.data.print_quantity_locked},可用 ${balanceResult.data.available}` + : `面单余额查询失败:${balanceResult?.error || '未知错误'}`; + // 使用独立 ext_id 避免与绑定成功回执冲突 + await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg, 'balance'); + } catch (balanceErr) { + ctx.logger.warn(`[inbox processor] 绑群后面单余额查询异常: ${balanceErr.message}`); + } + + return true; + } catch (error) { + ctx.logger.error(`[inbox processor] 绑群异常: ${error.message}`); + return false; + } + } + + /** + * 写入 outbound 回执并发送 HTTP 回调。 + * group_id / user_id / group_name / user_name 为强制入参, + * 缺失任一将抛出异常。 + * + * @param {Object} data 消息数据。 + * @param {string} data.group_id 群ID(必填)。 + * @param {string} data.user_id 用户ID(必填)。 + * @param {string} data.group_name 群名称(必填)。 + * @param {string} data.user_name 用户名称(必填)。 + * @param {number} [data.reuse_message_id] 复用已有消息记录作为推送记录(重推场景): + * 传入时跳过按 `sys:ack:{ext_id}` 查建,直接把推送结果回写到该记录; + * 不传(0)时保持原行为(按 ext_id 幂等查建回执记录)。 + * @param {string} replyContent 回复内容。 + * @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error / system。 + * system 类型不要求 user_id/user_name。 + * @param {Object} [extendProps=null] 回执携带的扩展指令(如开门 openDoor / 车牌登记 registerLicensePlate), + * 非空时透传到 notify.reply 的 data.extend_props。 + * @return {Promise} 推送是否成功(回调 HTTP 200 且返回 code=200)。 + */ + async writeOutboundReply(data, replyContent, source = 'ai_reply', extendProps = null) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(data.warehouse_id || 0); + const extId = String(data.ext_id || ''); + const parentId = Number(data.parent_id || 0); + const isSystem = source === 'system'; + const reuseMessageId = Number(data.reuse_message_id || 0); + + // 强制入参校验(system 类型不要求 user_id/user_name) + const groupId = String(data.group_id || ctx.inboxContext?.group_id || '').trim(); + const userId = String(data.user_id || ctx.inboxContext?.user_id || '').trim(); + const groupName = String(data.group_name || ctx.inboxContext?.group_name || '').trim(); + const userName = String(data.user_name || ctx.inboxContext?.user_name || '').trim(); + + if (!groupId || !groupName) { + throw new Error(`回执缺少必填字段: group_id=${groupId || '?'}, group_name=${groupName || '?'}`); + } + if (!isSystem && (!userId || !userName)) { + throw new Error(`回执缺少必填字段: user_id=${userId || '?'}, user_name=${userName || '?'}`); + } + + // 按群ID格式校正渠道来源(@chatroom→wx / 纯数字→qiwe): + // 群配置 ext_data 渠道错配时,回执会被桥接投递到错误渠道而丢失 + const rawExtData = data.ext_data || null; + const outboundExtData = normalizeExtDataSource(groupId, rawExtData); + if (rawExtData && outboundExtData && rawExtData.source + && rawExtData.source !== outboundExtData.source) { + ctx.logger.warn( + `[inbox processor] 回执 ext_data 渠道已校正 group_id=${groupId} ` + + `${rawExtData.source} → ${outboundExtData.source}` + ); + } + + const ackExtId = `sys:ack:${extId}`; + // 多候选路由:按 method 查询全部承接应用(id 升序),逐个尝试直到成功。 + // 同一仓库可能存在多个仓库级 API 应用,必须先按「群/消息来源应用」收敛候选 + // (群以 wms_inbox_group 为准):否则回执可能被首个返回 200 的其它适配器接走, + // 错投且被记为已送达。 + const sourceAppKey = await this.resolveReplySourceAppKey({ parentId, groupId, warehouseId, extId }); + const callbackConfigs = this.orderCallbackConfigsBySource( + await this.listApiAppCallbackConfigs(warehouseId, 'notify.reply'), + sourceAppKey, + { warehouseId, extId } + ); + // 重推(reuse_message_id>0):直接复用原记录,避免按 sys:ack: 前缀另建一条记录—— + // 那样会让原记录(如 sys:notice:* 系统通知)状态永远停留在失败/待推送,且每次重推都新建记录 + // 声明在 try 之外:异常兜底回写失败状态时仍需定位到该记录 + let outboundId = reuseMessageId > 0 ? reuseMessageId : 0; + try { + if (!outboundId) { + const existAck = await InboxMessage.findOne({ + where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false, + }); + if (existAck) { + outboundId = existAck.id; + } else { + const created = await InboxMessage.create({ + ext_id: ackExtId, warehouse_id: warehouseId, + store_id: Number(data.store_id) || ctx.inboxContext?.store_id || null, + direction: 'outbound', parent_id: parentId || null, + source_type: 'system', source_extra: null, + target_type: 'api', + group_id: groupId, + user_id: isSystem ? null : userId, + group_name: groupName, + user_name: isSystem ? null : userName, + content: replyContent, + ext_data: outboundExtData, + extend_props: extendProps || null, + flags: {}, + }); + outboundId = created.id; + } + } + + // 重推兜底:复用已有记录(定时补发送/手动重推)时,若调用方未传 extend_props, + // 从原记录回读,保证定时补发送报文一定带 extend_props(如开门指令等空文案回执) + let finalExtendProps = extendProps && typeof extendProps === 'object' && !Array.isArray(extendProps) + ? extendProps + : null; + if (!finalExtendProps && outboundId > 0) { + try { + const existed = await InboxMessage.findOne({ + where: { id: outboundId }, attributes: [ 'extend_props' ], raw: true, + }); + if (existed && existed.extend_props + && typeof existed.extend_props === 'object' && !Array.isArray(existed.extend_props)) { + finalExtendProps = existed.extend_props; + } + } catch (e) { + ctx.logger.warn(`[inbox processor] 回读 extend_props 失败: ${e.message}`); + } + } + + const hasCallbackConfigs = callbackConfigs.length > 0; + if (hasCallbackConfigs) { + const method = 'notify.reply'; + const notifyBody = { + code: 200, + data: { + // rule_reply(关键词规则引擎回执)与 ai_reply 同属机器人自动回复,映射为 ai 类型 + type: isSystem ? 'system' : (source === 'ai_reply' || source === 'rule_reply') ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error', + content: replyContent, + ext_data: outboundExtData, + ...(finalExtendProps + ? { extend_props: finalExtendProps } + : {}), + ext_id: String(outboundId), + group_id: groupId, + ...(isSystem ? {} : { user_id: userId, user_name: userName }), + group_name: groupName, + timestamp: Math.floor(Date.now() / 1000), + }, + }; + + // 逐个候选尝试:第一个成功即止;全部失败回写失败状态且不改动接口配置 + for (const callbackConfig of callbackConfigs) { + const attempt = await this.pushReplyOnce({ callbackConfig, warehouseId, method, notifyBody }); + if (attempt.pushOk) { + await InboxMessage.update( + { + push_status: 2, + push_response: { http_status: attempt.httpStatus, body: attempt.response || null }, + pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { where: { id: outboundId } } + ); + + // 同步更新原入站消息的推送状态 + if (parentId) { + await InboxMessage.update( + { + push_status: 2, + pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { where: { id: parentId } } + ); + } + return true; + } + } + // 全部候选尝试失败:回写状态和原因 + await InboxMessage.update( + { + push_status: 3, + push_response: { + error: `全部 ${callbackConfigs.length} 个回调应用尝试失败`, + }, + }, + { where: { id: outboundId } } + ); + return false; + } + // 无应用承接该回调:回写状态 + await InboxMessage.update( + { + push_status: 3, + push_response: { error: '无应用承接该回调(callback_functions 未勾选或应用未启用)' }, + }, + { where: { id: outboundId } } + ); + ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 无应用承接回调 notify.reply,回写失败状态 ext_id=${extId}`); + return false; + } catch (error) { + ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`); + + // 推送异常时更新状态 + 写日志 + try { + await InboxMessage.update( + { push_status: 3, push_response: { error: error.message } }, + { where: { id: outboundId } } + ); + } catch (updateErr) { + ctx.logger.error('[inbox processor] 更新推送状态失败: ' + updateErr.message); + } + try { + const { WarehouseLog } = ctx.model; + const crypto = require('crypto'); + await WarehouseLog.create({ + log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), + app_key: (await this.getApiAppCallbackConfig(warehouseId)).appKey || null, + method: 'notify.reply', + warehouse_id: warehouseId || null, + http_status: null, + body: '', result: 'Error: ' + error.message, + use_time: null, created_at: new Date(), + }); + } catch (logErr) { + ctx.logger.error('[notify-log] 失败日志写入异常: ' + logErr.message); + } + return false; + } + } + + /** + * 判断当前消息所在群是否为仓库内部群(wms_inbox_group.group_type='warehouse')。 + * 优先使用已加载的群信息(ctx.inboxContext.group_type),避免重复查库; + * 未加载时按 (group_id, warehouse_id) 查库,查库异常按「非仓库群」处理(屏蔽照常生效,安全默认)。 + * + * @param {string} groupId 外部群ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 是否仓库群。 + */ + async isWarehouseGroup(groupId, warehouseId) { + const { ctx } = this; + + const cachedGroupType = String(ctx.inboxContext?.group_type || '').trim(); + if (cachedGroupType) return cachedGroupType === 'warehouse'; + + if (!groupId) return false; + + try { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_type' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + return String((group && group.group_type) || '').trim() === 'warehouse'; + } catch (error) { + ctx.logger.warn(`[inbox processor] 查询群类型失败: ${error.message}`); + return false; + } + } + + /** + * 加载当前仓库的屏蔽用户ID集合(供 AI 判断真人接管)。 + * 口径与 isBlocked() 一致:仓库群忽略不带群ID的屏蔽记录(仅带 group_id 的记录才算命中), + * 避免货主群/快递群等场景的用户级屏蔽连带把仓库群用户标记为「已屏蔽」。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 屏蔽用户ID集合。 + */ + async loadBlockedUserIds(warehouseId) { + const { ctx } = this; + const isWarehouseGroup = String(ctx.inboxContext?.group_type || '').trim() === 'warehouse'; + + const { InboxBlock } = ctx.model; + const rows = await InboxBlock.findAll({ + attributes: [ 'group_id', 'user_id' ], + where: { warehouse_id: warehouseId }, + raw: true, + }); + + return new Set( + rows + .filter(r => !(isWarehouseGroup && !String(r.group_id || '').trim())) + .map(r => String(r.user_id || '').trim()) + .filter(Boolean) + ); + } + + /** + * 检查当前消息的群/用户是否在屏蔽列表中。 + * + * 口径: + * - 带群ID的屏蔽记录(`群:用户` / `群:*`)在对应群内始终生效; + * - 仅带 user_id 的全局用户屏蔽(`*:用户`)在仓库群内不生效——仓库群是内部群, + * 此类屏蔽多来自货主群/快递群等外部场景,不应连带跳过仓库群消息; + * 仓库群内由机器人发起的屏蔽([屏蔽] 指令)会写入当前群 group_id,故仍按带群ID记录生效。 + * - 无群ID的消息(如私聊)不受此例外影响。 + * + * @return {Promise} 是否已屏蔽。 + */ + async isBlocked() { + const { ctx } = this; + const app = ctx.app; + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + const userId = String(ctx.inboxContext?.user_id || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!groupId && !userId) return false; + + try { + // 1. 尝试从缓存读取屏蔽列表 + const cacheKey = `inbox:block:${warehouseId}`; + let blockedSet = await app.getCacheAsync(cacheKey); + + if (!blockedSet || !(blockedSet instanceof Set)) { + // 2. 缓存未命中,查库并填入缓存 + const { InboxBlock } = ctx.model; + const rows = await InboxBlock.findAll({ + attributes: [ 'group_id', 'user_id' ], + where: { warehouse_id: warehouseId }, + raw: true, + }); + + blockedSet = new Set(); + for (const row of rows) { + const g = String(row.group_id || '').trim(); + const u = String(row.user_id || '').trim(); + if (g && u) blockedSet.add(`${g}:${u}`); + if (g && !u) blockedSet.add(`${g}:*`); + if (!g && u) blockedSet.add(`*:${u}`); + } + + // TTL 5 分钟 + await app.setCacheAsync(cacheKey, blockedSet, 300); + } + + // 3. 检查当前消息是否命中屏蔽规则 + if (groupId && userId && blockedSet.has(`${groupId}:${userId}`)) return true; + if (groupId && blockedSet.has(`${groupId}:*`)) return true; + if (userId && blockedSet.has(`*:${userId}`)) { + // 仓库群忽略不带群ID的用户级屏蔽(见方法注释) + if (groupId && await this.isWarehouseGroup(groupId, warehouseId)) { + ctx.logger.info(`[inbox processor] 仓库群忽略不带群ID的用户屏蔽 group_id=${groupId} user_id=${userId}`); + return false; + } + return true; + } + + return false; + } catch (error) { + ctx.logger.warn(`[inbox processor] 屏蔽检查异常: ${error.message}`); + return false; + } + } + + /** + * 失效屏蔽缓存,在新增屏蔽记录后调用。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async invalidateBlockCache(warehouseId) { + const { ctx } = this; + try { + await ctx.app.setCacheAsync(`inbox:block:${warehouseId}`, null, 0); + } catch (error) { + ctx.logger.warn(`[inbox processor] 失效屏蔽缓存失败: ${error.message}`); + } + } + + /** + * 获取仓库 ApiApp 回调配置(URL + 签名凭证)。 + * 兼容旧调用:默认取承接 notify.reply 的首个应用。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调地址与签名凭证,未配置/异常时各字段为 null。 + */ + async getApiAppCallbackConfig(warehouseId) { + return await this.getApiAppCallbackConfigByMethod(warehouseId, 'notify.reply'); + } + + /** + * 按 method 获取仓库 ApiApp 回调配置(取候选列表中首个应用)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {string} method 出站 method。 + * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调地址与签名凭证,未配置/异常时各字段为 null。 + */ + async getApiAppCallbackConfigByMethod(warehouseId, method) { + const list = await this.listApiAppCallbackConfigs(warehouseId, method); + const first = list[0] || {}; + return { + url: first.url || null, + appKey: first.appKey || null, + appSecret: first.appSecret || null, + }; + } + + /** + * 查询仓库下承接指定 method 的全部回调候选应用(按 id 升序)。 + * callback_functions 为空/未勾选的应用不承接任何回调(不放行)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {string} method 出站 method。 + * @return {Promise>} 候选列表。 + */ + async listApiAppCallbackConfigs(warehouseId, method) { + const { ctx } = this; + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return []; + } + + const apiAppModel = ctx.model && ctx.model.ApiApp; + if (!apiAppModel || typeof apiAppModel.findAll !== 'function') { + return []; + } + + try { + const rows = await apiAppModel.findAll({ + attributes: [ 'id', 'callback_url', 'self_app_key', 'self_app_secret', 'callback_functions' ], + where: { + warehouse_id: warehouseId, + interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, + is_enabled: 1, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const methodStr = String(method || '').trim(); + return rows + .filter(row => { + let list = row.callback_functions; + if (typeof list === 'string') { + try { + list = JSON.parse(list); + } catch (error) { + list = null; + } + } + return Array.isArray(list) + && list.map(item => String(item || '').trim()).includes(methodStr); + }) + .map(row => ({ + appId: Number(row.id), + url: row.callback_url || null, + appKey: row.self_app_key || null, + appSecret: row.self_app_secret || null, + })); + } catch (error) { + ctx.logger.warn(`[inbox processor] 查询回调配置列表失败: ${error.message}`); + return []; + } + } + + /** + * 从来源记录中提取仓库级 API 应用的 AppKey。 + * 仅 source_type='api' 时 source_extra 才是 appKey(IM 来源存的是平台标识)。 + * @param {Object|null} row 入站消息或群记录。 + * @return {string|null} 来源应用 AppKey。 + */ + pickApiSourceAppKey(row) { + if (!row || String(row.source_type || '') !== 'api') return null; + const appKey = String(row.source_extra || '').trim(); + return appKey || null; + } + + /** + * 解析回执应发往的来源应用 AppKey。 + * 优先级:群创建来源(wms_inbox_group 为准)→ 入站消息来源 → ext_id(api:{appKey}:{requestId})兜底。 + * 群是站内信的会话归属中心,内部通知与回执都从群配置出发,优先按群来源收敛候选。 + * @param {Object} options 解析参数。 + * @param {number} [options.parentId] 入站消息记录 ID。 + * @param {string} [options.groupId] 外部群 ID。 + * @param {number} [options.warehouseId] 仓库 ID。 + * @param {string} [options.extId] 入站消息 ext_id。 + * @return {Promise} 来源应用 AppKey。 + */ + async resolveReplySourceAppKey({ parentId, groupId, warehouseId, extId } = {}) { + const { ctx } = this; + + const groupIdStr = String(groupId || '').trim(); + if (groupIdStr && Number(warehouseId) > 0) { + try { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'source_type', 'source_extra' ], + where: { group_id: groupIdStr, warehouse_id: Number(warehouseId) }, + raw: true, + }); + const appKey = this.pickApiSourceAppKey(group); + if (appKey) return appKey; + } catch (error) { + ctx.logger.warn(`[inbox processor] 查询群来源失败: ${error.message}`); + } + } + + const inboundId = Number(parentId) || 0; + if (inboundId > 0) { + try { + const row = await ctx.model.InboxMessage.findOne({ + attributes: [ 'source_type', 'source_extra' ], + where: { id: inboundId, warehouse_id: Number(warehouseId) || 0 }, + raw: true, + }); + const appKey = this.pickApiSourceAppKey(row); + if (appKey) return appKey; + } catch (error) { + ctx.logger.warn(`[inbox processor] 查询入站消息来源失败: ${error.message}`); + } + } + + // ext_id 约定:api:{appKey}:{requestId} + const matched = /^api:([^:]+):/.exec(String(extId || '')); + return matched ? matched[1] : null; + } + + /** + * 按来源应用收敛回执候选:来源应用承接时只发给它,避免多应用错投; + * 来源缺失或未承接时保持原有候选顺序(兼容旧行为)并记录告警。 + * @param {Array} candidates 候选应用列表(含 appKey)。 + * @param {string|null} sourceAppKey 来源应用 AppKey。 + * @param {Object} [context] 日志上下文。 + * @param {number} [context.warehouseId] 仓库 ID。 + * @param {string} [context.extId] 消息 ext_id。 + * @return {Array} 收敛后的候选列表。 + */ + orderCallbackConfigsBySource(candidates, sourceAppKey, { warehouseId, extId } = {}) { + const list = Array.isArray(candidates) ? candidates : []; + if (list.length <= 1) return list; + + const sourceKey = String(sourceAppKey || '').trim(); + if (!sourceKey) { + this.ctx.logger.warn( + `[inbox processor] 无法确定回执来源应用,按候选顺序尝试 warehouse=${warehouseId} ext_id=${extId} candidates=${list.length}` + ); + return list; + } + + const matched = list.filter(item => String(item.appKey || '').trim() === sourceKey); + if (matched.length > 0) return matched; + + this.ctx.logger.warn( + `[inbox processor] 来源应用未承接 notify.reply,按候选顺序兜底 warehouse=${warehouseId} source_app=${sourceKey} ext_id=${extId} candidates=${list.length}` + ); + return list; + } + + /** + * 单次回执推送尝试(回执专用协议:MD5(appSecret+timestamp+bodyJson) + POST)。 + * 每次尝试均写 wms_warehouse_log,失败不改动接口配置。 + * + * @param {Object} options 尝试参数。 + * @param {Object} options.callbackConfig 候选应用 { appId, url, appKey, appSecret }。 + * @param {number} options.warehouseId 仓库ID。 + * @param {string} options.method 出站 method。 + * @param {Object} options.notifyBody 推送体(已组装)。 + * @return {Promise} { pushOk, httpStatus, response, error }。 + */ + async pushReplyOnce({ callbackConfig, warehouseId, method, notifyBody }) { + const { ctx } = this; + const crypto = require('crypto'); + const callbackUrl = callbackConfig.url; + const bodyJson = JSON.stringify(notifyBody); + const timestamp = Math.floor(Date.now() / 1000); + const appKey = callbackConfig.appKey || ''; + const appSecret = callbackConfig.appSecret || ''; + + // MD5 签名:MD5(appSecret + timestamp + bodyJson) + const sign = appSecret + ? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex') + : ''; + + const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`; + const startTime = Date.now(); + + let curlResult = null; + let error = null; + try { + curlResult = await ctx.curl(urlWithSign, { + method: 'POST', dataType: 'json', contentType: 'json', + data: notifyBody, + headers: { 'Content-Type': 'application/json' }, timeout: 10000, + }); + } catch (curlError) { + error = curlError; + } + + // HTTP 200 且 body.code=200 → 推送成功 + const pushOk = !!curlResult && curlResult.status === 200 + && (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200); + + // 记录出站通知日志到 wms_warehouse_log(每次尝试均记录) + try { + const { WarehouseLog } = ctx.model; + await WarehouseLog.create({ + log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), + app_key: appKey || null, + method, + warehouse_id: warehouseId || null, + url: urlWithSign || null, + http_status: curlResult ? curlResult.status : null, + body: bodyJson.substring(0, 65535), + result: curlResult + ? JSON.stringify(curlResult.data || {}).substring(0, 65535) + : 'Error: ' + (error ? error.message : ''), + use_time: Date.now() - startTime, + created_at: new Date(), + }); + } catch (logErr) { + ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message); + } + + return { + pushOk, + httpStatus: curlResult ? curlResult.status : null, + response: curlResult ? (curlResult.data || null) : null, + error: error ? error.message : (pushOk ? null : '回调返回非200或code非200'), + }; + } + + /** + * 获取仓库 ApiApp 回调地址(兼容旧调用)。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 回调 URL。 + */ + async getApiAppCallbackUrl(warehouseId) { + const config = await this.getApiAppCallbackConfig(warehouseId); + return config.url; + } + + /** + * 系统通知异步推送:仅 POST 回调,不写 inbox_message。 + * @param {Object} data 通知数据。 + * @param {number} data.warehouse_id 仓库ID。 + * @param {string} data.group_id 目标群ID。 + * @param {string} data.group_name 目标群名称。 + * @param {string} data.content 通知内容。 + * @param {Object} [data.ext_data] 群扩展数据(渠道信息)。 + * @param {number} [data.store_id] 目标货主ID(用于写入回信记录的 store_id)。 + * @return {void} 无返回值,异步写入与推送。 + */ + pushSystemNotification(data = {}) { + const { ctx } = this; + const warehouseId = Number(data.warehouse_id); + const groupId = String(data.group_id || '').trim(); + const groupName = String(data.group_name || '').trim(); + const content = String(data.content || '').trim(); + const extData = data.ext_data || null; + const storeId = Number(data.store_id) || null; + + if (!warehouseId || !groupId || !content) return; + + // 构造 data 对象,复用 writeOutboundReply + const replyData = { + warehouse_id: warehouseId, + ext_id: `sys:notify:${warehouseId}:${groupId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`, + parent_id: null, + ext_data: extData, + group_id: groupId, + user_id: '', + group_name: groupName, + user_name: '', + store_id: storeId, + }; + + // 写库 + POST,异步不阻塞 + setImmediate(() => { + this.writeOutboundReply(replyData, content, 'system').catch(err => { + ctx.logger.warn(`[pushNotify] 推送异常 group=${groupName}: ${err.message}`); + }); + }); + } + + /** + * 尝试从消息正文中提取仓库ID。 + * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 + * + * @param {string} content 消息正文。 + * @return {number|null} 仓库ID,无法解析时返回 null。 + */ + extractWarehouseId(content) { + // 默认不解析,由业务方覆盖 + void content; + return null; + } + + /** + * 尝试从消息正文中提取货主ID。 + * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 + * + * @param {string} content 消息正文。 + * @return {number|null} 货主ID,无法解析时返回 null。 + */ + extractStoreId(content) { + // 默认不解析,由业务方覆盖 + void content; + return null; + } + + /** + * 从 Egg.js 请求上下文中获取仓库ID。 + * + * @return {number|null} 仓库ID。 + */ + getWarehouseIdFromContext() { + const { ctx } = this; + const user = ctx.user || ctx.state?.user || {}; + const warehouseId = Number(user.store_id || user.warehouse_id) || null; + return Number.isFinite(warehouseId) && warehouseId > 0 ? warehouseId : null; + } + + /** + * 从 Egg.js 请求上下文中获取货主ID。 + * + * @return {number|null} 货主ID。 + */ + getStoreIdFromContext() { + const { ctx } = this; + const user = ctx.user || ctx.state?.user || {}; + const storeId = Number(user.store_id) || null; + return Number.isFinite(storeId) && storeId > 0 ? storeId : null; + } +} + +module.exports = InboxProcessorService; diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js new file mode 100644 index 0000000..799ba54 --- /dev/null +++ b/app/service/inbox/receiver.js @@ -0,0 +1,249 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 消息体大小上限 64KB */ +const MAX_BODY_SIZE = 64 * 1024; + +/** + * 站内信接收服务。 + * 统一处理消息入站:幂等去重、写库。 + * 暂不包含出站转发逻辑,纯入库管理。 + */ +class InboxReceiverService extends Service { + /** + * 统一接收入口:幂等去重、写库。 + * @param {Object} data 消息数据。 + * @param {string} data.ext_id 外部唯一消息主键。 + * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)。 + * @param {string} [data.direction='inbound'] 消息方向。 + * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)。 + * @param {string} data.source_type 来源类型:im / api / system。 + * @param {string} [data.source_extra] 来源附加信息。 + * @param {string} data.target_type 目标类型:im / api / webhook。 + * @param {string} [data.group_name] 群名称(外部传入)。 + * @param {string} [data.user_name] 用户名称(外部传入)。 + * @param {string} [data.group_id] 外部群ID。 + * @param {string} [data.user_id] 外部用户ID。 + * @param {string} [data.content] 消息正文/摘要。 + * @param {Object} [data.ext_data] 透传数据。 + * @param {Object} [data.flags] 处理标记。 + * @param {number} [data.send_time] 消息原始发送时间(毫秒时间戳,可选,用于历史消息过滤)。 + * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。 + */ + async receive(data = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + // 安全边界:校验 ext_id 不能为空 + const extId = String(data.ext_id || '').trim(); + if (!extId) { + throw new Error('ext_id 不能为空'); + } + + // 安全边界:warehouse_id 必须由服务端上下文提供 + const warehouseId = Number(data.warehouse_id); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouse_id 无效'); + } + + // 枚举校验:direction + const VALID_DIRECTIONS = [ 'inbound', 'outbound' ]; + const direction = VALID_DIRECTIONS.includes(data.direction) ? data.direction : 'inbound'; + + // 枚举校验:source_type + const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ]; + const sourceType = VALID_SOURCE_TYPES.includes(data.source_type) ? data.source_type : (data.source_type || 'api'); + + // 枚举校验:target_type + const VALID_TARGET_TYPES = [ 'im', 'api', 'webhook' ]; + const targetType = VALID_TARGET_TYPES.includes(data.target_type) ? data.target_type : (data.target_type || 'im'); + + // parent_id 存在性校验 + const parentId = data.parent_id ? Number(data.parent_id) : null; + if (parentId) { + const parentExists = await InboxMessage.findOne({ + where: { id: parentId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + }); + if (!parentExists) { + throw new Error(`parent_id=${parentId} 对应的消息不存在`); + } + } + + // 幂等检查:ext_id 已存在则直接返回 + const exist = await InboxMessage.findOne({ + where: { ext_id: extId }, + attributes: [ 'id', 'ext_id' ], + paranoid: false, + }); + + if (exist) { + ctx.logger.info(`[inbox] 消息已存在,跳过入库 ext_id=${extId} id=${exist.id}`); + return { + ok: true, + id: exist.id, + ext_id: extId, + }; + } + + // 消息体大小限制 + const checkBody = { + content: data.content || null, + ext_data: data.ext_data || null, + }; + const bodySize = Buffer.byteLength(JSON.stringify(checkBody), 'utf8'); + if (bodySize > MAX_BODY_SIZE) { + throw new Error(`消息体超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`); + } + + // flags 合并:消息发送时间统一存入 flags.send_time(毫秒),供 AI 历史消息过滤 + const flags = { ...(data.flags || {}) }; + if (!flags.send_time && data.send_time != null) { + const sendTime = Number(data.send_time); + if (Number.isFinite(sendTime) && sendTime > 0) { + flags.send_time = Math.floor(sendTime); + } + } + + // 从群绑定查询货主ID(外部不再直接传入 store_id) + let storeId = null; + const extGroupId = String(data.group_id || '').trim(); + if (extGroupId && warehouseId) { + try { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'store_id' ], + where: { group_id: extGroupId, warehouse_id: warehouseId }, + raw: true, + }); + if (group && group.store_id) { + storeId = Number(group.store_id); + } + } catch (groupErr) { + ctx.logger.warn(`[inbox] 查找群货主失败: ${groupErr.message}`); + } + } + + // 写库(暂不触发异步转发) + const record = await InboxMessage.create({ + ext_id: extId, + warehouse_id: warehouseId, + store_id: storeId || null, + direction, + parent_id: parentId, + source_type: sourceType, + source_extra: data.source_extra || null, + target_type: targetType, + group_name: data.group_name || null, + user_name: data.user_name || null, + group_id: data.group_id || null, + user_id: data.user_id || null, + content: data.content || null, + ext_data: data.ext_data || null, + flags, + }); + + ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`); + + // 自动登记群:优先按 (group_id, warehouse_id) 幂等 upsert。 + // 群ID不变、仅名称变化时只更新名称,不重复建群。 + const groupName = String(data.group_name || '').trim(); + if (groupName) { + try { + if (extGroupId) { + const group = await ctx.model.InboxGroup.findOne({ + where: { group_id: extGroupId, warehouse_id: warehouseId }, + }); + + if (group) { + // 群已存在:名称变化时更新名称,不新建。 + // 来源字段为空时补写(用于出站 notify.reply 按来源应用路由); + // 已有来源且与本次不一致时不覆盖,避免多应用共用群时归属被反复改写。 + const patch = {}; + const oldName = group.group_name; + if (oldName !== groupName) { + patch.group_name = groupName; + } + if (!group.source_type && sourceType) { + patch.source_type = sourceType; + } + if (!group.source_extra && data.source_extra) { + patch.source_extra = data.source_extra; + } + if (Object.keys(patch).length > 0) { + await group.update(patch); + } + if (patch.group_name) { + ctx.logger.info( + `[inbox] 群名称已更新 group_id=${extGroupId}: ${oldName} → ${groupName}` + ); + } + if (group.source_extra && data.source_extra + && String(group.source_extra) !== String(data.source_extra)) { + ctx.logger.warn( + `[inbox] 群来源不一致 group_id=${extGroupId} existing=${group.source_extra} incoming=${data.source_extra}` + ); + } + } else { + // 群ID不存在:按群ID直接新建(群以ID为准,不按名称匹配既有群) + await ctx.model.InboxGroup.create({ + group_name: groupName, + group_id: extGroupId, + warehouse_id: warehouseId, + store_id: storeId || null, + source_type: sourceType, + source_extra: data.source_extra || null, + ai_enabled: 0, + }); + ctx.logger.info( + `[inbox] 新建群记录 group_id=${extGroupId} name=${groupName}` + ); + } + } else { + // 无群ID:按 (group_name, warehouse_id) 幂等登记(向后兼容) + await ctx.model.InboxGroup.findOrCreate({ + where: { group_name: groupName, warehouse_id: warehouseId }, + defaults: { + group_id: null, + store_id: storeId || null, + source_type: sourceType, + source_extra: data.source_extra || null, + ai_enabled: 0, + }, + }); + } + } catch (groupErr) { + ctx.logger.warn(`[inbox] 群登记失败: ${groupErr.message}`); + } + } + + // source_type 分流:API 来源异步回执 + if (sourceType === 'api') { + setImmediate(() => { + ctx.service.inbox.processor.handleApiMessage({ + warehouse_id: warehouseId, + store_id: storeId, + parent_id: record.id, + ext_data: data.ext_data || null, + ext_id: extId, + content: data.content || '', + group_name: data.group_name || null, + user_name: data.user_name || null, + group_id: data.group_id || null, + user_id: data.user_id || null, + flags, + }).catch(err => { + ctx.logger.error(`[inbox] API 异步回执异常 ext_id=${extId}: ${err.message}`); + }); + }); + } + + return { + ok: true, + id: record.id, + ext_id: extId, + }; + } +} + +module.exports = InboxReceiverService; diff --git a/app/service/inbox/rules.js b/app/service/inbox/rules.js new file mode 100644 index 0000000..50003d9 --- /dev/null +++ b/app/service/inbox/rules.js @@ -0,0 +1,489 @@ +'use strict'; + +/* eslint-disable no-use-before-define */ +/* 规则表/常量按“配置在后、逻辑在前”组织,类方法通过函数声明提升访问,此处禁用声明顺序检查 */ + +const Service = require('egg').Service; + +/** + * 站内信关键词规则引擎(主回复路径,替代 AI 推理)。 + * + * 设计参考 PHP Chat.php 的规则表结构: + * - 按群类型(store/warehouse/express)维护规则表,顺序即优先级,先命中先执行; + * - 每条规则:关键词数组 → inbox 函数,命中后从消息中提取运单号/订单号直接调用函数; + * - 函数返回的模板消息(direct_reply/message)原样回信; + * - 确认/感谢类短消息、未命中消息默认静默,不触发 AI,节省推理费用; + * - AI 仅在 config.inbox.aiFallback=true 时作为兜底。 + */ +class InboxRulesService extends Service { + + /** + * 规则引擎主入口:关键词匹配 + 参数提取 + 函数调用。 + * + * @param {string} content 消息正文。 + * @return {Promise} 处理结果: + * - { handled: false }:未命中任何规则(由调用方决定是否 AI 兜底/静默)。 + * - { handled: true, silent: true }:命中静默规则,不回复。 + * - { handled: true, reply: string, fn, params, result, matchedKey, thoughts }:已执行函数并生成回复。 + */ + async handle(content) { + const { ctx } = this; + const text = String(content || '').trim(); + if (!text) return { handled: false }; + + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const rules = RULE_TABLES[groupType]; + if (!Array.isArray(rules) || rules.length === 0) { + ctx.logger.info(`[inbox rules] 无规则表 group_type=${groupType || '-'}`); + return { handled: false }; + } + + const groupsSvc = ctx.service.inbox.groups; + const funcSvc = ctx.service.inbox.functions; + const activeGroups = groupsSvc.resolveActiveGroups(); + + // 收集所有命中规则:命中关键词最长者优先(长词优先)。 + // 相反语义的短词(如“拦截”vs“取消拦截”)不再依赖人工排序, + // 长词“取消拦截”天然排在短词“拦截”之前,短词不会吞掉长词语义。 + const candidates = []; + for (const rule of rules) { + if (rule.any) { + candidates.push({ rule, key: 'any', keyLen: Infinity }); + continue; + } + const hitKey = rule.keys.find(k => text.includes(k)); + if (hitKey) candidates.push({ rule, key: hitKey, keyLen: hitKey.length }); + } + // 稳定排序:keyLen 相同保持规则表顺序(先定义者优先) + candidates.sort((a, b) => b.keyLen - a.keyLen); + + for (const cand of candidates) { + const rule = cand.rule; + + // 防误判守卫(如拦截 vs 查询物流) + if (rule.guard && !rule.guard(text)) { + ctx.logger.info(`[inbox rules] 规则 ${rule.fn} 未通过防误判守卫: ${text.slice(0, 50)}`); + continue; + } + + // 内置帮助指令 + if (rule.fn === '__help__') { + const reply = HELP_TEXTS[groupType] || '当前群暂无可用的快捷指令'; + return { + handled: true, reply, fn: '__help__', params: {}, result: null, matchedKey: 'help', + thoughts: [{ round: 0, action: 'rule', function: '__help__', params: {}, reason: '帮助指令命中: help', functionResult: null }], + }; + } + + // 函数可用性校验(复用群分组权限,防止越权调用) + const def = funcSvc.registry.get(rule.fn); + if (!def || !groupsSvc.isFunctionAvailable(def, activeGroups)) { + ctx.logger.info( + `[inbox rules] 函数 ${rule.fn} 当前群不可用,跳过 groups=${def ? def.groups.join(',') : '-'} active=${activeGroups.join(',')}` + ); + continue; + } + + // 参数提取 + const params = {}; + if (rule.waybill) { + const waybills = extractWaybills(text); + if (waybills.length === 0) { + if (rule.noWaybillSilent) { + return { handled: true, silent: true }; + } + return { + handled: true, + reply: rule.tip || '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)', + fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0], + thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }], + }; + } + // 默认参数名 keyword,个别函数(如 queryReturn)用 waybill_code + params[rule.paramName || 'keyword'] = waybills.join(','); + } + if (rule.order) { + const orders = extractOrders(text); + if (orders.length === 0) { + return { + handled: true, + reply: rule.tip || '请提供订单号(发货单号或平台单号)', + fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0], + thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }], + }; + } + params[rule.paramName || 'keyword'] = orders.join(','); + } + if (rule.issueType) params.issue_type = rule.issueType; + if (rule.express) params.express = rule.express; + if (rule.expressSubType) { + const sub = resolveExpressSubType(text); + if (sub) params.as_sub_type = sub; + } + if (rule.expressFromText) { + const expressName = extractExpressName(text); + if (!expressName) { + return { + handled: true, + reply: rule.tip || '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东)', + fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0], + thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }], + }; + } + params.express = expressName; + } + if (rule.stockSearch) { + const kw = stripKeyword(text, rule.keys || []); + if (!kw) { + return { + handled: true, + reply: rule.tip || '请提供商品名称、编码或条码', + fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0], + thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }], + }; + } + params.keyword = kw; + } + + // 执行函数 + const result = await funcSvc.callFunction(rule.fn, params); + const reply = this.buildReply(rule.fn, result); + + const matchedKey = cand.key; + ctx.logger.info( + `[inbox rules] HIT fn=${rule.fn} key=${matchedKey} params=${JSON.stringify(params)} success=${!!result.success}` + ); + + return { + handled: true, + fn: rule.fn, + params, + result, + reply, + matchedKey, + thoughts: [{ + round: 0, + action: 'rule', + function: rule.fn, + params, + reason: `关键词规则命中: ${matchedKey}`, + functionResult: result, + }], + }; + } + + // 确认/感谢类短消息 → 静默(PHP nothing 规则) + if (SILENT_RE.test(text)) { + ctx.logger.info(`[inbox rules] 静默规则命中: ${text.slice(0, 50)}`); + return { handled: true, silent: true }; + } + + return { handled: false }; + } + + /** + * 根据函数执行结果构建回复文本。 + * 优先 direct_reply 模板消息(支持 messages 数组多行回复),其次 data.message,商品搜索做格式化,失败返回错误文案。 + * + * @param {string} fn 函数名。 + * @param {Object} result callFunction 返回结果。 + * @return {string|string[]|null} 回复文本(数组表示多条消息逐个回复),null 表示无需回复。 + */ + buildReply(fn, result) { + if (!result || typeof result !== 'object') return null; + if (result.success === false) { + return String(result.error || '操作失败,请联系客服处理'); + } + const data = result.data || {}; + if (data.direct_reply === true && Array.isArray(data.messages) && data.messages.length > 0) { + return data.messages.map(m => String(m)); + } + if (data.direct_reply === true && typeof data.message === 'string' && data.message) { + return data.message; + } + if (typeof data.message === 'string' && data.message) { + return data.message; + } + if (fn === 'searchStock' || fn === 'searchWarehouseStock') { + return this.formatStock(data); + } + return null; + } + + /** + * 商品搜索结果的纯文本格式化。 + * @param {Object} data 函数返回的 data。 + * @return {string} 格式化文本。 + */ + formatStock(data = {}) { + const items = Array.isArray(data.items) ? data.items : []; + if (items.length === 0) { + return String(data.hint || '未找到匹配商品,请尝试其他关键词'); + } + const lines = items.slice(0, 10).map((s, i) => { + const code = s.item_code || ''; + const name = s.item_name || ''; + const available = s.stock_available != null ? s.stock_available : 0; + const extra = s.prohibited_type ? `(违禁品:${s.prohibited_type})` : ''; + return `${i + 1}. ${code} ${name} 可用库存:${available}${extra}`; + }); + return `找到 ${items.length} 个商品:\n${lines.join('\n')}`; + } +} + +// ============================ 提取工具 ============================ + +/** + * 提取运单号(参考 PHP Chat.php getPostNums,结合 Node 运单特征)。 + * 排除:售后工单号(AS开头)、手机号、日期时间戳、纯字母串。 + * @param {string} text 消息正文。 + * @return {string[]} 去重后的运单号列表。 + */ +function extractWaybills(text) { + const raw = text.match(/[A-Za-z0-9_-]{10,24}/g) || []; + return [ ...new Set(raw) ].filter(t => { + if (/^AS\d+$/i.test(t)) return false; // 售后工单号 + if (/^1\d{10}$/.test(t)) return false; // 手机号 + if (/^\+?86[- ]?1\d{10}$/.test(t)) return false; // 国际区号手机(含/不含 +) + if (/^\d{3,4}-\d{7,8}$/.test(t)) return false; // 座机带横线(020-12345678) + if (/^0\d{9,11}$/.test(t)) return false; // 0开头座机/服务号(02012345678) + if (/^400\d{7}$/.test(t)) return false; // 400 服务电话 + // 日期时间戳(如 20260914201201):年份限定 19xx/20xx, + // 否则 14 位运单号(如中通 79140215263762 → 被误读成 7914-02-15)会被当日期戳剔除 + if (/^(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{4,}$/.test(t)) return false; + if (/^[A-Za-z_-]+$/.test(t)) return false; // 纯字母 + return true; + }); +} + +/** + * 提取订单号(发货单/平台单)。 + * 优先 SYS/SO/DD 前缀及字母数字混合号,兜底 12~20 位纯数字。 + * 前缀需独立成词(前不能紧邻字母数字),避免从长字符串中截取尾部 + * (如 NOTEXISTPOSTNUM20260814 误截成 TPOSTNUM20260814)。 + * @param {string} text 消息正文。 + * @return {string[]} 去重后的订单号列表。 + */ +function extractOrders(text) { + const raw = text.match(/(? 0) return list; + const nums = text.match(/(? !/^1\d{10}$/.test(t)); +} + +/** 改快递规则支持的目标快递名(长名在前,优先提取完整名称,避免“中通快运”被短名截断) */ +const EXPRESS_NAMES = [ '中通快运', '中通快递', '极兔速递', '京东快递', '圆通快递', '申通快递', '顺丰速运', '韵达快递', '邮政小包', '圆通', '中通', '申通', '顺丰', '韵达', '极兔', '邮政', 'EMS', '京东', '德邦' ]; + +/** + * 快递反馈 → 售后子类型映射(长词优先,避免“核实签收”被“签收”截断)。 + * 未命中保持默认 logistics_issue(物流异常)。 + */ +const EXPRESS_SUB_TYPE_RULES = [ + { keys: [ '核实签收', '签收核实', '已签收', '签收' ], sub: 'verify_delivery' }, + { keys: [ '破损', '坏了', '破损件' ], sub: 'damage' }, + { keys: [ '少发', '漏发', '发少' ], sub: 'missing_item' }, + { keys: [ '改地址', '地址更改', '改址' ], sub: 'change_address' }, + { keys: [ '换快递', '改快递' ], sub: 'change_carrier' }, + { keys: [ '催件', '催派', '催促' ], sub: 'urge' }, + { keys: [ '发货延迟', '延迟发货', '催发货' ], sub: 'delivery_delay' }, + { keys: [ '拒收' ], sub: 'rejected' }, +]; + +/** + * 从快递反馈文本推断售后子类型(长词优先)。 + * @param {string} text 消息正文。 + * @return {string|null} 售后子类型,未命中返回 null(由函数默认 logistics_issue)。 + */ +function resolveExpressSubType(text) { + let best = null; + let bestLen = 0; + for (const item of EXPRESS_SUB_TYPE_RULES) { + for (const k of item.keys) { + if (text.includes(k) && k.length > bestLen) { + best = item.sub; + bestLen = k.length; + } + } + } + return best; +} + +/** + * 从消息文本中解析目标快递名称(通用“改快递/换快递”规则用)。 + * @param {string} text 消息正文。 + * @return {string|null} 快递名称,未命中返回 null。 + */ +function extractExpressName(text) { + const lower = String(text || '').toLowerCase(); + return EXPRESS_NAMES.find(name => lower.includes(name.toLowerCase())) || null; +} + +/** + * 去除命中的关键词,取剩余文本作为查询词(查库存场景)。 + * @param {string} text 消息正文。 + * @param {string[]} keys 命中关键词列表。 + * @return {string} 剩余文本。 + */ +function stripKeyword(text, keys) { + let t = String(text || ''); + for (const k of keys) { + t = t.split(k).join(' '); + } + return t.replace(/\s+/g, ' ').trim(); +} + +/** 确认/感谢类短消息 → 静默 */ +const SILENT_RE = /^(好|好的|好的呢|好嘞|嗯|嗯嗯|哦|哦哦|ok|okay|收到|谢谢|感谢|谢谢啦|谢了|好了|可以|行|行了|对啊|是的|对|知道了|明白|了解了|1)\s*[!!。.,~~👍🙏❤️]*$/i; + +// ============================ 规则表(顺序即优先级) ============================ + +/** + * 运单号标签:"物流单号 / 物流单 号 / 物 流单号 / 快递单号 / 运单号" 等 + * 只是单号前缀说明,不代表"要查物流"。判定查询意图前先剔除标签词, + * 避免机器人格式"物流单号:SF123 拦截"因含"物流"被误判为物流查询而整条静默(不回信)。 + * 兼容 IM 转写时在标签字符间断插空格的情况(实测生产存在"物 流单号")。 + * 仅剔除标签本身,聊天正文里的"物流显示签收"等仍保留,查询类消息继续被守卫拦住。 + */ +const WAYBILL_LABEL_RE = /(物\s*流|快\s*递|运\s*单|包\s*裹|邮\s*件)\s*单\s*号?/g; + +/** 物流查询意图关键词:命中即认为不是拦截请求 */ +const TRACKING_QUERY_RE = /(到哪|在哪|哪里|快递到|物流|轨迹|查单|查快递|查物流|到哪里|取消拦截|撤销拦截|解除拦截|不拦截|不用拦截)/; + +/** + * 拦截类规则的防误判守卫:询问物流进度/查快递等不是拦截请求, + * 取消/撤销类语义属于 cancelIntercept(双保险,长词优先已能保证) + * @param {string} t 消息正文 + * @return {boolean} 是否允许命中拦截规则 + */ +const INTERCEPT_GUARD = t => !TRACKING_QUERY_RE.test(String(t || '').replace(WAYBILL_LABEL_RE, ' ')); + +/** 货主群(store) */ +const STORE_RULES = [ + { keys: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截', '不用拦截' ], fn: 'cancelIntercept', waybill: true, + tip: '如需取消拦截,发送:取消拦截+运单号(多个单号用逗号或空格分隔)\n例:取消拦截 SF123,SF456' }, + { keys: [ '拦截', '追回', '召回' ], fn: 'interceptWaybill', waybill: true, guard: INTERCEPT_GUARD, + tip: '如需拦截运单,发送:拦截+运单号(多个单号用逗号或空格分隔)\n例:拦截 SF123,SF456' }, + { keys: [ '揽收', '上门取件', '退货取件', '让快递来拿' ], fn: 'requestPickup', waybill: true, + tip: '如需安排上门揽收,发送:揽收+运单号\n例:揽收 SF123' }, + { keys: [ '少发', '发少' ], fn: 'handleStoreFeedback', issueType: 'missing', waybill: true, + tip: '如需反馈少发,发送:少发+运单号\n例:少发 SF123' }, + { keys: [ '重量', '查重', '核实重量', '核重', '称重' ], fn: 'queryWeight', waybill: true, + tip: '如需查询库内称重,发送:称重+运单号\n例:称重 SF123' }, + { keys: [ '错发', '发错' ], fn: 'handleStoreFeedback', issueType: 'wrong', waybill: true, + tip: '如需反馈错发,发送:错发+运单号\n例:错发 SF123' }, + { keys: [ '破损', '坏了' ], fn: 'handleStoreFeedback', issueType: 'damaged', waybill: true, + tip: '如需反馈破损,发送:破损+运单号\n例:破损 SF123' }, + { keys: [ '多发', '发多' ], fn: 'handleStoreFeedback', issueType: 'multiple', waybill: true, + tip: '如需反馈多发,发送:多发+运单号\n例:多发 SF123' }, + { keys: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机' ], fn: 'changeAddr', issueType: 'addr', waybill: true, + tip: '如需修改地址,发送:改地址+运单号\n例:改地址 SF123' }, + // 注意顺序:催退回/催促退回 必须在 催件/催促 之前("催促退回"含"催促") + { keys: [ '催退回', '催促退回' ], fn: 'changeAddr', issueType: 'return', waybill: true, + tip: '如需催退回,发送:催退回+运单号\n例:催退回 SF123' }, + { keys: [ '催件', '催派', '催促', '尽快安排派送', '未中转', '物流停滞' ], fn: 'changeAddr', issueType: 'urge', waybill: true, + tip: '如需催件,发送:催件+运单号\n例:催件 SF123' }, + { keys: [ '查退回', '是否已退回', '查退件', '查件' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code', + tip: '如需查退回,发送:查退回+运单号\n例:查退回 SF123' }, + { keys: [ '退回', '拒收' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code', + tip: '如需查退回,发送:查退回+运单号\n例:查退回 SF123' }, + { keys: [ '核实签收', '未收到', '是否发出', '是否已经发货', '没有找到快递' ], fn: 'weishoudao', waybill: true, + tip: '如需核实签收,发送:核实签收+运单号\n例:核实签收 SF123' }, + { keys: [ '出单', '打单', '打印单', '催发货', '分配快递号' ], fn: 'createPostnum', order: true, + tip: '如需出单/分配快递号,发送:出单+订单号\n例:出单 SYS2026010100001' }, + // 通用格式:改快递+订单号+快递名(放在固定“改圆通”等规则之前,两者关键词互不冲突) + { keys: [ '改快递', '换快递' ], fn: 'changeExpress', expressFromText: true, order: true, + tip: '如需改快递,发送:改快递+订单号+快递名称\n例:改快递 SYS2026010100001 圆通' }, + { keys: [ '改圆通' ], fn: 'changeExpress', express: '圆通', order: true, + tip: '如需改快递,发送:改圆通+订单号\n例:改圆通 SYS2026010100001' }, + { keys: [ '改中通' ], fn: 'changeExpress', express: '中通', order: true, + tip: '如需改快递,发送:改中通+订单号' }, + { keys: [ '改申通' ], fn: 'changeExpress', express: '申通', order: true, + tip: '如需改快递,发送:改申通+订单号' }, + { keys: [ '改极兔' ], fn: 'changeExpress', express: '极兔', order: true, + tip: '如需改快递,发送:改极兔+订单号' }, + { keys: [ '改韵达' ], fn: 'changeExpress', express: '韵达', order: true, + tip: '如需改快递,发送:改韵达+订单号' }, + { keys: [ '改顺丰' ], fn: 'changeExpress', express: '顺丰', order: true, + tip: '如需改快递,发送:改顺丰+订单号' }, + { keys: [ '改邮政' ], fn: 'changeExpress', express: '邮政', order: true, + tip: '如需改快递,发送:改邮政+订单号' }, + { keys: [ '改EMS', '改ems' ], fn: 'changeExpress', express: 'EMS', order: true, + tip: '如需改快递,发送:改EMS+订单号' }, + { keys: [ '改京东' ], fn: 'changeExpress', express: '京东', order: true, + tip: '如需改快递,发送:改京东+订单号' }, + { keys: [ '仓库地址', '退货地址', '退件地址', '寄回地址', '收货地址' ], fn: 'queryWarehouseAddress' }, + { keys: [ '到货' ], fn: 'registerLicensePlate', + tip: '如需到货登记,发送:到货+车牌号\n例:到货 粤A12345' }, + { keys: [ '打包视频', '装箱视频' ], fn: 'queryPackVideo', waybill: true, + tip: '如需查询打包视频,发送:打包视频+运单号\n例:打包视频 SF123' }, + { keys: [ '查库存' ], fn: 'searchStock', stockSearch: true, + tip: '如需查库存,发送:查库存+商品名称/编码/条码' }, + { keys: [ 'help', '指令', '帮助' ], fn: '__help__' }, +]; + +/** 仓库内部群(warehouse,客服子类型可用的函数较多,不可用函数自动跳过) */ +const WAREHOUSE_RULES = [ + { keys: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截', '不用拦截' ], fn: 'cancelIntercept', waybill: true, + tip: '如需取消拦截,发送:取消拦截+运单号' }, + { keys: [ '拦截', '追回', '召回' ], fn: 'interceptWaybill', waybill: true, guard: INTERCEPT_GUARD, + tip: '如需拦截运单,发送:拦截+运单号' }, + { keys: [ '揽收', '上门取件' ], fn: 'requestPickup', waybill: true, + tip: '如需安排上门揽收,发送:揽收+运单号' }, + { keys: [ '查退回', '是否已退回' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code', + tip: '如需查退回,发送:查退回+运单号' }, + { keys: [ '重量', '查重', '核实重量', '核重', '称重' ], fn: 'queryWeight', waybill: true, + tip: '如需查询库内称重,发送:称重+运单号' }, + { keys: [ '打包视频', '装箱视频' ], fn: 'queryPackVideo', waybill: true, + tip: '如需查询打包视频,发送:打包视频+运单号' }, + { keys: [ '仓库地址', '退货地址', '退件地址', '寄回地址', '收货地址' ], fn: 'queryWarehouseAddress' }, + { keys: [ '开门' ], fn: 'openDoor' }, + { keys: [ '到货' ], fn: 'registerLicensePlate', + tip: '如需到货登记,发送:到货+车牌号\n例:到货 粤A12345' }, + { keys: [ '离场' ], fn: 'departure', + tip: '如需离场登记,发送:车牌号+离场\n例:粤A12345离场' }, + { keys: [ '进场' ], fn: 'enter', + tip: '如需进场登记,发送:车牌号+进场\n例:粤A12345进场' }, + { keys: [ '查库存' ], fn: 'searchWarehouseStock', stockSearch: true, + tip: '如需查库存,发送:查库存+商品名称/编码/条码' }, + { keys: [ 'help', '指令', '帮助' ], fn: '__help__' }, +]; + +/** 快递售后群(express)规则表:消息含运单号即按反馈处理(按关键词推断子类型),无运单号静默 */ +const EXPRESS_RULES = [ + { any: true, fn: 'handleExpressFeedback', waybill: true, noWaybillSilent: true, expressSubType: true }, +]; + +/** 规则表:按群类型选择 */ +const RULE_TABLES = { + store: STORE_RULES, + warehouse: WAREHOUSE_RULES, + express: EXPRESS_RULES, +}; + +// ============================ 帮助文本 ============================ + +const HELP_TEXTS = { + store: '当前群支持以下指令(发送:指令+单号,多个单号用逗号或空格分隔):\n' + + '· 拦截+运单号 / 取消拦截+运单号\n' + + '· 揽收+运单号\n' + + '· 催件+运单号 / 催退回+运单号\n' + + '· 改地址+运单号\n' + + '· 称重+运单号 / 查退回+运单号 / 核实签收+运单号\n' + + '· 打包视频+运单号\n' + + '· 少发/错发/破损/多发+运单号\n' + + '· 出单+订单号\n' + + '· 改圆通/改中通/改申通/改顺丰/改韵达/改极兔/改邮政/改EMS/改京东+订单号\n' + + '· 仓库地址\n' + + '· 查库存+商品名称或条码', + warehouse: '当前群支持以下指令:\n' + + '· 拦截+运单号 / 取消拦截+运单号\n' + + '· 揽收+运单号\n' + + '· 查退回+运单号 / 称重+运单号\n' + + '· 打包视频+运单号\n' + + '· 仓库地址\n' + + '· 查库存+商品名称或条码', + express: '发送运单号+处理情况,系统将自动记录并回信货主群。', +}; + +module.exports = InboxRulesService; diff --git a/app/service/inbox/tools.js b/app/service/inbox/tools.js new file mode 100644 index 0000000..bafa37c --- /dev/null +++ b/app/service/inbox/tools.js @@ -0,0 +1,51 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 站内信工具方法集合(与业务函数无关的辅助逻辑)。 + * 从 inbox/functions.js 拆出,保持 functions.js 只负责业务函数注册与执行。 + */ +class InboxToolsService extends Service { + + /** + * 获取仓库的录制电脑 ID(带缓存)。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 录制电脑ID,找不到返回 null + */ + async getRecordingComputerId(warehouseId) { + const cacheKey = `_recordingComputer_${warehouseId}`; + if (this[cacheKey] !== undefined) { + return this[cacheKey]; + } + const row = await this.ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + attributes: [ 'id' ], + raw: true, + }); + this[cacheKey] = row ? row.id : null; + return this[cacheKey]; + } + + /** + * 构建视频完整 URL。 + * 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath} + * @param {number} warehouseId 仓库ID + * @param {number|null} recordingComputerId 录制电脑ID + * @param {string} videoPath 视频路径 + * @return {string} 完整 URL + */ + buildVideoUrl(warehouseId, recordingComputerId, videoPath) { + const path = String(videoPath || '').trim(); + if (!path || !recordingComputerId) { + return path; + } + // 已是完整 URL 时原样返回,避免重复拼接 + if (/^https?:\/\//i.test(path)) { + return path; + } + return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${path}`; + } +} + +module.exports = InboxToolsService; diff --git a/app/service/inbox/v2/config.js b/app/service/inbox/v2/config.js new file mode 100644 index 0000000..accb888 --- /dev/null +++ b/app/service/inbox/v2/config.js @@ -0,0 +1,214 @@ +'use strict'; + +const Service = require('egg').Service; + +/** v2 配置缓存键前缀(单仓库一份配置,TTL 300s)。 */ +const CACHE_KEY_PREFIX = 'inbox:v2:cfg:'; +/** 配置缓存 TTL(秒)。 */ +const CACHE_TTL = 300; +/** 缓存结构版本号,结构变更时递增,避免读到旧结构。 */ +const CACHE_VERSION = 2; + +/** + * v2 仓库可配置回信引擎 —— 配置加载服务。 + * + * 职责: + * - load(warehouseId):加载"系统级(warehouse_id IS NULL) + 仓库级(warehouse_id=当前仓库)"合并后的配置, + * 缓存于单 key inbox:v2:cfg:{warehouseId}(TTL 300s),缓存 miss 时从 DB 拼装; + * - invalidate(warehouseId):删除指定仓库配置缓存(仅管理接口调用,启动不清缓存防雪崩)。 + * + * 配置结构(纯对象,可安全进缓存/Redis 序列化,不含 Map/Set/RegExp 实例): + * { + * _v: 1, + * subTypes: { [id]: {id, type, sub_type, name, is_system, is_enabled, sort_order} }, + * keywords: [ {keyword, sub_type_id, sort_order} ], + * groupWhitelist: { [sub_type_id]: [ {group_type, sub_group} ] }, + * subTypeFunctions: { [sub_type_id]: [ {function_code, sort_order} ] }, + * functionEnabled: { [function_code]: true }, + * subTypeRules: { [sub_type_id]: [ {target, regexp, sort_order} ] }, + * replies: { [sub_type_id]: {reply, is_reply, no_number_hint, warehouse_id} } // 仓库级覆盖系统级 + * } + */ +class InboxV2ConfigService extends Service { + /** + * 加载仓库配置(缓存优先)。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 配置对象。 + */ + async load(warehouseId) { + const { app } = this; + const wid = Number(warehouseId) || 0; + const key = CACHE_KEY_PREFIX + wid; + + if (typeof app.getCacheAsync === 'function') { + const cached = await app.getCacheAsync(key); + if (cached && cached._v === CACHE_VERSION) return cached; + } + + const cfg = await this.build(wid); + if (typeof app.setCacheAsync === 'function') { + await app.setCacheAsync(key, cfg, CACHE_TTL); + } + return cfg; + } + + /** + * 失效仓库配置缓存(管理接口增删改配置后调用)。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async invalidate(warehouseId) { + const { app } = this; + const wid = Number(warehouseId) || 0; + if (typeof app.delCacheAsync === 'function') { + await app.delCacheAsync(CACHE_KEY_PREFIX + wid); + } + } + + /** + * 从 DB 拼装配置(全量小表查询 + 内存关联)。 + * @param {number} wid 仓库ID(0=未绑定仓库,只加载系统级)。 + * @return {Promise} 配置对象。 + */ + async build(wid) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const wh = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: wid }] }; + + // 1. 子类型(启用) + const subTypes = await ctx.model.AfterSaleSubType.findAll({ + where: { ...wh, is_enabled: 1 }, + raw: true, + }); + const subTypeMap = {}; + const validSubTypeIds = new Set(); + for (const s of subTypes) { + subTypeMap[s.id] = { + id: s.id, type: s.type, sub_type: s.sub_type, name: s.name, + is_system: s.is_system, is_enabled: s.is_enabled, + sort_order: Number(s.sort_order) || 0, + }; + validSubTypeIds.add(s.id); + } + + // 2. 关键词(启用) + const keywords = await ctx.model.AfterSaleKeyword.findAll({ + where: { ...wh, is_enabled: 1 }, + attributes: [ 'keyword', 'sub_type_id', 'sort_order' ], + raw: true, + }); + const kwList = keywords + .filter(k => validSubTypeIds.has(k.sub_type_id)) + .sort((a, b) => (a.sort_order - b.sort_order) || String(a.keyword).length - String(b.keyword).length); + + // 3. 群类型白名单(全局表) + const groupRows = await ctx.model.AfterSaleSubTypeGroup.findAll({ + attributes: [ 'sub_type_id', 'group_type', 'sub_group' ], + raw: true, + }); + const groupWhitelist = {}; + for (const g of groupRows) { + if (!validSubTypeIds.has(g.sub_type_id)) continue; + if (!groupWhitelist[g.sub_type_id]) groupWhitelist[g.sub_type_id] = []; + groupWhitelist[g.sub_type_id].push({ + group_type: String(g.group_type || '').trim(), + sub_group: String(g.sub_group || '').trim(), + }); + } + + // 4. 子类型-函数关系(全局表) + const funcRelRows = await ctx.model.AfterSaleSubTypeFunction.findAll({ + attributes: [ 'sub_type_id', 'function_id', 'sort_order' ], + raw: true, + }); + const funcRows = await ctx.model.AfterSaleFunction.findAll({ + attributes: [ 'id', 'function_code', 'is_enabled' ], + raw: true, + }); + const funcIdMap = {}; + const functionEnabled = {}; + // 启用状态硬编码:代码注册表中存在的函数即启用(DB is_enabled 仅作展示参考,不再作为启用依据) + let registry = null; + try { + registry = this.ctx.service.inbox.functions.registry; + } catch (e) { /* ignore */ } + for (const f of funcRows) { + funcIdMap[f.id] = f.function_code; + const inRegistry = registry instanceof Map && registry.has(f.function_code); + if (inRegistry || (registry === null && Number(f.is_enabled) === 1)) { + functionEnabled[f.function_code] = true; + } + } + const subTypeFunctions = {}; + for (const r of funcRelRows) { + const code = funcIdMap[r.function_id]; + if (!code || !validSubTypeIds.has(r.sub_type_id)) continue; + if (!subTypeFunctions[r.sub_type_id]) subTypeFunctions[r.sub_type_id] = []; + subTypeFunctions[r.sub_type_id].push({ function_code: code, sort_order: r.sort_order }); + } + for (const key of Object.keys(subTypeFunctions)) { + subTypeFunctions[key].sort((a, b) => a.sort_order - b.sort_order); + } + + // 5. 子类型-取号规则关系(全局表)+ 取号规则本体 + const ruleRelRows = await ctx.model.AfterSaleSubTypeRule.findAll({ + attributes: [ 'sub_type_id', 'number_rule_id', 'sort_order' ], + raw: true, + }); + const ruleRows = await ctx.model.InboxNumberRule.findAll({ + attributes: [ 'id', 'target', 'regexp', 'sort_order' ], + raw: true, + }); + const ruleIdMap = {}; + for (const n of ruleRows) ruleIdMap[n.id] = n; + const subTypeRules = {}; + for (const r of ruleRelRows) { + const rule = ruleIdMap[r.number_rule_id]; + if (!rule || !validSubTypeIds.has(r.sub_type_id)) continue; + if (!subTypeRules[r.sub_type_id]) subTypeRules[r.sub_type_id] = []; + subTypeRules[r.sub_type_id].push({ + target: String(rule.target || '').trim(), + regexp: String(rule.regexp || ''), + sort_order: r.sort_order || rule.sort_order || 0, + }); + } + for (const key of Object.keys(subTypeRules)) { + subTypeRules[key].sort((a, b) => a.sort_order - b.sort_order); + } + + // 6. 回复表:仓库级覆盖系统级(同子类型取 warehouse_id 非空者优先) + const replyRows = await ctx.model.AfterSaleReply.findAll({ + where: { ...wh, is_enabled: 1 }, + attributes: [ 'warehouse_id', 'sub_type_id', 'reply', 'is_reply', 'create_work_order', 'no_number_hint' ], + raw: true, + }); + const replies = {}; + for (const r of replyRows) { + if (!validSubTypeIds.has(r.sub_type_id)) continue; + const isWh = r.warehouse_id !== null && r.warehouse_id !== undefined; + const existing = replies[r.sub_type_id]; + if (!existing || (isWh && existing.warehouse_id === null)) { + replies[r.sub_type_id] = { + reply: String(r.reply || ''), + is_reply: Number(r.is_reply) === 1 ? 1 : 0, + create_work_order: Number(r.create_work_order) === 0 ? 0 : 1, + no_number_hint: r.no_number_hint ? String(r.no_number_hint) : '', + warehouse_id: isWh ? r.warehouse_id : null, + }; + } + } + + return { + _v: CACHE_VERSION, + subTypes: subTypeMap, + keywords: kwList, + groupWhitelist, + subTypeFunctions, + functionEnabled, + subTypeRules, + replies, + }; + } +} + +module.exports = InboxV2ConfigService; diff --git a/app/service/inbox/v2/functionSync.js b/app/service/inbox/v2/functionSync.js new file mode 100644 index 0000000..b21034f --- /dev/null +++ b/app/service/inbox/v2/functionSync.js @@ -0,0 +1,130 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * function_code → 中文名称映射(管理界面展示用)。 + * 未列出的函数回退到 function_code(英文注册名)。 + */ +const FUNCTION_NAME_MAP = { + hello: '问候', + help: '帮助', + queryPrintBalance: '查询面单余额', + createWaybill: '创建运单号', + searchStock: '搜索货主商品', + searchWarehouseStock: '搜索仓库商品', + queryOrder: '查询订单', + recallHistory: '回顾对话历史', + createOrder: '创建发货单', + blockUser: '屏蔽用户', + interceptWaybill: '拦截运单', + requestPickup: '揽收处理', + queryReturn: '查询退回单', + cancelIntercept: '取消拦截', + handleStoreFeedback: '问题反馈建单', + changeAddr: '改地址/催件处理', + weishoudao: '核实签收', + changeExpress: '改快递', + createPostnum: '分配快递号', + queryPackVideo: '查询打包视频', + queryWeight: '查询重量', + handleExpressFeedback: '快递反馈处理', + queryWarehouseAddress: '查询仓库地址', + listGroups: '查询群列表', + openDoor: '开门', + registerLicensePlate: '到货登记', + departure: '离场登记', + enter: '进场登记', +}; + +/** + * 售后函数表同步服务(v2 仓库可配置回信引擎)。 + * + * 职责:启动时把 inbox functions 注册表(代码权威源)幂等 upsert 到 + * wms_after_sale_function,供管理界面展示与开关控制。 + * + * 原则: + * - 只增改、不删:代码中已删除的函数保留 DB 行(避免关联行悬空,管理端可见并可停用); + * - 不覆盖管理端字段:is_enabled / sort_order 由管理端维护,同步仅刷新 name/description; + * - 失败仅告警:本服务不影响任何消息处理链路,运行时执行始终以代码注册表为准。 + */ +class InboxV2FunctionSyncService extends Service { + /** + * 同步注册表到售后函数表(幂等,可重复执行)。 + * @return {Promise<{ok:boolean, created:number, updated:number, total:number, skipped?:boolean, error?:string}>} 同步统计结果,skipped 表示未执行同步(模型缺失/注册表为空)。 + */ + async sync() { + const { ctx } = this; + const stats = { ok: false, created: 0, updated: 0, total: 0 }; + + // 模型缺失场景(如部分单测):直接跳过,不报错。 + if (!ctx.model || !ctx.model.AfterSaleFunction) { + return { ...stats, ok: true, skipped: true }; + } + + let registry; + try { + const functionsSvc = ctx.service.inbox.functions; + registry = functionsSvc && functionsSvc.registry; + } catch (e) { + ctx.logger.warn(`[inbox v2] 函数服务不可用,跳过函数表同步: ${e.message}`); + return { ...stats, ok: true, skipped: true }; + } + + if (!(registry instanceof Map) || registry.size === 0) { + return { ...stats, ok: true, skipped: true }; + } + + // 收集待同步行(function_code 即注册名)。 + const rows = []; + const seen = new Set(); + for (const [ code, def ] of registry) { + if (!code || seen.has(code)) continue; + seen.add(code); + rows.push({ + function_code: code, + name: FUNCTION_NAME_MAP[code] || code, + description: (typeof def.description === 'string' ? def.description : '').slice(0, 500) || null, + }); + } + stats.total = rows.length; + + try { + // 同步前查现有集合,用于统计新增/更新。 + const existing = await ctx.model.AfterSaleFunction.findAll({ + attributes: [ 'function_code' ], + raw: true, + }); + const existingSet = new Set(existing.map(r => r.function_code)); + stats.created = rows.filter(r => !existingSet.has(r.function_code)).length; + stats.updated = rows.length - stats.created; + + // bulkCreate + updateOnDuplicate:新行插入(is_enabled 默认 1、sort_order 默认 0), + // 已有行刷新 name/description;启用状态硬编码——注册表存在即启用(is_enabled 同步为 1), + // sort_order 由接口配置,不同步覆盖。 + await ctx.model.AfterSaleFunction.bulkCreate(rows, { + updateOnDuplicate: [ 'name', 'description', 'is_enabled' ], + }); + + // 代码已删除的函数:保留行但标记下线(is_enabled=0),不删除。 + if (rows.length > 0) { + const codes = rows.map(r => r.function_code); + const { Op } = ctx.app.Sequelize; + await ctx.model.AfterSaleFunction.update( + { is_enabled: 0 }, + { where: { function_code: { [Op.notIn]: codes } } } + ); + } + + stats.ok = true; + return stats; + } catch (error) { + ctx.logger.warn( + `[inbox v2] 售后函数表同步失败(不影响启动): ${error && error.message ? error.message : error}` + ); + return { ...stats, error: error && error.message ? error.message : String(error) }; + } + } +} + +module.exports = InboxV2FunctionSyncService; diff --git a/app/service/inbox/v2/rules.js b/app/service/inbox/v2/rules.js new file mode 100644 index 0000000..42dbb6e --- /dev/null +++ b/app/service/inbox/v2/rules.js @@ -0,0 +1,422 @@ +'use strict'; + +/* eslint-disable no-use-before-define */ + +const Service = require('egg').Service; + +/** + * 取号 target → 函数入参键映射。 + * keyword 类(运单号/订单号/平台单号/收货单/入库单/出库单)合并为一个逗号分隔字符串; + * express_name 取第一个匹配值。 + * 注意:只保留有真实消费者的映射;plate_no 当前无函数消费 params.plate_no + * (车牌函数自行从原消息提取),不入映射,避免悬空。 + */ +const TARGET_PARAM_MAP = { + waybill_no: 'keyword', + order_no: 'keyword', + source_order_codes: 'keyword', + receiving_no: 'keyword', + entry_order_no: 'keyword', + stockout_no: 'keyword', + express_name: 'express', +}; + +/** + * 函数按子类型补充 issue_type 入参(函数入参语义由代码定义,引擎按子类型转译)。 + */ +const FN_ISSUE_TYPE_MAP = { + handleStoreFeedback: { + damage: 'damaged', missing_item: 'missing', mis_shipment: 'wrong', extra_item: 'multiple', + }, + changeAddr: { + change_address: 'addr', rejected: 'return', urge: 'urge', + }, +}; + +/** 取号失败默认引导语(回复表未配置 no_number_hint 时使用)。 */ +const DEFAULT_NO_NUMBER_HINT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)'; + +/** 单值类 target 缺参引导语。 */ +const TARGET_HINT_MAP = { + express_name: '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)', +}; + +/** + * v2 仓库可配置回信引擎(规则驱动,替代 v1 硬编码规则表)。 + * + * 链路:关键词命中(长词优先)→ 群类型白名单过滤 → 关系表取处理函数 → + * 取号规则提取对象数组 → 入参组装 → callFunction(代码 groups 越权校验兜底)→ 回复表决策。 + * + * 出参与 v1 rules.handle 同构: + * - { handled: false }:未命中; + * - { handled: true, silent: true }:命中但静默(回复表 is_reply=0); + * - { handled: true, reply, fn, params, result, matchedKey, thoughts }:已执行。 + * + * 安全三件套(取号正则):保存时校验(管理接口)+ 长度上限(DB 列 500)+ + * 每次 new RegExp(绝不缓存编译对象,避免状态污染与 ReDoS 复用),非法正则跳过并告警。 + */ +class InboxV2RulesService extends Service { + /** + * v2 引擎主入口。 + * @param {string} content 消息正文。 + * @return {Promise} 处理结果(与 v1 rules.handle 同构)。 + */ + async handle(content) { + const { ctx } = this; + const text = String(content || '').trim(); + if (!text) return { handled: false }; + + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + if (!groupType) return { handled: false }; + + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupSubType = String(ctx.inboxContext?.sub_type || '').trim(); + const cfg = await ctx.service.inbox.v2.config.load(warehouseId); + + // 1. 关键词命中:长词优先;同长按 sort_order;同长同子类型只保留一次。 + const candidates = this._matchKeywords(text, cfg); + if (candidates.length === 0) { + ctx.logger.info(`[inbox v2] 未命中关键词 group=${groupType} text=${text.slice(0, 50)}`); + return { handled: false }; + } + + const groupsSvc = ctx.service.inbox.groups; + const funcSvc = ctx.service.inbox.functions; + const activeGroups = groupsSvc.resolveActiveGroups(); + + // 2. 候选子类型逐个尝试:白名单过滤 → 取函数 → 取号 → 执行。 + for (const cand of candidates) { + const subType = cfg.subTypes[cand.sub_type_id]; + if (!subType) continue; + + // 2.1 群类型白名单过滤(sub_group 维度;群 sub_type 为空时只按主类型) + if (!this._groupAllowed(cfg, cand.sub_type_id, groupType, groupSubType)) { + ctx.logger.info( + `[inbox v2] 子类型 ${subType.type}:${subType.sub_type} 不在群 ${groupType}:${groupSubType || '-'} 白名单,跳过` + ); + continue; + } + + // 2.2 取关联函数(启用且代码已注册且群权限可用) + const fns = (cfg.subTypeFunctions[cand.sub_type_id] || []).filter(f => + cfg.functionEnabled[f.function_code] + ); + if (fns.length === 0) { + ctx.logger.info(`[inbox v2] 子类型 ${subType.type}:${subType.sub_type} 无可用函数,跳过`); + continue; + } + + // 2.3 取号规则提取(对象数组:{target, values[]}) + const extracted = this._extractNumbers(text, cfg, cand.sub_type_id); + if (extracted === null) { + // 关联了取号规则但未提取到值 → 引导提示 + const reply = this._noNumberHint(cfg, cand.sub_type_id); + const thoughts = [{ + round: 0, + action: 'rule', + function: fns[0].function_code, + params: {}, + reason: `v2 关键词命中: ${cand.keyword},取号失败-引导提示`, + functionResult: null, + }]; + return { + handled: true, + reply, + fn: fns[0].function_code, + params: {}, + result: null, + matchedKey: cand.keyword, + thoughts, + }; + } + + // 2.4 逐函数执行:函数照常执行;create_work_order=0 时注入 skip_work_order + // 标记,由函数内部在建工单前自行跳过登记(其余处理不受影响)。 + const replyCfgNow = (cfg.replies || {})[cand.sub_type_id]; + const workOrderSkip = !!replyCfgNow && replyCfgNow.create_work_order === 0; + const results = []; + let lastFn = null; + let lastParams = null; + let executed = false; + if (workOrderSkip) { + ctx.inboxContext.skip_work_order = true; + ctx.logger.info( + `[inbox v2] 子类型 ${subType.type}:${subType.sub_type} 配置为不登记工单,函数照常执行但跳过建单` + ); + } + try { + for (const f of fns) { + const def = funcSvc.registry.get(f.function_code); + if (!def || !groupsSvc.isFunctionAvailable(def, activeGroups)) { + ctx.logger.info( + `[inbox v2] 函数 ${f.function_code} 当前群不可用,跳过 ` + + `groups=${def ? def.groups.join(',') : '-'} active=${activeGroups.join(',')}` + ); + continue; + } + const params = this._buildParams(f.function_code, subType, extracted); + const result = await funcSvc.callFunction(f.function_code, params); + lastFn = f.function_code; + lastParams = params; + executed = true; + ctx.logger.info( + `[inbox v2] 执行 fn=${f.function_code} sub=${subType.type}:${subType.sub_type} ` + + `params=${JSON.stringify(params)} success=${!!result.success}` + ); + if (!result.success) { + const thoughts = [{ + round: 0, + action: 'rule', + function: f.function_code, + params, + reason: `v2 关键词命中: ${cand.keyword}`, + functionResult: result, + }]; + return { + handled: true, + reply: String(result.error || '操作失败,请联系客服处理'), + fn: f.function_code, + params, + result, + matchedKey: cand.keyword, + thoughts, + }; + } + results.push({ fn: f.function_code, params, result }); + } + } finally { + if (workOrderSkip) ctx.inboxContext.skip_work_order = false; + } + if (!executed) continue; + + // 2.5 回复决策:完全由回复配置控制(仓库级覆盖系统级) + return this._buildOutcome(cfg, cand, subType, results, lastFn, lastParams, text); + } + + return { handled: false }; + } + + /** + * 关键词匹配:收集文本包含的所有关键词,按长度降序、sort_order 升序排序, + * 取最长命中词集合(同长多子类型均候选)。 + * @param {string} text 消息正文。 + * @param {Object} cfg v2 配置。 + * @return {Array<{keyword:string, sub_type_id:number}>} 候选列表。 + */ + _matchKeywords(text, cfg) { + const hits = []; + for (const k of cfg.keywords || []) { + if (k.keyword && text.includes(k.keyword)) hits.push({ keyword: k.keyword, sub_type_id: k.sub_type_id }); + } + if (hits.length === 0) return []; + hits.sort((a, b) => b.keyword.length - a.keyword.length); + const maxLen = hits[0].keyword.length; + const top = hits.filter(h => h.keyword.length === maxLen); + const seen = new Set(); + return top.filter(h => { + const key = h.sub_type_id; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); + } + + /** + * 群类型白名单过滤。 + * @param {Object} cfg v2 配置。 + * @param {number} subTypeId 子类型ID。 + * @param {string} groupType 群主类型。 + * @param {string} groupSubType 群子类型(可为空)。 + * @return {boolean} 是否允许。 + */ + _groupAllowed(cfg, subTypeId, groupType, groupSubType) { + const rows = (cfg.groupWhitelist || {})[subTypeId]; + if (!Array.isArray(rows) || rows.length === 0) return false; + return rows.some(r => { + if (r.group_type === '*') return true; // 全通配:所有群可用(如 help 指令) + if (r.group_type !== groupType) return false; + if (!groupSubType) return true; // 群未绑子类型:只按主类型放行 + if (r.sub_group === '*') return true; // 主类型内子类型通配(如 warehouse:*) + return r.sub_group === groupSubType; + }); + } + + /** + * 取号规则提取(安全三件套:每次 new RegExp + try/catch + 长度上限)。 + * @param {string} text 消息正文。 + * @param {Object} cfg v2 配置。 + * @param {number} subTypeId 子类型ID。 + * @return {Array|null} 提取结果数组 [{target, values[]}];未提取到任何值返回 null。 + */ + _extractNumbers(text, cfg, subTypeId) { + const rules = (cfg.subTypeRules || {})[subTypeId]; + if (!Array.isArray(rules) || rules.length === 0) return []; + + const out = []; + let anyHit = false; + for (const rule of rules) { + if (!rule.regexp) continue; + if (rule.regexp.length > 500) { + this.ctx.logger.warn(`[inbox v2] 取号正则超长跳过 sub_type_id=${subTypeId} target=${rule.target}`); + continue; + } + let re; + try { + re = new RegExp(rule.regexp, 'g'); // 每次新建,绝不缓存编译对象 + } catch (e) { + this.ctx.logger.warn( + `[inbox v2] 取号正则非法跳过 sub_type_id=${subTypeId} target=${rule.target}: ${e.message}` + ); + continue; + } + const values = []; + try { + for (const m of text.matchAll(re)) { + const v = String(m[0]).trim(); + if (v && !values.includes(v)) values.push(v); + } + } catch (e) { + this.ctx.logger.warn(`[inbox v2] 取号正则执行异常 target=${rule.target}: ${e.message}`); + } + out.push({ target: rule.target, values }); + if (values.length > 0) anyHit = true; + } + return anyHit ? out : null; + } + + /** + * 入参组装:取号结果对象数组 → 函数 params。 + * keyword 类 target 合并去重后 join(',');express/plate_no 取第一个值; + * 按函数补充 issue_type。 + * @param {string} fn 函数名。 + * @param {Object} subType 子类型记录。 + * @param {Array} extracted 提取结果。 + * @return {Object} 函数入参。 + */ + _buildParams(fn, subType, extracted) { + const params = {}; + const keywordValues = []; + for (const item of extracted) { + const paramKey = TARGET_PARAM_MAP[item.target]; + if (!paramKey || item.values.length === 0) continue; + if (paramKey === 'keyword') { + for (const v of item.values) { + if (!keywordValues.includes(v)) keywordValues.push(v); + } + } else if (!params[paramKey]) { + params[paramKey] = item.values[0]; + } + } + if (keywordValues.length > 0) params.keyword = keywordValues.join(','); + + // 子类型 → issue_type 转译 + const map = FN_ISSUE_TYPE_MAP[fn]; + if (map && map[subType.sub_type]) params.issue_type = map[subType.sub_type]; + return params; + } + + /** + * 取号失败引导语:回复表 no_number_hint → target 专属 → 默认。 + * @param {Object} cfg v2 配置。 + * @param {number} subTypeId 子类型ID。 + * @return {string} 引导语。 + */ + _noNumberHint(cfg, subTypeId) { + const replyCfg = (cfg.replies || {})[subTypeId]; + if (replyCfg && replyCfg.no_number_hint) return replyCfg.no_number_hint; + + const rules = (cfg.subTypeRules || {})[subTypeId] || []; + for (const r of rules) { + if (TARGET_HINT_MAP[r.target]) return TARGET_HINT_MAP[r.target]; + } + return DEFAULT_NO_NUMBER_HINT; + } + + /** + * 出参构建:回复决策完全由回复配置控制(仓库级覆盖系统级)。 + * @param {Object} cfg v2 配置。 + * @param {Object} cand 命中候选。 + * @param {Object} subType 子类型记录。 + * @param {Array} results 函数执行结果数组。 + * @param {string} lastFn 最后执行的函数名。 + * @param {Object} lastParams 最后执行的函数入参。 + * @param {string} text 消息正文。 + * @return {Object} 与 v1 rules.handle 同构的出参。 + */ + _buildOutcome(cfg, cand, subType, results, lastFn, lastParams, text) { + const last = results.length > 0 ? results[results.length - 1] : null; + const replyCfg = (cfg.replies || {})[cand.sub_type_id]; + + // 回复决策:完全由回复配置控制。 + // - is_reply=0 → 静默; + // - reply 模板渲染非空 → 回复; + // - 无回复配置或模板渲染为空 → 不回复(函数已照常执行,仅不出回执)。 + if (replyCfg && replyCfg.is_reply === 0) { + return { handled: true, silent: true }; + } + let reply = null; + if (replyCfg && replyCfg.reply) { + const rendered = this._renderReply(replyCfg.reply, subType, results, text, lastParams); + if (rendered && String(rendered).trim()) reply = rendered; + } + + let thoughts = results.map((r, idx) => ({ + round: idx, + action: 'rule', + function: r.fn, + params: r.params, + reason: `v2 关键词命中: ${cand.keyword}`, + functionResult: r.result, + })); + if (thoughts.length === 0 && lastParams) { + // 兜底(一般不可达:fns 全部不可用才出现):记录一条无函数调用的轨迹 + thoughts = [{ + round: 0, + action: 'rule', + function: lastFn, + params: lastParams, + reason: `v2 关键词命中: ${cand.keyword}(无可用函数)`, + functionResult: null, + }]; + } + + return { + handled: true, + reply, + fn: lastFn || (last && last.fn), + params: lastParams || (last && last.params), + result: last ? last.result : null, + matchedKey: cand.keyword, + thoughts, + }; + } + + /** + * 回复文案占位符渲染:{sub_type_name}/{keyword}/{express}/{back_text}。 + * {back_text} 优先取函数返回的 data.back_text(如 help 函数生成的指令清单); + * 函数未返回 back_text 时回退到 data.message(对齐 v1 rules.buildReply 口径, + * 否则 interceptWaybill 等只返回 message 的函数渲染恒为空 → 静默不回信)。 + * @param {string} tpl 模板文案。 + * @param {Object} subType 子类型记录。 + * @param {Array} results 函数执行结果。 + * @param {string} text 消息正文。 + * @param {Object} [fallbackParams] 未执行函数时的备用参数(create_work_order=0 场景)。 + * @return {string} 渲染后的文案。 + */ + _renderReply(tpl, subType, results, text, fallbackParams) { + const last = results.length > 0 ? results[results.length - 1] : null; + const params = (last && last.params) || fallbackParams || {}; + const lastData = (last && last.result && last.result.data) || {}; + const backText = lastData.back_text + ? String(lastData.back_text) + : (typeof lastData.message === 'string' ? String(lastData.message) : ''); + return String(tpl) + .replace(/\{sub_type_name\}/g, subType.name || '') + .replace(/\{keyword\}/g, String(params.keyword || '')) + .replace(/\{express\}/g, String(params.express || '')) + .replace(/\{back_text\}/g, backText) + .replace(/\{text\}/g, text.slice(0, 200)); + } +} + +module.exports = InboxV2RulesService; diff --git a/app/service/main.js b/app/service/main.js index 1dc4fab..089852d 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -1,6 +1,7 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../lib/query_condition_parser'); class MainService extends Service { constructor(ctx) { @@ -15,6 +16,7 @@ class MainService extends Service { this._noNeedLogin = null; this._noNeedRight = null; this._noNeedAuth = null; + this._noNeedBind = null; this.user = null; this.userId = null; } @@ -30,7 +32,6 @@ class MainService extends Service { } fail(message, data, code = 0) { - console.log('fail', message, data); const result = { flag: 'failure', code, @@ -85,6 +86,119 @@ class MainService extends Service { }; } + isPlainObject(value) { + return value && typeof value === 'object' && !Array.isArray(value); + } + + normalizeWhereCondition(fieldKey, condition) { + const isQuickWhere = fieldKey === 'quickWhere'; + + if (this.isPlainObject(condition)) { + const hasStandardKeys = [ 'value', 'operator', 'type', 'field', 'values' ] + .some(key => Object.prototype.hasOwnProperty.call(condition, key)); + + if (hasStandardKeys) { + const normalized = { + ...condition, + }; + + if (!Object.prototype.hasOwnProperty.call(normalized, 'value') && Object.prototype.hasOwnProperty.call(normalized, 'values')) { + normalized.value = normalized.values; + delete normalized.values; + } + + if (!Object.prototype.hasOwnProperty.call(normalized, 'operator') || !normalized.operator) { + normalized.operator = Array.isArray(normalized.value) ? 'in' : (isQuickWhere ? 'like' : 'eq'); + } + + if (isQuickWhere) { + normalized.operator = normalized.operator || 'like'; + normalized.type = normalized.type || 'text'; + } + + if ((normalized.operator === 'between' || normalized.operator === 'notbetween') && this.isPlainObject(normalized.value)) { + const start = normalized.value.start ?? normalized.value.from ?? normalized.value.begin; + const end = normalized.value.end ?? normalized.value.to ?? normalized.value.finish; + normalized.value = [ start, end ]; + } + + return normalized; + } + } + + if (isQuickWhere) { + return { + operator: 'like', + type: 'text', + value: condition, + }; + } + + return { + operator: Array.isArray(condition) ? 'in' : 'eq', + value: condition, + }; + } + + normalizeWhereParams(whereInput = {}) { + if (!this.isPlainObject(whereInput)) { + return {}; + } + + const normalized = {}; + for (const [ fieldKey, condition ] of Object.entries(whereInput)) { + normalized[fieldKey] = this.normalizeWhereCondition(fieldKey, condition); + } + return normalized; + } + + extractWhereValues(normalizedWhere = {}) { + if (!this.isPlainObject(normalizedWhere)) { + return {}; + } + + const whereValues = {}; + for (const [ fieldKey, condition ] of Object.entries(normalizedWhere)) { + if (this.isPlainObject(condition) && Object.prototype.hasOwnProperty.call(condition, 'value')) { + whereValues[fieldKey] = condition.value; + } else { + whereValues[fieldKey] = condition; + } + } + return whereValues; + } + + prepareWhereContext(data = {}, options = {}) { + const specialFieldMap = this.isPlainObject(options.specialFieldMap) ? options.specialFieldMap : {}; + const rawWhere = this.isPlainObject(data && data.where) ? data.where : {}; + const normalizedWhere = this.normalizeWhereParams(rawWhere); + const parsed = parseWhereConditions({ + where: normalizedWhere, + app: this.app, + specialFieldMap, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + const whereValues = this.extractWhereValues(normalizedWhere); + this.ctx.whereRaw = rawWhere; + this.ctx.where = normalizedWhere; + this.ctx.whereValue = whereValues; + this.ctx.whereParsed = parsed.result; + + if (this.isPlainObject(data)) { + data.where = normalizedWhere; + } + + return { + where: normalizedWhere, + whereValue: whereValues, + parsed: parsed.result, + }; + } + async findQimenAppWithContract(appkey, customerId, warehouseCode) { const { app } = this; const cacheKey = `contract:${appkey}:${customerId}:${warehouseCode}`; @@ -194,8 +308,8 @@ class MainService extends Service { const _noNeedRight = (this._noNeedRight || '').split(','); const _noNeedAuth = (this._noNeedAuth || '').split(','); const _noNeedLog = (this._noNeedLog || '').split(','); + const _noNeedBind = (this._noNeedBind || '').split(','); const api_path = `${servicePath}.${actionName}`; - console.log(api_path, '_noNeedLog', _noNeedLog); const result = { status: 401, message: '', @@ -223,13 +337,16 @@ class MainService extends Service { try { // 3. 验证JWT令牌 - const NewauthHeader = ''; const decoded = app.jwt.verify(token, app.config.jwt.secret); const now = Math.floor(Date.now() / 1000); const expiresIn = decoded.exp - now; - if (expiresIn < 1800 && expiresIn > 0) { + const renewThreshold = app.config.jwt.renewThreshold + ?? (app.config.jwt.expiresIn ? app.config.jwt.expiresIn - 1 : 14399); + if (expiresIn < renewThreshold && expiresIn > 0) { // 移除过期时间(exp)和签发时间(iat),保留其他payload - const { exp, iat, ...payload } = decoded; + const payload = { ...decoded }; + delete payload.exp; + delete payload.iat; // 生成新的 token,使用原来的有效时间配置 const newToken = app.jwt.sign( @@ -242,8 +359,52 @@ class MainService extends Service { // 设置新的 token 到响应头 ctx.set('Authorization', `Bearer ${newToken}`); - console.log('Token 已刷新,新 token:', newToken.substring(0, 50) + '...'); } + + // 3.5 中间层:白名单内的接口优先按真实用户放行(正常登录 token 或已绑定 oauth token), + // 未绑定真实用户的微信登录态(oauth_id + user_id=0)作为兜底放行,业务方法经 ctx.oauth 取微信身份。 + if (_noNeedBind.indexOf('*') > -1 || _noNeedBind.indexOf(actionName) > -1) { + let oauth = null; + const oauthId = Number(decoded.oauth_id || 0); + if (Number.isInteger(oauthId) && oauthId > 0) { + oauth = await ctx.model.UserOauth.findByPk(oauthId, { raw: true }); + if (oauth) { + ctx.oauth = oauth; + ctx.oauthId = oauth.id; + } + } + + // 1. 有真实用户(oauth.user_id 或 token id)→ 按正常用户上下文放行 + const userId = oauth ? Number(oauth.user_id || 0) : Number(decoded.id || decoded.userId || 0); + if (userId > 0) { + const bindUser = await ctx.service.systems.auth.user.findById(userId); + if (bindUser) { + if (bindUser.status !== 1) { + result.status = 403; + result.message = '账号已被禁用'; + return result; + } + this.setUserContext(ctx, bindUser, decoded); + result.status = 200; + result.message = 'ok'; + result.user = bindUser; + return result; + } + } + + // 2. 未绑定真实用户的微信登录态 → 兜底放行(ctx.oauth 可用) + if (oauth) { + result.status = 200; + result.message = 'ok'; + return result; + } + + // 3. 既无用户也无微信登录态 → 401 + result.status = 401; + result.message = '未提供有效的微信登录态'; + return result; + } + // 4. 获取用户信息 const user = await ctx.service.systems.auth.user.findById(decoded.id || decoded.userId); @@ -259,8 +420,7 @@ class MainService extends Service { return result; } - if (_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1) { - } else { + if (!(_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1)) { if (user.auth_end && new Date(user.auth_end) < new Date()) { result.status = 406; result.message = '仓库有效期已过期'; @@ -279,11 +439,8 @@ class MainService extends Service { } // 6. 验证API权限(只检查类型为api的权限) - console.log('检查权限开始'); const hasPermission = await this.checkApiPermission(user, api_path); - console.log('检查权限结束', hasPermission); - if (!hasPermission) { result.status = 403; @@ -323,25 +480,166 @@ class MainService extends Service { * 检查用户是否有API访问权限(只检查类型为api的权限) * @param {Object} user - 用户信息 * @param {string} apiPath - API路径 - * @return {Promise} + * @return {Promise} 是否有权限 */ async checkApiPermission(user, apiPath) { - const { ctx } = this; + const normalizedApiPath = String(apiPath || '').trim().toLowerCase(); + if (!normalizedApiPath) { + return false; + } - console.log(user); try { - // 方法1: 从用户的权限列表中检查(如果已经加载了权限) - if (user.permissions && Array.isArray(user.permissions)) { - // 用户权限列表中可能包含所有权限,需要过滤出api权限 - console.log('user.permissions', user.permissions); - return user.permissions.includes(apiPath); + const { allAccess, pathSet, permissionIds } = this.extractApiPermissionState(user); + if (allAccess) { + return true; } + + if (pathSet.has(normalizedApiPath)) { + return true; + } + + if (permissionIds.size > 0 && this.ctx.model && this.ctx.model.Permission && typeof this.ctx.model.Permission.findAll === 'function') { + const permissionRows = await this.ctx.model.Permission.findAll({ + where: { + id: [ ...permissionIds ], + status: 1, + }, + attributes: [ 'id', 'path' ], + raw: true, + }); + + return permissionRows.some(item => String(item && item.path || '').trim().toLowerCase() === normalizedApiPath); + } + return false; } catch (error) { console.error('检查API权限失败:', error); return false; } } + + extractApiPermissionState(user = {}) { + const state = { + allAccess: false, + pathSet: new Set(), + permissionIds: new Set(), + }; + const visited = new Set(); + const sources = [ + user.permissions, + user.role_permissions, + user.permission_ids, + user.permissionIds, + ]; + + for (const source of sources) { + this.collectApiPermissionValue(source, state, visited); + if (state.allAccess) { + break; + } + } + + return state; + } + + collectApiPermissionValue(value, state, visited) { + if (state.allAccess || value === undefined || value === null) { + return; + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return; + } + + if (trimmed === '*') { + state.allAccess = true; + return; + } + + if ((trimmed.startsWith('[') && trimmed.endsWith(']')) || (trimmed.startsWith('{') && trimmed.endsWith('}'))) { + try { + const parsed = JSON.parse(trimmed); + if (parsed !== value) { + this.collectApiPermissionValue(parsed, state, visited); + return; + } + } catch (_) { + // 忽略 JSON 解析失败,继续按普通字符串处理。 + } + } + + if (trimmed.includes(',')) { + this.collectApiPermissionValue(trimmed.split(','), state, visited); + return; + } + + const asNumber = Number(trimmed); + if (Number.isInteger(asNumber) && String(asNumber) === trimmed) { + state.permissionIds.add(asNumber); + return; + } + + state.pathSet.add(trimmed.toLowerCase()); + return; + } + + if (typeof value === 'number') { + if (Number.isInteger(value) && value > 0) { + state.permissionIds.add(value); + } + return; + } + + if (Array.isArray(value)) { + for (const item of value) { + this.collectApiPermissionValue(item, state, visited); + if (state.allAccess) { + break; + } + } + return; + } + + if (typeof value !== 'object') { + return; + } + + if (visited.has(value)) { + return; + } + visited.add(value); + + if (value.allAccess === true || value.isAllAccess === true) { + state.allAccess = true; + return; + } + + const candidates = [ + value.path, + value.apiPath, + value.permission, + value.permissionPath, + value.value, + value.id, + value.permission_id, + value.permissionId, + value.permissions, + value.permission_ids, + value.permissionIds, + value.children, + value.items, + value.list, + ]; + + for (const candidate of candidates) { + this.collectApiPermissionValue(candidate, state, visited); + if (state.allAccess) { + break; + } + } + } /** * 设置用户上下文信息 * @param {Object} ctx - 上下文对象 @@ -355,7 +653,6 @@ class MainService extends Service { ctx.username = user.username; ctx.realName = user.real_name; - if (user.store_id) { ctx.currentStoreId = user.store_id; } @@ -369,11 +666,12 @@ class MainService extends Service { ctx.jwtPayload = decoded; } - systemInit(_noNeedLogin, _noNeedRight, _noNeedLog = '*', _noNeedAuth = '*') { + systemInit(_noNeedLogin, _noNeedRight, _noNeedLog = '*', _noNeedAuth = '*', _noNeedBind = '') { this._noNeedLogin = _noNeedLogin; this._noNeedRight = _noNeedRight; this._noNeedLog = _noNeedLog; this._noNeedAuth = _noNeedAuth; + this._noNeedBind = _noNeedBind; } } diff --git a/app/service/openapi/callback.js b/app/service/openapi/callback.js new file mode 100644 index 0000000..889a502 --- /dev/null +++ b/app/service/openapi/callback.js @@ -0,0 +1,297 @@ +'use strict'; + +const crypto = require('crypto'); +const Service = require('egg').Service; +const { signRequest } = require('../../lib/api_sign'); + +/** @type {number} 最大重试次数 */ +const MAX_RETRY = 3; + +/** 签名模式:md5(canonicalQuery + secret + md5(body)),与 /openapi 入站验签一致 */ +const SIGN_MODE_OPENAPI = 'openapi'; + +/** 签名模式:md5(secret + timestamp + bodyJson),与 methods/warehouse_notify.json 协议一致 */ +const SIGN_MODE_SIMPLE = 'simple'; + +/** @type {number[]} 递增重试延迟(毫秒) */ +const RETRY_DELAY_MS = [ 2000, 5000, 15000 ]; + +/** + * OpenAPI 统一回调通知服务。 + * 将订单状态变更等事件通过签名鉴权回调到外部 callback_url, + * 支持自动重试与日志记录。 + */ +class OpenapiCallbackService extends Service { + + /** + * 计算回调签名。 + * 默认算法(signMode=openapi):md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))), + * 与 OpenAPI 入口签名算法完全一致。 + * signMode=simple 时改用 md5(selfAppSecret + timestamp + bodyJson),与 + * `methods/warehouse_notify.json` 描述的仓库通知协议一致(部分外部系统按该口径验签)。 + * @param {Object} options 签名参数。 + * @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.selfAppSecret 应用密钥。 + * @param {Object} options.body 完整回调报文体(奇门同层级 { request: {...} })。 + * @param {string} options.timestamp 秒级时间戳(10 位字符串,与 /openapi 入站时效校验一致)。 + * @param {string} [options.signMode='openapi'] 签名模式:openapi / simple。 + * @return {{ canonicalQuery: string, bodySign: string, sign: string }} 签名计算结果。 + */ + signCallback({ event, appKey, selfAppSecret, body, timestamp, signMode = SIGN_MODE_OPENAPI }) { + if (signMode === SIGN_MODE_SIMPLE) { + const bodyJson = JSON.stringify(body || {}); + const secret = String(selfAppSecret || ''); + return { + canonicalQuery: '', + bodySign: '', + sign: crypto.createHash('md5').update(secret + timestamp + bodyJson).digest('hex'), + }; + } + + const query = { + method: event, + v: '1.0', + timestamp, + app_key: appKey, + }; + + return signRequest({ query, body, selfAppSecret }); + } + + /** + * 发送回调请求(带自动重试)。 + * 报文体固定为奇门同层级结构 { request: {...} },event 仅拼入 query 的 method; + * 非 2xx 响应或网络错误触发重试,最多重试 MAX_RETRY 次, + * 每次重试间隔递增(2s → 5s → 15s),请求超时 30 秒。 + * @param {Object} options 回调选项。 + * @param {string} options.callbackUrl 回调目标 URL。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.selfAppSecret 应用密钥。 + * @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。 + * @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。 + * @param {string} [options.signMode='openapi'] 签名模式:openapi(默认)/ simple(仓库通知协议)。 + * @return {Promise} 回调结果 { success, retryCount, response, error }。 + */ + async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, request, signMode = SIGN_MODE_OPENAPI }) { + const { ctx } = this; + // 秒级时间戳(10 位):与 /openapi 入站时效校验(±600 秒窗口)及回调调试页保持一致 + const timestamp = String(Math.floor(Date.now() / 1000)); + // 报文体固定为奇门同层级 { request }:event 只出现在 query 的 method 中 + const body = { request: request || {} }; + const { sign } = this.signCallback({ event, appKey, selfAppSecret, body, timestamp, signMode }); + + const queryString = [ + `method=${encodeURIComponent(event)}`, + 'v=1.0', + `timestamp=${timestamp}`, + `app_key=${encodeURIComponent(appKey)}`, + `sign=${sign}`, + ].join('&'); + const separator = callbackUrl.includes('?') ? '&' : '?'; + const url = `${callbackUrl}${separator}${queryString}`; + + /** @type {string|null} 最后一次错误信息 */ + let lastError = null; + + /** @type {Object|null} 最后一次响应对象 */ + let lastResponse = null; + + for (let attempt = 0; attempt <= MAX_RETRY; attempt++) { + try { + const result = await ctx.curl(url, { + method: 'POST', + contentType: 'json', + dataType: 'json', + data: body, + timeout: 30000, + }); + + lastResponse = result; + + if (result.status >= 200 && result.status < 300) { + console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} status=${result.status} success=true response=${this._formatResponsePayload(result.data)}`); + + await this.logCallback({ + appKey, + event, + callbackUrl, + success: true, + retryCount: attempt, + response: result.data, + }); + + return { + success: true, + retryCount: attempt, + response: result.data, + error: null, + }; + } + + lastError = new Error(`回调返回非 2xx 状态码: ${result.status}`); + + console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} status=${result.status} success=false response=${this._formatResponsePayload(result.data)}`); + + await this.logCallback({ + appKey, + event, + callbackUrl, + success: false, + retryCount: attempt, + response: result.data, + error: lastError.message, + }); + } catch (error) { + lastError = error; + const availableResponse = lastResponse ? lastResponse.data : null; + + console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} success=false error=${error.message} response=${this._formatResponsePayload(availableResponse)}`); + + await this.logCallback({ + appKey, + event, + callbackUrl, + success: false, + retryCount: attempt, + response: availableResponse, + error: error.message, + }); + } + + if (attempt < MAX_RETRY) { + const delay = RETRY_DELAY_MS[attempt] || RETRY_DELAY_MS[RETRY_DELAY_MS.length - 1]; + await new Promise(resolve => setTimeout(resolve, delay)); + } + } + + return { + success: false, + retryCount: MAX_RETRY, + response: lastResponse ? lastResponse.data : null, + error: lastError ? lastError.message : '回调失败', + }; + } + + /** + * 根据 app_key 查询 api_app 获取 callback_url 与密钥,发送回调通知。 + * 报文体由 sendWithRetry 统一包装为奇门同层级 { request: {...} }。 + * @param {Object} options 回调选项。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。 + * @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。 + * @param {string} [options.signMode='openapi'] 签名模式:openapi(默认)/ simple(仓库通知协议)。 + * @return {Promise} 回调结果 { success, retryCount, response, error }。 + */ + async sendByAppKey({ appKey, event, request, signMode = SIGN_MODE_OPENAPI }) { + const { ctx } = this; + const normalizedAppKey = String(appKey || '').trim(); + + if (!normalizedAppKey) { + ctx.logger.warn('[OpenapiCallback] sendByAppKey 缺少 appKey'); + + return { + success: false, + retryCount: 0, + response: null, + error: '缺少 appKey', + }; + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + raw: true, + }); + + if (!appConfig || !appConfig.callback_url) { + ctx.logger.warn(`[OpenapiCallback] 未找到有效的回调配置,appKey=${normalizedAppKey}`); + + return { + success: false, + retryCount: 0, + response: null, + error: '未找到有效的回调配置', + }; + } + + return await this.sendWithRetry({ + callbackUrl: appConfig.callback_url, + appKey: normalizedAppKey, + selfAppSecret: appConfig.self_app_secret || '', + event, + request, + signMode, + }); + } + + /** + * 将回调响应报文格式化为日志可输出的字符串。 + * 兼容对象、字符串、Buffer / ArrayBuffer / TypedArray 与 null / undefined, + * 超出最大长度时做截断处理,避免日志刷屏。 + * @param {*} response 回调响应报文,类型不限。 + * @return {string} 格式化后的报文字符串。 + */ + _formatResponsePayload(response) { + const MAX_PAYLOAD_LENGTH = 500; + let payload; + + if (response === null || response === undefined) { + payload = 'null'; + } else if (typeof response === 'string') { + payload = response; + } else if (Buffer.isBuffer(response)) { + payload = response.toString('utf8'); + } else if (response instanceof ArrayBuffer) { + payload = Buffer.from(response).toString('utf8'); + } else if (ArrayBuffer.isView(response)) { + // TypedArray 与 DataView:仅取视图对应的内存区间 + payload = Buffer.from(response.buffer, response.byteOffset, response.byteLength).toString('utf8'); + } else { + try { + payload = JSON.stringify(response); + } catch (error) { + // 循环引用等序列化异常时降级处理 + payload = String(response); + } + } + + if (payload.length > MAX_PAYLOAD_LENGTH) { + return `${payload.slice(0, MAX_PAYLOAD_LENGTH)}...(truncated)`; + } + + return payload; + } + + /** + * 记录回调日志。 + * 格式:[OpenapiCallback] event=xxx appKey=xxx url=xxx retry=N success=xxx response=xxx + * @param {Object} options 日志选项。 + * @param {string} options.appKey 应用 app_key。 + * @param {string} options.event 事件名。 + * @param {string} options.callbackUrl 回调目标 URL。 + * @param {boolean} options.success 是否成功。 + * @param {number} options.retryCount 重试次数。 + * @param {*} [options.response] 回调响应报文。 + * @param {string} [options.error] 错误信息。 + * @return {void} 无返回值。 + */ + async logCallback({ appKey, event, callbackUrl, success, retryCount, response, error }) { + const { ctx } = this; + const payload = this._formatResponsePayload(response); + const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success} response=${payload}`; + + if (success) { + ctx.logger.info(logMessage); + } else if (retryCount >= MAX_RETRY) { + ctx.logger.error(`${logMessage} error=${error || '未知错误'}`); + } else { + ctx.logger.warn(`${logMessage} error=${error || '未知错误'}`); + } + } +} + +module.exports = OpenapiCallbackService; diff --git a/app/service/openapi/callbackRegistry.js b/app/service/openapi/callbackRegistry.js new file mode 100644 index 0000000..d091c35 --- /dev/null +++ b/app/service/openapi/callbackRegistry.js @@ -0,0 +1,196 @@ +'use strict'; + +/** + * OpenAPI 回调事件注册表。 + * 每个事件包含 name(事件名)、label(展示名)、description(说明)、 + * request(奇门同层级报文模板,即 request 节点的内容,不含外层 request 包装; + * 真实回调报文结构统一为 { request: {...} },字段名与嵌套层级和真实调用点完全一致)。 + * 回调调试页 GET /docs/api/openapi/callback-test 直接消费本注册表。 + */ +const CALLBACK_EVENTS = [ + { + name: 'entryorder.confirm', + label: '入库单确认完成(直入)', + description: '直入入库(API 来源)完成后回传,对应奇门 taobao.qimen.entryorder.confirm', + request: { + entryOrder: { + entryOrderCode: 'RK20260912001', + ownerCode: 'OWNER-001', + warehouseCode: 'WH-100', + entryOrderId: 543, + entryOrderType: 'SCRK', + outBizCode: 'DIRECT_INBOUND_1726131400000', + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:30:00', + remark: '导入/PDA直接入库提交', + }, + orderLines: [ + { + orderLineNo: 1, + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: '1001', + inventoryType: 'ZP', + planQty: 2, + actualQty: 2, + }, + ], + }, + }, + { + name: 'entryorder.match', + label: '入库单匹配收货完成', + description: '入库单匹配收货单完成后回传(API 来源),对应奇门 taobao.qimen.entryorder.confirm', + request: { + entryOrder: { + entryOrderCode: 'RK20260912002', + ownerCode: 'OWNER-001', + warehouseCode: 'WH-100', + entryOrderId: 543, + entryOrderType: 'SCRK', + outBizCode: 'RECEIVING_MATCH_1726131400000', + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:30:00', + remark: '匹配收货单RCV20260912001自动回传', + }, + orderLines: [ + { + orderLineNo: 1, + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: '1001', + inventoryType: 'ZP', + planQty: 2, + actualQty: 2, + }, + ], + }, + }, + { + name: 'deliveryorder.confirm', + label: '订单发货完成', + description: '订单同步(出库)完成后触发,对应奇门 taobao.qimen.deliveryorder.confirm', + request: { + deliveryOrder: { + totalOrderLines: 1, + deliveryOrderCode: 'DO20260912001', + deliveryOrderId: 123, + warehouseCode: 'WH-100', + orderType: 'JYCK', + status: 'DELIVERED', + outBizCode: 'DO20260912001', + confirmType: 0, + orderConfirmTime: '2026-09-12 10:30:00', + operatorCode: '', + operatorName: '', + storageFee: '0', + operateTime: '2026-09-12 10:30:00', + }, + packages: { + package: [ + { + logisticsCode: 'YTO', + logisticsName: '圆通速递', + expressCode: 'YT1234567890', + packageCode: 'DO20260912001', + invoiceNo: 'INV20260912001', + items: [ + { + itemCode: 'SKU-1', + itemId: 1001, + quantity: 2, + }, + ], + }, + ], + }, + orderLines: [ + { + orderLineNo: '1', + orderSourceCode: 'SO20260912001', + subSourceCode: '', + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: 1001, + itemName: '测试商品1', + extCode: '', + planQty: 2, + actualQty: 2, + retailPrice: 0, + actualPrice: 0, + discountAmount: '0', + inventoryType: 'ZP', + snList: [], + qrCode: '', + }, + ], + }, + }, + { + name: 'stockout.confirm', + label: '出库单确认完成', + description: '出库单确认回传(API 来源),对应奇门 taobao.qimen.stockout.confirm', + request: { + deliveryOrder: { + totalOrderLines: 1, + deliveryOrderCode: 'SO20260912001', + deliveryOrderId: 5001, + warehouseCode: 'WH-100', + orderType: 'PTCK', + status: 'DELIVERED', + outBizCode: 'SO20260912001', + confirmType: 0, + orderConfirmTime: '2026-09-12 10:30:00', + operatorCode: '', + operatorName: '', + }, + packages: { + package: [ + { + logisticsCode: 'YTO', + logisticsName: '圆通速递', + expressCode: 'YT1234567890', + packageCode: 'SO20260912001', + items: [ + { + itemCode: 'SKU-1', + itemId: 1001, + quantity: 2, + }, + ], + }, + ], + }, + orderLines: [ + { + orderLineNo: '1', + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: 1001, + itemName: '测试商品1', + planQty: 2, + actualQty: 2, + inventoryType: 'ZP', + }, + ], + }, + }, + { + name: 'deliveryorder.cancel', + label: '订单已取消', + description: '订单取消成功后触发(出站回调事件名 deliveryorder.cancel,与入站方法 order.cancel 区分,避免回调误路由到取消单据接口;无奇门对应接口,按 deliveryOrder 节点约定自定义)', + request: { + deliveryOrder: { + deliveryOrderCode: 'TEST-ORDER-001', + orderType: 'JYCK', + status: 'CANCELED', + }, + }, + }, +]; + +module.exports = { CALLBACK_EVENTS }; diff --git a/app/service/openapiEntry.js b/app/service/openapiEntry.js new file mode 100644 index 0000000..11f737f --- /dev/null +++ b/app/service/openapiEntry.js @@ -0,0 +1,335 @@ +'use strict'; + +const Service = require('egg').Service; + +class OpenapiService extends Service { + /** + * 解析 openapi method,拆分为服务路径与动作名。 + * @param {string} methodName method 名称。 + * @return {{ servicePath: string, actionName: string }} 解析结果。 + */ + resolveOpenapiMethod(methodName = '') { + const method = String(methodName || '').trim(); + const parts = method.split('.').filter(Boolean); + const actionName = parts.pop() || ''; + const servicePath = parts.join('.'); + + return { + servicePath, + actionName, + }; + } + + /** + * 根据服务路径查找 openapiMethods 下的目标服务。 + * @param {string} servicePath 服务路径。 + * @return {Object|null} 目标服务实例。 + */ + getOpenapiMethodService(servicePath = '') { + const { ctx } = this; + const pathSegments = String(servicePath || '').split('.').filter(Boolean); + let methodService = ctx.service.openapiMethods; + + if (pathSegments.length === 0) { + return methodService; + } + + for (const segment of pathSegments) { + methodService = methodService && methodService[segment]; + } + + return methodService || null; + } + + /** + * 解析 OpenAPI 合约信息(interface_type_id=2 必须绑定有效合约)。 + * 查询 ApiApp 并强制关联 StoreWarehouse,校验 store_id 必须存在。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 + */ + async resolveOpenapiContract(appKey) { + const { ctx, app } = this; + const normalizedAppKey = String(appKey || '').trim(); + if (!normalizedAppKey) { + throw new Error('app_key 缺失'); + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: [ + 'id', + 'warehouse_id', + 'qimen_warehouse_code', + [ app.Sequelize.col('contract.store_id'), 'store_id' ], + ], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'contract', + attributes: [], + required: true, + }, + ], + raw: true, + }); + + if (!appConfig || !appConfig.warehouse_id) { + throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); + } + + if (!appConfig.store_id) { + throw new Error(`未找到 app_key 对应的货主合约关系: ${normalizedAppKey}`); + } + + const warehouseId = appConfig.warehouse_id; + + return { + storeId: appConfig.store_id, + warehouseId, + appKey: normalizedAppKey, + customerId: null, + warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), + }; + } + + /** + * 分发 openapi method 到 openapiMethods 目录。 + * 分发前统一注入合约上下文(storeId/warehouseId/appKey 等), + * 确保所有下游方法可通过 this.getInfo() 获取货主范围信息。 + * @param {string} methodName method 名称。 + * @param {Object} body 请求体。 + * @param {Object} query 请求 query。 + * @param {Object} contractInfo 合约上下文信息。 + * @return {Promise} method 执行结果。 + */ + async dispatchOpenapiMethod(methodName, body, query, contractInfo) { + const { servicePath, actionName } = this.resolveOpenapiMethod(methodName); + const methodService = this.getOpenapiMethodService(servicePath); + + if (!methodService || typeof methodService[actionName] !== 'function') { + return { + ok: false, + httpStatus: 400, + code: 400, + message: `openapi method 不存在: ${methodName}`, + data: null, + }; + } + + // 统一注入合约上下文到方法服务实例 + if (contractInfo && typeof methodService.setInfo === 'function') { + methodService.setInfo( + contractInfo.storeId, + contractInfo.warehouseId, + contractInfo.appKey, + contractInfo.customerId, + contractInfo.warehouseCode + ); + } + + const methodResult = await methodService[actionName]({ + body, + query, + }); + + return { + ok: true, + httpStatus: 200, + code: 1, + message: 'ok', + data: methodResult, + }; + } + + /** + * 校验 openapi 基础 query 参数,仅校验 method/v/timestamp。 + * @param {Object} query 请求 query 参数。 + * @return {boolean} 是否通过基础参数校验。 + */ + validateOpenapiParams(query) { + const requiredFields = [ 'method', 'v', 'timestamp' ]; + for (const field of requiredFields) { + if (!query || !query[field]) { + return false; + } + } + + if (typeof query.method !== 'string' || !query.method.includes('.')) { + return false; + } + + return true; + } + + /** + * 读取并解析 JSON 请求体,采用 rawBody 优先策略。 + * @return {Promise} 解析后的 JSON 对象。 + */ + async parseJsonBody() { + const { ctx } = this; + let jsonData = ''; + + if (ctx.request.rawBody) { + jsonData = ctx.request.rawBody; + } else if (ctx.request.body !== undefined) { + jsonData = typeof ctx.request.body === 'string' + ? ctx.request.body + : JSON.stringify(ctx.request.body); + } else { + jsonData = await new Promise((resolve, reject) => { + let data = ''; + ctx.req.on('data', chunk => { + data += chunk; + }); + ctx.req.on('end', () => { + resolve(data); + }); + ctx.req.on('error', reject); + }); + } + + jsonData = jsonData ? String(jsonData) : ''; + if (!jsonData || jsonData.trim() === '') { + return { + ok: false, + httpStatus: 400, + code: 400, + message: 'json数据为空', + data: null, + }; + } + + try { + return JSON.parse(jsonData); + } catch (error) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: 'json数据解析错误', + data: null, + }; + } + } + + /** + * 提取并归一化 openapi 所需的 appKey 与 sign。 + * @param {Object} query 请求 query 参数。 + * @return {{ appKey: string, providedSign: string }} 归一化后的关键信息。 + */ + normalizeSignFields(query = {}) { + const appKey = String(query.app_key || query.appkey || query.self_app_key || '').trim(); + const providedSign = String(query.sign || query.signature || '').trim(); + + return { + appKey, + providedSign, + }; + } + + /** + * 处理 openapi 请求并返回统一结果。 + * @return {Promise} 统一结果对象。 + */ + async processRequest() { + const { ctx } = this; + const query = ctx.query || {}; + + if (!this.validateOpenapiParams(query)) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: '参数缺失或错误: method/v/timestamp', + data: null, + }; + } + + // 时间戳时效校验(±10分钟) + const nowTs = Math.floor(Date.now() / 1000); + const reqTs = Number(query.timestamp); + if (!Number.isFinite(reqTs) || Math.abs(nowTs - reqTs) > 600) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: `时间戳已过期或无效,服务器时间: ${nowTs}`, + data: null, + }; + } + + const body = await this.parseJsonBody(); + if (body && body.ok === false) { + return body; + } + + const { appKey, providedSign } = this.normalizeSignFields(query); + if (!appKey) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: '参数缺失或错误: app_key', + data: null, + }; + } + + const { systems: systemsService } = ctx.service; + const apiSignService = systemsService.apiSign; + let appConfig; + try { + appConfig = await apiSignService.getApiAppSecretByAppKey(appKey); + } catch (error) { + return { + ok: false, + httpStatus: 401, + code: 401, + message: `app_key 校验失败: ${error.message}`, + data: null, + }; + } + + const verifyResult = await apiSignService.verifyRequestSignByAppKey({ + appKey, + query, + body, + providedSign, + }); + + if (!verifyResult.ok) { + return { + ok: false, + httpStatus: 401, + code: 401, + message: `签名校验失败: ${verifyResult.message}`, + data: null, + }; + } + + // interface_type_id=2(OPENAPI)必须解析合约并注入货主信息 + let contractInfo = null; + try { + contractInfo = await this.resolveOpenapiContract(appKey); + } catch (error) { + return { + ok: false, + httpStatus: 403, + code: 403, + message: `合约校验失败: ${error.message}`, + data: null, + }; + } + + const queryWithAppKey = { + ...query, + app_key: appConfig.appKey, + }; + + return await this.dispatchOpenapiMethod(query.method, body, queryWithAppKey, contractInfo); + } +} + +module.exports = OpenapiService; diff --git a/app/service/openapiMethods/callback.js b/app/service/openapiMethods/callback.js new file mode 100644 index 0000000..40bc8ab --- /dev/null +++ b/app/service/openapiMethods/callback.js @@ -0,0 +1,77 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 回调测试方法服务。 + * 提供模拟发送回调通知的能力,用于测试回调链路是否正常。 + */ +class OpenapiCallbackMethodService extends MainService { + + /** + * 通过 app_key 解析应用信息。 + * 查询 ApiApp 表校验 app_key 有效性。 + * @param {string} appKey 开放接口 app_key。 + * @return {Promise} 包含 appKey 的信息对象。 + */ + async resolveAppInfo(appKey) { + const { ctx } = this; + const normalizedAppKey = String(appKey || '').trim(); + + if (!normalizedAppKey) { + throw new Error('app_key 缺失'); + } + + const appConfig = await ctx.model.ApiApp.findOne({ + attributes: [ 'self_app_key' ], + where: { + self_app_key: normalizedAppKey, + is_enabled: 1, + }, + raw: true, + }); + + if (!appConfig) { + throw new Error(`无法找到应用,请检查 app_key: ${normalizedAppKey}`); + } + + return { + appKey: normalizedAppKey, + }; + } + + /** + * 模拟发送回调通知(测试用)。 + * 通过 app_key 查找回调配置并发送一次回调请求。 + * @param {Object} [payload={}] 调用参数。 + * @param {Object} [payload.body={}] 请求体数据,可指定 event 与 request(奇门同层级业务报文,不含外层 request 包装)。 + * @param {Object} [payload.query={}] 请求 query 数据,需包含 app_key。 + * @return {Promise} 回调测试结果。 + */ + async test(payload = {}) { + const { body = {}, query = {} } = payload; + const { event = 'deliveryorder.confirm', request = {} } = body; + + try { + const info = await this.resolveAppInfo(query.app_key); + const result = await this.ctx.service.openapi.callback.sendByAppKey({ + appKey: info.appKey, + event, + request, + }); + + if (result.success) { + return this.success('回调测试成功', { retryCount: result.retryCount }); + } + + return this.fail('回调测试失败', { + error: result.error, + retryCount: result.retryCount, + }); + } catch (error) { + return this.fail(`回调测试异常: ${error.message}`); + } + } +} + +module.exports = OpenapiCallbackMethodService; diff --git a/app/service/openapiMethods/deliveryorder.js b/app/service/openapiMethods/deliveryorder.js new file mode 100644 index 0000000..e131e24 --- /dev/null +++ b/app/service/openapiMethods/deliveryorder.js @@ -0,0 +1,116 @@ +'use strict'; + +const MainService = require('../main'); + +const { findOrderByCodeAcrossTables } = require('../../lib/order_lookup'); + +class OpenapiDeliveryorderService extends MainService { + /** + * 查询发货单。 + * 上下文(storeId/warehouseId/appKey)已由 dispatchOpenapiMethod 统一注入。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 deliveryOrderCode。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 查询结果,成功时返回订单详情,失败时返回错误信息。 + */ + async query(payload = {}) { + const { body = {} } = payload; + const { deliveryOrderCode } = body; + + if (!deliveryOrderCode) { + return this.fail('deliveryOrderCode 参数缺失'); + } + + try { + const { storeId, warehouseId } = this.getInfo(); + // 跨表查找:订单可能已流转到 dispatch/history/outsourced,仅查 current 会误报未找到 + const { order } = await findOrderByCodeAcrossTables(this.ctx, warehouseId, { + delivery_order_code: deliveryOrderCode, + store_id: storeId, + }); + + if (order) { + return this.success('成功', { + totalLines: 0, + deliveryOrder: { + deliveryOrderCode: order.delivery_order_code, + deliveryOrderId: order.delivery_order_code, + warehouseCode: order.warehouse_code, + orderType: order.order_type, + status: order.status, + orderConfirmTime: order.order_confirm_time, + operatorCode: 0, + operatorName: '', + operateTime: order.update_at, + }, + packages: { + package: {}, + }, + orderLines: [], + }); + } + + return this.fail('未找到订单'); + } catch (error) { + return this.fail(`查询失败: ${error.message}`); + } + } + + /** + * 创建发货单。 + * 上下文(storeId/warehouseId/appKey)已由 dispatchOpenapiMethod 统一注入。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 deliveryOrder 与 orderLines。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 创建结果,成功时返回订单ID等,失败时返回错误信息。 + */ + async create(payload = {}) { + const { body = {} } = payload; + const { + deliveryOrder, + orderLines, + need_oms_waybill: needOmsWaybillSnake, + needOmsWaybill, + } = body; + + if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { + return this.fail('deliveryOrder 参数缺失或不完整'); + } + if (!orderLines) { + return this.fail('orderLines 参数缺失'); + } + + try { + // need_oms_waybill 在请求根节点传入(不在 deliveryOrder 内), + // 兼容 snake_case / camelCase 两种写法,仅 openapi(API) 来源会落库生效。 + const data = { + request: { + deliveryOrder, + orderLines, + need_oms_waybill: needOmsWaybillSnake ?? needOmsWaybill, + }, + }; + + const res = await this.ctx.service.systems.deliveryOrder.addOrder( + data, + this.getInfo(), + 'API' + ); + + if (res.success) { + return this.success(res.message, { + createTime: this.app.formatDate(new Date()), + deliveryOrderId: res.data.orderId, + warehouseCode: this.warehouseCode, + logisticsCode: '', + }); + } + + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); + } catch (error) { + return this.fail(`创建失败: ${error.message}`); + } + } +} + +module.exports = OpenapiDeliveryorderService; diff --git a/app/service/openapiMethods/entryorder.js b/app/service/openapiMethods/entryorder.js new file mode 100644 index 0000000..695658e --- /dev/null +++ b/app/service/openapiMethods/entryorder.js @@ -0,0 +1,156 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 入库单服务。 + * 对外提供入库单的创建与查询能力,通过 openapi 通道对接外部系统。 + */ +class OpenapiEntryorderService extends MainService { + + /** + * 创建入库单。 + * 上下文(storeId/warehouseId/appKey/warehouseCode)已由 dispatchOpenapiMethod 统一注入。 + * 接收外部系统的入库单数据,校验后通过底层 entryOrder 服务完成入库单创建。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,包含 entryOrder(入库单信息)和 orderLines(明细行)。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 创建结果,成功时返回 entryOrderId、entryOrderCode、status 和 createTime。 + */ + async create(payload = {}) { + const { body = {} } = payload; + const { entryOrder, orderLines } = body; + + if (!entryOrder || !entryOrder.entryOrderCode) { + return this.fail('entryOrder.entryOrderCode 参数缺失'); + } + + if (!orderLines || !orderLines.orderLine) { + return this.fail('orderLines.orderLine 参数缺失'); + } + + // 字段映射:OpenAPI 风格字段名 → 底层 tryCreateEntryOrder 期望的字段名 + // 注意(2026-09-14):以下字段当前未被底层消费,保留仅为兼容调用方,勿据此判断生效: + // - warehouseCode:仓库上下文一律以 app_key 合约解析结果为准,报文值被忽略 + // - operateTime / operatorName:底层既不落库也不参与任何逻辑 + // 另:ownerCode 不通过本映射生效,由下方显式作为 customerId 传入(落 qimen_owner_code) + const mappedEntryOrder = { + entryOrderCode: entryOrder.entryOrderCode, + orderType: entryOrder.entryOrderType || entryOrder.orderType || 'SCRK', + expectStartTime: entryOrder.expectedArriveTime || entryOrder.expectStartTime || '', + expectEndTime: entryOrder.expectEndTime || '', + supplierCode: entryOrder.supplierCode || '', + supplierName: entryOrder.supplierName || '', + warehouseCode: entryOrder.warehouseCode || '', + ownerCode: entryOrder.ownerCode || '', + remark: entryOrder.remark || '', + totalOrderLines: entryOrder.totalOrderLines || 0, + operateTime: entryOrder.operateTime || '', + operatorName: entryOrder.operatorName || '', + orderCreateTime: entryOrder.orderCreateTime || entryOrder.createTime || '', + logisticsCode: entryOrder.logisticsCode || '', + logisticsName: entryOrder.logisticsName || '', + expressCode: entryOrder.expressCode || '', + relatedOrders: entryOrder.relatedOrders || undefined, + }; + + try { + const data = { + request: { + entryOrder: mappedEntryOrder, + orderLines, + }, + }; + + // 货主编码对齐奇门口径:奇门侧 qimen_owner_code 取自请求上下文 customerId + // (出站回传 entryorder.confirm 的 ownerCode 即取该列,见 buildEntryOrderConfirmRequest)。 + // OpenAPI 合约上下文的 customerId 恒为 null,会导致 API 来源入库单 qimen_owner_code 为空、 + // 回传 ownerCode 为空,故此处用报文 entryOrder.ownerCode 补齐(与奇门落库口径一致)。 + const info = this.getInfo(); + const ownerCode = String(entryOrder.ownerCode || '').trim(); + + const res = await this.ctx.service.systems.entryOrder.addOrder( + data, + { ...info, customerId: ownerCode || info.customerId || '' }, + 'API' + ); + + if (res.success) { + return this.success(res.message, { + createTime: this.app.formatDate(new Date()), + entryOrderId: res.data.entryOrderId, + entryOrderCode: res.data.entryOrderCode, + status: res.data.status, + }); + } + + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); + } catch (error) { + return this.fail(`创建入库单失败: ${error.message}`); + } + } + + /** + * 查询入库单。 + * 上下文(storeId/warehouseId)已由 dispatchOpenapiMethod 统一注入。 + * 根据入库单号查询入库单详情,包括基本信息与商品明细。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 entryOrderCode(入库单号)。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 查询结果,成功时返回入库单详情。 + */ + async query(payload = {}) { + const { body = {} } = payload; + const { entryOrderCode } = body; + + if (!entryOrderCode) { + return this.fail('entryOrderCode 参数缺失'); + } + + try { + const { storeId, warehouseId, warehouseCode } = this.getInfo(); + const order = await this.ctx.service.systems.entryOrder.findByOrderCode( + entryOrderCode, + warehouseId, + storeId + ); + + if (!order) { + return this.fail('未找到入库单'); + } + + const orderLines = (order.items || []).map(item => ({ + itemId: item.stock_id, + itemCode: (item.stock && item.stock.item_code) || '', + itemName: (item.stock && item.stock.item_name) || '', + planQty: item.count, + actualQty: item.actual_qty || 0, + inventoryType: item.inventory_type || 'ZP', + orderLineNo: item.order_line_no || '', + remark: item.remark || '', + })); + + return this.success('查询成功', { + entryOrderCode: order.entry_order_code, + entryOrderId: order.id, + status: order.order_status, + entryOrderType: order.order_type || 'SCRK', + expectedArriveTime: order.expected_arrive_time || '', + supplierCode: order.supplier_code || '', + supplierName: order.supplier_name || '', + remark: order.remark || '', + createTime: order.created_at || '', + operateTime: order.updated_at || '', + operatorName: order.operator_name || '', + warehouseCode: order.warehouse_code || warehouseCode, + ownerCode: order.store_code || '', + totalOrderLines: order.total_order_lines || 0, + orderLines, + }); + } catch (error) { + return this.fail(`查询入库单失败: ${error.message}`); + } + } +} + +module.exports = OpenapiEntryorderService; diff --git a/app/service/openapiMethods/index.js b/app/service/openapiMethods/index.js new file mode 100644 index 0000000..21f02ff --- /dev/null +++ b/app/service/openapiMethods/index.js @@ -0,0 +1,35 @@ +'use strict'; + +const Service = require('egg').Service; + +class OpenapiMethodsIndexService extends Service { + /** + * openapi index.ping 健康探活方法。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 探活结果。 + */ + async ping(payload = {}) { + const { query = {} } = payload; + return { + pong: true, + method: query.method || 'index.ping', + }; + } + + /** + * openapiMethods 入口健康检查。 + * @param {Object} payload 调用参数。 + * @return {Promise} 健康检查结果。 + */ + async health(payload = {}) { + const { query = {} } = payload; + return { + module: 'openapiMethods', + status: 'ok', + method: query.method || '', + }; + } +} + +module.exports = OpenapiMethodsIndexService; diff --git a/app/service/openapiMethods/inventory.js b/app/service/openapiMethods/inventory.js new file mode 100644 index 0000000..b841741 --- /dev/null +++ b/app/service/openapiMethods/inventory.js @@ -0,0 +1,57 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 库存服务。 + * 提供库存查询能力,映射到 StockStore 底层模型。 + */ +class OpenapiInventoryService extends MainService { + + /** + * 库存查询。 + * 上下文(storeId)已由 dispatchOpenapiMethod 统一注入,查询结果按货主范围校验。 + * 根据商品 ID 列表查询对应的库存信息,包括总库存、锁定量和可用量。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 itemIds(商品 ID 数组)。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 查询结果,成功时返回 items 数组。 + */ + async query(payload = {}) { + const { body = {} } = payload; + const { itemIds } = body; + + if (!Array.isArray(itemIds) || itemIds.length === 0) { + return this.fail('itemIds 参数缺失或为空'); + } + + const { storeId } = this.getInfo(); + const items = []; + + for (const itemId of itemIds) { + const result = await this.ctx.service.systems.stockStore.getItemStorages(itemId); + if (result.success && result.data) { + // 按货主范围过滤:仅返回属于当前合约货主的库存 + if (Number(result.data.storage.storeId) !== Number(storeId)) { + continue; + } + items.push({ + itemId: result.data.stock.id, + itemCode: result.data.stock.item_code, + warehouseCode: result.data.stock.warehouse_code, + quantity: result.data.storage.quantity, + lockQuantity: result.data.storage.lockedQuantity, + inventoryType: 'ZP', + }); + } + } + + if (items.length === 0) { + return this.fail('未查询到有效库存信息'); + } + + return this.success('库存查询成功', { items }); + } +} + +module.exports = OpenapiInventoryService; diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js new file mode 100644 index 0000000..c02f399 --- /dev/null +++ b/app/service/openapiMethods/order.js @@ -0,0 +1,495 @@ +'use strict'; + +const MainService = require('../main'); + +const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfo } = require('../../lib/intercept_guard'); +const { buildNoticeTimePatch } = require('../../lib/intercept_time'); +const { preloadOrderModels, findOrderAcrossTables } = require('../../lib/order_lookup'); + +class OpenapiOrderService extends MainService { + /** + * 取消发货单。 + * 上下文(storeId/warehouseId/appKey)已由 dispatchOpenapiMethod 统一注入。 + * 支持类型: + * - 出库单类型(JYCK/HHCK/BFCK → ORDER):操作 wms_order_delivery 主表, + * 触发拦截时同步写入订单拦截时间 intercept_time(当前时间); + * - CK 组出库单(PTCK/DBCK/B2BCK/QTCK/CGTH):走独立出库单表 wms_order_stockout 取消, + * 取消成功后不需要向开放平台回传任何事件; + * - RK 组入库单(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):走入库单作废流程(状态守卫、 + * 回退收货单占用),取消成功后不需要向开放平台回传任何事件。 + * 其余类型返回不支持。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,包含 orderCode、orderType。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 取消结果,成功时返回成功消息,失败时返回错误信息。 + */ + async cancel(payload = {}) { + const { ctx } = this; + const { body = {}, query = {} } = payload; + const { orderCode } = body; + const orderType = String(body.orderType || 'JYCK').trim().toUpperCase(); + + // 出库单类型映射:JYCK / HHCK / BFCK → ORDER(wms_order_delivery 取消流程) + const ORDER_TYPES = [ 'JYCK', 'HHCK', 'BFCK' ]; + // CK 组出库单:走独立出库单表 wms_order_stockout 取消流程 + const CK_TYPES = [ 'PTCK', 'DBCK', 'B2BCK', 'QTCK', 'CGTH' ]; + // RK 组入库单:走入库单作废流程(与奇门 orderType 枚举 method=RK 完全一致) + const RK_TYPES = [ 'B2BRK', 'SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK' ]; + if (!ORDER_TYPES.includes(orderType) && !CK_TYPES.includes(orderType) && !RK_TYPES.includes(orderType)) { + return this.fail('暂不支持该订单类型的取消操作'); + } + + const normalizedOrderCode = String(orderCode || '').trim(); + if (!normalizedOrderCode) { + return this.fail('orderCode 参数缺失'); + } + + // CK 组:委托共享出库单取消实现,取消成功后不回传任何开放平台事件 + if (CK_TYPES.includes(orderType)) { + const info = this.getInfo(); + return ctx.service.systems.stockoutOrder.cancel( + { stockoutOrderCode: normalizedOrderCode }, + { + storeId: info.storeId, + warehouseId: info.warehouseId, + operatorLabel: String(info.appKey || '').trim() + ? `openapi:${String(info.appKey).trim()}` + : 'openapi', + } + ); + } + + // RK 组:委托共享入库单作废实现(守卫 + 回退收货单占用 + 操作日志), + // 取消成功后不回传任何开放平台事件;已作废按幂等成功处理 + if (RK_TYPES.includes(orderType)) { + const info = this.getInfo(); + const result = await ctx.service.systems.storage.entry.cancel( + { entryOrderCode: normalizedOrderCode }, + { + storeId: info.storeId, + warehouseId: info.warehouseId, + operatorLabel: String(info.appKey || '').trim() + ? `openapi:${String(info.appKey).trim()}` + : 'openapi', + skipExternalSync: true, + idempotent: true, + notFoundMessage: '未找到对应的入库单', + } + ); + + if (result.code === 200) { + return this.success('取消入库单成功'); + } + return this.fail(result.message || '取消入库单失败'); + } + + try { + const { storeId, warehouseId, appKey: ctxAppKey } = this.getInfo(); + + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + // 模型预取必须在事务外(首次获取可能执行 DDL 隐式提交) + const orderModels = await preloadOrderModels(ctx, warehouseId); + const transaction = await ctx.model.transaction(); + try { + // 跨表查找:current → dispatch → history → outsourced,命中即停 + const { order: existingOrder, location: existingLocation } = await findOrderAcrossTables(orderModels, { + delivery_order_code: normalizedOrderCode, + warehouse_id: warehouseId, + store_id: storeId, + }, { + findOptions: { + transaction, + lock: transaction.LOCK.UPDATE, + }, + }); + + if (!existingOrder) { + await transaction.rollback(); + return this.fail('未找到对应的订单'); + } + + // 订单已流转出 current(dispatch/history/outsourced): + // 仅当已取消时视为取消成功(幂等),否则无法在待出库表中取消 + if (existingLocation !== 'current') { + if (String(existingOrder.status || '').trim() === 'cancel') { + await transaction.rollback(); + return this.success('取消订单成功'); + } + 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') { + // 拦截前置校验:团购单已复核 / 散单已称重后不允许写入拦截请求状态 + const guardInfo = await resolveInterceptRequestGuardInfo(ctx, { + orderId: existingOrder.id, + waveId: existingOrder.wave_id, + warehouseId, + transaction, + }); + const blockReason = getInterceptRequestBlockReason({ + waveType: guardInfo.waveType, + inspectionStatus: String(existingOrder.inspection_status || '').trim(), + weighingWeight: guardInfo.weighingWeight, + }); + + if (!blockReason) { + // 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值) + const noticeNow = new Date(); + await existingOrder.update({ + intercept_status: 'intercepting', + ...buildNoticeTimePatch(existingOrder.intercept_time, noticeNow), + updated_at: noticeNow, + }, { + transaction, + }); + + // 同步更新运单表拦截标记 + try { + const { ctx: ctxExpress } = this; + const expressWarehouseId = ctxExpress.user && ctxExpress.user.store_id ? Number(ctxExpress.user.store_id) : 0; + if (expressWarehouseId > 0) { + await ctxExpress.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: existingOrder.id, warehouse_id: expressWarehouseId }, transaction } + ); + } + } catch (expressErr) { + this.ctx.logger.warn( + `[openapi order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}` + ); + } + } else { + this.ctx.logger.info( + `[openapi order cancel] 订单${blockReason},跳过写入拦截请求状态, orderId=${existingOrder.id}` + ); + } + + await transaction.commit(); + + // 写入拦截操作日志(失败不影响主流程;未写入拦截请求状态时不记录) + if (!blockReason) { + try { + const { ctx: ctx2 } = this; + if (ctx2.model && ctx2.model.OperationLog) { + const whId2 = ctx2.user && ctx2.user.store_id ? Number(ctx2.user.store_id) : 0; + await ctx2.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_INTERCEPT_REQUEST', + operator_id: ctx2.user?.employees_id || ctx2.user?.id || null, + operator_name: ctx2.user?.employees_name || 'OpenAPI', + external_log_type: 'NONE', + warehouse_id: whId2 || null, + platform_code: 'OPENAPI', + message: 'OpenAPI取消订单-触发拦截', + }); + } + } catch (logErr) { + this.ctx.logger.warn('[OpenAPIOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr); + } + } + + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + const { ctx: ctxWorkOrder } = this; + const whId = ctxWorkOrder.user && ctxWorkOrder.user.store_id ? Number(ctxWorkOrder.user.store_id) : 0; + if (whId > 0) { + await ctxWorkOrder.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: whId, + creatorLabel: ctxWorkOrder.user?.employees_name || 'OpenAPI系统', + }); + } + } catch (workOrderErr) { + this.ctx.logger.warn( + `[openapi order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}` + ); + } + + return this.fail(blockReason + ? `订单${blockReason},无法拦截执行,已转快递拦截` + : '取消失败,已通知拦截执行'); + } + + // 检查是否在波次中,若在波次中需清除波次关联 + const existingWaveId = Number(existingOrder.wave_id || 0); + + const updateValues = { + status: 'cancel', + outbound_status: 'fin', + step: 4, + updated_at: new Date(), + }; + if (existingWaveId > 0) { + updateValues.wave_id = 0; + updateValues.wave_no = ''; + } + + await existingOrder.update(updateValues, { + transaction, + }); + + // 波次清理:删除波次索引、重建波次索引、更新波次统计 + if (existingWaveId > 0) { + await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: [ existingOrder.id ], + transaction, + }); + + await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: [ existingWaveId ], + orderModel: DeliveryModel, + transaction, + }); + + const WaveBatch = ctx.model.WaveBatch; + if (WaveBatch) { + const wave = await WaveBatch.findOne({ + where: { wave_id: existingWaveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'total_orders', 'wave_status' ], + raw: true, + transaction, + }); + + if (wave) { + const totalOrders = Number(wave.total_orders); + const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0; + if (normalizedTotalOrders <= 0) { + await WaveBatch.update( + { total_orders: 0, wave_status: -1, update_time: new Date() }, + { where: { wave_id: existingWaveId, warehouse_id: warehouseId }, transaction } + ); + } + } + } + } + + // 释放储位分配锁定库存 + await this.releaseStockLockForCancel({ + orderId: existingOrder.id, + warehouseId, + transaction, + }); + + await transaction.commit(); + + // 写入取消操作日志(不影响主流程) + try { + if (this.ctx.model && this.ctx.model.OperationLog) { + const appKey = String(query.app_key || ctxAppKey || '').trim(); + await this.ctx.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_CANCEL', + operator_id: null, + operator_name: appKey ? `openapi:${appKey}` : 'openapi', + external_log_type: 'NONE', + warehouse_id: warehouseId || null, + platform_code: appKey || 'SYSTEM', + message: 'OpenAPI 取消订单', + }); + } + } catch (logErr) { + this.ctx.logger.warn('[OpenapiOrderCancel] 写入取消操作日志失败,不影响主流程', logErr); + } + + // 取消成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程) + try { + const callbackService = this.ctx.service.openapi && this.ctx.service.openapi.callback; + if (callbackService && typeof callbackService.sendByAppKey === 'function') { + const appKey = String(query.app_key || ctxAppKey || '').trim(); + if (appKey) { + // 出站回调事件名 deliveryorder.cancel:与入站方法 order.cancel 区分, + // 避免 callback_url 误指向 /openapi 时被路由到取消单据接口 + // 报文对齐奇门 request 层级:deliveryOrder 节点约定(无奇门对应接口, + // status 使用 CANCELED 与奇门 deliveryOrder.status 家族枚举风格一致) + callbackService.sendByAppKey({ + appKey, + event: 'deliveryorder.cancel', + request: { + deliveryOrder: { + deliveryOrderCode: normalizedOrderCode, + orderType, + status: 'CANCELED', + }, + }, + }).catch(err => { + this.ctx.logger.warn('[OpenapiOrderCancel] 回调忽略失败: %s', err.message); + }); + } + } + } catch (err) { + this.ctx.logger.warn('[OpenapiOrderCancel] 触发回调异常,不影响主流程: %s', err.message); + } + + return this.success('取消订单成功'); + } catch (error) { + try { + await transaction.rollback(); + } catch (rollbackError) { + ctx.logger.error(`取消订单回滚失败: ${rollbackError.message}`); + } + ctx.logger.error(`取消订单失败: ${error.message}`); + return this.fail(error.message || '取消订单失败'); + } + } catch (error) { + return this.fail(`取消订单失败: ${error.message}`); + } + } + + /** + * 取消订单时释放储位分配锁定库存。 + * - 有 wms_picking 记录时:释放 wms_storage.locked_quantity 与 wms_stock_warehouse.locked_quantity, + * 并删除对应的 wms_picking 分配记录。 + * - 无 wms_picking 记录时:从 wms_order_items 查询该订单的 stock_id 与 plan_qty, + * 只释放 wms_stock_warehouse.locked_quantity。 + * + * @param {Object} options - 释放参数。 + * @param {number} options.orderId - 订单ID。 + * @param {number} options.warehouseId - 仓库ID。 + * @param {Object} options.transaction - 数据库事务对象。 + * @return {Promise} + */ + async releaseStockLockForCancel({ orderId, warehouseId, transaction } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!orderId || !warehouseId) { + return; + } + + const pickingModel = ctx.model.Picking; + const storageModel = ctx.model.Storage; + const stockModel = ctx.model.StockWarehouse; + + if (!pickingModel || !storageModel || !stockModel) { + ctx.logger.warn('[openapi order.cancel releaseStockLockForCancel] 模型不可用,跳过库存释放'); + return; + } + + // 查找该订单的有效分配记录 + const pickingRows = await pickingModel.findAll({ + where: { + order_id: orderId, + status: { [Op.ne]: 'cancel' }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + if (!Array.isArray(pickingRows) || pickingRows.length === 0) { + // 无储位分配记录:从订单明细获取锁定信息,只释放 stock_warehouse 锁 + const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (!orderItemsModel) { + ctx.logger.warn('[openapi order.cancel releaseStockLockForCancel] OrderItems 模型不可用,跳过库存释放'); + return; + } + + const orderItems = await orderItemsModel.findAll({ + where: { order_id: orderId }, + attributes: [ 'stock_id', 'plan_qty' ], + raw: true, + transaction, + }); + + for (const item of orderItems) { + const stockId = Number(item.stock_id || 0); + const qty = Number(item.plan_qty || 0); + if (stockId <= 0 || qty <= 0) continue; + + await ctx.service.systems.stockStore.updateLockedQuantity(stockId, -qty, transaction, { + remark: 'OpenAPI取消订单-释放创建锁', + orderType: 'ORDER_CANCEL', + orderNo: String(orderId), + orderId, + }); + } + return; + } + + // 按 storage_id 汇总释放数量 + const storageQuantityMap = new Map(); + for (const row of pickingRows) { + const storageId = Number(row.storage_id || 0); + const quantity = Number(row.quantity || 0); + if (storageId > 0 && quantity > 0) { + storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity); + } + } + + if (storageQuantityMap.size === 0) { + return; + } + + // 查出关联的 wms_storage 记录,获取 stock_id + const storageIds = Array.from(storageQuantityMap.keys()); + const storageRows = await storageModel.findAll({ + where: { + id: { [Op.in]: storageIds }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const storageMap = new Map(); + for (const row of storageRows) { + storageMap.set(Number(row.id), row); + } + + // 依次释放 wms_storage 与 wms_stock_warehouse 锁定数量 + for (const [ storageId, quantity ] of storageQuantityMap.entries()) { + const storageRow = storageMap.get(storageId); + if (!storageRow) { + ctx.logger.warn(`[openapi order.cancel] 库存记录不存在,跳过: storageId=${storageId}`); + continue; + } + + const stockId = Number(storageRow.stock_id || 0); + if (stockId <= 0) { + ctx.logger.warn(`[openapi order.cancel] 库存记录缺少 stock_id,跳过: storageId=${storageId}`); + continue; + } + + // 释放 wms_storage.locked_quantity + await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); + + // 释放 wms_stock_warehouse.locked_quantity + const releaseResult = await ctx.service.systems.stockStore.updateLockedQuantity( + stockId, -Number(quantity), transaction, { + remark: 'OpenAPI取消订单-释放储位锁', + orderType: 'ORDER_CANCEL', + orderNo: String(orderId), + orderId, + } + ); + + if (!releaseResult.success) { + throw new Error(`库存主记录释放失败: stockId=${stockId}, ${releaseResult.error}`); + } + } + + // 删除已释放的分配记录 + const pickingIds = pickingRows + .map(row => Number(row.id || 0)) + .filter(id => id > 0); + + if (pickingIds.length > 0) { + await pickingModel.destroy({ + where: { + id: { [Op.in]: pickingIds }, + }, + transaction, + }); + } + } +} + +module.exports = OpenapiOrderService; diff --git a/app/service/openapiMethods/ping.js b/app/service/openapiMethods/ping.js new file mode 100644 index 0000000..c1903d6 --- /dev/null +++ b/app/service/openapiMethods/ping.js @@ -0,0 +1,23 @@ +'use strict'; + +const Service = require('egg').Service; + +class OpenapiMethodsPingService extends Service { + /** + * openapi ping 示例方法,回显请求体。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 回显结果。 + */ + async echo(payload = {}) { + const { body = {}, query = {} } = payload; + return { + pong: true, + method: query.method || '', + body, + }; + } +} + +module.exports = OpenapiMethodsPingService; diff --git a/app/service/openapiMethods/singleitem.js b/app/service/openapiMethods/singleitem.js new file mode 100644 index 0000000..3fb2c87 --- /dev/null +++ b/app/service/openapiMethods/singleitem.js @@ -0,0 +1,90 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * OpenAPI 单品服务。 + * 提供商品(单品)的同步与查询能力,映射到 StockStore 底层模型。 + */ +class OpenapiSingleitemService extends MainService { + + /** + * 同步(新增或更新)单品信息。 + * 上下文(storeId/warehouseId/appKey/warehouseCode)已由 dispatchOpenapiMethod 统一注入。 + * 将外部系统的商品数据写入 StockStore,并自动同步到库存表。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,仅需包含 item;warehouseCode 和 ownerCode 由 app_key 自动解析,调用方不得传入。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 同步结果,成功时返回 itemId。 + */ + async synchronize(payload = {}) { + const { body = {} } = payload; + const { item } = body; + + if (!item || !item.itemCode) { + return this.fail('item 参数缺失或不完整(缺少 itemCode)'); + } + + try { + const { storeId, warehouseId, appKey, warehouseCode } = this.getInfo(); + const ownerCode = storeId ? String(storeId) : ''; + + const requestData = { + warehouseCode: warehouseCode || '', + ownerCode: ownerCode || '', + item, + }; + + const stockData = await this.ctx.service.systems.stockStore.initQimenStockData( + requestData, + appKey, + storeId, + warehouseId + ); + + const result = await this.ctx.service.systems.stockStore.create(stockData); + return this.success('同步完成', { itemId: result.id }); + } catch (error) { + return this.fail(`同步失败: ${error.message}`); + } + } + + /** + * 查询单品详情。 + * 上下文(storeId)已由 dispatchOpenapiMethod 统一注入,查询按货主范围过滤。 + * 根据 itemId 查询 StockStore 记录并转换为 OpenAPI 统一格式。 + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 itemId。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 查询结果,成功时返回商品详情。 + */ + async query(payload = {}) { + const { body = {} } = payload; + const { itemId } = body; + + if (!itemId) { + return this.fail('itemId 参数缺失'); + } + + try { + const { storeId } = this.getInfo(); + + const row = await this.ctx.model.StockStore.findOne({ + where: { + id: itemId, + store_id: storeId, + }, + }); + if (!row) { + return this.fail(`商品不存在,itemId: ${itemId}`); + } + + const result = await this.ctx.service.systems.stockStore.convertToQimenFormat(row); + return this.success('查询成功', result); + } catch (error) { + return this.fail(`查询失败: ${error.message}`); + } + } +} + +module.exports = OpenapiSingleitemService; diff --git a/app/service/openapiMethods/stockout.js b/app/service/openapiMethods/stockout.js new file mode 100644 index 0000000..79fbb9d --- /dev/null +++ b/app/service/openapiMethods/stockout.js @@ -0,0 +1,89 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 开放 API 出库单适配层。 + * + * 处理 openapi stockout.create / stockout.query,业务逻辑统一委托到 + * `app/service/systems/stockout_order.js`(ctx.service.systems.stockoutOrder), + * 与 qimenMethods/stockout.js 共用同一份实现。 + * + * 与奇门的差异: + * - 入参为开放 API 扁平结构(body.deliveryOrder / body.orderLines / body.deliveryOrderCode), + * 不像奇门那样包一层 request 节点; + * - 落库 source_type=API,出库单回传走 OpenAPI 回调(event=stockout.confirm); + * - 上下文(storeId/warehouseId/warehouseCode)由 openapiEntry 合约解析后注入。 + */ +class OpenapiStockoutService extends MainService { + + /** + * 创建出库单。 + * + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 deliveryOrder 与 orderLines。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 创建结果,成功时返回 stockoutOrderId/stockoutOrderCode,失败返回错误信息。 + */ + async create(payload = {}) { + const { body = {} } = payload; + const { deliveryOrder, orderLines } = body; + + if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { + return this.fail('deliveryOrder 参数缺失或不完整'); + } + if (!orderLines) { + return this.fail('orderLines 参数缺失'); + } + + const info = this.getInfo(); + + return this.ctx.service.systems.stockoutOrder.create( + { + request: { + deliveryOrder, + orderLines, + }, + }, + { + storeId: info.storeId, + warehouseId: info.warehouseId, + warehouseCode: info.warehouseCode, + appKey: info.appKey, + sourceType: 'API', + } + ); + } + + /** + * 查询出库单。 + * + * @param {Object} payload 调用参数。 + * @param {Object} payload.body 请求体数据,需包含 deliveryOrderCode(兼容 deliveryOrder.deliveryOrderCode)。 + * @param {Object} payload.query 请求 query 数据。 + * @return {Promise} 查询结果,成功返回出库单详情,失败返回错误信息。 + */ + async query(payload = {}) { + const { body = {} } = payload; + const deliveryOrderCode = String( + body.deliveryOrderCode + || (body.deliveryOrder && body.deliveryOrder.deliveryOrderCode) + || '' + ).trim(); + + if (!deliveryOrderCode) { + return this.fail('deliveryOrderCode 参数缺失'); + } + + return this.ctx.service.systems.stockoutOrder.query({ + request: { + deliveryOrder: { + deliveryOrderCode, + }, + }, + }); + } + +} + +module.exports = OpenapiStockoutService; diff --git a/app/service/pda.js b/app/service/pda.js index de8f355..4752fd8 100644 --- a/app/service/pda.js +++ b/app/service/pda.js @@ -1,7 +1,8 @@ 'use strict'; const Service = require('egg').Service; -const { XMLParser } = require('fast-xml-parser'); + +const apiLogSink = require('../lib/api_log_sink'); class pdaService extends Service { async callMethod(className, actionName, requestData, authHeader) { @@ -31,9 +32,8 @@ class pdaService extends Service { // 调用方法 const authPass = await serviceInstance.checkAuth(servicePath, actionName, authHeader); const isLog = authPass.isLog; - if (authPass.status == 200) { + if (authPass.status === 200) { result.data = await serviceInstance[actionName](requestData); - console.log(result.data); result.status = 200; } else { @@ -62,41 +62,30 @@ class pdaService extends Service { return true; } + + /** + * 保存接口日志。 + * + * 经 Egg logger(apiLog)平铺写出到日志文件;wms_system_log 表已下线,不再有任何入库路径。 + * + * @param {Object} logData 日志数据 + * @param {number} startTime 开始时间戳 + * @return {Promise} 写出的平铺记录 + */ async saveLog(logData, startTime) { const { ctx, } = this; try { - // 限制日志内容长度 - if (logData.body && logData.body.length > 65535) { - logData.body = logData.body.substring(0, 65535); - } - - if (logData.result && logData.result.length > 65535) { - logData.result = logData.result.substring(0, 65535); - } - - logData.use_time = Date.now() - startTime; - - // 使用 egg-mysql 保存日志到数据库 - const result = await ctx.app.mysql.get('wms').insert('wms_system_log', { - method: logData.method || '', - v: logData.v || '', - url: logData.url || '', - headers: logData.headers || '', - auth: logData.auth || '', - created_at: ctx.app.mysql.get('wms').literals.now, - body: logData.body || '', - result: logData.result || '', - use_time: logData.use_time || 0, - store_id: logData.store_id || null, + return await apiLogSink.write(ctx.app, { + logData, + startTime, device: 'pda', }); - return result; } catch (error) { ctx.logger.error('保存日志失败: ' + error.message); - // 可以选择记录到文件日志作为备用 + // 兜底:至少把原始数据落到 app 日志,避免整条丢失 ctx.logger.info('日志数据: ', JSON.stringify(logData)); } } diff --git a/app/service/qimen.js b/app/service/qimen.js index 33bff3d..d0e0b9b 100644 --- a/app/service/qimen.js +++ b/app/service/qimen.js @@ -6,14 +6,13 @@ const { XMLParser } = require('fast-xml-parser'); class QimenService extends Service { /** * 验证接口是否存在且启用 - * @param appkey - * @param customerId - * @param warehouseCode + * @param {string} appkey 应用编码 + * @param {string} customerId 客户编码 + * @param {string} warehouseCode 仓库编码 */ async validateApi(appkey, customerId, warehouseCode) { try { - const { ctx } = this; const result = await this.ctx.service.main.findQimenAppWithContract(appkey, customerId, warehouseCode); return result; } catch (error) { @@ -41,7 +40,7 @@ class QimenService extends Service { } /** * 解析XML到数组 - * @param xmlString + * @param {string} xmlString XML 字符串 */ async parseXmlToArray(xmlString) { const cleanedXml = this.cleanXmlString(xmlString); @@ -59,12 +58,8 @@ class QimenService extends Service { parseAttributeValue: false, trimValues: false, // 也关闭trim,保持原始格式 ignoreDeclaration: true, - // 添加标签值处理器,手动控制转换 - tagValueProcessor: (tagName, tagValue, jPath, hasAttributes, isLeafNode) => { - // 如果是叶子节点且需要保持字符串格式的标签,可以在这里特殊处理 - // 默认返回原始值 - return tagValue; - }, + // 保持 fast-xml-parser 的真实叶子文本值,避免把标签名误当成字段值。 + tagValueProcessor: (tagName, tagValue) => tagValue, }); try { @@ -77,7 +72,7 @@ class QimenService extends Service { /** * 清理XML字符串 - * @param xmlString + * @param {string} xmlString XML 字符串 */ cleanXmlString(xmlString) { if (!xmlString) return ''; @@ -103,17 +98,17 @@ class QimenService extends Service { /** * 调用业务方法 - * @param className - * @param actionName - * @param xmlData - * @param storeId - * @param warehouseId - * @param appKey - * @param customerId - * @param warehouseCode - * @param format + * @param {string} className 类名 + * @param {string} actionName 方法名 + * @param {Object} xmlData 解析后的 XML 数据 + * @param {number} storeId 货主ID + * @param {number} warehouseId 仓库ID + * @param {string} appKey 应用编码 + * @param {string} customerId 客户编码 + * @param {string} warehouseCode 仓库编码 + * @return {Promise} 调用结果 */ - async callMethod(className, actionName, xmlData, storeId, warehouseId, appKey, customerId, warehouseCode, format = 'xml') { + async callMethod(className, actionName, xmlData, storeId, warehouseId, appKey, customerId, warehouseCode) { try { // 构建服务类路径 const servicePath = `${className}`; @@ -148,7 +143,7 @@ class QimenService extends Service { /** * 格式化响应 - * @param data + * @param {Object} data 响应数据 */ formatResponse(data) { return this.xmlResponse(data); @@ -156,7 +151,7 @@ class QimenService extends Service { /** * XML响应 - * @param data + * @param {Object} data 响应数据 */ xmlResponse(data) { let xml = '\n'; @@ -180,9 +175,9 @@ class QimenService extends Service { /** * 构建XML节点 - 支持多层级 - * @param key - * @param value - * @param level + * @param {string} key 节点名 + * @param {*} value 节点值 + * @param {number} level 缩进层级 */ buildXmlNode(key, value, level = 0) { const indent = ' '.repeat(level); @@ -218,7 +213,7 @@ class QimenService extends Service { /** * XML转义 - * @param unsafe + * @param {*} unsafe 待转义值 */ escapeXml(unsafe) { if (unsafe === null || unsafe === undefined) return ''; @@ -234,6 +229,14 @@ class QimenService extends Service { } }); } + /** + * 保存出站奇门请求日志(直接落库)。 + * 仅用于出站请求(qimenClient.sendRequest)的日志落库; + * 入站请求日志统一走文件队列异步消费落库,避免同一 log_id 双写入冲突。 + * @param {Object} logData 日志数据,需包含 log_id 等字段。 + * @param {number} startTime 请求开始时间戳。 + * @return {Promise} 新增日志主键 ID,失败时返回 undefined。 + */ async saveQimenLog(logData, startTime) { const { ctx, @@ -251,8 +254,10 @@ class QimenService extends Service { logData.use_time = Date.now() - startTime; - // 使用 egg-mysql 保存日志到数据库 + // 不再回退使用 ctx.qimenLogId:入站 log_id 已由文件队列消费落库, + // 出站复用会触发唯一索引冲突,出站日志必须使用自身生成的 log_id。 const result = await ctx.app.mysql.get('wms').insert('wms_qimen_log', { + log_id: logData.log_id || null, from_key: logData.from_key || '', to_key: logData.to_key || '', method: logData.method || '', @@ -272,11 +277,27 @@ class QimenService extends Service { ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData)); } } + /** + * 按 log_id 更新奇门请求日志的响应内容。 + * @param {string} result 响应内容。 + * @return {Promise} 数据库更新结果。 + */ async saveQimenLogResult(result) { - await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { result, id: this.ctx.qimenLogId }); + const { ctx } = this; + await ctx.app.mysql.get('wms').update('wms_qimen_log', { result }, { + where: { log_id: ctx.qimenLogId }, + }); } + /** + * 按 log_id 更新奇门请求日志的请求体内容。 + * @param {string} body 请求体内容。 + * @return {Promise} 数据库更新结果。 + */ async saveQimenLogBody(body) { - await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { body, id: this.ctx.qimenLogId }); + const { ctx } = this; + await ctx.app.mysql.get('wms').update('wms_qimen_log', { body }, { + where: { log_id: ctx.qimenLogId }, + }); } } diff --git a/app/service/qimenMethods/deliveryorder.js b/app/service/qimenMethods/deliveryorder.js index 635c0ae..ac8b0ae 100644 --- a/app/service/qimenMethods/deliveryorder.js +++ b/app/service/qimenMethods/deliveryorder.js @@ -2,11 +2,18 @@ const MainService = require('../main'); +const { findOrderByCodeAcrossTables } = require('../../lib/order_lookup'); + class deliveryorderServer extends MainService { async query(data) { - const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(this.warehouseId); - const hisDeliveryModel = await this.ctx.model.OrderDeliveryFactory.getHistoryModel(this.warehouseId); - const order = await DeliveryModel.findOne({ where: { delivery_order_code: data.request.orderCode } }); + const orderCode = String(data?.request?.orderCode || '').trim(); + if (!orderCode) { + return this.fail('订单号不能为空'); + } + // 跨表查找:订单可能已流转到 dispatch/history/outsourced,仅查 current 会误报未找到 + const { order } = await findOrderByCodeAcrossTables(this.ctx, this.warehouseId, { + delivery_order_code: orderCode, + }); const totalLines = 0; if (order) { return this.success('成功', { @@ -32,13 +39,18 @@ 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: new Date().format(), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode }); + return this.success(res.message, { + createTime: this.app.formatDate(new Date()), + // addOrder 成功返回 data.orderId,兼容历史字段 deliveryOrderId + deliveryOrderId: (res.data && (res.data.orderId || res.data.deliveryOrderId)) || '', + warehouseCode: info.warehouseCode, + logisticsCode: (res.data && res.data.logisticsCode) || '', + }); } - return this.fail(res.message, { createTime: new Date().format() }); - + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); } async batchcreate() { return this.fail('批量创建接口未完善'); diff --git a/app/service/qimenMethods/entryorder.js b/app/service/qimenMethods/entryorder.js index 67b941d..8be0b41 100644 --- a/app/service/qimenMethods/entryorder.js +++ b/app/service/qimenMethods/entryorder.js @@ -4,18 +4,20 @@ const MainService = require('../main'); class entryorderServer extends MainService { async create(data) { - const info = this.getInfo; const res = await this.ctx.service.systems.entryOrder.addOrder(data, this.getInfo(), 'QM'); - console.log('创建入库单返回', res); if (res.success) { - return this.success(res.message, { createTime: new Date().format(), entryOrderId: res.data.entryOrderId }); + return this.success(res.message, { + createTime: this.app.formatDate(new Date()), + entryOrderId: res.data.entryOrderId, + entryOrderCode: res.data.entryOrderCode, + status: res.data.status, + }); } - return this.fail(res.message, { createTime: new Date().format() }); + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); } - async query(data) { - console.log(data); + async query() { return this.fail('接口未完善'); } diff --git a/app/service/qimenMethods/inventory.js b/app/service/qimenMethods/inventory.js index 3d09f09..0f2f868 100644 --- a/app/service/qimenMethods/inventory.js +++ b/app/service/qimenMethods/inventory.js @@ -3,10 +3,6 @@ const MainService = require('../main'); class inventoryServer extends MainService { - - constructor(ctx) { - super(ctx); - } async query(data) { const criteria = data.request.criteriaList.criteria; const list = criteria.warehouseCode ? [ criteria ] : criteria; @@ -18,7 +14,7 @@ class inventoryServer extends MainService { warehouseCode: info.data.stock.warehouse_code, itemCode: info.data.stock.item_code, itemId: info.data.stock.id, - quantity: info.data.storage.quantity - info.data.storage.lockedQuantity, + quantity: info.data.storage.quantity, lockQuantity: info.data.storage.lockedQuantity, inventoryType: 'ZP', }); diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 02f2287..dc4b1dd 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -2,6 +2,10 @@ const MainService = require('../main'); +const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfo } = require('../../lib/intercept_guard'); +const { buildNoticeTimePatch } = require('../../lib/intercept_time'); +const { preloadOrderModels, findOrderAcrossTables } = require('../../lib/order_lookup'); + class orderServer extends MainService { constructor(ctx) { @@ -87,64 +91,688 @@ class orderServer extends MainService { }; } + /** + * 查询订单关联的拦截运单信息。 + * + * 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID, + * 禁止仅凭订单ID跨仓串读运单号;仓库ID缺失时拒绝读取。 + * + * @param {number|string} orderId 订单ID。 + * @param {number|string|null|undefined} warehouseId 仓库ID,必须为订单所属仓库。 + * @return {Promise>} 运单信息列表。 + */ + async getInterceptExpressInfo(orderId, warehouseId) { + const { ctx } = this; + const normalizedOrderId = Number(orderId || 0); + const normalizedWarehouseId = warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + ? Number(warehouseId) + : 0; + + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + return []; + } + + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 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, + warehouse_id: normalizedWarehouseId, + }, + 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, info.warehouseId); + + 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}`); + } + } + + /** + * 取消奇门订单。 + * 按 orderType 分发: + * - ORDER(JYCK/HHCK/BFCK):订单未同步且未开始拣货/打印时直接取消;已同步或已开始 + * 拣货/打印时转入拦截处理:写入订单拦截状态 intercept_status(intercepting/requested) + * 并同步写入拦截时间 intercept_time。 + * - RK(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):走入库单作废流程(状态守卫、 + * 回退收货单占用、写操作日志),取消成功后不需要向奇门回传任何事件。 + * - CK(PTCK/DBCK/B2BCK/QTCK/CGTH):走独立出库单表 wms_order_stockout 取消, + * 取消成功后不需要向奇门回传任何事件。 + * @param {Object} data 奇门请求数据。 + * @param {Object} data.request 请求体,包含 orderCode、orderType 等字段。 + * @return {Promise} 取消结果,成功时返回成功消息,失败时返回错误信息。 + */ 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('取消订单成功'); - break; - case 'RK' : - console.log(data, info); - const existingOrder = await ctx.model.EntryOrder.findOne({ - where: { - entry_order_code: data.request.orderCode, + { + const orderCode = String(data?.request?.orderCode || '').trim(); + if (!orderCode) { + return this.fail('订单号不能为空'); + } + + // 模型预取必须在事务外(首次获取可能执行 DDL 隐式提交) + const orderModels = await preloadOrderModels(ctx, info.warehouseId); + const transaction = await ctx.model.transaction(); + try { + // 跨表查找:current → dispatch → history → outsourced,命中即停 + const { order: existingOrder, location: existingLocation } = await findOrderAcrossTables(orderModels, { + delivery_order_code: orderCode, warehouse_id: info.warehouseId, store_id: info.storeId, - }, - }); - if (existingOrder) { - await existingOrder.update({ - order_status: 'CANCELLED', - updated_at: new Date(), + }, { + findOptions: { + transaction, + lock: transaction.LOCK.UPDATE, + }, }); + + if (!existingOrder) { + await transaction.rollback(); + return this.fail('未找到对应的订单'); + } + + // 订单已流转出 current(dispatch/history/outsourced): + // 仅当已取消时视为取消成功(幂等),否则无法在待出库表中取消 + if (existingLocation !== 'current') { + if (String(existingOrder.status || '').trim() === 'cancel') { + await transaction.rollback(); + return this.success('取消订单成功'); + } + await transaction.rollback(); + return this.fail('未找到对应的订单'); + } + + // 幂等处理:订单在配送表中且已取消,直接返回取消成功 + const currentStatus = String(existingOrder.status || '').trim(); + if (currentStatus === 'cancel') { + await transaction.rollback(); + return this.success('取消订单成功'); + } + + const pickStatus = String(existingOrder.pick_status || 'none').trim(); + const printStatus = String(existingOrder.print_status || 'none').trim(); + + if (pickStatus !== 'none' || printStatus !== 'none') { + // 拦截前置校验:团购单已复核 / 散单已称重后不允许写入拦截请求状态 + const guardInfo = await resolveInterceptRequestGuardInfo(ctx, { + orderId: existingOrder.id, + waveId: existingOrder.wave_id, + warehouseId: info.warehouseId, + transaction, + }); + const blockReason = getInterceptRequestBlockReason({ + waveType: guardInfo.waveType, + inspectionStatus: String(existingOrder.inspection_status || '').trim(), + weighingWeight: guardInfo.weighingWeight, + }); + + if (!blockReason) { + // 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值) + const noticeNow = new Date(); + await existingOrder.update({ + intercept_status: 'intercepting', + ...buildNoticeTimePatch(existingOrder.intercept_time, noticeNow), + updated_at: noticeNow, + }, { + transaction, + }); + + // 同步更新运单表拦截标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction } + ); + } catch (expressErr) { + ctx.logger.warn( + `[qimen order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}` + ); + } + } else { + ctx.logger.info( + `[qimen order cancel] 订单${blockReason},跳过写入拦截请求状态, orderId=${existingOrder.id}` + ); + } + + await transaction.commit(); + + // 写入拦截操作日志(失败不影响主流程;未写入拦截请求状态时不记录) + if (!blockReason) { + try { + if (ctx.model && ctx.model.OperationLog) { + const customerId2 = String(info.customerId || '').trim(); + await ctx.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_INTERCEPT_REQUEST', + operator_id: null, + operator_name: customerId2 ? `qimen:${customerId2}` : 'qimen', + external_log_type: 'NONE', + warehouse_id: info.warehouseId || null, + platform_code: customerId2 || 'SYSTEM', + message: '奇门取消订单-触发拦截', + }); + } + } catch (logErr) { + ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr); + } + } + + // 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程) + try { + const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id, info.warehouseId); + if (Array.isArray(interceptExpress) && interceptExpress.length > 0) { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: info.warehouseId, + creatorLabel: ctx.user?.employees_name || '奇门系统', + }); + } + } catch (workOrderErr) { + ctx.logger.warn( + `[qimen order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}` + ); + } + + if (!blockReason) { + await this.sendCancelInterceptNotice({ + orderCode, + existingOrder, + info, + }); + } + return this.fail(blockReason + ? `订单${blockReason},无法拦截执行,已转快递拦截` + : '取消失败,已通知拦截执行'); + } + + // 已同步订单不允许取消,转为拦截处理 + const syncStatus = String(existingOrder.sync_status || '').trim(); + if (syncStatus === 'fin') { + // 拦截前置校验:团购单已复核 / 散单已称重后不允许写入拦截请求状态 + const syncGuardInfo = await resolveInterceptRequestGuardInfo(ctx, { + orderId: existingOrder.id, + waveId: existingOrder.wave_id, + warehouseId: info.warehouseId, + transaction, + }); + const syncBlockReason = getInterceptRequestBlockReason({ + waveType: syncGuardInfo.waveType, + inspectionStatus: String(existingOrder.inspection_status || '').trim(), + weighingWeight: syncGuardInfo.weighingWeight, + }); + + if (!syncBlockReason) { + // 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值) + const noticeNow = new Date(); + await existingOrder.update({ + intercept_status: 'requested', + ...buildNoticeTimePatch(existingOrder.intercept_time, noticeNow), + updated_at: noticeNow, + }, { + transaction, + }); + + // 同步更新运单表拦截标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction } + ); + } catch (expressErr) { + ctx.logger.warn( + `[qimen order cancel] 更新运单拦截标记失败(sync), orderId=${existingOrder.id}, error=${expressErr.message}` + ); + } + } else { + ctx.logger.info( + `[qimen order cancel] 订单${syncBlockReason},跳过写入拦截请求状态(sync), orderId=${existingOrder.id}` + ); + } + + await transaction.commit(); + + // 写入拦截操作日志(失败不影响主流程;未写入拦截请求状态时不记录) + if (!syncBlockReason) { + try { + if (ctx.model && ctx.model.OperationLog) { + const customerId2 = String(info.customerId || '').trim(); + await ctx.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_INTERCEPT_REQUEST', + operator_id: null, + operator_name: customerId2 ? `qimen:${customerId2}` : 'qimen', + external_log_type: 'NONE', + warehouse_id: info.warehouseId || null, + platform_code: customerId2 || 'SYSTEM', + message: '奇门取消订单-触发拦截(已同步订单转拦截)', + }); + } + } catch (logErr) { + ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败(sync),不影响主流程', logErr); + } + } + + // 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程) + try { + const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id, info.warehouseId); + if (Array.isArray(interceptExpress) && interceptExpress.length > 0) { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: info.warehouseId, + creatorLabel: ctx.user?.employees_name || '奇门系统', + }); + } + } catch (workOrderErr) { + ctx.logger.warn( + `[qimen order cancel] 创建工单/通知失败(sync), orderId=${existingOrder.id}, error=${workOrderErr.message}` + ); + } + + if (!syncBlockReason) { + await this.sendCancelInterceptNotice({ + orderCode, + existingOrder, + info, + }); + } + return this.fail(syncBlockReason + ? `订单${syncBlockReason},无法取消,已转快递拦截` + : '订单已同步,不可取消,已转为拦截处理'); + } + + // 检查是否在波次中,若在波次中需清除波次关联 + const existingWaveId = Number(existingOrder.wave_id || 0); + + const updateValues = { + status: 'cancel', + outbound_status: 'fin', + step: 4, + updated_at: new Date(), + }; + if (existingWaveId > 0) { + updateValues.wave_id = 0; + updateValues.wave_no = ''; + } + + await existingOrder.update(updateValues, { transaction }); + + // 波次清理:删除波次索引、重建波次索引、更新波次统计 + if (existingWaveId > 0) { + await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId: info.warehouseId, + orderIds: [ existingOrder.id ], + transaction, + }); + + // 重建受影响波次的订单索引(wave_index 重新排序) + await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId: info.warehouseId, + waveIds: [ existingWaveId ], + orderModel: orderModels.current, + transaction, + }); + + const { Op } = this.app.Sequelize; + const WaveBatch = ctx.model.WaveBatch; + if (WaveBatch) { + await WaveBatch.decrement('total_orders', { + by: 1, + where: { + wave_id: existingWaveId, + warehouse_id: info.warehouseId, + total_orders: { [Op.gt]: 0 }, + }, + transaction, + }); + + const wave = await WaveBatch.findOne({ + where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, + attributes: [ 'wave_id', 'total_orders', 'wave_status' ], + raw: true, + transaction, + }); + + if (wave) { + const totalOrders = Number(wave.total_orders); + const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0; + if (normalizedTotalOrders <= 0) { + await WaveBatch.update( + { total_orders: 0, wave_status: -1, update_time: new Date() }, + { where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, transaction } + ); + } + } + } + } + + // 释放储位分配锁定库存(wms_storage / wms_stock_warehouse) + await this.releaseStorageLockForCancel({ + orderId: existingOrder.id, + warehouseId: info.warehouseId, + transaction, + }); + + await transaction.commit(); + + // 波次策略扫描清理(不影响主流程) + if (existingWaveId > 0) { + try { + ctx.service.systemMethods.order.wave.enqueueWaveStrategyQuickScanPostOrderChange( + info.warehouseId, + [ existingOrder.id ], + { triggerScan: true, source: 'qimenCancel' } + ); + } catch (scanErr) { + ctx.logger.warn('[QimenOrderCancel] 波次策略扫描触发失败,不影响主流程', scanErr); + } + } + + // 写入取消操作日志(不影响主流程) + try { + if (ctx.model && ctx.model.OperationLog) { + const customerId = String(info.customerId || '').trim(); + await ctx.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_CANCEL', + operator_id: null, + operator_name: customerId ? `qimen:${customerId}` : 'qimen', + external_log_type: 'NONE', + warehouse_id: info.warehouseId || null, + platform_code: customerId || 'SYSTEM', + message: '奇门取消订单', + }); + } + } catch (logErr) { + ctx.logger.warn('[QimenOrderCancel] 写入取消操作日志失败,不影响主流程', logErr); + } + + 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': + { + // RK 组入库单(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):委托共享入库单作废实现 + // (守卫 sync_status/COMPLETED、回退收货单占用、写操作日志), + // 取消成功后不需要向奇门回传任何事件;已作废按幂等成功处理。 + const orderCode = String(data?.request?.orderCode || '').trim(); + if (!orderCode) { + return this.fail('入库单号不能为空'); + } + + const rkInfo = this.getInfo(); + const result = await ctx.service.systems.storage.entry.cancel( + { entryOrderCode: orderCode }, + { + storeId: rkInfo.storeId, + warehouseId: rkInfo.warehouseId, + operatorLabel: String(rkInfo.customerId || '').trim() + ? `qimen:${String(rkInfo.customerId).trim()}` + : 'qimen', + skipExternalSync: true, + idempotent: true, + notFoundMessage: '未找到对应的入库单', + } + ); + + if (result.code === 200) { return this.success('取消入库单成功'); } - return this.fail('未找到对应的入库单'); - break; - case 'CK' : - return this.fail('取消出库单未开发完成'); - break; - case 'JG' : + return this.fail(result.message || '取消入库单失败'); + } + case 'CK': + { + // CK 组出库单(PTCK/DBCK/B2BCK/QTCK/CGTH):走独立出库单表 wms_order_stockout 取消, + // 共享实现 systems/stockout_order.js#cancel(事务 + 行锁,释放 QM_STOCKOUT 锁定)。 + // 取消成功后不需要向奇门回传任何事件。 + const orderCode = String(data?.request?.orderCode || '').trim(); + if (!orderCode) { + return this.fail('出库单号不能为空'); + } + + const ckInfo = this.getInfo(); + return ctx.service.systems.stockoutOrder.cancel( + { stockoutOrderCode: orderCode }, + { + storeId: ckInfo.storeId, + warehouseId: ckInfo.warehouseId, + operatorLabel: String(ckInfo.customerId || '').trim() + ? `qimen:${String(ckInfo.customerId).trim()}` + : 'qimen', + } + ); + } + case 'JG': return this.fail('取消加工单未开发完成'); - break; case 'BACKORDER': return this.fail('取消退货单未开发完成'); - break; default: return this.fail(`未识别的作业类型${orderType.method}`, {}); } } + + /** + * 取消订单时释放储位分配锁定库存。 + * - 有 wms_picking 记录时:释放 wms_storage.locked_quantity 与 wms_stock_warehouse.locked_quantity, + * 并删除对应的 wms_picking 分配记录。 + * - 无 wms_picking 记录时:从 wms_order_items 查询该订单的 stock_id 与 plan_qty, + * 只释放 wms_stock_warehouse.locked_quantity。 + * + * @param {Object} options - 释放参数。 + * @param {number} options.orderId - 订单ID。 + * @param {number} options.warehouseId - 仓库ID。 + * @param {Object} options.transaction - 数据库事务对象。 + * @return {Promise} + */ + async releaseStorageLockForCancel({ orderId, warehouseId, transaction } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!orderId || !warehouseId) { + return; + } + + const pickingModel = ctx.model.Picking; + const storageModel = ctx.model.Storage; + const stockModel = ctx.model.StockWarehouse; + + if (!pickingModel || !storageModel || !stockModel) { + ctx.logger.warn('[qimen order.cancel releaseStorageLockForCancel] 模型不可用,跳过库存释放'); + return; + } + + // 查找该订单的有效分配记录 + const pickingRows = await pickingModel.findAll({ + where: { + order_id: orderId, + status: { [Op.ne]: 'cancel' }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + if (!Array.isArray(pickingRows) || pickingRows.length === 0) { + // 无储位分配记录:从订单明细获取锁定信息,只释放 stock_warehouse 锁 + const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (!orderItemsModel) { + ctx.logger.warn('[qimen order.cancel releaseStorageLockForCancel] OrderItems 模型不可用,跳过库存释放'); + return; + } + + const orderItems = await orderItemsModel.findAll({ + where: { order_id: orderId }, + attributes: [ 'stock_id', 'plan_qty' ], + raw: true, + transaction, + }); + + for (const item of orderItems) { + const stockId = Number(item.stock_id || 0); + const qty = Number(item.plan_qty || 0); + if (stockId <= 0 || qty <= 0) continue; + + await ctx.service.systems.stockStore.updateLockedQuantity(stockId, -qty, transaction, { + remark: '奇门取消订单-释放创建锁', + orderType: 'ORDER_CANCEL', + orderNo: String(orderId), + orderId, + }); + } + return; + } + + // 按 storage_id 汇总释放数量 + const storageQuantityMap = new Map(); + for (const row of pickingRows) { + const storageId = Number(row.storage_id || 0); + const quantity = Number(row.quantity || 0); + if (storageId > 0 && quantity > 0) { + storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity); + } + } + + if (storageQuantityMap.size === 0) { + return; + } + + // 查出关联的 wms_storage 记录,获取 stock_id + const storageIds = Array.from(storageQuantityMap.keys()); + const storageRows = await storageModel.findAll({ + where: { + id: { [Op.in]: storageIds }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const storageMap = new Map(); + for (const row of storageRows) { + storageMap.set(Number(row.id), row); + } + + // 依次释放 wms_storage 与 wms_stock_warehouse 锁定数量 + for (const [ storageId, quantity ] of storageQuantityMap.entries()) { + const storageRow = storageMap.get(storageId); + if (!storageRow) { + ctx.logger.warn(`[qimen order.cancel] 库存记录不存在,跳过: storageId=${storageId}`); + continue; + } + + const stockId = Number(storageRow.stock_id || 0); + if (stockId <= 0) { + ctx.logger.warn(`[qimen order.cancel] 库存记录缺少 stock_id,跳过: storageId=${storageId}`); + continue; + } + + // 释放 wms_storage.locked_quantity + await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); + + // 释放 wms_stock_warehouse.locked_quantity + const releaseResult = await ctx.service.systems.stockStore.updateLockedQuantity( + stockId, -Number(quantity), transaction, { + remark: '奇门取消订单-释放储位锁', + orderType: 'ORDER_CANCEL', + orderNo: String(orderId), + orderId, + } + ); + + if (!releaseResult.success) { + throw new Error(`库存主记录释放失败: stockId=${stockId}, ${releaseResult.error}`); + } + } + + // 删除已释放的分配记录 + const pickingIds = pickingRows + .map(row => Number(row.id || 0)) + .filter(id => id > 0); + + if (pickingIds.length > 0) { + await pickingModel.destroy({ + where: { + id: { [Op.in]: pickingIds }, + }, + transaction, + }); + } + } + async pending(data) { - console.log(data); const orderType = this.orderType[data.request.orderType]; switch (orderType.method) { case 'ORDER': return this.fail('锁定订单未开发完成'); - break; - case 'RK' : + case 'RK': return this.fail('锁定入库单未开发完成'); - break; - case 'CK' : + case 'CK': return this.fail('锁定出库单未开发完成'); - break; - case 'JG' : + case 'JG': return this.fail('锁定加工单未开发完成'); - break; case 'BACKORDER': return this.fail('锁定退货单未开发完成'); - break; default: return this.fail(`未识别的作业类型${orderType.method}`, {}); } diff --git a/app/service/qimenMethods/returnorder.js b/app/service/qimenMethods/returnorder.js index af8d247..d271ad5 100644 --- a/app/service/qimenMethods/returnorder.js +++ b/app/service/qimenMethods/returnorder.js @@ -6,13 +6,13 @@ class returnorderServer extends MainService { /* 退货入库创建接口 */ - async create(data) { + async create() { return this.fail('接口未完善', { result: 'singleitemServer', storeId: this.storeId }); } /* 退货入库查询接口 */ - async query(data) { + async query() { return this.fail('接口未完善', { result: 'singleitemServer', storeId: this.storeId }); } } diff --git a/app/service/qimenMethods/singleitem.js b/app/service/qimenMethods/singleitem.js index f14c2f9..1bd411e 100644 --- a/app/service/qimenMethods/singleitem.js +++ b/app/service/qimenMethods/singleitem.js @@ -4,11 +4,8 @@ const MainService = require('../main'); class singleitemServer extends MainService { async synchronize(data) { - const { app } = this; try { - console.log('data', data); const stockData = await this.ctx.service.systems.stockStore.initQimenStockData(data.request, this.appKey, this.storeId, this.warehouseId); - console.log('stockData', stockData); const result = await await this.ctx.service.systems.stockStore.create(stockData); return this.success('同步完成', { itemId: result.id }); } catch (error) { diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index 9eb0827..a7525dc 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -2,71 +2,49 @@ const MainService = require('../main'); +/** + * 奇门出库单适配层。 + * + * 处理奇门 stockout.create / stockout.query 接口,业务逻辑统一委托到 + * `app/service/systems/stockout_order.js`(ctx.service.systems.stockoutOrder), + * 与 openapiMethods/stockout.js 共用同一份实现。 + * 落库表:`wms_order_stockout` + `wms_order_stockout_items`。 + */ class stockoutServer extends MainService { + /** + * 创建出库单(奇门渠道,source_type=QM)。 + * + * @param {object} data - 奇门 stockout.create 请求体 + * @param {object} data.request - 请求数据 + * @param {object} data.request.deliveryOrder - 出库单头信息 + * @param {object} data.request.orderLines - 出库单明细 + * @return {Promise} 返回 success / fail 结果 + */ async create(data) { - const { app } = this; - - let totalOrderLines = data.request.deliveryOrder.totalOrderLines || 0; - - let orderLine = data.request.orderLines.orderLine; - if (orderLine.orderLineNo) { - orderLine = [ orderLine ]; - } - const isSingle = totalOrderLines ? 0 : 1; - totalOrderLines = totalOrderLines || orderLine.length; - const errors = []; - const items = []; - for (let i = 0; i < orderLine.length; i++) { - const wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId); - if (!wms_stock) { - errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`); - continue; - } - if (!wms_stock.stock_id) { - errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》wms无对应关系\n请联系仓库关联创建商品`); - continue; - } - wms_stock.inventory_type = orderLine[i].inventoryType; - wms_stock.order_line_no = orderLine[i].orderLineNo; - wms_stock.count = orderLine[i].planQty; - wms_stock.item_id = orderLine[i].itemId; - items.push(wms_stock); - } - console.log('出库单参数:', data.request.deliveryOrder, this.appKey, this.storeId, this.warehouseId, totalOrderLines, 'QM', this.customerId, this.warehouseCode); - console.log('出库单明细:', items); - if (errors.length > 0) { - return this.fail('创建入库单失败,失败原因:\n' + errors.join('\n')); - } - /* const order = await this.ctx.service.systems.deliveryOrder.tryCreatedeliveryOrder(data.request.deliveryOrder,this.appKey, this.storeId, this.warehouseId,totalOrderLines,"QM",this.customerId,this.warehouseCode); - console.log("入库单参数",order); - if(!order.success){ - return this.fail("创建入库单失败,失败原因:\n"+order.error); - } - const orderId = order.deliveryOrderId; - for (var i = 0; i < items.length; i++) { - const item = items[i]; - let res = await this.ctx.service.systems.deliveryOrder.addItems(item,orderId); - console.log("“添加商品返回信息",res); - if(!res.success){ - errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); - } - } - if(errors.length>0){ - await app.model.deliveryOrder.delete(orderId);//失败删除; - return this.fail("创建入库单失败,失败原因:\n"+errors.join("\n")); - } - const lineCount = await this.ctx.service.systems.deliveryOrder.getLineCount(orderId);//获取接收行数 - if(lineCount==totalOrderLines){//所有行数接收完成 - await this.ctx.service.systems.deliveryOrder.received(orderId,this.warehouseId,this.storeId);//接收完成 - return this.success("入库单接收完毕",{deliveryOrderId:orderId}); - }*/ - return this.success('入库单接收中'); + const info = this.getInfo(); + return this.ctx.service.systems.stockoutOrder.create(data, { + storeId: info.storeId, + warehouseId: info.warehouseId, + warehouseCode: info.warehouseCode, + appKey: info.appKey, + sourceType: 'QM', + }); } + + /** + * 查询出库单。 + * + * @param {object} data - 奇门 stockout.query 请求体 + * @param {object} data.request - 请求数据 + * @param {object} data.request.deliveryOrder - 出库单查询条件 + * @param {string} data.request.deliveryOrder.deliveryOrderCode - 出库单号 + * @return {Promise} 返回 success / fail 结果 + */ async query(data) { - console.log(data); - return this.fail('接口未完善'); + return this.ctx.service.systems.stockoutOrder.query(data); } } + module.exports = stockoutServer; diff --git a/app/service/qimenMethods/taobao/qimen/service.js b/app/service/qimenMethods/taobao/qimen/service.js index 5721bec..4e5dab9 100644 --- a/app/service/qimenMethods/taobao/qimen/service.js +++ b/app/service/qimenMethods/taobao/qimen/service.js @@ -1,14 +1,17 @@ 'use strict'; -const MainService = require(`${APP_ROOT}/app/service/main`); +const MainService = require('../../../main'); class serviceServer extends MainService { + /** + * @param {*} data 奇门心跳传入解构 + * @return {Promise} 返回心跳信息 + */ async heartbeat(data) { - console.log(data); if (data?.request?.serialNumber) { - return this.success(new Date().format(), { code: data.request.serialNumber }); + return this.success(this.app.formatDate(new Date()), { code: data.request.serialNumber }); } - return this.fail(new Date().format(), { code: 0 }); + return this.fail(this.app.formatDate(new Date()), { code: 0 }); } } diff --git a/app/service/system.js b/app/service/system.js index 830f5b7..a62e7d4 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -1,28 +1,35 @@ 'use strict'; const Service = require('egg').Service; -const { XMLParser } = require('fast-xml-parser'); + +const apiLogSink = require('../lib/api_log_sink'); + +const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other', 'tv', 'workerstation', 'workstation' ]); +// project: all=全部, warehouse=仓库, store=货主, tms=物流 +const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 'scm', 'other' ]); class systemService extends Service { async callMethod(className, actionName, requestData, authHeader) { try { - - // 构建服务类路径 const servicePath = `${className}`; const classs = servicePath.split('.'); let systemMethods = this.ctx.service.systemMethods; for (let i = 0; i < classs.length; i++) { - const className = classs[i]; - systemMethods = systemMethods[className]; + const rawClassName = classs[i]; + // Egg.js 将文件名 snake_case 自动转为 camelCase,需做对应转换 + const camelName = rawClassName.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); + systemMethods = systemMethods[camelName] || systemMethods[rawClassName]; } // 检查服务是否存在 if (!systemMethods) { throw new Error(`服务 ${servicePath} 不存在`); - }else{ - console.log(`调用服务: ${servicePath}, 方法: ${actionName}`); } - const serviceInstance = systemMethods; + let serviceInstance = systemMethods; + + if (typeof serviceInstance[actionName] !== 'function' && serviceInstance?.index) { + serviceInstance = serviceInstance.index; + } // 检查方法是否存在 if (typeof serviceInstance[actionName] !== 'function') { @@ -35,9 +42,8 @@ class systemService extends Service { // 调用方法 const authPass = await serviceInstance.checkAuth(servicePath, actionName, authHeader); const isLog = authPass.isLog; - if (authPass.status == 200) { + if (authPass.status === 200) { result.data = await serviceInstance[actionName](requestData); - console.log(result.data); result.status = 200; } else { @@ -66,41 +72,117 @@ class systemService extends Service { return true; } + + validateRequestContext(params = {}, headers = {}) { + if (!this.validateParams(params)) { + return { + ok: false, + status: 400, + code: 400, + message: '参数缺失或错误: method/v/timestamp', + }; + } + + const rawTimestamp = String(params.timestamp || '').trim(); + if (!/^\d+$/.test(rawTimestamp)) { + return { + ok: false, + status: 400, + code: 400, + message: 'timestamp 必须为数字时间戳', + }; + } + + const timestampNum = Number(rawTimestamp); + if (!Number.isFinite(timestampNum) || timestampNum <= 0) { + return { + ok: false, + status: 400, + code: 400, + message: 'timestamp 非法', + }; + } + + const platform = String(headers.platform || '').trim(); + const project = String(headers.project || '').trim(); + const authorization = String(headers.authorization || '').trim(); + + if (!platform) { + return { + ok: false, + status: 400, + code: 400, + message: '缺少请求头 platform', + }; + } + + if (!project) { + return { + ok: false, + status: 400, + code: 400, + message: '缺少请求头 project', + }; + } + + if (!ALLOWED_PLATFORMS.has(platform.toLowerCase())) { + return { + ok: false, + status: 400, + code: 400, + message: `platform 不支持: ${platform}`, + }; + } + + if (!ALLOWED_PROJECTS.has(project.toLowerCase())) { + return { + ok: false, + status: 400, + code: 400, + message: `project 不支持: ${project}`, + }; + } + + if (authorization && !authorization.startsWith('Bearer ')) { + return { + ok: false, + status: 401, + code: 401, + message: 'Authorization 格式错误,应为 Bearer ', + }; + } + + return { + ok: true, + status: 200, + code: 0, + message: 'ok', + }; + } + + /** + * 保存接口日志。 + * + * 经 Egg logger(apiLog)平铺写出到日志文件;wms_system_log 表已下线,不再有任何入库路径。 + * + * @param {Object} logData 日志数据 + * @param {number} startTime 开始时间戳 + * @return {Promise} 写出的平铺记录 + */ async saveLog(logData, startTime) { const { ctx, } = this; try { - // 限制日志内容长度 - if (logData.body && logData.body.length > 65535) { - logData.body = logData.body.substring(0, 65535); - } - - if (logData.result && logData.result.length > 65535) { - logData.result = logData.result.substring(0, 65535); - } - - logData.use_time = Date.now() - startTime; - - // 使用 egg-mysql 保存日志到数据库 - const result = await ctx.app.mysql.get('wms').insert('wms_system_log', { - method: logData.method || '', - v: logData.v || '', - url: logData.url || '', - headers: logData.headers || '', - auth: logData.auth || '', - created_at: ctx.app.mysql.get('wms').literals.now, - body: logData.body || '', - result: logData.result || '', - use_time: logData.use_time || 0, - store_id: logData.store_id || null, + return await apiLogSink.write(ctx.app, { + logData, + startTime, device: ctx.header.platform, }); - return result; } catch (error) { ctx.logger.error('保存奇门接口日志失败: ' + error.message); - // 可以选择记录到文件日志作为备用 + // 兜底:至少把原始数据落到 app 日志,避免整条丢失 ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData)); } } diff --git a/app/service/systemMethods/afterSale.js b/app/service/systemMethods/afterSale.js new file mode 100644 index 0000000..7872889 --- /dev/null +++ b/app/service/systemMethods/afterSale.js @@ -0,0 +1,1219 @@ +'use strict'; + +const MainService = require('../main'); + +const AFTER_SALE_EXPORT_TASK_CACHE_KEY_PREFIX = 'after_sale_export_task_'; +const AFTER_SALE_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 售后 block 权限 ID → role_group 映射表。 + * 516=客服组, 517=仓库组, 518=财务组 + */ +const BLOCK_PERMISSION_ROLE_GROUP_MAP = Object.freeze({ + 516: 'customer_service', + 517: 'warehouse', + 518: 'finance', +}); + +/** + * 售后模块工作列表排除的终态(已完成/已关闭/已取消)。 + * pending_feedback 不在静态排除列表中,由 workList 根据 followup_at 动态判断。 + */ +const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'closed', 'cancelled' ]); + +/** + * 系统方法层:afterSale(售后模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.afterSale 中。 + */ +class AfterSaleMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount,typeList,typeCreate,typeUpdate,typeDelete,subTypeList,subTypeCreate,subTypeUpdate,subTypeDelete'; + const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress,workCount,typeList,subTypeList'; + const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount,typeList,typeCreate,typeUpdate,typeDelete,subTypeList,subTypeCreate,subTypeUpdate,subTypeDelete'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + // =========================== + // 售后工作列表 + // =========================== + + /** + * 售后工作列表:按当前用户的 block 权限筛选可见的售后单。 + * 解析用户 wms_role.permissions 中 type=block 的售后权限 ID(516/517/518), + * 映射为 role_group,仅展示当前用户可处理的售后单。 + * + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 动态筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async workList(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + // 提取当前用户的售后 block 权限 → role_group 列表 + const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups(); + + // 强制过滤:仅展示当前用户可处理的 role_group,且排除已完成/已取消 + const enforcedWhere = { + ...where, + role_group: { + operator: 'in', + value: allowedRoleGroups, + }, + status: { + operator: 'notin', + value: WORK_LIST_EXCLUDED_STATUSES, + }, + }; + + const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort, { + order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ]], + excludeFutureFollowup: true, + // 列表行补充货主名称 store_name(合约表 store_remask 货主备注,无备注时回退货主公司全称) + enrichStoreName: true, + }); + return this.success('ok', result); + } + + /** + * 解析当前用户所拥有的售后 block 权限对应的 role_group 列表。 + * 从 wms_role.permissions 中查询当前激活角色的原始权限 ID, + * 若 permissions='*' 则返回全部 role_group,否则筛选 516/517/518。 + * + * @return {Promise} 当前用户可处理的 role_group 列表 + */ + async _resolveAfterSaleBlockRoleGroups() { + const { ctx } = this; + const employeeId = ctx.user && ctx.user.employees_id; + if (!employeeId) { + return [ '__none__' ]; + } + + try { + // 1. 通过 EmployeeRole 找到 role_id + const employeeRole = await ctx.model.EmployeeRole.findOne({ + where: { employee_id: employeeId }, + attributes: [ 'role_id' ], + raw: true, + }); + if (!employeeRole || !employeeRole.role_id) { + return [ '__none__' ]; + } + + // 2. 读取 wms_role.permissions + const role = await ctx.model.Role.findOne({ + where: { id: employeeRole.role_id, status: 1 }, + attributes: [ 'permissions' ], + raw: true, + }); + if (!role) { + return [ '__none__' ]; + } + + // 3. 标准化解析 + const state = ctx.service.systems.auth.rolePermission.normalizePermissionSet(role.permissions); + + // 超级管理员 → 全部 role_group + if (state.allAccess) { + return [ 'customer_service', 'warehouse', 'finance' ]; + } + + // 匹配 block 权限 516/517/518 + const allowedRoleGroups = []; + for (const permId of state.permissionIds) { + if (BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) { + allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]); + } + } + + if (allowedRoleGroups.length === 0) { + return [ '__none__' ]; + } + return allowedRoleGroups; + } catch (err) { + ctx.logger.warn(`[_resolveAfterSaleBlockRoleGroups] 权限查询失败: ${err.message}`); + return [ '__none__' ]; + } + } + + // =========================== + // 待处理工单计数(角标用) + // =========================== + + /** + * 快速查询当前用户待处理售后工单数量(用于角标显示)。 + * 过滤逻辑与 workList 一致:role_group 按 block 权限,排除已完成/已取消。 + * 返回 { count: number },前端自行判断 >99 显示 99+。 + * + * @param {Object} data 请求体(可选 where 条件) + * @return {Promise} { count: number } + */ + async workCount(data = {}) { + const { service } = this; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + // 与 workList 一致的角色组 + 状态过滤 + const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups(); + const enforcedWhere = { + ...where, + role_group: { + operator: 'in', + value: allowedRoleGroups, + }, + status: { + operator: 'notin', + value: WORK_LIST_EXCLUDED_STATUSES, + }, + }; + + const result = await service.systems.afterSale.countPending(enforcedWhere, { excludeFutureFollowup: true }); + return this.success('ok', { count: result.count }); + } + + // =========================== + // 售后审计列表 + // =========================== + + /** + * 售后审计列表:不限 role_group 与 status(包含已完成/已取消)。 + * 用于管理员/审计角色查看全部售后单。 + * + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 动态筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async auditList(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const result = await service.systems.afterSale.list(where, pagination, sort); + return this.success('ok', result); + } + + // =========================== + // 售后明细 + // =========================== + + /** + * 售后明细:查询主表、步骤列表及步骤附件。 + * + * @param {Object} data 请求体 + * @param {number} data.id 售后单主键ID + * @return {Promise} 统一 success 包装,包含主表、步骤列表及附件信息 + */ + async detail(data = {}) { + const { service } = this; + const { id } = data || {}; + + if (!id) { + return this.fail('缺少售后单ID'); + } + + const result = await service.systems.afterSale.getDetail(Number(id)); + return this.success('ok', result); + } + + // =========================== + // 创建售后单 + // =========================== + + /** + * 创建售后单:生成售后单号,写入主表记录。 + * warehouse_id 由服务端从当前上下文自动注入。 + * + * @param {Object} data 请求体 + * @param {string} data.type 售后类型(order/receiving/entry/stockout) + * @param {string} data.sub_type 售后子类型 + * @param {string} data.title 售后标题 + * @param {string} [data.description] 售后详细描述 + * @param {number} [data.priority=0] 优先级 + * @param {number} [data.waybill_id] 关联运单ID + * @param {number} [data.order_delivery_id] 关联发货订单ID(兼容别名 order_id) + * @param {number} [data.entry_order_id] 关联入库单ID + * @param {number} [data.order_stockout_id] 关联出库单ID + * @param {number} [data.receiving_id] 关联收货单ID + * @param {number} [data.store_id] 关联货主ID + * @param {number} [data.inbox_message_id] 关联站内信ID + * @return {Promise} 统一 success 包装,返回新创建的售后单信息 + */ + async create(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + + if (!warehouseId) { + return this.fail('无法获取当前仓库上下文'); + } + + const { + type, + sub_type: subType, + title, + description, + priority, + waybill_id: waybillId, + order_delivery_id: orderDeliveryIdRaw, + order_id: orderIdRaw, + entry_order_id: entryOrderId, + order_stockout_id: orderStockoutId, + receiving_id: receivingId, + store_id: storeId, + inbox_message_id: inboxMessageId, + } = data || {}; + + // 兼容 order_id 别名(优先 order_delivery_id,为空时取 order_id) + const orderDeliveryId = orderDeliveryIdRaw || orderIdRaw || null; + + // 生成售后单号 + const afterSaleNo = await this.generateAfterSaleNo(warehouseId); + + // 处理单据关联字段的冗余同步(waybill_no 等从对应表同步取数) + const redundantFields = await this._resolveRedundantFields({ + waybillId, + orderDeliveryId, + entryOrderId, + orderStockoutId, + receivingId, + }); + + const createData = { + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type, + sub_type: subType, + title, + description: description || null, + priority: priority !== undefined ? Number(priority) : 0, + creator_id: creatorId, + role_group: 'customer_service', + status: 'pending', + waybill_id: waybillId || null, + waybill_no: redundantFields.waybill_no || null, + order_id: orderDeliveryId || null, + order_no: redundantFields.order_no || null, + entry_order_id: entryOrderId || null, + entry_order_no: redundantFields.entry_order_no || null, + order_stockout_id: orderStockoutId || null, + order_stockout_no: redundantFields.order_stockout_no || null, + receiving_id: receivingId || null, + receiving_no: redundantFields.receiving_no || null, + store_id: storeId || null, + inbox_message_id: inboxMessageId || null, + }; + + const result = await service.systems.afterSale.create(createData); + return this.success('售后单创建成功', result); + } + + /** + * 解析单据关联字段的冗余值(waybill_no、order_delivery_no 等), + * 从对应的关联表中同步取数。 + * + * @param {Object} params 关联ID集合 + * @param {number} [params.waybillId] 运单ID + * @param {number} [params.orderDeliveryId] 发货订单ID + * @param {number} [params.entryOrderId] 入库单ID + * @param {number} [params.orderStockoutId] 出库单ID + * @param {number} [params.receivingId] 收货单ID + * @return {Promise} 冗余字段键值对 + */ + async _resolveRedundantFields(params = {}) { + const { ctx } = this; + const redundant = {}; + + // 运单号 + if (params.waybillId) { + try { + const waybill = await ctx.model.OrderExpress.findOne({ + where: { id: params.waybillId }, + attributes: [ 'waybill_code' ], + raw: true, + }); + redundant.waybill_no = waybill ? waybill.waybill_code || null : null; + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询运单号失败: ${err.message}`); + } + } + + // 发货订单号 + if (params.orderDeliveryId) { + try { + const warehouseId = ctx.user && ctx.user.store_id; + const DeliveryModel = warehouseId + ? await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId) + : null; + if (DeliveryModel) { + const order = await DeliveryModel.findOne({ + where: { id: params.orderDeliveryId }, + attributes: [ 'delivery_order_code' ], + raw: true, + }); + redundant.order_no = order ? order.delivery_order_code || null : null; + } + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询发货订单号失败: ${err.message}`); + } + } + + // 入库单号 + if (params.entryOrderId) { + try { + const entry = await ctx.model.EntryOrder.findOne({ + where: { id: params.entryOrderId }, + attributes: [ 'entry_order_code' ], + raw: true, + }); + redundant.entry_order_no = entry ? entry.entry_order_code || null : null; + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询入库单号失败: ${err.message}`); + } + } + + // 出库单号 + if (params.orderStockoutId) { + try { + const stockout = await ctx.model.OrderStockout.findOne({ + where: { id: params.orderStockoutId }, + attributes: [ 'order_stockout_no' ], + raw: true, + }); + redundant.order_stockout_no = stockout ? stockout.order_stockout_no || null : null; + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询出库单号失败: ${err.message}`); + } + } + + // 收货单号 + if (params.receivingId) { + try { + const receiving = await ctx.model.Receiving.findOne({ + where: { id: params.receivingId }, + attributes: [ 'receiving_code' ], + raw: true, + }); + redundant.receiving_no = receiving ? receiving.receiving_code || null : null; + } catch (err) { + ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询收货单号失败: ${err.message}`); + } + } + + return redundant; + } + + // =========================== + // 转单 + // =========================== + + /** + * 转单:将售后单的 role_group 更新为目标值,并写入一条 detail 步骤记录。 + * + * @param {Object} data 请求体 + * @param {number} data.id 售后单主键ID + * @param {string} data.role_group 目标角色组(customer_service/warehouse/finance) + * @param {string} [data.remark] 转单备注 + * @return {Promise} 统一 success 包装 + */ + async transfer(data = {}) { + const { ctx, service } = this; + const { + id, + role_group: targetRoleGroup, + remark, + } = data || {}; + + if (!id) { + return this.fail('缺少售后单ID'); + } + if (!targetRoleGroup) { + return this.fail('缺少目标角色组'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + + const result = await service.systems.afterSale.transfer({ + id: Number(id), + targetRoleGroup, + remark: remark || '', + operatorId, + operatorSnapshot, + }); + + return this.success('转单成功', result); + } + + // =========================== + // 处理工单 + // =========================== + + /** + * 处理工单:校验权限后写入步骤记录,可选更新状态与附件。 + * 若处理完后当前 role_group 非客服组且状态未完结,自动回设为客服组。 + * + * @param {Object} data 请求体 + * @param {number} data.id 售后单主键ID + * @param {string} [data.remark] 处理备注 + * @param {string} [data.status] 目标售后状态 + * @param {string} [data.resolution] 完结处理结果(status=completed 时写入) + * @param {number[]} [data.attachment_ids] 附件文件ID列表 + * @return {Promise} 统一 success 包装 + */ + async handleWorkOrder(data = {}) { + const { ctx, service } = this; + const { + id, + remark, + status: targetStatus, + resolution, + attachment_ids: attachmentIds, + } = data || {}; + + if (!id) { + return this.fail('缺少售后单ID'); + } + + // status 不填或填错默认 processing;pending 是创建默认值,不适用于处理操作 + const ALLOWED_STATUSES = Object.keys(ctx.model.AfterSale.AFTER_SALE_STATUS).filter(s => s !== 'pending'); + const safeStatus = (targetStatus && ALLOWED_STATUSES.includes(targetStatus)) ? targetStatus : 'processing'; + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + const result = await service.systems.afterSale.handleWorkOrder({ + id: Number(id), + remark: remark || null, + targetStatus: safeStatus, + resolution: resolution || null, + attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [], + operatorId, + operatorSnapshot, + warehouseId, + notifyGroup: true, + }); + + return this.success('处理成功', result); + } + + // =========================== + // 批量设为待反馈 + // =========================== + + /** + * 批量将售后工单设为"待反馈"状态,按仓库配置自动计算下次跟进时间。 + * 所有工单在同一事务中处理,任一失败则全部回滚。 + * + * @param {Object} data 请求体 + * @param {number[]} data.ids 售后单主键ID列表 + * @param {string} [data.remark] 统一处理备注(所有工单共用) + * @return {Promise} 统一 success 包装,包含 total/success/failed + */ + async batchSetPendingFeedback(data = {}) { + const { ctx, service } = this; + const { ids, remark } = data || {}; + + if (!Array.isArray(ids) || ids.length === 0) { + return this.fail('ids 不能为空且必须为数组'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + if (!warehouseId) { + return this.fail('无法获取当前仓库上下文'); + } + + const result = await service.systems.afterSale.batchSetPendingFeedback({ + ids, + remark: remark || null, + operatorId, + operatorSnapshot, + warehouseId, + }); + + return this.success('批量设为待反馈完成', result); + } + + // =========================== + // 批量完结/关闭 + // =========================== + + /** + * 批量将售后工单设为完结或关闭状态。 + * completed 时自动写入 resolved_at 并清除 followup_at。 + * 所有工单在同一事务中处理,任一失败则全部回滚。 + * + * @param {Object} data 请求体 + * @param {number[]} data.ids 售后单主键ID列表 + * @param {string} data.status 目标状态:completed | closed + * @param {string} [data.resolution] 完结处理结果(仅 status=completed 时写入) + * @param {string} [data.remark] 统一处理备注(所有工单共用) + * @return {Promise} 统一 success 包装,包含 total/success/failed + */ + async batchClose(data = {}) { + const { ctx, service } = this; + const { ids, status: targetStatus, resolution, remark } = data || {}; + + if (!Array.isArray(ids) || ids.length === 0) { + return this.fail('ids 不能为空且必须为数组'); + } + + const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]); + if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) { + return this.fail('status 必须为 completed 或 closed'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + if (!warehouseId) { + return this.fail('无法获取当前仓库上下文'); + } + + const result = await service.systems.afterSale.batchClose({ + ids, + status: targetStatus, + resolution: resolution || null, + remark: remark || null, + operatorId, + operatorSnapshot, + warehouseId, + }); + + return this.success('批量操作完成', result); + } + + // =========================== + // 登记理赔 + // =========================== + + /** + * 登记理赔:更新售后单的理赔相关字段,写入步骤记录,绑定附件。 + * + * @param {Object} data 请求体 + * @param {number} data.id 售后单主键ID + * @param {number} [data.claim_needed] 仓库理赔标记(0/1) + * @param {number} [data.claim_amount] 仓库理赔金额 + * @param {string} [data.claim_status] 仓库理赔状态 + * @param {number} [data.carrier_claim_needed] 运方理赔标记(0/1) + * @param {number} [data.carrier_claim_amount] 运方理赔金额 + * @param {string} [data.carrier_claim_status] 运方理赔状态 + * @param {string} [data.remark] 理赔备注 + * @param {string} [data.action] 操作动作描述,默认"登记理赔" + * @param {number[]} [data.attachment_ids] 附件文件ID列表 + * @return {Promise} 统一 success 包装 + */ + async registerClaim(data = {}) { + const { ctx, service } = this; + const { + id, + claim_needed: claimNeeded, + claim_amount: claimAmount, + claim_status: claimStatus, + carrier_claim_needed: carrierClaimNeeded, + carrier_claim_amount: carrierClaimAmount, + carrier_claim_status: carrierClaimStatus, + remark, + action, + attachment_ids: attachmentIds, + } = data || {}; + + if (!id) { + return this.fail('缺少售后单ID'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + const result = await service.systems.afterSale.registerClaim({ + id: Number(id), + claimNeeded: claimNeeded !== undefined ? Number(claimNeeded) : undefined, + claimAmount: claimAmount !== undefined ? Number(claimAmount) : undefined, + claimStatus: claimStatus || undefined, + carrierClaimNeeded: carrierClaimNeeded !== undefined ? Number(carrierClaimNeeded) : undefined, + carrierClaimAmount: carrierClaimAmount !== undefined ? Number(carrierClaimAmount) : undefined, + carrierClaimStatus: carrierClaimStatus || undefined, + remark: remark || null, + action: action || '登记理赔', + attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [], + operatorId, + operatorSnapshot, + warehouseId, + }); + + return this.success('理赔登记成功', result); + } + + // =========================== + // 导出 + // =========================== + + /** + * 提交售后单导出任务。 + * 异步执行:分页查询 → ExcelJS 流式写入 → COS 上传。 + * 进度通过 Redis 缓存追踪。 + * + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与列表一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装,返回任务ID + */ + async export(data = {}) { + const { service } = this; + const { where, sort } = data || {}; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.afterSale.exportAfterSales({ + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount || 0, + total_count: safeProgress.totalCount || 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询售后单导出任务进度。 + * + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装,包含进度与下载链接 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + // =========================== + // 辅助方法 + // =========================== + + /** + * 生成售后单号。 + * 格式:AS + YYYYMMDD + 6位序号(如 AS20240809000001)。 + * + * @param {number} warehouseId 仓库ID + * @return {Promise} 售后单号 + */ + async generateAfterSaleNo(warehouseId) { + const { ctx } = this; + const datePart = this._getCurrentDatePart(); + const prefix = 'AS'; + + const sql = ` + SELECT after_sale_no + FROM wms_after_sale + WHERE warehouse_id = :warehouseId + AND after_sale_no LIKE :pattern + ORDER BY after_sale_no DESC + LIMIT 1 + `; + const pattern = `${prefix}${datePart}%`; + + const rows = await ctx.model.query(sql, { + replacements: { warehouseId, pattern }, + type: ctx.model.QueryTypes.SELECT, + }); + + const latestNo = String(rows && rows[0] && rows[0].after_sale_no || '').trim(); + let sequence = 1; + + if (latestNo) { + const match = latestNo.match(/(\d{6})$/); + const lastSequence = match ? Number(match[1]) : 0; + if (Number.isInteger(lastSequence) && lastSequence > 0) { + sequence = lastSequence + 1; + } + } + + return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`; + } + + /** + * 获取当前日期片段(YYYYMMDD)。 + * + * @return {string} 当前日期片段 + */ + _getCurrentDatePart() { + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; + } + + /** + * 构建操作人快照 JSON 字符串。 + * 从 ctx.user 中提取关键身份信息。 + * + * @return {string} 操作人快照 JSON + */ + _buildOperatorSnapshot() { + const { ctx } = this; + const user = ctx.user && typeof ctx.user === 'object' ? ctx.user : {}; + const snapshot = { + id: user.id || user.user_id || null, + name: user.employees_name || user.real_name || user.name || '', + role: user.role && user.role.name ? user.role.name : '', + }; + return JSON.stringify(snapshot); + } + + /** + * 生成导出任务ID。 + * + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx && this.ctx.user && this.ctx.user.store_id + ? this.ctx.user.store_id + : 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `after_sale_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化导出任务ID(兼容 task_id / taskId)。 + * + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${AFTER_SALE_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) + : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync( + cacheKey, + progressPayload, + AFTER_SALE_EXPORT_TASK_CACHE_TTL_SECONDS + ); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[afterSale.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取导出任务进度缓存。 + * + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存,不存在则返回 null + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[afterSale.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + + // =========================== + // 售后类型/子类型自定义配置 + // =========================== + + /** + * 售后类型列表:返回系统级(warehouse_id IS NULL)+ 当前仓库自定义的合并列表。 + * 默认按 sort_order 升序、id 升序;支持分页、where 条件({operator, value} 规范)与排序。 + * + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {number} [data.pagination.page=1] 页码 + * @param {number} [data.pagination.pageSize=20] 每页数量(上限500) + * @param {Object} [data.where] 筛选条件,支持字段 id/type/name/is_system/is_enabled/sort_order/created_at/updated_at + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder },不传时默认 sort_order ASC, id ASC + * @return {Promise} 统一 success 包装,data 为 { list, pagination } + */ + async typeList(data = {}) { + const { ctx, service } = this; + const { pagination, sort } = data || {}; + const { where } = this.prepareWhereContext(data); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const result = await service.systems.afterSale.getTypeList({ warehouseId, where, pagination, sort }); + return this.success('ok', result); + } + + /** + * 创建仓库自定义售后类型。warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * + * @param {Object} data 请求体 + * @param {string} data.type 类型编码(仅小写字母/数字/下划线,不可与系统级编码重复) + * @param {string} data.name 类型名称(长度≤50) + * @param {number} [data.sort_order=0] 排序值 + * @param {number} [data.is_enabled=1] 是否启用(0/1) + * @return {Promise} 成功返回 success 包装及新记录;失败返回 fail 包装(含业务码) + */ + async typeCreate(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const { + type, + name, + sort_order: sortOrder, + is_enabled: isEnabled, + } = data || {}; + + try { + const result = await service.systems.afterSale.createType({ warehouseId, type, name, sortOrder, isEnabled }); + return this.success('售后类型创建成功', result); + } catch (e) { + return this.fail(e.message, { code: Number(e.code) || 400 }); + } + } + + /** + * 更新仓库自定义售后类型。仅允许修改 name/is_enabled/sort_order,type 编码不可变。 + * + * @param {Object} data 请求体 + * @param {number} data.id 类型主键ID + * @param {string} [data.name] 类型名称(长度≤50) + * @param {number} [data.is_enabled] 是否启用(0/1) + * @param {number} [data.sort_order] 排序值 + * @return {Promise} 成功返回 success 包装及更新后记录;失败返回 fail 包装(含业务码) + */ + async typeUpdate(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const { + id, + name, + sort_order: sortOrder, + is_enabled: isEnabled, + } = data || {}; + + try { + const result = await service.systems.afterSale.updateType({ warehouseId, id, name, sortOrder, isEnabled }); + return this.success('售后类型更新成功', result); + } catch (e) { + return this.fail(e.message, { code: Number(e.code) || 400 }); + } + } + + /** + * 删除仓库自定义售后类型。系统级类型禁止删除; + * 删除前检查该类型下是否存在当前仓库的自定义子类型,存在则拒绝(需先删除子类型)。 + * + * @param {Object} data 请求体 + * @param {number} data.id 类型主键ID + * @return {Promise} 成功返回 success 包装;失败返回 fail 包装(含业务码) + */ + async typeDelete(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const { id } = data || {}; + + try { + const result = await service.systems.afterSale.deleteType({ warehouseId, id }); + return this.success('售后类型删除成功', { data: result }); + } catch (e) { + return this.fail(e.message, { code: Number(e.code) || 400 }); + } + } + + /** + * 售后子类型列表:返回系统级 + 当前仓库自定义的合并列表,支持按 type 过滤与按 type 分组返回。 + * 默认按 sort_order 升序、id 升序。 + * + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {number} [data.pagination.page=1] 页码 + * @param {number} [data.pagination.pageSize=20] 每页数量(上限500) + * @param {Object} [data.where] 筛选条件,支持字段 id/type/sub_type/name/is_system/is_enabled/sort_order/created_at/updated_at + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder },不传时默认 sort_order ASC, id ASC + * @param {boolean} [data.group] 是否按 type 分组返回 groups(true 时额外返回 groups 数组) + * @return {Promise} 统一 success 包装,data 为 { list, pagination, groups? } + */ + async subTypeList(data = {}) { + const { ctx, service } = this; + const { pagination, sort, group } = data || {}; + const { where } = this.prepareWhereContext(data); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const result = await service.systems.afterSale.getSubTypeList({ warehouseId, where, pagination, sort, group }); + return this.success('ok', result); + } + + /** + * 创建仓库自定义售后子类型。warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * 所属类型必须存在(系统级或当前仓库自定义)且处于启用状态。 + * + * @param {Object} data 请求体 + * @param {string} data.type 所属类型编码(必须已存在且启用) + * @param {string} data.sub_type 子类型编码(仅小写字母/数字/下划线,不可与系统级同 type 下编码重复) + * @param {string} data.name 子类型名称(长度≤50) + * @param {number} [data.sort_order=0] 排序值 + * @param {number} [data.is_enabled=1] 是否启用(0/1) + * @return {Promise} 成功返回 success 包装及新记录;失败返回 fail 包装(含业务码) + */ + async subTypeCreate(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const { + type, + sub_type: subType, + name, + sort_order: sortOrder, + is_enabled: isEnabled, + } = data || {}; + + try { + const result = await service.systems.afterSale.createSubType({ warehouseId, type, subType, name, sortOrder, isEnabled }); + return this.success('售后子类型创建成功', result); + } catch (e) { + return this.fail(e.message, { code: Number(e.code) || 400 }); + } + } + + /** + * 更新仓库自定义售后子类型。仅允许修改 name/is_enabled/sort_order,type 与 sub_type 编码不可变。 + * + * @param {Object} data 请求体 + * @param {number} data.id 子类型主键ID + * @param {string} [data.name] 子类型名称(长度≤50) + * @param {number} [data.is_enabled] 是否启用(0/1) + * @param {number} [data.sort_order] 排序值 + * @return {Promise} 成功返回 success 包装及更新后记录;失败返回 fail 包装(含业务码) + */ + async subTypeUpdate(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const { + id, + name, + sort_order: sortOrder, + is_enabled: isEnabled, + } = data || {}; + + try { + const result = await service.systems.afterSale.updateSubType({ warehouseId, id, name, sortOrder, isEnabled }); + return this.success('售后子类型更新成功', result); + } catch (e) { + return this.fail(e.message, { code: Number(e.code) || 400 }); + } + } + + /** + * 删除仓库自定义售后子类型。系统级子类型禁止删除; + * 若该子类型已被当前仓库的售后单使用(wms_after_sale 存在引用),拒绝删除。 + * + * @param {Object} data 请求体 + * @param {number} data.id 子类型主键ID + * @return {Promise} 成功返回 success 包装;失败返回 fail 包装(含业务码) + */ + async subTypeDelete(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const { id } = data || {}; + + try { + const result = await service.systems.afterSale.deleteSubType({ warehouseId, id }); + return this.success('售后子类型删除成功', { data: result }); + } catch (e) { + return this.fail(e.message, { code: Number(e.code) || 400 }); + } + } + +} + +module.exports = AfterSaleMethodService; diff --git a/app/service/systemMethods/apiApp.js b/app/service/systemMethods/apiApp.js new file mode 100644 index 0000000..732720c --- /dev/null +++ b/app/service/systemMethods/apiApp.js @@ -0,0 +1,128 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 仓库 API 应用管理 Service + * 管理当前仓库的外部 API 应用(AppKey/Secret 生成、IP 白名单、限流等)。 + * 仓库隔离:所有操作自动按 ctx.user.store_id 过滤。 + */ +class ApiAppService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询当前仓库的 API 应用列表(分页)。 + * @param {Object} data 查询参数。 + * @return {Promise} 分页结果。 + */ + async list(data) { + try { + const result = await this.service.systems.apiApp.list(data || {}); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 查询单个 API 应用详情。 + * @param {Object} data 查询参数。 + * @param {number|string} data.id 应用 ID。 + * @return {Promise} 应用详情。 + */ + async detail(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + const defaultTypeId = await this.service.systems.apiApp.getDefaultInterfaceTypeId(); + const record = await ctx.model.ApiApp.findOne({ + attributes: [ + 'id', 'app_name', 'warehouse_id', 'self_app_key', 'self_app_secret', + 'self_ip_whitelist', 'callback_url', 'callback_functions', 'interface_type_id', + 'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at', + ], + where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: defaultTypeId }, + raw: true, + }); + if (!record) return this.fail('API应用不存在'); + record.self_app_secret = record.self_app_secret + ? String(record.self_app_secret).substring(0, 8) + '****' + : ''; + return this.success('获取成功', record); + } catch (e) { return this.fail(e.message); } + } + + /** + * 创建 API 应用,自动生成 AppKey 和 AppSecret。 + * @param {Object} data 创建参数。 + * @return {Promise} 创建结果(含完整 secret)。 + */ + async create(data) { + try { + const result = await this.service.systems.apiApp.create(data || {}); + return this.success('创建成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 更新 API 应用。 + * @param {Object} data 更新参数。 + * @return {Promise} 更新结果。 + */ + async update(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + const result = await this.service.systems.apiApp.update(id, fields); + return this.success('更新成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 删除/停用 API 应用。 + * @param {Object} data 删除参数。 + * @return {Promise} 删除结果。 + */ + async delete(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + await this.service.systems.apiApp.delete(id); + return this.success('删除成功'); + } catch (e) { return this.fail(e.message); } + } + + /** + * 重新生成 AppSecret。 + * @param {Object} data 参数。 + * @return {Promise} 新 secret。 + */ + async regenerateSecret(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + const result = await this.service.systems.apiApp.regenerateSecret(id); + return this.success('重新生成成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 拉取出站回调 method 注册表(管理端多选列表)。 + * @return {Promise} { list: [{method,name,description}], total }。 + */ + async listCallbackFunctions() { + try { + const result = this.service.systems.apiApp.listCallbackFunctions(); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } +} + +module.exports = ApiAppService; diff --git a/app/service/systemMethods/camera.js b/app/service/systemMethods/camera.js new file mode 100644 index 0000000..e4c25b8 --- /dev/null +++ b/app/service/systemMethods/camera.js @@ -0,0 +1,116 @@ +'use strict'; + +const MainService = require('../main'); + +class CameraService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,detail,setOsd,ptzControl,ptzStop,ptzPresetGoto,ptzPresetSet'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,detail,setOsd,ptzControl,ptzStop,ptzPresetGoto,ptzPresetSet'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async list(data) { + try { + const result = await this.service.systems.camera.list(data || {}); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } + + async detail(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('获取成功', await this.service.systems.camera.detail(parseInt(id))); + } catch (e) { return this.fail(e.message); } + } + + async create(data) { + try { + return this.success('创建成功', await this.service.systems.camera.create(data)); + } catch (e) { return this.fail(e.message); } + } + + async update(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('更新成功', await this.service.systems.camera.update(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + async setOsd(data) { + try { + return this.success('设置成功', await this.service.systems.camera.setOsd(data)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 云台方向控制(按下) + * @param {Object} data - 入参 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.computerId - 打印电脑ID(必填) + * @param {string} data.action - 云台方向(8 个位置,必填) + * @param {number} [data.speed] - 云台转速(1-7,默认 4) + * @return {Promise} 统一响应 + */ + async ptzControl(data) { + try { + return this.success('云台控制成功', await this.service.systems.camera.ptzControl(data)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 云台停止(松手) + * @param {Object} data - 入参 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.computerId - 打印电脑ID(必填) + * @param {string} data.action - 云台方向(必须与按下时一致,必填) + * @return {Promise} 统一响应 + */ + async ptzStop(data) { + try { + return this.success('云台已停止', await this.service.systems.camera.ptzStop(data)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 云台预置点跳转 + * @param {Object} data - 入参 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.computerId - 打印电脑ID(必填) + * @param {number|string} data.presetId - 预置点编号(1-256,必填) + * @return {Promise} 统一响应 + */ + async ptzPresetGoto(data) { + try { + return this.success('预置点跳转成功', await this.service.systems.camera.ptzPresetGoto(data)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 云台预置点设置 + * @param {Object} data - 入参 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.presetId - 预置点编号(1-256,必填) + * @return {Promise} 统一响应 + */ + async ptzPresetSet(data) { + try { + return this.success('预置点设置成功', await this.service.systems.camera.ptzPresetSet(data)); + } catch (e) { return this.fail(e.message); } + } + + async delete(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + await this.service.systems.camera.delete(parseInt(id)); + return this.success('删除成功'); + } catch (e) { return this.fail(e.message); } + } +} + +module.exports = CameraService; diff --git a/app/service/systemMethods/cameraServer.js b/app/service/systemMethods/cameraServer.js new file mode 100644 index 0000000..5b8ff72 --- /dev/null +++ b/app/service/systemMethods/cameraServer.js @@ -0,0 +1,54 @@ +'use strict'; + +const MainService = require('../main'); + +class CameraServerService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,detail'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,detail'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async list(data) { + try { + const result = await this.service.systems.cameraServer.list(data || {}); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } + + async detail(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('获取成功', await this.service.systems.cameraServer.detail(parseInt(id))); + } catch (e) { return this.fail(e.message); } + } + + async create(data) { + try { + return this.success('创建成功', await this.service.systems.cameraServer.create(data)); + } catch (e) { return this.fail(e.message); } + } + + async update(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('更新成功', await this.service.systems.cameraServer.update(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + async delete(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + await this.service.systems.cameraServer.delete(parseInt(id)); + return this.success('删除成功'); + } catch (e) { return this.fail(e.message); } + } +} + +module.exports = CameraServerService; diff --git a/app/service/systemMethods/comboGoods.js b/app/service/systemMethods/comboGoods.js new file mode 100644 index 0000000..8544f40 --- /dev/null +++ b/app/service/systemMethods/comboGoods.js @@ -0,0 +1,168 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 将输入值转换为有限数字。 + * + * @param {unknown} value 待转换的值。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 转换后的数字。 + */ +function toNumber(value, defaultValue = 0) { + const normalized = Number(value); + return Number.isFinite(normalized) ? normalized : defaultValue; +} + +/** + * 系统方法层:comboGoods(组合商品接口包装层)。 + * 负责参数解构、权限校验出口与统一成功/失败包装。 + */ +class ComboGoodsMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = 'list,search'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 组合商品列表查询(分页)。 + * + * @param {Object} data 请求参数。 + * @param {Object} [data.pagination] 分页参数 {page, pageSize}。 + * @param {Object} [data.where] 筛选条件 {combo_code, combo_name, status, warehouse_id}。 + * @return {Promise} 统一 success 包装的分页列表。 + */ + async list(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const pagination = requestData.pagination || {}; + const where = requestData.where || {}; + + const result = await service.systems.comboGoods.list({ + page: toNumber(pagination.page, 1), + pageSize: toNumber(pagination.pageSize, 20), + combo_code: where.combo_code, + combo_name: where.combo_name, + status: where.status, + warehouse_id: where.warehouse_id, + }); + + return this.success('查询成功', result); + } + + /** + * 创建组合商品。 + * + * @param {Object} data 请求参数。 + * @param {string} data.combo_code 组合商品编码。 + * @param {string} data.combo_name 组合商品名称。 + * @param {number} [data.warehouse_id] 仓库ID。 + * @param {string} [data.remark] 备注。 + * @param {string} [data.custom_code] 自定义编码。 + * @param {Object[]} data.items 子商品明细数组 [{item_goods_sku_id, item_quantity}]。 + * @return {Promise} 统一 success 包装的创建结果。 + */ + async create(data = {}) { + const { ctx, service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + + try { + const result = await service.systems.comboGoods.create({ + combo_code: requestData.combo_code, + combo_name: requestData.combo_name, + warehouse_id: requestData.warehouse_id, + remark: requestData.remark, + custom_code: requestData.custom_code, + items: requestData.items, + creator_id: ctx.user?.id, + }); + + return this.success('创建成功', result); + } catch (error) { + return this.fail(error.message || '创建失败'); + } + } + + /** + * 编辑组合商品。 + * + * @param {Object} data 请求参数。 + * @param {number} data.id 组合商品ID(必填)。 + * @param {string} [data.combo_name] 组合商品名称。 + * @param {number} [data.warehouse_id] 仓库ID。 + * @param {string} [data.remark] 备注。 + * @param {string} [data.custom_code] 自定义编码。 + * @param {number} [data.status] 状态 1-启用 0-停用。 + * @param {Object[]} [data.items] 子商品明细数组。 + * @return {Promise} 统一 success 包装的编辑结果。 + */ + async update(data = {}) { + const { ctx, service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + + try { + const result = await service.systems.comboGoods.update({ + id: requestData.id, + combo_name: requestData.combo_name, + warehouse_id: requestData.warehouse_id, + remark: requestData.remark, + custom_code: requestData.custom_code, + status: requestData.status, + items: requestData.items, + editor_id: ctx.user?.id, + }); + + return this.success('编辑成功', result); + } catch (error) { + return this.fail(error.message || '编辑失败'); + } + } + + /** + * 删除组合商品(软删除)。 + * + * @param {Object} data 请求参数。 + * @param {number} data.id 组合商品ID。 + * @return {Promise} 统一 success 包装的删除结果。 + */ + async delete(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + + try { + const result = await service.systems.comboGoods.delete({ + id: requestData.id, + }); + + return this.success('删除成功', result); + } catch (error) { + return this.fail(error.message || '删除失败'); + } + } + + /** + * 关键字搜索组合商品。 + * + * @param {Object} data 请求参数。 + * @param {string} data.keyword 搜索关键字。 + * @param {number} [data.limit=20] 最大返回条数。 + * @return {Promise} 统一 success 包装的搜索结果。 + */ + async search(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + + const result = await service.systems.comboGoods.search({ + keyword: requestData.keyword, + limit: requestData.limit, + }); + + return this.success('搜索成功', result); + } +} + +module.exports = ComboGoodsMethodService; diff --git a/app/service/systemMethods/config.js b/app/service/systemMethods/config.js index fd57921..849e9b0 100644 --- a/app/service/systemMethods/config.js +++ b/app/service/systemMethods/config.js @@ -12,7 +12,6 @@ class configService extends MainService { async list() { const { ctx, - app, } = this; const user = ctx.user; const result = { diff --git a/app/service/systemMethods/dashboard.js b/app/service/systemMethods/dashboard.js index ddd612e..495261d 100644 --- a/app/service/systemMethods/dashboard.js +++ b/app/service/systemMethods/dashboard.js @@ -10,33 +10,182 @@ class dashboardService extends MainService { const _noNeedLog = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog); } + async storeStats() { - const data = { + const { ctx } = this; + const storeType = String(ctx.user?.store_type || '').trim(); + + if (storeType === 'store') { + return await this.storeSideStoreStats(); + } + + // 仓库端:单仓查询 + const warehouseId = Number(ctx.user?.store_id); + if (!warehouseId) { + return this.fail('缺少仓库上下文'); + } + const stats = await this.queryWarehouseStats(warehouseId); + return this.success('ok', this.mergeStoreStats([ stats ])); + } + + async storeSideStoreStats() { + const { ctx } = this; + const storeId = Number(ctx.user?.store_id); + if (!storeId) { + return this.fail('缺少货主上下文'); + } + + // 获取签约仓库 + const contracts = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: storeId, auth_status: 2 }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0); + if (!warehouseIds.length) { + return this.success('ok', this.emptyStoreStats()); + } + + // 跨仓并行查询并汇总 + const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseStats(wid, storeId).catch(() => null))); + return this.success('ok', this.mergeStoreStats(results.filter(Boolean))); + } + + async queryWarehouseStats(warehouseId, storeId = null) { + const { ctx } = this; + const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const { Sequelize } = ctx.app; + const { Op } = Sequelize; + + const pendingBase = { + step: { [Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Op.ne]: 'padding' }, + status: { [Op.ne]: 'cancel' }, + }; + if (storeId) { + pendingBase.store_id = storeId; + } + + const now = new Date(); + const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + const todayEnd = new Date(todayStart.getTime() + 86400000); + const yesterdayStart = new Date(todayStart.getTime() - 86400000); + + const [ + totalPending, + todayNew, + yesterdayNew, + unassignedOrders, + unprintedOrders, + unpickedOrders, + pendingShipments, + todayOutbound, + interceptedOrders, + exceptionOrders, + recheckedOrders, + packedOrders, + ] = await Promise.all([ + model.count({ where: pendingBase }), + model.count({ where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: todayEnd } } }), + model.count({ where: { ...pendingBase, create_at: { [Op.gte]: yesterdayStart, [Op.lt]: todayStart } } }), + model.count({ where: { ...pendingBase, post_status: 'none' } }), + model.count({ where: { ...pendingBase, print_status: 'none' } }), + model.count({ where: { ...pendingBase, pick_status: 'none' } }), + model.count({ where: { ...pendingBase, outbound_status: { [Op.ne]: 'fin' } } }), + model.count({ where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd }, ...(storeId ? { store_id: storeId } : {}) } }), + model.count({ where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } } }), + model.count({ where: { ...pendingBase, step: 3 } }), + model.count({ where: { ...pendingBase, recheck_status: 'fin' } }), + model.count({ where: { ...pendingBase, pack_status: 'fin' } }), + ]); + + return { + warehouseId, + totalPending, + todayNew, + yesterdayNew, + unassignedOrders, + unprintedOrders, + unpickedOrders, + pendingShipments, + todayOutbound, + interceptedOrders, + exceptionOrders, + recheckedOrders, + packedOrders, + }; + } + + mergeStoreStats(results) { + const merged = { + totalPending: 0, todayNew: 0, yesterdayNew: 0, + unassignedOrders: 0, unprintedOrders: 0, unpickedOrders: 0, + pendingShipments: 0, todayOutbound: 0, interceptedOrders: 0, exceptionOrders: 0, + recheckedOrders: 0, packedOrders: 0, + }; + + for (const r of results) { + merged.totalPending += r.totalPending || 0; + merged.todayNew += r.todayNew || 0; + merged.yesterdayNew += r.yesterdayNew || 0; + merged.unassignedOrders += r.unassignedOrders || 0; + merged.unprintedOrders += r.unprintedOrders || 0; + merged.unpickedOrders += r.unpickedOrders || 0; + merged.pendingShipments += r.pendingShipments || 0; + merged.todayOutbound += r.todayOutbound || 0; + merged.interceptedOrders += r.interceptedOrders || 0; + merged.exceptionOrders += r.exceptionOrders || 0; + merged.recheckedOrders += r.recheckedOrders || 0; + merged.packedOrders += r.packedOrders || 0; + } + + const orderTrend = merged.yesterdayNew > 0 + ? parseFloat((((merged.todayNew - merged.yesterdayNew) / merged.yesterdayNew) * 100).toFixed(1)) + : (merged.todayNew > 0 ? 100 : 0); + + const totalForRate = merged.pendingShipments + merged.todayOutbound; + const outboundRate = totalForRate > 0 + ? parseFloat(((merged.todayOutbound / totalForRate) * 100).toFixed(2)) + : 0; + + const shipmentProgress = merged.totalPending > 0 + ? parseFloat((((merged.totalPending - merged.pendingShipments) / merged.totalPending) * 100).toFixed(0)) + : 0; + + return { code: 200, message: '成功', data: { - todayOrders: 13023, - orderTrend: 2, - - // 处理状态 - unassignedOrders: 15, // 未分配快递号 - unprintedOrders: 32, // 未打印 - unpickedOrders: 28, // 未拣货 - - // 发货相关 - pendingShipments: 6542, // 待发货 - shipmentProgress: 0, // 发货进度 - - // 出库相关 - todayOutbound: 6480, // 今日出库 - outboundRate: 49.77, // 出库完成率 - - // 异常订单 - interceptedOrders: 8, // 拦截订单 - exceptionOrders: 10, // 异常订单 + todayOrders: merged.totalPending + merged.todayOutbound, + orderTrend, + unassignedOrders: merged.unassignedOrders, + unprintedOrders: merged.unprintedOrders, + unpickedOrders: merged.unpickedOrders, + pendingShipments: merged.pendingShipments, + shipmentProgress, + todayOutbound: merged.todayOutbound, + outboundRate, + interceptedOrders: merged.interceptedOrders, + exceptionOrders: merged.exceptionOrders, + recheckedOrders: merged.recheckedOrders, + packedOrders: merged.packedOrders, + }, + }; + } + + emptyStoreStats() { + return { + code: 200, + message: '成功', + data: { + todayOrders: 0, orderTrend: 0, + unassignedOrders: 0, unprintedOrders: 0, unpickedOrders: 0, + pendingShipments: 0, shipmentProgress: 0, + todayOutbound: 0, outboundRate: 0, + interceptedOrders: 0, exceptionOrders: 0, + recheckedOrders: 0, packedOrders: 0, }, }; - return this.success('ok', data); } async warehouseStats() { const data = { @@ -66,274 +215,715 @@ class dashboardService extends MainService { }; return this.success('ok', data); } + /** + * 热销商品排行:统计仓库端/货主端范围内今日热销商品 Top 10。 + * + * 口径说明: + * - 今日窗口为 [今日 00:00, 当前时刻),昨日窗口为 [昨日 00:00, 今日 00:00); + * - value 为窗口内非取消、非异常、未删除订单的商品计划数量(plan_qty)合计; + * - trend 为今日销量相对昨日销量的环比百分比(保留一位小数),昨日为 0 且今日大于 0 时按 100 处理; + * - 已出库订单会从常用表迁移到配送表,因此常用表与配送表均参与统计。 + * + * 仓库端使用 ctx.user.store_id 作为仓库ID,单仓统计; + * 货主端(store_type 为 store)跨所有签约仓库并行统计并按商品聚合。 + * + * @return {Promise} 热销商品排行响应,data 为最多 10 条的排行数组。 + */ async hot_order_rank() { - const data = { - code: 200, - message: '成功', - data: [{ - id: 1, - name: '新***盒1', - sku: 'SKU202510081', - value: 51516, - trend: 18.5, - }, - { - id: 2, - name: '天***g', - sku: 'SKU202401002', - value: 43132, - trend: 12.3, - }, - { - id: 3, - name: '定****l', - sku: 'SKU202401003', - value: 39098, - trend: -2.5, - }, - { - id: 4, - name: '奥*****膜', - sku: 'SKU202401004', - value: 39087, - trend: 8.7, - }, - { - id: 5, - name: '美*****液', - sku: 'SKU202401005', - value: 25776, - trend: 15.2, - }, - { - id: 6, - name: '荣耀Magic6 Pro 1TB', - sku: 'SKU202401006', - value: 65, - trend: 5.4, - }, - { - id: 7, - name: '三星Galaxy S24 Ultra 512GB', - sku: 'SKU202401007', - value: 54, - trend: -3.8, - }, - { - id: 8, - name: '一加12 512GB', - sku: 'SKU202401008', - value: 43, - trend: 22.1, - }, - { - id: 9, - name: '真我GT5 Pro 1TB', - sku: 'SKU202401009', - value: 38, - trend: 9.6, - }, - { - id: 10, - name: '魅族21 Pro 512GB', - sku: 'SKU202401010', - value: 29, - trend: 4.2, - }, - ], - }; - return this.success('ok', data); - } - async express_ratio() { - const data = { - code: 200, - message: '成功', - data: [{ - name: '顺丰速运', - value: 50250, - itemStyle: { - color: '#409EFF', - }, - }, - { - name: '中通快递', - value: 34089, - itemStyle: { - color: '#67C23A', - }, - }, - { - name: '圆通速递', - value: 10567, - itemStyle: { - color: '#E6A23C', - }, - }, - { - name: '韵达快递', - value: 9023, - itemStyle: { - color: '#909399', - }, - }, - { - name: '申通快递', - value: 8089, - itemStyle: { - color: '#67023A', - }, - }, - { - name: '邮政EMS', - value: 4089, - itemStyle: { - color: '#97293A', - }, - }, - { - name: '京东物流', - value: 3023, - itemStyle: { - color: '#F56C6C', - }, - }, - { - name: '极兔速递', - value: 1089, - itemStyle: { - color: '#67913A', - }, - }, - { - name: '德邦快递', - value: 357, - itemStyle: { - color: '#9370DB', - }, - }, - { - name: '其他快递', - value: 5, - itemStyle: { - color: '#67313A', - }, - }, - ], - }; + const { ctx } = this; + const storeType = String(ctx.user?.store_type || '').trim(); - return this.success('ok', data); + if (storeType === 'store') { + return await this.storeSideHotOrderRank(); + } + + const warehouseId = Number(ctx.user?.store_id); + if (!warehouseId) { + return this.fail('缺少仓库上下文'); + } + const rankMap = await this.queryWarehouseHotOrderRank(warehouseId); + return this.success('ok', await this.formatHotOrderRank(rankMap)); + } + + /** + * 货主端热销商品排行:跨所有已签约仓库并行统计并按商品聚合。 + * + * @return {Promise} 热销商品排行响应。 + */ + async storeSideHotOrderRank() { + const { ctx } = this; + const storeId = Number(ctx.user?.store_id); + if (!storeId) { + return this.fail('缺少货主上下文'); + } + + // 获取签约仓库 + const contracts = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: storeId, auth_status: 2 }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0); + if (!warehouseIds.length) { + return this.success('ok', this.emptyHotOrderRank()); + } + + // 跨仓并行查询并汇总 + const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseHotOrderRank(wid, storeId).catch(() => null))); + return this.success('ok', await this.formatHotOrderRank(this.mergeHotOrderRank(results.filter(Boolean)))); + } + + /** + * 查询单个仓库的热销商品聚合结果。 + * + * 今日窗口同时覆盖订单常用表与配送表(已出库订单会迁移到配送表); + * 昨日窗口仅统计今日候选商品的销量作为环比基线,避免全量扫描。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number|null} [storeId=null] 货主ID,货主端传值以限定统计范围。 + * @return {Promise>} 商品键到 { name, currentValue, previousValue } 的映射, + * 商品键规则:有编码时为 code:商品编码,无编码时为 stock:库存商品ID。 + */ + async queryWarehouseHotOrderRank(warehouseId, storeId = null) { + const now = new Date(); + const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + const yesterdayStart = new Date(todayStart.getTime() - 86400000); + + // 今日窗口:常用表与配送表并行聚合 + const [ currentRows, dispatchRows ] = await Promise.all([ + this.queryHotOrderRankWindowRows(warehouseId, 'current', todayStart, now, storeId), + this.queryHotOrderRankWindowRows(warehouseId, 'dispatch', todayStart, now, storeId), + ]); + const currentMap = this.buildHotOrderRankMap(currentRows.concat(dispatchRows)); + if (currentMap.size === 0) { + return currentMap; + } + + // 昨日窗口:仅统计今日候选商品的销量作为环比基线 + const keyFilter = this.buildHotOrderRankKeyFilter(currentMap); + const [ prevCurrentRows, prevDispatchRows ] = await Promise.all([ + this.queryHotOrderRankWindowRows(warehouseId, 'current', yesterdayStart, todayStart, storeId, keyFilter), + this.queryHotOrderRankWindowRows(warehouseId, 'dispatch', yesterdayStart, todayStart, storeId, keyFilter), + ]); + + const rankMap = new Map(); + for (const [ key, entry ] of currentMap.entries()) { + rankMap.set(key, { ...entry, previousValue: 0 }); + } + const previousMap = this.buildHotOrderRankMap(prevCurrentRows.concat(prevDispatchRows)); + for (const [ key, prevEntry ] of previousMap.entries()) { + const target = rankMap.get(key); + if (target) { + target.previousValue = prevEntry.currentValue; + } + } + return rankMap; + } + + /** + * 查询单个订单分表在指定时间窗口内的商品销量分组。 + * + * @param {number} warehouseId 仓库ID。 + * @param {string} tableType 表类型:current(常用表)或 dispatch(配送表)。 + * @param {Date} startTime 窗口开始时间(含)。 + * @param {Date} endTime 窗口结束时间(不含)。 + * @param {number|null} [storeId=null] 货主ID,货主端传值以限定统计范围。 + * @param {Object|null} [keyFilter=null] 候选商品键过滤:{ itemCodes, stockIds },为空则统计全部商品。 + * @return {Promise>} 分组行数组 [{ item_code, stock_id, item_name, total_qty }]。 + */ + async queryHotOrderRankWindowRows(warehouseId, tableType, startTime, endTime, storeId = null, keyFilter = null) { + const { ctx } = this; + const isDispatch = tableType === 'dispatch'; + const orderModel = isDispatch + ? await ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId) + : await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const itemsModel = isDispatch + ? await ctx.model.OrderItemsFactory.getDispatchModel(warehouseId) + : await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + + const orderTableName = orderModel.getTableName(); + const itemsTableName = itemsModel.getTableName(); + const whereClauses = [ + 'o.status NOT IN (\'cancel\', \'error\')', + 'o.delete_at IS NULL', + 'o.create_at >= :startTime', + 'o.create_at < :endTime', + ]; + const replacements = { startTime, endTime }; + if (storeId) { + whereClauses.push('o.store_id = :storeId'); + replacements.storeId = storeId; + } + if (keyFilter) { + const keyParts = []; + if (Array.isArray(keyFilter.itemCodes) && keyFilter.itemCodes.length > 0) { + keyParts.push('i.item_code IN (:itemCodes)'); + replacements.itemCodes = keyFilter.itemCodes; + } + if (Array.isArray(keyFilter.stockIds) && keyFilter.stockIds.length > 0) { + keyParts.push('i.stock_id IN (:stockIds)'); + replacements.stockIds = keyFilter.stockIds; + } + if (keyParts.length > 0) { + whereClauses.push(`(${keyParts.join(' OR ')})`); + } + } + + const rows = await ctx.model.query(` + SELECT + i.item_code, + i.stock_id, + MAX(i.item_name) AS item_name, + SUM(i.plan_qty) AS total_qty + FROM \`${itemsTableName}\` AS i + INNER JOIN \`${orderTableName}\` AS o ON o.id = i.order_id + WHERE ${whereClauses.join('\n AND ')} + GROUP BY i.item_code, i.stock_id + `, { + replacements, + type: ctx.app.Sequelize.QueryTypes.SELECT, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 将分组行转换为商品键到销量聚合的映射。 + * + * 商品键规则:优先使用商品编码(code:商品编码);无编码时使用库存商品ID(stock:库存商品ID); + * 编码与库存ID均缺失或销量不大于 0 的行会被跳过。 + * + * @param {Array} rows 分组行数组 [{ item_code, stock_id, item_name, total_qty }]。 + * @return {Map} 商品键到 { name, stockId, currentValue } 的映射, + * stockId 为库存商品ID(stock_warehouse.id)。 + */ + buildHotOrderRankMap(rows) { + const rankMap = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + const itemCode = String(row.item_code || '').trim(); + const stockId = Number(row.stock_id) || 0; + const totalQty = Number(row.total_qty) || 0; + if (totalQty <= 0) { + continue; + } + const key = itemCode ? `code:${itemCode}` : `stock:${stockId}`; + if (key === 'stock:0') { + continue; + } + const itemName = String(row.item_name || '').trim(); + const existing = rankMap.get(key); + if (existing) { + existing.currentValue += totalQty; + if (!existing.name && itemName) { + existing.name = itemName; + } + if (!existing.stockId && stockId > 0) { + existing.stockId = stockId; + } + } else { + rankMap.set(key, { name: itemName, stockId, currentValue: totalQty }); + } + } + return rankMap; + } + + /** + * 根据商品键映射构造昨日窗口的候选键过滤条件。 + * + * @param {Map} rankMap 商品键映射。 + * @return {Object} { itemCodes, stockIds } 候选商品编码与库存商品ID数组。 + */ + buildHotOrderRankKeyFilter(rankMap) { + const itemCodes = []; + const stockIds = []; + for (const key of rankMap.keys()) { + if (key.startsWith('code:')) { + itemCodes.push(key.slice(5)); + } else if (key.startsWith('stock:')) { + const stockId = Number(key.slice(6)); + if (stockId > 0) { + stockIds.push(stockId); + } + } + } + return { itemCodes, stockIds }; + } + + /** + * 合并多个仓库的热销商品聚合映射(货主端跨仓汇总)。 + * + * @param {Array>} results 各仓库的聚合映射数组。 + * @return {Map} 合并后的商品键到聚合数据(含 stockId)的映射。 + */ + mergeHotOrderRank(results) { + const merged = new Map(); + for (const rankMap of Array.isArray(results) ? results : []) { + if (!(rankMap instanceof Map)) { + continue; + } + for (const [ key, entry ] of rankMap.entries()) { + const existing = merged.get(key); + if (existing) { + existing.currentValue += entry.currentValue || 0; + existing.previousValue += entry.previousValue || 0; + if (!existing.name && entry.name) { + existing.name = entry.name; + } + if (!existing.stockId && entry.stockId) { + existing.stockId = entry.stockId; + } + } else { + merged.set(key, { + name: entry.name || '', + stockId: entry.stockId || 0, + currentValue: entry.currentValue || 0, + previousValue: entry.previousValue || 0, + }); + } + } + } + return merged; + } + + /** + * 批量查询库存商品信息,用于补充无编码商品的名称与编码。 + * + * @param {Array} stockIds 库存商品ID数组。 + * @return {Promise>} 库存商品ID到 { item_code, item_name } 的映射。 + */ + async loadHotOrderRankStockInfo(stockIds) { + const { ctx } = this; + const uniqueStockIds = [ ...new Set((Array.isArray(stockIds) ? stockIds : []).filter(id => Number(id) > 0)) ]; + if (uniqueStockIds.length === 0) { + return new Map(); + } + const { Op } = ctx.app.Sequelize; + const rows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: uniqueStockIds }, deleted_at: null }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }); + const stockInfoMap = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + stockInfoMap.set(Number(row.id), { + item_code: String(row.item_code || '').trim(), + item_name: String(row.item_name || '').trim(), + }); + } + return stockInfoMap; + } + + /** + * 解析商品键对应的商品名称与库存商品ID。 + * + * sku 统一取库存商品ID(stock_warehouse.id):库存键(stock:库存商品ID)直接取键内ID, + * 编码键(code:商品编码)取聚合条目携带的 stockId;均缺失时回退商品编码字符串。 + * 名称为聚合行携带的商品名,库存键无名称时回退库存主表信息或 商品+库存ID 兜底。 + * + * @param {string} key 商品键。 + * @param {Object} entry 聚合数据 { name, stockId, currentValue, previousValue }。 + * @param {Map} stockInfoMap 库存商品信息映射。 + * @return {Object} { name, sku } 商品展示信息(sku 为库存商品ID,缺失时回退商品编码字符串)。 + */ + resolveHotOrderRankProduct(key, entry, stockInfoMap) { + const stockId = key.startsWith('stock:') + ? Number(key.slice(6)) + : (Number(entry && entry.stockId) || 0); + if (stockId > 0) { + const stockInfo = stockInfoMap.get(stockId) || {}; + return { + name: entry.name || stockInfo.item_name || `商品${stockId}`, + sku: stockId, + }; + } + const itemCode = key.startsWith('code:') ? key.slice(5) : ''; + return { name: entry.name || itemCode, sku: itemCode }; + } + + /** + * 对商品名称做脱敏处理:保留前两个字符与后两个字符,中间以三个星号替代。 + * 名称长度不足 4 个字符时无法按规则脱敏,统一返回 ***。 + * + * @param {string} name 原始商品名称。 + * @return {string} 脱敏后的商品名称。 + */ + maskHotOrderRankName(name) { + const value = String(name || '').trim(); + if (value.length >= 4) { + return `${value.slice(0, 2)}***${value.slice(-2)}`; + } + return '***'; + } + + /** + * 将聚合映射格式化为热销商品排行响应数据。 + * + * 按今日销量降序取前 10 条;trend 为今日销量相对昨日的环比百分比(保留一位小数), + * 昨日为 0 且今日大于 0 时按 100 处理;name 做脱敏处理(前2字符+***+后2字符, + * 长度不足 4 字符时返回 ***),sku 为库存商品ID(stock_warehouse.id)。 + * + * @param {Map} rankMap 商品键到聚合数据的映射。 + * @return {Promise} { code: 200, message: '成功', data: [{ id, name, sku, value, trend }] }。 + */ + async formatHotOrderRank(rankMap) { + if (!rankMap || rankMap.size === 0) { + return this.emptyHotOrderRank(); + } + + const stockIds = []; + for (const key of rankMap.keys()) { + if (key.startsWith('stock:')) { + const stockId = Number(key.slice(6)); + if (stockId > 0) { + stockIds.push(stockId); + } + } + } + const stockInfoMap = await this.loadHotOrderRankStockInfo(stockIds); + + const sorted = [ ...rankMap.entries() ].sort((left, right) => right[1].currentValue - left[1].currentValue); + return { + code: 200, + message: '成功', + data: sorted.slice(0, 10).map(([ key, entry ], index) => { + const { name, sku } = this.resolveHotOrderRankProduct(key, entry, stockInfoMap); + const previousValue = entry.previousValue || 0; + const trend = previousValue > 0 + ? parseFloat((((entry.currentValue - previousValue) / previousValue) * 100).toFixed(1)) + : (entry.currentValue > 0 ? 100 : 0); + return { id: index + 1, name: this.maskHotOrderRankName(name), sku, value: entry.currentValue, trend }; + }), + }; + } + + /** + * 构造热销商品排行的空响应数据。 + * + * @return {Object} { code: 200, message: '成功', data: [] }。 + */ + emptyHotOrderRank() { + return { code: 200, message: '成功', data: [] }; + } + + async express_ratio() { + const { ctx } = this; + const storeType = String(ctx.user?.store_type || '').trim(); + + if (storeType === 'store') { + return await this.storeSideExpressRatio(); + } + + const warehouseId = Number(ctx.user?.store_id); + if (!warehouseId) { + return this.fail('缺少仓库上下文'); + } + const nameValueMap = await this.queryWarehouseExpressRatio(warehouseId); + return this.success('ok', this.formatChartData(nameValueMap)); + } + + async storeSideExpressRatio() { + const { ctx } = this; + const storeId = Number(ctx.user?.store_id); + if (!storeId) { + return this.fail('缺少货主上下文'); + } + + const contracts = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: storeId, auth_status: 2 }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0); + if (!warehouseIds.length) { + return this.success('ok', this.emptyChartData()); + } + + const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseExpressRatio(wid).catch(() => null))); + return this.success('ok', this.mergeChartData(results.filter(Boolean))); + } + + async queryWarehouseExpressRatio(warehouseId) { + const { ctx } = this; + const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const { Sequelize } = ctx.app; + + const rows = await model.findAll({ + attributes: [ + 'logistics_name', + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'value' ], + ], + where: { + step: { [Sequelize.Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Sequelize.Op.ne]: 'padding' }, + status: { [Sequelize.Op.ne]: 'cancel' }, + }, + group: [ 'logistics_name' ], + order: [[ Sequelize.fn('COUNT', Sequelize.col('id')), 'DESC' ]], + raw: true, + }); + + const nameValueMap = new Map(); + for (const row of rows) { + nameValueMap.set(row.logistics_name || '未指定快递', Number(row.value) || 0); + } + return nameValueMap; + } + + mergeChartData(results) { + const merged = new Map(); + for (const map of results) { + for (const [ name, value ] of map.entries()) { + merged.set(name, (merged.get(name) || 0) + value); + } + } + return this.formatChartData(merged); + } + + formatChartData(nameValueMap) { + if (!nameValueMap || nameValueMap.size === 0) { + return { code: 200, message: '成功', data: [] }; + } + + const colorPalette = [ + '#409EFF', '#67C23A', '#E6A23C', '#909399', '#67023A', + '#97293A', '#F56C6C', '#67913A', '#9370DB', '#67313A', + '#3AA1FF', '#36CFC9', '#FFC53D', '#FF7A45', '#597EF7', + ]; + + const sorted = [ ...nameValueMap.entries() ].sort((a, b) => b[1] - a[1]); + + return { + code: 200, + message: '成功', + data: sorted.map(([ name, value ], index) => ({ + name, + value, + itemStyle: { color: colorPalette[index % colorPalette.length] }, + })), + }; + } + + emptyChartData() { + return { + code: 200, + message: '成功', + data: [], + }; } async platform_distribution() { - const data = { - code: 200, - message: '成功', - data: [{ - name: '抖音', - value: 50250, - itemStyle: { - color: '#409EFF', - }, - }, - { - name: '拼多多', - value: 34089, - itemStyle: { - color: '#67C23A', - }, - }, - { - name: '小红书', - value: 8089, - itemStyle: { - color: '#67023A', - }, - }, - { - name: '淘宝', - value: 10567, - itemStyle: { - color: '#E6A23C', - }, - }, - { - name: '快手', - value: 9023, - itemStyle: { - color: '#909399', - }, - }, - { - name: '天猫', - value: 4089, - itemStyle: { - color: '#97293A', - }, - }, - { - name: '视频号', - value: 3023, - itemStyle: { - color: '#606399', - }, - }, - { - name: '阿里巴巴', - value: 1089, - itemStyle: { - color: '#67913A', - }, - }, - { - name: '其他', - value: 357, - itemStyle: { - color: '#9370DB', - }, - }, - { - name: 'TITOK', - value: 55, - itemStyle: { - color: '#17313A', - }, - }, - { - name: '京东', - value: 45, - itemStyle: { - color: '#F56C6C', - }, - }, - { - name: '德物', - value: 5, - itemStyle: { - color: '#67313A', - }, - }, - ], - }; - return this.success('ok', data); + const { ctx } = this; + const storeType = String(ctx.user?.store_type || '').trim(); + + if (storeType === 'store') { + return await this.storeSidePlatformDistribution(); + } + + const warehouseId = Number(ctx.user?.store_id); + if (!warehouseId) { + return this.fail('缺少仓库上下文'); + } + const nameValueMap = await this.queryWarehousePlatformDistribution(warehouseId); + return this.success('ok', this.formatChartData(nameValueMap)); } + + async storeSidePlatformDistribution() { + const { ctx } = this; + const storeId = Number(ctx.user?.store_id); + if (!storeId) { + return this.fail('缺少货主上下文'); + } + + const contracts = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: storeId, auth_status: 2 }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0); + if (!warehouseIds.length) { + return this.success('ok', this.emptyChartData()); + } + + const results = await Promise.all(warehouseIds.map(wid => this.queryWarehousePlatformDistribution(wid).catch(() => null))); + return this.success('ok', this.mergeChartData(results.filter(Boolean))); + } + + async queryWarehousePlatformDistribution(warehouseId) { + const { ctx } = this; + const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const { Sequelize } = ctx.app; + + const rows = await model.findAll({ + attributes: [ + 'sys_platform_name', + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'value' ], + ], + where: { + step: { [Sequelize.Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Sequelize.Op.ne]: 'padding' }, + status: { [Sequelize.Op.ne]: 'cancel' }, + }, + group: [ 'sys_platform_name' ], + order: [[ Sequelize.fn('COUNT', Sequelize.col('id')), 'DESC' ]], + raw: true, + }); + + const nameValueMap = new Map(); + for (const row of rows) { + nameValueMap.set(row.sys_platform_name || '未指定平台', Number(row.value) || 0); + } + return nameValueMap; + } + /** + * 订单趋势统计:按小时统计当日订单数与发货数 + * + * 口径说明: + * - orders:待处理表订单按创建时间(create_at)小时分组统计; + * - shipments:配送表与待处理表两表汇总—— + * - 配送表记录按发货时间(delivery_time)小时分组统计; + * - 待处理表已复核记录(recheck_status 为 fin)视为已发货,优先按复核时间(recheck_time)小时分组统计, + * recheck_time 为空时回退使用 create_at; + * - 配送表记录由待处理表迁移并同步删除源记录,两表数据无重叠,直接汇总不会重复计数。 + * + * @return {Object} 包含 categories(时段)、orders(订单数)、shipments(发货数)和 summary(汇总)的响应数据 + */ async order_trend() { + const { ctx } = this; + const warehouseId = ctx.user?.store_id; + + if (!warehouseId) { + return this.fail('缺少仓库上下文'); + } + + const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const dispatchModel = await ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId); + const { Sequelize } = ctx.app; + const { Op } = Sequelize; + + // 今日时间范围 + const now = new Date(); + const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + const currentHour = now.getHours(); + + // 时间段:08:00 到当前小时(最晚 23:00),若当前小时早于 08:00 则从 08:00 开始 + const startHour = 8; + const endHour = currentHour < startHour ? startHour : Math.min(currentHour, 23); + + // 生成 categories 和初始化小时映射 + const categories = []; + const orderMap = {}; + const shipmentMap = {}; + for (let h = startHour; h <= endHour; h++) { + const key = `${String(h).padStart(2, '0')}:00`; + categories.push(key); + orderMap[h] = 0; + shipmentMap[h] = 0; + } + + // 查询订单数按创建小时分组 + const orderRows = await model.findAll({ + attributes: [ + [ Sequelize.fn('HOUR', Sequelize.col('create_at')), 'hour' ], + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ], + ], + where: { + step: { [Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Op.ne]: 'padding' }, + status: { [Op.ne]: 'cancel' }, + create_at: { [Op.gte]: todayStart, [Op.lte]: now }, + }, + group: [ Sequelize.fn('HOUR', Sequelize.col('create_at')) ], + raw: true, + }); + + // 查询配送表发货数按发货小时分组(已进入配送流程的记录按 delivery_time 统计) + const dispatchShipmentRows = await dispatchModel.findAll({ + attributes: [ + [ Sequelize.fn('HOUR', Sequelize.col('delivery_time')), 'hour' ], + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ], + ], + where: { + dispatch_lane: 'm4', + delivery_time: { [Op.gte]: todayStart, [Op.lte]: now }, + }, + group: [ Sequelize.fn('HOUR', Sequelize.col('delivery_time')) ], + raw: true, + }); + + // 查询待处理表已复核发货数按复核小时分组(已复核视为已发货,优先按 recheck_time 统计,为空时回退 create_at) + const recheckTimeAttr = Sequelize.fn('COALESCE', Sequelize.col('recheck_time'), Sequelize.col('create_at')); + const recheckShipmentRows = await model.findAll({ + attributes: [ + [ Sequelize.fn('HOUR', recheckTimeAttr), 'hour' ], + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ], + ], + where: { + step: { [Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Op.ne]: 'padding' }, + status: { [Op.ne]: 'cancel' }, + recheck_status: 'fin', + [Op.or]: [ + { recheck_time: { [Op.gte]: todayStart, [Op.lte]: now } }, + { recheck_time: null, create_at: { [Op.gte]: todayStart, [Op.lte]: now } }, + ], + }, + group: [ Sequelize.fn('HOUR', recheckTimeAttr) ], + raw: true, + }); + + // 将查询结果填充到小时映射(发货数为配送表与待处理表两表汇总) + for (const row of orderRows) { + orderMap[row.hour] = Number(row.cnt); + } + for (const row of dispatchShipmentRows) { + shipmentMap[row.hour] = (shipmentMap[row.hour] || 0) + Number(row.cnt); + } + for (const row of recheckShipmentRows) { + shipmentMap[row.hour] = (shipmentMap[row.hour] || 0) + Number(row.cnt); + } + + // 按 categories 顺序构建 orders / shipments 数组 + const orders = categories.map(cat => orderMap[parseInt(cat, 10)] || 0); + const shipments = categories.map(cat => shipmentMap[parseInt(cat, 10)] || 0); + + // 汇总计算 + const totalOrders = orders.reduce((sum, v) => sum + v, 0); + const totalShipments = shipments.reduce((sum, v) => sum + v, 0); + const shipmentRate = totalOrders > 0 + ? parseFloat(((totalShipments / totalOrders) * 100).toFixed(1)) + : 0; + + // 找订单峰值小时 + let peakHour = categories[0] || '08:00'; + let peakOrders = 0; + for (let i = 0; i < categories.length; i++) { + if (orders[i] > peakOrders) { + peakOrders = orders[i]; + peakHour = categories[i]; + } + } + + // 当天日期 YYYY-MM-DD + const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`; + const data = { code: 200, message: '成功', data: { range: 'day', - date: '2024-01-15', + date: dateStr, summary: { - total_orders: 1256, - total_shipments: 892, - shipment_rate: 71.0, - peak_hour: '15:00', - peak_orders: 178, + total_orders: totalOrders, + total_shipments: totalShipments, + shipment_rate: shipmentRate, + peak_hour: peakHour, + peak_orders: peakOrders, }, - categories: [ '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00' ], - orders: [ 138, 84378, 102120, 129156, 153020, 153020, 153020, 153020, 153020, 153020 ], - shipments: [ 0, 30000, 60000, 70000, 86479, 86479, 86479, 86479, 86479, 86479 ], + categories, + orders, + shipments, }, }; + return this.success('ok', data); } } diff --git a/app/service/systemMethods/frontConfig.js b/app/service/systemMethods/frontConfig.js new file mode 100644 index 0000000..90aaad6 --- /dev/null +++ b/app/service/systemMethods/frontConfig.js @@ -0,0 +1,287 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 系统方法层:frontConfig(前端独立部署配置接口包装层)。 + * + * 业务实现全部委托 ctx.service.systems.frontConfig:本层只做参数白名单过滤、 + * 鉴权出口与统一成功/失败包装。 + */ +class FrontConfigMethodsService extends MainService { + constructor(ctx) { + super(ctx); + // 公共按域名拉取:免登录、免权限、免鉴权(保留系统日志,与 workbench 公共接口口径一致) + // 注意:getByDomain 是唯一免登录接口;域名验证接口(setDomain/getDomain/checkDomain)一律需登录 + const _noNeedLogin = 'getByDomain'; + // settings 页配置接口:需登录、免权限、免鉴权(权限由业务层 isWarehouse 判定),不记系统日志 + const _noNeedRight = 'getByDomain,getInfo,getCert,saveInfo,saveCert,setDomain,getDomain,checkDomain'; + const _noNeedLog = 'getInfo,getCert,saveInfo,saveCert,setDomain,getDomain,checkDomain'; + const _noNeedAuth = 'getByDomain,getInfo,getCert,saveInfo,saveCert,setDomain,getDomain,checkDomain'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 获取前端独立部署业务服务(systems/frontConfig)。 + * + * @return {Object|null} 业务服务实例;不可用时返回 null。 + */ + getFrontConfigService() { + return (this.service && this.service.systems && this.service.systems.frontConfig) || null; + } + + /** + * 按域名拉取仓库前端公开配置(公共无鉴权接口)。 + * + * 安全红线:响应仅含公开字段(domain/title/logo_url/login_bg_url/favicon_url/theme), + * 不含 cert_pem/key_pem/cert_path/key_path/sync_status/sync_attempts/last_sync_error 等内部字段。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} data.domain 待查询域名(必填,非空)。 + * @return {Promise} 统一响应结构;命中返回公开字段配置(code=200), + * 未登记域名返回 code=404「域名未配置」。 + */ + async getByDomain(data = {}) { + const { domain } = data || {}; + + const targetService = this.getFrontConfigService(); + if (!targetService || typeof targetService.getByDomain !== 'function') { + return this.fail('获取前端配置失败', { code: 500 }); + } + + try { + const result = await targetService.getByDomain(domain); + return this.success('获取成功', { ...result, code: 200 }); + } catch (error) { + return this.fail(error.message || '获取前端配置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 查询当前仓库前端独立部署品牌配置(settings 页回显,需登录)。 + * + * 仅返回品牌与基础字段(warehouse_id/domain/title/logo_url/favicon_url/login_bg_url/theme/updated_at), + * 不含证书/私钥原文与同步状态等内部字段(证书回显走 frontConfig.getCert)。 + * + * @return {Promise} 统一响应结果。 + */ + async getInfo() { + const targetService = this.getFrontConfigService(); + if (!targetService || typeof targetService.getInfo !== 'function') { + return this.fail('获取前端配置失败', { code: 500 }); + } + + try { + const result = await targetService.getInfo(); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取前端配置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 查询当前仓库前端独立部署证书配置(settings 页回显,需登录)。 + * + * 响应含证书原文(cert_pem)与私钥原文(key_pem,取自 cert_key 列), + * 仅供仓库主体登录后的 settings 页回显,公共无鉴权接口 frontConfig.getByDomain + * 仍只返回公开字段白名单。 + * + * @return {Promise} 统一响应结果。 + */ + async getCert() { + const targetService = this.getFrontConfigService(); + if (!targetService || typeof targetService.getCert !== 'function') { + return this.fail('获取前端证书配置失败', { code: 500 }); + } + + try { + const result = await targetService.getCert(); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取前端证书配置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 保存当前仓库前端独立部署品牌配置(upsert,一仓一行,仅品牌字段部分更新,需登录)。 + * + * domain 与证书字段不再受理:domain 变更必须走 frontConfig.setDomain(域名验证通过后方可上传证书); + * cert_pem/key_pem/cert_path/key_path/cert_expire_at 一律被白名单过滤忽略。 + * + * @param {Object} data 请求参数。 + * @param {string} [data.title] 站点标题(≤100 字符,空值清空)。 + * @param {string} [data.logo_url] Logo 地址(≤255 字符,空值清空)。 + * @param {string} [data.favicon_url] 站点 favicon 图标地址(≤255 字符,空值清空)。 + * @param {string} [data.login_bg_url] 登录页背景图地址(≤255 字符,空值清空)。 + * @param {Object|string} [data.theme] 主题配置(合法 JSON 对象或 JSON 字符串,空值清空)。 + * @return {Promise} 统一响应结果。 + */ + async saveInfo(data = {}) { + const targetService = this.getFrontConfigService(); + if (!targetService || typeof targetService.saveInfo !== 'function') { + return this.fail('保存前端配置失败', { code: 500 }); + } + + try { + const source = data || {}; + const params = {}; + + // domain/cert_path/key_path/cert_pem/key_pem/cert_expire_at 均不受理: + // domain 变更走 setDomain,证书与有效期字段由后端权威维护,前端传值直接忽略 + for (const key of [ 'title', 'logo_url', 'favicon_url', 'login_bg_url', 'theme' ]) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + params[key] = source[key]; + } + } + + const result = await targetService.saveInfo(params); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '保存前端配置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 上传当前仓库前端独立部署证书(需登录、仅仓库主体)。 + * + * domain 不再受理:域名一律取库内已设置且验证通过的值(前端若仍传 data.domain 一律忽略), + * 未设置域名或域名未通过 TXT 验证时由业务层返回 400。 + * 后端自动写入 cert_expire_at(证书 validTo 权威值),证书/私钥内容直接入库(不落盘), + * 保存后清理该域名的公共拉取缓存并返回证书配置输出 + * (响应含证书/私钥原文回显,13 字段,口径与 frontConfig.getCert 一致)。 + * + * 域名切换提示:待验证域名提升为生效域名时会清空证书 5 列并重置同步状态(域名已变,证书必须 + * 重新上传);前置闸门与 SAN/CN 覆盖校验始终以生效域名为准。 + * + * @param {Object} data 请求参数。 + * @param {string} data.pem 证书 PEM 文本(必填)。 + * @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。 + * @return {Promise} 统一响应结果。 + */ + async saveCert(data = {}) { + const targetService = this.getFrontConfigService(); + if (!targetService || typeof targetService.saveCert !== 'function') { + return this.fail('上传前端证书失败', { code: 500 }); + } + + try { + const source = data || {}; + const { pem, key } = source; + + // data.domain 不再受理:域名只认库内已设置并验证通过的值,前端若仍传 domain 一律忽略 + const result = await targetService.saveCert({ + pem, + key, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '上传前端证书失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 设置当前仓库前端独立部署域名(需登录、仅仓库主体)。 + * + * 设置成功只登记待验证域名并下发一次性 DNS TXT 校验记录(pending_verify_host / pending_verify_value) + * 与 CNAME 目标(cname);生效域名、证书与同步状态不会因本接口改变。 + * + * 两阶段切换(本次改造):本接口只登记待验证域名(pending_domain)并下发 TXT 校验码,不直接 + * 改动生效域名、证书与同步状态——切换期间旧域名全程可用,改错域名只要不配置 TXT 记录就不会生效; + * TXT 校验通过后由提升逻辑切换生效域名,届时旧域名进入 retired_domain 下线队列、证书被清空并 + * 重置同步状态(需重新上传证书)。入参为当前生效域名时表示「取消待切换」。 + * + * @param {Object} data 请求参数。 + * @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一)。 + * @return {Promise} 统一响应结果(code=1);data 含生效域名组 9 字段 + * (warehouse_id/domain/domain_status/verify_host/verify_value/cname/verified_at/attempts/last_error) + * + 待验证域名组 7 字段(pending_domain/pending_verify_host/pending_verify_value/pending_attempts/ + * pending_last_error/pending_created_at/pending_active)。 + */ + async setDomain(data = {}) { + const targetService = this.getFrontConfigService(); + if (!targetService || typeof targetService.setDomain !== 'function') { + return this.fail('设置域名失败', { code: 500 }); + } + + try { + const result = await targetService.setDomain(data || {}); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '设置域名失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 查询当前仓库前端独立部署域名与验证状态(需登录、仅仓库主体)。 + * + * 返回待校验的 verify_host/verify_value 与 cname;domain_status=1(已验证)时 + * verify_host/verify_value 返回空串(校验令牌已无用途);无记录时返回空值默认。 + * + * 两阶段切换后响应在既有 9 个字段之后追加待验证域名组(pending_domain / pending_verify_host / + * pending_verify_value / pending_attempts / pending_last_error / pending_created_at / pending_active; + * 无待验证域名时依次为 ''/''/''/0/''/null/false)。待验证域名的校验码始终回显——该域名尚未生效, + * 需据此配置 TXT 记录;生效域名已验证时既有 verify_host/verify_value 仍返回空串(口径不变)。 + * + * @return {Promise} 统一响应结果(code=1);data 含生效域名组 9 字段 + * (warehouse_id/domain/domain_status/verify_host/verify_value/cname/verified_at/attempts/last_error) + * + 待验证域名组 7 字段(pending_domain/pending_verify_host/pending_verify_value/pending_attempts/ + * pending_last_error/pending_created_at/pending_active)。 + */ + async getDomain() { + const targetService = this.getFrontConfigService(); + if (!targetService || typeof targetService.getDomain !== 'function') { + return this.fail('获取域名配置失败', { code: 500 }); + } + + try { + const result = await targetService.getDomain(); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取域名配置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 主动校验当前仓库前端独立部署域名的 DNS TXT 记录(需登录、仅仓库主体)。 + * + * 校验结果会回写 domain_status/domain_verified_at/attempts/last_error; + * 两阶段切换后:存在待验证域名(pending_active=true)时校验的是待验证域名的 TXT 记录,通过即 + * 提升为生效域名(旧域名入 retired_domain 下线队列、证书清空并重置同步状态);不通过只累加 + * pending_attempts 并记 pending_last_error,生效域名与证书不受影响。无待验证域名时保持原口径 + * 回写 domain_status/domain_verified_at/attempts/last_error。 + * 响应额外含 verified(本次是否通过)与 resolved_values(本次解析到的 TXT 值,最多 5 条)。 + * + * @return {Promise} 统一响应结果(code=1);未设置域名时 code=400。 + */ + async checkDomain() { + const targetService = this.getFrontConfigService(); + if (!targetService || typeof targetService.checkDomain !== 'function') { + return this.fail('校验域名失败', { code: 500 }); + } + + try { + const result = await targetService.checkDomain(); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '校验域名失败', { + code: Number(error.code) || 500, + }); + } + } +} + +module.exports = FrontConfigMethodsService; diff --git a/app/service/systemMethods/inbox.js b/app/service/systemMethods/inbox.js new file mode 100644 index 0000000..e0413d4 --- /dev/null +++ b/app/service/systemMethods/inbox.js @@ -0,0 +1,331 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 站内信系统方法层。 + * 提供需要用户权限的内部管理接口。 + */ +class InboxSystemService extends MainService { + /** + * 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。 + * @return {{list: Function, quickList: Function, members: Function, disable: Function, update: Function, reset: Function, messages: Function, checkAuth: Function}} 群管理子入口方法集合。 + */ + get group() { + return { + list: data => this.groupList(data), + quickList: data => this.groupQuickList(data), + members: data => this.groupMembers(data), + disable: data => this.groupDisable(data), + update: data => this.groupUpdate(data), + reset: data => this.groupReset(data), + messages: data => this.groupMessages(data), + checkAuth: (...args) => this.checkAuth(...args), + }; + } + + /** + * 消息管理子入口,供 /system dispatcher 按 inbox.message.* 路径访问。 + * @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}} 消息管理子入口方法集合。 + */ + get message() { + const { ctx } = this; + return { + list: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.list({ warehouseId, ...data }); + }, + detail: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.detail({ warehouseId, id: data.id }); + }, + thread: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.thread({ warehouseId, id: data.id }); + }, + stats: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.stats({ warehouseId, direction: data.direction }); + }, + reply: data => this.reply(data), + retry: data => this.retry(data), + checkAuth: (...args) => this.checkAuth(...args), + }; + } + + /** + * v2 可配置回信引擎配置管理子入口,供 /system dispatcher 按 inbox.v2.* 路径访问。 + * 全部委托给 systems/inbox/v2.js(配置管理系统服务层),本层只做 checkAuth 代理。 + * @return {Object} v2 配置管理方法集合(type/subType/keyword/numberRule/function/reply/relation)。 + */ + get v2() { + const { ctx } = this; + const svc = () => ctx.service.systems.inbox.v2; + return { + type: { ...svc().type, checkAuth: (...args) => this.checkAuth(...args) }, + subType: { ...svc().subType, checkAuth: (...args) => this.checkAuth(...args) }, + keyword: { ...svc().keyword, checkAuth: (...args) => this.checkAuth(...args) }, + numberRule: { ...svc().numberRule, checkAuth: (...args) => this.checkAuth(...args) }, + function: { ...svc().function, checkAuth: (...args) => this.checkAuth(...args) }, + reply: { ...svc().reply, checkAuth: (...args) => this.checkAuth(...args) }, + relation: { + function: { ...svc().relation.function, checkAuth: (...args) => this.checkAuth(...args) }, + rule: { ...svc().relation.rule, checkAuth: (...args) => this.checkAuth(...args) }, + group: { ...svc().relation.group, checkAuth: (...args) => this.checkAuth(...args) }, + }, + }; + } + + /** + * 生成货主绑群码。 + * 委托给 systems.store.bindCode 执行:校验 StoreWarehouse 合约 → 生成12位随机码 → 缓存300秒。 + * warehouseId 从 ctx.user.store_id 自动注入,绑群码缓存 key 为 chat:bind:{warehouseId}:{code}。 + * + * @param {Object} data 请求数据。 + * @param {number} data.storeId 货主ID。 + * @param {string} [data.subType] 群子类型编码:after_sales(售后) / finance(财务) / receiving(收货)。 + * @return {Promise} { code: 绑群码 }。 + */ + async bindCode(data = {}) { + const { ctx } = this; + const { storeId, subType } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + return await ctx.service.systems.store.bindCode({ + storeId, + warehouseId, + subType, + }); + } + + /** + * 拉取当前仓库的群列表。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {string} [data.keyword] 群名称模糊搜索。 + * @param {number} [data.page] 页码。 + * @param {number} [data.pageSize] 每页条数。 + * @return {Promise} { total, list }。 + */ + async groupList(data = {}) { + const { ctx } = this; + const { groupType, keyword, page, pageSize, pagination, where } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + return await ctx.service.systems.inbox.group.list({ + warehouseId, + groupType, + keyword, + page, + pageSize, + pagination, + where, + }); + } + + /** + * 群快速查询(下拉选择用,不分页)。 + * 双维度可选过滤,均不传时返回所有仓库/货主的群: + * - store_id:货主维度,透传为底层参数 storeId; + * - warehouse_id:仓库维度,透传为底层参数 warehouseId; + * - 两者可同时传(AND 关系),也可都不传(不加对应过滤条件)。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.keyword] 关键词,模糊匹配群名称与外部群ID。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {number} [data.limit=20] 返回条数上限,最大 100。 + * @param {number|string} [data.store_id] 货主ID(可选,对应 wms_inbox_group.store_id 列)。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,对应 wms_inbox_group.warehouse_id 列)。 + * @return {Promise} { list: 群快速列表 }。 + */ + async groupQuickList(data = {}) { + const { ctx } = this; + const { + keyword, groupType, limit, + store_id: storeId, + warehouse_id: warehouseId, + } = data; + + return await ctx.service.systems.inbox.group.quickList({ + storeId, + warehouseId, + keyword, + groupType, + limit, + }); + } + + /** + * 查询一个或多个群的成员列表(下拉选择用,多群聚合)。 + * warehouseId 从 ctx.user.store_id 自动注入,不信任前端传值。 + * + * @param {Object} data 请求数据。 + * @param {Array} data.groupIds 群内部主键ID数组(必填,非空且每个元素为正整数)。 + * @param {string} [data.keyword] 关键词,模糊匹配 user_name / user_id。 + * @param {number} [data.limit=20] 返回条数上限,最大 100。 + * @return {Promise} { list: 群成员列表 }。 + */ + async groupMembers(data = {}) { + const { ctx } = this; + const { groupIds, keyword, limit } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + return await ctx.service.systems.inbox.group.members({ + groupIds, + warehouseId, + keyword, + limit, + }); + } + + /** + * 禁用 / 解禁群。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} [data.isBlocked=1] 是否禁用 1=是 0=否。 + * @return {Promise} { message: 操作结果 }。 + */ + async groupDisable(data = {}) { + const { ctx } = this; + const { id, isBlocked } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + await ctx.service.systems.inbox.group.disable({ + id, + warehouseId, + isBlocked: isBlocked === 0 ? 0 : 1, + }); + + return { message: isBlocked === 0 ? '群已启用' : '群已禁用' }; + } + + /** + * 修改群信息。 + * 支持修改 group_type / sub_type / store_id / express_interfaces / + * system_express_code / ai_enabled / template_reply_enabled。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {string} [data.groupType] 群类型:store / warehouse / express。 + * @param {string} [data.subType] 群子类型。 + * @param {number} [data.storeId] 关联货主ID。 + * @param {number[]} [data.expressInterfaces] 快递接口ID数组(仅 express 生效)。 + * @param {string} [data.systemExpressCode] 系统快递编码(express 时必填)。 + * @param {number} [data.aiEnabled] 是否启用AI自动回复: 0=关闭 1=开启。 + * @param {number} [data.templateReplyEnabled] 是否启用模板消息回复: 0=关闭(普通文本回复) 1=开启(模板消息回复)。 + * @return {Promise} { message: 操作结果 }。 + */ + async groupUpdate(data = {}) { + const { ctx } = this; + const { + id, groupType, subType, storeId, + expressInterfaces, systemExpressCode, aiEnabled, + templateReplyEnabled, + } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + await ctx.service.systems.inbox.group.update({ + id, + warehouseId, + groupType, + subType, + storeId, + expressInterfaces, + systemExpressCode, + aiEnabled, + templateReplyEnabled, + }); + + return { message: '群信息修改成功' }; + } + + /** + * 清空群类型配置(入参主键ID或外部群ID)。 + * 清空 group_type / sub_type / store_id / 快递专属字段,AI 开关重置关闭, + * 仅保留群创建时信息。warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @return {Promise} { message: 操作结果 }。 + */ + async groupReset(data = {}) { + const { ctx } = this; + const { id } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + await ctx.service.systems.inbox.group.reset({ id, warehouseId }); + + return { message: '群类型配置已清空' }; + } + + /** + * 拉取指定群的消息列表。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {string} data.groupId 群ID(必填)。 + * @param {string} [data.direction] 消息方向筛选:inbound / outbound。 + * @param {string} [data.keyword] 关键词搜索(ext_id / content)。 + * @param {number} [data.page] 页码。 + * @param {number} [data.pageSize] 每页条数。 + * @return {Promise} { list, pagination }。 + */ + async groupMessages(data = {}) { + const { ctx } = this; + const { groupId, direction, keyword, page, pageSize } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + if (!groupId || typeof groupId !== 'string' || !groupId.trim()) { + throw new Error('groupId 不能为空'); + } + + return await ctx.service.inbox.message.list({ + warehouseId, + groupId: groupId.trim(), + direction, + keyword, + page, + pageSize, + }); + } + + /** + * 手动重推失败(push_status=3)的站内信消息。 + * 兼容旧版 inbox.retry 路径,与 inbox.message.retry 等价。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 消息ID(必填)。 + * @return {Promise} { ok, id, ext_id, message }。 + */ + async retry(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user?.store_id || 0); + return await ctx.service.inbox.message.retry({ warehouseId, id: data.id }); + } + + /** + * 系统回信:写入 outbound 记录。 + * 兼容旧版 inbox.reply 路径,与 inbox.message.reply 等价。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.parentId 原消息ID(必填)。 + * @param {string} [data.content] 回信正文。 + * @param {Object} [data.extData] 透传数据。 + * @param {Object} [data.flags] 处理标记。 + * @return {Promise} 回信结果。 + */ + async reply(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user?.store_id || 0); + return await ctx.service.inbox.index.reply({ warehouseId, ...data }); + } +} + +module.exports = InboxSystemService; diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 50557c4..5af9d95 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1,14 +1,1104 @@ 'use strict'; const MainService = require('../main'); +const crypto = require('crypto'); +const PddClient = require('../../lib/pdd_client'); +const { buildNotDeletedShopWhere } = require('../../lib/shop_soft_delete'); + +const DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router'; +const DEFAULT_TB_ROUTER_URL = 'https://eco.taobao.com/router/rest'; +const SHOP_MASK_PLACEHOLDER = '***'; +const TB_FILTERED_SERVICE_REGEXP = /\b(?:COD|RECEIVER[-_ ]?PAY)\b|代收货款|到付|拦截件|定时派送|上门取旧换新/i; + +/** + * 脱敏通用敏感文本。 + * + * @param {*} value 原始敏感值 + * @return {string|null} 脱敏后的值;原值为空时返回 null + */ +function maskSensitiveText(value) { + if (value === null || value === undefined || String(value).trim() === '') { + return null; + } + + return SHOP_MASK_PLACEHOLDER; +} + +/** + * 脱敏店铺归属人标识。 + * + * @param {*} ownerId 店铺归属人标识 + * @return {string|null} 脱敏后的归属人标识;原值为空时返回 null + */ +function maskShopOwnerId(ownerId) { + if (ownerId === null || ownerId === undefined || String(ownerId).trim() === '') { + return null; + } + + const ownerIdText = String(ownerId); + if (ownerIdText.length <= 5) { + return SHOP_MASK_PLACEHOLDER; + } + + return `${ownerIdText.slice(0, 3)}${SHOP_MASK_PLACEHOLDER}${ownerIdText.slice(-2)}`; +} + +/** + * 将店铺记录裁剪为安全的列表输出。 + * + * @param {Object} shopItem 店铺记录或模型实例 + * @return {Object} 脱敏后的店铺列表项 + */ +function maskShopListItem(shopItem) { + const plainItem = shopItem && typeof shopItem.get === 'function' + ? shopItem.get({ plain: true }) + : shopItem || {}; + const printPlatform = plainItem.printPlatform && typeof plainItem.printPlatform === 'object' + ? plainItem.printPlatform + : null; + + return { + id: plainItem.id, + warehouse_id: plainItem.warehouse_id, + platform_code: plainItem.platform_code, + platform_name: printPlatform ? printPlatform.platform_name || printPlatform.platform_code || '' : '', + shop_name: plainItem.shop_name, + custom_name: plainItem.custom_name, + status: plainItem.status, + auth_expire_at: plainItem.auth_expire_at, + token_expires_at: plainItem.token_expires_at, + refresh_token_expires_at: plainItem.refresh_token_expires_at, + scope: plainItem.scope, + created_at: plainItem.created_at, + updated_at: plainItem.updated_at, + owner_id: maskShopOwnerId(plainItem.owner_id), + access_token: maskSensitiveText(plainItem.access_token), + refresh_token: maskSensitiveText(plainItem.refresh_token), + auth_random_code: maskSensitiveText(plainItem.auth_random_code), + }; +} + +/** + * 将任意值标准化为空字符串。 + * + * @param {*} value 原始值 + * @return {string} 标准化后的字符串 + */ +function normalizeText(value) { + if (value === null || value === undefined) { + return ''; + } + + return String(value); +} + +/** + * 判断淘宝菜鸟服务项是否属于代收货款、到付、拦截件、定时派送或上门取旧换新类服务。 + * + * @param {Object} serviceItem 淘宝菜鸟服务项 + * @return {boolean} 是否需要从统一返回结果中过滤 + */ +function shouldFilterTbService(serviceItem) { + const currentServiceItem = serviceItem && typeof serviceItem === 'object' ? serviceItem : {}; + const candidateTexts = [ + currentServiceItem.service_code, + currentServiceItem.service_name, + currentServiceItem.service_desc, + ].map(item => normalizeText(item).trim()).filter(Boolean); + + return candidateTexts.some(item => TB_FILTERED_SERVICE_REGEXP.test(item)); +} + +/** + * 将任意值标准化为数组。 + * + * @param {*} value 原始值 + * @return {Array} 数组值;非数组时返回空数组 + */ +function normalizeArray(value) { + return Array.isArray(value) ? value : []; +} + +/** + * 将对象包裹的集合字段标准化为数组。 + * + * @param {*} value 原始集合值 + * @param {Array} [nestedKeys=[]] 对象包裹时的候选子字段名 + * @return {Array} 标准化后的数组 + */ +function normalizeWrappedArray(value, nestedKeys = []) { + if (Array.isArray(value)) { + return value; + } + + if (!value || typeof value !== 'object') { + return []; + } + + for (const nestedKey of normalizeArray(nestedKeys)) { + if (!nestedKey || !Object.prototype.hasOwnProperty.call(value, nestedKey)) { + continue; + } + + const nestedValue = value[nestedKey]; + + if (Array.isArray(nestedValue)) { + return nestedValue; + } + + if (nestedValue !== null && nestedValue !== undefined) { + return [ nestedValue ]; + } + } + + return Object.keys(value).length ? [ value ] : []; +} + +/** + * 按候选来源顺序提取首个非空包裹集合。 + * + * @param {Array<*>} values 候选来源列表 + * @param {Array} [nestedKeys=[]] 对象包裹时的候选子字段名 + * @return {Array} 首个非空的标准化数组 + */ +function normalizeFirstWrappedArray(values, nestedKeys = []) { + for (const value of normalizeArray(values)) { + const normalized = normalizeWrappedArray(value, nestedKeys); + + if (normalized.length) { + return normalized; + } + } + + return []; +} + +/** + * 按候选字段顺序提取首个非空值。 + * + * @param {Array<*>} values 候选值列表 + * @return {*} 首个非空值;未命中时返回空字符串 + */ +function resolveFirstNonEmptyValue(values = []) { + for (const value of normalizeArray(values)) { + if (value === null || value === undefined) { + continue; + } + + if (String(value).trim() === '') { + continue; + } + + return value; + } + + return ''; +} + +/** + * 将 JD 模板响应中的标准模板列表扁平化为前端易消费结构。 + * + * @param {Object} templateResponseItem JD 模板命中对象 + * @return {Array} 扁平化后的模板列表 + */ +function normalizeJdTemplateList(templateResponseItem) { + const currentTemplateResponseItem = templateResponseItem && typeof templateResponseItem === 'object' + ? templateResponseItem + : {}; + const cpCode = normalizeText(resolveFirstNonEmptyValue([ + currentTemplateResponseItem.cp_code, + currentTemplateResponseItem.cpcode, + currentTemplateResponseItem.cpCode, + ])).trim(); + const standardTemplateList = normalizeFirstWrappedArray([ + currentTemplateResponseItem.standard_templates, + currentTemplateResponseItem.standardTemplates, + currentTemplateResponseItem.standard_template_do, + currentTemplateResponseItem.standardTemplateDo, + ], [ 'standard_template_do', 'standardTemplateDo' ]); + + return standardTemplateList.map(templateItem => { + const currentTemplateItem = templateItem && typeof templateItem === 'object' + ? templateItem + : {}; + const brandCode = normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.brand_code, + currentTemplateItem.brandcode, + currentTemplateItem.brandCode, + ])).trim(); + const standardWaybillType = normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.standard_waybill_type, + currentTemplateItem.templatetype, + currentTemplateItem.templateType, + ])).trim(); + + return { + template_id: normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.standard_template_id, + currentTemplateItem.id, + currentTemplateItem.templateid, + currentTemplateItem.templateId, + ])).trim(), + template_name: normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.standard_template_name, + currentTemplateItem.name, + currentTemplateItem.templatename, + currentTemplateItem.templateName, + ])).trim(), + template_url: normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.standard_template_url, + currentTemplateItem.url, + currentTemplateItem.templateurl, + currentTemplateItem.templateUrl, + currentTemplateItem.tempurl, + currentTemplateItem.tempUrl, + ])).trim(), + cp_code: cpCode || normalizeText(resolveFirstNonEmptyValue([ + currentTemplateItem.cp_code, + currentTemplateItem.cpcode, + currentTemplateItem.cpCode, + ])).trim(), + wp_code: brandCode || standardWaybillType, + }; + }); +} + +/** + * 为 JD 模板命中结果补充扁平化模板列表,保持原始字段不变。 + * + * @param {Object} templateResponseItem JD 模板命中对象 + * @return {Object} 补充 list 字段后的 JD 模板响应 + */ +function appendJdTemplateList(templateResponseItem) { + const currentTemplateResponseItem = templateResponseItem && typeof templateResponseItem === 'object' + ? templateResponseItem + : {}; + + return { + ...currentTemplateResponseItem, + list: normalizeJdTemplateList(currentTemplateResponseItem), + }; +} + +/** + * 规范化菜鸟标准模板子项列表。 + * + * @param {*} standardTemplates 菜鸟标准模板字段 + * @return {Array} 标准模板子项列表 + */ +// eslint-disable-next-line no-unused-vars +function normalizeCainiaoStandardTemplateList(standardTemplates) { + return normalizeWrappedArray(standardTemplates, [ 'standard_template_do' ]); +} + +/** + * 按原始结构回填菜鸟标准模板子项列表。 + * + * @param {*} standardTemplates 菜鸟标准模板字段 + * @param {Array} templateList 过滤后的标准模板子项列表 + * @return {*} 回填后的标准模板字段 + */ +// eslint-disable-next-line no-unused-vars +function rebuildCainiaoStandardTemplates(standardTemplates, templateList) { + if (Array.isArray(standardTemplates)) { + return templateList; + } + + if (standardTemplates && typeof standardTemplates === 'object') { + if (Object.prototype.hasOwnProperty.call(standardTemplates, 'standard_template_do')) { + return { + ...standardTemplates, + standard_template_do: templateList, + }; + } + + return Object.keys(standardTemplates).length ? { + ...standardTemplates, + standard_template_do: templateList, + } : templateList; + } + + return templateList; +} + +/** + * 根据平台编码构建平台侧快递编码到系统快递信息的映射。 + * + * @param {Array} expressList 系统快递列表 + * @param {string} platformCode 平台编码 + * @return {Object} 平台侧快递编码到系统快递信息的映射 + */ +function buildPlatformExpressNameMap(expressList, platformCode) { + const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); + + if (!normalizedPlatformCode) { + return {}; + } + + return normalizeArray(expressList).reduce((result, expressItem) => { + const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; + const platformExpressCode = normalizeText(currentExpressItem[normalizedPlatformCode]).trim(); + + if (!platformExpressCode) { + return result; + } + + result[platformExpressCode] = { + name: normalizeText(currentExpressItem.name), + sys_express_code: normalizeText(currentExpressItem.code), + }; + return result; + }, {}); +} + +/** + * 解析并写入快递映射键,兼容原值与大写键。 + * + * @param {Object} targetMap 目标映射表 + * @param {string} rawKey 原始映射键 + * @param {Object} mappingItem 映射值 + */ +function appendExpressMappingKey(targetMap, rawKey, mappingItem) { + const mappingKey = normalizeText(rawKey).trim(); + + if (!mappingKey) { + return; + } + + targetMap[mappingKey] = mappingItem; + const upperKey = mappingKey.toUpperCase(); + + if (!Object.prototype.hasOwnProperty.call(targetMap, upperKey)) { + targetMap[upperKey] = mappingItem; + } +} + +/** + * 构建抖音电子面单快递映射表。 + * + * @param {Array} expressList 系统快递列表 + * @param {string} [platformCode='DY'] 平台编码,默认为 'DY' + * @return {Object} 支持 DY 平台编码与系统快递编码双键的映射表 + */ +function buildExpressNameMap(expressList, platformCode = 'DY') { + return normalizeArray(expressList).reduce((result, expressItem) => { + const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; + const mappingItem = { + name: normalizeText(currentExpressItem.name), + sys_express_code: normalizeText(currentExpressItem.code), + }; + + appendExpressMappingKey(result, currentExpressItem[platformCode], mappingItem); + appendExpressMappingKey(result, currentExpressItem.code, mappingItem); + + return result; + }, {}); +} + +/** + * 按候选键顺序匹配首个可用快递映射。 + * + * @param {Object} expressNameMap 快递映射表 + * @param {Array<*>} candidateKeys 候选映射键 + * @return {Object} 命中的快递映射,未命中时返回空对象 + */ +function resolveExpressMapping(expressNameMap, candidateKeys = []) { + const mapObject = expressNameMap && typeof expressNameMap === 'object' ? expressNameMap : {}; + + for (const candidateKey of normalizeArray(candidateKeys)) { + const normalizedKey = normalizeText(candidateKey).trim(); + + if (!normalizedKey) { + continue; + } + + if (mapObject[normalizedKey] && typeof mapObject[normalizedKey] === 'object') { + return mapObject[normalizedKey]; + } + + const upperKey = normalizedKey.toUpperCase(); + if (mapObject[upperKey] && typeof mapObject[upperKey] === 'object') { + return mapObject[upperKey]; + } + } + + return {}; +} + +/** + * 按系统快递编码分组构建快递产品类型映射。 + * + * @param {Array} productTypeList 快递产品类型列表 + * @return {Object} 系统快递编码(大写)到产品类型列表([{ name, code }])的映射 + */ +function buildExpressProductTypeMap(productTypeList) { + return normalizeArray(productTypeList).reduce((result, productTypeItem) => { + const currentItem = productTypeItem && typeof productTypeItem === 'object' ? productTypeItem : {}; + const expressCode = normalizeText(currentItem.express_code).trim().toUpperCase(); + const code = normalizeText(currentItem.code).trim(); + + if (!expressCode || !code) { + return result; + } + + if (!Array.isArray(result[expressCode])) { + result[expressCode] = []; + } + + if (result[expressCode].some(item => item.code === code)) { + return result; + } + + result[expressCode].push({ + name: normalizeText(currentItem.name).trim() || code, + code, + }); + + return result; + }, {}); +} + +/** + * 解析拼多多电子面单网点查询响应,收敛为前端易消费的结构。 + * + * @param {*} responseData 拼多多原始响应 + * @param {Object} [expressNameMap={}] 平台快递编码到系统快递信息的映射 + * @return {Object} 解析后的电子面单网点结构 + */ +function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { + const waybillResponse = responseData && typeof responseData === 'object' + ? responseData.pdd_waybill_search_response || {} + : {}; + const subscriptions = normalizeArray(waybillResponse.waybill_apply_subscription_cols); + + const list = subscriptions.map(subscription => { + const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; + const accountSources = normalizeFirstWrappedArray([ + subscriptionItem.branch_account_cols, + subscriptionItem.branchAccounts, + subscriptionItem.branch_accounts, + subscriptionItem.accounts, + subscriptionItem.waybill_branch_account, + ], [ 'waybill_branch_account', 'branch_account', 'account', 'list' ]); + const firstAccountSource = accountSources[0] && typeof accountSources[0] === 'object' + ? accountSources[0] + : {}; + const providerid = normalizeText( + subscriptionItem.providerid + || subscriptionItem.providerId + || subscriptionItem.ProviderID + || firstAccountSource.providerid + || firstAccountSource.providerId + || firstAccountSource.ProviderID + ); + + const accounts = accountSources.map(account => { + const accountItem = account && typeof account === 'object' ? account : {}; + const preferredCustomerCode = normalizeText( + accountItem.logisticsaccount + || subscriptionItem.logisticsaccount + || accountItem.shipperno + || subscriptionItem.shipperno + ); + const customerCodes = normalizeWrappedArray( + accountItem.customer_code_list + || accountItem.customerCodeList + || accountItem.customer_codes + || accountItem.customerCodes, + [ 'string', 'list', 'code' ] + ) + .map(item => normalizeText(item)) + .filter(Boolean); + if (!customerCodes.length && preferredCustomerCode) { + customerCodes.push(preferredCustomerCode); + } + const shipAddresses = normalizeFirstWrappedArray([ + accountItem.shipp_address_cols, + accountItem.ship_addresses, + accountItem.shipAddresses, + accountItem.address_dto, + accountItem.addresses, + accountItem.address, + subscriptionItem.address, + ], [ 'address_dto', 'waybill_address', 'list' ]).map(address => { + const rawAddressItem = address && typeof address === 'object' ? address : {}; + const addressItem = rawAddressItem.address && typeof rawAddressItem.address === 'object' + ? rawAddressItem.address + : rawAddressItem; + const province = normalizeText(addressItem.province); + const city = normalizeText(addressItem.city); + const district = normalizeText(addressItem.district || addressItem.area); + const town = normalizeText(addressItem.town); + const detail = normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address); + const fullAddress = normalizeText(addressItem.full_address || addressItem.fullAddress); + + return { + country: normalizeText(addressItem.country), + province, + city, + district, + town, + detail, + full_address: fullAddress || `${province}${city}${district}${town}${detail}`, + }; + }); + const services = normalizeFirstWrappedArray([ + accountItem.service_info_cols, + accountItem.service_info_dto, + accountItem.services, + accountItem.serviceInfos, + ], [ 'service_info_dto', 'waybill_service_info', 'service', 'list' ]).map(service => { + const serviceItem = service && typeof service === 'object' ? service : {}; + const attributes = normalizeFirstWrappedArray([ + serviceItem.service_attributes, + serviceItem.service_attribute_dto, + serviceItem.attributes, + ], [ 'service_attribute_dto', 'waybill_service_attribute', 'attribute', 'list' ]).map(attribute => { + const attributeItem = attribute && typeof attribute === 'object' ? attribute : {}; + + return { + attribute_code: normalizeText(attributeItem.attribute_code || attributeItem.attributeCode), + attribute_name: normalizeText(attributeItem.attribute_name || attributeItem.attributeName), + attribute_type: normalizeText(attributeItem.attribute_type || attributeItem.attributeType), + type_desc: normalizeText(attributeItem.type_desc || attributeItem.attribute_type_name || attributeItem.typeDesc), + }; + }); + + return { + service_code: normalizeText(serviceItem.service_code || serviceItem.serviceCode), + service_name: normalizeText(serviceItem.service_name || serviceItem.serviceName), + service_desc: normalizeText(serviceItem.service_desc || serviceItem.description || serviceItem.serviceDesc), + required: Boolean(serviceItem.required), + attributes, + }; + }); + + const result = { + branch_code: normalizeText(accountItem.branch_code), + branch_name: normalizeText(accountItem.branch_name), + quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, + cancel_quantity: accountItem.cancel_quantity ?? 0, + recycled_quantity: accountItem.recycled_quantity ?? 0, + allocated_quantity: accountItem.allocated_quantity ?? 0, + customer_code_list: customerCodes, + ship_addresses: shipAddresses, + services, + }; + + const platformShopId = normalizeText( + accountItem.shopid + || accountItem.shop_id + || subscriptionItem.shopid + || subscriptionItem.shop_id + || accountItem.providerid + || subscriptionItem.providerid + ); + if (platformShopId) { + result.platform_shop_id = platformShopId; + } + + return result; + }); + + const wpCode = normalizeText(subscriptionItem.wp_code); + const expressMapping = expressNameMap[wpCode] && typeof expressNameMap[wpCode] === 'object' + ? expressNameMap[wpCode] + : {}; + + return { + wp_code: wpCode, + wp_name: normalizeText(expressMapping.name) || '', + sys_express_code: normalizeText(expressMapping.sys_express_code) || '', + wp_type: normalizeText(subscriptionItem.wp_type), + providerid, + accounts, + }; + }); + + return { + request_id: normalizeText(waybillResponse.request_id), + total: subscriptions.length, + list, + }; +} + +/** + * 解析抖音(PolyAPI)电子面单网点查询响应,收敛为与拼多多一致的统一结构。 + * + * @param {*} responseData 抖音原始响应 + * @param {Object} [expressNameMap={}] 平台快递编码到系统快递信息的映射 + * @return {Object} 解析后的电子面单网点结构 + */ +function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { + const normalizedResponse = responseData && typeof responseData === 'object' + ? responseData + : {}; + const waybillResponse = [ + normalizedResponse.data, + normalizedResponse.result, + normalizedResponse.results, + normalizedResponse, + ].find(item => item && typeof item === 'object') || {}; + + const subscriptions = normalizeFirstWrappedArray([ + waybillResponse.waybill_apply_subscription_cols, + waybillResponse.waybillApplySubscriptionCols, + waybillResponse.waybill_apply_subscription_info, + waybillResponse.waybillApplySubscriptionInfo, + waybillResponse.results, + waybillResponse.result, + waybillResponse.list, + waybillResponse.waybill_condition_list, + waybillResponse.waybillConditionList, + normalizedResponse.results, + normalizedResponse.result, + ], [ 'waybill_apply_subscription_info', 'list', 'waybill_condition', 'waybillCondition' ]); + + const groupedByWpCode = new Map(); + + for (const subscription of subscriptions) { + const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; + const sysExpressCode = normalizeText( + subscriptionItem.sys_express_code + || subscriptionItem.sysExpressCode + || subscriptionItem.express_sys_code + || subscriptionItem.expressSysCode + ); + const wpCode = normalizeText( + subscriptionItem.wp_code + || subscriptionItem.providercode + || subscriptionItem.cp_code + || subscriptionItem.cpcode + || subscriptionItem.logistics_code + || subscriptionItem.express_code + ); + const expressMapping = resolveExpressMapping(expressNameMap, [ + subscriptionItem.providercode, + subscriptionItem.cp_code, + subscriptionItem.cpcode, + subscriptionItem.wp_code, + subscriptionItem.logistics_code, + subscriptionItem.express_code, + sysExpressCode, + wpCode, + ]); + + const accountSources = normalizeFirstWrappedArray([ + subscriptionItem.branch_account_cols, + subscriptionItem.branchAccounts, + subscriptionItem.branch_accounts, + subscriptionItem.accounts, + subscriptionItem.waybill_branch_account, + subscriptionItem.results, + subscriptionItem.result, + subscriptionItem.list, + ], [ 'waybill_branch_account', 'branch_account', 'account', 'results', 'result', 'list' ]); + const firstAccountSource = accountSources[0] && typeof accountSources[0] === 'object' + ? accountSources[0] + : {}; + const providerid = normalizeText( + subscriptionItem.providerid + || subscriptionItem.providerId + || subscriptionItem.ProviderID + || firstAccountSource.providerid + || firstAccountSource.providerId + || firstAccountSource.ProviderID + ); + + const accounts = (accountSources.length ? accountSources : [ subscriptionItem ]).map(account => { + const accountItem = account && typeof account === 'object' ? account : {}; + const preferredCustomerCode = normalizeText( + accountItem.logisticsaccount + || subscriptionItem.logisticsaccount + || accountItem.shipperno + || subscriptionItem.shipperno + ); + const customerCodes = normalizeWrappedArray( + accountItem.customer_code_list + || accountItem.customerCodeList + || accountItem.customer_codes + || accountItem.customerCodes, + [ 'string', 'list', 'code' ] + ).map(item => normalizeText(item)).filter(Boolean); + if (!customerCodes.length && preferredCustomerCode) { + customerCodes.push(preferredCustomerCode); + } + const shipAddresses = normalizeFirstWrappedArray([ + accountItem.shipp_address_cols, + accountItem.ship_addresses, + accountItem.shipAddresses, + accountItem.address_dto, + accountItem.addresses, + accountItem.address, + subscriptionItem.address, + accountItem.shippers, + ], [ 'address_dto', 'waybill_address' ]).map(address => { + const rawAddressItem = address && typeof address === 'object' ? address : {}; + const addressItem = rawAddressItem.address && typeof rawAddressItem.address === 'object' + ? rawAddressItem.address + : rawAddressItem; + const province = normalizeText(addressItem.province); + const city = normalizeText(addressItem.city); + const district = normalizeText(addressItem.district || addressItem.area); + const town = normalizeText(addressItem.town); + const detail = normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address); + const fullAddress = normalizeText(addressItem.full_address || addressItem.fullAddress); + + return { + country: normalizeText(addressItem.country), + province, + city, + district, + town, + detail, + full_address: fullAddress || `${province}${city}${district}${town}${detail}`, + }; + }); + const services = normalizeFirstWrappedArray([ + accountItem.service_info_cols, + accountItem.service_info_dto, + accountItem.services, + accountItem.serviceInfos, + ], [ 'service_info_dto', 'waybill_service_info', 'service' ]).map(service => { + const serviceItem = service && typeof service === 'object' ? service : {}; + const attributes = normalizeFirstWrappedArray([ + serviceItem.service_attributes, + serviceItem.service_attribute_dto, + serviceItem.attributes, + ], [ 'service_attribute_dto', 'waybill_service_attribute', 'attribute' ]).map(attribute => { + const attributeItem = attribute && typeof attribute === 'object' ? attribute : {}; + + return { + attribute_code: normalizeText(attributeItem.attribute_code), + attribute_name: normalizeText(attributeItem.attribute_name), + attribute_type: normalizeText(attributeItem.attribute_type), + type_desc: normalizeText(attributeItem.type_desc || attributeItem.attribute_type_name), + }; + }); + + return { + service_code: normalizeText(serviceItem.service_code), + service_name: normalizeText(serviceItem.service_name), + service_desc: normalizeText(serviceItem.service_desc || serviceItem.description), + required: Boolean(serviceItem.required), + attributes, + }; + }); + const result = { + branch_code: normalizeText(accountItem.branch_code || accountItem.branchCode || accountItem.sitecode), + branch_name: normalizeText(accountItem.branch_name || accountItem.branchName || accountItem.sitename), + quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, + cancel_quantity: accountItem.cancel_quantity ?? 0, + recycled_quantity: accountItem.recycled_quantity ?? 0, + allocated_quantity: accountItem.allocated_quantity ?? 0, + customer_code_list: customerCodes, + ship_addresses: shipAddresses, + services, + }; + const platformShopId = normalizeText( + accountItem.shopid + || subscriptionItem.shopid + || accountItem.providerid + || subscriptionItem.providerid + ); + if (platformShopId) { + result.platform_shop_id = platformShopId; + } + return result; + }); + + if (!groupedByWpCode.has(wpCode)) { + groupedByWpCode.set(wpCode, { + wp_code: wpCode, + wp_name: normalizeText(expressMapping.name) + || normalizeText( + subscriptionItem.wp_name + || subscriptionItem.providername + || subscriptionItem.cp_name + || subscriptionItem.cpname + ), + sys_express_code: normalizeText(expressMapping.sys_express_code || sysExpressCode), + wp_type: normalizeText( + subscriptionItem.wp_type + || subscriptionItem.providertype + || subscriptionItem.waybill_type + || subscriptionItem.type + ), + providerid, + accounts: [], + shipAddressKeys: new Set(), + }); + } + + const groupedItem = groupedByWpCode.get(wpCode); + + if (!groupedItem.wp_name) { + groupedItem.wp_name = normalizeText(expressMapping.name) + || normalizeText( + subscriptionItem.wp_name + || subscriptionItem.providername + || subscriptionItem.cp_name + || subscriptionItem.cpname + ); + } + if (!groupedItem.sys_express_code) { + groupedItem.sys_express_code = normalizeText(expressMapping.sys_express_code || sysExpressCode); + } + if (!groupedItem.wp_type) { + groupedItem.wp_type = normalizeText( + subscriptionItem.wp_type + || subscriptionItem.providertype + || subscriptionItem.waybill_type + || subscriptionItem.type + ); + } + if (!groupedItem.providerid && providerid) { + groupedItem.providerid = providerid; + } + + const dedupedAccounts = accounts.map(accountItem => { + const accountAddressKeys = new Set(); + const dedupedShipAddresses = normalizeArray(accountItem.ship_addresses).filter(addressItem => { + const addressKey = [ + normalizeText(addressItem && addressItem.country), + normalizeText(addressItem && addressItem.province), + normalizeText(addressItem && addressItem.city), + normalizeText(addressItem && addressItem.district), + normalizeText(addressItem && addressItem.detail), + normalizeText(addressItem && addressItem.full_address), + ].join('|'); + + if (accountAddressKeys.has(addressKey) || groupedItem.shipAddressKeys.has(addressKey)) { + return false; + } + + accountAddressKeys.add(addressKey); + groupedItem.shipAddressKeys.add(addressKey); + return true; + }); + + return { + ...accountItem, + ship_addresses: dedupedShipAddresses, + }; + }); + + groupedItem.accounts.push(...dedupedAccounts); + } + + const list = Array.from(groupedByWpCode.values()).map(item => ({ + wp_code: item.wp_code, + wp_name: item.wp_name, + sys_express_code: item.sys_express_code, + wp_type: item.wp_type, + providerid: item.providerid, + accounts: item.accounts, + })); + + const totalValue = Number(waybillResponse.total); + + return { + request_id: normalizeText(waybillResponse.request_id || normalizedResponse.request_id), + total: Number.isFinite(totalValue) ? totalValue : list.length, + list, + }; +} + +/** + * 判断是否命中拼多多顺丰定时派送服务。 + * + * @param {Array} list 拼多多网点解析列表 + * @return {boolean} 是否命中同步条件 + */ +function hasPddSfTimedDeliveryService(list = []) { + const normalizedList = Array.isArray(list) ? list : []; + + return normalizedList.some(expressItem => { + const expressCode = String(expressItem && expressItem.sys_express_code || '').trim().toUpperCase(); + if (expressCode !== 'SF' && expressCode !== 'SHUNFENG') { + return false; + } + + const accounts = Array.isArray(expressItem && expressItem.accounts) ? expressItem.accounts : []; + return accounts.some(account => { + const services = Array.isArray(account && account.services) ? account.services : []; + return services.some(serviceItem => String(serviceItem && serviceItem.service_code || '').trim().toUpperCase() === 'TIMED-DELIVERY'); + }); + }); +} + +/** + * 归一化淘宝菜鸟服务属性的类型描述。 + * + * @param {*} typeDesc 原始类型描述 + * @return {string} 归一化后的类型描述字符串 + */ +function normalizeTbAttributeTypeDesc(typeDesc) { + const normalizedTypeDesc = normalizeText(typeDesc); + + if (!normalizedTypeDesc) { + return normalizedTypeDesc; + } + + try { + const parsedTypeDesc = JSON.parse(normalizedTypeDesc); + + if (parsedTypeDesc && typeof parsedTypeDesc === 'object' && Object.prototype.hasOwnProperty.call(parsedTypeDesc, 'desc')) { + const descText = JSON.stringify(parsedTypeDesc.desc); + + if (typeof descText === 'string') { + return descText; + } + } + } catch (error) { + // 非 JSON 字符串保持原样,兼容原有返回结构。 + } + + return normalizedTypeDesc; +} + +/** + * 提取淘宝菜鸟电子面单响应中的签约订阅列表。 + * + * @param {*} responseData 淘宝原始响应 + * @return {Array} 标准化后的签约订阅列表 + */ +function extractTbWaybillSubscriptions(responseData) { + const waybillResponse = responseData && typeof responseData === 'object' + ? responseData.cainiao_waybill_ii_search_response || {} + : {}; + const waybillModules = waybillResponse.modules && typeof waybillResponse.modules === 'object' + ? waybillResponse.modules + : {}; + + return normalizeFirstWrappedArray( + [ waybillModules.waybill_apply_subscription_cols, waybillResponse.waybill_apply_subscription_cols ], + [ 'waybill_apply_subscription_info' ] + ); +} + +/** + * 解析淘宝菜鸟电子面单网点查询响应,收敛为前端易消费的统一结构。 + * + * @param {*} responseData 淘宝原始响应 + * @param {Object} [expressNameMap={}] 平台快递编码到系统快递信息的映射 + * @return {Object} 解析后的电子面单网点结构 + */ +function formatTbWaybillSearchResponse(responseData, expressNameMap = {}) { + const waybillResponse = responseData && typeof responseData === 'object' + ? responseData.cainiao_waybill_ii_search_response || {} + : {}; + const subscriptions = extractTbWaybillSubscriptions(responseData); + + const list = subscriptions.map(subscription => { + const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; + const wpCode = normalizeText(subscriptionItem.cp_code || subscriptionItem.wp_code); + const expressMapping = expressNameMap[wpCode] && typeof expressNameMap[wpCode] === 'object' + ? expressNameMap[wpCode] + : {}; + const accounts = normalizeFirstWrappedArray( + [ subscriptionItem.branch_account_cols, subscriptionItem.waybill_branch_account ], + [ 'waybill_branch_account' ] + ).map(account => { + const accountItem = account && typeof account === 'object' ? account : {}; + const customerCodes = normalizeWrappedArray(accountItem.customer_code_list, [ 'string' ]) + .map(item => normalizeText(item)) + .filter(Boolean); + const shipAddresses = normalizeFirstWrappedArray( + [ accountItem.shipp_address_cols, accountItem.address_dto ], + [ 'address_dto', 'waybill_address', 'address' ] + ).map(address => { + const addressItem = address && typeof address === 'object' ? address : {}; + + return { + country: normalizeText(addressItem.country) || '中国', + province: normalizeText(addressItem.province), + city: normalizeText(addressItem.city), + district: normalizeText(addressItem.district || addressItem.area), + detail: normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address), + full_address: normalizeText(addressItem.full_address), + }; + }); + const services = normalizeFirstWrappedArray( + [ accountItem.service_info_cols, accountItem.service_info_dto ], + [ 'service_info_dto', 'waybill_service_info' ] + ).map(service => { + const serviceItem = service && typeof service === 'object' ? service : {}; + const attributes = normalizeFirstWrappedArray( + [ serviceItem.service_attributes, serviceItem.service_attribute_dto ], + [ 'service_attribute_dto', 'waybill_service_attribute' ] + ).map(attribute => { + const attributeItem = attribute && typeof attribute === 'object' ? attribute : {}; + + return { + attribute_code: normalizeText(attributeItem.attribute_code), + attribute_name: normalizeText(attributeItem.attribute_name), + attribute_type: normalizeText(attributeItem.attribute_type), + type_desc: normalizeTbAttributeTypeDesc(attributeItem.type_desc || attributeItem.attribute_type_name), + }; + }); + + return { + service_code: normalizeText(serviceItem.service_code), + service_name: normalizeText(serviceItem.service_name), + service_desc: normalizeText(serviceItem.service_desc || serviceItem.description), + required: Boolean(serviceItem.required), + attributes, + }; + }).filter(serviceItem => !shouldFilterTbService(serviceItem) && serviceItem.attributes.length > 0); + + return { + branch_code: normalizeText(accountItem.branch_code) || normalizeText(customerCodes[0]), + branch_name: normalizeText(accountItem.branch_name), + quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, + cancel_quantity: accountItem.cancel_quantity ?? 0, + recycled_quantity: accountItem.recycled_quantity ?? 0, + allocated_quantity: accountItem.allocated_quantity ?? 0, + customer_code_list: customerCodes, + ship_addresses: shipAddresses, + services, + }; + }); + + return { + wp_code: wpCode, + wp_name: normalizeText(expressMapping.name) || normalizeText(subscriptionItem.cp_name), + sys_express_code: normalizeText(expressMapping.sys_express_code), + wp_type: normalizeText(subscriptionItem.wp_type || subscriptionItem.waybill_type), + accounts, + }; + }); + const totalValue = Number(waybillResponse.total); + + return { + request_id: normalizeText(waybillResponse.request_id), + total: Number.isFinite(totalValue) ? totalValue : subscriptions.length, + list, + }; +} + +/** + * index 模块免系统日志方法清单(显式登记)。 + * + * 历史口径:index 模块全部方法免系统日志(_noNeedLog='*')。 + * uploadClientErrorLog 为公共上报接口,要求免登录但保留系统日志, + * 因此将通配符改为显式清单:本清单之外的新方法默认记录系统日志, + * 新增方法如需免日志须在此登记。 + */ +const INDEX_NO_NEED_LOG_METHODS = 'fastWhereTree,loadStores,loadWarehouses,getWarehousePanelData,loadExpressInterfaces,getCOSUploadConfig,getImages,uploadSuccessNotify,recognizeLicensePlate,ReferenceFile,getMessageDetail,test,getI18nMessage,putI18nCollect,extractModule,tryAutoTranslateNewKeys,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,ensureShopPrintPlatformExists,buildShopPrintPlatformInclude,getShopList,requestPddWaybillSearch,requestPddStdTemplates,requestTbWaybillSearch,requestTbCainiaoStdTemplates,requestPolyStdTemplates,getShopExpressList,getCainiaoStfTemplates,normalizeTemplatePlatformCode,normalizeTemplateExpressCode,getExpressPlatformFieldName,getTemplateAllowedExpressCodeSet,filterPrintPlatformTemplateResponseData,getPrintPlatformTemplateCacheKey,requestPrintPlatformTemplateList,resolvePddTemplateWpCodeCandidates,requestPddTemplateSourceList,getPrintPlatformTemplateList,isPlatformOauthReservationDuplicateError,getPlatformOauthReservationCodePrefix,hasPlatformOauthReservationCodePrefix,normalizePlatformOauthReservationCode,generatePlatformOauthReservationCode,createPlatformOauthReservation,getPlatformOauthLink,listenPlatformOauthBind,loginToIm,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,parseWechatBadgeCode,queryUserByWechatBadge'; class indexService extends MainService { + /** + * 初始化基础方法的免登录、免权限、免鉴权和免日志配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ constructor(ctx) { super(ctx); - const _noNeedLogin = 'getI18nMessage,putI18nCollect'; - const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace'; - const _noNeedLog = '*'; - const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace'; + const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog'; + const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getWarehousePanelData,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog'; + const _noNeedLog = INDEX_NO_NEED_LOG_METHODS; + const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getWarehousePanelData,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -17,11 +1107,71 @@ class indexService extends MainService { const result = await service.systems.fastWhere.getTreeByType(type); return this.success('ok', { presetTree: result, code: 200 }); } - async loadStores(data) { + async loadStores() { const { service } = this; const result = await service.systems.store.loadStores(); return this.success('ok', { stores: result, code: 200 }); } + async loadWarehouses() { + const { service } = this; + const result = await service.systems.store.loadWarehouses(); + return this.success('ok', { warehouses: result, code: 200 }); + } + /** + * 获取仓库面板数据。 + * + * 最后更新时间一般由外部驱动;缓存有最后更新时间时按增量返回: + * is_change=false 时返回空 data(节约流量),is_change=true 时输出缓存数据; + * 缓存中没有最后更新时间时才查库拉取数据并兜底设置最后更新时间。 + * + * @param {Object} data 请求参数 + * @param {number|string} [data.last_change_at] 最后一次更改的时间戳(Unix 秒),force=false 时必填 + * @param {boolean|number|string} [data.force] 首次拉取兼容入参(true/1/'true'),当前仅影响 last_change_at 是否可缺省 + * @return {Promise} 返回 { is_change, last_change_at, data },其中 is_change=false 时 data 为空对象 + */ + async getWarehousePanelData(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null; + if (!warehouseId) { + return this.fail('缺少仓库上下文'); + } + + const force = data.force === true || data.force === 'true' || data.force === 1; + + const rawLast = data && data.last_change_at; + let lastChangeAt = 0; + if (force) { + // 首次拉取可不传时间戳,缺省视为 0;若传入则仍做格式校验 + if (rawLast !== undefined && rawLast !== null && String(rawLast).trim() !== '') { + lastChangeAt = Number(rawLast); + if (!Number.isFinite(lastChangeAt) || lastChangeAt < 0) { + return this.fail('参数错误:last_change_at 必须为数字时间戳'); + } + } + } else { + if (rawLast === undefined || rawLast === null || String(rawLast).trim() === '') { + return this.fail('参数错误:last_change_at 不能为空'); + } + lastChangeAt = Number(rawLast); + if (!Number.isFinite(lastChangeAt) || lastChangeAt < 0) { + return this.fail('参数错误:last_change_at 必须为数字时间戳'); + } + } + + const result = await service.systems.warehousePanel.getPanelData(warehouseId, { force, lastChangeAt }); + return this.success('ok', { + is_change: result.is_change, + last_change_at: result.last_change_at, + data: result.data, + code: 200, + }); + } + async loadExpressInterfaces(data = {}) { + const { service } = this; + const { systemExpressCode } = data; + const result = await service.systems.setting.expressInterface.loadExpressInterfaces({ systemExpressCode }); + return this.success('ok', { expressInterfaces: result, code: 200 }); + } async getCOSUploadConfig(datas) { const { service } = this; const { data } = datas; @@ -38,6 +1188,32 @@ class indexService extends MainService { const result = await service.systems.upload.uploadSuccessNotify(data); return this.success('ok', { data: result, code: 200 }); } + /** + * 识别车牌号码。 + * + * @param {Object} data 请求参数 + * @param {string} data.base64 base64 图片 + * @param {string} [data.imageBase64] 兼容的 base64 字段 + * @param {string} [data.image_base64] 兼容的 base64 字段 + * @return {Promise} 识别结果 + */ + async recognizeLicensePlate(data) { + const { service, ctx } = this; + const { base64 = '', imageBase64 = '', image_base64 = '' } = data || {}; + const imageBase64Value = String(base64 || imageBase64 || image_base64 || '').trim(); + + if (!imageBase64Value) { + return this.fail('base64 图片不能为空', { code: 400 }); + } + + try { + const result = await service.systems.licensePlate.recognizeLicensePlate(imageBase64Value); + return this.success('ok', { data: result, code: 200 }); + } catch (error) { + ctx.logger.error('车牌识别失败:', error); + return this.fail(error.message || '车牌识别失败', { code: 500 }); + } + } async ReferenceFile(data) { const { service } = this; const result = await service.systems.file.ReferenceFile(data); @@ -49,63 +1225,134 @@ class indexService extends MainService { return this.success('ok', { data: result, code: 200 }); } + /** + * 后台专用的拼多多接口测试入口。 + * + * @param {Object} data 请求参数 + * @param {string} data.type 拼多多接口名,例如 pdd.order.number.list.get + * @param {Object} [data.bizParams] 业务参数对象 + * @param {Object} [data.request] 业务参数别名,兼容旧调用方式 + * @param {string} [data.accessToken] 用户授权令牌 + * @param {string} [data.dataType='JSON'] 响应格式 + * @param {string} [data.version] API 版本 + * @param {string|number} [data.timestamp] 时间戳 + * @param {string} [data.clientId] client_id 覆盖值 + * @param {string} [data.clientSecret] client_secret 覆盖值 + * @param {string} [data.baseUrl] 请求地址 + * @param {Object} [data.headers] 额外请求头 + * @param {number} [data.timeout] 请求超时 + * @return {Promise} 调用结果 + */ + async test(data = {}) { + const { ctx } = this; + const input = data && typeof data === 'object' ? data : {}; + const { + type, + access_token: accessTokenSnake, + accessToken, + data_type: dataTypeSnake, + dataType = 'JSON', + version, + timestamp, + client_id: clientIdSnake, + clientId, + client_secret: clientSecretSnake, + clientSecret, + base_url: baseUrlSnake, + baseUrl = DEFAULT_PDD_ROUTER_URL, + headers = {}, + timeout, + bizParams, + biz_params: bizParamsSnake, + request, + ...rest + } = input; + + if (!String(type || '').trim()) { + return this.fail('type 不能为空', { code: 400 }); + } + + const requestParams = {}; + if (rest && typeof rest === 'object' && !Array.isArray(rest)) { + Object.assign(requestParams, rest); + } + if (bizParams && typeof bizParams === 'object' && !Array.isArray(bizParams)) { + Object.assign(requestParams, bizParams); + } + if (request && typeof request === 'object' && !Array.isArray(request)) { + Object.assign(requestParams, request); + } + + const normalizedAccessToken = accessToken !== undefined ? accessToken : accessTokenSnake; + const normalizedDataType = dataTypeSnake !== undefined ? dataTypeSnake : dataType; + const normalizedClientId = clientId !== undefined ? clientId : clientIdSnake; + const normalizedClientSecret = clientSecret !== undefined ? clientSecret : clientSecretSnake; + const normalizedBaseUrl = baseUrlSnake !== undefined ? baseUrlSnake : baseUrl; + if (bizParamsSnake && typeof bizParamsSnake === 'object' && !Array.isArray(bizParamsSnake)) { + Object.assign(requestParams, bizParamsSnake); + } + + const pddClient = new PddClient(ctx); + const builtRequest = pddClient.buildRequest({ + type, + accessToken: normalizedAccessToken, + dataType: normalizedDataType, + version, + timestamp, + clientId: normalizedClientId, + clientSecret: normalizedClientSecret, + bizParams: requestParams, + }); + + try { + const response = await ctx.curl(String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(headers && typeof headers === 'object' ? headers : {}), + }, + dataType: String(normalizedDataType || 'json').toLowerCase() === 'xml' ? 'text' : 'json', + data: builtRequest.requestBody, + timeout, + }); + + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + const parsedResponse = type === 'pdd.waybill.search' + ? formatPddWaybillSearchResponse(responseData) + : null; + + return this.success('ok', { + data: { + requestBody: builtRequest.requestBody, + signText: builtRequest.signText, + sortedPairs: builtRequest.sortedPairs, + response: responseData, + parsed_response: parsedResponse, + baseUrl: String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), + }, + code: 200, + }); + } catch (error) { + ctx.logger.error('PDD 测试接口调用失败:', error); + return this.fail(error.message || 'PDD 测试接口调用失败', { + code: 500, + data: { + requestBody: builtRequest.requestBody, + signText: builtRequest.signText, + sortedPairs: builtRequest.sortedPairs, + baseUrl: String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), + }, + }); + } + } + // app/controller/i18n.js 中 async getI18nMessage(data) { const { ctx } = this; const { language = 'zh-CN' } = data || ctx.query; - try { - // 1. 直接查询表数据看看 - const allTranslations = await ctx.model.I18nTranslation.findAll({ - limit: 5, - raw: true, - }); - console.log('📊 数据库翻译表数据(前5条):', allTranslations); - - const allKeys = await ctx.model.I18nKey.findAll({ - limit: 5, - raw: true, - }); - console.log('📊 数据库键值表数据(前5条):', allKeys); - - // 2. 检查关联查询 - const testQuery = await ctx.model.I18nTranslation.findAll({ - include: [{ - model: ctx.model.I18nKey, - as: 'key', - required: false, // LEFT JOIN - }], - limit: 5, - raw: false, - }); - - console.log('🔍 关联查询结果:', testQuery.length); - testQuery.forEach((item, index) => { - console.log(`结果${index + 1}:`, { - id: item.id, - language: item.language, - translation: item.translation, - hasKey: !!item.key, - keyName: item.key?.key_name, - }); - }); - - // 3. 按语言查询 - const languageQuery = await ctx.model.I18nTranslation.findAll({ - where: { language }, - include: [{ - model: ctx.model.I18nKey, - as: 'key', - }], - raw: false, - }); - - console.log(`🌍 语言 ${language} 的翻译数量:`, languageQuery.length); - - } catch (error) { - console.error('❌ 数据库查询错误:', error); - ctx.logger.error('数据库查询错误:', error); - } try { // 1. 查询当前项目的所有翻译(默认项目为 'wms') const translations = await ctx.model.I18nTranslation.findAll({ @@ -132,8 +1379,13 @@ class indexService extends MainService { // 构建嵌套路径 for (let i = 0; i < keys.length - 1; i++) { const key = keys[i]; - if (!current[key]) { + // 如果路径节点已存在但非对象(被其他叶子键占用),先保存旧值再转为对象 + if (!current[key] || typeof current[key] !== 'object') { + const oldValue = current[key]; current[key] = {}; + if (oldValue !== undefined) { + current[key]._self = oldValue; + } } current = current[key]; } @@ -328,7 +1580,7 @@ class indexService extends MainService { /** * 从键名提取模块 - * @param keyName + * @param {string} keyName 键名 */ extractModule(keyName) { if (!keyName) return 'common'; @@ -346,8 +1598,8 @@ class indexService extends MainService { /** * 尝试自动翻译新键值(可选功能) - * @param project - * @param targetLanguage + * @param {string} project 项目 + * @param {string} targetLanguage 目标语言 */ async tryAutoTranslateNewKeys(project, targetLanguage) { const { ctx } = this; @@ -389,7 +1641,7 @@ class indexService extends MainService { // 批量创建未翻译的记录 const createPromises = []; - for (const [ keyId, chineseText ] of Object.entries(chineseTranslations)) { + for (const [ keyId ] of Object.entries(chineseTranslations)) { if (!existingKeyIds.has(parseInt(keyId))) { createPromises.push( ctx.model.I18nTranslation.create({ @@ -418,9 +1670,2044 @@ class indexService extends MainService { const result = await service.systems.space.searchSpace(data); return this.success('ok', result); } - async getExpressList(data){ - - return this.success('ok', { data: this.app.config.expressList, code: 200 }); + async searchSpaces(data) { + const { service } = this; + const result = await service.systems.space.searchSpaces(data); + return this.success('ok', result); + } + async listInterfaceTypes() { + const { ctx } = this; + const rows = await ctx.model.InterfaceType.findAll({ + where: { is_enabled: 1, is_store: 1 }, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'description', 'is_enabled' ], + order: [[ 'id', 'ASC' ]], + }); + const list = rows.map(row => { + const item = row.get({ plain: true }); + return { + id: Number(item.id || 0), + interface_code: item.interface_code || '', + interface_name: item.interface_name || '', + interface_category: item.interface_category || '', + description: item.description || '', + is_enabled: Number(item.is_enabled || 0), + }; + }); + return this.success('ok', { list, total: list.length, code: 200 }); + } + async getLocationTypeList() { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null; + const cacheKey = `index:locationTypeList:${warehouseId || 'global'}`; + const cached = await this.app.getCacheAsync(cacheKey); + + if (Array.isArray(cached)) { + return this.success('ok', { list: cached, total: cached.length, code: 200 }); + } + + const where = { + is_active: true, + }; + + if (warehouseId) { + where[Op.or] = [ + { warehouse_id: warehouseId }, + { warehouse_id: null }, + ]; + } else { + where.warehouse_id = null; + } + + const rows = await ctx.model.LocationType.findAll({ + where, + attributes: [ + 'id', + 'type_code', + 'type_name', + 'temperature_zone', + 'allow_allocation', + 'allow_transfer_out', + 'description', + 'warehouse_id', + ], + order: [[ 'warehouse_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + const list = rows.map(item => ({ + id: Number(item.id || 0), + type_code: item.type_code || '', + type_name: item.type_name || '', + temperature_zone: item.temperature_zone || '', + allow_allocation: Boolean(item.allow_allocation), + allow_transfer_out: Boolean(item.allow_transfer_out), + description: item.description || '', + warehouse_id: item.warehouse_id === null || item.warehouse_id === undefined ? null : Number(item.warehouse_id), + })); + + await this.app.setCacheAsync(cacheKey, list, 300); + + return this.success('ok', { list, total: list.length, code: 200 }); + } + /** + * 获取奇门应用列表。 + * + * @return {Promise} 返回奇门应用列表结果 + */ + async getQimenAppList() { + const { ctx } = this; + const cacheKey = 'index:qimenAppList'; + const cached = await this.app.getCacheAsync(cacheKey); + + if (Array.isArray(cached)) { + return this.success('ok', { list: cached, total: cached.length, code: 200 }); + } + + const rows = await ctx.model.QimenApp.findAll({ + attributes: [ 'id', 'name', 'app_key' ], + order: [[ 'id', 'ASC' ]], + }); + const list = rows.map(row => { + const item = typeof row.get === 'function' ? row.get({ plain: true }) : row; + return { + id: Number(item.id || 0), + name: item.name || '', + app_key: item.app_key || '', + }; + }); + + await this.app.setCacheAsync(cacheKey, list, 300); + + return this.success('ok', { list, total: list.length, code: 200 }); + } + /** + * 获取快递列表。 + * + * @param {Object} data 请求参数 + * @param {boolean} [data.systemOnly] 是否仅返回系统基础快递列表 + * @param {string} [data.express_code] 快递公司编码 + * @return {Promise} 返回结果 + */ + async getExpressList(data) { + const { service } = this; + const { + systemOnly, + express_code: expressCode = '', + } = data || {}; + const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly); + const normalizedExpressCode = String(expressCode || '').trim(); + const result = await service.systems.express.getExpressList(isSystemOnly, normalizedExpressCode); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 获取快递产品类型列表。 + * + * @param {Object} data 请求参数 + * @param {string} [data.express_code] 快递公司编码 + * @return {Promise} 返回结果 + */ + async getExpressProductTypeList(data) { + const { service } = this; + const { express_code: expressCode = '' } = data || {}; + const result = await service.systems.express.getExpressProductTypeList(expressCode); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 获取平台列表。 + * + * @param {Object} data 请求参数 + * @param {number|string|boolean} [data.is_system=0] 是否仅返回系统基础平台列表,1 表示仅返回系统平台 + * @param {boolean} [data.systemOnly] 是否仅返回系统基础平台列表 + * @param {boolean} [data.full] 是否返回全量字段 + * @return {Promise} 返回结果 + */ + async getPlatformList(data) { + const { service } = this; + const payload = data || {}; + const { is_system: isSystem = 0, systemOnly, full } = payload; + const systemFilter = Object.prototype.hasOwnProperty.call(payload, 'is_system') ? isSystem : systemOnly; + const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemFilter); + const isFull = [ true, 1, '1', 'true' ].includes(full); + const result = await service.systems.platform.getPlatformList(isSystemOnly, isFull); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 获取打印平台全量列表。 + * + * 供前端新增、修改快递接口时下拉选择使用,不返回分页结构。 + * + * @return {Promise} 返回结果 + */ + async getPrintPlatformList() { + const { service } = this; + const result = await service.systems.setting.expressInterface.getPrintPlatformList(); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 校验店铺打印平台编码是否存在。 + * + * 运行环境未注册 `PrintPlatform` 模型时,仅做大写标准化,避免单测桩环境报错; + * 已注册模型时,强制以 `wms_print_platform.platform_code` 为准。 + * + * @param {string} platformCode 打印平台编码 + * @param {boolean} [isAll=false] 是否返回平台完整信息 + * @return {Promise} 标准化后的打印平台编码 + */ + async ensureShopPrintPlatformExists(platformCode, isAll = false) { + const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); + const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; + + if (!normalizedPlatformCode) { + throw new Error('平台编码不能为空'); + } + + if (!printPlatformModel || typeof printPlatformModel.findOne !== 'function') { + return normalizedPlatformCode; + } + + const printPlatform = await printPlatformModel.findOne({ + where: { + platform_code: normalizedPlatformCode, + deleted: 0, + status: 'ACTIVE', + }, + attributes: [ 'platform_code', 'platid' ], + }); + + if (!printPlatform) { + throw new Error('platform_code 未匹配到打印平台编码'); + } + if (isAll) { + return printPlatform; + } + return normalizedPlatformCode; + } + + /** + * 构建店铺关联打印平台的 Sequelize include 配置。 + * + * @param {boolean} [required=false] 是否强制要求命中打印平台 + * @return {Array} include 配置列表 + */ + buildShopPrintPlatformInclude(required = false) { + const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; + + if (!printPlatformModel) { + return []; + } + + return [{ + model: printPlatformModel, + as: 'printPlatform', + required, + attributes: [ 'platform_code', 'platform_name', 'status' ], + where: { + deleted: 0, + status: 'ACTIVE', + }, + }]; + } + + /** + * 获取当前仓库下的店铺列表。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.platform_code] 平台编码 + * @param {string} [data.platformCode] 平台编码,兼容驼峰字段 + * @return {Promise} 返回店铺列表结果 + */ + async getShopList(data = {}) { + const { ctx } = this; + const { platform_code: platformCodeSnake = '', platformCode: platformCodeCamel = '' } = data || {}; + const warehouseId = Number(ctx.user?.store_id); + + if (!warehouseId) { + return this.fail('未识别到当前仓库', { code: 400 }); + } + + const platformCode = String(platformCodeSnake || platformCodeCamel || '').trim().toUpperCase(); + const where = { + warehouse_id: warehouseId, + status: 1, + ...buildNotDeletedShopWhere(this.app), + }; + + if (platformCode) { + where.platform_code = await this.ensureShopPrintPlatformExists(platformCode); + } + + const list = await ctx.model.Shop.findAll({ + where, + include: this.buildShopPrintPlatformInclude(false), + order: [[ 'status', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + const maskedList = list.map(maskShopListItem); + + return this.success('ok', { data: { list: maskedList }, code: 200 }); + } + + /** + * 实时请求拼多多电子面单网点列表。 + * + * @param {string} accessToken 店铺授权令牌 + * @return {Promise} 拼多多原始响应数据 + * @throws {Error} 拼多多返回错误结构或请求失败时抛出异常 + */ + async requestPddWaybillSearch(accessToken) { + const { ctx } = this; + const pddClient = new PddClient(ctx); + const builtRequest = pddClient.buildRequest({ + type: 'pdd.waybill.search', + accessToken, + dataType: 'JSON', + }); + const response = await ctx.curl(DEFAULT_PDD_ROUTER_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + dataType: 'json', + data: builtRequest.requestBody, + }); + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + + if (responseData && typeof responseData === 'object' && responseData.error_response) { + const errorResponse = responseData.error_response; + throw new Error(errorResponse.error_msg || '拼多多电子面单查询失败'); + } + + return responseData; + } + + /** + * 实时请求拼多多官方标准模板接口。 + * + * @param {Object} payload 请求参数 + * @param {string} payload.accessToken 店铺授权令牌 + * @param {string} payload.wpCode 拼多多平台快递编码 + * @return {Promise} 拼多多原始响应数据 + * @throws {Error} 拼多多返回错误结构或请求失败时抛出异常 + */ + async requestPddStdTemplates(payload = {}) { + const { ctx } = this; + const { + accessToken = '', + wpCode = '', + } = payload || {}; + const normalizedAccessToken = String(accessToken || '').trim(); + const normalizedWpCode = String(wpCode || '').trim(); + + if (!normalizedAccessToken) { + throw new Error('拼多多模板查询 accessToken 不能为空'); + } + + if (!normalizedWpCode) { + throw new Error('拼多多模板查询 wp_code 不能为空'); + } + + const pddClient = new PddClient(ctx); + const builtRequest = pddClient.buildRequest({ + type: 'pdd.cloudprint.stdtemplates.get', + accessToken: normalizedAccessToken, + request: { + wp_code: normalizedWpCode, + }, + dataType: 'JSON', + }); + const response = await ctx.curl(DEFAULT_PDD_ROUTER_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + dataType: 'json', + data: builtRequest.requestBody, + }); + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + + if (responseData && typeof responseData === 'object' && responseData.error_response) { + const errorResponse = responseData.error_response; + throw new Error(errorResponse.error_msg || '拼多多标准模板查询失败'); + } + + return responseData; + } + + /** + * 实时请求淘宝菜鸟电子面单网点列表。 + * + * @param {Object} payload 请求载荷 + * @param {string} [payload.accessToken] 店铺授权令牌(session),为空时不下发 + * @param {string} [payload.cpCode] 快递公司编码 + * @return {Promise} 淘宝原始响应数据 + * @throws {Error} 淘宝返回错误结构或请求失败时抛出异常 + */ + async requestTbWaybillSearch(payload = {}) { + const { ctx } = this; + const { + accessToken, + cpCode = '', + } = payload || {}; + const appKey = String(this.app.config?.qimen?.appKey || '').trim(); + const appSecret = String(this.app.config?.qimen?.security || '').trim(); + + if (!appKey || !appSecret) { + throw new Error('淘宝接口配置缺失'); + } + + const signService = this.service.systems.sign; + if (!signService || typeof signService.signTopRequest !== 'function') { + throw new Error('签名服务不可用'); + } + + const requestParams = { + method: 'cainiao.waybill.ii.search', + app_key: appKey, + timestamp: this.app.formatDate(new Date()), + format: 'json', + v: '2.0', + sign_method: 'md5', + }; + const normalizedAccessToken = String(accessToken || '').trim(); + if (normalizedAccessToken) { + requestParams.session = normalizedAccessToken; + } + + const normalizedCpCode = String(cpCode || '').trim(); + if (normalizedCpCode) { + requestParams.cp_code = normalizedCpCode; + } + + const sign = signService.signTopRequest(requestParams, '', appSecret, 'md5'); + const response = await ctx.curl(DEFAULT_TB_ROUTER_URL, { + method: 'POST', + contentType: 'form', + dataType: 'json', + data: { + ...requestParams, + sign, + }, + }); + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + + if (responseData && typeof responseData === 'object' && responseData.error_response) { + const errorResponse = responseData.error_response; + throw new Error(errorResponse.sub_msg || errorResponse.msg || '淘宝菜鸟电子面单查询失败'); + } + + return responseData; + } + + /** + * 实时请求淘宝菜鸟公共标准面单模板列表。 + * + * @return {Promise} 淘宝原始响应数据 + * @throws {Error} 淘宝返回错误结构或请求失败时抛出异常 + */ + async requestTbCainiaoStdTemplates() { + const { ctx } = this; + const appKey = String(this.app.config?.qimen?.appKey || '').trim(); + const appSecret = String(this.app.config?.qimen?.security || '').trim(); + + if (!appKey || !appSecret) { + throw new Error('淘宝接口配置缺失'); + } + + const signService = this.service.systems.sign; + if (!signService || typeof signService.signTopRequest !== 'function') { + throw new Error('签名服务不可用'); + } + + const requestParams = { + method: 'cainiao.cloudprint.stdtemplates.get', + app_key: appKey, + timestamp: this.app.formatDate(new Date()), + format: 'json', + v: '2.0', + sign_method: 'md5', + }; + + const sign = signService.signTopRequest(requestParams, '', appSecret, 'md5'); + const response = await ctx.curl(DEFAULT_TB_ROUTER_URL, { + method: 'POST', + contentType: 'form', + dataType: 'json', + data: { + ...requestParams, + sign, + }, + }); + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + if (responseData && typeof responseData === 'object' && responseData.error_response) { + const errorResponse = responseData.error_response; + throw new Error(errorResponse.sub_msg || errorResponse.msg || '淘宝菜鸟标准模板查询失败'); + } + + return responseData.cainiao_cloudprint_stdtemplates_get_response.result.datas.standard_template_result || []; + } + /** + * 请求菠萝派标准模板并归一化为菜鸟链路兼容数组。 + * + * @param {string} appSecret 菠萝派访问令牌 + * @param {string|number} platid 菠萝派平台标识 + * @param {boolean} [isJD=false] 是否为京东平台 + * @return {Promise>} 归一化后的模板数组 + * @throws {Error} 当配置缺失或接口返回失败时抛出异常 + */ + async requestPolyStdTemplates(appSecret, platid, isJD = false) { + console.log('请求菠萝派标准模板接口入参', { appSecret: String(appSecret || '').trim() ? '***' : '', platid }); + const { service } = this; + if (!appSecret || !platid) { + throw new Error('菠萝派接口配置缺失'); + } + const query_data = { templatestype: 'ALL' }; + if (platid === 673) { + query_data.BizVersion = '2'; + } + if (platid === 544) { + platid = 611; + } + let interface_url = 'https://api.polyapi.com/OpenAPI/do'; + if (isJD) { + interface_url = 'https://apijd.polyapi.com/OpenAPI/do'; + } + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetTemplates', query_data, { + interface_url, + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + token: appSecret, + platid, + version: '1.0', + }); + console.log('请求菠萝派标准模板接口响应', JSON.stringify(responseData)); + const normalizedResponseData = responseData && typeof responseData === 'object' + ? { + ...responseData, + code: [ 0, '0', 10000, '10000' ].includes(responseData.code) ? 0 : responseData.code, + results: Array.isArray(responseData.results) && responseData.results.length > 0 + ? responseData.results + : Array.isArray(responseData.data) + ? responseData.data + : responseData.results, + } + : responseData; + + if (normalizedResponseData && normalizedResponseData.code !== 0) { + throw new Error(responseData.message || '菠萝派标准模板查询失败'); + } + + const normalizeTemplateItems = items => (Array.isArray(items) ? items : []).map(item => { + const sourceItem = item && typeof item === 'object' ? item : {}; + const { + results: nestedResults, + data: nestedData, + standard_templates: nestedStandardTemplates, + cp_code: itemCpCode, + cpcode: itemCpcode, + cpCode: itemCpCodeCamel, + ...restItem + } = sourceItem; + const standardTemplatesSource = Array.isArray(nestedResults) + ? nestedResults + : Array.isArray(nestedStandardTemplates) + ? nestedStandardTemplates + : Array.isArray(nestedData) + ? nestedData + : []; + const cpCode = itemCpCode ?? itemCpcode ?? itemCpCodeCamel; + + return { + ...restItem, + cp_code: cpCode, + standard_templates: { + standard_template_do: standardTemplatesSource.map(template => { + const sourceTemplate = template && typeof template === 'object' ? template : {}; + + return { + brand_code: sourceTemplate.brand_code || sourceTemplate.brandcode || 'default', + standard_template_id: sourceTemplate.standard_template_id || sourceTemplate.id || '', + standard_template_name: sourceTemplate.standard_template_name || sourceTemplate.name || '', + standard_template_url: sourceTemplate.standard_template_url || sourceTemplate.url || '', + standard_waybill_type: sourceTemplate.standard_waybill_type || sourceTemplate.templatetype || '', + }; + }), + }, + }; + }); + + const normalizedResults = normalizeTemplateItems(normalizedResponseData?.results); + + if (normalizedResults.length > 0) { + return normalizedResults; + } + + return normalizeTemplateItems(normalizedResponseData?.data); + } + /** + * 获取指定店铺的快递签约列表。 + * + * 每个列表项会按 sys_express_code 匹配 wms_express_product_type, + * 补充 product_types: [{ name, code }],未匹配到时返回空数组;PDD 平台不补充该字段。 + * + * @param {Object} data 请求参数 + * @param {string|number} [data.shop_id] 店铺 ID + * @param {string|number} [data.shopId] 店铺 ID,兼容驼峰字段 + * @return {Promise} 返回店铺对应的快递签约列表 + */ + async getShopExpressList(data = {}) { + const { ctx, service } = this; + const { + shop_id: shopIdSnake, + shopId: shopIdCamel, + cp_code: cpCodeSnake, + cpCode: cpCodeCamel, + } = data || {}; + const shopId = [ shopIdSnake, shopIdCamel ].find(item => item !== undefined && item !== null && String(item).trim() !== ''); + + if (shopId === undefined) { + return this.fail('shop_id 不能为空', { code: 400 }); + } + + const warehouseId = Number(ctx.user?.store_id); + + if (!warehouseId) { + return this.fail('未识别到当前仓库', { code: 400 }); + } + + const shop = await ctx.model.Shop.findOne({ + where: { + id: shopId, + warehouse_id: warehouseId, + ...buildNotDeletedShopWhere(this.app), + }, + include: this.buildShopPrintPlatformInclude(true), + }); + + if (!shop) { + return this.fail('店铺不存在', { code: 404 }); + } + + const shopPlain = typeof shop.get === 'function' + ? shop.get({ plain: true }) + : shop; + const platformCode_info = await this.ensureShopPrintPlatformExists(shopPlain.platform_code, true); + let list = []; + const platformCode = platformCode_info.platform_code; + const platid = platformCode_info.platid; + console.log('请求的店铺的platformCode', platformCode); + switch (platformCode) { + case 'PDD': { + const accessToken = String(shopPlain.access_token || '').trim(); + + if (!accessToken) { + return this.fail('店铺未授权', { code: 400 }); + } + + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildPlatformExpressNameMap(expressList, platformCode); + const responseData = await this.requestPddWaybillSearch(accessToken); + const parsed = formatPddWaybillSearchResponse(responseData, expressNameMap); + + if (hasPddSfTimedDeliveryService(parsed.list)) { + await this.service.systems.express.syncPddSfTimedDeliveryExpressProductTypes({ + shopExpressList: parsed.list, + }); + } + + list = parsed.list; + break; + } + case 'CAINIAO': { + const accessToken = String(shopPlain.access_token || '').trim(); + + if (!accessToken) { + return this.fail('店铺未授权', { code: 400 }); + } + + const cpCode = String(cpCodeSnake || cpCodeCamel || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildPlatformExpressNameMap(expressList, 'CAINIAO'); + const responseData = await this.requestTbWaybillSearch({ + accessToken, + cpCode, + }); + const parsed = formatTbWaybillSearchResponse(responseData, expressNameMap); + ctx.logger.info('[SystemMethods.getShopExpressList] cainiao.waybill.ii.search 响应', JSON.stringify({ + shop_id: shopPlain.id, + cp_code: cpCode, + response: responseData, + })); + ctx.logger.info('[SystemMethods.getShopExpressList] cainiao.waybill.ii.search 解析结果', JSON.stringify({ + shop_id: shopPlain.id, + cp_code: cpCode, + parsed, + })); + + list = parsed.list; + break; + } + case 'DY': { + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList, 'DY'); + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { + }, { + interface_url: 'https://api.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }); + console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); + const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); + list = parsed.list; + break; + } + case 'KS':{ + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList, 'KS'); + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { + }, { + interface_url: 'https://api.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }); + console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); + const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); + list = parsed.list; + break; + } + case 'SPH':{ + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList, 'SPH'); + await this.app.setCacheAsync('SPHquery', JSON.stringify({ + interface_url: 'https://api.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }), 3600); + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { + }, { + interface_url: 'https://api.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }); + await this.app.setCacheAsync('SPHrequest', JSON.stringify(responseData), 3600); + const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); + list = parsed.list; + break; + } + case 'XHS':{ + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList, 'XHS'); + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { + BizVersion: '2', + }, { + interface_url: 'https://api.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }); + console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); + const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); + list = parsed.list; + break; + } + case 'JD':{ + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList, 'JD'); + const jdExpressNameMap = { ...expressNameMap }; + + normalizeArray(expressList).forEach(expressItem => { + const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; + const mappingItem = { + name: normalizeText(currentExpressItem.name), + sys_express_code: normalizeText(currentExpressItem.code), + }; + + appendExpressMappingKey(jdExpressNameMap, currentExpressItem.name, mappingItem); + }); + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetProvider', { + + }, { + interface_url: 'https://jd.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }); + console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); + const parsed = formatDyWaybillSearchResponse(responseData, jdExpressNameMap); + parsed.list = normalizeArray(parsed.list).map(item => { + const currentItem = item && typeof item === 'object' ? item : {}; + const expressMapping = resolveExpressMapping(jdExpressNameMap, [ + currentItem.sys_express_code, + currentItem.wp_code, + currentItem.wpCode, + currentItem.wp_name, + currentItem.wpName, + currentItem.providername, + currentItem.cp_name, + currentItem.cpname, + currentItem.providercode, + currentItem.cp_code, + currentItem.cpcode, + ]); + + if (!Object.keys(expressMapping).length) { + return currentItem; + } + + return { + ...currentItem, + wp_name: normalizeText(expressMapping.name) || normalizeText(currentItem.wp_name) || normalizeText(currentItem.wpName), + sys_express_code: normalizeText(expressMapping.sys_express_code) || normalizeText(currentItem.sys_express_code), + }; + }); + const unresolvedItems = normalizeArray(parsed.list).filter(item => { + const currentItem = item && typeof item === 'object' ? item : {}; + return !normalizeText(currentItem.sys_express_code).trim(); + }); + const compensationCandidateCodeSet = new Set(); + + normalizeArray(unresolvedItems).forEach(item => { + const currentItem = item && typeof item === 'object' ? item : {}; + [ + currentItem.wp_code, + currentItem.wpCode, + currentItem.providercode, + currentItem.cp_code, + currentItem.cpcode, + ].forEach(candidateCode => { + const normalizedCandidateCode = normalizeText(candidateCode).trim().toUpperCase(); + + if (normalizedCandidateCode) { + compensationCandidateCodeSet.add(normalizedCandidateCode); + } + }); + }); + + const compensationCandidateCodes = Array.from(compensationCandidateCodeSet); + + if (compensationCandidateCodes.length) { + const { Op } = this.app.Sequelize; + const expressRows = await ctx.model.Express.findAll({ + attributes: [ 'code', 'name', 'JD' ], + where: { + [Op.or]: [ + { + code: { + [Op.in]: compensationCandidateCodes, + }, + }, + { + JD: { + [Op.in]: compensationCandidateCodes, + }, + }, + ], + }, + }); + const compensationExpressMap = {}; + + normalizeArray(expressRows).forEach(expressRow => { + const currentExpressRow = expressRow && typeof expressRow.get === 'function' + ? expressRow.get({ plain: true }) + : expressRow || {}; + const compensationMappingItem = { + name: normalizeText(currentExpressRow.name), + sys_express_code: normalizeText(currentExpressRow.code), + }; + + appendExpressMappingKey(compensationExpressMap, currentExpressRow.code, compensationMappingItem); + appendExpressMappingKey(compensationExpressMap, currentExpressRow.JD, compensationMappingItem); + }); + + parsed.list = normalizeArray(parsed.list).map(item => { + const currentItem = item && typeof item === 'object' ? item : {}; + const currentSysExpressCode = normalizeText(currentItem.sys_express_code).trim(); + + if (currentSysExpressCode) { + return currentItem; + } + + const compensationMapping = resolveExpressMapping(compensationExpressMap, [ + currentItem.wp_code, + currentItem.wpCode, + currentItem.providercode, + currentItem.cp_code, + currentItem.cpcode, + ]); + + if (!Object.keys(compensationMapping).length) { + return currentItem; + } + + const currentWpName = normalizeText(currentItem.wp_name) || normalizeText(currentItem.wpName); + + return { + ...currentItem, + wp_name: currentWpName || normalizeText(compensationMapping.name), + sys_express_code: normalizeText(compensationMapping.sys_express_code), + }; + }); + } + list = parsed.list; + break; + } + default: + list = []; + break; + } + + const listWithProductTypes = await this.attachExpressProductTypes(list, platformCode); + + return this.success('ok', { + data: { + shop_id: shopPlain.id, + platform_code: platformCode, + list: listWithProductTypes, + }, + code: 200, + }); + } + + /** + * 按系统快递编码为店铺快递列表补充快递产品类型。 + * + * 产品类型来源于 wms_express_product_type,读取走系统快递服务缓存。 + * PDD 分支不补充该字段。 + * + * @param {Array} list 店铺快递列表 + * @param {string} [platformCode=''] 店铺所属平台编码 + * @return {Promise} 补充 product_types 后的列表 + */ + async attachExpressProductTypes(list, platformCode = '') { + const { ctx, service } = this; + const normalizedList = normalizeArray(list); + const normalizedPlatformCode = normalizeText(platformCode).trim().toUpperCase(); + + if (normalizedList.length === 0 || normalizedPlatformCode === 'PDD') { + return normalizedList; + } + + let productTypeMap = {}; + + try { + const productTypeList = await service.systems.express.getExpressProductTypeList(); + productTypeMap = buildExpressProductTypeMap(productTypeList); + } catch (error) { + ctx.logger.warn('[SystemMethods.attachExpressProductTypes] 获取快递产品类型失败: %s', error.message); + } + + return normalizedList.map(item => { + const currentItem = item && typeof item === 'object' ? item : {}; + const expressCode = normalizeText(currentItem.sys_express_code).trim().toUpperCase(); + + return { + ...currentItem, + product_types: normalizeArray(productTypeMap[expressCode]), + }; + }); + } + + /** + * 获取淘宝菜鸟 STF 模板列表。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} data.express_code 快递公司编码 + * @return {Promise} 返回模板列表结果 + */ + async getCainiaoStfTemplates(data = {}) { + const { express_code: expressCode = '' } = data || {}; + + return await this.getPrintPlatformTemplateList({ + platform_code: 'CAINIAO', + express_code: expressCode, + }); + } + + /** + * 规范化打印模板查询的平台编码。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.platform_code] 平台编码(下划线) + * @param {string} [data.platformCode] 平台编码(驼峰) + * @return {string} 规范化后的平台编码 + */ + normalizeTemplatePlatformCode(data = {}) { + const normalizedPlatformCode = String( + data.platform_code !== undefined ? data.platform_code : data.platformCode + ).trim().toUpperCase(); + + return normalizedPlatformCode || 'CAINIAO'; + } + + /** + * 规范化打印模板查询的快递编码。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.express_code] 快递编码(下划线) + * @param {string} [data.expressCode] 快递编码(驼峰) + * @return {string} 规范化后的快递编码 + */ + normalizeTemplateExpressCode(data = {}) { + const expressCode = data.express_code !== undefined ? data.express_code : data.expressCode; + + if (expressCode === null || expressCode === undefined) { + return ''; + } + + return String(expressCode).trim().toUpperCase(); + } + + /** + * 获取 wms_express 中指定打印平台对应的字段名。 + * + * @param {string} platformCode 打印平台编码 + * @return {string} 平台对应字段名 + */ + getExpressPlatformFieldName(platformCode) { + const expressModel = this.ctx.model && this.ctx.model.Express; + const rawAttributes = expressModel && expressModel.rawAttributes + ? expressModel.rawAttributes + : {}; + + if (rawAttributes[platformCode]) { + return platformCode; + } + + const matchedAttributeName = Object.keys(rawAttributes).find(attributeName => { + const attribute = rawAttributes[attributeName] || {}; + const attributeField = String(attribute.field || attributeName || '').trim().toUpperCase(); + return attributeField === platformCode; + }); + + if (matchedAttributeName) { + return matchedAttributeName; + } + + throw new Error(`platform_code 未匹配到 wms_express 平台字段: ${platformCode}`); + } + + /** + * 按平台字段与快递编码解析模板可用的快递编码集合。 + * + * @param {string} platformCode 打印平台编码 + * @param {string} expressCode 入参快递编码 + * @return {Promise>} 可用于模板过滤的快递编码集合 + */ + async getTemplateAllowedExpressCodeSet(platformCode, expressCode) { + const fieldName = this.getExpressPlatformFieldName(platformCode); + const normalizedExpressCode = String(expressCode || '').trim().toUpperCase(); + const { Op } = this.app.Sequelize; + const expressRows = await this.ctx.model.Express.findAll({ + attributes: [ 'code', fieldName ], + where: { + [Op.or]: [ + { code: normalizedExpressCode }, + { [fieldName]: normalizedExpressCode }, + ], + }, + }); + console.log('expressCode', normalizedExpressCode); + console.log('expressRows', expressRows); + console.log('fieldName', fieldName); + const allowedCodeSet = new Set(); + + if (normalizedExpressCode) { + allowedCodeSet.add(normalizedExpressCode); + } + + for (const expressRow of Array.isArray(expressRows) ? expressRows : []) { + const plainRow = expressRow && typeof expressRow.get === 'function' + ? expressRow.get({ plain: true }) + : expressRow || {}; + const candidateCodes = [ + plainRow.code, + plainRow[fieldName], + ].map(item => String(item || '').trim().toUpperCase()).filter(Boolean); + + for (const code of candidateCodes) { + allowedCodeSet.add(code); + } + } + + return allowedCodeSet; + } + + /** + * 按快递编码过滤打印平台模板响应。 + * + * @param {Object} responseData 平台模板原始响应 + * @param {string} platformCode 打印平台编码 + * @param {string} expressCode 入参快递编码 + * @return {Promise} 过滤后的首个响应数据;未命中时返回 undefined + */ + async filterPrintPlatformTemplateResponseData(responseData, platformCode, expressCode) { + console.log('入参', platformCode, expressCode); + const normalizedExpressCode = String(expressCode || '').trim().toUpperCase(); + const normalizedResponseData = Array.isArray(responseData) + ? responseData + : []; + // 非 PDD 平台允许不传快递编码,直接回退首条模板。 + if (platformCode !== 'PDD' && !normalizedExpressCode) { + const fallbackTemplateResponseItem = normalizedResponseData[0]; + + if (platformCode === 'JD' && fallbackTemplateResponseItem) { + return appendJdTemplateList(fallbackTemplateResponseItem); + } + + return fallbackTemplateResponseItem; + } + + // 获取对应的wp_code + const allowedCodeSet = await this.getTemplateAllowedExpressCodeSet(platformCode, normalizedExpressCode); + console.log('allowedCodeSet', allowedCodeSet); + // console.log('normalizedResponseData', JSON.stringify(normalizedResponseData)); + // normalizedResponseData数组中的cp_code字段与allowedCodeSet匹配的第一个对象 + const matchedTemplateResponseItem = normalizedResponseData.find(item => { + const itemCpCode = normalizeText(resolveFirstNonEmptyValue([ + item?.cp_code, + item?.cpcode, + item?.cpCode, + ])).trim().toUpperCase(); + return allowedCodeSet.has(itemCpCode); + }); + + if (platformCode === 'JD' && matchedTemplateResponseItem) { + return appendJdTemplateList(matchedTemplateResponseItem); + } + + return matchedTemplateResponseItem; + } + + /** + * 获取打印平台模板缓存键。 + * + * @param {string} platformCode 平台编码 + * @return {string} 缓存键 + */ + getPrintPlatformTemplateCacheKey(platformCode) { + if (platformCode === 'CAINIAO') { + return 'index:cainiao:stfTemplates:responseData'; + } + + if (platformCode === 'PDD') { + return 'index:printPlatform:PDD:templates:v2:responseData'; + } + + return `index:printPlatform:${platformCode}:templates:responseData`; + } + + /** + * 按平台编码请求模板列表。 + * + * 当前已实现 CAINIAO 平台,其它平台返回空对象,便于后续扩展。 + * + * @param {string} platformCode 平台编码 + * @param {string|null} [s=null] 平台密钥或令牌 + * @param {string|number|null} [platid=null] 平台标识ID + * @param {string} [expressCode=''] 快递编码 + * @return {Promise} 平台模板响应 + */ + async requestPrintPlatformTemplateList(platformCode, s = null, platid = null, expressCode = '') { + console.log('请求打印平台模板列表,平台编码:', platformCode, platid); + const platformRequesters = { + CAINIAO: async () => await this.requestTbCainiaoStdTemplates(), + PDD: async () => await this.requestPddTemplateSourceList(s, expressCode), + KS: async () => await this.requestPolyStdTemplates(s, platid), + XHS: async () => await this.requestPolyStdTemplates(s, platid), + SPH: async () => await this.requestPolyStdTemplates(s, platid), + DY: async () => await this.requestPolyStdTemplates(s, platid), + JD: async () => await this.requestPolyStdTemplates(s, platid, true), + }; + const requester = platformRequesters[platformCode]; + + if (!requester) { + return {}; + } + + return await requester(); + } + + /** + * 基于快递编码解析拼多多模板查询候选 wp_code。 + * + * 优先使用 wms_express 的 PDD 平台字段,未命中时回退为入参快递编码。 + * + * @param {string} expressCode 入参快递编码 + * @return {Promise>} 候选 wp_code 数组 + */ + async resolvePddTemplateWpCodeCandidates(expressCode) { + const normalizedExpressCode = String(expressCode || '').trim().toUpperCase(); + + if (!normalizedExpressCode) { + return []; + } + + let fieldName = 'PDD'; + try { + fieldName = this.getExpressPlatformFieldName('PDD'); + } catch (error) { + return [ normalizedExpressCode ]; + } + + const { Op } = this.app.Sequelize; + const expressRows = await this.ctx.model.Express.findAll({ + attributes: [ 'code', fieldName ], + where: { + [Op.or]: [ + { + code: normalizedExpressCode, + }, + { + [fieldName]: normalizedExpressCode, + }, + ], + }, + }); + + const wpCodeList = []; + const wpCodeSet = new Set(); + const appendWpCode = value => { + const wpCode = String(value || '').trim().toUpperCase(); + + if (!wpCode || wpCodeSet.has(wpCode)) { + return; + } + + wpCodeSet.add(wpCode); + wpCodeList.push(wpCode); + }; + + for (const expressRow of normalizeArray(expressRows)) { + const plainRow = expressRow && typeof expressRow.get === 'function' + ? expressRow.get({ plain: true }) + : expressRow || {}; + + appendWpCode(plainRow[fieldName]); + appendWpCode(plainRow.code); + } + + if (!wpCodeList.length) { + appendWpCode(normalizedExpressCode); + } + + return wpCodeList; + } + + /** + * 基于拼多多官方模板直连接口构建模板源列表。 + * + * @param {string} accessToken 店铺授权令牌 + * @param {string} expressCode 入参快递编码 + * @return {Promise>} 模板源数组(包含 cp_code、wp_code 与标准模板结构) + */ + async requestPddTemplateSourceList(accessToken, expressCode = '') { + const normalizedAccessToken = String(accessToken || '').trim(); + + if (!normalizedAccessToken) { + return []; + } + + const wpCodeCandidates = await this.resolvePddTemplateWpCodeCandidates(expressCode); + + if (!wpCodeCandidates.length) { + return []; + } + + const templateSourceList = []; + + for (const wpCodeCandidate of wpCodeCandidates) { + const responseData = await this.requestPddStdTemplates({ + accessToken: normalizedAccessToken, + wpCode: wpCodeCandidate, + }); + const responseRoot = responseData && typeof responseData === 'object' + ? responseData.pdd_cloudprint_stdtemplates_get_response || responseData + : {}; + const templateResponseItems = normalizeFirstWrappedArray([ + responseRoot.result, + responseRoot.results, + responseRoot.standard_template_result, + responseRoot.standard_templates, + responseRoot.datas, + responseRoot.data, + ], [ 'standard_template_result', 'standard_templates', 'results', 'result', 'datas', 'data', 'list' ]); + const normalizedTemplateResponseItems = templateResponseItems.length + ? templateResponseItems + : [ responseRoot ]; + + for (const templateResponseItem of normalizedTemplateResponseItems) { + const sourceItem = templateResponseItem && typeof templateResponseItem === 'object' + ? templateResponseItem + : {}; + const itemWpCode = normalizeText(resolveFirstNonEmptyValue([ + sourceItem.wp_code, + sourceItem.wpCode, + sourceItem.cp_code, + sourceItem.cpcode, + sourceItem.cpCode, + wpCodeCandidate, + ])).trim().toUpperCase(); + const standardTemplateSourceList = normalizeFirstWrappedArray([ + sourceItem.standard_templates, + sourceItem.standard_template_do, + sourceItem.standardTemplateDo, + sourceItem.templates, + sourceItem.template_list, + sourceItem.templateList, + sourceItem.standard_template_result, + sourceItem.results, + sourceItem.result, + sourceItem.datas, + sourceItem.data, + ], [ 'standard_template_do', 'standardTemplateDo', 'standard_template_result', 'results', 'result', 'datas', 'data', 'list' ]); + const normalizedStandardTemplateSourceList = standardTemplateSourceList.length + ? standardTemplateSourceList + : sourceItem.standard_template_id || sourceItem.standard_template_name || sourceItem.standard_template_url + ? [ sourceItem ] + : []; + const normalizedTemplateList = normalizedStandardTemplateSourceList.map(templateItem => { + const sourceTemplate = templateItem && typeof templateItem === 'object' + ? templateItem + : {}; + + return { + standard_template_id: normalizeText(resolveFirstNonEmptyValue([ + sourceTemplate.standard_template_id, + sourceTemplate.id, + sourceTemplate.template_id, + sourceTemplate.templateId, + ])).trim(), + standard_template_name: normalizeText(resolveFirstNonEmptyValue([ + sourceTemplate.standard_template_name, + sourceTemplate.name, + sourceTemplate.template_name, + sourceTemplate.templateName, + ])).trim(), + standard_template_url: normalizeText(resolveFirstNonEmptyValue([ + sourceTemplate.standard_template_url, + sourceTemplate.url, + sourceTemplate.template_url, + sourceTemplate.templateUrl, + ])).trim(), + }; + }); + const seenTemplateUrlSet = new Set(); + const dedupedTemplateList = normalizedTemplateList.filter(templateItem => { + const templateUrl = templateItem && typeof templateItem === 'object' + ? templateItem.standard_template_url + : ''; + + if (seenTemplateUrlSet.has(templateUrl)) { + return false; + } + + seenTemplateUrlSet.add(templateUrl); + return true; + }); + + templateSourceList.push({ + cp_code: itemWpCode, + wp_code: itemWpCode, + standard_templates: { + standard_template_do: dedupedTemplateList, + }, + }); + } + } + + return templateSourceList; + } + + /** + * 获取打印平台模板列表。 + * + * 入参传入哪个平台编码,就返回该平台对应的模板数据。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.platform_code] 平台编码(下划线) + * @param {string} [data.platformCode] 平台编码(驼峰) + * @param {string} data.express_code 快递编码(下划线) + * @param {string} [data.expressCode] 快递编码(驼峰) + * @param {string} [data.shopId] 店铺ID(驼峰) + * + * @return {Promise} 返回模板列表结果 + */ + async getPrintPlatformTemplateList(data = {}) { + console.log('获取打印平台模板列表请求参数', data); + const platformCode = this.normalizeTemplatePlatformCode(data); + const expressCode = this.normalizeTemplateExpressCode(data); + const { ctx } = this; + const warehouseId = Number(ctx.user?.store_id); + + if (!warehouseId) { + return this.fail('未识别到当前仓库', { code: 400 }); + } + + const rawShopId = data.shop_id !== undefined ? data.shop_id : data.shopId; + const shopId = rawShopId !== undefined && rawShopId !== null && rawShopId !== '' + ? Number(rawShopId) + : null; + let shop = null; + + if (Number.isFinite(shopId) && shopId > 0) { + shop = await ctx.model.Shop.findOne({ + where: { + id: shopId, + warehouse_id: warehouseId, + ...buildNotDeletedShopWhere(this.app), + }, + include: this.buildShopPrintPlatformInclude(true), + }); + } + if (platformCode === 'PDD' && !expressCode) { + return this.fail('express_code 不能为空', { code: 400 }); + } + + let accessToken = ''; + let platid = null; + if (shop) { + const shopPlain = typeof shop.get === 'function' + ? shop.get({ plain: true }) + : shop; + + accessToken = String(shopPlain.access_token || '').trim(); + const printPlatformInfo = await this.ensureShopPrintPlatformExists(shopPlain.platform_code, true); + platid = Number(printPlatformInfo && printPlatformInfo.platid); + } + + const hasShopId = Number.isFinite(shopId) && shopId > 0; + const shouldBypassCache = platformCode === 'PDD' + ? hasShopId && Boolean(accessToken) + : hasShopId; + const cacheKey = this.getPrintPlatformTemplateCacheKey(platformCode); + const cached = shouldBypassCache ? null : await this.app.getCacheAsync(cacheKey); + + const hasShopRequestParams = Boolean(accessToken) && Number.isFinite(platid); + + const responseDataFromSource = cached !== null && cached !== undefined + ? cached + : hasShopRequestParams + ? await this.requestPrintPlatformTemplateList(platformCode, accessToken, platid, expressCode) + : await this.requestPrintPlatformTemplateList(platformCode, null, null, expressCode); + console.log('打印平台模板查询原始响应:', JSON.stringify(responseDataFromSource)); + + if (platformCode === 'PDD' && Boolean(accessToken) && (cached === null || cached === undefined)) { + await this.app.setCacheAsync(cacheKey, responseDataFromSource, 3600); + } + console.log('过滤入参', platformCode, expressCode); + const responseData = await this.filterPrintPlatformTemplateResponseData( + responseDataFromSource, + platformCode, + expressCode + ); + console.log('打印平台模板查询过滤后响应:', JSON.stringify(responseData)); + return this.success('ok', { + data: responseData || {}, + code: 200, + }); + } + + /** + * 判断是否为店铺预占记录的唯一约束冲突。 + * + * @param {Error} error 异常对象 + * @return {boolean} 是否可重试的唯一约束冲突 + */ + isPlatformOauthReservationDuplicateError(error) { + if (!error || error.name !== 'SequelizeUniqueConstraintError') { + return false; + } + + const fields = Array.isArray(error.errors) ? error.errors.map(item => item && item.path).filter(Boolean) : []; + return fields.length === 0 || fields.includes('auth_random_code') || fields.includes('shop_name'); + } + + /** + * 获取平台授权预占码前缀配置。 + * + * @return {string} 授权预占码前缀 + */ + getPlatformOauthReservationCodePrefix() { + const { app } = this; + return String(app.config.platformOauthReservationCodePrefix || '').trim(); + } + + /** + * 判断授权预占码是否已带当前前缀。 + * + * @param {string} authRandomCode 授权预占码 + * @param {string} prefix 授权预占码前缀 + * @return {boolean} 是否已带前缀 + */ + hasPlatformOauthReservationCodePrefix(authRandomCode, prefix) { + if (!prefix) { + return true; + } + + return String(authRandomCode || '').startsWith(prefix); + } + + /** + * 规范化平台授权预占码。 + * + * @param {string} authRandomCode 授权预占码 + * @param {string} prefix 授权预占码前缀 + * @return {string} 去掉当前前缀后的裸码,若未带前缀则原样返回 + */ + normalizePlatformOauthReservationCode(authRandomCode, prefix) { + const normalizedCode = String(authRandomCode || '').trim(); + + if (!normalizedCode) { + return ''; + } + + if (prefix && this.hasPlatformOauthReservationCodePrefix(normalizedCode, prefix)) { + return normalizedCode.slice(prefix.length); + } + + return normalizedCode; + } + + /** + * 生成平台授权预占裸码。 + * + * @return {string} 新授权预占裸码 + */ + generatePlatformOauthReservationCode() { + return crypto.randomBytes(24).toString('hex'); + } + + /** + * 创建平台授权的店铺预占记录。 + * + * @param {Object} data 请求参数 + * @param {string|number} data.warehouseId 仓库 ID + * @param {string} data.platformCode 平台编码 + * @return {Promise<{ shop: Object, authRandomCode: string }>} 预占结果 + */ + async createPlatformOauthReservation(data) { + const { ctx } = this; + const { warehouseId, platformCode } = data; + const normalizedPlatformCode = await this.ensureShopPrintPlatformExists(platformCode); + const maxRetryCount = 5; + const prefix = this.getPlatformOauthReservationCodePrefix(); + + const shop = await ctx.model.Shop.findOne({ + where: { + warehouse_id: warehouseId, + platform_code: normalizedPlatformCode, + status: 0, + ...buildNotDeletedShopWhere(this.app), + }, + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + if (shop) { + const storedAuthRandomCode = String(shop.auth_random_code || '').trim(); + if (storedAuthRandomCode) { + const authRandomCode = this.normalizePlatformOauthReservationCode(storedAuthRandomCode, prefix); + + if (authRandomCode !== storedAuthRandomCode) { + shop.auth_random_code = authRandomCode; + await shop.save(); + } + + return { + shop, + authRandomCode, + }; + } + } + + for (let retryIndex = 0; retryIndex < maxRetryCount; retryIndex++) { + const authRandomCode = this.generatePlatformOauthReservationCode(); + + try { + if (shop) { + shop.auth_random_code = authRandomCode; + await shop.save(); + + return { + shop, + authRandomCode, + }; + } + + const createdShop = await ctx.model.Shop.create({ + warehouse_id: warehouseId, + platform_code: normalizedPlatformCode, + shop_name: `PENDING_${authRandomCode}`, + status: 0, + auth_expire_at: null, + auth_random_code: authRandomCode, + }); + + return { + shop: createdShop, + authRandomCode, + }; + } catch (error) { + if (this.isPlatformOauthReservationDuplicateError(error) && retryIndex < maxRetryCount - 1) { + continue; + } + + if (this.isPlatformOauthReservationDuplicateError(error)) { + throw new Error('生成唯一授权码失败,请稍后重试'); + } + + throw error; + } + } + + throw new Error('生成唯一授权码失败,请稍后重试'); + } + + /** + * 获取平台授权链接。 + * + * @param {Object} data 请求参数 + * @param {string} [data.code] 平台编码 + * @param {string} [data.platform_code] 平台编码 + * @param {string} [data.platformCode] 平台编码 + * @return {Promise} 返回包含平台编码、授权链接和独立授权码的结果 + */ + async getPlatformOauthLink(data) { + const { ctx } = this; + const { + code = '', + platform_code: platformCodeSnake = '', + platformCode = '', + } = data || {}; + const rawPlatformCode = String(code || platformCodeSnake || platformCode || '').trim().toUpperCase(); + const warehouseId = String(ctx.user?.store_id ?? '').trim(); + + if (!rawPlatformCode) { + return this.fail('平台编码不能为空', { code: 400 }); + } + + if (!warehouseId) { + return this.fail('未识别到当前仓库', { code: 400 }); + } + + let platform_code = ''; + try { + platform_code = await this.ensureShopPrintPlatformExists(rawPlatformCode); + } catch (error) { + return this.fail(error.message || '平台不存在', { code: 400 }); + } + + const printPlatform = await ctx.model.PrintPlatform.findOne({ + where: { + platform_code, + deleted: 0, + status: 'ACTIVE', + }, + attributes: [ 'platform_code', 'auth_base_url' ], + }); + + if (!printPlatform) { + return this.fail('平台不存在', { code: 400 }); + } + + const authBaseUrl = String(printPlatform.auth_base_url || '').trim(); + if (!authBaseUrl) { + return this.fail('平台授权基础地址未配置', { code: 400 }); + } + + let reservation; + try { + reservation = await this.createPlatformOauthReservation({ warehouseId, platformCode: platform_code }); + } catch (error) { + ctx.logger.error('创建平台授权预占记录失败:', error); + return this.fail(error.message || '创建平台授权预占记录失败', { code: 500 }); + } + + const prefix = this.getPlatformOauthReservationCodePrefix(); + const oauthLink = `${authBaseUrl}${encodeURIComponent(`${prefix}${platform_code}_${reservation.authRandomCode}`)}`; + + return this.success('ok', { + data: { + code: reservation.authRandomCode, + platform_code, + oauth_link: oauthLink, + }, + code: 200, + }); + } + + /** + * 监听平台授权绑定结果。 + * + * @param {Object} data 请求参数 + * @param {string} [data.code] 业务编码 + * @param {string} [data.businessCode] 业务编码 + * @param {boolean} [data.longPoll] 是否启用长轮询 + * @return {Promise} 监听结果 + */ + async listenPlatformOauthBind(data = {}) { + const { service } = this; + const { + code = '', + businessCode = '', + business_code: businessCodeSnake = '', + longPoll = false, + long_poll: longPollSnake = false, + wait = false, + timeoutMs, + timeout_ms: timeoutMsSnake, + } = data || {}; + const result = await service.systems.platform.listenPlatformOauthBind({ + code: code || businessCode || businessCodeSnake, + longPoll: longPoll || longPollSnake || wait, + timeoutMs: timeoutMs || timeoutMsSnake, + }); + + if (result.code) { + return this.success('获取平台授权绑定状态成功', result); + } + + return this.fail(`获取平台授权绑定状态失败:${result.message}`, result); + } + + /** + * 前端请求生成唯一的登录码,后续可以通过这个登录码在IM系统中完成登录状态的绑定。登录码只写入到缓存中,不存储在数据库,具有较短的过期时间(如5分钟),并且只能使用一次。 + * + * @return {Promise} 返回登录码及用户信息 + */ + async loginToIm() { + const { ctx } = this; + const { user } = ctx; + if (!user || !user.id) { + return this.fail('用户未登录', { code: 401 }); + } + + const employeeId = String(user.employees_id ?? '').trim(); + const employeeName = String(user.employees_name ?? '').trim(); + const subjectId = String(user.store_id ?? '').trim(); + const subjectName = String(user.store_name ?? '').trim(); + const avatar = String(user.avatar ?? '').trim(); + const storeType = String(user.store_type ?? '').trim(); + + if (!employeeId || !employeeName || !subjectId || !subjectName || !storeType) { + return this.fail('用户信息不完整', { code: 400 }); + } + + const keyName = crypto.randomBytes(32).toString('hex'); + const cacheKey = `im:sso:code:${keyName}`; + const payload = { + employees_id: employeeId, + employees_name: employeeName, + subject: { + id: subjectId, + name: subjectName, + type: storeType, + }, + avatar, + created_at: Date.now(), + }; + + await this.app.setCacheAsync(cacheKey, payload, 300); + + return this.success('ok', { + data: { + code: keyName, + employees_id: employeeId, + employees_name: employeeName, + subject: payload.subject, + store_type: storeType, + avatar, + }, + code: 200, + }); + } + + async polyapiAuthorizeUrl() { + const { service } = this; + const respone = await service.systems.poloApi.request('Differ.JH.BuildeAuthorizeUrl', { + appkey: this.app.config.poloApi.appKey, + appsecret: this.app.config.poloApi.appSecret, + callbackurl: 'http://39.100.57.68/', + state: '1223456', + itemcode: 'JH_001', + }, { + interface_url: 'http://aliyun.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid: '544', + version: '1.5', + token: 'db820eeeb6c8425eb3f1cc25a28fb2f8', + shoptype: 'JH_001', + ordersource: 'KUAI_SHOU', + }); + return this.success('ok', { + data: { + respone, + }, + code: 200, + }); + } + + /** + * 根据运单号快速查询订单 ID 及其所属波次信息。 + * + * @param {Object} data 请求参数。 + * @param {string} data.waybill_code 运单号。 + * @return {Promise} 统一成功包装响应,包含 order_id 和 waves 数组。 + */ + async toOrder(data = {}) { + const { service } = this; + const { waybill_code: waybillCode } = data; + const result = await service.systems.waybill.toOrder({ waybill_code: waybillCode }); + return this.success('查询成功', result); + } + + /** + * 获取工作台绑定码(免登录、免鉴权) + * 不传 client_code:返回新会话的 client_code + 绑定码; + * 传 client_code:等待绑定完成返回 token,超时/缓存失效时重新生成绑定码后返回。 + * @param {Object} data - { clientCode | client_code } + */ + async getWorkbenchBindCode(data) { + const { service } = this; + try { + const result = await service.systems.workbench.getWorkbenchBindCode(data || {}); + if (result && result.success) { + return this.success('获取工作台绑定码成功', result); + } + return this.fail(result && result.message ? result.message : '获取工作台绑定码失败', undefined); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 通过工作台登录码登录,获取 token(免登录、免鉴权) + * @param {Object} data - { loginCode | login_code } + */ + async LoginWorkbenchByCode(data) { + const { service } = this; + try { + const result = await service.systems.workbench.loginWorkbenchByCode(data || {}); + if (result && result.success) { + return this.success('工作台登录成功', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '工作台登录失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 根据 token 查询用户信息(免登录、免鉴权,工作台工牌扫码用)。 + * + * 支持两种 token: + * 1. 微信工牌码(登录码):base64 的 {uuid:'{oauth_id}_{6位随机}',form:'wechat'}, + * 按 uuid 前缀取 wms_user_oauth.id → 返回 nickname / user_id; + * 已绑定账号(user_id>0)时返回 wms_account_store_employee 的工号名称(real_name), + * 未绑定时直接返回 wms_user_oauth.nickname。 + * 2. ye4s 登录临时码:对应 ye4s_user.tmp_code(旧流程兜底)。 + * + * @param {Object} data 请求参数 + * @param {string} data.token 微信工牌码(base64)或 ye4s 登录临时码 + * @return {Promise} 统一响应结构;命中时返回 real_name 与 user_id/wms_account_id,未命中时返回失败响应(code=404) + */ + async queryUserByToken(data = {}) { + const { ctx } = this; + const { token } = data || {}; + + if (!token || !String(token).trim()) { + return this.fail('token 不能为空', { code: 400 }); + } + + const rawToken = String(token).trim(); + + // 微信工牌码(base64 + uuid + wechat 来源):走 wms_user_oauth 查询 + const wechatBadge = this.parseWechatBadgeCode(rawToken); + if (wechatBadge) { + try { + return await this.queryUserByWechatBadge(wechatBadge.oauthId); + } catch (error) { + ctx.logger.error('工牌查询用户失败:', error); + return this.fail(error.message || '查询用户失败', { code: 500 }); + } + } + + try { + const ye4sClient = ctx.app.mysql.get('ye4s'); + const rows = await ye4sClient.select('ye4s_user', { + where: { + tmp_code: rawToken, + }, + columns: [ 'real_name', 'wms_account_id' ], + limit: 1, + }); + + if (!rows || rows.length === 0) { + return this.fail('用户不存在', { code: 404 }); + } + + const userRecord = rows[0]; + return this.success('查询成功', { + real_name: userRecord.real_name ?? '', + wms_account_id: userRecord.wms_account_id ?? null, + code: 200, + }); + } catch (error) { + ctx.logger.error('查询用户失败:', error); + return this.fail(error.message || '查询用户失败', { code: 500 }); + } + } + + /** + * 解析微信工牌码:base64 的 {uuid:'{oauth_id}_{6位随机}',form:'wechat'} + * - 解码为 JSON 且来源为 wechat 时返回 { oauthId }(wms_user_oauth.id) + * - 其他内容(ye4s 临时码等)返回 null,由调用方走旧逻辑 + * + * @param {string} token 工牌码原文 + * @return {{oauthId: number}|null} 解析结果 + */ + parseWechatBadgeCode(token) { + try { + const text = String(token || '').trim(); + // 快速预判:长度与字符集需符合 base64,避免每条码都走解码 + if (!text || text.length < 16 || !/^[A-Za-z0-9+/=_-]+$/.test(text)) { + return null; + } + const b64 = text.replace(/-/g, '+').replace(/_/g, '/'); + const decoded = Buffer.from(b64, 'base64').toString('utf8'); + if (!decoded || !decoded.trim().startsWith('{')) { + return null; + } + const payload = JSON.parse(decoded); + if (!payload || typeof payload !== 'object') { + return null; + } + const form = payload.form || payload.source || ''; + const uuid = payload.uuid || ''; + if (String(form) !== 'wechat' || !uuid) { + return null; + } + // uuid 形如 {oauth_id}_{6位随机},取前缀作为 wms_user_oauth.id + const oauthId = Number(String(uuid).split('_')[0]); + if (!Number.isInteger(oauthId) || oauthId <= 0) { + return null; + } + return { oauthId }; + } catch (error) { + return null; + } + } + + /** + * 微信工牌查询用户:按 wms_user_oauth.id 取 nickname/user_id; + * 已绑定账号(user_id>0)时返回 wms_account_store_employee 的工号名称(real_name), + * 未绑定/无工号记录时直接返回 wms_user_oauth.nickname。 + * + * @param {number} oauthId wms_user_oauth.id + * @return {Promise} 统一响应结构 + */ + async queryUserByWechatBadge(oauthId) { + const { ctx } = this; + + const oauth = await ctx.model.UserOauth.findByPk(oauthId); + if (!oauth) { + return this.fail('用户不存在', { code: 404 }); + } + + const userId = Number(oauth.user_id) || 0; + let realName = oauth.nickname || ''; + + // 已绑定账号:拉取 wms_account_store_employee 工号名称(real_name,status=1) + if (userId > 0) { + const employee = await ctx.model.AccountStoreEmployee.findOne({ + where: { account_id: userId, status: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (employee && employee.real_name) { + realName = employee.real_name; + } + } + + return this.success('查询成功', { + real_name: realName, + user_id: userId > 0 ? userId : null, + wms_account_id: userId > 0 ? userId : null, + nickname: oauth.nickname || '', + code: 200, + }); + } + + /** + * 上报客户端错误日志(免登录、免权限、免鉴权,保留系统日志)。 + * + * 入参支持三种形态: + * - 单条对象:{ client_type, app_version, device_id, ..., error_message/error_stack 至少一项 } + * - 数组:[ item1, item2, ... ](单次最多 50 条) + * - 包裹对象:{ logs: [ ... ] } + * 字段命名兼容 snake_case 与 camelCase,report_uuid 重复上报静默成功。 + * + * @param {Object|Array} data 上报数据。 + * @return {Promise} 统一响应结构;成功含 total/accepted/duplicated/rejected 统计, + * 参数错误返回 code=400,写入失败返回 code=500。 + */ + async uploadClientErrorLog(data) { + const { service } = this; + // 方法层只做入参形状解构,字段校验、截断与落库逻辑统一在 systems.clientErrorLog 处理 + const list = Array.isArray(data) + ? data + : Array.isArray(data && data.logs) + ? data.logs + : (data && typeof data === 'object' ? [ data ] : []); + + try { + const result = await service.systems.clientErrorLog.upload({ list }); + if (result && result.success) { + return this.success(result.message || '上报成功', { ...result }); + } + + return this.fail(result && result.message ? result.message : '上报失败', { + code: (result && result.code) || 500, + }); + } catch (error) { + return this.fail(`客户端错误日志上报失败: ${error.message}`, { code: 500 }); + } } } module.exports = indexService; diff --git a/app/service/systemMethods/order/archiveOrder.js b/app/service/systemMethods/order/archiveOrder.js new file mode 100644 index 0000000..26b5aa8 --- /dev/null +++ b/app/service/systemMethods/order/archiveOrder.js @@ -0,0 +1,55 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class ArchiveOrderService extends OrderBaseService { + 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 标准的查询条件对象,支持复杂查询。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('archiveOrder', data); + } + + /** + * 查询归档订单详情。 + * + * 默认使用 history 表查询; + * 若调用方显式传入表位参数,则保持调用方指定值。 + * + * @param {Object} data 请求体。 + * @return {Promise} 订单头、商品明细、运单与日志信息。 + */ + async detail(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const tableTypeFields = [ 'tableType', 'tablePosition', 'type', 'moduleName' ]; + const hasTableTypeInput = tableTypeFields.some(field => { + if (!Object.prototype.hasOwnProperty.call(requestData, field)) { + return false; + } + return String(requestData[field] ?? '').trim() !== ''; + }); + + const detailParams = hasTableTypeInput + ? requestData + : { + ...requestData, + tableType: 'history', + }; + + return await super.detail(detailParams); + } +} + +module.exports = ArchiveOrderService; diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js new file mode 100644 index 0000000..d53e234 --- /dev/null +++ b/app/service/systemMethods/order/base.js @@ -0,0 +1,2836 @@ +'use strict'; + +const MainService = require('../../main'); +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const { isInterceptedOrderStatus } = require('../../../lib/intercept_guard'); +const { isLockedOrderStatus } = require('../../../lib/lock_guard'); + +const DEFAULT_PAGE_SIZE = 20; +const MAX_PAGE_SIZE = 500; +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_LIST_BASE_ATTRIBUTES = [ + 'id', 'delivery_order_code', 'pre_delivery_order_code', 'pre_delivery_order_id', + 'order_type', 'order_flag', 'source_order_codes', + 'sys_platform_code', 'sys_platform_name', + 'create_at', + 'place_order_time', 'pay_time', 'pay_no', 'service_code', + 'operator_name', 'operate_time', 'delivery_time', + 'shop_nick', 'seller_nick', 'buyer_nick', + 'buyer_message', 'seller_message', 'remark', + 'total_amount', 'item_amount', 'discount_amount', 'freight', + 'ar_amount', 'got_amount', 'service_fee', + 'logistics_name', + 'delivery_type', 'weight_type', + 'is_urgency', 'invoice_flag', 'status', + 'name', 'zip_code', 'tel', 'mobile', 'email', + 'province', 'city', 'area', 'town', 'detail_address', + 'id_type', 'id_number', + 'sync_status', + 'items', 'items_count', 'items_total', 'items_weight', 'packages_weight', + 'has_sn_item', + 'wave_id', + 'wave_no', + 'wave_strategy_version', + 'wave_scan_result', + 'post_status', 'storage_status', 'pick_status', 'pack_status', + 'inspection_status', 'print_status', 'confirm_print_status', 'claim_status', + 'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status', 'recheck_time', + 'create_channel', + 'store_id', +]; + +const ORDER_B2B_DETAIL_ATTRIBUTES = Object.freeze([ + 'order_id', + 'total_box_count', + 'pickup_plate_number', + 'prep_remark', + 'prep_duration_seconds', + 'is_picked_up', + 'picked_up_at', + 'created_at', + 'prep_at', +]); + +/** B2B 作业明细空值(副表无对应行时的占位输出) */ +const ORDER_B2B_DETAIL_EMPTY = Object.freeze({ + total_box_count: 0, + pickup_plate_number: null, + prep_remark: null, + prep_duration_seconds: 0, + is_picked_up: 'N', + picked_up_at: null, + created_at: null, + prep_at: null, +}); + +/** B2B 作业明细可筛选字段(仅 B2B 域列表开放,避免污染普通订单列表口径) */ +const ORDER_B2B_DETAIL_FILTER_FIELDS = Object.freeze([ + 'total_box_count', + 'pickup_plate_number', + 'prep_remark', + 'prep_duration_seconds', + 'is_picked_up', + 'picked_up_at', + 'created_at', + 'prep_at', +]); + +const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({ + 0: '常规', + 1: '轻货', + 2: '重货', + 3: '冷链', +}); +const CREATE_CHANNEL_LABELS = Object.freeze({ + MANUAL: '手工单', + API: '接口', + QM: '奇门', + STOCKOUT: '出库转单', +}); +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, 3 ], + }, + }, + }, + waveStrategyFallbackOrder: { + modelType: 'current', + defaultWhere: { + step: { + operator: 'ne', + value: 0, + }, + wave_id: { + operator: 'eq', + value: 0, + }, + }, + }, + outboundOrder: { + modelType: 'current', + defaultWhere: { + outbound_status: { + operator: 'in', + value: [ 'fin', 'padding' ], + }, + step: { + operator: 'in', + value: [ 4, 9 ], + }, + }, + }, + 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 { + /** + * 脱敏展示值:保留首尾字符,中间统一替换为 ***。 + * @param {string|number|null|undefined} value 原始值。 + * @return {string|null} 脱敏后的值。 + */ + maskListSensitiveValue(value) { + if (value === null || value === undefined) { + return value; + } + + const normalizedValue = String(value); + if (!normalizedValue) { + return normalizedValue; + } + + const chars = Array.from(normalizedValue); + if (chars.length <= 1) { + return normalizedValue; + } + + return `${chars[0]}***${chars[chars.length - 1]}`; + } + + /** + * 判断订单拦截状态是否属于"已进入拦截流程"的状态。 + * + * requested/requesting/intercepting 为拦截发起中,intercepted_in_transit 为途中拦截成功, + * intercepted_at_warehouse 为仓库拦截成功;intercepted 为历史遗留值,一并兼容。 + * + * @param {*} status 拦截状态值。 + * @return {boolean} 是否已进入拦截流程。 + */ + isInterceptedOrderStatus(status = '') { + return isInterceptedOrderStatus(status); + } + + /** + * 判断订单锁定状态是否属于"已锁定"(lock_status != none)。 + * + * @param {*} status 锁定状态值。 + * @return {boolean} 是否已锁定。 + */ + isLockedOrderStatus(status = '') { + return isLockedOrderStatus(status); + } + + /** + * 断言订单未进入拦截流程,否则抛出阻断异常。 + * + * @param {Object} orderRow 订单行(需含 intercept_status 字段)。 + * @param {string} [actionText='继续作业'] 被阻断的作业文案。 + * @return {void} 无返回值。 + */ + assertOrderNotIntercepted(orderRow = {}, actionText = '继续作业') { + if (!this.isPlainObject(orderRow)) { + return; + } + + if (this.isInterceptedOrderStatus(orderRow.intercept_status)) { + throw new Error(`订单已被拦截,无法${actionText}`); + } + } + + /** + * 获取当前请求对应的仓库ID。 + * @return {number|string|null} 仓库ID。 + */ + getWarehouseId() { + const { ctx } = this; + const warehouseId = ctx?.user?.store_id ?? null; + + return warehouseId === '' ? null : warehouseId; + } + + /** + * 获取订单日志使用的操作人信息。 + * + * 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。 + * + * @return {{ id: string|null, name: string }} 操作人信息。 + */ + getOrderLogOperator() { + const { ctx } = this; + const stateUser = this.isPlainObject(ctx?.state?.user) ? ctx.state.user : null; + const ctxUser = this.isPlainObject(ctx?.user) ? ctx.user : null; + const paramsObject = this.isPlainObject(this.params) ? this.params : {}; + const paramsOperator = this.isPlainObject(paramsObject.__operator) + ? paramsObject.__operator + : (this.isPlainObject(paramsObject.operator) ? paramsObject.operator : null); + const operatorSource = stateUser || ctxUser || paramsOperator || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 获取订单日志使用的仓库ID。 + * + * 取值优先级:显式传入参数 -> 当前上下文仓库 -> ctx.user.warehouse_id -> ctx.user.store_id。 + * + * @param {number|string|null} [preferredWarehouseId=null] 优先使用的仓库ID。 + * @return {number|string|null} 归一化后的仓库ID。 + */ + getOrderLogWarehouseId(preferredWarehouseId = null) { + const { ctx } = this; + const candidates = [ + preferredWarehouseId, + this.getWarehouseId(), + ctx?.user?.warehouse_id, + ctx?.user?.store_id, + ]; + + for (const candidate of candidates) { + if (candidate === undefined || candidate === null || candidate === '') { + continue; + } + return candidate; + } + + return null; + } + + /** + * 规范分页参数并限制 pageSize 上限。 + * @param {Object} pageParams 分页参数。 + * @return {{ page: number, pageSize: number }} 规范化结果。 + */ + 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 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 {number|string} weightType 重量类型值。 + * @return {string} 中文重量类型。 + */ + formatWeightTypeLabel(weightType) { + if (typeof weightType === 'string') { + const trimmedWeightType = weightType.trim(); + + if (!trimmedWeightType) { + return ORDER_WEIGHT_TYPE_LABELS[0]; + } + + if (Object.values(ORDER_WEIGHT_TYPE_LABELS).includes(trimmedWeightType)) { + return trimmedWeightType; + } + } + + const normalizedWeightType = Number(weightType); + if (Number.isInteger(normalizedWeightType) + && Object.prototype.hasOwnProperty.call(ORDER_WEIGHT_TYPE_LABELS, normalizedWeightType)) { + return ORDER_WEIGHT_TYPE_LABELS[normalizedWeightType]; + } + + return ORDER_WEIGHT_TYPE_LABELS[0]; + } + + /** + * 将创建来源渠道编码转换为中文展示值。 + * @param {string} channel 创建来源渠道编码。 + * @return {string} 中文渠道名称。 + */ + formatCreateChannelLabel(channel) { + if (!channel || typeof channel !== 'string') { + return ''; + } + + const trimmedChannel = channel.trim(); + if (Object.prototype.hasOwnProperty.call(CREATE_CHANNEL_LABELS, trimmedChannel)) { + return CREATE_CHANNEL_LABELS[trimmedChannel]; + } + + return trimmedChannel; + } + + /** + * 规范波次扫描结果,空值时默认返回 0(未扫描)。 + * @param {*} scanResult 扫描结果原始值。 + * @return {number|string} 规范化后的扫描结果。 + */ + normalizeWaveScanResult(scanResult) { + if (scanResult === null || scanResult === undefined || scanResult === '') { + return 0; + } + + const numericResult = Number(scanResult); + return Number.isNaN(numericResult) ? scanResult : numericResult; + } + + /** + * 规范波次策略版本,空值时默认返回 0。 + * @param {*} strategyVersion 波次策略版本原始值。 + * @return {number|string} 规范化后的波次策略版本。 + */ + normalizeWaveStrategyVersion(strategyVersion) { + if (strategyVersion === null || strategyVersion === undefined || strategyVersion === '') { + return 0; + } + + const numericVersion = Number(strategyVersion); + return Number.isNaN(numericVersion) ? strategyVersion : numericVersion; + } + + /** + * 规范化订单锁定状态展示值。 + * none 返回 N,其余状态(warehouse/store 等)一律返回 Y。 + * @param {*} lockStatus 锁定状态值。 + * @return {string} Y 或 N。 + */ + normalizeLockStatusFlag(lockStatus) { + const normalizedStatus = String(lockStatus || '').trim() || 'none'; + return normalizedStatus === 'none' ? 'N' : 'Y'; + } + + /** + * 规范订单列表单行输出,保证重量类型直接返回中文。 + * @param {Object} order 订单列表行数据。 + * @return {Object} 规范后的订单列表行数据。 + */ + normalizeOrderListItem(order = {}) { + if (!this.isPlainObject(order)) { + return order; + } + + return { + ...order, + name: this.maskListSensitiveValue(order.name), + tel: this.maskListSensitiveValue(order.tel), + weight_type: this.formatWeightTypeLabel(order.weight_type), + wave_strategy_version: this.normalizeWaveStrategyVersion(order.wave_strategy_version), + wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result), + create_channel: this.formatCreateChannelLabel(order.create_channel), + lock_status: this.normalizeLockStatusFlag(order.lock_status), + is_sn_order: String(order.has_sn_item || '').trim().toUpperCase() === 'Y' ? 'Y' : 'N', + }; + } + + /** + * 获取指定模块的角标展示值。 + * @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); + let contextWarehouseId = this.getWarehouseId(); + + const hasContextWarehouseId = contextWarehouseId !== null + && contextWarehouseId !== undefined + && contextWarehouseId !== ''; + const hasParamWarehouseId = warehouseId !== null + && warehouseId !== undefined + && warehouseId !== ''; + + if (!hasContextWarehouseId && !hasParamWarehouseId) { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (!hasContextWarehouseId) { + contextWarehouseId = warehouseId; + } + + if (hasContextWarehouseId && hasParamWarehouseId + && 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 candidate of candidates) { + const normalizedCandidate = String(candidate ?? '').trim(); + if (!normalizedCandidate) { + continue; + } + + const normalizedType = ORDER_TABLE_TYPE_ALIASES[normalizedCandidate.toLowerCase()]; + if (normalizedType) { + return normalizedType; + } + + 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; + let contextWarehouseId = this.getWarehouseId(); + const normalizedTableType = this.resolveOrderTableType({ tableType }); + const actualWarehouseId = warehouseId ?? contextWarehouseId; + + const hasContextWarehouseId = contextWarehouseId !== null + && contextWarehouseId !== undefined + && contextWarehouseId !== ''; + const hasActualWarehouseId = actualWarehouseId !== null + && actualWarehouseId !== undefined + && actualWarehouseId !== ''; + + if (!hasContextWarehouseId && !hasActualWarehouseId) { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (!hasContextWarehouseId) { + contextWarehouseId = actualWarehouseId; + } + + if (hasContextWarehouseId && hasActualWarehouseId + && 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; + let contextWarehouseId = this.getWarehouseId(); + const normalizedTableType = this.resolveOrderTableType({ tableType }); + const actualWarehouseId = warehouseId ?? contextWarehouseId; + + const hasContextWarehouseId = contextWarehouseId !== null + && contextWarehouseId !== undefined + && contextWarehouseId !== ''; + const hasActualWarehouseId = actualWarehouseId !== null + && actualWarehouseId !== undefined + && actualWarehouseId !== ''; + + if (!hasContextWarehouseId && !hasActualWarehouseId) { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (!hasContextWarehouseId) { + contextWarehouseId = actualWarehouseId; + } + + if (hasContextWarehouseId && hasActualWarehouseId + && 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); + } + } + + /** + * 查询订单关联运单信息。 + * + * 强制同仓校验:查询条件必须同时包含订单ID与仓库ID, + * 禁止仅凭订单ID读取 wms_order_express,避免跨仓串读运单号。 + * 仓库ID优先取订单详情行(order.warehouse_id),缺省时回退当前用户上下文仓库。 + * + * @param {number|string} orderId 订单ID。 + * @param {Object} [order] 订单详情行,用于补充 sys_logistics_code / sys_logistics_name 与仓库ID。 + * @return {Promise} 运单信息列表。 + */ + async getOrderExpressesByOrderId(orderId, order) { + 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 []; + } + + // 强制同仓校验:仓库ID优先取订单行,缺省回退当前上下文仓库;均缺失时拒绝读取 + const contextWarehouseId = this.getWarehouseId(); + const orderWarehouseId = Number(order && order.warehouse_id); + const warehouseId = Number.isFinite(orderWarehouseId) && orderWarehouseId > 0 + ? orderWarehouseId + : (contextWarehouseId !== null && contextWarehouseId !== undefined && contextWarehouseId !== '' + ? Number(contextWarehouseId) + : 0); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return []; + } + + const rows = await orderExpressModel.findAll({ + where: { + order_id: normalizedOrderId, + warehouse_id: warehouseId, + }, + attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'weighing_weight', 'business_key', 'create_at', 'package_material_id', 'package_material_name_snapshot' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const sysLogisticsCode = order && order.sys_logistics_code != null + ? String(order.sys_logistics_code).trim() + : ''; + const sysLogisticsName = order && order.sys_logistics_name != null + ? String(order.sys_logistics_name).trim() + : ''; + + return (Array.isArray(rows) ? rows : []).map(row => ({ + waybill_code: String(row && row.waybill_code || '').trim(), + weighing_weight: row && row.weighing_weight != null ? Number(row.weighing_weight) : null, + sys_logistics_code: sysLogisticsCode, + sys_logistics_name: sysLogisticsName, + 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), + logistics_interface_name: String(row && row.logistics_interface_name || '').trim(), + business_key: String(row && row.business_key || '').trim(), + create_at: row && row.create_at != null ? new Date(row.create_at).getTime() : null, + package_material_id: row && row.package_material_id != null ? Number(row.package_material_id) : null, + package_material_name_snapshot: row && row.package_material_name_snapshot != null ? String(row.package_material_name_snapshot).trim() : null, + })); + } + + /** + * 归一化订单列表中的快递与系统名称字段。 + * @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, + name: this.maskListSensitiveValue(orderRow.name), + tel: this.maskListSensitiveValue(orderRow.tel), + mobile: this.maskListSensitiveValue(orderRow.mobile), + wave_strategy_version: this.normalizeWaveStrategyVersion(orderRow.wave_strategy_version), + wave_scan_result: this.normalizeWaveScanResult(orderRow.wave_scan_result), + 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, + }; + } + + /** + * 批量补齐订单列表的快递号信息。 + * + * 强制同仓校验:运单查询按「订单ID + 仓库ID」分组执行, + * 禁止仅凭订单ID读取 wms_order_express,避免跨仓串读运单号。 + * + * @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; + + // 强制同仓校验:逐订单解析仓库归属(行内 warehouse_id 优先,缺省回退当前上下文仓库), + // 无法确定仓库归属的订单不参与运单查询,避免仅凭订单ID跨仓串读 + const contextWarehouseId = this.getWarehouseId(); + const warehouseIdByOrder = new Map(); + for (const item of list) { + const orderId = Number(item && item.id); + if (!Number.isFinite(orderId) || orderId <= 0) { + continue; + } + const rowWarehouseId = Number(item && item.warehouse_id); + if (Number.isFinite(rowWarehouseId) && rowWarehouseId > 0) { + warehouseIdByOrder.set(orderId, rowWarehouseId); + } else if (contextWarehouseId !== null && contextWarehouseId !== undefined && contextWarehouseId !== '') { + warehouseIdByOrder.set(orderId, Number(contextWarehouseId)); + } + } + + const scopedOrderIds = orderIds.filter(orderId => warehouseIdByOrder.has(orderId)); + const expressRows = []; + if (scopedOrderIds.length > 0) { + const orderIdsByWarehouse = new Map(); + for (const orderId of scopedOrderIds) { + const orderWarehouseId = warehouseIdByOrder.get(orderId); + if (!orderIdsByWarehouse.has(orderWarehouseId)) { + orderIdsByWarehouse.set(orderWarehouseId, []); + } + orderIdsByWarehouse.get(orderWarehouseId).push(orderId); + } + + for (const [ orderWarehouseId, warehouseOrderIds ] of orderIdsByWarehouse.entries()) { + const rows = await orderExpressModel.findAll({ + where: { + order_id: { + [Op.in]: warehouseOrderIds, + }, + warehouse_id: orderWarehouseId, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'platform_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (Array.isArray(rows)) { + expressRows.push(...rows); + } + } + } + + 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); + } + } + + 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); + }); + } + + /** + * 批量补齐订单列表的波次内序号(wms_order_wave_index.wave_index)。 + * 表无记录或查询异常时降级为 0,不影响列表主流程。 + * @param {Object[]} list 订单列表,每项需含 id(订单ID)。 + * @return {Promise} 补齐 wave_index 后的列表。 + */ + async attachOrderWaveIndex(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 => ({ ...item, wave_index: 0 })); + } + + const warehouseId = this.getWarehouseId(); + const { ctx } = this; + const waveIndexMap = new Map(); + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && ctx.model && typeof ctx.model.query === 'function') { + try { + const rows = await ctx.model.query(` + SELECT order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `, { + replacements: { warehouseId, orderIds }, + type: ctx.model.QueryTypes && ctx.model.QueryTypes.SELECT, + }); + + for (const row of (Array.isArray(rows) ? rows : [])) { + const orderId = Number(row && row.order_id || 0); + if (orderId > 0) { + waveIndexMap.set(orderId, Number(row && row.wave_index || 0)); + } + } + } catch (error) { + ctx.logger && ctx.logger.warn && ctx.logger.warn('[order.base.attachOrderWaveIndex] 查询波次序号失败,已降级为 0', { + warehouseId, + orderCount: orderIds.length, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + return list.map(item => { + const orderId = Number(item && item.id); + return { + ...item, + wave_index: Number.isFinite(orderId) && orderId > 0 && waveIndexMap.has(orderId) + ? waveIndexMap.get(orderId) + : 0, + }; + }); + } + + /** + * 提取订单列表中的运单号虚拟筛选条件。 + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, expressNumbers: string[] }} 清洗后的 where 与运单号集合。 + */ + extractOrderListExpressVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const waybillCondition = normalizedWhere.waybill_codes; + const expressCondition = normalizedWhere.express_numbers; + + delete normalizedWhere.waybill_codes; + delete normalizedWhere.express_numbers; + + const expressNumbers = Array.from(new Set([ + ...this.normalizeExpressFilterValues(waybillCondition), + ...this.normalizeExpressFilterValues(expressCondition), + ])); + + return { + where: normalizedWhere, + expressNumbers, + }; + } + + /** + * 提取买家留言虚拟筛选条件 buyer_message_has。 + * 覆盖 buyer_message / seller_message / remark 三个字段,任一有值即为"有留言"。 + * 将其从 where 中移除并解析为布尔值,后续在 buildWhere 之后注入 Sequelize 条件。 + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, buyerMessageHas: boolean|null }} 清洗后的 where 与买家留言标记。 + */ + extractBuyerMessageHasVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const buyerMessageHasCondition = normalizedWhere.buyer_message_has; + + delete normalizedWhere.buyer_message_has; + + if (!buyerMessageHasCondition) { + return { where: normalizedWhere, buyerMessageHas: null }; + } + + const rawValue = this.isPlainObject(buyerMessageHasCondition) + && Object.prototype.hasOwnProperty.call(buyerMessageHasCondition, 'value') + ? buyerMessageHasCondition.value + : buyerMessageHasCondition; + + // 兼容布尔值、字符串 'true'/'false'、'Y'/'N'、数字 1/0、以及前端 select 组件值 'has'/'empty'/'none' + const normalizedRawValue = typeof rawValue === 'string' ? rawValue.trim().toLowerCase() : rawValue; + if (rawValue === true || normalizedRawValue === 'true' || normalizedRawValue === 'y' || normalizedRawValue === 'has' || rawValue === 1) { + return { where: normalizedWhere, buyerMessageHas: true }; + } + if (rawValue === false || normalizedRawValue === 'false' || normalizedRawValue === 'n' || normalizedRawValue === 'empty' || normalizedRawValue === 'none' || rawValue === 0) { + return { where: normalizedWhere, buyerMessageHas: false }; + } + + return { where: normalizedWhere, buyerMessageHas: null }; + } + + /** + * 提取 stock_query 虚拟筛选条件。 + * 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。 + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, stockQuery: string }} 清洗后的 where 与 stock_query 值。 + */ + extractStockQueryVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const stockQueryCondition = normalizedWhere.stock_query; + + delete normalizedWhere.stock_query; + + if (!stockQueryCondition) { + return { where: normalizedWhere, stockQuery: '' }; + } + + const rawValue = this.isPlainObject(stockQueryCondition) + && Object.prototype.hasOwnProperty.call(stockQueryCondition, 'value') + ? stockQueryCondition.value + : stockQueryCondition; + + const stockQuery = typeof rawValue === 'string' ? rawValue.trim() : ''; + + return { where: normalizedWhere, stockQuery }; + } + + /** + * 提取 wave_index(波次内序号)虚拟筛选条件。 + * 序号存储在 wms_order_wave_index 副表,需先查副表得到订单 ID 集合再注入主查询。 + * 支持 eq / in / gt / lt / ge / le / between / notbetween 等操作符, + * 其中 between 要求 value 为长度为 2 的数组(如 [1, 50])。 + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, waveIndexCondition: Object|null }} 清洗后的 where 与序号筛选条件。 + */ + extractWaveIndexVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const waveIndexCondition = normalizedWhere.wave_index ?? normalizedWhere.waveIndex; + + delete normalizedWhere.wave_index; + delete normalizedWhere.waveIndex; + + // 条件为空时忽略 + if (waveIndexCondition === undefined || waveIndexCondition === null || waveIndexCondition === '') { + return { where: normalizedWhere, waveIndexCondition: null }; + } + + if (this.isPlainObject(waveIndexCondition) + && (waveIndexCondition.value === undefined || waveIndexCondition.value === null || waveIndexCondition.value === '')) { + return { where: normalizedWhere, waveIndexCondition: null }; + } + + // 兼容简写:wave_index 直接传数值时按 eq 处理 + const normalizedCondition = this.isPlainObject(waveIndexCondition) + ? { ...waveIndexCondition } + : { operator: 'eq', value: waveIndexCondition }; + + return { where: normalizedWhere, waveIndexCondition: normalizedCondition }; + } + + /** + * 提取 wave_scope(波次范围)虚拟筛选条件。 + * 将其从 where 中移除并解析为波次范围值集合,后续直接生成订单表 wave_scope 字段过滤。 + * 取值约定:0=未分配波次,1=大团购,2=散单,3=小团购,4=单品单件;value 支持单个值或数组(多选)。 + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, waveScope: number[]|null }} 清洗后的 where 与波次范围值集合。 + */ + extractWaveScopeVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const waveScopeCondition = normalizedWhere.wave_scope ?? normalizedWhere.waveScope; + + delete normalizedWhere.wave_scope; + delete normalizedWhere.waveScope; + + // 条件为空时忽略 + if (waveScopeCondition === undefined || waveScopeCondition === null || waveScopeCondition === '') { + return { where: normalizedWhere, waveScope: null }; + } + + const sourceValue = this.isPlainObject(waveScopeCondition) + && Object.prototype.hasOwnProperty.call(waveScopeCondition, 'value') + ? waveScopeCondition.value + : waveScopeCondition; + + // 兼容简写:wave_scope 直接传数值或数组时按 eq/in 处理 + const sourceItems = Array.isArray(sourceValue) ? sourceValue : [ sourceValue ]; + const normalizedScopes = Array.from(new Set( + sourceItems + .filter(item => item !== undefined && item !== null && item !== '') + .map(item => Number(item)) + )); + + for (const scope of normalizedScopes) { + if (!Number.isInteger(scope) || scope < 0 || scope > 4) { + throw new Error('wave_scope 参数不合法,仅支持 0(未分配波次)/1(大团购)/2(散单)/3(小团购)/4(单品单件)'); + } + } + + return { + where: normalizedWhere, + waveScope: normalizedScopes.length > 0 ? normalizedScopes : null, + }; + } + + /** + * 提取 is_sn_order(是否序列号订单)虚拟筛选条件。 + * + * 订单表已冗余 has_sn_item 字段(建单时按明细 stock_warehouse.is_sn_mgmt 聚合), + * 因此这里仅做参数归一化,后续直接生成订单表字段条件,无需反查明细。 + * 原始列 has_sn_item 仍走通用 where 解析,可继续按标准操作符(eq/ne/in 等)使用。 + * + * 取值兼容:Y/N、1/0、true/false、是/否,以及 { value } 标准结构。 + * + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, isSnOrder: boolean|null }} 清洗后的 where 与序列号订单筛选值。 + */ + extractSnOrderVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const snCondition = normalizedWhere.is_sn_order + ?? normalizedWhere.isSnOrder; + + delete normalizedWhere.is_sn_order; + delete normalizedWhere.isSnOrder; + + if (snCondition === undefined || snCondition === null || snCondition === '') { + return { where: normalizedWhere, isSnOrder: null }; + } + + const rawValue = this.isPlainObject(snCondition) + && Object.prototype.hasOwnProperty.call(snCondition, 'value') + ? snCondition.value + : snCondition; + + if (rawValue === undefined || rawValue === null || rawValue === '') { + return { where: normalizedWhere, isSnOrder: null }; + } + + const normalizedValue = typeof rawValue === 'string' + ? rawValue.trim().toLowerCase() + : rawValue; + + if (normalizedValue === true || normalizedValue === 1 + || [ 'y', 'yes', 'true', '1', '是' ].includes(normalizedValue)) { + return { where: normalizedWhere, isSnOrder: true }; + } + + if (normalizedValue === false || normalizedValue === 0 + || [ 'n', 'no', 'false', '0', '否' ].includes(normalizedValue)) { + return { where: normalizedWhere, isSnOrder: false }; + } + + throw new Error('is_sn_order 参数不合法,仅支持 Y/N(或 true/false、1/0)'); + } + + /** + * 构建 is_sn_order(是否序列号订单)筛选条件。 + * + * has_sn_item='Y' 视为序列号订单;N 条件兼容历史 NULL 行(未回填前按非序列号订单处理)。 + * + * @param {boolean|null} isSnOrder true=仅序列号订单,false=仅非序列号订单,null=不过滤。 + * @return {Object|null} Sequelize 条件,无效值返回 null。 + */ + buildSnOrderFilterCondition(isSnOrder) { + if (typeof isSnOrder !== 'boolean') { + return null; + } + + const { Op } = this.app.Sequelize; + + if (isSnOrder) { + return { + has_sn_item: { [Op.eq]: 'Y' }, + }; + } + + return { + [Op.or]: [ + { has_sn_item: { [Op.is]: null } }, + { has_sn_item: { [Op.ne]: 'Y' } }, + ], + }; + } + + /** + * 提取 sn_code(按 SN 码反查订单)虚拟筛选条件。 + * + * 兼容 sn_code / snCode / sn_codes / snCodes 四种写法,值支持单个字符串 + * (逗号/空格/分号分隔多个)、字符串数组,以及 { value } 标准结构。 + * 取值仅做 trim 与去重,不做模糊匹配(扫码得到的是完整 SN 码)。 + * + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, snCodes: string[] }} 清洗后的 where 与 SN 码列表。 + */ + extractSnCodeVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + + const rawCondition = normalizedWhere.sn_code + ?? normalizedWhere.snCode + ?? normalizedWhere.sn_codes + ?? normalizedWhere.snCodes; + + delete normalizedWhere.sn_code; + delete normalizedWhere.snCode; + delete normalizedWhere.sn_codes; + delete normalizedWhere.snCodes; + + const value = this.isPlainObject(rawCondition) + && Object.prototype.hasOwnProperty.call(rawCondition, 'value') + ? rawCondition.value + : rawCondition; + + const candidates = Array.isArray(value) ? value : [ value ]; + const snCodes = Array.from(new Set( + candidates + .flatMap(item => String(item === undefined || item === null ? '' : item).split(/[\s,;]+/)) + .map(code => code.trim()) + .filter(Boolean) + )); + + return { + where: normalizedWhere, + snCodes, + }; + } + + /** + * 根据 SN 码查询 wms_order_item_sn 命中的订单ID。 + * + * 订单表结构不变,仅用 SN 码表反查 order_id 后回填到订单列表条件中; + * 查询走 (warehouse_id, sn_code) 唯一键或 idx_wms_order_item_sn_sn_code。 + * + * @param {string[]} snCodes SN 码列表。 + * @param {number|string} [warehouseId] 仓库ID(必须与当前上下文一致)。 + * @return {Promise} 命中的订单ID列表。 + */ + async findOrderIdsBySnCodes(snCodes = [], warehouseId = this.getWarehouseId()) { + 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 normalizedSnCodes = Array.from(new Set( + (Array.isArray(snCodes) ? snCodes : []) + .map(code => String(code || '').trim()) + .filter(Boolean) + )); + + if (normalizedSnCodes.length === 0) { + return []; + } + + const orderItemSnModel = this.ctx.model && this.ctx.model.OrderItemSn; + if (!orderItemSnModel || typeof orderItemSnModel.findAll !== 'function') { + return []; + } + + const { Op } = this.app.Sequelize; + const rows = await orderItemSnModel.findAll({ + where: { + warehouse_id: contextWarehouseId, + sn_code: { [Op.in]: normalizedSnCodes }, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + return Array.from(new Set((Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + } + + /** + * 根据 wave_index 筛选条件查询 wms_order_wave_index 命中的订单ID。 + * @param {Object} waveIndexCondition 序号筛选条件(含 operator/value)。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 命中的订单ID列表。 + */ + async findOrderIdsByWaveIndexCondition(waveIndexCondition = null, warehouseId = this.getWarehouseId()) { + 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。'); + } + + if (!waveIndexCondition || !this.isPlainObject(waveIndexCondition)) { + return []; + } + + const orderWaveIndexModel = this.ctx.model && this.ctx.model.OrderWaveIndex; + if (!orderWaveIndexModel || typeof orderWaveIndexModel.findAll !== 'function') { + return []; + } + + const parsed = parseWhereConditions({ + where: { wave_index: waveIndexCondition }, + app: this.app, + }); + + if (!parsed.ok) { + throw new Error(`wave_index 参数解析失败: ${parsed.reason}`); + } + + const { Sequelize } = this.app; + const conditions = Array.isArray(parsed.result.dynamicConditions) + ? parsed.result.dynamicConditions + : []; + + if (conditions.length === 0) { + return []; + } + + const waveIndexWhere = conditions.length > 1 + ? { [Sequelize.Op.and]: conditions } + : conditions[0]; + + const rows = await orderWaveIndexModel.findAll({ + where: { + [Sequelize.Op.and]: [ + waveIndexWhere, + { warehouse_id: contextWarehouseId }, + ], + }, + attributes: [ 'order_id' ], + raw: true, + }); + + return Array.from(new Set((Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + } + + /** + * 根据波次范围(wave_scope)构建订单表 wave_scope 字段过滤条件。 + * 订单表已冗余 wave_scope 字段(写入波次时维护),直接按字段过滤, + * 无需再反查 wms_wave_batch。 + * @param {Array} waveScopes 波次范围值集合(0/1/2/3/4)。 + * @return {Object|null} Sequelize 条件,无有效范围时返回 null。 + */ + buildWaveScopeFilterCondition(waveScopes = []) { + const { Op } = this.app.Sequelize; + const normalizedScopes = Array.from(new Set( + (Array.isArray(waveScopes) ? waveScopes : [ waveScopes ]) + .filter(scope => scope !== undefined && scope !== null && scope !== '') + .map(scope => Number(scope)) + )).filter(scope => Number.isInteger(scope) && scope >= 0 && scope <= 4); + + if (normalizedScopes.length === 0) { + return null; + } + + return { + wave_scope: { + [Op.in]: normalizedScopes, + }, + }; + } + + /** + * 构建 buyer_message_has 虚拟字段的 Sequelize where 条件。 + * 覆盖三个留言/备注字段:buyer_message、seller_message、remark。 + * @param {boolean} hasMessage true=任一字段有留言,false=三个字段全部为空。 + * @return {Object|null} Sequelize where 条件,无效时返回 null。 + */ + buildBuyerMessageHasCondition(hasMessage) { + if (typeof hasMessage !== 'boolean') { + return null; + } + const { Op } = this.app.Sequelize; + const hasContent = col => ({ + [Op.and]: [ + { [col]: { [Op.not]: null } }, + { [col]: { [Op.ne]: '' } }, + ], + }); + const isEmpty = col => ({ + [Op.or]: [ + { [col]: { [Op.is]: null } }, + { [col]: { [Op.eq]: '' } }, + ], + }); + const fields = [ 'buyer_message', 'seller_message', 'remark' ]; + if (hasMessage) { + return { [Op.or]: fields.map(col => hasContent(col)) }; + } + return { [Op.and]: fields.map(col => isEmpty(col)) }; + } + + /** + * 将附加条件并入 queryWhere,兼容 flat 对象与 { [Op.and]: [...] } 结构。 + * @param {Object} queryWhere 现有 Sequelize where 条件。 + * @param {Object} extraCondition 待并入的条件。 + * @return {Object} 合并后的 where 条件。 + */ + appendConditionToWhere(queryWhere = {}, extraCondition = null) { + if (!extraCondition || !this.isPlainObject(extraCondition) + || (Object.keys(extraCondition).length === 0 && Object.getOwnPropertySymbols(extraCondition).length === 0)) { + return queryWhere; + } + const { Op } = this.app.Sequelize; + + if (!this.isPlainObject(queryWhere) + || (Object.keys(queryWhere).length === 0 && Object.getOwnPropertySymbols(queryWhere).length === 0)) { + return extraCondition; + } + + if (Array.isArray(queryWhere[Op.and])) { + return { + ...queryWhere, + [Op.and]: [ ...queryWhere[Op.and], extraCondition ], + }; + } + + return { + [Op.and]: [ queryWhere, extraCondition ], + }; + } + + /** + * 规范化运单号筛选输入,兼容字符串、数组与 { value } 结构。 + * @param {*} condition 运单号筛选条件。 + * @return {string[]} 规范化后的运单号列表。 + */ + normalizeExpressFilterValues(condition) { + const sourceValue = this.isPlainObject(condition) && Object.prototype.hasOwnProperty.call(condition, 'value') + ? condition.value + : condition; + const sourceItems = []; + + if (Array.isArray(sourceValue)) { + sourceItems.push(...sourceValue); + } else if (typeof sourceValue === 'string') { + sourceItems.push(...sourceValue.split(',')); + } else if (sourceValue !== undefined && sourceValue !== null && sourceValue !== '') { + sourceItems.push(sourceValue); + } + + return sourceItems + .map(item => String(item || '').trim()) + .filter(Boolean); + } + + /** + * 根据运单号筛选条件查询命中的订单ID。 + * @param {string[]} expressNumbers 运单号列表。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 命中的订单ID列表。 + */ + async findOrderIdsByExpressNumbers(expressNumbers = [], warehouseId = this.getWarehouseId()) { + 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 normalizedExpressNumbers = Array.from(new Set( + (Array.isArray(expressNumbers) ? expressNumbers : []) + .map(item => String(item || '').trim()) + .filter(Boolean) + )); + + if (normalizedExpressNumbers.length === 0) { + return []; + } + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return []; + } + + const { Op } = this.app.Sequelize; + const rows = await orderExpressModel.findAll({ + where: { + warehouse_id: contextWarehouseId, + waybill_code: { + [Op.in]: normalizedExpressNumbers, + }, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + return Array.from(new Set((Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + } + + /** + * 根据 stock_query 模糊查询 stock_warehouse(商品编码、商品名称、主键ID)和 stock_barcodes(条码), + * 找到匹配的 stock_id,再通过 order_items 查找关联的订单 ID。 + * 若未匹配到任何 stock 则返回空数组,下游会将订单列表结果置空。 + * @param {string} stockQuery 模糊查询关键词。 + * @param {string} moduleName 模块名称(用于确定 order_items 表类型)。 + * @param {number|string} [warehouseId] 仓库ID。 + * @return {Promise} 命中的订单ID列表。 + */ + async findOrderIdsByStockQuery(stockQuery = '', moduleName = 'order', warehouseId = null) { + 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。'); + } + + if (!stockQuery || typeof stockQuery !== 'string') { + return []; + } + + const trimmedQuery = stockQuery.trim(); + if (!trimmedQuery) { + return []; + } + + const { Op } = this.app.Sequelize; + const likePattern = `%${trimmedQuery}%`; + + // 第一步:从 stock_warehouse 模糊查询 item_code、item_name 和 id + const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse; + const stockIdsFromWarehouse = []; + if (stockWarehouseModel) { + const stockRows = await stockWarehouseModel.findAll({ + where: { + warehouse_id: contextWarehouseId, + is_valid: 'Y', + [Op.or]: [ + { item_code: { [Op.like]: likePattern } }, + { item_name: { [Op.like]: likePattern } }, + { id: { [Op.like]: likePattern } }, + ], + }, + attributes: [ 'id' ], + raw: true, + }); + for (const row of stockRows) { + stockIdsFromWarehouse.push(Number(row.id)); + } + } + + // 第二步:从 stock_barcodes 模糊查询 barcode + const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode; + const stockIdsFromBarcodes = []; + if (stockBarcodeModel) { + const barcodeRows = await stockBarcodeModel.findAll({ + where: { + warehouse_id: contextWarehouseId, + barcode: { [Op.like]: likePattern }, + }, + attributes: [ 'stock_id' ], + raw: true, + }); + for (const row of barcodeRows) { + stockIdsFromBarcodes.push(Number(row.stock_id)); + } + } + + // 第三步:合并去重所有匹配的 stock_id + const allStockIds = Array.from(new Set([ ...stockIdsFromWarehouse, ...stockIdsFromBarcodes ])) + .filter(id => Number.isFinite(id) && id > 0); + + if (allStockIds.length === 0) { + return []; + } + + // 第四步:通过 order_items 查找关联的 order_id + const moduleConfig = this.getModuleConfig(moduleName); + const tableType = moduleConfig.modelType || 'current'; + const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, contextWarehouseId); + const orderItemRows = await orderItemsModel.findAll({ + where: { + stock_id: { [Op.in]: allStockIds }, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + return Array.from(new Set( + (Array.isArray(orderItemRows) ? orderItemRows : []) + .map(row => Number(row && row.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0) + )); + } + + /** + * 将命中的订单ID并入 Sequelize where 条件。 + * @param {Object} queryWhere 原始 where 条件。 + * @param {number[]} orderIds 命中的订单ID。 + * @return {Object} 合并后的 where 条件。 + */ + appendOrderIdsFilterToWhere(queryWhere = {}, orderIds = []) { + const { Op } = this.app.Sequelize; + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(item => Number(item)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + const orderIdCondition = { + id: { + [Op.in]: normalizedOrderIds, + }, + }; + + if (!this.isPlainObject(queryWhere) + || (Object.keys(queryWhere).length === 0 && Object.getOwnPropertySymbols(queryWhere).length === 0)) { + return orderIdCondition; + } + + if (Array.isArray(queryWhere[Op.and])) { + return { + ...queryWhere, + [Op.and]: [ ...queryWhere[Op.and], orderIdCondition ], + }; + } + + return { + [Op.and]: [ queryWhere, orderIdCondition ], + }; + } + + /** + * 构造列表排序参数。 + * @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 flatWhere = {}; + const andConditions = []; + + for (const condition of mergedConditions) { + if (this.isMergeableWhereCondition(condition)) { + Object.assign(flatWhere, condition); + continue; + } + + andConditions.push(condition); + } + + if (andConditions.length === 0) { + return flatWhere; + } + + if (Object.keys(flatWhere).length > 0) { + andConditions.unshift(flatWhere); + } + + return { + [Sequelize.Op.and]: andConditions, + }; + } + + /** + * 查询模块列表。 + * + * 默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),B2B 域列表通过 + * options.fixedWhere 指定 is_b2b 条件时不追加默认排除。 + * + * @param {string} moduleName 模块名称。 + * @param {Object} data 请求体。 + * @param {Object} [options] 查询选项。 + * @param {Object} [options.fixedWhere] 强制附加的筛选条件,与请求 where 取 AND, + * 不可被请求中的同名字段覆盖(用于 B2B 等固定域列表)。 + * @param {boolean} [options.b2bDetailFilter=false] 是否支持用 wms_order_b2b 作业明细字段 + * (total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds / + * is_picked_up / picked_up_at / created_at / prep_at)作为筛选条件。 + * @return {Promise} 列表与分页信息。 + */ + async listByModule(moduleName = 'order', data = {}, options = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const fixedWhere = this.isPlainObject(normalizedOptions.fixedWhere) + ? normalizedOptions.fixedWhere + : null; + const contextWarehouseId = this.getWarehouseId(); + const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData); + const { where } = this.prepareWhereContext(requestData, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); + const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); + const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); + const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterStockQuery); + const { where: whereAfterWaveScope, waveScope } = this.extractWaveScopeVirtualFilter(whereAfterWaveIndex); + const { where: whereAfterSnOrder, isSnOrder } = this.extractSnOrderVirtualFilter(whereAfterWaveScope); + const { where: whereAfterSnCode, snCodes } = this.extractSnCodeVirtualFilter(whereAfterSnOrder); + const { where: whereAfterB2bDetail, b2bDetailFilters } = normalizedOptions.b2bDetailFilter === true + ? this.extractB2bDetailVirtualFilter(whereAfterSnCode) + : { where: whereAfterSnCode, b2bDetailFilters: null }; + const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterB2bDetail); + let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (fixedWhere) { + queryWhere = this.appendConditionToWhere(queryWhere, fixedWhere); + } + + // 非 B2B 域列表:默认排除 B2B 订单(B2B 域列表由 fixedWhere 指定 is_b2b='Y') + if (!fixedWhere || !Object.prototype.hasOwnProperty.call(fixedWhere, 'is_b2b')) { + queryWhere = this.appendConditionToWhere(queryWhere, this.buildExcludeB2bCondition()); + } + + if (b2bDetailFilters) { + const b2bOrderIds = await this.findOrderIdsByB2bDetailFilters(b2bDetailFilters, contextWarehouseId); + if (b2bOrderIds !== null) { + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, b2bOrderIds); + } + } + + if (expressNumbers.length > 0) { + const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); + } + + if (buyerMessageHas !== null) { + const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas); + queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); + } + + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, moduleName, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds); + } + + if (waveIndexCondition) { + const waveIndexOrderIds = await this.findOrderIdsByWaveIndexCondition(waveIndexCondition, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, waveIndexOrderIds); + } + + if (waveScope) { + const waveScopeCondition = this.buildWaveScopeFilterCondition(waveScope); + queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition); + } + + if (isSnOrder !== null) { + const snOrderCondition = this.buildSnOrderFilterCondition(isSnOrder); + queryWhere = this.appendConditionToWhere(queryWhere, snOrderCondition); + } + + if (snCodes.length > 0) { + const snOrderIds = await this.findOrderIdsBySnCodes(snCodes, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, snOrderIds); + } + + const model = await this.getOrderModel(moduleName, contextWarehouseId); + const order = this.buildListOrder(requestData.sort, moduleName); + const offset = (page - 1) * pageSize; + const moduleConfig = this.getModuleConfig(moduleName); + const listAttributes = moduleConfig.modelType === 'history' + ? [ ...ORDER_LIST_BASE_ATTRIBUTES, 'archive_time' ] + : [ ...ORDER_LIST_BASE_ATTRIBUTES ]; + + const [ total, list ] = await Promise.all([ + model.count({ where: queryWhere }), + model.findAll({ + where: queryWhere, + attributes: listAttributes, + limit: pageSize, + offset, + order, + raw: true, + }), + ]); + + const normalized = list.map(order => this.normalizeOrderListItem(order)); + + // 批量查询货主备注(wms_store_warehouse.store_remask) + const storeRemarkMap = new Map(); + if (normalized.length > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) { + const storeIds = [ + ...new Set( + normalized + .map(row => Number(row.store_id || 0)) + .filter(id => id > 0) + ), + ]; + if (storeIds.length > 0) { + const swRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIds }, + warehouse_id: contextWarehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } + } + + const listWithRemark = normalized.map(row => ({ + ...row, + store_remark: storeRemarkMap.has(Number(row.store_id || 0)) + ? storeRemarkMap.get(Number(row.store_id || 0)) + : '', + })); + + const normalizedList = await this.attachOrderExpressNumbers(listWithRemark); + const listWithWaveIndex = await this.attachOrderWaveIndex(normalizedList); + + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + return { + list: listWithWaveIndex, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }; + } + + /** + * 为订单列表行附加 B2B 作业明细字段(副表 wms_order_b2b)。 + * + * 关联条件固定为 warehouse_id + order_id(分表 id 按仓库发号,不能只按 order_id 关联); + * 无副表行时输出空值占位,保证响应字段结构稳定。附加字段: + * total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds / + * is_picked_up / picked_up_at / created_at(副表创建时间) / prep_at。 + * + * @param {Array} list 订单列表行(需含 id)。 + * @param {number|string|null} [warehouseId=null] 仓库ID,缺省取当前上下文。 + * @return {Promise>} 附加 B2B 作业明细后的列表。 + */ + async attachB2bJobDetail(list = [], warehouseId = null) { + const rows = Array.isArray(list) ? list : []; + if (rows.length === 0) { + return rows; + } + + const normalizedWarehouseId = Number(warehouseId ?? this.getWarehouseId() ?? 0); + const b2bModel = this.ctx.model && this.ctx.model.OrderB2b; + const detailMap = new Map(); + + if (Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + && b2bModel && typeof b2bModel.findAll === 'function') { + const orderIds = [ ...new Set(rows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (orderIds.length > 0) { + const detailRows = await b2bModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + order_id: { [this.app.Sequelize.Op.in]: orderIds }, + }, + attributes: [ ...ORDER_B2B_DETAIL_ATTRIBUTES ], + raw: true, + }); + + for (const detail of (Array.isArray(detailRows) ? detailRows : [])) { + const orderId = Number(detail && detail.order_id || 0); + if (Number.isInteger(orderId) && orderId > 0) { + detailMap.set(orderId, detail); + } + } + } + } + + return rows.map(row => { + const detail = detailMap.get(Number(row && row.id || 0)); + if (!detail) { + return { ...row, ...ORDER_B2B_DETAIL_EMPTY }; + } + + return { + ...row, + total_box_count: Number(detail.total_box_count || 0), + pickup_plate_number: detail.pickup_plate_number ?? null, + prep_remark: detail.prep_remark ?? null, + prep_duration_seconds: Number(detail.prep_duration_seconds || 0), + is_picked_up: String(detail.is_picked_up || 'N').trim() === 'Y' ? 'Y' : 'N', + picked_up_at: detail.picked_up_at ?? null, + created_at: detail.created_at ?? null, + prep_at: detail.prep_at ?? null, + }; + }); + } + + /** + * 构造"排除 B2B 订单"条件(is_b2b 为 NULL 的存量行视为非 B2B)。 + * @return {Object} Sequelize 条件。 + */ + buildExcludeB2bCondition() { + const { Op } = this.app.Sequelize; + return { + is_b2b: { + [Op.or]: [ + { [Op.is]: null }, + 'N', + ], + }, + }; + } + + /** + * 从 where 中提取 B2B 作业明细筛选条件(仅 B2B 域列表使用)。 + * + * @param {Object} [where={}] 已解析的 where 条件。 + * @return {{ where: Object, b2bDetailFilters: (Object|null) }} 剩余 where 与作业明细筛选条件。 + */ + extractB2bDetailVirtualFilter(where = {}) { + const source = this.isPlainObject(where) ? where : {}; + const rest = {}; + const filters = {}; + + for (const [ fieldName, condition ] of Object.entries(source)) { + if (!ORDER_B2B_DETAIL_FILTER_FIELDS.includes(fieldName)) { + rest[fieldName] = condition; + continue; + } + + const conditionValue = this.isPlainObject(condition) && Object.prototype.hasOwnProperty.call(condition, 'value') + ? condition.value + : condition; + if (conditionValue === undefined || conditionValue === null || conditionValue === '') { + continue; + } + + filters[fieldName] = condition; + } + + return { + where: rest, + b2bDetailFilters: Object.keys(filters).length > 0 ? filters : null, + }; + } + + /** + * 按 B2B 作业明细筛选条件查询命中的订单ID。 + * + * 关联条件固定为 warehouse_id + order_id;无有效条件时返回 null(表示不过滤), + * 有条件下未命中时返回空数组(下游展开为空列表)。 + * + * @param {Object} filters 作业明细筛选条件。 + * @param {number|string|null} [warehouseId=null] 仓库ID,缺省取当前上下文。 + * @return {Promise} 命中订单ID列表,或 null(无有效条件)。 + */ + async findOrderIdsByB2bDetailFilters(filters = {}, warehouseId = null) { + const { Sequelize } = this.app; + const { Op } = Sequelize; + const b2bModel = this.ctx.model && this.ctx.model.OrderB2b; + const normalizedWarehouseId = Number(warehouseId ?? this.getWarehouseId() ?? 0); + + if (!this.isPlainObject(filters) || Object.keys(filters).length === 0) { + return null; + } + + if (!b2bModel || typeof b2bModel.findAll !== 'function' + || !Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return []; + } + + const parsed = parseWhereConditions({ + where: this.normalizeWhereInput({ where: filters }), + app: this.app, + }); + + if (!parsed.ok) { + throw new Error(`B2B 作业明细筛选条件解析失败: ${parsed.reason}`); + } + + const conditions = Array.isArray(parsed.result.dynamicConditions) ? parsed.result.dynamicConditions : []; + if (conditions.length === 0) { + return null; + } + + const rows = await b2bModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + [Op.and]: conditions, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + return [ ...new Set((Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + } + + /** + * 查询订单详情。 + * + * 兜底查询:当表位类型为配送表(dispatch)且查询不到订单时, + * 自动回退到待处理表(current)再查询一次,避免订单在配送表与 + * 待处理表之间流转后详情查询落空。 + * + * @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不能为空'); + } + + if (orderIds.length !== 1) { + throw new Error('订单详情仅支持查询单个订单'); + } + + const orderId = orderIds[0]; + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + + // 实际使用的表位类型:配送表(dispatch)查询不到时兜底查询待处理表(current) + let actualTableType = tableType; + let orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId); + let order = await orderModel.findOne({ + where: orderWhere, + raw: true, + }); + + if (!order && actualTableType === 'dispatch') { + actualTableType = 'current'; + orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId); + order = await orderModel.findOne({ + where: orderWhere, + raw: true, + }); + } + + if (!order) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderItemsModel = await this.getOrderItemsModelByTableType(actualTableType, warehouseId); + const orderItems = await orderItemsModel.findAll({ + where: { + order_id: orderId, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 通过 getStockDetails(带缓存)批量查询 stock_warehouse 标准信息 + // 为 items 附加 image_url、barcodes、item_name 等标准字段 + const orderItemsWithStockInfo = await this.attachStockDetailsToOrderItems(orderItems, warehouseId); + + const expresses = await this.getOrderExpressesByOrderId(orderId, order); + const logs = await this.getOrderOperationLogs(orderId); + + // 从运单列表中提取去重后的运单号数组 + const waybillCodes = Array.isArray(expresses) + ? [ ...new Set(expresses.map(expr => String(expr && expr.waybill_code || '').trim()).filter(Boolean)) ] + : []; + + return { + detail: order, + items: orderItemsWithStockInfo, + expresses, + waybill_codes: waybillCodes, + logs, + }; + } + + /** + * 通过 stock_warehouse 带缓存的标准方法(getStockDetails),批量查询商品详情, + * 将 order_items 仅作为 stock_id 来源,返回 getStockDetails 标准格式数据。 + * 每个结果会附带以下 order_items 关键关联字段: + * - plan_qty:需求量 + * - order_line_no:行号 + * - stock_id:原 order_items 中的 stock_id 关联键 + * - order_item_id:原 order_items 主键 id,供下游(如 pendingOrder)关联使用 + * - order_id:所属订单 id + * + * @param {Object[]} orderItems 订单商品列表。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 以 stock_warehouse 标准格式为主,附带少量 order_items 关键字段的数据。 + */ + async attachStockDetailsToOrderItems(orderItems = [], warehouseId) { + if (!Array.isArray(orderItems) || orderItems.length === 0) { + return []; + } + + // 构建 stockId → orderItem 关键字段的映射 + const stockIdToOrderItemMap = new Map(); + const stockIdsSet = new Set(); + for (const item of orderItems) { + const stockId = Number(item && item.stock_id); + if (stockId) { + stockIdsSet.add(stockId); + // 同一个 stock_id 可能对应多条 order_items 行,保留最后一条的关键字段 + stockIdToOrderItemMap.set(stockId, { + plan_qty: item.plan_qty != null ? item.plan_qty : 0, + order_line_no: item.order_line_no || '', + stock_id: stockId, + order_item_id: item.id != null ? item.id : 0, + order_id: item.order_id != null ? item.order_id : 0, + }); + } + } + + const stockIds = [ ...stockIdsSet ]; + + if (stockIds.length === 0) { + return []; + } + + /** @type {Map} */ + const stockDetailMap = new Map(); + try { + const stockWarehouseSvc = this.ctx.service?.systems?.stockWarehouse; + if (stockWarehouseSvc && typeof stockWarehouseSvc.getStockDetails === 'function') { + const stockDetails = await stockWarehouseSvc.getStockDetails(stockIds, { warehouseId }); + for (const detail of stockDetails) { + stockDetailMap.set(Number(detail.id), detail); + } + } + } catch (error) { + this.ctx.logger?.warn?.('[order.base.attachStockDetailsToOrderItems] 查询 stock_warehouse 详情失败,已降级为原始 items', { + error: error.message, + }); + return []; + } + + // 降级:当 getStockDetails 缓存层没有返回某些 stockId 的数据时,直接查 DB 补齐 + const missedIds = stockIds.filter(sid => !stockDetailMap.has(sid)); + if (missedIds.length > 0) { + this.ctx.logger?.info?.('[order.base.attachStockDetailsToOrderItems] getStockDetails 未返回部分 stock 详情,降级为直接查 DB', { + missedIds, + warehouseId, + }); + try { + const { app } = this; + const [ fallbackStockRows, fallbackBarcodeRows, fallbackImageRows ] = await Promise.all([ + app.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: missedIds }, is_valid: 'Y' }, + attributes: [ + 'id', 'item_code', 'item_name', 'sku_property', + 'quantity', 'locked_quantity', 'is_batch_mgmt', + 'is_shelf_life_mgmt', 'is_images', + 'store_id', 'packing_requirements', 'pick_requirements', + 'recheck_requirements', 'merge_requirements', 'stock_unit', + ], + raw: true, + }), + app.model.StockBarcode.findAll({ + where: { stock_id: { [app.Sequelize.Op.in]: missedIds } }, + attributes: [ 'id', 'barcode', 'stock_id' ], + raw: true, + }), + app.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { [app.Sequelize.Op.in]: missedIds.map(String) }, + }, + include: [{ + model: app.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + order: [[ 'display_order', 'ASC' ]], + raw: true, + }), + ]); + + const fallbackBarcodeMap = new Map(); + for (const row of fallbackBarcodeRows) { + const sid = row.stock_id; + if (!fallbackBarcodeMap.has(sid)) { + fallbackBarcodeMap.set(sid, []); + } + fallbackBarcodeMap.get(sid).push({ + id: row.id, + barcode: row.barcode, + }); + } + + const fallbackImageUrlMap = new Map(); + for (const row of fallbackImageRows) { + const sid = Number(row.business_id); + if (!fallbackImageUrlMap.has(sid)) { + fallbackImageUrlMap.set(sid, []); + } + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (url) { + fallbackImageUrlMap.get(sid).push(url); + } + } + + for (const row of fallbackStockRows) { + stockDetailMap.set(row.id, { + id: row.id, + item_code: row.item_code, + item_name: row.item_name, + sku_property: row.sku_property || '', + quantity: row.quantity || 0, + locked_quantity: row.locked_quantity || 0, + is_batch_mgmt: row.is_batch_mgmt || 'N', + is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N', + is_images: row.is_images || 'N', + store_id: row.store_id != null ? Number(row.store_id) : 0, + packing_requirements: row.packing_requirements || '', + pick_requirements: (row.merge_requirements || 'Y') === 'Y' + ? (row.packing_requirements || '') + : (row.pick_requirements || ''), + recheck_requirements: (row.merge_requirements || 'Y') === 'Y' + ? (row.packing_requirements || '') + : (row.recheck_requirements || ''), + merge_requirements: row.merge_requirements || 'Y', + stock_unit: row.stock_unit || '', + image_url: fallbackImageUrlMap.get(row.id) || [], + barcodes: fallbackBarcodeMap.get(row.id) || [], + }); + } + } catch (fallbackError) { + this.ctx.logger?.warn?.('[order.base.attachStockDetailsToOrderItems] 降级查询也失败', { + error: fallbackError.message, + }); + } + } + + // 以 getStockDetails 返回的标准格式为主, + // 仅从 order_items 中附加 plan_qty、order_line_no、stock_id、order_item_id、order_id 关键关联字段 + return stockIds.map(stockId => { + const stockDetail = stockDetailMap.get(stockId) || null; + const orderItemFields = stockIdToOrderItemMap.get(stockId) || {}; + + if (!stockDetail) { + return { + id: stockId, + item_code: '', + item_name: '', + sku_property: '', + quantity: 0, + locked_quantity: 0, + is_batch_mgmt: 'N', + is_shelf_life_mgmt: 'N', + is_images: 'N', + store_id: 0, + packing_requirements: '', + pick_requirements: '', + recheck_requirements: '', + merge_requirements: 'Y', + stock_unit: '', + image_url: [], + barcodes: [], + plan_qty: orderItemFields.plan_qty || 0, + order_line_no: orderItemFields.order_line_no || '', + stock_id: orderItemFields.stock_id || stockId, + order_item_id: orderItemFields.order_item_id || 0, + order_id: orderItemFields.order_id || 0, + }; + } + + return { + id: stockDetail.id, + item_code: stockDetail.item_code || '', + item_name: stockDetail.item_name || '', + sku_property: stockDetail.sku_property || '', + quantity: stockDetail.quantity != null ? stockDetail.quantity : 0, + locked_quantity: stockDetail.locked_quantity != null ? stockDetail.locked_quantity : 0, + is_batch_mgmt: stockDetail.is_batch_mgmt || 'N', + is_shelf_life_mgmt: stockDetail.is_shelf_life_mgmt || 'N', + is_images: stockDetail.is_images || 'N', + store_id: stockDetail.store_id != null ? Number(stockDetail.store_id) : 0, + packing_requirements: stockDetail.packing_requirements || '', + pick_requirements: stockDetail.pick_requirements || '', + recheck_requirements: stockDetail.recheck_requirements || '', + merge_requirements: stockDetail.merge_requirements || 'Y', + stock_unit: stockDetail.stock_unit || '', + image_url: Array.isArray(stockDetail.image_url) ? [ ...stockDetail.image_url ] : [], + barcodes: Array.isArray(stockDetail.barcodes) ? [ ...stockDetail.barcodes ] : [], + plan_qty: orderItemFields.plan_qty || 0, + order_line_no: orderItemFields.order_line_no || '', + stock_id: orderItemFields.stock_id || stockId, + order_item_id: orderItemFields.order_item_id || 0, + order_id: orderItemFields.order_id || 0, + }; + }); + } + + /** + * 获取订单操作日志列表。 + * @param {number} orderId 订单ID。 + * @return {Promise} 订单日志数组。 + */ + async getOrderOperationLogs(orderId) { + const warehouseId = this.getWarehouseId(); + const operationLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + + if (!operationLogService || typeof operationLogService.queryOrderLogs !== 'function') { + return []; + } + + if (warehouseId === null || warehouseId === undefined || warehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + const queryResult = await operationLogService.queryOrderLogs({ + id: orderId, + warehouseId, + page: 1, + pageSize: 200, + }); + + return Array.isArray(queryResult && queryResult.list) ? queryResult.list : []; + } + + /** + * 将审核状态映射为 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; + } + + /** + * 构建审核更新条件。 + * @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不能为空'); + } + + 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, + status: 'created', + 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]; + + return { + 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), + }; + } + + /** + * 更新订单审核态。 + * @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 (orderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + + if (!inspectionStatus) { + throw new Error('审核状态不能为空'); + } + + 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('订单不存在或不属于当前仓库'); + } + + 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]; + + return { + 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), + }; + } +} + +module.exports = OrderBaseService; diff --git a/app/service/systemMethods/order/deliveryExpectionOrder.js b/app/service/systemMethods/order/deliveryExpectionOrder.js new file mode 100644 index 0000000..a2570a4 --- /dev/null +++ b/app/service/systemMethods/order/deliveryExpectionOrder.js @@ -0,0 +1,55 @@ +'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); + } + + /** + * 查询配送异常订单详情。 + * + * 默认使用 dispatch 表查询; + * 若调用方显式传入表位参数,则保持调用方指定值。 + * + * @param {Object} data 请求体。 + * @return {Promise} 订单头、商品明细、运单与日志信息。 + */ + async detail(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const tableTypeFields = [ 'tableType', 'tablePosition', 'type', 'moduleName' ]; + const hasTableTypeInput = tableTypeFields.some(field => { + if (!Object.prototype.hasOwnProperty.call(requestData, field)) { + return false; + } + return String(requestData[field] ?? '').trim() !== ''; + }); + + const detailParams = hasTableTypeInput + ? requestData + : { + ...requestData, + tableType: 'dispatch', + }; + + return await super.detail(detailParams); + } + +} + +module.exports = DeliveryExpectionOrderService; diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js new file mode 100644 index 0000000..94d4b5a --- /dev/null +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -0,0 +1,565 @@ +'use strict'; + +const OrderBaseService = require('./base'); +const fs = require('fs'); +const path = require('path'); +const { stripWaybillSegmentSuffix, escapeLikeWildcards } = require('../../../lib/waybill_code'); + +const DEBUG_LOG = path.join(__dirname, '..', '..', '..', '..', 'temp', 'quickSearch_debug.log'); + +// 持久可写流:dbg 使用异步缓冲写,避免 appendFileSync 每次 open/write/close 的同步磁盘 IO +let debugStream = null; + +function getDebugStream() { + if (!debugStream) { + try { + debugStream = fs.createWriteStream(DEBUG_LOG, { flags: 'a' }); + debugStream.on('error', () => { + debugStream = null; + }); + } catch (_) { + debugStream = null; + } + } + return debugStream; +} + +function dbg(msg) { + const stream = getDebugStream(); + if (!stream) return; + const line = `[${new Date().toISOString()}] ${msg}\n`; + try { stream.write(line); } catch (_) { /* ignore */ } +} + +// express 表查询列(1a/1b/1c 三段共用) +const EXPRESS_ATTRIBUTES = [ + 'id', 'order_id', 'waybill_code', 'delivery_order_code', 'source_order_codes', 'store_id', + 'logistics_code', 'logistics_name', + 'logistics_interface_id', 'logistics_interface_name', + 'platform_code', 'status', 'is_back', 'is_intercept', 'is_galaxy_receive', + 'weighing_weight', +]; + +class DeliveryOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,summary,deliveryOrder,quickSearch'; + const _noNeedLog = 'list,summary,quickSearch'; + const _noNeedAuth = 'list,summary,deliveryOrder,quickSearch'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 配送订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('deliveryOrder', data); + } + + /** + * 配送订单每日汇总(以日期为维度统计订单量/发货量/拦截量等)。 + * + * 仓库维度取自登录上下文(ctx.user.store_id),禁止前端传 warehouse_id; + * 可选 store_id 按货主过滤。缺省统计最近 7 个自然日(含今天), + * 单次最多 90 天。 + * + * @param {Object} data 请求体。 + * @param {string} [data.start_date] 开始日期(yyyy-MM-dd,兼容 startDate/start_time)。 + * @param {string} [data.end_date] 结束日期(yyyy-MM-dd,兼容 endDate/end_time)。 + * @param {number} [data.store_id] 货主ID(可选,兼容 storeId)。 + * @return {Promise} 每日汇总列表与区间合计。 + */ + async summary(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (warehouseId <= 0) { + return this.fail('缺少仓库上下文'); + } + + const requestData = this.isPlainObject(data) ? data : {}; + const storeId = Number(requestData.store_id ?? requestData.storeId ?? 0) || 0; + + try { + const result = await this.service.systems.deliveryOrderSummary.queryDailySummary({ + warehouseId, + storeId: storeId > 0 ? storeId : null, + startDate: requestData.start_date ?? requestData.startDate ?? requestData.start_time, + endDate: requestData.end_date ?? requestData.endDate ?? requestData.end_time, + }); + return this.success('ok', result); + } catch (error) { + if (error && error.code === 'INVALID_SUMMARY_RANGE') { + return this.fail(error.message); + } + this.ctx.logger.error( + `[order.deliveryOrder.summary] ${error && error.message ? error.message : error}` + ); + return this.fail('配送订单汇总查询失败'); + } + } + + /** + * 查询配送订单详情。 + * + * 默认使用 dispatch 表查询; + * 若调用方显式传入表位参数,则保持调用方指定值。 + * + * @param {Object} data 请求体。 + * @return {Promise} 订单头、商品明细、运单与日志信息。 + */ + async detail(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const tableTypeFields = [ 'tableType', 'tablePosition', 'type', 'moduleName' ]; + const hasTableTypeInput = tableTypeFields.some(field => { + if (!Object.prototype.hasOwnProperty.call(requestData, field)) { + return false; + } + return String(requestData[field] ?? '').trim() !== ''; + }); + + const detailParams = hasTableTypeInput + ? requestData + : { + ...requestData, + tableType: 'dispatch', + }; + + return await super.detail(detailParams); + } + + /** + * 订单快速搜索。 + * 逐级短路搜索(wms_order_express 表),命中即停: + * 1. 运单号 waybill_code(等值 + 剥离一单多件分段后缀后的主体等值 + 主体前缀 LIKE); + * 2. 发货单号 delivery_order_code(等值优先,未命中再 %kw% 模糊); + * 3. 平台订单号 source_order_codes(%kw% 模糊兜底)。 + * 返回匹配的订单列表(最多 20 条),包含订单关键信息及关联运单号。 + * + * @param {Object} data 请求体。 + * @param {string} data.keyword 搜索关键词(必填)。 + * @return {Promise} { list, keyword } + */ + async quickSearch(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const requestData = this.isPlainObject(data) ? data : {}; + const keyword = String(requestData.keyword || '').trim(); + const warehouseId = this.getWarehouseId(); + + dbg('========== quickSearch START =========='); + dbg(`keyword="${keyword}" warehouseId=${warehouseId}`); + + if (!keyword) { + dbg('keyword empty → return []'); + return { list: [], keyword: '' }; + } + + if (!warehouseId) { + dbg('warehouseId empty → throw'); + throw new Error('缺少仓库上下文'); + } + + const MAX_RESULTS = 20; + + // 收集匹配的订单 ID(去重) + const matchedOrderIds = new Set(); + + // ====== 第一步:express 表逐级短路搜索 ====== + // 命中顺序:运单号(waybill_code) → 发货单号(delivery_order_code) → 平台订单号(source_order_codes)。 + // 每一级只要命中即停止后续查询,直接进入订单详情查询。 + // 性能背景:单仓库 wms_order_express 行数达 60w+,逐级短路保证绝大多数场景 + // (运单号/完整发货单号)只走索引点查,模糊全扫仅作为最后兜底。 + dbg('--- Step1: express level search ---'); + // 业务规则:运单号先剥离一单多件包裹序号后缀(如 -1-1-),主体必须等值匹配, + // 不得落入模糊 like + const waybillBase = stripWaybillSegmentSuffix(keyword); + const escapedWaybillBase = escapeLikeWildcards(waybillBase); + const waybillConditions = [ + { waybill_code: keyword }, + ...(waybillBase !== keyword ? [{ waybill_code: waybillBase }] : []), + ...(escapedWaybillBase ? [{ waybill_code: { [Op.like]: `${escapedWaybillBase}-%` } }] : []), + ]; + dbg(`waybillBase="${waybillBase}" escapedWaybillBase="${escapedWaybillBase}"`); + + let expressRecords = []; + let hitLevel = null; + + // Level 1:运单号(等值/主体等值/主体前缀,走 waybill_code 索引) + try { + expressRecords = await ctx.model.OrderExpress.findAll({ + attributes: EXPRESS_ATTRIBUTES, + where: { + warehouse_id: warehouseId, + [Op.or]: waybillConditions, + }, + raw: true, + limit: MAX_RESULTS, + }); + if (expressRecords.length > 0) hitLevel = 'waybill_code'; + dbg(`L1 waybill_code records: ${expressRecords.length}`); + } catch (e) { + dbg(`L1 ERROR: ${e.message}`); + } + + // Level 2a:发货单号等值(走 idx_delivery_code_store 索引) + if (!hitLevel) { + try { + expressRecords = await ctx.model.OrderExpress.findAll({ + attributes: EXPRESS_ATTRIBUTES, + where: { + warehouse_id: warehouseId, + delivery_order_code: keyword, + }, + raw: true, + limit: MAX_RESULTS, + }); + if (expressRecords.length > 0) hitLevel = 'delivery_order_code'; + dbg(`L2a delivery_order_code exact records: ${expressRecords.length}`); + } catch (e) { + dbg(`L2a ERROR: ${e.message}`); + } + } + + // Level 2b:发货单号模糊兜底(中缀 LIKE 无法走索引,仅在等值未命中时执行) + if (!hitLevel) { + try { + expressRecords = await ctx.model.OrderExpress.findAll({ + attributes: EXPRESS_ATTRIBUTES, + where: { + warehouse_id: warehouseId, + delivery_order_code: { [Op.like]: `%${keyword}%` }, + }, + raw: true, + limit: MAX_RESULTS, + }); + if (expressRecords.length > 0) hitLevel = 'delivery_order_code_like'; + dbg(`L2b delivery_order_code like records: ${expressRecords.length}`); + } catch (e) { + dbg(`L2b ERROR: ${e.message}`); + } + } + + // Level 3:平台订单号(无索引全扫兜底,最后一级,仅前两级均未命中时执行) + if (!hitLevel) { + try { + expressRecords = await ctx.model.OrderExpress.findAll({ + attributes: EXPRESS_ATTRIBUTES, + where: { + warehouse_id: warehouseId, + source_order_codes: { [Op.like]: `%${keyword}%` }, + }, + raw: true, + limit: MAX_RESULTS, + }); + if (expressRecords.length > 0) hitLevel = 'source_order_codes'; + dbg(`L3 source_order_codes records: ${expressRecords.length}`); + } catch (e) { + dbg(`L3 ERROR: ${e.message}`); + } + } + dbg(`hitLevel=${hitLevel}`); + + const waybillMap = new Map(); + for (const er of expressRecords) { + dbg(` er: id=${er.id} order_id=${er.order_id} waybill_code=${er.waybill_code} delivery_order_code=${er.delivery_order_code}`); + if (er.order_id) { + matchedOrderIds.add(er.order_id); + if (!waybillMap.has(er.order_id)) { + waybillMap.set(er.order_id, []); + } + waybillMap.get(er.order_id).push(this.buildWaybillItem(er)); + } + } + dbg(`matchedOrderIds: [${[ ...matchedOrderIds ].join(',')}]`); + dbg(`waybillMap keys: [${[ ...waybillMap.keys() ].join(',')}]`); + + if (matchedOrderIds.size === 0) { + dbg('matchedOrderIds empty → return []'); + return { list: [], keyword }; + } + + // ====== 第二步:订单表 IN 查详情 ====== + const orderIds = [ ...matchedOrderIds ].slice(0, MAX_RESULTS); + const orderMap = new Map(); + dbg(`--- Step2: order detail IN query, orderIds=[${orderIds.join(',')}] ---`); + + if (orderIds.length > 0) { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + dbg(`factory exists: ${!!factory}`); + dbg(`factory keys: ${factory ? Object.keys(factory).join(',') : 'N/A'}`); + dbg(`factory.getDispatchModel type: ${factory && typeof factory.getDispatchModel}`); + + // 直接尝试调用,不判断 typeof,看具体报什么错 + if (factory) { + const tableDefs = [ + { label: 'dispatch', getModel: () => factory.getDispatchModel(warehouseId) }, + { label: 'current', getModel: () => factory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => factory.getHistoryModel(warehouseId) }, + ]; + + // 序列表批量定位:命中则只查对应分表,未命中(存量订单)回退三表遍历 + const normalizedOrderIds = orderIds.map(Number).filter(n => Number.isFinite(n) && n > 0); + let locationMap = new Map(); + try { + if (typeof factory.getOrderLocations === 'function') { + locationMap = await factory.getOrderLocations(normalizedOrderIds, warehouseId); + } + } catch (e) { + dbg(` locationMap ERROR: ${e.message}`); + } + dbg(` locationMap size: ${locationMap.size}`); + + const idsByLabel = { dispatch: [], current: [], history: [] }; + const unresolvedIds = []; + for (const id of normalizedOrderIds) { + const location = locationMap.get(id); + if (location && idsByLabel[location]) { + idsByLabel[location].push(id); + } else { + unresolvedIds.push(id); + } + } + + for (const entry of tableDefs) { + const targetIds = [ ...new Set([ ...(idsByLabel[entry.label] || []), ...unresolvedIds ]) ]; + if (targetIds.length === 0) continue; + dbg(` trying table: ${entry.label}, targetIds=[${targetIds.join(',')}]`); + try { + const model = await entry.getModel(); + dbg(` ${entry.label} model: ${!!model}, typeof findAll=${model && typeof model.findAll}`); + if (!model || typeof model.findAll !== 'function') { + dbg(` ${entry.label} model invalid, skip`); + continue; + } + const whereClause = { id: targetIds }; + dbg(` ${entry.label} where: ${JSON.stringify(whereClause)}`); + const rows = await model.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'source_order_codes', 'pay_no', + 'store_id', 'status', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'buyer_nick', 'seller_nick', 'shop_nick', + 'total_amount', 'item_amount', 'freight', + 'items_count', 'items_weight', 'packages_weight', + 'wave_no', 'delivery_time', 'create_at', + ], + where: whereClause, + raw: true, + }); + dbg(` ${entry.label} rows count: ${rows.length}`); + for (const r of (rows || [])) { + dbg(` row: id=${r.id} delivery_order_code=${r.delivery_order_code} status=${r.status}`); + const rid = String(r.id); + if (!orderMap.has(rid)) { orderMap.set(rid, r); } + } + } catch (e) { + dbg(` ${entry.label} ERROR: ${e.message} | stack: ${(e.stack || '').split('\n').slice(0, 3).join(' | ')}`); + continue; + } + } + } + } + dbg(`orderMap.size: ${orderMap.size}, keys: [${[ ...orderMap.keys() ].join(',')}]`); + + // ====== 第三步:货主备注 ====== + dbg('--- Step3: store remark ---'); + const storeRemarkMap = new Map(); + const allStoreIds = new Set(); + for (const oid of orderIds) { + const wb = (waybillMap.get(oid) || [])[0]; + const sid = (wb && wb.store_id) || (orderMap.get(String(oid)) || {}).store_id || 0; + if (sid) allStoreIds.add(sid); + } + dbg(`allStoreIds: [${[ ...allStoreIds ].join(',')}]`); + if (allStoreIds.size > 0 && ctx.model.StoreWarehouse) { + try { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: { [Op.in]: [ ...allStoreIds ] }, warehouse_id: warehouseId }, + attributes: [ 'store_id', 'store_remask' ], raw: true, + }); + dbg(`store_warehouse rows: ${swRows.length}`); + for (const sw of swRows) { + dbg(` sw: store_id=${sw.store_id} store_remask="${sw.store_remask}"`); + storeRemarkMap.set(sw.store_id, sw.store_remask || ''); + } + } catch (e) { dbg(`store_warehouse ERROR: ${e.message}`); } + } + + // ====== 合并输出 ====== + dbg('--- Merge output ---'); + const list = []; + for (const oid of orderIds) { + const order = orderMap.get(String(oid)) || {}; + const waybills = waybillMap.get(oid) || []; + dbg(` oid=${oid} orderKeys=[${Object.keys(order).join(',')}] waybills=${waybills.length}`); + if (waybills.length === 0) { + list.push({ + order_id: oid, waybill_id: 0, waybill_code: '', + logistics_code: '', logistics_name: '', logistics_interface_id: 0, logistics_interface_name: '', + platform_code: '', waybill_status: null, waybill_status_text: '', + is_back: 'N', is_intercept: 'N', is_galaxy_receive: 'N', + weighing_weight: 0, weighing_weight_display: '0 kg', + delivery_order_code: order.delivery_order_code || '', + source_order_codes: order.source_order_codes || '', + pay_no: order.pay_no || '', + store_id: order.store_id || 0, store_name: order.store_name || '', + store_remask: storeRemarkMap.get(order.store_id) || '', + status: order.status || '', name: order.name || '', mobile: order.mobile || '', + province: order.province || '', city: order.city || '', area: order.area || '', + detail_address: order.detail_address || '', + buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '', + total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0, + items_count: order.items_count || 0, items_weight: order.items_weight || 0, + packages_weight: order.packages_weight || 0, + wave_no: order.wave_no || '', + delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null, + create_at: order.create_at ? app.formatDate(order.create_at) : null, + }); + } else { + for (const wb of waybills) { + list.push({ + order_id: oid, waybill_id: wb.id, waybill_code: wb.waybill_code, + logistics_code: wb.logistics_code, logistics_name: wb.logistics_name, + logistics_interface_id: wb.logistics_interface_id, logistics_interface_name: wb.logistics_interface_name, + platform_code: wb.platform_code, + waybill_status: wb.status, waybill_status_text: wb.status_text, + is_back: wb.is_back, is_intercept: wb.is_intercept, is_galaxy_receive: wb.is_galaxy_receive, + weighing_weight: wb.weighing_weight, weighing_weight_display: wb.weighing_weight_display, + delivery_order_code: wb.delivery_order_code || order.delivery_order_code || '', + source_order_codes: wb.source_order_codes || order.source_order_codes || '', + pay_no: order.pay_no || '', + store_id: wb.store_id || order.store_id || 0, store_name: order.store_name || '', + store_remask: storeRemarkMap.get(wb.store_id || order.store_id) || '', + status: order.status || '', name: order.name || '', mobile: order.mobile || '', + province: order.province || '', city: order.city || '', area: order.area || '', + detail_address: order.detail_address || '', + buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '', + total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0, + items_count: order.items_count || 0, items_weight: order.items_weight || 0, + packages_weight: order.packages_weight || 0, + wave_no: order.wave_no || '', + delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null, + create_at: order.create_at ? app.formatDate(order.create_at) : null, + }); + } + } + } + + dbg(`list.length: ${list.length}`); + dbg('========== quickSearch END =========='); + return { list, keyword }; + } + + buildWaybillItem(er) { + return { + id: er.id, + waybill_code: er.waybill_code, + delivery_order_code: er.delivery_order_code || '', + source_order_codes: er.source_order_codes || '', + store_id: er.store_id || 0, + logistics_code: er.logistics_code || '', + logistics_name: er.logistics_name || '', + logistics_interface_id: er.logistics_interface_id || 0, + logistics_interface_name: er.logistics_interface_name || '', + platform_code: er.platform_code || '', + status: er.status, + status_text: er.status === 1 ? '已分配' : '未分配', + is_back: er.is_back || 'N', + is_intercept: er.is_intercept || 'N', + is_galaxy_receive: er.is_galaxy_receive || 'N', + weighing_weight: er.weighing_weight || 0, + weighing_weight_display: er.weighing_weight > 0 + ? `${(er.weighing_weight / 1000).toFixed(2)} kg` : '0 kg', + }; + } + + /** + * 按订单 ID 列表批量查询订单关键字段(遍历 dispatch → current → history)。 + * @param {number[]} orderIds 订单ID列表 + * @param {number} warehouseId 仓库ID + * @return {Promise>} orderId → 订单行 + */ + async fetchOrderMapByIds(orderIds, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getDispatchModel !== 'function') { + return []; + } + + const attributes = [ + 'id', 'delivery_order_code', 'source_order_codes', 'pay_no', + 'store_id', 'status', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'buyer_nick', 'seller_nick', 'shop_nick', + 'total_amount', 'item_amount', 'freight', + 'items_count', 'items_weight', 'packages_weight', + 'wave_no', 'delivery_time', 'create_at', + ]; + + const tableOrders = [ + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + ]; + + // 序列表批量定位:命中则只查对应分表,未命中(存量订单)回退三表遍历 + const normalizedIds = [ ...new Set((orderIds || []).map(Number).filter(id => Number.isFinite(id) && id > 0)) ]; + let locationMap = new Map(); + try { + if (typeof orderDeliveryFactory.getOrderLocations === 'function') { + locationMap = await orderDeliveryFactory.getOrderLocations(normalizedIds, warehouseId); + } + } catch (_err) { + locationMap = new Map(); + } + + const idsByLabel = { dispatch: [], current: [], history: [] }; + const unresolvedIds = []; + for (const id of normalizedIds) { + const location = locationMap.get(id); + if (location && idsByLabel[location]) { + idsByLabel[location].push(id); + } else { + unresolvedIds.push(id); + } + } + + const resultMap = new Map(); + + for (const entry of tableOrders) { + const targetIds = [ ...new Set([ ...(idsByLabel[entry.label] || []), ...unresolvedIds ]) ]; + if (targetIds.length === 0) continue; + + try { + const model = await entry.getModel(); + if (!model || typeof model.findAll !== 'function') continue; + + const rows = await model.findAll({ + attributes, + where: { + id: { [Op.in]: targetIds }, + }, + raw: true, + }); + + for (const r of rows) { + const rid = String(r.id); + if (!resultMap.has(rid)) { + resultMap.set(rid, r); + } + } + } catch (_err) { + continue; + } + } + + return resultMap; + } + +} + +module.exports = DeliveryOrderService; diff --git a/app/service/systemMethods/order/deliveryOrder2b.js b/app/service/systemMethods/order/deliveryOrder2b.js new file mode 100644 index 0000000..a904d64 --- /dev/null +++ b/app/service/systemMethods/order/deliveryOrder2b.js @@ -0,0 +1,47 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +/** B2B 列表强制条件 */ +const B2B_FIXED_WHERE = Object.freeze({ is_b2b: 'Y' }); + +/** + * B2B 配送订单系统方法。 + * + * 查询条件与 order.deliveryOrder.list 完全一致(dispatch 分表 + dispatch_lane=m4), + * 仅额外强制 is_b2b='Y',用于 B2B 订单的配送域列表。 + */ +class DeliveryOrder2bService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * B2B 配送订单列表。 + * + * 在 order.deliveryOrder.list 的基础上强制 is_b2b='Y',并附加 wms_order_b2b 作业明细字段 + * (total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds / + * is_picked_up / picked_up_at / created_at / prep_at)。 + * + * @param {Object} data 请求体(与 order.deliveryOrder.list 一致)。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + const warehouseId = this.getWarehouseId(); + const result = await this.listByModule('deliveryOrder', data, { + fixedWhere: B2B_FIXED_WHERE, + b2bDetailFilter: true, + }); + return { + ...result, + list: await this.attachB2bJobDetail(result.list, warehouseId), + }; + } +} + +module.exports = DeliveryOrder2bService; diff --git a/app/service/systemMethods/order/entrustOrder.js b/app/service/systemMethods/order/entrustOrder.js new file mode 100644 index 0000000..e2a6f2c --- /dev/null +++ b/app/service/systemMethods/order/entrustOrder.js @@ -0,0 +1,55 @@ +'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); + } + + /** + * 查询委托外仓订单详情。 + * + * 默认使用 outsourced 表查询; + * 若调用方显式传入表位参数,则保持调用方指定值。 + * + * @param {Object} data 请求体。 + * @return {Promise} 订单头、商品明细、运单与日志信息。 + */ + async detail(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const tableTypeFields = [ 'tableType', 'tablePosition', 'type', 'moduleName' ]; + const hasTableTypeInput = tableTypeFields.some(field => { + if (!Object.prototype.hasOwnProperty.call(requestData, field)) { + return false; + } + return String(requestData[field] ?? '').trim() !== ''; + }); + + const detailParams = hasTableTypeInput + ? requestData + : { + ...requestData, + tableType: 'outsourced', + }; + + return await super.detail(detailParams); + } + +} + +module.exports = EntrustOrderService; diff --git a/app/service/systemMethods/order/expectionOrder.js b/app/service/systemMethods/order/expectionOrder.js new file mode 100644 index 0000000..c34edfc --- /dev/null +++ b/app/service/systemMethods/order/expectionOrder.js @@ -0,0 +1,89 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class ExpectionOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,expectionOrder,resolveException'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list,expectionOrder,resolveException'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 待处理异常订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('expectionOrder', data); + } + + /** + * 将待处理异常订单转回正常待处理状态(step 3 -> 2)。 + * + * 只操作当前仓库的当前订单表,且仅允许 step=3 的订单转出。 + * + * @param {Object} data 请求体。 + * @param {number[]} data.ids 订单ID 数组。 + * @return {Promise} 统一 success 包装的更新结果。 + */ + async resolveException(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + if (!Array.isArray(requestData.ids) || requestData.ids.length === 0) { + throw new Error('ids 不能为空'); + } + + const orderIds = Array.from(new Set(requestData.ids.map(v => { + const n = Number(v); + if (!Number.isInteger(n) || n <= 0) { + throw new Error('ids 仅支持正整数数组'); + } + return n; + }))); + + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere(orderIds, warehouseId); + where.step = 3; + + const [ affectedRows ] = await model.update({ + step: 2, + updated_at: new Date(), + }, { where }); + + const count = Number(affectedRows || 0); + + // 记录操作日志 + try { + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_RESOLVE_EXCEPTION', + operator, + extras: { + warehouseId: logWarehouseId, + orderIds, + updated_count: count, + message: `异常订单转正常:订单ID [${orderIds.join(', ')}],step 3 -> 2,共更新 ${count} 条`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[ExpectionOrderService.resolveException] 写入操作日志失败,不影响业务', logErr); + } + + return this.success('ok', { + updated_count: count, + ids: orderIds, + }); + } + +} + +module.exports = ExpectionOrderService; diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js new file mode 100644 index 0000000..5a2ad88 --- /dev/null +++ b/app/service/systemMethods/order/index.js @@ -0,0 +1,704 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +const ORDER_EXPORT_TASK_CACHE_KEY_PREFIX = 'order_export_task_'; +const ORDER_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +class OrderIndexService extends OrderBaseService { + /** + * 初始化订单系统方法的免登录、免权限、免日志和免鉴权配置。 + * @param {Egg.Context} ctx 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill,convertToB2b,cancelB2b'; + const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill,convertToB2b,cancelB2b'; + const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill,convertToB2b,cancelB2b'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 订单转 B2B 订单。 + * + * 仅限待处理表中处于待处理阶段(step in [1,2,3])、未取消、未拣货、未复核、 + * 未锁定、未拦截的订单(打印状态不限制);不符合条件跳过。 + * 事务内:订单表 is_b2b 置 Y + 写入 wms_order_b2b 作业明细,提交后写操作日志。 + * + * @param {Object} data 请求体。 + * @param {Array|number|string} [data.ids] 订单ID集合(优先)。 + * @param {Array|number|string} [data.order_ids] 订单ID集合别名。 + * @param {Array|number|string} [data.orderIds] 订单ID集合别名。 + * @param {number|string} [data.id] 订单ID单值别名。 + * @param {number|string} [data.order_id] 订单ID单值别名。 + * @param {number|string} [data.orderId] 订单ID单值别名。 + * @return {Promise} 统一成功包装响应(data 含 converted/skipped/not_found 分流结果)。 + */ + async convertToB2b(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawIds = requestData.ids !== undefined ? requestData.ids + : requestData.order_ids !== undefined ? requestData.order_ids + : requestData.orderIds !== undefined ? requestData.orderIds + : requestData.id !== undefined ? requestData.id + : requestData.order_id !== undefined ? requestData.order_id + : requestData.orderId; + const orderIds = [ ...new Set( + (Array.isArray(rawIds) ? rawIds : [ rawIds ]) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0) + ) ]; + if (orderIds.length === 0) { + return this.fail('订单ID不能为空', {}, 400); + } + if (orderIds.length > 200) { + return this.fail('单次最多转换 200 个订单', {}, 400); + } + + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + + const result = await this.service.systems.orderB2b.convertOrdersToB2b({ + warehouseId, + orderIds, + operator, + }); + + return this.success('ok', result); + } + + /** + * 取消 B2B 出库:订单流转回正常订单。 + * + * 仅限待处理表中 is_b2b=Y 且未锁定、未拦截的订单(打印状态不限制); + * 不符合条件跳过。事务内:订单表 is_b2b 置回 N + B2B 作业明细物理删除, + * 提交后写操作日志。 + * + * @param {Object} data 请求体。 + * @param {Array|number|string} [data.ids] 订单ID集合(优先)。 + * @param {Array|number|string} [data.order_ids] 订单ID集合别名。 + * @param {Array|number|string} [data.orderIds] 订单ID集合别名。 + * @param {number|string} [data.id] 订单ID单值别名。 + * @param {number|string} [data.order_id] 订单ID单值别名。 + * @param {number|string} [data.orderId] 订单ID单值别名。 + * @return {Promise} 统一成功包装响应(data 含 canceled/skipped/not_found 分流结果)。 + */ + async cancelB2b(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawIds = requestData.ids !== undefined ? requestData.ids + : requestData.order_ids !== undefined ? requestData.order_ids + : requestData.orderIds !== undefined ? requestData.orderIds + : requestData.id !== undefined ? requestData.id + : requestData.order_id !== undefined ? requestData.order_id + : requestData.orderId; + const orderIds = [ ...new Set( + (Array.isArray(rawIds) ? rawIds : [ rawIds ]) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0) + ) ]; + if (orderIds.length === 0) { + return this.fail('订单ID不能为空', {}, 400); + } + if (orderIds.length > 200) { + return this.fail('单次最多取消 200 个订单', {}, 400); + } + + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + + const result = await this.service.systems.orderB2b.cancelOrdersB2b({ + warehouseId, + orderIds, + operator, + }); + + return this.success('ok', result); + } + + /** + * 提交订单导出任务。 + * + * 入参支持 table_type/module 组合;where 与 sort 语义与订单列表保持一致。 + * 方法层负责任务入队与进度缓存,导出由 systems.orderExport 异步执行。 + * + * @param {Object} data 请求体。 + * @param {string} [data.table_type] 导出表类型(current/history/dispatch/outsourced,兼容模块别名)。 + * @param {string} [data.tableType] 导出表类型(驼峰写法)。 + * @param {string} [data.module] 订单模块名(可选)。 + * @param {string} [data.module_name] 订单模块名(下划线写法)。 + * @param {string} [data.export_mode] 导出模式:waybill(默认,按运单展开)或 item(按商品明细展开)。 + * @param {string} [data.exportMode] 导出模式(驼峰写法)。 + * @param {Array} [data.export_columns] 导出表头字段白名单(中文表头数组),不传或空数组输出全部列;非法表头会报错。 + * @param {Array} [data.exportColumns] 导出表头字段白名单(驼峰写法)。 + * @param {Object} [data.where] 查询条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一成功包装响应。 + */ + async export(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + table_type: tableTypeSnake, + tableType: tableTypeCamel, + module: moduleName, + module_name: moduleNameSnake, + export_mode: exportModeSnake, + exportMode: exportModeCamel, + export_columns: exportColumnsSnake, + exportColumns: exportColumnsCamel, + where, + sort, + } = requestData; + const taskId = this.generateExportTaskId(); + const tableType = tableTypeSnake || tableTypeCamel || 'current'; + const module = moduleName || moduleNameSnake || ''; + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const exportMode = exportModeSnake || exportModeCamel || ''; + const exportColumns = Array.isArray(exportColumnsSnake) + ? exportColumnsSnake + : (Array.isArray(exportColumnsCamel) ? exportColumnsCamel : []); + const result = await this.service.systems.orderExport.exportOrders({ + tableType, + moduleName: module, + export_mode: exportMode, + export_columns: exportColumns, + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount, + total_count: safeProgress.totalCount, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询订单导出任务进度。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一成功包装响应。 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成订单导出任务ID。 + * @return {string} 任务ID。 + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `order_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID。 + * @param {string} [data.taskId] 任务ID。 + * @return {string} 规范后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取订单导出任务缓存键。 + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${ORDER_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入订单导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, ORDER_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[order.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取订单导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[order.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + + /** + * 订单工作台总列表入口。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('order', data); + } + + /** + * 手动出库入口。 + * @param {Object} data 请求体。 + * @return {Promise} 迁移结果。 + */ + async manualOutboundOrder(data = {}) { + return await this.ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery(data); + } + + /** + * 获取订单工作台 8 个标签页的角标计数。 + * 其中配送、异常与归档相关标签页直接返回 99+。 + * @return {Promise} 角标展示值对象。 + */ + async badgeCount() { + const warehouseId = this.getWarehouseId(); + + if (warehouseId === null || warehouseId === undefined || warehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + const cacheKey = this.getBadgeCountCacheKey(warehouseId); + const cachedBadgeCount = await this.app.getCacheAsync(cacheKey); + + if (cachedBadgeCount && typeof cachedBadgeCount === 'object') { + return cachedBadgeCount; + } + + 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; + } + + /** + * 查询订单操作日志。 + * @param {Object} data 请求体。 + * @param {string|number} data.id 订单ID。 + * @param {number} [data.page] 页码。 + * @param {number} [data.pageSize] 每页数量。 + * @return {Promise} 统一 success 包装的分页结果。 + */ + async queryOrderLogs(data = {}) { + const { ctx, service } = this; + const requestData = data && typeof data === 'object' ? data : {}; + const { id, page, pageSize } = requestData; + + try { + const result = await service.systems.operationLog.queryOrderLogs({ + id, + page, + pageSize, + warehouseId: ctx.user.store_id, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (e) { + return this.success(e.message, { + code: 200, + }); + } + } + + /** + * 查询订单日志列表(不分页,返回全部)。 + * + * 仅接受 order_id 及常见别名(id、orderId), + * 仓库范围固定使用当前登录用户 store_id,避免越仓读取。 + * + * @param {Object} data 请求体。 + * @param {string|number} [data.order_id] 订单ID。 + * @param {string|number} [data.id] 订单ID别名。 + * @param {string|number} [data.orderId] 订单ID别名。 + * @return {Promise} 统一 success/fail 结构。 + */ + async queryOrderLogList(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const { + order_id: orderId, + id, + orderId: orderIdAlias, + } = requestData; + const rawOrderId = orderId ?? id ?? orderIdAlias; + + if (rawOrderId === undefined || rawOrderId === null || String(rawOrderId).trim() === '') { + return this.fail('order_id 参数不能为空', {}, 400); + } + + const normalizedOrderId = Number(String(rawOrderId).trim()); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + return this.fail('order_id 参数不合法', {}, 400); + } + + const warehouseId = this.getWarehouseId(); + if (warehouseId === null || warehouseId === undefined || warehouseId === '') { + return this.fail('缺少当前用户仓库上下文 store_id', {}, 400); + } + + const logs = await service.systems.operationLog.queryAllOrderLogs({ + id: normalizedOrderId, + warehouseId, + }); + + return this.success('ok', { + list: logs, + total: logs.length, + code: 200, + }); + } + + /** + * 更新订单运单的称重重量。 + * + * 规则: + * - 单运单订单:忽略传入 waybill_code,直接更新唯一记录。 + * - 多运单订单:必须传入 waybill_code 且匹配到订单下记录。 + * - 团购波次(wave_type = 1):将同一重量批量设置到该波次下所有订单的运单上。 + * - 运单号模式(order_id = 0):从运单号反查,必传 waybill_code。团购时按 wave_no + business_key 批量设置。 + * + * @param {Object} data 请求体。 + * @param {string} [data.waybill_code] 运单号,多运单场景或运单号模式必填。 + * @param {number|string} data.order_id 订单ID,传 0 时切换为运单号模式。 + * @param {number|string} data.weighing_weight 称重重量(g)。 + * @return {Promise} 统一成功/失败结构。 + * 订单模式单订单:{data: {order_id, waybill_code, weighing_weight}}; + * 订单模式团购批量:{data: {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}}; + * 运单号模式单运单:{data: {order_id, waybill_code, weighing_weight}}; + * 运单号模式团购批量:{data: {wave_id, wave_no, business_key, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}}。 + */ + async updateExpressWeighingWeight(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code: waybillCode = '', + order_id: orderId, + weighing_weight: weighingWeight, + } = requestData; + + try { + let result; + if (Number(orderId) === 0) { + // 运单号模式:从运单号反查订单与波次 + result = await this.service.systems.orderExpress.updateWeighingWeightByWaybill({ + waybillCode, + weighingWeight, + }); + } else { + // 订单模式 + result = await this.service.systems.orderExpress.updateWeighingWeight({ + orderId, + waybillCode, + weighingWeight, + }); + } + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const errorCode = Number(error && error.code); + const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 400; + return this.fail(error && error.message ? error.message : '更新称重重量失败', { + data: null, + }, statusCode); + } + } + + /** + * 按订单号与运单号绑定包材。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @param {number|string} data.order_id 订单ID。 + * @param {string} data.package_material_code 包材编码。 + * @return {Promise} 统一成功/失败结构。 + */ + async bindExpressPackageMaterial(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code: waybillCode = '', + order_id: orderId, + package_material_code: packageMaterialCode = '', + } = requestData; + + try { + const result = await this.service.systems.orderExpress.bindExpressPackageMaterial({ + orderId, + waybillCode, + packageMaterialCode, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const errorCode = Number(error && error.code); + const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500; + return this.fail(error && error.message ? error.message : '绑定包材失败', { + data: null, + }, statusCode); + } + } + + /** + * 根据运单号绑定包材。 + * + * method 层仅负责参数解构、systems 转发与统一返回结构。 + * 无需传入订单ID,仅凭运单号即可完成包材绑定。 + * + * 支持团购波次自动感知: + * - 非团购订单:仅绑定当前运单的包材。 + * - 团购波次(wave_type=1):自动将同一波次下、相同快递业务键(business_key)的 + * 所有运单批量绑定相同的包材,实现一键补齐。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @param {number|string} data.package_material_id 包材ID。 + * @return {Promise} 统一成功/失败结构。 + * 单条绑定:data 含 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code}; + * 团购批量绑定:data 含 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。 + */ + async bindExpressPackageMaterialByWaybill(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code: waybillCode = '', + package_material_id: packageMaterialId = '', + } = requestData; + + try { + const result = await this.service.systems.orderExpress.bindExpressPackageMaterialByWaybill({ + waybillCode, + packageMaterialId, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const errorCode = Number(error && error.code); + const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500; + return this.fail(error && error.message ? error.message : '绑定包材失败', { + data: null, + }, statusCode); + } + } + + /** + * 根据运单号拉取复核数据。 + * + * method 层仅负责参数解构、systems 转发与统一返回结构。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @return {Promise} 统一成功/失败结构。 + */ + async pullReviewDataByWaybill(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code: waybillCode = '', + } = requestData; + + try { + const result = await this.service.systems.orderReview.pullReviewDataByWaybill({ + waybillCode, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const errorCode = Number(error && error.code); + const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500; + return this.fail(error && error.message ? error.message : '拉取复核数据失败', { + data: null, + }, statusCode); + } + } + +} + +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/packing.js b/app/service/systemMethods/order/packing.js new file mode 100644 index 0000000..5c47629 --- /dev/null +++ b/app/service/systemMethods/order/packing.js @@ -0,0 +1,370 @@ +'use strict'; + +const MainService = require('../../main'); + +const PACKING_EXPORT_TASK_CACHE_KEY_PREFIX = 'packing_export_task_'; +const PACKING_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:order.packing(打包任务接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 + * 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。 + */ +class OrderPackingMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // 免权限方法列表:export/exportTaskProgress 免权限(异步任务模式,与 order.export 口径一致,无 wms_permission 记录) + const _noNeedRight = 'list,get,export,exportTaskProgress'; + // 免日志方法列表:导出与进度查询不记录操作日志(与订单导出口径一致) + const _noNeedLog = 'list,get,export,exportTaskProgress'; + // 免鉴权(仓库有效期检查)方法列表:导出与进度查询不检查仓库有效期(与订单导出口径一致) + const _noNeedAuth = 'list,get,export,exportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 打包任务列表查询(仓库侧 system method 包装层)。 + * 按仓库维度查询打包任务,支持分页、筛选、排序。 + * + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 { page, pageSize } + * @param {Object} [data.where] 筛选条件。 + * 支持字段:status(任务状态)、pack_mode(打包模式)、waybill_code(运单号)、wave_no(波次号)、 + * order_id(订单ID)、workbench_id(工作台ID)、operator_text(打包员/作业人员姓名)、 + * quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、 + * start_time(开始打包时间范围,{operator:'between', value:[start,end]})、end_time(结束打包时间范围)、create_time(创建时间范围); + * start_time_start / start_time_end 为开始时间范围的兼容旧写法。 + * 运单号与波次号字段支持 {operator, value} 标准结构且 value 支持数组: + * operator=contains/like 时按 LIKE '%值%' 模糊匹配(waybill_code 可命中 '主体-1-1-' 等分段单号),wave_no 另支持 eq/in 精确、ne 不等; + * waybill_code 缺省/eq 时为「完整单号等值 + 剥离分段后缀主体等值 + 主体前缀」精确匹配。 + * operator_text(打包员/作业人员姓名)支持 {operator,value} 标准结构且 value 支持数组: + * contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义、多值取并集)、eq/in 精确、ne 不等于(取首值)、notlike 排除(多值逐个排除)。 + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } + * @return {Promise} 统一成功包装响应 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.orderPacking.list(where, pagination, sort); + return this.success('ok', result); + } + + /** + * 打包任务详情查询(仓库侧 system method 包装层)。 + * + * @param {Object} data 请求体 + * @param {number} data.id 打包任务ID + * @return {Promise} 统一成功包装响应 + */ + async get(data = {}) { + const { service } = this; + const { id } = data; + const result = await service.systems.orderPacking.get({ id }); + return this.success('ok', result); + } + + /** + * 设置打包任务结束时间(仓库侧 system method 包装层)。 + * 若任务状态不是已完成,则同步更新状态为已完成。 + * 前端默认值逻辑:已有结束时间→当前时间;无结束时间→开始时间+5分钟。 + * 结束时间超过仓库配置的打包最大时长上限时,自动截断为上限时间。 + * + * @param {Object} data 请求体 + * @param {number} data.id 打包任务ID + * @param {string} data.end_time 结束时间(ISO 8601 或日期字符串) + * @return {Promise} 统一成功包装响应 + */ + async setEndTime(data = {}) { + const { service } = this; + const { id, end_time } = data; + const result = await service.systems.orderPacking.setEndTime({ id, end_time }); + return this.success('ok', result); + } + + /** + * 强制重新录制打包任务视频(仓库侧 system method 包装层)。 + * 将该任务推送到录制电脑,通过打印服务触发重新录制。 + * + * @param {Object} data 请求体 + * @param {number} data.id 打包任务ID + * @return {Promise} 统一成功包装响应 + */ + async forceRecord(data = {}) { + const { service } = this; + const { id } = data; + const result = await service.systems.orderPacking.forceRecord({ id }); + return this.success('ok', result); + } + + /** + * 提交打包任务导出任务(异步任务模式,与 order.export 口径一致)。 + * 入参 where/sort 与 list 完全一致;提交后立即返回 task_id, + * 后台异步生成单 Sheet Excel(打包任务列表)并上传, + * 通过 exportTaskProgress 查询进度与下载链接。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.where] 筛选条件(与 list 的 where 语义一致)。 + * @param {Object} [data.sort] 排序参数(与 list 的 sort 语义一致)。 + * @return {Promise} 统一成功包装响应(含 task_id/status/progress 等任务信息)。 + */ + async export(data = {}) { + const { service } = this; + const { sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + const taskId = this.generateExportTaskId(warehouseId); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '打包任务导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '打包任务导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.orderPacking.exportPackTask({ + where: enforcedWhere, + sort, + warehouseId, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount, + total_count: safeProgress.totalCount, + message: safeProgress.message || '打包任务导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '打包任务导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '打包任务导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询打包任务导出任务进度(与 order.exportTaskProgress 口径一致)。 + * + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一成功包装响应 + * (含 task_id/status/progress/current_count/total_count/message/error/download_url/update_time)。 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成打包任务导出任务ID。 + * @param {number|string} [warehouseId=''] 仓库ID(缺省兜底取当前上下文 store_id)。 + * @return {string} 导出任务ID。 + */ + generateExportTaskId(warehouseId = '') { + const normalizedWarehouseId = warehouseId || this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `packing_export_${normalizedWarehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化打包任务导出任务ID。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取打包任务导出任务缓存键。 + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${PACKING_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入打包任务导出任务进度缓存(Redis TTL 30 分钟)。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态载荷。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, PACKING_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[order.packing.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取打包任务导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存,未命中返回 null。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[order.packing.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } +} + +module.exports = OrderPackingMethodService; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js new file mode 100644 index 0000000..a0f1110 --- /dev/null +++ b/app/service/systemMethods/order/pendingOrder.js @@ -0,0 +1,7874 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfoMap } = require('../../../lib/intercept_guard'); +const { pickNoticeTimeOrderIds } = require('../../../lib/intercept_time'); + +const PENDING_OUTBOUND_STATUS = 'padding'; +const PENDING_CANCEL_STATUS = 'cancel'; +const PENDING_CANCEL_STEP = 9; +const PENDING_OUTBOUND_STEP = 4; +const PENDING_CANCEL_ALLOWED_STEPS = new Set([ 0, 1, 2, 3 ]); +const PENDING_CANCEL_PENDING_STEPS = new Set([ 1, 2 ]); +const ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_storage:request:'; +const ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const ALLOCATE_STORAGE_PROGRESS_MAP = Object.freeze({ + submitted: 5, + running: 50, + success: 100, + failed: 100, + not_found: 0, + unknown: 0, +}); + +const BATCH_INTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-intercept:'; +const BATCH_INTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const BATCH_LOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-lock:'; +const BATCH_LOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-unlock:'; +const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_express:request:'; +const ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const ALLOCATE_EXPRESS_PROGRESS_MAP = Object.freeze({ + submitted: 5, + running: 50, + success: 100, + failed: 100, + not_found: 0, + unknown: 0, +}); + +const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:'; +const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const SYNC_ORDER_IDS_TASK_CACHE_KEY_PREFIX = 'order:pending:sync_order_ids:request:'; +const SYNC_ORDER_IDS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const SYNC_ORDER_IDS_PROGRESS_MAP = Object.freeze({ + submitted: 5, + running: 50, + success: 100, + failed: 100, + not_found: 0, + unknown: 0, +}); + +const ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_sub_order:request:'; +const ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const ALLOCATE_SUB_ORDER_PROGRESS_MAP = Object.freeze({ + submitted: 5, + running: 50, + success: 100, + partial: 80, + failed: 100, + not_found: 0, + unknown: 0, +}); + +/** + * 中国行政区划反向查询表。 + * + * 用于在 AI 解析结果缺少 province/city/area 时进行兜底反向推断。 + * 覆盖三类特殊行政区: + * - direct:省直辖县级市(如湖北仙桃、潜江、天门) + * - no_district:不设区的地级市(如东莞、中山、嘉峪关、儋州、三沙) + * - delegated:地级市代管县级市(如苏州代管昆山) + * + * 键为 area(区/县)标准名称,值为 { province, city, type }。 + * 同时提供 city -> province 的映射表用于根据城市名反查省份。 + */ +const CHINA_ADMIN_DIVISION_MAP = Object.freeze({ + // ========== 省直辖县级市 / 省直管县 ========== + 仙桃市: { province: '湖北省', city: '湖北省', type: 'direct' }, + 潜江市: { province: '湖北省', city: '湖北省', type: 'direct' }, + 天门市: { province: '湖北省', city: '湖北省', type: 'direct' }, + 神农架林区: { province: '湖北省', city: '湖北省', type: 'direct' }, + 济源市: { province: '河南省', city: '河南省', type: 'direct' }, + 五指山市: { province: '海南省', city: '海南省', type: 'direct' }, + 琼海市: { province: '海南省', city: '海南省', type: 'direct' }, + 文昌市: { province: '海南省', city: '海南省', type: 'direct' }, + 万宁市: { province: '海南省', city: '海南省', type: 'direct' }, + 东方市: { province: '海南省', city: '海南省', type: 'direct' }, + 定安县: { province: '海南省', city: '海南省', type: 'direct' }, + 屯昌县: { province: '海南省', city: '海南省', type: 'direct' }, + 澄迈县: { province: '海南省', city: '海南省', type: 'direct' }, + 临高县: { province: '海南省', city: '海南省', type: 'direct' }, + 白沙黎族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 昌江黎族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 乐东黎族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 陵水黎族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 保亭黎族苗族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 琼中黎族苗族自治县: { province: '海南省', city: '海南省', type: 'direct' }, + 石河子市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 阿拉尔市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 图木舒克市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 五家渠市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 北屯市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 铁门关市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 双河市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 可克达拉市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 昆玉市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 胡杨河市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 新星市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + 白杨市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' }, + + // ========== 不设区的地级市(city 和 area 可为同一值) ========== + 东莞市: { province: '广东省', city: '东莞市', type: 'no_district' }, + 中山市: { province: '广东省', city: '中山市', type: 'no_district' }, + 嘉峪关市: { province: '甘肃省', city: '嘉峪关市', type: 'no_district' }, + 儋州市: { province: '海南省', city: '儋州市', type: 'no_district' }, + 三沙市: { province: '海南省', city: '三沙市', type: 'no_district' }, + + // ========== 常见地级市代管县级市 ========== + 昆山市: { province: '江苏省', city: '苏州市', type: 'delegated' }, + 常熟市: { province: '江苏省', city: '苏州市', type: 'delegated' }, + 张家港市: { province: '江苏省', city: '苏州市', type: 'delegated' }, + 太仓市: { province: '江苏省', city: '苏州市', type: 'delegated' }, + 江阴市: { province: '江苏省', city: '无锡市', type: 'delegated' }, + 宜兴市: { province: '江苏省', city: '无锡市', type: 'delegated' }, + 丹阳市: { province: '江苏省', city: '镇江市', type: 'delegated' }, + 扬中市: { province: '江苏省', city: '镇江市', type: 'delegated' }, + 句容市: { province: '江苏省', city: '镇江市', type: 'delegated' }, + 溧阳市: { province: '江苏省', city: '常州市', type: 'delegated' }, + 海安市: { province: '江苏省', city: '南通市', type: 'delegated' }, + 启东市: { province: '江苏省', city: '南通市', type: 'delegated' }, + 如皋市: { province: '江苏省', city: '南通市', type: 'delegated' }, + 仪征市: { province: '江苏省', city: '扬州市', type: 'delegated' }, + 高邮市: { province: '江苏省', city: '扬州市', type: 'delegated' }, + 兴化市: { province: '江苏省', city: '泰州市', type: 'delegated' }, + 靖江市: { province: '江苏省', city: '泰州市', type: 'delegated' }, + 泰兴市: { province: '江苏省', city: '泰州市', type: 'delegated' }, + 邳州市: { province: '江苏省', city: '徐州市', type: 'delegated' }, + 新沂市: { province: '江苏省', city: '徐州市', type: 'delegated' }, + 东台市: { province: '江苏省', city: '盐城市', type: 'delegated' }, + 建德市: { province: '浙江省', city: '杭州市', type: 'delegated' }, + 慈溪市: { province: '浙江省', city: '宁波市', type: 'delegated' }, + 余姚市: { province: '浙江省', city: '宁波市', type: 'delegated' }, + 瑞安市: { province: '浙江省', city: '温州市', type: 'delegated' }, + 乐清市: { province: '浙江省', city: '温州市', type: 'delegated' }, + 海宁市: { province: '浙江省', city: '嘉兴市', type: 'delegated' }, + 平湖市: { province: '浙江省', city: '嘉兴市', type: 'delegated' }, + 桐乡市: { province: '浙江省', city: '嘉兴市', type: 'delegated' }, + 诸暨市: { province: '浙江省', city: '绍兴市', type: 'delegated' }, + 嵊州市: { province: '浙江省', city: '绍兴市', type: 'delegated' }, + 兰溪市: { province: '浙江省', city: '金华市', type: 'delegated' }, + 义乌市: { province: '浙江省', city: '金华市', type: 'delegated' }, + 东阳市: { province: '浙江省', city: '金华市', type: 'delegated' }, + 永康市: { province: '浙江省', city: '金华市', type: 'delegated' }, + 江山市: { province: '浙江省', city: '衢州市', type: 'delegated' }, + 温岭市: { province: '浙江省', city: '台州市', type: 'delegated' }, + 临海市: { province: '浙江省', city: '台州市', type: 'delegated' }, + 龙泉市: { province: '浙江省', city: '丽水市', type: 'delegated' }, + 巢湖市: { province: '安徽省', city: '合肥市', type: 'delegated' }, + 无为市: { province: '安徽省', city: '芜湖市', type: 'delegated' }, + 桐城市: { province: '安徽省', city: '安庆市', type: 'delegated' }, + 天长市: { province: '安徽省', city: '滁州市', type: 'delegated' }, + 明光市: { province: '安徽省', city: '滁州市', type: 'delegated' }, + 界首市: { province: '安徽省', city: '阜阳市', type: 'delegated' }, + 宁国市: { province: '安徽省', city: '宣城市', type: 'delegated' }, + 广德市: { province: '安徽省', city: '宣城市', type: 'delegated' }, + 福清市: { province: '福建省', city: '福州市', type: 'delegated' }, + 晋江市: { province: '福建省', city: '泉州市', type: 'delegated' }, + 南安市: { province: '福建省', city: '泉州市', type: 'delegated' }, + 石狮市: { province: '福建省', city: '泉州市', type: 'delegated' }, + 龙海市: { province: '福建省', city: '漳州市', type: 'delegated' }, + 邵武市: { province: '福建省', city: '南平市', type: 'delegated' }, + 武夷山市: { province: '福建省', city: '南平市', type: 'delegated' }, + 漳平市: { province: '福建省', city: '龙岩市', type: 'delegated' }, + 福安市: { province: '福建省', city: '宁德市', type: 'delegated' }, + 福鼎市: { province: '福建省', city: '宁德市', type: 'delegated' }, + 乐平市: { province: '江西省', city: '景德镇市', type: 'delegated' }, + 瑞昌市: { province: '江西省', city: '九江市', type: 'delegated' }, + 共青城市: { province: '江西省', city: '九江市', type: 'delegated' }, + 庐山市: { province: '江西省', city: '九江市', type: 'delegated' }, + 贵溪市: { province: '江西省', city: '鹰潭市', type: 'delegated' }, + 瑞金市: { province: '江西省', city: '赣州市', type: 'delegated' }, + 井冈山市: { province: '江西省', city: '吉安市', type: 'delegated' }, + 丰城市: { province: '江西省', city: '宜春市', type: 'delegated' }, + 樟树市: { province: '江西省', city: '宜春市', type: 'delegated' }, + 高安市: { province: '江西省', city: '宜春市', type: 'delegated' }, + 德兴市: { province: '江西省', city: '上饶市', type: 'delegated' }, + 章丘区: { province: '山东省', city: '济南市', type: 'delegated' }, + 胶州市: { province: '山东省', city: '青岛市', type: 'delegated' }, + 平度市: { province: '山东省', city: '青岛市', type: 'delegated' }, + 莱西市: { province: '山东省', city: '青岛市', type: 'delegated' }, + 滕州市: { province: '山东省', city: '枣庄市', type: 'delegated' }, + 龙口市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 莱阳市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 莱州市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 招远市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 栖霞市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 海阳市: { province: '山东省', city: '烟台市', type: 'delegated' }, + 青州市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 诸城市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 寿光市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 安丘市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 高密市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 昌邑市: { province: '山东省', city: '潍坊市', type: 'delegated' }, + 曲阜市: { province: '山东省', city: '济宁市', type: 'delegated' }, + 邹城市: { province: '山东省', city: '济宁市', type: 'delegated' }, + 新泰市: { province: '山东省', city: '泰安市', type: 'delegated' }, + 肥城市: { province: '山东省', city: '泰安市', type: 'delegated' }, + 荣成市: { province: '山东省', city: '威海市', type: 'delegated' }, + 乳山市: { province: '山东省', city: '威海市', type: 'delegated' }, + 乐陵市: { province: '山东省', city: '德州市', type: 'delegated' }, + 禹城市: { province: '山东省', city: '德州市', type: 'delegated' }, + 临清市: { province: '山东省', city: '聊城市', type: 'delegated' }, + 巩义市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 新密市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 荥阳市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 新郑市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 登封市: { province: '河南省', city: '郑州市', type: 'delegated' }, + 偃师区: { province: '河南省', city: '洛阳市', type: 'delegated' }, + 舞钢市: { province: '河南省', city: '平顶山市', type: 'delegated' }, + 汝州市: { province: '河南省', city: '平顶山市', type: 'delegated' }, + 林州市: { province: '河南省', city: '安阳市', type: 'delegated' }, + 卫辉市: { province: '河南省', city: '新乡市', type: 'delegated' }, + 辉县市: { province: '河南省', city: '新乡市', type: 'delegated' }, + 长垣市: { province: '河南省', city: '新乡市', type: 'delegated' }, + 沁阳市: { province: '河南省', city: '焦作市', type: 'delegated' }, + 孟州市: { province: '河南省', city: '焦作市', type: 'delegated' }, + 禹州市: { province: '河南省', city: '许昌市', type: 'delegated' }, + 长葛市: { province: '河南省', city: '许昌市', type: 'delegated' }, + 义马市: { province: '河南省', city: '三门峡市', type: 'delegated' }, + 灵宝市: { province: '河南省', city: '三门峡市', type: 'delegated' }, + 邓州市: { province: '河南省', city: '南阳市', type: 'delegated' }, + 永城市: { province: '河南省', city: '商丘市', type: 'delegated' }, + 项城市: { province: '河南省', city: '周口市', type: 'delegated' }, + 大冶市: { province: '湖北省', city: '黄石市', type: 'delegated' }, + 丹江口市: { province: '湖北省', city: '十堰市', type: 'delegated' }, + 宜都市: { province: '湖北省', city: '宜昌市', type: 'delegated' }, + 当阳市: { province: '湖北省', city: '宜昌市', type: 'delegated' }, + 枝江市: { province: '湖北省', city: '宜昌市', type: 'delegated' }, + 老河口市: { province: '湖北省', city: '襄阳市', type: 'delegated' }, + 枣阳市: { province: '湖北省', city: '襄阳市', type: 'delegated' }, + 宜城市: { province: '湖北省', city: '襄阳市', type: 'delegated' }, + 钟祥市: { province: '湖北省', city: '荆门市', type: 'delegated' }, + 京山市: { province: '湖北省', city: '荆门市', type: 'delegated' }, + 应城市: { province: '湖北省', city: '孝感市', type: 'delegated' }, + 安陆市: { province: '湖北省', city: '孝感市', type: 'delegated' }, + 汉川市: { province: '湖北省', city: '孝感市', type: 'delegated' }, + 石首市: { province: '湖北省', city: '荆州市', type: 'delegated' }, + 洪湖市: { province: '湖北省', city: '荆州市', type: 'delegated' }, + 松滋市: { province: '湖北省', city: '荆州市', type: 'delegated' }, + 监利市: { province: '湖北省', city: '荆州市', type: 'delegated' }, + 麻城市: { province: '湖北省', city: '黄冈市', type: 'delegated' }, + 武穴市: { province: '湖北省', city: '黄冈市', type: 'delegated' }, + 赤壁市: { province: '湖北省', city: '咸宁市', type: 'delegated' }, + 广水市: { province: '湖北省', city: '随州市', type: 'delegated' }, + 恩施市: { province: '湖北省', city: '恩施土家族苗族自治州', type: 'delegated' }, + 利川市: { province: '湖北省', city: '恩施土家族苗族自治州', type: 'delegated' }, + 浏阳市: { province: '湖南省', city: '长沙市', type: 'delegated' }, + 宁乡市: { province: '湖南省', city: '长沙市', type: 'delegated' }, + 醴陵市: { province: '湖南省', city: '株洲市', type: 'delegated' }, + 湘乡市: { province: '湖南省', city: '湘潭市', type: 'delegated' }, + 韶山市: { province: '湖南省', city: '湘潭市', type: 'delegated' }, + 耒阳市: { province: '湖南省', city: '衡阳市', type: 'delegated' }, + 常宁市: { province: '湖南省', city: '衡阳市', type: 'delegated' }, + 武冈市: { province: '湖南省', city: '邵阳市', type: 'delegated' }, + 邵东市: { province: '湖南省', city: '邵阳市', type: 'delegated' }, + 汨罗市: { province: '湖南省', city: '岳阳市', type: 'delegated' }, + 临湘市: { province: '湖南省', city: '岳阳市', type: 'delegated' }, + 津市市: { province: '湖南省', city: '常德市', type: 'delegated' }, + 沅江市: { province: '湖南省', city: '益阳市', type: 'delegated' }, + 资兴市: { province: '湖南省', city: '郴州市', type: 'delegated' }, + 洪江市: { province: '湖南省', city: '怀化市', type: 'delegated' }, + 冷水江市: { province: '湖南省', city: '娄底市', type: 'delegated' }, + 涟源市: { province: '湖南省', city: '娄底市', type: 'delegated' }, + 吉首市: { province: '湖南省', city: '湘西土家族苗族自治州', type: 'delegated' }, + 增城区: { province: '广东省', city: '广州市', type: 'delegated' }, + 从化区: { province: '广东省', city: '广州市', type: 'delegated' }, + 乐昌市: { province: '广东省', city: '韶关市', type: 'delegated' }, + 南雄市: { province: '广东省', city: '韶关市', type: 'delegated' }, + 廉江市: { province: '广东省', city: '湛江市', type: 'delegated' }, + 雷州市: { province: '广东省', city: '湛江市', type: 'delegated' }, + 吴川市: { province: '广东省', city: '湛江市', type: 'delegated' }, + 高州市: { province: '广东省', city: '茂名市', type: 'delegated' }, + 化州市: { province: '广东省', city: '茂名市', type: 'delegated' }, + 信宜市: { province: '广东省', city: '茂名市', type: 'delegated' }, + 高要区: { province: '广东省', city: '肇庆市', type: 'delegated' }, + 四会市: { province: '广东省', city: '肇庆市', type: 'delegated' }, + 惠东县: { province: '广东省', city: '惠州市', type: 'delegated' }, + 博罗县: { province: '广东省', city: '惠州市', type: 'delegated' }, + 龙门县: { province: '广东省', city: '惠州市', type: 'delegated' }, + 兴宁市: { province: '广东省', city: '梅州市', type: 'delegated' }, + 陆丰市: { province: '广东省', city: '汕尾市', type: 'delegated' }, + 阳春市: { province: '广东省', city: '阳江市', type: 'delegated' }, + 英德市: { province: '广东省', city: '清远市', type: 'delegated' }, + 连州市: { province: '广东省', city: '清远市', type: 'delegated' }, + 普宁市: { province: '广东省', city: '揭阳市', type: 'delegated' }, + 罗定市: { province: '广东省', city: '云浮市', type: 'delegated' }, + 岑溪市: { province: '广西壮族自治区', city: '梧州市', type: 'delegated' }, + 东兴市: { province: '广西壮族自治区', city: '防城港市', type: 'delegated' }, + 桂平市: { province: '广西壮族自治区', city: '贵港市', type: 'delegated' }, + 北流市: { province: '广西壮族自治区', city: '玉林市', type: 'delegated' }, + 靖西市: { province: '广西壮族自治区', city: '百色市', type: 'delegated' }, + 平果市: { province: '广西壮族自治区', city: '百色市', type: 'delegated' }, + 合山市: { province: '广西壮族自治区', city: '来宾市', type: 'delegated' }, + 凭祥市: { province: '广西壮族自治区', city: '崇左市', type: 'delegated' }, + 都江堰市: { province: '四川省', city: '成都市', type: 'delegated' }, + 彭州市: { province: '四川省', city: '成都市', type: 'delegated' }, + 邛崃市: { province: '四川省', city: '成都市', type: 'delegated' }, + 崇州市: { province: '四川省', city: '成都市', type: 'delegated' }, + 简阳市: { province: '四川省', city: '成都市', type: 'delegated' }, + 广汉市: { province: '四川省', city: '德阳市', type: 'delegated' }, + 什邡市: { province: '四川省', city: '德阳市', type: 'delegated' }, + 绵竹市: { province: '四川省', city: '德阳市', type: 'delegated' }, + 江油市: { province: '四川省', city: '绵阳市', type: 'delegated' }, + 峨眉山市: { province: '四川省', city: '乐山市', type: 'delegated' }, + 阆中市: { province: '四川省', city: '南充市', type: 'delegated' }, + 华蓥市: { province: '四川省', city: '广安市', type: 'delegated' }, + 万源市: { province: '四川省', city: '达州市', type: 'delegated' }, + 西昌市: { province: '四川省', city: '凉山彝族自治州', type: 'delegated' }, + 会理市: { province: '四川省', city: '凉山彝族自治州', type: 'delegated' }, + 康定市: { province: '四川省', city: '甘孜藏族自治州', type: 'delegated' }, + 马尔康市: { province: '四川省', city: '阿坝藏族羌族自治州', type: 'delegated' }, + 清镇市: { province: '贵州省', city: '贵阳市', type: 'delegated' }, + 盘州市: { province: '贵州省', city: '六盘水市', type: 'delegated' }, + 赤水市: { province: '贵州省', city: '遵义市', type: 'delegated' }, + 仁怀市: { province: '贵州省', city: '遵义市', type: 'delegated' }, + 兴义市: { province: '贵州省', city: '黔西南布依族苗族自治州', type: 'delegated' }, + 兴仁市: { province: '贵州省', city: '黔西南布依族苗族自治州', type: 'delegated' }, + 凯里市: { province: '贵州省', city: '黔东南苗族侗族自治州', type: 'delegated' }, + 都匀市: { province: '贵州省', city: '黔南布依族苗族自治州', type: 'delegated' }, + 福泉市: { province: '贵州省', city: '黔南布依族苗族自治州', type: 'delegated' }, + 安宁市: { province: '云南省', city: '昆明市', type: 'delegated' }, + 宣威市: { province: '云南省', city: '曲靖市', type: 'delegated' }, + 腾冲市: { province: '云南省', city: '保山市', type: 'delegated' }, + 水富市: { province: '云南省', city: '昭通市', type: 'delegated' }, + 楚雄市: { province: '云南省', city: '楚雄彝族自治州', type: 'delegated' }, + 禄丰市: { province: '云南省', city: '楚雄彝族自治州', type: 'delegated' }, + 个旧市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' }, + 开远市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' }, + 蒙自市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' }, + 弥勒市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' }, + 文山市: { province: '云南省', city: '文山壮族苗族自治州', type: 'delegated' }, + 景洪市: { province: '云南省', city: '西双版纳傣族自治州', type: 'delegated' }, + 大理市: { province: '云南省', city: '大理白族自治州', type: 'delegated' }, + 瑞丽市: { province: '云南省', city: '德宏傣族景颇族自治州', type: 'delegated' }, + 芒市: { province: '云南省', city: '德宏傣族景颇族自治州', type: 'delegated' }, + 泸水市: { province: '云南省', city: '怒江傈僳族自治州', type: 'delegated' }, + 香格里拉市: { province: '云南省', city: '迪庆藏族自治州', type: 'delegated' }, + 兴平市: { province: '陕西省', city: '咸阳市', type: 'delegated' }, + 彬州市: { province: '陕西省', city: '咸阳市', type: 'delegated' }, + 韩城市: { province: '陕西省', city: '渭南市', type: 'delegated' }, + 华阴市: { province: '陕西省', city: '渭南市', type: 'delegated' }, + 子长市: { province: '陕西省', city: '延安市', type: 'delegated' }, + 神木市: { province: '陕西省', city: '榆林市', type: 'delegated' }, + 玉门市: { province: '甘肃省', city: '酒泉市', type: 'delegated' }, + 敦煌市: { province: '甘肃省', city: '酒泉市', type: 'delegated' }, + 华亭市: { province: '甘肃省', city: '平凉市', type: 'delegated' }, + 合作市: { province: '甘肃省', city: '甘南藏族自治州', type: 'delegated' }, + 格尔木市: { province: '青海省', city: '海西蒙古族藏族自治州', type: 'delegated' }, + 茫崖市: { province: '青海省', city: '海西蒙古族藏族自治州', type: 'delegated' }, + 德令哈市: { province: '青海省', city: '海西蒙古族藏族自治州', type: 'delegated' }, + 玉树市: { province: '青海省', city: '玉树藏族自治州', type: 'delegated' }, + 灵武市: { province: '宁夏回族自治区', city: '银川市', type: 'delegated' }, + 青铜峡市: { province: '宁夏回族自治区', city: '吴忠市', type: 'delegated' }, + 奎屯市: { province: '新疆维吾尔自治区', city: '伊犁哈萨克自治州', type: 'delegated' }, + 霍尔果斯市: { province: '新疆维吾尔自治区', city: '伊犁哈萨克自治州', type: 'delegated' }, + 库尔勒市: { province: '新疆维吾尔自治区', city: '巴音郭楞蒙古自治州', type: 'delegated' }, + 阿克苏市: { province: '新疆维吾尔自治区', city: '阿克苏地区', type: 'delegated' }, + 库车市: { province: '新疆维吾尔自治区', city: '阿克苏地区', type: 'delegated' }, + 阿图什市: { province: '新疆维吾尔自治区', city: '克孜勒苏柯尔克孜自治州', type: 'delegated' }, + 喀什市: { province: '新疆维吾尔自治区', city: '喀什地区', type: 'delegated' }, + 和田市: { province: '新疆维吾尔自治区', city: '和田地区', type: 'delegated' }, + 博乐市: { province: '新疆维吾尔自治区', city: '博尔塔拉蒙古自治州', type: 'delegated' }, + 阿拉山口市: { province: '新疆维吾尔自治区', city: '博尔塔拉蒙古自治州', type: 'delegated' }, + 伊宁市: { province: '新疆维吾尔自治区', city: '伊犁哈萨克自治州', type: 'delegated' }, + 塔城市: { province: '新疆维吾尔自治区', city: '塔城地区', type: 'delegated' }, + 乌苏市: { province: '新疆维吾尔自治区', city: '塔城地区', type: 'delegated' }, + 沙湾市: { province: '新疆维吾尔自治区', city: '塔城地区', type: 'delegated' }, + 阿勒泰市: { province: '新疆维吾尔自治区', city: '阿勒泰地区', type: 'delegated' }, + 昌吉市: { province: '新疆维吾尔自治区', city: '昌吉回族自治州', type: 'delegated' }, + 阜康市: { province: '新疆维吾尔自治区', city: '昌吉回族自治州', type: 'delegated' }, + 哈密市: { province: '新疆维吾尔自治区', city: '哈密市', type: 'delegated' }, + 吐鲁番市: { province: '新疆维吾尔自治区', city: '吐鲁番市', type: 'delegated' }, +}); + +/** + * 直辖市名称集合,用于判断是否为直辖市地址。 + */ +const MUNICIPALITY_SET = new Set([ + '北京市', '天津市', '上海市', '重庆市', +]); + +/** + * 省份名称集合,用于 city/area 名反向匹配省份。 + */ +const PROVINCE_LIST = [ + '北京市', '天津市', '上海市', '重庆市', + '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省', + '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', + '河南省', '湖北省', '湖南省', '广东省', '海南省', + '四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省', + '台湾省', + '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区', + '香港特别行政区', '澳门特别行政区', +]; + +/** + * 本地地址解析副接口内置的"省 → 地级市"地址字典数据。 + * + * 覆盖全国 34 个省级行政区下的地级市/自治州/地区/盟(约 340 条), + * 供 parseAddressLocal 遍历匹配识别省市区,不依赖 AI 接口。 + * 直辖市(北京/天津/上海/重庆)的 city 与 province 同名;港澳台无地级市条目, + * 仅靠 PROVINCE_LIST 识别省份。 + */ +const LOCAL_CITY_DICT = Object.freeze( + [ + [ '北京市', [ '北京市' ]], + [ '天津市', [ '天津市' ]], + [ '上海市', [ '上海市' ]], + [ '重庆市', [ '重庆市' ]], + [ '河北省', [ '石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市' ]], + [ '山西省', [ '太原市', '大同市', '阳泉市', '长治市', '晋城市', '朔州市', '晋中市', '运城市', '忻州市', '临汾市', '吕梁市' ]], + [ '内蒙古自治区', [ '呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市', '鄂尔多斯市', '呼伦贝尔市', '巴彦淖尔市', '乌兰察布市', '兴安盟', '锡林郭勒盟', '阿拉善盟' ]], + [ '辽宁省', [ '沈阳市', '大连市', '鞍山市', '抚顺市', '本溪市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市', '盘锦市', '铁岭市', '朝阳市', '葫芦岛市' ]], + [ '吉林省', [ '长春市', '吉林市', '四平市', '辽源市', '通化市', '白山市', '松原市', '白城市', '延边朝鲜族自治州' ]], + [ '黑龙江省', [ '哈尔滨市', '齐齐哈尔市', '鸡西市', '鹤岗市', '双鸭山市', '大庆市', '伊春市', '佳木斯市', '七台河市', '牡丹江市', '黑河市', '绥化市', '大兴安岭地区' ]], + [ '江苏省', [ '南京市', '无锡市', '徐州市', '常州市', '苏州市', '南通市', '连云港市', '淮安市', '盐城市', '扬州市', '镇江市', '泰州市', '宿迁市' ]], + [ '浙江省', [ '杭州市', '宁波市', '温州市', '嘉兴市', '湖州市', '绍兴市', '金华市', '衢州市', '舟山市', '台州市', '丽水市' ]], + [ '安徽省', [ '合肥市', '芜湖市', '蚌埠市', '淮南市', '马鞍山市', '淮北市', '铜陵市', '安庆市', '黄山市', '滁州市', '阜阳市', '宿州市', '六安市', '亳州市', '池州市', '宣城市' ]], + [ '福建省', [ '福州市', '厦门市', '莆田市', '三明市', '泉州市', '漳州市', '南平市', '龙岩市', '宁德市' ]], + [ '江西省', [ '南昌市', '景德镇市', '萍乡市', '九江市', '新余市', '鹰潭市', '赣州市', '吉安市', '宜春市', '抚州市', '上饶市' ]], + [ '山东省', [ '济南市', '青岛市', '淄博市', '枣庄市', '东营市', '烟台市', '潍坊市', '济宁市', '泰安市', '威海市', '日照市', '临沂市', '德州市', '聊城市', '滨州市', '菏泽市' ]], + [ '河南省', [ '郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市', '商丘市', '信阳市', '周口市', '驻马店市' ]], + [ '湖北省', [ '武汉市', '黄石市', '十堰市', '宜昌市', '襄阳市', '鄂州市', '荆门市', '孝感市', '荆州市', '黄冈市', '咸宁市', '随州市', '恩施土家族苗族自治州' ]], + [ '湖南省', [ '长沙市', '株洲市', '湘潭市', '衡阳市', '邵阳市', '岳阳市', '常德市', '张家界市', '益阳市', '郴州市', '永州市', '怀化市', '娄底市', '湘西土家族苗族自治州' ]], + [ '广东省', [ '广州市', '韶关市', '深圳市', '珠海市', '汕头市', '佛山市', '江门市', '湛江市', '茂名市', '肇庆市', '惠州市', '梅州市', '汕尾市', '河源市', '阳江市', '清远市', '东莞市', '中山市', '潮州市', '揭阳市', '云浮市' ]], + [ '广西壮族自治区', [ '南宁市', '柳州市', '桂林市', '梧州市', '北海市', '防城港市', '钦州市', '贵港市', '玉林市', '百色市', '贺州市', '河池市', '来宾市', '崇左市' ]], + [ '海南省', [ '海口市', '三亚市', '三沙市', '儋州市' ]], + [ '四川省', [ '成都市', '自贡市', '攀枝花市', '泸州市', '德阳市', '绵阳市', '广元市', '遂宁市', '内江市', '乐山市', '南充市', '眉山市', '宜宾市', '广安市', '达州市', '雅安市', '巴中市', '资阳市', '阿坝藏族羌族自治州', '甘孜藏族自治州', '凉山彝族自治州' ]], + [ '贵州省', [ '贵阳市', '六盘水市', '遵义市', '安顺市', '毕节市', '铜仁市', '黔西南布依族苗族自治州', '黔东南苗族侗族自治州', '黔南布依族苗族自治州' ]], + [ '云南省', [ '昆明市', '曲靖市', '玉溪市', '保山市', '昭通市', '丽江市', '普洱市', '临沧市', '楚雄彝族自治州', '红河哈尼族彝族自治州', '文山壮族苗族自治州', '西双版纳傣族自治州', '大理白族自治州', '德宏傣族景颇族自治州', '怒江傈僳族自治州', '迪庆藏族自治州' ]], + [ '西藏自治区', [ '拉萨市', '日喀则市', '昌都市', '林芝市', '山南市', '那曲市', '阿里地区' ]], + [ '陕西省', [ '西安市', '铜川市', '宝鸡市', '咸阳市', '渭南市', '延安市', '汉中市', '榆林市', '安康市', '商洛市' ]], + [ '甘肃省', [ '兰州市', '嘉峪关市', '金昌市', '白银市', '天水市', '武威市', '张掖市', '平凉市', '酒泉市', '庆阳市', '定西市', '陇南市', '临夏回族自治州', '甘南藏族自治州' ]], + [ '青海省', [ '西宁市', '海东市', '海北藏族自治州', '黄南藏族自治州', '海南藏族自治州', '果洛藏族自治州', '玉树藏族自治州', '海西蒙古族藏族自治州' ]], + [ '宁夏回族自治区', [ '银川市', '石嘴山市', '吴忠市', '固原市', '中卫市' ]], + [ '新疆维吾尔自治区', [ '乌鲁木齐市', '克拉玛依市', '吐鲁番市', '哈密市', '昌吉回族自治州', '博尔塔拉蒙古自治州', '巴音郭楞蒙古自治州', '克孜勒苏柯尔克孜自治州', '伊犁哈萨克自治州', '阿克苏地区', '喀什地区', '和田地区', '塔城地区', '阿勒泰地区' ]], + ].reduce((map, [ province, cities ]) => { + for (const city of cities) map[city] = province; + return map; + }, {}) +); + +/** + * parseAddressLocal 内置的示例地址数据。 + * + * 请求未传 address/addresses 时,接口直接遍历识别这批地址并返回结果, + * 便于验证本地字典遍历识别效果,覆盖直辖市、普通省市区、县级市、不设区地级市、 + * 自治区、仅有城市名、仅有县级市名等典型场景。 + */ +const LOCAL_SAMPLE_ADDRESSES = Object.freeze([ + '张三 13800138000 北京市朝阳区建国路88号', + '李四 13900139000 广东省广州市天河区体育西路100号', + '江苏省苏州市昆山市花桥镇光明路8号', + '广东省东莞市南城街道宏图路100号', + '新疆维吾尔自治区乌鲁木齐市天山区中山路1号', + '苏州市姑苏区干将西路100号', + '昆山市玉山镇前进西路100号', + '四川省成都市武侯区人民南路四段10号', +]); + +/** + * 根据已解析的地址字段,利用中国行政区划知识进行反向推断,补全缺失的 province/city/area。 + * + * 处理逻辑: + * 1. 若 area 在 CHINA_ADMIN_DIVISION_MAP 中,直接补全 province 和 city + * 2. 若 province 为空但 city 或 area 不为空,尝试通过名称匹配推断省份 + * 3. 若 city 为空但 area 不为空,尝试通过 area 名推断城市 + * 4. 若 city 和 area 都为空,尝试从 town / detailAddress 中提取信息 + * 5. 对不设区地级市,若 area 为空则用 city 填充 + * + * @param {Object} parsed AI 解析后的原始结果 { province, city, area, town, detailAddress, name, mobile } + * @return {Object} 修正后的结果,结构与输入一致 + */ +function reverseInferAddress(parsed) { + let { province, city, area, town } = parsed; + const { detailAddress } = parsed; + + // 标准化:去除末尾的"市"、"省"等做模糊匹配用 + const normalizeName = name => { + if (!name) return ''; + let n = name.trim(); + // 去掉末尾的"市"、"县"、"区"、"自治县"、"自治州" 等后缀 + n = n.replace(/(市|县|区|自治县|自治州|地区|盟|林区)$/, ''); + return n; + }; + + // --- 步骤1:area 命中行政区划映射表 --- + if (area) { + const entry = CHINA_ADMIN_DIVISION_MAP[area]; + if (entry) { + province = province || entry.province; + city = city || entry.city; + // 不设区地级市:area 和 city 一样时补充说明 + if (entry.type === 'no_district' && (!area || area === city || area === entry.city)) { + // area 已是 city 名,保持不变(允许 area = city 对于不设区地级市) + } + } + } + + // --- 步骤2:province 为空,从 city 或 area 反查 --- + if (!province) { + // 尝试从 city 反查省份(去掉"市"后缀) + if (city) { + const cityNorm = normalizeName(city); + // 先在映射表中查(按 city 名匹配) + for (const [ , entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) { + if (entry.city && normalizeName(entry.city) === cityNorm && entry.province) { + province = entry.province; + break; + } + } + // 如果没找到,尝试判断是否本身是省份名 + if (!province && PROVINCE_LIST.includes(city)) { + province = city; + } + } + // 如果 city 没有,尝试从 area 反查 + if (!province && area) { + const entry = CHINA_ADMIN_DIVISION_MAP[area]; + if (entry && entry.province) { + province = entry.province; + } + } + } + + // --- 步骤3:city 为空但 area 不为空,反查城市 --- + if (!city && area) { + const entry = CHINA_ADMIN_DIVISION_MAP[area]; + if (entry && entry.city) { + city = entry.city; + } else { + // 若 area 带"市"后缀,则 city 与 area 同名 + if (area.endsWith('市') && !MUNICIPALITY_SET.has(area)) { + city = area; + } + } + } + + // --- 步骤4:city 和 area 都为空,尝试从 town / detailAddress 提取 --- + if (!city && !area) { + const townStr = (town || '').trim(); + const detailStr = (detailAddress || '').trim(); + + // 从 town 中匹配已知城市/区县 + if (townStr) { + for (const [ key, entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) { + if (townStr.includes(key) || townStr.includes(normalizeName(key))) { + province = province || entry.province; + city = city || entry.city; + area = area || key; + break; + } + } + } + + // 从 detailAddress 中尝试匹配 + if (!city && !area && detailStr) { + for (const [ key, entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) { + if (detailStr.includes(key) || detailStr.includes(normalizeName(key))) { + province = province || entry.province; + city = city || entry.city; + area = area || key; + break; + } + } + } + } + + // --- 步骤5:不设区地级市兜底 --- + // 若 city 已知且为不设区地级市,area 为空则用 city 填充 + if (city && !area) { + const cityNorm = normalizeName(city); + for (const [ , entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) { + if (entry.type === 'no_district' && normalizeName(entry.city) === cityNorm) { + area = entry.city; // 对于不设区地级市,area 填 city 名 + province = province || entry.province; + break; + } + } + } + + return { ...parsed, province: province || '', city: city || '', area: area || '' }; +} + +/** + * 地址解析最终兜底:本地字典遍历与行政区划映射表均失败时,用正则按"省-市-区-镇"顺序 + * 从原始地址字符串中提取行政区划。支持省份全称与简称(如"广东"、"内蒙古")。 + * + * @param {string} text 原始地址字符串。 + * @return {Object} { province, city, area, town },识别不到的字段为空字符串。 + */ +function extractAddressByRegex(text) { + const src = String(text || ''); + const result = { province: '', city: '', area: '', town: '' }; + if (!src) return result; + + // 省份:全称与简称按长度降序匹配,避免"河北/河南"等前缀误配 + const shorten = p => p.replace(/(壮族自治区|回族自治区|维吾尔自治区|特别行政区|自治区|省|市)$/, ''); + const provincePattern = PROVINCE_LIST + .reduce((list, p) => { + const short = shorten(p); + if (short !== p) list.push(short); + list.push(p); + return list; + }, []) + .sort((a, b) => b.length - a.length) + .join('|'); + const provinceMatch = src.match(new RegExp(`(${provincePattern})`)); + if (!provinceMatch) return result; + + const provinceToken = provinceMatch[1]; + const fullProvince = PROVINCE_LIST.find(p => p.startsWith(provinceToken)); + result.province = fullProvince || provinceToken; + const rest = src.slice(provinceMatch.index + provinceToken.length); + + const cityMatch = rest.match(/([\u4e00-\u9fa5]{2,10}?(?:自治州|地区|盟|市))/); + if (!cityMatch) return result; + result.city = cityMatch[1]; + const restAfterCity = rest.slice(cityMatch.index + cityMatch[1].length); + + const areaMatch = restAfterCity.match(/([\u4e00-\u9fa5]{2,10}?(?:自治县|区|县|市))/); + if (!areaMatch) return result; + result.area = areaMatch[1]; + const restAfterArea = restAfterCity.slice(areaMatch.index + areaMatch[1].length); + + const townMatch = restAfterArea.match(/([\u4e00-\u9fa5]{2,10}?(?:街道|办事处|镇|乡))/); + if (townMatch) { + result.town = townMatch[1]; + } + return result; +} + +/** + * 本地地址解析副接口核心逻辑:不调用 AI,直接遍历内置的省市区地址字典数据, + * 对地址字符串做包含匹配,识别出省/市/区(及乡镇、详细地址、手机号)。 + * + * 遍历识别顺序: + * 1. 提取并剥离手机号 + * 2. 遍历 LOCAL_CITY_DICT 找最先出现的地级市 → city + province + * 3. 无城市命中时,遍历 CHINA_ADMIN_DIVISION_MAP 找特殊行政区 → area + 反查省/市 + * 4. 仍未识别省份时,遍历 PROVINCE_LIST 全称/简称匹配 + * 5. 有省无市时,在省名之后正则提取市 + * 6. 直辖市补全:province 与 city 同名 + * 7. 有市无区时,在市名之后遍历特殊行政区 + 正则提取区/县 + * 8. 复用 reverseInferAddress 统一补全缺失的省/市/区 + * 9. 正则提取乡镇/街道,剩余部分作为详细地址 + * + * @param {*} rawAddress 原始地址字符串。 + * @return {Object} { address, ok, message, fields };fields 为 + * { province, city, area, town, detailAddress, name, mobile } 或 null。 + */ +function parseAddressByLocalDict(rawAddress) { + const address = String(rawAddress || '').trim(); + if (!address) { + return { address, ok: false, message: '地址字符串不能为空', fields: null }; + } + + // 1. 提取并剥离手机号 + let working = address; + let mobile = ''; + const mobileMatch = working.match(/1[3-9]\d{9}/); + if (mobileMatch) { + mobile = mobileMatch[0]; + working = working.replace(mobile, ''); + } + + let province = ''; + let city = ''; + let area = ''; + + // 2. 遍历地级市字典,取地址中最先出现的城市 + let cityIdx = -1; + for (const [ cityName, provinceName ] of Object.entries(LOCAL_CITY_DICT)) { + const idx = working.indexOf(cityName); + if (idx >= 0 && (cityIdx === -1 || idx < cityIdx)) { + cityIdx = idx; + city = cityName; + province = provinceName; + } + } + + // 3. 无城市命中时,遍历特殊行政区映射(省直辖县级市/不设区地级市/代管县级市) + if (!city) { + let areaIdx = -1; + for (const [ key, entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) { + const idx = working.indexOf(key); + if (idx >= 0 && (areaIdx === -1 || idx < areaIdx)) { + areaIdx = idx; + area = key; + province = entry.province; + city = entry.city; + } + } + } + + // 4. 仍未识别省份时,遍历省份全称/简称 + if (!province) { + for (const p of PROVINCE_LIST) { + if (working.includes(p)) { + province = p; + break; + } + const short = p.replace(/(壮族自治区|回族自治区|维吾尔自治区|特别行政区|自治区|省|市)$/, ''); + if (short !== p && working.includes(short)) { + province = p; + break; + } + } + } + + // 5. 有省无市:在省名之后正则提取市 + if (province && !city) { + const short = province.replace(/(壮族自治区|回族自治区|维吾尔自治区|特别行政区|自治区|省|市)$/, ''); + const fullIdx = working.indexOf(province); + const shortIdx = working.indexOf(short); + const idx = Math.max(fullIdx, shortIdx); + const skipLen = fullIdx >= 0 ? province.length : short.length; + const rest = idx >= 0 ? working.slice(idx + skipLen) : working; + const cityMatch = rest.match(/([\u4e00-\u9fa5]{2,10}?(?:自治州|地区|盟|市))/); + if (cityMatch) { + city = cityMatch[1]; + } + } + + // 6. 直辖市补全:province 与 city 同名 + if (!province && MUNICIPALITY_SET.has(city)) { + province = city; + } + if (province && !city && MUNICIPALITY_SET.has(province)) { + city = province; + } + + // 7. 有市无区:在市名之后遍历特殊行政区 + 正则提取区/县 + if (city && !area) { + const cityPos = working.indexOf(city); + const rest = cityPos >= 0 ? working.slice(cityPos + city.length) : working; + for (const key of Object.keys(CHINA_ADMIN_DIVISION_MAP)) { + if (rest.includes(key)) { + area = key; + break; + } + } + if (!area) { + const areaMatch = rest.match(/([\u4e00-\u9fa5]{1,10}?(?:自治县|自治旗|旗|区|县|市))/); + if (areaMatch) { + area = areaMatch[1]; + } + // "市辖区"不是真实行政区(东莞/中山等不设区地级市的历史遗留写法), + // 从原文剥离并置空 area,交由 reverseInferAddress 对不设区地级市将 area 补为 city; + // 剥离可避免后续 town/detailAddress 提取把"市辖区"误并入街道名 + if (area === '市辖区') { + working = working.replace('市辖区', ''); + area = ''; + } + } + } + + // 8. 复用反向推断补全缺失的省/市/区(含不设区地级市 area 补 city 等规则) + let town = ''; + const inferred = reverseInferAddress({ + province, + city, + area, + town, + detailAddress: working, + name: '', + mobile, + }); + province = inferred.province; + city = inferred.city; + area = inferred.area; + + // 9. 提取乡镇/街道:限定在已识别行政区(city/area)之后的余串开头匹配, + // 避免正则从地址开头扫描时把省市区前缀吞进镇名(如"苏省苏州市昆山市花桥镇") + town = ''; + let restTail = working; + { + const areaPos = area ? working.indexOf(area) : -1; + const cityPos = city ? working.indexOf(city) : -1; + const areaEnd = areaPos >= 0 ? areaPos + area.length : -1; + const cityEnd = cityPos >= 0 ? cityPos + city.length : -1; + if (Math.max(areaEnd, cityEnd) >= 0) { + restTail = working.slice(Math.max(areaEnd, cityEnd)); + } + } + const townMatch = restTail.match(/^[\s,,、]*([\u4e00-\u9fa5]{2,10}?(?:街道|办事处|镇|乡))/); + if (townMatch) { + town = townMatch[1]; + } + let cutEnd = -1; + for (const part of [ province, city, area, town ]) { + if (!part) continue; + const idx = working.indexOf(part); + if (idx >= 0 && idx + part.length > cutEnd) { + cutEnd = idx + part.length; + } + } + let detailAddress = cutEnd >= 0 ? working.slice(cutEnd) : working; + detailAddress = detailAddress.replace(/^[\s,,、-]+/, '').trim(); + + // 10. 正则最终兜底:字典遍历无法识别时,用正则从原文提取省市区 + if (!province && !city && !area) { + const regexResult = extractAddressByRegex(working); + if (regexResult.province) { + province = regexResult.province; + city = city || regexResult.city; + area = area || regexResult.area; + if (!town) { + town = regexResult.town; + } + // 重算详细地址 + cutEnd = -1; + for (const part of [ province, city, area, town ]) { + if (!part) continue; + const idx = working.indexOf(part); + if (idx >= 0 && idx + part.length > cutEnd) { + cutEnd = idx + part.length; + } + } + detailAddress = cutEnd >= 0 ? working.slice(cutEnd) : working; + detailAddress = detailAddress.replace(/^[\s,,、-]+/, '').trim(); + } + } + + if (!province && !city && !area) { + return { address, ok: false, message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null }; + } + + return { + address, + ok: true, + message: 'ok', + fields: { province, city, area, town, detailAddress, name: '', mobile }, + }; +} + +class PendingOrderService extends OrderBaseService { + /** + * 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。 + * + * @param {Egg.Context} ctx 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 待处理订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('pendingOrder', data); + } + + /** + * 查询待处理订单详情。 + * + * 仅返回订单头、商品明细与运单信息; + * 待处理详情不再返回 logs 字段,也不触发操作日志查询。 + * + * 兜底查询:忽略请求中的 tableType 等表位参数, + * 固定先查询配送表(dispatch),查询不到时回退到待处理表(current)再查询一次, + * 避免订单在配送表与待处理表之间流转后详情查询落空。 + * + * @param {Object} data 请求体。 + * @return {Promise} 订单头、商品明细和运单信息。 + */ + async detail(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + + if (orderIds.length !== 1) { + throw new Error('订单详情仅支持查询单个订单'); + } + + const orderId = orderIds[0]; + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + + // 忽略传入的 tableType:固定先查配送表(dispatch),查不到再兜底待处理表(current) + let actualTableType = 'dispatch'; + let orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId); + let order = await orderModel.findOne({ + where: orderWhere, + raw: true, + }); + + if (!order) { + actualTableType = 'current'; + orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId); + order = await orderModel.findOne({ + where: orderWhere, + raw: true, + }); + } + + if (!order) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderItemsModel = await this.getOrderItemsModelByTableType(actualTableType, warehouseId); + const orderItems = await orderItemsModel.findAll({ + where: { + order_id: orderId, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 通过 getStockDetails(带缓存)批量查询 stock_warehouse 标准信息 + // 返回以 stock_warehouse 格式为主、附带 plan_qty / order_line_no / stock_id / order_item_id / order_id 的数据 + const orderItemsWithImages = await this.attachStockDetailsToOrderItems(orderItems, warehouseId); + + // 构建 order_item_id → orderItem 的快速查找映射(仍基于原始 order_items) + const orderItemMap = new Map(); + for (const item of orderItems) { + orderItemMap.set(item.id, item); + } + + // 构建 stockMap:直接从 attachStockDetailsToOrderItems(已是 stock_warehouse 格式)中按 stock_id 建立映射 + const stockMap = new Map(); + for (const item of orderItemsWithImages) { + const stockId = Number(item.stock_id); + if (stockId) { + stockMap.set(stockId, item); + } + } + + // 查询已分配的储位信息(排除已取消的分配记录) + const orderItemIds = orderItems.map(item => item.id).filter(Boolean); + const pickingMap = new Map(); + const storageItems = []; + if (orderItemIds.length > 0) { + const { Op } = this.app.Sequelize; + const pickingModel = this.ctx.model.Picking; + if (pickingModel) { + const pickingRows = await pickingModel.findAll({ + where: { + order_item_id: { [Op.in]: orderItemIds }, + status: { [Op.ne]: 'cancel' }, + }, + raw: true, + }); + for (const row of pickingRows) { + const key = row.order_item_id; + if (!pickingMap.has(key)) { + pickingMap.set(key, []); + } + pickingMap.get(key).push({ + space_id: row.space_id, + space_name: row.space_name, + storage_id: row.storage_id, + quantity: row.quantity, + status: row.status, + }); + + // 按库位维度平铺 picking 记录,并附带商品库存信息 + const orderItem = orderItemMap.get(row.order_item_id); + if (orderItem) { + const stockId = Number(orderItem.stock_id || 0); + const stockWarehouse = stockMap.get(stockId); + if (stockWarehouse) { + storageItems.push({ + order_item_id: row.order_item_id, + space_id: row.space_id, + space_name: row.space_name, + storage_id: row.storage_id, + quantity: row.quantity, + status: row.status, + stock_id: stockId, + item_code: stockWarehouse.item_code, + item_name: stockWarehouse.item_name, + sku_property: stockWarehouse.sku_property, + stock_unit: stockWarehouse.stock_unit, + }); + } + } + } + } + } + const orderItemsWithPicking = orderItemsWithImages.map(item => ({ + ...item, + picking_locations: pickingMap.get(item.order_item_id) || [], + })); + + const expresses = await this.getOrderExpressesByOrderId(orderId, order); + + return { + detail: order, + items: orderItemsWithPicking, + expresses, + storage_items: storageItems, + }; + } + + /** + * 将待处理订单反审回待审核状态。 + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息。 + */ + async reverseReviewOrder(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 where = this.buildOrderWhere(orderIds, warehouseId); + const step = this.resolveReviewStep('none'); + const now = new Date(); + const canUseTransaction = this.ctx.model && typeof this.ctx.model.transaction === 'function'; + const transaction = canUseTransaction ? await this.ctx.model.transaction() : null; + const dbQueryOptions = transaction ? { transaction } : {}; + + try { + const targetOrders = await model.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no' ], + where, + raw: true, + ...dbQueryOptions, + }); + + if (!Array.isArray(targetOrders) || targetOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const targetOrderIds = targetOrders + .map(order => Number(order && order.id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + + await this.assertOrdersWithoutWaybill(targetOrderIds, warehouseId, transaction); + + const affectedWaveIds = [ ...new Set(targetOrders + .map(order => Number(order && order.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + const updateValues = { + inspection_status: 'none', + step, + updated_at: now, + }; + + if (affectedWaveIds.length > 0) { + updateValues.wave_id = 0; + updateValues.wave_no = ''; + } + + const updateResult = await model.update(updateValues, { + where, + ...dbQueryOptions, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + if (affectedWaveIds.length > 0) { + await this.syncWavesAfterReverseReview({ + warehouseId, + waveIds: affectedWaveIds, + orderModel: model, + transaction: transaction || undefined, + }); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + ...dbQueryOptions, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + if (transaction) { + await transaction.commit(); + } + + 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]; + return { + 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), + }; + } catch (error) { + if (transaction) { + await transaction.rollback(); + } + throw error; + } + } + + /** + * 校验订单是否已分配运单号。 + * + * 强制同仓校验:读取 wms_order_express 必须同时带上订单ID与仓库ID, + * 禁止仅凭订单ID跨仓串读运单号。 + * 若任一订单存在非空运单号,直接抛出业务异常,阻止反审。 + * + * @param {Array} orderIds 订单ID集合。 + * @param {number|string|null|undefined} warehouseId 仓库ID,必须为当前订单所属仓库。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async assertOrdersWithoutWaybill(orderIds = [], warehouseId = null, transaction) { + const normalizedOrderIds = Array.isArray(orderIds) + ? orderIds + .map(orderId => Number(orderId || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0) + : []; + + if (normalizedOrderIds.length === 0) { + return; + } + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return; + } + + // 强制同仓校验:缺少仓库上下文时直接跳过校验读取(按无可读记录处理) + const normalizedWarehouseId = warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + ? Number(warehouseId) + : 0; + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return; + } + + const expressRows = await orderExpressModel.findAll({ + attributes: [ 'order_id', 'waybill_code' ], + where: { + order_id: normalizedOrderIds, + warehouse_id: normalizedWarehouseId, + }, + raw: true, + transaction, + }); + + const assignedOrderIds = [ ...new Set((Array.isArray(expressRows) ? expressRows : []) + .filter(row => String(row && row.waybill_code || '').trim()) + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + + if (assignedOrderIds.length > 0) { + const displayOrderIds = assignedOrderIds.slice(0, 10).join(','); + throw new Error(`订单[${displayOrderIds}]已分配运单号,禁止反审`); + } + } + + /** + * 反审后同步波次统计与索引。 + * + * 同一事务内重建目标波次索引,并回写波次总单量/处理量。 + * + * @param {Object} params 同步参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.waveIds 受影响波次ID集合。 + * @param {Object} params.orderModel 订单模型。 + * @param {Object} params.transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async syncWavesAfterReverseReview({ warehouseId, waveIds, orderModel, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveIds = Array.isArray(waveIds) + ? [ ...new Set(waveIds + .map(waveId => Number(waveId || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ] + : []; + + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) { + return; + } + + const waveService = this.service.systemMethods.order.wave; + const remainingCountMap = await waveService.replaceOrderWaveIndexByWaveIds({ + warehouseId: normalizedWarehouseId, + waveIds: normalizedWaveIds, + orderModel, + transaction, + }); + + const updatedWaveIds = []; + const emptiedWaveIds = []; + for (const waveId of normalizedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + if (remainingCount > 0) { + updatedWaveIds.push(waveId); + } else { + emptiedWaveIds.push(waveId); + } + } + + for (const waveId of updatedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + const updateWaveSql = ` + UPDATE wms_wave_batch + SET total_orders = :remainingCount, + processed_orders = LEAST(processed_orders, :remainingCount), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `; + + await this.ctx.model.query(updateWaveSql, { + replacements: { + warehouseId: normalizedWarehouseId, + waveId, + remainingCount, + }, + transaction, + }); + } + + if (emptiedWaveIds.length > 0) { + const emptyWaveSql = ` + UPDATE wms_wave_batch + SET total_orders = 0, + processed_orders = 0, + wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `; + + await this.ctx.model.query(emptyWaveSql, { + replacements: { + warehouseId: normalizedWarehouseId, + waveIds: emptiedWaveIds, + }, + transaction, + }); + } + } + + /** + * 将待处理订单批量分配储位。 + * + * 该入口仅接受订单相关入参,不再接受 warehouse_id / warehouseId; + * 仓库上下文统一取当前登录用户的 store_id。 + * + * @param {Object} data 请求体。 + * @return {Promise} 统一 success 包装的受理结果,包含 request_id 与 warehouse_id。 + */ + async allocateStorage(data = {}) { + console.log('[PendingOrderService.allocateStorage] 原始入参', data); + + const requestData = this.isPlainObject(data) ? data : {}; + const forbiddenWarehouseKeys = [ 'warehouse_id', 'warehouseId' ].filter(key => Object.prototype.hasOwnProperty.call(requestData, key)); + + if (forbiddenWarehouseKeys.length > 0) { + console.log('[PendingOrderService.allocateStorage] 检测到禁止传入的仓库字段', { + forbiddenWarehouseKeys, + requestData, + }); + throw new Error('待处理订单储位分配接口不再接受 warehouse_id / warehouseId,请使用当前用户仓库上下文'); + } + + 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, + }; + + console.log('[PendingOrderService.allocateStorage] 归一化入参', normalizedData); + const warehouseId = this.getWarehouseId(); + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const requestId = `storage_alloc_${warehouseId ?? 'unknown'}_${timestamp}_${randomToken}`; + const taskProgressState = { + total_count: 0, + processed_count: 0, + progress: 0, + }; + + await this.setAllocateStorageTaskProgress(requestId, { + status: 'submitted', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + }); + + setImmediate(async () => { + try { + await this.setAllocateStorageTaskProgress(requestId, { + status: 'running', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + }); + + const allocationRequest = { + allow_storage_location: normalizedData.allow_storage_location, + order_ids: normalizedData.order_ids, + progress_callback: async progressPayload => { + const safeProgressPayload = this.isPlainObject(progressPayload) ? progressPayload : {}; + const totalCount = this.normalizeAllocateStorageTaskCount( + safeProgressPayload.total_count + ?? safeProgressPayload.totalCount + ?? taskProgressState.total_count, + taskProgressState.total_count + ); + const processedCount = this.normalizeAllocateStorageTaskCount( + safeProgressPayload.processed_count + ?? safeProgressPayload.processedCount + ?? taskProgressState.processed_count, + taskProgressState.processed_count + ); + + taskProgressState.total_count = Math.max(taskProgressState.total_count, totalCount); + taskProgressState.processed_count = Math.min( + taskProgressState.total_count, + Math.max(taskProgressState.processed_count, processedCount) + ); + taskProgressState.progress = this.normalizeAllocateStorageTaskProgress( + safeProgressPayload.progress, + 'running', + taskProgressState.total_count, + taskProgressState.processed_count + ); + + await this.setAllocateStorageTaskProgress(requestId, { + status: 'running', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + }); + }, + }; + + console.log('[PendingOrderService.allocateStorage] 后台开始处理储位分配', { + request_id: requestId, + allocationRequest: { + allow_storage_location: allocationRequest.allow_storage_location, + order_ids: allocationRequest.order_ids, + }, + }); + const result = await this.service.systems.orderStorageAllocation.allocateStorage(allocationRequest); + + if (taskProgressState.total_count > 0) { + taskProgressState.processed_count = taskProgressState.total_count; + } + taskProgressState.progress = 100; + + await this.setAllocateStorageTaskProgress(requestId, { + status: 'success', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + result, + }); + + // 写操作日志(不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const warehouseId = this.getWarehouseId(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + const orderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids ? [ normalizedData.order_ids ] : []); + + // 从 result 中提取分配结果信息 + const resultData = result && result.data ? result.data : (result || {}); + const allocatedIds = Array.isArray(resultData.allocated_order_ids) ? resultData.allocated_order_ids : []; + const shortageIds = Array.isArray(resultData.shortage_order_ids) ? resultData.shortage_order_ids : []; + const skippedList = Array.isArray(resultData.skipped_orders) ? resultData.skipped_orders : []; + const allocatedSet = new Set(allocatedIds.map(Number)); + const shortageSet = new Set(shortageIds.map(Number)); + const skippedMap = new Map( + skippedList + .filter(item => Number(item && item.order_id) > 0) + .map(item => [ Number(item.order_id), item ]) + ); + + if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + const operatorInfo = operator || {}; + const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null; + const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system'; + const now = new Date(); + + const logRows = orderIds.map(orderId => { + const oid = Number(orderId); + const allocated = allocatedSet.has(oid); + const shortage = shortageSet.has(oid); + const skippedItem = skippedMap.get(oid) || null; + const skippedReason = skippedItem ? String(skippedItem.skipped_reason || '').trim() : ''; + const skippedMessage = skippedReason === 'intercepted' + ? '储位分配跳过:订单已拦截' + : (skippedReason ? `储位分配跳过:${skippedReason}` : ''); + const operationCode = allocated + ? 'ORDER_STORAGE_ALLOCATE_SUCCESS' + : shortage + ? 'ORDER_STORAGE_ALLOCATE_FAILED' + : skippedItem + ? 'ORDER_STORAGE_ALLOCATE_FAILED' + : 'ORDER_STORAGE_ALLOCATE_SUCCESS'; + const msg = allocated + ? '储位分配成功' + : shortage + ? '储位分配失败:库存不足' + : skippedMessage || '储位分配完成'; + return { + business_type: 'order', + business_id: String(oid), + operation_code: operationCode, + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: msg, + created_at: now, + }; + }).filter(row => Number(row.business_id) > 0); + + if (logRows.length > 0) { + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入成功操作日志失败,不影响业务', logErr); + } + console.log('[PendingOrderService.allocateStorage] 后台储位分配处理成功', { + request_id: requestId, + normalizedData, + result, + }); + } catch (error) { + await this.setAllocateStorageTaskProgress(requestId, { + status: 'failed', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + error: error && error.message ? error.message : String(error), + }); + + // 写操作日志(不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const warehouseId = this.getWarehouseId(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + const orderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids ? [ normalizedData.order_ids ] : []); + + if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + const operatorInfo = operator || {}; + const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null; + const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system'; + const errorMsg = error && error.message ? error.message : String(error); + const now = new Date(); + + const logRows = orderIds.map(orderId => { + const oid = Number(orderId); + return { + business_type: 'order', + business_id: String(oid), + operation_code: 'ORDER_STORAGE_ALLOCATE_FAILED', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: `储位分配失败:${errorMsg}`, + created_at: now, + }; + }).filter(row => Number(row.business_id) > 0); + + if (logRows.length > 0) { + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入失败操作日志失败,不影响业务', logErr); + } + console.log('[PendingOrderService.allocateStorage] 后台储位分配处理异常', { + request_id: requestId, + normalizedData, + error_message: error?.message, + error_stack: error?.stack, + }); + } + }); + + return this.success('ok', { + request_id: requestId, + warehouse_id: warehouseId, + message: '请求已提交,后端处理中', + }); + } + + /** + * 查询待处理订单储位分配任务进度。 + * + * @param {Object} data 请求体。 + * @param {string} data.request_id 请求ID(下划线写法)。 + * @param {string} data.requestId 请求ID(驼峰写法)。 + * @return {Promise} 统一响应,包含任务状态或结果。 + */ + async allocateStorageProgress(data = {}) { + const requestId = this.normalizeAllocateStorageRequestId(data); + if (!requestId) { + return this.fail('request_id 参数不能为空', {}, 400); + } + + const cachedProgress = await this.getAllocateStorageTaskProgress(requestId); + if (!cachedProgress) { + return this.success('ok', { + request_id: requestId, + status: 'not_found', + progress: ALLOCATE_STORAGE_PROGRESS_MAP.not_found, + total_count: 0, + processed_count: 0, + }); + } + + const normalizedStatus = String(cachedProgress.status || 'unknown').trim() || 'unknown'; + const normalizedCounts = this.normalizeAllocateStorageTaskCounts(cachedProgress, normalizedStatus); + const normalizedProgress = this.normalizeAllocateStorageTaskProgress( + cachedProgress.progress, + normalizedStatus, + normalizedCounts.total_count, + normalizedCounts.processed_count + ); + + return this.success('ok', { + request_id: requestId, + ...cachedProgress, + status: normalizedStatus, + progress: normalizedProgress, + total_count: normalizedCounts.total_count, + processed_count: normalizedCounts.processed_count, + }); + } + + /** + * 规范任务进度值,兼容历史缓存中缺失 progress 字段的场景。 + * + * @param {number|string|null|undefined} progress 原始进度值。 + * @param {string} status 任务状态。 + * @param {number} totalCount 总任务数。 + * @param {number} processedCount 已处理任务数。 + * @return {number} 归一化后的进度百分比(0-100)。 + */ + normalizeAllocateStorageTaskProgress(progress, status = 'unknown', totalCount = 0, processedCount = 0) { + const parsed = Number(progress); + if (Number.isFinite(parsed)) { + return Math.min(100, Math.max(0, Math.round(parsed))); + } + + if (String(status || 'unknown').trim() === 'success') { + return 100; + } + + const normalizedTotalCount = this.normalizeAllocateStorageTaskCount(totalCount, 0); + const normalizedProcessedCount = this.normalizeAllocateStorageTaskCount(processedCount, 0); + if (normalizedTotalCount > 0) { + return Math.round(Math.min(normalizedTotalCount, normalizedProcessedCount) / normalizedTotalCount * 100); + } + + const normalizedStatus = String(status || 'unknown').trim() || 'unknown'; + if (Object.prototype.hasOwnProperty.call(ALLOCATE_STORAGE_PROGRESS_MAP, normalizedStatus)) { + return ALLOCATE_STORAGE_PROGRESS_MAP[normalizedStatus]; + } + + return ALLOCATE_STORAGE_PROGRESS_MAP.unknown; + } + + /** + * 规范任务计数字段。 + * + * @param {number|string|null|undefined} value 原始计数值。 + * @param {number} defaultValue 默认值。 + * @return {number} 归一化后的非负整数。 + */ + normalizeAllocateStorageTaskCount(value, defaultValue = 0) { + const parsed = Number(value); + if (!Number.isFinite(parsed)) { + return Math.max(0, Math.round(Number(defaultValue) || 0)); + } + + return Math.max(0, Math.round(parsed)); + } + + /** + * 规范任务总量与处理量,兼容历史缓存与别名字段。 + * + * @param {Object} payload 原始缓存载荷。 + * @param {string} status 任务状态。 + * @return {{ total_count: number, processed_count: number }} 归一化后的计数信息。 + */ + normalizeAllocateStorageTaskCounts(payload = {}, status = 'unknown') { + const safePayload = this.isPlainObject(payload) ? payload : {}; + const totalCount = this.normalizeAllocateStorageTaskCount( + safePayload.total_count + ?? safePayload.totalCount + ?? safePayload.total, + 0 + ); + let processedCount = this.normalizeAllocateStorageTaskCount( + safePayload.processed_count + ?? safePayload.processedCount + ?? safePayload.processed, + 0 + ); + + if (totalCount > 0) { + processedCount = Math.min(totalCount, processedCount); + } else { + processedCount = 0; + } + + if (String(status || 'unknown').trim() === 'success' && totalCount > 0) { + processedCount = totalCount; + } + + return { + total_count: totalCount, + processed_count: processedCount, + }; + } + + /** + * 规范待处理订单储位分配请求ID。 + * + * @param {Object} data 请求体。 + * @param {string} data.request_id 请求ID(下划线写法)。 + * @param {string} data.requestId 请求ID(驼峰写法)。 + * @return {string} 归一化后的请求ID。 + */ + normalizeAllocateStorageRequestId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.request_id || normalizedData.requestId || '').trim(); + } + + /** + * 获取待处理订单储位分配任务缓存键。 + * + * @param {string} requestId 请求ID。 + * @return {string} 缓存键。 + */ + getAllocateStorageTaskCacheKey(requestId = '') { + const normalizedRequestId = String(requestId || '').trim(); + if (!normalizedRequestId) { + return ''; + } + + return `${ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX}${normalizedRequestId}`; + } + + /** + * 写入待处理订单储位分配任务进度。 + * + * @param {string} requestId 请求ID。 + * @param {Object} payload 任务状态与结果。 + * @return {Promise} 无返回值。 + */ + async setAllocateStorageTaskProgress(requestId = '', payload = {}) { + const cacheKey = this.getAllocateStorageTaskCacheKey(requestId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizedStatus = String(safePayload.status || 'unknown').trim() || 'unknown'; + const normalizedCounts = this.normalizeAllocateStorageTaskCounts(safePayload, normalizedStatus); + const normalizedProgress = this.normalizeAllocateStorageTaskProgress( + safePayload.progress, + normalizedStatus, + normalizedCounts.total_count, + normalizedCounts.processed_count + ); + const progressPayload = { + ...safePayload, + status: normalizedStatus, + progress: normalizedProgress, + total_count: normalizedCounts.total_count, + processed_count: normalizedCounts.processed_count, + request_id: String(requestId || '').trim(), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateStorage] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取待处理订单储位分配任务进度。 + * + * @param {string} requestId 请求ID。 + * @return {Promise} 任务缓存结果。 + */ + async getAllocateStorageTaskProgress(requestId = '') { + const cacheKey = this.getAllocateStorageTaskCacheKey(requestId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateStorage] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + // ========== allocateExpressCode 异步任务进度缓存工具方法 ========== + + /** + * 获取快递分配任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getAllocateExpressTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 规范快递分配任务ID。 + * + * @param {Object} data 请求体。 + * @return {string} 归一化后的任务ID。 + */ + normalizeAllocateExpressTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 写入快递分配任务进度。 + * + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态与结果。 + * @return {Promise} 无返回值。 + */ + async setAllocateExpressTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getAllocateExpressTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'unknown').trim(), + progress: Number(safePayload.progress || 0), + message: String(safePayload.message || ''), + result: safePayload.result || null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取快递分配任务进度。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存结果。 + */ + async getAllocateExpressTaskProgress(taskId = '') { + const cacheKey = this.getAllocateExpressTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + // ========== syncOrderIds 异步任务进度缓存工具方法 ========== + + /** + * 获取订单同步任务缓存键。 + * + * @param {string} requestId 请求ID。 + * @return {string} 缓存键。 + */ + getSyncOrderIdsTaskCacheKey(requestId = '') { + const normalizedRequestId = String(requestId || '').trim(); + if (!normalizedRequestId) { + return ''; + } + + return `${SYNC_ORDER_IDS_TASK_CACHE_KEY_PREFIX}${normalizedRequestId}`; + } + + /** + * 规范订单同步任务请求ID。 + * + * @param {Object} data 请求体。 + * @return {string} 归一化后的请求ID。 + */ + normalizeSyncOrderIdsRequestId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.request_id || normalizedData.requestId || '').trim(); + } + + /** + * 写入订单同步任务进度。 + * + * @param {string} requestId 请求ID。 + * @param {Object} payload 任务状态与结果。 + * @return {Promise} + */ + async setSyncOrderIdsTaskProgress(requestId = '', payload = {}) { + const cacheKey = this.getSyncOrderIdsTaskCacheKey(requestId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + ...safePayload, + request_id: String(requestId || '').trim(), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, SYNC_ORDER_IDS_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[pendingOrder.syncOrderIds] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取订单同步任务进度。 + * + * @param {string} requestId 请求ID。 + * @return {Promise} 任务缓存结果。 + */ + async getSyncOrderIdsTaskProgress(requestId = '') { + const cacheKey = this.getSyncOrderIdsTaskCacheKey(requestId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[pendingOrder.syncOrderIds] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + // ========== syncOrderIds 异步任务进度缓存工具方法结束 ========== + + /** + * 将待处理订单批量取消储位分配。 + * + * 该入口仅接受订单 ID 相关入参,不再接受 allow_storage_location 相关字段或 warehouse_id / warehouseId; + * 仓库上下文统一取当前登录用户的 store_id。 + * + * @param {Object} data 请求体。 + * @return {Promise} 统一 success 包装的储位取消分配结果。 + */ + async cancelAllocateStorage(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const forbiddenWarehouseKeys = [ 'warehouse_id', 'warehouseId' ].filter(key => Object.prototype.hasOwnProperty.call(requestData, key)); + + if (forbiddenWarehouseKeys.length > 0) { + console.log('[PendingOrderService.cancelAllocateStorage] 检测到禁止传入的仓库字段', { + forbiddenWarehouseKeys, + }); + throw new Error('待处理订单储位取消分配接口不再接受 warehouse_id / warehouseId,请使用当前用户仓库上下文'); + } + + const normalizedData = { + order_ids: requestData.order_ids + ?? requestData.orderIds + ?? requestData.ids + ?? requestData.order_id + ?? requestData.orderId + ?? requestData.id, + }; + + console.log('[PendingOrderService.cancelAllocateStorage] 归一化入参', normalizedData); + + // 前置校验:拣货完成的订单不允许取消分配储位 + const rawCancelOrderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []); + const cancelOrderIds = [ ...new Set(rawCancelOrderIds.map(id => Number(id)).filter(id => Number.isFinite(id) && id > 0)) ]; + + if (cancelOrderIds.length > 0) { + const model = await this.getOrderModel('order', this.getWarehouseId()); + const where = this.buildOrderWhere(cancelOrderIds, this.getWarehouseId()); + const orders = await model.findAll({ + where, + attributes: [ 'id', 'pick_status' ], + raw: true, + }); + + const pickedOrderIds = (Array.isArray(orders) ? orders : []) + .filter(o => o.pick_status === 'fin') + .map(o => Number(o.id)); + + if (pickedOrderIds.length > 0) { + throw new Error( + `以下订单已拣货完成,不允许取消分配储位:${pickedOrderIds.join(', ')}` + ); + } + } + + try { + console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 前', normalizedData); + const result = await this.service.systems.orderStorageAllocation.cancelAllocateStorage(normalizedData); + console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 成功', result); + + try { + if (this.ctx.model && this.ctx.model.OperationLog) { + const operator = this.getOrderLogOperator() || {}; + const operatorId = operator.id != null ? String(operator.id) : null; + const operatorName = operator.name ? String(operator.name) : 'system'; + const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null; + const resultData = result && result.data ? result.data : {}; + const cancellableOrderIds = Array.isArray(resultData.cancellable_order_ids) ? resultData.cancellable_order_ids : []; + const now = new Date(); + const logRows = []; + + for (const orderId of cancellableOrderIds) { + const normalizedOrderId = Number(orderId); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + continue; + } + + logRows.push({ + business_type: 'order', + business_id: String(normalizedOrderId), + operation_code: 'ORDER_STORAGE_UNALLOCATE_SUCCESS', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId, + platform_code: 'SYSTEM', + message: '取消储位分配成功', + created_at: now, + }); + } + + if (logRows.length > 0) { + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logError) { + this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配日志失败,不影响主流程', logError); + } + + return this.success('ok', result); + } catch (error) { + try { + if (this.ctx.model && this.ctx.model.OperationLog) { + const rawOrderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []); + const orderIds = [ ...new Set(rawOrderIds.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)) ]; + + if (orderIds.length > 0) { + const operator = this.getOrderLogOperator() || {}; + const operatorId = operator.id != null ? String(operator.id) : null; + const operatorName = operator.name ? String(operator.name) : 'system'; + const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null; + const errorMessage = error && error.message ? error.message : String(error); + const now = new Date(); + const logRows = orderIds.map(orderId => ({ + business_type: 'order', + business_id: String(orderId), + operation_code: 'ORDER_STORAGE_UNALLOCATE_FAILED', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId, + platform_code: 'SYSTEM', + message: `取消储位分配失败:${errorMessage}`, + created_at: now, + })); + + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logError) { + this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配失败日志失败,不影响主流程', logError); + } + + console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 异常', { + normalizedData, + error, + }); + throw error; + } + } + + /** + * 自动同步回传前置过滤:静默剔除 SN(序列号管理)订单。 + * + * auto_sync_back 由运单分配、手工运单等链路自动触发,此时 SN 订单尚未复核、 + * SN 明细也尚未写入,回传链路会拦截并置为待处理异常(sn_batch_forbidden), + * 因此自动触发场景直接跳过,不改变订单状态、不写 sync_message,仅在日志中记录被跳过的订单。 + * SN 订单的自动回传改由复核完成(order.recheckOrder.confirmRecheck)后触发。 + * + * @param {Object} params 过滤参数。 + * @param {Array|number|string} [params.orderIds] 待同步订单ID集合。 + * @param {number|string} [params.warehouseId] 仓库ID(后台链路 ctx.user 为空时必须显式传入)。 + * @param {string} [params.source] 触发来源(仅用于日志定位)。 + * @return {Promise<{ orderIds: number[], skippedSnOrderIds: number[] }>} 过滤后的订单ID与被跳过的SN订单ID。 + */ + async filterAutoSyncSnOrderIds(params = {}) { + const { ctx } = this; + const logger = ctx.logger && typeof ctx.logger === 'object' + ? ctx.logger + : { info() {}, warn() {} }; + const requestData = this.isPlainObject(params) ? params : {}; + const orderIds = this.normalizeOrderIds({ ids: requestData.orderIds }); + if (orderIds.length === 0) { + return { orderIds: [], skippedSnOrderIds: [] }; + } + + const source = String(requestData.source || '').trim() || 'unknown'; + const warehouseId = Number(requestData.warehouseId || this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { orderIds, skippedSnOrderIds: [] }; + } + + try { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + const orderModel = factory && typeof factory.getCurrentModel === 'function' + ? await factory.getCurrentModel(warehouseId) + : null; + if (!orderModel || typeof orderModel.findAll !== 'function') { + return { orderIds, skippedSnOrderIds: [] }; + } + + const { Op } = this.app.Sequelize; + const rows = await orderModel.findAll({ + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'has_sn_item' ], + raw: true, + }); + + const snOrderIdSet = new Set((Array.isArray(rows) ? rows : []) + .filter(row => String(row && row.has_sn_item || '').trim().toUpperCase() === 'Y') + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)); + + if (snOrderIdSet.size === 0) { + return { orderIds, skippedSnOrderIds: [] }; + } + + const skippedSnOrderIds = orderIds.filter(orderId => snOrderIdSet.has(orderId)); + const keptOrderIds = orderIds.filter(orderId => !snOrderIdSet.has(orderId)); + + logger.info('[auto_sync_back] 静默跳过SN订单', { + warehouseId, + source, + skippedSnOrderIds, + keptOrderIds, + }); + + return { orderIds: keptOrderIds, skippedSnOrderIds }; + } catch (error) { + logger.warn('[auto_sync_back] SN订单过滤失败,按原订单集合继续', { + warehouseId, + source, + orderCount: orderIds.length, + error: error && error.message ? error.message : `${error}`, + }); + return { orderIds, skippedSnOrderIds: [] }; + } + } + + /** + * 同步待处理订单(异步模式)。 + * + * 立即生成 request_id 并返回,后台通过 setImmediate 异步执行实际的订单同步流程。 + * 调用方可通过 syncOrderIdsProgress 接口轮询任务进度与最终结果。 + * + * 后台处理流程: + * ① 事务内查询订单 + 校验(SN、快递状态)+ 更新 sync_status='padding' + commit + * ② 按 create_channel 分组并行派发(QM / MANUAL / API) + * ③ 单订单失败静默写入 error 状态 + 异常标记,不影响整批结果 + * ④ 写入操作日志 + 更新最终进度 + * + * @param {Object} data 请求体。 + * @param {Array|string|number} data.order_ids 订单ID(支持数组、逗号字符串、单个ID,兼容 orderIds/ids 等多种别名)。 + * @return {Promise} 统一 success 包装,含 request_id。 + */ + async syncOrderIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const normalizedData = { + order_ids: requestData.order_ids + ?? requestData.orderIds + ?? requestData.ids + ?? requestData.order_id + ?? requestData.orderId + ?? requestData.id, + }; + + // 快照 ctx 数据(setImmediate 回调中 ctx 可能已失效) + // 显式传入的仓库ID优先:Qimen 创建订单等无登录用户上下文的异步链路 ctx.user 为空, + // 调用方必须显式传 warehouseId,否则回传任务会因"缺少仓库上下文"静默失败 + const explicitWarehouseId = Number(requestData.warehouse_id ?? requestData.warehouseId ?? 0); + const warehouseId = Number.isFinite(explicitWarehouseId) && explicitWarehouseId > 0 + ? explicitWarehouseId + : this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const requestId = `sync_order_${warehouseId ?? 'unknown'}_${timestamp}_${randomToken}`; + + // 初始化进度:submitted + await this.setSyncOrderIdsTaskProgress(requestId, { + status: 'submitted', + total_count: 0, + processed_count: 0, + progress: 0, + warehouse_id: warehouseId, + order_ids: normalizedData.order_ids, + }); + + this.ctx.logger.info('[PendingOrderService.syncOrderIds] 任务已提交', { + request_id: requestId, + warehouseId, + orderCount: Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids.length + : (normalizedData.order_ids ? 1 : 0), + }); + + // 后台异步执行 + setImmediate(async () => { + try { + await this.setSyncOrderIdsTaskProgress(requestId, { + status: 'running', + total_count: 0, + processed_count: 0, + progress: 0, + warehouse_id: warehouseId, + }); + + const result = await this.service.systems.orderStorageAllocation.syncOrderIds({ + ...normalizedData, + warehouse_id: warehouseId, + request_id: requestId, + }); + + // 最终进度:success(从结果中取真实数量) + const resultData = result && result.data ? result.data : {}; + const finalTotal = Number(resultData.pending_count || 0); + const finalProcessed = finalTotal; + const finalProgress = 100; + + await this.setSyncOrderIdsTaskProgress(requestId, { + status: 'success', + total_count: finalTotal, + processed_count: finalProcessed, + progress: finalProgress, + warehouse_id: warehouseId, + result, + }); + + // 静默写操作日志(不影响主流程) + try { + const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function') { + const rawOrderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids ? [ normalizedData.order_ids ] : []); + + const resultData = result && result.data ? result.data : {}; + const pendingSet = new Set((resultData.pending_order_ids || []).map(Number)); + const skippedMap = new Map(); + const failedMap = new Map(); + + for (const item of (resultData.skipped_orders || [])) { + skippedMap.set(Number(item.order_id), item.skipped_reason || 'unknown'); + } + for (const item of (resultData.failed_orders || [])) { + failedMap.set(Number(item.order_id), item.failed_reason || 'unknown'); + } + + const skipReasonMap = { not_found: '订单不存在', already_synced: '已同步' }; + const failReasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN明细未齐套或未复核' }; + const dispatchChannels = (resultData.dispatch_results || []) + .map(r => r.create_channel).filter(Boolean).join('/') || 'unknown'; + + const logPayloads = rawOrderIds.map(orderId => { + const oid = Number(orderId); + let msg; + + if (pendingSet.has(oid)) { + msg = `同步到${dispatchChannels}渠道`; + } else if (failedMap.has(oid)) { + const reason = failedMap.get(oid); + msg = `同步跳过:${failReasonMap[reason] || reason}`; + } else if (skippedMap.has(oid)) { + const reason = skippedMap.get(oid); + msg = `同步跳过:${skipReasonMap[reason] || reason}`; + } else { + msg = '同步跳过'; + } + + return { + businessType: 'order', + businessId: String(oid), + operationCode: 'ORDER_SYNC', + operator, + extras: { + message: msg, + warehouseId: logWarehouseId, + externalLogType: 'NONE', + }, + }; + }).filter(item => Number(item.businessId) > 0); + + if (logPayloads.length > 0) { + await opLogService.createOperationLogs(logPayloads); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入操作日志失败,不影响主流程', { + request_id: requestId, + error: logErr && logErr.message, + }); + } + + this.ctx.logger.info('[PendingOrderService.syncOrderIds] 后台同步任务完成', { + request_id: requestId, + status: result && result.code, + message: result && result.message, + }); + } catch (error) { + // 整体失败也静默写入进度 + try { + const cached = await this.getSyncOrderIdsTaskProgress(requestId); + const cachedTotal = cached && Number(cached.total_count || 0); + await this.setSyncOrderIdsTaskProgress(requestId, { + status: 'failed', + total_count: cachedTotal || 0, + processed_count: cached && Number(cached.processed_count || 0), + progress: cached && Number(cached.progress || 0), + warehouse_id: warehouseId, + error: error && error.message ? error.message : String(error), + }); + } catch (cacheErr) { + this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入失败进度缓存失败', { + request_id: requestId, + error: cacheErr && cacheErr.message, + }); + } + + // 写操作日志:崩溃场景下 service 层可能不可用,直接用 model 直写 + try { + const rawOrderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids ? [ normalizedData.order_ids ] : []); + const errorMsg = error && error.message ? String(error.message) : String(error); + + if (rawOrderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + const operatorId = operator.id; + const operatorName = operator.name || 'system'; + const now = new Date(); + + const logRows = rawOrderIds.map(orderId => ({ + business_type: 'order', + business_id: String(orderId), + operation_code: 'ORDER_SYNC_FAILED', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: `订单同步失败:${errorMsg}`, + created_at: now, + })).filter(row => Number(row.business_id) > 0); + + if (logRows.length > 0) { + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入失败操作日志失败,不影响主流程', { + request_id: requestId, + error: logErr && logErr.message, + }); + } + + this.ctx.logger.error('[PendingOrderService.syncOrderIds] 后台同步任务异常', { + request_id: requestId, + warehouseId, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + } + }); + + // 立即返回 request_id + return this.success('同步任务已提交,可通过 syncOrderIdsProgress 查询进度', { + request_id: requestId, + warehouse_id: warehouseId, + message: '同步任务已提交,后台处理中', + }); + } + + /** + * 查询订单同步任务进度。 + * + * @param {Object} data 请求体。 + * @param {string} data.request_id 请求ID(下划线写法)。 + * @param {string} data.requestId 请求ID(驼峰写法)。 + * @return {Promise} 任务进度响应,含 status / progress / total_count / processed_count / result。 + */ + async syncOrderIdsProgress(data = {}) { + const requestId = this.normalizeSyncOrderIdsRequestId(data); + if (!requestId) { + return this.fail('request_id 参数不能为空', {}, 400); + } + + const cachedProgress = await this.getSyncOrderIdsTaskProgress(requestId); + if (!cachedProgress) { + return this.success('ok', { + request_id: requestId, + status: 'not_found', + progress: SYNC_ORDER_IDS_PROGRESS_MAP.not_found, + total_count: 0, + processed_count: 0, + }); + } + + const normalizedStatus = String(cachedProgress.status || 'unknown').trim() || 'unknown'; + + return this.success('ok', { + request_id: requestId, + status: normalizedStatus, + progress: Number.isFinite(Number(cachedProgress.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(cachedProgress.progress)))) + : (SYNC_ORDER_IDS_PROGRESS_MAP[normalizedStatus] ?? SYNC_ORDER_IDS_PROGRESS_MAP.unknown), + total_count: Number(cachedProgress.total_count || 0), + processed_count: Number(cachedProgress.processed_count || 0), + warehouse_id: Number(cachedProgress.warehouse_id || 0), + result: cachedProgress.result || null, + error: cachedProgress.error || '', + update_time: cachedProgress.update_time || null, + }); + } + + /** + * 批量分配待处理订单的快递号,并复用现有运单创建核心链路。 + * + * @param {Object} data 请求体。 + * @param {Array} data.ids 订单 ID 数组(推荐)。 + * @param {Array} [data.orders] 订单对象数组(兼容旧格式,新调用方请使用 ids)。 + * @return {Promise} 统一 success 包装,立即返回 task_id。 + */ + async allocateExpressCode(data) { + const { ids, orders: legacyOrders } = data || {}; + + // 新格式:ids,直接转为管线所需格式(business_key 固定为 1) + let orders; + if (Array.isArray(ids) && ids.length > 0) { + orders = ids.map(id => ({ order_id: Number(id), business_key: 1 })); + } else if (Array.isArray(legacyOrders)) { + // 兼容旧格式:orders 对象数组 + orders = legacyOrders; + } else { + throw new Error('分配快递号接口需要传入 ids(订单ID数组)或 orders(订单对象数组)'); + } + + const { service } = this; + + // 生成任务ID,立即返回给前端 + const taskId = `exp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.submitted, + message: '分配快递任务已提交', + result: null, + error: '', + }; + await this.setAllocateExpressTaskProgress(taskId, taskPayload); + + // 捕获 warehouseId 供 setImmediate 异步回调使用, + // 避免 Qimen 等链路中 withPatchedCtxUser 补丁已撤销导致 getCurrentWarehouseId() 返回 0。 + const capturedWarehouseId = Number( + this.ctx && this.ctx.user && this.ctx.user.store_id || 0 + ); + + // 后台异步执行 + setImmediate(async () => { + try { + await this.setAllocateExpressTaskProgress(taskId, { + status: 'running', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.running, + message: '快递分配处理中', + }); + + const result = await service.systems.express.createWaybillCodePipeline(orders, { + awaitTasks: true, + warehouseId: capturedWarehouseId, + }); + + // 需要回 OMS 取号的订单会被本地流水线整体跳过(不分配本地快递), + // 这里改由 OMS 取号并回写运单号。 + // 与原设计保持一致:取号结果(含失败)不影响任务状态——失败已通过订单异常与 + // 操作日志体现,任务只表示「分配流程已执行完毕」。 + const skippedOmsOrderIds = Array.isArray(result && result.skipped_need_oms_waybill_order_ids) + ? result.skipped_need_oms_waybill_order_ids.map(orderId => Number(orderId)) + : []; + let omsResult = null; + let omsError = ''; + if (skippedOmsOrderIds.length > 0) { + try { + omsResult = await service.systems.express.requestOmsWaybills( + orders.filter(order => skippedOmsOrderIds.includes(Number(order.order_id))), + { warehouseId: capturedWarehouseId } + ); + } catch (error) { + omsError = error && error.message ? String(error.message) : String(error); + this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 回 OMS 取号失败,已按订单异常记录', { + orderIds: skippedOmsOrderIds, + error: omsError, + }); + } + } + + await this.setAllocateExpressTaskProgress(taskId, { + status: 'success', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.success, + message: '快递分配完成', + result: { + ...(result || {}), + ...(omsResult ? { oms: omsResult } : {}), + ...(omsError ? { oms_error: omsError } : {}), + }, + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : String(error); + + // 异常标记和失败日志仍在 asyncTask 内部处理,这里仅记录任务状态 + await this.setAllocateExpressTaskProgress(taskId, { + status: 'failed', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.failed, + message: '快递分配失败', + error: errorMessage, + }); + + // 回滚无运单号订单的 post_status + try { + const orderIds = [ ...new Set( + orders + .map(order => Number(order && (order.order_id || order.id))) + .filter(orderId => Number.isFinite(orderId) && orderId > 0) + ) ]; + + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function' + ? await orderDeliveryFactory.getCurrentModel() + : null; + + if (orderDeliveryModel && orderIds.length > 0) { + const currentOrders = await orderDeliveryModel.findAll({ + // eslint-disable-next-line array-bracket-spacing + where: { id: { [this.app.Sequelize.Op.in]: orderIds } }, + attributes: [ 'id', 'express_code', 'post_status' ], + raw: true, + }); + + const noWaybillOrderIds = (Array.isArray(currentOrders) ? currentOrders : []) + .filter(o => !String(o.express_code || '').trim()) + .map(o => Number(o.id)) + .filter(id => id > 0); + + if (noWaybillOrderIds.length > 0) { + await orderDeliveryModel.update( + { post_status: 'none', updated_at: new Date() }, + // eslint-disable-next-line array-bracket-spacing + { where: { id: { [this.app.Sequelize.Op.in]: noWaybillOrderIds } } } + ); + this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 回滚 post_status 为 none', { + orderIds: noWaybillOrderIds, + }); + } + } + } catch (markError) { + this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 回写订单状态失败,不影响主流程', markError); + } + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询快递分配任务进度。 + * + * @param {Object} data 请求体。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 统一 success 包装。 + */ + async allocateExpressCodeTaskProgress(data = {}) { + const taskId = this.normalizeAllocateExpressTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found, + message: '任务不存在', + result: null, + error: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getAllocateExpressTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found, + message: '任务不存在', + result: null, + error: '', + update_time: Date.now(), + }); + } + + return this.success('ok', { + ...cachedTask, + update_time: cachedTask.update_time || Date.now(), + }); + } + + /** + * 将待处理订单批量标记为待出库。 + * @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); + + 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, + step: PENDING_OUTBOUND_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, + 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), + }; + } + + /** + * 将待处理订单取消,并关闭到已取消状态。 + * 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。 + * 已同步订单取消时转为拦截处理:写入 intercept_status='requested' 并同步写入拦截时间 intercept_time。 + * + * 取消、波次清理、储位释放与创建锁释放在同一事务内完成: + * 任一环节失败整体回滚,避免"已取消但库存锁定未释放"的中间态。 + * + * @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 transaction = await this.ctx.model.transaction(); + let normalizedOrders = []; + let firstOrder = null; + let affectedRows = 0; + + try { + // 锁定订单行后读取最新状态,与储位分配事务串行化,避免读到过期快照 + const existingOrders = await model.findAll({ + where, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + if (!Array.isArray(existingOrders) || existingOrders.length === 0) { + await transaction.rollback(); + 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 guardInfoMap = await resolveInterceptRequestGuardInfoMap(this.ctx, { + orderRows: existingOrders, + warehouseId, + transaction, + }); + + // 已同步订单不允许取消,转为拦截处理 + const syncedOrders = existingOrders.filter( + order => String(order.sync_status || '').trim() === 'fin' + ); + if (syncedOrders.length > 0) { + // 已复核/已称重订单不允许写入拦截请求状态,直接拒绝取消 + const blockedSyncedOrders = syncedOrders.filter(order => { + const guardInfo = guardInfoMap.get(Number(order.id)) || {}; + return getInterceptRequestBlockReason({ + waveType: guardInfo.waveType, + inspectionStatus: String(order.inspection_status || '').trim(), + weighingWeight: guardInfo.weighingWeight, + }) !== ''; + }); + if (blockedSyncedOrders.length > 0) { + await transaction.rollback(); + const blockedCodes = blockedSyncedOrders + .map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim()) + .filter(Boolean) + .join(', '); + throw new Error(`订单已完成复核/称重,无法取消:${blockedCodes}`); + } + const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter( + id => Number.isInteger(id) && id > 0 + ); + if (syncedOrderIds.length > 0) { + const syncNow = new Date(); + // 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值) + const fillNoticeOrderIds = pickNoticeTimeOrderIds(syncedOrders); + await model.update( + { + intercept_status: 'requested', + updated_at: syncNow, + }, + { + where: { + id: syncedOrderIds, + }, + transaction, + } + ); + if (fillNoticeOrderIds.length > 0) { + await model.update( + { intercept_time: syncNow }, + { where: { id: fillNoticeOrderIds }, transaction } + ); + } + // 同步更新运单表拦截标记 + try { + const { Op: cancelOp } = this.app.Sequelize; + await this.ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [cancelOp.in]: syncedOrderIds }, warehouse_id: warehouseId }, transaction } + ); + } catch (expressErr) { + this.ctx.logger.warn( + `[PendingOrderService.cancelOrder] 更新运单拦截标记失败, count=${syncedOrderIds.length}, error=${expressErr.message}` + ); + } + this.ctx.logger.info( + `[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}` + ); + } + + // 拦截标记已写入,提交后抛出业务错误(调用方按"已转拦截"处理) + await transaction.commit(); + + // 创建售后工单 + 通知快递群(失败不影响主流程,与 batchIntercept 口径一致) + try { + const op = this.getOrderLogOperator(); + await this.ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: syncedOrderIds, + warehouseId, + creatorLabel: (op && op.name) || '系统', + reason: '订单已同步,不可取消,转为拦截处理', + }); + } catch (workOrderErr) { + this.ctx.logger.warn( + `[PendingOrderService.cancelOrder] 转拦截创建工单/通知失败, count=${syncedOrderIds.length}, error=${workOrderErr.message}` + ); + } + + // 写入拦截操作日志(不影响主流程) + try { + const operator = this.getOrderLogOperator() || {}; + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + if (syncedOrderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + const operatorId = operator.id != null ? String(operator.id) : null; + const operatorName = operator.name ? String(operator.name) : 'system'; + const logNow = new Date(); + await this.ctx.model.OperationLog.bulkCreate( + syncedOrderIds.map(orderId => ({ + business_type: 'order', + business_id: String(orderId), + operation_code: 'ORDER_INTERCEPT_REQUEST', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: '订单已同步,不可取消,转为拦截处理', + created_at: logNow, + })) + ); + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.cancelOrder] 写入拦截操作日志失败,不影响业务', logErr); + } + + const syncedCodes = syncedOrders + .map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim()) + .filter(Boolean) + .join(', '); + throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`); + } + + const now = new Date(); + const updateValues = { + status: PENDING_CANCEL_STATUS, + step: PENDING_CANCEL_STEP, + outbound_status: PENDING_OUTBOUND_STATUS, + updated_at: now, + }; + + const updateResult = await model.update(updateValues, { + where, + transaction, + }); + + affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0); + if (ordersWithWave.length > 0) { + const { Op } = this.app.Sequelize; + const WaveBatch = this.ctx.model.WaveBatch; + + const waveOrderIds = ordersWithWave + .map(order => Number(order.id)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + + if (waveOrderIds.length > 0) { + await model.update( + { + wave_id: 0, + wave_no: '', + updated_at: now, + }, + { + where: { + id: { + [Op.in]: waveOrderIds, + }, + warehouse_id: warehouseId, + }, + transaction, + } + ); + + await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: waveOrderIds, + transaction, + }); + + // 重建受影响波次的订单索引(wave_index 重新排序) + const affectedWaveIds = [ ...new Set(ordersWithWave + .map(order => Number(order.wave_id)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + if (affectedWaveIds.length > 0) { + await this.ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: affectedWaveIds, + orderModel: model, + transaction, + }); + } + } + + if (WaveBatch) { + const waveIdCountMap = new Map(); + for (const order of ordersWithWave) { + const waveId = Number(order.wave_id); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + waveIdCountMap.set(waveId, (waveIdCountMap.get(waveId) || 0) + 1); + } + + for (const [ waveId, canceledCount ] of waveIdCountMap.entries()) { + await WaveBatch.decrement('total_orders', { + by: canceledCount, + where: { + wave_id: waveId, + warehouse_id: warehouseId, + total_orders: { + [Op.gt]: 0, + }, + }, + transaction, + }); + + const wave = await WaveBatch.findOne({ + where: { + wave_id: waveId, + warehouse_id: warehouseId, + }, + attributes: [ 'wave_id', 'total_orders', 'wave_status' ], + raw: true, + transaction, + }); + + if (!wave) { + continue; + } + + const totalOrders = Number(wave.total_orders); + const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0; + if (normalizedTotalOrders <= 0) { + await WaveBatch.update( + { + total_orders: 0, + wave_status: -1, + update_time: now, + }, + { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + }, + transaction, + } + ); + } else { + await WaveBatch.update( + { + update_time: now, + }, + { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + }, + transaction, + } + ); + } + } + } + } + + // 释放储位分配和库存锁定(复用同一事务,取消与释放原子生效) + await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: orderIds, + transaction, + }); + + // 释放创建锁(lockItemStorages 加的锁,不含 picking 锁) + await this.releaseCreationLockForCancel({ + orderIds, + warehouseId, + transaction, + }); + + const updatedOrders = await model.findAll({ + where, + transaction, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + 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('订单不存在或不属于当前仓库'); + } + + firstOrder = normalizedOrders[0]; + + await transaction.commit(); + } catch (error) { + if (!transaction.finished) { + try { + await transaction.rollback(); + } catch (rollbackError) { + this.ctx.logger.error('[PendingOrderService.cancelOrder] 事务回滚失败', rollbackError); + } + } + throw error; + } + + // 写入取消操作日志(不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + if (normalizedOrders.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + const operatorInfo = operator || {}; + const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null; + const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system'; + const now = new Date(); + + const logRows = normalizedOrders.map(order => ({ + business_type: 'order', + business_id: String(order.id), + operation_code: 'ORDER_CANCEL', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: '订单取消', + created_at: now, + })).filter(row => Number(row.business_id) > 0); + + if (logRows.length > 0) { + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.cancelOrder] 写入取消操作日志失败,不影响业务', logErr); + } + + 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; + } + + /** + * 批量修改待处理订单的平台信息。 + * + * 用 code 查找 wms_platform 表中对应的平台记录,若存在则将订单的 + * sys_platform_code 和 sys_platform_name 更新为该平台的 code 和 name; + * 若不存在则返回错误。只操作当前仓库的当前订单表,不处理其他订单表。 + * 正在分配快递(wms_order_express 存在 status=0 的取号中占位记录)的订单跳过处理, + * 不影响其余订单,跳过明细通过 skipped_order_ids 透出。 + * + * @param {Object} data 请求体。 + * @param {number[]} data.order_ids 订单ID 数组。 + * @param {string} data.code 平台编码。 + * @return {Promise} 统一 success 包装的更新结果。 + */ + async updateOrderPlatform(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const rawOrderIds = requestData.order_ids; + if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) { + throw new Error('order_ids 不能为空'); + } + + const orderIds = Array.from(new Set(rawOrderIds.map(v => { + const n = Number(v); + if (!Number.isInteger(n) || n <= 0) { + throw new Error('order_ids 仅支持正整数数组'); + } + return n; + }))); + + const code = String(requestData.code || '').trim(); + if (!code) { + throw new Error('code 不能为空'); + } + + const platformList = await this.service.systems.platform.getPlatformList(true, true); + const platform = Array.isArray(platformList) + ? platformList.find(item => String(item.code || item.platform_code || '').trim() === code) + : null; + + if (!platform) { + throw new Error(`平台编码 ${code} 不存在`); + } + + // 正在分配快递的订单(order_express 存在 status=0 占位记录)跳过处理,不影响其余订单 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + const allocatingIdSet = new Set(); + if (orderExpressModel && typeof orderExpressModel.findAll === 'function') { + const allocatingRows = await orderExpressModel.findAll({ + attributes: [ 'order_id' ], + where: { + order_id: orderIds, + warehouse_id: warehouseId, + status: 0, + }, + raw: true, + }); + for (const row of Array.isArray(allocatingRows) ? allocatingRows : []) { + const orderId = Number(row && row.order_id); + if (Number.isFinite(orderId) && orderId > 0) { + allocatingIdSet.add(orderId); + } + } + } + const skippedOrderIds = orderIds.filter(orderId => allocatingIdSet.has(orderId)); + const updatableOrderIds = orderIds.filter(orderId => !allocatingIdSet.has(orderId)); + + const model = await this.getOrderModel('order', warehouseId); + const where = { + ...this.buildOrderWhere(updatableOrderIds, warehouseId), + post_status: 'none', + }; + + const platformName = String(platform.name || '').trim(); + + if (updatableOrderIds.length === 0) { + return this.success('ok', { + updated_count: 0, + skipped_order_ids: skippedOrderIds, + sys_platform_code: platform.code, + sys_platform_name: platformName, + }); + } + + // 更新前查询候选订单,筛出平台实际发生变化的订单,用于逐单写入订单日志 + const candidateOrders = await model.findAll({ + where, + attributes: [ 'id', 'sys_platform_code', 'sys_platform_name' ], + raw: true, + }); + + const changedOrders = Array.isArray(candidateOrders) + ? candidateOrders.filter(order => String(order.sys_platform_code || '').trim() !== String(platform.code || '').trim()) + : []; + + const [ affectedRows ] = await model.update({ + sys_platform_code: platform.code, + sys_platform_name: platformName, + updated_at: new Date(), + }, { where }); + + const count = Number(affectedRows || 0); + + // 记录操作日志 + try { + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_UPDATE_PLATFORM', + operator, + extras: { + warehouseId: logWarehouseId, + orderIds, + sys_platform_code: platform.code, + sys_platform_name: platformName, + updated_count: count, + message: `批量修改订单平台:订单ID [${orderIds.join(', ')}],平台 ${platform.code}(${platformName}),共更新 ${count} 条${skippedOrderIds.length > 0 ? `,跳过取号中 ${skippedOrderIds.length} 条` : ''}`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.updateOrderPlatform] 写入操作日志失败,不影响业务', logErr); + } + + // 为实际发生平台变化的订单逐单写入订单日志(订单详情页可见) + try { + const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function' && changedOrders.length > 0) { + const logPayloads = changedOrders + .map(order => { + const orderId = Number(order.id); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + const originalName = String(order.sys_platform_name || order.sys_platform_code || '未知').trim(); + return { + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_UPDATE_PLATFORM', + operator, + extras: { + warehouseId: logWarehouseId, + message: `修改订单平台:${originalName} → ${platform.code}(${platformName})`, + externalLogType: 'NONE', + }, + }; + }) + .filter(Boolean); + + if (logPayloads.length > 0) { + await opLogService.createOperationLogs(logPayloads); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.updateOrderPlatform] 写入订单日志失败,不影响业务', logErr); + } + + return this.success('ok', { + updated_count: count, + skipped_order_ids: skippedOrderIds, + sys_platform_code: platform.code, + sys_platform_name: String(platform.name || '').trim(), + }); + } + + /** + * 批量修改待处理订单的快递信息。 + * + * 用 express_code 从当前仓库快递列表(带缓存)中查找对应项: + * - 若为自定义映射(is_system_setting=true),则 sys_logistics_code/sys_logistics_name 写系统快递 + * 的 express_code/name,logistics_code/logistics_name 写自定义编码和名称; + * - 若为系统快递(is_system_setting=false),则 sys_logistics_code/sys_logistics_name 和 + * logistics_code/logistics_name 均写系统快递的 code/name; + * - 未找到则报错。 + * 只操作当前仓库的当前订单表,不处理其他订单表。 + * 操作日志逐单写入(business_id 为订单 ID),确保订单详情页可查询; + * 未满足更新条件(post_status 不为 none)的订单写入"未生效"日志。 + * 正在分配快递(wms_order_express 存在 status=0 的取号中占位记录)的订单跳过处理, + * 不影响其余订单,跳过明细通过 skipped_order_ids 透出。 + * + * @param {Object} data 请求体。 + * @param {number[]} data.order_ids 订单ID 数组。 + * @param {string} data.express_code 快递编码(系统编码或自定义编码)。 + * @return {Promise} 统一 success 包装的更新结果。 + */ + async updateOrderExpress(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const rawOrderIds = requestData.order_ids; + if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) { + throw new Error('order_ids 不能为空'); + } + + const orderIds = Array.from(new Set(rawOrderIds.map(v => { + const n = Number(v); + if (!Number.isInteger(n) || n <= 0) { + throw new Error('order_ids 仅支持正整数数组'); + } + return n; + }))); + + const expressCode = String(requestData.express_code || '').trim(); + if (!expressCode) { + throw new Error('express_code 不能为空'); + } + + // 使用带缓存的仓库快递列表 + const expressList = await this.service.systems.express.getExpressList(); + const expressItem = Array.isArray(expressList) + ? expressList.find(item => String(item.code || item.value || '').trim() === expressCode) + : null; + + if (!expressItem) { + throw new Error(`快递编码 ${expressCode} 不存在`); + } + + let sysLogisticsCode; + let sysLogisticsName; + let logisticsCode; + let logisticsName; + + if (expressItem.is_system_setting) { + // 自定义映射:express_code 字段存储对应的系统快递编码 + sysLogisticsCode = String(expressItem.express_code || '').trim(); + // 系统快递名称从列表中查找 + const sysItem = expressList.find(item => !item.is_system_setting && String(item.code || '').trim() === sysLogisticsCode); + sysLogisticsName = sysItem ? String(sysItem.name || '').trim() : sysLogisticsCode; + logisticsCode = expressItem.code; + logisticsName = String(expressItem.alias || expressItem.name || '').trim(); + } else { + // 系统快递:logistics_code/name 与 sys 一致 + sysLogisticsCode = expressItem.code; + sysLogisticsName = String(expressItem.name || '').trim(); + logisticsCode = expressItem.code; + logisticsName = sysLogisticsName; + } + + // 正在分配快递的订单(order_express 存在 status=0 占位记录)跳过处理,不影响其余订单 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + const allocatingIdSet = new Set(); + if (orderExpressModel && typeof orderExpressModel.findAll === 'function') { + const allocatingRows = await orderExpressModel.findAll({ + attributes: [ 'order_id' ], + where: { + order_id: orderIds, + warehouse_id: warehouseId, + status: 0, + }, + raw: true, + }); + for (const row of Array.isArray(allocatingRows) ? allocatingRows : []) { + const orderId = Number(row && row.order_id); + if (Number.isFinite(orderId) && orderId > 0) { + allocatingIdSet.add(orderId); + } + } + } + const skippedOrderIds = orderIds.filter(orderId => allocatingIdSet.has(orderId)); + const updatableOrderIds = orderIds.filter(orderId => !allocatingIdSet.has(orderId)); + + const model = await this.getOrderModel('order', warehouseId); + const where = { + ...this.buildOrderWhere(updatableOrderIds, warehouseId), + post_status: 'none', + }; + + if (updatableOrderIds.length === 0) { + return this.success('ok', { + updated_count: 0, + skipped_order_ids: skippedOrderIds, + sys_logistics_code: sysLogisticsCode, + sys_logistics_name: sysLogisticsName, + logistics_code: logisticsCode, + logistics_name: logisticsName, + }); + } + + // 更新前先确定实际可修改的订单集合,用于逐单写订单维度日志 + const updatableRows = await model.findAll({ + attributes: [ 'id' ], + where, + raw: true, + }); + const updatableIdSet = new Set( + (Array.isArray(updatableRows) ? updatableRows : []) + .map(row => Number(row && row.id)) + .filter(v => Number.isFinite(v) && v > 0) + ); + + const [ affectedRows ] = await model.update({ + sys_logistics_code: sysLogisticsCode, + sys_logistics_name: sysLogisticsName, + logistics_code: logisticsCode, + logistics_name: logisticsName, + updated_at: new Date(), + }, { where }); + + const count = Number(affectedRows || 0); + + // 记录操作日志:逐单写入(business_id 为订单 ID),订单详情页可查询 + const logPayloads = updatableOrderIds.map(orderId => { + const isUpdated = updatableIdSet.has(orderId); + return { + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_UPDATE_EXPRESS', + operator, + extras: { + warehouseId: logWarehouseId, + orderIds: [ orderId ], + express_code: expressCode, + sys_logistics_code: sysLogisticsCode, + sys_logistics_name: sysLogisticsName, + logistics_code: logisticsCode, + logistics_name: logisticsName, + updated_count: isUpdated ? 1 : 0, + message: isUpdated + ? `修改订单快递:快递 ${logisticsCode}(${logisticsName}),系统快递 ${sysLogisticsCode}(${sysLogisticsName})` + : `修改订单快递未生效(订单已分配快递或状态不允许):快递 ${logisticsCode}(${logisticsName})`, + }, + beforeChanges: null, + }; + }); + + try { + if (logPayloads.length === 1) { + await this.ctx.service.systems.operationLog.createOperationLog(logPayloads[0]); + } else { + await this.ctx.service.systems.operationLog.createOperationLogs(logPayloads); + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.updateOrderExpress] 写入操作日志失败,不影响业务', logErr); + } + + return this.success('ok', { + updated_count: count, + skipped_order_ids: skippedOrderIds, + sys_logistics_code: sysLogisticsCode, + sys_logistics_name: sysLogisticsName, + logistics_code: logisticsCode, + logistics_name: logisticsName, + }); + } + + /** + * 批量修改待处理订单的收件地址信息。 + * + * 地址字段仅允许在未分配快递(post_status = 'none')时修改。 + * 支持批量操作,返回更新数量和受影响的订单 ID 列表。 + * + * @param {Object} data 请求体。 + * @param {number[]} data.ids 订单 ID 数组(必填)。 + * @param {string} [data.name] 收件人姓名。 + * @param {string} [data.mobile] 手机号。 + * @param {string} [data.tel] 电话。 + * @param {string} [data.zip_code] 邮编。 + * @param {string} [data.province] 省份。 + * @param {string} [data.city] 城市。 + * @param {string} [data.area] 区/县。 + * @param {string} [data.town] 镇/街道。 + * @param {string} [data.detail_address] 详细地址。 + * @return {Promise} 统一 success 包装的更新结果,含 updated_count 与 ids。 + */ + async updateAddress(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + // 解析订单 ID + const orderIds = this.normalizeOrderIds(requestData); + if (orderIds.length === 0) { + throw new Error('ids 不能为空'); + } + + // 收集可更新的地址字段 + const addressFields = [ + 'name', 'mobile', 'tel', 'zip_code', + 'province', 'city', 'area', 'town', 'detail_address', + ]; + const addressUpdates = {}; + for (const field of addressFields) { + const value = requestData[field]; + if (value !== undefined && value !== null && String(value).trim() !== '') { + addressUpdates[field] = String(value).trim(); + } + } + + const hasAddressUpdates = Object.keys(addressUpdates).length > 0; + if (!hasAddressUpdates) { + throw new Error('至少需要提供一个地址字段进行修改'); + } + + const model = await this.getOrderModel('order', warehouseId); + const baseWhere = this.buildOrderWhere(orderIds, warehouseId); + const now = new Date(); + + let addressUpdatedCount = 0; + + // 地址字段更新(受 post_status='none' 限制) + if (hasAddressUpdates) { + addressUpdates.updated_at = now; + const addressWhere = { ...baseWhere, post_status: 'none' }; + const [ rows ] = await model.update(addressUpdates, { where: addressWhere }); + addressUpdatedCount = Number(rows || 0); + } + + // 记录操作日志 + try { + const updatedFieldNames = Object.keys(addressUpdates).filter(k => k !== 'updated_at'); + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_UPDATE_ADDRESS', + operator, + extras: { + warehouseId: logWarehouseId, + orderIds, + updated_fields: updatedFieldNames, + updated_count: addressUpdatedCount, + address_updated_count: addressUpdatedCount, + message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],地址更新 ${addressUpdatedCount} 条`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.updateAddress] 写入操作日志失败,不影响业务', logErr); + } + + return this.success('ok', { + updated_count: addressUpdatedCount, + ids: orderIds, + }); + } + + /** + * 批量修改待处理订单的备注(remark)字段。 + * + * 与 updateAddress 中的 remark 更新逻辑相似, + * 但作为独立接口只负责备注修改,不涉及地址字段。 + * remark 修改不受 post_status 限制,对所有状态的订单均可生效。 + * + * @param {Object} data 请求体。 + * @param {Array} data.ids 订单ID数组(必填,正整数数组)。 + * @param {string} data.remark 备注内容(必填,最大500字符)。 + * @return {Promise} 统一 success 包装的更新结果,含 updated_count 与 ids。 + */ + async updateRemark(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + // 解析订单 ID(仅支持数组) + const rawOrderIds = requestData.ids; + if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) { + throw new Error('ids 不能为空,且必须是正整数数组'); + } + + const orderIds = Array.from(new Set(rawOrderIds.map(v => { + const n = Number(v); + if (!Number.isInteger(n) || n <= 0) { + throw new Error('ids 仅支持正整数数组'); + } + return n; + }))); + + // 解析 remark + const rawRemark = requestData.remark; + if (rawRemark === undefined || rawRemark === null) { + throw new Error('remark 不能为空'); + } + const trimmed = String(rawRemark).trim(); + if (trimmed === '') { + throw new Error('remark 不能为空字符串'); + } + const remarkValue = trimmed.substring(0, 500); + + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere(orderIds, warehouseId); + const now = new Date(); + + const [ affectedRows ] = await model.update( + { remark: remarkValue, updated_at: now }, + { where } + ); + const count = Number(affectedRows || 0); + + // 记录操作日志 + try { + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_UPDATE_REMARK', + operator, + extras: { + warehouseId: logWarehouseId, + orderIds, + remark: remarkValue, + updated_count: count, + message: `批量修改订单备注:订单ID [${orderIds.join(', ')}],备注内容 [${remarkValue}],共更新 ${count} 条`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.updateRemark] 写入操作日志失败,不影响业务', logErr); + } + + return this.success('ok', { + updated_count: count, + ids: orderIds, + }); + } + + /** + * 克隆待处理订单。 + * + * 流程: + * 1. 查找原订单,校验可取消状态(step 0/1/2/3); + * 2. 若原订单已分配储位(storage_status='fin'),先清除已分配库存; + * 3. 取消原订单(step->9, status->'cancel')并记录"克隆"日志; + * 4. 以原订单业务数据创建新订单,所有流程状态字段重置为初始落库状态; + * 同步状态继承原订单:原订单已同步(sync_status=fin)则新订单直接置 fin 避免重复回传, + * 否则重置为 padding 重新走同步; + * 5. 对新订单记录"克隆创建"日志。 + * + * @param {Object} data 请求体。 + * @param {number} data.order_id 原订单ID。 + * @return {Promise} 统一 success 包装,含新订单 id。 + */ + async cloneOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const orderId = Number(requestData.order_id || requestData.id); + if (!Number.isInteger(orderId) || orderId <= 0) { + throw new Error('order_id 不能为空'); + } + + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere([ orderId ], warehouseId); + + // 1. 查原订单 + const existingOrders = await model.findAll({ where, raw: true }); + if (!Array.isArray(existingOrders) || existingOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + const original = existingOrders[0]; + + if (!this.isCancelablePendingOrder(original)) { + throw new Error('订单当前状态不允许克隆'); + } + + // 2. 若已分配储位,先清除库存。 + // 已同步订单同样允许克隆;库存释放失败不阻断克隆(与 cancelOrder 降级策略一致), + // 原订单残留占用保留在原订单名下,克隆新订单不重新占用库存 + // (新订单 storage_status 重置为 none,创建过程不触发储位分配与库存锁定)。 + if (String(original.storage_status || '').trim() === 'fin') { + try { + await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: [ orderId ], + }); + } catch (storageErr) { + this.ctx.logger.warn( + `[PendingOrderService.cloneOrder] 清除已分配库存失败,不影响克隆,orderId=${orderId}`, + storageErr + ); + } + } + + const now = new Date(); + const originalWaveId = Number(original.wave_id || 0); + + // 3. 取消原订单(若在波次中需清除波次关联) + const cancelUpdateValues = { + status: 'cancel', + step: 9, + outbound_status: 'padding', + updated_at: now, + }; + if (originalWaveId > 0) { + cancelUpdateValues.wave_id = 0; + cancelUpdateValues.wave_no = ''; + } + await model.update(cancelUpdateValues, { where }); + + // 克隆时清理波次索引(不影响主流程) + if (originalWaveId > 0) { + try { + await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: [ orderId ], + }); + await this.ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: [ originalWaveId ], + orderModel: model, + }); + } catch (waveErr) { + this.ctx.logger.warn('[PendingOrderService.cloneOrder] 清理波次关联失败,不影响克隆', waveErr); + } + } + + // 记录原订单"克隆"日志 + try { + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: orderId, + operationCode: 'ORDER_CLONE_SOURCE', + operator, + extras: { + warehouseId: logWarehouseId, + message: `订单克隆:原订单 ${orderId} 已取消,将创建新订单`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.cloneOrder] 写入原订单克隆日志失败', logErr); + } + + // 4. 构造新订单数据 — 保留业务字段,重置所有流程状态 + const RESET_FIELDS = { + step: 0, + status: 'created', + inspection_status: 'none', + recheck_status: 'none', + storage_status: 'none', + post_status: 'none', + pick_status: 'none', + pack_status: 'none', + print_status: 'none', + claim_status: 'none', + outbound_status: 'none', + lock_status: 'none', + intercept_status: 'none', + // 克隆重置拦截字段:通知拦截时间必须清空,避免新单继承原单发起拦截时刻 + intercept_time: null, + sync_status: 'padding', + order_flag: '', + wave_id: 0, + delivery_time: null, + operate_time: null, + operator_name: null, + express_code: null, + logistics_area_code: null, + delete_at: null, + create_at: now, + updated_at: now, + }; + + // 业务字段白名单(从原订单复制) + // 注意:不含 delivery_order_code —— 该字段受 (delivery_order_code, store_id, warehouse_id) + // 唯一索引约束,且原订单取消后仍留在 current 表占用索引,复制原单号会触发唯一键冲突 + // (Sequelize UniqueConstraintError,对外表现为 "Validation error")。新单号见下方生成逻辑。 + const COPY_FIELDS = [ + 'pre_delivery_order_code', 'pre_delivery_order_id', + 'order_type', 'warehouse_code', 'warehouse_id', 'store_id', 'from_key', + 'source_platform_code', 'source_platform_name', 'source_order_codes', + 'sys_platform_code', 'sys_platform_name', + 'place_order_time', 'pay_time', 'pay_no', + 'service_code', 'shop_nick', 'seller_nick', 'buyer_nick', + 'total_amount', 'item_amount', 'discount_amount', 'freight', + 'ar_amount', 'got_amount', 'service_fee', + 'logistics_code', 'logistics_name', 'sys_logistics_code', 'sys_logistics_name', + 'delivery_type', 'weight_type', 'is_urgency', 'invoice_flag', + 'name', 'zip_code', 'tel', 'mobile', 'email', + 'country_code', 'province', 'city', 'area', 'town', 'detail_address', + 'id_type', 'id_number', 'oaid', 'extend_props', + 'items', 'items_count', 'items_total', 'items_weight', 'items_hash', 'items_crc', + 'has_sn_item', + ]; + + const newOrderData = { ...RESET_FIELDS }; + // 克隆单生成全新发货单号(与手工单 createOrder 相同的生成规则) + newOrderData.delivery_order_code = `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`; + // 同步状态继承:原订单已同步(sync_status=fin)则新订单直接置 fin,避免重复回传平台; + // 未同步/同步失败(padding/error)重置为 padding 重新走同步流程 + newOrderData.sync_status = String(original.sync_status || '').trim() === 'fin' ? 'fin' : 'padding'; + for (const field of COPY_FIELDS) { + if (original[field] !== undefined) { + newOrderData[field] = original[field]; + } + } + // 克隆追溯链:原订单无前置单号时,把原单号写入新订单 pre_delivery_order_code + const originalDeliveryCode = String(original.delivery_order_code || '').trim(); + if (originalDeliveryCode && !String(newOrderData.pre_delivery_order_code || '').trim()) { + newOrderData.pre_delivery_order_code = originalDeliveryCode; + } + + // 克隆单同样由仓库序列表统一发号;发号失败直接抛错,不回退分表自增, + // 避免分表自增与序列表发号区间重叠产生冲突 id + await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseId); + const allocatedOrderId = await this.ctx.model.OrderDeliveryFactory.allocateOrderId(warehouseId, null, 'current'); + + const newOrder = await model.create({ ...newOrderData, id: allocatedOrderId }); + const newOrderId = Number(newOrder.id || newOrder.dataValues && newOrder.dataValues.id); + + // 5. 克隆订单明细 + try { + const orderItemsFactory = this.ctx.model && this.ctx.model.OrderItemsFactory; + if (orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function') { + const itemsModel = await orderItemsFactory.getCurrentModel(warehouseId); + if (itemsModel && typeof itemsModel.findAll === 'function') { + const originalItems = await itemsModel.findAll({ + where: { order_id: orderId }, + raw: true, + }); + + if (Array.isArray(originalItems) && originalItems.length > 0) { + const ITEM_COPY_FIELDS = [ + 'actual_price', 'retail_price', 'ext_code', 'inventory_type', + 'item_code', 'item_id', 'item_name', 'order_line_no', 'owner_code', + 'plan_qty', 'source_order_code', 'sub_source_order_code', + 'extend_props', 'stock_id', 'item_snapshot', + ]; + const newItems = originalItems.map(item => { + const newItem = { order_id: newOrderId, created_at: now, updated_at: now }; + for (const field of ITEM_COPY_FIELDS) { + if (item[field] !== undefined) { + newItem[field] = item[field]; + } + } + return newItem; + }); + await itemsModel.bulkCreate(newItems); + } + } + } + } catch (itemsErr) { + this.ctx.logger.warn('[PendingOrderService.cloneOrder] 克隆订单明细失败', itemsErr); + throw new Error(`克隆订单明细失败:${itemsErr.message}`); + } + + // 6. 记录新订单"克隆创建"日志 + try { + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: newOrderId, + operationCode: 'ORDER_CLONE_TARGET', + operator, + extras: { + warehouseId: logWarehouseId, + message: `克隆创建:由原订单 ${orderId} 克隆生成,新订单 ID ${newOrderId}`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.cloneOrder] 写入新订单克隆创建日志失败', logErr); + } + + return this.success('ok', { + source_order_id: orderId, + new_order_id: newOrderId, + }); + } + + /** + * 智能地址解析:使用本地省市区字典遍历方式将地址字符串解析为结构化地址。 + * + * 原 DeepSeek AI 解析方式已弃用,现改为本地字典遍历识别(与 parseAddressLocal 同源): + * - 遍历 LOCAL_CITY_DICT(约 340 个地级市)识别 province/city + * - 遍历 CHINA_ADMIN_DIVISION_MAP(省直辖县级市/不设区地级市/代管县级市)识别特殊区县 + * - 遍历 PROVINCE_LIST 全称/简称兜底识别省份 + * - 复用 reverseInferAddress 补全省/市/区,extractAddressByRegex 正则最终兜底 + * + * 支持单条解析与数组批量解析两种模式: + * - 单条:data.address 传字符串,返回单条解析结果(与原行为一致) + * - 批量:data.addresses(或 data.address)传字符串数组,按数组顺序返回 data.list, + * 每条元素含 address/flag/message 与解析字段,失败条目不影响其他条目 + * + * @param {Object} data 请求数据。 + * @param {string|string[]} data.address 原始地址字符串或字符串数组(必填)。 + * @param {string[]} [data.addresses] 批量地址字符串数组(与 address 数组二选一)。 + * @return {Promise} 解析结果;批量模式返回 data.list 数组。 + */ + async parseAddress(data = {}) { + // 批量模式:addresses 数组优先,其次 address 数组;均走本地字典遍历解析 + const rawAddresses = Array.isArray(data.addresses) + ? data.addresses + : (Array.isArray(data.address) ? data.address : null); + + if (rawAddresses) { + if (!rawAddresses.length) { + return this.fail('地址数组不能为空'); + } + if (rawAddresses.length > 50) { + return this.fail('单次批量解析最多支持 50 条地址'); + } + const EMPTY_FIELDS = { province: '', city: '', area: '', town: '', detailAddress: '', name: '', mobile: '' }; + const toListItem = r => ({ + address: r.address, + flag: r.ok ? 'success' : 'failure', + message: r.message, + ...(r.fields || EMPTY_FIELDS), + }); + const results = rawAddresses.map(item => parseAddressByLocalDict(item)); + return this.success('地址解析成功', { list: results.map(toListItem) }); + } + + // 单条模式(向后兼容) + const single = parseAddressByLocalDict(data.address); + if (!single.ok) { + return this.fail(single.message); + } + return this.success('地址解析成功', single.fields); + } + + + /** + * 本地地址解析接口:不调用 AI,直接内置省市区地址字典数据,遍历识别省市区。 + * + * 与 parseAddress 使用同一套本地字典遍历解析逻辑,两者解析结果等价; + * - 单条:data.address 传字符串,返回单条解析结果(与 parseAddress 单条结构一致) + * - 批量:data.addresses(或 data.address)传字符串数组,返回 data.list, + * 每条含 address/flag/message 与解析字段,失败条目不影响其他条目 + * - 演示:address 与 addresses 均不传时,直接使用接口内置的示例地址数据 + * 遍历识别并返回 data.list(data.source=sample) + * + * 识别范围:province/city/area/town/detailAddress/mobile(name 本地不识别,返回空字符串)。 + * + * @param {Object} data 请求数据。 + * @param {string|string[]} [data.address] 原始地址字符串或字符串数组。 + * @param {string[]} [data.addresses] 批量地址字符串数组(与 address 数组二选一)。 + * @return {Promise} 解析结果;批量/演示模式返回 data.list 数组。 + */ + async parseAddressLocal(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + + // 确定输入地址:addresses 数组 > address 数组 > address 字符串 > 内置示例地址数据 + let addresses; + let useSample = false; + if (Array.isArray(requestData.addresses)) { + addresses = requestData.addresses; + } else if (Array.isArray(requestData.address)) { + addresses = requestData.address; + } else if (String(requestData.address || '').trim()) { + addresses = [ String(requestData.address).trim() ]; + } else { + addresses = LOCAL_SAMPLE_ADDRESSES.slice(); + useSample = true; + } + + if (!addresses.length) { + return this.fail('地址数组不能为空'); + } + if (!useSample && addresses.length > 50) { + return this.fail('单次批量解析最多支持 50 条地址'); + } + + const EMPTY_FIELDS = { province: '', city: '', area: '', town: '', detailAddress: '', name: '', mobile: '' }; + const toListItem = r => ({ + address: r.address, + flag: r.ok ? 'success' : 'failure', + message: r.message, + ...(r.ok && r.fields ? r.fields : EMPTY_FIELDS), + }); + + // 单条模式(向后兼容 parseAddress 单条返回结构) + if (!useSample && addresses.length === 1) { + const single = parseAddressByLocalDict(addresses[0]); + if (!single.ok) { + return this.fail(single.message); + } + return this.success('地址解析成功', single.fields); + } + + const list = addresses.map(item => toListItem(parseAddressByLocalDict(item))); + const message = useSample ? '内置示例地址遍历识别成功' : '地址解析成功'; + return this.success(message, useSample ? { list, source: 'sample' } : { list }); + } + + /** + * 手动创建待处理订单。 + * + * 根据货主策略(need_order_approval)自动决定订单初始步骤: + * - need_order_approval=1(默认)→ step=0 待审核 + * - need_order_approval=0 → step=1 直接进待处理 + * + * @param {Object} data 请求体。 + * @param {number} data.store_id 货主ID(必填)。 + * @param {string} data.name 收件人姓名(必填)。 + * @param {string} [data.mobile] 收件人手机号(mobile/tel 至少一项必填)。 + * @param {string} [data.tel] 收件人电话。 + * @param {string} data.detail_address 详细地址(必填)。 + * @param {string} [data.province] 省份。 + * @param {string} [data.city] 城市。 + * @param {string} [data.area] 区/县。 + * @param {string} [data.town] 镇/街道。 + * @param {string} [data.zip_code] 邮编。 + * @param {Array} data.items 订单明细(必填,每项含 item_id 与 plan_qty)。 + * @param {string} [data.delivery_order_code] 订单号,不传则自动生成。 + * @param {string} [data.logistics_code] 快递编码,不传则读货主默认快递策略。 + * @param {string} [data.logistics_name] 快递名称。 + * @param {string} [data.sys_platform_code] 系统平台编码,不传则读货主默认平台策略。 + * @param {string} [data.source_platform_code] 来源平台编码。 + * @param {string} [data.source_order_codes] 来源订单号。 + * @param {string} [data.order_type] 订单类型。 + * @param {string} [data.is_urgency] 是否紧急(Y/N),默认 N。 + * @param {string} [data.invoice_flag] 是否需要发票(Y/N),默认 N。 + * @return {Promise} 统一 success 包装,含新订单 id 与 step 信息。 + */ + async createOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + + // 1. 参数校验 + const storeId = Number(requestData.store_id); + if (!Number.isInteger(storeId) || storeId <= 0) { + throw new Error('store_id(货主ID)不能为空'); + } + + const name = String(requestData.name || '').trim(); + if (!name) { + throw new Error('收件人姓名不能为空'); + } + + const mobile = String(requestData.mobile || '').trim(); + const tel = String(requestData.tel || '').trim(); + if (!mobile && !tel) { + throw new Error('收件人手机号或电话至少填写一项'); + } + + const detailAddress = String(requestData.detail_address || '').trim(); + if (!detailAddress) { + throw new Error('详细地址不能为空'); + } + + const province = String(requestData.province || '').trim(); + if (!province) { + throw new Error('省份不能为空'); + } + + const city = String(requestData.city || '').trim(); + if (!city) { + throw new Error('城市不能为空'); + } + + const area = String(requestData.area || '').trim(); + if (!area) { + throw new Error('区县不能为空'); + } + + const rawItems = requestData.items; + if (!Array.isArray(rawItems) || rawItems.length === 0) { + throw new Error('订单明细 items 不能为空'); + } + + // 2. 适配明细格式并校验(转为 addOrder 所需的驼峰格式) + // 手工单:item_id 即为仓库 stock_id,无需查 stock_store 做映射 + const orderLineItems = rawItems.map((item, idx) => { + if (!item || typeof item !== 'object') { + throw new Error(`第${idx + 1}行明细格式无效`); + } + const itemId = Number(item.item_id); + if (!Number.isInteger(itemId) || itemId <= 0) { + throw new Error(`第${idx + 1}行商品 item_id 必须为正整数`); + } + const planQty = Number(item.plan_qty); + if (!Number.isInteger(planQty) || planQty <= 0) { + throw new Error(`第${idx + 1}行计划数量 plan_qty 必须为正整数`); + } + return { + itemCode: String(item.item_code || '').trim(), + itemId, + itemName: String(item.item_name || '').trim() || '商品', + planQty, + stockId: itemId, + orderLineNo: String(item.order_line_no || String(idx + 1)).trim(), + actualPrice: Number(item.actual_price) || 0, + }; + }); + + // 3. 自动生成订单号(如未传) + const deliveryOrderCode = String(requestData.delivery_order_code || '').trim() + || `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`; + // 4. 适配为 addOrder 所需的奇门嵌套格式 + const adaptedData = { + request: { + deliveryOrder: { + deliveryOrderCode, + orderType: String(requestData.order_type || '').trim(), + sourcePlatformCode: String(requestData.source_platform_code || requestData.sys_platform_code || '').trim(), + sourcePlatformName: String(requestData.source_platform_name || '').trim(), + createChannel: String(requestData.create_channel || requestData.createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL', + logisticsCode: String(requestData.logistics_code || '').trim(), + logisticsName: String(requestData.logistics_name || '').trim(), + isUrgency: [ 'Y', 'N' ].includes(requestData.is_urgency) ? requestData.is_urgency : 'N', + invoiceFlag: [ 'Y', 'N' ].includes(requestData.invoice_flag) ? requestData.invoice_flag : 'N', + shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim(), + receiverInfo: { + name, + mobile, + tel, + province, + city, + area, + town: String(requestData.town || '').trim(), + detailAddress, + zipCode: String(requestData.zip_code || '').trim(), + }, + remark: String(requestData.remark || '').trim(), + }, + orderLines: { + orderLine: orderLineItems, + }, + }, + }; + + const info = { + storeId, + warehouseId, + appKey: (this.ctx.user && this.ctx.user.app_key) || '', + }; + + // 6. 委托 addOrder 执行完整逻辑(库存预占、平台快递解析、入队列、操作日志) + const result = await this.service.systems.deliveryOrder.addOrder(adaptedData, info); + + if (!result.success) { + throw new Error(result.message || '订单创建失败'); + } + + // 重复订单视为错误(与原逻辑保持一致) + if (result.message === '订单已存在' || (result.data && result.data.deliveryOrderId)) { + throw new Error(`订单号 ${deliveryOrderCode} 已存在`); + } + + const orderId = result.data && result.data.orderId; + const step = result.data && result.data.step; + const itemsTotal = orderLineItems.reduce((sum, item) => sum + item.planQty, 0); + + return this.success('ok', { + order_id: orderId, + delivery_order_code: deliveryOrderCode, + step, + step_label: step === 0 ? '待审核' : (step === 1 ? '待处理' : ''), + items_count: orderLineItems.length, + items_total: itemsTotal, + }); + } + + /** + * 下载创建订单导入模板。 + * + * 返回 base64 编码的 Excel 文件内容,前端解码后作为 .xlsx 文件下载。 + * + * @return {Promise} 统一 success 包装,含 base64 字符串与文件名。 + */ + async downloadCreateTemplate() { + const ExcelJS = require('exceljs'); + const workbook = new ExcelJS.Workbook(); + const sheet = workbook.addWorksheet('创建订单导入模板'); + + const columns = [ + // 必填 + { header: '*订单号', key: 'delivery_order_code', width: 24 }, + { header: '店铺名称', key: 'shop_nick', width: 20 }, + { header: '*收件人姓名', key: 'name', width: 16 }, + { header: '*手机号(mobile/tel至少填一项)', key: 'mobile', width: 28 }, + { header: '*详细地址', key: 'detail_address', width: 36 }, + { header: '*商品编码', key: 'item_code', width: 20 }, + { header: '*计划数量', key: 'plan_qty', width: 12 }, + // 非必填 + { header: '货主ID', key: 'store_id', width: 12 }, + { header: '电话', key: 'tel', width: 16 }, + { header: '省份', key: 'province', width: 12 }, + { header: '城市', key: 'city', width: 12 }, + { header: '区/县', key: 'area', width: 12 }, + { header: '镇/街道', key: 'town', width: 12 }, + { header: '邮编', key: 'zip_code', width: 12 }, + { header: '快递编码', key: 'logistics_code', width: 16 }, + { header: '快递名称', key: 'logistics_name', width: 16 }, + { header: '系统平台编码', key: 'sys_platform_code', width: 16 }, + { header: '来源平台编码', key: 'source_platform_code', width: 16 }, + { header: '来源订单号', key: 'source_order_codes', width: 20 }, + { header: '订单类型', key: 'order_type', width: 14 }, + { header: '是否紧急(Y/N)', key: 'is_urgency', width: 16 }, + { header: '是否需要发票(Y/N)', key: 'invoice_flag', width: 18 }, + { header: '商品名称', key: 'item_name', width: 24 }, + { header: '行号', key: 'order_line_no', width: 10 }, + { header: '实际价格', key: 'actual_price', width: 12 }, + ]; + + sheet.columns = columns; + + const headerRow = sheet.getRow(1); + headerRow.eachCell((cell, colNumber) => { + const col = columns[colNumber - 1]; + const isRequired = col && col.header.startsWith('*'); + cell.font = { bold: true, color: { argb: 'FF000000' } }; + cell.fill = { + type: 'pattern', + pattern: 'solid', + fgColor: { argb: isRequired ? 'FFFFC000' : 'FFD9D9D9' }, + }; + cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true }; + cell.border = { + top: { style: 'thin' }, + left: { style: 'thin' }, + bottom: { style: 'thin' }, + right: { style: 'thin' }, + }; + }); + headerRow.height = 36; + + sheet.addRow({ + delivery_order_code: 'ORD20260421001', + store_id: 1, + name: '张三', + mobile: '13800138000', + tel: '', + detail_address: 'XX路XX号', + province: '广东省', + city: '深圳市', + area: '南山区', + town: '', + zip_code: '518000', + logistics_code: 'STO', + logistics_name: '申通快递', + sys_platform_code: 'TB', + source_platform_code: '', + source_order_codes: '', + order_type: '', + is_urgency: 'N', + invoice_flag: 'N', + item_code: 'SKU001', + item_name: '商品A', + plan_qty: 2, + order_line_no: '1', + actual_price: 9.90, + shop_nick: '', + }); + + sheet.addRow({ + delivery_order_code: 'ORD20260421001', + store_id: 1, + name: '张三', + mobile: '13800138000', + tel: '', + detail_address: 'XX路XX号', + province: '广东省', + city: '深圳市', + area: '南山区', + town: '', + zip_code: '518000', + logistics_code: 'STO', + logistics_name: '申通快递', + sys_platform_code: 'TB', + source_platform_code: '', + source_order_codes: '', + order_type: '', + is_urgency: 'N', + invoice_flag: 'N', + item_code: 'SKU002', + item_name: '商品B', + plan_qty: 1, + order_line_no: '2', + actual_price: 19.90, + shop_nick: '', + }); + + const noteSheet = workbook.addWorksheet('填写说明'); + noteSheet.getColumn(1).width = 80; + const notes = [ + '【填写说明】', + '1. 带 * 的列为必填项,表头背景为橙色。', + '2. 每一行代表一条商品明细;同一订单的多个商品,订单号(delivery_order_code)必须相同。', + '3. 同一订单的所有行中,订单头信息(收件人、地址等)取第一行的值,后续行可省略但不影响解析。', + '4. mobile 和 tel 至少填写一项。', + '5. 计划数量(plan_qty)必须为正整数。', + '6. 是否紧急、是否需要发票只接受 Y 或 N(大写),不填默认 N。', + '7. 快递编码、系统平台编码不填时,系统会读取货主默认策略自动补充;不填货主ID时,系统会从当前登录用户的上下文自动获取。', + '8. 同一文件内,相同订单号只会创建一个订单,不会重复创建。', + ]; + notes.forEach((note, i) => { + const row = noteSheet.getRow(i + 1); + row.getCell(1).value = note; + if (i === 0) { + row.getCell(1).font = { bold: true, size: 13 }; + } + }); + + const buffer = await workbook.xlsx.writeBuffer(); + const base64 = Buffer.from(buffer).toString('base64'); + + return this.success('ok', { + base64, + filename: '创建订单导入模板.xlsx', + mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }); + } + + /** + * 归一化 ids 入参为去重后的正整数数组。 + * + * 支持数组、逗号分隔字符串、单个 number/string。 + * + * @param {Array|number|string} value 原始 ids 入参。 + * @return {Array} 归一化后的 ids 数组。 + */ + normalizeIdsInput(value) { + let sourceList = []; + + if (Array.isArray(value)) { + sourceList = value; + } else if (typeof value === 'string') { + sourceList = value.split(','); + } else if (typeof value === 'number') { + sourceList = [ value ]; + } else { + sourceList = []; + } + + const normalizedIds = sourceList + .map(item => String(item === undefined || item === null ? '' : item).trim()) + .filter(item => item !== '') + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0); + + return [ ...new Set(normalizedIds) ]; + } + + /** + * 批量拦截订单。 + * + * 提交后台异步任务,将给定订单的 intercept_status 更新为 'requested'。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} [data.order_ids] 订单ID数组(下划线写法)。 + * @param {Array} [data.orderIds] 订单ID数组(驼峰别名)。 + * @param {Array} [data.ids] 订单ID数组(简写别名)。 + * @param {string} [data.task_id] 任务ID(用于查询进度)。 + * @param {string} [data.taskId] 任务ID(驼峰别名)。 + * @return {Promise} 提交结果,包含 task_id、状态与 accepted_at。 + */ + async batchIntercept(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchInterceptOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchInterceptTaskId(data); + const taskId = requestedTaskId || this.generateBatchInterceptTaskId(warehouseId); + const existingTask = await this.getBatchInterceptTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量拦截任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchInterceptTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + intercepted_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchIntercept] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchInterceptTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchIntercept] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量拦截任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量拦截任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchInterceptTaskProgress(data = {}) { + const taskId = this.normalizeBatchInterceptTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchInterceptTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.intercepted_order_count = Number(cachedProgress.intercepted_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.intercepted_order_count = Number(result.intercepted_order_count || 0); + payload.intercepted_order_ids = this.normalizeIdsInput(result.intercepted_order_ids); + payload.skipped_order_ids = this.normalizeIdsInput(result.skipped_order_ids); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.intercepted_order_count = Number(cachedProgress.intercepted_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_INTERCEPT_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量拦截任务ID。 + * + * 格式:order_intercept_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchInterceptTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `order_intercept_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量拦截任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchInterceptTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量拦截的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchInterceptOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量拦截任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchInterceptTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_INTERCEPT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchInterceptTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchInterceptTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchInterceptTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_INTERCEPT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchInterceptTaskProgress(taskId = '') { + const cacheKey = this.getBatchInterceptTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量拦截后台任务。 + * + * 直接对给定订单ID数组,将 intercept_status 更新为 'requested' 并同步写入拦截时间 intercept_time, + * 同时写入操作日志。仅处理当前仓库上下文内的订单。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchInterceptTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchInterceptTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + intercepted_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'wave_id', 'inspection_status', 'intercept_time', 'sync_status', 'create_channel' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const interceptedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + // 拉取拦截请求前置校验信息(波次类型 + 散单称重重量):团购单已复核 / 散单已称重的订单不允许写入拦截请求状态,跳过拦截 + const guardInfoMap = await resolveInterceptRequestGuardInfoMap(ctx, { + orderRows: validOrderRows, + warehouseId, + }); + + const skippedInterceptOrderIds = []; + const eligibleOrderRows = []; + for (const row of (Array.isArray(validOrderRows) ? validOrderRows : [])) { + const guardInfo = guardInfoMap.get(Number(row.id)) || {}; + const blockReason = getInterceptRequestBlockReason({ + waveType: guardInfo.waveType, + inspectionStatus: String(row.inspection_status || '').trim(), + weighingWeight: guardInfo.weighingWeight, + }); + if (blockReason) { + skippedInterceptOrderIds.push(Number(row.id)); + ctx.logger.info( + `[order.pendingOrder.batchIntercept] 订单${blockReason},跳过拦截, orderId=${row.id}` + ); + } else { + eligibleOrderRows.push(row); + } + } + + // 未同步订单与手工单不发起拦截,默认按取消订单处理: + // 释放 stock 建单锁与 storage 储位锁,不走常规拦截(不迁移拦截锁) + const cancelHandledOrderRows = []; + const interceptTargetRows = []; + for (const row of eligibleOrderRows) { + const isManualOrder = String(row.create_channel || '').trim().toUpperCase() === 'MANUAL'; + const isUnsyncedOrder = String(row.sync_status || '').trim() !== 'fin'; + if (isManualOrder || isUnsyncedOrder) { + cancelHandledOrderRows.push(row); + } else { + interceptTargetRows.push(row); + } + } + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const eligibleOrderCount = interceptTargetRows.length; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + intercepted_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + intercepted_order_ids: [], + intercepted_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可拦截的当前仓库订单', + }, + }); + return; + } + + const cancelledOrderIds = []; + const UPDATE_CHUNK_SIZE = 500; + + // ── 未同步/手工单:按取消订单处理(状态置 cancel + 释放两层锁,不走拦截) ── + // 已同步订单(stock 层已同步出库)取消时按订单明细回补 stock quantity, + // 保证取消后两层可用数守恒(storage 锁释放、stock 数量冲回) + if (cancelHandledOrderRows.length > 0) { + const cancelIds = cancelHandledOrderRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + const now = new Date(); + + for (let i = 0; i < cancelIds.length; i += UPDATE_CHUNK_SIZE) { + const chunkCancelIds = cancelIds.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkCancelIds.length === 0) { + continue; + } + + const chunkRows = cancelHandledOrderRows.filter(row => chunkCancelIds.includes(Number(row.id))); + const syncedCancelIds = chunkRows + .filter(row => String(row.sync_status || '').trim() === 'fin') + .map(row => Number(row.id)); + const unsyncedCancelIds = chunkCancelIds.filter(id => !syncedCancelIds.includes(id)); + + const cancelTransaction = await this.ctx.model.transaction(); + try { + await orderModel.update( + { status: 'cancel', step: 9, outbound_status: 'padding', updated_at: now }, + { where: { id: { [Op.in]: chunkCancelIds }, warehouse_id: warehouseId }, transaction: cancelTransaction } + ); + + // 释放储位分配(普通模式:解除锁定/返还实物) + const originalUser = ctx.user; + ctx.user = originalUser + ? { ...originalUser, store_id: warehouseId } + : { store_id: warehouseId }; + try { + await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: chunkCancelIds, + transaction: cancelTransaction, + }); + } finally { + ctx.user = originalUser; + } + + // 释放 stock 建单锁(仅未同步订单:已同步订单的建单锁已在同步出库时释放) + if (unsyncedCancelIds.length > 0) { + await this.releaseCreationLockForCancel({ + orderIds: unsyncedCancelIds, + warehouseId, + transaction: cancelTransaction, + }); + } + + // 已同步订单:回补 stock quantity(同步出库冲回,货物回可用) + if (syncedCancelIds.length > 0) { + const orderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const cancelOrderItems = await orderItemsModel.findAll({ + where: { order_id: { [Op.in]: syncedCancelIds } }, + attributes: [ 'stock_id', 'plan_qty' ], + raw: true, + transaction: cancelTransaction, + }); + + // 回补依赖 ctx.user.store_id 写流水,任务执行时上下文可能已失效,临时注入 + const inboundOriginalUser = ctx.user; + ctx.user = inboundOriginalUser + ? { ...inboundOriginalUser, store_id: warehouseId } + : { store_id: warehouseId }; + + for (const item of Array.isArray(cancelOrderItems) ? cancelOrderItems : []) { + const stockId = Number(item && item.stock_id) || 0; + const qty = Number(item && item.plan_qty) || 0; + if (stockId <= 0 || qty <= 0) { + continue; + } + const inboundResult = await this.ctx.service.systems.stockStore.inbound( + stockId, + qty, + cancelTransaction, + { stockId } + ); + if (!inboundResult || inboundResult.success !== true) { + throw new Error( + `未同步/手工单取消回补库存失败: stockId=${stockId}, qty=${qty}, ${(inboundResult && inboundResult.error) || '未知错误'}` + ); + } + } + + ctx.user = inboundOriginalUser; + } + + await cancelTransaction.commit(); + } catch (cancelErr) { + await cancelTransaction.rollback().catch(() => {}); + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 未同步/手工单取消失败, ids=${chunkCancelIds.join(',')}, error=${cancelErr.message}` + ); + continue; + } + + cancelledOrderIds.push(...chunkCancelIds); + + // 写入操作日志(失败不影响主流程) + try { + const cancelLogRows = chunkRows + .map(row => { + const orderId = Number(row.id || 0); + const isSynced = String(row.sync_status || '').trim() === 'fin'; + return { + business_type: 'order', + business_id: String(orderId), + operation_code: 'ORDER_INTERCEPT_REQUEST_CANCELED', + operator_id: operator && operator.id != null ? String(operator.id) : null, + operator_name: operator && operator.name ? String(operator.name) : 'system', + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: isSynced + ? '已同步手工单拦截请求按取消订单处理(库存已回补)' + : '未同步订单拦截请求按取消订单处理', + created_at: new Date(), + }; + }) + .filter(row => Number(row.businessId) > 0); + if (cancelLogRows.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + await this.ctx.model.OperationLog.bulkCreate(cancelLogRows); + } + } catch (logErr) { + ctx.logger.warn(`[order.pendingOrder.batchIntercept] 未同步/手工单取消日志写入失败, count=${chunkCancelIds.length}, error=${logErr.message}`); + } + } + } + + // 分批更新拦截状态,每批最多500条(仅处理未命中「已复核/已称重」前置校验的订单) + for (let i = 0; i < interceptTargetRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = interceptTargetRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + // 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值) + const fillNoticeOrderIds = pickNoticeTimeOrderIds(chunkRows); + await orderModel.update( + { intercept_status: 'requested', updated_at: now }, + { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + } + ); + if (fillNoticeOrderIds.length > 0) { + await orderModel.update( + { intercept_time: now }, + { + where: { + id: { + [Op.in]: fillNoticeOrderIds, + }, + }, + } + ); + } + + // 同步更新运单表拦截标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 更新运单拦截标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}` + ); + } + + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + const op = this.getOrderLogOperator(); + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: chunkOrderIds, + warehouseId, + creatorLabel: op.name || '系统', + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 创建工单/通知失败, count=${chunkOrderIds.length}, error=${workOrderErr.message}` + ); + } + + // 写入操作日志 + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: orderId, + operationCode: 'ORDER_INTERCEPT_REQUEST', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newInterceptStatus: 'requested', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + interceptedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = eligibleOrderCount > 0 + ? Math.min(99, Math.round((interceptedOrderIds.length / eligibleOrderCount) * 100)) + : 0; + + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + intercepted_order_count: interceptedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + intercepted_order_count: interceptedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + intercepted_order_ids: interceptedOrderIds, + intercepted_order_count: interceptedOrderIds.length, + cancelled_order_ids: cancelledOrderIds, + cancelled_order_count: cancelledOrderIds.length, + skipped_order_ids: skippedInterceptOrderIds, + skipped_order_count: skippedInterceptOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已拦截 ${interceptedOrderIds.length} 条订单,未同步/手工单按取消处理 ${cancelledOrderIds.length} 条` + + (skippedInterceptOrderIds.length > 0 ? `,跳过 ${skippedInterceptOrderIds.length} 条(已复核/已称重)` : ''), + }, + }); + } catch (error) { + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'BATCH_INTERCEPT_FAILED', + }); + } + } + + /** + * 批量锁定订单(异步任务模式)。 + * + * 将给定订单的 lock_status 批量更新为 'warehouse',并写入操作日志 ORDER_LOCK。 + * 已取消订单不允许锁定,后台任务会跳过并通过 skipped_cancelled_order_ids 返回。 + * 仅操作当前仓库上下文内的订单,每批最多 500 条。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.order_ids 订单ID数组。 + * @param {string} [data.task_id] 可选的任务ID(用于幂等续查)。 + * @return {Promise} 提交响应,含 task_id。 + */ + async batchLock(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchLockOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchLockTaskId(data); + const taskId = requestedTaskId || this.generateBatchLockTaskId(warehouseId); + const existingTask = await this.getBatchLockTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量锁定任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchLockTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + locked_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchLock] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchLockTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchLock] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量锁定任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量锁定任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchLockTaskProgress(data = {}) { + const taskId = this.normalizeBatchLockTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchLockTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.locked_order_count = Number(cachedProgress.locked_order_count || 0); + payload.skipped_cancelled_order_count = Number(cachedProgress.skipped_cancelled_order_count || 0); + payload.skipped_cancelled_order_ids = this.normalizeIdsInput(cachedProgress.skipped_cancelled_order_ids); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.locked_order_count = Number(result.locked_order_count || 0); + payload.locked_order_ids = this.normalizeIdsInput(result.locked_order_ids); + payload.skipped_cancelled_order_count = Number(result.skipped_cancelled_order_count || 0); + payload.skipped_cancelled_order_ids = this.normalizeIdsInput(result.skipped_cancelled_order_ids); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.locked_order_count = Number(cachedProgress.locked_order_count || 0); + payload.skipped_cancelled_order_count = Number(cachedProgress.skipped_cancelled_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_LOCK_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量锁定任务ID。 + * + * 格式:order_lock_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchLockTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `order_lock_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量锁定任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchLockTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量锁定的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchLockOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量锁定任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchLockTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_LOCK_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量锁定任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchLockTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchLockTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchLockTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_LOCK_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchLock] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量锁定任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchLockTaskProgress(taskId = '') { + const cacheKey = this.getBatchLockTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchLock] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量锁定后台任务。 + * + * 直接对给定订单ID数组,将 lock_status 更新为 'warehouse',并写入操作日志 ORDER_LOCK。 + * 已取消(status='cancel')订单为终态,不参与锁定,会通过 skipped_cancelled_order_ids 透出。 + * 仅处理当前仓库上下文内的订单,每批最多 500 条。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchLockTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchLockTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchLockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + locked_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'status' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const lockedOrderIds = []; + const skippedCancelledOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + // 已取消订单为终态,不能再锁定;锁定后再解锁会让订单停留在取消态且带上锁定标记,无法正常出库 + const lockableOrderRows = []; + for (const row of normalizedOrderRows) { + const orderId = Number(row && row.id); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + if (String(row && row.status || '').trim() === PENDING_CANCEL_STATUS) { + skippedCancelledOrderIds.push(orderId); + continue; + } + lockableOrderRows.push(row); + } + + const totalOrderCount = orderIds.length; + const validOrderCount = lockableOrderRows.length; + + await this.setBatchLockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + skipped_cancelled_order_count: skippedCancelledOrderIds.length, + skipped_cancelled_order_ids: skippedCancelledOrderIds, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchLockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + locked_order_count: 0, + skipped_cancelled_order_count: skippedCancelledOrderIds.length, + skipped_cancelled_order_ids: skippedCancelledOrderIds, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + locked_order_ids: [], + locked_order_count: 0, + total_order_count: totalOrderCount, + skipped_cancelled_order_ids: skippedCancelledOrderIds, + skipped_cancelled_order_count: skippedCancelledOrderIds.length, + duration_ms: durationMs, + message: skippedCancelledOrderIds.length > 0 + ? `所选订单均已取消,已跳过 ${skippedCancelledOrderIds.length} 条,不能锁定` + : '未找到可锁定的当前仓库订单', + }, + }); + return; + } + + // 分批更新锁定状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < lockableOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = lockableOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + lock_status: 'warehouse', + updated_at: now, + }; + + const updateResult = await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + status: { + [Op.ne]: PENDING_CANCEL_STATUS, + }, + }, + }); + const affectedCount = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; + + // 查询与更新之间订单可能被取消:回查确认真正落库的订单,避免为未更新成功的订单写锁定日志 + let updatedRows = chunkRows; + if (affectedCount < chunkOrderIds.length) { + const confirmedRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'status' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + const confirmedOrderIds = new Set(); + for (const row of (Array.isArray(confirmedRows) ? confirmedRows : [])) { + const orderId = Number(row && row.id); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + if (String(row && row.status || '').trim() === PENDING_CANCEL_STATUS) { + if (!skippedCancelledOrderIds.includes(orderId)) { + skippedCancelledOrderIds.push(orderId); + } + continue; + } + confirmedOrderIds.add(orderId); + } + updatedRows = chunkRows.filter(row => confirmedOrderIds.has(Number(row.id))); + } + + // 写入操作日志 ORDER_LOCK + const logPayloads = updatedRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: orderId, + operationCode: 'ORDER_LOCK', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newLockStatus: 'warehouse', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchLock] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const row of updatedRows) { + const orderId = Number(row.id); + if (Number.isInteger(orderId) && orderId > 0) { + lockedOrderIds.push(orderId); + } + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((lockedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchLockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + locked_order_count: lockedOrderIds.length, + skipped_cancelled_order_count: skippedCancelledOrderIds.length, + skipped_cancelled_order_ids: skippedCancelledOrderIds, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchLockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + locked_order_count: lockedOrderIds.length, + skipped_cancelled_order_count: skippedCancelledOrderIds.length, + skipped_cancelled_order_ids: skippedCancelledOrderIds, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + locked_order_ids: lockedOrderIds, + locked_order_count: lockedOrderIds.length, + total_order_count: totalOrderCount, + skipped_cancelled_order_ids: skippedCancelledOrderIds, + skipped_cancelled_order_count: skippedCancelledOrderIds.length, + duration_ms: durationMs, + message: skippedCancelledOrderIds.length > 0 + ? `已锁定 ${lockedOrderIds.length} 条订单,已跳过 ${skippedCancelledOrderIds.length} 条已取消订单` + : `已锁定 ${lockedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'BATCH_LOCK_FAILED', + }); + } + } + + /** + * 批量解锁订单(异步任务模式)。 + * + * 将给定订单的 lock_status 批量更新为 'none',并写入操作日志 ORDER_UNLOCK。 + * 仅操作当前仓库上下文内的订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.order_ids 订单ID数组。 + * @param {string} [data.task_id] 可选的任务ID(用于幂等续查)。 + * @return {Promise} 提交响应,含 task_id。 + */ + async batchUnlock(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchUnlockOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchUnlockTaskId(data); + const taskId = requestedTaskId || this.generateBatchUnlockTaskId(warehouseId); + const existingTask = await this.getBatchUnlockTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量解锁任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchUnlockTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + unlocked_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchUnlock] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchUnlockTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchUnlock] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量解锁任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量解锁任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchUnlockTaskProgress(data = {}) { + const taskId = this.normalizeBatchUnlockTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchUnlockTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.unlocked_order_count = Number(cachedProgress.unlocked_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.unlocked_order_count = Number(result.unlocked_order_count || 0); + payload.unlocked_order_ids = this.normalizeIdsInput(result.unlocked_order_ids); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.unlocked_order_count = Number(cachedProgress.unlocked_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_UNLOCK_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量解锁任务ID。 + * + * 格式:order_unlock_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchUnlockTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `order_unlock_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量解锁任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchUnlockTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量解锁的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchUnlockOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量解锁任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchUnlockTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量解锁任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchUnlockTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchUnlockTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchUnlockTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnlock] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量解锁任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchUnlockTaskProgress(taskId = '') { + const cacheKey = this.getBatchUnlockTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnlock] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量解锁后台任务。 + * + * 直接对给定订单ID数组,将 lock_status 更新为 'none',并写入操作日志 ORDER_UNLOCK。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchUnlockTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchUnlockTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + unlocked_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const unlockedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unlocked_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unlocked_order_ids: [], + unlocked_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可解锁的当前仓库订单', + }, + }); + return; + } + + // 分批更新解锁状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + lock_status: 'none', + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 写入操作日志 ORDER_UNLOCK + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: orderId, + operationCode: 'ORDER_UNLOCK', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newLockStatus: 'none', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchUnlock] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + unlockedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((unlockedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unlocked_order_count: unlockedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unlocked_order_count: unlockedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unlocked_order_ids: unlockedOrderIds, + unlocked_order_count: unlockedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已解锁 ${unlockedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'BATCH_UNLOCK_FAILED', + }); + } + } + + /** + * 批量解除拦截订单(异步任务模式)。 + * + * 将给定订单的 intercept_status 批量更新为 'none',并写入操作日志 ORDER_INTERCEPT_CANCEL。 + * 仅操作当前仓库上下文内的订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} [data.order_ids] 订单ID数组(下划线写法)。 + * @param {Array} [data.orderIds] 订单ID数组(驼峰别名)。 + * @param {Array} [data.ids] 订单ID数组(简写别名)。 + * @param {string} [data.task_id] 任务ID(用于查询进度)。 + * @param {string} [data.taskId] 任务ID(驼峰别名)。 + * @return {Promise} 提交结果,包含 task_id、状态与 accepted_at。 + */ + async batchUnintercept(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchUninterceptOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchUninterceptTaskId(data); + const taskId = requestedTaskId || this.generateBatchUninterceptTaskId(warehouseId); + const existingTask = await this.getBatchUninterceptTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量解除拦截任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchUninterceptTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + unintercepted_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchUnintercept] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchUninterceptTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchUnintercept] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量解除拦截任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量解除拦截任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchUninterceptTaskProgress(data = {}) { + const taskId = this.normalizeBatchUninterceptTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchUninterceptTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.unintercepted_order_count = Number(cachedProgress.unintercepted_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.unintercepted_order_count = Number(result.unintercepted_order_count || 0); + payload.unintercepted_order_ids = this.normalizeIdsInput(result.unintercepted_order_ids); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.unintercepted_order_count = Number(cachedProgress.unintercepted_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_UNINTERCEPT_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量解除拦截任务ID。 + * + * 格式:order_unintercept_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchUninterceptTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `order_unintercept_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量解除拦截任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchUninterceptTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量解除拦截的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchUninterceptOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量解除拦截任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchUninterceptTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量解除拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchUninterceptTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchUninterceptTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchUninterceptTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量解除拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchUninterceptTaskProgress(taskId = '') { + const cacheKey = this.getBatchUninterceptTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量解除拦截后台任务。 + * + * 直接对给定订单ID数组,将 intercept_status 更新为 'none' 并同步清空拦截时间 intercept_time(置为 null), + * 同时写入操作日志 ORDER_INTERCEPT_CANCEL。 + * 同时释放订单对应的拦截锁定库存(intercept_locked_quantity 回落到可用数量,失败不阻断主流程)。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchUninterceptTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchUninterceptTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + unintercepted_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const uninterceptedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unintercepted_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unintercepted_order_ids: [], + unintercepted_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可解除拦截的当前仓库订单', + }, + }); + return; + } + + // 分批更新解除拦截状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + intercept_status: 'none', + intercept_time: null, + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 同步清除运单表拦截标记(退回收到标记 is_back 保持不变,由退回收货流程单独管理) + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'N' }, + { where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 清除运单拦截标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}` + ); + } + + // 注意:解除拦截不操作拦截锁定数量字段——业务上「拦截→取消拦截」两个环节均不动库存口径, + // 拦截锁定数量仅在库内拦截确定(confirmIntercept/interceptScan)时占用, + // 其回落由后续特定的入库处理链路统一接管,取消拦截环节不做释放。 + + // 写入操作日志 ORDER_INTERCEPT_CANCEL + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: orderId, + operationCode: 'ORDER_INTERCEPT_CANCEL', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newInterceptStatus: 'none', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + uninterceptedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((uninterceptedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unintercepted_order_count: uninterceptedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unintercepted_order_count: uninterceptedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unintercepted_order_ids: uninterceptedOrderIds, + unintercepted_order_count: uninterceptedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已解除拦截 ${uninterceptedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'BATCH_UNINTERCEPT_FAILED', + }); + } + } + + /** + * 手工录入运单号。 + * + * 为指定待处理订单创建一条运单记录(wms_order_express 表), + * 仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。 + * 完成后同步更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印。 + * + * @param {Object} data 请求体。 + * @param {number|string} data.order_id 订单ID(必填)。 + * @param {string} data.waybill_code 运单号(必填)。 + * @param {string} [data.logistics_interface_name] 物流接口名称(选填,手工填入的值)。 + * @return {Promise} 统一 success 包装,含创建的运单记录。 + */ + async manualWaybill(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + // 1. 参数校验 + const orderId = Number(requestData.order_id); + if (!Number.isInteger(orderId) || orderId <= 0) { + throw new Error('order_id 必须为正整数'); + } + + const waybillCode = String(requestData.waybill_code || '').trim(); + if (!waybillCode) { + throw new Error('waybill_code(运单号)不能为空'); + } + + const logisticsInterfaceName = String(requestData.logistics_interface_name || '').trim() || null; + + // 1.1 可选参数:快递编码。传入时参考 updateOrderExpress 的行为,同步修改订单的快递信息 + const expressCodeRaw = String(requestData.express_code || '').trim(); + let expressResolved = null; + if (expressCodeRaw) { + // 使用带缓存的仓库快递列表 + const expressList = await this.service.systems.express.getExpressList(); + const expressItem = Array.isArray(expressList) + ? expressList.find(item => String(item.code || item.value || '').trim() === expressCodeRaw) + : null; + + if (!expressItem) { + throw new Error(`快递编码 ${expressCodeRaw} 不存在`); + } + + let sysLogisticsCode; + let sysLogisticsName; + let logisticsCode; + let logisticsName; + + if (expressItem.is_system_setting) { + // 自定义映射:express_code 字段存储对应的系统快递编码 + sysLogisticsCode = String(expressItem.express_code || '').trim(); + // 系统快递名称从列表中查找 + const sysItem = expressList.find(item => !item.is_system_setting && String(item.code || '').trim() === sysLogisticsCode); + sysLogisticsName = sysItem ? String(sysItem.name || '').trim() : sysLogisticsCode; + logisticsCode = expressItem.code; + logisticsName = String(expressItem.alias || expressItem.name || '').trim(); + } else { + // 系统快递:logistics_code/name 与 sys 一致 + sysLogisticsCode = expressItem.code; + sysLogisticsName = String(expressItem.name || '').trim(); + logisticsCode = expressItem.code; + logisticsName = sysLogisticsName; + } + + expressResolved = { + sysLogisticsCode, + sysLogisticsName, + logisticsCode, + logisticsName, + }; + } + + // 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding') + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere([ orderId ], warehouseId); + const order = await model.findOne({ + where, + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_logistics_code', 'sys_logistics_name', 'delivery_order_code', 'source_order_codes' ], + raw: true, + }); + + if (!order) { + throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`); + } + + const allowedSteps = new Set([ 1, 2, 3 ]); + if (!allowedSteps.has(order.step)) { + throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理状态(step 1/2/3)的订单手工录入运单号`); + } + + if (order.outbound_status === PENDING_OUTBOUND_STATUS) { + throw new Error(`订单 ${orderId} 已标记待出库,不允许手工录入运单号`); + } + + // 3. 创建运单记录 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel) { + throw new Error('OrderExpress 模型未加载'); + } + + // 3.0 检查是否已分配运单号:若已有 status=1 的记录,拒绝重复录入 + const existingCompleted = await orderExpressModel.findOne({ + where: { + order_id: orderId, + warehouse_id: Number(order.warehouse_id) || warehouseId, + status: 1, + }, + attributes: [ 'id', 'waybill_code' ], + raw: true, + }); + if (existingCompleted) { + const existingWaybill = String(existingCompleted.waybill_code || '').trim(); + throw new Error( + `订单 ${orderId} 已分配运单号${existingWaybill ? `(${existingWaybill})` : ''},不允许重复手工录入` + ); + } + + // 3.1 计算 business_key 递增:查找当前订单已有最大 business_key,+1 递增 + const maxBusinessKey = await orderExpressModel.max('business_key', { + where: { + order_id: orderId, + warehouse_id: Number(order.warehouse_id) || warehouseId, + }, + }); + const nextBusinessKey = Number.isFinite(Number(maxBusinessKey)) && Number(maxBusinessKey) > 0 + ? Number(maxBusinessKey) + 1 + : 1; + + const expressRecord = await orderExpressModel.create({ + order_id: orderId, + waybill_code: waybillCode, + logistics_interface_name: logisticsInterfaceName, + logistics_code: expressResolved + ? expressResolved.logisticsCode + : String(order.sys_logistics_code || '').trim() || null, + logistics_name: expressResolved + ? expressResolved.logisticsName + : String(order.sys_logistics_name || '').trim() || null, + delivery_order_code: String(order.delivery_order_code || '').trim() || null, + source_order_codes: String(order.source_order_codes || '').trim() || null, + warehouse_id: Number(order.warehouse_id) || warehouseId, + store_id: order.store_id != null ? Number(order.store_id) : null, + business_key: nextBusinessKey, + status: 1, + create_at: new Date(), + }); + + // 3.2 更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印; + // 若传入了 express_code,同步修改订单的快递信息(与 updateOrderExpress 口径一致) + const orderUpdateFields = { + print_status: 'fin', + post_status: 'fin', + updated_at: new Date(), + }; + if (expressResolved) { + orderUpdateFields.sys_logistics_code = expressResolved.sysLogisticsCode; + orderUpdateFields.sys_logistics_name = expressResolved.sysLogisticsName; + orderUpdateFields.logistics_code = expressResolved.logisticsCode; + orderUpdateFields.logistics_name = expressResolved.logisticsName; + } + + await model.update( + orderUpdateFields, + { + where: { + id: orderId, + }, + } + ); + + // 4. 记录操作日志 + try { + await this.ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_MANUAL_WAYBILL', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + waybillCode, + logisticsInterfaceName, + businessKey: nextBusinessKey, + expressRecordId: expressRecord.id, + expressCode: expressCodeRaw || null, + sysLogisticsCode: expressResolved ? expressResolved.sysLogisticsCode : String(order.sys_logistics_code || '').trim() || null, + sysLogisticsName: expressResolved ? expressResolved.sysLogisticsName : String(order.sys_logistics_name || '').trim() || null, + logisticsCode: expressResolved ? expressResolved.logisticsCode : String(order.sys_logistics_code || '').trim() || null, + logisticsName: expressResolved ? expressResolved.logisticsName : String(order.sys_logistics_name || '').trim() || null, + message: expressResolved + ? `手工录入运单号:订单 ${orderId},运单号 ${waybillCode},快递 ${expressResolved.logisticsCode}(${expressResolved.logisticsName})` + : `手工录入运单号:订单 ${orderId},运单号 ${waybillCode}`, + }, + beforeChanges: null, + }); + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.manualWaybill] 写入操作日志失败,不影响业务', logErr); + } + + // 5. 自动同步回传(受合约策略 auto_sync_back 控制) + try { + const storeId = Number(order.store_id) || 0; + if (storeId > 0) { + const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( + Number(order.warehouse_id) || warehouseId, + storeId + ); + if ( + contractConfig + && contractConfig.policy_config + && contractConfig.policy_config.auto_sync_back === 1 + ) { + // SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过 + const autoSyncFilter = await this.filterAutoSyncSnOrderIds({ + orderIds: [ orderId ], + warehouseId: Number(order.warehouse_id) || warehouseId, + source: 'manualWaybill', + }); + if (autoSyncFilter.orderIds.length > 0) { + this.syncOrderIds({ orderIds: autoSyncFilter.orderIds }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] manualWaybill 自动同步失败: ${err.message}` + ); + }); + } + } + } + } catch (err) { + this.ctx.logger.error( + `[auto_sync_back] manualWaybill 自动同步异常: ${err.message}` + ); + } + + const result = { + id: expressRecord.id, + order_id: orderId, + waybill_code: waybillCode, + business_key: nextBusinessKey, + logistics_interface_name: logisticsInterfaceName, + create_at: expressRecord.create_at, + }; + if (expressResolved) { + result.express_code = expressCodeRaw; + result.sys_logistics_code = expressResolved.sysLogisticsCode; + result.sys_logistics_name = expressResolved.sysLogisticsName; + result.logistics_code = expressResolved.logisticsCode; + result.logistics_name = expressResolved.logisticsName; + } + + return this.success('ok', result); + } + + /** + * 取消订单时释放创建锁(lockItemStorages 添加的 wms_stock_warehouse.locked_quantity)。 + * + * 直接从 wms_order_items 读取 plan_qty,按 stock_id 汇总后释放对应 wms_stock_warehouse.locked_quantity。 + * 不依赖 wms_picking / wms_storage(储位分配的锁由 cancelAllocateStorage 负责释放)。 + * + * @param {Object} options - 释放参数。 + * @param {number[]} options.orderIds - 订单ID 数组。 + * @param {number} options.warehouseId - 仓库ID。 + * @param {Object} [options.transaction] - 可选外部事务;传入时复用,由调用方负责提交与回滚。 + * @return {Promise} + */ + async releaseCreationLockForCancel({ orderIds, warehouseId, transaction: externalTransaction } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!Array.isArray(orderIds) || orderIds.length === 0 || !warehouseId) { + return; + } + + const stockModel = ctx.model.StockWarehouse; + if (!stockModel) { + ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] StockWarehouse 模型不可用,跳过库存释放'); + return; + } + + const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (!OrderItemsModel) { + ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] OrderItems 模型不可用,跳过库存释放'); + return; + } + + const transaction = externalTransaction || await ctx.model.transaction(); + + try { + // 直接从 order_items 读取 plan_qty,按 stock_id 汇总 + const orderItems = await OrderItemsModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + }, + attributes: [ 'stock_id', 'plan_qty' ], + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + if (!Array.isArray(orderItems) || orderItems.length === 0) { + if (!externalTransaction) { + await transaction.commit(); + } + return; + } + + // 按 stock_id 汇总需要释放的创建锁数量 + const stockReleaseMap = new Map(); + for (const item of orderItems) { + const stockId = Number(item.stock_id || 0); + const planQty = Number(item.plan_qty || 0); + if (stockId > 0 && planQty > 0) { + stockReleaseMap.set(stockId, (stockReleaseMap.get(stockId) || 0) + planQty); + } + } + + if (stockReleaseMap.size === 0) { + if (!externalTransaction) { + await transaction.commit(); + } + return; + } + + // 释放 wms_stock_warehouse.locked_quantity + const stockService = ctx.service && ctx.service.systems && ctx.service.systems.stockStore; + for (const [ stockId, quantity ] of stockReleaseMap.entries()) { + const releaseResult = await stockService.updateLockedQuantity( + stockId, -Number(quantity), transaction, { + remark: '系统取消订单-释放创建锁', + orderType: 'ORDER_CANCEL', + orderNo: orderIds.join(','), + orderId: 0, + } + ); + + if (!releaseResult.success) { + throw new Error(`库存主记录锁定数量不足,无法释放创建锁: stockId=${stockId}, quantity=${quantity}, ${releaseResult.error}`); + } + } + + if (!externalTransaction) { + await transaction.commit(); + } + } catch (error) { + if (!externalTransaction) { + try { + await transaction.rollback(); + } catch (rollbackError) { + ctx.logger.error('[PendingOrderService.releaseCreationLockForCancel] 回滚失败', rollbackError); + } + } + throw error; + } + } + + // ========== allocateSubOrderNumber 子单号分配 ========== + + /** + * 分配子单号(异步任务模式)。 + * + * 为指定订单按 business_key(从 2 开始)逐个子单号分配运单号。 + * 将所有 business_key 全量传入 createWaybillCodePipeline, + * 由 pipeline 内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引 + * 保证并发安全:已分配(status=1)自动跳过,未分配 INSERT status=0 占位后分配。 + * + * @param {Object} data 请求体。 + * @param {number|string} data.order_id 订单ID(必填)。 + * @param {number} data.sub_order_count 子单号数量(必填,>=1)。 + * @return {Promise} 统一 success 包装,立即返回 task_id。 + */ + async allocateSubOrderNumber(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + + // 1. 参数校验 + const orderId = Number(requestData.order_id); + if (!Number.isInteger(orderId) || orderId <= 0) { + throw new Error('order_id 必须为正整数'); + } + + const subOrderCount = Number(requestData.sub_order_count); + if (!Number.isInteger(subOrderCount) || subOrderCount < 1) { + throw new Error('sub_order_count 必须为正整数且 >= 1'); + } + + // 2. 查询订单并校验状态 + // 先查 current 表;若不存在再查 dispatch 表(配送中订单可能已被定时任务迁移到 dispatch) + let model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere([ orderId ], warehouseId); + let order = await model.findOne({ + where, + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'status' ], + raw: true, + }); + + if (!order) { + model = await this.getOrderModelByTableType('dispatch', warehouseId); + order = await model.findOne({ + where, + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'status' ], + raw: true, + }); + } + + if (!order) { + throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`); + } + + if (order.status === PENDING_CANCEL_STATUS) { + throw new Error(`订单 ${orderId} 已取消,不允许分配子单号`); + } + + const allowedSteps = new Set([ 1, 2, 3, 4 ]); + if (!allowedSteps.has(order.step)) { + throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理(step 1/2/3)或配送中(step 4)的订单分配子单号`); + } + + // 仅待处理阶段(step 1/2/3)校验 outbound_status;配送中(step 4)不校验 + if (order.step !== 4 && order.outbound_status === PENDING_OUTBOUND_STATUS) { + throw new Error(`订单 ${orderId} 已标记待出库,不允许分配子单号`); + } + + // 3. 计算 business_key 列表(从 2 开始) + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel) { + throw new Error('OrderExpress 模型未加载'); + } + + // 3.1 校验主单号:必须已有 business_key=1 且 status=1 的主单号,才能拆子单号 + const { Op } = this.app.Sequelize; + const mainWaybill = await orderExpressModel.findOne({ + where: { + order_id: orderId, + warehouse_id: Number(order.warehouse_id) || warehouseId, + business_key: 1, + status: 1, + }, + attributes: [ 'id' ], + raw: true, + }); + if (!mainWaybill) { + throw new Error(`订单 ${orderId} 尚未分配主单号,请先分配主单号后再拆子单号`); + } + + const businessKeys = []; + for (let i = 0; i < subOrderCount; i++) { + businessKeys.push(2 + i); + } + + // 4. 预查已有的已分配运单号(status=1),仅用于初始 details 展示与全部跳过优化 + const existingCompleted = await orderExpressModel.findAll({ + where: { + order_id: orderId, + warehouse_id: Number(order.warehouse_id) || warehouseId, + status: 1, + business_key: { [Op.in]: businessKeys }, + }, + attributes: [ 'business_key', 'waybill_code' ], + raw: true, + }); + + const completedBusinessKeyMap = new Map(); + if (Array.isArray(existingCompleted)) { + for (const row of existingCompleted) { + completedBusinessKeyMap.set(Number(row.business_key), String(row.waybill_code || '').trim()); + } + } + + // 5. 生成任务ID,立即返回 + const taskId = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const taskPayload = { + task_id: taskId, + order_id: orderId, + status: 'submitted', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.submitted, + message: '子单号分配任务已提交', + result: { + total_count: businessKeys.length, + skip_count: completedBusinessKeyMap.size, + pending_count: businessKeys.length - completedBusinessKeyMap.size, + business_keys: businessKeys, + skipped_business_keys: businessKeys.filter(bk => completedBusinessKeyMap.has(bk)), + pending_business_keys: businessKeys.filter(bk => !completedBusinessKeyMap.has(bk)), + details: businessKeys.map(bk => ({ + business_key: bk, + status: completedBusinessKeyMap.has(bk) ? 'skipped' : 'pending', + waybill_code: completedBusinessKeyMap.get(bk) || null, + })), + }, + error: '', + }; + await this.setAllocateSubOrderTaskProgress(taskId, taskPayload); + + // 6. 如果全部已分配,跳过 pipeline 直接完成 + if (completedBusinessKeyMap.size === businessKeys.length) { + await this.setAllocateSubOrderTaskProgress(taskId, { + ...taskPayload, + status: 'success', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success, + message: '子单号分配完成(全部已分配,无待处理项)', + }); + return this.success('ok', { + ...taskPayload, + status: 'success', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success, + message: '子单号分配完成(全部已分配,无待处理项)', + update_time: Date.now(), + }); + } + + // 7. 后台异步执行分配(全量 business_key 传入 pipeline,由其内部事务保证去重与并发安全) + const orderWarehouseId = Number(order.warehouse_id) || warehouseId; + setImmediate(async () => { + try { + await this.setAllocateSubOrderTaskProgress(taskId, { + ...taskPayload, + status: 'running', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.running, + message: '子单号分配处理中', + }); + + // 全量传入(含已分配的),pipeline 内部 createWaybillCode 事务会跳过 status=1 的记录 + const ordersForPipeline = businessKeys.map(bk => ({ + order_id: orderId, + business_key: bk, + sys_platform_code: order.sys_platform_code, + logistics_code: order.logistics_code, + sys_platform_name: order.sys_platform_name, + logistics_name: order.logistics_name, + store_id: order.store_id, + warehouse_id: Number(order.warehouse_id) || warehouseId, + })); + + const pipelineResult = await this.service.systems.express.createWaybillCodePipeline( + ordersForPipeline, + { awaitTasks: true } + ); + + // 需要回 OMS 取号的订单会被本地流水线整体跳过(含全部 business_key), + // 这里改由 OMS 取号;OMS 每次真实取号并透传 printinfo/signature, + // 因此同一订单的不同包裹能各自拿到面单。 + const skippedSubOmsOrderIds = Array.isArray(pipelineResult && pipelineResult.skipped_need_oms_waybill_order_ids) + ? pipelineResult.skipped_need_oms_waybill_order_ids.map(orderId => Number(orderId)) + : []; + let omsSubResult = null; + let omsSubError = ''; + if (skippedSubOmsOrderIds.length > 0) { + try { + omsSubResult = await this.service.systems.express.requestOmsWaybills( + ordersForPipeline.filter(order => skippedSubOmsOrderIds.includes(Number(order.order_id))), + { warehouseId: orderWarehouseId } + ); + } catch (error) { + omsSubError = error && error.message ? String(error.message) : String(error); + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 回 OMS 取号失败,已按订单异常记录', { + orderId, + businessKeys, + error: omsSubError, + }); + } + } + + // 回查最终分配结果 + const updatedDetails = await this.buildSubOrderDetails(orderId, orderWarehouseId, businessKeys); + + const successCount = updatedDetails.filter(d => d.status === 'allocated' || d.status === 'skipped').length; + const isPartial = successCount < businessKeys.length; + + await this.setAllocateSubOrderTaskProgress(taskId, { + ...taskPayload, + status: isPartial ? 'partial' : 'success', + progress: isPartial ? ALLOCATE_SUB_ORDER_PROGRESS_MAP.partial : ALLOCATE_SUB_ORDER_PROGRESS_MAP.success, + message: isPartial + ? `子单号分配部分完成(${successCount}/${businessKeys.length})` + : '子单号分配完成', + result: { + ...taskPayload.result, + pipeline_result: pipelineResult, + ...(omsSubResult ? { oms: omsSubResult } : {}), + ...(omsSubError ? { oms_error: omsSubError } : {}), + details: updatedDetails, + }, + }); + + // 写入操作日志(成功) + try { + await this.writeAllocateSubOrderLog(orderId, orderWarehouseId, { + action: isPartial ? 'SUCCESS_PARTIAL' : 'SUCCESS', + subOrderCount: businessKeys.length, + successCount, + details: updatedDetails, + }); + } catch (logErr) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入成功操作日志失败: %s', + logErr && logErr.message ? logErr.message : logErr); + } + } catch (error) { + const errorMessage = error && error.message ? error.message : String(error); + + await this.setAllocateSubOrderTaskProgress(taskId, { + ...taskPayload, + status: 'failed', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.failed, + message: '子单号分配失败', + error: errorMessage, + }); + + // 写错误信息到 order_flag(尝试 current 和 dispatch 两张表) + try { + await this.writeAllocateSubOrderErrorFlag(orderId, orderWarehouseId, errorMessage); + } catch (flagErr) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入 order_flag 失败: %s', + flagErr && flagErr.message ? flagErr.message : flagErr); + } + + // 写入操作日志(失败) + try { + await this.writeAllocateSubOrderLog(orderId, orderWarehouseId, { + action: 'FAILED', + errorMessage, + }); + } catch (logErr) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入失败操作日志失败: %s', + logErr && logErr.message ? logErr.message : logErr); + } + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 写入子单号分配的 order_flag 错误信息。 + * 尝试更新 current 和 dispatch 两张表,任一成功即返回。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {string} errorMessage 错误信息。 + * @return {Promise} 无返回值。 + */ + async writeAllocateSubOrderErrorFlag(orderId, warehouseId, errorMessage) { + const flag = `[子单号分配失败] ${errorMessage}`.substring(0, 500); + const where = this.buildOrderWhere([ orderId ], warehouseId); + const updatePayload = { order_flag: flag, updated_at: new Date() }; + + // 尝试 current 表 + try { + const currentModel = await this.getOrderModel('order', warehouseId); + if (currentModel && typeof currentModel.update === 'function') { + const [ affected ] = await currentModel.update(updatePayload, { where }); + if (Number(affected) > 0) return; + } + } catch (err) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] current 表写入 order_flag 失败: %s', + err && err.message ? err.message : err); + } + + // 尝试 dispatch 表 + try { + const dispatchModel = await this.getOrderModelByTableType('dispatch', warehouseId); + if (dispatchModel && typeof dispatchModel.update === 'function') { + await dispatchModel.update(updatePayload, { where }); + } + } catch (err) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] dispatch 表写入 order_flag 失败: %s', + err && err.message ? err.message : err); + } + } + + /** + * 写入子单号分配的操作日志。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} opts 日志详情。 + * @param {string} opts.action 操作动作(SUCCESS/SUCCESS_PARTIAL/FAILED)。 + * @param {number} [opts.subOrderCount] 子单总数。 + * @param {number} [opts.successCount] 成功数。 + * @param {string} [opts.errorMessage] 错误信息。 + * @param {Array} [opts.details] 分配详情。 + * @return {Promise} 无返回值。 + */ + async writeAllocateSubOrderLog(orderId, warehouseId, opts = {}) { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + const now = new Date(); + + // 状态中文映射 + const STATUS_CN = { allocated: '成功', failed: '失败', skipped: '跳过', pending: '处理中' }; + const detailSummary = Array.isArray(opts.details) + ? opts.details.slice(0, 10).map(d => { + const cn = STATUS_CN[d.status] || d.status; + let seg = `子单${d.business_key}:${cn}`; + if (d.status === 'failed' && d.note) { + seg += `(${d.note})`; + } + return seg; + }).join(', ') + : ''; + + let message = `子单号分配${opts.action === 'FAILED' ? '失败' : '完成'}`; + if (opts.action === 'SUCCESS_PARTIAL') { + message = `子单号分配部分完成(${opts.successCount}/${opts.subOrderCount})`; + } + if (opts.errorMessage) { + message += ` - ${opts.errorMessage}`; + } + if (detailSummary) { + message += ` | ${detailSummary}`; + } + + const logRow = { + business_type: 'order', + business_id: String(orderId), + operation_code: '子单号分配', + operator_id: operator.id, + operator_name: operator.name, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: message.substring(0, 1000), + created_at: now, + }; + + if (this.ctx.model && this.ctx.model.OperationLog) { + await this.ctx.model.OperationLog.create(logRow); + } else if (this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog) { + await this.ctx.service.systems.operationLog.createOperationLog(logRow); + } + } + + /** + * 查询子单号分配任务进度。 + * + * 可按 task_id 或 business_key 查询。 + * 若传入 business_key,返回该 business_key 对应的分配详情。 + * + * @param {Object} data 请求体。 + * @param {string} data.task_id 任务ID。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @param {number} [data.business_key] 子单号业务ID(可选,按业务ID过滤)。 + * @param {number} [data.businessKey] 子单号业务ID(可选,驼峰写法)。 + * @return {Promise} 统一 success 包装。 + */ + async allocateSubOrderNumberProgress(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const taskId = String(requestData.task_id || requestData.taskId || '').trim(); + const businessKey = Number(requestData.business_key || requestData.businessKey); + + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found, + message: '任务不存在', + result: null, + error: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getAllocateSubOrderTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found, + message: '任务不存在', + result: null, + error: '', + update_time: Date.now(), + }); + } + + // 如果传入了 business_key,过滤出该业务ID对应的详情 + let filteredResult = cachedTask.result; + if (Number.isInteger(businessKey) && businessKey > 0 && cachedTask.result) { + const details = Array.isArray(cachedTask.result.details) ? cachedTask.result.details : []; + const matchedDetail = details.find(d => Number(d.business_key) === businessKey); + filteredResult = { + ...cachedTask.result, + filtered_business_key: businessKey, + matched_detail: matchedDetail || null, + }; + } + + return this.success('ok', { + ...cachedTask, + result: filteredResult, + update_time: cachedTask.update_time || Date.now(), + }); + } + + // ========== allocateSubOrderNumber 缓存工具方法 ========== + + /** + * 获取子单号分配任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getAllocateSubOrderTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入子单号分配任务进度。 + * + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态与结果。 + * @return {Promise} + */ + async setAllocateSubOrderTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + order_id: safePayload.order_id || null, + status: String(safePayload.status || 'unknown').trim(), + progress: Number(safePayload.progress || 0), + message: String(safePayload.message || ''), + result: safePayload.result || null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取子单号分配任务进度。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存结果。 + */ + async getAllocateSubOrderTaskProgress(taskId = '') { + const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 回查子单号分配结果详情(pipeline 执行后调用)。 + * + * 根据 order_express 表最终状态判断每个 business_key 的结果: + * - status=1 且 waybill_code 非空 → allocated(本次分配成功或之前已分配) + * - status=0 → pipeline 占位但 API 未完成 → failed + * - 无记录 → failed(pipeline 未处理到) + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number[]} businessKeys 全部 business_key 列表。 + * @return {Promise>} 每个 business_key 的分配详情。 + */ + async buildSubOrderDetails(orderId, warehouseId, businessKeys) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel) { + return businessKeys.map(bk => ({ + business_key: bk, + status: 'unknown', + waybill_code: null, + note: 'OrderExpress 模型未加载', + })); + } + + const { Op } = this.app.Sequelize; + const allRecords = await orderExpressModel.findAll({ + where: { + order_id: orderId, + warehouse_id: warehouseId, + business_key: { [Op.in]: businessKeys }, + }, + attributes: [ 'business_key', 'waybill_code', 'status' ], + raw: true, + }); + + const recordMap = new Map(); + if (Array.isArray(allRecords)) { + for (const row of allRecords) { + // 同一 business_key 可能有多条(status 不同),优先取 status=1 的 + const existing = recordMap.get(Number(row.business_key)); + if (!existing || Number(row.status) === 1) { + recordMap.set(Number(row.business_key), row); + } + } + } + + // 兜底:如果 order_express 中一条记录都没有,尝试从订单表的 order_flag 获取异常信息 + let orderFlagNote = ''; + if (recordMap.size === 0) { + try { + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + // 查 current 表 + let orderModel = await this.getOrderModel('order', warehouseId); + let orderRow = await orderModel.findOne({ + where: orderWhere, + attributes: [ 'order_flag' ], + raw: true, + }); + // 查 dispatch 表兜底 + if (!orderRow) { + orderModel = await this.getOrderModelByTableType('dispatch', warehouseId); + orderRow = await orderModel.findOne({ + where: orderWhere, + attributes: [ 'order_flag' ], + raw: true, + }); + } + if (orderRow && orderRow.order_flag) { + orderFlagNote = `(订单异常: ${String(orderRow.order_flag).trim()})`; + } + } catch (err) { + // 查 order_flag 失败不影响主流程 + this.ctx.logger.warn('[pendingOrder.buildSubOrderDetails] 查询 order_flag 失败: %s', + err && err.message ? err.message : err); + } + } + + return businessKeys.map(bk => { + const record = recordMap.get(bk); + if (record && Number(record.status) === 1 && String(record.waybill_code || '').trim()) { + return { + business_key: bk, + status: 'allocated', + waybill_code: String(record.waybill_code || '').trim(), + note: '子单号分配成功', + }; + } + + if (record && Number(record.status) === 0) { + return { + business_key: bk, + status: 'failed', + waybill_code: null, + note: '运单占位已创建但 API 未返回运单号(status=0)', + }; + } + + const baseNote = '未找到分配的运单记录'; + return { + business_key: bk, + status: 'failed', + waybill_code: null, + note: orderFlagNote ? `${baseNote}${orderFlagNote}` : baseNote, + }; + }); + } + + /** + * 批量设置订单为已打印状态。 + * + * 将给定订单 ID 列表中属于当前仓库的订单的 print_status 更新为 'fin'。 + * 先查 current 表(wms_order_delivery_{warehouseId}),再查 dispatch 表 + * (wms_order_delivery_{warehouseId}_dispatch)兜底。 + * 仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。 + * + * @param {Object} data 请求体。 + * @param {Array|number|string} [data.order_ids] 订单ID集合(下划线写法)。 + * @param {Array|number|string} [data.orderIds] 订单ID集合(驼峰别名)。 + * @param {Array|number|string} [data.ids] 订单ID集合(简写别名)。 + * @return {Promise} 统一 success 包装的更新结果。 + */ + async batchMarkPrinted(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const rawIds = requestData.order_ids !== undefined ? requestData.order_ids + : requestData.orderIds !== undefined ? requestData.orderIds + : requestData.ids; + const orderIds = this.normalizeIdsInput(rawIds); + if (orderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const { Op } = this.app.Sequelize; + const now = new Date(); + + const buildWhere = () => ({ + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + print_status: { [Op.ne]: 'fin' }, + }); + + // 1. 先查 current 表 + const currentModel = await this.getOrderModel('order', warehouseId); + const currentWhere = { + ...this.buildOrderWhere(orderIds, warehouseId), + ...buildWhere(), + }; + + const [ currentAffected ] = await currentModel.update( + { print_status: 'fin', updated_at: now }, + { where: currentWhere } + ); + let updatedCount = Number(currentAffected || 0); + + // 2. 查询 current 表中已存在的订单 ID,计算出未命中的 ID + const currentFoundRows = await currentModel.findAll({ + attributes: [ 'id' ], + where: this.buildOrderWhere(orderIds, warehouseId), + raw: true, + }); + const currentFoundIds = new Set( + (Array.isArray(currentFoundRows) ? currentFoundRows : []).map(row => Number(row.id)) + ); + const missingIds = orderIds.filter(id => !currentFoundIds.has(id)); + + // 3. dispatch 表兜底 + if (missingIds.length > 0) { + try { + const dispatchModel = await this.ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId); + if (dispatchModel && typeof dispatchModel.update === 'function') { + const dispatchWhere = { + id: { [Op.in]: missingIds }, + warehouse_id: warehouseId, + ...buildWhere(), + }; + + const [ dispatchAffected ] = await dispatchModel.update( + { print_status: 'fin', updated_at: now }, + { where: dispatchWhere } + ); + updatedCount += Number(dispatchAffected || 0); + } + } catch (dispatchErr) { + this.ctx.logger.warn('[PendingOrderService.batchMarkPrinted] dispatch 表更新失败,不影响 current 表结果', dispatchErr); + } + } + + // 写入操作日志(不影响主流程) + try { + const opLogService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function') { + const logPayloads = orderIds.map(orderId => ({ + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_BATCH_MARK_PRINTED', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + message: `批量标记已打印:订单 ${orderId}`, + }, + beforeChanges: null, + })); + await opLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.batchMarkPrinted] 写入操作日志失败,不影响业务', logErr); + } + + return this.success('ok', { + updated_count: updatedCount, + ids: orderIds, + }); + } + +} + +module.exports = PendingOrderService; diff --git a/app/service/systemMethods/order/pendingOrder2b.js b/app/service/systemMethods/order/pendingOrder2b.js new file mode 100644 index 0000000..865ba02 --- /dev/null +++ b/app/service/systemMethods/order/pendingOrder2b.js @@ -0,0 +1,47 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +/** B2B 列表强制条件 */ +const B2B_FIXED_WHERE = Object.freeze({ is_b2b: 'Y' }); + +/** + * B2B 待处理订单系统方法。 + * + * 查询条件与 order.pendingOrder.list 完全一致(current 分表 + 模块默认 where), + * 仅额外强制 is_b2b='Y',用于 B2B 备货/提货作业的独立列表。 + */ +class PendingOrder2bService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * B2B 待处理订单列表。 + * + * 在 order.pendingOrder.list 的基础上强制 is_b2b='Y',并附加 wms_order_b2b 作业明细字段 + * (total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds / + * is_picked_up / picked_up_at / created_at / prep_at)。 + * + * @param {Object} data 请求体(与 order.pendingOrder.list 一致)。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + const warehouseId = this.getWarehouseId(); + const result = await this.listByModule('pendingOrder', data, { + fixedWhere: B2B_FIXED_WHERE, + b2bDetailFilter: true, + }); + return { + ...result, + list: await this.attachB2bJobDetail(result.list, warehouseId), + }; + } +} + +module.exports = PendingOrder2bService; diff --git a/app/service/systemMethods/order/print.js b/app/service/systemMethods/order/print.js new file mode 100644 index 0000000..4c34b93 --- /dev/null +++ b/app/service/systemMethods/order/print.js @@ -0,0 +1,176 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class OrderPrintService extends OrderBaseService { + /** + * 初始化订单打印模块的免登录、免权限、免日志和免鉴权配置。 + * + * @param {Egg.Context} ctx 请求上下文。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; + const _noNeedLog = 'unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; + const _noNeedAuth = 'getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 获取波次平台打印中间态数据。 + * + * method 层仅负责参数解构与边界校验,具体业务查询与打印数据组装由 systems 层实现。 + * + * @param {Object} data 请求体。 + * @param {Array} data.wave_ids 波次ID数组。 + * @param {number|string} data.warehouse_id 仓库ID。 + * @return {Promise} 统一 success 包装的平台打印中间态结果。 + */ + async getWavePlatformPrintData(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + wave_ids: waveIds, + warehouse_id: warehouseId, + } = requestData; + + if (!Array.isArray(waveIds) || waveIds.length === 0) { + throw new Error('wave_ids 必填,且必须为非空数组'); + } + + if (warehouseId === undefined || warehouseId === null || String(warehouseId).trim() === '') { + throw new Error('warehouse_id 必填'); + } + + const result = await this.service.systems.orderPrint.getWavePlatformPrintData({ + waveIds, + warehouseId, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } + + /** + * 按订单ID拉取平台打印中间态数据。 + * + * method 层仅负责参数解构与边界校验,具体业务查询与打印数据组装由 systems 层实现。 + * 仓库ID统一从当前上下文获取,无需调用方传入。 + * + * @param {Object} data 请求体。 + * @param {Array} data.order_ids 订单ID数组。 + * @return {Promise} 统一 success 包装的平台打印中间态结果。 + */ + async getOrderPrintData(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + order_ids: orderIds, + } = requestData; + + if (!Array.isArray(orderIds) || orderIds.length === 0) { + throw new Error('order_ids 必填,且必须为非空数组'); + } + + const result = await this.service.systems.orderPrint.getOrderPrintData({ + orderIds, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } + + /** + * 按运单号数组拉取平台打印中间态数据。 + * + * method 层仅负责参数解构与边界校验,具体业务查询与打印数据组装由 systems 层实现。 + * 仓库ID统一从当前上下文获取,无需调用方传入。 + * + * @param {Object} data 请求体。 + * @param {Array} data.waybill_codes 运单号数组。 + * @return {Promise} 统一 success 包装的平台打印中间态结果。 + */ + async getPrintDataByWaybillCodes(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_codes: waybillCodes, + } = requestData; + + if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) { + throw new Error('waybill_codes 必填,且必须为非空数组'); + } + + const result = await this.service.systems.orderPrint.getPrintDataByWaybillCodes({ + waybillCodes, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } + + /** + * 按分组解锁波次平台打印锁。 + * + * method 层仅负责参数解构与边界校验,具体解锁逻辑由 systems 层实现。 + * + * @param {Object} data 请求体。 + * @param {Array} data.wave_ids 波次ID数组。 + * @param {number|string} data.warehouse_id 仓库ID。 + * @param {string} [data.group_type='platform_express'] 分组类型,支持 platform、platform_express、order。 + * @param {string} [data.unlock_scope='group'] 解锁范围,支持 group、wave。 + * @param {Array} data.groups 分组条件列表。 + * @return {Promise} 统一 success 包装的解锁结果。 + */ + async unlockWavePlatformPrintDataByGroup(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + wave_ids: waveIds, + warehouse_id: warehouseId, + group_type: groupType = 'platform_express', + unlock_scope: unlockScope = 'group', + groups, + } = requestData; + + if (!Array.isArray(waveIds) || waveIds.length === 0) { + throw new Error('wave_ids 必填,且必须为非空数组'); + } + + if (warehouseId === undefined || warehouseId === null || String(warehouseId).trim() === '') { + throw new Error('warehouse_id 必填'); + } + + const normalizedGroupType = String(groupType || '').trim(); + if (![ 'platform', 'platform_express', 'order' ].includes(normalizedGroupType)) { + throw new Error('group_type 仅支持 platform、platform_express、order'); + } + + const normalizedUnlockScope = String(unlockScope || '').trim(); + if (![ 'group', 'wave' ].includes(normalizedUnlockScope)) { + throw new Error('unlock_scope 仅支持 group、wave'); + } + + if (!Array.isArray(groups) || groups.length === 0) { + throw new Error('groups 必填,且必须为非空数组'); + } + + const result = await this.service.systems.orderPrint.unlockWavePlatformPrintDataByGroup({ + waveIds, + warehouseId, + groupType: normalizedGroupType, + unlockScope: normalizedUnlockScope, + groups, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } +} + +module.exports = OrderPrintService; diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js new file mode 100644 index 0000000..cdfd851 --- /dev/null +++ b/app/service/systemMethods/order/recheckOrder.js @@ -0,0 +1,5683 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class RecheckOrderService extends OrderBaseService { + /** + * 初始化复核订单系统方法免登录、免权限、免日志与免鉴权配置。 + * @param {Egg.Context} ctx 请求上下文。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList,interceptScan'; + const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,interceptScan'; + const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList,interceptScan'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 扫描关键词并返回以波次为单位的复核视图。 + * 支持运单号、波次号、车号三种匹配模式,并根据波次拣货模式自动分派散单/团购视图。 + * - 运单号/波次号命中散单波次(pick_mode=2/3/4):返回扁平化订单列表 list_type='single', + * 顶层携带波次/拣货人/策略/任务ID等汇总信息,list 为扁平订单数组 + * - 运单号/波次号命中团购波次(pick_mode=1/5):自动转为团购模式, + * 返回嵌套波次结构 list_type='group',每项含波次号、波次内订单明细(含 stock 商品明细)及相关汇总信息 + * - 车号匹配(团购模式 pick_mode=1/5):返回拣货任务下所有团购波次及订单,list_type='group',保持嵌套结构, + * 顶层携带 picker_id、picker_name、task_id + * - 车号匹配(散单模式 pick_mode=2/3/4):查询任务关联的所有波次,逐波次构建扫描视图后合并, + * 返回 list_type='single',按 order_id 去重,未复核订单排前,顶层携带汇总字段 + * - 运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs、 + * items_weight、suggested_package_material) + * - 所有模式的 list[] 每项均附带 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null) + * - 任一模式首次成功加载波次复核视图时,回写该波次的复核开始时间(recheck_start_time), + * 仅首次写入(按 IS NULL 条件更新),回写失败仅告警、不影响扫描主流程 + * @param {Object} data 请求体。 + * @param {string} [data.keyword] 通用扫描关键词。 + * @param {string} [data.value] 通用扫描关键词别名。 + * @param {string} [data.waybill_no] 运单号。 + * @param {string} [data.waybillCode] 运单号别名。 + * @param {string} [data.waybill_code] 运单号别名。 + * @param {string} [data.wave_no] 波次号。 + * @param {string} [data.waveNo] 波次号别名。 + * @param {string} [data.cart_code] 车号。 + * @param {string} [data.cartCode] 车号别名。 + * @return {Promise} 扫描结果,包含 match_type、list_type、picker_id、picker_name、task_id(散单/团单均有)与 list 数组, + * list 每项含 items_weight、suggested_package_material。 + */ + async scanOrder(data = {}) { + const warehouseId = this.getWarehouseId(); + const keyword = this.resolveScanKeyword(data); + const matchedResult = await this.pickOrderMatchByKeyword(keyword); + const { orderId, matchType, cartMatchContext, waveMatchContext } = matchedResult; + + // 散单处理:运单号匹配 → 查找订单所在波次 → 拉取波次全量订单 + if (matchType === 'waybill') { + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const order = await orderModel.findOne({ + where: this.buildOrderWhere([ orderId ], warehouseId), + attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status', 'intercept_status', 'delivery_order_code' ], + raw: true, + }); + + if (!order) { + throw new Error('未找到对应订单'); + } + + const orderWaveId = Number(order.wave_id || 0); + const orderWaveNo = String(order.wave_no || '').trim(); + + if (orderWaveId > 0 && orderWaveNo) { + // 检查波次是否为团购模式(pick_mode=1 团购小波次 / pick_mode=5 团购大波次) + const pickMode = await this.getPickModeByWaveId(orderWaveId, warehouseId); + if (pickMode === 1 || pickMode === 5) { + const groupTaskId = await this.getTaskIdByWaveId(orderWaveId, warehouseId); + if (groupTaskId > 0) { + const [ groupWaveList, pickerInfo ] = await Promise.all([ + this.buildGroupWaveList(groupTaskId, warehouseId), + this.getPickerInfoByTaskId(groupTaskId, warehouseId), + ]); + await this.markWaveRecheckStart( + groupWaveList.map(item => Number(item.wave_id || 0)), + warehouseId + ); + return { + match_type: matchType, + list_type: 'group', + waybill_no: keyword, + wave_id: orderWaveId, + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: groupTaskId, + list: groupWaveList, + }; + } + // 找不到拣货任务时退回单订单详情模式 + this.assertOrderCanRecheck(order); + const detailResult = await this.detail({ id: orderId }); + const fallbackOrder = detailResult.detail || {}; + const fallbackPackageMap = await this.batchQueryPackageMaterialRecommendation( + [{ items_hash: fallbackOrder.items_hash, items_crc: fallbackOrder.items_crc }], + warehouseId + ); + const fallbackItemHash = String(fallbackOrder.items_hash || '').trim(); + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + list: [{ + ...fallbackOrder, + items: Array.isArray(detailResult.items) ? detailResult.items : [], + expresses: Array.isArray(detailResult.expresses) ? detailResult.expresses : [], + logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], + suggested_package_material: fallbackItemHash + ? (fallbackPackageMap.get(fallbackItemHash) || null) + : null, + }], + }; + } + + const scanView = await this.buildSingleWaveScanView(orderWaveId, orderWaveNo, warehouseId); + if (scanView) { + await this.markWaveRecheckStart([ orderWaveId ], warehouseId); + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + ...scanView, + }; + } + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + list: [], + }; + } + + // 无波次信息时退回单订单模式 + this.assertOrderCanRecheck(order); + const detailResult = await this.detail({ id: orderId }); + const noWaveOrder = detailResult.detail || {}; + const noWavePackageMap = await this.batchQueryPackageMaterialRecommendation( + [{ items_hash: noWaveOrder.items_hash, items_crc: noWaveOrder.items_crc }], + warehouseId + ); + const noWaveItemHash = String(noWaveOrder.items_hash || '').trim(); + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + list: [{ + ...noWaveOrder, + items: Array.isArray(detailResult.items) ? detailResult.items : [], + expresses: Array.isArray(detailResult.expresses) ? detailResult.expresses : [], + logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], + suggested_package_material: noWaveItemHash + ? (noWavePackageMap.get(noWaveItemHash) || null) + : null, + }], + }; + } + + // 波次号匹配 → 直接按波次号查找波次及订单(散单/团购分流) + if (matchType === 'wave') { + const waveId = Number(waveMatchContext?.wave?.wave_id || 0); + const waveNo = String(waveMatchContext?.wave?.wave_no || '').trim(); + + if (waveId > 0 && waveNo) { + // 检查波次是否为团购模式(pick_mode=1 团购小波次 / pick_mode=5 团购大波次) + const pickMode = await this.getPickModeByWaveId(waveId, warehouseId); + if (pickMode === 1 || pickMode === 5) { + const groupTaskId = await this.getTaskIdByWaveId(waveId, warehouseId); + if (groupTaskId > 0) { + const [ groupWaveList, pickerInfo ] = await Promise.all([ + this.buildGroupWaveList(groupTaskId, warehouseId), + this.getPickerInfoByTaskId(groupTaskId, warehouseId), + ]); + await this.markWaveRecheckStart( + groupWaveList.map(item => Number(item.wave_id || 0)), + warehouseId + ); + return { + match_type: matchType, + list_type: 'group', + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: groupTaskId, + list: groupWaveList, + }; + } + throw new Error('团购波次未找到对应拣货任务,无法加载复核视图'); + } + + const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId); + if (scanView) { + await this.markWaveRecheckStart([ waveId ], warehouseId); + return { + match_type: matchType, + list_type: 'single', + ...scanView, + }; + } + return { + match_type: matchType, + list_type: 'single', + list: [], + }; + } + + throw new Error('波次信息不完整,无法加载复核视图'); + } + + // 车号匹配 → 查找拣货任务 → 根据 pick_mode 分流团单/散单 + if (matchType === 'cart' && cartMatchContext) { + const taskId = Number(cartMatchContext?.task?.task_id || 0); + + if (taskId > 0) { + const pickMode = Number(cartMatchContext?.task?.pick_mode || 0); + const { ctx } = this; + + // 团购模式(pick_mode 1/5):拉取任务下所有团购波次 + if (pickMode === 1 || pickMode === 5) { + const [ groupWaveList, pickerInfo ] = await Promise.all([ + this.buildGroupWaveList(taskId, warehouseId), + this.getPickerInfoByTaskId(taskId, warehouseId), + ]); + await this.markWaveRecheckStart( + groupWaveList.map(item => Number(item.wave_id || 0)), + warehouseId + ); + return { + match_type: 'cart', + list_type: 'group', + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: taskId, + list: groupWaveList, + }; + } + + // 散单模式(pick_mode 2/3/4):查询任务关联的波次,逐波次构建扫描视图并合并 + const taskWaveRows = await ctx.model.query( + ` + SELECT wave_id, wave_no + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + ORDER BY wave_id ASC + `, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : []; + const scanViews = []; + const scannedWaveIds = []; + + for (const tw of taskWaves) { + const waveId = Number(tw.wave_id || 0); + const waveNo = String(tw.wave_no || '').trim(); + + if (waveId > 0 && waveNo) { + const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId); + + if (scanView) { + scanViews.push(scanView); + scannedWaveIds.push(waveId); + } + } + } + + // 扫描视图构建成功后回写波次复核开始时间(仅首次写入,失败不影响主流程) + await this.markWaveRecheckStart(scannedWaveIds, warehouseId); + + if (scanViews.length === 0) { + return { + match_type: 'cart', + list_type: 'single', + task_id: taskId, + pick_mode: pickMode, + list: [], + }; + } + + // 合并所有波次的订单列表(按 order_id 去重) + const allOrders = scanViews.flatMap(v => (Array.isArray(v.list) ? v.list : [])); + const seenOrderIds = new Set(); + const mergedList = []; + + for (const order of allOrders) { + const oid = Number(order.order_id || 0); + + if (oid > 0 && !seenOrderIds.has(oid)) { + seenOrderIds.add(oid); + mergedList.push(order); + } + } + + // 排序:未复核的排前面,其次按 wave_index 从小到大 + mergedList.sort((a, b) => { + const aReviewed = a.is_reviewed ? 1 : 0; + const bReviewed = b.is_reviewed ? 1 : 0; + + if (aReviewed !== bReviewed) { + return aReviewed - bReviewed; + } + + return (Number(a.wave_index || 0)) - (Number(b.wave_index || 0)); + }); + + const totalOrders = mergedList.length; + // 复核统计仅计非拦截订单(拦截订单保留在 list 中按单提示) + const reviewableOrders = mergedList.filter( + o => !this.isInterceptedOrderStatus(o.intercept_status) + ); + const reviewedCount = reviewableOrders.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = reviewableOrders.length - reviewedCount; + const waveType = scanViews.find(v => Number(v.wave_type || 0) > 0)?.wave_type || 0; + const pickerInfo = await this.getPickerInfoByTaskId(taskId, warehouseId); + + return { + match_type: 'cart', + list_type: 'single', + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: taskId, + wave_id: 0, + wave_no: '', + wave_type: Number(waveType || 0), + pick_mode: pickMode, + strategy_id: null, + strategy_name: '', + total_orders: totalOrders, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + list: mergedList, + }; + } + + throw new Error('拣货任务信息不完整,无法加载复核视图'); + } + + throw new Error('未找到对应订单'); + } + + /** + * 回写波次复核开始时间(仅首次扫描写入)。 + * 对每个有效波次执行条件更新:仅当 recheck_start_time 为空时写入 NOW(),并同步刷新 update_time, + * 与拣货任务开始时间补写惯例(app/service/systems/pick.js)保持一致; + * 多波次场景每个波次各自按 IS NULL 条件判断,已写过复核开始时间的波次不会被覆盖。 + * 回写失败仅记录告警日志,不阻断扫描主流程(如迁移未执行导致字段缺失等场景)。 + * @param {number|Array} waveIds 波次ID或波次ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async markWaveRecheckStart(waveIds, warehouseId) { + const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId || 0); + const sourceWaveIds = Array.isArray(waveIds) ? waveIds : [ waveIds ]; + const normalizedWaveIds = [ ...new Set(sourceWaveIds + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) { + return; + } + + try { + await ctx.model.query( + ` + UPDATE wms_wave_batch + SET recheck_start_time = NOW(), + update_time = NOW() + WHERE wave_id IN (:waveIds) + AND warehouse_id = :warehouseId + AND recheck_start_time IS NULL + `, + { + replacements: { waveIds: normalizedWaveIds, warehouseId: normalizedWarehouseId }, + } + ); + } catch (error) { + ctx.logger.warn( + `[recheckOrder.markWaveRecheckStart] 回写波次复核开始时间失败,不影响扫描主流程, waveIds=${normalizedWaveIds.join(',')}, error=${error.message}` + ); + } + } + + /** + * 通过拣货任务ID刷新复核扫描视图。 + * 根据任务的 pick_mode 区分散单/团单模式,返回与 scanOrder 一致的数据结构,用于前端刷新数据。 + * - 散单模式(pick_mode 2/3/4):扁平化任务下所有波次的订单列表,顶层携带拣货人/任务等汇总信息 + * - 团购模式(pick_mode 1/5):返回任务下所有团购波次及订单的分组列表 + * @param {Object} data 请求体。 + * @param {number} data.task_id 拣货任务ID。 + * @return {Promise} 扫描视图,包含 match_type、list_type、picker_id、picker_name、task_id、list 等字段, + * 散单模式额外包含 pick_mode、total_orders、reviewed_count、unreviewed_count。 + */ + async scanTask(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const taskId = Number(requestData.task_id || 0); + + if (!Number.isFinite(taskId) || taskId <= 0) { + throw new Error('task_id 无效'); + } + + const warehouseId = this.getWarehouseId(); + const { ctx } = this; + + // 查询拣货任务信息 + const taskRows = await ctx.model.query( + ` + SELECT id AS task_id, pick_mode, pick_user_id, pick_user_name + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + + if (!taskRow) { + throw new Error('未找到对应拣货任务'); + } + + const pickMode = Number(taskRow.pick_mode || 0); + + // 查询任务关联的所有波次 + const taskWaveRows = await ctx.model.query( + ` + SELECT wave_id, wave_no + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + ORDER BY wave_id ASC + `, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : []; + + // 团购模式(pick_mode 1 或 5):复用 buildGroupWaveList + if (pickMode === 1 || pickMode === 5) { + const [ groupWaveList, pickerInfo ] = await Promise.all([ + this.buildGroupWaveList(taskId, warehouseId), + this.getPickerInfoByTaskId(taskId, warehouseId), + ]); + + return { + match_type: 'task', + list_type: 'group', + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: taskId, + list: groupWaveList, + }; + } + + // 散单模式(pick_mode 2、3、4):逐波次构建扫描视图并合并 + const scanViews = []; + + for (const tw of taskWaves) { + const waveId = Number(tw.wave_id || 0); + const waveNo = String(tw.wave_no || '').trim(); + + if (waveId > 0 && waveNo) { + const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId); + + if (scanView) { + scanViews.push(scanView); + } + } + } + + if (scanViews.length === 0) { + return { + match_type: 'task', + list_type: 'single', + task_id: taskId, + pick_mode: pickMode, + list: [], + }; + } + + // 合并所有波次的订单列表(按 order_id 去重) + const allOrders = scanViews.flatMap(v => (Array.isArray(v.list) ? v.list : [])); + const seenOrderIds = new Set(); + const mergedList = []; + + for (const order of allOrders) { + const oid = Number(order.order_id || 0); + + if (oid > 0 && !seenOrderIds.has(oid)) { + seenOrderIds.add(oid); + mergedList.push(order); + } + } + + // 排序:未复核的排前面,其次按 wave_index 从小到大 + mergedList.sort((a, b) => { + const aReviewed = a.is_reviewed ? 1 : 0; + const bReviewed = b.is_reviewed ? 1 : 0; + + if (aReviewed !== bReviewed) { + return aReviewed - bReviewed; + } + + return (Number(a.wave_index || 0)) - (Number(b.wave_index || 0)); + }); + + const totalOrders = mergedList.length; + // 复核统计仅计非拦截订单(拦截订单保留在 list 中按单提示) + const reviewableOrders = mergedList.filter( + o => !this.isInterceptedOrderStatus(o.intercept_status) + ); + const reviewedCount = reviewableOrders.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = reviewableOrders.length - reviewedCount; + const waveType = scanViews.find(v => Number(v.wave_type || 0) > 0)?.wave_type || 0; + + return { + match_type: 'task', + list_type: 'single', + picker_id: taskRow.pick_user_id != null ? Number(taskRow.pick_user_id) : null, + picker_name: String(taskRow.pick_user_name || '').trim(), + task_id: taskId, + wave_id: 0, + wave_no: '', + wave_type: Number(waveType || 0), + pick_mode: pickMode, + strategy_id: null, + strategy_name: '', + total_orders: totalOrders, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + list: mergedList, + }; + } + + /** + * 构建散单模式的扁平化扫描复核视图。 + * 将波次信息、拣货人、策略、任务ID等提升到顶层,订单列表扁平化。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号。 + * @param {number} warehouseId 仓库ID。 + * 拦截订单保留在 list 中(带 intercept_status),不参与复核校验与 reviewed/unreviewed/printed 统计, + * 波次内存在拦截订单时不再阻断整个扫描视图加载(与团购模式一致)。 + * @return {Promise} 扁平化扫描视图,包含 picker_id、picker_name、task_id、wave_id、wave_no、 + * wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count、 + * printed_count、unprinted_count、list。 + * list 中每项额外包含 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null)。 + */ + async buildSingleWaveScanView(waveId, waveNo, warehouseId) { + const baseWaveView = await this.buildSingleWaveView(waveId, waveNo, warehouseId); + + if (!baseWaveView) { + return null; + } + + const normalizedWaveId = Number(waveId || 0); + const orders = Array.isArray(baseWaveView.orders) ? baseWaveView.orders : []; + + // 分离拦截订单:拦截订单保留在 list 中由前端按单提示拦截(intercept_status), + // 仅对非拦截订单做复核校验与统计,与团购模式一致, + // 波次内存在拦截订单时不再阻断整个散单扫描视图加载 + const normalOrders = orders.filter( + order => !this.isInterceptedOrderStatus(order.intercept_status) + ); + + // 校验波次内非拦截订单是否都已拣货,未拣货订单不允许复核 + for (const order of normalOrders) { + this.assertOrderCanRecheck(order); + } + + // 并行查询拣货人信息和策略信息 + const [ pickerInfo, strategyInfo ] = await Promise.all([ + this.getPickerInfoByWaveId(normalizedWaveId, warehouseId), + this.getWaveStrategyInfo(normalizedWaveId, warehouseId), + ]); + + // 计算复核汇总(仅统计非拦截订单) + const reviewedCount = normalOrders.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = normalOrders.length - reviewedCount; + + // 计算打印汇总(仅统计非拦截订单) + const printedCount = normalOrders.filter(o => o.is_printed === true).length; + const unprintedCount = normalOrders.length - printedCount; + + // 批量查询包材推荐 + const packageMaterialMap = await this.batchQueryPackageMaterialRecommendation(orders, warehouseId); + + // 查询任务框的 stock_id → box_no 映射(用于先拣后分等散单模式) + const taskId = pickerInfo.task_id; + const boxNoByStockId = new Map(); + if (taskId > 0) { + const { ctx } = this; + const boxRows = await ctx.model.query( + `SELECT ref_id, box_no + FROM wms_wave_pick_task_box + WHERE task_id = :taskId`, + { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + for (const row of (Array.isArray(boxRows) ? boxRows : [])) { + const sid = Number(row.ref_id || 0); + const bno = Number(row.box_no || 0); + if (sid > 0 && bno > 0 && !boxNoByStockId.has(sid)) { + boxNoByStockId.set(sid, bno); + } + } + } + + // 为每个订单附加 items_weight、包材推荐和 stock 中的 box_no + const enrichedOrders = orders.map(order => { + const itemsHash = String(order.items_hash || '').trim(); + const enrichedStock = Array.isArray(order.stock) + ? order.stock.map(stockItem => ({ + ...stockItem, + box_no: boxNoByStockId.get(Number(stockItem.stock_id || 0)) || 0, + })) + : []; + return { + ...order, + stock: enrichedStock, + items_weight: order.items_weight != null ? Number(order.items_weight) : 0, + suggested_package_material: itemsHash ? (packageMaterialMap.get(itemsHash) || null) : null, + }; + }); + + return { + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: pickerInfo.task_id, + wave_id: baseWaveView.wave_id, + wave_no: baseWaveView.wave_no, + wave_type: baseWaveView.wave_type, + pick_mode: baseWaveView.pick_mode, + strategy_id: strategyInfo.strategy_id, + strategy_name: strategyInfo.strategy_name, + total_orders: orders.length, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + printed_count: printedCount, + unprinted_count: unprintedCount, + list: enrichedOrders, + }; + } + + /** + * 构建单个波次的复核视图(散单/团单内部共用)。 + * 查询波次信息、拣货模式、以及波次下全部订单列表。 + * 当 waveNo 为空但 waveId 有效时,通过 waveId 反查 wms_wave_batch 补全 waveNo。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号,可为空字符串,为空时自动反查补全。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 波次视图对象,包含 wave_id、wave_no、wave_type、pick_mode、order_count、orders; + * 当 waveId 无效或 waveNo 无法补全时返回 null。 + */ + async buildSingleWaveView(waveId, waveNo, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + + if (normalizedWaveId <= 0) { + return null; + } + + // 解析 waveNo,为空时通过 waveId 反查 wms_wave_batch 补全 + let normalizedWaveNo = String(waveNo || '').trim(); + if (!normalizedWaveNo) { + const fallbackRows = await ctx.model.query( + ` + SELECT wave_no + FROM wms_wave_batch + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const fallbackRow = Array.isArray(fallbackRows) && fallbackRows.length > 0 ? fallbackRows[0] : null; + if (!fallbackRow || !fallbackRow.wave_no) { + return null; + } + normalizedWaveNo = String(fallbackRow.wave_no).trim(); + } + + // 查询波次批次信息 + const waveRows = await ctx.model.query( + ` + SELECT + wave_id, + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + creator, + create_time, + update_time + FROM wms_wave_batch + WHERE wave_id = :waveId + AND wave_no = :waveNo + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, waveNo: normalizedWaveNo, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + + if (!waveRow) { + return null; + } + + // 查询波次关联的拣货任务,获取 pick_mode + const pickMode = await this.getPickModeByWaveId(normalizedWaveId, warehouseId); + + // 查询波次下所有订单 + const orders = await this.getWaveOrdersBasic(normalizedWaveNo, warehouseId); + const orderCount = orders.length; + + return { + wave_id: Number(waveRow.wave_id || 0), + wave_no: String(waveRow.wave_no || '').trim(), + wave_type: Number(waveRow.wave_type || 0), + wave_status: Number(waveRow.wave_status || 0), + pick_mode: pickMode, + total_orders: Number(waveRow.total_orders || 0), + processed_orders: Number(waveRow.processed_orders || 0), + creator: String(waveRow.creator || '').trim(), + create_time: waveRow.create_time || null, + update_time: waveRow.update_time || null, + order_count: orderCount, + orders, + }; + } + + /** + * 构建团购波次列表视图(团单模式)。 + * 根据拣货任务ID查找关联的所有波次,每个波次展开为一项。 + * 波次内非拦截订单的商品明细按 stock_id 合并,plan_qty 累加,直接输出 stocks 数组; + * 拦截订单单独输出 intercepted 列表。 + * @param {number} taskId 拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 波次视图列表,每项包含 wave_id、wave_no、wave_type、wave_status、 + * pick_mode、total_orders、processed_orders、creator、create_time、update_time、 + * order_count、box_no、reviewed_count、unreviewed_count、printed_count、unprinted_count、 + * stocks(非拦截订单合并后的商品明细)、 + * intercepted(拦截订单列表,仅当波次中存在拦截订单时出现,每项含 wave_index(波次内序号)、order_id、 + * delivery_order_code、waybill_no、intercept_status 等字段)、 + * items_weight(订单商品总重量,取自波次内首个正常订单)、 + * suggested_package_material(推荐包材信息,无推荐时为 null)、 + * first_waybill_no(波次内首个正常订单的运单号,用于包材绑定等后续操作,无正常订单时为第一个订单的运单号,均无则为空字符串)。 + */ + async buildGroupWaveList(taskId, warehouseId) { + const { ctx } = this; + const normalizedTaskId = Number(taskId || 0); + + if (normalizedTaskId <= 0) { + return []; + } + + // 查询拣货任务信息,获取 pick_mode + const taskRows = await ctx.model.query( + ` + SELECT id AS task_id, pick_mode, current_cart_code_snapshot + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { taskId: normalizedTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + + if (!taskRow) { + return []; + } + + const pickMode = Number(taskRow.pick_mode || 0); + + // 查询任务关联的所有波次 + const taskWaveRows = await ctx.model.query( + ` + SELECT wave_id, wave_no, box_no + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + ORDER BY box_no ASC, wave_id ASC + `, + { + replacements: { taskId: normalizedTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : []; + + // 并行查询每个波次的详细信息和订单 + const waveViewPromises = taskWaves.map(async tw => { + const twWaveId = Number(tw.wave_id || 0); + const twWaveNo = String(tw.wave_no || '').trim(); + + if (twWaveId <= 0) { + return null; + } + + const waveView = await this.buildSingleWaveView(twWaveId, twWaveNo, warehouseId); + + if (!waveView) { + return null; + } + + // 分离拦截订单与非拦截订单 + const orders = Array.isArray(waveView.orders) ? waveView.orders : []; + const interceptedOrders = []; + const normalOrders = []; + for (const order of orders) { + const interceptStatus = String(order.intercept_status || '').trim(); + if (this.isInterceptedOrderStatus(interceptStatus)) { + interceptedOrders.push(order); + } else { + normalOrders.push(order); + } + } + + // 校验所有非拦截订单是否都已拣货/未被拦截,不允许复核 + for (const order of normalOrders) { + this.assertOrderCanRecheck(order); + } + + // 团购波次中所有订单商品一致,取第一个正常订单的商品明细作为样板 + const sampleOrder = normalOrders.length > 0 ? normalOrders[0] : null; + const sampleStock = sampleOrder ? (Array.isArray(sampleOrder.stock) ? sampleOrder.stock : []) : []; + const stocks = sampleStock.map(item => ({ + stock_id: Number(item.stock_id || 0), + item_code: String(item.item_code || '').trim(), + item_name: String(item.item_name || '').trim(), + sku_property: String(item.sku_property || '').trim(), + packing_requirements: String(item.packing_requirements || '').trim(), + pick_requirements: String(item.pick_requirements || '').trim(), + recheck_requirements: String(item.recheck_requirements || '').trim(), + merge_requirements: String(item.merge_requirements || 'Y').trim(), + barcodes: Array.isArray(item.barcodes) ? [ ...item.barcodes ] : [], + images: Array.isArray(item.images) ? [ ...item.images ] : [], + has_shared_barcode: Boolean(item.has_shared_barcode), + need_recheck: String(item.need_recheck || 'Y').trim(), + need_sn: String(item.need_sn || 'N').trim().toUpperCase() === 'Y' ? 'Y' : 'N', + sn_code_rules: Array.isArray(item.sn_code_rules) + ? item.sn_code_rules.map(rule => ({ ...rule })) + : [], + plan_qty: Number(item.plan_qty || 0), + store_id: item.store_id != null ? Number(item.store_id) : 0, + owner_code: String(item.owner_code || '').trim(), + store_remark: String(item.store_remark || '').trim(), + })); + + // 构建拦截订单列表(wave_index 即波次内序号,供前端展示拦截订单的序号) + const intercepted = interceptedOrders.map(order => ({ + wave_index: Number(order.wave_index || 0), + order_id: Number(order.order_id || 0), + delivery_order_code: String(order.delivery_order_code || '').trim(), + waybill_no: String(order.waybill_no || '').trim(), + intercept_status: String(order.intercept_status || '').trim(), + })); + + // 计算波次内复核统计(基于非拦截订单的 recheck_status 实时聚合) + const reviewedCount = normalOrders.filter(o => String(o.recheck_status || '').trim() === 'fin').length; + const unreviewedCount = normalOrders.length - reviewedCount; + + // 计算波次内打印统计(基于非拦截订单的 is_printed 字段) + const printedCount = normalOrders.filter(o => o.is_printed === true).length; + const unprintedCount = normalOrders.length - printedCount; + + // 使用任务级别的 pick_mode 覆盖(团单模式下以任务为准) + const result = { + wave_id: waveView.wave_id, + wave_no: waveView.wave_no, + wave_type: waveView.wave_type, + wave_status: waveView.wave_status, + pick_mode: pickMode, + total_orders: waveView.total_orders, + processed_orders: waveView.processed_orders, + creator: waveView.creator, + create_time: waveView.create_time, + update_time: waveView.update_time, + order_count: waveView.order_count, + box_no: Number(tw.box_no || 0), + stocks, + store_id: sampleOrder ? Number(sampleOrder.store_id || 0) : 0, + store_remark: sampleOrder ? String(sampleOrder.store_remark || '').trim() : '', + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + printed_count: printedCount, + unprinted_count: unprintedCount, + }; + + // 仅当存在拦截订单时才追加 intercepted 字段 + if (intercepted.length > 0) { + result.intercepted = intercepted; + } + + // 团购波次内所有订单商品结构一致,暂存样本订单的商品指纹信息用于后续批量查询包材推荐 + result._sample_hash = sampleOrder ? String(sampleOrder.items_hash || '').trim() : ''; + result._sample_crc = sampleOrder ? Number(sampleOrder.items_crc || 0) : 0; + result.items_weight = sampleOrder ? Number(sampleOrder.items_weight || 0) : 0; + result.suggested_package_material = null; + + // 波次内首个订单的运单号,用于包材绑定等后续操作 + // 优先取首个正常订单的运单号,若无正常订单则取首个订单(含拦截)的运单号,均无则为空字符串 + const firstNonIntercepted = normalOrders.length > 0 ? normalOrders[0] : null; + const firstAnyOrder = orders.length > 0 ? orders[0] : null; + const firstOrderForWaybill = firstNonIntercepted || firstAnyOrder; + result.first_waybill_no = firstOrderForWaybill + ? String(firstOrderForWaybill.waybill_no || '').trim() + : ''; + + return result; + }); + + const waveViews = (await Promise.all(waveViewPromises)).filter(view => view !== null); + + // 批量查询所有波次的包材推荐 + if (waveViews.length > 0) { + const sampleOrdersForPackageQuery = waveViews + .filter(wv => wv._sample_hash) + .map(wv => ({ items_hash: wv._sample_hash, items_crc: wv._sample_crc })); + const packageMaterialMap = await this.batchQueryPackageMaterialRecommendation( + sampleOrdersForPackageQuery, + warehouseId + ); + for (const wv of waveViews) { + if (wv._sample_hash) { + wv.suggested_package_material = packageMaterialMap.get(wv._sample_hash) || null; + } + // 清理内部临时字段 + delete wv._sample_hash; + delete wv._sample_crc; + } + } + + return waveViews; + } + + /** + * 通过波次ID查询关联的拣货模式。 + * 优先查询 wms_wave_pick_task.wave_id,其次查 wms_wave_pick_task_wave 关联。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 拣货模式编码,未找到返回 0。 + */ + async getPickModeByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + + if (normalizedWaveId <= 0) { + return 0; + } + + // 先按 wave_id 直接查拣货任务 + const taskRows = await ctx.model.query( + ` + SELECT pick_mode + FROM wms_wave_pick_task + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId + ORDER BY create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(taskRows) && taskRows.length > 0) { + return Number(taskRows[0].pick_mode || 0); + } + + // 通过 wms_wave_pick_task_wave 关联查询 + const twRows = await ctx.model.query( + ` + SELECT t.pick_mode + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + ORDER BY t.create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(twRows) && twRows.length > 0) { + return Number(twRows[0].pick_mode || 0); + } + + return 0; + } + + /** + * 根据波次ID查询关联的拣货任务ID。 + * 优先查 wms_wave_pick_task.wave_id,其次查 wms_wave_pick_task_wave 关联表。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 拣货任务ID,未找到返回 0。 + */ + async getTaskIdByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + + if (normalizedWaveId <= 0) { + return 0; + } + + // 先按 wave_id 直接查拣货任务 + const taskRows = await ctx.model.query( + ` + SELECT id AS task_id + FROM wms_wave_pick_task + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId + ORDER BY create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(taskRows) && taskRows.length > 0) { + return Number(taskRows[0].task_id || 0); + } + + // 通过 wms_wave_pick_task_wave 关联查询 + const twRows = await ctx.model.query( + ` + SELECT tw.task_id + FROM wms_wave_pick_task_wave tw + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + ORDER BY tw.task_id DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(twRows) && twRows.length > 0) { + return Number(twRows[0].task_id || 0); + } + + return 0; + } + + /** + * 查询波次下所有订单的基本信息列表。 + * 包含运单号、打印状态、复核状态、波次内序号(优先从 wms_order_wave_index 读取真实 wave_index, + * 若表无记录则降级使用 Array.map 临时序号),按未复核优先 + 波次内序号升序排序。 + * @param {string} waveNo 波次号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单基本信息列表,每项含 order_id、delivery_order_code、 + * waybill_no、pick_status、is_printed、is_reviewed、shop_nick、items_count、 + * wave_index、recheck_status、wave_id、wave_no、order_type、status、 + * logistics_name、store_remark、intercept_status、items_weight、items_hash、items_crc、stock 等字段。 + */ + async getWaveOrdersBasic(waveNo, warehouseId) { + const normalizedWaveNo = String(waveNo || '').trim(); + + if (!normalizedWaveNo) { + return []; + } + + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderRows = await orderModel.findAll({ + where: { + wave_no: normalizedWaveNo, + warehouse_id: warehouseId, + recheck_status: { [this.app.Sequelize.Op.ne]: 'fin' }, + }, + attributes: [ + 'id', + 'delivery_order_code', + 'pre_delivery_order_code', + 'pick_status', + 'wave_id', + 'wave_no', + 'order_type', + 'status', + 'recheck_status', + 'items_count', + 'shop_nick', + 'logistics_name', + 'print_status', + 'store_id', + 'intercept_status', + 'items_weight', + 'packages_weight', + 'items_hash', + 'items_crc', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const { ctx } = this; + const orderRowsArray = Array.isArray(orderRows) ? orderRows : []; + const orderIds = orderRowsArray.map(row => Number(row.id || 0)); + + // 批量查询货主备注(wms_store_warehouse.store_remask) + const storeRemarkMap = new Map(); + if (orderIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) { + const storeIds = [ + ...new Set( + orderRowsArray + .map(row => Number(row.store_id || 0)) + .filter(id => id > 0) + ), + ]; + if (storeIds.length > 0) { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } + } + + // 批量查询运单信息 + const waybillMap = new Map(); + if (orderIds.length > 0 && ctx.model && ctx.model.OrderExpress) { + const expressRows = await ctx.model.OrderExpress.findAll({ + where: { order_id: orderIds, warehouse_id: warehouseId }, + attributes: [ 'order_id', 'waybill_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const er of (Array.isArray(expressRows) ? expressRows : [])) { + const oid = Number(er.order_id || 0); + if (oid > 0 && !waybillMap.has(oid)) { + waybillMap.set(oid, String(er.waybill_code || '').trim()); + } + } + } + + // 批量查询波次顺序索引(wms_order_wave_index) + const waveIndexMap = new Map(); + if (orderIds.length > 0 && ctx.model && typeof ctx.model.query === 'function') { + const waveIds = [ + ...new Set( + orderRowsArray + .map(row => Number(row.wave_id || 0)) + .filter(id => id > 0) + ), + ]; + if (waveIds.length > 0) { + try { + const waveIndexRows = await ctx.model.query( + ` + SELECT order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND order_id IN (:orderIds) + `, + { + replacements: { warehouseId, waveIds, orderIds }, + type: ctx.model.QueryTypes && ctx.model.QueryTypes.SELECT, + } + ); + for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) { + const wrOrderId = Number(wr && wr.order_id || 0); + if (wrOrderId > 0) { + waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0)); + } + } + } catch (e) { + ctx.logger.warn(`[recheckOrder.getWaveOrdersBasic] 查询波次索引失败, waveNo=${normalizedWaveNo}, error=${e.message}`); + } + } + } + + // 构建订单列表 + const orderList = orderRowsArray.map((row, index) => { + const orderId = Number(row.id || 0); + const recheckStatus = String(row.recheck_status || '').trim(); + const printStatus = String(row.print_status || '').trim(); + + // 运单号:从 wms_order_express 关联表查询 + const waybillNo = waybillMap.has(orderId) ? (waybillMap.get(orderId) || '') : ''; + + return { + order_id: orderId, + delivery_order_code: String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(), + waybill_no: waybillNo, + pick_status: String(row.pick_status || '').trim(), + is_printed: printStatus === 'fin', + is_reviewed: recheckStatus === 'fin', + shop_nick: String(row.shop_nick || '').trim(), + items_count: Number(row.items_count || 0), + wave_index: waveIndexMap.has(orderId) ? waveIndexMap.get(orderId) : index, + recheck_status: recheckStatus, + wave_id: Number(row.wave_id || 0), + wave_no: String(row.wave_no || '').trim(), + order_type: String(row.order_type || '').trim(), + status: Number(row.status || 0), + logistics_name: String(row.logistics_name || '').trim(), + store_id: Number(row.store_id || 0), + store_remark: storeRemarkMap.has(Number(row.store_id || 0)) + ? storeRemarkMap.get(Number(row.store_id || 0)) + : '', + intercept_status: String(row.intercept_status || '').trim(), + items_weight: Number(row.items_weight || 0), + packages_weight: Number(row.packages_weight || 0), + items_hash: String(row.items_hash || '').trim(), + items_crc: Number(row.items_crc || 0), + }; + }); + + // 排序:未复核的排前面,其次按波次内序号从小到大 + orderList.sort((a, b) => { + const aReviewed = a.is_reviewed ? 1 : 0; + const bReviewed = b.is_reviewed ? 1 : 0; + if (aReviewed !== bReviewed) { + return aReviewed - bReviewed; + } + return a.wave_index - b.wave_index; + }); + + // 补充库存信息 + const enrichedList = await this.enrichOrdersWithStock(orderList, warehouseId); + return enrichedList; + } + + /** + * 批量查询包材推荐信息。 + * 根据订单的 items_hash + items_crc 组合,从 wms_package_material_item_relation 表 + * 查询最匹配的包材推荐(按 bind_count 降序取 top-1)。 + * @param {Object[]} orderList 订单列表,每项需含 items_hash、items_crc 字段。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 以 items_hash 为键的包材推荐映射, + * 值为包材信息对象或 null(无推荐时)。 + */ + async batchQueryPackageMaterialRecommendation(orderList, warehouseId) { + const resultMap = new Map(); + + if (!Array.isArray(orderList) || orderList.length === 0) { + return resultMap; + } + + // 收集所有有效的 items_hash,并为每个 hash 记录对应的 items_crc + const hashCrcMap = new Map(); + for (const order of orderList) { + const hash = String(order.items_hash || '').trim(); + if (!hash) { + continue; + } + const crc = Number(order.items_crc || 0); + if (!hashCrcMap.has(hash)) { + hashCrcMap.set(hash, crc); + } + } + + if (hashCrcMap.size === 0) { + return resultMap; + } + + const uniqueHashes = [ ...hashCrcMap.keys() ]; + const { ctx } = this; + + if (!ctx.model || typeof ctx.model.query !== 'function') { + return resultMap; + } + + // 批量查询所有匹配的包材绑定记录,按 bind_count 降序 + let relationRows = []; + try { + relationRows = await ctx.model.query( + `SELECT * FROM wms_package_material_item_relation + WHERE warehouse_id = :warehouseId + AND items_hash IN (:uniqueHashes) + AND is_active = 1 + AND delete_at IS NULL + ORDER BY bind_count DESC`, + { + replacements: { warehouseId, uniqueHashes }, + type: ctx.model.QueryTypes.SELECT, + } + ); + } catch (e) { + ctx.logger.warn(`[recheckOrder.batchQueryPackageMaterialRecommendation] 查询包材推荐失败, error=${e.message}`); + return resultMap; + } + + const rows = Array.isArray(relationRows) ? relationRows : []; + + // 为每个 items_hash 取第一条匹配记录(已按 bind_count DESC 排序,且 items_crc 匹配) + for (const row of rows) { + const hash = String(row.items_hash || '').trim(); + if (!hash || resultMap.has(hash)) { + continue; + } + // 校验 items_crc 是否与订单一致 + const expectedCrc = hashCrcMap.get(hash); + const rowCrc = Number(row.items_crc || 0); + if (expectedCrc !== undefined && expectedCrc !== rowCrc) { + continue; + } + resultMap.set(hash, { + id: row.package_material_id, + code: String(row.package_material_code || '').trim() || null, + name: String(row.package_material_name || '').trim() || null, + spec: String(row.package_material_spec || '').trim() || null, + type: String(row.package_material_type || '').trim() || null, + weight: row.weight != null ? Number(row.weight) : null, + length: row.length != null ? Number(row.length) : null, + width: row.width != null ? Number(row.width) : null, + height: row.height != null ? Number(row.height) : null, + bind_count: row.bind_count != null ? Number(row.bind_count) : null, + }); + } + + return resultMap; + } + + /** + * 为订单列表批量补充库存信息。 + * 查询每个订单的明细商品、库存数量、条码列表和图片,构建 stock 数组。 + * @param {Object[]} orderList 订单基本信息列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 补充了 stock 字段的订单列表。 + */ + async enrichOrdersWithStock(orderList, warehouseId) { + if (!Array.isArray(orderList) || orderList.length === 0) { + return orderList; + } + + const orderIds = orderList.map(o => Number(o.order_id || 0)).filter(Boolean); + if (orderIds.length === 0) { + return orderList; + } + + // 1. 批量查询所有订单的商品明细 + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const allOrderItems = await orderItemsModel.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: orderIds }, + }, + attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'owner_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const itemsArray = Array.isArray(allOrderItems) ? allOrderItems : []; + + // 2. 收集所有唯一的 stock_id + const stockIds = [ ...new Set( + itemsArray + .map(item => Number(item.stock_id)) + .filter(Boolean) + ) ]; + + // 3. 批量查询库存信息(复用 getStockDetails,含条码与图片) + const stockMap = new Map(); + const barcodeMap = new Map(); + const imagesByStockId = new Map(); + if (stockIds.length > 0) { + const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + { warehouseId } + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + stockMap.set(sid, detail); + // 从 getStockDetails 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + barcodeMap.set(sid, detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean)); + } + // 从 getStockDetails 提取图片 URL(兼容数组/字符串格式) + const imageUrls = Array.isArray(detail.image_url) + ? detail.image_url.map(u => String(u || '').trim()).filter(Boolean) + : (detail.image_url ? [ String(detail.image_url).trim() ] : []); + if (imageUrls.length > 0) { + imagesByStockId.set(sid, imageUrls); + } + } + } + + // 3.1 批量查询序列号管理商品(is_sn_mgmt='Y')与其 SN 码规则,用于标记商品行是否需要采集 SN 码 + // 并下发 sn_code_rules 供前端扫码校验/加工 + const snStockIdSet = new Set(); + const snCodeRulesMap = new Map(); + if (stockIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { + const snRows = await this.ctx.model.StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'is_sn_mgmt', 'sn_code_rules' ], + raw: true, + paranoid: false, + }); + for (const snRow of (Array.isArray(snRows) ? snRows : [])) { + const sid = Number(snRow && snRow.id || 0); + if (sid <= 0) { + continue; + } + if (String(snRow.is_sn_mgmt || '').trim().toUpperCase() === 'Y') { + snStockIdSet.add(sid); + } + const rules = this.ctx.service.systems.snCodeRule.toRuleList(snRow.sn_code_rules); + if (rules.length > 0) { + snCodeRulesMap.set(sid, rules); + } + } + } + + // 4. 批量查询货主备注名(wms_store_warehouse.store_remask),按 store_id 映射 + const storeRemarkMapByStock = new Map(); + if (stockMap.size > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) { + const storeIdsForRemark = [ ...new Set( + [ ...stockMap.values() ] + .map(detail => Number(detail.store_id || 0)) + .filter(id => id > 0) + ) ]; + if (storeIdsForRemark.length > 0) { + const swRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIdsForRemark }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMapByStock.has(sid)) { + storeRemarkMapByStock.set(sid, String(sw.store_remask || '').trim()); + } + } + } + } + + // 5. 检测共享条码:以订单货主(store_id)为判定范围, + // 仅当条码在订单货主下(wms_stock_warehouse.store_id = 订单 store_id)绑定到多个不同 stock_id 时视为共享; + // 跨货主同码不提示。无货主(store_id<=0)的订单不做共享判定。 + // 已删除(delete_at/deleted_at 非空)或弃用(is_valid≠'Y')的商品资料不参与共享判定。 + const sharedBarcodeMap = new Map(); + if (barcodeMap.size > 0) { + const allBarcodes = []; + for (const [ , barcodes ] of barcodeMap) { + for (const bc of barcodes) { + allBarcodes.push(bc); + } + } + const orderStoreIds = [ ...new Set( + orderList + .map(order => Number(order.store_id || 0)) + .filter(storeId => storeId > 0) + ) ]; + if (allBarcodes.length > 0 + && orderStoreIds.length > 0 + && this.ctx.model + && this.ctx.model.StockBarcode) { + const sharedRows = await this.ctx.model.query( + `SELECT sb.barcode, sw.store_id, COUNT(DISTINCT sb.stock_id) AS cnt + FROM wms_stock_barcodes sb + INNER JOIN wms_stock_warehouse sw + ON sw.id = sb.stock_id + AND sw.is_valid = 'Y' + AND sw.delete_at IS NULL + AND sw.deleted_at IS NULL + WHERE sb.barcode IN (:barcodes) + AND sb.warehouse_id = :warehouseId + AND sw.warehouse_id = :warehouseId + AND sw.store_id IN (:orderStoreIds) + GROUP BY sb.barcode, sw.store_id + HAVING cnt > 1`, + { + replacements: { barcodes: allBarcodes, warehouseId, orderStoreIds }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + for (const row of (Array.isArray(sharedRows) ? sharedRows : [])) { + const rowStoreId = Number(row.store_id || 0); + const rowBarcode = String(row.barcode || '').trim(); + if (rowStoreId <= 0 || !rowBarcode) { + continue; + } + if (!sharedBarcodeMap.has(rowStoreId)) { + sharedBarcodeMap.set(rowStoreId, new Set()); + } + sharedBarcodeMap.get(rowStoreId).add(rowBarcode); + } + } + } + + // 6. 按 order_id 分组商品明细 + const itemsByOrderId = new Map(); + for (const item of itemsArray) { + const oid = Number(item.order_id); + if (!itemsByOrderId.has(oid)) { + itemsByOrderId.set(oid, []); + } + itemsByOrderId.get(oid).push(item); + } + + // 7. 为每个订单构建 stock 数组 + return orderList.map(order => { + const oid = Number(order.order_id || 0); + const items = itemsByOrderId.get(oid) || []; + const stock = items.map(item => { + const sid = Number(item.stock_id || 0); + const stockInfo = stockMap.get(sid) || {}; + const barcodes = (() => { + const arr = barcodeMap.get(sid); + if (Array.isArray(arr) && arr.length > 0) { + return arr; + } + return [ String(item.item_code || '').trim() ]; + })(); + const images = imagesByStockId.get(sid) || []; + + const hasSharedBarcode = (() => { + const arr = barcodeMap.get(sid); + const orderStoreId = Number(order.store_id || 0); + const sharedBarcodeSet = orderStoreId > 0 ? sharedBarcodeMap.get(orderStoreId) : null; + if (Array.isArray(arr) && arr.length > 0 && sharedBarcodeSet) { + return arr.some(bc => sharedBarcodeSet.has(bc)); + } + return false; + })(); + + return { + stock_id: sid, + item_code: String(item.item_code || stockInfo.item_code || '').trim(), + item_name: String(stockInfo.item_name || item.item_name || '').trim(), + sku_property: String(stockInfo.sku_property || '').trim(), + packing_requirements: String(stockInfo.packing_requirements || '').trim(), + pick_requirements: String(stockInfo.pick_requirements || '').trim(), + recheck_requirements: String(stockInfo.recheck_requirements || '').trim(), + merge_requirements: String(stockInfo.merge_requirements || 'Y').trim(), + barcodes, + images, + has_shared_barcode: hasSharedBarcode, + need_recheck: String(stockInfo.need_recheck || 'Y').trim(), + need_sn: snStockIdSet.has(sid) ? 'Y' : 'N', + sn_code_rules: snCodeRulesMap.get(sid) || [], + plan_qty: Number(item.plan_qty || 0), + store_id: stockInfo.store_id != null ? Number(stockInfo.store_id) : 0, + owner_code: String(item.owner_code || '').trim(), + store_remark: storeRemarkMapByStock.get(stockInfo.store_id != null ? Number(stockInfo.store_id) : 0) || '', + }; + }); + + return { + ...order, + stock, + }; + }); + } + + /** + * 通过波次ID查询关联的拣货人信息及任务ID。 + * 通过 wms_wave_pick_task_wave 关联 wms_wave_pick_task 获取 pick_user_id / pick_user_name / task_id。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{ picker_id: number|null, picker_name: string, task_id: number|null }>} 拣货人信息及任务ID。 + */ + async getPickerInfoByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + + if (normalizedWaveId <= 0) { + return { picker_id: null, picker_name: '', task_id: null }; + } + + const rows = await ctx.model.query( + ` + SELECT t.pick_user_id, t.pick_user_name, t.id AS task_id + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + AND t.pick_user_id IS NOT NULL + ORDER BY t.create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const row = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + + return { + picker_id: row && row.pick_user_id != null ? Number(row.pick_user_id) : null, + picker_name: String(row && row.pick_user_name || '').trim(), + task_id: row && row.task_id != null ? Number(row.task_id) : null, + }; + } + + /** + * 通过拣货任务ID查询拣货人信息。 + * @param {number} taskId 拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{ picker_id: number|null, picker_name: string }>} 拣货人信息。 + */ + async getPickerInfoByTaskId(taskId, warehouseId) { + const { ctx } = this; + const normalizedTaskId = Number(taskId || 0); + + if (normalizedTaskId <= 0) { + return { picker_id: null, picker_name: '' }; + } + + const rows = await ctx.model.query( + ` + SELECT pick_user_id, pick_user_name + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { taskId: normalizedTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const row = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + + return { + picker_id: row && row.pick_user_id != null ? Number(row.pick_user_id) : null, + picker_name: String(row && row.pick_user_name || '').trim(), + }; + } + + /** + * 查询波次关联的策略信息。 + * 当前 wms_wave_batch 与 wms_wave_pick_task 均未直接存储 strategy_id, + * 因此默认返回 null,后续若补充关联字段可在此扩展查询逻辑。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{ strategy_id: number|null, strategy_name: string }>} 策略信息。 + */ + // eslint-disable-next-line no-unused-vars + async getWaveStrategyInfo(waveId, warehouseId) { + return { + strategy_id: null, + strategy_name: '', + }; + } + + /** + * 兼容旧方法名,内部统一转发到 scanOrder。 + * @param {Object} data 请求体。 + * @return {Promise} 扫描结果。 + */ + async scanWaybill(data = {}) { + return await this.scanOrder(data); + } + + /** + * 确认订单已复核,并写入复核任务记录。 + * 支持两种模式:传入 wave_id 时走团购波次批量复核,否则走单订单复核。 + * @param {Object} data 请求体。 + * @param {number|string} [data.wave_id] 波次ID,传入时触发团购波次批量复核。 + * @param {number|string} [data.order_id] 订单ID。 + * @param {number|string} [data.id] 订单ID别名。 + * @param {number|string} [data.orderId] 订单ID别名。 + * @return {Promise} 复核确认结果。 + */ + async confirmRecheck(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + + // 团购波次批量复核 + const { wave_id: waveId } = requestData; + if (waveId) { + return await this.confirmRecheckByWaveId(Number(waveId), warehouseId); + } + + const { ctx } = this; + const orderId = this.resolveOrderId(data); + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + const order = await orderModel.findOne({ + where: orderWhere, + raw: true, + }); + + if (!order) { + throw new Error('未找到对应订单'); + } + + this.assertOrderCanRecheck(order); + + const expresses = await this.getOrderExpressesByOrderId(orderId, order); + const waybillNo = String(expresses?.[0]?.waybill_code || '').trim(); + + const now = new Date(); + const operator = this.getOrderLogOperator(); + const updateValues = { + recheck_status: 'fin', + recheck_time: now, + updated_at: now, + }; + + // SN(序列号管理)订单必须随复核提交 SN 码:SN 落库与复核状态更新同事务,任一失败整体回滚 + const needSnVerify = this.isSnOrderRow(order) || this.hasRecheckSnPayload(requestData); + const transaction = needSnVerify ? await ctx.model.transaction() : null; + let snSummary = { sn_count: 0, sn_item_count: 0, sn_created_count: 0, sn_reused_count: 0 }; + + try { + if (transaction) { + snSummary = await this.verifyRecheckSnForOrder({ + order, + warehouseId, + requestData, + operator, + now, + transaction, + }); + } + + const updateResult = await orderModel.update(updateValues, { + where: orderWhere, + ...(transaction ? { transaction } : {}), + }); + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + + if (affectedRows <= 0) { + throw new Error('未找到对应订单'); + } + + if (transaction) { + await transaction.commit(); + } + } catch (error) { + if (transaction) { + await transaction.rollback(); + } + throw error; + } + + const reviewNo = this.buildRecheckReviewNo(orderId, now); + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + const operatorNo = String(operator.id || '').trim(); + const operatorName = String(operator.name || '').trim(); + + await ctx.model.query( + ` + INSERT INTO wms_recheck_task ( + review_no, + warehouse_id, + order_id, + order_no, + waybill_no, + task_status, + scan_status, + review_emp_no, + review_emp_name, + scan_emp_no, + scan_emp_name, + scan_time, + finish_time, + remark + ) + VALUES ( + :reviewNo, + :warehouseId, + :orderId, + :orderNo, + :waybillNo, + :taskStatus, + :scanStatus, + :reviewEmpNo, + :reviewEmpName, + :scanEmpNo, + :scanEmpName, + :scanTime, + :finishTime, + :remark + ) + `, + { + replacements: { + reviewNo, + warehouseId, + orderId, + orderNo, + waybillNo, + taskStatus: 2, + scanStatus: 1, + reviewEmpNo: operatorNo, + reviewEmpName: operatorName, + scanEmpNo: operatorNo, + scanEmpName: operatorName, + scanTime: now, + finishTime: now, + remark: '系统复核完成', + }, + type: ctx.model.QueryTypes.INSERT, + } + ); + + // 更新波次拣货任务订单复核状态,并判断是否需要解绑车任务 + await this.updateTaskOrderReviewAndTryUnbindCart(orderId, warehouseId, operator, now); + + // 写入操作日志 + await this._writeRecheckActionLog({ + orderId, + waybillNo, + warehouseId, + operator, + now, + }); + + // 散单复核完成后,检查订单所属波次下所有订单是否均已复核完成, + // 若全部完成则更新波次状态为复核完成(wave_status=5),使波次从 batchList 中消失 + await this._tryCompleteWaveIfAllOrdersRechecked(orderId, order.wave_id, warehouseId, operator, now); + + // 通知仓库面板刷新(大屏增量更新,失败不影响主流程) + await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId)); + + // SN 订单此前被自动回传链路跳过(未复核 + SN 未齐套),复核通过后 SN 明细已齐套, + // 按货主-仓库签约策略 auto_sync_back 异步回传一次,失败不影响复核结果 + await this._tryAutoSyncBackAfterRecheck({ order, warehouseId, source: 'confirmRecheck' }); + + return { + order_id: orderId, + waybill_no: waybillNo, + recheck_status: 'fin', + recheck_time: now, + review_no: reviewNo, + has_sn_item: this.isSnOrderRow(order) ? 'Y' : 'N', + sn_count: snSummary.sn_count || 0, + sn_item_count: snSummary.sn_item_count || 0, + }; + } + + /** + * 判断订单是否为 SN(序列号管理)订单。 + * @param {Object} order 订单主表行。 + * @return {boolean} 是否 SN 订单。 + */ + isSnOrderRow(order = {}) { + return String((order && order.has_sn_item) || '').trim().toUpperCase() === 'Y'; + } + + /** + * 复核通过后对 SN 订单异步触发一次回传。 + * + * SN 订单在运单分配阶段被 auto_sync_back 前置过滤跳过(此时未复核、SN 明细未写入), + * 复核通过后 SN 明细已齐套,需要补一次回传。仅处理 SN 订单,且受货主-仓库签约策略 + * policy_config.auto_sync_back 控制;任何异常只写日志,不影响复核结果。 + * + * @param {Object} params 参数。 + * @param {Object} params.order 订单主表行(需含 id / store_id / has_sn_item / sync_status)。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {string} [params.source] 触发来源(仅用于日志定位)。 + * @return {Promise} 无返回值。 + */ + async _tryAutoSyncBackAfterRecheck({ order = {}, warehouseId, source = 'confirmRecheck' }) { + const { ctx } = this; + + try { + if (!this.isSnOrderRow(order)) { + return; + } + + const orderId = Number(order.id); + if (!Number.isInteger(orderId) || orderId <= 0) { + return; + } + + if (String(order.sync_status || '').trim() === 'fin') { + return; + } + + const storeId = Number(order.store_id) || 0; + if (storeId <= 0) { + ctx.logger.warn('[auto_sync_back] SN订单缺少货主 store_id,跳过复核后自动回传', { + warehouseId, + orderId, + source, + }); + return; + } + + const contractWarehouseId = Number(order.warehouse_id) || Number(warehouseId); + + const storeWarehouseService = this.service.systems && this.service.systems.storeWarehouse; + if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') { + ctx.logger.warn('[auto_sync_back] 签约策略服务不可用,跳过复核后自动回传', { + warehouseId, + orderId, + source, + }); + return; + } + + const contractConfig = await storeWarehouseService.getContractConfig(contractWarehouseId, storeId); + const policyConfig = contractConfig && contractConfig.policy_config ? contractConfig.policy_config : {}; + if (policyConfig.auto_sync_back !== 1) { + ctx.logger.info('[auto_sync_back] 未开启自动同步回传,跳过复核后自动回传', { + warehouseId: contractWarehouseId, + orderId, + storeId, + source, + }); + return; + } + + const pendingOrderService = ctx.service + && ctx.service.systemMethods + && ctx.service.systemMethods.order + && ctx.service.systemMethods.order.pendingOrder; + if (!pendingOrderService || typeof pendingOrderService.syncOrderIds !== 'function') { + ctx.logger.warn('[auto_sync_back] 待处理订单服务不可用,跳过复核后自动回传', { + warehouseId: contractWarehouseId, + orderId, + source, + }); + return; + } + + ctx.logger.info('[auto_sync_back] 复核完成,触发SN订单自动回传', { + warehouseId: contractWarehouseId, + orderId, + storeId, + source, + }); + + pendingOrderService.syncOrderIds({ + orderIds: [ orderId ], + warehouse_id: contractWarehouseId, + }).catch(err => { + ctx.logger.error( + `[auto_sync_back] ${source} 复核后自动回传失败: ${err && err.message ? err.message : err}` + ); + }); + } catch (error) { + ctx.logger.error( + `[auto_sync_back] ${source} 复核后自动回传异常: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 判断复核入参是否提交了 SN 码内容(唯一格式:sn_map = { stock_id: [sn_code] })。 + * @param {Object} payload 复核请求体。 + * @return {boolean} 是否提交了 SN 码。 + */ + hasRecheckSnPayload(payload = {}) { + const requestData = this.isPlainObject(payload) ? payload : {}; + const snMap = requestData.sn_map ?? requestData.snMap; + if (!this.isPlainObject(snMap)) { + return false; + } + + return Object.values(snMap).some(value => { + if (Array.isArray(value)) { + return value.some(code => String(code === undefined || code === null ? '' : code).trim() !== ''); + } + return String(value === undefined || value === null ? '' : value).trim() !== ''; + }); + } + + /** + * 复核提交时校验并写入 SN 码,具体规则由 systems.orderItemSn 承担。 + * @param {Object} params 参数。 + * @param {Object} params.order 订单主表行。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} params.requestData 复核请求体。 + * @param {Object} params.operator 操作人。 + * @param {Date} params.now 复核时间。 + * @param {Object} params.transaction Sequelize 事务。 + * @return {Promise} SN 提交汇总。 + */ + async verifyRecheckSnForOrder({ order, warehouseId, requestData, operator, now, transaction }) { + const snService = this.service && this.service.systems + ? (this.service.systems.orderItemSn || this.service.systems.order_item_sn) + : null; + + if (!snService || typeof snService.verifyRecheckSnList !== 'function') { + throw new Error('SN码校验服务不可用,无法提交复核'); + } + + return await snService.verifyRecheckSnList({ + order, + warehouseId, + payload: requestData, + operator, + now, + transaction, + }); + } + + /** + * 团购波次批量复核:将波次下所有非拦截订单标记为已复核,并更新波次批次状态为复核完成。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 批量复核结果,包含 wave_id、success_count、 + * intercepted_count、total_count。 + */ + async confirmRecheckByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId); + + if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) { + throw new Error('波次ID无效'); + } + + // 查询波次信息,判断是否为团购波次 + const waveRows = await ctx.model.query( + `SELECT wave_id, wave_no, wave_type + FROM wms_wave_batch + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId + LIMIT 1`, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + + if (!waveRow) { + throw new Error('未找到对应波次'); + } + + const waveType = Number(waveRow.wave_type || 0); + const pickMode = await this.getPickModeByWaveId(normalizedWaveId, warehouseId); + const isGroupBuy = waveType === 1 || pickMode === 1; + + if (!isGroupBuy) { + throw new Error('该波次不是团购波次,不允许批量复核'); + } + + // 查询波次下所有订单 + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderRows = await orderModel.findAll({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', + 'delivery_order_code', + 'pre_delivery_order_code', + 'intercept_status', + 'pick_status', + 'recheck_status', + 'has_sn_item', + ], + raw: true, + }); + + const orderList = Array.isArray(orderRows) ? orderRows : []; + + if (orderList.length === 0) { + throw new Error('波次下没有订单'); + } + + // 分离拦截订单与非拦截订单 + const normalOrders = []; + const interceptedOrders = []; + + for (const order of orderList) { + if (this.isInterceptedOrderStatus(String(order.intercept_status || '').trim())) { + interceptedOrders.push(order); + } else { + normalOrders.push(order); + } + } + + if (normalOrders.length === 0) { + return { + wave_id: normalizedWaveId, + success_count: 0, + intercepted_count: interceptedOrders.length, + total_count: orderList.length, + }; + } + + // 验证所有非拦截订单允许复核 + for (const order of normalOrders) { + this.assertOrderCanRecheck(order); + } + + // SN 订单必须逐单提交 SN 码,团购波次批量复核没有 SN 采集入口,直接拒绝 + if (normalOrders.some(order => this.isSnOrderRow(order))) { + throw new Error('SN订单不支持团购波次复核,请使用单订单复核并提交SN码'); + } + + const now = new Date(); + const normalOrderIds = normalOrders + .map(o => Number(o.id)) + .filter(id => id > 0); + + // 批量更新订单复核状态 + await orderModel.update( + { + recheck_status: 'fin', + recheck_time: now, + updated_at: now, + }, + { + where: this.buildOrderWhere(normalOrderIds, warehouseId), + } + ); + + // 批量插入复核任务记录 + const operator = this.getOrderLogOperator(); + const operatorNo = String(operator.id || '').trim(); + const operatorName = String(operator.name || '').trim(); + + if (normalOrders.length > 0) { + const valuePlaceholders = []; + const replacements = {}; + let idx = 0; + + for (const order of normalOrders) { + const orderId = Number(order.id); + const reviewNo = this.buildRecheckReviewNo(orderId, now); + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + const i = idx++; + + valuePlaceholders.push( + `(:reviewNo${i}, :warehouseId${i}, :orderId${i}, :orderNo${i}, :waybillNo${i}, ` + + `:taskStatus${i}, :scanStatus${i}, :reviewEmpNo${i}, :reviewEmpName${i}, ` + + `:scanEmpNo${i}, :scanEmpName${i}, :scanTime${i}, :finishTime${i}, :remark${i})` + ); + + replacements[`reviewNo${i}`] = reviewNo; + replacements[`warehouseId${i}`] = warehouseId; + replacements[`orderId${i}`] = orderId; + replacements[`orderNo${i}`] = orderNo; + replacements[`waybillNo${i}`] = ''; + replacements[`taskStatus${i}`] = 2; + replacements[`scanStatus${i}`] = 1; + replacements[`reviewEmpNo${i}`] = operatorNo; + replacements[`reviewEmpName${i}`] = operatorName; + replacements[`scanEmpNo${i}`] = operatorNo; + replacements[`scanEmpName${i}`] = operatorName; + replacements[`scanTime${i}`] = now; + replacements[`finishTime${i}`] = now; + replacements[`remark${i}`] = '系统复核完成'; + } + + const insertSQL = ` + INSERT INTO wms_recheck_task ( + review_no, + warehouse_id, + order_id, + order_no, + waybill_no, + task_status, + scan_status, + review_emp_no, + review_emp_name, + scan_emp_no, + scan_emp_name, + scan_time, + finish_time, + remark + ) VALUES ${valuePlaceholders.join(', ')} + `; + + await ctx.model.query(insertSQL, { + replacements, + type: ctx.model.QueryTypes.INSERT, + }); + } + + // 批量更新 wms_wave_pick_task_order 复核状态,并检查解绑车任务 + await this.updateTaskOrdersReviewBatch(normalOrderIds, warehouseId, operator, now); + + // 更新 wms_wave_batch 波次复核状态:标记复核完成、记录操作人与复核时间 + await ctx.model.query( + `UPDATE wms_wave_batch + SET wave_status = 5, + check_operator = :operatorName, + check_time = :now, + processed_orders = :processedCount, + update_time = :now + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId`, + { + replacements: { + waveId: normalizedWaveId, + warehouseId, + operatorName: operatorName || operatorNo, + processedCount: normalOrders.length, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + // 写入操作日志 + await this._writeRecheckActionLog({ + waveId: normalizedWaveId, + waveNo: String(waveRow.wave_no || '').trim(), + warehouseId, + operator, + orderIds: normalOrderIds, + normalOrderCount: normalOrders.length, + interceptedOrderCount: interceptedOrders.length, + totalOrderCount: orderList.length, + now, + }); + + // 通知仓库面板刷新(大屏增量更新,失败不影响主流程) + await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId)); + + return { + wave_id: normalizedWaveId, + success_count: normalOrders.length, + intercepted_count: interceptedOrders.length, + total_count: orderList.length, + }; + } + + /** + * 写入复核操作日志(内部方法)。 + * - 写 wms_wave_pick_action_log 一条复核动作日志; + * - 双写 wms_operation_log:团购批量复核按波次写一条 ORDER_RECHECK_BATCH, + * 同时按订单逐单写 ORDER_RECHECK,保证订单操作日志列表中可见。 + * + * @param {Object} params 日志参数。 + * @param {number} [params.orderId] 订单ID(单订单复核场景)。 + * @param {string} [params.waybillNo] 运单号(单订单复核场景)。 + * @param {number} [params.waveId] 波次ID(团购批量复核场景)。 + * @param {string} [params.waveNo] 波次号(团购批量复核场景)。 + * @param {number[]} [params.orderIds] 复核成功的订单ID数组(团购批量复核场景,用于逐单写订单级日志)。 + * @param {number} params.warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} params.operator 操作人信息。 + * @param {number} [params.normalOrderCount] 复核成功的订单数(批量场景)。 + * @param {number} [params.interceptedOrderCount] 拦截的订单数(批量场景)。 + * @param {number} [params.totalOrderCount] 总订单数(批量场景)。 + * @param {Date} params.now 操作时间。 + * @return {Promise} 无返回值。 + */ + async _writeRecheckActionLog(params = {}) { + const { + orderId, + waybillNo, + waveId, + waveNo, + orderIds, + warehouseId, + operator, + normalOrderCount, + interceptedOrderCount, + totalOrderCount, + now, + } = params; + + const operatorId = operator && operator.id ? Number(operator.id) : 0; + const operatorName = operator && operator.name ? String(operator.name).trim() : 'system'; + const isBatch = waveId !== undefined && waveId !== null; + const tag = isBatch ? 'recheck_batch' : 'recheck'; + const requestId = `${tag}_${warehouseId}_${isBatch ? waveId : orderId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: 0, + warehouseId: warehouseId || 0, + waveId: isBatch ? waveId : null, + orderId: isBatch ? null : (orderId || 0), + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: isBatch ? 'recheck_batch' : 'recheck', + requestId, + operatorId, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify(isBatch + ? { + wave_id: waveId, + wave_no: waveNo || '', + success_count: normalOrderCount, + intercepted_count: interceptedOrderCount, + total_count: totalOrderCount, + operator_name: operatorName, + recheck_time: now instanceof Date ? now.toISOString() : String(now || ''), + } + : { + order_id: orderId, + waybill_no: waybillNo || '', + operator_name: operatorName, + recheck_time: now instanceof Date ? now.toISOString() : String(now || ''), + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + } + ); + + // 双写 order_operation_log(失败不影响主流程) + try { + const ctx = this.ctx; + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (isBatch) { + // 波次复核:按波次记录一条操作日志 + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const messageParts = []; + if (waveNo) { + messageParts.push(`波次 ${String(waveNo).trim()}`); + } + messageParts.push(`复核完成,正常${normalOrderCount || 0}单、拦截${interceptedOrderCount || 0}单、总计${totalOrderCount || 0}单`); + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(waveId || ''), + operationCode: 'ORDER_RECHECK_BATCH', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: messageParts.join(''), + waveId, + waveNo: waveNo || '', + normalOrderCount: normalOrderCount || 0, + interceptedOrderCount: interceptedOrderCount || 0, + totalOrderCount: totalOrderCount || 0, + }, + }]); + + // 逐单补写订单级复核日志(business_id=订单ID),保证订单操作日志列表中可见 + const orderIdList = (Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id)) + .filter(id => id > 0); + if (orderIdList.length > 0) { + const waveNoText = waveNo ? `(波次 ${String(waveNo).trim()})` : ''; + await operationLogService.createOperationLogs(orderIdList.map(oid => ({ + businessType: 'order', + businessId: String(oid), + operationCode: 'ORDER_RECHECK', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: `订单${oid}复核完成${waveNoText}`, + orderId: oid, + }, + }))); + } + } + } else { + // 单订单复核 + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const messageParts = []; + if (waybillNo) { + messageParts.push(`运单 ${String(waybillNo).trim()} `); + } + messageParts.push('订单复核完成'); + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId || ''), + operationCode: 'ORDER_RECHECK', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: messageParts.join(''), + orderId: orderId || 0, + waybillNo: waybillNo || '', + }, + }]); + } + } + } catch (e) { + this.ctx.logger.warn('[recheckOrder._writeRecheckActionLog] 写入 order_operation_log 失败', { + error: e && e.message, + orderId, + waveId, + warehouseId, + }); + } + } + + /** + * 更新波次拣货任务订单的复核状态,若任务下所有订单均已复核完成则自动解绑车任务。 + * 复核状态更新后,会先清理波次内「已拦截且未打印」的订单(回池),避免其卡住任务完成判定。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @return {Promise} 无返回值。 + */ + async updateTaskOrderReviewAndTryUnbindCart(orderId, warehouseId, operator, now) { + const { ctx } = this; + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); + const hasReviewStatus = taskOrderColumnSet.has('review_status'); + const hasReviewUserId = taskOrderColumnSet.has('review_user_id'); + const hasReviewResult = taskOrderColumnSet.has('review_result'); + const hasReviewTime = taskOrderColumnSet.has('review_time'); + + // 若 review_status 列不存在,跳过后续所有逻辑 + if (!hasReviewStatus) { + return; + } + + const operatorUserId = Number(operator.id) || 0; + const reviewSetClauses = []; + + reviewSetClauses.push('review_status = 1'); + if (hasReviewUserId) reviewSetClauses.push('review_user_id = :operatorUserId'); + if (hasReviewResult) reviewSetClauses.push('review_result = 1'); + if (hasReviewTime) reviewSetClauses.push('review_time = :now'); + reviewSetClauses.push('update_time = NOW()'); + + await ctx.model.query( + `UPDATE wms_wave_pick_task_order + SET ${reviewSetClauses.join(',\n ')} + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { + orderId, + warehouseId, + operatorUserId, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + // 复核时同步清理波次内「已拦截且未打印」的订单(回池),避免拦截订单卡住任务/波次完成判定 + try { + const currentOrderModel = await this.getOrderModelByTableType('current', warehouseId); + const currentOrder = await currentOrderModel.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id' ], + raw: true, + }); + const currentWaveId = Number(currentOrder && currentOrder.wave_id || 0); + if (currentWaveId > 0) { + await this.removeUnprintedInterceptedOrdersFromWave({ + waveId: currentWaveId, + warehouseId, + operator, + }); + } + } catch (removeErr) { + ctx.logger.warn(`[confirmRecheck] 清理波次未打印拦截订单失败,不影响复核主流程, orderId=${orderId}, error=${removeErr.message}`); + } + + // 查询当前订单所属的波次拣货任务ID + const taskRows = await ctx.model.query( + `SELECT DISTINCT task_id + FROM wms_wave_pick_task_order + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + let resolvedTaskId = Number( + (Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0]?.task_id : 0) + ); + + // 团购模式(pick_mode=1/5)回退:wms_wave_pick_task_order 无记录时, + // 通过订单所属波次查找关联的拣货任务 + if (resolvedTaskId <= 0) { + resolvedTaskId = await this._resolveTaskIdByWaveFallback(orderId, warehouseId); + } + + if (resolvedTaskId <= 0) { + return; + } + + // 检查该任务下是否所有订单都已复核完成 + const allReviewed = await this._checkTaskOrdersAllReviewed(resolvedTaskId, warehouseId); + + if (!allReviewed) { + return; + } + + // 任务下所有订单均已复核完成,更新任务状态为复核通过,并解绑车任务(失败不影响主流程) + try { + await this.unbindCartForTask(resolvedTaskId, warehouseId, operatorUserId); + ctx.logger.info( + `[confirmRecheck] 车任务解绑成功, taskId=${resolvedTaskId}, orderId=${orderId}, operatorUserId=${operatorUserId}` + ); + } catch (unbindError) { + ctx.logger.warn( + `[confirmRecheck] 解绑车任务失败(复核已成功), taskId=${resolvedTaskId}, orderId=${orderId}, error=${unbindError.message}` + ); + } + + // 更新 wms_wave_pick_task 任务状态:status=3(已完成),review_status=3(复核通过) + const operatorName = String(operator.name || '').trim(); + const taskStatusSetClauses = [ + 'status = 3', + 'review_status = 3', + 'review_finish_time = :now', + 'review_time = :now', + 'update_time = NOW()', + ]; + if (operatorUserId > 0) { + taskStatusSetClauses.push('review_user_id = :operatorUserId'); + taskStatusSetClauses.push('review_user_name = :operatorName'); + } + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET ${taskStatusSetClauses.join(',\n ')} + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId: resolvedTaskId, warehouseId, operatorUserId, operatorName, now }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + } + + /** + * 团购模式(pick_mode=1/5)回退:通过订单的波次 ID 查找关联的拣货任务 ID。 + * wms_wave_pick_task_order 在团购模式下无记录,需要绕道 wave 关联表。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 任务ID,未找到返回 0。 + */ + async _resolveTaskIdByWaveFallback(orderId, warehouseId) { + const { ctx } = this; + + // 查订单所属 wave_id + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const order = await orderModel.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id' ], + raw: true, + }); + const orderWaveId = Number(order?.wave_id || 0); + if (orderWaveId <= 0) { + return 0; + } + + // 通过 wave_id 查拣货任务(仅限团购模式 pick_mode=1/5) + const taskWaveRows = await ctx.model.query( + `SELECT DISTINCT t.id AS task_id, t.pick_mode + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t + ON t.id = tw.task_id AND t.warehouse_id = :warehouseId + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + AND t.pick_mode IN (1, 5) + LIMIT 1`, + { + replacements: { waveId: orderWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const fallbackTaskId = Number( + (Array.isArray(taskWaveRows) && taskWaveRows.length > 0 ? taskWaveRows[0]?.task_id : 0) + ); + + if (fallbackTaskId <= 0) { + return 0; + } + + // 查任务关联的全部波次(团购任务一车多波次,必须任务下所有波次订单全部复核完成才允许解绑) + const taskAllWaveRows = await ctx.model.query( + `SELECT DISTINCT tw.wave_id + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = :taskId + AND tw.warehouse_id = :warehouseId`, + { + replacements: { taskId: fallbackTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskAllWaveIds = (Array.isArray(taskAllWaveRows) ? taskAllWaveRows : []) + .map(r => Number(r?.wave_id || 0)) + .filter(id => id > 0); + + if (taskAllWaveIds.length === 0) { + return 0; + } + + // 检查任务下所有波次的订单是否均已复核完成(团购模式以订单表 recheck_status 为准) + const unreviewedCount = await orderModel.count({ + where: { + wave_id: { [ctx.app.Sequelize.Op.in]: taskAllWaveIds }, + warehouse_id: warehouseId, + recheck_status: { [ctx.app.Sequelize.Op.ne]: 'fin' }, + }, + }); + + return unreviewedCount === 0 ? fallbackTaskId : 0; + } + + /** + * 检查拣货任务下是否所有订单均已复核完成。 + * - 散单模式:检查 wms_wave_pick_task_order.review_status + * - 团购模式:已由 _resolveTaskIdByWaveFallback 预先校验,此处直接返回 true + * + * @param {number} taskId 拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 全部已复核返回 true。 + */ + async _checkTaskOrdersAllReviewed(taskId, warehouseId) { + const { ctx } = this; + + // 先确认 wms_wave_pick_task_order 中是否有记录 + const totalRows = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const totalCount = Number( + (Array.isArray(totalRows) && totalRows.length > 0 ? totalRows[0]?.cnt : 0) + ); + + if (totalCount > 0) { + // 散单模式:检查是否有未复核的订单 + const unreviewedRows = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND review_status != 1`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const unreviewedCount = Number( + (Array.isArray(unreviewedRows) && unreviewedRows.length > 0 ? unreviewedRows[0]?.cnt : 0) + ); + return unreviewedCount === 0; + } + + // 团购模式(wms_wave_pick_task_order 无记录): + // 已在 _resolveTaskIdByWaveFallback 中通过订单表的 recheck_status 校验通过 + return true; + } + + /** + * 批量更新波次拣货任务订单的复核状态,并按任务维度检查是否需要解绑车任务。 + * 与单订单版本不同,本方法一次性更新所有相关任务订单的 review_status, + * 再按去重后的 task_id 逐任务判断是否所有订单均已复核完成。 + * 复核状态更新后,会先清理受影响波次内「已拦截且未打印」的订单(回池), + * 避免其卡住任务完成判定。 + * @param {number[]} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @return {Promise} 无返回值。 + */ + async updateTaskOrdersReviewBatch(orderIds, warehouseId, operator, now) { + const { ctx } = this; + + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return; + } + + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); + const hasReviewStatus = taskOrderColumnSet.has('review_status'); + + if (!hasReviewStatus) { + return; + } + + const hasReviewUserId = taskOrderColumnSet.has('review_user_id'); + const hasReviewResult = taskOrderColumnSet.has('review_result'); + const hasReviewTime = taskOrderColumnSet.has('review_time'); + const operatorUserId = Number(operator.id) || 0; + + const reviewSetClauses = [ 'review_status = 1' ]; + + if (hasReviewUserId) reviewSetClauses.push('review_user_id = :operatorUserId'); + if (hasReviewResult) reviewSetClauses.push('review_result = 1'); + if (hasReviewTime) reviewSetClauses.push('review_time = :now'); + reviewSetClauses.push('update_time = NOW()'); + + await ctx.model.query( + `UPDATE wms_wave_pick_task_order + SET ${reviewSetClauses.join(',\n ')} + WHERE order_id IN (:orderIds) + AND warehouse_id = :warehouseId`, + { + replacements: { orderIds, warehouseId, operatorUserId, now }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + // 复核时同步清理受影响波次内「已拦截且未打印」的订单(回池),避免拦截订单卡住任务完成判定 + try { + const cleanupOrderModel = await this.getOrderModelByTableType('current', warehouseId); + const cleanupWaveRows = await cleanupOrderModel.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'wave_id' ], + raw: true, + }); + const cleanupWaveIds = [ ...new Set((Array.isArray(cleanupWaveRows) ? cleanupWaveRows : []) + .map(r => Number(r && r.wave_id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + for (const cleanupWaveId of cleanupWaveIds) { + await this.removeUnprintedInterceptedOrdersFromWave({ + waveId: cleanupWaveId, + warehouseId, + operator, + }); + } + } catch (removeErr) { + ctx.logger.warn(`[confirmRecheck] 批量复核-清理波次未打印拦截订单失败,不影响主流程, error=${removeErr.message}`); + } + + // 查询受影响的去重 task_id + const taskRows = await ctx.model.query( + `SELECT DISTINCT task_id + FROM wms_wave_pick_task_order + WHERE order_id IN (:orderIds) + AND warehouse_id = :warehouseId`, + { + replacements: { orderIds, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + let taskIds = (Array.isArray(taskRows) ? taskRows : []) + .map(r => Number(r.task_id || 0)) + .filter(id => id > 0); + + // 团购模式(pick_mode=1/5)回退:wms_wave_pick_task_order 无记录时, + // 通过订单的波次 ID 查找关联的拣货任务 + if (taskIds.length === 0 && orderIds.length > 0) { + const firstOrderId = orderIds[0]; + const fallbackTaskId = await this._resolveTaskIdByWaveFallback(firstOrderId, warehouseId); + if (fallbackTaskId > 0) { + taskIds = [ fallbackTaskId ]; + } + } + + // 逐任务判断是否所有订单均已复核完成 + for (const taskId of taskIds) { + const unreviewedRows = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND review_status != 1`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const unreviewedCount = Number( + (Array.isArray(unreviewedRows) && unreviewedRows.length > 0 ? unreviewedRows[0]?.cnt : 0) + ); + + if (unreviewedCount > 0) { + continue; + } + + // 任务下所有订单均已复核完成,解绑车任务并更新任务状态 + try { + await this.unbindCartForTask(taskId, warehouseId, operatorUserId); + ctx.logger.info( + `[confirmRecheck] 批量复核-车任务解绑成功, taskId=${taskId}, operatorUserId=${operatorUserId}` + ); + } catch (unbindError) { + ctx.logger.warn( + `[confirmRecheck] 批量复核-解绑车任务失败, taskId=${taskId}, error=${unbindError.message}` + ); + } + + // 更新 wms_wave_pick_task 任务状态:status=3(已完成),review_status=3(复核通过) + const operatorName = String(operator.name || '').trim(); + const taskStatusSetClauses = [ + 'status = 3', + 'review_status = 3', + 'review_finish_time = :now', + 'review_time = :now', + 'update_time = NOW()', + ]; + if (operatorUserId > 0) { + taskStatusSetClauses.push('review_user_id = :operatorUserId'); + taskStatusSetClauses.push('review_user_name = :operatorName'); + } + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET ${taskStatusSetClauses.join(',\n ')} + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId, operatorUserId, operatorName, now }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + } + } + + /** + * 解绑车任务:清空波次拣货任务的车绑定、停用拣货车绑定记录、释放拣货车。 + * @param {number} taskId 波次拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} operatorUserId 操作员用户ID。 + * @return {Promise} 无返回值。 + */ + async unbindCartForTask(taskId, warehouseId, operatorUserId) { + const { ctx } = this; + + // 停用拣货车绑定记录 + await ctx.model.query( + `UPDATE wms_pick_task_cart_binding + SET is_active = 0, + unbind_user_id = :operatorUserId, + unbind_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND is_active = 1`, + { + replacements: { taskId, warehouseId, operatorUserId }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + } + + /** + * 从多种兼容字段中解析订单ID。 + * @param {Object} data 请求体。 + * @return {number} 规范化后的订单ID。 + */ + resolveOrderId(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + order_id: orderId, + id, + orderId: orderIdAlias, + } = requestData; + const normalizedOrderId = Number(orderId || id || orderIdAlias || 0); + + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + throw new Error('订单ID不能为空'); + } + + return normalizedOrderId; + } + + /** + * 从多种兼容字段中解析扫描关键词。 + * @param {Object} data 请求体。 + * @param {string} [data.wave_no] 波次号。 + * @param {string} [data.waveNo] 波次号别名。 + * @return {string} 规范化后的扫描关键词。 + */ + resolveScanKeyword(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + keyword, + value, + waybill_no: waybillNo, + waybillCode, + waybill_code: waybillCodeAlias, + wave_no: waveNo, + waveNo: waveNoAlias, + cart_code: cartCode, + cartCode: cartCodeAlias, + } = requestData; + const normalizedKeyword = String( + keyword || value || waybillNo || waybillCode || waybillCodeAlias || waveNo || waveNoAlias || cartCode || cartCodeAlias || '' + ).trim(); + + if (!normalizedKeyword) { + throw new Error('扫描关键词不能为空'); + } + + return normalizedKeyword; + } + + /** + * 根据扫描关键词解析订单ID。 + * 匹配优先级:运单号 → 波次号 → 车号。 + * @param {string} keyword 扫描关键词。 + * @return {Promise<{ orderId: number, matchType: string, cartMatchContext?: Object, waveMatchContext?: Object }>} 命中结果。 + */ + async pickOrderMatchByKeyword(keyword) { + const waybillOrderId = await this.pickOrderIdByWaybill(keyword); + + if (Number.isFinite(waybillOrderId) && waybillOrderId > 0) { + return { + orderId: waybillOrderId, + matchType: 'waybill', + }; + } + + const waveMatchContext = await this.pickWaveMatchContextByWaveNo(keyword); + const waveOrderId = Number(waveMatchContext?.order_id || 0); + + if (Number.isFinite(waveOrderId) && waveOrderId > 0) { + return { + orderId: waveOrderId, + matchType: 'wave', + waveMatchContext, + }; + } + + const cartMatchContext = await this.pickCartMatchContextByCartCode(keyword); + const cartOrderId = Number(cartMatchContext?.order_id || 0); + + if (Number.isFinite(cartOrderId) && cartOrderId > 0) { + return { + orderId: cartOrderId, + matchType: 'cart', + cartMatchContext, + }; + } + + throw new Error('未找到对应订单'); + } + + /** + * 根据运单号解析唯一订单ID。 + * @param {string} waybillNo 运单号。 + * @return {Promise} 订单ID,未命中返回 0。 + */ + async pickOrderIdByWaybill(waybillNo) { + const warehouseId = this.getWarehouseId(); + const orderIds = await this.findOrderIdsByExpressNumbers([ waybillNo ], warehouseId); + + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return 0; + } + + const normalizedOrderIds = orderIds + .map(item => Number(item)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0) + .sort((a, b) => a - b); + + if (normalizedOrderIds.length === 0) { + return 0; + } + + return normalizedOrderIds[0]; + } + + /** + * 根据车号在波次拣货任务维度反查订单ID。 + * 匹配字段:任务主表当前车号快照与任务订单行车号快照。 + * @param {string} cartCode 车号。 + * @return {Promise} 订单ID,未命中返回 0。 + */ + async pickOrderIdByCartCode(cartCode) { + const cartMatchContext = await this.pickCartMatchContextByCartCode(cartCode); + const orderId = Number(cartMatchContext?.order_id || 0); + + return Number.isFinite(orderId) && orderId > 0 ? orderId : 0; + } + + /** + * 根据波次号查询波次信息及波次下订单列表。 + * @param {string} waveNo 波次号。 + * @return {Promise<{order_id:number, wave:Object|null, orders:Array, matched_order_ids:Array}>} 命中上下文。 + */ + async pickWaveMatchContextByWaveNo(waveNo) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const normalizedWaveNo = String(waveNo || '').trim(); + + if (!normalizedWaveNo) { + return { + order_id: 0, + wave: null, + orders: [], + matched_order_ids: [], + }; + } + + // 查询波次批次信息 + const waveRows = await ctx.model.query( + ` + SELECT + wave_id, + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + creator, + create_time, + update_time + FROM wms_wave_batch + WHERE wave_no = :waveNo + AND warehouse_id = :warehouseId + ORDER BY create_time DESC, wave_id DESC + LIMIT 1 + `, + { + replacements: { waveNo: normalizedWaveNo, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + + if (!waveRow) { + return { + order_id: 0, + wave: null, + orders: [], + matched_order_ids: [], + }; + } + + const wave = { + wave_id: Number(waveRow.wave_id || 0), + wave_no: String(waveRow.wave_no || '').trim(), + wave_type: Number(waveRow.wave_type || 0), + wave_status: Number(waveRow.wave_status || 0), + total_orders: Number(waveRow.total_orders || 0), + processed_orders: Number(waveRow.processed_orders || 0), + creator: String(waveRow.creator || '').trim(), + create_time: waveRow.create_time || null, + update_time: waveRow.update_time || null, + }; + + // 查询波次下的订单列表 + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderRows = await orderModel.findAll({ + where: { + wave_no: normalizedWaveNo, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', + 'delivery_order_code', + 'pre_delivery_order_code', + 'pick_status', + 'wave_id', + 'wave_no', + 'order_type', + 'status', + 'recheck_status', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const orders = (Array.isArray(orderRows) ? orderRows : []).map(row => ({ + order_id: Number(row.id || 0), + delivery_order_code: String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(), + pick_status: String(row.pick_status || '').trim(), + wave_id: Number(row.wave_id || 0), + wave_no: String(row.wave_no || '').trim(), + order_type: String(row.order_type || '').trim(), + status: Number(row.status || 0), + recheck_status: String(row.recheck_status || '').trim(), + })); + + const matchedOrderIds = [ ...new Set(orders + .map(o => Number(o.order_id)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const primaryOrderId = Number(matchedOrderIds[0] || 0); + + return { + order_id: Number.isFinite(primaryOrderId) && primaryOrderId > 0 ? primaryOrderId : 0, + wave, + orders, + matched_order_ids: matchedOrderIds, + }; + } + + /** + * 根据车号读取任务上下文及任务订单行。 + * @param {string} cartCode 车号。 + * @return {Promise<{order_id:number, task:Object, task_orders:Array, matched_order_ids:Array}>} 命中上下文。 + */ + async pickCartMatchContextByCartCode(cartCode) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); + + /** + * 通过车号查找匹配的拣货任务行。 + * 匹配优先级: + * 1. wms_pick_task_cart_binding(车任务绑定表,unbind_time IS NULL,权威数据源) + * 2. wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot(快照回退兜底, + * 仅兜底该车号下不存在解绑记录的任务:绑定表为权威数据源,已解绑的任务不再回退命中,避免解绑后快照残留误匹配) + * @param {string} cartCode 车号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 任务行,未找到返回 null。 + */ + const findTaskByCartCode = async (cartCode, warehouseId) => { + // 第一优先级:车任务绑定表(权威活跃绑定数据源,unbind_time IS NULL 表示未解绑) + const bindingRows = await ctx.model.query( + ` + SELECT + t.id AS task_id, + t.task_no, + t.pick_mode, + t.status, + t.review_status, + t.current_cart_code_snapshot + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t + ON t.id = b.task_id + WHERE b.cart_code_snapshot = :cartCode + AND b.warehouse_id = :warehouseId + AND b.unbind_time IS NULL + ORDER BY b.create_time DESC, b.id DESC + LIMIT 1 + `, + { + replacements: { warehouseId, cartCode }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(bindingRows) && bindingRows.length > 0) { + return bindingRows[0]; + } + + // 第二优先级(回退兜底):任务主表 + 任务订单行快照。 + // 绑定表是权威数据源:该车号下存在解绑记录(unbind_time 非空)的任务不再回退命中, + // 避免解绑后任务主表/订单行快照残留导致误匹配已完成任务。 + const snapshotRows = await ctx.model.query( + ` + SELECT + t.id AS task_id, + t.task_no, + t.pick_mode, + t.status, + t.review_status, + t.current_cart_code_snapshot + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND ( + t.current_cart_code_snapshot = :cartCode + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = t.id + AND pto.cart_code_snapshot = :cartCode + ) + ) + AND NOT EXISTS ( + SELECT 1 + FROM wms_pick_task_cart_binding b + WHERE b.task_id = t.id + AND b.warehouse_id = :warehouseId + AND b.cart_code_snapshot = :cartCode + AND b.unbind_time IS NOT NULL + ) + ORDER BY t.create_time DESC, t.id DESC + LIMIT 1 + `, + { + replacements: { warehouseId, cartCode }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + return (Array.isArray(snapshotRows) && snapshotRows.length > 0) ? snapshotRows[0] : null; + }; + + const taskRow = await findTaskByCartCode(cartCode, warehouseId); + const taskId = Number(taskRow && taskRow.task_id || 0); + if (!Number.isInteger(taskId) || taskId <= 0) { + return { + order_id: 0, + task: null, + task_orders: [], + matched_order_ids: [], + }; + } + + const pickMode = Number(taskRow.pick_mode || 0); + + // 团购模式(小波次 pick_mode=1 / 大波次 pick_mode=5): + // wms_wave_pick_task_order 表无记录,直接返回 task 信息, + // 以 task_id 作为 order_id 保证 pickOrderMatchByKeyword 的 cartMatch.order_id > 0 检查通过 + if (pickMode === 1 || pickMode === 5) { + const task = { + task_id: taskId, + task_no: String(taskRow.task_no || '').trim(), + pick_mode: pickMode, + status: Number(taskRow.status || 0), + review_status: Number(taskRow.review_status || 0), + current_cart_code_snapshot: String(taskRow.current_cart_code_snapshot || '').trim(), + }; + return { + order_id: taskId, + task, + task_orders: [], + matched_order_ids: [], + }; + } + + const pickStatusSelect = taskOrderColumnSet.has('pick_status') + ? 'pto.pick_status' + : 'NULL AS pick_status'; + const waveIdSelect = taskOrderColumnSet.has('wave_id') + ? 'pto.wave_id' + : 'NULL AS wave_id'; + const boxNoSelect = taskOrderColumnSet.has('box_no') + ? 'pto.box_no' + : 'NULL AS box_no'; + const cartCodeSnapshotSelect = taskOrderColumnSet.has('cart_code_snapshot') + ? 'pto.cart_code_snapshot' + : 'NULL AS cart_code_snapshot'; + const taskOrderWarehouseFilterSql = taskOrderColumnSet.has('warehouse_id') + ? ' AND pto.warehouse_id = :warehouseId' + : ''; + const taskOrderRowsRaw = await ctx.model.query( + ` + SELECT + pto.id AS task_order_id, + pto.order_id, + ${pickStatusSelect}, + ${waveIdSelect}, + ${boxNoSelect}, + ${cartCodeSnapshotSelect} + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = :taskId + ${taskOrderWarehouseFilterSql} + ORDER BY pto.id ASC + `, + { + replacements: { + taskId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const task = { + task_id: Number(taskRow.task_id || 0), + task_no: String(taskRow.task_no || '').trim(), + pick_mode: Number(taskRow.pick_mode || 0), + status: Number(taskRow.status || 0), + review_status: Number(taskRow.review_status || 0), + current_cart_code_snapshot: String(taskRow.current_cart_code_snapshot || '').trim(), + }; + const taskOrderRows = (Array.isArray(taskOrderRowsRaw) ? taskOrderRowsRaw : []).map(row => ({ + task_order_id: Number(row && row.task_order_id || 0), + order_id: Number(row && row.order_id || 0), + pick_status: String(row && row.pick_status || '').trim(), + wave_id: Number(row && row.wave_id || 0), + box_no: Number(row && row.box_no || 0), + cart_code_snapshot: String(row && row.cart_code_snapshot || '').trim(), + })); + const matchedOrderIds = [ ...new Set(taskOrderRows + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + const primaryOrderId = Number(matchedOrderIds[0] || 0); + + return { + order_id: Number.isFinite(primaryOrderId) && primaryOrderId > 0 ? primaryOrderId : 0, + task, + task_orders: taskOrderRows, + matched_order_ids: matchedOrderIds, + }; + } + + /** + * 读取数据表字段集合。 + * @param {string} tableName 数据表名。 + * @return {Promise>} 字段名集合。 + */ + async getTableColumnSet(tableName) { + const { ctx } = this; + const normalizedTableName = String(tableName || '').trim(); + + if (!normalizedTableName) { + return new Set(); + } + + const escapedTableName = normalizedTableName.replace(/`/g, '``'); + + try { + const rows = await ctx.model.query(`SHOW COLUMNS FROM \`${escapedTableName}\``, { + type: ctx.model.QueryTypes.SELECT, + }); + + return new Set((Array.isArray(rows) ? rows : []) + .map(row => String(row && row.Field || '').trim()) + .filter(Boolean)); + } catch (error) { + ctx.logger.warn(`[recheckOrder.getTableColumnSet] 获取字段失败, table=${normalizedTableName}, error=${error.message}`); + return new Set(); + } + } + + /** + * 解析拣货模式名称。 + * @param {number|string} pickMode 拣货模式编码。 + * @return {string} 拣货模式名称。 + */ + resolvePickModeName(pickMode) { + const pickModeMap = { + 1: '团购小波次', + 2: '散单单品单件', + 3: '散单先拣后分', + 4: '边拣边分', + 5: '团购大波次', + }; + const normalizedPickMode = Number(pickMode || 0); + + return pickModeMap[normalizedPickMode] || '未知模式'; + } + + /** + * 构建波次号命中语义化视图。 + * @param {Object} waveMatchContext 波次号命中上下文。 + * @return {Promise} 语义化视图。 + */ + async buildWaveMatchView(waveMatchContext = {}) { + const context = this.isPlainObject(waveMatchContext) ? waveMatchContext : {}; + const wave = this.isPlainObject(context.wave) ? context.wave : {}; + const orders = Array.isArray(context.orders) ? context.orders : []; + + return { + wave_id: Number(wave.wave_id || 0), + wave_no: String(wave.wave_no || '').trim(), + wave_type: Number(wave.wave_type || 0), + wave_status: Number(wave.wave_status || 0), + total_orders: Number(wave.total_orders || 0), + processed_orders: Number(wave.processed_orders || 0), + creator: String(wave.creator || '').trim(), + create_time: wave.create_time || null, + update_time: wave.update_time || null, + order_count: orders.length, + orders, + }; + } + + /** + * 构建车号命中语义化视图。 + * @param {Object} cartMatchContext 车号命中上下文。 + * @return {Promise} 语义化视图。 + */ + async buildCartMatchView(cartMatchContext = {}) { + const context = this.isPlainObject(cartMatchContext) ? cartMatchContext : {}; + const task = this.isPlainObject(context.task) ? context.task : {}; + const taskOrders = Array.isArray(context.task_orders) ? context.task_orders : []; + const pickMode = Number(task.pick_mode || 0); + const modeName = this.resolvePickModeName(pickMode); + const enrichedTaskOrders = await this.enrichTaskOrderRows(taskOrders); + const taskSummary = { + task_id: Number(task.task_id || 0), + task_no: String(task.task_no || '').trim(), + pick_mode: pickMode, + status: Number(task.status || 0), + review_status: Number(task.review_status || 0), + current_cart_code_snapshot: String(task.current_cart_code_snapshot || '').trim(), + order_count: enrichedTaskOrders.length, + }; + + const baseView = { + mode_code: pickMode, + mode_name: modeName, + view_type: 'orders', + task: taskSummary, + }; + + if ([ 1, 5 ].includes(pickMode)) { + return { + ...baseView, + view_type: 'groups', + groups: this.groupTaskOrdersByWaveId(enrichedTaskOrders), + }; + } + if (pickMode === 2) { + return { + ...baseView, + view_type: 'orders', + orders: enrichedTaskOrders, + }; + } + if (pickMode === 3) { + return { + ...baseView, + view_type: 'pick_groups', + pick_groups: this.groupTaskOrdersByPickStatus(enrichedTaskOrders), + }; + } + if (pickMode === 4) { + return { + ...baseView, + view_type: 'box_groups', + box_groups: this.groupTaskOrdersByBoxNo(enrichedTaskOrders), + }; + } + + return { + ...baseView, + view_type: 'orders', + orders: enrichedTaskOrders, + }; + } + + /** + * 将车号匹配视图中的订单平铺为一维数组。 + * 根据 view_type 从 groups / pick_groups / box_groups / orders 中提取所有订单。 + * @param {Object} cartMatchView 车号匹配视图。 + * @return {Array} 平铺后的订单列表。 + */ + flattenCartMatchOrders(cartMatchView = {}) { + const view = this.isPlainObject(cartMatchView) ? cartMatchView : {}; + const { view_type: viewType } = view; + + if (viewType === 'groups') { + const groups = Array.isArray(view.groups) ? view.groups : []; + return groups.flatMap(g => (Array.isArray(g.orders) ? g.orders : [])); + } + if (viewType === 'pick_groups') { + const pickGroups = Array.isArray(view.pick_groups) ? view.pick_groups : []; + return pickGroups.flatMap(g => (Array.isArray(g.orders) ? g.orders : [])); + } + if (viewType === 'box_groups') { + const boxGroups = Array.isArray(view.box_groups) ? view.box_groups : []; + return boxGroups.flatMap(g => (Array.isArray(g.orders) ? g.orders : [])); + } + // view_type === 'orders' 或兜底 + return Array.isArray(view.orders) ? view.orders : []; + } + + /** + * 追加任务订单行的订单维度字段。 + * @param {Array} taskOrders 任务订单行。 + * @return {Promise>} 扩展后的任务订单行。 + */ + async enrichTaskOrderRows(taskOrders = []) { + const warehouseId = this.getWarehouseId(); + const normalizedTaskOrders = Array.isArray(taskOrders) ? taskOrders : []; + const orderIds = [ ...new Set(normalizedTaskOrders + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + + if (orderIds.length === 0) { + return []; + } + + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderRows = await orderModel.findAll({ + where: this.buildOrderWhere(orderIds, warehouseId), + attributes: [ 'id', 'wave_id', 'pick_status' ], + raw: true, + }); + const orderMap = new Map((Array.isArray(orderRows) ? orderRows : []) + .map(row => [ + Number(row && row.id || 0), + { + wave_id: Number(row && row.wave_id || 0), + pick_status: String(row && row.pick_status || '').trim(), + }, + ]) + .filter(item => Number(item[0]) > 0)); + + return normalizedTaskOrders.map(row => { + const orderId = Number(row && row.order_id || 0); + const orderInfo = orderMap.get(orderId) || {}; + const waveId = Number(row && row.wave_id || 0) > 0 + ? Number(row && row.wave_id || 0) + : Number(orderInfo.wave_id || 0); + const pickStatus = String(row && row.pick_status || '').trim() || String(orderInfo.pick_status || '').trim() || 'unknown'; + + return { + task_order_id: Number(row && row.task_order_id || 0), + order_id: orderId, + wave_id: Number.isInteger(waveId) && waveId > 0 ? waveId : 0, + pick_status: pickStatus, + box_no: Number(row && row.box_no || 0), + cart_code_snapshot: String(row && row.cart_code_snapshot || '').trim(), + }; + }); + } + + /** + * 按 wave_id 分组。 + * @param {Array} taskOrders 任务订单行。 + * @return {Array} wave 分组结果。 + */ + groupTaskOrdersByWaveId(taskOrders = []) { + return this.groupTaskOrders(taskOrders, row => `wave_${Number(row && row.wave_id || 0)}`, row => ({ + wave_id: Number(row && row.wave_id || 0), + orders: [], + })); + } + + /** + * 按 pick_status 分组。 + * @param {Array} taskOrders 任务订单行。 + * @return {Array} pick_status 分组结果。 + */ + groupTaskOrdersByPickStatus(taskOrders = []) { + return this.groupTaskOrders(taskOrders, row => `pick_status_${String(row && row.pick_status || 'unknown').trim() || 'unknown'}`, row => ({ + pick_status: String(row && row.pick_status || 'unknown').trim() || 'unknown', + orders: [], + })); + } + + /** + * 按 box_no 分组。 + * @param {Array} taskOrders 任务订单行。 + * @return {Array} box_no 分组结果。 + */ + groupTaskOrdersByBoxNo(taskOrders = []) { + return this.groupTaskOrders(taskOrders, row => `box_${Number(row && row.box_no || 0)}`, row => ({ + box_no: Number(row && row.box_no || 0), + orders: [], + })); + } + + /** + * 通用任务订单分组。 + * @param {Array} taskOrders 任务订单行。 + * @param {Function} keyGetter 分组键生成器。 + * @param {Function} initGroup 分组初始化函数。 + * @return {Array} 分组列表。 + */ + groupTaskOrders(taskOrders = [], keyGetter, initGroup) { + const normalizedTaskOrders = Array.isArray(taskOrders) ? taskOrders : []; + const groupMap = new Map(); + + normalizedTaskOrders.forEach(row => { + const groupKey = String(keyGetter(row)); + + if (!groupMap.has(groupKey)) { + groupMap.set(groupKey, initGroup(row)); + } + + const group = groupMap.get(groupKey); + group.orders.push({ ...row }); + }); + + return Array.from(groupMap.values()).map(group => ({ + ...group, + order_count: Array.isArray(group.orders) ? group.orders.length : 0, + })); + } + + /** + * 生成复核单号。 + * @param {number} orderId 订单ID。 + * @param {Date} now 当前时间。 + * @return {string} 复核单号。 + */ + buildRecheckReviewNo(orderId, now = new Date()) { + const timestamp = Number(now.getTime()); + const paddedOrderId = String(orderId).padStart(6, '0'); + + return `RC${timestamp}${paddedOrderId}`; + } + + /** + * 校验订单是否允许复核,未拣货订单或已拦截订单不允许复核。 + * @param {Object} order 订单信息。 + */ + assertOrderCanRecheck(order = {}) { + if (String(order.pick_status || '') === 'none') { + throw new Error('订单未拣货,不允许复核。'); + } + if (this.isInterceptedOrderStatus(order.intercept_status)) { + throw new Error('订单已被拦截,无法提交复核'); + } + } + + /** + * 复核订单列表查询,通过入参 list_type 区分散单模式与团购模式。 + * - 散单模式(single):返回待复核订单列表,每项为一个订单。 + * - 团购模式(group):返回波次维度的复核列表,每项为一个波次及其订单汇总。 + * 统一使用 list 字段名输出。 + * @param {Object} data 请求参数。 + * @param {string} [data.list_type='single'] 列表模式:single(散单模式)/ group(团购模式)。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.pagination] 分页参数,兼容 page/pageSize。 + * @return {Promise} 列表结果,包含 list 与 pagination。 + */ + async recheckOrderList(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { list_type: listType = 'single' } = requestData; + const normalizedListType = String(listType || 'single').trim(); + + if (normalizedListType === 'group') { + return await this.queryRecheckOrderGroupList(requestData); + } + return await this.queryRecheckOrderSingleList(requestData); + } + + /** + * 散单模式复核列表:按订单维度返回待复核订单,支持分页与关键词/波次号/复核状态筛选。 + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件,支持 keyword / wave_no / recheck_status / pick_status 等。 + * @param {Object} [data.pagination] 分页参数。 + * @return {Promise} { list: Array, pagination: Object }。 + */ + async queryRecheckOrderSingleList(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData); + const where = this.isPlainObject(requestData.where) ? requestData.where : {}; + const offset = (page - 1) * pageSize; + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderTableName = this.resolveModelTableName(orderModel); + + const conditions = []; + const replacements = { warehouseId, limit: pageSize, offset }; + + conditions.push('o.warehouse_id = :warehouseId'); + conditions.push('o.pick_status != \'none\''); + conditions.push('o.recheck_status != \'fin\''); + + // 关键词搜索:运单号 / 订单号 + const keyword = String(where.keyword || '').trim(); + if (keyword) { + conditions.push(`( + o.delivery_order_code LIKE :keyword + OR o.pre_delivery_order_code LIKE :keyword + OR EXISTS ( + SELECT 1 FROM wms_order_express oe + WHERE oe.order_id = o.id + AND oe.warehouse_id = o.warehouse_id + AND oe.waybill_code LIKE :keyword + AND oe.delete_at IS NULL + ) + )`); + replacements.keyword = `%${keyword}%`; + } + + // 波次号筛选 + const waveNo = String(where.wave_no || '').trim(); + if (waveNo) { + conditions.push('o.wave_no = :waveNo'); + replacements.waveNo = waveNo; + } + + // 复核状态筛选 + const recheckStatus = String(where.recheck_status || '').trim(); + if (recheckStatus) { + conditions.push('o.recheck_status = :recheckStatus'); + replacements.recheckStatus = recheckStatus; + } + + // 拣货状态筛选 + const pickStatus = String(where.pick_status || '').trim(); + if (pickStatus) { + conditions.push('o.pick_status = :pickStatus'); + replacements.pickStatus = pickStatus; + } + + // 波次内序号筛选(wms_order_wave_index.wave_index) + // 支持 wave_index: { operator: 'between', value: [起, 止] },以及 wave_index_min / wave_index_max + const rawWaveIndexCondition = this.isPlainObject(where.wave_index) ? where.wave_index : null; + if (rawWaveIndexCondition) { + const waveIndexOperator = String(rawWaveIndexCondition.operator || 'eq').toLowerCase(); + const rawWaveIndexValue = rawWaveIndexCondition.value; + if (waveIndexOperator === 'between' && Array.isArray(rawWaveIndexValue) && rawWaveIndexValue.length === 2) { + const betweenStart = Number(rawWaveIndexValue[0]); + const betweenEnd = Number(rawWaveIndexValue[1]); + if (Number.isFinite(betweenStart) && Number.isFinite(betweenEnd)) { + conditions.push('wi.wave_index BETWEEN :waveIndexBetweenStart AND :waveIndexBetweenEnd'); + replacements.waveIndexBetweenStart = betweenStart; + replacements.waveIndexBetweenEnd = betweenEnd; + } + } else if ((waveIndexOperator === 'gte' || waveIndexOperator === 'ge') + && rawWaveIndexValue !== undefined && rawWaveIndexValue !== null && rawWaveIndexValue !== '') { + const gteValue = Number(rawWaveIndexValue); + if (Number.isFinite(gteValue)) { + conditions.push('wi.wave_index >= :waveIndexGte'); + replacements.waveIndexGte = gteValue; + } + } else if ((waveIndexOperator === 'lte' || waveIndexOperator === 'le') + && rawWaveIndexValue !== undefined && rawWaveIndexValue !== null && rawWaveIndexValue !== '') { + const lteValue = Number(rawWaveIndexValue); + if (Number.isFinite(lteValue)) { + conditions.push('wi.wave_index <= :waveIndexLte'); + replacements.waveIndexLte = lteValue; + } + } else if (waveIndexOperator === 'eq' + && rawWaveIndexValue !== undefined && rawWaveIndexValue !== null && rawWaveIndexValue !== '') { + const eqValue = Number(rawWaveIndexValue); + if (Number.isFinite(eqValue)) { + conditions.push('wi.wave_index = :waveIndexEq'); + replacements.waveIndexEq = eqValue; + } + } + } else { + const rawWaveIndexMin = this.isPlainObject(where.wave_index_min) + ? where.wave_index_min.value + : where.wave_index_min; + if (rawWaveIndexMin !== undefined && rawWaveIndexMin !== null && rawWaveIndexMin !== '') { + const waveIndexMin = Number(rawWaveIndexMin); + if (Number.isFinite(waveIndexMin)) { + conditions.push('wi.wave_index >= :waveIndexMin'); + replacements.waveIndexMin = waveIndexMin; + } + } + const rawWaveIndexMax = this.isPlainObject(where.wave_index_max) + ? where.wave_index_max.value + : where.wave_index_max; + if (rawWaveIndexMax !== undefined && rawWaveIndexMax !== null && rawWaveIndexMax !== '') { + const waveIndexMax = Number(rawWaveIndexMax); + if (Number.isFinite(waveIndexMax)) { + conditions.push('wi.wave_index <= :waveIndexMax'); + replacements.waveIndexMax = waveIndexMax; + } + } + } + + // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → order_id + const stockQuery = String(where.stock_query || '').trim(); + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); + if (stockOrderIds.length > 0) { + conditions.push('o.id IN (:stockOrderIds)'); + replacements.stockOrderIds = stockOrderIds; + } else { + // 未匹配到任何商品,直接返回空列表 + return this.success('ok', { + list: [], + pagination: { + page, + pageSize, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + }); + } + } + + const whereClause = conditions.length > 0 + ? `WHERE ${conditions.join('\n AND ')}` + : ''; + + const waveIndexJoin = ` + LEFT JOIN wms_order_wave_index wi + ON wi.warehouse_id = o.warehouse_id + AND wi.order_id = o.id`; + + const listSql = ` + SELECT + o.id AS order_id, + o.delivery_order_code, + o.pre_delivery_order_code, + o.order_type, + o.wave_id, + o.wave_no, + o.pick_status, + o.recheck_status, + o.shop_nick, + o.logistics_name, + o.items_count, + o.items_total, + o.items_weight, + o.packages_weight, + o.weight_type, + o.status, + o.create_at, + o.recheck_time, + o.has_sn_item, + wi.wave_index, + (SELECT oe.waybill_code FROM wms_order_express oe WHERE oe.order_id = o.id AND oe.warehouse_id = o.warehouse_id AND oe.delete_at IS NULL LIMIT 1) AS waybill_code + FROM ${orderTableName} o${waveIndexJoin} + ${whereClause} + ORDER BY o.id ASC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + FROM ${orderTableName} o${waveIndexJoin} + ${whereClause} + `; + + const [ listRows, countRows ] = await Promise.all([ + ctx.model.query(listSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ctx.model.query(countSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ]); + + const total = Number( + (Array.isArray(countRows) && countRows.length > 0 ? countRows[0]?.total : 0) + ); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + const list = (Array.isArray(listRows) ? listRows : []).map(row => ({ + order_id: Number(row?.order_id || 0), + delivery_order_code: String(row?.delivery_order_code || row?.pre_delivery_order_code || '').trim(), + order_type: String(row?.order_type || '').trim(), + wave_id: Number(row?.wave_id || 0), + wave_no: String(row?.wave_no || '').trim(), + pick_status: String(row?.pick_status || '').trim(), + recheck_status: String(row?.recheck_status || '').trim(), + shop_nick: String(row?.shop_nick || '').trim(), + logistics_name: String(row?.logistics_name || '').trim(), + items_count: Number(row?.items_count || 0), + items_total: Number(row?.items_total || 0), + items_weight: row?.items_weight != null ? Number(row.items_weight) : null, + packages_weight: row?.packages_weight != null ? Number(row.packages_weight) : null, + weight_type: this.formatWeightTypeLabel(row?.weight_type), + waybill_code: String(row?.waybill_code || '').trim(), + wave_index: Number(row?.wave_index || 0), + status: Number(row?.status || 0), + create_at: row?.create_at || null, + recheck_time: row?.recheck_time || null, + has_sn_item: String(row?.has_sn_item || '').trim().toUpperCase() === 'Y' ? 'Y' : 'N', + })); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 团购模式复核列表:按波次维度返回复核汇总,每项包含波次信息及订单复核统计。 + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件,支持 wave_no / wave_type / wave_status 等。 + * @param {Object} [data.pagination] 分页参数。 + * @return {Promise} { list: Array, pagination: Object }。 + */ + async queryRecheckOrderGroupList(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData); + const where = this.isPlainObject(requestData.where) ? requestData.where : {}; + const offset = (page - 1) * pageSize; + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderTableName = this.resolveModelTableName(orderModel); + + const conditions = []; + const replacements = { warehouseId, limit: pageSize, offset }; + + conditions.push('wb.warehouse_id = :warehouseId'); + + // 波次号筛选 + const waveNo = String(where.wave_no || '').trim(); + if (waveNo) { + conditions.push('wb.wave_no LIKE :waveNo'); + replacements.waveNo = `%${waveNo}%`; + } + + // 波次类型筛选 + const waveType = Number(where.wave_type); + if (Number.isInteger(waveType) && waveType > 0) { + conditions.push('wb.wave_type = :waveType'); + replacements.waveType = waveType; + } + + // 波次状态筛选 + const waveStatus = Number(where.wave_status); + if (Number.isInteger(waveStatus)) { + conditions.push('wb.wave_status = :waveStatus'); + replacements.waveStatus = waveStatus; + } + + // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → order_id 过滤波次 + const stockQuery = String(where.stock_query || '').trim(); + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); + if (stockOrderIds.length > 0) { + conditions.push('o.id IN (:stockOrderIds)'); + replacements.stockOrderIds = stockOrderIds; + } else { + // 未匹配到任何商品,直接返回空列表 + return this.success('ok', { + list: [], + pagination: { + page, + pageSize, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + }); + } + } + + const whereClause = conditions.length > 0 + ? `WHERE ${conditions.join('\n AND ')}` + : ''; + + const listSql = ` + SELECT + wb.wave_id, + wb.wave_no, + wb.wave_type, + wb.wave_status, + wb.total_orders, + wb.processed_orders, + wb.creator, + wb.create_time, + wb.update_time, + COUNT(o.id) AS order_count, + SUM(CASE WHEN o.recheck_status = 'fin' THEN 1 ELSE 0 END) AS reviewed_count, + SUM(CASE WHEN o.recheck_status != 'fin' OR o.recheck_status IS NULL THEN 1 ELSE 0 END) AS unreviewed_count + FROM wms_wave_batch wb + LEFT JOIN ${orderTableName} o + ON o.wave_no = wb.wave_no + AND o.warehouse_id = wb.warehouse_id + AND o.pick_status != 'none' + ${whereClause} + GROUP BY wb.wave_id, wb.wave_no, wb.wave_type, wb.wave_status, + wb.total_orders, wb.processed_orders, wb.creator, + wb.create_time, wb.update_time + ORDER BY wb.create_time DESC, wb.wave_id DESC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + FROM wms_wave_batch wb + ${whereClause} + `; + + const [ listRows, countRows ] = await Promise.all([ + ctx.model.query(listSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ctx.model.query(countSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ]); + + const total = Number( + (Array.isArray(countRows) && countRows.length > 0 ? countRows[0]?.total : 0) + ); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + const list = (Array.isArray(listRows) ? listRows : []).map(row => { + const orderCount = Number(row?.order_count || 0); + const reviewedCount = Number(row?.reviewed_count || 0); + const unreviewedCount = Number(row?.unreviewed_count || 0); + + return { + wave_id: Number(row?.wave_id || 0), + wave_no: String(row?.wave_no || '').trim(), + wave_type: Number(row?.wave_type || 0), + wave_status: Number(row?.wave_status || 0), + total_orders: Number(row?.total_orders || 0), + processed_orders: Number(row?.processed_orders || 0), + creator: String(row?.creator || '').trim(), + create_time: row?.create_time || null, + update_time: row?.update_time || null, + order_count: orderCount, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + review_assignment_status: orderCount === 0 || reviewedCount === 0 + ? 'unreviewed' + : reviewedCount >= orderCount + ? 'reviewed' + : 'partially_reviewed', + }; + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 从 Sequelize 模型解析 SQL 表名并安全转义。 + * @param {Object} model Sequelize 模型对象。 + * @return {string} 可直接拼接到 SQL 的表名(已做反引号转义)。 + */ + resolveModelTableName(model) { + const rawTableName = model && typeof model.getTableName === 'function' + ? model.getTableName() + : model && model.tableName; + const tableName = typeof rawTableName === 'string' + ? rawTableName + : rawTableName && typeof rawTableName.tableName === 'string' + ? rawTableName.tableName + : ''; + const normalizedTableName = String(tableName || '').trim(); + if (!normalizedTableName) { + throw new Error('订单模型表名解析失败'); + } + + const tableParts = normalizedTableName.split('.') + .map(part => String(part || '').trim()) + .filter(Boolean); + if (tableParts.length === 0) { + throw new Error('订单模型表名解析失败'); + } + + for (const tablePart of tableParts) { + if (!/^[a-zA-Z0-9_$]+$/.test(tablePart)) { + throw new Error(`订单模型表名不合法: ${normalizedTableName}`); + } + } + + return tableParts.map(part => `\`${part}\``).join('.'); + } + + /** + * 确认仓库拦截:通过订单 ID 列表直接匹配订单,批量将其拦截状态更新为"仓库拦截成功"。 + * 仅拦截当前指定订单(不波及波次内其他订单),支持部分失败:未找到的订单与处理失败的 + * 订单记录在 failed 列表并返回失败原因,其余订单继续处理。 + * + * 本方法为 method 出口包装层:解析仓库上下文与订单ID后,复用 systems 层 + * interceptAutoConfirm.confirmInterceptForOrderIds 完成实际拦截确认动作, + * 与定时任务「自动库内拦截确定」共用同一内部实现,保证两条链路行为一致。 + * + * 前置条件:订单必须处于拦截发起中状态(requested/requesting/intercepting,历史值 intercepted 兼容)。 + * 未发起拦截(none/空)的订单直接静默跳过不参与处理;已确认拦截(intercepted_at_warehouse)及其它 + * 非可确认状态(intercepted_in_transit/returning/returned/delivered_by_mistake/timeout/cancelled/failed/ + * exception)的订单一律跳过并记录失败原因;更新 SQL 的 where 同时限定拦截状态,防止并发修改导致误更新。 + * + * 每个订单的拦截处理: + * 1. 更新 wms_order_delivery:intercept_status = intercepted_at_warehouse、step=4、outbound_status=fin, + * 并同步写入拦截时间 intercept_time(当前时间) + * 2. 同步更新运单表:is_intercept='Y'、is_back='Y'(库内拦截确认,货物在库内需退回) + * 3. 释放储位分配(cancelAllocateStorage 拦截模式:库存不归还可用,移入拦截锁定字段 intercept_locked_quantity) + * 4. 释放订单锁(lock_status='none') + * 5. 写入操作日志(ORDER_INTERCEPT_CONFIRM) + * 全部订单处理完后,按成功订单 ID 汇总批量创建售后工单 + 通知快递群。 + * 运单标记、储位释放、锁释放、工单创建、日志写入失败均不影响主流程。 + * + * @param {Object} data 请求体。 + * @param {number[]|string} data.ids 订单 ID 列表,支持数组或以逗号分隔的字符串(兼容 id/order_id/orderId 单值写法)。 + * @return {Promise} 批量拦截结果,包含 success/failed 列表与 success_count/failed_count 计数。 + */ + async confirmIntercept(data = {}) { + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(data); + + if (orderIds.length === 0) { + this.ctx.throw(400, '订单ID列表不能为空'); + } + + // method 出口仅做入参解构与包装,拦截确认动作统一由 systems 层内部方法执行 + const operator = this.getOrderLogOperator(); + return await this.ctx.service.systems.interceptAutoConfirm.confirmInterceptForOrderIds({ + orderIds, + warehouseId, + operator, + }); + } + + /** + * 拦截扫描:通过运单号查找运单记录,标记退回与拦截并处理关联工单与订单拦截状态。 + * + * 处理流程: + * 1. 根据运单号查询 wms_order_express;运单不存在,或运单 is_intercept≠'Y' 且关联订单 + * intercept_status 不在 requested/intercepting 时,视为非拦截订单并拒绝 + * 2. 校验通过后将运单 is_back、is_intercept 设为 'Y' + * 3. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入 + * "库内拦截成功"步骤并将工单置为 completed + * 4. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse(**不写 intercept_time**: + * 该字段恒为「最近一次发起拦截的通知时刻」,库内确定拦截不覆盖,见 app/lib/intercept_time.js; + * 库内确定拦截时刻以配送表 dispath_time 为准), + * 并释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)与订单锁(仅订单级状态更新,不标记订单下其他面单) + * + * 注:库内拦截确认需标记退回 is_back='Y';发起拦截链路仅写 is_intercept,不写 is_back。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @return {Promise} 拦截扫描结果,包含 waybill_code、is_back、is_intercept、after_sale(若有)、order。 + */ + async interceptScan(data = {}) { + const { ctx, service } = this; + const { waybill_code: waybillCode } = data || {}; + + if (!waybillCode || !String(waybillCode).trim()) { + throw new Error('运单号不能为空'); + } + + const normalizedWaybillCode = String(waybillCode).trim(); + const warehouseId = this.getWarehouseId(); + const now = new Date(); + + // 1. 查询运单记录 + const expressRecord = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: normalizedWaybillCode, warehouse_id: warehouseId }, + raw: true, + }); + + // 1a. 非拦截订单校验:运单不存在,或运单/关联订单均未发起系统拦截,则拒绝 + if (!expressRecord) { + throw new Error('非拦截订单'); + } + + const expressIntercepted = String(expressRecord.is_intercept || '').trim() === 'Y'; + let orderIntercepted = false; + + if (!expressIntercepted) { + const linkedOrderId = Number(expressRecord.order_id || 0); + + if (linkedOrderId > 0) { + const checkOrderModel = await this.getOrderModelByTableType('current', warehouseId); + const linkedOrder = await checkOrderModel.findOne({ + where: this.buildOrderWhere([ linkedOrderId ], warehouseId), + attributes: [ 'id', 'intercept_status' ], + raw: true, + }); + orderIntercepted = linkedOrder + ? [ 'requested', 'intercepting' ].includes(String(linkedOrder.intercept_status || '').trim()) + : false; + } + } + + if (!expressIntercepted && !orderIntercepted) { + throw new Error('非拦截订单'); + } + + // 2. 标记退回 + 拦截 + await ctx.model.OrderExpress.update( + { is_back: 'Y', is_intercept: 'Y' }, + { where: { id: expressRecord.id } } + ); + + // 3. 检查关联的未完结售后工单 + const afterSale = await ctx.model.AfterSale.findOne({ + where: { + waybill_no: normalizedWaybillCode, + warehouse_id: warehouseId, + deleted_at: null, + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + let afterSaleResult = null; + if (afterSale) { + const operator = this.getOrderLogOperator(); + const operatorId = operator.id ? Number(operator.id) : 0; + const operatorSnapshot = JSON.stringify({ + id: String(operator.id || ''), + name: String(operator.name || ''), + }); + + try { + afterSaleResult = await service.systems.afterSale.handleWorkOrder({ + id: afterSale.id, + remark: '库内拦截成功', + targetStatus: 'completed', + resolution: '库内拦截成功', + attachmentIds: [], + operatorId, + operatorSnapshot, + warehouseId, + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 处理工单失败, afterSaleId=${afterSale.id}, waybill=${normalizedWaybillCode}, error=${workOrderErr.message}` + ); + // 工单处理失败不阻断主流程 + } + } + + // 4. 更新订单拦截状态(与 confirmIntercept 一致:订单级拦截,覆盖所有面单含子面单) + const orderId = Number(expressRecord.order_id || 0); + let orderResult = null; + if (orderId > 0) { + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + const order = await orderModel.findOne({ + where: orderWhere, + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status' ], + raw: true, + }); + + if (order) { + // 库内确定拦截不写 intercept_time(不覆盖通知拦截时刻),库内确定时刻以配送表 dispath_time 为准 + await orderModel.update( + { + intercept_status: 'intercepted_at_warehouse', + step: 4, + outbound_status: 'fin', + updated_at: now, + }, + { where: orderWhere } + ); + + // 释放储位分配(拦截模式:库存移入拦截锁定,不归还可用) + try { + await service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: [ orderId ], + interceptMode: true, + }); + } catch (allocErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 释放储位分配失败, orderId=${orderId}, error=${allocErr.message}` + ); + } + + // 释放订单锁 + try { + await orderModel.update( + { lock_status: 'none', updated_at: now }, + { where: orderWhere } + ); + } catch (lockErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 释放锁失败, orderId=${orderId}, error=${lockErr.message}` + ); + } + + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + + // 写入操作日志 + try { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: orderId, + operationCode: 'ORDER_INTERCEPT_CONFIRM', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + previousInterceptStatus: String(order.intercept_status || '').trim(), + newInterceptStatus: 'intercepted_at_warehouse', + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 写入操作日志失败, orderId=${orderId}, error=${logErr.message}` + ); + } + + orderResult = { + order_id: orderId, + order_no: orderNo, + intercept_status: 'intercepted_at_warehouse', + }; + } + } + + return { + waybill_code: normalizedWaybillCode, + is_back: 'Y', + is_intercept: 'Y', + after_sale: afterSaleResult ? afterSaleResult.after_sale : null, + order: orderResult, + }; + } + + /** + * 批量快捷复核:对一批订单 IDs 依次执行前置条件检查与复核流程。 + * 支持部分失败:不满足前置条件的订单直接跳过并记录失败原因,其余订单继续走完拣货完成 + 复核标记流程。 + * + * 前置条件(任一不满足即跳过): + * 1. 未分配储位:storage_status 不等于 'fin' + * 2. 未分配快递:post_status 不等于 'fin' + * 3. 未同步:status 不等于 'created' + * 4. 已拦截:intercept_status 处于拦截流程状态(requested/requesting/intercepting/intercepted_in_transit/intercepted_at_warehouse,历史值 intercepted 兼容) + * + * 核心流程(每个满足条件的订单在独立事务中执行): + * 1. 若 pick_status 不等于 'fin',先完成拣货: + * - 更新 wms_wave_pick_task_order 拣货状态(仅当订单关联拣货任务时) + * - 更新 wms_order_delivery.pick_status = 'fin' + * - 更新 wms_picking.status = 'fin'(仅当存在拣货记录时) + * - 汇总 wms_picking 中各 storage_id 的 quantity,扣减 wms_storage.locked_quantity 与 quantity + * - 写入 wms_storage_transaction 出库流水 + * 2. 标记复核: + * - 更新 wms_order_delivery.recheck_status = 'fin'、recheck_time = now + * - 插入 wms_recheck_task 复核记录 + * - 更新 wms_wave_pick_task_order 复核状态并尝试解绑车任务 + * - 写入操作日志 + * + * @param {Object} data 请求体。 + * @param {number[]|string} data.ids 订单 ID 列表,支持数组或以逗号分隔的字符串。 + * @return {Promise} 批量复核结果,包含 success、failed、success_count、failed_count。 + */ + async batchQuickRecheck(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(data); + + if (orderIds.length === 0) { + this.ctx.throw(400, '订单ID列表不能为空'); + } + + // ── 1. 批量查询所有订单的当前状态 ── + const orderModel = await this.getOrderModel('order', warehouseId); + const orderRows = await orderModel.findAll({ + where: this.buildOrderWhere(orderIds, warehouseId), + attributes: [ + 'id', 'delivery_order_code', 'pre_delivery_order_code', + 'storage_status', 'post_status', 'sync_status', 'status', 'intercept_status', + 'pick_status', 'recheck_status', 'wave_id', 'wave_no', 'has_sn_item', + ], + raw: true, + }); + + const orderMap = new Map(); + for (const row of orderRows) { + orderMap.set(Number(row.id), row); + } + + // ── 2. 前置条件检查:将订单分为有效订单与跳过订单 ── + const validOrders = []; + const failedOrders = []; + + for (const orderId of orderIds) { + const order = orderMap.get(orderId); + + if (!order) { + failedOrders.push({ order_id: orderId, reason: '未找到对应订单' }); + continue; + } + + if (this.isInterceptedOrderStatus(order.intercept_status)) { + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '已拦截', + }); + continue; + } + + const storageStatus = String(order.storage_status || '').trim(); + if (storageStatus !== 'fin') { + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '未分配储位', + }); + continue; + } + + const postStatus = String(order.post_status || '').trim(); + if (postStatus !== 'fin') { + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '没有分配快递', + }); + continue; + } + + const syncStatus = String(order.sync_status || '').trim(); + if (syncStatus !== 'fin') { + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '没有同步', + }); + continue; + } + + validOrders.push(order); + } + + // ── 3. 逐订单在独立事务中执行拣货完成 + 复核标记 ── + const successOrders = []; + + for (const order of validOrders) { + const orderId = Number(order.id); + + try { + await ctx.model.transaction(async transaction => { + // 3a. 若未完成拣货,先执行拣货完成流程 + const pickStatus = String(order.pick_status || '').trim(); + if (pickStatus !== 'fin') { + await this._completePickForOrder(orderId, warehouseId, transaction); + // 更新内存中的 pick_status,避免后续 assertOrderCanRecheck 因旧值误判 + order.pick_status = 'fin'; + } + + // 3b. 标记复核 + await this._markRecheckForOrder(order, warehouseId, transaction); + }); + + successOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + }); + } catch (error) { + ctx.logger.warn( + `[batchQuickRecheck] 订单复核失败, orderId=${orderId}, error=${error.message}` + ); + failedOrders.push({ + order_id: orderId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: `复核失败: ${error.message}`, + }); + } + } + + // 通知仓库面板刷新(大屏增量更新,失败不影响主流程) + await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId)); + + return { + success: successOrders, + failed: failedOrders, + success_count: successOrders.length, + failed_count: failedOrders.length, + }; + } + + /** + * 规范波次 ID 入参,兼容 wave_ids、waveIds、wave_id 等写法。 + * @param {Object} data 请求体。 + * @return {number[]} 波次 ID 列表。 + */ + normalizeWaveIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawIds = requestData.wave_ids; + 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.waveIds !== undefined && requestData.waveIds !== null && requestData.waveIds !== '') { + const val = requestData.waveIds; + if (Array.isArray(val)) sourceIds.push(...val); + else if (typeof val === 'string') sourceIds.push(...val.split(',')); + else sourceIds.push(val); + } else if (requestData.wave_id !== undefined && requestData.wave_id !== null && requestData.wave_id !== '') { + sourceIds.push(requestData.wave_id); + } + + const normalizedIds = []; + for (const value of sourceIds) { + const normalizedId = Number(String(value).trim()); + if (Number.isFinite(normalizedId) && normalizedId > 0) { + normalizedIds.push(normalizedId); + } + } + + return Array.from(new Set(normalizedIds)); + } + + /** + * 按波次批量快捷复核:传入波次 IDs 列表,对每个波次下所有有效订单执行前置检查 + * (已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、 + * 库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、 + * 操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。 + * + * @param {Object} data 请求体。 + * @param {number[]|string} [data.wave_ids] 波次 ID 列表,支持数组或以逗号分隔的字符串。 + * @param {number[]|string} [data.waveIds] 波次 ID 列表别名(驼峰写法)。 + * @param {number} [data.wave_id] 单个波次 ID。 + * @return {Promise} 处理结果,包含 success/failed 列表及计数。 + */ + async batchQuickRecheckByWave(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const waveIds = this.normalizeWaveIds(data); + + if (waveIds.length === 0) { + this.ctx.throw(400, '波次ID列表不能为空'); + } + + // ── 1. 批量查询所有波次下的订单 ── + const orderModel = await this.getOrderModel('order', warehouseId); + const orderRows = await orderModel.findAll({ + where: { + wave_id: { [this.app.Sequelize.Op.in]: waveIds }, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', 'delivery_order_code', 'pre_delivery_order_code', + 'storage_status', 'post_status', 'sync_status', 'status', 'intercept_status', + 'pick_status', 'recheck_status', 'wave_id', 'wave_no', 'has_sn_item', + ], + raw: true, + }); + + // 按 wave_id 分组 + const waveOrderMap = new Map(); + for (const row of orderRows) { + const wid = Number(row.wave_id); + if (!waveOrderMap.has(wid)) { + waveOrderMap.set(wid, []); + } + waveOrderMap.get(wid).push(row); + } + + // ── 2. 前置条件检查:逐波次、逐订单校验 ── + const allSuccessOrders = []; + const allFailedOrders = []; + + for (const waveId of waveIds) { + const waveOrders = waveOrderMap.get(waveId) || []; + + if (waveOrders.length === 0) { + allFailedOrders.push({ + wave_id: waveId, + reason: '波次下无订单', + }); + continue; + } + + const validOrders = []; + + for (const order of waveOrders) { + const orderId = Number(order.id); + + if (this.isInterceptedOrderStatus(order.intercept_status)) { + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '已拦截', + }); + continue; + } + + const storageStatus = String(order.storage_status || '').trim(); + if (storageStatus !== 'fin') { + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '未分配储位', + }); + continue; + } + + const postStatus = String(order.post_status || '').trim(); + if (postStatus !== 'fin') { + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '没有分配快递', + }); + continue; + } + + const syncStatus = String(order.sync_status || '').trim(); + if (syncStatus !== 'fin') { + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: '没有同步', + }); + continue; + } + + validOrders.push(order); + } + + // ── 3. 逐订单在独立事务中执行拣货完成 + 复核标记 ── + for (const order of validOrders) { + const orderId = Number(order.id); + + try { + await ctx.model.transaction(async transaction => { + // 3a. 若未完成拣货,先执行拣货完成流程 + const pickStatus = String(order.pick_status || '').trim(); + if (pickStatus !== 'fin') { + await this._completePickForOrder(orderId, warehouseId, transaction); + // 更新内存中的 pick_status,避免后续 _markRecheckForOrder 因旧值误判 + order.pick_status = 'fin'; + } + + // 3b. 标记复核 + await this._markRecheckForOrder(order, warehouseId, transaction); + }); + + allSuccessOrders.push({ + order_id: orderId, + wave_id: Number(order.wave_id) || waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + }); + } catch (error) { + ctx.logger.warn( + `[batchQuickRecheckByWave] 订单复核失败, orderId=${orderId}, waveId=${waveId}, error=${error.message}` + ); + allFailedOrders.push({ + order_id: orderId, + wave_id: waveId, + delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(), + reason: `复核失败: ${error.message}`, + }); + } + } + } + + // 通知仓库面板刷新(大屏增量更新,失败不影响主流程) + await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId)); + + return { + success: allSuccessOrders, + failed: allFailedOrders, + success_count: allSuccessOrders.length, + failed_count: allFailedOrders.length, + }; + } + + /** + * 完成单个订单的拣货流程(内部方法,在事务中执行)。 + * 包含:更新拣货任务订单状态、订单拣货状态、拣货记录状态、扣减库存锁定数量与可用数量、写库存流水。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _completePickForOrder(orderId, warehouseId, transaction) { + const { ctx, app } = this; + + // 步骤1:若订单关联拣货任务,更新 wms_wave_pick_task_order 的拣货状态 + const taskOrderRows = await ctx.model.query( + `SELECT id, task_id + FROM wms_wave_pick_task_order + WHERE order_id = :orderId + AND warehouse_id = :warehouseId + LIMIT 1`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + + const hasTaskOrder = Array.isArray(taskOrderRows) && taskOrderRows.length > 0; + + if (hasTaskOrder) { + await ctx.model.query( + `UPDATE wms_wave_pick_task_order + SET pick_status = 1, + picked_time = NOW(), + update_time = NOW() + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + } + + // 步骤2:更新 wms_order_delivery.pick_status = 'fin' + const orderModel = await this.getOrderModel('order', warehouseId); + await orderModel.update( + { pick_status: 'fin' }, + { + where: this.buildOrderWhere([ orderId ], warehouseId), + transaction, + validate: false, + hooks: false, + } + ); + + // 步骤3:检查是否存在 wms_picking 记录(仅统计 pending 且未删除的记录) + // 使用 FOR UPDATE 行锁,防止并发事务读取到相同的 picking 记录导致重复扣减库存 + const pickingRows = await ctx.model.query( + `SELECT id, storage_id, quantity, space_id + FROM wms_picking + WHERE order_id = :orderId + AND warehouse_id = :warehouseId + AND status = 'pending' + AND deleted_at IS NULL + FOR UPDATE`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + + const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; + + if (normalizedPickingRows.length > 0) { + // 更新 wms_picking.status = 'fin'(仅更新 pending 且未删除的记录) + await ctx.model.query( + `UPDATE wms_picking + SET status = 'fin', updated_at = NOW() + WHERE order_id = :orderId + AND warehouse_id = :warehouseId + AND status = 'pending' + AND deleted_at IS NULL`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + + // 步骤4:汇总各 storage_id 的 quantity,扣减 wms_storage 锁定数量与可用数量 + const storageQtyMap = new Map(); + for (const row of normalizedPickingRows) { + const sid = Number(row.storage_id); + if (!sid || sid <= 0) continue; + const currentQty = storageQtyMap.get(sid) || 0; + storageQtyMap.set(sid, currentQty + (Number(row.quantity) || 0)); + } + + const storageIds = Array.from(storageQtyMap.keys()); + if (storageIds.length > 0) { + // 加行锁查询当前库存 + const storageRows = await ctx.model.Storage.findAll({ + where: { + id: { [app.Sequelize.Op.in]: storageIds }, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', 'locked_quantity', 'quantity', + 'store_id', 'stock_id', 'batch_no', 'inventory_type', 'space_id', + ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + // 校验锁定数量是否足够 + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + const locked = Number(sRow.locked_quantity) || 0; + if (locked < deduction) { + throw new Error( + `库存记录 ${sid} 锁定数量不足:当前锁定 ${locked},需扣减 ${deduction}` + ); + } + } + + // 构建 CASE WHEN 批量扣减 + const summaryEntries = Array.from(storageQtyMap.entries()); + const caseClauses = summaryEntries + .map(([ sid, qty ]) => `WHEN ${sid} THEN ${qty}`) + .join(' '); + + await ctx.model.query( + `UPDATE wms_storage + SET locked_quantity = locked_quantity - CASE id ${caseClauses} END, + quantity = quantity - CASE id ${caseClauses} END, + updated_at = NOW() + WHERE id IN (:storageIds) + AND warehouse_id = :warehouseId`, + { + replacements: { storageIds, warehouseId }, + transaction, + } + ); + + // 写入 wms_storage_transaction 出库流水 + const operator = this.getOrderLogOperator(); + const operatorId = String(operator.id || '').trim(); + const operatorName = String(operator.name || 'system').trim(); + const transactionRows = []; + + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + if (deduction <= 0) continue; + const beforeQty = Number(sRow.quantity) || 0; + const beforeLocked = Number(sRow.locked_quantity) || 0; + transactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: Number(sRow.store_id) || 0, + stock_id: Number(sRow.stock_id) || 0, + storage_id: sid, + space_id: Number(sRow.space_id) || null, + quantity: deduction, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - deduction), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - deduction), + batch_no: sRow.batch_no || null, + inventory_type: sRow.inventory_type || 'ZP', + order_type: 'PICK_OUTBOUND', + order_no: String(orderId), + order_id: orderId, + source_order_codes: String(orderId), + operator_id: operatorId, + operator_name: operatorName, + remark: '拣货完成出库(批量快捷复核)', + created_at: new Date(), + }); + } + + if (transactionRows.length > 0) { + await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); + } + + } + } + + // 写入 order_operation_log 拣货完成日志(双写) + try { + const operationLogService = ctx.service + && ctx.service.systems + && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logOperator = this.getOrderLogOperator(); + const operatorId = String(logOperator.id || '').trim(); + const operatorName = String(logOperator.name || 'system').trim(); + await operationLogService.createOperationLogs([ + { + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_PICK_COMPLETE', + operator: { id: operatorId || null, name: operatorName || 'system' }, + extras: { + message: `订单${orderId}拣货完成`, + warehouseId: Number(warehouseId), + externalLogType: 'API', + }, + }, + ], { transaction }); + } + } catch (e) { + ctx.logger.warn( + `[_completePickForOrder] order_operation_log 写入失败, orderId=${orderId}, error=${e.message}` + ); + } + + // 步骤5:更新 wms_wave_pick_task 状态 + if (hasTaskOrder) { + const taskId = Number(taskOrderRows[0]?.task_id || 0); + if (taskId > 0) { + // 检查该任务下是否所有订单都已完成拣货 + const taskOrderCount = await ctx.model.query( + `SELECT COUNT(*) AS cnt + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND pick_status != 1`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const allPicked = (Number(taskOrderCount[0]?.cnt || 0)) === 0; + + if (allPicked) { + // 全部完成 → 任务状态设为已完成 + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET status = 2, + finish_time = NOW(), + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + } else { + // 未全部完成 → 任务状态推进为拣货中(若仍为未开始) + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET status = CASE WHEN status = 0 THEN 1 ELSE status END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + } + } + } + } + + /** + * 标记单个订单为已复核(内部方法,在事务中执行)。 + * 包含:更新订单复核状态、插入复核任务记录、更新拣货任务复核状态并尝试解绑车任务、写操作日志。 + * + * @param {Object} order 订单信息行。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _markRecheckForOrder(order, warehouseId, transaction) { + const { ctx } = this; + const orderId = Number(order.id); + + // 校验订单是否允许复核(拣货已完成且未被拦截) + this.assertOrderCanRecheck(order); + + // SN 订单必须逐单提交 SN 码,快捷复核没有 SN 采集入口,直接拒绝避免绕过 SN 校验 + if (this.isSnOrderRow(order)) { + throw new Error('SN订单需在单订单复核中提交SN码,不支持快捷复核'); + } + + const now = new Date(); + + // 更新订单复核状态 + const orderModel = await this.getOrderModel('order', warehouseId); + await orderModel.update( + { + recheck_status: 'fin', + print_status: 'fin', + recheck_time: now, + updated_at: now, + }, + { + where: this.buildOrderWhere([ orderId ], warehouseId), + transaction, + validate: false, + hooks: false, + } + ); + + // 插入 wms_recheck_task 复核记录 + const operator = this.getOrderLogOperator(); + const reviewNo = this.buildRecheckReviewNo(orderId, now); + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + const operatorNo = String(operator.id || '').trim(); + const operatorName = String(operator.name || '').trim(); + + await ctx.model.query( + `INSERT INTO wms_recheck_task ( + review_no, + warehouse_id, + order_id, + order_no, + waybill_no, + task_status, + scan_status, + review_emp_no, + review_emp_name, + scan_emp_no, + scan_emp_name, + scan_time, + finish_time, + remark + ) VALUES ( + :reviewNo, + :warehouseId, + :orderId, + :orderNo, + :waybillNo, + :taskStatus, + :scanStatus, + :reviewEmpNo, + :reviewEmpName, + :scanEmpNo, + :scanEmpName, + :scanTime, + :finishTime, + :remark + )`, + { + replacements: { + reviewNo, + warehouseId, + orderId, + orderNo, + waybillNo: '', + taskStatus: 2, + scanStatus: 1, + reviewEmpNo: operatorNo, + reviewEmpName: operatorName, + scanEmpNo: operatorNo, + scanEmpName: operatorName, + scanTime: now, + finishTime: now, + remark: '系统复核完成(批量快捷复核)', + }, + type: ctx.model.QueryTypes.INSERT, + transaction, + } + ); + + // 更新波次拣货任务订单复核状态,并判断是否需要解绑车任务 + await this._updateTaskOrderReviewInTransaction(orderId, warehouseId, operator, now, transaction); + + // 写入操作日志 + await this._writeRecheckActionLogInTransaction({ + orderId, + warehouseId, + operator, + now, + transaction, + }); + + // 散单复核完成后,在事务内检查订单所属波次下所有订单是否均已复核完成, + // 若全部完成则更新波次状态为复核完成(wave_status=5),使波次从 batchList 中消失 + await this._tryCompleteWaveInTransaction(orderId, order.wave_id, warehouseId, operator, now, transaction); + } + + /** + * 散单复核完成后,检查订单所属波次下所有订单是否均已复核完成, + * 若全部完成则更新 wms_wave_batch.wave_status = 5(复核完成), + * 使该波次从 batchList 中自然消失。 + * + * @param {number} orderId 当前复核的订单ID。 + * @param {number|string|null} waveId 订单所属波次ID。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @return {Promise} 无返回值。 + */ + async _tryCompleteWaveIfAllOrdersRechecked(orderId, waveId, warehouseId, operator, now) { + const { ctx } = this; + const normalizedWaveId = Number(waveId); + if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) { + return; + } + + // 查询波次下是否还有未复核的订单(recheck_status != 'fin') + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const unreviewedCount = await orderModel.count({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + recheck_status: { [this.app.Sequelize.Op.ne]: 'fin' }, + }, + }); + + if (unreviewedCount > 0) { + return; + } + + // 波次下所有订单均已复核完成,查询已完成订单数并更新波次状态 + const processedCount = await orderModel.count({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + recheck_status: 'fin', + }, + }); + + const operatorName = String(operator.name || operator.id || '').trim(); + + await ctx.model.query( + `UPDATE wms_wave_batch + SET wave_status = 5, + check_operator = :operatorName, + check_time = :now, + processed_orders = :processedCount, + update_time = :now + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId`, + { + replacements: { + waveId: normalizedWaveId, + warehouseId, + operatorName, + processedCount, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + ctx.logger.info( + `[confirmRecheck] 波次复核完成, waveId=${normalizedWaveId}, orderId=${orderId}, processedCount=${processedCount}` + ); + } + + /** + * 在事务内检查订单所属波次下所有订单是否均已复核完成, + * 若全部完成则更新 wms_wave_batch.wave_status = 5(复核完成)。 + * 用于批量快捷复核(batchQuickRecheck)事务内的散单路径。 + * + * @param {number} orderId 当前复核的订单ID。 + * @param {number|string|null} waveId 订单所属波次ID。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _tryCompleteWaveInTransaction(orderId, waveId, warehouseId, operator, now, transaction) { + const { ctx } = this; + const normalizedWaveId = Number(waveId); + if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) { + return; + } + + // 在事务内查询波次下是否还有未复核的订单(recheck_status != 'fin') + const orderModel = await this.getOrderModel('order', warehouseId); + const unreviewedCount = await orderModel.count({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + recheck_status: { [this.app.Sequelize.Op.ne]: 'fin' }, + }, + transaction, + }); + + if (unreviewedCount > 0) { + return; + } + + // 波次下所有订单均已复核完成,查询已完成订单数并更新波次状态 + const processedCount = await orderModel.count({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + recheck_status: 'fin', + }, + transaction, + }); + + const operatorName = String(operator.name || operator.id || '').trim(); + + await ctx.model.query( + `UPDATE wms_wave_batch + SET wave_status = 5, + check_operator = :operatorName, + check_time = :now, + processed_orders = :processedCount, + update_time = :now + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId`, + { + replacements: { + waveId: normalizedWaveId, + warehouseId, + operatorName, + processedCount, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + + ctx.logger.info( + `[batchQuickRecheck] 波次复核完成, waveId=${normalizedWaveId}, orderId=${orderId}, processedCount=${processedCount}` + ); + } + + /** + * 将波次内「已拦截且未打印」的订单移除出波次(回池)。 + * + * 背景:拦截订单无法打印、无法复核,会卡住波次复核完成判定与波次终结; + * 解除拦截后因 wave_id 仍大于 0 而无法被波次策略重新抓取,导致无法继续发货。 + * 复核链路在更新复核状态后调用本方法,把未打印的拦截订单从波次中释放回候选池, + * 拦截解除后即可重新抓取发货;已打印(print_status != 'none')的拦截订单保持不动, + * 避免已贴面单实物与波次记录分离。 + * + * @param {Object} params 移除参数。 + * @param {number} params.waveId 波次ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} params.operator 操作人信息。 + * @param {Object} [params.transaction] Sequelize 事务对象(事务内调用时传入)。 + * @return {Promise<{removed_order_ids: number[], removed_count: number}>} 移除结果。 + */ + async removeUnprintedInterceptedOrdersFromWave({ waveId, warehouseId, operator, transaction = null } = {}) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0 + || !Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return { removed_order_ids: [], removed_count: 0 }; + } + + // 查询波次内「已拦截且未打印」的订单(intercept_status 空值按 none 处理,Op.ne 对 NULL 不命中) + const orderModel = await this.getOrderModelByTableType('current', normalizedWarehouseId); + const removableRows = await orderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + wave_id: normalizedWaveId, + print_status: 'none', + intercept_status: { [this.app.Sequelize.Op.ne]: 'none' }, + }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + transaction, + }); + const normalizedRemovableRows = Array.isArray(removableRows) ? removableRows : []; + const removedOrderIds = [ ...new Set(normalizedRemovableRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + if (removedOrderIds.length === 0) { + return { removed_order_ids: [], removed_count: 0 }; + } + + // 1. 订单 wave_id 清零(回池),清空波次编号与策略扫描标记 + await orderModel.update({ + wave_id: 0, + wave_no: '', + wave_strategy_version: 0, + wave_scan_result: 0, + }, { + where: { + warehouse_id: normalizedWarehouseId, + id: { [this.app.Sequelize.Op.in]: removedOrderIds }, + }, + transaction, + validate: false, + hooks: false, + }); + + // 2. 删除波次索引行(其余订单 wave_index 保持不变仅跳号,避免与已放货篮子编号错位) + const waveService = ctx.service && ctx.service.systemMethods && ctx.service.systemMethods.order + && ctx.service.systemMethods.order.wave; + if (waveService && typeof waveService.deleteOrderWaveIndexByOrderIds === 'function') { + await waveService.deleteOrderWaveIndexByOrderIds({ + warehouseId: normalizedWarehouseId, + orderIds: removedOrderIds, + transaction, + }); + } + + // 3. 移除任务订单关联(散单模式),任务复核完成判定与进度统计不再包含拦截订单 + await ctx.model.query( + `DELETE FROM wms_wave_pick_task_order + WHERE warehouse_id = :warehouseId + AND order_id IN (:orderIds)`, + { + replacements: { + warehouseId: normalizedWarehouseId, + orderIds: removedOrderIds, + }, + transaction, + } + ); + + // 4. 回写波次统计:total_orders 扣除被移除订单数,processed_orders 收敛不超过剩余订单数 + const remainingRows = await orderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + wave_id: normalizedWaveId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + const remainingCount = Array.isArray(remainingRows) ? remainingRows.length : 0; + await ctx.model.query( + `UPDATE wms_wave_batch + SET total_orders = :remainingCount, + processed_orders = LEAST(processed_orders, :remainingCount), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId`, + { + replacements: { + warehouseId: normalizedWarehouseId, + waveId: normalizedWaveId, + remainingCount, + }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + + // 5. 写订单操作日志 ORDER_WAVE_REMOVE(不影响主流程) + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logPayloads = normalizedRemovableRows.map(row => ({ + businessType: 'order', + businessId: `${row.id}`, + operationCode: 'ORDER_WAVE_REMOVE', + operator: { + id: operator && operator.id ? String(operator.id) : null, + name: operator && operator.name ? String(operator.name).trim() : 'system', + }, + extras: { + message: `订单从波次 ${String(row && row.wave_no || '').trim() || '未知波次'} 中移除`, + warehouseId: normalizedWarehouseId, + externalLogType: 'API', + }, + })); + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn(`[recheckOrder.removeUnprintedIntercepted] 写订单操作日志失败,不影响主流程, waveId=${normalizedWaveId}, error=${logErr.message}`); + } + + // 6. 触发波次策略快扫,让回池订单重新进入候选池(拦截未解除时策略仍会排除) + try { + if (waveService && typeof waveService.enqueueWaveStrategyQuickScanPostOrderChange === 'function') { + waveService.enqueueWaveStrategyQuickScanPostOrderChange( + normalizedWarehouseId, + removedOrderIds, + { triggerScan: true, source: 'recheckRemoveUnprintedIntercepted' } + ); + } + } catch (scanErr) { + ctx.logger.warn(`[recheckOrder.removeUnprintedIntercepted] 触发策略快扫失败,不影响主流程, waveId=${normalizedWaveId}, error=${scanErr.message}`); + } + + ctx.logger.info( + `[recheckOrder.removeUnprintedIntercepted] 波次未打印拦截订单已移除回池, waveId=${normalizedWaveId}, removedCount=${removedOrderIds.length}, orderIds=${removedOrderIds.join(',')}` + ); + + return { removed_order_ids: removedOrderIds, removed_count: removedOrderIds.length }; + } + + /** + * 在事务中更新波次拣货任务订单的复核状态,并判断是否需要解绑车任务。 + * 复核状态更新后,会先在事务内清理波次内「已拦截且未打印」的订单(回池), + * 避免其卡住任务完成判定。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} operator 操作人信息。 + * @param {Date} now 当前时间。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _updateTaskOrderReviewInTransaction(orderId, warehouseId, operator, now, transaction) { + const { ctx } = this; + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); + const hasReviewStatus = taskOrderColumnSet.has('review_status'); + + if (!hasReviewStatus) { + return; + } + + const hasReviewUserId = taskOrderColumnSet.has('review_user_id'); + const hasReviewResult = taskOrderColumnSet.has('review_result'); + const hasReviewTime = taskOrderColumnSet.has('review_time'); + const operatorUserId = Number(operator.id) || 0; + + const reviewSetClauses = [ 'review_status = 1' ]; + + if (hasReviewUserId) reviewSetClauses.push('review_user_id = :operatorUserId'); + if (hasReviewResult) reviewSetClauses.push('review_result = 1'); + if (hasReviewTime) reviewSetClauses.push('review_time = :now'); + reviewSetClauses.push('update_time = NOW()'); + + await ctx.model.query( + `UPDATE wms_wave_pick_task_order + SET ${reviewSetClauses.join(',\n ')} + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { + orderId, + warehouseId, + operatorUserId, + now, + }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + + // 复核时在事务内清理波次内「已拦截且未打印」的订单(回池),避免拦截订单卡住任务完成判定 + try { + const cleanupOrderModel = await this.getOrderModelByTableType('current', warehouseId); + const cleanupOrder = await cleanupOrderModel.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id' ], + raw: true, + transaction, + }); + const cleanupWaveId = Number(cleanupOrder && cleanupOrder.wave_id || 0); + if (cleanupWaveId > 0) { + await this.removeUnprintedInterceptedOrdersFromWave({ + waveId: cleanupWaveId, + warehouseId, + operator, + transaction, + }); + } + } catch (removeErr) { + ctx.logger.warn(`[batchQuickRecheck] 清理波次未打印拦截订单失败,不影响复核主流程, orderId=${orderId}, error=${removeErr.message}`); + } + + // 查询当前订单所属的波次拣货任务ID + const taskRows = await ctx.model.query( + `SELECT DISTINCT task_id + FROM wms_wave_pick_task_order + WHERE order_id = :orderId + AND warehouse_id = :warehouseId`, + { + replacements: { orderId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + + const taskId = Number( + (Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0]?.task_id : 0) + ); + + // 团购模式(pick_mode=1/5)回退:wms_wave_pick_task_order 无记录时, + // 通过订单所属波次查找关联的拣货任务(回退查询使用独立连接,不参与当前事务) + let resolvedTaskId = taskId; + if (resolvedTaskId <= 0) { + resolvedTaskId = await this._resolveTaskIdByWaveFallback(orderId, warehouseId); + } + + if (resolvedTaskId <= 0) { + return; + } + + // 检查该任务下是否所有订单都已复核完成 + const allReviewed = await this._checkTaskOrdersAllReviewed(resolvedTaskId, warehouseId); + + if (!allReviewed) { + return; + } + + // 任务下所有订单均已复核完成,解绑车任务 + try { + await this._unbindCartForTaskInTransaction(resolvedTaskId, warehouseId, operatorUserId, transaction); + ctx.logger.info( + `[batchQuickRecheck] 车任务解绑成功, taskId=${resolvedTaskId}, orderId=${orderId}, operatorUserId=${operatorUserId}` + ); + } catch (unbindError) { + ctx.logger.warn( + `[batchQuickRecheck] 解绑车任务失败(复核已成功), taskId=${resolvedTaskId}, orderId=${orderId}, error=${unbindError.message}` + ); + } + + // 更新 wms_wave_pick_task 任务状态:status=3(已完成),review_status=3(复核通过) + const operatorName = String(operator.name || '').trim(); + const taskStatusSetClauses = [ + 'status = 3', + 'review_status = 3', + 'review_finish_time = :now', + 'review_time = :now', + 'update_time = NOW()', + ]; + if (operatorUserId > 0) { + taskStatusSetClauses.push('review_user_id = :operatorUserId'); + taskStatusSetClauses.push('review_user_name = :operatorName'); + } + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET ${taskStatusSetClauses.join(',\n ')} + WHERE id = :taskId + AND warehouse_id = :warehouseId`, + { + replacements: { taskId: resolvedTaskId, warehouseId, operatorUserId, operatorName, now }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + } + + /** + * 在事务中解绑车任务:清空波次拣货任务的车绑定、停用拣货车绑定记录、释放拣货车。 + * + * @param {number} taskId 波次拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} operatorUserId 操作员用户ID。 + * @param {Object} transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _unbindCartForTaskInTransaction(taskId, warehouseId, operatorUserId, transaction) { + const { ctx } = this; + + // 停用拣货车绑定记录 + await ctx.model.query( + `UPDATE wms_pick_task_cart_binding + SET is_active = 0, + unbind_user_id = :operatorUserId, + unbind_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND is_active = 1`, + { + replacements: { taskId, warehouseId, operatorUserId }, + type: ctx.model.QueryTypes.UPDATE, + transaction, + } + ); + } + + /** + * 在事务中写入复核操作日志(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} params.orderId 订单ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {{ id: string|null, name: string }} params.operator 操作人信息。 + * @param {Date} params.now 操作时间。 + * @param {Object} params.transaction Sequelize 事务对象。 + * @return {Promise} 无返回值。 + */ + async _writeRecheckActionLogInTransaction(params = {}) { + const { orderId, warehouseId, operator, now, transaction } = params; + const operatorId = operator && operator.id ? Number(operator.id) : 0; + const operatorName = operator && operator.name ? String(operator.name).trim() : 'system'; + const requestId = `recheck_${warehouseId}_${orderId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: 0, + warehouseId: warehouseId || 0, + waveId: null, + orderId: orderId || 0, + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: 'recheck', + requestId, + operatorId, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify({ + order_id: orderId, + operator_name: operatorName, + recheck_time: now instanceof Date ? now.toISOString() : String(now || ''), + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + transaction, + } + ); + + // 双写 order_operation_log(失败不影响主流程) + try { + const ctx = this.ctx; + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId || ''), + operationCode: 'ORDER_RECHECK', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: '订单复核完成', + orderId: orderId || 0, + }, + }], { transaction }); + } + } catch (e) { + this.ctx.logger.warn('[recheckOrder._writeRecheckActionLogInTransaction] 写入 order_operation_log 失败', { + error: e && e.message, + orderId, + warehouseId, + }); + } + } + +} + +module.exports = RecheckOrderService; diff --git a/app/service/systemMethods/order/reviewOrder.js b/app/service/systemMethods/order/reviewOrder.js new file mode 100644 index 0000000..40bb1de --- /dev/null +++ b/app/service/systemMethods/order/reviewOrder.js @@ -0,0 +1,34 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class ReviewOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,reviewOrder,'; + const _noNeedLog = 'list,reviewOrder'; + const _noNeedAuth = 'list,reviewOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 待审核订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('reviewOrder', data); + } + + /** + * 更新订单审核状态。 + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息。 + */ + async reviewOrder(data = {}) { + return await this.updateReviewOrder(data); + } +} + +module.exports = ReviewOrderService; diff --git a/app/service/systemMethods/order/storageAllocation.js b/app/service/systemMethods/order/storageAllocation.js new file mode 100644 index 0000000..c3bfda1 --- /dev/null +++ b/app/service/systemMethods/order/storageAllocation.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = undefined; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js new file mode 100644 index 0000000..4819e67 --- /dev/null +++ b/app/service/systemMethods/order/wave.js @@ -0,0 +1,15332 @@ +'use strict'; + +const { Op } = require('sequelize'); +const OrderBaseService = require('./base'); +const runWaveStrategyQuickScanRunner = require('../../../lib/wave_strategy_quick_scan_runner'); + +const DEFAULT_PAGE = 1; +const DEFAULT_PAGE_SIZE = 20; +const MAX_PAGE_SIZE = 200; +const BATCH_LIST_MAX_PAGE_SIZE = 500; +const DEFAULT_MAX_WAVE_QUANTITY = 500; +const DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY = 13; +const FETCH_TASK_CACHE_KEY_PREFIX = 'wave:fetch:task:'; +const FETCH_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const BATCH_CANCEL_TASK_CACHE_KEY_PREFIX = 'wave:batch-cancel:'; +const BATCH_CANCEL_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_KEY_PREFIX = 'wave:batch-remove-exception-orders:'; +const BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-express:'; +const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const BATCH_ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-storage:'; +const BATCH_ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX = 'wave:quick-scan:task:'; +const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS = 60 * 5; +const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX = 'wave:quick-scan:lock:'; +const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS = 60 * 60 * 2; +const WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX = 'wave:strategy-list:'; +const WAVE_STRATEGY_LIST_CACHE_TTL_SECONDS = 60 * 30; +const CONFIRM_PRINT_UNCLAIMED_VERSION_KEY_PREFIX = 'wave:confirm-print:unclaimed:version:'; +const CONFIRM_PRINT_UNCLAIMED_POLL_TIMEOUT_MS = 60 * 1000; +const CONFIRM_PRINT_UNCLAIMED_POLL_INTERVAL_MS = 1000; +const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID = 1; +const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS = [ BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID ]; +const BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP = new Map(); +const WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP = Object.freeze({ + id: 'id', + delivery_no: 'delivery_order_code', + deliveryNo: 'delivery_order_code', + tracking_no: 'express_numbers', + trackingNo: 'express_numbers', + items_count: 'items_count', + items_count_min: 'items_count', + items_count_max: 'items_count', + items_total: 'items_total', + items_total_min: 'items_total', + items_total_max: 'items_total', + sys_logistics_name: 'logistics_name', + store_name: 'shop_nick', + owner_name: 'shop_nick', + province: 'province', + sys_platform_name: 'sys_platform_name', +}); +const WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS = Object.freeze({ + locked: '已锁定', + intercepted: '已拦截', + printed: '已打印', + no_match: '未匹配策略', +}); +const BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS = Object.freeze({ + storage: Object.freeze({ + fieldName: 'storage_assignment_status', + enumMap: Object.freeze({ + 未分配: 'none', + 部分分配: 'partial', + 已分配: 'finished', + }), + caseInsensitive: false, + statsColumnPrefix: 'storage', + withErrorStatus: true, + }), + express: Object.freeze({ + fieldName: 'express_assignment_status', + enumMap: Object.freeze({ + unassigned: 'none', + partially_assigned: 'partial', + assigned: 'finished', + }), + caseInsensitive: true, + statsColumnPrefix: 'post', + withErrorStatus: true, + }), + print: Object.freeze({ + fieldName: 'print_assignment_status', + enumMap: Object.freeze({ + unprinted: 'none', + partially_printed: 'partial', + printed: 'finished', + }), + caseInsensitive: true, + statsColumnPrefix: 'print', + withErrorStatus: false, + }), + confirm_print: Object.freeze({ + fieldName: 'confirm_print_assignment_status', + enumMap: Object.freeze({ + unconfirmed: 'none', + partially_confirmed: 'partial', + confirmed: 'finished', + }), + caseInsensitive: true, + statsColumnPrefix: 'confirm_print', + withErrorStatus: false, + }), + review: Object.freeze({ + fieldName: 'review_assignment_status', + enumMap: Object.freeze({ + unreviewed: 'none', + partially_reviewed: 'partial', + reviewed: 'finished', + }), + caseInsensitive: true, + statsColumnPrefix: 'review', + withErrorStatus: true, + }), + sync: Object.freeze({ + fieldName: 'sync_assignment_status', + enumMap: Object.freeze({ + unsynced: 'none', + partially_synced: 'partial', + synced: 'finished', + }), + caseInsensitive: true, + statsColumnPrefix: 'sync', + withErrorStatus: true, + }), +}); + +class WaveService extends OrderBaseService { + /** + * 初始化波次方法权限配置。 + * + * @param {Egg.Context} ctx 请求上下文。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,fetchableOrderCount,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount'; + const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,fetchableOrderCount,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintScan,confirmPrintUnclaimedWaveCount'; + const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,fetchableOrderCount,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 构建批次分配快递号链路追踪ID。 + * + * 优先使用入参中的 trace_id/traceId,其次尝试读取上下文中的 trace 标识, + * 最后兜底生成带时间戳的随机追踪ID。 + * + * @param {Object} [data={}] 入参对象。 + * @param {string} [fallback=''] 兜底业务标识(如 taskId)。 + * @return {string} 追踪ID。 + */ + buildBatchAllocateExpressTraceId(data = {}, fallback = '') { + const normalizedData = this.isPlainObject(data) ? data : {}; + const ctxTraceId = this.ctx && this.ctx.traceId !== undefined + ? this.ctx.traceId + : this.ctx && this.ctx.requestId !== undefined + ? this.ctx.requestId + : this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined + ? this.ctx.state.traceId + : ''; + const normalizedTraceId = String( + normalizedData.trace_id + || normalizedData.traceId + || ctxTraceId + || fallback + || '' + ).trim(); + + if (normalizedTraceId) { + return normalizedTraceId; + } + + return `wave_allocate_express_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + } + + /** + * 构建订单操作日志批量写入数据。 + * + * @param {Array} logItems 日志项。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Array} 可直接用于 bulkCreate 的日志行。 + */ + buildOrderOperationLogRows(logItems = [], warehouseId = 0) { + if (!Array.isArray(logItems) || logItems.length === 0) { + return []; + } + + const normalizedWarehouseId = Number(this.getOrderLogWarehouseId(warehouseId) || 0); + const stateUser = this.isPlainObject(this.ctx && this.ctx.state && this.ctx.state.user) + ? this.ctx.state.user + : null; + const ctxUser = this.isPlainObject(this.ctx && this.ctx.user) + ? this.ctx.user + : null; + const paramsObject = this.isPlainObject(this.params) ? this.params : {}; + const paramsOperator = this.isPlainObject(paramsObject.__operator) + ? paramsObject.__operator + : (this.isPlainObject(paramsObject.operator) ? paramsObject.operator : null); + const operatorSource = stateUser || ctxUser || paramsOperator || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + const platformCode = String(operatorSource.platform_code || 'SYSTEM').trim() || 'SYSTEM'; + + return logItems + .map(item => { + const orderId = Number(item && item.orderId || 0); + const operationCode = String(item && item.operationCode || '').trim() || 'ORDER_WAVE_UPDATE'; + const message = String(item && item.message || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0 || !message) { + return null; + } + + return { + business_type: 'order', + business_id: `${orderId}`, + operation_code: operationCode, + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : null, + platform_code: platformCode, + message, + }; + }) + .filter(Boolean); + } + + /** + * 批量写入订单操作日志。 + * + * 该方法为业务降级路径,写入失败仅告警,不影响主流程。 + * + * @param {Array} logItems 日志项。 + * @param {Object} options 写入选项。 + * @param {number|string} options.warehouseId 仓库ID。 + * @param {string} [options.scene='wave'] 场景标识,用于日志追踪。 + * @return {Promise} 实际写入条数。 + */ + async batchCreateOrderOperationLogs(logItems = [], options = {}) { + const rows = this.buildOrderOperationLogRows(logItems, options && options.warehouseId); + const loggerWarn = this.ctx.logger && typeof this.ctx.logger.warn === 'function' + ? this.ctx.logger.warn.bind(this.ctx.logger) + : null; + if (rows.length === 0) { + return 0; + } + + const operationLogModel = this.ctx.model && this.ctx.model.OperationLog; + if (!operationLogModel || typeof operationLogModel.bulkCreate !== 'function') { + if (loggerWarn) { + loggerWarn('[wave.batchCreateOrderOperationLogs] OperationLog.bulkCreate 不可用,跳过写入', { + scene: String(options && options.scene || 'wave'), + rows: rows.length, + }); + } + return 0; + } + + try { + await operationLogModel.bulkCreate(rows); + return rows.length; + } catch (error) { + if (loggerWarn) { + loggerWarn('[wave.batchCreateOrderOperationLogs] 批量写订单操作日志失败,不影响主流程', { + scene: String(options && options.scene || 'wave'), + rows: rows.length, + error: error && error.message ? error.message : `${error}`, + }); + } + return 0; + } + } + + /** + * 构建稳定机器结构标识(可作为抓取接口入参)。 + * + * @param {Object} params 结构参数。 + * @param {string} params.item_part_type 商品结构来源字段类型。 + * @param {string} params.item_part 商品结构来源值。 + * @param {boolean} params.distinguish_express 是否区分快递。 + * @param {string} params.logistics_name 快递名称。 + * @param {string} params.item_snapshot_key 机器明细快照。 + * @return {string} 稳定机器结构标识。 + */ + buildMachineStructureToken(params = {}) { + const itemPartType = String(params.item_part_type || 'items_hash').trim() || 'items_hash'; + const itemPart = encodeURIComponent(String(params.item_part || '').trim()); + const distinguishExpress = params.distinguish_express ? '1' : '0'; + const logisticsName = encodeURIComponent(String(params.logistics_name || '').trim()); + const itemSnapshotKey = encodeURIComponent(String(params.item_snapshot_key || '').trim()); + + return `v1|${itemPartType}|${itemPart}|${distinguishExpress}|${logisticsName}|${itemSnapshotKey}`; + } + + /** + * 解析机器结构标识。 + * + * @param {string} token 机器结构标识。 + * @return {{ item_part_type: string, item_part: string, distinguish_express: boolean, logistics_name: string, item_snapshot_key: string }} 解析结果。 + */ + parseMachineStructureToken(token) { + const normalizedToken = String(token || '').trim(); + const parts = normalizedToken.split('|'); + + if (parts.length < 6 || parts[0] !== 'v1') { + throw new Error('item_detail_machine 格式不合法'); + } + + const itemPartType = String(parts[1] || '').trim(); + if (![ 'items_hash', 'items' ].includes(itemPartType)) { + throw new Error('item_detail_machine item_part_type 不支持'); + } + + const itemPart = decodeURIComponent(String(parts[2] || '').trim()); + if (!itemPart) { + throw new Error('item_detail_machine item_part 不能为空'); + } + + const distinguishExpress = String(parts[3] || '') === '1'; + const logisticsName = decodeURIComponent(String(parts[4] || '').trim()); + const itemSnapshotKey = decodeURIComponent(String(parts[5] || '').trim()); + + return { + item_part_type: itemPartType, + item_part: itemPart, + distinguish_express: distinguishExpress, + logistics_name: logisticsName, + item_snapshot_key: itemSnapshotKey, + }; + } + + /** + * 获取订单可分组的商品结构值(优先 items_hash)。 + * + * @param {Object} order 订单主表记录。 + * @return {{ item_part_type: string, item_part: string }} 分组结构值。 + */ + getOrderItemPart(order = {}) { + const itemsHash = String(order.items_hash || '').trim(); + if (itemsHash) { + return { + item_part_type: 'items_hash', + item_part: itemsHash, + }; + } + + return { + item_part_type: 'items', + item_part: String(order.items || '').trim(), + }; + } + + /** + * 读取默认抓取数量(缓存优先,缓存 miss 再读库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 默认抓取数量。 + */ + async getDefaultWaveQuantity(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return DEFAULT_MAX_WAVE_QUANTITY; + } + + try { + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const maxWaveQuantity = Number(this.getWarehouseSubjectConfigValue(subjectConfig, 'max_wave_quantity')); + if (!Number.isInteger(maxWaveQuantity) || maxWaveQuantity <= 0) { + return DEFAULT_MAX_WAVE_QUANTITY; + } + + return maxWaveQuantity; + } catch (error) { + this.ctx.logger.warn('[wave.getDefaultWaveQuantity] 获取仓库默认波次数量失败: %s', error.message); + return DEFAULT_MAX_WAVE_QUANTITY; + } + } + + /** + * 读取最小团购抓取数量(缓存优先,缓存 miss 再读库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 最小团购抓取数量。 + */ + async getMinGroupOrderFetchQuantity(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; + } + + try { + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const minGroupOrderFetchQuantity = Number( + this.getWarehouseSubjectConfigValue(subjectConfig, 'min_group_order_fetch_quantity') + ); + if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) { + return DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; + } + + return minGroupOrderFetchQuantity; + } catch (error) { + this.ctx.logger.warn('[wave.getMinGroupOrderFetchQuantity] 获取仓库最小团购抓取数量失败: %s', error.message); + return DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; + } + } + + /** + * 读取团购波次编号前缀(缓存优先,缓存 miss 再读库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 团购波次编号前缀。 + */ + async getGroupWavePrefix(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return 'B'; + } + + try { + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const groupWavePrefix = String( + this.getWarehouseSubjectConfigValue(subjectConfig, 'group_wave_prefix') || '' + ).trim(); + if (!groupWavePrefix) { + return 'B'; + } + + return groupWavePrefix.slice(0, 5); + } catch (error) { + this.ctx.logger.warn('[wave.getGroupWavePrefix] 获取仓库团购波次前缀失败: %s', error.message); + return 'B'; + } + } + + /** + * 读取散单波次编号前缀(缓存优先,缓存 miss 再读库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 散单波次编号前缀。 + */ + async getSingleFetchByIdsWavePrefix(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return 'A'; + } + + try { + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const singleFetchByIdsWavePrefix = String( + this.getWarehouseSubjectConfigValue(subjectConfig, 'delete_order_wave_prefix') || '' + ).trim(); + if (!singleFetchByIdsWavePrefix) { + return 'A'; + } + + return singleFetchByIdsWavePrefix.slice(0, 5); + } catch (error) { + this.ctx.logger.warn('[wave.getSingleFetchByIdsWavePrefix] 获取仓库散单波次前缀失败: %s', error.message); + return 'A'; + } + } + + /** + * 统一读取仓库主体配置(缓存优先,缓存 miss 回源数据库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 仓库主体配置对象。 + */ + async getWarehouseSubjectConfig(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return {}; + } + + const deliveryOrderService = this.ctx.service.systems && this.ctx.service.systems.deliveryOrder; + if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') { + return {}; + } + + const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(normalizedWarehouseId); + return this.isPlainObject(subjectConfig) ? subjectConfig : {}; + } + + /** + * 从仓库主体配置中读取字段值,优先 subject_config 内嵌配置。 + * + * @param {Object} subjectConfig 仓库主体配置。 + * @param {string} key 字段名。 + * @return {*} 字段值。 + */ + getWarehouseSubjectConfigValue(subjectConfig = {}, key = '') { + const normalizedKey = String(key || '').trim(); + if (!normalizedKey) { + return undefined; + } + + const normalizedSubjectConfig = this.isPlainObject(subjectConfig) ? subjectConfig : {}; + const nestedSubjectConfig = this.isPlainObject(normalizedSubjectConfig.subject_config) + ? normalizedSubjectConfig.subject_config + : {}; + + if (nestedSubjectConfig[normalizedKey] !== undefined) { + return nestedSubjectConfig[normalizedKey]; + } + + return normalizedSubjectConfig[normalizedKey]; + } + + /** + * 解析抓取结构请求参数。 + * + * @param {Object} data 请求参数。 + * @param {number} defaultQuantity 默认抓取数量。 + * @return {Array} 结构化请求。 + */ + normalizeFetchStructureRequests(data = {}, defaultQuantity = DEFAULT_MAX_WAVE_QUANTITY) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawStructureList = requestData.structure_list; + + if (!Array.isArray(rawStructureList) || rawStructureList.length === 0) { + throw new Error('structure_list 必须是非空数组'); + } + + return rawStructureList.map((item, index) => { + if (!this.isPlainObject(item)) { + throw new Error(`structure_list[${index}] 必须是对象`); + } + + const itemDetailMachine = String(item.item_detail_machine || '').trim(); + if (!itemDetailMachine) { + throw new Error(`structure_list[${index}].item_detail_machine 不能为空`); + } + + const parsedToken = this.parseMachineStructureToken(itemDetailMachine); + const quantity = item.quantity === undefined || item.quantity === null || item.quantity === '' + ? defaultQuantity + : this.normalizePositiveInteger(item.quantity, `structure_list[${index}].quantity`, defaultQuantity); + + if (!Number.isInteger(quantity) || quantity <= 0) { + throw new Error(`structure_list[${index}].quantity 必须大于 0`); + } + + return { + index, + item_detail_machine: itemDetailMachine, + quantity, + ...parsedToken, + }; + }); + } + + /** + * 生成可排序且足够唯一的 wave_id。 + * + * @param {number} suffix 同批次偏移量。 + * @return {number} 波次ID。 + */ + generateWaveId(suffix = 0) { + const base = Date.now() * 1000; + const randomPart = Math.floor(Math.random() * 900) + 100; + return base + randomPart + Number(suffix || 0); + } + + /** + * 获取当前日期片段(YYYYMMDD)。 + * + * @return {string} 当前日期片段。 + */ + getCurrentDatePart() { + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; + } + + /** + * 获取当天前缀下的下一个波次序号(原子取号)。 + * + * 基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date 串行化并发事务): + * INSERT ... VALUES (:seed + 1) ON DUPLICATE KEY UPDATE + * current_seq = GREATEST(current_seq, :seed) + 1 + * 其中 :seed 为当日该前缀主表已有最大序号,保证与历史编号对齐; + * upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq, + * 避免 REPEATABLE READ 快照读读到旧值导致撞号或跳号。 + * 注意:不再依赖 LAST_INSERT_ID() 回读,因为 fresh INSERT 时其会被序列表自增主键覆盖。 + * + * @param {string} prefix 波次编号前缀。 + * @param {string} datePart 日期片段(YYYYMMDD)。 + * @param {Object} transaction Sequelize 事务。 + * @return {Promise} 下一个序号(最小为 1)。 + */ + async getNextWaveNoSequence(prefix, datePart, transaction) { + const normalizedPrefix = String(prefix || '').trim() || 'B'; + const normalizedDatePart = String(datePart || '').trim(); + const pattern = `${normalizedPrefix}${normalizedDatePart}%`; + const prefixDatePartLength = normalizedPrefix.length + normalizedDatePart.length; + const bizType = `wave_no_${normalizedPrefix.slice(0, 20)}`; + + // 历史对齐种子:当日该前缀主表已有最大序号(无则为 0) + const seedRows = await this.ctx.model.query( + `SELECT IFNULL(MAX(CAST(SUBSTRING(wave_no, :startPos) AS UNSIGNED)), 0) AS max_seq + FROM wms_wave_batch + WHERE wave_no LIKE :pattern`, + { + replacements: { + pattern, + startPos: prefixDatePartLength + 1, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq || 0); + + // 原子取号:全局维度(warehouse_id=0)按「前缀+日期」递增,唯一键串行化并发事务 + await this.ctx.model.query( + `INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at) + VALUES (:warehouseId, :bizType, :datePart, :seed + 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`, + { + replacements: { + warehouseId: 0, + bizType, + datePart: normalizedDatePart, + seed, + }, + transaction, + } + ); + + // 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化), + // FOR UPDATE 返回本事务最新写入值或最新提交版本,不受旧快照影响 + const seqRows = await this.ctx.model.query( + `SELECT current_seq + FROM wms_number_sequence + WHERE warehouse_id = :warehouseId AND biz_type = :bizType AND date_part = :datePart + FOR UPDATE`, + { + replacements: { + warehouseId: 0, + bizType, + datePart: normalizedDatePart, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const sequence = Number(seqRows && seqRows[0] && seqRows[0].current_seq || 0); + if (!Number.isInteger(sequence) || sequence <= 0) { + return 1; + } + + return sequence; + } + + /** + * 构建波次编号。 + * + * @param {string} [prefix='B'] 波次编号前缀。 + * @param {string} [datePart=''] 日期片段(YYYYMMDD)。 + * @param {number|string} [sequence=1] 当天序号。 + * @return {string} 波次编号。 + */ + buildWaveNo(prefix = 'B', datePart = '', sequence = 1) { + const normalizedPrefix = String(prefix || '').trim(); + const normalizedDatePart = String(datePart || '').trim(); + const normalizedSequence = Number(sequence || 0); + const safeSequence = Number.isInteger(normalizedSequence) && normalizedSequence > 0 ? normalizedSequence : 1; + return `${normalizedPrefix}${normalizedDatePart}${String(safeSequence).padStart(5, '0')}`; + } + + /** + * 获取波次创建人。 + * + * 优先级:employees_name > real_name > name > id(字符串) > system。 + * + * @return {string} 创建人。 + */ + getWaveCreator() { + const user = this.isPlainObject(this.ctx.user) ? this.ctx.user : {}; + const creator = String(user.employees_name || user.real_name || user.name || '').trim(); + if (creator) { + return creator; + } + + const userId = user.id; + if (userId !== undefined && userId !== null && userId !== '') { + return `${userId}`; + } + + return 'system'; + } + + /** + * 从 SQL 执行结果中提取 insertId。 + * + * @param {*} queryResult Sequelize query 返回值。 + * @return {number} 自增主键ID,提取失败返回 0。 + */ + extractInsertId(queryResult) { + if (Array.isArray(queryResult)) { + const [ first, second ] = queryResult; + const firstInsertId = Number(first && first.insertId || 0); + if (Number.isInteger(firstInsertId) && firstInsertId > 0) { + return firstInsertId; + } + + const secondInsertId = Number(second && second.insertId || 0); + if (Number.isInteger(secondInsertId) && secondInsertId > 0) { + return secondInsertId; + } + } + + const directInsertId = Number(queryResult && queryResult.insertId || 0); + if (Number.isInteger(directInsertId) && directInsertId > 0) { + return directInsertId; + } + + return 0; + } + + /** + * 从 LAST_INSERT_ID 查询结果中提取 insertId。 + * + * @param {*} queryResult Sequelize query 返回值。 + * @return {number} 自增主键ID,提取失败返回 0。 + */ + extractLastInsertId(queryResult) { + const directInsertId = this.extractInsertId(queryResult); + if (Number.isInteger(directInsertId) && directInsertId > 0) { + return directInsertId; + } + + if (!Array.isArray(queryResult)) { + return 0; + } + + const [ first ] = queryResult; + if (Array.isArray(first) && first.length > 0) { + for (const row of first) { + const rowInsertId = Number( + row && (row.insertId || row.insert_id || row.LAST_INSERT_ID || row.last_insert_id) || 0 + ); + if (Number.isInteger(rowInsertId) && rowInsertId > 0) { + return rowInsertId; + } + } + } + + return 0; + } + + /** + * 判断数据库错误是否为唯一键冲突(重复键 ER_DUP_ENTRY)。 + * + * @param {*} error 数据库异常对象。 + * @return {boolean} 是否唯一键冲突。 + */ + isDuplicateEntryError(error) { + const errno = Number( + error && (error.original && error.original.errno || error.parent && error.parent.errno || error.errno) || 0 + ); + const code = String( + error && (error.original && error.original.code || error.parent && error.parent.code || error.code) || '' + ); + return errno === 1062 || code === 'ER_DUP_ENTRY'; + } + + /** + * 根据波次元信息推导订单 wave_scope(波次范围)。 + * + * 口径: + * - wave_type=1 且 source=0 → 1(大团购); + * - wave_type=1 且 source=2 → 3(小团购); + * - wave_type=2 且 pickMode=2 → 4(单品单件); + * - 其余(散单等)→ 2(散单)。 + * 未分配波次(wave_id=0)由调用方直接置 0。 + * + * @param {number|string} waveType 波次类型(1-团购 2-散单)。 + * @param {number|string} source 波次来源(0-普通 1-管理后台策略 2-PDA策略)。 + * @param {number|string} [pickMode] 拣货模式(1-小团购 2-单品单件 3-先拣后分 4-边拣边分 5-大团购)。 + * @return {number} wave_scope:1-大团购 2-散单 3-小团购 4-单品单件。 + */ + resolveWaveScopeByWaveMeta(waveType, source, pickMode) { + const normalizedWaveType = Number(waveType) === 2 ? 2 : 1; + const normalizedSource = [ 0, 1, 2 ].includes(Number(source)) ? Number(source) : 0; + const normalizedPickMode = [ 1, 2, 3, 4, 5 ].includes(Number(pickMode)) + ? Number(pickMode) + : 0; + + if (normalizedWaveType === 1 && normalizedSource === 0) { + return 1; + } + + if (normalizedWaveType === 1 && normalizedSource === 2) { + return 3; + } + + if (normalizedWaveType === 2 && normalizedPickMode === 2) { + return 4; + } + + return 2; + } + + /** + * 新增一条“已就绪”波次批次记录,并返回自增 wave_id。 + * + * @param {Object} params 入参。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.totalOrders 订单总数。 + * @param {string} params.itemDetailMachine 机器结构标识。 + * @param {string} params.itemPartType 商品结构来源字段类型。 + * @param {string} params.itemPart 商品结构来源值。 + * @param {number|boolean|string} params.distinguishExpress 是否区分快递(归一化为0/1)。 + * @param {string} params.logisticsName 快递名称。 + * @param {string} params.itemSnapshotKey 机器明细快照。 + * @param {string} [params.wavePrefix] 波次编号前缀。 + * @param {string} [params.waveNo] 波次编号(传入则直接使用)。 + * @param {number|string} [params.waveType=1] 波次类型,仅允许 1(团购)或 2(散单),非法值回退 1。 + * @param {number|string} [params.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 + * @param {Object} params.transaction Sequelize 事务。 + * @return {Promise<{waveId: number, waveNo: string}>} 创建结果。 + */ + async createWaveBatchReady({ + warehouseId, + totalOrders, + itemDetailMachine, + itemPartType, + itemPart, + distinguishExpress, + logisticsName, + itemSnapshotKey, + wavePrefix, + waveNo, + waveType, + source, + transaction, + } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedTotalOrders = Number(totalOrders || 0); + const normalizedItemDetailMachine = String(itemDetailMachine || '').trim(); + const normalizedItemPartType = String(itemPartType || '').trim(); + const normalizedItemPart = String(itemPart || '').trim(); + const normalizedDistinguishExpress = distinguishExpress === true || Number(distinguishExpress) === 1 ? 1 : 0; + const normalizedLogisticsName = String(logisticsName || '').trim(); + const normalizedItemSnapshotKey = String(itemSnapshotKey || '').trim(); + const normalizedWavePrefix = String(wavePrefix || '').trim() || 'B'; + const normalizedWaveNoInput = String(waveNo || '').trim(); + const normalizedWaveType = Number(waveType) === 2 ? 2 : 1; + const normalizedSourceInput = Number(source); + const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; + const retryOnDuplicate = !normalizedWaveNoInput; + const maxWaveNoAttempts = retryOnDuplicate ? 3 : 1; + let normalizedWaveNo = normalizedWaveNoInput; + const creator = this.getWaveCreator(); + + const sql = ` + INSERT INTO wms_wave_batch + ( + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + item_detail_machine, + item_part_type, + item_part, + distinguish_express, + logistics_name, + item_snapshot_key, + warehouse_id, + creator, + source, + create_time, + update_time + ) + VALUES + ( + :waveNo, + :waveType, + 1, + :totalOrders, + 0, + :itemDetailMachine, + :itemPartType, + :itemPart, + :distinguishExpress, + :logisticsName, + :itemSnapshotKey, + :warehouseId, + :creator, + :source, + NOW(), + NOW() + ) + `; + + // 撞号重试:唯一索引兜底下,并发撞号时自动重新取号(最多 3 次) + let createResult = null; + for (let attempt = 1; attempt <= maxWaveNoAttempts; attempt += 1) { + if (!normalizedWaveNo) { + const datePart = this.getCurrentDatePart(); + const sequence = await this.getNextWaveNoSequence(normalizedWavePrefix, datePart, transaction); + normalizedWaveNo = this.buildWaveNo(normalizedWavePrefix, datePart, sequence); + } + + try { + createResult = await this.ctx.model.query(sql, { + replacements: { + waveNo: normalizedWaveNo, + waveType: normalizedWaveType, + totalOrders: normalizedTotalOrders, + itemDetailMachine: normalizedItemDetailMachine, + itemPartType: normalizedItemPartType, + itemPart: normalizedItemPart, + distinguishExpress: normalizedDistinguishExpress, + logisticsName: normalizedLogisticsName, + itemSnapshotKey: normalizedItemSnapshotKey, + warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0, + creator, + source: normalizedSource, + }, + transaction, + }); + break; + } catch (error) { + const isDuplicateWaveNo = this.isDuplicateEntryError(error); + if (!retryOnDuplicate || !isDuplicateWaveNo || attempt >= maxWaveNoAttempts) { + throw error; + } + + this.ctx.logger.warn( + '[wave.createWaveBatchReady] 波次编号 %s 已存在(撞号),自动重新取号重试 %d/%d', + normalizedWaveNo, + attempt, + maxWaveNoAttempts + ); + normalizedWaveNo = ''; + } + } + + let insertedWaveId = this.extractInsertId(createResult); + if (!Number.isInteger(insertedWaveId) || insertedWaveId <= 0) { + const fallbackResult = await this.ctx.model.query('SELECT LAST_INSERT_ID() AS insertId', { + transaction, + }); + insertedWaveId = this.extractLastInsertId(fallbackResult); + } + + if (!Number.isInteger(insertedWaveId) || insertedWaveId <= 0) { + throw new Error('创建波次失败,未获取到自增 wave_id'); + } + + return { + waveId: insertedWaveId, + waveNo: normalizedWaveNo, + }; + } + + /** + * 构建「排除 SN(序列号管理)订单」筛选条件。 + * + * has_sn_item='Y' 为序列号订单;NULL 视为非 SN(兼容未回填的存量行)。 + * + * @return {Object} Sequelize 条件。 + */ + buildExcludeSnOrderCondition() { + return { + [Op.or]: [ + { has_sn_item: { [Op.is]: null } }, + { has_sn_item: { [Op.ne]: 'Y' } }, + ], + }; + } + + /** + * 过滤候选订单中的 SN(序列号管理)订单。 + * + * @param {Array} rows 候选订单行(需含 has_sn_item)。 + * @return {Array} 非 SN 订单行。 + */ + filterNonSnCandidateRows(rows = []) { + return (Array.isArray(rows) ? rows : []) + .filter(row => String(row && row.has_sn_item || '').trim().toUpperCase() !== 'Y'); + } + + /** + * 构建抓取候选订单筛选条件。 + * + * @param {Object} structure 结构化请求。 + * @param {Object} [options={}] 附加选项。 + * @param {boolean} [options.excludeSnOrders=false] 是否排除 SN(序列号管理)订单。 + * @return {Object} Sequelize where 条件。 + */ + buildFetchWhere(structure = {}, options = {}) { + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const where = { + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', + wave_id: 0, + // 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行) + is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + }; + + if (normalizedOptions.excludeSnOrders === true) { + where[Op.and] = [ this.buildExcludeSnOrderCondition() ]; + } + + const itemPartType = String(structure.item_part_type || '').trim(); + const itemPart = String(structure.item_part || '').trim(); + if (itemPartType === 'items_hash') { + where.items_hash = itemPart; + } else { + where.items = itemPart; + } + + if (structure.distinguish_express) { + const expressCode = String(structure.logistics_name || '').trim(); + if (expressCode) { + where.sys_logistics_code = expressCode; + } + } + + return where; + } + + /** + * 按单个结构抓取订单并写入同一波次。 + * + * @param {Object} model 订单主表模型。 + * @param {Object} structure 结构化请求。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} [wavePrefix='B'] 波次编号前缀。 + * @param {number} [minGroupOrderFetchQuantity=13] 最小团购抓取数量。 + * @param {Object} [options={}] 额外抓取选项。 + * @param {number} [options.maxFetchQuantity=0] 本结构最大抓取订单数上限,0 表示不限制。 + * @param {boolean} [options.excludeSnOrders=false] 是否排除 SN(序列号管理)订单(团购抓取固定 true)。 + * @param {number|string} [options.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 + * @return {Promise} 单结构抓取结果。 + */ + async fetchSingleStructure( + model, + structure = {}, + warehouseId = 0, + wavePrefix = 'B', + minGroupOrderFetchQuantity = DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY, + options = {} + ) { + const { ctx } = this; + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const where = this.buildFetchWhere(structure, normalizedOptions); + const requestedQuantity = Number(structure.quantity || 0); + const normalizedMaxFetchQuantity = Number.isInteger(Number(normalizedOptions.maxFetchQuantity)) + && Number(normalizedOptions.maxFetchQuantity) > 0 + ? Number(normalizedOptions.maxFetchQuantity) + : 0; + const normalizedSourceInput = Number(normalizedOptions.source); + const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; + const logOperator = this.getOrderLogOperator() || {}; + const claimOperator = String(logOperator.name || '').trim() || null; + const grabOperatorId = Number(logOperator.id || 0) > 0 ? Number(logOperator.id) : null; + const normalizedMinGroupOrderFetchQuantity = Number.isInteger(Number(minGroupOrderFetchQuantity)) + && Number(minGroupOrderFetchQuantity) > 0 + ? Number(minGroupOrderFetchQuantity) + : DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; + const allWaveIds = []; + const allOrderIds = []; + const fetchedOrderLogItems = []; + let totalFetchedQuantity = 0; + let remainingFetchQuantity = normalizedMaxFetchQuantity; + let stopReason = ''; + const transaction = await ctx.model.transaction(); + try { + for (;;) { + let fetchLimit = requestedQuantity; + if (normalizedMaxFetchQuantity > 0) { + if (remainingFetchQuantity <= 0) { + stopReason = '达到最大抓取上限'; + break; + } + fetchLimit = Math.min(fetchLimit, remainingFetchQuantity); + } + + const rows = await model.findAll({ + where, + attributes: [ 'id' ], + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + order: [[ 'id', 'DESC' ]], + limit: fetchLimit, + }); + + const candidateOrderIds = rows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + + if (candidateOrderIds.length === 0) { + if (totalFetchedQuantity === 0) { + stopReason = '无可抓取订单'; + } + break; + } + + if (candidateOrderIds.length < normalizedMinGroupOrderFetchQuantity) { + stopReason = '剩余订单低于最小团购抓取数量'; + break; + } + + const { waveId, waveNo } = await this.createWaveBatchReady({ + warehouseId, + totalOrders: candidateOrderIds.length, + itemDetailMachine: structure.item_detail_machine, + itemPartType: structure.item_part_type, + itemPart: structure.item_part, + distinguishExpress: structure.distinguish_express, + logisticsName: structure.logistics_name, + itemSnapshotKey: structure.item_snapshot_key, + wavePrefix, + source: normalizedSource, + transaction, + }); + await model.update({ + wave_id: waveId, + wave_no: waveNo, + wave_scope: this.resolveWaveScopeByWaveMeta(1, normalizedSource), + grab_operator_id: grabOperatorId, + grab_operator: claimOperator, + }, { + where: { + id: { [Op.in]: candidateOrderIds }, + wave_id: 0, + }, + transaction, + }); + + // 抓取波次(source=1/2)无需领料:将抓取人冗余写入领料人字段,便于追溯 + if ([ 1, 2 ].includes(normalizedSource) && claimOperator) { + await ctx.model.WaveBatch.update( + { + claim_operator: claimOperator, + claim_time: new Date(), + }, + { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + }, + transaction, + } + ); + } + + const grabbedRows = await model.findAll({ + where: { + id: { [Op.in]: candidateOrderIds }, + wave_id: waveId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + + const grabbedOrderIds = grabbedRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0) + .sort((a, b) => a - b); + + const fetchedQuantity = grabbedOrderIds.length; + if (fetchedQuantity <= 0) { + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE wave_id = :waveId + `, { + replacements: { waveId }, + transaction, + }); + + if (totalFetchedQuantity === 0) { + stopReason = '无可抓取订单'; + } + break; + } + + if (fetchedQuantity !== candidateOrderIds.length) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :totalOrders, + update_time = NOW() + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + totalOrders: fetchedQuantity, + }, + transaction, + }); + } + + allWaveIds.push(waveId); + allOrderIds.push(...grabbedOrderIds); + fetchedOrderLogItems.push(...grabbedOrderIds.map(orderId => ({ + orderId, + operationCode: 'ORDER_WAVE_ASSIGN', + message: `订单被分配到波次 ${waveNo}`, + }))); + totalFetchedQuantity += fetchedQuantity; + if (normalizedMaxFetchQuantity > 0) { + remainingFetchQuantity -= fetchedQuantity; + if (remainingFetchQuantity <= 0) { + stopReason = '达到最大抓取上限'; + break; + } + } + } + + if (allWaveIds.length > 0 && allOrderIds.length > 0) { + await this.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: allWaveIds, + orderModel: model, + transaction, + }); + } + + await transaction.commit(); + await this.batchCreateOrderOperationLogs(fetchedOrderLogItems, { + warehouseId, + scene: 'fetchSingleStructure', + }); + + // 抓取波次(source=1/2)会冗余写入领料人/领料时间,递增统计版本号驱动长轮询 + await this.bumpConfirmPrintUnclaimedWaveVersion(warehouseId); + + const mergedOrderIds = [ ...new Set(allOrderIds) ].sort((a, b) => a - b); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, mergedOrderIds, { + triggerScan: false, + source: 'fetchSingleStructure', + }); + let reason = stopReason; + if (!reason && totalFetchedQuantity > 0 && totalFetchedQuantity < requestedQuantity) { + reason = '可抓取订单不足'; + } + + return { + item_detail_machine: structure.item_detail_machine, + request_quantity: requestedQuantity, + fetched_quantity: totalFetchedQuantity, + ...(normalizedMaxFetchQuantity > 0 ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + ...(normalizedMaxFetchQuantity > 0 ? { limit_reached: totalFetchedQuantity >= normalizedMaxFetchQuantity } : {}), + wave_id: allWaveIds.length > 0 ? allWaveIds[0] : 0, + wave_ids: allWaveIds, + order_ids: mergedOrderIds, + ...(reason ? { reason } : {}), + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + normalizeBoolean(value, defaultValue = false) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return value === 1; + } + + const normalized = String(value).trim().toLowerCase(); + if ([ '1', 'true', 'yes', 'y', 'on' ].includes(normalized)) { + return true; + } + + if ([ '0', 'false', 'no', 'n', 'off' ].includes(normalized)) { + return false; + } + + return defaultValue; + } + + normalizePositiveInteger(value, fieldName, defaultValue = 0) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const num = Number(value); + if (!Number.isInteger(num) || num < 0) { + throw new Error(`${fieldName} 参数不合法`); + } + + return num; + } + + /** + * 解析必填的正整数参数。 + * + * @param {*} value 原始参数值。 + * @param {string} fieldName 字段名称。 + * @return {number} 归一化后的正整数。 + */ + normalizeRequiredPositiveInteger(value, fieldName) { + if (value === undefined || value === null || value === '') { + throw new Error(`${fieldName} 参数不能为空`); + } + + const normalizedValue = Number(value); + if (!Number.isInteger(normalizedValue) || normalizedValue <= 0) { + throw new Error(`${fieldName} 参数必须为正整数`); + } + + return normalizedValue; + } + + /** + * 归一化 ids 入参为去重后的正整数数组。 + * + * 支持数组、逗号分隔字符串、单个 number/string。 + * + * @param {Array|number|string} value 原始 ids 入参。 + * @return {Array} 归一化后的 ids 数组。 + */ + normalizeIdsInput(value) { + let sourceList = []; + + if (Array.isArray(value)) { + sourceList = value; + } else if (typeof value === 'string') { + sourceList = value.split(','); + } else if (typeof value === 'number') { + sourceList = [ value ]; + } else { + sourceList = []; + } + + const normalizedIds = sourceList + .map(item => String(item === undefined || item === null ? '' : item).trim()) + .filter(item => item !== '') + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0); + + return [ ...new Set(normalizedIds) ]; + } + + /** + * 规范化分页参数。 + * + * @param {Object} data 请求参数;兼容直接传入 pagination 对象。 + * @param {Object} data.pagination 分页参数对象。 + * @param {number|string} data.pagination.page 页码。 + * @param {number|string} data.pagination.pageSize 每页数量(驼峰写法,可用)。 + * @param {number|string} data.pagination.page_size 每页数量(下划线写法,可用)。 + * @param {number|string} data.pagination.limit 每页数量(limit 写法,可用)。 + * @param {number|string} data.pagination.size 每页数量(size 写法,可用)。 + * @param {number|string} data.page 页码(直接分页对象写法)。 + * @param {number|string} data.pageSize 每页数量(直接分页对象驼峰写法)。 + * @param {number|string} data.page_size 每页数量(直接分页对象下划线写法)。 + * @param {number|string} data.limit 每页数量(直接分页对象 limit 写法)。 + * @param {number|string} data.size 每页数量(直接分页对象 size 写法)。 + * @param {Object} options 规范化选项。 + * @param {number|string} options.maxPageSize 每页数量上限。 + * @return {{ page: number, pageSize: number }} 规范化后的分页信息。 + */ + normalizePagination(data = {}, options = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const pagination = this.isPlainObject(normalizedData.pagination) ? normalizedData.pagination : normalizedData; + const pageSource = pagination.page; + const pageSizeSource = pagination.pageSize ?? pagination.page_size ?? pagination.limit ?? pagination.size; + const maxPageSizeSource = Number(options.maxPageSize || MAX_PAGE_SIZE); + const maxPageSize = Number.isInteger(maxPageSizeSource) && maxPageSizeSource > 0 + ? maxPageSizeSource + : MAX_PAGE_SIZE; + + const page = Number(pageSource || DEFAULT_PAGE); + const pageSize = Number(pageSizeSource || DEFAULT_PAGE_SIZE); + + const normalizedPage = Number.isInteger(page) && page > 0 ? page : DEFAULT_PAGE; + const normalizedPageSize = Number.isInteger(pageSize) && pageSize > 0 + ? Math.min(pageSize, maxPageSize) + : DEFAULT_PAGE_SIZE; + + return { + page: normalizedPage, + pageSize: normalizedPageSize, + }; + } + + /** + * 规范化波次状态列表。 + * + * @param {Array} value 波次状态列表。 + * @return {Array} 规范化后的状态数组。 + */ + normalizeWaveStatusList(value) { + if (!Array.isArray(value)) { + return [ 0, 1 ]; + } + + const statusList = value + .map(item => Number(item)) + .filter(item => Number.isInteger(item)); + + if (statusList.length === 0) { + return [ 0, 1 ]; + } + + return [ ...new Set(statusList) ]; + } + + /** + * 规范化波次策略类型筛选值,兼容单值与数组写法(1 散单 / 2 团购 / 3 SN)。 + * + * 数组中的空值(undefined/null/空字符串)会被忽略,重复值去重; + * 任一元组不合法时抛出统一错误提示。 + * + * @param {number|string|Array} value 策略类型筛选值。 + * @return {Array} 规范化后的策略类型数组,未传时返回空数组。 + */ + normalizeWaveStrategyTypeList(value) { + if (value === undefined || value === null) { + return []; + } + + const sourceList = Array.isArray(value) ? value : [ value ]; + const typeList = []; + sourceList.forEach(item => { + if (item === undefined || item === null || `${item}`.trim() === '') { + return; + } + + const normalized = Number(item); + if (!Number.isInteger(normalized) || ![ 1, 2, 3 ].includes(normalized)) { + throw new Error('strategy_type 仅支持 1(散单)、2(团购) 或 3(SN),数组写法如 [1, 3]'); + } + + typeList.push(normalized); + }); + + return [ ...new Set(typeList) ]; + } + + /** + * 规范化波次列表库位分配状态筛选值。 + * + * @param {string} value 入参筛选值。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListStorageAssignmentStatusFilter(value) { + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'storage'); + } + + /** + * 规范化波次列表快递分配状态筛选值(英文枚举)。 + * + * @param {string} value 入参筛选值。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListExpressAssignmentStatusFilter(value) { + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'express'); + } + + /** + * 规范化波次列表打印状态筛选值(英文枚举)。 + * + * @param {string} value 入参筛选值。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListPrintAssignmentStatusFilter(value) { + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'print'); + } + + /** + * 规范化波次列表确认打印状态筛选值(英文枚举)。 + * + * @param {string} value 入参筛选值。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListConfirmPrintAssignmentStatusFilter(value) { + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'confirm_print'); + } + + /** + * 规范化波次列表领料状态筛选值。 + * + * 领料状态以波次表 claim_time 为准(二态,无 partial): + * - none = 未领料(claim_time IS NULL); + * - finished = 已领料(claim_time IS NOT NULL)。 + * + * @param {string} value 入参筛选值(unclaimed/claimed,兼容中文 未领料/已领料)。 + * @return {string} 规范化后的筛选值(none/finished),未传时返回空字符串。 + */ + normalizeBatchListClaimAssignmentStatusFilter(value) { + if (value === undefined || value === null || value === '') { + return ''; + } + const normalizedValue = String(value).trim().toLowerCase(); + if (!normalizedValue) { + return ''; + } + if ([ 'unclaimed', 'none', '未领料', '未领单' ].includes(normalizedValue)) { + return 'none'; + } + if ([ 'claimed', 'finished', '已领料', '已领单' ].includes(normalizedValue)) { + return 'finished'; + } + throw new Error('claim_assignment_status 参数不合法,仅支持: unclaimed / claimed(未领料 / 已领料)'); + } + + /** + * 规范化波次列表复核状态筛选值(英文枚举)。 + * + * @param {string} value 入参筛选值。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListReviewAssignmentStatusFilter(value) { + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'review'); + } + + /** + * 规范化波次列表同步状态筛选值(英文枚举)。 + * + * @param {string} value 入参筛选值。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListSyncAssignmentStatusFilter(value) { + return this.normalizeBatchListAssignmentStatusFilterByType(value, 'sync'); + } + + /** + * 根据类型获取波次分配状态筛选配置。 + * + * @param {'storage'|'express'|'print'|'confirm_print'} type 筛选类型。 + * @return {{ fieldName: string, enumMap: Object, caseInsensitive: boolean, statsColumnPrefix: string, withErrorStatus: boolean }} 筛选配置。 + */ + getBatchListAssignmentFilterSchema(type) { + const normalizedType = String(type || '').trim(); + const schema = BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS[normalizedType]; + if (!schema) { + throw new Error(`不支持的分配状态筛选类型: ${normalizedType}`); + } + return schema; + } + + /** + * 按类型规范化波次列表分配状态筛选值。 + * + * @param {string} value 入参筛选值。 + * @param {'storage'|'express'|'print'|'confirm_print'} type 筛选类型。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListAssignmentStatusFilterByType(value, type) { + const schema = this.getBatchListAssignmentFilterSchema(type); + return this.normalizeBatchListAssignmentStatusFilter(value, schema); + } + + /** + * 规范化波次列表分配状态筛选值。 + * + * @param {string} value 入参筛选值。 + * @param {{ fieldName: string, enumMap: Object, caseInsensitive: boolean }} schema 筛选配置。 + * @return {string} 规范化后的筛选标识(none/partial/finished)。 + */ + normalizeBatchListAssignmentStatusFilter(value, schema) { + if (value === undefined || value === null || value === '') { + return ''; + } + + const normalizedValue = String(value).trim(); + if (!normalizedValue) { + return ''; + } + + const enumMap = this.isPlainObject(schema && schema.enumMap) ? schema.enumMap : {}; + const allowedValues = Object.keys(enumMap); + const isCaseInsensitive = Boolean(schema && schema.caseInsensitive); + const lookupValue = isCaseInsensitive ? normalizedValue.toLowerCase() : normalizedValue; + const normalizedEnumMap = isCaseInsensitive + ? Object.fromEntries( + Object.entries(enumMap).map(([ key, mappedValue ]) => [ String(key).toLowerCase(), mappedValue ]) + ) + : enumMap; + const matchedValue = normalizedEnumMap[lookupValue]; + + if (!matchedValue) { + const fieldName = String(schema && schema.fieldName || 'assignment_status'); + throw new Error(`${fieldName} 参数不合法,仅支持: ${allowedValues.join('、')}`); + } + + return matchedValue; + } + + /** + * 解析模型对应的 SQL 表名并完成安全转义。 + * + * @param {Object} model Sequelize 模型对象。 + * @return {string} 可直接拼接到 SQL 的表名。 + */ + getModelTableSqlName(model) { + const rawTableName = model && typeof model.getTableName === 'function' + ? model.getTableName() + : model && model.tableName; + const tableName = typeof rawTableName === 'string' + ? rawTableName + : rawTableName && typeof rawTableName.tableName === 'string' + ? rawTableName.tableName + : ''; + const normalizedTableName = String(tableName || '').trim(); + if (!normalizedTableName) { + throw new Error('订单模型表名解析失败'); + } + + const tableParts = normalizedTableName.split('.').map(part => String(part || '').trim()).filter(Boolean); + if (tableParts.length === 0) { + throw new Error('订单模型表名解析失败'); + } + + for (const tablePart of tableParts) { + if (!/^[a-zA-Z0-9_$]+$/.test(tablePart)) { + throw new Error(`订单模型表名不合法: ${normalizedTableName}`); + } + } + + return tableParts.map(part => `\`${part}\``).join('.'); + } + + /** + * 构建波次列表库位分配状态筛选 SQL 条件。 + * + * @param {string} statusFilter 库位分配状态筛选值。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListStorageAssignmentFilterClause(statusFilter = '') { + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'storage'); + } + + /** + * 构建波次列表快递分配状态筛选 SQL 条件。 + * + * @param {string} statusFilter 快递分配状态筛选值(none/partial/finished)。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListExpressAssignmentFilterClause(statusFilter = '') { + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'express'); + } + + /** + * 构建波次列表打印状态筛选 SQL 条件。 + * + * @param {string} statusFilter 打印状态筛选值(none/partial/finished)。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListPrintAssignmentFilterClause(statusFilter = '') { + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'print'); + } + + /** + * 构建波次列表确认打印状态筛选 SQL 条件。 + * + * @param {string} statusFilter 确认打印状态筛选值(none/partial/finished)。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListConfirmPrintAssignmentFilterClause(statusFilter = '') { + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'confirm_print'); + } + + /** + * 构建波次列表领料状态筛选 SQL 条件(波次表 claim_time 口径,二态)。 + * + * @param {string} statusFilter 领料状态筛选值(none/finished)。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListClaimAssignmentFilterClause(statusFilter = '') { + const normalizedStatusFilter = String(statusFilter || '').trim(); + if (!normalizedStatusFilter) { + return { + sql: '', + replacements: {}, + }; + } + if (normalizedStatusFilter === 'none') { + return { + sql: '\n AND wb.claim_time IS NULL', + replacements: {}, + }; + } + if (normalizedStatusFilter === 'finished') { + return { + sql: '\n AND wb.claim_time IS NOT NULL', + replacements: {}, + }; + } + throw new Error(`不支持的领料状态筛选值: ${normalizedStatusFilter}`); + } + + /** + * 构建波次列表复核状态筛选 SQL 条件。 + * + * @param {string} statusFilter 复核状态筛选值(none/partial/finished)。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListReviewAssignmentFilterClause(statusFilter = '') { + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'review'); + } + + /** + * 构建波次列表同步状态筛选 SQL 条件。 + * + * @param {string} statusFilter 同步状态筛选值(none/partial/finished)。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListSyncAssignmentFilterClause(statusFilter = '') { + return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'sync'); + } + + /** + * 按类型构建波次列表分配状态筛选 SQL 条件。 + * + * @param {string} statusFilter 分配状态筛选值(none/partial/finished)。 + * @param {'storage'|'express'|'print'|'confirm_print'} type 筛选类型。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListAssignmentStatusFilterClauseByType(statusFilter = '', type = 'storage') { + const schema = this.getBatchListAssignmentFilterSchema(type); + return this.buildBatchListAssignmentStatusFilterClause(statusFilter, schema); + } + + /** + * 构建波次列表分配状态筛选 SQL 条件(通用)。 + * + * @param {string} statusFilter 分配状态筛选值(none/partial/finished)。 + * @param {{ statsColumnPrefix: string, withErrorStatus: boolean }} schema 筛选配置。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListAssignmentStatusFilterClause(statusFilter = '', schema = {}) { + const normalizedStatusFilter = String(statusFilter || '').trim(); + if (!normalizedStatusFilter) { + return { + sql: '', + replacements: {}, + }; + } + + const statsPrefix = String(schema && schema.statsColumnPrefix || '').trim(); + if (!statsPrefix) { + throw new Error('分配状态筛选配置不完整,缺少统计字段前缀'); + } + + const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; + const noneExpr = `COALESCE(wave_order_stats.${statsPrefix}_none_count, 0)`; + const finExpr = `COALESCE(wave_order_stats.${statsPrefix}_fin_count, 0)`; + const withErrorStatus = Boolean(schema && schema.withErrorStatus); + const errorExpr = withErrorStatus ? `COALESCE(wave_order_stats.${statsPrefix}_error_count, 0)` : ''; + + if (normalizedStatusFilter === 'finished') { + return { + sql: ` + AND ${finExpr} = ${totalExpr} + AND ${totalExpr} > 0`, + replacements: {}, + }; + } + + if (normalizedStatusFilter === 'partial') { + return { + sql: ` + AND ${withErrorStatus ? `${errorExpr} = 0\n AND ` : ''}${noneExpr} <> ${totalExpr} + AND ${finExpr} <> ${totalExpr}`, + replacements: {}, + }; + } + + if (normalizedStatusFilter === 'none') { + return { + sql: ` + AND ( + ${totalExpr} = 0 + ${withErrorStatus ? `OR ${errorExpr} > 0\n ` : ''}OR ${noneExpr} = ${totalExpr} + )`, + replacements: {}, + }; + } + + throw new Error(`不支持的分配状态筛选值: ${normalizedStatusFilter}`); + } + + /** + * 判断波次列表 where 字段条件是否为空值。 + * + * 空值(undefined/null/空串/空数组)不参与 SQL 拼接; + * 例外:显式声明 isnull/isnotnull 的标准结构即使不带 value 也视为有效条件。 + * + * @param {*} rawCondition 原始条件值。 + * @return {boolean} 是否为空值。 + */ + isEmptyBatchListWhereValue(rawCondition) { + if (rawCondition === undefined || rawCondition === null) { + return true; + } + + if (typeof rawCondition === 'string') { + return rawCondition.trim() === ''; + } + + if (Array.isArray(rawCondition)) { + return rawCondition.length === 0; + } + + if (this.isPlainObject(rawCondition)) { + const hasStandardKeys = [ 'value', 'operator', 'type', 'field', 'values' ] + .some(key => Object.prototype.hasOwnProperty.call(rawCondition, key)); + if (!hasStandardKeys) { + return false; + } + + const operator = String(rawCondition.operator || '').toLowerCase(); + if (operator === 'isnull' || operator === 'isnotnull') { + return false; + } + + const value = Object.prototype.hasOwnProperty.call(rawCondition, 'value') + ? rawCondition.value + : rawCondition.values; + if (value === undefined || value === null) { + return true; + } + if (typeof value === 'string' && value.trim() === '') { + return true; + } + if (Array.isArray(value) && value.length === 0) { + return true; + } + return false; + } + + return false; + } + + /** + * 解析波次列表单字段条件(兼容裸值与 {operator,value,type} 标准结构)。 + * + * - 标准结构(含 value/operator/type/field/values 任一键):显式读取 operator,缺省回落 defaultOperator; + * - 裸值:数组按 in 处理,其余按 defaultOperator(保持历史语义,如 wave_no 默认模糊匹配)。 + * + * @param {*} rawCondition 原始条件值。 + * @param {string} [defaultOperator='eq'] 未显式传 operator 时的默认操作符。 + * @return {{ operator: string, value: *, hasExplicitOperator: boolean }} 解析结果。 + */ + resolveBatchListFieldCondition(rawCondition, defaultOperator = 'eq') { + const isStandardCondition = this.isPlainObject(rawCondition) + && [ 'value', 'operator', 'type', 'field', 'values' ] + .some(key => Object.prototype.hasOwnProperty.call(rawCondition, key)); + + if (isStandardCondition) { + const normalized = this.normalizeWhereCondition('__batch_list_where_field__', rawCondition); + return { + operator: String(normalized.operator || defaultOperator).toLowerCase(), + value: normalized.value, + hasExplicitOperator: true, + }; + } + + return { + operator: Array.isArray(rawCondition) ? 'in' : String(defaultOperator || 'eq').toLowerCase(), + value: rawCondition, + hasExplicitOperator: false, + }; + } + + /** + * 将波次列表单字段条件构建为 SQL 片段与占位符参数。 + * + * 支持操作符:eq/ne/gt/lt/ge/le/in/notin/between/notbetween/like/contains/ + * notlike/startswith/endswith/isnull/isnotnull(调用方通过 allowedOperators 限定)。 + * 数组值:like/contains/startswith/endswith 多值按 OR 展开,notlike 多值按 AND 展开。 + * + * @param {Object} options 构建参数。 + * @param {string} options.fieldKey 字段名(用于错误提示)。 + * @param {string} options.columnName 目标 SQL 列名(服务端白名单常量)。 + * @param {*} options.rawCondition 原始条件值。 + * @param {string} [options.defaultOperator='eq'] 默认操作符。 + * @param {'text'|'integer'|'number'} [options.valueType='text'] 值类型。 + * @param {boolean} [options.allowZero=true] integer 类型是否允许 0。 + * @param {Array} [options.allowedOperators=[]] 允许的操作符集合,空数组表示不限制。 + * @param {Function} [options.valueNormalizer=null] 自定义值归一化函数,优先级最高。 + * @param {string} [options.replacementKeyBase='whereField'] 占位符前缀。 + * @param {Object} [options.replacements={}] 占位符参数收集对象。 + * @return {string} SQL 条件片段(不含前导 AND),无有效条件时返回空字符串。 + */ + buildBatchListFieldConditionSql(options = {}) { + const { + fieldKey, + columnName, + rawCondition, + defaultOperator = 'eq', + valueType = 'text', + allowZero = true, + allowedOperators = [], + valueNormalizer = null, + replacementKeyBase = 'whereField', + replacements = {}, + } = options; + + if (this.isEmptyBatchListWhereValue(rawCondition)) { + return ''; + } + + const resolved = this.resolveBatchListFieldCondition(rawCondition, defaultOperator); + const rawValue = resolved.value; + let operator = String(resolved.operator || defaultOperator).toLowerCase(); + + if (allowedOperators.length > 0 && !allowedOperators.includes(operator)) { + throw new Error(`${fieldKey} 不支持操作符: ${operator},仅支持: ${allowedOperators.join('、')}`); + } + + const normalizeSingleValue = item => { + if (typeof valueNormalizer === 'function') { + return valueNormalizer(item); + } + + if (valueType === 'number') { + const numberValue = Number(item); + if (!Number.isFinite(numberValue)) { + throw new Error(`${fieldKey} 参数不合法`); + } + return numberValue; + } + + if (valueType === 'integer') { + const numberValue = Number(item); + const isValidInteger = Number.isInteger(numberValue) && (allowZero ? numberValue >= 0 : numberValue > 0); + if (!isValidInteger) { + throw new Error(`${fieldKey} 参数不合法`); + } + return numberValue; + } + + const textValue = String(item === undefined || item === null ? '' : item).trim(); + if (!textValue) { + throw new Error(`${fieldKey} 参数不合法`); + } + return textValue; + }; + + const normalizeValueList = () => { + const sourceList = Array.isArray(rawValue) ? rawValue : [ rawValue ]; + const valueList = sourceList.filter(item => item !== undefined && item !== null && String(item).trim() !== ''); + if (valueList.length === 0) { + throw new Error(`${fieldKey} 参数不合法`); + } + return valueList.map(item => normalizeSingleValue(item)); + }; + + // eq + 数组等价于 in(与 Sequelize 字段数组语义保持一致) + if (operator === 'eq' && Array.isArray(rawValue)) { + operator = 'in'; + } + + switch (operator) { + case 'eq': + case 'ne': { + const singleValue = normalizeSingleValue(Array.isArray(rawValue) ? rawValue[0] : rawValue); + replacements[replacementKeyBase] = singleValue; + return `${columnName} ${operator === 'eq' ? '=' : '<>'} :${replacementKeyBase}`; + } + + case 'gt': + case 'lt': + case 'ge': + case 'le': { + const comparators = { + gt: '>', + lt: '<', + ge: '>=', + le: '<=', + }; + const singleValue = normalizeSingleValue(Array.isArray(rawValue) ? rawValue[0] : rawValue); + replacements[replacementKeyBase] = singleValue; + return `${columnName} ${comparators[operator]} :${replacementKeyBase}`; + } + + case 'like': + case 'contains': + case 'startswith': + case 'endswith': { + const valueList = normalizeValueList(); + const useMultipleKeys = valueList.length > 1; + const clauses = valueList.map((textValue, index) => { + const replacementKey = useMultipleKeys ? `${replacementKeyBase}${index}` : replacementKeyBase; + replacements[replacementKey] = operator === 'startswith' + ? `${textValue}%` + : operator === 'endswith' + ? `%${textValue}` + : `%${textValue}%`; + return `${columnName} LIKE :${replacementKey}`; + }); + return clauses.length > 1 ? `(${clauses.join(' OR ')})` : clauses[0]; + } + + case 'notlike': { + const valueList = normalizeValueList(); + const useMultipleKeys = valueList.length > 1; + const clauses = valueList.map((textValue, index) => { + const replacementKey = useMultipleKeys ? `${replacementKeyBase}${index}` : replacementKeyBase; + replacements[replacementKey] = `%${textValue}%`; + return `${columnName} NOT LIKE :${replacementKey}`; + }); + return clauses.length > 1 ? `(${clauses.join(' AND ')})` : clauses[0]; + } + + case 'in': + case 'notin': { + const valueList = normalizeValueList(); + replacements[replacementKeyBase] = valueList; + return `${columnName} ${operator === 'in' ? 'IN' : 'NOT IN'} (:${replacementKeyBase})`; + } + + case 'between': + case 'notbetween': { + let betweenValue = rawValue; + if (this.isPlainObject(betweenValue)) { + const start = betweenValue.start ?? betweenValue.from ?? betweenValue.begin; + const end = betweenValue.end ?? betweenValue.to ?? betweenValue.finish; + betweenValue = [ start, end ]; + } + if (!Array.isArray(betweenValue) || betweenValue.length !== 2) { + throw new Error(`${fieldKey} 的 ${operator} 操作符要求 value 为长度为2的数组`); + } + + const startValue = normalizeSingleValue(betweenValue[0]); + const endValue = normalizeSingleValue(betweenValue[1]); + replacements[`${replacementKeyBase}From`] = startValue; + replacements[`${replacementKeyBase}To`] = endValue; + + return operator === 'between' + ? `${columnName} BETWEEN :${replacementKeyBase}From AND :${replacementKeyBase}To` + : `(${columnName} < :${replacementKeyBase}From OR ${columnName} > :${replacementKeyBase}To)`; + } + + case 'isnull': + return `${columnName} IS NULL`; + + case 'isnotnull': + return `${columnName} IS NOT NULL`; + + default: + throw new Error(`${fieldKey} 不支持操作符: ${operator}`); + } + } + + /** + * 归一化波次列表 distinguish_express 条件值(布尔/数字/文本统一为 0/1)。 + * + * @param {*} value 原始值。 + * @return {number} 0 或 1。 + */ + normalizeBatchListDistinguishExpressValue(value) { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + if (typeof value === 'number') { + if (value !== 0 && value !== 1) { + throw new Error('distinguish_express 参数不合法'); + } + return value; + } + + const boolText = String(value === undefined || value === null ? '' : value).trim().toLowerCase(); + if ([ '1', 'true', 'yes', 'y', 'on' ].includes(boolText)) { + return 1; + } + if ([ '0', 'false', 'no', 'n', 'off' ].includes(boolText)) { + return 0; + } + + throw new Error('distinguish_express 参数不合法'); + } + + /** + * 解析波次列表 store_id 筛选条件。 + * + * 兼容单值/数组/{operator,value}:默认按 in 匹配(返回包含任一筛选货主订单的波次,含混合货主波次); + * operator=ne/notin 时反向匹配(排除包含所选货主订单的波次)。 + * + * @param {*} rawCondition 原始条件。 + * @return {{ operator: 'in'|'notin', ids: number[] }} 归一化结果。 + */ + normalizeBatchListStoreIdCondition(rawCondition) { + if (rawCondition === undefined || rawCondition === null || rawCondition === '') { + return { + operator: 'in', + ids: [], + }; + } + + const resolved = this.resolveBatchListFieldCondition(rawCondition, 'in'); + const operator = String(resolved.operator || 'in').toLowerCase(); + if (![ 'eq', 'in', 'ne', 'notin' ].includes(operator)) { + throw new Error(`store_id 不支持操作符: ${operator},仅支持: eq、in、ne、notin`); + } + + const rawValue = resolved.value; + const sourceList = Array.isArray(rawValue) ? rawValue : [ rawValue ]; + const normalizedIds = []; + + for (const item of sourceList) { + if (item === undefined || item === null || item === '') { + continue; + } + + const numberValue = Number(String(item).trim()); + if (!Number.isInteger(numberValue) || numberValue <= 0) { + throw new Error('store_id 参数不合法'); + } + + normalizedIds.push(numberValue); + } + + return { + operator: operator === 'in' || operator === 'eq' ? 'in' : 'notin', + ids: [ ...new Set(normalizedIds) ], + }; + } + + /** + * 构建波次列表 where 条件(白名单字段)。 + * + * 每个白名单字段均支持裸值与 `{ operator, value, type }` 标准结构; + * 未显式传 operator 时按字段默认语义(wave_no/creator/logistics_name/item_part/ + * item_snapshot_key/item_detail_machine 默认 contains 模糊,其余默认 eq)。 + * + * @param {Object} whereData 查询 where 入参。 + * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string, reviewAssignmentStatus: string, storeIds: number[], storeIdOperator: 'in'|'notin' }} SQL 条件片段、参数与分配状态筛选值。 + */ + buildBatchListWhereClause(whereData = {}) { + const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; + const whereKeys = Object.keys(normalizedWhere); + + if (whereKeys.includes('warehouse_id') || whereKeys.includes('warehouseId')) { + throw new Error('where 中禁止传入 warehouse_id 或 warehouseId'); + } + + const allowedFields = [ + 'wave_id', + 'wave_no', + 'wave_type', + 'wave_status', + 'creator', + 'logistics_name', + 'item_part_type', + 'item_part', + 'item_snapshot_key', + 'item_detail_machine', + 'distinguish_express', + 'source', + 'total_orders', + 'total_orders_min', + 'total_orders_max', + 'processed_orders', + 'processed_orders_min', + 'processed_orders_max', + 'storage_assignment_status', + 'express_assignment_status', + 'print_assignment_status', + 'confirm_print_assignment_status', + 'claim_assignment_status', + 'review_assignment_status', + 'sync_assignment_status', + 'store_id', + ]; + + const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); + if (invalidFields.length > 0) { + throw new Error(`where 存在不支持的字段: ${invalidFields.join(',')}`); + } + + const conditions = []; + const replacements = {}; + + const textSearchOperators = [ 'eq', 'ne', 'like', 'contains', 'notlike', 'startswith', 'endswith', 'in', 'notin', 'isnull', 'isnotnull' ]; + const comparableOperators = [ 'eq', 'ne', 'gt', 'lt', 'ge', 'le', 'in', 'notin', 'between', 'notbetween', 'isnull', 'isnotnull' ]; + + const fieldSpecs = [ + { + fieldKey: 'wave_id', + columnName: 'wave_id', + defaultOperator: 'eq', + valueType: 'integer', + allowZero: false, + allowedOperators: comparableOperators, + replacementKeyBase: 'whereWaveId', + }, + { + fieldKey: 'wave_no', + columnName: 'wave_no', + defaultOperator: 'like', + allowedOperators: textSearchOperators, + replacementKeyBase: 'whereWaveNo', + }, + { + fieldKey: 'wave_type', + columnName: 'wave_type', + defaultOperator: 'eq', + valueType: 'integer', + allowedOperators: comparableOperators, + replacementKeyBase: 'whereWaveType', + }, + { + fieldKey: 'wave_status', + columnName: 'wave_status', + defaultOperator: 'eq', + valueType: 'integer', + allowedOperators: comparableOperators, + replacementKeyBase: 'whereWaveStatus', + }, + { + fieldKey: 'source', + columnName: 'source', + defaultOperator: 'eq', + valueType: 'integer', + allowedOperators: comparableOperators, + replacementKeyBase: 'whereSource', + }, + { + fieldKey: 'creator', + columnName: 'creator', + defaultOperator: 'like', + allowedOperators: textSearchOperators, + replacementKeyBase: 'whereCreator', + }, + { + fieldKey: 'logistics_name', + columnName: 'logistics_name', + defaultOperator: 'like', + allowedOperators: textSearchOperators, + replacementKeyBase: 'whereLogisticsName', + }, + { + fieldKey: 'item_part_type', + columnName: 'item_part_type', + defaultOperator: 'eq', + allowedOperators: textSearchOperators, + replacementKeyBase: 'whereItemPartType', + }, + { + fieldKey: 'item_part', + columnName: 'item_part', + defaultOperator: 'like', + allowedOperators: textSearchOperators, + replacementKeyBase: 'whereItemPart', + }, + { + fieldKey: 'item_snapshot_key', + columnName: 'item_snapshot_key', + defaultOperator: 'like', + allowedOperators: textSearchOperators, + replacementKeyBase: 'whereItemSnapshotKey', + }, + { + fieldKey: 'item_detail_machine', + columnName: 'item_detail_machine', + defaultOperator: 'like', + allowedOperators: textSearchOperators, + replacementKeyBase: 'whereItemDetailMachine', + }, + { + fieldKey: 'distinguish_express', + columnName: 'distinguish_express', + defaultOperator: 'eq', + valueType: 'integer', + valueNormalizer: value => this.normalizeBatchListDistinguishExpressValue(value), + allowedOperators: [ 'eq', 'ne', 'in', 'notin' ], + replacementKeyBase: 'whereDistinguishExpress', + }, + { + fieldKey: 'total_orders', + columnName: 'total_orders', + defaultOperator: 'eq', + valueType: 'number', + allowedOperators: comparableOperators, + replacementKeyBase: 'whereTotalOrders', + }, + { + fieldKey: 'total_orders_min', + columnName: 'total_orders', + defaultOperator: 'ge', + valueType: 'number', + allowedOperators: comparableOperators, + replacementKeyBase: 'whereTotalOrdersMin', + }, + { + fieldKey: 'total_orders_max', + columnName: 'total_orders', + defaultOperator: 'le', + valueType: 'number', + allowedOperators: comparableOperators, + replacementKeyBase: 'whereTotalOrdersMax', + }, + { + fieldKey: 'processed_orders', + columnName: 'processed_orders', + defaultOperator: 'eq', + valueType: 'number', + allowedOperators: comparableOperators, + replacementKeyBase: 'whereProcessedOrders', + }, + { + fieldKey: 'processed_orders_min', + columnName: 'processed_orders', + defaultOperator: 'ge', + valueType: 'number', + allowedOperators: comparableOperators, + replacementKeyBase: 'whereProcessedOrdersMin', + }, + { + fieldKey: 'processed_orders_max', + columnName: 'processed_orders', + defaultOperator: 'le', + valueType: 'number', + allowedOperators: comparableOperators, + replacementKeyBase: 'whereProcessedOrdersMax', + }, + ]; + + for (const fieldSpec of fieldSpecs) { + if (!Object.prototype.hasOwnProperty.call(normalizedWhere, fieldSpec.fieldKey)) { + continue; + } + + const fieldSql = this.buildBatchListFieldConditionSql({ + ...fieldSpec, + rawCondition: normalizedWhere[fieldSpec.fieldKey], + replacements, + }); + if (fieldSql) { + conditions.push(fieldSql); + } + } + + // store_id 货主筛选:支持单值/数组/{operator,value},默认 in(含混合货主波次),ne/notin 为排除语义。 + const storeIdCondition = this.normalizeBatchListStoreIdCondition(normalizedWhere.store_id); + + // 分配状态类筛选:由聚合统计判定,仅支持等值;显式传入其他操作符直接报错。 + const resolveAssignmentStatusFilter = (fieldKey, statusNormalizer) => { + const rawCondition = normalizedWhere[fieldKey]; + if (this.isEmptyBatchListWhereValue(rawCondition)) { + return ''; + } + + const { operator, value } = this.resolveBatchListFieldCondition(rawCondition, 'eq'); + if (operator !== 'eq') { + throw new Error(`${fieldKey} 不支持操作符: ${operator},仅支持: eq`); + } + + return statusNormalizer(value); + }; + + const storageAssignmentStatus = resolveAssignmentStatusFilter( + 'storage_assignment_status', + value => this.normalizeBatchListStorageAssignmentStatusFilter(value) + ); + const expressAssignmentStatus = resolveAssignmentStatusFilter( + 'express_assignment_status', + value => this.normalizeBatchListExpressAssignmentStatusFilter(value) + ); + const printAssignmentStatus = resolveAssignmentStatusFilter( + 'print_assignment_status', + value => this.normalizeBatchListPrintAssignmentStatusFilter(value) + ); + const confirmPrintAssignmentStatus = resolveAssignmentStatusFilter( + 'confirm_print_assignment_status', + value => this.normalizeBatchListConfirmPrintAssignmentStatusFilter(value) + ); + const claimAssignmentStatus = resolveAssignmentStatusFilter( + 'claim_assignment_status', + value => this.normalizeBatchListClaimAssignmentStatusFilter(value) + ); + const reviewAssignmentStatus = resolveAssignmentStatusFilter( + 'review_assignment_status', + value => this.normalizeBatchListReviewAssignmentStatusFilter(value) + ); + const syncAssignmentStatus = resolveAssignmentStatusFilter( + 'sync_assignment_status', + value => this.normalizeBatchListSyncAssignmentStatusFilter(value) + ); + + return { + sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', + replacements, + storageAssignmentStatus, + expressAssignmentStatus, + printAssignmentStatus, + confirmPrintAssignmentStatus, + claimAssignmentStatus, + reviewAssignmentStatus, + syncAssignmentStatus, + storeIds: storeIdCondition.ids, + storeIdOperator: storeIdCondition.operator, + }; + } + + /** + * 解析拣货任务列表分页参数。 + * + * 兼容 current/size 写法,并复用通用分页归一化能力。 + * + * @param {Object} data 请求参数。 + * @return {{ page: number, pageSize: number }} 归一化分页。 + */ + normalizeWavePickTaskListPagination(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const pagination = this.isPlainObject(normalizedData.pagination) + ? normalizedData.pagination + : normalizedData; + + const pageSource = pagination.page ?? pagination.page_no ?? pagination.pageNo ?? pagination.current; + const pageSizeSource = pagination.pageSize ?? pagination.page_size ?? pagination.size; + + return this.normalizePagination({ + page: pageSource, + pageSize: pageSizeSource, + }); + } + + /** + * 归一化拣货任务列表请求参数。 + * + * 兼容顶层筛选参数与 where 结构并保持旧调用可用: + * - 顶层支持 warehouse_id/status/source/keyword/task_no/cart_id/cart_code + * - 同名字段优先使用顶层值覆盖 where + * - warehouse_id 未传时回退当前仓库上下文 + * + * @param {Object} data 请求参数。 + * @return {{ warehouseId: number, where: Object }} 归一化仓库与查询条件。 + */ + normalizeWavePickTaskListRequest(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const baseWhere = this.isPlainObject(requestData.where) ? { ...requestData.where } : {}; + + const mergeFieldFromTopLevel = fieldName => { + if (Object.prototype.hasOwnProperty.call(requestData, fieldName)) { + baseWhere[fieldName] = requestData[fieldName]; + } + }; + + [ + 'status', + 'source', + 'keyword', + 'task_no', + 'wave_no', + 'pick_mode', + 'review_status', + 'pick_user_id', + 'review_user_id', + 'pick_user_name', + 'review_user_name', + 'claim_operator', + 'cart_id', + 'cart_code', + 'start_time_start', + 'start_time_end', + ].forEach(mergeFieldFromTopLevel); + + const contextWarehouseId = Number(this.getWarehouseId() || 0); + const inputWarehouseId = requestData.warehouse_id ?? requestData.warehouseId; + const warehouseId = inputWarehouseId !== undefined && inputWarehouseId !== null && inputWarehouseId !== '' + ? Number(inputWarehouseId) + : contextWarehouseId; + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('warehouse_id 参数不合法'); + } + + if (Number.isInteger(contextWarehouseId) + && contextWarehouseId > 0 + && inputWarehouseId !== undefined + && inputWarehouseId !== null + && inputWarehouseId !== '' + && warehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + return { + warehouseId, + where: baseWhere, + }; + } + + /** + * 构建拣货任务列表 where 条件(白名单字段)。 + * + * 注意:当前 wms_wave_pick_task 主表未落 strategy_id 字段, + * 因此 strategy_id 过滤入参会被忽略,不参与 SQL 条件拼接。 + * + * @param {Object} whereData 查询 where 入参。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildWavePickTaskListWhereClause(whereData = {}) { + const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; + const whereKeys = Object.keys(normalizedWhere); + const allowedFields = [ + 'status', + 'review_status', + 'pick_mode', + 'source', + 'strategy_id', + 'pick_user_id', + 'review_user_id', + 'pick_user_name', + 'review_user_name', + 'claim_operator', + 'task_no', + 'wave_no', + 'cart_id', + 'cart_code', + 'keyword', + 'start_time_start', + 'start_time_end', + ]; + + const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); + if (invalidFields.length > 0) { + throw new Error(`where 存在不支持的字段: ${invalidFields.join(',')}`); + } + + const conditions = []; + const replacements = {}; + + const appendIntegerEqualCondition = (fieldKey, columnName, replacementKey, allowZero = true) => { + const value = normalizedWhere[fieldKey]; + if (value === undefined || value === null || value === '') { + return; + } + + const numberValue = Number(value); + const isValid = Number.isInteger(numberValue) && (allowZero ? numberValue >= 0 : numberValue > 0); + if (!isValid) { + throw new Error(`${fieldKey} 参数不合法`); + } + + conditions.push(`${columnName} = :${replacementKey}`); + replacements[replacementKey] = numberValue; + }; + + const status = normalizedWhere.status; + if (Array.isArray(status)) { + const normalizedStatusList = [ ...new Set(status + .map(value => Number(value)) + .filter(value => Number.isInteger(value) && value >= 0)) ]; + if (normalizedStatusList.length <= 0) { + throw new Error('status 参数不合法'); + } + + conditions.push('t.status IN (:whereStatusList)'); + replacements.whereStatusList = normalizedStatusList; + } else { + appendIntegerEqualCondition('status', 't.status', 'whereStatus'); + } + appendIntegerEqualCondition('review_status', 't.review_status', 'whereReviewStatus'); + appendIntegerEqualCondition('pick_mode', 't.pick_mode', 'wherePickMode', false); + appendIntegerEqualCondition('source', 't.source', 'whereSource', false); + appendIntegerEqualCondition('pick_user_id', 't.pick_user_id', 'wherePickUserId'); + appendIntegerEqualCondition('review_user_id', 't.review_user_id', 'whereReviewUserId'); + appendIntegerEqualCondition('cart_id', 't.current_cart_id', 'whereCartId', false); + + const taskNo = normalizedWhere.task_no; + if (taskNo !== undefined && taskNo !== null && taskNo !== '') { + const normalizedTaskNo = String(taskNo).trim(); + if (!normalizedTaskNo) { + throw new Error('task_no 参数不合法'); + } + + conditions.push('t.task_no LIKE :whereTaskNo'); + replacements.whereTaskNo = `%${normalizedTaskNo}%`; + } + + const appendNameCondition = (fieldKey, columnName, replacementKey) => { + const raw = normalizedWhere[fieldKey]; + if (raw === undefined || raw === null || raw === '') { + return; + } + + // 支持操作符对象:{ operator: 'like' | 'notlike' | 'eq', value },默认 like + let operator = 'like'; + let value = raw; + if (this.isPlainObject(raw)) { + operator = String(raw.operator || 'like').trim().toLowerCase(); + value = raw.value; + } + + if (value === undefined || value === null || value === '') { + return; + } + const normalizedValue = String(value).trim(); + if (!normalizedValue) { + throw new Error(`${fieldKey} 参数不合法`); + } + + if (operator === 'eq') { + conditions.push(`${columnName} = :${replacementKey}`); + replacements[replacementKey] = normalizedValue; + } else if (operator === 'notlike') { + conditions.push(`(${columnName} NOT LIKE :${replacementKey} OR ${columnName} IS NULL)`); + replacements[replacementKey] = `%${normalizedValue}%`; + } else if (operator !== 'like') { + throw new Error(`${fieldKey} 不支持的 operator: ${operator}`); + } else { + conditions.push(`${columnName} LIKE :${replacementKey}`); + replacements[replacementKey] = `%${normalizedValue}%`; + } + }; + + appendNameCondition('pick_user_name', 't.pick_user_name', 'wherePickUserName'); + appendNameCondition('review_user_name', 't.review_user_name', 'whereReviewUserName'); + appendNameCondition('claim_operator', 't.claim_operator', 'whereClaimOperator'); + appendNameCondition('wave_no', 't.batch_no_array', 'whereWaveNo'); + // 拣货车编码:主表冗余的绑定快照(current_cart_code_snapshot),与列表返回字段同源, + // 支持操作符对象 { operator: 'like'|'notlike'|'eq', value },默认 like + appendNameCondition('cart_code', 't.current_cart_code_snapshot', 'whereCartCode'); + + const keyword = normalizedWhere.keyword; + if (keyword !== undefined && keyword !== null && keyword !== '') { + const normalizedKeyword = String(keyword).trim(); + if (!normalizedKeyword) { + throw new Error('keyword 参数不合法'); + } + + conditions.push(`( + t.task_no LIKE :whereKeyword + OR t.pick_user_name LIKE :whereKeyword + OR t.review_user_name LIKE :whereKeyword + OR t.batch_no LIKE :whereKeyword + OR t.current_cart_code_snapshot LIKE :whereKeyword + )`); + replacements.whereKeyword = `%${normalizedKeyword}%`; + } + + const startTimeStart = normalizedWhere.start_time_start; + if (startTimeStart !== undefined && startTimeStart !== null && startTimeStart !== '') { + const normalizedStartTimeStart = String(startTimeStart).trim(); + const startDate = new Date(normalizedStartTimeStart); + if (!normalizedStartTimeStart || Number.isNaN(startDate.getTime())) { + throw new Error('start_time_start 参数不合法'); + } + + conditions.push('t.create_time >= :whereCreateTimeStart'); + replacements.whereCreateTimeStart = normalizedStartTimeStart; + } + + const startTimeEnd = normalizedWhere.start_time_end; + if (startTimeEnd !== undefined && startTimeEnd !== null && startTimeEnd !== '') { + const normalizedStartTimeEnd = String(startTimeEnd).trim(); + const endDate = new Date(normalizedStartTimeEnd); + if (!normalizedStartTimeEnd || Number.isNaN(endDate.getTime())) { + throw new Error('start_time_end 参数不合法'); + } + + conditions.push('t.create_time <= :whereCreateTimeEnd'); + replacements.whereCreateTimeEnd = normalizedStartTimeEnd; + } + + return { + sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', + replacements, + }; + } + + /** + * 解析分配状态。 + * + * @param {number} total 总数量。 + * @param {number} noneCount 未分配数量。 + * @param {number} finCount 已分配数量。 + * @param {number} errorCount 分配异常数量。 + * @param {{ none?: string, partial?: string, finished?: string, error?: string }} [labels] 状态文案映射。 + * @return {string} 分配状态。 + */ + resolveAssignmentStatus(total, noneCount, finCount, errorCount = 0, labels = {}) { + const normalizedTotal = Number(total || 0); + const normalizedNoneCount = Number(noneCount || 0); + const normalizedFinCount = Number(finCount || 0); + const normalizedErrorCount = Number(errorCount || 0); + const normalizedLabels = labels && typeof labels === 'object' ? labels : {}; + const noneLabel = String(normalizedLabels.none || '未分配'); + const partialLabel = String(normalizedLabels.partial || '部分分配'); + const finishedLabel = String(normalizedLabels.finished || '已分配'); + const errorLabel = String(normalizedLabels.error || '分配异常'); + + if (normalizedErrorCount > 0) { + return errorLabel; + } + + if (normalizedTotal <= 0 || normalizedNoneCount === normalizedTotal) { + return noneLabel; + } + + if (normalizedFinCount === normalizedTotal) { + return finishedLabel; + } + + return partialLabel; + } + + normalizeSkuText(value) { + if (value === undefined || value === null) { + return ''; + } + + return String(value).trim(); + } + + normalizeShopName(value) { + if (value === undefined || value === null) { + return ''; + } + + return String(value).trim(); + } + + parseItemSnapshot(rawSnapshot) { + if (!rawSnapshot) { + return {}; + } + + if (typeof rawSnapshot === 'string') { + try { + const parsed = JSON.parse(rawSnapshot); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { + return {}; + } + } + + return typeof rawSnapshot === 'object' ? rawSnapshot : {}; + } + + normalizeOrderItemRow(row = {}) { + const snapshot = this.parseItemSnapshot(row.item_snapshot); + const stockIdRaw = snapshot.stock_id ?? row.stock_id; + const quantityRaw = row.plan_qty; + + const stockId = Number(stockIdRaw || 0); + const quantity = Number(quantityRaw || 0); + + return { + stock_id: Number.isInteger(stockId) && stockId > 0 ? stockId : 0, + item_code: String(snapshot.item_code ?? row.item_code ?? '').trim(), + item_name: String(snapshot.item_name ?? row.item_name ?? '').trim(), + barcode: String(snapshot.barcode ?? '').trim(), + quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 0, + }; + } + + mergeOrderItemDetails(itemRows = []) { + const merged = new Map(); + + for (const row of itemRows) { + const normalized = this.normalizeOrderItemRow(row); + const hasIdentity = normalized.stock_id > 0 + || normalized.item_code + || normalized.item_name; + + if (!hasIdentity || normalized.quantity <= 0) { + continue; + } + + const key = [ + normalized.stock_id, + normalized.item_code, + normalized.item_name, + normalized.barcode, + ].join('||'); + + if (!merged.has(key)) { + merged.set(key, { + stock_id: normalized.stock_id, + item_code: normalized.item_code, + item_name: normalized.item_name, + barcode: normalized.barcode, + quantity: 0, + }); + } + + merged.get(key).quantity += normalized.quantity; + } + + return Array.from(merged.values()) + .sort((a, b) => { + if (a.stock_id !== b.stock_id) return a.stock_id - b.stock_id; + return String(a.item_code).localeCompare(String(b.item_code)); + }); + } + + buildItemSummary(itemDetails = []) { + if (!Array.isArray(itemDetails) || itemDetails.length === 0) { + return ''; + } + + return itemDetails + .map(item => { + const name = String(item.item_name || '').trim(); + const barcode = String(item.barcode || item.item_code || '').trim(); + const qty = item.quantity; + return `${name}${barcode ? `(${barcode})` : ''}×${qty}`; + }) + .join(' | '); + } + + /** + * 构建订单商品快照字符串。 + * + * 输出格式:商品名称1*数量|商品名称2*数量。 + * + * @param {Array} itemDetails 商品明细列表。 + * @return {string} 商品快照字符串。 + */ + buildOrderItemSnapshot(itemDetails = []) { + if (!Array.isArray(itemDetails) || itemDetails.length === 0) { + return ''; + } + + const segments = itemDetails + .map(item => { + const itemName = String(item && (item.item_name || item.item_code) || '').trim(); + const quantity = Number(item && item.quantity || 0); + if (!itemName || !Number.isFinite(quantity) || quantity <= 0) { + return ''; + } + + return `${itemName}*${quantity}`; + }) + .filter(Boolean); + + return segments.join('|'); + } + + buildItemSnapshotKey(itemDetails = []) { + if (!Array.isArray(itemDetails) || itemDetails.length === 0) { + return ''; + } + + return itemDetails.map(item => [ + item.stock_id, + item.item_code, + item.item_name, + item.barcode, + item.quantity, + ].join('::')).join('|'); + } + + orderMatchesIncludeSku(itemDetails = [], includeSku = '') { + const token = String(includeSku || '').trim().toLowerCase(); + if (!token) { + return true; + } + + return itemDetails.some(item => String(item.item_code || '').toLowerCase().includes(token)); + } + + buildCoarseGroupKey(order = {}, distinguishExpress = false) { + const itemsHash = String(order.items_hash || '').trim(); + const itemsText = String(order.items || '').trim(); + const logisticsName = String(order.sys_logistics_code || '').trim(); + + const itemPart = itemsHash || itemsText; + if (!itemPart) { + return ''; + } + + return distinguishExpress ? `${itemPart}||${logisticsName}` : itemPart; + } + + buildStatusSummary(orders = []) { + const summary = { + post_none: 0, + post_fin: 0, + post_padding: 0, + pick_none: 0, + pick_fin: 0, + outbound_none: 0, + outbound_fin: 0, + }; + + for (const order of orders) { + const postStatus = String(order.post_status || ''); + const pickStatus = String(order.pick_status || ''); + const outboundStatus = String(order.outbound_status || ''); + + if (postStatus === 'none') summary.post_none += 1; + if (postStatus === 'fin') summary.post_fin += 1; + if (postStatus === 'padding') summary.post_padding += 1; + + if (pickStatus === 'none') summary.pick_none += 1; + if (pickStatus === 'fin') summary.pick_fin += 1; + + if (outboundStatus === 'none') summary.outbound_none += 1; + if (outboundStatus === 'fin') summary.outbound_fin += 1; + } + + return summary; + } + + buildGroupKey(order, itemDetails = [], options = {}) { + const itemSummary = this.buildItemSummary(itemDetails); + const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); + const logisticsName = String(order.sys_logistics_code || '').trim(); + + const baseParts = [ itemSnapshotKey ]; + if (options.distinguishExpress) { + baseParts.push(logisticsName); + } + + return { + key: baseParts.join('||'), + itemSummary, + itemSnapshotKey, + itemDetails, + logisticsName, + }; + } + + /** + * 团购波次可抓取列表。 + * + * 仅处理待处理订单(排除待审核),且排除已在波次中的订单。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 抓取列表和分页信息。 + */ + async groupOrderFetchList(data = {}) { + const t0 = Date.now(); + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const model = await this.getOrderModel('pendingOrder', warehouseId); + const t1 = Date.now(); + + const distinguishExpress = this.normalizeBoolean(requestData.distinguish_express, false); + const storeId = this.normalizePositiveInteger(requestData.store_id, 'store_id', 0); + const sameOrderQuantityInput = requestData.same_order_quantity; + const hasSameOrderQuantityInput = !(sameOrderQuantityInput === undefined || sameOrderQuantityInput === null || sameOrderQuantityInput === ''); + const explicitSameOrderQuantity = hasSameOrderQuantityInput + ? this.normalizePositiveInteger(sameOrderQuantityInput, 'same_order_quantity', 0) + : 0; + const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(warehouseId); + const sameOrderQuantity = explicitSameOrderQuantity > 0 + ? explicitSameOrderQuantity + : minGroupOrderFetchQuantity; + const shopName = this.normalizeShopName(requestData.shop_name); + const includeSku = this.normalizeSkuText(requestData.include_sku); + const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false); + const stockQuery = String(requestData.stock_query || '').trim(); + const { page, pageSize } = this.normalizePagination(requestData); + + const where = { + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', + wave_id: 0, + // 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行) + is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + // 团购抓取排除 SN(序列号管理)订单 + [Op.and]: [ this.buildExcludeSnOrderCondition() ], + }; + + if (storeId > 0) { + where.store_id = storeId; + } + + if (shopName) { + where.shop_nick = { [Op.like]: `%${shopName}%` }; + } + + // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → 限定候选订单范围 + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); + if (stockOrderIds.length > 0) { + where.id = { [Op.in]: stockOrderIds }; + } else { + // 未匹配到任何商品,直接返回空列表 + return { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + }; + } + } + + // Phase 1: 主表全量查询,用 items_hash 做分组基准 + const rawOrders = await model.findAll({ + where, + attributes: [ + 'id', 'store_id', 'logistics_name', + 'sys_logistics_code', 'sys_logistics_name', + 'items_hash', 'items', 'items_total', 'items_weight', 'packages_weight', + 'post_status', 'pick_status', 'outbound_status', 'create_at', + ], + raw: true, + order: [[ 'id', 'DESC' ]], + }); + const t2 = Date.now(); + + // Phase 2: 纯内存粗分组,items_hash 相同即为同组,速度快 + // coarseGroupMap: coarseKey -> { orders[] } + const coarseGroupMap = new Map(); + for (const order of rawOrders) { + const coarseKey = this.buildCoarseGroupKey(order, distinguishExpress); + if (!coarseKey) { + continue; + } + + if (!coarseGroupMap.has(coarseKey)) { + coarseGroupMap.set(coarseKey, { orders: [] }); + } + + coarseGroupMap.get(coarseKey).orders.push(order); + } + + // 过滤最小阈值、排序 + let groupEntries = Array.from(coarseGroupMap.entries()); + groupEntries = groupEntries.filter(([ , g ]) => g.orders.length >= sameOrderQuantity); + + groupEntries.sort(([ keyA, gA ], [ keyB, gB ]) => { + if (gB.orders.length !== gA.orders.length) { + return gB.orders.length - gA.orders.length; + } + + return keyA.localeCompare(keyB); + }); + + const total = groupEntries.length; + const t3 = Date.now(); + + // Phase 3: 分页分组,只取当前页 + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + const pageStart = (page - 1) * pageSize; + const pageGroupEntries = groupEntries.slice(pageStart, pageStart + pageSize); + + // 收集当前页每组的代表订单 id(同组 items_hash 相同,只需一条快照即可) + const representativeIdPerGroup = new Map(); // coarseKey -> representativeOrderId + for (const [ coarseKey, g ] of pageGroupEntries) { + const repOrder = g.orders.find(o => Number(o.id) > 0); + if (repOrder) { + representativeIdPerGroup.set(coarseKey, Number(repOrder.id)); + } + } + const pageOrderIds = Array.from(representativeIdPerGroup.values()); + const t4 = Date.now(); + + // Phase 4: 仅查每组代表订单的明细(每页 20 条左右,大幅降低 IN 数量) + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const orderItemRows = pageOrderIds.length > 0 + ? await orderItemsModel.findAll({ + where: { order_id: { [Op.in]: pageOrderIds } }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }) + : []; + const t5 = Date.now(); + + // 构建明细索引 + const orderItemsMap = new Map(); + for (const row of orderItemRows) { + const orderId = Number(row && row.order_id); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + if (!orderItemsMap.has(orderId)) { + orderItemsMap.set(orderId, []); + } + + orderItemsMap.get(orderId).push(row); + } + + // Phase 5: 构建当前页响应,每组取一个代表订单的 item_snapshot 作为展示快照 + const list = []; + for (const [ coarseKey, g ] of pageGroupEntries) { + // 同粗分组内 items_hash 相同,取该组的代表订单明细作为展示快照 + const representativeId = representativeIdPerGroup.get(coarseKey); + const itemRows = representativeId ? (orderItemsMap.get(representativeId) || []) : []; + const itemDetails = this.mergeOrderItemDetails(itemRows); + + // includeSku 精确过滤(页内应用,total 为粗分组数量) + if (!this.orderMatchesIncludeSku(itemDetails, includeSku)) { + continue; + } + + const itemSummary = this.buildItemSummary(itemDetails); + const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); + if (!itemSummary || !itemSnapshotKey) { + continue; + } + + const firstOrder = g.orders[0] || {}; + const itemPartInfo = this.getOrderItemPart(firstOrder); + const logisticsCode = String(firstOrder.sys_logistics_code || '').trim(); + const logisticsNameFromOrder = String(firstOrder.sys_logistics_name || '').trim(); + const logisticsDisplayName = logisticsNameFromOrder || logisticsCode; + const itemDetailMachine = this.buildMachineStructureToken({ + item_part_type: itemPartInfo.item_part_type, + item_part: itemPartInfo.item_part, + distinguish_express: distinguishExpress, + logistics_name: logisticsCode, + item_snapshot_key: itemSnapshotKey, + }); + + const store_ids = [ ...new Set( + g.orders.map(o => Number(o.store_id || 0)).filter(id => id > 0) + ) ]; + + let first_order_time = null; + let last_order_time = null; + let items_total = 0; + for (const o of g.orders) { + items_total += Number(o.items_total || 0); + if (!first_order_time || o.create_at < first_order_time) first_order_time = o.create_at; + if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; + } + + list.push({ + item_detail: itemSummary, + item_detail_machine: itemDetailMachine, + item_detail_machine_snapshot: itemSnapshotKey, + item_snapshot: itemDetails, + group: g.orders.length, + group_count: g.orders.length, + items_total, + items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, + packages_weight: firstOrder.packages_weight != null ? Number(firstOrder.packages_weight) : null, + store_id: store_ids.length === 1 ? store_ids[0] : 0, + store_ids, + logistics_code: logisticsCode, + logistics_name: logisticsDisplayName, + distinguish_express: distinguishExpress, + ...(returnOrderIds ? { order_ids: g.orders.map(o => Number(o.id)) } : {}), + first_order_time, + last_order_time, + status_summary: this.buildStatusSummary(g.orders), + }); + } + const t6 = Date.now(); + + this.ctx.logger.info('[wave.groupOrderFetchList] 链路耗时', { + warehouseId, + params: { distinguishExpress, storeId, sameOrderQuantity, shopName: shopName || null, includeSku: includeSku || null }, + counts: { + rawOrders: rawOrders.length, + coarseGroups: coarseGroupMap.size, + filteredGroups: total, + pageOrderIds: pageOrderIds.length, + orderItemRows: orderItemRows.length, + pageItems: list.length, + }, + timing_ms: { + getModel: t1 - t0, + queryOrders: t2 - t1, + coarseGrouping: t3 - t2, + pagination: t4 - t3, + queryItems: t5 - t4, + buildList: t6 - t5, + total: t6 - t0, + }, + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 散单波次可抓取列表。 + * + * 仅处理待处理订单(排除待审核),且排除已在波次中的订单。 + * 与团购抓取共用同一链路,仅排除团购阈值命中的分组。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 抓取列表和分页信息。 + */ + async singleOrderFetchList(data = {}) { + const t0 = Date.now(); + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const model = await this.getOrderModel('pendingOrder', warehouseId); + const t1 = Date.now(); + + const distinguishExpress = this.normalizeBoolean(requestData.distinguish_express, false); + const storeId = this.normalizePositiveInteger(requestData.store_id, 'store_id', 0); + const sameOrderQuantityInput = requestData.same_order_quantity; + const hasSameOrderQuantityInput = !(sameOrderQuantityInput === undefined || sameOrderQuantityInput === null || sameOrderQuantityInput === ''); + const explicitSameOrderQuantity = hasSameOrderQuantityInput + ? this.normalizePositiveInteger(sameOrderQuantityInput, 'same_order_quantity', 0) + : 0; + const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(warehouseId); + const sameOrderQuantity = explicitSameOrderQuantity > 0 + ? explicitSameOrderQuantity + : minGroupOrderFetchQuantity; + const shopName = this.normalizeShopName(requestData.shop_name); + const includeSku = this.normalizeSkuText(requestData.include_sku); + const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false); + const stockQuery = String(requestData.stock_query || '').trim(); + const { page, pageSize } = this.normalizePagination(requestData); + + const where = { + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', + wave_id: 0, + // 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行) + is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + // 散单抓取同样排除 SN(序列号管理)订单 + [Op.and]: [ this.buildExcludeSnOrderCondition() ], + }; + + if (storeId > 0) { + where.store_id = storeId; + } + + if (shopName) { + where.shop_nick = { [Op.like]: `%${shopName}%` }; + } + + // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → 限定候选订单范围 + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); + if (stockOrderIds.length > 0) { + where.id = { [Op.in]: stockOrderIds }; + } else { + // 未匹配到任何商品,直接返回空列表 + return { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + }; + } + } + + // Phase 1: 主表全量查询,用 items_hash 做分组基准 + const rawOrders = await model.findAll({ + where, + attributes: [ + 'id', 'store_id', 'logistics_name', + 'sys_logistics_code', 'sys_logistics_name', + 'items_hash', 'items', 'items_total', 'items_weight', 'packages_weight', + 'post_status', 'pick_status', 'outbound_status', 'create_at', + ], + raw: true, + order: [[ 'id', 'DESC' ]], + }); + const t2 = Date.now(); + + // Phase 2: 纯内存粗分组,items_hash 相同即为同组,速度快 + // coarseGroupMap: coarseKey -> { orders[] } + const coarseGroupMap = new Map(); + for (const order of rawOrders) { + const coarseKey = this.buildCoarseGroupKey(order, distinguishExpress); + if (!coarseKey) { + continue; + } + + if (!coarseGroupMap.has(coarseKey)) { + coarseGroupMap.set(coarseKey, { orders: [] }); + } + + coarseGroupMap.get(coarseKey).orders.push(order); + } + + // 过滤团购阈值(排除团购分组)、排序 + let groupEntries = Array.from(coarseGroupMap.entries()); + groupEntries = groupEntries.filter(([ , g ]) => g.orders.length < sameOrderQuantity); + + groupEntries.sort(([ keyA, gA ], [ keyB, gB ]) => { + if (gB.orders.length !== gA.orders.length) { + return gB.orders.length - gA.orders.length; + } + + return keyA.localeCompare(keyB); + }); + + const total = groupEntries.length; + const t3 = Date.now(); + + // Phase 3: 分页分组,只取当前页 + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + const pageStart = (page - 1) * pageSize; + const pageGroupEntries = groupEntries.slice(pageStart, pageStart + pageSize); + + // 收集当前页每组的代表订单 id(同组 items_hash 相同,只需一条快照即可) + const representativeIdPerGroup = new Map(); // coarseKey -> representativeOrderId + for (const [ coarseKey, g ] of pageGroupEntries) { + const repOrder = g.orders.find(o => Number(o.id) > 0); + if (repOrder) { + representativeIdPerGroup.set(coarseKey, Number(repOrder.id)); + } + } + const pageOrderIds = Array.from(representativeIdPerGroup.values()); + const t4 = Date.now(); + + // Phase 4: 仅查每组代表订单的明细(每页 20 条左右,大幅降低 IN 数量) + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const orderItemRows = pageOrderIds.length > 0 + ? await orderItemsModel.findAll({ + where: { order_id: { [Op.in]: pageOrderIds } }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }) + : []; + const t5 = Date.now(); + + // 构建明细索引 + const orderItemsMap = new Map(); + for (const row of orderItemRows) { + const orderId = Number(row && row.order_id); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + if (!orderItemsMap.has(orderId)) { + orderItemsMap.set(orderId, []); + } + + orderItemsMap.get(orderId).push(row); + } + + // Phase 5: 构建当前页响应,每组取一个代表订单的 item_snapshot 作为展示快照 + const list = []; + for (const [ coarseKey, g ] of pageGroupEntries) { + // 同粗分组内 items_hash 相同,取该组的代表订单明细作为展示快照 + const representativeId = representativeIdPerGroup.get(coarseKey); + const itemRows = representativeId ? (orderItemsMap.get(representativeId) || []) : []; + const itemDetails = this.mergeOrderItemDetails(itemRows); + + // includeSku 精确过滤(页内应用,total 为粗分组数量) + if (!this.orderMatchesIncludeSku(itemDetails, includeSku)) { + continue; + } + + const itemSummary = this.buildItemSummary(itemDetails); + const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); + if (!itemSummary || !itemSnapshotKey) { + continue; + } + + const firstOrder = g.orders[0] || {}; + const itemPartInfo = this.getOrderItemPart(firstOrder); + const logisticsCode = String(firstOrder.sys_logistics_code || '').trim(); + const logisticsNameFromOrder = String(firstOrder.sys_logistics_name || '').trim(); + const logisticsDisplayName = logisticsNameFromOrder || logisticsCode; + const itemDetailMachine = this.buildMachineStructureToken({ + item_part_type: itemPartInfo.item_part_type, + item_part: itemPartInfo.item_part, + distinguish_express: distinguishExpress, + logistics_name: logisticsCode, + item_snapshot_key: itemSnapshotKey, + }); + + const store_ids = [ ...new Set( + g.orders.map(o => Number(o.store_id || 0)).filter(id => id > 0) + ) ]; + + let first_order_time = null; + let last_order_time = null; + let items_total = 0; + for (const o of g.orders) { + items_total += Number(o.items_total || 0); + if (!first_order_time || o.create_at < first_order_time) first_order_time = o.create_at; + if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; + } + + list.push({ + item_detail: itemSummary, + item_detail_machine: itemDetailMachine, + item_detail_machine_snapshot: itemSnapshotKey, + item_snapshot: itemDetails, + group: g.orders.length, + group_count: g.orders.length, + items_total, + items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, + packages_weight: firstOrder.packages_weight != null ? Number(firstOrder.packages_weight) : null, + store_id: store_ids.length === 1 ? store_ids[0] : 0, + store_ids, + logistics_code: logisticsCode, + logistics_name: logisticsDisplayName, + distinguish_express: distinguishExpress, + ...(returnOrderIds ? { order_ids: g.orders.map(o => Number(o.id)) } : {}), + first_order_time, + last_order_time, + status_summary: this.buildStatusSummary(g.orders), + }); + } + const t6 = Date.now(); + + this.ctx.logger.info('[wave.singleOrderFetchList] 链路耗时', { + warehouseId, + params: { distinguishExpress, storeId, sameOrderQuantity, shopName: shopName || null, includeSku: includeSku || null }, + counts: { + rawOrders: rawOrders.length, + coarseGroups: coarseGroupMap.size, + filteredGroups: total, + pageOrderIds: pageOrderIds.length, + orderItemRows: orderItemRows.length, + pageItems: list.length, + }, + timing_ms: { + getModel: t1 - t0, + queryOrders: t2 - t1, + coarseGrouping: t3 - t2, + pagination: t4 - t3, + queryItems: t5 - t4, + buildList: t6 - t5, + total: t6 - t0, + }, + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 团购可抓取订单数统计。 + * + * 口径与 groupOrderFetchList 完全一致(同一候选 where、同一 items_hash 粗分组、 + * 同一团购阈值 same_order_quantity 过滤),但**不分页、不查订单明细**, + * 仅返回达到团购阈值分组的数量与组内订单数合计,供前端展示「可抓取订单数」等轻量统计。 + * + * 差异说明:groupOrderFetchList 的 pagination.total 是**分组数**(每组订单数在 group_count 内), + * 本方法 order_count 是**订单数合计**,两者口径不同;include_sku 为页内过滤,本方法不参与统计。 + * + * @param {Object} [data={}] 请求参数。 + * @param {boolean} [data.distinguish_express=false] 是否区分快递(影响分组粒度)。 + * @param {number|string} [data.store_id] 货主ID(作为筛选条件)。 + * @param {number|string} [data.same_order_quantity] 最小同组订单数量阈值(>=);未传时取仓库配置 min_group_order_fetch_quantity(默认 13)。 + * @param {string} [data.shop_name] 店铺名称(模糊匹配)。 + * @param {string} [data.stock_query] 商品模糊筛选(stock_warehouse / stock_barcodes → order_items)。 + * @return {Promise} 统一返回结构,data 含 group_count / order_count / same_order_quantity / raw_order_count / warehouse_id / distinguish_express。 + */ + async fetchableOrderCount(data = {}) { + const t0 = Date.now(); + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return this.fail('未识别到当前仓库上下文', {}, 400); + } + + const model = await this.getOrderModel('pendingOrder', warehouseId); + const t1 = Date.now(); + + const distinguishExpress = this.normalizeBoolean(requestData.distinguish_express, false); + const storeId = this.normalizePositiveInteger(requestData.store_id, 'store_id', 0); + const sameOrderQuantityInput = requestData.same_order_quantity; + const hasSameOrderQuantityInput = !(sameOrderQuantityInput === undefined || sameOrderQuantityInput === null || sameOrderQuantityInput === ''); + const explicitSameOrderQuantity = hasSameOrderQuantityInput + ? this.normalizePositiveInteger(sameOrderQuantityInput, 'same_order_quantity', 0) + : 0; + const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(warehouseId); + const sameOrderQuantity = explicitSameOrderQuantity > 0 + ? explicitSameOrderQuantity + : minGroupOrderFetchQuantity; + const shopName = this.normalizeShopName(requestData.shop_name); + const stockQuery = String(requestData.stock_query || '').trim(); + + const where = { + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', + wave_id: 0, + // 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行) + is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + // 团购抓取排除 SN(序列号管理)订单 + [Op.and]: [ this.buildExcludeSnOrderCondition() ], + }; + + if (storeId > 0) { + where.store_id = storeId; + } + + if (shopName) { + where.shop_nick = { [Op.like]: `%${shopName}%` }; + } + + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); + if (stockOrderIds.length <= 0) { + return this.success('ok', { + group_count: 0, + order_count: 0, + same_order_quantity: sameOrderQuantity, + raw_order_count: 0, + warehouse_id: warehouseId, + distinguish_express: distinguishExpress, + }); + } + + where.id = { [Op.in]: stockOrderIds }; + } + + // 仅取分组基准字段,不取明细(与 groupOrderFetchList Phase 1 同表同 where) + const rawOrders = await model.findAll({ + where, + attributes: [ 'id', 'items_hash', 'items', 'sys_logistics_code' ], + raw: true, + }); + const t2 = Date.now(); + + // 纯内存粗分组:items_hash(缺省回落 items)相同即为同组,distinguish_express 时再叠加快递编码 + const coarseGroupSizeMap = new Map(); + for (const order of rawOrders) { + const coarseKey = this.buildCoarseGroupKey(order, distinguishExpress); + if (!coarseKey) { + continue; + } + + coarseGroupSizeMap.set(coarseKey, Number(coarseGroupSizeMap.get(coarseKey) || 0) + 1); + } + + // 团购阈值过滤:仅统计同组订单数 >= sameOrderQuantity 的分组 + let groupCount = 0; + let orderCount = 0; + for (const groupSize of coarseGroupSizeMap.values()) { + if (groupSize < sameOrderQuantity) { + continue; + } + + groupCount += 1; + orderCount += groupSize; + } + const t3 = Date.now(); + + this.ctx.logger.info('[wave.fetchableOrderCount] 链路耗时', { + warehouseId, + params: { distinguishExpress, storeId, sameOrderQuantity, shopName: shopName || null, stockQuery: stockQuery || null }, + counts: { + rawOrders: rawOrders.length, + coarseGroups: coarseGroupSizeMap.size, + fetchableGroups: groupCount, + fetchableOrders: orderCount, + }, + timing_ms: { + getModel: t1 - t0, + queryOrders: t2 - t1, + counting: t3 - t2, + total: t3 - t0, + }, + }); + + return this.success('ok', { + group_count: groupCount, + order_count: orderCount, + same_order_quantity: sameOrderQuantity, + raw_order_count: rawOrders.length, + warehouse_id: warehouseId, + distinguish_express: distinguishExpress, + }); + } + + /** + * 查询当前仓库波次策略列表。 + * + * 仅查询当前登录仓库在 wms_wave_strategy 中的数据,返回标准 list/pagination 结构。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [data.pagination] 分页参数。 + * @param {number|string|Array} [data.strategy_type] 策略类型过滤,支持单值与数组:1 散单 / 2 团购 / 3 SN。 + * @param {Object} [data.where] 过滤条件,支持 where.strategy_type(单值或数组)。 + * @return {Promise} 波次策略列表及分页信息。 + */ + async waveStrategyList(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawType = requestData.strategy_type ?? requestData?.where?.strategy_type; + const strategyTypeList = this.normalizeWaveStrategyTypeList(rawType); + const calculateNextFetchOrderCount = Number( + requestData.calculate_next_fetch_order_count ?? requestData.calculateNextFetchOrderCount ?? 0 + ) === 1; + const debugEnabled = Number(requestData.debug ?? 0) === 1; + const { page, pageSize } = this.normalizePagination(requestData); + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const strategyModel = this.getWaveStrategyModel(); + if (!strategyModel || typeof strategyModel.findAndCountAll !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const offset = (page - 1) * pageSize; + const where = { + warehouse_id: contextWarehouseId, + }; + if (strategyTypeList.length === 1) { + where.strategy_type = strategyTypeList[0]; + } else if (strategyTypeList.length > 1) { + where.strategy_type = { [Op.in]: strategyTypeList }; + } + + const queryResult = await strategyModel.findAndCountAll({ + where, + order: [ + [ 'status', 'DESC' ], + [ 'id', 'DESC' ], + ], + offset, + limit: pageSize, + raw: true, + }); + + const list = Array.isArray(queryResult && queryResult.rows) ? queryResult.rows : []; + // 统计失败(如目标库尚未执行 has_sn_item 迁移)时降级为 0,避免整张策略列表返回失败 + let matchedOrderCountMap = new Map(); + try { + matchedOrderCountMap = await this.getWaveStrategyMatchedOrderCountFilteredMap( + contextWarehouseId, + list + ); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyList] 统计策略命中订单数失败,降级为 0', { + warehouse_id: contextWarehouseId, + error: error && error.message ? error.message : `${error}`, + }); + } + + let nextFetchOrderCountMap = new Map(); + if (calculateNextFetchOrderCount) { + try { + nextFetchOrderCountMap = await this.getWaveStrategyNextFetchOrderCountMap(contextWarehouseId, list); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyList] 预演下一抓取订单数失败,降级为 0', { + warehouse_id: contextWarehouseId, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + let debugFetchOrderListMap = new Map(); + if (debugEnabled) { + try { + debugFetchOrderListMap = await this.getWaveStrategyDebugFetchOrderListMap(contextWarehouseId, list); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyList] 预演抓取订单清单失败,降级为空', { + warehouse_id: contextWarehouseId, + error: error && error.message ? error.message : `${error}`, + }); + } + } + const mergedList = list.map(item => { + const strategyId = Number(item && item.id || 0); + const debugRow = debugEnabled ? (debugFetchOrderListMap.get(strategyId) || null) : null; + return { + ...item, + matched_order_count_filtered: Number( + matchedOrderCountMap.get(strategyId) || 0 + ), + next_fetch_order_count: calculateNextFetchOrderCount + ? Number(nextFetchOrderCountMap.get(strategyId) || 0) + : 0, + ...(debugEnabled && debugRow ? { + next_fetch_order_list: debugRow, + } : {}), + }; + }); + const total = Number(queryResult && queryResult.count || 0); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + // 统计本次查询条件下全部策略命中的去重订单总数(info.order_count); + // 与行级 matched_order_count_filtered 同口径,仅在该仓库存在策略时执行, + // 统计失败时安全降级为 0,不影响列表主流程。 + let matchedOrderCountTotal = 0; + if (total > 0) { + try { + matchedOrderCountTotal = await this.getWaveStrategyMatchedOrderCountTotal( + contextWarehouseId, + { strategyType: strategyTypeList } + ); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyList] 统计全部命中订单总数失败,降级为 0', { + warehouse_id: contextWarehouseId, + strategy_type: strategyTypeList, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + return this.success('ok', { + list: mergedList, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + info: { + order_count: matchedOrderCountTotal, + }, + }); + } + + /** + * 批量预演当前页策略“下一个抓取订单数”。 + * + * 仅执行候选查询与规则计算,不写库、不建波次、不占锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} [strategyRows=[]] 策略行数组。 + * @return {Promise>} strategy_id 到预演订单数映射。 + */ + async getWaveStrategyNextFetchOrderCountMap(warehouseId, strategyRows = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const rows = Array.isArray(strategyRows) ? strategyRows : []; + const countMap = new Map(); + + await Promise.all(rows.map(async row => { + const strategyId = Number(row && row.id || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + try { + const nextFetchOrderCount = await this.previewWaveStrategyNextFetchOrderCount({ + warehouseId: normalizedWarehouseId, + strategyRow: row, + }); + countMap.set(strategyId, Number(nextFetchOrderCount || 0)); + } catch (error) { + this.ctx.logger.warn('[wave.getWaveStrategyNextFetchOrderCountMap] 预演策略抓取数量失败,降级为 0', { + warehouse_id: normalizedWarehouseId, + strategy_id: strategyId, + error: error && error.message ? error.message : `${error}`, + }); + countMap.set(strategyId, 0); + } + })); + + return countMap; + } + + /** + * 调试:按策略返回候选订单明细列表(含结构、快递、货主等指标)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} [strategyRows=[]] 策略行数组。 + * @return {Promise>>} strategy_id 到候选订单明细列表的映射。 + */ + async getWaveStrategyDebugFetchOrderListMap(warehouseId, strategyRows = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const rows = Array.isArray(strategyRows) ? strategyRows : []; + const orderListMap = new Map(); + + const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + + await Promise.all(rows.map(async row => { + const strategyId = Number(row && row.id || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + try { + const candidateRows = await this.ctx.model.query(` + SELECT + o.id, + o.items_hash, + o.items, + o.logistics_name, + o.logistics_code, + o.sys_logistics_code, + o.store_id, + o.items_count, + o.items_total, + o.wave_id, + o.step, + o.status, + o.outbound_status, + o.post_status, + o.storage_status, + o.print_status + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id + AND o.warehouse_id = :warehouseId + AND o.wave_id = 0 + AND o.step != 0 + AND o.post_status = 'fin' + AND o.storage_status = 'fin' + AND o.print_status != 'fin' + AND o.status != 'cancel' + AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' + AND (o.is_b2b IS NULL OR o.is_b2b = 'N') + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id = :strategyId + ORDER BY o.id ASC + LIMIT 500 + `, { + replacements: { + warehouseId: normalizedWarehouseId, + strategyId, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const normalizedRows = Array.isArray(candidateRows) ? candidateRows : []; + const requireSameExpress = Number(row && row.require_same_express || 0) === 1; + const filteredRows = requireSameExpress && normalizedRows.length > 0 + ? (() => { + const expressGroupMap = new Map(); + for (const order of normalizedRows) { + const expressKey = this.getWaveStrategyQuickScanExpressKey({ + sys_logistics_code: order.sys_logistics_code, + logistics_code: order.logistics_code, + logistics_name: order.logistics_name, + }); + const key = expressKey || '__empty__'; + if (!expressGroupMap.has(key)) { + expressGroupMap.set(key, []); + } + expressGroupMap.get(key).push(order); + } + const groups = Array.from(expressGroupMap.values()) + .sort((a, b) => b.length - a.length); + return groups.length > 0 ? groups[0] : normalizedRows; + })() + : normalizedRows; + const detailList = filteredRows.map(order => ({ + order_id: Number(order && order.id || 0), + structure: { + items_hash: String(order && order.items_hash || '').trim(), + items: String(order && order.items || '').trim(), + }, + express: { + sys_logistics_code: String(order && order.sys_logistics_code || '').trim(), + logistics_code: String(order && order.logistics_code || '').trim(), + logistics_name: String(order && order.logistics_name || '').trim(), + }, + store_id: String(order && order.store_id || '').trim(), + items_count: Number(order && order.items_count || 0), + items_total: Number(order && order.items_total || 0), + wave_id: Number(order && order.wave_id || 0), + status: String(order && order.status || '').trim(), + outbound_status: String(order && order.outbound_status || '').trim(), + post_status: String(order && order.post_status || '').trim(), + storage_status: String(order && order.storage_status || '').trim(), + })); + + orderListMap.set(strategyId, { + candidate_count: detailList.length, + candidate_total: normalizedRows.length, + candidates: detailList, + }); + } catch (error) { + this.ctx.logger.warn('[wave.getWaveStrategyDebugFetchOrderListMap] 调试查询失败,降级为空', { + warehouse_id: normalizedWarehouseId, + strategy_id: strategyId, + error: error && error.message ? error.message : `${error}`, + }); + orderListMap.set(strategyId, { candidate_count: 0, candidates: [], error: error && error.message || `${error}` }); + } + })); + + return orderListMap; + } + + /** + * 预演单个策略“下一个抓取订单数”。 + * + * 口径复用自动分流逻辑,但仅计算最终会选中的订单数量,不执行写操作。 + * + * @param {Object} [params={}] 预演参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} params.strategyRow 策略行。 + * @return {Promise} 预演可抓取订单数。 + */ + async previewWaveStrategyNextFetchOrderCount(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; + const strategyId = Number(strategyRow.id || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return 0; + } + + const strategyType = Number(strategyRow.strategy_type || 0); + if (![ 1, 2, 3 ].includes(strategyType)) { + return 0; + } + + const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ + warehouseId, + strategyId, + minSameStructure: strategyRow.min_same_structure, + maxSameStructure: strategyRow.max_same_structure, + requireSameExpress: Number(strategyRow.require_same_express || 0), + strategyType, + }); + if (candidateRows.length <= 0) { + return 0; + } + + let groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); + if (groupedRows.length <= 0) { + return 0; + } + + if (Number(strategyRow.require_same_express || 0) === 1) { + const filteredRows = this.filterCandidateOrdersByRequireSameExpress(candidateRows); + groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(filteredRows); + if (groupedRows.length <= 0) { + return 0; + } + } + + if (strategyType === 2) { + const groupLimitRaw = Number(strategyRow.group_batch_max_orders || 0); + const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; + const selectedGroups = groupedRows.slice(0, groupLimit); + const selectedOrderIds = [ ...new Set(selectedGroups + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + return selectedOrderIds.length; + } + + const pickMode = this.resolveWaveStrategyFetchPickMode({ + requestData: {}, + strategyRow, + }); + const mergedOrderIds = [ ...new Set(groupedRows + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + if (mergedOrderIds.length <= 0) { + return 0; + } + + let selectedOrderIds = []; + if (pickMode === 3) { + const skuMap = await this.buildWaveStrategyFetchOrderSkuMap({ + warehouseId, + orderIds: mergedOrderIds, + }); + const skuLimitRaw = Number(strategyRow.batch_max_skus || 0); + const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; + const skuResult = this.selectWaveStrategyFetchOrdersBySkuLimit({ + orderIds: mergedOrderIds, + orderSkuMap: skuMap, + skuLimit, + }); + selectedOrderIds = skuResult.selectedOrderIds; + } else if (pickMode === 2 || pickMode === 4) { + selectedOrderIds = mergedOrderIds; + } else { + return 0; + } + + const orderLimitRaw = Number(strategyRow.batch_max_orders || 0); + const orderLimit = Number.isInteger(orderLimitRaw) && orderLimitRaw > 0 ? orderLimitRaw : 0; + const limitedOrderIds = orderLimit > 0 + ? selectedOrderIds.slice(0, orderLimit) + : selectedOrderIds; + + return limitedOrderIds.length; + } + + /** + * 按策略统计过滤后命中订单数。 + * + * 过滤口径与抓取候选 SQL(getWaveStrategyFetchCandidateOrders)保持一致: + * 1) 仅统计未在波次订单(wave_id = 0); + * 2) 仅统计 step != 0 的订单; + * 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding); + * 4) 散单/团购策略的同结构数量需落在 min_same_structure/max_same_structure 区间内 + * (require_same_express = 1 时按「结构 + 快递」分组计数); + * SN 策略(strategy_type=3)忽略同结构区间,仅统计 SN 订单。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} strategyRows 当前页策略行数组(含 require_same_express / strategy_type)。 + * @return {Promise>} strategy_id 到过滤后命中订单数的映射。 + */ + async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyRows = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const normalizedStrategies = [ ...new Map((Array.isArray(strategyRows) ? strategyRows : []) + .map(item => { + const strategyId = Number(item && (item.id ?? item.strategy_id) || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return null; + } + + return [ strategyId, { + id: strategyId, + strategyType: Number(item && item.strategy_type || 0), + requireSameExpress: Number(item && item.require_same_express || 0) === 1, + }]; + }) + .filter(Boolean)).values() ]; + if (normalizedStrategies.length === 0) { + return new Map(); + } + + const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; + const orderPoolConditionSql = alias => ` + AND ${alias}.warehouse_id = :warehouseId + AND ${alias}.wave_id = 0 + AND ${alias}.step != 0 + AND ${alias}.post_status = 'fin' + AND ${alias}.storage_status = 'fin' + AND ${alias}.print_status != 'fin' + AND ${alias}.status != 'cancel' + AND ${alias}.outbound_status != 'padding' + AND ${alias}.intercept_status = 'none' + AND ${alias}.lock_status = 'none' + AND (${alias}.is_b2b IS NULL OR ${alias}.is_b2b = 'N')`; + + const matchedMap = new Map(); + const runCountQuery = async (strategyGroup, options = {}) => { + const strategyIds = strategyGroup.map(item => item.id); + if (strategyIds.length === 0) { + return; + } + + const isSnStrategy = options.isSn === true; + const requireSameExpress = options.requireSameExpress === true; + const snCondition = isSnStrategy + ? "AND o.has_sn_item = 'Y'" + : "AND (o.has_sn_item IS NULL OR o.has_sn_item <> 'Y')"; + let querySql; + + if (isSnStrategy) { + // SN 策略忽略同结构区间,直接按策略命中明细统计 SN 订单 + querySql = ` + SELECT + m.strategy_id, + COUNT(DISTINCT m.order_id) AS matched_order_count_filtered + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id${orderPoolConditionSql('o')} + ${snCondition} + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id IN (:strategyIds) + GROUP BY m.strategy_id + `; + } else { + const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''; + const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; + querySql = ` + SELECT + m.strategy_id, + COUNT(DISTINCT m.order_id) AS matched_order_count_filtered + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id${orderPoolConditionSql('o')} + ${snCondition} + INNER JOIN ( + SELECT + src.items_hash AS structure_key${groupKeyExtra}, + COUNT(1) AS same_structure_count + FROM ${orderTableName} src + WHERE 1 = 1${orderPoolConditionSql('src')} + AND (src.has_sn_item IS NULL OR src.has_sn_item <> 'Y') + GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''} + ) same_structure + ON same_structure.structure_key = o.items_hash${joinKeyExtra} + INNER JOIN wms_wave_strategy s + ON s.id = m.strategy_id + AND s.warehouse_id = :warehouseId + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id IN (:strategyIds) + AND same_structure.same_structure_count >= COALESCE(NULLIF(s.min_same_structure, 0), 0) + AND (s.max_same_structure IS NULL OR s.max_same_structure <= 0 OR same_structure.same_structure_count <= s.max_same_structure) + GROUP BY m.strategy_id + `; + } + + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId: normalizedWarehouseId, + strategyIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + (Array.isArray(queryRows) ? queryRows : []).forEach(row => { + const strategyId = Number(row && row.strategy_id || 0); + const matchedCount = Number(row && row.matched_order_count_filtered || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + matchedMap.set(strategyId, matchedCount); + }); + }; + + const snStrategies = normalizedStrategies.filter(item => item.strategyType === 3); + const nonSnStrategies = normalizedStrategies.filter(item => item.strategyType !== 3); + + await Promise.all([ + runCountQuery(snStrategies, { isSn: true }), + runCountQuery(nonSnStrategies.filter(item => item.requireSameExpress), { requireSameExpress: true }), + runCountQuery(nonSnStrategies.filter(item => !item.requireSameExpress), { requireSameExpress: false }), + ]); + + return matchedMap; + } + + /** + * 统计仓库内全部策略命中的去重订单总数。 + * + * 口径与 getWaveStrategyMatchedOrderCountFilteredMap 完全一致(订单池过滤、 + * 散单/团购的同结构数量区间、require_same_express 分组方式;SN 策略忽略同结构区间), + * 但不再按策略分组统计,而是汇总查询条件下(仓库 + 可选策略类型)全部策略命中的订单并去重: + * 同一订单命中多个策略仅计一次。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [options={}] 统计选项。 + * @param {number|string|Array|null} [options.strategyType=null] 策略类型过滤(1 散单 / 2 团购 / 3 SN),支持数组;为空数组或 null 时不限制。 + * @return {Promise} 全部策略命中的去重订单总数。 + */ + async getWaveStrategyMatchedOrderCountTotal(warehouseId, options = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const strategyTypes = this.normalizeWaveStrategyTypeList(normalizedOptions.strategyType); + const strategyTypeFilterSql = strategyTypes.length > 0 + ? `AND s.strategy_type IN (${strategyTypes.join(', ')})` + : ''; + + const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; + const orderPoolConditionSql = alias => ` + AND ${alias}.warehouse_id = :warehouseId + AND ${alias}.wave_id = 0 + AND ${alias}.step != 0 + AND ${alias}.post_status = 'fin' + AND ${alias}.storage_status = 'fin' + AND ${alias}.print_status != 'fin' + AND ${alias}.status != 'cancel' + AND ${alias}.outbound_status != 'padding' + AND ${alias}.intercept_status = 'none' + AND ${alias}.lock_status = 'none' + AND (${alias}.is_b2b IS NULL OR ${alias}.is_b2b = 'N')`; + + // SN 策略命中明细:忽略同结构区间,仅统计 SN 订单 + const buildSnMatchedOrderIdSql = () => ` + SELECT m.order_id AS order_id + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id${orderPoolConditionSql('o')} + AND o.has_sn_item = 'Y' + INNER JOIN wms_wave_strategy s + ON s.id = m.strategy_id + AND s.warehouse_id = :warehouseId + AND s.strategy_type = 3 + ${strategyTypeFilterSql} + WHERE m.warehouse_id = :warehouseId + `; + + const buildMatchedOrderIdSql = requireSameExpress => { + const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''; + const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; + return ` + SELECT m.order_id AS order_id + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id${orderPoolConditionSql('o')} + AND (o.has_sn_item IS NULL OR o.has_sn_item <> 'Y') + INNER JOIN ( + SELECT + src.items_hash AS structure_key${groupKeyExtra}, + COUNT(1) AS same_structure_count + FROM ${orderTableName} src + WHERE 1 = 1${orderPoolConditionSql('src')} + AND (src.has_sn_item IS NULL OR src.has_sn_item <> 'Y') + GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''} + ) same_structure + ON same_structure.structure_key = o.items_hash${joinKeyExtra} + INNER JOIN wms_wave_strategy s + ON s.id = m.strategy_id + AND s.warehouse_id = :warehouseId + AND COALESCE(s.require_same_express, 0) = ${requireSameExpress ? 1 : 0} + AND s.strategy_type <> 3 + ${strategyTypeFilterSql} + WHERE m.warehouse_id = :warehouseId + AND same_structure.same_structure_count >= COALESCE(NULLIF(s.min_same_structure, 0), 0) + AND (s.max_same_structure IS NULL OR s.max_same_structure <= 0 OR same_structure.same_structure_count <= s.max_same_structure) + `; + }; + + const countRows = await this.ctx.model.query(` + SELECT COUNT(DISTINCT matched.order_id) AS order_count + FROM ( + ${buildSnMatchedOrderIdSql()} + UNION ALL + ${buildMatchedOrderIdSql(true)} + UNION ALL + ${buildMatchedOrderIdSql(false)} + ) matched + `, { + replacements: { + warehouseId: normalizedWarehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const totalCount = Number( + (Array.isArray(countRows) && countRows[0] && countRows[0].order_count) || 0 + ); + return Number.isInteger(totalCount) && totalCount >= 0 ? totalCount : 0; + } + + /** + * 新增波次策略。 + * + * warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 新增结果。 + */ + async waveStrategyCreate(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const strategyModel = this.getWaveStrategyModel(); + if (!strategyModel || typeof strategyModel.create !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const payload = await this.normalizeWaveStrategyUpsertPayload(requestData, { + warehouseId, + mode: 'create', + }); + const operator = this.getOrderLogOperator(); + const transaction = await this.ctx.model.transaction(); + let created; + try { + created = await strategyModel.create({ + ...payload, + warehouse_id: warehouseId, + creator_name: String(operator && operator.name || 'system').trim() || 'system', + }, { + transaction, + }); + + await this.bumpWaveStrategyVersionAndInvalidateCache(warehouseId, { transaction }); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + const createdData = created && typeof created.get === 'function' ? created.get({ plain: true }) : created; + + return this.success('ok', { data: createdData, code: 200 }); + } + + /** + * 修改波次策略。 + * + * warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 修改结果。 + */ + async waveStrategyUpdate(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const strategyModel = this.getWaveStrategyModel(); + if (!strategyModel || typeof strategyModel.findOne !== 'function' || typeof strategyModel.update !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const strategyId = this.normalizeWaveStrategyId(requestData); + const payload = await this.normalizeWaveStrategyUpsertPayload(requestData, { + warehouseId, + mode: 'update', + }); + if (Object.keys(payload).length === 0) { + throw new Error('缺少可更新字段'); + } + + const operator = this.getOrderLogOperator(); + const transaction = await this.ctx.model.transaction(); + let updated; + try { + const exists = await strategyModel.findOne({ + where: { + id: strategyId, + warehouse_id: warehouseId, + }, + raw: true, + transaction, + }); + if (!exists) { + throw new Error(`波次策略不存在: ${strategyId}`); + } + + await strategyModel.update({ + ...payload, + creator_name: String(operator && operator.name || 'system').trim() || 'system', + update_time: new Date(), + }, { + where: { + id: strategyId, + warehouse_id: warehouseId, + }, + transaction, + }); + + await this.bumpWaveStrategyVersionAndInvalidateCache(warehouseId, { transaction }); + + updated = await strategyModel.findOne({ + where: { + id: strategyId, + warehouse_id: warehouseId, + }, + raw: true, + transaction, + }); + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + return this.success('ok', { data: updated || null, code: 200 }); + } + + /** + * 递增仓库波次策略版本并失效相关缓存。 + * + * 数据更新在事务内执行;当传入事务时,缓存失效动作会在事务提交后执行。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [options={}] 处理选项。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @return {Promise} 自增后的版本号。 + */ + async bumpWaveStrategyVersionAndInvalidateCache(warehouseId, options = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const { transaction } = this.isPlainObject(options) ? options : {}; + const settingWarehouseService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.setting + && this.ctx.service.systems.setting.warehouse; + const modelContainer = this.ctx.model || this.app.model || {}; + const storeModel = modelContainer.Store; + + if (!storeModel || typeof storeModel.findByPk !== 'function') { + throw new Error('Store model 不可用'); + } + + const storeQueryOptions = { + attributes: [ 'id', 'subject_config' ], + }; + if (transaction) { + storeQueryOptions.transaction = transaction; + if (transaction.LOCK && transaction.LOCK.UPDATE) { + storeQueryOptions.lock = transaction.LOCK.UPDATE; + } + } + + const store = await storeModel.findByPk(normalizedWarehouseId, storeQueryOptions); + if (!store) { + throw new Error(`仓库不存在: ${normalizedWarehouseId}`); + } + + const currentSubjectConfig = store.subject_config && typeof store.subject_config === 'object' && !Array.isArray(store.subject_config) + ? { ...store.subject_config } + : {}; + const normalizedSubjectConfig = settingWarehouseService + && typeof settingWarehouseService.normalizeSubjectConfigInternalFields === 'function' + ? settingWarehouseService.normalizeSubjectConfigInternalFields(currentSubjectConfig) + : currentSubjectConfig; + const currentVersion = settingWarehouseService + && typeof settingWarehouseService.normalizeWaveStrategyVersion === 'function' + ? settingWarehouseService.normalizeWaveStrategyVersion(normalizedSubjectConfig.wave_strategy_version, { useDefaultWhenEmpty: true }) + : Number(normalizedSubjectConfig.wave_strategy_version || 1); + + if (!Number.isSafeInteger(currentVersion) || currentVersion < 0) { + throw new Error('subject_config.wave_strategy_version 必须是非负整数'); + } + if (currentVersion >= Number.MAX_SAFE_INTEGER) { + throw new Error('subject_config.wave_strategy_version 超出安全整数范围'); + } + + const nextVersion = currentVersion + 1; + normalizedSubjectConfig.wave_strategy_version = nextVersion; + + const subjectConfigForUpdate = typeof storeModel.normalizeSubjectConfig === 'function' + ? storeModel.normalizeSubjectConfig(normalizedSubjectConfig) + : normalizedSubjectConfig; + + await store.update({ + subject_config: subjectConfigForUpdate, + }, { + ...(transaction ? { transaction } : {}), + }); + + const invalidateCache = async () => { + if (settingWarehouseService && typeof settingWarehouseService.clearWarehouseSettingCache === 'function') { + await settingWarehouseService.clearWarehouseSettingCache(normalizedWarehouseId); + } + + const deliveryOrderService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.deliveryOrder; + const subjectConfigCacheKey = deliveryOrderService + && typeof deliveryOrderService.getStoreSubjectConfigCacheKey === 'function' + ? deliveryOrderService.getStoreSubjectConfigCacheKey(normalizedWarehouseId) + : `delivery_order:store:${normalizedWarehouseId}:subject_config`; + + if (subjectConfigCacheKey) { + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(subjectConfigCacheKey); + } else if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(subjectConfigCacheKey, null, 0); + } + } + + const strategyCacheKey = `${WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX}${normalizedWarehouseId}`; + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(strategyCacheKey); + } else if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(strategyCacheKey, null, 0); + } + + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId) + .then(scanPayload => { + this.ctx.logger.info('[wave.bumpWaveStrategyVersionAndInvalidateCache] 异步触发全量扫描成功', { + warehouseId: normalizedWarehouseId, + taskId: String(scanPayload && scanPayload.task_id || '').trim(), + state: String(scanPayload && scanPayload.state || '').trim(), + }); + }) + .catch(error => { + this.ctx.logger.warn('[wave.bumpWaveStrategyVersionAndInvalidateCache] 异步触发全量扫描失败,不影响主流程', { + warehouseId: normalizedWarehouseId, + error: error && error.message ? error.message : `${error}`, + }); + }); + }); + }; + + if (transaction && typeof transaction.afterCommit === 'function') { + transaction.afterCommit(async () => { + await invalidateCache(); + }); + } else { + await invalidateCache(); + } + + return nextVersion; + } + + /** + * 获取波次策略模型。 + * + * @return {Object|null} 模型对象。 + */ + getWaveStrategyModel() { + return this.ctx.model && ( + this.ctx.model.wms_wave_strategy + || this.ctx.model.PickingStrategy + || this.ctx.model.WmsWaveStrategy + ); + } + + /** + * 归一化波次策略主键。 + * + * @param {Object} data 请求参数。 + * @return {number} 策略主键。 + */ + normalizeWaveStrategyId(data = {}) { + const rawId = data && (data.id ?? data.strategy_id ?? data.strategyId); + return this.normalizeRequiredPositiveInteger(rawId, 'id'); + } + + /** + * 归一化波次策略新增/修改入参并执行统一校验。 + * + * @param {Object} data 请求参数。 + * @param {Object} options 处理选项。 + * @param {number} options.warehouseId 当前仓库ID。 + * @param {string} options.mode 模式:create/update。 + * @return {Promise} 可直接写库的载荷。 + */ + async normalizeWaveStrategyUpsertPayload(data = {}, options = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const mode = String(options && options.mode || '').trim().toLowerCase(); + const warehouseId = Number(options && options.warehouseId || 0); + const payload = {}; + + if (mode === 'create') { + const strategyName = String(requestData.strategy_name || '').trim(); + if (!strategyName) { + throw new Error('strategy_name 参数不能为空'); + } + payload.strategy_name = strategyName; + if (Object.prototype.hasOwnProperty.call(requestData, 'wave_prefix')) { + const wavePrefix = String(requestData.wave_prefix || '').trim().slice(0, 5); + payload.wave_prefix = wavePrefix || null; + } + payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); + if (![ 1, 2, 3 ].includes(payload.strategy_type)) { + throw new Error('strategy_type 仅支持 1(散单)、2(团购) 或 3(SN)'); + } + if (payload.strategy_type === 3) { + // SN 策略固定批次模式:先拣后分(batch_mode=2) + payload.batch_mode = 2; + } else if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { + payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); + } else if (payload.strategy_type === 2) { + payload.batch_mode = 0; + } else { + throw new Error('batch_mode 参数不能为空'); + } + } else { + if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_name')) { + const strategyName = String(requestData.strategy_name || '').trim(); + if (!strategyName) { + throw new Error('strategy_name 参数不能为空'); + } + payload.strategy_name = strategyName; + } + if (Object.prototype.hasOwnProperty.call(requestData, 'wave_prefix')) { + const wavePrefix = String(requestData.wave_prefix || '').trim().slice(0, 5); + payload.wave_prefix = wavePrefix || null; + } + if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_type')) { + payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); + if (![ 1, 2, 3 ].includes(payload.strategy_type)) { + throw new Error('strategy_type 仅支持 1(散单)、2(团购) 或 3(SN)'); + } + } + if (payload.strategy_type === 3) { + // SN 策略固定批次模式:先拣后分(batch_mode=2) + payload.batch_mode = 2; + } else if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { + payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); + } else if (payload.strategy_type === 2) { + payload.batch_mode = 0; + } + } + + if (Object.prototype.hasOwnProperty.call(requestData, 'status')) { + const normalizedStatus = Number(requestData.status); + if (![ 0, 1 ].includes(normalizedStatus)) { + throw new Error('status 参数不合法,仅支持 0 或 1'); + } + payload.status = normalizedStatus; + } + + this.patchWaveStrategyIntegerField(payload, requestData, 'order_min_sku'); + this.patchWaveStrategyIntegerField(payload, requestData, 'order_max_sku'); + this.patchWaveStrategyIntegerField(payload, requestData, 'order_min_qty'); + this.patchWaveStrategyIntegerField(payload, requestData, 'order_max_qty'); + this.patchWaveStrategyIntegerField(payload, requestData, 'min_same_structure'); + this.patchWaveStrategyIntegerField(payload, requestData, 'max_same_structure'); + if (Object.prototype.hasOwnProperty.call(requestData, 'batch_max_orders')) { + const rawBatchMaxOrders = requestData.batch_max_orders; + if (rawBatchMaxOrders === null || rawBatchMaxOrders === '') { + payload.batch_max_orders = null; + } else { + payload.batch_max_orders = this.normalizePositiveInteger(rawBatchMaxOrders, 'batch_max_orders'); + } + } + const resolvedStrategyType = Object.prototype.hasOwnProperty.call(payload, 'strategy_type') + ? payload.strategy_type + : Object.prototype.hasOwnProperty.call(requestData, 'strategy_type') + ? this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type') + : null; + if (resolvedStrategyType === 2) { + payload.batch_max_orders = 0; + } + if (resolvedStrategyType === 3) { + // SN 策略固定批次模式:先拣后分(batch_mode=2) + payload.batch_mode = 2; + } + const resolvedBatchMode = Object.prototype.hasOwnProperty.call(payload, 'batch_mode') + ? payload.batch_mode + : Object.prototype.hasOwnProperty.call(requestData, 'batch_mode') + ? this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode') + : null; + if (resolvedBatchMode === 2) { + if (Object.prototype.hasOwnProperty.call(requestData, 'batch_max_skus')) { + const rawBatchMaxSkus = requestData.batch_max_skus; + if (rawBatchMaxSkus === null || rawBatchMaxSkus === '') { + payload.batch_max_skus = null; + } else { + payload.batch_max_skus = this.normalizePositiveInteger(rawBatchMaxSkus, 'batch_max_skus'); + } + } + } else { + payload.batch_max_skus = 0; + } + if (resolvedStrategyType !== null && resolvedStrategyType !== 2) { + payload.group_batch_max_orders = 0; + } else if (resolvedStrategyType === 2) { + if (Object.prototype.hasOwnProperty.call(requestData, 'group_batch_max_orders')) { + const rawGroupBatchMaxOrders = requestData.group_batch_max_orders; + if (rawGroupBatchMaxOrders === null || rawGroupBatchMaxOrders === '') { + payload.group_batch_max_orders = null; + } else { + payload.group_batch_max_orders = this.normalizePositiveInteger(rawGroupBatchMaxOrders, 'group_batch_max_orders'); + } + } + } else if (Object.prototype.hasOwnProperty.call(requestData, 'group_batch_max_orders')) { + const rawGroupBatchMaxOrders = requestData.group_batch_max_orders; + if (rawGroupBatchMaxOrders === null || rawGroupBatchMaxOrders === '') { + payload.group_batch_max_orders = null; + } else { + payload.group_batch_max_orders = this.normalizePositiveInteger(rawGroupBatchMaxOrders, 'group_batch_max_orders'); + } + } + + if (Object.prototype.hasOwnProperty.call(requestData, 'require_same_express')) { + payload.require_same_express = this.normalizeBoolean(requestData.require_same_express, false); + } + if (Object.prototype.hasOwnProperty.call(requestData, 'allow_cross_owner')) { + payload.allow_cross_owner = this.normalizeBoolean(requestData.allow_cross_owner, true); + } + if (Object.prototype.hasOwnProperty.call(requestData, 'description')) { + payload.description = String(requestData.description || '').trim(); + } + if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_provinces')) { + const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_provinces); + payload.allowed_provinces = list.length > 0 ? list : null; + } else if (mode === 'update') { + payload.allowed_provinces = null; + } + if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_platforms')) { + const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_platforms, false); + payload.allowed_platforms = list.length > 0 ? list : null; + } else if (mode === 'update') { + payload.allowed_platforms = null; + } + + if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_owners')) { + const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_owners); + if (list.length > 0) { + await this.validateWaveStrategyAllowedOwners(list, warehouseId); + } + payload.allowed_owners = list.length > 0 ? list : null; + } else if (mode === 'update') { + payload.allowed_owners = null; + } + + if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_expresses')) { + const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_expresses, false); + if (list.length > 0) { + await this.validateWaveStrategyAllowedExpresses(list); + } + payload.allowed_expresses = list.length > 0 ? list : null; + } else if (mode === 'update') { + payload.allowed_expresses = null; + } + + await this.applyWaveStrategyMaxSameStructureConstraint(payload, warehouseId); + + delete payload.warehouse_id; + delete payload.creator; + delete payload.creator_name; + + return payload; + } + + /** + * 归一化波次策略波次前缀。 + * + * 规则: + * 1. 允许为空字符串(表示回退仓库前缀); + * 2. 非空时统一转大写; + * 3. 非空时仅允许 A-Z0-9,长度 1-5。 + * + * @param {*} rawWavePrefix 原始波次前缀入参。 + * @return {string} 归一化后的波次前缀。 + */ + normalizeWaveStrategyWavePrefix(rawWavePrefix) { + if (rawWavePrefix === undefined || rawWavePrefix === null) { + return ''; + } + + const normalizedWavePrefix = String(rawWavePrefix).trim() + .toUpperCase(); + if (!normalizedWavePrefix) { + return ''; + } + + if (normalizedWavePrefix.length < 1 || normalizedWavePrefix.length > 5) { + throw new Error('wave_prefix 非空时长度必须为 1-5 个字符'); + } + + if (!/^[A-Z0-9]+$/.test(normalizedWavePrefix)) { + throw new Error('wave_prefix 非空时仅支持 A-Z0-9'); + } + + return normalizedWavePrefix; + } + + /** + * 解析策略抓取建波使用的前缀(策略优先,仓库前缀兜底)。 + * + * @param {Object} params 解析参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.strategyType 策略类型(1-散单,2-团购,3-SN)。 + * @param {Object} [params.strategyRow={}] 策略行。 + * @return {Promise<{ wavePrefix: string, source: string }>} 前缀及来源。 + */ + async resolveWaveStrategyFetchWavePrefix(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const strategyType = Number(params.strategyType || 0); + const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; + const strategyWavePrefix = this.normalizeWaveStrategyWavePrefix(strategyRow.wave_prefix); + + if (strategyWavePrefix) { + return { + wavePrefix: strategyWavePrefix, + source: 'strategy', + }; + } + + const warehouseWavePrefix = strategyType === 2 + ? await this.getGroupWavePrefix(warehouseId) + : await this.getSingleFetchByIdsWavePrefix(warehouseId); + + return { + wavePrefix: String(warehouseWavePrefix || '').trim() || (strategyType === 2 ? 'B' : 'A'), + source: 'warehouse_fallback', + }; + } + + /** + * 按字段补丁方式归一化波次策略正整数参数。 + * + * @param {Object} payload 输出载荷。 + * @param {Object} requestData 原始请求。 + * @param {string} fieldName 字段名。 + */ + patchWaveStrategyIntegerField(payload = {}, requestData = {}, fieldName = '') { + if (!Object.prototype.hasOwnProperty.call(requestData, fieldName)) { + return; + } + + const rawValue = requestData[fieldName]; + if (rawValue === null || rawValue === '') { + payload[fieldName] = null; + return; + } + + payload[fieldName] = this.normalizeRequiredPositiveInteger(rawValue, fieldName); + } + + /** + * 校验 allowed_owners 是否在系统可用货主范围内。 + * + * @param {Array} ownerList 货主列表。 + * @param {number} warehouseId 当前仓库ID。 + * @return {Promise} 无返回值。 + */ + async validateWaveStrategyAllowedOwners(ownerList = [], warehouseId = 0) { + const normalizedOwners = Array.isArray(ownerList) + ? ownerList.map(item => String(item || '').trim().toLowerCase()).filter(Boolean) + : []; + if (normalizedOwners.length === 0) { + return; + } + + const availableOwnerSet = await this.getWaveStrategyAvailableOwnerSet(warehouseId); + const illegalOwners = normalizedOwners.filter(item => !availableOwnerSet.has(item)); + + if (illegalOwners.length > 0) { + throw new Error(`allowed_owners 存在非法值: ${illegalOwners.join(', ')}`); + } + } + + /** + * 校验 allowed_expresses 是否在系统可用快递范围内。 + * + * @param {Array} expressList 快递编码列表。 + * @return {Promise} 无返回值。 + */ + async validateWaveStrategyAllowedExpresses(expressList = []) { + const normalizedExpresses = Array.isArray(expressList) + ? expressList.map(item => String(item || '').trim()).filter(Boolean) + : []; + if (normalizedExpresses.length === 0) { + return; + } + + const availableExpressSet = await this.getWaveStrategyAvailableExpressSet(); + const availableLowerSet = new Set([ ...availableExpressSet ].map(s => s.toLowerCase())); + const illegalExpresses = normalizedExpresses.filter(item => !availableLowerSet.has(String(item).toLowerCase())); + + if (illegalExpresses.length > 0) { + throw new Error(`allowed_expresses 存在非法值: ${illegalExpresses.join(', ')}`); + } + } + + /** + * 获取当前仓库可用货主集合。 + * + * 优先复用 systems.store.loadStores,若不可用则回退查询签约表。 + * + * @param {number} warehouseId 当前仓库ID。 + * @return {Promise>} 货主集合(小写字符串)。 + */ + async getWaveStrategyAvailableOwnerSet(warehouseId = 0) { + const availableSet = new Set(); + const storeService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.store; + + if (storeService && typeof storeService.loadStores === 'function') { + const rows = await storeService.loadStores(); + for (const row of Array.isArray(rows) ? rows : []) { + const ownerId = String(row && (row.value ?? row.store_id) || '').trim().toLowerCase(); + if (ownerId) { + availableSet.add(ownerId); + } + } + } + + if (availableSet.size > 0) { + return availableSet; + } + + const normalizedWarehouseId = Number(warehouseId || 0); + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.findAll !== 'function') { + return availableSet; + } + + const rows = await storeWarehouseModel.findAll({ + attributes: [ 'store_id' ], + where: { + warehouse_id: normalizedWarehouseId, + warehouse_use_status: 1, + }, + raw: true, + }); + + for (const row of Array.isArray(rows) ? rows : []) { + const ownerId = String(row && row.store_id || '').trim().toLowerCase(); + if (ownerId) { + availableSet.add(ownerId); + } + } + + return availableSet; + } + + /** + * 获取当前仓库可用快递编码集合。 + * + * 优先复用 systems.express.getExpressList,若不可用则回退系统快递表。 + * + * @return {Promise>} 快递编码集合(小写字符串)。 + */ + async getWaveStrategyAvailableExpressSet() { + const availableSet = new Set(); + const expressService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.express; + + if (expressService && typeof expressService.getExpressList === 'function') { + const rows = await expressService.getExpressList(); + for (const row of Array.isArray(rows) ? rows : []) { + const code = String(row && (row.code || row.value) || '').trim().toLowerCase(); + if (code) { + availableSet.add(code); + } + } + } + + if (availableSet.size > 0) { + return availableSet; + } + + const expressModel = this.ctx.model && this.ctx.model.Express; + if (!expressModel || typeof expressModel.findAll !== 'function') { + return availableSet; + } + + const rows = await expressModel.findAll({ + attributes: [ 'code' ], + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + for (const row of Array.isArray(rows) ? rows : []) { + const code = String(row && row.code || '').trim().toLowerCase(); + if (code) { + availableSet.add(code); + } + } + + return availableSet; + } + + /** + * 按仓库最小团购抓取量约束 max_same_structure。 + * + * 当 min_group_order_fetch_quantity 为有效正整数且 + * max_same_structure >= min_group_order_fetch_quantity 时, + * 自动下调为 min_group_order_fetch_quantity - 1,且最小保持为 1。 + * + * @param {Object} payload 目标写库载荷。 + * @param {number} warehouseId 当前仓库ID。 + * @return {Promise} 无返回值。 + */ + async applyWaveStrategyMaxSameStructureConstraint(payload = {}, warehouseId = 0) { + if (!Object.prototype.hasOwnProperty.call(payload, 'max_same_structure')) { + return; + } + + const maxSameStructure = payload.max_same_structure; + if (maxSameStructure === null || maxSameStructure === undefined || maxSameStructure === '') { + return; + } + + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return; + } + + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const minGroupOrderFetchQuantity = Number( + this.getWarehouseSubjectConfigValue(subjectConfig, 'min_group_order_fetch_quantity') + ); + if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) { + return; + } + + const normalizedMaxSameStructure = Number(maxSameStructure); + if (!Number.isInteger(normalizedMaxSameStructure) || normalizedMaxSameStructure <= 0) { + throw new Error('max_same_structure 参数必须为正整数'); + } + + if (normalizedMaxSameStructure >= minGroupOrderFetchQuantity) { + payload.max_same_structure = Math.max(minGroupOrderFetchQuantity - 1, 1); + } + } + + /** + * 校验并标准化兜底订单列表 where 白名单字段。 + * + * 仅允许与波次策略过滤直接相关的字段;对兼容别名做统一映射, + * 例如 delivery_no -> delivery_order_code、tracking_no -> express_numbers。 + * + * @param {Object} whereData 原始 where 入参。 + * @return {Object} 标准化后的 where 条件。 + */ + normalizeWaveStrategyFallbackOrderListWhere(whereData = {}) { + const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; + const whereKeys = Object.keys(normalizedWhere); + + if (whereKeys.includes('warehouse_id') || whereKeys.includes('warehouseId')) { + throw new Error('where 中禁止传入 warehouse_id 或 warehouseId'); + } + + const allowedFields = Object.keys(WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP); + const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); + if (invalidFields.length > 0) { + throw new Error(`where 存在不支持的字段: ${invalidFields.join(',')}`); + } + + const hasStoreName = Object.prototype.hasOwnProperty.call(normalizedWhere, 'store_name'); + const hasOwnerName = Object.prototype.hasOwnProperty.call(normalizedWhere, 'owner_name'); + if (hasStoreName && hasOwnerName) { + throw new Error('store_name 与 owner_name 不能同时传入,请保留一个货主名称字段'); + } + + const rangeOperatorMap = Object.freeze({ + items_count_min: 'ge', + items_count_max: 'le', + items_total_min: 'ge', + items_total_max: 'le', + }); + const mappedWhere = {}; + for (const field of allowedFields) { + if (!Object.prototype.hasOwnProperty.call(normalizedWhere, field)) { + continue; + } + + if (Object.prototype.hasOwnProperty.call(rangeOperatorMap, field)) { + const rawValue = normalizedWhere[field]; + const value = this.isPlainObject(rawValue) && Object.prototype.hasOwnProperty.call(rawValue, 'value') + ? rawValue.value + : rawValue; + mappedWhere[field] = { + operator: rangeOperatorMap[field], + field: WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP[field], + value, + }; + continue; + } + + mappedWhere[WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP[field]] = normalizedWhere[field]; + } + + return mappedWhere; + } + + /** + * 解析兜底订单列表中的快递号展示值。 + * + * @param {Object} orderRow 订单行。 + * @return {string|null} 快递号。 + */ + resolveWaveStrategyFallbackTrackingNo(orderRow = {}) { + if (!this.isPlainObject(orderRow)) { + return null; + } + + const directTrackingNo = String(orderRow.tracking_no || '').trim(); + if (directTrackingNo) { + return directTrackingNo; + } + + const expressNumbers = Array.isArray(orderRow.express_numbers) + ? orderRow.express_numbers + : Array.isArray(orderRow.waybill_codes) + ? orderRow.waybill_codes + : []; + const normalizedExpressNumbers = expressNumbers + .map(item => String(item || '').trim()) + .filter(Boolean); + + if (normalizedExpressNumbers.length > 0) { + return normalizedExpressNumbers[0]; + } + + const expressNumbersText = String(orderRow.express_numbers || '').trim(); + if (expressNumbersText) { + return expressNumbersText.split(',').map(item => item.trim()).filter(Boolean)[0] || null; + } + + return null; + } + + /** + * 解析兜底订单列表中的货主名称展示值。 + * + * @param {Object} orderRow 订单行。 + * @return {string|null} 货主名称。 + */ + resolveWaveStrategyFallbackStoreName(orderRow = {}) { + if (!this.isPlainObject(orderRow)) { + return null; + } + + const candidateList = [ + orderRow.store_name, + orderRow.owner_name, + orderRow.shop_nick, + orderRow.seller_nick, + ]; + + for (const candidate of candidateList) { + const normalizedValue = String(candidate || '').trim(); + if (normalizedValue) { + return normalizedValue; + } + } + + return null; + } + + /** + * 解析兜底订单列表中的系统快递名称。 + * + * @param {Object} orderRow 订单行。 + * @return {string|null} 系统快递名称。 + */ + resolveWaveStrategyFallbackSysLogisticsName(orderRow = {}) { + if (!this.isPlainObject(orderRow)) { + return null; + } + + const candidateList = [ orderRow.sys_logistics_name, orderRow.logistics_name ]; + for (const candidate of candidateList) { + const normalizedValue = String(candidate || '').trim(); + if (normalizedValue) { + return normalizedValue; + } + } + + return null; + } + + /** + * 构建兜底订单列表单行输出,仅保留波次策略相关字段。 + * + * @param {Object} orderRow 原始订单行。 + * @param {string} itemSnapshot 商品快照文本。 + * @return {Object} 裁剪后的订单行。 + */ + buildWaveStrategyFallbackOrderListItem(orderRow = {}, itemSnapshot = '') { + const normalizedOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; + + // normalizeOrderListItem 已将 lock_status 归一化为 Y/N(none→N,其余→Y), + // 这里兼容归一化值(Y/N)与原始值(none/warehouse/store),避免把 N 误判为已锁定。 + const lockStatus = String(normalizedOrderRow.lock_status || '').trim(); + const isLocked = lockStatus === 'Y' + || (lockStatus !== '' && lockStatus !== 'N' && lockStatus !== 'none'); + + return { + id: normalizedOrderRow.id ?? null, + delivery_no: normalizedOrderRow.delivery_no ?? normalizedOrderRow.delivery_order_code ?? null, + tracking_no: this.resolveWaveStrategyFallbackTrackingNo(normalizedOrderRow), + items_count: normalizedOrderRow.items_count ?? null, + items_total: normalizedOrderRow.items_total ?? null, + items_weight: normalizedOrderRow.items_weight != null ? Number(normalizedOrderRow.items_weight) : null, + packages_weight: normalizedOrderRow.packages_weight != null ? Number(normalizedOrderRow.packages_weight) : null, + weight_type: this.formatWeightTypeLabel(normalizedOrderRow.weight_type), + sys_logistics_name: this.resolveWaveStrategyFallbackSysLogisticsName(normalizedOrderRow), + store_name: this.resolveWaveStrategyFallbackStoreName(normalizedOrderRow), + province: normalizedOrderRow.province ?? null, + sys_platform_name: normalizedOrderRow.sys_platform_name ?? null, + item_snapshot: String(itemSnapshot || ''), + wave_index: Number(normalizedOrderRow.wave_index || 0), + excluded_reason: isLocked + ? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.locked + : normalizedOrderRow.intercept_status !== 'none' + ? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.intercepted + : normalizedOrderRow.print_status === 'fin' + ? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.printed + : WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.no_match, + }; + } + + /** + * 查询兜底不符合波次策略的订单列表(含已完全打印被排除的订单)。 + * + * 查询条件:step != 0 且 wave_id = 0,且满足以下任一条件: + * - wave_scan_result = 2(未匹配任何波次策略) + * - print_status = 'fin'(已完全打印,被策略抓取阶段排除) + * 在当前页订单上增补 item_snapshot(格式:商品名称1*数量|商品名称2*数量)。 + * + * @param {Object} data 请求参数。 + * @param {Object} data.pagination 分页参数。 + * @param {Object} data.where 查询条件。 + * @param {Object} data.sort 排序参数。 + * @return {Promise} 列表查询结果,每行含 excluded_reason 标记。 + */ + async waveStrategyFallbackOrderList(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { pagination, where, sort } = requestData; + const normalizedPagination = this.normalizePagination(pagination || {}); + const { page, pageSize } = normalizedPagination; + const normalizedWhere = this.normalizeWaveStrategyFallbackOrderListWhere(where); + const contextWarehouseId = this.getWarehouseId(); + + // 构建基础 WHERE(复用框架 where 解析、快递号虚拟筛选等能力) + const { where: ctxWhere } = this.prepareWhereContext( + { ...requestData, where: normalizedWhere }, + { specialFieldMap: { quickWhere: { bucket: 'quick' } } } + ); + const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(ctxWhere); + const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); + const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); + const defaultWhere = this.getDefaultWhere('waveStrategyFallbackOrder'); + const mergedWhere = this.mergeWhereObjects(defaultWhere, whereAfterStockQuery); + let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { + specialFieldMap: { quickWhere: { bucket: 'quick' } }, + }); + + // 兜底列表同样排除 B2B 订单(B2B 订单不参与波次抓取,也不应出现在"未命中策略"列表中) + queryWhere = this.appendConditionToWhere(queryWhere, this.buildExcludeB2bCondition()); + + // 处理快递号虚拟筛选 + if (expressNumbers.length > 0) { + const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); + } + + if (buyerMessageHas !== null) { + const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas); + queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); + } + + // 处理 stock_query 虚拟筛选 + if (stockQuery) { + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'waveStrategyFallbackOrder', contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds); + } + + // 追加 OR 条件:未匹配策略(wave_scan_result=2) 或 已完全打印被排除(print_status='fin') + const { Sequelize } = this.app; + queryWhere = { + [Sequelize.Op.and]: [ + queryWhere, + { + [Sequelize.Op.or]: [ + { wave_scan_result: 2 }, + { print_status: 'fin' }, + { lock_status: { [Sequelize.Op.ne]: 'none' } }, + { intercept_status: { [Sequelize.Op.ne]: 'none' } }, + ], + }, + ], + }; + + // 获取模型并分页查询 + const model = await this.getOrderModel('waveStrategyFallbackOrder', contextWarehouseId); + const order = this.buildListOrder(sort, 'waveStrategyFallbackOrder'); + const offset = (page - 1) * pageSize; + + const [ total, sourceList ] = await Promise.all([ + model.count({ where: queryWhere }), + model.findAll({ + where: queryWhere, + limit: pageSize, + offset, + order, + raw: true, + }), + ]); + + const normalizedList = await this.attachOrderWaveIndex( + await this.attachOrderExpressNumbers( + sourceList.map(item => this.normalizeOrderListItem(item)) + ) + ); + + // 回填 item_snapshot + const orderIds = normalizedList + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + const warehouseId = Number(this.getWarehouseId() || 0); + const itemSnapshotMap = new Map(); + + if (orderIds.length > 0 && Number.isInteger(warehouseId) && warehouseId > 0) { + try { + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const hasValidModel = orderItemsModel && typeof orderItemsModel.findAll === 'function'; + const hasOpIn = Op && Object.prototype.hasOwnProperty.call(Op, 'in'); + + if (hasValidModel && hasOpIn) { + const orderItemRows = await orderItemsModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + const orderItemsMap = new Map(); + for (const row of orderItemRows || []) { + const orderId = Number(row && row.order_id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + if (!orderItemsMap.has(orderId)) { + orderItemsMap.set(orderId, []); + } + orderItemsMap.get(orderId).push(row); + } + + for (const orderId of orderIds) { + const itemRows = orderItemsMap.get(orderId) || []; + const itemDetails = this.mergeOrderItemDetails(itemRows); + itemSnapshotMap.set(orderId, this.buildOrderItemSnapshot(itemDetails)); + } + } + } catch (error) { + this.ctx.logger && this.ctx.logger.warn && this.ctx.logger.warn('[wave.waveStrategyFallbackOrderList] 回填 item_snapshot 失败,已降级为空字符串', { + warehouseId, + orderCount: orderIds.length, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + const list = normalizedList.map(item => { + const orderId = Number(item && item.id || 0); + return this.buildWaveStrategyFallbackOrderListItem(item, itemSnapshotMap.get(orderId) || ''); + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 解析波次列表的货主名称映射(store_id → 名称)。 + * + * 货主名称口径与售后/库存列表一致:合约表 wms_store_warehouse.store_remask + * (货主备注名称,store_id+warehouse_id 维度)优先,无合约或备注为空时回退 + * wms_store.company_name(公司全称)。 + * + * @param {Object[]} batchRows 波次行数据(含 order_total/owner_distinct_count/owner_named_count/owner_store_id)。 + * @param {number|string} [warehouseId=0] 当前仓库ID。 + * @return {Promise>} store_id → 货主名称。 + */ + async resolveWaveBatchOwnerStoreNameMap(batchRows = [], warehouseId = 0) { + const nameMap = new Map(); + const ownerStoreIds = []; + + for (const batch of batchRows) { + const orderCount = Number(batch && batch.order_total || 0); + const ownerDistinctCount = Number(batch && batch.owner_distinct_count || 0); + const ownerNamedCount = Number(batch && batch.owner_named_count || 0); + const ownerStoreId = Number(batch && batch.owner_store_id || 0); + if (orderCount > 0 && ownerDistinctCount === 1 && ownerNamedCount === orderCount && ownerStoreId > 0) { + ownerStoreIds.push(ownerStoreId); + } + } + + const uniqueStoreIds = [ ...new Set(ownerStoreIds) ]; + if (uniqueStoreIds.length === 0) { + return nameMap; + } + + const normalizedWarehouseId = Number(warehouseId || 0); + try { + // 1. 合约表货主备注名称(store_id + warehouse_id 维度) + const contractMap = new Map(); + if (normalizedWarehouseId > 0) { + const contractRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: uniqueStoreIds }, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const row of contractRows) { + const remask = String(row.store_remask || '').trim(); + if (remask) { + contractMap.set(Number(row.store_id), remask); + } + } + } + + // 2. 货主公司全称兜底 + const storeRows = await this.ctx.model.Store.findAll({ + where: { id: { [Op.in]: uniqueStoreIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const row of storeRows) { + const companyName = String(row.company_name || '').trim(); + if (companyName) { + nameMap.set(Number(row.id), companyName); + } + } + + // 3. 备注名称覆盖公司全称 + for (const storeId of uniqueStoreIds) { + if (contractMap.has(storeId)) { + nameMap.set(storeId, contractMap.get(storeId)); + } + } + } catch (error) { + this.ctx.logger?.warn?.('resolveWaveBatchOwnerStoreNameMap 解析货主名称失败:', error?.message || error); + } + + return nameMap; + } + + /** + * 波次列表查询。 + * + * 默认查询状态为 0/1 的波次,并附带订单分配状态汇总。 + * + * @param {Object} data 请求参数。 + * @param {Object} data.pagination 分页参数。 + * @return {Promise} 波次列表及分页信息。 + */ + async batchList(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizePagination(requestData, { + maxPageSize: BATCH_LIST_MAX_PAGE_SIZE, + }); + const waveStatusList = [ 0, 1 ]; + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const offset = (page - 1) * pageSize; + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const whereClause = this.buildBatchListWhereClause(requestData.where); + const storageAssignmentFilterClause = this.buildBatchListStorageAssignmentFilterClause(whereClause.storageAssignmentStatus); + const expressAssignmentFilterClause = this.buildBatchListExpressAssignmentFilterClause(whereClause.expressAssignmentStatus); + const printAssignmentFilterClause = this.buildBatchListPrintAssignmentFilterClause(whereClause.printAssignmentStatus); + const confirmPrintAssignmentFilterClause = this.buildBatchListConfirmPrintAssignmentFilterClause(whereClause.confirmPrintAssignmentStatus); + const claimAssignmentFilterClause = this.buildBatchListClaimAssignmentFilterClause(whereClause.claimAssignmentStatus); + const reviewAssignmentFilterClause = this.buildBatchListReviewAssignmentFilterClause(whereClause.reviewAssignmentStatus); + const syncAssignmentFilterClause = this.buildBatchListSyncAssignmentFilterClause(whereClause.syncAssignmentStatus); + const onlyTodo = Number(requestData.only_todo || 0); + const baseBatchWhereSql = ` + warehouse_id = :warehouseId + AND wave_status IN (:waveStatusList) + ${whereClause.sql} + `; + const storeIdFilter = Array.isArray(whereClause.storeIds) ? whereClause.storeIds : []; + const storeIdExcludeFilter = storeIdFilter.length > 0 && whereClause.storeIdOperator === 'notin'; + const ownerFilterJoinSql = storeIdFilter.length > 0 && !storeIdExcludeFilter ? ` + INNER JOIN ( + SELECT candidate_wave.wave_id + FROM ( + SELECT wave_id + FROM wms_wave_batch + WHERE ${baseBatchWhereSql} + ) candidate_wave + INNER JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id + AND od.store_id IN (:whereStoreIds) + GROUP BY candidate_wave.wave_id + ) wave_owner_filter ON wave_owner_filter.wave_id = wb.wave_id + ` : ''; + // store_id 排除语义(ne/notin):排除包含所选货主订单的波次(无货主订单的波次保留) + const ownerExcludeFilterSql = storeIdExcludeFilter ? ` + AND wb.wave_id NOT IN ( + SELECT DISTINCT od.wave_id + FROM ${orderTableName} od + WHERE od.wave_id IS NOT NULL + AND od.store_id IN (:whereStoreIds) + )` : ''; + const batchListFromSql = ` + FROM ( + SELECT + wave_id, + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + distinguish_express, + source, + logistics_name, + item_snapshot_key, + warehouse_id, + creator, + claim_operator, + claim_time, + create_time, + update_time + FROM wms_wave_batch + WHERE ${baseBatchWhereSql} + ) wb + LEFT JOIN ( + SELECT + candidate_wave.wave_id, + COUNT(od.wave_id) AS order_total, + SUM(CASE WHEN od.storage_status = 'none' THEN 1 ELSE 0 END) AS storage_none_count, + SUM(CASE WHEN od.storage_status = 'fin' THEN 1 ELSE 0 END) AS storage_fin_count, + SUM(CASE WHEN od.storage_status = 'error' THEN 1 ELSE 0 END) AS storage_error_count, + SUM(CASE WHEN od.post_status = 'none' THEN 1 ELSE 0 END) AS post_none_count, + SUM(CASE WHEN od.post_status = 'fin' THEN 1 ELSE 0 END) AS post_fin_count, + SUM(CASE WHEN od.post_status = 'error' THEN 1 ELSE 0 END) AS post_error_count, + SUM(CASE WHEN od.print_status = 'none' THEN 1 ELSE 0 END) AS print_none_count, + SUM(CASE WHEN od.print_status = 'fin' THEN 1 ELSE 0 END) AS print_fin_count, + SUM(CASE WHEN od.confirm_print_status = 'none' THEN 1 ELSE 0 END) AS confirm_print_none_count, + SUM(CASE WHEN od.confirm_print_status = 'fin' THEN 1 ELSE 0 END) AS confirm_print_fin_count, + SUM(CASE WHEN od.recheck_status = 'fin' THEN 1 ELSE 0 END) AS review_fin_count, + SUM(CASE WHEN od.recheck_status = 'error' THEN 1 ELSE 0 END) AS review_error_count, + SUM(CASE WHEN od.recheck_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count, + SUM(CASE WHEN od.sync_status = 'fin' THEN 1 ELSE 0 END) AS sync_fin_count, + SUM(CASE WHEN od.sync_status = 'error' THEN 1 ELSE 0 END) AS sync_error_count, + SUM(CASE WHEN od.sync_status IS NULL OR od.sync_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS sync_none_count, + SUM(CASE WHEN od.pick_status = 'none' THEN 1 ELSE 0 END) AS pick_none_count, + SUM(CASE WHEN od.pick_status = 'fin' THEN 1 ELSE 0 END) AS pick_fin_count, + SUM(CASE WHEN od.pick_status = 'error' THEN 1 ELSE 0 END) AS pick_error_count, + COUNT(DISTINCT NULLIF(od.store_id, 0)) AS owner_distinct_count, + MAX(NULLIF(od.store_id, 0)) AS owner_store_id, + SUM(CASE WHEN NULLIF(od.store_id, 0) IS NOT NULL THEN 1 ELSE 0 END) AS owner_named_count + FROM ( + SELECT wave_id + FROM wms_wave_batch + WHERE ${baseBatchWhereSql} + ) candidate_wave + LEFT JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id + GROUP BY candidate_wave.wave_id + ) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id + ${ownerFilterJoinSql} + LEFT JOIN wms_express e ON e.code = wb.logistics_name + WHERE 1 = 1 + ${ownerExcludeFilterSql} + ${storageAssignmentFilterClause.sql} + ${expressAssignmentFilterClause.sql} + ${printAssignmentFilterClause.sql} + ${confirmPrintAssignmentFilterClause.sql} + ${claimAssignmentFilterClause.sql} + ${reviewAssignmentFilterClause.sql} + ${syncAssignmentFilterClause.sql} + ${onlyTodo === 1 ? '\n AND COALESCE(wave_order_stats.order_total, 0) - COALESCE(wave_order_stats.review_fin_count, 0) > 0' : ''} + `; + + const listSql = ` + SELECT + wb.wave_id, + wb.wave_no, + wb.wave_type, + wb.wave_status, + wb.total_orders, + wb.processed_orders, + wb.distinguish_express, + wb.source, + wb.logistics_name AS logistics_code, + COALESCE(e.name, wb.logistics_name) AS logistics_name, + wb.item_snapshot_key, + wb.warehouse_id, + wb.creator, + wb.claim_operator, + wb.claim_time, + wb.create_time, + wb.update_time, + COALESCE(wave_order_stats.order_total, 0) AS order_total, + COALESCE(wave_order_stats.storage_none_count, 0) AS storage_none_count, + COALESCE(wave_order_stats.storage_fin_count, 0) AS storage_fin_count, + COALESCE(wave_order_stats.storage_error_count, 0) AS storage_error_count, + COALESCE(wave_order_stats.post_none_count, 0) AS post_none_count, + COALESCE(wave_order_stats.post_fin_count, 0) AS post_fin_count, + COALESCE(wave_order_stats.post_error_count, 0) AS post_error_count, + COALESCE(wave_order_stats.print_none_count, 0) AS print_none_count, + COALESCE(wave_order_stats.print_fin_count, 0) AS print_fin_count, + COALESCE(wave_order_stats.confirm_print_none_count, 0) AS confirm_print_none_count, + COALESCE(wave_order_stats.confirm_print_fin_count, 0) AS confirm_print_fin_count, + COALESCE(wave_order_stats.review_fin_count, 0) AS review_fin_count, + COALESCE(wave_order_stats.review_error_count, 0) AS review_error_count, + COALESCE(wave_order_stats.review_none_count, 0) AS review_none_count, + COALESCE(wave_order_stats.pick_none_count, 0) AS pick_none_count, + COALESCE(wave_order_stats.pick_fin_count, 0) AS pick_fin_count, + COALESCE(wave_order_stats.pick_error_count, 0) AS pick_error_count, + COALESCE(wave_order_stats.sync_none_count, 0) AS sync_none_count, + COALESCE(wave_order_stats.sync_fin_count, 0) AS sync_fin_count, + COALESCE(wave_order_stats.sync_error_count, 0) AS sync_error_count, + COALESCE(wave_order_stats.owner_distinct_count, 0) AS owner_distinct_count, + wave_order_stats.owner_store_id, + COALESCE(wave_order_stats.owner_named_count, 0) AS owner_named_count + ${batchListFromSql} + ORDER BY wb.total_orders DESC, wb.wave_id DESC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + ${batchListFromSql} + `; + + const [ batchRows, totalRows ] = await Promise.all([ + this.ctx.model.query(listSql, { + replacements: { + warehouseId, + waveStatusList, + ...whereClause.replacements, + ...storageAssignmentFilterClause.replacements, + ...expressAssignmentFilterClause.replacements, + ...printAssignmentFilterClause.replacements, + ...confirmPrintAssignmentFilterClause.replacements, + ...claimAssignmentFilterClause.replacements, + ...reviewAssignmentFilterClause.replacements, + ...syncAssignmentFilterClause.replacements, + ...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}), + limit: pageSize, + offset, + }, + }), + this.ctx.model.query(countSql, { + replacements: { + warehouseId, + waveStatusList, + ...whereClause.replacements, + ...storageAssignmentFilterClause.replacements, + ...expressAssignmentFilterClause.replacements, + ...printAssignmentFilterClause.replacements, + ...confirmPrintAssignmentFilterClause.replacements, + ...claimAssignmentFilterClause.replacements, + ...reviewAssignmentFilterClause.replacements, + ...syncAssignmentFilterClause.replacements, + ...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}), + }, + }), + ]); + + const rawList = Array.isArray(batchRows && batchRows[0]) ? batchRows[0] : []; + const totalRowList = Array.isArray(totalRows && totalRows[0]) ? totalRows[0] : []; + const total = Number(totalRowList[0] && totalRowList[0].total || 0); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + if (rawList.length === 0) { + return this.success('ok', { + list: [], + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + const ownerStoreNameMap = await this.resolveWaveBatchOwnerStoreNameMap(rawList, warehouseId); + + const list = rawList.map(batch => { + const waveId = Number(batch && batch.wave_id || 0); + const orderCount = Number(batch && batch.order_total || 0); + const storageNoneCount = Number(batch && batch.storage_none_count || 0); + const storageFinCount = Number(batch && batch.storage_fin_count || 0); + const storageErrorCount = Number(batch && batch.storage_error_count || 0); + const expressNoneCount = Number(batch && batch.post_none_count || 0); + const expressFinCount = Number(batch && batch.post_fin_count || 0); + const expressErrorCount = Number(batch && batch.post_error_count || 0); + const printNoneCount = Number(batch && batch.print_none_count || 0); + const printFinCount = Number(batch && batch.print_fin_count || 0); + const confirmPrintNoneCount = Number(batch && batch.confirm_print_none_count || 0); + const confirmPrintFinCount = Number(batch && batch.confirm_print_fin_count || 0); + const pickNoneCount = Number(batch && batch.pick_none_count || 0); + const pickFinCount = Number(batch && batch.pick_fin_count || 0); + const pickErrorCount = Number(batch && batch.pick_error_count || 0); + const reviewFinCount = Number(batch && batch.review_fin_count || 0); + const reviewErrorCount = Number(batch && batch.review_error_count || 0); + const syncNoneCount = Number(batch && batch.sync_none_count || 0); + const syncFinCount = Number(batch && batch.sync_fin_count || 0); + const syncErrorCount = Number(batch && batch.sync_error_count || 0); + const unreviewedOrderCount = orderCount - reviewFinCount; + const ownerDistinctCount = Number(batch && batch.owner_distinct_count || 0); + const ownerNamedCount = Number(batch && batch.owner_named_count || 0); + const ownerStoreId = Number(batch && batch.owner_store_id || 0); + + // 货主展示:仅当所有订单均存在货主(store_id)且货主唯一时返回货主名称,否则返回“混合”。 + const ownerName = orderCount > 0 + && ownerDistinctCount === 1 + && ownerNamedCount === orderCount + && ownerStoreId > 0 + ? (ownerStoreNameMap.get(ownerStoreId) || '') + : '混合'; + + // 复核状态判定:error 统一归入未复核 + let reviewAssignmentStatus; + if (reviewErrorCount > 0 || orderCount === 0 || reviewFinCount === 0) { + reviewAssignmentStatus = 'unreviewed'; + } else if (reviewFinCount === orderCount) { + reviewAssignmentStatus = 'reviewed'; + } else { + reviewAssignmentStatus = 'partially_reviewed'; + } + + return { + wave_id: waveId, + wave_no: String(batch && batch.wave_no || '').trim(), + wave_type: Number(batch && batch.wave_type || 0), + wave_status: Number(batch && batch.wave_status || 0), + total_orders: Number(batch && batch.total_orders || 0), + processed_orders: Number(batch && batch.processed_orders || 0), + item_detail_machine: String(batch && batch.item_detail_machine || '').trim(), + item_part_type: String(batch && batch.item_part_type || '').trim(), + item_part: String(batch && batch.item_part || '').trim(), + distinguish_express: Number(batch && batch.distinguish_express || 0), + source: Number(batch && batch.source || 0), + logistics_code: String(batch && batch.logistics_code || '').trim(), + logistics_name: String(batch && batch.logistics_name || '').trim(), + item_snapshot_key: String(batch && batch.item_snapshot_key || '').trim(), + warehouse_id: Number(batch && batch.warehouse_id || 0), + creator: String(batch && batch.creator || '').trim(), + create_time: batch && batch.create_time || null, + update_time: batch && batch.update_time || null, + order_count: orderCount, + storage_assignment_status: this.resolveAssignmentStatus(orderCount, storageNoneCount, storageFinCount, storageErrorCount), + express_assignment_status: this.resolveAssignmentStatus(orderCount, expressNoneCount, expressFinCount, expressErrorCount), + print_assignment_status: this.resolveAssignmentStatus(orderCount, printNoneCount, printFinCount, 0, { + none: '未打印', + partial: '部分打印', + finished: '已打印', + }), + confirm_print_assignment_status: this.resolveAssignmentStatus(orderCount, confirmPrintNoneCount, confirmPrintFinCount, 0, { + none: '未确认打印', + partial: '部分确认打印', + finished: '已确认打印', + }), + claim_assignment_status: batch && batch.claim_time ? '已领料' : '未领料', + claim_time: batch && batch.claim_time || null, + claim_operator: String(batch && batch.claim_operator || '').trim(), + pick_assignment_status: this.resolveAssignmentStatus(orderCount, pickNoneCount, pickFinCount, pickErrorCount, { + none: '未拣货', + partial: '部分拣货', + finished: '已拣货', + error: '拣货异常', + }), + review_assignment_status: reviewAssignmentStatus, + sync_assignment_status: this.resolveAssignmentStatus(orderCount, syncNoneCount, syncFinCount, syncErrorCount, { + none: '未同步', + partial: '部分同步', + finished: '已同步', + error: '同步异常', + }), + unreviewed_order_count: unreviewedOrderCount, + store_name: ownerName, + }; + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 获取确认打印未领单波次版本号的缓存 key。 + * + * @param {number} warehouseId 仓库ID。 + * @return {string} 缓存 key。 + */ + getConfirmPrintUnclaimedVersionKey(warehouseId) { + return `${CONFIRM_PRINT_UNCLAIMED_VERSION_KEY_PREFIX}${warehouseId}`; + } + + /** + * 递增确认打印未领单波次版本号。 + * + * 确认打印(print.confirmWavePrint)与领单(pick.waveClaimScan)会改变统计结果, + * 操作成功后调用本方法,驱动 confirmPrintUnclaimedWaveCount 长轮询立即返回新值。 + * Redis 不可用或失败仅记录 warn,不影响主流程(长轮询端会降级为轮询 DB)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async bumpConfirmPrintUnclaimedWaveVersion(warehouseId) { + try { + const client = this.app && this.app.redis && typeof this.app.redis.get === 'function' + ? this.app.redis.get('cache') + : null; + if (client && typeof client.incr === 'function') { + await client.incr(this.getConfirmPrintUnclaimedVersionKey(warehouseId)); + } + } catch (error) { + this.ctx.logger.warn('[wave.confirmPrintVersion] 版本号递增失败', { + warehouseId, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + /** + * 读取确认打印未领单波次版本号。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 版本号,读取失败或不存在时返回 null。 + */ + async getConfirmPrintUnclaimedWaveVersion(warehouseId) { + try { + const client = this.app && this.app.redis && typeof this.app.redis.get === 'function' + ? this.app.redis.get('cache') + : null; + if (!client || typeof client.get !== 'function') { + return null; + } + const rawValue = await client.get(this.getConfirmPrintUnclaimedVersionKey(warehouseId)); + const value = Number(rawValue); + return Number.isFinite(value) && value > 0 ? value : null; + } catch (error) { + this.ctx.logger.warn('[wave.confirmPrintVersion] 版本号读取失败', { + warehouseId, + error: error && error.message ? error.message : `${error}`, + }); + return null; + } + } + + /** + * 查询「已确认打印但未领单」的波次数量(波次表驱动口径)。 + * + * 口径说明: + * - 未领单:以波次表为准(wb.claim_time IS NULL)。历史领单发生在 wms_wave_batch + * 增加 claim_time 字段之前时,订单维度 claim_status 可能已是 'fin' 但波次表无 + * 记录,故不能用订单 claim_status 判断「波次是否领单」。 + * - 已确认打印:波次下存在 confirm_print_status='fin' 的非取消订单。 + * - 仅统计 wave_status 0/1 的波次(与波次列表一致)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 波次数量。 + */ + async queryConfirmPrintUnclaimedWaveCount(warehouseId) { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const rows = await this.ctx.model.query( + `SELECT COUNT(*) AS wave_count + FROM wms_wave_batch wb + WHERE wb.warehouse_id = :warehouseId + AND wb.wave_status IN (0, 1) + AND wb.claim_time IS NULL + AND EXISTS ( + SELECT 1 + FROM ${orderTableName} od + WHERE od.wave_id = wb.wave_id + AND od.warehouse_id = wb.warehouse_id + AND od.status <> 'cancel' + AND od.confirm_print_status = 'fin' + )`, + { replacements: { warehouseId } } + ); + const rawList = Array.isArray(rows && rows[0]) ? rows[0] : []; + return Number(rawList[0] && rawList[0].wave_count || 0); + } + + /** + * 确认打印扫描(与领单 pick.waveClaimScan 操作一致): + * 扫波次内任一订单面单号,将波次下已打印且非拦截的订单批量置 + * confirm_print_status='fin' 并写订单操作日志。 + * + * 实际复用 print.confirmWavePrint 实现,避免重复维护; + * 成功后递增统计版本号,驱动 confirmPrintUnclaimedWaveCount 长轮询。 + * + * @param {Object} data 入参。 + * @param {string} data.waybill_no 面单号/运单号(必填)。 + * @return {Promise} 统一返回结构。 + */ + async confirmPrintScan(data = {}) { + const printService = this.ctx.service + && this.ctx.service.systemMethods + && this.ctx.service.systemMethods.print; + if (!printService || typeof printService.confirmWavePrint !== 'function') { + return this.fail('确认打印服务不可用', {}, 500); + } + return await printService.confirmWavePrint(data); + } + + /** + * 快速查询「已确认打印但未领单」的波次数量(波次表驱动口径: + * 未领单以 wms_wave_batch.claim_time IS NULL 为准,已确认打印以波次下存在 + * confirm_print_status='fin' 的订单为准)。 + * + * 长轮询语义(参考工作台扫码登录): + * - 不传 last_count:立即返回当前值(status=current); + * - 传 last_count 且与当前值不同:立即返回新值(status=changed); + * - 传 last_count 且与当前值相同:进入等待,每 1s 检查一次版本号(确认打印/领单 + * 成功会递增版本号),最长等待 60s;期间变化立即返回新值(status=changed), + * 超时未变化则重查一次返回当前值(status=timeout)。 + * + * @param {Object} [data={}] 入参。 + * @param {number|string} [data.last_count] 上次调用返回的 count(可选基线)。 + * @return {Promise} 统一返回结构,data 含 count / warehouse_id / status。 + */ + async confirmPrintUnclaimedWaveCount(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return this.fail('未识别到当前仓库上下文', {}, 400); + } + + const rawLastCount = requestData.last_count === undefined + ? requestData.lastCount + : requestData.last_count; + const hasBaseline = rawLastCount !== undefined && rawLastCount !== null && rawLastCount !== ''; + const lastCount = hasBaseline ? Number(rawLastCount) : NaN; + + let currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId); + + // 未带基线或基线非法:直接返回当前值(快速查询) + if (!hasBaseline || !Number.isFinite(lastCount)) { + return this.success('ok', { + count: currentCount, + warehouse_id: warehouseId, + status: 'current', + }); + } + + // 已变化:立即返回新值 + if (currentCount !== lastCount) { + return this.success('ok', { + count: currentCount, + warehouse_id: warehouseId, + status: 'changed', + }); + } + + // 等待变化:优先轮询版本号(低成本),版本号不可用时降级为轮询 DB + const baselineVersion = await this.getConfirmPrintUnclaimedWaveVersion(warehouseId); + const startedAt = Date.now(); + const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + while (Date.now() - startedAt < CONFIRM_PRINT_UNCLAIMED_POLL_TIMEOUT_MS) { + await sleep(CONFIRM_PRINT_UNCLAIMED_POLL_INTERVAL_MS); + + const currentVersion = await this.getConfirmPrintUnclaimedWaveVersion(warehouseId); + if (baselineVersion !== null && currentVersion !== null && currentVersion !== baselineVersion) { + currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId); + return this.success('ok', { + count: currentCount, + warehouse_id: warehouseId, + status: 'changed', + }); + } + + // 版本号不可用:降级为直接对比 count + if (baselineVersion === null || currentVersion === null) { + currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId); + if (currentCount !== lastCount) { + return this.success('ok', { + count: currentCount, + warehouse_id: warehouseId, + status: 'changed', + }); + } + } + } + + // 超时兜底:重查一次返回当前值(若期间恰好变化也返回新值) + currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId); + return this.success('ok', { + count: currentCount, + warehouse_id: warehouseId, + status: currentCount !== lastCount ? 'changed' : 'timeout', + }); + } + + /** + * 拣货任务列表查询。 + * + * 基于 wms_wave_pick_task 主表按当前仓库维度分页查询,默认按 create_time 倒序。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} [data.page] 页码(兼容 current)。 + * @param {number|string} [data.pageSize] 每页数量(兼容 size/page_size)。 + * @param {Object} [data.where] 查询过滤。 + * @return {Promise} 列表与分页结果;每项 list 元素包含 wave_list 数组(wave_id / wave_no / box_no / status / bind_time / pick_time)。 + */ + async wavePickTaskList(data = {}) { + try { + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizeWavePickTaskListPagination(requestData); + const normalizedRequest = this.normalizeWavePickTaskListRequest(requestData); + const warehouseId = normalizedRequest.warehouseId; + const whereClause = this.buildWavePickTaskListWhereClause(normalizedRequest.where); + const offset = (page - 1) * pageSize; + + const listSql = ` + SELECT + t.id, + t.task_no, + t.warehouse_id, + t.wave_id, + t.pick_mode, + t.status, + t.review_status, + t.source, + t.wave_count, + t.order_count, + t.box_count, + t.pick_user_id, + t.pick_user_name, + t.review_user_id, + t.review_user_name, + t.current_cart_id, + t.current_cart_code_snapshot, + c.cart_name AS cart_name, + t.batch_no, + t.claim_operator_id, + t.claim_operator, + t.device_id, + t.start_time, + t.finish_time, + t.review_start_time, + t.review_finish_time, + t.create_time, + t.update_time + FROM wms_wave_pick_task t + LEFT JOIN wms_pick_cart c ON c.id = t.current_cart_id AND c.warehouse_id = t.warehouse_id + WHERE t.warehouse_id = :warehouseId + ${whereClause.sql} + ORDER BY t.create_time DESC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + ${whereClause.sql} + `; + + const replacements = { + warehouseId, + ...whereClause.replacements, + }; + + const [ listRows, countRows ] = await Promise.all([ + this.ctx.model.query(listSql, { + replacements: { + ...replacements, + limit: pageSize, + offset, + }, + }), + this.ctx.model.query(countSql, { + replacements, + }), + ]); + + const sourceList = Array.isArray(listRows && listRows[0]) ? listRows[0] : []; + const totalRowList = Array.isArray(countRows && countRows[0]) ? countRows[0] : []; + const total = Number(totalRowList[0] && totalRowList[0].total || 0); + + // 批量查询 wave_list:收集任务ID,从关联表获取波次详情 + const taskIds = sourceList + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + + const taskWaveMap = new Map(); + if (taskIds.length > 0) { + const taskWaveRows = await this.ctx.model.query(` + SELECT + ptw.task_id, + ptw.wave_id, + ptw.wave_no, + ptw.box_no, + ptw.status, + ptw.bind_time, + ptw.pick_time + FROM wms_wave_pick_task_wave ptw + WHERE ptw.task_id IN (:taskIds) + AND ptw.warehouse_id = :warehouseId + ORDER BY ptw.id ASC + `, { + replacements: { taskIds, warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const normalizedTaskWaveRows = Array.isArray(taskWaveRows) ? taskWaveRows : []; + for (const row of normalizedTaskWaveRows) { + const taskId = Number(row && row.task_id || 0); + if (!Number.isInteger(taskId) || taskId <= 0) { + continue; + } + if (!taskWaveMap.has(taskId)) { + taskWaveMap.set(taskId, []); + } + taskWaveMap.get(taskId).push({ + wave_id: Number(row && row.wave_id || 0), + wave_no: String(row && row.wave_no || '').trim(), + box_no: Number(row && row.box_no || 0), + status: Number(row && row.status || 0), + bind_time: row && row.bind_time || null, + pick_time: row && row.pick_time || null, + }); + } + } + + // 回退:对于 wms_wave_pick_task_wave 无记录的任务, + // 尝试从主表 wave_id / wms_wave_batch 查询波次信息。 + // 兼容场景:散单旧数据未写入关联表、已取消任务关联记录被删除等。 + const missingWaveTaskIds = sourceList + .map(item => { + const taskId = Number(item && item.id || 0); + return Number.isInteger(taskId) && taskId > 0 && !taskWaveMap.has(taskId) + ? { taskId, waveId: Number(item && item.wave_id || 0) } + : null; + }) + .filter(Boolean); + + if (missingWaveTaskIds.length > 0) { + // 优先走 wms_wave_batch 回退(主表 wave_id 有值时) + const batchFallbackIds = missingWaveTaskIds.filter(m => m.waveId > 0); + if (batchFallbackIds.length > 0) { + const fallbackWaveIds = [ ...new Set(batchFallbackIds.map(m => m.waveId)) ]; + const fallbackWaveRows = await this.ctx.model.query(` + SELECT + wave_id, + wave_no + FROM wms_wave_batch + WHERE wave_id IN (:waveIds) + AND warehouse_id = :warehouseId + `, { + replacements: { waveIds: fallbackWaveIds, warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const waveNoMap = new Map(); + const normalizedFallbackRows = Array.isArray(fallbackWaveRows) ? fallbackWaveRows : []; + for (const row of normalizedFallbackRows) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + waveNoMap.set(waveId, String(row && row.wave_no || '').trim()); + } + + for (const { taskId, waveId } of batchFallbackIds) { + const waveNo = waveNoMap.get(waveId) || ''; + taskWaveMap.set(taskId, [{ + wave_id: waveId, + wave_no: waveNo, + box_no: 0, + status: 0, + bind_time: null, + pick_time: null, + }]); + } + } + + // 剩余仍未回退到的任务(wave_id 为空或 wms_wave_batch 也无记录), + // 检查其 batch_no(散单模式下冗余了 wave_no) + const remainingFallbackTaskIds = missingWaveTaskIds + .filter(m => !taskWaveMap.has(m.taskId)) + .map(m => m.taskId); + + if (remainingFallbackTaskIds.length > 0) { + for (const taskId of remainingFallbackTaskIds) { + const item = sourceList.find(s => Number(s && s.id || 0) === taskId); + const batchNo = String(item && item.batch_no || '').trim(); + if (batchNo) { + taskWaveMap.set(taskId, [{ + wave_id: 0, + wave_no: batchNo, + box_no: 0, + status: 0, + bind_time: null, + pick_time: null, + }]); + } + } + } + } + + const list = sourceList.map(item => ({ + task_id: Number(item && item.id || 0), + task_no: String(item && item.task_no || '').trim(), + warehouse_id: Number(item && item.warehouse_id || 0), + pick_mode: Number(item && item.pick_mode || 0), + status: Number(item && item.status || 0), + review_status: Number(item && item.review_status || 0), + source: Number(item && item.source || 0), + wave_count: Number(item && item.wave_count || 0), + order_count: Number(item && item.order_count || 0), + box_count: Number(item && item.box_count || 0), + pick_user_id: Number(item && item.pick_user_id || 0), + pick_user_name: String(item && item.pick_user_name || '').trim(), + operator_id: Number(item && item.pick_user_id || 0), + operator_name: String(item && item.pick_user_name || '').trim(), + review_user_id: Number(item && item.review_user_id || 0), + review_user_name: String(item && item.review_user_name || '').trim(), + current_cart_id: Number(item && item.current_cart_id || 0), + current_cart_code_snapshot: String(item && item.current_cart_code_snapshot || '').trim(), + cart_name: String(item && item.cart_name || '').trim(), + batch_no: String(item && item.batch_no || '').trim(), + claim_operator_id: Number(item && item.claim_operator_id || 0) || null, + claim_operator: String(item && item.claim_operator || '').trim() || null, + device_id: String(item && item.device_id || '').trim(), + start_time: item && item.start_time || null, + start_at: item && item.start_time || null, + finish_time: item && item.finish_time || null, + finish_at: item && item.finish_time || null, + review_start_time: item && item.review_start_time || null, + review_finish_time: item && item.review_finish_time || null, + create_time: item && item.create_time || null, + created_at: item && item.create_time || null, + update_time: item && item.update_time || null, + wave_list: taskWaveMap.get(Number(item && item.id || 0)) || [], + })); + + return this.success('ok', { + list, + total, + page, + page_size: pageSize, + }); + } catch (error) { + const errorMessage = String(error && error.message || '').trim(); + const isBadRequest = /参数|上下文|不支持/.test(errorMessage); + return this.fail(`查询拣货任务列表失败: ${errorMessage || '未知错误'}`, {}, isBadRequest ? 400 : 500); + } + } + + /** + * 批量解除波次任务提交接口。 + * + * 仅处理当前登录仓库下的波次与订单,提交后异步执行。 + * 提交前校验:波次属于活动拣货任务、波次内存在已拣货完成或拣货中的订单、 + * 或波次状态已进入拣货中及后续环节时,拒绝取消波次。 + * + * @param {Object} data 请求参数。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 + * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 + * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 + * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 + * @return {Promise} 任务提交结果。 + */ + async batchCancel(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); + if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { + throw new Error('warehouse_id 参数不合法'); + } + if (requestWarehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + const warehouseId = requestWarehouseId; + const normalizedWaveIds = this.normalizeBatchCancelWaveIds(data); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const activeTaskWaves = await this.ctx.model.query( + `SELECT ptw.wave_id + FROM wms_wave_pick_task_wave ptw + INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id + WHERE ptw.wave_id IN (:waveIds) + AND pt.status IN (0, 1) + LIMIT 1`, + { + replacements: { waveIds: normalizedWaveIds }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + if (activeTaskWaves.length > 0) { + throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); + } + + // 业务规则校验:波次内存在已拣货完成或拣货中的订单时禁止取消波次 + const orderModelForGuard = await this.getOrderModel('pendingOrder', warehouseId); + const pickedOrderRows = await orderModelForGuard.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status' ], + where: { + warehouse_id: warehouseId, + wave_id: { [Op.in]: normalizedWaveIds }, + pick_status: { [Op.in]: [ 'padding', 'fin' ] }, + }, + raw: true, + }); + const normalizedPickedOrderRows = Array.isArray(pickedOrderRows) ? pickedOrderRows : []; + if (normalizedPickedOrderRows.length > 0) { + const blockedWaveIds = [ ...new Set(normalizedPickedOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + const blockedOrderIds = normalizedPickedOrderRows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + const shownOrderIds = blockedOrderIds.slice(0, 20).join(', '); + const orderIdSuffix = blockedOrderIds.length > 20 ? ' 等' : ''; + return this.fail( + `波次内存在已拣货完成或拣货中的订单,禁止取消波次:波次 ${blockedWaveIds.join(', ')},订单 ${shownOrderIds}${orderIdSuffix}`, + { + wave_ids: blockedWaveIds, + order_ids: blockedOrderIds, + }, + 400 + ); + } + + // 兜底校验:波次状态已进入拣货中及后续环节(拣货中/拣货完成/复核完成/打包完成)时禁止取消 + const advancedWaveRows = await this.ctx.model.query( + `SELECT wave_id, wave_no, wave_status + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND wave_status >= 3`, + { + replacements: { + warehouseId, + waveIds: normalizedWaveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + const normalizedAdvancedWaveRows = Array.isArray(advancedWaveRows) ? advancedWaveRows : []; + if (normalizedAdvancedWaveRows.length > 0) { + const blockedWaveIds = normalizedAdvancedWaveRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0); + return this.fail( + `波次已进入拣货或后续环节,禁止取消波次:波次 ${blockedWaveIds.join(', ')}`, + { wave_ids: blockedWaveIds }, + 400 + ); + } + + const requestedTaskId = this.normalizeBatchCancelTaskId(data); + const taskId = requestedTaskId || this.generateBatchCancelTaskId(warehouseId); + const existingTask = await this.getBatchCancelTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量解除波次任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchCancelTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + wave_ids: normalizedWaveIds.join(','), + wave_id_list: normalizedWaveIds, + total_wave_count: normalizedWaveIds.length, + processed_wave_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[wave.batchCancel] 任务提交成功', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + }); + + setImmediate(() => { + this.runBatchCancelTask({ + taskId, + warehouseId, + waveIds: normalizedWaveIds, + }).catch(error => { + this.ctx.logger.error('[wave.batchCancel] 后台任务异常', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量解除波次任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量解除波次任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchCancelTaskProgress(data = {}) { + const taskId = this.normalizeBatchCancelTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchCancelTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.affected_wave_ids = Array.isArray(result.affected_wave_ids) ? result.affected_wave_ids : []; + payload.affected_order_count = Number(result.affected_order_count || 0); + payload.canceled_wave_count = Number(result.canceled_wave_count || 0); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_CANCEL_FAILED'; + payload.failed_wave_id = Number(cachedProgress.failed_wave_id || 0); + payload.failed_wave_no = String(cachedProgress.failed_wave_no || '').trim(); + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 批次分配快递号任务提交接口。 + * + * 仅接收当前仓库下波次ID,提交后立即返回 task_id,实际分配由后台异步执行。 + * + * @param {Object} data 请求参数。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 + * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 + * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 + * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 + * @return {Promise} 任务受理结果。 + */ + async batchAllocateExpress(data = {}) { + const traceId = this.buildBatchAllocateExpressTraceId(data); + const requestSnapshot = { + warehouse_id: data && (data.warehouse_id ?? data.warehouseId), + wave_ids: data && (data.wave_ids ?? data.waveIds ?? data.ids), + task_id: data && (data.task_id ?? data.taskId), + }; + + this.ctx.logger.info('[wave.batchAllocateExpress] 入口请求', { + traceId, + requestSnapshot, + }); + + try { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-仓库上下文缺失', { + traceId, + contextWarehouseId, + requestSnapshot, + }); + throw new Error('未识别到当前仓库上下文'); + } + + const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); + if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-warehouse_id 非法', { + traceId, + contextWarehouseId, + requestWarehouseId, + requestSnapshot, + }); + throw new Error('warehouse_id 参数不合法'); + } + if (requestWarehouseId !== contextWarehouseId) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-warehouse_id 与上下文不一致', { + traceId, + contextWarehouseId, + requestWarehouseId, + requestSnapshot, + }); + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + const warehouseId = requestWarehouseId; + const normalizedWaveIds = this.normalizeBatchAllocateExpressWaveIds(data); + if (normalizedWaveIds.length === 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-wave_ids 为空', { + traceId, + warehouseId, + requestSnapshot, + }); + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchAllocateExpressTaskId(data); + const taskId = requestedTaskId || this.generateBatchAllocateExpressTaskId(warehouseId); + const existingTask = await this.getBatchAllocateExpressTaskProgress(taskId); + + if (existingTask) { + this.ctx.logger.info('[wave.batchAllocateExpress] 命中幂等任务缓存,直接返回', { + traceId, + taskId, + warehouseId, + waveIds: normalizedWaveIds, + cachedState: String(existingTask.state || '').trim() || 'submitted', + }); + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量分配快递任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchAllocateExpressTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + wave_ids: normalizedWaveIds.join(','), + wave_id_list: normalizedWaveIds, + total_wave_count: normalizedWaveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + trace_id: traceId, + }); + + this.ctx.logger.info('[wave.batchAllocateExpress] 任务提交成功', { + traceId, + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + waveIds: normalizedWaveIds, + }); + + setImmediate(() => { + this.runBatchAllocateExpressTask({ + taskId, + warehouseId, + waveIds: normalizedWaveIds, + trace_id: traceId, + }).catch(error => { + this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务异常', { + traceId, + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量分配快递任务已提交。', + accepted_at: acceptedAt, + }); + } catch (error) { + this.ctx.logger.error('[wave.batchAllocateExpress] 入口处理异常', { + traceId, + requestSnapshot, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + throw error; + } + } + + /** + * 查询批次分配快递号任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchAllocateExpressTaskProgress(data = {}) { + const taskId = this.normalizeBatchAllocateExpressTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchAllocateExpressTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.success_order_count = Number(cachedProgress.success_order_count || 0); + payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); + payload.allocated_order_count = Number(result.allocated_order_count || 0); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + payload.message = String(result.message || '').trim(); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.success_order_count = Number(cachedProgress.success_order_count || 0); + payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 批次分配储位任务提交接口。 + * + * 仅接收当前仓库下波次ID,提交后立即返回 task_id,实际分配由后台异步执行。 + * + * @param {Object} data 请求参数。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 + * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 + * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 + * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 + * @return {Promise} 任务受理结果。 + */ + async batchAllocateStorage(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); + if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { + throw new Error('warehouse_id 参数不合法'); + } + if (requestWarehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + const warehouseId = requestWarehouseId; + const normalizedWaveIds = this.normalizeBatchAllocateStorageWaveIds(data); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchAllocateStorageTaskId(data); + const taskId = requestedTaskId || this.generateBatchAllocateStorageTaskId(warehouseId); + const existingTask = await this.getBatchAllocateStorageTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量分配储位任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchAllocateStorageTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + wave_ids: normalizedWaveIds.join(','), + wave_id_list: normalizedWaveIds, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_wave_count: normalizedWaveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[wave.batchAllocateStorage] 任务提交成功', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + }); + + setImmediate(() => { + this.runBatchAllocateStorageTask({ + taskId, + warehouseId, + waveIds: normalizedWaveIds, + }).catch(error => { + this.ctx.logger.error('[wave.batchAllocateStorage] 后台任务异常', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量分配储位任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批次分配储位任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchAllocateStorageTaskProgress(data = {}) { + const taskId = this.normalizeBatchAllocateStorageTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchAllocateStorageTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + const cachedBusinessId = Number(cachedProgress.business_id || 0); + const cachedBusinessIds = this.normalizeIdsInput(cachedProgress.business_ids); + if (cachedBusinessId > 0) { + payload.business_id = cachedBusinessId; + } + if (cachedBusinessIds.length > 0) { + payload.business_ids = cachedBusinessIds; + } + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.success_order_count = Number(cachedProgress.success_order_count || 0); + payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); + payload.allocated_order_count = Number(result.allocated_order_count || cachedProgress.allocated_order_count || 0); + payload.affected_order_count = Number(result.affected_order_count || cachedProgress.affected_order_count || 0); + payload.allocated_order_ids = this.normalizeIdsInput( + result.allocated_order_ids !== undefined + ? result.allocated_order_ids + : cachedProgress.allocated_order_ids + ); + payload.shortage_order_ids = this.normalizeIdsInput( + result.shortage_order_ids !== undefined + ? result.shortage_order_ids + : cachedProgress.shortage_order_ids + ); + payload.affected_order_ids = this.normalizeIdsInput( + result.affected_order_ids !== undefined + ? result.affected_order_ids + : cachedProgress.affected_order_ids + ); + const successBusinessId = Number(result.business_id || payload.business_id || 0); + const successBusinessIds = this.normalizeIdsInput( + result.business_ids !== undefined + ? result.business_ids + : payload.business_ids + ); + if (successBusinessId > 0) { + payload.business_id = successBusinessId; + } + if (successBusinessIds.length > 0) { + payload.business_ids = successBusinessIds; + } + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + payload.message = String(result.message || '').trim(); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.success_order_count = Number(cachedProgress.success_order_count || 0); + payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_ALLOCATE_STORAGE_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 按仓库提交波次策略快速扫描异步任务。 + * + * 同一仓库同一时刻仅允许一个任务运行,若命中运行中任务则直接复用已有任务。 + * + * @param {number|string} [warehouseId=0] 仓库ID,未传时优先使用上下文仓库ID。 + * @param {Object} [options={}] 提交选项。 + * @param {Array|number|string} [options.orderIds] 可选订单ID数组。 + * @param {boolean} [options.wait=false] 是否等待任务执行完成后再返回最终进度快照。 + * @return {Promise} 任务受理结果(plain object)。 + */ + async submitWaveStrategyQuickScanForWarehouse(warehouseId = 0, options = {}) { + const normalizedWarehouseId = Number(warehouseId || this.getWarehouseId() || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); + const wait = this.normalizeBoolean(normalizedOptions.wait, false); + const forceRescan = this.normalizeBoolean(normalizedOptions.forceRescan, false); + + const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId); + if (runningTask && runningTask.task_id) { + const existingTaskId = String(runningTask.task_id || '').trim(); + const existingProgress = await this.getWaveStrategyQuickScanTaskProgress(existingTaskId); + const existingState = String(existingProgress && existingProgress.state || runningTask.state || 'running').trim() || 'running'; + + if (![ 'success', 'failed' ].includes(existingState)) { + return { + task_id: existingTaskId, + warehouse_id: normalizedWarehouseId, + state: existingState, + message: '已有快速扫描任务在运行中。请稍后重试或查询现有任务进度。', + accepted_at: runningTask.accepted_at || existingProgress && existingProgress.accepted_at || new Date().toISOString(), + }; + } + + await this.clearWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, existingTaskId); + } + + const taskId = this.generateWaveStrategyQuickScanTaskId(normalizedWarehouseId); + const acceptedAt = new Date().toISOString(); + + await this.setWaveStrategyQuickScanTaskProgress(taskId, 'submitted', { + warehouse_id: normalizedWarehouseId, + total_order_count: 0, + processed_order_count: 0, + matched_order_count: 0, + unmatched_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + start_time: null, + end_time: null, + ...(orderIds.length > 0 ? { order_ids: orderIds } : {}), + error: '', + error_code: '', + result: null, + ...(forceRescan ? { force_rescan: true } : {}), + }); + + await this.setWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, taskId, { + state: 'submitted', + accepted_at: acceptedAt, + }); + + if (wait) { + await this.runWaveStrategyQuickScanTask({ + taskId, + warehouseId: normalizedWarehouseId, + ...(orderIds.length > 0 ? { orderIds } : {}), + ...(forceRescan ? { forceRescan } : {}), + }); + + const finalProgress = await this.getWaveStrategyQuickScanTaskProgress(taskId) || {}; + return { + ...finalProgress, + task_id: taskId, + warehouse_id: normalizedWarehouseId, + accepted_at: acceptedAt, + }; + } + + setImmediate(() => { + this.runWaveStrategyQuickScanTask({ + taskId, + warehouseId: normalizedWarehouseId, + ...(orderIds.length > 0 ? { orderIds } : {}), + ...(forceRescan ? { forceRescan } : {}), + }).catch(error => { + this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', { + taskId, + warehouseId: normalizedWarehouseId, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return { + task_id: taskId, + warehouse_id: normalizedWarehouseId, + state: 'submitted', + message: '快速扫描任务已提交。', + accepted_at: acceptedAt, + }; + } + + /** + * 提交波次策略快速扫描异步任务。 + * + * 同一仓库同一时刻仅允许一个任务运行,若命中运行中任务则直接返回已有 task_id。 + * + * @return {Promise} 任务受理结果。 + */ + async waveStrategyQuickScan() { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const submitPayload = await this.submitWaveStrategyQuickScanForWarehouse(contextWarehouseId); + + return this.success('ok', { + status: 'success', + ...submitPayload, + }); + } + + /** + * 查询波次策略快速扫描任务进度。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度信息。 + */ + async waveStrategyQuickScanTaskProgress(data = {}) { + const taskId = this.normalizeWaveStrategyQuickScanTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getWaveStrategyQuickScanTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + return this.success('ok', { + task_id: taskId, + state: String(cachedProgress.state || 'submitted').trim() || 'submitted', + warehouse_id: Number(cachedProgress.warehouse_id || 0), + total_order_count: Number(cachedProgress.total_order_count || 0), + processed_order_count: Number(cachedProgress.processed_order_count || 0), + matched_order_count: Number(cachedProgress.matched_order_count || 0), + unmatched_order_count: Number(cachedProgress.unmatched_order_count || 0), + progress_percent: Number(cachedProgress.progress_percent || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + error_message: String(cachedProgress.error || '').trim(), + error_code: String(cachedProgress.error_code || '').trim(), + duration_ms: Number(cachedProgress.duration_ms || 0), + }); + } + + /** + * 构建快速扫描订单查询条件。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} strategyVersion 当前策略版本号。 + * @param {Array} [orderIds=[]] 限定扫描订单ID数组。 + * @param {boolean} [forceRescan=false] 是否强制全量重扫(忽略版本号条件)。 + * @return {Object} 订单查询 where 条件。 + */ + buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds = [], forceRescan = false) { + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + const where = { + warehouse_id: warehouseId, + step: { [Op.ne]: 0 }, + wave_id: 0, + intercept_status: 'none', + lock_status: 'none', + print_status: { [Op.ne]: 'fin' }, + // 波次策略扫描不扫描 B2B 订单(NULL 视为非 B2B,兼容存量行) + is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + }; + + if (!forceRescan) { + where[Op.or] = [ + { wave_strategy_version: { [Op.ne]: strategyVersion } }, + { wave_strategy_version: { [Op.is]: null } }, + ]; + } + + if (normalizedOrderIds.length > 0) { + where.id = { + [Op.in]: normalizedOrderIds, + }; + } + + return where; + } + + /** + * 获取快速扫描可用策略行(带缓存)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 策略原始行数组。 + */ + async getWaveStrategyQuickScanStrategyRows(warehouseId) { + const strategyModel = this.ctx.model && ( + this.ctx.model.wms_wave_strategy + || this.ctx.model.PickingStrategy + || this.ctx.model.WmsWaveStrategy + ); + if (!strategyModel || typeof strategyModel.findAll !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const strategyCacheKey = `${WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX}${warehouseId}`; + const cachedStrategyRows = this.app && typeof this.app.getCacheAsync === 'function' + ? await this.app.getCacheAsync(strategyCacheKey) + : null; + if (Array.isArray(cachedStrategyRows)) { + return cachedStrategyRows; + } + + const strategyRows = await strategyModel.findAll({ + where: { + warehouse_id: warehouseId, + status: 1, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(strategyCacheKey, strategyRows, WAVE_STRATEGY_LIST_CACHE_TTL_SECONDS); + } + + return strategyRows; + } + + /** + * 获取波次策略快速扫描命中副表模型。 + * + * @return {Object|null} 命中副表模型;若不可用返回 null。 + */ + getWaveStrategyQuickScanMatchModel() { + const modelContext = this.ctx && this.ctx.model; + if (!modelContext || typeof modelContext !== 'object') { + return null; + } + + return modelContext.wms_order_wave_strategy_match + || modelContext.OrderWaveStrategyMatch + || modelContext.WmsOrderWaveStrategyMatch + || null; + } + + /** + * 同步快速扫描命中策略到副表(先删后写)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array|number|string} [orderIds=[]] 扫描范围订单ID。 + * @param {Object} [matchedStrategyIdsByOrder={}] 订单命中策略映射。 + * @return {Promise} 无返回值。 + */ + async syncWaveStrategyQuickScanMatchedStrategies(warehouseId, orderIds = [], matchedStrategyIdsByOrder = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return; + } + + const matchModel = this.getWaveStrategyQuickScanMatchModel(); + if (!matchModel || typeof matchModel.destroy !== 'function' || typeof matchModel.bulkCreate !== 'function') { + throw new Error('波次策略命中副表模型不可用'); + } + + for (let i = 0; i < normalizedOrderIds.length; i += 500) { + const orderChunk = normalizedOrderIds.slice(i, i + 500); + await matchModel.destroy({ + where: { + warehouse_id: normalizedWarehouseId, + order_id: { [Op.in]: orderChunk }, + }, + }); + } + + const normalizedMatchedMap = this.isPlainObject(matchedStrategyIdsByOrder) + ? matchedStrategyIdsByOrder + : {}; + const orderScopeSet = new Set(normalizedOrderIds); + const dedupeSet = new Set(); + const createTime = this.getCurrentDateTime ? this.getCurrentDateTime() : new Date(); + const rows = []; + + Object.keys(normalizedMatchedMap).forEach(orderKey => { + const orderId = Number(orderKey); + if (!Number.isInteger(orderId) || orderId <= 0 || !orderScopeSet.has(orderId)) { + return; + } + + const strategyIds = Array.isArray(normalizedMatchedMap[orderKey]) + ? normalizedMatchedMap[orderKey] + : []; + strategyIds.forEach(strategyIdItem => { + const strategyId = Number(strategyIdItem); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + const dedupeKey = `${orderId}:${strategyId}`; + if (dedupeSet.has(dedupeKey)) { + return; + } + dedupeSet.add(dedupeKey); + + rows.push({ + warehouse_id: normalizedWarehouseId, + order_id: orderId, + strategy_id: strategyId, + create_time: createTime, + }); + }); + }); + + for (let i = 0; i < rows.length; i += 500) { + const rowChunk = rows.slice(i, i + 500); + await matchModel.bulkCreate(rowChunk); + } + } + + /** + * 清理波次策略快速扫描命中副表过期数据。 + * + * @param {Object} [options={}] 清理参数。 + * @param {number|string} [options.expireHours=24] 过期小时数。 + * @param {number|string} [options.warehouseId] 可选仓库ID。 + * @return {Promise} 删除条数。 + */ + async cleanupWaveStrategyQuickScanMatchedStrategies(options = {}) { + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const expireHoursRaw = Number(normalizedOptions.expireHours); + const expireHours = Number.isFinite(expireHoursRaw) && expireHoursRaw > 0 ? expireHoursRaw : 24; + const warehouseId = Number(normalizedOptions.warehouseId || 0); + const expireAt = new Date(Date.now() - Math.floor(expireHours * 60 * 60 * 1000)); + + const matchModel = this.getWaveStrategyQuickScanMatchModel(); + if (!matchModel || typeof matchModel.destroy !== 'function') { + throw new Error('波次策略命中副表模型不可用'); + } + + const where = { + create_time: { + [Op.lt]: expireAt, + }, + }; + + if (Number.isInteger(warehouseId) && warehouseId > 0) { + where.warehouse_id = warehouseId; + } + + const deletedCount = await matchModel.destroy({ where }); + // 清理后重建 + if (Number.isInteger(warehouseId) && warehouseId > 0) { + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(err => { + this.ctx.logger.warn('[wave.cleanupWaveStrategyQuickScanMatchedStrategies] 清理后自动扫描失败: %s', err.message); + }); + }); + } + return Number(deletedCount || 0); + } + + /** + * 按仓库 + 订单ID集合清理波次策略快速扫描命中副表数据。 + * + * @param {number|string} [warehouseId=0] 仓库ID。 + * @param {Array|number|string} [orderIds=[]] 订单ID集合。 + * @return {Promise} 删除条数。 + */ + async cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds(warehouseId = 0, orderIds = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return 0; + } + + const matchModel = this.getWaveStrategyQuickScanMatchModel(); + if (!matchModel || typeof matchModel.destroy !== 'function') { + throw new Error('波次策略命中副表模型不可用'); + } + + let totalDeletedCount = 0; + for (let i = 0; i < normalizedOrderIds.length; i += 500) { + const orderChunk = normalizedOrderIds.slice(i, i + 500); + if (orderChunk.length === 0) { + continue; + } + + const deletedCount = await matchModel.destroy({ + where: { + warehouse_id: normalizedWarehouseId, + order_id: { [Op.in]: orderChunk }, + }, + }); + totalDeletedCount += Number(deletedCount || 0); + } + + return totalDeletedCount; + } + + /** + * 异步处理订单变更后的波次策略快速扫描副表清理与触发。 + * + * @param {number|string} [warehouseId=0] 仓库ID。 + * @param {Array|number|string} [orderIds=[]] 订单ID集合。 + * @param {Object} [options={}] 处理选项。 + * @param {boolean} [options.triggerScan=false] 是否触发快速扫描。 + * @param {string} [options.source=''] 调用来源。 + * @return {void} 无返回值。 + */ + enqueueWaveStrategyQuickScanPostOrderChange(warehouseId = 0, orderIds = [], options = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return; + } + + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const triggerScan = this.normalizeBoolean(normalizedOptions.triggerScan, false); + const source = String(normalizedOptions.source || '').trim(); + + setImmediate(() => { + Promise.resolve() + .then(async () => { + const deletedCount = await this.cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds( + normalizedWarehouseId, + normalizedOrderIds + ); + + if (triggerScan) { + await this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId, { + orderIds: normalizedOrderIds, + }); + } + + this.ctx.logger.info('[wave.enqueueWaveStrategyQuickScanPostOrderChange] 异步处理完成', { + warehouseId: normalizedWarehouseId, + orderCount: normalizedOrderIds.length, + deletedCount, + triggerScan, + source, + }); + }) + .catch(error => { + this.ctx.logger.warn('[wave.enqueueWaveStrategyQuickScanPostOrderChange] 异步处理失败,不影响主流程', { + warehouseId: normalizedWarehouseId, + orderCount: normalizedOrderIds.length, + triggerScan, + source, + error: error && error.message ? error.message : `${error}`, + }); + }); + }); + } + + /** + * 执行快速扫描核心流程。 + * + * @param {Object} [options={}] 执行参数。 + * @param {number} options.warehouseId 仓库ID。 + * @param {number} options.strategyVersion 当前策略版本。 + * @param {Array} [options.orderIds] 可选订单ID数组。 + * @param {string} [options.taskId] 任务ID。 + * @return {Promise} 扫描执行结果。 + */ + async executeWaveStrategyQuickScan(options = {}) { + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const warehouseId = Number(normalizedOptions.warehouseId || 0); + const strategyVersion = this.normalizeWaveStrategyQuickScanVersion(normalizedOptions.strategyVersion); + const taskId = String(normalizedOptions.taskId || '').trim(); + const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); + const forceRescan = this.normalizeBoolean(normalizedOptions.forceRescan, false); + + const strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId); + const strategyList = this.normalizeWaveStrategyQuickScanList(strategyRows); + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderRows = await orderModel.findAll({ + attributes: [ + 'id', + 'store_id', + 'items_count', + 'items_total', + 'items_hash', + 'items', + 'logistics_code', + 'sys_logistics_code', + 'logistics_name', + 'province', + 'sys_platform_code', + 'source_platform_code', + 'has_sn_item', + ], + where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds, forceRescan), + raw: true, + }); + + const scanResult = await runWaveStrategyQuickScanRunner({ + orders: orderRows, + strategyList, + getStructureKey: order => this.getWaveStrategyQuickScanStructureKey(order), + getExpressKey: order => this.getWaveStrategyQuickScanExpressKey(order), + getMatchedStrategyIds: (order, normalizedStrategyList, context) => this.getWaveStrategyQuickScanMatchedStrategyIds( + order, + normalizedStrategyList, + context + ), + isOrderMatched: (order, normalizedStrategyList, context) => this.isWaveStrategyQuickScanOrderMatched( + order, + normalizedStrategyList, + context + ), + onProgress: taskId + ? async payload => { + const totalOrderCount = Number(payload && payload.totalOrderCount || 0); + const processedOrderCount = Number(payload && payload.processedOrderCount || 0); + const matchedOrderCount = Number(payload && payload.matchedOrderCount || 0); + const unmatchedOrderCount = Number(payload && payload.unmatchedOrderCount || 0); + + const progressPercent = totalOrderCount > 0 + ? Math.min(99, Math.round((processedOrderCount / totalOrderCount) * 100)) + : 0; + + await this.setWaveStrategyQuickScanTaskProgress(taskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + processed_order_count: processedOrderCount, + matched_order_count: matchedOrderCount, + unmatched_order_count: unmatchedOrderCount, + progress_percent: progressPercent, + }); + } + : null, + }); + + const matchedOrderIds = this.normalizeIdsInput(scanResult.matchedOrderIds); + const unmatchedOrderIds = this.normalizeIdsInput(scanResult.unmatchedOrderIds); + const matchedStrategyIdsByOrder = this.isPlainObject(scanResult.matchedStrategyIdsByOrder) + ? Object.keys(scanResult.matchedStrategyIdsByOrder).reduce((acc, key) => { + const orderId = Number(key); + if (!Number.isInteger(orderId) || orderId <= 0) { + return acc; + } + + const rawStrategyIds = scanResult.matchedStrategyIdsByOrder[key]; + const normalizedStrategyIds = [ ...new Set((Array.isArray(rawStrategyIds) ? rawStrategyIds : []) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0)) ]; + acc[orderId] = normalizedStrategyIds; + return acc; + }, {}) + : {}; + const scanScopeOrderIds = orderIds.length > 0 + ? orderIds + : [ ...new Set([ ...matchedOrderIds, ...unmatchedOrderIds ]) ]; + + await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, matchedOrderIds, { + wave_strategy_version: strategyVersion, + wave_scan_result: 1, + }); + await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, unmatchedOrderIds, { + wave_strategy_version: strategyVersion, + wave_scan_result: 2, + }); + await this.syncWaveStrategyQuickScanMatchedStrategies( + warehouseId, + scanScopeOrderIds, + matchedStrategyIdsByOrder + ); + + return { + strategyVersion, + totalOrderCount: Number(scanResult.totalOrderCount || 0), + processedOrderCount: Number(scanResult.processedOrderCount || 0), + matchedOrderCount: matchedOrderIds.length, + unmatchedOrderCount: unmatchedOrderIds.length, + matchedOrderIds, + unmatchedOrderIds, + matchedStrategyIdsByOrder, + }; + } + + /** + * 执行波次策略快速扫描后台任务。 + * + * 扫描范围:当前仓库 + step != 0 + wave_id = 0 + wave_strategy_version != 当前策略版本。 + * + * @param {Object} [params={}] 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {Array} [params.orderIds] 订单ID数组(驼峰写法)。 + * @param {Array} [params.order_ids] 订单ID数组(下划线写法)。 + * @param {Array} [params.ids] 订单ID数组(兼容写法)。 + * @return {Promise} 无返回值。 + */ + async runWaveStrategyQuickScanTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getWaveStrategyQuickScanTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + const startTime = Date.now(); + await this.setWaveStrategyQuickScanWarehouseLock(warehouseId, normalizedTaskId, { + state: 'running', + }); + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: 0, + processed_order_count: 0, + matched_order_count: 0, + unmatched_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + error: '', + error_code: '', + result: null, + }); + + try { + const normalizedParams = this.isPlainObject(params) ? params : {}; + const rawOrderIds = normalizedParams.orderIds !== undefined + ? normalizedParams.orderIds + : normalizedParams.order_ids !== undefined + ? normalizedParams.order_ids + : normalizedParams.ids; + const orderIds = this.normalizeIdsInput(rawOrderIds); + const forceRescan = this.normalizeBoolean( + normalizedParams.forceRescan ?? normalizedParams.force_rescan, + false + ); + + const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); + const strategyVersion = this.normalizeWaveStrategyQuickScanVersion( + this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') + ); + + const scanResult = await this.executeWaveStrategyQuickScan({ + warehouseId, + strategyVersion, + orderIds, + taskId: normalizedTaskId, + forceRescan, + }); + + if (scanResult.totalOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: 0, + processed_order_count: 0, + matched_order_count: 0, + unmatched_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + strategy_version: strategyVersion, + duration_ms: durationMs, + message: '未找到需要扫描的订单', + }, + }); + return; + } + + const durationMs = Date.now() - startTime; + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: scanResult.totalOrderCount, + processed_order_count: scanResult.processedOrderCount, + matched_order_count: scanResult.matchedOrderCount, + unmatched_order_count: scanResult.unmatchedOrderCount, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + strategy_version: strategyVersion, + total_order_count: scanResult.totalOrderCount, + processed_order_count: scanResult.processedOrderCount, + matched_order_count: scanResult.matchedOrderCount, + unmatched_order_count: scanResult.unmatchedOrderCount, + matched_order_ids: scanResult.matchedOrderIds, + unmatched_order_ids: scanResult.unmatchedOrderIds, + duration_ms: durationMs, + message: '波次策略快速扫描完成', + }, + }); + } catch (error) { + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_STRATEGY_QUICK_SCAN_FAILED', + }); + } finally { + await this.clearWaveStrategyQuickScanWarehouseLock(warehouseId, normalizedTaskId); + + // 方案 C:扫描完成后检查是否有新订单需要扫描 + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); + const currentVersion = this.normalizeWaveStrategyQuickScanVersion( + this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') + ); + + const pendingCount = await orderModel.count({ + where: { + warehouse_id: warehouseId, + step: { [Op.ne]: 0 }, + wave_id: 0, + intercept_status: 'none', + lock_status: 'none', + print_status: { [Op.ne]: 'fin' }, + is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + [Op.or]: [ + { wave_strategy_version: { [Op.ne]: currentVersion } }, + { wave_strategy_version: { [Op.is]: null } }, + ], + }, + }); + + if (pendingCount > 0) { + this.ctx.logger.info( + '[wave.runWaveStrategyQuickScanTask] 检测到遗漏订单,触发新一轮扫描', + { + warehouseId, + previousTaskId: normalizedTaskId, + pendingCount, + } + ); + + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(error => { + this.ctx.logger.warn( + '[wave.runWaveStrategyQuickScanTask] 触发新一轮扫描失败', + { + warehouseId, + error: error && error.message ? error.message : `${error}`, + } + ); + }); + }); + } + } catch (checkError) { + this.ctx.logger.warn( + '[wave.runWaveStrategyQuickScanTask] 遗漏订单检查失败', + { + warehouseId, + taskId: normalizedTaskId, + error: checkError && checkError.message ? checkError.message : `${checkError}`, + } + ); + } + } + } + + /** + * 批量更新快速扫描结果。 + * + * @param {Object} orderModel 订单模型。 + * @param {Array} orderIds 订单ID数组。 + * @param {Object} updatePayload 更新字段。 + * @return {Promise} 无返回值。 + */ + async batchUpdateWaveStrategyQuickScanOrders(orderModel, orderIds = [], updatePayload = {}) { + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return; + } + + for (let i = 0; i < normalizedOrderIds.length; i += 500) { + const chunkIds = normalizedOrderIds.slice(i, i + 500); + if (chunkIds.length === 0) { + continue; + } + + await orderModel.update(updatePayload, { + where: { + id: { + [Op.in]: chunkIds, + }, + }, + }); + } + } + + /** + * 生成波次策略快速扫描任务ID。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateWaveStrategyQuickScanTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_quick_scan_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化波次策略快速扫描任务ID。 + * + * @param {Object} [data={}] 请求参数。 + * @return {string} 归一化后的任务ID。 + */ + normalizeWaveStrategyQuickScanTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取波次策略快速扫描任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getWaveStrategyQuickScanTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入波次策略快速扫描任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态。 + * @param {Object} payload 进度数据。 + * @return {Promise} 无返回值。 + */ + async setWaveStrategyQuickScanTaskProgress(taskId = '', state = 'submitted', payload = {}) { + const cacheKey = this.getWaveStrategyQuickScanTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const mergedPayload = { + ...(await this.getWaveStrategyQuickScanTaskProgress(taskId) || {}), + ...safePayload, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取波次策略快速扫描任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getWaveStrategyQuickScanTaskProgress(taskId = '') { + const cacheKey = this.getWaveStrategyQuickScanTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 获取波次策略快速扫描仓库锁缓存键。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 缓存键。 + */ + getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return ''; + } + + return `${WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX}${normalizedWarehouseId}`; + } + + /** + * 写入波次策略快速扫描仓库锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {string} taskId 任务ID。 + * @param {Object} [extra={}] 附加字段。 + * @return {Promise} 无返回值。 + */ + async setWaveStrategyQuickScanWarehouseLock(warehouseId = 0, taskId = '', extra = {}) { + const cacheKey = this.getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId); + const normalizedTaskId = String(taskId || '').trim(); + if (!cacheKey || !normalizedTaskId) { + return; + } + + const extraPayload = this.isPlainObject(extra) ? extra : {}; + const lockPayload = { + warehouse_id: Number(warehouseId || 0), + task_id: normalizedTaskId, + state: String(extraPayload.state || 'running').trim() || 'running', + accepted_at: extraPayload.accepted_at || undefined, + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, lockPayload, WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 写入仓库锁缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取波次策略快速扫描仓库锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 锁信息。 + */ + async getWaveStrategyQuickScanWarehouseLock(warehouseId = 0) { + const cacheKey = this.getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 读取仓库锁缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 清理波次策略快速扫描仓库锁。 + * + * 仅当当前锁 owner 与传入 taskId 一致时才删除,防止误删并发任务锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {string} [taskId=''] 当前任务ID。 + * @return {Promise} 无返回值。 + */ + async clearWaveStrategyQuickScanWarehouseLock(warehouseId = 0, taskId = '') { + const cacheKey = this.getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId); + if (!cacheKey) { + return; + } + + try { + const cachedLock = await this.app.getCacheAsync(cacheKey); + const lockTaskId = String(cachedLock && cachedLock.task_id || '').trim(); + const currentTaskId = String(taskId || '').trim(); + if (lockTaskId && currentTaskId && lockTaskId !== currentTaskId) { + return; + } + + if (typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(cacheKey); + } else { + await this.app.setCacheAsync(cacheKey, null, 0); + } + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 清理仓库锁缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 将仓库策略版本号归一化为非负整数。 + * + * @param {*} value 原始版本号。 + * @return {number} 归一化版本号。 + */ + normalizeWaveStrategyQuickScanVersion(value) { + const versionNumber = Number(value); + if (!Number.isFinite(versionNumber)) { + return 0; + } + + const safeVersion = Math.floor(versionNumber); + return Number.isInteger(safeVersion) && safeVersion >= 0 ? safeVersion : 0; + } + + /** + * 归一化快速扫描策略列表。 + * + * @param {*} strategyRows 策略行数组。 + * @return {Array} 标准化策略列表。 + */ + normalizeWaveStrategyQuickScanList(strategyRows) { + const list = Array.isArray(strategyRows) ? strategyRows : []; + return list.map(row => { + const normalizedRow = this.isPlainObject(row) ? row : {}; + const strategyId = Number(normalizedRow.strategy_id || normalizedRow.strategyId || normalizedRow.id || 0); + return { + strategy_id: Number.isInteger(strategyId) && strategyId > 0 ? strategyId : null, + strategy_type: Number(normalizedRow.strategy_type || 0) || 0, + order_min_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_sku), + order_max_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_max_sku), + order_min_qty: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_qty), + order_max_qty: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_max_qty), + min_same_structure: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.min_same_structure), + max_same_structure: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.max_same_structure), + allowed_owners: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_owners), + allowed_expresses: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_expresses, false), + allowed_provinces: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_provinces), + allowed_platforms: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_platforms, false), + require_same_express: this.normalizeWaveStrategyQuickScanBoolean(normalizedRow.require_same_express, false), + allow_cross_owner: this.normalizeWaveStrategyQuickScanBoolean(normalizedRow.allow_cross_owner, true), + }; + }); + } + + /** + * 归一化为可为空的数值。 + * + * @param {*} value 原始数值。 + * @return {number|null} 数值或 null。 + */ + normalizeWaveStrategyQuickScanNumberOrNull(value) { + if (value === undefined || value === null || value === '') { + return null; + } + + const normalizedValue = Number(value); + if (!Number.isFinite(normalizedValue)) { + return null; + } + + return normalizedValue; + } + + /** + * 归一化快速扫描布尔值。 + * + * @param {*} value 原始值。 + * @param {boolean} [defaultValue=false] 默认值。 + * @return {boolean} 布尔值。 + */ + normalizeWaveStrategyQuickScanBoolean(value, defaultValue = false) { + if (typeof value === 'boolean') { + return value; + } + + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalizedValue = String(value).trim().toLowerCase(); + if ([ '1', 'true', 'yes', 'y', 'on' ].includes(normalizedValue)) { + return true; + } + if ([ '0', 'false', 'no', 'n', 'off' ].includes(normalizedValue)) { + return false; + } + + return defaultValue; + } + + /** + * 归一化快速扫描字符串数组。 + * + * 支持数组、JSON 字符串、逗号分隔字符串。 + * + * @param {*} value 原始值。 + * @param {boolean} [toLowerCase=true] 是否转为小写,默认 true 保持向后兼容。 + * @return {Array} 归一化字符串数组(去重)。 + */ + normalizeWaveStrategyQuickScanStringList(value, toLowerCase = true) { + let rawList = []; + + if (Array.isArray(value)) { + rawList = value; + } else if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + rawList = []; + } else if (trimmed.startsWith('[') && trimmed.endsWith(']')) { + try { + const parsed = JSON.parse(trimmed); + rawList = Array.isArray(parsed) ? parsed : []; + } catch (error) { + rawList = trimmed.split(/[,,;|\n\r]+/); + } + } else { + rawList = trimmed.split(/[,,;|\n\r]+/); + } + } else if (value !== undefined && value !== null) { + rawList = [ value ]; + } + + return [ ...new Set(rawList + .map(item => { const s = String(item || '').trim(); return toLowerCase ? s.toLowerCase() : s; }) + .filter(Boolean)) ]; + } + + /** + * 计算订单结构 key(items_hash 优先,其次 items)。 + * + * @param {Object} order 订单记录。 + * @return {string} 结构 key。 + */ + getWaveStrategyQuickScanStructureKey(order = {}) { + const itemsHash = String(order && order.items_hash || '').trim(); + if (itemsHash) { + return itemsHash; + } + + return String(order && order.items || '').trim(); + } + + /** + * 计算订单快递 key。 + * + * 优先级:sys_logistics_code > logistics_code > logistics_name,与 SQL 中 expressExpr 的 COALESCE 口径保持一致。 + * + * @param {Object} order 订单记录。 + * @return {string} 快递 key(去首尾空格后结果,空值返回空字符串)。 + */ + getWaveStrategyQuickScanExpressKey(order = {}) { + const orderObj = order && typeof order === 'object' ? order : {}; + const candidates = [ + String(orderObj.sys_logistics_code || '').trim(), + String(orderObj.logistics_code || '').trim(), + String(orderObj.logistics_name || '').trim(), + ]; + return candidates.find(Boolean) || ''; + } + + /** + * 当 require_same_express=1 时,按快递分组候选订单,仅保留最大快递组的订单。 + * + * 分组 key 使用 getWaveStrategyQuickScanExpressKey(sys_logistics_code > logistics_code > logistics_name), + * 空 key 的订单不参与筛选(直接丢弃)。 + * + * @param {Array} candidateRows 候选订单数组。 + * @return {Array} 按快递筛选后的候选订单数组(仅含最大快递组)。 + */ + filterCandidateOrdersByRequireSameExpress(candidateRows = []) { + const rows = Array.isArray(candidateRows) ? candidateRows : []; + if (rows.length === 0) { + return []; + } + + const expressGroups = new Map(); + for (const row of rows) { + const expressKey = this.getWaveStrategyQuickScanExpressKey(row); + if (!expressKey) { + continue; + } + if (!expressGroups.has(expressKey)) { + expressGroups.set(expressKey, []); + } + expressGroups.get(expressKey).push(row); + } + + if (expressGroups.size === 0) { + return []; + } + + let maxGroup = []; + for (const groupOrders of expressGroups.values()) { + if (groupOrders.length > maxGroup.length) { + maxGroup = groupOrders; + } + } + + return maxGroup; + } + + /** + * 判断订单是否命中任一快速扫描策略。 + * + * @param {Object} order 订单记录。 + * @param {Array} strategyList 策略列表。 + * @param {Object} context 统计上下文。 + * @return {boolean} 是否命中。 + */ + isWaveStrategyQuickScanOrderMatched(order = {}, strategyList = [], context = {}) { + const matchedStrategyIds = this.getWaveStrategyQuickScanMatchedStrategyIds(order, strategyList, context); + return matchedStrategyIds.length > 0; + } + + /** + * 获取订单命中的快速扫描策略ID列表。 + * + * 全量遍历 strategyList,不提前返回,收集所有命中策略的 strategy_id。 + * + * @param {Object} order 订单记录。 + * @param {Array} strategyList 策略列表。 + * @param {Object} [context={}] 统计上下文。 + * @return {Array} 去重后的正整数策略ID列表。 + */ + getWaveStrategyQuickScanMatchedStrategyIds(order, strategyList, context = {}) { + const list = Array.isArray(strategyList) ? strategyList : []; + if (list.length === 0) { + return []; + } + + const matchedStrategyIds = []; + for (const strategy of list) { + if (!this.isWaveStrategyQuickScanOrderMatchedSingleStrategy(order, strategy, context)) { + continue; + } + + const strategyId = Number(strategy && strategy.strategy_id || 0); + if (Number.isInteger(strategyId) && strategyId > 0) { + matchedStrategyIds.push(strategyId); + } + } + + return [ ...new Set(matchedStrategyIds) ]; + } + + /** + * 判断订单是否命中单条快速扫描策略。 + * + * @param {Object} order 订单记录。 + * @param {Object} strategy 策略配置。 + * @param {Object} context 统计上下文。 + * @return {boolean} 是否命中。 + */ + isWaveStrategyQuickScanOrderMatchedSingleStrategy(order = {}, strategy = {}, context = {}) { + const normalizedOrder = this.isPlainObject(order) ? order : {}; + const normalizedStrategy = this.isPlainObject(strategy) ? strategy : {}; + const structureStoreSetMap = context && context.structureStoreSetMap instanceof Map ? context.structureStoreSetMap : new Map(); + const structurePrimaryOwnerMap = context && context.structurePrimaryOwnerMap instanceof Map + ? context.structurePrimaryOwnerMap + : null; + + const structureKey = this.getWaveStrategyQuickScanStructureKey(normalizedOrder); + if (!structureKey) { + return false; + } + + // 策略类型与订单 SN 属性互斥:SN 策略(3)只命中 SN 订单;散单/团购策略(1/2)不命中 SN 订单 + const strategyType = Number(normalizedStrategy.strategy_type || 0); + const isSnOrder = String(normalizedOrder.has_sn_item || '').trim().toUpperCase() === 'Y'; + if (strategyType === 3 ? !isSnOrder : isSnOrder) { + return false; + } + + const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); + + if (normalizedStrategy.allow_cross_owner === false) { + if (structurePrimaryOwnerMap instanceof Map) { + const primaryOwnerStoreId = String(structurePrimaryOwnerMap.get(structureKey) || '').trim().toLowerCase(); + if (!primaryOwnerStoreId || storeId !== primaryOwnerStoreId) { + return false; + } + } else { + const ownerSet = structureStoreSetMap.get(structureKey); + if (ownerSet instanceof Set && ownerSet.size > 1) { + return false; + } + } + } + + const itemsCount = Number(normalizedOrder.items_count || 0); + const itemsTotal = Number(normalizedOrder.items_total || 0); + + if (!this.isWaveStrategyQuickScanValueInRange(itemsCount, normalizedStrategy.order_min_sku, normalizedStrategy.order_max_sku)) { + return false; + } + if (!this.isWaveStrategyQuickScanValueInRange(itemsTotal, normalizedStrategy.order_min_qty, normalizedStrategy.order_max_qty)) { + return false; + } + + if (normalizedStrategy.allowed_owners.length > 0 && !normalizedStrategy.allowed_owners.includes(storeId)) { + return false; + } + + const expressCandidates = [ + String(normalizedOrder.sys_logistics_code || '').trim().toLowerCase(), + String(normalizedOrder.logistics_code || '').trim().toLowerCase(), + String(normalizedOrder.logistics_name || '').trim().toLowerCase(), + ].filter(Boolean); + if (normalizedStrategy.allowed_expresses.length > 0) { + const allowedLower = (normalizedStrategy.allowed_expresses || []).map(s => String(s).toLowerCase()); + const hitExpress = expressCandidates.some(code => allowedLower.includes(code)); + if (!hitExpress) { + return false; + } + } + + const province = String(normalizedOrder.province || '').trim().toLowerCase(); + if (normalizedStrategy.allowed_provinces.length > 0 && !normalizedStrategy.allowed_provinces.includes(province)) { + return false; + } + + const platformCandidates = [ + String(normalizedOrder.sys_platform_code || '').trim().toLowerCase(), + String(normalizedOrder.source_platform_code || '').trim().toLowerCase(), + ].filter(Boolean); + if (normalizedStrategy.allowed_platforms.length > 0) { + const allowedPlatformsLower = normalizedStrategy.allowed_platforms.map(s => String(s).toLowerCase()); + const hitPlatform = platformCandidates.some(code => allowedPlatformsLower.includes(code)); + if (!hitPlatform) { + return false; + } + } + + return true; + } + + /** + * 判断值是否命中区间。 + * + * @param {number} value 待判断值。 + * @param {number|null} min 最小值。 + * @param {number|null} max 最大值。 + * @return {boolean} 是否命中。 + */ + isWaveStrategyQuickScanValueInRange(value, min, max) { + const normalizedValue = Number(value); + if (!Number.isFinite(normalizedValue)) { + return false; + } + + const hasMin = Number.isFinite(Number(min)); + const hasMax = Number.isFinite(Number(max)); + if (hasMin && normalizedValue < Number(min)) { + return false; + } + if (hasMax && normalizedValue > Number(max)) { + return false; + } + + return true; + } + + /** + * 过滤 singleFetchByIds 中属于团购候选结构的订单。 + * + * 规则:同结构(items_hash/items)待处理订单数达到最小团购阈值时,视为团购候选。 + * 为避免误抓,singleFetchByIds 默认排除这些订单,仅允许显式团购入口处理。 + * + * @param {Object} orderModel 订单模型。 + * @param {number} warehouseId 仓库ID。 + * @param {Array} orderRows 待过滤订单行。 + * @return {Promise} 需排除的订单ID集合。 + */ + async resolveGroupCandidateOrderIdsForSingleFetch(orderModel, warehouseId, orderRows = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedRows = Array.isArray(orderRows) + ? orderRows.filter(row => Number.isInteger(Number(row && row.id || 0)) && Number(row && row.id || 0) > 0) + : []; + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedRows.length === 0) { + return []; + } + + const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(normalizedWarehouseId); + if (!Number.isInteger(Number(minGroupOrderFetchQuantity)) || Number(minGroupOrderFetchQuantity) <= 1) { + return []; + } + + const itemHashValues = [ ...new Set(normalizedRows + .map(row => String(row && row.items_hash || '').trim()) + .filter(Boolean)) ]; + const itemValues = [ ...new Set(normalizedRows + .map(row => String(row && row.items || '').trim()) + .filter(Boolean)) ]; + if (itemHashValues.length === 0 && itemValues.length === 0) { + return []; + } + + const candidateWhereList = []; + if (itemHashValues.length > 0) { + candidateWhereList.push({ + items_hash: { [Op.in]: itemHashValues }, + }); + } + if (itemValues.length > 0) { + candidateWhereList.push({ + items: { [Op.in]: itemValues }, + }); + } + if (candidateWhereList.length === 0) { + return []; + } + + const candidateRows = await orderModel.findAll({ + attributes: [ 'id', 'items_hash', 'items', 'logistics_name' ], + where: { + wave_id: 0, + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + // 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行) + is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + [Op.or]: candidateWhereList, + }, + raw: true, + }); + + const buildItemKey = row => { + const itemHash = String(row && row.items_hash || '').trim(); + const itemText = String(row && row.items || '').trim(); + if (itemHash) { + return `items_hash:${itemHash}`; + } + if (itemText) { + return `items:${itemText}`; + } + return ''; + }; + + const itemCountMap = new Map(); + for (const row of Array.isArray(candidateRows) ? candidateRows : []) { + const itemKey = buildItemKey(row); + if (!itemKey) { + continue; + } + itemCountMap.set(itemKey, Number(itemCountMap.get(itemKey) || 0) + 1); + } + + const excludedOrderIds = []; + const normalizedThreshold = Number(minGroupOrderFetchQuantity); + for (const row of normalizedRows) { + const orderId = Number(row && row.id || 0); + const itemKey = buildItemKey(row); + if (!itemKey) { + continue; + } + + const itemGroupCount = Number(itemCountMap.get(itemKey) || 0); + if (itemGroupCount >= normalizedThreshold) { + excludedOrderIds.push(orderId); + } + } + + return [ ...new Set(excludedOrderIds) ].sort((a, b) => a - b); + } + + /** + * 按订单ID集合抓取到一个散单波次。 + * + * 规则: + * 1. 仅处理当前仓库上下文订单; + * 2. 传入 ids 中已存在波次(wave_id>0)的订单会被排除; + * 3. 不区分快递,所有可抓取订单统一写入同一个新波次; + * 4. 除已在波次中的订单外,其余传入且存在的订单均可抓取; + * 5. SN(序列号管理)订单允许按订单ID显式抓取散单(不在散单/团购策略候选中出现,但手工按订单抓取不受限); + * 6. 成功抓取后批量写订单操作日志。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} data.ids 订单ID集合(优先)。 + * @param {Array|number|string} data.order_ids 订单ID集合别名。 + * @param {Array|number|string} data.orderIds 订单ID集合别名。 + * @return {Promise} 抓取结果。 + */ + async singleFetchByIds(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const logOperator = this.getOrderLogOperator() || {}; + const grabOperatorId = Number(logOperator.id || 0) > 0 ? Number(logOperator.id) : null; + const grabOperator = String(logOperator.name || '').trim() || null; + const rawIds = data && ( + data.ids !== undefined + ? data.ids + : data.order_ids !== undefined + ? data.order_ids + : data.orderIds + ); + const normalizedIds = this.normalizeIdsInput(rawIds); + if (normalizedIds.length === 0) { + throw new Error('ids 参数不能为空或格式错误'); + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + + const transaction = await this.ctx.model.transaction(); + + try { + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name', 'intercept_status', 'lock_status', 'is_b2b' ], + where: { + id: { [Op.in]: normalizedIds }, + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : []; + const foundOrderIds = [ ...new Set(normalizedOrderRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const existingWaveRows = normalizedOrderRows + .filter(row => Number(row && row.wave_id || 0) > 0); + const excludedExistingWaveOrderIds = [ ...new Set(existingWaveRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + const excludedInterceptedOrderIds = [ ...new Set(normalizedOrderRows + .filter(row => this.isInterceptedOrderStatus(row && row.intercept_status)) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + const excludedLockedOrderIds = [ ...new Set(normalizedOrderRows + .filter(row => this.isLockedOrderStatus(row && row.lock_status)) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + // B2B 订单不参与波次抓取(NULL 视为非 B2B,兼容存量行) + const excludedB2bOrderIds = [ ...new Set(normalizedOrderRows + .filter(row => String(row && row.is_b2b || '').trim() === 'Y') + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + // SN(序列号管理)订单允许按订单ID显式抓取散单:SN 策略只是「不自动出现在散单策略候选」, + // 手工按订单抓取时不受限(manual_ids 波次在拣货侧固定走先拣后分 pick_mode=3,与 SN 策略一致), + // 因此这里不再排除 SN 订单,excluded_sn_order_ids 保留在响应中但恒为空数组。 + const excludedSnOrderIds = []; + + const fetchableRows = normalizedOrderRows.filter(row => { + const orderId = Number(row && row.id || 0); + const waveId = Number(row && row.wave_id || 0); + + if (!Number.isInteger(orderId) || orderId <= 0) { + return false; + } + + if (waveId > 0) { + return false; + } + + // 拦截流程中的订单不允许分配波次 + if (this.isInterceptedOrderStatus(row && row.intercept_status)) { + return false; + } + + // 已锁定的订单不允许抓取波次 + if (this.isLockedOrderStatus(row && row.lock_status)) { + return false; + } + + // B2B 订单不允许抓取波次 + if (String(row && row.is_b2b || '').trim() === 'Y') { + return false; + } + + return true; + }); + + const fetchableOrderIds = [ ...new Set(fetchableRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + const notFoundOrderIds = normalizedIds.filter(id => !foundOrderIds.includes(id)); + const skippedOrderIds = normalizedIds.filter(id => !fetchableOrderIds.includes(id)); + + if (fetchableOrderIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + wave_id: 0, + wave_no: '', + fetched_order_ids: [], + fetched_order_count: 0, + excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, + excluded_intercepted_order_ids: excludedInterceptedOrderIds, + excluded_locked_order_ids: excludedLockedOrderIds, + excluded_b2b_order_ids: excludedB2bOrderIds, + excluded_sn_order_ids: excludedSnOrderIds, + skipped_order_ids: skippedOrderIds, + not_found_order_ids: notFoundOrderIds, + }); + } + + const singleFetchByIdsWavePrefix = await this.getSingleFetchByIdsWavePrefix(warehouseId); + + const { waveId, waveNo } = await this.createWaveBatchReady({ + warehouseId, + totalOrders: fetchableOrderIds.length, + itemDetailMachine: `manual_single_ids_${Date.now()}`, + itemPartType: 'manual_ids', + itemPart: `ids_${fetchableOrderIds.length}`, + waveType: 2, + distinguishExpress: false, + logisticsName: '', + itemSnapshotKey: 'manual_single_ids', + wavePrefix: singleFetchByIdsWavePrefix, + transaction, + }); + + await orderModel.update({ + wave_id: waveId, + wave_no: waveNo, + wave_scope: this.resolveWaveScopeByWaveMeta(2, 0), + grab_operator_id: grabOperatorId, + grab_operator: grabOperator, + }, { + where: { + id: { [Op.in]: fetchableOrderIds }, + wave_id: 0, + }, + transaction, + }); + + const grabbedRows = await orderModel.findAll({ + where: { + id: { [Op.in]: fetchableOrderIds }, + wave_id: waveId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + const grabbedOrderIds = [ ...new Set((Array.isArray(grabbedRows) ? grabbedRows : []) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + + if (grabbedOrderIds.length <= 0) { + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE wave_id = :waveId + `, { + replacements: { waveId }, + transaction, + }); + + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + wave_id: 0, + wave_no: '', + fetched_order_ids: [], + fetched_order_count: 0, + excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, + excluded_sn_order_ids: excludedSnOrderIds, + skipped_order_ids: skippedOrderIds, + not_found_order_ids: notFoundOrderIds, + }); + } + + if (grabbedOrderIds.length !== fetchableOrderIds.length) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :totalOrders, + update_time = NOW() + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + totalOrders: grabbedOrderIds.length, + }, + transaction, + }); + } + + await this.rebuildOrderWaveIndex({ + warehouseId, + waveId, + orderIds: grabbedOrderIds, + orderModel, + transaction, + }); + + await transaction.commit(); + + await this.batchCreateOrderOperationLogs(grabbedOrderIds.map(orderId => ({ + orderId, + operationCode: 'ORDER_WAVE_ASSIGN', + message: `订单被分配到波次 ${waveNo}`, + })), { + warehouseId, + scene: 'singleFetchByIds', + }); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, grabbedOrderIds, { + triggerScan: false, + source: 'singleFetchByIds', + }); + + return this.success('ok', { + ids: normalizedIds, + wave_id: waveId, + wave_no: waveNo, + fetched_order_ids: grabbedOrderIds, + fetched_order_count: grabbedOrderIds.length, + excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, + excluded_intercepted_order_ids: excludedInterceptedOrderIds, + excluded_locked_order_ids: excludedLockedOrderIds, + excluded_b2b_order_ids: excludedB2bOrderIds, + excluded_sn_order_ids: excludedSnOrderIds, + skipped_order_ids: skippedOrderIds, + not_found_order_ids: notFoundOrderIds, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 批量将订单从波次中移出。 + * + * 仅处理当前仓库待处理订单中 step in [1,2,3] 且已分配波次(wave_id>0)的订单。 + * 全流程使用事务,确保订单更新与波次统计回写一致。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} data.ids 订单ID集合(优先)。 + * @param {Array|number|string} data.order_ids 订单ID集合别名。 + * @param {Array|number|string} data.orderIds 订单ID集合别名。 + * @param {Array|number|string} data.order_id 订单ID集合别名。 + * @param {Array|number|string} data.orderId 订单ID集合别名。 + * @param {Array|number|string} data.id 订单ID集合别名。 + * @return {Promise} 批量移出结果。 + */ + /** + * 在调用方事务内把订单从波次中摘除。 + * + * 处理内容:清空订单波次字段(wave_id/wave_no/wave_scope/wave_strategy_version/wave_scan_result)、 + * 重建受影响波次的订单索引(wave_index 重排)、回写 wms_wave_batch 统计(空波次置 wave_status=-1)。 + * 供 batchRemoveOrders、订单转 B2B 等「订单离开波次」场景复用;活动拣货任务校验由调用方负责。 + * + * @param {Object} params 摘除参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 待摘除订单ID集合。 + * @param {Object} params.orderModel 订单 current 分表模型。 + * @param {Object} params.transaction 事务对象(必填)。 + * @return {Promise} { removed_order_ids, affected_wave_ids, updated_wave_ids, + * emptied_wave_ids, wave_no_map } 摘除结果。 + */ + async detachOrdersFromWavesInTransaction({ warehouseId, orderIds, orderModel, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + const emptyResult = { + removed_order_ids: [], + affected_wave_ids: [], + updated_wave_ids: [], + emptied_wave_ids: [], + wave_no_map: new Map(), + }; + + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 + || normalizedOrderIds.length === 0) { + return emptyResult; + } + + if (!transaction) { + throw new Error('detachOrdersFromWavesInTransaction 必须在事务内调用'); + } + + const currentOrderModel = orderModel || await this.getOrderModel('pendingOrder', normalizedWarehouseId); + if (!currentOrderModel || typeof currentOrderModel.findAll !== 'function') { + return emptyResult; + } + + const waveRows = await currentOrderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no' ], + where: { + id: { [Op.in]: normalizedOrderIds }, + wave_id: { [Op.gt]: 0 }, + }, + raw: true, + transaction, + }); + + const removableRows = Array.isArray(waveRows) ? waveRows : []; + const removableOrderIds = [ ...new Set(removableRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const affectedWaveIds = [ ...new Set(removableRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + const waveNoMap = new Map(removableRows + .map(row => [ Number(row && row.id || 0), String(row && row.wave_no || '').trim() ]) + .filter(item => item[0] > 0)); + + if (removableOrderIds.length === 0 || affectedWaveIds.length === 0) { + return emptyResult; + } + + await currentOrderModel.update({ + wave_id: 0, + wave_no: '', + wave_scope: 0, + wave_strategy_version: 0, + wave_scan_result: 0, + }, { + where: { + id: { [Op.in]: removableOrderIds }, + }, + transaction, + }); + + // 重建受影响波次的订单索引(wave_index 重新排序),并获取各波次剩余订单数量 + const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({ + warehouseId: normalizedWarehouseId, + waveIds: affectedWaveIds, + orderModel: currentOrderModel, + transaction, + }); + + const updatedWaveIds = []; + const emptiedWaveIds = []; + + for (const waveId of affectedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + if (remainingCount > 0) { + updatedWaveIds.push(waveId); + } else { + emptiedWaveIds.push(waveId); + } + } + + for (const waveId of updatedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :remainingCount, + processed_orders = LEAST(processed_orders, :remainingCount), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `, { + replacements: { + warehouseId: normalizedWarehouseId, + waveId, + remainingCount, + }, + transaction, + }); + } + + if (emptiedWaveIds.length > 0) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = 0, + processed_orders = 0, + wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + warehouseId: normalizedWarehouseId, + waveIds: emptiedWaveIds, + }, + transaction, + }); + } + + return { + removed_order_ids: removableOrderIds, + affected_wave_ids: affectedWaveIds, + updated_wave_ids: updatedWaveIds, + emptied_wave_ids: emptiedWaveIds, + wave_no_map: waveNoMap, + }; + } + + async batchRemoveOrders(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const rawIds = data && ( + data.ids !== undefined ? data.ids + : data.order_ids !== undefined ? data.order_ids + : data.orderIds !== undefined ? data.orderIds + : data.order_id !== undefined ? data.order_id + : data.orderId !== undefined ? data.orderId + : data.id + ); + const normalizedIds = this.normalizeIdsInput(rawIds); + if (normalizedIds.length === 0) { + throw new Error('ids 参数不能为空或格式错误'); + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + + const removableRowsForCheck = await orderModel.findAll({ + attributes: [ 'wave_id' ], + where: { + id: { [Op.in]: normalizedIds }, + step: { [Op.in]: [ 1, 2, 3 ] }, + wave_id: { [Op.gt]: 0 }, + }, + raw: true, + }); + const affectedWaveIdsForCheck = [ ...new Set((Array.isArray(removableRowsForCheck) ? removableRowsForCheck : []) + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + if (affectedWaveIdsForCheck.length > 0) { + const activeTaskWaves = await this.ctx.model.query( + `SELECT ptw.wave_id + FROM wms_wave_pick_task_wave ptw + INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id + WHERE ptw.wave_id IN (:waveIds) + AND pt.status IN (0, 1) + LIMIT 1`, + { + replacements: { waveIds: affectedWaveIdsForCheck }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + if (activeTaskWaves.length > 0) { + throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); + } + } + + const transaction = await this.ctx.model.transaction(); + + try { + const removableRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no' ], + where: { + id: { [Op.in]: normalizedIds }, + step: { [Op.in]: [ 1, 2, 3 ] }, + wave_id: { [Op.gt]: 0 }, + }, + raw: true, + transaction, + }); + + const removableOrderRows = Array.isArray(removableRows) ? removableRows : []; + const removablePendingIds = [ ...new Set(removableOrderRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const removedOrderIds = [ ...new Set(removablePendingIds) ]; + const affectedWaveIds = [ ...new Set(removableOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + const removeOrderLogItems = removableOrderRows + .map(row => { + const orderId = Number(row && row.id || 0); + const waveNo = String(row && row.wave_no || '').trim() || '未知波次'; + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + orderId, + operationCode: 'ORDER_WAVE_REMOVE', + message: `订单从波次 ${waveNo} 中移除`, + }; + }) + .filter(Boolean); + + if (removablePendingIds.length === 0 || affectedWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + removed_order_ids: [], + removed_order_count: 0, + affected_wave_ids: [], + updated_wave_ids: [], + emptied_wave_ids: [], + }); + } + + const detachResult = await this.detachOrdersFromWavesInTransaction({ + warehouseId, + orderIds: removablePendingIds, + orderModel, + transaction, + }); + const updatedOrderCount = detachResult.removed_order_ids.length; + const updatedWaveIds = detachResult.updated_wave_ids; + const emptiedWaveIds = detachResult.emptied_wave_ids; + + await transaction.commit(); + await this.batchCreateOrderOperationLogs(removeOrderLogItems, { + warehouseId, + scene: 'batchRemoveOrders', + }); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { + triggerScan: true, + source: 'batchRemoveOrders', + }); + + return this.success('ok', { + ids: normalizedIds, + removed_order_ids: removedOrderIds, + removed_order_count: Number.isInteger(updatedOrderCount) && updatedOrderCount > 0 ? updatedOrderCount : 0, + affected_wave_ids: affectedWaveIds, + updated_wave_ids: updatedWaveIds, + emptied_wave_ids: emptiedWaveIds, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 强制重排指定波次的订单索引(wave_index)。 + * + * 用于修正历史数据中因各种原因导致的 wave_index 不连续问题。 + * 内部调用 replaceOrderWaveIndexByWaveIds 完成索引重建,并同步更新 wms_wave_batch.total_orders。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @return {Promise} 重排结果,含各波次重排前后的订单数量。 + */ + async resortWaveIndex(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const rawWaveIds = data && ( + data.wave_ids !== undefined ? data.wave_ids + : data.waveIds !== undefined ? data.waveIds + : data.wave_id !== undefined ? data.wave_id + : data.waveId !== undefined ? data.waveId + : null + ); + const normalizedWaveIds = this.normalizeIdsInput(rawWaveIds); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const transaction = await this.ctx.model.transaction(); + + try { + // 重排前记录各波次每单的 wave_index,用于对比是否实际发生重排 + const beforeRows = await this.ctx.model.query(` + SELECT wave_id, order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + ORDER BY wave_id, order_id + `, { + replacements: { warehouseId, waveIds: normalizedWaveIds }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const beforeIndexMap = new Map(); // waveId -> Map(orderId -> wave_index) + const beforeCountMap = new Map(); + for (const row of (Array.isArray(beforeRows) ? beforeRows : [])) { + const waveId = Number(row && row.wave_id || 0); + const orderId = Number(row && row.order_id || 0); + const waveIndex = Number(row && row.wave_index || 0); + if (!Number.isInteger(waveId) || waveId <= 0) continue; + if (!beforeIndexMap.has(waveId)) beforeIndexMap.set(waveId, new Map()); + if (Number.isInteger(orderId) && orderId > 0) { + beforeIndexMap.get(waveId).set(orderId, Number.isInteger(waveIndex) ? waveIndex : 0); + } + beforeCountMap.set(waveId, (beforeCountMap.get(waveId) || 0) + 1); + } + + // 重建波次索引(内部先删后插,wave_index 从 1 开始连续编号) + const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: normalizedWaveIds, + orderModel, + transaction, + }); + + // 重排后查询各波次每单的 wave_index,用于对比是否实际发生变化 + const afterRows = await this.ctx.model.query(` + SELECT wave_id, order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + ORDER BY wave_id, order_id + `, { + replacements: { warehouseId, waveIds: normalizedWaveIds }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const afterIndexMap = new Map(); // waveId -> Map(orderId -> wave_index) + for (const row of (Array.isArray(afterRows) ? afterRows : [])) { + const waveId = Number(row && row.wave_id || 0); + const orderId = Number(row && row.order_id || 0); + const waveIndex = Number(row && row.wave_index || 0); + if (!Number.isInteger(waveId) || waveId <= 0) continue; + if (!afterIndexMap.has(waveId)) afterIndexMap.set(waveId, new Map()); + if (Number.isInteger(orderId) && orderId > 0) { + afterIndexMap.get(waveId).set(orderId, Number.isInteger(waveIndex) ? waveIndex : 0); + } + } + + // 同步更新 wms_wave_batch.total_orders + const waveDetails = []; + for (const waveId of normalizedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + const beforeCount = Number(beforeCountMap.get(waveId) || 0); + + if (remainingCount > 0) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :remainingCount, + processed_orders = LEAST(processed_orders, :remainingCount), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `, { + replacements: { warehouseId, waveId, remainingCount }, + transaction, + }); + } else { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = 0, + processed_orders = 0, + wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `, { + replacements: { warehouseId, waveId }, + transaction, + }); + } + + // 对比每单重排前后的 wave_index,判断是否实际发生变化 + const beforeOrderMap = beforeIndexMap.get(waveId) || new Map(); + const afterOrderMap = afterIndexMap.get(waveId) || new Map(); + const allOrderIds = new Set([ ...beforeOrderMap.keys(), ...afterOrderMap.keys() ]); + let hasChanged = beforeCount !== remainingCount; + if (!hasChanged) { + for (const oid of allOrderIds) { + if (beforeOrderMap.get(oid) !== afterOrderMap.get(oid)) { + hasChanged = true; + break; + } + } + } + + waveDetails.push({ + wave_id: waveId, + before_index_count: beforeCount, + after_index_count: remainingCount, + reordered: hasChanged, + }); + } + + await transaction.commit(); + + const totalBefore = waveDetails.reduce((sum, w) => sum + w.before_index_count, 0); + const totalAfter = waveDetails.reduce((sum, w) => sum + w.after_index_count, 0); + + return this.success('ok', { + warehouse_id: warehouseId, + wave_count: normalizedWaveIds.length, + total_before_index_count: totalBefore, + total_after_index_count: totalAfter, + waves: waveDetails, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 批量移除异常订单任务提交接口。 + * + * 仅处理当前登录仓库下命中波次中的异常订单,提交后异步执行。 + * 异常判定与订单模块待处理异常定义保持一致:仅 step=3。 + * 实际移除动作复用既有 batchRemoveOrders 流水线,不重复实现解绑逻辑。 + * + * @param {Object} data 请求参数。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 + * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 + * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 + * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 + * @return {Promise} 任务提交结果。 + */ + async batchRemoveExceptionOrders(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); + if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { + throw new Error('warehouse_id 参数不合法'); + } + if (requestWarehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + const warehouseId = requestWarehouseId; + const normalizedWaveIds = this.normalizeBatchRemoveExceptionOrdersWaveIds(data); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchRemoveExceptionOrdersTaskId(data); + const taskId = requestedTaskId || this.generateBatchRemoveExceptionOrdersTaskId(warehouseId); + const existingTask = await this.getBatchRemoveExceptionOrdersTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量移除异常订单任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchRemoveExceptionOrdersTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + wave_ids: normalizedWaveIds.join(','), + wave_id_list: normalizedWaveIds, + total_wave_count: normalizedWaveIds.length, + processed_wave_count: 0, + total_order_count: 0, + processed_order_count: 0, + removed_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[wave.batchRemoveExceptionOrders] 任务提交成功', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + }); + + setImmediate(() => { + this.runBatchRemoveExceptionOrdersTask({ + taskId, + warehouseId, + waveIds: normalizedWaveIds, + }).catch(error => { + this.ctx.logger.error('[wave.batchRemoveExceptionOrders] 后台任务异常', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量移除异常订单任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量移除异常订单任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchRemoveExceptionOrdersTaskProgress(data = {}) { + const taskId = this.normalizeBatchRemoveExceptionOrdersTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchRemoveExceptionOrdersTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.removed_order_count = Number(cachedProgress.removed_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); + payload.total_order_count = Number(result.total_order_count || 0); + payload.processed_order_count = Number(result.processed_order_count || 0); + payload.removed_order_count = Number(result.removed_order_count || 0); + payload.removed_order_ids = Array.isArray(result.removed_order_ids) ? result.removed_order_ids : []; + payload.affected_wave_ids = Array.isArray(result.affected_wave_ids) ? result.affected_wave_ids : []; + payload.updated_wave_ids = Array.isArray(result.updated_wave_ids) ? result.updated_wave_ids : []; + payload.emptied_wave_ids = Array.isArray(result.emptied_wave_ids) ? result.emptied_wave_ids : []; + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.removed_order_count = Number(cachedProgress.removed_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_REMOVE_EXCEPTION_ORDERS_FAILED'; + payload.failed_wave_id = Number(cachedProgress.failed_wave_id || 0); + payload.failed_wave_no = String(cachedProgress.failed_wave_no || '').trim(); + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量取消任务ID。 + * + * 格式:wave_cancel_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchCancelTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_cancel_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量取消任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchCancelTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 生成可追踪的批量移除异常订单任务ID。 + * + * 格式:wave_remove_exception_orders_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchRemoveExceptionOrdersTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_remove_exception_orders_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量移除异常订单任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchRemoveExceptionOrdersTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量移除异常订单的波次ID参数。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的波次ID数组。 + */ + normalizeBatchRemoveExceptionOrdersWaveIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawWaveIds = normalizedData.wave_ids !== undefined + ? normalizedData.wave_ids + : normalizedData.waveIds !== undefined + ? normalizedData.waveIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : normalizedData.wave_id !== undefined + ? normalizedData.wave_id + : normalizedData.waveId; + + return this.normalizeIdsInput(rawWaveIds); + } + + /** + * 获取批量移除异常订单任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchRemoveExceptionOrdersTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量移除异常订单任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} status 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchRemoveExceptionOrdersTaskProgress(taskId = '', status = 'submitted', data = {}) { + const cacheKey = this.getBatchRemoveExceptionOrdersTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchRemoveExceptionOrdersTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.batchRemoveExceptionOrders] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取批量移除异常订单任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchRemoveExceptionOrdersTaskProgress(taskId = '') { + const cacheKey = this.getBatchRemoveExceptionOrdersTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.batchRemoveExceptionOrders] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 判断订单是否属于异常可移除范围。 + * + * 与订单模块“待处理异常”语义保持一致:仅 step=3。 + * + * @param {Object} row 订单行数据。 + * @return {boolean} 是否为异常可移除订单。 + */ + isExceptionRemovableOrder(row = {}) { + const step = Number(row && row.step || 0); + return step === 3; + } + + /** + * 执行批量移除异常订单后台任务。 + * + * 先按波次聚合异常订单,再复用 batchRemoveOrders 流水线执行解绑与波次统计回写。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchRemoveExceptionOrdersTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const waveIds = this.normalizeIdsInput( + cachedTask && cachedTask.wave_ids !== undefined + ? cachedTask.wave_ids + : params && params.waveIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (waveIds.length === 0) { + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'wave_ids 参数不能为空或格式错误', + error_code: 'INVALID_WAVE_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + wave_ids: waveIds.join(','), + wave_id_list: waveIds, + total_wave_count: waveIds.length, + processed_wave_count: 0, + total_order_count: 0, + processed_order_count: 0, + removed_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_wave_id: 0, + failed_wave_no: '', + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no', 'step' ], + where: { + warehouse_id: warehouseId, + wave_id: { + [Op.in]: waveIds, + }, + step: { + [Op.in]: [ 1, 2, 3 ], + }, + }, + raw: true, + }); + + const waveInfoById = new Map(); + const exceptionOrderIds = []; + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + const orderId = Number(row && row.id || 0); + const waveId = Number(row && row.wave_id || 0); + const waveNo = String(row && row.wave_no || '').trim(); + + if (!Number.isInteger(orderId) || orderId <= 0 || !Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + if (!waveInfoById.has(waveId)) { + waveInfoById.set(waveId, { + wave_id: waveId, + wave_no: waveNo || '未知波次', + }); + } + + if (this.isExceptionRemovableOrder(row)) { + exceptionOrderIds.push(orderId); + } + } + + const targetWaves = waveIds + .map(waveId => waveInfoById.get(waveId)) + .filter(Boolean); + const normalizedExceptionOrderIds = [ ...new Set(exceptionOrderIds) ]; + + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: targetWaves.length, + total_order_count: normalizedExceptionOrderIds.length, + processed_order_count: normalizedExceptionOrderIds.length, + progress_percent: targetWaves.length === 0 ? 100 : 80, + }); + + if (normalizedExceptionOrderIds.length === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: targetWaves.length, + total_order_count: 0, + processed_order_count: 0, + removed_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + removed_order_ids: [], + removed_order_count: 0, + affected_wave_ids: [], + updated_wave_ids: [], + emptied_wave_ids: [], + total_order_count: 0, + processed_order_count: 0, + duration_ms: durationMs, + message: '未找到可移除的异常订单', + }, + }); + return; + } + + const removeResult = await this.batchRemoveOrders({ + ids: normalizedExceptionOrderIds, + }); + + const resultPayload = this.isPlainObject(removeResult) ? removeResult : {}; + const removedOrderIds = Array.isArray(resultPayload.removed_order_ids) ? resultPayload.removed_order_ids : []; + const affectedWaveIds = Array.isArray(resultPayload.affected_wave_ids) ? resultPayload.affected_wave_ids : []; + const updatedWaveIds = Array.isArray(resultPayload.updated_wave_ids) ? resultPayload.updated_wave_ids : []; + const emptiedWaveIds = Array.isArray(resultPayload.emptied_wave_ids) ? resultPayload.emptied_wave_ids : []; + const removedOrderCount = Number(resultPayload.removed_order_count || removedOrderIds.length || 0); + const durationMs = Date.now() - startTime; + + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: targetWaves.length, + total_order_count: normalizedExceptionOrderIds.length, + processed_order_count: normalizedExceptionOrderIds.length, + removed_order_count: removedOrderCount, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + removed_order_ids: removedOrderIds, + removed_order_count: removedOrderCount, + affected_wave_ids: affectedWaveIds, + updated_wave_ids: updatedWaveIds, + emptied_wave_ids: emptiedWaveIds, + total_order_count: normalizedExceptionOrderIds.length, + processed_order_count: normalizedExceptionOrderIds.length, + duration_ms: durationMs, + message: `已移除 ${removedOrderCount} 条异常订单`, + }, + }); + } catch (error) { + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_BATCH_REMOVE_EXCEPTION_ORDERS_FAILED', + }); + } + } + + /** + * 归一化批量取消波次ID参数。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的波次ID数组。 + */ + normalizeBatchCancelWaveIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawWaveIds = normalizedData.wave_ids !== undefined + ? normalizedData.wave_ids + : normalizedData.waveIds !== undefined + ? normalizedData.waveIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : normalizedData.wave_id !== undefined + ? normalizedData.wave_id + : normalizedData.waveId; + + return this.normalizeIdsInput(rawWaveIds); + } + + /** + * 获取批量取消任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchCancelTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_CANCEL_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量取消任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} status 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchCancelTaskProgress(taskId = '', status = 'submitted', data = {}) { + const cacheKey = this.getBatchCancelTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchCancelTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_CANCEL_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.batchCancel] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取批量取消任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchCancelTaskProgress(taskId = '') { + const cacheKey = this.getBatchCancelTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.batchCancel] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 执行批量解除波次后台任务。 + * + * 逐个波次处理:波次已进入拣货中及后续环节、或波次内存在已拣货完成/拣货中的订单时, + * 跳过该波次并记录到 skipped_waves,避免删除已拣货波次;其余波次正常取消。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchCancelTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchCancelTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const waveIds = this.normalizeIdsInput( + cachedTask && cachedTask.wave_ids !== undefined + ? cachedTask.wave_ids + : params && params.waveIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchCancelTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (waveIds.length === 0) { + await this.setBatchCancelTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'wave_ids 参数不能为空或格式错误', + error_code: 'INVALID_WAVE_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + wave_ids: waveIds.join(','), + wave_id_list: waveIds, + total_wave_count: waveIds.length, + processed_wave_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_wave_id: 0, + failed_wave_no: '', + }); + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const querySql = ` + SELECT wave_id, wave_no, wave_status + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:ids) + `; + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId, + ids: waveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const targetWaves = (Array.isArray(queryRows) ? queryRows : []) + .map(row => ({ + wave_id: Number(row && row.wave_id || 0), + wave_no: String(row && row.wave_no || '').trim(), + wave_status: Number(row && row.wave_status || 0), + })) + .filter(item => Number.isInteger(item.wave_id) && item.wave_id > 0); + + if (targetWaves.length === 0) { + await this.setBatchCancelTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: 0, + processed_wave_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + result: { + ids: waveIds, + affected_wave_ids: [], + affected_order_count: 0, + canceled_wave_count: 0, + skipped_wave_ids: [], + skipped_wave_count: 0, + duration_ms: Date.now() - startTime, + }, + }); + return; + } + + let processedWaveCount = 0; + let affectedOrderCount = 0; + let canceledWaveCount = 0; + const affectedWaveIds = []; + const removedOrderIdSet = new Set(); + const skippedWaves = []; + + for (const wave of targetWaves) { + const waveId = Number(wave.wave_id || 0); + const waveNo = String(wave.wave_no || '').trim() || '未知波次'; + const waveStatus = Number(wave.wave_status || 0); + + // 兜底校验:波次已进入拣货中及后续环节时跳过取消,避免删除已拣货波次 + if (waveStatus >= 3) { + skippedWaves.push({ + wave_id: waveId, + wave_no: waveNo, + reason: 'wave_status_blocked', + wave_status: waveStatus, + }); + processedWaveCount += 1; + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), + }); + continue; + } + + const transaction = await this.ctx.model.transaction(); + + try { + // 业务规则校验:波次内存在已拣货完成或拣货中的订单时跳过取消,防止删除已拣货波次 + const pickedOrderGuardRows = await orderModel.findAll({ + attributes: [ 'id', 'pick_status' ], + where: { + wave_id: waveId, + pick_status: { [Op.in]: [ 'padding', 'fin' ] }, + }, + raw: true, + transaction, + }); + + const normalizedPickedOrderGuardRows = Array.isArray(pickedOrderGuardRows) ? pickedOrderGuardRows : []; + if (normalizedPickedOrderGuardRows.length > 0) { + await transaction.rollback(); + skippedWaves.push({ + wave_id: waveId, + wave_no: waveNo, + reason: 'picked_orders_exist', + picked_order_count: normalizedPickedOrderGuardRows.length, + }); + processedWaveCount += 1; + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), + }); + continue; + } + + const affectedOrderRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no' ], + where: { + wave_id: waveId, + }, + raw: true, + transaction, + }); + + const cancelOrderLogItems = (Array.isArray(affectedOrderRows) ? affectedOrderRows : []) + .map(row => { + const orderId = Number(row && row.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + orderId, + operationCode: 'ORDER_WAVE_CANCEL', + message: `波次 ${waveNo} 被删除,订单移出波次`, + }; + }) + .filter(Boolean); + + const orderUpdateResult = await orderModel.update({ + wave_id: 0, + wave_no: '', + wave_scope: 0, + wave_strategy_version: 0, + wave_scan_result: 0, + }, { + where: { + wave_id: waveId, + }, + transaction, + }); + const currentAffectedOrderCount = Number( + Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0 + ); + + // wave_status < 3 守卫:解波只作用于待拣货口径的波次,避免覆盖并发流程 + // (自动终结写入的 5、已进入拣货及后续环节的状态)导致状态互相打架 + const cancelSql = ` + UPDATE wms_wave_batch + SET wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + AND wave_status < 3 + `; + const cancelResult = await this.ctx.model.query(cancelSql, { + replacements: { + warehouseId, + waveId, + }, + transaction, + }); + const cancelMeta = Array.isArray(cancelResult) ? cancelResult[1] : null; + const currentCanceledWaveCount = Number( + cancelMeta && (cancelMeta.affectedRows || cancelMeta.affectedCount || cancelMeta.rowCount) + || 0 + ); + + await this.deleteOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: [ waveId ], + transaction, + }); + + await transaction.commit(); + + await this.batchCreateOrderOperationLogs(cancelOrderLogItems, { + warehouseId, + scene: 'batchCancel', + }); + + const currentRemovedOrderIds = (Array.isArray(affectedOrderRows) ? affectedOrderRows : []) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + for (const orderId of currentRemovedOrderIds) { + removedOrderIdSet.add(orderId); + } + + processedWaveCount += 1; + affectedOrderCount += Number.isInteger(currentAffectedOrderCount) && currentAffectedOrderCount > 0 + ? currentAffectedOrderCount + : 0; + canceledWaveCount += Number.isInteger(currentCanceledWaveCount) && currentCanceledWaveCount > 0 + ? currentCanceledWaveCount + : 0; + if (currentCanceledWaveCount > 0) { + affectedWaveIds.push(waveId); + } + + const progressPercent = Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)); + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: progressPercent, + }); + } catch (error) { + await transaction.rollback(); + await this.setBatchCancelTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), + end_time: Date.now(), + duration_ms: Date.now() - startTime, + failed_wave_id: waveId, + failed_wave_no: waveNo, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_BATCH_CANCEL_FAILED', + result: { + ids: waveIds, + affected_wave_ids: affectedWaveIds, + affected_order_count: affectedOrderCount, + canceled_wave_count: canceledWaveCount, + skipped_wave_ids: skippedWaves.map(item => item.wave_id), + skipped_wave_count: skippedWaves.length, + skipped_waves: skippedWaves, + duration_ms: Date.now() - startTime, + }, + }); + return; + } + } + + const removedOrderIds = [ ...removedOrderIdSet ].sort((a, b) => a - b); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { + triggerScan: true, + source: 'batchCancel', + }); + + const durationMs = Date.now() - startTime; + await this.setBatchCancelTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + ids: waveIds, + affected_wave_ids: affectedWaveIds, + affected_order_count: affectedOrderCount, + canceled_wave_count: canceledWaveCount, + skipped_wave_ids: skippedWaves.map(item => item.wave_id), + skipped_wave_count: skippedWaves.length, + skipped_waves: skippedWaves, + duration_ms: durationMs, + }, + }); + } + + /** + * 生成可追踪的批次分配快递号任务ID。 + * + * 格式:wave_allocate_express_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchAllocateExpressTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_allocate_express_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批次分配快递号任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchAllocateExpressTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批次分配快递号波次ID参数。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的波次ID数组。 + */ + normalizeBatchAllocateExpressWaveIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawWaveIds = normalizedData.wave_ids !== undefined + ? normalizedData.wave_ids + : normalizedData.waveIds !== undefined + ? normalizedData.waveIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : normalizedData.wave_id !== undefined + ? normalizedData.wave_id + : normalizedData.waveId; + + return this.normalizeIdsInput(rawWaveIds); + } + + /** + * 获取批次分配快递号任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchAllocateExpressTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批次分配快递号任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} status 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchAllocateExpressTaskProgress(taskId = '', status = 'submitted', data = {}) { + const cacheKey = this.getBatchAllocateExpressTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchAllocateExpressTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + update_time: Date.now(), + }; + const traceId = this.buildBatchAllocateExpressTraceId(safeData, taskId); + + try { + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存回写前', { + traceId, + taskId: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + warehouseId: Number(mergedPayload.warehouse_id || 0), + waveIds: mergedPayload.wave_id_list || mergedPayload.wave_ids || '', + totalOrderCount: Number(mergedPayload.total_order_count || 0), + processedOrderCount: Number(mergedPayload.processed_order_count || 0), + }); + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS); + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存回写后', { + traceId, + taskId: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + }); + } catch (error) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取批次分配快递号任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchAllocateExpressTaskProgress(taskId = '') { + const cacheKey = this.getBatchAllocateExpressTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存读取前', { + traceId: this.buildBatchAllocateExpressTraceId({}, taskId), + taskId: String(taskId || '').trim(), + }); + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存读取后-未命中', { + traceId: this.buildBatchAllocateExpressTraceId({}, taskId), + taskId: String(taskId || '').trim(), + }); + return null; + } + + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存读取后-命中', { + traceId: this.buildBatchAllocateExpressTraceId(cached, taskId), + taskId: String(taskId || '').trim(), + state: String(cached.state || '').trim() || 'submitted', + }); + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 生成可追踪的批次分配储位任务ID。 + * + * 格式:wave_allocate_storage_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchAllocateStorageTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_allocate_storage_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批次分配储位任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchAllocateStorageTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批次分配储位波次ID参数。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的波次ID数组。 + */ + normalizeBatchAllocateStorageWaveIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawWaveIds = normalizedData.wave_ids !== undefined + ? normalizedData.wave_ids + : normalizedData.waveIds !== undefined + ? normalizedData.waveIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : normalizedData.wave_id !== undefined + ? normalizedData.wave_id + : normalizedData.waveId; + + return this.normalizeIdsInput(rawWaveIds); + } + + /** + * 归一化批次分配储位任务数量。 + * + * @param {*} value 原始数量值。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 非负整数数量。 + */ + normalizeBatchAllocateStorageTaskCount(value, defaultValue = 0) { + const normalizedValue = Number(value); + if (!Number.isFinite(normalizedValue)) { + return Math.max(0, Number(defaultValue || 0)); + } + + const safeValue = Math.floor(normalizedValue); + if (!Number.isInteger(safeValue) || safeValue < 0) { + return 0; + } + + return safeValue; + } + + /** + * 构建批次分配储位 running 状态的进度写入数据。 + * + * running 阶段的 progress_percent 强制上限 99,避免在任务真正完成前提前显示 100%。 + * + * @param {Object} payload 进度回调载荷。 + * @param {Object} cachedProgress 当前缓存中的任务进度。 + * @return {{ total_order_count: number, processed_order_count: number, progress_percent: number }} 进度写入数据。 + */ + buildBatchAllocateStorageRunningProgressPayload(payload = {}, cachedProgress = {}) { + const normalizedPayload = this.isPlainObject(payload) ? payload : {}; + const normalizedCache = this.isPlainObject(cachedProgress) ? cachedProgress : {}; + + const totalOrderCount = this.normalizeBatchAllocateStorageTaskCount( + normalizedPayload.total_count, + normalizedCache.total_order_count + ); + const rawProcessedOrderCount = this.normalizeBatchAllocateStorageTaskCount( + normalizedPayload.processed_count, + normalizedCache.processed_order_count + ); + const processedOrderCount = totalOrderCount > 0 + ? Math.min(rawProcessedOrderCount, totalOrderCount) + : rawProcessedOrderCount; + + const fallbackProgressPercent = this.normalizeBatchAllocateStorageTaskCount( + normalizedPayload.progress_percent, + normalizedCache.progress_percent + ); + const calculatedProgressPercent = totalOrderCount > 0 + ? Math.round((processedOrderCount / totalOrderCount) * 100) + : fallbackProgressPercent; + + return { + total_order_count: totalOrderCount, + processed_order_count: processedOrderCount, + progress_percent: Math.max(0, Math.min(99, calculatedProgressPercent)), + }; + } + + /** + * 归一化批次分配储位成功态订单ID列表。 + * + * @param {*} value 原始订单ID集合。 + * @return {Array} 去重后的订单ID列表。 + */ + normalizeBatchAllocateStorageOrderIds(value) { + return [ ...new Set(this.normalizeIdsInput(value)) ]; + } + + /** + * 获取批次分配储位任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchAllocateStorageTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 获取批次分配储位仓库并发锁键。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 锁键。 + */ + getBatchAllocateStorageWarehouseLockKey(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return ''; + } + + return `wave_allocate_storage_lock_${normalizedWarehouseId}`; + } + + /** + * 尝试获取批次分配储位仓库维度并发锁。 + * + * 该锁仅在当前 Node.js 进程内生效,用于避免同仓库并发触发多个大事务。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {string} [taskId=''] 当前任务ID。 + * @return {{ acquired: boolean, ownerTaskId: string }} 获取结果。 + */ + tryAcquireBatchAllocateStorageWarehouseLock(warehouseId = 0, taskId = '') { + const lockKey = this.getBatchAllocateStorageWarehouseLockKey(warehouseId); + if (!lockKey) { + return { + acquired: false, + ownerTaskId: '', + }; + } + + if (BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.has(lockKey)) { + return { + acquired: false, + ownerTaskId: String(BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.get(lockKey) || '').trim(), + }; + } + + BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.set(lockKey, String(taskId || '').trim()); + + return { + acquired: true, + ownerTaskId: String(taskId || '').trim(), + }; + } + + /** + * 释放批次分配储位仓库维度并发锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {string} [taskId=''] 当前任务ID。 + * @return {void} + */ + releaseBatchAllocateStorageWarehouseLock(warehouseId = 0, taskId = '') { + const lockKey = this.getBatchAllocateStorageWarehouseLockKey(warehouseId); + if (!lockKey) { + return; + } + + const ownerTaskId = String(BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.get(lockKey) || '').trim(); + const normalizedTaskId = String(taskId || '').trim(); + + if (!ownerTaskId || ownerTaskId === normalizedTaskId) { + BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.delete(lockKey); + } + } + + /** + * 写入批次分配储位任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} status 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchAllocateStorageTaskProgress(taskId = '', status = 'submitted', data = {}) { + const cacheKey = this.getBatchAllocateStorageTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchAllocateStorageTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.batchAllocateStorage] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取批次分配储位任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchAllocateStorageTaskProgress(taskId = '') { + const cacheKey = this.getBatchAllocateStorageTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.batchAllocateStorage] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 判断是否为 business_key 列不存在错误。 + * + * 兼容 MySQL/Sequelize 常见报错文案,例如: + * Unknown column 'business_key' in 'field list' + * + * @param {Error|Object} error 异常对象。 + * @return {boolean} 是否为 business_key 缺列错误。 + */ + isMissingBusinessKeyColumnError(error) { + const messageList = [ + error && error.message, + error && error.parent && error.parent.message, + error && error.original && error.original.message, + error && error.sqlMessage, + ] + .map(item => String(item || '').toLowerCase()) + .filter(Boolean); + + return messageList.some(message => { + const hasUnknownColumn = message.includes('unknown column') || message.includes('column does not exist'); + const hasBusinessKey = message.includes('business_key'); + return hasUnknownColumn && hasBusinessKey; + }); + } + + /** + * 执行批次分配快递号后台任务。 + * + * 任务会等待快递分配流水线中所有批次真正完成分配(awaitTasks=true)后 + * 才写入 success 状态,避免进度接口在分配尚未完成时提前返回完成。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchAllocateExpressTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchAllocateExpressTaskProgress(normalizedTaskId); + const traceId = this.buildBatchAllocateExpressTraceId(cachedTask || params, normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const waveIds = this.normalizeIdsInput( + cachedTask && cachedTask.wave_ids !== undefined + ? cachedTask.wave_ids + : params && params.waveIds + ); + + this.ctx.logger.info('[wave.batchAllocateExpress] 后台任务入口', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + paramsSnapshot: { + warehouseId: params && params.warehouseId, + waveIds: params && params.waveIds, + }, + }); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 后台任务参数校验失败-warehouse_id 非法', { + traceId, + taskId: normalizedTaskId, + warehouseId, + }); + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + trace_id: traceId, + }); + return; + } + + if (waveIds.length === 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 后台任务参数校验失败-wave_ids 为空', { + traceId, + taskId: normalizedTaskId, + warehouseId, + }); + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'wave_ids 参数不能为空或格式错误', + error_code: 'INVALID_WAVE_IDS', + trace_id: traceId, + }); + return; + } + + const startTime = Date.now(); + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + wave_ids: waveIds.join(','), + wave_id_list: waveIds, + total_wave_count: waveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + trace_id: traceId, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const baseOrderWhere = { + warehouse_id: warehouseId, + wave_id: { + [Op.in]: waveIds, + }, + step: { + [Op.in]: [ 1, 2, 3 ], + }, + }; + let orderRows = []; + let useBusinessKeyColumn = true; + + try { + orderRows = await orderModel.findAll({ + attributes: [ 'id', 'business_key', 'intercept_status', 'lock_status' ], + where: baseOrderWhere, + raw: true, + }); + } catch (error) { + if (!this.isMissingBusinessKeyColumnError(error)) { + throw error; + } + + useBusinessKeyColumn = false; + this.ctx.logger.warn('[wave.batchAllocateExpress] 订单分表缺少 business_key 列,降级为仅查询 id', { + traceId, + taskId: normalizedTaskId, + warehouseId, + }); + orderRows = await orderModel.findAll({ + attributes: [ 'id', 'intercept_status', 'lock_status' ], + where: baseOrderWhere, + raw: true, + }); + } + + this.ctx.logger.info('[wave.batchAllocateExpress] 订单筛选完成', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + useBusinessKeyColumn, + matchedOrderCount: Array.isArray(orderRows) ? orderRows.length : 0, + }); + + const skippedInterceptedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) + .filter(row => this.isInterceptedOrderStatus(row && row.intercept_status)) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] + .sort((a, b) => a - b); + const skippedInterceptedOrderIdSet = new Set(skippedInterceptedOrderIds); + if (skippedInterceptedOrderIds.length > 0) { + this.ctx.logger.info('[wave.batchAllocateExpress] 跳过拦截订单', { + traceId, + taskId: normalizedTaskId, + warehouseId, + skippedInterceptedOrderIds, + }); + } + + const skippedLockedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) + .filter(row => this.isLockedOrderStatus(row && row.lock_status)) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] + .sort((a, b) => a - b); + const skippedLockedOrderIdSet = new Set(skippedLockedOrderIds); + if (skippedLockedOrderIds.length > 0) { + this.ctx.logger.info('[wave.batchAllocateExpress] 跳过锁定订单', { + traceId, + taskId: normalizedTaskId, + warehouseId, + skippedLockedOrderIds, + }); + } + + const normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) + .map(row => { + const orderId = Number(row && row.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0 + || skippedInterceptedOrderIdSet.has(orderId) + || skippedLockedOrderIdSet.has(orderId)) { + return null; + } + + const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 1); + return { + order_id: orderId, + business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 1, + }; + }) + .filter(Boolean); + + if (normalizedOrders.length === 0) { + this.ctx.logger.info('[wave.batchAllocateExpress] 未筛选到可分配快递号订单', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + skippedInterceptedOrderIds, + skippedLockedOrderIds, + }); + const durationMs = Date.now() - startTime; + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + allocated_order_count: 0, + skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, + skipped_need_oms_waybill_order_ids: [], + duration_ms: durationMs, + message: skippedInterceptedOrderIds.length > 0 || skippedLockedOrderIds.length > 0 + ? `拦截/锁定订单已跳过,未找到可分配快递号的订单(拦截 ${skippedInterceptedOrderIds.length} 单,锁定 ${skippedLockedOrderIds.length} 单)` + : '未找到可分配快递号的订单', + }, + trace_id: traceId, + }); + return; + } + + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + total_order_count: normalizedOrders.length, + trace_id: traceId, + }); + + this.ctx.logger.info('[wave.batchAllocateExpress] 即将调用快递号分配流水线', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + totalOrderCount: normalizedOrders.length, + sampleOrderIds: normalizedOrders.slice(0, 20).map(item => Number(item && item.order_id || 0)).filter(Boolean), + }); + // awaitTasks=true:等待所有批次真正分配完成后再返回,避免任务被提前标记 success。 + // warehouseId 显式传入:后台任务运行在 setImmediate 异步上下文中,ctx.user 可能已失效, + // 防止 getCurrentWarehouseId() 返回 0 导致跨仓/无效仓查询。 + const pipelineResult = await this.service.systems.express.createWaybillCodePipeline(normalizedOrders, { + awaitTasks: true, + warehouseId, + }); + const durationMs = Date.now() - startTime; + + this.ctx.logger.info('[wave.batchAllocateExpress] 快递号分配流水线执行完成', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + totalOrderCount: normalizedOrders.length, + durationMs, + pipelineResult, + }); + + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + total_order_count: normalizedOrders.length, + processed_order_count: normalizedOrders.length, + success_order_count: normalizedOrders.length, + failed_order_count: 0, + skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + allocated_order_count: normalizedOrders.length, + skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, + skipped_need_oms_waybill_order_ids: pipelineResult && Array.isArray(pipelineResult.skipped_need_oms_waybill_order_ids) + ? pipelineResult.skipped_need_oms_waybill_order_ids + : [], + duration_ms: durationMs, + message: String(pipelineResult && pipelineResult.message || '分配快递任务已提交').trim(), + }, + trace_id: traceId, + }); + } catch (error) { + this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务执行失败', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED', + trace_id: traceId, + }); + } + } + + /** + * 执行批次分配储位后台任务。 + * + * 任务仅负责按波次拉取订单并提交储位分配流水线,实际分配过程复用储位分配服务。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchAllocateStorageTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchAllocateStorageTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const waveIds = this.normalizeIdsInput( + cachedTask && cachedTask.wave_ids !== undefined + ? cachedTask.wave_ids + : params && params.waveIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (waveIds.length === 0) { + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'wave_ids 参数不能为空或格式错误', + error_code: 'INVALID_WAVE_IDS', + }); + return; + } + + const startTime = Date.now(); + const lockResult = this.tryAcquireBatchAllocateStorageWarehouseLock(warehouseId, normalizedTaskId); + if (!lockResult.acquired) { + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: lockResult.ownerTaskId + ? `同仓库存在执行中的批量储位分配任务,请稍后重试(running_task_id=${lockResult.ownerTaskId})` + : '同仓库存在执行中的批量储位分配任务,请稍后重试', + error_code: 'WAVE_BATCH_ALLOCATE_STORAGE_WAREHOUSE_CONFLICT', + }); + return; + } + + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + wave_ids: waveIds.join(','), + wave_id_list: waveIds, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_wave_count: waveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'lock_status' ], + where: { + warehouse_id: warehouseId, + wave_id: { + [Op.in]: waveIds, + }, + step: { + [Op.in]: [ 1, 2, 3 ], + }, + }, + raw: true, + }); + + const skippedLockedOrderIdSet = new Set((Array.isArray(orderRows) ? orderRows : []) + .filter(row => this.isLockedOrderStatus(row && row.lock_status)) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)); + const normalizedOrders = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] + .filter(orderId => !skippedLockedOrderIdSet.has(orderId)) + .map(orderId => ({ + order_id: orderId, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + })); + const normalizedOrderIds = normalizedOrders.map(item => Number(item.order_id || 0)).filter(Boolean); + + if (normalizedOrderIds.length === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + affected_order_ids: [], + affected_order_count: 0, + allocated_order_ids: [], + allocated_order_count: 0, + shortage_order_ids: [], + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + affected_order_ids: [], + affected_order_count: 0, + allocated_order_ids: [], + allocated_order_count: 0, + shortage_order_ids: [], + duration_ms: durationMs, + message: '未找到可分配储位的订单', + }, + }); + return; + } + + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_order_count: normalizedOrderIds.length, + }); + + const progressCallback = async callbackPayload => { + const latestProgress = await this.getBatchAllocateStorageTaskProgress(normalizedTaskId); + const runningProgressPayload = this.buildBatchAllocateStorageRunningProgressPayload( + callbackPayload, + latestProgress || { + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + progress_percent: 0, + } + ); + + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + ...runningProgressPayload, + }); + }; + + const pipelineResult = await this.service.systems.orderStorageAllocation.allocateStorage({ + ids: normalizedOrderIds, + orders: normalizedOrders, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + progress_callback: progressCallback, + }); + + if (!this.isPlainObject(pipelineResult) || Number(pipelineResult.code) !== 200) { + throw new Error(String(pipelineResult && pipelineResult.message || '储位分配任务提交失败').trim()); + } + + const resultData = this.isPlainObject(pipelineResult.data) ? pipelineResult.data : {}; + const pendingOrderIds = this.normalizeBatchAllocateStorageOrderIds(resultData.pending_order_ids); + const affectedOrderIds = pendingOrderIds.length > 0 + ? pendingOrderIds + : this.normalizeBatchAllocateStorageOrderIds(normalizedOrderIds); + const allocatedOrderIds = this.normalizeBatchAllocateStorageOrderIds(resultData.allocated_order_ids); + const shortageOrderIds = this.normalizeBatchAllocateStorageOrderIds(resultData.shortage_order_ids); + const affectedOrderCount = affectedOrderIds.length; + const successOrderCount = allocatedOrderIds.length; + const failedOrderCount = shortageOrderIds.length > 0 + ? shortageOrderIds.length + : Math.max(0, affectedOrderCount - successOrderCount); + const durationMs = Date.now() - startTime; + + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_order_count: affectedOrderCount, + processed_order_count: affectedOrderCount, + success_order_count: successOrderCount, + failed_order_count: failedOrderCount, + affected_order_ids: affectedOrderIds, + affected_order_count: affectedOrderCount, + allocated_order_ids: allocatedOrderIds, + allocated_order_count: successOrderCount, + shortage_order_ids: shortageOrderIds, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + affected_order_ids: affectedOrderIds, + affected_order_count: affectedOrderCount, + allocated_order_ids: allocatedOrderIds, + allocated_order_count: successOrderCount, + shortage_order_ids: shortageOrderIds, + duration_ms: durationMs, + message: String(pipelineResult && pipelineResult.message || '分配储位任务已提交').trim(), + }, + }); + } catch (error) { + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_BATCH_ALLOCATE_STORAGE_FAILED', + }); + } finally { + this.releaseBatchAllocateStorageWarehouseLock(warehouseId, normalizedTaskId); + } + } + + /** + * 批量将波次状态改为“自动加团中”。 + * + * 仅处理当前登录仓库下命中的波次状态,不修改订单表 wave_id。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} data.ids 波次ID集合。 + * @return {Promise} 批量更新结果。 + */ + async batchAutoGrouping(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const normalizedIds = this.normalizeIdsInput(data && data.ids); + if (normalizedIds.length === 0) { + throw new Error('ids 参数不能为空或格式错误'); + } + + const maxWaveQuantity = await this.getDefaultWaveQuantity(warehouseId); + + const transaction = await this.ctx.model.transaction(); + + try { + const querySql = ` + SELECT wave_id, wave_status, total_orders + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:ids) + `; + + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId, + ids: normalizedIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const affectedRows = Array.isArray(queryRows) ? queryRows : []; + const affectedWaveIds = [ ...new Set(affectedRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + const skippedDetails = []; + const skippedWaveIds = []; + const updatableWaveIds = []; + + for (const row of affectedRows) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + const waveStatus = Number(row && row.wave_status || 0); + const totalOrders = Number(row && row.total_orders || 0); + + if (waveStatus >= 2) { + skippedWaveIds.push(waveId); + skippedDetails.push({ + wave_id: waveId, + reason: 'printed_or_after_printed', + }); + continue; + } + + if (totalOrders >= maxWaveQuantity) { + skippedWaveIds.push(waveId); + skippedDetails.push({ + wave_id: waveId, + reason: 'reach_max_wave_quantity', + }); + continue; + } + + updatableWaveIds.push(waveId); + } + + if (affectedWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: [], + skipped_wave_ids: [], + skipped_wave_count: 0, + skipped_details: [], + updated_wave_count: 0, + }); + } + + if (updatableWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: affectedWaveIds, + skipped_wave_ids: skippedWaveIds, + skipped_wave_count: skippedWaveIds.length, + skipped_details: skippedDetails, + updated_wave_count: 0, + }); + } + + const updateSql = ` + UPDATE wms_wave_batch + SET wave_status = 0, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `; + + const updateResult = await this.ctx.model.query(updateSql, { + replacements: { + warehouseId, + waveIds: updatableWaveIds, + }, + transaction, + }); + + const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; + const updatedWaveCount = Number( + updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) + || updatableWaveIds.length + ); + + await transaction.commit(); + + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: affectedWaveIds, + skipped_wave_ids: skippedWaveIds, + skipped_wave_count: skippedWaveIds.length, + skipped_details: skippedDetails, + updated_wave_count: Number.isInteger(updatedWaveCount) && updatedWaveCount > 0 ? updatedWaveCount : 0, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 批量结束“自动加团中”状态。 + * + * 仅处理当前登录仓库下命中的波次,且仅将 wave_status=0 的波次更新为 1(已就绪)。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} data.ids 波次ID集合。 + * @return {Promise} 批量结束结果。 + */ + async batchFinishAutoGrouping(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const normalizedIds = this.normalizeIdsInput(data && data.ids); + if (normalizedIds.length === 0) { + throw new Error('ids 参数不能为空或格式错误'); + } + + const transaction = await this.ctx.model.transaction(); + + try { + const querySql = ` + SELECT wave_id, wave_status + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:ids) + `; + + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId, + ids: normalizedIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const affectedRows = Array.isArray(queryRows) ? queryRows : []; + const affectedWaveIds = [ ...new Set(affectedRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + if (affectedWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: [], + updated_wave_ids: [], + updated_wave_count: 0, + }); + } + + const updatedWaveIds = [ ...new Set(affectedRows + .filter(row => Number(row && row.wave_status || 0) === 0) + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + if (updatedWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: affectedWaveIds, + updated_wave_ids: [], + updated_wave_count: 0, + }); + } + + // 关闭自动加团前,重建波次订单索引(wave_index 重新排序),确保序号连续 + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + await this.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: updatedWaveIds, + orderModel, + transaction, + }); + + const updateSql = ` + UPDATE wms_wave_batch + SET wave_status = 1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND wave_status = 0 + `; + + const updateResult = await this.ctx.model.query(updateSql, { + replacements: { + warehouseId, + waveIds: updatedWaveIds, + }, + transaction, + }); + + const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; + const updatedWaveCount = Number( + updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) + || updatedWaveIds.length + ); + + await transaction.commit(); + + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: affectedWaveIds, + updated_wave_ids: updatedWaveIds, + updated_wave_count: Number.isInteger(updatedWaveCount) && updatedWaveCount > 0 ? updatedWaveCount : 0, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 生成可追踪的抓取任务ID。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 抓取任务ID。 + */ + generateFetchTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const waveIdSeed = this.generateWaveId(); + return `wave_fetch_${safeWarehouseId}_${waveIdSeed}`; + } + + /** + * 归一化抓取任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeFetchTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取抓取任务进度缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getFetchTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${FETCH_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入抓取任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {Object} payload 进度数据。 + * @return {Promise} 无返回值。 + */ + async setFetchTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getFetchTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + ...safePayload, + task_id: String(taskId || '').trim(), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, FETCH_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.fetch] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取抓取任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 任务进度缓存。 + */ + async getFetchTaskProgress(taskId = '') { + const cacheKey = this.getFetchTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.fetch] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 查询抓取任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async fetchTaskProgress(data = {}) { + const taskId = this.normalizeFetchTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getFetchTaskProgress(taskId); + + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + }); + } + + return this.success('ok', { + task_id: taskId, + ...cachedProgress, + status: String(cachedProgress.status || 'unknown').trim() || 'unknown', + }); + } + + /** + * 执行异步抓取任务。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.defaultQuantity 默认抓取数量。 + * @param {Array} params.structures 结构化抓取请求。 + * @param {string} [params.fetchMode='group'] 抓取模式:group|single。 + * @param {number} [params.maxFetchQuantity=0] single 模式最大抓取订单数上限。 + * @return {Promise} 无返回值。 + */ + async runFetchTask({ + taskId = '', + warehouseId = 0, + defaultQuantity = DEFAULT_MAX_WAVE_QUANTITY, + structures = [], + fetchMode = 'group', + maxFetchQuantity = 0, + } = {}) { + const normalizedTaskId = String(taskId || '').trim(); + const normalizedWarehouseId = Number(warehouseId || 0); + const structureList = Array.isArray(structures) ? structures : []; + const normalizedFetchMode = String(fetchMode || 'group').trim() === 'single' ? 'single' : 'group'; + const normalizedMaxFetchQuantity = Number.isInteger(Number(maxFetchQuantity)) && Number(maxFetchQuantity) > 0 + ? Number(maxFetchQuantity) + : 0; + + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('warehouseId 参数不合法'); + } + + if (structureList.length === 0) { + throw new Error('structures 不能为空'); + } + + if (normalizedFetchMode === 'single' && normalizedMaxFetchQuantity <= 0) { + throw new Error('single 模式要求 maxFetchQuantity 为正整数'); + } + + this.ctx.logger.info('[wave.fetch] 后台任务开始', { + taskId: normalizedTaskId, + warehouseId: normalizedWarehouseId, + structureCount: structureList.length, + defaultQuantity: Number(defaultQuantity || 0), + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + }); + + const startedAt = Date.now(); + await this.setFetchTaskProgress(normalizedTaskId, { + status: 'running', + warehouse_id: normalizedWarehouseId, + structure_count: structureList.length, + finished_structure_count: 0, + progress_percent: 0, + default_quantity: Number(defaultQuantity || 0), + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + started_at: startedAt, + }); + + try { + const groupWavePrefix = await this.getGroupWavePrefix(normalizedWarehouseId); + const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(normalizedWarehouseId); + const model = await this.getOrderModel('pendingOrder', normalizedWarehouseId); + + const results = []; + let totalFetchedQuantity = 0; + let reachedLimit = false; + for (let i = 0; i < structureList.length; i++) { + if (normalizedFetchMode === 'single' && totalFetchedQuantity >= normalizedMaxFetchQuantity) { + reachedLimit = true; + break; + } + + const structure = structureList[i]; + const remainingFetchQuantity = normalizedFetchMode === 'single' + ? normalizedMaxFetchQuantity - totalFetchedQuantity + : 0; + const result = await this.fetchSingleStructure( + model, + structure, + normalizedWarehouseId, + groupWavePrefix, + normalizedFetchMode === 'single' ? 1 : minGroupOrderFetchQuantity, + { + maxFetchQuantity: remainingFetchQuantity, + // 波次抓取(团购/散单)统一排除 SN 订单 + excludeSnOrders: true, + } + ); + results.push(result); + totalFetchedQuantity += Number(result.fetched_quantity || 0); + if (normalizedFetchMode === 'single' && totalFetchedQuantity >= normalizedMaxFetchQuantity) { + reachedLimit = true; + } + + const finishedStructureCount = results.length; + const progressPercent = Math.min( + 100, + Math.round((finishedStructureCount / structureList.length) * 100) + ); + + await this.setFetchTaskProgress(normalizedTaskId, { + status: 'running', + warehouse_id: normalizedWarehouseId, + structure_count: structureList.length, + finished_structure_count: finishedStructureCount, + progress_percent: progressPercent, + total_fetched_quantity: totalFetchedQuantity, + default_quantity: Number(defaultQuantity || 0), + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + ...(normalizedFetchMode === 'single' ? { limit_reached: reachedLimit } : {}), + started_at: startedAt, + }); + } + + const totalRequestQuantity = results.reduce((sum, item) => sum + Number(item.request_quantity || 0), 0); + const durationMs = Date.now() - startedAt; + const finishedStructureCount = results.length; + const progressPercent = structureList.length > 0 + ? Math.min(100, Math.round((finishedStructureCount / structureList.length) * 100)) + : 100; + + await this.setFetchTaskProgress(normalizedTaskId, { + status: 'success', + warehouse_id: normalizedWarehouseId, + structure_count: structureList.length, + finished_structure_count: finishedStructureCount, + progress_percent: progressPercent, + total_request_quantity: totalRequestQuantity, + total_fetched_quantity: totalFetchedQuantity, + default_quantity: Number(defaultQuantity || 0), + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + ...(normalizedFetchMode === 'single' ? { limit_reached: reachedLimit } : {}), + ...(normalizedFetchMode === 'single' && reachedLimit ? { stop_reason: '达到最大抓取上限' } : {}), + started_at: startedAt, + duration_ms: durationMs, + }); + + this.ctx.logger.info('[wave.fetch] 后台任务完成', { + taskId: normalizedTaskId, + warehouseId: normalizedWarehouseId, + structureCount: structureList.length, + defaultQuantity: Number(defaultQuantity || 0), + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + reachedLimit, + totalRequestQuantity, + totalFetchedQuantity, + durationMs, + }); + } catch (error) { + await this.setFetchTaskProgress(normalizedTaskId, { + status: 'failed', + warehouse_id: normalizedWarehouseId, + structure_count: structureList.length, + default_quantity: Number(defaultQuantity || 0), + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + started_at: startedAt, + duration_ms: Date.now() - startedAt, + error: error && error.message ? error.message : `${error}`, + }); + throw error; + } + } + + /** + * 提交异步抓取任务。 + * + * @param {Object} data 请求参数。 + * @param {'group'|'single'} [fetchMode='group'] 抓取模式。 + * @param {number} [maxFetchQuantity=0] single 模式最大抓取订单数。 + * @return {Promise} 任务提交结果。 + */ + async submitFetchTask(data = {}, fetchMode = 'group', maxFetchQuantity = 0) { + const warehouseId = this.getWarehouseId(); + const defaultQuantity = await this.getDefaultWaveQuantity(warehouseId); + const structures = this.normalizeFetchStructureRequests(data, defaultQuantity); + const taskId = this.generateFetchTaskId(warehouseId); + const normalizedFetchMode = String(fetchMode || 'group').trim() === 'single' ? 'single' : 'group'; + const normalizedMaxFetchQuantity = Number.isInteger(Number(maxFetchQuantity)) && Number(maxFetchQuantity) > 0 + ? Number(maxFetchQuantity) + : 0; + + await this.setFetchTaskProgress(taskId, { + status: 'submitted', + warehouse_id: Number(warehouseId || 0), + structure_count: structures.length, + finished_structure_count: 0, + progress_percent: 0, + default_quantity: defaultQuantity, + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + submitted_at: Date.now(), + }); + + this.ctx.logger.info('[wave.fetch] 任务提交成功', { + taskId, + warehouseId: Number(warehouseId || 0), + structureCount: structures.length, + defaultQuantity, + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + }); + + setImmediate(() => { + this.runFetchTask({ + taskId, + warehouseId: Number(warehouseId || 0), + defaultQuantity, + structures, + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + }).catch(error => { + this.ctx.logger.error('[wave.fetch] 后台任务异常', { + taskId, + warehouseId: Number(warehouseId || 0), + structureCount: structures.length, + defaultQuantity, + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + task_id: taskId, + warehouse_id: Number(warehouseId || 0), + structure_count: structures.length, + default_quantity: defaultQuantity, + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + message: '任务已提交,后端异步处理中', + }); + } + + /** + * 团购抓取波次:按机器结构标识批量抓取订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.structure_list 结构请求数组。 + * @return {Promise} 任务提交结果。 + */ + async groupFetch(data = {}) { + return this.submitFetchTask(data, 'group', 0); + } + + /** + * 散单抓取波次:支持按订单数上限停止。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.structure_list 结构请求数组。 + * @param {number|string} data.max_fetch_quantity 最大抓取订单数(必填正整数)。 + * @return {Promise} 任务提交结果。 + */ + async singleFetch(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const maxFetchQuantity = this.normalizeRequiredPositiveInteger( + normalizedData.max_fetch_quantity ?? normalizedData.maxFetchQuantity, + 'max_fetch_quantity' + ); + + return this.submitFetchTask(normalizedData, 'single', maxFetchQuantity); + } + + /** + * 按策略与策略类型推导本次抓取的拣货模式。 + * + * 优先使用显式入参 pick_mode/pickMode,其次回退到策略字段(strategy_type、batch_mode)。 + * + * @param {Object} options 推导参数。 + * @param {Object} [options.requestData={}] 请求参数。 + * @param {Object} [options.strategyRow={}] 策略行数据。 + * @return {number} 归一化后的拣货模式(1-5,异常时为 0)。 + */ + resolveWaveStrategyFetchPickMode(options = {}) { + const requestData = this.isPlainObject(options && options.requestData) + ? options.requestData + : {}; + const strategyRow = this.isPlainObject(options && options.strategyRow) + ? options.strategyRow + : {}; + + const strategyType = Number(strategyRow.strategy_type || 0); + // SN 策略固定先拣后分,忽略显式 pick_mode 入参 + if (strategyType === 3) { + return 3; + } + + const explicitPickMode = Number(requestData.pick_mode ?? requestData.pickMode); + if (Number.isInteger(explicitPickMode) && explicitPickMode >= 1 && explicitPickMode <= 5) { + return explicitPickMode; + } + + const batchMode = Number(strategyRow.batch_mode || 0); + const groupBatchMaxOrders = Number(strategyRow.group_batch_max_orders || 0); + + if (strategyType === 2) { + if (groupBatchMaxOrders > 1) { + return 1; + } + return 5; + } + + if (batchMode === 1) { + return 2; + } + if (batchMode === 2) { + return 3; + } + if ([ 3, 4, 5, 6 ].includes(batchMode)) { + return 4; + } + + return 0; + } + + /** + * 构建抓取策略的框分配规则(最小可执行结构)。 + * + * @param {Object} options 构建参数。 + * @param {number} options.pickMode 拣货模式。 + * @param {Array} [options.selectedWaveIds=[]] 预抓波次ID集合。 + * @param {number} [options.boxLimit=0] 最大可用框数。 + * @return {Array} 框分配规则列表。 + */ + buildWaveStrategyFetchBoxAssignments(options = {}) { + const pickMode = Number(options && options.pickMode || 0); + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const boxLimit = Number(options && options.boxLimit || 0); + + if (pickMode === 1) { + return selectedWaveIds.map((waveId, index) => ({ + wave_id: waveId, + box_no: index + 1, + rule: 'one_wave_one_box', + })); + } + + if (selectedWaveIds.length > 0) { + return [{ + wave_id: selectedWaveIds[0], + box_no: 1, + rule: pickMode === 5 ? 'single_wave_dynamic_append' : 'single_wave_single_box', + }]; + } + + return [{ + wave_id: 0, + box_no: 1, + rule: pickMode === 5 ? 'single_wave_dynamic_append' : 'single_wave_single_box', + box_limit: Number.isInteger(boxLimit) && boxLimit > 0 ? boxLimit : 1, + }]; + } + + /** + * 策略抓取前置预处理:统一输出标准化 plan。 + * + * 仅做策略与参数预处理,不执行任务写库。 + * + * @param {Object} params 预处理入参。 + * @param {number|string} params.strategyId 策略ID。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} [params.operator={}] 操作人信息。 + * @param {string} [params.source='unknown'] 来源标识(pda/admin)。 + * @param {Object} [params.data={}] 原始请求参数。 + * @return {Promise} 标准化抓取 plan。 + */ + async prepareWaveStrategyFetchPlan(params = {}) { + const strategyId = this.normalizeRequiredPositiveInteger(params && params.strategyId, 'strategy_id'); + const warehouseId = this.normalizeRequiredPositiveInteger(params && params.warehouseId, 'warehouse_id'); + const source = String(params && params.source || 'unknown').trim() || 'unknown'; + const operator = this.isPlainObject(params && params.operator) ? params.operator : {}; + const requestData = this.isPlainObject(params && params.data) ? params.data : {}; + const hasExplicitWaveSelectionInput = [ + 'selected_wave_ids', + 'selectedWaveIds', + 'wave_ids', + 'waveIds', + 'wave_id', + 'waveId', + ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); + + const plan = { + strategy_id: strategyId, + warehouse_id: warehouseId, + source, + operator, + pick_mode: 0, + wave_limit: 0, + order_limit: 0, + sku_limit: 0, + box_limit: 0, + selected_wave_ids: [], + box_assignments: [], + dynamic_append: false, + validation_errors: [], + }; + + let strategyRows = []; + try { + strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId); + } catch (error) { + strategyRows = []; + } + + let strategyRow = (Array.isArray(strategyRows) ? strategyRows : []).find(item => { + const currentId = Number(item && (item.id ?? item.strategy_id ?? item.strategyId) || 0); + return Number.isInteger(currentId) && currentId === strategyId; + }) || null; + + if (!strategyRow) { + const strategyModel = this.getWaveStrategyModel(); + if (strategyModel && typeof strategyModel.findOne === 'function') { + const strategyEntity = await strategyModel.findOne({ + where: { + id: strategyId, + warehouse_id: warehouseId, + status: 1, + }, + raw: true, + }); + if (strategyEntity && typeof strategyEntity.get === 'function') { + strategyRow = strategyEntity.get({ plain: true }); + } else { + strategyRow = strategyEntity || null; + } + } + } + + if (!strategyRow) { + plan.validation_errors.push(`策略不存在或已停用: ${strategyId}`); + return plan; + } + + plan.strategy_type = Number(strategyRow.strategy_type || 0); + plan.strategy_row = strategyRow; + + const selectedWaveIds = this.normalizeIdsInput( + requestData.selected_wave_ids !== undefined + ? requestData.selected_wave_ids + : requestData.selectedWaveIds !== undefined + ? requestData.selectedWaveIds + : requestData.wave_ids !== undefined + ? requestData.wave_ids + : requestData.waveIds !== undefined + ? requestData.waveIds + : requestData.wave_id !== undefined + ? requestData.wave_id + : requestData.waveId + ); + plan.selected_wave_ids = selectedWaveIds; + + const pickMode = this.resolveWaveStrategyFetchPickMode({ + requestData, + strategyRow, + }); + plan.pick_mode = pickMode; + + if (![ 1, 2, 3, 4, 5 ].includes(pickMode)) { + plan.validation_errors.push('无法从策略推导有效 pick_mode,请显式传入 pick_mode(1-5)'); + } + + const rawBoxLimit = requestData.box_limit ?? requestData.boxLimit ?? strategyRow.group_batch_max_orders; + const normalizedBoxLimit = Number(rawBoxLimit); + plan.box_limit = Number.isInteger(normalizedBoxLimit) && normalizedBoxLimit > 0 ? normalizedBoxLimit : 1; + + const rawOrderLimit = requestData.order_limit ?? requestData.orderLimit ?? strategyRow.batch_max_orders; + const normalizedOrderLimit = Number(rawOrderLimit); + plan.order_limit = Number.isInteger(normalizedOrderLimit) && normalizedOrderLimit > 0 ? normalizedOrderLimit : 0; + + const rawSkuLimit = requestData.sku_limit ?? requestData.skuLimit ?? strategyRow.batch_max_skus; + const normalizedSkuLimit = Number(rawSkuLimit); + plan.sku_limit = Number.isInteger(normalizedSkuLimit) && normalizedSkuLimit > 0 ? normalizedSkuLimit : 0; + + const rawWaveLimit = requestData.wave_limit ?? requestData.waveLimit; + const normalizedWaveLimit = Number(rawWaveLimit); + if (Number.isInteger(normalizedWaveLimit) && normalizedWaveLimit > 0) { + plan.wave_limit = normalizedWaveLimit; + } else { + plan.wave_limit = pickMode === 1 ? plan.box_limit : 1; + } + + if (pickMode === 1) { + if (plan.box_limit <= 0) { + plan.validation_errors.push('小团购模式 box_limit 必须大于 0'); + } + if (selectedWaveIds.length > plan.box_limit) { + plan.validation_errors.push(`小团购模式预抓波次数(${selectedWaveIds.length})超过 box_limit(${plan.box_limit})`); + } + } + + if ([ 1, 5 ].includes(pickMode) && hasExplicitWaveSelectionInput && selectedWaveIds.length === 0) { + plan.validation_errors.push('当前模式依赖波次,selected_wave_ids 不能为空'); + } + + if ([ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 1) { + plan.validation_errors.push('单品单件/先拣后分/边拣边分模式一次仅支持一个波次'); + } + + if (pickMode === 2 && plan.order_limit <= 0) { + plan.validation_errors.push('单品单件模式 order_limit 必须大于 0'); + } + + if (pickMode === 3 && plan.sku_limit <= 0) { + plan.validation_errors.push('先拣后分模式 sku_limit 必须大于 0'); + } + + if (pickMode === 5) { + plan.dynamic_append = true; + if (selectedWaveIds.length > 1) { + plan.validation_errors.push('大团购模式一次仅支持一个波次(后续追加采用动态扫描)'); + } + } + + plan.box_assignments = this.buildWaveStrategyFetchBoxAssignments({ + pickMode, + selectedWaveIds, + boxLimit: plan.box_limit, + }); + + return plan; + } + + /** + * 校验当前操作用户是否存在未完成任务。 + * + * 活跃状态定义:status in (0,1),不包含已完成(status=2)的任务。 + * + * @param {Object} params 校验参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.operatorId 操作用户ID。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async ensureNoActiveWavePickTaskForOperator(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const operatorId = Number(params.operatorId || 0); + const transaction = params.transaction; + + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return; + } + + const rows = await this.ctx.model.query(` + SELECT id, task_no + FROM wms_wave_pick_task + WHERE warehouse_id = :warehouseId + AND pick_user_id = :operatorId + AND status IN (0, 1) + ORDER BY id DESC + LIMIT 1 + FOR UPDATE + `, { + replacements: { + warehouseId, + operatorId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const activeTask = Array.isArray(rows) ? rows[0] : null; + if (activeTask) { + const taskNo = String(activeTask.task_no || '').trim(); + const taskId = Number(activeTask.id || 0); + throw new Error(`当前用户存在未完成任务,请先完成后再创建(task_id=${taskId}${taskNo ? `,task_no=${taskNo}` : ''})`); + } + } + + /** + * 归一化候选订单查询的创建时间上限(不含)。 + * + * @param {Date|string|null} [createdBefore=null] 创建时间上限。 + * @return {Date|null} 归一化后的 Date;非法输入返回 null(表示不限制)。 + */ + normalizeWaveStrategyFetchCreatedBefore(createdBefore = null) { + if (createdBefore instanceof Date && !Number.isNaN(createdBefore.getTime())) { + return createdBefore; + } + + if (typeof createdBefore === 'string' && createdBefore.trim()) { + const parsed = new Date(createdBefore.trim()); + if (!Number.isNaN(parsed.getTime())) { + return parsed; + } + } + + return null; + } + + /** + * 计算今日 0 点(本地时区),作为订单池分割的时间边界。 + * + * 第一订单池 = 创建时间早于今日 0 点的订单(前一天及更早订单); + * 第二订单池 = 其余订单(今日订单)。 + * + * @return {Date} 今日 0 点时间。 + */ + buildWaveStrategyFetchTodayStart() { + const now = new Date(); + return new Date(now.getFullYear(), now.getMonth(), now.getDate()); + } + + /** + * 查询策略自动分流候选订单(命中策略且未分配波次)。 + * + * 过滤口径:step != 0、wave_id = 0、status != cancel、outbound_status != padding; + * 散单/团购策略还需按同结构数量命中 min_same_structure/max_same_structure, + * SN 策略(strategy_type=3)忽略同结构数量区间(SN 订单只能由 SN 策略抓取)。 + * + * @param {Object} params 查询参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.strategyId 策略ID。 + * @param {number|string|null} [params.minSameStructure=0] 最小同结构数量(SN 策略忽略)。 + * @param {number|string|null} [params.maxSameStructure=null] 最大同结构数量(SN 策略忽略)。 + * @param {Date|string|null} [params.createdBefore=null] 创建时间上限(不含), + * 仅命中创建时间早于该值的订单,用于分割第一/第二订单池;为 null 时不限制。 + * @param {number|string} [params.strategyType=0] 策略类型:1-散单 2-团购 3-SN; + * 1/2 排除 SN 订单,3 仅取 SN 订单。 + * @return {Promise>} 候选订单数组(按 order_id 升序)。 + */ + async getWaveStrategyFetchCandidateOrders(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const strategyId = this.normalizeRequiredPositiveInteger(params.strategyId, 'strategy_id'); + const minSameStructureRaw = Number(params.minSameStructure ?? 0); + const maxSameStructureRaw = Number(params.maxSameStructure); + const minSameStructure = Number.isFinite(minSameStructureRaw) && minSameStructureRaw > 0 + ? Math.floor(minSameStructureRaw) + : 0; + const maxSameStructure = Number.isFinite(maxSameStructureRaw) && maxSameStructureRaw > 0 + ? Math.floor(maxSameStructureRaw) + : null; + const requireSameExpress = Number(params.requireSameExpress ?? 0) === 1; + const createdBefore = this.normalizeWaveStrategyFetchCreatedBefore(params.createdBefore); + const strategyType = Number(params.strategyType ?? 0); + const isSnStrategy = strategyType === 3; + const snOuterCondition = isSnStrategy + ? "AND o.has_sn_item = 'Y'" + : "AND (o.has_sn_item IS NULL OR o.has_sn_item <> 'Y')"; + const snSourceCondition = isSnStrategy + ? "AND src.has_sn_item = 'Y'" + : "AND (src.has_sn_item IS NULL OR src.has_sn_item <> 'Y')"; + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const structureExpr = alias => `${alias}.items_hash`; + const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; + const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')}` : ''; + const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; + // SN 策略(strategy_type=3)忽略同结构最小/最大数量限制:SN 订单只能由 SN 策略抓取, + // 若按散单的同结构区间过滤,单个/少量 SN 订单会永远匹配不到,故直接跳过同结构统计与过滤。 + const sameStructureJoinSql = isSnStrategy + ? '' + : ` + INNER JOIN ( + SELECT + ${structureExpr('src')} AS structure_key${requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''}, + COUNT(1) AS same_structure_count + FROM ${orderTableName} src + WHERE src.warehouse_id = :warehouseId + AND src.wave_id = 0 + AND src.step != 0 + AND src.post_status = 'fin' + AND src.storage_status = 'fin' + AND src.print_status != 'fin' + AND src.status != 'cancel' + AND src.outbound_status != 'padding' + AND src.intercept_status = 'none' + AND src.lock_status = 'none' + AND (src.is_b2b IS NULL OR src.is_b2b = 'N') + ${snSourceCondition} + GROUP BY ${structureExpr('src')}${groupKeyExtra} + ) same_structure + ON same_structure.structure_key = ${structureExpr('o')}${joinKeyExtra}`; + const sameStructureWhereSql = isSnStrategy + ? '' + : ` + AND same_structure.same_structure_count >= :minSameStructure + AND (:maxSameStructure IS NULL OR same_structure.same_structure_count <= :maxSameStructure)`; + const rows = await this.ctx.model.query(` + SELECT + o.id, + o.items_hash, + o.items, + o.logistics_name, + o.sys_logistics_code, + o.logistics_code, + o.items_count, + o.items_total, + o.has_sn_item + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id + AND o.warehouse_id = :warehouseId + AND o.wave_id = 0 + AND o.step != 0 + AND o.post_status = 'fin' + AND o.storage_status = 'fin' + AND o.print_status != 'fin' + AND o.status != 'cancel' + AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' + AND (o.is_b2b IS NULL OR o.is_b2b = 'N') + ${snOuterCondition} + AND (:createdBefore IS NULL OR o.create_at < :createdBefore) + ${sameStructureJoinSql} + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id = :strategyId${sameStructureWhereSql} + ORDER BY o.id ASC + `, { + replacements: { + warehouseId, + strategyId, + minSameStructure, + maxSameStructure, + createdBefore, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + return (Array.isArray(rows) ? rows : []) + .map(row => ({ + id: Number(row && row.id || 0), + items_hash: String(row && row.items_hash || '').trim(), + items: String(row && row.items || '').trim(), + logistics_name: String(row && row.logistics_name || '').trim(), + sys_logistics_code: String(row && row.sys_logistics_code || '').trim(), + logistics_code: String(row && row.logistics_code || '').trim(), + items_count: Number(row && row.items_count || 0), + items_total: Number(row && row.items_total || 0), + has_sn_item: String(row && row.has_sn_item || '').trim(), + })) + .filter(row => Number.isInteger(row.id) && row.id > 0) + .sort((a, b) => a.id - b.id); + } + + /** + * 按订单结构对候选订单分组。 + * + * @param {Array} candidateRows 候选订单数组。 + * @return {Array} 分组结果(含 group_min_order_id)。 + */ + groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows = []) { + const groupedMap = new Map(); + const rows = Array.isArray(candidateRows) ? candidateRows : []; + + for (const row of rows) { + const structureKey = this.getWaveStrategyQuickScanStructureKey(row); + if (!structureKey) { + continue; + } + + if (!groupedMap.has(structureKey)) { + groupedMap.set(structureKey, []); + } + groupedMap.get(structureKey).push(row); + } + + return Array.from(groupedMap.entries()) + .map(([ structureKey, orders ]) => { + const sortedOrders = orders + .map(item => ({ ...item })) + .sort((a, b) => Number(a.id || 0) - Number(b.id || 0)); + const minOrderId = sortedOrders.length > 0 ? Number(sortedOrders[0].id || 0) : 0; + return { + structure_key: structureKey, + group_min_order_id: minOrderId, + orders: sortedOrders, + order_ids: sortedOrders.map(item => Number(item.id || 0)).filter(id => Number.isInteger(id) && id > 0), + }; + }) + .filter(group => group.order_ids.length > 0) + .sort((a, b) => a.group_min_order_id - b.group_min_order_id); + } + + /** + * 读取订单商品明细并构建每单 SKU 集合。 + * + * @param {Object} params 构建参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID数组。 + * @return {Promise>>} order_id 到 SKU 集合映射。 + */ + async buildWaveStrategyFetchOrderSkuMap(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const orderIds = this.normalizeIdsInput(params.orderIds || []); + if (orderIds.length === 0) { + return new Map(); + } + + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + if (!orderItemsModel || typeof orderItemsModel.findAll !== 'function') { + throw new Error('订单明细模型不可用'); + } + + const itemRows = await orderItemsModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + const rowMap = new Map(); + for (const row of (Array.isArray(itemRows) ? itemRows : [])) { + const orderId = Number(row && row.order_id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + if (!rowMap.has(orderId)) { + rowMap.set(orderId, []); + } + rowMap.get(orderId).push(row); + } + + const skuMap = new Map(); + for (const orderId of orderIds) { + const detailRows = rowMap.get(orderId) || []; + const detailList = this.mergeOrderItemDetails(detailRows); + const skuSet = new Set(); + + detailList.forEach(item => { + const itemCode = String(item && item.item_code || '').trim(); + const stockId = Number(item && item.stock_id || 0); + if (itemCode) { + skuSet.add(itemCode); + return; + } + if (Number.isInteger(stockId) && stockId > 0) { + skuSet.add(`stock_${stockId}`); + } + }); + + skuMap.set(orderId, skuSet); + } + + return skuMap; + } + + /** + * 先拣后分模式按 SKU 上限筛选订单。 + * + * 当 SKU 种类超限时,循环剔除“出现频率最低”的 SKU, + * 每次剔除该 SKU 对应的全部订单,直到 SKU 种类满足上限。 + * + * @param {Object} params 筛选参数。 + * @param {Array} params.orderIds 候选订单ID(升序)。 + * @param {Map>} params.orderSkuMap 订单 SKU 映射。 + * @param {number|string} params.skuLimit SKU 上限。 + * @return {{ selectedOrderIds: Array, removedOrderIds: Array }} 筛选结果。 + */ + selectWaveStrategyFetchOrdersBySkuLimit(params = {}) { + const orderIds = this.normalizeIdsInput(params.orderIds || []); + const orderSkuMap = params.orderSkuMap instanceof Map ? params.orderSkuMap : new Map(); + const skuLimitRaw = Number(params.skuLimit || 0); + const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; + + if (orderIds.length === 0) { + return { + selectedOrderIds: [], + removedOrderIds: [], + }; + } + + if (skuLimit <= 0) { + return { + selectedOrderIds: [], + removedOrderIds: [ ...orderIds ], + }; + } + + const activeOrderSet = new Set(orderIds); + const removedOrderSet = new Set(); + + const buildSkuOrderMap = () => { + const skuOrderMap = new Map(); + for (const orderId of activeOrderSet) { + const skuSet = orderSkuMap.get(orderId) instanceof Set ? orderSkuMap.get(orderId) : new Set(); + for (const sku of skuSet) { + const skuKey = String(sku || '').trim(); + if (!skuKey) { + continue; + } + if (!skuOrderMap.has(skuKey)) { + skuOrderMap.set(skuKey, new Set()); + } + skuOrderMap.get(skuKey).add(orderId); + } + } + return skuOrderMap; + }; + + for (;;) { + const skuOrderMap = buildSkuOrderMap(); + if (skuOrderMap.size <= skuLimit) { + break; + } + + let targetSku = ''; + let minFrequency = Number.MAX_SAFE_INTEGER; + for (const [ sku, orderSet ] of skuOrderMap.entries()) { + const frequency = orderSet.size; + if (frequency < minFrequency) { + minFrequency = frequency; + targetSku = sku; + continue; + } + if (frequency === minFrequency && targetSku && String(sku).localeCompare(String(targetSku)) < 0) { + targetSku = sku; + } + } + + if (!targetSku) { + break; + } + + const targetOrderSet = skuOrderMap.get(targetSku) || new Set(); + for (const orderId of targetOrderSet) { + if (activeOrderSet.has(orderId)) { + activeOrderSet.delete(orderId); + removedOrderSet.add(orderId); + } + } + + if (activeOrderSet.size === 0) { + break; + } + } + + return { + selectedOrderIds: [ ...activeOrderSet ].sort((a, b) => a - b), + removedOrderIds: [ ...removedOrderSet ].sort((a, b) => a - b), + }; + } + + /** + * 在事务内按指定订单创建波次并更新订单波次字段。 + * + * @param {Object} params 创建参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID数组。 + * @param {number|string} params.waveType 波次类型(1-团购,2-散单)。 + * @param {string} params.wavePrefix 波次前缀。 + * @param {number|string} [params.source=0] 波次来源。 + * @param {number|string} [params.pickMode] 拣货模式(1-小团购 2-单品单件 3-先拣后分 4-边拣边分 5-大团购), + * 用于散单波次区分单品单件(pickMode=2 时订单 wave_scope 写入 4)。 + * @param {string} [params.claimOperator] 抓取人姓名:抓取波次(source=1/2)无需领料, + * 将该值冗余写入波次表领料人字段(claim_operator)。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise<{ waveId: number, waveNo: string, selectedOrderIds: Array }>} 创建结果。 + */ + async createWaveBatchByOrderIdsInTransaction(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const waveType = Number(params.waveType || 0) === 2 ? 2 : 1; + const wavePrefix = String(params.wavePrefix || '').trim() || (waveType === 2 ? 'A' : 'B'); + const sourceInput = Number(params.source); + const source = [ 0, 1, 2 ].includes(sourceInput) ? sourceInput : 0; + const pickModeInput = Number(params.pickMode); + const pickMode = [ 1, 2, 3, 4, 5 ].includes(pickModeInput) ? pickModeInput : 0; + const claimOperator = String(params.claimOperator || '').trim() || null; + const claimOperatorId = Number(params.claimOperatorId || 0) > 0 + ? Number(params.claimOperatorId) + : null; + const transaction = params.transaction; + const orderIds = this.normalizeIdsInput(params.orderIds || []); + if (orderIds.length === 0) { + throw new Error('创建波次失败:订单集合不能为空'); + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const lockRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'items_hash', 'items' ], + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + wave_id: 0, + step: { [Op.ne]: 0 }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + // 尾部兜底:候选筛选后再次排除 B2B 订单(NULL 视为非 B2B,兼容存量行) + is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const fetchableOrderIds = [ ...new Set((Array.isArray(lockRows) ? lockRows : []) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ].sort((a, b) => a - b); + + if (fetchableOrderIds.length === 0) { + throw new Error('创建波次失败:候选订单已被占用或状态变化'); + } + + const firstRow = Array.isArray(lockRows) ? lockRows[0] : null; + const itemPart = this.getOrderItemPart(firstRow || {}); + const itemSnapshotKey = `${itemPart.item_part_type}:${itemPart.item_part}`; + const itemDetailMachine = this.buildMachineStructureToken({ + item_part_type: itemPart.item_part_type, + item_part: itemPart.item_part, + distinguish_express: false, + logistics_name: '', + item_snapshot_key: itemSnapshotKey, + }); + + const { waveId, waveNo } = await this.createWaveBatchReady({ + warehouseId, + totalOrders: fetchableOrderIds.length, + itemDetailMachine, + itemPartType: itemPart.item_part_type, + itemPart: itemPart.item_part, + distinguishExpress: false, + logisticsName: '', + itemSnapshotKey, + wavePrefix, + waveType, + source, + transaction, + }); + + await orderModel.update({ + wave_id: waveId, + wave_no: waveNo, + wave_scope: this.resolveWaveScopeByWaveMeta(waveType, source, pickMode), + grab_operator_id: claimOperatorId, + grab_operator: claimOperator, + }, { + where: { + id: { [Op.in]: fetchableOrderIds }, + warehouse_id: warehouseId, + wave_id: 0, + }, + transaction, + }); + + const grabbedRows = await orderModel.findAll({ + where: { + id: { [Op.in]: fetchableOrderIds }, + warehouse_id: warehouseId, + wave_id: waveId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + const grabbedOrderIds = [ ...new Set((Array.isArray(grabbedRows) ? grabbedRows : []) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ].sort((a, b) => a - b); + + if (grabbedOrderIds.length <= 0) { + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + }, + transaction, + }); + throw new Error('创建波次失败:未抓取到有效订单'); + } + + if (grabbedOrderIds.length !== fetchableOrderIds.length) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :totalOrders, + update_time = NOW() + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + totalOrders: grabbedOrderIds.length, + }, + transaction, + }); + } + + // 抓取波次(source=1/2)无需领料:将抓取人冗余写入领料人字段,便于追溯 + if ([ 1, 2 ].includes(source) && claimOperator) { + await this.ctx.model.WaveBatch.update( + { + claim_operator: claimOperator, + claim_time: new Date(), + }, + { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + }, + transaction, + } + ); + + // 领料时间写入会改变确认打印未领单统计,递增版本号驱动长轮询 + await this.bumpConfirmPrintUnclaimedWaveVersion(warehouseId); + } + + await this.rebuildOrderWaveIndex({ + warehouseId, + waveId, + orderIds: grabbedOrderIds, + orderModel, + transaction, + }); + + return { + waveId, + waveNo, + selectedOrderIds: grabbedOrderIds, + }; + } + + /** + * 小团购第一池抓取时合并同结构全池订单(修复「1 单 1 波次」问题)。 + * + * 背景:波次抓取链路将订单池按「今日前 / 今日」分割,第一池非空时只抓第一池; + * 但候选 SQL 的同结构计数子查询为「全池统计」(不限策略、不含池边界), + * 导致某结构第一池仅剩 1 条时仍能通过 min_same_structure 门槛而单独成波。 + * + * 合并口径:针对第一池候选分组中出现过的结构 key(require_same_express=1 时为 + * 「结构+快递」组合,快递口径复用候选 SQL 中 expressExpr 的 COALESCE 优先级), + * 按候选 SQL 中同结构计数子查询的过筛口径(不限策略匹配、不含池边界 create_at 条件) + * 查询同结构全池订单,将两池同结构订单全部并入候选,后续复用既有分组与建波流程。 + * + * 门控条件(任一不满足则返回 null 跳过合并、维持现状): + * - 仅小团购(pickMode === 1)生效,大团购(pickMode === 5)不覆盖; + * - 仅第一池非空(candidatePoolStage === 'first')时生效; + * - 仅 max_same_structure 已设置且有效(正整数且非 999)时生效, + * 未设置(null/999)的团购策略跳过合并; + * - 同结构全池查询无新增订单(如该结构订单全部在第一池)时不合并。 + * + * @param {Object} params 合并参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} params.strategyRow 策略行。 + * @param {Array} params.candidateRows 当前候选订单(第一池)。 + * @param {Array} params.effectiveGroupedRows 第一池候选分组结果。 + * @param {string} params.candidatePoolStage 候选池阶段(first-第一池/second-第二池)。 + * @param {number|string} params.pickMode 拣货模式。 + * @param {boolean} params.requireSameExpress 是否要求同快递。 + * @param {Object} params.transaction 事务对象(合并查询与后续建波共用同一事务)。 + * @return {Promise|null>} 合并后的候选订单数组;跳过合并时返回 null。 + */ + async mergeWaveStrategyFirstPoolSameStructureOrders(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; + const candidateRows = Array.isArray(params.candidateRows) ? params.candidateRows : []; + const effectiveGroupedRows = Array.isArray(params.effectiveGroupedRows) ? params.effectiveGroupedRows : []; + const candidatePoolStage = String(params.candidatePoolStage || '').trim(); + const pickMode = Number(params.pickMode || 0); + const requireSameExpress = Boolean(params.requireSameExpress); + const transaction = params.transaction; + + // 门控一:仅小团购(pickMode=1)且第一池非空时执行合并 + if (pickMode !== 1 || candidatePoolStage !== 'first') { + return null; + } + + // 门控二:max_same_structure 未设置(null/999)时跳过合并,维持现状; + // 已设置有效的策略保存期已被钳制到 min-1,合并后天然受限,无需额外截断。 + const maxSameStructureRaw = Number(strategyRow.max_same_structure); + const maxSameStructureConfigured = Number.isInteger(maxSameStructureRaw) + && maxSameStructureRaw > 0 + && maxSameStructureRaw !== 999; + if (!maxSameStructureConfigured) { + return null; + } + + // 收集第一池候选分组中出现过的结构 key; + // require_same_express=1 时同时收集快递 key(分组均来自最大快递组,快递 key 唯一)。 + const structureKeySet = new Set(); + const expressKeySet = new Set(); + for (const group of effectiveGroupedRows) { + const structureKey = String(group && group.structure_key || '').trim(); + if (!structureKey) { + continue; + } + structureKeySet.add(structureKey); + if (requireSameExpress) { + const groupOrders = Array.isArray(group && group.orders) ? group.orders : []; + const expressKey = groupOrders.length > 0 + ? this.getWaveStrategyQuickScanExpressKey(groupOrders[0]) + : ''; + if (expressKey) { + expressKeySet.add(expressKey); + } + } + } + + const structureKeys = [ ...structureKeySet ].sort(); + const expressKeys = [ ...expressKeySet ].sort(); + if (structureKeys.length === 0 || (requireSameExpress && expressKeys.length === 0)) { + return null; + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const structureExpr = alias => `${alias}.items_hash`; + const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; + const expressCondition = requireSameExpress ? ` AND ${expressExpr('o')} IN (:expressKeys)` : ''; + const replacements = { + warehouseId, + structureKeys, + }; + if (requireSameExpress) { + replacements.expressKeys = expressKeys; + } + + // 复用候选 SQL 同结构计数子查询的过筛口径:不限策略匹配、不含池边界 create_at 条件, + // 将两池同结构订单全部取出;查询与建波共用同一事务,行锁与 wave_id=0 复筛由建波流程负责。 + const rows = await this.ctx.model.query(` + SELECT + o.id, + o.items_hash, + o.items, + o.logistics_name, + o.sys_logistics_code, + o.logistics_code, + o.items_count, + o.items_total + FROM ${orderTableName} o + WHERE o.warehouse_id = :warehouseId + AND o.wave_id = 0 + AND o.step != 0 + AND o.post_status = 'fin' + AND o.storage_status = 'fin' + AND o.print_status != 'fin' + AND o.status != 'cancel' + AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' + AND (o.is_b2b IS NULL OR o.is_b2b = 'N') + AND (o.has_sn_item IS NULL OR o.has_sn_item <> 'Y') + AND ${structureExpr('o')} IN (:structureKeys)${expressCondition} + ORDER BY o.id ASC + `, { + replacements, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + // 行归一化口径与 getWaveStrategyFetchCandidateOrders 保持一致 + const mergedRows = (Array.isArray(rows) ? rows : []) + .map(row => ({ + id: Number(row && row.id || 0), + items_hash: String(row && row.items_hash || '').trim(), + items: String(row && row.items || '').trim(), + logistics_name: String(row && row.logistics_name || '').trim(), + sys_logistics_code: String(row && row.sys_logistics_code || '').trim(), + logistics_code: String(row && row.logistics_code || '').trim(), + items_count: Number(row && row.items_count || 0), + items_total: Number(row && row.items_total || 0), + })) + .filter(row => Number.isInteger(row.id) && row.id > 0) + .sort((a, b) => a.id - b.id); + + if (mergedRows.length === 0) { + return null; + } + + // 合并订单并入候选(按 id 去重,第一池候选与全池查询结果存在重叠) + const candidateIdSet = new Set(candidateRows.map(row => Number(row && row.id || 0))); + const mergedCandidateRows = [ + ...candidateRows, + ...mergedRows.filter(row => !candidateIdSet.has(row.id)), + ].sort((a, b) => Number(a.id || 0) - Number(b.id || 0)); + + // 无新增订单时视为无需合并,返回 null 维持现状 + if (mergedCandidateRows.length <= candidateRows.length) { + return null; + } + + return mergedCandidateRows; + } + + /** + * 自动补齐按策略抓取的 selected_wave_ids / selected_order_ids。 + * + * 仅用于 PDA 按策略抓取场景,内部按 strategy_type + pick_mode 执行分流。 + * + * 候选订单按创建时间分割为两个订单池: + * - 第一订单池:创建时间早于今日 0 点(前一天及更早订单); + * - 第二订单池:其余订单(今日订单)。 + * 只有第一订单池抓取完毕(候选为空)才会抓取第二订单池,确保前一天的订单优先出库。 + * + * 小团购(pickMode=1)第一池抓取时,会将第一池候选分组中同结构的全池订单并入候选 + * (见 mergeWaveStrategyFirstPoolSameStructureOrders),避免同结构订单被两池分割后单独成波。 + * + * @param {Object} params 自动分流参数。 + * @param {Object} params.plan 抓取计划。 + * @param {Object} params.strategyRow 策略行。 + * @param {number|string} [params.waveBatchSource=0] 波次来源。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 自动补齐结果。 + */ + async autoPopulateWaveStrategyFetchSelections(params = {}) { + const plan = this.isPlainObject(params.plan) ? params.plan : {}; + const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; + const transaction = params.transaction; + const waveBatchSourceInput = Number(params.waveBatchSource); + const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; + + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const strategyId = this.normalizeRequiredPositiveInteger(plan.strategy_id, 'strategy_id'); + const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); + const strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0); + const operatorInfo = this.isPlainObject(plan.operator) ? plan.operator : {}; + const operatorId = Number((operatorInfo.operator_id ?? operatorInfo.id) || 0); + const claimOperator = String(operatorInfo.operator_name || operatorInfo.name || '').trim() || null; + const claimOperatorId = operatorId > 0 ? operatorId : null; + + await this.ensureNoActiveWavePickTaskForOperator({ + warehouseId, + operatorId, + transaction, + }); + + const candidateQueryParams = { + warehouseId, + strategyId, + minSameStructure: strategyRow.min_same_structure, + maxSameStructure: strategyRow.max_same_structure, + requireSameExpress: Number(strategyRow.require_same_express || 0), + strategyType, + }; + + // 订单池分割:第一订单池 = 创建时间早于今日 0 点(前一天及更早订单), + // 只有第一订单池抓取完毕(候选为空)才允许抓取第二订单池, + // 确保前一天的订单可以优先出库。 + const todayStart = this.buildWaveStrategyFetchTodayStart(); + const firstPoolRows = await this.getWaveStrategyFetchCandidateOrders({ + ...candidateQueryParams, + createdBefore: todayStart, + }); + + let candidateRows; + let candidatePoolStage = 'second'; + if (firstPoolRows.length > 0) { + candidateRows = firstPoolRows; + candidatePoolStage = 'first'; + } else { + candidateRows = await this.getWaveStrategyFetchCandidateOrders(candidateQueryParams); + } + + const candidateCount = candidateRows.length; + if (candidateCount <= 0) { + throw new Error('未找到符合策略且未分配波次的候选订单'); + } + + const groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); + if (groupedRows.length <= 0) { + throw new Error('候选订单缺少有效商品结构,无法创建波次'); + } + + const result = { + selected_wave_ids: [], + selected_order_ids: [], + removed_order_ids: [], + candidate_count: candidateCount, + candidate_pool_stage: candidatePoolStage, + first_pool_candidate_count: firstPoolRows.length, + grouped_count: groupedRows.length, + merged_order_count: 0, + wave_prefix: '', + wave_prefix_source: '', + }; + + const wavePrefixResolution = await this.resolveWaveStrategyFetchWavePrefix({ + warehouseId, + strategyType, + strategyRow, + }); + result.wave_prefix = wavePrefixResolution.wavePrefix; + result.wave_prefix_source = wavePrefixResolution.source; + + if (strategyType === 2) { + const requireSameExpress = Number(strategyRow.require_same_express || 0) === 1; + let effectiveGroupedRows = requireSameExpress + ? this.groupWaveStrategyFetchCandidateOrdersByStructure( + this.filterCandidateOrdersByRequireSameExpress(candidateRows) + ) + : groupedRows; + + // 小团购(pickMode=1)第一池抓取:将同结构全池订单并入候选,修复「1 单 1 波次」问题。 + // 合并受 pickMode=1 + 第一池阶段 + max_same_structure 有效三重门控; + // pickMode=5(大团购)不生效,admin 抓取入口(executeWaveStrategyDirectFetch)不经过本方法。 + const mergedCandidateRows = await this.mergeWaveStrategyFirstPoolSameStructureOrders({ + warehouseId, + strategyRow, + candidateRows, + effectiveGroupedRows, + candidatePoolStage, + pickMode, + requireSameExpress, + transaction, + }); + if (mergedCandidateRows !== null) { + result.merged_order_count = mergedCandidateRows.length - candidateRows.length; + effectiveGroupedRows = requireSameExpress + ? this.groupWaveStrategyFetchCandidateOrdersByStructure( + this.filterCandidateOrdersByRequireSameExpress(mergedCandidateRows) + ) + : this.groupWaveStrategyFetchCandidateOrdersByStructure(mergedCandidateRows); + } + + const groupLimitRaw = Number(strategyRow.group_batch_max_orders || plan.box_limit || 0); + const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; + const selectedGroups = effectiveGroupedRows + .slice(0, groupLimit); + if (selectedGroups.length === 0) { + throw new Error('团购策略未找到可创建波次的同结构分组'); + } + + for (const group of selectedGroups) { + const created = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: group.order_ids, + waveType: 1, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + claimOperator, + claimOperatorId, + transaction, + }); + result.selected_wave_ids.push(created.waveId); + result.selected_order_ids.push(...created.selectedOrderIds); + } + + if (result.selected_wave_ids.length <= 0) { + throw new Error('团购策略创建波次失败:无有效波次生成'); + } + } else if (strategyType === 1 || strategyType === 3) { + const effectiveCandidateRows = Number(strategyRow.require_same_express || 0) === 1 + ? this.filterCandidateOrdersByRequireSameExpress(candidateRows) + : candidateRows; + const effectiveGroupedRows = effectiveCandidateRows === candidateRows + ? groupedRows + : this.groupWaveStrategyFetchCandidateOrdersByStructure(effectiveCandidateRows); + + const mergedOrderIds = [ ...new Set(effectiveGroupedRows + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + if (mergedOrderIds.length === 0) { + throw new Error('散单/SN 策略无可用候选订单'); + } + + const orderLimitRaw = Number(plan.order_limit || strategyRow.batch_max_orders || 0); + const orderLimit = Number.isInteger(orderLimitRaw) && orderLimitRaw > 0 ? orderLimitRaw : 0; + let selectedOrderIds = []; + + if (pickMode === 3) { + const skuMap = await this.buildWaveStrategyFetchOrderSkuMap({ + warehouseId, + orderIds: mergedOrderIds, + }); + const skuLimitRaw = Number(plan.sku_limit || strategyRow.batch_max_skus || 0); + const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; + const skuResult = this.selectWaveStrategyFetchOrdersBySkuLimit({ + orderIds: mergedOrderIds, + orderSkuMap: skuMap, + skuLimit, + }); + result.removed_order_ids = skuResult.removedOrderIds; + selectedOrderIds = skuResult.selectedOrderIds; + } else if (pickMode === 4 || pickMode === 2) { + selectedOrderIds = mergedOrderIds; + } else { + throw new Error(`散单/SN 策略不支持的 pick_mode: ${pickMode}`); + } + + if (selectedOrderIds.length <= 0) { + throw new Error('散单/SN 策略筛选后无可用订单(候选可能已被剔除)'); + } + + const limitedOrderIds = orderLimit > 0 + ? selectedOrderIds.slice(0, orderLimit) + : selectedOrderIds; + if (limitedOrderIds.length <= 0) { + throw new Error('散单/SN 策略筛选后无可用订单(batch_max_orders 限制导致为空)'); + } + + const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: limitedOrderIds, + waveType: 2, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + pickMode, + claimOperator, + claimOperatorId, + transaction, + }); + + result.selected_wave_ids.push(createdWave.waveId); + result.selected_order_ids.push(...createdWave.selectedOrderIds); + if (result.selected_wave_ids.length <= 0) { + throw new Error('散单/SN 策略创建波次失败:无有效波次生成'); + } + } else { + throw new Error(`不支持的策略类型: ${strategyType}`); + } + + result.selected_wave_ids = [ ...new Set(result.selected_wave_ids) ].sort((a, b) => a - b); + result.selected_order_ids = [ ...new Set(result.selected_order_ids) ].sort((a, b) => a - b); + + this.ctx.logger.info('[wave.autoPopulateWaveStrategyFetchSelections] 自动分流完成', { + strategy_id: strategyId, + warehouse_id: warehouseId, + pick_mode: pickMode, + strategy_type: strategyType, + wave_prefix: result.wave_prefix, + wave_prefix_source: result.wave_prefix_source, + candidate_count: result.candidate_count, + candidate_pool_stage: result.candidate_pool_stage, + first_pool_candidate_count: result.first_pool_candidate_count, + merged_order_count: result.merged_order_count, + today_start: todayStart, + removed_count: result.removed_order_ids.length, + selected_count: result.selected_order_ids.length, + selected_wave_count: result.selected_wave_ids.length, + }); + + return result; + } + + /** + * 按策略直接抓取候选订单并创建波次(不创建拣货任务)。 + * + * 在一个事务内完成候选查询、分组与建波: + * - 团购策略(strategy_type=2):每个结构分组创建一个波次; + * - 散单策略(strategy_type=1):合并全部候选订单后创建一个散单波次; + * - SN 策略(strategy_type=3):只抓 SN 订单,与散单同形态建波并固定 pick_mode=3(先拣后分)。 + * + * @param {Object} params 执行参数。 + * @param {Object} params.plan 预处理计划。 + * @param {Object} [params.strategyRow={}] 策略行(可选,默认取 plan.strategy_row)。 + * @param {number|string} [params.waveBatchSource=0] 波次来源:0-普通波次 1-管理后台策略抓取 2-PDA策略抓取。 + * @return {Promise} 建波结果汇总。 + */ + async executeWaveStrategyDirectFetch(params = {}) { + const plan = this.isPlainObject(params && params.plan) ? params.plan : {}; + const strategyRow = this.isPlainObject(params && params.strategyRow) + ? params.strategyRow + : (this.isPlainObject(plan.strategy_row) ? plan.strategy_row : {}); + const waveBatchSourceInput = Number(params && params.waveBatchSource); + const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; + + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const strategyId = this.normalizeRequiredPositiveInteger(plan.strategy_id, 'strategy_id'); + const strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0); + const pickModeInput = Number(plan.pick_mode || 0); + const pickMode = [ 1, 2, 3, 4, 5 ].includes(pickModeInput) ? pickModeInput : 0; + const operatorInfo = this.isPlainObject(plan.operator) ? plan.operator : {}; + const claimOperator = String(operatorInfo.operator_name || operatorInfo.name || '').trim() || null; + const claimOperatorId = Number((operatorInfo.operator_id ?? operatorInfo.id) || 0) > 0 + ? Number((operatorInfo.operator_id ?? operatorInfo.id)) + : null; + const transaction = await this.ctx.model.transaction(); + + try { + const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ + warehouseId, + strategyId, + minSameStructure: strategyRow.min_same_structure, + maxSameStructure: strategyRow.max_same_structure, + requireSameExpress: Number(strategyRow.require_same_express || 0), + strategyType, + }); + // getWaveStrategyFetchCandidateOrders 已按策略类型过滤 SN 订单(3 只取 SN,1/2 排除 SN) + const candidateCount = candidateRows.length; + if (candidateCount <= 0) { + throw new Error('未找到符合策略且未分配波次的候选订单'); + } + + const groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); + if (groupedRows.length <= 0) { + throw new Error('候选订单缺少有效商品结构,无法创建波次'); + } + + const wavePrefixResolution = await this.resolveWaveStrategyFetchWavePrefix({ + warehouseId, + strategyType, + strategyRow, + }); + + const createdWaveIds = []; + const createdWaveNos = []; + const createdOrderIds = []; + + if (strategyType === 2) { + const effectiveGroupedRows = Number(strategyRow.require_same_express || 0) === 1 + ? this.groupWaveStrategyFetchCandidateOrdersByStructure( + this.filterCandidateOrdersByRequireSameExpress(candidateRows) + ) + : groupedRows; + for (const group of effectiveGroupedRows) { + const created = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: group.order_ids, + waveType: 1, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + claimOperator, + claimOperatorId, + transaction, + }); + createdWaveIds.push(created.waveId); + createdWaveNos.push(created.waveNo); + createdOrderIds.push(...created.selectedOrderIds); + } + } else if (strategyType === 1 || strategyType === 3) { + const effectiveCandidateRows = Number(strategyRow.require_same_express || 0) === 1 + ? this.filterCandidateOrdersByRequireSameExpress(candidateRows) + : candidateRows; + const effectiveGroupedRows = effectiveCandidateRows === candidateRows + ? groupedRows + : this.groupWaveStrategyFetchCandidateOrdersByStructure(effectiveCandidateRows); + + const mergedOrderIds = [ ...new Set(effectiveGroupedRows + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + if (mergedOrderIds.length <= 0) { + throw new Error('散单/SN 策略无可用候选订单'); + } + + const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: mergedOrderIds, + waveType: 2, + wavePrefix: wavePrefixResolution.wavePrefix, + source: waveBatchSource, + pickMode, + claimOperator, + claimOperatorId, + transaction, + }); + createdWaveIds.push(createdWave.waveId); + createdWaveNos.push(createdWave.waveNo); + createdOrderIds.push(...createdWave.selectedOrderIds); + } else { + throw new Error(`不支持的策略类型: ${strategyType}`); + } + + const normalizedWaveIds = [ ...new Set(createdWaveIds) ].sort((a, b) => a - b); + const normalizedWaveNos = [ ...new Set(createdWaveNos.map(item => String(item || '').trim()).filter(Boolean)) ]; + const normalizedOrderIds = [ ...new Set(createdOrderIds) ].sort((a, b) => a - b); + + if (normalizedWaveIds.length <= 0 || normalizedOrderIds.length <= 0) { + throw new Error('按策略抓取建波失败:未生成有效波次或订单结果'); + } + + const result = { + wave_ids: normalizedWaveIds, + wave_nos: normalizedWaveNos, + order_ids: normalizedOrderIds, + created_wave_count: normalizedWaveIds.length, + created_order_count: normalizedOrderIds.length, + wave_prefix: wavePrefixResolution.wavePrefix, + wave_prefix_source: wavePrefixResolution.source, + candidate_count: candidateCount, + grouped_count: groupedRows.length, + strategy_type: strategyType, + }; + + await transaction.commit(); + + // 写入订单操作日志:策略抓取分配到波次 + const strategyLogItems = normalizedOrderIds.map(orderId => ({ + orderId, + operationCode: 'ORDER_WAVE_STRATEGY_FETCH', + message: `策略(${strategyId})抓取分配到波次 ${normalizedWaveNos.join(',')}`, + })); + await this.batchCreateOrderOperationLogs(strategyLogItems, { + warehouseId, + scene: 'executeWaveStrategyDirectFetch', + }); + + this.ctx.logger.info('[wave.executeWaveStrategyDirectFetch] 按策略直接建波完成', { + strategy_id: strategyId, + warehouse_id: warehouseId, + strategy_type: strategyType, + wave_prefix: result.wave_prefix, + wave_prefix_source: result.wave_prefix_source, + candidate_count: result.candidate_count, + grouped_count: result.grouped_count, + created_wave_count: result.created_wave_count, + created_order_count: result.created_order_count, + }); + + return result; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 执行按策略抓取任务创建主流程。 + * + * 该方法在一个事务内完成任务主表、明细表、断点与日志的初始化写入。 + * + * @param {Object} params 创建参数。 + * @param {Object} params.plan 预处理后的抓取计划。 + * @param {Object} [params.data={}] 原始请求数据。 + * @param {number|string} [params.waveBatchSource=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 + * @return {Promise} 创建结果。 + */ + async createWavePickTaskFromPlan(params = {}) { + const plan = this.isPlainObject(params && params.plan) ? params.plan : {}; + const requestData = this.isPlainObject(params && params.data) ? params.data : {}; + const autoPopulateSelections = Boolean(params && params.autoPopulateSelections); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); + const waveBatchSourceInput = Number( + params && params.waveBatchSource !== undefined ? params.waveBatchSource : plan.wave_batch_source + ); + const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; + let effectivePlan = { + ...plan, + }; + let effectiveRequestData = { + ...requestData, + }; + const hasExplicitWaveSelectionInput = [ + 'selected_wave_ids', + 'selectedWaveIds', + 'wave_ids', + 'waveIds', + 'wave_id', + 'waveId', + ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); + const hasExplicitOrderSelectionInput = [ + 'selected_order_ids', + 'selectedOrderIds', + 'order_ids', + 'orderIds', + ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); + const hasManualSelectionInput = this.normalizeIdsInput(plan.selected_wave_ids || []).length > 0 + || hasExplicitWaveSelectionInput + || hasExplicitOrderSelectionInput; + + const normalizedCartId = this.normalizePositiveInteger( + effectiveRequestData.cart_id ?? effectiveRequestData.cartId, + 'cart_id', + 0 + ); + const transaction = await this.ctx.model.transaction(); + + try { + if (autoPopulateSelections && !hasManualSelectionInput) { + const autoFilled = await this.autoPopulateWaveStrategyFetchSelections({ + plan: effectivePlan, + strategyRow: effectivePlan.strategy_row, + waveBatchSource, + transaction, + }); + + effectivePlan = { + ...effectivePlan, + selected_wave_ids: autoFilled.selected_wave_ids, + box_assignments: this.buildWaveStrategyFetchBoxAssignments({ + pickMode, + selectedWaveIds: autoFilled.selected_wave_ids, + boxLimit: Number(effectivePlan.box_limit || 0), + }), + }; + effectiveRequestData = { + ...effectiveRequestData, + selected_wave_ids: autoFilled.selected_wave_ids, + selected_order_ids: autoFilled.selected_order_ids, + }; + } + + const selectedWaveIds = this.normalizeIdsInput(effectivePlan.selected_wave_ids || []); + const selectedOrderIds = this.normalizeIdsInput( + effectiveRequestData.selected_order_ids !== undefined + ? effectiveRequestData.selected_order_ids + : effectiveRequestData.selectedOrderIds !== undefined + ? effectiveRequestData.selectedOrderIds + : effectiveRequestData.order_ids !== undefined + ? effectiveRequestData.order_ids + : effectiveRequestData.orderIds + ); + + const validationErrors = Array.isArray(effectivePlan.validation_errors) + ? [ ...effectivePlan.validation_errors ] + : []; + if ([ 1, 5 ].includes(pickMode) && selectedWaveIds.length === 0) { + validationErrors.push('当前模式依赖波次,selected_wave_ids 不能为空'); + } + if ([ 2, 3, 4 ].includes(pickMode) && selectedOrderIds.length === 0) { + validationErrors.push('当前模式至少需要一个订单,selected_order_ids 不能为空'); + } + if (validationErrors.length > 0) { + throw new Error(`按策略抓取任务创建校验失败: ${validationErrors.join(';')}`); + } + + if (normalizedCartId > 0) { + await this.ensurePickCartAvailable({ + cartId: normalizedCartId, + warehouseId, + transaction, + }); + } + + // 查询所有选中波次的 wave_no(用于任务主表 batch_no_array 与任务波次关联记录) + const waveNoMap = new Map(); + if (selectedWaveIds.length > 0) { + const waveNoRows = await this.ctx.model.query( + `SELECT wave_id, wave_no + FROM wms_wave_batch + WHERE wave_id IN (:waveIds) + AND warehouse_id = :warehouseId`, + { + replacements: { waveIds: selectedWaveIds, warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + for (const row of Array.isArray(waveNoRows) ? waveNoRows : []) { + const wid = Number(row && row.wave_id || 0); + const wno = String(row && row.wave_no || '').trim(); + if (wid > 0 && wno) { + waveNoMap.set(wid, wno); + } + } + } + + // 散单模式:取第一个选中波次的 wave_no 写入任务 batch_no + const resolvedBatchNo = [ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 0 + ? (waveNoMap.get(selectedWaveIds[0]) || null) + : null; + + const taskPayload = this.buildTaskCreatePayload({ + plan: effectivePlan, + data: effectiveRequestData, + selectedWaveIds, + selectedOrderIds, + cartId: normalizedCartId, + }); + if (resolvedBatchNo !== null) { + taskPayload.batch_no = resolvedBatchNo; + } + // 逗号分隔写入任务主表 batch_no_array,便于统计与查询 + const batchNoArray = selectedWaveIds + .map(waveId => waveNoMap.get(waveId) || '') + .filter(Boolean) + .join(','); + if (batchNoArray) { + taskPayload.batch_no_array = batchNoArray; + } + + if (selectedWaveIds.length > 0 && [ 1, 2 ].includes(waveBatchSource)) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET source = :source, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + source: waveBatchSource, + warehouseId, + waveIds: selectedWaveIds, + }, + transaction, + }); + } + + const taskCreateResult = await this.createWavePickTaskWithRetry(taskPayload, transaction); + const taskId = Number(taskCreateResult.task_id || 0); + const taskNo = String(taskCreateResult.task_no || '').trim(); + + const taskWaveRows = this.buildTaskWaveRows({ + taskId, + plan: effectivePlan, + selectedWaveIds, + waveNoMap, + }); + // 查询波次索引(wave_index),使 box_no 与 wms_order_wave_index.wave_index 一致 + const waveIndexMap = new Map(); + if (selectedOrderIds.length > 0 && selectedWaveIds.length > 0) { + try { + const waveIndexRows = await this.ctx.model.query( + `SELECT order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND order_id IN (:orderIds)`, + { + replacements: { + warehouseId, + waveIds: selectedWaveIds, + orderIds: selectedOrderIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) { + const wrOrderId = Number(wr && wr.order_id || 0); + if (wrOrderId > 0) { + waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0)); + } + } + } catch (e) { + this.ctx.logger.warn('[wave.createTask] 查询波次索引失败,box_no 将退化为任务内序号', { + error: e && e.message, + warehouseId, + waveIds: selectedWaveIds, + }); + } + } + + const taskOrderRows = this.buildTaskOrderRows({ + taskId, + plan: effectivePlan, + selectedWaveIds, + selectedOrderIds, + cartId: normalizedCartId, + waveIndexMap, + }); + const taskSkuRows = await this.buildTaskSkuRows({ + plan: effectivePlan, + selectedOrderIds, + }); + const taskBoxRows = this.buildTaskBoxRows({ + taskId, + taskNo, + plan: effectivePlan, + taskWaveRows, + taskOrderRows, + taskSkuRows, + }); + + if (taskWaveRows.length > 0) { + await this.bulkInsertRows('wms_wave_pick_task_wave', taskWaveRows, transaction); + } + if (taskOrderRows.length > 0) { + await this.bulkInsertRows('wms_wave_pick_task_order', taskOrderRows, transaction); + } + if (taskBoxRows.length > 0) { + await this.bulkInsertRows('wms_wave_pick_task_box', taskBoxRows, transaction); + } + + if (normalizedCartId > 0) { + await this.bindPickCartForTask({ + taskId, + cartId: normalizedCartId, + warehouseId, + operatorId: taskPayload.pick_user_id, + transaction, + }); + } + + await this.initTaskCheckpointAndLogs({ + taskId, + taskNo, + plan: effectivePlan, + data: effectiveRequestData, + selectedOrderIds, + cartId: normalizedCartId, + operatorId: taskPayload.pick_user_id, + operatorName: taskPayload.pick_user_name, + transaction, + }); + + await transaction.commit(); + + // 写入订单操作日志:分配到波次 + if (selectedOrderIds.length > 0) { + const waveNoList = taskWaveRows + .map(r => String(r && r.wave_no || '').trim()) + .filter(Boolean); + const waveNoMessage = waveNoList.length > 0 ? waveNoList.join(',') : ''; + await this.batchCreateOrderOperationLogs( + selectedOrderIds.map(orderId => ({ + orderId, + operationCode: 'ORDER_WAVE_ASSIGN', + message: `分配到波次 ${waveNoMessage}`, + })), + { warehouseId, scene: 'createWavePickTaskFromPlan' } + ); + } + + return { + task_id: taskId, + task_no: taskNo, + state: 'created', + plan_summary: { + pick_mode: pickMode, + wave_count: taskWaveRows.length, + order_count: taskOrderRows.length, + box_count: taskBoxRows.length, + cart_id: normalizedCartId > 0 ? normalizedCartId : null, + }, + }; + } catch (error) { + const errorDetail = { + name: String(error && error.name || ''), + message: String(error && error.message || ''), + stack: String(error && error.stack || '').split('\n').slice(0, 6) + .join('\n'), + sql: String(error && error.sql || '').slice(0, 500), + errorType: Object.prototype.toString.call(error), + errors: Array.isArray(error && error.errors) + ? error.errors.map(e => ({ message: e.message, type: e.type, path: e.path, value: e.value })) + : [], + }; + this.ctx.logger.error('[wave.createWavePickTaskFromPlan] 任务创建异常详情', errorDetail); + await transaction.rollback(); + throw error; + } + } + + /** + * 构建任务主表写入载荷。 + * + * @param {Object} options 构建参数。 + * @param {Object} options.plan 预处理计划。 + * @param {Object} options.data 原始请求数据。 + * @param {Array} options.selectedWaveIds 已选波次ID。 + * @param {Array} options.selectedOrderIds 已选订单ID。 + * @param {number} options.cartId 拣货车ID。 + * @return {Object} 主表写入载荷。 + */ + buildTaskCreatePayload(options = {}) { + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const data = this.isPlainObject(options && options.data) ? options.data : {}; + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) + ? options.selectedOrderIds + : []; + const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const source = String(plan.source || 'unknown').trim(); + const sourceCode = source === 'admin' ? 2 : 1; + + const operator = this.isPlainObject(plan.operator) ? plan.operator : {}; + const rawOperatorId = operator.operator_id ?? operator.id; + const normalizedOperatorId = Number(rawOperatorId); + const pickUserId = Number.isInteger(normalizedOperatorId) && normalizedOperatorId >= 0 + ? normalizedOperatorId + : 0; + const pickUserName = String(operator.operator_name || operator.name || this.getOrderLogOperator().name || 'system').trim() || 'system'; + const taskNo = String(data.task_no || '').trim() || this.generateWavePickTaskNo(warehouseId, sourceCode); + + return { + task_no: taskNo, + warehouse_id: warehouseId, + wave_id: selectedWaveIds.length > 0 ? selectedWaveIds[0] : null, + pick_mode: pickMode, + status: 0, + source: sourceCode, + wave_count: selectedWaveIds.length, + order_count: selectedOrderIds.length, + box_count: pickMode === 5 ? 1 : 0, + batch_no: null, + batch_no_array: null, + pick_user_id: pickUserId, + pick_user_name: pickUserName, + current_cart_id: Number(options && options.cartId || 0) > 0 ? Number(options.cartId) : null, + current_cart_code_snapshot: null, + review_status: 0, + review_version: 0, + device_id: String(data.device_id || data.deviceId || '').trim() || `wave_${source}_${warehouseId}`, + ext_json: JSON.stringify({ + strategy_id: plan.strategy_id, + wave_limit: Number(plan.wave_limit || 0), + order_limit: Number(plan.order_limit || 0), + sku_limit: Number(plan.sku_limit || 0), + box_limit: Number(plan.box_limit || 0), + dynamic_append: Boolean(plan.dynamic_append), + }), + }; + } + + /** + * 构建任务波次关联写入行。 + * + * @param {Object} options 构建参数。 + * @param {number} options.taskId 任务ID。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.selectedWaveIds 已选波次ID。 + * @param {Map} [options.waveNoMap] wave_id → wave_no 映射。 + * @return {Array} 任务波次关联行。 + */ + buildTaskWaveRows(options = {}) { + const taskId = Number(options && options.taskId || 0); + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const waveNoMap = options && options.waveNoMap instanceof Map + ? options.waveNoMap + : new Map(); + + return selectedWaveIds.map((waveId, index) => ({ + task_id: taskId, + wave_id: waveId, + wave_no: waveNoMap.get(waveId) || null, + box_no: index + 1, + status: 0, + bind_time: null, + pick_time: null, + warehouse_id: warehouseId, + })); + } + + /** + * 构建任务订单明细写入行。 + * + * box_no 与 wms_order_wave_index.wave_index 保持一致(波次内全局顺序)。 + * 若 waveIndexMap 中无对应记录,则退化为当前订单在 selectedOrderIds 中的 index + 1。 + * + * @param {Object} options 构建参数。 + * @param {number} options.taskId 任务ID。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.selectedWaveIds 已选波次ID。 + * @param {Array} options.selectedOrderIds 已选订单ID。 + * @param {number} options.cartId 绑定车ID。 + * @param {Map} [options.waveIndexMap] orderId → wave_index 映射。 + * @return {Array} 任务订单行。 + */ + buildTaskOrderRows(options = {}) { + const taskId = Number(options && options.taskId || 0); + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const pickMode = Number(plan.pick_mode || 0); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) + ? options.selectedOrderIds + : []; + const cartId = Number(options && options.cartId || 0); + const waveIndexMap = options && options.waveIndexMap instanceof Map + ? options.waveIndexMap + : new Map(); + + if (![ 2, 3, 4 ].includes(pickMode)) { + return []; + } + + const defaultWaveId = selectedWaveIds.length > 0 ? selectedWaveIds[0] : null; + return selectedOrderIds.map((orderId, index) => { + const waveIndex = waveIndexMap.has(orderId) + ? Number(waveIndexMap.get(orderId) || 0) + : 0; + return { + task_id: taskId, + wave_id: defaultWaveId, + order_id: orderId, + order_no: null, + box_no: waveIndex > 0 ? waveIndex : (index + 1), + cart_id: cartId > 0 ? cartId : null, + cart_code_snapshot: null, + warehouse_id: warehouseId, + pick_status: 0, + review_status: 0, + review_user_id: null, + review_result: null, + review_remark: null, + exception_reason: null, + picked_time: null, + review_time: null, + }; + }); + } + + /** + * 构建任务 SKU 明细写入行(仅先拣后分模式使用)。 + * + * @param {Object} options 构建参数。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.selectedOrderIds 已选订单ID。 + * @return {Promise>} 任务 SKU 行。 + */ + async buildTaskSkuRows(options = {}) { + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const pickMode = Number(plan.pick_mode || 0); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) + ? this.normalizeIdsInput(options.selectedOrderIds) + : []; + + if (pickMode !== 3 || selectedOrderIds.length <= 0) { + return []; + } + + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + if (!orderItemsModel || typeof orderItemsModel.findAll !== 'function') { + throw new Error('订单明细模型不可用'); + } + + const itemRows = await orderItemsModel.findAll({ + where: { + order_id: { [Op.in]: selectedOrderIds }, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + const skuMap = new Map(); + for (const row of (Array.isArray(itemRows) ? itemRows : [])) { + const normalized = this.normalizeOrderItemRow(row); + if (normalized.quantity <= 0) { + continue; + } + + const skuId = Number(normalized.stock_id || 0); + const itemCode = String(normalized.item_code || '').trim(); + const itemName = String(normalized.item_name || '').trim(); + if (!(Number.isInteger(skuId) && skuId > 0) && !itemCode) { + continue; + } + + const key = Number.isInteger(skuId) && skuId > 0 ? `stock_${skuId}` : `code_${itemCode}`; + if (!skuMap.has(key)) { + skuMap.set(key, { + sku_id: Number.isInteger(skuId) && skuId > 0 ? skuId : null, + ref_id: Number.isInteger(skuId) && skuId > 0 ? skuId : null, + ref_label: itemName || itemCode || null, + required_qty: 0, + }); + } + + const aggregated = skuMap.get(key); + aggregated.required_qty += normalized.quantity; + if (!aggregated.ref_label && (itemName || itemCode)) { + aggregated.ref_label = itemName || itemCode; + } + } + + return Array.from(skuMap.values()) + .sort((a, b) => { + const leftSkuId = Number(a.sku_id || 0); + const rightSkuId = Number(b.sku_id || 0); + if (leftSkuId !== rightSkuId) { + return leftSkuId - rightSkuId; + } + return String(a.ref_label || '').localeCompare(String(b.ref_label || '')); + }) + .map((row, index) => ({ + box_no: index + 1, + sku_id: row.sku_id, + ref_id: row.ref_id, + ref_label: row.ref_label, + required_qty: Number(row.required_qty || 0), + })); + } + + /** + * 构建任务框明细写入行。 + * + * @param {Object} options 构建参数。 + * @param {number} options.taskId 任务ID。 + * @param {string} options.taskNo 任务编号。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.taskWaveRows 任务波次行。 + * @param {Array} options.taskOrderRows 任务订单行。 + * @param {Array} options.taskSkuRows 任务 SKU 行。 + * @return {Array} 任务框行。 + */ + buildTaskBoxRows(options = {}) { + const taskId = Number(options && options.taskId || 0); + const taskNo = String(options && options.taskNo || '').trim(); + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const pickMode = Number(plan.pick_mode || 0); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const taskWaveRows = Array.isArray(options && options.taskWaveRows) + ? options.taskWaveRows + : []; + const taskOrderRows = Array.isArray(options && options.taskOrderRows) + ? options.taskOrderRows + : []; + const taskSkuRows = Array.isArray(options && options.taskSkuRows) + ? options.taskSkuRows + : []; + + if ([ 1, 5 ].includes(pickMode)) { + return taskWaveRows.map(row => ({ + task_id: taskId, + order_id: null, + box_code: `${taskNo || taskId}-W${row.box_no}`, + box_no: row.box_no, + box_type: 3, + ref_id: row.wave_id, + ref_label: row.wave_no, + required_qty: 0, + picked_qty: 0, + box_status: 0, + review_result: null, + review_user_id: null, + review_time: null, + warehouse_id: warehouseId, + })); + } + + if (pickMode === 3 && taskSkuRows.length > 0) { + return taskSkuRows.map(row => ({ + task_id: taskId, + order_id: null, + box_code: `${taskNo || taskId}-S${row.box_no}`, + box_no: row.box_no, + box_type: 1, + ref_id: Number(row.ref_id || row.sku_id || 0) || null, + ref_label: String(row.ref_label || '').trim() || null, + required_qty: Number(row.required_qty || 0), + picked_qty: 0, + box_status: 0, + review_result: null, + review_user_id: null, + review_time: null, + warehouse_id: warehouseId, + })); + } + + return taskOrderRows.map(row => ({ + task_id: taskId, + order_id: row.order_id, + box_code: `${taskNo || taskId}-O${row.box_no}`, + box_no: row.box_no, + box_type: 2, + ref_id: row.order_id, + ref_label: null, + required_qty: 0, + picked_qty: 0, + box_status: 0, + review_result: null, + review_user_id: null, + review_time: null, + warehouse_id: warehouseId, + })); + } + + /** + * 领单时绑定拣货车并更新车辆主表。 + * + * @param {Object} params 绑定参数。 + * @param {number} params.taskId 任务ID。 + * @param {number} params.cartId 拣货车ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async bindPickCartForTask(params = {}) { + const taskId = this.normalizeRequiredPositiveInteger(params.taskId, 'task_id'); + const cartId = this.normalizeRequiredPositiveInteger(params.cartId, 'cart_id'); + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const transaction = params.transaction; + const operatorId = Number.isInteger(Number(params.operatorId)) + ? Number(params.operatorId) + : 0; + + const cartRows = await this.ctx.model.query(` + SELECT id, cart_code + FROM wms_pick_cart + WHERE id = :cartId + AND warehouse_id = :warehouseId + AND status = 1 + FOR UPDATE + `, { + replacements: { + cartId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const cartRow = Array.isArray(cartRows) ? cartRows[0] : null; + if (!cartRow) { + throw new Error(`拣货车不存在或已停用: ${cartId}`); + } + + // 通过绑定表判断车是否被其他活跃任务占用(不依赖 wms_pick_cart.current_task_id) + // 仅以 wms_pick_task_cart_binding.is_active = 1 为准,不关联任务状态做二次过滤 + const bindingRows = await this.ctx.model.query(` + SELECT b.task_id + FROM wms_pick_task_cart_binding b + WHERE b.cart_id = :cartId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + LIMIT 1 + FOR UPDATE + `, { + replacements: { + cartId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const activeBindingTaskId = Number( + (Array.isArray(bindingRows) && bindingRows.length > 0 ? bindingRows[0]?.task_id : 0) + ); + if (activeBindingTaskId > 0 && activeBindingTaskId !== taskId) { + throw new Error(`拣货车已被活动任务占用: ${cartId}`); + } + + await this.bulkInsertRows('wms_pick_task_cart_binding', [{ + task_id: taskId, + cart_id: cartId, + cart_code_snapshot: String(cartRow.cart_code || '').trim() || null, + warehouse_id: warehouseId, + bind_user_id: operatorId, + bind_type: 1, + unbind_user_id: null, + is_active: 1, + bind_time: new Date(), + unbind_time: null, + }], transaction); + + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET + current_cart_id = :cartId, + current_cart_code_snapshot = :cartCode + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + cartId, + cartCode: String(cartRow.cart_code || '').trim() || null, + warehouseId, + }, + transaction, + }); + } + + /** + * 初始化任务断点、动作日志与轨迹。 + * + * @param {Object} params 初始化参数。 + * @param {number} params.taskId 任务ID。 + * @param {string} params.taskNo 任务编号。 + * @param {Object} params.plan 预处理计划。 + * @param {Object} params.data 原始请求数据。 + * @param {Array} params.selectedOrderIds 已选订单ID。 + * @param {number} params.cartId 绑定车ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人姓名。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async initTaskCheckpointAndLogs(params = {}) { + const taskId = this.normalizeRequiredPositiveInteger(params.taskId, 'task_id'); + const taskNo = String(params.taskNo || '').trim(); + const plan = this.isPlainObject(params.plan) ? params.plan : {}; + const data = this.isPlainObject(params.data) ? params.data : {}; + const transaction = params.transaction; + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const operatorId = Number.isInteger(Number(params.operatorId)) + ? Number(params.operatorId) + : 0; + const operatorName = String(params.operatorName || 'system').trim() || 'system'; + const cartId = Number(params.cartId || 0) > 0 ? Number(params.cartId) : null; + const selectedOrderIds = Array.isArray(params.selectedOrderIds) && params.selectedOrderIds.length > 0 + ? params.selectedOrderIds + : [ 0 ]; + const deviceId = String(data.device_id || data.deviceId || '').trim() || `device_${warehouseId}`; + const requestId = String(data.request_id || data.requestId || `${taskNo || taskId}_init`).trim(); + + await this.bulkInsertRows('wms_wave_pick_checkpoint', [{ + task_id: taskId, + warehouse_id: warehouseId, + pick_user_id: operatorId, + device_id: deviceId, + current_location_id: null, + current_sku_id: null, + current_box_no: null, + picked_count: 0, + remaining_count: Math.max(selectedOrderIds.length, 0), + last_event_id: null, + last_seq_no: null, + checkpoint_json: JSON.stringify({ + state: 'created', + task_no: taskNo, + }), + version: 0, + }], transaction); + + await this.bulkInsertRows('wms_wave_pick_action_log', [{ + task_id: taskId, + warehouse_id: warehouseId, + wave_id: Array.isArray(plan.selected_wave_ids) && plan.selected_wave_ids.length > 0 + ? Number(plan.selected_wave_ids[0]) + : null, + order_id: selectedOrderIds[0], + sku_id: null, + location_id: null, + box_no: null, + cart_id: cartId, + qty_delta: 0, + action_type: 'init', + request_id: `${requestId}_${taskId}`, + operator_id: operatorId, + device_id: deviceId, + seq_no: 1, + snapshot: JSON.stringify({ + task_no: taskNo, + state: 'created', + }), + }], transaction); + + const traceRows = selectedOrderIds.map(orderId => ({ + warehouse_id: warehouseId, + order_id: Number(orderId), + task_id: taskId, + cart_id: cartId, + cart_code_snapshot: null, + pick_user_id: operatorId, + pick_time: null, + review_user_id: null, + review_time: null, + review_result: null, + event_type: 'task_created', + event_desc: `任务创建: ${taskNo || taskId}`, + operator_id: operatorId, + operator_name: operatorName, + snapshot: JSON.stringify({ + task_no: taskNo, + pick_mode: Number(plan.pick_mode || 0), + }), + })); + await this.bulkInsertRows('wms_order_pick_trace', traceRows, transaction); + } + + /** + * 校验拣货车是否可占用。 + * + * @param {Object} params 校验参数。 + * @param {number} params.cartId 拣货车ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async ensurePickCartAvailable(params = {}) { + const cartId = this.normalizeRequiredPositiveInteger(params.cartId, 'cart_id'); + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const transaction = params.transaction; + + const rows = await this.ctx.model.query(` + SELECT b.task_id + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t ON t.id = b.task_id + WHERE b.cart_id = :cartId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + AND t.status IN (0, 1) + LIMIT 1 + FOR UPDATE + `, { + replacements: { + cartId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + if (Array.isArray(rows) && rows.length > 0) { + throw new Error(`拣货车已绑定活动任务: ${cartId}`); + } + } + + /** + * 生成任务编号。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} sourceCode 来源编码。 + * @return {string} 任务编号。 + */ + generateWavePickTaskNo(warehouseId, sourceCode) { + const now = Date.now(); + const rand = Math.random().toString(36).slice(2, 8) + .toUpperCase(); + return `WPT${warehouseId}${sourceCode}${now}${rand}`; + } + + /** + * 写入任务主表并在任务编号冲突时重试。 + * + * @param {Object} payload 主表载荷。 + * @param {Object} transaction 事务对象。 + * @return {Promise<{ task_id: number, task_no: string }>} 主表写入结果。 + */ + async createWavePickTaskWithRetry(payload = {}, transaction) { + const maxRetry = 5; + const warehouseId = this.normalizeRequiredPositiveInteger(payload.warehouse_id, 'warehouse_id'); + + for (let attempt = 1; attempt <= maxRetry; attempt += 1) { + const candidateTaskNo = attempt === 1 && String(payload.task_no || '').trim() + ? String(payload.task_no || '').trim() + : this.generateWavePickTaskNo(warehouseId, Number(payload.source || 1)); + + const insertPayload = { + ...payload, + task_no: candidateTaskNo, + batch_no_array: String(payload.batch_no_array || '').trim() || null, + }; + + try { + const createResult = await this.ctx.model.query(` + INSERT INTO wms_wave_pick_task + ( + task_no, + warehouse_id, + wave_id, + pick_mode, + status, + source, + wave_count, + order_count, + box_count, + batch_no, + batch_no_array, + pick_user_id, + pick_user_name, + current_cart_id, + current_cart_code_snapshot, + review_status, + review_version, + device_id, + ext_json, + create_time, + update_time + ) + VALUES + ( + :task_no, + :warehouse_id, + :wave_id, + :pick_mode, + :status, + :source, + :wave_count, + :order_count, + :box_count, + :batch_no, + :batch_no_array, + :pick_user_id, + :pick_user_name, + :current_cart_id, + :current_cart_code_snapshot, + :review_status, + :review_version, + :device_id, + :ext_json, + NOW(), + NOW() + ) + `, { + replacements: insertPayload, + transaction, + }); + + let insertedTaskId = this.extractInsertId(createResult); + if (!Number.isInteger(insertedTaskId) || insertedTaskId <= 0) { + const fallbackResult = await this.ctx.model.query('SELECT LAST_INSERT_ID() AS insertId', { + transaction, + }); + insertedTaskId = this.extractLastInsertId(fallbackResult); + } + + if (!Number.isInteger(insertedTaskId) || insertedTaskId <= 0) { + throw new Error('创建任务失败,未获取到任务主键'); + } + + return { + task_id: insertedTaskId, + task_no: candidateTaskNo, + }; + } catch (error) { + const isDuplicateTaskNo = this.isTaskNoDuplicateError(error); + if (isDuplicateTaskNo && attempt < maxRetry) { + continue; + } + throw error; + } + } + + throw new Error('创建任务失败,任务编号重试次数已达上限'); + } + + /** + * 判断是否为 task_no 唯一键冲突。 + * + * @param {Error} error 数据库错误。 + * @return {boolean} 是否冲突。 + */ + isTaskNoDuplicateError(error) { + const message = String(error && error.message || '').toLowerCase(); + const parentErrno = Number(error && error.parent && error.parent.errno || 0); + return parentErrno === 1062 + || message.includes('duplicate entry') + || message.includes('uk_task_no'); + } + + /** + * 批量插入行数据。 + * + * @param {string} tableName 表名。 + * @param {Array} rows 行数据。 + * @param {Object} transaction 事务对象。 + * @return {Promise} 实际写入行数。 + */ + async bulkInsertRows(tableName, rows = [], transaction) { + if (!Array.isArray(rows) || rows.length === 0) { + return 0; + } + + const columns = Object.keys(rows[0]); + if (columns.length === 0) { + return 0; + } + + const replacements = {}; + const valueSqlList = rows.map((row, rowIndex) => { + const placeholders = columns.map(column => { + const key = `${column}_${rowIndex}`; + replacements[key] = Object.prototype.hasOwnProperty.call(row, column) + ? row[column] + : null; + return `:${key}`; + }); + return `(${placeholders.join(', ')})`; + }); + + const columnSql = columns.map(column => `\`${column}\``).join(', '); + const sql = `INSERT INTO ${tableName} (${columnSql}) VALUES ${valueSqlList.join(', ')}`; + await this.ctx.model.query(sql, { + replacements, + transaction, + }); + + return rows.length; + } + + /** + * 解析“存在未完成任务”异常信息中的任务标识。 + * + * @param {string} message 异常消息文本。 + * @return {{ task_id: number|null, task_no: string|null }} 解析结果。 + */ + parseWaveStrategyExistingTaskInfo(message = '') { + const normalizedMessage = String(message || ''); + const match = normalizedMessage.match(/task_id=(\d+)(?:,task_no=([^\)\)\s]+))?/); + if (!match) { + return { + task_id: null, + task_no: null, + }; + } + + const parsedTaskId = Number(match[1] || 0); + const parsedTaskNo = String(match[2] || '').trim(); + + return { + task_id: Number.isInteger(parsedTaskId) && parsedTaskId > 0 ? parsedTaskId : null, + task_no: parsedTaskNo || null, + }; + } + + /** + * 按策略抓取任务壳子方法(仅 PDA 使用),仅受理请求并返回任务信息。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.strategy_id 波次策略ID(支持 strategyId)。 + * @return {Promise} 受理结果。 + */ + async waveStrategyFetchPda(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const strategyId = this.normalizeRequiredPositiveInteger( + normalizedData.strategy_id ?? normalizedData.strategyId, + 'strategy_id' + ); + + let warehouseId; + try { + warehouseId = Number(this.getWarehouseId()); + } catch (error) { + throw new Error('未识别到当前仓库上下文'); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const operatorInfo = this.getOrderLogOperator(); + const plan = await this.prepareWaveStrategyFetchPlan({ + strategyId, + warehouseId, + operator: { + operator_id: operatorInfo.id, + operator_name: operatorInfo.name, + }, + source: 'pda', + data: normalizedData, + }); + + if (Array.isArray(plan.validation_errors) && plan.validation_errors.length > 0) { + return this.fail('按策略抓取预处理校验失败', { + data: { + status: 'failed', + fetch_state: 2, + tip: '创建失败,请重试', + task_id: null, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + plan, + }, + }, 400); + } + + try { + const createdTask = await this.createWavePickTaskFromPlan({ + plan, + data: normalizedData, + waveBatchSource: 2, + autoPopulateSelections: true, + }); + + this.ctx.logger.info('[wave.waveStrategyFetchPda] 任务创建成功', { + taskId: createdTask.task_id, + taskNo: createdTask.task_no, + warehouseId, + strategyId, + }); + + return this.success('ok', { + status: 'success', + fetch_state: 1, + tip: '任务创建成功', + task_id: createdTask.task_id, + task_no: createdTask.task_no, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + state: createdTask.state, + plan, + plan_summary: createdTask.plan_summary, + accepted_at: new Date().toISOString(), + }); + } catch (error) { + const errorMessage = String(error && error.message || ''); + if (errorMessage.includes('当前用户存在未完成任务')) { + const existingTaskInfo = this.parseWaveStrategyExistingTaskInfo(errorMessage); + return this.success('存在未完成任务', { + status: 'failed', + fetch_state: 3, + tip: '存在未完成任务,已返回任务ID,可继续拣货', + task_id: existingTaskInfo.task_id, + task_no: existingTaskInfo.task_no, + can_enter_pick_flow: true, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + plan, + }); + } + + return this.fail(`按策略抓取任务创建失败: ${error.message}`, { + data: { + status: 'failed', + fetch_state: 2, + tip: '创建失败,请重试', + task_id: null, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + plan, + }, + }, 500); + } + } + + /** + * 公共拣货任务取消流程。 + * + * 仅允许取消状态为 0/1 的任务。取消后会回收拣货车绑定,并物理删除该任务 + * 的任务-订单关联记录(wms_wave_pick_task_order),避免订单回池后残留脏数据。 + * + * 按任务来源区分行为: + * - source=0/1(PDA 抓取):释放关联波次(清空订单 wave_id、删除 wms_wave_batch), + * 使订单可重新参与后续策略抓取。 + * - source=2(后台/扫描创建):不释放波次,仅作废任务(更新状态为 9、解绑拣货车)。 + * + * 所有来源均会清理任务-波次关联(wms_wave_pick_task_wave)与任务-订单关联记录 + * (wms_wave_pick_task_order)。 + * + * @param {Object} [params={}] 取消参数。 + * @param {Array} params.taskIds 任务ID列表。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人名称。 + * @param {number|null} [params.restrictCreatorId=null] 限制创建人ID。 + * @return {Promise} 取消结果。 + */ + async cancelWavePickTasksInternal(params = {}) { + const normalizedParams = this.isPlainObject(params) ? params : {}; + const sourceTaskIds = Array.isArray(normalizedParams.taskIds) ? normalizedParams.taskIds : []; + const normalizedTaskIds = [ ...new Set(sourceTaskIds + .map(item => Number(item)) + .filter(taskId => Number.isInteger(taskId) && taskId > 0)) ]; + const warehouseId = Number(normalizedParams.warehouseId || 0); + const operatorId = Number(normalizedParams.operatorId || 0); + const operatorName = String(normalizedParams.operatorName || 'system').trim() || 'system'; + const rawRestrictCreatorId = normalizedParams.restrictCreatorId; + const restrictCreatorId = rawRestrictCreatorId === null || rawRestrictCreatorId === undefined + ? null + : Number(rawRestrictCreatorId); + + if (normalizedTaskIds.length === 0) { + const error = new Error('task_ids 必须为非空数组'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + const error = new Error('未获取到仓库上下文'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + if (!Number.isInteger(operatorId) || operatorId <= 0) { + const error = new Error('未获取到操作人上下文'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + if (restrictCreatorId !== null && (!Number.isInteger(restrictCreatorId) || restrictCreatorId <= 0)) { + const error = new Error('取消任务创建人限制参数不合法'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + const transaction = await this.ctx.model.transaction(); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const canceledAtColumnRows = await this.ctx.model.query(` + SHOW COLUMNS FROM wms_wave_pick_task LIKE 'cancelled_at' + `, { + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + const hasCancelledAtColumn = Array.isArray(canceledAtColumnRows) && canceledAtColumnRows.length > 0; + const cancelledTaskNos = []; + const cancelOrderLogItems = []; + let hasReleasedWaves = false; + + for (const taskId of normalizedTaskIds) { + const requestId = `wave_pick_task_cancel_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const taskRows = await this.ctx.model.query(` + SELECT id, task_no, warehouse_id, status, current_cart_id, source + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + ${restrictCreatorId !== null ? 'AND pick_user_id = :restrictCreatorId' : ''} + LIMIT 1 + FOR UPDATE + `, { + replacements: { + taskId, + warehouseId, + ...(restrictCreatorId !== null ? { restrictCreatorId } : {}), + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const taskRow = Array.isArray(taskRows) ? taskRows[0] : null; + if (!taskRow) { + if (restrictCreatorId !== null) { + const taskRowsWithoutCreator = await this.ctx.model.query(` + SELECT id + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, { + replacements: { + taskId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + if (Array.isArray(taskRowsWithoutCreator) && taskRowsWithoutCreator.length > 0) { + const error = new Error('仅允许取消本人创建的任务'); + error.statusCode = 403; + error.data = { + task_id: taskId, + warehouse_id: warehouseId, + operator_id: restrictCreatorId, + }; + throw error; + } + } + + const error = new Error('任务不存在'); + error.statusCode = 404; + error.data = { + task_id: taskId, + warehouse_id: warehouseId, + }; + throw error; + } + + const taskStatus = Number(taskRow.status || 0); + // status 2(待复核)、3(已完成)不允许取消,此时库存已扣减且订单已标记拣货完成 + if (![ 0, 1 ].includes(taskStatus)) { + const statusMessages = { 2: '待复核', 3: '已完成', 9: '已取消' }; + const statusText = statusMessages[taskStatus] || `状态${taskStatus}`; + const error = new Error(`当前任务已${statusText},不允许取消`); + error.statusCode = 400; + error.data = { + task_id: taskId, + task_no: String(taskRow.task_no || '').trim(), + warehouse_id: warehouseId, + status: taskStatus, + }; + throw error; + } + + const taskSource = Number(taskRow.source || 0); + const taskNo = String(taskRow.task_no || '').trim(); + + const taskWaveRows = await this.ctx.model.query(` + SELECT wave_id + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + const waveIds = [ ...new Set((Array.isArray(taskWaveRows) ? taskWaveRows : []) + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + const taskOrderRows = await this.ctx.model.query(` + SELECT order_id + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + const taskOrderIds = [ ...new Set((Array.isArray(taskOrderRows) ? taskOrderRows : []) + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + + // 收集订单操作日志(提交后统一写入) + for (const orderId of taskOrderIds) { + cancelOrderLogItems.push({ + orderId, + operationCode: 'ORDER_WAVE_CANCEL', + message: `取消拣货任务 ${taskNo},从波次释放`, + }); + } + + // source=2(后台/扫描创建)不释放波次,仅清理任务-波次关联 + const isScanCreated = taskSource === 2; + let releasedWaveRows = []; + if (waveIds.length > 0) { + if (!isScanCreated) { + // PDA 抓取:释放波次 + releasedWaveRows = await this.ctx.model.query(` + SELECT wave_id, wave_no + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + FOR UPDATE + `, { + replacements: { + warehouseId, + waveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + await orderModel.update({ + wave_id: 0, + wave_no: '', + wave_scope: 0, + wave_strategy_version: 0, + wave_scan_result: 0, + }, { + where: { + warehouse_id: warehouseId, + wave_id: { [Op.in]: waveIds }, + }, + transaction, + }); + + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + warehouseId, + waveIds, + }, + transaction, + }); + + // 清理波次订单索引 + await this.deleteOrderWaveIndexByWaveIds({ + warehouseId, + waveIds, + transaction, + }); + + if (Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0) { + hasReleasedWaves = true; + } + } + + // 清理任务-波次关联(所有来源都需要) + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } + + // 清理任务-订单关联记录(所有来源都需要): + // 任务取消后订单回池,wms_wave_pick_task_order 的关联记录属于脏数据,必须物理删除, + // 否则会污染后续任务进度统计、复核状态批量更新及车标快照兜底查询 + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + // 当任务状态为待复核(2)或已完成(3)时,回退订单拣货状态(仅 PDA 抓取) + if (!isScanCreated && [ 2, 3 ].includes(taskStatus)) { + await this.ctx.model.query(` + UPDATE wms_wave_pick_task_order + SET pick_status = 0, + picked_time = NULL, + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND pick_status = 1 + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + const pickedOrderIds = [ ...new Set((Array.isArray(taskOrderRows) ? taskOrderRows : []) + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + + if (pickedOrderIds.length > 0) { + await orderModel.update({ + pick_status: 'padding', + }, { + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: pickedOrderIds, + }, + pick_status: 'fin', + }, + transaction, + validate: false, + hooks: false, + }); + } + } + + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET + status = 9, + wave_count = 0, + ${hasCancelledAtColumn ? 'cancelled_at = NOW(),' : ''} + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + await this.ctx.model.query(` + UPDATE wms_pick_task_cart_binding + SET + is_active = 0, + unbind_user_id = :operatorId, + unbind_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND is_active = 1 + `, { + replacements: { + taskId, + warehouseId, + operatorId, + }, + transaction, + }); + + await this.bulkInsertRows('wms_wave_pick_action_log', [{ + task_id: taskId, + warehouse_id: warehouseId, + wave_id: Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0 + ? Number(releasedWaveRows[0].wave_id || 0) + : 0, + order_id: taskOrderIds.length > 0 ? Number(taskOrderIds[0]) : null, + sku_id: null, + location_id: null, + box_no: null, + cart_id: Number(taskRow.current_cart_id || 0) > 0 ? Number(taskRow.current_cart_id) : null, + qty_delta: 0, + action_type: 'cancel', + request_id: requestId, + operator_id: Number.isInteger(operatorId) ? operatorId : 0, + device_id: null, + seq_no: 1, + snapshot: JSON.stringify({ + task_no: taskNo, + source: taskSource, + released_wave_ids: isScanCreated ? [] : waveIds, + released_order_count: isScanCreated ? 0 : taskOrderIds.length, + }), + }], transaction); + + await this.bulkInsertRows('wms_order_pick_trace', [{ + warehouse_id: warehouseId, + order_id: taskOrderIds.length > 0 ? Number(taskOrderIds[0]) : 0, + task_id: taskId, + cart_id: Number(taskRow.current_cart_id || 0) > 0 ? Number(taskRow.current_cart_id) : null, + cart_code_snapshot: null, + pick_user_id: null, + pick_time: null, + review_user_id: null, + review_time: null, + review_result: null, + event_type: 'task_cancelled', + event_desc: isScanCreated + ? `任务取消(未释放波次): ${taskNo || taskId}` + : `任务取消并释放波次: ${taskNo || taskId}`, + operator_id: Number.isInteger(operatorId) ? operatorId : 0, + operator_name: operatorName, + snapshot: JSON.stringify({ + task_no: taskNo, + source: taskSource, + released_wave_ids: isScanCreated ? [] : waveIds, + released_order_count: isScanCreated ? 0 : taskOrderIds.length, + released_wave_nos: isScanCreated + ? [] + : (Array.isArray(releasedWaveRows) ? releasedWaveRows : []) + .map(row => String(row && row.wave_no || '').trim()) + .filter(Boolean), + }), + }], transaction); + + cancelledTaskNos.push(taskNo); + } + + await transaction.commit(); + + if (cancelOrderLogItems.length > 0) { + await this.batchCreateOrderOperationLogs(cancelOrderLogItems, { + warehouseId, + scene: 'cancelWavePickTasksInternal', + }); + } + + if (hasReleasedWaves) { + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(err => { + this.ctx.logger.warn('[wave.wavePickTaskCancel] 触发回池后重扫失败', { + warehouseId, + error: err && err.message ? err.message : String(err), + }); + }); + }); + } + + return { + cancelled_count: normalizedTaskIds.length, + task_ids: normalizedTaskIds, + task_nos: cancelledTaskNos, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 取消拣货任务并释放关联波次。 + * + * 仅允许取消状态为 0/1/2/3 的任务。取消后会回收拣货车绑定、 + * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 + * 当任务状态为 2(待复核)或 3(已完成)时,还会回退已拣货订单的拣货状态。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Array} data.task_ids 任务ID数组。 + * @return {Promise} 取消结果。 + */ + async wavePickTaskCancel(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const sourceTaskIds = Array.isArray(normalizedData.task_ids) ? normalizedData.task_ids : []; + if (sourceTaskIds.length === 0) { + return this.fail('task_ids 必须为非空数组', {}, 400); + } + + const normalizedTaskIds = []; + for (const item of sourceTaskIds) { + const taskId = Number(item); + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_ids 必须为正整数数组', { + data: { + task_ids: sourceTaskIds, + }, + }, 400); + } + normalizedTaskIds.push(taskId); + } + const taskIds = [ ...new Set(normalizedTaskIds) ]; + if (taskIds.length === 0) { + return this.fail('task_ids 必须为非空数组', {}, 400); + } + + const resolvedWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(resolvedWarehouseId) || resolvedWarehouseId <= 0) { + return this.fail('未获取到仓库上下文', {}, 400); + } + + const operatorInfo = this.getOrderLogOperator(); + const operatorId = Number(operatorInfo.id || 0); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 400); + } + const operatorName = String(operatorInfo.name || 'system').trim() || 'system'; + + try { + const result = await this.cancelWavePickTasksInternal({ + taskIds, + warehouseId: resolvedWarehouseId, + operatorId, + operatorName, + restrictCreatorId: null, + }); + + return this.success('ok', result); + } catch (error) { + if (Number.isInteger(error.statusCode) && error.statusCode >= 400 && error.statusCode < 500) { + return this.fail(error.message, { + data: this.isPlainObject(error.data) ? error.data : {}, + }, error.statusCode); + } + + return this.fail(`取消拣货任务失败: ${error.message}`, { + data: { + task_ids: taskIds, + warehouse_id: resolvedWarehouseId, + }, + }, 500); + } + } + + /** + * 取消本人创建的单个拣货任务并释放关联波次。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.task_id 任务ID。 + * @return {Promise} 取消结果。 + */ + async wavePickTaskCancelSelf(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + if (Object.prototype.hasOwnProperty.call(normalizedData, 'task_ids')) { + return this.fail('当前接口仅支持单个 task_id,请勿传 task_ids', { + data: { + task_ids: normalizedData.task_ids, + }, + }, 400); + } + + const taskId = Number(normalizedData.task_id); + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必须为正整数', { + data: { + task_id: normalizedData.task_id, + }, + }, 400); + } + + const resolvedWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(resolvedWarehouseId) || resolvedWarehouseId <= 0) { + return this.fail('未获取到仓库上下文', {}, 400); + } + + const operatorInfo = this.getOrderLogOperator(); + const operatorId = Number(operatorInfo.id || 0); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 400); + } + const operatorName = String(operatorInfo.name || 'system').trim() || 'system'; + + try { + const result = await this.cancelWavePickTasksInternal({ + taskIds: [ taskId ], + warehouseId: resolvedWarehouseId, + operatorId, + operatorName, + restrictCreatorId: operatorId, + }); + + return this.success('ok', result); + } catch (error) { + if (Number.isInteger(error.statusCode) && error.statusCode >= 400 && error.statusCode < 500) { + return this.fail(error.message, { + data: this.isPlainObject(error.data) ? error.data : {}, + }, error.statusCode); + } + + return this.fail(`取消本人拣货任务失败: ${error.message}`, { + data: { + task_id: taskId, + warehouse_id: resolvedWarehouseId, + }, + }, 500); + } + } + + /** + * 后台按策略直接抓取并创建波次。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.strategy_id 波次策略ID(支持 strategyId)。 + * @return {Promise} 建波结果。 + */ + async waveStrategyFetchAdmin(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const strategyId = this.normalizeRequiredPositiveInteger( + normalizedData.strategy_id ?? normalizedData.strategyId, + 'strategy_id' + ); + + let warehouseId; + try { + warehouseId = Number(this.getWarehouseId()); + } catch (error) { + throw new Error('未识别到当前仓库上下文'); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const operatorInfo = this.getOrderLogOperator(); + const plan = await this.prepareWaveStrategyFetchPlan({ + strategyId, + warehouseId, + operator: { + operator_id: operatorInfo.id, + operator_name: operatorInfo.name, + }, + source: 'admin', + data: normalizedData, + }); + + if (Array.isArray(plan.validation_errors) && plan.validation_errors.length > 0) { + return this.fail('按策略抓取预处理校验失败', { + data: { + status: 'failed', + fetch_state: 2, + tip: '建波失败,请重试', + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + plan, + }, + }, 400); + } + + try { + const directFetchResult = await this.executeWaveStrategyDirectFetch({ + plan, + waveBatchSource: 0, + }); + + this.ctx.logger.info('[wave.waveStrategyFetchAdmin] 建波成功', { + warehouseId, + strategyId, + strategyType: directFetchResult.strategy_type, + createdWaveCount: directFetchResult.created_wave_count, + createdOrderCount: directFetchResult.created_order_count, + }); + + return this.success('ok', { + status: 'success', + fetch_state: 1, + tip: '建波成功', + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + plan, + wave_ids: directFetchResult.wave_ids, + wave_nos: directFetchResult.wave_nos, + order_ids: directFetchResult.order_ids, + created_wave_count: directFetchResult.created_wave_count, + created_order_count: directFetchResult.created_order_count, + wave_prefix: directFetchResult.wave_prefix, + wave_prefix_source: directFetchResult.wave_prefix_source, + candidate_count: directFetchResult.candidate_count, + grouped_count: directFetchResult.grouped_count, + strategy_type: directFetchResult.strategy_type, + accepted_at: new Date().toISOString(), + }); + } catch (error) { + return this.fail(`按策略抓取建波失败: ${error.message}`, { + data: { + status: 'failed', + fetch_state: 2, + tip: '建波失败,请重试', + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + plan, + }, + }, 500); + } + } + + /** + * 删除指定订单的波次索引记录。 + * + * @param {Object} [params={}] 参数对象。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {Array} [params.orderIds] 订单ID列表。 + * @param {Object} [params.transaction] 事务对象。 + * @return {Promise} + */ + async deleteOrderWaveIndexByOrderIds({ warehouseId, orderIds, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedOrderIds.length === 0) { + return; + } + + const deleteSql = ` + DELETE FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `; + + await this.ctx.model.query(deleteSql, { + replacements: { + warehouseId: normalizedWarehouseId, + orderIds: normalizedOrderIds, + }, + transaction, + }); + } + + /** + * 删除指定波次的波次索引记录。 + * + * @param {Object} [params={}] 参数对象。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {Array} [params.waveIds] 波次ID列表。 + * @param {Object} [params.transaction] 事务对象。 + * @return {Promise} + */ + async deleteOrderWaveIndexByWaveIds({ warehouseId, waveIds, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveIds = this.normalizeIdsInput(waveIds); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) { + return; + } + + const deleteSql = ` + DELETE FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `; + + await this.ctx.model.query(deleteSql, { + replacements: { + warehouseId: normalizedWarehouseId, + waveIds: normalizedWaveIds, + }, + transaction, + }); + } + + /** + * 重建指定波次的订单波次索引。 + * + * @param {Object} [params={}] 参数对象。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {number|string} [params.waveId] 波次ID。 + * @param {Array} [params.orderIds] 订单ID列表。 + * @param {Object} [params.orderModel] 订单模型实例。 + * @param {Object} [params.transaction] 事务对象。 + * @return {Promise} + */ + async rebuildOrderWaveIndex({ warehouseId, waveId, orderIds, orderModel, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveId = Number(waveId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if ( + !Number.isInteger(normalizedWarehouseId) + || normalizedWarehouseId <= 0 + || !Number.isInteger(normalizedWaveId) + || normalizedWaveId <= 0 + || normalizedOrderIds.length === 0 + ) { + return; + } + await this.replaceOrderWaveIndexByWaveIds({ + warehouseId: normalizedWarehouseId, + waveIds: [ normalizedWaveId ], + orderModel, + transaction, + }); + } + + /** + * 按波次ID批量替换订单波次索引记录。 + * + * @param {Object} [params={}] 参数对象。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {Array} [params.waveIds] 波次ID列表。 + * @param {Object} [params.orderModel] 订单模型实例。 + * @param {Object} [params.transaction] 事务对象。 + * @return {Promise>} 各波次对应的订单总数映射。 + */ + async replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds, orderModel, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveIds = this.normalizeIdsInput(waveIds); + const currentOrderModel = orderModel || await this.getOrderModel('pendingOrder', normalizedWarehouseId); + + if ( + !Number.isInteger(normalizedWarehouseId) + || normalizedWarehouseId <= 0 + || normalizedWaveIds.length === 0 + || !currentOrderModel + || typeof currentOrderModel.findAll !== 'function' + ) { + return new Map(); + } + + const orderRows = await currentOrderModel.findAll({ + attributes: [ 'id', 'wave_id', 'sys_platform_code', 'source_platform_code', 'sys_logistics_code' ], + where: { + wave_id: { + [Op.in]: normalizedWaveIds, + [Op.gt]: 0, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + const orderRowsList = Array.isArray(orderRows) ? orderRows : []; + const waveOrderRowsMap = new Map(normalizedWaveIds.map(waveId => [ waveId, []])); + for (const row of orderRowsList) { + const waveId = Number(row && row.wave_id || 0); + const orderId = Number(row && row.id || 0); + if (!Number.isInteger(waveId) || waveId <= 0 || !waveOrderRowsMap.has(waveId)) { + continue; + } + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + waveOrderRowsMap.get(waveId).push({ + id: orderId, + sys_platform_code: String(row && row.sys_platform_code || ''), + source_platform_code: String(row && row.source_platform_code || ''), + sys_logistics_code: String(row && row.sys_logistics_code || ''), + }); + } + + await this.deleteOrderWaveIndexByWaveIds({ + warehouseId: normalizedWarehouseId, + waveIds: normalizedWaveIds, + transaction, + }); + + const allOrderIds = [ ...new Set(orderRowsList + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + if (allOrderIds.length > 0) { + await this.deleteOrderWaveIndexByOrderIds({ + warehouseId: normalizedWarehouseId, + orderIds: allOrderIds, + transaction, + }); + } + + const valueSqlList = []; + const replacements = { + warehouseId: normalizedWarehouseId, + }; + + let rowIndex = 0; + for (const waveId of normalizedWaveIds) { + const rawOrderRows = waveOrderRowsMap.get(waveId) || []; + // 按平台+快递排序:同平台、同快递订单聚合在一起,确保 wave_index 连续分配 + const orderRowsByWave = [ ...rawOrderRows ].sort((a, b) => { + const platformA = String( + (a && a.sys_platform_code) || (a && a.source_platform_code) || '' + ).trim().toLowerCase(); + const platformB = String( + (b && b.sys_platform_code) || (b && b.source_platform_code) || '' + ).trim().toLowerCase(); + if (platformA !== platformB) return platformA.localeCompare(platformB); + const logisticsA = String((a && a.sys_logistics_code) || '').trim().toLowerCase(); + const logisticsB = String((b && b.sys_logistics_code) || '').trim().toLowerCase(); + if (logisticsA !== logisticsB) return logisticsA.localeCompare(logisticsB); + return (Number(a && a.id) || 0) - (Number(b && b.id) || 0); + }); + const platformsIndexMap = new Map(); + const platformSequenceMap = new Map(); + for (const orderRow of orderRowsByWave) { + const currentOrderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(currentOrderId) || currentOrderId <= 0) { + continue; + } + + const platformKey = String( + (orderRow && orderRow.sys_platform_code) + || (orderRow && orderRow.source_platform_code) + || '' + ).trim().toLowerCase(); + const nextPlatformSequence = Number(platformSequenceMap.get(platformKey) || 0) + 1; + platformSequenceMap.set(platformKey, nextPlatformSequence); + platformsIndexMap.set(currentOrderId, nextPlatformSequence); + } + + for (const [ orderIndex, orderRow ] of orderRowsByWave.entries()) { + const orderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + const waveSequence = orderIndex + 1; + const platformsSequence = Number(platformsIndexMap.get(orderId) || waveSequence); + valueSqlList.push( + `(:warehouseId, :orderId_${rowIndex}, :waveId_${rowIndex}, :waveIndex_${rowIndex}, :platformsIndex_${rowIndex}, NOW())` + ); + replacements[`orderId_${rowIndex}`] = orderId; + replacements[`waveId_${rowIndex}`] = waveId; + replacements[`waveIndex_${rowIndex}`] = waveSequence; + replacements[`platformsIndex_${rowIndex}`] = platformsSequence; + rowIndex += 1; + } + } + + if (valueSqlList.length > 0) { + const insertSql = ` + INSERT INTO wms_order_wave_index + ( + warehouse_id, + order_id, + wave_id, + wave_index, + platforms_index, + create_at + ) + VALUES + ${valueSqlList.join(',\n ')} + `; + + await this.ctx.model.query(insertSql, { + replacements, + transaction, + }); + } + + const totalOrdersMap = new Map(); + for (const waveId of normalizedWaveIds) { + const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; + totalOrdersMap.set(waveId, orderRowsByWave.length); + } + + return totalOrdersMap; + } + + /** + * 兼容旧方法名 fetch,内部转调 groupFetch。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 任务提交结果。 + */ + async fetch(data = {}) { + return this.groupFetch(data); + } + +} + +module.exports = WaveService; diff --git a/app/service/systemMethods/outbound.js b/app/service/systemMethods/outbound.js new file mode 100644 index 0000000..9b294e0 --- /dev/null +++ b/app/service/systemMethods/outbound.js @@ -0,0 +1,94 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 出库相关 method 层入口。 + * 负责鉴权配置与参数解构,业务逻辑下沉到 systems。 + */ +class OutboundService extends MainService { + /** + * 初始化 outbound 模块鉴权配置。 + * + * @param {Egg.Context} ctx 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'autoOutbound'; + const _noNeedLog = 'autoOutbound'; + const _noNeedAuth = 'autoOutbound'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 手动触发自动化出库扫描。 + * + * 扫描当前仓库下满足自动化出库规则的订单并执行出库操作(任一规则命中即出库)。 + * 开关与规则由仓库 subject_config 控制: + * - auto_outbound_enabled:是否启用(默认关闭); + * - auto_outbound_rules:规则数组(空数组时不执行),每项仅校验: + * require_pack(pack_status='fin')/ require_weigh(wms_order_express.weighing_weight>0) + * / require_sync(sync_status='fin')。 + * 固定基线条件:已复核(recheck_status='fin')+ 已分配储位(storage_status='fin')。 + * + * @param {Object} data 请求参数。 + * @param {number} [data.warehouseId] 指定仓库ID,不传则使用当前用户上下文仓库。 + * @return {Promise} 执行结果,包含处理数量和仓库详情。 + */ + async autoOutbound(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { ctx } = this; + const warehouseId = Number(requestData.warehouseId) || this.getWarehouseId(); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('缺少有效的仓库ID'); + } + + const storeId = this.getWarehouseId(); + + if (!Number.isInteger(storeId) || storeId <= 0) { + throw new Error('缺少有效的货主ID'); + } + + const store = await ctx.model.Store.findOne({ + where: { id: storeId, status: 1, deleted_at: null }, + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + + if (!store) { + throw new Error('货主不存在或已禁用'); + } + + let subjectConfig = store.subject_config; + if (typeof subjectConfig === 'string') { + try { + subjectConfig = JSON.parse(subjectConfig); + } catch (error) { + throw new Error('subject_config 配置解析失败'); + } + } + + const orderAutoOutboundService = ctx.service.systems.orderAutoOutbound; + + if (!orderAutoOutboundService.isAutoOutboundEnabled(subjectConfig)) { + throw new Error('当前仓库未启用自动化出库'); + } + + const autoOutboundRules = orderAutoOutboundService.resolveAutoOutboundRules(subjectConfig); + + if (autoOutboundRules.length === 0) { + throw new Error('当前仓库未配置自动化出库规则'); + } + + const result = await orderAutoOutboundService.processWarehouseAutoOutbound( + warehouseId, + autoOutboundRules + ); + + return result; + } +} + +module.exports = OutboundService; diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js new file mode 100644 index 0000000..d4f3e10 --- /dev/null +++ b/app/service/systemMethods/pick.js @@ -0,0 +1,2166 @@ +'use strict'; + +const { Op } = require('sequelize'); +const MainService = require('../main'); +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); + +class PickService extends MainService { + /** + * 初始化 pick 模块鉴权配置。 + * + * @param {Egg.Context} ctx 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete,waveClaimScan'; + const _noNeedLog = 'query'; + const _noNeedAuth = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete,waveClaimScan'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 将入参标准化为布尔值。 + * + * 兼容 `true/false`、`1/0`、`yes/no`、`on/off` 以及大小写字符串。 + * + * @param {*} value 原始值。 + * @param {boolean} defaultValue 默认值。 + * @return {boolean} 解析后的布尔值。 + */ + normalizeBoolean(value, defaultValue = false) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + if (typeof value === 'boolean') { + return value; + } + + const normalized = String(value).trim().toLowerCase(); + if ([ '1', 'true', 'yes', 'y', 'on' ].includes(normalized)) { + return true; + } + if ([ '0', 'false', 'no', 'n', 'off' ].includes(normalized)) { + return false; + } + + return defaultValue; + } + + /** + * 按仓库上下文获取订单分表模型。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 订单模型。 + */ + async getOrderModelByWarehouse(warehouseId) { + const { ctx } = this; + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + throw new Error('订单分表模型工厂不可用'); + } + + const model = await factory.getCurrentModel(warehouseId); + if (!model || typeof model.findOne !== 'function') { + throw new Error('订单分表模型不可用'); + } + + return model; + } + + /** + * 生成拣货任务编号。 + * + * @return {string} 任务编号。 + */ + generatePickTaskNo() { + const now = new Date(); + const pad2 = value => String(value).padStart(2, '0'); + const datePart = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}`; + const timePart = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`; + const randomPart = Math.random().toString(36).slice(2, 6) + .toUpperCase(); + return `PK${datePart}${timePart}${randomPart}`; + } + + /** + * 创建波次拣货任务及关联关系。 + * + * @param {Object} params 创建参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.waveId 波次ID。 + * @param {string} params.waveNo 波次号。 + * @param {number} params.pickMode 拣货模式。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人名称。 + * @param {Array} params.orderIds 波次订单ID集合。 + * @param {string} [params.remark=''] 备注。 + * @param {number} [params.source=2] 任务来源:1-PDA抓取创建,2-扫描进任务/后台抓取,默认为2。 + * @param {boolean} [params.excludeUnclaimed=false] 普通波次(source=0)计算拣货数量时是否剔除未领料 + * (claim_status != fin)订单:true 时未领料订单不写入任务订单/筐,也不计入 order_count。 + * @return {Promise<{task_id: number, task_no: string}>} 创建结果。 + */ + async createWavePickTask(params = {}) { + const { ctx } = this; + const warehouseId = Number(params && params.warehouseId || 0); + const waveId = Number(params && params.waveId || 0); + const waveNo = String(params && params.waveNo || '').trim(); + const pickMode = Number(params && params.pickMode || 2); + const operatorId = Number(params && params.operatorId || 0); + const operatorName = String(params && params.operatorName || '').trim() || 'system'; + const source = Number(params && params.source !== undefined ? params.source : 2); + const remark = String(params && params.remark || '').trim(); + const excludeUnclaimed = Boolean(params && params.excludeUnclaimed); + const normalizedOrderIds = [ ...new Set((Array.isArray(params && params.orderIds) ? params.orderIds : []) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw Object.assign(new Error('warehouse_id 参数不合法'), { code: 400 }); + } + if (!Number.isInteger(waveId) || waveId <= 0 || !waveNo) { + throw Object.assign(new Error('目标波次信息不完整'), { code: 400 }); + } + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw Object.assign(new Error('未获取到操作人上下文'), { code: 401 }); + } + if (normalizedOrderIds.length <= 0) { + throw Object.assign(new Error('波次下无可用订单,无法创建任务'), { code: 400 }); + } + + const orderModel = await this.getOrderModelByWarehouse(warehouseId); + const orderRows = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: normalizedOrderIds, + }, + }, + attributes: [ 'id', 'intercept_status', 'claim_status', 'claim_operator_id', 'claim_operator' ], + raw: true, + }); + + // 拦截流程中的订单不允许抓取波次,直接剔除 + const orderRowMap = new Map((Array.isArray(orderRows) ? orderRows : []) + .map(row => [ Number(row && row.id || 0), row ])); + const interceptedOrderIds = new Set((Array.isArray(orderRows) ? orderRows : []) + .filter(row => isInterceptedOrderStatus(row && row.intercept_status)) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)); + if (interceptedOrderIds.size > 0) { + const excludedIds = normalizedOrderIds.filter(id => interceptedOrderIds.has(id)); + if (excludedIds.length > 0) { + ctx.logger.info('[pick.createWavePickTask] 剔除拦截订单: %s', excludedIds.join(',')); + } + } + + // 领料语义(普通波次 source=0):未领料或领料人非本人的订单不参与拣货数量计算,直接剔除 + const unclaimedOrderIds = excludeUnclaimed + ? new Set(normalizedOrderIds.filter(id => { + const row = orderRowMap.get(id); + if (!row || String(row && row.claim_status || '') !== 'fin') { + return true; + } + return Number(row && row.claim_operator_id || 0) !== operatorId; + })) + : new Set(); + if (unclaimedOrderIds.size > 0) { + const excludedIds = normalizedOrderIds.filter(id => unclaimedOrderIds.has(id)); + if (excludedIds.length > 0) { + ctx.logger.info('[pick.createWavePickTask] 剔除未领料订单: %s', excludedIds.join(',')); + } + } + + const activeOrderIds = normalizedOrderIds + .filter(id => !interceptedOrderIds.has(id) && !unclaimedOrderIds.has(id)); + if (activeOrderIds.length <= 0) { + const emptyReason = unclaimedOrderIds.size > 0 + ? '波次下订单均未领料或均被拦截,无法创建任务' + : '波次下订单均已被拦截,无法创建任务'; + throw Object.assign(new Error(emptyReason), { code: 400 }); + } + + // 取首个活跃订单的领料人冗余写入任务主表(整波领单同波次领料人一致) + const firstActiveOrderRow = orderRowMap.get(activeOrderIds[0]) || null; + const claimOperatorId = Number(firstActiveOrderRow && firstActiveOrderRow.claim_operator_id || 0); + const claimOperator = String(firstActiveOrderRow && firstActiveOrderRow.claim_operator || '').trim(); + + const orderNoMap = new Map((Array.isArray(orderRows) ? orderRows : []) + .map(row => [ Number(row && row.id || 0), '' ])); + + const taskNo = this.generatePickTaskNo(); + const transaction = await ctx.model.transaction(); + try { + const taskInsertResult = await ctx.model.query( + ` + INSERT INTO wms_wave_pick_task ( + task_no, + warehouse_id, + wave_id, + claim_operator_id, + claim_operator, + batch_no, + batch_no_array, + pick_mode, + status, + source, + wave_count, + order_count, + box_count, + pick_user_id, + pick_user_name, + remark, + create_time, + update_time + ) VALUES ( + :taskNo, + :warehouseId, + :waveId, + :claimOperatorId, + :claimOperator, + :batchNo, + :batchNoArray, + :pickMode, + 0, + :source, + 1, + :orderCount, + 0, + :operatorId, + :operatorName, + :remark, + NOW(), + NOW() + ) + `, + { + replacements: { + taskNo, + warehouseId, + waveId, + claimOperatorId: claimOperatorId > 0 ? claimOperatorId : null, + claimOperator: claimOperator || null, + batchNo: waveNo, + batchNoArray: waveNo, + pickMode, + source, + orderCount: activeOrderIds.length, + operatorId, + operatorName, + remark, + }, + transaction, + } + ); + + const taskInsertHead = Array.isArray(taskInsertResult) ? taskInsertResult[0] : null; + const taskInsertMeta = Array.isArray(taskInsertResult) ? taskInsertResult[1] : null; + let taskId = Number( + (taskInsertMeta && (taskInsertMeta.insertId || taskInsertMeta.lastID || taskInsertMeta.id)) + || (taskInsertHead && (taskInsertHead.insertId || taskInsertHead.lastID || taskInsertHead.id)) + || 0 + ); + if (!Number.isInteger(taskId) || taskId <= 0) { + const taskIdRows = await ctx.model.query( + ` + SELECT id + FROM wms_wave_pick_task + WHERE warehouse_id = :warehouseId + AND task_no = :taskNo + ORDER BY id DESC + LIMIT 1 + `, + { + replacements: { + warehouseId, + taskNo, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const taskRow = Array.isArray(taskIdRows) && taskIdRows.length > 0 ? taskIdRows[0] : null; + taskId = Number(taskRow && taskRow.id || 0); + } + if (!Number.isInteger(taskId) || taskId <= 0) { + throw Object.assign(new Error('任务创建失败(未返回任务ID)'), { code: 500 }); + } + + await ctx.model.query( + ` + INSERT INTO wms_wave_pick_task_wave ( + task_id, + wave_id, + wave_no, + status, + warehouse_id, + bind_time, + create_time, + update_time + ) VALUES ( + :taskId, + :waveId, + :waveNo, + 0, + :warehouseId, + NOW(), + NOW(), + NOW() + ) + `, + { + replacements: { + taskId, + waveId, + waveNo, + warehouseId, + }, + transaction, + } + ); + + if (activeOrderIds.length > 0) { + // 按库位排序并按 stock_id 分组,同 stock_id 的订单共享同一篮号 + const stockGroups = await this.resolveLocationSortedOrderIds( + activeOrderIds, + warehouseId, + transaction + ); + + // 写入 wms_wave_pick_task_box:每个 stock_id 一个框,记录 stock_id → box_no 映射 + const boxValuesSql = []; + const boxReplacements = {}; + let boxNo = 0; + let boxIndex = 0; + for (const group of stockGroups) { + boxNo += 1; + const stockId = group.stock_id > 0 ? group.stock_id : 0; + const boxNoKey = `boxNo${boxIndex}`; + const stockIdKey = `stockId${boxIndex}`; + const boxCodeKey = `boxCode${boxIndex}`; + boxValuesSql.push(`( + :taskId, + NULL, + :${boxCodeKey}, + :${boxNoKey}, + 1, + :${stockIdKey}, + NULL, + 0, + 0, + 0, + NULL, + NULL, + NULL, + :warehouseId, + NOW(), + NOW() + )`); + boxReplacements[boxNoKey] = boxNo; + boxReplacements[stockIdKey] = stockId; + boxReplacements[boxCodeKey] = `${taskNo}-S${boxNo}`; + boxIndex += 1; + } + + if (boxValuesSql.length > 0) { + await ctx.model.query( + ` + INSERT INTO wms_wave_pick_task_box ( + task_id, + order_id, + box_code, + box_no, + box_type, + ref_id, + ref_label, + required_qty, + picked_qty, + box_status, + review_result, + review_user_id, + review_time, + warehouse_id, + create_time, + update_time + ) VALUES ${boxValuesSql.join(',\n')} + `, + { + replacements: { + taskId, + warehouseId, + ...boxReplacements, + }, + transaction, + } + ); + + // 更新任务主表的 box_count(大团购固定 1,其余按实际筐数) + await ctx.model.query( + `UPDATE wms_wave_pick_task + SET box_count = :boxCount, + update_time = NOW() + WHERE id = :taskId`, + { + replacements: { taskId, boxCount: pickMode === 5 ? 1 : boxValuesSql.length }, + transaction, + } + ); + } + + // 写入 wms_wave_pick_task_order:每个订单写入一次(取该订单所属的最小 box_no) + const orderBoxMap = new Map(); + boxNo = 0; + for (const group of stockGroups) { + boxNo += 1; + for (const orderId of group.order_ids) { + if (!orderBoxMap.has(orderId) || orderBoxMap.get(orderId) > boxNo) { + orderBoxMap.set(orderId, boxNo); + } + } + } + + const orderValuesSql = []; + const orderReplacements = {}; + let paramIndex = 0; + for (const [ orderId, orderBoxNo ] of orderBoxMap) { + const orderIdKey = `orderId${paramIndex}`; + const orderNoKey = `orderNo${paramIndex}`; + const boxNoKey = `oBoxNo${paramIndex}`; + orderValuesSql.push(`( + :taskId, + :waveId, + :${orderIdKey}, + :${orderNoKey}, + :${boxNoKey}, + :warehouseId, + 0, + 0, + NOW(), + NOW() + )`); + orderReplacements[orderIdKey] = orderId; + orderReplacements[orderNoKey] = orderNoMap.get(orderId) || ''; + orderReplacements[boxNoKey] = orderBoxNo; + paramIndex += 1; + } + + await ctx.model.query( + ` + INSERT INTO wms_wave_pick_task_order ( + task_id, + wave_id, + order_id, + order_no, + box_no, + warehouse_id, + pick_status, + review_status, + create_time, + update_time + ) VALUES ${orderValuesSql.join(',\n')} + `, + { + replacements: { + taskId, + waveId, + warehouseId, + ...orderReplacements, + }, + transaction, + } + ); + } + + await transaction.commit(); + + // 写入 order_operation_log 开始拣货日志 + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logPayloads = activeOrderIds.map(orderId => ({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_PICKING', + operator: { + id: operatorId ? String(operatorId) : null, + name: operatorName || 'system', + }, + extras: { + message: `订单${orderId}开始拣货(波次 ${waveNo})`, + warehouseId, + externalLogType: 'API', + }, + })); + await operationLogService.createOperationLogs(logPayloads); + } + } catch (e) { + ctx.logger.warn('[pick.createWavePickTask] 写入 order_operation_log 失败,不影响主流程', { + error: e && e.message, + activeOrderIds, + }); + } + + return { + task_id: taskId, + task_no: taskNo, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 按库位排序并按 stock_id 分组订单,使 box_no 按拣货路径顺序分配。 + * + * 同 stock_id 的订单归入同一组(同一篮号),组间按 pick_sequence ASC 排序。 + * 若某订单无拣货数据(未分配储位),排到末尾保持原顺序。 + * + * @param {Array} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise>} 按库位排序后的分组列表。 + */ + async resolveLocationSortedOrderIds(orderIds, warehouseId, transaction) { + const { ctx } = this; + const normalizedOrderIds = [ ...new Set((Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (normalizedOrderIds.length === 0) { + return []; + } + + if (normalizedOrderIds.length === 1) { + return [{ stock_id: 0, order_ids: normalizedOrderIds }]; + } + + try { + // 查询拣货明细获取 order_item_id 和 space_id + const pickingRows = await ctx.model.Picking.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: normalizedOrderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'order_id', 'order_item_id', 'space_id' ], + raw: true, + transaction, + }); + + const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; + const orderSpaceMap = new Map(); + const orderItemIds = []; + for (const row of normalizedPickingRows) { + const oid = Number(row && row.order_id || 0); + const sid = Number(row && row.space_id || 0); + const oiid = Number(row && row.order_item_id || 0); + if (oid > 0 && !orderSpaceMap.has(oid)) { + orderSpaceMap.set(oid, sid); + } + if (oiid > 0) { + orderItemIds.push(oiid); + } + } + + // 查询订单商品明细获取 stock_id,收集每个订单的所有 stock_id + const orderStockIdSet = new Map(); + if (orderItemIds.length > 0) { + const factory = ctx.model && ctx.model.OrderItemsFactory; + if (factory && typeof factory.getCurrentModel === 'function') { + const orderItemModel = await factory.getCurrentModel(warehouseId); + if (orderItemModel && typeof orderItemModel.findAll === 'function') { + const itemRows = await orderItemModel.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: [ ...new Set(orderItemIds) ] }, + }, + attributes: [ 'id', 'order_id', 'stock_id' ], + raw: true, + transaction, + }); + for (const row of (Array.isArray(itemRows) ? itemRows : [])) { + const oid = Number(row && row.order_id || 0); + const stockId = Number(row && row.stock_id || 0); + if (oid > 0 && stockId > 0) { + if (!orderStockIdSet.has(oid)) { + orderStockIdSet.set(oid, new Set()); + } + orderStockIdSet.get(oid).add(stockId); + } + } + } + } + } + + // 按 stock_id 分组:每个 stock_id 一个组,订单可出现在多个组(多商品订单) + const groupMap = new Map(); + for (const oid of normalizedOrderIds) { + const stockIds = orderStockIdSet.get(oid); + if (stockIds && stockIds.size > 0) { + for (const stockId of stockIds) { + if (!groupMap.has(stockId)) { + groupMap.set(stockId, { stock_id: stockId, order_ids: [] }); + } + groupMap.get(stockId).order_ids.push(oid); + } + } else { + const key = -oid; // 无 stock_id 的订单各自成组 + if (!groupMap.has(key)) { + groupMap.set(key, { stock_id: 0, order_ids: [] }); + } + groupMap.get(key).order_ids.push(oid); + } + } + + const spaceIds = [ ...new Set([ ...orderSpaceMap.values() ].filter(sid => sid > 0)) ]; + const sequenceMap = new Map(); + if (spaceIds.length > 0) { + const locationRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [this.app.Sequelize.Op.in]: spaceIds } }, + attributes: [ 'id', 'pick_sequence' ], + raw: true, + transaction, + }); + for (const row of (Array.isArray(locationRows) ? locationRows : [])) { + const lid = Number(row && row.id || 0); + if (lid > 0 && !sequenceMap.has(lid)) { + sequenceMap.set(lid, Number(row.pick_sequence || 0)); + } + } + } + + // 每组取最小 pick_sequence 排序 + const groups = [ ...groupMap.values() ]; + groups.sort((a, b) => { + const seqA = Math.min(...a.order_ids.map(oid => sequenceMap.get(orderSpaceMap.get(oid)) ?? Number.MAX_SAFE_INTEGER)); + const seqB = Math.min(...b.order_ids.map(oid => sequenceMap.get(orderSpaceMap.get(oid)) ?? Number.MAX_SAFE_INTEGER)); + if (seqA !== seqB) return seqA - seqB; + return a.order_ids[0] - b.order_ids[0]; + }); + + return groups; + } catch (error) { + ctx.logger.warn('[pick.resolveLocationSortedOrderIds] 按库位排序失败,退回原顺序', { + error: error && error.message, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + return [{ stock_id: 0, order_ids: normalizedOrderIds }]; + } + } + + /** + * 按关键字获取或创建波次拣货任务。 + * + * 关键字支持两种命中方式: + * - 命中运单号:先定位订单并强校验订单已入波次。 + * - 命中波次号:直接按波次定位。 + * + * 去重策略(按优先级): + * 1. 波次级去重:同一 warehouse_id + 同一 wave_id 且存在活动任务(status IN 0,1)时不再创建。 + * 2. keyword 级去重:同一 warehouse_id + 同一 keyword(remark 字段)在 30 分钟内已有任务时不再创建。 + * - 已完成(status IN 2,3):直接返回已有任务结果。 + * - 进行中(status IN 0,1):返回冲突提示。 + * + * 命中目标波次后按以下规则处理: + * - 若波次存在活动任务且创建人为当前用户:直接返回任务ID。 + * - 若波次存在活动任务但创建人非当前用户:返回冲突失败信息。 + * - 若波次不存在活动任务:按波次类型创建任务并返回任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.keyword 运单号或波次号关键字。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async query(data = {}) { + const { ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const { keyword } = requestData; + + const normalizedKeyword = String(keyword || '').trim(); + if (!normalizedKeyword) { + return this.fail('请传入关键字 keyword', {}, 400); + } + + const userWarehouseId = ctx && ctx.user ? ctx.user.store_id : undefined; + const stateWarehouseId = ctx && ctx.state && ctx.state.user ? ctx.state.user.store_id : undefined; + const normalizedWarehouseId = Number(userWarehouseId || stateWarehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return this.fail('缺少当前用户仓库上下文 store_id', {}, 400); + } + + const stateUser = this.isPlainObject(ctx && ctx.state && ctx.state.user) ? ctx.state.user : null; + const ctxUser = this.isPlainObject(ctx && ctx.user) ? ctx.user : null; + const operatorSource = stateUser || ctxUser || {}; + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const operatorId = Number(rawOperatorId || 0); + const operatorName = String( + operatorSource.operator_name + || operatorSource.employees_name + || operatorSource.name + || '' + ).trim() || 'system'; + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 401); + } + + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { + warehouse_id: normalizedWarehouseId, + waybill_code: normalizedKeyword, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + let targetWaveId = 0; + let targetWaveNo = ''; + let targetWaveType = 2; + let targetWaveSource = 0; + let selectedOrderIds = []; + + const orderId = Number(orderExpress && orderExpress.order_id || 0); + if (orderExpress && orderId > 0) { + let orderModel = null; + try { + orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); + } catch (error) { + return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500); + } + + const order = await orderModel.findOne({ + where: { + id: orderId, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'wave_no', 'wave_id' ], + raw: true, + }); + if (!order) { + return this.fail('运单对应订单不存在', {}, 404); + } + + const orderWaveId = Number(order.wave_id || 0); + const orderWaveNo = String(order.wave_no || '').trim(); + if (!(orderWaveId > 0 || orderWaveNo)) { + return this.fail('运单对应订单未进入波次,无法创建拣货任务', {}, 400); + } + + if (orderWaveId > 0) { + const waveByIdRows = await ctx.model.query( + ` + SELECT wave_id, wave_no, wave_type, source + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT 1 + `, + { + replacements: { + warehouseId: normalizedWarehouseId, + waveId: orderWaveId, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const waveRow = Array.isArray(waveByIdRows) && waveByIdRows.length > 0 ? waveByIdRows[0] : null; + if (!waveRow) { + return this.fail('运单对应波次不存在或不属于当前仓库', {}, 404); + } + + targetWaveId = Number(waveRow.wave_id || 0); + targetWaveNo = String(waveRow.wave_no || '').trim(); + targetWaveType = Number(waveRow.wave_type || 2); + targetWaveSource = Number(waveRow.source || 0); + } else { + const waveByNoRows = await ctx.model.query( + ` + SELECT wave_id, wave_no, wave_type, source + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_no = :waveNo + LIMIT 1 + `, + { + replacements: { + warehouseId: normalizedWarehouseId, + waveNo: orderWaveNo, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const waveRow = Array.isArray(waveByNoRows) && waveByNoRows.length > 0 ? waveByNoRows[0] : null; + if (!waveRow) { + return this.fail('运单对应波次不存在或不属于当前仓库', {}, 404); + } + + targetWaveId = Number(waveRow.wave_id || 0); + targetWaveNo = String(waveRow.wave_no || '').trim(); + targetWaveType = Number(waveRow.wave_type || 2); + targetWaveSource = Number(waveRow.source || 0); + } + } else { + const waveRows = await ctx.model.query( + ` + SELECT wave_id, wave_no, wave_type, source + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_no = :waveNo + LIMIT 1 + `, + { + replacements: { + warehouseId: normalizedWarehouseId, + waveNo: normalizedKeyword, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + if (!waveRow) { + return this.fail('关键字未命中运单号或波次号', {}, 404); + } + + targetWaveId = Number(waveRow.wave_id || 0); + targetWaveNo = String(waveRow.wave_no || '').trim(); + targetWaveType = Number(waveRow.wave_type || 2); + targetWaveSource = Number(waveRow.source || 0); + } + + if (!Number.isInteger(targetWaveId) || targetWaveId <= 0 || !targetWaveNo) { + return this.fail('目标波次信息不完整', {}, 400); + } + + // 领料前置校验:source=0 普通波次需整波领料,未领料阻隔创建拣货任务 + // (未打印的拦截订单未领料不阻隔拣货,拦截订单将在任务创建时被剔除; + // 已打印的拦截订单面单实物已流出,仍需先领料登记) + if (targetWaveSource === 0) { + const claimGatePickMode = await this.getWavePickModeByWaveId(targetWaveId); + let claimGateOrderModel = null; + try { + claimGateOrderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); + } catch (error) { + return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500); + } + + const claimGateStats = await this.getWaveClaimGateStats({ + orderModel: claimGateOrderModel, + warehouseId: normalizedWarehouseId, + waveId: targetWaveId, + waveNo: targetWaveNo, + claimOperatorId: operatorId, + }); + if (claimGateStats.total_order_count > 0 && claimGateStats.unclaimed_order_count > 0) { + return this.fail('订单未领料或领料人不是本人,请先领料后再拣货', { + action: 'wave_claim', + wave_id: targetWaveId, + wave_no: targetWaveNo, + wave_type: targetWaveType, + wave_source: targetWaveSource, + pick_mode: claimGatePickMode, + unclaimed_order_count: claimGateStats.unclaimed_order_count, + intercepted_order_count: claimGateStats.intercepted_order_count, + total_order_count: claimGateStats.total_order_count, + }, 400); + } + } + + const activeTaskRows = await ctx.model.query( + ` + SELECT t.id AS task_id, t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.status IN (0, 1) + AND ( + t.wave_id = :waveId + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = t.id + AND tw.wave_id = :waveId + ) + ) + ORDER BY t.id DESC + LIMIT 1 + `, + { + replacements: { + waveId: targetWaveId, + warehouseId: normalizedWarehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const activeTask = Array.isArray(activeTaskRows) && activeTaskRows.length > 0 ? activeTaskRows[0] : null; + if (activeTask) { + const activeTaskId = Number(activeTask.task_id || 0); + const taskOwnerId = Number(activeTask.pick_user_id || 0); + const taskOwnerName = String(activeTask.pick_user_name || '').trim() || `${taskOwnerId}`; + if (taskOwnerId > 0 && taskOwnerId === operatorId) { + return this.success('ok', { + data: { + task_id: activeTaskId, + status: 'existing', + tip: '当前波次已有您创建的活动任务,可直接继续', + }, + code: 200, + }); + } + + return this.fail( + `当前波次已由其他人创建活动任务,请移交任务创建人处理(创建人: ${taskOwnerName},任务ID: ${activeTaskId})`, + { + task_id: activeTaskId, + task_owner_id: taskOwnerId, + task_owner_name: taskOwnerName, + }, + 409 + ); + } + + // 波次级已完成任务去重:同一 warehouse_id + 同一 wave_id 已有完成任务时不再创建 + const completedTaskRows = await ctx.model.query( + ` + SELECT t.id AS task_id, t.status, t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.status IN (2, 3) + AND ( + t.wave_id = :waveId + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = t.id + AND tw.wave_id = :waveId + ) + ) + ORDER BY t.id DESC + LIMIT 1 + `, + { + replacements: { + waveId: targetWaveId, + warehouseId: normalizedWarehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const completedTask = Array.isArray(completedTaskRows) && completedTaskRows.length > 0 ? completedTaskRows[0] : null; + if (completedTask) { + return this.success('ok', { + data: { + task_id: Number(completedTask.task_id), + status: 'existing_completed', + tip: '该波次已完成拣货任务,无需重复创建', + }, + code: 200, + }); + } + + // keyword 级别去重:同一 warehouse_id + 同一 keyword(remark)在 30 分钟内已有任务则不再创建 + const keywordRemark = `pick.query keyword=${normalizedKeyword}`; + const keywordDedupRows = await ctx.model.query( + ` + SELECT t.id AS task_id, t.status, t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.remark = :remark + AND t.create_time >= DATE_SUB(NOW(), INTERVAL 30 MINUTE) + ORDER BY t.id DESC + LIMIT 1 + `, + { + replacements: { + warehouseId: normalizedWarehouseId, + remark: keywordRemark, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const keywordDedupTask = Array.isArray(keywordDedupRows) && keywordDedupRows.length > 0 ? keywordDedupRows[0] : null; + if (keywordDedupTask) { + const existingTaskId = Number(keywordDedupTask.task_id || 0); + const existingStatus = Number(keywordDedupTask.status ?? -1); + + // 已完成(status=2 待复核 / status=3 已完成):直接返回已有结果,不创建新任务 + if (existingStatus === 2 || existingStatus === 3) { + return this.success('ok', { + data: { + task_id: existingTaskId, + status: 'existing_completed', + tip: '该关键字近期已有完成任务,无需重复创建', + }, + code: 200, + }); + } + + // 进行中(status=0 待开始 / status=1 拣货中):返回已有任务ID,提示任务进行中 + if (existingStatus === 0 || existingStatus === 1) { + const taskOwnerId = Number(keywordDedupTask.pick_user_id || 0); + const taskOwnerName = String(keywordDedupTask.pick_user_name || '').trim() || `${taskOwnerId}`; + return this.fail( + `该关键字近期已有进行中任务(创建人: ${taskOwnerName},任务ID: ${existingTaskId}),请稍后再试`, + { + task_id: existingTaskId, + task_owner_id: taskOwnerId, + task_owner_name: taskOwnerName, + }, + 409 + ); + } + } + + const normalizedWaveType = Number(targetWaveType || 2); + const isGroupWave = normalizedWaveType === 1; + // 检查是否为 singleFetchByIds 创建的波次(item_part_type='manual_ids'),使用先拣后分模式 + let isManualIdsWave = false; + try { + const waveInfoRows = await ctx.model.query( + `SELECT item_part_type + FROM wms_wave_batch + WHERE wave_id = :waveId + LIMIT 1`, + { + replacements: { waveId: targetWaveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const waveInfo = Array.isArray(waveInfoRows) && waveInfoRows.length > 0 ? waveInfoRows[0] : null; + isManualIdsWave = String(waveInfo && waveInfo.item_part_type || '').trim() === 'manual_ids'; + } catch (e) { + // 查询失败不影响主流程,退回默认拣货模式 + } + const pickMode = isGroupWave ? 5 : (isManualIdsWave ? 3 : 2); + + if (selectedOrderIds.length === 0) { + let orderModel = null; + try { + orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); + } catch (error) { + return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500); + } + + const orderRows = await orderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + wave_id: targetWaveId, + }, + attributes: [ 'id' ], + raw: true, + }); + selectedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (selectedOrderIds.length <= 0) { + const fallbackRows = await orderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + wave_no: targetWaveNo, + }, + attributes: [ 'id' ], + raw: true, + }); + selectedOrderIds = [ ...new Set((Array.isArray(fallbackRows) ? fallbackRows : []) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + } + + if (selectedOrderIds.length <= 0) { + return this.fail('波次下无可用订单,无法创建任务', {}, 400); + } + } + + // 跨波次订单级去重:检查这批订单是否已有已完成(status 2/3)的拣货任务 + if (selectedOrderIds.length > 0) { + const crossWaveDedupRows = await ctx.model.query( + ` + SELECT t.id AS task_id, t.task_no, t.status, t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task t + INNER JOIN wms_wave_pick_task_order pto + ON pto.task_id = t.id + AND pto.warehouse_id = t.warehouse_id + WHERE t.warehouse_id = :warehouseId + AND t.status IN (2, 3) + AND pto.order_id IN (:orderIds) + AND pto.pick_status = 1 + ORDER BY t.id DESC + LIMIT 1 + `, + { + replacements: { + warehouseId: normalizedWarehouseId, + orderIds: selectedOrderIds, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const crossWaveDedupTask = Array.isArray(crossWaveDedupRows) && crossWaveDedupRows.length > 0 + ? crossWaveDedupRows[0] + : null; + if (crossWaveDedupTask) { + return this.success('ok', { + data: { + task_id: Number(crossWaveDedupTask.task_id), + status: 'existing_completed', + tip: '该批订单已有完成拣货任务,无需重复创建', + }, + code: 200, + }); + } + } + + try { + const createdTask = await this.createWavePickTask({ + warehouseId: normalizedWarehouseId, + waveId: targetWaveId, + waveNo: targetWaveNo, + pickMode, + operatorId, + operatorName, + orderIds: selectedOrderIds, + remark: `pick.query keyword=${normalizedKeyword}`, + source: 2, + // 普通波次(source=0):计算拣货数量时剔除未领料(claim_status != fin)订单 + excludeUnclaimed: targetWaveSource === 0, + }); + + return this.success('ok', { + data: { + task_id: createdTask.task_id, + status: 'created', + tip: '任务创建成功', + }, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isFinite(code) && code >= 400 && code < 600) { + return this.fail(error.message || '任务创建失败', {}, code); + } + + ctx.logger.error('[PickService.query] 获取或创建波次任务失败: %s', error && error.message ? error.message : error); + return this.fail('任务创建失败', {}, 500); + } + } + + /** + * 查询拣货任务详情。 + * + * 仅允许任务创建人查看任务详情,包含主任务、波次、订单与框信息。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.task_id 拣货任务ID。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async wavePickTaskDetail(data = {}) { + const { service, ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const { task_id } = requestData; + + const taskId = Number(task_id); + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必填且必须为正整数', {}, 400); + } + + const stateUser = this.isPlainObject(ctx && ctx.state && ctx.state.user) ? ctx.state.user : null; + const ctxUser = this.isPlainObject(ctx && ctx.user) ? ctx.user : null; + const operatorSource = stateUser || ctxUser || {}; + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const operatorId = Number(rawOperatorId || 0); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 401); + } + + try { + const result = await service.systems.pick.wavePickTaskDetail({ + taskId, + operatorId, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = this.isPlainObject(error && error.data) ? error.data : {}; + return this.fail(error.message || '查询失败', errorData, code); + } + + ctx.logger.error('[PickService.wavePickTaskDetail] 查询拣货任务详情失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } + + /** + * 查询当前登录用户正在处理中的拣货任务。 + * + * 仅供 PDA 使用,无需入参;按当前登录用户与仓库上下文返回最新任务ID。 + * + * @return {Promise} 统一 success/fail 包装结果。 + */ + async wavePickTaskCurrent() { + const { service, ctx } = this; + + try { + const result = await service.systems.pick.wavePickTaskCurrent(); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || '查询失败', {}, code); + } + + ctx.logger.error('[PickService.wavePickTaskCurrent] 查询当前拣货任务失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } + + /** + * 提交拣货任务中间态。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.task_id 拣货任务ID。 + * @param {Object} [data.payload] 中间态业务数据。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async wavePickTaskSubmit(data = {}) { + const { service, ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const taskId = Number(requestData.task_id || requestData.taskId || 0); + + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pick.wavePickTaskSubmit({ + taskId, + payload: this.isPlainObject(requestData.payload) ? requestData.payload : {}, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = this.isPlainObject(error && error.data) ? error.data : {}; + return this.fail(error.message || '提交失败', errorData, code); + } + + ctx.logger.error('[PickService.wavePickTaskSubmit] 提交拣货任务中间态失败: %s', error && error.message ? error.message : error); + return this.fail('提交失败', {}, 500); + } + } + + /** + * 按波次号一键完成拣货。 + * + * 内部复用 query 的去重与任务创建逻辑: + * - 若波次已有当前用户的活动任务 → 直接复用并完成。 + * - 若波次已有他人活动任务 → 返回 409 冲突。 + * - 若波次已完成 → 返回 already_completed。 + * - 否则新建任务(source=2,后台抓取),创建成功后在内部调用 wavePickTaskComplete(mode=1 全部确认)完成拣货。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.wave_id 波次ID。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async wavePickComplete(data = {}) { + const { service, ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const waveId = Number(requestData.wave_id || requestData.waveId || 0); + + if (!Number.isInteger(waveId) || waveId <= 0) { + return this.fail('wave_id 必填且必须为正整数', {}, 400); + } + + // --- 解析操作人上下文(与 query 保持一致)--- + const userWarehouseId = ctx && ctx.user ? ctx.user.store_id : undefined; + const stateWarehouseId = ctx && ctx.state && ctx.state.user ? ctx.state.user.store_id : undefined; + const normalizedWarehouseId = Number(userWarehouseId || stateWarehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return this.fail('缺少当前用户仓库上下文 store_id', {}, 400); + } + + const stateUser = this.isPlainObject(ctx && ctx.state && ctx.state.user) ? ctx.state.user : null; + const ctxUser = this.isPlainObject(ctx && ctx.user) ? ctx.user : null; + const operatorSource = stateUser || ctxUser || {}; + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const operatorId = Number(rawOperatorId || 0); + const operatorName = String( + operatorSource.operator_name + || operatorSource.employees_name + || operatorSource.name + || '' + ).trim() || 'system'; + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 401); + } + + // --- 按 wave_id 直接查波次 --- + const waveRows = await ctx.model.query( + `SELECT wave_id, wave_no, wave_type, source + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT 1`, + { + replacements: { warehouseId: normalizedWarehouseId, waveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + if (!waveRow) { + return this.fail('波次不存在或不属于当前仓库', {}, 404); + } + + const targetWaveId = Number(waveRow.wave_id || 0); + const targetWaveNo = String(waveRow.wave_no || '').trim(); + const targetWaveType = Number(waveRow.wave_type || 2); + const targetWaveSource = Number(waveRow.source || 0); + + if (!Number.isInteger(targetWaveId) || targetWaveId <= 0 || !targetWaveNo) { + return this.fail('目标波次信息不完整', {}, 400); + } + + // --- 去重:活动任务检查(与 query 一致)--- + const activeTaskRows = await ctx.model.query( + `SELECT t.id AS task_id, t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.status IN (0, 1) + AND ( + t.wave_id = :waveId + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = t.id + AND tw.wave_id = :waveId + ) + ) + ORDER BY t.id DESC + LIMIT 1`, + { + replacements: { waveId: targetWaveId, warehouseId: normalizedWarehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const activeTask = Array.isArray(activeTaskRows) && activeTaskRows.length > 0 ? activeTaskRows[0] : null; + + let taskId = 0; + + if (activeTask) { + const activeTaskId = Number(activeTask.task_id || 0); + const taskOwnerId = Number(activeTask.pick_user_id || 0); + const taskOwnerName = String(activeTask.pick_user_name || '').trim() || `${taskOwnerId}`; + if (taskOwnerId > 0 && taskOwnerId !== operatorId) { + return this.fail( + `当前波次已由其他人创建活动任务,请移交任务创建人处理(创建人: ${taskOwnerName},任务ID: ${activeTaskId})`, + { task_id: activeTaskId, task_owner_id: taskOwnerId, task_owner_name: taskOwnerName }, + 409 + ); + } + // 当前用户的活动任务,直接复用 + taskId = activeTaskId; + } + + // --- 去重:已完成任务检查(与 query 一致)--- + if (taskId <= 0) { + const completedTaskRows = await ctx.model.query( + `SELECT t.id AS task_id + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.status IN (2, 3) + AND ( + t.wave_id = :waveId + OR EXISTS ( + SELECT 1 + FROM wms_wave_pick_task_wave tw + WHERE tw.task_id = t.id + AND tw.wave_id = :waveId + ) + ) + ORDER BY t.id DESC + LIMIT 1`, + { + replacements: { waveId: targetWaveId, warehouseId: normalizedWarehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const completedTask = Array.isArray(completedTaskRows) && completedTaskRows.length > 0 ? completedTaskRows[0] : null; + if (completedTask) { + return this.success('ok', { + data: { + task_id: Number(completedTask.task_id), + status: 'already_completed', + tip: '该波次已完成拣货任务,无需重复操作', + }, + code: 200, + }); + } + } + + // --- 无已有任务则创建新任务(与 query 一致)--- + if (taskId <= 0) { + let orderModel = null; + try { + orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); + } catch (error) { + return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500); + } + + const orderRows = await orderModel.findAll({ + where: { warehouse_id: normalizedWarehouseId, wave_id: targetWaveId }, + attributes: [ 'id' ], + raw: true, + }); + let selectedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (selectedOrderIds.length <= 0) { + const fallbackRows = await orderModel.findAll({ + where: { warehouse_id: normalizedWarehouseId, wave_no: targetWaveNo }, + attributes: [ 'id' ], + raw: true, + }); + selectedOrderIds = [ ...new Set((Array.isArray(fallbackRows) ? fallbackRows : []) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + } + + if (selectedOrderIds.length <= 0) { + return this.fail('波次下无可用订单,无法创建任务', {}, 400); + } + + const normalizedWaveType = Number(targetWaveType || 2); + const isGroupWave = normalizedWaveType === 1; + // 检查是否为 singleFetchByIds 创建的波次(item_part_type='manual_ids'),使用先拣后分模式 + let isManualIdsWaveWP = false; + try { + const waveInfoRowsWP = await ctx.model.query( + `SELECT item_part_type + FROM wms_wave_batch + WHERE wave_id = :waveId + LIMIT 1`, + { + replacements: { waveId: targetWaveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const waveInfoWP = Array.isArray(waveInfoRowsWP) && waveInfoRowsWP.length > 0 ? waveInfoRowsWP[0] : null; + isManualIdsWaveWP = String(waveInfoWP && waveInfoWP.item_part_type || '').trim() === 'manual_ids'; + } catch (e) { + // 查询失败不影响主流程,退回默认拣货模式 + } + const pickMode = isGroupWave ? 5 : (isManualIdsWaveWP ? 3 : 2); + + try { + const createdTask = await this.createWavePickTask({ + warehouseId: normalizedWarehouseId, + waveId: targetWaveId, + waveNo: targetWaveNo, + pickMode, + operatorId, + operatorName, + orderIds: selectedOrderIds, + remark: `pick.wavePickComplete wave_id=${waveId}`, + source: 2, + // 普通波次(source=0):计算拣货数量时剔除未领料(claim_status != fin)订单 + excludeUnclaimed: targetWaveSource === 0, + }); + taskId = createdTask.task_id; + } catch (error) { + const code = Number(error && error.code); + if (Number.isFinite(code) && code >= 400 && code < 600) { + return this.fail(error.message || '任务创建失败', {}, code); + } + ctx.logger.error('[PickService.wavePickComplete] 创建波次任务失败: %s', error && error.message ? error.message : error); + return this.fail('任务创建失败', {}, 500); + } + } + + // --- 任务已就绪,调用内部 wavePickTaskComplete 全部确认完成 --- + try { + const result = await service.systems.pick.wavePickTaskComplete({ + taskId, + mode: 1, + orderIds: [], + }); + + return this.success('ok', { + data: { + ...result, + status: 'completed', + tip: '波次拣货已完成', + }, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = this.isPlainObject(error && error.data) ? error.data : {}; + return this.fail(error.message || '拣货完成失败', errorData, code); + } + ctx.logger.error('[PickService.wavePickComplete] 完成拣货失败: %s', error && error.message ? error.message : error); + return this.fail('拣货完成失败', {}, 500); + } + } + + /** + * 完全提交拣货任务。 + * + * mode: 1=全部确认,2=部分确认(需传 order_ids)。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.task_id 拣货任务ID。 + * @param {number|string} [data.mode=1] 提交模式。 + * @param {Array|number|string} [data.order_ids] 部分确认时的订单ID集合。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async wavePickTaskComplete(data = {}) { + const { service, ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const taskId = Number(requestData.task_id || requestData.taskId || 0); + const mode = Number(requestData.mode || 1); + const rawOrderIds = requestData.order_ids !== undefined + ? requestData.order_ids + : requestData.orderIds; + let orderIds = []; + if (Array.isArray(rawOrderIds)) { + orderIds = rawOrderIds; + } else if (typeof rawOrderIds === 'string') { + orderIds = rawOrderIds.split(','); + } else if (typeof rawOrderIds === 'number') { + orderIds = [ rawOrderIds ]; + } + const normalizedOrderIds = [ ...new Set(orderIds + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pick.wavePickTaskComplete({ + taskId, + mode, + orderIds: normalizedOrderIds, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = this.isPlainObject(error && error.data) ? error.data : {}; + return this.fail(error.message || '提交失败', errorData, code); + } + + ctx.logger.error('[PickService.wavePickTaskComplete] 完全提交拣货任务失败: %s', error && error.message ? error.message : error); + return this.fail('提交失败', {}, 500); + } + } + + /** + * 查询波次关联的拣货模式。 + * + * 优先按拣货任务主表(wms_wave_pick_task.wave_id)直接关联查询, + * 未命中时回退到任务与波次关联表(wms_wave_pick_task_wave)查询。 + * + * @param {number|string} waveId 波次ID。 + * @return {Promise} 拣货模式:1-团购小波次 2-散单单品单件 3-先拣后分 4-边拣边分 5-团购大波次(0 表示无关联拣货任务)。 + */ + async getWavePickModeByWaveId(waveId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) { + return 0; + } + + const directRows = await ctx.model.query( + `SELECT pick_mode + FROM wms_wave_pick_task + WHERE wave_id = :waveId + ORDER BY id DESC + LIMIT 1`, + { + replacements: { waveId: normalizedWaveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const directRow = Array.isArray(directRows) && directRows.length > 0 ? directRows[0] : null; + if (directRow) { + return Number(directRow.pick_mode || 0); + } + + const linkRows = await ctx.model.query( + `SELECT t.pick_mode + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id + WHERE tw.wave_id = :waveId + ORDER BY t.id DESC + LIMIT 1`, + { + replacements: { waveId: normalizedWaveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const linkRow = Array.isArray(linkRows) && linkRows.length > 0 ? linkRows[0] : null; + return linkRow ? Number(linkRow.pick_mode || 0) : 0; + } + + /** + * 统计波次下领料门禁相关数量(普通波次 source=0 领料前置校验)。 + * + * 统计口径: + * - total_order_count:波次下全部订单数(含拦截订单); + * - intercepted_order_count:拦截订单数(intercept_status != none); + * - unclaimed_order_count:需要领料的订单数,包括未领料 + * (claim_status != fin)与已领料但领料人非本人(claim_operator_id != 操作人)两种; + * 未打印的拦截订单不阻隔拣货,不计入该数量;已打印(print_status=fin)的拦截订单 + * 面单实物已流出,仍需领料登记,计入该数量。 + * + * @param {Object} params 统计参数。 + * @param {Object} params.orderModel 订单分表模型。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.waveId 波次ID。 + * @param {string} [params.waveNo=''] 波次编码(wave_id 未命中时回退按 wave_no 统计)。 + * @param {number} [params.claimOperatorId=0] 当前操作人工号(判断领料人是否本人)。 + * @return {Promise<{total_order_count: number, intercepted_order_count: number, unclaimed_order_count: number}>} + * 统计结果。 + */ + async getWaveClaimGateStats(params = {}) { + const { ctx } = this; + const orderModel = params && params.orderModel; + const warehouseId = Number(params && params.warehouseId || 0); + const waveId = Number(params && params.waveId || 0); + const waveNo = String(params && params.waveNo || '').trim(); + const claimOperatorId = Number(params && params.claimOperatorId || 0); + if (!orderModel || typeof orderModel.findAll !== 'function') { + ctx.logger.warn('[pick.getWaveClaimGateStats] 订单模型不可用,返回空统计'); + return { total_order_count: 0, intercepted_order_count: 0, unclaimed_order_count: 0 }; + } + + let rows = []; + if (Number.isInteger(waveId) && waveId > 0) { + rows = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + wave_id: waveId, + }, + attributes: [ 'id', 'claim_status', 'intercept_status', 'claim_operator_id', 'print_status' ], + raw: true, + }); + rows = Array.isArray(rows) ? rows : []; + } + if (rows.length === 0 && waveNo) { + const fallbackRows = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + wave_no: waveNo, + }, + attributes: [ 'id', 'claim_status', 'intercept_status', 'claim_operator_id', 'print_status' ], + raw: true, + }); + rows = Array.isArray(fallbackRows) ? fallbackRows : []; + } + + const orderIds = [ ...new Set(rows + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const interceptedOrderIds = new Set(rows + .filter(item => isInterceptedOrderStatus(item && item.intercept_status)) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)); + // 仅未打印的拦截订单免领料;已打印的拦截订单面单实物已流出,仍需领料登记 + const interceptClaimSkippedOrderIds = new Set(rows + .filter(item => interceptedOrderIds.has(Number(item && item.id || 0)) + && String(item && item.print_status || '').trim() !== 'fin') + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)); + const unclaimedOrderCount = rows + .filter(item => { + const orderIdItem = Number(item && item.id || 0); + if (!orderIds.includes(orderIdItem) || interceptClaimSkippedOrderIds.has(orderIdItem)) { + return false; + } + if (String(item && item.claim_status || '') !== 'fin') { + return true; + } + // 已领料但领料人不是本人:仍视为需要领料 + return claimOperatorId > 0 && Number(item && item.claim_operator_id || 0) !== claimOperatorId; + }) + .length; + + return { + total_order_count: orderIds.length, + intercepted_order_count: interceptedOrderIds.size, + unclaimed_order_count: unclaimedOrderCount, + }; + } + + /** + * 递增「确认打印未领单波次」统计版本号(失败仅记录 warn,不影响主流程)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async bumpConfirmPrintUnclaimedWaveVersionSafe(warehouseId) { + const { ctx } = this; + try { + const waveService = ctx.service + && ctx.service.systemMethods + && ctx.service.systemMethods.order + && ctx.service.systemMethods.order.wave; + if (waveService && typeof waveService.bumpConfirmPrintUnclaimedWaveVersion === 'function') { + await waveService.bumpConfirmPrintUnclaimedWaveVersion(warehouseId); + } + } catch (error) { + ctx.logger.warn('[PickService.waveClaimScan] 统计版本号递增失败: %s', + error && error.message ? error.message : error); + } + } + + /** + * 补写波次领料时间。 + * + * 场景:波次下订单已全部领料(claim_status=fin),但波次表 claim_time 为空 + * (历史领单发生在 claim_time 字段之前,或旧版拦截逻辑跳过领料导致整波未写领料时间)。 + * 此时 order.wave.confirmPrintUnclaimedWaveCount 以波次表 claim_time 判定未领单, + * 会长期把该波次计为「已打印未领料」;而重复扫描领料只会返回 already_claimed, + * 不会补记,故在幂等分支补写一次领料时间。 + * + * @param {Object} params 参数。 + * @param {number} params.waveId 波次ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {string} params.operatorName 领料人。 + * @param {*} params.currentClaimTime 波次当前领料时间(非空则不补写)。 + * @return {Promise} 是否补写成功。 + */ + async backfillWaveClaimTime(params = {}) { + const { ctx } = this; + const waveId = Number(params.waveId || 0); + const warehouseId = Number(params.warehouseId || 0); + const operatorName = String(params.operatorName || '').trim() || 'system'; + if (!(waveId > 0) || !(warehouseId > 0) || params.currentClaimTime) { + return false; + } + try { + const updateResult = await ctx.model.WaveBatch.update( + { + claim_operator: operatorName, + claim_time: new Date(), + }, + { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + claim_time: null, + }, + } + ); + const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; + return affectedRows > 0; + } catch (error) { + ctx.logger.warn('[PickService.backfillWaveClaimTime] 波次领料时间补写失败: %s', + error && error.message ? error.message : error); + return false; + } + } + + /** + * 扫描面单号领取整波(领料)。 + * + * 按面单号(运单号,wms_order_express.waybill_code)定位待处理订单表中的订单后反查订单所在波次, + * 仅对普通波次(wms_wave_batch.source=0,含团购/散单)支持整波领料: + * 命中后将该波次下全部未领单订单 claim_status 置为 fin(领单完成), + * 并写入 ORDER_WAVE_CLAIM 订单操作日志,返回波次ID(wave_id)与波次编码(wave_no); + * 策略抓取波次(source=1/2)无需领料,返回 400 并提示「该波次为抓取波次,无需领料」 + * (失败 data 含 no_claim_needed=true、wave_id、wave_no); + * 波次下存在未打印订单(print_status != fin,拦截订单除外)时禁止领料, + * 返回 400 并提示「波次未打印,禁止领料」(失败 data 含 wave_id、wave_no、unprinted_order_count、 + * intercepted_order_count,拦截订单未打印不阻隔领料); + * 拦截订单跳过领料的口径按打印状态区分:未打印的拦截订单跳过领料(不置为 fin,其未打印状态也不阻隔整波领料); + * 已打印(print_status=fin)的拦截订单面单实物已随波次流出并被领取,照常置为领料完成,不再受拦截影响。 + * 其余未知类型返回通用不支持提示。 + * 波次内订单已全部领单时返回 already_claimed 幂等结果并提示已领料;此时若波次表 + * claim_time 为空(历史领单/旧版拦截跳过导致),补写一次领料时间,避免 + * order.wave.confirmPrintUnclaimedWaveCount 长期把该波次计为「已打印未领料」。 + * + * @param {Object} data 请求参数。 + * @param {string} data.waybill_no 面单号(运单号,wms_order_express.waybill_code)。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async waveClaimScan(data = {}) { + const { ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const waybillNo = String(requestData.waybill_no || requestData.waybillNo || '').trim(); + if (!waybillNo) { + return this.fail('waybill_no 必填(面单号/运单号)', {}, 400); + } + + // --- 仓库上下文与操作人 --- + const userWarehouseId = ctx && ctx.user ? ctx.user.store_id : undefined; + const stateWarehouseId = ctx && ctx.state && ctx.state.user ? ctx.state.user.store_id : undefined; + const normalizedWarehouseId = Number(userWarehouseId || stateWarehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return this.fail('缺少当前用户仓库上下文 store_id', {}, 400); + } + + const stateUser = this.isPlainObject(ctx && ctx.state && ctx.state.user) ? ctx.state.user : null; + const ctxUser = this.isPlainObject(ctx && ctx.user) ? ctx.user : null; + const operatorSource = stateUser || ctxUser || {}; + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const operatorId = Number(rawOperatorId || 0); + const operatorName = String( + operatorSource.operator_name + || operatorSource.employees_name + || operatorSource.name + || '' + ).trim() || 'system'; + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 401); + } + + // --- 1. 面单号定位订单 --- + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { + warehouse_id: normalizedWarehouseId, + waybill_code: waybillNo, + }, + attributes: [ 'order_id' ], + raw: true, + }); + const matchedOrderId = Number(orderExpress && orderExpress.order_id || 0); + if (!(matchedOrderId > 0)) { + return this.fail('未查询到该面单号对应的订单,无记录', {}, 404); + } + + // --- 2. 待处理订单表定位订单 --- + let orderModel = null; + try { + orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); + } catch (error) { + return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500); + } + const order = await orderModel.findOne({ + where: { + id: matchedOrderId, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (!order) { + return this.fail('订单不在待处理订单表,无记录', {}, 404); + } + + // --- 3. 订单定位波次 --- + const orderWaveId = Number(order.wave_id || 0); + const orderWaveNo = String(order.wave_no || '').trim(); + if (!(orderWaveId > 0 || orderWaveNo)) { + return this.fail('运单对应订单未分配波次', {}, 400); + } + + let waveRows = []; + if (orderWaveId > 0) { + waveRows = await ctx.model.query( + `SELECT wave_id, wave_no, wave_type, source, claim_time + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT 1`, + { + replacements: { + warehouseId: normalizedWarehouseId, + waveId: orderWaveId, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + } else { + waveRows = await ctx.model.query( + `SELECT wave_id, wave_no, wave_type, source, claim_time + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_no = :waveNo + LIMIT 1`, + { + replacements: { + warehouseId: normalizedWarehouseId, + waveNo: orderWaveNo, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + } + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + if (!waveRow) { + return this.fail('运单对应波次不存在或不属于当前仓库', {}, 404); + } + + const targetWaveId = Number(waveRow.wave_id || 0); + const targetWaveNo = String(waveRow.wave_no || '').trim(); + const targetWaveType = Number(waveRow.wave_type || 0); + const targetWaveSource = Number(waveRow.source || 0); + const targetWaveClaimTime = waveRow.claim_time || null; + if (!(targetWaveId > 0) || !targetWaveNo) { + return this.fail('目标波次信息不完整', {}, 400); + } + + // --- 4. 波次关联拣货模式与领料资格判定(仅普通波次 source=0 支持整波领料)--- + const pickMode = await this.getWavePickModeByWaveId(targetWaveId); + + const isFetchedWave = targetWaveSource === 1 || targetWaveSource === 2; + if (isFetchedWave) { + return this.fail('该波次为抓取波次,无需领料', { + no_claim_needed: true, + wave_id: targetWaveId, + wave_no: targetWaveNo, + wave_type: targetWaveType, + wave_source: targetWaveSource, + pick_mode: pickMode, + matched_order_id: matchedOrderId, + waybill_no: waybillNo, + }, 400); + } + if (targetWaveSource !== 0) { + return this.fail('当前波次类型不支持整波领单', { + wave_id: targetWaveId, + wave_no: targetWaveNo, + wave_type: targetWaveType, + wave_source: targetWaveSource, + }, 400); + } + + // --- 5. 查询波次下全部订单 --- + const waveOrderRows = await orderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + wave_id: targetWaveId, + }, + attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status', 'claim_operator_id' ], + raw: true, + }); + let waveOrders = Array.isArray(waveOrderRows) ? waveOrderRows : []; + if (waveOrders.length === 0) { + const fallbackRows = await orderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + wave_no: targetWaveNo, + }, + attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status', 'claim_operator_id' ], + raw: true, + }); + waveOrders = Array.isArray(fallbackRows) ? fallbackRows : []; + } + const waveOrderIds = [ ...new Set(waveOrders + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + if (waveOrderIds.length === 0) { + return this.fail('波次下无可用订单', {}, 400); + } + + const totalOrderCount = waveOrderIds.length; + // 拦截订单跳过领料的口径:仅「未打印」的拦截订单跳过(保持未领料),其未打印/未领料状态不阻隔领料与拣货; + // 已打印(print_status=fin)的拦截订单面单实物已随波次流出并被领取,领料登记不再受拦截影响, + // 否则会出现实物已领走但订单仍未领料(波次已确认打印后又收到拦截的场景)。 + const interceptedWaveOrderIds = new Set(waveOrders + .filter(item => isInterceptedOrderStatus(item && item.intercept_status)) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)); + const interceptClaimSkippedOrderIds = new Set(waveOrders + .filter(item => interceptedWaveOrderIds.has(Number(item && item.id || 0)) + && String(item && item.print_status || '').trim() !== 'fin') + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)); + + const unclaimedOrderIds = [ ...new Set(waveOrders + .filter(item => { + const orderIdItem = Number(item && item.id || 0); + if (interceptClaimSkippedOrderIds.has(orderIdItem)) { + return false; + } + if (String(item && item.claim_status || '') !== 'fin') { + return true; + } + // 已领料但领料人不是本人:重新领料并覆盖领料人 + return Number(item && item.claim_operator_id || 0) !== operatorId; + }) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + const ownClaimedOrderIds = [ ...new Set(waveOrders + .filter(item => String(item && item.claim_status || '') === 'fin' + && Number(item && item.claim_operator_id || 0) === operatorId + && !interceptClaimSkippedOrderIds.has(Number(item && item.id || 0))) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + const baseResponse = { + wave_id: targetWaveId, + wave_no: targetWaveNo, + wave_type: targetWaveType, + wave_source: targetWaveSource, + pick_mode: pickMode, + matched_order_id: matchedOrderId, + waybill_no: waybillNo, + total_order_count: totalOrderCount, + intercepted_order_count: interceptedWaveOrderIds.size, + intercept_skipped_order_count: interceptClaimSkippedOrderIds.size, + }; + + if (unclaimedOrderIds.length === 0) { + // 波次已领料(本人):若波次表缺少领料时间(历史领单或旧版拦截跳过导致), + // 补写一次,避免 order.wave.confirmPrintUnclaimedWaveCount 长期把该波次计为未领料 + const backfilled = ownClaimedOrderIds.length > 0 + ? await this.backfillWaveClaimTime({ + waveId: targetWaveId, + warehouseId: normalizedWarehouseId, + operatorName, + currentClaimTime: targetWaveClaimTime, + }) + : false; + if (backfilled) { + await this.bumpConfirmPrintUnclaimedWaveVersionSafe(normalizedWarehouseId); + } + + return this.success('ok', { + data: { + ...baseResponse, + claimed_order_count: ownClaimedOrderIds.length, + claimed_intercepted_order_count: ownClaimedOrderIds + .filter(orderId => interceptedWaveOrderIds.has(orderId)).length, + status: 'already_claimed', + tip: '该波次订单已领料(本人),无需重复领取', + }, + code: 200, + }); + } + + // 波次打印校验:存在未打印订单(print_status != fin)时禁止整波领料 + // (拦截订单的未打印状态不阻隔领料) + const unprintedOrderIds = [ ...new Set(waveOrders + .filter(item => String(item && item.print_status || '') !== 'fin' + && !interceptedWaveOrderIds.has(Number(item && item.id || 0))) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + if (unprintedOrderIds.length > 0) { + return this.fail('波次未打印,禁止领料', { + ...baseResponse, + unprinted_order_count: unprintedOrderIds.length, + }, 400); + } + + // --- 6. 事务更新领单状态并写订单日志 --- + const operationLogService = ctx.service + && ctx.service.systems + && ctx.service.systems.operationLog; + const transaction = await ctx.model.transaction(); + try { + await orderModel.update( + { + claim_status: 'fin', + claim_operator_id: operatorId > 0 ? operatorId : null, + claim_operator: operatorName, + }, + { + where: { + id: { [Op.in]: unclaimedOrderIds }, + warehouse_id: normalizedWarehouseId, + }, + transaction, + } + ); + + const claimedRows = await orderModel.findAll({ + where: { + id: { [Op.in]: unclaimedOrderIds }, + warehouse_id: normalizedWarehouseId, + claim_status: 'fin', + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + const claimedOrderIds = [ ...new Set((Array.isArray(claimedRows) ? claimedRows : []) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (claimedOrderIds.length > 0) { + // 回写波次表领料人、领料时间 + await ctx.model.WaveBatch.update( + { + claim_operator: operatorName, + claim_time: new Date(), + }, + { + where: { + wave_id: targetWaveId, + warehouse_id: normalizedWarehouseId, + }, + transaction, + } + ); + + if (operationLogService + && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(claimedOrderIds.map(orderId => ({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_WAVE_CLAIM', + operator: { + id: operatorId ? String(operatorId) : null, + name: operatorName || 'system', + }, + operationAction: 'UPDATE', + extras: { + message: `整波领单完成(波次 ${targetWaveNo})`, + warehouseId: normalizedWarehouseId, + externalLogType: 'API', + }, + })), { transaction }); + } + } + + await transaction.commit(); + + // 驱动确认打印未领单波次统计长轮询:领单会减少未领单波次数量,递增版本号 + await this.bumpConfirmPrintUnclaimedWaveVersionSafe(normalizedWarehouseId); + + return this.success('ok', { + data: { + ...baseResponse, + claimed_order_count: claimedOrderIds.length, + claimed_intercepted_order_count: claimedOrderIds + .filter(orderId => interceptedWaveOrderIds.has(orderId)).length, + status: 'claimed', + tip: `整波领单完成,本次领取 ${claimedOrderIds.length} 个订单`, + }, + code: 200, + }); + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[PickService.waveClaimScan] 整波领单失败: %s', error && error.message ? error.message : error); + return this.fail('领单失败', {}, 500); + } + } + +} + +module.exports = PickService; diff --git a/app/service/systemMethods/pickCart.js b/app/service/systemMethods/pickCart.js new file mode 100644 index 0000000..4de4881 --- /dev/null +++ b/app/service/systemMethods/pickCart.js @@ -0,0 +1,352 @@ +'use strict'; + +const MainService = require('../main'); + +class PickCartService extends MainService { + /** + * 初始化 pickCart 模块鉴权配置。 + * + * @param {Egg.Context} ctx 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'scan,bindTaskCart,create,update,delete,batchDelete,detail,list,codeDuplicateCheck'; + const _noNeedLog = ''; + const _noNeedAuth = 'scan,bindTaskCart,create,update,delete,batchDelete,detail,list,codeDuplicateCheck'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 按拣货车编码扫码查询。 + * + * @param {Object} data 请求参数。 + * @param {string} data.cart_code 拣货车编码。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async scan(data = {}) { + const { service, ctx } = this; + const cartCode = String(data && (data.cart_code || data.cartCode) || '').trim(); + + if (!cartCode) { + return this.fail('cart_code 必填', {}, 400); + } + + try { + const result = await service.systems.pickCart.scan({ cartCode }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '查询失败', errorData, code); + } + + ctx.logger.error('[PickCartService.scan] 扫码查询拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } + + /** + * 绑定拣货任务与拣货车。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.task_id 拣货任务ID。 + * @param {number|string} [data.cart_id] 拣货车ID。 + * @param {string} [data.cart_code] 拣货车编码。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async bindTaskCart(data = {}) { + const { service, ctx } = this; + const taskId = Number(data && (data.task_id || data.taskId) || 0); + const cartId = Number(data && (data.cart_id || data.cartId) || 0); + const cartCode = String(data && (data.cart_code || data.cartCode) || '').trim(); + + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必填且必须为正整数', {}, 400); + } + if ((!Number.isInteger(cartId) || cartId <= 0) && !cartCode) { + return this.fail('cart_id 或 cart_code 至少传一个', {}, 400); + } + + try { + const result = await service.systems.pickCart.bindTaskCart({ + taskId, + cartId, + cartCode, + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '绑定失败', errorData, code); + } + + ctx.logger.error('[PickCartService.bindTaskCart] 绑定拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('绑定失败', {}, 500); + } + } + + /** + * 创建拣货车。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async create(data = {}) { + const { service, ctx } = this; + + try { + const result = await service.systems.pickCart.create({ + cartCode: String(data && (data.cart_code || data.cartCode) || '').trim(), + cartName: String(data && (data.cart_name || data.cartName) || '').trim(), + status: data && data.status !== undefined ? Number(data.status) : 1, + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '创建失败', errorData, code); + } + + ctx.logger.error('[PickCartService.create] 创建拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('创建失败', {}, 500); + } + } + + /** + * 更新拣货车。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async update(data = {}) { + const { service, ctx } = this; + const cartId = Number(data && (data.cart_id || data.cartId) || 0); + + if (!Number.isInteger(cartId) || cartId <= 0) { + return this.fail('cart_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pickCart.update({ + cartId, + cartCode: data && (data.cart_code !== undefined || data.cartCode !== undefined) + ? String(data.cart_code || data.cartCode || '').trim() + : undefined, + cartName: data && (data.cart_name !== undefined || data.cartName !== undefined) + ? String(data.cart_name || data.cartName || '').trim() + : undefined, + status: data && data.status !== undefined ? Number(data.status) : undefined, + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '更新失败', errorData, code); + } + + ctx.logger.error('[PickCartService.update] 更新拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('更新失败', {}, 500); + } + } + + /** + * 删除拣货车。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async delete(data = {}) { + const { service, ctx } = this; + const cartId = Number(data && (data.cart_id || data.cartId) || 0); + + if (!Number.isInteger(cartId) || cartId <= 0) { + return this.fail('cart_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pickCart.delete({ cartId }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '删除失败', errorData, code); + } + + ctx.logger.error('[PickCartService.delete] 删除拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('删除失败', {}, 500); + } + } + + /** + * 批量删除拣货车。已绑定任务的将被跳过。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.ids 拣货车ID列表。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async batchDelete(data = {}) { + const { service, ctx } = this; + const ids = Array.isArray(data && data.ids) ? data.ids : []; + + if (ids.length === 0) { + return this.fail('ids 必填且必须为非空数组', {}, 400); + } + + try { + const result = await service.systems.pickCart.batchDelete({ ids }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '批量删除失败', errorData, code); + } + + ctx.logger.error('[PickCartService.batchDelete] 批量删除拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('批量删除失败', {}, 500); + } + } + + /** + * 查询拣货车详情。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async detail(data = {}) { + const { service, ctx } = this; + const cartId = Number(data && (data.cart_id || data.cartId) || 0); + + if (!Number.isInteger(cartId) || cartId <= 0) { + return this.fail('cart_id 必填且必须为正整数', {}, 400); + } + + try { + const result = await service.systems.pickCart.detail({ cartId }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '查询失败', errorData, code); + } + + ctx.logger.error('[PickCartService.detail] 查询拣货车详情失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } + + /** + * 分页查询拣货车列表。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async list(data = {}) { + const { service, ctx } = this; + + try { + const result = await service.systems.pickCart.list({ + pagination: data && data.pagination && typeof data.pagination === 'object' ? data.pagination : {}, + where: data && data.where && typeof data.where === 'object' ? data.where : {}, + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '查询失败', errorData, code); + } + + ctx.logger.error('[PickCartService.list] 查询拣货车列表失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } + + /** + * 拣货车编码查重。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async codeDuplicateCheck(data = {}) { + const { service, ctx } = this; + const cartCode = String(data && (data.cart_code || data.cartCode) || '').trim(); + const excludeCartId = Number(data && (data.exclude_cart_id || data.excludeCartId) || 0); + + if (!cartCode) { + return this.fail('cart_code 必填', {}, 400); + } + + try { + const result = await service.systems.pickCart.codeDuplicateCheck({ + cartCode, + excludeCartId, + warehouseId: this.getWarehouseId(), + }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '校验失败', errorData, code); + } + + ctx.logger.error('[PickCartService.codeDuplicateCheck] 拣货车编码查重失败: %s', error && error.message ? error.message : error); + return this.fail('校验失败', {}, 500); + } + } +} + +module.exports = PickCartService; diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index f7d7f3e..1edd667 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -1,67 +1,807 @@ 'use strict'; -const { up } = require('../../../database/migrations/20251109160640-init-wms_account'); +const { randomBytes } = require('node:crypto'); // 打印相关 Service const MainService = require('../main'); +const { + ExpressPrintPayloadBuilder, + RequestScopedPrintIdGenerator, +} = require('../../lib/express_print_payload_builder'); +const { + INTERCEPT_STATUS_NONE, + isInterceptedOrderStatus, +} = require('../../lib/intercept_guard'); /** * 打印 Service * 参考 indexService 初始化方式,后续可扩展具体业务函数 */ class PrintService extends MainService { - constructor(ctx) { - super(ctx); - // 初始化免登录、免权限、免日志、免认证等配置 - const _noNeedLogin = ''; - const _noNeedRight = '*'; - const _noNeedLog = ''; - const _noNeedAuth = '*'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - this.defaultComponents = [ - { name: '抖音', port: '13888' }, - { name: '拼多多', port: '5000' }, - { name: '快手', port: '16888/ks/printer' }, - { name: '京东', port: '9113' }, - { name: '菜鸟', port: '13528' }, - { name: '视频号', port: '12705' }, - { name: '小红书', port: '10818' }, - { name: 'LODOP', port: '8000' } - ]; + constructor(ctx) { + super(ctx); + // 初始化免登录、免权限、免日志、免认证等配置 + const _noNeedLogin = ''; + const _noNeedRight = '*'; + const _noNeedLog = 'notifyLock,notify_lock'; + const _noNeedAuth = '*'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + this.defaultComponents = [ + { name: '抖音', port: '13888' }, + { name: '拼多多', port: '5000' }, + { name: '快手', port: '16888/ks/printer' }, + { name: '京东', port: '9113' }, + { name: '菜鸟', port: '13528' }, + { name: '视频号', port: '12705' }, + { name: '小红书', port: '10818' }, + { name: 'LODOP', port: '8000' }, + ]; + } + + /** + * 构建 print.send 入参摘要,避免打印超大对象。 + * @param {Object} payload 原始入参。 + * @return {Object} 安全摘要信息。 + */ + buildPrintSendInputSummary(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {}; + const waveGroups = Array.isArray(data.waveGroups) ? data.waveGroups : []; + const firstWavePlatforms = Array.isArray(waveGroups[0] && waveGroups[0].platforms) ? waveGroups[0].platforms : []; + const firstPlatformOrders = Array.isArray(firstWavePlatforms[0] && firstWavePlatforms[0].orders) + ? firstWavePlatforms[0].orders + : []; + return { + type: normalizedPayload.type || '', + printer: normalizedPayload.printer || '', + computerId: normalizedPayload.computerId || '', + printStationId: normalizedPayload.printStationId || '', + hasTemplate: Boolean(normalizedPayload.template), + requestCode: normalizedPayload.requestCode ? String(normalizedPayload.requestCode) : '', + waveGroupsCount: waveGroups.length, + firstWavePlatformsCount: firstWavePlatforms.length, + firstGroupOrdersCount: firstPlatformOrders.length, + dataKeys: Object.keys(data).slice(0, 20), + }; + } + + /** + * 统计快递 payload 摘要,避免输出完整文档对象。 + * @param {Object} payload 快递发送 payload。 + * @return {{documentCount:number}} 文档数量摘要。 + */ + summarizeExpressPayload(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + let documentCount = 0; + if (normalizedPayload.task && Array.isArray(normalizedPayload.task.documents)) { + documentCount = normalizedPayload.task.documents.length; + } else if (Array.isArray(normalizedPayload.documents)) { + documentCount = normalizedPayload.documents.length; + } else if (Array.isArray(normalizedPayload.document_list)) { + documentCount = normalizedPayload.document_list.length; + } else if (Array.isArray(normalizedPayload.data)) { + documentCount = normalizedPayload.data.length; + } else if (normalizedPayload.document || normalizedPayload.print_data) { + documentCount = 1; } - async send(_data) { - const { ctx } = this; - const warehouseId = ctx.user.store_id; - const { printer, type, template, data, computerId, timestamp, count } = _data; - console.log('send to computer', warehouseId, printer, type, template, data, computerId, timestamp, count); - //生成打印编号并记录到数据库 - const printRecord = await ctx.model.PrintRecord.create({ - warehouse_id: warehouseId, - computer_id: computerId, - printer, - type, - data: { template, data }, - status: 'pending' - }); - //处理后的数据 - let processedData = {}; - switch (type) { - case "customize": - const { page_width, page_height, template_content } = template; - let htm = ``; - for (const item of template_content) { - let content = item.content; + return { documentCount }; + } - for(const key in data) { - console.log("正在匹配字段:", key, "与", item.field_code); - if(item.field_code == key) { - content = data[key]; - } - } - console.log("转后的内容:", content); - switch (item.type) { - case "text": - htm += `
    `; + for (const item of template_content) { + let content = item.content; + + for (const key in data) { + if (String(item.field_code) === key) { + content = data[key]; + } + } + switch (item.type) { + case 'text': + htm += `
    ${content}
    `; - break; - case "image": - htm += ``; - break; - case "barcode": - htm += `
    `; - break; - case "qrcode": - let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`; - //转换成urlencode - toUrl = encodeURIComponent(toUrl); - let url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`; + ">
    `; + break; + case 'qrcode': { + let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`; + // 转换成urlencode + toUrl = encodeURIComponent(toUrl); + const url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`; - - htm += `
    `; - break; - case "line": - htm += `
    `; - break; - case "rectangle": - htm += `
    `; - break; - case "table": - let tableHtml = ``; - for (let i = 0; i < item.rows; i++) { - tableHtml += ``; - for (let j = 0; j < item.columns; j++) { - let content = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; - tableHtml += ``; - } tableHtml += ``; - } tableHtml += `
    ${content}
    `; - htm += tableHtml; - break; + break; + case 'table': { + let tableHtml = ``; + for (let i = 0; i < item.rows; i++) { + tableHtml += ''; + for (let j = 0; j < item.columns; j++) { + let cellContent = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; + // 解析单元格字段码为实际数据,与 text 类型保持一致的解析逻辑 + for (const key in data) { + if (String(cellContent) === key) { + cellContent = data[key]; } - } - htm += ``; - processedData = { - pageWidth: page_width, - pageHeight: page_height, - htm: htm, - lodopkey:["","13528A153BAEE3A0254B9507DCDE2839","EDE92F75B6A3D917F65910","D60BC84D7CF2DE18156A6F88987304CB6D8"] - } - break; - case "express": - break; + } + tableHtml += ``; + } tableHtml += ''; + } tableHtml += '
    ${cellContent}
    '; + htm += tableHtml; + break; + } default: - return this.fail('不支持的打印类型', 1001); + break; + } + } + htm += ''; + processedData = { + pageWidth: page_width, + pageHeight: page_height, + htm, + lodopkey: [ '', '13528A153BAEE3A0254B9507DCDE2839', 'EDE92F75B6A3D917F65910', 'D60BC84D7CF2DE18156A6F88987304CB6D8' ], + }; + this.ctx.logger.info('[print.send] customize payload 组装完成', { + warehouseId, + type, + pageWidth: page_width, + pageHeight: page_height, + templateItemCount: template_content.length, + }); + break; + } + case 'express': { + const expressPrintStation = await this.loadExpressPrintStation({ printStationId, warehouseId }); + if (!expressPrintStation.success) { + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: expressPrintStation.error, + }); + return this.fail(expressPrintStation.error, { code: 400 }); + } + const expressRecordFields = this.buildExpressPrintRecordFields(expressPrintStation.data); + if (!expressRecordFields.success) { + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: expressRecordFields.error, + }); + return this.fail(expressRecordFields.error, { code: 400 }); } - const printData = { - printer, + const platformCodes = this.collectExpressPlatformCodes(data.waveGroups); + const platformComponentsResult = await this.loadExpressPlatformComponents({ platformCodes }); + if (!platformComponentsResult.success) { + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, type, - template, - data: processedData, - timestamp, - count, - printId: printRecord.id - }; - const res = await this.service.systems.print.index.sendToComputer({warehouse:warehouseId, computerId: computerId, data:printData}); - console.log('sendToComputer response', res); - //发送成功后更新打印记录状态 - if (res.status=="success") { - await printRecord.update({ status: 'sent' }); - return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); - } else { - await printRecord.update({ status: 'failed', error_message: res.error }); - return this.fail(res.error, { code: 504, printId: printRecord.id }); + reason: platformComponentsResult.error, + }); + return this.fail(platformComponentsResult.error, { code: 400 }); } + const componentOnlineResult = await this.validateExpressComponentsOnline({ + computerId: expressRecordFields.data.computer_id, + platformComponents: platformComponentsResult.data, + }); + if (!componentOnlineResult.success) { + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: componentOnlineResult.error, + }); + return this.fail(componentOnlineResult.error, { code: 400 }); + } + const payloadBuilder = new ExpressPrintPayloadBuilder({ baseDir: this.app.baseDir }); + const idGenerator = new RequestScopedPrintIdGenerator(requestCode); + const expressSendResult = await this.sendExpressWaveGroups({ + warehouseId, + waveGroups: data.waveGroups, + requestCode, + printStation: expressPrintStation.data, + payloadBuilder, + idGenerator, + expressRecordFields: expressRecordFields.data, + platformComponents: platformComponentsResult.data, + type, + template, + data, + }); + if (!expressSendResult.success) { + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + printId: expressSendResult.printId || 0, + reason: expressSendResult.error, + }); + return this.fail(expressSendResult.error, { + code: 504, + printId: expressSendResult.printId || 0, + printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [], + }); + } + // 异步检查是否需要解绑拣货车(不阻塞返回) + const expressWaveIds = this.extractUniqueWaveIds(data.waveGroups); + for (const wid of expressWaveIds) { + this.tryUnbindCartAfterPrintComplete(wid).catch(err => { + this.ctx.logger.error('[print.send] 异步解绑车标异常', { + waveId: wid, + warehouseId, + error: err && err.message ? err.message : `${err}`, + }); + }); + } + + this.ctx.logger.info('[print.send] 最终返回 success', { + warehouseId, + type, + printId: expressSendResult.printId || 0, + printIdsCount: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds.length : 0, + }); + return this.success('发送打印任务成功', { + code: 200, + printId: expressSendResult.printId || 0, + printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [], + }); + } + default: + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: '不支持的打印类型', + }); + return this.fail('不支持的打印类型', 1001); } - async getPrintResult(data) { - const { ctx } = this; - const warehouseId = ctx.user.store_id; - const { printId } = data; - if (!printId) return this.fail('参数错误', 1001); - const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true }); - if (!record) return this.fail('打印记录不存在', 1002); - return this.success('success', { ...record, code: 0 }); + + const printData = { + printer, + type, + template, + data: processedData, + timestamp, + count, + printId: printRecord.id, + ...(customizeOrderIds.length > 0 ? { order_ids: customizeOrderIds } : {}), + }; + const sendStartAt = Date.now(); + const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData }); + const sendDurationMs = Date.now() - sendStartAt; + if (res.status === 'success') { + this.ctx.logger.info('[print.send] sendToComputer 调用成功', { + warehouseId, + type, + printId: printRecord.id, + computerId, + durationMs: sendDurationMs, + }); + } else { + this.ctx.logger.error('[print.send] sendToComputer 调用失败', { + warehouseId, + type, + printId: printRecord.id, + computerId, + durationMs: sendDurationMs, + error: res && res.error ? res.error : '打印服务返回失败', + }); } - async getPrintRecordItem(data) { - const { ctx } = this; - const warehouseId = ctx.user.store_id; - const { id } = data; - if (!id) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true }); - if (!item) return this.fail('打印记录不存在', 1002); - return this.success('success', { ...item, code: 0 }); + // 发送成功后更新打印记录状态 + if (res.status === 'success') { + await printRecord.update(this.buildSentPrintRecordUpdatePayload()); + // 同步更新关联配送订单的 print_status 为 'fin' + if (customizeOrderIds.length > 0) { + const updateResult = await this.updateOrderPrintStatusByCallback({ + warehouseId, + orderIds: customizeOrderIds, + result: 'success', + }); + if (!updateResult.success) { + this.ctx.logger.error('[print.send] 同步订单 print_status 失败', { + warehouseId, + type, + orderIdsCount: customizeOrderIds.length, + reason: updateResult.errorMessage, + }); + } + } + this.ctx.logger.info('[print.send] 最终返回 success', { + warehouseId, + type, + printId: printRecord.id, + }); + return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); } - /** + await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ + errorMessage: res.error || '打印服务返回失败', + })); + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + printId: printRecord.id, + reason: res.error || '打印服务返回失败', + }); + return this.fail(res.error, { code: 504, printId: printRecord.id }); + } + + /** + * 校验快递打印请求的必要参数。 + * @param {Object} payload 校验参数。 + * @param {Object} payload.data 请求 data。 + * @param {number|string} payload.printStationId 打印台 ID。 + * @param {string} payload.requestCode 请求参数码。 + * @return {Object|null} 失败时返回 fail 响应,成功返回 null。 + */ + validateExpressSendInput(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const waveGroups = Array.isArray(requestData.data && requestData.data.waveGroups) + ? requestData.data.waveGroups + : []; + if (waveGroups.length === 0) { + this.ctx.logger.warn('[print.send] express 参数校验失败-data.waveGroups 为空', { + printStationId: requestData.printStationId || '', + requestCode: requestData.requestCode ? String(requestData.requestCode) : '', + }); + return this.fail('type=express 时 data.waveGroups 必须是非空数组', { code: 400 }); + } + + const normalizedPrintStationId = String(requestData.printStationId || '').trim(); + if (!normalizedPrintStationId) { + this.ctx.logger.warn('[print.send] express 参数校验失败-printStationId 为空', { + requestCode: requestData.requestCode ? String(requestData.requestCode) : '', + waveGroupsCount: waveGroups.length, + }); + return this.fail('type=express 时 printStationId 参数不能为空', { code: 400 }); + } + + const normalizedRequestCode = String(requestData.requestCode || '').trim(); + if (!normalizedRequestCode) { + this.ctx.logger.warn('[print.send] express 参数校验失败-requestCode 为空', { + printStationId: normalizedPrintStationId, + waveGroupsCount: waveGroups.length, + }); + return this.fail('type=express 时 requestCode 参数不能为空', { code: 400 }); + } + + return null; + } + + /** + * 查询并校验快递打印台。 + * @param {Object} payload 查询参数。 + * @param {number|string} payload.printStationId 打印台 ID。 + * @param {number|string} payload.warehouseId 仓库 ID。 + * @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询结果。 + */ + async loadExpressPrintStation(payload = {}) { + const { ctx } = this; + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const printStation = await ctx.model.PrintStations.findOne({ + where: { + id: normalizedPayload.printStationId, + warehouse_id: normalizedPayload.warehouseId, + deleted: 0, + }, + raw: true, + }); + if (!printStation) { + this.ctx.logger.warn('[print.send] 打印台查询失败', { + printStationId: normalizedPayload.printStationId, + warehouseId: normalizedPayload.warehouseId, + }); + return { + success: false, + error: '打印台不存在', + }; + } + + this.ctx.logger.info('[print.send] 打印台查询成功', { + printStationId: printStation.id, + warehouseId: normalizedPayload.warehouseId, + computerId: printStation.computer_id || '', + defaultPrinterName: printStation.default_printer_name || '', + }); + + return { + success: true, + data: printStation, + }; + } + + /** + * 组装快递打印记录的必填字段,避免写入 null。 + * @param {Object} printStation 打印台配置。 + * @return {{success:boolean,data?:{computer_id:string,printer:string},error?:string}} 组装结果。 + */ + buildExpressPrintRecordFields(printStation = {}) { + const normalizedStation = printStation && typeof printStation === 'object' ? printStation : {}; + const computerId = String(normalizedStation.computer_id || '').trim(); + if (!computerId) { + return { + success: false, + error: '打印台未配置打印电脑', + }; + } + + const defaultPrinterName = String(normalizedStation.default_printer_name || '').trim(); + return { + success: true, + data: { + computer_id: computerId, + printer: defaultPrinterName || 'EXPRESS_DYNAMIC_PRINTER', + }, + }; + } + + /** + * 收集 express 请求中涉及的平台编码列表。 + * @param {Array} waveGroups 波次分组数据。 + * @return {Array} 去重后的平台编码列表。 + */ + collectExpressPlatformCodes(waveGroups = []) { + const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : []; + const platformCodeSet = new Set(); + for (const waveGroup of normalizedWaveGroups) { + const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; + for (const platformGroup of platforms) { + const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : []; + if (orders.length === 0) { + continue; + } + const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim(); + if (platformCode) { + platformCodeSet.add(platformCode); + } + } + } + return Array.from(platformCodeSet); + } + + /** + * 从 waveGroups 中提取去重后的 wave_id 列表。 + * @param {Array} waveGroups 波次分组数据。 + * @return {Array} 去重后的波次ID列表。 + */ + extractUniqueWaveIds(waveGroups = []) { + const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : []; + const waveIdSet = new Set(); + for (const waveGroup of normalizedWaveGroups) { + const waveId = Number(waveGroup && waveGroup.wave_id || 0); + if (Number.isInteger(waveId) && waveId > 0) { + waveIdSet.add(waveId); + } + } + return Array.from(waveIdSet); + } + + /** + * 从波次平台数据中提取订单ID列表。 + * + * 优先使用平台分组透出的 order_ids;若缺失则回退读取 orders[*].order_id。 + * + * @param {Array} waveGroups 波次平台分组。 + * @return {Array} 去重后的订单ID列表。 + */ + collectOrderIdsFromWaveGroups(waveGroups = []) { + const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : []; + const orderIdSet = new Set(); + + for (const waveGroup of normalizedWaveGroups) { + const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; + for (const platformGroup of platforms) { + const platformOrderIds = Array.isArray(platformGroup && platformGroup.order_ids) + ? platformGroup.order_ids + : []; + for (const orderId of platformOrderIds) { + const normalizedOrderId = Number(orderId || 0); + if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) { + orderIdSet.add(normalizedOrderId); + } + } + + const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : []; + for (const order of orders) { + const normalizedOrderId = Number(order && order.order_id || 0); + if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) { + orderIdSet.add(normalizedOrderId); + } + } + } + } + + return Array.from(orderIdSet); + } + + /** + * 从通知锁定入参中提取订单ID。 + * + * 优先使用 order_ids/orderIds;为空时回退使用 waveGroups 提取。 + * + * @param {Object} payload 通知锁定入参。 + * @param {Array} [payload.order_ids] 订单ID列表(推荐)。 + * @param {Array} [payload.orderIds] 兼容驼峰订单ID列表。 + * @param {Array} [payload.waveGroups] 波次分组。 + * @param {Object} [payload.data] 兼容 print.send 结构的数据体。 + * @return {{orderIds:Array,orderIdsCount:number,waveGroupsCount:number,source:string}} 提取结果。 + */ + extractOrderIdsFromNotifyLockPayload(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {}; + const directOrderIds = this.normalizeOrderIds(Array.isArray(normalizedPayload.order_ids) + ? normalizedPayload.order_ids + : (Array.isArray(normalizedPayload.orderIds) ? normalizedPayload.orderIds : [])); + const waveGroups = Array.isArray(normalizedPayload.waveGroups) + ? normalizedPayload.waveGroups + : (Array.isArray(data.waveGroups) ? data.waveGroups : []); + const waveGroupOrderIds = this.collectOrderIdsFromWaveGroups(waveGroups); + const hasDirectOrderIds = directOrderIds.length > 0; + const orderIds = hasDirectOrderIds ? directOrderIds : waveGroupOrderIds; + + return { + orderIds, + orderIdsCount: orderIds.length, + waveGroupsCount: waveGroups.length, + source: hasDirectOrderIds ? 'order_ids' : 'waveGroups', + }; + } + + /** + * 构建 notifyLock 的轻量日志摘要,避免落库超大对象。 + * + * @param {Object} payload notifyLock 原始入参。 + * @param {Object} extracted 已提取摘要信息。 + * @param {Array} [extracted.orderIds] 订单ID列表。 + * @param {number} [extracted.orderIdsCount] 订单数量。 + * @param {number} [extracted.waveGroupsCount] 波次数量。 + * @param {string} [extracted.source] 订单来源标识。 + * @return {Object} 轻量可落库摘要。 + */ + buildNotifyLockInputSummary(payload = {}, extracted = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {}; + const orderIds = Array.isArray(extracted.orderIds) ? extracted.orderIds : []; + const orderIdsCount = Number(extracted.orderIdsCount || orderIds.length || 0); + const waveGroupsCount = Number(extracted.waveGroupsCount || 0); + const source = String(extracted.source || '').trim(); + const requestCode = normalizedPayload.requestCode + ? String(normalizedPayload.requestCode).slice(0, 128) + : (normalizedPayload.request_code ? String(normalizedPayload.request_code).slice(0, 128) : ''); + + return { + action: 'notifyLock', + source, + order_ids_count: orderIdsCount, + order_ids_sample: orderIds.slice(0, 100), + wave_groups_count: waveGroupsCount, + request_code: requestCode, + payload_keys: Object.keys(normalizedPayload).slice(0, 20), + data_keys: Object.keys(data).slice(0, 20), + has_data: Object.keys(data).length > 0, + }; + } + + /** + * 获取打印相关订单操作日志的操作人信息。 + * + * 取值优先级:ctx.state.user -> ctx.user,字段优先尝试 employees/operator/id 与 name。 + * + * @return {{id:string|null,name:string}} 操作人信息。 + */ + getPrintOrderOperationOperator() { + const stateUser = this.ctx && this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' + ? this.ctx.state.user + : null; + const ctxUser = this.ctx && this.ctx.user && typeof this.ctx.user === 'object' + ? this.ctx.user + : null; + const user = stateUser || ctxUser || {}; + + const rawOperatorId = user.employees_id ?? user.operator_id ?? user.id; + const rawOperatorName = user.employees_name + ?? user.operator_name + ?? user.real_name + ?? user.name; + + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : (String(rawOperatorId).trim() || null); + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : (String(rawOperatorName).trim() || 'system'); + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 按订单ID批量写入打印相关订单操作日志。 + * + * 日志写入失败不会中断主流程,仅记录 warn/error。 + * + * @param {Object} payload 写入参数。 + * @param {Array} payload.orderIds 订单ID列表。 + * @param {string} payload.source 来源标识(如 print.send/print.notifyLock)。 + * @param {string} payload.message 日志消息。 + * @param {string} [payload.operationCode='ORDER_PRINT'] 操作编码。 + * @return {Promise} 无返回值。 + */ + async writePrintOrderOperationLogsByOrderIds(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds); + if (orderIds.length === 0) { + return; + } + + const source = String(normalizedPayload.source || '').trim() || 'print.send'; + const message = String(normalizedPayload.message || '').trim() || `${source} 执行完成`; + const operationCode = String(normalizedPayload.operationCode || '').trim() || 'ORDER_PRINT'; + const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + this.ctx.logger.warn('[print.operationLog] operationLog 批量写入服务不可用,跳过日志写入', { + source, + orderIdsCount: orderIds.length, + }); + return; + } + + const operator = this.getPrintOrderOperationOperator(); + const payloads = orderIds.map(orderId => ({ + businessType: 'order', + businessId: orderId, + operationCode, + operator, + extras: { + warehouseId, + message, + }, + })); + + try { + const results = await operationLogService.createOperationLogs(payloads); + if (!Array.isArray(results)) { + return; + } + for (let index = 0; index < payloads.length; index++) { + if (results[index]) { + continue; + } + this.ctx.logger.warn('[print.operationLog] 订单操作日志写入失败,不影响主流程', { + source, + orderId: payloads[index].businessId, + operationCode, + }); + } + } catch (error) { + this.ctx.logger.error('[print.operationLog] 批量写入订单操作日志异常,不影响主流程', { + source, + orderIdsCount: orderIds.length, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + /** + * 通知锁定接口:仅执行订单锁定流程,不发送打印任务。 + * + * @param {Object} data 入参。 + * @param {Array} [data.order_ids] 订单ID列表(推荐)。 + * @param {Array} [data.orderIds] 兼容驼峰订单ID列表。 + * @param {Array} [data.waveGroups] 波次分组(兼容 print.send 轻量版本)。 + * @param {Object} [data.data] 兼容 print.send 的 data 包装。 + * @return {Promise} 统一 success/fail 返回结构。 + */ + async notifyLock(data = {}) { + const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); + const { + orderIds, + orderIdsCount, + waveGroupsCount, + source, + } = this.extractOrderIdsFromNotifyLockPayload(data); + + const notifyLockInputSummary = this.buildNotifyLockInputSummary(data, { + orderIds, + orderIdsCount, + waveGroupsCount, + source, + }); + + let printRecord = null; + try { + printRecord = await this.ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ + warehouse_id: warehouseId, + computer_id: 0, + printer: 'notifyLock', + type: 'notify_lock', + data: notifyLockInputSummary, + request_code: notifyLockInputSummary.request_code || null, + })); + } catch (error) { + this.ctx.logger.error('[print.notifyLock] PrintRecord 创建失败', { + warehouseId, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + } + + if (orderIdsCount === 0) { + if (printRecord && typeof printRecord.update === 'function') { + try { + await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ + errorMessage: '未提取到有效订单ID,请传入 order_ids 或 waveGroups', + failCode: 'NOTIFY_LOCK_INVALID_INPUT', + })); + } catch (error) { + this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', { + warehouseId, + printId: printRecord.id, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + } + } + return this.fail('未提取到有效订单ID,请传入 order_ids 或 waveGroups', { + code: 400, + locked_count: 0, + order_ids_count: 0, + wave_groups_count: waveGroupsCount, + }); + } + + const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({ + warehouseId, + orderIds, + }); + + if (!lockResult.success) { + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds, + source: 'print.notifyLock', + message: `通知锁定执行失败,原因=${lockResult.errorMessage || '未知错误'}`, + }); + if (printRecord && typeof printRecord.update === 'function') { + try { + await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ + errorMessage: lockResult.errorMessage || '未知错误', + failCode: 'NOTIFY_LOCK_FAILED', + })); + } catch (error) { + this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', { + warehouseId, + printId: printRecord.id, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + } + } + return this.fail(`订单锁定失败:${lockResult.errorMessage || '未知错误'}`, { + code: 500, + locked_count: 0, + order_ids_count: orderIdsCount, + order_ids: orderIds, + }); + } + + if (printRecord && typeof printRecord.update === 'function') { + try { + await printRecord.update(this.buildSentPrintRecordUpdatePayload()); + } catch (error) { + this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', { + warehouseId, + printId: printRecord.id, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + } + } + + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds, + source: 'print.notifyLock', + message: `通知锁定执行成功,locked_count=${lockResult.lockedCount}`, + }); + + return this.success('ok', { + code: 0, + locked_count: lockResult.lockedCount, + order_ids_count: orderIdsCount, + order_ids: orderIds, + source, + }); + } + + /** + * notifyLock 的 snake_case 兼容别名。 + * + * @param {Object} data 入参。 + * @return {Promise} 与 notifyLock 一致的返回结构。 + */ + async notify_lock(data = {}) { + return this.notifyLock(data); + } + + /** + * 当 batchOrderIds 为空时,尝试通过 wave_id 从数据库反查订单 ID 列表作为兜底。 + * + * 适用于前端未回传 order_ids 的场景(如团购打印),确保打印成功后仍能标记订单为已打印。 + * + * @param {Object} payload 查询参数。 + * @param {number|string} payload.warehouseId 仓库ID。 + * @param {number|null} payload.waveId 波次ID。 + * @return {Promise>} 订单ID列表;查询失败或参数无效时返回空数组。 + */ + async resolveBatchOrderIdsByWaveFallback(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const warehouseId = Number(normalizedPayload.warehouseId || 0); + const waveId = Number(normalizedPayload.waveId || 0); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(waveId) || waveId <= 0) { + return []; + } + + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + this.ctx.logger.warn('[print.markWavePrintStatus] OrderDeliveryFactory 不可用'); + return []; + } + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + if (!orderDeliveryModel || typeof orderDeliveryModel.findAll !== 'function') { + this.ctx.logger.warn('[print.markWavePrintStatus] orderDeliveryModel 不可用'); + return []; + } + + const rows = await orderDeliveryModel.findAll({ + attributes: [ 'id' ], + where: { + wave_id: waveId, + warehouse_id: warehouseId, + status: { [this.app.Sequelize.Op.ne]: 'cancel' }, + intercept_status: 'none', + }, + raw: true, + }); + + const orderIds = (Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.id)) + .filter(id => Number.isInteger(id) && id > 0); + + if (orderIds.length > 0) { + this.ctx.logger.info('[print.markWavePrintStatus] wave_id=%d 查询到 %d 个订单', waveId, orderIds.length); + } + + return orderIds; + } catch (error) { + this.ctx.logger.warn('[print.markWavePrintStatus] 查询失败 wave_id=%d reason=%s', + waveId, error && error.message ? error.message : `${error}`); + return []; + } + } + + /** + * 标记/取消标记整个波次的订单打印状态。 + * + * 仅操作当前仓库下、状态非取消的订单。 + * 仓库隔离:从 ctx.user.store_id 获取仓库 ID。 + * + * @param {Object} data 入参。 + * @param {number|string} data.wave_id 波次ID(必填)。 + * @param {string} [data.status='printed'] 目标状态:'printed' 标记已打印,'unprinted' 取消已打印标记。 + * @return {Promise} 统一返回结构。 + */ + async markWavePrintStatus(data = {}) { + const { ctx } = this; + const requestData = data && typeof data === 'object' ? data : {}; + const waveId = Number(requestData.wave_id || 0); + const targetStatus = String(requestData.status || 'printed').trim().toLowerCase(); + + if (!Number.isInteger(waveId) || waveId <= 0) { + return this.fail('wave_id 参数必填,且必须为正整数', { code: 400 }); + } + + if (![ 'printed', 'unprinted' ].includes(targetStatus)) { + return this.fail('status 参数不合法,仅支持 printed / unprinted', { code: 400 }); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return this.fail('无法获取当前仓库ID,请确认已登录', { code: 400 }); + } + + const orderIds = await this.resolveBatchOrderIdsByWaveFallback({ warehouseId, waveId }); + if (orderIds.length === 0) { + return this.fail(`波次 ${waveId} 在当前仓库下没有可操作的订单`, { code: 404 }); + } + + const printStatus = targetStatus === 'printed' ? 'fin' : 'none'; + try { + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return this.fail('OrderDeliveryFactory 不可用', { code: 500 }); + } + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { + return this.fail('OrderDeliveryModel 不可用', { code: 500 }); + } + + const updateResult = await orderDeliveryModel.update({ + print_status: printStatus, + updated_at: new Date(), + }, { + where: { + id: { [this.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + status: { [this.app.Sequelize.Op.ne]: 'cancel' }, + }, + }); + + const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; + this.ctx.logger.info('[print.markWavePrintStatus] 波次打印状态标记完成 wave_id=%d target=%s affected=%d/%d', + waveId, targetStatus, affectedRows, orderIds.length); + + return this.success('ok', { + code: 0, + wave_id: waveId, + status: targetStatus, + print_status: printStatus, + total_orders: orderIds.length, + affected_orders: affectedRows, + order_ids: orderIds, + }); + } catch (error) { + this.ctx.logger.error('[print.markWavePrintStatus] 更新失败 wave_id=%d reason=%s', + waveId, error && error.message ? error.message : `${error}`); + return this.fail(`波次打印状态更新失败:${error && error.message ? error.message : '未知错误'}`, { code: 500 }); + } + } + + /** + * 波次确认打印:扫描波次内任一订单的面单号,将波次下全部已打印且非拦截的订单 + * 批量标记 confirm_print_status='fin',记录「打印完成后真实扫描面单确认」。 + * + * 约束: + * - 仅当前仓库下的订单可确认(面单定位强制 warehouse_id 隔离); + * - 波次下存在未打印订单(print_status != 'fin',拦截订单除外)时阻断; + * - 拦截订单跳过(不确认、不阻断); + * - 全部已确认时重复扫描返回 already_confirmed,不重复写日志。 + * + * @param {Object} data 入参。 + * @param {string} data.waybill_no 面单号/运单号(必填)。 + * @return {Promise} 统一返回结构。 + */ + async confirmWavePrint(data = {}) { + const { ctx } = this; + const requestData = data && typeof data === 'object' && !Array.isArray(data) ? data : {}; + const waybillNo = String(requestData.waybill_no || requestData.waybillNo || '').trim(); + if (!waybillNo) { + return this.fail('waybill_no 必填(面单号/运单号)', {}, 400); + } + + // --- 仓库上下文 --- + const userWarehouseId = ctx && ctx.user ? ctx.user.store_id : undefined; + const stateWarehouseId = ctx && ctx.state && ctx.state.user ? ctx.state.user.store_id : undefined; + const warehouseId = Number(userWarehouseId || stateWarehouseId || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return this.fail('缺少当前用户仓库上下文 store_id', {}, 400); + } + + // --- 1. 面单号定位订单 --- + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillNo, + }, + attributes: [ 'order_id' ], + raw: true, + }); + const matchedOrderId = Number(orderExpress && orderExpress.order_id || 0); + if (!(matchedOrderId > 0)) { + return this.fail('未查询到该面单号对应的订单,无记录', {}, 404); + } + + // --- 2. 订单定位波次 --- + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return this.fail('OrderDeliveryFactory 不可用', {}, 500); + } + let orderModel = null; + try { + orderModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + } catch (error) { + return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500); + } + const order = await orderModel.findOne({ + where: { + id: matchedOrderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (!order) { + return this.fail('订单不在待处理订单表,无记录', {}, 404); + } + const orderWaveId = Number(order.wave_id || 0); + const orderWaveNo = String(order.wave_no || '').trim(); + if (!(orderWaveId > 0 || orderWaveNo)) { + return this.fail('运单对应订单未分配波次', {}, 400); + } + + // --- 3. 查询波次下全部订单 --- + const waveOrderWhere = { warehouse_id: warehouseId }; + if (orderWaveId > 0) { + waveOrderWhere.wave_id = orderWaveId; + } else { + waveOrderWhere.wave_no = orderWaveNo; + } + const waveOrderRows = await orderModel.findAll({ + where: waveOrderWhere, + attributes: [ 'id', 'print_status', 'confirm_print_status', 'intercept_status' ], + raw: true, + }); + const waveOrders = Array.isArray(waveOrderRows) ? waveOrderRows : []; + if (waveOrders.length === 0) { + return this.fail('波次下无可用订单', {}, 400); + } + + // --- 4. 统计与校验(拦截订单跳过,未打印阻断) --- + const interceptedWaveOrderIds = new Set(waveOrders + .filter(item => isInterceptedOrderStatus(item && item.intercept_status)) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)); + + const unprintedOrderIds = [ ...new Set(waveOrders + .filter(item => String(item && item.print_status || '') !== 'fin' + && !interceptedWaveOrderIds.has(Number(item && item.id || 0))) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + if (unprintedOrderIds.length > 0) { + return this.fail('波次存在未打印订单,禁止确认打印', { + waybill_no: waybillNo, + matched_order_id: matchedOrderId, + wave_id: orderWaveId, + wave_no: orderWaveNo, + unprinted_order_count: unprintedOrderIds.length, + }, 400); + } + + const pendingOrderIds = [ ...new Set(waveOrders + .filter(item => String(item && item.print_status || '') === 'fin' + && String(item && item.confirm_print_status || '') !== 'fin' + && !interceptedWaveOrderIds.has(Number(item && item.id || 0))) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + const confirmedOrderIds = [ ...new Set(waveOrders + .filter(item => String(item && item.confirm_print_status || '') === 'fin' + && !interceptedWaveOrderIds.has(Number(item && item.id || 0))) + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + const baseResponse = { + waybill_no: waybillNo, + matched_order_id: matchedOrderId, + wave_id: orderWaveId, + wave_no: orderWaveNo, + total_order_count: waveOrders.length, + intercepted_order_count: interceptedWaveOrderIds.size, + }; + + if (pendingOrderIds.length === 0) { + return this.success('ok', { + code: 200, + data: { + ...baseResponse, + confirmed_order_count: confirmedOrderIds.length, + status: 'already_confirmed', + tip: '该波次订单均已确认打印,无需重复确认', + }, + }); + } + + // --- 5. 事务批量确认并写订单操作日志 --- + const operationLogService = ctx.service + && ctx.service.systems + && ctx.service.systems.operationLog; + const operator = this.getPrintOrderOperationOperator(); + const transaction = await ctx.model.transaction(); + try { + const updateResult = await orderModel.update({ + confirm_print_status: 'fin', + }, { + where: { + id: { [this.app.Sequelize.Op.in]: pendingOrderIds }, + warehouse_id: warehouseId, + print_status: 'fin', + }, + transaction, + }); + const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(pendingOrderIds.map(orderId => ({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_CONFIRM_PRINT', + operator, + operationAction: 'UPDATE', + extras: { + warehouseId, + message: `确认打印(扫描面单 ${waybillNo},波次 ${orderWaveNo})`, + }, + })), { transaction }); + } + + await transaction.commit(); + + // 驱动确认打印未领单波次统计长轮询:递增版本号,等待中的查询立即返回新值 + try { + const waveService = ctx.service + && ctx.service.systemMethods + && ctx.service.systemMethods.order + && ctx.service.systemMethods.order.wave; + if (waveService && typeof waveService.bumpConfirmPrintUnclaimedWaveVersion === 'function') { + await waveService.bumpConfirmPrintUnclaimedWaveVersion(warehouseId); + } + } catch (error) { + this.ctx.logger.warn('[print.confirmWavePrint] 统计版本号递增失败', { + warehouseId, + error: error && error.message ? error.message : `${error}`, + }); + } + + this.ctx.logger.info('[print.confirmWavePrint] 波次确认打印完成 warehouse_id=%d wave_id=%d affected=%d/%d', + warehouseId, orderWaveId, affectedRows, pendingOrderIds.length); + + return this.success('ok', { + code: 200, + data: { + ...baseResponse, + confirmed_order_count: confirmedOrderIds.length + affectedRows, + newly_confirmed_order_count: affectedRows, + status: 'confirmed', + tip: `波次确认打印完成,本次确认 ${affectedRows} 个订单`, + }, + }); + } catch (error) { + await transaction.rollback(); + this.ctx.logger.error('[print.confirmWavePrint] 波次确认打印失败 warehouse_id=%d wave_id=%d reason=%s', + warehouseId, orderWaveId, error && error.message ? error.message : `${error}`); + return this.fail('确认打印失败', {}, 500); + } + } + + /** + * 在打印发送成功后批量锁定订单。 + * + * 仅将 print_lock_status=none 的订单更新为 warehouse,避免覆盖既有锁定状态。 + * + * @param {Object} payload 锁定参数。 + * @param {number|string} payload.warehouseId 仓库ID。 + * @param {Array} payload.orderIds 订单ID数组。 + * @return {Promise<{success:boolean,lockedCount:number,errorMessage:string}>} 锁定结果。 + */ + async lockOrderDeliveryAfterPrintSentSuccess(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const warehouseId = Number(normalizedPayload.warehouseId || 0); + const orderIds = Array.isArray(normalizedPayload.orderIds) + ? Array.from(new Set(normalizedPayload.orderIds + .map(orderId => Number(orderId || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0))) + : []; + + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) { + return { + success: true, + lockedCount: 0, + errorMessage: '', + }; + } + + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return { + success: false, + lockedCount: 0, + errorMessage: 'OrderDeliveryFactory 不可用', + }; + } + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { + return { + success: false, + lockedCount: 0, + errorMessage: 'OrderDeliveryModel 不可用', + }; + } + + const updateResult = await orderDeliveryModel.update({ + print_lock_status: 'warehouse', + print_status: 'fin', + }, { + where: { + id: orderIds, + intercept_status: 'none', + }, + }); + + const lockedCount = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; + return { + success: true, + lockedCount: lockedCount > 0 ? lockedCount : 0, + errorMessage: '', + }; + } catch (error) { + return { + success: false, + lockedCount: 0, + errorMessage: error && error.message ? error.message : `${error}`, + }; + } + } + + /** + * 加载并校验 express 请求涉及平台的打印组件配置。 + * + * 解析顺序: + * 1. 直接按 `wms_print_platform.platform_code` 匹配(快递接口透出的打印平台编码, + * 如 CAINIAO/DY/JD/KS/PDD/SPH/XHS); + * 2. 未匹配的编码视为系统平台编码(如 TB/TM/1688/TGC),经 + * `wms_platform.code -> print_platform_id -> wms_print_platform.platform_name` + * 回退解析对应打印组件。 + * + * @param {Object} payload 查询参数。 + * @param {Array} payload.platformCodes 平台编码列表。 + * @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询与校验结果。 + */ + async loadExpressPlatformComponents(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const platformCodes = Array.isArray(normalizedPayload.platformCodes) + ? normalizedPayload.platformCodes.filter(item => String(item || '').trim()) + : []; + if (platformCodes.length === 0) { + return { + success: false, + error: 'type=express 时未识别到有效平台编码', + }; + } + + const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; + const platformModel = this.ctx && this.ctx.model && this.ctx.model.Platform; + const platformComponentMap = {}; + + // 1) 优先按打印平台编码直接匹配 + if (printPlatformModel && typeof printPlatformModel.findAll === 'function') { + const platformRows = await printPlatformModel.findAll({ + attributes: [ 'id', 'platform_code', 'platform_name' ], + where: { + platform_code: platformCodes, + }, + raw: true, + }); + for (const row of Array.isArray(platformRows) ? platformRows : []) { + const platformCode = String(row && row.platform_code ? row.platform_code : '').trim(); + if (!platformCode) { + continue; + } + platformComponentMap[platformCode] = String(row && row.platform_name ? row.platform_name : '').trim(); + } + } + + // 2) 未匹配编码按系统平台编码回退解析(TB/TM/1688 等经 print_platform_id 关联) + const unresolvedCodes = platformCodes.filter(platformCode => { + return !String(platformComponentMap[platformCode] || '').trim(); + }); + if (unresolvedCodes.length > 0 + && printPlatformModel && typeof printPlatformModel.findAll === 'function' + && platformModel && typeof platformModel.findAll === 'function') { + const systemPlatformRows = await platformModel.findAll({ + attributes: [ 'code', 'print_platform_id' ], + where: { + code: unresolvedCodes, + }, + raw: true, + }); + const codeListByPrintPlatformIdMap = new Map(); + for (const row of Array.isArray(systemPlatformRows) ? systemPlatformRows : []) { + const platformCode = String(row && row.code ? row.code : '').trim(); + const printPlatformId = Number(row && row.print_platform_id || 0); + if (!platformCode || !Number.isInteger(printPlatformId) || printPlatformId <= 0) { + continue; + } + if (!codeListByPrintPlatformIdMap.has(printPlatformId)) { + codeListByPrintPlatformIdMap.set(printPlatformId, []); + } + codeListByPrintPlatformIdMap.get(printPlatformId).push(platformCode); + } + + if (codeListByPrintPlatformIdMap.size > 0) { + const printPlatformRows = await printPlatformModel.findAll({ + attributes: [ 'id', 'platform_name' ], + where: { + id: Array.from(codeListByPrintPlatformIdMap.keys()), + }, + raw: true, + }); + const componentNameByPrintPlatformIdMap = new Map(); + for (const row of Array.isArray(printPlatformRows) ? printPlatformRows : []) { + const printPlatformId = Number(row && row.id || 0); + const componentName = String(row && row.platform_name ? row.platform_name : '').trim(); + if (!Number.isInteger(printPlatformId) || printPlatformId <= 0) { + continue; + } + componentNameByPrintPlatformIdMap.set(printPlatformId, componentName); + } + for (const [ printPlatformId, codeList ] of codeListByPrintPlatformIdMap) { + const componentName = componentNameByPrintPlatformIdMap.get(printPlatformId) || ''; + for (const platformCode of codeList) { + platformComponentMap[platformCode] = componentName; + } + } + } + } + + for (const platformCode of platformCodes) { + const component = String(platformComponentMap[platformCode] || '').trim(); + if (!component) { + return { + success: false, + error: `平台 ${platformCode} 未配置打印组件`, + }; + } + } + + this.ctx.logger.info('[print.send] express 平台打印组件解析完成', { + platformComponents: platformComponentMap, + }); + + return { + success: true, + data: platformComponentMap, + }; + } + + /** + * 校验 express 请求涉及组件是否全部在线。 + * @param {Object} payload 校验参数。 + * @param {string} payload.computerId 打印电脑 ID。 + * @param {Object} payload.platformComponents 平台到组件映射。 + * @return {Promise<{success:boolean,error?:string}>} 校验结果。 + */ + async validateExpressComponentsOnline(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const computerId = String(normalizedPayload.computerId || '').trim(); + const platformComponents = normalizedPayload.platformComponents && typeof normalizedPayload.platformComponents === 'object' + ? normalizedPayload.platformComponents + : {}; + if (!computerId) { + return { + success: false, + error: '打印台未配置打印电脑', + }; + } + + const redisPrinter = this.app.redis.get('printer'); + const entries = Object.entries(platformComponents); + for (const entry of entries) { + const platformCode = String(entry[0] || '').trim(); + const component = String(entry[1] || '').trim(); + const statusKey = `printer:${computerId}:name:${component}:status`; + const componentStatus = await redisPrinter.get(statusKey); + if (componentStatus !== 'connected') { + return { + success: false, + error: `平台 ${platformCode} 打印组件 ${component} 未在线`, + }; + } + } + + return { success: true }; + } + + /** + * 根据平台快递编码解析打印机名称。 + * @param {Object} payload 解析参数。 + * @param {Object} payload.printStation 打印台配置。 + * @param {string} payload.sysLogisticsCode 系统快递编码。 + * @return {{success:boolean,data?:string,error?:string}} 解析结果。 + */ + resolveExpressPrinterName(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const printStation = normalizedPayload.printStation && typeof normalizedPayload.printStation === 'object' + ? normalizedPayload.printStation + : {}; + let subjectConfig = printStation.subject_config; + if (typeof subjectConfig === 'string') { + try { + subjectConfig = JSON.parse(subjectConfig); + } catch (error) { + subjectConfig = {}; + } + } + if (!subjectConfig || typeof subjectConfig !== 'object' || Array.isArray(subjectConfig)) { + subjectConfig = {}; + } + + const expressBindPrinter = Array.isArray(subjectConfig.express_bind_printer) + ? subjectConfig.express_bind_printer + : []; + const sysLogisticsCode = String(normalizedPayload.sysLogisticsCode || '').trim(); + const matchedPrinter = expressBindPrinter.find(item => { + const sourceItem = item && typeof item === 'object' ? item : {}; + return String(sourceItem.express_code || '').trim() === sysLogisticsCode; + }); + const printerName = String( + matchedPrinter && matchedPrinter.printer_name + ? matchedPrinter.printer_name + : (printStation.default_printer_name || '') + ).trim(); + if (!printerName) { + return { + success: false, + error: '打印台未配置默认打印机', + }; + } + + this.ctx.logger.info('[print.send] resolveExpressPrinterName 成功', { + sysLogisticsCode, + printerName, + matched: Boolean(matchedPrinter), + matchSource: matchedPrinter ? '命中快递绑定' : '回退默认打印机', + }); + + return { + success: true, + data: printerName, + }; + } + + /** + * 串行发送快递打印任务(波次 -> 平台快递组)。 + * @param {Object} payload 发送参数。 + * @param {number|string} payload.warehouseId 仓库 ID。 + * @param {Array} payload.waveGroups 波次分组。 + * @param {string} payload.requestCode 请求参数码。 + * @param {Object} payload.printStation 打印台配置。 + * @param {Object} payload.payloadBuilder 快递模板组装器。 + * @param {Object} payload.idGenerator 本次请求 ID 生成器。 + * @param {Object} payload.expressRecordFields 快递打印记录字段。 + * @param {Object} payload.platformComponents 平台到打印组件映射。 + * @param {string} payload.type 打印类型。 + * @param {Object|null} payload.template 模板数据。 + * @param {Object} payload.data 业务数据。 + * @return {Promise<{success:boolean,error?:string,taskCodes?:Array,printId:number,printIds:Array}>} 发送结果。 + */ + async sendExpressWaveGroups(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const waveGroups = Array.isArray(normalizedPayload.waveGroups) + ? normalizedPayload.waveGroups + : []; + const generatedTaskCodes = []; + const createdPrintRecordIds = []; + + for (const waveGroup of waveGroups) { + const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; + for (const platformGroup of platforms) { + const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : []; + if (orders.length === 0) { + continue; + } + const groupSummary = { + waveNo: waveGroup && waveGroup.wave_no ? waveGroup.wave_no : '', + platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', + sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code ? platformGroup.sys_logistics_code : '', + ordersCount: orders.length, + }; + const requestCode = String(normalizedPayload.requestCode || '').trim() || null; + const rawWaveId = waveGroup && waveGroup.wave_id; + const normalizedWaveId = rawWaveId === null || rawWaveId === undefined || String(rawWaveId).trim() === '' + ? null + : Number(rawWaveId); + const waveId = Number.isFinite(normalizedWaveId) + ? normalizedWaveId + : null; + const waveNo = String(waveGroup && waveGroup.wave_no ? waveGroup.wave_no : '').trim() || null; + const platformCodeForRecord = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim() || null; + const platformName = String(platformGroup && platformGroup.platform_name ? platformGroup.platform_name : '').trim() || null; + const sysLogisticsCode = String(platformGroup && platformGroup.sys_logistics_code ? platformGroup.sys_logistics_code : '').trim() || null; + const sysLogisticsName = String(platformGroup && platformGroup.sys_logistics_name ? platformGroup.sys_logistics_name : '').trim() || null; + this.ctx.logger.info('[print.send] 平台快递组发送开始', groupSummary); + + const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim(); + const component = String( + normalizedPayload.platformComponents + && normalizedPayload.platformComponents[platformCode] + ? normalizedPayload.platformComponents[platformCode] + : '' + ).trim(); + if (!component) { + this.ctx.logger.error('[print.send] 平台快递组发送失败-打印组件缺失', { + ...groupSummary, + reason: `平台 ${platformCode} 未配置打印组件`, + }); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...groupSummary, + status: 'failure', + reason: `平台 ${platformCode} 未配置打印组件`, + }); + return { + success: false, + error: `平台 ${platformCode} 未配置打印组件`, + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, + }; + } + + const printerNameResult = this.resolveExpressPrinterName({ + printStation: normalizedPayload.printStation, + sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code, + }); + if (!printerNameResult.success) { + this.ctx.logger.error('[print.send] 平台快递组发送失败-打印机解析失败', { + ...groupSummary, + reason: printerNameResult.error, + }); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...groupSummary, + status: 'failure', + reason: printerNameResult.error, + }); + return { + success: false, + error: printerNameResult.error, + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, + }; + } + + const normalizedPlatformCode = this.normalizeExpressPlatformCode({ + platformCode: platformGroup && platformGroup.platform ? platformGroup.platform : '', + payloadBuilder: normalizedPayload.payloadBuilder, + }); + const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou'; + const orderBatches = []; + if (isKuaishouPlatform) { + for (let index = 0; index < orders.length; index += 10) { + orderBatches.push(orders.slice(index, index + 10)); + } + } else { + orderBatches.push(orders); + } + const totalDocumentCount = orders.length; + + for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) { + const batchOrders = orderBatches[batchIndex]; + const batchOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, batchOrders); + // 兜底:前端未回传 order_ids 时,通过 wave_id 反查当前波次全部订单ID + if (batchOrderIds.length === 0 && waveId) { + const fallbackIds = await this.resolveBatchOrderIdsByWaveFallback({ + warehouseId: normalizedPayload.warehouseId, + waveId, + }); + if (fallbackIds.length > 0) { + batchOrderIds.push(...fallbackIds); + } + } + const currentPrinterName = printerNameResult.data; + const batchSummary = { + ...groupSummary, + batchIndex: batchIndex + 1, + batchCount: orderBatches.length, + batchOrdersCount: batchOrders.length, + }; + let requestPayload; + let currentTaskCode = ''; + try { + requestPayload = normalizedPayload.payloadBuilder.buildPayload({ + platform: platformGroup && platformGroup.platform, + printerName: printerNameResult.data, + orders: batchOrders, + idGenerator: normalizedPayload.idGenerator, + }); + if (isKuaishouPlatform && requestPayload && requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { + requestPayload.task.firstDocumentNumber = batchIndex * 10 + 1; + requestPayload.task.totalDocumentCount = totalDocumentCount; + } + currentTaskCode = await this.reserveUniquePrintTaskCode(); + if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { + requestPayload.task.taskID = currentTaskCode; + } + if (currentTaskCode && !generatedTaskCodes.includes(currentTaskCode)) { + generatedTaskCodes.push(currentTaskCode); + } + + const payloadSummary = this.summarizeExpressPayload(requestPayload); + this.ctx.logger.info('[print.send] 组装 payload 成功', { + ...batchSummary, + platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', + ordersCount: batchOrders.length, + documentCount: payloadSummary.documentCount, + }); + } catch (error) { + this.ctx.logger.error('[print.send] 组装 payload 失败', { + ...batchSummary, + platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', + ordersCount: batchOrders.length, + reason: error && error.message ? error.message : '快递打印任务组装失败', + }); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...batchSummary, + status: 'failure', + reason: error && error.message ? error.message : '快递打印任务组装失败', + }); + return { + success: false, + error: error && error.message ? error.message : '快递打印任务组装失败', + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, + }; + } + + let currentPrintRecord; + try { + currentPrintRecord = await this.ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ + warehouse_id: normalizedPayload.warehouseId, + computer_id: normalizedPayload.expressRecordFields.computer_id, + printer: currentPrinterName, + type: normalizedPayload.type, + request_code: requestCode, + wave_id: waveId, + wave_no: waveNo, + platform_code: platformCodeForRecord, + platform_name: platformName, + sys_logistics_code: sysLogisticsCode, + sys_logistics_name: sysLogisticsName, + data: { + printer: currentPrinterName, + component, + type: 'express', + order_ids: batchOrderIds, + data: requestPayload, + }, + })); + createdPrintRecordIds.push(currentPrintRecord.id); + this.ctx.logger.info('[print.send] PrintRecord 创建成功', { + ...batchSummary, + printId: currentPrintRecord.id, + computerId: normalizedPayload.expressRecordFields.computer_id, + printer: currentPrinterName, + }); + } catch (error) { + this.ctx.logger.error('[print.send] PrintRecord 创建失败', { + ...batchSummary, + computerId: normalizedPayload.expressRecordFields.computer_id, + printer: currentPrinterName, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + return { + success: false, + error: error && error.message ? error.message : '打印记录创建失败', + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, + }; + } + + const printData = { + printer: currentPrinterName, + component, + type: 'express', + order_ids: batchOrderIds, + data: requestPayload, + printId: currentPrintRecord.id, + }; + const sendStartAt = Date.now(); + let sendResult; + try { + sendResult = await this.service.systems.print.index.sendToComputer({ + warehouse: normalizedPayload.warehouseId, + computerId: normalizedPayload.printStation.computer_id, + data: printData, + }); + } catch (error) { + const sendDurationMs = Date.now() - sendStartAt; + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds: batchOrderIds, + source: 'print.send', + message: `批次发送失败,原因=${error && error.message ? error.message : `${error}`}`, + }); + this.ctx.logger.error('[print.send] sendToComputer 调用失败', { + ...batchSummary, + printId: currentPrintRecord.id, + computerId: normalizedPayload.printStation.computer_id, + durationMs: sendDurationMs, + reason: error && error.message ? error.message : `${error}`, + }); + await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ + errorMessage: error && error.message ? error.message : `${error}`, + })); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...batchSummary, + printId: currentPrintRecord.id, + computerId: normalizedPayload.printStation.computer_id, + status: 'failure', + reason: error && error.message ? error.message : `${error}`, + }); + return { + success: false, + error: error && error.message ? error.message : '打印服务调用失败', + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, + }; + } + const sendDurationMs = Date.now() - sendStartAt; + if (sendResult.status !== 'success') { + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds: batchOrderIds, + source: 'print.send', + message: `批次发送失败,原因=${sendResult.error || '打印服务返回失败'}`, + }); + this.ctx.logger.error('[print.send] sendToComputer 调用失败', { + ...batchSummary, + printId: currentPrintRecord.id, + computerId: normalizedPayload.printStation.computer_id, + durationMs: sendDurationMs, + reason: sendResult.error || '打印服务返回失败', + }); + await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ + errorMessage: sendResult.error || '打印服务返回失败', + })); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...batchSummary, + printId: currentPrintRecord.id, + computerId: normalizedPayload.printStation.computer_id, + status: 'failure', + reason: sendResult.error || '打印服务返回失败', + }); + } else { + this.ctx.logger.info('[print.send] sendToComputer 调用成功', { + ...batchSummary, + computerId: normalizedPayload.printStation.computer_id, + durationMs: sendDurationMs, + }); + } + if (sendResult.status !== 'success') { + return { + success: false, + error: sendResult.error || '打印服务返回失败', + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, + }; + } + const providerTaskId = String( + sendResult && (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id) + ? (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id) + : '' + ).trim(); + try { + await this.bindTaskCodeToPrintRecordWithRetry({ + printRecordId: currentPrintRecord.id, + taskCode: currentTaskCode, + provider: providerTaskId, + }); + } catch (error) { + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds: batchOrderIds, + source: 'print.send', + message: `批次发送失败,原因=${error && error.message ? error.message : `${error}`}`, + }); + await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ + errorMessage: error && error.message ? error.message : `${error}`, + })); + this.ctx.logger.error('[print.send] 平台快递组发送成功但回写失败', { + ...batchSummary, + printId: currentPrintRecord.id, + taskCode: currentTaskCode, + providerTaskId, + reason: error && error.message ? error.message : `${error}`, + }); + return { + success: false, + error: `打印任务发送成功但回写失败:${error && error.message ? error.message : '未知错误'}`, + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, + }; + } + + const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({ + warehouseId: normalizedPayload.warehouseId, + orderIds: batchOrderIds, + }); + if (!lockResult.success) { + this.ctx.logger.error('[print.send] 批次发送成功后锁定订单失败', { + ...batchSummary, + warehouseId: normalizedPayload.warehouseId, + orderIdsCount: batchOrderIds.length, + reason: lockResult.errorMessage, + }); + } + + const orderPrintStatusUpdateResult = await this.updateOrderPrintStatusByCallback({ + warehouseId: normalizedPayload.warehouseId, + orderIds: batchOrderIds, + result: 'success', + }); + if (!orderPrintStatusUpdateResult.success) { + this.ctx.logger.error('[print.send] 批次发送成功后同步订单主表 print_status 失败', { + ...batchSummary, + warehouseId: normalizedPayload.warehouseId, + orderIdsCount: batchOrderIds.length, + reason: orderPrintStatusUpdateResult.errorMessage, + }); + } + + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds: batchOrderIds, + source: 'print.send', + message: `批次发送结束成功,print_id=${currentPrintRecord.id},order_count=${batchOrderIds.length}`, + }); + + this.ctx.logger.info('[print.send] 平台快递组发送结束', { + ...batchSummary, + printId: currentPrintRecord.id, + computerId: normalizedPayload.printStation.computer_id, + status: 'success', + }); + } + } + } + + return { + success: true, + taskCodes: generatedTaskCodes, + printId: createdPrintRecordIds[0] || 0, + printIds: createdPrintRecordIds, + }; + } + + /** + * 解析打印回执时间,解析失败时回退当前时间。 + * @param {string|Date|number} callbackTime 回执时间。 + * @return {Date} 归一化后的打印时间。 + */ + parsePrintCallbackTime(callbackTime) { + if (callbackTime instanceof Date && !Number.isNaN(callbackTime.getTime())) { + return callbackTime; + } + if (callbackTime === undefined || callbackTime === null || callbackTime === '') { + return new Date(); + } + const parsedDate = new Date(callbackTime); + if (Number.isNaN(parsedDate.getTime())) { + return new Date(); + } + return parsedDate; + } + + /** + * 处理打印结果回执,按 print_task_code 更新打印记录并保证幂等。 + * @param {Object} data 回执参数。 + * @param {string} data.print_task_code 打印任务编码。 + * @param {string} data.result 回执结果,仅支持 success/failed。 + * @param {string} [data.error_message] 失败原因。 + * @param {string} [data.fail_code] 失败编码。 + * @param {string} [data.printer] 打印机标识。 + * @param {string|Date|number} [data.callback_time] 回执时间。 + * @return {Promise} 统一回执处理结果。 + */ + async handlePrintCallback(data = {}) { + const requestData = data && typeof data === 'object' ? data : {}; + const { + print_task_code: printTaskCode, + result, + error_message: errorMessage, + fail_code: failCode, + printer, + callback_time: callbackTime, + } = requestData; + + const normalizedPrintTaskCode = String(printTaskCode || '').trim(); + if (!normalizedPrintTaskCode) { + return this.fail('print_task_code 参数不能为空', { code: 400 }); + } + + const normalizedResult = String(result || '').trim().toLowerCase(); + if (![ 'success', 'failed' ].includes(normalizedResult)) { + return this.fail('result 参数不合法,仅支持 success/failed', { code: 400 }); + } + + const printTaskMap = await this.ctx.model.PrintTaskMap.findOne({ + where: { + task_code: normalizedPrintTaskCode, + }, + raw: true, + }); + if (!printTaskMap || !printTaskMap.print_record_id) { + return this.fail('打印任务映射不存在', { + code: 404, + result: 'not_found', + print_task_code: normalizedPrintTaskCode, + }); + } + + const printRecordId = Number(printTaskMap.print_record_id || 0); + const printRecord = await this.ctx.model.PrintRecord.findOne({ + where: { id: printRecordId }, + raw: true, + }); + if (!printRecord) { + return this.fail('打印记录不存在', { + code: 404, + result: 'not_found', + print_task_code: normalizedPrintTaskCode, + print_record_id: printRecordId, + }); + } + + const currentPrintStatus = String(printRecord.print_status || '').trim(); + if (normalizedResult === 'success' && currentPrintStatus === 'printed') { + return this.success('打印回执已处理', { + code: 0, + result: 'idempotent', + print_task_code: normalizedPrintTaskCode, + print_record_id: printRecordId, + print_status: 'unknown', + }); + } + + if (normalizedResult === 'failed' && currentPrintStatus === 'printed') { + return this.success('已打印成功,忽略失败回执', { + code: 0, + result: 'ignored', + print_task_code: normalizedPrintTaskCode, + print_record_id: printRecordId, + print_status: 'unknown', + }); + } + + const normalizedPrintTime = this.parsePrintCallbackTime(callbackTime); + const orderIds = this.extractOrderIdsFromPrintRecordData(printRecord.data); + const warehouseId = Number(printRecord.warehouse_id || 0); + const updatePayload = normalizedResult === 'success' + ? { + status: 'sent', + print_status: 'unknown', + error_message: null, + fail_code: null, + print_time: normalizedPrintTime, + } + : { + print_status: 'print_failed', + error_message: errorMessage ? String(errorMessage) : null, + fail_code: failCode ? String(failCode) : 'PRINT_CALLBACK_FAILED', + print_time: normalizedPrintTime, + }; + + await this.ctx.model.PrintRecord.update(updatePayload, { + where: { id: printRecordId }, + }); + + const orderPrintStatusUpdateResult = await this.updateOrderPrintStatusByCallback({ + warehouseId, + orderIds, + result: normalizedResult, + }); + if (!orderPrintStatusUpdateResult.success) { + this.ctx.logger.error('[print.callback] 同步订单主表 print_status 失败', { + printTaskCode: normalizedPrintTaskCode, + printRecordId, + result: normalizedResult, + orderIdsCount: orderIds.length, + reason: orderPrintStatusUpdateResult.errorMessage, + }); + } + + this.ctx.logger.info('[print.callback] 回执处理完成', { + printTaskCode: normalizedPrintTaskCode, + printRecordId, + result: normalizedResult, + printer: printer ? String(printer) : '', + }); + + return this.success('打印回执处理成功', { + code: 0, + result: 'updated', + print_task_code: normalizedPrintTaskCode, + print_record_id: printRecordId, + print_status: 'unknown', + }); + } + + /** + * 查询单条打印结果。 + * @param {Object} data 入参。 + * @param {number|string} data.printId 打印记录ID。 + * @return {Promise} 查询结果。 + */ + async getPrintResult(data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { printId } = data; + if (!printId) return this.fail('参数错误', 1001); + const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true }); + if (!record) return this.fail('打印记录不存在', 1002); + return this.success('success', { ...record, code: 0 }); + } + + /** + * 查询单条打印记录详情。 + * @param {Object} data 入参。 + * @param {number|string} data.id 打印记录ID。 + * @return {Promise} 查询结果。 + */ + async getPrintRecordItem(data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { id } = data; + if (!id) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true }); + if (!item) return this.fail('打印记录不存在', 1002); + return this.success('success', { ...item, code: 0 }); + } + /** * 1. 查询打印台列表 * @param {Object} data { page, pageSize, where } */ - async getList(data) { - const { ctx } = this; - console.log("ctx.user in PrintService constructor", ctx.user); - const warehouse_id = ctx.user.store_id; - // TODO: 需根据实际分页和条件查询调整 - const { page = 1, pageSize = 20, where = {} } = data; - // 字段过滤 - const filter = {}; - ['id', 'name', 'computer_id', 'custom_barcode'].forEach(key => { - if (where[key]) filter[key] = where[key]; - }); - filter.warehouse_id = warehouse_id; - filter.deleted = 0; - // 查询总数 - console.log("ctx.model.PrintStations", ctx.model.PrintStations); - const total = await ctx.model.PrintStations.count({ where: filter }); - // 查询分页数据 - const list = await ctx.model.PrintStations.findAll({ - where: filter, - offset: (page - 1) * pageSize, - limit: pageSize, - order: [['create_at', 'DESC']], - raw: true, - }); - let computers = list.map(item => { - const computer = { - id: item.computer_id, - is_online: 0, - components: this.defaultComponents.map(component => ({ - name: component.name, - is_online: 0, - })) - }; - return computer; - }); - // 动态属性处理(如 is_online、components) - for (let i = 0; i < computers.length; i++) { - let key = `warehouse:${warehouse_id}:printer:${computers[i].id}`; - const computerInfo = await this.app.redis.get("printer").get(key); - console.log("key and computerInfo", key, computerInfo); - if (computerInfo) { - computers[i].is_online = 1; - computers[i].components = await Promise.all(computers[i].components.map(async component => { - const componentKey = `printer:${computers[i].id}:name:${component.name}:status`; - const componentInfo = await this.app.redis.get("printer").get(componentKey); - console.log("componentKey and componentInfo", componentKey, componentInfo); - if (componentInfo && componentInfo == "connected") { - component.is_online = 1; - } - return component; - })); - } - } - - for (const item of list) { - const computer = computers.find(c => c.id === item.computer_id); - item.is_online = computer ? computer.is_online : 0; - item.components = computer ? computer.components : this.defaultComponents.map(component => ({ - name: component.name, - is_online: 0, - })); - } - const result = { - code: 200, - data: { - list: list, - pagination: { - hasNext: page * pageSize < total, - hasPrevious: page > 1, - page: page, - pageSize: pageSize, - total: total, - totalPages: Math.ceil(total / pageSize), - }, - queryInfo: { - conditions: where, - hasBarcodeSearch: false, - sortField: 'id', - sortOrder: "DESC" - }, - summary: { - total_available: total, - total_items: pageSize, - total_locked: 0, - total_quantity: 0 - } - } - } - return this.success('success', result); + async getList(data) { + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + const requestData = data && typeof data === 'object' ? data : {}; + const { whereValue } = this.prepareWhereContext(requestData); + const { page = 1, pageSize = 20 } = requestData; + // 字段过滤 + const filter = {}; + [ 'id', 'name', 'computer_id', 'custom_barcode' ].forEach(key => { + const value = whereValue[key]; + if (value !== undefined && value !== null && value !== '') filter[key] = value; + }); + filter.warehouse_id = warehouse_id; + filter.deleted = 0; + // 查询总数 + const total = await ctx.model.PrintStations.count({ where: filter }); + // 查询分页数据 + const list = await ctx.model.PrintStations.findAll({ + where: filter, + offset: (page - 1) * pageSize, + limit: pageSize, + order: [[ 'create_at', 'DESC' ]], + raw: true, + }); + const computers = list.map(item => { + const computer = { + id: item.computer_id, + is_online: 0, + components: this.defaultComponents.map(component => ({ + name: component.name, + is_online: 0, + })), + }; + return computer; + }); + // 动态属性处理(如 is_online、components) + for (let i = 0; i < computers.length; i++) { + const key = `warehouse:${warehouse_id}:printer:${computers[i].id}`; + const computerInfo = await this.app.redis.get('printer').get(key); + if (computerInfo) { + computers[i].is_online = 1; + computers[i].components = await Promise.all(computers[i].components.map(async component => { + const componentKey = `printer:${computers[i].id}:name:${component.name}:status`; + const componentInfo = await this.app.redis.get('printer').get(componentKey); + if (componentInfo && componentInfo === 'connected') { + component.is_online = 1; + } + return component; + })); + } } - /** + for (const item of list) { + const computer = computers.find(c => c.id === item.computer_id); + item.is_online = computer ? computer.is_online : 0; + item.components = computer ? computer.components : this.defaultComponents.map(component => ({ + name: component.name, + is_online: 0, + })); + } + const result = { + code: 200, + data: { + list, + pagination: { + hasNext: page * pageSize < total, + hasPrevious: page > 1, + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + queryInfo: { + conditions: this.ctx.where || {}, + hasBarcodeSearch: false, + sortField: 'id', + sortOrder: 'DESC', + }, + summary: { + total_available: total, + total_items: pageSize, + total_locked: 0, + total_quantity: 0, + }, + }, + }; + return this.success('success', result); + } + + /** * 2. 获取单个打印台 * @param {Object} data { id } + * @return {Promise} 返回打印台详情(不包含 warehouse_id) */ - async getItem(data) { - const { ctx } = this; - const { id } = data; - if (!id) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true }); - if (!item) return this.fail('打印台不存在', 1002); - return this.success('success', { ...item, code: 0 }); - } - /** + async getItem(data) { + const { ctx } = this; + const { id } = data; + if (!id) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true }); + if (!item) return this.fail('打印台不存在', 1002); + const rest = { ...item }; + delete rest.warehouse_id; + return this.success('success', { ...rest, code: 0 }); + } + /** * 3. 添加打印台 * @param {Object} data { id, name, computer_id, custom_barcode } + * @return {Promise} 返回新增结果。 */ - async add(data) { - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - const { name, computer_id, custom_barcode } = data; - if (!name || !computer_id) return this.fail('参数错误', 1001); - const newItem = await ctx.model.PrintStations.create({ - warehouse_id, - name, - computer_id, - custom_barcode, - creator_id: ctx.user?.employees_id || '', - creator_name: ctx.user?.employees_name || '', - default_printer_name: data.default_printer_name || '', - create_at: new Date(), - update_at: new Date(), - deleted: 0, - }); - return this.success('添加打印台成功', { data: newItem, code: 0 }); - } - async hasName(data) { - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - const { name, id } = data; - if (!name) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true }); - return this.success('success', { exists: !!item, code: 0 }); - } - /** - * 3. 修改打印台 - * @param {Object} data { id, name, computer_id, custom_barcode } - */ - async updateItem(data) { - const { ctx } = this; - const { id, name, computer_id, custom_barcode } = data; - if (!id) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintStations.findOne({ where: { id } }); - if (!item) return this.fail('打印台不存在', 1002); - // 只更新允许字段 - if (name !== undefined) item.name = name; - if (computer_id !== undefined) item.computer_id = computer_id; - if (custom_barcode !== undefined) item.custom_barcode = custom_barcode; - await item.save(); - return this.success('success', { data: null, code: 0 }); + async add(data) { + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + const { name, computer_id, custom_barcode, subject_config } = data; + if (!name || !computer_id) return this.fail('参数错误', 1001); + const createPayload = { + warehouse_id, + name, + computer_id, + custom_barcode, + creator_id: ctx.user?.employees_id || '', + creator_name: ctx.user?.employees_name || '', + default_printer_name: data.default_printer_name || '', + create_at: new Date(), + update_at: new Date(), + deleted: 0, + }; + + if (Object.prototype.hasOwnProperty.call(data, 'subject_config')) { + try { + createPayload.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(subject_config); + } catch (error) { + return this.fail(error.message, 1001); + } } - /** + const newItem = await ctx.model.PrintStations.create(createPayload); + return this.success('添加打印台成功', { data: newItem, code: 0 }); + } + async hasName(data) { + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + const { name, id } = data; + if (!name) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true }); + return this.success('success', { exists: !!item, code: 0 }); + } + /** + * 3. 修改打印台 + * @param {Object} data { id, name, computer_id, custom_barcode } + * @return {Promise} 返回更新结果。 + */ + async updateItem(data) { + const { ctx } = this; + const { id, name, computer_id, custom_barcode, subject_config } = data; + if (!id) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintStations.findOne({ where: { id } }); + if (!item) return this.fail('打印台不存在', 1002); + // 只更新允许字段 + if (name !== undefined) item.name = name; + if (computer_id !== undefined) item.computer_id = computer_id; + if (custom_barcode !== undefined) item.custom_barcode = custom_barcode; + if (Object.prototype.hasOwnProperty.call(data, 'subject_config')) { + try { + item.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(subject_config); + } catch (error) { + return this.fail(error.message, 1001); + } + } + await item.save(); + return this.success('success', { data: null, code: 0 }); + } + + /** * 4. 删除打印台 * @param {Object} data { ids } */ - async del(data) { - const { ctx } = this; - const { ids } = data; - if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001); - // 软删除 - const result = await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } }); - // TODO: 检查 result 是否成功 - return this.success('success', { data: null, code: 0 }); - } + async del(data) { + const { ctx } = this; + const { ids } = data; + if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001); + // 软删除 + await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } }); + // TODO: 检查 result 是否成功 + return this.success('success', { data: null, code: 0 }); + } - /** + /** * 5. 获取打印电脑列表 - * @param {Object} data {} */ - async getComputer() { - const { ctx } = this; - // TODO: 打印电脑状态需根据实际业务实现 - const warehouseId = ctx.user.store_id; - const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } }); + async getComputer() { + const { ctx } = this; + // TODO: 打印电脑状态需根据实际业务实现 + const warehouseId = ctx.user.store_id; + const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } }); - return this.success('success', { data: list, code: 0 }); - } + return this.success('success', { data: list, code: 0 }); + } - /** + /** * 7. 获取打印电脑的所有打印机 * @param {Object} data { id } */ - async getComputerPrinter(data) { - const { ctx } = this; - const { id } = data; - if (!id) return this.fail('参数错误', 1001); - const printerListResult = await this.app.redis.get("printer").get(`printer:${id}:printerList`); - console.log("getComputerPrinter printerListResult", printerListResult); - const printerList = JSON.parse(printerListResult); - let printers = []; - if(!printerList ||!printerList.data || printerList.data.length === 0){ - printers = []; - } else { - printers = printerList.data; - } - return this.success('success', { data: printers, code: 0 }); + async getComputerPrinter(data) { + const { id } = data; + if (!id) return this.fail('参数错误', 1001); + const printerListResult = await this.app.redis.get('printer').get(`printer:${id}:printerList`); + const printerList = JSON.parse(printerListResult); + let printers = []; + if (!printerList || !printerList.data || printerList.data.length === 0) { + printers = []; + } else { + printers = printerList.data; + } + return this.success('success', { data: printers, code: 0 }); + } + + /** + * 8. 保存打印台的默认打印机与快递绑定打印机配置。 + * @param {Object} data 请求参数。 + * @param {string} data.defaultPrinter 默认打印机名称,必填。 + * @param {Array} data.express 快递绑定数组,必填。 + * @param {number|string} data.print_station_id 打印台 ID,必填。 + * @return {Promise} 保存结果。 + */ + async savePrinters(data) { + const { ctx } = this; + const { defaultPrinter, express, print_station_id } = data; + if (!defaultPrinter || !Array.isArray(express) || !print_station_id) return this.fail('参数错误', { code: 1001 }); + + const item = await ctx.model.PrintStations.findOne({ + where: { + id: print_station_id, + deleted: 0, + }, + }); + if (!item) return this.fail('打印台不存在', { code: 1002 }); + + const expressBindPrinter = express.map(expressItem => { + const sourceItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; + return { + printer_name: sourceItem.printer_name || sourceItem.name || defaultPrinter, + express_code: sourceItem.express_code || sourceItem.express_id, + }; + }); + + const rawSubjectConfig = item.subject_config && typeof item.subject_config === 'object' && !Array.isArray(item.subject_config) + ? item.subject_config + : {}; + const mergedSubjectConfig = { + ...rawSubjectConfig, + express_bind_printer: expressBindPrinter, + }; + + try { + item.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(mergedSubjectConfig); + } catch (error) { + return this.fail(error.message, { code: 1001 }); } - /** - * 8. 保存打印台的快递-打印机绑定 - * @param {Object} data { default, express } - */ - async savePrinters(data) { - const { ctx } = this; - const { defaultPrinter, express } = data; - // express: [{ express_id, name }] - if (!defaultPrinter || !Array.isArray(express)) return this.fail('参数错误', 1001); - // TODO: 需根据打印台ID、快递ID等实际业务调整 - // 这里只做示例保存,实际应覆盖原有绑定 - // 1. 保存默认打印机 - // 2. 保存 express 打印机绑定 - // 3. 需用 PrintStationExpress model - // 示例:批量保存 - for (const item of express) { - await ctx.model.PrintStationExpress.upsert({ - print_station_id: data.print_station_id, // 需传入 - express_id: item.express_id, - express_name: item.name, - printer_name: item.name, - is_default: item.name === defaultPrinter ? 1 : 0, - creator_id: ctx.user?.id || '', - creator_name: ctx.user?.name || '', - create_at: new Date(), - update_at: new Date(), - deleted: 0, - }); + item.default_printer_name = defaultPrinter; + item.update_at = new Date(); + await item.save(); + + return this.success('success', { data: null, code: 0 }); + } + + async tryUnbindCartAfterPrintComplete(waveId, warehouseId) { + const { ctx } = this; + const resolvedWarehouseId = Number(warehouseId || ctx.user && ctx.user.store_id || 0); + let taskId = 0; + let waveType = 0; + try { + const waveBatch = await ctx.model.WaveBatch.findOne({ where: { wave_id: waveId }, attributes: [ 'wave_type' ], raw: true }); + if (!waveBatch) return; + waveType = Number(waveBatch.wave_type); + if (![ 1, 2 ].includes(waveType)) return; + const taskWaveRows = await ctx.model.query( + 'SELECT task_id FROM wms_wave_pick_task_wave WHERE wave_id = :waveId AND warehouse_id = :warehouseId LIMIT 1', + { replacements: { waveId, warehouseId: resolvedWarehouseId }, type: ctx.model.QueryTypes.SELECT } + ); + const taskWave = Array.isArray(taskWaveRows) && taskWaveRows.length > 0 ? taskWaveRows[0] : null; + if (!taskWave || !taskWave.task_id) return; + taskId = Number(taskWave.task_id); + if (!taskId) return; + + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + this.ctx.logger.warn('[print.unbindCart] OrderDeliveryFactory 不可用,跳过检查'); + return; + } + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(resolvedWarehouseId); + + // 查询任务主表:团购模式校验、任务结束状态兜底解绑均需要 + const taskRows = await ctx.model.query( + 'SELECT pick_mode, status FROM wms_wave_pick_task WHERE id = :taskId LIMIT 1', + { replacements: { taskId }, type: ctx.model.QueryTypes.SELECT } + ); + const task = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + if (!task) return; + const pickMode = Number(task.pick_mode || 0); + const taskStatus = Number(task.status || 0); + + // 拦截订单不可打印(打印清单剔除 + 打印回执更新排除拦截订单),print_status 永远停留在 none。 + // 解绑判定的「未打印」统计必须排除拦截订单,与打印剔除、复核打印统计口径保持一致, + // 避免波次内存在拦截订单时车永远无法解绑。 + const nonInterceptedWhere = { [ctx.model.Sequelize.Op.in]: [ INTERCEPT_STATUS_NONE, null ] }; + + const unbindCart = async reason => { + const operator = this.getPrintOrderOperationOperator(); + const unbindUserId = operator.id || null; + await ctx.model.query( + 'UPDATE wms_pick_task_cart_binding SET is_active = 0, unbind_user_id = :unbindUserId, unbind_time = NOW(), update_time = NOW() WHERE task_id = :taskId AND is_active = 1', + { replacements: { taskId, unbindUserId } } + ); + this.ctx.logger.info('[print.unbindCart] 车标解绑成功', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', reason, unbindUserId }); + }; + + let totalOrderCount = 0; + let unprintedCount = 0; + + if (waveType === 1) { + // 团购波次:仅团购拣货模式(pick_mode=1 小团购 / pick_mode=5 大团购)参与解绑判断 + if (![ 1, 5 ].includes(pickMode)) return; + + // 团购任务订单不写入 wms_wave_pick_task_order,改为按任务关联的全部波次统计: + // 任务下所有波次的非拦截订单均已打印时才解绑 + const taskWaveIdRows = await ctx.model.query( + 'SELECT DISTINCT wave_id FROM wms_wave_pick_task_wave WHERE task_id = :taskId AND warehouse_id = :warehouseId', + { replacements: { taskId, warehouseId: resolvedWarehouseId }, type: ctx.model.QueryTypes.SELECT } + ); + const waveIds = (Array.isArray(taskWaveIdRows) ? taskWaveIdRows : []) + .map(r => Number(r && r.wave_id)) + .filter(id => id > 0); + if (waveIds.length === 0) { + // 任务无波次关联:仅任务已结束(待复核/完成/取消)时兜底解绑,避免车残留 + if ([ 2, 3, 9 ].includes(taskStatus)) await unbindCart('task_no_wave_ended'); + return; } - return this.success('success', { data: null, code: 0 }); + unprintedCount = await orderDeliveryModel.count({ + where: { + warehouse_id: resolvedWarehouseId, + wave_id: { [ctx.model.Sequelize.Op.in]: waveIds }, + print_status: 'none', + intercept_status: nonInterceptedWhere, + }, + }); + totalOrderCount = await orderDeliveryModel.count({ + where: { + warehouse_id: resolvedWarehouseId, + wave_id: { [ctx.model.Sequelize.Op.in]: waveIds }, + intercept_status: nonInterceptedWhere, + }, + }); + } else { + // 散单波次:按任务订单维度检查,任务下所有非拦截订单均已打印时才解绑 + const taskOrders = await ctx.model.query( + 'SELECT DISTINCT order_id FROM wms_wave_pick_task_order WHERE task_id = :taskId', + { replacements: { taskId }, type: ctx.model.QueryTypes.SELECT } + ); + const orderIds = (Array.isArray(taskOrders) ? taskOrders : []).map(r => Number(r && r.order_id)).filter(id => id > 0); + if (orderIds.length === 0) { + // 任务订单关联为空(如拦截订单被提交拣货移除):任务已结束时兜底解绑,避免车残留 + if ([ 2, 3, 9 ].includes(taskStatus)) await unbindCart('task_no_orders_ended'); + return; + } + unprintedCount = await orderDeliveryModel.count({ + where: { + id: { [ctx.model.Sequelize.Op.in]: orderIds }, + print_status: 'none', + intercept_status: nonInterceptedWhere, + }, + }); + totalOrderCount = await orderDeliveryModel.count({ + where: { + id: { [ctx.model.Sequelize.Op.in]: orderIds }, + intercept_status: nonInterceptedWhere, + }, + }); + } + + if (unprintedCount > 0) { + this.ctx.logger.info('[print.unbindCart] 尚有未打印订单,跳过解绑', { waveId, warehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', totalOrders: totalOrderCount, unprintedCount }); + return; + } + + await unbindCart('all_printed'); + } catch (error) { + this.ctx.logger.error('[print.unbindCart] 解绑车标检查异常', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, error: error && error.message ? error.message : String(error) }); } + } } module.exports = PrintService; diff --git a/app/service/systemMethods/printComputer.js b/app/service/systemMethods/printComputer.js new file mode 100644 index 0000000..7aeae5e --- /dev/null +++ b/app/service/systemMethods/printComputer.js @@ -0,0 +1,81 @@ +'use strict'; + +const MainService = require('../main'); + +class PrintComputerService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = '*'; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 打印电脑列表。 + * @param {Object} data 查询参数 { pagination, where } + * @return {Promise} 列表数据与分页信息 + */ + async list(data) { + try { + const result = await this.service.systems.printComputer.list(data || {}); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 更新打印电脑。 + * @param {Object} data { id, name? } + * @return {Promise} 更新后的电脑记录 + */ + async update(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('更新成功', await this.service.systems.printComputer.update(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 设置录制电脑(会先取消同仓库下其他录制电脑)。 + * @param {Object} data { id, recording_size_value, recording_size_unit, recording_directory } + * @return {Promise} 设置结果 + */ + async setRecording(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('设置录制成功', await this.service.systems.printComputer.setRecording(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 取消录制电脑。 + * @param {Object} data { id } + * @return {Promise} 取消结果 + */ + async cancelRecording(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('取消录制成功', await this.service.systems.printComputer.cancelRecording(parseInt(id))); + } catch (e) { return this.fail(e.message); } + } + + /** + * 软删除打印电脑。 + * @param {Object} data { id } + * @return {Promise} 删除结果 + */ + async delete(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + await this.service.systems.printComputer.delete(parseInt(id)); + return this.success('删除成功'); + } catch (e) { return this.fail(e.message); } + } +} + +module.exports = PrintComputerService; diff --git a/app/service/systemMethods/report.js b/app/service/systemMethods/report.js new file mode 100644 index 0000000..8ee4078 --- /dev/null +++ b/app/service/systemMethods/report.js @@ -0,0 +1,266 @@ +'use strict'; + +const MainService = require('../main'); +const ReportDeliveryPlanMethodService = require('./report/deliveryPlan'); +const ReportDeliveryLogMethodService = require('./report/deliveryLog'); +const ReportDefinitionMethodService = require('./report/definition'); + +const REPORT_GENERATE_TASK_CACHE_KEY_PREFIX = 'report_generate_task_'; +const REPORT_GENERATE_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:report(配置驱动通用报表接口包装层)。 + * 仅做出口包装与导出任务编排,业务逻辑下沉 systems/report。 + */ +class ReportMethodService extends MainService { + /** + * 初始化 report 方法层:配置免鉴权清单,并挂载子目录服务实例。 + * report.js 与 report/ 子目录同名并存时,egg 会把子目录服务作为静态属性挂在类构造器上, + * ctx 层实例化后静态属性不可见,需按 storeWarehouse 同款模式在实例上显式挂载, + * 保证 /system 网关可按 report.deliveryPlan.* / report.deliveryLog.* 路径解析。 + * @param {Egg.Context} ctx Egg 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'generate,generateTaskProgress'; + const _noNeedLog = 'generate,generateTaskProgress'; + const _noNeedAuth = 'generate,generateTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + // 显式挂载子目录服务实例(与 storeWarehouse.js 挂载 store/warehouse 的模式一致) + this.deliveryPlan = new ReportDeliveryPlanMethodService(ctx); + this.deliveryLog = new ReportDeliveryLogMethodService(ctx); + this.definition = new ReportDefinitionMethodService(ctx); + } + + /** + * 提交报表导出异步任务(手动导出)。 + * warehouse_id 由服务端从登录上下文自动注入,前端无需传递。 + * @param {Object} data 请求体 + * @param {number} data.report_id 报表定义ID(必填,兼容 reportId) + * @param {number} [data.reportId] 报表定义ID(驼峰写法,优先级高于 report_id) + * @param {number} [data.store_id] 货主ID(可选,货主维度报表时传入) + * @param {Object} [data.params] 查询器业务参数(如 bizDate) + * @return {Promise} 统一 success 包装,data 为导出任务信息 + */ + async generate(data = {}) { + const { service } = this; + const { + report_id: reportIdSnake, + reportId: reportIdCamel, + store_id: storeIdSnake, + storeId: storeIdCamel, + params = {}, + } = data; + + const reportId = Number(reportIdCamel ?? reportIdSnake ?? 0) || 0; + if (!Number.isInteger(reportId) || reportId <= 0) { + return this.fail('报表ID report_id 必须为正整数'); + } + + // 服务端注入仓库维度(禁止前端传 warehouse_id) + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id) || 0; + const storeId = Number(storeIdCamel ?? storeIdSnake ?? 0) || 0; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.report.generate({ + reportId, + storeId: storeId > 0 ? storeId : null, + warehouseId, + params, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询报表导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async generateTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + // ==================== 导出任务辅助方法(局部实现,不新增公共代码) ==================== + + /** + * 生成报表导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `report_generate_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化导出任务ID。 + * @param {Object} data 请求体 + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${REPORT_GENERATE_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, REPORT_GENERATE_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[report.generate] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[report.generateTaskProgress] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } +} + +module.exports = ReportMethodService; diff --git a/app/service/systemMethods/report/definition.js b/app/service/systemMethods/report/definition.js new file mode 100644 index 0000000..e4c71ba --- /dev/null +++ b/app/service/systemMethods/report/definition.js @@ -0,0 +1,137 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:report.definition(报表定义管理接口包装层)。 + * 仅做出口包装与参数解构,业务逻辑下沉 systems/report。 + */ +class ReportDefinitionMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // typeList 为只读公共元数据:免权限/免鉴权/免日志(与 report 模块免权限只读接口惯例一致),仍要求登录; + // save/list/delete 属定义管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用, + // 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围 + const _noNeedRight = 'typeList'; + const _noNeedLog = 'typeList'; + const _noNeedAuth = 'typeList'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询报表类型注册清单(内置查询器 + 标题/描述/窗口参数 + 全量字段清单)。 + * 免权限只读(仅登录),供前端报表配置页渲染类型下拉与字段勾选。 + * @param {Object} data 请求体(无必填参数,兼容空对象) + * @return {Promise} 统一 success 包装,data 为 { list: Array } 注册类型清单 + */ + async typeList(data = {}) { + void data; + const { service } = this; + const types = await service.systems.report.listRegisteredTypes(); + return this.success('ok', { + list: types, + }); + } + + /** + * 新增/更新报表定义(按 id upsert:未传 id 视为新增,未传字段不覆盖)。 + * @param {Object} data 请求体 + * @param {number} [data.id] 报表定义ID(正整数;不传视为新增) + * @param {string} data.name 报表名称(必填,≤100) + * @param {string} data.type 报表类型(注册方法 key,如 stockFlow;新增必填) + * @param {string} data.file_name 导出文件名模板(支持 {date}/{time}/{datetime}/{timestamp};新增必填,≤200,兼容 fileName) + * @param {Array} data.fields 勾选字段 key 数组(新增必填,须为该类型注册字段子集) + * @param {number} [data.is_enabled] 是否启用(0/1) + * @param {string} [data.remark] 备注(≤500) + * @return {Promise} 统一 success 包装,data 为保存后的报表定义视图 + */ + async save(data = {}) { + const { service } = this; + const { + id, + name, + type, + file_name: fileNameSnake, + fileName: fileNameCamel, + fields, + is_enabled: isEnabled, + remark, + } = data; + + // 仅附加入参中存在的字段(undefined 不进入参数对象),保持「未传不覆盖」语义 + const saveArgs = { id, name, type }; + const normalizedFileName = fileNameCamel !== undefined ? fileNameCamel : fileNameSnake; + if (normalizedFileName !== undefined) { + saveArgs.fileName = normalizedFileName; + } + if (fields !== undefined) { + saveArgs.fields = fields; + } + if (isEnabled !== undefined) { + saveArgs.isEnabled = isEnabled; + } + if (remark !== undefined) { + saveArgs.remark = remark; + } + + try { + const result = await service.systems.report.saveDefinition(saveArgs); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '报表定义保存失败'); + } + } + + /** + * 分页查询报表定义列表。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(name 模糊关键字、type/is_enabled 精确) + * @param {Object} [data.pagination] 分页 { page, pageSize } + * @param {Object} [data.sort] 排序 { sortField, sortOrder }(白名单:id/name/type/is_enabled/created_at/updated_at) + * @return {Promise} 统一 success 包装,data 为 { list, total, page, pageSize } + */ + async list(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + name: nameKeyword, + type, + is_enabled: isEnabled, + } = whereValue; + const { pagination = {}, sort = {} } = data; + + try { + const result = await service.systems.report.listDefinitions({ + nameKeyword, + type, + isEnabled, + pagination, + sort, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '报表定义列表查询失败'); + } + } + + /** + * 软删除报表定义(存在启用中的投递计划引用时拦截)。 + * @param {Object} data 请求体 + * @param {number} data.id 报表定义ID(必填,正整数) + * @return {Promise} 统一 success 包装,data 为 { id, deleted } + */ + async delete(data = {}) { + const { service } = this; + const { id } = data; + + try { + const result = await service.systems.report.deleteDefinition({ id }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '报表定义删除失败'); + } + } +} + +module.exports = ReportDefinitionMethodService; diff --git a/app/service/systemMethods/report/deliveryLog.js b/app/service/systemMethods/report/deliveryLog.js new file mode 100644 index 0000000..e9f0179 --- /dev/null +++ b/app/service/systemMethods/report/deliveryLog.js @@ -0,0 +1,50 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:report.deliveryLog(货主报表投递记录审计查询接口包装层)。 + * 仅做出口包装与参数解构,业务逻辑下沉 systems/reportDelivery。 + */ +class ReportDeliveryLogMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // 审计查询属于管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用, + // 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围 + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 分页查询投递记录(审计)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(store_id/report_id/status) + * @param {Object} [data.pagination] 分页 { page, pageSize } + * @param {Object} [data.sort] 排序 { sortField, sortOrder } + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + store_id: storeId, + report_id: reportId, + status, + } = whereValue; + const { pagination = {}, sort = {} } = data; + + const result = await service.systems.reportDelivery.listLogs({ + storeId, + reportId, + status, + pagination, + sort, + }); + return this.success('ok', result); + } +} + +module.exports = ReportDeliveryLogMethodService; diff --git a/app/service/systemMethods/report/deliveryPlan.js b/app/service/systemMethods/report/deliveryPlan.js new file mode 100644 index 0000000..e75a63b --- /dev/null +++ b/app/service/systemMethods/report/deliveryPlan.js @@ -0,0 +1,130 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:report.deliveryPlan(货主报表投递计划接口包装层)。 + * 仅做出口包装与参数解构,业务逻辑下沉 systems/reportDelivery。 + */ +class ReportDeliveryPlanMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // 计划管理属于管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用, + // 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围 + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 新增/更新投递计划(货主+报表定义ID唯一,存在则更新)。 + * @param {Object} data 请求体 + * @param {number} data.store_id 货主ID(必填) + * @param {number} data.report_id 报表定义ID(必填,兼容 reportId) + * @param {Array} data.schedule_times 每日投递时间点数组(HH:mm,自动去重排序) + * @param {string} [data.channel='inbox'] 投递渠道(仅支持 inbox) + * @param {number} [data.late_grace_minutes=60] 补投宽限分钟(0-1440) + * @param {string|null} [data.name] 计划名称(可空;未传不覆盖,null/空串清空,非空 trim ≤100) + * @param {string} [data.remark] 备注 + * @param {string} [data.notify_template] 文本通知模板(≤500,白名单标签 {time}/{url}/{report_name}/{biz_date}) + * @param {Array} [data.notify_group_ids] 通知群ID数组(wms_inbox_group.id,≤20) + * @param {Array} [data.notify_member_ids] 通知成员ID数组(外部IM用户ID,≤100) + * @return {Promise} 统一 success 包装 + */ + async save(data = {}) { + const { service } = this; + const { + store_id: storeId, + report_id: reportIdSnake, + reportId: reportIdCamel, + schedule_times: scheduleTimes, + channel, + late_grace_minutes: lateGraceMinutes, + name, + remark, + notify_template: notifyTemplate, + notify_group_ids: notifyGroupIds, + notify_member_ids: notifyMemberIds, + } = data; + + // 基础参数解构透传;通知类参数仅在入参存在时附加, + // 保持旧调用形状与既有回归断言一致(undefined 不进入参数对象) + const saveArgs = { + storeId, + reportId: reportIdCamel !== undefined ? reportIdCamel : reportIdSnake, + scheduleTimes, + channel, + lateGraceMinutes, + remark, + }; + if (name !== undefined) { + saveArgs.name = name; + } + if (notifyTemplate !== undefined) { + saveArgs.notifyTemplate = notifyTemplate; + } + if (notifyGroupIds !== undefined) { + saveArgs.notifyGroupIds = notifyGroupIds; + } + if (notifyMemberIds !== undefined) { + saveArgs.notifyMemberIds = notifyMemberIds; + } + + const result = await service.systems.reportDelivery.savePlan(saveArgs); + return this.success('ok', result); + } + + /** + * 快速复制投递计划到其他货主(目标已存在相同报表定义计划时跳过,不覆盖不报错)。 + * @param {Object} data 请求体 + * @param {number} data.id 源计划ID(必填,正整数) + * @param {Array} data.store_ids 目标货主ID数组(必填,兼容 storeIds 驼峰) + * @return {Promise} 统一 success 包装,data={ created, skipped } + */ + async copy(data = {}) { + const { service } = this; + const { + id, + store_ids: storeIdsSnake, + storeIds: storeIdsCamel, + } = data; + + // 兼容 storeIds 驼峰入参,优先取驼峰形式,保持与 save 的 reportId 兼容口径一致 + const storeIds = storeIdsCamel !== undefined ? storeIdsCamel : storeIdsSnake; + + const result = await service.systems.reportDelivery.copyPlan({ id, storeIds }); + return this.success('ok', result); + } + + /** + * 分页查询投递计划列表。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(store_id/report_id/enabled) + * @param {Object} [data.pagination] 分页 { page, pageSize } + * @param {Object} [data.sort] 排序 { sortField, sortOrder } + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + store_id: storeId, + report_id: reportId, + enabled, + } = whereValue; + const { pagination = {}, sort = {} } = data; + + const result = await service.systems.reportDelivery.listPlans({ + storeId, + reportId, + enabled, + pagination, + sort, + }); + return this.success('ok', result); + } +} + +module.exports = ReportDeliveryPlanMethodService; diff --git a/app/service/systemMethods/returnReceived.js b/app/service/systemMethods/returnReceived.js new file mode 100644 index 0000000..54c8a0e --- /dev/null +++ b/app/service/systemMethods/returnReceived.js @@ -0,0 +1,373 @@ +'use strict'; + +const MainService = require('../main'); + +const RETURN_RECEIVED_EXPORT_TASK_CACHE_KEY_PREFIX = 'return_received_export_task_'; +const RETURN_RECEIVED_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:returnReceived(退回收到模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.return_received 中。 + */ +class ReturnReceivedMethodService extends MainService { + constructor(ctx) { + super(ctx); + // 免登录方法列表:空(全部需要登录) + const _noNeedLogin = ''; + // 免权限方法列表:detail 复用列表权限(仅登录 + 仓库隔离校验),其余走 API 权限校验 + const _noNeedRight = 'detail'; + // 免日志方法列表:空(全部记录日志) + const _noNeedLog = ''; + // 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期) + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用退回收到业务服务,并捕获业务错误码。 + * + * @param {Function} fn 业务调用函数。 + * @param {string} fallbackMessage 兜底错误文案。 + * @return {Promise} 统一 success/fail 包装。 + */ + async _call(fn, fallbackMessage) { + try { + const result = await fn(); + return this.success('ok', result); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || fallbackMessage, {}, code); + } + this.ctx.logger.error(`[returnReceived] ${fallbackMessage}: ${error && error.message ? error.message : error}`); + return this.fail('服务器内部错误', {}, 500); + } + } + + /** + * 扫码登记退回包裹(增)。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 退回收件运单号。 + * @param {string} [data.remark] 备注。 + * @param {number|string} [data.return_received_task_id] 收件任务ID,不传默认 1(系统预设「历史收件」); + * 兼容旧字段 receiving_task_id(新字段优先)。 + * @return {Promise} 统一 success 包装。 + */ + async create(data = {}) { + const { waybill_code, remark, return_received_task_id, receiving_task_id } = data; + // 新字段 return_received_task_id 优先,兼容旧字段 receiving_task_id + const taskId = return_received_task_id !== undefined && return_received_task_id !== null && return_received_task_id !== '' + ? return_received_task_id + : receiving_task_id; + return this._call(() => this.service.systems.returnReceived.create({ waybill_code, remark, return_received_task_id: taskId }), '扫码登记失败'); + } + + /** + * 分页查询退回收到登记列表(查,仓库隔离自动注入)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + return this._call(() => service.systems.returnReceived.list(enforcedWhere, pagination, sort), '查询列表失败'); + } + + /** + * 查询单条退回收到登记详情(查)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录主键ID。 + * @return {Promise} 统一 success 包装。 + */ + async detail(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnReceived.detail(Number(id)), '查询详情失败'); + } + + /** + * 删除单条退回收到登记记录(删)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录主键ID。 + * @return {Promise} 统一 success 包装。 + */ + async delete(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnReceived.delete(Number(id)), '删除失败'); + } + + /** + * 提交退回收到登记列表导出任务(异步任务模式,与 returnUnpack.export 口径一致)。 + * 入参 where/sort 与 list 完全一致;提交后立即返回 task_id, + * 后台异步生成单 Sheet Excel(退回收到登记列表)并上传, + * 通过 exportTaskProgress 查询进度与下载链接。 + * warehouse_id 由服务端从 ctx.user.store_id 注入,禁止前端传入。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.where] 筛选条件(与 list 的 where 语义一致)。 + * @param {Object} [data.sort] 排序参数(与 list 的 sort 语义一致)。 + * @return {Promise} 统一成功包装响应(含 task_id/status/progress 等任务信息)。 + */ + async export(data = {}) { + const { service } = this; + const { sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + const taskId = this.generateExportTaskId(warehouseId); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '退回收到导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '退回收到导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.returnReceived.exportList({ + where: enforcedWhere, + sort, + warehouseId, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount, + total_count: safeProgress.totalCount, + message: safeProgress.message || '退回收到导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '退回收到导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '退回收到导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询退回收到导出任务进度(与 order.exportTaskProgress 口径一致)。 + * + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一成功包装响应 + * (含 task_id/status/progress/current_count/total_count/message/error/download_url/update_time)。 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成退回收到导出任务ID。 + * @param {number|string} [warehouseId=''] 仓库ID(缺省兜底取当前上下文 store_id)。 + * @return {string} 导出任务ID。 + */ + generateExportTaskId(warehouseId = '') { + const normalizedWarehouseId = warehouseId || this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `return_received_export_${normalizedWarehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化退回收到导出任务ID。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取退回收到导出任务缓存键。 + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${RETURN_RECEIVED_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入退回收到导出任务进度缓存(Redis TTL 30 分钟)。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态载荷。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, RETURN_RECEIVED_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[returnReceived.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取退回收到导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存,未命中返回 null。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[returnReceived.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } +} + +module.exports = ReturnReceivedMethodService; diff --git a/app/service/systemMethods/returnReceivedTask.js b/app/service/systemMethods/returnReceivedTask.js new file mode 100644 index 0000000..b93432e --- /dev/null +++ b/app/service/systemMethods/returnReceivedTask.js @@ -0,0 +1,166 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 系统方法层:returnReceivedTask(收件任务模块接口包装层,退回收件任务分组)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑, + * 将具体业务逻辑下沉到 systems.returnReceivedTask 中。 + * + * 权限口径:create/delete 需要登录、免 API 权限校验(无需 wms_permission 记录); + * 仓库与创建人均由服务端从登录上下文自动注入,禁止前端传入。 + */ +class ReturnReceivedTaskMethodService extends MainService { + constructor(ctx) { + super(ctx); + // 免登录方法列表:空(全部需要登录) + const _noNeedLogin = ''; + // 免权限方法列表:create/delete/batchDelete/list 免 API 权限校验(仅需登录) + const _noNeedRight = 'create,delete,batchDelete,list'; + // 免日志方法列表:list(查询类不记录操作日志) + const _noNeedLog = 'list'; + // 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期) + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用收件任务业务服务,并捕获业务错误码。 + * + * @param {Function} fn 业务调用函数。 + * @param {string} fallbackMessage 兜底错误文案。 + * @return {Promise} 统一 success/fail 包装。 + */ + async _call(fn, fallbackMessage) { + try { + const result = await fn(); + return this.success('ok', result); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || fallbackMessage, {}, code); + } + this.ctx.logger.error(`[returnReceivedTask] ${fallbackMessage}: ${error && error.message ? error.message : error}`); + return this.fail('服务器内部错误', {}, 500); + } + } + + /** + * 创建收件任务(增)。 + * warehouse_id / creator_id / creator_name 由服务端从当前登录上下文自动注入,前端无需传递; + * 批次号一律由服务端自动生成(RT+YYYYMMDD+5位序号,参考波次号取号机制),不接收外部输入。 + * + * @param {Object} data 请求体。 + * @param {string} [data.title] 标题(任务名称)。 + * @return {Promise} 统一 success 包装,返回新建的收件任务行。 + */ + async create(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; + const { title } = data || {}; + + return this._call( + () => this.service.systems.returnReceivedTask.create({ + warehouseId, + title, + creatorId, + creatorName, + }), + '创建收件任务失败' + ); + } + + /** + * 分页查询收件任务列表(查)。 + * warehouse_id 由服务端从当前登录上下文自动注入(含系统级任务 warehouse_id=0),禁止前端传入。 + * 搜索关键词 where.quickWhere:在 title(标题)/batch_no(编号)/creator_name(创建人)三个字段中模糊匹配 + * (OR 关系);title/batch_no/creator_name 也支持 {operator,value} 标准结构(like/eq/in 等)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.where] 筛选条件(含 has_register:是否有登记,true/false)。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.sort] 排序参数(sortField: id/batch_no/created_at/updated_at,默认 id desc)。 + * @return {Promise} 统一 success 包装,返回 { list, pagination }。 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + // 仓库隔离:由服务端从当前上下文自动注入(含系统级任务 warehouse_id=0),禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'in', value: [ 0, warehouseId ] }; + } + + return this._call( + () => service.systems.returnReceivedTask.list(enforcedWhere, pagination, sort, warehouseId), + '查询列表失败' + ); + } + + /** + * 批量删除收件任务(删,硬删除)。 + * 逐条分流:不存在/系统预设(id=1)/非本仓库/已有收件登记的任务计入 skipped_ids 不报错; + * 其余硬删除并清理缓存。warehouse_id 由服务端从当前登录上下文自动注入,前端无需传递。 + * + * @param {Object} data 请求体。 + * @param {Array|number} data.ids 收件任务ID(数组或单值,单次上限 200)。 + * @return {Promise} 统一 success 包装,返回 + * { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。 + */ + async batchDelete(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { ids } = data || {}; + + return this._call( + () => this.service.systems.returnReceivedTask.batchDelete({ warehouseId, ids }), + '批量删除收件任务失败' + ); + } + + /** + * 删除收件任务(删,硬删除)。 + * 兼容两种入参: + * - ids(数组或单值):批量删除,逐条分流,不存在/系统预设/非本仓库/已有登记的任务 + * 计入 skipped_ids 不报错,返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids }; + * - id(单值):单值删除,不满足条件抛 404/409。 + * warehouse_id 由服务端从当前登录上下文自动注入,前端无需传递。 + * + * @param {Object} data 请求体。 + * @param {Array|number} [data.ids] 收件任务ID(数组或单值,单次上限 200,优先于 id)。 + * @param {number|string} [data.id] 收件任务ID(单值删除)。 + * @return {Promise} 统一包装:单值删除返回 { id, deleted }; + * 批量删除返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。 + */ + async delete(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, ids } = data || {}; + + // 批量删除:传 ids 时走批量分流语义 + if (ids !== undefined && ids !== null) { + return this._call( + () => this.service.systems.returnReceivedTask.batchDelete({ warehouseId, ids }), + '批量删除收件任务失败' + ); + } + + return this._call( + () => this.service.systems.returnReceivedTask.delete(id, warehouseId), + '删除收件任务失败' + ); + } +} + +module.exports = ReturnReceivedTaskMethodService; diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js new file mode 100644 index 0000000..c769e00 --- /dev/null +++ b/app/service/systemMethods/returnUnpack.js @@ -0,0 +1,556 @@ +'use strict'; + +const MainService = require('../main'); + +const RETURN_UNPACK_EXPORT_TASK_CACHE_KEY_PREFIX = 'return_unpack_export_task_'; +const RETURN_UNPACK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:returnUnpack(退回拆包模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.return_unpack 中。 + */ +class ReturnUnpackMethodService extends MainService { + constructor(ctx) { + super(ctx); + // 免登录方法列表:空(全部需要登录) + const _noNeedLogin = ''; + // 免权限方法列表:export/exportTaskProgress 免权限(异步任务模式,与 order.export 口径一致,无 wms_permission 记录); + // 其余走 API 权限校验(detail 走固定 ID 548 客服授权,与设计一致) + const _noNeedRight = 'export,exportTaskProgress'; + // 免日志方法列表:导出与进度查询不记录操作日志(与订单导出口径一致) + const _noNeedLog = 'export,exportTaskProgress'; + // 免鉴权(仓库有效期检查)方法列表:导出与进度查询不检查仓库有效期(与订单导出口径一致) + const _noNeedAuth = 'export,exportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用退回拆包业务服务,并捕获业务错误码。 + * + * @param {Function} fn 业务调用函数。 + * @param {string} fallbackMessage 兜底错误文案。 + * @return {Promise} 统一 success/fail 包装。 + */ + async _call(fn, fallbackMessage) { + try { + const result = await fn(); + return this.success('ok', result); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || fallbackMessage, {}, code); + } + this.ctx.logger.error(`[returnUnpack] ${fallbackMessage}: ${error && error.message ? error.message : error}`); + return this.fail('服务器内部错误', {}, 500); + } + } + + /** + * 开拆包单(增)。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 拆包的运单号。 + * @param {Array} [data.camera_ids] 摄像头ID列表。 + * @param {number} [data.return_received_id] 关联退回收到单ID。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async create(data = {}) { + const { waybill_code, camera_ids, return_received_id, remark } = data; + return this._call( + () => this.service.systems.returnUnpack.create({ waybill_code, camera_ids, return_received_id, remark }), + '开拆包单失败' + ); + } + + /** + * 运单批量转入退件登记(退回拆包,批量)。 + * 新方法需鉴权 + 需登录 + 记录日志,不在任何免检清单内。 + * + * @param {Object} data 请求体。 + * @param {number|Array} data.ids 运单表主键ID(wms_order_express.id,单个数值或数组,去重后上限 200)。 + * @return {Promise} 统一 success 包装,data 含 total/success_count/failed_count/success/failed。 + */ + async transferByWaybills(data = {}) { + const { ids } = data; + return this._call( + () => this.service.systems.returnUnpack.transferByWaybills({ ids }), + '运单批量转入退件登记失败' + ); + } + + /** + * 配送订单批量转退回拆包单。 + * 新方法需鉴权 + 需登录 + 记录日志,不在任何免检清单内。 + * + * @param {Object} data 请求体。 + * @param {number|Array} data.ids 订单表主键ID(单个数值或数组,去重后上限 200)。 + * @return {Promise} 统一 success 包装,data 含 + * total/success_count/skipped_count/failed_count/success/skipped/failed。 + */ + async transferByOrders(data = {}) { + const { ids } = data; + return this._call( + () => this.service.systems.returnUnpack.transferByOrders({ ids }), + '配送订单批量转退回拆包单失败' + ); + } + + /** + * 录明细(增)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id),为空时按未知商品登记(is_recognized=0)。 + * @param {string} [data.barcode] 扫描条码(仅作记录,不参与商品匹配)。 + * @param {number} [data.quantity] 数量。 + * @param {string} [data.product_status] 产品状态 normal/damaged。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async addDetail(data = {}) { + const { id, stock_id, barcode, quantity, product_status, remark } = data; + return this._call( + () => this.service.systems.returnUnpack.addDetail({ id, stock_id, barcode, quantity, product_status, remark }), + '录明细失败' + ); + } + + /** + * 更新明细(改,仅数量/备注)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @param {number} data.detail_id 明细ID。 + * @param {number} [data.quantity] 数量。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async updateDetail(data = {}) { + const { id, detail_id, quantity, remark } = data; + return this._call( + () => this.service.systems.returnUnpack.updateDetail({ id, detail_id, quantity, remark }), + '更新明细失败' + ); + } + + /** + * 移除明细(删)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @param {number} data.detail_id 明细ID。 + * @return {Promise} 统一 success 包装。 + */ + async removeDetail(data = {}) { + const { id, detail_id } = data; + return this._call( + () => this.service.systems.returnUnpack.removeDetail({ id, detail_id }), + '移除明细失败' + ); + } + + /** + * 取消拆包单(删,仅未完成状态)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async cancel(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.cancel({ id }), '取消拆包单失败'); + } + + /** + * 提交确认(改,转 completed 终态)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async submit(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.submit({ id }), '提交确认失败'); + } + + /** + * 强制重新录制拆包视频(改,参考 order.packing.forceRecord)。 + * 校验仓库录制电脑在线后重置视频状态并推送打印服务 /record/force 触发重新录制。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async forceRecord(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.forceRecord({ id }), '强制录制失败'); + } + + /** + * 分页查询拆包单列表(查,仓库隔离自动注入)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + return this._call( + () => service.systems.returnUnpack.list(enforcedWhere, pagination, sort), + '查询列表失败' + ); + } + + /** + * 分页查询拆包明细列表(查,仓库隔离自动注入)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async detailList(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + return this._call( + () => service.systems.returnUnpack.detailList(enforcedWhere, pagination, sort), + '查询明细列表失败' + ); + } + + /** + * 分页查询拆包录像列表(查,按拆包单维度校验仓库隔离)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件(unpack_id 必填,camera_id/status 可选)。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async videoList(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where, whereValue } = this.prepareWhereContext(data, {}); + + const unpackId = Number((whereValue && whereValue.unpack_id) || 0); + + return this._call(async () => { + if (!Number.isFinite(unpackId) || unpackId <= 0) { + throw service.systems.returnUnpack.createBusinessError('unpack_id 必填且必须为正整数', 400); + } + // 拆包单仓库隔离校验(不存在 404 / 跨仓库 403) + await service.systems.returnUnpack._findByIdChecked(unpackId); + return service.systems.returnUnpack.videoList( + { ...where, unpack_id: unpackId }, + pagination, + sort + ); + }, '查询录像列表失败'); + } + + /** + * 查询拆包单详情(查)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async detail(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.detail(Number(id)), '查询详情失败'); + } + + /** + * 提交退回拆包导出任务(异步任务模式,与 order.export 口径一致)。 + * 入参 where/sort 与 list 完全一致;提交后立即返回 task_id, + * 后台异步生成双 Sheet Excel(正常退回运单号列表 + 明细表)并上传, + * 通过 exportTaskProgress 查询进度与下载链接。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.where] 筛选条件(与 list 的 where 语义一致)。 + * @param {Object} [data.sort] 排序参数(与 list 的 sort 语义一致)。 + * @return {Promise} 统一成功包装响应(含 task_id/status/progress 等任务信息)。 + */ + async export(data = {}) { + const { service } = this; + const { sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + const taskId = this.generateExportTaskId(warehouseId); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '退回拆包导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '退回拆包导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.returnUnpack.exportUnpack({ + where: enforcedWhere, + sort, + warehouseId, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount, + total_count: safeProgress.totalCount, + message: safeProgress.message || '退回拆包导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '退回拆包导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '退回拆包导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询退回拆包导出任务进度(与 order.exportTaskProgress 口径一致)。 + * + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一成功包装响应 + * (含 task_id/status/progress/current_count/total_count/message/error/download_url/update_time)。 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成退回拆包导出任务ID。 + * @param {number|string} [warehouseId=''] 仓库ID(缺省兜底取当前上下文 store_id)。 + * @return {string} 导出任务ID。 + */ + generateExportTaskId(warehouseId = '') { + const normalizedWarehouseId = warehouseId || this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `return_unpack_export_${normalizedWarehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化退回拆包导出任务ID。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取退回拆包导出任务缓存键。 + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${RETURN_UNPACK_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入退回拆包导出任务进度缓存(Redis TTL 30 分钟)。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态载荷。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, RETURN_UNPACK_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[returnUnpack.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取退回拆包导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存,未命中返回 null。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[returnUnpack.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + + /** + * 删除拆包单(删,后台管理,不限制状态)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 拆包单ID。 + * @return {Promise} 统一 success 包装。 + */ + async delete(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.delete(Number(id)), '删除失败'); + } +} + +module.exports = ReturnUnpackMethodService; diff --git a/app/service/systemMethods/returnWaybill.js b/app/service/systemMethods/returnWaybill.js new file mode 100644 index 0000000..3b39c18 --- /dev/null +++ b/app/service/systemMethods/returnWaybill.js @@ -0,0 +1,132 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 系统方法层:returnWaybill(未退登记模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.return_waybill 中。 + */ +class ReturnWaybillMethodService extends MainService { + constructor(ctx) { + super(ctx); + // 免登录方法列表:空(全部需要登录) + const _noNeedLogin = ''; + // 免权限方法列表:detail 复用列表权限(仅登录 + 仓库隔离校验),其余走 API 权限校验 + const _noNeedRight = 'detail'; + // 免日志方法列表:空(全部记录日志) + const _noNeedLog = ''; + // 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期) + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用未退登记业务服务,并捕获业务错误码。 + * + * @param {Function} fn 业务调用函数。 + * @param {string} fallbackMessage 兜底错误文案。 + * @return {Promise} 统一 success/fail 包装。 + */ + async _call(fn, fallbackMessage) { + try { + const result = await fn(); + return this.success('ok', result); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || fallbackMessage, {}, code); + } + this.ctx.logger.error(`[returnWaybill] ${fallbackMessage}: ${error && error.message ? error.message : error}`); + return this.fail('服务器内部错误', {}, 500); + } + } + + /** + * 未退登记(增)。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @param {number} data.store_id 货主ID。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async create(data = {}) { + const { waybill_code, store_id, remark } = data; + return this._call( + () => this.service.systems.returnWaybill.create({ waybill_code, store_id, remark }), + '登记失败' + ); + } + + /** + * 修改登记(改)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录ID。 + * @param {string} [data.waybill_code] 运单号。 + * @param {number} [data.store_id] 货主ID。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装。 + */ + async update(data = {}) { + const { id, waybill_code, store_id, remark } = data; + return this._call( + () => this.service.systems.returnWaybill.update({ id, waybill_code, store_id, remark }), + '修改登记失败' + ); + } + + /** + * 分页查询登记列表(查,仓库隔离自动注入)。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一 success 包装。 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, {}); + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0); + const enforcedWhere = { ...where }; + if (warehouseId > 0) { + enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId }; + } + + return this._call( + () => service.systems.returnWaybill.list(enforcedWhere, pagination, sort), + '查询列表失败' + ); + } + + /** + * 查询单条登记详情(查)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录ID。 + * @return {Promise} 统一 success 包装。 + */ + async detail(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnWaybill.detail(Number(id)), '查询详情失败'); + } + + /** + * 删除单条登记(删)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 登记记录ID。 + * @return {Promise} 统一 success 包装。 + */ + async delete(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnWaybill.delete(Number(id)), '删除失败'); + } +} + +module.exports = ReturnWaybillMethodService; diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js new file mode 100644 index 0000000..9230e74 --- /dev/null +++ b/app/service/systemMethods/setting/account.js @@ -0,0 +1,106 @@ +'use strict'; + +const MainService = require('../../main'); + +class accountService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat'; + const _noNeedLog = '*'; + const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemAccount(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.account[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 账号列表。 + * @param {Object} data 请求体 + */ + async list(data = {}) { + const { service } = this; + try { + this.prepareWhereContext(data, { + specialFieldMap: { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.setting.account.list(data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取工号列表失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 新增工号。 + * @param {Object} data 请求体 + */ + async add(data = {}) { + return this.callSystemAccount('add', data, '添加工号失败'); + } + + /** + * 删除工号。 + * @param {Object} data 请求体 + */ + async delete(data = {}) { + return this.callSystemAccount('delete', data, '删除工号失败'); + } + + /** + * 更新工号。 + * @param {Object} data 请求体 + */ + async update(data = {}) { + return this.callSystemAccount('update', data, '更新工号失败'); + } + + /** + * 为其他账号获取微信绑定码。 + * @param {Object} data 请求体 + */ + async getBindWechatCode(data = {}) { + return this.callSystemAccount('getBindWechatCode', data, '获取账号绑定微信码失败'); + } + + /** + * 为其他账号解绑微信。 + * @param {Object} data 请求体 + */ + async unbindWechat(data = {}) { + return this.callSystemAccount('unbindWechat', data, '解绑账号微信失败'); + } +} + +module.exports = accountService; diff --git a/app/service/systemMethods/setting/express.js b/app/service/systemMethods/setting/express.js new file mode 100644 index 0000000..2259c69 --- /dev/null +++ b/app/service/systemMethods/setting/express.js @@ -0,0 +1,242 @@ +'use strict'; + +const MainService = require('../../main'); + +class expressService extends MainService { + /** + * 初始化快递映射模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,listBase,create,checkCodeUnique,update,delete'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,listBase,create,checkCodeUnique,update,delete'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用快递映射系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemExpress(methodName, data, defaultMessage) { + const { service } = this; + + try { + const result = await service.systems.setting.express[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取快递映射列表。 + * + * @param {Object} data 请求参数 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { service } = this; + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + code: { + field: 'code', + }, + name: { + field: 'name', + }, + express_code: { + field: 'express_code', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + try { + const result = await service.systems.setting.express.list(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取快递映射列表失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取系统快递编码和名称列表。 + * + * @return {Promise} 基础快递列表结果 + */ + async listBase() { + return await this.callSystemExpress('listBase', {}, '获取系统快递基础列表失败'); + } + + /** + * 创建快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { code, name, express_code: expressCode, expressCode: camelExpressCode, ...rest } = data || {}; + const payload = { + ...rest, + code, + name, + express_code: expressCode !== undefined ? expressCode : camelExpressCode, + }; + + return await this.callSystemExpress('create', payload, '创建快递映射失败'); + } + + /** + * 校验快递编码是否已被占用。 + * + * @param {Object} data 请求参数 + * @return {Promise} 校验结果 + */ + async checkCodeUnique(data = {}) { + const { id, code, ...rest } = data || {}; + const payload = { + ...rest, + id, + code, + }; + + return await this.callSystemExpress('checkCodeUnique', payload, '校验快递编码失败'); + } + + /** + * 修改快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const { id, code, name, express_code: expressCode, expressCode: camelExpressCode, ...rest } = data || {}; + const payload = { + ...rest, + id, + code, + name, + express_code: expressCode !== undefined ? expressCode : camelExpressCode, + }; + + return await this.callSystemExpress('update', payload, '更新快递映射失败'); + } + + /** + * 归一化删除 ID 列表。 + * + * 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + resolveDeleteIds(data = {}) { + const { + ids, + id, + setting_id: settingId, + settingId: camelSettingId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 删除快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { + ids, + id, + setting_id: settingId, + settingId: camelSettingId, + ...rest + } = data || {}; + + const payload = { + ...rest, + ids: this.resolveDeleteIds({ + ids, + id, + setting_id: settingId, + settingId: camelSettingId, + }), + }; + + return await this.callSystemExpress('delete', payload, '删除快递映射失败'); + } +} + +module.exports = expressService; diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js new file mode 100644 index 0000000..1d2d007 --- /dev/null +++ b/app/service/systemMethods/setting/expressInterface.js @@ -0,0 +1,485 @@ +'use strict'; + +const MainService = require('../../main'); + +class expressInterfaceService extends MainService { + /** + * 初始化快递接口管理模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,listByWarehousePlatformCode,create,update,delete'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,listByWarehousePlatformCode,create,update,delete'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用快递接口系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemExpressInterface(methodName, data, defaultMessage) { + const { service } = this; + + try { + const result = await service.systems.setting.expressInterface[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取快递接口列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + name: { + field: 'name', + }, + express_code: { + field: 'express_code', + }, + platform_code: { + field: 'platform_code', + }, + sender_name: { + field: 'sender_name', + }, + sender_tel: { + field: 'sender_tel', + }, + viewer: { + field: 'viewer', + }, + client_id: { + field: 'client_id', + }, + share_id: { + field: 'share_id', + }, + site_code: { + field: 'site_code', + }, + product_type: { + field: 'product_type', + }, + shop_name: { + field: 'shop_name', + }, + is_enabled: { + field: 'is_enabled', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const result = await this.callSystemExpressInterface('list', payload, '获取快递接口列表失败'); + if (result.flag !== 'success') { + return result; + } + + const list = result.data?.list || result.list || []; + if (list.length === 0) { + return result; + } + + // 收集唯一 shop_id(去重) + const shopIds = [ ...new Set( + list + .map(item => item.shop_id) + .filter(id => id !== null && id !== undefined && Number(id) !== 0) + ) ]; + + if (shopIds.length === 0) { + const defaultList = list.map(item => ({ ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 })); + if (result.data) { + result.data.list = defaultList; + } else { + result.list = defaultList; + } + return result; + } + + const { ctx } = this; + + // 并行调用 getShopExpressList,构建 Map + const shopExpressMap = new Map(); + const shopResults = await Promise.all( + shopIds.map(async shopId => { + try { + const shopExpressResult = await ctx.service.systemMethods.index.getShopExpressList({ + shop_id: shopId, + }); + return { shopId: Number(shopId), result: shopExpressResult }; + } catch (err) { + ctx.logger.warn( + `[expressInterface.list] 获取店铺 ${shopId} 快递签约数据异常: ${err.message}` + ); + return { shopId: Number(shopId), result: null }; + } + }) + ); + + for (const { shopId, result: shopResult } of shopResults) { + ctx.logger.info('[expressInterface.list] shopId=' + shopId + ' flag=' + (shopResult ? shopResult.flag : 'null') + ' msg=' + (shopResult ? shopResult.message : 'null')); + if (shopResult && shopResult.flag === 'success') { + const shopExpressList = shopResult.data?.list || shopResult.list || []; + if (shopExpressList.length > 0) { + shopExpressMap.set(shopId, shopExpressList); + } + } + } + + // 为每条记录匹配并汇总 quantity + const enrichedList = list.map(item => { + const shopId = item.shop_id; + if (shopId === null || shopId === undefined) { + return { ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 }; + } + + const shopExpressList = shopExpressMap.get(Number(shopId)); + if (!shopExpressList || shopExpressList.length === 0) { + return { ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 }; + } + + const sysExpressCode = (item.sys_express_code || '').trim().toUpperCase(); + const expressCode = (item.express_code || '').trim().toUpperCase(); + + // 按 sys_express_code 或 express_code(wp_code) 匹配 + const matchedExpress = shopExpressList.find(expressItem => { + const itemSysCode = (expressItem.sys_express_code || '').trim().toUpperCase(); + const itemWpCode = (expressItem.wp_code || '').trim().toUpperCase(); + return itemSysCode === sysExpressCode + || itemWpCode === expressCode + || itemSysCode === expressCode; + }); + + if (!matchedExpress) { + return { ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 }; + } + + let accounts = Array.isArray(matchedExpress.accounts) ? matchedExpress.accounts : []; + + // 若有 site_code,进一步按 branch_code 筛选匹配的网点账号 + const siteCode = (item.site_code || '').trim().toUpperCase(); + if (siteCode) { + const branchMatched = accounts.filter(acc => + (acc.branch_code || '').trim().toUpperCase() === siteCode + ); + if (branchMatched.length > 0) { + accounts = branchMatched; + } + } + + // 若有 shipperno,进一步按 customer_code_list 筛选匹配的账号 + const shipperNo = (item.shipperno || '').trim(); + if (shipperNo && accounts.length > 0) { + const shipperMatched = accounts.filter(acc => + Array.isArray(acc.customer_code_list) && acc.customer_code_list.includes(shipperNo) + ); + if (shipperMatched.length > 0) { + accounts = shipperMatched; + } + } + + return { ...item, quantity: accounts.reduce((sum, acc) => sum + (Number(acc.quantity) || 0), 0), recycled_quantity: accounts.reduce((sum, acc) => sum + (Number(acc.recycled_quantity) || 0), 0), cancel_quantity: accounts.reduce((sum, acc) => sum + (Number(acc.cancel_quantity) || 0), 0), allocated_quantity: accounts.reduce((sum, acc) => sum + (Number(acc.allocated_quantity) || 0), 0) }; + }); + + if (result.data) { + result.data.list = enrichedList; + } else { + result.list = enrichedList; + } + + return result; + } + + /** + * 按仓库与平台代码查询快递接口全量记录。 + * + * @param {Object} data 请求参数 + * @return {Promise} 查询结果 + */ + async listByWarehousePlatformCode(data = {}) { + return await this.callSystemExpressInterface('listByWarehousePlatformCode', data, '获取快递接口查询失败'); + } + + /** + * 创建快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { + name, + express_code: expressCode, + expressCode: camelExpressCode, + sys_express_code: sysExpressCode, + sysExpressCode: camelSysExpressCode, + platform_code: platformCode, + platformCode: camelPlatformCode, + weight_type: weightType, + weightType: camelWeightType, + address, + town_name: townName, + townName: camelTownName, + ispickup: isPickup, + isPickup: camelIsPickup, + shipperno: shipperNo, + shipperNo: camelShipperNo, + template_url: templateUrl, + templateUrl: camelTemplateUrl, + ext_data: extData, + extData: camelExtData, + template_id: templateId, + templateId: camelTemplateId, + paymode, + payMode, + brandno, + brandNo, + providertype, + providerType, + providerid, + providerId, + ...rest + } = data || {}; + + const payload = { + ...rest, + }; + + if (name !== undefined) { + payload.name = name; + } + if (expressCode !== undefined || camelExpressCode !== undefined) { + payload.express_code = expressCode !== undefined ? expressCode : camelExpressCode; + } + if (platformCode !== undefined || camelPlatformCode !== undefined) { + payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode; + } + if (sysExpressCode !== undefined || camelSysExpressCode !== undefined) { + payload.sys_express_code = sysExpressCode !== undefined ? sysExpressCode : camelSysExpressCode; + } + if (weightType !== undefined || camelWeightType !== undefined) { + payload.weight_type = weightType !== undefined ? weightType : camelWeightType; + } + if (address !== undefined) { + payload.address = address; + } + if (townName !== undefined || camelTownName !== undefined) { + payload.town_name = townName !== undefined ? townName : camelTownName; + } + if (isPickup !== undefined || camelIsPickup !== undefined) { + payload.ispickup = isPickup !== undefined ? isPickup : camelIsPickup; + } + if (shipperNo !== undefined || camelShipperNo !== undefined) { + payload.shipperno = shipperNo !== undefined ? shipperNo : camelShipperNo; + } + if (templateUrl !== undefined || camelTemplateUrl !== undefined) { + payload.template_url = templateUrl !== undefined ? templateUrl : camelTemplateUrl; + } + if (extData !== undefined || camelExtData !== undefined) { + payload.ext_data = extData !== undefined ? extData : camelExtData; + } + if (templateId !== undefined || camelTemplateId !== undefined) { + payload.template_id = templateId !== undefined ? templateId : camelTemplateId; + } + if (paymode !== undefined || payMode !== undefined) { + payload.paymode = paymode !== undefined ? paymode : payMode; + } + if (brandno !== undefined || brandNo !== undefined) { + payload.brandno = brandno !== undefined ? brandno : brandNo; + } + if (providertype !== undefined || providerType !== undefined) { + payload.providertype = providertype !== undefined ? providertype : providerType; + } + if (providerid !== undefined || providerId !== undefined) { + payload.providerid = providerid !== undefined ? providerid : providerId; + } + + return await this.callSystemExpressInterface('create', payload, '创建快递接口失败'); + } + + /** + * 修改快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const { + id, + interface_id: interfaceId, + interfaceId: camelInterfaceId, + name, + express_code: expressCode, + expressCode: camelExpressCode, + sys_express_code: sysExpressCode, + sysExpressCode: camelSysExpressCode, + platform_code: platformCode, + platformCode: camelPlatformCode, + weight_type: weightType, + weightType: camelWeightType, + address, + town_name: townName, + townName: camelTownName, + ispickup: isPickup, + isPickup: camelIsPickup, + shipperno: shipperNo, + shipperNo: camelShipperNo, + template_url: templateUrl, + templateUrl: camelTemplateUrl, + ext_data: extData, + extData: camelExtData, + platform_shop_id: platformShopId, + platformShopId: camelPlatformShopId, + template_id: templateId, + templateId: camelTemplateId, + paymode, + payMode, + brandno, + brandNo, + providertype, + providerType, + providerid, + providerId, + is_enabled: isEnabledSnake, + isEnabled: isEnabledCamel, + ...rest + } = data || {}; + + const payload = { + ...rest, + }; + + payload.id = id !== undefined ? id : (interfaceId !== undefined ? interfaceId : camelInterfaceId); + if (name !== undefined) { + payload.name = name; + } + if (expressCode !== undefined || camelExpressCode !== undefined) { + payload.express_code = expressCode !== undefined ? expressCode : camelExpressCode; + } + if (platformCode !== undefined || camelPlatformCode !== undefined) { + payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode; + } + if (sysExpressCode !== undefined || camelSysExpressCode !== undefined) { + payload.sys_express_code = sysExpressCode !== undefined ? sysExpressCode : camelSysExpressCode; + } + if (weightType !== undefined || camelWeightType !== undefined) { + payload.weight_type = weightType !== undefined ? weightType : camelWeightType; + } + if (address !== undefined) { + payload.address = address; + } + if (townName !== undefined || camelTownName !== undefined) { + payload.town_name = townName !== undefined ? townName : camelTownName; + } + if (isPickup !== undefined || camelIsPickup !== undefined) { + payload.ispickup = isPickup !== undefined ? isPickup : camelIsPickup; + } + if (shipperNo !== undefined || camelShipperNo !== undefined) { + payload.shipperno = shipperNo !== undefined ? shipperNo : camelShipperNo; + } + if (templateUrl !== undefined || camelTemplateUrl !== undefined) { + payload.template_url = templateUrl !== undefined ? templateUrl : camelTemplateUrl; + } + if (extData !== undefined || camelExtData !== undefined) { + payload.ext_data = extData !== undefined ? extData : camelExtData; + } + if (platformShopId !== undefined || camelPlatformShopId !== undefined) { + payload.platform_shop_id = platformShopId !== undefined ? platformShopId : camelPlatformShopId; + } + if (templateId !== undefined || camelTemplateId !== undefined) { + payload.template_id = templateId !== undefined ? templateId : camelTemplateId; + } + if (paymode !== undefined || payMode !== undefined) { + payload.paymode = paymode !== undefined ? paymode : payMode; + } + if (brandno !== undefined || brandNo !== undefined) { + payload.brandno = brandno !== undefined ? brandno : brandNo; + } + if (providertype !== undefined || providerType !== undefined) { + payload.providertype = providertype !== undefined ? providertype : providerType; + } + if (providerid !== undefined || providerId !== undefined) { + payload.providerid = providerid !== undefined ? providerid : providerId; + } + if (isEnabledSnake !== undefined || isEnabledCamel !== undefined) { + payload.is_enabled = isEnabledSnake !== undefined ? isEnabledSnake : isEnabledCamel; + } + + return await this.callSystemExpressInterface('update', payload, '更新快递接口失败'); + } + + /** + * 删除快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { + id, + interface_id: interfaceId, + interfaceId: camelInterfaceId, + ...rest + } = data || {}; + + const payload = { + ...rest, + }; + + payload.id = id !== undefined ? id : (interfaceId !== undefined ? interfaceId : camelInterfaceId); + + return await this.callSystemExpressInterface('delete', payload, '删除快递接口失败'); + } +} + +module.exports = expressInterfaceService; diff --git a/app/service/systemMethods/setting/packageMaterial.js b/app/service/systemMethods/setting/packageMaterial.js new file mode 100644 index 0000000..384c4ac --- /dev/null +++ b/app/service/systemMethods/setting/packageMaterial.js @@ -0,0 +1,266 @@ +'use strict'; + +const MainService = require('../../main'); + +class packageMaterialService extends MainService { + /** + * 初始化包材设置模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'get,list,create,update,delete,search'; + const _noNeedLog = '*'; + const _noNeedAuth = 'get,list,create,update,delete,search'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用包材系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemPackageMaterial(methodName, data, defaultMessage) { + try { + const result = await this.service.systems.setting.packageMaterial[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 归一化删除 ID 列表。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + resolveDeleteIds(data = {}) { + const { + ids, + id, + material_id: materialId, + materialId: camelMaterialId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 查询包材列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async get(data = {}) { + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + material_code: { + field: 'material_code', + }, + material_name: { + field: 'material_name', + }, + material_type: { + field: 'material_type', + }, + status: { + field: 'status', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + return await this.callSystemPackageMaterial('get', payload, '获取包材列表失败'); + } + + /** + * 兼容旧式 list 命名,内部转发至 get。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + return await this.get(data); + } + + /** + * 快捷搜索包材,按关键词模糊匹配编码和名称。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.keyword] 搜索关键词 + * @return {Promise} data 为搜索结果数组,最多 50 条 + */ + async search(data = {}) { + const result = await this.service.systems.setting.packageMaterial.search(data); + return this.success('ok', result); + } + + /** + * 创建包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + } = data || {}; + + const payload = { + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + }; + + return await this.callSystemPackageMaterial('create', payload, '创建包材失败'); + } + + /** + * 更新包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 更新结果 + */ + async update(data = {}) { + const { + id, + material_id: materialId, + materialId: camelMaterialId, + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + } = data || {}; + + const payload = { + id: id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId), + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + }; + + return await this.callSystemPackageMaterial('update', payload, '更新包材失败'); + } + + /** + * 删除包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { + ids, + id, + material_id: materialId, + materialId: camelMaterialId, + } = data || {}; + + const payload = { + ids: this.resolveDeleteIds({ + ids, + id, + material_id: materialId, + materialId: camelMaterialId, + }), + }; + + return await this.callSystemPackageMaterial('delete', payload, '删除包材失败'); + } +} + +module.exports = packageMaterialService; diff --git a/app/service/systemMethods/setting/packageSupplier.js b/app/service/systemMethods/setting/packageSupplier.js new file mode 100644 index 0000000..b48770f --- /dev/null +++ b/app/service/systemMethods/setting/packageSupplier.js @@ -0,0 +1,237 @@ +'use strict'; + +const MainService = require('../../main'); + +class packageSupplierService extends MainService { + /** + * 初始化包材供应商设置模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'get,list,create,update,delete'; + const _noNeedLog = '*'; + const _noNeedAuth = 'get,list,create,update,delete'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用包材供应商系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemPackageSupplier(methodName, data, defaultMessage) { + try { + const result = await this.service.systems.setting.packageSupplier[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 归一化删除 ID 列表。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + resolveDeleteIds(data = {}) { + const { + ids, + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 查询包材供应商列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async get(data = {}) { + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + supplier_code: { + field: 'supplier_code', + }, + supplier_name: { + field: 'supplier_name', + }, + contact_name: { + field: 'contact_name', + }, + contact_phone: { + field: 'contact_phone', + }, + status: { + field: 'status', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + return await this.callSystemPackageSupplier('get', payload, '获取包材供应商列表失败'); + } + + /** + * 兼容旧式 list 命名,内部转发至 get。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + return await this.get(data); + } + + /** + * 创建包材供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + } = data || {}; + + const payload = { + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + }; + + return await this.callSystemPackageSupplier('create', payload, '创建包材供应商失败'); + } + + /** + * 更新包材供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 更新结果 + */ + async update(data = {}) { + const { + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + } = data || {}; + + const payload = { + id: id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId), + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + }; + + return await this.callSystemPackageSupplier('update', payload, '更新包材供应商失败'); + } + + /** + * 删除包材供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { + ids, + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + } = data || {}; + + const payload = { + ids: this.resolveDeleteIds({ + ids, + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + }), + }; + + return await this.callSystemPackageSupplier('delete', payload, '删除包材供应商失败'); + } +} + +module.exports = packageSupplierService; diff --git a/app/service/systemMethods/setting/permission.js b/app/service/systemMethods/setting/permission.js new file mode 100644 index 0000000..66a9a63 --- /dev/null +++ b/app/service/systemMethods/setting/permission.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class permissionService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,add,delete,update'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,add,delete,update'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemPermission(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.permission[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 权限列表。 + * @param {Object} data 请求体 + */ + async list(data = {}) { + return this.callSystemPermission('list', data, '获取权限列表失败'); + } + + /** + * 新增权限。 + * @param {Object} data 请求体 + */ + async add(data = {}) { + return this.callSystemPermission('add', data, '新增权限失败'); + } + + /** + * 删除权限。 + * @param {Object} data 请求体 + */ + async delete(data = {}) { + return this.callSystemPermission('delete', data, '删除权限失败'); + } + + /** + * 更新权限。 + * @param {Object} data 请求体 + */ + async update(data = {}) { + return this.callSystemPermission('update', data, '更新权限失败'); + } +} + +module.exports = permissionService; diff --git a/app/service/systemMethods/setting/platform.js b/app/service/systemMethods/setting/platform.js new file mode 100644 index 0000000..f72bda5 --- /dev/null +++ b/app/service/systemMethods/setting/platform.js @@ -0,0 +1,237 @@ +'use strict'; + +const MainService = require('../../main'); + +class platformService extends MainService { + /** + * 初始化平台设置模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,create,update,delete'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,create,update,delete'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用平台设置系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemPlatform(methodName, data, defaultMessage) { + const { service } = this; + + try { + const result = await service.systems.setting.platform[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取平台设置列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + code: { + field: 'code', + }, + name: { + field: 'name', + }, + platform_code: { + field: 'platform_code', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + return await this.callSystemPlatform('list', payload, '获取平台设置列表失败'); + } + + /** + * 创建平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { + code, + name, + platform_code: platformCode, + platformCode: camelPlatformCode, + ...rest + } = data || {}; + + const payload = { + ...rest, + code, + name, + platform_code: platformCode !== undefined ? platformCode : camelPlatformCode, + }; + + return await this.callSystemPlatform('create', payload, '创建平台设置失败'); + } + + /** + * 修改平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const { + id, + setting_id: settingId, + settingId: camelSettingId, + code, + name, + platform_code: platformCode, + platformCode: camelPlatformCode, + ...rest + } = data || {}; + + const payload = { + ...rest, + }; + + payload.id = id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId); + + if (code !== undefined) { + payload.code = code; + } + + if (name !== undefined) { + payload.name = name; + } + + if (platformCode !== undefined || camelPlatformCode !== undefined) { + payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode; + } + + return await this.callSystemPlatform('update', payload, '更新平台设置失败'); + } + + /** + * 归一化删除 ID 列表。 + * + * 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + resolveDeleteIds(data = {}) { + const { + ids, + id, + setting_id: settingId, + settingId: camelSettingId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 删除平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { + ids, + id, + setting_id: settingId, + settingId: camelSettingId, + ...rest + } = data || {}; + + const normalizedIds = this.resolveDeleteIds({ + ids, + id, + setting_id: settingId, + settingId: camelSettingId, + }); + + const payload = { + ...rest, + ids: normalizedIds, + }; + + return await this.callSystemPlatform('delete', payload, '删除平台设置失败'); + } +} + +module.exports = platformService; diff --git a/app/service/systemMethods/setting/printTemplate.js b/app/service/systemMethods/setting/printTemplate.js index fa99777..ccbbac7 100644 --- a/app/service/systemMethods/setting/printTemplate.js +++ b/app/service/systemMethods/setting/printTemplate.js @@ -1,35 +1,149 @@ 'use strict'; const MainService = require('../../main'); +const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ]; class printTemplateService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,save,listTemplatesByType'; + const _noNeedRight = 'list,save,create,delete,listTemplatesByType'; const _noNeedLog = '*'; - const _noNeedAuth = 'list,save,listTemplatesByType'; + const _noNeedAuth = 'list,save,create,delete,listTemplatesByType'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } - async list(data) { + async list() { const { service } = this; const result = await service.systems.setting.printTemplate.getTree(); return this.success('ok', { presetTree: result, code: 200 }); } - async save(data) { - console.log('接收到保存请求:', data); - const { service } = this; - const result = await service.systems.setting.printTemplate.save(data); - return this.success('ok', result); + + /** + * 规范化并校验业务类型 + * @param {string} businessType 业务类型 + * @return {string} 标准化后的业务类型 + */ + normalizeAndValidateBusinessType(businessType) { + const normalizedBusinessType = String(businessType || '').trim().toUpperCase(); + if (!normalizedBusinessType) { + throw new Error('business_type 参数不能为空'); + } + if (!SUPPORTED_BUSINESS_TYPES.includes(normalizedBusinessType)) { + throw new Error(`business_type 参数非法,仅支持:${SUPPORTED_BUSINESS_TYPES.join('、')}`); + } + return normalizedBusinessType; } + + /** + * 保存打印模板 + * @param {Object} data 入参 + * @return {Promise} 保存结果 + */ + async save(data) { + const { service } = this; + const payload = data || {}; + try { + if (payload.business_type !== undefined && payload.business_type !== null && String(payload.business_type).trim() !== '') { + payload.business_type = this.normalizeAndValidateBusinessType(payload.business_type); + } + } catch (error) { + return this.fail(error.message, { code: 400 }); + } + try { + const result = await service.systems.setting.printTemplate.save(payload); + return this.success('ok', result); + } catch (error) { + const message = error && error.message ? error.message : '保存打印模板失败'; + if (message.includes('business_type 参数')) { + return this.fail(message, { code: 400 }); + } + return this.fail(message, { code: 500 }); + } + } + + /** + * 创建打印模板 + * @param {Object} data 入参 + * @return {Promise} 创建结果 + */ + async create(data) { + const { service } = this; + const { template_name, business_type, page_width, page_height } = data || {}; + + if (!template_name || String(template_name).trim() === '') { + return this.fail('template_name 参数不能为空', { code: 400 }); + } + let normalizedBusinessType = ''; + try { + normalizedBusinessType = this.normalizeAndValidateBusinessType(business_type); + } catch (error) { + return this.fail(error.message, { code: 400 }); + } + if (page_width === undefined || page_width === null || page_width === '') { + return this.fail('page_width 参数不能为空', { code: 400 }); + } + if (page_height === undefined || page_height === null || page_height === '') { + return this.fail('page_height 参数不能为空', { code: 400 }); + } + + try { + const result = await service.systems.setting.printTemplate.createTemplate({ + ...data, + business_type: normalizedBusinessType, + }); + return this.success('ok', result); + } catch (error) { + if (error.message === '同一业务类型和平台下已存在自定义模板') { + return this.fail(error.message, { code: 409 }); + } + if (error.message && error.message.includes('business_type 参数')) { + return this.fail(error.message, { code: 400 }); + } + return this.fail(error.message || '创建打印模板失败', { code: 500 }); + } + } + + /** + * 删除打印模板 + * @param {Object} data 入参 + * @return {Promise} 删除结果 + */ + async delete(data) { + const { service } = this; + const { id } = data || {}; + const templateId = Number(id); + + if (!templateId || Number.isNaN(templateId)) { + return this.fail('id 参数不能为空', { code: 400 }); + } + + try { + const result = await service.systems.setting.printTemplate.deleteTemplate(templateId); + return this.success('ok', result); + } catch (error) { + if (error.message === '模板不存在或无权限') { + return this.fail(error.message, { code: 404 }); + } + return this.fail(error.message || '删除打印模板失败', { code: 500 }); + } + } + + /** + * 按业务类型查询模板 + * @param {Object} data 入参 + * @return {Promise} 查询结果 + */ async listTemplatesByType(data) { const { service } = this; - console.log('接收到根据业务类型查询模板请求:', data); - const { businessType } = data; - if(!businessType){ - throw new Error('缺少业务类型参数'); + const { businessType } = data || {}; + let normalizedBusinessType = ''; + try { + normalizedBusinessType = this.normalizeAndValidateBusinessType(businessType); + } catch (error) { + return this.fail(error.message, { code: 400 }); } - const list = await service.systems.setting.printTemplate.listTemplatesByType(businessType); + + const list = await service.systems.setting.printTemplate.listTemplatesByType(normalizedBusinessType); return this.success('ok', { data: list, code: 200 }); } } diff --git a/app/service/systemMethods/setting/role.js b/app/service/systemMethods/setting/role.js new file mode 100644 index 0000000..7fa3469 --- /dev/null +++ b/app/service/systemMethods/setting/role.js @@ -0,0 +1,68 @@ +'use strict'; + +const MainService = require('../../main'); + +class roleService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,add,delete,update,permission'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,add,delete,update,permission'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemRole(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.role[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 角色列表。 + * @param {*} data 请求参数 + */ + async list(data = {}) { + return this.callSystemRole('list', data, '获取角色列表失败'); + } + + /** + * 角色权限列表(兼容旧入口)。 + * @param {*} data 请求参数 + */ + async permission(data = {}) { + return this.callSystemRole('permission', data, '获取角色权限列表失败'); + } + + /** + * 新增角色。 + * @param {*} data 请求参数 + */ + async add(data = {}) { + return this.callSystemRole('add', data, '新增角色失败'); + } + + /** + * 删除角色。 + * @param {*} data 请求参数 + */ + async delete(data = {}) { + return this.callSystemRole('delete', data, '删除角色失败'); + } + + /** + * 更新角色。 + * @param {*} data 请求参数 + */ + async update(data = {}) { + return this.callSystemRole('update', data, '更新角色失败'); + } +} + +module.exports = roleService; diff --git a/app/service/systemMethods/setting/store_warehouse.js b/app/service/systemMethods/setting/store_warehouse.js new file mode 100644 index 0000000..3d19407 --- /dev/null +++ b/app/service/systemMethods/setting/store_warehouse.js @@ -0,0 +1,14 @@ +'use strict'; + +const MainService = require('../../main'); + +// 旧兼容入口 `setting.store_warehouse.*` 已下线; +// 保留空服务壳体,确保调用时在 dispatcher 层直接返回“方法不存在”。 +class StoreWarehouseLegacyService extends MainService { + constructor(ctx) { + super(ctx); + this.systemInit('', '', '*', ''); + } +} + +module.exports = StoreWarehouseLegacyService; diff --git a/app/service/systemMethods/setting/warehouse.js b/app/service/systemMethods/setting/warehouse.js new file mode 100644 index 0000000..806a169 --- /dev/null +++ b/app/service/systemMethods/setting/warehouse.js @@ -0,0 +1,110 @@ +'use strict'; + +const MainService = require('../../main'); + +class SettingWarehouseMethodsService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getSettings,getFieldMeta,saveSettings,getweChatApp'; + const _noNeedLog = '*'; + const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings,getweChatApp'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 获取仓库设置(subject_config)。 + * + * @return {Promise} 统一响应结果。 + */ + async getSettings() { + const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse; + + if (!targetService || typeof targetService.getSettings !== 'function') { + return this.fail('获取仓库设置失败', { code: 500 }); + } + + try { + const result = await targetService.getSettings(); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取仓库设置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取仓库设置字段元信息列表。 + * + * @return {Promise} 统一响应结果。 + */ + async getFieldMeta() { + const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse; + + if (!targetService || typeof targetService.getFieldMeta !== 'function') { + return this.fail('获取仓库设置字段信息失败', { code: 500 }); + } + + try { + const list = await targetService.getFieldMeta(); + return this.success('ok', { list }); + } catch (error) { + return this.fail(error.message || '获取仓库设置字段信息失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 修改仓库设置并清理当前仓库缓存。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一响应结果。 + */ + async saveSettings(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse; + + if (!targetService || typeof targetService.saveSettings !== 'function') { + return this.fail('保存仓库设置失败', { code: 500 }); + } + + try { + const { subject_config } = data || {}; + const result = await targetService.saveSettings({ subject_config }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '保存仓库设置失败', { + code: Number(error.code) || 500, + }); + } + } + + + /** + * 获取当前仓库启用的微信小程序授权配置(wms_wechat_app)。 + * + * 仅返回一条启用(is_enabled=1)记录,配置统一封装在响应 data 字段中, + * data 为对象而非数组;无可用记录时 data 为 null。 + * + * @return {Promise} 统一响应结果。 + */ + async getweChatApp() { + const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse; + + if (!targetService || typeof targetService.getWechatApp !== 'function') { + return this.fail('获取微信小程序配置失败', { code: 500 }); + } + + try { + const result = await targetService.getWechatApp(); + return this.success('ok', { data: result }); + } catch (error) { + return this.fail(error.message || '获取微信小程序配置失败', { + code: Number(error.code) || 500, + }); + } + } +} + +module.exports = SettingWarehouseMethodsService; diff --git a/app/service/systemMethods/shops.js b/app/service/systemMethods/shops.js new file mode 100644 index 0000000..c828973 --- /dev/null +++ b/app/service/systemMethods/shops.js @@ -0,0 +1,169 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 店铺 methods 出口。 + */ +class ShopsMethodService extends MainService { + /** + * 初始化店铺模块鉴权配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = '*'; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用店铺业务服务。 + * + * @param {string} methodName 业务方法名 + * @param {Object} data 请求参数 + * @param {string} fallbackMessage 默认错误文案 + * @return {Promise} methods 标准返回 + */ + async callShopsSystem(methodName, data, fallbackMessage) { + const { service } = this; + + try { + const result = await service.systems.shops[methodName](data); + return this.success('ok', { data: result, code: 200 }); + } catch (error) { + return this.fail(error.message || fallbackMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * shops.list:分页查询店铺。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 查询结果 + */ + async list(data = {}) { + const payload = { + ...(data && typeof data === 'object' ? data : {}), + }; + + this.prepareWhereContext(payload, { + specialFieldMap: this.service.systems.shops.getListWhereSpecialFieldMap(), + }); + + return await this.callShopsSystem('list', payload, '查询店铺列表失败'); + } + + /** + * shops.add:新增店铺。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 新增结果 + */ + async add(data = {}) { + const { + custom_name: customName, + customName: customNameCamel, + platform_code: platformCode, + platformCode: platformCodeCamel, + } = data || {}; + + return await this.callShopsSystem('add', { + custom_name: customName !== undefined ? customName : customNameCamel, + platform_code: platformCode !== undefined ? platformCode : platformCodeCamel, + }, '新增店铺失败'); + } + + /** + * shops.del:软删除店铺。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 删除结果 + */ + async del(data = {}) { + const { + id, + shop_id: shopId, + shopId: shopIdCamel, + } = data || {}; + + return await this.callShopsSystem('del', { + id: id !== undefined ? id : (shopId !== undefined ? shopId : shopIdCamel), + }, '删除店铺失败'); + } + + /** + * shops.edit:编辑店铺。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 编辑结果 + */ + async edit(data = {}) { + const { + id, + shop_id: shopId, + shopId: shopIdCamel, + shop_name: shopName, + shopName: shopNameCamel, + custom_name: customName, + customName: customNameCamel, + platform_code: platformCode, + platformCode: platformCodeCamel, + } = data || {}; + + const payload = { + id: id !== undefined ? id : (shopId !== undefined ? shopId : shopIdCamel), + }; + + if (shopName !== undefined || shopNameCamel !== undefined) { + payload.shop_name = shopName !== undefined ? shopName : shopNameCamel; + } + + if (customName !== undefined || customNameCamel !== undefined) { + payload.custom_name = customName !== undefined ? customName : customNameCamel; + } + + if (platformCode !== undefined || platformCodeCamel !== undefined) { + payload.platform_code = platformCode !== undefined ? platformCode : platformCodeCamel; + } + + return await this.callShopsSystem('edit', payload, '编辑店铺失败'); + } + + /** + * shop.GetAuthorizeSessionKey:按店铺平台生成授权会话。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 会话结果 + */ + async GetAuthorizeSessionKey(data = {}) { + const { + id, + shop_id: shopId, + shopId: shopIdCamel, + callbackurl, + callback_url: callbackUrlSnake, + callbackUrl, + appId, + app_id: appIdSnake, + toUserName, + to_user_name: toUserNameSnake, + } = data || {}; + + return await this.callShopsSystem('getAuthorizeSessionKey', { + id: id !== undefined ? id : (shopId !== undefined ? shopId : shopIdCamel), + callbackurl: callbackurl !== undefined + ? callbackurl + : (callbackUrlSnake !== undefined ? callbackUrlSnake : callbackUrl), + appId: appId !== undefined ? appId : appIdSnake, + toUserName: toUserName !== undefined ? toUserName : toUserNameSnake, + }, '获取授权会话失败'); + } +} + +module.exports = ShopsMethodService; diff --git a/app/service/systemMethods/stock.js b/app/service/systemMethods/stock.js deleted file mode 100644 index 6473789..0000000 --- a/app/service/systemMethods/stock.js +++ /dev/null @@ -1,361 +0,0 @@ -'use strict'; - -const MainService = require('../main'); - -class indexService extends MainService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search'; - const _noNeedLog = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; - const _noNeedAuth = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - async stockWarehouse(data) { - const { service } = this; - const { pagination, where } = data; - console.log('where', where); - const result = await service.systems.stockStore.getWarehouseStock(where, pagination); - return this.success('ok', result); - } - async getProhibitedType() { - const { service } = this; - const result = await service.systems.stockStore.getProhibitedType(); - return this.success('ok', { data: result, code: 200 }); - } - async getInfo(data) { - const { service } = this; - const result = await service.systems.stockStore.getInfo(data); - return this.success('ok', { data: result, code: 200 }); - } - async saveWarehouseStock(data) { - const { service } = this; - const result = await service.systems.stockStore.saveWarehouseStock(data); - return this.success('ok', { data: result, code: 200 }); - } - - async createWarehouseStock(data) { - const { service } = this; - const result = await service.systems.stockStore.createWarehouseStock(data); - return this.success('ok', { data: result, code: 200 }); - } - async getBarcodes(data) { - const { service } = this; - const result = await service.systems.stockStore.getBarcodes(data); - return this.success('ok', { data: result, code: 200 }); - } - async saveWarehouseStockBarcode(data) { - const { service } = this; - const result = await service.systems.stockStore.saveWarehouseStockBarcode(data); - return this.success('ok', { data: result, code: 200 }); - } - async getStoreStocks(data) { - const { service } = this; - const result = await service.systems.stockStore.getStoreStocks(data); - return this.success('ok', { data: result, code: 200 }); - } - async bindItem(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.bindItem(data); - return this.success('绑定成功', { data: result, code: 200 }); - } catch (e) { - return this.success(e.message, { code: 200 }); - } - } - async unbindItem(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.unbindItem(data); - return this.success('解绑成功', { data: result, code: 200 }); - } catch (e) { - return this.success(e.message, { code: 200 }); - } - } - async checkItemCodeUnique(data) { - const { ctx, service } = this; - const { id, item_code, store_id } = data; - console.log(data); - try { - if (!item_code || !store_id) { - return this.fail('参数错误'); - } - const data = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id); - return this.success('获取成功', { data, code: 200 }); - } catch (error) { - return this.fail(error.message); - } - } - async queryStockLogs(data) { - console.log('请求'); - const { ctx } = this; - try { - const { service } = this; - data.warehouseId = ctx.user.store_id; - const result = await service.systems.operationLog.queryStockLogs(data); - return this.success('ok', { data: result, code: 200 }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } - - async handleBatchDelete(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.handleBatchDelete(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } - - async deleteUnit(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.deleteUnit(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } - - async deleteProhibited(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.deleteProhibited(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 200 }); - } - } - async handleBatchChange(data) { - const { service } = this; - try { - const result = await service.systems.stockStore.handleBatchChange(data); - return this.success(result.message, { data: result.data, code: result.code }); - } catch (e) { - console.log(e); - return this.success(e.message, { code: 405 }); - } - } - async getStockUnits() { - console.log('query_getStockUnits'); - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - - try { - // 构建查询条件 - const where = { - [ctx.app.Sequelize.Op.or]: [ - { warehouse_id: null }, // 系统预设单位 - { warehouse_id }, // 本仓库的单位 - ], - }; - - const units = await ctx.model.StockUnit.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null) - [ 'created_at', 'DESC' ], // 按创建时间倒序 - ], - }); - return this.success('ok', { data: units, code: 200 }); - } catch (error) { - console.log(error); - return this.fail(error.message); - } - } - async getUnitList() { - console.log('query_getUnitList'); - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - - try { - // 构建查询条件 - const where = { - warehouse_id, - }; - - const units = await ctx.model.StockUnit.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null) - [ 'created_at', 'DESC' ], // 按创建时间倒序 - ], - }); - return this.success('ok', { data: units, code: 200 }); - } catch (error) { - console.log(error); - return this.fail(error.message); - } - } - async createProhibited(data) { - console.log('createProhibited', data); - const { ctx } = this; - const warehouse_id = ctx.user.store_id || null; - const { name } = data; - - // 参数验证 - if (!name || name.trim() === '') { - ctx.body = { - code: 400, - message: '违禁品类型名称不能为空', - }; - return; - } - - const trimmedName = name.trim(); - - try { - // 1. 检查是否是系统预设单位(warehouse_id为null) - const systemUnit = await ctx.model.ProhibitedType.findOne({ - where: { - type_name: trimmedName, - warehouse_id: null, - }, - }); - - if (systemUnit) { - ctx.body = { - code: 400, - message: '该违禁品类型是系统预设,不允许添加', - }; - return; - } - - // 2. 检查当前仓库是否已存在相同名称的单位 - const existUnit = await ctx.model.ProhibitedType.findOne({ - where: { - type_name: trimmedName, - warehouse_id, - }, - }); - - if (existUnit) { - ctx.body = { - code: 400, - message: '该违禁品类型名称已存在', - }; - return; - } - - // 3. 创建单位 - const unit = await ctx.model.ProhibitedType.create({ - type_name: trimmedName, - warehouse_id, - }); - - // 4. 获取更新后的单位列表 - const where = {}; - if (warehouse_id) { - where[ctx.app.Sequelize.Op.or] = [ - { warehouse_id: null }, // 系统预设单位 - { warehouse_id }, // 当前仓库的单位 - ]; - } else { - where.warehouse_id = null; // 只显示系统预设单位 - } - - const units = await ctx.model.ProhibitedType.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null) - [ 'created_at', 'DESC' ], // 按创建时间倒序 - ], - }); - return this.success('添加成功', { code: 200 }); - } catch (error) { - console.log(error); - return this.success('创建违禁品类型失败', { code: 405 }); - } - } - async createUnit() { - const { ctx } = this; - const warehouse_id = ctx.user.store_id || null; - const { name } = ctx.request.body; - - // 参数验证 - if (!name || name.trim() === '') { - ctx.body = { - code: 400, - message: '单位名称不能为空', - }; - return; - } - - const trimmedName = name.trim(); - - try { - // 1. 检查是否是系统预设单位(warehouse_id为null) - const systemUnit = await ctx.model.StockUnit.findOne({ - where: { - name: trimmedName, - warehouse_id: null, - }, - }); - - if (systemUnit) { - ctx.body = { - code: 400, - message: '该单位是系统预设单位,不允许添加', - }; - return; - } - - // 2. 检查当前仓库是否已存在相同名称的单位 - const existUnit = await ctx.model.StockUnit.findOne({ - where: { - name: trimmedName, - warehouse_id, - }, - }); - - if (existUnit) { - ctx.body = { - code: 400, - message: '该单位名称已存在', - }; - return; - } - - // 3. 创建单位 - const unit = await ctx.model.StockUnit.create({ - name: trimmedName, - warehouse_id, - }); - - // 4. 获取更新后的单位列表 - const where = {}; - if (warehouse_id) { - where[ctx.app.Sequelize.Op.or] = [ - { warehouse_id: null }, // 系统预设单位 - { warehouse_id }, // 当前仓库的单位 - ]; - } else { - where.warehouse_id = null; // 只显示系统预设单位 - } - - const units = await ctx.model.StockUnit.findAll({ - where, - order: [ - [ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null) - [ 'created_at', 'DESC' ], // 按创建时间倒序 - ], - }); - return this.success('添加成功', { code: 200 }); - } catch (error) { - return this.success('创建库存单位失败', { code: 200 }); - } - } - - async search(data) { - const { service } = this; - const result = await service.systems.stockStore.search(data); - return this.success('ok', result); - } -} -module.exports = indexService; diff --git a/app/service/systemMethods/stock/check.js b/app/service/systemMethods/stock/check.js new file mode 100644 index 0000000..529603b --- /dev/null +++ b/app/service/systemMethods/stock/check.js @@ -0,0 +1,1143 @@ +'use strict'; + +const MainService = require('../../main'); + +const STOCK_CHECK_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_check_export_task_'; +const STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** 单次导出任务允许的最大盘点任务数量 */ +const STOCK_CHECK_EXPORT_MAX_TASK_IDS = 50; + +/** 全部 25 个 method 名(免权限/免鉴权清单共用) */ +const ALL_METHOD_NAMES = 'create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,workDataSpaceDetails,workDataDetail,report,markEmpty,recordList,recordDelete,recheckClearLocation,finish,submit,cancel,audit,batchDelete,export,exportDetail,exportTaskProgress,patternList,patternCreate,staticLockList'; + +/** + * 系统方法层:stock.check(库存盘点模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.stockCheck 中。 + */ +class StockCheckMethodService extends MainService { + constructor(ctx) { + super(ctx); + // 免登录方法列表:空(全部需要登录) + const _noNeedLogin = ''; + // 免权限方法列表:全部 20 个方法免 API 权限校验(与 stock/transaction.js 口径一致) + const _noNeedRight = ALL_METHOD_NAMES; + // 免日志方法列表:查询类与导出类不记录操作日志(recordDelete/patternCreate 为写操作,保留操作日志) + const _noNeedLog = 'list,detail,result,workData,workDataSpaceDetails,workDataDetail,recordList,staticLockList,export,exportDetail,exportTaskProgress,patternList'; + // 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致) + const _noNeedAuth = ALL_METHOD_NAMES; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用库存盘点业务服务,并捕获业务错误码。 + * 成功/失败均按统一 data 层封装:{ flag, code, message, data }, + * 与项目 toSuccess/toFailure 常规口径一致(业务数据整体放入 data)。 + * + * @param {Function} fn 业务调用函数。 + * @param {string} fallbackMessage 兜底错误文案。 + * @return {Promise} 统一 { flag, code, message, data } 包装。 + */ + async _call(fn, fallbackMessage) { + try { + const result = await fn(); + return { flag: 'success', code: 1, message: 'ok', data: result }; + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return { flag: 'failure', code, message: error.message || fallbackMessage, data: null }; + } + this.ctx.logger.error(`[stock.check] ${fallbackMessage}: ${error && error.message ? error.message : error}`); + return { flag: 'failure', code: 500, message: '服务器内部错误', data: null }; + } + } + + /** + * 创建盘点任务(空任务)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * + * @param {Object} data 请求体。 + * @param {string} [data.title] 盘点名称/主题。 + * @param {string} [data.type] 盘点范围类型:location/store/goods,缺省 location。 + * @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘; + * 按库位盘点(location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。 + * @param {number} [data.store_id] 货主ID(按货主盘点时必填)。 + * @param {boolean|number} [data.is_static] 是否静态盘点(纯标记,0/1 或布尔;兼容 isStatic 驼峰写法; + * 缺省 0=普通盘点;仅对商品盘点有效,按库位盘点一律 0。静态盘点定式创建的任务由服务端自动置 1)。 + * @param {string} [data.remark] 备注。 + * 盘点日期固定为今天,前端不传。 + * @return {Promise} 统一 success 包装,返回新建的盘点任务信息。 + */ + async create(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; + const { + title, + type, + mode, + store_id: storeIdSnake, + storeId: storeIdCamel, + is_static: isStaticSnake, + isStatic: isStaticCamel, + remark, + } = data || {}; + const storeId = storeIdSnake !== undefined ? storeIdSnake : storeIdCamel; + const isStatic = isStaticSnake !== undefined ? isStaticSnake : isStaticCamel; + + return this._call( + () => this.service.systems.stockCheck.create({ + warehouseId, + title, + type, + mode, + storeId, + isStatic, + remark, + creatorId, + creatorName, + }), + '创建盘点任务失败' + ); + } + + /** + * 拉取盘点定式清单(供前端选择定式快速创建盘点任务)。 + * + * @return {Promise} 统一 success 包装,返回 { patterns, total }; + * patterns 每条含 id/name/description/type。 + */ + async patternList() { + return this._call( + () => this.service.systems.stockCheck.patternList(), + '拉取盘点定式失败' + ); + } + + /** + * 拉取「静态盘点锁定中」的库存商品列表(公共查询,供库存操作前置判断)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * 口径:is_static=1 且状态为 approved(审核完成)/checking(盘点作业中)任务的商品明细 stock_id 去重集合; + * 结果按仓库维度缓存(TTL 300 秒,状态流转时主动失效)。 + * + * @return {Promise} 统一 success 包装,返回 + * { warehouse_id, stock_ids, rows, total, cached, updated_at }; + * rows 每个 stock_id 一条:{ stock_id, item_code, item_name, check_ids, check_nos, location_codes }。 + */ + async staticLockList() { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + + return this._call( + () => this.service.systems.stockCheck.staticLockList({ warehouseId }), + '拉取静态盘点锁定商品列表失败' + ); + } + + /** + * 按定式快速创建盘点任务。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * 盘点方式由定式范围类型固定:库位类定式一律盲盘(blind)、商品类定式一律明盘(open); + * 盘点日期固定为今天,两者均无需前端传入。 + * + * @param {Object} data 请求体。 + * @param {string} data.pattern_id 定式ID(兼容 patternId 驼峰写法)。 + * @param {string} [data.title] 盘点名称/主题,缺省取定式 name。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装,返回 + * { check, total_items, pattern_id }。 + */ + async patternCreate(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; + const { + pattern_id: patternIdRaw, + patternId: patternIdAlias, + title, + remark, + } = data || {}; + const patternId = patternIdRaw !== undefined && patternIdRaw !== null && patternIdRaw !== '' + ? patternIdRaw + : patternIdAlias; + + return this._call( + () => this.service.systems.stockCheck.patternCreate({ + warehouseId, + patternId, + title, + remark, + creatorId, + creatorName, + }), + '按定式创建盘点任务失败' + ); + } + + /** + * 拉取盘点任务列表。 + * 按当前用户仓库(ctx.user.store_id)限定数据范围。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 查询条件。 + * @param {string|Array} [data.where.status] 状态筛选(单值或数组)。 + * @param {string|Array} [data.where.type] 范围类型筛选(location/store/goods)。 + * @param {string|Array} [data.where.mode] 盘点方式筛选(open/blind)。 + * @param {number} [data.where.store_id] 货主筛选。 + * @param {string} [data.where.keyword] 关键字(单号/标题模糊)。 + * @param {string|Array} [data.where.created_at] 创建时间筛选(单值=当天起,[from,to]=区间)。 + * @param {string|Array} [data.where.start_time] 盘点开始时间筛选。 + * @param {string|Array} [data.where.end_time] 盘点结束时间筛选。 + * @return {Promise} 统一 success 包装,返回 rows/total。 + */ + async list(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { pagination } = data || {}; + + return this._call(async () => { + const { whereValue = {} } = this.prepareWhereContext(data); + const status = whereValue.status !== undefined ? whereValue.status : data.status; + const type = whereValue.type !== undefined ? whereValue.type : data.type; + const mode = whereValue.mode !== undefined ? whereValue.mode : data.mode; + const storeId = whereValue.store_id !== undefined ? whereValue.store_id : data.store_id; + const keyword = whereValue.keyword !== undefined ? whereValue.keyword : data.keyword; + const createdAt = whereValue.created_at !== undefined ? whereValue.created_at : data.created_at; + const startTime = whereValue.start_time !== undefined ? whereValue.start_time : data.start_time; + const endTime = whereValue.end_time !== undefined ? whereValue.end_time : data.end_time; + return this.service.systems.stockCheck.list({ + warehouseId, + status, + type, + mode, + storeId, + keyword, + createdAt, + startTime, + endTime, + pagination, + }); + }, '查询盘点任务列表失败'); + } + + /** + * 添加盘点明细(按任务盘点类型添加商品或库位)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {Array} [data.stock_ids] 商品库存ID列表(wms_stock_warehouse.id,按商品盘点类型使用)。 + * @param {Array} [data.locations] 库位编码列表(按库位盘点类型使用;兼容 location_codes 写法)。 + * @param {Array} [data.location_ids] 库位ID列表(wms_location_space.id,按库位盘点类型使用; + * 兼容 locationIds 驼峰写法;与 locations 同时传入时 location_ids 优先、locations 忽略)。 + * @return {Promise} 统一 success 包装,返回新增数、跳过数与非法项列表。 + */ + async addDetail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { + id, + stock_ids: stockIds, + locations: locationsRaw, + location_codes: locationCodesRaw, + location_ids: locationIdsRaw, + locationIds: locationIdsAlias, + } = data || {}; + const locations = locationsRaw !== undefined ? locationsRaw : locationCodesRaw; + const locationIds = locationIdsRaw !== undefined ? locationIdsRaw : locationIdsAlias; + + return this._call( + () => this.service.systems.stockCheck.addDetail({ + warehouseId, + id, + stockIds, + locations, + locationIds, + }), + '添加盘点明细失败' + ); + } + + /** + * 批量添加库位明细(兼容入口,转调 addDetail 的库位ID直查路径)。 + * 入参传库位ID列表,服务端直接按 ID 查库校验,不经过 space_code 二次解析; + * 幂等添加 scope_type='location' 明细行,已存在的同库位明细自动跳过。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {Array} data.location_ids 库位ID列表(wms_location_space.id,单次上限 200; + * 兼容 locationIds 驼峰写法)。 + * @return {Promise} 统一 success 包装,返回 + * { added, skipped, invalid_location_ids, total_items }。 + */ + async addLocationDetail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, location_ids: locationIdsRaw, locationIds: locationIdsAlias } = data || {}; + const locationIds = locationIdsRaw !== undefined ? locationIdsRaw : locationIdsAlias; + + return this._call( + () => this.service.systems.stockCheck.addLocationDetail({ warehouseId, id, locationIds }), + '批量添加库位明细失败' + ); + } + + /** + * 删除盘点明细(批量:从任务中移除一个或多个商品/库位范围行)。 + * 仅主表状态 created/rejected 允许删除;明细存在作业记录时一并防御性删除; + * 查不到的明细 ID 计入 skipped_ids 不报错;删除后重算主表 total_items。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {Array|number} data.detail_ids 盘点明细ID数组(单次上限 200; + * 兼容 detailIds 驼峰写法;兼容旧版单值 detail_id 写法,单值自动转数组)。 + * @return {Promise} 统一 success 包装,返回 + * { deleted_count, deleted_ids, skipped_ids, total_items }; + * 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版 + * { detail_id, deleted, total_items } 变更为上述结构。 + */ + async detailDelete(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, detail_ids: detailIdsRaw, detailIds: detailIdsAlias, detail_id: detailIdSingle } = data || {}; + const detailIds = detailIdsRaw !== undefined + ? detailIdsRaw + : (detailIdsAlias !== undefined ? detailIdsAlias : detailIdSingle); + + return this._call( + () => this.service.systems.stockCheck.detailDelete({ + warehouseId, + id, + detailIds, + }), + '删除盘点明细失败' + ); + } + + /** + * 拉取盘点任务详情(只返回任务本身信息)。 + * 不返回明细范围行(明细范围行/盘点结果请调用 result)、作业记录(recordList) + * 与盘点作业数据(workData)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回 { check }; + * check 为盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/ + * start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/ + * remark/created_at/updated_at)。 + */ + async detail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.detail({ warehouseId, id }), + '查询盘点明细失败' + ); + } + + /** + * 拉取盘点明细结果(按范围行聚合作业记录)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回 { check, rows, total }; + * 商品行含已盘聚合(checked_quantity/diff_quantity/is_diff/status/location_codes/ + * checkers/last_checked_at)与 records(作业记录列表,每条含 barcode/item_name/images)、 + * locations(按库位聚合 [{ location_id, location_code, quantity }]); + * 库位行含 checked_quantity(行级合计)/diff_quantity(行内差异代数和)/is_diff/status + * 与 records、locations、stocks(按商品聚合,账面查 wms_storage SUM(quantity)); + * 未知商品(记录 stock_id 为空)行级输出 unknown_items [{ barcode, item_name, checked_quantity }] + * (无账面,差异 = 实盘 - 0 = 盘盈,已计入行级 checked_quantity/diff_quantity/is_diff)。 + */ + async result(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.result({ warehouseId, id }), + '查询盘点结果失败' + ); + } + + /** + * 拉取盘点作业数据(视图由任务类型与 is_goods 驱动)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * 视图规则:任务范围为库位(type=location)时一律按库位视图返回(无视 view/is_goods); + * 任务范围为商品(type=goods/store)时默认聚合库位视图(space), + * 仅传入 is_goods=true 时按商品视图(goods)返回。 + * 分页:data.pagination.{page,pageSize}(与 stock.check.list 口径一致, + * 未传或非法时默认 page=1、pageSize=20,上限 200); + * 响应 rows 为当前页行、total 为全部行数,并返回 page/pageSize。 + * 不返回任务主表信息(check)——任务信息请调用 stock.check.detail; + * 响应返回 view(服务端实际解析出的视图类型 location/goods/space),供调用方判断 rows 行结构。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {boolean} [data.is_goods] 商品任务是否按商品视图返回(true=goods); + * 缺省 false=聚合库位视图(space);库位任务无视该参数(兼容 isGoods 驼峰写法)。 + * @param {string} [data.keyword] 关键字(仅库位任务 location 视图生效):按行 + * location_code/location_name 模糊匹配(不区分大小写)过滤任务明细后返回;非库位任务忽略。 + * @param {boolean} [data.only_abnormal] 只看未盘和差异(可选,向后兼容新增,兼容 onlyAbnormal 驼峰写法): + * 过滤在 keyword 之后、分页切片之前完成,三视图均生效——location 视图仅保留 status=unchecked + * 或含未知商品记录(has_unknown=true)的行;goods 视图仅保留未盘行(locations 均无 record_ids) + * 或明盘差异行(is_diff=1,盲盘无数量字段仅按未盘过滤);space 视图按行内 goods 子项过滤 + * (status=unchecked 或明盘 checked_quantity≠system_quantity),过滤后 goods 为空的行整体移除。 + * @param {Object} [data.pagination] 分页配置 { page, pageSize }。 + * @return {Promise} 统一 success 包装,返回 { view, rows, total, page, pageSize };rows 结构按视图不同: + * location=库位结构(任务库位范围行为列表,行内挂 goods/unknown 作业记录子列表); + * goods=商品结构(按商品 stock_id 汇总,一个商品一行——同商品的库位明细行合并: + * 行内 locations 每项带该库位明细ID detail_id 与账面快照 snapshot_quantity(明盘), + * 明盘返回数量与差异,盲盘不返回数量字段;逐库位明细请调 workDataDetail(id + stock_id)); + * space=聚合库位结构(任务商品所在库位为列表,按拣货路径排序,行内挂该库位的任务商品, + * 明盘返回账面/实盘数量,盲盘不返回数量字段)。 + */ + async workData(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { + id, + is_goods: isGoodsSnake, + isGoods: isGoodsCamel, + keyword, + pagination, + only_abnormal: onlyAbnormalSnake, + onlyAbnormal: onlyAbnormalCamel, + } = data || {}; + const isGoods = isGoodsSnake !== undefined ? isGoodsSnake : isGoodsCamel; + const onlyAbnormal = onlyAbnormalSnake !== undefined ? onlyAbnormalSnake : onlyAbnormalCamel; + + return this._call( + () => this.service.systems.stockCheck.workData({ warehouseId, id, isGoods, keyword, pagination, onlyAbnormal }), + '拉取盘点作业数据失败' + ); + } + + /** + * 拉取盘点作业数据(space 视图分页版)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * 行结构与 workData space 视图行一致(id=库位ID/location_id 同义库位ID/space_code/custom_barcode/custom_name/goods, + * goods 行含 detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/ + * record_ids,明盘另含 system_quantity/checked_quantity,status=checked/unchecked); + * 传入 location_id 时只返回该库位行(total=1),不传时按分页返回全部库位行。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {number} [data.location_id] 库位ID(兼容 locationId 驼峰写法)。 + * @param {Object} [data.pagination] 分页配置 { page, pageSize }。 + * @return {Promise} 统一 success 包装,返回 { view:'space', rows, total, page, pageSize }。 + */ + async workDataSpaceDetails(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { + id, + location_id: locationIdSnake, + locationId: locationIdCamel, + pagination, + } = data || {}; + const locationId = locationIdSnake !== undefined ? locationIdSnake : locationIdCamel; + + return this._call( + () => this.service.systems.stockCheck.workDataSpaceDetails({ warehouseId, id, locationId, pagination }), + '拉取盘点作业数据失败' + ); + } + + /** + * 拉取盘点作业数据明细(库位明细单行 / 商品钻取)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * ① 库位明细(detail_id 指向 scope_type=location 的行)返回单行, + * 结构与 workData location 视图单行一致(detail_id/location_id/location_code/location_name/ + * status/has_unknown/is_empty/checked_at/checkers/goods); + * ② 商品(id=盘点任务ID + stock_id,或 detail_id 指向商品范围行)返回该商品的库位分行数据 + 汇总: + * { check_id, stock_id, item_code/item_name/spec/store_id/store_name/barcode/images, + * summary 商品级汇总(明盘含 system_quantity 账面快照合计/checked_quantity 实盘合计/ + * diff_quantity/is_diff;盲盘不含数量字段), + * rows 按库位分行(detail_id 该库位明细ID/location_id 与同义 space_id/location_code, + * 明盘另含 system_quantity 该库位当前账面/snapshot_quantity 该库位账面快照/locked_quantity/ + * checked_quantity 该库位实盘/diff_quantity 该库位差异,另有 checked_at/checker_name/record_ids/images) }。 + * + * @param {Object} data 请求体。 + * @param {number} [data.id] 盘点任务ID(商品钻取必传,与 stock_id 搭配)。 + * @param {number} [data.stock_id] 商品库存ID(商品钻取必传;兼容 stockId 驼峰写法)。 + * @param {number} [data.detail_id] 盘点明细ID(库位明细必传;商品可只传本参数按明细商品钻取; + * 兼容 detailId 驼峰写法)。 + * @return {Promise} 统一 success 包装,data 为库位单行或商品 { summary, rows } 结构。 + */ + async workDataDetail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { + id, + detail_id: detailIdSnake, + detailId: detailIdCamel, + stock_id: stockIdSnake, + stockId: stockIdCamel, + } = data || {}; + const detailId = detailIdSnake !== undefined ? detailIdSnake : detailIdCamel; + const stockId = stockIdSnake !== undefined ? stockIdSnake : stockIdCamel; + + return this._call( + () => this.service.systems.stockCheck.workDataDetail({ warehouseId, id, stockId, detailId }), + '拉取盘点明细作业数据失败' + ); + } + + /** + * 盘点作业上报(覆盖式)。 + * 同明细 + 同商品 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增; + * 未知商品(未传 stock_id 但传了 barcode):先按条码匹配系统商品,命中回填 stock_id 按已知商品处理, + * 未命中记录 stock_id=null + barcode + item_name(item_name 缺省为 barcode); + * stock_id 与 barcode 都未传沿用现有报错口径。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {number} [data.detail_id] 明细ID(可选:商品行可不传,服务端按 id + stock_id + space_id + * 反查该商品的库位明细;库位盘点行仍必传)。 + * @param {number} data.space_id 库位ID(wms_location_space.id,**必传**;兼容 spaceId / location_id / locationId 写法)。 + * 必须属于本仓库且所属分区有效;服务端以该 ID 为准落库,不再按库位编码猜库位。 + * @param {string} [data.location] 库位编码(可选,仅做一致性校验:与 space_id 对应库位编码不一致报 400)。 + * @param {number} data.quantity 实盘数量(>=0 且 <= 2147483647)。 + * @param {number} [data.stock_id] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。 + * @param {string} [data.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品,未命中记为未知商品)。 + * @param {string} [data.item_name] 未知商品名称(缺省为 barcode;已知商品忽略)。 + * @return {Promise} 统一 success 包装,返回 { record, detail_id, mode: 'created'|'updated', ...summary }; + * record 为作业记录全字段(含 barcode/item_name)。 + */ + async report(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const checkerId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const checkerName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; + const { + id, + detail_id: detailId, + location, + quantity, + stock_id: stockId, + barcode, + item_name: itemName, + is_empty: isEmpty, + space_id: spaceIdSnake, + spaceId: spaceIdCamel, + location_id: locationIdSnake, + locationId: locationIdCamel, + } = data || {}; + const spaceId = [ spaceIdSnake, spaceIdCamel, locationIdSnake, locationIdCamel ] + .find(value => value !== undefined && value !== null && value !== ''); + + return this._call( + () => this.service.systems.stockCheck.report({ + warehouseId, + id, + detailId, + location, + spaceId, + quantity, + stockId, + barcode, + itemName, + is_empty: isEmpty, + checkerId, + checkerName, + }), + '盘点作业上报失败' + ); + } + + /** + * 标记库位为空(库位盘点模式专属)。 + * warehouse_id 由服务端从当前上下文自动注入;仅任务范围为库位(type=location)时允许, + * 非库位任务报 400;状态仅 approved/checking;明细必须属于本任务且为库位范围行。 + * 行为与 report(is_empty=true) 一致:写/更新空标记记录、清除该明细商品记录、重算汇总。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {number} data.detail_id 库位明细ID。 + * @return {Promise} 统一 success 包装,返回 + * { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。 + */ + async markEmpty(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const checkerId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const checkerName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; + const { id, detail_id: detailId } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.markEmpty({ + warehouseId, + id, + detailId, + checkerId, + checkerName, + }), + '标记空库位失败' + ); + } + + /** + * 拉取盘点作业记录列表。 + * 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;按记录 id 倒序,返回分页结果。 + * + * @param {Object} data 请求体。 + * @param {number} [data.id] 盘点任务ID(可选)。 + * @param {number} [data.detail_id] 明细ID(可选,传了只查该明细)。 + * @param {Object} [data.pagination] 分页参数。 + * @return {Promise} 统一 success 包装,返回 { rows, total, page, pageSize }; + * rows 每条为记录表全字段(含 barcode/item_name)+ 商品快照列(item_code/item_name, + * 未知商品显示扫描条码与名称快照)与 images: [{ id: file_id, url }](业务类型 stock_check_record)。 + */ + async recordList(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, detail_id: detailId, pagination } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.recordList({ + warehouseId, + id, + detailId, + pagination, + }), + '查询盘点作业记录失败' + ); + } + + /** + * 批量删除盘点作业记录(按行清除盘点信息)。 + * 仅主表状态 approved/checking 允许删除;删除后重算盘点进度汇总,主表状态不回退。 + * 查不到的记录 ID 计入 skipped_ids 不报错;deleted_ids/skipped_ids 保持入参顺序。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {Array|number} data.record_ids 作业记录ID数组(单次上限 200; + * 兼容 recordIds 驼峰写法;兼容旧版单值 record_id 写法,单值自动转数组)。 + * @return {Promise} 统一 success 包装,返回 + * { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status }; + * 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版 + * { record_id, deleted, ...summary } 变更为上述结构。 + */ + async recordDelete(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { + id, + record_ids: recordIdsRaw, + recordIds: recordIdsArrayAlias, + recordId: recordIdSingleAlias, + record_id: recordIdSingleSnake, + } = data || {}; + const recordIds = recordIdsRaw !== undefined + ? recordIdsRaw + : (recordIdsArrayAlias !== undefined + ? recordIdsArrayAlias + : (recordIdSingleAlias !== undefined ? recordIdSingleAlias : recordIdSingleSnake)); + + return this._call( + () => this.service.systems.stockCheck.recordDelete({ + warehouseId, + id, + recordIds, + }), + '批量删除盘点作业记录失败' + ); + } + + /** + * 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。 + * 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记),该库位回到未盘; + * 仅任务范围为库位(type=location)且状态 approved/checking 时允许,非库位任务报 400。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {number} data.location_id 库位ID(wms_location_space.id;兼容 locationId 驼峰写法)。 + * @return {Promise} 统一 success 包装,返回 + * { detail_id, location_id, deleted_count, total_items, checked_items, diff_items, detail_status }。 + */ + async recheckClearLocation(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, location_id: locationIdRaw, locationId: locationIdAlias } = data || {}; + const locationId = locationIdRaw !== undefined ? locationIdRaw : locationIdAlias; + + return this._call( + () => this.service.systems.stockCheck.recheckClearLocation({ + warehouseId, + id, + locationId, + }), + '重盘清除库位失败' + ); + } + + /** + * 完成盘点作业(允许部分未盘完成,未盘明细按实盘 0 处理计为盘亏)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回差异汇总(含 unchecked_items 未盘明细数)。 + */ + async finish(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.finish({ warehouseId, id }), + '完成盘点作业失败' + ); + } + + /** + * 完成盘点任务(提交审核)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回最新状态。 + */ + async submit(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.submit({ warehouseId, id }), + '提交盘点任务失败' + ); + } + + /** + * 取消盘点任务。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回最新状态。 + */ + async cancel(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.cancel({ warehouseId, id }), + '取消盘点任务失败' + ); + } + + /** + * 审核盘点任务。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {string} data.action 审核动作:approve=通过,reject=驳回。 + * @param {string} [data.reason] 驳回原因(写入备注)。 + * @return {Promise} 统一 success 包装,返回最新状态。 + */ + async audit(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, action, reason } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.audit({ warehouseId, id, action, reason }), + '审核盘点任务失败' + ); + } + + /** + * 批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * + * @param {Object} data 请求体。 + * @param {Array} data.ids 盘点任务ID数组(单次上限 200)。 + * @return {Promise} 统一 success 包装,返回 + * { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。 + */ + async batchDelete(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { ids } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.batchDelete({ warehouseId, ids }), + '批量删除盘点任务失败' + ); + } + + /** + * 提交盘点任务导出任务。 + * 异步执行:查询任务与作业记录 → ExcelJS 流式写入(Sheet1=盘点单行,Sheet2=盘点明细:一行一条实际盘点记录,含商品/库位/实盘数量/盘点人/时间,不导出未盘的任务范围行)→ COS 上传。 + * 进度通过 Redis 缓存追踪,立即返回任务ID。 + * + * @param {Object} data 请求体。 + * @param {Array} [data.ids] 盘点任务ID数组(兼容 task_ids 写法,上限 50)。 + * @param {Array} [data.task_ids] 盘点任务ID数组(兼容别名)。 + * @return {Promise} 统一 success 包装,返回任务ID。 + */ + async export(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { ids, task_ids: taskIdsRaw } = data || {}; + + const idSource = ids !== undefined ? ids : taskIdsRaw; + const idList = Array.isArray(idSource) ? idSource : (idSource !== undefined ? [ idSource ] : []); + const numericIds = [ ...new Set(idList.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ]; + if (numericIds.length === 0) { + return this.fail('请至少选择一个盘点任务', {}, 400); + } + if (numericIds.length > STOCK_CHECK_EXPORT_MAX_TASK_IDS) { + return this.fail(`单次最多导出 ${STOCK_CHECK_EXPORT_MAX_TASK_IDS} 个盘点任务`, {}, 400); + } + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await this.service.systems.stockCheck.exportStockChecks({ + warehouseId, + ids: numericIds, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount || 0, + total_count: safeProgress.totalCount || 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 提交盘点明细导出任务(单任务,按盘点范围分流)。 + * 异步执行:商品范围任务固定两个 Sheet——Sheet1「汇总和差异」(每商品一行:账面快照合计/实盘合计/差异/差异类型盘盈|盘亏)+ Sheet2「库位明细」(库位编码/数量/条码/商品名称); + * 库位范围任务 Sheet「盘点明细」(库位/商品/盘点数量)→ ExcelJS 流式写入 → COS 上传。 + * 进度通过 Redis 缓存追踪,立即返回任务ID;进度查询复用 exportTaskProgress。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回任务ID。 + */ + async exportDetail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + return this.fail('盘点任务ID不能为空', {}, 400); + } + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await this.service.systems.stockCheck.exportCheckDetail({ + warehouseId, + id: checkId, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount || 0, + total_count: safeProgress.totalCount || 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询盘点任务导出进度。 + * + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一 success 包装,包含进度与下载链接。 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + // =========================== + // 导出任务辅助方法 + // =========================== + + /** + * 生成导出任务ID。 + * + * @return {string} 导出任务ID。 + */ + generateExportTaskId() { + const warehouseId = this.ctx && this.ctx.user && this.ctx.user.store_id + ? this.ctx.user.store_id + : 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `stock_check_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化导出任务ID(兼容 task_id / taskId)。 + * + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${STOCK_CHECK_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态载荷。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) + : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync( + cacheKey, + progressPayload, + STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS + ); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[stock.check.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取导出任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存,不存在则返回 null。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[stock.check.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } +} + +module.exports = StockCheckMethodService; diff --git a/app/service/systemMethods/stock/combo.js b/app/service/systemMethods/stock/combo.js new file mode 100644 index 0000000..14015da --- /dev/null +++ b/app/service/systemMethods/stock/combo.js @@ -0,0 +1 @@ +// 此处放组合商品明细的逻辑链路 diff --git a/app/service/systemMethods/stock/index.js b/app/service/systemMethods/stock/index.js new file mode 100644 index 0000000..0ea6c58 --- /dev/null +++ b/app/service/systemMethods/stock/index.js @@ -0,0 +1,21 @@ +'use strict'; + +const MainService = require('../../main'); + +class StockIndexService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'stockWarehouse'; + const _noNeedLog = 'stockWarehouse'; + const _noNeedAuth = 'stockWarehouse'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + // Legacy alias: stock.stockWarehouse -> stock.warehouse.list + async stockWarehouse(data = {}) { + return await this.ctx.service.systemMethods.stock.warehouse.list(data); + } +} + +module.exports = StockIndexService; diff --git a/app/service/systemMethods/stock/report.js b/app/service/systemMethods/stock/report.js new file mode 100644 index 0000000..d9c8436 --- /dev/null +++ b/app/service/systemMethods/stock/report.js @@ -0,0 +1,561 @@ +'use strict'; + +const MainService = require('../../main'); + +const STOCK_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_report_export_task_'; +const STOCK_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:stock.report(库存流水报表接口包装层)。 + */ +class StockReportMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'search,searchStore,export,exportStore,exportTaskProgress'; + const _noNeedLog = 'search,searchStore,export,exportStore,exportTaskProgress'; + const _noNeedAuth = 'search,searchStore,export,exportStore,exportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询库存流水统计报表。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field;白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回 + * @param {Array} [data.where.store_ids] 货主ID列表 + * @param {number|number[]} [data.where.stock_id] 商品库存ID(单数) + * @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数) + * @param {string} [data.where.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配) + * @param {Object} [data.pagination] 分页参数 { page, pageSize }(兼容 page_size);也支持顶层 data.page / data.pageSize / data.page_size(与其他 list 一致,顶层值优先);未传或非法时默认 { page: 1, pageSize: 20 },响应始终返回 data.pagination 分页信息 + * @return {Promise} 统一 success 包装 + */ + async search(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + by_space: bySpace, + store_ids: storeIds, + stock_id: stockIdRaw, + stock_ids: stockIdsRaw, + keyword, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + // 兼容 stock_id(单数,支持数组)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + // 分页参数:与项目其他 list 接口保持一致—— + // 支持 data.pagination { page, pageSize }(pageSize 兼容 page_size), + // 同时兼容顶层 data.page(分页)与 data.pageSize / data.page_size(分页大小,顶层值优先) + const { pagination: inputPagination, page: topLevelPage, pageSize: topLevelPageSize, page_size: topLevelPageSizeSnake } = data; + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + if (topLevelPage !== undefined) { + pagination.page = topLevelPage; + } + const resolvedTopLevelPageSize = topLevelPageSize !== undefined ? topLevelPageSize : topLevelPageSizeSnake; + if (resolvedTopLevelPageSize !== undefined) { + pagination.pageSize = resolvedTopLevelPageSize; + } + + const result = await service.systems.storage.report.search(startTime, endTime, bySpace, storeIds, { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }, 'warehouse', stockIds, keyword, pagination); + return this.success('ok', result); + } + + /** + * 货主侧库存流水统计报表。 + * 以货主维度查询库存流水,只关注商品入库和订单出库,不涉及库位维度。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {Array} [data.where.warehouse_ids] 仓库ID列表(可选过滤) + * @param {number|number[]} [data.where.stock_id] 商品库存ID(单数) + * @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数) + * @param {string} [data.where.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配) + * @return {Promise} 统一 success 包装 + */ + async searchStore(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + warehouse_ids: warehouseIdsRaw, + warehouse_id: warehouseIdRaw, + stock_id: stockIdRaw, + stock_ids: stockIdsRaw, + keyword, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + // 兼容 warehouse_id(单数)和 warehouse_ids(数组) + const warehouseIds = warehouseIdsRaw !== undefined + ? warehouseIdsRaw + : (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined); + + // 兼容 stock_id(单数,支持数组)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + // 货主侧不涉及库位维度(by_space 固定为 false) + const result = await service.systems.storage.report.search( + startTime, + endTime, + false, + warehouseIds, // store 模式下 storeIds 参数实际承载 warehouse_id 过滤 + { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }, + 'store', + stockIds, + keyword + ); + return this.success('ok', result); + } + + /** + * 货主侧提交库存报表导出任务。 + * 与 export 逻辑一致但使用货主维度,只关注商品入库和订单出库,不涉及库位维度。 + * 异步执行,立即返回任务ID。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {Array} [data.where.warehouse_ids] 仓库ID列表 + * @param {number|number[]} [data.where.stock_id] 商品库存ID(单数) + * @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数) + * @param {string} [data.where.keyword] 商品关键字(模糊匹配) + * @param {string} [data.export_mode] 导出模式:'item' 导出含锁定类型的全部变更记录 + * @param {string} [data.exportMode] 导出模式(驼峰写法,同 export_mode) + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async exportStore(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + warehouse_ids: warehouseIdsRaw, + warehouse_id: warehouseIdRaw, + stock_id: stockIdRaw, + stock_ids: stockIdsRaw, + keyword, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + // 兼容 warehouse_id(单数)和 warehouse_ids(数组) + const warehouseIds = warehouseIdsRaw !== undefined + ? warehouseIdsRaw + : (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined); + + // 兼容 stock_id(单数,支持数组)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const exportMode = String(data.export_mode || data.exportMode || '').trim(); + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + const sortOption = { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }; + + const onProgress = async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount ?? safeProgress.current_count ?? 0, + total_count: safeProgress.totalCount ?? safeProgress.total_count ?? 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }; + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.report.export( + startTime, endTime, false, warehouseIds, + sortOption, exportMode, 'store', stockIds, keyword, onProgress + ); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 提交库存流水统计报表导出任务(仓库侧)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回 + * @param {Array} [data.where.store_ids] 货主ID列表 + * @param {number|number[]} [data.where.stock_id] 商品库存ID(单数) + * @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数) + * @param {string} [data.where.keyword] 商品关键字(模糊匹配) + * @param {string} [data.export_mode] 导出模式:'item' 导出含锁定类型的全部变更记录,不传则排除锁定类型 + * @param {string} [data.exportMode] 导出模式(驼峰写法,同 export_mode) + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async export(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + by_space: bySpace, + store_ids: storeIds, + stock_id: stockIdRaw, + stock_ids: stockIdsRaw, + keyword, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + // 兼容 stock_id(单数,支持数组)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const exportMode = String(data.export_mode || data.exportMode || '').trim(); + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + const sortOption = { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }; + + const onProgress = async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount ?? safeProgress.current_count ?? 0, + total_count: safeProgress.totalCount ?? safeProgress.total_count ?? 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }; + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.report.export( + startTime, endTime, bySpace, storeIds, sortOption, exportMode, + 'warehouse', stockIds, keyword, onProgress + ); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询库存流水统计报表导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `stock_report_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${STOCK_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, STOCK_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[stock.report.export] 写入导出任务缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[stock.report.export] 读取导出任务缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } +} + +module.exports = StockReportMethodService; diff --git a/app/service/systemMethods/stock/store.js b/app/service/systemMethods/stock/store.js new file mode 100644 index 0000000..00eea09 --- /dev/null +++ b/app/service/systemMethods/stock/store.js @@ -0,0 +1 @@ +// 此处放货主商品明细的逻辑链路 diff --git a/app/service/systemMethods/stock/transaction.js b/app/service/systemMethods/stock/transaction.js new file mode 100644 index 0000000..1c06b0e --- /dev/null +++ b/app/service/systemMethods/stock/transaction.js @@ -0,0 +1,541 @@ +'use strict'; + +const MainService = require('../../main'); + +const STOCK_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_transaction_export_task_'; +const STOCK_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:stock.transaction(商品出入库流水查询包装层)。 + */ +class StockTransactionMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,storeList,export,exportStore,exportTaskProgress'; + const _noNeedLog = 'list,storeList,export,exportStore,exportTaskProgress'; + const _noNeedAuth = 'list,storeList,export,exportStore,exportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 仓库侧商品出入库流水列表查询。 + * 按当前用户仓库(ctx.user.store_id)限定数据范围。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + const { pagination } = data; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + store_ids: storeIds, + stock_ids: stockIdsRaw, + stock_id: stockIdRaw, + keyword, + ids, + transaction_type: transactionType, + order_type: orderType, + order_no: orderNo, + batch_no: batchNo, + entry_order_id: entryOrderId, + receiving_id: receivingId, + order_id: orderId, + } = whereValue; + + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const sortOption = { + sortField: sortFieldCamel || sortFieldSnake, + sortOrder: sortOrderCamel || sortOrderSnake, + }; + + const result = await service.systems.stockTransaction.queryList({ + warehouseId, + startTime, + endTime, + storeIds, + stockIds, + keyword, + ids, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort: sortOption, + pagination, + mode: 'warehouse', + }); + + return this.success('ok', result); + } + + /** + * 货主侧商品出入库流水列表查询。 + * 按当前登录货主的 store_id(ctx.user.store_id)限定数据范围,不接受外部传入 store_id,防止跨货主查询。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async storeList(data = {}) { + const { service } = this; + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isInteger(storeId) || storeId <= 0) { + return this.failure('无法获取当前货主身份,请重新登录'); + } + + const { pagination } = data; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + warehouse_ids: warehouseIdsRaw, + warehouse_id: warehouseIdRaw, + stock_ids: stockIdsRaw, + stock_id: stockIdRaw, + keyword, + ids, + transaction_type: transactionType, + order_type: orderType, + order_no: orderNo, + batch_no: batchNo, + entry_order_id: entryOrderId, + receiving_id: receivingId, + order_id: orderId, + } = whereValue; + + // 兼容 warehouse_id(单数)和 warehouse_ids(数组) + const warehouseIds = warehouseIdsRaw !== undefined + ? warehouseIdsRaw + : (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined); + + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const sortOption = { + sortField: sortFieldCamel || sortFieldSnake, + sortOrder: sortOrderCamel || sortOrderSnake, + }; + + const result = await service.systems.stockTransaction.queryList({ + storeId, + startTime, + endTime, + warehouseIds, + stockIds, + keyword, + ids, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort: sortOption, + pagination, + mode: 'store', + }); + + return this.success('ok', result); + } + + /** + * 仓库侧提交商品流水导出任务。 + * 与 list 使用相同查询条件,异步执行,立即返回任务ID。 + * @param {Object} data 请求体 + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async export(data = {}) { + const { service } = this; + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + store_ids: storeIds, + stock_ids: stockIdsRaw, + stock_id: stockIdRaw, + keyword, + ids, + transaction_type: transactionType, + order_type: orderType, + order_no: orderNo, + batch_no: batchNo, + entry_order_id: entryOrderId, + receiving_id: receivingId, + order_id: orderId, + } = whereValue; + + // 兼容 stock_id(单数)和 stock_ids(数组) + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + + const { sort = {} } = data; + const sortOption = { + sortField: sort.sortField || sort.sort_field, + sortOrder: sort.sortOrder || sort.sort_order, + }; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.stockTransaction.exportList({ + warehouseId, + startTime, + endTime, + storeIds, + stockIds, + keyword, + ids, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort: sortOption, + mode: 'warehouse', + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 货主侧提交商品流水导出任务。 + * 与 storeList 使用相同查询条件,异步执行,立即返回任务ID。 + * store_id 从当前登录上下文(ctx.user.store_id)获取,不接受外部传入,防止跨货主查询。 + * @param {Object} data 请求体 + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async exportStore(data = {}) { + const { service } = this; + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isInteger(storeId) || storeId <= 0) { + return this.failure('无法获取当前货主身份,请重新登录'); + } + + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + warehouse_ids: warehouseIdsRaw, + warehouse_id: warehouseIdRaw, + stock_ids: stockIdsRaw, + stock_id: stockIdRaw, + keyword, + ids, + transaction_type: transactionType, + order_type: orderType, + order_no: orderNo, + batch_no: batchNo, + entry_order_id: entryOrderId, + receiving_id: receivingId, + order_id: orderId, + } = whereValue; + + const warehouseIds = warehouseIdsRaw !== undefined + ? warehouseIdsRaw + : (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined); + + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + + const { sort = {} } = data; + const sortOption = { + sortField: sort.sortField || sort.sort_field, + sortOrder: sort.sortOrder || sort.sort_order, + }; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.stockTransaction.exportList({ + storeId, + startTime, + endTime, + warehouseIds, + stockIds, + keyword, + ids, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort: sortOption, + mode: 'store', + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询商品流水导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `stock_transaction_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${STOCK_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, STOCK_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[stock.transaction.export] 写入导出任务缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[stock.transaction.export] 读取导出任务缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } +} + +module.exports = StockTransactionMethodService; diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js new file mode 100644 index 0000000..a808798 --- /dev/null +++ b/app/service/systemMethods/stock/warehouse.js @@ -0,0 +1,1335 @@ +'use strict'; + +const MainService = require('../../main'); + +const STOCK_WAREHOUSE_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_warehouse_export_task_'; +const STOCK_WAREHOUSE_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +class WarehouseService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail,staticList'; + const _noNeedLog = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail,staticList'; + const _noNeedAuth = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail,staticList'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 归一化回收站筛选条件,兼容历史 is_deleted 字段。 + * @param {Object} where 原始 where 条件 + * @return {Object} 归一化后的 where 条件 + */ + normalizeWarehouseRecycleWhere(where = {}) { + if (!this.isPlainObject(where)) { + return {}; + } + + const normalizedWhere = { ...where }; + const recycleCondition = normalizedWhere.is_deleted; + if (!this.isPlainObject(recycleCondition)) { + return normalizedWhere; + } + + const recycleValue = recycleCondition.value; + const isDeleted = recycleValue === true + || recycleValue === 1 + || String(recycleValue || '').trim().toLowerCase() === 'true' + || String(recycleValue || '').trim() === '1'; + + normalizedWhere.deleted_at = { + operator: isDeleted ? 'isnotnull' : 'isnull', + value: isDeleted ? 1 : 0, + }; + delete normalizedWhere.is_deleted; + + return normalizedWhere; + } + + /** + * 仓库商品列表查询。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 筛选条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @return {Promise} 统一成功包装响应 + */ + async list(data = {}) { + const { service } = this; + const { pagination } = data; + const sort = data.sort || {}; + const sortParams = { + sortField: sort.sortField || sort.sort_field || 'id', + sortOrder: sort.sortOrder || sort.sort_order || 'DESC', + }; + if (this.isPlainObject(data)) { + const rawWhere = this.isPlainObject(data.where) ? data.where : {}; + data.where = this.normalizeWarehouseRecycleWhere(rawWhere); + } + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, + has_requirements: { + bucket: 'requirement', + }, + }, + }); + const result = await service.systems.stockStore.getWarehouseStock(where, pagination, sortParams); + return this.success('ok', result); + } + + /** + * 外仓商品列表查询。 + * - 传入 warehouse_id:按指定仓库维度查询 + * - 不传 warehouse_id:按当前货主维度查询(store_id = ctx.user.store_id) + * @param {Object} data 请求体 + * @param {number} [data.warehouse_id] 仓库ID(可选) + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 筛选条件 + * @return {Promise} 统一成功包装响应 + */ + async externalList(data = {}) { + const { service, ctx } = this; + const warehouseId = Number(data.warehouse_id || data.warehouseId || 0); + const { pagination } = data; + const sort = data.sort || {}; + const sortParams = { + sortField: sort.sortField || sort.sort_field || 'id', + sortOrder: sort.sortOrder || sort.sort_order || 'DESC', + }; + if (this.isPlainObject(data)) { + const rawWhere = this.isPlainObject(data.where) ? data.where : {}; + data.where = this.normalizeWarehouseRecycleWhere(rawWhere); + } + // 传入 warehouse_id 时合并到 where 条件中 + if (warehouseId > 0) { + data.where = { + ...(data.where || {}), + warehouse_id: { operator: 'eq', value: warehouseId }, + }; + } + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, + has_requirements: { + bucket: 'requirement', + }, + }, + }); + // 始终按当前货主维度查(store_id = self) + const result = await service.systems.stockStore.getWarehouseStock(where, pagination, sortParams, 0, ctx.user.store_id); + return this.success('ok', result); + } + + /** + * 提交外仓商品导出任务(复用 externalList 的筛选语义与排序规则)。 + * - 传入 warehouse_id:按指定仓库维度导出 + * - 不传 warehouse_id:按当前货主维度导出(store_id = ctx.user.store_id) + * @param {Object} data 请求体 + * @param {number} [data.warehouse_id] 仓库ID(可选) + * @param {Object} [data.where] 筛选条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async externalExport(data = {}) { + const { service, ctx } = this; + const warehouseId = Number(data.warehouse_id || data.warehouseId || 0); + const sort = data.sort || {}; + const sortField = sort.sortField || sort.sort_field; + const sortOrder = sort.sortOrder || sort.sort_order; + const sortParams = { + ...(sortField ? { sortField } : {}), + ...(sortOrder ? { sortOrder } : {}), + }; + + if (this.isPlainObject(data)) { + const rawWhere = this.isPlainObject(data.where) ? data.where : {}; + data.where = this.normalizeWarehouseRecycleWhere(rawWhere); + } + // 传入 warehouse_id 时合并到 where 条件中 + if (warehouseId > 0) { + data.where = { + ...(data.where || {}), + warehouse_id: { operator: 'eq', value: warehouseId }, + }; + } + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, + has_requirements: { + bucket: 'requirement', + }, + }, + }); + + const taskId = this.generateExportTaskId('external'); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '外仓导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '外仓导出任务执行中', + result: null, + error: '', + }); + + // 始终按当前货主维度导出(store_id = self) + const result = await service.systems.stockStore.exportExternalWarehouseStock(where, sortParams, warehouseId, ctx.user.store_id); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '外仓导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '外仓导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 提交仓库商品导出任务(复用 list 的筛选语义与排序规则)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async export(data = {}) { + const { service } = this; + if (this.isPlainObject(data)) { + const rawWhere = this.isPlainObject(data.where) ? data.where : {}; + data.where = this.normalizeWarehouseRecycleWhere(rawWhere); + } + const { where, whereValue = {} } = this.prepareWhereContext(data, { + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, + has_requirements: { + bucket: 'requirement', + }, + }, + }); + + const { sort = {} } = data; + const sortField = sort.sortField || sort.sort_field || whereValue.sortField || whereValue.sort_field; + const sortOrder = sort.sortOrder || sort.sort_order || whereValue.sortOrder || whereValue.sort_order; + const sortParams = { + ...(sortField ? { sortField } : {}), + ...(sortOrder ? { sortOrder } : {}), + }; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.stockStore.exportWarehouseStock(where, sortParams); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询仓库商品导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成仓库商品导出任务ID。 + * @param {string} [prefix=''] 任务类型前缀(如 'external') + * @return {string} 导出任务ID + */ + generateExportTaskId(prefix = '') { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const typePrefix = prefix ? `${prefix}_` : ''; + return `stock_warehouse_${typePrefix}export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化仓库商品导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取仓库商品导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${STOCK_WAREHOUSE_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入仓库商品导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, STOCK_WAREHOUSE_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[stock.warehouse.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取仓库商品导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[stock.warehouse.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + + /** + * 查询违禁品类型列表(系统预设 + 当前仓库)。 + * @return {Promise} data 为违禁品类型数组 + */ + async getProhibitedType() { + const { service } = this; + const result = await service.systems.stockStore.getProhibitedType(); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 按商品条件获取仓库商品详情。 + * @param {Object} data 请求体(常见包含 id/item_code) + * @return {Promise} data 为单个商品详情对象 + */ + async getInfo(data) { + const { service } = this; + const result = await service.systems.stockStore.getInfo(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 更新仓库商品资料。 + * @param {Object} data 请求体(含商品主键与可编辑字段) + * @return {Promise} data 为更新结果 + */ + async saveWarehouseStock(data) { + const { service } = this; + const { + id, + item_code, + item_name, + goods_code, + sku_property, + stock_unit, + packing_requirements, + pick_requirements, + recheck_requirements, + merge_requirements, + length, + width, + height, + volume, + volume_cm3, + volumeCm3, + gross_weight, + net_weight, + tag_price, + retail_price, + is_sn_mgmt, + is_shelf_life_mgmt, + is_batch_mgmt, + need_recheck, + prohibited_id, + brand_name, + managementFlags, + enable_box_spec, + box_unit, + quantity_per_box, + box_gross_weight, + box_net_weight, + box_length, + box_width, + box_height, + box_volume, + box_volume_m3, + boxVolumeM3, + box_remark, + shelf_life_days, + inbound_min_days, + outbound_min_days, + remaining_threshold_days, + warning_quantity, + sn_code_rules, + snCodeRules, + } = data || {}; + try { + const result = await service.systems.stockStore.saveWarehouseStock({ + id, + item_code, + item_name, + goods_code, + sku_property, + stock_unit, + packing_requirements, + pick_requirements, + recheck_requirements, + merge_requirements, + length, + width, + height, + volume, + volume_cm3, + volumeCm3, + gross_weight, + net_weight, + tag_price, + retail_price, + is_sn_mgmt, + is_shelf_life_mgmt, + is_batch_mgmt, + need_recheck, + prohibited_id, + brand_name, + managementFlags, + enable_box_spec, + box_unit, + quantity_per_box, + box_gross_weight, + box_net_weight, + box_length, + box_width, + box_height, + box_volume, + box_volume_m3, + boxVolumeM3, + box_remark, + shelf_life_days, + inbound_min_days, + outbound_min_days, + remaining_threshold_days, + warning_quantity, + sn_code_rules, + snCodeRules, + }); + return this.success('ok', { data: result, code: 200 }); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 新建仓库商品资料。 + * @param {Object} data 请求体(必填字段见 stockStore 校验) + * @return {Promise} data 为新建结果 + */ + async createWarehouseStock(data) { + const { service } = this; + const result = await service.systems.stockStore.createWarehouseStock(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 导入仓库商品资料。 + * + * 支持直接传数组,也支持从 rows、items、list、data 中提取数组。 + * SKU 为空时创建,SKU 不为空时更新,并返回批量处理结果汇总。 + * + * @param {Object|Array} data 导入请求体或商品数组 + * @return {Promise} 导入结果汇总 + */ + async import(data = {}) { + const { service } = this; + const rows = this._normalizeWarehouseImportRows(data); + const summary = { + total_count: rows.length, + created_count: 0, + updated_count: 0, + fail_count: 0, + created_ids: [], + updated_ids: [], + fail_items: [], + }; + + if (rows.length === 0) { + return this.fail('导入数据不能为空', summary); + } + + for (let index = 0; index < rows.length; index += 1) { + const sourceRow = rows[index]; + const normalizedRow = this._normalizeWarehouseImportRow(sourceRow); + + if (!normalizedRow) { + summary.fail_count += 1; + summary.fail_items.push({ + index, + row: sourceRow, + error: '导入行数据无效', + }); + continue; + } + + try { + const hasSku = String(normalizedRow.id ?? '').trim() !== ''; + let result; + + if (hasSku) { + result = await service.systems.stockStore.saveWarehouseStock(normalizedRow); + } else { + result = await service.systems.stockStore.createWarehouseStock(normalizedRow); + } + + // 条码同步:仅当传入非空条码时写入 wms_stock_barcodes 表(未传条码则保留原有条码) + const barcodes = Array.isArray(normalizedRow.barcode) ? normalizedRow.barcode : []; + if (barcodes.length > 0) { + const stockId = (result && result.id != null) ? result.id : normalizedRow.id; + if (stockId != null) { + await service.systems.stockStore.saveWarehouseStockBarcode({ + id: stockId, + barcodes, + }); + } + } + + if (hasSku) { + summary.updated_count += 1; + if (result && result.id != null) { + summary.updated_ids.push(result.id); + } else { + summary.updated_ids.push(normalizedRow.id); + } + } else { + summary.created_count += 1; + if (result && result.id != null) { + summary.created_ids.push(result.id); + } + } + } catch (error) { + summary.fail_count += 1; + summary.fail_items.push({ + index, + row: normalizedRow, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + if (summary.created_count + summary.updated_count === 0) { + return this.fail('导入失败', summary); + } + + return this.success('导入完成', summary); + } + + /** + * 归一化仓库商品导入数据列表。 + * + * @param {Object|Array} data 导入请求体或商品数组 + * @return {Array} 商品数组 + */ + _normalizeWarehouseImportRows(data = {}) { + if (Array.isArray(data)) { + return data; + } + + if (!this.isPlainObject(data)) { + return []; + } + + const candidates = [ data.rows, data.items, data.list, data.data ]; + for (const candidate of candidates) { + if (Array.isArray(candidate)) { + return candidate; + } + } + + return []; + } + + /** + * 归一化单条仓库商品导入数据。 + * + * @param {Object} row 原始导入行 + * @return {Object|null} 归一化后的数据行 + */ + _normalizeWarehouseImportRow(row) { + if (!this.isPlainObject(row)) { + return null; + } + + const pickValue = keys => { + for (const key of keys) { + if (!Object.prototype.hasOwnProperty.call(row, key)) { + continue; + } + + const value = row[key]; + if (value === undefined || value === null) { + continue; + } + + if (typeof value === 'string' && value.trim() === '') { + continue; + } + + return value; + } + return undefined; + }; + + const sku = pickValue([ 'SKU', 'sku', 'id', 'item_id', 'itemId', 'stock_id', 'stockId' ]); + const itemCode = pickValue([ '商品编码', 'item_code', 'itemCode' ]) ?? ''; + const goodsCode = pickValue([ '货物编码', 'goods_code', 'goodsCode', 'cargo_code', 'cargoCode' ]) ?? ''; + const itemName = pickValue([ '商品名称', 'item_name', 'itemName' ]) + ?? itemCode + ?? goodsCode + ?? ''; + const storeId = pickValue([ 'store_id', 'storeId' ]) ?? this.ctx?.user?.store_id; + const needRecheckRaw = pickValue([ '是否需要复核', 'need_recheck', 'needRecheck' ]); + + return { + ...row, + id: sku, + store_id: storeId, + item_code: itemCode, + goods_code: goodsCode, + item_name: itemName, + sku_property: pickValue([ 'SKU规格', 'sku_property', 'skuProperty' ]) ?? '', + stock_unit: pickValue([ '库存单位', 'stock_unit', 'stockUnit' ]) ?? '', + brand_name: pickValue([ '品牌', 'brand_name', 'brandName' ]) ?? '', + gross_weight: pickValue([ '毛重', 'gross_weight', 'grossWeight' ]), + tag_price: pickValue([ '标价', 'tag_price', 'tagPrice' ]), + retail_price: pickValue([ '零售价', 'retail_price', 'retailPrice' ]), + ...(needRecheckRaw !== undefined && { need_recheck: this._normalizeNeedRecheckValue(needRecheckRaw) }), + barcode: this._normalizeBarcodeField( + pickValue([ '条码', 'bar_code', 'barCode', 'barcodeList', 'barcode_list', 'barcode' ]) + ), + }; + } + + /** + * 归一化「是否需要复核」字段值:需要 → Y,不需要 → N。 + * 支持中文(需要/需要复核/不需要/无需复核)、Y/N、1/0、布尔值。 + * + * @param {string|number|boolean} raw 原始值 + * @return {string} 'Y' 或 'N' + */ + _normalizeNeedRecheckValue(raw) { + const normalized = String(raw ?? '').trim(); + if ([ '需要', '需要复核', 'Y', 'y', '1' ].includes(normalized) || raw === true) { + return 'Y'; + } + if ([ '不需要', '无需', '无需复核', 'N', 'n', '0' ].includes(normalized) || raw === false) { + return 'N'; + } + throw new Error(`是否需要复核值不合法: ${raw},仅支持 需要/不需要`); + } + + /** + * 归一化条码字段,只接受逗号分隔的字符串格式,返回去重后的条码数组。 + * 与 stock.warehouse.export 导出格式对齐(导出使用逗号分隔)。 + * + * @param {string|undefined|null} raw 原始条码值(逗号分隔字符串) + * @return {Array} 归一化后的去重条码数组 + */ + _normalizeBarcodeField(raw) { + if (typeof raw === 'string' && raw.trim()) { + return [ ...new Set(raw.split(',').map(s => s.trim()).filter(Boolean)) ]; + } + return []; + } + + /** + * 查询商品条码列表。 + * @param {Object} data 请求体(支持分页与关键字) + * @return {Promise} data 为条码分页结果 + */ + async getBarcodes(data) { + const { service } = this; + const result = await service.systems.stockStore.getBarcodes(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 保存商品条码信息。 + * @param {Object} data 请求体(包含 stock_id 与条码字段) + * @return {Promise} data 为保存结果 + */ + async saveWarehouseStockBarcode(data) { + const { service } = this; + const result = await service.systems.stockStore.saveWarehouseStockBarcode(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 查询仓库与货主商品关联列表。 + * @param {Object} data 请求体(支持筛选/分页) + * @return {Promise} data 为关联分页结果 + */ + async getStoreStocks(data) { + const { ctx, service } = this; + // 校验归属:stock_warehouse 的 store_id 或 warehouse_id 匹配当前主体即可放行 + const stockId = Number(data.stock_id || 0); + if (stockId > 0) { + const stock = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId }, + attributes: [ 'id', 'store_id', 'warehouse_id' ], + raw: true, + }); + if (!stock + || (stock.store_id !== ctx.user.store_id && stock.warehouse_id !== ctx.user.store_id)) { + return this.fail('无权限查看该商品的绑定信息', { code: 403 }); + } + // 使用实际的 warehouse_id 查询 + data._warehouseId = stock.warehouse_id; + } + const result = await service.systems.stockStore.getStoreStocks(data); + return this.success('ok', { data: result, code: 200 }); + } + + /** + * 绑定货主商品。 + * @param {Object} data 请求体(关联关系参数) + * @return {Promise} 成功或失败均返回 success 包装,message 给出结果 + */ + async bindItem(data) { + const { service } = this; + const { id, warehouse_stock } = data || {}; + try { + const result = await service.systems.stockStore.bindItem({ + id, + warehouse_stock, + }); + return this.success('绑定成功', { data: result, code: 200 }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } + + /** + * 解绑货主商品。 + * @param {Object} data 请求体(关联关系参数) + * @return {Promise} 成功或失败均返回 success 包装,message 给出结果 + */ + async unbindItem(data) { + const { service } = this; + const { id } = data || {}; + try { + const result = await service.systems.stockStore.unbindItem({ id }); + return this.success('解绑成功', { data: result, code: 200 }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } + + /** + * 校验商品编码唯一性。 + * @param {Object} data 请求体 + * @param {number} [data.item_id] 商品ID(编辑场景,排除自身) + * @param {number} [data.id] 兼容旧字段的商品ID + * @param {string} data.item_code 商品编码 + * @param {number} data.owner_id 货主ID + * @param {number} [data.store_id] 兼容旧字段的货主ID + * @param {number} data.warehouse_id 仓库ID + * @return {Promise} data.unique 为是否唯一,重复时返回提示信息 + */ + async checkItemCodeUnique(data) { + const { ctx, service } = this; + const { + item_id, + id, + item_code, + owner_id, + store_id, + warehouse_id, + } = data || {}; + const targetItemId = item_id || id || null; + const targetOwnerId = owner_id || store_id; + const targetWarehouseId = warehouse_id || ctx.user.store_id; + try { + if (!item_code || !targetOwnerId || !targetWarehouseId) { + return this.fail('参数错误'); + } + const result = await service.systems.stockStore.checkItemCodeUnique( + targetItemId, + item_code, + targetOwnerId, + targetWarehouseId + ); + return this.success('获取成功', { data: result, code: 200 }); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 查询静态商品列表(仓库级)。 + * 静态判定:商品最后一个收/发流水时间超过仓库配置的静态时间阈值即视为进入静态。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数(page/pageSize) + * @param {number} [data.hours] 静态时间阈值(小时),缺省读仓库配置 stock_static_hours(默认 168) + * @return {Promise} data 为 { list, pagination } + */ + async staticList(data = {}) { + const { ctx, service } = this; + const pagination = this.isPlainObject(data.pagination) ? data.pagination : data; + const result = await service.systems.stockWarehouse.getStaticStockList({ + warehouseId: ctx.user && ctx.user.store_id, + hours: data.hours, + page: Number(pagination.page || 1), + pageSize: Number(pagination.pageSize || 20), + }); + return this.success('ok', result); + } + + /** + * 查询库存操作日志。 + * @param {Object} data 请求体(会自动注入当前 warehouseId) + * @return {Promise} data 为日志分页结果 + */ + async queryStockLogs(data) { + const { ctx, service } = this; + try { + const stockId = Number(data.id || 0); + if (stockId > 0) { + // 校验 stock_warehouse:store_id 或 warehouse_id 匹配当前主体即可放行 + const stock = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId }, + attributes: [ 'id', 'store_id', 'warehouse_id' ], + raw: true, + }); + if (!stock + || (stock.store_id !== ctx.user.store_id && stock.warehouse_id !== ctx.user.store_id)) { + return this.fail('无权限查看该商品的库存日志', { code: 403 }); + } + data.warehouseId = stock.warehouse_id; + } else { + data.warehouseId = ctx.user.store_id; + } + const result = await service.systems.operationLog.queryStockLogs(data); + return this.success('ok', { data: result, code: 200 }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } + + /** + * 批量删除仓库商品资料(软删除)。 + * @param {Object} data 请求体(含 ids) + * @return {Promise} data 为删除结果,message 为业务提示 + */ + async handleBatchDelete(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.handleBatchDelete(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } + + /** + * 删除库存单位。 + * @param {Object} data 请求体(含单位ID) + * @return {Promise} data 为删除结果,message 为业务提示 + */ + async deleteUnit(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.deleteUnit(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } + + /** + * 删除违禁品类型。 + * @param {Object} data 请求体(含类型ID) + * @return {Promise} data 为删除结果,message 为业务提示 + */ + async deleteProhibited(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.deleteProhibited(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + return this.success(e.message, { code: 200 }); + } + } + + /** + * 批量修改商品资料字段。 + * @param {Object} data 请求体(含 ids/method/value) + * @return {Promise} data 为修改结果,message 为业务提示 + */ + async handleBatchChange(data) { + const { service } = this; + try { + const result = await service.systems.stockStore.handleBatchChange(data); + return this.success(result.message, { data: result.data, code: result.code }); + } catch (e) { + return this.success(e.message, { code: 405 }); + } + } + + /** + * 查询可用库存单位(系统预设 + 仓库自定义)。 + * @return {Promise} data 为单位数组 + */ + async getStockUnits() { + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + + try { + const where = { + [ctx.app.Sequelize.Op.or]: [ + { warehouse_id: null }, + { warehouse_id }, + ], + }; + + const units = await ctx.model.StockUnit.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('ok', { data: units, code: 200 }); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 查询当前仓库自定义单位列表。 + * @return {Promise} data 为单位数组 + */ + async getUnitList() { + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + + try { + const where = { + warehouse_id, + }; + + const units = await ctx.model.StockUnit.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('ok', { data: units, code: 200 }); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 新增违禁品类型。 + * @param {Object} data 请求体 + * @param {string} data.name 违禁品类型名称 + * @return {Promise} 成功返回 success;参数校验失败时直接写入 ctx.body + */ + async createProhibited(data) { + const { ctx } = this; + const warehouse_id = ctx.user.store_id || null; + const { name } = data; + + if (!name || name.trim() === '') { + ctx.body = { + code: 400, + message: '违禁品类型名称不能为空', + }; + return; + } + + const trimmedName = name.trim(); + + try { + const systemUnit = await ctx.model.ProhibitedType.findOne({ + where: { + type_name: trimmedName, + warehouse_id: null, + }, + }); + + if (systemUnit) { + ctx.body = { + code: 400, + message: '该违禁品类型是系统预设,不允许添加', + }; + return; + } + + const existUnit = await ctx.model.ProhibitedType.findOne({ + where: { + type_name: trimmedName, + warehouse_id, + }, + }); + + if (existUnit) { + ctx.body = { + code: 400, + message: '该违禁品类型名称已存在', + }; + return; + } + + await ctx.model.ProhibitedType.create({ + type_name: trimmedName, + warehouse_id, + }); + + const where = {}; + if (warehouse_id) { + where[ctx.app.Sequelize.Op.or] = [ + { warehouse_id: null }, + { warehouse_id }, + ]; + } else { + where.warehouse_id = null; + } + + await ctx.model.ProhibitedType.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('添加成功', { code: 200 }); + } catch (error) { + return this.success('创建违禁品类型失败', { code: 405 }); + } + } + + /** + * 新增库存单位。 + * @return {Promise} 成功返回 success;参数校验失败时直接写入 ctx.body + */ + async createUnit() { + const { ctx } = this; + const warehouse_id = ctx.user.store_id || null; + const { name } = ctx.request.body; + + if (!name || name.trim() === '') { + ctx.body = { + code: 400, + message: '单位名称不能为空', + }; + return; + } + + const trimmedName = name.trim(); + + try { + const systemUnit = await ctx.model.StockUnit.findOne({ + where: { + name: trimmedName, + warehouse_id: null, + }, + }); + + if (systemUnit) { + ctx.body = { + code: 400, + message: '该单位是系统预设单位,不允许添加', + }; + return; + } + + const existUnit = await ctx.model.StockUnit.findOne({ + where: { + name: trimmedName, + warehouse_id, + }, + }); + + if (existUnit) { + ctx.body = { + code: 400, + message: '该单位名称已存在', + }; + return; + } + + await ctx.model.StockUnit.create({ + name: trimmedName, + warehouse_id, + }); + + const where = {}; + if (warehouse_id) { + where[ctx.app.Sequelize.Op.or] = [ + { warehouse_id: null }, + { warehouse_id }, + ]; + } else { + where.warehouse_id = null; + } + + await ctx.model.StockUnit.findAll({ + where, + order: [ + [ 'warehouse_id', 'ASC' ], + [ 'created_at', 'DESC' ], + ], + }); + return this.success('添加成功', { code: 200 }); + } catch (error) { + return this.success('创建库存单位失败', { code: 200 }); + } + } + + /** + * 快捷搜索仓库商品,当 mode='combo' 时桥接到组合商品查询。 + * @param {Object} data 请求体 + * @param {string} [data.mode] 查询模式,'combo' 时搜索组合商品,默认搜索普通商品 + * @param {string} [data.keyword] 搜索关键字(默认模式) + * @param {number} [data.id] 组合商品ID(mode='combo' 时精确查询) + * @param {string} [data.custom_code] 自定义编码(mode='combo' 时模糊查询) + * @param {number} [data.store_id] 货主ID(默认模式) + * @param {boolean} [data.with_stock] 是否返回库存数据(默认模式) + * @param {boolean} [data.is_batch] 是否按批次返回(默认模式) + * @return {Promise} data 为搜索结果数组(默认模式)或组合商品列表(combo 模式) + */ + async search(data) { + const { service } = this; + const { mode } = data || {}; + + if (mode === 'combo') { + const { id, custom_code, keyword } = data || {}; + if (keyword) { + const result = await service.systems.comboGoods.search({ keyword }); + return this.success('ok', result); + } + const result = await service.systems.comboGoods.searchByIdOrCode({ id, custom_code }); + return this.success('ok', result); + } + + const result = await service.systems.stockStore.search(data); + return this.success('ok', result); + } + + /** + * 查询商品库存明细(按库位/批次维度展示库存分布)。 + * @param {Object} data 请求体 + * @param {number} data.stock_id 商品库存ID(stock_warehouse.id) + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} data 为库存明细分页结果 + */ + async getStockDetail(data) { + const { service } = this; + const result = await service.systems.stockStore.getStockDetail(data); + return this.success('ok', result); + } +} + +module.exports = WarehouseService; diff --git a/app/service/systemMethods/storage/delivery.js b/app/service/systemMethods/storage/delivery.js new file mode 100644 index 0000000..7ebcbbe --- /dev/null +++ b/app/service/systemMethods/storage/delivery.js @@ -0,0 +1,47 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.delivery(兼容层)。 + * 历史调用兼容:统一转发到 storage.stockout,避免继续以 delivery 命名承载非订单出库语义。 + */ +class StorageDeliveryService extends MainService { + 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); + } + + /** + * 出库单列表查询(兼容转发)。 + * @param {Object} data 请求体 + * @return {Promise} 出库单列表结果 + */ + async list(data = {}) { + return await this.ctx.service.systemMethods.storage.stockout.list(data); + } + + /** + * 出库单转订单(兼容转发)。 + * @param {Object} data 请求体 + * @return {Promise} 转订单结果 + */ + async toOrder(data = {}) { + return await this.ctx.service.systemMethods.storage.stockout.toOrder(data); + } + + /** + * 拉取出库单明细(兼容转发)。 + * @param {Object} data 请求体 + * @return {Promise} 订单/出库单明细结果 + */ + async listItems(data = {}) { + return await this.ctx.service.systemMethods.storage.stockout.listItems(data); + } +} + +module.exports = StorageDeliveryService; diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js new file mode 100644 index 0000000..3d5d04b --- /dev/null +++ b/app/service/systemMethods/storage/entry.js @@ -0,0 +1,794 @@ +'use strict'; +const MainService = require('../../main'); + +const ENTRY_EXPORT_TASK_CACHE_KEY_PREFIX = 'entry_export_task_'; +const ENTRY_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:storage.entry(入库单相关接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 + * 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。 + */ +class entryService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,listStore,get,getStore,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedLog = 'list,listStore,get,getStore,getPrintData,reviewEntry,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedAuth = 'list,listStore,get,getStore,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 入库单列表查询。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 动态筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.storage.entry.list(where, pagination, sort); + return this.success('ok', result); + } + + /** + * 货主侧入库单列表查询。 + * 与 list 共享底层逻辑,但以货主维度(store_id)过滤,不使用仓库维度(warehouse_id)。 + * 货主登录后仅能看到自己货主下的入库单。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 动态筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async listStore(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.storage.entry.list(where, pagination, sort, 'store'); + + // 裁剪货主侧冗余字段:货主自己的 store_name/store 关联、奇门编码 + if (result && result.data && Array.isArray(result.data.list)) { + result.data.list.forEach(item => { + delete item.store_name; + delete item.store; + delete item.qimen_owner_code; + delete item.qimen_warehouse_code; + }); + } + return this.success('ok', result); + } + + /** + * 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。 + * 返回入库单基本信息(id、entry_order_code、order_status、store_remask)、 + * 商品明细列表(含计划数量、已完成入库数量、商品信息、收货单绑定明细), + * 以及收货单绑定关系列表。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID(必填) + * @return {Promise} 统一 success 包装 + */ + async get(data = {}) { + const { service } = this; + const { id } = data || {}; + const result = await service.systems.storage.entry.get({ id }); + return this.success('ok', result); + } + + /** + * 货主侧查询入库单详情。与 get 共享底层逻辑, + * 但以货主维度(store_id)校验权限(不使用 warehouse_id), + * 货主登录后仅能查看自己货主下的入库单明细。 + * 返回结构与 get 一致。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID(必填) + * @return {Promise} 统一 success 包装 + */ + async getStore(data = {}) { + const { service } = this; + const { id } = data || {}; + const result = await service.systems.storage.entry.get({ id }, 'store'); + return this.success('ok', result); + } + + /** + * 作废入库单。 + * 支持传入单个 id 或批量 ids,保持透传给业务层处理。 + * @param {Object} data 请求体 + * @param {number} [data.id] 单个入库单ID + * @param {number[]} [data.ids] 批量入库单ID数组 + * @return {Promise} 统一 success 包装 + */ + async cancel(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.cancel(data); + return this.success('ok', result); + } + + /** + * 按商品增量添加导入/PDA 直接入库记录(从 storage.entry 模块暴露)。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number} [data.stock_id] 商品SKU ID(单条模式) + * @param {number} [data.quantity] 本次入库数量(单条模式) + * @param {string} [data.inbound_type] 入库方式(单条模式) + * @param {Array} [data.items] 商品列表(批量模式) + * @param {string} [data.remark] 备注(单条模式) + * @param {number} [data.space_id] 库位ID(单条模式) + * @param {number} [data.receiving_detail_id] 收货单明细ID(单条模式,可选) + * @param {number} [data.allocated_quantity] 预分配数量(单条模式,可选) + * @return {Promise} 统一 success 包装 + */ + async addItem(data = {}) { + const { service } = this; + const { + entry_order_id, + stock_id, + quantity, + inbound_type, + items, + remark, + space_id, + receiving_detail_id, + allocated_quantity, + } = data || {}; + const result = await service.systems.inboundDirectLog.addItem({ + entry_order_id, + stock_id, + quantity, + inbound_type, + items, + remark, + space_id, + receiving_detail_id, + allocated_quantity, + }); + return this.success('ok', result); + } + + /** + * 提交确认完成导入/PDA 直接入库(从 storage.entry 模块暴露)。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单 ID + * @param {number} [data.noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0) + * @return {Promise} 统一 success 包装 + */ + async commit(data = {}) { + const { service } = this; + const { entry_order_id, noNeedNotice = 0 } = data || {}; + const result = await service.systems.inboundDirectLog.commit(entry_order_id, noNeedNotice); + return this.success('ok', result); + } + + /** + * 移除一条导入/PDA 直接入库记录(从 storage.entry 模块暴露)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库记录ID + * @return {Promise} 统一 success 包装 + */ + async removeItem(data = {}) { + const { service } = this; + const result = await service.systems.inboundDirectLog.removeItem(data); + return this.success('ok', result); + } + + /** + * 绑定入库单与收货单的主表关系(仅主表绑定,不做明细分配)。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 收货单 ID 列表 + * @return {Promise} 统一 success 包装 + */ + async bindReceiving(data = {}) { + const { ctx } = this; + console.log('[DEBUG] systems keys:', Object.keys(ctx.service.systems)); + console.log('[DEBUG] receiving_entry_match:', typeof ctx.service.systems.receivingEntryMatch); + const { entry_order_id, receiving_ids } = data || {}; + const creator_id = ctx.user ? ctx.user.id || ctx.user.user_id : undefined; + const result = await ctx.service.systems.receivingEntryMatch.bindEntryOrderReceiving({ + entry_order_id, + receiving_ids, + creator_id, + }); + return this.success('绑定完成', result); + } + + /** + * 解除入库单与收货单的绑定关系。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 要解除绑定的收货单 ID 列表 + * @return {Promise} 统一 success 包装 + */ + async unbindReceiving(data = {}) { + const { ctx } = this; + const { entry_order_id, receiving_ids } = data || {}; + const result = await ctx.service.systems.receivingEntryMatch.unbindEntryOrderReceiving({ + entry_order_id, + receiving_ids, + }); + return this.success('解绑完成', result); + } + + /** + * 快捷直入/虚拟入库(system method 包装层)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @param {number} [data.noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0) + * @return {Promise} 统一 success 包装 + */ + async quickInbound(data = {}) { + const { service } = this; + const { id, noNeedNotice = 0 } = data; + const result = await service.systems.storage.entry.quickInbound({ id, noNeedNotice }); + if (result && result.code === 200) { + return this.success(result.message || 'ok', result); + } + return this.fail(result?.message || '快捷入库失败', result); + } + + /** + * 获取入库单打印数据,按 RECEIPT 模板 field_code 映射返回。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @param {number} [data.warehouse_id] 仓库ID,不传则取当前用户仓库 + * @return {Promise} 打印数据(扁平键值 + items 明细数组) + */ + async getPrintData(data = {}) { + const { ctx } = this; + const id = Number(data && data.id || 0); + if (!id) { + return this.fail('id 参数不能为空', { code: 400 }); + } + + try { + // 直接查询入库单完整信息(含 items、warehouse、store 等关联),供打印模板使用 + const entryOrder = await ctx.model.EntryOrder.findByPk(id, { + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name' ], + required: false, + }, + { + model: ctx.model.EntryItems, + as: 'items', + required: false, + }, + ], + }); + + if (!entryOrder || entryOrder.warehouse_id !== ctx.user.store_id || !entryOrder.is_enabled) { + return this.fail('入库单不存在', { code: 404 }); + } + + const entryOrderJSON = entryOrder.toJSON(); + const items = Array.isArray(entryOrderJSON.items) ? entryOrderJSON.items : []; + + // 查询商品条码和图片(复用 getStockDetails 缓存) + const barcodeMap = new Map(); + const imageMap = new Map(); + try { + const stockIds = items + .map(item => Number(item.stock_id || 0)) + .filter(sid => sid > 0); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + {} + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + // 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + barcodeMap.set( + sid, + detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) + ); + } + // 提取图片(有图片标记但实际 URL 需要额外查询) + if (detail.is_images === 'Y') { + imageMap.set(sid, ''); + } + } + } + } catch (err) { + ctx.logger.warn('[entry.getPrintData] 查询商品详情失败: %s', err.message); + } + + const printData = { + entry_order_code: entryOrderJSON.entry_order_code || '', + order_type: entryOrderJSON.order_type || '', + order_status: entryOrderJSON.order_status || '', + purchase_order_code: entryOrderJSON.purchase_order_code || '', + supplier_name: entryOrderJSON.supplier_name || '', + warehouse_name: entryOrderJSON.warehouse_name || '', + store_name: entryOrderJSON.store_name || '', + logistics_name: entryOrderJSON.logistics_name || '', + express_code: entryOrderJSON.express_code || '', + order_create_time: entryOrderJSON.order_create_time || '', + expect_start_time: entryOrderJSON.expect_start_time || '', + remark: entryOrderJSON.remark || '', + total_order_lines: entryOrderJSON.total_order_lines || 0, + items: items.map(item => ({ + items_col1: item.item_code || '', + items_col2: '', + items_col3: (barcodeMap.get(Number(item.stock_id)) || []).join(';') || '', + items_col4: item.count || 0, + items_col5: item.received_quantity || 0, + items_col6: item.inventory_type || '', + items_col7: imageMap.get(Number(item.stock_id)) || '', + })), + }; + + return this.success('ok', { data: printData, code: 200 }); + } catch (error) { + ctx.logger.error('[entry.getPrintData] 获取入库单打印数据失败:', error); + return this.fail(error.message || '获取打印数据失败', { code: 500 }); + } + } + /** + * 入库单商品与收货单商品对照视图(system method 包装层)。 + * 支持传入多个收货单ID:多个收货单明细先合并为一个整体,再与入库单做一次对照, + * 每个入库明细仅输出一行(含合并收货数量与各收货单来源明细)。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用) + * @param {number} [data.receiving_id] 单个收货单ID(向后兼容) + * @return {Promise} 统一 success 包装 + */ + async receivingCompare(data = {}) { + const { service } = this; + const { entry_order_id, receiving_id, receiving_ids } = data || {}; + const result = await service.systems.storage.entry.receivingCompare({ entry_order_id, receiving_id, receiving_ids }); + return this.success('ok', result); + } + + /** + * 查询入库单操作日志。warehouseId 由服务端从当前上下文自动注入,前端无需传递。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @param {number} [data.page=1] 页码 + * @param {number} [data.pageSize=20] 每页数量 + * @return {Promise} 统一 success 包装 + */ + async queryEntryLogs(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user?.store_id; + const result = await service.systems.operationLog.queryEntryOrderLogs({ + id: data.id, + warehouseId, + page: data.page, + pageSize: data.pageSize, + }); + return this.success('ok', result); + } + + /** + * 查询入库单已绑定收货单中匹配指定商品的可绑定收货明细列表。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.stock_id 商品stock_id + * @return {Promise} 统一 success 包装 + */ + async getReceivingDetailsForBind(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.getReceivingDetailsForBind(data); + if (result && result.code === 200) { + return this.success('ok', result.data); + } + return this.fail(result?.message || '查询失败', result); + } + + /** + * 拉取入库单绑定的收货单中,指定商品的可用容器列表(收货明细)。 + * 用于 PDA 上架时选择容器。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.stock_id 商品stock_id + * @return {Promise} 统一 success 包装,data 包含 { list, total } + */ + async containerList(data = {}) { + const { service } = this; + const { entry_order_id, stock_id } = data || {}; + const result = await service.systems.storage.entry.containerList({ entry_order_id, stock_id }); + if (result && result.code === 200) { + return this.success('ok', result.data); + } + return this.fail(result?.message || '查询失败', result); + } + + /** + * 审核入库单(CREATED → PENDING)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @return {Promise} 统一 success/fail 包装 + */ + async reviewEntry(data = {}) { + const { service } = this; + const result = await service.systems.entryOrder.reviewEntry(data); + if (result && result.success) { + return this.success(result.message, result.data, 200); + } + return this.fail(result?.message || '审核失败', result, 400); + } + + /** + * 提交入库单导出任务(复用 list 的筛选语义与排序规则)。 + * 导出分为两个 sheet:Sheet1=入库单列表,Sheet2=入库单明细(按入库单分页拉取写入流)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 list 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async export(data = {}) { + const { service } = this; + const { where, sort } = data || {}; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.entry.exportEntryOrders({ + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询入库单导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成入库单导出任务ID。 + * @param {string} [prefix=''] 任务类型前缀(如 'store') + * @return {string} 导出任务ID + */ + generateExportTaskId(prefix = '') { + const storeId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const typePrefix = prefix ? `${prefix}_` : ''; + return `entry_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化入库单导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取入库单导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${ENTRY_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入入库单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, ENTRY_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.entry.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取入库单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.entry.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + + /** + * 提交货主侧入库单导出任务(复用 listStore 的筛选语义与排序规则)。 + * 导出分为两个 sheet:Sheet1=入库单列表,Sheet2=入库单明细(按入库单分页拉取写入流)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 listStore 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async storeExport(data = {}) { + const { service } = this; + const { where, sort } = data || {}; + + const taskId = this.generateExportTaskId('store'); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '货主侧入库单导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '货主侧入库单导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.entry.exportStoreEntryOrders({ + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '货主侧入库单导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '货主侧入库单导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '货主侧入库单导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询货主侧入库单导出任务进度。 + * 复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async storeExportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + +} +module.exports = entryService; 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 new file mode 100644 index 0000000..e3711d0 --- /dev/null +++ b/app/service/systemMethods/storage/inventory.js @@ -0,0 +1,410 @@ +'use strict'; + +const MainService = require('../../main'); + +const STORAGE_INVENTORY_EXPORT_TASK_CACHE_KEY_PREFIX = 'storage_inventory_export_task_'; +const STORAGE_INVENTORY_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:storage.inventory(库存操作接口包装层)。 + * 职责:统一包装库存操作接口,调用底层 systems/storage/inventory service。 + */ +class InventoryMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,export,exportTaskProgress,listByStockId,listBySpaceId'; + const _noNeedLog = 'list,export,exportTaskProgress,listByStockId,listBySpaceId'; + const _noNeedAuth = 'list,quickPutaway,directPutaway,export,exportTaskProgress,listByStockId,listBySpaceId'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 移库(库位转移):将单条库存从一个库位移动到另一个库位。 + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(必填) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} [data.quantity] 移库数量(可选,默认全部移动) + * @return {Promise} 统一 success 包装 + */ + async transferLocation(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.transferLocation(data); + return this.success('ok', result); + } + + /** + * 按库位+商品维度移库:自动查找该库位下该商品的所有库存记录,合并移动到目标库位。 + * @param {Object} data 请求体 + * @param {number} data.space_id 原库位ID(必填) + * @param {number} data.stock_id 商品SKU ID(必填) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} data.quantity 移库数量(必填) + * @return {Promise} 统一 success 包装 + */ + async transferByProduct(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.transferByProduct(data); + return this.success('ok', result); + } + + /** + * 维护库存效期:传入库存记录ID与生产日期/到期日期,更新当前库存批次的两个日期字段。 + * + * 仓库上下文来自当前登录用户(ctx.user.store_id),跨仓库的 storage_id 按不存在处理。 + * production_date / expiry_date 至少传一个,未传字段保持库内原值,传 null 或空串表示清空; + * 合并后生产日期不能晚于到期日期。 + * + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(wms_storage.id,必填) + * @param {string|null} [data.production_date] 生产日期(YYYY-MM-DD,null/空串清空) + * @param {string|null} [data.expiry_date] 到期日期(YYYY-MM-DD,null/空串清空) + * @return {Promise} 统一 success 包装(内层为 code/message/data 结构) + */ + async updateExpiry(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.updateExpiry(data); + return this.success('ok', result); + } + + /** + * 提取 stock_query 虚拟筛选条件(与订单查询一致)。 + * 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。 + * 兼容 value 为字符串或数组的场景(如 { operator: 'contains', value: ['A', 'B'] }), + * 数组按多关键字处理,由底层 service 取并集解析 stock_id。 + * @param {Object} whereInput 原始 where 条件。 + * @return {{ where: Object, stockQuery: string|string[] }} 清洗后的 where 与 stock_query 值。 + */ + extractStockQueryVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const stockQueryCondition = normalizedWhere.stock_query; + + delete normalizedWhere.stock_query; + + if (!stockQueryCondition) { + return { where: normalizedWhere, stockQuery: '' }; + } + + const rawValue = this.isPlainObject(stockQueryCondition) + && Object.prototype.hasOwnProperty.call(stockQueryCondition, 'value') + ? stockQueryCondition.value + : stockQueryCondition; + + // value 为数组时逐项清洗为字符串数组(多关键字并集搜索) + if (Array.isArray(rawValue)) { + const stockQuery = rawValue + .map(item => String(item).trim()) + .filter(Boolean); + return { where: normalizedWhere, stockQuery }; + } + + const stockQuery = typeof rawValue === 'string' ? rawValue.trim() : ''; + + return { where: normalizedWhere, stockQuery }; + } + + /** + * 库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.where.stock_query] 虚拟筛选字段:按商品编码(item_code)/名称(item_name)/货物编码(goods_code)/条码(barcode)/SKU ID 模糊匹配,如 { operator: 'like', value: '111' };value 支持数组(如 { operator: 'contains', value: ['111'] }),多关键字取并集匹配 + * @param {Object} [data.pagination] 分页参数 { page, pageSize } + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } + * @param {boolean} [data.group_by_batch=false] 是否按批次查询 + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort, group_by_batch } = data; + const { where: cleanedWhere, stockQuery } = this.extractStockQueryVirtualFilter(data.where); + data.where = cleanedWhere; + this.prepareWhereContext(data); + const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch, stockQuery); + return this.success('ok', result); + } + + /** + * 按商品查询库存明细:传入 stock_id,返回该商品在当前仓库下所有数量大于 1 的 storage 行。 + * 支持两种模式:group_by_space=false 不汇总(逐条明细,含效期/预警字段,默认); + * group_by_space=true 按库位汇总数量(不含批次/效期/预警字段)。 + * @param {Object} data 请求体 + * @param {number} data.stock_id 商品SKU ID(必填) + * @param {boolean} [data.group_by_space=false] 是否按库位汇总 + * @return {Promise} 统一 success 包装 + */ + async listByStockId(data = {}) { + const { service } = this; + const groupBySpace = data.group_by_space === true || data.group_by_space === 'true'; + const result = await service.systems.storage.inventory.getStorageListByStockId(data.stock_id, groupBySpace); + return this.success('ok', result); + } + + /** + * 按库位查询库存商品列表:传入 space_id,判断该库位是否为当前仓库的库位, + * 是则返回该库位下有量库存(quantity > 0)的商品列表(按 stock_id 汇总为一条)。 + * 商品信息统一走 stock_warehouse 通用链路(getStockDetails),返回 stock_warehouse 通用属性。 + * @param {Object} data 请求体 + * @param {number} data.space_id 库位ID(必填) + * @return {Promise} 统一 success 包装 + */ + async listBySpaceId(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.getStorageListBySpaceId(data.space_id); + return this.success('ok', result); + } + + /** + * 收货单快捷入库:将收货单的明细直接转为入库单,相同商品自动合并数量。 + * 要求货主配置中允许收货单快捷入库,否则直接返回失败。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} 统一 success 包装,返回创建的入库单信息 + */ + async quickPutaway(data = {}) { + const { service } = this; + const { receiving_id } = data; + const result = await service.systems.storage.inventory.quickPutaway({ receiving_id }); + return this.success('ok', result); + } + + /** + * 收货单直入库存(一步完成):直接写 wms_storage 库位库存并生成入库单。 + * 入库单明细与收货明细一一对应,按收货明细的库位 space_id 入库。 + * 要求货主配置中允许收货单直入库存,否则直接返回失败。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} 统一 success 包装,返回创建的入库单信息 + */ + async directPutaway(data = {}) { + const { service } = this; + const { receiving_id } = data; + const result = await service.systems.storage.inventory.directPutaway({ receiving_id }); + return this.success('ok', result); + } + /** + * 提交库存导出异步任务(入参与 list 一致,复用相同的 where/sort/group_by_batch 语义)。 + * + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(与 list 完全一致) + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder }(与 list 完全一致) + * @param {boolean} [data.group_by_batch=false] 是否按批次导出,默认 false + * - false:按 stock_id + 库位聚合导出库存汇总 + * - true:按 storage_id 逐条导出库存明细 + * @return {Promise} 统一 success 包装,data 为导出任务信息 + */ + async export(data = {}) { + const { service } = this; + const groupByBatch = data.group_by_batch === true || data.group_by_batch === 'true'; + + // 与 list 一致:prepareWhereContext 会设置 ctx.whereParsed,systems 层从中读取条件 + this.prepareWhereContext(data); + + const { sort = {} } = data; + const sortField = sort.sortField || sort.sort_field; + const sortOrder = sort.sortOrder || sort.sort_order; + const sortParams = { + ...(sortField ? { sortField } : {}), + ...(sortOrder ? { sortOrder } : {}), + }; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.inventory.exportInventoryList(sortParams, groupByBatch); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询库存导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + // ==================== 导出任务辅助方法 ==================== + + /** + * 生成库存导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `storage_inventory_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${STORAGE_INVENTORY_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, STORAGE_INVENTORY_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.inventory.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.inventory.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } +} + +module.exports = InventoryMethodService; diff --git a/app/service/systemMethods/storage/management.js b/app/service/systemMethods/storage/management.js new file mode 100644 index 0000000..765c77a --- /dev/null +++ b/app/service/systemMethods/storage/management.js @@ -0,0 +1,70 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.management(库存管理接口包装层)。 + */ +class StorageManagementMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'replenishmentDemand'; + const _noNeedLog = ''; + const _noNeedAuth = 'replenishmentDemand'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 分拣缺货补货需求计算。 + * + * 仓库级别的计算,针对当前仓库所有未完成储位分配的订单, + * 计算每个 SKU 在分拣区与存货区的可用库存对比, + * 输出分拣区缺口及建议补货量,供仓库人员决策移库。 + * + * 仓库 ID 从用户上下文(ctx.user.store_id / ctx.user.warehouse_id)自动获取,无需显式传入。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.sort] 排序参数。 + * @param {number|number[]} [data.store_id] 货主筛选:单值或数组(正整数),也可通过 data.where.store_id 传入;不传时返回全部货主。 + * @return {Promise} 统一 success 包装的补货需求明细、汇总与分页信息。 + */ + async replenishmentDemand(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const pagination = requestData.pagination || {}; + const sort = requestData.sort || requestData.order || {}; + const where = this.isPlainObject(requestData.where) ? requestData.where : {}; + + // 货主筛选:支持顶层 store_id / store_ids,或 where.store_id(单值/数组) + const rawStoreIdValue = requestData.store_id !== undefined && requestData.store_id !== null + ? requestData.store_id + : (requestData.store_ids !== undefined && requestData.store_ids !== null + ? requestData.store_ids + : where.store_id); + + let storeIds = []; + if (rawStoreIdValue !== undefined && rawStoreIdValue !== null && rawStoreIdValue !== '') { + const rawList = Array.isArray(rawStoreIdValue) ? rawStoreIdValue : [ rawStoreIdValue ]; + const normalizedStoreIds = new Set(); + for (const item of rawList) { + const value = Number(item); + if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) { + throw new Error(`store_id 必须是正整数,非法值: ${item}`); + } + normalizedStoreIds.add(value); + } + storeIds = Array.from(normalizedStoreIds); + } + + const result = await service.systems.storage.management.replenishmentDemand({ + pagination, + sort, + storeIds, + }); + return this.success('补货需求计算完成', result); + } +} + +module.exports = StorageManagementMethodService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 08ba957..22771d0 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -2,74 +2,682 @@ const MainService = require('../../main'); +const RECEIVING_EXPORT_TASK_CACHE_KEY_PREFIX = 'receiving_export_task_'; +const RECEIVING_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; +/** + * 系统方法层:storage.receiving(收货单相关接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 + * 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。 + */ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving'; + const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedLog = ''; + const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + + /** + * 收货单列表查询(system method 包装层)。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 筛选条件 + * @param {boolean} [data.filterDepleted=false] 是否过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满) + * @param {number} [data.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 + * @param {string} [data.stock_query_where] 可选,按商品条码/商品编码/商品ID搜索,返回明细中含匹配商品的收货单 + * @return {Promise} 统一成功包装响应 + */ async getReceivingList(data) { const { service } = this; - const { pagination, where } = data; - console.log('where', where); - console.log('service.systems.storage.receiving', service.systems.storage.index.index); - const result = await service.systems.storage.receiving.getReceivingList(where, pagination); + const { pagination, sort, filterDepleted = false, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort, { filterDepleted, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere }); return this.success('ok', result); } + + /** + * 货主侧收货单列表查询(system method 包装层)。 + * 以当前平台激活的货主 store_id 为维度查询收货单。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 筛选条件 + * @param {Object} [data.sort] 排序参数 + * @param {string|string[]} [data.stock_query_where] 可选,按商品条码/商品编码/商品ID搜索,返回明细中含匹配商品的收货单 + * @return {Promise} 统一成功包装响应 + */ + async getStoreReceivingList(data) { + const { ctx, app } = this; + const { pagination, sort, stock_query_where: stockQueryWhere } = data; + + // 从平台激活上下文获取 store_id(使用原生查询避免 AccountPlatformActive 无 id 列兼容问题) + const platformRows = await app.model.query( + 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + + 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + + 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', + { + replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { + return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); + } + + const storeId = platformRows[0].store_id; + + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const { service } = this; + const result = await service.systems.storage.receiving.getStoreReceivingList( + where, + storeId, + pagination, + sort, + { stock_query_where: stockQueryWhere } + ); + + return this.success('ok', result); + } + + /** + * 收货单详情查询(分页返回明细)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {Object} data.pagination 明细分页参数 + * @return {Promise} 统一成功包装响应 + */ + async getReceivingDetail(data) { + const { service } = this; + const result = await service.systems.storage.receiving.getReceivingDetail(data); + return this.success('ok', result); + } + + /** + * 批量作废收货单。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @return {Promise} 统一成功包装响应 + */ + async batchCancelReceiving(data) { + const { service } = this; + const result = await service.systems.storage.receiving.batchCancelReceiving(data); + return this.success('ok', result); + } + + /** + * 创建收货单。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async create(data) { const { service } = this; const result = await service.systems.storage.receiving.create(data); return this.success('创建失败', result); } + + /** + * 绑定收货单货主。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {number} data.store_id 货主ID + * @return {Promise} 统一成功包装响应 + */ + async bindStore(data) { + const { service } = this; + const result = await service.systems.storage.receiving.bindStore(data); + return this.success('ok', result); + } + + /** + * 绑定或改绑收货单明细商品。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 收货单明细ID + * @param {number} data.system_product_id 商品ID + * @return {Promise} 统一成功包装响应 + */ + async bindDetailProduct(data) { + const { service } = this; + const result = await service.systems.storage.receiving.bindDetailProduct(data); + return this.success('ok', result); + } + + /** + * 添加收货商品(当前依赖底层 addItem 实现)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {Object} data.item 商品信息 + * @return {Promise} 统一成功包装响应 + */ async addItem(data) { const { service } = this; const { id, item } = data; const result = await service.systems.storage.receiving.addItem(id, item); return this.success('ok', result); } + + /** + * 删除收货商品(当前依赖底层 removeItem 实现)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {number} data.item_id 商品明细ID + * @return {Promise} 统一成功包装响应 + */ async removeItem(data) { const { service } = this; const { id, item_id } = data; const result = await service.systems.storage.receiving.removeItem(id, item_id); return this.success('ok', result); } - async saveReceiving(data) { + + /** + * 保存收货单。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ + async save(data) { const { service } = this; - const result = await service.systems.storage.receiving.saveReceiving(data); + const result = await service.systems.storage.receiving.save(data); return this.success('ok', result); } + + /** + * 查询收货单完整信息(含明细与图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @return {Promise} 统一成功包装响应 + */ async get(data) { const { service } = this; const result = await service.systems.storage.receiving.get(data); return this.success('ok', result); } + + /** + * 新增一条收货明细(支持可选 item)。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async addDetail(data) { const { service } = this; const result = await service.systems.storage.receiving.addDetail(data); return this.success('ok', result); } + + /** + * 删除收货明细。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async deleteDetail(data) { const { service } = this; const result = await service.systems.storage.receiving.deleteDetail(data); return this.success('ok', result); } + + /** + * 修改收货明细字段。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async detailChange(data) { const { service } = this; const result = await service.systems.storage.receiving.detailChange(data); return this.success('ok', result); } + + /** + * 作废收货单(单条)。 + * @param {Object} data 请求体 + * @return {Promise} 统一成功包装响应 + */ async cancel(data) { const { service } = this; const result = await service.systems.storage.receiving.invalid(data); return this.success('ok', result); } + + /** + * 完成收货单并触发入库处理。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {string} [data.remark] 完成备注 + * @return {Promise} 统一成功包装响应 + */ async completeReceiving(data) { const { service } = this; const result = await service.systems.storage.receiving.completeReceiving(data); return this.success('ok', result); } + + /** + * 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @param {string} [data.remark] 驳回理由(覆盖原备注) + * @return {Promise} 统一成功包装响应 + */ + async rejectReceiving(data) { + const { service } = this; + const result = await service.systems.storage.receiving.rejectReceiving(data); + return this.success('ok', result); + } + + /** + * 批量审核收货单。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @return {Promise} 统一成功包装响应 + */ + async reviewReceiving(data) { + const { service } = this; + const { ids } = data || {}; + const result = await service.systems.storage.receiving.reviewReceiving({ ids }); + return this.success('ok', result); + } + + /** + * 查询收货单操作日志(分页)。 + * @param {Object} data 请求体 + * @param {number|string} data.receiving_id 收货单ID + * @param {Object} [data.pagination] 分页对象,支持 page/pageSize + * @return {Promise} 统一成功包装响应 + */ + async queryReceivingLogs(data = {}) { + const { ctx, service } = this; + const requestData = data && typeof data === 'object' ? data : {}; + const pagination = requestData.pagination && typeof requestData.pagination === 'object' + ? requestData.pagination + : {}; + + const result = await service.systems.operationLog.queryReceivingLogs({ + id: requestData.receiving_id, + page: pagination.page, + pageSize: pagination.pageSize || pagination.page_size, + warehouseId: ctx.user.store_id, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } + + /** + * PDA 扫码定位收货明细(system method 包装层),返回匹配的明细列表。 + * 同一条码可能匹配到多条收货明细,以列表形式返回所有匹配结果。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {string} data.barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID) + * @return {Promise} 统一成功包装响应,含匹配的收货明细列表 { list, total } + */ + async scanDetail(data) { + const { service } = this; + const { entry_order_id, barcode } = data; + const result = await service.systems.storage.receiving.scanDetail(entry_order_id, barcode); + if (result.code !== 200) { + return this.fail(result.message); + } + return this.success('查询成功', result.data); + } + + /** + * 提交收货单导出任务(仓库维度,复用 getReceivingList 的筛选语义与排序规则)。 + * 导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 getReceivingList 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async export(data = {}) { + const { service } = this; + const { sort = {} } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '收货单导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '收货单导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.receiving.exportReceivingList({ + where, + sort, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '收货单导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '收货单导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '收货单导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询收货单导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成收货单导出任务ID。 + * @param {string} [prefix=''] 任务类型前缀(如 'store') + * @return {string} 导出任务ID + */ + generateExportTaskId(prefix = '') { + const storeId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const typePrefix = prefix ? `${prefix}_` : ''; + return `receiving_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化收货单导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取收货单导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${RECEIVING_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入收货单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, RECEIVING_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.receiving.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取收货单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.receiving.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + + /** + * 提交货主侧收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。 + * 以当前平台激活的货主 store_id 为维度导出。导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async storeExport(data = {}) { + const { ctx, app, service } = this; + + // 从平台激活上下文获取 store_id + const platformRows = await app.model.query( + 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + + 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + + 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', + { + replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { + return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); + } + + const storeId = platformRows[0].store_id; + const { sort = {} } = data; + + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const taskId = this.generateExportTaskId('store'); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '货主侧收货单导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + message: '货主侧收货单导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.receiving.exportStoreReceivingList({ + where, + storeId, + sort, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '货主侧收货单导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '货主侧收货单导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '货主侧收货单导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询货主侧收货单导出任务进度。 + * 复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async storeExportTaskProgress(data = {}) { + return this.exportTaskProgress(data); + } + } module.exports = configService; diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js new file mode 100644 index 0000000..e63164a --- /dev/null +++ b/app/service/systemMethods/storage/stockout.js @@ -0,0 +1,1028 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.stockout(非订单出库单)。 + * 说明:直接读写 wms_order_stockout + wms_order_stockout_items 表。 + */ +class StorageStockoutService extends MainService { + 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); + } + + /** + * 出库单列表查询。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应 + */ + async list(data = {}) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const { pagination = {}, sort = {} } = data; + + const { parsed } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const page = Math.max(Number(pagination.page) || 1, 1); + const pageSize = Math.max(Number(pagination.pageSize) || 20, 1); + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const OrderStockoutModel = ctx.model.OrderStockout; + + const andConditions = [ + { warehouse_id: warehouseId }, + { deleted_at: null }, + ]; + + const dynamicConditions = Array.isArray(parsed && parsed.dynamicConditions) ? parsed.dynamicConditions : []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereCondition = parsed && parsed.rawConditionsByField && parsed.rawConditionsByField.quickWhere; + const quickValue = quickWhereCondition && Object.prototype.hasOwnProperty.call(quickWhereCondition, 'value') + ? quickWhereCondition.value + : null; + if (quickValue !== null && quickValue !== undefined && String(quickValue).trim() !== '') { + const keyword = String(quickValue).trim(); + andConditions.push({ + [Op.or]: [ + { stockout_order_code: { [Op.like]: `%${keyword}%` } }, + { remark: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + const validSortFields = [ + 'id', + 'stockout_order_code', + 'order_status', + 'order_type', + 'updated_at', + 'created_at', + 'order_create_time', + ]; + const sortField = validSortFields.includes(String(sort.sortField || '').trim()) + ? String(sort.sortField).trim() + : 'updated_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + + const finalWhere = { [Op.and]: andConditions }; + const { count, rows } = await OrderStockoutModel.findAndCountAll({ + // 必须返回 id:前端行点击/详情/打印/确认等均依赖 row.id(与 receiving 等列表保持一致) + attributes: { exclude: [ 'warehouse_name' ] }, + where: finalWhere, + order: [[ sortField, sortOrder ], [ 'id', 'DESC' ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + // 补充货主名称:store_name 快照为空时按 store_id 解析 wms_store.company_name + const storeIds = [ ...new Set(rows.map(row => Number(row.store_id)).filter(id => Number.isFinite(id) && id > 0)) ]; + if (storeIds.length > 0) { + const stores = await ctx.model.Store.findAll({ + where: { id: { [Op.in]: storeIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + const nameMap = new Map(stores.map(item => [ Number(item.id), String(item.company_name || '') ])); + for (const row of rows) { + if (!row.store_name) { + row.store_name = nameMap.get(Number(row.store_id)) || ''; + } + } + } + + return this.success('ok', { + list: rows, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page < Math.ceil(count / pageSize), + }, + }); + } + + /** + * 出库单转订单。 + * + * 将非订单出库单(wms_order_stockout)转为正式销售订单: + * 1. 新订单 create_channel 固定为 STOCKOUT; + * 2. 释放出库单占用的库存锁定,转由新订单重新锁定; + * 3. 转单成功后原出库单置为 CANCELLED,并记录已转订单号(幂等)。 + * + * 仅 CREATED / PENDING 状态的出库单允许转单;建单失败时自动补偿恢复出库单锁定。 + * + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @param {string} [data.delivery_order_code] 新订单号,不传自动生成(SK 前缀) + * @param {Object} [data.receiverInfo] 收件人信息(name/mobile/tel/province/city/area/town/detailAddress/zipCode) + * @return {Promise} 统一成功/失败包装响应 + */ + async toOrder(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + if (warehouseId <= 0) { + return this.fail('缺少仓库上下文'); + } + + const order = await ctx.model.OrderStockout.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!order) { + return this.fail('出库单不存在'); + } + + // 幂等:已转订单的出库单直接返回原订单信息 + const currentExtendProps = + order.extend_props && typeof order.extend_props === 'object' && !Array.isArray(order.extend_props) + ? order.extend_props + : {}; + if (currentExtendProps.transferred_order_id) { + return this.success('出库单已转订单', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_id: currentExtendProps.transferred_order_id, + delivery_order_code: currentExtendProps.transferred_order_code || '', + }); + } + + if (![ 'CREATED', 'PENDING' ].includes(order.order_status)) { + return this.fail(`出库单当前状态(${order.order_status})不允许转订单`); + } + + const items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: order.id }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (!items || items.length === 0) { + return this.fail('出库单没有明细,无法转订单'); + } + + // 收货信息:出库单已存的 receiver_* 字段为基础,接口传入的非空 receiverInfo 字段覆盖 + const storedReceiverInfo = { + company: order.receiver_company || '', + name: order.receiver_name || '', + zipCode: order.receiver_zip_code || '', + tel: order.receiver_tel || '', + mobile: order.receiver_mobile || '', + email: order.receiver_email || '', + countryCode: order.receiver_country_code || '', + province: order.receiver_province || '', + city: order.receiver_city || '', + area: order.receiver_area || '', + town: order.receiver_town || '', + detailAddress: order.receiver_detail_address || '', + }; + const passedReceiverInfo = data.receiverInfo && typeof data.receiverInfo === 'object' + ? data.receiverInfo + : {}; + const receiverInfo = { ...storedReceiverInfo }; + for (const [ key, value ] of Object.entries(passedReceiverInfo)) { + if (value !== undefined && value !== null && String(value).trim() !== '') { + receiverInfo[key] = String(value).trim(); + } + } + + // 收货信息必填校验:name、(tel/mobile) 其一、省市区镇详细地址,缺失禁止转订单 + const missingFields = []; + if (!String(receiverInfo.name || '').trim()) { + missingFields.push('name(收件人姓名)'); + } + const receiverTel = String(receiverInfo.tel || '').trim(); + const receiverMobile = String(receiverInfo.mobile || '').trim(); + if (!receiverTel && !receiverMobile) { + missingFields.push('tel/mobile(固定电话或移动电话至少一项)'); + } + const addressFields = [ + [ 'province', '省' ], + [ 'city', '市' ], + [ 'area', '区' ], + [ 'town', '镇' ], + [ 'detailAddress', '详细地址' ], + ]; + for (const [ key, label ] of addressFields) { + if (!String(receiverInfo[key] || '').trim()) { + missingFields.push(`${key}(${label})`); + } + } + if (missingFields.length > 0) { + return this.fail(`收货信息缺失,不能转订单:缺少 ${missingFields.join('、')}`); + } + + const stockStoreService = ctx.service.systems.stockStore; + const lockMeta = { + orderType: 'QM_STOCKOUT', + orderNo: order.stockout_order_code, + orderId: order.id, + }; + + // 第一步:释放出库单占用的库存锁定(新订单创建时会重新锁定) + const releaseTransaction = await ctx.model.transaction(); + try { + for (const item of items) { + const qty = Number(item.plan_qty) || 0; + if (qty <= 0) continue; + const releaseResult = await stockStoreService.lockItemStorages( + item.stock_id, + -qty, + releaseTransaction, + null, + { ...lockMeta, remark: '出库单转订单释放锁定' } + ); + if (!releaseResult.success) { + throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`); + } + } + await releaseTransaction.commit(); + } catch (err) { + await releaseTransaction.rollback().catch(() => {}); + ctx.logger.error(`[stockout.toOrder] 释放出库单锁定失败: ${err.message}`); + return this.fail(`转订单失败:${err.message}`); + } + + // 第二步:创建订单(create_channel=STOCKOUT,内部重新锁定库存) + // 快递编码沿用出库单已解析的 express_code(系统快递编码),平台不传 sourcePlatformCode 走兜底平台 + const deliveryOrderCode = String(data.delivery_order_code || '').trim() + || `SK${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`; + + const orderLines = items.map((item, idx) => ({ + itemCode: item.item_code || '', + itemId: Number(item.item_id) || 0, + itemName: item.item_name || '', + planQty: Number(item.plan_qty) || 0, + stockId: Number(item.stock_id) || 0, + inventoryType: item.inventory_type || '', + orderLineNo: String(item.order_line_no || idx + 1), + ownerCode: item.owner_code || '', + sourceOrderCode: order.stockout_order_code, + })); + + const addOrderData = { + request: { + deliveryOrder: { + deliveryOrderCode, + orderType: order.order_type || 'QTCK', + createChannel: 'STOCKOUT', + logisticsCode: order.express_code || '', + sourcePlatformCode: order.source_platform_code || '', + receiverInfo, + remark: order.remark || '', + sourceOrderCode: order.stockout_order_code, + }, + orderLines: { orderLine: orderLines }, + }, + }; + + const info = { + storeId: order.store_id, + warehouseId, + appKey: (ctx.user && ctx.user.app_key) || '', + }; + + let addOrderResult = null; + try { + addOrderResult = await ctx.service.systems.deliveryOrder.addOrder(addOrderData, info, 'STOCKOUT'); + } catch (err) { + addOrderResult = { success: false, message: err.message, data: null }; + } + + const orderId = addOrderResult && addOrderResult.data && addOrderResult.data.orderId; + const isDuplicate = !!(addOrderResult && addOrderResult.success && addOrderResult.message === '订单已存在'); + + if (!addOrderResult || !addOrderResult.success || !orderId || isDuplicate) { + // 建单失败/订单号重复:补偿恢复出库单锁定 + await this._restoreStockoutLocks(stockStoreService, items, lockMeta, ctx); + return this.fail(`转订单失败:${(addOrderResult && addOrderResult.message) || '订单创建失败'}`); + } + + // 第三步:标记出库单已转订单(状态推进到 TRANSFERRED,该状态下禁止一键出库) + try { + await ctx.model.OrderStockout.update( + { + order_status: 'TRANSFERRED', + sync_message: `已转订单 ${deliveryOrderCode}`, + extend_props: { + ...currentExtendProps, + transferred_order_id: orderId, + transferred_order_code: deliveryOrderCode, + transferred_at: new Date(), + }, + updated_at: new Date(), + }, + { where: { id: order.id } } + ); + } catch (updateErr) { + // 订单已创建成功,仅出库单标记失败:记录告警,不回滚订单 + ctx.logger.error(`[stockout.toOrder] 标记出库单已转失败: ${updateErr.message}`); + } + + await this._writeStockoutOperationLog( + order, + 'STOCKOUT_TO_ORDER', + `出库单已转订单 ${deliveryOrderCode}(order_id=${orderId}),已释放库存锁定` + ); + + return this.success('转订单成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_id: orderId, + delivery_order_code: deliveryOrderCode, + step: addOrderResult.data.step, + }); + } + + /** + * 转订单失败时恢复出库单库存锁定(补偿)。 + * @param {Object} stockStoreService 库存服务 + * @param {Array} items 出库单明细 + * @param {Object} lockMeta 锁元信息 + * @param {Object} ctx 请求上下文 + * @return {Promise} 无返回值 + */ + async _restoreStockoutLocks(stockStoreService, items, lockMeta, ctx) { + const restoreTransaction = await ctx.model.transaction(); + try { + for (const item of items) { + const qty = Number(item.plan_qty) || 0; + if (qty <= 0) continue; + const restoreResult = await stockStoreService.lockItemStorages( + item.stock_id, + qty, + restoreTransaction, + null, + { ...lockMeta, remark: '出库单转订单失败恢复锁定' } + ); + if (!restoreResult.success) { + throw new Error(`库存${item.stock_id}恢复锁定失败: ${restoreResult.error}`); + } + } + await restoreTransaction.commit(); + } catch (err) { + await restoreTransaction.rollback().catch(() => {}); + ctx.logger.error(`[stockout.toOrder] 恢复出库单锁定失败: ${err.message}`); + } + } + + /** + * 写 wms_operation_log 操作日志(businessType=stockout),失败仅告警不影响主流程。 + * + * 委托到共享实现 `systems/stockout_order.js#_writeStockoutOperationLog`, + * 保持本入口的历史口径:操作人取自 ctx.user,仓库取自 ctx.user.store_id(缺失时 + * 回退出库单自身 warehouse_id)。 + * + * @param {Object} order 出库单实例或行 + * @param {string} operationCode 操作编码 + * @param {string} message 日志内容 + * @param {Object} [options={}] 选项,可含 transaction + * @return {Promise} 无返回值 + */ + async _writeStockoutOperationLog(order, operationCode, message, options = {}) { + const { ctx } = this; + const stockoutOrderService = ctx.service && ctx.service.systems && ctx.service.systems.stockoutOrder; + if (!stockoutOrderService || typeof stockoutOrderService._writeStockoutOperationLog !== 'function') { + ctx.logger.warn('[stockout] 出库单领域服务不可用,跳过记录'); + return; + } + const user = ctx.user || {}; + await stockoutOrderService._writeStockoutOperationLog(order, operationCode, message, { + transaction: options.transaction, + warehouseId: Number(ctx.user && ctx.user.store_id) || order.warehouse_id || null, + operator: { + id: user.employees_id ?? user.id ?? null, + name: String(user.employees_name || user.real_name || user.name || 'system'), + }, + }); + } + + /** + * 出库单明细查询。 + * @param {Object} data 请求体 + * @param {number} [data.id] 出库单ID + * @param {string} [data.stockout_order_code] 出库单号 + * @return {Promise} 统一成功包装响应 + */ + async listItems(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const id = Number(data.id || 0); + // 兼容 delivery_order_code 旧参数名 + const stockoutOrderCode = String(data.stockout_order_code || data.delivery_order_code || '').trim(); + + if (!id && !stockoutOrderCode) { + return this.fail('id 或 stockout_order_code 至少传一个'); + } + + const OrderStockoutModel = ctx.model.OrderStockout; + const OrderStockoutItemsModel = ctx.model.OrderStockoutItems; + + const where = { + warehouse_id: warehouseId, + deleted_at: null, + }; + if (id > 0) { + where.id = id; + } else { + where.stockout_order_code = stockoutOrderCode; + } + + const order = await OrderStockoutModel.findOne({ + where, + raw: true, + }); + + if (!order || !order.id) { + return this.success('ok', { + order: null, + list: [], + }); + } + + const list = await OrderStockoutItemsModel.findAll({ + where: { + order_id: order.id, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return this.success('ok', { + order, + list, + }); + } + + /** + * 查询出库单操作日志(分页)。 + * 日志业务类型 business_type=stockout,business_id=出库单ID; + * 覆盖创建/审核/转订单/确认/修改/取消等操作(STOCKOUT_* 操作编码)。 + * @param {Object} data 请求体 + * @param {number} [data.id] 出库单ID(与 stockout_order_code 至少传一个) + * @param {string} [data.stockout_order_code] 出库单号 + * @param {Object} [data.pagination] 分页对象,支持 page / pageSize(或 page_size) + * @return {Promise} 统一成功包装响应 { list, pagination } + */ + async listLogs(data = {}) { + const { ctx, service } = this; + const requestData = data && typeof data === 'object' ? data : {}; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const id = Number(requestData.id || 0); + const stockoutOrderCode = String(requestData.stockout_order_code || '').trim(); + // 分页参数:兼容顶层 page/pageSize(与订单日志 order.queryOrderLogs 一致)与 pagination 对象两种写法 + const pagination = requestData.pagination && typeof requestData.pagination === 'object' + ? requestData.pagination + : {}; + const page = requestData.page ?? pagination.page; + const pageSize = requestData.pageSize ?? pagination.pageSize ?? pagination.page_size; + + if (!id && !stockoutOrderCode) { + return this.fail('id 或 stockout_order_code 至少传一个'); + } + + const emptyResult = { + list: [], + pagination: { + page: Number.parseInt(page, 10) || 1, + pageSize: Number.parseInt(pageSize, 10) || 20, + total: 0, + totalPages: 0, + }, + }; + + // 定位出库单ID(日志 business_id 存的是出库单ID) + let stockoutId = id; + if (!stockoutId) { + const order = await ctx.model.OrderStockout.findOne({ + where: { + stockout_order_code: stockoutOrderCode, + warehouse_id: warehouseId, + deleted_at: null, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!order || !order.id) { + return this.success('ok', { + data: emptyResult, + code: 200, + }); + } + + stockoutId = Number(order.id); + } + + try { + const result = await service.systems.operationLog.queryStockoutLogs({ + id: stockoutId, + page, + pageSize, + warehouseId, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (e) { + // 与订单日志接口一致:查询异常时以 200 包装返回错误信息 + return this.success(e.message, { + code: 200, + }); + } + } + + /** + * 出库单确认(直出)。 + * 不改变内部库存,直接按出库单明细的计划数量确认。 + * 出站回传按 source_type 分流(QM→奇门 taobao.qimen.stockout.confirm, + * API→OpenAPI 回调 stockout.confirm,其他内部来源直接视为成功), + * 回传成功后释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水),状态才推进到 COMPLETED。 + * 要求运单号已填写(以复数 waybill_codes 为准,存量单回退单数 waybill_code),否则拒绝确认。 + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @return {Promise} 统一成功/失败包装响应 + */ + async confirm(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const order = await ctx.model.OrderStockout.findByPk(id); + if (!order) { + return this.fail('出库单不存在'); + } + + if (!order.canConfirm || !order.canConfirm()) { + return this.fail(`出库单当前状态(${order.order_status})不允许确认`); + } + + // 校验运单号是否已填写:回传以复数 waybill_codes 为准(一单多运单 → 奇门 packages.package[]), + // 单数 waybill_code 已弃用,仅在复数缺失时对存量单做兼容回退。 + const confirmWaybillCodes = (Array.isArray(order.waybill_codes) && order.waybill_codes.length > 0 + ? order.waybill_codes + : [ order.waybill_code ]) + .map(code => String(code || '').trim()) + .filter(code => !!code); + if (confirmWaybillCodes.length === 0) { + return this.fail('出库单未填写运单号(waybill_codes),请先更新运单号后再确认'); + } + + // 第一步:事务内写入明细 actual_qty(暂不改变 order_status) + const transaction = await ctx.model.transaction(); + let items; + try { + items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: id }, + transaction, + }); + + for (const item of items) { + await item.update({ + actual_qty: item.plan_qty, + updated_at: new Date(), + }, { transaction }); + } + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + ctx.logger.error('[stockout.confirm] 明细更新失败:', err); + return this.fail(`确认失败:${err.message}`); + } + + // 第二步:按出库单来源通知外部 + // QM → 奇门 taobao.qimen.stockout.confirm;API → OpenAPI 回调 stockout.confirm; + // WMS 等内部来源 → 无需通知外部,直接视为成功。 + // 与出库单转订单回传(orderAsync.syncStockoutOrders)共用同一分流实现,避免两处逻辑漂移。 + const orderAsyncService = ctx.service.systems && ctx.service.systems.orderAsync; + let qimenSuccess = false; + let qimenMessage = ''; + + if (!orderAsyncService || typeof orderAsyncService.notifyStockoutExternal !== 'function') { + qimenMessage = '出库单回传服务不可用'; + ctx.logger.error('[stockout.confirm] 出库单回传服务不可用(ctx.service.systems.orderAsync 缺失)'); + } else { + try { + // 直出确认没有发货单上下文,orderRow 传空对象:报文内快递信息回退出库单 express_code/express_name + // 运单号统一走复数(packages.package[].expressCode),不传 deliveryOrder.expressCode + const outboundData = orderAsyncService.buildStockoutConfirmRequest(order, {}, items, confirmWaybillCodes); + + // API 来源需按货主合约反查回调 appKey;QM 来源由奇门 client 按货主编码发送,无需 appKey + let appKey = ''; + if (String(order.source_type || 'QM').trim().toUpperCase() === 'API') { + const resolvedApp = await orderAsyncService.resolveOpenApiAppByStore(order.store_id, order.warehouse_id); + appKey = String((resolvedApp && resolvedApp.appKey) || '').trim(); + } + + const notifyResult = await orderAsyncService.notifyStockoutExternal(order, outboundData, { appKey }); + qimenSuccess = !!(notifyResult && notifyResult.success === true); + qimenMessage = qimenSuccess + ? '' + : String((notifyResult && notifyResult.message) || '通知外部失败').trim(); + } catch (outboundErr) { + qimenMessage = outboundErr.message || '出站通知异常'; + ctx.logger.error(`[stockout.confirm] 出站通知异常: ${qimenMessage}`); + } + } + + // 第三步:根据出站结果更新状态 + if (qimenSuccess) { + // 直出确认:释放出库单占用的库存锁定(QM_STOCKOUT,负数量释放并自动写 UNLOCK 流水), + // 与状态推进到 COMPLETED 在同一事务内完成,失败回滚可重试。 + const finalizeTransaction = await ctx.model.transaction(); + try { + let totalReleaseQty = 0; + for (const item of items) { + const qty = Number(item.plan_qty) || 0; + if (qty <= 0) continue; + const releaseResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stock_id, + -qty, + finalizeTransaction, + null, + { + orderType: 'QM_STOCKOUT', + orderNo: order.stockout_order_code, + orderId: order.id, + remark: '出库单确认释放锁定', + } + ); + if (!releaseResult.success) { + // 已释放过(锁定不足)视为幂等成功,避免阻断重试 + const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存'); + if (alreadyReleased) { + ctx.logger.warn(`[stockout.confirm] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`); + continue; + } + throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`); + } + totalReleaseQty += qty; + } + + await this._writeStockoutOperationLog( + order, + 'STOCKOUT_CONFIRM', + `出库单确认完成(直出),释放锁定库存 ${totalReleaseQty}`, + { transaction: finalizeTransaction } + ); + + await ctx.model.OrderStockout.update( + { order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: '', updated_at: new Date() }, + { where: { id: order.id }, transaction: finalizeTransaction } + ); + + await finalizeTransaction.commit(); + } catch (err) { + await finalizeTransaction.rollback().catch(() => {}); + ctx.logger.error(`[stockout.confirm] 释放锁定失败: ${order.stockout_order_code} - ${err.message}`); + return this.fail(`确认失败:${err.message}`); + } + ctx.logger.info(`[stockout.confirm] 确认完成: ${order.stockout_order_code}`); + + return this.success('确认成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_status: 'COMPLETED', + logisticsName: 'OTHER', + expressCode: order.express_code, + expressCodes: order.express_codes, + qimenSync: 'success', + }); + } + + // 出站失败:更新 sync_status,order_status 不变 + await ctx.model.OrderStockout.update( + { sync_status: 'FAILED', sync_message: qimenMessage, updated_at: new Date() }, + { where: { id: order.id } } + ); + ctx.logger.error(`[stockout.confirm] 出站同步失败: ${order.stockout_order_code} - ${qimenMessage}`); + + return this.fail(`出站同步失败: ${qimenMessage || '未发起出站通知'}`); + } + + /** + * 出库单取消。 + * + * 委托到共享实现 `systems/stockout_order.js#cancel`(奇门 / openapi 同口径: + * 事务 + 行锁,释放 QM_STOCKOUT 库存锁定,状态置 CANCELLED 并写操作日志), + * 本入口负责入参校验与对外契约映射。 + * + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @return {Promise} 统一成功/失败包装响应 + */ + async cancel(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + if (warehouseId <= 0) { + return this.fail('缺少仓库上下文'); + } + + const stockoutOrderService = ctx.service && ctx.service.systems && ctx.service.systems.stockoutOrder; + if (!stockoutOrderService || typeof stockoutOrderService.cancel !== 'function') { + return this.fail('出库单取消服务不可用'); + } + + const result = await stockoutOrderService.cancel( + { id }, + { + storeId: null, + warehouseId, + operatorLabel: String( + (ctx.user && (ctx.user.employees_name || ctx.user.real_name || ctx.user.name)) || 'system' + ), + } + ); + + if (result.flag !== 'success') { + // 契约文案映射:共享层「未找到对应的出库单」→ 本入口「出库单不存在」,其余文案原样透出 + return this.fail( + result.message === '未找到对应的出库单' ? '出库单不存在' : result.message + ); + } + + return this.success('取消成功', { + id: result.id, + stockout_order_code: result.stockout_order_code, + order_status: result.order_status, + }); + } + + /** + * 更新出库单快递和运单号。 + * 用于在确认前填写 express_code / waybill_codes。 + * 运单号以复数 waybill_codes 为准(一单多运单);单数 waybill_code 已弃用, + * 传入 waybill_codes 时会自动镜像为首个单号写回单数列。 + * express_code 传入后自动从系统快递表解析 express_name。 + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @param {string} [data.express_code] 快递公司编码(如 SF、STO),传入后自动解析 express_name + * @param {string} [data.waybill_code] 运单号(单数,已弃用;仅作为 waybill_codes 首个的镜像,勿单独使用) + * @param {string[]} [data.waybill_codes] 运单号列表(复数,回传以此为准,支持一单多运单) + * @return {Promise} 统一成功/失败包装响应 + */ + async updateExpress(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const order = await ctx.model.OrderStockout.findByPk(id); + if (!order) { + return this.fail('出库单不存在'); + } + + const updateData = { updated_at: new Date() }; + + // express_code:自动解析 express_name + if (data.express_code !== undefined) { + updateData.express_code = data.express_code || null; + if (data.express_code) { + try { + const expressMap = await ctx.service.systems.setting.express.getSystemExpressMap(); + const info = expressMap.get(String(data.express_code).trim().toUpperCase()); + updateData.express_name = info ? info.name : ''; + } catch (e) { + ctx.logger.warn('[updateExpress] 解析快递名称失败: ' + e.message); + updateData.express_name = ''; + } + } else { + updateData.express_name = null; + } + } + + // waybill_code(单数)已弃用:回传以 waybill_codes(复数)为准(一单多运单), + // 单数列仅作为复数首个的镜像保留,便于历史查询与展示; + // 传入 waybill_codes 时以复数首个覆盖单数,避免两列不一致。 + if (data.waybill_code !== undefined) { + updateData.waybill_code = data.waybill_code || null; + } + if (data.waybill_codes !== undefined) { + const codes = data.waybill_codes; + if (codes !== null && !Array.isArray(codes)) { + return this.fail('waybill_codes 必须是数组或 null'); + } + updateData.waybill_codes = codes; + updateData.waybill_code = Array.isArray(codes) && codes.length > 0 + ? String(codes[0] || '').trim() || null + : null; + } + + if (Object.keys(updateData).length <= 1) { + return this.fail('没有需要更新的字段'); + } + + await order.update(updateData); + await order.reload(); + + return this.success('更新成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + express_code: order.express_code, + express_name: order.express_name, + waybill_code: order.waybill_code, + waybill_codes: order.waybill_codes, + }); + } + + /** + * 修改出库单信息。 + * + * 可修改范围:收件人(name/tel/mobile 等)、地址(province/city/area/town/detailAddress 等)、 + * 快递编码(express_code,自动解析 express_name)、来源平台(source_platform_code/name)。 + * 未传入的字段不修改;快递编码与平台相关字段不传即保持原值。 + * + * 限制:仅 CREATED / PENDING 状态允许修改;修改后收货信息不完整(name、(tel/mobile) 其一、 + * 省市区镇详细地址缺任一)时禁止提交。 + * + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @param {string} [data.name] 收件人姓名 + * @param {string} [data.tel] 固定电话 + * @param {string} [data.mobile] 移动电话 + * @param {string} [data.company] 公司名称 + * @param {string} [data.email] 电子邮箱 + * @param {string} [data.zipCode] 邮编 + * @param {string} [data.countryCode] 国家二字码 + * @param {string} [data.province] 省份 + * @param {string} [data.city] 城市 + * @param {string} [data.area] 区/县 + * @param {string} [data.town] 镇/街道 + * @param {string} [data.detailAddress] 详细地址 + * @param {string} [data.receiver_id] 收件人证件号 + * @param {string} [data.express_code] 快递公司编码(自动解析 express_name) + * @param {string} [data.source_platform_code] 来源平台编码 + * @param {string} [data.source_platform_name] 来源平台名称 + * @return {Promise} 统一成功/失败包装响应 + */ + async updateInfo(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + if (warehouseId <= 0) { + return this.fail('缺少仓库上下文'); + } + + const order = await ctx.model.OrderStockout.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!order) { + return this.fail('出库单不存在'); + } + + if (![ 'CREATED', 'PENDING' ].includes(order.order_status)) { + return this.fail(`出库单当前状态(${order.order_status})不允许修改`); + } + + const updateData = { updated_at: new Date() }; + const changedLabels = []; + + // 收件人 / 地址字段:传入才更新,空串置 NULL + const receiverFieldMap = { + receiver_name: [ 'name', '收件人姓名' ], + receiver_tel: [ 'tel', '固定电话' ], + receiver_mobile: [ 'mobile', '移动电话' ], + receiver_company: [ 'company', '公司名称' ], + receiver_email: [ 'email', '电子邮箱' ], + receiver_zip_code: [ 'zipCode', '邮编' ], + receiver_country_code: [ 'countryCode', '国家' ], + receiver_province: [ 'province', '省份' ], + receiver_city: [ 'city', '城市' ], + receiver_area: [ 'area', '区县' ], + receiver_town: [ 'town', '镇街道' ], + receiver_detail_address: [ 'detailAddress', '详细地址' ], + receiver_id: [ 'receiver_id', '证件号' ], + }; + for (const [ column, [ param, label ]] of Object.entries(receiverFieldMap)) { + if (data[param] !== undefined) { + updateData[column] = data[param] === null + ? null + : String(data[param]).trim() || null; + changedLabels.push(label); + } + } + + // 快递编码:传入才更新,并自动解析 express_name(与 updateExpress 同口径) + if (data.express_code !== undefined) { + const expressCode = String(data.express_code || '').trim(); + if (expressCode) { + let expressName = ''; + try { + const expressMap = await ctx.service.systems.setting.express.getSystemExpressMap(); + const info = expressMap.get(expressCode.toUpperCase()); + expressName = info ? info.name : ''; + } catch (e) { + ctx.logger.warn('[updateInfo] 解析快递名称失败: ' + e.message); + } + updateData.express_code = expressCode; + updateData.express_name = expressName; + } else { + updateData.express_code = null; + updateData.express_name = null; + } + changedLabels.push('快递编码'); + } + + // 来源平台:传入才更新,空串置 NULL + if (data.source_platform_code !== undefined) { + updateData.source_platform_code = String(data.source_platform_code || '').trim() || null; + changedLabels.push('来源平台'); + } + if (data.source_platform_name !== undefined) { + updateData.source_platform_name = String(data.source_platform_name || '').trim() || null; + if (!changedLabels.includes('来源平台')) { + changedLabels.push('来源平台'); + } + } + + // 修改后的收货信息完整性校验:name、(tel/mobile) 其一、省市区镇详细地址必填,缺失禁止提交 + const mergedReceiver = { + name: updateData.receiver_name !== undefined ? updateData.receiver_name : order.receiver_name, + tel: updateData.receiver_tel !== undefined ? updateData.receiver_tel : order.receiver_tel, + mobile: updateData.receiver_mobile !== undefined ? updateData.receiver_mobile : order.receiver_mobile, + province: updateData.receiver_province !== undefined ? updateData.receiver_province : order.receiver_province, + city: updateData.receiver_city !== undefined ? updateData.receiver_city : order.receiver_city, + area: updateData.receiver_area !== undefined ? updateData.receiver_area : order.receiver_area, + town: updateData.receiver_town !== undefined ? updateData.receiver_town : order.receiver_town, + detailAddress: updateData.receiver_detail_address !== undefined ? updateData.receiver_detail_address : order.receiver_detail_address, + }; + const missingFields = []; + if (!String(mergedReceiver.name || '').trim()) { + missingFields.push('name(收件人姓名)'); + } + if (!String(mergedReceiver.tel || '').trim() && !String(mergedReceiver.mobile || '').trim()) { + missingFields.push('tel/mobile(固定电话或移动电话至少一项)'); + } + const addressFields = [ + [ 'province', '省' ], + [ 'city', '市' ], + [ 'area', '区' ], + [ 'town', '镇' ], + [ 'detailAddress', '详细地址' ], + ]; + for (const [ key, label ] of addressFields) { + if (!String(mergedReceiver[key] || '').trim()) { + missingFields.push(`${key}(${label})`); + } + } + if (missingFields.length > 0) { + return this.fail(`收货信息缺失,禁止提交:缺少 ${missingFields.join('、')}`); + } + + await ctx.model.OrderStockout.update(updateData, { where: { id: order.id } }); + const updated = await ctx.model.OrderStockout.findByPk(order.id, { raw: true }); + + if (changedLabels.length > 0) { + await this._writeStockoutOperationLog( + order, + 'STOCKOUT_UPDATE_INFO', + `修改出库单信息:${changedLabels.join('、')}` + ); + } + + return this.success('修改成功', updated); + } +} + +module.exports = StorageStockoutService; diff --git a/app/service/systemMethods/storage/transaction.js b/app/service/systemMethods/storage/transaction.js new file mode 100644 index 0000000..4055045 --- /dev/null +++ b/app/service/systemMethods/storage/transaction.js @@ -0,0 +1,317 @@ +'use strict'; + +const MainService = require('../../main'); + +const STORAGE_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX = 'storage_transaction_export_task_'; +const STORAGE_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +class StorageTransactionService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,export,exportTaskProgress'; + const _noNeedLog = 'list,export,exportTaskProgress'; + const _noNeedAuth = 'list,export,exportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 解析 list/export 通用过滤入参(where 白名单字段 + 时间区间 + keyword)。 + * @param {Object} data 请求体 + * @return {Object} 归一化后的过滤参数 + */ + _parseListFilters(data = {}) { + const { whereValue = {} } = this.prepareWhereContext(data); + const { keyword: topKeyword } = data; + const { + transaction_type: transactionType, + stock_id: stockIdRaw, + stock_ids: stockIdsRaw, + space_id: spaceId, + store_id: storeIdRaw, + store_ids: storeIdsRaw, + order_type: orderType, + order_no: orderNo, + batch_no: batchNo, + inventory_type: inventoryType, + operator_name: operatorName, + order_id: orderId, + start_time: startTime, + end_time: endTime, + created_at: createdAt, + keyword: whereKeyword, + } = whereValue; + + // created_at 支持 between:规范化后 value 为 [start, end] 数组 + const createdRange = Array.isArray(createdAt) ? createdAt : []; + const resolvedStartTime = startTime ?? createdRange[0] ?? null; + const resolvedEndTime = endTime ?? createdRange[1] ?? null; + + // 兼容 stock_id(单数)与 stock_ids(数组),store_id 同理 + const stockIds = stockIdsRaw !== undefined + ? stockIdsRaw + : (stockIdRaw !== undefined ? [ stockIdRaw ] : null); + const storeIds = storeIdsRaw !== undefined + ? storeIdsRaw + : (storeIdRaw !== undefined ? [ storeIdRaw ] : null); + const keyword = topKeyword ?? whereKeyword ?? ''; + + // 仓库ID 由服务端从当前上下文注入,禁止前端传参 + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + + return { + warehouseId, + startTime: resolvedStartTime, + endTime: resolvedEndTime, + storeIds, + stockIds, + spaceId, + keyword, + transactionType, + orderType, + orderNo, + batchNo, + inventoryType, + operatorName, + orderId, + }; + } + + /** + * 库位维度出入库流水逐条明细列表(wms_storage_transaction)。 + * 支持 where 条件、keyword 快捷搜索、分页、排序;仓库ID由服务端从当前上下文自动注入。 + * group_by_batch 参数已废弃:本接口不再聚合,恒返回逐条明细。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.where.created_at] 创建时间区间(operator: between,value: [start, end]) + * @param {Object} [data.pagination] 分页参数 { page, pageSize } + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } + * @param {string} [data.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配) + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { pagination = {}, sort = {} } = data; + const filters = this._parseListFilters(data); + const result = await service.systems.stockTransaction.list({ + ...filters, + sort, + pagination, + }); + return this.success('ok', result); + } + + /** + * 提交库位流水导出异步任务。 + * 与 list 使用相同查询条件(where/sort/keyword),异步执行,立即返回任务ID。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(与 list 完全一致) + * @param {Object} [data.sort] 排序参数(与 list 完全一致) + * @param {string} [data.keyword] 商品关键字(与 list 完全一致) + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async export(data = {}) { + const { service } = this; + const { sort = {} } = data; + const filters = this._parseListFilters(data); + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.stockTransaction.exportStorageList({ + ...filters, + sort, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询库位流水导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成库位流水导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `storage_transaction_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化库位流水导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取库位流水导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${STORAGE_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入库位流水导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, STORAGE_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.transaction.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取库位流水导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.transaction.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } +} + +module.exports = StorageTransactionService; diff --git a/app/service/systemMethods/store.js b/app/service/systemMethods/store.js index 25b66ff..67bcfe4 100644 --- a/app/service/systemMethods/store.js +++ b/app/service/systemMethods/store.js @@ -35,11 +35,6 @@ class storeService extends MainService { const result = await service.systems.store.getStoreRoles(data); return this.success('ok', result); } - async getStoreRoles(data) { - const { service } = this; - const result = await service.systems.store.getStoreRoles(data); - return this.success('ok', result); - } async auditApply(data) { const { service } = this; const result = await service.systems.store.auditApply(data); diff --git a/app/service/systemMethods/storeWarehouse.js b/app/service/systemMethods/storeWarehouse.js new file mode 100644 index 0000000..c2d748e --- /dev/null +++ b/app/service/systemMethods/storeWarehouse.js @@ -0,0 +1,16 @@ +'use strict'; + +const MainService = require('../main'); +const StoreWarehouseStoreService = require('./storeWarehouse/store'); +const StoreWarehouseWarehouseService = require('./storeWarehouse/warehouse'); + +class StoreWarehouseNamespaceService extends MainService { + constructor(ctx) { + super(ctx); + this.systemInit('', '', '*', ''); + this.store = new StoreWarehouseStoreService(ctx); + this.warehouse = new StoreWarehouseWarehouseService(ctx); + } +} + +module.exports = StoreWarehouseNamespaceService; diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js new file mode 100644 index 0000000..02de554 --- /dev/null +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -0,0 +1,1034 @@ +'use strict'; + +const MainService = require('../../main'); + +const PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_KEY_PREFIX = 'print_quantity_log_export_task_'; +const PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + + +/** + * 规范仓库配置方法入参,避免把原始引用直接传给下游服务。 + * + * @param {Object} data 请求数据。 + * @return {Object} 复制后的请求数据。 + */ +function normalizeStoreWarehousePayload(data) { + if (!data || typeof data !== 'object' || Array.isArray(data)) { + return {}; + } + + return { ...data }; +} + +class StoreWarehouseStoreService extends MainService { + /** + * 创建一个仓库配置 store 服务。 + * + * @param {Object} ctx 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,export,exportTaskProgress,sign,confirmSign,unbind,rename,openAccount,createUser,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,export,exportTaskProgress,sign,confirmSign,unbind,rename,openAccount,createUser,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 获取签约列表(货主侧)。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async list(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.listForStore !== 'function') { + return this.fail('获取签约列表失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.listForStore(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取签约列表失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 发起签约。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async sign(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.sign !== 'function') { + return this.fail('签约失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.sign(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '签约失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 确认签约:对方主体确认待签约的申请。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async confirmSign(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.confirmSign !== 'function') { + return this.fail('确认签约失败', { code: 500 }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.confirmSign(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '确认签约失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 修改签约名称。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async rename(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.rename !== 'function') { + return this.fail('修改签约名称失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.rename(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '修改签约名称失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 解除签约。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async unbind(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.unbind !== 'function') { + return this.fail('解除签约失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.unbind(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '解除签约失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 人工调整面单余额。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async adjustPrintQuantity(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.adjustPrintQuantity !== 'function') { + return this.fail('人工调整面单余额失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.adjustPrintQuantity(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '人工调整面单余额失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 查询面单余额变更日志(分页)。 + * + * @param {Object} data 请求数据。 + * @param {number|string} data.store_id 货主 ID。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.pagination] 分页对象。 + * @param {number|string} [data.pagination.page] 页码。 + * @param {number|string} [data.pagination.page_size] 每页条数。 + * @return {Promise} 统一响应结果。 + */ + async queryPrintQuantityLogs(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.queryPrintQuantityLogs !== 'function') { + return this.fail('查询面单余额变更日志失败', { + code: 500, + }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { where } = this.prepareWhereContext(requestData); + const { + store_id, + } = requestData; + const rawPagination = requestData.pagination && typeof requestData.pagination === 'object' + ? requestData.pagination + : {}; + const { + page, + page_size, + } = rawPagination; + + const result = await targetService.queryPrintQuantityLogs({ + store_id, + where, + pagination: { + page, + page_size, + }, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '查询面单余额变更日志失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取合约策略配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async getPolicyConfig(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.getPolicyConfig !== 'function') { + return this.fail('获取合约策略配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.getPolicyConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取合约策略配置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取合约策略字段信息。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async getPolicyConfigFields(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.getPolicyConfigFields !== 'function') { + return this.fail('获取合约策略字段信息失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.getPolicyConfigFields(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取合约策略字段信息失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 保存合约策略配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async savePolicyConfig(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.savePolicyConfig !== 'function') { + return this.fail('保存合约策略配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.savePolicyConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '保存合约策略配置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取接口配置列表。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async listApiConfig(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.listApiConfig !== 'function') { + return this.fail('获取接口配置列表失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.listApiConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取接口配置列表失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 保存接口配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async saveApiConfig(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.saveApiConfig !== 'function') { + return this.fail('保存接口配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.saveApiConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '保存接口配置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 删除奇门接口配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async deleteQimenConfig(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.deleteQimenConfig !== 'function') { + return this.fail('删除接口配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.deleteQimenConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '删除接口配置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 仓库代货主一键开户。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async openAccount(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.openAccount !== 'function') { + return this.fail('一键开户失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.openAccount(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '一键开户失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 为货主创建用户:按用户名查找账号,不存在则注册并随机生成密码返回, + * 两种情况统一完成货主工号绑定与货主管理员角色(id=5)授权。 + * + * @param {Object} data 请求数据。 + * @param {string} data.username 用户名(必填)。 + * @param {number|string} data.store_id 货主 ID(必填)。 + * @return {Promise} 统一响应结果。 + */ + async createUser(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.createUser !== 'function') { + return this.fail('创建货主用户失败', { + code: 500, + }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { + username, + store_id, + } = requestData; + + const result = await targetService.createUser({ + username, + store_id, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '创建货主用户失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 提交货主签约列表导出任务(异步)。 + * 入参筛选条件与 storeWarehouse.store.list 的 listForStore 语义一致 + * (keyword/counterparty_id/store_id/auth_status/use_status/warehouse_use_status/id 等), + * page/page_size 忽略(全量导出)。提交后立即返回 task_id,后台异步生成 Excel 并上传, + * 导出进度/下载请通过 exportTaskProgress 查询。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果(包含 task_id)。 + */ + async export(data = {}) { + const { service } = this; + const targetService = service && service.systems && service.systems.storeWarehouse; + + if (!targetService || typeof targetService.exportListForStore !== 'function') { + return this.fail('导出签约列表失败', { code: 500 }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const taskId = this.generateExportTaskId('', { base: 'store_relation_list' }); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await targetService.exportListForStore(requestData); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } catch (error) { + return this.fail(error.message || '导出签约列表失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 查询货主签约列表导出任务进度。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一响应结果。 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 提交面单余额变更日志导出任务。 + * 入参条件与 queryPrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。 + * + * @param {Object} data 请求数据。 + * @param {number|string} data.store_id 货主ID(必填)。 + * @param {Object} [data.where] 动态筛选条件,与 queryPrintQuantityLogs 的 where 语义一致。 + * @return {Promise} 统一响应结果(包含 task_id)。 + */ + async exportPrintQuantityLogs(data = {}) { + const { service } = this; + const targetService = service && service.systems && service.systems.storeWarehouse; + + if (!targetService || typeof targetService.exportPrintQuantityLogs !== 'function') { + return this.fail('导出面单余额变更日志失败', { code: 500 }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { where } = this.prepareWhereContext(requestData); + const { store_id } = requestData; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await targetService.exportPrintQuantityLogs({ + store_id, + where, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } catch (error) { + return this.fail(error.message || '导出面单余额变更日志失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 查询面单余额变更日志导出任务进度。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一响应结果。 + */ + async exportPrintQuantityLogsTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 货主侧查询面单余额变更日志(自动从平台激活上下文获取 store_id)。 + * 无需显式传入 store_id,系统自动从当前用户激活的货主平台上下文中获取。 + * + * @param {Object} data 请求数据。 + * @param {Object} [data.where] 动态筛选条件。 + * @param {Object} [data.pagination] 分页对象。 + * @param {number|string} [data.pagination.page] 页码。 + * @param {number|string} [data.pagination.page_size] 每页条数。 + * @return {Promise} 统一响应结果。 + */ + async queryStorePrintQuantityLogs(data = {}) { + const { ctx, app, service } = this; + + // 从平台激活上下文获取 store_id + const platformRows = await app.model.query( + 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + + 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + + 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', + { + replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { + return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); + } + + const storeId = platformRows[0].store_id; + const targetService = service && service.systems && service.systems.storeWarehouse; + + if (!targetService || typeof targetService.queryPrintQuantityLogs !== 'function') { + return this.fail('查询面单余额变更日志失败', { code: 500 }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { where } = this.prepareWhereContext(requestData); + const rawPagination = requestData.pagination && typeof requestData.pagination === 'object' + ? requestData.pagination + : {}; + const { page, page_size } = rawPagination; + + const result = await targetService.queryPrintQuantityLogs({ + store_id: storeId, + where, + pagination: { page, page_size }, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '查询面单余额变更日志失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 货主侧提交面单余额变更日志导出任务(自动从平台激活上下文获取 store_id)。 + * 入参条件与 queryStorePrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。 + * + * @param {Object} data 请求数据。 + * @param {Object} [data.where] 动态筛选条件。 + * @return {Promise} 统一响应结果(包含 task_id)。 + */ + async exportStorePrintQuantityLogs(data = {}) { + const { ctx, app, service } = this; + + // 从平台激活上下文获取 store_id + const platformRows = await app.model.query( + 'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' + + 'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' + + 'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1', + { + replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) { + return this.fail('未获取到货主平台激活上下文,请先切换至货主角色'); + } + + const storeId = platformRows[0].store_id; + const targetService = service && service.systems && service.systems.storeWarehouse; + + if (!targetService || typeof targetService.exportPrintQuantityLogs !== 'function') { + return this.fail('导出面单余额变更日志失败', { code: 500 }); + } + + try { + const requestData = normalizeStoreWarehousePayload(data); + const { where } = this.prepareWhereContext(requestData); + + const taskId = this.generateExportTaskId('store'); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '货主侧导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '货主侧导出任务执行中', + result: null, + error: '', + }); + + const result = await targetService.exportPrintQuantityLogs({ + store_id: storeId, + where, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '货主侧导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '货主侧导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } catch (error) { + return this.fail(error.message || '导出面单余额变更日志失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 货主侧查询面单余额变更日志导出任务进度。 + * 复用 exportPrintQuantityLogsTaskProgress 的缓存查询逻辑。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一响应结果。 + */ + async exportStorePrintQuantityLogsTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成导出任务ID。 + * @param {string} [prefix=''] 任务类型子前缀(如 'store')。 + * @param {Object} [options={}] 配置项。 + * @param {string} [options.base='print_qty_log'] 任务基础前缀,用于区分不同导出业务。 + * @return {string} 导出任务ID。 + */ + generateExportTaskId(prefix = '', options = {}) { + const storeId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const safeOptions = this.isPlainObject(options) ? options : {}; + const basePrefix = String(safeOptions.base || '').trim() || 'print_qty_log'; + const typePrefix = prefix ? `${prefix}_` : ''; + return `${basePrefix}_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态载荷。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) + : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[storeWarehouse.store.exportPrintQuantityLogs] 写入导出任务缓存失败: %s', + error && error.message ? error.message : error); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[storeWarehouse.store.exportPrintQuantityLogs] 读取导出任务缓存失败: %s', + error && error.message ? error.message : error); + return null; + } + } +} + +module.exports = StoreWarehouseStoreService; diff --git a/app/service/systemMethods/storeWarehouse/warehouse.js b/app/service/systemMethods/storeWarehouse/warehouse.js new file mode 100644 index 0000000..5661b49 --- /dev/null +++ b/app/service/systemMethods/storeWarehouse/warehouse.js @@ -0,0 +1,89 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 规范签约请求入参。 + * + * @param {Object} data 请求数据。 + * @return {Object} 复制后的请求数据。 + */ +function normalizeWarehouseStorePayload(data) { + if (!data || typeof data !== 'object' || Array.isArray(data)) { + return {}; + } + return { ...data }; +} + +class StoreWarehouseWarehouseService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,sign,confirmSign'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,sign,confirmSign'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 仓库侧获取签约列表(含外部合作仓库)。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async list(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.listForWarehouse !== 'function') { + return this.fail('获取签约列表失败', { code: 500 }); + } + + try { + const payload = normalizeWarehouseStorePayload(data); + const result = await targetService.listForWarehouse(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取签约列表失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 仓库侧发起签约。 + * @param data + */ + async sign(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + if (!targetService || typeof targetService.sign !== 'function') { + return this.fail('签约失败', { code: 500 }); + } + try { + const payload = normalizeWarehouseStorePayload(data); + const result = await targetService.sign(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '签约失败', { code: Number(error.code) || 500 }); + } + } + + /** + * 仓库侧确认签约。 + * @param data + */ + async confirmSign(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + if (!targetService || typeof targetService.confirmSign !== 'function') { + return this.fail('确认签约失败', { code: 500 }); + } + try { + const payload = normalizeWarehouseStorePayload(data); + const result = await targetService.confirmSign(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '确认签约失败', { code: Number(error.code) || 500 }); + } + } +} + +module.exports = StoreWarehouseWarehouseService; diff --git a/app/service/systemMethods/store_express_binding_policy.js b/app/service/systemMethods/store_express_binding_policy.js new file mode 100644 index 0000000..b97258e --- /dev/null +++ b/app/service/systemMethods/store_express_binding_policy.js @@ -0,0 +1,210 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 店铺-快递绑定策略 methods 出口。 + * + * 支持以下 method 调用(通过 /system?method=storeExpressBindingPolicy.xxx): + * - storeExpressBindingPolicy.list 分页查询策略列表 + * - storeExpressBindingPolicy.add 新增策略 + * - storeExpressBindingPolicy.edit 编辑策略 + * - storeExpressBindingPolicy.del 软删除策略 + */ +class StoreExpressBindingPolicyMethodService extends MainService { + /** + * 初始化鉴权配置。 + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = '*'; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用业务服务。 + * @param {string} methodName 业务方法名 + * @param {Object} data 请求参数 + * @param {string} fallbackMessage 默认错误文案 + * @return {Promise} methods 标准返回 + */ + async callSystem(methodName, data, fallbackMessage) { + const { service } = this; + + try { + const result = await service.systems.storeExpressBindingPolicy[methodName](data); + return this.success('ok', { data: result, code: 200 }); + } catch (error) { + return this.fail(error.message || fallbackMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * storeExpressBindingPolicy.list:分页查询策略列表。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 查询结果 + */ + async list(data = {}) { + const payload = { + ...(data && typeof data === 'object' ? data : {}), + }; + + this.prepareWhereContext(payload, { + specialFieldMap: this.service.systems.storeExpressBindingPolicy.getListWhereSpecialFieldMap(), + }); + + return await this.callSystem('list', payload, '查询策略列表失败'); + } + + /** + * storeExpressBindingPolicy.add:新增策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 新增结果 + */ + async add(data = {}) { + const { + custom_name: customName, + customName: customNameCamel, + express_code: expressCode, + expressCode: expressCodeCamel, + priority, + is_enabled: isEnabled, + isEnabled: isEnabledCamel, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeId, + prohibitedTypeId: prohibitedTypeIdCamel, + remark, + creator_id: creatorId, + creatorId: creatorIdCamel, + } = data || {}; + + return await this.callSystem('add', { + custom_name: customName !== undefined ? customName : customNameCamel, + express_code: expressCode !== undefined ? expressCode : expressCodeCamel, + priority, + is_enabled: isEnabled !== undefined ? isEnabled : isEnabledCamel, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeId !== undefined ? prohibitedTypeId : prohibitedTypeIdCamel, + remark, + creator_id: creatorId !== undefined ? creatorId : creatorIdCamel, + }, '新增策略失败'); + } + + /** + * storeExpressBindingPolicy.edit:编辑策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 编辑结果 + */ + async edit(data = {}) { + const { + id, + policy_id: policyId, + policyId: policyIdCamel, + custom_name: customName, + customName: customNameCamel, + express_code: expressCode, + expressCode: expressCodeCamel, + priority, + is_enabled: isEnabled, + isEnabled: isEnabledCamel, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeId, + prohibitedTypeId: prohibitedTypeIdCamel, + remark, + creator_id: creatorId, + creatorId: creatorIdCamel, + } = data || {}; + + const payload = { + id: id !== undefined ? id : (policyId !== undefined ? policyId : policyIdCamel), + }; + + if (customName !== undefined || customNameCamel !== undefined) { + payload.custom_name = customName !== undefined ? customName : customNameCamel; + } + if (expressCode !== undefined || expressCodeCamel !== undefined) { + payload.express_code = expressCode !== undefined ? expressCode : expressCodeCamel; + } + if (priority !== undefined) { + payload.priority = priority; + } + if (isEnabled !== undefined || isEnabledCamel !== undefined) { + payload.is_enabled = isEnabled !== undefined ? isEnabled : isEnabledCamel; + } + if (regions !== undefined) { + payload.regions = regions; + } + if (shopName !== undefined) { + payload.shop_name = shopName; + } + if (storeIds !== undefined) { + payload.store_ids = storeIds; + } + if (excludeRegions !== undefined) { + payload.exclude_regions = excludeRegions; + } + if (minWeightG !== undefined) { + payload.min_weight_g = minWeightG; + } + if (maxWeightG !== undefined) { + payload.max_weight_g = maxWeightG; + } + if (weightType !== undefined) { + payload.weight_type = weightType; + } + if (prohibitedTypeId !== undefined || prohibitedTypeIdCamel !== undefined) { + payload.prohibited_type_id = prohibitedTypeId !== undefined ? prohibitedTypeId : prohibitedTypeIdCamel; + } + if (remark !== undefined) { + payload.remark = remark; + } + if (creatorId !== undefined || creatorIdCamel !== undefined) { + payload.creator_id = creatorId !== undefined ? creatorId : creatorIdCamel; + } + + return await this.callSystem('edit', payload, '编辑策略失败'); + } + + /** + * storeExpressBindingPolicy.del:软删除策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 删除结果 + */ + async del(data = {}) { + const { + id, + policy_id: policyId, + policyId: policyIdCamel, + } = data || {}; + + return await this.callSystem('del', { + id: id !== undefined ? id : (policyId !== undefined ? policyId : policyIdCamel), + }, '删除策略失败'); + } +} + +module.exports = StoreExpressBindingPolicyMethodService; diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index 1a83b5d..33a2deb 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -5,23 +5,65 @@ const MainService = require('../main'); class userService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = 'login,register'; + const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode'; const _noNeedRight = '*'; - const _noNeedLog = 'info'; + const _noNeedLog = 'info,getAccountInfo,changePassword,getBindWechatCode,getLoginWechatCode'; const _noNeedAuth = '*'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + // info:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问 + const _noNeedBind = 'info'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth, _noNeedBind); } async login(data) { const { service } = this; const { username, password } = data; const result = await service.systems.auth.user.login(username, password); - console.log('result', result); if (result.code) { return this.success('登录成功', result); } return this.fail('登录失败:' + result.message, result); } + async loginByCode(data) { + const { service } = this; + const code = typeof data?.code === 'string' ? data.code.trim() : ''; + if (!code) { + return this.fail('1111登录失败:缺少登录码 code', { + success: false, + data: null, + code: 0, + message: '缺少登录码 code', + }); + } + const result = await service.systems.auth.user.loginByYe4sCode(code); + if (result.code) { + return this.success('登录成功', result); + } + return this.fail('登录失败:' + result.message, result); + } + async getBindWechatCode(data) { + const { service } = this; + const result = await service.systems.auth.user.getBindWechatCode(data); + if (result.code) { + return this.success('获取绑定微信码成功', result); + } + return this.fail('获取绑定微信码失败:' + result.message, result); + } + async getLoginWechatCode(data) { + const { service } = this; + const result = await service.systems.auth.user.getLoginWechatCode(data); + if (result.code) { + return this.success('获取微信登录码成功', result); + } + return this.fail('获取微信登录码失败:' + result.message, result); + } + async unbindWechat(data) { + const { service } = this; + const result = await service.systems.auth.user.unbindWechat(data); + if (result.code) { + return this.success('解绑成功', result); + } + return this.fail('解绑失败:' + result.message, result); + } async logout() { return this.success('登出成功'); } @@ -30,12 +72,39 @@ class userService extends MainService { const result = await service.systems.auth.user.info(data); return this.success('获取成功' + JSON.stringify(data), result); } + // 获取当前登录账号的账号级信息(仅 wms_account,不含敏感字段) + async getAccountInfo(data) { + const { service } = this; + const result = await service.systems.auth.user.getAccountInfo(data); + if (result.code === 200) { + return this.success(result.message || '获取账号信息成功', result); + } + return this.fail(result.message || '获取账号信息失败', result); + } + // 修改当前账号用户名(服务端校验重名,排除自己) + async updateUsername(data) { + const { service } = this; + const result = await service.systems.auth.user.updateUsername(data); + if (result.code === 200) { + return this.success(result.message || '用户名修改成功', result); + } + return this.fail(result.message || '用户名修改失败', result); + } + // 修改当前账号密码(首次自定义密码可不传旧密码) + async changePassword(data) { + const { service } = this; + const result = await service.systems.auth.user.changePassword(data); + if (result.code === 200) { + return this.success(result.message || '密码修改成功', result); + } + return this.fail(result.message || '密码修改失败', result); + } async changeRole(data) { const { service } = this; const result = await service.systems.auth.user.changeRole(data); return this.success('获取成功', result, 200); } - //注册 + // 注册 async register(data) { const { service } = this; const result = await service.systems.auth.user.register(data); diff --git a/app/service/systemMethods/warehouse.js b/app/service/systemMethods/warehouse.js index e053bb1..493a5e7 100644 --- a/app/service/systemMethods/warehouse.js +++ b/app/service/systemMethods/warehouse.js @@ -1,5 +1,6 @@ 'use strict'; +const ExcelJS = require('exceljs'); const MainService = require('../main'); class warehouseService extends MainService { @@ -13,22 +14,20 @@ class warehouseService extends MainService { } async getWarehouseZones() { const { ctx, service } = this; - console.log('获取仓库主体下所有实体仓库'); try { const zones = await service.systems.locationZone.getWarehouseLevelZones(ctx.user.store_id); return this.success('获取成功', { zones, code: 200 }); } catch (error) { - console.log(error); return this.fail('获取失败' + error.message, { code: 0 }); } } /** * 获取仓库树状结构 - * @param data + * @param {Object} data 请求体 */ async getWarehouseTree(data) { - const { ctx, service } = this; + const { service } = this; const { warehouseId } = data; try { @@ -45,7 +44,7 @@ class warehouseService extends MainService { /** * 获取子节点(懒加载) - * @param data + * @param {Object} data 请求体 */ async getChildren(data) { const { ctx, service } = this; @@ -65,10 +64,10 @@ class warehouseService extends MainService { /** * 创建分区 - * @param data + * @param {Object} data 请求体 */ async create(data) { - const { ctx, service } = this; + const { service } = this; try { const result = await service.systems.locationZone.createZone(data); @@ -80,19 +79,18 @@ class warehouseService extends MainService { /** * 更新分区 - * @param datas + * @param {Object} datas 请求体 */ async update(datas) { - const { ctx, service } = this; - console.log('接收的数据', datas); + const { service } = this; const { id } = datas; - const { length, width, height, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles } = datas; + const { length, width, height, is_active, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles } = datas; try { if (!id) { return this.fail('分区ID不能为空'); } - const result = await service.systems.locationZone.updateZone(parseInt(id), { length, width, height, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles }); + const result = await service.systems.locationZone.updateZone(parseInt(id), { length, width, height, is_active, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles }); return this.success(result.message, { data: result.data, code: 200 }); } catch (error) { return this.fail(error.message); @@ -101,10 +99,10 @@ class warehouseService extends MainService { /** * 删除分区 - * @param data + * @param {Object} data 请求体 */ async delete(data) { - const { ctx, service } = this; + const { service } = this; const { id } = data; try { @@ -113,20 +111,18 @@ class warehouseService extends MainService { } const result = await service.systems.locationZone.deleteZone(parseInt(id)); - console.log('删除返回', result); return this.success(result.message, { code: 200 }); } catch (error) { - console.log('error', error); return this.fail(error.message); } } /** * 获取分区详情 - * @param data + * @param {Object} data 请求体 */ async detail(data) { - const { ctx, service } = this; + const { service } = this; const { id } = data; try { @@ -140,9 +136,8 @@ class warehouseService extends MainService { } } async checkBarcodeUnique(data) { - const { ctx, service } = this; + const { service } = this; const { id, barcode } = data; - console.log(data); try { if (!id) { return this.fail('库位ID不能为空'); @@ -150,7 +145,7 @@ class warehouseService extends MainService { if (!barcode) { return this.fail('条码不能为空'); } - const data = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), barcode); + const data = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), barcode, this.ctx.user.store_id); return this.success('获取成功', { data, code: 200 }); } catch (error) { return this.fail(error.message); @@ -158,7 +153,7 @@ class warehouseService extends MainService { } /** * 切换分区状态 - * @param data + * @param {Object} data 请求体 */ async toggleActive(data) { const { ctx, service } = this; @@ -181,7 +176,7 @@ class warehouseService extends MainService { /** * 获取分区路径 - * @param data + * @param {Object} data 请求体 */ async getPath(data) { const { ctx, service } = this; @@ -198,36 +193,6 @@ class warehouseService extends MainService { this.fail(error.message); } } - async createRack() { - const { ctx } = this; - const params = ctx.request.body; - - // 验证参数 - ctx.validate({ - warehouse_id: { type: 'int', required: true }, - zone_code: { type: 'string', required: true }, - zone_name: { type: 'string', required: true }, - parent_id: { type: 'int', required: false }, - x: { type: 'int', required: true }, - y: { type: 'int', required: true }, - z: { type: 'int', required: false, default: 0 }, - length: { type: 'int', required: true }, - width: { type: 'int', required: true }, - height: { type: 'int', required: true }, - rack_columns: { type: 'int', required: true }, - rack_rows: { type: 'int', required: true }, - rack_levels: { type: 'int', required: true }, - direction: { type: 'enum', values: [ 'north', 'south', 'east', 'west' ], required: false }, - color: { type: 'string', required: false }, - }); - - try { - const rack = await ctx.service.location.createRackWithSpaces(params); - ctx.success(rack, '货架创建成功'); - } catch (error) { - this.fail(error.message, 400); - } - } /** * 获取拣货路径 @@ -366,7 +331,7 @@ class warehouseService extends MainService { zone_id: id, deleted_at: null, }, - order: [[ 'pick_sequence', 'ASC' ]], + order: [[ 'space_code', 'ASC' ]], }); return this.success('获取成功', { spaces, code: 200 }); } catch (e) { @@ -374,7 +339,7 @@ class warehouseService extends MainService { } } async createRackWithSpaces(data) { - const { ctx, app, service } = this; + const { ctx, service } = this; const { id } = data; if (!id) { return this.fail('货架ID不能为空'); @@ -386,39 +351,46 @@ class warehouseService extends MainService { id, deleted_at: null, }, + lock: transaction.LOCK.UPDATE, transaction, }); if (!rack) { throw new Error('货架不存在'); } - if (rack.zone_type != 'rack') { + if (rack.zone_type !== 'rack') { throw new Error('仓库元素不为货架,拒绝生成仓位'); } const message = await service.systems.locationZone.generateSpacesForRack(id, rack, transaction); await transaction.commit(); return this.success(message, { code: 200 }); } catch (e) { - console.log('创建错误', e); await transaction.rollback(); return this.fail(e.message, 500); } } + /** + * 获取仓位详情。 + * @param {Object} data 请求参数 + * @param {number|string} data.id 仓位ID + * @return {Promise} 标准响应结果 + */ async getSpaceInfo(data) { - const { ctx, service } = this; + const { service } = this; const { id } = data; try { const data = await service.systems.locationZone.getSpaceInfo(id); return this.success('获取成功', { data, code: 200 }); } catch (error) { - console.log(error); + if (error.message === '仓位不存在' || error.message === '仓位不属于当前仓库') { + return this.fail(error.message, { code: 0 }); + } return this.fail('获取失败' + error.message, { code: 0 }); } } async updateSpaceInfo(data) { - const { ctx, app, service } = this; - console.log('修改的数据', data); + const { ctx, service } = this; const { id } = data; if (!id) { return this.fail('仓位ID不能为空'); @@ -437,7 +409,7 @@ class warehouseService extends MainService { throw new Error('仓位不存在'); } if (data.custom_barcode) { - const { isUnique } = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), data.custom_barcode); + const { isUnique } = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), data.custom_barcode, ctx.user.store_id); if (!isUnique) { throw new Error('自定义条码已存在'); } @@ -459,5 +431,399 @@ class warehouseService extends MainService { } } + + getBatchFieldValue(row, keys) { + for (const key of keys) { + if (Object.prototype.hasOwnProperty.call(row, key)) { + return row[key]; + } + } + return undefined; + } + + hasBatchField(row, keys) { + return keys.some(key => Object.prototype.hasOwnProperty.call(row, key)); + } + + normalizeBatchString(value) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + return normalized === '' ? null : normalized; + } + + async getCurrentWarehouseCode(warehouseId, transaction) { + const { ctx } = this; + const warehouseZone = await ctx.model.LocationZone.findOne({ + where: { + warehouse_id: warehouseId, + zone_type: 'warehouse', + deleted_at: null, + }, + attributes: [ 'zone_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + return String(warehouseZone && warehouseZone.zone_code || warehouseId).trim(); + } + + async batchUpdateSpaceInfo(data) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const warehouseId = ctx.user && ctx.user.store_id; + const items = Array.isArray(data && data.items) ? data.items : (Array.isArray(data && data.list) ? data.list : []); + const rackId = data && data.id ? Number(data.id) : null; + + if (!warehouseId) { + return this.fail('缺少当前仓库上下文'); + } + if (items.length === 0) { + return this.fail('批量数据不能为空'); + } + if (rackId !== null && (!Number.isFinite(rackId) || rackId <= 0)) { + return this.fail('货架ID格式不正确'); + } + + const transaction = await ctx.model.transaction(); + try { + const seenSpaceCodes = new Set(); + const seenBarcodes = new Map(); + const normalizedItems = []; + const typeIdSet = new Set(); + const MAX_PICK_SEQUENCE = 2147483647; + + for (let index = 0; index < items.length; index++) { + const row = items[index]; + const rowNo = index + 1; + + if (!row || typeof row !== 'object' || Array.isArray(row)) { + throw new Error(`第 ${rowNo} 行数据格式不正确`); + } + + const spaceCode = this.normalizeBatchString(this.getBatchFieldValue(row, [ 'space_code', '仓位编码' ])); + if (!spaceCode) { + throw new Error(`第 ${rowNo} 行缺少仓位编码`); + } + if (seenSpaceCodes.has(spaceCode)) { + throw new Error(`第 ${rowNo} 行仓位编码重复: ${spaceCode}`); + } + seenSpaceCodes.add(spaceCode); + + const customName = this.normalizeBatchString(this.getBatchFieldValue(row, [ 'custom_name', '自定义名称' ])); + if (customName && customName.length > 100) { + throw new Error(`第 ${rowNo} 行自定义名称超出长度边界`); + } + + const customBarcode = this.normalizeBatchString(this.getBatchFieldValue(row, [ 'custom_barcode', '自定义条码' ])); + if (customBarcode && customBarcode.length > 100) { + throw new Error(`第 ${rowNo} 行自定义条码超出长度边界`); + } + if (customBarcode) { + const duplicateRowNo = seenBarcodes.get(customBarcode); + if (duplicateRowNo) { + throw new Error(`第 ${rowNo} 行自定义条码重复,首次出现在第 ${duplicateRowNo} 行`); + } + seenBarcodes.set(customBarcode, rowNo); + } + + const hasPickSequence = this.hasBatchField(row, [ 'pick_sequence', '拣货顺序' ]); + const rawPickSequence = this.getBatchFieldValue(row, [ 'pick_sequence', '拣货顺序' ]); + let pickSequence = null; + if (hasPickSequence) { + if (rawPickSequence === '' || rawPickSequence === null || rawPickSequence === undefined) { + pickSequence = null; + } else if (!Number.isInteger(Number(rawPickSequence))) { + throw new Error(`第 ${rowNo} 行拣货顺序必须为整数`); + } else { + pickSequence = Number(rawPickSequence); + if (pickSequence < 0 || pickSequence > MAX_PICK_SEQUENCE) { + throw new Error(`第 ${rowNo} 行拣货顺序超出边界`); + } + } + } + + const hasLocationTypeId = this.hasBatchField(row, [ 'location_type_id' ]); + const rawLocationTypeId = this.getBatchFieldValue(row, [ 'location_type_id' ]); + let locationTypeId = null; + if (hasLocationTypeId) { + if (rawLocationTypeId === '' || rawLocationTypeId === null || rawLocationTypeId === undefined) { + locationTypeId = null; + } else if (!Number.isInteger(Number(rawLocationTypeId)) || Number(rawLocationTypeId) <= 0) { + throw new Error(`第 ${rowNo} 行仓位类型ID必须为正整数`); + } else { + locationTypeId = Number(rawLocationTypeId); + typeIdSet.add(locationTypeId); + } + } + + normalizedItems.push({ + rowNo, + spaceCode, + customName, + customBarcode, + hasPickSequence, + pickSequence, + locationTypeId, + hasCustomName: this.hasBatchField(row, [ 'custom_name', '自定义名称' ]), + hasCustomBarcode: this.hasBatchField(row, [ 'custom_barcode', '自定义条码' ]), + hasLocationTypeId, + }); + } + + const spaces = await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: warehouseId, + deleted_at: null, + space_code: Array.from(seenSpaceCodes), + }, + include: [ + { + model: ctx.model.LocationZone, + as: 'zone', + attributes: [ 'id', 'zone_type' ], + required: true, + where: { + zone_type: 'rack', + deleted_at: null, + ...(rackId !== null ? { id: rackId } : {}), + }, + }, + ], + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const spaceMap = new Map(); + for (const space of spaces) { + spaceMap.set(String(space.space_code).trim(), space); + } + + const missingSpaceCodes = normalizedItems + .map(item => item.spaceCode) + .filter(spaceCode => !spaceMap.has(spaceCode)); + if (missingSpaceCodes.length > 0) { + throw new Error(`提交数据超出货架库位边界,以下仓位不存在或不属于当前货架: ${missingSpaceCodes.slice(0, 10).join(', ')}`); + } + + const targetIds = spaces.map(item => item.id); + if (targetIds.length !== normalizedItems.length) { + throw new Error('提交数据超出货架库位边界'); + } + + if (typeIdSet.size > 0) { + const locationTypes = await ctx.model.LocationType.findAll({ + where: { + id: Array.from(typeIdSet), + is_active: true, + [Op.or]: [ + { warehouse_id: warehouseId }, + { warehouse_id: null }, + ], + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + + const validTypeIds = new Set(locationTypes.map(lt => lt.id)); + const invalidTypeIds = Array.from(typeIdSet).filter(id => !validTypeIds.has(id)); + if (invalidTypeIds.length > 0) { + throw new Error(`存在无效仓位类型ID: ${invalidTypeIds.join(', ')}`); + } + } + + for (const item of normalizedItems) { + if (!item.customBarcode) { + continue; + } + const matchedSpace = spaceMap.get(item.customBarcode); + if (matchedSpace && String(matchedSpace.space_code).trim() !== item.spaceCode) { + throw new Error(`第 ${item.rowNo} 行自定义条码与其他仓位编码冲突: ${item.customBarcode}`); + } + } + + const requestedBarcodes = normalizedItems + .map(item => item.customBarcode) + .filter(Boolean); + if (requestedBarcodes.length > 0) { + const conflictSpace = await ctx.model.LocationSpace.findOne({ + where: { + warehouse_id: warehouseId, + deleted_at: null, + id: { + [Op.notIn]: targetIds, + }, + custom_barcode: requestedBarcodes, + }, + attributes: [ 'id', 'space_code', 'custom_barcode' ], + raw: true, + transaction, + }); + + if (conflictSpace) { + throw new Error(`存在重复条码冲突: ${conflictSpace.custom_barcode}`); + } + } + + await Promise.all(normalizedItems.map(item => { + const space = spaceMap.get(item.spaceCode); + const updateData = { + updated_by: ctx.user.id, + }; + + if (item.hasLocationTypeId) { + updateData.location_type_id = item.locationTypeId !== null ? item.locationTypeId : null; + } + if (item.hasCustomName) { + updateData.custom_name = item.customName; + } + if (item.hasCustomBarcode) { + updateData.custom_barcode = item.customBarcode; + } + if (item.hasPickSequence) { + updateData.pick_sequence = item.pickSequence; + } + + return space.update(updateData, { transaction }); + })); + + await transaction.commit(); + return this.success('批量保存成功', { + code: 200, + count: normalizedItems.length, + }); + } catch (error) { + await transaction.rollback(); + return this.fail(`批量保存失败: ${error.message}`, { code: 500 }); + } + } + + async exportRackSpaces(data) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const warehouseId = ctx.user && ctx.user.store_id; + const rackId = Number(data && data.id); + + if (!warehouseId) { + return this.fail('缺少当前仓库上下文'); + } + if (!Number.isFinite(rackId) || rackId <= 0) { + return this.fail('导出失败: 货架ID不能为空', { code: 500 }); + } + + try { + const warehouseCode = await this.getCurrentWarehouseCode(warehouseId); + + const rackZone = await ctx.model.LocationZone.findOne({ + where: { + id: rackId, + warehouse_id: warehouseId, + zone_type: 'rack', + deleted_at: null, + }, + attributes: [ 'id', 'zone_code' ], + raw: true, + }); + + if (!rackZone) { + return this.fail('导出失败: 指定货架不存在或不属于当前仓库', { code: 500 }); + } + + const [ spaces, locationTypes ] = await Promise.all([ + ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: warehouseId, + deleted_at: null, + zone_id: rackId, + }, + attributes: [ 'id', 'space_code', 'custom_name', 'custom_barcode', 'pick_sequence', 'location_type_id' ], + include: [ + { + model: ctx.model.LocationType, + as: 'locationType', + attributes: [ 'type_name' ], + required: false, + }, + ], + order: [[ 'space_code', 'ASC' ], [ 'id', 'ASC' ]], + }), + ctx.model.LocationType.findAll({ + where: { + is_active: true, + [Op.or]: [ + { warehouse_id: warehouseId }, + { warehouse_id: null }, + ], + }, + attributes: [ 'type_name' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }), + ]); + + if (!Array.isArray(spaces) || spaces.length === 0) { + return this.fail('导出失败: 指定货架下没有可导出的仓位数据', { code: 500 }); + } + + const locationTypeNames = locationTypes + .map(t => String(t.type_name || '').trim()) + .filter(Boolean); + + const workbook = new ExcelJS.Workbook(); + const worksheet = workbook.addWorksheet('货架导出'); + + worksheet.columns = [ + { header: '仓位编码', key: 'space_code', width: 20 }, + { header: '自定义名称', key: 'custom_name', width: 24 }, + { header: '自定义条码', key: 'custom_barcode', width: 24 }, + { header: '拣货顺序', key: 'pick_sequence', width: 14 }, + { header: '仓位类型', key: 'location_type_name', width: 18 }, + ]; + + worksheet.getRow(1).font = { bold: true }; + + for (const space of spaces) { + const row = typeof space.get === 'function' ? space.get({ plain: true }) : space; + worksheet.addRow({ + space_code: row && row.space_code ? String(row.space_code) : '', + custom_name: row && row.custom_name ? String(row.custom_name) : '', + custom_barcode: row && row.custom_barcode ? String(row.custom_barcode) : '', + pick_sequence: row && row.pick_sequence !== null && row.pick_sequence !== undefined ? Number(row.pick_sequence) : '', + location_type_name: String(row && row.locationType && row.locationType.type_name || '').trim(), + }); + } + + if (locationTypeNames.length > 0) { + const typeSheet = workbook.addWorksheet('_仓位类型', { state: 'veryHidden' }); + locationTypeNames.forEach((name, i) => { + typeSheet.getCell(i + 1, 1).value = name; + }); + const lastDataRow = spaces.length + 1; + worksheet.dataValidations.add(`E2:E${lastDataRow}`, { + type: 'list', + allowBlank: true, + formulae: [ `_仓位类型!$A$1:$A$${locationTypeNames.length}` ], + }); + } + + const rackCode = String(rackZone.zone_code || rackId).trim(); + const filename = `warehouse-rack-spaces-${warehouseCode || warehouseId}-${rackCode}.xlsx`; + const buffer = await workbook.xlsx.writeBuffer(); + const base64 = Buffer.from(buffer).toString('base64'); + + return this.success('导出成功', { + code: 200, + count: Array.isArray(spaces) ? spaces.length : 0, + base64, + filename, + mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }); + } catch (error) { + return this.fail(`导出失败: ${error.message}`); + } + } } module.exports = warehouseService; diff --git a/app/service/systemMethods/waybill/warehouse.js b/app/service/systemMethods/waybill/warehouse.js new file mode 100644 index 0000000..237df27 --- /dev/null +++ b/app/service/systemMethods/waybill/warehouse.js @@ -0,0 +1,682 @@ +'use strict'; + +const MainService = require('../../main'); + +const WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX = 'waybill_export_task_'; +const WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX = 'waybill_receive_task_'; +/** 轨迹查询所依赖的出站回调 method */ +const WAYBILL_TRACE_EVENT = 'waybill.getTrace'; +/** 轨迹查询外部接口未配置时的失败提示 */ +const WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE = + '如需查询运单物流轨迹,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口'; +/** 揽收状态查询所依赖的出站回调 method */ +const WAYBILL_RECEIVE_EVENT = 'waybill.getreceive'; +/** 仓库未配置外部接口时的失败提示(直接失败,不进入任务流程) */ +const WAYBILL_RECEIVE_NOT_CONFIGURED_MESSAGE = + '如需更新运单是否揽收信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口'; + +/** 按 where 筛选解析运单号时允许的最大条数(超出要求缩小范围) */ +const WAYBILL_RECEIVE_MAX_CODES = 5000; + +/** + * 运单号仓库侧入口层。 + * 负责鉴权声明、参数校验,委托 systems/waybill.js 执行业务逻辑。 + * + * 所有方法均需登录但无需细粒度鉴权(与订单列表保持一致)。 + */ +class WaybillWarehouseService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,getTrace'; + const _noNeedLog = ''; + const _noNeedAuth = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,getTrace'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 运单列表查询(仓库侧)。 + * 支持分页、多条件筛选、排序。 + * + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.pagination] 分页参数 { page, pageSize }。 + * @param {Object} [data.sort] 排序参数 { field, order }。 + * @return {Promise} 运单列表与分页信息。 + */ + async list(data) { + try { + const { where, pagination, sort } = data || {}; + const result = await this.service.systems.waybill.list({ + where: where || {}, + pagination: pagination || {}, + sort: sort || {}, + }); + return this.success('获取成功', result); + } catch (e) { + return this.fail(e.message); + } + } + + /** + * 运单详情查询(仓库侧)。 + * 支持按运单ID或运单号查询。 + * + * @param {Object} data 请求参数。 + * @param {number} [data.id] 运单记录ID。 + * @param {string} [data.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。 + * @return {Promise} 运单详情(含订单/打印/打包信息)。 + */ + async detail(data) { + try { + const { id, waybillCode } = data || {}; + if (!id && !waybillCode) { + return this.fail('运单ID或运单号不能为空'); + } + const result = await this.service.systems.waybill.detail({ + id, + waybillCode, + }); + return this.success('获取成功', result); + } catch (e) { + return this.fail(e.message); + } + } + + /** + * 运单导出(仓库侧)。异步任务模式,提交后通过 exportTaskProgress 查询进度。 + * + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件(同 list)。 + * @param {Object} [data.sort] 排序参数(同 list)。 + * @param {string[]} [data.exportFields] 需要导出的字段列表。 + * @return {Promise} 任务提交结果,含 task_id。 + */ + async export(data) { + try { + const { where, sort, exportFields } = data || {}; + const taskId = this.generateExportTaskId(); + + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await this.service.systems.waybill.export({ + where: where || {}, + sort: sort || {}, + exportFields, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress || 0, + current_count: safeProgress.currentCount || safeProgress.current_count || 0, + total_count: safeProgress.totalCount || safeProgress.total_count || 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } catch (e) { + return this.fail(e.message); + } + } + + /** + * 查询运单导出任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 任务进度信息。 + */ + async exportTaskProgress(data = {}) { + try { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } catch (e) { + return this.fail(e.message); + } + } + + /** + * 批量更新运单是否揽收(仓库侧)。 + * + * 链路走 OpenAPI 出站回调 `waybill.getreceive`(单批最多 10 单,自动切批), + * 不读取本地库的揽收标记;返回结果按 waybill_code + warehouse_id 回写 + * `wms_order_express.is_galaxy_receive`。 + * 异步任务模式:提交后通过 `updateReceiveTaskProgress` 查询进度。 + * 仓库未配置承接该 method 的 API 应用时直接失败(不创建任务)。 + * + * 入参二选一: + * - `waybillCodes`:显式运单号列表(优先); + * - `where`:与 `waybill.warehouse.list` 完全一致的筛选条件(不含分页/排序), + * 服务端先按条件解析运单号再走同一任务链路。 + * + * @param {Object} data 请求参数。 + * @param {string[]} [data.waybillCodes] 运单号列表(兼容 waybill_codes)。 + * @param {Object} [data.where] 筛选条件(同 waybill.warehouse.list 的 where)。 + * @return {Promise} 任务提交结果,含 task_id。 + */ + async updateReceive(data = {}) { + try { + const safeData = this.isPlainObject(data) ? data : {}; + let waybillCodes = this.normalizeReceiveWaybillCodes(safeData.waybillCodes || safeData.waybill_codes); + const rawWhere = this.isPlainObject(safeData.where) ? safeData.where : null; + + if (waybillCodes.length === 0 && !rawWhere) { + return this.fail('运单号不能为空,或传入 where 筛选条件'); + } + + const warehouseId = Number(this.ctx?.user?.store_id || 0); + if (!warehouseId) { + return this.fail('无法获取当前仓库ID'); + } + + // 未配置外部访问接口:直接失败,不进入任务流程 + const appKey = await this.resolveReceiveAppKey(warehouseId); + if (!appKey) { + return this.fail(WAYBILL_RECEIVE_NOT_CONFIGURED_MESSAGE); + } + + // 仅传 where 时:按与列表一致的筛选口径解析运单号(带数量上限,避免一次任务过大) + if (waybillCodes.length === 0) { + const resolved = await this.service.systems.waybill.resolveWaybillCodesByWhere({ + where: rawWhere, + warehouseId, + limit: WAYBILL_RECEIVE_MAX_CODES, + }); + if (resolved.exceeded) { + return this.fail( + `符合条件的运单超过 ${WAYBILL_RECEIVE_MAX_CODES} 条,请缩小筛选范围或直接传 waybillCodes` + ); + } + waybillCodes = this.normalizeReceiveWaybillCodes(resolved.codes); + if (waybillCodes.length === 0) { + return this.fail('未匹配到符合条件的运单'); + } + } + + const taskId = this.generateReceiveTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: waybillCodes.length, + message: '更新揽收状态任务已提交', + result: null, + error: '', + }; + await this.setReceiveTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setReceiveTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 0, + current_count: 0, + total_count: waybillCodes.length, + message: '正在查询运单揽收状态', + result: null, + error: '', + }); + + const result = await this.service.systems.waybill.queryReceiveStatus({ + warehouseId, + waybillCodes, + appKey, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setReceiveTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: safeProgress.progress || 0, + current_count: safeProgress.currentCount || 0, + total_count: safeProgress.totalCount || waybillCodes.length, + message: safeProgress.message || '正在查询运单揽收状态', + result: null, + error: '', + }); + }, + }); + + if (!result || result.success !== true) { + await this.setReceiveTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: waybillCodes.length, + message: '更新揽收状态失败', + result: null, + error: String(result && result.reason || '运单揽收状态查询失败'), + }); + return; + } + + const failedList = Array.isArray(result.failed) ? result.failed : []; + await this.setReceiveTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: waybillCodes.length, + total_count: waybillCodes.length, + message: `更新完成:更新 ${result.updated} 单,未变化 ${result.unchanged} 单,失败 ${failedList.length} 单`, + result: { + total: result.total, + updated: result.updated, + unchanged: result.unchanged, + not_found: Array.isArray(result.not_found) ? result.not_found : [], + failed: failedList, + }, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setReceiveTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '更新揽收状态失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } catch (e) { + return this.fail(e.message); + } + } + + /** + * 查询运单揽收状态更新任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 任务进度信息。 + */ + async updateReceiveTaskProgress(data = {}) { + try { + const safeData = this.isPlainObject(data) ? data : {}; + const taskId = String(safeData.task_id || safeData.taskId || '').trim(); + const notFoundPayload = { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + update_time: Date.now(), + }; + + if (!taskId) { + return this.success('ok', notFoundPayload); + } + + const cachedTask = await this.getReceiveTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', notFoundPayload); + } + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + update_time: Date.now(), + }); + } catch (e) { + return this.fail(e.message); + } + } + + // ==================== 任务辅助方法 ==================== + + /** + * 生成运单导出任务ID。 + * @return {string} 任务ID。 + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `waybill_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 生成运单揽收状态更新任务ID。 + * @return {string} 任务ID。 + */ + generateReceiveTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `waybill_receive_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 规范化运单号:转字符串、去空格、去空、去重。 + * @param {Array} waybillCodes 原始运单号列表。 + * @return {Array} 规范化后的运单号列表。 + */ + normalizeReceiveWaybillCodes(waybillCodes) { + if (!Array.isArray(waybillCodes)) return []; + return [ ...new Set(waybillCodes.map(code => String(code || '').trim()).filter(Boolean)) ]; + } + + /** + * 解析仓库承接 waybill.getreceive 的 API 应用 AppKey(按 id 升序取首个)。 + * 返回空字符串表示仓库未配置该外部访问接口。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 目标应用 AppKey。 + */ + async resolveReceiveAppKey(warehouseId) { + const warehouseNotify = this.service.systems && this.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.listCallbackConfigs !== 'function') { + return ''; + } + + const candidates = await warehouseNotify.listCallbackConfigs( + Number(warehouseId) || 0, + WAYBILL_RECEIVE_EVENT + ); + const first = Array.isArray(candidates) ? candidates[0] : null; + return String(first && first.appKey || '').trim(); + } + + /** + * 解析仓库承接 waybill.getTrace 的 API 应用 AppKey(按 id 升序取首个)。 + * 返回空字符串表示仓库未配置轨迹查询外部接口。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 目标应用 AppKey。 + */ + async resolveTraceAppKey(warehouseId) { + const warehouseNotify = this.service.systems && this.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.listCallbackConfigs !== 'function') { + return ''; + } + + const candidates = await warehouseNotify.listCallbackConfigs( + Number(warehouseId) || 0, + WAYBILL_TRACE_EVENT + ); + const first = Array.isArray(candidates) ? candidates[0] : null; + return String(first && first.appKey || '').trim(); + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体。 + * @return {string} 规范后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取运单任务缓存键。 + * @param {string} taskId 任务ID。 + * @param {string} [prefix] 缓存键前缀,区分导出/揽收状态更新等任务类型。 + * @return {string} 缓存键。 + */ + getTaskCacheKey(taskId = '', prefix = WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX) { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${prefix}${normalizedTaskId}`; + } + + /** + * 写入运单任务进度缓存。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态。 + * @param {string} [prefix] 缓存键前缀。 + * @return {Promise} 无返回值。 + */ + async setTaskProgress(taskId = '', payload = {}, prefix = WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX) { + const cacheKey = this.getTaskCacheKey(taskId, prefix); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) + : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + }; + + await this.app.setCacheAsync(cacheKey, progressPayload); + } + + /** + * 读取运单任务进度缓存。 + * @param {string} taskId 任务ID。 + * @param {string} [prefix] 缓存键前缀。 + * @return {Promise} 任务状态对象或 null。 + */ + async getTaskProgress(taskId = '', prefix = WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX) { + const cacheKey = this.getTaskCacheKey(taskId, prefix); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + return await this.app.getCacheAsync(cacheKey); + } + + /** + * 写入运单导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + await this.setTaskProgress(taskId, payload, WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX); + } + + /** + * 读取运单导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务状态对象或 null。 + */ + async getExportTaskProgress(taskId = '') { + return await this.getTaskProgress(taskId, WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX); + } + + /** + * 写入运单揽收状态更新任务进度缓存。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态。 + * @return {Promise} 无返回值。 + */ + async setReceiveTaskProgress(taskId = '', payload = {}) { + await this.setTaskProgress(taskId, payload, WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX); + } + + /** + * 读取运单揽收状态更新任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务状态对象或 null。 + */ + async getReceiveTaskProgress(taskId = '') { + return await this.getTaskProgress(taskId, WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX); + } + + /** + * 查询单个运单的全部物流轨迹(仓库侧)。 + * + * 全部回源:实时调用外部访问接口 `waybill.getTrace` 查询,不做本地存储。 + * 一次返回该运单号下的所有轨迹(不分页),按操作时间倒序排列(最新的在前)。 + * 命中轨迹(非空)时顺带把该运单 `is_galaxy_receive` 置为 Y(只升不降)。 + * + * @param {Object} data 请求参数。 + * @param {string} [data.waybillCode] 运单号(兼容 waybill_code)。 + * @return {Promise} { waybill_code, total, list, received_updated }。 + */ + async getTrace(data = {}) { + try { + const safeData = this.isPlainObject(data) ? data : {}; + const waybillCode = String(safeData.waybillCode || safeData.waybill_code || '').trim(); + if (!waybillCode) { + return this.fail('运单号不能为空'); + } + + const warehouseId = Number(this.ctx?.user?.store_id || 0); + if (!warehouseId) { + return this.fail('无法获取当前仓库ID'); + } + + const appKey = await this.resolveTraceAppKey(warehouseId); + if (!appKey) { + return this.fail(WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE); + } + + const fetched = await this.service.systems.waybill.fetchTracesByWaybill({ + warehouseId, + waybillCode, + appKey, + }); + + if (!fetched.success) { + const reason = fetched.reason || fetched.error || '运单轨迹查询失败'; + return this.fail(`运单轨迹查询失败: ${reason}`); + } + + // 有轨迹即视为已揽收(只升不降);失败不阻断查询 + let receivedUpdated = 0; + if (!fetched.empty) { + receivedUpdated = await this.service.systems.waybill.markReceiveByTraces({ + warehouseId, + waybillCodes: [ waybillCode ], + }); + } + + return this.success('获取成功', { + waybill_code: waybillCode, + total: fetched.traces.length, + list: fetched.traces, + received_updated: receivedUpdated, + }); + } catch (e) { + return this.fail(e.message); + } + } +} + +module.exports = WaybillWarehouseService; diff --git a/app/service/systemMethods/wechat.js b/app/service/systemMethods/wechat.js new file mode 100644 index 0000000..8dd9e08 --- /dev/null +++ b/app/service/systemMethods/wechat.js @@ -0,0 +1,415 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 微信开放平台 method 层(system.json module: wechat)。 + */ +class WechatService extends MainService { + constructor(ctx) { + super(ctx); + // getAuthUrl:需登录、免权限、不记系统日志;loginByCode/getUserAgreementText:免登录、免权限、免鉴权; + // pushLoginCode/queryauth/wxaauth/registerMiniprogram/getTemplateList/commit/getTrialQRCode/submitAudit/userList/getUserAgreement/setUserAgreement/getAgreementVersion:需登录、免权限(PC 已登录用户操作); + // bindUser/updateInfo/uploadHeadimg/getMyLoginCode:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问 + // _noNeedLog:除 loginByCode 外其余方法不记系统日志(loginByCode 保留日志,便于排查登录请求的入参出参) + this.systemInit('loginByCode,getUserAgreementText', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', 'getAuthUrl,getUserAgreementText,getMyLoginCode,bindUser,bindByEmployee,pushLoginCode,queryauth,wxaauth,registerMiniprogram,updateInfo,uploadHeadimg,getTemplateList,getAuthorizerInfo,commit,submitAudit,getTrialQRCode,userList,getUserAgreement,setUserAgreement,getAgreementVersion', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', 'bindUser,updateInfo,uploadHeadimg,getMyLoginCode'); + } + + /** + * 获取当前微信登录用户的登录码(至少微信登录):无则生成写入,有则直接返回。 + * + * @return {Promise} 统一响应结果。 + */ + async getMyLoginCode() { + try { + const result = await this.service.systems.wechat.getMyLoginCode(); + if (result && result.success === true) { + return this.success(result.message || '获取成功', result.data); + } + return this.fail((result && result.message) || '获取失败'); + } catch (e) { + return this.fail('获取登录码失败:' + e.message); + } + } + + async getAuthUrl(data) { + try { + const result = await this.service.systems.wechat.getAuthUrl(data || {}); + return this.success('获取成功', result); + } catch (e) { + return this.fail(e.message); + } + } + + /** + * 小程序登录码登录(免登录):入参 code + app_id,返回 token + user(参考 auth.login)。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一响应结果。 + */ + async loginByCode(data) { + try { + const result = await this.service.systems.wechat.loginByCode(data || {}); + if (result.code) { + return this.success('登录成功', result); + } + return this.fail('登录失败:' + result.message, result); + } catch (e) { + return this.fail('登录失败:' + e.message); + } + } + + /** + * 绑定用户(微信登录态中间层):用户名密码一致则绑定并签发新 token。 + * + * @param {Object} data 请求参数(username/password)。 + * @return {Promise} 统一响应结果。 + */ + async bindUser(data) { + try { + const result = await this.service.systems.wechat.bindUser(data || {}); + if (result.code) { + return this.success('绑定成功', result); + } + return this.fail('绑定失败:' + result.message, result); + } catch (e) { + return this.fail('绑定失败:' + e.message); + } + } + + /** + * 按工号绑定微信(需登录需权限,PC 管理员操作):传工号 id 与微信绑定记录 id, + * 查工号的账号 id 写入 wms_user_oauth.user_id。 + * + * @param {Object} data 请求参数(id 工号id、oauth_id 微信绑定记录id)。 + * @return {Promise} 统一响应结果。 + */ + async bindByEmployee(data) { + try { + const result = await this.service.systems.wechat.bindByEmployee(data || {}); + if (result.code) { + return this.success(result.message || '绑定成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('绑定失败:' + e.message); + } + } + + /** + * 获取小程序用户须知富文本(免登录):传入 appId,24h 缓存。 + * + * @param {Object} data 请求参数(appId)。 + * @return {Promise} 统一响应结果。 + */ + async getUserAgreementText(data) { + try { + const result = await this.service.systems.wechat.getUserAgreementText(data || {}); + if (result.code) { + return this.success(result.message || '获取成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('获取用户须知失败:' + e.message); + } + } + + /** + * 获取当前仓库小程序用户须知(需登录)。 + * + * @param {Object} data 请求参数(无)。 + * @return {Promise} 统一响应结果。 + */ + async getUserAgreement(data) { + try { + const result = await this.service.systems.wechat.getUserAgreement(data || {}); + if (result.code) { + return this.success(result.message || '获取成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('获取用户须知失败:' + e.message); + } + } + + /** + * 设置当前仓库小程序用户须知(需登录)。 + * + * @param {Object} data 请求参数(text 富文本)。 + * @return {Promise} 统一响应结果。 + */ + async setUserAgreement(data) { + try { + const result = await this.service.systems.wechat.setUserAgreement(data || {}); + if (result.code) { + return this.success(result.message || '设置成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('设置用户须知失败:' + e.message); + } + } + + /** + * 获取指定协议版本内容(需登录免权限):传版本记录 id,校验仓库后返回协议内容。 + * + * @param {Object} data 请求参数(id 协议版本记录id)。 + * @return {Promise} 统一响应结果。 + */ + async getAgreementVersion(data) { + try { + const result = await this.service.systems.wechat.getAgreementVersion(data || {}); + if (result.code) { + return this.success(result.message || '获取成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('获取协议版本失败:' + e.message); + } + } + + /** + * 确认登录码(需登录,PC 已登录用户确认小程序登录)。 + * + * @param {Object} data 请求参数(code)。 + * @return {Promise} 统一响应结果。 + */ + async pushLoginCode(data) { + try { + const result = await this.service.systems.wechat.pushLoginCode(data || {}); + if (result.code) { + return this.success(result.message || '操作成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('确认登录失败:' + e.message); + } + } + + /** + * 查询当前仓库小程序认证状态(需登录)。 + * + * @param {Object} data 请求参数(taskid)。 + * @return {Promise} 统一响应结果。 + */ + async queryauth(data) { + try { + const result = await this.service.systems.wechat.queryauth(data || {}); + if (result.code) { + return this.success(result.message || '查询成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('查询认证状态失败:' + e.message); + } + } + + /** + * 发起小程序认证(需登录):后端分步——图片字段传 COS 文件 URL,后端下载 → + * wxa/sec/uploadauthmaterial 换 mediaid → { auth_data } 包裹提交 wxa/sec/wxaauth。 + * + * @param {Object} data 请求参数(新版 auth_data 字段白名单透传,详见 methods/system.json)。 + * @return {Promise} 统一响应结果。 + */ + async wxaauth(data) { + try { + const result = await this.service.systems.wechat.wxaauth(data || {}); + if (result.code) { + return this.success(result.message || '认证已发起', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('发起认证失败:' + e.message); + } + } + + /** + * 获取并同步当前仓库小程序基础信息(需登录)。 + * + * 调微信 api_get_authorizer_info 拉取授权账号详情(authorizer_info + authorization_info), + * 将基础信息/认证类型/权限集等落库 wms_wechat_app 后返回完整数据。 + * + * @param {Object} data 请求参数(无)。 + * @return {Promise} 统一响应结果。 + */ + async getAuthorizerInfo(data) { + try { + const result = await this.service.systems.wechat.getAuthorizerInfo(data || {}); + if (result.code) { + return this.success(result.message || '获取成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('获取小程序基础信息失败:' + e.message); + } + } + + /** + * 快速注册企业小程序(需登录)。 + * + * @param {Object} data 请求参数(name/code/code_type/legal_persona_wechat/legal_persona_name/component_phone)。 + * @return {Promise} 统一响应结果。 + */ + async registerMiniprogram(data) { + try { + const result = await this.service.systems.wechat.registerMiniprogram(data || {}); + if (result.code) { + return this.success(result.message || '操作成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('注册小程序失败:' + e.message); + } + } + + /** + * 更新微信账号资料(微信登录态中间层,仅未绑定用户)。 + * + * @param {Object} data 请求参数(nickname/headimgurl)。 + * @return {Promise} 统一响应结果。 + */ + async updateInfo(data) { + try { + const result = await this.service.systems.wechat.updateInfo(data || {}); + if (result.code) { + return this.success(result.message || '更新成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('更新失败:' + e.message); + } + } + + /** + * 上传微信账号头像(微信登录态中间层,至少微信登录即可)。 + * + * @param {Object} data 请求参数(image: 裁剪后的 PNG base64)。 + * @return {Promise} 统一响应结果。 + */ + async uploadHeadimg(data) { + try { + const result = await this.service.systems.wechat.uploadHeadimg(data || {}); + if (result.code) { + return this.success(result.message || '上传成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('上传头像失败:' + e.message); + } + } + + /** + * 获取小程序模板库列表(需登录,实时拉取,不缓存)。 + * + * @return {Promise} 统一响应结果。 + */ + async getTemplateList() { + try { + const result = await this.service.systems.wechat.getTemplateList(); + if (result.code) { + return this.success(result.message || '获取成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('获取模板列表失败:' + e.message); + } + } + + /** + * 上传代码并生成体验版(需登录)。 + * + * @param {Object} data 请求参数(template_id/ext_json/user_version/user_desc)。 + * @return {Promise} 统一响应结果。 + */ + async commit(data) { + try { + const result = await this.service.systems.wechat.commit(data || {}); + if (result.code) { + return this.success(result.message || '上传成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('上传代码失败:' + e.message); + } + } + + /** + * 获取体验版二维码(需登录)。 + * + * @param {Object} data 请求参数(可选 path)。 + * @return {Promise} 统一响应结果。 + */ + async getTrialQRCode(data) { + try { + const result = await this.service.systems.wechat.getTrialQRCode(data || {}); + if (result.code) { + return this.success(result.message || '获取成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('获取体验版二维码失败:' + e.message); + } + } + + /** + * 提交代码审核(需登录)。 + * + * @param {Object} data 请求参数(item_list/version_desc 等,均为可选)。 + * @return {Promise} 统一响应结果。 + */ + async submitAudit(data) { + try { + const result = await this.service.systems.wechat.submitAudit(data || {}); + if (result.code) { + return this.success(result.message || '提交成功', result); + } + return this.fail(result.message, result); + } catch (e) { + return this.fail('提交代码审核失败:' + e.message); + } + } + + /** + * 拉取当前仓库小程序的用户列表(需登录,支持 where/pagination/sort)。 + * + * @param {Object} data 请求参数(可选 app_id/where/pagination/sort)。 + * @return {Promise} 统一响应结果。 + */ + async userList(data = {}) { + try { + // where 字段白名单:仅允许按用户表常规字段过滤,禁止探测敏感列 + const allowedWhereFields = new Set([ + 'id', + 'user_id', + 'app_id', + 'openid', + 'unionid', + 'nickname', + 'sex', + 'login_time', + 'login_count', + 'created_at', + 'updated_at', + ]); + const rawWhere = data.where && typeof data.where === 'object' ? data.where : {}; + const filteredWhere = {}; + for (const key of Object.keys(rawWhere)) { + if (allowedWhereFields.has(key)) { + filteredWhere[key] = rawWhere[key]; + } + } + data.where = filteredWhere; + + this.prepareWhereContext(data); + const result = await this.service.systems.wechat.userList(data); + if (result.code) { + return this.success(result.message || '获取成功', result.data); + } + return this.fail(result.message); + } catch (e) { + return this.fail('获取用户列表失败:' + e.message); + } + } +} + +module.exports = WechatService; diff --git a/app/service/systemMethods/workbench.js b/app/service/systemMethods/workbench.js new file mode 100644 index 0000000..b147156 --- /dev/null +++ b/app/service/systemMethods/workbench.js @@ -0,0 +1,366 @@ +'use strict'; + +const MainService = require('../main'); + +class WorkbenchService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = 'business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder,getWorkbenchCount'; + const _noNeedRight = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder,getWorkbenchCount'; + const _noNeedLog = 'list,detail,getWorkbenchInfo,removeMember,bindMember'; + const _noNeedAuth = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder,getWorkbenchCount'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 工作台列表(分页 + 筛选) + * @param data + */ + async list(data) { + const { service } = this; + try { + const result = await service.systems.workbench.list(data || {}); + return this.success('获取成功', result); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 工作台详情 + * @param data + */ + async detail(data) { + const { service } = this; + try { + const { id } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const record = await service.systems.workbench.detail(parseInt(id)); + return this.success('获取成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 创建工作台 + * @param data + */ + async create(data) { + const { service } = this; + try { + const record = await service.systems.workbench.create(data); + return this.success('创建成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 更新工作台 + * @param data + */ + async update(data) { + const { service } = this; + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const record = await service.systems.workbench.update(parseInt(id), fields); + return this.success('更新成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 删除工作台(软删除) + * @param data + */ + async delete(data) { + const { service } = this; + try { + const { id } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + await service.systems.workbench.delete(parseInt(id)); + return this.success('删除成功'); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 工作台业务入口(免登录、免鉴权) + * @param {Object} data - { name, data } + */ + async business(data) { + const { ctx, service } = this; + const { name, data: bizData } = data || {}; + ctx.logger.info('[Workbench.business] 收到业务请求 name=%s data=%j', name, bizData); + try { + const result = await service.systems.workbench.business(name, bizData); + return this.success('ok', result); + } catch (error) { + ctx.logger.error('[Workbench.business] 业务处理失败 name=%s error=%s', name, error.message); + return this.fail(error.message); + } + } + + /** + * 工作台绑定摄像头 + * @param data + */ + async bindCamera(data) { + const { service } = this; + try { + const { id, camera_ids } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const record = await service.systems.workbench.bindCamera(parseInt(id), camera_ids); + return this.success('绑定成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 工作台绑定:校验缓存绑定码与工作台ID,写入随机 token(需登录、需权限) + * @param data - { code, id } + */ + async bind(data) { + const { service } = this; + try { + const result = await service.systems.workbench.bindWorkbench(data || {}); + if (result && result.success) { + return this.success('绑定成功', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '绑定失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 使用 token 获取工作台信息(免登录、免鉴权)。 + * 返回主表信息、成员列表 members,以及当前正在打包的波次(current_wave)与订单列表(current_orders)。 + * @param {Object} data - { token } + */ + async getWorkbenchInfo(data) { + const { service } = this; + try { + const { token } = data || {}; + const result = await service.systems.workbench.getWorkbenchInfoByToken({ token }); + if (result && result.success) { + return this.success('获取成功', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '获取工作台信息失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 重置工作台登录码(需登录、需权限) + * @param data - { id } + */ + async resetLoginCode(data) { + const { service } = this; + try { + const { id } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const result = await service.systems.workbench.resetLoginCode(parseInt(id)); + return this.success('重置成功', result); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 移除工作台成员(免登录、免鉴权,以工作台 token 鉴权) + * @param data - { ids, token } + */ + async removeMember(data) { + const { service } = this; + try { + const result = await service.systems.workbench.removeWorkbenchMember(data || {}); + if (result && result.success) { + return this.success('移除成功', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '移除成员失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 绑定工作台成员(免登录、免鉴权,以工作台 token 鉴权) + * @param data - { userId | user_id, userName | user_name | name, token } + */ + async bindMember(data) { + const { service } = this; + try { + const result = await service.systems.workbench.bindWorkbenchMember(data || {}); + if (result && result.success) { + return this.success('绑定成功', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '绑定成员失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } + /** + * 工作台打包上报(免登录、免鉴权,以工作台 token 鉴权,仓库与工作台由服务端注入) + * 推荐只传 token + key(key 来自 workbench.queryOrder 响应,20 分钟有效, + * 订单参数由后端从缓存拉取防篡改);不传 key 时旧参数模式过渡兼容。 + * @param {Object} data - { + * token, key, + * delivery_order_code, wave_no, status, pack_time, + * wave_total_orders, items_count, items_total, users + * } + */ + async packOrder(data) { + const { service } = this; + try { + const { + token, + key, + delivery_order_code: deliveryOrderCode, + wave_no: waveNo, + status, + pack_time: packTime, + wave_total_orders: waveTotalOrders, + items_count: itemsCount, + items_total: itemsTotal, + users, + } = data || {}; + const result = await service.systems.workbench.packOrderByToken({ + token, + key, + delivery_order_code: deliveryOrderCode, + wave_no: waveNo, + status, + pack_time: packTime, + wave_total_orders: waveTotalOrders, + items_count: itemsCount, + items_total: itemsTotal, + users, + }); + if (result && result.success) { + return this.success('ok', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '打包上报失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 工作台打包完成(免登录、免鉴权,以工作台 token 鉴权,仓库与工作台由服务端注入) + * @param {Object} data - { token } + */ + async finishPack(data) { + const { service } = this; + try { + const { token } = data || {}; + const result = await service.systems.workbench.finishPackByToken({ token }); + if (result && result.success) { + return this.success('ok', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '打包完成失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 工作台称重上报(免登录、免鉴权,以工作台 token 鉴权,仓库由服务端注入) + * @param {Object} data - { token, barcode, weight } + */ + async sendWeight(data) { + const { service } = this; + try { + const { token, barcode, weight } = data || {}; + const result = await service.systems.workbench.sendWeightByToken({ token, barcode, weight }); + if (result && result.success) { + return this.success('ok', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '称重上报失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 条码查询订单(免登录、免鉴权,以工作台 token 鉴权,仓库由服务端注入) + * body 传入的 warehouse_id/workbench_id 一律忽略,仅以 token 解析出的工作台仓库为准。 + * @param {Object} data - { token, barcode } + */ + async queryOrder(data) { + const { service } = this; + try { + const { token, barcode } = data || {}; + const result = await service.systems.workbench.queryOrderByToken({ token, barcode }); + if (result && result.success) { + return this.success('ok', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '查询订单失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 当前工作台班次打包统计(免登录、免鉴权,以工作台 token 鉴权,仓库与工作台由服务端注入)。 + * 统计窗口:本地时间当日 08:00 至次日 08:00,早于 08:00 时为昨日 08:00 至今日 08:00。 + * @param {Object} data - { token } + */ + async getWorkbenchCount(data) { + const { service } = this; + try { + const { token } = data || {}; + const result = await service.systems.workbench.getWorkbenchCountByToken({ token }); + if (result && result.success) { + return this.success('ok', result); + } + const statusCode = result && result.statusCode; + return this.fail( + result && result.message ? result.message : '获取工作台统计失败', + statusCode ? { code: statusCode } : undefined + ); + } catch (error) { + return this.fail(error.message); + } + } +} + +module.exports = WorkbenchService; diff --git a/app/service/systems/account_platform.js b/app/service/systems/account_platform.js index 7f1af72..fb0fd34 100644 --- a/app/service/systems/account_platform.js +++ b/app/service/systems/account_platform.js @@ -3,22 +3,85 @@ const Service = require('egg').Service; class AccountPlatformService extends Service { + getActiveInclude(ctx) { + return [ + { + model: ctx.model.AccountStoreEmployee, + as: 'accountStoreEmployee', + where: { status: 1 }, + required: true, + include: [ + { + model: ctx.model.EmployeeRole, + as: 'employeeRoles', + required: false, + attributes: [ 'id', 'employee_id', 'role_id' ], + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [ 'id', 'name', 'code', 'permissions', 'description' ], + }, + ], + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'name', 'code' ], + }, + ], + }, + ]; + } + + getPrimaryRoleBinding(accountStoreEmployee) { + const bindings = Array.isArray(accountStoreEmployee?.employeeRoles) + ? accountStoreEmployee.employeeRoles + : []; + return bindings.length > 0 ? bindings[0] : null; + } + + formatActiveContext(platformActive) { + if (!platformActive || !platformActive.accountStoreEmployee) { + return null; + } + + const employee = platformActive.accountStoreEmployee; + const roleBinding = this.getPrimaryRoleBinding(employee); + const role = roleBinding?.role || null; + const store = employee.store || null; + + return { + account_id: platformActive.account_id, + platform_code: platformActive.platform_code, + role_id: roleBinding ? roleBinding.role_id : null, + role_name: role ? role.name : '', + role_code: role ? role.code : '', + role_permissions: role ? this.ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions) : [], + store_id: employee.store_id, + store_name: store ? store.name : '', + store_code: store ? store.code : '', + created_at: platformActive.created_at, + updated_at: platformActive.updated_at, + }; + } + /** * 切换平台激活角色 * @param {number} accountId - 账号ID - * @param {number} accountStoreRoleId - 账号仓库角色关联ID + * @param {number} accountStoreRoleId - 账号仓库员工关联ID(保持历史参数名兼容) * @param {string} platformCode - 平台编码 - * @return {Promise} + * @return {Promise} 切换结果 */ async switchActiveRole(accountId, accountStoreRoleId, platformCode) { - const { ctx, app } = this; + const { ctx } = this; // 使用事务确保数据一致性 const transaction = await ctx.model.transaction(); try { - // 1. 验证角色关联的有效性 - const accountStoreRole = await ctx.model.AccountStoreRole.findOne({ + // 1. 验证员工关联的有效性 + const accountStoreEmployee = await ctx.model.AccountStoreEmployee.findOne({ where: { id: accountStoreRoleId, account_id: accountId, @@ -27,18 +90,33 @@ class AccountPlatformService extends Service { transaction, }); - if (!accountStoreRole) { + if (!accountStoreEmployee) { throw new Error('角色关联不存在或已失效'); } + const existingActive = await ctx.model.AccountPlatformActive.findOne({ + where: { + account_id: accountId, + platform_code: platformCode, + }, + transaction, + }); + // 2. 使用 upsert 切换激活角色 - const [ platformActive, created ] = await ctx.model.AccountPlatformActive.upsert({ + await ctx.model.AccountPlatformActive.upsert({ account_id: accountId, - account_store_role_id: accountStoreRoleId, + employee_id: accountStoreRoleId, platform_code: platformCode, }, { transaction, - returning: true, + }); + + const platformActive = await ctx.model.AccountPlatformActive.findOne({ + where: { + account_id: accountId, + platform_code: platformCode, + }, + transaction, }); await transaction.commit(); @@ -48,7 +126,7 @@ class AccountPlatformService extends Service { return { success: true, - created, + created: !existingActive, data: platformActive, }; } catch (error) { @@ -56,7 +134,7 @@ class AccountPlatformService extends Service { // 处理唯一约束冲突 if (error.name === 'SequelizeUniqueConstraintError') { - // 如果是 account_store_role_id 和 platform_code 冲突,说明同一个平台不能关联到不同的账号 + // 如果是 employee_id 和 platform_code 冲突,说明同一个平台不能关联到不同账号 if (error.errors && error.errors.some(e => e.path === 'uk_account_store_role_platform')) { throw new Error('该角色已被其他账号在同一平台激活'); } @@ -72,7 +150,7 @@ class AccountPlatformService extends Service { * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 * @param {boolean} useCache - 是否使用缓存 - * @return {Promise} + * @return {Promise} 当前激活角色 */ async getActiveRoleByPlatform(accountId, platformCode, useCache = true) { const { ctx, app } = this; @@ -97,26 +175,7 @@ class AccountPlatformService extends Service { account_id: accountId, platform_code: platformCode, }, - include: [ - { - model: ctx.model.AccountStoreRole, - as: 'accountStoreRole', - where: { status: 1 }, - required: true, - include: [ - { - model: ctx.model.Role, - as: 'role', - attributes: [ 'id', 'name', 'code', 'permissions' ], - }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'name', 'code' ], - }, - ], - }, - ], + include: this.getActiveInclude(ctx), }); if (!platformActive) { @@ -124,19 +183,7 @@ class AccountPlatformService extends Service { } // 整理返回数据 - const result = { - account_id: accountId, - platform_code: platformCode, - role_id: platformActive.accountStoreRole.role_id, - role_name: platformActive.accountStoreRole.role.name, - role_code: platformActive.accountStoreRole.role.code, - role_permissions: platformActive.accountStoreRole.role.permissions, - store_id: platformActive.accountStoreRole.store_id, - store_name: platformActive.accountStoreRole.store.name, - store_code: platformActive.accountStoreRole.store.code, - created_at: platformActive.created_at, - updated_at: platformActive.updated_at, - }; + const result = this.formatActiveContext(platformActive); // 缓存结果 if (useCache) { @@ -154,7 +201,7 @@ class AccountPlatformService extends Service { * 批量获取账号在多个平台的激活状态 * @param {number} accountId - 账号ID * @param {Array} platformCodes - 平台编码数组 - * @return {Promise} + * @return {Promise} 激活状态映射 */ async getMultiplePlatformActiveRoles(accountId, platformCodes) { const { ctx } = this; @@ -164,40 +211,22 @@ class AccountPlatformService extends Service { account_id: accountId, platform_code: platformCodes, }, - include: [ - { - model: ctx.model.AccountStoreRole, - as: 'accountStoreRole', - where: { status: 1 }, - required: true, - include: [ - { - model: ctx.model.Role, - as: 'role', - attributes: [ 'id', 'name', 'code' ], - }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'name', 'code' ], - }, - ], - }, - ], + include: this.getActiveInclude(ctx), }); // 转换为平台编码为key的对象 const result = {}; platformActives.forEach(active => { + const context = this.formatActiveContext(active); result[active.platform_code] = { - role_id: active.accountStoreRole.role_id, - role_name: active.accountStoreRole.role.name, - role_code: active.accountStoreRole.role.code, - store_id: active.accountStoreRole.store_id, - store_name: active.accountStoreRole.store.name, - store_code: active.accountStoreRole.store.code, - created_at: active.created_at, - updated_at: active.updated_at, + role_id: context ? context.role_id : null, + role_name: context ? context.role_name : '', + role_code: context ? context.role_code : '', + store_id: context ? context.store_id : null, + store_name: context ? context.store_name : '', + store_code: context ? context.store_code : '', + created_at: context ? context.created_at : active.created_at, + updated_at: context ? context.updated_at : active.updated_at, }; }); @@ -214,57 +243,41 @@ class AccountPlatformService extends Service { /** * 获取账号所有平台的激活状态 * @param {number} accountId - 账号ID - * @return {Promise} + * @return {Promise} 平台激活列表 */ async getAllPlatformActives(accountId) { const { ctx } = this; const platformActives = await ctx.model.AccountPlatformActive.findAll({ where: { account_id: accountId }, - include: [ - { - model: ctx.model.AccountStoreRole, - as: 'accountStoreRole', - where: { status: 1 }, - required: true, - include: [ - { - model: ctx.model.Role, - as: 'role', - attributes: [ 'id', 'name', 'code' ], - }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'name', 'code' ], - }, - ], - }, - ], + include: this.getActiveInclude(ctx), order: [[ 'platform_code', 'ASC' ]], }); - return platformActives.map(active => ({ - platform_code: active.platform_code, - role_id: active.accountStoreRole.role_id, - role_name: active.accountStoreRole.role.name, - role_code: active.accountStoreRole.role.code, - store_id: active.accountStoreRole.store_id, - store_name: active.accountStoreRole.store.name, - store_code: active.accountStoreRole.store.code, - created_at: active.created_at, - updated_at: active.updated_at, - })); + return platformActives.map(active => { + const context = this.formatActiveContext(active); + return { + platform_code: active.platform_code, + role_id: context ? context.role_id : null, + role_name: context ? context.role_name : '', + role_code: context ? context.role_code : '', + store_id: context ? context.store_id : null, + store_name: context ? context.store_name : '', + store_code: context ? context.store_code : '', + created_at: active.created_at, + updated_at: active.updated_at, + }; + }); } /** * 清除平台激活状态 * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 - * @return {Promise} + * @return {Promise} 是否清除成功 */ async clearPlatformActive(accountId, platformCode) { - const { ctx, app } = this; + const { ctx } = this; try { const result = await ctx.model.AccountPlatformActive.destroy({ @@ -285,8 +298,8 @@ class AccountPlatformService extends Service { /** * 清理平台缓存 - * @param accountId - * @param platformCode + * @param {number} accountId 账号ID + * @param {string} platformCode 平台编码 * @private */ async clearPlatformCache(accountId, platformCode) { @@ -304,7 +317,7 @@ class AccountPlatformService extends Service { * 获取账号可用的角色列表 * @param {number} accountId - 账号ID * @param {number} storeId - 仓库ID(可选) - * @return {Promise} + * @return {Promise} 角色列表,包含角色信息和所属仓库信息 */ async getAvailableRoles(accountId, storeId = null) { const { ctx } = this; @@ -318,13 +331,21 @@ class AccountPlatformService extends Service { where.store_id = storeId; } - const accountStoreRoles = await ctx.model.AccountStoreRole.findAll({ + const accountStoreEmployees = await ctx.model.AccountStoreEmployee.findAll({ where, include: [ { - model: ctx.model.Role, - as: 'role', - attributes: [ 'id', 'name', 'code', 'description' ], + model: ctx.model.EmployeeRole, + as: 'employeeRoles', + required: false, + attributes: [ 'id', 'employee_id', 'role_id' ], + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [ 'id', 'name', 'code', 'description' ], + }, + ], }, { model: ctx.model.Store, @@ -334,30 +355,42 @@ class AccountPlatformService extends Service { ], order: [ [ 'store_id', 'ASC' ], - [ 'role_id', 'ASC' ], + [ 'id', 'ASC' ], ], }); - return accountStoreRoles.map(item => ({ - id: item.id, - account_id: item.account_id, - store_id: item.store_id, - store_name: item.store.name, - store_code: item.store.code, - role_id: item.role_id, - role_name: item.role.name, - role_code: item.role.code, - role_description: item.role.description, - real_name: item.real_name, - created_at: item.created_at, - })); + const rows = []; + for (const employee of accountStoreEmployees) { + const roleBindings = Array.isArray(employee.employeeRoles) + ? employee.employeeRoles + : []; + for (const binding of roleBindings) { + const role = binding.role; + if (!role) continue; + rows.push({ + id: employee.id, + account_id: employee.account_id, + store_id: employee.store_id, + store_name: employee.store ? employee.store.name : '', + store_code: employee.store ? employee.store.code : '', + role_id: binding.role_id, + role_name: role.name, + role_code: role.code, + role_description: role.description, + real_name: employee.real_name, + created_at: employee.created_at, + }); + } + } + + return rows; } /** * 根据平台获取账号的当前仓库和角色 * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 - * @return {Promise} + * @return {Promise} 当前上下文 */ async getCurrentContext(accountId, platformCode) { const activeRole = await this.getActiveRoleByPlatform(accountId, platformCode); diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js new file mode 100644 index 0000000..18cbfb3 --- /dev/null +++ b/app/service/systems/afterSale.js @@ -0,0 +1,2907 @@ +'use strict'; + +const fs = require('fs'); +const fsp = require('fs/promises'); +const os = require('os'); +const path = require('path'); +const crypto = require('crypto'); +const Service = require('egg').Service; + +/** + * 售后模块业务逻辑层。 + * 负责 wms_after_sale / wms_after_sale_detail 的 CRUD、附件绑定等核心操作。 + * 所有数据库交互集中在此层,供 systemMethods/afterSale.js 调用。 + */ +class AfterSaleService extends Service { + // =========================== + // 列表查询 + // =========================== + + /** + * 售后单列表查询,支持 where 条件、分页、排序。 + * + * @param {Object} where 标准化 where 条件对象 + * @param {Object} [where.after_sale_no] 售后单号条件 + * @param {Object} [where.type] 售后类型条件 + * @param {Object} [where.sub_type] 售后子类型条件 + * @param {Object} [where.status] 售后状态条件 + * @param {Object} [where.priority] 优先级条件 + * @param {Object} [where.role_group] 角色组条件 + * @param {Object} [where.waybill_no] 运单号条件 + * @param {Object} [where.claim_status] 仓库理赔状态条件 + * @param {Object} [where.carrier_claim_status] 运方理赔状态条件 + * @param {Object} [where.quickWhere] 快捷搜索条件 + * @param {Object} [where.warehouse_id] 仓库ID(由方法层注入) + * @param {Object} [pagination] 分页参数 + * @param {number} [pagination.page=1] 页码 + * @param {number} [pagination.pageSize=20] 每页数量 + * @param {Object} [sort] 排序参数 + * @param {string} [sort.sortField] 排序字段 + * @param {string} [sort.sortOrder] 排序顺序(asc/desc) + * @param {Object} [opts] 额外选项 + * @param {Array} [opts.order] 自定义 Sequelize order(优先于 sort) + * @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单 + * @param {boolean} [opts.enrichStoreName] 是否补充每行 store_name 货主名称(合约表货主备注 store_remask,无备注时回退货主公司全称) + * @return {Promise} { list: Array, pagination: Object } + */ + async list(where = {}, pagination = {}, sort = {}, opts = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + // 构建 Sequelize where 条件 + const queryWhere = this._buildListWhere(where, Op); + + // 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不显示 + if (opts.excludeFutureFollowup) { + const pendingFeedbackWhere = { + [Op.or]: [ + { status: { [Op.ne]: 'pending_feedback' } }, + { + status: 'pending_feedback', + [Op.or]: [ + { followup_at: null }, + { followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } }, + ], + }, + ], + }; + // 合并到现有 where 中(AND 关系) + if (queryWhere[Op.and]) { + queryWhere[Op.and].push(pendingFeedbackWhere); + } else { + queryWhere[Op.and] = [ pendingFeedbackWhere ]; + } + } + + // 排序:opts.order 优先于 sort + const order = Array.isArray(opts.order) && opts.order.length > 0 + ? opts.order + : this._buildListOrder(sort); + + const { count, rows } = await ctx.model.AfterSale.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + const totalPages = Math.ceil(count / pageSize); + + const list = rows.map(row => this._formatAfterSaleRow(row, app)); + + // 工作列表:批量补充货主名称(合约表 store_remask 货主备注,无备注时回退货主公司全称) + if (opts.enrichStoreName && list.length > 0) { + await this._enrichListStoreNames(list); + } + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages, + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 快速统计符合条件的售后单数量(用于角标显示,不做分页)。 + * 与 list() 共享相同的 where 构建逻辑,但只返回 count。 + * + * @param {Object} where 标准化 where 条件对象 + * @param {Object} [opts] 额外选项 + * @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单 + * @return {Promise} { count: number } + */ + async countPending(where = {}, opts = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const queryWhere = this._buildListWhere(where, Op); + + // 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不计数 + if (opts.excludeFutureFollowup) { + const pendingFeedbackWhere = { + [Op.or]: [ + { status: { [Op.ne]: 'pending_feedback' } }, + { + status: 'pending_feedback', + [Op.or]: [ + { followup_at: null }, + { followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } }, + ], + }, + ], + }; + if (queryWhere[Op.and]) { + queryWhere[Op.and].push(pendingFeedbackWhere); + } else { + queryWhere[Op.and] = [ pendingFeedbackWhere ]; + } + } + + const count = await ctx.model.AfterSale.count({ + where: queryWhere, + }); + + return { count }; + } + + /** + * 根据标准化 where 条件构建 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象 + * @param {Object} Op Sequelize Op 对象 + * @return {Object} Sequelize where 条件 + */ + _buildListWhere(where = {}, Op) { + const queryWhere = {}; + + // 软删除过滤 + queryWhere.deleted_at = null; + + // 直接映射字段 + const directFields = [ + 'type', 'sub_type', 'status', 'priority', 'role_group', + 'claim_status', 'carrier_claim_status', 'after_sale_no', + 'waybill_no', 'order_delivery_no', 'entry_order_no', + 'order_stockout_no', 'receiving_no', 'warehouse_id', + 'store_id', 'creator_id', + ]; + + for (const field of directFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 快捷搜索:在 after_sale_no / title / waybill_no 等字段中模糊搜索 + if (where.quickWhere !== undefined && where.quickWhere !== null) { + const quickValue = this._extractConditionValue(where.quickWhere); + if (quickValue !== undefined && quickValue !== null && String(quickValue).trim() !== '') { + const likePattern = { [Op.like]: `%${String(quickValue).trim()}%` }; + queryWhere[Op.or] = [ + { after_sale_no: likePattern }, + { title: likePattern }, + { waybill_no: likePattern }, + { order_delivery_no: likePattern }, + { entry_order_no: likePattern }, + { order_stockout_no: likePattern }, + { receiving_no: likePattern }, + ]; + } + } + + return queryWhere; + } + + /** + * 解析标准化条件值为 Sequelize 可用的条件对象。 + * + * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值) + * @param {Object} Op Sequelize Op 对象 + * @return {*} Sequelize 条件 + */ + _resolveConditionValue(condition, Op) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const operator = condition.operator; + const value = condition.value; + + if (!operator) { + return value; + } + + switch (operator) { + case 'eq': + return value; + case 'ne': + return { [Op.ne]: value }; + case 'in': + return { [Op.in]: Array.isArray(value) ? value : [ value ] }; + case 'notin': + return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; + case 'like': + return { [Op.like]: `%${value}%` }; + case 'gt': + return { [Op.gt]: value }; + case 'gte': + return { [Op.gte]: value }; + case 'lt': + return { [Op.lt]: value }; + case 'lte': + return { [Op.lte]: value }; + case 'between': + return { [Op.between]: Array.isArray(value) ? value : [ value ] }; + default: + return value; + } + } + + return condition; + } + + /** + * 从条件对象中提取原始 value。 + * + * @param {*} condition 标准化条件 + * @return {*} 原始值 + */ + _extractConditionValue(condition) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + if ('value' in condition) { + return condition.value; + } + } + return condition; + } + + /** + * 根据 sort 参数构建 Sequelize 排序数组。 + * + * @param {Object} sort 排序参数 + * @param {string} [sort.sortField] 排序字段 + * @param {string} [sort.sort_order] 排序顺序 + * @param {string} [sort.sortOrder] 排序顺序(驼峰) + * @return {Array>} Sequelize order 数组 + */ + _buildListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field || 'updated_at'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + // 允许排序的字段白名单 + const allowedSortFields = new Set([ + 'id', 'after_sale_no', 'type', 'sub_type', 'status', 'priority', + 'role_group', 'created_at', 'updated_at', 'resolved_at', + 'claim_status', 'carrier_claim_status', + ]); + + const safeSortField = allowedSortFields.has(sortField) ? sortField : 'created_at'; + + return [[ safeSortField, sortOrder ]]; + } + // =========================== + // 明细查询 + // =========================== + + /** + * 售后单明细查询,包含主表信息、步骤列表及附件。 + * 售后主表 description(详细描述)非空时,默认作为第一条 step 输出 + * (虚拟步骤:id=null、is_virtual=true、action=售后描述、remark=description,不落库)。 + * 若关联了订单(order_delivery_id),自动补充收件人/发件人/订单明细/打包视频。 + * 若关联了货主(store_id),自动补充货主合约备注。 + * + * @param {number} id 售后单主键ID + * @return {Promise} 售后单明细,包含主表、步骤列表(含附件)、关联单据详情 + * @throws {Error} 售后单不存在时抛出 + */ + async getDetail(id) { + const { ctx, app } = this; + + // 查询主表 + const afterSale = await ctx.model.AfterSale.findOne({ + where: { id, deleted_at: null }, + raw: true, + }); + + if (!afterSale) { + throw new Error('售后单不存在'); + } + + // 查询步骤列表(按创建时间升序) + const steps = await ctx.model.AfterSaleDetail.findAll({ + where: { after_sale_id: id, deleted_at: null }, + order: [[ 'created_at', 'ASC' ]], + raw: true, + }); + + // 查询步骤附件 + const stepsWithAttachments = await this._enrichStepsWithAttachments(steps); + + // 格式化时间字段 + const formatRow = row => this._formatAfterSaleRow(row, app); + + // 补充关联单据详情 + const related = await this._enrichAfterSaleDetail(afterSale); + + // 默认详细描述作为第一条 step 输出(虚拟步骤,不落库) + let finalSteps = stepsWithAttachments; + if (afterSale.description && String(afterSale.description).trim()) { + finalSteps = [{ + id: null, + after_sale_id: afterSale.id, + step_status: 'pending', + operator_id: null, + operator_snapshot: null, + action: '售后描述', + remark: afterSale.description, + started_at: null, + completed_at: null, + created_at: afterSale.created_at, + attachments: [], + is_virtual: true, + }, ...stepsWithAttachments ]; + } + + // 开始处理时间:取首条真实步骤记录的创建时间(不含默认描述虚拟步骤) + const firstStep = steps[0]; + const startedAt = firstStep ? (firstStep.created_at ? app.formatDate(firstStep.created_at) : null) : null; + + return { + after_sale: { ...formatRow(afterSale), started_at: startedAt }, + steps: finalSteps.map(formatRow), + related, + }; + } + + /** + * 根据售后单关联的业务单据ID,补充关联详情。 + * 包括:订单信息(收件人/发件人/明细/打包视频)、货主合约备注。 + * + * @param {Object} afterSale 售后主表记录 + * @return {Promise} 关联详情对象 + */ + async _enrichAfterSaleDetail(afterSale) { + const { ctx } = this; + const related = {}; + + // ======= 1. 关联订单详情 ======= + // 统一使用 order_id + const resolvedOrderId = afterSale.order_id; + if (resolvedOrderId) { + try { + related.order = await this._resolveOrderDetail( + resolvedOrderId, + afterSale.warehouse_id + ); + } catch (err) { + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析订单详情失败 id=${resolvedOrderId}: ${err.message}`); + } + } + + // ======= 2. 关联运单详情(快递公司 + 接口) ======= + if (afterSale.waybill_id) { + try { + related.waybill = await this._resolveWaybillDetail(afterSale.waybill_id); + } catch (err) { + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析运单详情失败 id=${afterSale.waybill_id}: ${err.message}`); + } + } + + // ======= 3. 货主合约备注 ======= + if (afterSale.store_id && afterSale.warehouse_id) { + try { + related.store_contract = await this._resolveStoreContractNote( + afterSale.store_id, + afterSale.warehouse_id + ); + } catch (err) { + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析货主合约备注失败 store_id=${afterSale.store_id}: ${err.message}`); + } + } + + return related; + } + + /** + * 解析关联订单的详细信息:收件人、发件人、订单明细、打包视频。 + * + * @param {number} orderDeliveryId 发货订单ID + * @param {number} warehouseId 仓库ID + * @return {Promise} 订单详情,查询失败返回 null + */ + async _resolveOrderDetail(orderDeliveryId, warehouseId) { + const { ctx, app } = this; + + try { + // 1. 查询订单主记录:优先按订单 id 序列表(wms_order_id_location_{warehouseId}) + // 定位订单所在车道直接查对应分表,未命中再按 current → history → dispatch → outsourced + // 遍历回退,最后回退基表(存量订单) + let order = null; + let preferredLane = null; + const factory = ctx.model.OrderDeliveryFactory; + + if (factory && typeof factory.getCurrentModel === 'function') { + const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ]; + const laneGetters = { + current: () => factory.getCurrentModel(warehouseId), + history: () => factory.getHistoryModel(warehouseId), + dispatch: () => factory.getDispatchModel(warehouseId), + outsourced: () => factory.getOutsourcedModel(warehouseId), + }; + + // 序列表定位优先:命中车道先查对应分表 + try { + if (typeof factory.getOrderLocation === 'function') { + const location = await factory.getOrderLocation(orderDeliveryId, warehouseId); + if (location && laneGetters[location]) { + preferredLane = String(location); + } + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 序列表定位失败: ${err.message}`); + } + + const orderedLanes = preferredLane + ? [ preferredLane, ...laneLabels.filter(label => label !== preferredLane) ] + : laneLabels; + + for (const lane of orderedLanes) { + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderDeliveryId }, + raw: true, + }); + if (row) { + order = row; + break; + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 分表 ${lane} 查询失败: ${err.message}`); + } + } + } + + // 分表均未命中:回退基表(存量订单) + if (!order) { + try { + order = await ctx.model.OrderDelivery.findOne({ + where: { id: orderDeliveryId }, + attributes: [ + 'id', 'name', 'tel', 'mobile', 'email', 'zip_code', 'country_code', + 'province', 'city', 'area', 'town', 'detail_address', 'store_id', 'items', + ], + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 主表查询失败: ${err.message}`); + } + } + + if (!order) { + ctx.logger.info(`[_resolveOrderDetail] 未找到订单 id=${orderDeliveryId} warehouseId=${warehouseId}`); + return null; + } + + ctx.logger.info(`[_resolveOrderDetail] 找到订单 id=${orderDeliveryId} code=${order.delivery_order_code} status=${order.status}`); + + // 2. 构建收件人信息 + const recipient = { + name: order.name || '', + tel: order.tel || '', + mobile: order.mobile || '', + email: order.email || '', + zip_code: order.zip_code || '', + country: order.country_code || '', + province: order.province || '', + city: order.city || '', + district: order.district || '', + town: order.town || '', + address: order.detail_address || '', + }; + + // 3. 构建发件人信息(从货主 subject_config 中取) + let sender = null; + if (order.store_id) { + try { + const store = await ctx.model.Store.findOne({ + where: { id: order.store_id }, + attributes: [ 'id', 'subject_config', 'company_name' ], + raw: true, + }); + if (store) { + let subjectConfig = store.subject_config; + if (typeof subjectConfig === 'string') { + try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; } + } + sender = { + name: (subjectConfig && subjectConfig.sender_name) || store.company_name || '', + tel: (subjectConfig && subjectConfig.sender_tel) || '', + province: (subjectConfig && subjectConfig.province_name) || '', + city: (subjectConfig && subjectConfig.city_name) || '', + district: (subjectConfig && subjectConfig.district_name) || '', + town: (subjectConfig && subjectConfig.town_name) || '', + address: (subjectConfig && subjectConfig.address) || '', + }; + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 查询发件人信息失败: ${err.message}`); + } + } + + // 4. 订单明细(优先 order.items JSON,为空时回退到分表查询) + let orderItems = []; + if (order.items) { + try { + const parsed = typeof order.items === 'string' ? JSON.parse(order.items) : order.items; + orderItems = Array.isArray(parsed) ? parsed : []; + } catch { + // items 解析失败,忽略 + } + } + + // 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询(序列表定位车道优先) + if (orderItems.length === 0 && ctx.model.OrderItemsFactory) { + try { + const itemsFactory = ctx.model.OrderItemsFactory; + const itemsLaneLabels = [ 'current', 'history', 'dispatch' ]; + const itemsLaneGetters = { + current: () => itemsFactory.getCurrentModel(warehouseId), + history: () => itemsFactory.getHistoryModel(warehouseId), + dispatch: () => itemsFactory.getDispatchModel(warehouseId), + }; + const orderedItemsLanes = preferredLane && itemsLaneGetters[preferredLane] + ? [ preferredLane, ...itemsLaneLabels.filter(label => label !== preferredLane) ] + : itemsLaneLabels; + + let dbItems = []; + for (const lane of orderedItemsLanes) { + try { + const itemsModel = await itemsLaneGetters[lane](); + if (!itemsModel || typeof itemsModel.findAll !== 'function') continue; + const laneRows = await itemsModel.findAll({ + where: { order_id: orderDeliveryId }, + raw: true, + }); + if (laneRows && laneRows.length > 0) { + dbItems = laneRows; + break; + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 商品明细分表 ${lane} 查询失败: ${err.message}`); + } + } + + if (dbItems.length > 0) { + // 收集 stock_id 用于批量查库存详情 + const stockIds = dbItems + .map(item => Number(item.stock_id)) + .filter(id => Number.isInteger(id) && id > 0); + + // 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性) + const stockDetailsMap = new Map(); + if (stockIds.length > 0) { + try { + const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId, + cacheTTL: 300, + }); + for (const detail of details) { + stockDetailsMap.set(detail.id, detail); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`); + } + } + + orderItems = dbItems.map(item => { + const stock = stockDetailsMap.get(Number(item.stock_id)) || {}; + return { + id: item.id, + order_line_no: item.order_line_no || '', + item_code: item.item_code || stock.item_code || '', + item_name: item.item_name || stock.item_name || '', + sku_property: stock.sku_property || '', + quantity: stock.quantity || 0, + locked_quantity: stock.locked_quantity || 0, + is_batch_mgmt: stock.is_batch_mgmt || 'N', + is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N', + is_images: stock.is_images || 'N', + store_id: stock.store_id || null, + packing_requirements: stock.packing_requirements || '', + pick_requirements: stock.pick_requirements || '', + recheck_requirements: stock.recheck_requirements || '', + merge_requirements: stock.merge_requirements || 'Y', + stock_unit: stock.stock_unit || '', + image_url: stock.image_url || [], + barcodes: stock.barcodes || [], + plan_qty: item.plan_qty || 0, + stock_id: item.stock_id || null, + order_item_id: item.id, + order_id: orderDeliveryId, + }; + }); + ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`); + } + } + + // 5. 打包视频 + const packVideos = []; + try { + const packTasks = await ctx.model.PackTask.findAll({ + where: { order_id: orderDeliveryId, deleted_at: null }, + include: [ + { + model: ctx.model.PackTaskVideo, + as: 'videos', + where: { deleted_at: null }, + required: false, + }, + ], + order: [[ 'create_time', 'DESC' ]], + raw: false, + }); + + for (const task of packTasks) { + const taskJson = task.toJSON ? task.toJSON() : task; + const videos = (taskJson.videos || []).map(v => ({ + id: v.id, + video_url: v.video_url, + camera_id: v.camera_id, + status: v.status, + created_at: v.created_at ? app.formatDate(v.created_at) : null, + })); + packVideos.push({ + pack_task_id: taskJson.id, + status: taskJson.status, + pack_quantity: taskJson.pack_quantity, + start_time: taskJson.start_time ? app.formatDate(taskJson.start_time) : null, + end_time: taskJson.end_time ? app.formatDate(taskJson.end_time) : null, + operator_text: taskJson.operator_text || '', + videos, + }); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 查询打包视频失败: ${err.message}`); + } + + // 6. 组装返回 + return { + id: order.id, + delivery_order_code: order.delivery_order_code || '', + warehouse_id: order.warehouse_id, + store_id: order.store_id, + // 重量(g) + items_weight: order.items_weight || 0, + packages_weight: order.packages_weight || 0, + // 波次 + wave_id: order.wave_id || 0, + wave_no: order.wave_no || '', + // 来源 + platform_name: order.source_platform_name || '', + source_order_codes: order.source_order_codes || '', + // 创建来源渠道 + create_channel: order.create_channel || '', + create_channel_label: this._getCreateChannelLabel(order.create_channel), + // 状态机 + sync_status: order.sync_status || 'padding', + inspection_status: order.inspection_status || 'none', + storage_status: order.storage_status || 'none', + post_status: order.post_status || 'none', + print_status: order.print_status || 'none', + pick_status: order.pick_status || 'none', + pack_status: order.pack_status || 'none', + intercept_status: order.intercept_status || 'none', + // 数量 + items_count: order.items_count, + items_total: order.items_total, + // 金额 + total_amount: order.total_amount, + item_amount: order.item_amount, + // 收件人 / 发件人 / 明细 / 打包视频 + recipient, + sender, + items: orderItems, + pack_videos: packVideos, + }; + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 整体异常 id=${orderDeliveryId}: ${err.message}`, err.stack); + return null; + } + } + + /** + * 解析货主在当前仓库下的合约备注。 + * + * @param {number} storeId 货主ID + * @param {number} warehouseId 仓库ID + * @return {Promise} 合约备注信息 + */ + async _resolveStoreContractNote(storeId, warehouseId) { + const { ctx } = this; + + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: [ 'id', 'store_remask', 'warehouse_remask', 'store_use_status', 'warehouse_use_status' ], + raw: true, + }); + + if (!sw) return null; + + return { + contract_id: sw.id, + store_remask: sw.store_remask || '', + warehouse_remask: sw.warehouse_remask || '', + store_use_status: sw.store_use_status, + warehouse_use_status: sw.warehouse_use_status, + }; + } + + /** + * 解析关联运单的快递公司名称与使用的物流接口。 + * + * @param {number} waybillId 运单ID(wms_order_express.id) + * @return {Promise} 运单详情,查询失败返回 null + */ + async _resolveWaybillDetail(waybillId) { + const { ctx } = this; + + const waybill = await ctx.model.OrderExpress.findOne({ + where: { id: waybillId }, + attributes: [ + 'id', 'waybill_code', 'order_id', 'logistics_code', + 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', + 'status', 'is_back', 'is_intercept', 'warehouse_id', 'create_at', + ], + raw: true, + }); + + if (!waybill) return null; + + return { + id: waybill.id, + waybill_code: waybill.waybill_code || '', + order_id: waybill.order_id, + logistics_code: waybill.logistics_code || '', + logistics_name: waybill.logistics_name || '', + logistics_interface_id: waybill.logistics_interface_id, + logistics_interface_name: waybill.logistics_interface_name || '', + status: waybill.status, + is_back: waybill.is_back || 'N', + is_intercept: waybill.is_intercept || 'N', + warehouse_id: waybill.warehouse_id, + create_at: waybill.create_at ? ctx.app.formatDate(waybill.create_at) : null, + }; + } + + /** + * 为步骤列表补充附件信息。 + * + * @param {Array} steps 步骤列表 + * @return {Promise>} 含附件信息的步骤列表 + */ + async _enrichStepsWithAttachments(steps = []) { + const { ctx } = this; + + if (!steps || steps.length === 0) { + return []; + } + + const detailIds = steps.map(s => s.id).filter(Boolean); + if (detailIds.length === 0) { + return steps; + } + + // 查询所有步骤的附件引用 + const references = await ctx.model.FileReference.findAll({ + where: { + business_type: 'after_sale_detail', + business_id: { [ctx.app.Sequelize.Op.in]: detailIds.map(String) }, + }, + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ 'id', 'file_key', 'file_url', 'file_name', 'file_size', 'mime_type' ], + required: false, + }, + ], + raw: false, + }); + + // 构建 detailId → files 映射 + const attachmentMap = new Map(); + for (const ref of references) { + const refJson = ref.toJSON ? ref.toJSON() : ref; + const detailId = Number(refJson.business_id); + const fileInfo = refJson.file || null; + + if (!detailId) continue; + + if (!attachmentMap.has(detailId)) { + attachmentMap.set(detailId, []); + } + + if (fileInfo) { + attachmentMap.get(detailId).push({ + id: fileInfo.id, + file_key: fileInfo.file_key, + file_url: fileInfo.file_url, + file_name: fileInfo.file_name, + file_size: fileInfo.file_size, + mime_type: fileInfo.mime_type, + }); + } + } + + // 为每个步骤挂载附件 + return steps.map(step => ({ + ...step, + attachments: attachmentMap.get(step.id) || [], + })); + } + + // =========================== + // 创建售后单 + // =========================== + + /** + * 创建售后单主表记录。 + * + * @param {Object} data 售后单数据 + * @param {number} data.warehouse_id 仓库ID + * @param {string} data.after_sale_no 售后单号 + * @param {string} data.type 售后类型 + * @param {string} data.sub_type 售后子类型 + * @param {string} data.title 售后标题 + * @param {string} [data.description] 售后描述 + * @param {number} [data.priority] 优先级 + * @param {number} data.creator_id 创建人ID + * @param {string} [data.role_group] 当前处理角色组 + * @param {string} [data.status] 售后状态 + * @param {Object} [transaction] Sequelize 事务对象 + * @return {Promise} 创建的售后单记录 + */ + async create(data, transaction = null) { + const { ctx, app } = this; + const record = await ctx.model.AfterSale.create(data, { transaction }); + const json = record && record.toJSON ? record.toJSON() : record; + return this._formatAfterSaleRow(json, app); + } + + /** + * 批量补充列表行的货主名称 store_name。 + * 货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称), + * 无合约或备注为空时回退 wms_store.company_name(公司全称)。 + * + * @param {Object[]} list 售后单列表行(原地补充 store_name 字段) + * @return {Promise} + */ + async _enrichListStoreNames(list) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const storeIds = [ ...new Set(list.map(row => row.store_id).filter(Boolean)) ]; + const warehouseIds = [ ...new Set(list.map(row => row.warehouse_id).filter(Boolean)) ]; + + if (storeIds.length === 0) { + list.forEach(row => { + row.store_name = ''; + }); + return; + } + + // 1. 合约表货主备注名称(store_id + warehouse_id 维度) + let contractMap = {}; + if (warehouseIds.length > 0) { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: storeIds }, + warehouse_id: { [Op.in]: warehouseIds }, + }, + attributes: [ 'store_id', 'warehouse_id', 'store_remask' ], + raw: true, + }); + contractMap = swRows.reduce((acc, sw) => { + acc[`${sw.store_id}_${sw.warehouse_id}`] = sw.store_remask || ''; + return acc; + }, {}); + } + + // 2. 货主公司全称兜底 + let storeMap = {}; + const storeRows = await ctx.model.Store.findAll({ + where: { id: { [Op.in]: storeIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + storeMap = storeRows.reduce((acc, store) => { + acc[store.id] = store.company_name || ''; + return acc; + }, {}); + + list.forEach(row => { + const contractRemask = contractMap[`${row.store_id}_${row.warehouse_id}`] || ''; + row.store_name = contractRemask || storeMap[row.store_id] || ''; + }); + } + + // =========================== + // 更新售后单 + // =========================== + + /** + * 更新售后单主表字段。 + * + * @param {number} id 售后单主键ID + * @param {Object} data 需要更新的字段键值对 + * @param {Object} [transaction] Sequelize 事务对象 + * @return {Promise} 更新后的售后单记录 + * @throws {Error} 售后单不存在时抛出 + */ + async update(id, data, transaction = null) { + const { ctx, app } = this; + + const record = await ctx.model.AfterSale.findOne({ + where: { id, deleted_at: null }, + transaction, + }); + + if (!record) { + throw new Error('售后单不存在'); + } + + await record.update(data, { transaction }); + const json = record && record.toJSON ? record.toJSON() : record; + return this._formatAfterSaleRow(json, app); + } + + /** + * 格式化售后单记录的时间字段。 + * @param {Object} row 原始数据库行 + * @param {Object} app Egg app 实例 + * @return {Object} 格式化后的行 + */ + _formatAfterSaleRow(row, app) { + if (!row) return row; + return { + ...row, + created_at: row.created_at ? app.formatDate(row.created_at) : null, + updated_at: row.updated_at ? app.formatDate(row.updated_at) : null, + resolved_at: row.resolved_at ? app.formatDate(row.resolved_at) : null, + followup_at: row.followup_at ? app.formatDate(row.followup_at) : null, + started_at: row.started_at ? app.formatDate(row.started_at) : null, + completed_at: row.completed_at ? app.formatDate(row.completed_at) : null, + }; + } + + // =========================== + // 步骤记录 + // =========================== + + /** + * 写入一条售后进度步骤记录。 + * + * @param {number} afterSaleId 售后单主键ID + * @param {Object} stepData 步骤数据 + * @param {number} [stepData.step_status=2] 步骤状态(0=待开始,1=进行中,2=已完成,3=已跳过) + * @param {number} [stepData.operator_id] 操作人账户ID + * @param {string} [stepData.operator_snapshot] 操作人信息快照 JSON + * @param {string} [stepData.action] 操作动作描述 + * @param {string} [stepData.remark] 处理备注 + * @param {Date} [stepData.started_at] 步骤开始时间 + * @param {Date} [stepData.completed_at] 步骤完成时间 + * @param {Object} [transaction] Sequelize 事务对象 + * @return {Promise} 创建的步骤记录 + */ + async addStep(afterSaleId, stepData = {}, transaction = null) { + const { ctx } = this; + const now = new Date(); + + const record = await ctx.model.AfterSaleDetail.create({ + after_sale_id: afterSaleId, + step_status: stepData.step_status !== undefined ? stepData.step_status : 'processing', + operator_id: stepData.operator_id || null, + operator_snapshot: stepData.operator_snapshot || null, + action: stepData.action || null, + remark: stepData.remark || null, + started_at: stepData.started_at || now, + completed_at: stepData.completed_at || now, + created_at: now, + }, { transaction }); + + return record && record.toJSON ? record.toJSON() : record; + } + + // =========================== + // 附件绑定 + // =========================== + + /** + * 将文件绑定到售后步骤(批量)。 + * 通过 wms_file_reference 表建立关联。 + * + * @param {number} detailId 售后步骤ID + * @param {number[]} fileIds 文件ID列表 + * @param {Object} [transaction] Sequelize 事务对象 + * @return {Promise>} 创建的文件引用记录列表 + */ + async bindAttachments(detailId, fileIds = [], transaction = null) { + const { ctx } = this; + + if (!detailId || !Array.isArray(fileIds) || fileIds.length === 0) { + return []; + } + + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + const createdBy = ctx.user + ? String(ctx.user.employees_name || ctx.user.real_name || ctx.user.name || ctx.user.id || '') + : ''; + + const references = []; + for (const fileId of fileIds) { + // 检查是否已存在绑定,防止重复 + const existing = await ctx.model.FileReference.findOne({ + where: { + file_id: fileId, + warehouse_id: warehouseId, + business_type: 'after_sale_detail', + business_id: String(detailId), + }, + transaction, + }); + + if (existing) { + references.push(existing); + continue; + } + + const reference = await ctx.model.FileReference.create({ + file_id: fileId, + warehouse_id: warehouseId, + business_type: 'after_sale_detail', + business_id: String(detailId), + display_order: 0, + created_by: createdBy, + created_at: new Date(), + }, { transaction }); + + references.push(reference); + } + + return references.map(r => (r && r.toJSON ? r.toJSON() : r)); + } + + // =========================== + // 转单 + // =========================== + + /** + * 转单:更新售后单 role_group 并写入步骤记录。 + * + * @param {Object} params 转单参数 + * @param {number} params.id 售后单主键ID + * @param {string} params.targetRoleGroup 目标角色组 + * @param {string} params.remark 转单备注 + * @param {number} params.operatorId 操作人ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @return {Promise} 更新后的售后单记录 + */ + async transfer(params = {}) { + const { id, targetRoleGroup, remark, operatorId, operatorSnapshot } = params; + + const transaction = await this.ctx.model.transaction(); + + try { + // 更新 role_group + const updated = await this.update(id, { + role_group: targetRoleGroup, + updated_at: new Date(), + }, transaction); + + // 写入步骤记录(step_status 与主表当前 status 一致) + await this.addStep(id, { + step_status: updated.status || 'processing', + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action: '转单', + remark: remark || `转至${targetRoleGroup}`, + started_at: new Date(), + completed_at: new Date(), + }, transaction); + + await transaction.commit(); + return updated; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 处理工单 + // =========================== + + /** + * 处理工单:校验权限 → 写步骤 → 可选更新状态 → 变量回设 → 绑附件。 + * + * @param {Object} params 处理参数 + * @param {number} params.id 售后单主键ID + * @param {string|null} params.remark 处理备注 + * @param {string|null} params.targetStatus 目标售后状态 + * @param {string|null} params.resolution 完结处理结果 + * @param {number[]} params.attachmentIds 附件文件ID列表 + * @param {number} params.operatorId 操作人ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {number} params.warehouseId 仓库ID + * @param {boolean} [params.notifyGroup] 是否将处理备注发送到对应货主售后群(内部自动处理不传) + * @return {Promise} 处理结果,包含更新后的售后单、步骤记录和通知群数量 + * @throws {Error} 售后单不存在或权限不足时抛出 + */ + async handleWorkOrder(params = {}) { + const { + id, remark, targetStatus, resolution, + attachmentIds, operatorId, operatorSnapshot, + warehouseId, notifyGroup, + } = params; + + const { ctx } = this; + + // 1. 查询售后单并校验存在性(限定仓库范围) + const afterSale = await ctx.model.AfterSale.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + + if (!afterSale) { + throw new Error('售后单不存在'); + } + + // 2. status 不填或填错默认 processing;pending 是创建默认值,不适用于处理操作 + const ALLOWED_STATUSES = Object.keys(ctx.model.AfterSale.AFTER_SALE_STATUS).filter(s => s !== 'pending'); + const safeStatus = (targetStatus && ALLOWED_STATUSES.includes(targetStatus)) ? targetStatus : 'processing'; + + // 3. 校验 role_group 权限:操作人必须有对应 role_group 的处理权限。 + // 实际权限解析已在方法层(systemMethods/afterSale.js)通过 block 权限完成, + // 此处仅做兜底校验。 + const allowedRoleGroups = [ 'customer_service', 'warehouse', 'finance' ]; + const currentRoleGroup = afterSale.role_group; + + if (currentRoleGroup && !allowedRoleGroups.includes(currentRoleGroup)) { + throw new Error('无权限处理当前角色组的售后单'); + } + + // 4. 开启事务 + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + + // 5. 写入步骤记录(action 由服务端固定为"处理工单",step_status 同步主表 status) + const step = await this.addStep(id, { + step_status: safeStatus, + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action: '处理工单', + remark, + started_at: now, + completed_at: now, + }, transaction); + + // 6. 绑定附件 + if (Array.isArray(attachmentIds) && attachmentIds.length > 0) { + await this.bindAttachments(step.id, attachmentIds, transaction); + } + + // 7. 更新售后单状态 + const updateFields = { updated_at: now }; + + updateFields.status = safeStatus; + + // 若完结,写入 resolution 和 resolved_at;清除 followup_at + if (safeStatus === 'completed') { + updateFields.resolution = resolution || null; + updateFields.resolved_at = now; + updateFields.followup_at = null; + } + + // 若设为 pending_feedback:按仓库配置自动计算下次跟进时间 + if (safeStatus === 'pending_feedback') { + const hours = await this._resolveFollowupHours(afterSale.warehouse_id, afterSale.type, afterSale.sub_type); + ctx.logger.info( + '[handleWorkOrder] id=%s warehouse=%s type=%s subType=%s hours=%d', + id, afterSale.warehouse_id, afterSale.type, afterSale.sub_type, hours + ); + // 使用数据库 NOW() 确保与查询条件时区一致 + updateFields.followup_at = ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`); + } + + // 8. 若当前角色非客服组且状态非完结,自动回设为客服组 + if (currentRoleGroup && currentRoleGroup !== 'customer_service' && safeStatus !== 'completed') { + updateFields.role_group = 'customer_service'; + } + + await afterSale.update(updateFields, { transaction }); + + await transaction.commit(); + + // 9. 处理备注发送到对应的货主售后群(仅交互处理传入 notifyGroup 时触发,不转发快递群) + let notifiedGroupCount = 0; + if (notifyGroup && remark && String(remark).trim()) { + try { + const remarkText = String(remark).trim(); + const asRow = afterSale.toJSON ? afterSale.toJSON() : afterSale; + + // 定位货主:优先工单 store_id,缺失时从来源消息所在群反查 + let notifyStoreId = Number(asRow.store_id || 0); + if (!notifyStoreId && asRow.inbox_message_id) { + try { + const inbound = await ctx.model.InboxMessage.findByPk(asRow.inbox_message_id, { + attributes: [ 'group_id' ], + raw: true, + }); + if (inbound && inbound.group_id) { + const originGroup = await ctx.model.InboxGroup.findOne({ + attributes: [ 'store_id' ], + where: { + group_id: inbound.group_id, + warehouse_id: warehouseId, + is_blocked: 0, + }, + raw: true, + }); + if (originGroup && originGroup.store_id) { + notifyStoreId = Number(originGroup.store_id); + } + } + } catch (originErr) { + ctx.logger.warn(`[handleWorkOrder] 反查来源群货主失败 id=${id}: ${originErr.message}`); + } + } + + if (notifyStoreId) { + const storeGroups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ + storeIds: [ notifyStoreId ], + warehouseId, + }); + // 通知文案只给运单号 + 处理内容(售后单号对客户无意义) + const waybillNo = String(asRow.waybill_no || '').trim(); + const content = waybillNo + ? `运单${waybillNo} 处理备注:\n${remarkText}` + : `处理备注:\n${remarkText}`; + for (const g of storeGroups) { + if (!g.group_id) continue; + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name || '', + content, + ext_data: g.ext_data || null, + }); + notifiedGroupCount += 1; + } + } + + ctx.logger.info( + `[handleWorkOrder] 处理备注发送到货主售后群 id=${id} store=${notifyStoreId} notified=${notifiedGroupCount}` + ); + } catch (notifyErr) { + ctx.logger.warn(`[handleWorkOrder] 处理备注发送群失败 id=${id}: ${notifyErr.message}`); + } + } + + const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; + + return { + after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app), + step, + notified_groups: notifiedGroupCount, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 拦截链路:批量创建工单 + 通知快递群 + // =========================== + + /** + * 拦截链路共享方法:根据订单 ID 查找运单,幂等创建售后工单,并按快递分组通知售后群。 + * 用于 batchIntercept / confirmIntercept / Qimen cancel / OpenAPI cancel 等入口统一调用。 + * + * @param {Object} params 参数。 + * @param {number[]} params.orderIds 订单 ID 列表。 + * @param {number} params.warehouseId 仓库 ID。 + * @param {string} params.creatorLabel 创建人标签(如 "系统"、"王小明")。 + * @param {string} [params.reason] 拦截原因。 + * @return {Promise<{ createdCount: number, notifiedCount: number }>} 创建与通知统计。 + */ + async createInterceptWorkOrdersAndNotify(params = {}) { + const { ctx } = this; + const { orderIds, warehouseId, creatorLabel, reason } = params; + + if (!Array.isArray(orderIds) || orderIds.length === 0 || !warehouseId) { + return { createdCount: 0, notifiedCount: 0 }; + } + + try { + // 1. 查询运单信息 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id', + ], + where: { + order_id: { [ctx.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (expressList.length === 0) { + return { createdCount: 0, notifiedCount: 0 }; + } + + // 2. 幂等检查:已有未完结的拦截工单不再重复创建 + const expressIds = expressList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, + type: 'order', + sub_type: 'intercept', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); + + if (toCreate.length === 0) { + return { createdCount: 0, notifiedCount: 0 }; + } + + // 3. 批量创建工单 + const label = creatorLabel || '系统'; + let createdCount = 0; + const createdWaybillIds = []; + + for (const e of toCreate) { + try { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${label}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `拦截原因: ${reason}` : '', + ].filter(Boolean).join('\n'); + + await this.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: 'intercept', + title: `[系统拦截] ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || null, + order_id: e.order_id || null, + }); + createdCount += 1; + createdWaybillIds.push(e.id); + } catch (createErr) { + ctx.logger.warn( + `[afterSale.createInterceptWorkOrdersAndNotify] 创建工单失败, waybill=${e.waybill_code}, error=${createErr.message}` + ); + } + } + + // 4. 按快递分组通知售后群 + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { + code, + interfaceId: e.logistics_interface_id, + logisticsName: String(e.logistics_name || '').trim(), + waybills: [], + }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedCount = 0; + const notifiedWaybillIds = new Set(); + // 无对应快递群(或快递无接口)的运单收集后统一降级通知仓库异常群(与货主群缺失降级行为一致) + const fallbackEntries = []; + + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) { + fallbackEntries.push(info); + continue; + } + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + + if (afterSalesGroups.length === 0) { + fallbackEntries.push(info); + continue; + } + + const notifyMsg = info.waybills.join('\n') + '\n拦截'; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: notifyMsg, + ext_data: g.ext_data || null, + }); + notifiedCount += 1; + } + // 标记该快递下所有运单已通知 + const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); + codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + fallbackEntries.push(info); + ctx.logger.warn(`[afterSale] 查售后群失败 code=${code}: ${e.message}`); + } + } + + // 4b. 无对应快递群降级:转发仓库异常群,内容前缀标记失败(与货主群缺失降级一致) + if (fallbackEntries.length > 0) { + try { + const exceptionGroups = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id', 'group_name', 'ext_data' ], + where: { + warehouse_id: warehouseId, + group_type: 'warehouse', + sub_type: 'exception', + is_blocked: 0, + }, + raw: true, + }); + + if (exceptionGroups.length > 0) { + const labelSet = new Set(); + const fallbackLines = []; + for (const entry of fallbackEntries) { + const label = entry.logisticsName || entry.code || '未知快递'; + labelSet.add(label); + for (const waybill of entry.waybills) { + fallbackLines.push(`${label} ${waybill}`); + } + } + const fallbackContent = `通知快递【${Array.from(labelSet).join('、')}】失败\n${fallbackLines.join('\n')}\n拦截`; + for (const g of exceptionGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: fallbackContent, + ext_data: g.ext_data || null, + }); + } + ctx.logger.warn('[afterSale.createInterceptWorkOrdersAndNotify] 无对应快递群,已降级通知仓库异常群', { + warehouseId, + fallbackCount: fallbackEntries.length, + exceptionGroupCount: exceptionGroups.length, + }); + } + } catch (fallbackErr) { + ctx.logger.warn(`[afterSale] 降级通知异常群失败: ${fallbackErr.message}`); + } + } + + // 5. 有通知的工单升级为 pending_feedback + if (notifiedWaybillIds.size > 0) { + const notifiedWaybillIdArr = [ ...notifiedWaybillIds ]; + const hours = await this._resolveFollowupHours(warehouseId, 'order', 'intercept'); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: notifiedWaybillIdArr }, + warehouse_id: warehouseId, + type: 'order', + sub_type: 'intercept', + status: 'pending', + }, + } + ); + } + + return { createdCount, notifiedCount }; + } catch (error) { + ctx.logger.warn(`[afterSale.createInterceptWorkOrdersAndNotify] 整体失败: ${error.message}`); + return { createdCount: 0, notifiedCount: 0 }; + } + } + + // =========================== + // 跟进时间配置 + // =========================== + + /** + * 根据仓库配置解析跟进小时数。 + * 优先级:policy_config sub_type 精确匹配 → type._default → 整数兜底 → 24h。 + * + * @param {number} warehouseId 仓库ID + * @param {string} type 售后类型 + * @param {string} subType 售后子类型 + * @return {Promise} 跟进小时数 + */ + async _resolveFollowupHours(warehouseId, type, subType) { + const { ctx } = this; + + // 仓库配置值的最小有效阈值:≤1 视为未配置的占位值,回退到 DEFAULTS + // (实际业务最小合理值为 intercept/urge 的 4h,不存在 0/1h 的跟进场景) + const MIN_VALID_FOLLOWUP_HOURS = 2; + + // 1. 仓库已保存的配置 + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { warehouse_id: warehouseId }, + attributes: [ 'policy_config' ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + ctx.logger.info( + '[_resolveFollowupHours] warehouseId=%s type=%s subType=%s hasStoreWarehouse=%s', + warehouseId, type, subType, !!(sw && sw.policy_config) + ); + + if (sw && sw.policy_config) { + let config = sw.policy_config; + if (typeof config === 'string') { + try { config = JSON.parse(config); } catch { config = {}; } + } + const whConfig = config && config.after_sale_followup_hours; + ctx.logger.info( + '[_resolveFollowupHours] whConfig type=%s value=%s', + typeof whConfig, JSON.stringify(whConfig) + ); + + if (whConfig && typeof whConfig === 'object') { + const whTypeMap = whConfig[type]; + ctx.logger.info( + '[_resolveFollowupHours] whTypeMap for type=%s: %s', + type, JSON.stringify(whTypeMap) + ); + + // 分支 A:嵌套对象格式 {"order": {"damage": 48, "_default": 24}} + if (whTypeMap && typeof whTypeMap === 'object') { + if (subType) { + const subVal = this._tryParseHours(whTypeMap[subType]); + if (typeof subVal === 'number' && subVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info('[_resolveFollowupHours] MATCH subType (nested): %s=%dh', subType, subVal); + return subVal; + } + } + const defVal = this._tryParseHours(whTypeMap._default); + if (typeof defVal === 'number' && defVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info('[_resolveFollowupHours] MATCH type._default (nested): %s._default=%dh', type, defVal); + return defVal; + } + } + + // 分支 B:扁平格式 {"order": "24"} 或 {"order": 24} + // 值为字符串或数字,直接作为该 type 下所有 subType 的统一时长 + const flatVal = this._tryParseHours(whTypeMap); + if (typeof flatVal === 'number' && flatVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info('[_resolveFollowupHours] MATCH type flat: %s=%dh', type, flatVal); + return flatVal; + } + } + // 分支 C:全局数字 {"after_sale_followup_hours": 24} 或 {"after_sale_followup_hours": "24"} + { + const globalVal = this._tryParseHours(whConfig); + if (typeof globalVal === 'number' && globalVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info('[_resolveFollowupHours] MATCH whConfig global: %dh', globalVal); + return globalVal; + } + } + ctx.logger.info(`[_resolveFollowupHours] whConfig found but no valid match (all < ${MIN_VALID_FOLLOWUP_HOURS}h or type mismatch), falling to DEFAULTS`); + } + + // 2. 仓库未配置时,使用字段默认值(与 setting.warehouse.getFieldMeta 返回一致) + const DEFAULTS = { + order: { _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 }, + receiving: { _default: 24, shortage: 48, damage: 48 }, + entry: { _default: 24, shortage: 48, damage: 48 }, + stockout: { _default: 24, return_issue: 48, shortage: 48 }, + }; + const typeDefault = DEFAULTS[type]; + if (typeDefault) { + if (subType && typeof typeDefault[subType] === 'number') { + ctx.logger.info('[_resolveFollowupHours] DEFAULTS subType match: %s=%dh', subType, typeDefault[subType]); + return typeDefault[subType]; + } + if (typeof typeDefault._default === 'number') { + ctx.logger.info('[_resolveFollowupHours] DEFAULTS type._default: %s=%dh', type, typeDefault._default); + return typeDefault._default; + } + } + + // 3. 硬兜底 + ctx.logger.warn('[_resolveFollowupHours] FALLBACK 24h for type=%s subType=%s', type, subType); + return 24; + } + + /** + * 将配置值尝试转为有效的小时数。 + * 兼容数字 24 和字符串 "24" 两种格式;无法解析时返回 null。 + * + * @param {*} raw 原始配置值 + * @return {number|null} 有效小时数,或 null + */ + _tryParseHours(raw) { + if (raw === null || raw === undefined || raw === '') return null; + if (typeof raw === 'number' && Number.isFinite(raw)) return raw; + if (typeof raw === 'string') { + const parsed = Number(raw); + if (Number.isFinite(parsed)) return parsed; + } + return null; + } + + // =========================== + // 批量设为待反馈 + // =========================== + + /** + * 批量将售后工单设为"待反馈"状态,并按仓库配置自动计算 followup_at。 + * 对每个工单写入步骤记录,所有操作在同一事务中执行。 + * + * @param {Object} params 批量操作参数 + * @param {number[]} params.ids 售后单主键ID列表 + * @param {number} params.operatorId 操作人账户ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {string} [params.remark] 统一处理备注(所有工单共用) + * @param {number} params.warehouseId 仓库ID(用于权限校验) + * @return {Promise} { total, success, failed: [{id, reason}] } + */ + async batchSetPendingFeedback(params = {}) { + const { ids, operatorId, operatorSnapshot, remark, warehouseId } = params; + const { ctx } = this; + + // 1. 入参校验 + if (!Array.isArray(ids) || ids.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0); + if (numericIds.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + // 2. 查询所有目标工单 + const afterSales = await ctx.model.AfterSale.findAll({ + where: { + id: { [ctx.app.Sequelize.Op.in]: numericIds }, + deleted_at: null, + }, + }); + + const afterSaleMap = new Map(); + for (const record of afterSales) { + afterSaleMap.set(record.id, record); + } + + // 3. 预校验 & 分类 + const validRecords = []; + const failed = []; + + // 终态不可设为待反馈 + const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]); + + for (const id of numericIds) { + const record = afterSaleMap.get(id); + if (!record) { + failed.push({ id, reason: '售后单不存在或已删除' }); + continue; + } + if (TERMINAL_STATUSES.has(record.status)) { + failed.push({ id, reason: `工单已完结(${record.status}),不可设为待反馈` }); + continue; + } + if (record.warehouse_id !== warehouseId) { + failed.push({ id, reason: '仓库不匹配,无权操作' }); + continue; + } + validRecords.push(record); + } + + // 4. 开启事务,逐条更新 + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + let successCount = 0; + + for (const record of validRecords) { + // 4a. 解析该工单的跟进小时数 + const hours = await this._resolveFollowupHours( + record.warehouse_id, + record.type, + record.sub_type + ); + + ctx.logger.info( + '[batchSetPendingFeedback] id=%s type=%s subType=%s hours=%d', + record.id, record.type, record.sub_type, hours + ); + + // 4b. 写入步骤记录 + await this.addStep(record.id, { + step_status: 'pending_feedback', + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action: '设为待反馈', + remark: remark || null, + started_at: now, + completed_at: now, + }, transaction); + + // 4c. 更新主表:status + followup_at + role_group 回客服组 + const updateFields = { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + updated_at: now, + }; + // 若非客服组,自动回设为客服组(与 handleWorkOrder 行为一致) + if (record.role_group && record.role_group !== 'customer_service') { + updateFields.role_group = 'customer_service'; + } + + await record.update(updateFields, { transaction }); + successCount++; + } + + await transaction.commit(); + + return { + total: numericIds.length, + success: successCount, + failed, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 批量完结/关闭 + // =========================== + + /** + * 批量将售后工单设为完结或关闭状态。 + * completed 时自动写入 resolved_at 并清除 followup_at;closed 仅更新状态。 + * 对每个工单写入步骤记录,所有操作在同一事务中执行。 + * + * @param {Object} params 批量操作参数 + * @param {number[]} params.ids 售后单主键ID列表 + * @param {string} params.status 目标状态:completed | closed + * @param {string} [params.resolution] 完结处理结果(仅 status=completed 时写入) + * @param {number} params.operatorId 操作人账户ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {string} [params.remark] 统一处理备注(所有工单共用) + * @param {number} params.warehouseId 仓库ID(用于权限校验) + * @return {Promise} { total, success, failed: [{id, reason}] } + */ + async batchClose(params = {}) { + const { ids, status: targetStatus, resolution, operatorId, operatorSnapshot, remark, warehouseId } = params; + const { ctx } = this; + + // 1. 入参校验 + const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]); + if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) { + return { total: 0, success: 0, failed: [{ id: 0, reason: 'status 必须为 completed 或 closed' }] }; + } + + if (!Array.isArray(ids) || ids.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0); + if (numericIds.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + // 2. 查询所有目标工单 + const afterSales = await ctx.model.AfterSale.findAll({ + where: { + id: { [ctx.app.Sequelize.Op.in]: numericIds }, + deleted_at: null, + }, + }); + + const afterSaleMap = new Map(); + for (const record of afterSales) { + afterSaleMap.set(record.id, record); + } + + // 3. 预校验 & 分类 + const validRecords = []; + const failed = []; + + // 终态不可重复完结/关闭 + const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]); + + for (const id of numericIds) { + const record = afterSaleMap.get(id); + if (!record) { + failed.push({ id, reason: '售后单不存在或已删除' }); + continue; + } + if (TERMINAL_STATUSES.has(record.status)) { + failed.push({ id, reason: `工单已是终态(${record.status}),不可重复${targetStatus === 'completed' ? '完结' : '关闭'}` }); + continue; + } + if (record.warehouse_id !== warehouseId) { + failed.push({ id, reason: '仓库不匹配,无权操作' }); + continue; + } + validRecords.push(record); + } + + // 4. 开启事务,逐条更新 + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + let successCount = 0; + + // 操作动作名称 + const actionName = targetStatus === 'completed' ? '批量完结' : '批量关闭'; + + for (const record of validRecords) { + // 4a. 写入步骤记录 + await this.addStep(record.id, { + step_status: targetStatus, + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action: actionName, + remark: remark || null, + started_at: now, + completed_at: now, + }, transaction); + + // 4b. 更新主表 + const updateFields = { + status: targetStatus, + updated_at: now, + followup_at: null, + }; + + // completed:额外写入 resolution + resolved_at + if (targetStatus === 'completed') { + updateFields.resolution = resolution || null; + updateFields.resolved_at = now; + } + + await record.update(updateFields, { transaction }); + successCount++; + } + + await transaction.commit(); + + return { + total: numericIds.length, + success: successCount, + failed, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 登记理赔 + // =========================== + + /** + * 登记理赔:更新售后单的理赔字段,写入步骤记录,绑定附件。 + * + * @param {Object} params 理赔参数 + * @param {number} params.id 售后单主键ID + * @param {number} [params.claimNeeded] 仓库理赔标记 + * @param {number} [params.claimAmount] 仓库理赔金额 + * @param {string} [params.claimStatus] 仓库理赔状态 + * @param {number} [params.carrierClaimNeeded] 运方理赔标记 + * @param {number} [params.carrierClaimAmount] 运方理赔金额 + * @param {string} [params.carrierClaimStatus] 运方理赔状态 + * @param {string|null} params.remark 理赔备注 + * @param {string} params.action 操作动作描述 + * @param {number[]} params.attachmentIds 附件文件ID列表 + * @param {number} params.operatorId 操作人ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {number} params.warehouseId 仓库ID + * @return {Promise} 理赔处理结果 + * @throws {Error} 售后单不存在时抛出 + */ + async registerClaim(params = {}) { + const { + id, claimNeeded, claimAmount, claimStatus, + carrierClaimNeeded, carrierClaimAmount, carrierClaimStatus, + remark, action, attachmentIds, operatorId, operatorSnapshot, + } = params; + + const { ctx } = this; + + // 校验售后单存在 + const afterSale = await ctx.model.AfterSale.findOne({ + where: { id, deleted_at: null }, + }); + + if (!afterSale) { + throw new Error('售后单不存在'); + } + + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + + // 构建更新字段(仅含非空传入值) + const updateFields = { updated_at: now }; + + if (claimNeeded !== undefined) updateFields.claim_needed = claimNeeded; + if (claimAmount !== undefined) updateFields.claim_amount = claimAmount; + if (claimStatus !== undefined) updateFields.claim_status = claimStatus; + if (carrierClaimNeeded !== undefined) updateFields.carrier_claim_needed = carrierClaimNeeded; + if (carrierClaimAmount !== undefined) updateFields.carrier_claim_amount = carrierClaimAmount; + if (carrierClaimStatus !== undefined) updateFields.carrier_claim_status = carrierClaimStatus; + + await afterSale.update(updateFields, { transaction }); + + // 写入步骤(step_status 与主表当前 status 一致) + const step = await this.addStep(id, { + step_status: afterSale.status || 'processing', + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action, + remark, + started_at: now, + completed_at: now, + }, transaction); + + // 绑定附件 + if (Array.isArray(attachmentIds) && attachmentIds.length > 0) { + await this.bindAttachments(step.id, attachmentIds, transaction); + } + + await transaction.commit(); + + const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; + + return { + after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app), + step, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 导出 + // =========================== + + /** + * 售后单导出:分页查询 → ExcelJS 流式写入 → COS 上传。 + * 通过 onProgress 回调实时推送进度。 + * + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件 + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 导出结果,包含文件下载信息 + */ + async exportAfterSales(options = {}) { + const { where = {}, sort = {}, onProgress } = options; + + const reportProgress = async (status, progress, message, extra = {}) => { + if (typeof onProgress === 'function') { + await onProgress({ status, progress, message, ...extra }); + } + }; + + await reportProgress('running', 5, '正在准备导出数据...'); + + // 先统计总数 + const { count: totalCount } = await this.ctx.model.AfterSale.findAndCountAll({ + where: this._buildListWhere(where, this.ctx.app.Sequelize.Op), + raw: true, + }); + + await reportProgress('running', 10, `共 ${totalCount} 条记录,开始导出...`, { totalCount, currentCount: 0 }); + + // 分页查询并导出 + const pageSize = 500; + const totalPages = Math.ceil(totalCount / pageSize); + const allRows = []; + + for (let page = 1; page <= totalPages; page++) { + const result = await this.list(where, { page, pageSize }, sort); + const rows = Array.isArray(result.list) ? result.list : []; + allRows.push(...rows); + + const progress = 10 + Math.floor(((page / totalPages) * 80)); + await reportProgress('running', progress, `正在导出... (${allRows.length}/${totalCount})`, { + totalCount, + currentCount: allRows.length, + }); + + // 每页之间稍作让渡,避免长时间阻塞 + await new Promise(resolve => setImmediate(resolve)); + } + + await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: allRows.length }); + + // 生成 Excel 文件并上传 COS + const exportResult = await this._generateAndUploadExcel(allRows); + + await reportProgress('success', 100, '导出完成', { + totalCount, + currentCount: allRows.length, + result: exportResult, + }); + + return { + ...exportResult, + total_count: totalCount, + current_count: allRows.length, + }; + } + + /** + * 生成 Excel 并上传 COS,返回下载信息。 + * 与其他导出(order/return_received 等)口径一致:流式写临时文件 → uploadFile → uploadSuccessNotify。 + * + * @param {Array} rows 售后单数据行 + * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl } + */ + async _generateAndUploadExcel(rows = []) { + const { ctx } = this; + + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-after-sale-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `售后单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + + const ExcelJS = require('exceljs'); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + try { + const worksheet = workbook.addWorksheet('售后单列表'); + + // 定义列 + worksheet.columns = [ + { header: '售后单号', key: 'after_sale_no', width: 22 }, + { header: '售后类型', key: 'type', width: 12 }, + { header: '售后子类型', key: 'sub_type', width: 14 }, + { header: '售后状态', key: 'status', width: 12 }, + { header: '优先级', key: 'priority', width: 10 }, + { header: '标题', key: 'title', width: 30 }, + { header: '描述', key: 'description', width: 30 }, + { header: '当前处理角色', key: 'role_group', width: 16 }, + { header: '仓库理赔状态', key: 'claim_status', width: 14 }, + { header: '仓库理赔金额', key: 'claim_amount', width: 14 }, + { header: '运方理赔状态', key: 'carrier_claim_status', width: 14 }, + { header: '运方理赔金额', key: 'carrier_claim_amount', width: 14 }, + { header: '运单号', key: 'waybill_no', width: 20 }, + { header: '发货订单号', key: 'order_delivery_no', width: 20 }, + { header: '入库单号', key: 'entry_order_no', width: 20 }, + { header: '出库单号', key: 'order_stockout_no', width: 20 }, + { header: '收货单号', key: 'receiving_no', width: 20 }, + { header: '处理结果', key: 'resolution', width: 30 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + { header: '完结时间', key: 'resolved_at', width: 20 }, + ]; + + // 写入数据行 + for (const row of rows) { + worksheet.addRow(row).commit(); + } + worksheet.commit(); + await workbook.commit(); + + // ---- 上传文件(与 order/return_received 导出口径一致)---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/after_sale/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'afterSaleExport', + description: `售后单导出,共 ${rows.length} 条记录`, + }); + } + + // 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录,最后回退 COS key + const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {}; + const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null; + const fileUrlFromRecord = resolvedFileRecord + ? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '') + : ''; + const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || ''; + + return { + filename, + fileKey: safeUploadResult.fileName || uploadKey, + url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey, + cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '', + cosUrl: safeUploadResult.cosUrl || '', + }; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + ctx.logger.error(`[afterSale.export] 生成/上传 Excel 失败: ${error.message}`); + throw error; + } finally { + await fsp.rm(tempDir, { recursive: true, force: true }); + } + } + + // =========================== + // 工具方法 + // =========================== + + /** + * 获取创建来源渠道的中文标签。 + * @param {string} channel 创建渠道代码 + * @return {string} 中文标签 + */ + _getCreateChannelLabel(channel) { + const labels = { + MANUAL: '手工单', + API: '接口', + QM: '奇门', + }; + return labels[channel] || channel || ''; + } + + // =========================== + // 售后类型/子类型自定义配置 + // =========================== + + /** + * 构造售后类型配置业务错误(携带业务码,供方法层包装为统一失败响应)。 + * @param {string} message 错误提示信息 + * @param {number} [code=400] 业务错误码 + * @return {Error} 携带业务码的错误对象 + */ + _createAfterSaleTypeConfigError(message, code = 400) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 校验售后类型/子类型编码:非空且仅允许小写字母、数字、下划线。 + * @param {string} code 编码值 + * @param {string} fieldLabel 字段中文名(用于错误提示) + * @return {string} 去空格后的编码 + * @throws {Error} 编码为空或格式不合法时抛出(业务码 400) + */ + _validateAfterSaleTypeCode(code, fieldLabel) { + const trimmed = typeof code === 'string' ? code.trim() : ''; + if (!trimmed) { + throw this._createAfterSaleTypeConfigError(`${fieldLabel}不能为空`, 400); + } + if (!/^[a-z0-9_]+$/.test(trimmed)) { + throw this._createAfterSaleTypeConfigError(`${fieldLabel}只能包含小写字母、数字和下划线`, 400); + } + return trimmed; + } + + /** + * 归一化售后类型/子类型的 sort_order 入参。 + * @param {*} value 原始排序值 + * @return {number} 归一化后的整数排序值(非法值按 0 处理) + */ + _normalizeAfterSaleTypeSortOrder(value) { + const num = Number(value); + if (!Number.isFinite(num)) return 0; + return Math.floor(num); + } + + /** + * 归一化 is_enabled 入参。 + * @param {*} value 原始值(0/1/布尔/字符串) + * @param {number} [defaultValue=1] 缺省值 + * @return {number} 0 或 1 + */ + _normalizeAfterSaleTypeEnabled(value, defaultValue = 1) { + if (value === undefined || value === null || value === '') return defaultValue; + return value === 0 || value === '0' || value === false || value === 'false' ? 0 : 1; + } + + /** + * 格式化售后类型/子类型配置行:数值字段归一化、时间字段格式化。 + * @param {Object} row 原始行数据 + * @return {Object} 格式化后的行数据 + */ + _formatAfterSaleTypeConfigRow(row) { + if (!row) return row; + const { app } = this; + return { + ...row, + warehouse_id: row.warehouse_id === null || row.warehouse_id === undefined ? null : Number(row.warehouse_id), + is_system: Number(row.is_system), + is_enabled: Number(row.is_enabled), + sort_order: Number(row.sort_order), + created_at: row.created_at ? app.formatDate(row.created_at) : null, + updated_at: row.updated_at ? app.formatDate(row.updated_at) : null, + }; + } + + /** + * 构建售后类型列表的 where 条件(字段白名单,仓库维度由作用域条件统一控制)。 + * @param {Object} where 标准化 where 条件对象 + * @param {Object} Op Sequelize Op 对象 + * @return {Object} Sequelize where 条件 + */ + _buildAfterSaleTypeListWhere(where = {}, Op) { + const queryWhere = {}; + const directFields = [ + 'id', 'type', 'name', 'is_system', 'is_enabled', + 'sort_order', 'created_at', 'updated_at', + ]; + for (const field of directFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + return queryWhere; + } + + /** + * 构建售后类型列表的排序参数(字段白名单)。 + * @param {Object} sort 排序参数 + * @param {string} [sort.sortField] 排序字段 + * @param {string} [sort.sortOrder] 排序顺序(asc/desc) + * @return {Array>} Sequelize order 数组 + */ + _buildAfterSaleTypeListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field; + const allowedSortFields = new Set([ + 'id', 'type', 'name', 'is_enabled', 'sort_order', 'created_at', 'updated_at', + ]); + if (sortField && allowedSortFields.has(sortField)) { + const sortOrderRaw = String(sort.sortOrder || sort.sort_order || 'asc').toLowerCase(); + const sortOrder = sortOrderRaw === 'desc' ? 'DESC' : 'ASC'; + return [[ sortField, sortOrder ], [ 'id', 'ASC' ]]; + } + return [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]]; + } + + /** + * 构建售后子类型列表的 where 条件(字段白名单,仓库维度由作用域条件统一控制)。 + * @param {Object} where 标准化 where 条件对象 + * @param {Object} Op Sequelize Op 对象 + * @return {Object} Sequelize where 条件 + */ + _buildAfterSaleSubTypeListWhere(where = {}, Op) { + const queryWhere = {}; + const directFields = [ + 'id', 'type', 'sub_type', 'name', 'is_system', 'is_enabled', + 'sort_order', 'created_at', 'updated_at', + ]; + for (const field of directFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + return queryWhere; + } + + /** + * 构建售后子类型列表的排序参数(字段白名单)。 + * @param {Object} sort 排序参数 + * @param {string} [sort.sortField] 排序字段 + * @param {string} [sort.sortOrder] 排序顺序(asc/desc) + * @return {Array>} Sequelize order 数组 + */ + _buildAfterSaleSubTypeListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field; + const allowedSortFields = new Set([ + 'id', 'type', 'sub_type', 'name', 'is_enabled', 'sort_order', 'created_at', 'updated_at', + ]); + if (sortField && allowedSortFields.has(sortField)) { + const sortOrderRaw = String(sort.sortOrder || sort.sort_order || 'asc').toLowerCase(); + const sortOrder = sortOrderRaw === 'desc' ? 'DESC' : 'ASC'; + return [[ sortField, sortOrder ], [ 'id', 'ASC' ]]; + } + return [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]]; + } + + /** + * 售后类型列表:系统级(warehouse_id IS NULL)+ 当前仓库自定义合并,支持分页/where/sort。 + * @param {Object} params 参数对象 + * @param {number} params.warehouseId 当前仓库ID(0 表示无仓库上下文,仅返回系统级数据) + * @param {Object} [params.where] 标准化 where 条件 + * @param {Object} [params.pagination] 分页参数 {page, pageSize} + * @param {Object} [params.sort] 排序参数 {sortField, sortOrder} + * @return {Promise} { list: Array, pagination: Object } + */ + async getTypeList(params = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const { warehouseId = 0, where = {}, pagination = {}, sort = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const scopeWhere = warehouseId + ? { [Op.or]: [{ warehouse_id: null }, { warehouse_id: warehouseId }] } + : { warehouse_id: null }; + const fieldWhere = this._buildAfterSaleTypeListWhere(where, Op); + const queryWhere = { ...scopeWhere, ...fieldWhere }; + + const order = this._buildAfterSaleTypeListOrder(sort); + + const { count, rows } = await ctx.model.AfterSaleType.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + attributes: [ + 'id', 'type', 'name', 'warehouse_id', 'is_system', + 'is_enabled', 'sort_order', 'created_at', 'updated_at', + ], + }); + + const totalPages = Math.ceil(count / pageSize); + + return { + list: rows.map(row => this._formatAfterSaleTypeConfigRow(row)), + pagination: { + page, + pageSize, + total: count, + totalPages, + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 创建仓库自定义售后类型。 + * @param {Object} params 参数对象 + * @param {number} params.warehouseId 当前仓库ID + * @param {string} params.type 类型编码 + * @param {string} params.name 类型名称 + * @param {*} [params.sortOrder] 排序值 + * @param {*} [params.isEnabled] 是否启用(0/1) + * @return {Promise} 新创建的售后类型记录 + * @throws {Error} 参数不合法、编码重复时抛出(携带业务码) + */ + async createType(params = {}) { + const { ctx } = this; + const { warehouseId = 0, type, name, sortOrder, isEnabled } = params; + + if (!warehouseId) { + throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能创建售后类型', 400); + } + + const typeCode = this._validateAfterSaleTypeCode(type, '类型编码'); + if (typeCode.length > 20) { + throw this._createAfterSaleTypeConfigError('类型编码长度不能超过20个字符', 400); + } + const typeName = typeof name === 'string' ? name.trim() : ''; + if (!typeName) { + throw this._createAfterSaleTypeConfigError('类型名称不能为空', 400); + } + if (typeName.length > 50) { + throw this._createAfterSaleTypeConfigError('类型名称长度不能超过50个字符', 400); + } + + const sortOrderValue = this._normalizeAfterSaleTypeSortOrder(sortOrder); + const isEnabledValue = this._normalizeAfterSaleTypeEnabled(isEnabled); + + // 不能与系统级类型编码重复 + const systemType = await ctx.model.AfterSaleType.findOne({ + where: { type: typeCode, warehouse_id: null }, + attributes: [ 'id' ], + raw: true, + }); + if (systemType) { + throw this._createAfterSaleTypeConfigError('该类型编码与系统预设类型重复,不允许使用', 409); + } + + // 同仓库内唯一(唯一索引兜底) + const existType = await ctx.model.AfterSaleType.findOne({ + where: { type: typeCode, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + if (existType) { + throw this._createAfterSaleTypeConfigError('该类型编码在当前仓库已存在', 409); + } + + try { + const record = await ctx.model.AfterSaleType.create({ + warehouse_id: warehouseId, + type: typeCode, + name: typeName, + is_system: 0, + is_enabled: isEnabledValue, + sort_order: sortOrderValue, + }); + return this._formatAfterSaleTypeConfigRow(record && record.toJSON ? record.toJSON() : record); + } catch (error) { + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this._createAfterSaleTypeConfigError('该类型编码在当前仓库已存在', 409); + } + throw error; + } + } + + /** + * 更新仓库自定义售后类型(仅 name/is_enabled/sort_order 可改,type 编码不可变)。 + * @param {Object} params 参数对象 + * @param {number} params.warehouseId 当前仓库ID + * @param {number} params.id 类型主键ID + * @param {string} [params.name] 类型名称 + * @param {*} [params.isEnabled] 是否启用(0/1) + * @param {*} [params.sortOrder] 排序值 + * @return {Promise} 更新后的售后类型记录 + * @throws {Error} 记录不存在/为系统预设或参数不合法时抛出(携带业务码) + */ + async updateType(params = {}) { + const { ctx } = this; + const { warehouseId = 0, id, name, sortOrder, isEnabled } = params; + + if (!warehouseId) { + throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能修改售后类型', 400); + } + + const typeId = Number(id); + if (!Number.isFinite(typeId) || typeId <= 0) { + throw this._createAfterSaleTypeConfigError('售后类型ID不合法', 400); + } + + const record = await ctx.model.AfterSaleType.findOne({ + where: { id: typeId, warehouse_id: warehouseId, is_system: 0 }, + }); + if (!record) { + throw this._createAfterSaleTypeConfigError('售后类型不存在、无权操作或为系统预设类型', 404); + } + + const updateData = {}; + if (name !== undefined) { + const typeName = typeof name === 'string' ? name.trim() : ''; + if (!typeName) { + throw this._createAfterSaleTypeConfigError('类型名称不能为空', 400); + } + if (typeName.length > 50) { + throw this._createAfterSaleTypeConfigError('类型名称长度不能超过50个字符', 400); + } + updateData.name = typeName; + } + if (isEnabled !== undefined) { + updateData.is_enabled = this._normalizeAfterSaleTypeEnabled(isEnabled); + } + if (sortOrder !== undefined) { + updateData.sort_order = this._normalizeAfterSaleTypeSortOrder(sortOrder); + } + + if (Object.keys(updateData).length === 0) { + throw this._createAfterSaleTypeConfigError('没有需要更新的字段', 400); + } + + await record.update(updateData); + return this._formatAfterSaleTypeConfigRow(record.toJSON()); + } + + /** + * 删除仓库自定义售后类型(系统级禁止删除;存在当前仓库自定义子类型时拒绝删除)。 + * @param {Object} params 参数对象 + * @param {number} params.warehouseId 当前仓库ID + * @param {number} params.id 类型主键ID + * @return {Promise} { id, deleted: true } + * @throws {Error} 记录不存在/为系统预设或存在自定义子类型时抛出(携带业务码) + */ + async deleteType(params = {}) { + const { ctx } = this; + const { warehouseId = 0, id } = params; + + if (!warehouseId) { + throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能删除售后类型', 400); + } + + const typeId = Number(id); + if (!Number.isFinite(typeId) || typeId <= 0) { + throw this._createAfterSaleTypeConfigError('售后类型ID不合法', 400); + } + + const record = await ctx.model.AfterSaleType.findOne({ + where: { id: typeId, warehouse_id: warehouseId, is_system: 0 }, + attributes: [ 'id', 'type' ], + raw: true, + }); + if (!record) { + throw this._createAfterSaleTypeConfigError('售后类型不存在、无权操作或为系统预设类型', 404); + } + + // 删除前检查该类型下是否存在当前仓库的自定义子类型,存在则拒绝(不做级联删除,避免误删数据) + const subTypeCount = await ctx.model.AfterSaleSubType.count({ + where: { type: record.type, warehouse_id: warehouseId, is_system: 0 }, + }); + if (subTypeCount > 0) { + throw this._createAfterSaleTypeConfigError('该类型下存在当前仓库的自定义子类型,请先删除子类型', 409); + } + + await ctx.model.AfterSaleType.destroy({ + where: { id: typeId, warehouse_id: warehouseId, is_system: 0 }, + }); + return { id: typeId, deleted: true }; + } + + /** + * 售后子类型列表:系统级 + 当前仓库自定义合并,支持 type 过滤与按 type 分组返回。 + * @param {Object} params 参数对象 + * @param {number} params.warehouseId 当前仓库ID(0 表示无仓库上下文,仅返回系统级数据) + * @param {Object} [params.where] 标准化 where 条件 + * @param {Object} [params.pagination] 分页参数 {page, pageSize} + * @param {Object} [params.sort] 排序参数 {sortField, sortOrder} + * @param {boolean} [params.group=false] 是否按 type 分组返回 groups + * @return {Promise} { list: Array, pagination: Object, groups?: Array } + */ + async getSubTypeList(params = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const { + warehouseId = 0, + where = {}, + pagination = {}, + sort = {}, + group = false, + } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const scopeWhere = warehouseId + ? { [Op.or]: [{ warehouse_id: null }, { warehouse_id: warehouseId }] } + : { warehouse_id: null }; + const fieldWhere = this._buildAfterSaleSubTypeListWhere(where, Op); + const queryWhere = { ...scopeWhere, ...fieldWhere }; + + const order = this._buildAfterSaleSubTypeListOrder(sort); + const attributes = [ + 'id', 'type', 'sub_type', 'name', 'warehouse_id', 'is_system', + 'is_enabled', 'sort_order', 'created_at', 'updated_at', + ]; + + const { count, rows } = await ctx.model.AfterSaleSubType.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + attributes, + }); + + const totalPages = Math.ceil(count / pageSize); + const result = { + list: rows.map(row => this._formatAfterSaleTypeConfigRow(row)), + pagination: { + page, + pageSize, + total: count, + totalPages, + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + + // 按 type 分组:基于全量过滤结果(不受分页影响)构建分组结构 + if (group) { + const typeRows = await ctx.model.AfterSaleType.findAll({ + where: scopeWhere, + attributes: [ 'type', 'name' ], + raw: true, + }); + const typeNameMap = {}; + for (const row of typeRows) { + typeNameMap[row.type] = row.name; + } + + const allRows = await ctx.model.AfterSaleSubType.findAll({ + where: queryWhere, + order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + attributes, + }); + + const groups = []; + const groupIndexMap = new Map(); + for (const row of allRows) { + if (!groupIndexMap.has(row.type)) { + groupIndexMap.set(row.type, groups.length); + groups.push({ + type: row.type, + name: typeNameMap[row.type] || row.type, + items: [], + }); + } + groups[groupIndexMap.get(row.type)].items.push(this._formatAfterSaleTypeConfigRow(row)); + } + result.groups = groups; + } + + return result; + } + + /** + * 创建仓库自定义售后子类型。 + * @param {Object} params 参数对象 + * @param {number} params.warehouseId 当前仓库ID + * @param {string} params.type 所属类型编码(必须已存在且启用) + * @param {string} params.subType 子类型编码 + * @param {string} params.name 子类型名称 + * @param {*} [params.sortOrder] 排序值 + * @param {*} [params.isEnabled] 是否启用(0/1) + * @return {Promise} 新创建的售后子类型记录 + * @throws {Error} 参数不合法、类型不存在/停用、编码重复时抛出(携带业务码) + */ + async createSubType(params = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const { warehouseId = 0, type, subType, name, sortOrder, isEnabled } = params; + + if (!warehouseId) { + throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能创建售后子类型', 400); + } + + const typeCode = this._validateAfterSaleTypeCode(type, '类型编码'); + if (typeCode.length > 20) { + throw this._createAfterSaleTypeConfigError('类型编码长度不能超过20个字符', 400); + } + const subTypeCode = this._validateAfterSaleTypeCode(subType, '子类型编码'); + if (subTypeCode.length > 50) { + throw this._createAfterSaleTypeConfigError('子类型编码长度不能超过50个字符', 400); + } + const subTypeName = typeof name === 'string' ? name.trim() : ''; + if (!subTypeName) { + throw this._createAfterSaleTypeConfigError('子类型名称不能为空', 400); + } + if (subTypeName.length > 50) { + throw this._createAfterSaleTypeConfigError('子类型名称长度不能超过50个字符', 400); + } + + // 所属类型必须存在(系统级或当前仓库自定义)且启用 + const typeRecord = await ctx.model.AfterSaleType.findOne({ + where: { + [Op.or]: [ + { type: typeCode, warehouse_id: null }, + { type: typeCode, warehouse_id: warehouseId }, + ], + }, + attributes: [ 'id', 'is_enabled' ], + raw: true, + }); + if (!typeRecord) { + throw this._createAfterSaleTypeConfigError('售后类型不存在', 400); + } + if (Number(typeRecord.is_enabled) !== 1) { + throw this._createAfterSaleTypeConfigError('售后类型已停用,不能添加子类型', 400); + } + + // 不能与系统级同 type 下的子类型编码重复 + const systemSubType = await ctx.model.AfterSaleSubType.findOne({ + where: { type: typeCode, sub_type: subTypeCode, warehouse_id: null }, + attributes: [ 'id' ], + raw: true, + }); + if (systemSubType) { + throw this._createAfterSaleTypeConfigError('该子类型编码与系统预设重复,不允许使用', 409); + } + + // 同类型同仓库内唯一(唯一索引兜底) + const existSubType = await ctx.model.AfterSaleSubType.findOne({ + where: { type: typeCode, sub_type: subTypeCode, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + if (existSubType) { + throw this._createAfterSaleTypeConfigError('该子类型编码在当前仓库已存在', 409); + } + + const sortOrderValue = this._normalizeAfterSaleTypeSortOrder(sortOrder); + const isEnabledValue = this._normalizeAfterSaleTypeEnabled(isEnabled); + + try { + const record = await ctx.model.AfterSaleSubType.create({ + warehouse_id: warehouseId, + type: typeCode, + sub_type: subTypeCode, + name: subTypeName, + is_system: 0, + is_enabled: isEnabledValue, + sort_order: sortOrderValue, + }); + return this._formatAfterSaleTypeConfigRow(record && record.toJSON ? record.toJSON() : record); + } catch (error) { + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this._createAfterSaleTypeConfigError('该子类型编码在当前仓库已存在', 409); + } + throw error; + } + } + + /** + * 更新仓库自定义售后子类型(仅 name/is_enabled/sort_order 可改,type 与 sub_type 编码不可变)。 + * @param {Object} params 参数对象 + * @param {number} params.warehouseId 当前仓库ID + * @param {number} params.id 子类型主键ID + * @param {string} [params.name] 子类型名称 + * @param {*} [params.isEnabled] 是否启用(0/1) + * @param {*} [params.sortOrder] 排序值 + * @return {Promise} 更新后的售后子类型记录 + * @throws {Error} 记录不存在/为系统预设或参数不合法时抛出(携带业务码) + */ + async updateSubType(params = {}) { + const { ctx } = this; + const { warehouseId = 0, id, name, sortOrder, isEnabled } = params; + + if (!warehouseId) { + throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能修改售后子类型', 400); + } + + const subTypeId = Number(id); + if (!Number.isFinite(subTypeId) || subTypeId <= 0) { + throw this._createAfterSaleTypeConfigError('售后子类型ID不合法', 400); + } + + const record = await ctx.model.AfterSaleSubType.findOne({ + where: { id: subTypeId, warehouse_id: warehouseId, is_system: 0 }, + }); + if (!record) { + throw this._createAfterSaleTypeConfigError('售后子类型不存在、无权操作或为系统预设类型', 404); + } + + const updateData = {}; + if (name !== undefined) { + const subTypeName = typeof name === 'string' ? name.trim() : ''; + if (!subTypeName) { + throw this._createAfterSaleTypeConfigError('子类型名称不能为空', 400); + } + if (subTypeName.length > 50) { + throw this._createAfterSaleTypeConfigError('子类型名称长度不能超过50个字符', 400); + } + updateData.name = subTypeName; + } + if (isEnabled !== undefined) { + updateData.is_enabled = this._normalizeAfterSaleTypeEnabled(isEnabled); + } + if (sortOrder !== undefined) { + updateData.sort_order = this._normalizeAfterSaleTypeSortOrder(sortOrder); + } + + if (Object.keys(updateData).length === 0) { + throw this._createAfterSaleTypeConfigError('没有需要更新的字段', 400); + } + + await record.update(updateData); + return this._formatAfterSaleTypeConfigRow(record.toJSON()); + } + + /** + * 删除仓库自定义售后子类型(系统级禁止删除;已被售后单使用时拒绝删除)。 + * @param {Object} params 参数对象 + * @param {number} params.warehouseId 当前仓库ID + * @param {number} params.id 子类型主键ID + * @return {Promise} { id, deleted: true } + * @throws {Error} 记录不存在/为系统预设或已被售后单使用时抛出(携带业务码) + */ + async deleteSubType(params = {}) { + const { ctx } = this; + const { warehouseId = 0, id } = params; + + if (!warehouseId) { + throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能删除售后子类型', 400); + } + + const subTypeId = Number(id); + if (!Number.isFinite(subTypeId) || subTypeId <= 0) { + throw this._createAfterSaleTypeConfigError('售后子类型ID不合法', 400); + } + + const record = await ctx.model.AfterSaleSubType.findOne({ + where: { id: subTypeId, warehouse_id: warehouseId, is_system: 0 }, + attributes: [ 'id', 'type', 'sub_type' ], + raw: true, + }); + if (!record) { + throw this._createAfterSaleTypeConfigError('售后子类型不存在、无权操作或为系统预设类型', 404); + } + + // 检查 wms_after_sale 引用(命中 idx_type_subtype 索引,成本可控),被使用时拒绝删除 + const usedCount = await ctx.model.AfterSale.count({ + where: { + warehouse_id: warehouseId, + type: record.type, + sub_type: record.sub_type, + deleted_at: null, + }, + }); + if (usedCount > 0) { + throw this._createAfterSaleTypeConfigError('该子类型已被售后单使用,无法删除', 409); + } + + await ctx.model.AfterSaleSubType.destroy({ + where: { id: subTypeId, warehouse_id: warehouseId, is_system: 0 }, + }); + return { id: subTypeId, deleted: true }; + } +} + +module.exports = AfterSaleService; diff --git a/app/service/systems/apiApp.js b/app/service/systems/apiApp.js new file mode 100644 index 0000000..d0c4f54 --- /dev/null +++ b/app/service/systems/apiApp.js @@ -0,0 +1,348 @@ +'use strict'; + +const { randomBytes } = require('node:crypto'); +const { Service } = require('egg'); +const { CALLBACK_FUNCTIONS, CALLBACK_METHOD_SET } = require('../../lib/callback_functions'); + +class ApiAppService extends Service { + /** + * 生成唯一的 AppKey。 + * 格式:AK{yyyyMMddHHmmss}{random8} + * @return {string} AppKey + */ + generateAppKey() { + const now = new Date(); + const timestamp = [ + now.getFullYear(), + String(now.getMonth() + 1).padStart(2, '0'), + String(now.getDate()).padStart(2, '0'), + String(now.getHours()).padStart(2, '0'), + String(now.getMinutes()).padStart(2, '0'), + String(now.getSeconds()).padStart(2, '0'), + ].join(''); + return `AK${timestamp}${randomBytes(4).toString('hex')}`; + } + + /** + * 生成 AppSecret。 + * @return {string} 64 字符十六进制密钥。 + */ + generateAppSecret() { + return randomBytes(32).toString('hex'); + } + + /** + * 获取默认的仓库渠道接口类型 ID。 + * 查找 interface_type 中 interface_code = 'OPEN_API_WAREHOUSE' 的记录。 + * @return {Promise} 接口类型 ID,找不到时返回 0。 + */ + async getDefaultInterfaceTypeId() { + const row = await this.ctx.model.InterfaceType.findOne({ + attributes: [ 'id' ], + where: { interface_code: 'OPEN_API_WAREHOUSE', is_enabled: 1 }, + raw: true, + }); + return row ? Number(row.id) : 0; + } + + /** + * 查询当前仓库的 API 应用列表(分页)。 + * @param {Object} data 查询参数。 + * @param {number} [data.page=1] 页码。 + * @param {number} [data.pageSize=20] 每页数量。 + * @param {string} [data.app_name] 应用名称(模糊搜索)。 + * @param {number} [data.is_enabled] 启用状态。 + * @return {Promise} 分页结果。 + */ + async list(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + const page = Math.max(1, Number(data.page) || 1); + const pageSize = Math.min(100, Math.max(1, Number(data.pageSize) || 20)); + + // 仅查询仓库开放接口类型的应用,排除货主/奇门等类型 + const where = { + warehouse_id: warehouseId, + interface_type_id: await this.getDefaultInterfaceTypeId(), + }; + if (data.app_name) { + where.app_name = { [this.app.Sequelize.Op.like]: `%${String(data.app_name).trim()}%` }; + } + if (data.is_enabled !== undefined && data.is_enabled !== null && data.is_enabled !== '') { + where.is_enabled = Number(data.is_enabled); + } + + const total = await ctx.model.ApiApp.count({ where }); + const list = await ctx.model.ApiApp.findAll({ + attributes: [ + 'id', 'app_name', 'warehouse_id', 'self_app_key', 'self_app_secret', + 'self_ip_whitelist', 'callback_url', 'callback_functions', 'interface_type_id', + 'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at', + ], + where, + offset: (page - 1) * pageSize, + limit: pageSize, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + // 脱敏:只返回 secret 前 8 位 + const maskedList = list.map(item => ({ + ...item, + self_app_secret: item.self_app_secret + ? String(item.self_app_secret).substring(0, 8) + '****' + : '', + })); + + return { + list: maskedList, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasNext: page * pageSize < total, + hasPrevious: page > 1, + }, + }; + } + + /** + * 创建仓库 API 应用,自动生成 AppKey 和 AppSecret。 + * @param {Object} data 创建参数。 + * @param {string} data.app_name 应用名称(必填)。 + * @param {number|string} [data.interface_type_id] 接口类型 ID,不传则查 WH_CHANNEL。 + * @param {Array} [data.self_ip_whitelist] IP 白名单。 + * @param {string} [data.callback_url] 回调地址。 + * @param {number} [data.rate_limit=1000] 速率限制。 + * @param {string} [data.sign_method='md5'] 签名方法。 + * @return {Promise} 创建结果(含完整 secret,仅创建时返回)。 + */ + async create(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + + if (!warehouseId) { + throw new Error('无法获取当前仓库ID'); + } + + const appName = String(data.app_name || '').trim(); + if (!appName) { + throw new Error('应用名称不能为空'); + } + if (appName.length > 200) { + throw new Error('应用名称不能超过200个字符'); + } + + const interfaceTypeId = data.interface_type_id + ? Number(data.interface_type_id) + : await this.getDefaultInterfaceTypeId(); + + const appKey = this.generateAppKey(); + const appSecret = this.generateAppSecret(); + + const payload = { + app_name: appName, + warehouse_id: warehouseId, + interface_type_id: interfaceTypeId, + self_app_key: appKey, + self_app_secret: appSecret, + self_ip_whitelist: Array.isArray(data.self_ip_whitelist) ? data.self_ip_whitelist : null, + callback_url: String(data.callback_url || '').trim() || null, + callback_functions: this.normalizeCallbackFunctions(data.callback_functions), + rate_limit: Number(data.rate_limit) || 1000, + sign_method: 'md5', + is_enabled: 1, + }; + + const record = await ctx.model.ApiApp.create(payload); + + this.ctx.logger.info('[apiApp] 创建仓库API应用成功', { + warehouseId, + appId: record.id, + appName, + appKey, + }); + + return { + id: record.id, + app_name: record.app_name, + warehouse_id: record.warehouse_id, + interface_type_id: record.interface_type_id, + self_app_key: record.self_app_key, + self_app_secret: record.self_app_secret, + self_ip_whitelist: record.self_ip_whitelist, + callback_url: record.callback_url, + callback_functions: record.callback_functions, + rate_limit: record.rate_limit, + sign_method: record.sign_method, + is_enabled: record.is_enabled, + created_at: record.created_at, + updated_at: record.updated_at, + }; + } + + /** + * 校验并规范化 callback_functions: + * 仅允许代码注册表中的 method,去重去空; + * 非数组入参视为 null(不承接任何回调)。 + * @param {*} value 入参值。 + * @return {Array|null} 规范化后的 method 数组(可为空数组)。 + */ + normalizeCallbackFunctions(value) { + if (!Array.isArray(value)) return null; + const functions = [ ...new Set(value.map(item => String(item || '').trim()).filter(Boolean)) ]; + const invalid = functions.filter(method => !CALLBACK_METHOD_SET.has(method)); + if (invalid.length > 0) { + throw new Error(`存在未注册的回调方法: ${invalid.join(', ')}`); + } + return functions; + } + + /** + * 拉取出站回调 method 注册表(管理端多选列表)。 + * @return {Object} { list: [{method,name,description}], total }。 + */ + listCallbackFunctions() { + return { + list: CALLBACK_FUNCTIONS.map(item => ({ ...item })), + total: CALLBACK_FUNCTIONS.length, + }; + } + + /** + * 更新仓库 API 应用。 + * @param {number|string} id 应用 ID。 + * @param {Object} data 更新字段。 + * @param {string} [data.app_name] 应用名称。 + * @param {Array} [data.self_ip_whitelist] IP 白名单。 + * @param {string} [data.callback_url] 回调地址。 + * @param {number} [data.rate_limit] 速率限制。 + * @param {string} [data.sign_method] 签名方法。 + * @param {number} [data.is_enabled] 启用状态。 + * @return {Promise} 更新后的记录(脱敏)。 + */ + async update(id, data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + + const record = await ctx.model.ApiApp.findOne({ + where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() }, + }); + + if (!record) { + throw new Error('API应用不存在或不属于当前仓库'); + } + + const updatableFields = [ 'app_name', 'self_ip_whitelist', 'callback_url', 'callback_functions', 'rate_limit', 'sign_method', 'is_enabled' ]; + for (const field of updatableFields) { + if (data[field] !== undefined && data[field] !== null) { + if (field === 'sign_method') { + throw new Error('签名方法当前仅支持 md5,不允许修改'); + } else if (field === 'callback_functions') { + record[field] = this.normalizeCallbackFunctions(data[field]); + } else if (field === 'is_enabled') { + record[field] = Number(data[field]); + } else if (field === 'rate_limit') { + const val = Number(data[field]); + record[field] = val > 0 && val <= 100000 ? val : record[field]; + } else if (field === 'app_name') { + const val = String(data[field]).trim(); + if (!val) throw new Error('应用名称不能为空'); + if (val.length > 200) throw new Error('应用名称不能超过200个字符'); + record[field] = val; + } else { + record[field] = data[field]; + } + } + } + + await record.save(); + + this.ctx.logger.info('[apiApp] 更新仓库API应用成功', { + warehouseId, + appId: record.id, + }); + + return { + id: record.id, + app_name: record.app_name, + warehouse_id: record.warehouse_id, + interface_type_id: record.interface_type_id, + self_app_key: record.self_app_key, + self_app_secret: record.self_app_secret + ? String(record.self_app_secret).substring(0, 8) + '****' + : '', + self_ip_whitelist: record.self_ip_whitelist, + callback_url: record.callback_url, + callback_functions: record.callback_functions, + rate_limit: record.rate_limit, + sign_method: record.sign_method, + is_enabled: record.is_enabled, + created_at: record.created_at, + updated_at: record.updated_at, + }; + } + + /** + * 删除仓库 API 应用(软删除:is_enabled=0)。 + * @param {number|string} id 应用 ID。 + * @return {Promise} 无返回值。 + */ + async delete(id) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + + const record = await ctx.model.ApiApp.findOne({ + where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() }, + }); + + if (!record) { + throw new Error('API应用不存在或不属于当前仓库'); + } + + record.is_enabled = 0; + await record.save(); + + this.ctx.logger.info('[apiApp] 停用仓库API应用成功', { + warehouseId, + appId: record.id, + }); + } + + /** + * 重新生成 AppSecret。 + * @param {number|string} id 应用 ID。 + * @return {Promise} 包含新 secret 的结果(仅此次返回完整 secret)。 + */ + async regenerateSecret(id) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + + const record = await ctx.model.ApiApp.findOne({ + where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() }, + }); + + if (!record) { + throw new Error('API应用不存在或不属于当前仓库'); + } + + const newSecret = this.generateAppSecret(); + record.self_app_secret = newSecret; + await record.save(); + + this.ctx.logger.info('[apiApp] 重新生成AppSecret成功', { + warehouseId, + appId: record.id, + }); + + return { + id: record.id, + app_name: record.app_name, + self_app_key: record.self_app_key, + self_app_secret: newSecret, + }; + } +} + +module.exports = ApiAppService; diff --git a/app/service/systems/api_sign.js b/app/service/systems/api_sign.js new file mode 100644 index 0000000..21d7662 --- /dev/null +++ b/app/service/systems/api_sign.js @@ -0,0 +1,153 @@ +'use strict'; + +const Service = require('egg').Service; +const apiSignLib = require('../../lib/api_sign'); + +const API_APP_CACHE_PREFIX = 'openapi:api-app'; +const API_APP_CACHE_TTL_SECONDS = 300; +const OPENAPI_INTERFACE_TYPE_ID = 2; +const WAREHOUSE_INTERFACE_TYPE_ID = 3; + +class ApiSignService extends Service { + /** + * 构建 API 应用配置缓存键。 + * @param {string} appKey 开放接口 app_key。 + * @param {number} [interfaceTypeId] 接口类型 ID,用于区分不同入口的缓存。 + * @return {string} 缓存键。 + */ + getApiAppCacheKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) { + const prefix = interfaceTypeId === WAREHOUSE_INTERFACE_TYPE_ID + ? 'warehouse:api-app' + : API_APP_CACHE_PREFIX; + return `${prefix}:${String(appKey || '').trim()}`; + } + + /** + * 根据 app_key 查询 API 应用可用配置(带缓存)。 + * @param {string} appKey 开放接口 app_key。 + * @param {number} [interfaceTypeId=2] 接口类型 ID,2=货主级 / 3=仓库级。 + * @return {Promise} 查询结果,包含应用主键与密钥。 + */ + async getApiAppConfigByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) { + const normalizedAppKey = String(appKey || '').trim(); + if (!normalizedAppKey) { + throw new Error('appKey 不能为空'); + } + + const cacheKey = this.getApiAppCacheKey(normalizedAppKey, interfaceTypeId); + if (this.app && typeof this.app.getCacheAsync === 'function') { + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (cached && typeof cached === 'object') { + return cached; + } + } catch (error) { + this.ctx.logger.warn(`[api_sign] 读取缓存失败,降级查库: ${error.message}`); + } + } + + const row = await this.ctx.model.ApiApp.findOne({ + attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ], + where: { + self_app_key: normalizedAppKey, + interface_type_id: interfaceTypeId, + }, + raw: true, + }); + + if (!row) { + throw new Error('未找到对应的 API 应用配置'); + } + + if (Number(row.is_enabled) !== 1) { + throw new Error('API 应用已禁用'); + } + + if (!row.self_app_secret) { + throw new Error('API 应用缺少 self_app_secret 配置'); + } + + const appConfig = { + id: row.id, + appKey: row.self_app_key, + selfAppSecret: row.self_app_secret, + interfaceTypeId: Number(row.interface_type_id), + warehouseId: row.warehouse_id ? Number(row.warehouse_id) : null, + }; + + if (this.app && typeof this.app.setCacheAsync === 'function') { + this.app.setCacheAsync(cacheKey, appConfig, API_APP_CACHE_TTL_SECONDS) + .catch(error => { + this.ctx.logger.warn(`[api_sign] 写入缓存失败: ${error.message}`); + }); + } + + return appConfig; + } + + /** + * 根据 app_key 查询 API 应用密钥信息。 + * @param {string} appKey 开放接口 app_key。 + * @param {number} [interfaceTypeId=2] 接口类型 ID。 + * @return {Promise} 查询结果,包含应用主键与密钥。 + */ + async getApiAppSecretByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) { + return await this.getApiAppConfigByAppKey(appKey, interfaceTypeId); + } + + /** + * 使用 app_key 读取密钥并执行签名验证。 + * @param {Object} options 验签参数。 + * @param {string} options.appKey 开放接口 app_key。 + * @param {Object} [options.query={}] 请求 query 参数。 + * @param {*} [options.body] 请求体。 + * @param {string} options.providedSign 请求中携带的 sign。 + * @param {string[]} [options.ignoreKeys] 额外忽略的 query 字段。 + * @param {number} [options.interfaceTypeId=2] 接口类型 ID。 + * @return {Promise} 验签结果。 + */ + async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID } = {}) { + let appConfig; + try { + appConfig = await this.getApiAppSecretByAppKey(appKey, interfaceTypeId); + } catch (error) { + return { + ok: false, + code: 'APP_CONFIG_INVALID', + message: error.message, + }; + } + + const verifyResult = apiSignLib.verifyRequestSign({ + query, + body, + providedSign, + selfAppSecret: appConfig.selfAppSecret, + ignoreKeys, + }); + + if (!verifyResult.ok) { + return { + ok: false, + code: 'SIGN_INVALID', + message: verifyResult.message, + expectedSign: verifyResult.expectedSign, + providedSign: verifyResult.providedSign, + appId: appConfig.id, + }; + } + + return { + ok: true, + code: 'OK', + message: verifyResult.message, + sign: verifyResult.expectedSign, + appId: appConfig.id, + appKey: appConfig.appKey, + interfaceTypeId: appConfig.interfaceTypeId, + warehouseId: appConfig.warehouseId, + }; + } +} + +module.exports = ApiSignService; diff --git a/app/service/systems/auth/role_permission.js b/app/service/systems/auth/role_permission.js new file mode 100644 index 0000000..6a7077d --- /dev/null +++ b/app/service/systems/auth/role_permission.js @@ -0,0 +1,236 @@ +'use strict'; + +const Service = require('egg').Service; + +class RolePermissionService extends Service { + /** + * 规范化权限类型过滤参数 + * @param {string|string[]|undefined|null} type 权限类型过滤值 + * @return {null|string|string[]} 可用于 where.type 的过滤值;null 表示不加过滤 + */ + normalizeTypeFilter(type) { + if (Array.isArray(type)) { + const normalizedTypes = Array.from(new Set(type + .map(item => (typeof item === 'string' ? item.trim() : '')) + .filter(Boolean))); + return normalizedTypes.length > 0 ? normalizedTypes : null; + } + + if (typeof type === 'string') { + const normalizedType = type.trim(); + return normalizedType || null; + } + + return null; + } + + normalizePermissionSet(rawValue) { + if (rawValue === undefined || rawValue === null) { + return { allAccess: false, permissionIds: [] }; + } + + if (Array.isArray(rawValue)) { + const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item)); + if (normalizedItems.some(item => item === '*')) { + return { allAccess: true, permissionIds: [] }; + } + + const permissionIds = normalizedItems + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0) + .map(item => Math.floor(item)); + + return { + allAccess: false, + permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b), + }; + } + + if (typeof rawValue === 'number') { + return this.normalizePermissionSet([ rawValue ]); + } + + if (typeof rawValue === 'string') { + const trimmed = rawValue.trim(); + if (!trimmed) { + return { allAccess: false, permissionIds: [] }; + } + if (trimmed === '*') { + return { allAccess: true, permissionIds: [] }; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawValue) { + return this.normalizePermissionSet(parsed); + } + } catch (_) { + // ignore JSON parse failure and continue with string splitting. + } + + if (trimmed.includes(',')) { + return this.normalizePermissionSet(trimmed.split(',')); + } + + return this.normalizePermissionSet([ trimmed ]); + } + + return { allAccess: false, permissionIds: [] }; + } + + toApiPermissionIds(rawValue) { + const state = this.normalizePermissionSet(rawValue); + return state.allAccess ? [ '*' ] : state.permissionIds; + } + + serializePermissionSet(rawValue) { + const state = this.normalizePermissionSet(rawValue); + return state.allAccess ? '*' : JSON.stringify(state.permissionIds); + } + + async getPermissionIdsForRoles(roleIds, options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const normalizedRoleIds = Array.from(new Set((roleIds || []) + .map(roleId => Number(roleId)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0))); + + if (normalizedRoleIds.length === 0) { + return []; + } + + const roleRows = await ctx.model.Role.findAll({ + where: { + id: { + [Op.in]: normalizedRoleIds, + }, + ...(options.includeRoleDisabled === true ? {} : { status: 1 }), + }, + attributes: [ 'id', 'permissions' ], + raw: true, + transaction: options.transaction, + }); + + if (!roleRows || roleRows.length === 0) { + return []; + } + + const directPermissionIds = []; + let allAccess = false; + + for (const row of roleRows) { + const state = this.normalizePermissionSet(row.permissions); + if (state.allAccess) { + allAccess = true; + break; + } + + if (state.permissionIds.length > 0) { + directPermissionIds.push(...state.permissionIds); + } + } + + const permissionWhere = { + status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1, + }; + + const typeFilter = this.normalizeTypeFilter(options.type); + if (Array.isArray(typeFilter) && typeFilter.length > 0) { + permissionWhere.type = { + [Op.in]: typeFilter, + }; + } else if (typeFilter) { + permissionWhere.type = typeFilter; + } + + if (allAccess) { + const allPermissions = await ctx.model.Permission.findAll({ + where: permissionWhere, + attributes: [ 'id' ], + raw: true, + transaction: options.transaction, + }); + + return Array.from(new Set(allPermissions + .map(item => Number(item.id)) + .filter(item => Number.isFinite(item) && item > 0))); + } + + const permissionIds = Array.from(new Set(directPermissionIds + .filter(item => Number.isFinite(item) && item > 0))); + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + where: { + ...permissionWhere, + id: { + [Op.in]: permissionIds, + }, + }, + attributes: [ 'id' ], + raw: true, + transaction: options.transaction, + }); + + return Array.from(new Set(permissions + .map(item => Number(item.id)) + .filter(item => Number.isFinite(item) && item > 0))); + } + + async assignPermissions(roleId, permissionIds, options = {}) { + const { ctx } = this; + + await ctx.model.Role.update({ + permissions: this.serializePermissionSet(permissionIds), + updated_at: new Date(), + }, { + where: { id: roleId }, + transaction: options.transaction, + }); + + return true; + } + + async removePermissionsFromAllRoles(permissionIds, options = {}) { + const { ctx } = this; + const removeSet = new Set((permissionIds || []) + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0)); + + if (removeSet.size === 0) { + return 0; + } + + const roleRows = await ctx.model.Role.findAll({ + attributes: [ 'id', 'permissions' ], + transaction: options.transaction, + }); + + let updatedCount = 0; + for (const role of roleRows) { + const state = this.normalizePermissionSet(role.permissions); + if (state.allAccess || state.permissionIds.length === 0) { + continue; + } + + const nextPermissionIds = state.permissionIds.filter(permissionId => !removeSet.has(Number(permissionId))); + if (nextPermissionIds.length === state.permissionIds.length) { + continue; + } + + await role.update({ + permissions: JSON.stringify(nextPermissionIds), + updated_at: new Date(), + }, { + transaction: options.transaction, + }); + updatedCount++; + } + + return updatedCount; + } +} + +module.exports = RolePermissionService; diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 0d217ac..3e1e448 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -1,10 +1,529 @@ 'use strict'; const Service = require('egg').Service; +const crypto = require('node:crypto'); + +const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:'; +const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:'; +const WECHAT_BIND_SCAN_CACHE_PREFIX = 'user:wechat:bind:scan:'; +const WECHAT_BIND_CACHE_TTL_SECONDS = 60; +const WECHAT_BIND_SCAN_CACHE_TTL_SECONDS = 180; +const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:'; +const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000; +const WECHAT_LOGIN_CLIENT_CACHE_PREFIX = 'user:wechat:login:client:'; +const WECHAT_LOGIN_CODE_CACHE_PREFIX = 'user:wechat:login:code:'; +const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:'; +const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60; class UserService extends Service { - constructor(ctx) { - super(ctx); + /** + * 根据平台解析菜单权限类型过滤条件 + * @param {string} platform 平台标识 + * @return {{ type: object }} 菜单权限类型过滤条件 + */ + getMenuTypeWhereByPlatform(platform) { + const { Op } = this.app.Sequelize; + const normalizedPlatform = String(platform || '').trim().toLowerCase(); + const platformTypeStrategy = { + web: { + mode: 'prefix', + values: [ 'web_' ], + }, + pda: { + mode: 'prefix', + values: [ 'pda_' ], + }, + miniprogram: { + mode: 'prefix', + values: [ 'miniprogram_' ], + }, + workerstation: { + mode: 'type', + values: [ 'workerstation_pages' ], + }, + workstation: { + mode: 'type', + values: [ 'workerstation_pages' ], + }, + }; + + const strategy = platformTypeStrategy[normalizedPlatform]; + if (!strategy) { + return { + type: { + [Op.like]: `${normalizedPlatform}_%`, + }, + }; + } + + if (strategy.mode === 'prefix') { + const likeConditions = strategy.values.map(prefix => ({ [Op.like]: `${prefix}%` })); + if (likeConditions.length === 1) { + return { + type: likeConditions[0], + }; + } + return { + type: { + [Op.or]: likeConditions, + }, + }; + } + + return { + type: strategy.values.length === 1 ? strategy.values[0] : { + [Op.in]: strategy.values, + }, + }; + } + + getCurrentAccountId() { + const { ctx } = this; + const rawUserId = ctx.userId || (ctx.user && ctx.user.id); + const accountId = Number(rawUserId); + if (!Number.isFinite(accountId) || accountId <= 0) { + return null; + } + return accountId; + } + + getWechatBindCacheKey(accountId) { + return `${WECHAT_BIND_CACHE_PREFIX}${accountId}`; + } + + getWechatBindCodeCacheKey(code) { + return `${WECHAT_BIND_CODE_CACHE_PREFIX}${code}`; + } + + getWechatBindScanCacheKey(code) { + return `${WECHAT_BIND_SCAN_CACHE_PREFIX}${code}`; + } + + getWechatLoginClientCacheKey(clientCode) { + return `${WECHAT_LOGIN_CLIENT_CACHE_PREFIX}${clientCode}`; + } + + getWechatLoginCodeCacheKey(code) { + return `${WECHAT_LOGIN_CODE_CACHE_PREFIX}${code}`; + } + + getWechatLoginEventChannel(clientCode) { + return `${WECHAT_LOGIN_EVENT_CHANNEL_PREFIX}${clientCode}`; + } + + createWechatBindCodeCandidate() { + const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + let code = ''; + for (let i = 0; i < 6; i++) { + const index = crypto.randomInt(0, charset.length); + code += charset[index]; + } + return code; + } + + async createUniqueSixCode(getCacheKey, maxAttempts = 200) { + for (let attempt = 0; attempt < maxAttempts; attempt++) { + const code = this.createWechatBindCodeCandidate(); + if (!this.parseWechatBindCode(code)) { + continue; + } + + const cacheKey = getCacheKey(code); + const existsState = await this.app.getCacheAsync(cacheKey); + if (!existsState) { + return code; + } + } + + throw new Error('生成登录码失败,请稍后重试'); + } + + async createWechatBindCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatBindCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginClientCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginClientCacheKey.bind(this), maxAttempts); + } + + parseWechatBindCode(code) { + const normalized = typeof code === 'string' ? code.trim().toUpperCase() : ''; + if (!normalized) { + return null; + } + + if (!/^[A-Z0-9]{6}$/.test(normalized)) { + return null; + } + if (!/[A-Z]/.test(normalized) || !/[0-9]/.test(normalized)) { + return null; + } + + return normalized; + } + + formatBindWechatData(state, source = 'db') { + const expiresAt = Number(state.expires_at || 0); + return { + account_id: state.account_id, + code: state.code || '', + status: state.status || 'pending', + is_bound: state.status === 'bound', + updated_at: state.updated_at || new Date().toISOString(), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + scanned_at: state.scanned_at || null, + source, + ye4s_user_id: state.ye4s_user_id || null, + }; + } + + formatLoginWechatData(state, source = 'cache') { + const expiresAt = Number(state.expires_at || 0); + return { + client_code: state.client_code || '', + code: state.code || '', + status: state.status || 'pending', + updated_at: state.updated_at || new Date().toISOString(), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + source, + }; + } + + getRemainingSecondsByExpiresAt(expiresAt, fallbackTtl = WECHAT_BIND_CACHE_TTL_SECONDS) { + const ts = Number(expiresAt); + if (!Number.isFinite(ts) || ts <= 0) { + return fallbackTtl; + } + return Math.max(1, Math.ceil((ts - Date.now()) / 1000)); + } + + async setWechatBindCache(cacheKey, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { + await this.app.setCacheAsync(cacheKey, state, ttl); + } + + async setWechatBindCodeCache(code, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const codeCacheKey = this.getWechatBindCodeCacheKey(code); + await this.app.setCacheAsync(codeCacheKey, state, ttl); + } + + async setWechatBindScanCache(code, state, ttl = WECHAT_BIND_SCAN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + await this.app.setCacheAsync(scanCacheKey, state, ttl); + } + + async getWechatBindScanCache(code) { + if (!code) { + return null; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + return await this.app.getCacheAsync(scanCacheKey); + } + + async setWechatLoginClientCache(clientCode, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!clientCode) { + return; + } + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + await this.app.setCacheAsync(clientCacheKey, state, ttl); + } + + async setWechatLoginCodeCache(code, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const codeCacheKey = this.getWechatLoginCodeCacheKey(code); + await this.app.setCacheAsync(codeCacheKey, state, ttl); + } + + async findYe4sBindingByAccountId(accountId) { + const { ctx } = this; + const ye4sClient = ctx.app.mysql.get('ye4s'); + const rows = await ye4sClient.select('ye4s_user', { + where: { + wms_account_id: accountId, + }, + columns: [ 'id', 'tmp_code', 'wms_account_id' ], + orders: [[ 'id', 'desc' ]], + limit: 1, + }); + if (!rows || rows.length === 0) { + return null; + } + return rows[0]; + } + + getWechatBindEventChannel(accountId) { + return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`; + } + + getWechatLongPollTimeoutMs(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = Number(timeoutMs); + if (Number.isFinite(waitMs) && waitMs > 0) { + return Math.floor(waitMs); + } + return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; + } + + shouldUseWechatBindLongPoll(data = {}) { + return data.longPoll === true; + } + + async publishWechatBindEvent(accountId, payload = {}) { + const { app } = this; + if (!accountId) { + return; + } + + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis) { + return; + } + + const channel = this.getWechatBindEventChannel(accountId); + const eventData = { + account_id: accountId, + event_at: new Date().toISOString(), + ...payload, + }; + + try { + await cacheRedis.publish(channel, JSON.stringify(eventData)); + } catch (error) { + app.coreLogger.warn(`发布微信绑定事件失败: ${error.message}`); + } + } + + /** + * 发布微信登录事件(唤醒 user.getLoginWechatCode 打开的长轮询)。 + * + * @param {string} clientCode 客户端编码。 + * @param {object} [payload={}] 附加事件数据(如 ye4s_user_id)。 + * @return {Promise} 无返回值。 + */ + async publishWechatLoginEvent(clientCode, payload = {}) { + const { app } = this; + if (!clientCode) { + return; + } + + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis) { + return; + } + + const channel = this.getWechatLoginEventChannel(clientCode); + const eventData = { + client_code: clientCode, + event_at: new Date().toISOString(), + ...payload, + }; + + try { + await cacheRedis.publish(channel, JSON.stringify(eventData)); + } catch (error) { + app.coreLogger.warn(`发布微信登录事件失败: ${error.message}`); + } + } + + async waitForWechatBindEvent(accountId, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const { app } = this; + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis || !accountId || typeof cacheRedis.duplicate !== 'function') { + return { + timed_out: true, + reason: 'redis_not_available', + }; + } + + const channel = this.getWechatBindEventChannel(accountId); + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + const subscriber = cacheRedis.duplicate(); + + return await new Promise(resolve => { + let settled = false; + let timer = null; + + function onMessage(messageChannel, message) { + if (messageChannel !== channel) { + return; + } + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = { raw: message }; + } + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + }); + } + + function onError(error) { + app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + }); + } + + function finalize(result) { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + } + + function cleanup() { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + } + + timer = setTimeout(() => { + finalize({ + timed_out: true, + reason: 'timeout', + }); + }, waitMs); + + subscriber.on('message', onMessage); + subscriber.on('error', onError); + + Promise.resolve(subscriber.subscribe(channel)).catch(error => { + app.coreLogger.warn(`订阅微信绑定频道失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_failed', + }); + }); + }); + } + + async refreshWechatBindState(accountId, cachedState = null, options = {}) { + const now = Date.now(); + const cacheKey = this.getWechatBindCacheKey(accountId); + const forceNewCode = options.forceNewCode === true; + const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); + + if (ye4sBinding) { + const boundState = { + account_id: accountId, + status: 'bound', + code: '', + updated_at: new Date().toISOString(), + ye4s_user_id: ye4sBinding.id || null, + expires_at: null, + scanned_at: null, + }; + + await this.setWechatBindCache(cacheKey, boundState, WECHAT_BIND_CACHE_TTL_SECONDS); + + const hasChanged = !cachedState || cachedState.status !== 'bound' || Number(cachedState.ye4s_user_id || 0) !== Number(boundState.ye4s_user_id || 0); + if (hasChanged) { + await this.publishWechatBindEvent(accountId, { + status: 'bound', + code: '', + source: 'db', + }); + } + + return { + state: boundState, + source: 'db', + message: '账号已绑定微信', + }; + } + + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + let codeState = null; + if (!forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode)) { + const codeCacheKey = this.getWechatBindCodeCacheKey(cachedCode); + codeState = await this.app.getCacheAsync(codeCacheKey); + } + + const codeAccountId = Number(codeState && codeState.account_id); + const cachedExpiresAt = Number((codeState && codeState.expires_at) || (cachedState && cachedState.expires_at)); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(codeAccountId) && codeAccountId === accountId && (Number.isFinite(cachedExpiresAt) ? cachedExpiresAt > now : !!codeState); + + if (cachedCodeValid) { + const scanState = await this.getWechatBindScanCache(cachedCode); + const normalizedStatus = scanState ? 'scanned' : 'pending'; + const state = { + account_id: accountId, + status: normalizedStatus, + code: cachedCode, + updated_at: cachedState.updated_at || new Date().toISOString(), + ye4s_user_id: null, + expires_at: Number.isFinite(cachedExpiresAt) ? cachedExpiresAt : null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, + }; + return { + state, + source: 'cache', + message: normalizedStatus === 'scanned' ? '二维码已被扫码,请继续绑定' : '获取绑定码成功(缓存)', + }; + } + + const nextCode = await this.createWechatBindCode(); + const expiresAt = now + WECHAT_BIND_CACHE_TTL_SECONDS * 1000; + const pendingState = { + account_id: accountId, + status: 'pending', + code: nextCode, + updated_at: new Date().toISOString(), + ye4s_user_id: null, + expires_at: expiresAt, + scanned_at: null, + }; + + const tasks = [ + this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCodeCache(nextCode, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatBindCodeCache(cachedCode, null, 1)); + tasks.push(this.setWechatBindScanCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); + + return { + state: pendingState, + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? '长轮询超时,已刷新绑定码' : '账号未绑定,已生成绑定码', + }; } /** @@ -12,11 +531,10 @@ class UserService extends Service { * @param {string} username - 用户名/手机号/邮箱 * @param {string} password - 密码 * @param {string} loginType - 登录类型: username, phone, email, auto - * @param {string} platformCode - 平台编码(web、pda、mini等) * @return {Object} 登录结果 */ async login(username, password, loginType = 'auto') { - const { ctx, app } = this; + const { app } = this; try { // 统一的认证错误信息 @@ -29,7 +547,6 @@ class UserService extends Service { app.coreLogger.warn(`登录失败: 用户不存在 [${username}]`); throw authError; } - console.log('登录获取用户信息', user); // 2. 检查用户状态 try { this.checkUserStatus(user); @@ -48,53 +565,7 @@ class UserService extends Service { // 4. 更新最后登录时间 await this.updateLastLoginTime(user.id); - // 5. 设置设备类型(用于菜单查询) - const platformCode = ctx.header.platform || 'web'; - // 6. 获取用户完整信息 - const userInfo = await this.findById(user.id); - console.log('用户信息', userInfo); - // 7. 如果用户有角色但当前平台没有激活角色,则自动设置一个 - if (userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) { - await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode); - } - - // 8. 生成 JWT Token - const tokenPayload = { - id: user.id, - username: user.username, - real_name: user.real_name, - platform_code: platformCode, - current_role_id: userInfo.employees_id, - current_store_id: userInfo.store_id || null, - }; - - const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, { - expiresIn: app.config.jwt.expiresIn, - }); - - return { - success: true, - data: { - user: { - id: user.id, - username: user.username, - real_name: user.real_name, - phone: user.phone, - email: user.email, - status: user.status, - last_login_at: user.last_login_at, - roles: userInfo.roles, - role_id: userInfo.role_id, - menus: userInfo.menus, - permissions: userInfo.permissions, - userRole: userInfo.userRole, - realName: userInfo.realName, - }, - token, - }, - code: 200, - message: '登录成功', - }; + return this.buildLoginResult(user, { includeUser: false }); } catch (error) { app.coreLogger.error(`登录异常: ${error.message}`); @@ -108,19 +579,1020 @@ class UserService extends Service { } } + /** + * 登录码登录:使用Ye4s登录码进行登录 + * @param {string} code 登录码(WECHAT_LOGIN_CODE) + * @return {Object} 登录结果 + */ + async loginByYe4sCode(code) { + const { ctx, app } = this; + + try { + const rawCode = typeof code === 'string' ? code.trim() : ''; + if (!rawCode) { + return { + success: false, + data: null, + code: 0, + message: '缺少或无效的登录码 code', + }; + } + + const candidateSet = new Set([ rawCode ]); + try { + const decoded = Buffer.from(rawCode, 'base64').toString('utf8').trim(); + if (decoded) { + candidateSet.add(decoded); + if (decoded.startsWith('{') && decoded.endsWith('}')) { + const parsed = JSON.parse(decoded); + const possibleCode = [ parsed && parsed.uuid, parsed && parsed.tmp_code, parsed && parsed.code ] + .map(item => (typeof item === 'string' ? item.trim() : '')) + .filter(Boolean); + for (const item of possibleCode) { + candidateSet.add(item); + } + } + } + } catch (decodeErr) { + // 非 base64/JSON 登录码时忽略解码失败,继续使用原始 code。 + } + + const codeCandidates = Array.from(candidateSet).filter(item => typeof item === 'string' && item.length > 0); + if (codeCandidates.length === 0) { + return { + success: false, + data: null, + code: 0, + message: '缺少或无效的登录码 code', + }; + } + + const ye4sClient = ctx.app.mysql.get('ye4s'); + const rows = await ye4sClient.select('ye4s_user', { + where: { + tmp_code: codeCandidates, + }, + columns: [ 'id', 'tmp_code', 'wms_account_id' ], + orders: [[ 'id', 'DESC' ]], + limit: 1, + }); + + if (!rows || rows.length === 0) { + return { + success: false, + data: null, + code: 0, + message: '登录码不存在或已过期', + }; + } + + const ye4sUserId = Number(rows[0].id); + if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { + return { + success: false, + data: null, + code: 0, + message: '登录码对应用户无效', + }; + } + + return await this.loginByYe4sUserId(ye4sUserId); + } catch (error) { + app.coreLogger.error(`登录码登录异常: ${error.message}`); + return { + success: false, + data: null, + code: 0, + message: '登录失败,请稍后重试', + }; + } + } + + async waitForLoginCodeRefresh(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + await new Promise(resolve => { + setTimeout(resolve, waitMs); + }); + } + + isTransientWechatLoginError(error) { + if (!error) { + return false; + } + const code = typeof error.code === 'string' ? error.code : ''; + const message = typeof error.message === 'string' ? error.message.toLowerCase() : ''; + const transientCodes = new Set([ 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'PROTOCOL_CONNECTION_LOST', 'ECONNREFUSED' ]); + if (transientCodes.has(code)) { + return true; + } + return message.includes('econnreset') || message.includes('read econnreset') || message.includes('connection lost') || message.includes('timeout'); + } + + extractYe4sUserIdFromLoginEvent(eventData) { + if (!eventData) { + return null; + } + + if (typeof eventData === 'number' || typeof eventData === 'string') { + const id = Number(eventData); + return Number.isFinite(id) && id > 0 ? id : null; + } + + if (typeof eventData !== 'object') { + return null; + } + + const rawId = eventData.ye4s_user_id ?? eventData.ye4sUserId ?? eventData.user_id ?? eventData.userId ?? eventData.value; + const ye4sUserId = Number(rawId); + return Number.isFinite(ye4sUserId) && ye4sUserId > 0 ? ye4sUserId : null; + } + + /** + * 等待微信登录事件并解析事件中的 ye4s 用户 ID。 + * @param {string} clientCode 客户端编码 + * @param {number} timeoutMs 等待超时时间,单位为毫秒 + * @return {Promise} 事件监听结果 + */ + async waitForWechatLoginEvent(clientCode, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const { app } = this; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis || !normalizedClientCode || typeof cacheRedis.duplicate !== 'function') { + return { + timed_out: true, + reason: 'redis_not_available', + event: null, + }; + } + + const channel = this.getWechatLoginEventChannel(normalizedClientCode); + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + const subscriber = cacheRedis.duplicate(); + + return await new Promise(resolve => { + let settled = false; + let timer = null; + + const onMessage = (messageChannel, message) => { + if (messageChannel !== channel) { + return; + } + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = message; + } + const ye4sUserId = this.extractYe4sUserIdFromLoginEvent(eventData); + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + ye4s_user_id: ye4sUserId, + }); + }; + + function onError(error) { + app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + event: null, + }); + } + + function finalize(result) { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + } + + function cleanup() { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + } + + timer = setTimeout(() => { + finalize({ + timed_out: true, + reason: 'timeout', + event: null, + }); + }, waitMs); + + subscriber.on('message', onMessage); + subscriber.on('error', onError); + + Promise.resolve(subscriber.subscribe(channel)).catch(error => { + app.coreLogger.warn(`订阅微信登录频道失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_failed', + event: null, + }); + }); + }); + } + + async loginByYe4sUserId(ye4sUserId) { + const { ctx, app } = this; + + const normalizedYe4sUserId = Number(ye4sUserId); + if (!Number.isFinite(normalizedYe4sUserId) || normalizedYe4sUserId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '登录事件缺少有效的 ye4s_user_id', + }; + } + + const maxAttempts = 2; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { id: normalizedYe4sUserId }); + if (!ye4sUser) { + return { + success: false, + code: 0, + data: null, + message: 'ye4s 用户不存在', + }; + } + + const wmsAccountId = Number(ye4sUser.wms_account_id); + if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '该 ye4s 用户未绑定WMS账号', + }; + } + + const user = await ctx.model.Account.findOne({ + where: { id: wmsAccountId }, + }); + + if (!user) { + return { + success: false, + code: 0, + data: null, + message: '绑定的WMS账号不存在', + }; + } + + try { + this.checkUserStatus(user); + } catch (statusError) { + app.coreLogger.warn(`微信事件登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); + return { + success: false, + code: 0, + data: null, + message: '绑定账号状态异常', + }; + } + + await this.updateLastLoginTime(user.id); + const loginResult = await this.buildLoginResult(user, { includeUser: false }); + return loginResult; + } catch (error) { + const isTransient = this.isTransientWechatLoginError(error); + if (isTransient && attempt < maxAttempts) { + app.coreLogger.warn(`微信事件登录异常,准备重试(${attempt}/${maxAttempts}): ${error.message}`); + await this.waitForLoginCodeRefresh(200); + continue; + } + + app.coreLogger.error(`微信事件登录异常: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + } + + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + + async tryBuildWechatLoginTokenFromState(clientCode, state) { + const eventYe4sUserId = this.extractYe4sUserIdFromLoginEvent(state); + if (!Number.isFinite(Number(eventYe4sUserId)) || Number(eventYe4sUserId) <= 0) { + return null; + } + + const loginResult = await this.loginByYe4sUserId(eventYe4sUserId); + if (!loginResult || !loginResult.success || !loginResult.data || !loginResult.data.token) { + return { + success: false, + code: 0, + data: null, + message: loginResult && loginResult.message ? loginResult.message : '登录事件处理失败', + }; + } + + const cleanupCode = state && typeof state.code === 'string' ? state.code.trim().toUpperCase() : ''; + await Promise.all([ + this.setWechatLoginClientCache(clientCode, null, 1), + cleanupCode ? this.setWechatLoginCodeCache(cleanupCode, null, 1) : Promise.resolve(), + ]); + + return { + success: true, + code: 200, + data: { + client_code: clientCode, + status: 'authorized', + source: 'event', + ye4s_user_id: Number(eventYe4sUserId), + loginToken: loginResult.data.token, + }, + message: '已收到登录事件并签发登录令牌', + }; + } + + async refreshWechatLoginState(clientCode, cachedState = null, options = {}) { + const now = Date.now(); + const forceNewCode = options.forceNewCode === true; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + + if (!normalizedClientCode) { + throw new Error('无效的客户端编码格式'); + } + + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + const cachedExpiresAt = Number(cachedState && cachedState.expires_at); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(cachedExpiresAt) && cachedExpiresAt > now; + + if (cachedCodeValid) { + return { + state: { + client_code: normalizedClientCode, + code: cachedCode, + status: 'pending', + updated_at: cachedState.updated_at || new Date().toISOString(), + expires_at: cachedExpiresAt, + }, + source: 'cache', + message: `客户端编码 ${normalizedClientCode} 已命中缓存登录码`, + }; + } + + const nextCode = await this.createWechatLoginCode(); + const expiresAt = now + WECHAT_LOGIN_CACHE_TTL_SECONDS * 1000; + const loginState = { + client_code: normalizedClientCode, + code: nextCode, + status: 'pending', + updated_at: new Date().toISOString(), + expires_at: expiresAt, + }; + + const tasks = [ + this.setWechatLoginClientCache(normalizedClientCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + this.setWechatLoginCodeCache(nextCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatLoginCodeCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); + + return { + state: loginState, + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? + `客户端编码 ${normalizedClientCode} 长轮询结束,已刷新登录码` : + `客户端编码 ${normalizedClientCode} 已生成登录码`, + }; + } + + /** + * 获取微信扫码登录码 + * @param {Object} data 请求参数 + * @return {Object} 登录码结果 + */ + async getLoginWechatCode(data = {}) { + const { app } = this; + try { + const rawClientCode = typeof data.clientCode === 'string' ? data.clientCode : (typeof data.client_code === 'string' ? data.client_code : ''); + const hasInputClientCode = !!rawClientCode && rawClientCode.trim().length > 0; + + let clientCode = ''; + let shouldWaitRefresh = false; + let cachedState = null; + + if (hasInputClientCode) { + const normalizedClientCode = this.parseWechatBindCode(rawClientCode); + if (!normalizedClientCode) { + return { + success: false, + code: 0, + data: null, + message: '无效的客户端编码格式', + }; + } + + const inputClientCacheKey = this.getWechatLoginClientCacheKey(normalizedClientCode); + try { + cachedState = await this.app.getCacheAsync(inputClientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + // 传入 clientCode 但缓存不存在时,按空值处理,重新分配新的客户端编码。 + if (cachedState) { + clientCode = normalizedClientCode; + shouldWaitRefresh = true; + } else { + clientCode = await this.createWechatLoginClientCode(); + } + } else { + clientCode = await this.createWechatLoginClientCode(); + } + + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + if (!cachedState) { + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + } + + // 若外部已将 ye4s_user_id 写入 clientCode 对应缓存,直接登录并返回,不再等待长轮询。 + if (hasInputClientCode && cachedState) { + const immediateLoginResult = await this.tryBuildWechatLoginTokenFromState(clientCode, cachedState); + if (immediateLoginResult && immediateLoginResult.success) { + return immediateLoginResult; + } + if (immediateLoginResult && immediateLoginResult.success === false) { + app.coreLogger.warn(`微信登录缓存态直登失败,继续轮询: ${immediateLoginResult.message}`); + } + } + + if (shouldWaitRefresh) { + const waitResult = await this.waitForWechatLoginEvent(clientCode, this.getWechatLongPollTimeoutMs()); + const eventYe4sUserId = Number(waitResult && waitResult.ye4s_user_id); + if (!waitResult.timed_out && Number.isFinite(eventYe4sUserId) && eventYe4sUserId > 0) { + const eventState = { + ...(cachedState || {}), + ye4s_user_id: eventYe4sUserId, + }; + const loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, eventState); + if (loginResponse && loginResponse.success) { + return loginResponse; + } + app.coreLogger.warn(`微信事件登录未成功,降级为刷新登录码: ${loginResponse && loginResponse.message ? loginResponse.message : 'unknown_error'}`); + } + + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + const refreshed = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: true, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(refreshed.state, refreshed.source), + message: refreshed.message, + }; + } + + const generated = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: false, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(generated.state, generated.source), + message: generated.message, + }; + } catch (error) { + app.coreLogger.error(`获取微信登录码失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取微信登录码失败,请稍后重试', + }; + } + } + + /** + * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) + * @param {Object} data 请求参数 + * @return {Object} 绑定码结果 + */ + async getBindWechatCode(data = {}) { + const accountId = this.getCurrentAccountId(); + return await this.getBindWechatCodeByAccountId(accountId, data, { + missingAccountMessage: '未识别到登录账号,无法生成绑定码', + }); + } + + async getBindWechatCodeByAccountId(accountId, data = {}, options = {}) { + const { app } = this; + try { + const normalizedAccountId = Number(accountId); + if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: options.missingAccountMessage || '未识别到目标账号,无法生成绑定码', + }; + } + + const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); + const useLongPoll = this.shouldUseWechatBindLongPoll(data); + const waitTimeoutMs = this.getWechatLongPollTimeoutMs(); + + let cachedState = null; + try { + cachedState = await this.app.getCacheAsync(cacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); + } + + const refreshed = await this.refreshWechatBindState(normalizedAccountId, cachedState, { + forceNewCode: false, + }); + + if (refreshed.state.status === 'bound' || !useLongPoll) { + return { + success: true, + code: 200, + data: this.formatBindWechatData(refreshed.state, refreshed.source), + message: refreshed.message, + }; + } + + const waitResult = await this.waitForWechatBindEvent(normalizedAccountId, waitTimeoutMs); + try { + cachedState = await this.app.getCacheAsync(cacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); + } + + const nextState = await this.refreshWechatBindState(normalizedAccountId, cachedState, { + forceNewCode: waitResult.timed_out, + }); + + if (waitResult.timed_out) { + return { + success: true, + code: 200, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: '长轮询结束未检测到状态变化,已刷新绑定码', + }; + } + + return { + success: true, + code: 200, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: nextState.message, + }; + } catch (error) { + app.coreLogger.error(`获取微信绑定码失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取绑定码失败,请稍后重试', + }; + } + } + + /** + * 根据绑定临时码获取账号ID(供 ye4s 扫码绑定调用) + * @param {Object} data 请求参数 + * @return {Object} 账号查询结果 + */ + async getUserByTempCode(data = {}) { + const { ctx, app } = this; + try { + const loadAccountRealName = async accountId => { + const account = await ctx.model.Account.findOne({ + where: { + id: accountId, + }, + attributes: [ 'id', 'real_name' ], + raw: true, + }); + return account && account.real_name ? account.real_name : ''; + }; + + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; + if (!rawCode) { + return { + success: false, + code: 0, + data: null, + message: '缺少绑定码 code', + }; + } + + const code = this.parseWechatBindCode(rawCode); + if (!code) { + return { + success: false, + code: 0, + data: null, + message: '无效的绑定码格式', + }; + } + + const codeCacheKey = this.getWechatBindCodeCacheKey(code); + let codeState = null; + try { + codeState = await this.app.getCacheAsync(codeCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取绑定码映射缓存失败: ${cacheErr.message}`); + } + + const cachedAccountId = Number(codeState && codeState.account_id); + if (!Number.isFinite(cachedAccountId) || cachedAccountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '绑定码不存在或已过期', + }; + } + + const realName = await loadAccountRealName(cachedAccountId); + const scanState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: new Date().toISOString(), + source: 'gateway-scan', + }; + + const codeExpiresAt = Number(codeState && codeState.expires_at); + const scannedBindState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: scanState.scanned_at, + updated_at: scanState.scanned_at, + ye4s_user_id: null, + expires_at: Number.isFinite(codeExpiresAt) ? codeExpiresAt : null, + }; + const bindCacheTtl = this.getRemainingSecondsByExpiresAt(codeExpiresAt, WECHAT_BIND_CACHE_TTL_SECONDS); + + await Promise.all([ + this.setWechatBindScanCache(code, scanState, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), + this.setWechatBindCache(this.getWechatBindCacheKey(cachedAccountId), scannedBindState, bindCacheTtl), + ]); + await this.publishWechatBindEvent(cachedAccountId, { + status: 'scanned', + code, + scanned_at: scanState.scanned_at, + source: 'gateway-scan', + }); + + return { + success: true, + code: 200, + data: { + account_id: cachedAccountId, + real_name: realName, + code, + status: 'scanned', + source: 'scan-cache', + scanned_at: scanState.scanned_at, + updated_at: codeState && codeState.updated_at ? codeState.updated_at : scanState.scanned_at, + }, + message: '扫码状态已记录', + }; + } catch (error) { + app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取账号失败,请稍后重试', + }; + } + } + + /** + * 账号绑定:供 ye4s 扫码后回调,按临时码绑定到指定 ye4s_user.id + * @param {Object} data 请求参数 + * @return {Object} 绑定结果 + */ + async bindAccountByTempCode(data = {}) { + const { ctx, app } = this; + try { + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; + const rawYe4sUserId = data.ye4s_user_id ?? data.ye4sUserId; + const ye4sUserId = Number(rawYe4sUserId); + + if (!rawCode) { + return { + success: false, + code: 0, + data: null, + message: '缺少绑定码 code', + }; + } + + const code = this.parseWechatBindCode(rawCode); + if (!code) { + return { + success: false, + code: 0, + data: null, + message: '无效的绑定码格式', + }; + } + + if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '缺少有效的 ye4s_user_id', + }; + } + + const scanState = await this.getWechatBindScanCache(code); + const accountId = Number(scanState && scanState.account_id); + if (!Number.isFinite(accountId) || accountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '未检测到扫码记录或扫码状态已过期,请重新扫码', + }; + } + + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { id: ye4sUserId }); + if (!ye4sUser) { + return { + success: false, + code: 0, + data: null, + message: 'ye4s 用户不存在', + }; + } + + const updateRet = await ye4sClient.update('ye4s_user', { + id: ye4sUserId, + wms_account_id: accountId, + }); + + const boundState = { + account_id: accountId, + status: 'bound', + code: '', + updated_at: new Date().toISOString(), + ye4s_user_id: ye4sUserId, + expires_at: null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, + }; + + await Promise.all([ + this.setWechatBindCache(this.getWechatBindCacheKey(accountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCodeCache(code, null, 1), + this.setWechatBindScanCache(code, { + ...scanState, + status: 'bound', + ye4s_user_id: ye4sUserId, + bound_at: boundState.updated_at, + }, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), + ]); + + await this.publishWechatBindEvent(accountId, { + status: 'bound', + code: '', + source: 'gateway-bind', + }); + + return { + success: true, + code: 200, + data: { + account_id: accountId, + ye4s_user_id: ye4sUserId, + code, + status: 'bound', + source: 'gateway-bind', + affected_rows: Number(updateRet && updateRet.affectedRows ? updateRet.affectedRows : 0), + updated_at: boundState.updated_at, + }, + message: '绑定成功', + }; + } catch (error) { + app.coreLogger.error(`账号绑定失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '绑定失败,请稍后重试', + }; + } + } + + /** + * 解绑微信:清理 ye4s_user 中与当前账号关联的数据 + * @return {Object} 解绑结果 + */ + async unbindWechat() { + const accountId = this.getCurrentAccountId(); + return await this.unbindWechatByAccountId(accountId, { + missingAccountMessage: '未识别到登录账号,无法解绑', + }); + } + + async unbindWechatByAccountId(accountId, options = {}) { + const { ctx, app } = this; + try { + const normalizedAccountId = Number(accountId); + if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: options.missingAccountMessage || '未识别到目标账号,无法解绑', + }; + } + + const ye4sClient = ctx.app.mysql.get('ye4s'); + const bindRows = await ye4sClient.select('ye4s_user', { + where: { + wms_account_id: normalizedAccountId, + }, + columns: [ 'id', 'tmp_code', 'wms_account_id' ], + orders: [[ 'id', 'desc' ]], + limit: 500, + }); + + let affectedRows = 0; + for (const row of bindRows) { + try { + const ret = await ye4sClient.update('ye4s_user', { + id: row.id, + wms_account_id: null, + }); + affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); + } catch (err) { + const ret = await ye4sClient.update('ye4s_user', { + id: row.id, + wms_account_id: 0, + }); + affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); + } + } + + const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); + await this.setWechatBindCache(cacheKey, null, 1); + await this.publishWechatBindEvent(normalizedAccountId, { + status: 'unbound', + source: 'unbind', + }); + + return { + success: true, + code: 200, + data: { + account_id: normalizedAccountId, + status: 'unbound', + matched_rows: bindRows.length, + affected_rows: affectedRows, + updated_at: new Date().toISOString(), + }, + message: bindRows.length > 0 ? '解绑成功' : '当前账号未绑定微信', + }; + } catch (error) { + app.coreLogger.error(`解绑微信失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '解绑失败,请稍后重试', + }; + } + } + + /** + * 生成统一登录成功结构 + * @param {Object} user 用户对象 + * @param {Object} options 登录选项 + * @return {Object} 登录结果 + */ + async buildLoginResult(user, options = {}) { + const { ctx, app } = this; + const includeUser = options.includeUser !== false; + + // 设置设备类型(用于菜单查询) + const platformCode = ctx.header.platform || 'web'; + // 获取用户完整信息 + const userInfo = await this.findById(user.id); + if (!userInfo) { + throw new Error('用户信息加载失败'); + } + + // 如果用户有角色但当前平台没有激活角色,则自动设置一个 + if (userInfo && userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) { + await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode); + } + + // 生成 JWT Token + const tokenPayload = { + id: user.id, + username: user.username, + real_name: user.real_name, + platform_code: platformCode, + current_role_id: userInfo.employees_id, + current_store_id: userInfo.store_id || null, + }; + + const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, { + expiresIn: app.config.jwt.expiresIn, + }); + + const payloadData = { + token, + }; + + if (includeUser) { + payloadData.user = { + id: user.id, + username: user.username, + real_name: user.real_name, + phone: user.phone, + email: user.email, + status: user.status, + last_login_at: user.last_login_at, + roles: userInfo.roles, + role_id: userInfo.role_id, + menus: userInfo.menus, + permissions: userInfo.permissions, + userRole: userInfo.userRole, + realName: userInfo.realName, + }; + } + + return { + success: true, + data: payloadData, + code: 200, + message: '登录成功', + }; + } + /** * 切换角色(重构版) - * @param {Object} data - 切换角色数据 - * @param {number} data.roleId - 角色关联ID (account_store_role.id) - * @param {string} data.platformCode - 平台编码(web、pda、mini等) - * @return {Object} 切换结果 + * @param {Object} data 切换角色数据 + * @return {Object} 切换结果 */ async changeRole(data) { const { ctx, app } = this; const user = ctx.state.user || ctx.user; try { // 验证角色关联是否存在且有效 - const accountStoreRole = await ctx.model.AccountStoreEmployee.findOne({ + const accountStoreEmployee = await ctx.model.AccountStoreEmployee.findOne({ where: { id: data.roleId, account_id: user.id, @@ -129,12 +1601,12 @@ class UserService extends Service { include: [ { model: ctx.model.EmployeeRole, - as: 'employeeRole', + as: 'employeeRoles', }, ], }); - if (!accountStoreRole) { + if (!accountStoreEmployee) { throw new Error('角色不存在或未授权'); } @@ -147,8 +1619,13 @@ class UserService extends Service { platform_code: platformCode, }); - // 清理缓存 - await this.clearUserCache(user.id); + // 清理缓存:必须带上 platformCode + // clearUserCache(userId) 不带平台时只清 web/pda/mini/app/workerstation/workstation 这几个硬编码平台, + // 小程序(miniProgram)、微信(wx)等取值不在清单内且 Redis key 大小写敏感,会残留旧身份, + // 导致紧随其后的 findById 命中 5 分钟旧缓存,签发 token / 返回 user 时仍是切换前的角色。 + await this.clearUserCache(user.id, platformCode); + // 同步清理平台激活上下文缓存(platform_active:{accountId}:{platformCode},30 分钟 TTL) + await this.service.systems.accountPlatform.clearPlatformCache(user.id, platformCode); // 获取更新后的用户信息 const userInfo = await this.findById(user.id); @@ -159,7 +1636,7 @@ class UserService extends Service { real_name: user.real_name, platform_code: platformCode, current_role_id: userInfo.employees_id, - current_store_id: accountStoreRole.store_id || null, + current_store_id: accountStoreEmployee.store_id || null, }; const newToken = app.jwt.sign(tokenPayload, app.config.jwt.secret, { expiresIn: app.config.jwt.expiresIn, @@ -189,22 +1666,68 @@ class UserService extends Service { /** * 获取用户信息(重构版) - * @param {Object} data - 请求数据 + * @param {Object} [data={}] 入参。 + * @param {string} [data.wechat_appId] 小程序 AppID:传入时按该小程序归属仓库过滤工号列表, + * 仅保留非仓库工号(货主)与该仓库工号;未传入/查不到仓库时保持原逻辑。 * @return {Object} 用户信息 */ - async info(data) { + async info(data = {}) { const { ctx } = this; try { + // 微信登录态中间层:未绑定真实用户时返回微信层信息(不 401) + if (!ctx.userId && !ctx.user && ctx.oauth) { + const oauth = ctx.oauth; + return { + success: true, + data: { + id: Number(oauth.user_id) || 0, + is_bound: Number(oauth.user_id) > 0, + oauth_id: oauth.id, + user_id: Number(oauth.user_id) || 0, + openid: oauth.openid, + unionid: oauth.unionid || '', + nickname: oauth.nickname || '', + headimgurl: oauth.headimgurl || '', + login_time: oauth.login_time, + login_count: oauth.login_count, + }, + code: 200, + }; + } + const userId = ctx.userId || (ctx.user && ctx.user.id); const user = await this.findById(userId); + if (!user) { + return { + success: false, + data: null, + code: 401, + }; + } + + // 可选:传入 wechat_appId 时按小程序归属仓库过滤工号列表 + // (只保留非仓库工号(货主)与仅该仓库工号) + const appId = typeof data.wechat_appId === 'string' ? data.wechat_appId.trim() : ''; + if (appId) { + const wechatApp = await ctx.model.WechatApp.findOne({ + where: { appid: appId, is_enabled: 1 }, + attributes: [ 'id', 'appid', 'warehouse_id' ], + }); + const warehouseId = Number(wechatApp && wechatApp.warehouse_id); + if (wechatApp && Number.isInteger(warehouseId) && warehouseId > 0 && Array.isArray(user.employees)) { + user.employees = user.employees.filter( + employee => String(employee.role_type) !== 'warehouse' || Number(employee.store_id) === warehouseId + ); + } + } + return { success: true, data: user, code: 200, }; } catch (error) { - console.log(error); return { success: false, data: null, @@ -213,54 +1736,353 @@ class UserService extends Service { } } + /** + * 获取当前登录账号的账号级信息(仅 wms_account,不含敏感字段) + * @return {Promise} 账号信息 + */ + async getAccountInfo() { + const { ctx } = this; + const userId = this.getCurrentAccountId(); + if (!userId) { + return { + success: false, + data: null, + code: 401, + message: '未登录或登录已过期', + }; + } + + try { + const account = await ctx.model.Account.findOne({ + where: { id: userId }, + // 白名单字段,避免返回 password_hash / salt / last_login_ip 等敏感信息 + attributes: [ + 'id', 'username', 'real_name', 'phone', 'email', + 'status', 'is_custom_password', 'last_login_at', 'created_at', 'updated_at', + ], + raw: true, + }); + + if (!account) { + return { + success: false, + data: null, + code: 404, + message: '账号不存在', + }; + } + + return { + success: true, + data: account, + code: 200, + message: '获取账号信息成功', + }; + } catch (error) { + ctx.logger.error(`获取账号信息失败: ${error.message}`); + return { + success: false, + data: null, + code: 0, + message: '获取账号信息失败', + }; + } + } + + /** + * 修改当前登录账号的用户名(服务端做重名校验,排除自己) + * @param {Object} [data={}] 入参 + * @param {string} [data.username] 新用户名 + * @return {Promise} 修改结果 + */ + async updateUsername(data = {}) { + const { ctx } = this; + const userId = this.getCurrentAccountId(); + if (!userId) { + return { + success: false, + data: null, + code: 401, + message: '未登录或登录已过期', + }; + } + + const username = typeof data.username === 'string' ? data.username.trim() : ''; + if (!username) { + return { + success: false, + data: null, + code: 400, + message: 'username 不能为空', + }; + } + if (username.length < 3 || username.length > 50) { + return { + success: false, + data: null, + code: 400, + message: '用户名长度应在3-50个字符之间', + }; + } + if (!/^[a-zA-Z0-9_]+$/.test(username)) { + return { + success: false, + data: null, + code: 400, + message: '用户名只能包含字母、数字和下划线', + }; + } + + try { + const account = await ctx.model.Account.findOne({ + where: { id: userId }, + attributes: [ 'id', 'username' ], + raw: true, + }); + if (!account) { + return { + success: false, + data: null, + code: 404, + message: '账号不存在', + }; + } + if (account.username === username) { + return { + success: true, + data: { id: userId, username }, + code: 200, + message: '用户名未变更', + }; + } + + const { Op } = this.app.Sequelize; + const duplicate = await ctx.model.Account.findOne({ + where: { + username, + id: { [Op.ne]: userId }, + }, + attributes: [ 'id' ], + raw: true, + }); + if (duplicate) { + return { + success: false, + data: null, + code: 409, + message: '用户名已存在', + }; + } + + await ctx.model.Account.update({ username }, { + where: { id: userId }, + }); + // clearUserCache 默认平台清单不含 miniprogram/wx 等取值,先按当前平台补清一次 + const platformCode = ctx.header && ctx.header.platform; + if (platformCode) { + await this.clearUserCache(userId, platformCode); + } + await this.clearUserCache(userId); + + ctx.username = username; + if (ctx.user) { + ctx.user.username = username; + } + + return { + success: true, + data: { id: userId, username }, + code: 200, + message: '用户名修改成功', + }; + } catch (error) { + const isDuplicate = error && ( + error.name === 'SequelizeUniqueConstraintError' + || (error.parent && error.parent.code === 'ER_DUP_ENTRY') + ); + if (isDuplicate) { + return { + success: false, + data: null, + code: 409, + message: '用户名已存在', + }; + } + ctx.logger.error(`修改用户名失败: ${error.message}`); + return { + success: false, + data: null, + code: 0, + message: '修改用户名失败', + }; + } + } + + /** + * 修改当前登录账号的密码;首次自定义密码(is_custom_password=0)无需旧密码。 + * @param {Object} [data={}] 入参 + * @param {string} [data.old_password] 旧密码(is_custom_password=1 时必填) + * @param {string} [data.new_password] 新密码 + * @return {Promise} 修改结果 + */ + async changePassword(data = {}) { + const { ctx } = this; + const userId = this.getCurrentAccountId(); + if (!userId) { + return { + success: false, + data: null, + code: 401, + message: '未登录或登录已过期', + }; + } + + const rawOldPassword = data.old_password !== undefined ? data.old_password : data.oldPassword; + const rawNewPassword = data.new_password !== undefined ? data.new_password : data.newPassword; + const oldPassword = typeof rawOldPassword === 'string' ? rawOldPassword : ''; + const newPassword = typeof rawNewPassword === 'string' ? rawNewPassword.trim() : ''; + + if (!newPassword) { + return { + success: false, + data: null, + code: 400, + message: '新密码不能为空', + }; + } + if (newPassword.length > 64) { + return { + success: false, + data: null, + code: 400, + message: '新密码长度不能超过64个字符', + }; + } + + try { + const account = await ctx.model.Account.findOne({ + where: { id: userId }, + attributes: [ 'id', 'password_hash', 'salt', 'is_custom_password' ], + raw: true, + }); + if (!account) { + return { + success: false, + data: null, + code: 404, + message: '账号不存在', + }; + } + + if (Number(account.is_custom_password) === 1) { + if (!oldPassword) { + return { + success: false, + data: null, + code: 400, + message: '请输入旧密码', + }; + } + try { + await this.verifyPassword(oldPassword, account.password_hash, account.salt); + } catch (error) { + return { + success: false, + data: null, + code: 400, + message: '旧密码错误', + }; + } + } + + const salt = this.generateSalt(); + const passwordHash = await this.encryptPassword(newPassword, salt); + await ctx.model.Account.update({ + password_hash: passwordHash, + salt, + is_custom_password: 1, + }, { + where: { id: userId }, + }); + await this.clearUserCache(userId); + + return { + success: true, + data: { is_custom_password: 1 }, + code: 200, + message: '密码修改成功', + }; + } catch (error) { + ctx.logger.error(`修改密码失败: ${error.message}`); + return { + success: false, + data: null, + code: 0, + message: '修改密码失败', + }; + } + } + /** * 查找用户所有的角色以及对应的主体(重构版) - * @param {number} userId - 用户ID - * @param {string} platformCode - 平台编码 - * @return {Promise} + * @param {number} userId 用户ID + * @return {Promise} 角色列表 */ async getRoles(userId) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; - const project = ctx.header.project; + const project = ctx.header.project || 'all'; try { - // 获取用户的所有角色关联 - const store_where = { - status: 1, - }; - if (project != 'all') { - store_where.project = project; - } - console.log('store_where', store_where, project, platformCode, ctx.header); - const accountStoreEmployees = await ctx.model.AccountStoreEmployee.findAll({ - where: { - account_id: userId, + const loadAccountStoreEmployees = async projectFilter => { + const store_where = { status: 1, - }, - include: [ - { - model: ctx.model.EmployeeRole, - as: 'employeeRole', - attributes: [ 'id', 'role_id' ], + }; + if (projectFilter && projectFilter !== 'all') { + store_where.project = projectFilter; + } + return ctx.model.AccountStoreEmployee.findAll({ + where: { + account_id: userId, + status: 1, }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'company_name', 'project', 'auth_end' ], - where: store_where, - }, - ], - order: [[ 'created_at', 'DESC' ]], - }); - if (!accountStoreEmployees) { - throw ('没有符合的角色'); + include: [ + { + model: ctx.model.EmployeeRole, + as: 'employeeRoles', + attributes: [ 'id', 'role_id' ], + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'auth_end' ], + where: store_where, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + }; + + // 先按请求 project 过滤;查不到时降级到 all,便于补齐平台激活记录。 + let accountStoreEmployees = await loadAccountStoreEmployees(project); + if ((!accountStoreEmployees || accountStoreEmployees.length === 0) && project && project !== 'all') { + accountStoreEmployees = await loadAccountStoreEmployees('all'); + } + + if (!accountStoreEmployees || accountStoreEmployees.length === 0) { + return { + Employees: [], + activeEmployeeId: null, + menus: [], + permissions: [], + userRole: '', + realName: null, + }; } - console.log('accountStoreEmployees>>>>>', accountStoreEmployees); // 获取当前平台的激活角色 let activeEmployeeId = null; - let employee_id = null; let realName = null; let userRole = ''; + let currentPlatformEmployeeId = null; const platformActive = await ctx.model.AccountPlatformActive.findOne({ where: { @@ -270,14 +2092,14 @@ class UserService extends Service { attributes: [ 'account_id', 'employee_id', 'platform_code' ], }); if (platformActive) { - employee_id = platformActive.employee_id; + currentPlatformEmployeeId = platformActive.employee_id; } // 转换数据格式 const Employees = accountStoreEmployees.map(item => ({ id: item.id, store_id: item.store_id, store_name: item.store.company_name, - is_primary: platformActive && platformActive.employee_id === item.id ? 1 : 0, + is_primary: currentPlatformEmployeeId === item.id ? 1 : 0, real_name: item.real_name, auth_end: item.store.auth_end, role_type: item.store.project, @@ -285,10 +2107,10 @@ class UserService extends Service { // 确定当前激活角色 for (const Employee of Employees) { - if (Employee.is_primary == 1) { + if (Employee.is_primary === 1) { activeEmployeeId = Employee.id; realName = Employee.real_name; - userRole = Employee.role_type == 1 ? 'warehouse' : 'customer'; + userRole = Employee.role_type === 1 ? 'warehouse' : 'customer'; break; } } @@ -297,7 +2119,7 @@ class UserService extends Service { if (!activeEmployeeId && Employees.length > 0) { activeEmployeeId = Employees[0].id; realName = Employees[0].real_name; - userRole = Employees[0].role_type == 1 ? 'warehouse' : 'customer'; + userRole = Employees[0].role_type === 1 ? 'warehouse' : 'customer'; // 设置为激活角色 if (Employees[0].id) { @@ -308,28 +2130,31 @@ class UserService extends Service { // 获取菜单和权限 const menus = await this.getMenus(activeEmployeeId); - console.log('获取菜单', activeEmployeeId, menus); const permissions = await this.getPermissions(activeEmployeeId); return { Employees, activeEmployeeId, menus, permissions, userRole, realName }; } catch (error) { console.error('获取用户角色失败:', error); - return [[], null, [], [], '', null ]; + return { + Employees: [], + activeEmployeeId: null, + menus: [], + permissions: [], + userRole: '', + realName: null, + }; } } /** * 根据ID查找用户(重构版) - * @param {number} userId - 用户ID - * @param {string} platformCode - 平台编码 - * @param useCache - * @return {Promise} + * @param {number} userId 用户ID + * @param {boolean} useCache 是否使用缓存 + * @return {Promise} 用户信息 */ async findById(userId, useCache = true) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; - const project = ctx.header.project; - console.log(`调用${ctx.query_count}次,平台为${platformCode}`); ctx.query_count++; try { // 生成缓存key @@ -340,7 +2165,6 @@ class UserService extends Service { try { const cachedUser = await this.app.getCacheAsync(cacheKey); if (cachedUser) { - console.log('用户信息缓存命中:', userId); return cachedUser; } } catch (cacheError) { @@ -364,12 +2188,22 @@ class UserService extends Service { } // 3. 获取角色信息(这个方法内部也有缓存逻辑) - const { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId); - console.log('activeEmployeeId>>>>>>>>', activeEmployeeId); + let { Employees, activeEmployeeId, menus, permissions, userRole } = await this.getRoles(userId); + + // pda 场景若缺少激活角色,优先补一条当前平台激活记录,避免直接报错。 + if (platformCode === 'pda' && !activeEmployeeId && Employees.length > 0) { + const fallbackEmployee = Employees[0]; + await this.ensurePlatformActiveRole(userId, fallbackEmployee.id, platformCode); + activeEmployeeId = fallbackEmployee.id; + userRole = fallbackEmployee.role_type === 1 ? 'warehouse' : 'customer'; + menus = await this.getMenus(activeEmployeeId); + permissions = await this.getPermissions(activeEmployeeId); + } // 4. 获取当前角色对应的仓库ID let storeId = null; let storeName = null; let storeCode = null; + let storeType = null; let roleName = null; let auth_end = null; let employees_name = null; @@ -379,6 +2213,7 @@ class UserService extends Service { storeId = currentRole.store_id; storeName = currentRole.store_name; storeCode = currentRole.store_code; + storeType = currentRole.role_type; roleName = currentRole.role_name; employees_name = currentRole.real_name; auth_end = currentRole.auth_end; @@ -386,8 +2221,8 @@ class UserService extends Service { } const avatar = await this.getAvatarByEmployeeId(activeEmployeeId); - if (platformCode == 'pda' && !activeEmployeeId) { - throw ('无登录权限'); + if (platformCode === 'pda' && !activeEmployeeId) { + ctx.logger.warn(`pda 平台未找到可激活角色,accountId=${userId},将以空角色上下文返回`); } // 5. 组合用户信息 const userInfo = { @@ -402,6 +2237,7 @@ class UserService extends Service { store_id: storeId, store_name: storeName, store_code: storeCode, + store_type: storeType, menus, permissions, userRole, @@ -411,11 +2247,9 @@ class UserService extends Service { }; // 6. 设置缓存 if (useCache) { - console.log('设置用户缓存', userInfo); await this.setUserCache(cacheKey, userInfo, 300); // 缓存5分钟 } - console.log('用户信息数据库查询:', userId); return userInfo; } catch (error) { @@ -424,17 +2258,18 @@ class UserService extends Service { } } /** - * 设置用户缓存 - * @param cacheKey - * @param userInfo - * @param ttl - * @private - */ + * 设置用户缓存 + * @param {string} cacheKey 缓存键 + * @param {Object|null} userInfo 用户信息 + * @param {number} ttl 缓存时间 + * @private + */ async setUserCache(cacheKey, userInfo, ttl = 300) { try { // 移除缓存标识字段 if (userInfo) { - const { cached_at, ...cacheData } = userInfo; + const cacheData = { ...userInfo }; + delete cacheData.cached_at; await this.app.setCacheAsync(cacheKey, cacheData, ttl); } else { await this.app.setCacheAsync(cacheKey, null, ttl); @@ -444,8 +2279,7 @@ class UserService extends Service { } } async getAvatarByEmployeeId(employeeId) { - const { ctx, app } = this; - const { Op } = app.Sequelize; + const { ctx } = this; let url = ''; const image = await ctx.model.FileReference.findOne({ where: { @@ -466,8 +2300,8 @@ class UserService extends Service { } /** * 清除用户缓存 - * @param userId - * @param platformCode + * @param {number} userId 用户ID + * @param {string|null} platformCode 平台编码 */ async clearUserCache(userId, platformCode = null) { try { @@ -477,7 +2311,7 @@ class UserService extends Service { await this.app.setCacheAsync(cacheKey, null, 1); } else { // 清除用户所有平台的缓存 - const platforms = [ 'web', 'pda', 'mini', 'app' ]; + const platforms = [ 'web', 'pda', 'mini', 'app', 'workerstation', 'workstation' ]; for (const platform of platforms) { const cacheKey = `user:info:${userId}:${platform}`; await this.app.setCacheAsync(cacheKey, null, 1); @@ -487,7 +2321,6 @@ class UserService extends Service { // 同时清除相关的缓存 await this.clearRelatedCache(userId); - console.log('用户缓存已清除:', userId); return true; } catch (error) { console.warn('清除用户缓存失败:', error.message); @@ -496,7 +2329,7 @@ class UserService extends Service { } /** * 清除用户相关缓存 - * @param userId + * @param {number} userId 用户ID * @private */ async clearRelatedCache(userId) { @@ -533,9 +2366,8 @@ class UserService extends Service { } /** * 获取权限列表(重构版) - * @param {number} roleId - 角色ID - * @param activeEmployeeId - * @return {Promise} + * @param {number} activeEmployeeId 员工ID + * @return {Promise} 权限列表 */ async getPermissions(activeEmployeeId) { const { ctx, app } = this; @@ -546,41 +2378,49 @@ class UserService extends Service { } try { - // 1. 获取员工的角色 + // 1. 获取员工绑定且启用的角色 const roles = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], where: { employee_id: activeEmployeeId, }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], raw: true, // 获取纯数据对象 }); - console.log('员工绑定的角色', roles); if (!roles || roles.length === 0) { return []; } - const roleIds = roles.map(item => item.role_id); - - // 2. 获取角色的权限 - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { - role_id: { - [Op.in]: roleIds, - }, - }, - raw: true, - }); - if (!rolePermissions || rolePermissions.length === 0) { + const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ]; + if (roleIds.length === 0) { return []; } - const permissionIds = rolePermissions.map(item => item.permission_id); + // 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表) + const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, + }); + if (permissionIds.length === 0) { + return []; + } const permissions = await ctx.model.Permission.findAll({ where: { id: { [Op.in]: permissionIds, }, - // 修正 like 查询 + status: 1, + // 页面权限(`*_pages`)仅用于菜单路由,不应出现在接口权限集合中,包含 workerstation_pages。 type: { [ctx.app.Sequelize.Op.notLike]: '%_pages', }, @@ -590,7 +2430,6 @@ class UserService extends Service { [ 'sort', 'ASC' ], ], }); - console.log('permissions列表', permissions); if (!permissions) { return []; } @@ -602,56 +2441,65 @@ class UserService extends Service { } } - + /** + * 获取当前员工菜单 + * @param {number} activeEmployeeId 员工ID + * @return {Promise} 菜单路由列表 + */ async getMenus(activeEmployeeId) { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; - console.log('获取员工菜单员工id:', activeEmployeeId); if (!ctx.header.platform || !activeEmployeeId) { return []; } try { - // 1. 获取员工的角色 + // 1. 获取员工绑定且启用的角色 const roles = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], where: { employee_id: activeEmployeeId, }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], raw: true, // 获取纯数据对象 }); - console.log('员工绑定的角色', roles); if (!roles || roles.length === 0) { return []; } - const roleIds = roles.map(item => item.role_id); - - // 2. 获取角色的权限 - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { - role_id: { - [Op.in]: roleIds, - }, - }, - raw: true, - }); - if (!rolePermissions || rolePermissions.length === 0) { + const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ]; + if (roleIds.length === 0) { return []; } - const permissionIds = rolePermissions.map(item => item.permission_id); + // 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表) + const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, + }); + if (permissionIds.length === 0) { + return []; + } - // 3. 获取权限对应的菜单(根据设备筛选) + // 3. 获取权限对应的菜单(根据平台权限类型策略筛选) + const menuTypeWhere = this.getMenuTypeWhereByPlatform(ctx.header.platform); const permissions = await ctx.model.Permission.findAll({ where: { id: { [Op.in]: permissionIds, }, - // 修正 like 查询 - type: { - [Op.like]: `${ctx.header.platform}_%`, - }, + status: 1, + ...menuTypeWhere, }, order: [ [ 'sort', 'ASC' ], @@ -669,7 +2517,7 @@ class UserService extends Service { /** * 转换权限为路由格式(保持不变) - * @param data + * @param {Array} data 权限列表 */ async convertToRoutes(data) { const map = new Map(); @@ -697,7 +2545,7 @@ class UserService extends Service { // 构建树形结构 data.forEach(item => { const node = map.get(item.id); - if (item.parent_id === 0) { + if (!item.parent_id) { roots.push(node); } else { const parent = map.get(item.parent_id); @@ -727,7 +2575,9 @@ class UserService extends Service { // 移除辅助字段 const cleanNode = node => { - const { id, sort, ...rest } = node; + const rest = { ...node }; + delete rest.id; + delete rest.sort; if (rest.children && rest.children.length > 0) { rest.children = rest.children.map(child => cleanNode(child)); } @@ -739,19 +2589,17 @@ class UserService extends Service { /** * 根据标识符查找用户(已重构) - * @param identifier - * @param type - * @param useCache + * @param {string} identifier 标识符 + * @param {string} type 查找类型 + * @return {Promise} 用户对象 */ - async findUserByIdentifier(identifier, type = 'auto', useCache = true) { - const { ctx, app } = this; + async findUserByIdentifier(identifier, type = 'auto') { + const { ctx } = this; let user; if (type === 'auto') { // 自动判断类型 - const Op = app.Sequelize.Op; - if (/^1[3-9]\d{9}$/.test(identifier)) { // 手机号格式 user = await ctx.model.Account.findOne({ @@ -799,7 +2647,7 @@ class UserService extends Service { /** * 检查用户状态(保持不变) - * @param user + * @param {Object} user 用户对象 */ checkUserStatus(user) { if (user.status === 0) { @@ -815,9 +2663,9 @@ class UserService extends Service { /** * 验证密码(重构版) - * @param inputPassword - * @param storedHash - * @param salt + * @param {string} inputPassword 输入密码 + * @param {string} storedHash 存储哈希 + * @param {string} salt 密码盐 */ async verifyPassword(inputPassword, storedHash, salt) { const crypto = require('crypto'); @@ -833,8 +2681,8 @@ class UserService extends Service { /** * 加密密码(保持不变) - * @param password - * @param salt + * @param {string} password 密码 + * @param {string} salt 密码盐 */ async encryptPassword(password, salt) { const crypto = require('crypto'); @@ -853,11 +2701,10 @@ class UserService extends Service { /** * 更新最后登录时间(重构版) - * @param userId + * @param {number} userId 用户ID */ async updateLastLoginTime(userId) { const { ctx } = this; - console.log('登录上下文', ctx.request.header['x-real-ip']); await ctx.model.Account.update({ last_login_at: new Date(), last_login_ip: ctx.request.header['x-real-ip'], @@ -869,9 +2716,9 @@ class UserService extends Service { /** * 确保平台激活角色存在 - * @param accountId - * @param accountStoreRoleId - * @param platformCode + * @param {number} accountId 账号ID + * @param {number} accountStoreRoleId 角色关联ID + * @param {string} platformCode 平台编码 * @private */ async ensurePlatformActiveRole(accountId, accountStoreRoleId, platformCode) { @@ -888,13 +2735,13 @@ class UserService extends Service { } } - /** * 用户注册(重构版) - * @param userInfo + * @param {Object} userInfo 用户信息 + * @param {Object|null} transaction 可选事务对象,传入时 Account.create 将在事务内执行 */ - async register(userInfo) { - const { ctx, app } = this; + async register(userInfo, transaction = null) { + const { ctx } = this; // 检查用户名是否已存在 const existingUser = await this.findUserByIdentifier(userInfo.username, 'username'); @@ -916,7 +2763,7 @@ class UserService extends Service { real_name: userInfo.real_name || '', status: 1, salt, - }); + }, transaction ? { transaction } : {}); return { userId: user.id, diff --git a/app/service/systems/camera.js b/app/service/systems/camera.js new file mode 100644 index 0000000..120705f --- /dev/null +++ b/app/service/systems/camera.js @@ -0,0 +1,365 @@ +'use strict'; + +const Service = require('egg').Service; + +class CameraService extends Service { + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = ctx.user.store_id; + const { pagination = {}, where = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = { warehouse_id: warehouseId }; + if (where.server_id) queryWhere.server_id = parseInt(where.server_id); + if (where.custom_name) queryWhere.custom_name = { [Op.like]: `%${where.custom_name}%` }; + if (where.status !== undefined && where.status !== null && where.status !== '') { + queryWhere.status = parseInt(where.status); + } + + const { count, rows } = await ctx.model.Camera.findAndCountAll({ + where: queryWhere, + include: [{ + model: ctx.model.CameraServer, + as: 'server', + attributes: [ 'id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status' ], + required: false, + }], + order: [[ 'created_at', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + return { list: rows, pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize), hasPrevious: page > 1, hasNext: page * pageSize < count } }; + } + + async detail(id) { + const { ctx } = this; + const record = await ctx.model.Camera.findOne({ + where: { id, warehouse_id: ctx.user.store_id }, + include: [{ + model: ctx.model.CameraServer, + as: 'server', + attributes: [ 'id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status' ], + required: false, + }], + }); + if (!record) throw new Error('摄像头不存在或无权访问'); + return record; + } + + async create(data) { + const { ctx } = this; + if (!data.server_id) throw new Error('所属服务器ID不能为空'); + if (data.channel_id === undefined || data.channel_id === null) throw new Error('通道编号不能为空'); + if (data.custom_name !== undefined && data.custom_name !== null && String(data.custom_name).trim() === '') { + throw new Error('自定义名称不能为空'); + } + return await ctx.model.Camera.create({ + warehouse_id: ctx.user.store_id, + server_id: parseInt(data.server_id), + channel_id: parseInt(data.channel_id), + channel_name: data.channel_name || null, + ip: data.ip || null, + port: data.port !== undefined && data.port !== null ? parseInt(data.port) : null, + model: data.model || null, + serial_number: data.serial_number || null, + stream_type: data.stream_type || null, + username: data.username || null, + password: data.password || null, + custom_name: data.custom_name || null, + status: data.status !== undefined ? parseInt(data.status) : 1, + remark: data.remark || null, + }); + } + + async update(id, data) { + const { ctx } = this; + const record = await ctx.model.Camera.findOne({ where: { id, warehouse_id: ctx.user.store_id } }); + if (!record) throw new Error('摄像头不存在或无权操作'); + + const fields = {}; + if (data.server_id !== undefined) fields.server_id = parseInt(data.server_id); + if (data.channel_id !== undefined) fields.channel_id = parseInt(data.channel_id); + if (data.channel_name !== undefined) fields.channel_name = data.channel_name; + if (data.ip !== undefined) fields.ip = data.ip; + if (data.port !== undefined) fields.port = data.port !== null ? parseInt(data.port) : null; + if (data.model !== undefined) fields.model = data.model; + if (data.serial_number !== undefined) fields.serial_number = data.serial_number; + if (data.stream_type !== undefined) fields.stream_type = data.stream_type; + if (data.username !== undefined) fields.username = data.username; + if (data.password !== undefined) fields.password = data.password; + if (data.custom_name !== undefined) { + if (data.custom_name !== null && String(data.custom_name).trim() === '') { + throw new Error('自定义名称不能为空'); + } + fields.custom_name = data.custom_name; + } + if (data.status !== undefined) fields.status = parseInt(data.status); + if (data.remark !== undefined) fields.remark = data.remark; + if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段'); + + await record.update(fields); + return record; + } + + /** + * 设置摄像头 OSD 文字叠加 + * @param {Object} data - 配置选项 + * @param {number} data.id - 摄像头ID + * @param {string} data.text - OSD 叠加文字 + * @param {number} [data.x] - X 坐标(-1 到 1,默认 -0.9) + * @param {number} [data.y] - Y 坐标(-1 到 1,默认 0.8) + * @return {Promise} 打印服务响应 + */ + async setOsd(data) { + const { ctx } = this; + const { id, text, x, y } = data || {}; + const warehouseId = ctx.user.store_id; + + if (!id) throw new Error('摄像头ID不能为空'); + if (!text) throw new Error('OSD叠加文字不能为空'); + + // 查询摄像头及关联服务器 + const camera = await ctx.model.Camera.findOne({ + where: { id: parseInt(id), warehouse_id: warehouseId }, + include: [{ + model: ctx.model.CameraServer, + as: 'server', + attributes: [ 'id', 'name', 'username', 'password', 'public_ip', 'internal_ip' ], + required: false, + }], + }); + if (!camera) throw new Error('摄像头不存在或无权操作'); + + const OsdClient = require('../../lib/osd_client'); + const osdClient = new OsdClient(ctx); + + const result = await osdClient.setOsd({ + camera, + warehouseId, + text, + x, + y, + }); + + if (result.error) { + throw new Error(`打印服务请求失败: ${result.error}`); + } + if (!result.response || result.response.status !== 200) { + const status = result.response ? result.response.status : '无响应'; + const resData = result.response && result.response.data; + const msg = (resData && resData.message) || (resData && typeof resData === 'string' ? resData : '') || '未知错误'; + throw new Error(`打印服务返回异常(${status}): ${msg}`); + } + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + osd_text: text, + position: { x: result.request.x, y: result.request.y }, + print_service_response: result.response, + }; + } + + /** + * 查询本仓库摄像头(云台控制复用,带录像服务器认证信息兜底) + * @param {number|string} id - 摄像头ID + * @param {number} warehouseId - 仓库ID + * @return {Promise} 摄像头记录 + */ + async _findCameraForControl(id, warehouseId) { + const { ctx } = this; + const camera = await ctx.model.Camera.findOne({ + where: { id: parseInt(id), warehouse_id: warehouseId }, + include: [{ + model: ctx.model.CameraServer, + as: 'server', + attributes: [ 'id', 'name', 'username', 'password', 'public_ip', 'internal_ip' ], + required: false, + }], + }); + if (!camera) throw new Error('摄像头不存在或无权操作'); + return camera; + } + + /** + * 校验打印服务响应,失败时抛出业务错误(与 setOsd 同口径) + * @param {Object} result - 打印服务调用结果 + * @return {Object} 原始结果 + */ + _assertPtzSuccess(result) { + if (!result) throw new Error('打印服务无响应'); + if (result.error) { + throw new Error(`打印服务请求失败: ${result.error}`); + } + if (!result.response || result.response.status < 200 || result.response.status >= 300) { + const status = result.response ? result.response.status : '无响应'; + const resData = result.response && result.response.data; + const msg = (resData && resData.message) || (resData && typeof resData === 'string' ? resData : '') || '未知错误'; + throw new Error(`打印服务返回异常(${status}): ${msg}`); + } + return result; + } + + /** + * 云台方向控制(按下):按指定方向转动摄像头,需配对调用 ptzStop 停止 + * @param {Object} data - 参数 + * @param {number} data.id - 摄像头ID(必填) + * @param {string} data.action - 云台方向(8 个位置,必填) + * @param {number} [data.speed] - 云台转速(1-7,默认 4) + * @return {Promise} 下发结果 + */ + async ptzControl(data) { + const { ctx } = this; + const { id, action, speed } = data || {}; + const warehouseId = ctx.user.store_id; + if (!id) throw new Error('摄像头ID不能为空'); + + const PtzClient = require('../../lib/ptz_client'); + const normalizedAction = PtzClient.normalizeAction(action); + const normalizedSpeed = PtzClient.normalizeSpeed(speed); + + const camera = await this._findCameraForControl(id, warehouseId); + const ptzClient = new PtzClient(ctx); + const result = await ptzClient.control({ + camera, + warehouseId, + action: normalizedAction, + speed: normalizedSpeed, + }); + this._assertPtzSuccess(result); + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + action: normalizedAction, + speed: normalizedSpeed, + print_service_response: result.response, + }; + } + + /** + * 云台停止(松手):停止转动,action 必须与按下时一致 + * @param {Object} data - 参数 + * @param {number} data.id - 摄像头ID(必填) + * @param {string} data.action - 云台方向(必须与按下时一致,必填) + * @return {Promise} 下发结果 + */ + async ptzStop(data) { + const { ctx } = this; + const { id, action } = data || {}; + const warehouseId = ctx.user.store_id; + if (!id) throw new Error('摄像头ID不能为空'); + + const PtzClient = require('../../lib/ptz_client'); + const normalizedAction = PtzClient.normalizeAction(action); + + const camera = await this._findCameraForControl(id, warehouseId); + const ptzClient = new PtzClient(ctx); + const result = await ptzClient.stop({ + camera, + warehouseId, + action: normalizedAction, + }); + this._assertPtzSuccess(result); + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + action: normalizedAction, + print_service_response: result.response, + }; + } + + /** + * 云台预置点跳转(一次调用即可,无需 stop) + * @param {Object} data - 参数 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.presetId - 预置点编号(1-256,必填) + * @return {Promise} 下发结果 + */ + async ptzPresetGoto(data) { + const { ctx } = this; + const { id, presetId } = data || {}; + const warehouseId = ctx.user.store_id; + if (!id) throw new Error('摄像头ID不能为空'); + + const PtzClient = require('../../lib/ptz_client'); + const normalizedPresetId = PtzClient.normalizePresetId(presetId); + + const camera = await this._findCameraForControl(id, warehouseId); + const ptzClient = new PtzClient(ctx); + const result = await ptzClient.presetGoto({ + camera, + warehouseId, + presetId: normalizedPresetId, + }); + this._assertPtzSuccess(result); + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + preset_id: normalizedPresetId, + print_service_response: result.response, + }; + } + + /** + * 云台预置点设置:把摄像头当前机位保存为指定预置点(一次调用即可) + * @param {Object} data - 参数 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.presetId - 预置点编号(1-256,必填) + * @return {Promise} 下发结果 + */ + async ptzPresetSet(data) { + const { ctx } = this; + const { id, presetId } = data || {}; + const warehouseId = ctx.user.store_id; + if (!id) throw new Error('摄像头ID不能为空'); + + const PtzClient = require('../../lib/ptz_client'); + const normalizedPresetId = PtzClient.normalizePresetId(presetId); + + const camera = await this._findCameraForControl(id, warehouseId); + const ptzClient = new PtzClient(ctx); + const result = await ptzClient.presetSet({ + camera, + warehouseId, + presetId: normalizedPresetId, + }); + this._assertPtzSuccess(result); + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + preset_id: normalizedPresetId, + print_service_response: result.response, + }; + } + + async delete(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const record = await ctx.model.Camera.findOne({ where: { id, warehouse_id: warehouseId } }); + if (!record) throw new Error('摄像头不存在或无权操作'); + + // 检查是否被工作台绑定 + const boundWorkbenches = await ctx.model.Workbench.findAll({ + where: { warehouse_id: warehouseId }, + attributes: [ 'id', 'name' ], + }); + for (const wb of boundWorkbenches) { + const deviceIds = Array.isArray(wb.device_ids) ? wb.device_ids : []; + if (deviceIds.includes(id)) { + throw new Error(`摄像头已被工作台「${wb.name}」绑定,请先解绑后再删除`); + } + } + + await record.destroy(); + } +} + +module.exports = CameraService; diff --git a/app/service/systems/cameraServer.js b/app/service/systems/cameraServer.js new file mode 100644 index 0000000..0bdd0fe --- /dev/null +++ b/app/service/systems/cameraServer.js @@ -0,0 +1,127 @@ +'use strict'; + +const Service = require('egg').Service; + +class CameraServerService extends Service { + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = ctx.user.store_id; + const { pagination = {}, where = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = { warehouse_id: warehouseId }; + if (where.name) queryWhere.name = { [Op.like]: `%${where.name}%` }; + if (where.status !== undefined && where.status !== null && where.status !== '') { + queryWhere.status = parseInt(where.status); + } + + const { count, rows } = await ctx.model.CameraServer.findAndCountAll({ + where: queryWhere, + order: [[ 'created_at', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + return { list: rows, pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize), hasPrevious: page > 1, hasNext: page * pageSize < count } }; + } + + async detail(id) { + const { ctx } = this; + const record = await ctx.model.CameraServer.findOne({ where: { id, warehouse_id: ctx.user.store_id } }); + if (!record) throw new Error('录像服务器不存在或无权访问'); + return record; + } + + async create(data) { + const { ctx } = this; + if (!data.name || !String(data.name).trim()) throw new Error('服务器名称不能为空'); + + // 规范化 IP 和端口 + const publicIp = data.public_ip ? String(data.public_ip).trim() : ''; + const internalIp = data.internal_ip ? String(data.internal_ip).trim() : ''; + const publicPort = data.public_port !== undefined && data.public_port !== null ? parseInt(data.public_port) : null; + const internalPort = data.internal_port !== undefined && data.internal_port !== null ? parseInt(data.internal_port) : null; + + // IP-端口配对校验:有 IP 则端口必填 + if (publicIp && !publicPort) throw new Error('公网端口不能为空'); + if (internalIp && !internalPort) throw new Error('内网端口不能为空'); + + // 至少一组 IP+端口 完整 + const hasPublic = !!(publicIp && publicPort); + const hasInternal = !!(internalIp && internalPort); + if (!hasPublic && !hasInternal) throw new Error('至少需要填写一组公网IP+端口或内网IP+端口'); + + return await ctx.model.CameraServer.create({ + warehouse_id: ctx.user.store_id, + name: String(data.name).trim(), + brand: data.brand || null, + public_ip: publicIp || null, + internal_ip: internalIp || null, + public_port: publicPort, + internal_port: internalPort, + username: data.username || null, + password: data.password || null, + status: data.status !== undefined ? parseInt(data.status) : 1, + remark: data.remark || null, + }); + } + + async update(id, data) { + const { ctx } = this; + const record = await ctx.model.CameraServer.findOne({ where: { id, warehouse_id: ctx.user.store_id } }); + if (!record) throw new Error('录像服务器不存在或无权操作'); + + const fields = {}; + if (data.name !== undefined) fields.name = String(data.name).trim(); + if (data.brand !== undefined) fields.brand = data.brand; + if (data.public_ip !== undefined) fields.public_ip = data.public_ip ? String(data.public_ip).trim() : null; + if (data.internal_ip !== undefined) fields.internal_ip = data.internal_ip ? String(data.internal_ip).trim() : null; + if (data.public_port !== undefined) fields.public_port = data.public_port !== null ? parseInt(data.public_port) : null; + if (data.internal_port !== undefined) fields.internal_port = data.internal_port !== null ? parseInt(data.internal_port) : null; + if (data.username !== undefined) fields.username = data.username; + if (data.password !== undefined) fields.password = data.password; + if (data.status !== undefined) fields.status = parseInt(data.status); + if (data.remark !== undefined) fields.remark = data.remark; + if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段'); + + // 合并新旧值,校验最终状态 + const mergedPublicIp = data.public_ip !== undefined ? fields.public_ip : record.public_ip; + const mergedInternalIp = data.internal_ip !== undefined ? fields.internal_ip : record.internal_ip; + const mergedPublicPort = data.public_port !== undefined ? fields.public_port : record.public_port; + const mergedInternalPort = data.internal_port !== undefined ? fields.internal_port : record.internal_port; + + // IP-端口配对校验 + if (mergedPublicIp && !mergedPublicPort) throw new Error('公网端口不能为空'); + if (mergedInternalIp && !mergedInternalPort) throw new Error('内网端口不能为空'); + + // 至少一组 IP+端口 完整 + const hasPublic = !!(mergedPublicIp && mergedPublicPort); + const hasInternal = !!(mergedInternalIp && mergedInternalPort); + if (!hasPublic && !hasInternal) throw new Error('至少需要填写一组公网IP+端口或内网IP+端口'); + + await record.update(fields); + return record; + } + + async delete(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const record = await ctx.model.CameraServer.findOne({ where: { id, warehouse_id: warehouseId } }); + if (!record) throw new Error('录像服务器不存在或无权操作'); + + // 检查是否有关联摄像头 + const cameraCount = await ctx.model.Camera.count({ + where: { server_id: id, warehouse_id: warehouseId }, + }); + if (cameraCount > 0) { + throw new Error(`录像服务器下存在 ${cameraCount} 个摄像头,请先删除摄像头后再删除服务器`); + } + + await record.destroy(); + } +} + +module.exports = CameraServerService; diff --git a/app/service/systems/client_error_log.js b/app/service/systems/client_error_log.js new file mode 100644 index 0000000..8096a0f --- /dev/null +++ b/app/service/systems/client_error_log.js @@ -0,0 +1,255 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('crypto'); + +/** 单次批量上报最大条数 */ +const MAX_BATCH_SIZE = 50; + +/** error_message 单条最大长度(超出截断) */ +const ERROR_MESSAGE_MAX_LENGTH = 5000; + +/** error_stack 单条最大长度(超出截断) */ +const ERROR_STACK_MAX_LENGTH = 65535; + +/** extra 单条最大长度(超出截断) */ +const EXTRA_MAX_LENGTH = 65535; + +/** 字符串字段最大长度(与 wms_client_error_log 表结构列宽对齐) */ +const STRING_FIELD_LIMITS = Object.freeze({ + client_type: 32, + app_version: 64, + device_id: 128, + os_version: 64, + device_model: 128, + error_type: 64, + report_uuid: 64, +}); + +/** + * 客户端错误日志服务层。 + * + * 职责:接收 index.uploadClientErrorLog 转交的原始上报数据(数组), + * 完成字段归一化、必填校验、长度截断、report_uuid 幂等去重与批量落库; + * 所有写入失败均返回友好结果对象,不向上抛出未捕获异常。 + */ +class ClientErrorLogService extends Service { + /** + * 从上报项中按候选字段名提取首个非空值(兼容 snake_case 与 camelCase 两种入参命名)。 + * + * @param {Object} item 上报项。 + * @param {Array} keys 候选字段名(按优先级排序)。 + * @return {*} 命中的字段值;未命中返回 undefined。 + */ + _pick(item, keys) { + for (const key of keys) { + if (Object.prototype.hasOwnProperty.call(item, key) && item[key] !== null && item[key] !== undefined) { + return item[key]; + } + } + + return undefined; + } + + /** + * 将任意值转换为去除首尾空白并截断到指定长度的字符串。 + * + * @param {*} value 原始值。 + * @param {number} maxLength 最大长度。 + * @return {string} 转换后的字符串。 + */ + _toText(value, maxLength) { + if (value === null || value === undefined) { + return ''; + } + + const text = String(value).trim(); + return text.length > maxLength ? text.slice(0, maxLength) : text; + } + + /** + * 解析客户端时间:支持毫秒/秒时间戳与日期字符串,解析失败返回 null。 + * + * @param {*} value 客户端时间原始值。 + * @return {Date|null} 解析出的日期;无法解析返回 null。 + */ + _parseClientTime(value) { + if (value === null || value === undefined || value === '') { + return null; + } + + let parsed = null; + + if (typeof value === 'number') { + // 13 位以上视为毫秒,其余视为秒 + parsed = new Date(value >= 1e12 ? value : value * 1000); + } else { + const text = String(value).trim(); + if (/^\d{10,16}$/.test(text)) { + const number = Number(text); + parsed = new Date(number >= 1e12 ? number : number * 1000); + } else { + parsed = new Date(text); + } + } + + if (Number.isNaN(parsed.getTime())) { + return null; + } + + return parsed; + } + + /** + * 归一化单条上报项,输出可落库字段或拒绝原因。 + * + * @param {*} raw 原始上报项。 + * @return {Object} { row } 归一化成功;{ error } 校验失败(附原因文案)。 + */ + _normalizeItem(raw) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + return { error: '日志项必须为对象' }; + } + + const errorMessage = this._toText( + this._pick(raw, [ 'error_message', 'errorMessage' ]), + ERROR_MESSAGE_MAX_LENGTH + ); + const errorStack = this._toText( + this._pick(raw, [ 'error_stack', 'errorStack' ]), + ERROR_STACK_MAX_LENGTH + ); + + // 必填校验:error_message 与 error_stack 至少一项有值 + if (!errorMessage && !errorStack) { + return { error: 'error_message 与 error_stack 至少填写一项' }; + } + + const extraRaw = this._pick(raw, [ 'extra' ]); + let extra = ''; + if (extraRaw !== null && extraRaw !== undefined) { + if (typeof extraRaw === 'string') { + extra = extraRaw.slice(0, EXTRA_MAX_LENGTH); + } else { + try { + extra = JSON.stringify(extraRaw); + } catch (error) { + extra = ''; + } + + if (extra.length > EXTRA_MAX_LENGTH) { + extra = extra.slice(0, EXTRA_MAX_LENGTH); + } + } + } + + let reportUuid = this._toText( + this._pick(raw, [ 'report_uuid', 'reportUuid' ]), + STRING_FIELD_LIMITS.report_uuid + ); + // 客户端未生成 uuid 时由服务端补齐,保证唯一索引可用(此时不做幂等去重) + if (!reportUuid) { + reportUuid = `srv-${crypto.randomUUID()}`; + } + + return { + row: { + client_type: this._toText(this._pick(raw, [ 'client_type', 'clientType' ]), STRING_FIELD_LIMITS.client_type), + app_version: this._toText(this._pick(raw, [ 'app_version', 'appVersion' ]), STRING_FIELD_LIMITS.app_version), + device_id: this._toText(this._pick(raw, [ 'device_id', 'deviceId' ]), STRING_FIELD_LIMITS.device_id), + os_version: this._toText(this._pick(raw, [ 'os_version', 'osVersion' ]), STRING_FIELD_LIMITS.os_version), + device_model: this._toText(this._pick(raw, [ 'device_model', 'deviceModel' ]), STRING_FIELD_LIMITS.device_model), + error_type: this._toText(this._pick(raw, [ 'error_type', 'errorType' ]), STRING_FIELD_LIMITS.error_type), + error_message: errorMessage, + error_stack: errorStack, + extra, + report_uuid: reportUuid, + client_time: this._parseClientTime(this._pick(raw, [ 'client_time', 'clientTime' ])), + }, + }; + } + + /** + * 批量上报客户端错误日志(幂等写入,report_uuid 重复时静默成功)。 + * + * @param {Object} params 入参(由方法层解构传入)。 + * @param {Array} params.list 归一化后的上报项数组(单次最多 50 条)。 + * @return {Promise} 处理结果: + * success=true 时含 total/accepted/duplicated/rejected/rejected_reasons 统计; + * success=false 时含 message/code(校验失败或写入失败)。 + */ + async upload({ list }) { + const { ctx } = this; + + if (!Array.isArray(list) || list.length === 0) { + return { success: false, message: '缺少上报日志数据', code: 400 }; + } + + if (list.length > MAX_BATCH_SIZE) { + return { success: false, message: `单次最多上报 ${MAX_BATCH_SIZE} 条日志`, code: 400 }; + } + + const rows = []; + const rejectedReasons = []; + list.forEach((item, index) => { + const normalized = this._normalizeItem(item); + if (normalized.error) { + rejectedReasons.push({ index, reason: normalized.error }); + } else { + rows.push(normalized.row); + } + }); + + if (rows.length === 0) { + return { success: false, message: '没有可入库的有效日志', code: 400, rejected: rejectedReasons.length }; + } + + // 幂等去重:查询已存在的 report_uuid,重复项静默成功、不产生重复行 + let existingUuids = []; + try { + const uuids = rows.map(row => row.report_uuid); + const existingRows = await ctx.model.ClientErrorLog.findAll({ + where: { report_uuid: uuids }, + attributes: [ 'report_uuid' ], + raw: true, + }); + existingUuids = existingRows.map(item => item.report_uuid); + } catch (error) { + ctx.logger.error(`[clientErrorLog] 查询已有 report_uuid 失败: ${error.message}`); + return { success: false, message: '日志上报失败,请稍后重试', code: 500 }; + } + + const newRows = rows.filter(row => !existingUuids.includes(row.report_uuid)); + const duplicatedCount = rows.length - newRows.length; + + let insertedCount = 0; + if (newRows.length > 0) { + try { + // created_at/updated_at 由 Sequelize 时间戳统一取服务器当前时间,不采信客户端时间。 + // 注意:Sequelize v6 的 bulkCreate 在实例校验(validate)之后才注入时间戳, + // 模型显式声明 created_at/updated_at 且 allowNull:false 时,validate:true 会触发 + // notNull Violation,导致所有有效上报写入失败;字段类型/必填/长度校验已由本服务层 + // _normalizeItem 完整保证(字符串归一化 + 长度截断 + client_time 解析), + // 故此处关闭模型级校验,与项目中其他 bulkCreate 调用(默认 validate:false)保持一致。 + await ctx.model.ClientErrorLog.bulkCreate(newRows, { validate: false }); + insertedCount = newRows.length; + } catch (error) { + ctx.logger.error(`[clientErrorLog] 批量写入失败: ${error.message}`); + return { success: false, message: '日志写入失败,请稍后重试', code: 500 }; + } + } + + return { + success: true, + message: '上报成功', + code: 200, + total: list.length, + accepted: insertedCount, + duplicated: duplicatedCount, + rejected: rejectedReasons.length, + rejected_reasons: rejectedReasons.slice(0, 10), + }; + } +} + +module.exports = ClientErrorLogService; diff --git a/app/service/systems/comboGoods.js b/app/service/systems/comboGoods.js new file mode 100644 index 0000000..497a55d --- /dev/null +++ b/app/service/systems/comboGoods.js @@ -0,0 +1,1011 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 将输入值转换为有限数字。 + * + * @param {unknown} value 待转换的值。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 转换后的数字。 + */ +function toNumber(value, defaultValue = 0) { + const normalized = Number(value); + return Number.isFinite(normalized) ? normalized : defaultValue; +} + +/** + * 组合商品业务逻辑服务层。 + * 负责组合商品的 CRUD、搜索、校验等核心业务逻辑。 + */ +class ComboGoodsService extends Service { + // ---------- 公共辅助方法 ---------- + + /** + * 通过 stock_id 批量查询 wms_stock_warehouse,返回 Map 结构。 + * + * @param {number[]} stockIds stock_id 数组。 + * @return {Promise>} stockId → { id, item_name, store_id, item_code } 的映射。 + */ + async fetchStockInfoMap(stockIds) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const uniqueIds = [ ...new Set(stockIds.filter(id => toNumber(id) > 0)) ]; + + if (uniqueIds.length === 0) { + return new Map(); + } + + const rows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: uniqueIds }, + }, + attributes: [ 'id', 'item_name', 'store_id', 'item_code' ], + raw: true, + }); + + const map = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + const stockId = toNumber(row.id); + if (stockId > 0) { + map.set(stockId, { + id: stockId, + item_name: String(row.item_name || ''), + store_id: toNumber(row.store_id), + item_code: String(row.item_code || ''), + }); + } + } + return map; + } + + /** + * 构建字符串简记(格式:stock_id|数量,stock_id2|数量)。 + * + * @param {Object[]} items 明细数组,每项包含 item_goods_sku_id 与 item_quantity。 + * @return {string} 字符串简记。 + */ + buildSimpleNotation(items) { + if (!Array.isArray(items) || items.length === 0) { + return ''; + } + return items + .map(item => `${toNumber(item.item_goods_sku_id)}|${toNumber(item.item_quantity)}`) + .join(','); + } + + /** + * 构建商品名称简记(格式:【数量】商品名称+【数量】商品名称)。 + * + * @param {Object[]} items 明细数组,每项包含 item_goods_sku_id 与 item_quantity。 + * @param {Map} stockInfoMap stockId → { item_name } 的映射。 + * @return {string} 商品名称简记。 + */ + buildNameNotation(items, stockInfoMap) { + if (!Array.isArray(items) || items.length === 0) { + return ''; + } + return items + .map(item => { + const stockId = toNumber(item.item_goods_sku_id); + const qty = toNumber(item.item_quantity); + const stockInfo = stockInfoMap.get(stockId); + const name = stockInfo ? stockInfo.item_name : `SKU#${stockId}`; + return `【${qty}】${name}`; + }) + .join('+'); + } + + /** + * 校验子商品的有效性(必须存在于 wms_stock_warehouse、状态正常、未删除)。 + * + * @param {number[]} stockIds 待校验的 stock_id 数组。 + * @return {Promise} 校验结果,{ ok: boolean, message?: string, stockInfoMap?: Map }。 + */ + async validateItems(stockIds) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const uniqueIds = [ ...new Set(stockIds.filter(id => toNumber(id) > 0)) ]; + + if (uniqueIds.length === 0) { + return { ok: false, message: '子商品列表不能为空' }; + } + + const rows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: uniqueIds }, + is_valid: 'Y', + deleted_at: null, + }, + attributes: [ 'id', 'item_name', 'store_id', 'item_code' ], + raw: true, + }); + + const validMap = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + validMap.set(toNumber(row.id), { + id: toNumber(row.id), + item_name: String(row.item_name || ''), + store_id: toNumber(row.store_id), + item_code: String(row.item_code || ''), + }); + } + + // 找出哪些 stock_id 不在有效列表中 + const invalidIds = uniqueIds.filter(id => !validMap.has(id)); + if (invalidIds.length > 0) { + return { ok: false, message: `以下子商品不存在或已停用:${invalidIds.join(', ')}` }; + } + + // 校验是否所有子商品属于同一个货主(owner_id / store_id) + const ownerIds = new Set(); + for (const [ , info ] of validMap) { + ownerIds.add(info.store_id); + } + if (ownerIds.size > 1) { + return { ok: false, message: '所有子商品必须属于同一个货主,不允许跨货主组合' }; + } + + return { ok: true, stockInfoMap: validMap }; + } + + /** + * 从 stockInfoMap 中提取 targetStoreId。 + * + * @param {Map} stockInfoMap stockId → { store_id } 的映射。 + * @return {number} 目标货主ID,如果无法确定则返回 0。 + */ + getTargetStoreIdFromMap(stockInfoMap) { + if (!stockInfoMap || stockInfoMap.size === 0) { + return 0; + } + const storeIds = new Set(); + for (const [ , info ] of stockInfoMap) { + storeIds.add(info.store_id); + } + if (storeIds.size !== 1) { + return 0; + } + return storeIds.values().next().value; + } + + /** + * 自定义编码货主唯一性校验(创建时)。 + * 通过 items 反查 store_id,再查询是否存在相同 custom_code + 同货主的非删除记录。 + * + * @param {string} customCode 自定义编码。 + * @param {Map} stockInfoMap 当前 items 的 stockId → { store_id } 映射。 + * @throws {Error} 如果自定义编码在同一货主内已存在。 + */ + async checkCustomCodeUniqueForCreate(customCode, stockInfoMap) { + const { ctx } = this; + const targetStoreId = this.getTargetStoreIdFromMap(stockInfoMap); + if (targetStoreId <= 0) { + return; // 无法确定货主,跳过校验 + } + + // 查出所有 status != 0 且 custom_code 相同的 combo_id + const sameCodeRows = await ctx.model.query( + `SELECT id FROM wms_combo_goods + WHERE custom_code = :customCode AND status != 0`, + { + replacements: { customCode }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (!Array.isArray(sameCodeRows) || sameCodeRows.length === 0) { + return; // 无重复 + } + + const conflictComboIds = sameCodeRows.map(r => toNumber(r.id)).filter(id => id > 0); + if (conflictComboIds.length === 0) { + return; + } + + // 查这些 combo_id 的子商品对应的 stock_id + const conflictItemRows = await ctx.model.query( + `SELECT DISTINCT cgi.item_goods_sku_id + FROM wms_combo_goods_item cgi + WHERE cgi.combo_id IN (:comboIds)`, + { + replacements: { comboIds: conflictComboIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (!Array.isArray(conflictItemRows) || conflictItemRows.length === 0) { + return; + } + + const conflictStockIds = conflictItemRows + .map(r => toNumber(r.item_goods_sku_id)) + .filter(id => id > 0); + + if (conflictStockIds.length === 0) { + return; + } + + // 查出这些 stock_id 对应的 store_id + const { Op } = ctx.app.Sequelize; + const conflictStocks = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: conflictStockIds } }, + attributes: [ 'store_id' ], + raw: true, + }); + + const conflictStoreIds = new Set(); + for (const row of (Array.isArray(conflictStocks) ? conflictStocks : [])) { + conflictStoreIds.add(toNumber(row.store_id)); + } + + if (conflictStoreIds.has(targetStoreId)) { + throw new Error('自定义编码已存在'); + } + } + + /** + * 自定义编码货主唯一性校验(更新时,排除自身 id)。 + * 通过已有子商品反查 store_id,再查询是否存在相同 custom_code + 同货主的非删除记录(排除自身)。 + * + * @param {string} customCode 自定义编码。 + * @param {number} comboId 当前组合商品ID(排除自身)。 + * @param {Object|null} itemValidation 如已做过 validateItems,传入结果复用 stockInfoMap。 + * @throws {Error} 如果自定义编码在同一货主内已存在。 + */ + async checkCustomCodeUniqueForUpdate(customCode, comboId, itemValidation) { + const { ctx } = this; + let targetStoreId = 0; + + // 优先使用传入的 itemValidation 中的 stockInfoMap + if (itemValidation && itemValidation.ok && itemValidation.stockInfoMap) { + targetStoreId = this.getTargetStoreIdFromMap(itemValidation.stockInfoMap); + } + + // 如果无法从传入 items 确定货主,则从已有子商品反查 + if (targetStoreId <= 0) { + const existingItems = await ctx.model.query( + `SELECT cgi.item_goods_sku_id + FROM wms_combo_goods_item cgi + WHERE cgi.combo_id = :comboId`, + { + replacements: { comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(existingItems) && existingItems.length > 0) { + const stockIds = existingItems + .map(r => toNumber(r.item_goods_sku_id)) + .filter(id => id > 0); + if (stockIds.length > 0) { + const stockInfoMap = await this.fetchStockInfoMap(stockIds); + targetStoreId = this.getTargetStoreIdFromMap(stockInfoMap); + } + } + } + + if (targetStoreId <= 0) { + return; // 无法确定货主,跳过校验 + } + + // 查出所有 status != 0 且 custom_code 相同且 id != comboId 的记录 + const sameCodeRows = await ctx.model.query( + `SELECT id FROM wms_combo_goods + WHERE custom_code = :customCode AND status != 0 AND id != :comboId`, + { + replacements: { customCode, comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (!Array.isArray(sameCodeRows) || sameCodeRows.length === 0) { + return; // 无重复 + } + + const conflictComboIds = sameCodeRows.map(r => toNumber(r.id)).filter(id => id > 0); + if (conflictComboIds.length === 0) { + return; + } + + // 查这些冲突 combo_id 的子商品对应的 store_id + const conflictItemRows = await ctx.model.query( + `SELECT DISTINCT cgi.item_goods_sku_id + FROM wms_combo_goods_item cgi + WHERE cgi.combo_id IN (:comboIds)`, + { + replacements: { comboIds: conflictComboIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (!Array.isArray(conflictItemRows) || conflictItemRows.length === 0) { + return; + } + + const conflictStockIds = conflictItemRows + .map(r => toNumber(r.item_goods_sku_id)) + .filter(id => id > 0); + + if (conflictStockIds.length === 0) { + return; + } + + const { Op } = ctx.app.Sequelize; + const conflictStocks = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: conflictStockIds } }, + attributes: [ 'store_id' ], + raw: true, + }); + + const conflictStoreIds = new Set(); + for (const row of (Array.isArray(conflictStocks) ? conflictStocks : [])) { + conflictStoreIds.add(toNumber(row.store_id)); + } + + if (conflictStoreIds.has(targetStoreId)) { + throw new Error('自定义编码已存在'); + } + } + + // ---------- 1. 列表查询 ---------- + + /** + * 组合商品列表查询(分页)。 + * + * @param {Object} options 查询选项。 + * @param {number} [options.page=1] 页码。 + * @param {number} [options.pageSize=20] 每页大小。 + * @param {string} [options.combo_code] 组合商品编码筛选。 + * @param {string} [options.combo_name] 组合商品名称筛选(模糊)。 + * @param {number} [options.status] 状态筛选。 + * @param {number} [options.warehouse_id] 仓库ID筛选。 + * @return {Promise} 分页列表结果。 + */ + async list(options = {}) { + const { ctx } = this; + const page = Math.max(1, toNumber(options.page, 1)); + const pageSize = Math.min(200, Math.max(1, toNumber(options.pageSize, 20))); + + // 构建 where 子句与 replacements + const { whereClause, replacements } = this.buildListWhere(options); + + // 查询总数 + const countSql = `SELECT COUNT(*) AS cnt FROM wms_combo_goods WHERE ${whereClause}`; + const countRows = await ctx.model.query(countSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + const total = toNumber(countRows && countRows[0] && countRows[0].cnt, 0); + + // 查询主表分页数据 + const offset = (page - 1) * pageSize; + const listSql = `SELECT * FROM wms_combo_goods WHERE ${whereClause} + ORDER BY id DESC LIMIT ${offset}, ${pageSize}`; + const mainRows = await ctx.model.query(listSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + + const list = Array.isArray(mainRows) ? mainRows : []; + + if (list.length === 0) { + return { list: [], total, page, pageSize }; + } + + // 批量查询明细 + const comboIds = list.map(row => toNumber(row.id)).filter(id => id > 0); + const itemRows = comboIds.length > 0 + ? await ctx.model.query( + 'SELECT * FROM wms_combo_goods_item WHERE combo_id IN (:comboIds) ORDER BY sort_order ASC, id ASC', + { + replacements: { comboIds }, + type: ctx.model.QueryTypes.SELECT, + } + ) + : []; + + // 按 combo_id 分组明细 + const itemsByComboId = new Map(); + for (const item of Array.isArray(itemRows) ? itemRows : []) { + const comboId = toNumber(item.combo_id); + if (!itemsByComboId.has(comboId)) { + itemsByComboId.set(comboId, []); + } + itemsByComboId.get(comboId).push({ + id: toNumber(item.id), + combo_id: comboId, + item_goods_sku_id: toNumber(item.item_goods_sku_id), + item_quantity: toNumber(item.item_quantity), + sort_order: toNumber(item.sort_order), + }); + } + + // 收集所有 stock_id 以批量获取商品名称 + const allStockIds = []; + for (const [ , items ] of itemsByComboId) { + for (const item of items) { + allStockIds.push(item.item_goods_sku_id); + } + } + const stockInfoMap = await this.fetchStockInfoMap(allStockIds); + + // 组装最终列表 + const resultList = list.map(row => { + const comboId = toNumber(row.id); + const items = itemsByComboId.get(comboId) || []; + return { + id: comboId, + combo_code: String(row.combo_code || ''), + combo_name: String(row.combo_name || ''), + combo_sku_id: toNumber(row.combo_sku_id), + custom_code: row.custom_code || null, + status: toNumber(row.status), + warehouse_id: toNumber(row.warehouse_id), + remark: String(row.remark || ''), + creator_id: toNumber(row.creator_id), + editor_id: toNumber(row.editor_id), + created_at: row.created_at, + updated_at: row.updated_at, + items, + simpleNotation: this.buildSimpleNotation(items), + nameNotation: this.buildNameNotation(items, stockInfoMap), + }; + }); + + return { list: resultList, total, page, pageSize }; + } + + /** + * 为列表查询构建参数化的 WHERE 子句。 + * + * @param {Object} options 查询选项。 + * @return {Object} 包含 whereClause(string)与 replacements(Object)的对象。 + */ + buildListWhere(options) { + const clauses = []; + const replacements = {}; + + if (options.combo_code) { + clauses.push('combo_code = :comboCode'); + replacements.comboCode = String(options.combo_code).trim(); + } + if (options.combo_name) { + clauses.push('combo_name LIKE :comboName'); + replacements.comboName = `%${String(options.combo_name).trim()}%`; + } + if (options.status !== undefined && options.status !== null && options.status !== '') { + clauses.push('status = :status'); + replacements.status = toNumber(options.status); + } + if (options.warehouse_id !== undefined && options.warehouse_id !== null && options.warehouse_id !== '') { + clauses.push('warehouse_id = :warehouseId'); + replacements.warehouseId = toNumber(options.warehouse_id); + } + + return { + whereClause: clauses.length > 0 ? clauses.join(' AND ') : '1=1', + replacements, + }; + } + + // ---------- 2. 创建组合商品 ---------- + + /** + * 创建组合商品(含明细),使用事务保证原子性。 + * + * @param {Object} options 创建参数。 + * @param {string} options.combo_code 组合商品编码。 + * @param {string} options.combo_name 组合商品名称。 + * @param {number} [options.warehouse_id] 仓库ID。 + * @param {string} [options.remark] 备注。 + * @param {string} [options.custom_code] 自定义编码。 + * @param {Object[]} options.items 子商品明细数组 [{item_goods_sku_id, item_quantity}]。 + * @param {number} [options.creator_id] 创建人ID。 + * @return {Promise} 创建结果,包含 id、combo_code、combo_name、custom_code。 + */ + async create(options = {}) { + const { ctx } = this; + const { combo_code, combo_name, items } = options; + const warehouseId = toNumber(options.warehouse_id); + const remark = String(options.remark || ''); + const customCode = options.custom_code ? String(options.custom_code).trim() : ''; + const creatorId = toNumber(options.creator_id || ctx.user?.id || 0); + + // 参数基础校验 + if (!combo_code || !String(combo_code).trim()) { + throw new Error('组合商品编码不能为空'); + } + if (!combo_name || !String(combo_name).trim()) { + throw new Error('组合商品名称不能为空'); + } + if (!Array.isArray(items) || items.length === 0) { + throw new Error('子商品列表不能为空'); + } + + const trimmedCode = String(combo_code).trim(); + const trimmedName = String(combo_name).trim(); + + // 唯一性校验 + const existing = await ctx.model.query( + 'SELECT id FROM wms_combo_goods WHERE combo_code = :comboCode LIMIT 1', + { + replacements: { comboCode: trimmedCode }, + type: ctx.model.QueryTypes.SELECT, + } + ); + if (Array.isArray(existing) && existing.length > 0) { + throw new Error(`组合商品编码 "${trimmedCode}" 已存在`); + } + + // 子商品有效性校验 + const stockIds = items.map(item => toNumber(item.item_goods_sku_id)).filter(id => id > 0); + const validation = await this.validateItems(stockIds); + if (!validation.ok) { + throw new Error(validation.message); + } + + // 自定义编码货主唯一性校验 + if (customCode) { + await this.checkCustomCodeUniqueForCreate(customCode, validation.stockInfoMap); + } + + // 事务写入 + const transaction = await ctx.model.transaction(); + + try { + // 插入主表 + const insertResult = await ctx.model.query( + `INSERT INTO wms_combo_goods (combo_code, combo_name, warehouse_id, remark, custom_code, status, creator_id, editor_id) + VALUES (:comboCode, :comboName, :warehouseId, :remark, :customCode, 1, :creatorId, :creatorId)`, + { + replacements: { + comboCode: trimmedCode, + comboName: trimmedName, + warehouseId: warehouseId > 0 ? warehouseId : null, + remark, + customCode: customCode || null, + creatorId: creatorId > 0 ? creatorId : null, + }, + transaction, + } + ); + + const insertHead = Array.isArray(insertResult) ? insertResult[0] : null; + const comboId = toNumber( + (typeof insertHead === 'number' && insertHead > 0) ? insertHead + : (insertHead && (insertHead.insertId || insertHead.lastID || insertHead.id)) + || (insertResult && insertResult.insertId) + || 0 + ); + if (comboId <= 0) { + throw new Error('创建组合商品主记录失败'); + } + + // 批量插入明细 + if (items.length > 0) { + const itemValues = items.map((item, index) => { + const skuId = toNumber(item.item_goods_sku_id); + const qty = Math.max(1, toNumber(item.item_quantity, 1)); + const sortOrder = toNumber(item.sort_order, index); + return `(${comboId}, ${skuId}, ${qty}, ${sortOrder})`; + }).join(', '); + + await ctx.model.query( + `INSERT INTO wms_combo_goods_item (combo_id, item_goods_sku_id, item_quantity, sort_order) VALUES ${itemValues}`, + { transaction } + ); + } + + await transaction.commit(); + + return { + id: comboId, + combo_code: trimmedCode, + combo_name: trimmedName, + custom_code: customCode || null, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // ---------- 3. 编辑组合商品 ---------- + + /** + * 编辑组合商品(含明细替换),使用事务保证原子性。 + * + * @param {Object} options 编辑参数。 + * @param {number} options.id 组合商品ID。 + * @param {string} [options.combo_name] 组合商品名称。 + * @param {number} [options.warehouse_id] 仓库ID。 + * @param {string} [options.remark] 备注。 + * @param {string} [options.custom_code] 自定义编码。 + * @param {number} [options.status] 状态 1-启用 0-停用。 + * @param {Object[]} [options.items] 子商品明细数组。 + * @param {number} [options.editor_id] 编辑人ID。 + * @return {Promise} 编辑结果,包含 id。 + */ + async update(options = {}) { + const { ctx } = this; + const comboId = toNumber(options.id); + const editorId = toNumber(options.editor_id || ctx.user?.id || 0); + + if (comboId <= 0) { + throw new Error('组合商品ID不能为空'); + } + + // 校验记录是否存在 + const existingRows = await ctx.model.query( + 'SELECT id, combo_code, combo_name FROM wms_combo_goods WHERE id = :comboId LIMIT 1', + { + replacements: { comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + if (!Array.isArray(existingRows) || existingRows.length === 0) { + throw new Error('组合商品不存在'); + } + + // 如果传入了 items,校验子商品有效性 + const items = options.items; + let itemValidation = null; + if (items !== undefined && Array.isArray(items) && items.length > 0) { + const stockIds = items.map(item => toNumber(item.item_goods_sku_id)).filter(id => id > 0); + itemValidation = await this.validateItems(stockIds); + if (!itemValidation.ok) { + throw new Error(itemValidation.message); + } + } + + // 构建主表更新 set 子句 + const setClauses = []; + const replacements = { comboId }; + if (options.combo_name !== undefined) { + const name = String(options.combo_name).trim(); + if (!name) { + throw new Error('组合商品名称不能为空'); + } + setClauses.push('combo_name = :comboName'); + replacements.comboName = name; + } + if (options.warehouse_id !== undefined) { + const wid = toNumber(options.warehouse_id); + setClauses.push('warehouse_id = :warehouseId'); + replacements.warehouseId = wid > 0 ? wid : null; + } + if (options.remark !== undefined) { + setClauses.push('remark = :remark'); + replacements.remark = String(options.remark); + } + if (options.custom_code !== undefined) { + const customCode = options.custom_code ? String(options.custom_code).trim() : ''; + setClauses.push('custom_code = :customCode'); + replacements.customCode = customCode || null; + } + if (options.status !== undefined) { + const st = toNumber(options.status); + setClauses.push('status = :status'); + replacements.status = st === 1 ? 1 : 0; + } + if (editorId > 0) { + setClauses.push('editor_id = :editorId'); + replacements.editorId = editorId; + } + + // 自定义编码货主唯一性校验(排除自身 id) + if (options.custom_code !== undefined && options.custom_code && String(options.custom_code).trim()) { + const customCode = String(options.custom_code).trim(); + // 获取目标 store_id:优先从传入的 items 的 stockInfoMap 获取,否则查已有子商品 + await this.checkCustomCodeUniqueForUpdate(customCode, comboId, itemValidation); + } + + // 事务执行 + const transaction = await ctx.model.transaction(); + + try { + // 更新主表 + if (setClauses.length > 0) { + await ctx.model.query( + `UPDATE wms_combo_goods SET ${setClauses.join(', ')} WHERE id = :comboId`, + { replacements, transaction } + ); + } + + // 如果传入了 items,先删旧明细再插入新明细 + if (items !== undefined) { + await ctx.model.query( + 'DELETE FROM wms_combo_goods_item WHERE combo_id = :comboId', + { replacements: { comboId }, transaction } + ); + + if (Array.isArray(items) && items.length > 0) { + const itemValues = items.map((item, index) => { + const skuId = toNumber(item.item_goods_sku_id); + const qty = Math.max(1, toNumber(item.item_quantity, 1)); + const sortOrder = toNumber(item.sort_order, index); + return `(${comboId}, ${skuId}, ${qty}, ${sortOrder})`; + }).join(', '); + + await ctx.model.query( + `INSERT INTO wms_combo_goods_item (combo_id, item_goods_sku_id, item_quantity, sort_order) VALUES ${itemValues}`, + { transaction } + ); + } + } + + await transaction.commit(); + + return { id: comboId }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // ---------- 4. 删除组合商品 ---------- + + /** + * 删除组合商品(软删除:status = 0)。 + * + * @param {Object} options 删除参数。 + * @param {number} options.id 组合商品ID。 + * @return {Promise} 删除结果。 + */ + async delete(options = {}) { + const { ctx } = this; + const comboId = toNumber(options.id); + + if (comboId <= 0) { + throw new Error('组合商品ID不能为空'); + } + + // 校验记录是否存在 + const existingRows = await ctx.model.query( + 'SELECT id FROM wms_combo_goods WHERE id = :comboId LIMIT 1', + { + replacements: { comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + if (!Array.isArray(existingRows) || existingRows.length === 0) { + throw new Error('组合商品不存在'); + } + + // 软删除:将 status 置为 0 + await ctx.model.query( + 'UPDATE wms_combo_goods SET status = 0 WHERE id = :comboId', + { + replacements: { comboId }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + + return { id: comboId }; + } + + // ---------- 5. 关键字搜索 ---------- + + /** + * 关键字搜索组合商品(模糊匹配 custom_code、combo_code 或 combo_name,自定义编码优先排序,限制返回条数)。 + * + * @param {Object} options 搜索选项。 + * @param {string} options.keyword 搜索关键字。 + * @param {number} [options.limit=20] 最大返回条数。 + * @return {Promise} 搜索结果列表。 + */ + async search(options = {}) { + const { ctx } = this; + const keyword = String(options.keyword || '').trim(); + const limit = Math.min(100, Math.max(1, toNumber(options.limit, 20))); + + if (!keyword) { + return { list: [] }; + } + + const rows = await ctx.model.query( + `SELECT * FROM wms_combo_goods + WHERE status = 1 + AND (custom_code LIKE :keywordLike + OR combo_code LIKE :keywordLike + OR combo_name LIKE :keywordLike) + ORDER BY (CASE WHEN custom_code LIKE :keywordLike THEN 0 ELSE 1 END) ASC, + id DESC + LIMIT :limit`, + { + replacements: { + keywordLike: `%${keyword}%`, + limit, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const list = Array.isArray(rows) ? rows : []; + + if (list.length === 0) { + return { list: [] }; + } + + // 批量查询明细 + const comboIds = list.map(row => toNumber(row.id)).filter(id => id > 0); + const itemRows = comboIds.length > 0 + ? await ctx.model.query( + 'SELECT * FROM wms_combo_goods_item WHERE combo_id IN (:comboIds) ORDER BY sort_order ASC, id ASC', + { + replacements: { comboIds }, + type: ctx.model.QueryTypes.SELECT, + } + ) + : []; + + const itemsByComboId = new Map(); + for (const item of Array.isArray(itemRows) ? itemRows : []) { + const cid = toNumber(item.combo_id); + if (!itemsByComboId.has(cid)) { + itemsByComboId.set(cid, []); + } + itemsByComboId.get(cid).push({ + id: toNumber(item.id), + combo_id: cid, + item_goods_sku_id: toNumber(item.item_goods_sku_id), + item_quantity: toNumber(item.item_quantity), + sort_order: toNumber(item.sort_order), + }); + } + + // 批量获取商品信息 + const allStockIds = []; + for (const [ , items ] of itemsByComboId) { + for (const item of items) { + allStockIds.push(item.item_goods_sku_id); + } + } + const stockInfoMap = await this.fetchStockInfoMap(allStockIds); + + const resultList = list.map(row => { + const cid = toNumber(row.id); + const items = itemsByComboId.get(cid) || []; + return { + id: cid, + combo_code: String(row.combo_code || ''), + combo_name: String(row.combo_name || ''), + combo_sku_id: toNumber(row.combo_sku_id), + custom_code: row.custom_code || null, + status: toNumber(row.status), + warehouse_id: toNumber(row.warehouse_id), + remark: String(row.remark || ''), + creator_id: toNumber(row.creator_id), + editor_id: toNumber(row.editor_id), + items, + simpleNotation: this.buildSimpleNotation(items), + nameNotation: this.buildNameNotation(items, stockInfoMap), + }; + }); + + return { list: resultList }; + } + + /** + * 按 id 或 custom_code 搜索组合商品,返回含明细和简记字段的结果。 + * + * @param {Object} options 查询选项 + * @param {number} [options.id] 组合商品主键ID,精确查询单条 + * @param {string} [options.custom_code] 自定义编码,模糊匹配 + * @return {Promise} 包含 list 数组的结果对象,每条含 items、simpleNotation、nameNotation + */ + async searchByIdOrCode(options = {}) { + const { ctx } = this; + const comboId = toNumber(options.id); + const customCode = String(options.custom_code || '').trim(); + + // 优先按 id 精确查询 + if (comboId > 0) { + const rows = await ctx.model.query( + 'SELECT * FROM wms_combo_goods WHERE id = :id AND status = 1', + { + replacements: { id: comboId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const list = Array.isArray(rows) ? rows : []; + return this.enrichComboList(list); + } + + // 按 custom_code 模糊查询 + if (customCode) { + const sqlQuery = [ + 'SELECT * FROM wms_combo_goods', + 'WHERE status = 1', + 'AND custom_code LIKE :codeLike', + 'ORDER BY id DESC', + 'LIMIT 50', + ].join(' '); + const rows = await ctx.model.query( + sqlQuery, + { + replacements: { codeLike: `%${customCode}%` }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const list = Array.isArray(rows) ? rows : []; + return this.enrichComboList(list); + } + + // 无有效查询条件时走通用搜索 + return this.search({ keyword: '' }); + } + + /** + * 为组合商品列表批量填充子商品明细、simpleNotation 和 nameNotation。 + * + * @param {Object[]} list 组合商品原始行数组 + * @return {Promise} 包含 list 数组的富化结果 + */ + async enrichComboList(list) { + if (list.length === 0) { + return { list: [] }; + } + + // 批量查询明细 + const comboIds = list.map(row => toNumber(row.id)).filter(id => id > 0); + const itemRows = comboIds.length > 0 + ? await this.ctx.model.query( + 'SELECT * FROM wms_combo_goods_item WHERE combo_id IN (:comboIds) ORDER BY sort_order ASC, id ASC', + { + replacements: { comboIds }, + type: this.ctx.model.QueryTypes.SELECT, + } + ) + : []; + + const itemsByComboId = new Map(); + for (const item of Array.isArray(itemRows) ? itemRows : []) { + const cid = toNumber(item.combo_id); + if (!itemsByComboId.has(cid)) { + itemsByComboId.set(cid, []); + } + itemsByComboId.get(cid).push({ + id: toNumber(item.id), + combo_id: cid, + item_goods_sku_id: toNumber(item.item_goods_sku_id), + item_quantity: toNumber(item.item_quantity), + sort_order: toNumber(item.sort_order), + }); + } + + // 批量获取商品信息 + const allStockIds = []; + for (const [ , items ] of itemsByComboId) { + for (const item of items) { + allStockIds.push(item.item_goods_sku_id); + } + } + const stockInfoMap = await this.fetchStockInfoMap(allStockIds); + + const resultList = list.map(row => { + const cid = toNumber(row.id); + const items = itemsByComboId.get(cid) || []; + return { + id: cid, + combo_code: String(row.combo_code || ''), + combo_name: String(row.combo_name || ''), + combo_sku_id: toNumber(row.combo_sku_id), + custom_code: row.custom_code || null, + status: toNumber(row.status), + warehouse_id: toNumber(row.warehouse_id), + remark: String(row.remark || ''), + creator_id: toNumber(row.creator_id), + editor_id: toNumber(row.editor_id), + items, + simpleNotation: this.buildSimpleNotation(items), + nameNotation: this.buildNameNotation(items, stockInfoMap), + }; + }); + + return { list: resultList }; + } +} + +module.exports = ComboGoodsService; diff --git a/app/service/systems/deliveryOrderSummary.js b/app/service/systems/deliveryOrderSummary.js new file mode 100644 index 0000000..36c860c --- /dev/null +++ b/app/service/systems/deliveryOrderSummary.js @@ -0,0 +1,253 @@ +'use strict'; + +const Service = require('egg').Service; +const { + resolveSummaryRange, + buildDateKeys, + buildDailyMap, + addCountRows, + addShippedRows, + finalizeDailyRows, + summarizeRows, +} = require('../../lib/delivery_order_summary'); + +/** 不参与发货/订单量统计的订单状态。 */ +const CANCELLED_ORDER_STATUS = 'cancel'; +/** 库内确定拦截状态(与 report/queries/interceptOrder 口径一致)。 */ +const INTERCEPTED_AT_WAREHOUSE_STATUS = 'intercepted_at_warehouse'; +/** 未进入拦截流程的拦截状态。 */ +const INTERCEPT_STATUS_NONE = 'none'; + +/** + * 系统层:配送订单每日汇总。 + * + * 数据源为订单常用表与配送表(订单出库后迁移到配送表,迁移时删除源行,两表无重叠, + * 直接相加不会重复计数);归档表 history / 委托外仓表 outsourced 不参与统计。 + * + * 每日指标口径(各指标按自身时间字段落入统计日): + * - order_count:当日创建订单数(create_at,排除取消单); + * - dispatch_count:当日迁入配送表的订单数(配送表 dispath_time); + * - shipped_count:当日发货订单数(delivery_time,排除取消单); + * - shipped_items_total:当日发货商品件数(发货订单 items_total 合计); + * - shipped_amount:当日发货订单金额(发货订单 total_amount 合计,两位小数); + * - intercepted_count:当日拦截订单数(intercept_status != 'none' 且 intercept_time 落入当日); + * - intercepted_at_warehouse_count:当日库内确定拦截订单数(配送表 dispath_time 落入当日, + * intercept_status = 'intercepted_at_warehouse'); + * - cancelled_count:当日取消订单数(status = 'cancel' 且 updated_at 落入当日,取消操作会刷新 updated_at)。 + */ +class DeliveryOrderSummaryService extends Service { + /** + * 查询配送订单每日汇总。 + * + * @param {Object} options 查询参数。 + * @param {number} options.warehouseId 仓库ID(必填)。 + * @param {number|null} [options.storeId] 货主ID(可选,>0 时按货主过滤)。 + * @param {*} [options.startDate] 开始日期(yyyy-MM-dd,缺省为结束日往前 6 天)。 + * @param {*} [options.endDate] 结束日期(yyyy-MM-dd,缺省为今天)。 + * @return {Promise} { warehouse_id, store_id, start_date, end_date, day_count, list, summary } + */ + async queryDailySummary({ warehouseId, storeId = null, startDate = null, endDate = null } = {}) { + const normalizedWarehouseId = Number(warehouseId) || 0; + if (normalizedWarehouseId <= 0) { + const error = new Error('配送订单汇总缺少仓库上下文'); + error.code = 'INVALID_SUMMARY_REQUEST'; + throw error; + } + + const range = resolveSummaryRange({ startDate, endDate }); + const dateKeys = buildDateKeys(range.start, range.end); + const dailyMap = buildDailyMap(dateKeys); + + const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!factory) { + throw new Error('订单配送模型工厂不可用'); + } + + const [ currentModel, dispatchModel ] = await Promise.all([ + factory.getCurrentModel(normalizedWarehouseId), + factory.getDispatchModel(normalizedWarehouseId), + ]); + + const { Op } = this.app.Sequelize; + const normalizedStoreId = Number(storeId) || 0; + const storeScope = normalizedStoreId > 0 ? { store_id: normalizedStoreId } : {}; + const notCancelled = { [Op.ne]: CANCELLED_ORDER_STATUS }; + const timeWindow = () => ({ [Op.gte]: range.start, [Op.lt]: range.endExclusive }); + + const [ + currentCreatedRows, + dispatchCreatedRows, + currentShippedRows, + dispatchShippedRows, + currentInterceptedRows, + dispatchInterceptedRows, + dispatchConfirmedRows, + dispatchMigratedRows, + currentCancelledRows, + dispatchCancelledRows, + ] = await Promise.all([ + this.queryDailyCount(currentModel, 'create_at', { + ...storeScope, + status: notCancelled, + create_at: timeWindow(), + }), + this.queryDailyCount(dispatchModel, 'create_at', { + ...storeScope, + status: notCancelled, + create_at: timeWindow(), + }), + this.queryDailyShipped(currentModel, { + ...storeScope, + status: notCancelled, + delivery_time: timeWindow(), + }), + this.queryDailyShipped(dispatchModel, { + ...storeScope, + status: notCancelled, + delivery_time: timeWindow(), + }), + this.queryDailyCount(currentModel, 'intercept_time', { + ...storeScope, + intercept_status: { [Op.ne]: INTERCEPT_STATUS_NONE }, + intercept_time: timeWindow(), + }), + this.queryDailyCount(dispatchModel, 'intercept_time', { + ...storeScope, + intercept_status: { [Op.ne]: INTERCEPT_STATUS_NONE }, + intercept_time: timeWindow(), + }), + this.queryDailyCount(dispatchModel, 'dispath_time', { + ...storeScope, + intercept_status: INTERCEPTED_AT_WAREHOUSE_STATUS, + dispath_time: timeWindow(), + }), + this.queryDailyCount(dispatchModel, 'dispath_time', { + ...storeScope, + dispath_time: timeWindow(), + }), + this.queryDailyCount(currentModel, 'updated_at', { + ...storeScope, + status: CANCELLED_ORDER_STATUS, + updated_at: timeWindow(), + }), + this.queryDailyCount(dispatchModel, 'updated_at', { + ...storeScope, + status: CANCELLED_ORDER_STATUS, + updated_at: timeWindow(), + }), + ]); + + addCountRows(dailyMap, currentCreatedRows, 'order_count'); + addCountRows(dailyMap, dispatchCreatedRows, 'order_count'); + addCountRows(dailyMap, dispatchMigratedRows, 'dispatch_count'); + addCountRows(dailyMap, dispatchConfirmedRows, 'intercepted_at_warehouse_count'); + addShippedRows(dailyMap, currentShippedRows); + addShippedRows(dailyMap, dispatchShippedRows); + addCountRows(dailyMap, currentInterceptedRows, 'intercepted_count'); + addCountRows(dailyMap, dispatchInterceptedRows, 'intercepted_count'); + addCountRows(dailyMap, currentCancelledRows, 'cancelled_count'); + addCountRows(dailyMap, dispatchCancelledRows, 'cancelled_count'); + + const list = finalizeDailyRows(dateKeys, dailyMap); + + return { + warehouse_id: normalizedWarehouseId, + store_id: normalizedStoreId > 0 ? normalizedStoreId : null, + start_date: range.startDate, + end_date: range.endDate, + day_count: range.dayCount, + list, + summary: summarizeRows(list), + }; + } + + /** + * 按日期分组计数。 + * + * 分组日期按「数据库时区 → 服务器本地时区」换算后再取 DATE, + * 与 JS 侧 new Date(y, m, d) 构造的自然日边界保持一致。 + * + * @param {Object} model 订单分表模型。 + * @param {string} dateField 时间字段。 + * @param {Object} where 查询条件。 + * @return {Promise>} 聚合行(date / count)。 + */ + async queryDailyCount(model, dateField, where) { + const { fn, col } = this.app.Sequelize; + const dateColumn = this.buildLocalDateColumn(dateField); + + return await model.findAll({ + attributes: [ + [ dateColumn, 'date' ], + [ fn('COUNT', col('id')), 'count' ], + ], + where, + group: [ dateColumn ], + raw: true, + }); + } + + /** + * 按发货日期分组统计发货订单数、商品件数与订单金额。 + * + * @param {Object} model 订单分表模型。 + * @param {Object} where 查询条件。 + * @return {Promise>} 聚合行(date / count / items_total / amount)。 + */ + async queryDailyShipped(model, where) { + const { fn, col } = this.app.Sequelize; + const dateColumn = this.buildLocalDateColumn('delivery_time'); + + return await model.findAll({ + attributes: [ + [ dateColumn, 'date' ], + [ fn('COUNT', col('id')), 'count' ], + [ fn('SUM', col('items_total')), 'items_total' ], + [ fn('SUM', col('total_amount')), 'amount' ], + ], + where, + group: [ dateColumn ], + raw: true, + }); + } + + /** + * 构造按服务器本地自然日归一化的日期表达式。 + * + * @param {string} dateField 时间字段。 + * @return {Object} Sequelize 表达式 DATE(CONVERT_TZ(field, dbTz, localTz))。 + */ + buildLocalDateColumn(dateField) { + const { fn, col } = this.app.Sequelize; + return fn( + 'DATE', + fn('CONVERT_TZ', col(dateField), this.resolveDbTimezone(), this.resolveLocalTimezone()) + ); + } + + /** + * 数据库连接时区(Sequelize options.timezone,缺省 +00:00)。 + * + * @return {string} 形如 +00:00 / +08:00。 + */ + resolveDbTimezone() { + const sequelize = this.ctx.model && this.ctx.model.options ? this.ctx.model : null; + return (sequelize && sequelize.options && sequelize.options.timezone) || '+00:00'; + } + + /** + * 服务器本地时区偏移(形如 +08:00)。 + * + * @return {string} 时区偏移。 + */ + resolveLocalTimezone() { + const offsetMinutes = -new Date().getTimezoneOffset(); + const sign = offsetMinutes < 0 ? '-' : '+'; + const absMinutes = Math.abs(offsetMinutes); + const hours = String(Math.floor(absMinutes / 60)).padStart(2, '0'); + const minutes = String(absMinutes % 60).padStart(2, '0'); + return `${sign}${hours}:${minutes}`; + } +} + +module.exports = DeliveryOrderSummaryService; diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index ef45491..951eab4 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1,139 +1,1278 @@ 'use strict'; const Service = require('egg').Service; +const { normalizeWarehouseShardId } = require('../../lib/warehouse_shard_guard'); +const { isLockedOrderStatus } = require('../../lib/lock_guard'); + +const DELIVERY_ORDER_STEP = Object.freeze({ + PENDING_REVIEW: 0, + APPROVED: 1, + PROCESSING: 2, + REJECTED_OR_EXCEPTION: 3, + OUTBOUND_OR_DELIVERING: 4, + COMPLETED: 5, + CLOSED: 9, +}); + +const DEFAULT_STORE_SUBJECT_CONFIG = Object.freeze({ + max_notice_webhook_count: 5, + default_express_code: 'STO', + default_platform_code: 'TB', +}); + +const ORDER_OPERATION_CODES = Object.freeze({ + CREATE: 'ORDER_CREATE', + PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK', + EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK', + EXPRESS_POLICY_MATCH: 'ORDER_EXPRESS_POLICY_MATCH', + AUTO_EXPRESS_SKIP: 'ORDER_AUTO_EXPRESS_SKIP', + NEED_OMS_WAYBILL_WAIT: 'ORDER_NEED_OMS_WAYBILL_WAIT', +}); + +const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600; class DeliveryOrderService extends Service { - async addOrder(data, info) { - const { ctx } = this; - if (!info.warehouseId) { - return { - success: false, - message: '订单创建失败: 非法参数', - data: null, - }; - } - const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); - const { deliveryOrder, orderLines } = data.request; + getStoreSubjectConfigCacheKey(storeId) { + return `delivery_order:store:${Number(storeId || 0)}:subject_config`; + } - // 开启事务 - const transaction = await ctx.model.transaction(); + 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 { - if (!info.storeId) { - throw new Error('非法参数'); - } - if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { - throw new Error('订单信息不完整'); - } - - // 检查订单是否已存在(根据唯一索引) - const existingOrder = await DeliveryModel.findOne({ - where: { - delivery_order_code: deliveryOrder.deliveryOrderCode, - store_id: info.storeId, - warehouse_id: info.warehouseId, - }, - attributes: [ 'id' ], - transaction, + const store = await storeModel.findByPk(normalizedStoreId, { + attributes: [ 'id', 'subject_config' ], }); - if (existingOrder) { - await transaction.rollback(); - return { - success: true, - message: '订单已存在', - data: { deliveryOrderId: existingOrder.id }, - }; + 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); } - // 准备订单数据 - const orderData = await this.prepareOrderData(deliveryOrder, info); + return normalizedConfig; + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.getStoreSubjectConfig] load subject_config failed: %s', error.message); + return this.normalizeStoreSubjectConfig(null); + } + } - // 创建订单 - const createdOrder = await DeliveryModel.create(orderData, { transaction }); - const orderId = createdOrder.id; + findCodeOption(list, code) { + const normalizedCode = String(code || '').trim(); + if (!normalizedCode || !Array.isArray(list)) { + return null; + } - let itemsInfo = null; - // 添加订单明细 - if (orderLines && (orderLines.orderLine)) { - itemsInfo = await this.addOrderLines( - orderLines.orderLine, - orderId, - info, - transaction - ); - } else { - throw new Error('[订单无明细]'); + 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(); + } + + /** + * 记录待写入的订单操作日志项。 + * + * @param {Array} operationLogs 待写入的日志数组。 + * @param {string} operationCode 操作编码。 + * @param {string} message 日志内容。 + * @param {Object} [options={}] 记录选项。 + * @param {boolean} [options.prepend=false] 是否插入到数组首位。 + * @return {void} + */ + appendOrderOperationLog(operationLogs, operationCode, message, options = {}) { + if (!Array.isArray(operationLogs)) { + return; + } + + const logItem = { + operationCode, + message, + }; + + if (options && options.prepend) { + operationLogs.unshift(logItem); + return; + } + + operationLogs.push(logItem); + } + + /** + * 获取订单日志使用的操作人信息。 + * + * 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。 + * + * @return {{ id: string|null, name: string }} 操作人信息。 + */ + getOrderLogOperator() { + const { ctx } = this; + const stateUser = ctx && ctx.state && typeof ctx.state.user === 'object' && ctx.state.user + ? ctx.state.user + : null; + const ctxUser = ctx && ctx.user && typeof ctx.user === 'object' + ? ctx.user + : null; + const operatorSource = stateUser || ctxUser || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 获取订单日志使用的仓库ID。 + * + * 取值优先级:显式传入参数 -> this.store.id -> ctx.user.warehouse_id -> ctx.user.store_id。 + * + * @param {number|string|null} [preferredWarehouseId=null] 优先使用的仓库ID。 + * @return {number|string|null} 归一化后的仓库ID。 + */ + getOrderLogWarehouseId(preferredWarehouseId = null) { + const { ctx } = this; + const candidates = [ + preferredWarehouseId, + this.store && this.store.id, + ctx && ctx.user && ctx.user.warehouse_id, + ctx && ctx.user && ctx.user.store_id, + ]; + + for (const candidate of candidates) { + if (candidate === undefined || candidate === null || candidate === '') { + continue; } + return candidate; + } - // 更新订单统计信息 - 直接使用itemsInfo中的计算结果 - if (itemsInfo) { - const stats = { - items: itemsInfo.items_str || '', // 原始结构字符串 - items_count: itemsInfo.stock_count || 0, // 商品种类数 - items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果) - items_weight: itemsInfo.total_weight || 0, // 总重量 - items_hash: this.generateItemsHash(itemsInfo), // 哈希值 - items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验 - updated_at: new Date(), - }; + return null; + } - await DeliveryModel.update( - stats, - { - where: { id: orderId }, - transaction, - } - ); + /** + * 将订单操作日志写入数据库,优先批量写入。 + * + * @param {Array} operationLogs 待写入的日志数组。 + * @param {number|string} orderId 订单ID。 + * @param {Object} [options={}] 写入选项。 + * @param {number|string} [options.warehouseId] 订单所属仓库ID。 + * @param {Object} [options.transaction] 事务对象(可选)。 + * @return {Promise} 无返回值。 + */ + async flushOrderOperationLogs(operationLogs, orderId, options = {}) { + const { ctx } = this; + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + const requestOptions = options && typeof options === 'object' ? options : {}; + let operator = this.getOrderLogOperator(); + const warehouseId = this.getOrderLogWarehouseId(requestOptions.warehouseId ?? requestOptions.warehouse_id); + // 根据创建渠道覆盖操作人名称 + const createChannel = String(requestOptions.createChannel ?? requestOptions.create_channel ?? '').trim().toUpperCase(); + if (createChannel === 'QM') { + operator = { id: null, name: '奇门' }; + } else if (createChannel === 'API') { + operator = { id: null, name: 'API' }; + } - // 记录详细日志 - ctx.logger.info('[订单统计信息已更新]', { + if (!Array.isArray(operationLogs) || operationLogs.length === 0) { + return; + } + + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] operationLog service unavailable', { + orderId, + logs: operationLogs.length, + }); + return; + } + + const payloads = operationLogs.map(logItem => ({ + businessType: 'order', + businessId: orderId, + operationCode: logItem.operationCode, + operator, + extras: { + warehouseId, + message: logItem.message, + }, + transaction: requestOptions.transaction, + })); + + try { + const results = await operationLogService.createOperationLogs(payloads, { + transaction: requestOptions.transaction, + }); + + for (let index = 0; index < payloads.length; index += 1) { + if (results[index]) { + continue; + } + const logItem = operationLogs[index] || {}; + ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志失败,不影响业务', { orderId, - orderCode: deliveryOrder.deliveryOrderCode, - stats: { - items_count: stats.items_count, - items_total: stats.items_total, - items_weight: stats.items_weight, - items_hash_preview: stats.items_hash?.substring(0, 8) + '...', - items_crc: stats.items_crc, - }, + operationCode: logItem.operationCode, + message: logItem.message, }); } - - // 异步处理:订单入队列 - this.addOrderToQueue(orderId, info.warehouseId); - - await transaction.commit(); - - return { - success: true, - message: '订单创建成功', - data: { - orderId, - stats: itemsInfo ? { - items_count: itemsInfo.stock_count, - items_total: itemsInfo.item_total_count, - items_weight: itemsInfo.total_weight, - } : null, - }, - }; - } catch (error) { - console.error('创建订单失败:', error); - // 回滚事务 - await transaction.rollback(); - - return { - success: false, - message: `订单创建失败: ${error.message}`, - data: null, - }; + ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 批量写入操作日志异常,不影响业务', { + orderId, + error: error.message, + }); } } /** - * 生成订单结构哈希值 - * 直接使用itemsInfo中的items_str - * @param itemsInfo - */ + * 按平台码解析平台列表项,优先基础平台,再匹配平台设置。 + * + * @param {Array} platformList 平台列表。 + * @param {string} platformCode 平台编码。 + * @return {Object|null} 匹配到的平台项。 + */ + findPlatformOptionByCode(platformList, platformCode) { + const normalizedCode = String(platformCode || '').trim(); + if (!normalizedCode || !Array.isArray(platformList)) { + return null; + } + + const basePlatform = platformList.find(item => item + && !item.is_system_setting + && String(item.code || item.value || '').trim() === normalizedCode) || null; + if (basePlatform) { + return basePlatform; + } + + return platformList.find(item => item + && item.is_system_setting + && String(item.code || item.value || '').trim() === normalizedCode) || null; + } + + /** + * 获取平台快照里的系统平台码。 + * + * @param {Object} option 平台项。 + * @param {string} fallbackCode 兜底编码。 + * @return {string} 系统平台码。 + */ + getPlatformSnapshotCode(option, fallbackCode = '') { + return String(option && (option.platform_code || option.code || option.value || fallbackCode) || '').trim(); + } + + /** + * 获取平台快照里的系统平台名称。 + * + * @param {Object} option 平台项。 + * @return {string} 系统平台名称。 + */ + getPlatformSnapshotName(option) { + if (!option || typeof option !== 'object') { + return ''; + } + + return String(option.platform_name || option.name || option.label || option.code || option.value || '').trim(); + } + + /** + * 解析平台快照。 + * + * 优先级: + * 1. 先匹配平台列表里的基础平台项; + * 2. 再匹配平台列表里的系统设置项; + * 3. 兜底:合约 policy_config.default_platform_code。 + * + * @param {string} sourcePlatformCode 外部平台编码。 + * @param {Object} storeSubjectConfig 合约 policy_config。 + * @param {Object} [policyConfig={}] 合约策略配置。 + * @param {Object} [info={}] 上下文信息。 + * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 + * @return {Promise} 平台快照。 + */ + async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, policyConfig = {}, info = {}, operationLogs = []) { + const platformList = await this.ctx.service.systems.platform.getPlatformList( + false, + false, + info.warehouseId + ); + const externalCode = String(sourcePlatformCode || '').trim(); + const matchedPlatform = this.findPlatformOptionByCode(platformList, externalCode); + + if (matchedPlatform) { + return { + sysPlatformCode: this.getPlatformSnapshotCode(matchedPlatform, externalCode), + sysPlatformName: this.getPlatformSnapshotName(matchedPlatform), + }; + } + + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform code not found in platform service list', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + sourcePlatformCode: externalCode, + }); + + // 兜底优先级:合约 policy_config + const policyDefaultCode = String(policyConfig && policyConfig.default_platform_code || '').trim(); + const ownerDefaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim(); + const defaultCode = policyDefaultCode || ownerDefaultCode; + const fallbackPlatform = defaultCode ? this.findPlatformOptionByCode(platformList, defaultCode) : null; + const fallbackPlatformName = this.getPlatformSnapshotName(fallbackPlatform) || defaultCode; + + if (defaultCode) { + const fallbackSource = policyDefaultCode ? 'policy_config' : 'subject_config'; + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.PLATFORM_FALLBACK, + `平台编码${externalCode}匹配不到平台,已转为默认平台:${fallbackPlatformName}(来源:${fallbackSource})` + ); + + if (fallbackPlatform) { + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform code fallback to default', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + sourcePlatformCode: externalCode, + defaultPlatformCode: defaultCode, + fallbackSource, + }); + + return { + sysPlatformCode: this.getPlatformSnapshotCode(fallbackPlatform, defaultCode), + sysPlatformName: fallbackPlatformName, + }; + } + } + + 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: fallbackPlatformName || '', + }; + } + + /** + * 通过快递设置表解析系统快递编码。 + * + * 说明:wms_express_setting 以 `code` 作为匹配键,以 `express_code` 作为系统快递编码。 + * 由于该表带有 `warehouse_id` 作用域,这里优先按 `warehouse_id + code` 进行限定查询, + * 命中后直接返回对应的系统快递编码。 + * + * @param {string} logisticsCode 外部快递编码。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 系统快递编码,未命中时返回空字符串。 + */ + async resolveExpressCodeFromSetting(logisticsCode, warehouseId) { + const expressSetting = await this.resolveExpressSettingSnapshot(logisticsCode, warehouseId); + return String(expressSetting && expressSetting.expressCode || '').trim(); + } + + /** + * 通过快递设置表读取快递映射快照。 + * + * @param {string} logisticsCode 外部快递编码。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 命中的快递设置快照,未命中返回 null。 + */ + async resolveExpressSettingSnapshot(logisticsCode, warehouseId) { + const normalizedLogisticsCode = String(logisticsCode || '').trim(); + if (!normalizedLogisticsCode) { + return null; + } + + const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting; + if (!expressSettingModel || typeof expressSettingModel.findOne !== 'function') { + return null; + } + + const where = { + code: normalizedLogisticsCode, + }; + const normalizedWarehouseId = Number(warehouseId || 0); + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + where.warehouse_id = normalizedWarehouseId; + } + + const expressSetting = await expressSettingModel.findOne({ + attributes: [ 'code', 'name', 'express_code' ], + where, + raw: true, + }); + + if (!expressSetting) { + return null; + } + + return { + code: String(expressSetting.code || normalizedLogisticsCode).trim(), + name: String(expressSetting.name || '').trim(), + expressCode: String(expressSetting.express_code || '').trim(), + }; + } + + /** + * 解析是否启用外部快递编码。 + * + * 优先级:显式值 -> policy_config,均未提供时默认关闭。 + * + * @param {Object} storeSubjectConfig 合约 policy_config(与 policyConfig 同源)。 + * @param {Object} policyConfig 合约策略配置。 + * @param {any} explicitValue 显式指定值。 + * @return {boolean} 是否启用外部快递编码。 + */ + resolveEnableExternalExpressCode(storeSubjectConfig, policyConfig = {}, explicitValue = undefined) { + if (explicitValue !== undefined) { + return this.normalizePolicyFlag(explicitValue); + } + + if (policyConfig && Object.prototype.hasOwnProperty.call(policyConfig, 'enable_external_express_code')) { + return this.normalizePolicyFlag(policyConfig.enable_external_express_code); + } + + if (storeSubjectConfig && Object.prototype.hasOwnProperty.call(storeSubjectConfig, 'enable_external_express_code')) { + return this.normalizePolicyFlag(storeSubjectConfig.enable_external_express_code); + } + + return false; + } + + /** + * 解析订单快递快照。 + * + * 默认快递编码统一从合约 policy_config 读取。 + * + * 分支路由: + * 1. 先读取是否启用外部快递编码开关; + * 2. 开关关闭时,直接使用合约默认快递回填四个快递字段; + * 3. 开关开启时,先匹配 wms_express_setting,再匹配 wms_express,最后回退默认快递。 + * + * @param {string} logisticsCode 外部快递编码。 + * @param {Object} storeSubjectConfig 合约 policy_config。 + * @param {Object} [info={}] 上下文信息,可含 policyConfig / enableExternalExpressCode / warehouseId。 + * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 + * @return {Promise} 快递快照。 + */ + async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}, operationLogs = []) { + const expressList = await this.ctx.service.systems.express.getExpressList(); + const externalCode = String(logisticsCode || '').trim(); + + // 默认快递编码统一从合约 policy_config 读取 + const policyConfig = info && info.policyConfig && typeof info.policyConfig === 'object' + ? info.policyConfig + : {}; + const contractConfig = storeSubjectConfig && typeof storeSubjectConfig === 'object' + ? storeSubjectConfig + : {}; + const defaultCode = String( + contractConfig.default_express_code + || policyConfig.default_express_code + || '' + ).trim(); + + const fallbackExpress = this.findCodeOption(expressList, defaultCode) + || this.findCodeOption(expressList, DEFAULT_STORE_SUBJECT_CONFIG.default_express_code); + const fallbackLogisticsCode = String( + fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode || DEFAULT_STORE_SUBJECT_CONFIG.default_express_code) + || defaultCode + || DEFAULT_STORE_SUBJECT_CONFIG.default_express_code + ).trim(); + const fallbackLogisticsName = this.getOptionName(fallbackExpress); + const explicitEnableExternalExpressCode = info && Object.prototype.hasOwnProperty.call(info, 'enableExternalExpressCode') + ? info.enableExternalExpressCode + : undefined; + const isEnableExternalExpressCode = this.resolveEnableExternalExpressCode( + storeSubjectConfig, + policyConfig, + explicitEnableExternalExpressCode + ); + + this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 快递解析开始', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + logisticsCode: externalCode, + enableExternalExpressCode: isEnableExternalExpressCode, + defaultExpressCode: defaultCode, + }); + + if (!isEnableExternalExpressCode) { + this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 未启用外部快递编码,直接使用默认快递', { + deliveryOrderCode: info.deliveryOrderCode, + logisticsCode: externalCode, + matched: false, + fallbackLogisticsCode, + fallbackLogisticsName, + }); + + return { + logisticsCode: fallbackLogisticsCode, + logisticsName: fallbackLogisticsName, + sysLogisticsCode: fallbackLogisticsCode, + sysLogisticsName: fallbackLogisticsName, + weightType: 0, + }; + } + + const expressSetting = await this.resolveExpressSettingSnapshot(externalCode, info.warehouseId); + if (expressSetting) { + const matchedSysExpress = this.findCodeOption(expressList, expressSetting.expressCode); + const matchedSysLogisticsCode = String( + matchedSysExpress && (matchedSysExpress.code || matchedSysExpress.value || matchedSysExpress.express_code || expressSetting.expressCode) + || expressSetting.expressCode + || '' + ).trim(); + const matchedSysLogisticsName = this.getOptionName(matchedSysExpress); + + this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 外部快递编码命中 wms_express_setting 映射', { + deliveryOrderCode: info.deliveryOrderCode, + logisticsCode: externalCode, + matched: true, + source: 'wms_express_setting', + mappedLogisticsCode: String(expressSetting.code || externalCode).trim(), + mappedLogisticsName: String(expressSetting.name || '').trim(), + sysLogisticsCode: matchedSysLogisticsCode, + sysLogisticsName: matchedSysLogisticsName, + }); + + return { + logisticsCode: String(expressSetting.code || externalCode).trim(), + logisticsName: String(expressSetting.name || '').trim(), + sysLogisticsCode: matchedSysLogisticsCode, + sysLogisticsName: matchedSysLogisticsName, + weightType: 0, + }; + } + + const matchedExpress = this.findCodeOption(expressList, externalCode); + + if (matchedExpress) { + const matchedLogisticsCode = String( + matchedExpress.code || matchedExpress.value || matchedExpress.express_code || externalCode + ).trim(); + const matchedLogisticsName = this.getOptionName(matchedExpress); + + this.ctx.logger.info('[DeliveryOrderService.resolveExpressSnapshot] 外部快递编码命中系统快递列表', { + deliveryOrderCode: info.deliveryOrderCode, + logisticsCode: externalCode, + matched: true, + source: 'wms_express', + matchedLogisticsCode, + matchedLogisticsName, + }); + + return { + logisticsCode: matchedLogisticsCode, + logisticsName: matchedLogisticsName, + sysLogisticsCode: matchedLogisticsCode, + sysLogisticsName: matchedLogisticsName, + weightType: 0, + }; + } + if (fallbackExpress) { + this.ctx.logger.warn('[DeliveryOrderService.resolveExpressSnapshot] 快递编码未匹配到任何快递,兜底为默认快递', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + logisticsCode: externalCode, + matched: false, + fallbackLogisticsCode, + fallbackLogisticsName, + defaultExpressCode: defaultCode, + }); + + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_FALLBACK, + `快递编码${externalCode}匹配不到快递,已转为默认快递:${fallbackLogisticsName || fallbackLogisticsCode}` + ); + + return { + logisticsCode: fallbackLogisticsCode, + logisticsName: fallbackLogisticsName, + sysLogisticsCode: fallbackLogisticsCode, + sysLogisticsName: fallbackLogisticsName, + weightType: 0, + }; + } + + this.ctx.logger.warn('[DeliveryOrderService.resolveExpressSnapshot] 默认快递不在快递列表中,使用全局兜底快递', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + logisticsCode: externalCode, + matched: false, + fallbackLogisticsCode, + fallbackLogisticsName, + defaultExpressCode: defaultCode, + }); + + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_FALLBACK, + `快递编码${externalCode}匹配不到快递,兜底快递:${fallbackLogisticsName || fallbackLogisticsCode}` + ); + + return { + logisticsCode: fallbackLogisticsCode, + logisticsName: fallbackLogisticsName, + sysLogisticsCode: fallbackLogisticsCode, + sysLogisticsName: fallbackLogisticsName, + weightType: 0, + }; + } + + /** + * 归一化“是否需要回 OMS 取号”入参为 0/1。 + * 兼容 1/0、'1'/'0'、true/false、'true'/'false'、'Y'/'N'、'YES'/'NO', + * 其余非法值一律按 0 处理。 + * + * @param {*} value 原始入参。 + * @return {number} 1=需要回 OMS 取号,0=不需要。 + */ + normalizeNeedOmsWaybill(value) { + if (value === true) { + return 1; + } + if (value === false || value === null || value === undefined) { + return 0; + } + + const text = String(value).trim().toUpperCase(); + return [ '1', 'TRUE', 'Y', 'YES' ].includes(text) ? 1 : 0; + } + + /** + * 创建发货单。 + * + * @param {Object} data 奇门/系统订单入参。 + * @param {Object} info 当前仓库与货主上下文。 + * @param {string} [createChannel=''] 订单创建渠道标识。 + * @return {Promise} 创建结果。 + */ + async addOrder(data, info, createChannel = '') { + const { ctx } = this; + let warehouseIdStr; + try { + warehouseIdStr = normalizeWarehouseShardId(info.warehouseId); + } catch (e) { + return { + success: false, + message: `订单创建失败: ${e.message}`, + data: null, + }; + } + info = { ...info, warehouseId: warehouseIdStr }; + // 跨分表单号查重模型:dispatch/history 模型获取可能执行 DDL(隐式提交),必须在事务外完成 + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseIdStr); + const DeliveryDispatchModel = await ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseIdStr); + const DeliveryHistoryModel = await ctx.model.OrderDeliveryFactory.getHistoryModel(warehouseIdStr); + const { deliveryOrder, orderLines } = data.request; + + // 请求级 extendProps,携带 ewaybill_order_code 等关键字段 + const requestExtendProps = (data.request && data.request.extendProps && Object.keys(data.request.extendProps).length > 0) + ? data.request.extendProps + : undefined; + + const normalizedCreateChannel = String( + createChannel + || deliveryOrder.createChannel + || deliveryOrder.create_channel + || 'MANUAL' + ).trim().toUpperCase() || 'MANUAL'; + + // 是否需要回 OMS 取号:仅 openapi(API)创建来源使用, + // 支持请求根节点(data.request.need_oms_waybill)与 deliveryOrder 内两种传参位置, + // 其他渠道(QM/MANUAL/STOCKOUT)一律强制 0,避免被非法入参污染。 + const needOmsWaybill = normalizedCreateChannel === 'API' + ? this.normalizeNeedOmsWaybill( + data.request.need_oms_waybill + ?? data.request.needOmsWaybill + ?? deliveryOrder.need_oms_waybill + ?? deliveryOrder.needOmsWaybill + ) + : 0; + + // 订单 id 序列表初始化可能执行 DDL(隐式提交),必须在事务外先完成 + try { + await ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseIdStr); + } catch (error) { + // 初始化失败不降级:后续发号会直接失败并回滚建单,绝不让分表自增介入发号 + ctx.logger.warn('[DeliveryOrderService.addOrder] 序列表初始化失败,本次建单将失败:', error.message); + } + + // 单次建单执行体:重试时复用,事务随每次尝试重新开启 + const createOnce = async operationLogs => { + // 开启事务 + const transaction = await ctx.model.transaction(); + + try { + if (!info.storeId) { + throw new Error('非法参数'); + } + if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { + throw new Error('订单信息不完整'); + } + + // 检查订单是否已存在:依次查 current/dispatch/history 分表 + // (各分表唯一索引均为 单号+货主+仓库,跨表间约束独立,必须逐表查重) + const codeDuplicateWhere = { + delivery_order_code: deliveryOrder.deliveryOrderCode, + store_id: info.storeId, + warehouse_id: info.warehouseId, + }; + const [ existingOrder, existingDispatchOrder, existingHistoryOrder ] = await Promise.all([ + DeliveryModel.findOne({ + where: codeDuplicateWhere, + attributes: [ 'id' ], + transaction, + }), + DeliveryDispatchModel.findOne({ + where: codeDuplicateWhere, + attributes: [ 'id' ], + transaction, + }), + DeliveryHistoryModel.findOne({ + where: codeDuplicateWhere, + attributes: [ 'id' ], + transaction, + }), + ]); + + const duplicateOrder = existingOrder || existingDispatchOrder || existingHistoryOrder; + if (duplicateOrder) { + const duplicateLocation = existingOrder + ? 'current' + : (existingDispatchOrder ? 'dispatch' : 'history'); + ctx.logger.warn( + `[DeliveryOrderService.addOrder] 跨分表单号重复拒绝: ${deliveryOrder.deliveryOrderCode}, 命中的表: ${duplicateLocation}, 已存在订单 id: ${duplicateOrder.id}` + ); + await transaction.rollback(); + return { + success: true, + message: '订单已存在', + data: { deliveryOrderId: duplicateOrder.id }, + }; + } + + // 准备订单数据 + const step = await this.resolveOrderStep(info, transaction); + const orderData = await this.prepareOrderData( + deliveryOrder, + info, + normalizedCreateChannel, + step, + operationLogs, + requestExtendProps, + needOmsWaybill + ); + + // 创建订单:订单 id 统一由仓库序列表分配,显式写入 current 分表。 + // 不再回退分表自增:分表自增序列与序列表发号区间重叠会产生冲突 id, + // 发号失败时直接抛错,由事务回滚,杜绝脏 id 落库。 + const orderId = await ctx.model.OrderDeliveryFactory.allocateOrderId(warehouseIdStr, transaction, 'current'); + + // 将建单渠道注入 info,供 addOrderLines 区分 MANUAL 降级逻辑 + info.createChannel = normalizedCreateChannel; + + let itemsInfo = null; + // 添加订单明细(先写明细、后写主表:库存预占失败直接回滚,不留悬挂主表行) + if (orderLines && (orderLines.orderLine)) { + itemsInfo = await this.addOrderLines( + orderLines.orderLine, + orderId, + info, + transaction + ); + } else { + throw new Error('[订单无明细]'); + } + + // 统计列(items / items_hash / items_crc)在 wms_order_delivery_* 上均为二级索引列, + // 必须与主表 INSERT 同一条语句写入:先插占位值(''/0/NULL)再 UPDATE 回写, + // 会让并发建单在同一索引区间反复“删标记旧条目 + 插入新条目”, + // 批量推单高并发下必然死锁(生产 2026-09-10 单批 354 个事务因此失败)。 + const stats = this.buildOrderStats(itemsInfo, deliveryOrder); + await DeliveryModel.create({ ...orderData, ...stats, id: orderId }, { transaction }); + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.CREATE, + `订单创建成功,orderId:${orderId}`, + { prepend: true } + ); + + // 快递策略命中时只覆盖非索引的快递字段(不动 items/items_hash/items_crc) + const expressOverride = {}; + if (itemsInfo) { + // ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) ===== + // enable_external_express_code 开启时仅"纯货主维度"策略参与漏斗,命中后覆盖外部快递匹配结果; + // 关闭时全维度策略参与,沿用原有逻辑 + try { + const funnelPolicyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId); + const enableExternalExpressCode = this.resolveEnableExternalExpressCode(funnelPolicyConfig, funnelPolicyConfig); + const receiverInfo = deliveryOrder.receiverInfo; + const shopNick = deliveryOrder.shopNick; + // 外部编码开启:仅需货主ID即可参与漏斗(只匹配纯货主维度策略); + // 外部编码关闭:需 shopNick 或收货省/市信息 + const hasEnoughData = enableExternalExpressCode + ? Boolean(info.storeId) + : Boolean(shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city))); + + if (hasEnoughData) { + const address = [ + receiverInfo?.province || '', + receiverInfo?.city || '', + receiverInfo?.area || '', + receiverInfo?.town || '', + receiverInfo?.detail_address || '', + ].join('').trim(); + + const matchResult = await ctx.service.systems.expressPolicy.matchPolicy( + info.warehouseId, + { + storeId: info.storeId, + customShopName: shopNick || '', + address: address || '', + weight: itemsInfo.total_weight || null, + // 从订单商品聚合的违禁品类型ID(StockWarehouse.prohibited_id 去重) + prohibitedTypeIds: itemsInfo && Array.isArray(itemsInfo.prohibited_type_ids) + ? itemsInfo.prohibited_type_ids + : null, + }, + { + // 启用外部编码时仅匹配纯货主维度策略,命中后覆盖外部快递映射结果 + onlyStoreDimension: enableExternalExpressCode, + } + ); + + if (matchResult && matchResult.expressCode) { + const expressList = await ctx.service.systems.express.getExpressList(); + const matchedExpress = expressList.find( + item => item && String(item.code || item.value || '').trim() === String(matchResult.expressCode).trim() + ); + + let logisticsCode; + let logisticsName; + let sysLogisticsCode; + let sysLogisticsName; + + if (matchedExpress) { + if (matchedExpress.is_system_setting) { + // 自定义映射:sys 写映射的系统快递,logistics 写自定义编码 + sysLogisticsCode = String(matchedExpress.express_code || '').trim(); + const sysItem = expressList.find( + item => item && !item.is_system_setting && String(item.code || item.value || '').trim() === sysLogisticsCode + ); + sysLogisticsName = sysItem ? String(sysItem.name || sysItem.label || sysLogisticsCode).trim() : sysLogisticsCode; + logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); + logisticsName = String(matchedExpress.alias || matchedExpress.name || logisticsCode).trim(); + } else { + // 系统快递:4 字段一致 + logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); + logisticsName = String(matchedExpress.name || matchedExpress.label || logisticsCode).trim(); + sysLogisticsCode = logisticsCode; + sysLogisticsName = logisticsName; + } + } else { + // 未在列表中,fallback + logisticsCode = String(matchResult.expressCode).trim(); + logisticsName = logisticsCode; + sysLogisticsCode = logisticsCode; + sysLogisticsName = logisticsCode; + } + + expressOverride.logistics_code = logisticsCode; + expressOverride.logistics_name = logisticsName; + expressOverride.sys_logistics_code = sysLogisticsCode; + expressOverride.sys_logistics_name = sysLogisticsName; + expressOverride.weight_type = matchResult.weightType; + + // 写入操作日志:命中了哪条策略 + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_POLICY_MATCH, + `快递策略命中: ${matchResult.policyName || '未知'}(${matchResult.policyId || '?'}) → ${sysLogisticsName || sysLogisticsCode}` + ); + + ctx.logger.info('[ExpressPolicyMatch] 策略命中(延迟匹配)', { + orderId, + orderCode: deliveryOrder.deliveryOrderCode, + logisticsCode, + sysLogisticsCode, + weightType: matchResult.weightType, + policyName: matchResult.policyName, + policyId: matchResult.policyId, + totalWeight: itemsInfo.total_weight, + }); + } else if (hasEnoughData) { + // 策略未命中:记快递降级日志(取已落库的初始快递值) + const fallbackCode = orderData.sys_logistics_code || orderData.logistics_code; + const fallbackName = orderData.sys_logistics_name || orderData.logistics_name; + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_FALLBACK, + enableExternalExpressCode + ? `未命中货主快递策略,保留外部快递: ${fallbackName || fallbackCode}` + : `未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}` + ); + } + } + } catch (policyErr) { + ctx.logger.warn('[ExpressPolicyMatch] 策略匹配异常,跳过', { + orderId, + error: policyErr.message, + }); + } + + if (Object.keys(expressOverride).length > 0) { + await DeliveryModel.update( + expressOverride, + { + where: { id: orderId }, + transaction, + } + ); + } + + // 记录详细日志 + ctx.logger.info('[订单统计信息已更新]', { + orderId, + orderCode: deliveryOrder.deliveryOrderCode, + stats: { + items_count: stats.items_count, + items_total: stats.items_total, + items_weight: stats.items_weight, + items_hash_preview: stats.items_hash?.substring(0, 8) + '...', + items_crc: stats.items_crc, + }, + }); + } + + await transaction.commit(); + + await this.flushOrderOperationLogs(operationLogs, orderId, { + warehouseId: info.warehouseId, + createChannel: normalizedCreateChannel, + }); + + // 异步处理订单后续流程 + this.asyncProcessOrderCreated(orderId, info, normalizedCreateChannel).catch(error => { + ctx.logger.warn(`[DeliveryOrderService.addOrder] asyncProcessOrderCreated failed: ${error.message}`, { + orderId, + error: error.message, + }); + }); + + return { + success: true, + message: '订单创建成功', + data: { + orderId, + step, + stats: itemsInfo ? { + items_count: itemsInfo.stock_count, + items_total: itemsInfo.item_total_count, + items_weight: itemsInfo.total_weight, + source_order_codes: (itemsInfo.stats && itemsInfo.stats.source_order_codes) || [], + } : null, + }, + }; + + } catch (error) { + console.error('创建订单失败:', error); + // 回滚事务(安全处理,防止事务已结束导致二次回滚异常) + await transaction.rollback().catch(rollbackErr => { + console.error('回滚事务失败:', rollbackErr.message); + }); + + throw error; + } + }; + + // 重试约定: + // 1. 主键冲突(分表自增水位与已有数据重叠)修复水位后重试一次; + // 2. 死锁 / 锁等待超时:批量推单高并发下的瞬时竞争,事务已整体回滚,退避后重放。 + const MAX_CREATE_ATTEMPTS = 3; + for (let attempt = 1; attempt <= MAX_CREATE_ATTEMPTS; attempt++) { + const operationLogs = []; + try { + return await createOnce(operationLogs); + } catch (error) { + if (this.isPrimaryKeyDuplicate(error) && attempt === 1) { + try { + const factory = ctx.model.OrderDeliveryFactory; + const tableName = factory.generateTableName(warehouseIdStr, 'current'); + await factory.ensureAutoIncrementWatermark(tableName); + ctx.logger.warn('[DeliveryOrderService.addOrder] 主键冲突,已修复自增水位,重试建单', { + deliveryOrderCode: deliveryOrder && deliveryOrder.deliveryOrderCode, + warehouseId: warehouseIdStr, + storeId: info.storeId, + error: error.message, + }); + } catch (repairError) { + ctx.logger.warn('[DeliveryOrderService.addOrder] 自增水位修复失败,放弃重试', { + error: repairError.message, + }); + } + continue; + } + + // 死锁/锁等待:退避后重试(带抖动,避免同一批请求再次同时竞争) + if (this.isRetryableLockError(error) && attempt < MAX_CREATE_ATTEMPTS) { + ctx.logger.warn('[DeliveryOrderService.addOrder] 数据库锁冲突,退避后重试建单', { + deliveryOrderCode: deliveryOrder && deliveryOrder.deliveryOrderCode, + warehouseId: warehouseIdStr, + storeId: info.storeId, + attempt, + maxAttempts: MAX_CREATE_ATTEMPTS, + error: error.message, + }); + await new Promise(resolve => setTimeout(resolve, 30 * attempt + Math.floor(Math.random() * 50))); + continue; + } + + return { + success: false, + message: `订单创建失败: ${this.formatOrderCreateError(error, deliveryOrder)}`, + data: null, + }; + } + } + + return { + success: false, + message: '订单创建失败: 重试后仍未成功,请稍后重试', + data: null, + }; + } + + /** + * 构建订单主表统计列(随 INSERT 一次写入)。 + * + * wms_order_delivery_* 的 items / items_hash / items_crc 都是二级索引列, + * 只能在 INSERT 时写入:若先插占位值再 UPDATE 回写,高并发建单时 + * 几十行占位值(''/0/NULL)落在同一索引区间,会反复触发“删标记 + 插入” + * 而互相死锁。 + * + * @param {Object} itemsInfo addOrderLines 返回的明细统计信息。 + * @param {Object} deliveryOrder 订单主信息。 + * @return {Object} 可直接并入 INSERT 的统计字段。 + */ + buildOrderStats(itemsInfo, deliveryOrder) { + return { + items: itemsInfo.items_str || '', // 原始结构字符串 + items_count: itemsInfo.stock_count || 0, // 商品种类数 + items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果) + items_weight: itemsInfo.total_weight || 0, // 总重量 + items_hash: this.generateItemsHash(itemsInfo), // 哈希值 + items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验 + source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode, + // 是否含序列号管理商品:建单时按 stock_warehouse.is_sn_mgmt 聚合,随 INSERT 一次写入 + has_sn_item: itemsInfo.has_sn_item ? 'Y' : 'N', + // 主表 timestamps:false,updated_at 需显式写入(原先由统计列 UPDATE 顺带更新) + updated_at: new Date(), + }; + } + + /** + * 判断是否为可重试的数据库锁冲突(死锁 / 锁等待超时)。 + * + * 建单事务整体回滚后重放是安全的(订单 id 由序列表重新发号), + * 批量推单场景下瞬时竞争可自愈。 + * + * @param {Error} error 原始异常。 + * @return {boolean} 是否可重试。 + */ + isRetryableLockError(error) { + if (!error) { + return false; + } + + const original = error.original || error.parent || error; + const code = (original && (original.code || original.errno)) || error.code; + if (code === 1213 || code === 1205 || code === 'ER_LOCK_DEADLOCK' || code === 'ER_LOCK_WAIT_TIMEOUT') { + return true; + } + + const message = String((original && original.sqlMessage) || error.message || '').toLowerCase(); + return message.includes('deadlock found') || message.includes('lock wait timeout'); + } + + /** + * 判断是否为分表主键自增冲突。 + * + * 分表自增水位被破坏(显式 id 导入、表重建、迁移复制 id)后,自增插入会与 + * 已有主键重叠,Sequelize 抛出的 UniqueConstraintError 对外 message 为 + * “Validation error”,需按 errors[].path 识别。 + * + * @param {Error} error Sequelize 错误对象。 + * @return {boolean} 是否为主键唯一冲突。 + */ + isPrimaryKeyDuplicate(error) { + if (!error || error.name !== 'SequelizeUniqueConstraintError' || !Array.isArray(error.errors)) { + return false; + } + + return error.errors.some(item => item + && item.type === 'unique violation' + && (item.path === 'PRIMARY' || item.path === 'id')); + } + + /** + * 将建单异常格式化为可读的失败原因。 + * + * Sequelize 唯一约束错误的 message 固定为 “Validation error”,若不解析 + * errors/parent 会掩盖真实原因,这里优先提取具体冲突字段与值。 + * + * @param {Error} error 原始异常。 + * @param {Object} [deliveryOrder] 请求中的发货单信息。 + * @return {string} 可读的失败原因。 + */ + formatOrderCreateError(error, deliveryOrder) { + if (error && error.name === 'SequelizeUniqueConstraintError' && Array.isArray(error.errors)) { + const primaryDup = error.errors.find(item => item + && item.type === 'unique violation' + && (item.path === 'PRIMARY' || item.path === 'id')); + if (primaryDup) { + return `订单ID主键冲突(id=${primaryDup.value} 已被占用):分表自增水位与已有数据重叠,已尝试修复并重试,请再次提交`; + } + + const codeDup = error.errors.find(item => item && item.path === 'delivery_order_code'); + if (codeDup) { + const orderCode = (deliveryOrder && deliveryOrder.deliveryOrderCode) || codeDup.value; + return `订单号 ${orderCode} 已存在`; + } + + const firstItem = error.errors[0] || {}; + return String(firstItem.message || error.message || '唯一约束冲突').trim(); + } + + if (this.isRetryableLockError(error)) { + return '数据库锁冲突(死锁/锁等待超时),系统已自动重试,请稍后再试'; + } + + const parentSqlMessage = error && error.parent && error.parent.sqlMessage; + if (parentSqlMessage) { + return `${error.message} (${parentSqlMessage})`; + } + + return String((error && error.message) || '').trim() || '未知错误'; + } + + /** + * 根据货主仓库策略解析订单步骤。 + * 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, warehouse_use_status=1),则抛出错误拒绝创建。 + * + * @param {Object} info 当前仓库与货主上下文,需包含 storeId 和 warehouseId。 + * @param {Object|null} transaction 数据库事务。 + * @return {Promise} 订单步骤,需审批返回 0,免审批返回 1。 + * @throws {Error} 货主未与当前仓库签约时抛出。 + */ + async resolveOrderStep(info, transaction = null) { + const { ctx } = this; + const storeId = Number(info && info.storeId) || 0; + const warehouseId = Number(info && info.warehouseId) || 0; + + if (storeId <= 0 || warehouseId <= 0) { + return DELIVERY_ORDER_STEP.PENDING_REVIEW; + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + attributes: [ 'id' ], + transaction, + raw: true, + }); + + if (!relation) { + throw new Error('仓库方已暂停接收推单,无法创建订单,请联系仓库方'); + } + + const relation2 = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + attributes: [ 'id' ], + transaction, + raw: true, + }); + + if (!relation2) { + throw new Error('仓库已禁用,无法创建订单,如需继续推单请进入货主后台修改配置'); + } + + const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; + const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function' + ? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id, transaction) + : null; + + return Number(policyConfig && policyConfig.need_order_approval) === 0 + ? DELIVERY_ORDER_STEP.APPROVED + : DELIVERY_ORDER_STEP.PENDING_REVIEW; + } + + /** + * 生成订单结构哈希值。 + * + * @param {Object} itemsInfo 订单明细信息。 + * @return {string} 结构哈希值。 + */ generateItemsHash(itemsInfo) { const crypto = require('crypto'); @@ -149,28 +1288,145 @@ class DeliveryOrderService extends Service { /** * 计算CRC32校验码 - * @param str + * @param {string} str 待计算字符串 + * @return {number} CRC32校验值 */ calculateCRC32(str) { if (!str) return 0; try { const crc32 = require('crc-32'); - return crc32.str(str) >>> 0; // 转为无符号整数 + const crc = crc32.str(str); + return crc >= 0 ? crc : crc + 4294967296; } catch (error) { // 降级方案:简单校验和 let crc = 0; for (let i = 0; i < str.length; i++) { - crc = (crc + str.charCodeAt(i)) & 0xFFFFFFFF; + crc = (crc + str.charCodeAt(i)) % 4294967296; } return crc; } } - // 准备订单数据 - // 准备订单数据 - async prepareOrderData(deliveryOrder, info) { - const { ctx, service } = this; + /** + * 标准化订单来源键(上游对接应用的 appKey)。 + * + * 奇门/ERP 的 appKey 是纯数字(如 23060081),OpenAPI 应用的是字符串 + * (如 WMSD08A3696BBA9551F261C88BBF7F462BD),统一按字符串落库, + * 供出库单回传与取号业务分支回源使用。 + * + * @param {any} value 来源键原始值。 + * @return {string|null} 去空后的字符串(超长截断到 100),无值返回 null。 + */ + normalizeOrderFromKey(value) { + if (value === null || value === undefined) { + return null; + } + + const text = String(value).trim(); + return text ? text.slice(0, 100) : null; + } + + /** + * 解析订单操作人名称。 + * + * 优先使用外部传入的操作人;当未传入时按创建渠道自动补齐: + * - QM:奇门-${应用名称} + * - API:API-${应用名称} + * - MANUAL/其他:当前登录用户姓名(employees_name -> real_name -> name) + * + * @param {string|null|undefined} operatorName 外部传入的操作人名称。 + * @param {string} [createChannel='MANUAL'] 订单创建渠道标识。 + * @param {Object} [info={}] 当前仓库与货主上下文。 + * @return {Promise} 解析后的操作人名称。 + */ + async resolveOperatorName(operatorName, createChannel = 'MANUAL', info = {}) { + const explicitOperatorName = operatorName === undefined || operatorName === null + ? '' + : String(operatorName).trim(); + if (explicitOperatorName) { + return explicitOperatorName; + } + + const normalizedCreateChannel = String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL'; + const appKey = String( + (info && info.appKey) + || (this.ctx.user && this.ctx.user.app_key) + || '' + ).trim(); + + if (normalizedCreateChannel === 'QM') { + if (!appKey) { + return '奇门'; + } + + try { + const app = await this.ctx.model.QimenApp.findOne({ + where: { app_key: appKey }, + attributes: [ 'name' ], + raw: true, + }); + const appName = String(app && app.name || '').trim(); + return appName ? `奇门-${appName}` : '奇门'; + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.resolveOperatorName] 查询奇门应用失败,不影响主流程: %s', error.message); + return '奇门'; + } + } + + if (normalizedCreateChannel === 'API') { + if (!appKey) { + return 'API'; + } + + try { + const app = await this.ctx.model.ApiApp.findOne({ + where: { self_app_key: appKey }, + attributes: [ 'app_name' ], + raw: true, + }); + const appName = String(app && app.app_name || '').trim(); + return appName ? `API-${appName}` : 'API'; + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.resolveOperatorName] 查询API应用失败,不影响主流程: %s', error.message); + return 'API'; + } + } + + const loginUser = this.ctx.user && typeof this.ctx.user === 'object' + ? this.ctx.user + : (this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' ? this.ctx.state.user : {}); + const manualOperatorName = String( + loginUser.employees_name + || loginUser.real_name + || loginUser.name + || '' + ).trim(); + + return manualOperatorName || null; + } + + /** + * 准备订单主表数据。 + * + * @param {Object} deliveryOrder 订单主信息。 + * @param {Object} info 当前仓库与货主上下文。 + * @param {string} [createChannel='MANUAL'] 订单创建渠道标识。 + * @param {number} step 订单步骤。 + * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 + * @param {Object} [requestExtendProps] 请求级扩展属性,携带 ewaybill_order_code 等关键字段。 + * @param {number} [needOmsWaybill=0] 是否需要回 OMS 取号(0/1),仅 openapi 来源可能为 1。 + * @return {Promise} 可入库的订单数据。 + */ + async prepareOrderData( + deliveryOrder, + info, + createChannel = 'MANUAL', + step = DELIVERY_ORDER_STEP.PENDING_REVIEW, + operationLogs = [], + requestExtendProps, + needOmsWaybill = 0 + ) { const { deliveryOrderCode, preDeliveryOrderCode, @@ -180,13 +1436,16 @@ class DeliveryOrderService extends Service { orderFlag, sourcePlatformCode, sourcePlatformName, - createTime, + oaidOrderSourceCode, placeOrderTime, payTime, payNo, shopNick, sellerNick, buyerNick, + buyerMessage, + sellerMessage, + remark, operatorName, operateTime, totalAmount, @@ -196,44 +1455,30 @@ class DeliveryOrderService extends Service { arAmount, gotAmount, logisticsCode, - logisticsName, expressCode, logisticsAreaCode, isUrgency, invoiceFlag, - senderInfo, receiverInfo, + sourceOrderCode, } = 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 policyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId); + const enableExternalExpressCode = this.resolveEnableExternalExpressCode(policyConfig, policyConfig); + const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, policyConfig, policyConfig, { + deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + }, operationLogs); + const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, policyConfig, { + deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + policyConfig, + enableExternalExpressCode, + }, operationLogs); + const resolvedOperatorName = await this.resolveOperatorName(operatorName, createChannel, info); + const fromKey = this.normalizeOrderFromKey(info.appKey); return { delivery_order_code: deliveryOrderCode, pre_delivery_order_code: preDeliveryOrderCode || '', @@ -241,17 +1486,25 @@ class DeliveryOrderService extends Service { order_type: orderType, warehouse_code: warehouseCode, order_flag: orderFlag || '', - // 使用验证后的平台信息 - source_platform_code: platformCode, - source_platform_name: platformName, - create_at: createTime ? new Date(createTime) : new Date(), + source_platform_code: sourcePlatformCode || '', + source_platform_name: sourcePlatformName || '', + oaid_order_source_code: oaidOrderSourceCode || '', + create_channel: String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL', + need_oms_waybill: this.normalizeNeedOmsWaybill(needOmsWaybill), + sys_platform_code: platformSnapshot.sysPlatformCode, + sys_platform_name: platformSnapshot.sysPlatformName, + // 创建时间统一取服务器当前时间,不采用报文 createTime,避免被平台上报时间覆盖 + create_at: new Date(), place_order_time: placeOrderTime ? new Date(placeOrderTime) : null, pay_time: payTime ? new Date(payTime) : null, - pay_no: payNo || '', + pay_no: payNo || sourceOrderCode || '', shop_nick: shopNick, seller_nick: sellerNick, buyer_nick: buyerNick, - operator_name: operatorName, + buyer_message: buyerMessage || '', + seller_message: sellerMessage || '', + remark: remark || '', + operator_name: resolvedOperatorName, operate_time: operateTime ? new Date(operateTime) : null, total_amount: totalAmount ? parseFloat(totalAmount) : 0, item_amount: itemAmount ? parseFloat(itemAmount) : 0, @@ -259,13 +1512,17 @@ 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: expressSnapshot.logisticsCode, + logistics_name: expressSnapshot.logisticsName, + sys_logistics_code: expressSnapshot.sysLogisticsCode, + sys_logistics_name: expressSnapshot.sysLogisticsName, express_code: expressCode || '', + weight_type: expressSnapshot.weightType ?? 0, logistics_area_code: logisticsAreaCode || '', is_urgency: isUrgency || 'N', invoice_flag: invoiceFlag || 'N', - status: 'pedding', + status: Number(step) >= DELIVERY_ORDER_STEP.APPROVED ? 'created' : 'pedding', + step: Number.isInteger(Number(step)) ? Number(step) : DELIVERY_ORDER_STEP.PENDING_REVIEW, // 收件人信息 name: receiverInfo?.name || '', tel: receiverInfo?.tel || '', @@ -278,15 +1535,25 @@ class DeliveryOrderService extends Service { town: receiverInfo?.town || '', detail_address: receiverInfo?.detailAddress || '', zip_code: receiverInfo?.zipCode || '', + oaid: receiverInfo?.oaid || '', // 发件人信息(如果需要存储) // 业务关联ID + extend_props: requestExtendProps || null, store_id: info.storeId, warehouse_id: info.warehouseId, - from_key: info.appKey, + from_key: fromKey, }; } - // 添加订单明细 + /** + * 添加订单明细并完成库存预占。 + * + * @param {Object|Array} orderLines 订单明细数据。 + * @param {number} orderId 订单主键。 + * @param {Object} info 当前仓库与货主上下文。 + * @param {Object} transaction 数据库事务。 + * @return {Promise} 明细创建与库存统计结果。 + */ async addOrderLines(orderLines, orderId, info, transaction) { const { ctx, app } = this; const { warehouseId, appKey, storeId } = info; @@ -314,13 +1581,17 @@ class DeliveryOrderService extends Service { const errors = []; const stockQuantityMap = new Map(); // stock_id -> 数量 const stockWeightMap = new Map(); // stock_id -> 单件重量(grossWeight) - const processedItemIds = new Set(); - console.log('order_items', order_items); + // 预取签约策略配置(避免锁内查DB,减少锁持有时间) + const oversellConfig = await ctx.service.systems.stockStore + .getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId); + // ===== Phase 1: 解析阶段(不锁)===== + // 遍历所有 orderLine,解析 StockStore、验证数据、合并重复商品, + // 但不对 wms_stock_warehouse 加锁,避免因传入顺序不同导致死锁。 + const resolvedItems = []; for (let i = 0; i < order_items.length; i++) { const line = order_items[i]; - console.log('line', line); // 跳过空值 if (!line || typeof line !== 'object') { @@ -328,7 +1599,6 @@ class DeliveryOrderService extends Service { continue; } - // 数量验证 const planQty = line.planQty ? parseInt(line.planQty) : 0; if (planQty <= 0) { @@ -336,98 +1606,170 @@ class DeliveryOrderService extends Service { continue; } let wms_stock = null; - if (!line.itemId) { - console.log('ERP不处理WMS的外部商品编码'); - // 查找唯一键 - wms_stock = await app.model.StockStore.findOne({ where: { - item_code: line.itemCode, - app_key: appKey, - warehouse_id: warehouseId, - store_id: storeId, - }, transaction }); + // 手工单:调用方直接传入 stockId 时需查 StockStore 获取完整信息(含 gross_weight) + if (line.stockId && line.stockId > 0) { + wms_stock = await app.model.StockStore.findByPk(line.stockId, { transaction }); + if (!wms_stock) { + // 降级:查不到记录时用调用方传入的字段构造最小对象 + wms_stock = { + id: line.stockId, + stock_id: line.stockId, + item_name: line.itemName || '', + item_code: line.itemCode || '', + gross_weight: 0, + }; + } + + // 手工单直接传仓库 stock_id:校验库存记录归属当前货主,禁止跨货主下单 + const stockWarehouseRecord = await app.model.StockWarehouse.findByPk(line.stockId, { + attributes: [ 'id', 'store_id' ], + transaction, + raw: true, + }); + if (stockWarehouseRecord && Number(stockWarehouseRecord.store_id) !== Number(storeId)) { + errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n库存归属货主(store_id=${stockWarehouseRecord.store_id})与当前货主(store_id=${storeId})不一致,无法创建订单`); + continue; + } } else { - wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction }); + // 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景) + const findByItemCode = async () => { + if (!line.itemCode) return null; + const stockWhere = { + item_code: line.itemCode, + warehouse_id: warehouseId, + store_id: storeId, + }; + if (appKey) { + stockWhere.app_key = appKey; + } + return await app.model.StockStore.findOne({ where: stockWhere, transaction }); + }; + + if (!line.itemId) { + wms_stock = await findByItemCode(); + } else { + wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction }); + // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 + if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) { + wms_stock = null; + } + // 外部渠道(奇门/开放平台)itemId 可能是平台商品标识或条码而非 WMS 主键, + // 主键查不到或跨货主时降级按 item_code 查找,避免误报“未同步推送到仓库” + if (!wms_stock) { + wms_stock = await findByItemCode(); + } + } } - // 如果没有itemId,直接记录错误 + if (!wms_stock) { errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`); continue; } const itemId = parseInt(wms_stock.id); - // ========== 核心库存检查逻辑 ========== - const stockResult = await ctx.service.systems.stockStore.getItemStorages(wms_stock.id, transaction); - if (!stockResult.success) { - errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n${stockResult.error}`); - continue; - } - - const { stock, storage } = stockResult.data; - const stockId = storage.id; + const stockId = Number(wms_stock.stock_id) || 0; if (!stockId) { - errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`); + // 此时 stock_store 存在但未绑定库存记录(stock_id 为空),即仓库侧已解绑 + errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》仓库已解绑,请联系仓库关联绑定`); continue; } - if (processedItemIds.has(itemId)) { - errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》在同一订单中重复出现`); - continue; - } - processedItemIds.add(itemId); - - const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty; - stockQuantityMap.set(stockId, totalQtyForStock); - - // 记录商品重量(如果storage中有grossWeight) - if (storage.grossWeight !== undefined && storage.grossWeight !== null) { - const weight = parseFloat(storage.grossWeight) || 0; - stockWeightMap.set(stockId, weight); - } else { - // 如果库存中没有重量信息,记录0 - stockWeightMap.set(stockId, 0); - } - - if (storage.canUse < totalQtyForStock) { - errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存不足,可用 ${storage.canUse},需求 ${totalQtyForStock}`); - stockQuantityMap.set(stockId, totalQtyForStock - planQty); + // 重复商品:累加到已存在的条目 + const existingIdx = resolvedItems.findIndex(ri => ri.itemId === itemId); + if (existingIdx >= 0) { + resolvedItems[existingIdx].planQty += planQty; + ctx.logger.info(`[addOrderLines] 合并重复行: itemId=${itemId}, 额外数量=${planQty}, 累加后=${resolvedItems[existingIdx].planQty}`); continue; } - // 锁定库存 - const lockResult = await ctx.service.systems.stockStore.lockItemStorages( - storage.id, + resolvedItems.push({ + itemId, + stockId, planQty, - transaction + wms_stock, + line, + lineIndex: i, + }); + } + + // ===== Sort: 按 stockId 升序排序,保证所有事务加锁顺序一致,从根本上消除死锁 ===== + resolvedItems.sort((a, b) => a.stockId - b.stockId); + + // ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 & 违禁品类型 & 序列号管理标记 ===== + const stockIds = [ ...new Set(resolvedItems.map(item => item.stockId).filter(Boolean)) ]; + const warehouseWeightMap = new Map(); + const stockProhibitedMap = new Map(); // stock_id -> 违禁品类型ID + let hasSnItem = false; // 订单是否包含序列号管理商品(任一明细 is_sn_mgmt='Y') + if (stockIds.length > 0) { + const warehouseRecords = await app.model.StockWarehouse.findAll({ + where: { id: stockIds }, + attributes: [ 'id', 'gross_weight', 'prohibited_id', 'is_sn_mgmt' ], + transaction, + raw: true, + }); + for (const record of warehouseRecords) { + if (String(record.is_sn_mgmt || '').trim().toUpperCase() === 'Y') { + hasSnItem = true; + } + const gw = parseFloat(record.gross_weight) || 0; + if (gw > 0) { + warehouseWeightMap.set(record.id, gw); + } + const prohibitedId = Number(record.prohibited_id) || 0; + if (prohibitedId > 0) { + stockProhibitedMap.set(record.id, prohibitedId); + } + } + } + + // ===== Phase 2: 锁定阶段(按排序后顺序逐个加锁)===== + for (const item of resolvedItems) { + const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stockId, + item.planQty, + transaction, + oversellConfig, + { orderType: 'DELIVERY_ORDER', orderNo: String(orderId), orderId } ); if (!lockResult.success) { - errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); - stockQuantityMap.set(stockId, totalQtyForStock - planQty); + errors.push(`SKU${item.wms_stock.id}商品《${item.wms_stock.item_name}》编码《${item.wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); continue; } - // ========== 库存检查逻辑结束 ========== + + const totalQtyForStock = (stockQuantityMap.get(item.stockId) || 0) + item.planQty; + stockQuantityMap.set(item.stockId, totalQtyForStock); + + // 优先取 wms_stock_warehouse.gross_weight(仓库称重),其次取 wms_stock_store.gross_weight + const warehouseWeight = warehouseWeightMap.get(item.stockId); + const weight = (warehouseWeight != null && warehouseWeight > 0) + ? warehouseWeight + : (parseFloat(item.wms_stock.gross_weight) || 0); + stockWeightMap.set(item.stockId, weight); // 所有检查通过,准备订单行数据 lineData.push({ order_id: orderId, - actual_price: this.safeParseFloat(line.actualPrice, 0), - retail_price: this.safeParseFloat(line.retailPrice, 0), - ext_code: line.extCode || '', - inventory_type: line.inventoryType || '', - item_code: line.itemCode || '', - item_id: line.itemId || null, - item_name: line.itemName || '', - order_line_no: line.orderLineNo || `${i + 1}`, - owner_code: line.ownerCode || '', - plan_qty: planQty, - source_order_code: line.sourceOrderCode || '', - sub_source_order_code: line.subSourceOrderCode || '', - extend_props: line.extendProps ? - (typeof line.extendProps === 'string' ? line.extendProps : JSON.stringify(line.extendProps)) + actual_price: this.safeParseFloat(item.line.actualPrice, 0), + retail_price: this.safeParseFloat(item.line.retailPrice, 0), + ext_code: item.line.extCode || '', + inventory_type: item.line.inventoryType || '', + item_code: item.line.itemCode || '', + item_id: item.itemId, + item_name: item.line.itemName || '', + order_line_no: item.line.orderLineNo || `${item.lineIndex + 1}`, + owner_code: item.line.ownerCode || '', + plan_qty: item.planQty, + source_order_code: item.line.sourceOrderCode || '', + sub_source_order_code: item.line.subSourceOrderCode || '', + extend_props: item.line.extendProps ? + (typeof item.line.extendProps === 'string' ? item.line.extendProps : JSON.stringify(item.line.extendProps)) : null, + stock_id: item.stockId, + item_snapshot: this.buildOrderItemSnapshot(item.wms_stock, item.line), // 可选:记录重量信息到明细 - item_weight: stockWeightMap.get(stockId) || 0, + item_weight: stockWeightMap.get(item.stockId) || 0, }); } @@ -436,15 +1778,14 @@ class DeliveryOrderService extends Service { let total_weight = 0; // 总重量 let stock_count = 0; // stock种类数 let item_total_count = 0; // 商品总数 + let source_order_codes = new Set(); // 订单来源去重集合 if (stockQuantityMap.size > 0) { // 生成结构字符串 const sortedStocks = Array.from(stockQuantityMap.entries()) .sort(([ stockIdA ], [ stockIdB ]) => stockIdA - stockIdB) .map(([ stockId, quantity ]) => { - // 可选:在字符串中包含重量信息 - const weight = stockWeightMap.get(stockId) || 0; - return `${stockId}+${quantity}${weight > 0 ? `@${weight}` : ''}`; + return `${stockId}+${quantity}`; }); items_str = sortedStocks.join('|'); @@ -462,9 +1803,7 @@ class DeliveryOrderService extends Service { const qty = parseInt(quantity) || 0; return sum + (weight * qty); }, 0); - - // 格式化重量(保留2位小数) - total_weight = parseFloat(total_weight.toFixed(2)); + source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); // 订单来源去重集合 ctx.logger.debug('[订单统计信息]', { orderId, @@ -474,6 +1813,32 @@ class DeliveryOrderService extends Service { items_str_length: items_str.length, items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''), }); + } else if (lineData.length > 0) { + // MANUAL 降级:stockQuantityMap 为空时,从 lineData 直接计算统计 + stock_count = lineData.length; + item_total_count = lineData.reduce((sum, ld) => sum + (Number(ld.plan_qty) || 0), 0); + total_weight = 0; + // items_str 用 item_id 作为标识 + const itemEntries = new Map(); + for (const ld of lineData) { + const iid = Number(ld.item_id) || 0; + const qty = Number(ld.plan_qty) || 0; + itemEntries.set(iid, (itemEntries.get(iid) || 0) + qty); + } + items_str = Array.from(itemEntries.entries()) + .sort(([ a ], [ b ]) => a - b) + .map(([ iid, qty ]) => `${iid}+${qty}`) + .join('|'); + source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); + + ctx.logger.debug('[订单统计信息-MANUAL降级]', { + orderId, + stock_count, + item_total_count, + total_weight, + items_str_length: items_str.length, + items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''), + }); } if (errors.length > 0) { @@ -498,15 +1863,43 @@ class DeliveryOrderService extends Service { stock_quantity_map: Object.fromEntries(stockQuantityMap), // stock_id -> 数量 stock_weight_map: Object.fromEntries(stockWeightMap), // stock_id -> 单件重量 line_data: lineData, // 创建的明细数据 + prohibited_type_ids: [ ...new Set(stockProhibitedMap.values()) ], // 违禁品类型ID去重数组(快递策略匹配用) + has_sn_item: hasSnItem, // 是否含序列号管理商品 stats: { // 统计信息汇总 unique_items: stock_count, total_items: item_total_count, total_weight, avg_weight_per_item: stock_count > 0 ? (total_weight / item_total_count).toFixed(2) : 0, + source_order_codes: Array.from(source_order_codes), // 订单来源去重集合 }, }; } + 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; @@ -514,21 +1907,1113 @@ class DeliveryOrderService extends Service { return isNaN(num) ? defaultValue : num; } - // 订单入队列(异步处理) - async addOrderToQueue(orderId, warehouseId) { - const { ctx, app } = this; + /** + * 在当前调用内临时注入 ctx.user 上下文,并在结束后恢复。 + * + * 仅用于复用依赖登录上下文的既有 service 能力,避免扩大影响范围。 + * + * @param {Object} patchUser 需要覆盖的用户上下文字段。 + * @param {Function} callback 业务回调。 + * @return {Promise} 回调执行结果。 + */ + async withPatchedCtxUser(patchUser, callback) { + const { ctx } = this; + const originUser = ctx.user; + const safeOriginUser = originUser && typeof originUser === 'object' ? originUser : {}; + const safePatchUser = patchUser && typeof patchUser === 'object' ? patchUser : {}; + ctx.user = { + ...safeOriginUser, + ...safePatchUser, + }; try { - const queueData = { + return await callback(); + } finally { + ctx.user = originUser; + } + } + + /** + * 构建订单创建后异步处理所需上下文。 + * + * @param {number|string} orderId 订单ID。 + * @param {Object} info 订单创建上下文。 + * @return {Promise} 异步处理上下文。 + */ + async buildAsyncProcessContext(orderId, info = {}) { + const { ctx } = this; + const normalizedOrderId = Number(orderId || 0); + const warehouseId = Number(info && info.warehouseId || 0); + const storeId = Number(info && info.storeId || 0); + + if (!Number.isInteger(normalizedOrderId) || normalizedOrderId <= 0) { + return null; + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return null; + } + + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const order = await DeliveryModel.findOne({ + where: { + id: normalizedOrderId, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (!order) { + return null; + } + + const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const orderItemRows = await OrderItemsModel.findAll({ + where: { + order_id: normalizedOrderId, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + return { + orderId: normalizedOrderId, + warehouseId, + storeId: storeId > 0 ? storeId : Number(order.store_id || 0), + order, + orderItemRows: Array.isArray(orderItemRows) ? orderItemRows : [], + }; + } + + /** + * 构建快递分配显式请求体。 + * + * @param {Object} context 异步处理上下文。 + * @return {Object} 快递分配请求。 + */ + buildExpressAllocateRequest(context) { + const order = context && context.order ? context.order : {}; + return { + ids: [ Number(order.id || context.orderId || 0) ], + }; + } + + /** + * 将订单入队到自动分配快递消费队列(wms_waybill_allocate_queue)。 + * + * 仅写入队列不取号,由定时任务 app/schedule/consume_waybill_allocate_queue.js + * 按仓库+货主串行批量消费。入队幂等(uk_order_id_business_key),重复入队忽略。 + * 调用方需保证截单/未审核订单不会走到此方法。 + * + * @param {Object} context 异步处理上下文。 + * @return {Promise} 无返回值。 + */ + async enqueueAutoWaybillAllocation(context) { + const queueModel = this.ctx.model && this.ctx.model.WaybillAllocateQueue; + if (!queueModel || typeof queueModel.findOrCreate !== 'function') { + this.ctx.logger.warn('[DeliveryOrderService.enqueueAutoWaybillAllocation] 运单分配队列模型未初始化,跳过入队'); + return; + } + + const orderId = Number(context && context.orderId || 0); + const warehouseId = Number(context && context.warehouseId || 0); + const storeId = Number(context && context.storeId || 0); + if (!Number.isInteger(orderId) || orderId <= 0 || !Number.isInteger(warehouseId) || warehouseId <= 0) { + return; + } + + try { + await queueModel.findOrCreate({ + where: { + order_id: orderId, + business_key: 1, + }, + defaults: { + order_id: orderId, + business_key: 1, + warehouse_id: warehouseId, + store_id: storeId > 0 ? storeId : 0, + status: 'pending', + retry_count: 0, + next_retry_at: null, + error_message: null, + created_at: new Date(), + updated_at: new Date(), + }, + }); + this.ctx.logger.info('[DeliveryOrderService.enqueueAutoWaybillAllocation] 订单已入队等待批量分配快递', { orderId, warehouseId, - timestamp: Date.now(), - action: 'order_created', - }; - + storeId, + }); } catch (error) { + // 唯一键冲突(重复入队)或 DB 异常仅记录,不阻断订单创建后续异步流程 + this.ctx.logger.warn('[DeliveryOrderService.enqueueAutoWaybillAllocation] 入队失败: %s', error.message, { + orderId, + error: error.message, + }); } } + + /** + * 构建储位分配显式请求体。 + * + * 自动分配不传 allow_storage_location:默认禁止分配到存储储位, + * 仅当货主关闭存拣分离(storage_separation=0)时由底层按策略放行。 + * + * @param {Object} context 异步处理上下文。 + * @return {Object} 储位分配请求。 + */ + buildStorageAllocateRequest(context) { + return { + order_ids: [ Number(context && context.orderId || 0) ], + // 显式携带仓库上下文,避免依赖 ctx.user(Qimen 链路无登录用户) + warehouse_id: Number(context && context.warehouseId || 0), + }; + } + + /** + * 读取货主-仓库策略配置。 + * + * @param {number} storeId 货主ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 策略配置。 + */ + async getStoreWarehousePolicyConfig(storeId, warehouseId) { + const storeWarehouseService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.storeWarehouse; + if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') { + return {}; + } + + try { + const contractConfig = await storeWarehouseService.getContractConfig( + Number(warehouseId || 0), + Number(storeId || 0) + ); + const policyConfig = contractConfig && typeof contractConfig.policy_config === 'object' + ? contractConfig.policy_config + : {}; + return policyConfig; + } catch (error) { + this.ctx.logger.warn(`[DeliveryOrderService.getStoreWarehousePolicyConfig] read contract config failed: ${error.message}`, { + storeId, + warehouseId, + error: error.message, + }); + return {}; + } + } + + /** + * 归一化策略开关值。 + * + * @param {any} value 原始开关值。 + * @return {boolean} 是否开启。 + */ + normalizePolicyFlag(value) { + if (typeof value === 'boolean') { + return value; + } + const normalizedText = String(value === undefined || value === null ? '' : value).trim().toLowerCase(); + return [ '1', 'true', 'yes', 'on' ].includes(normalizedText); + } + + /** + * 解析自动分配时间窗口配置,货主-仓库级优先,未启用时由仓库级兜底。 + * + * @param {Object} policyConfig 货主-仓库级策略配置。 + * @param {Object|null} warehouseSubjectConfig 仓库级主体配置。 + * @return {{cutoffEnabled: boolean, cutoffTime: string, allocateStartTime: string}} + * 最终生效的截单开关、截单时间与开始自动分配时间。 + */ + resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig) { + const policyEnabled = this.normalizePolicyFlag( + (policyConfig && policyConfig.cutoff_order_enabled) + ); + const policyTime = (policyConfig && typeof policyConfig.cutoff_order_time === 'string' + ? policyConfig.cutoff_order_time.trim() + : '') || '18:00'; + const policyStartTime = (policyConfig && typeof policyConfig.allocate_start_time === 'string' + ? policyConfig.allocate_start_time.trim() + : '') || '08:00'; + + // 货主-仓库级已启用截单,直接使用 + if (policyEnabled) { + return { + cutoffEnabled: true, + cutoffTime: policyTime, + allocateStartTime: policyStartTime, + }; + } + + // 货主-仓库级未启用,由仓库级兜底 + if (warehouseSubjectConfig && warehouseSubjectConfig.cutoff_order_enabled) { + const warehouseTime = (typeof warehouseSubjectConfig.cutoff_order_time === 'string' + ? warehouseSubjectConfig.cutoff_order_time.trim() + : '') || '18:00'; + const warehouseStartTime = (typeof warehouseSubjectConfig.allocate_start_time === 'string' + ? warehouseSubjectConfig.allocate_start_time.trim() + : '') || '08:00'; + return { + cutoffEnabled: true, + cutoffTime: warehouseTime, + allocateStartTime: warehouseStartTime, + }; + } + + return { + cutoffEnabled: false, + cutoffTime: '18:00', + allocateStartTime: '08:00', + }; + } + + /** + * 判断当前时间是否已超过指定截单时间。 + * + * @param {string} cutoffTimeStr 截单时间,格式 HH:mm。 + * @return {boolean} 是否已超过截单时间。 + */ + isPastCutoffTime(cutoffTimeStr) { + if (!cutoffTimeStr || typeof cutoffTimeStr !== 'string') { + return false; + } + + const trimmed = cutoffTimeStr.trim(); + if (!/^\d{2}:\d{2}$/.test(trimmed)) { + return false; + } + + const now = new Date(); + const [ hours, minutes ] = trimmed.split(':').map(Number); + const cutoffTotalMinutes = hours * 60 + minutes; + const nowTotalMinutes = now.getHours() * 60 + now.getMinutes(); + + return nowTotalMinutes >= cutoffTotalMinutes; + } + + /** + * 判断当前时间是否处于自动分配窗口之外。 + * + * 同天窗口(开始时间早于截单时间):now < start 或 now >= cutoff 时禁止; + * 跨天窗口(开始时间晚于截单时间,截单时间视为次日):now in [cutoff, start) 时禁止; + * 开始时间与截单时间相同时窗口恒空,防御性全天禁止。 + * + * @param {string} allocateStartTimeStr 开始自动分配时间,格式 HH:mm。 + * @param {string} cutoffTimeStr 截单时间,格式 HH:mm。 + * @param {Date} [nowDate=new Date()] 当前时间(测试可注入)。 + * @return {boolean} 是否禁止自动分配。 + */ + isAllocationWindowClosed(allocateStartTimeStr, cutoffTimeStr, nowDate = new Date()) { + const parseTime = value => { + if (!value || typeof value !== 'string') { + return null; + } + + const trimmed = value.trim(); + if (!/^\d{2}:\d{2}$/.test(trimmed)) { + return null; + } + + const [ hours, minutes ] = trimmed.split(':').map(Number); + return hours * 60 + minutes; + }; + + const startMinutes = parseTime(allocateStartTimeStr); + const cutoffMinutes = parseTime(cutoffTimeStr); + const nowMinutes = nowDate.getHours() * 60 + nowDate.getMinutes(); + + if (startMinutes === null || cutoffMinutes === null) { + return false; + } + + if (startMinutes === cutoffMinutes) { + return true; // 窗口为空,防御性全天禁止 + } + + if (startMinutes < cutoffMinutes) { + // 同天窗口 [start, cutoff) + return nowMinutes < startMinutes || nowMinutes >= cutoffMinutes; + } + + // 跨天窗口:截单时间视为次日 [start, 24:00) ∪ [00:00, cutoff) + return nowMinutes >= cutoffMinutes && nowMinutes < startMinutes; + } + + /** + * 构建自动加团结构信息。 + * + * @param {Object} context 异步处理上下文。 + * @return {Object|null} 自动加团结构信息。 + */ + buildAutoGroupingStructure(context) { + const waveService = this.ctx.service && this.ctx.service.systemMethods + && this.ctx.service.systemMethods.order + && this.ctx.service.systemMethods.order.wave; + if (!waveService) { + return null; + } + + const order = context && context.order ? context.order : {}; + const itemPartType = String(order.items_hash || '').trim() ? 'items_hash' : 'items'; + const itemPart = String(itemPartType === 'items_hash' ? order.items_hash : order.items || '').trim(); + if (!itemPart) { + return null; + } + + const logisticsName = String(order.sys_logistics_code || '').trim(); + const mergedItemDetails = typeof waveService.mergeOrderItemDetails === 'function' + ? waveService.mergeOrderItemDetails(context && context.orderItemRows ? context.orderItemRows : []) + : []; + const itemSnapshotKey = typeof waveService.buildItemSnapshotKey === 'function' + ? waveService.buildItemSnapshotKey(mergedItemDetails) + : ''; + const itemDetailMachine = typeof waveService.buildMachineStructureToken === 'function' + ? waveService.buildMachineStructureToken({ + item_part_type: itemPartType, + item_part: itemPart, + distinguish_express: true, + logistics_name: logisticsName, + item_snapshot_key: itemSnapshotKey, + }) + : ''; + + return { + itemPartType, + itemPart, + logisticsName, + itemSnapshotKey, + itemDetailMachine, + }; + } + + /** + * 查找自动加团中的匹配波次。 + * + * @param {Object} context 异步处理上下文。 + * @param {Object} structure 自动加团结构信息。 + * @return {Promise} 命中的波次ID,未命中返回 0。 + */ + async findAutoGroupingWaveId(context, structure) { + const { ctx } = this; + const waveService = ctx.service.systemMethods.order.wave; + const request = { + page: 1, + pageSize: 50, + where: { + wave_status: 0, + item_part_type: structure.itemPartType, + item_part: structure.itemPart, + item_snapshot_key: structure.itemSnapshotKey, + distinguish_express: 1, + logistics_name: structure.logisticsName, + }, + }; + + const response = await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + return await waveService.batchList(request); + }); + const list = response && response.list; + if (!Array.isArray(list) || list.length === 0) { + return 0; + } + + return Number(list[0] && list[0].wave_id || 0); + } + + /** + * 将订单加入指定波次,并回写波次统计。 + * + * @param {Object} context 异步处理上下文。 + * @param {number} waveId 波次ID。 + * @return {Promise} 是否成功加入。 + */ + async appendOrderToWave(context, waveId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) { + return false; + } + + const warehouseId = Number(context.warehouseId || 0); + const orderId = Number(context.orderId || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(orderId) || orderId <= 0) { + return false; + } + + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const transaction = await ctx.model.transaction(); + try { + const orderRow = await DeliveryModel.findOne({ + where: { + id: orderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'wave_id', 'step', 'status', 'outbound_status', 'lock_status', 'has_sn_item', 'is_b2b' ], + transaction, + lock: transaction.LOCK.UPDATE, + }); + if (!orderRow) { + await transaction.commit(); + return false; + } + + // 已锁定的订单不允许自动加团 + if (isLockedOrderStatus(orderRow.lock_status)) { + await transaction.commit(); + return false; + } + + // B2B 订单不参与波次抓取,自动加团时静默跳过(NULL 视为非 B2B,兼容存量行) + if (String(orderRow.is_b2b || '').trim() === 'Y') { + await transaction.commit(); + return false; + } + + // SN(序列号管理)订单不参与团购,自动加团时静默跳过 + if (String(orderRow.has_sn_item || '').trim().toUpperCase() === 'Y') { + await transaction.commit(); + return false; + } + + const currentWaveId = Number(orderRow.wave_id || 0); + if (currentWaveId === normalizedWaveId) { + await transaction.commit(); + return true; + } + if (currentWaveId > 0) { + await transaction.commit(); + return false; + } + + const currentStep = Number(orderRow.step || 0); + const currentStatus = String(orderRow.status || '').trim(); + const currentOutboundStatus = String(orderRow.outbound_status || '').trim(); + if (![ 1, 2, 3 ].includes(currentStep) || currentStatus === 'cancel' || currentOutboundStatus === 'padding') { + await transaction.commit(); + return false; + } + + const waveRows = await ctx.model.query(` + SELECT wave_id, wave_no, total_orders + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT 1 + FOR UPDATE + `, { + replacements: { + warehouseId, + waveId: normalizedWaveId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + const wave = Array.isArray(waveRows) && waveRows[0] ? waveRows[0] : null; + if (!wave) { + await transaction.commit(); + return false; + } + + await DeliveryModel.update({ + wave_id: normalizedWaveId, + wave_no: String(wave.wave_no || '').trim(), + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + wave_id: 0, + lock_status: 'none', + }, + transaction, + }); + + await ctx.service.systemMethods.order.wave.rebuildOrderWaveIndex({ + warehouseId, + waveId: normalizedWaveId, + orderIds: [ orderId ], + orderModel: DeliveryModel, + transaction, + }); + + await ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = total_orders + 1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `, { + replacements: { + warehouseId, + waveId: normalizedWaveId, + }, + transaction, + }); + + await transaction.commit(); + + // 写入订单操作日志:自动加团 + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_WAVE_AUTO_GROUP', + operator: { + id: null, + name: 'system', + }, + extras: { + message: `自动加团到波次 ${wave.wave_no || normalizedWaveId}`, + warehouseId, + waveId: normalizedWaveId, + waveNo: wave.wave_no || '', + }, + }]); + } + } catch (e) { + this.ctx.logger.warn('[delivery_order.appendOrderToWave] 写入 operation_log 失败,不影响主流程', { + error: e && e.message, + orderId, + waveId: normalizedWaveId, + }); + } + + return true; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 统计可参与新团购波次的订单数量。 + * + * @param {Object} context 异步处理上下文。 + * @param {Object} structure 自动加团结构信息。 + * @return {Promise} 可参与数量。 + */ + async countCandidateGroupOrders(context, structure) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(context.warehouseId); + const where = { + warehouse_id: context.warehouseId, + wave_id: 0, + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + lock_status: 'none', + sys_logistics_code: structure.logisticsName, + // 自动加团同样不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行) + is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + // 团购排除 SN(序列号管理)订单 + [Op.or]: [ + { has_sn_item: { [Op.is]: null } }, + { has_sn_item: { [Op.ne]: 'Y' } }, + ], + }; + where[structure.itemPartType] = structure.itemPart; + + return await DeliveryModel.count({ where }); + } + + /** + * 按结构创建团购波次。 + * + * @param {Object} context 异步处理上下文。 + * @param {Object} structure 自动加团结构信息。 + * @param {number} minGroupOrderFetchQuantity 最小团购抓取数量。 + * @param {number} maxWaveQuantity 最大加团数量。 + * @return {Promise} 抓取结果。 + */ + async createGroupingWave(context, structure, minGroupOrderFetchQuantity, maxWaveQuantity) { + const { ctx } = this; + const waveService = ctx.service.systemMethods.order.wave; + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(context.warehouseId); + + const requestStructure = { + item_part_type: structure.itemPartType, + item_part: structure.itemPart, + distinguish_express: true, + logistics_name: structure.logisticsName, + sys_logistics_code: structure.logisticsName, + item_snapshot_key: structure.itemSnapshotKey, + item_detail_machine: structure.itemDetailMachine, + quantity: maxWaveQuantity, + }; + + return await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + return await waveService.fetchSingleStructure( + DeliveryModel, + requestStructure, + context.warehouseId, + 'B', + minGroupOrderFetchQuantity, + { maxFetchQuantity: maxWaveQuantity, excludeSnOrders: true } + ); + }); + } + + /** + * 将波次标记为自动加团中。 + * + * @param {Object} context 异步处理上下文。 + * @param {number[]} waveIds 波次ID集合。 + * @return {Promise} 无返回值。 + */ + async markWaveAutoGrouping(context, waveIds) { + const waveService = this.ctx.service.systemMethods.order.wave; + await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + await waveService.batchAutoGrouping({ ids: waveIds }); + }); + } + + /** + * 达到最大加团数时将波次结束自动加团。 + * + * @param {Object} context 异步处理上下文。 + * @param {number} waveId 波次ID。 + * @param {number} maxWaveQuantity 最大加团数量。 + * @return {Promise} 无返回值。 + */ + async finishAutoGroupingIfNeeded(context, waveId, maxWaveQuantity) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + const normalizedMaxWaveQuantity = Number(maxWaveQuantity || 0); + if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) { + return; + } + if (!Number.isInteger(normalizedMaxWaveQuantity) || normalizedMaxWaveQuantity <= 0) { + return; + } + + const rows = await ctx.model.query(` + SELECT total_orders + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT 1 + `, { + replacements: { + warehouseId: context.warehouseId, + waveId: normalizedWaveId, + }, + type: ctx.model.QueryTypes.SELECT, + }); + + const totalOrders = Number(Array.isArray(rows) && rows[0] ? rows[0].total_orders : 0); + if (!Number.isInteger(totalOrders) || totalOrders < normalizedMaxWaveQuantity) { + return; + } + + const waveService = this.ctx.service.systemMethods.order.wave; + await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + await waveService.batchFinishAutoGrouping({ ids: [ normalizedWaveId ] }); + }); + } + + /** + * 执行自动加团逻辑(仅团购),从仓库级配置读取 auto_grouping_enabled。 + * + * @param {Object} context 异步处理上下文。 + * @param {number} context.storeId 货主ID。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async runAutoGrouping(context) { + const { ctx } = this; + const warehouseSubjectConfig = await this.getStoreSubjectConfig(context.warehouseId); + if (!warehouseSubjectConfig || !warehouseSubjectConfig.auto_grouping_enabled) { + return; + } + + const maxWaveQuantity = Number(warehouseSubjectConfig.max_wave_quantity || 0) > 0 + ? Number(warehouseSubjectConfig.max_wave_quantity) + : 500; + const structure = this.buildAutoGroupingStructure(context); + if (!structure) { + return; + } + + const waveService = ctx.service.systemMethods.order.wave; + const minGroupOrderFetchQuantity = await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + return await waveService.getMinGroupOrderFetchQuantity(context.warehouseId); + }); + + const matchedAutoGroupingWaveId = await this.findAutoGroupingWaveId(context, structure); + if (matchedAutoGroupingWaveId > 0) { + const joined = await this.appendOrderToWave(context, matchedAutoGroupingWaveId); + if (!joined) { + return; + } + + await this.finishAutoGroupingIfNeeded(context, matchedAutoGroupingWaveId, maxWaveQuantity); + // appendOrderToWave 内部已写入 ORDER_WAVE_AUTO_GROUP 日志 + return; + } + + const candidateCount = await this.countCandidateGroupOrders(context, structure); + if (candidateCount < minGroupOrderFetchQuantity) { + return; + } + + const fetchResult = await this.createGroupingWave( + context, + structure, + minGroupOrderFetchQuantity, + maxWaveQuantity + ); + const createdWaveIds = Array.isArray(fetchResult && fetchResult.wave_ids) + ? fetchResult.wave_ids.filter(id => Number.isInteger(Number(id)) && Number(id) > 0).map(id => Number(id)) + : []; + if (createdWaveIds.length <= 0) { + return; + } + + await this.markWaveAutoGrouping(context, createdWaveIds); + await this.finishAutoGroupingIfNeeded(context, createdWaveIds[0], maxWaveQuantity); + + // 写入 ORDER_WAVE_AUTO_GROUP 日志(新建波次路径) + if (context.orderId) { + try { + const waveRows = await ctx.model.query(` + SELECT wave_no FROM wms_wave_batch + WHERE warehouse_id = :warehouseId AND wave_id = :waveId + LIMIT 1 + `, { + replacements: { warehouseId: context.warehouseId, waveId: createdWaveIds[0] }, + type: ctx.model.QueryTypes.SELECT, + }); + const waveNo = (Array.isArray(waveRows) && waveRows[0]) ? String(waveRows[0].wave_no || '').trim() : ''; + const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function') { + await opLogService.createOperationLogs([{ + businessType: 'order', + businessId: `${context.orderId}`, + operationCode: 'ORDER_WAVE_AUTO_GROUP', + operator: { id: null, name: 'system' }, + extras: { + message: `自动加团到波次 ${waveNo || createdWaveIds[0]}`, + warehouseId: context.warehouseId, + waveId: createdWaveIds[0], + waveNo, + }, + }]); + } + } catch (e) { + ctx.logger.warn('[delivery_order.runAutoGrouping] 写入 ORDER_WAVE_AUTO_GROUP 日志失败', { + error: e && e.message, + orderId: context.orderId, + waveId: createdWaveIds[0], + }); + } + } + } + + /** + * 执行订单创建后的单步动作,单步失败不影响后续。 + * + * @param {string} stepName 步骤名称。 + * @param {Function} stepHandler 步骤处理函数。 + * @return {Promise} 无返回值。 + */ + async runAsyncProcessStep(stepName, stepHandler) { + try { + await stepHandler(); + } catch (error) { + this.ctx.logger.warn(`[DeliveryOrderService.asyncProcessOrderCreated] ${stepName} failed: ${error.message}`, { + step: stepName, + error: error.message, + }); + } + } + + /** + * 查找订单备注命中仓库「自动分配快递排除备注」的关键字。 + * + * 备注范围:remark(备注)、buyer_message(买家留言)、seller_message(卖家留言), + * 任一字段包含任一关键字即视为命中;命中时返回第一个命中的关键字,未命中返回空串。 + * + * @param {Object} order 订单行数据。 + * @param {Object|null} warehouseSubjectConfig 仓库主体配置(subject_config)。 + * @return {string} 命中的排除关键字,未命中返回空字符串。 + */ + findAutoExpressExcludedRemark(order, warehouseSubjectConfig) { + const rawRemarks = warehouseSubjectConfig + && warehouseSubjectConfig.auto_allocate_express_exclude_remarks; + const keywords = (Array.isArray(rawRemarks) ? rawRemarks : []) + .map(item => (typeof item === 'string' ? item : String(item === undefined || item === null ? '' : item)).trim()) + .filter(Boolean); + if (keywords.length === 0 || !order || typeof order !== 'object') { + return ''; + } + + const remarkText = [ 'remark', 'buyer_message', 'seller_message' ] + .map(field => String(order[field] === undefined || order[field] === null ? '' : order[field])) + .join(' ') + .trim(); + if (!remarkText) { + return ''; + } + + return keywords.find(keyword => remarkText.includes(keyword)) || ''; + } + + /** + * 补写「跳过自动分配快递」的订单操作日志。 + * + * 订单备注命中仓库「自动分配快递排除备注」关键字时不自动分配快递, + * 写一条操作记录说明跳过原因与命中的关键字,便于仓库人员在订单日志中查看。 + * 写入失败仅记录告警,不影响订单创建主流程。 + * + * @param {Object} context 异步处理上下文。 + * @param {string} matchedKeyword 命中的排除关键字。 + * @return {Promise} 无返回值。 + */ + async appendAutoExpressSkipLog(context, matchedKeyword) { + const orderId = Number(context && context.orderId || 0); + const warehouseId = Number(context && context.warehouseId || 0); + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function' || orderId <= 0) { + return; + } + + try { + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: `${orderId}`, + operationCode: ORDER_OPERATION_CODES.AUTO_EXPRESS_SKIP, + operator: { + id: null, + name: 'system', + }, + extras: { + warehouseId, + message: `订单备注命中「自动分配快递排除备注」关键字「${matchedKeyword}」,跳过自动分配快递`, + }, + }]); + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.appendAutoExpressSkipLog] 写入操作日志失败,不影响主流程', { + orderId, + warehouseId, + matchedKeyword, + error: error && error.message, + }); + } + } + + /** + * 补写「等待外部 OMS 取号」的订单操作日志。 + * + * need_oms_waybill=1 的订单(仅 openapi 创建来源可能为 1)不参与本地自动分配快递: + * 分流时不入本地取号队列,写一条操作记录说明原因与当前等待态; + * 外部 OMS 取号能力上线后再接入实际取号与运单回写。 + * 写入失败仅记录告警,不影响订单创建主流程。 + * + * @param {Object} context 异步处理上下文。 + * @return {Promise} 无返回值。 + */ + async appendNeedOmsWaybillWaitLog(context) { + const orderId = Number(context && context.orderId || 0); + const warehouseId = Number(context && context.warehouseId || 0); + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function' || orderId <= 0) { + return; + } + + try { + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: `${orderId}`, + operationCode: ORDER_OPERATION_CODES.NEED_OMS_WAYBILL_WAIT, + operator: { + id: null, + name: 'system', + }, + extras: { + warehouseId, + message: '订单需要回 OMS 取号,已跳过本地分配快递,等待外部 OMS 取号', + }, + }]); + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.appendNeedOmsWaybillWaitLog] 写入操作日志失败,不影响主流程', { + orderId, + warehouseId, + error: error && error.message, + }); + } + } + + // 订单异步流程 + /** + * 订单创建后的异步流程。 + * + * 按顺序执行:自动分配快递 -> 自动分配储位 -> 自动加团。 + * 每一步都使用显式请求对象调用下游能力,单步异常不中断后续。 + * + * @param {number|string} orderId 订单ID。 + * @param {Object} info 当前仓库与货主上下文。 + * @param {string} createChannel 订单创建渠道。 + * @return {Promise} 无返回值。 + */ + async asyncProcessOrderCreated(orderId, info, createChannel) { + const normalizedCreateChannel = String(createChannel || '').trim().toUpperCase(); + if (![ 'API', 'QM' ].includes(normalizedCreateChannel)) { + return; + } + + const context = await this.buildAsyncProcessContext(orderId, info); + if (!context) { + return; + } + + // 已锁定的订单不自动分配快递、储位,不自动加团 + if (isLockedOrderStatus(context.order && context.order.lock_status)) { + this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 订单已锁定,跳过自动分配快递/储位/自动加团', { + warehouseId: context.warehouseId, + orderId: context.orderId, + lockStatus: context.order.lock_status, + }); + return; + } + + const policyConfig = await this.getStoreWarehousePolicyConfig(context.storeId, context.warehouseId); + + // 截单时间兜底:货主-仓库级未启用时,fallback 到仓库级配置 + const warehouseSubjectConfig = await this.getStoreSubjectConfig(context.warehouseId); + const { cutoffEnabled, cutoffTime, allocateStartTime } = this.resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig); + + // 早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),均不自动分配 + const isAllocationBlocked = cutoffEnabled + && this.isAllocationWindowClosed(allocateStartTime, cutoffTime); + + // 如果需要审核,不触发自动分配快递、储位、加团 + const needApproval = Number(policyConfig && policyConfig.need_order_approval) !== 0; + + // 仓库「自动分配快递排除备注」:订单备注命中任一关键字时跳过自动分配快递 + const excludedRemarkKeyword = this.findAutoExpressExcludedRemark(context.order, warehouseSubjectConfig); + const isExpressExcludedByRemark = Boolean(excludedRemarkKeyword); + + const isAutoAllocateExpressEnabled = !isAllocationBlocked && !needApproval + && !isExpressExcludedByRemark + && this.normalizePolicyFlag(policyConfig.auto_allocate_express); + const isAutoAllocateStorageEnabled = !isAllocationBlocked && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage); + + // 记录开关判定结果,便于排查自动分配快递/储位未触发的问题 + this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 自动流程开关判定', { + warehouseId: context.warehouseId, + orderId: context.orderId, + storeId: context.storeId, + cutoffEnabled, + allocateStartTime, + cutoffTime, + isAllocationBlocked, + needApproval, + autoAllocateExpressFlag: policyConfig && policyConfig.auto_allocate_express, + autoAllocateStorageFlag: policyConfig && policyConfig.auto_allocate_storage, + isExpressExcludedByRemark, + excludedRemarkKeyword, + autoExpressExcludeRemarks: warehouseSubjectConfig && warehouseSubjectConfig.auto_allocate_express_exclude_remarks, + isAutoAllocateExpressEnabled, + isAutoAllocateStorageEnabled, + }); + + if (isExpressExcludedByRemark) { + await this.runAsyncProcessStep('appendAutoExpressSkipLog', async () => { + await this.appendAutoExpressSkipLog(context, excludedRemarkKeyword); + }); + } + + // 需要回 OMS 取号的订单(仅 openapi 创建来源可能为 1):本地流水线不会给它分配快递, + // 这里仅记录标记;是否自动发起取号仍由货主-仓库「自动分配快递」开关决定, + // 开关关闭时只能由人工触发「分配快递号」。 + const needOmsWaybill = this.normalizeNeedOmsWaybill(context.order && context.order.need_oms_waybill) === 1; + + if (needOmsWaybill) { + this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 订单需要回 OMS 取号,跳过本地自动分配快递', { + orderId: context.orderId, + warehouseId: context.warehouseId, + storeId: context.storeId, + autoAllocateExpressEnabled: isAutoAllocateExpressEnabled, + }); + await this.runAsyncProcessStep('appendNeedOmsWaybillWaitLog', async () => { + await this.appendNeedOmsWaybillWaitLog(context); + }); + } + + if (isAutoAllocateExpressEnabled) { + await this.runAsyncProcessStep('allocateExpress', async () => { + // 不再逐单直接取号:改为写入消费队列,由定时任务按仓库+货主串行批量消费, + // 避免大批量订单创建时 N 条并发取号事务的 AB-BA 死锁。截单/未审核订单在此处不会入队。 + await this.enqueueAutoWaybillAllocation(context); + }); + } + + if (isAutoAllocateStorageEnabled) { + await this.runAsyncProcessStep('allocateStorage', async () => { + const request = this.buildStorageAllocateRequest(context); + await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + await this.ctx.service.systems.orderStorageAllocation.allocateStorage(request); + }); + }); + } + + if (!isAllocationBlocked && !needApproval) { + await this.runAsyncProcessStep('autoGrouping', async () => { + await this.runAutoGrouping(context); + }); + } + + await this.runAsyncProcessStep('waveStrategyQuickScan', async () => { + await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + const result = await this.ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse( + context.warehouseId + ); + const taskId = result && typeof result === 'object' + ? (result.taskId || result.task_id || result.id || null) + : result; + + this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] wave strategy quick scan triggered', { + warehouseId: context.warehouseId, + orderId: context.orderId, + taskId, + }); + }); + }); + } } module.exports = DeliveryOrderService; diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index 36a6788..fd820d7 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -1,70 +1,157 @@ 'use strict'; const Service = require('egg').Service; +/** + * 校验商品 ID 是否合法:必须是纯数字且未超出 BIGINT(20) 有符号范围。 + * @param {string|number|null|undefined} value 待校验的商品 ID + * @return {boolean} 合法返回 true,否则返回 false + */ +function isValidItemId(value) { + if (value === null || value === undefined || value === '') return false; + const str = String(value); + // 纯数字校验 + if (!/^\d+$/.test(str)) return false; + try { + // BIGINT(20) 有符号上限 9223372036854775807,超出范围视为非法 + return BigInt(str) <= BigInt('9223372036854775807'); + } catch (error) { + return false; + } +} + +/** + * 提取商品编码开头的连续数字,作为归一化条码用于商品匹配。 + * 用于剥离中文后缀(如 "6934864201409-新品" → "6934864201409"): + * - 纯数字编码原样返回(与精确匹配等价); + * - 编码不以数字开头时无法归一化,返回 null; + * - 只取开头连续数字段,后续任意字符(中英文、符号、空格)一律视为后缀丢弃。 + * @param {string|number|null|undefined} value 原始商品编码(itemCode) + * @return {string|null} 归一化后的纯数字条码;无法归一化返回 null + */ +function normalizeItemCodeForMatch(value) { + if (value === null || value === undefined) return null; + const str = String(value).trim(); + if (!str) return null; + const matched = str.match(/^\d+/); + return matched ? matched[0] : null; +} + class entryOrderService extends Service { - async addOrder(data, info, fromCode) { + /** + * 创建入库单(含明细行校验与插入)。 + * 明细行商品匹配优先级:itemId 主键 > itemCode 精确匹配 > itemCode 归一化条码匹配; + * 带中文后缀的编码(如 6934864201409-新品)在精确匹配不到时剥离后缀按纯数字条码对齐, + * 归一化条码对应多个商品时按失败处理,避免错配。 + * @param {Object} data 请求体,包含 request.entryOrder 与 request.orderLines + * @param {Object} info 上下文信息 { storeId, warehouseId, appKey, customerId, warehouseCode } + * @param {string} fromCode 来源标识(WMS / API / QM) + * @param {Object} [options={}] 可选配置 + * @param {boolean} [options.autoReview=false] 是否自动审核,true 时入库单创建后状态直接变为 PENDING + * @return {Promise} { success, message, data: { entryOrderId, entryOrderCode, createTime, warehouseCode, status } } + */ + async addOrder(data, info, fromCode, options = {}) { + const { autoReview = false } = options; const { storeId, warehouseId, appKey, customerId, warehouseCode } = info; - const { app } = this; + const { app, ctx } = this; const transaction = await app.model.transaction(); // 开启事务 try { - console.log('入库单开始接收处理'); let totalOrderLines = data.request.entryOrder.totalOrderLines || 0; let orderLine = data.request.orderLines.orderLine; if (orderLine.itemCode) { orderLine = [ orderLine ]; } - console.log('orderLine', orderLine); - const isSingle = totalOrderLines ? 0 : 1; totalOrderLines = totalOrderLines || orderLine.length; let errors = []; const items = []; - console.log('循环开始'); // 验证商品 - for (var i = 0; i < orderLine.length; i++) { + for (let i = 0; i < orderLine.length; i++) { + const line = orderLine[i]; + const lineNo = line.orderLineNo || i + 1; + // 请求行展示信息:取自原始报文,保证失败提示展示真实 SKU/商品/编码 + const lineItemId = line.itemId ?? ''; + const lineItemName = line.itemName || ''; + const lineItemCode = line.itemCode || ''; let wms_stock = null; // ERP不处理WMS的外部商品编码 - if (!orderLine[i].itemId) { - console.log('ERP不处理WMS的外部商品编码'); - // 查找唯一键 - wms_stock = await app.model.StockStore.findOne({ where: { - item_code: orderLine[i].itemCode, + // 查找唯一键:按商品编码精确查找(限定 appKey/仓库/货主作用域,作用域内 item_code 唯一) + const findByItemCode = async itemCode => { + if (!itemCode) return null; + return await app.model.StockStore.findOne({ where: { + item_code: itemCode, app_key: appKey, warehouse_id: warehouseId, store_id: storeId, }, transaction }); - } else { - wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId, { transaction }); + }; + // itemId 必须是纯数字且在 BIGINT 范围内才可作为商品主键使用, + // 非法值(如带中文后缀的编码)视为未提供,降级按 item_code 匹配 + const validItemId = isValidItemId(line.itemId) ? String(line.itemId) : null; + if (validItemId) { + wms_stock = await app.model.StockStore.findByPk(validItemId, { transaction }); + // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 + if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) { + wms_stock = null; + } + } + // 匹配优先级:itemId 主键 > itemCode 精确匹配 > itemCode 归一化条码匹配 + // 外部渠道 itemId 可能是平台商品标识或条码而非 WMS 主键,主键查不到时降级按 item_code 查找 + if (!wms_stock) { + wms_stock = await findByItemCode(lineItemCode); + } + // 带中文后缀的编码(如 6934864201409-新品)精确匹配不到时, + // 剥离后缀按纯数字条码与 StockStore.item_code 对齐匹配 + if (!wms_stock) { + const normalizedBarcode = normalizeItemCodeForMatch(lineItemCode); + if (normalizedBarcode && normalizedBarcode !== lineItemCode) { + const normalizedRows = await app.model.StockStore.findAll({ + where: { + item_code: normalizedBarcode, + app_key: appKey, + warehouse_id: warehouseId, + store_id: storeId, + }, + transaction, + }); + if (normalizedRows.length === 1) { + wms_stock = normalizedRows[0]; + } else if (normalizedRows.length > 1) { + // 同一归一化条码对应多个商品,无法确定唯一 SKU,按失败处理,避免错配 + errors.push(`订单行${lineNo}:编码《${lineItemCode}》归一化条码《${normalizedBarcode}》匹配到多个商品,请人工核对后重试`); + continue; + } + } } if (!wms_stock) { - errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`); + errors.push(`订单行${lineNo}:SKU${lineItemId}商品《${lineItemName}》编码《${lineItemCode}》\n未同步推送到仓库`); continue; } if (!wms_stock.stock_id) { - errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》wms无对应关系\n请联系仓库关联创建商品`); + errors.push(`订单行${lineNo}:SKU${lineItemId}商品《${lineItemName}》编码《${lineItemCode}》wms无对应关系\n请联系仓库关联创建商品`); continue; } - wms_stock.inventory_type = orderLine[i].inventoryType || 'ZP'; - wms_stock.order_line_no = orderLine[i].orderLineNo || i + 1; - wms_stock.count = orderLine[i].planQty; - wms_stock.item_id = orderLine[i].itemId || wms_stock.id; + wms_stock.inventory_type = line.inventoryType || 'ZP'; + wms_stock.order_line_no = line.orderLineNo || i + 1; + wms_stock.count = line.planQty; + // item_id 统一写入实际匹配到的 StockStore 主键 id(纯数字), + // 避免中文后缀等非数字值写入 BIGINT 列触发 MySQL 严格模式报错 + wms_stock.item_id = wms_stock.id; items.push(wms_stock); } - console.log('items>>>>>', items); if (errors.length > 0) { await transaction.rollback(); // 验证失败,回滚事务 return { success: false, - message: '创建入库单失败,失败原因:\n' + errors.join('\n'), + message: `创建入库单失败,失败原因:\n${errors.join('\n')}`, data: { createTime: new Date(), }, }; } - // 创建入库单(内部也使用事务) + // 创建入库单(内部也使用事务),autoReview 在 addOrder 层控制最终状态 const order = await this.tryCreateEntryOrder( data.request.entryOrder, appKey, @@ -77,7 +164,6 @@ class entryOrderService extends Service { transaction // 传递事务 ); - console.log('入库单参数', order); if (!order.success) { await transaction.rollback(); return { @@ -94,12 +180,13 @@ class entryOrderService extends Service { errors = []; // 重置错误数组 // 添加商品明细 - for (var i = 0; i < items.length; i++) { + for (let i = 0; i < items.length; i++) { const item = items[i]; const res = await this.addItems(item, orderId, transaction); - console.log('添加商品返回信息', res); if (!res.success) { - errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); + // item.item_id / item.item_name / item.item_code 均取自校验阶段实际匹配到的 StockStore 实例, + // 保证失败行展示真实的 SKU 主键、商品名称与商品编码 + errors.push(`订单行${item.order_line_no}:SKU${item.item_id}商品《${item.item_name}》编码《${item.item_code}》入库失败,错误信息:${res.error}`); } } @@ -116,25 +203,61 @@ class entryOrderService extends Service { // 获取接收行数并处理状态 const lineCount = await this.getLineCount(orderId, transaction); + const expectedTotalOrderLines = Number(totalOrderLines) || 0; - if (lineCount == totalOrderLines) { - // 所有行数接收完成 - await this.received(orderId, warehouseId, storeId, transaction); + // autoReview 决定最终状态:true → PENDING(已审核),false → CREATED(已创建待审核) + const finalStatus = autoReview ? 'PENDING' : 'CREATED'; + + if (lineCount === expectedTotalOrderLines) { + // 所有明细行已插入完毕,将状态从 CREATING 更新为目标状态 + await app.model.EntryOrder.update( + { order_status: finalStatus, updated_at: new Date() }, + { where: { id: orderId, warehouse_id: warehouseId, store_id: storeId }, transaction } + ); } + // 写入操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: orderId, + operationCode: 'ENTRY_ORDER_CREATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + storeId, + entryOrderCode: orderCode, + sourceType: fromCode, + totalOrderLines, + finalStatus, + }, + transaction, + }); + // 提交事务 await transaction.commit(); - if (lineCount == totalOrderLines) { + // 异步匹配收货单并写入绑定关系(不阻塞 addOrder 返回) + if (lineCount === expectedTotalOrderLines) { + setImmediate(() => { + ctx.service.systems.receivingEntryMatch.matchAfterEntryCompleted(orderId).catch(err => { + ctx.logger.error(`[addOrder] 异步匹配收货单异常: ${err.message}`, err.stack); + }); + }); + } + + if (lineCount === expectedTotalOrderLines) { return { success: true, - message: '入库单接收完毕', + message: '入库单创建完成', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, - status: 'COMPLETED', + status: finalStatus, }, }; } @@ -142,21 +265,21 @@ class entryOrderService extends Service { // 部分接收或等待接收 return { success: true, - message: '入库单接收中', + message: '入库单创建中', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, - status: 'PARTIAL_RECEIVED', + status: 'CREATING', }, }; } catch (error) { // 发生异常,回滚事务 - await transaction.rollback().catch(e => console.error('回滚事务失败:', e)); + await transaction.rollback().catch(e => ctx.logger.error(`回滚事务失败: ${e.message}`, e)); - console.error('addOrder 事务异常:', error); + ctx.logger.error(`addOrder 事务异常: ${error.message}`, error); return { success: false, message: `系统异常: ${error.message}`, @@ -167,7 +290,12 @@ class entryOrderService extends Service { } } - // 辅助函数:获取行数(支持事务) + /** + * 获取入库单的明细行数(支持事务)。 + * @param {number} orderId 入库单ID + * @param {Object|null} [transaction=null] 可选事务对象 + * @return {Promise} 明细行数 + */ async getLineCount(orderId, transaction = null) { const { app } = this; const options = { @@ -182,10 +310,16 @@ class entryOrderService extends Service { return count; } - // 辅助函数:标记为已接收(支持事务) + /** + * 标记入库单为已完成(支持事务)。 + * @param {number} orderId 入库单ID + * @param {number} warehouseId 仓库ID + * @param {number} storeId 货主ID + * @param {Object|null} [transaction=null] 可选事务对象 + * @return {Promise} + */ async received(orderId, warehouseId, storeId, transaction = null) { const { app } = this; - const updateData = { order_status: 'COMPLETED', updated_at: new Date(), @@ -230,10 +364,361 @@ class entryOrderService extends Service { }; } - async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) { - const { app } = this; + async findByOrderCode(entryOrderCode, warehouseId, storeId) { + const { ctx } = this; + + return await ctx.model.EntryOrder.findOne({ + where: { + entry_order_code: entryOrderCode, + warehouse_id: warehouseId, + store_id: storeId, + is_enabled: 1, + deleted_at: null, + }, + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [[ 'company_name', 'store_name' ]], + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [[ 'company_name', 'store_name' ]], + }, + { + model: ctx.model.EntryItems, + as: 'items', + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'item_code', 'item_name' ], + }, + ], + }, + ], + }); + } + + async findByStatus(status, params = {}) { + const { ctx, app } = this; + const { warehouse_id, store_id, start_date, end_date, page = 1, pageSize = 20 } = params; + + const where = { + order_status: status, + is_enabled: 1, + deleted_at: null, + }; + + if (warehouse_id) { + where.warehouse_id = warehouse_id; + } + + if (store_id) { + where.store_id = store_id; + } + + if (start_date || end_date) { + where.created_at = {}; + if (start_date) { + where.created_at[app.Sequelize.Op.gte] = start_date; + } + if (end_date) { + where.created_at[app.Sequelize.Op.lte] = end_date; + } + } + + const currentPage = Math.max(Number(page) || 1, 1); + const currentPageSize = Math.max(Number(pageSize) || 20, 1); + + const { count, rows } = await ctx.model.EntryOrder.findAndCountAll({ + where, + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [[ 'company_name', 'store_name' ]], + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [[ 'company_name', 'store_name' ]], + }, + ], + order: [[ 'created_at', 'DESC' ]], + offset: (currentPage - 1) * currentPageSize, + limit: currentPageSize, + distinct: true, + }); + + return { + list: rows, + pagination: { + page: currentPage, + pageSize: currentPageSize, + total: count, + totalPages: Math.ceil(count / currentPageSize), + }, + }; + } + + async getStatsByWarehouse(warehouseId, startDate, endDate) { + const { ctx, app } = this; + + const where = { + warehouse_id: warehouseId, + is_enabled: 1, + deleted_at: null, + }; + + if (startDate || endDate) { + where.created_at = {}; + if (startDate) { + where.created_at[app.Sequelize.Op.gte] = startDate; + } + if (endDate) { + where.created_at[app.Sequelize.Op.lte] = endDate; + } + } + + const result = await ctx.model.EntryOrder.findAll({ + attributes: [ + 'order_status', + [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'count' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('total_order_lines')), 'total_lines' ], + ], + where, + group: [ 'order_status' ], + raw: true, + }); + + const stats = { + pending: 0, + completed: 0, + cancelled: 0, + total: 0, + total_lines: 0, + }; + + result.forEach(item => { + const status = String(item.order_status || '').toLowerCase(); + const count = parseInt(item.count, 10) || 0; + const totalLines = parseInt(item.total_lines, 10) || 0; + + if (stats[status] !== undefined) { + stats[status] = count; + } + + stats.total += count; + stats.total_lines += totalLines; + }); + + return stats; + } + + async updateSyncStatus(orderId, status, message = null, options = {}) { + const { ctx } = this; + const order = await ctx.model.EntryOrder.findByPk(orderId, { + transaction: options.transaction, + }); + + if (!order) { + throw new Error('入库单不存在'); + } + + const updateData = { + sync_status: status, + }; + + if (message !== null) { + updateData.sync_message = message; + } + + return await order.update(updateData, { + transaction: options.transaction, + }); + } + + async updateOrderStatus(orderId, status, options = {}) { + const { ctx } = this; + const order = await ctx.model.EntryOrder.findByPk(orderId, { + transaction: options.transaction, + }); + + if (!order) { + throw new Error('入库单不存在'); + } + + const validTransitions = { + CREATED: [ 'PENDING', 'CANCELLED' ], + PENDING: [ 'COMPLETED', 'CANCELLED' ], + CREATING: [ 'CREATED', 'CANCELLED' ], + }; + + const allowedTransitions = validTransitions[order.order_status]; + if (!allowedTransitions || !allowedTransitions.includes(status)) { + throw new Error(`状态从${order.order_status}转换到${status}不被允许`); + } + + return await order.update({ order_status: status }, { + transaction: options.transaction, + }); + } + + async calculateReceivedQuantities(orderId) { + const { ctx, app } = this; + const order = await ctx.model.EntryOrder.findByPk(orderId, { + attributes: [ 'id', 'entry_order_code' ], + raw: true, + }); + + if (!order) { + throw new Error('入库单不存在'); + } + + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: orderId }, + attributes: [ 'id', 'count', 'item_id' ], + raw: true, + }); + + const itemIds = [ ...new Set(items.map(item => item.item_id).filter(Boolean)) ]; + const receivedRows = itemIds.length > 0 + ? await ctx.model.Storage.findAll({ + where: { + inbound_order_no: order.entry_order_code, + item_id: itemIds, + }, + attributes: [ + 'item_id', + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'received' ], + ], + group: [ 'item_id' ], + raw: true, + }) + : []; + + const receivedMap = new Map( + receivedRows.map(row => [ Number(row.item_id), Number(row.received) || 0 ]) + ); + + let totalExpected = 0; + let totalReceived = 0; + let allReceived = items.length > 0; + let anyReceived = false; + + items.forEach(item => { + const expected = Number(item.count) || 0; + const received = receivedMap.get(Number(item.item_id)) || 0; + + totalExpected += expected; + totalReceived += received; + + if (expected > 0 && received < expected) { + allReceived = false; + } + + if (received > 0) { + anyReceived = true; + } + }); + + return { + total_expected: totalExpected, + total_received: totalReceived, + all_received: allReceived, + any_received: anyReceived, + percentage: totalExpected > 0 ? Math.round((totalReceived / totalExpected) * 100) : 0, + }; + } + + async batchUpdateReceived(updates, options = {}) { + const { ctx } = this; + const externalTransaction = options.transaction || null; + const transaction = externalTransaction || await ctx.model.transaction(); + + try { + const pendingUpdates = []; + + for (const update of updates) { + const { id, quantity } = update; + const item = await ctx.model.EntryItems.findByPk(id, { transaction }); + + if (!item) { + throw new Error(`入库明细 ${id} 不存在`); + } + + item.validateReceiveQuantity(quantity); + pendingUpdates.push({ + item, + quantity, + }); + } + + for (const pending of pendingUpdates) { + const newReceived = (pending.item.received_quantity || 0) + pending.quantity; + await pending.item.update({ + received_quantity: newReceived, + }, { transaction }); + } + + if (!externalTransaction) { + await transaction.commit(); + } + + return { success: true }; + } catch (error) { + if (!externalTransaction) { + await transaction.rollback(); + } + throw error; + } + } + + async getOrderProgress(orderId) { + const { ctx, app } = this; + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: orderId }, + attributes: [ + [ app.Sequelize.fn('SUM', app.Sequelize.col('count')), 'total_plan' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('received_quantity')), 'total_received' ], + [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'item_count' ], + ], + raw: true, + }); + + const result = items[0] || {}; + const totalPlan = parseInt(result.total_plan, 10) || 0; + const totalReceived = parseInt(result.total_received, 10) || 0; + + return { + total_plan: totalPlan, + total_received: totalReceived, + total_remaining: Math.max(0, totalPlan - totalReceived), + item_count: parseInt(result.item_count, 10) || 0, + progress_percent: totalPlan > 0 ? Math.min(100, Math.round((totalReceived / totalPlan) * 100)) : 0, + is_completed: totalReceived >= totalPlan, + }; + } + + /** + * 尝试创建入库单(含去重与状态校验)。 + * 若入库单已存在且状态为 CREATING,则复用该记录;否则新建,初始状态为 CREATING。 + * 最终状态(CREATED / PENDING)由调用方 addOrder 根据 autoReview 决定。 + * @param {Object} order 入库单基本信息 + * @param {string} appKey 应用标识 + * @param {number} storeId 货主ID + * @param {number} warehouseId 仓库ID + * @param {number} totalOrderLines 总行数 + * @param {string} sourceType 来源类型(WMS / API / QM) + * @param {string|null} qimenOwnerCode 奇门货主编码 + * @param {string|null} qimenWarehouseCode 奇门仓库编码 + * @param {Object|null} [transaction=null] 外部事务对象 + * @return {Promise} { success, code, message, entryOrderId, entryOrderCode, orderStatus, error? } + */ + async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) { const { ctx } = this; - console.log('创建入库单信息', order, appKey, storeId, warehouseId); try { const options = transaction ? { transaction } : {}; @@ -259,8 +744,6 @@ class entryOrderService extends Service { updated_at: new Date(), }, options); - console.log(`入库单 ${order.entryOrderCode} 已存在,状态更新为接收中`); - return { success: true, code: 1, @@ -303,18 +786,18 @@ class entryOrderService extends Service { const warehouse_data = await this.ctx.service.systems.store.getStoreName(warehouseId); let store_name = null; let warehouse_name = null; - if (warehouse_data.code == 200) { + if (warehouse_data.code === 200) { warehouse_name = warehouse_data.data.company_name; } const store_data = await this.ctx.service.systems.store.getStoreName(storeId); - if (store_data.code == 200) { + if (store_data.code === 200) { store_name = store_data.data.company_name; } const contract_data = await this.ctx.service.systems.store.getStoreRemaskName(storeId, warehouseId); let contract = null; - if (contract_data.code == 200) { + if (contract_data.code === 200) { contract = contract_data.data; } // 构建入库单数据 @@ -325,7 +808,7 @@ class entryOrderService extends Service { total_order_lines: totalOrderLines, order_create_time: order.orderCreateTime ? new Date(order.orderCreateTime) : new Date(), expect_start_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(), - expect_end_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(), + expect_end_time: order.expectEndTime ? new Date(order.expectEndTime) : new Date(), logistics_code: order.logisticsCode || '', logistics_name: order.logisticsName || '', express_code: order.expressCode || '', @@ -355,8 +838,6 @@ class entryOrderService extends Service { await internalTransaction.commit(); } - console.log(`成功创建入库单: ${order.entryOrderCode}, ID: ${newEntryOrder.id}`); - return { success: true, code: 1, @@ -366,7 +847,6 @@ class entryOrderService extends Service { }; } catch (error) { - console.log('创建入库单失败', error); // 如果这是内部创建的事务,回滚它 if (internalTransaction) { await internalTransaction.rollback(); @@ -389,10 +869,17 @@ class entryOrderService extends Service { } } + /** + * 添加入库单明细行(按 order_line_no 幂等去重)。 + * 写入前将 item_id 强制转为合法数字,非法值兜底为 0, + * 避免中文后缀等非数字值写入 BIGINT 列触发 MySQL 严格模式报错。 + * @param {Object} item 明细行数据(来自 StockStore 实例并附加了 order_line_no / count / item_id 等字段) + * @param {number} orderId 入库单 ID + * @param {Object|null} [transaction=null] 可选事务对象 + * @return {Promise} { success, code, message? } 成功时 code=1 + */ async addItems(item, orderId, transaction = null) { - const { app } = this; const { ctx } = this; - console.log('添加入库单商品'); try { const options = transaction ? { transaction } : {}; @@ -408,6 +895,8 @@ class entryOrderService extends Service { if (!existingOrderItem) { try { + // item_id 必须是合法数字(StockStore 主键),非法值兜底为 0 + const numericItemId = Number(item.item_id); // 构建入库明细数据 const entryItemsData = { order_id: orderId, @@ -415,7 +904,7 @@ class entryOrderService extends Service { order_line_no: item.order_line_no || '', owner_code: item.owner_code || '', item_code: item.item_code || '', - item_id: item.item_id || 0, + item_id: Number.isFinite(numericItemId) ? numericItemId : 0, count: item.count || 0, inventory_type: item.inventory_type || '', stock_id: item.stock_id || '', @@ -431,7 +920,6 @@ class entryOrderService extends Service { code: 1, }; } catch (error) { - console.log('添加商品明细出错', error); throw error; } } @@ -453,299 +941,75 @@ class entryOrderService extends Service { } } - async received(orderId, warehouseId, storeId, transaction = null) { - console.log('完结传参', orderId, warehouseId, storeId); - const { app } = this; - const { ctx } = this; + /** + * 审核入库单(CREATED → PENDING)。 + * 只允许已绑定收货单的入库单推进状态,未绑定则拒绝。 + * + * @param {Object} data 请求体 + * @param {number} data.id 入库单 ID + * @return {Promise} { success, message, data } + */ + async reviewEntry(data = {}) { + const { app, ctx } = this; + const orderId = Number(data.id || 0); - const options = transaction ? { transaction } : {}; + if (!orderId) { + return { success: false, message: 'id 必填' }; + } - const existingOrder = await ctx.model.EntryOrder.findOne({ - where: { - warehouse_id: warehouseId, - store_id: storeId, - id: orderId, - }, - ...options, + const entryOrder = await app.model.EntryOrder.findOne({ + where: { id: orderId, is_enabled: 1, deleted_at: null }, }); - if (!existingOrder) { + if (!entryOrder) { + return { success: false, message: '入库单不存在' }; + } + + if (entryOrder.order_status !== 'CREATED') { return { success: false, - code: 0, - message: '入库单不存在', - entryOrderId: null, - orderStatus: null, - error: '入库单不存在', + message: `当前状态[${entryOrder.order_status}]不允许审核,仅 CREATED 可审核`, }; } - const allowedStatuses = [ 'CREATING' ]; - if (allowedStatuses.includes(existingOrder.order_status)) { - await existingOrder.update({ - order_status: 'CREATED', - updated_at: new Date(), - }, options); + // 校验:必须有绑定的收货单 + const hasReceiving = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: orderId, deleted_at: null }, + }); + if (!hasReceiving) { + return { + success: false, + message: '入库单未绑定收货单,请先绑定收货单后再审核', + }; } + // 推进状态 + await entryOrder.update({ + order_status: 'PENDING', + updated_at: new Date(), + }); + + // 写操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'ENTRY_ORDER_REVIEW', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: '入库单审核通过(CREATED → PENDING)', + }, + }); + return { success: true, - code: 1, - message: '完成', + message: '审核成功', + data: { id: entryOrder.id, order_status: 'PENDING' }, }; } - - async qimenEntryorderConfirm(entryOrder, orderLines, isFin, outBizCode) { - if (orderLines.length < 1) { - throw new Error('行不能为空'); - } - console.log('isFin:', isFin); - const queryData = { - request: { - entryOrder: { - entryOrderCode: entryOrder.entry_order_code, - ownerCode: entryOrder.qimen_owner_code, - warehouseCode: entryOrder.qimen_warehouse_code, - entryOrderId: entryOrder.id, - entryOrderType: entryOrder.order_type, - outBizCode, - confirmType: isFin ? 0 : 1, - status: isFin ? 'FULFILLED' : 'PARTFULFILLED', - freight: 0, - operateTime: new Date().format(), - remark: entryOrder.remark, - }, - orderLines, - }, - }; - const Result = await this.ctx.service.systems.qimenQuery.send('taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData); - return Result; - } - async entryorderConfirm(orderId, isCompleted) { - const { app, ctx } = this; - const transaction = await app.model.transaction(); - - try { - // 锁定数据 - const entryOrder = await app.model.EntryOrder.findOne({ - where: { - id: orderId, - is_enabled: 1, - deleted_at: null, - }, - include: [ - { - model: app.model.EntryItems, - as: 'items', - lock: transaction.LOCK.UPDATE, - }, - ], - lock: transaction.LOCK.UPDATE, - transaction, - }); - - if (!entryOrder) { - await transaction.rollback(); - return { success: false, message: '入库单不存在' }; - } - - // 状态检查 - const allowedStatuses = [ 'CREATED', 'PARTIAL_RECEIVED', 'CONFIRMED' ]; - if (!allowedStatuses.includes(entryOrder.order_status)) { - await transaction.rollback(); - return { - success: false, - code: 'INVALID_STATUS', - message: `入库单状态[${entryOrder.order_status}]不允许确认`, - }; - } - - const orderLines = []; - let totalPlanQty = 0; - let totalReceivedQty = 0; - let totalConfirmIncrement = 0; - let hasItemsToConfirm = false; - - // 第一阶段:计算和验证,不执行更新 - const pendingUpdates = []; - - for (let i = 0; i < entryOrder.items.length; i++) { - const item = entryOrder.items[i]; - const planQty = item.count || 0; - const receivedQty = item.received_quantity || 0; - const confirmedQty = item.confirm_quantity || 0; - - // 计算本次确认的增量 - const confirmIncrement = Math.max(0, receivedQty - confirmedQty); - - if (confirmIncrement > 0) { - hasItemsToConfirm = true; - - // 奇门需要的是本次确认的数量(actualQty) - const orderLine = { - orderLineNo: i + 1, - ownerCode: item.owner_code, - itemCode: item.item_code, - itemId: item.item_id, - inventoryType: item.inventory_type, - planQty, - actualQty: confirmIncrement, // 传本次增量 - }; - orderLines.push(orderLine); - - totalConfirmIncrement += confirmIncrement; - - // 记录待更新数据(不执行) - pendingUpdates.push({ - id: item.id, - item_id: item.item_id, - new_confirm_quantity: confirmedQty + confirmIncrement, - old_confirm_quantity: confirmedQty, - received_quantity: receivedQty, - confirm_increment: confirmIncrement, - }); - } - - totalPlanQty += planQty; - totalReceivedQty += receivedQty; - } - - // 没有需要确认的数量 - if (!hasItemsToConfirm) { - await transaction.rollback(); - return { success: false, message: '没有需要确认的收货数量' }; - } - - // 判断是否最终完成 - const isFin = isCompleted ? true : (totalReceivedQty >= totalPlanQty); - let qimenResult = {}; - let queryId = null; - // 奇门入库单,数据同步到奇门 - if (entryOrder.source_type == 'QM') { - // 第二阶段:调用奇门接口 - const Result = await this.qimenEntryorderConfirm( - entryOrder, - orderLines, - isFin, - Math.round(new Date() / 1000) - ); - console.log(Result); - queryId = Result.queryId; - qimenResult = Result.xmlArray.response; - // 奇门调用失败,回滚事务 - if (!qimenResult || qimenResult.flag != 'success') { - await transaction.rollback(); - console.error('奇门接口调用失败:', qimenResult); - return { - success: false, - code: 'QIMEN_FAILED', - message: '奇门接口调用失败', - detail: qimenResult?.message || '未知错误', - }; - } - } - // 第三阶段:奇门成功,执行数据库更新 - - // 1. 更新确认数量 - for (const update of pendingUpdates) { - const result = await app.model.EntryItems.update({ - confirm_quantity: update.new_confirm_quantity, - updated_at: new Date(), - }, { - where: { - id: update.id, - confirm_quantity: update.old_confirm_quantity, // 乐观锁,防止并发 - }, - transaction, - }); - const res = await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction); - console.log('增加库存返回', res); - if (result[0] === 0) { - // 更新失败,可能被并发修改了 - console.warn(`更新入库明细失败,可能已被修改: id=${update.id}`); - // 可以选择重试或抛出异常 - } - } - - // 2. 更新入库单状态 - let newOrderStatus = entryOrder.order_status; - if (isFin) { - newOrderStatus = 'COMPLETED'; - } else if (totalConfirmIncrement > 0) { - if (entryOrder.order_status === 'CREATED') { - newOrderStatus = 'CONFIRMED'; - } else { - newOrderStatus = 'PARTIAL_RECEIVED'; - } - } - - const updateResult = await app.model.EntryOrder.update({ - order_status: newOrderStatus, - sync_status: 'SUCCESS', - sync_message: JSON.stringify({ - confirmTime: new Date(), - totalPlan: totalPlanQty, - totalReceived: totalReceivedQty, - totalConfirmIncrement, - isFin, - pendingUpdatesCount: pendingUpdates.length, - qimenResult: qimenResult?.data || {}, - }), - updated_at: new Date(), - }, { - where: { - id: entryOrder.id, - order_status: entryOrder.order_status, // 乐观锁 - }, - transaction, - }); - - if (updateResult[0] === 0) { - // 入库单状态已被修改,回滚 - await transaction.rollback(); - return { - success: false, - code: 'CONCURRENT_MODIFICATION', - message: '入库单已被修改,请刷新后重试', - }; - } - // 4. 提交事务 - await transaction.commit(); - - console.log(`入库单确认成功: id=${entryOrder.id}, 确认增量=${totalConfirmIncrement}, 状态=${newOrderStatus}`); - - return { - success: true, - message: isFin ? '入库单完成确认' : '入库单增量确认成功', - data: { - entryOrderId: entryOrder.id, - entryOrderCode: entryOrder.entry_order_code, - orderStatus: newOrderStatus, - totalPlan: totalPlanQty, - totalReceived: totalReceivedQty, - totalConfirmIncrement, - isFin, - updatedItemsCount: pendingUpdates.length, - orderLinesCount: orderLines.length, - }, - }; - - } catch (error) { - // 发生异常,回滚事务 - await transaction.rollback().catch(e => { - console.error('回滚事务失败:', e); - }); - - console.error('确认入库单失败:', error); - - return { - success: false, - code: 'SYSTEM_ERROR', - message: `系统异常: ${error.message}`, - stack: process.env.NODE_ENV === 'development' ? error.stack : undefined, - }; - } - } } module.exports = entryOrderService; diff --git a/app/service/systems/excel.js b/app/service/systems/excel.js new file mode 100644 index 0000000..d101ae4 --- /dev/null +++ b/app/service/systems/excel.js @@ -0,0 +1,944 @@ +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); +const { Readable } = require('stream'); +const Service = require('egg').Service; +const XLSX = require('xlsx'); +const ExcelJS = require('exceljs'); + +const CONTENT_TYPE_MAP = { + xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + xls: 'application/vnd.ms-excel', + csv: 'text/csv; charset=utf-8', +}; + +class ExcelService extends Service { + getContentType(bookType = 'xlsx') { + const normalizedType = String(bookType || 'xlsx').replace('.', '').toLowerCase(); + return CONTENT_TYPE_MAP[normalizedType] || CONTENT_TYPE_MAP.xlsx; + } + + sanitizeSheetName(name, index = 1) { + const safeName = String(name || `Sheet${index}`) + .replace(/[\\/?*\[\]:]/g, '_') + .trim(); + + return (safeName || `Sheet${index}`).slice(0, 31); + } + + normalizeHeaders(headerRow = []) { + const usedNames = new Set(); + + return headerRow.map((value, index) => { + const baseName = String(value == null ? '' : value).trim() || `column_${index + 1}`; + let uniqueName = baseName; + let suffix = 2; + + while (usedNames.has(uniqueName)) { + uniqueName = `${baseName}_${suffix}`; + suffix += 1; + } + + usedNames.add(uniqueName); + return uniqueName; + }); + } + + normalizeColumns(columns = []) { + if (!Array.isArray(columns)) { + return []; + } + + return columns + .map(column => { + if (!column) { + return null; + } + + const key = column.key || column.field || column.dataIndex || column.prop; + const header = column.header || column.title || column.label || key; + + if (!key && !header) { + return null; + } + + return { + key: key || header, + header: header || key, + width: Number(column.width || column.wch || 0) || undefined, + }; + }) + .filter(Boolean); + } + + prepareSheetData(sheetConfig = {}) { + const { + rows = [], + columns = [], + header = [], + skipHeader = false, + widths = [], + } = sheetConfig; + + const normalizedColumns = this.normalizeColumns(columns); + let aoaData = []; + + if (normalizedColumns.length > 0) { + const headerRow = normalizedColumns.map(column => column.header); + const columnKeys = normalizedColumns.map(column => column.key); + const bodyRows = Array.isArray(rows) + ? rows.map(row => { + if (Array.isArray(row)) { + return row; + } + + return columnKeys.map(key => (row && typeof row === 'object' ? row[key] : '')); + }) + : []; + aoaData = skipHeader ? bodyRows : [ headerRow, ...bodyRows ]; + } else if (Array.isArray(rows) && rows.length > 0 && Array.isArray(rows[0])) { + aoaData = Array.isArray(header) && header.length > 0 && !skipHeader + ? [ header, ...rows ] + : rows; + } else if (Array.isArray(rows) && rows.length > 0) { + const derivedHeaders = Array.isArray(header) && header.length > 0 + ? header + : Object.keys(rows[0] || {}); + const bodyRows = rows.map(row => derivedHeaders.map(key => (row && typeof row === 'object' ? row[key] : ''))); + aoaData = skipHeader ? bodyRows : [ derivedHeaders, ...bodyRows ]; + } else { + aoaData = Array.isArray(header) && header.length > 0 ? [ header ] : []; + } + + const resolvedWidths = Array.isArray(widths) && widths.length > 0 + ? widths.map(item => (typeof item === 'number' ? { wch: item } : item)) + : normalizedColumns + .filter(column => column.width) + .map(column => ({ wch: column.width })); + + return { + normalizedColumns, + aoaData, + resolvedWidths, + skipHeader, + originalRows: Array.isArray(rows) ? rows : [], + }; + } + + hasEmbeddedImages(options = {}) { + return Array.isArray(options.sheets) + && options.sheets.some(sheet => Array.isArray(sheet && sheet.embeddedImages) && sheet.embeddedImages.length > 0); + } + + buildWorksheet(sheetConfig = {}) { + const { + merges = [], + textColumns = [], + } = sheetConfig; + const { + aoaData, + resolvedWidths, + } = this.prepareSheetData(sheetConfig); + + const worksheet = XLSX.utils.aoa_to_sheet(aoaData); + + if (resolvedWidths.length > 0) { + worksheet['!cols'] = resolvedWidths; + } + + if (Array.isArray(merges) && merges.length > 0) { + worksheet['!merges'] = merges; + } + + this.applyTextColumnsToSheetJs(worksheet, textColumns); + + return worksheet; + } + + buildWorkbook(options = {}) { + const { sheets = [], props = {} } = options; + + if (!Array.isArray(sheets) || sheets.length === 0) { + throw new Error('至少需要一个 sheet 配置'); + } + + const workbook = XLSX.utils.book_new(); + workbook.Props = { + Company: 'WMS', + CreatedDate: new Date(), + ...props, + }; + + sheets.forEach((sheetConfig, index) => { + const worksheet = this.buildWorksheet(sheetConfig || {}); + const sheetName = this.sanitizeSheetName(sheetConfig && sheetConfig.name, index + 1); + XLSX.utils.book_append_sheet(workbook, worksheet, sheetName); + }); + + return workbook; + } + + async buildExcelJsWorkbook(options = {}) { + const { sheets = [], props = {} } = options; + + if (!Array.isArray(sheets) || sheets.length === 0) { + throw new Error('至少需要一个 sheet 配置'); + } + + const workbook = new ExcelJS.Workbook(); + workbook.creator = props.author || 'WMS'; + workbook.company = props.company || 'WMS'; + workbook.created = props.createdAt || new Date(); + workbook.modified = new Date(); + + for (let index = 0; index < sheets.length; index += 1) { + const sheetConfig = sheets[index] || {}; + const sheetName = this.sanitizeSheetName(sheetConfig.name, index + 1); + const worksheet = workbook.addWorksheet(sheetName); + const { + merges = [], + embeddedImages = [], + styledRows = [], + textColumns = [], + } = sheetConfig; + const { + normalizedColumns, + aoaData, + resolvedWidths, + skipHeader, + originalRows, + } = this.prepareSheetData(sheetConfig); + + if (normalizedColumns.length > 0 && originalRows.length > 0 && !Array.isArray(originalRows[0])) { + if (skipHeader) { + aoaData.forEach(row => worksheet.addRow(row)); + } else { + worksheet.columns = normalizedColumns.map(column => ({ + header: column.header, + key: column.key, + width: column.width || 18, + })); + originalRows.forEach(row => worksheet.addRow(row || {})); + } + } else if (normalizedColumns.length > 0 && originalRows.length === 0 && !skipHeader) { + worksheet.columns = normalizedColumns.map(column => ({ + header: column.header, + key: column.key, + width: column.width || 18, + })); + } else { + aoaData.forEach(row => worksheet.addRow(row)); + } + + if (resolvedWidths.length > 0) { + resolvedWidths.forEach((column, columnIndex) => { + const width = Number(column && column.wch) || Number(column && column.width) || undefined; + if (width) { + worksheet.getColumn(columnIndex + 1).width = width; + } + }); + } + + if (Array.isArray(merges) && merges.length > 0) { + merges.forEach(merge => { + if (!merge) { + return; + } + + if (typeof merge === 'string') { + worksheet.mergeCells(merge); + return; + } + + if (merge.s && merge.e) { + worksheet.mergeCells(merge.s.r + 1, merge.s.c + 1, merge.e.r + 1, merge.e.c + 1); + } + }); + } + + if (Array.isArray(styledRows) && styledRows.length > 0) { + this.applyStyledRows(worksheet, styledRows); + } + + if (Array.isArray(textColumns) && textColumns.length > 0) { + this.applyTextColumnsToExcelJs(worksheet, textColumns); + } + + if (Array.isArray(embeddedImages) && embeddedImages.length > 0) { + await this.addEmbeddedImages(workbook, worksheet, embeddedImages); + } + } + + return workbook; + } + + inferImageExtension(imageConfig = {}, contentType = '') { + const preferred = String(imageConfig.extension || '').replace('.', '').toLowerCase(); + if (preferred) { + return preferred === 'jpg' ? 'jpeg' : preferred; + } + + const fileSource = imageConfig.url || imageConfig.filePath || imageConfig.filename || ''; + const ext = path.extname(String(fileSource)).replace('.', '').toLowerCase(); + if (ext) { + return ext === 'jpg' ? 'jpeg' : ext; + } + + if (contentType.includes('png')) return 'png'; + if (contentType.includes('gif')) return 'gif'; + if (contentType.includes('jpg') || contentType.includes('jpeg')) return 'jpeg'; + if (contentType.includes('webp')) return 'png'; + + return 'png'; + } + + async resolveImageSource(imageConfig = {}) { + try { + if (imageConfig.buffer) { + return { + buffer: Buffer.isBuffer(imageConfig.buffer) ? imageConfig.buffer : Buffer.from(imageConfig.buffer), + extension: this.inferImageExtension(imageConfig), + }; + } + + if (imageConfig.dataUrl) { + const match = String(imageConfig.dataUrl).match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/); + if (match) { + return { + buffer: Buffer.from(match[2], 'base64'), + extension: this.inferImageExtension(imageConfig, match[1]), + }; + } + } + + if (imageConfig.base64) { + return { + buffer: Buffer.from(String(imageConfig.base64), 'base64'), + extension: this.inferImageExtension(imageConfig), + }; + } + + if (imageConfig.filePath) { + const resolvedFilePath = path.resolve(String(imageConfig.filePath)); + const buffer = await fs.promises.readFile(resolvedFilePath); + return { + buffer, + extension: this.inferImageExtension({ ...imageConfig, filePath: resolvedFilePath }), + }; + } + + if (imageConfig.url) { + const imageUrl = String(imageConfig.url); + const dataUrlMatch = imageUrl.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/); + if (dataUrlMatch) { + return { + buffer: Buffer.from(dataUrlMatch[2], 'base64'), + extension: this.inferImageExtension(imageConfig, dataUrlMatch[1]), + }; + } + + if (this.ctx && typeof this.ctx.curl === 'function') { + const response = await this.ctx.curl(imageUrl, { + method: 'GET', + timeout: 15000, + followRedirect: true, + }); + const contentType = String((response.headers && (response.headers['content-type'] || response.headers['Content-Type'])) || '').toLowerCase(); + const buffer = Buffer.isBuffer(response.data) ? response.data : Buffer.from(response.data || ''); + + if (buffer.length > 0) { + return { + buffer, + extension: this.inferImageExtension(imageConfig, contentType), + }; + } + } else if (typeof fetch === 'function' && /^https?:\/\//i.test(imageUrl)) { + const response = await fetch(imageUrl); + if (response && response.ok) { + const contentType = String(response.headers.get('content-type') || '').toLowerCase(); + const arrayBuffer = await response.arrayBuffer(); + const buffer = Buffer.from(arrayBuffer); + + if (buffer.length > 0) { + return { + buffer, + extension: this.inferImageExtension(imageConfig, contentType), + }; + } + } + } + } + } catch (error) { + if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') { + this.ctx.logger.warn('[ExcelService.resolveImageSource] 图片加载失败: %s', error.message); + } + } + + return null; + } + + mergeCellStyle(baseStyle = {}, patchStyle = {}) { + const mergedStyle = { + ...baseStyle, + ...patchStyle, + }; + + if (baseStyle.font || patchStyle.font) { + mergedStyle.font = { + ...(baseStyle.font || {}), + ...(patchStyle.font || {}), + }; + } + + if (baseStyle.alignment || patchStyle.alignment) { + mergedStyle.alignment = { + ...(baseStyle.alignment || {}), + ...(patchStyle.alignment || {}), + }; + } + + if (baseStyle.protection || patchStyle.protection) { + mergedStyle.protection = { + ...(baseStyle.protection || {}), + ...(patchStyle.protection || {}), + }; + } + + if (patchStyle.fill) { + mergedStyle.fill = patchStyle.fill; + } + + if (patchStyle.border) { + mergedStyle.border = patchStyle.border; + } + + if (patchStyle.numFmt) { + mergedStyle.numFmt = patchStyle.numFmt; + } + + return mergedStyle; + } + + applyStyledRows(worksheet, styledRows = []) { + styledRows.forEach(item => { + if (!item) { + return; + } + + const rowNumber = Math.max(Number(item.row || 1), 1); + const fromCol = Math.max(Number(item.fromCol || 1), 1); + const toCol = Math.max(Number(item.toCol || fromCol), fromCol); + const row = worksheet.getRow(rowNumber); + + if (item.height) { + row.height = item.height; + } + + if (item.style && typeof item.style === 'object') { + for (let col = fromCol; col <= toCol; col += 1) { + const cell = worksheet.getCell(rowNumber, col); + cell.style = this.mergeCellStyle(cell.style || {}, item.style); + } + } + }); + } + + /** + * SheetJS 路径:将 textColumns 指定列落地为文本单元格。 + * 单元格类型强制为文本(t:'s')、值转字符串,并附加文本数字格式(z:'@'), + * 防止长数字串被 Excel 按数值展示成科学计数法。 + * @param {Object} worksheet SheetJS 工作表对象 + * @param {Array} [textColumns=[]] 0 基文本列索引列表 + * @return {void} 无返回值 + */ + applyTextColumnsToSheetJs(worksheet, textColumns = []) { + if (!worksheet || !Array.isArray(textColumns) || textColumns.length === 0) { + return; + } + + const columnSet = new Set( + textColumns.map(index => Math.max(0, Math.floor(Number(index) || 0))) + ); + const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1'); + + for (let row = range.s.r; row <= range.e.r; row += 1) { + for (const column of columnSet) { + if (column > range.e.c) { + continue; + } + const address = XLSX.utils.encode_cell({ r: row, c: column }); + const cell = worksheet[address]; + if (!cell) { + continue; + } + if (cell.v !== null && cell.v !== undefined) { + cell.t = 's'; + cell.v = String(cell.v); + } + cell.z = '@'; + } + } + } + + /** + * ExcelJS 路径:将 textColumns 指定列落地为文本单元格。 + * 单元格值转为字符串(原始对象类型除外),并设置文本数字格式 numFmt='@', + * 防止长数字串被 Excel 按数值展示成科学计数法。 + * @param {Object} worksheet ExcelJS 工作表对象 + * @param {Array} [textColumns=[]] 0 基文本列索引列表 + * @return {void} 无返回值 + */ + applyTextColumnsToExcelJs(worksheet, textColumns = []) { + if (!worksheet || !Array.isArray(textColumns) || textColumns.length === 0) { + return; + } + + const columnSet = new Set( + textColumns.map(index => Math.max(1, Math.floor(Number(index) || 0) + 1)) + ); + + for (let row = 1; row <= worksheet.rowCount; row += 1) { + worksheet.getRow(row).eachCell({ includeEmpty: false }, (cell, columnNumber) => { + if (!columnSet.has(columnNumber)) { + return; + } + const value = cell.value; + if (value !== null && value !== undefined && typeof value !== 'object') { + cell.value = String(value); + } + cell.numFmt = '@'; + }); + } + } + + async addEmbeddedImages(workbook, worksheet, embeddedImages = []) { + for (const imageConfig of embeddedImages) { + if (!imageConfig) { + continue; + } + + const row = Math.max(Number(imageConfig.row || 1), 1); + const col = Math.max(Number(imageConfig.col || imageConfig.column || 1), 1); + const width = Math.max(Number(imageConfig.width || 120), 40); + const height = Math.max(Number(imageConfig.height || 120), 40); + const cell = worksheet.getCell(row, col); + const fallbackText = imageConfig.fallbackText || imageConfig.url || ''; + const resolvedImage = await this.resolveImageSource(imageConfig); + + if (!resolvedImage || !resolvedImage.buffer || resolvedImage.buffer.length === 0) { + if (fallbackText) { + cell.value = fallbackText; + } + continue; + } + + const imageId = workbook.addImage({ + buffer: resolvedImage.buffer, + extension: resolvedImage.extension, + }); + + worksheet.addImage(imageId, { + tl: { col: col - 1 + 0.05, row: row - 1 + 0.05 }, + ext: { width, height }, + editAs: 'oneCell', + }); + + if (fallbackText) { + cell.value = fallbackText; + } + + worksheet.getRow(row).height = Math.max(Number(worksheet.getRow(row).height || 20), Math.ceil(height * 0.75)); + worksheet.getColumn(col).width = Math.max(Number(worksheet.getColumn(col).width || 10), Math.ceil(width / 7)); + } + } + + async generateBuffer(options = {}) { + const bookType = String(options.bookType || 'xlsx').replace('.', '').toLowerCase(); + + const shouldUseExcelJs = this.hasEmbeddedImages(options) + || (Array.isArray(options.sheets) + && options.sheets.some(sheet => sheet && (sheet.forceExcelJs || (Array.isArray(sheet.styledRows) && sheet.styledRows.length > 0)))); + + if (shouldUseExcelJs) { + if (bookType !== 'xlsx') { + throw new Error('带图片的 Excel 仅支持 xlsx 格式'); + } + + const workbook = await this.buildExcelJsWorkbook({ + ...options, + bookType, + }); + const buffer = await workbook.xlsx.writeBuffer(); + return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer); + } + + const workbook = this.buildWorkbook(options); + const buffer = XLSX.write(workbook, { + type: 'buffer', + bookType, + compression: true, + }); + + return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer); + } + + async writeFile(filePath, options = {}) { + if (!filePath) { + throw new Error('filePath 不能为空'); + } + + const resolvedFilePath = path.resolve(filePath); + const ext = path.extname(resolvedFilePath).replace('.', '').toLowerCase() || options.bookType || 'xlsx'; + const buffer = await this.generateBuffer({ + ...options, + bookType: ext, + }); + + await fs.promises.mkdir(path.dirname(resolvedFilePath), { recursive: true }); + await this.writeAtomicBufferFile(resolvedFilePath, buffer); + + return { + filePath: resolvedFilePath, + size: buffer.length, + bookType: ext, + }; + } + + 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); + const ext = rawExt || fallbackExt; + const baseName = path.basename(normalizedName, rawExt); + const safeBaseName = String(baseName || 'export') + .replace(/[<>:"/\\|?*]/g, '_') + .replace(/\s+/g, '_') + .replace(/_+/g, '_') + .replace(/^_+|_+$/g, '') + .slice(0, 120) || 'export'; + + return `${safeBaseName}${ext}`; + } + + buildUploadKey(filename, options = {}) { + if (options.key) { + return String(options.key) + .replace(/\\/g, '/') + .replace(/^\/+/, '') + .replace(/\/+/g, '/'); + } + + const now = new Date(); + const dateFolder = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; + const normalizedDir = String(options.dir || 'exports/excel') + .replace(/\\/g, '/') + .replace(/^\/+|\/+$/g, ''); + + return path.posix.join(normalizedDir, dateFolder, filename); + } + + async generateAndUpload({ + filename = 'export.xlsx', + dir = 'exports/excel', + key, + category = 'document', + saveRecord = false, + businessType, + businessId, + uploaderDept, + expireTime, + expireDays, + onProgress, + ...options + } = {}) { + const uploadService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.upload; + + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用,无法上传 Excel 文件'); + } + + const bookType = String(options.bookType || path.extname(filename).replace('.', '') || 'xlsx').toLowerCase(); + const safeFilename = this.sanitizeFilename(filename, `.${bookType}`); + const contentType = this.getContentType(bookType); + const buffer = await this.generateBuffer({ + ...options, + bookType, + }); + const md5Hash = crypto.createHash('md5').update(buffer).digest('hex'); + const sha1Hash = crypto.createHash('sha1').update(buffer).digest('hex'); + const uploadKey = this.buildUploadKey(safeFilename, { dir, key }); + const uploadStream = Readable.from(buffer); + + uploadStream.filename = safeFilename; + uploadStream.mimeType = contentType; + uploadStream.fileSize = buffer.length; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category, + mimetype: 'xls,xlsx,csv', + onProgress, + }); + + let fileRecord = null; + if ((saveRecord || businessType || businessId) && typeof uploadService.uploadSuccessNotify === 'function') { + const recordResult = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: safeFilename, + name: safeFilename, + fileSize: buffer.length, + size: buffer.length, + fileType: category, + mimeType: contentType, + type: category, + category, + businessType, + businessId, + uploaderDept, + expireTime, + expireDays, + md5Hash, + sha1Hash, + }); + + fileRecord = recordResult && (recordResult.data || recordResult); + } + + return { + filename: safeFilename, + fileKey: uploadResult.fileName, + size: buffer.length, + contentType, + ...uploadResult, + fileRecord, + }; + } + + /** + * 上传已经生成到本地临时目录的 Excel 文件(供流式生成场景复用上传链路)。 + * 与 generateAndUpload 的区别:文件由调用方(如 ExcelJS.stream.WorkbookWriter)落盘, + * 这里只负责归一化文件名、构建上传 key、流式上传与可选的落库记录。 + * @param {Object} options 参数 + * @param {string} options.filePath 本地文件绝对路径 + * @param {string} [options.filename] 原始文件名 + * @param {string} [options.dir='exports/excel'] 上传目录 + * @param {string} [options.key] 自定义上传 key(优先于 dir) + * @param {string} [options.category='document'] 文件分类 + * @param {boolean} [options.saveRecord=false] 是否落库记录 + * @param {string} [options.businessType] 业务类型(落库记录用) + * @param {string} [options.businessId] 业务ID(落库记录用) + * @param {string} [options.uploaderDept] 上传部门(落库记录用) + * @param {string|number} [options.expireTime] 过期时间(落库记录用) + * @param {number} [options.expireDays] 过期天数(落库记录用) + * @param {Function} [options.onProgress] 上传进度回调 + * @return {Promise} 上传结果(含 filename/fileKey/size/contentType 与 uploadFile 返回值) + */ + async uploadExistingFile({ + filePath, + filename = 'export.xlsx', + dir = 'exports/excel', + key, + category = 'document', + saveRecord = false, + businessType, + businessId, + uploaderDept, + expireTime, + expireDays, + onProgress, + ...options + } = {}) { + const uploadService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.upload; + + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用,无法上传 Excel 文件'); + } + + if (typeof filePath !== 'string' || !filePath) { + throw new Error('filePath 不能为空'); + } + + const bookType = String(options.bookType || path.extname(filename).replace('.', '') || 'xlsx').toLowerCase(); + const safeFilename = this.sanitizeFilename(filename, `.${bookType}`); + const contentType = this.getContentType(bookType); + const stat = await fs.promises.stat(filePath); + const uploadKey = this.buildUploadKey(safeFilename, { dir, key }); + const uploadStream = fs.createReadStream(filePath); + + uploadStream.filename = safeFilename; + uploadStream.mimeType = contentType; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category, + mimetype: 'xls,xlsx,csv', + onProgress, + }); + + let fileRecord = null; + if ((saveRecord || businessType || businessId) && typeof uploadService.uploadSuccessNotify === 'function') { + const recordResult = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: safeFilename, + name: safeFilename, + fileSize: stat.size, + size: stat.size, + fileType: category, + mimeType: contentType, + type: category, + category, + businessType, + businessId, + uploaderDept, + expireTime, + expireDays, + }); + + fileRecord = recordResult && (recordResult.data || recordResult); + } + + return { + filename: safeFilename, + fileKey: uploadResult.fileName, + size: stat.size, + contentType, + ...uploadResult, + fileRecord, + }; + } + + async sendFile({ ctx = this.ctx, filename = 'export.xlsx', ...options } = {}) { + if (!ctx) { + throw new Error('ctx 不存在,无法输出下载响应'); + } + + const ext = path.extname(filename).replace('.', '').toLowerCase() || options.bookType || 'xlsx'; + const buffer = await this.generateBuffer({ + ...options, + bookType: ext, + }); + + ctx.set('Content-Type', this.getContentType(ext)); + ctx.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`); + ctx.body = buffer; + + return { + filename, + size: buffer.length, + contentType: this.getContentType(ext), + }; + } + + async parseBuffer(buffer, options = {}) { + if (!buffer) { + throw new Error('buffer 不能为空'); + } + + const workbook = XLSX.read(buffer, { + type: 'buffer', + raw: false, + cellDates: true, + ...options.readOptions, + }); + + return this.workbookToJSON(workbook, options); + } + + async parseFile(filePath, options = {}) { + if (!filePath) { + throw new Error('filePath 不能为空'); + } + + const resolvedFilePath = path.resolve(filePath); + const buffer = await fs.promises.readFile(resolvedFilePath); + const result = await this.parseBuffer(buffer, options); + + return { + filePath: resolvedFilePath, + ...result, + }; + } + + workbookToJSON(workbook, options = {}) { + const { + headerRow = 1, + defval = '', + blankrows = false, + includeRawRows = false, + sheetNames, + } = options; + + const startIndex = Math.max(Number(headerRow) || 1, 1) - 1; + const selectedSheetNames = Array.isArray(sheetNames) && sheetNames.length > 0 + ? workbook.SheetNames.filter(name => sheetNames.includes(name)) + : workbook.SheetNames; + + const sheets = selectedSheetNames.map(name => { + const sheet = workbook.Sheets[name]; + const rawRows = XLSX.utils.sheet_to_json(sheet, { + header: 1, + raw: false, + defval, + blankrows, + }); + const headerValues = Array.isArray(rawRows[startIndex]) ? rawRows[startIndex] : []; + const headers = this.normalizeHeaders(headerValues); + const dataRows = rawRows.slice(startIndex + 1) + .filter(row => blankrows || row.some(cell => String(cell == null ? '' : cell).trim() !== '')); + const rows = dataRows.map(row => { + return headers.reduce((result, headerName, columnIndex) => { + result[headerName] = row[columnIndex] == null ? defval : row[columnIndex]; + return result; + }, {}); + }); + + const sheetResult = { + name, + headers, + rows, + rowCount: rows.length, + }; + + if (includeRawRows) { + sheetResult.rawRows = rawRows; + } + + return sheetResult; + }); + + return { + sheetNames: selectedSheetNames, + sheets, + }; + } +} + +module.exports = ExcelService; diff --git a/app/service/systems/express.js b/app/service/systems/express.js new file mode 100644 index 0000000..61ad564 --- /dev/null +++ b/app/service/systems/express.js @@ -0,0 +1,3618 @@ +'use strict'; + +const { Service } = require('egg'); + +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); +const { isLockedOrderStatus } = require('../../lib/lock_guard'); + +const DEFAULT_CACHE_TTL_SECONDS = 600; +const DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS = 60 * 60; +const DEFAULT_WAYBILL_BATCH_SIZE = 10; +const WAYBILL_EXCEPTION_STEP = 3; +const WAYBILL_ASYNC_SINGLE_ORDER_PLATFORM_CODES = new Set([ 'cainiao', 'pdd' ]); +const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([ + 'id', + 'store_id', + 'warehouse_id', + 'delivery_order_code', + 'source_platform_code', + 'source_platform_name', + 'oaid_order_source_code', + 'sys_platform_code', + 'sys_platform_name', + 'order_type', + 'status', + 'post_status', + 'step', + 'order_flag', + 'from_key', + 'create_at', + 'place_order_time', + 'pay_time', + 'operate_time', + 'delivery_time', + 'name', + 'tel', + 'mobile', + 'email', + 'country_code', + 'province', + 'city', + 'area', + 'town', + 'detail_address', + 'zip_code', + 'total_amount', + 'item_amount', + 'discount_amount', + 'freight', + 'ar_amount', + 'got_amount', + 'items', + 'items_count', + 'items_total', + 'items_weight', + 'logistics_name', + 'sys_logistics_code', + 'sys_logistics_name', + 'express_code', + 'logistics_area_code', + 'oaid', + 'source_order_codes', + 'logistics_code', + 'extend_props', + 'buyer_nick', + 'pay_no', + 'from_key', +]); + +class ExpressService extends Service { + /** + * 生成快递列表缓存键。 + * + * @param {number|string} warehouseId 仓库ID + * @param {boolean} [systemOnly=false] 是否仅返回系统基础快递列表 + * @param {string} [systemExpressCode=''] 系统快递编码 + * @return {string} 缓存键 + */ + getExpressListCacheKey(warehouseId = 0, systemOnly = false, systemExpressCode = '') { + const normalizedExpressCode = String(systemExpressCode || '').trim().toUpperCase(); + + if (systemOnly) { + if (normalizedExpressCode) { + return `express:list:system:${normalizedExpressCode}`; + } + return 'express:list:system'; + } + + const normalizedWarehouseId = Number(warehouseId || 0); + + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + if (normalizedExpressCode) { + return `express:list:${normalizedWarehouseId}:express:${normalizedExpressCode}`; + } + return `express:list:${normalizedWarehouseId}`; + } + + if (normalizedExpressCode) { + return `express:list:express:${normalizedExpressCode}`; + } + + return 'express:list'; + } + /** + * 获取当前上下文中的仓库ID。 + * + * @return {number} 仓库ID,未获取到时返回 0 + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); + + if (Number.isFinite(warehouseId) && warehouseId > 0) { + return warehouseId; + } + + return 0; + } + + /** + * 构建快递号分配链路追踪ID。 + * + * 优先使用入参中的 trace_id/traceId,其次读取上下文 trace 信息,最后兜底生成。 + * + * @param {Object} [data={}] 入参。 + * @param {string} [fallback=''] 兜底标识。 + * @return {string} 追踪ID。 + */ + buildWaybillTraceId(data = {}, fallback = '') { + const normalizedData = data && typeof data === 'object' ? data : {}; + const ctxTraceId = this.ctx && this.ctx.traceId !== undefined + ? this.ctx.traceId + : this.ctx && this.ctx.requestId !== undefined + ? this.ctx.requestId + : this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined + ? this.ctx.state.traceId + : ''; + const normalizedTraceId = String( + normalizedData.trace_id + || normalizedData.traceId + || ctxTraceId + || fallback + || '' + ).trim(); + + if (normalizedTraceId) { + return normalizedTraceId; + } + + return `waybill_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + } + + /** + * 获取订单日志使用的操作人信息。 + * + * 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。 + * + * @return {{ id: string|null, name: string }} 操作人信息。 + */ + getOrderLogOperator() { + const stateUser = this.ctx && this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' + ? this.ctx.state.user + : null; + const ctxUser = this.ctx && this.ctx.user && typeof this.ctx.user === 'object' + ? this.ctx.user + : null; + const operatorSource = stateUser || ctxUser || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 获取订单日志使用的仓库ID。 + * + * @param {number|string|null} [preferredWarehouseId=null] 优先仓库ID。 + * @return {number|string|null} 仓库ID。 + */ + getOrderLogWarehouseId(preferredWarehouseId = null) { + const candidates = [ + preferredWarehouseId, + this.getCurrentWarehouseId(), + this.ctx && this.ctx.user ? this.ctx.user.warehouse_id : null, + this.ctx && this.ctx.user ? this.ctx.user.store_id : null, + ]; + + for (const candidate of candidates) { + if (candidate === undefined || candidate === null || candidate === '') { + continue; + } + return candidate; + } + + return null; + } + + /** + * 为分配快递失败订单写入订单操作日志。 + * + * @param {Array} orderIds 订单ID数组。 + * @param {string} errorMessage 失败原因。 + * @param {number|string|null} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async createAllocateExpressFailureLogs(orderIds = [], errorMessage = '', warehouseId = null) { + const operationLogService = this.service + && this.service.systems + && this.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + return; + } + + const operator = this.getOrderLogOperator(); + const normalizedWarehouseId = this.getOrderLogWarehouseId(warehouseId); + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(orderId => Number(orderId)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + const normalizedErrorMessage = String(errorMessage || '').trim() || '未知异常'; + + const payloads = normalizedOrderIds.map(orderId => ({ + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_EXPRESS_ALLOCATE_FAILED', + operator, + extras: { + message: `分配快递失败:${normalizedErrorMessage}`, + warehouseId: normalizedWarehouseId, + externalLogType: 'API', + }, + })); + + await operationLogService.createOperationLogs(payloads); + } + + /** + * 将 business_key 规范化为内部可处理的正整数列表。 + *【已使用】 + * @param {*} businessKey 原始 business_key 值。 + * @return {Array} 正整数业务键列表。 + */ + normalizeWaybillBusinessKeys(businessKey = null) { + const rawBusinessKeys = Array.isArray(businessKey) + ? businessKey.flat(Infinity) + : [ businessKey ]; + const normalizedBusinessKeys = []; + const seenBusinessKeys = new Set(); + + for (const rawBusinessKey of rawBusinessKeys) { + const normalizedBusinessKey = Number(rawBusinessKey); + + if (!Number.isInteger(normalizedBusinessKey) || normalizedBusinessKey <= 0 || seenBusinessKeys.has(normalizedBusinessKey)) { + continue; + } + + seenBusinessKeys.add(normalizedBusinessKey); + normalizedBusinessKeys.push(normalizedBusinessKey); + } + + return normalizedBusinessKeys; + } + + /** + * 规范化运单创建时携带的平台上下文编码。 + * + * 该值仅作为异步后处理的辅助上下文,不参与主流程分组与去重。 + *【已使用】 + * @param {Object} order 原始订单。 + * @return {string} 平台编码,小写。 + */ + normalizeWaybillCreatePlatformCode(order = {}) { + if (!order || typeof order !== 'object') { + return ''; + } + + const expressPlatform = order.wms_express_platform && typeof order.wms_express_platform === 'object' + ? order.wms_express_platform + : (order.wmsExpressPlatform && typeof order.wmsExpressPlatform === 'object' ? order.wmsExpressPlatform : null); + + const rawPlatformCode = (expressPlatform && (expressPlatform.platform_code || expressPlatform.platformCode)) + || (typeof order.wms_express_platform === 'string' ? order.wms_express_platform : '') + || (typeof order.wmsExpressPlatform === 'string' ? order.wmsExpressPlatform : '') + || order.platform_code + || order.platformCode + || order.express_platform_code + || order.expressPlatformCode + || ''; + + return String(rawPlatformCode).trim().toLowerCase(); + } + + /** + * 规范化运单余额相关策略配置。 + * + * @param {*} policyConfig 策略配置。 + * @return {Object} 规范化后的策略配置对象。 + */ + normalizeWaybillPolicyConfig(policyConfig) { + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + + if (storeWarehouseModel && typeof storeWarehouseModel.normalizePolicyConfig === 'function') { + try { + return storeWarehouseModel.normalizePolicyConfig(policyConfig, { + fieldName: 'policy_config', + allowEmpty: true, + sanitizeOnly: true, + }) || {}; + } catch (error) { + this.ctx.logger.warn('[ExpressService.normalizeWaybillPolicyConfig] policy_config 解析失败: %s', error.message); + return {}; + } + } + + if (policyConfig && typeof policyConfig === 'object' && !Array.isArray(policyConfig)) { + return policyConfig; + } + + if (typeof policyConfig !== 'string') { + return {}; + } + + try { + const parsedConfig = JSON.parse(policyConfig); + if (parsedConfig && typeof parsedConfig === 'object' && !Array.isArray(parsedConfig)) { + return parsedConfig; + } + } catch (error) { + this.ctx.logger.warn('[ExpressService.normalizeWaybillPolicyConfig] policy_config 解析失败: %s', error.message); + } + + return {}; + } + + /** + * 生成运单余额不足的异常文案。 + * + * @param {Object} options 文案参数。 + * @param {number} options.availableQuantity 当前可用余额。 + * @param {number} options.requestedQuantity 本次请求数量。 + * @param {number} options.shortageQuantity 不足数量。 + * @param {number} options.expressQuota 快递额度。 + * @param {number} options.usedQuantity 已用额度。 + * @return {string} 异常文案。 + */ + buildWaybillBalanceExceptionText({ + availableQuantity = 0, + requestedQuantity = 0, + shortageQuantity = 0, + expressQuota = 0, + usedQuantity = 0, + } = {}) { + return `货主快递余额不足:余额 ${Math.max(0, Number(usedQuantity) || 0) + Math.max(0, Number(availableQuantity) || 0)},已用 ${Math.max(0, Number(usedQuantity) || 0)},可用 ${Math.max(0, Number(availableQuantity) || 0)},额度 ${Math.max(0, Number(expressQuota) || 0)},需要 ${Math.max(0, Number(requestedQuantity) || 0)},不足 ${Math.max(0, Number(shortageQuantity) || 0)}`; + } + + /** + * 规范化运单创建入参并按订单与业务键去重。 + * + * 仅当输入已经完成基础规整时,直接做最小必要校验与去重; + * 如果还保留数组业务键或缺失主字段,则回退到完整规整流程。 + *【已使用】 + * @param {Array} orders 原始运单创建入参,business_key 可为单值或数组。 + * @return {Array} 规范化后的订单列表。 + */ + async normalizeWaybillCreateOrders(orders = []) { + const normalizedOrders = Array.isArray(orders) ? orders : []; + const normalizedOrderMap = new Map(); + + await this.loadExpressList(); + for (const order of normalizedOrders) { + if (!order || typeof order !== 'object') { + continue; + } + + const orderId = Number(order.id || order.order_id); + const businessKeys = this.normalizeWaybillBusinessKeys(order.business_key); + if (!Number.isInteger(orderId) || orderId <= 0 || businessKeys.length === 0) { + continue; + } + + const sysPlatformCode = String(order.sys_platform_code || order.sysPlatformCode || '').trim(); + const logisticsCode = String(order.logistics_code || order.logisticsCode || '').trim(); + const platformCode = this.normalizeWaybillCreatePlatformCode(order); + + for (const businessKey of businessKeys) { + const orderKey = `${orderId}:${businessKey}`; + + if (normalizedOrderMap.has(orderKey)) { + continue; + } + + normalizedOrderMap.set(orderKey, { + order_id: orderId, + business_key: businessKey, + ...(sysPlatformCode ? { sys_platform_code: sysPlatformCode } : {}), + ...(logisticsCode ? { logistics_code: logisticsCode } : {}), + ...(platformCode ? { platform_code: platformCode } : {}), + }); + } + } + + return Array.from(normalizedOrderMap.values()); + } + + /** + * 根据订单主表记录构建签约关系分组,并标记缺失订单。 + *【已使用】 + * @param {Array} normalizedOrders 规范化后的订单列表。 + * @param {Array} orderDeliveryRows 订单主表查询结果。 + * @param {number} currentWarehouseId 当前仓库 ID。 + * @return {Object} 分组结果,包含 relationGroupMap 和 missingOrderIds。 + */ + buildWaybillCreateRelationGroups(normalizedOrders = [], orderDeliveryRows = [], currentWarehouseId = 0) { + const orderDeliveryMap = new Map(); + + for (const row of Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []) { + const orderId = Number(row && row.id); + if (Number.isFinite(orderId) && orderId > 0) { + orderDeliveryMap.set(orderId, row); + } + } + + const relationGroupMap = new Map(); + const missingOrderIds = []; + + for (const order of Array.isArray(normalizedOrders) ? normalizedOrders : []) { + const orderRow = orderDeliveryMap.get(order.order_id); + if (!orderRow) { + missingOrderIds.push(order.order_id); + continue; + } + + const storeId = Number(orderRow.store_id || 0); + const warehouseId = Number(orderRow.warehouse_id || currentWarehouseId); + if (!Number.isFinite(storeId) || storeId <= 0 || !Number.isFinite(warehouseId) || warehouseId <= 0) { + missingOrderIds.push(order.order_id); + continue; + } + + const relationKey = `${storeId}:${warehouseId}`; + let relationGroup = relationGroupMap.get(relationKey); + if (!relationGroup) { + relationGroup = { + store_id: storeId, + warehouse_id: warehouseId, + orders: [], + }; + relationGroupMap.set(relationKey, relationGroup); + } + + relationGroup.orders.push({ + ...order, + store_id: storeId, + warehouse_id: warehouseId, + }); + } + + return { + relationGroupMap, + missingOrderIds, + }; + } + + /** + * 处理签约关系分组中的可创建与失败订单。 + *【已使用】 + * @param {Map} relationGroupMap 签约关系分组。 + * @param {Map} relationMap 签约关系记录映射。 + * @return {Promise} 处理结果,包含 successOrderKeySet、failedOrdersByReason 和 balanceWarnings。 + */ + async collectWaybillRelationProcessingState(relationGroupMap, relationMap) { + const successOrderKeySet = new Set(); + const failedOrdersByReason = new Map(); + const balanceWarnings = []; + + for (const relationGroup of relationGroupMap.values()) { + const relationKey = `${relationGroup.store_id}:${relationGroup.warehouse_id}`; + const relation = relationMap.get(relationKey); + + if (!relation) { + const exceptionText = '签约关系不存在,无法创建运单'; + const failedOrderIds = relationGroup.orders.map(order => order.order_id); + failedOrdersByReason.set(exceptionText, (failedOrdersByReason.get(exceptionText) || []).concat(failedOrderIds)); + continue; + } + + const policyConfig = this.normalizeWaybillPolicyConfig(relation.policy_config); + const expressQuota = Math.max(0, Number(policyConfig.express_quota || 0) || 0); + const requestCount = relationGroup.orders.length; + const currentPrintQuantity = Number(relation.print_quantity || 0); + const currentLockedQuantity = Number(relation.print_quantity_locked || 0); + const availableQuantity = currentPrintQuantity - currentLockedQuantity; + const allowedQuantity = Math.max(0, availableQuantity + expressQuota); + const successCount = Math.min(requestCount, allowedQuantity); + const failedCount = requestCount - successCount; + const successOrders = relationGroup.orders.slice(0, successCount); + const failedOrders = relationGroup.orders.slice(successCount); + this.ctx.logger.info(`[waybill-balance] store_id=${relation.store_id} warehouse_id=${relation.warehouse_id} print_quantity=${currentPrintQuantity} print_quantity_locked=${currentLockedQuantity} availableQuantity=${availableQuantity} expressQuota=${expressQuota} allowedQuantity=${allowedQuantity} requestCount=${requestCount} successCount=${successCount} failedCount=${failedCount}`); + + for (const order of successOrders) { + successOrderKeySet.add(`${order.order_id}:${order.business_key}`); + } + + if (failedCount > 0) { + const exceptionText = this.buildWaybillBalanceExceptionText({ + availableQuantity, + requestedQuantity: requestCount, + shortageQuantity: failedCount, + expressQuota, + usedQuantity: Math.max(0, currentLockedQuantity), + }); + + const failedOrderIds = failedOrders.map(order => order.order_id); + failedOrdersByReason.set(exceptionText, (failedOrdersByReason.get(exceptionText) || []).concat(failedOrderIds)); + } + } + + return { + successOrderKeySet, + failedOrdersByReason, + balanceWarnings, + }; + } + + /** + * 根据成功订单、订单主表快照和已存在快递记录,统计需要新增锁定的余额数量。 + * + * 只统计真正会进入 `rowsToCreate` 的记录,避免把已存在且状态不同的记录重复计入。 + * + * @param {Array} successOrders 成功订单列表。 + * @param {Map} orderDeliveryMap 订单主表快照映射。 + * @param {Map} existingMap 已存在快递记录映射。 + * @return {Map} 关系分组锁定统计。 + */ + buildWaybillRelationLockMap(successOrders = [], orderDeliveryMap = new Map(), existingMap = new Map()) { + const relationLockMap = new Map(); + + for (const order of Array.isArray(successOrders) ? successOrders : []) { + const orderKey = `${order.order_id}:${order.business_key}`; + if (existingMap.has(orderKey)) { + continue; + } + + const orderDelivery = orderDeliveryMap.get(Number(order.order_id)); + const storeId = Number(orderDelivery && orderDelivery.store_id) || 0; + const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0; + if (!Number.isFinite(storeId) || storeId <= 0 || !Number.isFinite(warehouseId) || warehouseId <= 0) { + continue; + } + + const relationKey = `${storeId}:${warehouseId}`; + const currentRelationLock = relationLockMap.get(relationKey) || { + store_id: storeId, + warehouse_id: warehouseId, + locked_quantity: 0, + }; + currentRelationLock.locked_quantity += 1; + relationLockMap.set(relationKey, currentRelationLock); + } + + return relationLockMap; + } + + /** + * 按店铺和仓库分组锁定新增的运单余额。 + * + * @param {Map} relationLockMap 关系分组锁定统计。 + * @param {Map} relationMap 签约关系记录映射。 + * @param {Object} storeWarehouseModel 签约关系模型。 + * @param {Object} transaction 数据库事务。 + * @return {Promise} 无返回值。 + */ + async lockWaybillRelationBalance(relationLockMap, relationMap, storeWarehouseModel, transaction) { + if (!relationLockMap || relationLockMap.size === 0) { + return; + } + + for (const relationLock of relationLockMap.values()) { + const relationKey = `${relationLock.store_id}:${relationLock.warehouse_id}`; + const relation = relationMap.get(relationKey); + if (!relation) { + continue; + } + + const currentLockedQuantity = Number(relation.print_quantity_locked || 0); + const incrementQuantity = Number(relationLock.locked_quantity || 0); + if (incrementQuantity <= 0) { + continue; + } + + await storeWarehouseModel.update({ + print_quantity_locked: currentLockedQuantity + incrementQuantity, + }, { + where: { + id: relation.id, + }, + transaction, + }); + } + } + + /** + * 将运单失败订单批量回写为异常状态。 + * + * @param {Object} orderDeliveryModel 订单主表模型。 + * @param {Array} orderIds 订单ID 列表。 + * @param {string} exceptionText 异常信息。 + * @param {Object} transaction 数据库事务。 + * @return {Promise} 无返回值。 + */ + async markWaybillOrdersAsException(orderDeliveryModel, orderIds = [], exceptionText = '', transaction) { + const { Op } = this.app.Sequelize; + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(orderId => Number(orderId)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + + if (normalizedOrderIds.length === 0 || !exceptionText) { + return; + } + + await orderDeliveryModel.update({ + inspection_status: 'error', + step: WAYBILL_EXCEPTION_STEP, + order_flag: exceptionText, + updated_at: new Date(), + }, { + where: { + id: { + [Op.in]: normalizedOrderIds, + }, + status: { + [Op.ne]: 'cancel', + }, + // 保护配送中(step=4)订单不被回退为异常状态 + step: { + [Op.ne]: 4, + }, + }, + transaction, + }); + } + + /** + * 批量回写运单创建失败订单的异常状态。 + *【已使用】 + * @param {Object} orderDeliveryModel 订单主表模型。 + * @param {Map>} failedOrdersByReason 失败原因与订单 ID 映射。 + * @param {Object} transaction 数据库事务。 + * @return {Promise} 无返回值。 + */ + async writeWaybillOrderExceptions(orderDeliveryModel, failedOrdersByReason = new Map(), transaction) { + if (!failedOrdersByReason || typeof failedOrdersByReason.forEach !== 'function') { + return; + } + + for (const [ exceptionText, orderIds ] of failedOrdersByReason.entries()) { + await this.markWaybillOrdersAsException(orderDeliveryModel, orderIds, exceptionText, transaction); + } + } + + /** + * 补写 dispatch 表订单的 order_flag 异常信息。 + * dispatch 表中的配送中订单(step=4)不应回退 step,仅记录异常标记。 + * + * @param {Array} dispatchOrderDeliveryRows dispatch 表中的订单行。 + * @param {Map>} failedOrdersByReason 失败原因与订单 ID 映射。 + * @param {Object} transaction 数据库事务。 + * @return {Promise} 无返回值。 + */ + async writeDispatchOrderFlags(dispatchOrderDeliveryRows = [], failedOrdersByReason = new Map(), transaction) { + if (!failedOrdersByReason || typeof failedOrdersByReason.forEach !== 'function') { + return; + } + + const { Op } = this.app.Sequelize; + const dispatchOrderIdSet = new Set( + (Array.isArray(dispatchOrderDeliveryRows) ? dispatchOrderDeliveryRows : []) + .map(row => Number(row && row.id)) + .filter(id => Number.isFinite(id) && id > 0) + ); + + if (dispatchOrderIdSet.size === 0) { + return; + } + + this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 入口 dispatchOrderIds=%s failedReasons=%d', + Array.from(dispatchOrderIdSet).join(','), failedOrdersByReason.size); + + // 找到同时属于 dispatch 表且失败的订单 + const dispatchFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!dispatchFactory || typeof dispatchFactory.getDispatchModel !== 'function') { + this.ctx.logger.warn('[ExpressService.writeDispatchOrderFlags] dispatchFactory 不可用'); + return; + } + + const currentWarehouseId = this.getCurrentWarehouseId(); + if (!currentWarehouseId) return; + + for (const [ exceptionText, orderIds ] of failedOrdersByReason.entries()) { + const failedDispatchIds = (Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id)) + .filter(id => dispatchOrderIdSet.has(id)); + + if (failedDispatchIds.length === 0) continue; + + this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 准备写入 order_flag: ids=%s reason=%s', + failedDispatchIds.join(','), exceptionText); + + try { + const dispatchModel = await dispatchFactory.getDispatchModel(currentWarehouseId); + if (dispatchModel && typeof dispatchModel.update === 'function') { + await dispatchModel.update({ + order_flag: exceptionText, + updated_at: new Date(), + }, { + where: { + id: { [Op.in]: failedDispatchIds }, + status: { [Op.ne]: 'cancel' }, + }, + transaction, + }); + this.ctx.logger.info('[ExpressService.writeDispatchOrderFlags] 写入成功 ids=%s', failedDispatchIds.join(',')); + } + } catch (err) { + this.ctx.logger.warn('[ExpressService.writeDispatchOrderFlags] 写入 dispatch order_flag 失败: %s', + err && err.message ? err.message : err); + } + } + } + + /** + * 将运单异步后处理失败订单批量回写为错误状态。 + * + * @param {Object} orderDeliveryModel 订单主表模型。 + * @param {Array} orderIds 订单ID 列表。 + * @param {string} errorMessage 错误信息。 + * @param {Object} [extraWhere={}] 追加 where 约束,用于限制更新边界。 + * @return {Promise} 无返回值。 + */ + async markWaybillAsyncOrdersAsError(orderDeliveryModel, orderIds = [], errorMessage = '', extraWhere = {}) { + if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { + return; + } + + const { Op } = this.app.Sequelize; + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(orderId => Number(orderId)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + const normalizedErrorMessage = String(errorMessage || '').trim() || '接口调用失败'; + + if (normalizedOrderIds.length === 0) { + return; + } + + const normalizedExtraWhere = extraWhere && typeof extraWhere === 'object' && !Array.isArray(extraWhere) + ? { ...extraWhere } + : {}; + const where = { + ...normalizedExtraWhere, + id: { + [Op.in]: normalizedOrderIds, + }, + }; + + await orderDeliveryModel.update({ + post_status: 'error', + step: 3, + order_flag: normalizedErrorMessage, + updated_at: new Date(), + }, { + where: { + ...where, + status: { + [Op.ne]: 'cancel', + }, + // 保护配送中(step=4)订单不被回退为异常状态 + step: { + [Op.ne]: 4, + }, + }, + }); + } + + /** + * 生成合并后的快递项展示名称。 + * + * @param {string} settingCode 快递设置编码 + * @param {Object} expressItem 系统快递项 + * @return {string} 展示名称 + */ + buildMergedExpressLabel(settingCode, expressItem) { + const normalizedSettingCode = String(settingCode || '').trim(); + const expressName = String(expressItem && (expressItem.name || expressItem.label || expressItem.code || expressItem.value) || '').trim(); + + if (!normalizedSettingCode) { + return expressName; + } + + if (!expressName) { + return normalizedSettingCode; + } + + return `${normalizedSettingCode} (${expressName})`; + } + + /** + * 规范化快递设置记录。 + * + * @param {Object} row 数据库记录 + * @param {Map} expressMap 系统快递映射 + * @return {Object|null} 规范化后的记录 + */ + normalizeExpressSettingRow(row, expressMap) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + const expressCode = String(row.express_code || '').trim(); + const expressItem = expressMap instanceof Map ? expressMap.get(expressCode) : null; + const settingName = String(row.name || '').trim(); + const label = settingName + ? `${code} (${settingName})` + : this.buildMergedExpressLabel(code, expressItem); + + return { + code, + name: settingName || code, + value: code, + label, + is_system_setting: true, + id: row.id === undefined || row.id === null ? null : row.id, + alias: String(row.name || '').trim(), + express_code: String((expressItem && (expressItem.code || expressItem.value)) || expressCode || '').trim(), + }; + } + + /** + * 从数据库加载快递设置列表。 + * + * @param {number|string} warehouseId 仓库ID + * @param {string} [systemExpressCode=''] 系统快递编码 + * @return {Promise} 快递设置列表 + */ + async loadExpressSettingListFromDatabase(warehouseId = 0, systemExpressCode = '') { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return []; + } + const normalizedExpressCode = String(systemExpressCode || '').trim().toUpperCase(); + + const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting; + if (!expressSettingModel || typeof expressSettingModel.findAll !== 'function') { + return []; + } + + const where = { + warehouse_id: normalizedWarehouseId, + deleted_at: null, + }; + + if (normalizedExpressCode) { + where.express_code = normalizedExpressCode; + } + + const rows = await expressSettingModel.findAll({ + attributes: [ 'id', 'code', 'name', 'express_code' ], + where, + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows; + } + + /** + * 构建仓库快递自定义编码列表。 + * + * 仅返回快递设置记录,不合并系统快递记录;用于按快递公司编码筛选场景。 + * + * @param {Array} expressList 系统快递列表 + * @param {Array} expressSettingList 快递设置列表 + * @return {Array} 自定义编码列表 + */ + buildExpressSettingCustomCodeList(expressList, expressSettingList) { + const normalizedExpressList = Array.isArray(expressList) ? expressList : []; + const expressMap = new Map(); + + for (const expressItem of normalizedExpressList) { + if (!expressItem || typeof expressItem !== 'object') { + continue; + } + + const code = String(expressItem.code || expressItem.value || '').trim(); + if (!code || expressMap.has(code)) { + continue; + } + + expressMap.set(code, expressItem); + } + + const result = []; + + for (const row of Array.isArray(expressSettingList) ? expressSettingList : []) { + const mergedItem = this.normalizeExpressSettingRow(row, expressMap); + if (!mergedItem) { + continue; + } + + result.push(mergedItem); + } + + return result; + } + + /** + * 合并系统快递和快递设置列表。 + * + * @param {Array} expressList 系统快递列表 + * @param {Array} expressSettingList 快递设置列表 + * @return {Array} 合并后的快递列表 + */ + buildMergedExpressList(expressList, expressSettingList) { + const mergedList = []; + const seenCodeMap = new Set(); + const normalizedExpressList = Array.isArray(expressList) ? expressList : []; + const expressMap = new Map(); + + for (const expressItem of normalizedExpressList) { + if (!expressItem || typeof expressItem !== 'object') { + continue; + } + + const code = String(expressItem.code || expressItem.value || '').trim(); + if (!code) { + continue; + } + + if (!expressMap.has(code)) { + expressMap.set(code, expressItem); + } + } + + for (const expressItem of normalizedExpressList) { + if (!expressItem || typeof expressItem !== 'object') { + continue; + } + + const code = String(expressItem.code || expressItem.value || '').trim(); + if (!code || seenCodeMap.has(code)) { + continue; + } + + mergedList.push(expressItem); + seenCodeMap.add(code); + } + + for (const row of Array.isArray(expressSettingList) ? expressSettingList : []) { + const mergedItem = this.normalizeExpressSettingRow(row, expressMap); + if (!mergedItem || seenCodeMap.has(mergedItem.code)) { + continue; + } + + mergedList.push(mergedItem); + seenCodeMap.add(mergedItem.code); + } + + return mergedList; + } + + /** + * 生成快递产品类型列表缓存键。 + * + * @param {string} expressCode 快递公司编码 + * @return {string} 缓存键 + */ + getExpressProductTypeListCacheKey(expressCode = '') { + const normalizedExpressCode = String(expressCode || '').trim(); + + if (!normalizedExpressCode) { + return 'express:product-type:list'; + } + + return `express:product-type:list:${normalizedExpressCode}`; + } + + /** + * 规范化快递产品类型记录。 + * + * @param {Object} row 数据库记录 + * @return {Object|null} 规范化后的记录 + */ + normalizeExpressProductTypeRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + const name = String(row.name || '').trim(); + + return { + code, + express_code: String(row.express_code || '').trim(), + name, + value: code, + label: name || code, + }; + } + + /** + * 规范化快递编码为大写键值。 + * + * @param {*} expressCode 原始快递编码 + * @return {string} 规范化后的快递编码 + */ + normalizeExpressCodeKey(expressCode) { + return String(expressCode || '').trim().toUpperCase(); + } + + /** + * 判断是否为顺丰快递编码。 + * + * @param {*} expressCode 原始快递编码 + * @return {boolean} 是否顺丰 + */ + isSfExpressCode(expressCode) { + const normalizedExpressCode = this.normalizeExpressCodeKey(expressCode); + return normalizedExpressCode === 'SF' || normalizedExpressCode === 'SHUNFENG'; + } + + /** + * 从 type_desc 中提取快递产品类型映射。 + * + * @param {*} typeDesc 原始 type_desc + * @return {Array<{ code: string, name: string }>} 提取后的产品类型列表 + */ + extractExpressProductTypesFromTypeDesc(typeDesc) { + const rawTypeDesc = String(typeDesc || '').trim(); + if (!rawTypeDesc) { + return []; + } + + const normalizeCode = value => String(value || '').trim(); + const normalizeName = value => String(value || '').trim(); + const toPair = (codeValue, nameValue) => { + const code = normalizeCode(codeValue); + if (!code) { + return null; + } + + return { + code, + name: normalizeName(nameValue) || code, + }; + }; + + const pairs = []; + + const appendMapObject = source => { + if (!source || typeof source !== 'object' || Array.isArray(source)) { + return; + } + + const preferredSource = source.desc && typeof source.desc === 'object' && !Array.isArray(source.desc) + ? source.desc + : source; + + for (const [ key, value ] of Object.entries(preferredSource)) { + if (value && typeof value === 'object' && !Array.isArray(value)) { + const nestedCode = String(value.code || value.value || key || '').trim(); + const nestedName = String(value.name || value.label || value.desc || value.text || nestedCode || '').trim(); + const pair = toPair(nestedCode, nestedName); + if (pair) { + pairs.push(pair); + } + continue; + } + + const pair = toPair(key, value); + if (pair) { + pairs.push(pair); + } + } + }; + + const appendArray = source => { + if (!Array.isArray(source)) { + return; + } + + for (const item of source) { + if (item && typeof item === 'object') { + const code = item.code || item.value || item.key || item.id || ''; + const name = item.name || item.label || item.desc || item.text || item.title || code; + const pair = toPair(code, name); + if (pair) { + pairs.push(pair); + } + continue; + } + + const text = String(item || '').trim(); + if (!text) { + continue; + } + + const splitIndex = text.indexOf(':') >= 0 ? text.indexOf(':') : text.indexOf('='); + if (splitIndex > 0) { + const pair = toPair(text.slice(0, splitIndex), text.slice(splitIndex + 1)); + if (pair) { + pairs.push(pair); + } + continue; + } + + const pair = toPair(text, text); + if (pair) { + pairs.push(pair); + } + } + }; + + try { + const parsed = JSON.parse(rawTypeDesc); + if (Array.isArray(parsed)) { + appendArray(parsed); + } else if (parsed && typeof parsed === 'object') { + appendMapObject(parsed); + } + } catch (error) { + const segments = rawTypeDesc.split(/[,,;;]+/).map(item => item.trim()).filter(Boolean); + appendArray(segments); + } + + const dedupedMap = new Map(); + for (const item of pairs) { + if (!item || !item.code) { + continue; + } + + const existing = dedupedMap.get(item.code); + if (!existing || (!existing.name && item.name)) { + dedupedMap.set(item.code, item); + } + } + + return Array.from(dedupedMap.values()); + } + + /** + * 从拼多多网点服务列表中提取顺丰定时派送产品类型。 + * + * @param {Array} shopExpressList 店铺快递签约列表 + * @return {Array<{ express_code: string, code: string, name: string }>} 可写入的产品类型列表 + */ + collectPddSfTimedDeliveryProductTypes(shopExpressList = []) { + const result = []; + + for (const expressItem of Array.isArray(shopExpressList) ? shopExpressList : []) { + const expressCode = this.normalizeExpressCodeKey(expressItem && expressItem.sys_express_code); + if (!this.isSfExpressCode(expressCode)) { + continue; + } + + const accounts = Array.isArray(expressItem && expressItem.accounts) ? expressItem.accounts : []; + for (const account of accounts) { + const services = Array.isArray(account && account.services) ? account.services : []; + for (const serviceItem of services) { + const serviceCode = String(serviceItem && serviceItem.service_code || '').trim().toUpperCase(); + if (serviceCode !== 'TIMED-DELIVERY') { + continue; + } + + const attributes = Array.isArray(serviceItem && serviceItem.attributes) ? serviceItem.attributes : []; + for (const attribute of attributes) { + const typeDesc = attribute && attribute.type_desc; + const productTypeList = this.extractExpressProductTypesFromTypeDesc(typeDesc); + for (const productType of productTypeList) { + result.push({ + express_code: expressCode, + code: String(productType.code || '').trim(), + name: String(productType.name || '').trim() || String(productType.code || '').trim(), + }); + } + } + } + } + } + + const dedupedMap = new Map(); + for (const item of result) { + if (!item || !item.express_code || !item.code) { + continue; + } + + const key = `${item.express_code}:${item.code}`; + const existed = dedupedMap.get(key); + if (!existed || (!existed.name && item.name)) { + dedupedMap.set(key, item); + } + } + + return Array.from(dedupedMap.values()); + } + + /** + * 清理快递产品类型缓存。 + * + * @param {string} expressCode 快递公司编码 + * @return {Promise} 无返回值 + */ + async clearExpressProductTypeCache(expressCode = '') { + const cacheKeys = [ this.getExpressProductTypeListCacheKey() ]; + const normalizedExpressCode = this.normalizeExpressCodeKey(expressCode); + if (normalizedExpressCode) { + cacheKeys.push(this.getExpressProductTypeListCacheKey(normalizedExpressCode)); + } + + for (const cacheKey of cacheKeys) { + if (!cacheKey) { + continue; + } + + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(cacheKey); + } else if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, null, 0); + } + } + } + + /** + * 将快递产品类型列表幂等写入数据库。 + * + * @param {Array<{ express_code: string, code: string, name: string }>} items 快递产品类型列表 + * @return {Promise<{ createdCount: number, updatedCount: number }>} 写入结果 + */ + async upsertExpressProductTypeList(items = []) { + const expressProductTypeModel = this.ctx.model && this.ctx.model.ExpressProductType; + if (!expressProductTypeModel || typeof expressProductTypeModel.findAll !== 'function') { + return { createdCount: 0, updatedCount: 0 }; + } + + const validItems = Array.isArray(items) + ? items.filter(item => item && item.express_code && item.code) + : []; + if (validItems.length === 0) { + return { createdCount: 0, updatedCount: 0 }; + } + + const { Op } = this.app.Sequelize; + let createdCount = 0; + let updatedCount = 0; + const changedExpressCodeSet = new Set(); + + const groupedByExpressCode = validItems.reduce((result, item) => { + const expressCode = this.normalizeExpressCodeKey(item.express_code); + if (!expressCode) { + return result; + } + + if (!result[expressCode]) { + result[expressCode] = []; + } + + result[expressCode].push({ + express_code: expressCode, + code: String(item.code || '').trim(), + name: String(item.name || '').trim() || String(item.code || '').trim(), + }); + return result; + }, {}); + + for (const [ expressCode, groupItems ] of Object.entries(groupedByExpressCode)) { + const codeList = Array.from(new Set(groupItems.map(item => item.code).filter(Boolean))); + if (codeList.length === 0) { + continue; + } + + const existedRows = await expressProductTypeModel.findAll({ + attributes: [ 'id', 'express_code', 'code', 'name' ], + where: { + express_code: expressCode, + code: { + [Op.in]: codeList, + }, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const existedMap = new Map(); + for (const row of Array.isArray(existedRows) ? existedRows : []) { + const rowCode = String(row && row.code || '').trim(); + if (!rowCode || existedMap.has(rowCode)) { + continue; + } + existedMap.set(rowCode, row); + } + + for (const item of groupItems) { + const existed = existedMap.get(item.code); + if (!existed) { + if (typeof expressProductTypeModel.create === 'function') { + await expressProductTypeModel.create({ + express_code: expressCode, + code: item.code, + name: item.name, + }); + createdCount += 1; + changedExpressCodeSet.add(expressCode); + } + continue; + } + + const existedName = String(existed.name || '').trim(); + if (item.name && item.name !== existedName && typeof expressProductTypeModel.update === 'function') { + await expressProductTypeModel.update({ + name: item.name, + }, { + where: { + id: existed.id, + }, + }); + updatedCount += 1; + changedExpressCodeSet.add(expressCode); + } + } + } + + if (changedExpressCodeSet.size > 0) { + await this.clearExpressProductTypeCache(); + for (const expressCode of changedExpressCodeSet) { + await this.clearExpressProductTypeCache(expressCode); + } + } + + return { + createdCount, + updatedCount, + }; + } + + /** + * 同步拼多多顺丰定时派送服务中的快递产品类型。 + * + * 仅处理 service_code 为 TIMED-DELIVERY 且系统快递编码为 SF/SHUNFENG 的数据。 + * + * @param {Object} payload 入参 + * @param {Array} payload.shopExpressList 店铺快递签约列表 + * @return {Promise<{ createdCount: number, updatedCount: number, parsedCount: number }>} 同步结果 + */ + async syncPddSfTimedDeliveryExpressProductTypes(payload = {}) { + const { shopExpressList = [] } = payload && typeof payload === 'object' ? payload : {}; + const productTypeList = this.collectPddSfTimedDeliveryProductTypes(shopExpressList); + + if (productTypeList.length === 0) { + return { + createdCount: 0, + updatedCount: 0, + parsedCount: 0, + }; + } + + const upsertResult = await this.upsertExpressProductTypeList(productTypeList); + + return { + createdCount: Number(upsertResult.createdCount || 0), + updatedCount: Number(upsertResult.updatedCount || 0), + parsedCount: productTypeList.length, + }; + } + + 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(), + is_system_setting: false, + id: null, + alias: null, + }; + } + async loadExpressList() { + const cachedList = await this.loadExpressListFromCache(); + if (cachedList !== null) { + return cachedList; + } + + const expressList = await this.loadExpressListFromDatabase(); + await this.app.setCacheAsync('express:list:system:normal', expressList, DEFAULT_CACHE_TTL_SECONDS); + return expressList; + } + + async loadExpressListFromCache() { + const key = 'express:list:system:normal'; + try { + const cachedList = await this.app.getCacheAsync(key); + if (cachedList !== null && cachedList !== undefined) { + return Array.isArray(cachedList) ? cachedList : []; + } + } catch (error) { + this.ctx.logger.warn('[ExpressService.loadExpressListFromCache] 获取系统快递列表缓存失败: %s', error.message); + } + + return null; + } + + async loadExpressListFromDatabase() { + const rows = await this.ctx.model.Express.findAll({ + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows; + } + + /** + * 获取系统快递编码和名称列表。 + * + * 该接口只返回系统基础快递数据,不合并仓库自定义映射。 + * + * @return {Promise} 系统快递编码和名称列表 + */ + async getSystemExpressList() { + return await this.loadExpressListFromDatabase(); + } + + /** + * 从数据库加载快递产品类型列表。 + * + * @param {string} expressCode 快递公司编码 + * @return {Promise} 快递产品类型列表 + */ + async loadExpressProductTypeListFromDatabase(expressCode = '') { + const normalizedExpressCode = String(expressCode || '').trim(); + const query = { + attributes: [ 'code', 'name', 'express_code' ], + order: [[ 'express_code', 'ASC' ], [ 'code', 'ASC' ]], + raw: true, + }; + + if (normalizedExpressCode) { + query.where = { + express_code: normalizedExpressCode, + }; + } + + const rows = await this.ctx.model.ExpressProductType.findAll(query); + + if (!Array.isArray(rows)) { + return []; + } + + return rows + .map(row => this.normalizeExpressProductTypeRow(row)) + .filter(Boolean); + } + + /** + * 获取快递列表。 + * + * 默认先读取系统快递,再按当前仓库合并快递设置;同一编码只保留一条记录。 + * systemOnly 为 true 时仅返回系统快递列表。 + * + * 当传入系统快递编码时,按当前仓库与 `express_code` 字段仅返回对应自定义编码列表。 + * + * @param {boolean} [systemOnly=false] 是否仅返回系统基础快递列表 + * @param {string} [systemExpressCode=''] 系统快递编码 + * @return {Promise} 快递列表 + */ + async getExpressList(systemOnly = false, systemExpressCode = '') { + const warehouseId = this.getCurrentWarehouseId(); + const normalizedExpressCode = String(systemExpressCode || '').trim().toUpperCase(); + const cacheKey = this.getExpressListCacheKey(warehouseId, systemOnly, normalizedExpressCode); + + try { + const cachedList = await this.app.getCacheAsync(cacheKey); + if (cachedList !== null && cachedList !== undefined) { + return Array.isArray(cachedList) ? cachedList : []; + } + + if (systemOnly) { + const expressList = await this.getSystemExpressList(); + const filteredExpressList = normalizedExpressCode + ? expressList.filter(item => String(item && (item.code || item.value) || '').trim().toUpperCase() === normalizedExpressCode) + : expressList; + await this.app.setCacheAsync(cacheKey, filteredExpressList, DEFAULT_CACHE_TTL_SECONDS); + return filteredExpressList; + } + + const [ expressList, expressSettingList ] = await Promise.all([ + this.loadExpressListFromDatabase(), + this.loadExpressSettingListFromDatabase(warehouseId, normalizedExpressCode), + ]); + + if (normalizedExpressCode) { + const customCodeList = this.buildExpressSettingCustomCodeList(expressList, expressSettingList); + await this.app.setCacheAsync(cacheKey, customCodeList, DEFAULT_CACHE_TTL_SECONDS); + return customCodeList; + } + + const mergedList = this.buildMergedExpressList(expressList, expressSettingList); + await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_CACHE_TTL_SECONDS); + + return mergedList; + } catch (error) { + this.ctx.logger.error('[ExpressService.getExpressList] 获取快递列表失败', { + error: error.message, + stack: error.stack, + }); + throw error; + } + } + + /** + * 获取快递产品类型列表。 + * + * @param {string} expressCode 快递公司编码 + * @return {Promise} 快递产品类型列表 + */ + async getExpressProductTypeList(expressCode = '') { + const cacheKey = this.getExpressProductTypeListCacheKey(expressCode); + const normalizedExpressCode = String(expressCode || '').trim(); + + try { + const cachedList = await this.app.getCacheAsync(cacheKey); + if (cachedList !== null && cachedList !== undefined) { + return Array.isArray(cachedList) ? cachedList : []; + } + + const expressProductTypeList = await this.loadExpressProductTypeListFromDatabase(normalizedExpressCode); + await this.app.setCacheAsync(cacheKey, expressProductTypeList, DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS); + + return expressProductTypeList; + } catch (error) { + this.ctx.logger.error('[ExpressService.getExpressProductTypeList] 获取快递产品类型失败', { + error: error.message, + stack: error.stack, + expressCode: normalizedExpressCode, + }); + throw error; + } + } + + /** + * 规范化打印平台编码。 + * + * @param {*} platformCode 原始平台编码。 + * @return {string} 规范化后的平台编码。 + */ + normalizeWaybillPrintPlatformCode(platformCode) { + return String(platformCode || '').trim(); + } + + /** + * 按系统平台列表加载“系统平台编码 -> 请求平台编码”映射。 + * + * @param {Array} platformList 系统平台列表。 + * @return {Promise>} 映射结果。 + */ + async loadWaybillPrintPlatformCodeMap(platformList = []) { + const { Op } = this.app.Sequelize; + const printPlatformModel = this.ctx.model && this.ctx.model.PrintPlatform; + const normalizedPlatformList = Array.isArray(platformList) ? platformList : []; + + const platformCodeByPrintPlatformIdMap = new Map(); + for (const platform of normalizedPlatformList) { + const platformCode = this.normalizeWaybillPrintPlatformCode(platform && platform.code).toLowerCase(); + const printPlatformId = Number(platform && platform.print_platform_id); + if (!platformCode || !Number.isFinite(printPlatformId) || printPlatformId <= 0) { + continue; + } + + if (!platformCodeByPrintPlatformIdMap.has(printPlatformId)) { + platformCodeByPrintPlatformIdMap.set(printPlatformId, []); + } + platformCodeByPrintPlatformIdMap.get(printPlatformId).push(platformCode); + } + + if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { + return new Map(); + } + + const printPlatformRows = await printPlatformModel.findAll({ + where: { + id: { + [Op.in]: Array.from(platformCodeByPrintPlatformIdMap.keys()), + }, + }, + attributes: [ 'id', 'platform_code' ], + raw: true, + }); + + const printPlatformCodeMap = new Map(); + for (const row of Array.isArray(printPlatformRows) ? printPlatformRows : []) { + const printPlatformId = Number(row && row.id); + const platformCode = this.normalizeWaybillPrintPlatformCode(row && row.platform_code); + if (!Number.isFinite(printPlatformId) || printPlatformId <= 0 || !platformCode) { + continue; + } + + const systemPlatformCodes = platformCodeByPrintPlatformIdMap.get(printPlatformId); + if (!Array.isArray(systemPlatformCodes) || systemPlatformCodes.length === 0) { + continue; + } + + for (const systemPlatformCode of systemPlatformCodes) { + printPlatformCodeMap.set(systemPlatformCode, platformCode); + } + } + + return printPlatformCodeMap; + } + + /** + * 按系统平台列表加载“系统平台编码 -> 异步分流请求平台编码”映射。 + * + * 该映射仅用于运单异步后处理分流,来源必须是 + * `wms_print_platform.request_platform_code`,避免与分组/快递接口匹配使用的 + * `wms_print_platform.platform_code` 语义混用。 + * + * @param {Array} platformList 系统平台列表。 + * @return {Promise>} 映射结果。 + */ + async loadWaybillAsyncRequestPlatformCodeMap(platformList = []) { + const { Op } = this.app.Sequelize; + const printPlatformModel = this.ctx.model && this.ctx.model.PrintPlatform; + const normalizedPlatformList = Array.isArray(platformList) ? platformList : []; + + const platformCodeByPrintPlatformIdMap = new Map(); + for (const platform of normalizedPlatformList) { + const platformCode = this.normalizeWaybillPrintPlatformCode(platform && platform.code).toLowerCase(); + const printPlatformId = Number(platform && platform.print_platform_id); + if (!platformCode || !Number.isFinite(printPlatformId) || printPlatformId <= 0) { + continue; + } + + if (!platformCodeByPrintPlatformIdMap.has(printPlatformId)) { + platformCodeByPrintPlatformIdMap.set(printPlatformId, []); + } + platformCodeByPrintPlatformIdMap.get(printPlatformId).push(platformCode); + } + + if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { + return new Map(); + } + + const printPlatformRows = await printPlatformModel.findAll({ + where: { + id: { + [Op.in]: Array.from(platformCodeByPrintPlatformIdMap.keys()), + }, + }, + attributes: [ 'id', 'request_platform_code' ], + raw: true, + }); + + const requestPlatformCodeMap = new Map(); + for (const row of Array.isArray(printPlatformRows) ? printPlatformRows : []) { + const printPlatformId = Number(row && row.id); + const requestPlatformCode = this.normalizeWaybillPrintPlatformCode(row && row.request_platform_code); + if (!Number.isFinite(printPlatformId) || printPlatformId <= 0 || !requestPlatformCode) { + continue; + } + + const systemPlatformCodes = platformCodeByPrintPlatformIdMap.get(printPlatformId); + if (!Array.isArray(systemPlatformCodes) || systemPlatformCodes.length === 0) { + continue; + } + + for (const systemPlatformCode of systemPlatformCodes) { + requestPlatformCodeMap.set(systemPlatformCode, requestPlatformCode); + } + } + + return requestPlatformCodeMap; + } + + /** + * 解析运单异步分流所需的请求平台编码。 + * + * @param {string} sysPlatformCode 订单系统平台编码。 + * @param {Map} [requestPlatformCodeMap=new Map()] 系统平台到请求平台编码映射。 + * @return {string} 请求平台编码;未命中时返回空字符串。 + */ + resolveWaybillAsyncRequestPlatformCode(sysPlatformCode = '', requestPlatformCodeMap = new Map()) { + const normalizedSysPlatformCode = this.normalizeWaybillPrintPlatformCode(sysPlatformCode).toLowerCase(); + if (!normalizedSysPlatformCode) { + return ''; + } + + return requestPlatformCodeMap instanceof Map + ? this.normalizeWaybillPrintPlatformCode(requestPlatformCodeMap.get(normalizedSysPlatformCode)) + : ''; + } + + /** + * 解析运单分组所需的打印平台编码。 + * + * @param {string} sysPlatformCode 订单系统平台编码。 + * @param {Map} printPlatformCodeMap 打印平台编码映射。 + * @return {string} 打印平台编码;未命中时回退系统平台编码。 + */ + resolveWaybillGroupPrintPlatformCode(sysPlatformCode = '', printPlatformCodeMap = new Map()) { + const normalizedSysPlatformCode = this.normalizeWaybillPrintPlatformCode(sysPlatformCode).toLowerCase(); + if (!normalizedSysPlatformCode) { + return ''; + } + + const mappedPrintPlatformCode = printPlatformCodeMap instanceof Map + ? this.normalizeWaybillPrintPlatformCode(printPlatformCodeMap.get(normalizedSysPlatformCode)) + : ''; + + this.ctx.logger.info('[ExpressService.resolveWaybillGroupPrintPlatformCode] 映射查找', { + sysPlatformCode, + normalizedSysPlatformCode, + mapSize: printPlatformCodeMap instanceof Map ? printPlatformCodeMap.size : 'not-a-map', + mapKeys: printPlatformCodeMap instanceof Map ? JSON.stringify(Array.from(printPlatformCodeMap.keys())) : 'N/A', + mappedValue: printPlatformCodeMap instanceof Map ? printPlatformCodeMap.get(normalizedSysPlatformCode) : 'N/A', + finalResult: mappedPrintPlatformCode || '(空)', + }); + + return mappedPrintPlatformCode; + } + + /** + * 按打印平台编码和 logistics_code 对订单进行分组。 + *【已使用】 + * @param {Array} orders 已规范化的订单列表。 + * @param {Map} [printPlatformCodeMap=new Map()] 系统平台到打印平台编码映射。 + * @return {Array} 分组结果。 + */ + groupWaybillOrdersByPlatformAndLogistics(orders = [], printPlatformCodeMap = new Map()) { + // 【step2】按平台 + 快递编码+货主id分组,后续按组串行处理。 + + const groupedOrders = []; + const groupedOrderMap = new Map(); + + for (const order of Array.isArray(orders) ? orders : []) { + if (!order || typeof order !== 'object') { + continue; + } + + const sysPlatformCode = String(order.sys_platform_code || '').trim(); + const logisticsCode = String(order.logistics_code || '').trim(); + const printPlatformCode = this.resolveWaybillGroupPrintPlatformCode(sysPlatformCode, printPlatformCodeMap); + if (!sysPlatformCode || !logisticsCode || !printPlatformCode) { + this.ctx.logger.warn('[ExpressService.groupWaybillOrdersByPlatformAndLogistics] 订单分组被跳过', { + orderId: order.id, + sysPlatformCode: sysPlatformCode || '(空)', + logisticsCode: logisticsCode || '(空)', + printPlatformCode: printPlatformCode || '(空)', + reason: !sysPlatformCode ? 'sysPlatformCode为空' : !logisticsCode ? 'logisticsCode为空' : 'printPlatformCode映射失败', + }); + continue; + } + + const groupKey = `${printPlatformCode}:${logisticsCode}:${order.store_id || 0}`; + let groupedOrder = groupedOrderMap.get(groupKey); + + if (!groupedOrder) { + groupedOrder = { + options: { + sys_platform_code: sysPlatformCode, + print_platform_code: printPlatformCode, + logistics_code: logisticsCode, + sys_logistics_code: String(order.sys_logistics_code || '').trim(), + weight_type: order.weight_type !== undefined ? Number(order.weight_type) : 0, + sys_platform_name: order.sys_platform_name || '', + logistics_name: order.logistics_name || '', + store_id: order.store_id || 0, + }, + orders: [], + }; + groupedOrderMap.set(groupKey, groupedOrder); + groupedOrders.push(groupedOrder); + } + + groupedOrder.orders.push(order); + } + + return groupedOrders; + } + + /** + * 将订单按指定数量拆分为多个批次。 + *【已使用】 + * @param {Array} orders 订单列表 + * @param {number} [batchSize=10] 每批最大数量 + * @return {Array>} 批次列表 + */ + splitWaybillOrdersIntoBatches(orders = [], batchSize = DEFAULT_WAYBILL_BATCH_SIZE) { + // 【step3】按批大小切分订单,控制单次创建量。 + const normalizedOrders = Array.isArray(orders) ? orders : []; + const normalizedBatchSize = Math.floor(Number(batchSize)); + const effectiveBatchSize = Number.isFinite(normalizedBatchSize) && normalizedBatchSize > 0 + ? normalizedBatchSize + : DEFAULT_WAYBILL_BATCH_SIZE; + const batches = []; + + for (let index = 0; index < normalizedOrders.length; index += effectiveBatchSize) { + batches.push(normalizedOrders.slice(index, index + effectiveBatchSize)); + } + + return batches; + } + + /** + * 从仓库+平台接口配置列表中按订单分组快递编码选择可用配置。 + * + * 匹配字段顺序:sys_express_code -> express_code -> express[platform_code]。 + * 比对时统一去空格并转小写,匹配命中后按原列表顺序返回首条。 + * + * @param {Array} interfaceList 接口配置列表。 + * @param {Object} groupedOrder 订单分组信息。 + * @param {Object} matchedPlatform 平台配置。 + * @return {Object|null} 匹配到的接口配置,未匹配返回 null。 + */ + pickWaybillExpressInterface(interfaceList = [], groupedOrder = {}, matchedPlatform = null) { + const normalizeCode = value => String(value || '').trim().toLowerCase(); + const logisticsCode = normalizeCode( + groupedOrder + && groupedOrder.options + && groupedOrder.options.logistics_code + ); + const sysLogisticsCode = normalizeCode( + groupedOrder + && groupedOrder.options + && groupedOrder.options.sys_logistics_code + ); + const orderWeightType = Number( + groupedOrder + && groupedOrder.options + && groupedOrder.options.weight_type + ) || 0; + + const platformCode = normalizeCode( + groupedOrder + && groupedOrder.options + && groupedOrder.options.print_platform_code + || matchedPlatform + && matchedPlatform.route_platform_code + || matchedPlatform + && matchedPlatform.default_express_interface + || matchedPlatform + && matchedPlatform.print_platform_code + ); + + const enabledList = (Array.isArray(interfaceList) ? interfaceList : []) + .filter(item => item && typeof item === 'object' && Number(item.is_enabled) === 1); + + // 通用匹配函数 + const matchByCode = (item, targetCode, useSysCode = true) => { + if (!targetCode) return false; + const candidateCodes = [ normalizeCode(item.express_code) ]; + if (useSysCode) { + candidateCodes.push(normalizeCode(item.sys_express_code)); + } + const expressMap = item.express && typeof item.express === 'object' ? item.express : null; + if (expressMap && platformCode) { + candidateCodes.push(normalizeCode(expressMap[platformCode])); + } + if (!candidateCodes.some(code => code && code === targetCode)) return false; + + const itemWeightType = item.weight_type !== null && item.weight_type !== undefined + ? Number(item.weight_type) : null; + if (itemWeightType !== null && itemWeightType !== orderWeightType) return false; + + return true; + }; + + // 第一步:logistics_code 仅匹配 express_code + 平台码(不用 sys_express_code) + if (logisticsCode) { + for (const item of enabledList) { + if (matchByCode(item, logisticsCode, false)) { + return item; + } + } + } + + // 第二步:sys_logistics_code 匹配 sys_express_code + express_code(全放开) + if (sysLogisticsCode) { + for (const item of enabledList) { + if (matchByCode(item, sysLogisticsCode, true)) { + return item; + } + } + } + + return null; + } + + /** + * 解析运单后处理可用的平台编码。 + * + * @param {Object} order 订单或平台上下文。 + // 【step4】检查余额、锁定可用数量,并拆出成功与失败订单。 + * @return {string} 平台编码,小写。 + */ + resolveWaybillAsyncPlatformCode(order = {}) { + if (!order || typeof order !== 'object') { + return ''; + } + + const expressPlatform = order.wms_express_platform && typeof order.wms_express_platform === 'object' + ? order.wms_express_platform + : (order.wmsExpressPlatform && typeof order.wmsExpressPlatform === 'object' ? order.wmsExpressPlatform : null); + + const rawPlatformCode = (expressPlatform && (expressPlatform.platform_code || expressPlatform.platformCode)) + || order.express_platform_code + || order.expressPlatformCode + || order.platform_code + || order.platformCode + || order.sys_platform_code + || order.sysPlatformCode + || (typeof order.wms_express_platform === 'string' ? order.wms_express_platform : '') + || (typeof order.wmsExpressPlatform === 'string' ? order.wmsExpressPlatform : ''); + + return String(rawPlatformCode || '').trim().toLowerCase(); + } + + /** + * 按平台编码汇总需要异步后处理的订单。 + * + * @param {Array} orders 成功订单列表。 + // 【step5】把失败订单回写为异常状态,供主链路统一收口。 + * @return {Array} 平台分组结果。 + */ + groupWaybillAsyncOrdersByPlatform(orders = []) { + const groupedOrderMap = new Map(); + + for (const order of Array.isArray(orders) ? orders : []) { + if (!order || typeof order !== 'object') { + continue; + } + + const platformCode = this.resolveWaybillAsyncPlatformCode(order); + let groupedOrder = groupedOrderMap.get(platformCode); + + if (!groupedOrder) { + groupedOrder = { + platform_code: platformCode, + orders: [], + }; + groupedOrderMap.set(platformCode, groupedOrder); + } + + groupedOrder.orders.push(order); + } + + return Array.from(groupedOrderMap.values()); + } + + /** + * 将订单主表快照按订单 ID 建立映射。 + *【已使用】 + * @param {Array} orderDeliveryRows 订单主表查询结果。 + // 【step5】按失败原因分批回写异常,避免失败链路遗漏。 + * @return {Map} 订单快照映射。 + */ + buildWaybillOrderDeliveryMap(orderDeliveryRows = []) { + const orderDeliveryMap = new Map(); + + for (const row of Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []) { + const orderId = Number(row && row.id); + if (Number.isFinite(orderId) && orderId > 0) { + orderDeliveryMap.set(orderId, row); + } + } + + return orderDeliveryMap; + } + + /** + * 将异步后处理文本字段标准化。 + * + * @param {*} value 原始值。 + * @return {string|null} 标准化结果。 + */ + normalizeWaybillAsyncText(value) { + if (value === undefined || value === null) { + return null; + } + + const normalizedValue = String(value).trim(); + return normalizedValue ? normalizedValue : null; + } + + /** + * 将异步后处理数值字段标准化。 + * + * @param {*} value 原始值。 + * @return {number} 标准化结果。 + */ + normalizeWaybillAsyncNumber(value) { + const normalizedValue = Number(value); + return Number.isFinite(normalizedValue) ? normalizedValue : 0; + } + + /** + * 将异步后处理日期字段标准化为 ISO 字符串。 + * + * @param {*} value 原始值。 + * @return {string|null} 标准化结果。 + */ + formatWaybillAsyncDate(value) { + if (value === undefined || value === null || value === '') { + return null; + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + return null; + } + + return date.toISOString(); + } + + /** + * 标准化异步后处理商品明细字段。 + * + * @param {*} value 原始值。 + * @return {Array} 标准化结果。 + */ + normalizeWaybillAsyncItems(value) { + if (Array.isArray(value)) { + return value.map(item => (typeof item === 'string' ? item.trim() : item)); + } + + if (typeof value === 'string') { + return value + .split('|') + .map(item => item.trim()) + .filter(Boolean); + } + + return []; + } + + /** + * 构建异步后处理中的路由信息块。 + * + * @param {Object} order 订单上下文。 + * @param {Object} orderDelivery 订单主表快照。 + * @return {Object} 路由信息块。 + */ + buildWaybillAsyncRouteInfo(order = {}, orderDelivery = {}) { + return { + source_platform_code: this.normalizeWaybillAsyncText(orderDelivery.source_platform_code), + source_platform_name: this.normalizeWaybillAsyncText(orderDelivery.source_platform_name), + sys_platform_code: this.normalizeWaybillAsyncText(orderDelivery.sys_platform_code || order.sys_platform_code), + sys_platform_name: this.normalizeWaybillAsyncText(orderDelivery.sys_platform_name), + logistics_code: this.normalizeWaybillAsyncText(order.logistics_code || orderDelivery.logistics_code), + logistics_name: this.normalizeWaybillAsyncText(orderDelivery.logistics_name), + sys_logistics_code: this.normalizeWaybillAsyncText(orderDelivery.sys_logistics_code), + sys_logistics_name: this.normalizeWaybillAsyncText(orderDelivery.sys_logistics_name), + express_code: this.normalizeWaybillAsyncText(orderDelivery.express_code), + logistics_area_code: this.normalizeWaybillAsyncText(orderDelivery.logistics_area_code), + }; + } + + /** + * 构建异步后处理中的订单信息块。 + * + * @param {Object} orderDelivery 订单主表快照。 + * @return {Object} 订单信息块。 + */ + buildWaybillAsyncOrderInfo(orderDelivery = {}) { + return { + delivery_order_code: this.normalizeWaybillAsyncText(orderDelivery.delivery_order_code), + order_type: this.normalizeWaybillAsyncText(orderDelivery.order_type), + status: this.normalizeWaybillAsyncText(orderDelivery.status), + step: this.normalizeWaybillAsyncNumber(orderDelivery.step), + order_flag: this.normalizeWaybillAsyncText(orderDelivery.order_flag), + from_key: this.normalizeWaybillAsyncText(orderDelivery.from_key), + create_at: this.formatWaybillAsyncDate(orderDelivery.create_at), + place_order_time: this.formatWaybillAsyncDate(orderDelivery.place_order_time), + pay_time: this.formatWaybillAsyncDate(orderDelivery.pay_time), + operate_time: this.formatWaybillAsyncDate(orderDelivery.operate_time), + delivery_time: this.formatWaybillAsyncDate(orderDelivery.delivery_time), + }; + } + + /** + * 构建异步后处理中的收件人信息块。 + * + * @param {Object} orderDelivery 订单主表快照。 + * @return {Object} 收件人信息块。 + */ + buildWaybillAsyncReceiverInfo(orderDelivery = {}) { + return { + name: this.normalizeWaybillAsyncText(orderDelivery.name), + tel: this.normalizeWaybillAsyncText(orderDelivery.tel), + mobile: this.normalizeWaybillAsyncText(orderDelivery.mobile), + email: this.normalizeWaybillAsyncText(orderDelivery.email), + country_code: this.normalizeWaybillAsyncText(orderDelivery.country_code), + province: this.normalizeWaybillAsyncText(orderDelivery.province), + city: this.normalizeWaybillAsyncText(orderDelivery.city), + area: this.normalizeWaybillAsyncText(orderDelivery.area), + town: this.normalizeWaybillAsyncText(orderDelivery.town), + detail_address: this.normalizeWaybillAsyncText(orderDelivery.detail_address), + zip_code: this.normalizeWaybillAsyncText(orderDelivery.zip_code), + }; + } + + /** + * 构建异步后处理中的结算信息块。 + * + * @param {Object} orderDelivery 订单主表快照。 + * @return {Object} 结算信息块。 + */ + buildWaybillAsyncSettlementInfo(orderDelivery = {}) { + return { + total_amount: this.normalizeWaybillAsyncNumber(orderDelivery.total_amount), + item_amount: this.normalizeWaybillAsyncNumber(orderDelivery.item_amount), + discount_amount: this.normalizeWaybillAsyncNumber(orderDelivery.discount_amount), + freight: this.normalizeWaybillAsyncNumber(orderDelivery.freight), + ar_amount: this.normalizeWaybillAsyncNumber(orderDelivery.ar_amount), + got_amount: this.normalizeWaybillAsyncNumber(orderDelivery.got_amount), + }; + } + + /** + * 构建异步后处理中的商品汇总信息块。 + * + * @param {Object} orderDelivery 订单主表快照。 + * @return {Object} 商品汇总信息块。 + */ + buildWaybillAsyncItemsSummary(orderDelivery = {}) { + return { + items: this.normalizeWaybillAsyncItems(orderDelivery.items), + items_count: this.normalizeWaybillAsyncNumber(orderDelivery.items_count), + items_total: this.normalizeWaybillAsyncNumber(orderDelivery.items_total), + items_weight: this.normalizeWaybillAsyncNumber(orderDelivery.items_weight), // 单位 g,传递给下游快递平台 + }; + } + + /** + * 构建异步后处理中的单个订单项。 + * + * @param {Object} order 成功订单上下文。 + * @return {Object} 订单项快照。 + */ + buildWaybillAsyncOrderListItem(order = {}) { + const orderDelivery = order && typeof order.order_delivery === 'object' ? order.order_delivery : {}; + + return { + order_id: this.normalizeWaybillAsyncNumber(order.order_id), + business_key: this.normalizeWaybillAsyncNumber(order.business_key), + sys_platform_code: this.normalizeWaybillAsyncText(order.sys_platform_code || orderDelivery.sys_platform_code), + logistics_code: this.normalizeWaybillAsyncText(order.logistics_code || orderDelivery.logistics_code), + express_platform_code: this.normalizeWaybillAsyncText(order.express_platform_code || orderDelivery.express_platform_code || this.resolveWaybillAsyncPlatformCode(order)), + route_info: this.buildWaybillAsyncRouteInfo(order, orderDelivery), + order_info: this.buildWaybillAsyncOrderInfo(orderDelivery), + receiver_info: this.buildWaybillAsyncReceiverInfo(orderDelivery), + settlement_info: this.buildWaybillAsyncSettlementInfo(orderDelivery), + items_summary: this.buildWaybillAsyncItemsSummary(orderDelivery), + }; + } + + /** + * 运单后处理 bizcontent 骨架的返回结构。 + * + * 顶层返回对象仅包含一个 `bizcontent` 字段,方便后续按平台继续扩展。 + * + * @typedef {Object} WaybillAsyncBizcontentSkeletonResult + * @property {WaybillAsyncBizcontentSkeleton} bizcontent 顶层业务载荷对象。 + */ + + /** + * 运单后处理 bizcontent 的完整结构。 + * + * 该结构当前只负责承载统一字段与订单列表骨架,平台差异字段按需挂载。 + * + * @typedef {Object} WaybillAsyncBizcontentSkeleton + * @property {string} platform_code 平台编码,来源于当前业务上下文或订单分组结果。 + * @property {string} [express_platform_code] 物流平台编码,仅在上游传入时保留。 + * @property {number} store_id 店铺 ID,未传时为 `0`。 + * @property {number} warehouse_id 仓库 ID,未传时为 `0`。 + * @property {Array} order_list 订单列表骨架。 + * @property {Object} platform_payload 平台专属载荷占位对象,当前固定为空对象。 + */ + + /** + * `order_list` 中单个订单项的结构。 + * + * @typedef {Object} WaybillAsyncOrderItemSkeleton + * @property {number} order_id 订单 ID,未能解析时为 `0`。 + * @property {number} business_key 业务主键,未能解析时为 `0`。 + * @property {string} sys_platform_code 系统平台编码,做了去空格处理。 + * @property {string} logistics_code 物流编码,做了去空格处理。 + * @property {string} express_platform_code 当前订单对应的物流平台编码。 + */ + + /** + * 构建运单后处理统一业务数据骨架。 + * + * 仅保留请求级公共字段与订单列表骨架,平台差异字段暂时留空,后续再补充。 + * + * 返回数据结构如下: + * - 顶层返回对象:`{ bizcontent: WaybillAsyncBizcontentSkeleton }` + * - `bizcontent`:包含平台编码、店铺 ID、仓库 ID、订单列表和平台专属载荷占位 + * - `order_list`:由多个 `WaybillAsyncOrderItemSkeleton` 组成 + * - `platform_payload`:当前固定为空对象 `{}`,用于后续按平台补充差异字段 + * + * @param {Array} orders 成功订单列表。 + * @param {Object} [options={}] 业务上下文。 + * @return {WaybillAsyncBizcontentSkeletonResult} 统一业务数据骨架。 + */ + buildWaybillAsyncBizcontentSkeleton(orders = [], options = {}) { + const normalizedOrders = Array.isArray(orders) ? orders : []; + const platformCode = this.resolveWaybillAsyncPlatformCode({ + ...options, + wms_express_platform: options.wms_express_platform || options.wmsExpressPlatform || null, + }); + const expressPlatformCode = String(options.express_platform_code || options.expressPlatformCode || '').trim(); + + return { + bizcontent: { + platform_code: platformCode, + store_id: Number(options.store_id || options.storeId || 0) || 0, + warehouse_id: Number(options.warehouse_id || options.warehouseId || 0) || 0, + order_list: normalizedOrders.map(order => this.buildWaybillAsyncOrderListItem(order)), + platform_payload: {}, + ...(expressPlatformCode ? { express_platform_code: expressPlatformCode } : {}), + // 这里先不拼平台公共字段,后续再补充平台凭证、接口版本、渠道参数等内容。 + }, + }; + } + + /** + * 判断异步取号平台是否需要逐单分发。 + * + * 当前菜鸟、拼多多平台要求按单请求,避免整批订单透传到平台侧。 + * + * @param {string} platformCode 平台编码。 + * @return {boolean} 是否逐单分发。 + */ + shouldDispatchWaybillAsyncPerOrder(platformCode = '') { + const normalizedPlatformCode = String(platformCode || '').trim().toLowerCase(); + + return WAYBILL_ASYNC_SINGLE_ORDER_PLATFORM_CODES.has(normalizedPlatformCode); + } + + /** + * 将统一业务数据骨架按wms_print_platform.request_platform_code分流。 + * + * 直接调用平台服务实例上的同名方法;如果方法不存在,或平台方法返回失败结果,则向上抛出异常。 + * + * @param {string} platformCode 平台编码。 + * @param {Object} bizcontent 统一业务数据骨架。 + * @return {Promise} 无返回值。 + */ + async dispatchWaybillAsyncPlatform(platformCode = '', bizcontent = {}) { + const normalizedPlatformCode = String(platformCode).trim().toLowerCase(); + const expressPlatformService = this.service + && this.service.systems + && (this.service.systems.expressPlatform || this.service.systems.express_platform); + const dispatchMethod = expressPlatformService && expressPlatformService[normalizedPlatformCode]; + + if (typeof dispatchMethod !== 'function') { + throw new Error(normalizedPlatformCode + '接口未实现'); + } + + const normalizedOrders = Array.isArray(bizcontent && bizcontent.orders) + ? bizcontent.orders + : []; + + // 需要逐单调用的平台(cainiao/pdd):拆分为逐单 payload,并发调用 + if (this.shouldDispatchWaybillAsyncPerOrder(normalizedPlatformCode) && normalizedOrders.length > 1) { + const perOrderPayloads = normalizedOrders.map(order => ({ + ...bizcontent, + orders: [ order ], + })); + + const perOrderResults = await Promise.all( + perOrderPayloads.map(payload => + dispatchMethod.call(expressPlatformService, payload).then( + dispatchResult => ({ payload, dispatchResult, error: null }), + error => ({ payload, dispatchResult: null, error }) + ) + ) + ); + + // 检查是否有失败结果;取第一个失败原因作为异常抛出 + const firstFailure = perOrderResults.find( + item => item.error + || (item.dispatchResult && typeof item.dispatchResult === 'object' && item.dispatchResult.flag === 'failure') + ); + if (firstFailure) { + const failureMessage = firstFailure.error + ? (firstFailure.error.message || String(firstFailure.error)) + : (firstFailure.dispatchResult && firstFailure.dispatchResult.message); + throw new Error(failureMessage || normalizedPlatformCode + '接口调用失败'); + } + + return; + } + + // 非逐单平台:保持原有单次批量调用 + const dispatchResult = await dispatchMethod.call(expressPlatformService, bizcontent); + if (dispatchResult && typeof dispatchResult === 'object' && dispatchResult.flag === 'failure') { + throw new Error(dispatchResult.message || normalizedPlatformCode + '接口调用失败'); + } + } + + /** + * 对指定订单回 OMS 取号(need_oms_waybill=1)。 + * + * 内部完成「查订单 → 组报文 → 调 oms 平台方法 → 写回运单号」, + * 供队列消费与手工「分配快递号」共用。 + * + * @param {Array} orders 订单列表([{ order_id, business_key }])。 + * @param {Object} [options={}] 上下文。 + * @param {number} options.warehouseId 仓库 ID。 + * @return {Promise} 平台返回结果。 + */ + async requestOmsWaybills(orders = [], options = {}) { + const warehouseId = Number(options.warehouseId) || 0; + const normalizedOrders = (Array.isArray(orders) ? orders : []) + .map(order => ({ + order_id: Number(order && (order.order_id || order.id)) || 0, + business_key: Number(order && order.business_key) || 1, + })) + .filter(order => Number.isInteger(order.order_id) && order.order_id > 0); + + if (warehouseId <= 0 || normalizedOrders.length === 0) { + return { flag: 'success', code: 0, message: '无需要回 OMS 取号的订单' }; + } + + const { Op } = this.app.Sequelize; + const orderModel = await this.getWaybillAsyncOrderDeliveryModel(warehouseId); + + if (!orderModel || typeof orderModel.findAll !== 'function') { + throw new Error('订单主表模型未初始化,无法回 OMS 取号'); + } + + const orderRows = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: Array.from(new Set(normalizedOrders.map(order => order.order_id))), + }, + }, + attributes: [ + 'id', 'warehouse_id', 'store_id', 'delivery_order_code', + 'logistics_code', 'sys_logistics_code', 'source_order_codes', 'need_oms_waybill', 'from_key', + ], + raw: true, + }); + const orderMap = new Map( + (Array.isArray(orderRows) ? orderRows : []).map(row => [ Number(row.id), row ]) + ); + const payloadOrders = []; + const missingOrderIds = []; + + for (const order of normalizedOrders) { + const orderRow = orderMap.get(order.order_id); + + if (!orderRow) { + missingOrderIds.push(order.order_id); + continue; + } + + payloadOrders.push({ + order_id: order.order_id, + business_key: order.business_key, + order_delivery: orderRow, + }); + } + + if (payloadOrders.length === 0) { + throw new Error(`订单不存在或已流转到其它分表: ${missingOrderIds.join(',')}`); + } + + try { + return await this.dispatchWaybillAsyncPlatform('oms', { + warehouse_id: warehouseId, + store_id: Number(payloadOrders[0].order_delivery.store_id) || 0, + orders: payloadOrders, + }); + } catch (error) { + // 与本地平台失败口径一致:标记订单异常、写失败日志、清理未完成占位行 + await this.handleWaybillAllocateFailure( + payloadOrders.map(order => ({ + order_id: order.order_id, + business_key: order.business_key, + })), + { warehouse_id: warehouseId, sys_platform_code: 'oms' }, + error && error.message ? error.message : String(error) + ).catch(failureError => { + this.ctx.logger.error('[ExpressService.requestOmsWaybills] 失败收尾处理异常', { + error: failureError && failureError.message ? failureError.message : `${failureError}`, + }); + }); + + throw error; + } + } + + /** + * 统一的运单分配失败收尾:标记订单异常、写失败日志、清理未完成的快递占位行。 + * + * 本地平台(asyncTask)与回 OMS 取号(requestOmsWaybills / 队列消费)共用同一口径, + * 避免第三方取号失败只体现在任务进度里、订单侧看不到异常。 + * + * @param {Array} orders 订单列表([{ order_id, business_key }])。 + * @param {Object} [options={}] 上下文。 + * @param {number} [options.warehouse_id] 仓库 ID。 + * @param {string} [options.sys_platform_code] 平台编码(OMS 场景传 'oms')。 + * @param {string} errorMessage 失败原因。 + * @return {Promise>} 被标记失败的订单 ID 列表。 + */ + async handleWaybillAllocateFailure(orders = [], options = {}, errorMessage = '') { + const errOrders = (Array.isArray(orders) ? orders : []).map(order => ({ + order_id: order && (order.order_id || order.id), + business_key: order && order.business_key, + })); + const allOrderIds = errOrders + .map(order => Number(order && order.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0); + + if (allOrderIds.length === 0) { + return []; + } + + // 查询已成功分配(status=1)的订单,从失败列表中排除,避免误标异常 + const successOrderIdSet = new Set(); + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (orderExpressModel) { + try { + // 强制同仓校验:读取运单状态必须同时限定订单ID与仓库ID,禁止跨仓串读 + const statusCheckWarehouseId = Number(options && options.warehouse_id) + || this.getCurrentWarehouseId(); + const successRows = await orderExpressModel.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: allOrderIds }, + status: 1, + warehouse_id: statusCheckWarehouseId, + }, + attributes: [ 'order_id' ], + raw: true, + }); + for (const row of Array.isArray(successRows) ? successRows : []) { + const successOrderId = Number(row && row.order_id); + if (Number.isFinite(successOrderId) && successOrderId > 0) { + successOrderIdSet.add(successOrderId); + } + } + } catch (statusCheckError) { + this.ctx.logger.error('[ExpressService.handleWaybillAllocateFailure] 查询已成功订单状态失败,降级为全量标记', { + error: statusCheckError && statusCheckError.message ? statusCheckError.message : `${statusCheckError}`, + }); + } + } + + const failedOrderIds = allOrderIds.filter(orderId => !successOrderIdSet.has(orderId)); + if (failedOrderIds.length === 0) { + return []; + } + + const logWarehouseId = this.getOrderLogWarehouseId(options && options.warehouse_id); + const message = String(errorMessage || '运单分配失败'); + + this.service.systems.orderPendingException.markPendingException({ + ids: failedOrderIds, + exception_text: `订单快递分配失败: ${message}`, + }); + + await this.createAllocateExpressFailureLogs(failedOrderIds, message, logWarehouseId); + await this.hardDeleteWaybillAsyncOrderExpressRows(errOrders, { + platform_code: options && options.sys_platform_code, + error_message: message, + }); + + return failedOrderIds; + } + + /** + * 解析运单后处理分发平台编码。 + * + * 优先使用 `wms_print_platform.request_platform_code`,未提供时兼容历史字段。 + * + * @param {Object} [matchedPlatform={}] 平台匹配信息。 + * @return {string} 后处理分发平台编码。 + */ + resolveWaybillAsyncDispatchPlatformCode(matchedPlatform = {}) { + return String( + matchedPlatform.request_platform_code + || matchedPlatform.route_platform_code + || matchedPlatform.platform_code + || matchedPlatform.code + || matchedPlatform.default_express_interface + || '' + ).trim(); + } + + + /** + * 硬删除运单异步失败分组对应的订单快递记录(仅删除 status=0 的未完成记录,保护手工录入等已完成记录)。 + * + * 删除条件必须同时包含订单ID和业务键,若任一订单缺少 business_key,则记录原因并跳过整个分组,避免误删。 + * + * @param {Array} orders 失败分组订单列表。 + * @param {Object} [options={}] 分组上下文。 + * @param {string} [options.platform_code=''] 平台编码。 + * @param {string} [options.error_message=''] 失败原因。 + * @return {Promise} 是否已成功执行硬删除。 + */ + async hardDeleteWaybillAsyncOrderExpressRows(orders = [], options = {}) { + const { Op } = this.app.Sequelize; + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + + if (!orderExpressModel || typeof orderExpressModel.destroy !== 'function') { + this.ctx.logger.error('[ExpressService.hardDeleteWaybillAsyncOrderExpressRows] 订单快递模型未初始化,跳过失败分组硬删', { + platform_code: String(options.platform_code || '').trim(), + error_message: String(options.error_message || '').trim(), + }); + return false; + } + + const normalizedOrders = Array.isArray(orders) ? orders : []; + const deleteConditions = []; + + for (const order of normalizedOrders) { + const orderId = Number(order && order.order_id); + const businessKey = Number(order && order.business_key); + + if (!Number.isFinite(orderId) || orderId <= 0) { + this.ctx.logger.error('[ExpressService.hardDeleteWaybillAsyncOrderExpressRows] 失败分组订单缺少有效 order_id,已跳过该分组硬删', { + order_id: order && order.order_id, + business_key: order && order.business_key, + platform_code: String(options.platform_code || '').trim(), + error_message: String(options.error_message || '').trim(), + }); + return false; + } + + if (!Number.isFinite(businessKey) || businessKey <= 0) { + this.ctx.logger.error('[ExpressService.hardDeleteWaybillAsyncOrderExpressRows] 失败分组订单缺少 business_key,已跳过该分组硬删与回写', { + order_id: orderId, + business_key: order && order.business_key, + platform_code: String(options.platform_code || '').trim(), + error_message: String(options.error_message || '').trim(), + }); + return false; + } + + deleteConditions.push({ + order_id: orderId, + business_key: businessKey, + }); + } + + if (deleteConditions.length === 0) { + return false; + } + + try { + await orderExpressModel.destroy({ + where: { + [Op.or]: deleteConditions, + status: 0, + }, + }); + return true; + } catch (error) { + this.ctx.logger.error('[ExpressService.hardDeleteWaybillAsyncOrderExpressRows] 失败分组硬删订单快递记录失败', { + error: error.message, + stack: error.stack, + platform_code: String(options.platform_code || '').trim(), + error_message: String(options.error_message || '').trim(), + delete_conditions: deleteConditions, + }); + return false; + } + } + + /** + * 获取运单异步后处理使用的订单主表模型。 + * + * 优先使用当前上下文中已挂载的订单主表模型;如果只有工厂,则按仓库 ID 取当前模型。 + * + * @param {number} currentWarehouseId 当前仓库 ID。 + * @return {Promise} 订单主表模型或空值。 + * 【已使用】 + */ + async getWaybillAsyncOrderDeliveryModel(currentWarehouseId = 0) { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!currentWarehouseId || !orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return null; + } + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(currentWarehouseId); + if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { + return null; + } + + return orderDeliveryModel; + } + + + /** + * 按分组和批次顺序初始化订单运单表。 + * + * 先标准化订单,再按 print_platform_code 和 logistics_code 分组, + * 最后按每批最多 10 条的规则顺序调用现有 createWaybillCode。 + * business_key 支持单值或数组输入,内部会展开成多条记录后再分组批处理。 + *【已使用】 + * @param {Array} orders 订单与业务键列表。 + * @param {Object} [options] 可选配置。 + * @param {boolean} [options.awaitTasks=false] 是否等待所有异步任务完成后再返回。 + * @param {Function} [options.onBatchComplete] 单批完成回调 ({ processed, total })。 + * @param {number} [options.warehouseId] 仓库ID覆盖值,用于 setImmediate 等异步上下文中 ctx.user 不可用的场景。 + * @return {Promise} 处理结果,包含 orders、waybill_codes 和 skippedOrders。 + */ + async createWaybillCodePipeline(orders = [], options = {}) { + const { app } = this; + const { Op } = app.Sequelize; + const orderList = Array.isArray(orders) ? orders : []; + const traceId = this.buildWaybillTraceId({}, `pipeline_${Date.now()}`); + const pipelineOptions = options && typeof options === 'object' ? options : {}; + + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 入口请求', { + traceId, + orderCount: orderList.length, + orderIds: orderList.slice(0, 50).map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0), + waveIds: orderList.slice(0, 50).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0), + }); + + const warehouseId = Number(options.warehouseId) > 0 ? Number(options.warehouseId) : this.getCurrentWarehouseId(); + + const orderDeliveryModel = await this.getWaybillAsyncOrderDeliveryModel(warehouseId); + + if (!orderDeliveryModel || typeof orderDeliveryModel.findAll !== 'function') { + this.ctx.logger.error('[ExpressService.createWaybillCodePipeline] 分配前置条件失败-订单主表模型不可用', { + traceId, + warehouseId, + }); + throw new Error('订单主表模型未初始化'); + } + + // 【step1】先按订单ID和业务键筛选,找出已存在的快递记录,避免重复创建。 + // 先从 current 表查;若存在未覆盖的 order_id,再从 dispatch 表补查(配送中订单可能已迁移) + const inputOrderIds = orderList.map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0); + const currentOrders = await orderDeliveryModel.findAll({ + where: { + id: inputOrderIds, + warehouse_id: warehouseId, + step: { + [Op.in]: [ 1, 2, 3, 4 ], + }, + status: { + [Op.ne]: 'cancel', + }, + }, + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status', 'need_oms_waybill' ], + raw: true, + }); + + // 补查 dispatch 表:获取 current 表未覆盖的 order_id + const currentCoveredIds = new Set((Array.isArray(currentOrders) ? currentOrders : []).map(o => Number(o.id))); + const uncoveredIds = inputOrderIds.filter(id => !currentCoveredIds.has(id)); + let dispatchOrders = []; + if (uncoveredIds.length > 0) { + const dispatchModel = this.ctx.model && this.ctx.model.OrderDeliveryFactory + ? await this.ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId) + : null; + if (dispatchModel && typeof dispatchModel.findAll === 'function') { + dispatchOrders = await dispatchModel.findAll({ + where: { + id: uncoveredIds, + warehouse_id: warehouseId, + step: { + [Op.in]: [ 4 ], + }, + status: { + [Op.ne]: 'cancel', + }, + }, + attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status', 'lock_status', 'need_oms_waybill' ], + raw: true, + }); + } + } + + // 拦截订单跳过(除 none 外一律视为已拦截) + const mergedOrders = [ ...(Array.isArray(currentOrders) ? currentOrders : []), ...dispatchOrders ]; + const interceptedOrderIdSet = new Set(mergedOrders + .filter(order => isInterceptedOrderStatus(order && order.intercept_status)) + .map(order => Number(order && order.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)); + const skippedInterceptedOrderIds = Array.from(interceptedOrderIdSet); + const orders_arr = mergedOrders.filter(order => !interceptedOrderIdSet.has(Number(order && order.id || 0))); + if (skippedInterceptedOrderIds.length > 0) { + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过拦截订单', { + traceId, + warehouseId, + skippedInterceptedOrderIds, + }); + } + + // 锁定订单跳过(除 none 外一律视为已锁定,锁定期间不允许分配快递) + const lockedOrderIdSet = new Set(orders_arr + .filter(order => isLockedOrderStatus(order && order.lock_status)) + .map(order => Number(order && order.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)); + const skippedLockedOrderIds = Array.from(lockedOrderIdSet); + const activeOrders = orders_arr.filter(order => !lockedOrderIdSet.has(Number(order && order.id || 0))); + if (skippedLockedOrderIds.length > 0) { + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过锁定订单', { + traceId, + warehouseId, + skippedLockedOrderIds, + }); + } + + // 需要回 OMS 取号的订单分流:不参与本地分配快递,等外部 OMS 取号能力接入后单独处理。 + // need_oms_waybill 为订单级标记(仅 openapi 创建来源可能为 1),同一订单的所有 business_key 一并跳过。 + const needOmsWaybillOrderIdSet = new Set(activeOrders + .filter(order => Number(order && order.need_oms_waybill) === 1) + .map(order => Number(order && order.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)); + const skippedNeedOmsWaybillOrderIds = Array.from(needOmsWaybillOrderIdSet); + const allocatableOrders = activeOrders + .filter(order => !needOmsWaybillOrderIdSet.has(Number(order && order.id || 0))); + if (skippedNeedOmsWaybillOrderIds.length > 0) { + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过需要回 OMS 取号的订单', { + traceId, + warehouseId, + skippedNeedOmsWaybillOrderIds, + }); + } + + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', { + traceId, + warehouseId, + inputOrderCount: orderList.length, + currentCount: (Array.isArray(currentOrders) ? currentOrders : []).length, + dispatchCount: dispatchOrders.length, + matchedOrderCount: allocatableOrders.length, + skippedInterceptedOrderIds, + skippedLockedOrderIds, + skippedNeedOmsWaybillOrderIds, + }); + + // 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + let filteredOrdersArr = allocatableOrders; + if (orderExpressModel && allocatableOrders.length > 0) { + const orderIds = allocatableOrders.map(o => Number(o.id)).filter(id => id > 0); + const completedRows = await orderExpressModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + status: 1, + }, + attributes: [ 'order_id', 'business_key' ], + raw: true, + }); + const skipSet = new Set(); + for (const row of completedRows) { + skipSet.add(`${Number(row.order_id)}:${Number(row.business_key)}`); + } + if (skipSet.size > 0) { + const beforeCount = allocatableOrders.length; + filteredOrdersArr = allocatableOrders.filter(order => { + const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); + const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1; + if (businessKey === 1 && skipSet.has(`${Number(order.id)}:1`)) { + return false; + } + return true; + }); + if (filteredOrdersArr.length < beforeCount) { + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过已分配运单号(business_key=1)的订单', { + traceId, + skippedCount: beforeCount - filteredOrdersArr.length, + skippedOrderIds: allocatableOrders + .filter(order => { + const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); + const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1; + return businessKey === 1 && skipSet.has(`${Number(order.id)}:1`); + }) + .map(o => o.id), + }); + } + } + } + + if (filteredOrdersArr.length === 0) { + const noAllocatableByNeedOms = allocatableOrders.length === 0 && skippedNeedOmsWaybillOrderIds.length > 0; + const emptyMessage = noAllocatableByNeedOms + ? '订单需要回 OMS 取号,已跳过本地分配快递,等待外部 OMS 取号' + : '所有订单均已分配运单号,无需处理'; + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 无可处理订单', { + traceId, + needOmsWaybillOnly: noAllocatableByNeedOms, + skippedNeedOmsWaybillOrderIds, + }); + return { + message: emptyMessage, + skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, + skipped_need_oms_waybill_order_ids: skippedNeedOmsWaybillOrderIds, + }; + } + + // orders_arr和orderList合并:同一 order_id 在 orderList 中可能有多条(不同 business_key), + // 需要展开为多条 ordersWithExpress,不能用 find() 只取第一条 + const ordersWithExpress = []; + for (const order of filteredOrdersArr) { + const matchingExpresses = orderList.filter(express => Number(order.id) === Number(express.order_id)); + if (matchingExpresses.length > 0) { + for (const express of matchingExpresses) { + ordersWithExpress.push({ + ...order, + business_key: express.business_key || 1, + }); + } + } else { + // 兜底:orderList 中无对应记录,business_key 默认为 1 + ordersWithExpress.push({ + ...order, + business_key: 1, + }); + } + } + const platformList = await this.service.systems.platform.getPlatformList(true, true); + const printPlatformCodeMap = await this.loadWaybillPrintPlatformCodeMap(platformList); + const requestPlatformCodeMap = await this.loadWaybillAsyncRequestPlatformCodeMap(platformList); + const groupedOrders = this.groupWaybillOrdersByPlatformAndLogistics(ordersWithExpress, printPlatformCodeMap); + + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 平台物流分组结果', { + traceId, + groupedCount: groupedOrders.length, + }); + + // 【step2】按平台 + 快递编码分组,后续按组串行处理。 + for (const groupedOrder of groupedOrders) { + const matchedPlatform = platformList.find(platform => String(platform.code || '').trim().toLowerCase() === String(groupedOrder.options.sys_platform_code || '').trim().toLowerCase()); + const matchedPlatformWithRequestCode = matchedPlatform ? { + ...matchedPlatform, + request_platform_code: this.resolveWaybillAsyncRequestPlatformCode( + groupedOrder.options.sys_platform_code, + requestPlatformCodeMap + ) || String(matchedPlatform.request_platform_code || '').trim(), + } : null; + const batches = this.splitWaybillOrdersIntoBatches(groupedOrder.orders); + const expressInterfacePlatformCode = String( + groupedOrder.options.print_platform_code || '' + ).trim(); + const listByWarehousePlatformCode = expressInterfacePlatformCode + ? await this.service.systems.setting.expressInterface.listByWarehousePlatformCode({ + warehouseId, + platform_code: expressInterfacePlatformCode, + }) + : { data: [] }; + const expressInterface = this.pickWaybillExpressInterface( + listByWarehousePlatformCode && listByWarehousePlatformCode.data, + groupedOrder, + matchedPlatformWithRequestCode + ); + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 分组前置条件检查', { + traceId, + warehouseId, + storeId: groupedOrder.options.store_id || 0, + sysPlatformCode: groupedOrder.options.sys_platform_code, + printPlatformCode: groupedOrder.options.print_platform_code, + expressInterfacePlatformCode, + logisticsCode: groupedOrder.options.logistics_code, + sysLogisticsCode: groupedOrder.options.sys_logistics_code, + weightType: groupedOrder.options.weight_type, + matchedPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.code, + requestPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.request_platform_code, + hasExpressInterface: Boolean(expressInterface), + }); + + // 发件人相关字段统一走接口配置,货主配置仅用于打印链路。 + const expressInterfaceConfig = expressInterface ? { + ...expressInterface, + } : null; + + // 各批次并发执行:同组内不同批次的订单相互独立,无重叠,可安全并发 + if (pipelineOptions.awaitTasks) { + await Promise.all(batches.map(batch => + this.asyncTask(batch, { + ...groupedOrder.options, + trace_id: traceId, + warehouse_id: warehouseId, + }, matchedPlatformWithRequestCode, expressInterfaceConfig) + )); + } else { + // 非等待模式:fire-and-forget,所有批次同时触发 + for (const batch of batches) { + this.asyncTask(batch, { + ...groupedOrder.options, + trace_id: traceId, + warehouse_id: warehouseId, + }, matchedPlatformWithRequestCode, expressInterfaceConfig); + } + } + } + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 流水线任务提交完成', { + traceId, + groupedCount: groupedOrders.length, + }); + return { + message: '分配快递任务已提交', + skipped_intercepted_order_ids: skippedInterceptedOrderIds, + skipped_locked_order_ids: skippedLockedOrderIds, + skipped_need_oms_waybill_order_ids: skippedNeedOmsWaybillOrderIds, + }; + } + /** + * 异步执行订单快递分配任务。错误订单转异常,并记录失败订单列表。 + * 【已使用】 + * @param {*} batch + * @param {*} sysPlatformCode + * @param {*} logisticsCode + * @param {*} matchedPlatform + * @param {*} listByWarehousePlatformCode + */ + + async asyncTask(batch, options, matchedPlatform, listByWarehousePlatformCode) { + const traceId = this.buildWaybillTraceId(options || {}, 'asyncTask'); + this.ctx.logger.info('[ExpressService.asyncTask] 任务入口', { + traceId, + warehouseId: options && options.warehouse_id, + sysPlatformCode: options && options.sys_platform_code, + logisticsCode: options && options.logistics_code, + orderIds: (Array.isArray(batch) ? batch : []).map(order => Number(order && (order.id || order.order_id))).filter(orderId => Number.isFinite(orderId) && orderId > 0), + waveIds: (Array.isArray(batch) ? batch : []).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0), + }); + try { + if (!listByWarehousePlatformCode) { + this.ctx.logger.warn('[ExpressService.asyncTask] 分配前置条件失败-快递接口配置缺失', { + traceId, + sysPlatformCode: options && options.sys_platform_code, + logisticsCode: options && options.logistics_code, + }); + throw new Error(`当前订单平台【${options.sys_platform_name}】,快递【${options.logistics_name}】,未配置有效的快递接口`); + } + if (!matchedPlatform) { + this.ctx.logger.warn('[ExpressService.asyncTask] 分配前置条件失败-平台配置缺失', { + traceId, + sysPlatformCode: options && options.sys_platform_code, + logisticsCode: options && options.logistics_code, + }); + throw new Error(`未找到订单平台【${options.sys_platform_name}】的有效平台配置`); + } + this.ctx.logger.info('[ExpressService.asyncTask] 调用 createWaybillCode 前', { + traceId, + batchCount: Array.isArray(batch) ? batch.length : 0, + }); + await this.createWaybillCode(batch, matchedPlatform, { + ...(listByWarehousePlatformCode || {}), + trace_id: traceId, + }); + this.ctx.logger.info('[ExpressService.asyncTask] 调用 createWaybillCode 后', { + traceId, + batchCount: Array.isArray(batch) ? batch.length : 0, + }); + } catch (error) { + console.error('异步任务执行失败:', error.message); + this.ctx.logger.error('[ExpressService.asyncTask] 异步任务执行异常', { + traceId, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + const errorMessage = error && error.message ? String(error.message) : String(error); + + await this.handleWaybillAllocateFailure( + batch.map(order => ({ + order_id: order && (order.id || order.order_id), + business_key: order && order.business_key, + })), + { + warehouse_id: options && options.warehouse_id, + sys_platform_code: options && options.sys_platform_code, + }, + errorMessage + ); + } + } + /** + * 处理订单快递记录。 + * 先按订单ID和业务键筛选 wms_order_express,再排除已存在且状态不为 0 的记录, + * 对可重试记录重置 retry_count,并为缺失记录补插状态为 0 的快递记录。 + *【已使用】 + * @param {Array} orders 订单与业务键列表,business_key 可为单值或数组。 + * @param {number} orders[].order_id 订单ID。 + * @param {number|Array} orders[].business_key 业务键。 + * @return {Promise} 处理后的订单列表与运单号列表。 + */ + /** + * 创建运单编码并在事务后触发异步后处理。 + * + * 事务成功后,如果异步后处理失败,则回补本次事务中已经增加的 + * `print_quantity_locked`,避免锁定量长期偏高。 + * + * @param {Array} orders 运单创建入参。 + * @param {Object} [matchedPlatform={}] 平台匹配结果。 + * @param {Object} [listByWarehousePlatformCode={}] 按仓库和平台分组的接口信息。 + * @return {Promise} 创建结果。 + */ + async createWaybillCode(orders, matchedPlatform, listByWarehousePlatformCode) { + const traceId = this.buildWaybillTraceId({ + trace_id: listByWarehousePlatformCode && listByWarehousePlatformCode.trace_id, + traceId: listByWarehousePlatformCode && listByWarehousePlatformCode.traceId, + }, 'createWaybillCode'); + this.ctx.logger.info('[ExpressService.createWaybillCode] 入口请求', { + traceId, + orderCount: Array.isArray(orders) ? orders.length : 0, + orderIds: (Array.isArray(orders) ? orders : []).slice(0, 50).map(order => Number(order && (order.id || order.order_id))).filter(orderId => Number.isFinite(orderId) && orderId > 0), + platformCode: matchedPlatform && matchedPlatform.code, + requestPlatformCode: matchedPlatform && matchedPlatform.request_platform_code, + routePlatformCode: this.resolveWaybillAsyncDispatchPlatformCode(matchedPlatform), + defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface, + warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id, + }); + const { app, ctx } = this; + const { Op } = app.Sequelize; + const orderExpressModel = ctx.model && ctx.model.OrderExpress; + const currentWarehouseId = Number( + (listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id) + || this.getCurrentWarehouseId() + ); + if (!orderExpressModel + || typeof orderExpressModel.findAll !== 'function' + || typeof orderExpressModel.update !== 'function' + || typeof orderExpressModel.bulkCreate !== 'function') { + throw new Error('订单快递模型未初始化'); + } + + const normalizedOrders = await this.normalizeWaybillCreateOrders(orders); + + if (normalizedOrders.length === 0) { + return { + orders: [], + waybill_codes: [], + }; + } + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + const storeWarehouseModel = ctx.model && ctx.model.StoreWarehouse; + if (!currentWarehouseId) { + throw new Error('当前仓库ID不能为空'); + } + + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + throw new Error('订单主表模型未初始化'); + } + + if (!storeWarehouseModel || typeof storeWarehouseModel.findAll !== 'function' || typeof storeWarehouseModel.update !== 'function') { + throw new Error('签约关系模型未初始化'); + } + const maxAttempts = 3; + /** + * 执行运单创建事务,并在死锁或锁等待超时时按次数重试。 + * @param {number} attempt 当前尝试次数。 + * @return {Promise} 运单创建事务结果。 + */ + const executeCreateWaybillTransactionWithRetry = async attempt => { + try { + // 【step6】开启事务,确保余额锁定、异常回写和快递记录写入保持原子性。 + return await app.model.transaction(async transaction => { + // 【step6】事务内先加载订单主表快照,后续所有判断都基于同一批视图。 + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(currentWarehouseId); + const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory; + const orderItemsModel = orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function' + ? await orderItemsFactory.getCurrentModel(currentWarehouseId) + : null; + if (!orderDeliveryModel + || typeof orderDeliveryModel.findAll !== 'function' + || typeof orderDeliveryModel.update !== 'function') { + throw new Error('订单主表模型未初始化'); + } + + const orderDeliveryInclude = []; + if (orderItemsModel) { + orderDeliveryInclude.push({ + model: orderItemsModel, + as: 'orderItems', + attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'source_order_code' ], + required: false, + }); + } + + const orderDeliveryRows = await orderDeliveryModel.findAll({ + // 保留后处理 order_list 需要的最小字段集,同时控制在 15 个字段以内。 + // warehouse_id 由当前仓库 ID 兜底,因此不额外查询。 + attributes: WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES, + where: { + id: { + [Op.in]: normalizedOrders.map(order => order.order_id), + }, + }, + include: orderDeliveryInclude, + transaction, + }); + + // 补查 dispatch 表:配送中订单可能已迁移,current 表未覆盖的从 dispatch 补齐 + const currentCoveredOrderIds = new Set( + (Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []).map(row => Number(row && row.id)) + ); + const uncoveredOrderIds = normalizedOrders + .map(o => o.order_id) + .filter(id => !currentCoveredOrderIds.has(id)); + let dispatchOrderDeliveryRows = []; + if (uncoveredOrderIds.length > 0) { + ctx.logger.info('[ExpressService.createWaybillCode] dispatch 补查 uncoveredOrderIds=%s', + [ ...new Set(uncoveredOrderIds) ].join(',')); + const dispatchModel = orderDeliveryFactory && typeof orderDeliveryFactory.getDispatchModel === 'function' + ? await orderDeliveryFactory.getDispatchModel(currentWarehouseId) + : null; + if (dispatchModel && typeof dispatchModel.findAll === 'function') { + // dispatch 表 items 关联可能不同,去掉 include 避免关联查询报错 + dispatchOrderDeliveryRows = await dispatchModel.findAll({ + attributes: WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES, + where: { + id: { [Op.in]: uncoveredOrderIds }, + }, + transaction, + }); + ctx.logger.info('[ExpressService.createWaybillCode] dispatch 补查结果 count=%d', + dispatchOrderDeliveryRows.length); + + // 补查 dispatch 表的商品明细(物流 API 需要 items 信息) + if (dispatchOrderDeliveryRows.length > 0) { + const dispatchItemsFactory = ctx.model && ctx.model.OrderItemsFactory; + const dispatchItemsModel = dispatchItemsFactory && typeof dispatchItemsFactory.getDispatchModel === 'function' + ? await dispatchItemsFactory.getDispatchModel(currentWarehouseId) + : null; + if (dispatchItemsModel && typeof dispatchItemsModel.findAll === 'function') { + const dispatchOrderIds = dispatchOrderDeliveryRows.map(row => Number(row.id)).filter(id => id > 0); + const dispatchItems = await dispatchItemsModel.findAll({ + where: { order_id: { [Op.in]: dispatchOrderIds } }, + attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'source_order_code' ], + raw: true, + transaction, + }); + // 将 items 以 Sequelize include 格式附加到 dispatch 行上 + if (Array.isArray(dispatchItems) && dispatchItems.length > 0) { + const itemsByOrderId = new Map(); + for (const item of dispatchItems) { + const oid = Number(item.order_id); + if (!itemsByOrderId.has(oid)) itemsByOrderId.set(oid, []); + itemsByOrderId.get(oid).push(item); + } + for (const row of dispatchOrderDeliveryRows) { + const oid = Number(row.id); + row.orderItems = itemsByOrderId.get(oid) || []; + } + } + } + } + } else { + ctx.logger.warn('[ExpressService.createWaybillCode] dispatch 模型不可用'); + } + } + + const allOrderDeliveryRows = [ ...(Array.isArray(orderDeliveryRows) ? orderDeliveryRows : []), ...dispatchOrderDeliveryRows ]; + const orderDeliveryMap = this.buildWaybillOrderDeliveryMap(allOrderDeliveryRows); + + const existingCompletedRows = await orderExpressModel.findAll({ + where: { + warehouse_id: currentWarehouseId, + [Op.or]: normalizedOrders.map(order => ({ + order_id: order.order_id, + business_key: order.business_key, + })), + }, + attributes: [ 'order_id', 'business_key', 'status' ], + raw: true, + transaction, + }); + + const completedOrderKeySet = new Set(); + for (const row of Array.isArray(existingCompletedRows) ? existingCompletedRows : []) { + const orderId = Number(row && row.order_id); + const businessKey = Number(row && row.business_key); + const status = Number(row && row.status); + if (Number.isFinite(orderId) && orderId > 0 && Number.isInteger(businessKey) && status === 1) { + completedOrderKeySet.add(`${orderId}:${businessKey}`); + } + } + + const pendingOrders = normalizedOrders.filter(order => !completedOrderKeySet.has(`${order.order_id}:${order.business_key}`)); + + if (pendingOrders.length === 0) { + return { + orders: [], + waybill_codes: [], + }; + } + + // 跳过已取消订单:已取消订单不允许取号,且不标记异常、不写失败日志。 + const cancelledOrderIdSet = new Set( + allOrderDeliveryRows + .filter(row => String(row.status || '').trim() === 'cancel') + .map(row => Number(row.id)) + .filter(id => Number.isFinite(id) && id > 0) + ); + let effectivePendingOrders = pendingOrders; + if (cancelledOrderIdSet.size > 0) { + effectivePendingOrders = pendingOrders.filter(order => !cancelledOrderIdSet.has(Number(order.order_id))); + ctx.logger.info('[ExpressService.createWaybillCode] 跳过已取消订单取号', { + traceId, + skippedOrderIds: Array.from(cancelledOrderIdSet), + }); + } + + if (effectivePendingOrders.length === 0) { + return { + orders: [], + waybill_codes: [], + }; + } + + const { + relationGroupMap, + missingOrderIds, + } = this.buildWaybillCreateRelationGroups(effectivePendingOrders, allOrderDeliveryRows, currentWarehouseId); + + const relationWhereList = Array.from(relationGroupMap.values()).map(group => ({ + store_id: group.store_id, + warehouse_id: group.warehouse_id, + })); + + const relationRows = relationWhereList.length > 0 + ? await storeWarehouseModel.findAll({ + attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked', 'policy_config' ], + where: { + [Op.or]: relationWhereList, + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }) + : []; + + const relationMap = new Map(); + for (const relation of Array.isArray(relationRows) ? relationRows : []) { + const relationKey = `${Number(relation.store_id || 0)}:${Number(relation.warehouse_id || 0)}`; + if (relationKey !== '0:0') { + relationMap.set(relationKey, relation); + } + } + + const { + successOrderKeySet, + failedOrdersByReason, + balanceWarnings, + } = await this.collectWaybillRelationProcessingState(relationGroupMap, relationMap); + + if (missingOrderIds.length > 0) { + const exceptionText = '订单不存在或不属于当前仓库'; + failedOrdersByReason.set(exceptionText, (failedOrdersByReason.get(exceptionText) || []).concat(missingOrderIds)); + } + + // 【step5】事务内统一回写失败订单异常,避免成功与失败状态分离。 + await this.writeWaybillOrderExceptions(orderDeliveryModel, failedOrdersByReason, transaction); + + // 补写 dispatch 表 order_flag:dispatch 订单的异常信息需单独写(current 表写不到) + if (dispatchOrderDeliveryRows.length > 0 && failedOrdersByReason.size > 0) { + try { + await this.writeDispatchOrderFlags(dispatchOrderDeliveryRows, failedOrdersByReason, transaction); + } catch (dispatchFlagErr) { + ctx.logger.warn('[ExpressService.createWaybillCode] 补写 dispatch order_flag 失败: %s', + dispatchFlagErr && dispatchFlagErr.message ? dispatchFlagErr.message : dispatchFlagErr); + } + } + + if (balanceWarnings.length > 0) { + ctx.logger.warn('[ExpressService.createWaybillCode] 余额不足但允许超额分配: %s', balanceWarnings.join(';')); + } + + const successOrders = effectivePendingOrders.filter(order => successOrderKeySet.has(`${order.order_id}:${order.business_key}`)); + const existingRows = await orderExpressModel.findAll({ + where: { + [Op.or]: successOrders.map(order => ({ + order_id: order.order_id, + business_key: order.business_key, + warehouse_id: currentWarehouseId, + })), + }, + attributes: [ 'id', 'order_id', 'business_key', 'status', 'retry_count', 'warehouse_id' ], + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const existingMap = new Map(); + const retryIds = []; + for (const row of Array.isArray(existingRows) ? existingRows : []) { + const orderId = Number(row && row.order_id); + const businessKey = Number(row && row.business_key); + if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isInteger(businessKey)) { + continue; + } + + const orderKey = `${orderId}:${businessKey}`; + existingMap.set(orderKey, row); + + // 过滤 status != 0 的已存在记录。 + if (Number(row && row.status) === 0) { + retryIds.push(row.id); + } + } + + // 【step6】先重置可重试记录,再补插缺失记录。 + const retryableIds = Array.from(new Set(retryIds.filter(id => Number.isFinite(Number(id)) && Number(id) > 0))); + if (retryableIds.length > 0) { + await orderExpressModel.update({ + retry_count: 0, + }, { + where: { + id: { + [Op.in]: retryableIds, + }, + }, + transaction, + }); + } + + const successOrdersWithDelivery = successOrders + .filter(order => { + const existingRow = existingMap.get(`${order.order_id}:${order.business_key}`); + return !existingRow || Number(existingRow.status) === 0; + }) + .map(order => ({ + ...order, + order_delivery: orderDeliveryMap.get(order.order_id) || null, + })); + + if (successOrdersWithDelivery.length > 0) { + const successOrderIds = Array.from(new Set(successOrdersWithDelivery + .map(order => Number(order.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + + if (successOrderIds.length > 0) { + // 仅对非配送中(step != 4)的订单更新 step 为 2;配送中订单保持 step 不变 + const step4OrderIdSet = new Set(); + for (const orderId of successOrderIds) { + const orderRow = orderDeliveryMap.get(orderId); + if (orderRow && Number(orderRow.step) === 4) { + step4OrderIdSet.add(orderId); + } + } + const stepUpdatableIds = successOrderIds.filter(id => !step4OrderIdSet.has(id)); + if (stepUpdatableIds.length > 0) { + await orderDeliveryModel.update({ + step: 2, + updated_at: new Date(), + }, { + where: { + id: { + [Op.in]: stepUpdatableIds, + }, + status: { + [Op.ne]: 'cancel', + }, + }, + transaction, + }); + } + } + } + + if (successOrdersWithDelivery.length === 0) { + return { + orders: [], + waybill_codes: [], + }; + } + + // 【step6】组装待插入记录,保持已存在且非 0 状态的记录不被覆盖。 + const rowsToCreate = []; + for (const order of successOrders) { + const orderKey = `${order.order_id}:${order.business_key}`; + const existingRow = existingMap.get(orderKey); + if (existingRow) { + const status = Number(existingRow.status); + if (status !== 0) { + continue; + } + + continue; + } + + ctx.logger.info('[DEBUG] rowsToCreate order', JSON.stringify({ + order_id: order.order_id, + store_id: order.store_id, + has_delivery: !!order.order_delivery, + delivery_store_id: order.order_delivery && order.order_delivery.store_id, + delivery_doc: order.order_delivery && order.order_delivery.delivery_order_code, + })); + + rowsToCreate.push({ + order_id: order.order_id, + business_key: order.business_key, + status: 0, + retry_count: 0, + warehouse_id: currentWarehouseId, + store_id: order.store_id || null, + logistics_code: (listByWarehousePlatformCode && listByWarehousePlatformCode.sys_express_code) || '', + delivery_order_code: (orderDeliveryMap.get(order.order_id) && orderDeliveryMap.get(order.order_id).delivery_order_code) || null, + source_order_codes: (orderDeliveryMap.get(order.order_id) && orderDeliveryMap.get(order.order_id).source_order_codes) || null, + }); + } + + const relationLockMap = this.buildWaybillRelationLockMap(successOrders, orderDeliveryMap, existingMap); + if (relationLockMap.size > 0) { + await this.lockWaybillRelationBalance(relationLockMap, relationMap, storeWarehouseModel, transaction); + } + + // 【step6】批量插入新快递记录后,事务提交。 + if (rowsToCreate.length > 0) { + await orderExpressModel.bulkCreate(rowsToCreate, { + transaction, + }); + } + + return { + orders: successOrdersWithDelivery, + waybill_codes: [], + }; + }); + } catch (err) { + const errorCode = err && err.parent && err.parent.code; + const errorMessage = String((err && err.message) || (err && err.parent && err.parent.message) || ''); + const isRetryableDeadlock = errorCode === 'ER_LOCK_DEADLOCK' + || errorCode === 'ER_LOCK_WAIT_TIMEOUT' + || errorMessage.includes('Deadlock found when trying to get lock'); + + if (!isRetryableDeadlock || attempt >= maxAttempts) { + throw err; + } + + ctx.logger.warn(`[ExpressService.createWaybillCode] deadlock retry attempt=${attempt} maxAttempts=${maxAttempts} code=${errorCode || 'UNKNOWN'} message=${errorMessage}`); + await new Promise(resolve => setTimeout(resolve, 50 * attempt)); + return executeCreateWaybillTransactionWithRetry(attempt + 1); + } + }; + + this.ctx.logger.info('[ExpressService.createWaybillCode] DB 回写事务前', { + traceId, + orderCount: normalizedOrders.length, + }); + const createWaybillResult = await executeCreateWaybillTransactionWithRetry(1); + + this.ctx.logger.info('[ExpressService.createWaybillCode] DB 回写事务后', { + traceId, + successOrderCount: Array.isArray(createWaybillResult && createWaybillResult.orders) + ? createWaybillResult.orders.length + : 0, + }); + + try { + const dispatchPlatformCode = this.resolveWaybillAsyncDispatchPlatformCode(matchedPlatform); + if (Array.isArray(createWaybillResult.orders) + && createWaybillResult.orders.length > 0 + && matchedPlatform + && dispatchPlatformCode) { + try { + this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用前', { + traceId, + platformInterface: dispatchPlatformCode, + orderCount: createWaybillResult.orders.length, + }); + await this.dispatchWaybillAsyncPlatform(dispatchPlatformCode, { + matchedPlatform, + listByWarehousePlatformCode, + orders: createWaybillResult.orders, + trace_id: traceId, + }); + this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用后', { + traceId, + platformInterface: dispatchPlatformCode, + }); + } catch (error) { + throw error; + } + } + } catch (error) { + const restoreRelationMap = new Map(); + for (const order of Array.isArray(createWaybillResult.orders) ? createWaybillResult.orders : []) { + const orderDelivery = order && order.order_delivery; + const storeId = Number(order && order.store_id) || Number(orderDelivery && orderDelivery.store_id) || 0; + const warehouseId = Number(order && order.warehouse_id) || Number(orderDelivery && orderDelivery.warehouse_id) || 0; + if (!Number.isFinite(storeId) || storeId <= 0 || !Number.isFinite(warehouseId) || warehouseId <= 0) { + continue; + } + + const relationKey = `${storeId}:${warehouseId}`; + const currentRelation = restoreRelationMap.get(relationKey) || { + store_id: storeId, + warehouse_id: warehouseId, + success_count: 0, + }; + currentRelation.success_count += 1; + restoreRelationMap.set(relationKey, currentRelation); + } + console.error('运单后处理失败,准备回补锁定量:', error.message, 'restoreRelationList', Array.from(restoreRelationMap.values())); + this.ctx.logger.error('[ExpressService.createWaybillCode] 平台后处理异常,准备回补锁定量', { + traceId, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + restoreRelationList: Array.from(restoreRelationMap.values()), + }); + if (restoreRelationMap.size > 0) { + const restoreRelationList = Array.from(restoreRelationMap.values()); + const restoreRows = await storeWarehouseModel.findAll({ + attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity_locked' ], + where: { + [Op.or]: restoreRelationList.map(item => ({ + store_id: item.store_id, + warehouse_id: item.warehouse_id, + })), + }, + raw: true, + }); + + const restoreRowMap = new Map(); + for (const row of Array.isArray(restoreRows) ? restoreRows : []) { + const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`; + if (relationKey !== '0:0') { + restoreRowMap.set(relationKey, row); + } + } + + const canIncrementLockedQuantity = typeof storeWarehouseModel.increment === 'function'; + + for (const item of restoreRelationList) { + const relationKey = `${item.store_id}:${item.warehouse_id}`; + const row = restoreRowMap.get(relationKey); + if (!row) { + continue; + } + + const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0)); + const restoreQuantity = Math.min(currentLockedQuantity, item.success_count); + if (restoreQuantity <= 0) { + continue; + } + + if (canIncrementLockedQuantity) { + await storeWarehouseModel.increment('print_quantity_locked', { + by: -restoreQuantity, + where: { + id: row.id, + }, + }); + continue; + } + + await storeWarehouseModel.update({ + print_quantity_locked: currentLockedQuantity - restoreQuantity, + }, { + where: { + id: row.id, + }, + }); + } + } + + throw error; + } + + this.ctx.logger.info('[ExpressService.createWaybillCode] 处理完成', { + traceId, + successOrderCount: Array.isArray(createWaybillResult && createWaybillResult.orders) + ? createWaybillResult.orders.length + : 0, + }); + + return createWaybillResult; + } + +} + +module.exports = ExpressService; diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js new file mode 100644 index 0000000..74b6676 --- /dev/null +++ b/app/service/systems/express_platform.js @@ -0,0 +1,3766 @@ +'use strict'; + +const MainService = require('../main'); +const PddClient = require('../../lib/pdd_client'); + +const crypto = require('node:crypto'); + +const DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router'; +const DEFAULT_TB_ROUTER_URL = 'https://eco.taobao.com/router/rest'; + +/** OMS 取号方法名(OMS 侧 openapi method)。 */ +const OMS_WAYBILL_EVENT = 'deliveryorder.getwaybill'; + +/** OMS 单次取号上限(printinfo 单张可达数百 KB,文档建议不超过 20 单)。 */ +const OMS_WAYBILL_MAX_BATCH_SIZE = 20; + +/** + * OMS 逐单失败原因中「不可重试」的关键词(对应 OMS 文档 4.4)。 + * 命中即认为重试无意义,避免反复打平台。 + */ +const OMS_WAYBILL_NON_RETRYABLE_KEYWORDS = Object.freeze([ + '缺少发货单号', + '缺少快递编码', + '未找到发货单', + '不属于当前 app_key', + '已取消', + '已作废', + '已归档', + '订单已配送', + '订单已完成', + '缺少来源平台', + '未关联店铺', + '未关联外部打单账号', + '外部打单账号或平台配置不存在', + '未绑定到快递接口', + '不存在(系统快递编码', + '已停用', + '未开启回平台取号', + '真实取号已关闭', + '未找到订单', + '面单余额不足', + '已发货或已终结', +]); + +/** + * 上游未返回时必须保留已有值的运单报文字段。 + * + * OMS 回源取号只透传 signature/encryptprintinfo/ver,不返回 printinfo/encryptedtoken, + * 若按 null 写入会把本地取号已落库的有效报文冲掉,故这类字段统一改为「有值才覆盖」。 + */ +const ORDER_EXPRESS_UPSTREAM_OPTIONAL_FIELDS = Object.freeze([ + 'printinfo', + 'signature', + 'encryptprintinfo', + 'encryptedtoken', + 'ver', +]); + +/** OMS 取号请求/返回报文缓存 TTL(秒):覆盖一个工作日,便于事后核对报文格式。 */ +const OMS_WAYBILL_PAYLOAD_CACHE_TTL = 24 * 60 * 60; + +/** OMS 取号报文缓存单键上限(字节):超出时按字段脱敏,避免 Redis 单键过大。 */ +const OMS_WAYBILL_PAYLOAD_CACHE_MAX_BYTES = 256 * 1024; + +/** + * 报文超限时按字段名脱敏的密文/大字段。 + * 只截断取值,保留字段名与总长度,保证缓存里仍能看清报文结构。 + */ +const OMS_WAYBILL_PAYLOAD_HEAVY_FIELDS = Object.freeze([ + 'printinfo', + 'printdata', + 'encryptprintinfo', + 'encryptedtoken', + 'signature', +]); + +/** 大字段脱敏后保留的字符数(用于人工核对字段内容前缀)。 */ +const OMS_WAYBILL_PAYLOAD_HEAVY_FIELD_KEEP_CHARS = 64; + +/** OMS 取号报文缓存键前缀。 */ +const OMS_WAYBILL_PAYLOAD_CACHE_KEY_PREFIX = 'oms:waybill'; + +/** + * 将任意值标准化为数组。 + * + * @param {*} value 原始值。 + * @return {Array} 标准化后的数组。 + */ +function normalizeArray(value) { + return Array.isArray(value) ? value : []; +} + +/** + * 将对象包裹的集合字段标准化为数组。 + * + * @param {*} value 原始集合值。 + * @param {Array} [nestedKeys=[]] 对象包裹时的候选子字段名。 + * @return {Array} 标准化后的数组。 + */ +function normalizeWrappedArray(value, nestedKeys = []) { + if (Array.isArray(value)) { + return value; + } + + if (!value || typeof value !== 'object') { + return []; + } + + for (const nestedKey of normalizeArray(nestedKeys)) { + if (!nestedKey || !Object.prototype.hasOwnProperty.call(value, nestedKey)) { + continue; + } + + const nestedValue = value[nestedKey]; + if (Array.isArray(nestedValue)) { + return nestedValue; + } + + if (nestedValue !== null && nestedValue !== undefined) { + return [ nestedValue ]; + } + } + + return Object.keys(value).length > 0 ? [ value ] : []; +} + +/** + * 按候选来源顺序提取首个非空集合。 + * + * @param {Array<*>} values 候选来源列表。 + * @param {Array} [nestedKeys=[]] 对象包裹时的候选子字段名。 + * @return {Array} 首个非空数组。 + */ +function normalizeFirstWrappedArray(values, nestedKeys = []) { + for (const value of normalizeArray(values)) { + const normalized = normalizeWrappedArray(value, nestedKeys); + if (normalized.length > 0) { + return normalized; + } + } + + return []; +} + +/** + * 校验菜鸟电子面单模板地址是否合法。 + * + * 仅允许下发 `http` 或 `https` 协议的完整 URL,非法值直接视为不可用。 + * + * @param {*} templateUrl 待校验的模板地址。 + * @return {boolean} 是否为合法模板地址。 + */ +function isValidCainiaoTemplateUrl(templateUrl) { + const normalizedTemplateUrl = String(templateUrl || '').trim(); + + if (!normalizedTemplateUrl) { + return false; + } + + try { + const parsedTemplateUrl = new URL(normalizedTemplateUrl); + return parsedTemplateUrl.protocol === 'http:' || parsedTemplateUrl.protocol === 'https:'; + } catch { + return false; + } +} + +const DEFAULT_CAINIAO_TEMPLATE_URL = 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=288948'; + +/** + * 将仓库ID/订单ID/业务键三段标识打包为 64 位无符号整数(Uint64)。 + * + * 位宽分配("不够的补位"由左移自动补 0 完成): + * - warehouse_id:高 24 bit(hex 6 位,0x000000 ~ 0xFFFFFF) + * - order_id :中 32 bit(hex 8 位,0x00000000 ~ 0xFFFFFFFF) + * - business_key:低 8 bit (hex 2 位,0x00 ~ 0xFF) + * 合计 64 bit,拼出的 hex 固定 16 位(不足高位补 0)。 + * + * 例:f425c_3948e_1 → hex 补位 0f425c0003948e01 → 1099542414161645057 + * + * 纯函数(幂等):不含时间/随机因素,相同入参必然输出相同 Uint64,可安全重试。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {number|string} orderId 订单ID。 + * @param {number|string} businessKey 业务键(1=主单号,>1=子单号)。 + * @return {string} Uint64 的十进制字符串(超过 JS 安全整数 2^53,必须用字符串形式传输/序列化)。 + */ +/* eslint-disable no-bitwise -- Uint64 位打包/拆解必须使用位运算 */ +function toUint64(warehouseId, orderId, businessKey) { + const wh = BigInt(Number(warehouseId) || 0); + const oid = BigInt(Number(orderId) || 0); + const bk = BigInt(Number(businessKey) || 0); + if (wh < 0n || wh > 0xFFFFFFn) throw new Error(`toUint64: warehouse_id 超出 24 位范围: ${warehouseId}`); + if (oid < 0n || oid > 0xFFFFFFFFn) throw new Error(`toUint64: order_id 超出 32 位范围: ${orderId}`); + if (bk < 0n || bk > 0xFFn) throw new Error(`toUint64: business_key 超出 8 位范围: ${businessKey}`); + return ((wh << 40n) | (oid << 8n) | bk).toString(); +} + +/** + * 将 Uint64 反向拆解为仓库ID/订单ID/业务键(toUint64 的逆运算)。 + * + * @param {string|number|bigint} value Uint64 值(十进制字符串/数字/BigInt 均可)。 + * @return {{ warehouseId: number, orderId: number, businessKey: number }} 拆解结果。 + */ +function fromUint64(value) { + const v = BigInt(value); + if (v < 0n || v > 0xFFFFFFFFFFFFFFFFn) throw new Error(`fromUint64: 超出 64 位范围: ${value}`); + return { + warehouseId: Number(v >> 40n), + orderId: Number((v >> 8n) & 0xFFFFFFFFn), + businessKey: Number(v & 0xFFn), + }; +} +/* eslint-enable no-bitwise */ + +/** + * 快递平台服务类。 + * + * 当前仅保留平台方法出口,后续接入真实平台实现时再补充具体调用逻辑。 + * 这里的 `data` 统一与上游 `app/service/systems/express.js` 中 + * `buildWaybillAsyncBizcontentSkeleton` / `buildWaybillAsyncOrderListItem` + * 生成的结构对齐,完整形状如下: + * + * ```js + * { + * bizcontent: { + * platform_code: string, + * express_platform_code: string, + * store_id: number, + * warehouse_id: number, + * order_list: [ + * { + * order_id: number, + * business_key: number, + * sys_platform_code: string, + * logistics_code: string, + * express_platform_code: string, + * route_info: { + * source_platform_code: string, + * source_platform_name: string, + * sys_platform_code: string, + * sys_platform_name: string, + * logistics_code: string, + * logistics_name: string, + * sys_logistics_code: string, + * sys_logistics_name: string, + * express_code: string, + * logistics_area_code: string, + * }, + * order_info: { + * delivery_order_code: string, + * order_type: string, + * status: string, + * step: number, + * order_flag: string, + * from_key: string, + * create_at: string, + * place_order_time: string, + * pay_time: string, + * operate_time: string, + * delivery_time: string, + * }, + * receiver_info: { + * name: string, + * tel: string, + * mobile: string, + * email: string, + * country_code: string, + * province: string, + * city: string, + * area: string, + * town: string, + * detail_address: string, + * zip_code: string, + * }, + * settlement_info: { + * total_amount: number, + * item_amount: number, + * discount_amount: number, + * freight: number, + * ar_amount: number, + * got_amount: number, + * }, + * items_summary: { + * items: Array, + * items_count: number, + * items_total: number, + * items_weight: number, + * }, + * }, + * ], + * platform_payload: {}, + * }, + * } + * ``` + * + * @typedef {Object} ExpressPlatformData + * @property {ExpressPlatformBizcontent} bizcontent 顶层业务载荷对象。 + * + * @typedef {Object} ExpressPlatformBizcontent + * @property {string} platform_code 平台编码。 + * @property {string} express_platform_code 物流平台编码。 + * @property {number} store_id 店铺 ID。 + * @property {number} warehouse_id 仓库 ID。 + * @property {Array} order_list 订单列表。 + * @property {Object} platform_payload 平台专属载荷占位对象。 + * + * @typedef {Object} ExpressPlatformOrderItem + * @property {number} order_id 订单 ID。 + * @property {number} business_key 业务主键。 + * @property {string} sys_platform_code 系统平台编码。 + * @property {string} logistics_code 物流编码。 + * @property {string} express_platform_code 订单对应的物流平台编码。 + * @property {ExpressPlatformRouteInfo} route_info 路由信息块。 + * @property {ExpressPlatformOrderInfo} order_info 订单信息块。 + * @property {ExpressPlatformReceiverInfo} receiver_info 收件人信息块。 + * @property {ExpressPlatformSettlementInfo} settlement_info 结算信息块。 + * @property {ExpressPlatformItemsSummary} items_summary 商品汇总信息块。 + * + * @typedef {Object} ExpressPlatformRouteInfo + * @property {string} source_platform_code 来源平台编码。 + * @property {string} source_platform_name 来源平台名称。 + * @property {string} sys_platform_code 系统平台编码。 + * @property {string} sys_platform_name 系统平台名称。 + * @property {string} logistics_code 物流编码。 + * @property {string} logistics_name 物流名称。 + * @property {string} sys_logistics_code 系统物流编码。 + * @property {string} sys_logistics_name 系统物流名称。 + * @property {string} express_code 快递单号或快递编码。 + * @property {string} logistics_area_code 物流区域编码。 + * + * @typedef {Object} ExpressPlatformOrderInfo + * @property {string} delivery_order_code 发货单号。 + * @property {string} order_type 订单类型。 + * @property {string} status 订单状态。 + * @property {number} step 流程步骤。 + * @property {string} order_flag 订单标记。 + * @property {string} from_key 来源键。 + * @property {string} create_at 创建时间。 + * @property {string} place_order_time 下单时间。 + * @property {string} pay_time 支付时间。 + * @property {string} operate_time 操作时间。 + * @property {string} delivery_time 发货时间。 + * + * @typedef {Object} ExpressPlatformReceiverInfo + * @property {string} name 收件人姓名。 + * @property {string} tel 电话。 + * @property {string} mobile 手机号。 + * @property {string} email 邮箱。 + * @property {string} country_code 国家编码。 + * @property {string} province 省份。 + * @property {string} city 城市。 + * @property {string} area 区县。 + * @property {string} town 乡镇。 + * @property {string} detail_address 详细地址。 + * @property {string} zip_code 邮编。 + * + * @typedef {Object} ExpressPlatformSettlementInfo + * @property {number} total_amount 总金额。 + * @property {number} item_amount 商品金额。 + * @property {number} discount_amount 优惠金额。 + * @property {number} freight 运费。 + * @property {number} ar_amount 应收金额。 + * @property {number} got_amount 已收金额。 + * + * @typedef {Object} ExpressPlatformItemsSummary + * @property {Array} items 商品明细。 + * @property {number} items_count 商品数量。 + * @property {number} items_total 商品总额。 + * @property {number} items_weight 商品总重量。 + */ +class ExpressPlatformService extends MainService { + /** + * 获取订单日志使用的操作人信息。 + * + * 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。 + * + * @return {{ id: string|null, name: string }} 操作人信息。 + */ + getOrderLogOperator() { + const stateUser = this.isPlainObject(this.ctx && this.ctx.state && this.ctx.state.user) + ? this.ctx.state.user + : null; + const ctxUser = this.isPlainObject(this.ctx && this.ctx.user) + ? this.ctx.user + : null; + const operatorSource = stateUser || ctxUser || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 从候选来源中提取可落库的打印版本号字段。 + * + * 仅当上游明确返回 ver 且非空字符串时返回 `{ ver }`, + * 避免在回写时写入默认值或覆盖已有有效值。 + * + * @param {Array<*>} candidates 候选来源列表。 + * @return {{ver?: string}} 可直接合并到 OrderExpress.update 的字段补丁。 + */ + buildOrderExpressVerPatch(candidates = []) { + const normalizedCandidates = Array.isArray(candidates) ? candidates : [ candidates ]; + for (const candidate of normalizedCandidates) { + if (candidate === null || candidate === undefined) { + continue; + } + const normalized = String(candidate).trim(); + if (normalized) { + return { + ver: normalized, + }; + } + } + return {}; + } + + /** + * 构建快递平台链路追踪ID。 + * + * 优先使用入参中的 trace_id/traceId,其次使用上下文 trace 信息,最后兜底生成。 + * + * @param {Object} [data={}] 入参。 + * @return {string} 追踪ID。 + */ + buildExpressPlatformTraceId(data = {}) { + const normalizedData = data && typeof data === 'object' ? data : {}; + const ctxTraceId = this.ctx && this.ctx.traceId !== undefined + ? this.ctx.traceId + : this.ctx && this.ctx.requestId !== undefined + ? this.ctx.requestId + : this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined + ? this.ctx.state.traceId + : ''; + const normalizedTraceId = String( + normalizedData.trace_id + || normalizedData.traceId + || ctxTraceId + || '' + ).trim(); + + if (normalizedTraceId) { + return normalizedTraceId; + } + + return `express_platform_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + } + + /** + * 清理平台取号失败的订单资源。 + * + * 回退 print_quantity_locked、硬删除 OrderExpress(status=0) 记录、 + * 标记订单异常、写失败日志。所有清理步骤在事务内完成,保证原子性。 + * + * @param {Array<{order_id: number, business_key: number, warehouse_id: number, store_id?: number}>} failedOrders 失败订单列表。 + * @param {string} reason 失败原因描述。 + * @return {Promise} 无返回值。 + */ + async cleanupFailedWaybillOrders(failedOrders, reason) { + const normalizedFailedOrders = Array.isArray(failedOrders) ? failedOrders : []; + if (normalizedFailedOrders.length === 0) { + return; + } + + const traceId = this.buildExpressPlatformTraceId(); + const normalizedReason = String(reason || '未知失败').trim(); + this.ctx.logger.info('[expressPlatform.cleanupFailedWaybillOrders] 开始清理失败订单资源', { + traceId, + failedCount: normalizedFailedOrders.length, + reason: normalizedReason, + failedOrderKeys: normalizedFailedOrders.map(o => `${o.warehouse_id}_${o.order_id}_${o.business_key}`).join(','), + }); + + const { Op } = this.app.Sequelize; + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + + try { + // 1) 按 store_id:warehouse_id 聚合回退 lock 量 + const restoreRelationMap = new Map(); + for (const order of normalizedFailedOrders) { + const storeId = Number(order.store_id) || 0; + const warehouseId = Number(order.warehouse_id) || 0; + if (!storeId || !warehouseId) { + continue; + } + const relationKey = `${storeId}:${warehouseId}`; + const currentRelation = restoreRelationMap.get(relationKey) || { + store_id: storeId, + warehouse_id: warehouseId, + failed_count: 0, + }; + currentRelation.failed_count += 1; + restoreRelationMap.set(relationKey, currentRelation); + } + + if (restoreRelationMap.size > 0 && storeWarehouseModel && typeof storeWarehouseModel.findAll === 'function') { + const restoreRelationList = Array.from(restoreRelationMap.values()); + const restoreRows = await storeWarehouseModel.findAll({ + attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity_locked' ], + where: { + [Op.or]: restoreRelationList.map(item => ({ + store_id: item.store_id, + warehouse_id: item.warehouse_id, + })), + }, + raw: true, + }); + + const restoreRowMap = new Map(); + for (const row of Array.isArray(restoreRows) ? restoreRows : []) { + const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`; + if (relationKey !== '0:0') { + restoreRowMap.set(relationKey, row); + } + } + + const canIncrementLockedQuantity = typeof storeWarehouseModel.increment === 'function'; + + for (const item of restoreRelationList) { + const relationKey = `${item.store_id}:${item.warehouse_id}`; + const row = restoreRowMap.get(relationKey); + if (!row) { + continue; + } + + const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0)); + const restoreQuantity = Math.min(currentLockedQuantity, item.failed_count); + if (restoreQuantity <= 0) { + continue; + } + + if (canIncrementLockedQuantity) { + await storeWarehouseModel.increment('print_quantity_locked', { + by: -restoreQuantity, + where: { + id: row.id, + }, + }); + } else { + await storeWarehouseModel.update({ + print_quantity_locked: currentLockedQuantity - restoreQuantity, + }, { + where: { + id: row.id, + }, + }); + } + + // 记录回退流水 + try { + await this.ctx.model.StoreWarehousePrintQuantityLog.create({ + contract_id: Number(row.id || 0), + store_id: Number(row.store_id || 0), + warehouse_id: Number(row.warehouse_id || 0), + change_type: 'order_restore', + business_type: 'order_express', + business_id: null, + change_quantity: -restoreQuantity, + balance_before: Math.max(0, currentLockedQuantity), + balance_after: Math.max(0, currentLockedQuantity - restoreQuantity), + reason: `平台取号失败回退锁定: ${normalizedReason}`, + operator_id: null, + created_by: null, + }); + } catch (logError) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 回退流水写入失败', { + traceId, + error: logError && logError.message ? logError.message : `${logError}`, + }); + } + } + } + + // 2) 硬删除 OrderExpress(status=0) 记录 + if (orderExpressModel && typeof orderExpressModel.destroy === 'function') { + const deleteConditions = []; + for (const order of normalizedFailedOrders) { + const orderId = Number(order.order_id) || 0; + const businessKey = Number(order.business_key) || 0; + if (!orderId || !businessKey) { + continue; + } + deleteConditions.push({ + order_id: orderId, + business_key: businessKey, + }); + } + + if (deleteConditions.length > 0) { + try { + await orderExpressModel.destroy({ + where: { + [Op.or]: deleteConditions, + status: 0, + }, + }); + } catch (destroyError) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 硬删除 OrderExpress 失败', { + traceId, + error: destroyError && destroyError.message ? destroyError.message : `${destroyError}`, + }); + } + } + } + + // 3) 标记订单异常 + const failedOrderIds = normalizedFailedOrders + .map(order => Number(order.order_id) || 0) + .filter(orderId => orderId > 0); + const uniqueFailedOrderIds = Array.from(new Set(failedOrderIds)); + if (uniqueFailedOrderIds.length > 0) { + const orderPendingExceptionService = this.service + && this.service.systems + && this.service.systems.orderPendingException; + if (orderPendingExceptionService && typeof orderPendingExceptionService.markPendingException === 'function') { + try { + await orderPendingExceptionService.markPendingException({ + ids: uniqueFailedOrderIds, + exception_text: `订单快递分配失败(${normalizedReason})`, + }); + } catch (markError) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 标记订单异常失败', { + traceId, + error: markError && markError.message ? markError.message : `${markError}`, + }); + } + } + } + + // 4) 写失败日志 + const expressService = this.service && this.service.systems && this.service.systems.express; + if (expressService && typeof expressService.createAllocateExpressFailureLogs === 'function' && uniqueFailedOrderIds.length > 0) { + const sampleWarehouseId = normalizedFailedOrders.length > 0 + ? (Number(normalizedFailedOrders[0].warehouse_id) || null) + : null; + try { + await expressService.createAllocateExpressFailureLogs(uniqueFailedOrderIds, normalizedReason, sampleWarehouseId); + } catch (logError) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 写失败日志异常', { + traceId, + error: logError && logError.message ? logError.message : `${logError}`, + }); + } + } + + this.ctx.logger.info('[expressPlatform.cleanupFailedWaybillOrders] 清理完成', { + traceId, + failedCount: normalizedFailedOrders.length, + deletedExpressCount: normalizedFailedOrders.filter(o => Number(o.order_id) > 0 && Number(o.business_key) > 0).length, + markedOrderCount: uniqueFailedOrderIds.length, + restoredRelationCount: restoreRelationMap.size, + }); + } catch (error) { + this.ctx.logger.error('[expressPlatform.cleanupFailedWaybillOrders] 清理流程异常', { + traceId, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + // 清理异常不抛给上游,避免干扰主流程 + } + } + + /** + * 取号回写前兜底校验:比对订单主表当前快递编码与本次取号请求的快递编码。 + * + * 取号请求为外部 HTTP 调用且耗时较长,期间订单快递可能被并发修改; + * 此处只做告警记录,不阻断回写,用于事后定位编码错位问题。 + * + * @param {Object} params 校验入参。 + * @param {string} params.traceId 本次取号链路标识。 + * @param {Array} params.successUpdates 即将回写的成功取号项列表。 + * @param {string} [params.requestExpressCode] 本次取号请求使用的快递编码。 + * @param {Object} [params.transaction] 回写事务对象。 + * @return {Promise} 无返回值。 + */ + async warnExpressCodeMismatch(params = {}) { + const { + traceId, + successUpdates, + requestExpressCode, + transaction, + } = params; + const updates = Array.isArray(successUpdates) ? successUpdates : []; + const requestCode = String(requestExpressCode || '').trim(); + if (!requestCode || updates.length === 0) { + return; + } + + const firstWarehouseId = Number(updates[0] && updates[0].warehouse_id) || 0; + if (!firstWarehouseId) { + return; + } + + try { + const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(firstWarehouseId); + const orderIds = updates + .map(item => Number(item && item.order_id)) + .filter(v => Number.isFinite(v) && v > 0); + if (orderIds.length === 0) { + return; + } + const rows = await orderModel.findAll({ + attributes: [ 'id', 'logistics_code' ], + where: { id: orderIds }, + transaction, + raw: true, + }); + const currentCodeMap = new Map( + (Array.isArray(rows) ? rows : []) + .map(row => [ Number(row && row.id) || 0, String(row && row.logistics_code || '').trim() ]) + ); + for (const item of updates) { + const orderId = Number(item && item.order_id) || 0; + const currentCode = currentCodeMap.get(orderId) || ''; + if (currentCode && currentCode !== requestCode) { + this.ctx.logger.error('[expressPlatform.polyapi] 回写前快递编码不一致告警', { + traceId, + order_id: orderId, + request_express_code: requestCode, + current_logistics_code: currentCode, + }); + } + } + } catch (error) { + // 兜底校验失败不影响回写主流程 + this.ctx.logger.warn('[expressPlatform.polyapi] 回写前快递编码校验异常,跳过', { + traceId, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + /** + * 从 orders 数据中提取失败订单清理所需的基本字段。 + * + * @param {Array} orders 订单列表。 + * @return {Array<{order_id: number, business_key: number, warehouse_id: number, store_id: number}>} 标准化后的失败订单列表。 + */ + buildFailedOrderCleanupList(orders = []) { + const normalizedOrders = Array.isArray(orders) ? orders : []; + const result = []; + for (const order of normalizedOrders) { + const orderDelivery = order && order.order_delivery ? order.order_delivery : {}; + const orderId = Number(orderDelivery.id) || Number(order.order_id) || 0; + const businessKey = Number(order.business_key) || 0; + const warehouseId = Number(orderDelivery.warehouse_id) || Number(order.warehouse_id) || 0; + const storeId = Number(orderDelivery.store_id) || Number(order.store_id) || 0; + if (!orderId || !businessKey) { + continue; + } + result.push({ + order_id: orderId, + business_key: businessKey, + warehouse_id: warehouseId, + store_id: storeId, + }); + } + return result; + } + + /** + * 菠萝派(PolyAPI)平台取号接口。 + * + * 流程:查询已分配运单号 → 调用平台字典接口 → 按平台编码构造订单载荷并调用 + * Differ.JH.Logistics.PostOrder 取号 → 逐条校验结果 → 事务回写运单号与快递编码。 + * 回写前会兜底校验主表当前快递编码与本次取号接口编码是否一致,不一致仅告警。 + * + * @param {Object} [data={}] 平台业务入参。 + * @param {Object} [data.matchedPlatform] 匹配到的快递平台配置。 + * @param {Object} [data.listByWarehousePlatformCode] 当前仓库平台快递接口配置。 + * @param {Array} [data.orders] 待取号订单列表(含 order_delivery 与 business_key)。 + * @return {Promise} 无返回值;内部完成回写与日志,失败时抛出异常。 + */ + async polyapi(data = {}) { + const { matchedPlatform, listByWarehousePlatformCode, orders } = data; + const traceId = this.buildExpressPlatformTraceId(data); + const normalizedOrders = Array.isArray(orders) ? orders : []; + const orderIdListForLog = normalizedOrders + .map(item => Number(item && item.order_id) || Number(item && item.order_delivery && item.order_delivery.id) || 0) + .filter(orderId => Number.isFinite(orderId) && orderId > 0); + const waveIdListForLog = normalizedOrders + .map(item => Number(item && item.wave_id) || Number(item && item.order_delivery && item.order_delivery.wave_id) || 0) + .filter(waveId => Number.isFinite(waveId) && waveId > 0); + + this.ctx.logger.info('[expressPlatform.polyapi] 入口请求', { + traceId, + waveIds: Array.from(new Set(waveIdListForLog)), + orderIds: Array.from(new Set(orderIdListForLog)).slice(0, 50), + orderCount: normalizedOrders.length, + requestSnapshot: { + matchedPlatformCode: matchedPlatform && matchedPlatform.code, + defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface, + platformCode: listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code, + logisticsCode: listByWarehousePlatformCode && listByWarehousePlatformCode.logistics_code, + warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id, + }, + }); + const ExpressList = await this.service.systems.express.loadExpressList(); + const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || ''; + const orderDataMap = new Map(); + for (const order_tmp of normalizedOrders) { + const od = order_tmp && order_tmp.order_delivery; + if (!od) continue; + orderDataMap.set(`${od.id}_${order_tmp.business_key}`, { + delivery_order_code: od.delivery_order_code || '', + source_order_codes: od.source_order_codes || '', + store_id: od.store_id || 0, + }); + } + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + const allocatedWaybillMap = new Map(); + if (orderExpressModel && typeof orderExpressModel.findAll === 'function') { + const { Op } = this.app.Sequelize; + const orderIdList = Array.from(new Set((Array.isArray(orders) ? orders : []) + .map(order => Number(order && order.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + + if (orderIdList.length > 0) { + this.ctx.logger.info('[expressPlatform.polyapi] 查询已分配快递号前', { + traceId, + orderCount: orderIdList.length, + orderIds: orderIdList.slice(0, 50), + }); + // 强制同仓校验:读取已分配运单必须同时限定订单ID与仓库ID,禁止跨仓串读 + const allocatedWarehouseId = Number(listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id) + || Number(this.ctx && this.ctx.user && this.ctx.user.store_id) + || 0; + const allocatedWaybillRows = allocatedWarehouseId > 0 + ? await orderExpressModel.findAll({ + attributes: [ 'order_id', 'business_key', 'waybill_code' ], + where: { + order_id: { + [Op.in]: orderIdList, + }, + warehouse_id: allocatedWarehouseId, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }) + : []; + + this.ctx.logger.info('[expressPlatform.polyapi] 查询已分配快递号后', { + traceId, + hitRowCount: Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows.length : 0, + }); + + for (const row of Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows : []) { + const orderId = Number(row && row.order_id); + const businessKey = Number(row && row.business_key); + const waybillCode = String(row && row.waybill_code || '').trim(); + if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isFinite(businessKey) || businessKey <= 0 || !waybillCode) { + continue; + } + + const waybillKey = `${orderId}:${businessKey}`; + if (!allocatedWaybillMap.has(waybillKey)) { + allocatedWaybillMap.set(waybillKey, waybillCode); + } + } + } + } + const Dictionary_bizcontent = { + }; + this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 字典接口调用前', { + traceId, + api: 'Differ.JH.LogisticsPlatFeatures', + request: Dictionary_bizcontent, + tokenPresent: Boolean(listByWarehousePlatformCode && listByWarehousePlatformCode.token), + }); + const Dictionary_result = await this.service.systems.poloApi.request('Differ.JH.LogisticsPlatFeatures', Dictionary_bizcontent, matchedPlatform, listByWarehousePlatformCode.token); + this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 字典接口调用后', { + traceId, + api: 'Differ.JH.LogisticsPlatFeatures', + response: Dictionary_result, + }); + if (Dictionary_result && Dictionary_result.code && String(Dictionary_result.code) !== '10000') { + const dictErrorMessage = String(Dictionary_result.submessage || Dictionary_result.message || '字典接口调用失败').trim(); + this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 字典接口返回业务失败', { + traceId, + code: Dictionary_result.code, + message: dictErrorMessage, + response: Dictionary_result, + }); + // 字典接口失败,清理所有订单后抛出 + const allFailedOrders = this.buildFailedOrderCleanupList(orders); + await this.cleanupFailedWaybillOrders(allFailedOrders, `字典接口失败: ${dictErrorMessage}`); + throw new Error(`菠萝派字典接口返回错误: ${dictErrorMessage}`); + } + const last3day = new Date(); + last3day.setDate(last3day.getDate() + 3); + const pickUpDate = this.app.formatDate(last3day); + const last4day = new Date(); + last4day.setDate(last4day.getDate() + 4); + const pickUpEndDate = this.app.formatDate(last4day); + + console.log('listByWarehousePlatformCode', listByWarehousePlatformCode); + const order_bizcontent = { + orders: orders.map(order_tmp => { + const order = order_tmp.order_delivery; + console.log('order', order); + const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}; + let plattradeno = order.oaid_order_source_code || order.source_order_codes || ''; + if (listByWarehousePlatformCode.platform_code === 'DY' && String(order.from_key || '') === '23060081' && !!order.pay_no && plattradeno.indexOf(',') > -1) { + plattradeno = order.pay_no; + } + let playload = { + object_Id: `${order.warehouse_id.toString(16)}_${Number(order.id || 0).toString(16)}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 + orderno: `${order.warehouse_id.toString(16)}_${Number(order.id || 0).toString(16)}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 + plattradeno, + tid: plattradeno, + ismultiplepieces: order.package_count > 1 ? 1 : 0, + logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', + logistictype: expressListItem[listByWarehousePlatformCode.platform_code] || '', + providercode: expressListItem[listByWarehousePlatformCode.platform_code] || order.logistics_code || '', + numpackage: order.package_count || '1', + Businesstype: listByWarehousePlatformCode.product_type, + Expresstype: listByWarehousePlatformCode.product_type, + ProductType: listByWarehousePlatformCode.product_type || '', + transtype: '0', + transtypecode: '1', + mainsubpaymode: '1', + businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS', + paymode: '1', + ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal', + ProviderID: '', + procode: order.procode || '普通商品', + codpaymoney: order.ar_amount ?? null, + packagemoney: order.item_amount ?? null, + weight: Number(order.items_weight) || 0, // 单位 g,需确认 PolyAPI 期望单位 + supporpaymoney: order.total_amount ?? null, + length: Number(order.length) || 0, + width: Number(order.width) || 0, + height: Number(order.height) || 0, + volume: Number(order.volume) || 0, + ispickup: listByWarehousePlatformCode.ispickup ?? 0, + Sipshopid: listByWarehousePlatformCode.platform_shop_id || '', + oaid: order.oaid || '', + cpcode: expressListItem[listByWarehousePlatformCode.platform_code] || '', + logisticsproductname: 'JH_02', + dmssorting: 0, + brandno: listByWarehousePlatformCode.brandno || null, + needencrypt: 1, + ordertime: order.place_order_time || '', + customername: '测试', + ordersource: matchedPlatform.ordersource || '', + inputsite: listByWarehousePlatformCode.site_code || '', + sitecode: listByWarehousePlatformCode.site_code || '', + shipperno: listByWarehousePlatformCode.shipperno || '', + customercode: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.shipperno || '' : listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', + sender: { + Company: listByWarehousePlatformCode.shop_name || '', + name: listByWarehousePlatformCode.sender_name || '', + phone: order.sys_platform_code === 'XHS' ? undefined : listByWarehousePlatformCode.sender_tel || '', + mobile: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.sender_tel : undefined, + country: 'CN', + city: listByWarehousePlatformCode.city_name || '', + province: listByWarehousePlatformCode.province_name || '', + area: listByWarehousePlatformCode.district_name || '', + town: listByWarehousePlatformCode.town_name || '', + address: listByWarehousePlatformCode.address || '', + }, // 需要实现 + receiver: { + name: order.name || '', + company: order.company || '', + phone: order.sys_platform_code === 'KS' || order.sys_platform_code === 'KS' ? undefined : (order.mobile || order.tel || ''), + mobile: order.mobile || order.tel || '', + country: order.country_code || 'CN', + province: order.province || '', + city: order.city || '', + area: order.area || '', + town: order.town || '', + address: order.detail_address || '', + zip: order.zip_code || '', + email: order.email || '', + + }, + goods: (order.orderItems && order.orderItems.map(item => ({ + productid: item.item_code, + cnname: 'sp', + count: item.plan_qty || 0, + }))) || [], + // Mallmaskid: '', + + template_url: listByWarehousePlatformCode.template_id || '', + labelformat: listByWarehousePlatformCode.labelformat || '', + extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', + }; + console.log('matchedPlatform.platid', matchedPlatform.platid); + console.log('startPlayload', playload); + if (playload.providercode === 'JD') { + playload.pickUpDate = pickUpDate; + playload.pickUpEndDate = pickUpEndDate; + playload.shipperno = listByWarehousePlatformCode.shipperno || ''; + } + if (Number(matchedPlatform.platid) === 673) { + playload.BizVersion = '2'; + playload.brandno = listByWarehousePlatformCode.brandno === 'SF' ? listByWarehousePlatformCode.brandno : undefined; + } + if (Number(matchedPlatform.platid) === 544) { + const { + orderno, + plattradeno, + logistictype, + ProductType, + providercode, + numpackage, + businessplat, + oaid, + ordertype, + businessType, + codpaymoney, + ProviderID, + cpcode, + logisticsproductname, + needencrypt, + ordersource, + shipperno, + sitecode, + customercode, + goods, + sender = {}, + receiver = {}, + } = playload; + const { + name: senderNameRaw, + company: senderCompanyRaw, + phone: senderPhoneRaw, + mobile: senderMobileRaw, + country, + city: senderCity, + province: senderProvince, + address: senderAddress, + } = sender; + const { + name, + phone, + province: receiverProvince, + city: receiverCity, + address: receiverAddress, + } = receiver; + const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || ''; + const senderCompany = senderCompanyRaw || listByWarehousePlatformCode.shop_name || ''; + const customername = senderNameRaw || senderCompanyRaw || listByWarehousePlatformCode.shop_name || '测试'; + + playload = { + orderno, + plattradeno, + ProductType, + businesstype: ProductType, + expresstype: ProductType, + logistictype, + providercode: providercode || cpcode || logistictype || '', + numpackage, + businessplat, + platcode: plattradeno, + mainsubpaymode: '1', + ordertype, + businessType: businessType || ordertype || 'JH_Normal', + codpaymoney, + ProviderID, + cpcode, + logisticsproductname, + needencrypt, + ordersource, + shipperno, + sitecode, + customername, + goods, + oaid, + customercode: logistictype === 'SF' ? undefined : customercode || shipperno || listByWarehousePlatformCode.shipperno || listByWarehousePlatformCode.client_id || '', + sender: { + name: senderName, + phone: senderPhoneRaw, + mobile: senderMobileRaw, + company: senderCompany, + country, + city: senderCity, + province: senderProvince, + address: senderAddress, + }, + receiver: { + name, + phone, + province: receiverProvince, + city: receiverCity, + address: receiverAddress, + }, + }; + console.log('playload.providercode', playload.providercode); + if (playload.providercode === 'SF') { + playload.expressPayMethod = '1'; + } else { + playload.paymode = '1'; + playload.codpaymoney = ''; + } + } + if (matchedPlatform.platid === 672) { + /* if (!order.source_order_codes) { + throw new Error('订单数据错误,缺失平台订单号'); + } + */ + playload.object_Id = toUint64(order.warehouse_id, order.id, order_tmp.business_key); + // extend_props 可能为 null,先做空值保护,避免直接抛 TypeError 掩盖业务错误 + const ewaybillOrderCode = order.extend_props && order.extend_props.ewaybill_order_code; + if (!ewaybillOrderCode) { + throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请核实非手工单(视频号手工单分配不了运单号),复制次信息给ERP方反馈'); + } + playload.oaid = ewaybillOrderCode; + + playload.transtype = '0'; + playload.Mallmaskid = order.buyer_nick; + playload.mainsubpaymode = '1'; + delete playload.plattradeno; + } + playload.ProviderID = listByWarehousePlatformCode.providerid || ''; + console.log('playload', playload); + return playload; + }), + shoptype: matchedPlatform.shoptype, + }; + + // 调用菠萝派平台接口进行数据处理 + this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用前', { + traceId, + api: 'Differ.JH.Logistics.PostOrder', + waveIds: Array.from(new Set(waveIdListForLog)), + orderIds: Array.from(new Set(orderIdListForLog)).slice(0, 50), + request: order_bizcontent, + }); + const result = await this.service.systems.poloApi.request('Differ.JH.Logistics.PostOrder', order_bizcontent, matchedPlatform, listByWarehousePlatformCode.token); + this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用后', { + traceId, + api: 'Differ.JH.Logistics.PostOrder', + response: JSON.stringify(result), + }); + console.log('分配运单号结果', result); + + // 统一处理:不再依赖顶层 code,直接从 results 逐条提取 issuccess 和 submessage + { + // 逐条检查 issuccess,将平台返回的业务失败项单独提取,避免因 logisticno 为空被误判为"运单号为空" + const allResults = Array.isArray(result.results) ? result.results : []; + + // 平台系统级失败(如 code=40000 / GSE.REQUEST_FAILURE.SYSTEMERROR)时 results 是空数组, + // 继续往下走会把"0 条结果"当成成功,订单既不回写运单号也不标记异常,这里直接按失败抛出。 + if (allResults.length === 0 && normalizedOrders.length > 0) { + const polyapiRequestId = String( + result && (result.polyapirequestid || result.requestid || result.request_id) || '' + ).trim(); + const emptyResultReason = String( + result && (result.submessage || result.message) || '' + ).trim() || `菠萝派平台接口未返回取号结果(code=${String(result && result.code || '') || '空'})`; + // 带上菠萝派请求ID,便于平台侧按 polyapirequestid 定位本次调用 + const reasonWithRequestId = polyapiRequestId + ? `${emptyResultReason}(polyapirequestid=${polyapiRequestId})` + : emptyResultReason; + this.ctx.logger.error('[expressPlatform.polyapi] 平台返回空 results,判定为系统级失败', { + traceId, + polyapirequestid: polyapiRequestId, + code: result && result.code, + subcode: result && result.subcode, + reason: emptyResultReason, + orderCount: normalizedOrders.length, + response: JSON.stringify(result), + }); + const allFailedOrders = this.buildFailedOrderCleanupList(orders); + await this.cleanupFailedWaybillOrders(allFailedOrders, reasonWithRequestId); + throw new Error(`菠萝派分配快递号失败: ${reasonWithRequestId}`); + } + + const itemFailedList = []; + const itemSuccessList = []; + for (const item of allResults) { + const isSuccess = String(item.issuccess || '') === '1'; + if (isSuccess) { + itemSuccessList.push(item); + } else { + itemFailedList.push(item); + } + } + + // 逐条失败项:按 submessage 分组,每组使用各自的失败原因 + if (itemFailedList.length > 0) { + // 按 submessage 分组 + const reasonGroups = new Map(); + for (const failedItem of itemFailedList) { + const itemReason = String( + failedItem.submessage || failedItem.message || failedItem.subcode || '平台返回逐条业务失败' + ).trim(); + if (!reasonGroups.has(itemReason)) { + reasonGroups.set(itemReason, []); + } + reasonGroups.get(itemReason).push(failedItem); + } + + this.ctx.logger.error('[expressPlatform.polyapi] results 中存在逐条业务失败项', { + traceId, + totalCount: allResults.length, + failedCount: itemFailedList.length, + successCount: itemSuccessList.length, + reasonGroups: Array.from(reasonGroups.keys()), + sampleFailItem: JSON.stringify(itemFailedList.slice(0, 3)), + }); + + // 逐组清理 + for (const [ groupReason, groupItems ] of reasonGroups) { + const itemFailedOrders = []; + for (const failedItem of groupItems) { + const [ , order_id_hex, business_key ] = String(failedItem.orderno || '').split('_'); + const orderId = parseInt(order_id_hex, 16) || 0; + const businessKey = Number(business_key) || 0; + if (!orderId || !businessKey) continue; + + let storeId = 0; + let warehouseId = 0; + for (const order of Array.isArray(orders) ? orders : []) { + const orderDelivery = order && order.order_delivery; + const oId = Number(orderDelivery && orderDelivery.id) || 0; + const bk = Number(order && order.business_key) || 0; + if (oId === orderId && bk === businessKey) { + storeId = Number(orderDelivery && orderDelivery.store_id) || 0; + warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0; + break; + } + } + itemFailedOrders.push({ + order_id: orderId, + business_key: businessKey, + warehouse_id: warehouseId, + store_id: storeId, + }); + } + if (itemFailedOrders.length > 0) { + await this.cleanupFailedWaybillOrders(itemFailedOrders, groupReason); + } + } + + // 全部订单都失败则抛出 + if (itemSuccessList.length === 0) { + const firstReason = Array.from(reasonGroups.keys())[0] || '平台返回逐条业务失败'; + throw new Error(firstReason); + } + } + + // 仅用成功的 items 继续处理 + result.results = itemSuccessList; + + const resolveWaybillCode = item => String(item && (item.waybill_code || item.logisticno) || '').trim(); + let successUpdates = []; + switch (listByWarehousePlatformCode.platform_code) { + case 'KS': + successUpdates = (result.results || []).map(item => { + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; + const waybillCode = resolveWaybillCode(item); + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo: item.printinfo, + signature: item.signature, + encryptprintinfo: item.encryptprintinfo, + ...this.buildOrderExpressVerPatch([ item.ver ]), + create_at: new Date(), + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: sysExpressName || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; + case 'DY': + successUpdates = (result.results || []).map(item => { + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; + + const waybillCode = resolveWaybillCode(item); + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + signature: item.signature, + encryptedtoken: item.encryptedtoken, + encryptprintinfo: item.encryptprintinfo, + ...this.buildOrderExpressVerPatch([ item.ver ]), + create_at: new Date(), + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: sysExpressName || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; + case 'JD':{ + const batchPrintOrders = (result.results || []).map(item => ({ + orderno: String(item.orderno), + logisticno: String(item.logisticno), + outputformat: 'JH_PDF', + labelformat: 'JH_A4', + printobjecttype: 'JH_Label', + numpackage: '1', + countrycode: '', + logisticsid: '', + orderitemno: '', + sendername: '', + sendercompany: '', + senderprovince: '', + sendercity: '', + senderarea: '', + senderaddress: '', + sendertel: '', + receivername: '', + receivercompany: '', + receiverprovince: '', + receivercity: '', + receiverarea: '', + receiveraddress: '', + receivertel: '', + cargoname: '', + senddata: '', + // weight: '', + eCustomerCode: '', + remark: '', + selleruserid: '', + printno: '', + iscloudprint: 'false', + needprintdetail: 'false', + extenddata: '', + providercode: String(item.procode || item.realcpcode || item.logisticcompanycode || ''), + packageno: '', + fontsize: '', + platorderno: '', + sipshopid: 0, + })); + console.log('京东批量打印请求参数', JSON.stringify({ + api: 'Differ.JH.Logistics.BatchPrintOrder', + orders: batchPrintOrders, + })); + const batchPrintPlatform = { + ...matchedPlatform, + platid: 611, + interface_url: 'https://apijd.polyapi.com/OpenAPI/do', + }; + const batchPrintResult = await this.service.systems.poloApi.request( + 'Differ.JH.Logistics.BatchPrintOrder', + { orders: batchPrintOrders }, + batchPrintPlatform, + listByWarehousePlatformCode.token + ); + console.log('京东批量打印返回结果', JSON.stringify(batchPrintResult)); + if (String(batchPrintResult && batchPrintResult.code || '') !== '10000') { + const errorMessage = String( + batchPrintResult && (batchPrintResult.submessage || batchPrintResult.message) + || '京东批量打印接口调用失败' + ).trim(); + throw new Error(errorMessage); + } + + successUpdates = (batchPrintResult && batchPrintResult.results || []).map(item => { + const objectId = String(item && item.orderno || '').trim(); + const [ warehouse_id_hex, order_id_hex, business_key ] = objectId.split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; + const waybillCode = String(item && (item.logisticno || item.waybill_code) || '').trim(); + const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'printdata') + ? item.printdata + : item && Object.prototype.hasOwnProperty.call(item, 'htmldata') + ? item.htmldata + : item && Object.prototype.hasOwnProperty.call(item, 'urldata') + ? item.urldata + : item && Object.prototype.hasOwnProperty.call(item, 'batchprintdata') + ? item.batchprintdata + : null; + const printinfo = this.stringifyPlatformPrintData(rawPrintData, rawPrintData) + || JSON.stringify(item); + const signature = String(item && item.signature || '').trim() || null; + const encryptprintinfo = String(item && item.encryptprintinfo || '').trim() || null; + const encryptedtoken = String(item && item.encryptedtoken || '').trim() || null; + + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo, + signature, + encryptprintinfo, + encryptedtoken, + ...this.buildOrderExpressVerPatch([ item && item.ver ]), + create_at: new Date(), + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: sysExpressName || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; + } + case 'XHS':{ + successUpdates = (result.results || []).map(item => { + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; + const waybillCode = resolveWaybillCode(item); + const printInfo = item.print_info ?? item.printinfo; + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo: printInfo, + signature: item.signature, + encryptedtoken: item.encryptedtoken, + encryptprintinfo: item.encryptprintinfo, + ...this.buildOrderExpressVerPatch([ item.ver ]), + create_at: new Date(), + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: sysExpressName || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; + } + case 'SPH':{ + successUpdates = (result.results || []).map(item => { + const objectId = String(item && (item.object_id || item.object_Id || item.orderno) || '').trim(); + const objectIdParts = objectId.split('_'); + if (!objectId || objectIdParts.length < 3) { + throw new Error(`视频号取号返回 object_id 无法解析: ${objectId || JSON.stringify(item)}`); + } + const [ warehouse_id_hex, order_id_hex, business_key ] = objectIdParts; + const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; + const waybillCode = resolveWaybillCode(item); + const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'raw') + ? item.raw + : null; + const printinfo = this.stringifyPlatformPrintData(item && item.printinfo, item && item.printinfo) + || this.stringifyPlatformPrintData(rawPrintData, rawPrintData) + || null; + const signature = item && Object.prototype.hasOwnProperty.call(item, 'signature') + ? item.signature + : rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'signature') + ? rawPrintData.signature + : undefined; + const encryptprintinfo = item && Object.prototype.hasOwnProperty.call(item, 'encryptprintinfo') + ? item.encryptprintinfo + : rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'encryptprintinfo') + ? rawPrintData.encryptprintinfo + : undefined; + const encryptedtoken = item && Object.prototype.hasOwnProperty.call(item, 'encryptedtoken') + ? item.encryptedtoken + : rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'encryptedtoken') + ? rawPrintData.encryptedtoken + : undefined; + const ver = item && Object.prototype.hasOwnProperty.call(item, 'ver') + ? item.ver + : rawPrintData && typeof rawPrintData === 'object' && Object.prototype.hasOwnProperty.call(rawPrintData, 'ver') + ? rawPrintData.ver + : undefined; + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo, + signature, + encryptprintinfo, + encryptedtoken, + ...this.buildOrderExpressVerPatch([ ver ]), + create_at: new Date(), + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: sysExpressName || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; + } + case 'PDD': + successUpdates = (result.results || []).map(item => { + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; + const waybillCode = resolveWaybillCode(item); + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + signature: item.signature, + encryptedtoken: item.encryptedtoken, + encryptprintinfo: item.encryptprintinfo, + ...this.buildOrderExpressVerPatch([ item.ver ]), + create_at: new Date(), + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: sysExpressName || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; + case 'QT': + case 'OTHER': + successUpdates = (result.results || []).map(item => { + const [ warehouse_id_hex, order_id_hex, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); + const order_id = parseInt(order_id_hex, 16) || 0; + const waybillCode = String(item.logisticno || item.waybill_code || '').trim(); + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo: item.printinfo, + signature: item.signature, + encryptprintinfo: item.encryptprintinfo, + encryptedtoken: item.encryptedtoken, + ...this.buildOrderExpressVerPatch([ item.ver ]), + create_at: new Date(), + delivery_order_code: orderDataMap.get(`${order_id}_${business_key}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${order_id}_${business_key}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${order_id}_${business_key}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: sysExpressName || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; + default: { + const unmatchedPlatformCode = String(listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code || '').trim(); + this.ctx.logger.error('[expressPlatform.polyapi] switch 无匹配 platform_code', { + traceId, + platform_code: unmatchedPlatformCode, + }); + // 未知平台编码,清理本批次全部订单资源后抛出 + const allFailedOrders = this.buildFailedOrderCleanupList(orders); + await this.cleanupFailedWaybillOrders(allFailedOrders, `未知平台编码: ${unmatchedPlatformCode || '空'}`); + throw new Error(`当前快递平台编码【${unmatchedPlatformCode}】未在system接口中实现,无法获取快递号`); + } + } + + // 统一校验:过滤掉运单号为空的 successUpdates,避免空字符串写入 OrderExpress.waybill_code + const emptyWaybillUpdates = []; + const validSuccessUpdates = []; + for (const item of successUpdates) { + if (!item.waybill_code) { + emptyWaybillUpdates.push(item); + this.ctx.logger.error('[expressPlatform.polyapi] 运单号为空,跳过回写', { + warehouse_id: item.warehouse_id, + order_id: item.order_id, + business_key: item.business_key, + }); + } else { + validSuccessUpdates.push(item); + } + } + successUpdates = validSuccessUpdates; + + if (emptyWaybillUpdates.length > 0) { + this.ctx.logger.error('[expressPlatform.polyapi] 存在运单号为空的订单', { + count: emptyWaybillUpdates.length, + emptyOrderIds: emptyWaybillUpdates.map(i => `${i.warehouse_id}_${i.order_id}_${i.business_key}`).join(','), + totalSuccessUpdates: successUpdates.length, + }); + + // 反查 orders 找到运单号为空订单对应的 store_id,补齐清理所需信息后统一清理 + const emptyFailedOrders = []; + for (const emptyItem of emptyWaybillUpdates) { + const orderId = Number(emptyItem.order_id) || 0; + const warehouseId = Number(emptyItem.warehouse_id) || 0; + const businessKey = Number(emptyItem.business_key) || 0; + let storeId = 0; + for (const order of Array.isArray(orders) ? orders : []) { + const orderDelivery = order && order.order_delivery; + const oId = Number(orderDelivery && orderDelivery.id) || 0; + const bk = Number(order && order.business_key) || 0; + if (oId === orderId && bk === businessKey) { + storeId = Number(orderDelivery && orderDelivery.store_id) || 0; + break; + } + } + emptyFailedOrders.push({ + order_id: orderId, + business_key: businessKey, + warehouse_id: warehouseId, + store_id: storeId, + }); + } + await this.cleanupFailedWaybillOrders(emptyFailedOrders, '运单号为空'); + + // 全部订单都失败则抛出 + if (successUpdates.length === 0) { + throw new Error(`菠萝派平台接口返回运单号全部为空,共${emptyWaybillUpdates.length}笔订单取号失败`); + } + } + + const orderMetaMap = new Map(); + for (const order of Array.isArray(orders) ? orders : []) { + const orderDelivery = order && order.order_delivery; + const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0; + const orderId = Number(orderDelivery && orderDelivery.id) || 0; + const businessKey = Number(order && order.business_key) || 0; + if (!warehouseId || !orderId || !businessKey) { + continue; + } + + orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, { + store_id: Number(orderDelivery && orderDelivery.store_id) || 0, + warehouse_id: warehouseId, + }); + } + + const settlementRelationMap = new Map(); + for (const item of successUpdates) { + const warehouseId = Number(item.warehouse_id) || 0; + const orderId = Number(item.order_id) || 0; + const businessKey = Number(item.business_key) || 0; + if (!warehouseId || !orderId || !businessKey) { + continue; + } + + const orderMeta = orderMetaMap.get(`${warehouseId}_${orderId}_${businessKey}`); + if (!orderMeta) { + continue; + } + + const storeId = Number(orderMeta.store_id) || 0; + if (!storeId) { + continue; + } + + const relationKey = `${storeId}:${warehouseId}`; + const currentRelation = settlementRelationMap.get(relationKey) || { + store_id: storeId, + warehouse_id: warehouseId, + success_count: 0, + }; + currentRelation.success_count += 1; + settlementRelationMap.set(relationKey, currentRelation); + } + + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) { + this.ctx.logger.info('[expressPlatform.polyapi] DB 回写事务开始前', { + traceId, + successUpdateCount: successUpdates.length, + relationCount: settlementRelationMap.size, + sampleOrderIds: successUpdates.slice(0, 50).map(item => Number(item && item.order_id || 0)).filter(Boolean), + }); + try { + await this.ctx.model.transaction(async transaction => { + // 统一加锁顺序:先锁 store_warehouse 再更新 order_express, + // 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁 + await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction); + + // 回写前兜底校验:主表当前快递编码与本次取号接口编码不一致时告警, + // 防止取号期间订单快递被并发修改导致回写编码错位 + await this.warnExpressCodeMismatch({ + traceId, + successUpdates, + requestExpressCode: listByWarehousePlatformCode && listByWarehousePlatformCode.sys_express_code, + transaction, + }); + + for (const item of successUpdates) { + const warehouseId = Number(item.warehouse_id) || 0; + const orderId = Number(item.order_id) || 0; + const businessKey = Number(item.business_key) || 0; + if (!warehouseId || !orderId || !businessKey) { + continue; + } + + await this.ctx.model.OrderExpress.update(item.orderExpressValues, { + where: { + order_id: orderId, + business_key: businessKey, + warehouse_id: warehouseId, + }, + transaction, + }); + + if (item.orderDeliveryValues) { + const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id); + await orderModel.update(item.orderDeliveryValues, { + where: { + id: orderId, + }, + transaction, + }); + } + } + }); + } catch (error) { + this.ctx.logger.error('[expressPlatform.polyapi] DB 回写事务异常', { + traceId, + successUpdateCount: successUpdates.length, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + throw error; + } + + this.ctx.logger.info('[expressPlatform.polyapi] DB 回写事务完成后', { + traceId, + successUpdateCount: successUpdates.length, + relationCount: settlementRelationMap.size, + }); + + const operationLogService = this.service + && this.service.systems + && this.service.systems.operationLog; + const operator = this.getOrderLogOperator(); + const logPayloads = []; + for (const item of successUpdates) { + const warehouseId = Number(item.warehouse_id) || 0; + const orderId = Number(item.order_id) || 0; + if (!warehouseId || !orderId) { + continue; + } + logPayloads.push({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'WAYBILL', + operator, + extras: { + message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`, + warehouseId, + externalLogType: 'API', + }, + }); + } + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } else { + this.ctx.logger.warn('[expressPlatform.polyapi] operationLog 批量写入服务不可用,跳过日志写入', { + traceId, + count: logPayloads.length, + }); + } + + this.ctx.logger.info('[expressPlatform.polyapi] 订单操作日志写入完成', { + traceId, + operationLogCount: successUpdates.length, + }); + + // 自动同步回传:快递号分配成功后异步触发订单同步 + try { + const settlementEntries = Array.from(settlementRelationMap.entries()); + for (const [ key, relation ] of settlementEntries) { + const successCount = Number(relation && relation.success_count) || 0; + if (successCount <= 0) continue; + const [ storeId, warehouseId ] = key.split(':').map(Number); + if (!storeId || !warehouseId) continue; + + const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( + warehouseId, + storeId + ); + if ( + contractConfig + && contractConfig.policy_config + && contractConfig.policy_config.auto_sync_back === 1 + ) { + // 收集本次分配成功的订单ID + const syncedOrderIds = successUpdates + .filter(u => { + const orderId = Number(u.order_id) || 0; + const wid = Number(u.warehouse_id) || 0; + const bk = Number(u.business_key) || 0; + const meta = orderMetaMap.get(`${wid}_${orderId}_${bk}`); + return meta && meta.store_id === storeId && wid === warehouseId; + }) + .map(u => Number(u.order_id) || 0) + .filter(Boolean); + + if (syncedOrderIds.length > 0) { + // SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过 + const autoSyncFilter = await this.ctx.service.systemMethods.order.pendingOrder.filterAutoSyncSnOrderIds({ + orderIds: syncedOrderIds, + warehouseId, + source: 'polyapi', + }); + if (autoSyncFilter.orderIds.length > 0) { + // 异步调用,不阻塞主流程 + // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, + // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 + this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + orderIds: autoSyncFilter.orderIds, + warehouseId, + }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] polyapi 自动同步失败: ${err.message}` + ); + }); + } + } + } + } + } catch (err) { + this.ctx.logger.error( + `[auto_sync_back] polyapi 自动同步异常: ${err.message}` + ); + } + } + } + this.ctx.logger.info('[expressPlatform.polyapi] 处理完成', { + traceId, + orderCount: normalizedOrders.length, + }); + return { + flag: true, + code: 0, + message: '菠萝派平台数据处理成功', + data: result, + }; + // throw new Error('菠萝派平台接口未实现'); + } + + /** + * 菜鸟数据处理接口。 + * + * @param {Object} [data={}] 平台业务入参。 + * @return {Promise} 处理结果。 + */ + async cainiao(data = {}) { + const { + matchedPlatform = {}, + listByWarehousePlatformCode = {}, + orders = [], + } = data && typeof data === 'object' ? data : {}; + const normalizedOrders = Array.isArray(orders) ? orders : []; + const normalizedExtData = this.normalizePddExtData(listByWarehousePlatformCode.ext_data); + const qimenConfig = this.app.config && this.app.config.qimen ? this.app.config.qimen : {}; + const appKey = String(qimenConfig.appKey || '').trim(); + const appSecret = String(qimenConfig.security || '').trim(); + const signService = this.service && this.service.systems ? this.service.systems.sign : null; + const normalizedTemplateUrl = isValidCainiaoTemplateUrl(listByWarehousePlatformCode.template_url) + ? String(listByWarehousePlatformCode.template_url).trim() + : DEFAULT_CAINIAO_TEMPLATE_URL; + const ExpressList = await this.service.systems.express.loadExpressList(); + const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || ''; + const orderDataMap = new Map(); + for (const order_tmp of normalizedOrders) { + const od = order_tmp && order_tmp.order_delivery; + if (!od) continue; + orderDataMap.set(`${od.id}_${order_tmp.business_key}`, { + delivery_order_code: od.delivery_order_code || '', + source_order_codes: od.source_order_codes || '', + store_id: od.store_id || 0, + }); + } + if (!appKey || !appSecret) { + throw new Error('淘宝接口配置缺失'); + } + + if (!signService || typeof signService.signTopRequest !== 'function') { + throw new Error('签名服务不可用'); + } + + const tradeOrderList = normalizedOrders.map( + order_tmp => { + const orderDelivery = order_tmp && order_tmp.order_delivery ? order_tmp.order_delivery : {}; + const sourceOrderCodes = orderDelivery && orderDelivery.source_order_codes + ? String(orderDelivery.source_order_codes) + .split(',') + .map(item => String(item || '').trim()) + .filter(Boolean) + : []; + // tid 优先取订单表 oaid_order_source_code,为空/空字符串时兜底到原逻辑 + const oaidOrderSourceCodes = orderDelivery && orderDelivery.oaid_order_source_code + ? String(orderDelivery.oaid_order_source_code) + .split(',') + .map(item => String(item || '').trim()) + .filter(Boolean) + : []; + const recipientMobile = orderDelivery && (orderDelivery.mobile || orderDelivery.tel) || ''; + const orderDeliveryOaid = orderDelivery && orderDelivery.oaid ? String(orderDelivery.oaid).trim() : ''; + const oaidTooLong = orderDeliveryOaid.indexOf('-') !== -1 || orderDeliveryOaid.length > 128; + + const tradeOrderInfo = { + logistics_services: normalizedExtData, + object_id: `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`, + order_info: { + order_channels_type: String( + orderDelivery.sys_platform_code + || order_tmp.sys_platform_code + || matchedPlatform.platform_code + || listByWarehousePlatformCode.platform_code + || 'CAINIAO' + ).trim() || 'CAINIAO', + trade_order_list: sourceOrderCodes.length > 0 + ? sourceOrderCodes + : [ orderDelivery && orderDelivery.delivery_order_code || '' ], + }, + package_info: { + items: (orderDelivery && orderDelivery.orderItems || []).map(item => ({ + name: item.item_name || '商品', + count: item.plan_qty, + })) || [], + goods_description: '化妆品', + id: `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`, + length: Number(orderDelivery.length || 1), + width: Number(orderDelivery.width || 1), + height: Number(orderDelivery.height || 1), + weight: Number(orderDelivery.items_weight || 1), + }, + recipient: { + address: { + country: '中国', + city: orderDelivery && orderDelivery.city || '', + province: orderDelivery && orderDelivery.province || '', + district: orderDelivery && orderDelivery.area || '', + town: orderDelivery && orderDelivery.town || null, + detail: orderDelivery && orderDelivery.detail_address || '', + }, + mobile: recipientMobile, + name: orderDelivery && orderDelivery.name || '', + phone: recipientMobile, + oaid: oaidTooLong ? '' : orderDeliveryOaid, + caid: oaidTooLong ? orderDeliveryOaid : '', + tid: oaidOrderSourceCodes.length > 0 + ? oaidOrderSourceCodes[0] + : sourceOrderCodes.length > 0 + ? sourceOrderCodes[0] + : orderDelivery && orderDelivery.delivery_order_code || '', + }, + user_id: listByWarehousePlatformCode.shop && listByWarehousePlatformCode.shop.owner_id || 0, + notify_extend_info: normalizedExtData, + }; + + tradeOrderInfo.template_url = isValidCainiaoTemplateUrl(listByWarehousePlatformCode.template_url) + ? String(listByWarehousePlatformCode.template_url).trim() + : normalizedTemplateUrl; + + return tradeOrderInfo; + } + ); + const cainiaoPayload = { + param_waybill_cloud_print_apply_new_request: { + cp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express + ? (listByWarehousePlatformCode.express.CAINIAO || listByWarehousePlatformCode.express.cainiao_code || '') + : '', + product_code: String(listByWarehousePlatformCode.product_type || '').trim(), + sender: { + address: { + city: listByWarehousePlatformCode.city_name, + detail: listByWarehousePlatformCode.address, + district: listByWarehousePlatformCode.district_name, + province: listByWarehousePlatformCode.province_name, + town: listByWarehousePlatformCode.town_name || null, + }, + mobile: listByWarehousePlatformCode.sender_tel, + name: listByWarehousePlatformCode.sender_name, + phone: listByWarehousePlatformCode.sender_tel, + }, + trade_order_info_dtos: tradeOrderList, + brand_code: String(listByWarehousePlatformCode.site_code || 'default').trim(), + need_encrypt: true, + customer_code: String( + listByWarehousePlatformCode.customer_code + || listByWarehousePlatformCode.client_id + || listByWarehousePlatformCode.shipperno + || '' + ).trim(), + shipping_branch_code: String(listByWarehousePlatformCode.site_code || '').trim(), + }, + }; + + await this.app.setCacheAsync('Cainiaoquery', JSON.stringify(cainiaoPayload), 3600); + const requestParams = { + method: 'cainiao.waybill.ii.get', + app_key: appKey, + session: String(listByWarehousePlatformCode.token || '').trim(), + timestamp: this.app.formatDate(new Date()), + format: 'json', + v: '2.0', + sign_method: 'md5', + param_waybill_cloud_print_apply_new_request: JSON.stringify( + cainiaoPayload.param_waybill_cloud_print_apply_new_request + ), + }; + const sign = signService.signTopRequest(requestParams, '', appSecret, 'md5'); + const response = await this.ctx.curl(DEFAULT_TB_ROUTER_URL, { + method: 'POST', + contentType: 'form', + dataType: 'json', + data: { + ...requestParams, + sign, + }, + }); + await this.app.setCacheAsync('Cainiaoresult', JSON.stringify(response), 3600); + + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + + if (responseData && typeof responseData === 'object' && responseData.error_response) { + const errorResponse = responseData.error_response; + throw new Error(errorResponse.sub_msg || errorResponse.msg || '菜鸟平台接口调用失败'); + } + + const responseRoot = responseData && responseData.cainiao_waybill_ii_get_response + ? responseData.cainiao_waybill_ii_get_response + : {}; + const modules = normalizeFirstWrappedArray([ + responseRoot.modules, + responseRoot.waybill_cloud_print_response_infos, + responseRoot.waybill_cloud_print_response_list, + responseRoot.waybill_cloud_print_response, + ], [ 'waybill_cloud_print_response', 'modules', 'module', 'waybill_cloud_print_response_info' ]); + + if (modules.length === 0) { + throw new Error('菜鸟平台接口返回数据为空'); + } + + if (modules.length !== normalizedOrders.length) { + throw new Error(`菜鸟平台接口返回数量异常: 请求 ${normalizedOrders.length} 条, 返回 ${modules.length} 条`); + } + + const requestedObjectIdSet = new Set(normalizedOrders.map(order => { + const orderDelivery = order && order.order_delivery ? order.order_delivery : {}; + return `${orderDelivery.warehouse_id}_${orderDelivery.id}_${order.business_key}`; + })); + const receivedObjectIdSet = new Set(); + const successUpdates = modules.map(moduleItem => { + const objectId = String(moduleItem && moduleItem.object_id || '').trim(); + if (!objectId || !requestedObjectIdSet.has(objectId)) { + throw new Error(`菜鸟平台接口返回 object_id 异常: ${objectId || 'empty'}`); + } + if (receivedObjectIdSet.has(objectId)) { + throw new Error(`菜鸟平台接口返回重复 object_id: ${objectId}`); + } + receivedObjectIdSet.add(objectId); + + const [ warehouseId, orderId, businessKey ] = objectId.split('_'); + const waybillCode = String(moduleItem && (moduleItem.parent_waybill_code || moduleItem.waybill_code) || '').trim(); + if (!waybillCode) { + throw new Error(`菜鸟平台接口返回运单号为空: ${objectId}`); + } + + const rawPrintData = moduleItem && Object.prototype.hasOwnProperty.call(moduleItem, 'print_data') + ? moduleItem.print_data + : moduleItem && Object.prototype.hasOwnProperty.call(moduleItem, 'printData') + ? moduleItem.printData + : null; + const parsedPrintData = this.parsePlatformPrintData(rawPrintData, '菜鸟', objectId); + const persistedPrintData = this.stringifyPlatformPrintData(rawPrintData, parsedPrintData); + if (!persistedPrintData) { + throw new Error(`菜鸟平台接口返回 print_data 为空: ${objectId}`); + } + + const parsedPrintDataRoot = parsedPrintData && typeof parsedPrintData === 'object' ? parsedPrintData : {}; + const printDataContent = parsedPrintDataRoot.data && typeof parsedPrintDataRoot.data === 'object' + ? parsedPrintDataRoot.data + : {}; + const extraInfo = printDataContent.extraInfo && typeof printDataContent.extraInfo === 'object' + ? printDataContent.extraInfo + : {}; + const orderExpressVerPatch = this.buildOrderExpressVerPatch([ + moduleItem && moduleItem.ver, + parsedPrintDataRoot.ver, + printDataContent.ver, + extraInfo.ver, + ]); + const signature = String( + parsedPrintDataRoot.signature + || printDataContent.signature + || extraInfo.signature + || moduleItem && moduleItem.signature + || '' + ).trim() || null; + const encryptPrintInfo = String( + parsedPrintDataRoot.encryptedData + || parsedPrintDataRoot.key + || printDataContent.encryptedData + || printDataContent.encryptWaybillCode + || extraInfo.encryptWaybillCode + || extraInfo.key + || moduleItem && (moduleItem.encrypt_waybill_code || moduleItem.encryptprintinfo) + || '' + ).trim() || null; + + return { + warehouse_id: Number(warehouseId) || 0, + order_id: Number(orderId) || 0, + business_key: Number(businessKey) || 0, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo: persistedPrintData, + signature, + encryptprintinfo: encryptPrintInfo, + ...orderExpressVerPatch, + create_at: new Date(), + delivery_order_code: orderDataMap.get(`${orderId}_${businessKey}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${orderId}_${businessKey}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${orderId}_${businessKey}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: sysExpressName || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + + await this.persistWaybillSuccessUpdates(successUpdates, normalizedOrders); + + // 自动同步回传:快递号分配成功后异步触发订单同步 + try { + const orderMetaMap = this.buildWaybillOrderMetaMap(normalizedOrders); + const settlementRelationMap = this.buildWaybillSettlementRelationMap( + successUpdates, + orderMetaMap + ); + const settlementEntries = Array.from(settlementRelationMap.entries()); + for (const [ key, relation ] of settlementEntries) { + const successCount = Number(relation && relation.success_count) || 0; + if (successCount <= 0) continue; + const [ storeId, warehouseId ] = key.split(':').map(Number); + if (!storeId || !warehouseId) continue; + + const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( + warehouseId, + storeId + ); + if ( + contractConfig + && contractConfig.policy_config + && contractConfig.policy_config.auto_sync_back === 1 + ) { + // 收集本次分配成功的订单ID + const syncedOrderIds = successUpdates + .filter(u => { + const orderId = Number(u.order_id) || 0; + const wid = Number(u.warehouse_id) || 0; + const bk = Number(u.business_key) || 0; + const meta = orderMetaMap.get(`${wid}_${orderId}_${bk}`); + return meta && meta.store_id === storeId && wid === warehouseId; + }) + .map(u => Number(u.order_id) || 0) + .filter(Boolean); + + if (syncedOrderIds.length > 0) { + // SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过 + const autoSyncFilter = await this.ctx.service.systemMethods.order.pendingOrder.filterAutoSyncSnOrderIds({ + orderIds: syncedOrderIds, + warehouseId, + source: 'cainiao', + }); + if (autoSyncFilter.orderIds.length > 0) { + // 异步调用,不阻塞主流程 + // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, + // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 + this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + orderIds: autoSyncFilter.orderIds, + warehouseId, + }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] cainiao 自动同步失败: ${err.message}` + ); + }); + } + } + } + } + } catch (err) { + this.ctx.logger.error( + `[auto_sync_back] cainiao 自动同步异常: ${err.message}` + ); + } + + return { + flag: true, + code: 0, + message: '菜鸟平台数据处理成功', + data: responseData, + }; + } + + /** + * 解析平台返回的打印数据结构。 + * + * @param {*} rawPrintData 平台原始打印数据。 + * @param {string} platformName 平台名称。 + * @param {string} objectId 请求对象标识。 + * @return {Object|null} 解析后的打印数据对象。 + */ + parsePlatformPrintData(rawPrintData, platformName, objectId) { + if (rawPrintData === null || rawPrintData === undefined || rawPrintData === '') { + return null; + } + + if (typeof rawPrintData === 'string') { + try { + return JSON.parse(rawPrintData); + } catch (error) { + throw new Error(`${platformName}平台接口返回 print_data 解析失败: ${objectId}`); + } + } + + if (typeof rawPrintData === 'object') { + return rawPrintData; + } + + throw new Error(`${platformName}平台接口返回 print_data 结构异常: ${objectId}`); + } + + /** + * 将平台打印数据标准化为可落库的字符串。 + * + * @param {*} rawPrintData 平台原始打印数据。 + * @param {Object|null} parsedPrintData 解析后的打印数据对象。 + * @return {string|null} 可落库字符串。 + */ + stringifyPlatformPrintData(rawPrintData, parsedPrintData) { + if (typeof rawPrintData === 'string') { + return rawPrintData.trim() || null; + } + + const dataToPersist = parsedPrintData !== undefined ? parsedPrintData : rawPrintData; + if (dataToPersist === null || dataToPersist === undefined || dataToPersist === '') { + return null; + } + + if (typeof dataToPersist === 'object') { + return JSON.stringify(dataToPersist); + } + + return String(dataToPersist).trim() || null; + } + + /** + * 构建订单与货主仓库关系映射。 + * + * @param {Array} orders 订单列表。 + * @return {Map} 订单元数据映射。 + */ + buildWaybillOrderMetaMap(orders = []) { + const orderMetaMap = new Map(); + + for (const order of Array.isArray(orders) ? orders : []) { + const orderDelivery = order && order.order_delivery ? order.order_delivery : {}; + const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0; + const orderId = Number(orderDelivery && orderDelivery.id) || 0; + const businessKey = Number(order && order.business_key) || 0; + if (!warehouseId || !orderId || !businessKey) { + continue; + } + + orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, { + store_id: Number(orderDelivery && orderDelivery.store_id) || 0, + warehouse_id: warehouseId, + }); + } + + return orderMetaMap; + } + + /** + * 按货主仓库聚合成功获取面单的扣减数量。 + * + * @param {Array} successUpdates 成功回写项。 + * @param {Map} orderMetaMap 订单元数据映射。 + * @return {Map} 聚合结果。 + */ + buildWaybillSettlementRelationMap(successUpdates = [], orderMetaMap = new Map()) { + const settlementRelationMap = new Map(); + + for (const item of Array.isArray(successUpdates) ? successUpdates : []) { + const relationMeta = orderMetaMap.get(`${item.warehouse_id}_${item.order_id}_${item.business_key}`); + if (!relationMeta || !relationMeta.store_id || !relationMeta.warehouse_id) { + continue; + } + + const relationKey = `${relationMeta.store_id}:${relationMeta.warehouse_id}`; + const currentRelation = settlementRelationMap.get(relationKey) || { + store_id: relationMeta.store_id, + warehouse_id: relationMeta.warehouse_id, + success_count: 0, + }; + currentRelation.success_count += 1; + settlementRelationMap.set(relationKey, currentRelation); + } + + return settlementRelationMap; + } + + /** + * 事务内按 store:warehouse 扣减打印余量并写扣减流水。 + * + * 必须在结算事务内最先执行:先锁 wms_store_warehouse,再更新 wms_order_express, + * 与 createWaybillCode 回写事务(先锁 store_warehouse 后锁 order_express)保持 + * 一致加锁顺序,消除两类事务间的 AB-BA 死锁。 + * + * @param {Map} settlementRelationMap 结算关系聚合。 + * @param {Object} storeWarehouseModel 签约关系模型。 + * @param {Object} transaction Sequelize 事务。 + * @return {Promise} 无返回值。 + */ + async lockAndDeductWaybillSettlement(settlementRelationMap = new Map(), storeWarehouseModel, transaction) { + if (!storeWarehouseModel + || typeof storeWarehouseModel.findAll !== 'function' + || !settlementRelationMap + || settlementRelationMap.size === 0) { + return; + } + + const { Op } = this.app.Sequelize; + const relationList = Array.from(settlementRelationMap.values()); + const relationRows = await storeWarehouseModel.findAll({ + attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ], + where: { + [Op.or]: relationList.map(item => ({ + store_id: item.store_id, + warehouse_id: item.warehouse_id, + })), + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const relationRowMap = new Map(); + for (const row of Array.isArray(relationRows) ? relationRows : []) { + const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`; + if (relationKey !== '0:0') { + relationRowMap.set(relationKey, row); + } + } + + for (const item of relationList) { + const relationKey = `${item.store_id}:${item.warehouse_id}`; + const row = relationRowMap.get(relationKey); + if (!row) { + continue; + } + + const currentPrintQuantity = Number(row.print_quantity || 0); + const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0)); + const successCount = Number(item.success_count || 0); + if (successCount <= 0) { + continue; + } + + const printDecrement = successCount; + const lockedDecrement = Math.min(currentLockedQuantity, printDecrement); + const nextPrintQuantity = currentPrintQuantity - printDecrement; + const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement); + + await storeWarehouseModel.update({ + print_quantity: nextPrintQuantity, + print_quantity_locked: nextLockedQuantity, + }, { + where: { + id: row.id, + }, + transaction, + }); + + await this.ctx.model.StoreWarehousePrintQuantityLog.create({ + contract_id: Number(row.id || 0), + store_id: Number(row.store_id || 0), + warehouse_id: Number(row.warehouse_id || 0), + change_type: 'order_deduct', + business_type: 'order_express', + business_id: null, + change_quantity: -printDecrement, + balance_before: Math.max(0, currentPrintQuantity), + balance_after: Math.max(0, nextPrintQuantity), + reason: '获取快递号成功扣减', + operator_id: null, + created_by: null, + }, { + transaction, + }); + } + } + + /** + * 回写成功获取的面单结果,并扣减打印余量与写入操作日志。 + * + * @param {Array} successUpdates 成功回写项。 + * @param {Array} orders 请求订单列表。 + * @return {Promise} 无返回值。 + */ + async persistWaybillSuccessUpdates(successUpdates = [], orders = []) { + const normalizedSuccessUpdates = Array.isArray(successUpdates) ? successUpdates : []; + if (normalizedSuccessUpdates.length === 0) { + return; + } + + const orderMetaMap = this.buildWaybillOrderMetaMap(orders); + const settlementRelationMap = this.buildWaybillSettlementRelationMap(normalizedSuccessUpdates, orderMetaMap); + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + + if (typeof this.ctx.model.transaction === 'function') { + await this.ctx.model.transaction(async transaction => { + // 统一加锁顺序:先锁 store_warehouse 再更新 order_express, + // 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁 + await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction); + + for (const item of normalizedSuccessUpdates) { + if (!item.warehouse_id || !item.order_id || !item.business_key) { + throw new Error('平台接口返回 object_id 无法解析'); + } + + await this.ctx.model.OrderExpress.update(this.dropEmptyOrderExpressFields(item.orderExpressValues), { + where: { + order_id: item.order_id, + business_key: item.business_key, + warehouse_id: item.warehouse_id, + }, + transaction, + }); + + const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id); + if (item.orderDeliveryValues && orderModel && typeof orderModel.update === 'function') { + await orderModel.update(item.orderDeliveryValues, { + where: { + id: item.order_id, + }, + transaction, + }); + } + } + }); + } + + const operationLogService = this.service && this.service.systems && this.service.systems.operationLog; + const operator = this.getOrderLogOperator(); + const logPayloads = normalizedSuccessUpdates + .filter(item => item.warehouse_id && item.order_id) + .map(item => ({ + businessType: 'order', + businessId: `${item.order_id}`, + operationCode: 'WAYBILL', + operator, + extras: { + message: `订单${item.order_id}获取快递单成功,单号:${item.waybill_code}`, + warehouseId: item.warehouse_id, + externalLogType: 'API', + }, + })); + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function' && logPayloads.length > 0) { + await operationLogService.createOperationLogs(logPayloads); + } + } + + /** + * 规范化拼多多接口要求的扩展字段字符串。 + * + * @param {*} value 扩展字段原始值。 + * @return {string} 规范化后的字符串。 + */ + normalizePddExtData(value) { + if (value === null || value === undefined || value === '') { + return ''; + } + + if (typeof value === 'string') { + return value.trim(); + } + + if (typeof value === 'object') { + return JSON.stringify(value); + } + + return String(value); + } + + /** + * 拼多多数据处理接口。 + * + * @param {Object} [data={}] 平台业务入参。 + * @return {Promise} 当前暂未实现,直接抛出异常。 + */ + async pdd(data = {}) { + const { + listByWarehousePlatformCode = {}, + orders = [], + } = data && typeof data === 'object' ? data : {}; + const normalizedOrders = Array.isArray(orders) ? orders : []; + const normalizedExtData = this.normalizePddExtData(listByWarehousePlatformCode.ext_data); + const ExpressList = await this.service.systems.express.loadExpressList(); + const sysExpressName = (ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}).name || ''; + const orderDataMap = new Map(); + for (const order_tmp of normalizedOrders) { + const od = order_tmp && order_tmp.order_delivery; + if (!od) continue; + orderDataMap.set(`${od.id}_${order_tmp.business_key}`, { + delivery_order_code: od.delivery_order_code || '', + source_order_codes: od.source_order_codes || '', + store_id: od.store_id || 0, + }); + } + + console.log('拼多多平台接口入参', data); + + const tradeOrderList = normalizedOrders.map( + order_tmp => { + return { + logistics_services: normalizedExtData, + object_id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`, + order_info: { + order_channels_type: 'PDD', + trade_order_list: [ `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}` ], + }, + package_info: { + items: (order_tmp.order_delivery && order_tmp.order_delivery.orderItems || []).map(item => ({ + name: item.item_name || '商品', + count: item.plan_qty, + })) || [], + id: `${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`, + total_packages_count: order_tmp.business_key || 1, + }, + recipient: { + address: { + country: '中国', + city: order_tmp.order_delivery && order_tmp.order_delivery.city || '', + province: order_tmp.order_delivery && order_tmp.order_delivery.province || '', + district: order_tmp.order_delivery && order_tmp.order_delivery.area || '', + town: order_tmp.order_delivery && order_tmp.order_delivery.town || null, + detail: order_tmp.order_delivery && order_tmp.order_delivery.detail_address || '', + }, + moblie: order_tmp.order_delivery && (order_tmp.order_delivery.mobile || order_tmp.order_delivery.tel) || '', + name: order_tmp.order_delivery && order_tmp.order_delivery.name || '', + phone: order_tmp.order_delivery && (order_tmp.order_delivery.mobile || order_tmp.order_delivery.tel) || '', + }, + template_url: listByWarehousePlatformCode.template_url || '', + user_id: listByWarehousePlatformCode.shop.owner_id || 0, + }; + } + ); + // 构建pdd接口入参 + const pddPayload = { + // 这里根据实际需要构建接口入参 + type: 'pdd.waybill.get', + accessToken: listByWarehousePlatformCode.token, + param_waybill_cloud_print_apply_new_request: { + need_encrypt: true, + sender: { + address: { + country: '中国', + city: listByWarehousePlatformCode.city_name, + province: listByWarehousePlatformCode.province_name, + district: listByWarehousePlatformCode.district_name, + town: listByWarehousePlatformCode.town_name || null, + detail: listByWarehousePlatformCode.address, + }, + moblie: listByWarehousePlatformCode.sender_tel, + name: listByWarehousePlatformCode.sender_name, + phone: listByWarehousePlatformCode.sender_tel, + }, + trade_order_info_dtos: tradeOrderList, + wp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express + ? (listByWarehousePlatformCode.express.PDD || '') + : '', + }, + }; + console.log('拼多多平台接口构建的请求参数', JSON.stringify(pddPayload, null, 2)); + + await this.app.setCacheAsync('Pddquery', JSON.stringify(pddPayload), 3600); + + // 这里写一个调用pdd_client的入参示例 + // + // + // + + const pddClient = new PddClient(this.ctx); + const { + type, + accessToken, + dataType, + timestamp, + ...requestParams + } = pddPayload; + const pddConfig = (this.ctx && this.ctx.app && this.ctx.app.config && this.ctx.app.config.pdd) || {}; + const configClientId = pddConfig.client_id || pddConfig.clientId; + const configClientSecret = pddConfig.client_secret || pddConfig.clientSecret; + console.log('拼多多签名凭据来源', { + clientId: configClientId || '(missing app.config.pdd.client_id)', + hasClientSecret: Boolean(configClientSecret), + source: 'app.config.pdd', + }); + const builtRequest = pddClient.buildRequest({ + type, + accessToken, + dataType, + timestamp, + clientId: configClientId, + clientSecret: configClientSecret, + bizParams: requestParams, + }); + + console.log('拼多多平台接口请求参数', JSON.stringify({ + baseUrl: DEFAULT_PDD_ROUTER_URL, + requestBody: builtRequest.requestBody, + signText: builtRequest.signText, + sortedPairs: builtRequest.sortedPairs, + }, null, 2)); + + try { + const response = await this.ctx.curl(DEFAULT_PDD_ROUTER_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + dataType: String(pddPayload.dataType || 'JSON').toLowerCase() === 'xml' ? 'text' : 'json', + data: builtRequest.requestBody, + }); + + await this.app.setCacheAsync('Pddresult', JSON.stringify(response), 3600); + + const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') + ? response.data + : response; + console.log('拼多多平台接口返回参数', JSON.stringify(responseData, null, 2)); + + const errorResponse = responseData && responseData.error_response; + if (errorResponse) { + const errorMessage = String(errorResponse.sub_msg || errorResponse.error_msg || '拼多多平台接口调用失败').trim(); + throw new Error(errorMessage); + } + + const modules = responseData + && responseData.pdd_waybill_get_response + && Array.isArray(responseData.pdd_waybill_get_response.modules) + ? responseData.pdd_waybill_get_response.modules + : []; + + if (modules.length === 0) { + throw new Error('拼多多平台接口返回数据为空'); + } + + if (modules.length !== normalizedOrders.length) { + throw new Error(`拼多多平台接口返回数量异常: 请求 ${normalizedOrders.length} 条, 返回 ${modules.length} 条`); + } + + const requestedObjectIdSet = new Set(normalizedOrders.map(order => `${order.order_delivery.warehouse_id}_${order.order_delivery.id}_${order.business_key}`)); + const successUpdates = modules.map(moduleItem => { + const objectId = String(moduleItem && moduleItem.object_id || '').trim(); + if (!objectId || !requestedObjectIdSet.has(objectId)) { + throw new Error(`拼多多平台接口返回 object_id 异常: ${objectId || 'empty'}`); + } + + const [ warehouseId, orderId, businessKey ] = objectId.split('_'); + const waybillCode = String(moduleItem && (moduleItem.parent_waybill_code || moduleItem.waybill_code) || '').trim(); + if (!waybillCode) { + throw new Error(`拼多多平台接口返回运单号为空: ${objectId}`); + } + + let parsedPrintData = null; + if (moduleItem && moduleItem.print_data) { + try { + parsedPrintData = JSON.parse(moduleItem.print_data); + } catch (parseError) { + throw new Error(`拼多多平台接口返回 print_data 解析失败: ${objectId}`); + } + } + + return { + warehouse_id: Number(warehouseId) || 0, + order_id: Number(orderId) || 0, + business_key: Number(businessKey) || 0, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + signature: (parsedPrintData && parsedPrintData.signature) || String(moduleItem && moduleItem.signature || '').trim() || null, + encryptprintinfo: (parsedPrintData && parsedPrintData.encryptedData) || null, + ...this.buildOrderExpressVerPatch([ + moduleItem && moduleItem.ver, + parsedPrintData && parsedPrintData.ver, + parsedPrintData && parsedPrintData.data && parsedPrintData.data.ver, + ]), + create_at: new Date(), + delivery_order_code: orderDataMap.get(`${orderId}_${businessKey}`)?.delivery_order_code || null, + source_order_codes: orderDataMap.get(`${orderId}_${businessKey}`)?.source_order_codes || null, + store_id: orderDataMap.get(`${orderId}_${businessKey}`)?.store_id || null, + logistics_code: listByWarehousePlatformCode.sys_express_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: sysExpressName || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + + const orderMetaMap = new Map(); + for (const order of normalizedOrders) { + const orderDelivery = order && order.order_delivery; + const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0; + const orderId = Number(orderDelivery && orderDelivery.id) || 0; + const businessKey = Number(order && order.business_key) || 0; + if (!warehouseId || !orderId || !businessKey) { + continue; + } + + orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, { + store_id: Number(orderDelivery && orderDelivery.store_id) || 0, + warehouse_id: warehouseId, + }); + } + + const settlementRelationMap = new Map(); + for (const item of successUpdates) { + const relationMeta = orderMetaMap.get(`${item.warehouse_id}_${item.order_id}_${item.business_key}`); + if (!relationMeta || !relationMeta.store_id || !relationMeta.warehouse_id) { + continue; + } + + const relationKey = `${relationMeta.store_id}:${relationMeta.warehouse_id}`; + const currentRelation = settlementRelationMap.get(relationKey) || { + store_id: relationMeta.store_id, + warehouse_id: relationMeta.warehouse_id, + success_count: 0, + }; + currentRelation.success_count += 1; + settlementRelationMap.set(relationKey, currentRelation); + } + + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) { + await this.ctx.model.transaction(async transaction => { + // 统一加锁顺序:先锁 store_warehouse 再更新 order_express, + // 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁 + await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction); + + for (const item of successUpdates) { + if (!item.warehouse_id || !item.order_id || !item.business_key) { + throw new Error('拼多多平台接口返回 object_id 无法解析'); + } + + await this.ctx.model.OrderExpress.update(item.orderExpressValues, { + where: { + order_id: item.order_id, + business_key: item.business_key, + warehouse_id: item.warehouse_id, + }, + transaction, + }); + + const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id); + if (item.orderDeliveryValues && orderModel && typeof orderModel.update === 'function') { + await orderModel.update(item.orderDeliveryValues, { + where: { + id: item.order_id, + }, + transaction, + }); + } + } + }); + } + + const operationLogService = this.service && this.service.systems && this.service.systems.operationLog; + const operator = this.getOrderLogOperator(); + const logPayloads = successUpdates + .filter(item => item.warehouse_id && item.order_id) + .map(item => ({ + businessType: 'order', + businessId: `${item.order_id}`, + operationCode: 'WAYBILL', + operator, + extras: { + message: `订单${item.order_id}获取快递单成功,单号:${item.waybill_code}`, + warehouseId: item.warehouse_id, + externalLogType: 'API', + }, + })); + if (operationLogService && typeof operationLogService.createOperationLogs === 'function' && logPayloads.length > 0) { + await operationLogService.createOperationLogs(logPayloads); + } + + // 自动同步回传:快递号分配成功后异步触发订单同步 + try { + const settlementEntries = Array.from(settlementRelationMap.entries()); + for (const [ key, relation ] of settlementEntries) { + const successCount = Number(relation && relation.success_count) || 0; + if (successCount <= 0) continue; + const [ storeId, warehouseId ] = key.split(':').map(Number); + if (!storeId || !warehouseId) continue; + + const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( + warehouseId, + storeId + ); + if ( + contractConfig + && contractConfig.policy_config + && contractConfig.policy_config.auto_sync_back === 1 + ) { + // 收集本次分配成功的订单ID + const syncedOrderIds = successUpdates + .filter(u => { + const orderId = Number(u.order_id) || 0; + const wid = Number(u.warehouse_id) || 0; + const bk = Number(u.business_key) || 0; + const meta = orderMetaMap.get(`${wid}_${orderId}_${bk}`); + return meta && meta.store_id === storeId && wid === warehouseId; + }) + .map(u => Number(u.order_id) || 0) + .filter(Boolean); + + if (syncedOrderIds.length > 0) { + // SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过 + const autoSyncFilter = await this.ctx.service.systemMethods.order.pendingOrder.filterAutoSyncSnOrderIds({ + orderIds: syncedOrderIds, + warehouseId, + source: 'pdd', + }); + if (autoSyncFilter.orderIds.length > 0) { + // 异步调用,不阻塞主流程 + // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, + // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 + this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + orderIds: autoSyncFilter.orderIds, + warehouseId, + }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] pdd 自动同步失败: ${err.message}` + ); + }); + } + } + } + } + } catch (err) { + this.ctx.logger.error( + `[auto_sync_back] pdd 自动同步异常: ${err.message}` + ); + } + + return { + flag: true, + code: 0, + message: '拼多多平台数据处理成功', + data: responseData, + }; + } catch (error) { + console.log('拼多多平台接口返回异常', error && error.message ? error.message : `${error}`); + throw error; + } + } + + /** + * 规范化 OMS 取号订单项。 + * + * 兼容两种入参形态: + * - 队列/流水线风格:`{ order_id, business_key, order_delivery: {...} }` + * - 展平风格:直接把订单字段放在数组项上 + * + * @param {Array} orders 订单列表。 + * @return {Array} 规范化后的订单项。 + */ + normalizeOmsWaybillOrders(orders = []) { + const normalized = []; + + for (const item of normalizeArray(orders)) { + if (!item || typeof item !== 'object') { + continue; + } + + const orderDelivery = item.order_delivery && typeof item.order_delivery === 'object' + ? item.order_delivery + : item; + const orderId = Number(orderDelivery.id || orderDelivery.order_id || item.order_id) || 0; + + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + const businessKey = Number(item.business_key || item.businessKey) || 1; + const expressCode = String( + orderDelivery.logistics_code + || orderDelivery.sys_logistics_code + || orderDelivery.express_code + || '' + ).trim().toUpperCase(); + + normalized.push({ + order_id: orderId, + business_key: businessKey, + delivery_order_code: String( + orderDelivery.delivery_order_code || orderDelivery.deliveryOrderCode || '' + ).trim(), + express_code: expressCode, + store_id: Number(orderDelivery.store_id) || 0, + warehouse_id: Number(orderDelivery.warehouse_id) || 0, + source_order_codes: orderDelivery.source_order_codes || null, + from_key: String(orderDelivery.from_key || '').trim(), + // 打印按来源平台(wms_print_platform.platform_code)匹配模板,不能落 'oms' + platform_code: String( + orderDelivery.sys_platform_code || orderDelivery.source_platform_code || '' + ).trim().toUpperCase(), + }); + } + + return normalized; + } + + /** + * 加载「系统平台编码 -> 打印平台编码」映射。 + * + * 与 `express.js createWaybillCodePipeline` 同源同参(`getPlatformList(true, true)`), + * 保证本地取号与 OMS 回源取号算出的平台码口径一致。 + * 映射缺失时返回空 Map,调用方按原值兜底,不影响取号主流程。 + * + * @return {Promise>} 系统平台编码(大写)到打印平台编码(大写)的映射。 + */ + async buildWaybillPrintPlatformCodeMap() { + const platformService = this.service && this.service.systems && this.service.systems.platform; + + if (!platformService || typeof platformService.getPlatformList !== 'function') { + this.ctx.logger.warn('[ExpressPlatformService.buildWaybillPrintPlatformCodeMap] platform 服务不可用,平台码不做归一'); + return new Map(); + } + + let platformList = []; + try { + platformList = await platformService.getPlatformList(true, true); + } catch (error) { + this.ctx.logger.warn('[ExpressPlatformService.buildWaybillPrintPlatformCodeMap] 平台列表加载失败,平台码不做归一', { + error: error && error.message ? error.message : `${error}`, + }); + return new Map(); + } + + const printPlatformCodeMap = new Map(); + for (const platform of normalizeArray(platformList)) { + const platformCode = String(platform && platform.code || '').trim().toUpperCase(); + const printPlatformCode = String(platform && platform.default_express_interface || '').trim().toUpperCase(); + if (platformCode && printPlatformCode) { + printPlatformCodeMap.set(platformCode, printPlatformCode); + } + } + + return printPlatformCodeMap; + } + + /** + * 将平台码归一为打印平台编码。 + * + * 落库口径统一为 `wms_print_platform.platform_code`: + * 本地取号取的是 `wms_express_interface.platform_code`(已是打印平台码), + * OMS 回源取号的来源平台码(如 DYXD)必须映射成同一编码后再落库。 + * + * @param {string} platformCode 原始平台码。 + * @param {Map} [printPlatformCodeMap] 平台码映射。 + * @return {string} 归一后的平台码;无法归一或为空时返回原值(大写)。 + */ + resolveWaybillPrintPlatformCode(platformCode, printPlatformCodeMap = new Map()) { + const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); + + if (!normalizedPlatformCode) { + return ''; + } + + const mappedPlatformCode = printPlatformCodeMap instanceof Map + ? printPlatformCodeMap.get(normalizedPlatformCode) + : ''; + + return String(mappedPlatformCode || normalizedPlatformCode).trim().toUpperCase(); + } + + /** + * 就地归一 OMS 取号订单项的平台码。 + * + * @param {Array} items 归一化后的 OMS 取号订单项。 + * @param {Map} [printPlatformCodeMap] 平台码映射。 + * @return {Array} 归一后的订单项。 + */ + applyWaybillPrintPlatformCodes(items = [], printPlatformCodeMap = new Map()) { + for (const item of normalizeArray(items)) { + if (!item || typeof item !== 'object') { + continue; + } + item.platform_code = this.resolveWaybillPrintPlatformCode(item.platform_code, printPlatformCodeMap); + } + + return items; + } + + /** + * 为 OMS 淘宝(菜鸟)运单回拼 printinfo 整包。 + * + * OMS 取号把菜鸟加密面单拆成 `signature` / `encryptprintinfo` / `ver` 平铺返回, + * `printinfo` 恒为空串;而 WMS 菜鸟打印只认 `printinfo` 里的 + * `{ encryptedData, signature, ver }`(见 app/lib/printer_data_builder.js 的菜鸟分支)。 + * 不回拼会导致打印退化成模板兜底(`_dataFrom='template'`),与菠萝派取号单输出不一致。 + * + * 取值原样保留密文前缀(`AES:` / `MD:`),不做解码。 + * + * @param {string} platformCode 归一后的平台编码。 + * @param {Object} orderExpressValues 待写入的运单字段集合。 + * @return {string} 可直接落库的 printinfo JSON;不适用时返回空字符串。 + */ + buildOmsCainiaoPrintinfo(platformCode, orderExpressValues = {}) { + const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); + + // CAINIAO 为归一后的打印平台码;TB 为归一失败时的原始码(打印侧同样归一为菜鸟) + if (normalizedPlatformCode !== 'CAINIAO' && normalizedPlatformCode !== 'TB') { + return ''; + } + + const values = orderExpressValues && typeof orderExpressValues === 'object' ? orderExpressValues : {}; + + if (String(values.printinfo || '').trim()) { + return ''; + } + + const encryptedData = String(values.encryptprintinfo || '').trim(); + if (!encryptedData) { + return ''; + } + + const payload = { encryptedData }; + const signature = String(values.signature || '').trim(); + if (signature) { + payload.signature = signature; + } + const version = String(values.ver || '').trim(); + if (version) { + payload.ver = version; + } + + return JSON.stringify(payload); + } + + /** + * 剔除上游未返回(null/undefined/空串)的运单报文字段。 + * + * 命中的字段不做写入,交由数据库保留已有值,避免 OMS 回源取号把本地已落库的报文冲成空。 + * + * @param {Object} [values={}] 待写入 `wms_order_express` 的字段集合。 + * @return {Object} 剔除空值后的字段集合。 + */ + dropEmptyOrderExpressFields(values = {}) { + const source = values && typeof values === 'object' ? values : {}; + const sanitized = { ...source }; + + for (const field of ORDER_EXPRESS_UPSTREAM_OPTIONAL_FIELDS) { + if (!Object.prototype.hasOwnProperty.call(sanitized, field)) { + continue; + } + const value = sanitized[field]; + if (value === null || value === undefined || String(value).trim() === '') { + delete sanitized[field]; + } + } + + return sanitized; + } + + /** + * 按货主 + 仓库反查可用于回调 OMS 的 OpenAPI 应用配置。 + * + * @param {number} storeId 货主 ID。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} { appKey, selfAppSecret, callbackUrl } 或 null。 + */ + async resolveOmsWaybillAppConfig(storeId, warehouseId) { + const orderAsyncService = this.service && this.service.systems && this.service.systems.orderAsync; + + if (!orderAsyncService || typeof orderAsyncService.resolveOpenApiAppByStore !== 'function') { + return null; + } + + return await orderAsyncService.resolveOpenApiAppByStore(storeId, warehouseId); + } + + /** + * 为待取号订单解析回 OMS 用的 appKey。 + * + * 优先使用订单 `from_key`(建单时落库的来源应用 appKey,即 api_app.self_app_key), + * 缺失时按「货主 + 仓库」反查授权关系下的启用 ApiApp。 + * + * @param {Array} items 归一化后的订单项(就地写入 app_key)。 + * @return {Promise} 无返回值。 + */ + async attachOmsWaybillAppKeys(items = []) { + const cache = new Map(); + + for (const item of normalizeArray(items)) { + if (item.from_key) { + item.app_key = item.from_key; + item.app_key_source = 'order.from_key'; + continue; + } + + const cacheKey = `${item.store_id}:${item.warehouse_id}`; + if (!cache.has(cacheKey)) { + const appConfig = await this.resolveOmsWaybillAppConfig(item.store_id, item.warehouse_id); + cache.set(cacheKey, String(appConfig && appConfig.appKey || '').trim()); + } + + item.app_key = cache.get(cacheKey); + item.app_key_source = 'store_warehouse.api_app'; + } + } + + /** + * 生成稳定的 OMS 幂等 request_id。 + * + * 摘要输入采用与菠萝派/菜鸟/拼多多一致的包裹标识 + * `warehouse_id(16进制)_order_id(16进制)_business_key`, + * 同批(同一组包裹)在重试时得到相同值,OMS 会直接回放上次响应, + * 避免重复调用打单平台产生重复面单。 + * + * @param {number} warehouseId 仓库 ID(订单项缺 warehouse_id 时兜底)。 + * @param {Array} items 本批订单项。 + * @return {string} request_id(不超过 OMS 100 字符上限)。 + */ + buildOmsWaybillRequestId(warehouseId, items = []) { + const objectIds = normalizeArray(items) + .map(item => { + const warehouseHex = (Number(item.warehouse_id) || Number(warehouseId) || 0).toString(16); + const orderHex = (Number(item.order_id) || 0).toString(16); + const businessKey = Number(item.business_key) || 1; + + return `${warehouseHex}_${orderHex}_${businessKey}`; + }) + .sort(); + + return `oms-getwaybill-${crypto.createHash('md5').update(objectIds.join(','), 'utf8').digest('hex')}`; + } + + /** + * 生成 OMS 取号报文缓存的键集合。 + * + * 除固定 latest 键外,再按 request_id 落一份,便于用日志里的 request_id 直接定位。 + * + * @param {string} [requestId=''] 本次取号的 request_id。 + * @return {{ request: string, response: string, responseByRequestId: string }} 缓存键集合。 + */ + buildOmsWaybillPayloadCacheKeys(requestId = '') { + const normalizedRequestId = String(requestId || '').trim(); + + return { + request: `${OMS_WAYBILL_PAYLOAD_CACHE_KEY_PREFIX}:request:latest`, + response: `${OMS_WAYBILL_PAYLOAD_CACHE_KEY_PREFIX}:response:latest`, + responseByRequestId: normalizedRequestId + ? `${OMS_WAYBILL_PAYLOAD_CACHE_KEY_PREFIX}:response:${normalizedRequestId}` + : '', + }; + } + + /** + * 按字段名截断报文中的密文/大字段。 + * + * 仅改写命中 {@link OMS_WAYBILL_PAYLOAD_HEAVY_FIELDS} 且超长的字符串取值, + * 其余字段(含层级结构)原样保留,确保缓存内容仍能反映真实报文格式。 + * + * @param {*} value 报文节点。 + * @param {number} [depth=0] 当前递归深度,超过 10 层不再下钻。 + * @return {*} 处理后的报文节点。 + */ + truncateOmsWaybillPayloadFields(value, depth = 0) { + if (depth > 10 || value === null || typeof value !== 'object') { + return value; + } + + if (Array.isArray(value)) { + return value.map(item => this.truncateOmsWaybillPayloadFields(item, depth + 1)); + } + + const truncated = {}; + for (const [ key, item ] of Object.entries(value)) { + const isHeavyField = OMS_WAYBILL_PAYLOAD_HEAVY_FIELDS.includes(String(key).toLowerCase()); + if (isHeavyField + && typeof item === 'string' + && item.length > OMS_WAYBILL_PAYLOAD_HEAVY_FIELD_KEEP_CHARS) { + truncated[key] = `${item.slice(0, OMS_WAYBILL_PAYLOAD_HEAVY_FIELD_KEEP_CHARS)}...(truncated,total=${item.length})`; + continue; + } + truncated[key] = this.truncateOmsWaybillPayloadFields(item, depth + 1); + } + + return truncated; + } + + /** + * 缓存 OMS 回源取号的请求与返回报文。 + * + * OMS 返回的报文格式是与 OMS 对齐的唯一依据,落缓存后可直接用 + * `script/redis-cache.ps1 -Action get -Key ` 取回核对,不再依赖日志留存。 + * 缓存失败只告警,绝不影响取号结果。 + * + * 缓存键(TTL 见 {@link OMS_WAYBILL_PAYLOAD_CACHE_TTL}): + * - `oms:waybill:request:latest`:最近一次请求体 + * - `oms:waybill:response:latest`:最近一次完整快照(元信息 + 请求 + 返回报文) + * - `oms:waybill:response:`:按 request_id 归档的同一份快照 + * + * @param {Object} [payload={}] 快照数据。 + * @param {string} [payload.request_id] 本次取号 request_id。 + * @param {string} [payload.app_key] 目标 OMS 应用 appKey。 + * @param {number} [payload.warehouse_id] 仓库 ID。 + * @param {number} [payload.store_id] 货主 ID。 + * @param {number} [payload.order_count] 本次批次订单数。 + * @param {Array} [payload.delivery_order_codes] 本次批次发货单号。 + * @param {Object} [payload.transport] 传输层结果(success/retry_count/error)。 + * @param {Object} [payload.request] 实际下发的请求体。 + * @param {*} [payload.response] OMS 原始返回报文。 + * @return {Promise} 缓存键与字节数;未缓存时返回 null。 + */ + async cacheOmsWaybillPayload(payload = {}) { + const app = this.ctx && this.ctx.app; + const cacheKeys = this.buildOmsWaybillPayloadCacheKeys(payload.request_id); + + if (!app || typeof app.setCacheAsync !== 'function') { + return null; + } + + const snapshot = { + cached_at: new Date().toISOString(), + request_id: String(payload.request_id || ''), + app_key: String(payload.app_key || ''), + event: OMS_WAYBILL_EVENT, + warehouse_id: Number(payload.warehouse_id) || 0, + store_id: Number(payload.store_id) || 0, + order_count: Number(payload.order_count) || 0, + delivery_order_codes: normalizeArray(payload.delivery_order_codes), + transport: payload.transport || {}, + request: payload.request === undefined ? null : payload.request, + response: payload.response === undefined ? null : payload.response, + payload_truncated: false, + }; + + let payloadBytes = Buffer.byteLength(JSON.stringify(snapshot), 'utf8'); + + if (payloadBytes > OMS_WAYBILL_PAYLOAD_CACHE_MAX_BYTES) { + snapshot.request = this.truncateOmsWaybillPayloadFields(snapshot.request); + snapshot.response = this.truncateOmsWaybillPayloadFields(snapshot.response); + snapshot.payload_truncated = true; + payloadBytes = Buffer.byteLength(JSON.stringify(snapshot), 'utf8'); + } + + if (payloadBytes > OMS_WAYBILL_PAYLOAD_CACHE_MAX_BYTES) { + // 脱敏后仍超限:响应只留元信息,避免把 Redis 打爆 + snapshot.response = ``; + payloadBytes = Buffer.byteLength(JSON.stringify(snapshot), 'utf8'); + } + + try { + await app.setCacheAsync(cacheKeys.request, snapshot.request, OMS_WAYBILL_PAYLOAD_CACHE_TTL); + await app.setCacheAsync(cacheKeys.response, snapshot, OMS_WAYBILL_PAYLOAD_CACHE_TTL); + if (cacheKeys.responseByRequestId) { + await app.setCacheAsync(cacheKeys.responseByRequestId, snapshot, OMS_WAYBILL_PAYLOAD_CACHE_TTL); + } + } catch (error) { + this.ctx.logger.warn('[ExpressPlatformService.oms] OMS 取号报文缓存写入失败', { + requestId: snapshot.request_id, + error: error && error.message ? error.message : `${error}`, + }); + return null; + } + + this.ctx.logger.info('[ExpressPlatformService.oms] OMS 取号报文已缓存', { + requestId: snapshot.request_id, + cacheKey: cacheKeys.response, + requestIdCacheKey: cacheKeys.responseByRequestId, + ttlSeconds: OMS_WAYBILL_PAYLOAD_CACHE_TTL, + payloadBytes, + truncated: snapshot.payload_truncated, + }); + + return { + ...cacheKeys, + payloadBytes, + }; + } + + /** + * 判断 OMS 逐单失败原因是否值得重试。 + * + * @param {string} message OMS 返回的失败原因。 + * @return {boolean} 可重试返回 true。 + */ + isRetryableOmsWaybillMessage(message) { + const text = String(message || '').trim(); + + if (!text) { + return false; + } + + return !OMS_WAYBILL_NON_RETRYABLE_KEYWORDS.some(keyword => text.includes(keyword)); + } + + /** + * 为回 OMS 取号的订单补齐 order_express 占位行。 + * + * 这类订单被本地取号流水线整体跳过(不建占位行),若不补齐, + * 取号成功后的 update 会因无匹配行而丢失运单号。 + * + * @param {Array} items 本次取号成功的订单项。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 无返回值。 + */ + async ensureOmsWaybillOrderExpressRows(items = [], warehouseId = 0) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + const normalizedItems = normalizeArray(items).filter(item => item.order_id); + + if (!orderExpressModel + || typeof orderExpressModel.findAll !== 'function' + || typeof orderExpressModel.bulkCreate !== 'function' + || normalizedItems.length === 0) { + return; + } + + const { Op } = this.app.Sequelize; + const existingRows = await orderExpressModel.findAll({ + where: { + order_id: { + [Op.in]: normalizedItems.map(item => item.order_id), + }, + }, + attributes: [ 'order_id', 'business_key' ], + raw: true, + }); + const existingKeySet = new Set( + normalizeArray(existingRows).map(row => `${Number(row.order_id)}:${Number(row.business_key) || 1}`) + ); + const rowsToCreate = normalizedItems + .filter(item => !existingKeySet.has(`${item.order_id}:${item.business_key}`)) + .map(item => ({ + order_id: item.order_id, + business_key: item.business_key, + status: 0, + retry_count: 0, + warehouse_id: item.warehouse_id || warehouseId, + store_id: item.store_id || null, + logistics_code: item.express_code || '', + delivery_order_code: item.delivery_order_code || null, + source_order_codes: item.source_order_codes || null, + })); + + if (rowsToCreate.length === 0) { + return; + } + + await orderExpressModel.bulkCreate(rowsToCreate, { ignoreDuplicates: true }); + } + + /** + * OMS 回源取号(deliveryorder.getwaybill)。 + * + * 处理 need_oms_waybill=1 的订单:不调本地快递平台,改由 OMS 侧的 + * 外部打单账号取号,回传运单号后写入 order_express 并把订单置为已分配快递。 + * + * 约定: + * - 单批最多 100 单(OMS 硬上限),超出自动切分; + * - request_id 由订单集合推导,重试复用同一值以命中 OMS 幂等; + * - 有失败时抛错,`error.retryable` 标记是否值得重试,由队列消费侧决定状态。 + * + * @param {Object} data 业务数据骨架(orders / warehouse_id / store_id)。 + * @return {Promise} 处理结果。 + */ + async oms(data = {}) { + const source = data && typeof data === 'object' ? data : {}; + const warehouseIdHint = Number(source.warehouse_id || source.warehouseId) || 0; + const storeIdHint = Number(source.store_id || source.storeId) || 0; + const rawOrders = normalizeArray(source.orders); + const items = this.normalizeOmsWaybillOrders(rawOrders); + + if (items.length === 0) { + return { + flag: 'success', + code: 0, + message: '没有需要回 OMS 取号的订单', + data: { total: 0, success: 0, failed: 0, results: [] }, + }; + } + + // 平台码统一归一为打印平台码,与本地取号落库口径保持一致(避免把 DYXD 这类来源平台码写进 order_express) + const printPlatformCodeMap = await this.buildWaybillPrintPlatformCodeMap(); + this.applyWaybillPrintPlatformCodes(items, printPlatformCodeMap); + + const startedAt = Date.now(); + const callbackService = this.service && this.service.openapi && this.service.openapi.callback; + const ExpressList = await this.service.systems.express.loadExpressList(); + const aggregatedResults = []; + const failedMessages = []; + const successUpdates = []; + const successItems = []; + let retryable = false; + let successCount = 0; + + await this.attachOmsWaybillAppKeys(items); + + // 按 appKey 分组后再按 100 切分:不同 OMS 应用/仓库不能混在同一批 + const appKeyGroupMap = new Map(); + for (const item of items) { + const groupKey = String(item.app_key || '').trim(); + if (!appKeyGroupMap.has(groupKey)) { + appKeyGroupMap.set(groupKey, []); + } + appKeyGroupMap.get(groupKey).push(item); + } + + const batches = []; + for (const [ groupAppKey, groupItems ] of appKeyGroupMap.entries()) { + for (let offset = 0; offset < groupItems.length; offset += OMS_WAYBILL_MAX_BATCH_SIZE) { + batches.push({ + appKey: groupAppKey, + orders: groupItems.slice(offset, offset + OMS_WAYBILL_MAX_BATCH_SIZE), + }); + } + } + + for (const { appKey, orders: batch } of batches) { + if (!appKey) { + for (const item of batch) { + failedMessages.push( + `${item.delivery_order_code || item.order_id}: 订单缺少来源应用 appKey,且货主 ${item.store_id} 仓库 ${item.warehouse_id} 未配置可用的 OpenAPI 应用` + ); + } + continue; + } + + const warehouseId = Number(batch[0].warehouse_id) || warehouseIdHint; + + if (!callbackService || typeof callbackService.sendByAppKey !== 'function') { + throw new Error('OpenAPI 回调服务不可用,无法回 OMS 取号'); + } + + const requestId = this.buildOmsWaybillRequestId(warehouseId, batch); + const callbackRequest = { + orders: batch.map(item => ({ + deliveryOrderCode: item.delivery_order_code, + expressCode: item.express_code, + // 包裹序号(0 基):不传时 OMS 按单号尾部 _N 推导,主单子单会撞成同一个包裹 + packageIndex: Math.max((Number(item.business_key) || 1) - 1, 0), + })), + request_id: requestId, + }; + const callbackResult = await callbackService.sendByAppKey({ + appKey, + event: OMS_WAYBILL_EVENT, + request: callbackRequest, + }); + + // 无论成功失败都缓存请求/返回报文:OMS 返回格式是与 OMS 对齐的唯一依据 + await this.cacheOmsWaybillPayload({ + request_id: requestId, + app_key: appKey, + warehouse_id: warehouseId, + store_id: Number(batch[0].store_id) || storeIdHint, + order_count: batch.length, + delivery_order_codes: batch.map(item => item.delivery_order_code).filter(Boolean), + transport: { + success: Boolean(callbackResult && callbackResult.success), + retry_count: Number(callbackResult && callbackResult.retryCount) || 0, + error: callbackResult && callbackResult.error ? String(callbackResult.error) : null, + }, + request: callbackRequest, + response: callbackResult ? callbackResult.response : null, + }); + + if (!callbackResult || callbackResult.success !== true) { + const transportError = new Error( + `OMS 取号请求失败: ${callbackResult && callbackResult.error ? callbackResult.error : '未知错误'}` + ); + transportError.retryable = true; + throw transportError; + } + + const responseBody = callbackResult.response && typeof callbackResult.response === 'object' + ? callbackResult.response + : {}; + const responseCode = Number(responseBody.code) || 0; + const responseFlag = String(responseBody.flag || '').trim().toLowerCase(); + + if (responseFlag !== 'success' || responseCode !== 1) { + const responseMessage = String(responseBody.message || 'OMS 取号返回失败').trim(); + const businessError = new Error(`OMS 取号返回失败(code=${responseCode}): ${responseMessage}`); + businessError.retryable = responseCode === 409 || responseCode >= 500; + throw businessError; + } + + const responseResults = normalizeArray(responseBody.data && responseBody.data.results); + + if (responseResults.length !== batch.length) { + const countError = new Error( + `OMS 取号返回数量异常: 请求 ${batch.length} 条,返回 ${responseResults.length} 条` + ); + countError.retryable = true; + throw countError; + } + + for (let index = 0; index < batch.length; index++) { + const item = batch[index]; + const row = responseResults[index] || {}; + const isSuccess = row.success === true; + const waybillCode = String(row.waybill_code || '').trim(); + const rowMessage = String(row.message || '').trim(); + + aggregatedResults.push({ + delivery_order_code: item.delivery_order_code, + success: isSuccess, + message: rowMessage || (isSuccess ? 'ok' : 'OMS 未返回失败原因'), + waybill_code: waybillCode, + }); + + if (!isSuccess) { + failedMessages.push(`${item.delivery_order_code || item.order_id}: ${rowMessage || '取号失败'}`); + if (this.isRetryableOmsWaybillMessage(rowMessage)) { + retryable = true; + } + continue; + } + + if (!waybillCode) { + failedMessages.push(`${item.delivery_order_code || item.order_id}: OMS 返回成功但运单号为空`); + retryable = true; + continue; + } + + // 回显的包裹序号必须与请求一致,否则运单号可能被落到错误的包裹行 + const expectedPackageIndex = Math.max((Number(item.business_key) || 1) - 1, 0); + const responsePackageIndex = Number(row.package_index); + if (typeof row.package_index !== 'undefined' + && row.package_index !== null + && row.package_index !== '' + && Number.isInteger(responsePackageIndex) + && responsePackageIndex !== expectedPackageIndex) { + failedMessages.push( + `${item.delivery_order_code || item.order_id}: OMS 返回包裹序号不一致(期望 ${expectedPackageIndex},返回 ${responsePackageIndex})` + ); + retryable = true; + continue; + } + + const expressCode = String(row.express_code || item.express_code || '').trim().toUpperCase(); + const expressName = (ExpressList.find(entry => entry.code === expressCode) || {}).name || ''; + // 平台码先归一为打印平台码再落库:item.platform_code 已在入口归一, + // OMS 回传的 platform_code 同样要过一遍映射,禁止落 'oms' 或来源平台码。 + const responsePlatformCode = this.resolveWaybillPrintPlatformCode(row.platform_code, printPlatformCodeMap); + const platformCode = String(item.platform_code || responsePlatformCode || '').trim().toUpperCase(); + // 打印定位字段:print_history_id 用于打印前回 OMS 换新 params, + // cai_niao_auth_info_id 用于打印时按店铺(授权网点)分组,一组只换一次 params + const printHistoryId = String( + row.print_history_id + || (Array.isArray(row.print_history_ids) && row.print_history_ids[0] && row.print_history_ids[0].id) + || '' + ).trim(); + const caiNiaoAuthInfoId = Number(row.cai_niao_auth_info_id) || 0; + // 面单打印数据与签名:OMS 原样透传,打印时必须原样下发(不要解码 base64/URL 编码); + // 上游未返回的报文字段不写库,避免把已有有效值冲成空。 + const orderExpressValues = this.dropEmptyOrderExpressFields({ + waybill_code: waybillCode, + status: 1, + retry_count: 0, + create_at: new Date(), + delivery_order_code: item.delivery_order_code || null, + source_order_codes: item.source_order_codes || null, + store_id: item.store_id || null, + logistics_code: expressCode, + logistics_name: expressName, + printinfo: String(row.printinfo || '') || null, + signature: String(row.signature || '') || null, + // 快手口径的加密密钥由 encryptprintinfo 承载;OMS 新版另给 key 字段,作为兜底 + encryptprintinfo: String( + row.encryptprintinfo + || (platformCode === 'KS' ? row.key : '') + || '' + ) || null, + ver: String(row.ver || '') || null, + }); + if (platformCode) { + orderExpressValues.platform_code = platformCode; + } + if (printHistoryId) { + orderExpressValues.print_history_id = printHistoryId; + } + if (caiNiaoAuthInfoId > 0) { + orderExpressValues.cai_niao_auth_info_id = caiNiaoAuthInfoId; + } + // 菜鸟(淘宝)打印只认 printinfo 整包:OMS 恒回空串、把密文拆成平铺字段, + // 这里按菜鸟规范回拼,保证与菠萝派取号落库结构一致 + const omsCainiaoPrintinfo = this.buildOmsCainiaoPrintinfo(platformCode, orderExpressValues); + if (omsCainiaoPrintinfo) { + orderExpressValues.printinfo = omsCainiaoPrintinfo; + } + successCount += 1; + successItems.push(item); + successUpdates.push({ + warehouse_id: item.warehouse_id || warehouseId, + order_id: item.order_id, + business_key: item.business_key, + waybill_code: waybillCode, + orderExpressValues, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }); + } + } + + if (successUpdates.length > 0) { + const successWarehouseId = Number(successUpdates[0].warehouse_id) || warehouseIdHint; + await this.ensureOmsWaybillOrderExpressRows(successItems, successWarehouseId); + await this.persistWaybillSuccessUpdates(successUpdates, rawOrders); + } + + this.ctx.logger.info('[ExpressPlatformService.oms] 回 OMS 取号完成', { + warehouseId: warehouseIdHint, + storeId: storeIdHint, + total: items.length, + success: successCount, + failed: failedMessages.length, + retryable, + durationMs: Date.now() - startedAt, + firstFailure: failedMessages[0] || '', + }); + + if (failedMessages.length > 0) { + const failureError = new Error(failedMessages.join('; ')); + failureError.retryable = retryable; + throw failureError; + } + + return { + flag: 'success', + code: 0, + message: `回 OMS 取号成功 ${successCount} 单`, + data: { + total: items.length, + success: successCount, + failed: 0, + results: aggregatedResults, + }, + }; + } +} + +// 静态挂载 Uint64 工具:供回包解析(SPH object_Id 反解)等场景复用 +ExpressPlatformService.toUint64 = toUint64; +ExpressPlatformService.fromUint64 = fromUint64; + +module.exports = ExpressPlatformService; diff --git a/app/service/systems/express_policy.js b/app/service/systems/express_policy.js new file mode 100644 index 0000000..19107f6 --- /dev/null +++ b/app/service/systems/express_policy.js @@ -0,0 +1,304 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 快递策略内部服务。 + * + * 为快递匹配链路提供策略查询能力,内置缓存加速。 + * 不对外暴露 method 路由,仅供其他 service 内部调用。 + */ +class ExpressPolicyService extends Service { + // -------------------- 缓存键 -------------------- + + /** + * 仓库维度策略列表缓存键。 + * @param {number} warehouseId 仓库 ID + * @return {string} 缓存键 + */ + getWarehousePolicyCacheKey(warehouseId) { + return `express_policy:warehouse:${warehouseId}`; + } + + /** + * 仓库维度策略缓存过期秒数(默认 300s)。 + * @return {number} 过期秒数 + */ + getWarehousePolicyCacheTTL() { + return 300; + } + + // -------------------- 缓存清理 -------------------- + + /** + * 清理指定仓库的策略缓存。 + * @param {number} warehouseId 仓库 ID + * @return {Promise} + */ + async clearWarehousePolicyCache(warehouseId) { + const cacheKey = this.getWarehousePolicyCacheKey(warehouseId); + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(cacheKey); + } + } + + // -------------------- 数据查询 -------------------- + + /** + * 从数据库查询仓库下所有启用的策略,按优先级降序排列。 + * @param {number} warehouseId 仓库 ID + * @return {Promise>} 策略列表(plain object) + */ + async fetchWarehousePoliciesFromDB(warehouseId) { + const { ctx } = this; + + try { + const rows = await ctx.model.StoreExpressBindingPolicy.findAll({ + where: { + warehouse_id: warehouseId, + is_enabled: 1, + deleted_at: null, + }, + order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + return rows; + } catch (error) { + if (ctx.logger && typeof ctx.logger.warn === 'function') { + ctx.logger.warn('[ExpressPolicyDBError]', error.message, { warehouseId }); + } + return []; + } + } + + // -------------------- 对外方法 -------------------- + + /** + * 获取仓库策略目录(缓存优先)。 + * + * 查询链路:缓存命中 → 直接返回;缓存未命中 → 查库 → 写缓存 → 返回。 + * + * @param {number} warehouseId 仓库 ID + * @param {Object} [options] 选项 + * @param {boolean} [options.forceRefresh=false] 是否强制刷新缓存 + * @return {Promise>} 策略列表(按 priority DESC 排序) + */ + async getWarehousePolicies(warehouseId, options = {}) { + const { app } = this; + const { forceRefresh = false } = options; + + if (!Number.isFinite(Number(warehouseId)) || Number(warehouseId) <= 0) { + return []; + } + + const cacheKey = this.getWarehousePolicyCacheKey(warehouseId); + const ttl = this.getWarehousePolicyCacheTTL(); + + // 1) 读缓存(非强制刷新时) + if (!forceRefresh && app && typeof app.getCacheAsync === 'function') { + try { + const cached = await app.getCacheAsync(cacheKey); + if (cached && Array.isArray(cached) && cached.length > 0) { + return cached; + } + } catch (error) { + if (app.logger && typeof app.logger.warn === 'function') { + app.logger.warn('[ExpressPolicyCacheReadError]', error.message, { warehouseId }); + } + } + } + + // 2) 查库 + const policies = await this.fetchWarehousePoliciesFromDB(warehouseId); + + // 3) 写缓存 + if (app && typeof app.setCacheAsync === 'function') { + try { + await app.setCacheAsync(cacheKey, policies, ttl); + } catch (error) { + if (app.logger && typeof app.logger.warn === 'function') { + app.logger.warn('[ExpressPolicyCacheWriteError]', error.message, { warehouseId }); + } + } + } + + return policies; + } + + // -------------------- 策略匹配 -------------------- + + /** + * 检查 policy 中数组字段的任意值是否命中目标字符串(子串包含匹配)。 + * @param {Array|null} policyArray 策略中的数组字段 + * @param {string} target 目标字符串(如地址、店铺名称) + * @return {boolean} 是否命中 + */ + _matchAnyToken(policyArray, target) { + if (!Array.isArray(policyArray) || policyArray.length === 0) { + return true; // 未限定 = 不限制 + } + const normalizedTarget = String(target || '').trim(); + if (!normalizedTarget) { + return false; + } + return policyArray.some(token => { + const t = String(token || '').trim(); + return t && normalizedTarget.includes(t); + }); + } + + /** + * 检查两个数组是否有交集。 + * @param {Array<*>|null} policyArray 策略中的数组字段 + * @param {Array<*>|null} inputArray 传入的数组 + * @return {boolean} 是否有交集 + */ + _matchAnyIntersect(policyArray, inputArray) { + if (!Array.isArray(policyArray) || policyArray.length === 0) { + return true; // 未限定 = 不限制 + } + if (!Array.isArray(inputArray) || inputArray.length === 0) { + return false; + } + const policySet = new Set(policyArray.map(v => Number(v))); + return inputArray.some(v => policySet.has(Number(v))); + } + + /** + * 检查传入值是否在策略数组范围内。 + * @param {Array<*>|null} policyArray 策略中的数组字段 + * @param {number} value 传入值 + * @return {boolean} 是否命中 + */ + _matchValueInArray(policyArray, value) { + if (!Array.isArray(policyArray) || policyArray.length === 0) { + return true; // 未限定 = 不限制 + } + return policyArray.some(v => Number(v) === Number(value)); + } + + /** + * 判断策略是否为"纯货主维度"策略: + * store_ids 非空,且 shop_name / prohibited_type_id / regions / exclude_regions / 重量区间全部未限定。 + * + * @param {Object} policy 策略行 + * @return {boolean} 是否为纯货主策略 + */ + _isStoreOnlyPolicy(policy = {}) { + const asArray = v => (Array.isArray(v) ? v : []); + if (asArray(policy.store_ids).length === 0) { + return false; + } + const hasOtherDimension = asArray(policy.shop_name).length > 0 + || asArray(policy.prohibited_type_id).length > 0 + || asArray(policy.regions).length > 0 + || asArray(policy.exclude_regions).length > 0 + || (policy.min_weight_g !== null && policy.min_weight_g !== undefined) + || (policy.max_weight_g !== null && policy.max_weight_g !== undefined); + return !hasOtherDimension; + } + + /** + * 按策略优先级漏斗筛选,返回命中策略的快递编码与重量段类型。 + * + * 筛选顺序(按 priority DESC,同 priority 按 updated_at DESC): + * 1. store_ids —— 传入货主ID是否在策略限定范围内(NULL=不限) + * 2. shop_name —— 自定义店铺名称子串匹配(任意一个命中即通过) + * 3. prohibited_type_id —— 违禁品类型ID数组交集(有交集即命中) + * 4. regions —— 地址包含任意限定地区即命中 + * 5. exclude_regions —— 地址包含任意排除地区则跳过该策略 + * 6. min_weight_g / max_weight_g —— 重量区间 + * + * @param {number} warehouseId 仓库 ID + * @param {Object} params 匹配参数 + * @param {number} [params.storeId] 货主 ID + * @param {string} [params.customShopName] 自定义店铺名称 + * @param {Array} [params.prohibitedTypeIds] 商品违禁品类型 ID 数组 + * @param {string} [params.address] 省市区详细地址(单个字符串) + * @param {number} [params.weight] 重量(克) + * @param {Object} [options] 匹配选项 + * @param {boolean} [options.onlyStoreDimension=false] 仅匹配"纯货主维度"策略(store_ids 非空且其它维度全空) + * @return {Promise<{expressCode: string|null, weightType: number|null}>} 命中策略的快递编码与重量段类型,未命中时 expressCode 为 null + */ + async matchPolicy(warehouseId, params = {}, options = {}) { + const { + storeId, + customShopName, + prohibitedTypeIds, + address, + weight, + } = params; + const { onlyStoreDimension = false } = options; + + const policies = await this.getWarehousePolicies(warehouseId); + if (!Array.isArray(policies) || policies.length === 0) { + return { expressCode: null, weightType: null }; + } + + for (const policy of policies) { + // 0) 维度白名单:onlyStoreDimension 开启时跳过非纯货主策略 + if (onlyStoreDimension && !this._isStoreOnlyPolicy(policy)) { + continue; + } + + // 1) store_ids — 未限定(NULL)视为不限;否则传入 storeId 必须在范围内 + if (!this._matchValueInArray(policy.store_ids, storeId)) { + continue; + } + + // 2) shop_name — 子串包含匹配 + if (!this._matchAnyToken(policy.shop_name, customShopName)) { + continue; + } + + // 3) prohibited_type_id — 数组交集 + if (!this._matchAnyIntersect(policy.prohibited_type_id, prohibitedTypeIds)) { + continue; + } + + // 4) regions — 地址包含任意限定地区 + if (!this._matchAnyToken(policy.regions, address)) { + continue; + } + + // 5) exclude_regions — 地址包含任意排除地区则跳过 + if (Array.isArray(policy.exclude_regions) && policy.exclude_regions.length > 0) { + const excluded = policy.exclude_regions.some(token => { + const t = String(token || '').trim(); + return t && String(address || '').includes(t); + }); + if (excluded) { + continue; + } + } + + // 6) 重量区间 + const weightNum = Number(weight); + if (Number.isFinite(weightNum)) { + if (policy.min_weight_g !== null && policy.min_weight_g !== undefined) { + if (weightNum < Number(policy.min_weight_g)) { + continue; + } + } + if (policy.max_weight_g !== null && policy.max_weight_g !== undefined) { + if (weightNum > Number(policy.max_weight_g)) { + continue; + } + } + } + + // 全部通过 → 命中 + return { + expressCode: policy.express_code || null, + weightType: policy.weight_type !== undefined ? policy.weight_type : 0, + policyName: policy.custom_name || null, + policyId: policy.id || null, + }; + } + + // 无命中 + return { expressCode: null, weightType: null }; + } +} + +module.exports = ExpressPolicyService; diff --git a/app/service/systems/file.js b/app/service/systems/file.js index 1946ac6..a80583f 100644 --- a/app/service/systems/file.js +++ b/app/service/systems/file.js @@ -4,17 +4,23 @@ const Service = require('egg').Service; class FileService extends Service { async getImages(data) { const { ctx } = this; - const result = await ctx.model.FileReference.findAll({ where: { - business_type: data.type, - business_id: data.id, - }, include: [ - { - model: ctx.model.File, - as: 'file', - attributes: [ 'file_url', 'file_name' ], - required: true, + const result = await ctx.model.FileReference.findAll({ + where: { + business_type: data.type, + business_id: data.id, }, - ] }); + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ + 'file_url', + 'file_name', + ], + required: true, + }, + ], + }); return result; } async ReferenceFile(data) { @@ -22,9 +28,8 @@ class FileService extends Service { const { id, type, images } = data; const warehouseId = ctx.user.store_id; - console.log('<<>>>', type); switch (type) { - case 'stock': + case 'stock': { const stock = await ctx.model.StockWarehouse.findOne({ where: { warehouse_id: warehouseId, @@ -36,7 +41,6 @@ class FileService extends Service { if (!stock) { throw new Error('找不到商品'); } - console.log('<<>>>', images.length); if (images.length > 0) { await ctx.model.StockWarehouse.update({ is_images: 'Y' }, { @@ -66,9 +70,9 @@ class FileService extends Service { beforeChanges: null, }); break; - + } default: - // code + // code } // 获取现有的file_id const existingRefs = await ctx.model.FileReference.findAll({ diff --git a/app/service/systems/frontConfig.js b/app/service/systems/frontConfig.js new file mode 100644 index 0000000..323637a --- /dev/null +++ b/app/service/systems/frontConfig.js @@ -0,0 +1,2239 @@ +'use strict'; + +const crypto = require('node:crypto'); +// 域名验证 TXT 记录的兜底解析使用 Node 内置 DNS(本文件为全仓首次引入 node:dns): +// DoH(ctx.curl)多端点全部「未取到值」时降级为系统解析,且显式限时(见 resolveTxtBySystem); +// 仅服务域名验证链路,不参与业务主链路。 +const dns = require('node:dns'); + +const { Service } = require('egg'); + +// 仓库前端配置品牌文本字段元信息(对应 wms_warehouse_front_config,一仓一行)。 +// 域名与证书字段不在此列:domain 只能通过 frontConfig.setDomain 设置(并先通过域名验证), +// cert_pem/cert_key/cert_path/key_path 只能通过证书上传接口(saveCert)变更。 +const TEXT_FIELDS = Object.freeze([ + Object.freeze({ key: 'title', name: 'title', maxLength: 100 }), + Object.freeze({ key: 'logo_url', name: 'logo_url', maxLength: 255 }), + Object.freeze({ key: 'favicon_url', name: 'favicon_url', maxLength: 255 }), + Object.freeze({ key: 'login_bg_url', name: 'login_bg_url', maxLength: 255 }), +]); + +// 公共按域名拉取接口对外输出的字段白名单(安全红线:严禁输出证书/私钥内容与证书路径、同步状态等内部字段) +const PUBLIC_FIELDS = Object.freeze([ + 'domain', + 'title', + 'logo_url', + 'login_bg_url', + 'favicon_url', + 'theme', +]); + +// 公共按域名拉取接口缓存 TTL(秒) +const PUBLIC_CACHE_TTL_SECONDS = 600; +// 未登记域名空缓存 TTL(秒):短缓存兜底防穿透,域名登记后由保存流程主动失效 +const PUBLIC_MISS_CACHE_TTL_SECONDS = 60; + +// 证书/私钥 PEM 文本最大长度(正常 RSA/ECC 证书远小于该值,防止异常大报文) +const PEM_MAX_LENGTH = 64 * 1024; + +// 域名验证状态(与 wms_warehouse_front_config.domain_status 列及模型 validate 保持一致) +const DOMAIN_STATUS_UNVERIFIED = 0; +const DOMAIN_STATUS_VERIFIED = 1; +const DOMAIN_STATUS_FAILED = 2; + +// 域名形态:至少两段标签,每段 1~63 位、仅字母数字与连字符、首尾不得为连字符; +// 天然排除通配符 *、下划线、首尾点与单段主机名(长度上限由 normalizeText 的 ≤100 兜住) +const DOMAIN_PATTERN = /^(?!-)[A-Za-z0-9-]{1,63}(?} 无返回值。 + */ + async deleteCacheByKey(cacheKey) { + if (!cacheKey) { + return; + } + + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(cacheKey); + return; + } + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, null, 0); + } + } + + /** + * 校验并规范化仓库前端配置的字符串字段。 + * + * @param {*} value 原始值。 + * @param {string} fieldName 字段名。 + * @param {number} maxLength 字段最大长度。 + * @return {string|null} 规范化后的字符串;空值返回 null(表示清空)。 + * @throws {Error} 超长时抛出,状态码 400。 + */ + normalizeText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + return null; + } + + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength} 字符`, 400); + } + + return normalized; + } + + /** + * 校验并规范化仓库前端配置的 theme 字段。 + * + * @param {*} value 原始值(对象或 JSON 字符串)。 + * @return {Object|null} 规范化后的主题对象;空值返回 null(表示清空)。 + * @throws {Error} 非合法 JSON 对象时抛出,状态码 400。 + */ + normalizeTheme(value) { + if (value === undefined || value === null || value === '') { + return null; + } + + let parsed = value; + if (typeof value === 'string') { + try { + parsed = JSON.parse(value.trim()); + } catch (error) { + throw this.createError('theme 必须是合法的 JSON 对象', 400); + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw this.createError('theme 必须是合法的 JSON 对象', 400); + } + + return parsed; + } + + /** + * 校验非空 domain 的全局唯一性(可空列唯一索引允许多 NULL,数据库不兜底)。 + * + * 两阶段切换后「占用」的定义包含待验证域名:其他仓库的 domain 或 pending_domain + * 命中任一即视为已占用(否则两个仓库可同时把同一域名登记为待验证,直到「提升」时才在 + * domain 唯一索引上撞车)。注意 pending_domain 只有普通索引(非唯一), + * 并发提交仍可能绕过本校验,最终由 domain 唯一索引在提升时兜底。 + * + * @param {string} domain 待校验域名(非空,已小写化)。 + * @param {number} excludeWarehouseId 排除的仓库 ID(当前仓库自身)。 + * @return {Promise} 无返回值。 + * @throws {Error} domain 已被其他仓库使用时抛出,状态码 409。 + */ + async assertDomainUnique(domain, excludeWarehouseId) { + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findOne !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + const { Op } = this.app.Sequelize; + const existing = await configModel.findOne({ + where: { + store_id: { [Op.ne]: excludeWarehouseId }, + [Op.or]: [ + { domain }, + { pending_domain: domain }, + ], + }, + attributes: [ 'store_id', 'domain', 'pending_domain' ], + }); + + if (existing) { + throw this.createError(`域名 ${domain} 已被其他仓库使用`, 409); + } + } + + /** + * 从记录(Sequelize 实例或普通对象)读取字段值。 + * + * @param {Object} record 记录实例或普通对象。 + * @param {string} key 字段名。 + * @return {*} 字段值;不可读时返回 null。 + */ + getRecordField(record, key) { + if (!record) { + return null; + } + + if (typeof record.get === 'function') { + return record.get(key); + } + + return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : null; + } + + /** + * 脱敏并截断错误文本:去掉 PEM 块内容、压缩空白、按列宽截断。 + * + * 安全红线:域名验证失败原因会写入 domain_last_error 并回显前端, + * 严禁把原始网络错误/堆栈原样落库(脱敏思路参考 script/warehouse-cert-sync.cjs 的 sanitizeErrorText)。 + * + * @param {*} text 原始错误文本。 + * @return {string} 脱敏截断后的文本(≤500 字符)。 + */ + sanitizeErrorText(text) { + return String(text === undefined || text === null ? '' : text) + .replace(/-----BEGIN [^-]*-----[\s\S]*?-----END [^-]*-----/g, '[PEM 内容已省略]') + .replace(/\s+/g, ' ') + .trim() + .slice(0, DOMAIN_LAST_ERROR_MAX_LENGTH); + } + + /** + * 读取域名验证配置(config.frontConfig.domainVerify),缺失或非法项回退默认值。 + * + * 公共方法:app/schedule 下的域名验证定时任务会直接调用,签名与返回值需保持稳定。 + * + * @return {Object} 域名验证配置,字段如下: + * - enable {boolean}:是否启用域名验证定时任务; + * - interval {string}:扫描间隔(Egg schedule 语法); + * - lockTtlSeconds {number}:Redis 跨进程锁 TTL(秒); + * - batchSize {number}:单轮最多处理行数; + * - dohUrls {string[]}:DoH 端点数组(顺序即尝试顺序,多端点顺序尝试、命中即返回); + * - dohUrl {string}:恒等于 dohUrls[0],兼容仍在读单端点键的旧调用方(历史单字符串配置仍生效); + * - timeoutMs {number}:单个 DoH 端点、以及系统 DNS 兜底单次查询的超时(毫秒); + * - maxAttempts {number}:自动重试次数上限。 + */ + getDomainVerifyConfig() { + const frontConfig = (this.app && this.app.config && this.app.config.frontConfig) || {}; + const raw = frontConfig.domainVerify || {}; + const toPositiveNumber = (value, fallback) => { + const parsed = Number(value); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; + }; + + const dohUrls = this.resolveDohUrls(raw); + + return { + enable: raw.enable !== false, + interval: String(raw.interval || '10m'), + lockTtlSeconds: toPositiveNumber(raw.lockTtlSeconds, 600), + // 单轮行数上限:最坏耗时核算见 DEFAULT_DOMAIN_VERIFY_BATCH_SIZE 与 config.default.js 注释 + batchSize: Math.floor(toPositiveNumber(raw.batchSize, DEFAULT_DOMAIN_VERIFY_BATCH_SIZE)), + // 同时暴露数组与首项:dohUrls 供调用方按序尝试多个端点,dohUrl 兼容旧的单端点读取方(恒为 dohUrls[0]) + dohUrls, + dohUrl: dohUrls[0], + timeoutMs: toPositiveNumber(raw.timeoutMs, DEFAULT_DOH_TIMEOUT_MS), + maxAttempts: Math.floor(toPositiveNumber(raw.maxAttempts, 20)), + }; + } + + /** + * 解析 DoH 端点列表(dohUrl → dohUrls 的兼容规则)。 + * + * 兼容规则(按优先级): + * 1. config.frontConfig.domainVerify.dohUrls 为「有效非空字符串数组」(逐项 trim 后至少一项非空)→ 使用它,顺序不变; + * 2. 否则 config.frontConfig.domainVerify.dohUrl 非空(历史单字符串配置)→ 等价于 [dohUrl]; + * 3. 否则使用内置默认数组 DEFAULT_DOH_URLS。 + * + * 数组项若全为空串/空白/非字符串,视为「无效配置」继续走规则 2/3,避免配置写错时整个解析链路不可用。 + * + * @param {Object} [raw] config.frontConfig.domainVerify 原始配置对象。 + * @return {string[]} 去空后的 DoH 端点数组,至少含一项。 + */ + resolveDohUrls(raw) { + const source = raw || {}; + const normalizeList = list => (Array.isArray(list) ? list : []) + .map(url => String(url === undefined || url === null ? '' : url).trim()) + .filter(url => url.length > 0); + + const multi = normalizeList(source.dohUrls); + if (multi.length > 0) { + return multi; + } + + const single = normalizeList([ source.dohUrl ]); + if (single.length > 0) { + return single; + } + + return DEFAULT_DOH_URLS.slice(); + } + + /** + * 读取 CNAME 目标(config.frontConfig.cname)。 + * + * 域名未通过验证时随 getDomain 返回给前端,提示用户把域名 CNAME 指向该目标。 + * + * @return {string} CNAME 目标;未配置返回空串。 + */ + getCnameTarget() { + const frontConfig = (this.app && this.app.config && this.app.config.frontConfig) || {}; + return String(frontConfig.cname || '').trim(); + } + + /** + * 生成域名验证所需的随机码(一次性校验子域 + TXT 记录值)。 + * + * 校验目标用一次性随机子域(wmsv-<10 位 hex>.<域名>)而非裸域名, + * 避免与用户主域上已有的其它 TXT 记录(SPF/DKIM/站点校验等)互相干扰。 + * + * @param {string} domain 已规范化的域名。 + * @return {Object} { host: 待校验 TXT 主机名, token: 待校验 TXT 记录值(32 位 hex) }。 + */ + buildDomainVerifyCode(domain) { + const randomTag = crypto.randomBytes(DOMAIN_VERIFY_HOST_RANDOM_BYTES).toString('hex'); + + return { + host: `${DOMAIN_VERIFY_HOST_PREFIX}${randomTag}.${domain}`, + token: crypto.randomBytes(DOMAIN_VERIFY_TOKEN_BYTES).toString('hex'), + }; + } + + /** + * 解析 DoH 应答中单条 TXT 记录的 data 文本(去外层引号、多段拼接、截断保护)。 + * + * DoH JSON 的 Answer[].data 形如 "abc" 或 "abc" "def"(TXT 单条记录可按 255 字节分段)。 + * + * @param {*} data DoH 应答中的 data 字段。 + * @return {string} 解析后的 TXT 文本;无内容返回空串。 + */ + parseTxtAnswerData(data) { + const text = String(data === undefined || data === null ? '' : data).trim(); + if (!text) { + return ''; + } + + const segments = text.match(/"([^"]*)"/g); + const value = segments && segments.length > 0 + ? segments.map(segment => segment.slice(1, -1)).join('') + : text.replace(/"/g, ''); + + return value.trim().slice(0, TXT_VALUE_MAX_LENGTH); + } + + /** + * 从 DoH 应答的 Answer 数组中提取 TXT 记录(type=16)。 + * + * @param {Array} answers DoH 应答的 Answer 数组。 + * @return {string[]} TXT 记录文本列表(已去空、截断)。 + */ + extractTxtValuesFromAnswers(answers) { + const values = []; + + for (const answer of Array.isArray(answers) ? answers : []) { + if (!answer || Number(answer.type) !== 16) { + continue; + } + + const value = this.parseTxtAnswerData(answer.data); + if (value) { + values.push(value); + } + } + + return values; + } + + /** + * 请求单个 DoH 端点解析 TXT 记录,并把结果三分类(本方法自身不抛异常)。 + * + * 分类口径: + * - values:拿到至少一条 TXT 值 → 调用方应立即返回,不再尝试后续端点; + * - empty :Status === 0 且有 Question 但无 Answer(NODATA),或 Status === 3(NXDOMAIN) + * → 「本端点未解析到记录」。注意这不等于「记录一定不存在」:可能是该端点的负缓存滞后 + * (见 resolveTxtByDoh 中的实测案例),故调用方必须继续尝试下一个端点,不能就此定论; + * - error :请求异常/超时、HTTP 非 200、响应体非对象等 → 「本端点解析失败」,同样继续下一个端点。 + * + * @param {string} host 待解析主机名。 + * @param {string} endpoint DoH 端点地址(不含查询串)。 + * @param {number} timeoutMs 单端点请求超时(毫秒)。 + * @return {Promise} { kind: values|empty|error, endpoint: string, values?: string[], reason?: string }。 + * reason 已脱敏截断,仅用于日志与最终错误文案。 + */ + async queryDohEndpoint(host, endpoint, timeoutMs) { + try { + const url = endpoint + '?name=' + encodeURIComponent(host) + '&type=TXT'; + const response = await this.ctx.curl(url, { + method: 'GET', + headers: { accept: 'application/dns-json' }, + timeout: timeoutMs, + dataType: 'json', + }); + + const statusCode = Number(response && response.status) || 0; + if (statusCode !== 200) { + return { kind: 'error', endpoint, reason: 'DoH 服务返回异常状态码 ' + statusCode }; + } + + const body = response && response.data; + if (!body || typeof body !== 'object') { + return { kind: 'error', endpoint, reason: 'DoH 响应体不是合法 JSON' }; + } + + const values = this.extractTxtValuesFromAnswers(body.Answer); + if (values.length > 0) { + return { kind: 'values', endpoint, values }; + } + + // Status=3(NXDOMAIN)或 Status=0 但无 Answer(NODATA)→ 端点级「未解析到记录」 + return { kind: 'empty', endpoint }; + } catch (error) { + return { + kind: 'error', + endpoint, + reason: this.sanitizeErrorText(error && error.message) || 'DoH 请求异常', + }; + } + } + + /** + * DoH(DNS-over-HTTPS)多端点顺序解析 TXT 记录。 + * + * 契约变更(内部 helper,仅本文件 resolveTxtValues 调用): + * 旧版返回 string[](单端点 dohUrl,NODATA 直接定论为「无记录」);现返回明细对象, + * 以便上层区分「端点说没有记录(empty)」与「端点不可用(error)」并据此决定是否降级系统 DNS。 + * 对外契约(resolveTxtValues / verifyDomainRecord)保持向后兼容。 + * + * 为什么不能让单端点的 NODATA 直接定论(本次线上实测案例): + * 主机 wmsv-aa4adaab13.wms.wms.gztbyc.com 的 TXT 记录 ddd9ae51cf95b488db544f23ccd01e7b 真实存在 + * (8.8.8.8 / 223.5.5.5 / nslookup / AliDNS DoH 四方一致),但默认端点 https://doh.pub/dns-query + * 仍返回 Status=0 且 Answer 为空(陈旧负缓存:同一主机 A 查询同步 NODATA,返回的 SOA 序列号 2026081813 + * 旧于 TXT 查询的 2026082815,重复两次结果一致)。旧实现据此直接返回 [] 且不降级, + * 导致 verifyDomainRecord 判 verified=false → domain_status 被打成 2 → 被 getByDomain/nginx 闸门断流。 + * 因此这里改为:只有端点「明确拿到值」才立即成功返回;某个端点 empty 仅记为「候选无记录」, + * 必须等所有端点都尝试完(必要时再降级系统 DNS)才定论。 + * + * @param {string} host 待解析主机名。 + * @param {Object} verifyConfig 域名验证配置(getDomainVerifyConfig 返回值,取 dohUrls / timeoutMs)。 + * @return {Promise} { values: string[], endpoint: string|null, hadEmpty: boolean, + * emptyEndpoint: string|null, errors: Array<{endpoint: string, reason: string}> }。 + * values 非空时 endpoint 为命中端点;values 为空时 emptyEndpoint 为第一个报 empty 的端点(无则 null), + * errors 为所有端点级失败原因(已脱敏)。本方法自身不抛异常。 + */ + async resolveTxtByDoh(host, verifyConfig) { + const configured = verifyConfig && verifyConfig.dohUrls; + const endpoints = Array.isArray(configured) && configured.length > 0 + ? configured + : this.resolveDohUrls({}); + const configuredTimeout = Number(verifyConfig && verifyConfig.timeoutMs); + const timeoutMs = Number.isFinite(configuredTimeout) && configuredTimeout > 0 + ? configuredTimeout + : DEFAULT_DOH_TIMEOUT_MS; + + const errors = []; + let emptyEndpoint = null; + + for (const endpoint of endpoints) { + const result = await this.queryDohEndpoint(host, endpoint, timeoutMs); + + if (result.kind === 'values') { + return { + values: result.values, + endpoint: result.endpoint, + hadEmpty: !!emptyEndpoint, + emptyEndpoint, + errors, + }; + } + + if (result.kind === 'empty') { + if (!emptyEndpoint) { + emptyEndpoint = result.endpoint; + } + this.ctx.logger.info( + '[FrontConfigService.resolveTxtByDoh] 端点返回 NODATA/NXDOMAIN,继续尝试下一个端点: host=%s endpoint=%s', + host, + result.endpoint + ); + continue; + } + + errors.push({ endpoint: result.endpoint, reason: result.reason }); + this.ctx.logger.warn( + '[FrontConfigService.resolveTxtByDoh] 端点解析失败,继续尝试下一个端点: host=%s endpoint=%s reason=%s', + host, + result.endpoint, + result.reason + ); + } + + return { values: [], endpoint: null, hadEmpty: !!emptyEndpoint, emptyEndpoint, errors }; + } + + /** + * 系统 DNS(node:dns)解析 TXT 记录:DoH 全部端点都未取到值后的兜底路径。 + * + * 特别注意(本次实测):本机 Node resolver 可能指向不可用的解析器(Windows 上出现 127.0.0.1, + * 而实际 DNS 为 192.168.8.1,该解析器对 TXT 查询直接超时),此时 resolveTxt 报 ECONNREFUSED/超时。 + * c-ares 自身默认「5s × 多次重试」,故这里显式限时,避免单行串行阻塞定时任务整轮(核算见 resolveTxtValues)。 + * + * @param {string} host 待解析主机名。 + * @param {number} [timeoutMs] 超时上限(毫秒);≤ 0 或未传时不做限时(保持旧行为)。 + * @return {Promise} TXT 记录文本列表(多段已拼接、去空、截断)。 + * @throws {Error} 解析失败(含 NXDOMAIN/超时)时抛出。 + */ + async resolveTxtBySystem(host, timeoutMs) { + const limitMs = Number(timeoutMs) > 0 ? Number(timeoutMs) : 0; + + const query = (async () => { + const records = await dns.promises.resolveTxt(host); + const values = []; + + for (const record of Array.isArray(records) ? records : []) { + const joined = Array.isArray(record) ? record.join('') : String(record || ''); + const value = joined.trim().slice(0, TXT_VALUE_MAX_LENGTH); + if (value) { + values.push(value); + } + } + + return values; + })(); + + if (limitMs <= 0) { + return query; + } + + let timer = null; + try { + // Promise.race 会给两个分支都挂上处理器,落败分支的 reject 不会产生 unhandledRejection + return await Promise.race([ + query, + new Promise((_resolve, reject) => { + timer = setTimeout( + () => reject(new Error('系统 DNS 解析超时(>' + limitMs + 'ms)')), + limitMs + ); + }), + ]); + } finally { + if (timer) { + clearTimeout(timer); + } + } + } + + /** + * 解析指定主机名的 TXT 记录(DoH 多端点顺序尝试为主,必要时降级系统 DNS)。 + * + * 决策流程: + * 1. 依次尝试 dohUrls(见 getDomainVerifyConfig / resolveDohUrls)中的每个端点: + * - 有 TXT 值 → 立即返回 { values, source: 'doh', endpoint }; + * - empty(Status=0 且无 Answer / Status=3 NXDOMAIN)→ 记下「候选无记录」并继续下一个端点; + * - error(异常/超时/HTTP 非 200/响应体非对象)→ 记录脱敏原因并继续下一个端点。 + * 2. 所有端点结束后: + * - 至少一个端点 empty(且无端点拿到值)→ 降级系统 DNS: + * · 有值 → { values, source: 'system', endpoint: null }; + * · 空/NXDOMAIN → { values: [], source: 'doh', endpoint: null }(语义=未解析到记录,不抛错); + * · 抛错(如 ECONNREFUSED)→ 仍按「未解析到记录」返回 []:已有端点明确说没有该记录时, + * 不能因为兜底路径不可用就把结果升级成 500(否则会把「没配记录」误报成服务故障)。 + * - 所有端点都是 error(无任何 empty)→ 降级系统 DNS: + * · 有值 → { values, source: 'system', endpoint: null }; + * · 空 → { values: [], source: 'system', endpoint: null }(系统 DNS 明确答复为空 → 未解析到记录); + * · 抛错 → 所有可用解析路径都不可用 → 抛 500(保持旧语义 + 脱敏/截断)。 + * + * 兼容性:返回对象在既有 { values, source } 之上「追加」 endpoint 字段; + * verifyDomainRecord / checkDomain / verifyPendingDomains / app/schedule 的签名与判定口径均不变, + * verifyDomainRecord 仍永不抛异常(解析失败只体现为 error 文案)。 + * + * 可观测性:端点级失败、降级决策与最终定论都会打 INFO/WARN 日志并带上 source/endpoint, + * 便于把「记录确实不存在」与「解析链路整体不可用」区分开。 + * + * 最坏耗时:单主机 ≈ (DoH 端点数 3 + 系统 DNS 兜底 1) × timeoutMs(3000ms) = 12s(系统 DNS 亦按 timeoutMs 限时); + * 单轮 batchSize(20) 行最坏 ≈ 240s,明显小于 lockTtlSeconds(600s) 与 interval(600s)。 + * + * @param {string} host 待解析主机名(域名验证一律传 domain_verify_host,不用裸域名)。 + * @return {Promise} { values: string[], source: 'doh'|'system', endpoint: string|null }。 + * @throws {Error} 所有 DoH 端点均失败且系统 DNS 也失败时抛出,状态码 500,文案已脱敏截断。 + */ + async resolveTxtValues(host) { + const normalizedHost = String(host || '').trim().toLowerCase(); + if (!normalizedHost) { + throw this.createError('域名解析主机名不能为空', 400); + } + + const verifyConfig = this.getDomainVerifyConfig(); + const dohResult = await this.resolveTxtByDoh(normalizedHost, verifyConfig); + + if (dohResult.values.length > 0) { + return { values: dohResult.values, source: 'doh', endpoint: dohResult.endpoint }; + } + + // 至少一个端点明确「未解析到记录」(NODATA/NXDOMAIN)→ 已有旁证,系统 DNS 仅作二次确认 + const trustedEmpty = dohResult.hadEmpty; + + let systemValues = null; + let systemError = null; + try { + systemValues = await this.resolveTxtBySystem(normalizedHost, verifyConfig.timeoutMs); + } catch (error) { + systemError = error; + } + + if (Array.isArray(systemValues) && systemValues.length > 0) { + this.ctx.logger.info( + '[FrontConfigService.resolveTxtValues] DoH 未取到值,系统 DNS 命中: host=%s dohEmptyEndpoint=%s', + normalizedHost, + dohResult.emptyEndpoint || '-' + ); + return { values: systemValues, source: 'system', endpoint: null }; + } + + if (trustedEmpty) { + if (systemError) { + this.ctx.logger.warn( + '[FrontConfigService.resolveTxtValues] DoH 有端点明确无记录、系统 DNS 失败,按「未解析到记录」处理: host=%s endpoint=%s reason=%s', + normalizedHost, + dohResult.emptyEndpoint, + this.sanitizeErrorText(systemError.message) || '未知错误' + ); + } + return { values: [], source: 'doh', endpoint: null }; + } + + if (!systemError) { + // 所有 DoH 端点均 error,但系统 DNS 明确答复为空 → 未解析到记录(不升级为 500) + this.ctx.logger.warn( + '[FrontConfigService.resolveTxtValues] DoH 端点全部失败且系统 DNS 返回空,按「未解析到记录」处理: host=%s dohErrors=%d', + normalizedHost, + dohResult.errors.length + ); + return { values: [], source: 'system', endpoint: null }; + } + + const systemReason = this.sanitizeErrorText(systemError.message) || '未知错误'; + const dohReason = dohResult.errors.length > 0 + ? dohResult.errors.map(item => item.endpoint + ': ' + item.reason).join('; ') + : ''; + this.ctx.logger.warn( + '[FrontConfigService.resolveTxtValues] DoH 与系统 DNS 均失败: host=%s doh=%s system=%s', + normalizedHost, + this.sanitizeErrorText(dohReason), + systemReason + ); + throw this.createError( + 'DNS 解析失败:' + this.sanitizeErrorText(dohReason ? dohReason + ';系统 DNS: ' + systemReason : systemReason), + 500 + ); + } + + /** + * 校验一条 TXT 归属记录(定时任务逐行调用,必须失败隔离、不得抛异常)。 + * + * 签名说明(两阶段切换改造):新增可选第二参数 overrides,允许调用方直接指定待校验的 + * host / token——校验「待验证域名」时传 pending_verify_host / pending_verify_token + * 走这条路径;不传时回退读取记录上的 domain_verify_host / domain_verify_token, + * 因此既有两个调用点(生效域名校验 / 升级前逻辑)行为完全不变。 + * + * @param {Object} record 配置记录(Sequelize 实例或 raw 普通对象;未传 overrides 时需含 domain_verify_host / domain_verify_token)。 + * @param {Object} [overrides={}] 显式指定的校验目标。 + * @param {string} [overrides.host] 待解析主机名(优先级高于记录上的 domain_verify_host)。 + * @param {string} [overrides.token] 待比对 TXT 值(优先级高于记录上的 domain_verify_token)。 + * @return {Promise} 校验结果,字段如下: + * - verified {boolean}:是否校验通过(解析到的 TXT 记录中包含校验值); + * - values {string[]}:实际解析到的 TXT 值; + * - source {string}:解析来源 doh/system,未解析为空串(resolveTxtValues 另返回 endpoint,本方法不透出); + * - 注意:解析路径「明确无记录」时本方法返回 verified=false + values=[](不抛异常), + * 仅当所有 DoH 端点与系统 DNS 都解析失败时,resolveTxtValues 才抛 500 并在此转为 error 文案。 + * - error {string|null}:失败原因(已脱敏截断),成功为 null。 + */ + async verifyDomainRecord(record, overrides = {}) { + const overrideHost = String((overrides && overrides.host) || '').trim(); + const overrideToken = String((overrides && overrides.token) || '').trim(); + const verifyHost = overrideHost + || String(this.getRecordField(record, 'domain_verify_host') || '').trim(); + const verifyToken = overrideToken + || String(this.getRecordField(record, 'domain_verify_token') || '').trim(); + + if (!verifyHost) { + return { verified: false, values: [], source: '', error: '未生成待校验的 TXT 主机名,请重新设置域名' }; + } + + if (!verifyToken) { + return { verified: false, values: [], source: '', error: '未生成待校验的 TXT 记录值,请重新设置域名' }; + } + + try { + const { values, source } = await this.resolveTxtValues(verifyHost); + const normalizedValues = values.map(value => String(value).trim()); + + // 校验值为后端生成的 hex,比对时忽略大小写(DNS 记录本身大小写不敏感) + const expected = verifyToken.toLowerCase(); + if (normalizedValues.some(value => value.toLowerCase() === expected)) { + return { verified: true, values: normalizedValues, source, error: null }; + } + + return { + verified: false, + values: normalizedValues, + source, + error: normalizedValues.length > 0 ? 'TXT 记录未包含校验值' : '未解析到 TXT 记录', + }; + } catch (error) { + return { + verified: false, + values: [], + source: '', + error: this.sanitizeErrorText(error.message) || '域名解析失败', + }; + } + } + + /** + * 判定错误是否为「数据库列不存在」(迁移尚未执行的典型表现)。 + * + * 迁移尚未执行时查询 domain_status 等新列会报 ER_BAD_FIELD_ERROR / Unknown column, + * 这类错误必须走降级路径(而非中断定时任务、也不应让公共拉取接口直接 500)。 + * + * @param {*} error 错误对象。 + * @return {boolean} 是未知列错误返回 true。 + */ + isUnknownColumnError(error) { + if (!error) { + return false; + } + + const code = String((error.parent && error.parent.code) || error.code || ''); + if (code === 'ER_BAD_FIELD_ERROR') { + return true; + } + + const message = String(error.message || ''); + return /unknown column/i.test(message) || message.includes('ER_BAD_FIELD_ERROR'); + } + + /** + * 查询「已验证」的域名配置记录(公共拉取闸门的查库入口)。 + * + * 迁移容错:迁移尚未执行(domain_status 列不存在)时降级为仅按 domain 查询, + * 保持迁移前的行为,并用进程内一次性标记避免刷日志; + * 迁移完成后需重启实例,闸门才会真正生效(进程内标记与 model 定义均在重启后刷新)。 + * + * @param {Object} configModel WarehouseFrontConfig model。 + * @param {string} normalizedDomain 已 trim 的域名。 + * @return {Promise} 命中返回记录实例,未命中返回 null。 + * @throws {Error} 非「未知列」的数据库异常原样抛出(由调用方转 500)。 + */ + async findVerifiedDomainRecord(configModel, normalizedDomain) { + try { + return await configModel.findOne({ + where: { + domain: normalizedDomain, + domain_status: DOMAIN_STATUS_VERIFIED, + }, + }); + } catch (error) { + if (!this.isUnknownColumnError(error)) { + throw error; + } + + // 一次性 WARN:迁移完成并重启实例后自动恢复闸门,避免每个请求都刷日志 + if (this.app && !this.app._frontConfigDomainStatusFallbackWarned) { + this.app._frontConfigDomainStatusFallbackWarned = true; + this.ctx.logger.warn( + '[FrontConfigService.findVerifiedDomainRecord] wms_warehouse_front_config.domain_status 列不存在' + + '(迁移尚未执行),本次降级为仅按 domain 查询;迁移完成后需重启实例才能恢复域名验证闸门' + ); + } + + return configModel.findOne({ + where: { + domain: normalizedDomain, + }, + }); + } + } + + /** + * 扫描并校验「待验证域名」(供定时任务与手动触发复用)。 + * + * 两阶段切换后本方法只处理 pending 组:选取 pending_domain / pending_verify_host / + * pending_verify_token 均非空、且 pending_verify_attempts 未达 maxAttempts 上限的行, + * 按 id 升序单批处理 batchSize 行。 + * · 校验通过 → promotePendingDomain 提升为生效域名(清证书/重置同步/旧域名入下线队列) + * + 清旧、新两个域名缓存,计入 verified; + * · 校验失败 → pending_verify_attempts + 1、pending_last_error(脱敏截断),计入 failed, + * 生效域名、domain_status 与证书一律不动(旧域名不会被本任务断流); + * · 已达上限的行不再自动重试,计入 skipped(仍可由 checkDomain 手动触发)。 + * + * 失败隔离:单行解析/提升/落库失败只计入 errors,不中断整轮;onRow 回调抛错同样不影响主流程。 + * fail-soft:model 不可用、或迁移尚未执行(pending_* 列不存在,ER_BAD_FIELD_ERROR) + * 时不抛出,返回零统计 + errors 中的脱敏原因,由调用方记 WARN。 + * + * @param {Object} [options] 扫描选项。 + * @param {number} [options.batchSize] 单轮最多处理行数(默认取 domainVerify.batchSize)。 + * @param {number} [options.maxAttempts] 超过后不再自动重试(默认取 domainVerify.maxAttempts)。 + * @param {Function} [options.onRow] 每行处理后的回调,参数 + * { id, store_id, domain, pending_domain, verified_domain, verified, error } + * (domain 为库内生效域名,可为空;pending_domain / verified_domain 为本轮校验的待验证域名)。 + * @return {Promise<{scanned:number, verified:number, failed:number, skipped:number, errors:string[]}>} + * scanned:本轮选中的待处理行数;verified:其中校验通过且提升成功的行数; + * failed:校验失败且 pending 状态回写成功的行数;skipped:因达到 maxAttempts 上限而未自动重试的行数; + * errors:脱敏后的错误原因列表(含提升失败,这类行不计入 verified / failed)。 + */ + async verifyPendingDomains(options = {}) { + const verifyConfig = this.getDomainVerifyConfig(); + const batchSize = Number(options.batchSize) > 0 + ? Math.floor(Number(options.batchSize)) + : verifyConfig.batchSize; + const maxAttempts = Number(options.maxAttempts) > 0 + ? Math.floor(Number(options.maxAttempts)) + : verifyConfig.maxAttempts; + const onRow = typeof options.onRow === 'function' ? options.onRow : null; + + const summary = { scanned: 0, verified: 0, failed: 0, skipped: 0, errors: [] }; + + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findAll !== 'function') { + summary.errors.push('WarehouseFrontConfig model 不可用'); + return summary; + } + + const { Op } = this.app.Sequelize; + const pendingWhere = { + pending_domain: { [Op.ne]: null }, + pending_verify_host: { [Op.ne]: null }, + pending_verify_token: { [Op.ne]: null }, + }; + + let rows = []; + try { + rows = await configModel.findAll({ + where: { + ...pendingWhere, + pending_verify_attempts: { [Op.lt]: maxAttempts }, + }, + attributes: [ + 'id', + 'store_id', + 'domain', + 'pending_domain', + 'pending_verify_host', + 'pending_verify_token', + 'pending_verify_attempts', + 'pending_last_error', + ], + order: [[ 'id', 'ASC' ]], + limit: batchSize, + raw: true, + }); + } catch (error) { + const reason = this.sanitizeErrorText(error.message) || '未知错误'; + // 迁移未执行时 pending_* 列不存在:明确提示,避免把「列不存在」误判为数据/网络问题 + const hint = this.isUnknownColumnError(error) + ? '(迁移 20260924180000-add-pending-domain-to-wms-warehouse-front-config 尚未执行,pending_* 列不存在)' + : ''; + this.ctx.logger.warn('[FrontConfigService.verifyPendingDomains] 查询待验证域名失败: %s', reason); + summary.errors.push('查询待验证域名失败:' + reason + hint); + return summary; + } + + // 已达上限的行不再自动重试,单独计数便于观察「自动重试已耗尽」的域名规模; + // 计数失败不影响主流程(计入 errors 即可) + try { + summary.skipped = await configModel.count({ + where: { + ...pendingWhere, + pending_verify_attempts: { [Op.gte]: maxAttempts }, + }, + }); + } catch (error) { + const reason = this.sanitizeErrorText(error.message) || '未知错误'; + this.ctx.logger.warn('[FrontConfigService.verifyPendingDomains] 统计已达重试上限行数失败: %s', reason); + summary.errors.push('统计已达重试上限行数失败:' + reason); + } + + summary.scanned = rows.length; + + for (const row of rows) { + const rowId = Number(row.id); + const rowDomain = String(row.domain || '').trim(); + const pendingDomain = String(row.pending_domain || '').trim(); + let result = { verified: false, error: '未解析到 TXT 记录' }; + + try { + // verifyDomainRecord 契约上不抛异常,此处为最后一道兜底,保证单行失败不中断整轮 + result = await this.verifyDomainRecord(row, { + host: row.pending_verify_host, + token: row.pending_verify_token, + }); + } catch (error) { + result = { verified: false, error: this.sanitizeErrorText(error.message) || '域名校验异常' }; + } + + if (result.verified) { + // 校验通过 → 提升为生效域名:清空证书、重置同步状态、旧域名写入 retired_domain 下线队列 + try { + await this.promotePendingDomain(row); + summary.verified += 1; + // 先写库、后清缓存:旧域名(即将下线)与新域名两个 key 都必须清,清失败仅记 WARN + await this.clearDomainCaches( + [ rowDomain, pendingDomain ], + 'FrontConfigService.verifyPendingDomains' + ); + } catch (error) { + const reason = this.sanitizeErrorText(error.message) || '未知错误'; + summary.errors.push('提升待验证域名失败(id=' + rowId + '):' + reason); + this.ctx.logger.warn( + '[FrontConfigService.verifyPendingDomains] 提升待验证域名失败 id=%s: %s', + rowId, + reason + ); + } + } else { + // 校验失败只写 pending 组:生效域名、domain_status 与证书一律不动 + const pendingError = this.sanitizeErrorText(result.error || '未解析到 TXT 记录'); + try { + // 防并发守卫:仅更新 id 与 pending_domain 均匹配的行,避免与并发校验/取消待切换互相覆盖 + await configModel.update({ + pending_verify_attempts: Number(row.pending_verify_attempts || 0) + 1, + pending_last_error: pendingError, + }, { + where: { id: rowId, pending_domain: row.pending_domain }, + }); + summary.failed += 1; + } catch (error) { + const reason = this.sanitizeErrorText(error.message) || '未知错误'; + summary.errors.push('更新待验证域名状态失败(id=' + rowId + '):' + reason); + this.ctx.logger.warn( + '[FrontConfigService.verifyPendingDomains] 更新待验证域名状态失败 id=%s: %s', + rowId, + reason + ); + } + } + + if (onRow) { + try { + await onRow({ + id: rowId, + store_id: Number(row.store_id) || 0, + domain: rowDomain, + pending_domain: pendingDomain, + verified_domain: pendingDomain, + verified: !!result.verified, + error: result.verified ? null : this.sanitizeErrorText(result.error || ''), + }); + } catch (error) { + // 回调异常只 WARN,绝不影响主流程 + this.ctx.logger.warn( + '[FrontConfigService.verifyPendingDomains] onRow 回调执行失败 id=%s: %s', + rowId, + this.sanitizeErrorText(error.message) + ); + } + } + } + + return summary; + } + + /** + * 构建前端配置品牌信息输出对象(settings 页回显,无记录时返回默认空值)。 + * + * 安全红线:仅输出品牌与基础字段,严禁输出 cert_pem/key_pem/cert_expire_at/ + * sync_status/sync_attempts/last_sync_error/last_synced_at 等证书与同步内部字段。 + * + * @param {Object|null} record 配置记录实例(可为 null)。 + * @param {number} warehouseId 当前仓库 ID。 + * @return {Object} 品牌信息输出对象(warehouse_id/domain/title/logo_url/favicon_url/login_bg_url/theme/updated_at)。 + */ + buildInfoOutput(record, warehouseId) { + const hasRecord = !!(record && typeof record.get === 'function'); + const getValue = key => (hasRecord ? record.get(key) : null); + + return { + warehouse_id: Number(warehouseId || 0), + domain: hasRecord ? (getValue('domain') || '') : '', + title: hasRecord ? (getValue('title') || '') : '', + logo_url: hasRecord ? (getValue('logo_url') || '') : '', + favicon_url: hasRecord ? (getValue('favicon_url') || '') : '', + login_bg_url: hasRecord ? (getValue('login_bg_url') || '') : '', + theme: hasRecord ? (getValue('theme') || null) : null, + updated_at: hasRecord ? (getValue('updated_at') || null) : null, + }; + } + + /** + * 构建前端配置证书输出对象(证书/私钥原文回显,无记录时返回默认空值)。 + * + * 证书回显:输出证书原文(cert_pem)与私钥原文(key_pem,取自 cert_key 列), + * 不再输出 cert_path/key_path 路径字段(保存时已置空,尚无真实路径)。 + * 安全说明:私钥原文回显仅限仓库主体登录后的 settings 页(getCert/saveCert + * 复用本输出);公共无鉴权接口 getByDomain 走 buildPublicOutput 白名单,不经过本方法。 + * + * ⚠ 响应契约:本方法输出 13 个字段(原有 10 个 + 本次新增 3 个),文档与测试需同步。 + * 原有 10 字段:warehouse_id/domain/cert_pem/key_pem/cert_expire_at/sync_status/ + * sync_attempts/last_sync_error/last_synced_at/updated_at。 + * 新增 3 字段(追加在末尾): + * - domain_status:域名验证状态 0-未验证/1-已验证/2-验证失败; + * - can_set_cert:域名非空且已验证(domain_status=1)才允许上传证书; + * - can_set_cert_reason:不可上传时的原因,可上传为空串。 + * + * @param {Object|null} record 配置记录实例(可为 null)。 + * @param {number} warehouseId 当前仓库 ID。 + * @return {Object} 证书输出对象(13 字段)。 + */ + buildCertOutput(record, warehouseId) { + const hasRecord = !!(record && typeof record.get === 'function'); + const getValue = key => (hasRecord ? record.get(key) : null); + + const domain = hasRecord ? (getValue('domain') || '') : ''; + const domainStatus = hasRecord ? Number(getValue('domain_status') || 0) : DOMAIN_STATUS_UNVERIFIED; + // 上传证书的前置闸门:必须先设置域名并通过 DNS TXT 验证 + const canSetCert = !!domain && domainStatus === DOMAIN_STATUS_VERIFIED; + + let canSetCertReason = ''; + if (!domain) { + canSetCertReason = '请先设置域名'; + } else if (!canSetCert) { + canSetCertReason = this.describeDomainStatus(domainStatus); + } + + return { + warehouse_id: Number(warehouseId || 0), + domain: hasRecord ? (getValue('domain') || '') : '', + cert_pem: hasRecord ? (getValue('cert_pem') || '') : '', + key_pem: hasRecord ? (getValue('cert_key') || '') : '', + cert_expire_at: hasRecord ? (getValue('cert_expire_at') || null) : null, + sync_status: hasRecord ? Number(getValue('sync_status') || 0) : 0, + sync_attempts: hasRecord ? Number(getValue('sync_attempts') || 0) : 0, + last_sync_error: hasRecord ? (getValue('last_sync_error') || '') : '', + last_synced_at: hasRecord ? (getValue('last_synced_at') || null) : null, + updated_at: hasRecord ? (getValue('updated_at') || null) : null, + can_set_cert: canSetCert, + can_set_cert_reason: canSetCertReason, + domain_status: domainStatus, + }; + } + + /** + * 查询当前仓库前端独立部署品牌配置(settings 页回显)。 + * + * 需登录(token 绑定仓库上下文,只能查到自己仓库的配置),仅返回品牌与基础字段, + * 不含证书/私钥原文与同步状态等内部字段(证书回显走 getCert)。 + * + * @return {Promise} 品牌信息输出对象;无记录时返回默认空值。 + * @throws {Error} 未识别到当前仓库时抛出 400;非仓库主体时抛出 403。 + */ + async getInfo() { + const warehouseId = this.getCurrentWarehouseId(); + + // 仅仓库主体管理员可查看前端独立部署配置(isWarehouse 判定) + await this.assertWarehouseSubject(); + + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findOne !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + const record = await configModel.findOne({ + where: { + store_id: warehouseId, + }, + }); + + return this.buildInfoOutput(record, warehouseId); + } + + /** + * 查询当前仓库前端独立部署证书配置(settings 页回显)。 + * + * 需登录(token 绑定仓库上下文,只能查到自己仓库的配置), + * 响应含证书原文(cert_pem)与私钥原文(key_pem),仅供仓库主体 settings 页回显; + * 公共无鉴权接口 getByDomain 仍只返回公开字段白名单。 + * + * @return {Promise} 证书输出对象;无记录时返回默认空值。 + * @throws {Error} 未识别到当前仓库时抛出 400;非仓库主体时抛出 403。 + */ + async getCert() { + const warehouseId = this.getCurrentWarehouseId(); + + // 仅仓库主体管理员可查看前端独立部署证书(isWarehouse 判定) + await this.assertWarehouseSubject(); + + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findOne !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + const record = await configModel.findOne({ + where: { + store_id: warehouseId, + }, + }); + + return this.buildCertOutput(record, warehouseId); + } + + /** + * 查询当前仓库域名验证状态(settings 页回显,需登录、仅仓库主体)。 + * + * 需登录(token 绑定仓库上下文,只能查到自己仓库的配置);无记录时返回空值默认。 + * + * 两阶段切换后输出在既有 9 个字段之后追加待验证域名组(pending_domain / pending_verify_host / + * pending_verify_value / pending_attempts / pending_last_error / pending_created_at / + * pending_active),既有字段一律不改名、不删除;字段口径详见 buildDomainOutput。 + * + * @return {Promise} 域名输出对象,既有 9 字段(warehouse_id/domain/domain_status/ + * verify_host/verify_value/cname/verified_at/attempts/last_error)+ 待验证域名组 7 字段 + * (pending_domain/pending_verify_host/pending_verify_value/pending_attempts/pending_last_error/ + * pending_created_at/pending_active),字段含义见 buildDomainOutput。 + * @throws {Error} 未识别到当前仓库时抛出 400;非仓库主体时抛出 403。 + */ + async getDomain() { + const warehouseId = this.getCurrentWarehouseId(); + + // 仅仓库主体管理员可查看前端独立部署域名配置(isWarehouse 判定) + await this.assertWarehouseSubject(); + + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findOne !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + const record = await configModel.findOne({ + where: { + store_id: warehouseId, + }, + }); + + return this.buildDomainOutput(record, warehouseId); + } + + /** + * 设置当前仓库自持域名(需登录、仅仓库主体)。 + * + * 两阶段切换(本次改造核心):本接口只登记「待验证域名」,不直接改动生效域名。 + * 第一阶段(本接口):把入参写入 pending_domain 并下发一次性 DNS TXT 校验记录; + * 第二阶段(checkDomain 手动触发 / app/schedule/domain_verify_scan.js 定时扫描): + * TXT 校验通过后由 promotePendingDomain 一次性把 pending_domain 提升为 domain + * (同时把旧域名写入 retired_domain 下线队列、清空证书并重置同步状态)。 + * 这样生效域名全程不变:切换期间旧域名的前端页面与 getByDomain 公共拉取都仍然可用, + * 直到提升完成后由外部证书脚本按 retired_domain 删除旧域名的 nginx 配置与证书文件。 + * + * 分支(域名比较一律忽略大小写): + * A) 入参 == 生效域名 domain 且无待验证域名 → 幂等短路:不写库;仅当库内字面值与归一化 + * 结果不一致时把 domain 改写为小写并清理新旧两个字面值的缓存 key。 + * · 与旧实现的差异:原有「未验证/验证失败且缺校验码则补发校验码」的子分支已移除, + * 缺码的历史脏数据行不再自动补码(需重新生效请提交一个不同的待验证域名)。 + * B) 入参 == 生效域名 domain 且有 pending_domain → 取消待切换:清空 pending 6 列; + * 生效域名、证书 5 列、同步 4 列与公共缓存一律不动。 + * C) 入参 == 现有 pending_domain → 校验码齐全则幂等短路(不重发、不写库); + * 校验码缺失(脏数据)则只补发 pending 校验码并清 pending 尝试次数/失败原因。 + * D) 其它(新的待切换域名,含首次设置)→ 查重(其他仓库的 domain 或 pending_domain + * 占用即 409)→ 生成新校验码写入 pending 组;生效域名 domain / domain_status / + * domain_verified_at / domain_verify_* / 证书 5 列 / 同步 4 列一律不动, + * 也不清理任何公共缓存(新域名尚未生效,getByDomain 不受影响)。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一,忽略大小写去重)。 + * @return {Promise} 域名输出对象(生效域名组 + 待验证域名组 + cname)。 + * @throws {Error} 未识别到当前仓库时抛出 400;非仓库主体时抛出 403; + * 参数非法时抛出 400;域名被其他仓库占用时抛出 409。 + */ + async setDomain(data = {}) { + const warehouseId = this.getCurrentWarehouseId(); + + // 仅仓库主体管理员可配置前端独立部署域名(isWarehouse 判定) + await this.assertWarehouseSubject(); + + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findOne !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + const domain = this.normalizeText(data.domain, 'domain', 100); + if (!domain) { + throw this.createError('domain 不能为空', 400); + } + + // 统一转小写存储:DNS 大小写不敏感,避免同一域名靠大小写差异绕过去重校验 + const normalizedDomain = domain.toLowerCase(); + if (!DOMAIN_PATTERN.test(normalizedDomain)) { + throw this.createError('domain 格式不正确', 400); + } + + const record = await configModel.findOne({ + where: { + store_id: warehouseId, + }, + }); + + const currentDomain = record ? String(record.get('domain') || '').trim() : ''; + const currentPendingDomain = record ? String(record.get('pending_domain') || '').trim() : ''; + const matchesCurrentDomain = !!currentDomain && currentDomain.toLowerCase() === normalizedDomain; + const matchesPendingDomain = !!currentPendingDomain + && currentPendingDomain.toLowerCase() === normalizedDomain; + + // ===== 分支 A:入参 == 生效域名 且无待验证域名 → 幂等短路(仅大小写规范化时写库) ===== + // 本分支刻意跳过 assertDomainUnique 查重:域名已是本仓自身持有,查重恒为「不冲突」, + // 属无意义查询;全局唯一性由分支 D 的查重与数据库唯一索引共同兜底。 + if (record && matchesCurrentDomain && !currentPendingDomain) { + if (currentDomain === normalizedDomain) { + // 完全无变化:不写库、不清缓存,直接回显当前状态(幂等) + return this.buildDomainOutput(record, warehouseId); + } + + // 大小写规范化:只把 domain 一个字面值字段改写为小写,其余字段一律不动 + try { + await record.update({ domain: normalizedDomain }); + } catch (error) { + // 并发写入兜底:唯一索引冲突统一转为业务错误 + // (大小写规范化可能撞上其他仓库已占用的同名字面值,属真实冲突) + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError(`域名 ${normalizedDomain} 已被其他仓库使用`, 409); + } + throw error; + } + + // 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量 + const refreshedRecord = await configModel.findByPk(record.id); + + // 缓存清理:公共拉取缓存键按域名字面值精确匹配(front:config:domain:Shop.com 与 + // ...:shop.com 是两个 key),新旧两个字面值都必须清 + await this.clearDomainCaches( + [ currentDomain, normalizedDomain ], + 'FrontConfigService.setDomain' + ); + + return this.buildDomainOutput(refreshedRecord, warehouseId); + } + + // ===== 分支 B:入参 == 生效域名 且有待验证域名 → 取消待切换 ===== + if (record && matchesCurrentDomain && currentPendingDomain) { + // 只清 pending 6 列:生效域名、证书 5 列、同步 4 列一律不动; + // 待验证域名从未生效(不参与 getByDomain),因此无需清理公共缓存 + await record.update(this.buildPendingClearPatch()); + + const refreshedRecord = await configModel.findByPk(record.id); + return this.buildDomainOutput(refreshedRecord, warehouseId); + } + + // ===== 分支 C:入参 == 现有待验证域名 → 码齐幂等短路,码缺只补码 ===== + if (record && matchesPendingDomain) { + const pendingVerifyHost = String(record.get('pending_verify_host') || '').trim(); + const pendingVerifyToken = String(record.get('pending_verify_token') || '').trim(); + + if (pendingVerifyHost && pendingVerifyToken) { + // 校验码齐全:不重发、不写库,直接回显(幂等) + return this.buildDomainOutput(record, warehouseId); + } + + // 脏数据(待验证域名没有校验码)→ 只补发校验码并清 pending 尝试次数/失败原因, + // 不碰生效域名、证书与同步状态,也不清缓存(待验证域名未生效) + const verifyCode = this.buildDomainVerifyCode(normalizedDomain); + await record.update({ + pending_domain: normalizedDomain, + pending_verify_host: verifyCode.host, + pending_verify_token: verifyCode.token, + pending_verify_attempts: 0, + pending_last_error: null, + pending_created_at: record.get('pending_created_at') || new Date(), + }); + + const refreshedRecord = await configModel.findByPk(record.id); + return this.buildDomainOutput(refreshedRecord, warehouseId); + } + + // ===== 分支 D:新的待验证域名(含首次设置)→ 只登记 pending,不动生效域名 ===== + // domain 全局唯一:可空列唯一索引不拦多个 NULL,非空值的唯一性必须应用层校验 + // (其他仓库的 domain 或 pending_domain 命中任一都算占用) + await this.assertDomainUnique(normalizedDomain, warehouseId); + + // 生成校验码并只写入 pending 组;生效域名组/证书/同步状态一律不动 + const verifyCode = this.buildDomainVerifyCode(normalizedDomain); + const pendingPatch = { + pending_domain: normalizedDomain, + pending_verify_host: verifyCode.host, + pending_verify_token: verifyCode.token, + pending_verify_attempts: 0, + pending_last_error: null, + pending_created_at: new Date(), + }; + + let savedRecord = record; + try { + if (record) { + await record.update(pendingPatch); + } else { + // 首次设置:新行只带 store_id 与 pending 组;domain 保持 NULL(尚未生效), + // domain_status 默认 0,证书脚本只处理 domain_status = 1 的行,不会误处理本行 + savedRecord = await configModel.create({ + store_id: warehouseId, + ...pendingPatch, + }); + } + } catch (error) { + // 并发写入兜底:唯一索引冲突统一转为业务错误 + if (error && error.name === 'SequelizeUniqueConstraintError') { + const conflictFields = error.fields || {}; + if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) { + throw this.createError(`域名 ${normalizedDomain} 已被其他仓库使用`, 409); + } + throw this.createError('仓库前端配置保存冲突,请稍后重试', 409); + } + throw error; + } + + // 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量 + const refreshedRecord = await configModel.findByPk(savedRecord.id); + + // 不清任何公共缓存:新域名尚未生效(生效域名 domain 未变),getByDomain 结果不受影响 + return this.buildDomainOutput(refreshedRecord, warehouseId); + } + + /** + * 把「待验证域名」提升为「生效域名」(两阶段切换的第二阶段,checkDomain 与定时扫描共用)。 + * + * 调用前提:pending_verify_host / pending_verify_token 已经 TXT 校验通过(本方法不再解析 DNS)。 + * 一次 update 提交以下字段(where 带 id + pending_domain 守卫,防并发重复提升): + * 1. 下线队列:生效域名非空且与待验证域名不同(忽略大小写)→ retired_domain = 旧域名、 + * retired_at = now。首次设置(无生效域名)不写这两列(保持 NULL,等价于清空); + * 同时刻意不把 retired_domain 置 NULL——队列里可能还有更早的旧域名等待外部证书脚本 + * 消费,覆盖会丢失下线任务(孤儿由脚本兜底清理)。 + * 2. 生效组:domain = pending_domain、domain_status = 1、domain_verified_at = now、 + * domain_verify_host / domain_verify_token / domain_verify_attempts 由 pending_* 平移、 + * domain_last_error = null。 + * 3. 清空 pending 6 列(pending_verify_attempts 归 0,其余置 NULL)。 + * 4. 清空证书 5 列 + 重置同步 4 列:域名已变,旧证书 SAN/CN 不覆盖新域名,必须重新上传; + * sync_status = 0 让外部证书脚本在用户上传新证书后自动部署。注意提升后到新证书上传前, + * 证书脚本会以「cert_pem 内容为空」记一次同步失败(属预期噪音,失败只落库不删旧域名文件)。 + * + * 边界:retired_domain 只保留最近一个旧域名,多次连续切换会丢中间域名(由脚本孤儿兜底清理); + * 本方法不碰 nginx 文件,也不清缓存——缓存清理由调用方负责(清旧域名与新域名两个 key)。 + * + * @param {Object} record 配置记录(Sequelize 实例或 raw 普通对象,需含 id 与 pending_* 字段)。 + * @return {Promise} 提升后的最新记录实例(findByPk 回查);model 不支持 findByPk 时返回 null。 + * @throws {Error} 数据库异常原样抛出(含 domain 唯一索引冲突 SequelizeUniqueConstraintError)。 + */ + async promotePendingDomain(record) { + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.update !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + const recordId = Number(this.getRecordField(record, 'id')); + const pendingDomain = String(this.getRecordField(record, 'pending_domain') || '').trim(); + if (!Number.isFinite(recordId) || recordId <= 0 || !pendingDomain) { + throw this.createError('待验证域名记录不完整,无法提升为生效域名', 500); + } + + const previousDomain = String(this.getRecordField(record, 'domain') || '').trim(); + const shouldRetire = !!previousDomain + && previousDomain.toLowerCase() !== pendingDomain.toLowerCase(); + const now = new Date(); + + const updateValues = { + // 生效组:由 pending 组平移 + domain: pendingDomain, + domain_status: DOMAIN_STATUS_VERIFIED, + domain_verified_at: now, + domain_verify_host: this.getRecordField(record, 'pending_verify_host') || null, + domain_verify_token: this.getRecordField(record, 'pending_verify_token') || null, + domain_verify_attempts: Number(this.getRecordField(record, 'pending_verify_attempts') || 0), + domain_last_error: null, + // 待验证组:清空 + ...this.buildPendingClearPatch(), + // 证书与同步状态:域名已变,证书必须重新上传(等外部脚本按新域名重新部署) + cert_pem: null, + cert_key: null, + cert_path: null, + key_path: null, + cert_expire_at: null, + sync_status: 0, + sync_attempts: 0, + last_sync_error: null, + last_synced_at: null, + }; + + if (shouldRetire) { + updateValues.retired_domain = previousDomain; + updateValues.retired_at = now; + } + + // 防并发守卫:仅更新 id 与 pending_domain 均匹配的行 + // (重复提升、用户已取消待切换、其他实例已提升过时都不会误改) + await configModel.update(updateValues, { + where: { id: recordId, pending_domain: pendingDomain }, + }); + + if (typeof configModel.findByPk === 'function') { + return configModel.findByPk(recordId); + } + + return null; + } + + /** + * 校验「待验证域名」的 TXT 记录,通过则提升为生效域名(checkDomain 的路径一)。 + * + * 与旧口径的关键差异:校验失败**只写 pending 组**(pending_verify_attempts / pending_last_error), + * 生效域名 domain、domain_status、domain_verified_at 与证书一律不动——旧域名不会被本路径断流。 + * + * @param {Object} record 配置记录实例(含 pending_* 字段)。 + * @param {string} pendingDomain 待验证域名(已 trim,非空)。 + * @param {number} warehouseId 当前仓库 ID。 + * @return {Promise} 域名输出对象 + verified(本次是否通过)+ resolved_values。 + * @throws {Error} 提升时待验证域名已被其他仓库用为生效域名,抛出 409。 + */ + async checkPendingDomainRecord(record, pendingDomain, warehouseId) { + const configModel = this.ctx.model.WarehouseFrontConfig; + const previousDomain = String(record.get('domain') || '').trim(); + + const verifyResult = await this.verifyDomainRecord(record, { + host: record.get('pending_verify_host'), + token: record.get('pending_verify_token'), + }); + + if (!verifyResult.verified) { + // 校验不通过:只写 pending 组;写入失败也不影响结论(回显时按库内值兜底) + const pendingError = this.sanitizeErrorText(verifyResult.error) || '未解析到 TXT 记录'; + try { + await configModel.update({ + pending_verify_attempts: Number(record.get('pending_verify_attempts') || 0) + 1, + pending_last_error: pendingError, + }, { + where: { id: record.id, pending_domain: pendingDomain }, + }); + } catch (error) { + this.ctx.logger.warn( + '[FrontConfigService.checkPendingDomainRecord] 回写待验证失败原因失败: %s', + this.sanitizeErrorText(error.message) + ); + } + + const refreshedRecord = await configModel.findByPk(record.id); + return { + ...this.buildDomainOutput(refreshedRecord || record, warehouseId), + verified: false, + resolved_values: this.buildResolvedValues(verifyResult.values), + }; + } + + // 校验通过 → 提升为生效域名(清证书、重置同步状态、旧域名入下线队列) + try { + await this.promotePendingDomain(record); + } catch (error) { + this.ctx.logger.warn( + '[FrontConfigService.checkPendingDomainRecord] 提升待验证域名失败 domain=%s: %s', + pendingDomain, + this.sanitizeErrorText(error.message) + ); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError(`域名 ${pendingDomain} 已被其他仓库使用`, 409); + } + throw error; + } + + // 先写库、后清缓存:旧域名(即将下线)与新域名两个 key 都必须清,清失败仅记 WARN + await this.clearDomainCaches( + [ previousDomain, pendingDomain ], + 'FrontConfigService.checkPendingDomainRecord' + ); + + const promotedRecord = await configModel.findByPk(record.id); + return { + ...this.buildDomainOutput(promotedRecord || record, warehouseId), + verified: true, + resolved_values: this.buildResolvedValues(verifyResult.values), + }; + } + + /** + * 主动执行一次域名 TXT 校验并回写结果(需登录、仅仓库主体)。 + * + * 两阶段切换后本接口同时承担两条路径: + * 1. 存在 pending_domain(切换中)→ 校验 pending_verify_host 的 TXT 是否等于 + * pending_verify_token:通过则由 promotePendingDomain 提升为生效域名并清旧/新域名缓存, + * 返回 verified = true;不通过只累加 pending_verify_attempts 并记 pending_last_error, + * 返回 verified = false。全程不会改动生效域名与证书。 + * 2. 无 pending_domain(切换完成或尚未发起切换)→ 保持升级前口径: + * · 生效域名已验证(domain_status = 1)→ 一律短路 verified = true,不写库、不加 attempts + * (不论库内有无校验码),避免误点「校验」把已生效域名打成验证失败; + * · 生效域名为空 → 400「请先设置域名」; + * · 生效域名非空但未验证/验证失败(升级前登记的历史行)→ 用生效域名的 domain_verify_* + * 校验并回写 domain_status / domain_verify_attempts / domain_last_error(兼容路径)。 + * + * 校验一律以库内一次性随机子域为目标(不用裸域名),避免与用户主域其它 TXT 记录冲突。 + * + * @return {Promise} 域名输出对象 + verified(本次是否通过) + * + resolved_values(本次解析到的 TXT 值,最多 5 条)。 + * @throws {Error} 未识别到当前仓库时抛出 400;未设置域名时抛出 400;非仓库主体时抛出 403; + * 待验证域名已被其他仓库用为生效域名时抛出 409。 + */ + async checkDomain() { + const warehouseId = this.getCurrentWarehouseId(); + + // 仅仓库主体管理员可触发域名校验(isWarehouse 判定) + await this.assertWarehouseSubject(); + + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findOne !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + const record = await configModel.findOne({ + where: { + store_id: warehouseId, + }, + }); + + if (!record) { + throw this.createError('请先设置域名', 400); + } + + const pendingDomain = String(record.get('pending_domain') || '').trim(); + + // ===== 路径一:存在待验证域名 → 校验 pending 的 TXT 记录(通过即提升为生效域名) ===== + if (pendingDomain) { + return this.checkPendingDomainRecord(record, pendingDomain, warehouseId); + } + + // ===== 路径二:无待验证域名 → 生效域名的校验口径(升级前行为,兼容历史行) ===== + const domain = String(record.get('domain') || '').trim(); + if (!domain) { + throw this.createError('请先设置域名', 400); + } + + const domainStatus = Number(record.get('domain_status') || 0); + + // 已验证域名一律短路(不论库内有无校验码): + // 1) 兼容迁移回填的历史行:域名线上已生效(直接视为已验证)但从未生成校验记录; + // 2) 已验证域名不需要重复校验;若不短路,用户误点一次「校验」会走真实 DNS 解析, + // 失败即写 domain_status = 2 且 attempts + 1,把已生效域名降级后被 getByDomain 与 + // nginx 闸门断流; + // 3) 短路不写库、不降状态、不加 attempts,返回结构与 getDomain 口径一致。 + if (domainStatus === DOMAIN_STATUS_VERIFIED) { + return { + ...this.buildDomainOutput(record, warehouseId), + verified: true, + resolved_values: [], + }; + } + + const patch = {}; + let verifyHost = String(record.get('domain_verify_host') || '').trim(); + let verifyToken = String(record.get('domain_verify_token') || '').trim(); + + // 未验证/验证失败(domain_status ∈ {0, 2},已验证行已在上方短路)且库内缺少校验码: + // 补发一份,用户配置 DNS 解析后再次校验即可通过(本次校验仍会因记录未生效而失败) + if (!verifyHost || !verifyToken) { + const verifyCode = this.buildDomainVerifyCode(domain); + verifyHost = verifyCode.host; + verifyToken = verifyCode.token; + patch.domain_verify_host = verifyHost; + patch.domain_verify_token = verifyToken; + } + + const verifyResult = await this.verifyDomainRecord(record, { + host: verifyHost, + token: verifyToken, + }); + + if (verifyResult.verified) { + patch.domain_status = DOMAIN_STATUS_VERIFIED; + patch.domain_verified_at = new Date(); + patch.domain_last_error = null; + } else { + patch.domain_status = DOMAIN_STATUS_FAILED; + patch.domain_verify_attempts = Number(record.get('domain_verify_attempts') || 0) + 1; + patch.domain_last_error = this.sanitizeErrorText(verifyResult.error) || '域名验证失败'; + } + + await record.update(patch); + + // 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量 + const savedRecord = await configModel.findByPk(record.id); + + return { + ...this.buildDomainOutput(savedRecord, warehouseId), + verified: !!verifyResult.verified, + resolved_values: this.buildResolvedValues(verifyResult.values), + }; + } + + /** + * 构建域名验证输出对象(getDomain/setDomain/checkDomain 共用)。 + * + * 返回结构(两阶段切换后扩展,既有字段一律不改名、不删除): + * · 生效域名组:warehouse_id / domain / domain_status / verify_host / verify_value / + * verified_at / attempts / last_error;domain_status = 1(已验证)时 verify_host / + * verify_value 返回空串(校验令牌已无用途,保持既有口径); + * · 待验证域名组(新增):pending_domain / pending_verify_host / pending_verify_value / + * pending_attempts / pending_last_error / pending_created_at / pending_active; + * 无待验证域名时依次返回 '' / '' / '' / 0 / '' / null / false; + * · 公共:cname(CNAME 目标)。 + * 待验证域名的校验码始终回显(pending_domain 非空即有值):该域名尚未生效,用户需要据此配置 TXT。 + * + * @param {Object|null} record 配置记录实例(可为 null,返回空值默认)。 + * @param {number} warehouseId 当前仓库 ID。 + * @return {Object} 域名输出对象(生效组 + 待验证组 + cname)。 + */ + buildDomainOutput(record, warehouseId) { + const hasRecord = !!(record && typeof record.get === 'function'); + const getValue = key => (hasRecord ? record.get(key) : null); + + const domain = hasRecord ? String(getValue('domain') || '').trim() : ''; + const domainStatus = hasRecord ? Number(getValue('domain_status') || 0) : DOMAIN_STATUS_UNVERIFIED; + const exposeVerifyInfo = !!domain && domainStatus !== DOMAIN_STATUS_VERIFIED; + const pendingDomain = hasRecord ? String(getValue('pending_domain') || '').trim() : ''; + + return { + warehouse_id: Number(warehouseId || 0), + domain, + domain_status: domainStatus, + verify_host: exposeVerifyInfo ? String(getValue('domain_verify_host') || '') : '', + verify_value: exposeVerifyInfo ? String(getValue('domain_verify_token') || '') : '', + cname: this.getCnameTarget(), + verified_at: hasRecord ? (getValue('domain_verified_at') || null) : null, + attempts: hasRecord ? Number(getValue('domain_verify_attempts') || 0) : 0, + last_error: hasRecord ? String(getValue('domain_last_error') || '') : '', + // 待验证域名组(追加字段,不影响既有字段语义) + pending_domain: pendingDomain, + pending_verify_host: pendingDomain ? String(getValue('pending_verify_host') || '') : '', + pending_verify_value: pendingDomain ? String(getValue('pending_verify_token') || '') : '', + pending_attempts: hasRecord ? Number(getValue('pending_verify_attempts') || 0) : 0, + pending_last_error: hasRecord ? String(getValue('pending_last_error') || '') : '', + pending_created_at: hasRecord ? (getValue('pending_created_at') || null) : null, + pending_active: !!pendingDomain, + }; + } + + /** + * 规范化 checkDomain 回显的解析值(排障用:限量 + 截断,避免响应被超长/超多记录撑爆)。 + * + * @param {*} values 解析到的 TXT 值列表(可为空/非数组)。 + * @return {string[]} 最多 DOMAIN_RESOLVED_VALUES_LIMIT 条、单条 ≤ DOMAIN_RESOLVED_VALUE_MAX_LENGTH 字符。 + */ + buildResolvedValues(values) { + return (Array.isArray(values) ? values : []) + .slice(0, DOMAIN_RESOLVED_VALUES_LIMIT) + .map(value => String(value).slice(0, DOMAIN_RESOLVED_VALUE_MAX_LENGTH)); + } + + /** + * 域名状态→前端可读文案(用于 can_set_cert_reason,已验证返回空串)。 + * + * @param {number} domainStatus 域名验证状态。 + * @return {string} 状态文案。 + */ + describeDomainStatus(domainStatus) { + if (Number(domainStatus) === DOMAIN_STATUS_VERIFIED) { + return ''; + } + + if (Number(domainStatus) === DOMAIN_STATUS_FAILED) { + return '域名验证失败'; + } + + return '域名待验证'; + } + + /** + * 构建前端配置公共拉取接口的缓存键(按域名)。 + * + * @param {string} domain 域名(内部会 trim 规范化)。 + * @return {string} Redis 缓存键。 + */ + getDomainCacheKey(domain) { + return `front:config:domain:${String(domain || '').trim()}`; + } + + /** + * 构建前端配置公共拉取接口的输出对象(仅公开字段白名单)。 + * + * 安全红线:只输出 PUBLIC_FIELDS 白名单字段, + * 严禁输出 cert_pem/cert_key 证书与私钥内容,以及 cert_path、key_path、 + * sync_status、sync_attempts、last_sync_error 等内部字段。 + * + * @param {Object} record 配置记录实例。 + * @return {Object} 仅含公开字段的输出对象。 + */ + buildPublicOutput(record) { + const hasRecord = !!(record && typeof record.get === 'function'); + const getValue = key => (hasRecord ? record.get(key) : null); + + const output = {}; + for (const key of PUBLIC_FIELDS) { + const value = hasRecord ? getValue(key) : null; + output[key] = key === 'theme' ? (value || null) : (value || ''); + } + return output; + } + + /** + * 清理指定域名的前端配置公共拉取缓存(空域名跳过)。 + * + * @param {string} domain 待清理的域名。 + * @return {Promise} 无返回值。 + */ + async clearDomainCache(domain) { + const normalizedDomain = String(domain || '').trim(); + if (!normalizedDomain) { + return; + } + + await this.deleteCacheByKey(this.getDomainCacheKey(normalizedDomain)); + } + + /** + * 批量清理多个域名的公共拉取缓存(去重、忽略空值,单个失败仅记 WARN 不抛出)。 + * + * 顺序说明(重要):域名提升/切换必须先写库、后清缓存,且旧域名与新域名两个 key 都要清—— + * 公共拉取缓存 key 按域名精确匹配(front:config:domain:{domain}),漏清旧域名会让已下线的 + * 旧域名继续对外返回配置,漏清新域名则让新域名继续返回旧配置。 + * + * @param {string[]} domains 待清理域名列表(可含空值/重复项)。 + * @param {string} [logTag] 日志前缀(定位调用方)。 + * @return {Promise} 无返回值(绝不抛出)。 + */ + async clearDomainCaches(domains, logTag = 'FrontConfigService.clearDomainCaches') { + const uniqueDomains = [ ...new Set( + (Array.isArray(domains) ? domains : []) + .map(item => String(item || '').trim()) + .filter(item => !!item) + ) ]; + + await Promise.all(uniqueDomains.map(domain => this.clearDomainCache(domain) + .catch(error => { + this.ctx.logger.warn('[%s] 清理前端配置缓存失败 domain=%s: %s', logTag, domain, error.message); + }))); + } + + /** + * 构建「清空待验证域名」的更新字段(setDomain 取消待切换 与 promotePendingDomain 共用)。 + * + * 每次调用返回新对象,避免调用方误改共享字面量。 + * + * @return {Object} pending 6 列的清空字段(pending_verify_attempts 归 0,其余置 NULL)。 + */ + buildPendingClearPatch() { + return { + pending_domain: null, + pending_verify_host: null, + pending_verify_token: null, + pending_verify_attempts: 0, + pending_last_error: null, + pending_created_at: null, + }; + } + + /** + * 按域名查询前端配置(公共无鉴权接口业务实现,Redis 缓存 + 查库兜底)。 + * + * 安全红线:只返回公开字段(domain/title/logo_url/login_bg_url/favicon_url/theme), + * 严禁返回 cert_pem/cert_key 证书与私钥内容,以及 cert_path/key_path/ + * sync_status/sync_attempts/last_sync_error 等内部字段。 + * + * @param {string} domain 待查询域名。 + * @return {Promise} 仅含公开字段的配置对象。 + * @throws {Error} domain 为空时抛出 400;未登记域名抛出 404;数据库异常抛出 500。 + */ + async getByDomain(domain) { + const normalizedDomain = String(domain || '').trim(); + + if (!normalizedDomain) { + throw this.createError('domain 不能为空', 400); + } + + if (normalizedDomain.length > 100) { + throw this.createError('domain 长度不能超过 100 字符', 400); + } + + const cacheKey = this.getDomainCacheKey(normalizedDomain); + + // 缓存取舍:命中缓存后 TTL(PUBLIC_CACHE_TTL_SECONDS = 600s)内直接返回, + // 若该行随后被置为「未验证」,理论上最长仍有 600s 会被放行; + // 但 setDomain / saveCert / 域名验证扫描成功均已调用 clearDomainCache 主动失效, + // 实际可通过缓存被放行的窗口很短,接受该取舍。 + // 优先读缓存;Redis 异常时降级查库(getCacheAsync 内部已做 Redis 降级处理) + if (this.app && typeof this.app.getCacheAsync === 'function') { + try { + const cached = await this.app.getCacheAsync(cacheKey); + + // 未登记域名空缓存标记:直接按未配置返回,防穿透 + if (cached && typeof cached === 'object' && cached.configured === false) { + throw this.createError('域名未配置', 404); + } + + if (cached && typeof cached === 'object' && typeof cached.domain === 'string' && cached.domain) { + return cached; + } + } catch (error) { + if (Number(error.code) === 404) { + throw error; + } + this.ctx.logger.warn('[FrontConfigService.getByDomain] 读取缓存失败,降级查库: %s', error.message); + } + } + + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findOne !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + // 应用层闸门:只放行 domain_status = 1(已验证)的域名; + // 迁移尚未执行时 findVerifiedDomainRecord 内部降级为仅按 domain 查询(保持迁移前行为) + const record = await this.findVerifiedDomainRecord(configModel, normalizedDomain); + + if (!record) { + // 缓存穿透兜底:未登记域名写短 TTL 空缓存,防止高频探测打穿数据库 + if (this.app && typeof this.app.setCacheAsync === 'function') { + try { + await this.app.setCacheAsync(cacheKey, { configured: false }, PUBLIC_MISS_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[FrontConfigService.getByDomain] 写入未命中空缓存失败: %s', error.message); + } + } + throw this.createError('域名未配置', 404); + } + + const output = this.buildPublicOutput(record); + + if (this.app && typeof this.app.setCacheAsync === 'function') { + try { + await this.app.setCacheAsync(cacheKey, output, PUBLIC_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[FrontConfigService.getByDomain] 写入缓存失败: %s', error.message); + } + } + + return output; + } + + /** + * 规范化证书/私钥 PEM 文本:去首尾空白,空值返回 null(表示未提供)。 + * + * @param {*} value 原始值(PEM 文本)。 + * @param {string} fieldName 字段名(用于错误提示)。 + * @return {string|null} 规范化后的 PEM 文本;空值返回 null。 + * @throws {Error} 内容超过长度上限时抛出,状态码 400。 + */ + normalizePem(value, fieldName) { + if (value === undefined || value === null) { + return null; + } + + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + + if (normalized.length > PEM_MAX_LENGTH) { + throw this.createError(`${fieldName} 内容长度不能超过 ${PEM_MAX_LENGTH} 字符`, 400); + } + + return normalized; + } + + /** + * 用 Node 内置 crypto.X509Certificate 解析证书 PEM 文本。 + * + * @param {string} certPem 证书 PEM 文本。 + * @return {Object} 解析成功后的 X509Certificate 实例。 + * @throws {Error} 证书无法解析时抛出,状态码 400,统一文案“证书不合法”。 + */ + parseCertPem(certPem) { + try { + return new crypto.X509Certificate(certPem); + } catch (error) { + throw this.createError('证书不合法', 400); + } + } + + /** + * 校验证书有效期:未生效或已过期的证书禁止提交。 + * + * @param {Object} cert 已解析的 X509Certificate 实例。 + * @return {void} 无返回值。 + * @throws {Error} 证书未生效或已过期时抛出,状态码 400,统一文案“证书不合法”。 + */ + assertCertValid(cert) { + const now = Date.now(); + const validFrom = new Date(cert.validFrom); + const validTo = new Date(cert.validTo); + + if (Number.isNaN(validFrom.getTime())) { + throw this.createError('证书不合法', 400); + } + + if (validFrom.getTime() > now) { + throw this.createError('证书不合法', 400); + } + + if (Number.isNaN(validTo.getTime())) { + throw this.createError('证书不合法', 400); + } + + if (validTo.getTime() <= now) { + throw this.createError('证书不合法', 400); + } + } + + /** + * 收集证书可覆盖的域名列表:SAN 中的 DNS 项与 CN,统一转小写。 + * + * @param {Object} cert 已解析的 X509Certificate 实例。 + * @return {string[]} 小写域名列表。 + */ + collectCertNames(cert) { + const names = []; + + const sanText = cert.subjectAltName || ''; + for (const part of String(sanText).split(',')) { + const entry = String(part).trim(); + if (entry.startsWith('DNS:')) { + const dnsName = entry.slice(4).trim(); + if (dnsName) { + names.push(dnsName.toLowerCase()); + } + } + } + + const subjectText = cert.subject || ''; + const cnMatch = /CN\s*=\s*([^,\n]+)/i.exec(String(subjectText)); + if (cnMatch && cnMatch[1]) { + names.push(cnMatch[1].trim().toLowerCase()); + } + + return names; + } + + /** + * 判断证书域名列表是否覆盖目标域名(支持精确匹配与通配符 *.example.com)。 + * + * @param {string[]} names 证书 SAN/CN 域名列表(小写)。 + * @param {string} domain 待校验域名。 + * @return {boolean} 是否覆盖。 + */ + certCoversDomain(names, domain) { + const target = String(domain).toLowerCase(); + if (!target) { + return true; + } + + return names.some(name => { + const normalized = String(name).toLowerCase(); + if (normalized === target) { + return true; + } + + if (normalized.startsWith('*.')) { + const suffix = normalized.slice(1); + if (!target.endsWith(suffix)) { + return false; + } + const prefix = target.slice(0, target.length - suffix.length); + return prefix.length > 0 && !prefix.includes('.'); + } + + return false; + }); + } + + /** + * 校验私钥与证书是否成对:对比两者的 SPKI DER 公钥指纹。 + * + * @param {string} keyPem 私钥 PEM 文本。 + * @param {Object} cert 已解析的 X509Certificate 实例。 + * @return {void} 无返回值。 + * @throws {Error} 私钥无法解析或与证书不匹配时抛出,状态码 400,统一文案“证书不合法”。 + */ + validateKeyPem(keyPem, cert) { + let publicKey; + try { + publicKey = crypto.createPublicKey(keyPem); + } catch (error) { + throw this.createError('证书不合法', 400); + } + + const keySpki = publicKey.export({ type: 'spki', format: 'der' }); + const certSpki = cert.publicKey.export({ type: 'spki', format: 'der' }); + if (Buffer.compare(keySpki, certSpki) !== 0) { + throw this.createError('证书不合法', 400); + } + } + + /** + * 校验当前主体为仓库主体(前端独立部署配置仅仓库主体可操作)。 + * + * @return {Promise} 当前主体对象(含 id/company_name/project/isWarehouse/status)。 + * @throws {Error} 签约关系服务不可用时抛出 500;非仓库主体时抛出 403。 + */ + async assertWarehouseSubject() { + const storeWarehouseService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.storeWarehouse; + if (!storeWarehouseService || typeof storeWarehouseService.getCurrentSubject !== 'function') { + throw this.createError('签约关系服务不可用', 500); + } + + const currentSubject = await storeWarehouseService.getCurrentSubject(); + if (!currentSubject || !currentSubject.isWarehouse) { + throw this.createError('仅仓库主体可配置前端独立部署', 403); + } + + return currentSubject; + } + + /** + * 保存当前仓库前端独立部署品牌配置(upsert,一仓一行,仅品牌字段部分更新)。 + * + * 域名与证书不在本接口受理范围:domain 变更必须走 setDomain(并重新通过域名验证); + * cert_pem/key_pem/cert_path/key_path/cert_expire_at 一律不受理(方法层白名单过滤)。 + * 保存仍视为一次配置变更:同步状态重置为待同步,写库成功后清理当前 domain 的公共拉取缓存。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} [data.title] 站点标题(≤100 字符,空值清空)。 + * @param {string} [data.logo_url] Logo 地址(≤255 字符,空值清空)。 + * @param {string} [data.favicon_url] 站点 favicon 图标地址(≤255 字符,空值清空)。 + * @param {string} [data.login_bg_url] 登录页背景图地址(≤255 字符,空值清空)。 + * @param {Object|string} [data.theme] 主题配置(合法 JSON 对象或 JSON 字符串,空值清空)。 + * @return {Promise} 保存后的品牌信息输出对象(同步状态已重置为待同步;不含证书/私钥字段)。 + * @throws {Error} 非仓库主体时抛出 403;参数非法时抛出 400。 + */ + async saveInfo(data = {}) { + const warehouseId = this.getCurrentWarehouseId(); + + // 仅仓库主体管理员可配置前端独立部署(isWarehouse 判定) + await this.assertWarehouseSubject(); + + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findOne !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + const patch = {}; + + for (const field of TEXT_FIELDS) { + if (Object.prototype.hasOwnProperty.call(data, field.key)) { + patch[field.key] = this.normalizeText(data[field.key], field.name, field.maxLength); + } + } + + if (Object.prototype.hasOwnProperty.call(data, 'theme')) { + patch.theme = this.normalizeTheme(data.theme); + } + + // 保存即重置同步状态:本次保存待同步 + patch.sync_status = 0; + patch.sync_attempts = 0; + patch.last_sync_error = null; + patch.last_synced_at = null; + + let record = await configModel.findOne({ + where: { + store_id: warehouseId, + }, + }); + + // 品牌字段不改变 domain:写库成功后清理当前 domain 的公共拉取缓存即可 + const previousDomain = record ? String(record.get('domain') || '').trim() : ''; + + try { + if (record) { + await record.update(patch); + } else { + record = await configModel.create({ + store_id: warehouseId, + ...patch, + }); + } + } catch (error) { + // 并发写入兜底:唯一索引冲突统一转为业务错误 + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('仓库前端配置保存冲突,请稍后重试', 409); + } + throw error; + } + + // 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量 + const savedRecord = await configModel.findByPk(record.id); + + // 写库成功后清理公共拉取缓存(先写库后清缓存);清缓存失败仅记日志,不影响保存结果 + if (previousDomain) { + await this.clearDomainCache(previousDomain) + .catch(error => { + this.ctx.logger.warn('[FrontConfigService.saveInfo] 清理前端配置缓存失败: %s', error.message); + }); + } + + return this.buildInfoOutput(savedRecord, warehouseId); + } + + /** + * 上传当前仓库前端独立部署证书(证书/私钥成对,需登录、仅仓库主体)。 + * + * domain 不再作为入参受理:域名一律取库内已设置的值(前端若仍传 domain 会被忽略), + * 且必须先通过 DNS TXT 验证(domain_status=1)才允许上传。 + * 校验链:库内域名非空且已验证 → 证书可解析 → 未生效拒绝 → 已过期拒绝 → + * 私钥与证书成对 → 证书 SAN/CN 覆盖库内 domain(支持 *.example.com 通配,不覆盖返回 400)。 + * 证书校验链任一失败均返回统一文案“证书不合法”(400),不返回细节。 + * 通过后自动写入 cert_expire_at(证书 validTo 权威值,不接受前端传值), + * 证书/私钥 PEM 内容直接写入 cert_pem/cert_key 列(内容仅定时任务读取,不写暂存文件); + * cert_path/key_path 保存时置空,避免内容已换而路径陈旧,等待定时任务部署后回填真实路径; + * 同时重置同步状态;写库成功后清理该域名的公共拉取缓存(先写库后清缓存)。 + * + * 两阶段域名切换提示:待验证域名提升(promotePendingDomain)时会清空证书 5 列并重置同步状态, + * 用户必须为新域名重新上传证书;本接口前置闸门(无生效域名/未验证返回 400)与 SAN/CN 覆盖校验 + * 始终以生效域名 domain 为准,存在 pending_domain 不影响本接口受理口径。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} data.pem 证书 PEM 文本(必填)。 + * @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。 + * @return {Promise} 保存后的证书输出对象(13 字段,含证书/私钥原文回显)。 + * @throws {Error} 非仓库主体时抛出 403;未设置/未验证域名、参数非法或证书不合法时抛出 400。 + */ + async saveCert(data = {}) { + const warehouseId = this.getCurrentWarehouseId(); + + // 仅仓库主体管理员可上传前端独立部署证书(isWarehouse 判定) + await this.assertWarehouseSubject(); + + const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig; + if (!configModel || typeof configModel.findOne !== 'function') { + throw this.createError('WarehouseFrontConfig model 不可用', 500); + } + + // 入参必填校验:pem/key 必填(nginx 起 HTTPS 需要成对);data.domain 一律忽略不受理 + const certPem = this.normalizePem(data.pem, 'pem'); + if (!certPem) { + throw this.createError('pem 不能为空', 400); + } + + const keyPem = this.normalizePem(data.key, 'key'); + if (!keyPem) { + throw this.createError('key 不能为空', 400); + } + + const record = await configModel.findOne({ + where: { + store_id: warehouseId, + }, + }); + + // 前置闸门:证书必须挂在当前仓库已设置并验证通过的域名上 + const domain = record ? String(record.get('domain') || '').trim() : ''; + if (!domain) { + throw this.createError('请先设置并验证域名', 400); + } + + if (Number(record.get('domain_status') || 0) !== DOMAIN_STATUS_VERIFIED) { + throw this.createError('域名未通过验证,暂时无法上传证书', 400); + } + + // 校验链:证书可解析 → 未生效/已过期拒绝 → 私钥匹配 → SAN/CN 覆盖库内域名 + const cert = this.parseCertPem(certPem); + this.assertCertValid(cert); + this.validateKeyPem(keyPem, cert); + + const certNames = this.collectCertNames(cert); + if (!this.certCoversDomain(certNames, domain)) { + throw this.createError('证书不合法', 400); + } + + // 证书/私钥内容直接入库(不再写暂存文件),有效期以证书 validTo 权威写入。 + // cert_path/key_path 保存时置空:内容已换而路径陈旧,避免 nginx 误读; + // 等待定时任务(Egg schedule/外部 crontab)部署后回填真实路径。 + // patch 内不再含 domain:本接口已不受理域名变更,域名唯一性由 setDomain 保证,无需重复校验。 + const patch = { + cert_pem: certPem, + cert_key: keyPem, + cert_path: null, + key_path: null, + cert_expire_at: new Date(cert.validTo), + // 保存即重置同步状态:本次上传待同步 + sync_status: 0, + sync_attempts: 0, + last_sync_error: null, + last_synced_at: null, + }; + + try { + await record.update(patch); + } catch (error) { + // 并发写入兜底:唯一索引冲突统一转为业务错误 + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('仓库前端配置保存冲突,请稍后重试', 409); + } + throw error; + } + + // 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量 + const savedRecord = await configModel.findByPk(record.id); + + // 写库成功后清理公共拉取缓存(先写库后清缓存:避免先清后写时并发读把旧值重新写回缓存)。 + // 域名已不能在本接口变更,「旧域名/新域名」必然相同,因此只需清当前域名一个 key; + // 清缓存失败仅记日志,不影响保存结果。 + await this.clearDomainCache(domain) + .catch(error => { + this.ctx.logger.warn('[FrontConfigService.saveCert] 清理前端配置缓存失败: %s', error.message); + }); + + return this.buildCertOutput(savedRecord, warehouseId); + } +} + +module.exports = FrontConfigService; diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js new file mode 100644 index 0000000..ff0b7b5 --- /dev/null +++ b/app/service/systems/inbound_direct_log.js @@ -0,0 +1,1953 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 非收货单途径入库直接记录服务(导入/PDA入库)。 + * + * 职责: + * 1. 根据入库单号获取入库明细(含已记录的导入/PDA 入库记录) + * 2. 按商品增量添加导入/PDA 入库记录,超计划数量时拒绝 + * 3. 提交确认完成入库,写入库存并触发奇门/API 回传 + */ +class InboundDirectLogService extends Service { + + /** + * 获取入库单的受控入库信息(精简版)。 + * 返回入库单基本信息、明细列表(含计划数量与已完成数量)、收货单绑定关系。 + * @param {number} entryOrderId 入库单ID(必填) + * @return {Promise} code/data/message 结构 + * - data.entryOrder: { id, entry_order_code, order_status, store_remask } + * - data.items: [{ id, stock_id, planned, completed, stock, bindings }] + * - data.receivingBindings: 收货单绑定关系列表 + */ + async getItems(entryOrderId) { + const { ctx, app } = this; + const id = Number(entryOrderId || 0); + + if (!id) { + return { code: 400, message: 'id 参数不能为空', data: null }; + } + + const entryOrder = await ctx.model.EntryOrder.findByPk(id, { + include: [ + { + model: ctx.model.EntryItems, + as: 'items', + required: false, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + required: false, + }, + ], + }, + { + model: ctx.model.EntryOrderReceiving, + as: 'receivingBindings', + required: false, + include: [ + { + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ], + required: false, + }, + ], + }, + ], + }); + + if (!entryOrder) { + return { code: 404, message: '入库单不存在', data: null }; + } + + // 校验仓库权限 + if (entryOrder.warehouse_id !== ctx.user.store_id || !entryOrder.is_enabled) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + + // 查询货主商家备注 + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: entryOrder.store_id, warehouse_id: entryOrder.warehouse_id }, + attributes: [ 'store_remask' ], + raw: true, + }); + + // 查询该入库单下已有的导入/PDA 入库记录(显式过滤软删除,仅统计未删除记录) + const directLogs = await ctx.model.InboundDirectLog.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + order: [[ 'created_at', 'ASC' ]], + }); + + // 将直接入库记录按 entry_item_id 关联到明细 + // 优先使用 entry_item_id 精确匹配(绑定模式),其次回退到 stock_id 匹配(非绑定模式) + const itemDirectLogs = {}; + for (const log of directLogs) { + // 绑定模式下 entry_item_id 已设置,优先用它定位明细行 + const itemByEntryItemId = log.entry_item_id + ? entryOrder.items.find(i => String(i.id) === String(log.entry_item_id)) + : null; + const item = itemByEntryItemId || entryOrder.items.find( + i => String(i.stock_id) === String(log.stock_id) + ); + const key = item ? String(item.id) : `stock_${log.stock_id}`; + if (!itemDirectLogs[key]) itemDirectLogs[key] = []; + itemDirectLogs[key].push({ + id: log.id, + stock_id: log.stock_id, + quantity: log.quantity, + inbound_type: log.inbound_type, + space_id: log.space_id, + remark: log.remark, + operator_id: log.operator_id, + operator_name: log.operator_name, + created_at: log.created_at, + }); + } + + // 将入库单层级的收货单绑定扁平化(不再按明细维度) + const receivingBindings = (entryOrder.receivingBindings && entryOrder.receivingBindings.length > 0) + ? entryOrder.receivingBindings.map(rb => ({ + id: rb.id, + receiving_id: rb.receiving_id, + receiving: rb.receiving || null, + })) + : []; + + // 收集所有 stock_id,通过 getStockDetails 批量获取带缓存的商品详情 + const stockIds = [ ...new Set( + (entryOrder.items || []) + .map(item => Number(item.stock_id)) + .filter(id => id && id > 0) + ) ]; + + /** @type {Map} */ + const stockMap = new Map(); + if (stockIds.length > 0) { + const warehouseId = ctx.user.store_id; + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const detail of stockDetails) { + stockMap.set(detail.id, detail); + } + } + + // 组装明细(精简字段,突出已入/总数) + const items = (entryOrder.items || []).map(item => { + const planQty = Number(item.count) || 0; + const logKey = String(item.id); + const logs = itemDirectLogs[logKey] || []; + const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0); + // 优先使用已持久化的 received_quantity(commit 后由系统写入), + // 若为 0 则回退到 InboundDirectLog 汇总(尚未提交时的导入量), + // 确保绑定收货明细场景下 completed 口径与 received_quantity 一致。 + const receivedQty = Number(item.received_quantity) || 0; + const completed = receivedQty > 0 ? receivedQty : directInQty; + + return { + id: item.id, + stock_id: item.stock_id, + planned: planQty, + completed, + stock: stockMap.get(Number(item.stock_id)) || null, + }; + }); + + // 收集所有 InboundDirectLog 中的 space_id,批量查询库位名称 + /** @type {Map} space_id -> space_name */ + const spaceNameMap = new Map(); + const allSpaceIds = [ ...new Set( + Object.values(itemDirectLogs) + .flat() + .map(log => log.space_id) + .filter(id => id != null) + ) ]; + if (allSpaceIds.length > 0) { + const spaces = await ctx.model.LocationSpace.findAll({ + where: { id: { [app.Sequelize.Op.in]: allSpaceIds } }, + attributes: [ 'id', 'custom_name', 'space_code' ], + raw: true, + }); + for (const sp of spaces) { + spaceNameMap.set(sp.id, sp.custom_name || sp.space_code || ''); + } + } + + // 批量查询已绑定的收货明细列表 + const entryItemIds = items.map(i => i.id).filter(Boolean); + /** @type {Map>} 按 entry_item_id 分组 */ + const bindingsMap = new Map(); + if (entryItemIds.length > 0) { + // 1. 查绑定关系表(从 InboundDirectLog 中筛选有 receiving_detail_id 的记录) + const bindingRows = await ctx.model.InboundDirectLog.findAll({ + where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + receiving_detail_id: { [app.Sequelize.Op.ne]: null }, + deleted_at: null, + }, + attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'quantity', 'status' ], + raw: true, + }); + + if (bindingRows.length > 0) { + // 2. 验证收货明细存在性(仅校验,不取冗余字段) + const detailIds = [ ...new Set(bindingRows.map(b => b.receiving_detail_id).filter(Boolean)) ]; + const validDetailIds = new Set(); + if (detailIds.length > 0) { + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: { [app.Sequelize.Op.in]: detailIds } }, + attributes: [ 'id' ], + raw: true, + }); + for (const d of details) { + validDetailIds.add(d.id); + } + } + + // 3. 按 entry_item_id 分组,只保留核心字段 + for (const b of bindingRows) { + const key = b.entry_item_id; + if (!bindingsMap.has(key)) { + bindingsMap.set(key, []); + } + bindingsMap.get(key).push({ + detail_id: b.receiving_detail_id, + binding_id: b.id, + allocated_quantity: b.quantity || 0, + }); + } + } + } + + // 将 bindings 挂到对应 item,并补充库位信息(space_id/space_name 来自 InboundDirectLog) + for (const item of items) { + const bindings = bindingsMap.get(item.id) || []; + const logKey = String(item.id); + const directLogs = itemDirectLogs[logKey] || []; + + // 从 InboundDirectLog 中提取 space_id,并解析库位名称 + // 如果 bindings 为空但有 directLog 带 space_id,则构造一条 binding 展示库位信息 + if (bindings.length === 0 && directLogs.length > 0) { + const firstWithSpace = directLogs.find(l => l.space_id); + if (firstWithSpace) { + item.bindings = [{ + space_id: firstWithSpace.space_id, + space_name: spaceNameMap.get(Number(firstWithSpace.space_id)) || '', + }]; + } else { + item.bindings = []; + } + } else { + // 如果有 bindings,取第一条带 space_id 的 directLog 补充 + const firstWithSpace = directLogs.find(l => l.space_id); + const sid = firstWithSpace ? firstWithSpace.space_id : null; + item.bindings = bindings.map(b => ({ + ...b, + space_id: sid, + space_name: sid != null ? (spaceNameMap.get(Number(sid)) || '') : '', + })); + } + } + + return { + code: 200, + message: '查询成功', + data: { + entryOrder: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + order_status: entryOrder.order_status, + store_remask: (storeWarehouse && storeWarehouse.store_remask) || '', + }, + items, + receivingBindings, + }, + }; + } + + /** + * 单条校验并写入一条导入/PDA 入库记录。 + * @param {Object} ctx Egg.js 上下文对象 + * @param {Object} entryOrder 入库单实例 + * @param {Object} item 入库项,包含 stock_id、quantity、inbound_type、remark、space_id + * @param {Object} [transaction] Sequelize 事务对象,可选 + * @return {Promise<{ok: boolean, log?: Object, error?: Object}>} 返回操作结果,ok 为 true 时 log 包含入库记录详情,ok 为 false 时 error 包含错误信息 + */ + async _addSingleItem(ctx, entryOrder, item, transaction) { + const stockId = Number(item.stock_id || 0); + const quantity = Number(item.quantity || 0); + const inboundType = String(item.inbound_type || '').trim().toLowerCase(); + const remark = item.remark ? String(item.remark).trim() : ''; + const spaceId = item.space_id ? Number(item.space_id) : null; + const receivingDetailId = Number(item.receiving_detail_id || 0); + const isBindingMode = receivingDetailId > 0; + + if (!stockId) { + return { ok: false, error: { code: 400, message: 'items[].stock_id 必填' } }; + } + + // 绑定模式下必须传 space_id + if (isBindingMode && !spaceId) { + return { ok: false, error: { code: 400, message: '绑定收货明细时必须指定 space_id' } }; + } + + // 非绑定模式下校验 quantity 必填且为正整数 + if (!isBindingMode) { + if (!quantity || quantity <= 0 || !Number.isFinite(quantity)) { + return { ok: false, error: { code: 400, message: 'items[].quantity 必须为正整数' } }; + } + } + + if (![ 'import', 'pda' ].includes(inboundType)) { + return { ok: false, error: { code: 400, message: 'items[].inbound_type 必须为 import 或 pda' } }; + } + + // 确定有效数量:绑定模式下自动计算收货明细的可用数量(actual_quantity - 已绑定数量) + let effectiveQuantity = quantity; + if (isBindingMode) { + // 查询收货明细 + const receivingDetail = await ctx.model.ReceivingDetail.findOne({ + where: { id: receivingDetailId }, + ...(transaction ? { transaction } : {}), + }); + if (!receivingDetail) { + return { ok: false, error: { code: 400, message: `收货明细不存在(id=${receivingDetailId})` } }; + } + // 绑定模式下 stock_id 必须匹配收货明细的 system_product_id + if (receivingDetail.system_product_id !== stockId) { + return { ok: false, error: { code: 400, message: `收货明细的商品(system_product_id=${receivingDetail.system_product_id})与传入的 stock_id(${stockId})不匹配` } }; + } + + // 查询该收货明细已被占用的数量(pending + committed),从 InboundDirectLog 查 + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(quantity), 0) AS total + FROM wms_inbound_direct_log + WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + } + ); + const usedQty = Number(allocatedSum?.[0]?.total || 0); + const actualQty = Number(receivingDetail.actual_quantity) || 0; + effectiveQuantity = actualQty - usedQty; + if (effectiveQuantity <= 0) { + return { + ok: false, + error: { + code: 400, + message: `收货明细可用数量不足:实际数量 ${actualQty},已占用 ${usedQty},可用 ${effectiveQuantity}`, + }, + }; + } + } + + // 查找入库单中该 stock_id 对应的所有明细,累加计划数量 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id, stock_id: stockId }, + ...(transaction ? { transaction } : {}), + }); + + if (!entryItems || entryItems.length === 0) { + return { ok: false, error: { code: 400, message: `入库单中不存在 stock_id=${stockId} 的商品` } }; + } + + // 计算该 stock_id 在入库单明细中的计划总数与已收货总数 + const totalPlanQty = entryItems.reduce((sum, ei) => sum + (Number(ei.count) || 0), 0); + const totalReceivedQty = entryItems.reduce((sum, ei) => sum + (Number(ei.received_quantity) || 0), 0); + + // 计算该 stock_id 在该入库单下已有的导入/PDA 入库总量 + const logWhere = { entry_order_id: entryOrder.id, stock_id: stockId }; + const existingLogs = await ctx.model.InboundDirectLog.findAll({ + where: logWhere, + attributes: [ 'quantity' ], + raw: true, + ...(transaction ? { transaction } : {}), + }); + const existingTotal = existingLogs.reduce((sum, log) => sum + Number(log.quantity), 0); + + // 绑定模式和非绑定模式均受可入库数量限制 + // CREATED 人工导入允许超过计划数量 + const isManualImport = entryOrder.order_status === 'CREATED' && !isBindingMode; + if (!isManualImport) { + const maxAllowed = totalPlanQty - existingTotal; + if (maxAllowed <= 0) { + return { + ok: false, + error: { + code: 400, + message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${existingTotal + effectiveQuantity}`, + data: { + stock_id: stockId, + plan_quantity: totalPlanQty, + existing_quantity: existingTotal, + requested_quantity: effectiveQuantity, + exceeded_by: effectiveQuantity, + }, + }, + }; + } + if (effectiveQuantity > maxAllowed) { + effectiveQuantity = maxAllowed; + } + } + + // 剩余可入库数 = 计划数 - max(已收货量, 已写入 direct_log 的待入库量) + // 避免多次 addItem 之间 received_quantity 始终为 0 导致的重复入库漏拦截 + { + const occupiedQuantity = Math.max(totalReceivedQty, existingTotal); + const remainingQuantity = Math.max(0, totalPlanQty - occupiedQuantity); + if (remainingQuantity <= 0) { + return { + ok: false, + error: { + code: 400, + message: `商品 stock_id=${stockId} 无可入库数量:计划 ${totalPlanQty},已收货 ${totalReceivedQty}`, + }, + }; + } + if (effectiveQuantity > remainingQuantity) { + effectiveQuantity = remainingQuantity; + } + } + + const newTotal = existingTotal + effectiveQuantity; + + // 绑定模式:只由 _bindReceivingDetail 负责写入(status='pending'),避免重复插入两条记录 + if (isBindingMode) { + item.allocated_quantity = effectiveQuantity; + const receivingBindResult = await this._bindReceivingDetail( + ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction + ); + + if (receivingBindResult && receivingBindResult.error) { + return { ok: false, error: { code: 400, message: receivingBindResult.error } }; + } + + return { + ok: true, + log: { + id: receivingBindResult?.binding_id || 0, + stock_id: stockId, + quantity: effectiveQuantity, + inbound_type: inboundType, + space_id: spaceId, + plan_quantity: totalPlanQty, + existing_before: existingTotal, + existing_after: newTotal, + remaining: Math.max(0, totalPlanQty - newTotal), + receivingBindResult, + }, + }; + } + + // 非绑定模式:直接写入一条无收货明细绑定的入库记录 + const log = await ctx.model.InboundDirectLog.create({ + warehouse_id: entryOrder.warehouse_id, + store_id: entryOrder.store_id, + stock_id: stockId, + quantity: effectiveQuantity, + inbound_type: inboundType, + entry_order_id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + space_id: spaceId, + remark, + operator_id: ctx.user?.employees_id || ctx.user?.id || null, + operator_name: ctx.user?.employees_name || '', + created_at: new Date(), + }, transaction ? { transaction } : {}); + + return { + ok: true, + log: { + id: log.id, + stock_id: stockId, + quantity: effectiveQuantity, + inbound_type: inboundType, + space_id: spaceId, + plan_quantity: totalPlanQty, + existing_before: existingTotal, + existing_after: newTotal, + remaining: Math.max(0, totalPlanQty - newTotal), + }, + }; + } + + /** + * 将入库直接记录绑定到收货单明细(预占模式,status='pending')。 + * 校验收货明细存在、未取消、可用数量足够后,写入 wms_inbound_direct_log 并确保主表绑定存在。 + * @param {Object} ctx Egg.js 上下文对象 + * @param {Object} entryOrder 入库单实例 + * @param {Object} item 入库项参数,包含 allocated_quantity、item_code 等可选字段 + * @param {number} stockId 商品SKU ID + * @param {number} receivingDetailId 收货单明细ID + * @param {number} quantity 本次入库数量 + * @param {Object} [transaction] Sequelize 事务对象,可选 + * @return {Promise} 返回绑定结果 { binding_id, receiving_detail_id, allocated_quantity, status } + */ + async _bindReceivingDetail(ctx, entryOrder, item, stockId, receivingDetailId, quantity, transaction) { + // 确定预分配数量:优先用 allocated_quantity,否则回退到 quantity + let allocatedQty = Number(item.allocated_quantity || 0); + if (!allocatedQty || allocatedQty <= 0) { + allocatedQty = quantity; + } + if (!Number.isFinite(allocatedQty) || allocatedQty <= 0) { + return { error: 'allocated_quantity 必须为正整数' }; + } + if (allocatedQty > quantity) { + return { error: `allocated_quantity(${allocatedQty}) 不能大于入库数量(${quantity})` }; + } + + // 1. 查询收货明细行(锁定) + const receivingDetail = await ctx.model.ReceivingDetail.findOne({ + where: { id: receivingDetailId }, + ...(transaction ? { lock: transaction.LOCK?.UPDATE, transaction } : {}), + }); + if (!receivingDetail) { + return { error: `收货明细不存在(id=${receivingDetailId})` }; + } + + // 2. 查询已占用(pending + committed)的分配量,从 InboundDirectLog 查 + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(quantity), 0) AS total + FROM wms_inbound_direct_log + WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + } + ); + const usedQty = Number(allocatedSum?.[0]?.total || 0); + const availableQty = (Number(receivingDetail.actual_quantity) || 0) - usedQty; + if (allocatedQty > availableQty) { + return { + error: `收货明细可用数量不足: 可用${availableQty}, 请求${allocatedQty}`, + available_quantity: availableQty, + requested_quantity: allocatedQty, + }; + } + + // 3. 查找入库明细行(entry_item_id) + const entryItem = await ctx.model.EntryItems.findOne({ + where: { + order_id: entryOrder.id, + stock_id: stockId, + }, + ...(transaction ? { transaction } : {}), + }); + + // 4. 写入绑定到 InboundDirectLog(status='pending',预占不提交) + const binding = await ctx.model.InboundDirectLog.create({ + warehouse_id: entryOrder.warehouse_id, + store_id: entryOrder.store_id, + stock_id: stockId, + quantity: allocatedQty, + inbound_type: item.inbound_type || 'import', + entry_order_id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + entry_item_id: entryItem?.id || 0, + receiving_detail_id: receivingDetailId, + space_id: item.space_id ? Number(item.space_id) : null, + status: 'pending', + creator_id: ctx.user?.id || 0, + operator_id: ctx.user?.employees_id || ctx.user?.id || null, + operator_name: ctx.user?.employees_name || '', + }, transaction ? { transaction } : {}); + + return { + binding_id: binding.id, + receiving_detail_id: receivingDetailId, + allocated_quantity: allocatedQty, + status: 'pending', + }; + } + + /** + * 按商品增量添加导入/PDA 入库记录(支持单条和批量)。 + * + * 单条模式(兼容旧调用): + * { entry_order_id, stock_id, quantity, inbound_type, remark } + * + * 批量模式(推荐): + * { entry_order_id, items: [{ stock_id, quantity, inbound_type, remark }] } + * + * 批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。 + * 若该商品在当前入库单中的累计入库量超过计划数量则拒绝。 + * + * 可选收货单明细绑定(批量模式下 items 元素支持): + * { ..., receiving_detail_id, allocated_quantity } + * 传入 receiving_detail_id 后,将校验收货明细可用数量并写入 wms_entry_receiving_binding(status='pending' 预占)。 + * @param {Object} params 请求参数对象 + * @param {number} params.entry_order_id 入库单ID + * @param {number} [params.stock_id] 商品SKU ID(单条模式) + * @param {number} [params.quantity] 本次入库数量(单条模式) + * @param {string} [params.inbound_type] 入库方式(单条模式) + * @param {Array} [params.items] 商品列表(批量模式) + * @param {string} [params.remark] 备注(单条模式) + * @param {number} [params.receiving_detail_id] 收货单明细ID(单条模式,可选,传入后触发预占绑定) + * @param {number} [params.allocated_quantity] 预分配数量(单条模式,可选,默认等于 quantity) + * @return {Promise} 返回 { code, message, data },code=200 表示成功 + */ + async addItem(params) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const entryOrderId = Number(params.entry_order_id) || 0; + + if (!entryOrderId || entryOrderId <= 0) { + return { code: 400, message: 'entry_order_id 必填', data: null }; + } + + // 判断批量/单条模式 + const isBatch = Array.isArray(params.items) && params.items.length > 0; + const items = isBatch ? params.items : [{ + stock_id: params.stock_id, + space_id: params.space_id, + quantity: params.quantity, + inbound_type: params.inbound_type, + remark: params.remark, + receiving_detail_id: params.receiving_detail_id, + allocated_quantity: params.allocated_quantity, + }]; + + // 通过主键查找入库单 + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); + + if (!entryOrder || entryOrder.warehouse_id !== warehouseId) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + + // 检查入库单状态 + if (entryOrder.order_status === 'CANCELLED') { + return { code: 400, message: '已作废入库单不允许操作', data: null }; + } + if (entryOrder.order_status === 'COMPLETED') { + return { code: 400, message: '已完成的入库单不允许操作', data: null }; + } + + // 检查接入库单是否已绑定收货单 + const hasReceivingBindings = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + }); + + // CREATED + 已绑定 → 拒绝(需先走 reviewEntry 审核) + if (entryOrder.order_status === 'CREATED' && hasReceivingBindings) { + return { code: 400, message: '入库单已绑定收货单且状态为 CREATED,请先审核后再进行上架操作', data: null }; + } + + // PENDING 状态:允许导入。items 可传 receiving_detail_id 走绑定模式(预占收货明细), + // 也可不传走非绑定模式(数量受计划数量限制),不再强制绑定收货单、不再强制传收货单 ID; + // 绑定模式下的 space_id/明细可用数量等校验由 _addSingleItem 统一处理。 + + // 批量模式下用事务包裹,任一失败整批回退 + const useTransaction = isBatch; + const txn = useTransaction ? await ctx.model.transaction() : null; + + try { + const results = []; + for (const item of items) { + const result = await this._addSingleItem(ctx, entryOrder, item, txn); + if (!result.ok) { + if (txn) await txn.rollback(); + return result.error; + } + results.push(result.log); + } + + if (txn) await txn.commit(); + + // 非阻塞记录操作日志(批量模式只记一条汇总) + if (results.length > 0) { + const totalQty = results.reduce((s, r) => s + r.quantity, 0); + const types = [ ...new Set(results.map(r => r.inbound_type)) ].join(','); + setImmediate(() => { + ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'DIRECT_INBOUND_ADD', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: `导入/PDA入库添加 ${results.length} 种商品,总数量 ${totalQty},方式 ${types}`, + }, + }).catch(err => { + ctx.logger.error(`[InboundDirectLog] 记录操作日志失败: ${err.message}`); + }); + }); + } + + if (!isBatch) { + const r = results[0]; + return { + code: 200, + message: '添加成功', + data: { ...r }, + }; + } + + return { + code: 200, + message: `添加成功,共 ${results.length} 项`, + data: { + count: results.length, + total_quantity: results.reduce((s, r) => s + r.quantity, 0), + items: results, + }, + }; + } catch (error) { + if (txn && typeof txn.rollback === 'function') { + await txn.rollback(); + } + throw error; + } + } + + /** + * 移除一条导入/PDA 入库记录(仅限未提交的入库单)。 + * @param {Object} params 请求参数对象 + * @param {number} params.id 入库记录ID(wms_inbound_direct_log.id) + * @return {Promise} 返回 { code, message, data },code=200 表示移除成功 + */ + async removeItem(params) { + const { ctx } = this; + const logId = Number(params.id || 0); + + if (!logId) { + return { code: 400, message: 'id 必填', data: null }; + } + + const log = await ctx.model.InboundDirectLog.findByPk(logId); + if (!log) { + return { code: 404, message: '入库记录不存在', data: null }; + } + + // 检查所属入库单状态 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + id: log.entry_order_id, + warehouse_id: ctx.user.store_id, + is_enabled: 1, + deleted_at: null, + }, + }); + + if (!entryOrder) { + return { code: 404, message: '关联入库单不存在或无权访问', data: null }; + } + + if (entryOrder.order_status === 'CANCELLED') { + return { code: 400, message: '已作废入库单不允许操作', data: null }; + } + if (entryOrder.order_status === 'COMPLETED') { + return { code: 400, message: '已完成的入库单不允许移除记录', data: null }; + } + + // 软删除该记录 + await log.destroy(); + + // 非阻塞记录操作日志 + setImmediate(() => { + ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'DIRECT_INBOUND_REMOVE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: `移除导入/PDA入库记录 id=${logId},stock_id=${log.stock_id},数量 ${log.quantity},方式 ${log.inbound_type}`, + }, + }).catch(err => { + ctx.logger.error(`[InboundDirectLog] 记录操作日志失败: ${err.message}`); + }); + }); + + return { + code: 200, + message: '移除成功', + data: { + id: logId, + stock_id: log.stock_id, + quantity: log.quantity, + inbound_type: log.inbound_type, + }, + }; + } + + /** + * 提交确认完成入库(先同步后写库模式)。 + * 先调用 qimenEntrySync 进行奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存。 + * 同步失败则只写 FAILED 状态 + 操作日志,不写库存。 + * @param {number} entryOrderId 入库单 ID + * @param {number} [noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0) + * @return {Promise} code/data/message 结构 + */ + async commit(entryOrderId, noNeedNotice = 0) { + const { ctx, app } = this; + const warehouseId = ctx.user.store_id; + const entryOrderIdNum = Number(entryOrderId) || 0; + + if (!entryOrderIdNum || entryOrderIdNum <= 0) { + return { code: 400, message: 'entry_order_id 必填', data: null }; + } + + // 通过主键查找入库单 + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderIdNum); + + if (!entryOrder || entryOrder.warehouse_id !== warehouseId) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + + if (entryOrder.order_status === 'CANCELLED') { + return { code: 400, message: '已作废入库单不允许完成', data: null }; + } + if (entryOrder.order_status === 'COMPLETED') { + return { code: 400, message: '入库单已完成,请勿重复提交', data: null }; + } + + // 查询该入库单下所有未删除的导入/PDA 入库记录 + const directLogs = await ctx.model.InboundDirectLog.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + }); + + if (!directLogs || directLogs.length === 0) { + return { code: 400, message: '暂无导入/PDA 入库记录,请先添加商品', data: null }; + } + + // 按 stock_id 汇总入库数量 + const stockSummary = {}; + for (const log of directLogs) { + const key = String(log.stock_id); + if (!stockSummary[key]) stockSummary[key] = 0; + stockSummary[key] += Number(log.quantity); + } + + // 查询入库单所有明细 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + }); + + if (!entryItems.length) { + return { code: 400, message: '入库单无明细', data: null }; + } + + const storeId = entryOrder.store_id; + + // ===== 阶段一:先同步奇门/API(事务外) ===== + const items = entryItems.map((item, idx) => ({ + orderLineNo: idx + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: Number(item.count) || 0, + actualQty: stockSummary[String(item.stock_id)] || 0, + })); + + const syncResult = await this.qimenEntrySync({ + entryOrder, + orderLines: items, + outBizCode: `DIRECT_INBOUND_${Date.now()}`, + remark: '导入/PDA直接入库提交', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + // ===== 阶段二:同步成功后在 onSuccess 内开启事务写入库存 ===== + onSuccess: async eo => { + const transaction = await ctx.model.transaction(); + + try { + const processedStockIds = new Set(); + + // 查询 pending 绑定:entry_item_id → 收货明细ID(从 InboundDirectLog 查) + const entryItemIds = entryItems.map(ei => ei.id); + const pendingBindings = await ctx.model.InboundDirectLog.findAll({ + where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + receiving_detail_id: { [app.Sequelize.Op.ne]: null }, + status: 'pending', + deleted_at: null, + }, + attributes: [ 'id', 'entry_item_id', 'receiving_detail_id' ], + raw: true, + }); + + // 查收货明细详情,构建 entry_item_id → 明细信息 的映射 + const detailIds = [ ...new Set(pendingBindings.map(b => b.receiving_detail_id)) ]; + const bindingDetailMap = new Map(); + if (detailIds.length > 0) { + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: detailIds }, + attributes: [ 'id', 'receiving_id', 'batch_number', 'production_date', 'expiry_date', 'actual_quantity' ], + raw: true, + }); + const detailById = new Map(details.map(d => [ d.id, d ])); + for (const b of pendingBindings) { + const d = detailById.get(b.receiving_detail_id); + if (!d) continue; + // 多条绑定取最后一条明细信息,用于批次/生产日期/到期日期等展示字段 + bindingDetailMap.set(b.entry_item_id, d); + } + } + + // 按 entry_item_id 汇总 wms_inbound_direct_log 的入库数量 + const itemDirectLogQtyMap = {}; + for (const log of directLogs) { + if (log.entry_item_id) { + const itemKey = String(log.entry_item_id); + if (!itemDirectLogQtyMap[itemKey]) itemDirectLogQtyMap[itemKey] = 0; + itemDirectLogQtyMap[itemKey] += Number(log.quantity); + } + } + + // 逐商品写入库存 + // 非绑定模式下同一 stock_id 可能对应多个 entryItem,按顺序: + // 第一个 entryItem 写库存和 received_quantity,后续同 stock_id 的 entryItem 仅写 received_quantity=0 + const nonBindingStockProcessed = new Set(); + for (const item of entryItems) { + const stockId = item.stock_id; + if (!stockId) continue; + + // 按 entry_item 维度获取该明细的直接入库汇总数量 + const itemDirectQty = itemDirectLogQtyMap[String(item.id)] || 0; + const isBinding = itemDirectQty > 0; + const inboundQty = isBinding + ? itemDirectQty + : (stockSummary[String(stockId)] || 0); + if (inboundQty <= 0) continue; + + // 判断是否为绑定模式:比较收货明细数量合计与入库记录数量 + const bindInfo = bindingDetailMap.get(item.id); + let itemReceivedQty = inboundQty; + if (bindInfo) { + // 绑定模式下 received_quantity 与库存流水保持一致: + // 统一按实际入库记录量(inboundQty,绑定模式下即 itemDirectQty)写入, + // 不再因收货明细 actual_quantity 较小而缩减 + itemReceivedQty = inboundQty; + } + + // 非绑定模式:同一 stock_id 只对第一个 entryItem 写入 received_quantity,后续写 0 + if (!isBinding && nonBindingStockProcessed.has(String(stockId))) { + itemReceivedQty = 0; + } + + // 更新入库明细的 received_quantity + await ctx.model.EntryItems.update({ + received_quantity: itemReceivedQty, + }, { + where: { id: item.id }, + transaction, + }); + + // 同一 stock_id 只写一次 StockWarehouse 总库存(聚合量),但 Storage 按入库记录逐条写入 + const isStockWarehouseDone = processedStockIds.has(String(stockId)); + if (isStockWarehouseDone && !isBinding) { + // 非绑定模式:StockWarehouse 已写但 Storage 还未写,不能 continue,继续写 Storage + } else if (isStockWarehouseDone) { + continue; + } + if (!isStockWarehouseDone) { + processedStockIds.add(String(stockId)); + if (!isBinding) { + nonBindingStockProcessed.add(String(stockId)); + } + } + + // 使用入库单号作为批次号;若有收货绑定则使用收货明细信息 + const rdReceivingId = bindInfo ? bindInfo.receiving_id : null; + const effectiveBatchNo = bindInfo?.batch_number || eo.entry_order_code; + const rdProductionDate = bindInfo?.production_date || null; + const rdExpiryDate = bindInfo?.expiry_date || null; + const batchNo = eo.entry_order_code; + const inventoryType = item.inventory_type || 'ZP'; + + // StockWarehouse 总库存:每个 stock_id 聚合写入一次 + if (!isStockWarehouseDone) { + // 锁定并更新 StockWarehouse 总库存 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!stockRecord) { + throw new Error(`商品库存记录不存在或已失效,无法入库: stock_id=${stockId}`); + } + + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + // 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据) + if (beforeQuantity <= 0) { + const nonNegativeDelta = Math.max(0, Number(stockRecord.quantity) || 0) - Math.max(0, beforeQuantity); + await ctx.service.systems.storage.index.offsetGapOnInbound(stockId, inboundQty, { + transaction, + maxOffset: nonNegativeDelta, + orderNo: eo.entry_order_code || 'DIRECT_INBOUND', + orderId: eo.id, + operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''), + operatorName: ctx.user?.employees_name || '', + }); + } + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + // 写入库存流水(聚合维度) + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: inboundQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } + + /** + * 写入 Storage 库位库存 + storage_transaction 的通用函数 + * @param {number} spaceId 库位ID + * @param {number} qty 入库数量 + * @param {number|null} rdId 收货单ID + * @param {string|null} prodDate 生产日期 + * @param {string|null} expDate 到期日期 + */ + const writeStorageRecord = async (spaceId, qty, rdId, prodDate, expDate) => { + if (qty <= 0) return; + + const sRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: stockId, + batch_no: effectiveBatchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let sId = null; + let sBeforeQty = 0; + let sAfterQty = 0; + let sBeforeLockedQty = 0; + let sAfterLockedQty = 0; + let sBeforeInterceptQty = 0; + let sAfterInterceptQty = 0; + + if (sRecord) { + if (Number(sRecord.stock_id) !== Number(stockId)) { + throw new Error( + `入库库存归属冲突: storage_id=${sRecord.id} 当前 stock_id=${sRecord.stock_id}, ` + + `本次入库 stock_id=${stockId}, space_id=${spaceId}, batch_no=${effectiveBatchNo}` + ); + } + sBeforeQty = Number(sRecord.quantity) || 0; + sAfterQty = sBeforeQty + qty; + sBeforeLockedQty = Number(sRecord.locked_quantity) || 0; + sAfterLockedQty = sBeforeLockedQty; + sBeforeInterceptQty = Number(sRecord.intercept_locked_quantity) || 0; + sAfterInterceptQty = sBeforeInterceptQty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${qty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${qty}`), + entry_order_id: eo.id, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + production_date: prodDate, + expiry_date: expDate, + receiving_id: rdId, + updated_at: new Date(), + }, { + where: { id: sRecord.id }, + transaction, + }); + sId = sRecord.id; + } else { + sBeforeQty = 0; + sAfterQty = qty; + sBeforeLockedQty = 0; + sAfterLockedQty = 0; + + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: spaceId, + stock_id: stockId, + batch_no: effectiveBatchNo, + inventory_type: inventoryType, + quantity: qty, + locked_quantity: 0, + available_quantity: qty, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + receiving_id: rdId, + entry_order_id: eo.id, + supplier_id: null, + supplier_batch_no: null, + production_date: prodDate, + expiry_date: expDate, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + sId = createdStorage.id; + } + + // 写入库位维度库存流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + storage_id: sId, + space_id: spaceId, + quantity: qty, + before_quantity: sBeforeQty, + after_quantity: sAfterQty, + before_locked_quantity: sBeforeLockedQty, + after_locked_quantity: sAfterLockedQty, + before_intercept_locked_quantity: sBeforeInterceptQty, + after_intercept_locked_quantity: sAfterInterceptQty, + batch_no: effectiveBatchNo, + inventory_type: inventoryType, + order_type: 'entry_order', + order_no: eo.entry_order_code, + order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + created_at: new Date(), + }, { transaction }); + }; + + if (isBinding) { + // 绑定模式:按 entryItem 维度写 Storage(与收货明细绑定,space_id 取第一条入库记录的库位) + const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); + const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; + await writeStorageRecord(spaceId, inboundQty, rdReceivingId, rdProductionDate, rdExpiryDate); + } else { + // 非绑定模式:按每个 InboundDirectLog 记录独立写 Storage,每条记录保有自己指定的 space_id 和 quantity + const stockDirectLogs = directLogs.filter(l => String(l.stock_id) === String(stockId) && Number(l.quantity) > 0); + for (const dlog of stockDirectLogs) { + const dlogSpaceId = dlog.space_id || 1; + const dlogQty = Number(dlog.quantity) || 0; + await writeStorageRecord(dlogSpaceId, dlogQty, null, null, null); + } + } + } + + // 将 pending 绑定升级为 committed(在 InboundDirectLog 中更新状态) + if (pendingBindings.length > 0) { + await ctx.model.InboundDirectLog.update( + { status: 'committed', updated_at: new Date() }, + { where: { id: pendingBindings.map(b => b.id) }, transaction } + ); + } + + // 回写收货单和收货明细的入库状态(绑定模式:按 receiving_detail_id 优先扣减) + await this._syncReceivingStorageStatus({ entryItemIds, transaction, entryOrderId: eo.id }); + + // 非绑定模式剩余导入量:按 stock_id 匹配绑定收货单明细占用(绑定模式优先,剩余兜底) + await this._applyReceivingStockOccupancy({ entryOrder: eo, directLogs, transaction }); + + // 更新入库单状态为 COMPLETED + await eo.update({ + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: JSON.stringify({ + completedAt: new Date(), + totalQuantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), + itemCount: processedStockIds.size, + source: 'direct_inbound', + }), + updated_at: new Date(), + }, { transaction }); + + // 记录操作日志(事务内) + const totalQty = Object.values(stockSummary).reduce((s, q) => s + q, 0); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: eo.id, + operationCode: 'DIRECT_INBOUND_COMMIT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: eo.warehouse_id, + message: `导入/PDA入库提交完成,共 ${processedStockIds.size} 种商品,总数量 ${totalQty}`, + }, + transaction, + }); + + await transaction.commit(); + + // 入库完成通知货主(失败不影响主流程);noNeedNotice=1 时跳过通知 + if (Number(noNeedNotice) !== 1) { + try { + await this.notifyEntryOrderCompleted(eo); + } catch (noticeErr) { + ctx.logger.warn('[inbound_direct_log.commit] 入库完成通知货主失败,不影响业务', noticeErr); + } + } + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; + } + }, + }); + + if (!syncResult.success) { + ctx.logger.warn(`[InboundDirectLog] commit 同步失败 entryOrderId=${entryOrder.id}: ${syncResult.message}`); + return { + code: 500, + message: syncResult.message, + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + sync_status: 'FAILED', + }, + }; + } + + return { + code: 200, + message: '入库完成', + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + items_count: entryItems.length, + total_quantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), + }, + }; + } + + /** + * 发送入库单完成入库通知(entry_order_completed)。 + * 文案格式: + * 首行「入库单号{入库单号}」; + * 明细行「{商品名称} {商家编码} {规格} 数量:{数量}」,行间以「---」分隔; + * 末尾行「已入库完毕」。 + * 明细通过入库单ID查询 wms_entry_items 及关联商品数据,仅展示已入库数量大于 0 的行。 + * 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。 + * 通知失败不影响入库主流程(由调用方 try/catch 包裹)。 + * @param {Object} entryOrder 入库单快照(含 id / entry_order_code / warehouse_id / store_id) + * @return {Promise} 通知发送结果,通知服务不可用或参数不完整时返回 null + */ + async notifyEntryOrderCompleted(entryOrder = {}) { + const { ctx } = this; + const { + id = null, + entry_order_code: entryOrderCodeRaw = '', + warehouse_id: warehouseIdRaw = 0, + store_id: storeIdRaw = 0, + } = entryOrder || {}; + + const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + if (!noticeService) return null; + + const warehouseId = Number(warehouseIdRaw || (ctx.user && ctx.user.store_id) || 0); + const storeId = Number(storeIdRaw || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId) || storeId <= 0) { + return null; + } + + const entryOrderCode = String(entryOrderCodeRaw || id || '').trim(); + if (!entryOrderCode) return null; + + // 组装明细文案:明细查询失败时降级为无明细行,仍发送首行 + 结尾行,保证通知可达 + let detailLines = []; + try { + const completedItems = await this._queryCompletedEntryItems(id); + detailLines = this._buildCompletedItemLines(completedItems); + } catch (detailErr) { + ctx.logger.warn('[inbound_direct_log.notifyEntryOrderCompleted] 查询入库明细失败,通知降级为不含明细文案', detailErr); + } + + const contentLines = [ `入库单号${entryOrderCode}` ]; + for (let i = 0; i < detailLines.length; i++) { + contentLines.push(` ${detailLines[i]}`); + if (i < detailLines.length - 1) contentLines.push('---'); + } + contentLines.push(' 已入库完毕'); + const content = contentLines.join('\n'); + + return await noticeService.send({ + warehouseId, + storeId, + messageType: 'text', + businessName: 'entry_order', + event: 'entry_order_completed', + channel: 'warehouse', + title: `入库单${entryOrderCode}已完成入库`, + content, + storeContent: content, + businessId: id, + subject: { + id: warehouseId, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: (ctx.user && (ctx.user.employees_id || ctx.user.id)) || null, + name: (ctx.user && ctx.user.employees_name) || '', + }, + metadata: { + entryOrderId: id, + entryOrderCode, + warehouseId, + storeId, + }, + }); + } + + /** + * 查询入库单明细(含商品资料),用于组装完成入库通知文案。 + * 复用 EntryItems → StockWarehouse 的既有模型关联,不直接写 SQL。 + * @param {number} entryOrderId 入库单ID + * @return {Promise>} 入库明细列表(含 stock 关联数据),入参无效时返回空数组 + */ + async _queryCompletedEntryItems(entryOrderId) { + const { ctx } = this; + const orderId = Number(entryOrderId || 0); + if (!Number.isFinite(orderId) || orderId <= 0) return []; + + return await ctx.model.EntryItems.findAll({ + where: { order_id: orderId }, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + required: false, + attributes: [ 'id', 'item_name', 'sku_property' ], + }, + ], + order: [[ 'order_line_no', 'ASC' ]], + }); + } + + /** + * 将入库明细组装为通知文案明细行。 + * 每行格式:{商品名称} {商家编码} {规格} 数量:{数量}, + * 仅展示已入库数量(received_quantity)大于 0 的明细行。 + * 字段来源:商品名称=stock.item_name、商家编码=item.item_code、规格=stock.sku_property、数量=item.received_quantity。 + * @param {Array} entryItems 入库明细列表(含 stock 关联数据) + * @return {Array} 通知文案明细行列表 + */ + _buildCompletedItemLines(entryItems = []) { + const lines = []; + for (const item of entryItems || []) { + const inboundQty = Number(item.received_quantity) || 0; + if (inboundQty <= 0) continue; + + const stock = item.stock || {}; + const itemName = String(stock.item_name || '').trim(); + const merchantCode = String(item.item_code || '').trim(); + const skuProperty = String(stock.sku_property || '').trim(); + + lines.push(`${itemName} ${merchantCode} ${skuProperty} 数量:${inboundQty}`); + } + return lines; + } + + /** + * 组装 entryorder.confirm 业务报文(与奇门 taobao.qimen.entryorder.confirm 同层级)。 + * 返回 { entryOrder, orderLines },不包含外层 request 包装, + * 字段与取值逻辑以奇门分支为唯一基准,奇门与 OpenAPI 回传共用。 + * @param {Object} entryOrder 入库单对象 + * @param {Array} orderLines 入库明细行数组 + * @param {Object} [options] 可选配置 + * @param {string} [options.outBizCode] 外部业务编码,缺省时自动生成 DIRECT_INBOUND_时间戳 + * @param {boolean} [options.isFin=true] 是否最终确认(confirmType 0=最终 / 1=部分,status FULFILLED / PARTFULFILLED) + * @param {string} [options.remark] 备注 + * @return {{ entryOrder: Object, orderLines: Array }} 组装后的业务报文 + */ + buildEntryOrderConfirmRequest(entryOrder, orderLines, options = {}) { + const { app } = this; + const { outBizCode, isFin = true, remark } = options; + + return { + entryOrder: { + entryOrderCode: entryOrder.entry_order_code, + ownerCode: entryOrder.qimen_owner_code || '', + warehouseCode: entryOrder.qimen_warehouse_code || '', + entryOrderId: entryOrder.id, + entryOrderType: entryOrder.order_type, + outBizCode: outBizCode || `DIRECT_INBOUND_${Date.now()}`, + confirmType: isFin ? 0 : 1, + status: isFin ? 'FULFILLED' : 'PARTFULFILLED', + freight: 0, + operateTime: app.formatDate(new Date()), + remark: remark || '', + }, + orderLines, + }; + } + + /** + * OpenAPI 回传:查询 ApiApp 回调地址并 POST 回传。 + * 报文体与奇门同层级({ request: { entryOrder, orderLines } },外层 request 由发送端自动包裹), + * 与奇门分支共用 buildEntryOrderConfirmRequest 组装。 + * @param {Object} entryOrder 入库单 + * @param {Object} [options] 可选配置 + * @param {Object} options.request 奇门同层级业务报文 { entryOrder, orderLines }(由 buildEntryOrderConfirmRequest 组装) + * @param {boolean} [options.throwOnError=false] 失败时是否向外抛出异常 + * @return {Promise} 返回回传结果 { success, error?, statusCode?, body? },异常时返回 null + */ + async _sendOpenApiCallback(entryOrder, options = {}) { + const { ctx, app } = this; + const { request, throwOnError = false } = options; + + try { + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: entryOrder.store_id, + warehouse_id: entryOrder.warehouse_id, + auth_status: 2, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!storeWarehouse) { + const warnMsg = `[InboundDirectLog] OpenAPI回传:未找到授权关系 entryOrderId=${entryOrder.id}`; + ctx.logger.warn(warnMsg); + console.log('[quickInbound] _sendOpenApiCallback 最终返回:', { success: false, error: '未找到授权关系' }); + if (throwOnError) { + throw new Error(warnMsg); + } + return null; + } + + const apiApp = await ctx.model.ApiApp.findOne({ + where: { + contract_id: storeWarehouse.id, + is_enabled: 1, + callback_url: { + [ app.Sequelize.Op.and ]: [ + { [ app.Sequelize.Op.ne ]: null }, + { [ app.Sequelize.Op.ne ]: '' }, + ], + }, + }, + attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ], + raw: true, + }); + + if (!apiApp || !apiApp.callback_url) { + const warnMsg = `[InboundDirectLog] OpenAPI回传:未找到有效ApiApp配置 entryOrderId=${entryOrder.id}`; + ctx.logger.warn(warnMsg); + console.log('[quickInbound] _sendOpenApiCallback 最终返回:', { success: false, error: '未找到ApiApp配置' }); + if (throwOnError) { + throw new Error(warnMsg); + } + return null; + } + + console.log('[quickInbound] _sendOpenApiCallback 发送前:', { + entryOrderId: entryOrder.id, + callbackUrl: apiApp.callback_url, + appKey: apiApp.self_app_key, + request, + }); + + const result = await ctx.service.openapi.callback.sendWithRetry({ + callbackUrl: apiApp.callback_url, + appKey: apiApp.self_app_key, + selfAppSecret: apiApp.self_app_secret || '', + event: 'entryorder.confirm', + request, + }); + + console.log('[quickInbound] _sendOpenApiCallback 响应:', { + entryOrderId: entryOrder.id, + success: result?.success, + statusCode: result?.statusCode, + error: result?.error, + body: typeof result?.body === 'string' ? result.body.substring(0, 500) : JSON.stringify(result?.body || {}).substring(0, 500), + }); + + if (result.success) { + ctx.logger.info( + `[InboundDirectLog] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + + `callbackUrl=${apiApp.callback_url}` + ); + } else { + const failMsg = `[InboundDirectLog] OpenAPI回传失败 entryOrderId=${entryOrder.id} error=${result.error}`; + ctx.logger.warn(failMsg); + if (throwOnError) { + throw new Error(failMsg); + } + } + + console.log('[quickInbound] _sendOpenApiCallback 最终返回:', result); + return result; + } catch (error) { + ctx.logger.error(`[InboundDirectLog] OpenAPI回传异常: ${error.message}`, error.stack); + console.log('[quickInbound] _sendOpenApiCallback 最终返回 (异常):', { success: false, error: error.message }); + if (throwOnError) { + throw error; + } + return null; + } + } + + /** + * 奇门入库同步(统一入口)。 + * 先发奇门 entryorder.confirm 请求,成功才执行本地回调,失败则写操作日志并返回失败。 + * + * @param {Object} params 参数对象 + * @param {Object} params.entryOrder - 入库单完整对象(EntryOrder model instance) + * @param {Array} params.orderLines - 明细行数组 [{ orderLineNo, ownerCode, itemCode, itemId, inventoryType, planQty, actualQty }] + * @param {string} params.outBizCode - 外部业务编码(如 DIRECT_INBOUND_xxx) + * @param {string} params.remark - 备注(如 "导入/PDA直接入库提交") + * @param {boolean} [params.isFin=true] - 是否最终确认(confirmType: 0=最终, 1=部分) + * @param {Function} params.onSuccess - 同步成功后执行的回调(接收 entryOrder),在独立事务中执行,应包含业务写库 + operationLog(QUICK_INBOUND) + * @param {Object} params.operator - 操作人 { id, name },用于 operationLog + * @return {Promise} { success: boolean, message: string, data?: any } + */ + async qimenEntrySync(params) { + const { ctx, app } = this; + const { + entryOrder, + orderLines, + outBizCode, + remark, + isFin = true, + onSuccess, + operator, + } = params; + + console.log('[qimenEntrySync] 进入:', { + entryOrderId: entryOrder?.id, + entryOrderCode: entryOrder?.entry_order_code, + sourceType: entryOrder?.source_type, + orderLinesCount: orderLines?.length, + isFin, + }); + + // 1. 校验 + if (!orderLines || orderLines.length === 0) { + console.log('[qimenEntrySync] 最终判定: failure (行不能为空)'); + return { success: false, message: '行不能为空' }; + } + + // 2. 按来源类型分别处理 + const sourceType = String(entryOrder.source_type || '').toUpperCase(); + + if (sourceType !== 'QM' && sourceType !== 'API') { + const skipMsg = `来源类型 ${sourceType} 不支持回传`; + console.log(`[qimenEntrySync] 最终判定: 跳过 (${skipMsg})`); + ctx.logger.info(`[qimenEntrySync] ${skipMsg} entryOrderId=${entryOrder.id}`); + + // 不需要回传的来源类型,直接执行回调 + if (onSuccess) { + await onSuccess(entryOrder); + } + return { success: true, message: `无需同步,来源类型: ${sourceType}` }; + } + + // 3. 构造 queryData 并发请求(事务外) + if (sourceType === 'QM') { + const queryData = { + request: this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { + outBizCode, + remark, + isFin, + }), + }; + + console.log('[qimenEntrySync] 奇门请求发送前:', { + entryOrderId: entryOrder.id, + api: 'taobao.qimen.entryorder.confirm', + ownerCode: entryOrder.qimen_owner_code, + queryData, + }); + + let qimenResult; + try { + const result = await app.qimenClient.send( + 'taobao.qimen.entryorder.confirm', + entryOrder.qimen_owner_code, + queryData, + { ctx } + ); + qimenResult = result?.xmlArray?.response; + } catch (err) { + qimenResult = { flag: 'error', code: '-1', message: err.message }; + } + + console.log('[qimenEntrySync] 奇门响应:', { + entryOrderId: entryOrder.id, + flag: qimenResult?.flag, + code: qimenResult?.code, + message: qimenResult?.message, + }); + + const isQimenSuccess = qimenResult && String(qimenResult.flag) === 'success'; + + if (!isQimenSuccess) { + const failMsg = qimenResult?.message || '奇门同步失败'; + console.log(`[qimenEntrySync] 最终判定: failure (${failMsg})`); + + const txn = await ctx.model.transaction(); + try { + await entryOrder.update({ + sync_status: 'FAILED', + sync_message: JSON.stringify({ + error: failMsg, + errorCode: 'QIMEN_FAILED', + errorTime: new Date().toISOString(), + source: 'qimenEntrySync', + }), + updated_at: new Date(), + }, { transaction: txn }); + + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'QUICK_INBOUND_FAILED', + operator: operator || {}, + extras: { warehouseId: entryOrder.warehouse_id, message: failMsg }, + transaction: txn, + }); + + await txn.commit(); + } catch (e) { + await txn.rollback(); + ctx.logger.error(`[qimenEntrySync] 失败日志写入异常: ${e.message}`); + } + + return { success: false, message: failMsg }; + } + + // 4. 成功:执行回调 + ctx.logger.info(`[qimenEntrySync] 奇门回传成功 entryOrderId=${entryOrder.id}`); + console.log('[qimenEntrySync] 最终判定: success'); + + if (onSuccess) { + await onSuccess(entryOrder); + } + + return { success: true, message: '同步成功' }; + } + + // API 来源:调用 OpenAPI 回传 + if (sourceType === 'API') { + console.log('[qimenEntrySync] OpenAPI 回传开始:', { + entryOrderId: entryOrder.id, + }); + + let apiResult; + try { + apiResult = await this._sendOpenApiCallback(entryOrder, { + throwOnError: true, + request: this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { + outBizCode, + remark, + isFin, + }), + }); + } catch (err) { + apiResult = { success: false, error: err.message }; + } + + console.log('[qimenEntrySync] OpenAPI 回传结果:', apiResult); + + const isApiSuccess = apiResult && apiResult.success === true; + + if (!isApiSuccess) { + const failMsg = apiResult?.error || 'API回传失败'; + console.log(`[qimenEntrySync] 最终判定: failure (${failMsg})`); + + const txn = await ctx.model.transaction(); + try { + await entryOrder.update({ + sync_status: 'FAILED', + sync_message: JSON.stringify({ + error: failMsg, + errorCode: 'API_FAILED', + errorTime: new Date().toISOString(), + source: 'qimenEntrySync', + }), + updated_at: new Date(), + }, { transaction: txn }); + + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'QUICK_INBOUND_FAILED', + operator: operator || {}, + extras: { warehouseId: entryOrder.warehouse_id, message: failMsg }, + transaction: txn, + }); + + await txn.commit(); + } catch (e) { + await txn.rollback(); + ctx.logger.error(`[qimenEntrySync] API失败日志写入异常: ${e.message}`); + } + + return { success: false, message: failMsg }; + } + + ctx.logger.info(`[qimenEntrySync] OpenAPI回传成功 entryOrderId=${entryOrder.id}`); + console.log('[qimenEntrySync] 最终判定: success (API)'); + + if (onSuccess) { + await onSuccess(entryOrder); + } + + return { success: true, message: '同步成功' }; + } + } + + /** + * 根据已提交(committed)的入库明细-收货明细绑定,回写收货单及收货明细的入库状态。 + * 在事务内执行,读取 committed 绑定并按 receiving_detail_id 汇总。 + * + * @param {Object} params 参数 + * @param {number[]} params.entryItemIds 当前入库单的所有明细 ID 列表 + * @param {Object} params.transaction Sequelize 事务对象 + * @param {number} [params.entryOrderId] 入库单 ID(用于同步数量台账) + * @return {Promise} + */ + async _syncReceivingStorageStatus({ entryItemIds, transaction, entryOrderId = null }) { + const { ctx, app } = this; + + // 查询所有 committed 状态的绑定记录(从 InboundDirectLog 中筛选有 receiving_detail_id 的记录) + const committedBindings = await ctx.model.InboundDirectLog.findAll({ + where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + receiving_detail_id: { [app.Sequelize.Op.ne]: null }, + status: 'committed', + deleted_at: null, + }, + attributes: [ 'receiving_detail_id', 'quantity' ], + raw: true, + transaction, + }); + + if (!committedBindings || committedBindings.length === 0) { + return; + } + + // 按 receiving_detail_id 汇总 quantity + const detailQuantityMap = new Map(); + for (const b of committedBindings) { + const detailId = b.receiving_detail_id; + const qty = Number(b.quantity) || 0; + detailQuantityMap.set(detailId, (detailQuantityMap.get(detailId) || 0) + qty); + } + + const detailIds = [ ...detailQuantityMap.keys() ]; + + // 查询收货明细(含 actual_quantity 和 receiving_id) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: detailIds }, + attributes: [ 'id', 'receiving_id', 'actual_quantity', 'stored_quantity', 'storage_status' ], + raw: true, + transaction, + }); + + if (!details.length) { + return; + } + + // 逐条计算并更新收货明细 + const receivingIdSet = new Set(); + const ledgerQuantityMap = new Map(); + for (const detail of details) { + const storedQuantity = detailQuantityMap.get(detail.id) || 0; + const actualQuantity = Number(detail.actual_quantity) || 0; + const storageStatus = storedQuantity >= actualQuantity + ? 'all' + : (storedQuantity > 0 ? 'partial' : 'none'); + + receivingIdSet.add(detail.receiving_id); + + await ctx.model.ReceivingDetail.update( + { + stored_quantity: storedQuantity, + storage_status: storageStatus, + updated_at: new Date(), + }, + { + where: { id: detail.id }, + transaction, + } + ); + + // 台账覆盖条目:绑定模式对收货明细为直接覆写语义 + ledgerQuantityMap.set(detail.id, { + receivingId: Number(detail.receiving_id), + quantity: storedQuantity, + }); + } + + // 按收货单汇总,更新 wms_receiving.storage_status + const receivingIds = [ ...receivingIdSet ]; + if (receivingIds.length === 0) { + return; + } + + // 重新查询该收货单下所有明细的 storage_status,汇总主表状态 + const allDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingIds }, + attributes: [ 'receiving_id', 'storage_status' ], + raw: true, + transaction, + group: [ 'receiving_id', 'storage_status' ], + }); + + // 按 receiving_id 分组 + const receivingDetailStatusMap = new Map(); + for (const d of allDetails) { + const rid = d.receiving_id; + if (!receivingDetailStatusMap.has(rid)) { + receivingDetailStatusMap.set(rid, new Set()); + } + receivingDetailStatusMap.get(rid).add(d.storage_status); + } + + for (const [ rid, statusSet ] of receivingDetailStatusMap) { + let receivingStorageStatus = 'none'; + if (statusSet.has('all') && statusSet.has('partial')) { + receivingStorageStatus = 'partial'; + } else if (statusSet.has('all')) { + if (statusSet.has('none') || statusSet.has('waiting')) { + receivingStorageStatus = 'partial'; + } else { + receivingStorageStatus = 'all'; + } + } else if (statusSet.has('partial')) { + receivingStorageStatus = 'partial'; + } + + await ctx.model.Receiving.update( + { + storage_status: receivingStorageStatus, + updated_at: new Date(), + }, + { + where: { id: rid }, + transaction, + } + ); + } + + // 同步数量台账:绑定模式按 committed 汇总量覆写对应明细条目(保持台账与 stored_quantity 一致) + if (entryOrderId && ledgerQuantityMap.size > 0) { + await ctx.service.systems.receivingEntryMatch.setLedgerAllocation({ + entryOrderId, + detailQuantityMap: ledgerQuantityMap, + transaction, + }); + } + } + + /** + * 非绑定模式收货单占用:导入记录未携带 receiving_detail_id 时, + * 将剩余导入量按 stock_id(=收货明细 system_product_id)匹配到绑定收货单明细上, + * 依次占用剩余可入数量(actual_quantity - stored_quantity), + * 回写 stored_quantity/storage_status 并汇总收货单主表 storage_status。 + * 携带 receiving_detail_id 的导入记录已由 _syncReceivingStorageStatus 优先处理, + * 本方法只处理未携带 receiving_detail_id 的剩余部分(必须先调用前者)。 + * + * @param {Object} params 参数 + * @param {Object} params.entryOrder 入库单实例 + * @param {Array} params.directLogs 入库单下所有未删除的导入/PDA 入库记录 + * @param {Object} params.transaction Sequelize 事务对象 + * @return {Promise} + */ + async _applyReceivingStockOccupancy({ entryOrder, directLogs, transaction }) { + const { ctx, app } = this; + + // 1. 入库单未绑定收货单 → 跳过 + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + transaction, + }); + const receivingIds = [ ...new Set((bindings || []).map(b => Number(b.receiving_id)).filter(Boolean)) ]; + if (receivingIds.length === 0) return; + + // 2. 汇总未携带 receiving_detail_id 的导入量(绑定模式已优先处理,这里只取剩余部分) + const stockInboundQtyMap = new Map(); + for (const log of directLogs) { + if (log.receiving_detail_id) continue; + const stockId = Number(log.stock_id); + const qty = Number(log.quantity) || 0; + if (!stockId || qty <= 0) continue; + stockInboundQtyMap.set( + stockId, + { inboundQty: (stockInboundQtyMap.get(stockId)?.inboundQty || 0) + qty } + ); + } + if (stockInboundQtyMap.size === 0) return; + + // 3. 查询绑定收货单明细(事务内读取,stored_quantity 已包含绑定模式扣减结果) + const boundDetails = await ctx.model.ReceivingDetail.findAll({ + where: { + receiving_id: { [app.Sequelize.Op.in]: receivingIds }, + system_product_id: { [app.Sequelize.Op.ne]: null }, + }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], + raw: true, + transaction, + }); + if (!boundDetails || boundDetails.length === 0) return; + + // 4. 复用 storage.entry 的收货单占用逻辑(与 quickInbound 一致,事务内行锁防并发超分) + await ctx.service.systems.storage.entry._applyReceivingInboundUsage({ + receivingDetailRows: boundDetails, + stockInboundQtyMap, + transaction, + entryOrderId: entryOrder.id, + }); + + ctx.logger.info( + `[InboundDirectLog] 非绑定模式导入已按 stock_id 占用收货单明细,entryOrderId=${entryOrder.id}` + ); + } +} + +module.exports = InboundDirectLogService; diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js new file mode 100644 index 0000000..4c8735f --- /dev/null +++ b/app/service/systems/inbox/group.js @@ -0,0 +1,797 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +// 从分组服务导入群类型定义,用于两层类型校验 +const { GROUP_TYPES: INBOX_GROUP_TYPES } = require('../../inbox/groups'); + +/** + * 站内信群管理业务逻辑层。 + * 提供群列表查询、禁用、修改等核心能力。 + */ +class InboxGroupService extends Service { + /** + * 拉取当前仓库的群列表。 + * + * @param {Object} data 请求数据。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {string} [data.keyword] 按群名称模糊搜索。 + * @param {number} [data.page=1] 页码。 + * @param {number} [data.pageSize=20] 每页条数。 + * @return {Promise} { total, list }。 + */ + async list(data = {}) { + const { ctx } = this; + const { InboxGroup, StoreWarehouse, ExpressInterface, Express } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(data.warehouseId); + + // 分页:优先取 pagination 对象,兜底扁平参数 + const pag = data.pagination || {}; + const page = Math.max(1, Number(pag.page || data.page) || 1); + const pageSize = Math.min(100, Math.max(1, Number(pag.pageSize || data.pageSize) || 20)); + const offset = (page - 1) * pageSize; + + if (!warehouseId) throw new Error('warehouseId 无效'); + + const where = { warehouse_id: warehouseId }; + + // ── 扁平参数(向后兼容)── + const groupType = String(data.groupType || '').trim(); + const keyword = String(data.keyword || '').trim(); + if (groupType) where.group_type = groupType; + if (keyword) where.group_name = { [Op.like]: `%${keyword}%` }; + + // ── 结构化 where(operator 模式)── + if (data.where && typeof data.where === 'object') { + // 从 where 中提取虚拟字段(不允许直接作为列名查询) + const whereInput = { ...data.where }; + + // keyword:虚拟字段 → 模糊搜索 group_name + if (whereInput.keyword !== undefined) { + const kw = whereInput.keyword; + delete whereInput.keyword; + const kwValue = kw && typeof kw === 'object' && kw.value !== undefined ? kw.value : kw; + const kwArr = Array.isArray(kwValue) ? kwValue : [ kwValue ]; + const kwStr = kwArr.filter(Boolean).join('').trim(); + if (kwStr && !keyword) { + where.group_name = { [Op.like]: `%${kwStr}%` }; + } + } + + // groupType: camelCase → group_type(优先已从扁平参数设置的 group_type) + if (whereInput.groupType !== undefined) { + const gt = whereInput.groupType; + delete whereInput.groupType; + const gtValue = gt && typeof gt === 'object' && gt.value !== undefined ? gt.value : gt; + const gtStr = String(gtValue || '').trim(); + if (gtStr && !groupType) { + where.group_type = gtStr; + } + } + + if (Object.keys(whereInput).length > 0) { + const parsed = parseWhereConditions({ + where: whereInput, + app: ctx.app, + specialFieldMap: { + store_id: { field: 'store_id' }, + group_id: { field: 'group_id' }, + group_name: { field: 'group_name' }, + sub_type: { field: 'sub_type' }, + source_type: { field: 'source_type' }, + is_blocked: { field: 'is_blocked' }, + ai_enabled: { field: 'ai_enabled' }, + template_reply_enabled: { field: 'template_reply_enabled' }, + system_express_code: { field: 'system_express_code' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + if (Array.isArray(parsed.result.dynamicConditions)) { + Object.assign(where, ...parsed.result.dynamicConditions); + } + } + } + + const { count, rows } = await InboxGroup.findAndCountAll({ + attributes: [ + 'id', 'group_name', 'group_id', 'store_id', + 'group_type', 'sub_type', 'source_type', 'source_extra', + 'is_blocked', 'ai_enabled', 'template_reply_enabled', + 'express_interfaces', 'system_express_code', + 'created_at', 'updated_at', + ], + where, + order: [[ 'created_at', 'DESC' ]], + limit: pageSize, + offset, + raw: true, + }); + + // 收集需要批量查询的 ID + const storeIds = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ]; + const allExpressInterfaceIds = []; + const expressCodes = [ ...new Set(rows.map(r => r.system_express_code).filter(Boolean)) ]; + + rows.forEach(row => { + if (row.express_interfaces) { + const ids = row.express_interfaces.split(',').map(Number).filter(Boolean); + ids.forEach(id => allExpressInterfaceIds.push(id)); + } + }); + const uniqueExpressInterfaceIds = [ ...new Set(allExpressInterfaceIds) ]; + + // 批量查询货主仓库合约备注 + let storeWarehouseMap = {}; + if (storeIds.length > 0) { + const swRows = await StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { + store_id: { [Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + raw: true, + }); + storeWarehouseMap = swRows.reduce((acc, sw) => { + acc[sw.store_id] = sw.store_remask || ''; + return acc; + }, {}); + } + + // 批量查询快递接口名称 + let expressInterfaceMap = {}; + if (uniqueExpressInterfaceIds.length > 0) { + const eiRows = await ExpressInterface.findAll({ + attributes: [ 'id', 'name' ], + where: { id: { [Op.in]: uniqueExpressInterfaceIds } }, + raw: true, + }); + expressInterfaceMap = eiRows.reduce((acc, ei) => { + acc[ei.id] = ei.name || ''; + return acc; + }, {}); + } + + // 批量查询系统快递名称 + let expressNameMap = {}; + if (expressCodes.length > 0) { + const expressRows = await Express.findAll({ + attributes: [ 'code', 'name' ], + where: { code: { [Op.in]: expressCodes } }, + raw: true, + }); + expressNameMap = expressRows.reduce((acc, e) => { + acc[e.code] = e.name || ''; + return acc; + }, {}); + } + + // 组装返回数据 + const formatDate = ctx.app.formatDate; + const list = rows.map(row => ({ + ...row, + store_name: row.store_id ? (storeWarehouseMap[row.store_id] || '') : '', + express_interfaces: row.express_interfaces + ? row.express_interfaces.split(',').map(Number).filter(Boolean) + .map(id => ({ + id, + name: expressInterfaceMap[id] || '', + })) + : [], + system_express_name: row.system_express_code + ? (expressNameMap[row.system_express_code] || '') + : '', + created_at: row.created_at ? formatDate(row.created_at) : '', + updated_at: row.updated_at ? formatDate(row.updated_at) : '', + })); + + return { total: count, list }; + } + + /** + * 群快速查询(下拉选择用,不分页)。 + * 关键词同时模糊匹配群名称与外部群ID,按创建时间倒序返回轻量字段, + * 软删除记录由 paranoid 自动排除。 + * 双维度可选过滤,均不传时 where 不含这两列、返回所有仓库/货主的群: + * - store_id(货主维度)↔ wms_inbox_group.store_id 列; + * - warehouse_id(仓库维度)↔ wms_inbox_group.warehouse_id 列; + * - 两者可同时传(AND 关系),也可都不传(不加对应过滤条件)。 + * + * @param {Object} data 请求数据。 + * @param {number|string} [data.storeId] 货主ID(可选,来自 API 入参 store_id,映射到 wms_inbox_group.store_id 列; + * 传入时须为可解析的正整数,否则抛错「store_id 无效」;不传或为空时不加货主过滤)。 + * @param {number|string} [data.warehouseId] 仓库ID(可选,来自 API 入参 warehouse_id,映射到 wms_inbox_group.warehouse_id 列; + * 传入时须为可解析的正整数,否则抛错「warehouse_id 无效」;不传或为空时不加仓库过滤)。 + * @param {string} [data.keyword] 关键词,模糊匹配 group_name / group_id。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {number} [data.limit=20] 返回条数上限,最大 100。 + * @return {Promise<{list: Array<{id: number, group_id: (string|null), group_name: string, group_type: (string|null), sub_type: (string|null), is_blocked: number, template_reply_enabled: number}>}>} 群快速列表。 + */ + async quickList(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const keyword = String(data.keyword || '').trim(); + const groupType = String(data.groupType || '').trim(); + const limit = Math.min(100, Math.max(1, Number(data.limit) || 20)); + + const where = {}; + + // store_id(货主维度,对应 wms_inbox_group.store_id 列)可选: + // 传入时校验为可解析的正整数,设置 where.store_id;不传或为空串时不加货主过滤 + const storeIdRaw = String(data.storeId ?? '').trim(); + if (storeIdRaw) { + const storeId = Number(storeIdRaw); + if (!Number.isInteger(storeId) || storeId <= 0) throw new Error('store_id 无效'); + where.store_id = storeId; + } + + // warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)可选: + // 传入时校验为可解析的正整数,设置 where.warehouse_id;不传或为空串时不加仓库过滤 + const warehouseIdRaw = String(data.warehouseId ?? '').trim(); + if (warehouseIdRaw) { + const warehouseId = Number(warehouseIdRaw); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) throw new Error('warehouse_id 无效'); + where.warehouse_id = warehouseId; + } + + if (groupType) where.group_type = groupType; + if (keyword) { + where[Op.or] = [ + { group_name: { [Op.like]: `%${keyword}%` } }, + { group_id: { [Op.like]: `%${keyword}%` } }, + ]; + } + + const rows = await InboxGroup.findAll({ + attributes: [ 'id', 'group_id', 'group_name', 'group_type', 'sub_type', 'is_blocked', 'template_reply_enabled' ], + where, + order: [[ 'created_at', 'DESC' ]], + limit, + raw: true, + }); + + return { list: rows }; + } + + /** + * 查询一个或多个群的成员列表(下拉选择用,多群聚合)。 + * 先用内部主键数组 + 仓库批量校验群存在(软删自动排除,attributes 只取 id/group_id, + * 找不到任何匹配群抛「群不存在或无权限操作」),再收集所有群的外部群ID(去重、剔除空值), + * 按外部群ID集合在消息表中聚合去重成员:取每个 user_id 最新一条消息的 user_name + * (消息按 id 倒序,首次出现的即最新),关键词在聚合后对 user_name / user_id 做包含匹配, + * 最后截断到 limit 条。外部群ID集合为空时直接返回空列表。 + * 局限说明:多群共享同一聚合池,最多取最近 500 条消息,更早消息中的成员不会出现在结果中; + * user_id 为 NULL / 空串的消息被排除;关键词匹配大小写不敏感。 + * + * @param {Object} data 请求数据。 + * @param {Array} data.groupIds wms_inbox_group 内部主键ID数组(必填,非空且每个元素为正整数)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {string} [data.keyword] 关键词,模糊匹配 user_name / user_id。 + * @param {number} [data.limit=20] 返回条数上限,最大 100。 + * @return {Promise<{list: Array<{user_id: string, user_name: string}>}>} 群成员列表。 + */ + async members(data = {}) { + const { ctx } = this; + const { InboxGroup, InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(data.warehouseId); + if (!warehouseId) throw new Error('warehouseId 无效'); + + // groupIds 校验:非空数组且每个元素为数字或可解析数字字符串的正整数 + const rawGroupIds = data.groupIds; + if (!Array.isArray(rawGroupIds) || rawGroupIds.length === 0) { + throw new Error('groupIds 无效'); + } + const groupIds = rawGroupIds.map(item => { + if (typeof item !== 'number' && typeof item !== 'string') return NaN; + return Number(item); + }); + if (groupIds.some(id => !Number.isInteger(id) || id <= 0)) { + throw new Error('groupIds 无效'); + } + + // 批量校验群存在(软删自动排除),attributes 只取 id / group_id + const groups = await InboxGroup.findAll({ + attributes: [ 'id', 'group_id' ], + where: { id: { [Op.in]: groupIds }, warehouse_id: warehouseId }, + raw: true, + }); + if (!groups || groups.length === 0) { + throw new Error('群不存在或无权限操作'); + } + + // 收集所有群的外部群ID(去重、剔除空值),全部为空则没有可关联的消息成员 + const externalGroupIds = [ ...new Set( + groups.map(g => String(g.group_id || '').trim()).filter(Boolean) + ) ]; + if (externalGroupIds.length === 0) { + return { list: [] }; + } + + const keyword = String(data.keyword || '').trim(); + const limit = Math.min(100, Math.max(1, Number(data.limit) || 20)); + + // 拉取多群最近消息集合(软删除由 paranoid 自动排除),共享同一聚合池。 + // 局限说明:聚合池最多取最近 500 条消息,更早消息中的成员不会出现在结果中。 + // user_id 同时排除 NULL 与空串(用字段级 Op.and 避免同名键覆盖), + // 防止脏数据进入聚合池并输出 "null"/"" 成员。 + const messages = await InboxMessage.findAll({ + attributes: [ 'id', 'user_id', 'user_name' ], + where: { + warehouse_id: warehouseId, + group_id: { [Op.in]: externalGroupIds }, + user_id: { + [Op.and]: [ + { [Op.ne]: null }, + { [Op.ne]: '' }, + ], + }, + }, + order: [[ 'id', 'DESC' ]], + limit: 500, + raw: true, + }); + + // 按 user_id 去重:消息已按 id 倒序,首次出现即该用户最新消息。 + // JS 层兜底:跳过 null/undefined user_id,防止 String(null) 变成 "null" 输出。 + const memberMap = new Map(); + for (const msg of messages) { + if (msg.user_id === null || msg.user_id === undefined) continue; + const userId = String(msg.user_id).trim(); + if (!userId || memberMap.has(userId)) continue; + memberMap.set(userId, String(msg.user_name || '').trim()); + } + + let list = Array.from(memberMap.entries()) + .map(([ user_id, user_name ]) => ({ user_id, user_name })); + + // 关键词在聚合结果上过滤 user_name / user_id: + // 统一转小写后做包含匹配,与 quickList 的 SQL LIKE(MySQL 默认大小写不敏感)语义一致 + if (keyword) { + const lowerKeyword = keyword.toLowerCase(); + list = list.filter(item => { + const userName = String(item.user_name || '').toLowerCase(); + const userId = String(item.user_id || '').toLowerCase(); + return userName.includes(lowerKeyword) || userId.includes(lowerKeyword); + }); + } + + return { list: list.slice(0, limit) }; + } + + /** + * 禁用 / 解禁群。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {number} data.isBlocked 是否屏蔽 1=禁用 0=启用。 + * @return {Promise} + */ + async disable(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + + const id = Number(data.id); + const warehouseId = Number(data.warehouseId); + const isBlocked = data.isBlocked === 1 ? 1 : 0; + + if (!id) throw new Error('群ID无效'); + if (!warehouseId) throw new Error('warehouseId 无效'); + + const [ affected ] = await InboxGroup.update( + { is_blocked: isBlocked }, + { where: { id, warehouse_id: warehouseId } } + ); + + if (!affected) { + throw new Error('群不存在或无权限操作'); + } + + ctx.logger.info( + `[inbox group] ${isBlocked ? '禁用' : '启用'}群 id=${id} warehouse_id=${warehouseId}` + ); + } + + /** + * 修改群信息。 + * 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。 + * 群类型切为 express 时 system_express_code 必填, + * express_interfaces 仅在群类型为 express 时生效(非 express 类型忽略)。 + * ai_enabled 控制是否 AI 处理,template_reply_enabled 控制命中处理后 + * 是否以模板消息形式回复(0=普通文本回复,1=模板消息回复),两者独立。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {string} [data.groupType] 群类型:store / warehouse / express。 + * @param {string} [data.subType] 群子类型。 + * @param {number} [data.storeId] 关联货主ID。 + * @param {number[]} [data.expressInterfaces] 快递接口ID数组。 + * @param {string} [data.systemExpressCode] 系统快递编码。 + * @param {number} [data.aiEnabled] 是否启用AI自动回复: 0=关闭 1=开启。 + * @param {number} [data.templateReplyEnabled] 是否启用模板消息回复: 0=关闭(普通文本回复) 1=开启(模板消息回复)。 + * @return {Promise} + */ + async update(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + + const id = Number(data.id); + const warehouseId = Number(data.warehouseId); + + if (!id) throw new Error('群ID无效'); + if (!warehouseId) throw new Error('warehouseId 无效'); + + // 查群是否存在 + const group = await InboxGroup.findOne({ + attributes: [ 'id', 'group_type', 'group_id', 'warehouse_id' ], + where: { id, warehouse_id: warehouseId }, + raw: true, + }); + if (!group) throw new Error('群不存在或无权限操作'); + + // 目标群类型(优先新值,否则保留原值) + const targetGroupType = data.groupType !== undefined + ? String(data.groupType).trim() + : group.group_type || ''; + + // 两层类型校验:subType 必须在对应 groupType 的合法子类型列表中 + if (data.subType !== undefined && targetGroupType) { + const gtDef = INBOX_GROUP_TYPES.find(gt => gt.type === targetGroupType); + if (!gtDef) { + throw new Error(`无效的群类型: ${targetGroupType}`); + } + const subType = String(data.subType || '').trim(); + if (subType) { + const validKeys = gtDef.subTypes.map(st => st.key); + if (!validKeys.includes(subType)) { + throw new Error( + `子类型 "${subType}" 不在群类型 "${targetGroupType}" 的合法范围内,` + + `可用值: ${validKeys.join(', ')}` + ); + } + } + } + + const isExpress = targetGroupType === 'express'; + + // express_interfaces 处理 + let expressInterfaces = null; + if (data.expressInterfaces !== undefined) { + if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length > 0) { + // 校验快递接口ID有效性 + await this.validateExpressInterfaces(data.expressInterfaces); + expressInterfaces = data.expressInterfaces.join(','); + } else if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length === 0) { + // 空数组 = 清空 = 表示全部快递类型 + expressInterfaces = ''; + } else { + expressInterfaces = null; // 未传入 = 不修改 + } + } + + // system_express_code 校验 + let systemExpressCode; + if (data.systemExpressCode !== undefined) { + const code = String(data.systemExpressCode).trim(); + if (code) { + await this.validateSystemExpressCode(code); + systemExpressCode = code; + } else { + systemExpressCode = null; + } + } + + // 切换为 express 类型时 system_express_code 不能为空 + if (isExpress && data.groupType !== undefined) { + const finalCode = systemExpressCode !== undefined ? systemExpressCode : group.system_express_code; + if (!finalCode) { + throw new Error('群类型为快递群时,系统快递编码不能为空'); + } + } + + // 构建更新字段 + const updateData = {}; + if (data.groupType !== undefined) updateData.group_type = targetGroupType || null; + if (data.subType !== undefined) updateData.sub_type = String(data.subType || '').trim() || null; + if (data.storeId !== undefined) { + updateData.store_id = Number.isFinite(Number(data.storeId)) && Number(data.storeId) > 0 + ? Number(data.storeId) : null; + } else if (data.groupType !== undefined && targetGroupType !== 'store') { + // 群类型切为非货主群(warehouse/express)且未显式传 storeId 时, + // 清空遗留的货主绑定,避免仓库群/快递群仍残留 store_id + updateData.store_id = null; + } + // 快递专属字段处理 + if (isExpress) { + if (expressInterfaces !== null) { + updateData.express_interfaces = expressInterfaces || null; + } + if (systemExpressCode !== undefined) { + updateData.system_express_code = systemExpressCode || null; + } + } else if (data.groupType !== undefined) { + // 群类型切为非快递群(store/warehouse)时清空快递专属配置, + // 避免货主群/仓库群残留 express_interfaces / system_express_code + updateData.express_interfaces = null; + updateData.system_express_code = null; + } + // AI 开关(所有群类型均支持) + if (data.aiEnabled !== undefined) { + updateData.ai_enabled = data.aiEnabled === 1 ? 1 : 0; + } + // 模板消息回复开关(所有群类型均支持,独立于 AI 开关) + if (data.templateReplyEnabled !== undefined) { + updateData.template_reply_enabled = data.templateReplyEnabled === 1 ? 1 : 0; + } + + if (Object.keys(updateData).length === 0) { + throw new Error('未提供任何需要修改的字段'); + } + + await InboxGroup.update(updateData, { where: { id, warehouse_id: warehouseId } }); + ctx.logger.info( + `[inbox group] 修改群 id=${id} fields=${Object.keys(updateData).join(',')}` + ); + } + + /** + * 清空群类型配置。 + * 将群恢复为"仅保留创建信息"状态:清空 group_type / sub_type / store_id / + * express_interfaces / system_express_code,AI 开关与模板消息回复开关重置为关闭。 + * 保留群名称、群ID、仓库、来源信息、屏蔽状态与扩展数据。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @return {Promise<{id: number, group_name: string, group_id: string|null}>} 被重置的群信息。 + */ + async reset(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + + const id = Number(data.id); + const warehouseId = Number(data.warehouseId); + + if (!warehouseId) throw new Error('warehouseId 无效'); + if (!id) throw new Error('群ID无效'); + + const where = { id, warehouse_id: warehouseId }; + + const group = await InboxGroup.findOne({ + attributes: [ 'id', 'group_name', 'group_id' ], + where, + raw: true, + }); + if (!group) throw new Error('群不存在或无权限操作'); + + await InboxGroup.update( + { + group_type: null, + sub_type: null, + store_id: null, + express_interfaces: null, + system_express_code: null, + ai_enabled: 0, + template_reply_enabled: 0, + }, + { where } + ); + + ctx.logger.info( + `[inbox group] 清空群类型配置 id=${group.id} group_id=${group.group_id} warehouse_id=${warehouseId}` + ); + + return { id: group.id, group_name: group.group_name, group_id: group.group_id }; + } + + /** + * 校验快递接口ID数组的有效性。 + * 所有ID必须在 wms_express_interface 表中存在。 + * + * @param {number[]} ids 快递接口ID数组。 + * @return {Promise} 无效时抛出异常。 + */ + async validateExpressInterfaces(ids) { + const { ctx } = this; + if (!Array.isArray(ids) || ids.length === 0) return; + + const numericIds = ids.map(Number).filter(id => Number.isFinite(id) && id > 0); + if (numericIds.length !== ids.length) { + throw new Error('快递接口ID包含无效值'); + } + + const count = await ctx.model.ExpressInterface.count({ + where: { id: { [ctx.app.Sequelize.Op.in]: numericIds } }, + }); + + if (count !== numericIds.length) { + throw new Error('部分快递接口ID不存在'); + } + } + + /** + * 校验系统快递编码有效性。 + * 必须在 wms_express 表中存在对应的 code。 + * + * @param {string} code 系统快递编码。 + * @return {Promise} 无效时抛出异常。 + */ + async validateSystemExpressCode(code) { + const { ctx } = this; + const trimmed = String(code).trim(); + if (!trimmed) throw new Error('系统快递编码不能为空'); + + const exists = await ctx.model.Express.count({ + where: { code: trimmed }, + }); + + if (!exists) { + throw new Error(`系统快递编码 "${trimmed}" 不存在`); + } + } + + /** + * 根据快递接口ID和快递编码,查询绑定的售后群和揽收群。 + * + * 匹配规则: + * 1. group_type = 'express' + * 2. system_express_code 精确匹配 expressCode + * 3. express_interfaces 为空(未设置)→ 视为匹配所有该快递的接口 + * 4. express_interfaces 不为空 → 必须包含传入的 expressInterfaceId + * + * @param {Object} params 查询参数。 + * @param {number} params.expressInterfaceId 快递接口ID(wms_express_interface.id)。 + * @param {string} params.expressCode 快递编码(wms_express.code)。 + * @param {number} [params.warehouseId] 仓库ID,不传则查所有仓库。 + * @return {Promise<{afterSalesGroups: Array, pickupGroups: Array}>} 售后群和揽收群列表。 + */ + async findGroupsByExpress({ expressInterfaceId, expressCode, warehouseId }) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const eid = Number(expressInterfaceId); + const code = String(expressCode || '').trim(); + if (!eid || !code) { + throw new Error('expressInterfaceId 和 expressCode 不能为空'); + } + + const where = { + group_type: 'express', + system_express_code: code, + is_blocked: 0, + [Op.or]: [ + { express_interfaces: { [Op.or]: [ null, '' ] } }, + { express_interfaces: { [Op.like]: `%${eid}%` } }, + ], + }; + + if (warehouseId) { + where.warehouse_id = Number(warehouseId); + } + + const rows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'id', 'group_name', 'group_id', 'sub_type', 'express_interfaces', 'warehouse_id', 'ext_data' ], + where, + raw: true, + }); + + const afterSalesGroups = rows.filter(r => r.sub_type === 'after_sales'); + const pickupGroups = rows.filter(r => r.sub_type === 'pickup'); + + ctx.logger.info( + `[inbox group] 查快递绑定群 eid=${eid} code=${code} ` + + `after_sales=${afterSalesGroups.length} pickup=${pickupGroups.length}` + ); + + return { afterSalesGroups, pickupGroups }; + } + + /** + * 根据货主ID列表,查询绑定的货主售后群。 + * + * 匹配规则: + * 1. group_type = 'store' + * 2. sub_type = 'after_sales' + * 3. store_id 在传入列表中 + * + * @param {Object} params 查询参数。 + * @param {number[]} params.storeIds 货主ID列表。 + * @param {number} params.warehouseId 仓库ID。 + * @return {Promise} 货主售后群列表 [{group_id, group_name, store_id, ext_data}]。 + */ + async findStoreAfterSalesGroups({ storeIds, warehouseId }) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const ids = (Array.isArray(storeIds) ? storeIds : [ storeIds ]) + .map(id => Number(id)) + .filter(id => Number.isFinite(id) && id > 0); + + if (ids.length === 0) { + return []; + } + + const rows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'id', 'group_name', 'group_id', 'store_id', 'ext_data' ], + where: { + warehouse_id: Number(warehouseId), + group_type: 'store', + sub_type: 'after_sales', + store_id: { [Op.in]: ids }, + is_blocked: 0, + }, + raw: true, + }); + + ctx.logger.info( + `[inbox group] 查货主售后群 warehouse=${warehouseId} ` + + `stores=[${ids.join(',')}] found=${rows.length}` + ); + + return rows; + } + + /** + * 按货主ID列表查询指定子类型的货主群(如收货群 receiving / 售后群 after_sales)。 + * + * 匹配规则: + * 1. group_type = 'store' + * 2. sub_type 在传入子类型列表中 + * 3. store_id 在传入列表中 + * 4. is_blocked = 0 + * + * @param {Object} params 查询参数。 + * @param {number[]} params.storeIds 货主ID列表。 + * @param {number} params.warehouseId 仓库ID。 + * @param {string[]} params.subTypes 货主群子类型列表(如 [ 'receiving' ])。 + * @return {Promise} 货主群列表 [{group_id, group_name, store_id, sub_type, ext_data}]。 + */ + async findStoreGroups({ storeIds, warehouseId, subTypes }) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const ids = (Array.isArray(storeIds) ? storeIds : [ storeIds ]) + .map(id => Number(id)) + .filter(id => Number.isFinite(id) && id > 0); + const subs = (Array.isArray(subTypes) ? subTypes : [ subTypes ]) + .map(s => String(s || '').trim()) + .filter(Boolean); + + if (ids.length === 0 || subs.length === 0) { + return []; + } + + const rows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'id', 'group_name', 'group_id', 'store_id', 'sub_type', 'ext_data' ], + where: { + warehouse_id: Number(warehouseId), + group_type: 'store', + sub_type: { [Op.in]: subs }, + store_id: { [Op.in]: ids }, + is_blocked: 0, + }, + raw: true, + }); + + ctx.logger.info( + `[inbox group] 查货主群 warehouse=${warehouseId} ` + + `stores=[${ids.join(',')}] subTypes=[${subs.join(',')}] found=${rows.length}` + ); + + return rows; + } +} + +module.exports = InboxGroupService; diff --git a/app/service/systems/inbox/v2.js b/app/service/systems/inbox/v2.js new file mode 100644 index 0000000..c840ff2 --- /dev/null +++ b/app/service/systems/inbox/v2.js @@ -0,0 +1,798 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * v2 可配置回信引擎 —— 配置管理系统服务层。 + * + * 规则: + * - warehouseId 一律从登录上下文 ctx.user.store_id 注入(仓库隔离); + * - 系统预设锁定:is_system=1 的主数据只读;系统级子类型(warehouse_id=NULL) + * 的关联行只读(群白名单另尊重关联行 is_system 列); + * - 关键词属仓库级数据(warehouse_id=当前仓库),可挂在系统级子类型下 + * (keyword.create/update/delete 不做子类型「仓库自定义」限制); + * - 自定义子类型可挂在系统级或本仓库自定义类型下(subType.create 父类型只校验存在性); + * - 删除子类型前校验引用(关键词/函数/规则/群/回复),有引用拒绝删除; + * - 函数表由代码同步权威:只允许改 is_enabled / sort_order,不允许增删改 code; + * - 取号规则为全局资源,仓库侧只读; + * - 所有写操作完成后失效该仓库 v2 配置缓存(inbox:v2:cfg:{warehouseId})。 + */ +class InboxV2ConfigManageService extends Service { + /** 当前仓库ID(从登录上下文注入)。 */ + get wid() { + return Number(this.ctx.user?.store_id || 0); + } + + /** 写操作后失效缓存。 */ + async _invalidate() { + try { + await this.ctx.service.inbox.v2.config.invalidate(this.wid); + } catch (e) { + this.ctx.logger.warn(`[inbox v2 manage] 失效缓存失败: ${e.message}`); + } + } + + _op() { + return this.ctx.app.Sequelize.Op; + } + + /** + * 校验子类型是否属于当前仓库可写范围(仓库自定义,warehouse_id=当前仓库)。 + * @param {number} subTypeId 子类型ID。 + * @param {string} [label] 错误提示中的实体名称。 + * @return {Promise} 子类型记录(raw)。 + */ + async _assertWritableSubType(subTypeId, label = '子类型') { + const row = await this.ctx.model.AfterSaleSubType.findOne({ + where: { id: Number(subTypeId) || 0, warehouse_id: this.wid }, + attributes: [ 'id', 'warehouse_id', 'is_system' ], + raw: true, + }); + if (!row) { + throw new Error(`${label}不存在或不是本仓库自定义(系统级只读)`); + } + return row; + } + + /** + * 取子类型(含系统级+仓库级,用于只读查询)。 + * @param {number} subTypeId 子类型ID。 + * @return {Promise} 子类型记录(raw),不存在返回 null。 + */ + async _findSubType(subTypeId) { + const Op = this._op(); + return this.ctx.model.AfterSaleSubType.findOne({ + where: { id: Number(subTypeId) || 0, [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] }, + attributes: [ 'id', 'warehouse_id', 'is_system', 'sub_type', 'type' ], + raw: true, + }); + } + + /** + * 通用分页参数。 + * @param {Object} [params] 请求参数(含 page/pageSize)。 + * @return {{page: number, pageSize: number}} 归一化分页参数。 + */ + _page(params = {}) { + const page = Math.max(1, Number(params.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20)); + return { page, pageSize }; + } + + // ─────────────────────────── 类型 ─────────────────────────── + + get type() { + const svc = this; + return { + list: params => svc._typeList(params), + create: params => svc._typeCreate(params), + update: params => svc._typeUpdate(params), + delete: params => svc._typeDelete(params), + }; + } + + async _typeList(params = {}) { + const Op = this._op(); + const { page, pageSize } = this._page(params); + const where = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] }; + if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') { + where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0; + } + const { rows, count } = await this.ctx.model.AfterSaleType.findAndCountAll({ + where, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], + offset: (page - 1) * pageSize, limit: pageSize, raw: true, + }); + return { list: rows, pagination: { page, pageSize, total: count } }; + } + + async _typeCreate(params = {}) { + const { AfterSaleType } = this.ctx.model; + const type = String(params.type || '').trim(); + const name = String(params.name || '').trim(); + if (!type || !name) throw new Error('type 与 name 不能为空'); + if (type.length > 20 || name.length > 50) throw new Error('type(≤20)/name(≤50) 超长'); + const exist = await AfterSaleType.findOne({ + where: { type, warehouse_id: this.wid }, raw: true, + }); + if (exist) throw new Error(`类型编码 ${type} 已存在`); + const row = await AfterSaleType.create({ + warehouse_id: this.wid, type, name, is_system: 0, is_enabled: 1, + sort_order: Number(params.sortOrder) || 0, + }); + await this._invalidate(); + return { id: row.id, message: '创建成功' }; + } + + async _typeUpdate(params = {}) { + const { AfterSaleType } = this.ctx.model; + const row = await AfterSaleType.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true }); + if (!row) throw new Error('类型不存在或不是本仓库自定义(系统级只读)'); + if (row.is_system === 1) throw new Error('系统预设类型不可修改'); + const patch = {}; + if (params.name !== undefined) { + const name = String(params.name || '').trim(); + if (!name) throw new Error('name 不能为空'); + patch.name = name.slice(0, 50); + } + if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') patch.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0; + if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0; + if (Object.keys(patch).length === 0) throw new Error('无可更新字段'); + await AfterSaleType.update(patch, { where: { id: row.id } }); + await this._invalidate(); + return { message: '更新成功' }; + } + + async _typeDelete(params = {}) { + const { AfterSaleType, AfterSaleSubType } = this.ctx.model; + const row = await AfterSaleType.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true }); + if (!row) throw new Error('类型不存在或不是本仓库自定义(系统级只读)'); + if (row.is_system === 1) throw new Error('系统预设类型不可删除'); + const subCount = await AfterSaleSubType.count({ where: { type: row.type, warehouse_id: this.wid } }); + if (subCount > 0) throw new Error(`该类型下还有 ${subCount} 个子类型,请先删除子类型`); + await AfterSaleType.destroy({ where: { id: row.id } }); + await this._invalidate(); + return { message: '删除成功' }; + } + + // ─────────────────────────── 子类型 ─────────────────────────── + + get subType() { + const svc = this; + return { + list: params => svc._subTypeList(params), + create: params => svc._subTypeCreate(params), + update: params => svc._subTypeUpdate(params), + delete: params => svc._subTypeDelete(params), + }; + } + + async _subTypeList(params = {}) { + const Op = this._op(); + const { page, pageSize } = this._page(params); + const where = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] }; + if (params.type) where.type = String(params.type).trim(); + if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') { + where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0; + } + const { rows, count } = await this.ctx.model.AfterSaleSubType.findAndCountAll({ + where, order: [[ 'type', 'ASC' ], [ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], + offset: (page - 1) * pageSize, limit: pageSize, raw: true, + }); + return { list: rows, pagination: { page, pageSize, total: count } }; + } + + async _subTypeCreate(params = {}) { + const { AfterSaleSubType } = this.ctx.model; + const type = String(params.type || '').trim(); + const subType = String(params.subType || '').trim(); + const name = String(params.name || '').trim(); + if (!type || !subType || !name) throw new Error('type/subType/name 不能为空'); + if (subType.length > 50 || name.length > 50) throw new Error('subType/name 超长(≤50)'); + // 自定义子类型可挂在系统级类型或本仓库自定义类型下:父类型只需存在且可见即可; + // 子类型自身始终写 warehouse_id=当前仓库 + is_system=0,因此后续配置全部可写。 + const Op = this._op(); + const parent = await this.ctx.model.AfterSaleType.findOne({ + where: { type, [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] }, + raw: true, + }); + if (!parent) throw new Error(`类型 ${type} 不存在`); + const exist = await AfterSaleSubType.findOne({ where: { type, sub_type: subType, warehouse_id: this.wid }, raw: true }); + if (exist) throw new Error(`子类型 ${type}:${subType} 已存在`); + const row = await AfterSaleSubType.create({ + warehouse_id: this.wid, type, sub_type: subType, name, is_system: 0, is_enabled: 1, + sort_order: Number(params.sortOrder) || 0, + }); + await this._invalidate(); + return { id: row.id, message: '创建成功' }; + } + + async _subTypeUpdate(params = {}) { + const row = await this._assertWritableSubType(params.id, '子类型'); + const patch = {}; + if (params.name !== undefined) { + const name = String(params.name || '').trim(); + if (!name) throw new Error('name 不能为空'); + patch.name = name.slice(0, 50); + } + if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') patch.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0; + if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0; + if (Object.keys(patch).length === 0) throw new Error('无可更新字段'); + await this.ctx.model.AfterSaleSubType.update(patch, { where: { id: row.id } }); + await this._invalidate(); + return { message: '更新成功' }; + } + + async _subTypeDelete(params = {}) { + const { ctx } = this; + const row = await this._assertWritableSubType(params.id, '子类型'); + // 级联清理关联(关键词/函数关联/取号关联/群白名单/回复),避免逐个手动清理 + const t = await this.ctx.model.transaction(); + const counts = {}; + try { + counts.keyword = await ctx.model.AfterSaleKeyword.destroy({ where: { sub_type_id: row.id }, transaction: t }); + counts.function = await ctx.model.AfterSaleSubTypeFunction.destroy({ where: { sub_type_id: row.id }, transaction: t }); + counts.rule = await ctx.model.AfterSaleSubTypeRule.destroy({ where: { sub_type_id: row.id }, transaction: t }); + counts.group = await ctx.model.AfterSaleSubTypeGroup.destroy({ where: { sub_type_id: row.id }, transaction: t }); + counts.reply = await ctx.model.AfterSaleReply.destroy({ where: { sub_type_id: row.id }, transaction: t }); + await ctx.model.AfterSaleSubType.destroy({ where: { id: row.id }, transaction: t }); + await t.commit(); + } catch (e) { + await t.rollback(); + throw e; + } + await this._invalidate(); + return { + message: `删除成功(已级联清理:关键词 ${counts.keyword}、函数关联 ${counts.function}、取号关联 ${counts.rule}、群白名单 ${counts.group}、回复 ${counts.reply})`, + }; + } + + // ─────────────────────────── 关键词 ─────────────────────────── + + get keyword() { + const svc = this; + return { + list: params => svc._keywordList(params), + create: params => svc._keywordCreate(params), + update: params => svc._keywordUpdate(params), + delete: params => svc._keywordDelete(params), + }; + } + + async _keywordList(params = {}) { + const Op = this._op(); + const { page, pageSize } = this._page(params); + const where = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] }; + if (params.subTypeId) where.sub_type_id = Number(params.subTypeId) || 0; + if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') { + where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0; + } + const { rows, count } = await this.ctx.model.AfterSaleKeyword.findAndCountAll({ + where, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], + offset: (page - 1) * pageSize, limit: pageSize, raw: true, + }); + return { list: rows, pagination: { page, pageSize, total: count } }; + } + + /** + * 同词查重(可见范围:系统级 + 本仓库)。 + * @param {string} keyword 关键词。 + * @param {number} [excludeId] 排除自身ID(更新场景)。 + * @return {Promise} 重复时的提示文案(含所在级别与子类型),无重复返回 null。 + */ + async _keywordDupDescribe(keyword, excludeId) { + const Op = this._op(); + const rows = await this.ctx.model.AfterSaleKeyword.findAll({ + where: { + keyword, + [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }], + }, + attributes: [ 'id', 'sub_type_id', 'warehouse_id' ], + raw: true, + }); + const dup = rows.find(r => Number(r.id) !== Number(excludeId || 0)); + if (!dup) return null; + const sub = await this.ctx.model.AfterSaleSubType.findOne({ + where: { id: dup.sub_type_id }, + attributes: [ 'type', 'sub_type', 'name' ], + raw: true, + }); + const level = dup.warehouse_id === null ? '系统级' : '本仓库'; + const rule = sub ? `${sub.type}:${sub.sub_type}(${sub.name})` : `子类型ID ${dup.sub_type_id}`; + return `关键词「${keyword}」已存在于【${level}】${rule}下,不可重复添加`; + } + + async _keywordCreate(params = {}) { + const { AfterSaleKeyword } = this.ctx.model; + const subTypeId = Number(params.subTypeId) || 0; + const keyword = String(params.keyword || '').trim(); + if (!subTypeId || !keyword) throw new Error('subTypeId 与 keyword 不能为空'); + if (keyword.length > 100) throw new Error('关键词超长(≤100)'); + // 关键词为仓库级数据(warehouse_id=当前仓库):允许绑定系统级子类型或本仓库自定义子类型, + // 只校验子类型存在,不做「仓库自定义」限制(与 keyword.update / keyword.delete 的可写范围对齐)。 + const subType = await this._findSubType(subTypeId); + if (!subType) throw new Error('子类型不存在'); + // 同词查重(系统级+本仓库),重复时提示在哪个规则(子类型)下 + const dupMsg = await this._keywordDupDescribe(keyword); + if (dupMsg) throw new Error(dupMsg); + const row = await AfterSaleKeyword.create({ + warehouse_id: this.wid, sub_type_id: subTypeId, keyword, is_system: 0, is_enabled: 1, + sort_order: Number(params.sortOrder) || 0, + }); + await this._invalidate(); + return { id: row.id, message: '创建成功' }; + } + + async _keywordUpdate(params = {}) { + const { AfterSaleKeyword } = this.ctx.model; + const row = await AfterSaleKeyword.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true }); + if (!row) throw new Error('关键词不存在或不是本仓库自定义(系统级只读)'); + if (row.is_system === 1) throw new Error('系统预设关键词不可修改'); + const patch = {}; + if (params.keyword !== undefined) { + const keyword = String(params.keyword || '').trim(); + if (!keyword) throw new Error('keyword 不能为空'); + const sliced = keyword.slice(0, 100); + // 改词同样查重(排除自身),重复时提示在哪个规则(子类型)下 + const dupMsg = await this._keywordDupDescribe(sliced, row.id); + if (dupMsg) throw new Error(dupMsg); + patch.keyword = sliced; + } + if (params.subTypeId) { + await this._assertWritableSubType(params.subTypeId, '子类型'); + patch.sub_type_id = Number(params.subTypeId); + } + if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') patch.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0; + if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0; + if (Object.keys(patch).length === 0) throw new Error('无可更新字段'); + await AfterSaleKeyword.update(patch, { where: { id: row.id } }); + await this._invalidate(); + return { message: '更新成功' }; + } + + async _keywordDelete(params = {}) { + const { AfterSaleKeyword } = this.ctx.model; + const row = await AfterSaleKeyword.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true }); + if (!row) throw new Error('关键词不存在或不是本仓库自定义(系统级只读)'); + if (row.is_system === 1) throw new Error('系统预设关键词不可删除'); + await AfterSaleKeyword.destroy({ where: { id: row.id } }); + await this._invalidate(); + return { message: '删除成功' }; + } + + // ─────────────────────────── 取号规则(全局只读) ─────────────────────────── + + get numberRule() { + const svc = this; + return { list: params => svc._numberRuleList(params) }; + } + + async _numberRuleList() { + const rows = await this.ctx.model.InboxNumberRule.findAll({ + order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true, + }); + return { list: rows }; + } + + // ─────────────────────────── 处理函数(代码同步权威,只允许开关/排序) ─────────────────────────── + + get function() { + const svc = this; + return { + list: params => svc._functionList(params), + update: params => svc._functionUpdate(params), + }; + } + + async _functionList(params = {}) { + const Op = this._op(); + const where = {}; + if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') { + where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0; + } + if (params.keyword) { + const like = `%${String(params.keyword).trim()}%`; + where[Op.or] = [{ function_code: { [Op.like]: like } }, { name: { [Op.like]: like } }]; + } + const rows = await this.ctx.model.AfterSaleFunction.findAll({ + where, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true, + }); + // 附上代码注册表中是否存在(便于识别已下线函数) + let registry = null; + try { + registry = this.ctx.service.inbox.functions.registry; + } catch (e) { /* ignore */ } + return { + list: rows.map(r => ({ + ...r, + in_registry: registry instanceof Map ? registry.has(r.function_code) : null, + })), + }; + } + + async _functionUpdate(params = {}) { + const { AfterSaleFunction } = this.ctx.model; + const row = await AfterSaleFunction.findOne({ where: { id: Number(params.id) || 0 }, raw: true }); + if (!row) throw new Error('函数不存在'); + const patch = {}; + // 启用状态硬编码(代码注册表存在即启用),接口只允许调整排序 + if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0; + if (Object.keys(patch).length === 0) throw new Error('只允许更新 sortOrder(是否启用由代码硬编码,不做接口配置)'); + await AfterSaleFunction.update(patch, { where: { id: row.id } }); + await this._invalidate(); + return { message: '更新成功' }; + } + + // ─────────────────────────── 回复 ─────────────────────────── + + get reply() { + const svc = this; + return { + create: params => svc._replyCreate(params), + update: params => svc._replyUpdate(params), + delete: params => svc._replyDelete(params), + // 推荐接口:保存(upsert)/ 还原(删除仓库级,回退系统级) + save: params => svc._replySave(params), + restore: params => svc._replyRestore(params), + merged: params => svc._replyMerged(params), + }; + } + + /** + * 保存仓库级回复配置(upsert):按传入字段保存,未传字段保持原值; + * 无仓库级配置时按传入字段创建(默认 reply 空、is_reply=1、create_work_order=1)。 + * 停用即回退系统级语义由 restore 承担,不再提供 isEnabled 开关。 + * @param {Object} params 请求参数。 + * @return {Promise} 保存结果。 + */ + async _replySave(params = {}) { + const { AfterSaleReply } = this.ctx.model; + const subTypeId = Number(params.subTypeId) || 0; + if (!subTypeId) throw new Error('subTypeId 不能为空'); + const subType = await this._findSubType(subTypeId); + if (!subType) throw new Error('子类型不存在'); + + const patch = {}; + if (params.reply !== undefined && params.reply !== null) patch.reply = String(params.reply).slice(0, 2000); + if (params.isReply !== undefined && params.isReply !== null && params.isReply !== '') patch.is_reply = Number(params.isReply) === 0 ? 0 : 1; + if (params.createWorkOrder !== undefined && params.createWorkOrder !== null && params.createWorkOrder !== '') patch.create_work_order = Number(params.createWorkOrder) === 0 ? 0 : 1; + if (params.noNumberHint !== undefined && params.noNumberHint !== null) patch.no_number_hint = params.noNumberHint ? String(params.noNumberHint).slice(0, 500) : null; + + const exist = await AfterSaleReply.findOne({ + where: { warehouse_id: this.wid, sub_type_id: subTypeId }, + raw: true, + }); + if (exist) { + if (Object.keys(patch).length > 0) { + await AfterSaleReply.update(patch, { where: { id: exist.id } }); + } + } else { + await AfterSaleReply.create({ + warehouse_id: this.wid, + sub_type_id: subTypeId, + reply: patch.reply !== undefined ? patch.reply : '', + is_reply: patch.is_reply !== undefined ? patch.is_reply : 1, + create_work_order: patch.create_work_order !== undefined ? patch.create_work_order : 1, + no_number_hint: patch.no_number_hint !== undefined ? patch.no_number_hint : null, + is_enabled: 1, + }); + } + await this._invalidate(); + return { + id: exist ? exist.id : null, + message: exist ? '保存成功' : '创建成功', + }; + } + + /** + * 还原仓库级回复配置:删除仓库级行,回退到系统级配置。 + * @param {Object} params 请求参数。 + * @return {Promise} 还原结果。 + */ + async _replyRestore(params = {}) { + const { AfterSaleReply } = this.ctx.model; + const subTypeId = Number(params.subTypeId) || 0; + if (!subTypeId) throw new Error('subTypeId 不能为空'); + const row = await AfterSaleReply.findOne({ + where: { warehouse_id: this.wid, sub_type_id: subTypeId }, + raw: true, + }); + if (row) { + await AfterSaleReply.destroy({ where: { id: row.id } }); + await this._invalidate(); + return { message: '已还原为系统级配置' }; + } + return { message: '本仓库无自定义回复配置,已是系统级配置' }; + } + + /** + * 回复配置(合并后生效配置):以全部有效子类型(系统级+本仓库)为基底, + * 每个子类型只返回一条「生效配置」:本仓库有自定义则整行覆盖系统级; + * 无任何回复配置行的子类型返回初始值(reply={back_text}、is_reply=1、create_work_order=1、 + * no_number_hint 按取号规则:express_name→快递提示、有其他规则→运单号提示、无规则→空), + * 保证任何仓库都有完整列表。无启用状态字段:停用即回退系统级由 restore 承担。 + * @param {Object} params 请求参数。 + * @return {Promise} { merged, total } 合并后生效配置数组与总数。 + */ + async _replyMerged(params = {}) { + const Op = this._op(); + const wh = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] }; + // 拉全量(系统级+本仓库级)在内存合并,数据量小 + const [ rows, subs, ruleRelRows, ruleRows ] = await Promise.all([ + this.ctx.model.AfterSaleReply.findAll({ + where: wh, + order: [[ 'sub_type_id', 'ASC' ], [ 'warehouse_id', 'ASC' ]], + raw: true, + }), + this.ctx.model.AfterSaleSubType.findAll({ + where: wh, + attributes: [ 'id', 'type', 'sub_type', 'name', 'warehouse_id' ], + raw: true, + }), + this.ctx.model.AfterSaleSubTypeRule.findAll({ + attributes: [ 'sub_type_id', 'number_rule_id' ], + raw: true, + }), + this.ctx.model.InboxNumberRule.findAll({ + attributes: [ 'id', 'target' ], + raw: true, + }), + ]); + const ruleTargets = {}; + for (const n of ruleRows) ruleTargets[n.id] = n.target; + const subTargets = {}; + for (const rel of ruleRelRows) { + const t = ruleTargets[rel.number_rule_id]; + if (!t) continue; + if (!subTargets[rel.sub_type_id]) subTargets[rel.sub_type_id] = []; + if (!subTargets[rel.sub_type_id].includes(t)) subTargets[rel.sub_type_id].push(t); + } + const initialHint = st => { + const ts = subTargets[st.id] || []; + if (ts.includes('express_name')) { + return '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)'; + } + return ts.length > 0 ? '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)' : ''; + }; + const mergedMap = new Map(); + for (const r of rows) { + const isWh = r.warehouse_id !== null && r.warehouse_id !== undefined; + const existing = mergedMap.get(r.sub_type_id); + if (!existing || (isWh && !existing._wh)) { + mergedMap.set(r.sub_type_id, { ...r, _wh: isWh }); + } + } + const subMap = {}; + for (const s of subs) subMap[s.id] = s; + const toRow = (st, r) => ({ + id: r ? r.id : null, + sub_type_id: st.id, + type: String(st.type || ''), + sub_type: String(st.sub_type || ''), + sub_type_name: String(st.name || ''), + warehouse_id: r ? (r._wh ? r.warehouse_id : null) : (st.warehouse_id === null || st.warehouse_id === undefined ? null : this.wid), + is_custom: r ? (r._wh ? 1 : 0) : (st.warehouse_id === null || st.warehouse_id === undefined ? 0 : 1), + reply: r ? String(r.reply || '') : '{back_text}', + is_reply: r ? (Number(r.is_reply) === 1 ? 1 : 0) : 1, + create_work_order: r ? (Number(r.create_work_order) === 0 ? 0 : 1) : 1, + no_number_hint: r ? (r.no_number_hint ? String(r.no_number_hint) : '') : initialHint(st), + created_at: r ? r.created_at : null, + updated_at: r ? r.updated_at : null, + }); + let list = subs.map(st => { + const r = mergedMap.get(st.id); + return toRow(st, r); + }); + if (params.subTypeId) { + const sid = Number(params.subTypeId) || 0; + list = list.filter(x => x.sub_type_id === sid); + } + const total = list.length; + return { merged: list, total }; + } + + async _replyCreate(params = {}) { + const { AfterSaleReply } = this.ctx.model; + const subTypeId = Number(params.subTypeId) || 0; + const reply = String(params.reply || ''); + if (!subTypeId) throw new Error('subTypeId 不能为空'); + if (!reply) throw new Error('reply 不能为空'); + // 允许系统级子类型:仓库级回复的语义就是覆盖系统级配置(读取时仓库级优先) + const subType = await this._findSubType(subTypeId); + if (!subType) throw new Error('子类型不存在'); + const exist = await AfterSaleReply.findOne({ where: { warehouse_id: this.wid, sub_type_id: subTypeId }, raw: true }); + if (exist) throw new Error('该子类型已有仓库级回复,请用更新'); + const row = await AfterSaleReply.create({ + warehouse_id: this.wid, sub_type_id: subTypeId, reply, + is_reply: Number(params.isReply) === 0 ? 0 : 1, + create_work_order: Number(params.createWorkOrder) === 0 ? 0 : 1, + no_number_hint: params.noNumberHint ? String(params.noNumberHint).slice(0, 500) : null, + is_enabled: 1, + }); + await this._invalidate(); + return { id: row.id, message: '创建成功' }; + } + + async _replyUpdate(params = {}) { + const { AfterSaleReply } = this.ctx.model; + const row = await AfterSaleReply.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true }); + if (!row) throw new Error('回复配置不存在或不是本仓库的(系统级回复只读)'); + const patch = {}; + if (params.reply !== undefined) { + const reply = String(params.reply || ''); + if (!reply) throw new Error('reply 不能为空'); + patch.reply = reply; + } + if (params.isReply !== undefined && params.isReply !== null && params.isReply !== '') patch.is_reply = Number(params.isReply) === 1 ? 1 : 0; + if (params.createWorkOrder !== undefined && params.createWorkOrder !== null && params.createWorkOrder !== '') patch.create_work_order = Number(params.createWorkOrder) === 1 ? 1 : 0; + if (params.noNumberHint !== undefined) { + patch.no_number_hint = params.noNumberHint ? String(params.noNumberHint).slice(0, 500) : null; + } + if (Object.keys(patch).length === 0) throw new Error('无可更新字段'); + await AfterSaleReply.update(patch, { where: { id: row.id } }); + await this._invalidate(); + return { message: '更新成功' }; + } + + async _replyDelete(params = {}) { + const { AfterSaleReply } = this.ctx.model; + const row = await AfterSaleReply.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true }); + if (!row) throw new Error('回复配置不存在或不是本仓库的(系统级回复只读)'); + await AfterSaleReply.destroy({ where: { id: row.id } }); + await this._invalidate(); + return { message: '删除成功' }; + } + + // ─────────────────────────── 关联关系(set=全量替换,仅本仓库自定义子类型可写) ─────────────────────────── + + get relation() { + const svc = this; + return { + function: { + list: params => svc._relFunctionList(params), + set: params => svc._relFunctionSet(params), + }, + rule: { + list: params => svc._relRuleList(params), + set: params => svc._relRuleSet(params), + }, + group: { + list: params => svc._relGroupList(params), + set: params => svc._relGroupSet(params), + }, + }; + } + + async _relFunctionList(params = {}) { + const subType = await this._findSubType(params.subTypeId); + if (!subType) throw new Error('子类型不存在'); + const rows = await this.ctx.model.AfterSaleSubTypeFunction.findAll({ + where: { sub_type_id: subType.id }, + order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true, + }); + return { list: rows }; + } + + async _relFunctionSet(params = {}) { + const subType = await this._assertWritableSubType(params.subTypeId, '子类型'); + const items = Array.isArray(params.items) ? params.items : []; + const funcRows = await this.ctx.model.AfterSaleFunction.findAll({ attributes: [ 'id' ], raw: true }); + const validIds = new Set(funcRows.map(r => r.id)); + const t = await this.ctx.model.transaction(); + try { + await this.ctx.model.AfterSaleSubTypeFunction.destroy({ where: { sub_type_id: subType.id }, transaction: t }); + let order = 0; + for (const item of items) { + const fid = Number(item.functionId) || 0; + if (!validIds.has(fid)) continue; + await this.ctx.model.AfterSaleSubTypeFunction.create({ + sub_type_id: subType.id, function_id: fid, + sort_order: Number(item.sortOrder) || order, + }, { transaction: t }); + order += 1; + } + await t.commit(); + } catch (e) { + await t.rollback(); + throw e; + } + await this._invalidate(); + return { message: '关联已更新' }; + } + + async _relRuleList(params = {}) { + const subType = await this._findSubType(params.subTypeId); + if (!subType) throw new Error('子类型不存在'); + const rows = await this.ctx.model.AfterSaleSubTypeRule.findAll({ + where: { sub_type_id: subType.id }, + order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true, + }); + return { list: rows }; + } + + async _relRuleSet(params = {}) { + const subType = await this._assertWritableSubType(params.subTypeId, '子类型'); + const items = Array.isArray(params.items) ? params.items : []; + const ruleRows = await this.ctx.model.InboxNumberRule.findAll({ attributes: [ 'id' ], raw: true }); + const validIds = new Set(ruleRows.map(r => r.id)); + const t = await this.ctx.model.transaction(); + try { + await this.ctx.model.AfterSaleSubTypeRule.destroy({ where: { sub_type_id: subType.id }, transaction: t }); + let order = 0; + for (const item of items) { + const rid = Number(item.ruleId) || 0; + if (!validIds.has(rid)) continue; + await this.ctx.model.AfterSaleSubTypeRule.create({ + sub_type_id: subType.id, number_rule_id: rid, + sort_order: Number(item.sortOrder) || order, + }, { transaction: t }); + order += 1; + } + await t.commit(); + } catch (e) { + await t.rollback(); + throw e; + } + await this._invalidate(); + return { message: '关联已更新' }; + } + + async _relGroupList(params = {}) { + const subType = await this._findSubType(params.subTypeId); + if (!subType) throw new Error('子类型不存在'); + const rows = await this.ctx.model.AfterSaleSubTypeGroup.findAll({ + where: { sub_type_id: subType.id }, + order: [[ 'group_type', 'ASC' ], [ 'sub_group', 'ASC' ], [ 'id', 'ASC' ]], raw: true, + }); + return { list: rows }; + } + + async _relGroupSet(params = {}) { + const subType = await this._assertWritableSubType(params.subTypeId, '子类型'); + const items = Array.isArray(params.items) ? params.items : []; + const { AfterSaleSubTypeGroup } = this.ctx.model; + const validTypes = [ 'store', 'warehouse', 'express', '*' ]; + const t = await this.ctx.model.transaction(); + try { + // 系统预设行(is_system=1)不可删:保留并合并 + const sysRows = await AfterSaleSubTypeGroup.findAll({ + where: { sub_type_id: subType.id, is_system: 1 }, raw: true, transaction: t, + }); + await AfterSaleSubTypeGroup.destroy({ where: { sub_type_id: subType.id, is_system: 0 }, transaction: t }); + const seen = new Set(); + for (const row of sysRows) { + seen.add(`${row.group_type}:${row.sub_group}`); + } + // 通配覆盖:groupType='*' 覆盖所有具体类型行;主类型内 subGroup='*' 覆盖该主类型其他具体行 + const norm = items + .map(it => ({ + gt: String(it.groupType || '').trim(), + sg: String(it.subGroup || '').trim(), + so: Number(it.sortOrder) || 0, + })) + .filter(x => validTypes.includes(x.gt)); + const hasWildcardAll = norm.some(x => x.gt === '*'); + const wildcardTypes = new Set(norm.filter(x => x.gt !== '*' && x.sg === '*').map(x => x.gt)); + for (const { gt, sg: rawSg, so } of norm) { + let sg = rawSg; + if (gt === '*') sg = ''; // 全通配时子类型无意义,归一化为空 + if (hasWildcardAll && gt !== '*') continue; // 有全部时覆盖掉对应类型 + if (gt !== '*' && wildcardTypes.has(gt) && sg !== '*') continue; // 主类型内通配覆盖具体行 + const key = `${gt}:${sg}`; + if (seen.has(key)) continue; + seen.add(key); + await AfterSaleSubTypeGroup.create({ + sub_type_id: subType.id, group_type: gt, sub_group: sg, + is_system: 0, sort_order: so, + }, { transaction: t }); + } + await t.commit(); + } catch (e) { + await t.rollback(); + throw e; + } + await this._invalidate(); + return { message: '关联已更新' }; + } +} + +module.exports = InboxV2ConfigManageService; diff --git a/app/service/systems/intercept_auto_confirm.js b/app/service/systems/intercept_auto_confirm.js new file mode 100644 index 0000000..9979374 --- /dev/null +++ b/app/service/systems/intercept_auto_confirm.js @@ -0,0 +1,578 @@ +// app/service/systems/intercept_auto_confirm.js +'use strict'; + +const MainService = require('../main'); + +// 允许确认拦截(更新为 intercepted_at_warehouse)的前置拦截状态白名单: +// 拦截发起中(requested/requesting/intercepting)与历史遗留值 intercepted。 +// 其余状态一律不允许确认拦截,防止并发修改导致误更新。 +const CONFIRMABLE_INTERCEPT_STATUSES = Object.freeze([ 'requested', 'requesting', 'intercepting', 'intercepted' ]); + +// 自动确认扫描命中的拦截状态:仅请求拦截(requested) +const AUTO_CONFIRM_INTERCEPT_STATUS = 'requested'; +// 自动确认扫描要求的面单打印状态:未打印 +const AUTO_CONFIRM_PRINT_STATUS = 'none'; +// 拦截时间超时阈值(小时):intercept_time 超过 12 小时自动确认 +const INTERCEPT_TIME_TIMEOUT_HOURS = 12; +// 创建时间超时阈值(小时):create_at 超过 36 小时自动确认 +const CREATE_AT_TIMEOUT_HOURS = 36; +// 拦截时间超时阈值(毫秒),供口径镜像函数使用 +const INTERCEPT_TIME_TIMEOUT_MS = INTERCEPT_TIME_TIMEOUT_HOURS * 60 * 60 * 1000; +// 创建时间超时阈值(毫秒),供口径镜像函数使用 +const CREATE_AT_TIMEOUT_MS = CREATE_AT_TIMEOUT_HOURS * 60 * 60 * 1000; +// 单批扫描数量上限(分页扫描,避免单批过大) +const SCAN_BATCH_SIZE = 100; +// 单批确认数量上限(批量确认,避免单批过大) +const CONFIRM_BATCH_SIZE = 100; +// 仓库当前表分表名匹配模式:wms_order_delivery_{warehouseId}(不含 history/dispatch/outsourced) +const CURRENT_SHARD_TABLE_PATTERN = /^wms_order_delivery_(\d+)$/; +// 定时任务自动确认的操作人(无用户上下文) +const AUTO_CONFIRM_OPERATOR = Object.freeze({ id: null, name: '系统' }); + +/** + * 将任意时间值转换为毫秒时间戳,无法解析时返回 null。 + * + * @param {*} value 时间值(Date / 日期字符串 / 数字)。 + * @return {number|null} 毫秒时间戳或 null。 + */ +function toTimestamp(value) { + if (value === null || value === undefined || value === '') { + return null; + } + + if (value instanceof Date) { + const time = value.getTime(); + return Number.isFinite(time) ? time : null; + } + + if (typeof value === 'number') { + return Number.isFinite(value) ? value : null; + } + + const parsed = Date.parse(String(value)); + return Number.isFinite(parsed) ? parsed : null; +} + +/** + * 自动库内拦截确定服务。 + * + * 背景:订单发起拦截(intercept_status='requested')后若人工迟迟未做「库内拦截确定」, + * 订单会长期停留在拦截发起中。本服务定时扫描待处理表(current 分表),对 + * 「intercept_status='requested' 且 print_status='none'(面单未打印)」的订单, + * 满足以下任一条件时自动执行库内拦截确定: + * - intercept_time 超过 12 小时(NULL 自然不命中,无需特判); + * - create_at 超过 36 小时。 + * + * 本服务同时提供 confirmInterceptForOrderIds 作为库内拦截确定的内部实现, + * systemMethods/order/recheckOrder.js 的 confirmIntercept 出口复用该方法, + * 定时任务同样复用,保证两条链路行为一致。 + */ +class InterceptAutoConfirmService extends MainService { + /** + * 在当前调用内临时注入 ctx.user 上下文,并在结束后恢复。 + * + * 用于复用依赖登录上下文的既有 service 能力(如储位取消分配读取 ctx.user.store_id), + * 避免扩大影响范围。 + * + * @param {Object} patchUser 需要覆盖的用户上下文字段。 + * @param {Function} callback 业务回调。 + * @return {Promise} 回调执行结果。 + */ + async withPatchedCtxUser(patchUser, callback) { + const { ctx } = this; + const originUser = ctx.user; + const safeOriginUser = originUser && typeof originUser === 'object' ? originUser : {}; + const safePatchUser = patchUser && typeof patchUser === 'object' ? patchUser : {}; + ctx.user = { + ...safeOriginUser, + ...safePatchUser, + }; + + try { + return await callback(); + } finally { + ctx.user = originUser; + } + } + + /** + * 枚举库内全部仓库的当前订单分表(wms_order_delivery_{warehouseId})对应的仓库ID。 + * + * 通过 INFORMATION_SCHEMA 枚举真实存在的物理分表,比查询 wms_warehouse 更可靠: + * 避免仓库配置表与物理分表不一致(如已建表未配置、已停用仓库残留分表)导致的漏扫; + * history/dispatch/outsourced 等表位通过表名正则过滤,仅保留 current 表位。 + * + * @return {Promise} 仓库ID列表。 + */ + async listCurrentWarehouseIds() { + const { ctx } = this; + const rows = await ctx.model.query( + 'SELECT TABLE_NAME AS tableName' + + ' FROM INFORMATION_SCHEMA.TABLES' + + ' WHERE TABLE_SCHEMA = DATABASE()' + + ' AND TABLE_NAME LIKE \'wms_order_delivery\\_%\'' + + ' ORDER BY TABLE_NAME', + { type: ctx.model.QueryTypes.SELECT } + ); + + const warehouseIds = []; + for (const row of (Array.isArray(rows) ? rows : [])) { + const tableName = String(row.tableName || row.TABLE_NAME || '').trim(); + const matched = CURRENT_SHARD_TABLE_PATTERN.exec(tableName); + if (!matched) { + continue; + } + + const warehouseId = Number(matched[1]); + if (Number.isInteger(warehouseId) && warehouseId > 0) { + warehouseIds.push(warehouseId); + } + } + + return Array.from(new Set(warehouseIds)); + } + + /** + * 构造自动确认候选订单的 SQL 过滤条件(不含 warehouse_id 与 id 分页条件)。 + * + * 口径: + * - intercept_status = 'requested'(请求拦截); + * - print_status = 'none'(面单未打印); + * - 满足任一超时条件:intercept_time 超过 12 小时,或 create_at 超过 36 小时; + * 时间比较使用数据库侧 NOW()/DATE_SUB,避免应用与数据库时钟偏差; + * intercept_time 为 NULL 时小于比较自然不命中,无需特判。 + * + * @return {string} SQL 过滤条件片段。 + */ + buildCandidateWhereSql() { + return `intercept_status = '${AUTO_CONFIRM_INTERCEPT_STATUS}'` + + ` AND print_status = '${AUTO_CONFIRM_PRINT_STATUS}'` + + ' AND (' + + ` intercept_time < DATE_SUB(NOW(), INTERVAL ${INTERCEPT_TIME_TIMEOUT_HOURS} HOUR)` + + ` OR create_at < DATE_SUB(NOW(), INTERVAL ${CREATE_AT_TIMEOUT_HOURS} HOUR)` + + ' )'; + } + + /** + * 候选订单口径镜像函数:判断单行是否命中自动确认条件(12h/36h 口径)。 + * + * 与 buildCandidateWhereSql 的 SQL 口径保持一致,供单元测试验证边界语义; + * 生产扫描以 SQL 为准。 + * + * @param {Object} fields 订单行字段。 + * @param {string} [fields.interceptStatus] 拦截状态。 + * @param {string} [fields.printStatus] 面单打印状态。 + * @param {Date|string|number|null} [fields.interceptTime] 拦截时间(可空)。 + * @param {Date|string|number|null} [fields.createAt] 创建时间。 + * @param {Date} [now=new Date()] 当前时间基准。 + * @return {boolean} 是否命中自动确认条件。 + */ + matchesAutoConfirmCriteria(fields = {}, now = new Date()) { + const row = fields && typeof fields === 'object' ? fields : {}; + const interceptStatus = String(row.interceptStatus ?? '').trim(); + const printStatus = String(row.printStatus ?? '').trim(); + const nowMs = now instanceof Date ? now.getTime() : toTimestamp(now); + + if (interceptStatus !== AUTO_CONFIRM_INTERCEPT_STATUS || printStatus !== AUTO_CONFIRM_PRINT_STATUS) { + return false; + } + + const interceptMs = toTimestamp(row.interceptTime); + if (interceptMs !== null && interceptMs < nowMs - INTERCEPT_TIME_TIMEOUT_MS) { + return true; + } + + const createMs = toTimestamp(row.createAt); + if (createMs !== null && createMs < nowMs - CREATE_AT_TIMEOUT_MS) { + return true; + } + + return false; + } + + /** + * 解析并校验仓库当前订单分表名。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 可直接拼接到 SQL 的表名(仅含字母数字下划线)。 + */ + resolveCurrentTableName(warehouseId) { + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error(`非法仓库ID: ${warehouseId}`); + } + + const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.generateTableName !== 'function') { + throw new Error('订单工厂不可用'); + } + + const tableName = String(factory.generateTableName(normalizedWarehouseId, 'current') || '').trim(); + if (!/^[a-zA-Z0-9_]+$/.test(tableName)) { + throw new Error(`订单表名不合法: ${tableName}`); + } + + return tableName; + } + + /** + * 分页扫描指定仓库的自动确认候选订单ID(id 游标翻页,避免 OFFSET 深翻页)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {number} [batchSize=SCAN_BATCH_SIZE] 单批扫描数量。 + * @return {Promise} 命中条件的订单ID列表。 + */ + async scanCandidateOrderIds(warehouseId, batchSize = SCAN_BATCH_SIZE) { + const { ctx } = this; + const tableName = this.resolveCurrentTableName(warehouseId); + const candidateWhereSql = this.buildCandidateWhereSql(); + const normalizedBatchSize = Math.max(Number.parseInt(batchSize, 10) || SCAN_BATCH_SIZE, 1); + const orderIds = []; + let lastId = 0; + + for (;;) { + const rows = await ctx.model.query( + 'SELECT id' + + ` FROM ${tableName}` + + ' WHERE warehouse_id = :warehouseId' + + ` AND ${candidateWhereSql}` + + ' AND id > :lastId' + + ' ORDER BY id ASC' + + ' LIMIT :limit', + { + replacements: { + warehouseId: Number(warehouseId), + lastId, + limit: normalizedBatchSize, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const pageRows = Array.isArray(rows) ? rows : []; + if (pageRows.length === 0) { + break; + } + + let pageMaxId = lastId; + for (const row of pageRows) { + const orderId = Number(row && row.id || 0); + if (Number.isFinite(orderId) && orderId > 0) { + orderIds.push(orderId); + pageMaxId = orderId; + } + } + + // 防死循环:本页没有解析出任何有效订单ID,或已不足一页,结束翻页 + if (pageMaxId <= lastId || pageRows.length < normalizedBatchSize) { + break; + } + + lastId = pageMaxId; + } + + return orderIds; + } + + /** + * 库内拦截确定内部实现:按订单ID列表批量确认仓库拦截(不依赖用户上下文)。 + * + * systemMethods 出口 confirmIntercept 与定时任务统一复用本方法,保证行为一致。 + * 支持部分失败:未找到的订单与处理失败的订单记录在 failed 列表并返回失败原因, + * 其余订单继续处理;每单失败不影响其他订单。 + * + * 每个订单的拦截处理: + * 1. 更新订单:intercept_status=intercepted_at_warehouse、step=4、outbound_status=fin, + * where 同时限定拦截状态白名单防并发误更新; + * **不写 intercept_time**(该字段恒为「最近一次发起拦截的通知时刻」,库内确定拦截不覆盖, + * 见 app/lib/intercept_time.js;库内确定拦截时刻以配送表 dispath_time 为准) + * 2. 同步更新运单表:is_intercept='Y'、is_back='Y' + * 3. 释放储位分配(cancelAllocateStorage 拦截模式,临时注入仓库上下文) + * 4. 释放订单锁(lock_status='none') + * 5. 写入操作日志(ORDER_INTERCEPT_CONFIRM) + * 全部订单处理完后,按成功订单ID汇总批量创建售后工单 + 通知快递群。 + * 运单标记、储位释放、锁释放、工单创建、日志写入失败均不影响主流程。 + * + * @param {Object} params 参数。 + * @param {number[]} params.orderIds 订单ID列表。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} [params.operator] 操作人信息({ id, name })。 + * @return {Promise} 批量拦截结果,包含 success/failed 列表与 success_count/failed_count 计数。 + */ + async confirmInterceptForOrderIds(params = {}) { + const { ctx } = this; + const requestParams = params && typeof params === 'object' ? params : {}; + const orderIds = Array.isArray(requestParams.orderIds) + ? Array.from(new Set( + requestParams.orderIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0) + )) + : []; + const warehouseId = requestParams.warehouseId ?? null; + const operator = requestParams.operator && typeof requestParams.operator === 'object' + ? requestParams.operator + : { ...AUTO_CONFIRM_OPERATOR }; + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + + if (warehouseId === null || warehouseId === undefined || warehouseId === '') { + throw new Error('缺少仓库上下文 store_id'); + } + + const { Op } = ctx.app.Sequelize; + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderRows = await orderModel.findAll({ + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status', 'wave_no' ], + raw: true, + }); + + const orderMap = new Map(); + for (const row of orderRows) { + orderMap.set(Number(row.id), row); + } + + const successOrders = []; + const failedOrders = []; + const successOrderIds = []; + + for (const orderId of orderIds) { + const order = orderMap.get(orderId); + + if (!order) { + failedOrders.push({ order_id: orderId, reason: '未找到对应订单' }); + continue; + } + + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + const interceptStatus = String(order.intercept_status || '').trim(); + + // 未发起拦截(none/空)的订单直接跳过,不参与确认拦截处理 + if (interceptStatus === '' || interceptStatus === 'none') { + continue; + } + + // 已确认拦截的订单跳过,避免重复执行副作用(释放储位/工单/日志等) + if (interceptStatus === 'intercepted_at_warehouse') { + failedOrders.push({ + order_id: orderId, + delivery_order_code: orderNo, + reason: '订单已确认拦截', + }); + continue; + } + + // 仅拦截发起中与历史值 intercepted 允许确认,其余状态不允许确认拦截 + if (!CONFIRMABLE_INTERCEPT_STATUSES.includes(interceptStatus)) { + failedOrders.push({ + order_id: orderId, + delivery_order_code: orderNo, + reason: `订单拦截状态不允许确认拦截: ${interceptStatus}`, + }); + continue; + } + + try { + const now = new Date(); + // 库内确定拦截不写 intercept_time(不覆盖通知拦截时刻),库内确定时刻以配送表 dispath_time 为准 + const updateValues = { + intercept_status: 'intercepted_at_warehouse', + step: 4, + outbound_status: 'fin', + updated_at: now, + }; + const updateResult = await orderModel.update(updateValues, { + where: { + id: orderId, + warehouse_id: warehouseId, + // 数据库层再次限定拦截状态,防止查询后状态被并发修改导致误更新 + intercept_status: { [Op.in]: CONFIRMABLE_INTERCEPT_STATUSES }, + }, + }); + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + + if (affectedRows <= 0) { + throw new Error('拦截状态更新失败,请稍后重试'); + } + + // 同步更新运单表:标记拦截 + 退回(库内拦截确认,货物在库内需退回) + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y', is_back: 'Y' }, + { where: { order_id: orderId, warehouse_id: warehouseId } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[interceptAutoConfirm.confirmInterceptForOrderIds] 更新运单拦截/退回标记失败, orderId=${orderId}, error=${expressErr.message}` + ); + } + + // 拦截成功后释放储位分配(拦截模式:库存移入拦截锁定,不归还可用) + try { + await this.withPatchedCtxUser({ store_id: warehouseId }, () => ( + ctx.service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: [ orderId ], + interceptMode: true, + }) + )); + } catch (allocErr) { + ctx.logger.warn( + `[interceptAutoConfirm.confirmInterceptForOrderIds] 释放储位分配失败,不影响拦截, orderId=${orderId}, error=${allocErr.message}` + ); + } + + // 拦截成功后释放订单锁 + try { + await orderModel.update( + { lock_status: 'none', updated_at: now }, + { where: { id: orderId, warehouse_id: warehouseId } } + ); + } catch (lockErr) { + ctx.logger.warn( + `[interceptAutoConfirm.confirmInterceptForOrderIds] 释放锁失败,不影响拦截, orderId=${orderId}, error=${lockErr.message}` + ); + } + + // 写入操作日志(失败不影响主流程) + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: orderId, + operationCode: 'ORDER_INTERCEPT_CONFIRM', + operator, + extras: { + warehouseId, + orderId, + orderNo, + previousInterceptStatus: String(order.intercept_status || '').trim(), + newInterceptStatus: 'intercepted_at_warehouse', + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn( + `[interceptAutoConfirm.confirmInterceptForOrderIds] 写入操作日志失败,不影响业务, orderId=${orderId}, error=${logErr.message}` + ); + } + + successOrders.push({ + order_id: orderId, + order_no: orderNo, + intercept_status: 'intercepted_at_warehouse', + updated_at: now, + }); + successOrderIds.push(orderId); + } catch (error) { + ctx.logger.warn( + `[interceptAutoConfirm.confirmInterceptForOrderIds] 确认拦截失败, orderId=${orderId}, error=${error.message}` + ); + failedOrders.push({ + order_id: orderId, + delivery_order_code: orderNo, + reason: `确认拦截失败: ${error.message}`, + }); + } + } + + // 创建售后工单 + 通知快递群(成功订单 ID 汇总统一调用,失败不影响主流程) + if (successOrderIds.length > 0) { + try { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: successOrderIds, + warehouseId, + creatorLabel: operator.name || '系统', + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[interceptAutoConfirm.confirmInterceptForOrderIds] 创建工单/通知失败, orderIds=${successOrderIds.join(',')}, error=${workOrderErr.message}` + ); + } + } + + return { + success: successOrders, + failed: failedOrders, + success_count: successOrders.length, + failed_count: failedOrders.length, + }; + } + + /** + * 自动库内拦截确定主入口:枚举仓库 → 分页扫描候选订单 → 分批确认拦截。 + * + * 单个仓库扫描/确认失败仅记录日志与 detail.error,不影响其他仓库; + * 全部动作失败不阻断下轮执行(异常上抛由定时任务捕获记录)。 + * + * @param {Object} [options={}] 执行选项。 + * @param {number} [options.scanBatchSize=SCAN_BATCH_SIZE] 单批扫描数量。 + * @param {number} [options.confirmBatchSize=CONFIRM_BATCH_SIZE] 单批确认数量。 + * @return {Promise} 执行结果汇总,包含 warehouse_count/candidate_count/confirmed_count/ + * failed_count/warehouse_ids/duration_ms/details。 + */ + async runAutoConfirm(options = {}) { + const { ctx } = this; + const startedAt = Date.now(); + const requestOptions = options && typeof options === 'object' ? options : {}; + const scanBatchSize = Math.max(Number.parseInt(requestOptions.scanBatchSize, 10) || SCAN_BATCH_SIZE, 1); + const confirmBatchSize = Math.max(Number.parseInt(requestOptions.confirmBatchSize, 10) || CONFIRM_BATCH_SIZE, 1); + const warehouseIds = await this.listCurrentWarehouseIds(); + + const details = []; + let candidateCount = 0; + let confirmedCount = 0; + let failedCount = 0; + + for (const warehouseId of warehouseIds) { + const detail = { + warehouse_id: warehouseId, + candidate_count: 0, + confirmed_count: 0, + failed_count: 0, + error: null, + }; + + try { + const candidateIds = await this.scanCandidateOrderIds(warehouseId, scanBatchSize); + detail.candidate_count = candidateIds.length; + + for (let offset = 0; offset < candidateIds.length; offset += confirmBatchSize) { + const batchIds = candidateIds.slice(offset, offset + confirmBatchSize); + const batchResult = await this.confirmInterceptForOrderIds({ + orderIds: batchIds, + warehouseId, + operator: AUTO_CONFIRM_OPERATOR, + }); + + detail.confirmed_count += batchResult.success_count; + detail.failed_count += batchResult.failed_count; + } + } catch (error) { + detail.error = String(error && error.message ? error.message : error); + ctx.logger.warn( + `[interceptAutoConfirm.runAutoConfirm] 仓库 ${warehouseId} 处理失败,跳过: ${detail.error}` + ); + } + + candidateCount += detail.candidate_count; + confirmedCount += detail.confirmed_count; + failedCount += detail.failed_count; + details.push(detail); + } + + return { + warehouse_count: warehouseIds.length, + candidate_count: candidateCount, + confirmed_count: confirmedCount, + failed_count: failedCount, + warehouse_ids: warehouseIds, + duration_ms: Date.now() - startedAt, + details, + }; + } +} + +module.exports = InterceptAutoConfirmService; diff --git a/app/service/systems/license_plate.js b/app/service/systems/license_plate.js new file mode 100644 index 0000000..d3a3506 --- /dev/null +++ b/app/service/systems/license_plate.js @@ -0,0 +1,255 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('crypto'); +const https = require('https'); + +const OCR_HOST = 'ocr.tencentcloudapi.com'; +const OCR_SERVICE = 'ocr'; +const OCR_VERSION = '2018-11-19'; +const OCR_ACTION = 'LicensePlateOCR'; +const MAX_IMAGE_BYTES = 7 * 1024 * 1024; + +class LicensePlateService extends Service { + /** + * 获取腾讯云公共配置。 + * + * 说明:优先读取独立的腾讯云公共配置,若不存在则回退到兼容的 COS 配置, + * 以保证历史配置方式仍然可用。 + * + * @return {Object} 腾讯云公共配置对象 + */ + getTencentCloudConfig() { + const tencentCloudConfig = this.config.tencentCloud || {}; + const cosConfig = this.config.cos || {}; + + return { + appId: tencentCloudConfig.appId ?? cosConfig.appId, + secretId: tencentCloudConfig.secretId ?? cosConfig.secretId, + secretKey: tencentCloudConfig.secretKey ?? cosConfig.secretKey, + }; + } + + /** + * 获取腾讯云 OCR 的默认区域。 + * + * @return {string} 腾讯云区域标识 + */ + getTencentCloudRegion() { + const tencentCloudConfig = this.config.tencentCloud || {}; + const cosConfig = this.config.cos || {}; + + return tencentCloudConfig.region || cosConfig.region || 'ap-guangzhou'; + } + + /** + * 规范化并校验 base64 图片。 + * + * @param {string} imageBase64 前端传入的 base64 图片 + * @return {{ base64: string, buffer: Buffer, size: number }} 规范化后的图片信息 + */ + normalizeBase64Image(imageBase64) { + const rawValue = String(imageBase64 || '').trim(); + + if (!rawValue) { + throw new Error('base64 图片不能为空'); + } + + const normalizedBase64 = rawValue + .replace(/^data:[^;]+;base64,/i, '') + .replace(/\s+/g, ''); + + if (!normalizedBase64) { + throw new Error('base64 图片不能为空'); + } + + if (!/^[A-Za-z0-9+/=]+$/.test(normalizedBase64)) { + throw new Error('base64 图片格式不正确'); + } + + const buffer = Buffer.from(normalizedBase64, 'base64'); + + if (!buffer.length) { + throw new Error('base64 图片解码失败'); + } + + if (buffer.length > MAX_IMAGE_BYTES) { + throw new Error('图片大小不能超过 7MB'); + } + + const normalizedWithoutPadding = normalizedBase64.replace(/=+$/u, ''); + const roundTripWithoutPadding = buffer.toString('base64').replace(/=+$/u, ''); + + if (normalizedWithoutPadding !== roundTripWithoutPadding) { + throw new Error('base64 图片格式不正确'); + } + + return { + base64: normalizedBase64, + buffer, + size: buffer.length, + }; + } + + /** + * 生成腾讯云 TC3 请求签名。 + * + * @param {Object} options 请求参数 + * @param {string} options.action 腾讯云动作名 + * @param {string} options.service 腾讯云服务名 + * @param {string} options.version 腾讯云接口版本 + * @param {string} options.region 腾讯云区域 + * @param {Object} options.payload 请求体 + * @return {{ requestOptions: Object, payloadString: string }} 请求配置 + */ + buildTencentCloudRequest({ action, service, version, region, payload }) { + const { secretId, secretKey } = this.getTencentCloudConfig(); + + if (!secretId || !secretKey) { + throw new Error('腾讯云密钥未配置'); + } + + const timestamp = Math.floor(Date.now() / 1000); + const date = new Date(timestamp * 1000).toISOString().slice(0, 10); + const payloadString = JSON.stringify(payload || {}); + const hashedRequestPayload = crypto.createHash('sha256').update(payloadString).digest('hex'); + const canonicalHeaders = `content-type:application/json; charset=utf-8\nhost:${OCR_HOST}\n`; + const signedHeaders = 'content-type;host'; + const canonicalRequest = [ + 'POST', + '/', + '', + canonicalHeaders, + signedHeaders, + hashedRequestPayload, + ].join('\n'); + const credentialScope = `${date}/${service}/tc3_request`; + const stringToSign = [ + 'TC3-HMAC-SHA256', + timestamp, + credentialScope, + crypto.createHash('sha256').update(canonicalRequest).digest('hex'), + ].join('\n'); + + const secretDate = crypto.createHmac('sha256', `TC3${secretKey}`).update(date).digest(); + const secretService = crypto.createHmac('sha256', secretDate).update(service).digest(); + const secretSigning = crypto.createHmac('sha256', secretService).update('tc3_request').digest(); + const signature = crypto.createHmac('sha256', secretSigning).update(stringToSign).digest('hex'); + + const authorization = `TC3-HMAC-SHA256 Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; + + return { + payloadString, + requestOptions: { + hostname: OCR_HOST, + method: 'POST', + path: '/', + headers: { + Authorization: authorization, + 'Content-Type': 'application/json; charset=utf-8', + Host: OCR_HOST, + 'X-TC-Action': action, + 'X-TC-Version': version, + 'X-TC-Timestamp': String(timestamp), + 'X-TC-Region': region, + }, + }, + }; + } + + /** + * 发送腾讯云请求并解析 JSON 响应。 + * + * @param {Object} requestConfig 请求配置 + * @param {Object} requestConfig.requestOptions https 请求参数 + * @param {string} requestConfig.payloadString 请求体字符串 + * @return {Promise} 腾讯云响应对象 + */ + async sendTencentCloudRequest(requestConfig) { + const { requestOptions, payloadString } = requestConfig; + + const responseText = await new Promise((resolve, reject) => { + const request = https.request(requestOptions, response => { + response.setEncoding('utf8'); + let responseBody = ''; + + response.on('data', chunk => { + responseBody += chunk; + }); + + response.on('end', () => { + resolve(responseBody); + }); + }); + + request.on('error', reject); + request.setTimeout(30000, () => { + request.destroy(new Error('腾讯云车牌识别请求超时')); + }); + request.write(payloadString); + request.end(); + }); + + let parsedResponse; + try { + parsedResponse = JSON.parse(responseText); + } catch (error) { + throw new Error(`腾讯云响应解析失败: ${error.message}`); + } + + const responsePayload = parsedResponse && parsedResponse.Response ? parsedResponse.Response : parsedResponse; + + if (responsePayload && responsePayload.Error) { + const { Code = 'TencentCloudError', Message = '腾讯云接口调用失败' } = responsePayload.Error; + throw new Error(`${Code}: ${Message}`); + } + + return parsedResponse; + } + + /** + * 识别车牌号码。 + * + * @param {string} imageBase64 前端传入的 base64 图片 + * @return {Promise} 车牌识别结果 + */ + async recognizeLicensePlate(imageBase64) { + const { base64 } = this.normalizeBase64Image(imageBase64); + const region = this.getTencentCloudRegion(); + const requestConfig = this.buildTencentCloudRequest({ + action: OCR_ACTION, + service: OCR_SERVICE, + version: OCR_VERSION, + region, + payload: { + ImageBase64: base64, + }, + }); + + const response = await this.sendTencentCloudRequest(requestConfig); + return this.formatLicensePlateResult(response); + } + + /** + * 统一整理腾讯云车牌识别响应。 + * + * @param {Object} response 腾讯云响应 + * @return {Object} 归一化后的识别结果 + */ + formatLicensePlateResult(response) { + const responseData = response && response.Response ? response.Response : response || {}; + const licensePlate = String( + responseData.LicensePlate + || responseData.Number + || responseData.PlateNumber + || responseData.CarPlateNumber + || '' + ).trim(); + + return { + licensePlate, + }; + } +} + +module.exports = LicensePlateService; diff --git a/app/service/systems/location.js b/app/service/systems/location.js index 578e3da..f4d57a8 100644 --- a/app/service/systems/location.js +++ b/app/service/systems/location.js @@ -5,7 +5,7 @@ const Service = require('egg').Service; class LocationService extends Service { /** * 创建货架并自动生成仓位 - * @param params + * @param {Object} params 货架基础参数 */ async createRackWithSpaces(params) { const { ctx } = this; @@ -37,9 +37,9 @@ class LocationService extends Service { /** * 为货架生成仓位 - * @param rackId - * @param rack - * @param transaction + * @param {number|string} rackId 货架ID + * @param {Object} rack 货架信息 + * @param {Object} transaction 事务对象 */ async _generateSpacesForRack(rackId, rack, transaction) { const { app } = this; @@ -56,7 +56,7 @@ class LocationService extends Service { for (let row = 1; row <= rack_rows; row++) { for (let column = 1; column <= rack_columns; column++) { for (let level = 1; level <= rack_levels; level++) { - const spaceCode = `${rack.zone_code}-${row.toString().padStart(2, '0')}-${column.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`; + const spaceCode = `${rack.zone_code}-${column.toString().padStart(2, '0')}-${row.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`; // 计算相对坐标 const relativeX = (column - 1) * cellLength; @@ -71,12 +71,12 @@ class LocationService extends Service { row_no: row.toString(), column_no: column.toString(), level_no: level.toString(), - cell_no: `${row}-${column}-${level}`, + cell_no: `${column}-${row}-${level}`, length: cellLength, width: cellWidth, height: cellHeight, volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³ - max_weight: 100, // 默认100kg + max_weight: 100000, // 默认100000g space_status: 'AVAILABLE', is_enabled: true, relative_x: relativeX, @@ -97,9 +97,9 @@ class LocationService extends Service { /** * 计算库区内货架的排序(按X坐标排序) - * @param warehouseId - * @param areaId - * @param transaction + * @param {number|string} warehouseId 仓库ID + * @param {number|string} areaId 库区ID + * @param {Object} transaction 事务对象 */ async _calculateAreaRackOrder(warehouseId, areaId, transaction) { const { app } = this; @@ -129,8 +129,8 @@ class LocationService extends Service { /** * 计算仓库的拣货路径 - * @param warehouseId - * @param transaction + * @param {number|string} warehouseId 仓库ID + * @param {Object} transaction 事务对象 */ async _calculatePickPathForWarehouse(warehouseId, transaction) { const { app } = this; @@ -189,10 +189,10 @@ class LocationService extends Service { /** * 更新货架下仓位的拣货顺序 - * @param rackId - * @param rackSequence - * @param rackDistance - * @param transaction + * @param {number|string} rackId 货架ID + * @param {number} rackSequence 货架拣货顺序 + * @param {number} rackDistance 起始点距离 + * @param {Object} transaction 事务对象 */ async _updateSpacePickSequence(rackId, rackSequence, rackDistance, transaction) { const { app } = this; @@ -241,8 +241,8 @@ class LocationService extends Service { /** * 计算拣货优先级 - * @param row - * @param distance + * @param {number} row 层数 + * @param {number} distance 距离 */ _calculatePickPriority(row, distance) { // 行数越小(下层)优先级越高 @@ -257,8 +257,8 @@ class LocationService extends Service { /** * 更新货架位置后重新计算路径 - * @param rackId - * @param newPosition + * @param {number|string} rackId 货架ID + * @param {Object} newPosition 新坐标 */ async updateRackPosition(rackId, newPosition) { const { ctx, app } = this; @@ -305,8 +305,8 @@ class LocationService extends Service { /** * 获取拣货路径 - * @param warehouseId - * @param options + * @param {number|string} warehouseId 仓库ID + * @param {Object} options 查询选项 */ async getPickPath(warehouseId, options = {}) { const { app } = this; @@ -364,7 +364,7 @@ class LocationService extends Service { /** * 批量更新邻居关系 - * @param warehouseId + * @param {number|string} warehouseId 仓库ID */ async updateNeighborRelations(warehouseId) { const { app } = this; @@ -392,8 +392,8 @@ class LocationService extends Service { /** * 查找相邻货架 - * @param currentRack - * @param allRacks + * @param {Object} currentRack 当前货架 + * @param {Array} allRacks 所有货架 */ async _findNeighborRacks(currentRack, allRacks) { const NEIGHBOR_DISTANCE = 2000; // 2米内视为邻居 diff --git a/app/service/systems/location_space.js b/app/service/systems/location_space.js index 779f8b8..8cc4c1c 100644 --- a/app/service/systems/location_space.js +++ b/app/service/systems/location_space.js @@ -5,7 +5,8 @@ const Service = require('egg').Service; class LocationSpaceService extends Service { /** * 创建仓位 - * @param data + * @param {Object} data 仓位数据 + * @return {Promise} 创建结果 */ async create(data) { const { ctx } = this; @@ -47,10 +48,13 @@ class LocationSpaceService extends Service { ctx.throw(400, '仓位编码已存在'); } - // 检查条码唯一性 + // 检查条码唯一性(仓库内唯一) if (data.custom_barcode) { const barcodeExists = await ctx.model.LocationSpace.findOne({ - where: { custom_barcode: data.custom_barcode }, + where: { + warehouse_id: data.warehouse_id, + custom_barcode: data.custom_barcode, + }, }); if (barcodeExists) { @@ -72,7 +76,8 @@ class LocationSpaceService extends Service { /** * 批量创建仓位 - * @param dataList + * @param {Array} dataList 仓位数据列表 + * @return {Promise} 创建结果 */ async batchCreate(dataList) { const { ctx } = this; @@ -101,10 +106,11 @@ class LocationSpaceService extends Service { ctx.throw(400, `以下仓位编码已存在: ${codes}`); } - // 检查条码重复 + // 检查条码重复(仓库内唯一) if (barcodes.length > 0) { const duplicateBarcodes = await ctx.model.LocationSpace.findAll({ where: { + warehouse_id: warehouseId, custom_barcode: { [ctx.app.Sequelize.Op.in]: barcodes }, }, attributes: [ 'custom_barcode' ], @@ -133,7 +139,8 @@ class LocationSpaceService extends Service { /** * 获取仓位列表 - * @param params + * @param {Object} params 查询参数 + * @return {Promise} 列表结果 */ async list(params = {}) { const { ctx } = this; @@ -224,7 +231,8 @@ class LocationSpaceService extends Service { /** * 获取仓位详情 - * @param id + * @param {number|string} id 仓位ID + * @return {Promise} 仓位详情 */ async detail(id) { const { ctx } = this; @@ -259,8 +267,9 @@ class LocationSpaceService extends Service { /** * 更新仓位 - * @param id - * @param data + * @param {number|string} id 仓位ID + * @param {Object} data 更新数据 + * @return {Promise} 更新结果 */ async update(id, data) { const { ctx } = this; @@ -289,10 +298,11 @@ class LocationSpaceService extends Service { } } - // 如果修改条码,检查唯一性 + // 如果修改条码,检查唯一性(仓库内唯一) if (data.custom_barcode && data.custom_barcode !== locationSpace.custom_barcode) { const exists = await ctx.model.LocationSpace.findOne({ where: { + warehouse_id: locationSpace.warehouse_id, custom_barcode: data.custom_barcode, id: { [ctx.app.Sequelize.Op.ne]: id }, }, @@ -323,7 +333,8 @@ class LocationSpaceService extends Service { /** * 删除仓位(软删除) - * @param id + * @param {number|string} id 仓位ID + * @return {Promise} 删除结果 */ async delete(id) { const { ctx } = this; @@ -359,8 +370,9 @@ class LocationSpaceService extends Service { /** * 启用/禁用仓位 - * @param id - * @param enabled + * @param {number|string} id 仓位ID + * @param {boolean} enabled 是否启用 + * @return {Promise} 操作结果 */ async toggleStatus(id, enabled) { const { ctx } = this; @@ -389,8 +401,9 @@ class LocationSpaceService extends Service { /** * 更新仓位状态 - * @param id - * @param status + * @param {number|string} id 仓位ID + * @param {string} status 仓位状态 + * @return {Promise} 操作结果 */ async updateStatus(id, status) { const { ctx } = this; @@ -440,7 +453,8 @@ class LocationSpaceService extends Service { /** * 查询可用仓位 - * @param params + * @param {Object} params 查询参数 + * @return {Promise} 可用仓位列表 */ async findAvailableSpaces(params) { const { ctx } = this; @@ -490,8 +504,9 @@ class LocationSpaceService extends Service { /** * 根据编码查找仓位 - * @param warehouseId - * @param spaceCode + * @param {number|string} warehouseId 仓库ID + * @param {string} spaceCode 仓位编码 + * @return {Promise} 仓位信息 */ async findByCode(warehouseId, spaceCode) { const { ctx } = this; @@ -525,7 +540,8 @@ class LocationSpaceService extends Service { /** * 根据条码查找仓位 - * @param barcode + * @param {string} barcode 条码 + * @return {Promise} 仓位信息 */ async findByBarcode(barcode) { const { ctx } = this; @@ -558,7 +574,8 @@ class LocationSpaceService extends Service { /** * 获取仓库仓位统计 - * @param warehouseId + * @param {number|string} warehouseId 仓库ID + * @return {Promise} 统计结果 */ async getWarehouseStats(warehouseId) { const { ctx } = this; @@ -585,8 +602,9 @@ class LocationSpaceService extends Service { /** * 获取分区的仓位统计 - * @param warehouseId - * @param zoneId + * @param {number|string} warehouseId 仓库ID + * @param {number|string|null} zoneId 分区ID + * @return {Promise} 统计结果 */ async getZoneStats(warehouseId, zoneId = null) { const { ctx } = this; @@ -602,7 +620,8 @@ class LocationSpaceService extends Service { /** * 验证仓位是否可分配 - * @param locationSpaceId + * @param {number|string} locationSpaceId 仓位ID + * @return {Promise} 仓位信息 */ async validateAllocation(locationSpaceId) { const { ctx } = this; @@ -634,7 +653,8 @@ class LocationSpaceService extends Service { /** * 验证仓位是否可移出 - * @param locationSpaceId + * @param {number|string} locationSpaceId 仓位ID + * @return {Promise} 仓位信息 */ async validateTransferOut(locationSpaceId) { const { ctx } = this; @@ -666,7 +686,8 @@ class LocationSpaceService extends Service { /** * 内部方法:验证关联数据 - * @param data + * @param {Object} data 关联数据 + * @return {Promise} */ async _validateReferences(data) { const { ctx } = this; diff --git a/app/service/systems/location_zone.js b/app/service/systems/location_zone.js index 7a857d8..3951f58 100644 --- a/app/service/systems/location_zone.js +++ b/app/service/systems/location_zone.js @@ -3,13 +3,77 @@ const Service = require('egg').Service; class LocationZoneService extends Service { + async collectZoneSubtree(rootId, transaction) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const zoneIds = [ Number(rootId) ]; + const zones = []; + let parentIds = [ Number(rootId) ]; + + while (parentIds.length > 0) { + const children = await ctx.model.LocationZone.findAll({ + where: { + parent_id: { + [Op.in]: parentIds, + }, + deleted_at: null, + }, + raw: true, + transaction, + }); + + if (!Array.isArray(children) || children.length === 0) { + break; + } + + zones.push(...children); + parentIds = children + .map(item => Number(item && item.id)) + .filter(childId => Number.isFinite(childId) && childId > 0); + zoneIds.push(...parentIds); + } + + return { + zoneIds, + zones, + }; + } + + async assertSpacesNotOccupied(spaceIds, transaction) { + if (!Array.isArray(spaceIds) || spaceIds.length === 0) { + return; + } + + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const stockCount = await ctx.model.Storage.count({ + where: { + space_id: { + [Op.in]: spaceIds, + }, + delete_at: null, + is_enabled: 1, + [Op.or]: [ + { quantity: { [Op.gt]: 0 } }, + { locked_quantity: { [Op.gt]: 0 } }, + { available_quantity: { [Op.gt]: 0 } }, + ], + }, + transaction, + }); + + if (stockCount > 0) { + throw new Error('删除范围内库位有库存,禁止删除,请先移库'); + } + } + /** * 获取所有仓库级别的分区列表 - * @param warehouseId + * @param {number|string} warehouseId 仓库ID * @return {Promise} 仓库级别分区列表 */ async getWarehouseLevelZones(warehouseId) { - const { ctx, app } = this; + const { ctx } = this; try { const zones = await ctx.model.LocationZone.findAll({ @@ -32,27 +96,22 @@ class LocationZoneService extends Service { let totalSpaces = 0; for (let ii = 0; ii < warehouse_tree.warehouseRoot.children.length; ii++) { const area = warehouse_tree.warehouseRoot.children[ii]; - console.log('area', area); for (let iii = 0; iii < area.children.length; iii++) { const zone = area.children[iii]; - if (zone.type == 'rack') { - console.log('货架', zone); + if (zone.type === 'rack') { racks.push(zone); rackCount++; - const sz_count = await app.model.LocationSpace.count({ where: { zone_id: zone.id } }); - console.log(sz_count); const { rackColumns = 1, rackRows = 1, rackLevels = 1 } = zone.data; totalSpaces += rackColumns * rackRows * rackLevels; } } - if (area.type == 'area') { + if (area.type === 'area') { areaCount++; } } zones[i].rackCount = rackCount; zones[i].areaCount = areaCount; zones[i].totalSpaces = totalSpaces; - console.log('zones[i]', i, rackCount, areaCount, zones[i].rackCount, zones[i].areaCount); } // 转换为前端需要的格式 return zones.map(zone => ({ @@ -75,11 +134,10 @@ class LocationZoneService extends Service { } /** - * 根据仓库ID获取完整的树状结构(支持Element Tree格式) - * @param {number} warehouseId - 仓库ID - * @param warehouseSpaceId - * @return {Promise} 树状结构数据 - */ + * 根据仓库ID获取完整的树状结构(支持Element Tree格式)。 + * @param {number|string} warehouseSpaceId 仓库分区ID + * @return {Promise} 树状结构数据 + */ async getZoneTreeByWarehouse(warehouseSpaceId) { const { ctx } = this; const warehouseId = ctx.user.store_id; @@ -318,16 +376,46 @@ class LocationZoneService extends Service { return count === 0; } + /** + * 校验分区编码在同仓库未占用(已归档分区不占用编码:paranoid 查询自动带 deleted_at IS NULL)。 + * 同仓库同 zone_code 并存会生成同 space_code 的库位行,导致盘点/库存按编码定位到多条库位。 + * + * @param {number} warehouseId 仓库ID。 + * @param {string} zoneCode 分区编码。 + * @param {number} [excludeZoneId] 排除的分区ID(更新场景排除自身)。 + * @return {Promise} 校验不通过时抛出错误。 + */ + async assertZoneCodeAvailable(warehouseId, zoneCode, excludeZoneId = 0) { + const { ctx } = this; + const code = String(zoneCode || '').trim(); + if (!code) { + return; + } + if (!/^[A-Z0-9]{1,5}$/.test(code)) { + throw new Error('编码必须是1-5位大写字母或数字'); + } + const where = { + warehouse_id: Number(warehouseId), + zone_code: code, + }; + if (Number(excludeZoneId) > 0) { + where.id = { [ctx.app.Sequelize.Op.ne]: Number(excludeZoneId) }; + } + const exists = await ctx.model.LocationZone.findOne({ + where, + attributes: [ 'id' ], + raw: true, + }); + if (exists) { + throw new Error(`分区编码已存在:${code}(同仓库编码需唯一,归档分区不占用编码)`); + } + } + /** * 创建元素 - * @param {Object} data - 元素数据 + * @param {Object} data 元素数据 * @return {Promise} 创建的元素 */ - /** - * 创建元素 - * @param {Object} data - 元素数据 - * @return {Promise} 创建的元素 - */ async createZone(data) { const { ctx } = this; try { @@ -342,10 +430,12 @@ class LocationZoneService extends Service { // 3. 验证父元素 await this.validateParentElement(data, warehouse_id); - // 5. 处理编码(根据类型) const zoneCode = this.generateZoneCodeByType(data); + // 5.1 编码唯一性:同仓库未归档分区不得重复(否则会生成同编码库位,盘点按编码定位错乱) + await this.assertZoneCodeAvailable(warehouse_id, zoneCode); + // 6. 创建分区 const zone = await ctx.model.LocationZone.create({ warehouse_id, @@ -366,7 +456,7 @@ class LocationZoneService extends Service { direction: data.direction, color: data.color || this.getDefaultColorByType(data.zone_type), }); - if (zone.zone_type == 'rack') { + if (zone.zone_type === 'rack') { await this.generateSpacesForRack(zone.id, zone); } return { @@ -382,7 +472,7 @@ class LocationZoneService extends Service { /** * 验证基本字段 - * @param data + * @param {Object} data 元素数据 */ validateBasicFields(data) { // 所有元素都需要这些字段 @@ -405,21 +495,22 @@ class LocationZoneService extends Service { /** * 根据类型进行特定验证 - * @param data - * @param warehouseId + * @param {Object} data 元素数据 + * @param {number|string} warehouseId 仓库ID */ async validateByZoneType(data, warehouseId) { const { ctx } = this; switch (data.zone_type) { - case 'warehouse': + case 'warehouse': { // 仓库必须 parent_id = 0 if (data.parent_id !== 0 && data.parent_id !== null) { throw new Error('仓库元素的父元素必须为0或null'); } break; + } - case 'area': + case 'area': { // 库区必须有父元素且父元素必须是仓库 if (!data.parent_id) { throw new Error('库区必须指定父元素'); @@ -438,8 +529,9 @@ class LocationZoneService extends Service { throw new Error('库区只能创建在仓库上'); } break; + } - case 'rack': + case 'rack': { // 货架必须有父元素且父元素必须是通道 if (!data.parent_id) { throw new Error('货架必须指定父元素'); @@ -471,7 +563,9 @@ class LocationZoneService extends Service { throw new Error('货架列数、层数、分格数必须大于0'); } break; - case 'pick_start': + } + + case 'pick_start': { // 这些元素必须有父元素且父元素可以是任何类型(除了自身) if (!data.parent_id) { throw new Error(`${this.getZoneTypeText(data.zone_type)}必须指定父元素`); @@ -483,13 +577,11 @@ class LocationZoneService extends Service { deleted_at: null, }, }); - if (parentSpecial.zone_type !== 'area') { - throw new Error('拣货起点只能创建在库区上'); - } if (!parentSpecial) { throw new Error('父元素不存在'); } break; + } default: throw new Error('不支持的分区类型'); @@ -498,8 +590,8 @@ class LocationZoneService extends Service { /** * 验证父元素 - * @param data - * @param warehouseId + * @param {Object} data 元素数据 + * @param {number|string} warehouseId 仓库ID */ async validateParentElement(data, warehouseId) { const { ctx } = this; @@ -531,18 +623,21 @@ class LocationZoneService extends Service { const parentEndX = parent.x + parent.length; const parentEndY = parent.y + parent.width; const parentEndZ = parent.z + parent.height; - const elementEndX = data.x + data.length; const elementEndY = data.y + data.width; const elementEndZ = data.z + data.height; + if (elementEndX > parentEndX || elementEndY > parentEndY || elementEndZ > parentEndZ) { + throw new Error('元素必须位于父元素范围内'); + } + } /** * 验证坐标是否重叠 - * @param data - * @param warehouseId - * @param excludeId + * @param {Object} data 元素数据 + * @param {number|string} warehouseId 仓库ID + * @param {number|string|null} excludeId 排除的分区ID */ async validateZoneOverlap(data, warehouseId, excludeId = null) { const { ctx } = this; @@ -565,8 +660,9 @@ class LocationZoneService extends Service { /** * 检查两个元素是否重叠 - * @param zone1 - * @param zone2 + * @param {Object} zone1 元素1 + * @param {Object} zone2 元素2 + * @return {boolean} 是否重叠 */ isOverlap(zone1, zone2) { const zone1EndX = zone1.x + zone1.length; @@ -587,7 +683,8 @@ class LocationZoneService extends Service { /** * 根据类型生成编码 - * @param data + * @param {Object} data 元素数据 + * @return {string|null} 编码 */ generateZoneCodeByType(data) { // 只有特定类型需要编码 @@ -621,7 +718,8 @@ class LocationZoneService extends Service { /** * 根据类型获取默认颜色 - * @param zoneType + * @param {string} zoneType 类型 + * @return {string} 默认颜色 */ getDefaultColorByType(zoneType) { const colorMap = { @@ -638,7 +736,8 @@ class LocationZoneService extends Service { /** * 获取类型文本 - * @param type + * @param {string} type 类型 + * @return {string} 类型文本 */ getZoneTypeText(type) { const typeMap = { @@ -674,18 +773,55 @@ class LocationZoneService extends Service { throw new Error('分区不存在'); } - console.log('修改的数据', data); + const updateData = { ...data }; + + // 编码变更需保证同仓库未归档分区内唯一(未变更则跳过) + if (updateData.zone_code !== undefined && updateData.zone_code !== null) { + const nextCode = String(updateData.zone_code).trim(); + if (nextCode && nextCode !== String(zone.zone_code || '').trim()) { + await this.assertZoneCodeAvailable(zone.warehouse_id, nextCode, id); + updateData.zone_code = nextCode; + } else if (!nextCode) { + delete updateData.zone_code; + } + } + + if (data.is_active !== undefined) { + const isActive = [ true, 1, '1', 'true' ].includes(data.is_active); + const isInactive = [ false, 0, '0', 'false' ].includes(data.is_active); + + if (!isActive && !isInactive) { + throw new Error('is_active 参数格式不正确'); + } + + if (isInactive) { + const activeChildren = await ctx.model.LocationZone.count({ + where: { + parent_id: id, + deleted_at: null, + is_active: 1, + }, + }); + + if (activeChildren > 0) { + throw new Error('请先禁用所有子分区'); + } + } + + updateData.is_active = isActive ? 1 : 0; + } + // 验证坐标是否重叠(如果修改了坐标) if ( - (data.x !== undefined || data.y !== undefined || data.length || data.width) && + (updateData.x !== undefined || updateData.y !== undefined || updateData.length || updateData.width) && zone.warehouse_id ) { - const x = data.x !== undefined ? data.x : zone.x; - const y = data.y !== undefined ? data.y : zone.y; - const z = data.z !== undefined ? data.z : zone.z || 0; - const length = data.length || zone.length; - const width = data.width || zone.width; - const height = data.height || zone.height || 0; + const x = updateData.x !== undefined ? updateData.x : zone.x; + const y = updateData.y !== undefined ? updateData.y : zone.y; + const z = updateData.z !== undefined ? updateData.z : zone.z || 0; + const length = updateData.length || zone.length; + const width = updateData.width || zone.width; + const height = updateData.height || zone.height || 0; const overlaps = await this.checkZoneOverlap( zone.warehouse_id, @@ -704,7 +840,7 @@ class LocationZoneService extends Service { } // 更新分区 - await zone.update(data); + await zone.update(updateData); return { success: true, @@ -725,7 +861,6 @@ class LocationZoneService extends Service { */ async deleteZone(id) { const { ctx } = this; - console.log('需要删除的id', id); try { const zone = await ctx.model.LocationZone.findOne({ where: { @@ -737,22 +872,57 @@ class LocationZoneService extends Service { if (!zone) { throw new Error('分区不存在'); } - // 检查是否有子分区 - const childrenCount = await ctx.model.LocationZone.count({ - where: { - parent_id: id, - deleted_at: null, - }, + + await ctx.model.transaction(async transaction => { + const { Op } = ctx.app.Sequelize; + const { zoneIds, zones } = await this.collectZoneSubtree(id, transaction); + const rackZoneIds = [ zone, ...zones ] + .filter(item => item && item.zone_type === 'rack') + .map(item => Number(item.id)) + .filter(zoneId => Number.isFinite(zoneId) && zoneId > 0); + const spaceZoneIds = zone.zone_type === 'rack' + ? zoneIds + : rackZoneIds; + + const spaces = await ctx.model.LocationSpace.findAll({ + where: { + zone_id: { + [Op.in]: spaceZoneIds, + }, + deleted_at: null, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + + const spaceIds = (Array.isArray(spaces) ? spaces : []) + .map(space => Number(space && space.id)) + .filter(spaceId => Number.isFinite(spaceId) && spaceId > 0); + + await this.assertSpacesNotOccupied(spaceIds, transaction); + + if (spaceIds.length > 0) { + await ctx.model.LocationSpace.destroy({ + where: { + id: { + [Op.in]: spaceIds, + }, + }, + transaction, + }); + } + + await ctx.model.LocationZone.destroy({ + where: { + id: { + [Op.in]: zoneIds, + }, + }, + transaction, + }); }); - if (zone.zone_type == 'rack') { - // 货架执行删除需要检测库位是否还有库存 - throw new Error('货架XX库位有库存,禁止删除,请先移库'); - } - if (childrenCount > 0) { - throw new Error('请先删除或转移所有子分区'); - } - // 执行软删除 - await zone.destroy(); + return { success: true, message: '删除成功', @@ -765,14 +935,14 @@ class LocationZoneService extends Service { /** * 检查区域重叠 - * @param warehouseId - * @param x - * @param y - * @param z - * @param length - * @param width - * @param height - * @param excludeId + * @param {number|string} warehouseId 仓库ID + * @param {number} x X 坐标 + * @param {number} y Y 坐标 + * @param {number} z Z 坐标 + * @param {number} length 长度 + * @param {number} width 宽度 + * @param {number} height 高度 + * @param {number|string|null} excludeId 排除的分区ID * @private */ async checkZoneOverlap(warehouseId, x, y, z, length, width, height, excludeId) { @@ -931,37 +1101,42 @@ class LocationZoneService extends Service { } async generateSpacesForRack(rackId, rack, transaction = null) { - const { app } = this; + const { app, ctx } = this; + const { Op } = app.Sequelize; const { rack_columns, rack_rows, rack_levels, direction, x, y, z } = rack; + const expectedSpaceCount = Number(rack_columns || 0) * Number(rack_rows || 0) * Number(rack_levels || 0); + + // 读取已有仓位编码,用于差量补齐。 + const existingSpaces = await ctx.model.LocationSpace.findAll({ + where: { + zone_id: rackId, + deleted_at: null, + }, + attributes: [ 'id', 'space_code' ], + raw: true, + transaction, + }); + const existingSpaceCodeSet = new Set( + (Array.isArray(existingSpaces) ? existingSpaces : []) + .map(item => String(item && item.space_code || '').trim()) + .filter(Boolean) + ); + + const rackWidth = rack.width; + const rackLength = rack.length; + const prelativeX = x; + const prelativeY = y; + const prelativeZ = z; + const cellLength = rackLength / rack_columns / rack_levels; + const cellWidth = rackWidth; + const cellHeight = rack.height / rack_rows; + const spaces = []; - let rackWidth = 0; - let rackLength = 0; - const rackHeight = 0; - let cellLength = 0; - let cellWidth = 0; - let cellHeight = 0; - let prelativeX = 0; - let prelativeY = 0; - let prelativeZ = 0; - - - rackWidth = rack.width; - rackLength = rack.length; - prelativeX = x; - prelativeY = y; - prelativeZ = z; - // 计算每个仓位的尺寸 - cellLength = rackLength / rack_columns / rack_levels; - cellWidth = rackWidth; - cellHeight = rack.height / rack_rows; - - // 生成所有仓位 - for (let column = 1; column <= rack_columns; column++) { - for (let row = 1; row <= rack_rows; row++) { + for (let row = 1; row <= rack_rows; row++) { + for (let column = 1; column <= rack_columns; column++) { for (let level = 1; level <= rack_levels; level++) { const spaceCode = `${rack.zone_code}-${column.toString().padStart(2, '0')}-${row.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`; - // 计算相对坐标 let relativeX = 0; let relativeY = 0; let relativeZ = (level - 1) * cellWidth + prelativeZ; @@ -979,7 +1154,7 @@ class LocationZoneService extends Service { spaces.push({ warehouse_id: rack.warehouse_id, zone_id: rackId, - location_type_id: row == 1 ? 1 : 2, // 默认第一层为分拣,其他层为存储 + location_type_id: row === 1 ? 1 : 2, space_code: spaceCode, row_no: row.toString(), column_no: column.toString(), @@ -988,8 +1163,8 @@ class LocationZoneService extends Service { length: cellLength, width: cellWidth, height: cellHeight, - volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³ - max_weight: 100, // 默认100kg + volume: cellLength * cellWidth * cellHeight / 1000000, + max_weight: 100000, space_status: 'AVAILABLE', is_enabled: true, relative_x: relativeX, @@ -1001,55 +1176,178 @@ class LocationZoneService extends Service { } } - // 批量插入仓位 - if (spaces.length > 0) { - await app.model.LocationSpace.bulkCreate(spaces, { transaction }); + const expectedSpaceCodeSet = new Set(spaces.map(space => String(space.space_code || '').trim()).filter(Boolean)); + const spacesNeedDelete = (Array.isArray(existingSpaces) ? existingSpaces : []).filter(space => { + const spaceCode = String(space && space.space_code || '').trim(); + return spaceCode && !expectedSpaceCodeSet.has(spaceCode); + }); + + if (spacesNeedDelete.length > 0) { + const extraSpaceIds = spacesNeedDelete + .map(space => Number(space && space.id)) + .filter(spaceId => Number.isFinite(spaceId) && spaceId > 0); + + if (extraSpaceIds.length > 0) { + const storages = await ctx.model.Storage.findAll({ + where: { + space_id: { + [Op.in]: extraSpaceIds, + }, + delete_at: null, + is_enabled: 1, + [Op.or]: [ + { quantity: { [Op.gt]: 0 } }, + { locked_quantity: { [Op.gt]: 0 } }, + { available_quantity: { [Op.gt]: 0 } }, + ], + }, + attributes: [ 'space_id', 'quantity', 'locked_quantity', 'available_quantity' ], + raw: true, + transaction, + }); + + if (Array.isArray(storages) && storages.length > 0) { + const occupiedSpaceIdSet = new Set(storages.map(item => Number(item && item.space_id)).filter(Boolean)); + const occupiedSpaceCodes = spacesNeedDelete + .filter(space => occupiedSpaceIdSet.has(Number(space && space.id))) + .map(space => String(space && space.space_code || '').trim()) + .filter(Boolean); + + throw new Error(`发现 ${spacesNeedDelete.length} 个多余库位,其中 ${occupiedSpaceCodes.length} 个存在库存,禁止自动删除:${occupiedSpaceCodes.slice(0, 10).join(',')}`); + } + + await ctx.model.LocationSpace.destroy({ + where: { + id: { + [Op.in]: extraSpaceIds, + }, + }, + transaction, + }); + } + } + + const missingSpaces = spaces.filter(space => !existingSpaceCodeSet.has(String(space.space_code || '').trim())); + const existingSpaceCount = existingSpaceCodeSet.size; + + if (missingSpaces.length === 0 && spacesNeedDelete.length === 0) { + return `货架 ${rack.zone_code} 已完整存在 ${existingSpaceCount} 个仓位,无需补齐`; + } + + if (missingSpaces.length === 0) { + return `货架 ${rack.zone_code} 已删除 ${spacesNeedDelete.length} 个多余库位,当前总数 ${expectedSpaceCount}/${expectedSpaceCount}`; } - return `为货架 ${rack.zone_code} 生成了 ${spaces.length} 个仓位`; - } - async getSpaceInfo(id) { - const { ctx } = this; try { - const path = []; - const space = await ctx.model.LocationSpace.findOne({ + await app.model.LocationSpace.bulkCreate(missingSpaces, { transaction }); + const finalSpaceCount = existingSpaceCount - spacesNeedDelete.length + missingSpaces.length; + if (spacesNeedDelete.length > 0) { + return `为货架 ${rack.zone_code} 删除 ${spacesNeedDelete.length} 个多余库位并补齐 ${missingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`; + } + return `为货架 ${rack.zone_code} 补齐 ${missingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`; + } catch (error) { + // 并发场景:再次按编码回查后补齐剩余缺口。 + const latestSpaces = await ctx.model.LocationSpace.findAll({ where: { - id, - warehouse_id: ctx.user.store_id, + zone_id: rackId, deleted_at: null, }, - attributes: [ 'id', 'location_type_id', 'space_code', 'custom_name', 'custom_barcode', 'space_status', 'pick_sequence' ], + attributes: [ 'space_code' ], + raw: true, + transaction, }); - if (!space) { + const latestSpaceCodeSet = new Set( + (Array.isArray(latestSpaces) ? latestSpaces : []) + .map(item => String(item && item.space_code || '').trim()) + .filter(Boolean) + ); + const retryMissingSpaces = spaces.filter(space => !latestSpaceCodeSet.has(String(space.space_code || '').trim())); + + if (retryMissingSpaces.length === 0) { + return `货架 ${rack.zone_code} 已完整存在 ${latestSpaceCodeSet.size} 个仓位,无需补齐`; + } + + await app.model.LocationSpace.bulkCreate(retryMissingSpaces, { transaction }); + const finalSpaceCount = latestSpaceCodeSet.size + retryMissingSpaces.length; + if (spacesNeedDelete.length > 0) { + return `为货架 ${rack.zone_code} 删除 ${spacesNeedDelete.length} 个多余库位并补齐 ${retryMissingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`; + } + return `为货架 ${rack.zone_code} 补齐 ${retryMissingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`; + } + } + /** + * 获取仓位信息(优先当前仓库,未命中时校验全局归属)。 + * @param {number|string} id 仓位ID + * @return {Promise} 仓位信息 + * @throws {Error} 仓位不存在 + * @throws {Error} 仓位不属于当前仓库 + */ + async getSpaceInfo(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const attributes = [ 'id', 'location_type_id', 'space_code', 'custom_name', 'custom_barcode', 'space_status', 'pick_sequence' ]; + + try { + const currentWarehouseSpace = await ctx.model.LocationSpace.findOne({ + where: { + id, + warehouse_id: warehouseId, + deleted_at: null, + }, + attributes, + }); + + if (currentWarehouseSpace) { + return currentWarehouseSpace; + } + + const globalSpace = await ctx.model.LocationSpace.findOne({ + where: { + id, + deleted_at: null, + }, + attributes: [ 'id', 'warehouse_id' ], + }); + + if (!globalSpace) { throw new Error('仓位不存在'); } - return space; + + if (Number(globalSpace.warehouse_id) !== Number(warehouseId)) { + throw new Error('仓位不属于当前仓库'); + } + + throw new Error('仓位不存在'); } catch (error) { ctx.logger.error('获取分区路径失败:', error); throw error; } } - async checkBarcodeUnique(id, barcode) { - const { ctx } = this; + async checkBarcodeUnique(id, barcode, warehouseId) { + const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; try { - // 检查条码是否被其他仓位使用(排除当前仓位) + // 检查条码是否被其他仓位使用(排除当前仓位,仓库内唯一) + const whereConditions = [ + { + id: { + [Op.ne]: id, // 排除当前仓位ID + }, + }, + { + [Op.or]: [ + { custom_barcode: barcode }, // 检查自定义条码 + { space_code: barcode }, // 检查仓位编码 + ], + }, + { deleted_at: null }, // 未删除的记录 + ]; + if (warehouseId) { + whereConditions.push({ warehouse_id: warehouseId }); + } const space = await ctx.model.LocationSpace.findOne({ where: { - [Op.and]: [ - { - id: { - [Op.ne]: id, // 排除当前仓位ID - }, - }, - { - [Op.or]: [ - { custom_barcode: barcode }, // 检查自定义条码 - { space_code: barcode }, // 检查仓位编码 - ], - }, - { deleted_at: null }, // 未删除的记录 - ], + [Op.and]: whereConditions, }, attributes: [ 'id' ], }); diff --git a/app/service/systems/notice/drivers/generic.js b/app/service/systems/notice/drivers/generic.js new file mode 100644 index 0000000..062123c --- /dev/null +++ b/app/service/systems/notice/drivers/generic.js @@ -0,0 +1,39 @@ +'use strict'; + +class CustomizeWebhookDriver { + constructor(ctx, options = {}) { + this.ctx = ctx; + this.options = options; + } + + async send({ hook, payload }) { + const requestOptions = { + method: 'POST', + headers: { + 'content-type': 'application/json', + }, + timeout: 5000, + dataType: 'json', + contentType: 'json', + data: payload, + }; + + this.ctx.logger.info('[CustomizeWebhookDriver.send] 发送内容', { + hookUrl: String(hook && hook.hook_url || '').substring(0, 80), + hookType: String(hook && hook.hook_type || 'customize'), + payloadKeys: Object.keys(payload || {}), + }); + + const response = await this.ctx.curl(String(hook.hook_url || ''), requestOptions); + + return { + hookId: Number(hook && hook.id) || 0, + hookType: String(hook && hook.hook_type || this.options.hookType || 'customize'), + hookUrl: String(hook && hook.hook_url || ''), + status: Number(response && response.status) || 200, + response: response && response.data !== undefined ? response.data : null, + }; + } +} + +module.exports = CustomizeWebhookDriver; diff --git a/app/service/systems/notice/drivers/wecom.js b/app/service/systems/notice/drivers/wecom.js new file mode 100644 index 0000000..0e18817 --- /dev/null +++ b/app/service/systems/notice/drivers/wecom.js @@ -0,0 +1,86 @@ +'use strict'; + +class WecomWebhookDriver { + constructor(ctx, options = {}) { + this.ctx = ctx; + this.options = options; + } + + buildTextContent(payload = {}) { + const message = payload.message || {}; + const lines = [ + String(message.title || '').trim(), + String(message.content || message.body || '').trim(), + ].filter(Boolean); + + if (message.url) { + lines.push(`链接:${String(message.url).trim()}`); + } + + return lines.join('\n') || '您有一条新的业务通知'; + } + + buildMarkdownContent(payload = {}) { + const message = payload.message || {}; + const title = String(message.title || '业务通知').trim(); + const content = String(message.content || message.body || '').trim(); + const url = String(message.url || '').trim(); + const lines = [ + `**${title}**`, + content ? `>${content}` : '', + url ? `[点击查看](${url})` : '', + ].filter(Boolean); + + return lines.join('\n'); + } + + buildRequestData(payload = {}) { + const messageType = String(payload.message && payload.message.type || 'text').trim().toLowerCase(); + + if ([ 'image', 'file' ].includes(messageType)) { + return { + msgtype: 'markdown', + markdown: { + content: this.buildMarkdownContent(payload), + }, + }; + } + + return { + msgtype: 'text', + text: { + content: this.buildTextContent(payload), + }, + }; + } + + async send({ hook, payload }) { + const requestData = this.buildRequestData(payload); + this.ctx.logger.info('[WecomWebhookDriver.send] 发送内容', { + hookUrl: String(hook && hook.hook_url || '').substring(0, 80), + requestData, + }); + const requestOptions = { + method: 'POST', + headers: { + 'content-type': 'application/json', + }, + timeout: 5000, + dataType: 'json', + contentType: 'json', + data: requestData, + }; + + const response = await this.ctx.curl(String(hook && hook.hook_url || ''), requestOptions); + + return { + hookId: Number(hook && hook.id) || 0, + hookType: 'wecom', + hookUrl: String(hook && hook.hook_url || ''), + status: Number(response && response.status) || 200, + response: response && response.data !== undefined ? response.data : null, + }; + } +} + +module.exports = WecomWebhookDriver; diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js new file mode 100644 index 0000000..4a3170e --- /dev/null +++ b/app/service/systems/notice/index.js @@ -0,0 +1,1354 @@ +'use strict'; + +const { Service } = require('egg'); +const CustomizeWebhookDriver = require('./drivers/generic'); +const WecomWebhookDriver = require('./drivers/wecom'); + +const MESSAGE_TYPE_MAP = Object.freeze({ + text: 'text', + txt: 'text', + message: 'text', + 文本: 'text', + image: 'image', + img: 'image', + picture: 'image', + 图片: 'image', + file: 'file', + attachment: 'file', + 文件: 'file', +}); +const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; +const DEFAULT_RETRY_DELAYS_MS = Object.freeze([ 3000, 6000, 12000 ]); +const EVENT_CODE_PATTERN = /^[a-z_][a-z0-9_]*$/; +const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ + 'all', + '*', + 'receiving_completed', + 'receiving_rejected', + 'receiving_reviewed', + 'receiving_store_bound', + 'receiving_store_unmatched', + 'receiving_pending_inbound', + 'entry_order_completed', + 'order_cancel_intercepted', + 'wave_strategy_quick_scan_failed', + 'store_warehouse_print_quantity_adjusted', +]); +/** + * 固定群订阅配置:事件 → 目标群类型/子类型(仓库接口消息推送通道,统一推送配置来源)。 + * 群类型定义见 app/service/inbox/groups.js 的 GROUP_TYPES: + * warehouse 子类型:receiving 收货 / production 生产 / stockout 出库 / finance 财务 / all 全体 / customer_service 客服 / exception 异常 + * store 子类型:after_sales 售后 / finance 财务 / receiving 收货(需 store_id) + */ +const FIXED_GROUP_SUBSCRIPTIONS = Object.freeze({ + receiving_completed: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), + ]), + receiving_rejected: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), + ]), + receiving_reviewed: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), + Object.freeze({ + groupType: 'store', + subType: 'receiving', + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + }), + ]), + receiving_store_bound: Object.freeze([ + Object.freeze({ + groupType: 'store', + subType: 'receiving', + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + }), + ]), + receiving_store_unmatched: Object.freeze([ + Object.freeze({ + groupType: 'store', + subType: 'receiving', + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + }), + ]), + receiving_pending_inbound: Object.freeze([ + Object.freeze({ + groupType: 'store', + subType: 'receiving', + // 未绑定货主(或无货主收货群)时回退仓库客服群人工跟进 + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'customer_service' }), + ]), + }), + ]), + entry_order_completed: Object.freeze([ + Object.freeze({ + groupType: 'store', + subType: 'receiving', + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + }), + ]), + order_cancel_intercepted: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'exception' }), + ]), + order_sync_completed: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + store_warehouse_print_quantity_adjusted: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'finance' }), + ]), + storage_transfer_completed: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'production' }), + ]), + wave_strategy_quick_scan_failed: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'exception' }), + ]), +}); +const DRIVER_TYPE_ALIASES = Object.freeze({ + custom: 'customize', + customize: 'customize', + generic: 'customize', + wecom: 'wecom', +}); + +class NoticeService extends Service { + /** + * 统一通知服务构造函数,初始化驱动缓存。 + * @param {object} ctx Egg 上下文 + */ + constructor(ctx) { + super(ctx); + this.driverCache = new Map(); + } + + /** + * 根据 webhook 类型获取对应发送驱动。 + * @param {string} [hookType='customize'] webhook 类型 + * @return {object} webhook 驱动实例 + */ + getDriver(hookType = 'customize') { + const normalizedHookType = String(hookType || 'customize').trim().toLowerCase() || 'customize'; + const resolvedHookType = DRIVER_TYPE_ALIASES[normalizedHookType] || 'customize'; + + if (!this.driverCache.has(resolvedHookType)) { + let driver = null; + switch (resolvedHookType) { + case 'wecom': + driver = new WecomWebhookDriver(this.ctx, { + hookType: resolvedHookType, + }); + break; + case 'customize': + default: + driver = new CustomizeWebhookDriver(this.ctx, { + hookType: resolvedHookType, + }); + break; + } + + this.driverCache.set(resolvedHookType, driver); + } + return this.driverCache.get(resolvedHookType); + } + + /** + * 规范化消息类型,兼容中英文和别名写法。 + * @param {string} [type='text'] 原始消息类型 + * @return {string} 标准化后的消息类型 + */ + normalizeMessageType(type = 'text') { + const rawType = String(type || 'text').trim(); + const normalizedType = rawType.toLowerCase(); + return MESSAGE_TYPE_MAP[rawType] || MESSAGE_TYPE_MAP[normalizedType] || 'text'; + } + + /** + * 将传入值安全转换为对象。 + * @param {*} value 原始值 + * @param {object} [fallback={}] 转换失败时的兜底对象 + * @return {object} 转换后的对象 + */ + toObject(value, fallback = {}) { + if (!value) { + return fallback; + } + + if (typeof value === 'object' && !Array.isArray(value)) { + return value; + } + + if (typeof value === 'string') { + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback; + } catch (_) { + return fallback; + } + } + + return fallback; + } + + /** + * 规范化订阅事件列表,支持数组、字符串和对象格式。 + * @param {*} rawEvents 原始事件配置 + * @return {string[]} 事件编码数组 + */ + normalizeEventList(rawEvents) { + if (!rawEvents) { + return []; + } + + if (Array.isArray(rawEvents)) { + return rawEvents + .map(item => String(item || '').trim().toLowerCase() + .replace(/\./g, '_')) + .filter(Boolean); + } + + if (typeof rawEvents === 'string') { + const trimmed = rawEvents.trim(); + if (!trimmed) { + return []; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawEvents) { + return this.normalizeEventList(parsed); + } + } catch (_) { + // ignore parse failure and continue with string split + } + + return trimmed.split(/[\s,;|]+/).map(item => item.trim().toLowerCase().replace(/\./g, '_')).filter(Boolean); + } + + if (typeof rawEvents === 'object') { + if (rawEvents.all === true) { + return [ 'all' ]; + } + + return this.normalizeEventList(rawEvents.include || rawEvents.events || []); + } + + return []; + } + + /** + * 判断当前 webhook 是否命中本次消息事件。 + * @param {*} rawEvents 订阅的事件配置 + * @param {object} payload 统一消息载荷 + * @return {boolean} 是否命中 + */ + matchesEvents(rawEvents, payload) { + const eventList = this.normalizeEventList(rawEvents); + if (eventList.length === 0) { + return true; + } + + const candidateEvents = new Set([ + payload.event, + payload.businessName, + `${payload.businessName}_${payload.message.type}`, + ].map(item => String(item || '').trim().toLowerCase()).filter(Boolean)); + + return eventList.some(item => item === '*' || item === 'all' || candidateEvents.has(item)); + } + + /** + * 生成本次通知的追踪 ID。 + * @return {string} 追踪ID + */ + buildTraceId() { + return `notice_${Date.now()}_${Math.random().toString(16).slice(2, 10)}`; + } + + /** + * 获取当前模型中已注册的事件编码列表。 + * @return {string[]} 注册的事件编码列表 + */ + getRegisteredEventCodes() { + const notificationWebhookModel = this.ctx.model && this.ctx.model.NotificationWebhook; + if (!notificationWebhookModel) { + return [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + } + + if (typeof notificationWebhookModel.getAvailableEventCodes === 'function') { + const codes = notificationWebhookModel.getAvailableEventCodes() + .map(item => String(item || '').trim().toLowerCase()) + .filter(Boolean); + // 默认注册事件码始终生效(与模型配置合并,便于服务内按现有模式追加新事件码) + return codes.length > 0 + ? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ] + : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + } + + if (Array.isArray(notificationWebhookModel.AVAILABLE_EVENTS)) { + const codes = notificationWebhookModel.AVAILABLE_EVENTS + .map(item => String(item && item.code || '').trim().toLowerCase()) + .filter(Boolean); + return codes.length > 0 + ? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ] + : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + } + + return [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + } + + /** + * 判断事件编码是否符合标识符式命名:仅允许小写字母、数字、下划线,且首字符不能为数字。 + * @param {string} event 事件编码 + * @return {boolean} 是否有效 + */ + isValidEventCode(event) { + const normalizedEvent = String(event || '').trim().toLowerCase(); + return normalizedEvent === 'all' || normalizedEvent === '*' || EVENT_CODE_PATTERN.test(normalizedEvent); + } + + /** + * 校验待发送事件是否已在通知模型中注册。 + * @param {string} event 事件名 + */ + assertEventRegistered(event) { + const normalizedEvent = String(event || '').trim().toLowerCase(); + if (!normalizedEvent) { + throw new Error('event 不能为空'); + } + + if (!this.isValidEventCode(normalizedEvent)) { + throw new Error(`event 命名不合法,仅支持小写字母、数字、下划线,且首字符不能为数字: ${normalizedEvent}`); + } + + const registeredCodes = this.getRegisteredEventCodes(); + if (registeredCodes.length > 0 && !registeredCodes.includes(normalizedEvent)) { + throw new Error(`event 未注册,不允许发送: ${normalizedEvent}`); + } + } + + /** + * 获取通知失败后的重试间隔,默认按 3 秒、6 秒、12 秒阶梯重试。 + * @param {object} [options={}] 原始通知入参 + * @return {number[]} 重试间隔数组 + */ + getRetryDelays(options = {}) { + const customDelays = Array.isArray(options.retryDelaysMs) + ? options.retryDelaysMs + : (Array.isArray(this.app && this.app.config && this.app.config.noticeRetryDelaysMs) + ? this.app.config.noticeRetryDelaysMs + : DEFAULT_RETRY_DELAYS_MS); + + const normalizedDelays = customDelays + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item >= 0); + + return normalizedDelays.length > 0 ? normalizedDelays : [ ...DEFAULT_RETRY_DELAYS_MS ]; + } + + /** + * Promise 风格 sleep,用于统一重试等待。 + * @param {number} [ms=0] 等待毫秒数 + * @return {Promise} + */ + async sleep(ms = 0) { + const waitMs = Math.max(0, Number(ms) || 0); + await new Promise(resolve => setTimeout(resolve, waitMs)); + } + + /** + * 判断外部 webhook 返回是否可视为成功。 + * @param {object} [result={}] 发送结果 + * @return {boolean} 是否成功 + */ + isSuccessfulResponse(result = {}) { + const status = Number(result && result.status || 0); + if (status > 0 && (status < 200 || status >= 300)) { + return false; + } + + const response = result && Object.prototype.hasOwnProperty.call(result, 'response') + ? result.response + : null; + + if ([ 0, '0', false, 'false' ].includes(response)) { + return false; + } + + if (response && typeof response === 'object') { + if (response.ok === false || response.success === false) { + return false; + } + + if (Object.prototype.hasOwnProperty.call(response, 'errcode')) { + const errcode = Number(response.errcode); + if (Number.isFinite(errcode) && errcode !== 0) { + return false; + } + } + + if (Object.prototype.hasOwnProperty.call(response, 'code')) { + const responseCode = Number(response.code); + if (Number.isFinite(responseCode) && responseCode === 0) { + return false; + } + } + } + + return true; + } + + /** + * 归一化失败原因,便于日志记录与回写数据库。 + * @param {object} params 参数对象 + * @param {object|null} [params.result=null] 最近一次发送结果 + * @param {Error|null} [params.error=null] 最近一次异常 + * @return {string} 失败原因 + */ + getFailureMessage({ result = null, error = null } = {}) { + if (error && error.message) { + return error.message; + } + + const status = Number(result && result.status || 0); + if (status > 0 && (status < 200 || status >= 300)) { + return `webhook 请求失败,HTTP 状态码 ${status}`; + } + + const response = result && Object.prototype.hasOwnProperty.call(result, 'response') + ? result.response + : null; + + if ([ 0, '0' ].includes(response)) { + return 'webhook 返回 0,判定为失败'; + } + + if ([ false, 'false' ].includes(response)) { + return 'webhook 返回 false,判定为失败'; + } + + if (response && typeof response === 'object') { + if (Object.prototype.hasOwnProperty.call(response, 'errcode')) { + const errcode = Number(response.errcode); + if (Number.isFinite(errcode) && errcode !== 0) { + return String(response.errmsg || response.message || `企业微信 webhook 返回异常 errcode=${errcode}`); + } + } + if (response.message) { + return String(response.message); + } + if (response.msg) { + return String(response.msg); + } + if (response.errmsg) { + return String(response.errmsg); + } + } + + return 'webhook 推送失败'; + } + + /** + * 当 webhook 在重试后仍失败时,写入失败日志表。 + * @param {object} params 失败日志参数 + * @param {object} params.hook webhook 配置 + * @param {object} params.payload 标准化后的 payload + * @param {object|null} [params.result=null] 最近一次发送结果 + * @param {Error|null} [params.error=null] 最近一次异常 + * @param {number} [params.retryCount=0] 已执行重试次数 + * @return {Promise} + */ + async persistFailureLog({ hook, payload, result = null, error = null, retryCount = 0 }) { + const logModel = this.ctx.model && this.ctx.model.NotificationSendLog; + if (!logModel || typeof logModel.create !== 'function') { + return; + } + + try { + await logModel.create({ + trace_id: String(payload.traceId || ''), + webhook_id: Number(hook && hook.id || 0) || null, + store_id: Number(hook && hook.store_id || (payload.subject && payload.subject.id) || 0) || null, + warehouse_id: Number(payload.warehouseId || 0) || null, + owner_store_id: Number(payload.storeId || 0) || null, + business_name: String(payload.businessName || ''), + event: String(payload.event || ''), + hook_type: String(hook && hook.hook_type || ''), + hook_url: String(hook && hook.hook_url || ''), + request_payload: this.buildOutgoingPayload(hook || {}, payload), + response_payload: result && Object.prototype.hasOwnProperty.call(result, 'response') ? result.response : null, + http_status: Number(result && result.status || 0) || null, + status: 'failed', + error_message: this.getFailureMessage({ result, error }), + retry_count: Number(retryCount || 0), + created_by: Number(payload.sender && payload.sender.id || 0) || null, + }); + } catch (logError) { + this.ctx.logger.error('[NoticeService.persistFailureLog] save failed: %s', logError.message); + } + } + + /** + * 对单个 webhook 执行发送与阶梯重试。 + * @param {object} params 发送参数 + * @param {object} params.hook webhook 配置 + * @param {object} params.payload 标准化后的 payload + * @return {Promise} 发送结果 + */ + async sendWithRetry({ hook, payload }) { + const driver = this.getDriver(hook && hook.hook_type); + const outgoingPayload = this.buildOutgoingPayload(hook, payload); + const retryDelays = this.getRetryDelays(payload.raw || {}); + let lastResult = null; + let lastError = null; + + for (let attemptIndex = 0; attemptIndex <= retryDelays.length; attemptIndex++) { + try { + const result = await driver.send({ + hook, + payload: outgoingPayload, + }); + lastResult = result; + + if (this.isSuccessfulResponse(result)) { + return { + success: true, + retryCount: attemptIndex, + attemptCount: attemptIndex + 1, + ...(result || {}), + }; + } + + lastError = new Error(this.getFailureMessage({ result })); + } catch (error) { + lastError = error; + } + + if (attemptIndex < retryDelays.length) { + const waitMs = retryDelays[attemptIndex]; + this.ctx.logger.warn( + `[NoticeService.sendWithRetry] webhook send failed, retry in ${waitMs}ms (attempt ${attemptIndex + 1}/${retryDelays.length + 1}): ${this.getFailureMessage({ result: lastResult, error: lastError })}` + ); + await this.sleep(waitMs); + } + } + + await this.persistFailureLog({ + hook, + payload, + result: lastResult, + error: lastError, + retryCount: retryDelays.length, + }); + + return { + success: false, + hookId: Number(hook && hook.id || 0), + hookType: String(hook && hook.hook_type || ''), + hookUrl: String(hook && hook.hook_url || ''), + status: Number(lastResult && lastResult.status || 0) || 0, + response: lastResult && Object.prototype.hasOwnProperty.call(lastResult, 'response') ? lastResult.response : null, + error: this.getFailureMessage({ result: lastResult, error: lastError }), + retryCount: retryDelays.length, + attemptCount: retryDelays.length + 1, + }; + } + + /** + * 生成货主/仓库信息缓存键。 + * @param {number|string} warehouseId 仓库主体 ID + * @param {number|string} storeId 货主 ID + * @return {string} 缓存键 + */ + getStoreInfoCacheKey(warehouseId, storeId) { + return `warehouse:${Number(warehouseId || 0)}store:${Number(storeId || 0)}:info`; + } + + /** + * 解析货主信息,优先命中缓存,未命中时回查数据库并缓存 600 秒。 + * @param {object} [options={}] 原始通知入参 + * @param {object} [subject={}] 主体信息 + * @return {Promise} 货主信息 + */ + async resolveStoreInfo(options = {}, subject = {}) { + const directStore = this.toObject(options.store || options.owner, {}); + const subjectType = String(subject.type || options.subjectType || '').trim().toLowerCase(); + const warehouseId = Number( + options.warehouseId || options.warehouse_id || subject.warehouseId || (subjectType === 'warehouse' ? subject.id : 0) || options.subjectId || options.subject_id || 0 + ); + const storeId = Number( + options.ownerId || options.owner_id || options.storeOwnerId || options.store_owner_id || directStore.id || (subjectType === 'store' ? subject.id : 0) || (Number.isFinite(warehouseId) && warehouseId > 0 ? (options.storeId || options.store_id) : 0) || 0 + ); + + const normalizedStore = { + id: Number.isFinite(storeId) && storeId > 0 ? storeId : null, + name: String(directStore.name || directStore.companyName || directStore.company_name || ''), + businessLicense: String(directStore.businessLicense || directStore.business_license || ''), + storeRemask: String(directStore.storeRemask || directStore.store_remask || directStore.remask || ''), + warehouseUseStatus: directStore.warehouseUseStatus === undefined || directStore.warehouseUseStatus === null + ? null + : Number(directStore.warehouseUseStatus), + authStatus: directStore.authStatus === undefined || directStore.authStatus === null + ? null + : Number(directStore.authStatus), + }; + + if (!Number.isFinite(storeId) || storeId <= 0) { + return normalizedStore; + } + + const canUseCache = Number.isFinite(warehouseId) && warehouseId > 0; + const cacheKey = canUseCache ? this.getStoreInfoCacheKey(warehouseId, storeId) : ''; + + if (canUseCache && this.app && typeof this.app.getCacheAsync === 'function') { + try { + const cachedValue = await this.app.getCacheAsync(cacheKey); + const cachedStore = this.toObject(cachedValue, null); + if (cachedStore && Object.keys(cachedStore).length > 0) { + const businessLicense = String(cachedStore.businessLicense || cachedStore.business_license || normalizedStore.businessLicense || ''); + const storeRemask = String(cachedStore.storeRemask || cachedStore.store_remask || cachedStore.remask || normalizedStore.storeRemask || ''); + const warehouseUseStatus = cachedStore.warehouseUseStatus === undefined || cachedStore.warehouseUseStatus === null + ? normalizedStore.warehouseUseStatus + : Number(cachedStore.warehouseUseStatus); + const authStatus = cachedStore.authStatus === undefined || cachedStore.authStatus === null + ? normalizedStore.authStatus + : Number(cachedStore.authStatus); + return { + id: normalizedStore.id, + name: String(cachedStore.name || cachedStore.companyName || cachedStore.company_name || normalizedStore.name || ''), + businessLicense, + storeRemask, + warehouseUseStatus, + authStatus, + }; + } + } catch (error) { + this.ctx.logger.warn('[NoticeService.resolveStoreInfo] read cache failed: %s', error.message); + } + } + + const storeModel = this.ctx.model && this.ctx.model.Store; + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + + try { + const [ storeRecord, relationRecord ] = await Promise.all([ + storeModel && typeof storeModel.findByPk === 'function' + ? storeModel.findByPk(storeId, { + attributes: [ 'id', 'company_name', 'business_license' ], + }) + : null, + canUseCache && storeWarehouseModel && typeof storeWarehouseModel.findOne === 'function' + ? storeWarehouseModel.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + }, + attributes: [ 'store_remask', 'warehouse_use_status', 'auth_status' ], + }) + : null, + ]); + + const businessLicense = normalizedStore.businessLicense || String(storeRecord && storeRecord.business_license || ''); + const storeRemask = normalizedStore.storeRemask || String(relationRecord && relationRecord.store_remask || ''); + const warehouseUseStatus = relationRecord && relationRecord.warehouse_use_status !== undefined && relationRecord.warehouse_use_status !== null + ? Number(relationRecord.warehouse_use_status) + : normalizedStore.warehouseUseStatus; + const authStatus = relationRecord && relationRecord.auth_status !== undefined && relationRecord.auth_status !== null + ? Number(relationRecord.auth_status) + : normalizedStore.authStatus; + const resolvedStore = { + id: normalizedStore.id, + name: normalizedStore.name || String(storeRecord && storeRecord.company_name || ''), + businessLicense, + storeRemask, + warehouseUseStatus, + authStatus, + }; + + if (canUseCache && this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, resolvedStore, 600); + } + + return resolvedStore; + } catch (error) { + this.ctx.logger.warn('[NoticeService.resolveStoreInfo] load store info failed: %s', error.message); + return normalizedStore; + } + } + + /** + * 解析主体配置,优先使用入参,缺失时回查主体表。 + * @param {object} [options={}] 原始通知入参 + * @param {object} [subject={}] 主体信息 + * @return {Promise} 主体配置 + */ + async resolveSubjectConfig(options = {}, subject = {}) { + const storeModel = this.ctx.model && this.ctx.model.Store; + const deliveryOrderService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.deliveryOrder; + const normalizeSubjectConfig = value => { + if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') { + return storeModel.normalizeSubjectConfig(value); + } + + const config = this.toObject(value, {}); + return { + max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, + default_express_code: 'STO', + default_platform_code: 'TB', + ...config, + }; + }; + + const directConfig = this.toObject(subject.config || options.subjectConfig || options.subject_config, null); + if (directConfig && Object.keys(directConfig).length > 0) { + return normalizeSubjectConfig(directConfig); + } + + const subjectId = Number( + options.subjectId || options.subject_id || subject.id || options.warehouseId || options.warehouse_id || options.storeId || options.store_id || 0 + ); + if (!Number.isFinite(subjectId) || subjectId <= 0) { + return normalizeSubjectConfig(null); + } + + try { + if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') { + return normalizeSubjectConfig(null); + } + + const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(subjectId); + const nestedSubjectConfig = this.toObject(subjectConfig && subjectConfig.subject_config, null); + const resolvedSubjectConfig = nestedSubjectConfig && Object.keys(nestedSubjectConfig).length > 0 + ? nestedSubjectConfig + : subjectConfig; + return normalizeSubjectConfig(resolvedSubjectConfig); + } catch (error) { + this.ctx.logger.warn('[NoticeService.resolveSubjectConfig] load subject_config failed: %s', error.message); + return normalizeSubjectConfig(null); + } + } + + /** + * 将业务入参整理为统一通知 payload。 + * @param {object} [options={}] 发送入参 + * @return {Promise} 标准化后的 payload + */ + async normalizePayload(options = {}) { + const subject = this.toObject(options.subject, {}); + const messageType = this.normalizeMessageType( + options.messageType || options.msgType || options.message_type || options.type + ); + const businessName = String( + options.businessName || options.business || options.bussinessType || options.business_type || '' + ).trim(); + + if (!businessName) { + throw new Error('businessName / bussinessType 不能为空'); + } + + const warehouseId = Number( + options.warehouseId || options.warehouse_id || subject.warehouseId || (String(subject.type || options.subjectType || '').trim().toLowerCase() === 'warehouse' ? subject.id : 0) || 0 + ); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId / warehouse_id 不能为空'); + } + + const subjectId = Number( + options.subjectId || options.subject_id || subject.id || warehouseId + ); + if (!Number.isFinite(subjectId) || subjectId <= 0) { + throw new Error('subject.id / subjectId / warehouseId / warehouse_id 不能为空'); + } + + const contentSource = options.content !== undefined + ? options.content + : (options.message !== undefined ? options.message : (options.messageBody !== undefined ? options.messageBody : options.body)); + const content = typeof contentSource === 'string' + ? contentSource + : (contentSource == null ? '' : JSON.stringify(contentSource)); + + const url = String( + options.url || options.fileUrl || options.file_url || options.imageUrl || options.image_url || '' + ).trim(); + + if ([ 'image', 'file' ].includes(messageType) && !url) { + throw new Error('图片/文件消息必须提供 url'); + } + + const event = String(options.event || options.eventName || `${businessName}_${messageType}`).trim(); + this.assertEventRegistered(event); + const title = String(options.title || options.summary || businessName).trim() || businessName; + const resolvedSubject = { + ...subject, + id: subjectId, + }; + const [ subjectConfig, storeInfo ] = await Promise.all([ + this.resolveSubjectConfig(options, resolvedSubject), + this.resolveStoreInfo(options, resolvedSubject), + ]); + + return { + traceId: String(options.traceId || this.buildTraceId()), + hookType: String(options.hookType || options.webhookType || '').trim(), + event, + businessName, + warehouseId, + storeId: storeInfo && storeInfo.id ? Number(storeInfo.id) : null, + businessId: options.businessId || options.bussinessId || null, + occurredAt: options.occurredAt || new Date().toISOString(), + sender: this.toObject(options.sender || options.operator, {}), + receivers: Array.isArray(options.receivers) ? options.receivers : [], + subject: { + id: subjectId, + type: String(subject.type || options.subjectType || 'store'), + name: String(subject.name || options.subjectName || options.store_name || ''), + code: String(subject.code || options.subjectCode || ''), + config: subjectConfig, + }, + store: storeInfo, + message: { + type: messageType, + title, + content, + url, + fileName: String(options.fileName || options.filename || ''), + mimeType: String(options.mimeType || options.contentType || ''), + body: contentSource, + }, + storeContent: String(options.storeContent || options.store_content || '').trim(), + metadata: this.toObject(options.metadata, {}), + raw: options, + }; + } + + /** + * 构建实际对外发送的统一消息体。 + * @param {object} webhook webhook 配置 + * @param {object} payload 标准化后的消息载荷 + * @return {object} 对外发送载荷 + */ + buildOutgoingPayload(webhook, payload) { + return { + traceId: payload.traceId, + event: payload.event, + businessName: payload.businessName, + businessId: payload.businessId, + occurredAt: payload.occurredAt, + subject: payload.subject, + store: payload.store, + sender: payload.sender, + receivers: payload.receivers, + message: payload.message, + metadata: payload.metadata, + }; + } + + /** + * 获取当前主体允许发送的 webhook 数量上限。 + * @param {object} [payload={}] 标准化后的消息载荷 + * @return {number} 上限数量 + */ + getWebhookLimit(payload = {}) { + const rawLimit = payload && payload.subject && payload.subject.config + ? payload.subject.config.max_notice_webhook_count + : DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; + const normalizedLimit = Number(rawLimit); + + if (!Number.isInteger(normalizedLimit) || normalizedLimit < 0) { + return DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; + } + + return Math.min(normalizedLimit, DEFAULT_MAX_NOTICE_WEBHOOK_COUNT); + } + + /** + * 筛选本次需要触达的 webhook(仅支持调用方显式传入的 hooks,不再读取 wms_notification_webhook 表)。 + * @param {object} payload 标准化后的消息载荷 + * @return {Promise} webhook 列表 + */ + async findMatchedWebhooks(payload) { + const webhookLimit = this.getWebhookLimit(payload); + if (webhookLimit <= 0) { + return []; + } + + if (Array.isArray(payload.raw.hooks)) { + return payload.raw.hooks + .filter(item => this.matchesEvents(item && item.events, payload)) + .slice(0, webhookLimit); + } + + return []; + } + + /** + * 获取事件对应的固定群订阅配置。 + * @param {string} event 事件编码 + * @return {Array|null} 固定订阅目标数组,未配置返回 null + */ + getFixedGroupTargets(event) { + const normalizedEvent = String(event || '').trim().toLowerCase(); + return FIXED_GROUP_SUBSCRIPTIONS[normalizedEvent] || null; + } + + /** + * 根据固定订阅配置查询本次事件需要触达的群。 + * @param {object} payload 标准化后的消息载荷 + * @param {Array|null} [targetsOverride] 可选,覆盖固定订阅目标(降级查找用) + * @return {Promise} 目标群列表 + */ + async findSubscribedGroups(payload, targetsOverride = null) { + const targets = targetsOverride || this.getFixedGroupTargets(payload.event); + if (!targets || targets.length === 0) { + return []; + } + + const groupModel = this.ctx.model && this.ctx.model.InboxGroup; + if (!groupModel || typeof groupModel.findAll !== 'function') { + this.ctx.logger.warn('[NoticeService.findSubscribedGroups] InboxGroup 模型不可用'); + return []; + } + + const warehouseId = Number(payload.warehouseId || 0); + const storeId = Number(payload.storeId || 0); + const { Op } = this.app.Sequelize; + + const conditions = []; + for (const target of targets) { + const groupType = String(target && target.groupType || '').trim().toLowerCase(); + const subType = String(target && target.subType || '').trim(); + if (!groupType) { + continue; + } + // 货主群必须定位到货主,无 store_id 时跳过 + if (groupType === 'store' && (!Number.isFinite(storeId) || storeId <= 0)) { + continue; + } + + const condition = { group_type: groupType, is_blocked: 0 }; + if (subType) { + condition.sub_type = subType; + } + if (groupType === 'store') { + condition.store_id = storeId; + } + conditions.push(condition); + } + + if (conditions.length === 0) { + return []; + } + + try { + const rows = await groupModel.findAll({ + where: { + warehouse_id: warehouseId, + [Op.or]: conditions, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return (Array.isArray(rows) ? rows : []) + .filter(row => row && row.group_id) + .map(row => ({ + group_id: row.group_id, + group_name: row.group_name || '', + group_type: row.group_type || '', + sub_type: row.sub_type || '', + ext_data: row.ext_data || null, + })); + } catch (error) { + this.ctx.logger.warn(`[NoticeService.findSubscribedGroups] 查询订阅群失败: ${error.message}`); + return []; + } + } + + /** + * 解析降级通知中的货主名称:优先取合约表(wms_store_warehouse)货主备注 storeRemask, + * 其次货主名称,均缺失时按 storeId 回查合约表/货主表,查不到再回退「货主{storeId}」/「货主」。 + * @param {object} payload 标准化后的消息载荷 + * @return {Promise} 货主名称 + */ + async resolveStoreLabelInternal(payload) { + const storeRemask = String((payload.store && payload.store.storeRemask) || '').trim(); + const directName = storeRemask || String((payload.store && payload.store.name) || '').trim(); + if (directName) { + return directName; + } + + const storeId = Number(payload.storeId || 0); + if (!Number.isFinite(storeId) || storeId <= 0) { + return '货主'; + } + + const warehouseId = Number(payload.warehouseId || 0); + const storeModel = this.ctx.model && this.ctx.model.Store; + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + + try { + const [ storeRecord, relationRecord ] = await Promise.all([ + storeModel && typeof storeModel.findByPk === 'function' + ? storeModel.findByPk(storeId, { + attributes: [ 'id', 'company_name' ], + }) + : null, + Number.isFinite(warehouseId) && warehouseId > 0 && storeWarehouseModel && typeof storeWarehouseModel.findOne === 'function' + ? storeWarehouseModel.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + }, + attributes: [ 'store_remask' ], + }) + : null, + ]); + + const contractRemask = String(relationRecord && relationRecord.store_remask || '').trim(); + const companyName = String(storeRecord && storeRecord.company_name || '').trim(); + if (contractRemask) { + return contractRemask; + } + if (companyName) { + return companyName; + } + } catch (error) { + this.ctx.logger.warn('[NoticeService.resolveStoreLabelInternal] load store name failed: %s', error.message); + } + + return `货主${storeId}`; + } + + /** + * 走仓库接口消息推送通道(不依赖 wms_notification_webhook 配置)。 + * 按固定群订阅把通知推送到货主/仓库群,由外部适配器投递。 + * @param {object} payload 标准化后的消息载荷 + * @return {Promise} 发送汇总结果 + */ + async sendToWarehouseChannel(payload) { + const { ctx } = this; + const warehouseNotifyService = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify; + + if (!warehouseNotifyService || typeof warehouseNotifyService.pushSystemMessage !== 'function') { + ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 仓库接口推送服务不可用', { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + }); + + return { + success: false, + message: '仓库接口推送服务不可用', + data: { + traceId: payload.traceId, + event: payload.event, + matchedGroupCount: 0, + sentCount: 0, + failedCount: 0, + results: [], + }, + }; + } + + // 货主目标群未配置时,降级发送到仓库异常群,内容前缀标记失败 + const fixedTargets = this.getFixedGroupTargets(payload.event) || []; + const hasStoreTarget = fixedTargets.some( + target => String(target && target.groupType || '').trim().toLowerCase() === 'store' + ); + + // 合约已停用(warehouse_use_status=0)或已解除/拒绝/过期(auth_status≠2)的货主: + // 不推货主群,也不降级到异常群(该货主本就不应被通知) + const storeInfo = payload.store || {}; + const warehouseUseStatus = storeInfo.warehouseUseStatus === undefined || storeInfo.warehouseUseStatus === null + ? null + : Number(storeInfo.warehouseUseStatus); + const authStatus = storeInfo.authStatus === undefined || storeInfo.authStatus === null + ? null + : Number(storeInfo.authStatus); + const storeContractInactive = warehouseUseStatus === 0 || (authStatus !== null && authStatus !== 2); + + // 主目标查询(store 目标的 fallbackTargets 不参与主查询,避免主目标命中时 fallback 群也被推送) + const primaryTargets = fixedTargets + .map(target => ({ + groupType: String(target && target.groupType || '').trim().toLowerCase(), + subType: String(target && target.subType || '').trim(), + })) + .filter(target => target.groupType); + const groups = await this.findSubscribedGroups(payload, primaryTargets); + + const effectiveGroups = storeContractInactive + ? groups.filter(group => group && group.group_type !== 'store') + : groups; + + // store 目标回退链:主目标(如 store:receiving)未命中时,按 fallbackTargets 顺序逐级尝试(如 store:after_sales) + const storeChains = fixedTargets.filter( + target => String(target && target.groupType || '').trim().toLowerCase() === 'store' + ); + const extraStoreGroups = []; + let storeChainMatchedCount = 0; + + if (!storeContractInactive) { + for (const chain of storeChains) { + const chainSubType = String(chain.subType || '').trim(); + const primaryMatched = effectiveGroups.some( + group => group && group.group_type === 'store' && (!chainSubType || String(group.sub_type || '').trim() === chainSubType) + ); + if (primaryMatched) { + storeChainMatchedCount += 1; + continue; + } + + const fallbackTargets = Array.isArray(chain.fallbackTargets) ? chain.fallbackTargets : []; + let chainMatched = false; + for (const fallbackTarget of fallbackTargets) { + const fallbackGroups = await this.findSubscribedGroups(payload, [ fallbackTarget ]); + if (fallbackGroups.length > 0) { + for (const fallbackGroup of fallbackGroups) { + extraStoreGroups.push(fallbackGroup); + } + chainMatched = true; + break; + } + } + if (chainMatched) { + storeChainMatchedCount += 1; + } + } + } + + const mergedGroups = [ ...effectiveGroups, ...extraStoreGroups ]; + const effectiveGroupsFinal = mergedGroups.filter( + (group, index) => mergedGroups.findIndex(item => item.group_id === group.group_id) === index + ); + const storeGroupMatched = storeChains.length === 0 || storeChainMatchedCount >= storeChains.length; + let fallbackGroups = []; + let storeLabel = '货主'; + + if (hasStoreTarget && !storeGroupMatched && !storeContractInactive) { + storeLabel = await this.resolveStoreLabelInternal(payload); + const exceptionGroups = await this.findSubscribedGroups(payload, [ + { groupType: 'warehouse', subType: 'exception' }, + ]); + const matchedGroupIds = new Set(effectiveGroupsFinal.map(group => group.group_id)); + fallbackGroups = exceptionGroups.filter(group => !matchedGroupIds.has(group.group_id)); + + if (fallbackGroups.length > 0) { + ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 货主群未配置,降级发送到仓库异常群', { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + storeLabel, + fallbackGroupCount: fallbackGroups.length, + }); + } + } + + const pushGroups = [ ...effectiveGroupsFinal, ...fallbackGroups ]; + if (pushGroups.length === 0) { + ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 未匹配到订阅群', { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + }); + + return { + success: true, + message: '未匹配到订阅群', + data: { + traceId: payload.traceId, + event: payload.event, + matchedGroupCount: 0, + sentCount: 0, + failedCount: 0, + results: [], + }, + }; + } + + const fallbackGroupIds = new Set(fallbackGroups.map(group => group.group_id)); + const message = payload.message || {}; + const fileUrl = String(message.url || '').trim(); + const tasks = pushGroups.map(group => { + // 货主群使用货主侧文案(货主端地址/路径),仓库群使用仓库侧文案 + const baseContent = group.group_type === 'store' && payload.storeContent + ? payload.storeContent + : (message.content || ''); + // 文件/图片类通知把资源链接以文本拼回 content,保持"接收方只处理 content"的协议 + const fileLine = fileUrl + ? `\n明细文件:${String(message.fileName || '').trim() ? `${String(message.fileName).trim()} ` : ''}${fileUrl}` + : ''; + // 货主群未配置降级到异常群时,内容前缀标记失败 + const failPrefix = fallbackGroupIds.has(group.group_id) + ? `通知货主【${storeLabel}】失败\n` + : ''; + + return warehouseNotifyService.pushSystemMessage({ + warehouseId: payload.warehouseId, + // 仅货主群关联货主,仓库群不标记 store_id(避免仓库群消息被误标货主) + storeId: group.group_type === 'store' ? payload.storeId : null, + group, + content: `${failPrefix}${baseContent}${fileLine}`.trim(), + // ext_id 幂等键需含事件维度:同一业务单在不同事件(创建/完成/审核)应各落一条消息,避免被幂等复用吞掉 + extId: payload.businessId ? `${payload.businessId}:${payload.event}` : payload.traceId, + extData: group.ext_data || null, + }); + }); + const results = await Promise.all(tasks); + const sentCount = results.filter(item => item && item.success).length; + const failedCount = results.length - sentCount; + + const summary = { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + matchedGroupCount: pushGroups.length, + sentCount, + failedCount, + }; + + if (failedCount > 0) { + ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 群推送存在失败', summary); + } else { + ctx.logger.info('[NoticeService.sendToWarehouseChannel] 群推送完成', summary); + } + + return { + success: failedCount === 0, + message: failedCount === 0 ? '通知已推送' : `部分群推送失败(${failedCount})`, + data: { + traceId: payload.traceId, + event: payload.event, + matchedGroupCount: pushGroups.length, + sentCount, + failedCount, + results, + }, + }; + } + + /** + * 统一通知发送入口:按 channel 路由分发。 + * channel=warehouse|group(默认):走仓库接口消息推送(wms_api_app 配置 + 固定群订阅); + * channel=webhook:仅使用调用方显式传入的 hooks(不再读取 wms_notification_webhook 表); + * channel=both:双通道同时发送。 + * @param {object} [options={}] 发送入参 + * @return {Promise} 发送汇总结果 + */ + async send(options = {}) { + const payload = await this.normalizePayload(options); + const channel = String(options.channel || 'warehouse').trim().toLowerCase(); + + if (channel === 'warehouse' || channel === 'group') { + return await this.sendToWarehouseChannel(payload); + } + + if (channel === 'both') { + const [ webhookResult, warehouseResult ] = await Promise.all([ + this.sendViaWebhooks(payload), + this.sendToWarehouseChannel(payload), + ]); + + const webhookData = (webhookResult && webhookResult.data) || {}; + const warehouseData = (warehouseResult && warehouseResult.data) || {}; + const sentCount = Number(webhookData.sentCount || 0) + Number(warehouseData.sentCount || 0); + const failedCount = Number(webhookData.failedCount || 0) + Number(warehouseData.failedCount || 0); + const results = [ + ...(Array.isArray(webhookData.results) ? webhookData.results : []), + ...(Array.isArray(warehouseData.results) ? warehouseData.results : []), + ]; + + return { + success: webhookResult.success && warehouseResult.success, + message: `双通道发送完成(webhook ${webhookData.sentCount}/${webhookData.matchedHookCount || 0},群 ${warehouseData.sentCount}/${warehouseData.matchedGroupCount || 0})`, + data: { + traceId: payload.traceId, + event: payload.event, + matchedHookCount: Number(webhookData.matchedHookCount || 0), + matchedGroupCount: Number(warehouseData.matchedGroupCount || 0), + sentCount, + failedCount, + results, + }, + }; + } + + return await this.sendViaWebhooks(payload); + } + + /** + * 通过调用方显式传入的 hooks 分发(不读取 wms_notification_webhook 表)。 + * @param {object} payload 标准化后的消息载荷 + * @return {Promise} 发送汇总结果 + */ + async sendViaWebhooks(payload) { + const webhooks = await this.findMatchedWebhooks(payload); + + if (webhooks.length === 0) { + this.ctx.logger.warn('[NoticeService.send] 未匹配到可用 webhook', { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + messageType: payload.message && payload.message.type, + }); + + return { + success: true, + message: '未匹配到可用 webhook', + data: { + traceId: payload.traceId, + event: payload.event, + matchedHookCount: 0, + sentCount: 0, + failedCount: 0, + results: [], + }, + }; + } + + const tasks = webhooks.map(async hook => await this.sendWithRetry({ hook, payload })); + const results = await Promise.all(tasks); + const sentCount = results.filter(item => item && item.success).length; + const failedCount = results.length - sentCount; + + const summary = { + traceId: payload.traceId, + event: payload.event, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + matchedHookCount: webhooks.length, + sentCount, + failedCount, + messageType: payload.message && payload.message.type, + }; + + if (failedCount > 0) { + this.ctx.logger.warn('[NoticeService.send] webhook 发送存在失败', summary); + } else { + this.ctx.logger.info('[NoticeService.send] webhook 发送完成', summary); + } + + return { + success: failedCount === 0, + message: failedCount === 0 ? '通知已发送' : `部分 webhook 发送失败(${failedCount})`, + data: { + traceId: payload.traceId, + event: payload.event, + matchedHookCount: webhooks.length, + sentCount, + failedCount, + results, + }, + }; + } +} + +module.exports = NoticeService; diff --git a/app/service/systems/notification.js b/app/service/systems/notification.js deleted file mode 100644 index 62287a3..0000000 --- a/app/service/systems/notification.js +++ /dev/null @@ -1,49 +0,0 @@ -const { Service } = require('egg'); - -class NotificationService extends Service { - constructor(ctx) { - super(ctx); - // 设置全局变量 oldAction - this.oldreceivingUrl = 'http://ye4s.wms.gztbyc.com/index/wms/wms/receiving_notic'; - - } - - /** - * 发送通知 - * @param {Object} options - 通知参数 - * @param {string} options.type - 通知类型,如 'email', 'sms', 'system' - * @param {string} options.title - 通知标题 - * @param {string} options.content - 通知内容 - * @param {string} options.bussinessType - 业务类型,如 'receiving' - * @param {string[]} [options.receivers] - 接收人列表 - * @param {string} options.bussinessId - 业务ID - * @return {Promise} 发送结果 - */ - async send(options) { - const { type, title, content, bussinessType, bussinessId, receivers = [] } = options; - switch (bussinessType) { - case 'receiving': - // 发送接收通知 - await this.ctx.curl(this.oldreceivingUrl, { - method: 'POST', - data: { - id: bussinessId, - }, - dataType: 'json', - }); - break; - } - return { - success: true, - message: '通知已发送', - data: { - type, - title, - content, - receivers, - }, - }; - } -} - -module.exports = NotificationService; diff --git a/app/service/systems/operation_log.js b/app/service/systems/operation_log.js index 976adf0..089ffe6 100644 --- a/app/service/systems/operation_log.js +++ b/app/service/systems/operation_log.js @@ -1,9 +1,109 @@ -// app/service/operationLog.js +// app/service/systems/operation_log.js 'use strict'; const Service = require('egg').Service; +const OPERATION_LOG_ATTRIBUTES = [ + 'id', + 'operation_code', + 'operator_name', + 'created_at', + 'external_log_type', + 'external_log_id', + 'platform_code', + 'message', +]; + class operationLogService extends Service { + /** + * 将单条日志参数转换为数据库字段。 + * @param {Object} params 日志参数。 + * @param {string} params.businessType 业务类型。 + * @param {string|number} params.businessId 业务ID。 + * @param {string} params.operationCode 操作编码。 + * @param {Object} [params.operator={}] 操作人信息。 + * @param {string} [params.changeSummary=''] 变更描述(extras.message 缺省时作为日志说明落库)。 + * @param {Object} [params.extras={}] 扩展字段。 + * @param {Object|null} [params.beforeChanges=null] 操作前快照。 + * @return {Object} 可直接落库的日志数据。 + */ + buildOperationLogData(params = {}) { + const { ctx } = this; + const { + businessType, + businessId, + operationCode, + operator = {}, + beforeChanges = null, + changeSummary = '', + extras = {}, + } = params; + + return { + business_type: businessType, + business_id: String(businessId), + operation_code: operationCode, + // 使用 nullish 合并符,确保当 operator.id 为 0 时仍然保留 0 + operator_id: operator?.id ?? null, + operator_name: operator?.name ?? null, + external_log_type: extras.externalLogType || 'NONE', + external_log_id: extras.externalLogId ?? null, + warehouse_id: extras.warehouseId ?? null, + before_changes: beforeChanges, + platform_code: ctx.user?.platform_code || 'SYSTEM', + // 日志说明:优先 extras.message;调用方只传 changeSummary 时回退使用,避免前端"操作说明"为空 + message: extras.message || changeSummary || null, + }; + } + + /** + * 规范并校验日志查询入参,强制要求业务ID与仓库ID。 + * @param {Object} query 查询参数。 + * @param {string} businessType 业务类型。 + * @return {{ where: Object, id: string|number, warehouseId: string|number }} 查询条件。 + */ + buildBusinessLogWhere(query = {}, businessType) { + const requestQuery = query && typeof query === 'object' ? query : {}; + const { + id, + warehouseId, + } = requestQuery; + + if (!id) { + throw new Error('id不能为空'); + } + + if (!warehouseId) { + throw new Error('仓库id不能为空'); + } + + return { + where: { + business_type: businessType, + business_id: id, + warehouse_id: warehouseId, + }, + id, + warehouseId, + }; + } + + /** + * 将日志模型结果格式化为接口输出结构。 + * @param {Object[]} rows 日志行数据。 + * @return {Object[]} 格式化后的日志列表。 + */ + formatOperationLogRows(rows = []) { + const { app } = this; + return rows.map(item => { + const itemTmp = JSON.parse(JSON.stringify(item)); + itemTmp.operation_name = app.getOperationCodeName(item.operation_code); + itemTmp.platform_name = app.getPlatformName(item.platform_code); + itemTmp.created_at = app.formatDate(itemTmp.created_at); + return itemTmp; + }); + } + /** * 通用操作日志记录方法 * @param {Object} params 日志参数 @@ -20,32 +120,26 @@ class operationLogService extends Service { * @param {string} params.extras.externalLogType 外部日志类型 * @param {number} params.extras.externalLogId 外部日志ID * @param {number} params.extras.warehouseId 仓库ID + * @param {string} params.extras.message 日志信息 + * @param {Object} [params.transaction] 事务对象(可选) + * */ - async createOperationLog(params) { + async createOperationLog(params = {}) { const { ctx } = this; const { businessType, businessId, - operationCode, - operator = {}, - beforeChanges = null, - extras = {}, + transaction, } = params; try { - const logData = { - business_type: businessType, - business_id: String(businessId), - operation_code: operationCode, - operator_id: operator?.id || null, - operator_name: operator?.name || null, - external_log_type: extras.externalLogType || 'NONE', - external_log_id: extras.externalLogId || null, - warehouse_id: extras.warehouseId || null, - before_changes: beforeChanges, - platform_code: ctx.user?.platform_code || 'SYSTEM', - }; + const logData = this.buildOperationLogData(params); - const result = await ctx.model.OperationLog.create(logData); + const createOptions = {}; + if (transaction) { + createOptions.transaction = transaction; + } + + const result = await ctx.model.OperationLog.create(logData, createOptions); ctx.logger.info(`[OperationLog] 记录操作日志成功,ID: ${result.id}, Business: ${businessType}/${businessId}`); return result; } catch (error) { @@ -55,72 +149,202 @@ class operationLogService extends Service { } } - async queryStockLogs(query) { + /** + * 批量写入操作日志,优先使用 bulkCreate,失败时自动降级单条写入。 + * @param {Array} paramsList 日志参数数组。 + * @param {Object} [options={}] 写入选项。 + * @param {Object} [options.transaction] 事务对象(可选)。 + * @return {Promise>} 写入结果数组。 + */ + async createOperationLogs(paramsList = [], options = {}) { + const { ctx } = this; + const requestOptions = options && typeof options === 'object' ? options : {}; + const transaction = requestOptions.transaction; + const normalizedParamsList = Array.isArray(paramsList) ? paramsList.filter(Boolean) : []; + + if (normalizedParamsList.length === 0) { + return []; + } + + const operationLogModel = ctx.model && ctx.model.OperationLog; + if (!operationLogModel || typeof operationLogModel.bulkCreate !== 'function') { + ctx.logger.warn('[OperationLog] OperationLog.bulkCreate 不可用,降级单条写入'); + return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({ + ...item, + transaction: item && item.transaction ? item.transaction : transaction, + }))); + } try { - const { ctx, app } = this; - const { - id, - warehouseId, - page = 1, - pageSize = 20, - } = query; - const where = {}; - where.business_type = 'stock'; - if (!id) { - throw new Error('id不能为空'); - } else { - where.business_id = id; + const rows = normalizedParamsList.map(item => this.buildOperationLogData(item)); + const bulkCreateOptions = {}; + if (transaction) { + bulkCreateOptions.transaction = transaction; } - if (!warehouseId) { - throw new Error('仓库id不能为空'); - } else { - where.warehouse_id = warehouseId; - } - - const offset = (page - 1) * pageSize; - - const result = await ctx.model.OperationLog.findAndCountAll({ - where, - order: [[ 'created_at', 'DESC' ]], - offset, - attributes: [ 'id', 'operation_code', 'operator_name', 'created_at', 'external_log_type', 'external_log_id', 'platform_code' ], - limit: pageSize, - }); - - return { - list: result.rows.map(item => { - const item_tmp = JSON.parse(JSON.stringify(item)); - item_tmp.operation_name = app.getOperationCodeName(item.operation_code); - item_tmp.platform_name = app.getPlatformName(item.platform_code); - item_tmp.created_at = new Date(item_tmp.created_at).format(); - return item_tmp; - }), - pagination: { - page, - pageSize, - total: result.count, - totalPages: Math.ceil(result.count / pageSize), - }, - }; - } catch (e) { - console.log(e); - throw e; + return await operationLogModel.bulkCreate(rows, bulkCreateOptions); + } catch (error) { + ctx.logger.error(`[OperationLog] 批量记录操作日志失败,降级单条写入: ${error.message}`, error); + return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({ + ...item, + transaction: item && item.transaction ? item.transaction : transaction, + }))); } } - async queryOrderLogs() { + /** + * 按业务类型查询操作日志分页数据。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 业务ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {number} [query.page=1] 页码。 + * @param {number} [query.pageSize=20] 每页数量。 + * @param {string} businessType 业务类型。 + * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 + */ + async queryLogsByBusinessType(query = {}, businessType) { + const { ctx } = this; + const requestQuery = query && typeof query === 'object' ? query : {}; + const { + page = 1, + pageSize = 20, + } = requestQuery; + const { where } = this.buildBusinessLogWhere(requestQuery, businessType); + + const currentPage = Number.parseInt(page, 10) || 1; + const currentPageSize = Number.parseInt(pageSize, 10) || 20; + const offset = (currentPage - 1) * currentPageSize; + + const result = await ctx.model.OperationLog.findAndCountAll({ + where, + order: [[ 'created_at', 'DESC' ]], + offset, + attributes: OPERATION_LOG_ATTRIBUTES, + limit: currentPageSize, + }); + + const rows = Array.isArray(result.rows) ? result.rows : []; + + return { + list: this.formatOperationLogRows(rows), + pagination: { + page: currentPage, + pageSize: currentPageSize, + total: result.count, + totalPages: Math.ceil(result.count / currentPageSize), + }, + }; } + + /** + * 查询库存操作日志。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 库存业务ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {number} [query.page=1] 页码。 + * @param {number} [query.pageSize=20] 每页数量。 + * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 + */ + async queryStockLogs(query = {}) { + return await this.queryLogsByBusinessType(query, 'stock'); + } + + /** + * 查询订单操作日志。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 订单ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {number} [query.page=1] 页码。 + * @param {number} [query.pageSize=20] 每页数量。 + * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 + */ + async queryOrderLogs(query = {}) { + return await this.queryLogsByBusinessType(query, 'order'); + } + + /** + * 查询订单操作日志(不分页,返回全部)。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 订单ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @return {Promise} 日志列表。 + */ + async queryAllOrderLogs(query = {}) { + return await this.queryAllLogsByBusinessType(query, 'order'); + } + + /** + * 按业务类型查询日志全量数据(不分页)。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 业务ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {string} businessType 业务类型。 + * @return {Promise} 日志列表。 + */ + async queryAllLogsByBusinessType(query = {}, businessType) { + const { ctx } = this; + const requestQuery = query && typeof query === 'object' ? query : {}; + const { where } = this.buildBusinessLogWhere(requestQuery, businessType); + + const rows = await ctx.model.OperationLog.findAll({ + where, + order: [[ 'created_at', 'DESC' ]], + attributes: OPERATION_LOG_ATTRIBUTES, + raw: true, + }); + + const normalizedRows = Array.isArray(rows) ? rows : []; + return this.formatOperationLogRows(normalizedRows); + } + + /** + * 查询收货单操作日志。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 收货单ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {number} [query.page=1] 页码。 + * @param {number} [query.pageSize=20] 每页数量。 + * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 + */ + async queryReceivingLogs(query = {}) { + return await this.queryLogsByBusinessType(query, 'receiving'); + } + + /** + * 查询入库单操作日志。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 入库单ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {number} [query.page=1] 页码。 + * @param {number} [query.pageSize=20] 每页数量。 + * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 + */ + async queryEntryOrderLogs(query = {}) { + return await this.queryLogsByBusinessType(query, 'entry_order'); + } + + /** + * 查询出库单操作日志。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 出库单ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {number} [query.page=1] 页码。 + * @param {number} [query.pageSize=20] 每页数量。 + * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 + */ + async queryStockoutLogs(query = {}) { + return await this.queryLogsByBusinessType(query, 'stockout'); + } + async getMessageDetail(data) { const { id, type } = data; const { ctx } = this; - const warehouseId = ctx.user.store_id; let LogModel = null; switch (type) { case 'QIMEN': - // code LogModel = ctx.model.QimenLog; break; + default: + throw new Error(`不支持的日志类型: ${type}`); } const result = await LogModel.findOne({ where: { id } }); return result; diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js new file mode 100644 index 0000000..6d462f5 --- /dev/null +++ b/app/service/systems/order_async.js @@ -0,0 +1,3036 @@ +'use strict'; + +const MainService = require('../main'); + +const CREATE_CHANNEL_QM = 'QM'; +const CREATE_CHANNEL_MANUAL = 'MANUAL'; +const CREATE_CHANNEL_API = 'API'; +const CREATE_CHANNEL_STOCKOUT = 'STOCKOUT'; +const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]); +const TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS = 3; +const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50; +const DISPATCH_BATCH_SIZE = 20; +const SYNC_ORDER_IDS_PROGRESS_CACHE_TTL = 7200; +/** SN 状态中代表「已随订单发出」的集合(复核提交后写入 VERIFIED),回传平台时只带这些 SN */ +const SHIPPED_SN_STATUS_LIST = [ 'VERIFIED', 'REISSUED' ]; + +// 订单同步通知合并去抖:最后一次同步后等待 3 分钟无新同步,再统一推送一条消息 +const ORDER_SYNC_NOTICE_DEBOUNCE_MS = 3 * 60 * 1000; +const ORDER_SYNC_NOTICE_RETRY_MS = 2 * 60 * 1000; +const ORDER_SYNC_NOTICE_MAX_RETRIES = 5; +const ORDER_SYNC_NOTICE_KEY_PREFIX = 'order_sync_notice'; +const ORDER_SYNC_NOTICE_FLUSH_BATCH_SIZE = 50; +const ORDER_SYNC_NOTICE_MAX_ORDER_LINES = 30; +const ORDER_SYNC_NOTICE_LIST_TTL_SECONDS = 24 * 60 * 60; +const ORDER_SYNC_NOTICE_LOCK_TTL_SECONDS = 120; + +function getSyncOrderIdsProgressCacheKey(requestId) { + if (!requestId) return null; + return `order:pending:sync_order_ids:request:${String(requestId).trim()}`; +} + +async function updateDispatchBatchProgress(service, cacheKey, batchSize) { + if (!cacheKey || !service || !service.app) return; + try { + const cached = await service.app.getCacheAsync(cacheKey); + if (cached && typeof cached === 'object') { + const total = Number(cached.total_count || 0); + const processed = Number(cached.processed_count || 0) + Number(batchSize || 0); + await service.app.setCacheAsync(cacheKey, { + ...cached, + processed_count: processed, + progress: total > 0 ? Math.min(100, Math.round(processed / total * 100)) : 0, + update_time: Date.now(), + }, SYNC_ORDER_IDS_PROGRESS_CACHE_TTL); + } + } catch (err) { + // 进度更新失败不影响主流程 + } +} + +function normalizeDatabaseErrorCodeInternal(error) { + const code = error && (error.code + || (error.parent && error.parent.code) + || error.errno + || (error.parent && error.parent.errno) + || null); + + return typeof code === 'number' ? code : String(code || '').trim() || null; +} + +function isRetryableTransactionLockErrorInternal(error) { + const code = normalizeDatabaseErrorCodeInternal(error); + const message = String((error && error.message) || (error && error.parent && error.parent.message) || '').toLowerCase(); + + return RETRYABLE_DATABASE_ERROR_CODES.has(code) + || message.includes('deadlock found when trying to get lock') + || message.includes('lock wait timeout'); +} + +async function runTransactionWithLockRetryInternal(service, tag, callback, attempt = 1) { + try { + return await service.ctx.model.transaction(async transaction => { + return await callback(transaction); + }); + } catch (error) { + const retryable = isRetryableTransactionLockErrorInternal(error); + if (!retryable || attempt >= TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS) { + throw error; + } + + const code = normalizeDatabaseErrorCodeInternal(error) || 'UNKNOWN'; + const message = String((error && error.message) || (error && error.parent && error.parent.message) || '').trim(); + service.ctx.logger.warn(`[OrderAsyncService.${tag}] transaction lock retry attempt=${attempt} maxAttempts=${TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS} code=${code} message=${message}`); + await new Promise(resolve => setTimeout(resolve, TRANSACTION_LOCK_RETRY_BASE_DELAY_MS * attempt)); + return await runTransactionWithLockRetryInternal(service, tag, callback, attempt + 1); + } +} + +function normalizeQimenResponseInternal(xmlArray) { + if (!xmlArray || typeof xmlArray !== 'object') { + return {}; + } + + const response = xmlArray.response || xmlArray; + if (Array.isArray(response)) { + return response[0] && typeof response[0] === 'object' ? response[0] : {}; + } + + return response && typeof response === 'object' ? response : {}; +} + +function resolveQimenSyncItemQuantityInternal(orderItem = {}) { + const actualQty = Number(orderItem.actual_qty); + if (Number.isFinite(actualQty) && actualQty > 0) { + return actualQty; + } + + const planQty = Number(orderItem.plan_qty); + if (Number.isFinite(planQty) && planQty > 0) { + return planQty; + } + + return 0; +} + +function resolveOrderWaybillCodeInternal(orderRow = {}) { + return String( + orderRow.waybill_code + || orderRow.express_code + || orderRow.invoice_no + || '' + ).trim(); +} + +function resolveOrderWaybillCodesInternal(orderRow = {}, waybillCodes = []) { + const normalizedCodes = Array.isArray(waybillCodes) + ? waybillCodes + .map(code => String(code || '').trim()) + .filter(code => !!code) + : []; + + if (normalizedCodes.length > 0) { + return normalizedCodes; + } + + const fallbackCode = resolveOrderWaybillCodeInternal(orderRow); + return fallbackCode ? [ fallbackCode ] : []; +} + +/** + * 按订单ID批量构建运单号映射。 + * + * 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID, + * 禁止仅凭订单ID跨仓串读运单号;仓库ID缺失时返回空映射。 + * + * @param {Object} service 订单异步服务实例。 + * @param {Array} orderIds 订单ID列表。 + * @param {number|string|null|undefined} warehouseId 仓库ID,必须为订单所属仓库。 + * @return {Promise>} order_id 到运单号数组的映射。 + */ +async function buildOrderWaybillCodeMapInternal(service, orderIds = [], warehouseId = null) { + const normalizedOrderIds = Array.isArray(orderIds) + ? orderIds.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) + : []; + const waybillCodeMap = new Map(); + + const orderExpressModel = service.ctx.model && service.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function' || normalizedOrderIds.length === 0) { + return waybillCodeMap; + } + + const normalizedWarehouseId = warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + ? Number(warehouseId) + : 0; + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return waybillCodeMap; + } + + const { Op } = service.app.Sequelize; + const expressRows = await orderExpressModel.findAll({ + where: { + order_id: { + [Op.in]: normalizedOrderIds, + }, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'order_id', 'business_key', 'waybill_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + for (const expressRow of Array.isArray(expressRows) ? expressRows : []) { + const orderId = Number(expressRow && expressRow.order_id); + const waybillCode = String(expressRow && expressRow.waybill_code || '').trim(); + if (!Number.isFinite(orderId) || orderId <= 0 || !waybillCode) { + continue; + } + + if (!waybillCodeMap.has(orderId)) { + waybillCodeMap.set(orderId, []); + } + + waybillCodeMap.get(orderId).push(waybillCode); + } + + return waybillCodeMap; +} + +/** + * 解析单个订单明细回传用的 snList:优先使用明细上已有的 sn_list,其次用 SN 表数据。 + * + * @param {Object} orderItem 订单明细记录。 + * @param {Map} snListMap 明细ID -> SN 列表。 + * @return {string[]} SN 列表。 + */ +function resolveOrderLineSnListInternal(orderItem = {}, snListMap = new Map()) { + if (Array.isArray(orderItem.sn_list) && orderItem.sn_list.length > 0) { + return orderItem.sn_list + .map(code => String(code || '').trim()) + .filter(code => !!code); + } + + const itemId = Number(orderItem.id ?? orderItem.order_item_id); + if (!Number.isFinite(itemId) || itemId <= 0) { + return []; + } + + return snListMap.get(itemId) || []; +} + +/** + * 奇门 deliveryorder.confirm 的 orderLine.sn 限长(见接口规范 string(50))。 + */ +const QIMEN_SN_CODE_MAX_LENGTH = 50; + +/** + * 按奇门规范拆分单行 SN:不超过长度上限的放 snList;超长的(二维码/链接型 SN)改放 orderLine.qrCode, + * 多个之间用分号拼接,并与明细自带 qr_code 合并去重。未指定上限时(如 API/JSON 渠道)全部保留在 snList。 + * + * @param {string[]} snCodes 已发出的 SN 列表。 + * @param {string} qrCode 明细自带的二维码。 + * @param {number} [maxSnCodeLength] snList 单值长度上限,缺省或非正数表示不限制。 + * @return {{ snList: string[], qrCode: string }} 奇门 orderLine 的 snList 与 qrCode。 + */ +function splitOrderLineSnCodesInternal(snCodes = [], qrCode = '', maxSnCodeLength) { + const limit = Number(maxSnCodeLength); + const hasLimit = Number.isFinite(limit) && limit > 0; + const shortCodes = []; + const longCodes = []; + + for (const code of Array.isArray(snCodes) ? snCodes : []) { + const normalizedCode = String(code || '').trim(); + if (!normalizedCode) { + continue; + } + if (!hasLimit || normalizedCode.length <= limit) { + shortCodes.push(normalizedCode); + } else { + longCodes.push(normalizedCode); + } + } + + const qrCodes = [ String(qrCode || '').trim(), ...longCodes ].filter((code, index, list) => !!code && list.indexOf(code) === index); + + return { + snList: shortCodes, + qrCode: qrCodes.join(';'), + }; +} + +/** + * 构建订单明细 -> 已发出 SN 列表映射(用于回传报文 orderLines[].snList)。 + * + * 只取已随订单发出(VERIFIED/REISSUED)的 SN,避免把退回/作废的 SN 回传平台; + * 查询失败仅告警并返回空映射,不阻断回传主流程。 + * + * @param {Object} service 订单异步服务实例。 + * @param {Object} orderRow 订单主表记录(需含 id、warehouse_id)。 + * @param {Array} orderItems 订单明细记录。 + * @return {Promise>} order_item_id 到 SN 列表的映射。 + */ +async function buildOrderItemSnListMapInternal(service, orderRow = {}, orderItems = []) { + const snListMap = new Map(); + const orderItemSnModel = service.ctx.model && service.ctx.model.OrderItemSn; + const orderId = Number(orderRow && orderRow.id); + + if (!orderItemSnModel || typeof orderItemSnModel.findAll !== 'function') { + return snListMap; + } + if (!Number.isFinite(orderId) || orderId <= 0) { + return snListMap; + } + + const itemIds = [ ...new Set((Array.isArray(orderItems) ? orderItems : []) + .map(item => Number(item && (item.id ?? item.order_item_id))) + .filter(itemId => Number.isFinite(itemId) && itemId > 0)) ]; + if (itemIds.length === 0) { + return snListMap; + } + + const { Op } = service.app.Sequelize; + const where = { + order_id: orderId, + order_item_id: { [Op.in]: itemIds }, + sn_status: { [Op.in]: SHIPPED_SN_STATUS_LIST }, + }; + const warehouseId = Number(orderRow && orderRow.warehouse_id); + if (Number.isFinite(warehouseId) && warehouseId > 0) { + where.warehouse_id = warehouseId; + } + + try { + const snRows = await orderItemSnModel.findAll({ + where, + attributes: [ 'order_item_id', 'sn_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + for (const row of Array.isArray(snRows) ? snRows : []) { + const itemId = Number(row && row.order_item_id); + const snCode = String(row && row.sn_code || '').trim(); + if (!Number.isFinite(itemId) || itemId <= 0 || !snCode) { + continue; + } + if (!snListMap.has(itemId)) { + snListMap.set(itemId, []); + } + snListMap.get(itemId).push(snCode); + } + } catch (error) { + service.ctx.logger.warn('[order_async] 读取订单SN明细失败,回传报文将不带 snList', { + orderId, + message: error && error.message, + }); + } + + return snListMap; +} + +async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, orderItems, requestContext = {}) { + const app = service.app; + const now = app.formatDate(new Date()); + const firstItemOwnerCode = Array.isArray(orderItems) + ? String((orderItems.find(item => item && String(item.owner_code || '').trim()) || {}).owner_code || '').trim() + : ''; + const appKey = String( + requestContext.appKey + || orderRow.from_key + || '' + ).trim(); + const warehouseCodeHint = String( + requestContext.qimenWarehouseCode + || requestContext.warehouseCode + || orderRow.warehouse_code + || '' + ).trim(); + const ownerCodeHint = String( + requestContext.customerId + || requestContext.qimenOwnerCode + || firstItemOwnerCode + || '' + ).trim(); + let qimenContract = null; + + if (appKey && ownerCodeHint && warehouseCodeHint && typeof service.findQimenAppWithContract === 'function') { + try { + qimenContract = await service.findQimenAppWithContract(appKey, ownerCodeHint, warehouseCodeHint); + } catch (error) { + service.ctx.logger.warn('[OrderAsyncService.buildQimenDeliveryOrderConfirmData] 读取奇门合同缓存失败', { + appKey, + customerId: ownerCodeHint, + warehouseCode: warehouseCodeHint, + message: error.message, + }); + } + } + + const ownerCode = String( + requestContext.customerId + || requestContext.qimenOwnerCode + || firstItemOwnerCode + || (qimenContract && qimenContract.qimen_customer_id) + || '' + ).trim(); + const warehouseCode = String( + requestContext.qimenWarehouseCode + || requestContext.warehouseCode + || orderRow.warehouse_code + || (qimenContract && qimenContract.qimen_warehouse_code) + || '' + ).trim(); + const packageExpressCode = String( + requestContext.packageExpressCode + || orderRow.express_code + || orderRow.waybill_code + || '' + ).trim(); + const packageExpressCodeList = resolveOrderWaybillCodesInternal(orderRow, requestContext.packageExpressCodes); + const deliveryOrderCode = String(orderRow.delivery_order_code || '').trim(); + const packageCode = String(orderRow.package_code || '').trim() || deliveryOrderCode; + const invoiceNo = String(orderRow.invoice_no || '').trim(); + const orderConfirmTime = now; + const snListMap = await buildOrderItemSnListMapInternal(service, orderRow, orderItems); + const orderLines = []; + + for (const orderItem of Array.isArray(orderItems) ? orderItems : []) { + const quantity = resolveQimenSyncItemQuantityInternal(orderItem); + if (quantity <= 0) { + continue; + } + + const snPayload = splitOrderLineSnCodesInternal( + resolveOrderLineSnListInternal(orderItem, snListMap), + orderItem.qr_code, + requestContext.snCodeMaxLength + ); + + orderLines.push({ + orderLineNo: String(orderItem.order_line_no || '').trim() || orderLines.length + 1, + orderSourceCode: String(orderItem.source_order_code || '').trim(), + subSourceCode: String(orderItem.sub_source_order_code || '').trim(), + ownerCode: String(orderItem.owner_code || ownerCode || '').trim(), + itemCode: String(orderItem.item_code || '').trim(), + itemId: Number(orderItem.item_id) || orderItem.item_id, + itemName: String(orderItem.item_name || '').trim(), + extCode: String(orderItem.ext_code || '').trim(), + planQty: Number(orderItem.plan_qty) || 0, + actualQty: quantity, + retailPrice: Number(orderItem.retail_price) || 0, + actualPrice: Number(orderItem.actual_price) || 0, + discountAmount: String(orderItem.discount_amount || '').trim(), + inventoryType: String(orderItem.inventory_type || '').trim(), + snList: snPayload.snList, + qrCode: snPayload.qrCode, + }); + } + + return { + ownerCode, + warehouseCode, + request: { + deliveryOrder: { + totalOrderLines: orderLines.length, + deliveryOrderCode, + deliveryOrderId: Number(orderRow.id) || undefined, + warehouseCode, + orderType: String(orderRow.order_type || '').trim(), + status: 'DELIVERED', + outBizCode: deliveryOrderCode, + confirmType: 0, + orderConfirmTime, + operatorCode: '', + operatorName: '', + storageFee: String(orderRow.storage_fee || '').trim(), + operateTime: now, + }, + packages: { + package: (packageExpressCodeList.length > 0 ? packageExpressCodeList : [ packageExpressCode ]) + .filter(code => String(code || '').trim()) + .map(expressCode => ({ + logisticsCode: String(orderRow.logistics_code || '').trim(), + logisticsName: String(orderRow.logistics_name || '').trim(), + expressCode: String(expressCode || '').trim(), + packageCode, + invoiceNo, + items: Array.isArray(orderItems) ? orderItems + .filter(item => item && Number(item.plan_qty) > 0) + .map(item => ({ + itemCode: String(item.item_code || '').trim(), + itemId: Number(item.item_id) || String(item.item_id || '').trim(), + quantity: Number(item.plan_qty) || 0, + })) : [], + })), + }, + orderLines, + }, + }; +} + +/** + * 判断货主是否开启「手工单回传通知」。 + * 读取货主-仓库签约策略 policy_config.notify_manual_sync,未配置默认否。 + * + * @param {object} service 服务实例。 + * @param {number} warehouseId 仓库 ID。 + * @param {number} storeId 货主 ID。 + * @return {Promise} true=发送通知,false=不发送通知。 + */ +async function isManualSyncNoticeEnabledInternal(service, warehouseId, storeId) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedStoreId = Number(storeId || 0); + if (normalizedWarehouseId <= 0 || normalizedStoreId <= 0) { + return false; + } + + const storeWarehouseService = service + && service.ctx + && service.ctx.service + && service.ctx.service.systems + && service.ctx.service.systems.storeWarehouse; + + if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') { + service.ctx.logger.warn('[OrderAsyncService.isManualSyncNoticeEnabled] storeWarehouse 服务不可用,按默认否处理', { + warehouseId: normalizedWarehouseId, + storeId: normalizedStoreId, + }); + return false; + } + + try { + const contractConfig = await storeWarehouseService.getContractConfig(normalizedWarehouseId, normalizedStoreId); + const policyConfig = contractConfig && contractConfig.policy_config; + return !!(policyConfig && Number(policyConfig.notify_manual_sync) === 1); + } catch (error) { + service.ctx.logger.warn('[OrderAsyncService.isManualSyncNoticeEnabled] 读取合约策略失败,按默认否处理: %s', String((error && error.message) || error || '').trim()); + return false; + } +} + +async function sendManualSyncNoticeInternal(service, syncResult = {}, context = {}) { + const rawNoticeService = service && service.ctx && service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + if (!noticeService || typeof noticeService.send !== 'function') { + service.ctx.logger.error('[OrderAsyncService.sendManualSyncNotice] 通知服务不可用,通知失败', { + warehouseId: Number(context.warehouseId || syncResult.warehouse_id || 0), + orderIds: Array.isArray(syncResult.order_ids) ? syncResult.order_ids : [], + }); + + return { + success: false, + message: '通知服务不可用,通知失败', + data: null, + }; + } + + const payload = buildManualSyncNoticePayloadInternal(syncResult, context); + + service.ctx.logger.info('[OrderAsyncService.sendManualSyncNotice] 调用通知服务前', { + event: payload.event, + businessName: payload.businessName, + warehouseId: payload.warehouseId, + storeId: payload.storeId, + orderIds: Array.isArray(syncResult.order_ids) ? syncResult.order_ids : [], + status: payload.metadata && payload.metadata.status, + routeState: payload.metadata && payload.metadata.route_state, + }); + + const noticeResult = await noticeService.send(payload); + + service.ctx.logger.info('[OrderAsyncService.sendManualSyncNotice] 通知服务返回结果', { + event: payload.event, + businessName: payload.businessName, + warehouseId: payload.warehouseId, + orderIds: Array.isArray(syncResult.order_ids) ? syncResult.order_ids : [], + success: !!(noticeResult && noticeResult.success), + message: noticeResult && noticeResult.message, + data: noticeResult && noticeResult.data, + }); + + return noticeResult; +} + +async function syncManualOrdersInternal(service, groupedOrder = {}, context = {}) { + const orderIds = Array.isArray(groupedOrder.order_ids) + ? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) + : []; + const warehouseId = Number(context.warehouseId || 0); + + if (orderIds.length === 0) { + return { + create_channel: CREATE_CHANNEL_MANUAL, + order_ids: [], + order_count: 0, + warehouse_id: warehouseId, + handler: 'syncManualOrders', + sync_target: 'internal', + orders: [], + sync_results: [], + route_state: 'rejected', + status: 'failed', + message: 'MANUAL 同步订单不能为空', + success_count: 0, + failed_count: 0, + }; + } + + if (warehouseId <= 0) { + return { + create_channel: CREATE_CHANNEL_MANUAL, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: 'syncManualOrders', + sync_target: 'internal', + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + sync_results: [], + route_state: 'rejected', + status: 'failed', + message: '缺少仓库上下文', + success_count: 0, + failed_count: orderIds.length, + }; + } + + const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const { Op } = service.app.Sequelize; + const orderRows = await orderModel.findAll({ + where: { + id: { + [Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const orderMap = new Map(); + for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { + if (orderRow && Number(orderRow.id) > 0) { + // 分发前过滤:已同步完成的订单不再派发 + if (String(orderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[syncManualOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`); + continue; + } + orderMap.set(Number(orderRow.id), orderRow); + } + } + + const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId); + + // dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣 + const uniqueOrderIds = [ ...new Set(orderIds) ]; + const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); + const syncResults = []; + for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE); + const batchResults = await Promise.all(batch.map(orderId => { + const dispathedOrderRow = orderMap.get(orderId); + if (!dispathedOrderRow) { + return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' }; + } + return processManualOrderInternal( + service, + orderModel, + orderItemsModel, + orderId, + warehouseId, + orderMap.get(orderId), + context, + waybillCodeMap.get(orderId) + ); + })); + syncResults.push(...batchResults); + await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length); + } + + const successCount = syncResults.filter(item => item.status === 'success').length; + const failedCount = syncResults.filter(item => item.status === 'failed').length; + const overallSuccess = failedCount === 0 && successCount === syncResults.length; + const firstFailedResult = syncResults.find(item => item.status === 'failed'); + const aggregateNoticeResult = syncResults.length === 1 + ? syncResults[0] && syncResults[0].notice_result + : firstFailedResult && firstFailedResult.notice_result; + + return { + create_channel: CREATE_CHANNEL_MANUAL, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: 'syncManualOrders', + sync_target: 'internal', + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + sync_results: syncResults, + route_state: overallSuccess ? 'accepted' : 'rejected', + status: overallSuccess ? 'success' : 'failed', + message: overallSuccess ? 'MANUAL 同步成功' : String(firstFailedResult && firstFailedResult.message || 'MANUAL 同步失败').trim() || 'MANUAL 同步失败', + success_count: successCount, + failed_count: failedCount, + notice_result: aggregateNoticeResult, + }; +} + +async function markPendingExceptionInternal(service, orderModel, orderId, warehouseId, exceptionText) { + const normalizedText = String(exceptionText || '').trim() || '订单同步失败'; + const orderPendingExceptionService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.orderPendingException; + + if (orderPendingExceptionService && typeof orderPendingExceptionService.markPendingException === 'function') { + try { + return await orderPendingExceptionService.markPendingException({ + id: orderId, + warehouse_id: warehouseId, + exception_text: normalizedText, + }); + } catch (error) { + service.ctx.logger.warn('[OrderAsyncService.markPendingException] 复用异常服务失败,回退到直接更新', { + orderId, + warehouseId, + message: error.message, + }); + } + } + + await orderModel.update({ + inspection_status: 'error', + step: 3, + order_flag: normalizedText, + updated_at: new Date(), + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + status: { + [service.app.Sequelize.Op.ne]: 'cancel', + }, + }, + }); + + return { + success: true, + exception_text: normalizedText, + order_flag: normalizedText, + }; +} + +async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow = null) { + const stockStoreService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.stockStore; + + if (!service.ctx.model || typeof service.ctx.model.transaction !== 'function') { + throw new Error('事务能力未初始化'); + } + + if (!stockStoreService || typeof stockStoreService.outbound !== 'function') { + throw new Error('库存出库服务未初始化'); + } + + await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulQimenSync', async transaction => { + let resolvedOrderRow = orderRow; + // 最小修复:始终执行 SELECT ... FOR UPDATE,不再因 orderRow 已传入而跳过 + if (orderModel && typeof orderModel.findOne === 'function') { + resolvedOrderRow = await orderModel.findOne({ + where: { + id: orderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes', 'sync_status' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + } + + // 防重:如果订单已完成同步,跳过本次出库扣减 + if (resolvedOrderRow && String(resolvedOrderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`); + return; + } + + const outboundMetaOrderId = Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null; + const outboundMetaOrderNo = String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null; + const freshOrderItems = await orderItemsModel.findAll({ + where: { + order_id: orderId, + }, + raw: true, + transaction, + }); + + for (const orderItem of Array.isArray(freshOrderItems) ? freshOrderItems : []) { + const itemId = Number(orderItem && orderItem.item_id); + const quantity = resolveQimenSyncItemQuantityInternal(orderItem); + + if (!Number.isFinite(itemId) || itemId <= 0 || quantity <= 0) { + continue; + } + + const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null; + const stockId = Number(orderItem && orderItem.stock_id) || 0; + const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, { + orderId: outboundMetaOrderId, + orderNo: outboundMetaOrderNo, + orderItemId: outboundOrderItemId, + sourceOrderCodes: String(resolvedOrderRow && resolvedOrderRow.source_order_codes || '').trim() || undefined, + }, { stockId: stockId > 0 ? stockId : undefined }); + if (!outboundResult || outboundResult.success !== true) { + throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim()); + } + } + + await orderModel.update({ + sync_status: 'fin', + inspection_status: 'padding', + step: 2, + order_flag: '', + updated_at: new Date(), + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + status: { + [service.app.Sequelize.Op.ne]: 'cancel', + }, + }, + transaction, + }); + }); +} + +async function processLocalChannelOrderInternal(service, createChannel, orderModel, orderItemsModel, orderId, warehouseId, orderRow) { + if (!orderRow) { + return { + order_id: orderId, + status: 'failed', + message: '发货单不存在', + }; + } + + try { + await runTransactionWithLockRetryInternal(service, 'processLocalChannelOrder', async transaction => { + // 防重:SELECT FOR UPDATE 锁定订单行并检查 sync_status,防止重复出库 + const lockedOrderRow = await orderModel.findOne({ + where: { + id: orderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'sync_status' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + if (lockedOrderRow && String(lockedOrderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`); + return; + } + + const freshOrderItems = await orderItemsModel.findAll({ + where: { + order_id: orderId, + }, + raw: true, + transaction, + }); + + for (const orderItem of Array.isArray(freshOrderItems) ? freshOrderItems : []) { + const itemId = Number(orderItem && orderItem.item_id); + const quantity = resolveQimenSyncItemQuantityInternal(orderItem); + + if (!Number.isFinite(itemId) || itemId <= 0 || quantity <= 0) { + continue; + } + + const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null; + const stockId = Number(orderItem && orderItem.stock_id) || 0; + const outboundResult = await service.ctx.service.systems.stockStore.outbound(itemId, quantity, transaction, { + orderId: Number(orderRow && orderRow.id) || Number(orderId) || null, + orderNo: String(orderRow && orderRow.delivery_order_code || '').trim() || null, + orderItemId: outboundOrderItemId, + sourceOrderCodes: String(orderRow && orderRow.source_order_codes || '').trim() || undefined, + }, { stockId: stockId > 0 ? stockId : undefined }); + if (!outboundResult || outboundResult.success !== true) { + throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim()); + } + } + + await orderModel.update({ + sync_status: 'fin', + inspection_status: 'padding', + step: 2, + order_flag: '', + updated_at: new Date(), + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + status: { + [service.app.Sequelize.Op.ne]: 'cancel', + }, + }, + transaction, + }); + }); + + return { + order_id: orderId, + delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + status: 'success', + message: `${createChannel} 同步成功`, + }; + } catch (error) { + await orderModel.update({ + sync_status: 'error', + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + }, + }); + + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, error.message || `${createChannel} 同步后库存扣减失败`); + + return { + order_id: orderId, + delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + status: 'failed', + message: error.message || `${createChannel} 同步后库存扣减失败`, + error: error.message, + }; + } +} + +async function processManualOrderInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow, context = {}, waybillCodes = []) { + if (!orderRow) { + return { + order_id: orderId, + status: 'failed', + message: '发货单不存在', + }; + } + + const resolvedWaybillCodes = resolveOrderWaybillCodesInternal(orderRow, waybillCodes); + const noticeSyncResult = { + create_channel: CREATE_CHANNEL_MANUAL, + order_ids: [ orderId ], + order_count: 1, + delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + store_id: Number(orderRow && orderRow.store_id) || 0, + waybill_code: resolvedWaybillCodes, + receiver_name: String(orderRow.name || '').trim(), + receiver_phone: String(orderRow.mobile || orderRow.tel || '').trim(), + warehouse_id: warehouseId, + handler: 'syncManualOrders', + sync_target: 'internal', + route_state: 'accepted', + status: 'success', + message: '订单同步通知已合并排队', + success_count: 1, + failed_count: 0, + }; + + const manualSyncNoticeEnabled = await isManualSyncNoticeEnabledInternal( + service, + warehouseId, + Number(orderRow && orderRow.store_id) || 0 + ); + let noticeResult; + if (!manualSyncNoticeEnabled) { + service.ctx.logger.info(`[OrderAsyncService.processManualOrder] 货主未开启手工单回传通知,跳过通知 orderId=${orderId}`); + noticeResult = { + success: true, + message: '货主未开启手工单回传通知,跳过通知', + data: { + mode: 'skipped', + warehouseId, + storeId: Number(orderRow && orderRow.store_id) || 0, + }, + }; + } else { + noticeResult = await enqueueOrderSyncNoticeInternal(service, noticeSyncResult, context); + } + + if (!noticeResult || noticeResult.success !== true) { + const noticeMessage = String(noticeResult && noticeResult.message || '通知发送失败').trim() || '通知发送失败'; + + await orderModel.update({ + sync_status: 'error', + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + }, + }); + + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, noticeMessage); + + return { + order_id: orderId, + delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + status: 'failed', + message: noticeMessage, + error: noticeMessage, + notice_result: noticeResult || { + success: false, + message: noticeMessage, + data: null, + }, + }; + } + + const localSyncResult = await processLocalChannelOrderInternal( + service, + CREATE_CHANNEL_MANUAL, + orderModel, + orderItemsModel, + orderId, + warehouseId, + orderRow + ); + + return { + ...localSyncResult, + notice_result: noticeResult, + }; +} + +/** + * 按订单货主合约反查可用的 OpenAPI 应用配置(ApiApp)。 + * + * 口径与入库单回调 _sendOpenApiCallback 对齐: + * 先按 store_id + warehouse_id + auth_status=2 查 StoreWarehouse 授权关系, + * 再按 contract_id 查启用(is_enabled=1)且配置了 callback_url 的 ApiApp。 + * 未找到授权关系 / 无可用 ApiApp 配置时返回 null 并记录 warn 日志。 + * + * @param {Object} service 订单异步服务实例。 + * @param {number|string} storeId 货主 ID。 + * @param {number|string} warehouseId 仓库 ID。 + * @return {Promise} { appKey, selfAppSecret, callbackUrl },未找到可用配置时返回 null。 + */ +async function resolveOpenApiAppByStoreInternal(service, storeId, warehouseId) { + const normalizedStoreId = Number(storeId || 0); + const normalizedWarehouseId = Number(warehouseId || 0); + const storeWarehouseModel = service.ctx.model && service.ctx.model.StoreWarehouse; + const apiAppModel = service.ctx.model && service.ctx.model.ApiApp; + + if (!Number.isFinite(normalizedStoreId) || normalizedStoreId <= 0 + || !Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0 + || !storeWarehouseModel || typeof storeWarehouseModel.findOne !== 'function' + || !apiAppModel || typeof apiAppModel.findOne !== 'function') { + service.ctx.logger.warn('[OrderAsyncService.resolveOpenApiAppByStore] 缺少货主/仓库上下文或数据模型不可用,无法反查 ApiApp', { + storeId: normalizedStoreId, + warehouseId: normalizedWarehouseId, + }); + return null; + } + + const { Op } = service.app.Sequelize; + + const storeWarehouse = await storeWarehouseModel.findOne({ + where: { + store_id: normalizedStoreId, + warehouse_id: normalizedWarehouseId, + auth_status: 2, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!storeWarehouse) { + service.ctx.logger.warn(`[OrderAsyncService] OpenAPI回调:未找到授权关系 storeId=${normalizedStoreId} warehouseId=${normalizedWarehouseId}`); + return null; + } + + const apiApp = await apiAppModel.findOne({ + where: { + contract_id: storeWarehouse.id, + is_enabled: 1, + callback_url: { + [Op.and]: [ + { [Op.ne]: null }, + { [Op.ne]: '' }, + ], + }, + }, + attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ], + raw: true, + }); + + if (!apiApp || !apiApp.callback_url) { + service.ctx.logger.warn(`[OrderAsyncService] OpenAPI回调:未找到有效ApiApp配置 storeId=${normalizedStoreId} warehouseId=${normalizedWarehouseId} contractId=${storeWarehouse.id}`); + return null; + } + + return { + appKey: String(apiApp.self_app_key || '').trim(), + selfAppSecret: String(apiApp.self_app_secret || '').trim(), + callbackUrl: String(apiApp.callback_url || '').trim(), + }; +} + +/** + * 将 API 渠道订单标记为同步失败(sync_status='error' + 待处理异常)。 + * + * 与奇门渠道回传失败口径一致:失败不扣减库存、不置 'fin', + * 订单可被重新派发重试(分发前过滤仅跳过 'fin')。 + * + * @param {Object} service 订单异步服务实例。 + * @param {Object} orderModel 订单主模型。 + * @param {number} orderId 订单 ID。 + * @param {number} warehouseId 仓库 ID。 + * @param {string} message 失败原因。 + * @return {Promise} 无返回值,写库失败仅记录 error 日志。 + */ +async function markApiSyncFailedInternal(service, orderModel, orderId, warehouseId, message) { + try { + await orderModel.update({ + sync_status: 'error', + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + }, + }); + } catch (error) { + service.ctx.logger.error(`[OrderAsyncService.markApiSyncFailed] 更新 sync_status=error 失败 orderId=${orderId}`, { + message: String((error && error.message) || error || '').trim(), + }); + } + + try { + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + } catch (error) { + service.ctx.logger.error(`[OrderAsyncService.markApiSyncFailed] 标记待处理异常失败 orderId=${orderId}`, { + message: String((error && error.message) || error || '').trim(), + }); + } +} + +/** + * API 渠道单订单同步:先回传 deliveryorder.confirm,回调成功后才本地扣减库存并置已同步。 + * + * 与奇门渠道(processQmOrderInternal)口径对齐: + * ① 组装与奇门 taobao.qimen.deliveryorder.confirm 完全一致的 request 报文 + * (缺奇门货主编码等组装数据时直接失败); + * ② 解析发送用 appKey:context.appKey 优先,其次订单来源键 from_key(与回 OMS 取号同口径, + * 从哪里来回哪里去),都缺失时按订单货主合约反查 ApiApp + * (同一批次按货主缓存,N 单 / M 货主 → 2M 次查询,无 N+1); + * API(OMS) 渠道的 deliveryorder.confirm 不校验 ownerCode,故不再要求奇门货主编码; + * ③ 发送回调(sendByAppKey,内部最多 4 次尝试),成功才算平台已确认; + * ④ 回调成功 → 扣减库存 + sync_status='fin';失败/异常 → sync_status='error' + * + 待处理异常,不扣减库存,可重新派发; + * 订单/回调配置缺失(无 store_id、无「启用且 callback_url 非空」的 ApiApp)按失败处理, + * 不再静默跳过,避免订单在平台未确认时被置为已同步。 + * + * @param {Object} service 订单异步服务实例。 + * @param {Object} orderModel 订单主模型。 + * @param {Object} orderItemsModel 订单明细模型。 + * @param {number} orderId 订单 ID。 + * @param {number} warehouseId 仓库 ID。 + * @param {Object} orderRow 订单主表记录。 + * @param {Array} orderItems 订单明细记录。 + * @param {Object} [context] 同步上下文(appKey 可选)。 + * @param {Array} [waybillCodes] 运单号列表。 + * @param {Map} [appByStoreCache] 货主 → ApiApp 反查结果缓存(批内共享)。 + * @return {Promise} 单订单同步结果(status / message / error 等)。 + */ +async function processApiOrderInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow, orderItems, context = {}, waybillCodes = [], appByStoreCache = new Map()) { + if (!orderRow) { + return { + order_id: orderId, + status: 'failed', + message: '发货单不存在', + }; + } + + const deliveryOrderCode = String(orderRow.delivery_order_code || '').trim(); + + /** + * 统一失败出口:写 sync_status='error' + 待处理异常后返回失败结果。 + * @param {string} message 失败原因。 + * @param {Object} [extra] 附加返回字段。 + * @return {Promise} 单订单失败结果。 + */ + const failSync = async (message, extra = {}) => { + await markApiSyncFailedInternal(service, orderModel, orderId, warehouseId, message); + + return { + order_id: orderId, + delivery_order_code: deliveryOrderCode, + status: 'failed', + message, + error: message, + ...extra, + }; + }; + + try { + // ① 组装回调报文 + const requestData = await buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, orderItems, { + ...context, + packageExpressCode: Array.isArray(waybillCodes) ? waybillCodes[0] : '', + packageExpressCodes: waybillCodes, + }); + + if (!requestData || !requestData.request) { + service.ctx.logger.warn(`[OrderAsyncService.processApiOrder] 回调报文组装数据缺失 orderId=${orderId}`, { + deliveryOrderCode, + ownerCode: requestData && requestData.ownerCode, + }); + + return await failSync('发货单回传报文组装失败'); + } + + // ② 解析发送用 appKey:按订单来源键(from_key)回原通道,与回 OMS 取号口径一致。 + // API(OMS) 渠道的 deliveryorder.confirm 不校验 ownerCode,故不再要求奇门货主编码。 + const callbackService = service.ctx.service.openapi && service.ctx.service.openapi.callback; + if (!callbackService || typeof callbackService.sendByAppKey !== 'function') { + return await failSync('OpenAPI 回调服务未初始化'); + } + + const orderFromKey = String(orderRow.from_key || '').trim(); + let resolvedAppKey = String(context.appKey || orderFromKey).trim(); + if (!resolvedAppKey) { + const storeId = Number(orderRow.store_id) || 0; + if (storeId <= 0) { + service.ctx.logger.warn(`[OrderAsyncService.processApiOrder] 订单缺少货主 store_id orderId=${orderId}`, { + deliveryOrderCode, + }); + + return await failSync('发货单缺少货主 store_id,无法解析回传用 appKey'); + } + + if (!appByStoreCache.has(storeId)) { + appByStoreCache.set(storeId, await resolveOpenApiAppByStoreInternal(service, storeId, warehouseId)); + } + + const resolvedApp = appByStoreCache.get(storeId); + resolvedAppKey = String(resolvedApp && resolvedApp.appKey || '').trim(); + + if (!resolvedAppKey) { + service.ctx.logger.warn(`[OrderAsyncService.processApiOrder] 货主无可用 ApiApp 配置 orderId=${orderId} storeId=${storeId}`, { + deliveryOrderCode, + }); + + return await failSync('货主未配置可用的 OpenAPI 回调(wms_api_app 启用且 callback_url 非空)'); + } + } + + // ③ 发送回调:回调成功才继续本地出库扣减 + let callbackResult = null; + try { + callbackResult = await callbackService.sendByAppKey({ + appKey: resolvedAppKey, + event: 'deliveryorder.confirm', + request: requestData.request, + }); + } catch (error) { + const message = `OpenAPI 回调确认异常: ${String((error && error.message) || error || '').trim() || '未知错误'}`; + + service.ctx.logger.error(`[OrderAsyncService.processApiOrder] deliveryorder.confirm 回调异常 orderId=${orderId}`, { + appKey: resolvedAppKey, + deliveryOrderCode, + message, + }); + + return await failSync(message); + } + + if (!callbackResult || callbackResult.success !== true) { + const callbackRetryCount = Number(callbackResult && callbackResult.retryCount) || 0; + const message = `OpenAPI 回调确认失败: ${String((callbackResult && callbackResult.error) || '回调失败').trim()}`; + + service.ctx.logger.error(`[OrderAsyncService.processApiOrder] deliveryorder.confirm 回调失败 orderId=${orderId}`, { + appKey: resolvedAppKey, + deliveryOrderCode, + retryCount: callbackRetryCount, + error: callbackResult && callbackResult.error, + }); + + return await failSync(message, { + callback_retry_count: callbackRetryCount, + }); + } + + service.ctx.logger.info(`[OrderAsyncService.processApiOrder] deliveryorder.confirm 回调成功,开始本地出库扣减 orderId=${orderId}`, { + appKey: resolvedAppKey, + deliveryOrderCode, + retryCount: Number(callbackResult.retryCount) || 0, + }); + + // ④ 回调成功 → 扣减库存 + 置 sync_status='fin' + const localSyncResult = await processLocalChannelOrderInternal( + service, + CREATE_CHANNEL_API, + orderModel, + orderItemsModel, + orderId, + warehouseId, + orderRow + ); + + return { + ...localSyncResult, + callback_retry_count: Number(callbackResult.retryCount) || 0, + }; + } catch (error) { + const message = `API 渠道同步异常: ${String((error && error.message) || error || '').trim() || '未知错误'}`; + + service.ctx.logger.error(`[OrderAsyncService.processApiOrder] 同步异常 orderId=${orderId}`, { + deliveryOrderCode, + message, + }); + + return await failSync(message); + } +} + +/** + * 本地渠道(MANUAL / API)订单同步收尾: + * MANUAL:逐单锁定扣减库存并置 sync_status='fin'; + * API:逐单先回传 deliveryorder.confirm,回调成功后才扣减库存并置 'fin', + * 回调失败/无可用回调配置则 sync_status='error' + 待处理异常(与奇门渠道口径一致), + * 最后统计成功/失败数量返回。 + * + * @param {Object} service 订单异步服务实例。 + * @param {string} createChannel 创建渠道(MANUAL / API)。 + * @param {Object} [groupedOrder] 分组后的订单(含 order_ids / order_count / orders)。 + * @param {Object} [context] 同步上下文(含 warehouseId / request_id;appKey 可选,缺失时按订单货主合约反查)。 + * @param {string} [syncTarget] 同步目标(internal / api)。 + * @return {Promise} 同步结果(含 success_count / failed_count / sync_results 等)。 + */ +async function finalizeLocalChannelOrdersInternal(service, createChannel, groupedOrder = {}, context = {}, syncTarget = 'internal') { + const orderIds = Array.isArray(groupedOrder.order_ids) + ? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) + : []; + const warehouseId = Number(context.warehouseId || 0); + + if (orderIds.length === 0) { + return { + create_channel: createChannel, + order_ids: [], + order_count: 0, + warehouse_id: warehouseId, + handler: createChannel === CREATE_CHANNEL_MANUAL ? 'syncManualOrders' : 'syncApiOrders', + sync_target: syncTarget, + orders: [], + sync_results: [], + route_state: 'rejected', + status: 'failed', + message: `${createChannel} 同步订单不能为空`, + success_count: 0, + failed_count: 0, + }; + } + + if (warehouseId <= 0) { + return { + create_channel: createChannel, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: createChannel === CREATE_CHANNEL_MANUAL ? 'syncManualOrders' : 'syncApiOrders', + sync_target: syncTarget, + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + sync_results: [], + route_state: 'rejected', + status: 'failed', + message: '缺少仓库上下文', + success_count: 0, + failed_count: orderIds.length, + }; + } + + const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const { Op } = service.app.Sequelize; + const [ orderRows, orderItemRows ] = await Promise.all([ + orderModel.findAll({ + where: { + id: { + [Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + raw: true, + }), + orderItemsModel.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + }, + raw: true, + }), + ]); + + const orderMap = new Map(); + for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { + if (orderRow && Number(orderRow.id) > 0) { + // 分发前过滤:已同步完成的订单不再派发 + if (String(orderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[syncApiOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`); + continue; + } + orderMap.set(Number(orderRow.id), orderRow); + } + } + + // 订单明细按 order_id 建索引,供逐单回调组装奇门报文复用(与 syncQmOrdersInternal 一致) + const itemsByOrderId = new Map(); + for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) { + const itemOrderId = Number(orderItem && orderItem.order_id); + if (!Number.isFinite(itemOrderId) || itemOrderId <= 0) { + continue; + } + + if (!itemsByOrderId.has(itemOrderId)) { + itemsByOrderId.set(itemOrderId, []); + } + + itemsByOrderId.get(itemOrderId).push(orderItem); + } + + // API 渠道:一次性批量取运单号 + 批内共享货主 appKey 反查缓存, + // 供逐单「先回传 deliveryorder.confirm → 成功才扣减库存」复用(无逐单 N+1 查询) + const isApiChannel = createChannel === CREATE_CHANNEL_API; + const waybillCodeMap = isApiChannel + ? await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId) + : new Map(); + const appByStoreCache = new Map(); + + // dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣 + const uniqueOrderIds = [ ...new Set(orderIds) ]; + const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); + const syncResults = []; + for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE); + const batchResults = await Promise.all(batch.map(orderId => { + const dispathedOrderRow = orderMap.get(orderId); + if (!dispathedOrderRow) { + return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' }; + } + if (isApiChannel) { + return processApiOrderInternal( + service, + orderModel, + orderItemsModel, + orderId, + warehouseId, + dispathedOrderRow, + itemsByOrderId.get(orderId) || [], + context, + waybillCodeMap.get(orderId) || [], + appByStoreCache + ); + } + return processLocalChannelOrderInternal( + service, + createChannel, + orderModel, + orderItemsModel, + orderId, + warehouseId, + orderMap.get(orderId) + ); + })); + syncResults.push(...batchResults); + await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length); + } + + const successCount = syncResults.filter(item => item.status === 'success').length; + const failedCount = syncResults.filter(item => item.status === 'failed').length; + const overallSuccess = failedCount === 0 && successCount === syncResults.length; + + return { + create_channel: createChannel, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: createChannel === CREATE_CHANNEL_MANUAL ? 'syncManualOrders' : 'syncApiOrders', + sync_target: syncTarget, + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + sync_results: syncResults, + route_state: overallSuccess ? 'accepted' : 'rejected', + status: overallSuccess ? 'success' : 'failed', + message: overallSuccess ? `${createChannel} 同步成功` : `${createChannel} 同步失败`, + success_count: successCount, + failed_count: failedCount, + }; +} + +/** + * 构建出库单确认回传数据(taobao.qimen.stockout.confirm / OpenAPI 回调共用)。 + * + * 快递信息取订单侧实际发货信息:物流编码优先订单 sys_logistics_code → logistics_code → + * 出库单 express_code;运单号来自 wms_order_express 表(waybillCodes)。 + * + * @param {Object} service 服务实例 + * @param {Object} stockoutOrder 出库单主表记录(raw) + * @param {Object} orderRow 订单主表记录(raw) + * @param {Array} stockoutItems 出库单明细(raw 数组) + * @param {Array} [waybillCodes] 运单号列表 + * @return {Object} 出库单确认回传请求体 + */ +function buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stockoutItems, waybillCodes = []) { + const now = service.app.formatDate(new Date()); + // STOCKOUT 渠道运单号只认 wms_order_express 表(分配快递号时写入), + // 不回退订单主表 express_code(该字段是面单号前置,不是完整运单号) + const normalizedWaybillCodes = (Array.isArray(waybillCodes) ? waybillCodes : []) + .map(code => String(code || '').trim()) + .filter(code => !!code); + const expressCode = String( + orderRow.sys_logistics_code + || orderRow.logistics_code + || stockoutOrder.express_code + || 'OTHER' + ).trim(); + const expressName = String( + orderRow.sys_logistics_name + || orderRow.logistics_name + || stockoutOrder.express_name + || 'OTHER' + ).trim(); + const stockoutOrderCode = String(stockoutOrder.stockout_order_code || '').trim(); + const packageCode = String(orderRow.package_code || '').trim() || stockoutOrderCode; + const orderLines = (Array.isArray(stockoutItems) ? stockoutItems : []).map(item => { + const planQty = Number(item.plan_qty) || 0; + const actualQty = Number(item.actual_qty) || planQty; + + return { + orderLineNo: String(item.order_line_no || '').trim(), + ownerCode: String(item.owner_code || stockoutOrder.qimen_owner_code || '').trim(), + itemCode: String(item.item_code || '').trim(), + itemId: item.item_id, + itemName: String(item.item_name || '').trim(), + planQty, + actualQty, + inventoryType: String(item.inventory_type || 'ZP').trim(), + }; + }); + + return { + deliveryOrder: { + totalOrderLines: Number(stockoutOrder.total_order_lines) || orderLines.length, + deliveryOrderCode: stockoutOrderCode, + deliveryOrderId: Number(stockoutOrder.id) || undefined, + warehouseCode: String(stockoutOrder.qimen_warehouse_code || '').trim(), + orderType: String(stockoutOrder.order_type || '').trim(), + status: 'DELIVERED', + outBizCode: stockoutOrderCode, + confirmType: 0, + orderConfirmTime: now, + operatorCode: '', + operatorName: '', + }, + packages: { + package: normalizedWaybillCodes.map(waybillCode => ({ + logisticsCode: expressCode, + logisticsName: expressName, + expressCode: waybillCode, + packageCode, + items: orderLines.map(line => ({ + itemCode: line.itemCode, + itemId: line.itemId, + quantity: line.actualQty, + })), + })), + }, + orderLines, + }; +} + +/** + * 通知外部出库单确认结果(按出库单 source_type 分流)。 + * + * - QM:奇门 taobao.qimen.stockout.confirm,flag=success 视为成功; + * - API:OpenAPI 签名回调(event=stockout.confirm,报文为与奇门同层级的 request 节点); + * - 其他(WMS 等内部来源):无需通知外部,直接视为成功。 + * + * @param {Object} service 服务实例 + * @param {Object} stockoutOrder 出库单主表记录(raw) + * @param {Object} requestData 出库单确认回传请求体 + * @param {Object} [context] 上下文(含 appKey) + * @return {Promise<{success: boolean, message: string}>} 通知结果 + */ +async function notifyStockoutExternalInternal(service, stockoutOrder, requestData, context = {}) { + const { ctx, app } = service; + const sourceType = String(stockoutOrder.source_type || 'QM').trim().toUpperCase(); + + if (sourceType === 'QM') { + if (!app.qimenClient || typeof app.qimenClient.send !== 'function') { + return { success: false, message: '奇门客户端未初始化' }; + } + + if (!stockoutOrder.qimen_owner_code) { + return { success: false, message: '出库单缺少奇门货主编码' }; + } + + try { + const sendResult = await app.qimenClient.send( + 'taobao.qimen.stockout.confirm', + stockoutOrder.qimen_owner_code, + requestData, + { ctx } + ); + const response = (sendResult && sendResult.xmlArray && sendResult.xmlArray.response) + ? (Array.isArray(sendResult.xmlArray.response) ? sendResult.xmlArray.response[0] : sendResult.xmlArray.response) + : {}; + const flag = String(response.flag || '').trim(); + if (flag === 'success') { + return { success: true, message: '' }; + } + + return { + success: false, + message: `${response.code || ''} ${response.message || '奇门出库单确认失败'}`.trim(), + }; + } catch (error) { + return { success: false, message: error.message || '奇门出库单确认异常' }; + } + } + + if (sourceType === 'API') { + const callbackService = ctx.service.openapi && ctx.service.openapi.callback; + const appKey = String(context.appKey || '').trim(); + + if (!callbackService || typeof callbackService.sendByAppKey !== 'function') { + return { success: false, message: 'OpenAPI 回调服务未初始化' }; + } + + if (!appKey) { + return { success: false, message: '缺少 appKey,无法回传出库单' }; + } + + try { + // requestData 即奇门 request 节点内容,OpenAPI 回调按同层级 request 发送 + const callbackResult = await callbackService.sendByAppKey({ + appKey, + event: 'stockout.confirm', + request: requestData, + }); + + if (callbackResult && callbackResult.success === true) { + return { success: true, message: '' }; + } + + return { + success: false, + message: String(callbackResult && callbackResult.error || 'OpenAPI 回传失败').trim(), + }; + } catch (error) { + return { success: false, message: error.message || 'OpenAPI 回传异常' }; + } + } + + // WMS 等内部来源:无需通知外部 + return { success: true, message: '' }; +} + +/** + * 出库单回传成功后的收尾: + * 同一事务内 ① 写回出库单快递信息并推进 COMPLETED/SUCCESS; + * ② 按订单明细扣减库存(outbound,自动释放订单锁定);③ 订单 sync_status=fin。 + * + * @param {Object} service 服务实例 + * @param {Object} orderModel 订单模型 + * @param {Object} orderItemsModel 订单明细模型 + * @param {number} orderId 订单ID + * @param {number} warehouseId 仓库ID + * @param {Object} stockoutOrder 出库单记录(raw) + * @param {Object} expressWriteback 出库单快递写回字段 + * @param {Object} [orderRow] 订单记录(raw) + * @return {Promise} 失败抛异常 + */ +async function finalizeSuccessfulStockoutSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, stockoutOrder, expressWriteback, orderRow = null) { + const stockStoreService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.stockStore; + + if (!service.ctx.model || typeof service.ctx.model.transaction !== 'function') { + throw new Error('事务能力未初始化'); + } + + if (!stockStoreService || typeof stockStoreService.outbound !== 'function') { + throw new Error('库存出库服务未初始化'); + } + + await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulStockoutSync', async transaction => { + let resolvedOrderRow = orderRow; + if (orderModel && typeof orderModel.findOne === 'function') { + resolvedOrderRow = await orderModel.findOne({ + where: { + id: orderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes', 'sync_status' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + } + + const stockoutUpdate = { + ...expressWriteback, + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: '', + updated_at: new Date(), + }; + + // 防重:订单已完成同步(并发重试触发),仅补齐出库单写回后跳过扣减 + if (resolvedOrderRow && String(resolvedOrderRow.sync_status || '').trim() === 'fin') { + await service.ctx.model.OrderStockout.update(stockoutUpdate, { + where: { id: stockoutOrder.id }, + transaction, + }); + service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`); + return; + } + + const freshOrderItems = await orderItemsModel.findAll({ + where: { order_id: orderId }, + raw: true, + transaction, + }); + + for (const orderItem of Array.isArray(freshOrderItems) ? freshOrderItems : []) { + const itemId = Number(orderItem && orderItem.item_id); + const quantity = resolveQimenSyncItemQuantityInternal(orderItem); + + if (!Number.isFinite(itemId) || itemId <= 0 || quantity <= 0) { + continue; + } + + const stockId = Number(orderItem && orderItem.stock_id) || 0; + const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, { + orderId: Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null, + orderNo: String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null, + orderItemId: Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null, + sourceOrderCodes: String(resolvedOrderRow && resolvedOrderRow.source_order_codes || '').trim() || undefined, + }, { stockId: stockId > 0 ? stockId : undefined }); + + if (!outboundResult || outboundResult.success !== true) { + throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim()); + } + } + + // 写回出库单快递信息 + 状态推进 + await service.ctx.model.OrderStockout.update(stockoutUpdate, { + where: { id: stockoutOrder.id }, + transaction, + }); + + await orderModel.update({ + sync_status: 'fin', + inspection_status: 'padding', + step: 2, + order_flag: '', + updated_at: new Date(), + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + status: { + [service.app.Sequelize.Op.ne]: 'cancel', + }, + }, + transaction, + }); + }); +} + +/** + * 单个 STOCKOUT 订单回传处理: + * 反查出库单 → 收集订单实际快递信息 → 通知外部 → 成功后写回出库单并扣库存完成同步; + * 失败时订单 sync_status=error 并标记待处理异常,出库单 sync_status=FAILED 记录失败原因。 + * + * @param {Object} service 服务实例 + * @param {Object} orderModel 订单模型 + * @param {Object} orderItemsModel 订单明细模型 + * @param {number} orderId 订单ID + * @param {number} warehouseId 仓库ID + * @param {Object} orderRow 订单记录(raw) + * @param {Array} orderItems 订单明细(raw 数组) + * @param {Object} [context] 上下文 + * @param {Array} [waybillCodes] 运单号列表 + * @return {Promise} 处理结果 + */ +async function processStockoutOrderInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow, orderItems, context = {}, waybillCodes = []) { + const { ctx } = service; + const deliveryOrderCode = String(orderRow && orderRow.delivery_order_code || '').trim(); + const buildFailure = (message, extra = {}) => ({ + order_id: orderId, + delivery_order_code: deliveryOrderCode, + status: 'failed', + message, + ...extra, + }); + + if (!orderRow) { + return buildFailure('发货单不存在'); + } + + // 反查出库单:订单 source_order_codes 的首个来源单号(转订单时为出库单号), + // 兜底取订单明细 source_order_code + const sourceOrderCodes = String(orderRow.source_order_codes || '') + .split(',') + .map(code => String(code || '').trim()) + .filter(code => !!code); + const sourceItem = Array.isArray(orderItems) + ? orderItems.find(item => item && String(item.source_order_code || '').trim()) + : null; + const itemSourceOrderCode = String(sourceItem && sourceItem.source_order_code || '').trim(); + const stockoutOrderCode = String(sourceOrderCodes[0] || itemSourceOrderCode || '').trim(); + + if (!stockoutOrderCode) { + const message = '出库单转订单回传失败:未找到订单来源出库单号'; + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + const stockoutOrder = await ctx.model.OrderStockout.findOne({ + where: { + stockout_order_code: stockoutOrderCode, + warehouse_id: warehouseId, + deleted_at: null, + }, + raw: true, + }); + + if (!stockoutOrder) { + const message = `出库单转订单回传失败:出库单(${stockoutOrderCode})不存在`; + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + // 幂等:出库单已完成同步(并发/重试场景),跳过外部通知,直接收尾 + if (String(stockoutOrder.sync_status || '').trim() === 'SUCCESS') { + service.ctx.logger.info(`[syncStockoutOrders] 出库单已完成同步,跳过通知直接收尾 stockoutOrderCode=${stockoutOrderCode}`); + try { + await finalizeSuccessfulStockoutSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, stockoutOrder, {}, orderRow); + return { + order_id: orderId, + delivery_order_code: deliveryOrderCode, + status: 'success', + message: '出库单已同步,订单收尾完成', + }; + } catch (error) { + const message = `出库单回传后收尾失败:${error.message}`; + await orderModel.update({ + sync_status: 'error', + order_flag: message, + updated_at: new Date(), + }, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + } + + // 运单号校验:订单未分配运单号时无法回传出库单 + // STOCKOUT 渠道运单号只认 wms_order_express 表,不回退订单主表 express_code(面单号前置) + const normalizedWaybillCodes = (Array.isArray(waybillCodes) ? waybillCodes : []) + .map(code => String(code || '').trim()) + .filter(code => !!code); + if (normalizedWaybillCodes.length === 0) { + const message = '出库单转订单回传失败:订单未分配运单号'; + await orderModel.update({ + sync_status: 'error', + order_flag: message, + updated_at: new Date(), + }, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + const stockoutItems = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: stockoutOrder.id }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 快递信息写回字段(回传成功落库):物流编码/名称 + 运单号列表(复数为准,单数为镜像) + const expressWriteback = { + waybill_code: normalizedWaybillCodes[0] || '', + waybill_codes: normalizedWaybillCodes, + express_code: String( + orderRow.sys_logistics_code + || orderRow.logistics_code + || stockoutOrder.express_code + || '' + ).trim(), + express_name: String( + orderRow.sys_logistics_name + || orderRow.logistics_name + || stockoutOrder.express_name + || '' + ).trim(), + }; + + // 通知外部(奇门 stockout.confirm / OpenAPI 回调,按出库单 source_type 分流) + const requestData = buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stockoutItems, normalizedWaybillCodes); + const notifyResult = await notifyStockoutExternalInternal(service, stockoutOrder, requestData, { + ...context, + appKey: String(context.appKey || orderRow.from_key || '').trim(), + }); + + if (!notifyResult || notifyResult.success !== true) { + const message = `出库单转订单回传失败:${String(notifyResult && notifyResult.message || '通知外部失败').trim()}`; + await orderModel.update({ + sync_status: 'error', + order_flag: message, + updated_at: new Date(), + }, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + await ctx.model.OrderStockout.update({ + sync_status: 'FAILED', + sync_message: message, + updated_at: new Date(), + }, { + where: { id: stockoutOrder.id }, + }); + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + try { + await finalizeSuccessfulStockoutSyncInternal( + service, + orderModel, + orderItemsModel, + orderId, + warehouseId, + stockoutOrder, + expressWriteback, + orderRow + ); + } catch (error) { + const message = `出库单回传后库存扣减失败:${error.message}`; + await orderModel.update({ + sync_status: 'error', + order_flag: message, + updated_at: new Date(), + }, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message); + return buildFailure(message); + } + + service.ctx.logger.info(`[syncStockoutOrders] 出库单回传成功 stockoutOrderCode=${stockoutOrderCode} orderId=${orderId}`); + + return { + order_id: orderId, + delivery_order_code: deliveryOrderCode, + status: 'success', + message: '出库单回传成功', + }; +} + +/** + * STOCKOUT 创建渠道订单同步入口。 + * + * 从待处理订单同步入口(syncOrderIds)按 create_channel 分组路由到本函数: + * 反查对应出库单,把订单实际快递编码/运单号写回出库单并通知外部 + * (QM→奇门 stockout.confirm,API→OpenAPI 回调),成功后才扣减库存完成同步。 + * + * @param {Object} service 服务实例 + * @param {Object} groupedOrder 分组后的订单 + * @param {Object} context 上下文 + * @return {Promise} 同步结果 + */ +async function syncStockoutOrdersInternal(service, groupedOrder = {}, context = {}) { + const orderIds = Array.isArray(groupedOrder.order_ids) + ? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) + : []; + const warehouseId = Number(context.warehouseId || 0); + + if (orderIds.length === 0) { + return { + create_channel: CREATE_CHANNEL_STOCKOUT, + order_ids: [], + order_count: 0, + warehouse_id: warehouseId, + handler: 'syncStockoutOrders', + sync_target: 'stockout', + orders: [], + sync_results: [], + route_state: 'rejected', + status: 'failed', + message: 'STOCKOUT 同步订单不能为空', + success_count: 0, + failed_count: 0, + }; + } + + if (warehouseId <= 0) { + return { + create_channel: CREATE_CHANNEL_STOCKOUT, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: 'syncStockoutOrders', + sync_target: 'stockout', + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + sync_results: [], + route_state: 'rejected', + status: 'failed', + message: '缺少仓库上下文', + success_count: 0, + failed_count: orderIds.length, + }; + } + + const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const { Op } = service.app.Sequelize; + const [ orderRows, orderItemRows ] = await Promise.all([ + orderModel.findAll({ + where: { + id: { + [Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + raw: true, + }), + orderItemsModel.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + }, + raw: true, + }), + ]); + + const orderMap = new Map(); + for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { + if (orderRow && Number(orderRow.id) > 0) { + if (String(orderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[syncStockoutOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`); + continue; + } + orderMap.set(Number(orderRow.id), orderRow); + } + } + + const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId); + + const itemsByOrderId = new Map(); + for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) { + const itemOrderId = Number(orderItem && orderItem.order_id); + if (!Number.isFinite(itemOrderId) || itemOrderId <= 0) { + continue; + } + + if (!itemsByOrderId.has(itemOrderId)) { + itemsByOrderId.set(itemOrderId, []); + } + + itemsByOrderId.get(itemOrderId).push(orderItem); + } + + const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); + const uniqueOrderIds = [ ...new Set(orderIds) ]; + const syncResults = []; + for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE); + const batchResults = await Promise.all(batch.map(orderId => { + const dispatchedOrderRow = orderMap.get(orderId); + if (!dispatchedOrderRow) { + service.ctx.logger.info(`[syncStockoutOrders] 订单已过滤,跳过 orderId=${orderId}`); + return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' }; + } + + return processStockoutOrderInternal( + service, + orderModel, + orderItemsModel, + orderId, + warehouseId, + dispatchedOrderRow, + itemsByOrderId.get(orderId) || [], + context, + waybillCodeMap.get(orderId) + ); + })); + syncResults.push(...batchResults); + await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length); + } + + const successCount = syncResults.filter(item => item.status === 'success').length; + const failedCount = syncResults.filter(item => item.status === 'failed').length; + const overallSuccess = failedCount === 0 && successCount === syncResults.length; + + return { + create_channel: CREATE_CHANNEL_STOCKOUT, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: 'syncStockoutOrders', + sync_target: 'stockout', + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + sync_results: syncResults, + route_state: overallSuccess ? 'accepted' : 'rejected', + status: overallSuccess ? 'success' : 'failed', + message: overallSuccess ? '出库单回传成功' : '出库单回传失败', + success_count: successCount, + failed_count: failedCount, + }; +} + +function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) { + const orderIds = Array.isArray(syncResult.order_ids) + ? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) + : []; + const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0); + const noticeStatus = String(syncResult.status || '').trim() || 'success'; + const deliveryOrderCode = String(syncResult.delivery_order_code || '').trim(); + const receiverName = String(syncResult.receiver_name || '').trim() || '无'; + const receiverPhone = String(syncResult.receiver_phone || '').trim() || '无'; + const waybillCodeList = Array.isArray(syncResult.waybill_code) + ? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code) + : (Array.isArray(syncResult.waybill_code_list) + ? syncResult.waybill_code_list.map(code => String(code || '').trim()).filter(code => !!code) + : (String(syncResult.waybill_code || '').trim() ? [ String(syncResult.waybill_code || '').trim() ] : [])); + + return { + event: 'order_sync_completed', + businessName: 'order', + warehouseId, + storeId: Number(syncResult.store_id || context.storeId || context.warehouseId || 0), + subject: { + id: warehouseId, + type: 'warehouse', + }, + title: '订单同步完成', + message: [ + `订单${deliveryOrderCode || '无'} 姓名:${receiverName} 电话:${receiverPhone} 运单号:${waybillCodeList.length > 0 ? waybillCodeList.join(',') : '无'}`, + ].join('\n'), + metadata: { + create_channel: CREATE_CHANNEL_MANUAL, + sync_target: 'internal', + order_ids: orderIds, + delivery_order_code: deliveryOrderCode, + waybill_code: waybillCodeList, + order_count: Number.isFinite(Number(syncResult.order_count)) ? Number(syncResult.order_count) : orderIds.length, + status: noticeStatus, + route_state: String(syncResult.route_state || '').trim(), + success_count: Number(syncResult.success_count || 0), + failed_count: Number(syncResult.failed_count || 0), + }, + }; +} + +/** + * 解析订单同步通知合并维度中的货主 ID。 + * 与 buildManualSyncNoticePayloadInternal 的 storeId 取值保持一致。 + * + * @param {object} syncResult 单订单同步结果。 + * @param {object} context 上下文。 + * @return {number} 货主 ID。 + */ +function resolveOrderSyncNoticeStoreIdInternal(syncResult = {}, context = {}) { + return Number(syncResult.store_id || context.storeId || context.warehouseId || 0); +} + +/** + * 生成订单同步通知合并队列的成员标识。 + * 按「仓库:货主」聚合,货主售后群按货主维度订阅。 + * + * @param {number} warehouseId 仓库 ID。 + * @param {number} storeId 货主 ID。 + * @return {string} 队列成员标识。 + */ +function buildOrderSyncNoticeMemberInternal(warehouseId, storeId) { + return `${warehouseId}:${storeId}`; +} + +/** + * 解析订单同步通知合并队列的成员标识。 + * + * @param {string} member 队列成员标识。 + * @return {Object|null} 解析结果或 null。 + */ +function parseOrderSyncNoticeMemberInternal(member) { + const normalized = String(member || '').trim(); + if (!normalized) { + return null; + } + + const [ warehousePart, storePart ] = normalized.split(':'); + const warehouseId = Number(warehousePart); + const storeId = Number(storePart); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId)) { + return null; + } + + return { warehouseId, storeId }; +} + +/** + * 生成订单同步通知合并相关的 Redis 键集合。 + * + * @param {number} warehouseId 仓库 ID。 + * @param {number} storeId 货主 ID。 + * @return {Object} Redis 键集合。 + */ +function buildOrderSyncNoticeKeysInternal(warehouseId, storeId) { + const member = buildOrderSyncNoticeMemberInternal(warehouseId, storeId); + + return { + member, + queueKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:queue`, + listKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:list:${member}`, + retryKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:retry:${member}`, + lockKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:lock:${member}`, + }; +} + +/** + * 获取订单同步通知合并使用的 Redis 客户端。 + * + * @param {object} service 服务实例。 + * @return {Object|null} Redis 客户端或 null。 + */ +function getOrderSyncNoticeRedisClientInternal(service) { + if (!service || !service.app || !service.app.redis || typeof service.app.redis.get !== 'function') { + return null; + } + + try { + return service.app.redis.get('cache') || null; + } catch (error) { + return null; + } +} + +/** + * 把单订单同步结果构建为合并队列条目。 + * + * @param {object} syncResult 单订单同步结果。 + * @return {Object} 合并队列条目。 + */ +function buildOrderSyncNoticeEntryInternal(syncResult = {}) { + const orderIds = Array.isArray(syncResult.order_ids) + ? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) + : []; + const waybillCodes = Array.isArray(syncResult.waybill_code) + ? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code) + : (Array.isArray(syncResult.waybill_code_list) + ? syncResult.waybill_code_list.map(code => String(code || '').trim()).filter(code => !!code) + : (String(syncResult.waybill_code || '').trim() ? [ String(syncResult.waybill_code || '').trim() ] : [])); + + return { + order_id: orderIds[0] || null, + delivery_order_code: String(syncResult.delivery_order_code || '').trim(), + receiver_name: String(syncResult.receiver_name || '').trim(), + receiver_phone: String(syncResult.receiver_phone || '').trim(), + waybill_codes: waybillCodes, + enqueue_at: Date.now(), + }; +} + +/** + * 解析合并队列中的原始条目。 + * + * @param {*} rawEntry 原始条目。 + * @return {Object|null} 解析结果或 null。 + */ +function parseOrderSyncNoticeEntryInternal(rawEntry) { + if (!rawEntry) { + return null; + } + + try { + const entry = typeof rawEntry === 'string' ? JSON.parse(rawEntry) : rawEntry; + if (!entry || typeof entry !== 'object') { + return null; + } + + const orderId = Number(entry.order_id); + + return { + order_id: Number.isFinite(orderId) && orderId > 0 ? orderId : null, + delivery_order_code: String(entry.delivery_order_code || '').trim(), + receiver_name: String(entry.receiver_name || '').trim(), + receiver_phone: String(entry.receiver_phone || '').trim(), + waybill_codes: Array.isArray(entry.waybill_codes) + ? entry.waybill_codes.map(code => String(code || '').trim()).filter(code => !!code) + : [], + enqueue_at: Number(entry.enqueue_at) || null, + }; + } catch (error) { + return null; + } +} + +/** + * 订单同步通知入队:把单订单通知合并到 Redis 队列, + * 等待 3 分钟去抖窗口结束后由定时任务统一推送。 + * Redis 不可用或入队失败时回退为立即发送(保持原有行为)。 + * + * @param {object} service 服务实例。 + * @param {object} syncResult 单订单同步结果。 + * @param {object} context 上下文。 + * @return {Promise} 入队或回退发送结果。 + */ +async function enqueueOrderSyncNoticeInternal(service, syncResult = {}, context = {}) { + const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0); + const storeId = resolveOrderSyncNoticeStoreIdInternal(syncResult, context); + const redis = getOrderSyncNoticeRedisClientInternal(service); + + if (!redis) { + service.ctx.logger.warn('[OrderAsyncService.enqueueOrderSyncNotice] Redis 不可用,回退立即发送通知', { + warehouseId, + storeId, + }); + + return await sendManualSyncNoticeInternal(service, syncResult, context); + } + + const keys = buildOrderSyncNoticeKeysInternal(warehouseId, storeId); + const entry = buildOrderSyncNoticeEntryInternal(syncResult); + + try { + const dueAtSeconds = Math.floor((Date.now() + ORDER_SYNC_NOTICE_DEBOUNCE_MS) / 1000); + await redis.rpush(keys.listKey, JSON.stringify(entry)); + await redis.expire(keys.listKey, ORDER_SYNC_NOTICE_LIST_TTL_SECONDS); + await redis.zadd(keys.queueKey, dueAtSeconds, keys.member); + + service.ctx.logger.info('[OrderAsyncService.enqueueOrderSyncNotice] 订单同步通知已入队,等待合并推送', { + warehouseId, + storeId, + orderId: entry.order_id, + dueAt: dueAtSeconds * 1000, + }); + + return { + success: true, + message: '订单同步通知已合并排队,3 分钟内无新同步将统一推送', + data: { + mode: 'deferred', + warehouseId, + storeId, + due_at: dueAtSeconds * 1000, + }, + }; + } catch (error) { + service.ctx.logger.warn('[OrderAsyncService.enqueueOrderSyncNotice] 合并入队失败,回退立即发送通知', { + warehouseId, + storeId, + error: String((error && error.message) || error || '').trim(), + }); + + return await sendManualSyncNoticeInternal(service, syncResult, context); + } +} + +/** + * 构建合并后的订单同步通知载荷。 + * + * @param {number} warehouseId 仓库 ID。 + * @param {number} storeId 货主 ID。 + * @param {Object[]} entries 合并队列条目。 + * @return {Object} 通知载荷。 + */ +function buildConsolidatedOrderSyncNoticePayloadInternal(warehouseId, storeId, entries = []) { + const normalizedEntries = (Array.isArray(entries) ? entries : []).filter(entry => !!entry); + const orderLines = normalizedEntries.map(entry => { + const code = String(entry.delivery_order_code || '').trim() || '无'; + const name = String(entry.receiver_name || '').trim() || '无'; + const phone = String(entry.receiver_phone || '').trim() || '无'; + const waybillList = Array.isArray(entry.waybill_codes) ? entry.waybill_codes : []; + const waybill = waybillList.length > 0 ? waybillList.join(',') : '无'; + + return `订单${code} 姓名:${name} 电话:${phone} 运单号:${waybill}`; + }); + + const shownLines = orderLines.slice(0, ORDER_SYNC_NOTICE_MAX_ORDER_LINES); + const hiddenCount = orderLines.length - shownLines.length; + const lines = [ + `订单同步完成(共 ${normalizedEntries.length} 单)`, + ...shownLines, + ]; + + if (hiddenCount > 0) { + lines.push(`……其余 ${hiddenCount} 单未列出`); + } + + return { + event: 'order_sync_completed', + businessName: 'order', + warehouseId, + storeId, + subject: { + id: warehouseId, + type: 'warehouse', + }, + title: '订单同步完成', + message: lines.join('\n'), + metadata: { + create_channel: CREATE_CHANNEL_MANUAL, + sync_target: 'internal', + order_ids: normalizedEntries.map(entry => entry.order_id).filter(orderId => orderId), + order_count: normalizedEntries.length, + status: 'success', + route_state: 'accepted', + success_count: normalizedEntries.length, + failed_count: 0, + debounced: true, + }, + }; +} + +/** + * 发送合并后的订单同步通知。 + * + * @param {object} service 服务实例。 + * @param {number} warehouseId 仓库 ID。 + * @param {number} storeId 货主 ID。 + * @param {Object[]} entries 合并队列条目。 + * @return {Promise} 通知服务返回结果。 + */ +async function sendConsolidatedOrderSyncNoticeInternal(service, warehouseId, storeId, entries = []) { + const rawNoticeService = service && service.ctx && service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + if (!noticeService || typeof noticeService.send !== 'function') { + throw new Error('通知服务不可用'); + } + + const payload = buildConsolidatedOrderSyncNoticePayloadInternal(warehouseId, storeId, entries); + + service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送前', { + warehouseId, + storeId, + entryCount: entries.length, + }); + + const noticeResult = await noticeService.send(payload); + + service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送结果', { + warehouseId, + storeId, + entryCount: entries.length, + success: !!(noticeResult && noticeResult.success), + message: noticeResult && noticeResult.message, + }); + + return noticeResult; +} + +/** + * 处理合并通知发送失败:放回队列并按重试策略推迟。 + * + * @param {object} service 服务实例。 + * @param {Object} redis Redis 客户端。 + * @param {Object} keys 合并维度键集合。 + * @param {string} queueKey 全局队列键。 + * @param {string} member 队列成员。 + * @param {Object[]} entries 合并队列条目。 + * @return {Promise} 无返回值。 + */ +async function handleOrderSyncNoticeFlushFailureInternal(service, redis, keys, queueKey, member, entries) { + const retries = Number(await redis.incr(keys.retryKey)) || 1; + + if (retries >= ORDER_SYNC_NOTICE_MAX_RETRIES) { + await redis.del(keys.listKey, keys.retryKey); + await redis.zrem(queueKey, member); + service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知重试次数超限,放弃发送', { + member, + entryCount: entries.length, + retries, + }); + + return; + } + + if (entries.length > 0) { + await redis.rpush(keys.listKey, ...entries.map(entry => JSON.stringify(entry))); + await redis.expire(keys.listKey, ORDER_SYNC_NOTICE_LIST_TTL_SECONDS); + } + + await redis.zadd(queueKey, Math.floor((Date.now() + ORDER_SYNC_NOTICE_RETRY_MS) / 1000), member); + service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送失败,已重新排队', { + member, + entryCount: entries.length, + retries, + }); +} + +/** + * 冲刷合并的订单同步通知:把 3 分钟去抖窗口已到期的「仓库:货主」维度订单统一推送。 + * 由定时任务调用。 + * + * @param {object} service 服务实例。 + * @return {Promise} 本轮冲刷结果。 + */ +async function flushDeferredOrderSyncNoticesInternal(service) { + const redis = getOrderSyncNoticeRedisClientInternal(service); + if (!redis) { + service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] Redis 不可用,跳过本轮合并通知'); + + return { + skipped: true, + reason: 'redis_unavailable', + flushedCount: 0, + failedCount: 0, + skippedCount: 0, + }; + } + + const queueKey = `${ORDER_SYNC_NOTICE_KEY_PREFIX}:queue`; + const nowSeconds = Math.floor(Date.now() / 1000); + let dueMembers = []; + + try { + dueMembers = await redis.zrangebyscore(queueKey, '-inf', nowSeconds, 'LIMIT', 0, ORDER_SYNC_NOTICE_FLUSH_BATCH_SIZE); + } catch (error) { + service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 读取到期队列失败', { + error: String((error && error.message) || error || '').trim(), + }); + + return { + skipped: true, + reason: 'queue_read_failed', + flushedCount: 0, + failedCount: 0, + skippedCount: 0, + }; + } + + if (!Array.isArray(dueMembers) || dueMembers.length === 0) { + return { + skipped: false, + flushedCount: 0, + failedCount: 0, + skippedCount: 0, + }; + } + + let flushedCount = 0; + let failedCount = 0; + let skippedCount = 0; + + for (const member of dueMembers) { + const parsedMember = parseOrderSyncNoticeMemberInternal(member); + if (!parsedMember) { + skippedCount += 1; + continue; + } + + const keys = buildOrderSyncNoticeKeysInternal(parsedMember.warehouseId, parsedMember.storeId); + let lockAcquired = false; + + try { + const lockResult = await redis.set(keys.lockKey, String(process.pid || ''), 'EX', ORDER_SYNC_NOTICE_LOCK_TTL_SECONDS, 'NX'); + lockAcquired = lockResult === 'OK'; + } catch (lockError) { + service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] 获取合并锁失败,跳过本轮', { + member, + error: String((lockError && lockError.message) || lockError || '').trim(), + }); + continue; + } + + if (!lockAcquired) { + skippedCount += 1; + continue; + } + + try { + // 加锁期间可能又有新订单入队把到期时间推后,重新校验到期时间 + const currentScore = await redis.zscore(queueKey, member); + if (Number(currentScore) > nowSeconds) { + skippedCount += 1; + continue; + } + + const existsCount = Number(await redis.exists(keys.listKey)) || 0; + if (existsCount === 0) { + await redis.del(keys.listKey, keys.retryKey); + await redis.zrem(queueKey, member); + continue; + } + + // 原子搬走列表,避免与并发新入队条目互相污染 + const processingKey = `${keys.listKey}:processing`; + await redis.rename(keys.listKey, processingKey); + const rawEntries = await redis.lrange(processingKey, 0, -1); + await redis.del(processingKey); + + const entries = (Array.isArray(rawEntries) ? rawEntries : []) + .map(rawEntry => parseOrderSyncNoticeEntryInternal(rawEntry)) + .filter(entry => !!entry); + + if (entries.length === 0) { + await redis.del(keys.retryKey); + await redis.zrem(queueKey, member); + continue; + } + + const noticeResult = await sendConsolidatedOrderSyncNoticeInternal( + service, + parsedMember.warehouseId, + parsedMember.storeId, + entries + ); + + if (noticeResult && noticeResult.success === true) { + await redis.del(keys.retryKey); + await redis.zrem(queueKey, member); + flushedCount += 1; + } else { + await handleOrderSyncNoticeFlushFailureInternal(service, redis, keys, queueKey, member, entries); + failedCount += 1; + } + } catch (error) { + failedCount += 1; + service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 冲刷合并通知失败', { + member, + error: String((error && error.message) || error || '').trim(), + }); + + try { + await redis.zadd(queueKey, Math.floor((Date.now() + ORDER_SYNC_NOTICE_RETRY_MS) / 1000), member); + } catch (reQueueError) { + // 重新排队失败仅记录日志 + } + } finally { + try { + await redis.del(keys.lockKey); + } catch (lockReleaseError) { + // 释放锁失败仅记录日志 + } + } + } + + service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 本轮合并通知冲刷完成', { + dueMemberCount: dueMembers.length, + flushedCount, + failedCount, + skippedCount, + }); + + return { + skipped: false, + flushedCount, + failedCount, + skippedCount, + }; +} + + +async function processQmOrderInternal(service, orderModel, orderItemsModel, qimenClient, orderId, warehouseId, orderRow, orderItems, context, waybillCode) { + if (!orderRow) { + return { + order_id: orderId, + status: 'failed', + message: '发货单不存在', + qimen_flag: 'failure', + }; + } + + if (!qimenClient || typeof qimenClient.send !== 'function') { + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, '奇门客户端未初始化'); + + return { + order_id: orderId, + delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + status: 'failed', + message: '奇门客户端未初始化', + qimen_flag: 'failure', + }; + } + + const requestData = await buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, orderItems, { + ...context, + packageExpressCode: Array.isArray(waybillCode) ? waybillCode[0] : (waybillCode || orderRow.express_code || ''), + packageExpressCodes: Array.isArray(waybillCode) ? waybillCode : [], + snCodeMaxLength: QIMEN_SN_CODE_MAX_LENGTH, + }); + if (!requestData.ownerCode) { + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, '发货单缺少奇门货主编码'); + + return { + order_id: orderId, + delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + status: 'failed', + message: '发货单缺少奇门货主编码', + qimen_flag: 'failure', + }; + } + + service.ctx.logger.info('[OrderAsyncService.syncQmOrders] 奇门请求参数', { + orderId, + deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(), + ownerCode: requestData.ownerCode, + warehouseCode: requestData.warehouseCode, + totalOrderLines: requestData.request.deliveryOrder.totalOrderLines, + deliveryOrder: requestData.request.deliveryOrder, + package: requestData.request.packages, + orderLinesCount: Array.isArray(requestData.request.orderLines) + ? requestData.request.orderLines.length + : 0, + }); + + let sendResult; + try { + sendResult = await qimenClient.send('taobao.qimen.deliveryorder.confirm', requestData.ownerCode, requestData.request, { + ctx: service.ctx, + }); + } catch (error) { + await orderModel.update({ + sync_status: 'error', + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + }, + }); + + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, error.message || '奇门发货单确认失败'); + + return { + order_id: orderId, + delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + status: 'failed', + message: error.message || '奇门发货单确认失败', + qimen_flag: 'failure', + error: error.message, + }; + } + + const response = normalizeQimenResponseInternal(sendResult.xmlArray); + service.ctx.logger.info('[OrderAsyncService.syncQmOrders] 奇门返回结果', { + orderId, + deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(), + qimenQueryId: sendResult.queryId || null, + rawXmlArray: sendResult.xmlArray, + normalizedResponse: response, + }); + const isSuccess = String(response.flag || '').trim() === 'success'; + + if (isSuccess) { + try { + await finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow); + } catch (error) { + await orderModel.update({ + sync_status: 'error', + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + }, + }); + + await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, error.message || '奇门发货单确认后库存扣减失败'); + + return { + order_id: orderId, + delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + status: 'failed', + message: error.message || '奇门发货单确认后库存扣减失败', + qimen_flag: 'failure', + qimen_code: 'LOCAL_STOCK_ERROR', + qimen_message: error.message || '奇门发货单确认后库存扣减失败', + qimen_query_id: sendResult.queryId || null, + }; + } + } else { + await orderModel.update({ + sync_status: 'error', + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + }, + }); + } + + const result = { + order_id: orderId, + delivery_order_code: String(orderRow.delivery_order_code || '').trim(), + status: isSuccess ? 'success' : 'failed', + message: String(response.message || '').trim() || (isSuccess ? '奇门发货单确认成功' : '奇门发货单确认失败'), + qimen_flag: String(response.flag || '').trim(), + qimen_code: String(response.code || '').trim(), + qimen_message: String(response.message || '').trim(), + qimen_query_id: sendResult.queryId || null, + }; + + if (!isSuccess) { + await markPendingExceptionInternal( + service, + orderModel, + orderId, + warehouseId, + String(response.message || response.code || '奇门发货单确认失败').trim() || '奇门发货单确认失败' + ); + } + + return result; +} + + +async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) { + const orderIds = Array.isArray(groupedOrder.order_ids) + ? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) + : []; + const warehouseId = Number(context.warehouseId || 0); + + if (orderIds.length === 0) { + return { + create_channel: CREATE_CHANNEL_QM, + order_ids: [], + order_count: 0, + warehouse_id: warehouseId, + handler: 'syncQmOrders', + sync_target: 'qimen', + orders: [], + qimen_results: [], + route_state: 'rejected', + status: 'failed', + message: 'QM 同步订单不能为空', + }; + } + + if (warehouseId <= 0) { + return { + create_channel: CREATE_CHANNEL_QM, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: 'syncQmOrders', + sync_target: 'qimen', + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + qimen_results: [], + route_state: 'rejected', + status: 'failed', + message: '缺少仓库上下文', + }; + } + + const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const { Op } = service.app.Sequelize; + const [ orderRows, orderItemRows ] = await Promise.all([ + orderModel.findAll({ + where: { + id: { + [Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + raw: true, + }), + orderItemsModel.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + }, + raw: true, + }), + ]); + + const orderMap = new Map(); + for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { + if (orderRow && Number(orderRow.id) > 0) { + // 分发前过滤:已同步完成的订单不再派发,避免重复同步覆盖 error 等异常状态 + if (String(orderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[syncQmOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`); + continue; + } + orderMap.set(Number(orderRow.id), orderRow); + } + } + + const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId); + + const itemsByOrderId = new Map(); + for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) { + const orderId = Number(orderItem && orderItem.order_id); + if (!Number.isFinite(orderId) || orderId <= 0) { + continue; + } + + if (!itemsByOrderId.has(orderId)) { + itemsByOrderId.set(orderId, []); + } + + itemsByOrderId.get(orderId).push(orderItem); + } + + const qimenClient = service.app.qimenClient; + const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id); + // dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣 + const uniqueOrderIds = [ ...new Set(orderIds) ]; + const qimenResults = []; + for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) { + const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE); + const batchResults = await Promise.all(batch.map(orderId => { + // 分发时二次检查:orderRow 不在 map 中则跳过 + const dispathedOrderRow = orderMap.get(orderId); + if (!dispathedOrderRow) { + service.ctx.logger.info(`[syncQmOrders] 订单已过滤,跳过 orderId=${orderId}`); + return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' }; + } + return processQmOrderInternal( + service, + orderModel, + orderItemsModel, + qimenClient, + orderId, + warehouseId, + dispathedOrderRow, + itemsByOrderId.get(orderId) || [], + context, + waybillCodeMap.get(orderId) + ); + })); + qimenResults.push(...batchResults); + await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length); + } + + const successCount = qimenResults.filter(item => item.status === 'success').length; + const failedCount = qimenResults.filter(item => item.status === 'failed').length; + const overallSuccess = failedCount === 0 && successCount === qimenResults.length; + + return { + create_channel: CREATE_CHANNEL_QM, + order_ids: orderIds, + order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length, + warehouse_id: warehouseId, + handler: 'syncQmOrders', + sync_target: 'qimen', + orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [], + qimen_results: qimenResults, + route_state: overallSuccess ? 'accepted' : 'rejected', + status: overallSuccess ? 'success' : 'failed', + message: overallSuccess ? '奇门发货单确认成功' : '奇门发货单确认失败', + success_count: successCount, + failed_count: failedCount, + }; +} + +/** + * 订单异步同步路由服务。 + */ +class OrderAsyncService extends MainService { + async finalizeSuccessfulQimenSync(orderModel, orderItemsModel, orderId, warehouseId, orderRow = null) { + return await finalizeSuccessfulQimenSyncInternal(this, orderModel, orderItemsModel, orderId, warehouseId, orderRow); + } + + + /** + * QM 创建入口处理。 + * + * @param {Object} groupedOrder 分组后的订单。 + * @param {Object} context 上下文。 + * @return {Promise} 处理结果。 + */ + async syncQmOrders(groupedOrder = {}, context = {}) { + return await syncQmOrdersInternal(this, groupedOrder, context); + } + + /** + * MANUAL 创建入口处理。 + * + * @param {Object} groupedOrder 分组后的订单。 + * @param {Object} context 上下文。 + * @return {Promise} 处理结果。 + */ + async syncManualOrders(groupedOrder = {}, context = {}) { + return await syncManualOrdersInternal(this, groupedOrder, context); + } + + /** + * 冲刷合并的订单同步通知(由定时任务调用)。 + * 把 3 分钟去抖窗口已到期的「仓库:货主」维度订单统一推送一条消息。 + * + * @return {Promise} 本轮冲刷结果。 + */ + async flushDeferredOrderSyncNotices() { + return await flushDeferredOrderSyncNoticesInternal(this); + } + + /** + * API 创建入口处理。 + * + * @param {Object} groupedOrder 分组后的订单。 + * @param {Object} context 上下文。 + * @return {Promise} 处理结果。 + */ + async syncApiOrders(groupedOrder = {}, context = {}) { + return await finalizeLocalChannelOrdersInternal(this, CREATE_CHANNEL_API, groupedOrder, context, 'api'); + } + + /** + * STOCKOUT 创建入口处理(出库单转订单回传)。 + * + * 回传时把订单实际快递编码/运单号写回出库单,并按出库单来源通知外部 + * (QM→奇门 stockout.confirm,API→OpenAPI 回调),成功后才扣减库存完成同步。 + * + * @param {Object} groupedOrder 分组后的订单。 + * @param {Object} context 上下文。 + * @return {Promise} 处理结果。 + */ + async syncStockoutOrders(groupedOrder = {}, context = {}) { + return await syncStockoutOrdersInternal(this, groupedOrder, context); + } + + /** + * 组装出库单确认回传报文(与奇门 request 节点同层级,OpenAPI 回调复用)。 + * + * 供出库单转订单回传与出库单直出确认(storage.stockout.confirm)共用, + * 避免两处各写一份报文结构导致漂移。 + * + * @param {Object} stockoutOrder 出库单记录(模型实例或 raw 对象)。 + * @param {Object} orderRow 发货单记录(raw);直出确认无订单上下文时传空对象即可。 + * @param {Array} stockoutItems 出库单明细数组。 + * @param {Array} [waybillCodes] 运单号列表。 + * @return {Object} 出库单确认回传请求体。 + */ + buildStockoutConfirmRequest(stockoutOrder, orderRow, stockoutItems, waybillCodes = []) { + return buildStockoutConfirmDataInternal(this, stockoutOrder, orderRow, stockoutItems, waybillCodes); + } + + /** + * 按出库单 source_type 通知外部(QM→奇门,API→OpenAPI 回调,其他→无需通知直接成功)。 + * + * @param {Object} stockoutOrder 出库单记录。 + * @param {Object} requestData 出库单确认回传请求体。 + * @param {Object} [context] 上下文(API 来源需传 appKey)。 + * @return {Promise<{success: boolean, message: string}>} 通知结果。 + */ + async notifyStockoutExternal(stockoutOrder, requestData, context = {}) { + return await notifyStockoutExternalInternal(this, stockoutOrder, requestData, context); + } + + /** + * 按货主合约反查可用的 OpenAPI 应用配置(ApiApp),用于 API 来源出站回调。 + * + * @param {number|string} storeId 货主 ID。 + * @param {number|string} warehouseId 仓库 ID。 + * @return {Promise} { appKey, selfAppSecret, callbackUrl },未找到时返回 null。 + */ + async resolveOpenApiAppByStore(storeId, warehouseId) { + return await resolveOpenApiAppByStoreInternal(this, storeId, warehouseId); + } +} + +module.exports = OrderAsyncService; diff --git a/app/service/systems/order_auto_outbound.js b/app/service/systems/order_auto_outbound.js new file mode 100644 index 0000000..17097dc --- /dev/null +++ b/app/service/systems/order_auto_outbound.js @@ -0,0 +1,658 @@ +'use strict'; + +const MainService = require('../main'); +const Sequelize = require('sequelize'); +const { Op } = Sequelize; + +const OUTBOUND_STATUS = 'fin'; +const OUTBOUND_STEP = 4; +const ORDER_STATUS_FINISHED = 'finished'; +const MAX_BATCH_SIZE = 500; +const STORAGE_STATUS_FIN = 'fin'; +const RECHECK_STATUS_FIN = 'fin'; +const DAY_MS = 24 * 3600 * 1000; +const BEIJING_OFFSET_MS = 8 * 3600 * 1000; +// 出库操作日志编码(app/dict/businessDict.js OPERATION_CODE) +const AUTO_OUTBOUND_OPERATION_CODE = 'ORDER_AUTO_OUTBOUND'; +// 定时任务无用户上下文,按系统操作人记录 +const AUTO_OUTBOUND_OPERATOR = Object.freeze({ id: null, name: '系统' }); + +/** + * 订单自动化出库服务。 + * + * 当仓库开启 auto_outbound_enabled 且配置了 auto_outbound_rules(数组,任一命中即出库)时, + * 自动将满足条件的订单标记为出库并将订单状态更新为已完成。 + * 规则前置条件固定为「已复核」(recheck_status=fin)+「已分配储位」(storage_status=fin)。 + */ +class OrderAutoOutboundService extends MainService { + /** + * 获取所有启用了自动化出库且配置了规则的仓库。 + * + * 自动出库配置以仓库为单位生效(wms_store.id 即 warehouse_id), + * 处理范围仅限当前仓库,不再扩散到该货主签约的外部合同仓。 + * + * @return {Promise}>>} 仓库配置列表。 + */ + async getEnabledAutoOutboundWarehouses() { + const { app } = this; + const { Store } = app.model; + + if (!Store) { + return []; + } + + const stores = await Store.findAll({ + where: { + status: 1, + deleted_at: null, + }, + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + + const result = []; + + for (const store of stores) { + if (!this.isAutoOutboundEnabled(store.subject_config)) { + continue; + } + + const rules = this.resolveAutoOutboundRules(store.subject_config); + + // 空数组表示不出库任何订单,直接跳过(无需告警) + if (rules.length === 0) { + continue; + } + + result.push({ + storeId: store.id, + warehouseId: store.id, + rules, + }); + } + + return result; + } + + /** + * 判断仓库是否启用自动出库(subject_config.auto_outbound_enabled)。 + * + * @param {Object|string|null|undefined} rawConfig subject_config 原始值。 + * @return {boolean} 是否启用。 + */ + isAutoOutboundEnabled(rawConfig) { + const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(rawConfig); + const enabled = subjectConfig && subjectConfig.auto_outbound_enabled; + + return enabled === true || enabled === 1 || enabled === '1' || enabled === 'true'; + } + + /** + * 解析自动出库规则数组(复用 Store 模型归一化,补齐缺省字段)。 + * 旧对象结构或非法规则一律按空数组处理(空数组 = 不出库任何订单)。 + * + * @param {Object|string|null|undefined} rawConfig subject_config 原始值。 + * @return {Array} 规则数组。 + */ + resolveAutoOutboundRules(rawConfig) { + const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(rawConfig); + const rules = subjectConfig && subjectConfig.auto_outbound_rules; + const storeModel = this.app && this.app.model && this.app.model.Store; + + if (storeModel && typeof storeModel.normalizeAutoOutboundRules === 'function') { + try { + return storeModel.normalizeAutoOutboundRules(rules); + } catch (error) { + this.ctx.logger.warn(`[auto-outbound] 自动出库规则配置非法,已按空规则处理: ${error.message}`); + return []; + } + } + + if (!Array.isArray(rules)) { + return []; + } + + return rules.filter(rule => rule && typeof rule === 'object' && !Array.isArray(rule)); + } + + /** + * 规范化 subject_config,支持字符串 JSON 和对象两种格式。 + * + * @param {Object|string} rawConfig 原始主体配置。 + * @return {Object} 规范化后的配置对象。 + */ + normalizeSubjectConfigForAutoOutbound(rawConfig) { + if (!rawConfig) { + return {}; + } + + if (typeof rawConfig === 'object' && !Array.isArray(rawConfig)) { + return rawConfig; + } + + if (typeof rawConfig === 'string') { + try { + return JSON.parse(rawConfig); + } catch (error) { + return {}; + } + } + + return {}; + } + + /** + * 构造单条自动化出库规则的订单查询条件。 + * + * 基础条件(所有规则固定):已复核(recheck_status='fin')+ 已分配储位(storage_status='fin') + * + 未出库(outbound_status='none')+ 状态非 cancel/error/finished。 + * + * @param {Object} rule 自动化出库规则(单条),支持字段: + * - {boolean} [rule.require_pack] 是否要求已打包(pack_status='fin') + * - {boolean} [rule.require_sync] 是否要求已同步(sync_status='fin') + * - {boolean} [rule.exclude_same_day_outbound] 是否不出库当天复核订单(默认 true); + * 开启后按「复核时间所在北京日 D」判定: + * recheck_time < D + deadline(默认 06:00)的订单不受影响; + * recheck_time ≥ D + deadline 的订单在 now < D + release(默认 22:00)前不出库,到达后放行。 + * release 支持跨天(最大 47:59),如 27:00 表示次日 03:00 放行; + * recheck_time 为 null 的订单不受限制。 + * - {string} [rule.same_day_outbound_deadline_time] 允许当天出库最后时间(HH:mm,默认 '06:00',当天内)。 + * - {string} [rule.same_day_outbound_release_time] 放行时间(HH:mm,默认 '22:00',支持 00:00~47:59)。 + * 常用组合:deadline='00:00' + release='23:59' → 当天复核的订单当天不出库,过了零点全部出库; + * deadline='00:00' + release='27:00' → 到次日 03:00 才全部出库。 + * 注:require_weigh(已称重)涉及 wms_order_express,由调用方通过订单ID 子集约束,不在此处拼装。 + * + * @return {Object} Sequelize where 条件对象。 + */ + buildAutoOutboundWhere(rule) { + const safeRule = rule && typeof rule === 'object' ? rule : {}; + const where = { + outbound_status: 'none', + status: { + [Op.notIn]: [ 'cancel', 'error', 'finished' ], + }, + storage_status: STORAGE_STATUS_FIN, + // 未复核订单一律不自动出库(固定基线) + recheck_status: RECHECK_STATUS_FIN, + }; + + // 开启「不出库当天订单」(默认开启)时:按复核时间所在北京日计算未放行窗口, + // 未放行窗口内的订单(recheck_time ∈ [D+deadline, D+24h) 且 now < D+release)不自动出库。 + // 注意:应用按 UTC 读写 DATETIME,recheck_time 存储为 UTC 时刻,边界需按北京时间(UTC+8)换算。 + if (safeRule.exclude_same_day_outbound !== false) { + const recheckCondition = this.buildSameDayOutboundRecheckCondition(new Date(), safeRule); + if (recheckCondition) { + where.recheck_time = recheckCondition; + } + } + + if (safeRule.require_pack) { + where.pack_status = 'fin'; + } + + if (safeRule.require_sync) { + where.sync_status = 'fin'; + } + + return where; + } + + /** + * 扫描仓库下命中任一自动出库规则的订单ID。 + * + * 逐条规则查询(规则内条件 AND),命中即纳入结果;订单ID 去重并保留首个命中的规则下标。 + * 需要称重的规则通过关联 EXISTS 子查询(订单表驱动、快递表按 order_id 点查)约束。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} rules 自动化出库规则数组。 + * @param {number} [limit=MAX_BATCH_SIZE] 单次扫描上限(按仓库汇总)。 + * @return {Promise<{orderIds: Array, ruleIndexById: Map}>} 命中订单ID与规则下标映射。 + */ + async findAutoOutboundOrderIds(warehouseId, rules, limit = MAX_BATCH_SIZE) { + const { ctx } = this; + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + const emptyResult = { orderIds: [], ruleIndexById: new Map() }; + + if (!factory || typeof factory.getCurrentModel !== 'function') { + return emptyResult; + } + + const orderModel = await factory.getCurrentModel(warehouseId); + if (!orderModel) { + return emptyResult; + } + + const ruleList = Array.isArray(rules) ? rules : []; + const orderIds = []; + const ruleIndexById = new Map(); + + for (let index = 0; index < ruleList.length; index += 1) { + const remaining = limit - orderIds.length; + if (remaining <= 0) { + break; + } + + const rule = ruleList[index] && typeof ruleList[index] === 'object' ? ruleList[index] : {}; + const where = this.buildAutoOutboundWhere(rule); + + if (rule.require_weigh) { + const weighCondition = this.buildWeighExistsCondition(orderModel, warehouseId); + if (!weighCondition) { + ctx.logger.warn( + `[auto-outbound] 仓库 ${warehouseId} 缺少订单快递模型或仓库ID非法,跳过「需已称重」规则${index + 1}` + ); + continue; + } + where[Op.and] = [ ...(Array.isArray(where[Op.and]) ? where[Op.and] : []), weighCondition ]; + } + + const orders = await orderModel.findAll({ + where, + attributes: [ 'id' ], + limit: remaining, + raw: true, + }); + + for (const order of orders) { + const orderId = Number(order && order.id); + if (!Number.isFinite(orderId) || orderId <= 0 || ruleIndexById.has(orderId)) { + continue; + } + ruleIndexById.set(orderId, index); + orderIds.push(orderId); + } + } + + return { orderIds, ruleIndexById }; + } + + /** + * 解析 HH:mm 时间配置为小时/分钟,支持跨天(小时可超过 23)。 + * 缺省、格式非法或超出 maxHour 时回退指定默认值。 + * + * @param {string} [timeText] 时间文本,如 '22:00'、'27:00'(= 次日 03:00)。 + * @param {number} defaultHour 默认小时。 + * @param {number} defaultMinute 默认分钟。 + * @param {number} [maxHour=23] 允许的最大小时(放开时间支持 47,表示可跨到次日)。 + * @return {{hour: number, minute: number}} 小时与分钟。 + */ + resolveSameDayTime(timeText, defaultHour, defaultMinute, maxHour = 23) { + const text = typeof timeText === 'string' ? timeText.trim() : ''; + const match = /^(\d{1,2}):([0-5]\d)$/.exec(text); + if (!match) { + return { hour: defaultHour, minute: defaultMinute }; + } + const hour = Number(match[1]); + if (hour > maxHour) { + return { hour: defaultHour, minute: defaultMinute }; + } + return { hour, minute: Number(match[2]) }; + } + + /** + * 解析「允许当天出库最后时间」(当天内,最大 23:59;缺省/非法回退 06:00)。 + * + * @param {string} [timeText] 时间文本。 + * @return {{hour: number, minute: number}} 小时与分钟。 + */ + resolveSameDayDeadlineTime(timeText) { + return this.resolveSameDayTime(timeText, 6, 0, 23); + } + + /** + * 解析「放行时间」(支持跨天,最大 47:59;27:00 = 次日 03:00;缺省/非法回退 22:00)。 + * + * @param {string} [timeText] 时间文本。 + * @return {{hour: number, minute: number}} 小时与分钟。 + */ + resolveSameDayReleaseTime(timeText) { + return this.resolveSameDayTime(timeText, 22, 0, 47); + } + + /** + * 计算北京时间「当天 00:00」对应的 UTC 时刻。 + * + * 用 UTC 显式换算,不依赖 Node 进程时区(生产服务器 TZ 可能与北京时间不一致)。 + * + * @param {Date} [now] 当前时刻(默认 new Date())。 + * @return {Date} 北京时间当天 0 点对应的 UTC Date。 + */ + buildBeijingDayStartUtc(now = new Date()) { + const beijingNowMs = now.getTime() + BEIJING_OFFSET_MS; + const beijingMidnightMs = Math.floor(beijingNowMs / DAY_MS) * DAY_MS; + return new Date(beijingMidnightMs - BEIJING_OFFSET_MS); + } + + /** + * 计算「不出库当天订单」的未放行窗口(按**复核时间所在北京日**对齐,支持跨天)。 + * + * 口径(第 D 天复核的订单,D 为复核时间的北京日): + * - recheck_time < D + deadline → 不受限制(豁免,照常出库); + * - recheck_time ≥ D + deadline 且 now < D + release → 未放行,不出库; + * - now ≥ D + release → 放行(照常出库)。 + * + * 由于 release 最大 47:59,复核日只可能是「今天」或「昨天」,故返回至多两个窗口。 + * + * @param {Date} now 当前时刻。 + * @param {Object} rule 自动化出库规则(单条)。 + * @return {Array<{start: number, end: number}>} 未放行窗口(UTC 毫秒区间,已合并相邻/重叠)。 + */ + buildSameDayOutboundHoldWindows(now, rule) { + const safeRule = rule && typeof rule === 'object' ? rule : {}; + const release = this.resolveSameDayReleaseTime(safeRule.same_day_outbound_release_time); + const deadline = this.resolveSameDayDeadlineTime(safeRule.same_day_outbound_deadline_time); + const releaseMs = (release.hour * 60 + release.minute) * 60000; + const deadlineMs = (deadline.hour * 60 + deadline.minute) * 60000; + const todayStartMs = this.buildBeijingDayStartUtc(now).getTime(); + + const windows = []; + for (const dayOffset of [ -1, 0 ]) { + const dayStartMs = todayStartMs + dayOffset * DAY_MS; + if (now.getTime() >= dayStartMs + releaseMs) { + continue; // 该复核日的放行时刻已到 + } + windows.push({ start: dayStartMs + deadlineMs, end: dayStartMs + DAY_MS }); + } + + windows.sort((a, b) => a.start - b.start); + const merged = []; + for (const window of windows) { + const last = merged[merged.length - 1]; + if (last && window.start <= last.end) { + last.end = Math.max(last.end, window.end); + } else { + merged.push({ ...window }); + } + } + + return merged; + } + + /** + * 生成「不出库当天订单」对 recheck_time 的查询约束(允许集 = 未放行窗口的补集 + NULL)。 + * + * 返回 null 表示当前时刻没有任何未放行窗口(即完全不限制)。 + * + * @param {Date} now 当前时刻。 + * @param {Object} rule 自动化出库规则(单条)。 + * @return {Object|null} Sequelize 条件对象或 null。 + */ + buildSameDayOutboundRecheckCondition(now, rule) { + const windows = this.buildSameDayOutboundHoldWindows(now, rule); + if (windows.length === 0) { + return null; + } + + const ranges = []; + let cursor = null; + for (const window of windows) { + if (cursor === null) { + ranges.push({ [Op.lt]: new Date(window.start) }); + } else if (window.start > cursor) { + ranges.push({ [Op.gte]: new Date(cursor), [Op.lt]: new Date(window.start) }); + } + cursor = cursor === null ? window.end : Math.max(cursor, window.end); + } + ranges.push({ [Op.gte]: new Date(cursor) }); + // recheck_time 为 null 的订单不受限制(既有口径) + ranges.push({ [Op.is]: null }); + + return { [Op.or]: ranges }; + } + + /** + * 构造「已称重」半连接条件(关联 EXISTS 子查询)。 + * + * `wms_order_express.weighing_weight` 无索引且历史命中率极高,若先捞出全量称重订单ID + * 再用 `id IN (...)` 约束,会全表扫描快递大表,并把百万级订单ID 塞进 SQL 与内存。 + * 改为关联 EXISTS 后由订单表驱动,快递表按 order_id 唯一索引逐行点查。 + * + * @param {Object} orderModel 当前仓库的订单模型(Sequelize 模型)。 + * @param {number} warehouseId 仓库ID。 + * @return {Object|null} Sequelize literal 条件;模型缺失或仓库ID非法时返回 null。 + */ + buildWeighExistsCondition(orderModel, warehouseId) { + const { ctx } = this; + const { OrderExpress } = ctx.model; + + if (!OrderExpress) { + return null; + } + + const safeWarehouseId = Number(warehouseId); + if (!Number.isInteger(safeWarehouseId) || safeWarehouseId <= 0) { + return null; + } + + const orderTableRef = this.buildSqlTableRef(orderModel); + const expressTableRef = this.buildSqlTableRef(OrderExpress); + if (!orderTableRef || !expressTableRef) { + return null; + } + + return Sequelize.literal( + `EXISTS (SELECT 1 FROM ${expressTableRef}` + + ` WHERE ${expressTableRef}.\`order_id\` = ${orderTableRef}.\`id\`` + + ` AND ${expressTableRef}.\`warehouse_id\` = ${safeWarehouseId}` + + ` AND ${expressTableRef}.\`weighing_weight\` > 0)` + ); + } + + /** + * 把模型解析为 SQL 中可直接引用的表名(含 schema)。 + * + * @param {Object} model Sequelize 模型。 + * @return {string|null} 形如 `table` 或 `schema`.`table` 的表引用;无法解析时返回 null。 + */ + buildSqlTableRef(model) { + if (!model) { + return null; + } + + const raw = typeof model.getTableName === 'function' ? model.getTableName() : model; + const tableName = typeof raw === 'string' ? raw : (raw && raw.tableName); + const schema = raw && typeof raw === 'object' ? raw.schema : null; + const safeTable = this.quoteSqlIdentifier(tableName); + + if (!safeTable) { + return null; + } + + if (schema) { + const safeSchema = this.quoteSqlIdentifier(schema); + return safeSchema ? `${safeSchema}.${safeTable}` : null; + } + + return safeTable; + } + + /** + * 转义 SQL 标识符(仅允许字母、数字、下划线与 $,避免拼接注入)。 + * + * @param {string} name 标识符。 + * @return {string|null} 反引号包裹的标识符;非法时返回 null。 + */ + quoteSqlIdentifier(name) { + if (typeof name !== 'string' || !/^[A-Za-z0-9_$]+$/.test(name)) { + return null; + } + return `\`${name}\``; + } + + /** + * 对指定仓库执行单次自动化出库扫描与执行。 + * + * 按规则逐条扫描(任一规则命中即出库),订单ID 去重后一次性更新, + * 并对本次出库订单写入操作日志(写日志失败仅告警,不影响出库主流程)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} rules 自动化出库规则数组。 + * @return {Promise<{warehouseId: number, processedCount: number, errorMessage: string|null}>} 执行结果。 + */ + async processWarehouseAutoOutbound(warehouseId, rules) { + const { ctx } = this; + const result = { + warehouseId, + processedCount: 0, + errorMessage: null, + }; + + try { + const { orderIds, ruleIndexById } = await this.findAutoOutboundOrderIds(warehouseId, rules); + + if (orderIds.length === 0) { + return result; + } + + const now = new Date(); + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + const orderModel = await factory.getCurrentModel(warehouseId); + + const [ affectedRows ] = await orderModel.update( + { + outbound_status: OUTBOUND_STATUS, + step: OUTBOUND_STEP, + status: ORDER_STATUS_FINISHED, + delivery_time: now, + updated_at: now, + }, + { + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + } + ); + + result.processedCount = Number(affectedRows) || 0; + + if (result.processedCount > 0) { + ctx.logger.info( + `[auto-outbound] 仓库 ${warehouseId} 自动化出库 ${result.processedCount} 条订单,订单ID: ${orderIds.join(',')}` + ); + + await this.writeAutoOutboundOperationLogs(warehouseId, orderIds, rules, ruleIndexById); + } + } catch (error) { + result.errorMessage = error.message; + ctx.logger.error(`[auto-outbound] 仓库 ${warehouseId} 自动化出库失败: ${error.message}`); + } + + return result; + } + + /** + * 写入自动出库订单操作日志(business_type=order,operation_code=ORDER_AUTO_OUTBOUND)。 + * + * 日志写入失败仅告警,不影响出库主流程。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} orderIds 本次出库的订单ID列表。 + * @param {Array} rules 自动化出库规则数组。 + * @param {Map} ruleIndexById 订单ID → 命中规则下标。 + * @return {Promise} 无返回值。 + */ + async writeAutoOutboundOperationLogs(warehouseId, orderIds, rules, ruleIndexById) { + const { ctx } = this; + const operationLogService = ctx.service + && ctx.service.systems + && ctx.service.systems.operationLog; + + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + return; + } + + const ruleList = Array.isArray(rules) ? rules : []; + const payloads = orderIds.map(orderId => { + const ruleIndex = ruleIndexById && typeof ruleIndexById.get === 'function' && ruleIndexById.has(orderId) + ? ruleIndexById.get(orderId) + : -1; + const rule = ruleIndex >= 0 ? ruleList[ruleIndex] : null; + + return { + businessType: 'order', + businessId: orderId, + operationCode: AUTO_OUTBOUND_OPERATION_CODE, + operator: AUTO_OUTBOUND_OPERATOR, + extras: { + warehouseId, + message: ruleIndex >= 0 + ? `自动出库(命中规则${ruleIndex + 1}:${this.buildAutoOutboundRuleSummary(rule)})` + : '自动出库', + }, + }; + }); + + try { + await operationLogService.createOperationLogs(payloads); + } catch (error) { + ctx.logger.warn( + `[auto-outbound] 仓库 ${warehouseId} 写入自动出库操作日志失败,不影响出库: ${error.message}` + ); + } + } + + /** + * 生成规则条件摘要(用于操作日志 message)。 + * + * @param {Object} rule 自动化出库规则。 + * @return {string} 规则摘要文本。 + */ + buildAutoOutboundRuleSummary(rule) { + const safeRule = rule && typeof rule === 'object' ? rule : {}; + const conditions = []; + + if (safeRule.require_pack) { + conditions.push('需已打包'); + } + if (safeRule.require_weigh) { + conditions.push('需已称重'); + } + if (safeRule.require_sync) { + conditions.push('需已同步'); + } + if (safeRule.exclude_same_day_outbound !== false) { + conditions.push('不出库当天订单'); + } + + return conditions.length > 0 ? conditions.join('、') : '无附加条件'; + } + + /** + * 执行全局自动化出库扫描。 + * 遍历所有启用了自动化出库的仓库,对每个仓库扫描并执行符合条件的订单出库。 + * + * @return {Promise<{totalProcessed: number, warehouseResults: Array}>} 全局执行结果。 + */ + async executeAutoOutbound() { + const { ctx } = this; + + ctx.app._autoOutboundRunning = true; + + try { + const warehouses = await this.getEnabledAutoOutboundWarehouses(); + + if (!warehouses || warehouses.length === 0) { + return { totalProcessed: 0, warehouseResults: [] }; + } + + let totalProcessed = 0; + const warehouseResults = []; + + for (const { warehouseId, rules } of warehouses) { + const result = await this.processWarehouseAutoOutbound(warehouseId, rules); + warehouseResults.push(result); + totalProcessed += result.processedCount; + } + + return { totalProcessed, warehouseResults }; + } catch (error) { + ctx.logger.error(`[auto-outbound] 全局自动化出库执行失败: ${error.message}`); + return { totalProcessed: 0, warehouseResults: [] }; + } finally { + ctx.app._autoOutboundRunning = false; + } + } +} + +module.exports = OrderAutoOutboundService; diff --git a/app/service/systems/order_b2b.js b/app/service/systems/order_b2b.js new file mode 100644 index 0000000..935f7ec --- /dev/null +++ b/app/service/systems/order_b2b.js @@ -0,0 +1,525 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 订单转 B2B 操作码 */ +const ORDER_B2B_CONVERT_OPERATION_CODE = 'ORDER_B2B_CONVERT'; +/** 取消 B2B(流转回正常订单)操作码 */ +const ORDER_B2B_CANCEL_OPERATION_CODE = 'ORDER_B2B_CANCEL'; +/** 单次转换订单数上限 */ +const ORDER_B2B_CONVERT_BATCH_LIMIT = 200; + +/** + * 允许转 B2B 的订单步骤白名单。 + * + * 仅待处理阶段(1 已审核 / 2 处理中 / 3 驳回异常)可转;4 配送中(含已提交出库)、 + * 5 已完成、9 已关闭等已离开待处理阶段的订单一律拒绝,避免误转已配送/已关闭订单。 + */ +const ORDER_B2B_CONVERT_ALLOWED_STEPS = new Set([ 1, 2, 3 ]); + +/** 非白名单步骤的拒绝文案 */ +const ORDER_B2B_CONVERT_STEP_SKIP_REASONS = Object.freeze({ + 0: '订单待审核,不允许转B2B', + 4: '订单已提交出库,不允许转B2B', + 5: '订单已完成,不允许转B2B', + 9: '订单已关闭,不允许转B2B', +}); + +/** + * B2B 订单业务服务。 + * + * 负责订单转 B2B(wms_order_delivery.is_b2b 置 Y + wms_order_b2b 作业明细落表)。 + */ +class OrderB2bService extends Service { + /** + * 将待处理订单批量转为 B2B 订单。 + * + * 仅限待处理表(current 分表)中处于待处理阶段(step in [1,2,3])、未取消、 + * 未拣货、未复核、未锁定、未拦截的订单(打印状态不限制);不符合条件的订单跳过(计入 skipped),不报错。 + * 已在波次中的订单(含库内抓取进波次的订单)转换成功后会在同一事务内从波次摘除 + * (清空波次字段、重排 wave_index、回写波次统计);若波次存在进行中的拣货任务则跳过转换。 + * 事务内完成 is_b2b 置 Y 与 wms_order_b2b 明细写入;操作日志在事务提交后写入。 + * + * @param {Object} params 转换参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID数组。 + * @param {Object|null} [params.operator=null] 操作人 { id, name }。 + * @return {Promise} { converted_order_ids, converted_count, skipped_order_ids, + * skipped_count, skipped_reasons, not_found_order_ids, removed_from_wave_order_ids, + * affected_wave_ids, emptied_wave_ids, active_pick_task_wave_ids } + */ + async convertOrdersToB2b(params = {}) { + const { ctx, app } = this; + const normalizedWarehouseId = Number(params && params.warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const rawIds = params && params.orderIds; + const normalizedOrderIds = [ ...new Set( + (Array.isArray(rawIds) ? rawIds : [ rawIds ]) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0) + ) ]; + if (normalizedOrderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + if (normalizedOrderIds.length > ORDER_B2B_CONVERT_BATCH_LIMIT) { + throw new Error(`单次最多转换 ${ORDER_B2B_CONVERT_BATCH_LIMIT} 个订单`); + } + + const operator = params && params.operator && typeof params.operator === 'object' + ? params.operator + : null; + const { Op } = app.Sequelize; + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(normalizedWarehouseId); + + const transaction = await ctx.model.transaction(); + const convertedRows = []; + const skippedReasons = []; + const waveRemovalLogItems = []; + let waveDetachResult = null; + let notFoundOrderIds = []; + let notConvertedWaveIds = []; + + try { + const lockRows = await orderModel.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'step', 'status', + 'pick_status', 'recheck_status', + 'print_status', 'lock_status', 'intercept_status', 'is_b2b', + 'wave_id', 'wave_no', + ], + where: { + id: { [Op.in]: normalizedOrderIds }, + warehouse_id: normalizedWarehouseId, + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const rowMap = new Map((Array.isArray(lockRows) ? lockRows : []).map(row => [ Number(row && row.id || 0), row ])); + notFoundOrderIds = normalizedOrderIds.filter(orderId => !rowMap.has(orderId)); + + for (const orderId of normalizedOrderIds) { + const row = rowMap.get(orderId); + if (!row) { + continue; + } + + const skipReason = this.resolveConvertSkipReason(row); + if (skipReason) { + skippedReasons.push({ + order_id: orderId, + delivery_order_code: String(row.delivery_order_code || '').trim(), + reason: skipReason, + }); + continue; + } + + convertedRows.push(row); + } + + // 已在波次中的订单:波次存在进行中的拣货任务时无法安全摘除,跳过转换 + const waveBoundRows = convertedRows.filter(row => Number(row && row.wave_id || 0) > 0); + if (waveBoundRows.length > 0) { + const waveIds = [ ...new Set(waveBoundRows.map(row => Number(row.wave_id))) ]; + const activeWaveRows = await ctx.model.query(` + SELECT DISTINCT ptw.wave_id + FROM wms_wave_pick_task_wave ptw + INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id + WHERE ptw.wave_id IN (:waveIds) + AND pt.status IN (0, 1) + `, { + replacements: { waveIds }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + const activeWaveIdSet = new Set((Array.isArray(activeWaveRows) ? activeWaveRows : []) + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)); + + if (activeWaveIdSet.size > 0) { + notConvertedWaveIds = [ ...activeWaveIdSet ].sort((a, b) => a - b); + const retainedRows = []; + for (const row of convertedRows) { + const waveId = Number(row && row.wave_id || 0); + if (waveId > 0 && activeWaveIdSet.has(waveId)) { + skippedReasons.push({ + order_id: Number(row.id), + delivery_order_code: String(row.delivery_order_code || '').trim(), + reason: '订单所在波次存在进行中的拣货任务,不允许转B2B', + }); + continue; + } + retainedRows.push(row); + } + + convertedRows.length = 0; + convertedRows.push(...retainedRows); + } + } + + if (convertedRows.length > 0) { + const convertedOrderIds = convertedRows.map(row => Number(row.id)); + const now = new Date(); + + await orderModel.update( + { is_b2b: 'Y', updated_at: now }, + { + where: { + id: { [Op.in]: convertedOrderIds }, + warehouse_id: normalizedWarehouseId, + }, + transaction, + } + ); + + // 写入 B2B 作业明细(uk_warehouse_order 唯一): + // 正常流程为创建新行;并发/重复转换命中同一行时重置作业字段(取消 B2B 为物理删除,无历史行恢复) + const b2bModel = ctx.model.OrderB2b; + for (const row of convertedRows) { + const orderId = Number(row.id); + const baseFields = { + warehouse_id: normalizedWarehouseId, + order_id: orderId, + }; + const existing = await b2bModel.findOne({ + where: { + warehouse_id: normalizedWarehouseId, + order_id: orderId, + }, + transaction, + }); + if (existing) { + await existing.update({ + total_box_count: 0, + pickup_plate_number: null, + prep_remark: null, + prep_duration_seconds: 0, + prep_at: null, + is_picked_up: 'N', + picked_up_at: null, + ...baseFields, + }, { transaction }); + } else { + await b2bModel.create({ + ...baseFields, + created_at: now, + }, { transaction }); + } + } + + // 已在波次中的订单(含库内抓取进波次的订单):转 B2B 后必须从波次摘除, + // 清空波次字段、重排 wave_index、回写波次统计(空波次置 wave_status=-1) + const waveBoundConvertedRows = convertedRows.filter(row => Number(row && row.wave_id || 0) > 0); + if (waveBoundConvertedRows.length > 0) { + waveDetachResult = await ctx.service.systemMethods.order.wave.detachOrdersFromWavesInTransaction({ + warehouseId: normalizedWarehouseId, + orderIds: waveBoundConvertedRows.map(row => Number(row.id)), + orderModel, + transaction, + }); + for (const orderId of waveDetachResult.removed_order_ids) { + waveRemovalLogItems.push({ + orderId, + waveNo: String(waveDetachResult.wave_no_map.get(orderId) || '').trim(), + }); + } + } + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + // 操作日志在事务提交后写入,失败不影响主流程 + for (const row of convertedRows) { + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: Number(row.id), + operationCode: ORDER_B2B_CONVERT_OPERATION_CODE, + operationAction: 'UPDATE', + changeSummary: '订单转为B2B订单', + operator, + extras: { + warehouseId: normalizedWarehouseId, + orderId: Number(row.id), + orderNo: String(row.delivery_order_code || '').trim(), + message: '订单转为B2B订单', + }, + beforeChanges: null, + }); + } catch (error) { + ctx.logger.warn(`[orderB2b.convertOrdersToB2b] 写入操作日志失败,不影响业务, orderId=${row.id}, error=${error.message}`); + } + } + + // 波次摘除日志在事务提交后写入,失败不影响主流程 + for (const item of waveRemovalLogItems) { + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: Number(item.orderId), + operationCode: 'ORDER_WAVE_REMOVE', + operationAction: 'UPDATE', + changeSummary: `订单从波次 ${item.waveNo || '未知波次'} 中移除(转B2B)`, + operator, + extras: { + warehouseId: normalizedWarehouseId, + orderId: Number(item.orderId), + waveNo: item.waveNo, + reason: 'convertToB2b', + message: `订单从波次 ${item.waveNo || '未知波次'} 中移除(转B2B)`, + }, + beforeChanges: null, + }); + } catch (error) { + ctx.logger.warn(`[orderB2b.convertOrdersToB2b] 写入波次移除日志失败,不影响业务, orderId=${item.orderId}, error=${error.message}`); + } + } + + const skippedOrderIds = [ ...new Set(skippedReasons.map(item => item.order_id)) ]; + return { + converted_order_ids: [ ...new Set(convertedRows.map(row => Number(row.id))) ], + converted_count: convertedRows.length, + skipped_order_ids: skippedOrderIds, + skipped_count: skippedOrderIds.length, + skipped_reasons: skippedReasons, + not_found_order_ids: notFoundOrderIds, + removed_from_wave_order_ids: waveDetachResult ? waveDetachResult.removed_order_ids : [], + affected_wave_ids: waveDetachResult ? waveDetachResult.affected_wave_ids : [], + emptied_wave_ids: waveDetachResult ? waveDetachResult.emptied_wave_ids : [], + active_pick_task_wave_ids: notConvertedWaveIds, + }; + } + + /** + * 判断订单是否满足转 B2B 条件,返回跳过原因;可转换时返回空串。 + * + * 条件:非已取消(status != cancel)、处于待处理阶段(step in [1,2,3])、 + * 未拣货(pick_status != fin)、未复核(recheck_status != fin)、 + * 未锁定(lock_status = none)、未拦截(intercept_status = none)、未转 B2B(is_b2b != Y)。 + * 打印状态不参与校验:已打印(print_status = fin)的订单同样允许转 B2B。 + * + * @param {Object} row 订单行。 + * @return {string} 跳过原因,可转换返回空字符串。 + */ + resolveConvertSkipReason(row = {}) { + // 已取消订单即使仍停留在待处理步骤也不允许转 B2B + if (String(row && row.status || '').trim() === 'cancel') { + return '订单已取消,不允许转B2B'; + } + + // 仅待处理阶段可转:4 配送中/已提交出库、5 已完成、9 已关闭一律拒绝 + const step = Number(row && row.step || 0); + if (!ORDER_B2B_CONVERT_ALLOWED_STEPS.has(step)) { + return ORDER_B2B_CONVERT_STEP_SKIP_REASONS[step] || `订单当前步骤(${step})不允许转B2B`; + } + + // 已进入作业流程的订单不允许转 B2B:拣货/复核完成后订单实物已分拣、单据已核对 + if (String(row && row.pick_status || '').trim() === 'fin') { + return '订单已拣货,不允许转B2B'; + } + + if (String(row && row.recheck_status || '').trim() === 'fin') { + return '订单已复核,不允许转B2B'; + } + + if (String(row && row.lock_status || 'none').trim() !== 'none') { + return '订单已锁定,不允许转B2B'; + } + + if (String(row && row.intercept_status || 'none').trim() !== 'none') { + return '订单已拦截,不允许转B2B'; + } + + if (String(row && row.is_b2b || '').trim() === 'Y') { + return '订单已是B2B订单'; + } + + return ''; + } + + /** + * 取消 B2B 出库:将 B2B 订单流转回正常订单。 + * + * 仅限待处理表(current 分表)中 is_b2b=Y 且未锁定、未拦截的订单(打印状态不限制); + * 不符合条件的订单跳过,不报错。事务内完成 is_b2b 置回 N 与 B2B 作业明细物理删除; + * 操作日志在事务提交后写入。 + * + * @param {Object} params 取消参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID数组。 + * @param {Object|null} [params.operator=null] 操作人 { id, name }。 + * @return {Promise} { canceled_order_ids, canceled_count, skipped_order_ids, + * skipped_count, skipped_reasons, not_found_order_ids } + */ + async cancelOrdersB2b(params = {}) { + const { ctx, app } = this; + const normalizedWarehouseId = Number(params && params.warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const rawIds = params && params.orderIds; + const normalizedOrderIds = [ ...new Set( + (Array.isArray(rawIds) ? rawIds : [ rawIds ]) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0) + ) ]; + if (normalizedOrderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + if (normalizedOrderIds.length > ORDER_B2B_CONVERT_BATCH_LIMIT) { + throw new Error(`单次最多取消 ${ORDER_B2B_CONVERT_BATCH_LIMIT} 个订单`); + } + + const operator = params && params.operator && typeof params.operator === 'object' + ? params.operator + : null; + const { Op } = app.Sequelize; + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(normalizedWarehouseId); + + const transaction = await ctx.model.transaction(); + const canceledRows = []; + const skippedReasons = []; + let notFoundOrderIds = []; + + try { + const lockRows = await orderModel.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'step', + 'print_status', 'lock_status', 'intercept_status', 'is_b2b', + ], + where: { + id: { [Op.in]: normalizedOrderIds }, + warehouse_id: normalizedWarehouseId, + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const rowMap = new Map((Array.isArray(lockRows) ? lockRows : []).map(row => [ Number(row && row.id || 0), row ])); + notFoundOrderIds = normalizedOrderIds.filter(orderId => !rowMap.has(orderId)); + + for (const orderId of normalizedOrderIds) { + const row = rowMap.get(orderId); + if (!row) { + continue; + } + + const skipReason = this.resolveCancelSkipReason(row); + if (skipReason) { + skippedReasons.push({ + order_id: orderId, + delivery_order_code: String(row.delivery_order_code || '').trim(), + reason: skipReason, + }); + continue; + } + + canceledRows.push(row); + } + + if (canceledRows.length > 0) { + const canceledOrderIds = canceledRows.map(row => Number(row.id)); + const now = new Date(); + + await orderModel.update( + { is_b2b: 'N', updated_at: now }, + { + where: { + id: { [Op.in]: canceledOrderIds }, + warehouse_id: normalizedWarehouseId, + }, + transaction, + } + ); + + // B2B 作业明细物理删除(不保留历史),关联条件固定为 warehouse_id + order_id + await ctx.model.OrderB2b.destroy({ + where: { + warehouse_id: normalizedWarehouseId, + order_id: { [Op.in]: canceledOrderIds }, + }, + transaction, + }); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + // 操作日志在事务提交后写入,失败不影响主流程 + for (const row of canceledRows) { + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: Number(row.id), + operationCode: ORDER_B2B_CANCEL_OPERATION_CODE, + operationAction: 'UPDATE', + changeSummary: '取消B2B出库,订单流转回正常订单', + operator, + extras: { + warehouseId: normalizedWarehouseId, + orderId: Number(row.id), + orderNo: String(row.delivery_order_code || '').trim(), + message: '取消B2B出库,订单流转回正常订单', + }, + beforeChanges: null, + }); + } catch (error) { + ctx.logger.warn(`[orderB2b.cancelOrdersB2b] 写入操作日志失败,不影响业务, orderId=${row.id}, error=${error.message}`); + } + } + + const skippedOrderIds = [ ...new Set(skippedReasons.map(item => item.order_id)) ]; + return { + canceled_order_ids: [ ...new Set(canceledRows.map(row => Number(row.id))) ], + canceled_count: canceledRows.length, + skipped_order_ids: skippedOrderIds, + skipped_count: skippedOrderIds.length, + skipped_reasons: skippedReasons, + not_found_order_ids: notFoundOrderIds, + }; + } + + /** + * 判断 B2B 订单是否满足取消条件,返回跳过原因;可取消时返回空串。 + * + * 条件:待处理(step != 0)、是 B2B(is_b2b = Y)、未锁定(lock_status = none)、 + * 未拦截(intercept_status = none)。打印状态不参与校验。 + * + * @param {Object} row 订单行。 + * @return {string} 跳过原因,可取消返回空字符串。 + */ + resolveCancelSkipReason(row = {}) { + if (Number(row && row.step || 0) === 0) { + return '订单待审核,不允许取消B2B'; + } + + if (String(row && row.is_b2b || '').trim() !== 'Y') { + return '订单不是B2B订单'; + } + + if (String(row && row.lock_status || 'none').trim() !== 'none') { + return '订单已锁定,不允许取消B2B'; + } + + if (String(row && row.intercept_status || 'none').trim() !== 'none') { + return '订单已拦截,不允许取消B2B'; + } + + return ''; + } +} + +module.exports = OrderB2bService; diff --git a/app/service/systems/order_delivery_archive.js b/app/service/systems/order_delivery_archive.js new file mode 100644 index 0000000..6958229 --- /dev/null +++ b/app/service/systems/order_delivery_archive.js @@ -0,0 +1,795 @@ +'use strict'; + +const MainService = require('../main'); + +/** 单批处理条数(与 current → dispatch 迁移保持一致,单批一个事务) */ +const MAX_BATCH_SIZE = 1000; + +/** 归档门槛:订单创建时间(create_at)距今超过该月数即归档 */ +const DEFAULT_ARCHIVE_AFTER_MONTHS = 4; + +/** 归档门槛:订单迁移进配送表(dispath_time)距今超过该月数即归档 */ +const DEFAULT_DISPATCH_STAY_MONTHS = 3; + +/** 单仓库单轮最多处理的批次数(异常情况下防止死循环) */ +const DEFAULT_MAX_BATCHES_PER_WAREHOUSE = 200; + +/** 单轮总时长上限(毫秒):超过后停止本轮,剩余订单下一轮继续 */ +const DEFAULT_MAX_RUN_MS = 30 * 60 * 1000; + +/** 单批查询超时(毫秒) */ +const DEFAULT_QUERY_TIMEOUT_MS = 60 * 1000; + +/** 单批事务遇到死锁/锁等待时的最大尝试次数 */ +const DEFAULT_BATCH_MAX_ATTEMPTS = 3; + +/** 重试基础退避毫秒数(按尝试次数线性放大) */ +const BATCH_RETRY_BASE_DELAY_MS = 50; + +/** 历史表位置标识(写入订单索引表 wms_order_id_location_{仓库}.location) */ +const HISTORY_LOCATION = 'history'; + +/** 配送域分表名匹配(仅 _dispatch 参与归档) */ +const DISPATCH_TABLE_PATTERN = /^wms_order_delivery_(\d+)_dispatch$/; + +/** 可重试的数据库锁错误码 */ +const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]); + +/** + * 按自然月回退时间(与 MySQL DATE_SUB(NOW(), INTERVAL n MONTH) 语义一致: + * 目标月份天数不足时取该月最后一天,如 3/31 回退 1 个月 → 2/28)。 + * + * @param {Date} baseDate 基准时间。 + * @param {number} months 回退月数(正整数)。 + * @return {Date} 回退后的时间。 + */ +function subtractMonths(baseDate, months) { + const base = baseDate instanceof Date ? baseDate : new Date(baseDate); + const normalizedMonths = Math.max(0, Math.floor(Number(months) || 0)); + + if (normalizedMonths === 0) { + return new Date(base.getTime()); + } + + const day = base.getDate(); + const target = new Date(base.getTime()); + // 先落到 1 号再回退月份,避免 9/30 回退 1 个月时被 JS 进位成 10/30 + target.setDate(1); + target.setMonth(target.getMonth() - normalizedMonths); + const daysInTargetMonth = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate(); + target.setDate(Math.min(day, daysInTargetMonth)); + + return target; +} + +/** + * 规范化正整数配置项。 + * + * @param {*} value 原始值。 + * @param {number} fallback 回退值。 + * @return {number} 规范化结果。 + */ +function normalizePositiveNumber(value, fallback) { + const parsed = Number(value); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; +} + +/** + * 配送表订单归档到历史表的同步服务。 + * + * 归档链路(单批一个事务,全部成功或全部回滚): + * 1. 从 `wms_order_delivery_{仓库}_dispatch` 按主键游标取候选订单 + * (create_at 距今 > 4 个月,或 dispath_time 距今 > 3 个月); + * 2. 复制订单行到 `_history`(剔除历史表不存在的 dispatch_lane / dispath_time, + * 写入 archive_time = 当前时刻),id 原样复制(多表共用 id 契约); + * 3. 同步复制商品明细 `wms_order_items_{仓库}_dispatch` → `_history`; + * 4. 更新订单索引表 `wms_order_id_location_{仓库}` 的 location 为 history; + * 5. 硬删除 dispatch 源行(先子表后主表)。 + * + * 幂等与可续跑:每批提交后源行已消失,重跑查询不会命中;若历史表已存在同 id + * 记录(上一轮中断或人工补数的残留),则跳过写入但仍清理源行,保证重复执行安全。 + */ +class OrderDeliveryArchiveService extends MainService { + /** + * 读取归档任务默认参数(config.orderDeliveryArchive 优先)。 + * + * @return {Object} 归档参数。 + */ + getArchiveDefaults() { + const config = (this.app && this.app.config && this.app.config.orderDeliveryArchive) || {}; + + return { + archiveAfterMonths: normalizePositiveNumber(config.archiveAfterMonths, DEFAULT_ARCHIVE_AFTER_MONTHS), + dispatchStayMonths: normalizePositiveNumber(config.dispatchStayMonths, DEFAULT_DISPATCH_STAY_MONTHS), + batchSize: Math.min( + normalizePositiveNumber(config.batchSize, MAX_BATCH_SIZE), + MAX_BATCH_SIZE + ), + maxBatchesPerWarehouse: normalizePositiveNumber( + config.maxBatchesPerWarehouse, + DEFAULT_MAX_BATCHES_PER_WAREHOUSE + ), + maxRunMs: normalizePositiveNumber(config.maxRunMs, DEFAULT_MAX_RUN_MS), + queryTimeoutMs: normalizePositiveNumber(config.queryTimeoutMs, DEFAULT_QUERY_TIMEOUT_MS), + batchMaxAttempts: normalizePositiveNumber(config.batchMaxAttempts, DEFAULT_BATCH_MAX_ATTEMPTS), + }; + } + + /** + * 合并调用方参数与默认参数。 + * + * @param {Object} options 调用方参数。 + * @return {Object} 合并后的参数。 + */ + buildArchiveOptions(options = {}) { + const defaults = this.getArchiveDefaults(); + const source = this.isPlainObject(options) ? options : {}; + + return { + archiveAfterMonths: normalizePositiveNumber(source.archiveAfterMonths, defaults.archiveAfterMonths), + dispatchStayMonths: normalizePositiveNumber(source.dispatchStayMonths, defaults.dispatchStayMonths), + batchSize: Math.min(normalizePositiveNumber(source.batchSize, defaults.batchSize), MAX_BATCH_SIZE), + maxBatchesPerWarehouse: normalizePositiveNumber(source.maxBatchesPerWarehouse, defaults.maxBatchesPerWarehouse), + maxRunMs: normalizePositiveNumber(source.maxRunMs, defaults.maxRunMs), + queryTimeoutMs: normalizePositiveNumber(source.queryTimeoutMs, defaults.queryTimeoutMs), + batchMaxAttempts: normalizePositiveNumber(source.batchMaxAttempts, defaults.batchMaxAttempts), + }; + } + + /** + * 构造归档时间门槛。 + * + * 使用应用进程时钟(而非数据库 NOW()):dispath_time / create_at 均由应用以 + * `new Date()` 写入,两者同源比较可避免数据库时区与服务时区不一致带来的偏差。 + * + * @param {Date} [now] 基准时间,默认当前时间。 + * @param {Object} options 归档参数。 + * @return {{ now: Date, createThreshold: Date, dispatchThreshold: Date }} 门槛集合。 + */ + buildArchiveThresholds(now = new Date(), options = {}) { + const resolved = this.buildArchiveOptions(options); + const baseTime = now instanceof Date ? now : new Date(); + + return { + now: baseTime, + createThreshold: subtractMonths(baseTime, resolved.archiveAfterMonths), + dispatchThreshold: subtractMonths(baseTime, resolved.dispatchStayMonths), + }; + } + + /** + * 规范化仓库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 listDispatchWarehouseIds() { + 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 = DISPATCH_TABLE_PATTERN.exec(String(tableName || '')); + return matched ? Number(matched[1]) : null; + }) + .filter(value => Number.isFinite(value) && value > 0))) + .sort((left, right) => left - right); + } + + /** + * 获取归档所需的模型集合。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 模型集合。 + */ + async getArchiveModels(warehouseId) { + const orderFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + const itemsFactory = this.ctx.model && this.ctx.model.OrderItemsFactory; + + if (!orderFactory + || typeof orderFactory.getDispatchModel !== 'function' + || typeof orderFactory.getHistoryModel !== 'function') { + throw new Error('订单工厂未初始化,无法获取配送表/历史表模型'); + } + + if (!itemsFactory + || typeof itemsFactory.getDispatchModel !== 'function' + || typeof itemsFactory.getHistoryModel !== 'function') { + throw new Error('订单商品工厂未初始化,无法获取配送表/历史表模型'); + } + + return { + dispatchOrderModel: await orderFactory.getDispatchModel(warehouseId), + historyOrderModel: await orderFactory.getHistoryModel(warehouseId), + dispatchItemModel: await itemsFactory.getDispatchModel(warehouseId), + historyItemModel: await itemsFactory.getHistoryModel(warehouseId), + }; + } + + /** + * 构造候选订单查询条件。 + * + * 仅取 _dispatch 分表内满足下列任一条件的订单: + * - 创建时间距今超过 archiveAfterMonths(默认 4 个月); + * - 迁移进配送表时间(dispath_time)距今超过 dispatchStayMonths(默认 3 个月)。 + * + * 注意:dispath_time 为 NULL 的存量订单由上述 OR 的另一分支(create_at)兜底, + * 无需显式 IS NULL 判断 —— SQL 三值逻辑下 `dispath_time < ?` 对 NULL 结果为 + * UNKNOWN,天然不会命中。 + * + * 游标条件用主键 id(条件列 create_at / dispath_time 均无索引), + * 避免生产大表上的全表扫描 + filesort。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} lastId 上一批处理到的最大 id(0 表示从头开始)。 + * @param {Object} thresholds 归档时间门槛。 + * @return {Object} Sequelize where 条件。 + */ + buildCandidateWhere(warehouseId, lastId, thresholds) { + const { Op } = this.ctx.app.Sequelize; + const normalizedLastId = Number(lastId); + + return { + warehouse_id: warehouseId, + id: Number.isFinite(normalizedLastId) && normalizedLastId > 0 + ? { [Op.gt]: normalizedLastId } + : { [Op.gt]: 0 }, + [Op.or]: [ + { dispath_time: { [Op.lt]: thresholds.dispatchThreshold } }, + { create_at: { [Op.lt]: thresholds.createThreshold } }, + ], + }; + } + + /** + * 构造 Sequelize 查询参数(事务 + 超时)。 + * + * @param {Object|null} transaction 事务对象。 + * @param {number} [queryTimeoutMs] 查询超时时间。 + * @return {Object} Sequelize 查询参数。 + */ + buildQueryOptions(transaction, queryTimeoutMs) { + const queryOptions = {}; + + if (transaction) { + queryOptions.transaction = transaction; + } + + const normalizedTimeoutMs = Number(queryTimeoutMs); + if (Number.isFinite(normalizedTimeoutMs) && normalizedTimeoutMs > 0) { + queryOptions.timeout = normalizedTimeoutMs; + } + + return queryOptions; + } + + /** + * 构造写入历史表的订单行。 + * + * 历史表比配送表少两列,必须剔除,否则 Sequelize 属性映射会静默丢弃/报错: + * - dispatch_lane:配送域车道,仅 dispatch 分表存在; + * - dispath_time:迁移进配送表的时间,仅 dispatch 分表存在 + * (迁出/迁入时刻统一由 archive_time 表达)。 + * + * @param {Object} row 配送表订单行。 + * @param {Date} archiveTime 归档时间。 + * @return {Object} 可写入历史表的订单行。 + */ + buildHistoryOrderRow(row, archiveTime) { + const payload = { ...(row || {}) }; + delete payload.dispatch_lane; + delete payload.dispath_time; + payload.archive_time = archiveTime; + + return payload; + } + + /** + * 构造写入历史表的商品明细行。 + * + * 商品配送表与历史表列完全一致(历史表仅多 archive_time),无需剔除字段。 + * + * @param {Object} row 配送表商品明细行。 + * @param {Date} archiveTime 归档时间。 + * @return {Object} 可写入历史表的商品明细行。 + */ + buildHistoryItemRow(row, archiveTime) { + return { + ...(row || {}), + archive_time: archiveTime, + }; + } + + /** + * 识别可重试的数据库锁错误。 + * + * @param {Error} error 运行时错误。 + * @return {{ retryable: boolean, category: string, message: string }} 分类结果。 + */ + getArchiveErrorInfo(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 {Object} transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async rollbackQuietly(transaction) { + if (!transaction || typeof transaction.rollback !== 'function') { + return; + } + + try { + await transaction.rollback(); + } catch (error) { + this.ctx.logger.warn(`[archive-dispatch-to-history] 事务回滚失败: ${error.message}`); + } + } + + /** + * 单批归档:查询候选 → 写历史表 → 更新位置指针 → 删除源行,全部在一个事务内完成。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [params] 单批参数。 + * @param {number} [params.lastId] 上一批处理到的最大 id。 + * @param {number} [params.batchSize] 单批条数。 + * @param {Object} [params.thresholds] 归档时间门槛。 + * @param {Object} [options] 归档参数。 + * @return {Promise} 单批结果。 + */ + async archiveDispatchBatch(warehouseId, params = {}, options = {}) { + const resolved = this.buildArchiveOptions(options); + const normalizedWarehouseId = Number(warehouseId); + + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('仓库ID不能为空'); + } + + const batchSize = Math.min(normalizePositiveNumber(params.batchSize, resolved.batchSize), MAX_BATCH_SIZE); + const lastId = Number(params.lastId) > 0 ? Number(params.lastId) : 0; + const thresholds = params.thresholds || this.buildArchiveThresholds(new Date(), resolved); + const archiveTime = new Date(); + const { Op } = this.ctx.app.Sequelize; + + // 序列表初始化可能执行 DDL(隐式提交),必须在事务外完成: + // 位置指针与历史表写入必须同事务原子完成,无索引表宁可整批失败重试。 + await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(normalizedWarehouseId); + + const transaction = await this.ctx.model.transaction(); + + try { + const models = await this.getArchiveModels(normalizedWarehouseId); + + // 加行锁读取候选:归档会删除源行,锁住候选可避免与并发修改(如拦截确认) + // 交错导致"归档了旧值、删掉了新值"。 + const candidateRows = await models.dispatchOrderModel.findAll({ + where: this.buildCandidateWhere(normalizedWarehouseId, lastId, thresholds), + order: [[ 'id', 'ASC' ]], + limit: batchSize, + raw: true, + lock: transaction.LOCK.UPDATE, + ...this.buildQueryOptions(transaction, resolved.queryTimeoutMs), + }); + + const rows = Array.isArray(candidateRows) ? candidateRows : []; + const orderIds = Array.from(new Set(rows + .map(row => Number(row && row.id)) + .filter(value => Number.isFinite(value) && value > 0))); + + if (orderIds.length === 0) { + await transaction.commit(); + + return { + warehouseId: normalizedWarehouseId, + lastId, + maxCandidateId: lastId, + selectedCount: 0, + archivedCount: 0, + alreadyArchivedCount: 0, + itemsSelectedCount: 0, + itemsArchivedCount: 0, + hasMore: false, + }; + } + + const maxCandidateId = Math.max(...orderIds); + + // 幂等保护:历史表已存在同 id 记录(上一轮中断残留 / 人工补数)时不再重复写入, + // 但仍清理源行,保证本任务重复执行或跨轮次执行结果一致。 + const existingHistoryRows = await models.historyOrderModel.findAll({ + where: { id: { [Op.in]: orderIds } }, + attributes: [ 'id' ], + raw: true, + ...this.buildQueryOptions(transaction, resolved.queryTimeoutMs), + }); + const existingHistoryIdSet = new Set((Array.isArray(existingHistoryRows) ? existingHistoryRows : []) + .map(row => Number(row && row.id))); + const rowsToArchive = rows.filter(row => !existingHistoryIdSet.has(Number(row.id))); + + // 商品明细:按 order_id 一并搬迁(子表同步迁入) + const dispatchItems = await models.dispatchItemModel.findAll({ + where: { order_id: { [Op.in]: orderIds } }, + order: [[ 'id', 'ASC' ]], + raw: true, + ...this.buildQueryOptions(transaction, resolved.queryTimeoutMs), + }); + const itemRows = Array.isArray(dispatchItems) ? dispatchItems : []; + const itemIds = Array.from(new Set(itemRows + .map(row => Number(row && row.id)) + .filter(value => Number.isFinite(value) && value > 0))); + + let itemsToArchive = itemRows; + if (itemIds.length > 0) { + const existingHistoryItems = await models.historyItemModel.findAll({ + where: { id: { [Op.in]: itemIds } }, + attributes: [ 'id' ], + raw: true, + ...this.buildQueryOptions(transaction, resolved.queryTimeoutMs), + }); + const existingItemIdSet = new Set((Array.isArray(existingHistoryItems) ? existingHistoryItems : []) + .map(row => Number(row && row.id))); + itemsToArchive = itemRows.filter(row => !existingItemIdSet.has(Number(row.id))); + } + + if (rowsToArchive.length > 0) { + await models.historyOrderModel.bulkCreate( + rowsToArchive.map(row => this.buildHistoryOrderRow(row, archiveTime)), + this.buildQueryOptions(transaction, resolved.queryTimeoutMs) + ); + } + + if (itemsToArchive.length > 0) { + await models.historyItemModel.bulkCreate( + itemsToArchive.map(row => this.buildHistoryItemRow(row, archiveTime)), + this.buildQueryOptions(transaction, resolved.queryTimeoutMs) + ); + } + + // 订单索引表位置指针 dispatch → history,与历史表写入同事务, + // 保证「订单去向」与数据所在表位原子一致。 + const locationFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!locationFactory || typeof locationFactory.updateOrderLocation !== 'function') { + throw new Error('订单工厂缺少 updateOrderLocation,无法同步订单索引表位置'); + } + + for (const orderId of orderIds) { + await locationFactory.updateOrderLocation(orderId, normalizedWarehouseId, HISTORY_LOCATION, transaction); + } + + // 删除源行:先子表后主表 + if (itemIds.length > 0) { + await models.dispatchItemModel.destroy({ + where: { id: { [Op.in]: itemIds } }, + ...this.buildQueryOptions(transaction, resolved.queryTimeoutMs), + }); + } + + await models.dispatchOrderModel.destroy({ + where: { id: { [Op.in]: orderIds } }, + ...this.buildQueryOptions(transaction, resolved.queryTimeoutMs), + }); + + await transaction.commit(); + + return { + warehouseId: normalizedWarehouseId, + lastId: maxCandidateId, + maxCandidateId, + selectedCount: orderIds.length, + archivedCount: rowsToArchive.length, + alreadyArchivedCount: orderIds.length - rowsToArchive.length, + itemsSelectedCount: itemIds.length, + itemsArchivedCount: itemsToArchive.length, + hasMore: rows.length >= batchSize, + }; + } catch (error) { + await this.rollbackQuietly(transaction); + throw error; + } + } + + /** + * 归档指定仓库的配送表订单(按主键游标循环分批,直到无候选或达到限额)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [options] 归档参数。 + * @param {Function} [options.onBatch] 单批完成回调(用于上报进度)。 + * @param {Function} [options.shouldStop] 外部中断判断回调。 + * @return {Promise} 仓库归档汇总。 + */ + async archiveDispatchOrdersForWarehouse(warehouseId, options = {}) { + const resolved = this.buildArchiveOptions(options); + const normalizedWarehouseId = Number(warehouseId); + + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('仓库ID不能为空'); + } + + const thresholds = options.thresholds || this.buildArchiveThresholds(new Date(), resolved); + const deadlineAt = options.deadlineAt > 0 ? Number(options.deadlineAt) : 0; + const onBatch = typeof options.onBatch === 'function' ? options.onBatch : null; + const shouldStop = typeof options.shouldStop === 'function' ? options.shouldStop : null; + + const summary = { + warehouseId: normalizedWarehouseId, + batches: 0, + selectedCount: 0, + archivedCount: 0, + alreadyArchivedCount: 0, + itemsArchivedCount: 0, + failedBatches: 0, + failedCount: 0, + lastId: Number(options.lastId) > 0 ? Number(options.lastId) : 0, + stopReason: '', + }; + + for (let batchIndex = 0; batchIndex < resolved.maxBatchesPerWarehouse; batchIndex++) { + if (shouldStop && shouldStop()) { + summary.stopReason = 'external_stop'; + break; + } + + if (deadlineAt > 0 && Date.now() >= deadlineAt) { + summary.stopReason = 'run_budget_exhausted'; + break; + } + + let batchResult = null; + let lastError = null; + + for (let attempt = 1; attempt <= resolved.batchMaxAttempts; attempt++) { + try { + batchResult = await this.archiveDispatchBatch(normalizedWarehouseId, { + lastId: summary.lastId, + batchSize: resolved.batchSize, + thresholds, + }, resolved); + break; + } catch (error) { + lastError = error; + const errorInfo = this.getArchiveErrorInfo(error); + + if (!errorInfo.retryable || attempt >= resolved.batchMaxAttempts) { + break; + } + + this.ctx.logger.warn( + `[archive-dispatch-to-history] 仓库 ${normalizedWarehouseId} 第 ${batchIndex + 1} 批遇到 ${errorInfo.category},` + + `重试 ${attempt}/${resolved.batchMaxAttempts}: ${errorInfo.message}` + ); + await new Promise(resolve => setTimeout(resolve, BATCH_RETRY_BASE_DELAY_MS * attempt)); + } + } + + if (!batchResult) { + // 单批彻底失败:记录后越过该批(游标推进到候选范围内已知的最大 id), + // 避免整轮卡死在同一批;未迁移的行保留在配送表,下一轮继续尝试。 + summary.failedBatches += 1; + summary.stopReason = 'batch_failure'; + this.ctx.logger.error( + `[archive-dispatch-to-history] 仓库 ${normalizedWarehouseId} 第 ${batchIndex + 1} 批归档失败,已跳过该批: ` + + `${lastError ? lastError.message : 'unknown error'}` + ); + + const skippedLastId = await this.resolveFailureCursor(normalizedWarehouseId, summary.lastId, thresholds, resolved); + summary.failedCount += skippedLastId.failedCount; + summary.lastId = skippedLastId.lastId; + + if (!skippedLastId.advanced) { + break; + } + + continue; + } + + summary.batches += 1; + summary.selectedCount += batchResult.selectedCount; + summary.archivedCount += batchResult.archivedCount; + summary.alreadyArchivedCount += batchResult.alreadyArchivedCount; + summary.itemsArchivedCount += batchResult.itemsArchivedCount; + summary.lastId = batchResult.lastId; + + if (onBatch) { + await onBatch({ ...batchResult, batchIndex: batchIndex + 1, summary: { ...summary } }); + } + + // 未取满一批(hasMore=false)说明候选已清空;取满但下一轮可能仍有候选,继续循环 + if (batchResult.selectedCount === 0 || !batchResult.hasMore) { + summary.stopReason = 'no_more_candidates'; + break; + } + } + + if (!summary.stopReason) { + summary.stopReason = 'max_batches_reached'; + } + + return summary; + } + + /** + * 单批失败后推进游标:取该批候选范围内的最大 id,返回下一次查询起点。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} lastId 当前游标。 + * @param {Object} thresholds 归档时间门槛。 + * @param {Object} options 归档参数。 + * @return {Promise<{ lastId: number, failedCount: number, advanced: boolean }>} 游标结果。 + */ + async resolveFailureCursor(warehouseId, lastId, thresholds, options) { + try { + const models = await this.getArchiveModels(warehouseId); + const rows = await models.dispatchOrderModel.findAll({ + where: this.buildCandidateWhere(warehouseId, lastId, thresholds), + attributes: [ 'id' ], + order: [[ 'id', 'ASC' ]], + limit: options.batchSize, + raw: true, + ...this.buildQueryOptions(null, options.queryTimeoutMs), + }); + const idList = (Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.id)) + .filter(value => Number.isFinite(value) && value > 0); + + if (idList.length === 0) { + return { lastId, failedCount: 0, advanced: false }; + } + + return { + lastId: Math.max(...idList), + failedCount: idList.length, + advanced: true, + }; + } catch (error) { + this.ctx.logger.error(`[archive-dispatch-to-history] 推进失败游标时查询失败: ${error.message}`); + return { lastId, failedCount: 0, advanced: false }; + } + } + + /** + * 归档全部(或指定)仓库的配送表订单。 + * + * 每批一个事务、失败仅推进游标不中断整体,因此任务中断后重新执行即可续跑: + * 已迁移的行已从配送表删除,不会重复处理。 + * + * @param {Object} [data] 请求参数。 + * @param {number|Array} [data.warehouseId] 单个仓库ID或仓库ID列表。 + * @param {Array} [data.warehouseIds] 仓库ID列表。 + * @param {Object} [options] 归档参数(可覆盖 config.orderDeliveryArchive)。 + * @param {Function} [options.onBatch] 单批完成回调。 + * @param {Function} [options.onWarehouseDone] 单仓库完成回调。 + * @return {Promise} 归档汇总结果。 + */ + async archiveDispatchOrdersToHistory(data = {}, options = {}) { + const resolved = this.buildArchiveOptions(options); + const requestData = this.isPlainObject(data) ? data : {}; + const explicitWarehouseIds = this.normalizeWarehouseIds(requestData); + const warehouseIds = explicitWarehouseIds.length > 0 + ? explicitWarehouseIds + : await this.listDispatchWarehouseIds(); + + const startedAt = Date.now(); + const deadlineAt = startedAt + resolved.maxRunMs; + const thresholds = this.buildArchiveThresholds(new Date(startedAt), resolved); + const results = []; + + let totalSelected = 0; + let totalArchived = 0; + let totalAlreadyArchived = 0; + let totalItemsArchived = 0; + let totalFailedBatches = 0; + let totalFailedCount = 0; + + for (const warehouseId of warehouseIds) { + if (Date.now() >= deadlineAt) { + results.push({ + warehouseId, + batches: 0, + selectedCount: 0, + archivedCount: 0, + alreadyArchivedCount: 0, + itemsArchivedCount: 0, + failedBatches: 0, + failedCount: 0, + lastId: 0, + stopReason: 'run_budget_exhausted', + }); + continue; + } + + const warehouseResult = await this.archiveDispatchOrdersForWarehouse(warehouseId, { + ...resolved, + thresholds, + deadlineAt, + onBatch: options.onBatch, + shouldStop: options.shouldStop, + }); + + results.push(warehouseResult); + + totalSelected += warehouseResult.selectedCount; + totalArchived += warehouseResult.archivedCount; + totalAlreadyArchived += warehouseResult.alreadyArchivedCount; + totalItemsArchived += warehouseResult.itemsArchivedCount; + totalFailedBatches += warehouseResult.failedBatches; + totalFailedCount += warehouseResult.failedCount; + + if (typeof options.onWarehouseDone === 'function') { + await options.onWarehouseDone(warehouseResult); + } + } + + const backlogRemaining = results.some(result => result.stopReason === 'run_budget_exhausted'); + + return { + warehouseIds, + batchSize: resolved.batchSize, + archiveAfterMonths: resolved.archiveAfterMonths, + dispatchStayMonths: resolved.dispatchStayMonths, + thresholds: { + createThreshold: thresholds.createThreshold.toISOString(), + dispatchThreshold: thresholds.dispatchThreshold.toISOString(), + }, + elapsedMs: Date.now() - startedAt, + totalSelected, + totalArchived, + totalAlreadyArchived, + totalItemsArchived, + totalFailedBatches, + totalFailedCount, + backlogRemaining, + results, + }; + } +} + +module.exports = OrderDeliveryArchiveService; diff --git a/app/service/systems/order_delivery_migration.js b/app/service/systems/order_delivery_migration.js new file mode 100644 index 0000000..4a7f91f --- /dev/null +++ b/app/service/systems/order_delivery_migration.js @@ -0,0 +1,702 @@ +'use strict'; + +const MainService = require('../main'); + +const OUTBOUND_STATUS = 'fin'; +const OUTBOUND_STATUS_TIMEOUT = 'timeout'; +const OUTBOUND_STEP = 4; +const OUTBOUND_SYNC_STEPS = [ OUTBOUND_STEP, 9 ]; +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' ]); +const DEFAULT_OUTBOUND_STATUSES = [ OUTBOUND_STATUS, 'padding' ]; + +/** + * 订单出库后迁移到配送表的同步服务。 + */ +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: DEFAULT_OUTBOUND_STATUSES, + 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 = DEFAULT_OUTBOUND_STATUSES) { + 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 : DEFAULT_OUTBOUND_STATUSES; + } + + /** + * 构造 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, + 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}`; + } + + /** + * 构造配送表插入行。 + * + * 写入配送表时追加 dispath_time(当前时间),用于记录订单迁移进配送表的时间; + * 仅配送表写入该字段,源表数据不受影响。 + * + * @param {Object} row 当前订单工作台数据。 + * @return {Object} 可写入配送表的数据。 + */ + buildDispatchRow(row) { + const payload = { ...(row || {}) }; + delete payload.dispatch_lane; + + return { + ...payload, + dispatch_lane: DISPATCH_LANE, + dispath_time: new Date(), + }; + } + + /** + * 构造商品明细迁移行。 + * + * @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; + + // 序列表初始化可能执行 DDL(隐式提交),必须在事务外完成。 + // 初始化失败直接终止迁移:位置指针与配送表写入必须在同一事务内原子完成, + // 没有序列表则无法保证索引一致,宁可迁移失败重试也不产生错位指针。 + await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(normalizedWarehouseId); + + 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: { + [Op.in]: OUTBOUND_SYNC_STEPS, + }, + }, + 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))); + let deliveryOrderCodes = Array.from(new Set(validSourceRows + .map(row => String(row.delivery_order_code || '').trim()) + .filter(Boolean))); + const sourceOrderIds = Array.from(sourceOrderRowMap.keys()); + const orderCodeMap = new Map(); // source order_id → renamed delivery_order_code + + 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 = []; + for (const row of validSourceRows) { + let tryCode = String(row.delivery_order_code || '').trim(); + const storeId = String(row.store_id || '').trim(); + const warehouseId = String(row.warehouse_id || '').trim(); + const originalKey = `${tryCode}::${storeId}::${warehouseId}`; + let seq = 2; + + while (existingKeySet.has(`${tryCode}::${storeId}::${warehouseId}`)) { + tryCode = `${String(row.delivery_order_code || '').trim()}-${seq}`; + seq++; + } + + const newKey = `${tryCode}::${storeId}::${warehouseId}`; + if (newKey !== originalKey) { + this.ctx.logger.info( + `[sync-outbound-orders-to-delivery] delivery_order_code 冲突,重命名: ${originalKey} → ${newKey}` + ); + orderCodeMap.set(Number(row.id), tryCode); + } + existingKeySet.add(newKey); + + const modifiedRow = tryCode !== String(row.delivery_order_code || '').trim() + ? { ...row, delivery_order_code: tryCode } + : row; + + rowsToCreate.push(this.buildDispatchRow(modifiedRow)); + } + + for (const renamedCode of orderCodeMap.values()) { + deliveryOrderCodes.push(renamedCode); + } + deliveryOrderCodes = Array.from(new Set(deliveryOrderCodes.filter(Boolean))); + + if (rowsToCreate.length > 0) { + assertMigrationDeadline('创建配送表订单'); + await targetOrderModel.bulkCreate(rowsToCreate, { + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + + // 更新序列表位置指针:current → dispatch。与上方 bulkCreate 处于同一事务, + // 任一步失败整体回滚,保证配送表数据与位置索引原子一致(存量订单自动补录, + // 显式 id 大于序列表水位时 MySQL 会自动推进,后续发号不会与存量 id 冲突)。 + const locationFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!locationFactory || typeof locationFactory.updateOrderLocation !== 'function') { + throw new Error('订单工厂缺少 updateOrderLocation,无法同步序列表位置指针'); + } + for (const row of rowsToCreate) { + await locationFactory.updateOrderLocation( + Number(row.id), + normalizedWarehouseId, + 'dispatch', + transaction + ); + } + } + + 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 renamedCode = orderCodeMap.get(Number(item.order_id)); + const key = renamedCode + ? `${renamedCode}::${String(sourceOrder.store_id || '').trim()}::${String(sourceOrder.warehouse_id || '').trim()}` + : this.buildDispatchKey(sourceOrder); + const targetOrderId = targetOrderIdMap.get(key); + + 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), + }); + } + + 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_export.js b/app/service/systems/order_export.js new file mode 100644 index 0000000..3412adf --- /dev/null +++ b/app/service/systems/order_export.js @@ -0,0 +1,1292 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); +const OrderBaseService = require('../systemMethods/order/base'); + +const DEFAULT_EXPORT_PAGE_SIZE = 1000; +const ORDER_EXPORT_QUERY_CONCURRENCY = 2; +const ORDER_EXPORT_MAX_ROWS_PER_SHEET = 1000000; +const ORDER_EXPORT_UPLOAD_MAX_SIZE_BYTES = 1024 * 1024 * 1024; // 订单导出上传文件上限 1GB +const ORDER_EXPORT_WORKSHEET_NAME = '订单导出'; +const ORDER_EXPORT_ALLOWED_TABLE_TYPES = new Set([ 'current', 'history', 'dispatch', 'outsourced' ]); +/** 订单导出中可见的 SN 状态(已登记/已核验/已重发),排除退回/作废 */ +const ORDER_EXPORT_VISIBLE_SN_STATUS_LIST = Object.freeze([ 'BOUND', 'VERIFIED', 'REISSUED' ]); +const ORDER_EXPORT_MODULE_MAP = Object.freeze({ + order: 'order', + revieworder: 'reviewOrder', + pendingorder: 'pendingOrder', + outboundorder: 'outboundOrder', + expectionorder: 'expectionOrder', + archiveorder: 'archiveOrder', + entrustorder: 'entrustOrder', + deliveryorder: 'deliveryOrder', + deliveryexpectionorder: 'deliveryExpectionOrder', +}); +const ORDER_EXPORT_COLUMNS = Object.freeze([ + { header: '系统订单号', key: 'id', width: 12 }, + { header: '外部订单号', key: 'delivery_order_code', width: 24 }, + { header: '平台单号', key: 'external_order_code', width: 24 }, + { header: '订单状态', key: 'status', width: 16 }, + { header: '拦截状态', key: 'intercept_status', width: 20 }, + { header: '抓取波次号', key: 'wave_no', width: 18 }, + { header: '波次序号', key: 'wave_index', width: 12 }, + { header: '货主', key: 'store_id', width: 20 }, + { header: '平台', key: 'sys_platform_name', width: 16 }, + { header: '来源', key: 'create_channel', width: 12 }, + { header: '店铺昵称', key: 'shop_nick', width: 20 }, + { header: '收件人', key: 'receiver_name', width: 16 }, + { header: '收件人电话', key: 'receiver_mobile', width: 18 }, + { header: '省', key: 'receiver_province', width: 10 }, + { header: '市', key: 'receiver_city', width: 10 }, + { header: '区', key: 'receiver_district', width: 10 }, + { header: '镇', key: 'receiver_town', width: 10 }, + { header: '详细地址', key: 'receiver_detail', width: 30 }, + { header: '商品明细', key: 'items_detail', width: 50 }, + { header: '物流公司', key: 'logistics_name', width: 18 }, + { header: '运单号', key: 'waybill_code', width: 24 }, + { header: '业务类型', key: 'business_type', width: 12 }, + { header: '运单接口', key: 'logistics_interface_name', width: 20 }, + { header: '包材ID', key: 'package_material_id', width: 14 }, + { header: '包材编码', key: 'package_material_code', width: 20 }, + { header: '包材名称', key: 'package_material_name', width: 20 }, + { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, + { header: '订单商品总类数', key: 'items_count', width: 16 }, + { header: '订单商品总数', key: 'items_total', width: 16 }, + { header: 'SN码数量', key: 'sn_quantity', width: 12 }, + { header: 'SN码汇总', key: 'sn_codes_summary', width: 60 }, + { header: '商品重量', key: 'items_weight', width: 12 }, + { header: '称重重量(g)', key: 'weighing_weight', width: 14 }, + { header: '订单金额', key: 'total_amount', width: 14 }, + { header: '实收金额', key: 'got_amount', width: 14 }, + { header: '创建时间', key: 'create_at', width: 20 }, + { header: '支付时间', key: 'pay_time', width: 20 }, + { header: '发货时间', key: 'delivery_time', width: 20 }, + { header: '出库状态', key: 'outbound_status', width: 14 }, + { header: '复核状态', key: 'inspection_status', width: 14 }, + { header: '复核完成状态', key: 'recheck_status', width: 16 }, + { header: '复核时间', key: 'recheck_time', width: 20 }, + { header: '配货状态', key: 'post_status', width: 14 }, + { header: '打包状态', key: 'pack_status', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '买家留言', key: 'buyer_message', width: 30 }, + { header: '卖家留言', key: 'seller_message', width: 30 }, + { header: '归档时间', key: 'archive_time', width: 20 }, +]); + +/** 商品明细展开列配置(item 模式) */ +const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ + { header: '订单ID', key: 'id', width: 12 }, + { header: '订单号', key: 'delivery_order_code', width: 24 }, + { header: '外部单号', key: 'external_order_code', width: 24 }, + { header: '订单状态', key: 'status', width: 16 }, + { header: '拦截状态', key: 'intercept_status', width: 20 }, + { header: '波次号', key: 'wave_no', width: 18 }, + { header: '波次序号', key: 'wave_index', width: 12 }, + { header: '货主', key: 'store_id', width: 20 }, + { header: '平台', key: 'sys_platform_name', width: 16 }, + { header: '来源', key: 'create_channel', width: 12 }, + { header: '店铺昵称', key: 'shop_nick', width: 20 }, + { header: '收件人', key: 'receiver_name', width: 16 }, + { header: '收件人电话', key: 'receiver_mobile', width: 18 }, + { header: '省', key: 'receiver_province', width: 10 }, + { header: '市', key: 'receiver_city', width: 10 }, + { header: '区', key: 'receiver_district', width: 10 }, + { header: '镇', key: 'receiver_town', width: 10 }, + { header: '详细地址', key: 'receiver_detail', width: 30 }, + { header: '仓库商品名称', key: 'item_name', width: 30 }, + { header: '商品条码', key: 'item_barcode', width: 24 }, + { header: '商品图片', key: 'item_image', width: 40 }, + { header: '数量', key: 'item_quantity', width: 10 }, + { header: '物流公司', key: 'logistics_name', width: 18 }, + { header: '运单号', key: 'waybill_code', width: 30 }, + { header: '业务类型', key: 'business_type', width: 12 }, + { header: '运单接口', key: 'logistics_interface_name', width: 20 }, + { header: '包材ID', key: 'package_material_id', width: 14 }, + { header: '包材编码', key: 'package_material_code', width: 20 }, + { header: '包材名称', key: 'package_material_name', width: 20 }, + { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, + { header: '订单商品总类数', key: 'items_count', width: 16 }, + { header: '订单商品总数', key: 'items_total', width: 16 }, + { header: 'SN码数量', key: 'sn_quantity', width: 12 }, + { header: 'SN码', key: 'sn_codes', width: 60 }, + { header: '商品重量', key: 'items_weight', width: 12 }, + { header: '称重重量(g)', key: 'weighing_weight', width: 14 }, + { header: '订单金额', key: 'total_amount', width: 14 }, + { header: '实收金额', key: 'got_amount', width: 14 }, + { header: '创建时间', key: 'create_at', width: 20 }, + { header: '支付时间', key: 'pay_time', width: 20 }, + { header: '发货时间', key: 'delivery_time', width: 20 }, + { header: '出库状态', key: 'outbound_status', width: 14 }, + { header: '复核状态', key: 'inspection_status', width: 14 }, + { header: '复核完成状态', key: 'recheck_status', width: 16 }, + { header: '复核时间', key: 'recheck_time', width: 20 }, + { header: '配货状态', key: 'post_status', width: 14 }, + { header: '打包状态', key: 'pack_status', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '买家留言', key: 'buyer_message', width: 30 }, + { header: '卖家留言', key: 'seller_message', width: 30 }, + { header: '归档时间', key: 'archive_time', width: 20 }, +]); + +/** 全部可导出表头字段(waybill 与 item 两种模式的并集,用于入参校验) */ +const ORDER_EXPORT_ALL_COLUMN_HEADERS = Object.freeze( + new Set([ + ...ORDER_EXPORT_COLUMNS.map(column => column.header), + ...ORDER_EXPORT_ITEM_COLUMNS.map(column => column.header), + ]) +); + +/** 订单状态中文翻译映射 */ +const ORDER_STATUS_LABELS = Object.freeze({ + status: { + pedding: '待处理', + created: '已创建', + cancel: '已取消', + error: '异常', + finished: '已完成', + }, + outbound_status: { + none: '无', + padding: '待出库', + fin: '已完成', + timeout: '超时', + error: '异常', + }, + inspection_status: { + none: '无', + padding: '待检验', + running: '检验中', + fin: '已完成', + error: '异常', + }, + recheck_status: { + none: '无', + fin: '已完成', + }, + post_status: { + none: '无', + padding: '待配货', + fin: '已完成', + timeout: '超时', + error: '异常', + }, + pack_status: { + none: '无', + padding: '待打包', + fin: '已完成', + error: '异常', + }, +}); + +/** + * 订单导出系统服务。 + * 负责复用订单列表查询语义,按页拉取数据并流式写入本地 xlsx 后上传。 + */ +class OrderExportService extends OrderBaseService { + /** + * 获取单页导出数量。 + * @return {number} 单页导出数量。 + */ + getExportPageSize() { + return DEFAULT_EXPORT_PAGE_SIZE; + } + + /** + * 规范订单导出模块名。 + * @param {string} moduleName 原始模块名。 + * @return {string} 规范后的模块名;为空时返回空字符串。 + */ + normalizeExportModuleName(moduleName = '') { + const normalizedModuleName = String(moduleName || '').trim(); + if (!normalizedModuleName) { + return ''; + } + + const mappedModuleName = ORDER_EXPORT_MODULE_MAP[normalizedModuleName.toLowerCase()]; + if (!mappedModuleName) { + throw new Error(`不支持的订单导出模块: ${normalizedModuleName}`); + } + + return mappedModuleName; + } + + /** + * 根据表类型推导默认排序所使用的模块名。 + * @param {string} tableType 订单表类型。 + * @return {string} 用于排序默认值的模块名。 + */ + getSortModuleNameByTableType(tableType = 'current') { + switch (tableType) { + case 'history': + return 'archiveOrder'; + case 'dispatch': + return 'deliveryOrder'; + case 'outsourced': + return 'entrustOrder'; + case 'current': + default: + return 'order'; + } + } + + /** + * 解析订单导出目标,兼容 module/module_name 与 table_type 两种写法。 + * @param {Object} options 解析参数。 + * @param {string} [options.moduleName] 模块名。 + * @param {string} [options.tableType] 表类型。 + * @return {{ tableType: string, defaultWhereModuleName: string, sortModuleName: string }} 导出目标。 + */ + resolveExportTarget(options = {}) { + const safeOptions = this.isPlainObject(options) ? options : {}; + const moduleName = this.normalizeExportModuleName(safeOptions.moduleName || ''); + const rawTableType = String(safeOptions.tableType || '').trim(); + const tableTypeToken = rawTableType.toLowerCase(); + const moduleNameFromTableType = ORDER_EXPORT_ALLOWED_TABLE_TYPES.has(tableTypeToken) + ? '' + : this.normalizeExportModuleName(rawTableType); + const resolvedTableType = rawTableType + ? this.resolveOrderTableType({ tableType: rawTableType }) + : (moduleName ? this.getModuleConfig(moduleName).modelType : 'current'); + + if (moduleName && moduleNameFromTableType && moduleName !== moduleNameFromTableType) { + throw new Error(`module 与 table_type 不匹配: ${moduleName} / ${rawTableType}`); + } + + if (moduleName) { + const expectedTableType = this.getModuleConfig(moduleName).modelType; + if (expectedTableType !== resolvedTableType) { + throw new Error(`module ${moduleName} 仅支持 ${expectedTableType} 表,当前传入 ${resolvedTableType}`); + } + } + + return { + tableType: resolvedTableType, + defaultWhereModuleName: moduleName || moduleNameFromTableType || '', + sortModuleName: moduleName || moduleNameFromTableType || this.getSortModuleNameByTableType(resolvedTableType), + }; + } + + /** + * 获取订单导出列配置。 + * @param {string} [mode='waybill'] 导出模式:'waybill'(按运单展开)或 'item'(按商品明细展开)。 + * @param {Array} [selectedHeaders=[]] 表头字段白名单(中文);不传/空数组返回全部列。 + * @return {Array} 导出列配置。 + */ + getOrderExportColumns(mode = 'waybill', selectedHeaders = []) { + const columns = mode === 'item' ? ORDER_EXPORT_ITEM_COLUMNS : ORDER_EXPORT_COLUMNS; + const safeHeaders = Array.isArray(selectedHeaders) ? selectedHeaders : []; + const headerSet = new Set( + safeHeaders.map(header => String(header || '').trim()).filter(Boolean) + ); + if (headerSet.size === 0) { + return columns.map(column => ({ ...column })); + } + return columns + .filter(column => headerSet.has(column.header)) + .map(column => ({ ...column })); + } + + /** + * 校验并规范导出表头字段入参(中文表头数组)。 + * 白名单基于 ORDER_EXPORT_ALL_COLUMN_HEADERS(两模式列头并集), + * 新增列(如“来源”)在列配置中登记后即自动可用。 + * 不传/空数组返回空数组(表示输出全部列);存在非法表头时抛错。 + * @param {Array|*} rawColumns 原始入参。 + * @return {Array} 去重后的表头数组。 + */ + normalizeExportColumns(rawColumns) { + if (!Array.isArray(rawColumns)) { + return []; + } + + const selectedHeaders = [ ...new Set( + rawColumns.map(header => String(header || '').trim()).filter(Boolean) + ) ]; + const invalidHeaders = selectedHeaders.filter( + header => !ORDER_EXPORT_ALL_COLUMN_HEADERS.has(header) + ); + if (invalidHeaders.length > 0) { + throw new Error(`不支持的导出表头字段: ${invalidHeaders.join(', ')}`); + } + + return selectedHeaders; + } + + /** + * 生成订单导出文件名。 + * @param {Object} target 导出目标。 + * @return {string} 文件名。 + */ + buildOrderExportFilename(target = {}) { + const safeTarget = this.isPlainObject(target) ? target : {}; + const timestamp = new Date(); + const year = timestamp.getFullYear(); + const month = String(timestamp.getMonth() + 1).padStart(2, '0'); + const day = String(timestamp.getDate()).padStart(2, '0'); + const hour = String(timestamp.getHours()).padStart(2, '0'); + const minute = String(timestamp.getMinutes()).padStart(2, '0'); + const second = String(timestamp.getSeconds()).padStart(2, '0'); + const moduleTag = safeTarget.defaultWhereModuleName || safeTarget.tableType || 'current'; + + return `订单导出_${moduleTag}_${year}${month}${day}${hour}${minute}${second}.xlsx`; + } + + /** + * 生成上传 key。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} tableType 表类型。 + * @return {string} 上传 key。 + */ + buildUploadKey(warehouseId, tableType) { + const safeWarehouseId = String(warehouseId || 'unknown').trim() || 'unknown'; + const safeTableType = String(tableType || 'current').trim() || 'current'; + const randomToken = crypto.randomBytes(6).toString('hex'); + return `exports/order/${safeWarehouseId}/${safeTableType}/${Date.now()}_${randomToken}.xlsx`; + } + + /** + * 将模型行转换为普通对象。 + * @param {Object} row 模型行或普通对象。 + * @return {Object} 普通对象。 + */ + toPlainRow(row = {}) { + if (row && typeof row.get === 'function') { + return row.get({ plain: true }); + } + + return this.isPlainObject(row) ? { ...row } : {}; + } + + /** + * 规范导出单元格值。 + * @param {*} value 原始值。 + * @return {string|number} 规范后的值。 + */ + normalizeExportCellValue(value) { + if (value === null || value === undefined) { + return ''; + } + + if (Array.isArray(value)) { + return value.map(item => this.normalizeExportCellValue(item)).filter(Boolean).join(','); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (typeof value === 'object') { + return JSON.stringify(value); + } + + return value; + } + + /** + * 映射订单导出数据行。 + * - waybill 模式:按运单号展开,每个运单一组;商品总类数/商品总数仅主单号行体现,子单号行置 0。 + * - item 模式:按商品明细展开,每个商品一行;运单信息汇总填充。 + * @param {Object} orderRow 订单行。 + * @param {Object} [context] 导出上下文,包含批量查询的辅助数据。 + * @param {Map>} [context.itemsMap] 订单ID → 商品明细列表的映射。 + * @param {Map} [context.storeRemarkMap] 货主ID → 货主备注的映射。 + * @param {Map} [context.stockNameMap] stockId → 仓库商品名称的映射。 + * @param {Map} [context.barcodeMap] stockId → 商品条码(逗号拼接)的映射。 + * @param {Map} [context.imageUrlMap] stockId → 商品图片URL的映射。 + * @param {Map>} [context.expressMap] 订单ID → 运单行列表的映射。 + * @param {Map} [context.packageMaterialMap] package_material_id → 包材编码的映射。 + * @param {Set} [context.snStockIdSet] 启用序列号管理的 stockId 集合(用于统计 SN 码数量)。 + * @param {Map} [context.snCodesByOrderMap] 订单ID → 已登记 SN 码列表(订单级汇总)。 + * @param {Map>} [context.snCodesByItemMap] 订单ID → (明细ID → 已登记 SN 码列表)。 + * @param {string} [mode='waybill'] 导出模式:'waybill' 或 'item'。 + * @return {Array} 导出行数组。 + */ + mapOrderExportRow(orderRow = {}, context = {}, mode = 'waybill') { + const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; + const { + itemsMap, + storeRemarkMap, + stockNameMap, + barcodeMap, + imageUrlMap, + expressMap, + packageMaterialMap, + snStockIdSet, + snCodesByOrderMap, + snCodesByItemMap, + } = context; + const safeItemsMap = itemsMap instanceof Map ? itemsMap : new Map(); + const safeStoreRemarkMap = storeRemarkMap instanceof Map ? storeRemarkMap : new Map(); + const safeExpressMap = expressMap instanceof Map ? expressMap : new Map(); + const externalOrderCode = safeOrderRow.pre_delivery_order_code || safeOrderRow.source_order_codes || ''; + + /** + * 翻译状态字段为中文,未知值保留原始值。 + * @param {string} field 状态字段名。 + * @param {*} value 原始状态值。 + * @return {string} 翻译后的中文状态文本。 + */ + const translateStatus = (field, value) => { + const raw = String(value ?? '').trim(); + if (!raw) return ''; + const labelMap = ORDER_STATUS_LABELS[field]; + return labelMap && labelMap[raw] ? labelMap[raw] : raw; + }; + + /** + * 安全格式化日期字段,空值/无效值返回空字符串。 + * @param {*} value 日期原始值。 + * @return {string} 格式化后的日期字符串或空字符串。 + */ + const formatDateSafe = value => { + if (value === null || value === undefined || value === '' || value === 0) { + return ''; + } + const d = new Date(value); + if (isNaN(d.getTime()) || d.getTime() <= 0) { + return ''; + } + return this.app.formatDate(value); + }; + + const orderId = Number(safeOrderRow.id || 0); + const storeId = Number(safeOrderRow.store_id || 0); + const storeRemark = safeStoreRemarkMap.get(storeId) || ''; + const items = safeItemsMap.get(orderId) || []; + const safeStockNameMap = stockNameMap instanceof Map ? stockNameMap : new Map(); + const safeBarcodeMap = barcodeMap instanceof Map ? barcodeMap : new Map(); + const safeImageUrlMap = imageUrlMap instanceof Map ? imageUrlMap : new Map(); + const safeSnStockIdSet = snStockIdSet instanceof Set ? snStockIdSet : new Set(); + + /** + * 计算单个明细的 SN 码数量(仅序列号管理商品计入,取 plan_qty)。 + * @param {Object} item 订单明细。 + * @return {number} SN 码数量。 + */ + const resolveItemSnQuantity = item => { + const stockId = Number(item && item.stock_id || 0); + if (!safeSnStockIdSet.has(stockId)) { + return 0; + } + const planQty = Number(item && item.plan_qty); + return Number.isFinite(planQty) && planQty > 0 ? planQty : 0; + }; + + // 订单级 SN 码数量:明细中所有序列号管理商品的 plan_qty 合计(用于账单核对) + const orderSnQuantity = (Array.isArray(items) ? items : []) + .reduce((sum, item) => sum + resolveItemSnQuantity(item), 0); + + // 复核时登记的 SN 码(订单级汇总 + 明细级列表) + const safeSnCodesByOrderMap = snCodesByOrderMap instanceof Map ? snCodesByOrderMap : new Map(); + const safeSnCodesByItemMap = snCodesByItemMap instanceof Map ? snCodesByItemMap : new Map(); + const orderSnCodes = safeSnCodesByOrderMap.get(orderId) || []; + const itemSnCodesMap = safeSnCodesByItemMap.get(orderId) instanceof Map + ? safeSnCodesByItemMap.get(orderId) + : new Map(); + const joinSnCodes = codes => (Array.isArray(codes) ? codes.join(', ') : ''); + + const itemsDetail = Array.isArray(items) && items.length > 0 + ? items.map(item => { + const stockId = Number(item.stock_id || 0); + const warehouseItemName = stockId > 0 ? safeStockNameMap.get(stockId) : ''; + const displayName = warehouseItemName || item.item_name || ''; + return `${displayName} x${item.plan_qty || 1}`; + }).join('; ') + : ''; + + /** 订单公共字段(不含 items_detail,由各模式自行拼接) */ + const commonFields = { + id: this.normalizeExportCellValue(safeOrderRow.id), + delivery_order_code: this.normalizeExportCellValue(safeOrderRow.delivery_order_code), + external_order_code: this.normalizeExportCellValue(externalOrderCode), + status: translateStatus('status', safeOrderRow.status), + intercept_status: this.normalizeExportCellValue(safeOrderRow.intercept_status), + wave_no: this.normalizeExportCellValue(safeOrderRow.wave_no), + wave_index: this.normalizeExportCellValue(safeOrderRow.wave_index ?? 0), + store_id: this.normalizeExportCellValue(storeRemark || safeOrderRow.store_name || safeOrderRow.store_id), + sys_platform_name: this.normalizeExportCellValue(safeOrderRow.sys_platform_name), + create_channel: this.formatCreateChannelLabel(String(safeOrderRow.create_channel || '')), + shop_nick: this.normalizeExportCellValue(safeOrderRow.shop_nick), + receiver_name: this.normalizeExportCellValue(safeOrderRow.name || ''), + receiver_mobile: this.normalizeExportCellValue(safeOrderRow.mobile || safeOrderRow.tel || ''), + receiver_province: this.normalizeExportCellValue(safeOrderRow.province || ''), + receiver_city: this.normalizeExportCellValue(safeOrderRow.city || ''), + receiver_district: this.normalizeExportCellValue(safeOrderRow.area || ''), + receiver_town: this.normalizeExportCellValue(safeOrderRow.town || ''), + receiver_detail: this.normalizeExportCellValue(safeOrderRow.detail_address || ''), + logistics_name: this.normalizeExportCellValue(safeOrderRow.logistics_name), + items_count: this.normalizeExportCellValue(safeOrderRow.items_count), + items_total: this.normalizeExportCellValue(safeOrderRow.items_total), + sn_quantity: this.normalizeExportCellValue(orderSnQuantity), + sn_codes_summary: this.normalizeExportCellValue(joinSnCodes(orderSnCodes)), + items_weight: this.normalizeExportCellValue(safeOrderRow.items_weight), + total_amount: this.normalizeExportCellValue(safeOrderRow.total_amount), + got_amount: this.normalizeExportCellValue(safeOrderRow.got_amount), + remark: this.normalizeExportCellValue(safeOrderRow.remark), + buyer_message: this.normalizeExportCellValue(safeOrderRow.buyer_message), + seller_message: this.normalizeExportCellValue(safeOrderRow.seller_message), + create_at: formatDateSafe(safeOrderRow.create_at), + pay_time: formatDateSafe(safeOrderRow.pay_time), + delivery_time: formatDateSafe(safeOrderRow.delivery_time), + outbound_status: translateStatus('outbound_status', safeOrderRow.outbound_status), + inspection_status: translateStatus('inspection_status', safeOrderRow.inspection_status), + recheck_status: translateStatus('recheck_status', safeOrderRow.recheck_status), + recheck_time: formatDateSafe(safeOrderRow.recheck_time), + post_status: translateStatus('post_status', safeOrderRow.post_status), + pack_status: translateStatus('pack_status', safeOrderRow.pack_status), + archive_time: formatDateSafe(safeOrderRow.archive_time), + }; + + const expressList = safeExpressMap.get(orderId) || []; + + // ★ 模式B:按商品明细展开 + if (mode === 'item') { + const waybillSummary = expressList.map(e => e.waybill_code).filter(Boolean).join(', '); + const waybillFirstTime = expressList.length > 0 ? formatDateSafe(expressList[0].create_at) : ''; + const weightSummary = expressList.reduce((sum, e) => sum + (Number(e.weighing_weight) || 0), 0); + + const firstExp = expressList.length > 0 ? expressList[0] : null; + const businessType = firstExp ? (Number(firstExp.business_key) === 1 ? '主单号' : '子单号') : ''; + const interfaceName = firstExp ? String(firstExp.logistics_interface_name || '') : ''; + const materialId = firstExp ? (firstExp.package_material_id != null ? Number(firstExp.package_material_id) : '') : ''; + const safePackageMaterialMap = packageMaterialMap instanceof Map ? packageMaterialMap : new Map(); + const materialCode = materialId ? (safePackageMaterialMap.get(Number(materialId)) || '') : ''; + + if (items.length === 0) { + return [{ + ...commonFields, + item_name: '', + item_barcode: '', + item_image: '', + item_quantity: '', + sn_codes: '', + business_type: businessType, + logistics_interface_name: this.normalizeExportCellValue(interfaceName), + package_material_id: materialId, + package_material_code: this.normalizeExportCellValue(materialCode), + package_material_name: this.normalizeExportCellValue(firstExp ? firstExp.package_material_name_snapshot : ''), + waybill_code: waybillSummary, + waybill_allocated_at: waybillFirstTime, + weighing_weight: weightSummary || '', + }]; + } + + return items.map(item => { + const sid = Number(item.stock_id || 0); + return { + ...commonFields, + item_name: (sid > 0 ? safeStockNameMap.get(sid) : '') || item.item_name || '', + item_barcode: sid > 0 ? (safeBarcodeMap.get(sid) || '') : '', + item_image: sid > 0 ? (safeImageUrlMap.get(sid) || '') : '', + item_quantity: item.plan_qty || 1, + sn_quantity: resolveItemSnQuantity(item), + sn_codes: joinSnCodes(itemSnCodesMap.get(Number(item.id || 0)) || []), + business_type: businessType, + logistics_interface_name: this.normalizeExportCellValue(interfaceName), + package_material_id: materialId, + package_material_code: this.normalizeExportCellValue(materialCode), + package_material_name: this.normalizeExportCellValue(firstExp ? firstExp.package_material_name_snapshot : ''), + waybill_code: waybillSummary, + waybill_allocated_at: waybillFirstTime, + weighing_weight: weightSummary || '', + }; + }); + } + + // ★ 模式A(默认 waybill):按运单展开,保留 items_detail + const safePackageMaterialMap = packageMaterialMap instanceof Map ? packageMaterialMap : new Map(); + + if (expressList.length === 0) { + // 无运单的订单也输出一行(运单字段为空) + return [{ + ...commonFields, + items_detail: this.normalizeExportCellValue(itemsDetail), + waybill_code: '', + business_type: '', + logistics_interface_name: '', + package_material_id: '', + package_material_code: '', + package_material_name: '', + waybill_allocated_at: '', + weighing_weight: '', + }]; + } + + return expressList.map(exp => { + const isMainWaybill = Number(exp.business_key) === 1; + return { + ...commonFields, + items_detail: this.normalizeExportCellValue(itemsDetail), + // 商品总类数/商品总数为订单级数据,仅主单号行体现;子单号行置 0,避免与主单号重复 + items_count: isMainWaybill ? commonFields.items_count : 0, + items_total: isMainWaybill ? commonFields.items_total : 0, + sn_quantity: isMainWaybill ? commonFields.sn_quantity : 0, + sn_codes_summary: isMainWaybill ? commonFields.sn_codes_summary : '', + waybill_code: exp.waybill_code || '', + business_type: isMainWaybill ? '主单号' : '子单号', + logistics_interface_name: this.normalizeExportCellValue(exp.logistics_interface_name), + package_material_id: exp.package_material_id != null ? Number(exp.package_material_id) : '', + package_material_code: this.normalizeExportCellValue( + exp.package_material_id != null ? (safePackageMaterialMap.get(Number(exp.package_material_id)) || '') : '' + ), + package_material_name: this.normalizeExportCellValue(exp.package_material_name_snapshot), + waybill_allocated_at: formatDateSafe(exp.create_at), + weighing_weight: exp.weighing_weight != null ? Number(exp.weighing_weight) : '', + }; + }); + } + + /** + * 上传本地导出文件并记录文件信息。 + * @param {Object} options 上传参数。 + * @param {string} options.filePath 本地文件路径。 + * @param {string} options.filename 文件名。 + * @param {number|string} options.warehouseId 仓库ID。 + * @param {string} options.tableType 表类型。 + * @return {Promise} 上传结果。 + */ + async uploadOrderExportFile(options = {}) { + const safeOptions = this.isPlainObject(options) ? options : {}; + const { + filePath, + filename, + warehouseId, + tableType, + } = safeOptions; + const uploadService = this.ctx?.service?.systems?.upload; + + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const uploadKey = this.buildUploadKey(warehouseId, tableType); + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + maxSizeBytes: ORDER_EXPORT_UPLOAD_MAX_SIZE_BYTES, + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'orderExport', + businessId: `${warehouseId}:${tableType}`, + uploaderType: this.ctx?.user?.role || 'system_api', + uploaderDept: this.ctx?.user?.department || '', + }); + } + + return { + filename, + fileKey: uploadResult.fileName, + url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '', + cdnUrl: uploadResult.cdnUrl || uploadResult.url || '', + cosUrl: uploadResult.cosUrl || '', + fileRecord: fileRecord?.data || fileRecord || null, + }; + } + + /** + * 构建单个导出页:分页查询订单 + 批量富化 + 映射导出行。 + * @param {Object} options 分页构建参数。 + * @param {number} options.page 页码(从 1 开始)。 + * @param {number} options.pageSize 分页大小。 + * @param {Object} options.queryWhere 查询条件。 + * @param {Array>} options.order 排序参数。 + * @param {Object} options.orderModel 订单头模型。 + * @param {Object} options.target 导出目标。 + * @param {number|string} options.warehouseId 仓库ID。 + * @param {string} options.mode 导出模式:'waybill' 或 'item'。 + * @return {Promise<{exportRows: Array, orderCount: number}>} 导出行数组与订单数。 + */ + async buildOrderExportPage(options = {}) { + const safeOptions = this.isPlainObject(options) ? options : {}; + const { + page, + pageSize, + queryWhere, + order, + orderModel, + target, + warehouseId, + mode, + } = safeOptions; + + const rows = await orderModel.findAll({ + where: queryWhere, + limit: pageSize, + offset: (page - 1) * pageSize, + order, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + return { exportRows: [], orderCount: 0 }; + } + + const normalizedRows = rows.map(row => + this.normalizeOrderListItem(this.toPlainRow(row)) + ); + const rowsWithWaveIndex = await this.attachOrderWaveIndex(normalizedRows); + + const orderIds = rowsWithWaveIndex.map(r => Number(r.id || 0)).filter(id => id > 0); + + // 批量查询商品明细(wms_order_items) + const itemsMap = new Map(); + if (orderIds.length > 0) { + try { + const itemsModel = await this.getOrderItemsModelByTableType(target.tableType, warehouseId); + const itemsRows = await itemsModel.findAll({ + where: { order_id: { [this.app.Sequelize.Op.in]: orderIds } }, + attributes: [ 'id', 'order_id', 'item_name', 'plan_qty', 'stock_id' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const item of (Array.isArray(itemsRows) ? itemsRows : [])) { + const oid = Number(item.order_id || 0); + if (oid > 0) { + if (!itemsMap.has(oid)) { + itemsMap.set(oid, []); + } + itemsMap.get(oid).push(item); + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询订单商品明细失败: ${err.message}`); + } + } + + // 批量查询序列号管理商品(用于导出 SN码数量:明细中 is_sn_mgmt='Y' 商品的 plan_qty 合计) + const snStockIdSet = new Set(); + if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { + try { + const snStockIds = [ + ...new Set( + [ ...itemsMap.values() ] + .flat() + .map(item => Number(item.stock_id || 0)) + .filter(id => id > 0) + ), + ]; + if (snStockIds.length > 0) { + const snRows = await this.ctx.model.StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: snStockIds }, + warehouse_id: warehouseId, + is_sn_mgmt: 'Y', + }, + attributes: [ 'id' ], + raw: true, + paranoid: false, + }); + for (const snRow of (Array.isArray(snRows) ? snRows : [])) { + const sid = Number(snRow.id || 0); + if (sid > 0) { + snStockIdSet.add(sid); + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询序列号管理商品失败: ${err.message}`); + } + } + + // 批量查询复核时登记的 SN 码(wms_order_item_sn),用于导出 SN 码汇总 / 商品行 SN 码列表 + const snCodesByOrderMap = new Map(); + const snCodesByItemMap = new Map(); + if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.OrderItemSn) { + try { + const { Op } = this.app.Sequelize; + const snRows = await this.ctx.model.OrderItemSn.findAll({ + where: { + warehouse_id: warehouseId, + order_id: { [Op.in]: orderIds }, + sn_status: { [Op.in]: ORDER_EXPORT_VISIBLE_SN_STATUS_LIST }, + }, + attributes: [ 'order_id', 'order_item_id', 'sn_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + for (const snRow of (Array.isArray(snRows) ? snRows : [])) { + const snOrderId = Number(snRow.order_id || 0); + const snItemId = Number(snRow.order_item_id || 0); + const snCode = String(snRow.sn_code || '').trim(); + if (snOrderId <= 0 || !snCode) { + continue; + } + + if (!snCodesByOrderMap.has(snOrderId)) { + snCodesByOrderMap.set(snOrderId, []); + } + snCodesByOrderMap.get(snOrderId).push(snCode); + + if (snItemId > 0) { + if (!snCodesByItemMap.has(snOrderId)) { + snCodesByItemMap.set(snOrderId, new Map()); + } + const itemSnMap = snCodesByItemMap.get(snOrderId); + if (!itemSnMap.has(snItemId)) { + itemSnMap.set(snItemId, []); + } + itemSnMap.get(snItemId).push(snCode); + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询订单SN码失败: ${err.message}`); + } + } + + // 批量查询仓库商品名称、条码与图片(复用 getStockDetails 缓存) + const stockNameMap = new Map(); + const barcodeMap = new Map(); + const imageUrlMap = new Map(); + if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { + try { + const stockIds = [ + ...new Set( + [ ...itemsMap.values() ] + .flat() + .map(item => Number(item.stock_id || 0)) + .filter(id => id > 0) + ), + ]; + if (stockIds.length > 0) { + const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + { warehouseId } + ); + for (const detail of stockDetails) { + const sid = Number(detail.id || 0); + if (sid > 0) { + stockNameMap.set(sid, String(detail.item_name || '').trim()); + // 从 getStockDetails 的 barcodes 中提取条码并转为逗号拼接 + const barcodesRaw = Array.isArray(detail.barcodes) + ? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) + : []; + if (barcodesRaw.length > 0) { + barcodeMap.set(sid, [ ...new Set(barcodesRaw) ].join(', ')); + } + // 图片字段(有图片标记但实际 URL 需要额外查询) + if (detail.is_images === 'Y') { + imageUrlMap.set(sid, ''); + } + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询商品详情失败: ${err.message}`); + } + } + + // 批量查询货主备注(wms_store_warehouse.store_remask) + const storeRemarkMap = new Map(); + if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.StoreWarehouse) { + try { + const storeIds = [ + ...new Set( + rowsWithWaveIndex + .map(r => Number(r.store_id || 0)) + .filter(id => id > 0) + ), + ]; + if (storeIds.length > 0) { + const swRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询货主备注失败: ${err.message}`); + } + } + + // 批量查询运单数据(wms_order_express),按订单ID分组 + const expressMap = new Map(); + if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.OrderExpress) { + try { + const expressRows = await this.ctx.model.OrderExpress.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'logistics_interface_name', 'package_material_id', 'package_material_name_snapshot', 'create_at', 'weighing_weight' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const exp of (Array.isArray(expressRows) ? expressRows : [])) { + const oid = Number(exp.order_id || 0); + if (oid > 0) { + if (!expressMap.has(oid)) { + expressMap.set(oid, []); + } + expressMap.get(oid).push(exp); + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询运单数据失败: ${err.message}`); + } + } + + // 批量查询包材编码(wms_package_material),按 package_material_id 分组 + const packageMaterialMap = new Map(); + if (expressMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.PackageMaterial) { + try { + const materialIds = [ + ...new Set( + [ ...expressMap.values() ] + .flat() + .map(exp => Number(exp.package_material_id || 0)) + .filter(id => id > 0) + ), + ]; + if (materialIds.length > 0) { + const pmRows = await this.ctx.model.PackageMaterial.findAll({ + where: { id: { [this.app.Sequelize.Op.in]: materialIds } }, + attributes: [ 'id', 'material_code' ], + raw: true, + }); + for (const pm of (Array.isArray(pmRows) ? pmRows : [])) { + const pid = Number(pm.id || 0); + if (pid > 0 && !packageMaterialMap.has(pid)) { + packageMaterialMap.set(pid, String(pm.material_code || '').trim()); + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询包材编码失败: ${err.message}`); + } + } + + const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap, snStockIdSet, snCodesByOrderMap, snCodesByItemMap }; + + const exportRows = []; + for (const row of rowsWithWaveIndex) { + const rowExportRows = this.mapOrderExportRow(row, exportContext, mode); + exportRows.push(...rowExportRows); + } + + return { exportRows, orderCount: rowsWithWaveIndex.length }; + } + + /** + * 导出订单列表。 + * 查询采用 ORDER_EXPORT_QUERY_CONCURRENCY 个 worker 并发分页查询, + * 先查询完成的页先入 FIFO 队列,由单一串行 writer 按入队顺序写入文件(行序按完成顺序,非列表顺序)。 + * 单个 sheet 最多写入 ORDER_EXPORT_MAX_ROWS_PER_SHEET 行数据,超出后自动新建下一个 sheet 续写。 + * @param {Object} options 导出参数。 + * @param {string} [options.tableType] 表类型。 + * @param {string} [options.moduleName] 模块名。 + * @param {Object} [options.where] 查询条件。 + * @param {Object} [options.sort] 排序参数。 + * @param {string} [options.export_mode] 导出模式:waybill 或 item。 + * @param {Array} [options.export_columns] 导出表头字段白名单(中文表头数组),不传输出全部列。 + * @param {Array} [options.exportColumns] 导出表头字段白名单(驼峰写法)。 + * @param {Function} [options.onProgress] 进度回调。 + * @return {Promise} 上传结果与统计信息。 + */ + async exportOrders(options = {}) { + const safeOptions = this.isPlainObject(options) ? options : {}; + const target = this.resolveExportTarget({ + tableType: safeOptions.tableType, + moduleName: safeOptions.moduleName, + }); + const warehouseId = this.getWarehouseId(); + const requestData = { + where: this.isPlainObject(safeOptions.where) ? { ...safeOptions.where } : {}, + sort: this.isPlainObject(safeOptions.sort) ? { ...safeOptions.sort } : {}, + }; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + const { where } = this.prepareWhereContext(requestData, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); + const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); + const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); + const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterStockQuery); + const { where: whereAfterWaveScope, waveScope } = this.extractWaveScopeVirtualFilter(whereAfterWaveIndex); + const mergedWhere = this.mergeWhereObjects( + target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {}, + whereAfterWaveScope + ); + let queryWhere = this.buildWhere(mergedWhere, warehouseId, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (expressNumbers.length > 0) { + const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, warehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); + } + + if (buyerMessageHas !== null) { + const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas); + queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); + } + + if (stockQuery) { + // 仅传 table_type 时推导出与当前表类型一致的模块名,保证 order_items 表类型正确 + const stockQueryModuleName = target.defaultWhereModuleName || target.sortModuleName || 'order'; + const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, stockQueryModuleName, warehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds); + } + + if (waveIndexCondition) { + const waveIndexOrderIds = await this.findOrderIdsByWaveIndexCondition(waveIndexCondition, warehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, waveIndexOrderIds); + } + + if (waveScope) { + const waveScopeCondition = this.buildWaveScopeFilterCondition(waveScope); + queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition); + } + + const orderModel = await this.getOrderModelByTableType(target.tableType, warehouseId); + const pageSize = this.getExportPageSize(); + const order = this.buildListOrder(requestData.sort, target.sortModuleName); + const totalCount = await orderModel.count({ where: queryWhere }); + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-order-export-')); + const filename = this.buildOrderExportFilename(target); + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + const worksheet = workbook.addWorksheet(ORDER_EXPORT_WORKSHEET_NAME); + const exportMode = String(safeOptions.export_mode || '').trim() || 'waybill'; + const mode = exportMode === 'item' ? 'item' : 'waybill'; + const selectedHeaders = this.normalizeExportColumns( + safeOptions.export_columns ?? safeOptions.exportColumns + ); + const resolvedColumns = this.getOrderExportColumns(mode, selectedHeaders); + worksheet.columns = resolvedColumns; + + let currentCount = 0; + // 分 sheet 写入:每个 sheet 最多 ORDER_EXPORT_MAX_ROWS_PER_SHEET 行数据, + // 超出后提交当前 sheet 并新建下一个 sheet(名称:订单导出、订单导出2、…),新 sheet 同样带表头。 + let currentWorksheet = worksheet; + let currentSheetIndex = 1; + let currentSheetRows = 0; + + const ensureSheetCapacity = () => { + if (currentSheetRows < ORDER_EXPORT_MAX_ROWS_PER_SHEET) { + return; + } + currentWorksheet.commit(); + currentSheetIndex += 1; + currentWorksheet = workbook.addWorksheet(`${ORDER_EXPORT_WORKSHEET_NAME}${currentSheetIndex}`); + currentWorksheet.columns = resolvedColumns; + currentSheetRows = 0; + }; + + const writeExportRow = exportRow => { + ensureSheetCapacity(); + currentWorksheet.addRow(exportRow).commit(); + currentSheetRows += 1; + }; + + try { + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 5 : 90, + currentCount, + totalCount, + message: totalCount > 0 ? `已命中 ${totalCount} 条订单,开始导出` : '未命中数据,开始生成空文件', + }); + + const totalPages = totalCount > 0 ? Math.ceil(totalCount / pageSize) : 0; + + // FIFO 队列:各 worker 查询完成的页按完成顺序入队,由单一 writer 串行落盘 + const exportPageQueue = []; + let exportQueueHead = 0; + let pagesCompleted = 0; + let queueDone = false; + let queueWake = null; + let firstError = null; + + const wakeWriter = () => { + if (queueWake) { + const resolveWake = queueWake; + queueWake = null; + resolveWake(); + } + }; + const enqueueExportRows = exportRows => { + if (Array.isArray(exportRows) && exportRows.length > 0) { + exportPageQueue.push(exportRows); + wakeWriter(); + } + }; + const finishExportQueue = () => { + queueDone = true; + wakeWriter(); + }; + const waitForQueueWake = () => new Promise(resolve => { + queueWake = resolve; + }); + + // 串行 writer:按入队顺序写入 ExcelJS 流,避免并发 commit 导致的行序竞态 + const writerLoop = (async () => { + try { + for (;;) { + while (exportQueueHead < exportPageQueue.length) { + const exportRows = exportPageQueue[exportQueueHead]; + exportQueueHead += 1; + for (const exportRow of exportRows) { + writeExportRow(exportRow); + } + } + if (exportQueueHead > 0) { + if (exportQueueHead >= exportPageQueue.length) { + exportPageQueue.length = 0; + exportQueueHead = 0; + } else { + exportPageQueue.splice(0, exportQueueHead); + exportQueueHead = 0; + } + } + if (queueDone || firstError) { + break; + } + await waitForQueueWake(); + } + } catch (err) { + if (!firstError) { + firstError = err; + } + queueDone = true; + wakeWriter(); + } + })(); + + // 有界并发查询:限制 2 个 worker,先查询完成的页先入队 + let nextPage = 1; + const runWorker = async () => { + while (!firstError) { + const page = nextPage; + nextPage += 1; + if (page > totalPages) { + break; + } + try { + const pageResult = await this.buildOrderExportPage({ + page, + pageSize, + queryWhere, + order, + orderModel, + target, + warehouseId, + mode, + }); + enqueueExportRows(pageResult.exportRows); + currentCount += pageResult.orderCount; + pagesCompleted += 1; + await progressHandler({ + status: 'running', + progress: Math.min(99, Math.max(5, Math.round((currentCount / Math.max(totalCount, 1)) * 90))), + currentCount, + totalCount, + message: `已完成 ${currentCount}/${totalCount} 条订单查询(${pagesCompleted}/${totalPages} 页)`, + }); + } catch (err) { + if (!firstError) { + firstError = err; + } + break; + } + } + }; + + const workers = Array.from( + { length: Math.min(ORDER_EXPORT_QUERY_CONCURRENCY, totalPages) }, + () => runWorker() + ); + + await Promise.all(workers); + finishExportQueue(); + await writerLoop; + + if (firstError) { + throw firstError; + } + + currentWorksheet.commit(); + await workbook.commit(); + + const uploadResult = await this.uploadOrderExportFile({ + filePath, + filename, + warehouseId, + tableType: target.tableType, + }); + + await progressHandler({ + status: 'success', + progress: 100, + currentCount, + totalCount, + message: '导出任务完成', + result: uploadResult, + }); + + return { + ...uploadResult, + table_type: target.tableType, + module_name: target.defaultWhereModuleName || '', + current_count: currentCount, + total_count: totalCount, + sheet_count: currentSheetIndex, + }; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + throw error; + } finally { + await fsp.rm(tempDir, { recursive: true, force: true }); + } + } +} + +module.exports = OrderExportService; diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js new file mode 100644 index 0000000..dce7669 --- /dev/null +++ b/app/service/systems/order_express.js @@ -0,0 +1,2235 @@ +'use strict'; + +const Service = require('egg').Service; + +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); + +/** + * 订单快递业务服务。 + * + * 负责订单快递记录的读取与称重重量更新。 + */ +class OrderExpressService extends Service { + /** + * 创建带业务错误码的异常对象。 + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 规范化并校验订单ID。 + * @param {number|string} orderId 订单ID。 + * @return {number} 合法订单ID。 + */ + normalizeOrderId(orderId) { + const normalizedOrderId = Number(orderId || 0); + + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + throw this.createBusinessError('order_id 必填且必须为正整数', 400); + } + + return normalizedOrderId; + } + + /** + * 规范化并校验运单号。 + * @param {string} waybillCode 运单号。 + * @return {string} 合法运单号。 + */ + normalizeWaybillCode(waybillCode) { + const normalizedWaybillCode = String(waybillCode || '').trim(); + + if (!normalizedWaybillCode) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedWaybillCode; + } + + /** + * 规范化并校验包材编码。 + * @param {string} packageMaterialCode 包材编码。 + * @return {string} 合法包材编码。 + */ + normalizePackageMaterialCode(packageMaterialCode) { + const normalizedCode = String(packageMaterialCode || '').trim().toUpperCase(); + + if (!normalizedCode) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedCode; + } + + /** + * 规范化并校验包材ID。 + * @param {number|string} packageMaterialId 包材ID。 + * @return {number} 合法包材ID。 + */ + normalizePackageMaterialId(packageMaterialId) { + const normalizedId = Number(packageMaterialId || 0); + + if (!Number.isFinite(normalizedId) || normalizedId <= 0) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedId; + } + + /** + * 规范化并校验绑定包材场景的订单ID。 + * @param {number|string} orderId 订单ID。 + * @return {number} 合法订单ID。 + */ + normalizeBindOrderId(orderId) { + const normalizedOrderId = Number(orderId || 0); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedOrderId; + } + + /** + * 获取当前仓库 ID。 + * @return {number} 当前仓库 ID。 + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx && this.ctx.user ? this.ctx.user.store_id : 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('参数错误', 400); + } + + return warehouseId; + } + + /** + * 根据包材ID查询当前仓库启用中的包材。 + * @param {number} packageMaterialId 包材ID。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 包材记录。 + */ + async findActivePackageMaterialById(packageMaterialId, warehouseId) { + const packageMaterialModel = this.ctx.model && this.ctx.model.PackageMaterial; + if (!packageMaterialModel || typeof packageMaterialModel.findOne !== 'function') { + throw this.createBusinessError('包材模型未初始化', 500); + } + + const materialRow = await packageMaterialModel.findOne({ + where: { + warehouse_id: warehouseId, + id: packageMaterialId, + status: 1, + }, + attributes: [ 'id', 'material_code', 'material_name', 'warehouse_id', 'status' ], + raw: true, + }); + + if (!materialRow) { + throw this.createBusinessError('包材ID不存在', 404); + } + + return materialRow; + } + + /** + * 根据包材编码查询当前仓库启用中的包材。 + * @param {string} packageMaterialCode 包材编码。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 包材记录。 + */ + async findActivePackageMaterialByCode(packageMaterialCode, warehouseId) { + const packageMaterialModel = this.ctx.model && this.ctx.model.PackageMaterial; + if (!packageMaterialModel || typeof packageMaterialModel.findOne !== 'function') { + throw this.createBusinessError('包材模型未初始化', 500); + } + + const materialRow = await packageMaterialModel.findOne({ + where: { + warehouse_id: warehouseId, + material_code: packageMaterialCode, + status: 1, + }, + attributes: [ 'id', 'material_code', 'material_name', 'warehouse_id', 'status' ], + raw: true, + }); + + if (!materialRow) { + throw this.createBusinessError('包材编码不存在', 404); + } + + return materialRow; + } + + /** + * 根据订单号与运单号查询有效订单快递记录。 + * @param {number} orderId 订单 ID。 + * @param {string} waybillCode 运单号。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 订单快递记录。 + */ + async findValidOrderExpressByOrderAndWaybill(orderId, waybillCode, warehouseId) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('订单快递模型未初始化', 500); + } + + const orderExpressRow = await orderExpressModel.findOne({ + where: { + order_id: orderId, + waybill_code: waybillCode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id' ], + raw: true, + }); + + if (!orderExpressRow) { + throw this.createBusinessError('订单运单记录不存在', 404); + } + + return orderExpressRow; + } + + /** + * 查询订单拦截状态(依次查询 current → dispatch 分表)。 + * @param {number} orderId 订单 ID。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 拦截状态,查询失败时返回 'none'。 + */ + async findOrderInterceptStatus(orderId, warehouseId) { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return 'none'; + } + + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'intercept_status' ], + raw: true, + }); + if (row) { + return String(row.intercept_status || '').trim() || 'none'; + } + } catch (_err) { continue; } + } + + return 'none'; + } + + /** + * 断言订单未进入拦截流程,否则抛出业务异常。 + * @param {number} orderId 订单 ID。 + * @param {number} warehouseId 仓库 ID。 + * @param {string} [actionText='继续作业'] 被阻断的作业文案。 + * @return {Promise} 无返回值。 + */ + async assertOrderNotIntercepted(orderId, warehouseId, actionText = '继续作业') { + const interceptStatus = await this.findOrderInterceptStatus(orderId, warehouseId); + if (isInterceptedOrderStatus(interceptStatus)) { + throw this.createBusinessError(`订单已被拦截,无法${actionText}`, 400); + } + } + + /** + * 读取订单的波次范围与打包状态(依次查询 current → history → dispatch 分表)。 + * + * 序列表定位优先:命中时先查对应分表,未命中(存量订单)按原遍历顺序回退。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} { id, wave_scope, pack_status },未命中时返回 null。 + */ + async findOrderWaveAndPackStatus(orderId, warehouseId) { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return null; + } + + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + try { + if (typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId); + if (preferredLocation) { + tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (_err) { /* 定位失败,保持原遍历顺序 */ } + + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_scope', 'pack_status' ], + raw: true, + }); + if (row) return row; + } catch (_err) { continue; } + } + + return null; + } + + /** + * 读取仓库「散单称重是否需要打包」配置。 + * + * 配置来源:wms_store.subject_config.single_weigh_require_pack(默认关闭)。 + * 走 deliveryOrder.getStoreSubjectConfig 公共读取链路(带缓存);配置缺失、 + * 读取失败或值非法时按「关闭」处理,保证称重主流程可用。 + * + * @param {number|null} warehouseId 仓库ID。 + * @return {Promise} 是否要求散单称重前已完成打包。 + */ + async isSingleWeighRequirePack(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return false; + } + + try { + const deliveryOrderService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.deliveryOrder; + if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') { + return false; + } + + const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(normalizedWarehouseId); + return !!(subjectConfig && subjectConfig.single_weigh_require_pack === true); + } catch (error) { + this.ctx.logger.warn( + '[OrderExpressService.isSingleWeighRequirePack] 读取仓库配置失败,按关闭处理: %s', + error.message + ); + return false; + } + } + + /** + * 散单称重前置校验:开启「散单称重是否需要打包」时,打包中或已打包订单允许称重。 + * + * 适用范围:订单波次范围 wave_scope 不属于 1(大团购)/ 3(小团购)时生效, + * 即未分配波次、散单、单品单件等按散单处理的订单;团购订单不校验。 + * 订单未命中(分表无记录)时跳过校验,由后续称重逻辑自行报错。 + * + * @param {number} orderId 订单ID。 + * @param {number|null} warehouseId 仓库ID,缺失时跳过校验。 + * @return {Promise} 无返回值;未打包或打包异常时抛出业务异常。 + */ + async assertSingleOrderPackedForWeigh(orderId, warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return; + } + + const requirePack = await this.isSingleWeighRequirePack(normalizedWarehouseId); + if (!requirePack) { + return; + } + + const orderRow = await this.findOrderWaveAndPackStatus(orderId, normalizedWarehouseId); + if (!orderRow) { + return; + } + + const waveScope = Number(orderRow.wave_scope || 0); + if (waveScope === 1 || waveScope === 3) { + return; + } + + const packStatus = String(orderRow.pack_status || '').trim(); + if (packStatus !== 'fin' && packStatus !== 'padding') { + throw this.createBusinessError(this.buildWeighPackBlockedMessage(), 400); + } + } + + /** + * 构造「散单称重需先打包」拦截文案,供各称重入口复用(保证提示语一致)。 + * @return {string} 拦截提示文案。 + */ + buildWeighPackBlockedMessage() { + return '订单未打包'; + } + + /** + * 规范化并校验称重重量。 + * + * 必须为正整数(单位 g),且必须大于 0。 + * + * @param {number|string} weighingWeight 称重重量(g)。 + * @return {number} 合法重量数值。 + */ + normalizeWeighingWeight(weighingWeight) { + if (weighingWeight === null || weighingWeight === undefined || String(weighingWeight).trim() === '') { + throw this.createBusinessError('weighing_weight 必填', 400); + } + + const normalizedWeightText = String(weighingWeight).trim(); + if (!/^\d+$/.test(normalizedWeightText)) { + throw this.createBusinessError('weighing_weight 格式非法,必须为正整数(单位 g)', 400); + } + + const normalizedWeight = Number(normalizedWeightText); + if (!Number.isFinite(normalizedWeight) || normalizedWeight <= 0) { + throw this.createBusinessError('weighing_weight 必须大于 0', 400); + } + + return normalizedWeight; + } + + /** + * 读取订单下有效快递记录。 + * + * 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID, + * 禁止仅凭订单ID跨仓串读运单号;仓库ID缺失时直接抛业务错误拒绝读取。 + * + * @param {number} orderId 订单ID。 + * @param {number|string|null|undefined} warehouseId 仓库ID,必须为订单所属仓库。 + * @return {Promise>} 快递记录列表。 + */ + async findValidOrderExpressRows(orderId, warehouseId) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + throw this.createBusinessError('订单快递模型未初始化', 500); + } + + if (warehouseId === null || warehouseId === undefined || warehouseId === '') { + throw this.createBusinessError('缺少仓库上下文,禁止读取订单运单记录', 400); + } + + const where = { + order_id: orderId, + delete_at: null, + warehouse_id: warehouseId, + }; + + const rows = await orderExpressModel.findAll({ + where, + attributes: [ 'id', 'order_id', 'waybill_code', 'weighing_weight' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 回写订单表的 packages_weight(所有包裹总重量 = 该订单全部有效运单称重之和)。 + * + * 称重主流程的补充回写动作,失败仅告警不阻断称重流程。 + * + * @param {number} orderId 订单ID。 + * @param {number|null} warehouseId 仓库ID,缺失时跳过回写。 + * @param {Object|null} [orderDeliveryModel] 已知的订单分表模型;缺省时按 current → dispatch → history 自动定位。 + * @return {Promise} 计算出的包裹总重量(g),失败返回 0。 + */ + async _syncOrderPackagesWeight(orderId, warehouseId, orderDeliveryModel = null) { + const { ctx } = this; + const normalizedOrderId = Number(orderId || 0); + if (normalizedOrderId <= 0 || !warehouseId) { + return 0; + } + + try { + const orderExpressModel = ctx.model && ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.sum !== 'function') { + return 0; + } + const sumResult = await orderExpressModel.sum('weighing_weight', { + where: { + order_id: normalizedOrderId, + delete_at: null, + warehouse_id: warehouseId, + }, + }); + const packagesWeight = Number.isFinite(Number(sumResult)) && Number(sumResult) > 0 + ? Math.round(Number(sumResult)) + : 0; + + let targetModel = orderDeliveryModel; + if (!targetModel || typeof targetModel.update !== 'function') { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + return packagesWeight; + } + const tableOrders = [ + { label: 'current', getModel: () => factory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => factory.getDispatchModel(warehouseId) }, + { label: 'history', getModel: () => factory.getHistoryModel(warehouseId) }, + ]; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.update !== 'function') continue; + const found = await model.findOne({ + where: { id: normalizedOrderId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + if (found) { + targetModel = model; + break; + } + } catch (_err) { continue; } + } + } + + if (targetModel && typeof targetModel.update === 'function') { + await targetModel.update( + { packages_weight: packagesWeight }, + { where: { id: normalizedOrderId, warehouse_id: warehouseId } } + ); + } + return packagesWeight; + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[order_express._syncOrderPackagesWeight] 回写包裹总重量失败 orderId=${normalizedOrderId}: ${err && err.message}` + ); + return 0; + } + } + + /** + * 批量回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部有效运单称重之和)。 + * + * 一次聚合查询 + 逐订单 UPDATE,失败仅告警不阻断称重流程。 + * + * @param {number[]} orderIds 波次内参与称重的订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} orderDeliveryModel 订单分表模型(波次订单所在分表)。 + * @return {Promise} 无返回值。 + */ + async _syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel) { + const { ctx } = this; + const normalizedOrderIds = (Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id || 0)) + .filter(id => id > 0); + if (normalizedOrderIds.length === 0 || !warehouseId) { + return; + } + + try { + const orderExpressModel = ctx.model && ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return; + } + const { Op } = this.app.Sequelize; + const rows = await orderExpressModel.findAll({ + where: { + order_id: { [Op.in]: normalizedOrderIds }, + delete_at: null, + warehouse_id: warehouseId, + }, + attributes: [ 'order_id', 'weighing_weight' ], + raw: true, + }); + const sumMap = new Map(); + for (const row of (Array.isArray(rows) ? rows : [])) { + const oid = Number(row && row.order_id || 0); + if (oid <= 0) continue; + sumMap.set(oid, (sumMap.get(oid) || 0) + Number(row.weighing_weight || 0)); + } + + if (orderDeliveryModel && typeof orderDeliveryModel.update === 'function') { + for (const oid of normalizedOrderIds) { + await orderDeliveryModel.update( + { packages_weight: Math.round(sumMap.get(oid) || 0) }, + { where: { id: oid, warehouse_id: warehouseId } } + ); + } + } + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[order_express._syncWavePackagesWeight] 批量回写包裹总重量失败: ${err && err.message}` + ); + } + } + + /** + * 更新订单运单称重重量。 + * + * 支持团购波次批量设置: + * - 散单(wave_id = 0)或非团购波次:仅更新单个订单的运单重量。 + * - 团购波次(wave_type = 1):将同一重量批量设置到该波次下所有订单的运单上。 + * + * @param {Object} payload 入参对象。 + * @param {number|string} payload.orderId 订单ID。 + * @param {string} [payload.waybillCode] 运单号,多运单场景必填。 + * @param {number|string} payload.weighingWeight 称重重量(g)。 + * @return {Promise} 单订单返回 {order_id, waybill_code, weighing_weight, items_weight}; + * 团购批量返回 {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。 + */ + async updateWeighingWeight(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { + orderId, + waybillCode = '', + weighingWeight, + } = requestData; + + const normalizedOrderId = this.normalizeOrderId(orderId); + const normalizedWeight = this.normalizeWeighingWeight(weighingWeight); + const normalizedWaybillCode = String(waybillCode || '').trim(); + const warehouseId = this.ctx && this.ctx.user ? this.ctx.user.store_id : null; + + // 无法获取仓库ID时降级为单个订单逻辑 + if (!warehouseId) { + return await this._updateSingleOrderWeight( + normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 先查运单表校验运单是否存在(强制同仓校验:订单ID + 仓库ID) + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const expressRow = await orderExpressModel.findOne({ + where: { + order_id: normalizedOrderId, + delete_at: null, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ], + raw: true, + }); + + if (!expressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + // 拦截流程中的订单不允许称重 + await this.assertOrderNotIntercepted(normalizedOrderId, warehouseId, '称重'); + + // 依次查询多个订单表获取波次信息:current → history → dispatch + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + throw this.createBusinessError('订单模型未初始化', 500); + } + + const orderTableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + // 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历 + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(normalizedOrderId, warehouseId); + if (preferredLocation) { + orderTableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (_err) { /* 定位失败,保持原遍历顺序 */ } + + let orderRow = null; + let orderDeliveryModel = null; + for (const entry of orderTableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') { + continue; + } + const row = await model.findOne({ + where: { id: normalizedOrderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (row) { + orderRow = row; + orderDeliveryModel = model; + break; + } + } catch (_err) { + // 该表可能不存在,继续尝试下一张表 + continue; + } + } + + // 所有表都找不到 → 兼容前端传入 wave_id 的场景,尝试按波次查询 + if (!orderRow) { + const fallbackModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + return await this._tryWaveCompatibility( + normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId, fallbackModel + ); + } + + const waveId = Number(orderRow.wave_id || 0); + + // 散单 → 走单个订单逻辑 + if (waveId === 0) { + return await this._updateSingleOrderWeight( + normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 查询波次类型 + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') { + throw this.createBusinessError('波次模型未初始化', 500); + } + + const waveRow = await waveBatchModel.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 波次记录缺失或非团购波次 → 降级为单个订单逻辑 + if (!waveRow || Number(waveRow.wave_type) !== 1) { + return await this._updateSingleOrderWeight( + normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 团购波次 → 批量设置同一重量 + return await this._updateWaveOrderWeight( + waveId, String(waveRow.wave_no || ''), normalizedWeight, warehouseId, orderDeliveryModel, normalizedOrderId + ); + } + + /** + * 通过运单号更新称重重量(运单号模式,order_id=0 时使用)。 + * + * 从运单号反查 wms_order_express,再定位订单和波次: + * - 散单或非团购波次:仅更新该运单的称重重量。 + * - 团购波次(wave_type=1):按 wave_no + business_key 批量设置同一重量, + * 并返回含拆单汇总信息的结构。 + * + * @param {Object} payload 入参对象。 + * @param {string} payload.waybillCode 运单号(必填)。 + * @param {number|string} payload.weighingWeight 称重重量(g)。 + * @return {Promise} 单运单返回 {order_id, waybill_code, weighing_weight, items_weight}; + * 团购批量返回 {wave_id, wave_no, order_id, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。 + */ + async updateWeighingWeightByWaybill(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { waybillCode, weighingWeight } = requestData; + + const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); + const normalizedWeight = this.normalizeWeighingWeight(weighingWeight); + const warehouseId = this.getCurrentWarehouseId(); + + // 按运单号 + 仓库ID 查 wms_order_express + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const expressRow = await orderExpressModel.findOne({ + where: { + waybill_code: normalizedWaybillCode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ], + raw: true, + }); + + if (!expressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + const orderId = Number(expressRow.order_id || 0); + + // 拦截流程中的订单不允许称重 + await this.assertOrderNotIntercepted(orderId, warehouseId, '称重'); + + // 依次查询多个订单表获取波次信息:current → history → dispatch + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + throw this.createBusinessError('订单模型未初始化', 500); + } + + const orderTableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + // 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历 + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId); + if (preferredLocation) { + orderTableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (_err) { /* 定位失败,保持原遍历顺序 */ } + + let orderRow = null; + let orderDeliveryModel = null; + for (const entry of orderTableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') { + continue; + } + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (row) { + orderRow = row; + orderDeliveryModel = model; + break; + } + } catch (_err) { + // 该表可能不存在,继续尝试下一张表 + continue; + } + } + + if (!orderRow) { + throw this.createBusinessError('运单号对应的订单不存在', 404); + } + + const waveId = Number(orderRow.wave_id || 0); + + // 散单 → 走单个运单逻辑 + if (waveId === 0) { + return await this._updateSingleOrderWeight( + orderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 查询波次类型 + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') { + throw this.createBusinessError('波次模型未初始化', 500); + } + + const waveRow = await waveBatchModel.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 非团购波次 → 降级为单运单逻辑 + if (!waveRow || Number(waveRow.wave_type) !== 1) { + return await this._updateSingleOrderWeight( + orderId, normalizedWaybillCode, normalizedWeight, warehouseId + ); + } + + // 团购波次 → 按 wave_id 批量设置波次下全部运单 + return await this._updateWaveAllOrdersWeight( + waveId, + String(waveRow.wave_no || ''), + normalizedWeight, + warehouseId, + orderDeliveryModel, + orderId + ); + } + + /** + * 批量更新团购波次下所有订单运单的称重重量(内部方法,运单号模式入口)。 + * + * 查询波次下全部订单,按 order_id 批量更新所有运单的 weighing_weight, + * 不区分 business_key。与 _updateWaveOrderWeight 功能等价但调用入口不同。 + * + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号。 + * @param {number} weight 称重重量。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。 + * @param {number} orderId 触发更新的运单对应订单ID。 + * @return {Promise<{wave_id:number, wave_no:string, order_id:number, weighing_weight:number, total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string, items_weight:number}>} + * 团购批量更新结果,含拆单汇总信息及触发订单ID。 + */ + async _updateWaveAllOrdersWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel, orderId) { + // 查询波次下所有订单 + const waveOrders = await orderDeliveryModel.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id', 'intercept_status' ], + raw: true, + }); + + if (!waveOrders || waveOrders.length === 0) { + throw this.createBusinessError('波次下未找到订单', 404); + } + + // 波次内拦截订单不参与批量称重 + const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + const orderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => !isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + if (interceptedWaveOrderIds.length > 0) { + this.ctx.logger.info( + `[order_express._updateWaveAllOrdersWeight] 波次内拦截订单不参与称重: ${interceptedWaveOrderIds.join(',')}` + ); + } + + // 批量更新波次下全部运单的称重重量 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.update !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const { Op } = this.app.Sequelize; + // 强制同仓校验:批量更新称重重量必须同时限定订单ID与仓库ID + const updateWhere = { + order_id: { [Op.in]: orderIds }, + delete_at: null, + warehouse_id: warehouseId, + }; + + // 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判 + const matchingCount = await orderExpressModel.count({ where: updateWhere }); + if (matchingCount === 0) { + throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500); + } + + await orderExpressModel.update( + { weighing_weight: weight }, + { where: updateWhere } + ); + + const successCount = matchingCount; + + // 写入操作日志 + await this._writeWeighActionLog({ + waveId, + waveNo, + weight, + warehouseId, + successCount, + totalCount: orderIds.length, + }); + + // 回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部运单称重之和) + await this._syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel); + + // 构建拆单汇总信息(按触发订单 ID 汇总) + const summary = await this._buildWaveWeighingSummary(waveId, orderId, warehouseId, weight); + + // 从订单表读取当前 items_weight(只读,不做 UPDATE) + const orderRow = await orderDeliveryModel.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'items_weight' ], + raw: true, + }); + const itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0; + + return { + wave_id: waveId, + wave_no: waveNo, + order_id: orderId, + weighing_weight: weight, + total_weight: summary.total_weight, + split_count: summary.split_count, + splits: summary.splits, + store_name: summary.store_name, + sys_logistics_name: summary.sys_logistics_name, + items_weight: itemsWeight, + }; + } + + /** + * 构建团购波次称重拆单汇总信息(内部方法)。 + * + * 查询指定订单下所有运单记录,按 business_key 分组汇总称重重量, + * 并获取货主名称与系统快递名称。 + * + * @param {number} waveId 波次ID。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} currentWeight 本次设置的称重重量。 + * @return {Promise<{total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string}>} + * 拆单汇总信息。 + */ + async _buildWaveWeighingSummary(waveId, orderId, warehouseId, currentWeight) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return { + total_weight: currentWeight, + split_count: 0, + splits: [], + store_name: '', + sys_logistics_name: '', + }; + } + + // 查询指定订单下所有有效运单记录(强制同仓校验:订单ID + 仓库ID) + const expressRows = await orderExpressModel.findAll({ + where: { + order_id: orderId, + delete_at: null, + warehouse_id: warehouseId, + }, + attributes: [ 'business_key', 'weighing_weight', 'waybill_code' ], + raw: true, + }); + + // 按 business_key 分组汇总称重重量 + const splitMap = new Map(); + for (const row of expressRows) { + const bk = row.business_key === null || row.business_key === undefined + ? '__null__' + : String(row.business_key); + if (!splitMap.has(bk)) { + splitMap.set(bk, { + business_key: row.business_key, + weighing_weight: 0, + waybill_code: row.waybill_code || null, + }); + } + const entry = splitMap.get(bk); + entry.weighing_weight = entry.weighing_weight + Number(row.weighing_weight || 0); + // 优先取非空的 waybill_code 作为该拆单的代表运单号 + if (!entry.waybill_code && row.waybill_code) { + entry.waybill_code = row.waybill_code; + } + } + + const splits = [ ...splitMap.values() ]; + const totalWeight = splits.reduce((sum, s) => sum + s.weighing_weight, 0); + // split_count:仅统计 waybill_code 不为空的 business_key + const splitCount = splits.filter(s => s.waybill_code !== null).length; + + // 获取货主名称 + const storeName = await this._getStoreName([ orderId ], warehouseId); + + // 获取系统快递名称 + const sysLogisticsName = await this._getWaveSysLogisticsName([ orderId ], warehouseId); + + return { + total_weight: totalWeight, + split_count: splitCount, + splits, + store_name: storeName, + sys_logistics_name: sysLogisticsName, + }; + } + + /** + * 获取波次下第一个订单的货主名称(shop_nick)。 + * + * @param {number[]} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 货主名称(shop_nick),获取失败时返回空字符串。 + */ + async _getStoreName(orderIds, warehouseId) { + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return ''; + } + const { Op } = this.app.Sequelize; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const orderRow = await model.findOne({ + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + shop_nick: { [Op.ne]: null }, + }, + attributes: [ 'shop_nick' ], + raw: true, + }); + if (orderRow) return String(orderRow.shop_nick || '').trim(); + } catch (_err) { continue; } + } + return ''; + } catch (_err) { + return ''; + } + } + + /** + * 获取波次下订单的系统快递名称。 + * + * 取波次下第一个有值的 sys_logistics_name。 + * + * @param {number[]} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 系统快递名称,获取失败时返回空字符串。 + */ + async _getWaveSysLogisticsName(orderIds, warehouseId) { + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + return ''; + } + const { Op } = this.app.Sequelize; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const orderRow = await model.findOne({ + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + sys_logistics_name: { [Op.ne]: null }, + }, + attributes: [ 'sys_logistics_name' ], + raw: true, + }); + if (orderRow) return String(orderRow.sys_logistics_name || '').trim(); + } catch (_err) { continue; } + } + return ''; + } catch (_err) { + return ''; + } + } + + /** + * 更新单个订单运单的称重重量(内部方法)。 + * + * @param {number} orderId 订单ID。 + * @param {string} waybillCode 运单号。 + * @param {number} weight 称重重量。 + * @param {number|null} warehouseId 仓库ID。 + * @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number, items_weight:number}>} 更新结果。 + */ + async _updateSingleOrderWeight(orderId, waybillCode, weight, warehouseId) { + // 散单称重前置校验:开启「散单称重是否需要打包」后,仅打包中或已打包订单允许称重 + await this.assertSingleOrderPackedForWeigh(orderId, warehouseId); + + const rows = await this.findValidOrderExpressRows(orderId, warehouseId); + + if (rows.length === 0) { + throw this.createBusinessError('未找到有效的订单运单记录', 404); + } + + let targetRow = null; + if (rows.length === 1) { + targetRow = rows[0]; + } else { + if (!waybillCode) { + throw this.createBusinessError('多运单订单必须传入 waybill_code', 400); + } + + targetRow = rows.find( + row => String(row && row.waybill_code || '').trim() === waybillCode + ) || null; + if (!targetRow) { + throw this.createBusinessError('waybill_code 未匹配到该订单下的运单记录', 404); + } + } + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + const updateResult = await orderExpressModel.update( + { weighing_weight: weight }, + { where: { id: Number(targetRow.id) } } + ); + + const affectedRows = Array.isArray(updateResult) + ? Number(updateResult[0] || 0) + : Number(updateResult || 0); + if (!Number.isFinite(affectedRows) || affectedRows <= 0) { + throw this.createBusinessError('更新称重重量失败', 500); + } + + // 写入操作日志 + await this._writeWeighActionLog({ + orderId: Number(targetRow.order_id), + waybillCode: String(targetRow.waybill_code || '').trim(), + weight, + warehouseId, + }); + + // 回写订单表 packages_weight:所有包裹总重量 = 该订单全部有效运单称重之和 + const packagesWeight = await this._syncOrderPackagesWeight(Number(targetRow.order_id), warehouseId); + + // 从订单表读取当前 items_weight(只读,不做 UPDATE) + // 依次查 current / dispatch 两张表 + let itemsWeight = 0; + if (warehouseId) { + try { + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const orderRow = await model.findOne({ + where: { id: Number(targetRow.order_id), warehouse_id: warehouseId }, + attributes: [ 'items_weight' ], + raw: true, + }); + if (orderRow) { itemsWeight = Number(orderRow.items_weight || 0); break; } + } catch (_err) { continue; } + } + } + } catch (_err) { + // 查询失败时静默降级为 0 + } + } + + return { + order_id: Number(targetRow.order_id), + waybill_code: String(targetRow.waybill_code || '').trim(), + weighing_weight: weight, + packages_weight: packagesWeight, + items_weight: itemsWeight, + }; + } + + /** + * 批量更新团购波次下所有订单运单的称重重量(内部方法)。 + * + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号。 + * @param {number} weight 称重重量。 + * @param {number|null} warehouseId 仓库ID。 + * @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。 + * @param {number} [orderId] 触发更新的订单ID,未传时取波次下第一个订单。 + * @return {Promise<{wave_id:number, wave_no:string, weighing_weight:number, total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string, items_weight:number}>} + * 团购批量更新结果,含拆单汇总信息。 + */ + async _updateWaveOrderWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel, orderId) { + // 查询波次下所有订单 + const waveOrders = await orderDeliveryModel.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id', 'intercept_status' ], + raw: true, + }); + + if (!waveOrders || waveOrders.length === 0) { + throw this.createBusinessError('波次下未找到订单', 404); + } + + // 波次内拦截订单不参与批量称重 + const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + const orderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => !isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + if (interceptedWaveOrderIds.length > 0) { + this.ctx.logger.info( + `[order_express._updateWaveOrderWeight] 波次内拦截订单不参与称重: ${interceptedWaveOrderIds.join(',')}` + ); + } + const totalCount = orderIds.length; + + // 批量更新所有订单的运单称重重量 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.update !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const { Op } = this.app.Sequelize; + // 强制同仓校验:批量更新称重重量必须同时限定订单ID与仓库ID + const updateWhere = { + order_id: { [Op.in]: orderIds }, + delete_at: null, + warehouse_id: warehouseId, + }; + + // 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判 + const matchingCount = await orderExpressModel.count({ where: updateWhere }); + if (matchingCount === 0) { + throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500); + } + + await orderExpressModel.update( + { weighing_weight: weight }, + { where: updateWhere } + ); + + const successCount = matchingCount; + + // 写入操作日志 + await this._writeWeighActionLog({ + waveId, + waveNo, + weight, + warehouseId, + successCount, + totalCount, + }); + + // 回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部运单称重之和) + await this._syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel); + + // 构建拆单汇总信息(按触发订单 ID 汇总,未传时取波次下第一个订单) + const scopeOrderId = (Number.isFinite(Number(orderId)) && Number(orderId) > 0) + ? Number(orderId) + : orderIds[0]; + const summary = await this._buildWaveWeighingSummary(waveId, scopeOrderId, warehouseId, weight); + + // 从订单表读取当前 items_weight(只读,不做 UPDATE) + const orderRow = await orderDeliveryModel.findOne({ + where: { id: scopeOrderId, warehouse_id: warehouseId }, + attributes: [ 'items_weight' ], + raw: true, + }); + const itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0; + + return { + wave_id: waveId, + wave_no: waveNo, + weighing_weight: weight, + total_weight: summary.total_weight, + split_count: summary.split_count, + splits: summary.splits, + store_name: summary.store_name, + sys_logistics_name: summary.sys_logistics_name, + items_weight: itemsWeight, + }; + } + + /** + * 写入称重操作日志到 wms_wave_pick_action_log(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} [params.orderId] 订单ID(单订单称重场景)。 + * @param {string} [params.waybillCode] 运单号(单订单称重场景)。 + * @param {number} [params.waveId] 波次ID(团购批量称重场景)。 + * @param {string} [params.waveNo] 波次号(团购批量称重场景)。 + * @param {number} params.weight 称重重量。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} [params.successCount] 批量更新成功数。 + * @param {number} [params.totalCount] 批量更新总数。 + * @return {Promise} 无返回值。 + */ + async _writeWeighActionLog(params = {}) { + const { + orderId, + waybillCode, + waveId, + waveNo, + weight, + warehouseId, + successCount, + totalCount, + } = params; + + const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {}; + const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0); + const operatorName = String( + ctxUser.employees_name || ctxUser.name || 'system' + ).trim(); + + const isBatch = waveId !== undefined && waveId !== null; + const tag = isBatch ? 'weigh_batch' : 'weigh'; + const requestId = `${tag}_${warehouseId}_${isBatch ? waveId : orderId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: 0, + warehouseId: warehouseId || 0, + waveId: isBatch ? waveId : null, + orderId: isBatch ? null : (orderId || 0), + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: isBatch ? 'weigh_batch' : 'weigh', + requestId, + operatorId, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify(isBatch + ? { + wave_id: waveId, + wave_no: waveNo || '', + weighing_weight: weight, + success_count: successCount, + total_count: totalCount, + operator_name: operatorName, + } + : { + order_id: orderId, + waybill_code: waybillCode || '', + weighing_weight: weight, + operator_name: operatorName, + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + } + ); + + // 写入 order_operation_log + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logPayloads = []; + if (isBatch && waveId) { + logPayloads.push({ + businessType: 'order', + businessId: `wave_${waveId}`, + operationCode: 'ORDER_WEIGH', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + message: `波次 ${waveNo || waveId} 批量称重 ${weight}g,成功 ${successCount}/${totalCount}`, + warehouseId, + waveId, + waveNo: waveNo || '', + weighingWeight: weight, + successCount, + totalCount, + }, + }); + } else if (orderId) { + logPayloads.push({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_WEIGH', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + message: `订单称重 ${weight}g`, + warehouseId, + orderId, + waybillCode: waybillCode || '', + weighingWeight: weight, + }, + }); + } + if (logPayloads.length > 0) { + await operationLogService.createOperationLogs(logPayloads); + } + } + } catch (e) { + this.ctx.logger.warn('[order_express._writeWeighActionLog] 写入 operation_log 失败,不影响主流程', { + error: e && e.message, + waveId, + orderId, + }); + } + } + + /** + * 先用传入的 ID 在 wms_wave_batch 中查找波次: + * - 波次不存在 → 抛出"订单不存在"错误。 + * - 波次存在且 wave_type = 1(团购)→ 走团购批量称重逻辑。 + * - 波次存在但 wave_type ≠ 1 → 无法确定具体订单,抛出错误提示传入正确的 order_id。 + * + * @param {number} waveIdLike 可能是 wave_id 的数值。 + * @param {string} waybillCode 运单号(兼容参数,本路径不使用)。 + * @param {number} weight 称重重量。 + * @param {number|null} warehouseId 仓库ID。 + * @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。 + * @return {Promise} 团购批量更新结果。 + * @throws {Error} 波次不存在或非团购波次时抛出业务错误。 + */ + async _tryWaveCompatibility(waveIdLike, waybillCode, weight, warehouseId, orderDeliveryModel) { + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') { + throw this.createBusinessError('订单不存在', 404); + } + + const waveRow = await waveBatchModel.findOne({ + where: { wave_id: waveIdLike, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 波次也不存在 → 报订单不存在 + if (!waveRow) { + throw this.createBusinessError('订单不存在', 404); + } + + // 非团购波次 → 无法确定具体订单,提示前端传入正确的 order_id + if (Number(waveRow.wave_type) !== 1) { + throw this.createBusinessError( + `传入的 ID ${waveIdLike} 对应波次(wave_no: ${waveRow.wave_no}),非团购波次,请传入正确的 order_id`, + 400 + ); + } + + // 团购波次 → 批量设置同一重量 + return await this._updateWaveOrderWeight( + waveIdLike, + String(waveRow.wave_no || ''), + weight, + warehouseId, + orderDeliveryModel + ); + } + + /** + * 写入或更新商品结构-包材绑定关系记录。 + * + * 若订单的 items_hash 不存在则跳过;关系表写入失败不影响主流程。 + * + * @param {Object} params 绑定上下文参数。 + * @param {number} params.orderId 订单ID。 + * @param {string} params.waybillCode 运单号。 + * @param {number} params.packageMaterialId 包材ID。 + * @param {string} params.packageMaterialCode 包材编码。 + * @param {string} params.packageMaterialName 包材名称。 + * @param {number} params.warehouseId 仓库ID。 + * @return {Promise} + */ + async _upsertPackageMaterialItemRelation({ orderId, waybillCode, packageMaterialId, packageMaterialCode, packageMaterialName, warehouseId }) { + const { ctx } = this; + try { + // 1. 查订单的 items_hash / items_crc(依次查 current / dispatch 两张表) + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') return; + + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let orderRow = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'items_hash', 'items_crc' ], + raw: true, + }); + if (row) { orderRow = row; break; } + } catch (_err) { continue; } + } + if (!orderRow || !orderRow.items_hash) return; + + const { items_hash: itemsHash, items_crc: itemsCrc } = orderRow; + + // 2. 查关系表 + const relationModel = ctx.model && ctx.model.PackageMaterialItemRelation; + if (!relationModel) return; + + const existing = await relationModel.findOne({ + where: { + warehouse_id: warehouseId, + items_hash: itemsHash, + items_crc: itemsCrc, + package_material_id: packageMaterialId, + delete_at: null, + }, + raw: true, + }); + + // 3. 查包材完整快照 + const packageMaterialModel = ctx.model && ctx.model.PackageMaterial; + const materialRow = packageMaterialModel + ? await packageMaterialModel.findOne({ where: { id: packageMaterialId }, raw: true }) + : null; + + const snapshot = { + package_material_code: String(packageMaterialCode || '').trim(), + package_material_name: String(packageMaterialName || '').trim(), + package_material_spec: String(materialRow && materialRow.spec || '').trim(), + package_material_type: String(materialRow && materialRow.material_type || '').trim(), + length: Number(materialRow && materialRow.length || 0), + width: Number(materialRow && materialRow.width || 0), + height: Number(materialRow && materialRow.height || 0), + weight: Number(materialRow && materialRow.weight || 0), + }; + + const userId = ctx.user && ctx.user.id ? Number(ctx.user.id) : null; + const now = new Date(); + + if (existing) { + await relationModel.update({ + bind_count: (Number(existing.bind_count) || 0) + 1, + last_order_id: orderId, + last_waybill_code: waybillCode, + last_bind_user_id: userId, + last_bind_at: now, + is_active: 1, + ...snapshot, + }, { + where: { id: existing.id }, + }); + } else { + await relationModel.create({ + warehouse_id: warehouseId, + items_hash: itemsHash, + items_crc: itemsCrc, + package_material_id: packageMaterialId, + bind_count: 1, + last_order_id: orderId, + last_waybill_code: waybillCode, + last_bind_user_id: userId, + last_bind_at: now, + is_active: 1, + ...snapshot, + }); + } + } catch (err) { + // 关系表写入失败不影响主流程 + ctx && ctx.logger && ctx.logger.error(`[packageMaterialRelation] upsert failed: ${err.message}`); + } + } + + /** + * 绑定订单快递记录的包材信息。 + * @param {Object} payload 入参对象。 + * @param {number|string} payload.orderId 订单ID。 + * @param {string} payload.waybillCode 运单号。 + * @param {string} payload.packageMaterialCode 包材编码。 + * @return {Promise} 绑定后的结果快照。 + */ + async bindExpressPackageMaterial(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { + orderId, + waybillCode, + packageMaterialCode, + } = requestData; + + const normalizedOrderId = this.normalizeBindOrderId(orderId); + const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); + const normalizedPackageMaterialCode = this.normalizePackageMaterialCode(packageMaterialCode); + const warehouseId = this.getCurrentWarehouseId(); + + const materialRow = await this.findActivePackageMaterialByCode(normalizedPackageMaterialCode, warehouseId); + const orderExpressRow = await this.findValidOrderExpressByOrderAndWaybill(normalizedOrderId, normalizedWaybillCode, warehouseId); + + // 拦截流程中的订单不允许绑定包材 + await this.assertOrderNotIntercepted(Number(orderExpressRow.order_id), warehouseId, '绑定包材'); + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + const updateResult = await orderExpressModel.update({ + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + }, { + where: { + id: Number(orderExpressRow.id), + delete_at: null, + }, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + const isSameMaterial = Number(orderExpressRow.package_material_id) === Number(materialRow.id); + + if (!Number.isFinite(affectedRows) || affectedRows <= 0) { + if (!isSameMaterial) { + throw this.createBusinessError('绑定包材失败', 500); + } + // 同一包材幂等:跳过 update 报错,继续走关系表 + } + + await this._upsertPackageMaterialItemRelation({ + orderId: normalizedOrderId, + waybillCode: normalizedWaybillCode, + packageMaterialId: Number(materialRow.id), + packageMaterialCode: String(materialRow.material_code || '').trim(), + packageMaterialName: String(materialRow.material_name || '').trim(), + warehouseId, + }); + + return { + order_id: Number(orderExpressRow.order_id), + waybill_code: String(orderExpressRow.waybill_code || '').trim(), + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + package_material_code: String(materialRow.material_code || '').trim(), + }; + } + + /** + * 根据运单号绑定包材。 + * + * 仅凭运单号即可绑定包材,无需传入订单ID。 + * 先按运单号 + 仓库ID 查询有效运单记录,再按包材ID查询启用中的包材, + * 最后更新运单记录的包材字段。 + * + * 支持团购波次自动感知: + * - 非团购订单(wave_id=0 或 wave_type≠1):仅绑定当前运单的包材,行为与旧版一致。 + * - 团购波次(wave_type=1):自动将同一波次下、相同快递业务键(business_key)的 + * 所有运单批量绑定相同的包材,实现一键补齐。 + * + * @param {Object} [payload={}] 请求参数。 + * @param {string} payload.waybillCode 运单号。 + * @param {number|string} payload.packageMaterialId 包材ID。 + * @return {Promise} 单条绑定返回 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code}; + * 团购批量绑定返回 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。 + */ + async bindExpressPackageMaterialByWaybill(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { + waybillCode, + packageMaterialId, + } = requestData; + + const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); + const normalizedPackageMaterialId = this.normalizePackageMaterialId(packageMaterialId); + const warehouseId = this.getCurrentWarehouseId(); + + // 按运单号 + 仓库ID 查询有效运单记录 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const orderExpressRow = await orderExpressModel.findOne({ + where: { + waybill_code: normalizedWaybillCode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id', 'business_key' ], + raw: true, + }); + + if (!orderExpressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + // 拦截流程中的订单不允许绑定包材 + await this.assertOrderNotIntercepted(Number(orderExpressRow.order_id), warehouseId, '绑定包材'); + + // 查询启用中的包材 + const materialRow = await this.findActivePackageMaterialById(normalizedPackageMaterialId, warehouseId); + + // --- 团购波次自动感知 --- + // 依次查询 current / dispatch 表获取波次信息 + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { + try { + const orderTableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let orderRow = null; + for (const entry of orderTableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: Number(orderExpressRow.order_id), warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (row) { orderRow = row; break; } + } catch (_err) { continue; } + } + + if (orderRow) { + const waveId = Number(orderRow.wave_id || 0); + + if (waveId > 0) { + // 查询波次类型 + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (waveBatchModel && typeof waveBatchModel.findOne === 'function') { + const waveRow = await waveBatchModel.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 团购波次(wave_type=1)→ 按业务键分类批量绑定 + if (waveRow && Number(waveRow.wave_type) === 1) { + return await this._bindWavePackageMaterialByBusinessKey({ + waveId, + waveNo: String(waveRow.wave_no || ''), + businessKey: orderExpressRow.business_key ?? null, + packageMaterialId: Number(materialRow.id), + packageMaterialCode: String(materialRow.material_code || '').trim(), + packageMaterialName: String(materialRow.material_name || '').trim(), + warehouseId, + triggerOrderId: Number(orderExpressRow.order_id), + triggerWaybillCode: normalizedWaybillCode, + }); + } + } + } + } + } catch (_waveErr) { + // 波次查询失败时静默降级为单条绑定,保证向后兼容 + this.ctx && this.ctx.logger && this.ctx.logger.warn( + `[bindExpressPackageMaterialByWaybill] 团购波次检测失败,降级为单条绑定: ${_waveErr.message}` + ); + } + } + + // 非团购 → 单条绑定(保持现有逻辑) + return await this._bindSingleExpressPackageMaterial({ + orderExpressRow, + materialRow, + normalizedWaybillCode, + warehouseId, + }); + } + + /** + * 单条运单包材绑定(内部方法)。 + * + * 更新单条运单记录的包材字段,并写入包材-商品结构关系表。 + * + * @param {Object} params 绑定上下文参数。 + * @param {Object} params.orderExpressRow 运单记录。 + * @param {Object} params.materialRow 包材记录。 + * @param {string} params.normalizedWaybillCode 规范化后的运单号。 + * @param {number} params.warehouseId 仓库ID。 + * @return {Promise} 绑定后的结果快照,包含 order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。 + */ + async _bindSingleExpressPackageMaterial({ orderExpressRow, materialRow, normalizedWaybillCode, warehouseId }) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + + // 更新运单记录的包材字段 + const updateResult = await orderExpressModel.update({ + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + }, { + where: { + id: Number(orderExpressRow.id), + delete_at: null, + }, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + const isSameMaterial = Number(orderExpressRow.package_material_id) === Number(materialRow.id); + + if (!Number.isFinite(affectedRows) || affectedRows <= 0) { + if (!isSameMaterial) { + throw this.createBusinessError('绑定包材失败', 500); + } + // 同一包材幂等:跳过 update 报错,继续走关系表 + } + + await this._upsertPackageMaterialItemRelation({ + orderId: Number(orderExpressRow.order_id), + waybillCode: normalizedWaybillCode, + packageMaterialId: Number(materialRow.id), + packageMaterialCode: String(materialRow.material_code || '').trim(), + packageMaterialName: String(materialRow.material_name || '').trim(), + warehouseId, + }); + + // 写入包材绑定操作日志(单条绑定) + try { + const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {}; + const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0); + const operatorName = String(ctxUser.employees_name || ctxUser.name || 'system').trim() || 'system'; + const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (opLogService && typeof opLogService.createOperationLogs === 'function') { + await opLogService.createOperationLogs([{ + businessType: 'order', + businessId: `${Number(orderExpressRow.order_id || 0)}`, + operationCode: 'ORDER_PACKAGE_MATERIAL_BIND', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + message: `订单绑定包材 ${String(materialRow.material_name || materialRow.material_code || '').trim()}`, + warehouseId, + orderId: Number(orderExpressRow.order_id || 0), + waybillCode: normalizedWaybillCode, + packageMaterialId: Number(materialRow.id), + packageMaterialName: String(materialRow.material_name || '').trim(), + }, + }]); + } + } catch (e) { + this.ctx.logger.warn('[order_express._bindSingleExpressPackageMaterial] 写入 operation_log 失败', { + error: e && e.message, + orderId: Number(orderExpressRow.order_id || 0), + }); + } + + return { + order_id: Number(orderExpressRow.order_id), + waybill_code: String(orderExpressRow.waybill_code || '').trim(), + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + package_material_code: String(materialRow.material_code || '').trim(), + }; + } + + /** + * 团购波次按快递业务键分类批量绑定包材(内部方法)。 + * + * 查询波次下所有订单,再按触发运单的 business_key 筛选出同分类的运单, + * 批量更新包材字段并写入关系表。 + * + * @param {Object} params 批量绑定上下文参数。 + * @param {number} params.waveId 波次ID。 + * @param {string} params.waveNo 波次号。 + * @param {string|null} params.businessKey 快递业务键,用于分类过滤。 + * @param {number} params.packageMaterialId 包材ID。 + * @param {string} params.packageMaterialCode 包材编码。 + * @param {string} params.packageMaterialName 包材名称。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.triggerOrderId 触发绑定的订单ID。 + * @param {string} params.triggerWaybillCode 触发绑定的运单号。 + * @return {Promise} 团购批量绑定结果,含 wave_id、wave_no、business_key、order_id、waybill_code、package_material_id、package_material_code、package_material_name_snapshot、bind_count、bound_waybills、store_name、sys_logistics_name。 + */ + async _bindWavePackageMaterialByBusinessKey({ + waveId, + waveNo, + businessKey, + packageMaterialId, + packageMaterialCode, + packageMaterialName, + warehouseId, + triggerOrderId, + triggerWaybillCode, + }) { + // 1. 查询波次下所有订单(current + dispatch 两张表) + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + throw this.createBusinessError('订单模型未初始化', 500); + } + + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + const orderIdSet = new Set(); + const excludedInterceptedOrderIds = []; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findAll !== 'function') continue; + const rows = await model.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id', 'intercept_status' ], + raw: true, + }); + if (Array.isArray(rows)) { + rows.forEach(r => { + const orderId = Number(r.id); + if (isInterceptedOrderStatus(r && r.intercept_status)) { + excludedInterceptedOrderIds.push(orderId); + return; + } + orderIdSet.add(orderId); + }); + } + } catch (_err) { continue; } + } + + if (excludedInterceptedOrderIds.length > 0) { + this.ctx.logger.info( + `[bindExpressPackageMaterialByWaybill] 波次内拦截订单不参与批量绑定: ${excludedInterceptedOrderIds.join(',')}` + ); + } + + if (orderIdSet.size === 0) { + throw this.createBusinessError('波次下未找到订单', 404); + } + + const orderIds = Array.from(orderIdSet); + + // 2. 查询这些订单下相同 business_key 的所有有效运单 + const { Op } = this.app.Sequelize; + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + // business_key 为 null 时需特殊处理 Sequelize 查询 + const businessKeyWhere = (businessKey === null || businessKey === undefined) + ? { [Op.is]: null } + : businessKey; + + // 强制同仓校验:按订单ID批量查询运单必须同时限定仓库ID + const expressRows = await orderExpressModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + business_key: businessKeyWhere, + delete_at: null, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'package_material_id' ], + raw: true, + }); + + if (!expressRows || expressRows.length === 0) { + // 波次下无同 business_key 运单 → 降级为仅绑定触发运单 + const orderExpressRow = await orderExpressModel.findOne({ + where: { waybill_code: triggerWaybillCode, warehouse_id: warehouseId, delete_at: null }, + attributes: [ 'id', 'order_id', 'waybill_code', 'package_material_id' ], + raw: true, + }); + if (!orderExpressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + const materialRow = { + id: packageMaterialId, + material_code: packageMaterialCode, + material_name: packageMaterialName, + }; + + return await this._bindSingleExpressPackageMaterial({ + orderExpressRow, + materialRow, + normalizedWaybillCode: triggerWaybillCode, + warehouseId, + }); + } + + const expressIds = expressRows.map(r => Number(r.id)); + + // 3. 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判 + const matchingCount = await orderExpressModel.count({ + where: { id: { [Op.in]: expressIds }, delete_at: null }, + }); + if (matchingCount === 0) { + throw this.createBusinessError('批量绑定包材失败,无有效运单记录', 500); + } + + // 4. 批量更新包材字段 + await orderExpressModel.update( + { + package_material_id: packageMaterialId, + package_material_name_snapshot: packageMaterialName, + }, + { + where: { id: { [Op.in]: expressIds }, delete_at: null }, + } + ); + + // 5. 逐条写入包材-商品结构关系表(失败不影响主流程) + for (const row of expressRows) { + await this._upsertPackageMaterialItemRelation({ + orderId: Number(row.order_id), + waybillCode: String(row.waybill_code || '').trim(), + packageMaterialId, + packageMaterialCode, + packageMaterialName, + warehouseId, + }); + } + + // 6. 写入操作日志 + await this._writePackageMaterialActionLog({ + waveId, + waveNo, + businessKey, + packageMaterialCode, + packageMaterialName, + warehouseId, + bindCount: expressRows.length, + totalOrderCount: orderIds.length, + }); + + // 7. 获取货主名称与系统快递名称 + const storeName = await this._getStoreName(orderIds, warehouseId); + const sysLogisticsName = await this._getWaveSysLogisticsName(orderIds, warehouseId); + + // 8. 构建返回结构 + return { + wave_id: waveId, + wave_no: waveNo, + business_key: businessKey, + order_id: triggerOrderId, + waybill_code: triggerWaybillCode, + package_material_id: packageMaterialId, + package_material_code: packageMaterialCode, + package_material_name_snapshot: packageMaterialName, + bind_count: expressRows.length, + bound_waybills: expressRows.map(r => ({ + order_id: Number(r.order_id), + waybill_code: String(r.waybill_code || '').trim(), + })), + store_name: storeName, + sys_logistics_name: sysLogisticsName, + }; + } + + /** + * 写入包材绑定操作日志到 wms_wave_pick_action_log(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} params.waveId 波次ID。 + * @param {string} params.waveNo 波次号。 + * @param {string|null} params.businessKey 快递业务键。 + * @param {string} params.packageMaterialCode 包材编码。 + * @param {string} params.packageMaterialName 包材名称。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.bindCount 绑定运单数。 + * @param {number} params.totalOrderCount 波次下订单总数。 + * @return {Promise} 无返回值。 + */ + async _writePackageMaterialActionLog({ + waveId, + waveNo, + businessKey, + packageMaterialCode, + packageMaterialName, + warehouseId, + bindCount, + totalOrderCount, + }) { + const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {}; + const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0); + const operatorName = String( + ctxUser.employees_name || ctxUser.name || 'system' + ).trim(); + + const requestId = `bind_pm_${warehouseId}_${waveId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: 0, + warehouseId: warehouseId || 0, + waveId, + orderId: null, + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: 'bind_package_material', + requestId, + operatorId, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify({ + wave_id: waveId, + wave_no: waveNo || '', + business_key: businessKey, + package_material_code: packageMaterialCode, + package_material_name: packageMaterialName, + bind_count: bindCount, + total_order_count: totalOrderCount, + operator_name: operatorName, + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + } + ); + + // 写入 order_operation_log + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: `wave_${waveId}`, + operationCode: 'ORDER_PACKAGE_MATERIAL_BIND', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + message: `波次 ${waveNo || waveId} 绑定包材 ${packageMaterialName || packageMaterialCode},绑定量 ${bindCount}`, + warehouseId, + waveId, + waveNo: waveNo || '', + packageMaterialCode, + packageMaterialName, + bindCount, + businessKey, + }, + }]); + } + } catch (e) { + this.ctx.logger.warn('[order_express._writePackageMaterialActionLog] 写入 operation_log 失败,不影响主流程', { + error: e && e.message, + waveId, + }); + } + } +} + +module.exports = OrderExpressService; diff --git a/app/service/systems/order_item_sn.js b/app/service/systems/order_item_sn.js new file mode 100644 index 0000000..fd205a1 --- /dev/null +++ b/app/service/systems/order_item_sn.js @@ -0,0 +1,713 @@ +'use strict'; + +const OrderBaseService = require('../systemMethods/order/base'); + +/** SN 主表状态:复核提交即视为已核验并已随订单发出 */ +const SN_STATUS_VERIFIED = 'VERIFIED'; +/** SN 主表状态:已绑定待核验(可被复核提交升级为 VERIFIED) */ +const SN_STATUS_BOUND = 'BOUND'; +/** 核验通过 */ +const VERIFY_STATUS_PASS = 'PASS'; +/** 流水表中代表「已随订单发出」的变更后状态,用于判断 SN 是否已经发过 */ +const SHIPPED_SN_STATUS_LIST = [ 'VERIFIED', 'REISSUED' ]; +/** 复核提交写入的流水动作类型 */ +const RECHECK_LOG_ACTION = 'VERIFY'; +/** SN 码最大长度(与 wms_order_item_sn.sn_code VARCHAR(512) 保持一致,支持链接/二维码内容) */ +const MAX_SN_CODE_LENGTH = 512; + +/** + * 订单明细 SN 服务。 + * 负责复核提交环节的 SN 入参归一化、数量与占用校验,以及 SN 主表/流水表落库。 + */ +class OrderItemSnService extends OrderBaseService { + /** + * 归一化复核入参中的 SN 提交内容。 + * + * 统一只有一种格式:sn_map = { stock_id: [ sn_code, ... ] }(值也兼容逗号/换行分隔的字符串), + * 即「商品(仓库商品ID)→ SN 码列表」一一对应,不再按订单明细ID提交。 + * 单个 SN 码最长 512 字符(支持链接/二维码内容)。 + * + * @param {Object} payload 复核请求体。 + * @return {Map} 仓库商品ID键 -> SN 码列表。 + */ + normalizeRecheckSnPayload(payload = {}) { + const requestData = this.isPlainObject(payload) ? payload : {}; + const codesByStock = new Map(); + const snMap = requestData.sn_map ?? requestData.snMap; + if (!this.isPlainObject(snMap)) { + return codesByStock; + } + + for (const [ rawStockKey, rawCodes ] of Object.entries(snMap)) { + const stockKey = this.normalizeSnStockKey(rawStockKey); + if (!stockKey) { + continue; + } + const codeList = Array.isArray(rawCodes) ? rawCodes : this.splitSnCodeText(rawCodes); + const codes = codeList + .map(code => this.normalizeSnCode(code)) + .filter(code => !!code); + for (const code of codes) { + if (code.length > MAX_SN_CODE_LENGTH) { + throw new Error( + `SN码长度不能超过${MAX_SN_CODE_LENGTH}个字符:${code.slice(0, 32)}…(共${code.length}字符)` + ); + } + } + if (codes.length === 0) { + continue; + } + if (!codesByStock.has(stockKey)) { + codesByStock.set(stockKey, []); + } + codesByStock.get(stockKey).push(...codes); + } + + return codesByStock; + } + + /** + * 判断请求体是否提交了 SN 码内容(非空才算提交)。 + * @param {Object} payload 复核请求体。 + * @return {boolean} 是否提交了 SN 码。 + */ + hasRecheckSnPayload(payload = {}) { + const codesByStock = this.normalizeRecheckSnPayload(payload); + for (const codes of codesByStock.values()) { + if (codes.length > 0) { + return true; + } + } + return false; + } + + /** + * 复核提交时校验并写入 SN 码。 + * 校验规则: + * 1. SN 订单必须提交 SN 码,且每个序列号管理商品(stock_id)的 SN 数量必须等于该商品在订单内的 plan_qty 合计; + * 2. 非序列号管理商品不允许提交 SN 码;提交的 stock_id 必须属于当前订单; + * 3. 同一批提交内 SN 不可重复; + * 4. SN 若已绑定其它订单/明细,或流水显示已随其它订单发出,则判定为已发过,直接失败; + * 5. 同一订单同一明细重复提交视为幂等,不重复写入。 + * @param {Object} params 参数。 + * @param {Object} params.order 订单主表行(需包含 id 与 has_sn_item)。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} params.payload 复核请求体,含 sn_map(stock_id -> SN 列表)。 + * @param {Object} [params.operator] 操作人。 + * @param {Date} [params.now] 复核时间。 + * @param {Object} [params.transaction] Sequelize 事务,与复核状态更新共用。 + * @return {Promise<{ sn_count: number, sn_item_count: number, sn_created_count: number, sn_reused_count: number }>} + * SN 提交汇总:SN 总数、涉及明细数、新增写入数、幂等复用数。 + */ + async verifyRecheckSnList({ order = {}, warehouseId, payload = {}, operator = {}, now = new Date(), transaction }) { + const orderId = Number(order && order.id); + const normalizedWarehouseId = Number(warehouseId); + const storeId = Number(order && order.store_id) || 0; + + if (!Number.isInteger(orderId) || orderId <= 0) { + throw new Error('订单ID不合法,无法校验SN码'); + } + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('仓库ID不合法,无法校验SN码'); + } + + const codesByStock = this.normalizeRecheckSnPayload(payload); + const isSnOrder = this.isSnOrderRow(order); + const submittedCodeCount = this.countSnCodes(codesByStock); + + if (submittedCodeCount === 0) { + if (isSnOrder) { + throw new Error('订单包含序列号管理商品,提交复核时必须上传全部SN码'); + } + return { sn_count: 0, sn_item_count: 0, sn_created_count: 0, sn_reused_count: 0 }; + } + + const items = await this.loadOrderItemsForSn(orderId, normalizedWarehouseId, transaction); + const snStockIdSet = await this.loadSnStockIdSet(items, normalizedWarehouseId); + const stockItemMap = this.buildSnStockItemMap(items, snStockIdSet); + + if (isSnOrder && stockItemMap.size === 0) { + throw new Error('订单序列号商品信息缺失,无法校验SN码,请检查商品是否启用序列号管理'); + } + + this.assertSnStockCodesMatched({ stockItemMap, codesByStock }); + const codesByItem = this.mapStockCodesToOrderItems({ stockItemMap, codesByStock }); + + const allCodes = []; + for (const codes of codesByItem.values()) { + allCodes.push(...codes); + } + this.assertSnCodesUnique(allCodes); + + const writeResult = await this.persistRecheckSn({ + orderId, + warehouseId: normalizedWarehouseId, + storeId, + codesByItem, + allCodes, + operator, + now, + transaction, + }); + + return { + sn_count: allCodes.length, + sn_item_count: codesByItem.size, + sn_created_count: writeResult.createdCount, + sn_reused_count: writeResult.reusedCount, + }; + } + + /** + * 判断订单是否含序列号管理商品。 + * @param {Object} order 订单主表行。 + * @return {boolean} 是否 SN 订单。 + */ + isSnOrderRow(order = {}) { + return String(order && order.has_sn_item || '').trim().toUpperCase() === 'Y'; + } + + /** + * 清洗单个 SN 码。 + * @param {*} rawCode 原始 SN 码。 + * @return {string} 清洗后的 SN 码,空值返回空串。 + */ + normalizeSnCode(rawCode) { + if (rawCode === undefined || rawCode === null) { + return ''; + } + return String(rawCode).trim(); + } + + /** + * 把 SN 文本按换行/逗号/分号/空格拆分为 SN 数组。 + * @param {*} rawText 原始文本。 + * @return {string[]} SN 数组。 + */ + splitSnCodeText(rawText) { + if (rawText === undefined || rawText === null) { + return []; + } + if (Array.isArray(rawText)) { + return rawText.map(code => this.normalizeSnCode(code)).filter(Boolean); + } + return String(rawText) + .split(/[\s,;]+/) + .map(code => this.normalizeSnCode(code)) + .filter(Boolean); + } + + /** + * 归一化订单明细主键,统一为字符串键,避免数字/字符串混用导致分组错乱。 + * @param {*} rawItemKey 明细ID原始值。 + * @return {string} 明细ID键,非法返回空串。 + */ + normalizeSnItemKey(rawItemKey) { + return this.normalizeSnStockKey(rawItemKey); + } + + /** + * 归一化仓库商品ID(stock_id)键,统一为字符串键。 + * @param {*} rawStockKey 仓库商品ID原始值。 + * @return {string} 仓库商品ID键,非法返回空串。 + */ + normalizeSnStockKey(rawStockKey) { + if (rawStockKey === undefined || rawStockKey === null) { + return ''; + } + const stockKey = String(rawStockKey).trim(); + if (!stockKey) { + return ''; + } + return /^\d+$/.test(stockKey) ? String(Number(stockKey)) : stockKey; + } + + /** + * 统计按明细分组的 SN 总数。 + * @param {Map} codesByItem 按明细分组的 SN。 + * @return {number} SN 总数。 + */ + countSnCodes(codesByItem) { + let total = 0; + for (const codes of codesByItem.values()) { + total += codes.length; + } + return total; + } + + /** + * 读取订单明细。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise} 订单明细列表。 + */ + async loadOrderItemsForSn(orderId, warehouseId, transaction) { + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const rows = await orderItemsModel.findAll({ + where: { order_id: orderId }, + attributes: [ 'id', 'stock_id', 'item_code', 'item_name', 'plan_qty' ], + order: [[ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 读取明细对应商品的序列号管理标记,返回序列号管理商品ID集合。 + * @param {Object[]} items 订单明细。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 启用了序列号管理的仓库商品ID集合。 + */ + async loadSnStockIdSet(items, warehouseId) { + const { ctx } = this; + const snStockIdSet = new Set(); + const stockIds = [ ...new Set( + (items || []).map(item => Number(item.stock_id)).filter(id => Number.isInteger(id) && id > 0) + ) ]; + + if (stockIds.length === 0) { + return snStockIdSet; + } + + const stockModel = ctx.model && ctx.model.StockWarehouse; + if (!stockModel) { + throw new Error('商品仓库模型不存在,无法校验SN码'); + } + + const { Op } = this.app.Sequelize; + // paranoid:false 保证商品被软删后仍能读到 is_sn_mgmt,避免历史订单无法校验 SN + const stockRows = await stockModel.findAll({ + where: { + id: { [Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'is_sn_mgmt' ], + raw: true, + paranoid: false, + }); + + for (const row of (stockRows || [])) { + if (String(row.is_sn_mgmt || '').trim().toUpperCase() !== 'Y') { + continue; + } + const stockId = Number(row.id); + if (Number.isInteger(stockId) && stockId > 0) { + snStockIdSet.add(stockId); + } + } + + return snStockIdSet; + } + + /** + * 按序列号管理商品(stock_id)聚合订单明细。 + * @param {Object[]} items 订单明细。 + * @param {Set} snStockIdSet 序列号管理商品ID集合。 + * @return {Map} 仓库商品ID键 -> 该商品的订单明细(按明细ID升序)。 + */ + buildSnStockItemMap(items, snStockIdSet) { + const stockItemMap = new Map(); + const sortedItems = (Array.isArray(items) ? items : []) + .slice() + .sort((a, b) => Number(a && a.id || 0) - Number(b && b.id || 0)); + + for (const item of sortedItems) { + if (!snStockIdSet || !snStockIdSet.has(Number(item && item.stock_id))) { + continue; + } + const stockKey = this.normalizeSnStockKey(item.stock_id); + if (!stockKey) { + continue; + } + if (!stockItemMap.has(stockKey)) { + stockItemMap.set(stockKey, []); + } + stockItemMap.get(stockKey).push(item); + } + + return stockItemMap; + } + + /** + * 校验提交的 SN 是否按商品齐套。 + * @param {Object} params 参数。 + * @param {Map} params.stockItemMap 序列号管理商品 -> 明细。 + * @param {Map} params.codesByStock 提交的 SN(商品ID -> SN 列表)。 + */ + assertSnStockCodesMatched({ stockItemMap, codesByStock }) { + for (const [ stockKey, codes ] of codesByStock.entries()) { + const items = stockItemMap.get(stockKey); + if (!items || items.length === 0) { + throw new Error(`提交的SN码对应商品不在订单中或未启用序列号管理:stock_id=${stockKey}`); + } + const label = this.buildSnItemLabel(items[0]); + const requiredQty = this.sumSnItemPlanQty(items); + if (requiredQty <= 0) { + throw new Error(`商品[${label}]数量异常,无法校验SN码`); + } + if (codes.length !== requiredQty) { + throw new Error(`商品[${label}]需提交${requiredQty}个SN码,实际提交${codes.length}个`); + } + } + + for (const [ stockKey, items ] of stockItemMap.entries()) { + if (codesByStock.has(stockKey)) { + continue; + } + const requiredQty = this.sumSnItemPlanQty(items); + // 数量为 0 的序列号商品不需要提交 SN,避免历史脏数据阻塞复核 + if (requiredQty <= 0) { + continue; + } + throw new Error( + `商品[${this.buildSnItemLabel(items[0])}]需提交${requiredQty}个SN码,实际提交0个` + ); + } + } + + /** + * 汇总同一商品下所有明细的 plan_qty(仅统计合法正整数)。 + * @param {Object[]} items 同一商品的订单明细。 + * @return {number} 需要的 SN 总数。 + */ + sumSnItemPlanQty(items) { + let total = 0; + for (const item of (Array.isArray(items) ? items : [])) { + const planQty = Number(item && item.plan_qty); + if (Number.isInteger(planQty) && planQty > 0) { + total += planQty; + } + } + return total; + } + + /** + * 把「商品 -> SN 列表」按明细 plan_qty 顺序拆分到具体订单明细,供落库使用。 + * @param {Object} params 参数。 + * @param {Map} params.stockItemMap 序列号管理商品 -> 明细。 + * @param {Map} params.codesByStock 提交的 SN(商品ID -> SN 列表)。 + * @return {Map} 订单明细ID键 -> SN 列表。 + */ + mapStockCodesToOrderItems({ stockItemMap, codesByStock }) { + const codesByItem = new Map(); + + for (const [ stockKey, codes ] of codesByStock.entries()) { + const items = stockItemMap.get(stockKey) || []; + let cursor = 0; + + for (const item of items) { + const planQty = Number(item && item.plan_qty); + if (!Number.isInteger(planQty) || planQty <= 0) { + continue; + } + const itemCodes = codes.slice(cursor, cursor + planQty); + cursor += planQty; + if (itemCodes.length === 0) { + continue; + } + const itemKey = this.normalizeSnItemKey(item.id); + if (!itemKey) { + continue; + } + codesByItem.set(itemKey, itemCodes); + } + + if (cursor < codes.length) { + const tailItem = items[items.length - 1]; + const tailKey = tailItem ? this.normalizeSnItemKey(tailItem.id) : ''; + if (tailKey) { + const merged = (codesByItem.get(tailKey) || []).concat(codes.slice(cursor)); + codesByItem.set(tailKey, merged); + } + } + } + + return codesByItem; + } + + /** + * 校验同一批提交内 SN 不重复。 + * @param {string[]} allCodes 全部 SN。 + */ + assertSnCodesUnique(allCodes) { + const seen = new Set(); + const duplicated = new Set(); + for (const code of allCodes) { + if (seen.has(code)) { + duplicated.add(code); + } + seen.add(code); + } + if (duplicated.size > 0) { + const sample = Array.from(duplicated).slice(0, 5).join('、'); + throw new Error(`SN码重复提交:${sample}`); + } + } + + /** + * 生成明细展示文案,优先商品编码 + 名称。 + * @param {Object} item 订单明细。 + * @return {string} 展示文案。 + */ + buildSnItemLabel(item = {}) { + const code = String(item.item_code || '').trim(); + const name = String(item.item_name || '').trim(); + if (code && name) { + return `${code} ${name}`; + } + return code || name || String(item.id || ''); + } + + /** + * 校验 SN 是否已发过并写入 SN 主表与流水表。 + * @param {Object} params 参数。 + * @param {number} params.orderId 订单ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} [params.storeId] 货主ID(从订单冗余写入,便于按货主隔离查询)。 + * @param {Map} params.codesByItem 按明细分组的 SN。 + * @param {string[]} params.allCodes 全部 SN。 + * @param {Object} [params.operator] 操作人。 + * @param {Date} params.now 复核时间。 + * @param {Object} [params.transaction] Sequelize 事务。 + * @return {Promise<{ createdCount: number, reusedCount: number }>} 新增写入数与此前已绑定同明细的幂等复用数。 + */ + async persistRecheckSn({ orderId, warehouseId, storeId = 0, codesByItem, allCodes, operator = {}, now = new Date(), transaction }) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const orderItemSnModel = ctx.model && ctx.model.OrderItemSn; + const orderItemSnLogModel = ctx.model && ctx.model.OrderItemSnLog; + + if (!orderItemSnModel || !orderItemSnLogModel) { + throw new Error('订单SN模型不存在,无法写入SN码'); + } + + const itemIdByCode = new Map(); + for (const [ itemKey, codes ] of codesByItem.entries()) { + for (const code of codes) { + itemIdByCode.set(code, Number(itemKey)); + } + } + + const lockOption = transaction && transaction.LOCK ? { lock: transaction.LOCK.UPDATE } : {}; + const existingRows = await orderItemSnModel.findAll({ + where: { + warehouse_id: warehouseId, + sn_code: { [Op.in]: allCodes }, + }, + attributes: [ 'id', 'order_id', 'order_item_id', 'sn_code', 'sn_status' ], + raw: true, + ...lockOption, + transaction, + }); + + const existingByCode = new Map(); + for (const row of existingRows || []) { + existingByCode.set(String(row.sn_code), row); + } + + const createRows = []; + const upgradeRows = []; + let reusedCount = 0; + + for (const code of allCodes) { + const existing = existingByCode.get(code); + if (!existing) { + createRows.push(code); + continue; + } + + const sameOrder = Number(existing.order_id) === orderId; + const sameItem = Number(existing.order_item_id) === Number(itemIdByCode.get(code)); + const existingStatus = String(existing.sn_status || '').trim().toUpperCase(); + + if (!sameOrder || !sameItem) { + throw new Error(`SN码[${code}]已被其他订单占用,不可重复使用`); + } + if (existingStatus === SN_STATUS_VERIFIED) { + reusedCount += 1; + continue; + } + if (existingStatus === SN_STATUS_BOUND) { + upgradeRows.push(existing); + continue; + } + throw new Error(`SN码[${code}]状态为${existingStatus || 'UNKNOWN'},不可用于当前订单复核`); + } + + const createCodeSet = new Set(createRows); + await this.assertSnCodesNotShipped({ + warehouseId, + allCodes: allCodes.filter(code => createCodeSet.has(code)), + orderId, + transaction, + }); + + const normalizedStoreId = Number(storeId) > 0 ? Number(storeId) : null; + const createdRows = []; + if (createRows.length > 0) { + const payload = createRows.map(code => ({ + warehouse_id: warehouseId, + store_id: normalizedStoreId, + order_id: orderId, + order_item_id: itemIdByCode.get(code), + sn_code: code, + sn_status: SN_STATUS_VERIFIED, + verify_status: VERIFY_STATUS_PASS, + bound_at: now, + verified_at: now, + version: 1, + created_at: now, + updated_at: now, + })); + + let instances; + try { + instances = await orderItemSnModel.bulkCreate(payload, { transaction }); + } catch (error) { + if (this.isDuplicateKeyError(error)) { + throw new Error('SN码已被占用,请核对后重新提交'); + } + throw error; + } + + for (const instance of instances || []) { + createdRows.push({ + sn_id: instance.id, + order_item_id: Number(instance.order_item_id), + sn_code: String(instance.sn_code), + }); + } + } + + if (upgradeRows.length > 0) { + await orderItemSnModel.update({ + sn_status: SN_STATUS_VERIFIED, + verify_status: VERIFY_STATUS_PASS, + verified_at: now, + updated_at: now, + version: this.app.Sequelize.literal('version + 1'), + ...(normalizedStoreId !== null && { store_id: normalizedStoreId }), + }, { + where: { id: { [Op.in]: upgradeRows.map(row => row.id) } }, + transaction, + }); + } + + const operatorId = this.normalizeSnOperatorId(operator); + const logRows = [ + ...createdRows.map(row => ({ + warehouse_id: warehouseId, + sn_id: row.sn_id, + order_id: orderId, + order_item_id: row.order_item_id, + sn_code: row.sn_code, + from_sn_status: null, + to_sn_status: SN_STATUS_VERIFIED, + verify_status: VERIFY_STATUS_PASS, + action_type: RECHECK_LOG_ACTION, + remark: '复核提交SN核验', + operator_id: operatorId, + operated_at: now, + created_at: now, + updated_at: now, + })), + ...upgradeRows.map(row => ({ + warehouse_id: warehouseId, + sn_id: row.id, + order_id: orderId, + order_item_id: Number(row.order_item_id), + sn_code: String(row.sn_code), + from_sn_status: SN_STATUS_BOUND, + to_sn_status: SN_STATUS_VERIFIED, + verify_status: VERIFY_STATUS_PASS, + action_type: RECHECK_LOG_ACTION, + remark: '复核提交SN核验', + operator_id: operatorId, + operated_at: now, + created_at: now, + updated_at: now, + })), + ]; + + if (logRows.length > 0) { + await orderItemSnLogModel.bulkCreate(logRows, { transaction }); + } + + return { createdCount: createdRows.length, reusedCount }; + } + + /** + * 校验 SN 是否已经随其它订单发出(流水存在 VERIFIED/REISSUED 记录)。 + * @param {Object} params 参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {string[]} params.allCodes 待校验 SN。 + * @param {number} params.orderId 当前订单ID。 + * @param {Object} [params.transaction] Sequelize 事务。 + * @return {Promise} 无返回值,命中已发货 SN 时抛错。 + */ + async assertSnCodesNotShipped({ warehouseId, allCodes, orderId, transaction }) { + if (!Array.isArray(allCodes) || allCodes.length === 0) { + return; + } + + const { ctx } = this; + const { Op } = this.app.Sequelize; + const orderItemSnLogModel = ctx.model && ctx.model.OrderItemSnLog; + if (!orderItemSnLogModel) { + throw new Error('订单SN流水模型不存在,无法校验SN码'); + } + + const shippedLogs = await orderItemSnLogModel.findAll({ + where: { + warehouse_id: warehouseId, + sn_code: { [Op.in]: allCodes }, + to_sn_status: { [Op.in]: SHIPPED_SN_STATUS_LIST }, + order_id: { [Op.ne]: orderId }, + }, + attributes: [ 'sn_code', 'order_id', 'to_sn_status' ], + raw: true, + transaction, + }); + + if (Array.isArray(shippedLogs) && shippedLogs.length > 0) { + const first = shippedLogs[0]; + throw new Error( + `SN码[${first.sn_code}]已随订单[${first.order_id}]发货,不可重复使用` + ); + } + } + + /** + * 归一化操作人ID,非数字操作人(如 system)落空,避免 BIGINT 写入失败。 + * @param {Object} operator 操作人。 + * @return {number|null} 操作人ID。 + */ + normalizeSnOperatorId(operator = {}) { + const rawId = String(operator && operator.id || '').trim(); + if (!/^\d+$/.test(rawId)) { + return null; + } + const parsed = Number(rawId); + return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null; + } + + /** + * 判断是否唯一键冲突错误。 + * @param {Object} error 错误对象。 + * @return {boolean} 是否唯一键冲突。 + */ + isDuplicateKeyError(error) { + if (!error) { + return false; + } + if (error.name === 'SequelizeUniqueConstraintError') { + return true; + } + return Boolean(error.parent && error.parent.code === 'ER_DUP_ENTRY'); + } +} + +module.exports = OrderItemSnService; 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_packing.js b/app/service/systems/order_packing.js new file mode 100644 index 0000000..9d74fe9 --- /dev/null +++ b/app/service/systems/order_packing.js @@ -0,0 +1,1225 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); +const Service = require('egg').Service; +const { stripWaybillSegmentSuffix, escapeLikeWildcards } = require('../../lib/waybill_code'); + +/** 打包任务导出主表分页拉取大小 */ +const PACK_TASK_EXPORT_PAGE_SIZE = 500; +/** 打包任务导出关联数据分批拉取大小 */ +const PACK_TASK_EXPORT_BATCH_SIZE = 100; + +/** + * 快捷搜索运单号模糊降级的最小关键词长度。 + * 运单号通常较长(如 JDX057941864338),短于该长度的输入(如单字符 "7")没有模糊搜索意义, + * 且 %短词% 极易误命中海量历史单号(实测 "7" 可命中 24149 行), + * 违背「不完整短串不得命中订单」的业务约束,因此禁止短词降级进入 %kw% 模糊分支。 + */ +const QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH = 4; + +/** + * 打包任务服务层(仓库侧)。 + * 负责打包任务列表查询、详情查询等仓库维度的打包管理业务逻辑。 + * 数据来源:wms_pack_task 表。 + */ +class OrderPackingService extends Service { + /** + * 获取仓库的录制电脑 ID(带缓存)。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 录制电脑ID,找不到返回 null + */ + async _getRecordingComputerId(warehouseId) { + const cacheKey = `_recordingComputer_${warehouseId}`; + if (this[cacheKey] !== undefined) { + return this[cacheKey]; + } + const row = await this.ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + attributes: [ 'id' ], + raw: true, + }); + this[cacheKey] = row ? row.id : null; + return this[cacheKey]; + } + + /** + * 构建视频完整 URL。 + * 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath} + * @param {number} warehouseId 仓库ID + * @param {number|null} recordingComputerId 录制电脑ID + * @param {string} videoPath 视频路径 + * @return {string} 完整 URL + */ + _buildVideoUrl(warehouseId, recordingComputerId, videoPath) { + if (!videoPath || !recordingComputerId) { + return videoPath || ''; + } + return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${videoPath}`; + } + + /** + * 创建带业务错误码的异常对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 构建列表筛选条件(list 与 exportPackTask 复用同一套语义,导出会自动获得同一筛选语义)。 + * + * @param {Object} where 筛选条件对象(与 list 入参一致)。其中 operator_text(打包员/作业人员姓名, + * 对应 wms_pack_task.operator_text 多人姓名逗号拼接快照列)支持 {operator,value} 标准结构, + * value 支持字符串或字符串数组(多值取并集):contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义)、 + * eq/in 精确(单值等值、多值 Op.in)、ne 不等于(取首值)、notlike 排除(多值逐个排除)。 + * @param {Object} Op Sequelize Op 对象 + * @param {number} warehouseId 仓库ID + * @return {Promise} Sequelize where 条件对象 + */ + async _buildListWhere(where = {}, Op, warehouseId) { + const { ctx, app } = this; + + const queryWhere = { warehouse_id: warehouseId }; + + // 状态筛选 + if (where.status !== undefined && where.status !== null) { + const statusValue = where.status?.value ?? where.status; + if (statusValue !== '' && statusValue !== undefined && statusValue !== null) { + queryWhere.status = Number(statusValue); + } + } + + // 打包模式筛选 + if (where.pack_mode !== undefined && where.pack_mode !== null) { + const packModeValue = where.pack_mode?.value ?? where.pack_mode; + if (packModeValue !== '' && packModeValue !== undefined && packModeValue !== null) { + queryWhere.pack_mode = Number(packModeValue); + } + } + + // 运单号筛选:通过 wms_order_express 表解析 order_id,再按 order_id 过滤(wms_pack_task.waybill_code 通常为空)。 + // 支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多单号取并集): + // - operator=contains/like:按下发单号模糊匹配 LIKE '%单号%'(通配符已转义),可命中 '主体-1-1-' 等分段单号; + // - 其他(缺省/eq):完整单号等值 + 剥离 -1-1- 分段后缀主体等值 + 主体前缀 LIKE '主体-%', + // 不落入 %短串% 模糊分支(保持「不完整短串不得命中订单」的业务约束)。 + if (where.waybill_code) { + const waybillValue = where.waybill_code?.value ?? where.waybill_code; + const waybillOperator = String(where.waybill_code?.operator || '').trim().toLowerCase(); + const waybillList = (Array.isArray(waybillValue) ? waybillValue : [ waybillValue ]) + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(Boolean); + + if (waybillList.length > 0) { + const isContainsWaybill = waybillOperator === 'contains' || waybillOperator === 'like'; + const waybillConditions = []; + + for (const waybillCode of waybillList) { + if (isContainsWaybill) { + waybillConditions.push({ + waybill_code: { [Op.like]: `%${escapeLikeWildcards(waybillCode)}%` }, + }); + continue; + } + + // 剥离分段后缀得到主体运单号(JDX057941864338-1-1- → JDX057941864338) + const baseWaybill = stripWaybillSegmentSuffix(waybillCode); + const escapedBase = escapeLikeWildcards(baseWaybill); + // 等值匹配集合:完整单号等值 + 主体单号等值 + 主体单号前缀段(主体相同、分段序号不同) + waybillConditions.push({ waybill_code: waybillCode }); + if (baseWaybill !== waybillCode) { + waybillConditions.push({ waybill_code: baseWaybill }); + } + if (escapedBase) { + waybillConditions.push({ waybill_code: { [Op.like]: `${escapedBase}-%` } }); + } + } + + const expressRecords = await ctx.model.OrderExpress.findAll({ + where: { + warehouse_id: warehouseId, + delete_at: null, + [Op.or]: waybillConditions, + }, + attributes: [ 'order_id' ], + raw: true, + }); + const matchedOrderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ]; + if (matchedOrderIds.length > 0) { + queryWhere.order_id = { [Op.in]: matchedOrderIds }; + } else { + // 无匹配运单号 → 强制返回空结果 + queryWhere.id = -1; + } + } + } + + // 波次号筛选:支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多值取并集)。 + // - operator=eq / in:精确匹配(单值等值,多值 Op.in); + // - operator=ne:不等于; + // - operator=contains / like 与缺省:模糊匹配 LIKE '%值%'(通配符已转义,缺省保持历史模糊行为)。 + if (where.wave_no) { + const waveNoValue = where.wave_no?.value ?? where.wave_no; + const waveNoOperator = String(where.wave_no?.operator || '').trim().toLowerCase(); + const waveNoList = (Array.isArray(waveNoValue) ? waveNoValue : [ waveNoValue ]) + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(Boolean); + + if (waveNoList.length > 0) { + if (waveNoOperator === 'eq' || waveNoOperator === 'in') { + queryWhere.wave_no = waveNoList.length === 1 ? waveNoList[0] : { [Op.in]: waveNoList }; + } else if (waveNoOperator === 'ne') { + queryWhere.wave_no = { [Op.ne]: waveNoList[0] }; + } else if (waveNoList.length === 1) { + queryWhere.wave_no = { [Op.like]: `%${escapeLikeWildcards(waveNoList[0])}%` }; + } else { + const likeConditions = waveNoList.map( + item => ({ wave_no: { [Op.like]: `%${escapeLikeWildcards(item)}%` } }) + ); + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + { [Op.or]: likeConditions }, + ]; + } + } + } + + // 打包员(作业人员)筛选:wms_pack_task.operator_text 为多人姓名逗号拼接快照(如 '小吴哥,阿猫')。 + // 支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多值取并集): + // - operator=contains / like 与缺省:模糊匹配 LIKE '%值%'(通配符已转义); + // - operator=eq / in:精确匹配(单值等值,多值 Op.in); + // - operator=ne:不等于(取首值); + // - operator=notlike:NOT LIKE '%值%'(多值时逐个排除)。 + // 本函数同时被 list 与 exportPackTask 复用,因此导出 Excel 会自动获得同一筛选语义。 + if (where.operator_text) { + // 空值识别:仅当条件是对象且 value 为 null/undefined 时视为空(忽略该条件、不过滤), + // 不得回退到条件对象本身,否则会被 String 化为 '[object Object]' 产生恒空过滤。 + const operatorTextCondition = where.operator_text; + const isConditionObject = operatorTextCondition + && typeof operatorTextCondition === 'object' + && !Array.isArray(operatorTextCondition); + const operatorTextRawValue = isConditionObject ? operatorTextCondition.value : operatorTextCondition; + const operatorTextOperator = isConditionObject + ? String(operatorTextCondition.operator || '').trim().toLowerCase() + : ''; + const operatorTextList = (Array.isArray(operatorTextRawValue) ? operatorTextRawValue : [ operatorTextRawValue ]) + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(Boolean); + + if (operatorTextList.length > 0) { + if (operatorTextOperator === 'eq' || operatorTextOperator === 'in') { + queryWhere.operator_text = operatorTextList.length === 1 + ? operatorTextList[0] + : { [Op.in]: operatorTextList }; + } else if (operatorTextOperator === 'ne') { + queryWhere.operator_text = { [Op.ne]: operatorTextList[0] }; + } else if (operatorTextOperator === 'notlike') { + if (operatorTextList.length === 1) { + queryWhere.operator_text = { [Op.notLike]: `%${escapeLikeWildcards(operatorTextList[0])}%` }; + } else { + const notLikeConditions = operatorTextList.map( + item => ({ operator_text: { [Op.notLike]: `%${escapeLikeWildcards(item)}%` } }) + ); + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), ...notLikeConditions ]; + } + } else if (operatorTextList.length === 1) { + queryWhere.operator_text = { [Op.like]: `%${escapeLikeWildcards(operatorTextList[0])}%` }; + } else { + const likeConditions = operatorTextList.map( + item => ({ operator_text: { [Op.like]: `%${escapeLikeWildcards(item)}%` } }) + ); + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + { [Op.or]: likeConditions }, + ]; + } + } + } + + // 订单ID精确匹配 + if (where.order_id !== undefined && where.order_id !== null) { + const orderIdValue = where.order_id?.value ?? where.order_id; + if (orderIdValue !== '' && orderIdValue !== undefined && orderIdValue !== null) { + queryWhere.order_id = Number(orderIdValue); + } + } + + // 工作台ID精确匹配 + if (where.workbench_id !== undefined && where.workbench_id !== null) { + const workbenchIdValue = where.workbench_id?.value ?? where.workbench_id; + if (workbenchIdValue !== '' && workbenchIdValue !== undefined && workbenchIdValue !== null) { + queryWhere.workbench_id = Number(workbenchIdValue); + } + } + + // 快捷搜索:支持波次号直接模糊匹配 + 运单号通过 express → order → wave 链路解析 + if (where.quickWhere) { + const quickValue = where.quickWhere?.value ?? where.quickWhere; + if (quickValue && String(quickValue).trim()) { + const kw = String(quickValue).trim(); + const orConditions = []; + + // 1. 波次号直接模糊匹配(用户可能直接搜波次号) + orConditions.push({ wave_no: { [Op.like]: `%${kw}%` } }); + + // 2. 运单号解析:express → order → wave + // 团购波次 → 按 wave_no 查 packing 表;散单 → 按 order_id 查 packing 表 + // 业务规则:先剥离包裹序号后缀(如 -1-1-),主体运单号等值匹配为最高优先级; + // 精确未命中时才降级为模糊 like,保留快捷搜索能力 + const baseKw = stripWaybillSegmentSuffix(kw); + const escapedKw = escapeLikeWildcards(baseKw); + const exactWaybillConditions = [ + { waybill_code: kw }, + ...(baseKw !== kw ? [{ waybill_code: baseKw }] : []), + ...(escapedKw ? [{ waybill_code: { [Op.like]: `${escapedKw}-%` } }] : []), + ]; + let expressRecords = await ctx.model.OrderExpress.findAll({ + where: { + [Op.or]: exactWaybillConditions, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'order_id' ], + raw: true, + }); + // 精确未命中 → 降级为模糊匹配(兼容快捷搜索输入非完整运单号的场景) + // 关键词校验:短词(trim 后长度小于 QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH,含纯单字符) + // 禁止降级进入 %kw% 模糊分支——运单号通常较长,%短词% 极易误命中大量历史单号, + // 违背「不完整短串不得命中订单」的业务约束,此时运单号解析保持空结果 + if (expressRecords.length === 0 && kw.length >= QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH) { + expressRecords = await ctx.model.OrderExpress.findAll({ + where: { + waybill_code: { [Op.like]: `%${kw}%` }, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'order_id' ], + raw: true, + }); + } + + if (expressRecords.length > 0) { + const orderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ]; + + if (orderIds.length > 0) { + // 查 order_delivery 分表获取 wave_id(current + dispatch) + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const orderTableModels = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + const orderRecords = []; + for (const entry of orderTableModels) { + try { + const model = await entry.getModel(); + if (!model) continue; + const rows = await model.findAll({ + where: { id: { [Op.in]: orderIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id' ], + raw: true, + }); + orderRecords.push(...rows); + } catch (_err) { continue; } + } + + // order_id → wave_id 映射 + const orderWaveMap = new Map(); + const noWaveOrderIds = []; + orderRecords.forEach(o => { + if (o.wave_id > 0) { + orderWaveMap.set(o.id, o.wave_id); + } else { + noWaveOrderIds.push(o.id); + } + }); + + // 未匹配到 order_delivery 的 order_id 也按散单处理 + const matchedOrderIds = new Set(orderRecords.map(o => o.id)); + orderIds.forEach(oid => { + if (!matchedOrderIds.has(oid)) { + noWaveOrderIds.push(oid); + } + }); + + const waveIds = [ ...new Set(orderWaveMap.values()) ]; + + if (waveIds.length > 0) { + // 查 wms_wave_batch 获取 wave_type 和 wave_no + const waveRecords = await ctx.model.WaveBatch.findAll({ + where: { wave_id: { [Op.in]: waveIds } }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // wave_id → { wave_no, wave_type } 映射 + const waveMap = new Map(); + waveRecords.forEach(w => { + waveMap.set(w.wave_id, { wave_no: w.wave_no, wave_type: w.wave_type }); + }); + + // 分离:团购波次号 / 散单订单ID + const groupBuyWaveNos = []; + const singleOrderIds = [ ...noWaveOrderIds ]; + + orderRecords.forEach(o => { + const waveInfo = waveMap.get(o.wave_id); + if (waveInfo) { + if (waveInfo.wave_type === 1) { + // 团购 → 按波次号查 packing 表 + if (waveInfo.wave_no) { + groupBuyWaveNos.push(waveInfo.wave_no); + } + } else { + // 散单(wave_type=2) → 按 order_id 查 packing 表 + singleOrderIds.push(o.id); + } + } else { + // wave_id 在 wms_wave_batch 中不存在,按散单处理 + singleOrderIds.push(o.id); + } + }); + + if (groupBuyWaveNos.length > 0) { + orConditions.push({ wave_no: { [Op.in]: [ ...new Set(groupBuyWaveNos) ] } }); + } + if (singleOrderIds.length > 0) { + orConditions.push({ order_id: { [Op.in]: [ ...new Set(singleOrderIds) ] } }); + } + } else { + // 所有订单都没有波次(wave_id = 0),全部按散单处理 + orConditions.push({ order_id: { [Op.in]: orderIds } }); + } + } + } + + queryWhere[Op.or] = orConditions; + } + } + + // has_video 筛选:1=有视频 2=无视频 + if (where.has_video !== undefined && where.has_video !== null) { + const hasVideoValue = Number(where.has_video?.value ?? where.has_video); + if (hasVideoValue === 1) { + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + app.Sequelize.literal('EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL)'), + ]; + } else if (hasVideoValue === 2) { + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + app.Sequelize.literal('NOT EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL)'), + ]; + } + } + + // video_enable 筛选:1=录像可用 2=录像不可用 + if (where.video_enable !== undefined && where.video_enable !== null) { + const videoEnableValue = Number(where.video_enable?.value ?? where.video_enable); + if (videoEnableValue === 1) { + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + app.Sequelize.literal("EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"), + ]; + } else if (videoEnableValue === 2) { + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + app.Sequelize.literal("NOT EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"), + ]; + } + } + + // 时间范围筛选:start_time / end_time / create_time + // 支持 {operator:'between', value:[start,end]} 或直接传 [start,end] + const applyTimeRangeFilter = (field, cond) => { + if (!cond) return; + const operator = String(cond?.operator || '').toLowerCase(); + let range = cond?.value ?? cond; + if (!Array.isArray(range) && operator === 'between' && range && typeof range === 'object') { + range = [ range.start ?? range.from ?? range.begin, range.end ?? range.to ?? range.finish ]; + } + if (!Array.isArray(range)) return; + const [ startVal, endVal ] = range; + if (startVal !== undefined && startVal !== null && String(startVal).trim() !== '') { + queryWhere[field] = { ...(queryWhere[field] || {}), [Op.gte]: new Date(startVal) }; + } + if (endVal !== undefined && endVal !== null && String(endVal).trim() !== '') { + queryWhere[field] = { ...(queryWhere[field] || {}), [Op.lte]: new Date(endVal) }; + } + }; + + // 开始打包时间范围(统一 between 写法 + 兼容旧拆分写法) + applyTimeRangeFilter('start_time', where.start_time); + if (where.start_time_start) { + const startTimeStart = where.start_time_start?.value ?? where.start_time_start; + if (startTimeStart) { + queryWhere.start_time = { ...(queryWhere.start_time || {}), [Op.gte]: new Date(startTimeStart) }; + } + } + if (where.start_time_end) { + const startTimeEnd = where.start_time_end?.value ?? where.start_time_end; + if (startTimeEnd) { + queryWhere.start_time = { ...(queryWhere.start_time || {}), [Op.lte]: new Date(startTimeEnd) }; + } + } + + // 结束打包时间范围 + applyTimeRangeFilter('end_time', where.end_time); + + // 创建时间范围 + applyTimeRangeFilter('create_time', where.create_time); + + return queryWhere; + } + + /** + * 构建列表排序(list 与 export 复用同一套语义)。 + * @param {Object} sort 排序参数 { sortField, sortOrder } + * @return {Array} Sequelize order 数组 + */ + _buildListOrder(sort = {}) { + const sortField = sort.sortField || 'create_time'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ 'id', 'order_id', 'warehouse_id', 'workbench_id', 'wave_id', 'pack_quantity', 'pack_mode', 'status', 'start_time', 'end_time', 'create_time', 'update_time' ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_time'; + return [[ actualSortField, sortOrder ]]; + } + /** + * 打包任务列表查询(仓库侧)。 + * 按仓库维度(warehouse_id)查询打包任务,支持分页、筛选、排序。 + * + * @param {Object} where 筛选条件对象 + * @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常 + * @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购 + * @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤)。支持 {operator,value} 标准结构,value 支持字符串或数组: + * operator=contains/like 时按 LIKE '%单号%' 模糊匹配(可命中分段单号);缺省/eq 时先剥离一单多件分段后缀、主体单号等值匹配 + 主体前缀匹配 + * @param {Object} [where.wave_no] 波次号。支持 {operator,value} 标准结构,value 支持字符串或数组:eq/in 精确、ne 不等、contains/like 与缺省为模糊匹配 + * @param {Object} [where.operator_text] 打包员/作业人员姓名(wms_pack_task.operator_text 快照列,多人姓名逗号拼接)。支持 {operator,value} 标准结构,value 支持字符串或数组:contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义、多值取并集)、eq/in 精确、ne 不等于(取首值)、notlike 排除(多值逐个排除) + * @param {Object} [where.order_id] 订单ID(精确匹配) + * @param {Object} [where.workbench_id] 工作台ID(精确匹配) + * @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查;运单号先剥离分段后缀等值匹配,精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中) + * @param {Object} [where.start_time] 开始打包时间范围,支持 {operator:'between', value:[start,end]} + * @param {Object} [where.start_time_start] 开始打包时间起始(兼容旧写法) + * @param {Object} [where.start_time_end] 开始打包时间结束(兼容旧写法) + * @param {Object} [where.end_time] 结束打包时间范围,支持 {operator:'between', value:[start,end]} + * @param {Object} [where.create_time] 创建时间范围,支持 {operator:'between', value:[start,end]} + * @param {Object} pagination 分页参数 { page, pageSize } + * @param {Object} sort 排序参数 { sortField, sortOrder } + * @return {Promise} 打包任务列表与分页信息 + */ + async list(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(Number(pagination.page) || 1, 1); + const pageSize = Math.max(Number(pagination.pageSize) || 20, 1); + + // 仓库上下文 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库,无法查询打包任务', + data: { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + }, + }; + } + + // 构建查询条件(与导出复用同一套筛选语义) + const queryWhere = await this._buildListWhere(where, Op, warehouseId); + + + // 排序(与导出复用同一套排序语义) + const order = this._buildListOrder(sort); + + // 查询(含工作台、视频和运单关联) + // 性能优化:count 与 rows 分离。findAndCountAll 携带 hasMany include(videos/expresses)时, + // count 会生成 COUNT(DISTINCT) + 双 LEFT JOIN(生产实测 520ms),拆开后 count 走单表索引(约 44ms)。 + const count = await ctx.model.PackTask.count({ where: queryWhere }); + const rows = await ctx.model.PackTask.findAll({ + where: queryWhere, + order, + limit: pageSize, + offset: (page - 1) * pageSize, + include: [ + { + model: ctx.model.Workbench, + as: 'workbench', + attributes: [ 'id', 'name', 'type' ], + }, + { + model: ctx.model.PackTaskVideo, + as: 'videos', + attributes: [ 'id', 'video_url', 'camera_id', 'status' ], + required: false, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + attributes: [ 'id', 'custom_name', 'channel_name' ], + }, + ], + }, + { + model: ctx.model.OrderExpress, + as: 'expresses', + attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ], + where: { warehouse_id: warehouseId, delete_at: null }, + required: false, + }, + ], + }); + + // 扁平化输出 + const recordingComputerId = await this._getRecordingComputerId(warehouseId); + const list = rows.map(row => { + const plain = row.get({ plain: true }); + const rawVideos = plain.videos || []; + const { app: appCtx } = this; + return { + ...plain, + start_time: plain.start_time ? appCtx.formatDate(plain.start_time) : null, + end_time: plain.end_time ? appCtx.formatDate(plain.end_time) : null, + create_time: plain.create_time ? appCtx.formatDate(plain.create_time) : null, + update_time: plain.update_time ? appCtx.formatDate(plain.update_time) : null, + deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null, + workbench_name: plain.workbench?.name || null, + workbench_type: plain.workbench?.type || null, + has_video: rawVideos.length > 0 ? 1 : 2, + video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2, + videos: rawVideos.map(v => ({ + id: v.id, + video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url), + status: v.status || null, + camera_id: v.camera_id, + camera_name: v.camera?.custom_name || v.camera?.channel_name || null, + })), + expresses: (plain.expresses || []).map(e => ({ + id: e.id, + waybill_code: e.waybill_code, + logistics_code: e.logistics_code, + logistics_name: e.logistics_name, + logistics_interface_name: e.logistics_interface_name || null, + platform_code: e.platform_code || null, + status: e.status, + })), + workbench: undefined, + }; + }); + + const totalPages = Math.ceil(count / pageSize) || 0; + + return { + code: 200, + message: 'ok', + data: { + list, + pagination: { + page, + pageSize, + total: count, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }, + }; + } + + /** + * 导出打包任务列表(单 Sheet Excel,异步任务内部调用)。 + * 复用 list 的 where/sort 语义;仓库隔离由方法层注入 warehouseId,此处再强制兜底; + * 分页拉取主表全量数据后批量关联工作台/视频/运单,流式生成 Excel 并上传。 + * + * @param {Object} options 导出选项。 + * @param {Object} [options.where] 标准化 where 条件(与 list 一致)。 + * @param {Object} [options.sort] 排序参数(与 list 一致)。 + * @param {number} [options.warehouseId] 仓库ID(由方法层从上下文注入)。 + * @param {Function} [options.onProgress] 进度回调。 + * @return {Promise} 上传结果与统计信息(含 url/cdnUrl/cosUrl/fileKey/current_count/total_count/sheet_count)。 + */ + async exportPackTask(options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const safeOptions = options && typeof options === 'object' && !Array.isArray(options) ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const warehouseId = Number(safeOptions.warehouseId || 0); + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + // 复用 list 的 where/sort 语义,并强制仓库隔离(服务端注入,前端无需传 warehouse_id) + const queryWhere = await this._buildListWhere(where, Op, warehouseId); + const order = this._buildListOrder(sort); + + const totalCount = await ctx.model.PackTask.count({ where: queryWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 85, + currentCount: 0, + totalCount, + message: totalCount > 0 ? `已命中 ${totalCount} 条打包任务,开始导出` : '未命中数据,开始生成空文件', + }); + + // ---- 分页拉取主表全量数据 ---- + const allTaskRows = []; + let page = 1; + while (allTaskRows.length < totalCount) { + const rows = await ctx.model.PackTask.findAll({ + where: queryWhere, + order, + limit: PACK_TASK_EXPORT_PAGE_SIZE, + offset: (page - 1) * PACK_TASK_EXPORT_PAGE_SIZE, + raw: true, + }); + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + allTaskRows.push(...rows); + page += 1; + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((allTaskRows.length / Math.max(totalCount, 1)) * 20)), + currentCount: allTaskRows.length, + totalCount, + message: `正在拉取打包任务列表,已完成 ${allTaskRows.length}/${totalCount}`, + }); + } + + // ---- 批量拉取关联数据(工作台 / 视频 / 运单) ---- + const taskIds = allTaskRows + .map(row => Number(row.id)) + .filter(id => Number.isInteger(id) && id > 0); + const workbenchIds = [ ...new Set( + allTaskRows.map(row => Number(row.workbench_id || 0)).filter(id => Number.isInteger(id) && id > 0) + ) ]; + const orderIds = [ ...new Set( + allTaskRows.map(row => Number(row.order_id || 0)).filter(id => Number.isInteger(id) && id > 0) + ) ]; + + /** @type {Map} */ + const workbenchMap = new Map(); + if (workbenchIds.length > 0) { + const workbenches = await ctx.model.Workbench.findAll({ + where: { id: { [Op.in]: workbenchIds } }, + attributes: [ 'id', 'name', 'type' ], + raw: true, + }); + for (const wb of workbenches) { + workbenchMap.set(Number(wb.id), wb); + } + } + + /** @type {Map>} */ + const videosMap = new Map(); + if (taskIds.length > 0) { + for (let idx = 0; idx < taskIds.length; idx += PACK_TASK_EXPORT_BATCH_SIZE) { + const batchIds = taskIds.slice(idx, idx + PACK_TASK_EXPORT_BATCH_SIZE); + const videos = await ctx.model.PackTaskVideo.findAll({ + where: { pack_task_id: { [Op.in]: batchIds } }, + attributes: [ 'id', 'pack_task_id', 'video_url', 'camera_id', 'status' ], + raw: true, + }); + for (const video of videos) { + const key = Number(video.pack_task_id); + if (!videosMap.has(key)) { + videosMap.set(key, []); + } + videosMap.get(key).push(video); + } + } + } + + /** @type {Map} */ + const cameraNameMap = new Map(); + const cameraIds = [ ...new Set( + Array.from(videosMap.values()) + .flat() + .map(v => Number(v.camera_id || 0)) + .filter(id => Number.isInteger(id) && id > 0) + ) ]; + if (cameraIds.length > 0) { + const cameras = await ctx.model.Camera.findAll({ + where: { id: { [Op.in]: cameraIds } }, + attributes: [ 'id', 'custom_name', 'channel_name' ], + raw: true, + }); + for (const camera of cameras) { + cameraNameMap.set(Number(camera.id), camera.custom_name || camera.channel_name || ''); + } + } + + /** @type {Map>} */ + const expressesMap = new Map(); + if (orderIds.length > 0) { + for (let idx = 0; idx < orderIds.length; idx += PACK_TASK_EXPORT_BATCH_SIZE) { + const batchOrderIds = orderIds.slice(idx, idx + PACK_TASK_EXPORT_BATCH_SIZE); + const expresses = await ctx.model.OrderExpress.findAll({ + where: { + order_id: { [Op.in]: batchOrderIds }, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code' ], + raw: true, + }); + for (const express of expresses) { + const key = Number(express.order_id); + if (!expressesMap.has(key)) { + expressesMap.set(key, []); + } + expressesMap.get(key).push(express); + } + } + } + + await progressHandler({ + status: 'running', + progress: 55, + currentCount: allTaskRows.length, + totalCount, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,单 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-pack-task-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `打包任务导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + const formatDateTime = value => (value ? app.formatDate(value) : ''); + + const PACK_MODE_TEXT = { 1: '散单', 2: '团购' }; + const STATUS_TEXT = { 0: '待处理', 1: '打包中', 2: '已完成', 3: '异常' }; + + try { + const sheet = workbook.addWorksheet('打包任务列表'); + sheet.columns = [ + { header: '任务ID', key: 'id', width: 14 }, + { header: '订单ID', key: 'order_id', width: 14 }, + { header: '波次号', key: 'wave_no', width: 18 }, + { header: '运单号', key: 'waybill_code', width: 22 }, + { header: '关联运单号', key: 'waybill_codes', width: 30 }, + { header: '打包模式', key: 'pack_mode_text', width: 10 }, + { header: '任务状态', key: 'status_text', width: 10 }, + { header: '打包数量', key: 'pack_quantity', width: 10 }, + { header: '商品总数量', key: 'item_quantity', width: 12 }, + { header: '商品种类数', key: 'sku_count', width: 12 }, + { header: '工作台', key: 'workbench_name', width: 14 }, + { header: '作业人员', key: 'operator_text', width: 20 }, + { header: '开始打包时间', key: 'start_time', width: 20 }, + { header: '结束打包时间', key: 'end_time', width: 20 }, + { header: '创建时间', key: 'create_time', width: 20 }, + { header: '视频状态', key: 'has_video_text', width: 10 }, + { header: '录像可用', key: 'video_enable_text', width: 10 }, + { header: '备注', key: 'remark', width: 30 }, + ]; + + for (const row of allTaskRows) { + const taskId = Number(row.id); + const workbench = workbenchMap.get(Number(row.workbench_id || 0)); + const videos = videosMap.get(taskId) || []; + const expresses = expressesMap.get(Number(row.order_id || 0)) || []; + const waybillCodes = expresses + .map(e => e.waybill_code) + .filter(code => code && String(code).trim()) + .join(', '); + const hasVideo = videos.length > 0; + const videoEnable = videos.some(v => v.video_url && v.status !== 'failed'); + + sheet.addRow({ + id: taskId, + order_id: row.order_id, + wave_no: normalizeCellValue(row.wave_no), + waybill_code: normalizeCellValue(row.waybill_code), + waybill_codes: waybillCodes, + pack_mode_text: PACK_MODE_TEXT[Number(row.pack_mode)] || '', + status_text: STATUS_TEXT[Number(row.status)] || '', + pack_quantity: row.pack_quantity, + item_quantity: row.item_quantity, + sku_count: row.sku_count, + workbench_name: workbench ? normalizeCellValue(workbench.name) : '', + operator_text: normalizeCellValue(row.operator_text), + start_time: formatDateTime(row.start_time), + end_time: formatDateTime(row.end_time), + create_time: formatDateTime(row.create_time), + has_video_text: hasVideo ? '有视频' : '无视频', + video_enable_text: videoEnable ? '可用' : '不可用', + remark: normalizeCellValue(row.remark), + }).commit(); + } + sheet.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + currentCount: allTaskRows.length, + totalCount, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/pack_task/${warehouseId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `打包任务导出(仓库${warehouseId}),共${totalCount}条打包任务`, + }); + } + + // 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录(兼容 data 包裹),最后才回退 COS key + const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {}; + const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null; + const fileUrlFromRecord = resolvedFileRecord + ? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '') + : ''; + const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || ''; + + const uploadInfo = { + filename, + fileKey: safeUploadResult.fileName || uploadKey, + url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey, + cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '', + cosUrl: safeUploadResult.cosUrl || '', + current_count: allTaskRows.length, + total_count: totalCount, + sheet_count: 1, + }; + + await progressHandler({ + status: 'success', + progress: 100, + currentCount: allTaskRows.length, + totalCount, + message: '导出任务完成', + result: uploadInfo, + }); + + return uploadInfo; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + throw error; + } finally { + // 清理临时文件(不存在或删除失败均忽略) + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (err) { /* ignore */ } + } + } + + /** + * 打包任务详情查询。 + * 按 id + warehouse_id 查询单条打包任务记录。 + * + * @param {Object} options 查询参数 + * @param {number} options.id 打包任务ID + * @return {Promise} 打包任务详情 + */ + async get(options = {}) { + const { ctx } = this; + const { id } = options; + + if (!id) { + return { code: 400, message: '打包任务ID不能为空', data: null }; + } + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + return { code: 400, message: '用户未绑定仓库,无法查询打包任务', data: null }; + } + + const record = await ctx.model.PackTask.findOne({ + where: { id: Number(id), warehouse_id: warehouseId }, + include: [ + { + model: ctx.model.Workbench, + as: 'workbench', + attributes: [ 'id', 'name', 'type' ], + }, + { + model: ctx.model.PackTaskVideo, + as: 'videos', + attributes: [ 'id', 'video_url', 'camera_id', 'status' ], + required: false, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + attributes: [ 'id', 'custom_name', 'channel_name' ], + }, + ], + }, + { + model: ctx.model.OrderExpress, + as: 'expresses', + attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ], + where: { warehouse_id: warehouseId, delete_at: null }, + required: false, + }, + ], + }); + + if (!record) { + return { code: 404, message: '打包任务不存在或无权访问', data: null }; + } + + const plain = record.get({ plain: true }); + const recordingComputerId = await this._getRecordingComputerId(warehouseId); + const rawVideos = plain.videos || []; + const { app: appCtx } = this; + const data = { + ...plain, + start_time: plain.start_time ? appCtx.formatDate(plain.start_time) : null, + end_time: plain.end_time ? appCtx.formatDate(plain.end_time) : null, + create_time: plain.create_time ? appCtx.formatDate(plain.create_time) : null, + update_time: plain.update_time ? appCtx.formatDate(plain.update_time) : null, + deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null, + workbench_name: plain.workbench?.name || null, + workbench_type: plain.workbench?.type || null, + has_video: rawVideos.length > 0 ? 1 : 2, + video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2, + videos: rawVideos.map(v => ({ + id: v.id, + video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url), + status: v.status || null, + camera_id: v.camera_id, + camera_name: v.camera?.custom_name || v.camera?.channel_name || null, + })), + expresses: (plain.expresses || []).map(e => ({ + id: e.id, + waybill_code: e.waybill_code, + logistics_code: e.logistics_code, + logistics_name: e.logistics_name, + logistics_interface_name: e.logistics_interface_name || null, + platform_code: e.platform_code || null, + status: e.status, + })), + workbench: undefined, + }; + + return { code: 200, message: 'ok', data }; + } + + /** + * 设置打包任务结束时间。 + * 按 id + warehouse_id 查找任务,更新结束时间。 + * 若任务状态不是已完成(2),则同时将状态更新为已完成。 + * 结束时间超过仓库配置的打包最大时长上限时,自动截断为 开始时间+上限时长 + * (散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes,单位分钟)。 + * + * @param {Object} options 操作参数 + * @param {number} options.id 打包任务ID + * @param {string} options.end_time 结束时间(ISO 8601 或日期字符串) + * @return {Promise} 操作结果 + */ + async setEndTime(options = {}) { + const { ctx } = this; + const { id, end_time } = options; + + if (!id) { + return { code: 400, message: '打包任务ID不能为空', data: null }; + } + if (!end_time) { + return { code: 400, message: '结束时间不能为空', data: null }; + } + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + return { code: 400, message: '用户未绑定仓库,无法操作打包任务', data: null }; + } + + const record = await ctx.model.PackTask.findOne({ + where: { id: Number(id), warehouse_id: warehouseId }, + }); + + if (!record) { + return { code: 404, message: '打包任务不存在或无权访问', data: null }; + } + + const newEndTime = new Date(end_time); + + // 结束时间不能早于开始时间 + if (record.start_time && newEndTime < new Date(record.start_time)) { + return { code: 400, message: '结束时间不能早于开始时间', data: null }; + } + + // 结束时间超过仓库配置的打包最大时长上限时,截断为 开始时间+上限时长 + const workbenchService = ctx.service.systems && ctx.service.systems.workbench; + const finalEndTime = workbenchService && typeof workbenchService.resolvePackTaskEndTime === 'function' + ? await workbenchService.resolvePackTaskEndTime(record, newEndTime) + : newEndTime; + + const updates = { end_time: finalEndTime }; + + // 若任务状态不是已完成(2),同步更新为已完成 + const wasFinished = record.status === 2; + if (!wasFinished) { + updates.status = 2; + } + + await record.update(updates); + + // 任务由未结束转为已完成时,同步更新关联订单打包状态(与 workbench.finishPack 语义一致) + if (!wasFinished && updates.status === 2 && workbenchService + && typeof workbenchService._updateOrderPackStatus === 'function') { + const isGroupTask = Number(record.pack_mode) === 2; + const taskWaveId = isGroupTask ? Number(record.wave_id || 0) : 0; + await workbenchService._updateOrderPackStatus(warehouseId, { + orderId: Number(record.order_id || 0), + waveId: taskWaveId, + packStatus: 2, + caller: 'OrderPacking.setEndTime', + }); + } + + return { + code: 200, + message: '结束时间设置成功', + data: { + id: record.id, + end_time: this.app.formatDate(updates.end_time), + status: updates.status, + }, + }; + } + + /** + * 强制重新录制打包任务视频。 + * 将任务推送到录制电脑,通过打印服务触发重新录制。 + * + * @param {Object} options 操作参数 + * @param {number} options.id 打包任务ID + * @return {Promise} 操作结果 { code, message, data } + */ + async forceRecord(options = {}) { + const { ctx } = this; + const { id } = options; + + if (!id) { + return { code: 400, message: '打包任务ID不能为空', data: null }; + } + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + return { code: 400, message: '用户未绑定仓库,无法操作打包任务', data: null }; + } + + // 1. 查找打包任务 + const packTask = await ctx.model.PackTask.findOne({ + where: { id: Number(id), warehouse_id: warehouseId }, + }); + if (!packTask) { + return { code: 404, message: '打包任务不存在或无权访问', data: null }; + } + + // 2. 查找仓库的录制电脑 + const recordingComputer = await ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + raw: true, + }); + if (!recordingComputer) { + return { code: 400, message: '该仓库无录制电脑,无法强制录制', data: null }; + } + + // 3. 检查录制电脑是否在线 + const redisPrinter = ctx.app.redis.get('printer'); + const onlineKey = `warehouse:${warehouseId}:printer:${recordingComputer.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + if (!onlineInfo) { + return { code: 400, message: '该仓库录制电脑不在线,无法强制录制', data: null }; + } + + // 4. 重置视频记录状态为 created,触发重新录制 + await ctx.model.PackTaskVideo.update( + { status: 'created', video_url: '' }, + { where: { pack_task_id: Number(id), deleted_at: null } } + ); + + // 5. 通知打印服务推送强制录制任务 + const printServiceUrl = ctx.app.config.printService.url; + const requestData = { pack_task_id: Number(id) }; + let printServiceResponse = null; + let printServiceError = null; + try { + const res = await ctx.curl(`${printServiceUrl}/record/force`, { + method: 'POST', + contentType: 'json', + data: requestData, + dataType: 'json', + timeout: 10000, + }); + printServiceResponse = { + status: res.status, + headers: res.headers, + data: res.data, + }; + } catch (err) { + printServiceError = err.message; + ctx.logger.warn(`通知打印服务强制录制 pack_task_id=${id} 失败: ${err.message}`); + } + + return { + code: printServiceError ? 500 : 200, + message: printServiceError ? `通知打印服务失败: ${printServiceError}` : '强制录制任务已推送', + data: { + pack_task_id: Number(id), + computer_id: recordingComputer.id, + print_service_url: `${printServiceUrl}/record/force`, + print_service_request: requestData, + print_service_response: printServiceResponse, + print_service_error: printServiceError, + }, + }; + } +} + +module.exports = OrderPackingService; diff --git a/app/service/systems/order_pending_exception.js b/app/service/systems/order_pending_exception.js new file mode 100644 index 0000000..3ed417e --- /dev/null +++ b/app/service/systems/order_pending_exception.js @@ -0,0 +1,68 @@ +'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 = {}) { + console.log('订单转异常', JSON.stringify(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, + }; + } + + /** + * 将待处理异常订单恢复为待处理状态。 + * + * 兼容单条与批量入参,支持 id、order_id、ids 三种订单 ID 写法。 + * 会同步清空订单标记,并将审核状态恢复为待处理状态,对应 inspection_status 为 padding、step 为 2。 + * + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息,包含清理后的订单标记与更新数量。 + */ + async reversePendingException(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + + const result = await this.updateOrderInspectionState(requestData, 'padding', { + extraUpdateValues: { + order_flag: '', + }, + }); + + return { + ...result, + order_flag: '', + }; + } +} + +module.exports = OrderPendingExceptionService; diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js new file mode 100644 index 0000000..df0b60b --- /dev/null +++ b/app/service/systems/order_print.js @@ -0,0 +1,4008 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const { Op } = require('sequelize'); +const OrderBaseService = require('../systemMethods/order/base'); +const PrinterDataBuilder = require('../../lib/printer_data_builder'); + +// 抖音临时 key(logistics.getShopKey)有效期约 5 分钟,缓存留 30 秒冗余 +const DOUYIN_PRINT_PARAMS_CACHE_TTL_SECONDS = 270; + +/** OMS 换新打印数据(只读、不消耗面单)的入站方法名。 */ +const OMS_PRINT_DATA_EVENT = 'deliveryorder.getprintdata'; + +// OMS 返回的抖音 params 有效期 600 秒,缓存留 300 秒余量 +const OMS_DOUYIN_PARAMS_CACHE_TTL_SECONDS = 300; + +/** OMS 抖音 params 缓存键前缀(按 cai_niao_auth_info_id 即店铺/授权网点维度)。 */ +const OMS_DOUYIN_PARAMS_CACHE_KEY_PREFIX = 'oms:douyin:params'; + +class OrderPrintSystemService extends OrderBaseService { + /** + * 判断订单是否处于锁定状态。 + * + * 当前约定 print_lock_status=none 表示未锁定,其余值均视为锁定。 + * + * @param {Object} orderRow 订单行。 + * @return {boolean} 是否锁定。 + */ + isOrderLocked(orderRow = {}) { + const lockStatus = String(orderRow && orderRow.print_lock_status || 'none').trim() || 'none'; + return lockStatus !== 'none'; + } + + /** + * 构建波次平台打印“已锁定”短路返回。 + * + * @param {Object} payload 聚合入参。 + * @param {Array} payload.lockedOrders 已锁定订单列表。 + * @param {Array} payload.validWaveIds 命中的有效波次ID。 + * @param {Array} payload.missingWaveIds 未命中波次ID。 + * @param {Array} payload.filteredWaveIds 被过滤波次及原因。 + * @return {Object} 锁定短路返回结构。 + */ + buildLockedWavePlatformResult(payload = {}) { + const requestPayload = this.isPlainObject(payload) ? payload : {}; + const lockedOrders = Array.isArray(requestPayload.lockedOrders) ? requestPayload.lockedOrders : []; + const validWaveIds = Array.isArray(requestPayload.validWaveIds) ? requestPayload.validWaveIds : []; + const missingWaveIds = Array.isArray(requestPayload.missingWaveIds) ? requestPayload.missingWaveIds : []; + const filteredWaveIds = Array.isArray(requestPayload.filteredWaveIds) ? requestPayload.filteredWaveIds : []; + + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + locked_count: lockedOrders.length, + }, + waveGroups: [], + wave_ids: validWaveIds, + locked_count: lockedOrders.length, + locked_orders: lockedOrders, + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } + + /** + * 组装单订单“已锁定”平台打印中间态结果(轻量对象)。 + * + * @param {Object} payload 聚合入参。 + * @param {Object} payload.orderRow 订单行。 + * @param {string} payload.platformCode 平台编码。 + * @return {Object} 锁定订单中间态。 + */ + buildLockedOrderPlatformPrintItem(payload = {}) { + const requestPayload = this.isPlainObject(payload) ? payload : {}; + const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {}; + const platformCode = String(requestPayload.platformCode || '').trim(); + const normalizedPlatform = PrinterDataBuilder.normalizePlatformAlias(platformCode); + const orderId = Number(orderRow.id || 0); + + return { + wave_id: Number(orderRow.wave_id || 0), + wave_no: String(orderRow.wave_no || '').trim(), + order_id: orderId, + order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(), + store_id: Number(orderRow.store_id || 0), + warehouse_id: Number(orderRow.warehouse_id || 0), + platform: platformCode, + platform_name: normalizedPlatform.meta && normalizedPlatform.meta.name + ? String(normalizedPlatform.meta.name).trim() + : '', + sys_logistics_code: String(orderRow.sys_logistics_code || '').trim(), + sys_logistics_name: String(orderRow.sys_logistics_name || '').trim(), + waybill_code: '', + print_data: { + order_id: orderId, + order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(), + wave_id: Number(orderRow.wave_id || 0), + wave_no: String(orderRow.wave_no || '').trim(), + platform: platformCode, + platform_name: normalizedPlatform.meta && normalizedPlatform.meta.name + ? String(normalizedPlatform.meta.name).trim() + : '', + status: 'locked', + status_text: '已锁定', + print_lock_status: String(orderRow.print_lock_status || '').trim() || 'none', + }, + }; + } + + /** + * 判断当前配置是否需要补查拣货明细。 + * + * 未配置时默认按类型5处理,因此也需要补查。 + * + * @param {Object} policyConfig 策略配置。 + * @return {boolean} 是否需要补查拣货明细。 + */ + shouldLoadPickingDetails(policyConfig = {}) { + const config = this.isPlainObject(policyConfig) ? policyConfig : {}; + const displayType = Object.prototype.hasOwnProperty.call(config, 'waybill_custom_display_type') + ? String(config.waybill_custom_display_type || '').trim() + : '5'; + + return [ '2', '3', '4', '5' ].includes(displayType); + } + + /** + * 归一化商品快照,兼容 JSON 字符串。 + * + * @param {*} rawSnapshot 原始商品快照。 + * @return {Object} 快照对象。 + */ + normalizeItemSnapshot(rawSnapshot) { + if (this.isPlainObject(rawSnapshot)) { + return rawSnapshot; + } + + if (typeof rawSnapshot === 'string') { + const text = rawSnapshot.trim(); + if (!text) { + return {}; + } + + try { + const parsed = JSON.parse(text); + return this.isPlainObject(parsed) ? parsed : {}; + } catch (error) { + return {}; + } + } + + return {}; + } + + /** + * 从候选字段中读取首个非空文本。 + * + * @param {Object} source 源对象。 + * @param {Array} keys 候选键。 + * @return {string} 首个非空文本。 + */ + getFirstNonEmptyFieldText(source, keys = []) { + if (!this.isPlainObject(source)) { + return ''; + } + + for (const key of keys) { + const value = source[key]; + if (value === undefined || value === null) { + continue; + } + + const text = String(value).trim(); + if (text) { + return text; + } + } + + return ''; + } + + /** + * 构建打印项聚合键。 + * + * 同一库位下的拣货行只有商品身份一致时才允许合并: + * - 优先 stock_id(>0):同一库位同一商品合并数量; + * - stock_id 缺失时回退 order_item_id(同一订单商品行); + * - 再缺失时回退 商品名称+条码 兜底; + * - 均无法识别时不做跨行合并(每行独立)。 + * + * @param {Object} item 打印项。 + * @return {string} 聚合键。 + */ + buildPrintItemAggregationKey(item = {}) { + const source = this.isPlainObject(item) ? item : {}; + const location = String(source.pick_location || '').trim(); + const stockId = Number(source.stock_id || 0); + if (stockId > 0) { + return `${location}::stock:${stockId}`; + } + + const orderItemId = Number(source.order_item_id || 0); + if (orderItemId > 0) { + return `${location}::order_item:${orderItemId}`; + } + + const name = String(source.item_name || '').trim(); + const barcode = String(source.barcode || '').trim(); + if (name || barcode) { + return `${location}::name:${name}|${barcode}`; + } + + return `${location}::id:${Math.random()}`; + } + + /** + * 批量补查打印所需的拣货明细,并注入商品多条码。 + * + * 优先使用 wms_picking.space_name,只有缺失时才查询库位表,减少额外 SQL。 + * 同时从 wms_stock_barcodes 表批量查询每个 stock_id 对应的全部条码, + * 注入到打印项的 barcodes 数组中,供 resolveItemBarcodeText 优先读取。 + * + * 商品信息(item_name / barcode / stock_id / quantity)全部从 wms_picking + * 直读,不再反查 order_items 表,彻底消除因订单迁移导致 order_item_id + * 错配的风险。 + * + * @param {Array} orderRows 订单列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单ID到补齐后订单对象的映射。 + */ + async buildPrintOrderRowMapWithPicking(orderRows = [], warehouseId) { + const rows = Array.isArray(orderRows) ? orderRows : []; + const orderIds = Array.from(new Set(rows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0))); + const resultMap = new Map(); + + if (orderIds.length === 0) { + return resultMap; + } + + const pickingModel = this.ctx.model && this.ctx.model.Picking; + if (!pickingModel || typeof pickingModel.findAll !== 'function') { + return resultMap; + } + + const pickingRows = await pickingModel.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + warehouse_id: warehouseId, + status: { + [Op.ne]: 'cancel', + }, + }, + attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status', 'stock_id' ], + order: [[ 'order_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; + if (normalizedPickingRows.length === 0) { + return resultMap; + } + + // 库位兜底:space_name 为空时通过 space_id 补查 location_space 表 + const locationFallbackSpaceIds = Array.from(new Set(normalizedPickingRows + .filter(row => !String(row && row.space_name || '').trim()) + .map(row => Number(row && row.space_id || 0)) + .filter(spaceId => Number.isInteger(spaceId) && spaceId > 0))); + const locationModel = this.ctx.model && this.ctx.model.LocationSpace; + const locationRows = locationModel + && typeof locationModel.findAll === 'function' + && locationFallbackSpaceIds.length > 0 + ? await locationModel.findAll({ + where: { + id: { + [Op.in]: locationFallbackSpaceIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'space_code', 'custom_name', 'custom_barcode' ], + raw: true, + }) + : []; + const locationMap = new Map((Array.isArray(locationRows) ? locationRows : []) + .map(row => [ Number(row && row.id || 0), row ])); + + // 按 order_id 分组 picking 行 + const pickingRowsByOrderId = new Map(); + for (const row of normalizedPickingRows) { + const orderId = Number(row && row.order_id || 0); + if (orderId <= 0) { + continue; + } + + const list = pickingRowsByOrderId.get(orderId) || []; + list.push(row); + pickingRowsByOrderId.set(orderId, list); + } + + // 阶段一:从 picking.stock_id 收集所有 stock_id + const allStockIds = new Set(); + for (const row of normalizedPickingRows) { + const stockId = Number(row && row.stock_id || 0); + if (stockId > 0) { + allStockIds.add(stockId); + } + } + const uniqueStockIds = Array.from(allStockIds); + + // 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称 + const stockWarehouseMap = new Map(); + if (uniqueStockIds.length > 0) { + const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse; + if (stockWarehouseModel && typeof stockWarehouseModel.findAll === 'function') { + const stockRows = await stockWarehouseModel.findAll({ + where: { + id: { [Op.in]: uniqueStockIds }, + is_valid: 'Y', + }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }); + for (const row of Array.isArray(stockRows) ? stockRows : []) { + stockWarehouseMap.set(Number(row.id), row); + } + } + } + + // 阶段三:构建所有打印项(全部从 picking + stock_warehouse 直取) + const printItemsByOrderId = new Map(); + + for (const orderRow of rows) { + const orderId = Number(orderRow && orderRow.id || 0); + const pickingList = pickingRowsByOrderId.get(orderId) || []; + if (pickingList.length === 0) { + continue; + } + + const printItems = pickingList.map(pickingRow => { + const stockId = Number(pickingRow && pickingRow.stock_id || 0); + const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null; + const locationRow = locationMap.get(Number(pickingRow && pickingRow.space_id || 0)) || {}; + const pickLocation = this.getFirstNonEmptyFieldText({ + space_name: pickingRow && pickingRow.space_name, + space_code: locationRow.space_code, + custom_name: locationRow.custom_name, + custom_barcode: locationRow.custom_barcode, + }, [ 'space_name', 'space_code', 'custom_name', 'custom_barcode' ]); + + const quantity = Number(pickingRow && pickingRow.quantity || 0); + + return { + order_item_id: Number(pickingRow && pickingRow.order_item_id || 0), + item_name: stockInfo ? String(stockInfo.item_name || '').trim() : '', + barcode: stockInfo ? String(stockInfo.item_code || '').trim() : '', + quantity: quantity > 0 ? quantity : 0, + pick_location: pickLocation, + stock_id: stockId > 0 ? stockId : undefined, + }; + }).filter(item => { + return String(item.item_name || '').trim() + || String(item.barcode || '').trim() + || String(item.pick_location || '').trim(); + }); + + if (printItems.length === 0) { + continue; + } + + printItemsByOrderId.set(orderId, printItems); + } + + // 阶段四:批量查询 wms_stock_barcodes 获取所有条码 + const barcodeMap = new Map(); + + if (uniqueStockIds.length > 0) { + const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode; + + if (stockBarcodeModel && typeof stockBarcodeModel.findAll === 'function') { + const barcodeRows = await stockBarcodeModel.findAll({ + where: { + stock_id: { + [Op.in]: uniqueStockIds, + }, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + + for (const item of Array.isArray(barcodeRows) ? barcodeRows : []) { + const stockId = Number(item && item.stock_id || 0); + const code = String(item && item.barcode || '').trim(); + + if (!stockId || !code) { + continue; + } + + if (!barcodeMap.has(stockId)) { + barcodeMap.set(stockId, []); + } + + barcodeMap.get(stockId).push(code); + } + } + } + + // 阶段五:注入条码并构建结果映射 + for (const orderRow of rows) { + const orderId = Number(orderRow && orderRow.id || 0); + const printItems = printItemsByOrderId.get(orderId); + + if (!printItems) { + continue; + } + + // 为每条打印项注入 barcodes 数组,供 resolveItemBarcodeText 优先读取 + for (const item of printItems) { + const stockId = Number(item.stock_id || 0); + item.stock_id = stockId > 0 ? stockId : 0; + + if (stockId > 0 && barcodeMap.has(stockId)) { + item.barcodes = barcodeMap.get(stockId); + } + } + + // 按「库位 + 商品(stock_id)」聚合:同一库位的同一商品合并为一行, + // 同一库位的不同商品保持独立行,避免数量、条码被错误合并。 + const aggregatedMap = new Map(); + for (const item of printItems) { + const key = this.buildPrintItemAggregationKey(item); + const existing = aggregatedMap.get(key); + if (existing) { + // 累加数量 + existing.quantity += item.quantity; + // 合并 item_name(用 、 拼接去重) + if (item.item_name && !existing.item_name.split('、').includes(item.item_name)) { + existing.item_name = `${existing.item_name}、${item.item_name}`; + } + // 合并 barcode(用 ; 拼接去重) + if (item.barcode && !existing.barcode.split(';').includes(item.barcode)) { + existing.barcode = `${existing.barcode};${item.barcode}`; + } + // 合并 barcodes 数组(Set 去重) + if (item.barcodes && item.barcodes.length > 0) { + const merged = new Set([ ...(existing.barcodes || []), ...item.barcodes ]); + existing.barcodes = Array.from(merged); + } + } else { + aggregatedMap.set(key, { ...item }); + } + } + const mergedPrintItems = Array.from(aggregatedMap.values()); + + // 聚合完成后清理内部字段,避免污染 JSON 输出 + for (const item of mergedPrintItems) { + delete item.stock_id; + } + + // 为聚合后的商品行添加序号(从 1 开始) + for (let i = 0; i < mergedPrintItems.length; i++) { + mergedPrintItems[i].seq_no = i + 1; + } + + resultMap.set(orderId, { + ...orderRow, + items: JSON.stringify(mergedPrintItems), + }); + } + + return resultMap; + } + + /** + * 归一化签约策略配置,兼容缓存中的字符串形态。 + * + * @param {*} rawPolicyConfig 原始策略配置。 + * @return {Object} 归一化后的策略配置对象。 + */ + normalizeContractPolicyConfig(rawPolicyConfig) { + if (this.isPlainObject(rawPolicyConfig)) { + return rawPolicyConfig; + } + + if (typeof rawPolicyConfig === 'string') { + const text = rawPolicyConfig.trim(); + if (!text) { + return {}; + } + + try { + const parsed = JSON.parse(text); + return this.isPlainObject(parsed) ? parsed : {}; + } catch (error) { + this.ctx.logger.warn('[orderPrint.normalizeContractPolicyConfig] policy_config 解析失败: %s', error.message); + } + } + + return {}; + } + + /** + * 获取波次平台打印数据中间态。 + * + * 输出以波次分组为主结构(waveGroups),并在波次内按平台分组, + * 便于上游按「波次 -> 平台 -> 订单」层级批量发起打印。 + * + * @param {Object} params 请求参数。 + * @param {Array} params.waveIds 波次ID数组。 + * @param {number|string} params.warehouseId 仓库ID。 + * @return {Promise} 平台打印中间态结果。 + */ + async getWavePlatformPrintData(params = {}) { + const requestParams = this.isPlainObject(params) ? params : {}; + const { + waveIds, + warehouseId, + } = requestParams; + + const normalizedWaveIds = this.normalizeWaveIds(waveIds); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 必填,且必须为非空数组'); + } + + const normalizedWarehouseId = this.resolveWarehouseId(warehouseId); + const waveRows = await this.queryWavesByIds(normalizedWarehouseId, normalizedWaveIds); + if (waveRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + locked_count: 0, + total_locked_orders: 0, + intercepted_count: 0, + }, + waveGroups: [], + locked_wave_groups: [], + wave_ids: [], + locked_count: 0, + locked_orders: [], + intercepted_count: 0, + intercepted_orders: [], + ext: { + missing_wave_ids: normalizedWaveIds, + filtered_wave_ids: [], + }, + }; + } + + // 波次元信息映射(source / wave_type),供自定义区「波次总单数×数量」行尾规则使用 + const waveMetaMap = new Map(); + for (const waveRow of waveRows) { + waveMetaMap.set(Number(waveRow.wave_id), waveRow); + } + + const hitWaveIdSet = new Set(waveRows.map(row => Number(row.wave_id))); + const missingWaveIds = normalizedWaveIds.filter(waveId => !hitWaveIdSet.has(waveId)); + const hitWaveIds = normalizedWaveIds.filter(waveId => hitWaveIdSet.has(waveId)); + const orderRows = await this.queryOrdersByWaveIds(hitWaveIds, normalizedWarehouseId); + const { + validWaveIds, + filteredWaveIds, + } = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows); + const validWaveIdSet = new Set(validWaveIds); + const validOrderRows = orderRows.filter(order => validWaveIdSet.has(Number(order && order.wave_id || 0))); + const interceptedOrderRows = validOrderRows.filter( + orderRow => this.isInterceptedOrderStatus(orderRow && orderRow.intercept_status) + ); + const lockedOrderRows = validOrderRows.filter(orderRow => this.isOrderLocked(orderRow)); + const unlockedOrderRows = validOrderRows.filter( + orderRow => !this.isOrderLocked(orderRow) + && !this.isInterceptedOrderStatus(orderRow && orderRow.intercept_status) + ); + const interceptedOrders = interceptedOrderRows + .map(orderRow => ({ + order_id: Number(orderRow && orderRow.id || 0), + order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(), + wave_id: Number(orderRow && orderRow.wave_id || 0), + wave_no: String(orderRow && orderRow.wave_no || '').trim(), + intercept_status: String(orderRow && orderRow.intercept_status || '').trim() || 'none', + status: 'intercepted', + status_text: '已拦截', + })); + const lockedOrders = lockedOrderRows + .map(orderRow => ({ + order_id: Number(orderRow && orderRow.id || 0), + order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(), + wave_id: Number(orderRow && orderRow.wave_id || 0), + wave_no: String(orderRow && orderRow.wave_no || '').trim(), + print_lock_status: String(orderRow && orderRow.print_lock_status || '').trim() || 'none', + status: 'locked', + status_text: '已锁定', + })); + + const lockedWaveIds = Array.from(new Set(lockedOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + const lockedOrderPrintList = lockedOrderRows.map(orderRow => { + const platformCode = this.resolvePrintPlatformCode(orderRow, {}); + return this.buildLockedOrderPlatformPrintItem({ + orderRow, + platformCode, + }); + }); + const lockedWaveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ + waveRows, + hitWaveIds: lockedWaveIds, + orderPrintList: lockedOrderPrintList, + }); + + const validOrderWaveIds = Array.from(new Set(unlockedOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + + if (unlockedOrderRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + locked_count: lockedOrders.length, + total_locked_orders: lockedOrders.length, + intercepted_count: interceptedOrders.length, + }, + waveGroups: [], + locked_wave_groups: lockedWaveGroups, + wave_ids: validWaveIds, + locked_count: lockedOrders.length, + locked_orders: lockedOrders, + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } + + const orderIds = unlockedOrderRows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds, normalizedWarehouseId); + this.assertBusinessWaybillCompleteness(orderIds, orderExpressRows); + const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows( + unlockedOrderRows, + orderExpressRows, + normalizedWarehouseId + ); + const jdEnrichedOrderExpressRows = await this.enrichJdOrderExpressRows( + unlockedOrderRows, + cainiaoEnrichedOrderExpressRows, + normalizedWarehouseId + ); + const enrichedOrderExpressRows = await this.enrichPddDyOrderExpressRows( + unlockedOrderRows, + jdEnrichedOrderExpressRows, + normalizedWarehouseId + ); + const orderExpressMap = this.buildOrderExpressMap(enrichedOrderExpressRows); + const policyConfigMap = await this.getPolicyConfigMapByStore(unlockedOrderRows, normalizedWarehouseId); + const pickingCandidateRows = unlockedOrderRows.filter(orderRow => { + const storeId = Number(orderRow && orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + return this.shouldLoadPickingDetails(policyConfig); + }); + const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId); + const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds( + orderIds, + normalizedWarehouseId, + validOrderWaveIds + ); + const pickTaskBoxNoMap = await this.querySmallGroupBoxNoMap( + orderIds, + normalizedWarehouseId, + new Map(unlockedOrderRows.map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ])) + ); + const waveIdsForCount = validOrderWaveIds; + const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId); + const templateSampleCache = new Map(); + const orderPrintList = []; + + for (const orderRow of unlockedOrderRows) { + const orderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + const orderExpress = orderExpressMap.get(orderId) || {}; + const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow; + const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {}; + const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0); + const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); + const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); + const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const waveMetaRow = waveMetaMap.get(waveIdForCount) || {}; + const pickTaskBoxInfo = pickTaskBoxNoMap.get(orderId) || {}; + const effectiveOrderRowWithWaveIndex = { + ...effectiveOrderRow, + wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, + wave_index: waveIndex > 0 ? waveIndex : 0, + platforms_index: platformsIndex > 0 ? platformsIndex : 0, + wave_source: Number(waveMetaRow.source || 0), + wave_type: Number(waveMetaRow.wave_type || 0), + box_no: Number(pickTaskBoxInfo.box_no || 0), + }; + const storeId = Number(orderRow && orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress); + const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); + + orderPrintList.push(await this.buildOrderPlatformPrintItem({ + orderRow: effectiveOrderRowWithWaveIndex, + orderExpress, + policyConfig, + platformCode, + templateSample, + })); + } + + const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ + waveRows, + hitWaveIds: validOrderWaveIds, + orderPrintList, + }); + const totalPlatforms = waveGroups.reduce((sum, waveGroup) => { + return sum + Number(waveGroup && waveGroup.platforms && waveGroup.platforms.length || 0); + }, 0); + + return { + summary: { + total_waves: waveGroups.length, + total_orders: orderPrintList.length, + total_platforms: totalPlatforms, + locked_count: lockedOrders.length, + total_locked_orders: lockedOrders.length, + intercepted_count: interceptedOrders.length, + }, + waveGroups, + locked_wave_groups: lockedWaveGroups, + wave_ids: validWaveIds, + locked_count: lockedOrders.length, + locked_orders: lockedOrders, + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } + + /** + * 按订单ID拉取平台打印中间态数据。 + * + * 与 getWavePlatformPrintData 输出完全相同的结构,但入参由波次ID改为订单ID。 + * 跳过了波次查询步骤,直接从订单ID入手,其余打印数据组装、锁定/未锁定分离、 + * 波次平台分组等逻辑与 getWavePlatformPrintData 保持一致。 + * 仓库ID统一从当前上下文获取,不再接受调用方传入。 + * + * @param {Object} params 请求参数。 + * @param {Array} params.orderIds 订单ID数组。 + * @return {Promise} 平台打印中间态结果。 + */ + async getOrderPrintData(params = {}) { + const requestParams = this.isPlainObject(params) ? params : {}; + const { + orderIds, + } = requestParams; + + const normalizedOrderIds = this.normalizeOrderIds(orderIds); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 必填,且必须为非空数组'); + } + + const normalizedWarehouseId = this.getContextWarehouseId(); + const orderRows = await this.queryOrdersByIds(normalizedOrderIds, normalizedWarehouseId); + if (orderRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + intercepted_count: 0, + }, + waveGroups: [], + wave_ids: [], + intercepted_count: 0, + intercepted_orders: [], + ext: { + missing_order_ids: normalizedOrderIds, + filtered_order_ids: [], + }, + }; + } + + const hitOrderIdSet = new Set(orderRows.map(row => Number(row.id))); + const missingOrderIds = normalizedOrderIds.filter(orderId => !hitOrderIdSet.has(orderId)); + + // 订单级过滤:仅保留 post_status === 'fin' 的订单(等价于波次级的快递完全分配检查) + const postFinOrderRows = orderRows.filter(row => String(row && row.post_status || '').trim() === 'fin'); + // 拦截订单从打印清单中剔除 + const interceptedOrderRows = postFinOrderRows.filter( + row => this.isInterceptedOrderStatus(row && row.intercept_status) + ); + const interceptedOrders = interceptedOrderRows.map(row => ({ + order_id: Number(row && row.id || 0), + order_no: String(row && (row.delivery_order_code || row.source_order_codes) || '').trim(), + wave_id: Number(row && row.wave_id || 0), + wave_no: String(row && row.wave_no || '').trim(), + intercept_status: String(row && row.intercept_status || '').trim() || 'none', + status: 'intercepted', + status_text: '已拦截', + })); + const validOrderRows = postFinOrderRows.filter( + row => !this.isInterceptedOrderStatus(row && row.intercept_status) + ); + const filteredOrderIds = orderRows + .filter(row => String(row && row.post_status || '').trim() !== 'fin') + .map(row => ({ + order_id: Number(row && row.id || 0), + reason: '快递未完全分配', + })) + .concat(interceptedOrderRows.map(row => ({ + order_id: Number(row && row.id || 0), + reason: '已拦截', + }))); + + if (validOrderRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + intercepted_count: interceptedOrders.length, + }, + waveGroups: [], + wave_ids: [], + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, + ext: { + missing_order_ids: missingOrderIds, + filtered_order_ids: filteredOrderIds, + }, + }; + } + + const validOrderWaveIds = Array.from(new Set(validOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + + const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds); + + // 波次元信息映射(source / wave_type),供自定义区「波次总单数×数量」行尾规则使用 + const waveMetaMap = new Map(); + for (const waveRow of waveRows) { + waveMetaMap.set(Number(waveRow.wave_id), waveRow); + } + + const orderIdsForExpress = validOrderRows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIdsForExpress, normalizedWarehouseId); + this.assertBusinessWaybillCompleteness(orderIdsForExpress, orderExpressRows); + const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows( + validOrderRows, + orderExpressRows, + normalizedWarehouseId + ); + const jdEnrichedOrderExpressRows = await this.enrichJdOrderExpressRows( + validOrderRows, + cainiaoEnrichedOrderExpressRows, + normalizedWarehouseId + ); + const enrichedOrderExpressRows = await this.enrichPddDyOrderExpressRows( + validOrderRows, + jdEnrichedOrderExpressRows, + normalizedWarehouseId + ); + const orderExpressMap = this.buildOrderExpressMap(enrichedOrderExpressRows); + const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId); + const pickingCandidateRows = validOrderRows.filter(orderRow => { + const storeId = Number(orderRow && orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + return this.shouldLoadPickingDetails(policyConfig); + }); + const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId); + const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds( + orderIdsForExpress, + normalizedWarehouseId, + validOrderWaveIds + ); + const pickTaskBoxNoMap = await this.querySmallGroupBoxNoMap( + orderIdsForExpress, + normalizedWarehouseId, + new Map(validOrderRows.map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ])) + ); + const waveIdsForCount = validOrderWaveIds; + const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId); + const templateSampleCache = new Map(); + const orderPrintList = []; + + for (const orderRow of validOrderRows) { + const orderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + const orderExpress = orderExpressMap.get(orderId) || {}; + const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow; + const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {}; + const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0); + const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); + const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); + const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const waveMetaRow = waveMetaMap.get(waveIdForCount) || {}; + const pickTaskBoxInfo = pickTaskBoxNoMap.get(orderId) || {}; + const effectiveOrderRowWithWaveIndex = { + ...effectiveOrderRow, + wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, + wave_index: waveIndex > 0 ? waveIndex : 0, + platforms_index: platformsIndex > 0 ? platformsIndex : 0, + wave_source: Number(waveMetaRow.source || 0), + wave_type: Number(waveMetaRow.wave_type || 0), + box_no: Number(pickTaskBoxInfo.box_no || 0), + }; + const storeId = Number(orderRow && orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress); + const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); + + orderPrintList.push(await this.buildOrderPlatformPrintItem({ + orderRow: effectiveOrderRowWithWaveIndex, + orderExpress, + policyConfig, + platformCode, + templateSample, + })); + } + + const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ + waveRows, + hitWaveIds: validOrderWaveIds, + orderPrintList, + }); + const totalPlatforms = waveGroups.reduce((sum, waveGroup) => { + return sum + Number(waveGroup && waveGroup.platforms && waveGroup.platforms.length || 0); + }, 0); + + return { + summary: { + total_waves: waveGroups.length, + total_orders: orderPrintList.length, + total_platforms: totalPlatforms, + intercepted_count: interceptedOrders.length, + }, + waveGroups, + wave_ids: validOrderWaveIds, + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, + ext: { + missing_order_ids: missingOrderIds, + filtered_order_ids: filteredOrderIds, + }, + }; + } + + /** + * 规范化“按分组解锁”规则。 + * + * @param {Object} payload 规则入参。 + * @param {Array} payload.groups 分组条件原始列表。 + * @param {string} payload.groupType 分组类型。 + * @param {string} payload.unlockScope 解锁范围。 + * @param {Array} payload.validWaveIds 有效波次ID列表。 + * @return {Array} 规范化后的分组规则列表。 + */ + /** + * 按运单号数组拉取平台打印中间态数据。 + * + * 与 getOrderPrintData 输出相同的 waveGroups 结构,但入参改为运单号数组。 + * 支持子单号(business_key > 1): + * - 主面单:与现有逻辑一致 + * - 子面单:使用主订单的订单数据构建打印数据,但在自定义区追加 "子单号【{business_key}】-{主单号}" 行 + * + * 仓库ID统一从当前上下文获取。 + * + * @param {Object} params 请求参数。 + * @param {Array} params.waybillCodes 运单号数组。 + * @return {Promise} 平台打印中间态结果。 + */ + async getPrintDataByWaybillCodes(params = {}) { + const requestParams = this.isPlainObject(params) ? params : {}; + const { waybillCodes } = requestParams; + + if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) { + throw new Error('waybill_codes 必填,且必须为非空数组'); + } + + const normalizedWaybillCodes = Array.from(new Set( + waybillCodes.map(code => String(code || '').trim()).filter(Boolean) + )); + if (normalizedWaybillCodes.length === 0) { + throw new Error('waybill_codes 必填,且必须为非空数组'); + } + + const normalizedWarehouseId = this.getContextWarehouseId(); + + // 1. 按运单号查询运单记录(不限制 business_key,支持子单号) + const waybillRows = await this.queryWaybillsByCodes(normalizedWaybillCodes, normalizedWarehouseId); + if (waybillRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + intercepted_count: 0, + }, + waveGroups: [], + wave_ids: [], + intercepted_count: 0, + intercepted_orders: [], + ext: { + missing_waybill_codes: normalizedWaybillCodes, + filtered_waybill_codes: [], + }, + }; + } + + const foundWaybillCodeSet = new Set(waybillRows.map(r => String(r.waybill_code || '').trim())); + const missingWaybillCodes = normalizedWaybillCodes.filter(code => !foundWaybillCodeSet.has(code)); + + // 2. 提取所有涉及的订单ID,查询订单 + const orderIdSet = new Set(waybillRows.map(r => Number(r.order_id)).filter(id => id > 0)); + const orderIds = Array.from(orderIdSet); + const orderRows = await this.queryOrdersByIds(orderIds, normalizedWarehouseId); + const orderRowMap = new Map(orderRows.map(row => [ Number(row.id), row ])); + + // 过滤未找到订单的运单 + const validWaybillRows = waybillRows.filter(row => orderRowMap.has(Number(row.order_id))); + const invalidWaybillCodes = waybillRows + .filter(row => !orderRowMap.has(Number(row.order_id))) + .map(row => ({ + waybill_code: String(row.waybill_code || '').trim(), + reason: '关联订单未找到或不属于当前仓库', + })); + + if (validWaybillRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + intercepted_count: 0, + }, + waveGroups: [], + wave_ids: [], + intercepted_count: 0, + intercepted_orders: [], + ext: { + missing_waybill_codes: missingWaybillCodes, + filtered_waybill_codes: invalidWaybillCodes, + }, + }; + } + + // 3. 过滤 post_status !== 'fin' 或进入拦截流程的订单 + const interceptedOrderRows = orderRows.filter( + row => this.isInterceptedOrderStatus(row && row.intercept_status) + ); + const interceptedOrderIdSet = new Set(interceptedOrderRows.map(row => Number(row.id))); + const interceptedOrders = interceptedOrderRows.map(row => ({ + order_id: Number(row && row.id || 0), + order_no: String(row && (row.delivery_order_code || row.source_order_codes) || '').trim(), + wave_id: Number(row && row.wave_id || 0), + wave_no: String(row && row.wave_no || '').trim(), + intercept_status: String(row && row.intercept_status || '').trim() || 'none', + status: 'intercepted', + status_text: '已拦截', + })); + const validOrderIdSet = new Set( + orderRows + .filter(row => String(row.post_status || '').trim() === 'fin' + && !this.isInterceptedOrderStatus(row && row.intercept_status)) + .map(row => Number(row.id)) + ); + const finalWaybillRows = validWaybillRows.filter(row => validOrderIdSet.has(Number(row.order_id))); + const filteredWaybillCodes = validWaybillRows + .filter(row => !validOrderIdSet.has(Number(row.order_id))) + .map(row => ({ + waybill_code: String(row.waybill_code || '').trim(), + reason: interceptedOrderIdSet.has(Number(row.order_id)) + ? '关联订单已被拦截' + : '关联订单快递未完全分配', + })); + + if (finalWaybillRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + intercepted_count: interceptedOrders.length, + }, + waveGroups: [], + wave_ids: [], + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, + ext: { + missing_waybill_codes: missingWaybillCodes, + filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ], + }, + }; + } + + // 4. 收集有效订单行 + const validOrderRows = Array.from( + new Map(orderRows.filter(row => validOrderIdSet.has(Number(row.id))).map(row => [ Number(row.id), row ])).values() + ); + + // 4b. 对命中的所有运单行做平台增强(主单和子单各自走自己的增强,密文/签名/参数按运单独立) + const waybillRowsForEnrich = finalWaybillRows.map(row => ({ ...row })); + const cainiaoEnrichedWaybillRows = await this.enrichCainiaoOrderExpressRows( + validOrderRows, waybillRowsForEnrich, normalizedWarehouseId + ); + const jdEnrichedWaybillRows = await this.enrichJdOrderExpressRows( + validOrderRows, cainiaoEnrichedWaybillRows, normalizedWarehouseId + ); + const enrichedWaybillRows = await this.enrichPddDyOrderExpressRows( + validOrderRows, jdEnrichedWaybillRows, normalizedWarehouseId + ); + // 构建 order_id → 增强后运单列表的映射(同一订单可能有多个运单) + const enrichedWaybillMap = new Map(); + for (const row of enrichedWaybillRows) { + const oid = Number(row.order_id); + if (!enrichedWaybillMap.has(oid)) { + enrichedWaybillMap.set(oid, []); + } + enrichedWaybillMap.get(oid).push(row); + } + + // 4c. 获取每个订单的主运单(business_key=1),用于子面单自定义区追加主运单号 + const mainWaybillMap = await this.getMainWaybillMapByOrderIds(orderIds, normalizedWarehouseId); + + // 5. 获取策略配置 + const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId); + + // 6. 拣货明细、波次序号等辅助数据 + const pickingCandidateRows = validOrderRows.filter(orderRow => { + const storeId = Number(orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + return this.shouldLoadPickingDetails(policyConfig); + }); + const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId); + + const validOrderWaveIds = Array.from(new Set(validOrderRows + .map(row => Number(row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds); + + // 波次元信息映射(source / wave_type),供自定义区「波次总单数×数量」行尾规则使用 + const waveMetaMap = new Map(); + for (const waveRow of waveRows) { + waveMetaMap.set(Number(waveRow.wave_id), waveRow); + } + + const orderIdsForIndex = validOrderRows.map(row => Number(row.id)).filter(id => id > 0); + const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds( + orderIdsForIndex, normalizedWarehouseId, validOrderWaveIds + ); + const pickTaskBoxNoMap = await this.querySmallGroupBoxNoMap( + orderIdsForIndex, + normalizedWarehouseId, + new Map(validOrderRows.map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ])) + ); + const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(validOrderWaveIds, normalizedWarehouseId); + const templateSampleCache = new Map(); + + // 7. 为每个运单构建打印数据 + const orderPrintList = []; + for (const enrichedRow of enrichedWaybillRows) { + const orderId = Number(enrichedRow.order_id); + const orderRow = orderRowMap.get(orderId); + if (!orderRow) continue; + + const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow; + const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {}; + const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0); + const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); + const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); + const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const waveMetaRow = waveMetaMap.get(waveIdForCount) || {}; + const pickTaskBoxInfo = pickTaskBoxNoMap.get(orderId) || {}; + const effectiveOrderRowWithWaveIndex = { + ...effectiveOrderRow, + wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, + wave_index: waveIndex > 0 ? waveIndex : 0, + platforms_index: platformsIndex > 0 ? platformsIndex : 0, + wave_source: Number(waveMetaRow.source || 0), + wave_type: Number(waveMetaRow.wave_type || 0), + box_no: Number(pickTaskBoxInfo.box_no || 0), + }; + + const storeId = Number(orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, enrichedRow); + const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); + + // 子面单:自定义区首行追加子单号标识 + const businessKey = Number(enrichedRow.business_key || 1); + const mainWaybill = mainWaybillMap.get(orderId); + const mainWaybillCode = mainWaybill ? String(mainWaybill.waybill_code || '').trim() : ''; + const isChildWaybill = businessKey > 1 && mainWaybillCode; + + const extraCustomLines = isChildWaybill + ? [ `子单号【${businessKey}】-${mainWaybillCode}` ] + : []; + + orderPrintList.push(await this.buildOrderPlatformPrintItem({ + orderRow: effectiveOrderRowWithWaveIndex, + orderExpress: enrichedRow, + policyConfig, + platformCode, + templateSample, + extraCustomLines, + })); + } + + // 8. 分组输出 + // 分离有波次和无波次的打印条目 + const wavedItems = orderPrintList.filter(item => Number(item && item.wave_id || 0) > 0); + const noWaveItems = orderPrintList.filter(item => Number(item && item.wave_id || 0) === 0); + + const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ + waveRows, + hitWaveIds: validOrderWaveIds, + orderPrintList: wavedItems, + }); + + // 无波次条目按平台直接分组 + if (noWaveItems.length > 0) { + const noWavePlatforms = this.groupOrderPrintItemsByPlatform(noWaveItems); + waveGroups.push({ + wave_id: 0, + wave_no: '', + order_count: noWaveItems.length, + platforms: noWavePlatforms, + }); + // 将 0 加入 wave_ids 表示有无波次条目 + if (!validOrderWaveIds.includes(0)) { + validOrderWaveIds.push(0); + } + } + + const totalPlatforms = waveGroups.reduce((sum, waveGroup) => { + return sum + Number(waveGroup && waveGroup.platforms && waveGroup.platforms.length || 0); + }, 0); + + return { + summary: { + total_waves: waveGroups.length, + total_orders: orderPrintList.length, + total_platforms: totalPlatforms, + intercepted_count: interceptedOrders.length, + }, + waveGroups, + wave_ids: validOrderWaveIds, + intercepted_count: interceptedOrders.length, + intercepted_orders: interceptedOrders, + ext: { + missing_waybill_codes: missingWaybillCodes, + filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ], + }, + }; + } + + /** + * 按运单号数组查询运单记录(不限制 business_key,支持子单号)。 + * + * @param {string[]} waybillCodes 运单号数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 运单记录数组。 + */ + async queryWaybillsByCodes(waybillCodes = [], warehouseId) { + if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) { + return []; + } + + const normalizedCodes = Array.from(new Set( + waybillCodes.map(code => String(code || '').trim()).filter(Boolean) + )); + if (normalizedCodes.length === 0) { + return []; + } + + const rows = await this.ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', + 'order_id', + 'business_key', + 'waybill_code', + 'logistics_code', + 'logistics_name', + 'logistics_interface_id', + 'logistics_interface_name', + 'platform_code', + 'warehouse_id', + 'printinfo', + 'signature', + 'encryptprintinfo', + 'ver', + 'print_history_id', + 'cai_niao_auth_info_id', + ], + where: { + waybill_code: { + [Op.in]: normalizedCodes, + }, + warehouse_id: warehouseId, + }, + order: [[ 'order_id', 'ASC' ], [ 'business_key', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 按订单ID列表获取主运单映射(business_key=1)。 + * + * @param {number[]} orderIds 订单ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} order_id → 主运单记录。 + */ + async getMainWaybillMapByOrderIds(orderIds = [], warehouseId) { + const map = new Map(); + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return map; + } + + const normalizedOrderIds = Array.from(new Set( + orderIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0) + )); + if (normalizedOrderIds.length === 0) { + return map; + } + + const rows = await this.ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'order_id', 'business_key', 'waybill_code' ], + where: { + order_id: { [Op.in]: normalizedOrderIds }, + warehouse_id: warehouseId, + business_key: 1, + }, + raw: true, + }); + + for (const row of rows) { + map.set(Number(row.order_id), row); + } + return map; + } + + /** + * 规范化"按分组解锁"规则。 + * + * @param {Object} payload 规则入参。 + * @param {Array} payload.groups 分组条件原始列表。 + * @param {string} payload.groupType 分组类型。 + * @param {string} payload.unlockScope 解锁范围。 + * @param {Array} payload.validWaveIds 有效波次ID列表。 + * @return {Array} 规范化后的分组规则列表。 + */ + normalizeUnlockGroupRules(payload = {}) { + const requestPayload = this.isPlainObject(payload) ? payload : {}; + const groups = Array.isArray(requestPayload.groups) ? requestPayload.groups : []; + const groupType = String(requestPayload.groupType || '').trim(); + const unlockScope = String(requestPayload.unlockScope || 'group').trim(); + const validWaveIds = Array.isArray(requestPayload.validWaveIds) ? requestPayload.validWaveIds : []; + const validWaveIdSet = new Set(validWaveIds.map(waveId => Number(waveId || 0))); + const normalizedRules = []; + const dedupeKeySet = new Set(); + + for (const rawGroup of groups) { + if (!this.isPlainObject(rawGroup)) { + continue; + } + + const rawWaveId = rawGroup.wave_id ?? rawGroup.waveId; + const waveId = Number(String(rawWaveId ?? '').trim()); + if (!Number.isInteger(waveId) || waveId <= 0 || !validWaveIdSet.has(waveId)) { + continue; + } + + const rawPlatform = String(rawGroup.platform ?? rawGroup.group_key ?? rawGroup.groupKey ?? '').trim(); + const normalizedPlatformAlias = PrinterDataBuilder.normalizePlatformAlias(rawPlatform); + const platform = String(normalizedPlatformAlias && normalizedPlatformAlias.platform || rawPlatform).trim().toLowerCase(); + const sysLogisticsCode = String(rawGroup.sys_logistics_code ?? rawGroup.sysLogisticsCode ?? '').trim().toLowerCase(); + const orderIdSet = new Set(Array.isArray(rawGroup.order_ids || rawGroup.orderIds) + ? (rawGroup.order_ids || rawGroup.orderIds) + .map(orderId => Number(String(orderId ?? '').trim())) + .filter(orderId => Number.isInteger(orderId) && orderId > 0) + : []); + + if (unlockScope !== 'wave') { + if (groupType === 'platform' && !platform) { + continue; + } + + if (groupType === 'platform_express' && (!platform || !sysLogisticsCode)) { + continue; + } + + if (groupType === 'order' && orderIdSet.size === 0) { + continue; + } + } + + const dedupeKey = `${waveId}@@${groupType}@@${unlockScope}@@${platform}@@${sysLogisticsCode}@@${Array.from(orderIdSet).sort((a, b) => a - b).join(',')}`; + if (dedupeKeySet.has(dedupeKey)) { + continue; + } + + dedupeKeySet.add(dedupeKey); + normalizedRules.push({ + waveId, + platform, + sysLogisticsCode, + orderIdSet, + }); + } + + return normalizedRules; + } + + /** + * 判断订单是否命中“按分组解锁”规则。 + * + * @param {Object} payload 匹配入参。 + * @param {Object} payload.orderRow 订单行。 + * @param {Object} payload.rule 分组规则。 + * @param {string} payload.groupType 分组类型。 + * @param {string} payload.unlockScope 解锁范围。 + * @return {boolean} 是否命中规则。 + */ + isOrderMatchedByUnlockGroupRule(payload = {}) { + const requestPayload = this.isPlainObject(payload) ? payload : {}; + const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {}; + const rule = this.isPlainObject(requestPayload.rule) ? requestPayload.rule : {}; + const groupType = String(requestPayload.groupType || '').trim(); + const unlockScope = String(requestPayload.unlockScope || 'group').trim(); + + const orderWaveId = Number(orderRow && orderRow.wave_id || 0); + const ruleWaveId = Number(rule && rule.waveId || 0); + if (!Number.isInteger(orderWaveId) || orderWaveId <= 0 || orderWaveId !== ruleWaveId) { + return false; + } + + if (unlockScope === 'wave') { + return true; + } + + const orderId = Number(orderRow && orderRow.id || 0); + const orderIdSet = rule.orderIdSet instanceof Set ? rule.orderIdSet : new Set(); + if (groupType === 'order') { + return orderIdSet.has(orderId); + } + + const orderPlatformAlias = PrinterDataBuilder.normalizePlatformAlias(this.resolvePrintPlatformCode(orderRow, {})); + const orderPlatform = String(orderPlatformAlias && orderPlatformAlias.platform || '').trim().toLowerCase(); + if (orderPlatform !== String(rule.platform || '').trim().toLowerCase()) { + return false; + } + + if (groupType === 'platform_express') { + const orderSysLogisticsCode = String(orderRow && orderRow.sys_logistics_code || '').trim().toLowerCase(); + if (!orderSysLogisticsCode || orderSysLogisticsCode !== String(rule.sysLogisticsCode || '').trim().toLowerCase()) { + return false; + } + } + + if (orderIdSet.size > 0 && !orderIdSet.has(orderId)) { + return false; + } + + return true; + } + + /** + * 按分组解锁波次平台打印锁。 + * + * @param {Object} params 请求参数。 + * @param {Array} params.waveIds 波次ID数组。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {string} params.groupType 分组类型。 + * @param {string} params.unlockScope 解锁范围。 + * @param {Array} params.groups 分组条件。 + * @return {Promise} 解锁结果。 + */ + async unlockWavePlatformPrintDataByGroup(params = {}) { + const requestParams = this.isPlainObject(params) ? params : {}; + const { + waveIds, + warehouseId, + groupType, + unlockScope, + groups, + } = requestParams; + + const normalizedWaveIds = this.normalizeWaveIds(waveIds); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 必填,且必须为非空数组'); + } + + const normalizedWarehouseId = this.resolveWarehouseId(warehouseId); + const waveRows = await this.queryWavesByIds(normalizedWarehouseId, normalizedWaveIds); + if (waveRows.length === 0) { + return { + summary: { + total_waves: 0, + total_locked_orders: 0, + matched_group_orders: 0, + unlocked_count: 0, + }, + wave_ids: [], + unlocked_order_ids: [], + ext: { + missing_wave_ids: normalizedWaveIds, + filtered_wave_ids: [], + }, + }; + } + + const hitWaveIdSet = new Set(waveRows.map(row => Number(row.wave_id))); + const missingWaveIds = normalizedWaveIds.filter(waveId => !hitWaveIdSet.has(waveId)); + const hitWaveIds = normalizedWaveIds.filter(waveId => hitWaveIdSet.has(waveId)); + const orderRows = await this.queryOrdersByWaveIds(hitWaveIds, normalizedWarehouseId); + const { + validWaveIds, + filteredWaveIds, + } = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows); + const validWaveIdSet = new Set(validWaveIds); + + const lockedOrderRows = orderRows.filter(orderRow => { + const orderWaveId = Number(orderRow && orderRow.wave_id || 0); + return validWaveIdSet.has(orderWaveId) && this.isOrderLocked(orderRow); + }); + + if (lockedOrderRows.length === 0) { + return { + summary: { + total_waves: validWaveIds.length, + total_locked_orders: 0, + matched_group_orders: 0, + unlocked_count: 0, + }, + wave_ids: validWaveIds, + unlocked_order_ids: [], + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } + + const normalizedRules = this.normalizeUnlockGroupRules({ + groups, + groupType, + unlockScope, + validWaveIds, + }); + if (normalizedRules.length === 0) { + throw new Error('groups 未匹配到有效的分组解锁条件'); + } + + const matchedOrderRows = lockedOrderRows.filter(orderRow => { + return normalizedRules.some(rule => this.isOrderMatchedByUnlockGroupRule({ + orderRow, + rule, + groupType, + unlockScope, + })); + }); + const matchedOrderIds = Array.from(new Set(matchedOrderRows + .map(orderRow => Number(orderRow && orderRow.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0))); + + if (matchedOrderIds.length === 0) { + return { + summary: { + total_waves: validWaveIds.length, + total_locked_orders: lockedOrderRows.length, + matched_group_orders: 0, + unlocked_count: 0, + }, + wave_ids: validWaveIds, + unlocked_order_ids: [], + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } + + const orderModel = await this.getOrderModel('order', normalizedWarehouseId); + const updateResult = await orderModel.update({ + print_lock_status: 'none', + }, { + where: { + id: { + [Op.in]: matchedOrderIds, + }, + print_lock_status: { + [Op.ne]: 'none', + }, + }, + }); + + const unlockedCount = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; + // 尝试写入操作日志(非阻塞,不影响主流程) + try { + const operationLogService = this.service && this.service.systems && this.service.systems.operationLog; + const operator = this.getOrderLogOperator(); + const warehouseIdForLog = this.getOrderLogWarehouseId(normalizedWarehouseId) || normalizedWarehouseId; + + const rawGroupsText = (() => { + try { + return JSON.stringify(Array.isArray(groups) ? groups : []); + } catch (e) { + return ''; + } + })(); + + // 截断 groups 描述为合理长度,避免 message 过长 + const truncatedGroups = String(rawGroupsText || '').slice(0, 200); + const baseNote = `按分组解锁 groupType=${String(groupType || '')} groups=${truncatedGroups}`; + + const payloads = matchedOrderRows.map(orderRow => { + const orderId = Number(orderRow && orderRow.id || 0); + const waveId = Number(orderRow && orderRow.wave_id || 0); + const waveNo = String(orderRow && orderRow.wave_no || '').trim(); + + const note = `${baseNote} wave_id=${waveId} wave_no=${waveNo}`; + + return { + businessType: 'order', + businessId: orderId, + operationCode: 'unlock_by_group', + operator: { + id: operator && operator.id ? operator.id : (this.ctx.state?.user?.id || this.ctx.user?.id || 0), + name: operator && operator.name ? operator.name : (this.ctx.state?.user?.real_name || this.ctx.user?.name || 'system'), + }, + extras: { + warehouseId: warehouseIdForLog, + externalLogType: 'REQUEST', + externalLogId: null, + // 额外信息放入 message 中以便在表中检索;表结构暂无专门 trace 字段 + message: JSON.stringify({ + source: 'order.print.unlockWavePlatformPrintDataByGroup', + trace_id: this.ctx.requestId || this.ctx.traceId || null, + note, + }), + }, + beforeChanges: null, + }; + }).filter(item => item && Number(item.businessId) > 0); + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function' && payloads.length > 0) { + // 为性能考虑,若太多则分批(每批 100 条)并发写入 + const BATCH_SIZE = 100; + for (let i = 0; i < payloads.length; i += BATCH_SIZE) { + const batch = payloads.slice(i, i + BATCH_SIZE); + // 不等待所有批次顺序完成,改为并发触发但捕获错误 + // 这里仍然 await,以保证在单请求内完成写入,但不会抛出影响主逻辑的异常 + try { + await operationLogService.createOperationLogs(batch); + } catch (err) { + this.ctx.logger.warn('[orderPrint.unlockWavePlatformPrintDataByGroup] 写入操作日志失败,不影响业务', err); + } + } + } + } catch (logErr) { + this.ctx.logger.warn('[orderPrint.unlockWavePlatformPrintDataByGroup] 写入操作日志失败(全局捕获),不影响业务', logErr); + } + + return { + summary: { + total_waves: validWaveIds.length, + total_locked_orders: lockedOrderRows.length, + matched_group_orders: matchedOrderIds.length, + unlocked_count: unlockedCount > 0 ? unlockedCount : 0, + }, + wave_ids: validWaveIds, + unlocked_order_ids: matchedOrderIds, + unlocked_orders: matchedOrderRows.map(orderRow => ({ + order_id: Number(orderRow && orderRow.id || 0), + wave_id: Number(orderRow && orderRow.wave_id || 0), + wave_no: String(orderRow && orderRow.wave_no || '').trim(), + order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(), + })), + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } + + /** + * 规范化波次ID数组(去重与数字化)。 + * + * @param {Array} waveIds 原始波次ID数组。 + * @return {Array} 规范化后的波次ID数组。 + */ + normalizeWaveIds(waveIds = []) { + if (!Array.isArray(waveIds)) { + return []; + } + + const normalizedSet = new Set(); + + for (const rawId of waveIds) { + const normalizedId = Number(String(rawId ?? '').trim()); + if (Number.isInteger(normalizedId) && normalizedId > 0) { + normalizedSet.add(normalizedId); + } + } + + return Array.from(normalizedSet); + } + + /** + * 规范化订单ID数组。 + * + * 去重、过滤非法值(非正整数),返回纯数字数组。 + * + * @param {Array} orderIds 订单ID数组。 + * @return {Array} 规范化后的订单ID数组。 + */ + normalizeOrderIds(orderIds = []) { + if (!Array.isArray(orderIds)) { + return []; + } + + const normalizedSet = new Set(); + + for (const rawId of orderIds) { + const normalizedId = Number(String(rawId ?? '').trim()); + if (Number.isInteger(normalizedId) && normalizedId > 0) { + normalizedSet.add(normalizedId); + } + } + + return Array.from(normalizedSet); + } + + /** + * 从当前上下文获取仓库ID。 + * + * 用于不再接受调用方传入 warehouseId 的场景,直接从登录态/上下文读取。 + * + * @return {number} 当前上下文中的仓库ID。 + */ + getContextWarehouseId() { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + return contextWarehouseId; + } + + /** + * 解析并校验仓库ID。 + * + * @param {number|string} warehouseId 入参仓库ID。 + * @return {number} 规范化后的仓库ID。 + */ + resolveWarehouseId(warehouseId) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + const normalizedWarehouseId = Number(String(warehouseId ?? '').trim()); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('warehouse_id 必填且必须为正整数'); + } + + if (normalizedWarehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 必须与当前用户上下文 store_id 保持一致'); + } + + return normalizedWarehouseId; + } + + /** + * 按波次ID批量查询波次信息。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} waveIds 波次ID数组。 + * @return {Promise>} 波次基础信息。 + */ + async queryWavesByIds(warehouseId, waveIds = []) { + if (!Array.isArray(waveIds) || waveIds.length === 0) { + return []; + } + + const querySql = ` + SELECT wave_id, wave_no, source, wave_type + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND wave_status <> -1 + `; + + const rows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId, + waveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 按波次ID批量查询订单明细。 + * + * @param {Array} waveIds 波次ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单明细列表。 + */ + async queryOrdersByWaveIds(waveIds = [], warehouseId) { + if (!Array.isArray(waveIds) || waveIds.length === 0) { + return []; + } + + const orderModel = await this.getOrderModel('order', warehouseId); + const rows = await orderModel.findAll({ + attributes: [ + 'id', + 'delivery_order_code', + 'source_order_codes', + 'warehouse_id', + 'store_id', + 'wave_id', + 'wave_no', + 'name', + 'tel', + 'mobile', + 'province', + 'city', + 'area', + 'town', + 'detail_address', + 'zip_code', + 'items', + 'source_platform_code', + 'sys_platform_code', + 'sys_platform_name', + 'logistics_code', + 'logistics_name', + 'sys_logistics_code', + 'sys_logistics_name', + 'post_status', + 'status', + 'outbound_status', + 'print_status', + 'lock_status', + 'print_lock_status', + 'intercept_status', + 'items_count', + 'items_total', + 'items_weight', + 'freight', + 'create_at', + 'pay_time', + 'from_key', + ], + where: { + wave_id: { + [Op.in]: waveIds, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 按订单ID批量查询订单明细。 + * + * 与 queryOrdersByWaveIds 返回相同的字段结构,但按订单 ID 列表直接查询。 + * + * @param {Array} orderIds 订单ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单明细列表。 + */ + async queryOrdersByIds(orderIds = [], warehouseId) { + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return []; + } + + // 公共查询字段:current 表与 dispatch 表使用相同字段选择 + const sharedAttributes = [ + 'id', + 'delivery_order_code', + 'source_order_codes', + 'warehouse_id', + 'store_id', + 'wave_id', + 'wave_no', + 'name', + 'tel', + 'mobile', + 'province', + 'city', + 'area', + 'town', + 'detail_address', + 'zip_code', + 'items', + 'source_platform_code', + 'sys_platform_code', + 'sys_platform_name', + 'logistics_code', + 'logistics_name', + 'sys_logistics_code', + 'sys_logistics_name', + 'post_status', + 'status', + 'outbound_status', + 'print_status', + 'lock_status', + 'print_lock_status', + 'intercept_status', + 'items_count', + 'items_total', + 'items_weight', + 'freight', + 'create_at', + 'pay_time', + // OMS 取号订单的回源应用 appKey,打印时回 OMS 换新 params 要用 + 'from_key', + ]; + + // 第一步:查询 current 主表(wms_order_delivery_{warehouseId}) + const orderModel = await this.getOrderModel('order', warehouseId); + const rows = await orderModel.findAll({ + attributes: sharedAttributes, + where: { + id: { + [Op.in]: orderIds, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + const currentRows = Array.isArray(rows) ? rows : []; + + // 第二步:若 current 表未命中全部订单,计算缺失 ID 并兜底查询 dispatch 表 + if (currentRows.length < orderIds.length) { + const foundIds = new Set(currentRows.map(row => row.id)); + const missingIds = orderIds.filter(id => !foundIds.has(id)); + + try { + // 获取 dispatch 分表模型,表可能不存在(返回 null) + const dispatchModel = await this.getOrderModelByTableType('dispatch', warehouseId); + if (dispatchModel) { + const dispatchRows = await dispatchModel.findAll({ + attributes: sharedAttributes, + where: { + id: { + [Op.in]: missingIds, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + if (Array.isArray(dispatchRows) && dispatchRows.length > 0) { + // 合并 current 表与 dispatch 表结果,按 wave_id、id 升序排列 + const mergedRows = [ ...currentRows, ...dispatchRows ].sort((a, b) => { + const waveDiff = (a.wave_id || 0) - (b.wave_id || 0); + if (waveDiff !== 0) return waveDiff; + return (a.id || 0) - (b.id || 0); + }); + return mergedRows; + } + } + } catch (err) { + // dispatch 表查询失败时仅记录日志,不影响 current 表已查到的结果 + this.ctx.logger.warn( + `[queryOrdersByIds] dispatch 兜底查询失败,将仅返回 current 表结果:${err.message}` + ); + } + } + + return currentRows; + } + + /** + * 按订单ID批量查询快递单信息。 + * + * @param {Array} orderIds 订单ID数组。 + * @return {Promise>} 快递单信息列表。 + */ + /** + * 根据订单 ID 列表批量查询运单记录。 + * 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。 + * + * @param {number[]} orderIds 订单 ID 列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、 + * logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、 + * warehouse_id、printinfo、signature、encryptprintinfo、ver。 + */ + async queryOrderExpressByOrderIds(orderIds = [], warehouseId) { + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return []; + } + + const normalizedOrderIds = Array.from(new Set(orderIds + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0))); + if (normalizedOrderIds.length === 0) { + return []; + } + + const rows = await this.ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', + 'order_id', + 'business_key', + 'waybill_code', + 'logistics_code', + 'logistics_name', + 'logistics_interface_id', + 'logistics_interface_name', + 'platform_code', + 'warehouse_id', + 'printinfo', + 'signature', + 'encryptprintinfo', + 'ver', + 'print_history_id', + 'cai_niao_auth_info_id', + ], + where: { + order_id: { + [Op.in]: normalizedOrderIds, + }, + warehouse_id: warehouseId, + business_key: 1, + }, + order: [[ 'order_id', 'ASC' ], [ 'business_key', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 按订单ID批量查询波次顺序信息。 + * + * 数据来源:wms_order_wave_index。 + * 当 query 能力不可用、SQL 执行失败或无数据时,优雅降级返回空映射。 + * + * @param {Array} orderIds 订单ID数组。 + * @param {number} warehouseId 仓库ID。 + * @param {Array} [waveIds] 可选波次ID数组,用于限制查询范围。 + * @return {Promise>} 订单顺序映射。 + */ + async queryWaveOrderIndexMapByOrderIds(orderIds = [], warehouseId, waveIds = []) { + const resultMap = new Map(); + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0))); + const normalizedWaveIds = Array.from(new Set((Array.isArray(waveIds) ? waveIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0))); + + if (normalizedOrderIds.length === 0) { + return resultMap; + } + + const queryMethod = this.ctx.model && this.ctx.model.query; + if (typeof queryMethod !== 'function') { + return resultMap; + } + + const waveFilterSql = normalizedWaveIds.length > 0 + ? ' AND wave_id IN (:waveIds)\n' + : ''; + const querySql = ` + SELECT order_id, wave_id, wave_index, platforms_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND order_id IN (:orderIds) +${waveFilterSql} + `; + + try { + const rows = await queryMethod.call(this.ctx.model, querySql, { + replacements: { + warehouseId, + orderIds: normalizedOrderIds, + ...(normalizedWaveIds.length > 0 ? { waveIds: normalizedWaveIds } : {}), + }, + type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT, + }); + + for (const row of Array.isArray(rows) ? rows : []) { + const orderId = Number(row && row.order_id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + resultMap.set(orderId, { + wave_id: Number(row && row.wave_id || 0), + wave_index: Number(row && row.wave_index || 0), + platforms_index: Number(row && row.platforms_index || 0), + }); + } + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.queryWaveOrderIndexMapByOrderIds] 查询失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + + return resultMap; + } + + /** + * 批量查询小团购波次(wave_type=1 且 source∈{1,2} 策略任务)的拣货篮号映射。 + * + * 小团购判定由调用方根据 wms_wave_batch.wave_type/source 完成,本方法只负责取篮号。 + * 篮号存在两种写入场景,均需兼容: + * - PDA 扫码创建任务(systemMethods/pick.js createWavePickTask):订单级篮号写入 + * wms_wave_pick_task_order.box_no(订单所属最小篮号),订单级优先; + * - 计划创建任务(systemMethods/order/wave.js createWavePickTaskFromPlan):篮号写入 + * wms_wave_pick_task_wave.box_no(每波次一篮),任务订单表不含小团购订单行, + * 按订单所属 wave_id 兜底取波次级篮号。 + * + * 同一订单/波次可能命中多个任务,按 task_id DESC 取最新任务的记录。 + * 查询失败时优雅降级返回空映射。 + * + * @param {Array} orderIds 订单ID数组。 + * @param {number} warehouseId 仓库ID。 + * @param {Map} [orderWaveIdMap] 订单ID到波次ID的映射,用于波次级篮号兜底。 + * @return {Promise>} 订单ID到拣货篮号映射。 + */ + async querySmallGroupBoxNoMap(orderIds = [], warehouseId, orderWaveIdMap = null) { + const resultMap = new Map(); + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0))); + if (normalizedOrderIds.length === 0) { + return resultMap; + } + + const queryMethod = this.ctx.model && this.ctx.model.query; + if (typeof queryMethod !== 'function') { + return resultMap; + } + + const safeOrderWaveIdMap = orderWaveIdMap instanceof Map ? orderWaveIdMap : new Map(); + + try { + // 1) 订单级篮号(PDA 扫码创建任务):同一订单多条时取最新任务(task_id DESC) + const orderRows = await queryMethod.call(this.ctx.model, ` + SELECT order_id, box_no + FROM wms_wave_pick_task_order + WHERE warehouse_id = :warehouseId + AND order_id IN (:orderIds) + ORDER BY task_id DESC + `, { + replacements: { + warehouseId, + orderIds: normalizedOrderIds, + }, + type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT, + }); + + for (const row of Array.isArray(orderRows) ? orderRows : []) { + const orderId = Number(row && row.order_id || 0); + const boxNo = Number(row && row.box_no || 0); + if (orderId > 0 && boxNo > 0 && !resultMap.has(orderId)) { + resultMap.set(orderId, { box_no: boxNo }); + } + } + + // 2) 波次级篮号兜底(计划创建任务):未命中订单按其 wave_id 取波次篮号 + const backfillWaveIds = new Set(); + for (const orderId of normalizedOrderIds) { + if (resultMap.has(orderId)) { + continue; + } + const waveId = Number(safeOrderWaveIdMap.get(orderId) || 0); + if (waveId > 0) { + backfillWaveIds.add(waveId); + } + } + + if (backfillWaveIds.size > 0) { + const waveRows = await queryMethod.call(this.ctx.model, ` + SELECT wave_id, box_no + FROM wms_wave_pick_task_wave + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + ORDER BY task_id DESC + `, { + replacements: { + warehouseId, + waveIds: Array.from(backfillWaveIds), + }, + type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT, + }); + + const waveBoxNoMap = new Map(); + for (const row of Array.isArray(waveRows) ? waveRows : []) { + const waveId = Number(row && row.wave_id || 0); + const boxNo = Number(row && row.box_no || 0); + if (waveId > 0 && boxNo > 0 && !waveBoxNoMap.has(waveId)) { + waveBoxNoMap.set(waveId, boxNo); + } + } + + for (const orderId of normalizedOrderIds) { + if (resultMap.has(orderId)) { + continue; + } + const waveId = Number(safeOrderWaveIdMap.get(orderId) || 0); + const boxNo = waveBoxNoMap.get(waveId) || 0; + if (waveId > 0 && boxNo > 0) { + resultMap.set(orderId, { box_no: boxNo }); + } + } + } + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.querySmallGroupBoxNoMap] 查询失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + + return resultMap; + } + + /** + * 按波次ID批量查询波次总订单数。 + * + * 数据来源:wms_order_wave_index。 + * 当 query 能力不可用、SQL 执行失败或无数据时,优雅降级返回空映射。 + * + * @param {Array} waveIds 波次ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 波次ID到总订单数映射。 + */ + async queryWaveTotalOrderCountMap(waveIds = [], warehouseId) { + const resultMap = new Map(); + const normalizedWaveIds = Array.from(new Set((Array.isArray(waveIds) ? waveIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0))); + + if (normalizedWaveIds.length === 0) { + return resultMap; + } + + const queryMethod = this.ctx.model && this.ctx.model.query; + if (typeof queryMethod !== 'function') { + return resultMap; + } + + const querySql = ` + SELECT wave_id, COUNT(1) AS total_orders + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + GROUP BY wave_id + `; + + try { + const rows = await queryMethod.call(this.ctx.model, querySql, { + replacements: { + warehouseId, + waveIds: normalizedWaveIds, + }, + type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT, + }); + + for (const row of Array.isArray(rows) ? rows : []) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + const totalOrders = Number(row && row.total_orders || 0); + resultMap.set(waveId, totalOrders > 0 ? totalOrders : 0); + } + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.queryWaveTotalOrderCountMap] 查询失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + + return resultMap; + } + + /** + * 校验业务ID为1的运单号数据完整性。 + * + * @param {Array} orderIds 订单ID数组。 + * @param {Array} orderExpressRows 快递单查询结果。 + */ + assertBusinessWaybillCompleteness(orderIds = [], orderExpressRows = []) { + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0))); + if (normalizedOrderIds.length === 0) { + return; + } + + const validOrderIdSet = new Set(); + const rows = Array.isArray(orderExpressRows) ? orderExpressRows : []; + for (const row of rows) { + const orderId = Number(row && row.order_id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + const waybillCode = String(row && row.waybill_code || '').trim(); + if (!waybillCode) { + continue; + } + + validOrderIdSet.add(orderId); + } + + const missingOrderIds = normalizedOrderIds.filter(orderId => !validOrderIdSet.has(orderId)); + if (missingOrderIds.length > 0) { + throw new Error(`业务id为1的运单号数据缺失,缺失 order_id: ${missingOrderIds.join(',')}`); + } + } + + /** + * 按订单ID构建快递信息映射,优先保留带运单号的记录。 + * + * @param {Array} rows 快递数据行。 + * @return {Map} 订单到快递信息的映射。 + */ + buildOrderExpressMap(rows = []) { + const expressMap = new Map(); + + for (const row of rows) { + const orderId = Number(row && row.order_id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + const previousRow = expressMap.get(orderId); + if (!previousRow) { + expressMap.set(orderId, row); + continue; + } + + const previousWaybillCode = String(previousRow.waybill_code || '').trim(); + const currentWaybillCode = String(row && row.waybill_code || '').trim(); + if (!previousWaybillCode && currentWaybillCode) { + expressMap.set(orderId, row); + } + } + + return expressMap; + } + + /** + * 判断平台编码是否归一化为菜鸟。 + * + * @param {string} platformCode 平台编码。 + * @return {boolean} 是否为菜鸟平台。 + */ + isCainiaoPlatformCode(platformCode = '') { + return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'cainiao'; + } + + /** + * 判断平台编码是否归一化为京东。 + * + * @param {string} platformCode 平台编码。 + * @return {boolean} 是否为京东平台。 + */ + isJdPlatformCode(platformCode = '') { + return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'jd'; + } + + /** + * 判断平台编码是否归一化为拼多多。 + * + * @param {string} platformCode 平台编码。 + * @return {boolean} 是否为拼多多平台。 + */ + isPddPlatformCode(platformCode = '') { + return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'pdd'; + } + + /** + * 判断平台编码是否归一化为抖音。 + * + * @param {string} platformCode 平台编码。 + * @return {boolean} 是否为抖音平台。 + */ + isDouyinPlatformCode(platformCode = '') { + return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'douyin'; + } + + /** + * 收集菜鸟编码映射可能命中的快递编码候选项。 + * + * 优先使用系统快递编码,其次兼容订单/运单上的物流编码,避免遗漏历史数据。 + * + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {Array} 去重后的快递编码候选列表。 + */ + collectCainiaoExpressLookupCodes(orderRow = {}, orderExpress = {}) { + const codeList = []; + const appendCode = value => { + const normalizedCode = String(value || '').trim(); + if (!normalizedCode || codeList.includes(normalizedCode)) { + return; + } + + codeList.push(normalizedCode); + }; + + appendCode(orderRow && orderRow.sys_logistics_code); + appendCode(orderExpress && orderExpress.logistics_code); + appendCode(orderRow && orderRow.logistics_code); + + return codeList; + } + + /** + * 批量查询快递基础资料中的菜鸟编码映射。 + * + * @param {Array} expressCodes 快递编码列表。 + * @return {Promise>} 快递编码到菜鸟编码的映射。 + */ + async queryCainiaoCpCodeMap(expressCodes = []) { + const expressModel = this.ctx.model && this.ctx.model.Express; + const normalizedCodes = Array.from(new Set((Array.isArray(expressCodes) ? expressCodes : []) + .map(code => String(code || '').trim()) + .filter(Boolean))); + const cpCodeMap = new Map(); + + if (!expressModel || typeof expressModel.findAll !== 'function' || normalizedCodes.length === 0) { + return cpCodeMap; + } + + const rows = await expressModel.findAll({ + attributes: [ 'code', 'CAINIAO' ], + where: { + code: { + [Op.in]: normalizedCodes, + }, + }, + raw: true, + }); + + for (const row of Array.isArray(rows) ? rows : []) { + const code = String(row && row.code || '').trim(); + const cainiaoCode = String(row && row.CAINIAO || '').trim(); + if (!code || !cainiaoCode) { + continue; + } + + cpCodeMap.set(code, cainiaoCode); + } + + return cpCodeMap; + } + + /** + * 读取仓库下菜鸟平台的快递接口配置列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 接口配置列表。 + */ + async queryCainiaoExpressInterfaceList(warehouseId) { + const expressInterfaceService = this.service + && this.service.systems + && this.service.systems.setting + && this.service.systems.setting.expressInterface; + + if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') { + return []; + } + + const result = await expressInterfaceService.listByWarehousePlatformCode({ + warehouseId, + platformCode: 'CAINIAO', + }); + + return Array.isArray(result && result.data) ? result.data : []; + } + + /** + * 读取仓库下京东平台的快递接口表配置列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 接口配置列表。 + */ + async queryJdExpressInterfaceList(warehouseId) { + const expressInterfaceService = this.service + && this.service.systems + && this.service.systems.setting + && this.service.systems.setting.expressInterface; + + if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') { + return []; + } + + const result = await expressInterfaceService.listByWarehousePlatformCode({ + warehouseId, + platformCode: 'JD', + }); + + return Array.isArray(result && result.data) ? result.data : []; + } + + /** + * 读取仓库下拼多多平台的快递接口表配置列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 接口配置列表。 + */ + async queryPddExpressInterfaceList(warehouseId) { + const expressInterfaceService = this.service + && this.service.systems + && this.service.systems.setting + && this.service.systems.setting.expressInterface; + + if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') { + return []; + } + + const result = await expressInterfaceService.listByWarehousePlatformCode({ + warehouseId, + platformCode: 'PDD', + }); + + return Array.isArray(result && result.data) ? result.data : []; + } + + /** + * 读取仓库下抖音平台的快递接口表配置列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 接口配置列表。 + */ + async queryDouyinExpressInterfaceList(warehouseId) { + const expressInterfaceService = this.service + && this.service.systems + && this.service.systems.setting + && this.service.systems.setting.expressInterface; + + if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') { + return []; + } + + const result = await expressInterfaceService.listByWarehousePlatformCode({ + warehouseId, + platformCode: 'DY', + }); + const dyList = Array.isArray(result && result.data) ? result.data : []; + if (dyList.length > 0) { + return dyList; + } + + const fallbackResult = await expressInterfaceService.listByWarehousePlatformCode({ + warehouseId, + platformCode: 'DOUYIN', + }); + + return Array.isArray(fallbackResult && fallbackResult.data) ? fallbackResult.data : []; + } + + /** + * 按订单物流编码匹配菜鸟主面单接口配置。 + * + * 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。 + * + * @param {Array} interfaceList 接口配置列表。 + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {Object|null} 命中的接口配置。 + */ + pickCainiaoExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) { + const logisticsCode = String( + orderExpress && orderExpress.logistics_code + || orderRow && orderRow.logistics_code + || orderRow && orderRow.sys_logistics_code + || '' + ).trim(); + if (!logisticsCode) { + return null; + } + + const expressService = this.service && this.service.systems && this.service.systems.express; + if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') { + return expressService.pickWaybillExpressInterface( + interfaceList, + { + options: { + logistics_code: logisticsCode, + sys_platform_code: 'CAINIAO', + }, + }, + { code: 'CAINIAO' } + ); + } + + const normalizedLogisticsCode = logisticsCode.toLowerCase(); + for (const item of Array.isArray(interfaceList) ? interfaceList : []) { + if (!this.isPlainObject(item)) { + continue; + } + + const candidateCodes = [ + String(item.sys_express_code || '').trim().toLowerCase(), + String(item.express_code || '').trim().toLowerCase(), + ]; + const expressMap = this.isPlainObject(item.express) ? item.express : {}; + candidateCodes.push(String(expressMap.CAINIAO || '').trim().toLowerCase()); + + if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) { + return item; + } + } + + return null; + } + + /** + * 按订单物流编码匹配京东主面单接口表配置。 + * + * 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。 + * + * @param {Array} interfaceList 接口配置列表。 + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {Object|null} 命中的接口配置。 + */ + pickJdExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) { + const logisticsCode = String( + orderExpress && orderExpress.logistics_code + || orderRow && orderRow.logistics_code + || orderRow && orderRow.sys_logistics_code + || '' + ).trim(); + if (!logisticsCode) { + return null; + } + + const expressService = this.service && this.service.systems && this.service.systems.express; + if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') { + const matchedInterface = expressService.pickWaybillExpressInterface( + interfaceList, + { + options: { + logistics_code: logisticsCode, + sys_platform_code: 'JD', + }, + }, + { code: 'JD' } + ); + if (matchedInterface) { + return matchedInterface; + } + } + + const normalizedLogisticsCode = logisticsCode.toLowerCase(); + for (const item of Array.isArray(interfaceList) ? interfaceList : []) { + if (!this.isPlainObject(item)) { + continue; + } + + const candidateCodes = [ + String(item.sys_express_code || '').trim().toLowerCase(), + String(item.express_code || '').trim().toLowerCase(), + ]; + const expressMap = this.isPlainObject(item.express) ? item.express : {}; + candidateCodes.push(String(expressMap.JD || '').trim().toLowerCase()); + + if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) { + return item; + } + } + + return null; + } + + /** + * 按订单物流编码匹配拼多多主面单接口表配置。 + * + * 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。 + * + * @param {Array} interfaceList 接口配置列表。 + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {Object|null} 命中的接口配置。 + */ + pickPddExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) { + const logisticsCode = String( + orderExpress && orderExpress.logistics_code + || orderRow && orderRow.logistics_code + || orderRow && orderRow.sys_logistics_code + || '' + ).trim(); + if (!logisticsCode) { + return null; + } + + const expressService = this.service && this.service.systems && this.service.systems.express; + if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') { + const matchedInterface = expressService.pickWaybillExpressInterface( + interfaceList, + { + options: { + logistics_code: logisticsCode, + sys_platform_code: 'PDD', + print_platform_code: 'PDD', + }, + }, + { code: 'PDD' } + ); + if (matchedInterface) { + return matchedInterface; + } + } + + const normalizedLogisticsCode = logisticsCode.toLowerCase(); + for (const item of Array.isArray(interfaceList) ? interfaceList : []) { + if (!this.isPlainObject(item)) { + continue; + } + + const candidateCodes = [ + String(item.sys_express_code || '').trim().toLowerCase(), + String(item.express_code || '').trim().toLowerCase(), + ]; + const expressMap = this.isPlainObject(item.express) ? item.express : {}; + candidateCodes.push(String(expressMap.PDD || '').trim().toLowerCase()); + + if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) { + return item; + } + } + + return null; + } + + /** + * 按订单物流编码匹配抖音主面单接口表配置。 + * + * 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。 + * + * @param {Array} interfaceList 接口配置列表。 + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {Object|null} 命中的接口配置。 + */ + pickDouyinExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) { + const logisticsCode = String( + orderExpress && orderExpress.logistics_code + || orderRow && orderRow.logistics_code + || orderRow && orderRow.sys_logistics_code + || '' + ).trim(); + if (!logisticsCode) { + return null; + } + + const expressService = this.service && this.service.systems && this.service.systems.express; + if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') { + const matchedInterface = expressService.pickWaybillExpressInterface( + interfaceList, + { + options: { + logistics_code: logisticsCode, + sys_platform_code: 'DY', + print_platform_code: 'DY', + }, + }, + { code: 'DY' } + ); + if (matchedInterface) { + return matchedInterface; + } + } + + const normalizedLogisticsCode = logisticsCode.toLowerCase(); + for (const item of Array.isArray(interfaceList) ? interfaceList : []) { + if (!this.isPlainObject(item)) { + continue; + } + + const candidateCodes = [ + String(item.sys_express_code || '').trim().toLowerCase(), + String(item.express_code || '').trim().toLowerCase(), + ]; + const expressMap = this.isPlainObject(item.express) ? item.express : {}; + candidateCodes.push(String(expressMap.DY || '').trim().toLowerCase()); + candidateCodes.push(String(expressMap.DOUYIN || '').trim().toLowerCase()); + + if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) { + return item; + } + } + + return null; + } + + /** + * 解析抖音打印应使用的快递接口配置(按取号店铺隔离)。 + * + * 优先用运单落库的 logistics_interface_id 精确命中取号时使用的接口配置, + * 避免同仓同平台多店铺时按快递编码误取到其他店铺的 token; + * 仅当运单缺少 interface_id(历史数据)且同仓抖音接口只绑定了一个店铺时,才回退到按快递编码匹配。 + * + * @param {Array} interfaceList 接口配置列表。 + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {Object} 命中结果,interfaceRow 为命中的接口配置(未命中为 null),matchedBy 为命中方式。 + */ + resolveDouyinExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) { + const safeList = (Array.isArray(interfaceList) ? interfaceList : []) + .filter(item => this.isPlainObject(item)); + const interfaceId = Number(orderExpress && orderExpress.logistics_interface_id || 0); + + if (Number.isInteger(interfaceId) && interfaceId > 0) { + const exactInterface = safeList.find(item => Number(item.id) === interfaceId); + return { + interfaceRow: exactInterface || null, + matchedBy: exactInterface ? 'logistics_interface_id' : 'logistics_interface_id_missed', + }; + } + + const shopIds = new Set(safeList + .map(item => Number(item.shop_id || 0)) + .filter(shopId => Number.isInteger(shopId) && shopId > 0)); + if (shopIds.size > 1) { + // 多店铺场景下无法判定归属,宁可不取临时 key,也不能串用其他店铺的 token + return { + interfaceRow: null, + matchedBy: 'shop_ambiguous', + }; + } + + const fallbackInterface = this.pickDouyinExpressInterface(safeList, orderRow, orderExpress); + return { + interfaceRow: fallbackInterface || null, + matchedBy: fallbackInterface ? 'express_code' : 'unmatched', + }; + } + + /** + * 构建抖音临时 key 缓存键。 + * + * 抖音 logistics.getShopKey 以店铺(wms_express_interface.shop_id + token)为维度, + * 缓存键必须带店铺标识与 token 指纹,避免不同店铺之间串用临时 key。 + * + * @param {Object} interfaceRow 命中的快递接口配置。 + * @return {string} 缓存键,无法定位归属时返回空字符串(表示不缓存)。 + */ + buildDouyinParamsCacheKey(interfaceRow = {}) { + const safeInterfaceRow = this.isPlainObject(interfaceRow) ? interfaceRow : {}; + const token = String(safeInterfaceRow.token || '').trim(); + if (!token || !this.app || typeof this.app.getCacheAsync !== 'function') { + return ''; + } + + const tokenFingerprint = crypto.createHash('md5').update(token, 'utf8').digest('hex') + .slice(0, 8); + const shopId = Number(safeInterfaceRow.shop_id || 0); + if (Number.isInteger(shopId) && shopId > 0) { + return `douyin:params:shop${shopId}:${tokenFingerprint}`; + } + + const interfaceId = Number(safeInterfaceRow.id || 0); + return Number.isInteger(interfaceId) && interfaceId > 0 + ? `douyin:params:if${interfaceId}:${tokenFingerprint}` + : ''; + } + + /** + * 获取抖音打印临时 key 的 params 串(按店铺缓存)。 + * + * 同一批次内相同缓存键的并发请求复用同一个 Promise,避免波次打印重复调用菠萝派。 + * + * @param {Object} interfaceRow 命中的快递接口配置。 + * @param {Map>} [inflightMap] 并发去重表。 + * @return {Promise} params 串,获取失败返回空字符串。 + */ + async getDouyinPrintParams(interfaceRow = {}, inflightMap = new Map()) { + const safeInterfaceRow = this.isPlainObject(interfaceRow) ? interfaceRow : {}; + const token = String(safeInterfaceRow.token || '').trim(); + if (!token) { + this.ctx.logger.warn('[orderPrint.getDouyinPrintParams] 快递接口缺少 token,跳过临时 key 获取', { + interfaceId: Number(safeInterfaceRow.id || 0), + shopId: Number(safeInterfaceRow.shop_id || 0), + }); + return ''; + } + + const cacheKey = this.buildDouyinParamsCacheKey(safeInterfaceRow); + if (cacheKey) { + try { + const cachedParams = await this.app.getCacheAsync(cacheKey); + if (cachedParams && typeof cachedParams === 'string') { + return cachedParams; + } + } catch (error) { + this.ctx.logger.warn('[orderPrint.getDouyinPrintParams] 读取缓存失败: %s', error.message); + } + + if (inflightMap.has(cacheKey)) { + return inflightMap.get(cacheKey); + } + } + + const requestTask = this.requestDouyinPrintParams(safeInterfaceRow, token, cacheKey); + if (!cacheKey) { + return requestTask; + } + + inflightMap.set(cacheKey, requestTask); + try { + return await requestTask; + } finally { + inflightMap.delete(cacheKey); + } + } + + /** + * 调用菠萝派获取抖音临时 key,并仅对有效返回回写缓存。 + * + * @param {Object} interfaceRow 命中的快递接口配置。 + * @param {string} token 店铺访问令牌。 + * @param {string} cacheKey 缓存键,为空时不回写缓存。 + * @return {Promise} params 串,失败返回空字符串。 + */ + async requestDouyinPrintParams(interfaceRow = {}, token = '', cacheKey = '') { + const poloConfig = this.config.poloApi || {}; + const interfaceId = Number(interfaceRow.id || 0); + const shopId = Number(interfaceRow.shop_id || 0); + try { + const PoloApiClient = require('../../lib/polo_api_client'); + const poloClient = new PoloApiClient(this.ctx); + const result = await poloClient.request({ + method: 'Differ.JH.Business.GetPlatApiRequestInfo', + bizcontent: { platMethod: '/logistics/getShopKey' }, + config: { + interface_url: 'https://api.polyapi.com/openapi/do', + appkey: poloConfig.appKey || '', + app_secret: poloConfig.appSecret || '', + platid: 126, + version: '1.5', + token, + }, + token, + }); + + const requestInfo = String(result && result.requestinfo || '').trim(); + this.ctx.logger.info('[orderPrint.requestDouyinPrintParams] 菠萝派临时 key 响应', { + interfaceId, + shopId, + cacheKey, + code: String(result && result.code || ''), + hasRequestInfo: !!requestInfo, + }); + if (!requestInfo) { + this.ctx.logger.warn('[orderPrint.requestDouyinPrintParams] 菠萝派未返回 requestinfo,params 置空', { + interfaceId, + shopId, + }); + return ''; + } + + if (cacheKey && this.app && typeof this.app.setCacheAsync === 'function') { + try { + await this.app.setCacheAsync(cacheKey, requestInfo, DOUYIN_PRINT_PARAMS_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[orderPrint.requestDouyinPrintParams] 写入缓存失败: %s', error.message); + } + } + return requestInfo; + } catch (error) { + this.ctx.logger.warn('[orderPrint.requestDouyinPrintParams] 获取抖音临时 key 失败: %s', error.message); + return ''; + } + } + + /** + * 构建 OMS 抖音 params 缓存键。 + * + * params 有效期 600 秒,且同一店铺(cai_niao_auth_info_id)共用一份, + * 因此按店铺维度缓存,避免波次内每单都回 OMS 换一次。 + * + * @param {number|string} caiNiaoAuthInfoId 菜鸟授权网点ID(店铺维度,每个店铺唯一)。 + * @return {string} 缓存键,无法定位时返回空字符串(表示不缓存)。 + */ + buildOmsDouyinParamsCacheKey(caiNiaoAuthInfoId) { + const normalizedAuthInfoId = Number(caiNiaoAuthInfoId) || 0; + + return normalizedAuthInfoId > 0 + ? `${OMS_DOUYIN_PARAMS_CACHE_KEY_PREFIX}:${normalizedAuthInfoId}` + : ''; + } + + /** + * 按 cai_niao_auth_info_id 归集抖音打印参数换取的样本。 + * + * 同一店铺(授权网点)内任取一条带 print_history_id 的运单即可完成换取, + * 换取到的 params 供该店铺下所有运单共用。 + * + * @param {Array} orderRows 订单行列表。 + * @param {Array} orderExpressRows 运单行列表。 + * @return {Map} 授权网点ID → 换取样本。 + */ + buildDouyinOmsParamsSampleMap(orderRows = [], orderExpressRows = []) { + const orderRowMap = new Map((Array.isArray(orderRows) ? orderRows : []) + .map(row => [ Number(row && row.id || 0), row ])); + const sampleMap = new Map(); + + for (const row of Array.isArray(orderExpressRows) ? orderExpressRows : []) { + const caiNiaoAuthInfoId = Number(row && row.cai_niao_auth_info_id || 0); + const printHistoryId = String(row && row.print_history_id || '').trim(); + if (caiNiaoAuthInfoId <= 0 || !printHistoryId || sampleMap.has(caiNiaoAuthInfoId)) { + continue; + } + + const orderRow = orderRowMap.get(Number(row && row.order_id || 0)) || {}; + sampleMap.set(caiNiaoAuthInfoId, { + caiNiaoAuthInfoId, + printHistoryId, + waybillCode: String(row && row.waybill_code || '').trim(), + storeId: Number(orderRow.store_id || row.store_id || 0), + warehouseId: Number(orderRow.warehouse_id || row.warehouse_id || 0), + fromKey: String(orderRow.from_key || '').trim(), + }); + } + + return sampleMap; + } + + /** + * 解析回 OMS 换打印数据所用的 appKey。 + * + * 优先使用订单建单时的来源应用 `from_key`,缺失时按「货主 + 仓库」反查授权关系下的 ApiApp。 + * + * @param {Object} sample 换取样本。 + * @param {Map} [cache] appKey 缓存(按货主+仓库)。 + * @return {Promise} appKey,取不到返回空字符串。 + */ + async resolveOmsPrintAppKey(sample = {}, cache = new Map()) { + const safeSample = this.isPlainObject(sample) ? sample : {}; + + if (safeSample.fromKey) { + return String(safeSample.fromKey).trim(); + } + + const cacheKey = `${Number(safeSample.storeId) || 0}:${Number(safeSample.warehouseId) || 0}`; + if (cache.has(cacheKey)) { + return cache.get(cacheKey); + } + + const orderAsyncService = this.service + && this.service.systems + && this.service.systems.orderAsync; + let appKey = ''; + if (orderAsyncService && typeof orderAsyncService.resolveOpenApiAppByStore === 'function') { + try { + const appConfig = await orderAsyncService.resolveOpenApiAppByStore( + safeSample.storeId, + safeSample.warehouseId + ); + appKey = String(appConfig && appConfig.appKey || '').trim(); + } catch (error) { + this.ctx.logger.warn('[orderPrint.resolveOmsPrintAppKey] 反查 ApiApp 失败: %s', error.message); + } + } + + cache.set(cacheKey, appKey); + return appKey; + } + + /** + * 调 OMS `deliveryorder.getprintdata` 换取新的抖音打印数据(params)。 + * + * 只读接口,不消耗面单;请求只带一个 printHistoryId,OMS 自行按取号记录回源平台。 + * + * @param {Object} params 入参。 + * @param {string} params.appKey 目标 OMS 应用 appKey。 + * @param {string} params.printHistoryId 打印记录ID。 + * @param {number} params.caiNiaoAuthInfoId 菜鸟授权网点ID(仅用于日志)。 + * @return {Promise<{params: string, template_url: string}|null>} 换取结果,失败返回 null。 + */ + async requestOmsDouyinPrintParams({ appKey = '', printHistoryId = '', caiNiaoAuthInfoId = 0 } = {}) { + const normalizedAppKey = String(appKey || '').trim(); + const normalizedPrintHistoryId = String(printHistoryId || '').trim(); + const callbackService = this.service && this.service.openapi && this.service.openapi.callback; + + if (!normalizedAppKey || !normalizedPrintHistoryId) { + return null; + } + + if (!callbackService || typeof callbackService.sendByAppKey !== 'function') { + this.ctx.logger.warn('[orderPrint.requestOmsDouyinPrintParams] OpenAPI 回调服务不可用,跳过 OMS 换取 params'); + return null; + } + + try { + const result = await callbackService.sendByAppKey({ + appKey: normalizedAppKey, + event: OMS_PRINT_DATA_EVENT, + request: { printHistoryIds: [ normalizedPrintHistoryId ] }, + }); + + if (!result || result.success !== true) { + this.ctx.logger.warn('[orderPrint.requestOmsDouyinPrintParams] OMS 换取打印数据请求失败', { + caiNiaoAuthInfoId, + printHistoryId: normalizedPrintHistoryId, + error: result && result.error ? String(result.error) : '未知错误', + }); + return null; + } + + const responseBody = this.isPlainObject(result.response) ? result.response : {}; + const results = Array.isArray(responseBody.data && responseBody.data.results) + ? responseBody.data.results + : []; + const matched = results.find(item => item && item.success === true && String(item.params || '').trim()) || null; + + if (!matched) { + this.ctx.logger.warn('[orderPrint.requestOmsDouyinPrintParams] OMS 未返回可用 params', { + caiNiaoAuthInfoId, + printHistoryId: normalizedPrintHistoryId, + message: String(results[0] && results[0].message || responseBody.message || '').trim(), + }); + return null; + } + + const params = String(matched.params || '').trim(); + const templateUrl = String(matched.template_url || '').trim(); + this.ctx.logger.info('[orderPrint.requestOmsDouyinPrintParams] OMS 换取 params 成功', { + caiNiaoAuthInfoId, + printHistoryId: normalizedPrintHistoryId, + paramsLength: params.length, + hasTemplateUrl: !!templateUrl, + }); + + return { params, template_url: templateUrl }; + } catch (error) { + this.ctx.logger.warn('[orderPrint.requestOmsDouyinPrintParams] OMS 换取 params 异常: %s', error.message); + return null; + } + } + + /** + * 按店铺换取抖音打印 params。 + * + * 仅处理通过 OMS 取号(有 cai_niao_auth_info_id + print_history_id)的运单; + * 每个店铺只取其中一个 print_history_id 回 OMS 换一次,结果按店铺缓存并共享。 + * + * @param {Array} orderRows 订单行列表。 + * @param {Array} orderExpressRows 运单行列表。 + * @return {Promise>} 授权网点ID → 换取结果。 + */ + async resolveOmsDouyinPrintParamsMap(orderRows = [], orderExpressRows = []) { + const sampleMap = this.buildDouyinOmsParamsSampleMap(orderRows, orderExpressRows); + const paramsMap = new Map(); + if (sampleMap.size === 0) { + return paramsMap; + } + + const appKeyCache = new Map(); + for (const [ caiNiaoAuthInfoId, sample ] of sampleMap.entries()) { + const cacheKey = this.buildOmsDouyinParamsCacheKey(caiNiaoAuthInfoId); + if (cacheKey) { + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (cached && typeof cached === 'object' && String(cached.params || '').trim()) { + paramsMap.set(caiNiaoAuthInfoId, { + params: String(cached.params).trim(), + template_url: String(cached.template_url || '').trim(), + }); + continue; + } + } catch (error) { + this.ctx.logger.warn('[orderPrint.resolveOmsDouyinPrintParamsMap] 读取缓存失败: %s', error.message); + } + } + + const appKey = await this.resolveOmsPrintAppKey(sample, appKeyCache); + if (!appKey) { + this.ctx.logger.warn('[orderPrint.resolveOmsDouyinPrintParamsMap] 未找到回 OMS 的 appKey,跳过换取 params', { + caiNiaoAuthInfoId, + storeId: sample.storeId, + warehouseId: sample.warehouseId, + }); + continue; + } + + const fetched = await this.requestOmsDouyinPrintParams({ + appKey, + printHistoryId: sample.printHistoryId, + caiNiaoAuthInfoId, + }); + if (!fetched) { + continue; + } + + if (cacheKey && this.app && typeof this.app.setCacheAsync === 'function') { + try { + await this.app.setCacheAsync(cacheKey, fetched, OMS_DOUYIN_PARAMS_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[orderPrint.resolveOmsDouyinPrintParamsMap] 写入缓存失败: %s', error.message); + } + } + + paramsMap.set(caiNiaoAuthInfoId, fetched); + } + + return paramsMap; + } + + /** + * 为菜鸟打印订单补齐主面单专用来源字段。 + * + * 仅对打印平台归一化为菜鸟的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。 + * + * @param {Array} orderRows 订单列表。 + * @param {Array} orderExpressRows 快递单列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 补齐后的快递单列表。 + */ + async enrichCainiaoOrderExpressRows(orderRows = [], orderExpressRows = [], warehouseId) { + const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : []; + const normalizedOrderExpressRows = Array.isArray(orderExpressRows) ? orderExpressRows : []; + if (normalizedOrderRows.length === 0 || normalizedOrderExpressRows.length === 0) { + return normalizedOrderExpressRows; + } + + const orderRowMap = new Map(normalizedOrderRows.map(row => [ Number(row && row.id || 0), row ])); + const cainiaoOrderIds = []; + const expressLookupCodes = []; + + for (const row of normalizedOrderExpressRows) { + const orderId = Number(row && row.order_id || 0); + const orderRow = orderRowMap.get(orderId) || {}; + const platformCode = this.resolvePrintPlatformCode(orderRow, row); + if (!this.isCainiaoPlatformCode(platformCode)) { + continue; + } + + cainiaoOrderIds.push(orderId); + expressLookupCodes.push(...this.collectCainiaoExpressLookupCodes(orderRow, row)); + } + + if (cainiaoOrderIds.length === 0) { + return normalizedOrderExpressRows; + } + + let cainiaoCpCodeMap = new Map(); + try { + cainiaoCpCodeMap = await this.queryCainiaoCpCodeMap(expressLookupCodes); + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.enrichCainiaoOrderExpressRows] 查询菜鸟快递编码失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + + let interfaceList = []; + try { + interfaceList = await this.queryCainiaoExpressInterfaceList(warehouseId); + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.enrichCainiaoOrderExpressRows] 查询菜鸟快递接口失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + + const cainiaoOrderIdSet = new Set(cainiaoOrderIds); + return normalizedOrderExpressRows.map(row => { + const orderId = Number(row && row.order_id || 0); + if (!cainiaoOrderIdSet.has(orderId)) { + return row; + } + + const orderRow = orderRowMap.get(orderId) || {}; + const matchedCpCode = this.collectCainiaoExpressLookupCodes(orderRow, row) + .map(code => cainiaoCpCodeMap.get(code) || '') + .find(Boolean) || ''; + const matchedInterface = this.pickCainiaoExpressInterface(interfaceList, orderRow, row); + const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim(); + + if (!matchedCpCode && !matchedTemplateUrl) { + return row; + } + + return { + ...row, + ...(matchedCpCode ? { cainiao_cp_code: matchedCpCode } : {}), + ...(matchedTemplateUrl ? { cainiao_template_url: matchedTemplateUrl } : {}), + }; + }); + } + + /** + * 为京东打印订单补齐主面单模板来源字段。 + * + * 仅对打印平台归一化为京东的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。 + * + * @param {Array} orderRows 订单列表。 + * @param {Array} orderExpressRows 快递单列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 补齐后的快递单列表。 + */ + async enrichJdOrderExpressRows(orderRows = [], orderExpressRows = [], warehouseId) { + const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : []; + const normalizedOrderExpressRows = Array.isArray(orderExpressRows) ? orderExpressRows : []; + if (normalizedOrderRows.length === 0 || normalizedOrderExpressRows.length === 0) { + return normalizedOrderExpressRows; + } + + const orderRowMap = new Map(normalizedOrderRows.map(row => [ Number(row && row.id || 0), row ])); + const jdOrderIds = []; + + for (const row of normalizedOrderExpressRows) { + const orderId = Number(row && row.order_id || 0); + const orderRow = orderRowMap.get(orderId) || {}; + const platformCode = this.resolvePrintPlatformCode(orderRow, row); + if (!this.isJdPlatformCode(platformCode)) { + continue; + } + + jdOrderIds.push(orderId); + } + + if (jdOrderIds.length === 0) { + return normalizedOrderExpressRows; + } + + let interfaceList = []; + try { + interfaceList = await this.queryJdExpressInterfaceList(warehouseId); + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.enrichJdOrderExpressRows] 查询京东快递接口表失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + + if (!Array.isArray(interfaceList) || interfaceList.length === 0) { + return normalizedOrderExpressRows; + } + + const jdOrderIdSet = new Set(jdOrderIds); + return normalizedOrderExpressRows.map(row => { + const orderId = Number(row && row.order_id || 0); + if (!jdOrderIdSet.has(orderId)) { + return row; + } + + const orderRow = orderRowMap.get(orderId) || {}; + const matchedInterface = this.pickJdExpressInterface(interfaceList, orderRow, row); + const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim(); + if (!matchedTemplateUrl) { + return row; + } + + return { + ...row, + jd_template_url: matchedTemplateUrl, + }; + }); + } + + /** + * 为拼多多与抖音打印订单补齐主面单模板来源字段。 + * + * 仅对打印平台归一化为拼多多/抖音的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。 + * + * @param {Array} orderRows 订单列表。 + * @param {Array} orderExpressRows 快递单列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 补齐后的快递单列表。 + */ + async enrichPddDyOrderExpressRows(orderRows = [], orderExpressRows = [], warehouseId) { + const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : []; + const normalizedOrderExpressRows = Array.isArray(orderExpressRows) ? orderExpressRows : []; + if (normalizedOrderRows.length === 0 || normalizedOrderExpressRows.length === 0) { + return normalizedOrderExpressRows; + } + + const orderRowMap = new Map(normalizedOrderRows.map(row => [ Number(row && row.id || 0), row ])); + const pddOrderIds = []; + const douyinOrderIds = []; + + for (const row of normalizedOrderExpressRows) { + const orderId = Number(row && row.order_id || 0); + const orderRow = orderRowMap.get(orderId) || {}; + const platformCode = this.resolvePrintPlatformCode(orderRow, row); + if (this.isPddPlatformCode(platformCode)) { + pddOrderIds.push(orderId); + continue; + } + + if (this.isDouyinPlatformCode(platformCode)) { + douyinOrderIds.push(orderId); + } + } + + if (pddOrderIds.length === 0 && douyinOrderIds.length === 0) { + return normalizedOrderExpressRows; + } + + this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 分支入口', { + douyinOrderCount: douyinOrderIds.length, + douyinOrderIds: douyinOrderIds.slice(0, 10), + }); + + let pddInterfaceList = []; + if (pddOrderIds.length > 0) { + try { + pddInterfaceList = await this.queryPddExpressInterfaceList(warehouseId); + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.enrichPddDyOrderExpressRows] 查询拼多多快递接口表失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + } + + let douyinInterfaceList = []; + if (douyinOrderIds.length > 0) { + try { + douyinInterfaceList = await this.queryDouyinExpressInterfaceList(warehouseId); + this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 接口列表查询结果', { + interfaceCount: douyinInterfaceList.length, + }); + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.enrichPddDyOrderExpressRows] 查询抖音快递接口表失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + } + + const pddOrderIdSet = new Set(pddOrderIds); + const douyinOrderIdSet = new Set(douyinOrderIds); + const douyinParamsInflightMap = new Map(); + // OMS 取号的抖音单:按 cai_niao_auth_info_id(店铺)分组,每组只换一次 params + const omsDouyinParamsMap = douyinOrderIds.length > 0 + ? await this.resolveOmsDouyinPrintParamsMap(normalizedOrderRows, normalizedOrderExpressRows) + : new Map(); + return Promise.all(normalizedOrderExpressRows.map(async row => { + const orderId = Number(row && row.order_id || 0); + const orderRow = orderRowMap.get(orderId) || {}; + + if (pddOrderIdSet.has(orderId)) { + const matchedInterface = this.pickPddExpressInterface(pddInterfaceList, orderRow, row); + const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim(); + if (!matchedTemplateUrl) { + return row; + } + + return { + ...row, + pdd_template_url: matchedTemplateUrl, + }; + } + + if (douyinOrderIdSet.has(orderId)) { + const resolvedInterface = this.resolveDouyinExpressInterface(douyinInterfaceList, orderRow, row); + const matchedInterface = resolvedInterface.interfaceRow; + const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim(); + const caiNiaoAuthInfoId = Number(row && row.cai_niao_auth_info_id || 0); + const omsDouyinParams = caiNiaoAuthInfoId > 0 ? omsDouyinParamsMap.get(caiNiaoAuthInfoId) : null; + + // OMS 取号的抖音单:params 与模板地址都以 OMS 换取的为准,同店铺共用一份 + if (omsDouyinParams && omsDouyinParams.params) { + this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 使用 OMS 换取 params', { + orderId, + caiNiaoAuthInfoId, + printHistoryId: String(row && row.print_history_id || '').trim(), + hasOmsTemplateUrl: !!omsDouyinParams.template_url, + }); + return { + ...row, + dy_template_url: String(omsDouyinParams.template_url || matchedTemplateUrl || '').trim(), + dy_params: omsDouyinParams.params, + }; + } + + this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 单笔匹配结果', { + orderId, + logisticsInterfaceId: Number(row && row.logistics_interface_id || 0), + matchedInterfaceId: Number(matchedInterface && matchedInterface.id || 0), + matchedShopId: Number(matchedInterface && matchedInterface.shop_id || 0), + matchedBy: resolvedInterface.matchedBy, + hasMatchedInterface: !!matchedInterface, + matchedTemplateUrl, + sysLogisticsCode: orderRow.sys_logistics_code, + logisticsCode: row.logistics_code, + }); + if (!matchedTemplateUrl) { + if (!matchedInterface) { + this.ctx.logger.warn('[enrichPddDyOrderExpressRows] 未匹配到抖音快递接口,跳过临时 key 获取', { + orderId, + logisticsInterfaceId: Number(row && row.logistics_interface_id || 0), + matchedBy: resolvedInterface.matchedBy, + }); + } + return row; + } + + // 临时 key 按取号店铺维度获取与缓存,避免多店铺之间串用 + const dyParams = await this.getDouyinPrintParams(matchedInterface, douyinParamsInflightMap); + + return { + ...row, + dy_template_url: matchedTemplateUrl, + dy_params: dyParams, + }; + } + + return row; + })); + } + + /** + * 获取波次订单对应货主的签约策略映射。 + * + * @param {Array} orderRows 订单行。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 货主策略映射。 + */ + async getPolicyConfigMapByStore(orderRows = [], warehouseId) { + const storeIds = Array.from(new Set(orderRows + .map(row => Number(row && row.store_id || 0)) + .filter(storeId => Number.isInteger(storeId) && storeId > 0))); + const policyMap = new Map(); + + if (storeIds.length === 0) { + return policyMap; + } + + const storeWarehouseService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.storeWarehouse; + if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') { + return policyMap; + } + + await Promise.all(storeIds.map(async storeId => { + try { + const contractConfig = await storeWarehouseService.getContractConfig(warehouseId, storeId); + const policyConfig = this.normalizeContractPolicyConfig(contractConfig && contractConfig.policy_config); + policyMap.set(storeId, policyConfig); + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.getPolicyConfigMapByStore] 读取签约策略失败 warehouseId=${warehouseId} storeId=${storeId} message=${error.message}` + ); + policyMap.set(storeId, {}); + } + })); + + return policyMap; + } + + /** + * 解析订单平台编码,保留原始平台值(仅去首尾空白)。 + * + * @param {Object} orderRow 订单行。 + * @param {Object} orderExpress 快递行。 + * @return {string} 打印平台编码。 + */ + resolvePrintPlatformCode(orderRow = {}, orderExpress = {}) { + const candidates = [ + orderExpress && orderExpress.platform_code, + orderRow && orderRow.sys_platform_code, + orderRow && orderRow.source_platform_code, + ]; + + for (const candidate of candidates) { + const rawCandidate = String(candidate || '').trim(); + if (!rawCandidate) { + continue; + } + + return rawCandidate; + } + + return ''; + } + + /** + * 按平台加载打印模板样例。 + * + * @param {string} platformCode 平台编码。 + * @param {Map} cache 模板缓存。 + * @return {Object} 模板样例对象。 + */ + loadTemplateSampleByPlatform(platformCode, cache) { + const normalized = PrinterDataBuilder.normalizePlatformAlias(platformCode); + const cacheKey = normalized.meta && normalized.meta.template_file + ? normalized.meta.template_file + : `platform:${normalized.platform || 'unknown'}`; + if (cache.has(cacheKey)) { + return cache.get(cacheKey); + } + + if (!normalized.meta || !normalized.meta.template_file) { + cache.set(cacheKey, {}); + return {}; + } + + const templatePath = path.join(this.app.baseDir, 'printer_data_template', normalized.meta.template_file); + try { + const fileContent = fs.readFileSync(templatePath, 'utf8'); + const parsedTemplate = JSON.parse(fileContent); + const templateSample = this.isPlainObject(parsedTemplate) ? parsedTemplate : {}; + cache.set(cacheKey, templateSample); + return templateSample; + } catch (error) { + this.ctx.logger.warn(`[orderPrint.loadTemplateSampleByPlatform] 模板读取失败 template=${templatePath} message=${error.message}`); + cache.set(cacheKey, {}); + return {}; + } + } + + /** + * 组装单订单平台打印中间态结果。 + * + * @param {Object} payload 聚合入参。 + * @param {Object} payload.orderRow 订单行。 + * @param {Object} payload.orderExpress 快递行。 + * @param {Object} payload.policyConfig 策略配置。 + * @param {string} payload.platformCode 平台编码。 + * @param {Object} payload.templateSample 模板样例。 + * @return {Promise} 逐单打印中间态。 + */ + async buildOrderPlatformPrintItem(payload = {}) { + const requestPayload = this.isPlainObject(payload) ? payload : {}; + const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {}; + const orderExpress = this.isPlainObject(requestPayload.orderExpress) ? requestPayload.orderExpress : {}; + const policyConfig = this.isPlainObject(requestPayload.policyConfig) ? requestPayload.policyConfig : {}; + const templateSample = this.isPlainObject(requestPayload.templateSample) ? requestPayload.templateSample : {}; + const platformCode = String(requestPayload.platformCode || '').trim(); + const extraCustomLines = Array.isArray(requestPayload.extraCustomLines) ? requestPayload.extraCustomLines : []; + + // 查最匹配的包材名称(基于 items_hash) + let suggestedPackageMaterialName = ''; + const itemsHash = String(orderRow.items_hash || '').trim(); + const itemsCrc = Number(orderRow.items_crc || 0); + if (itemsHash) { + const relationModel = this.ctx.model && this.ctx.model.PackageMaterialItemRelation; + if (relationModel) { + const topMatch = await relationModel.findOne({ + where: { + warehouse_id: Number(orderRow.warehouse_id || 0), + items_hash: itemsHash, + items_crc: itemsCrc, + is_active: 1, + delete_at: null, + }, + order: [[ 'bind_count', 'DESC' ]], + attributes: [ 'package_material_name' ], + raw: true, + }); + if (topMatch && topMatch.package_material_name) { + suggestedPackageMaterialName = String(topMatch.package_material_name).trim(); + } + } + } + + const orderId = Number(orderRow.id || 0); + const waveId = Number(orderRow.wave_id || 0); + const requestId = `wave_${waveId}_order_${orderId}`; + const waybillCode = String(orderExpress.waybill_code || '').trim(); + const orderSysLogisticsCode = String(orderRow.sys_logistics_code || '').trim(); + const orderSysLogisticsName = String(orderRow.sys_logistics_name || '').trim(); + const expressSysLogisticsCode = String(orderExpress.sys_logistics_code || '').trim(); + const expressSysLogisticsName = String(orderExpress.sys_logistics_name || '').trim(); + const documentId = waybillCode || `doc_${orderId}`; + + // 查询仓库 subject_config 用于发件人兜底 + const warehouseId = Number(orderRow.warehouse_id || 0); + let subjectConfig = {}; + if (warehouseId > 0) { + const storeRow = await this.ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'subject_config' ], + raw: true, + }); + if (storeRow && storeRow.subject_config) { + subjectConfig = this.isPlainObject(storeRow.subject_config) + ? storeRow.subject_config + : {}; + } + } + + const printPayload = PrinterDataBuilder.buildPlatformRequestSkeleton({ + platform: platformCode, + order_express: orderExpress, + order_delivery: orderRow, + store_contract: { + policy_config: policyConfig, + }, + policy_config: policyConfig, + subject_config: subjectConfig, + template_sample: templateSample, + options: { + requestId, + taskId: requestId, + documentId, + packageMaterialName: suggestedPackageMaterialName, + extraCustomLines, + customAreaBaseUrl: this.ctx.app.config.customAreaBaseUrl || '', + }, + }); + const printData = this.extractSinglePlatformPrintData(printPayload); + // 子面单场景:同一运单号可能对应多个 business_key,注入 business_key 到返回文档中供调用方区分 + if (printData && typeof printData === 'object' && !Array.isArray(printData)) { + const expressBusinessKey = Number(orderExpress.business_key || 1); + if (expressBusinessKey > 1) { + printData.business_key = expressBusinessKey; + } + } + return { + wave_id: waveId, + wave_no: String(orderRow.wave_no || '').trim(), + order_id: orderId, + order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(), + store_id: Number(orderRow.store_id || 0), + warehouse_id: Number(orderRow.warehouse_id || 0), + platform: platformCode, + platform_name: printPayload.platform_meta && printPayload.platform_meta.name + ? String(printPayload.platform_meta.name).trim() + : '', + sys_logistics_code: orderSysLogisticsCode || expressSysLogisticsCode, + sys_logistics_name: orderSysLogisticsName || expressSysLogisticsName, + waybill_code: String(orderExpress.waybill_code || '').trim(), + print_data: printData, + }; + } + + /** + * 提取单个打印文档对象。 + * + * @param {Object} printPayload 打印载荷。 + * @return {Object} 单个文档对象;未命中时返回空对象。 + */ + extractSinglePlatformPrintData(printPayload = {}) { + const requestSkeleton = this.isPlainObject(printPayload) + ? printPayload.request_skeleton + : null; + if (!this.isPlainObject(requestSkeleton)) { + return {}; + } + + const taskDocuments = requestSkeleton.task && Array.isArray(requestSkeleton.task.documents) + ? requestSkeleton.task.documents + : []; + if (taskDocuments.length > 0 && this.isPlainObject(taskDocuments[0])) { + return taskDocuments[0]; + } + + if (Array.isArray(requestSkeleton.documents) && this.isPlainObject(requestSkeleton.documents[0])) { + return requestSkeleton.documents[0]; + } + + const taskListEntry = Array.isArray(requestSkeleton.taskList) + ? requestSkeleton.taskList.find(item => Array.isArray(item && item.documents) && item.documents.length > 0) + : null; + if (taskListEntry && this.isPlainObject(taskListEntry.documents[0])) { + return taskListEntry.documents[0]; + } + + if (Array.isArray(requestSkeleton.taskList) && this.isPlainObject(requestSkeleton.taskList[0])) { + return requestSkeleton.taskList[0]; + } + + return {}; + } + + /** + * 将逐单打印中间态按平台分组。 + * + * @param {Array} orderPrintList 逐单打印中间态列表。 + * @return {Array} 平台分组列表。 + */ + groupOrderPrintItemsByPlatform(orderPrintList = []) { + const groupedPlatformMap = new Map(); + + for (const item of orderPrintList) { + const platform = String(item && item.platform || '').trim() || 'unknown'; + const group = groupedPlatformMap.get(platform) || { + platform, + platform_name: String(item && item.platform_name || '').trim(), + order_count: 0, + orders: [], + }; + + group.orders.push(this.isPlainObject(item && item.print_data) ? item.print_data : {}); + group.order_count = group.orders.length; + groupedPlatformMap.set(platform, group); + } + + const groups = Array.from(groupedPlatformMap.values()); + groups.sort((a, b) => String(a.platform || '').localeCompare(String(b.platform || ''))); + return groups; + } + + /** + * 将逐单打印中间态按波次分组,并在波次内按平台+系统快递分组。 + * + * @param {Object} payload 聚合输入。 + * @param {Array} payload.waveRows 波次元数据列表。 + * @param {Array} payload.hitWaveIds 命中的波次ID数组(已过滤)。 + * @param {Array} payload.orderPrintList 逐单打印中间态列表。 + * @return {Array} 波次平台分组结果(platforms 为扁平平台+系统快递项)。 + */ + groupOrderPrintItemsByWaveAndPlatform(payload = {}) { + const { + waveRows = [], + hitWaveIds = [], + orderPrintList = [], + } = this.isPlainObject(payload) ? payload : {}; + + const waveMetaMap = new Map(); + for (const row of waveRows) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + waveMetaMap.set(waveId, { + wave_id: waveId, + wave_no: String(row && row.wave_no || '').trim(), + }); + } + + const waveGroupMap = new Map(); + const wavePlatformMap = new Map(); + for (const waveId of hitWaveIds) { + const normalizedWaveId = Number(waveId); + if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) { + continue; + } + + const waveMeta = waveMetaMap.get(normalizedWaveId) || { + wave_id: normalizedWaveId, + wave_no: '', + }; + waveGroupMap.set(normalizedWaveId, { + wave_id: waveMeta.wave_id, + wave_no: waveMeta.wave_no, + order_count: 0, + platforms: [], + }); + wavePlatformMap.set(normalizedWaveId, new Map()); + } + + for (const item of orderPrintList) { + const waveId = Number(item && item.wave_id || 0); + const waveGroup = waveGroupMap.get(waveId); + if (!waveGroup) { + continue; + } + + const platform = String(item && item.platform || '').trim() || 'unknown'; + const normalizedSysLogisticsCode = String(item && item.sys_logistics_code || '').trim(); + const normalizedSysLogisticsName = String(item && item.sys_logistics_name || '').trim(); + const normalizedSysLogisticsIdentity = normalizedSysLogisticsCode || normalizedSysLogisticsName || 'unknown'; + const platformSysKey = `${platform}@@${normalizedSysLogisticsIdentity}`; + const platformMap = wavePlatformMap.get(waveId) || new Map(); + const platformGroup = platformMap.get(platformSysKey) || { + platform, + platform_name: String(item && item.platform_name || '').trim(), + sys_logistics_code: normalizedSysLogisticsCode || 'unknown', + sys_logistics_name: normalizedSysLogisticsName || 'unknown', + order_count: 0, + order_ids: [], + orders: [], + }; + + const orderId = Number(item && item.order_id || 0); + if (Number.isInteger(orderId) && orderId > 0) { + platformGroup.order_ids.push(orderId); + } + platformGroup.orders.push(this.isPlainObject(item && item.print_data) ? item.print_data : {}); + platformGroup.order_ids = Array.from(new Set(platformGroup.order_ids)); + platformGroup.order_count = platformGroup.orders.length; + + platformMap.set(platformSysKey, platformGroup); + wavePlatformMap.set(waveId, platformMap); + } + + const waveGroups = Array.from(waveGroupMap.values()); + for (const waveGroup of waveGroups) { + const platformMap = wavePlatformMap.get(Number(waveGroup.wave_id)) || new Map(); + const platforms = Array.from(platformMap.values()); + platforms.sort((a, b) => { + const platformCompare = String(a.platform || '').localeCompare(String(b.platform || '')); + if (platformCompare !== 0) { + return platformCompare; + } + + const sysCodeCompare = String(a.sys_logistics_code || '').localeCompare(String(b.sys_logistics_code || '')); + if (sysCodeCompare !== 0) { + return sysCodeCompare; + } + + return String(a.sys_logistics_name || '').localeCompare(String(b.sys_logistics_name || '')); + }); + waveGroup.platforms = platforms; + waveGroup.order_count = platforms.reduce((sum, platformGroup) => { + return sum + Number(platformGroup && platformGroup.order_count || 0); + }, 0); + } + + waveGroups.sort((a, b) => { + const waveNoCompare = String(a.wave_no || '').localeCompare(String(b.wave_no || '')); + if (waveNoCompare !== 0) { + return waveNoCompare; + } + + return Number(a.wave_id || 0) - Number(b.wave_id || 0); + }); + + return waveGroups; + } + + /** + * 过滤快递未完全分配的波次。 + * + * 规则:仅当波次下全部订单的 post_status 都为 fin 时,才视为快递已完全分配。 + * + * @param {Array} hitWaveIds 命中的波次ID数组。 + * @param {Array} orderRows 波次订单列表。 + * @return {{ validWaveIds: Array, filteredWaveIds: Array }} 过滤结果。 + */ + filterFullyAssignedExpressWaves(hitWaveIds = [], orderRows = []) { + const statsMap = new Map(); + for (const waveId of hitWaveIds) { + statsMap.set(Number(waveId), { + total: 0, + fin: 0, + }); + } + + for (const row of orderRows) { + const waveId = Number(row && row.wave_id || 0); + const stats = statsMap.get(waveId); + if (!stats) { + continue; + } + + const postStatus = String(row && row.post_status || '').trim(); + stats.total += 1; + if (postStatus === 'fin') { + stats.fin += 1; + } + } + + const validWaveIds = []; + const filteredWaveIds = []; + for (const waveId of hitWaveIds) { + const stats = statsMap.get(waveId) || { total: 0, fin: 0 }; + const isFullyAssigned = stats.total > 0 && stats.fin === stats.total; + if (isFullyAssigned) { + validWaveIds.push(waveId); + } else { + filteredWaveIds.push({ + wave_id: waveId, + reason: '快递未完全分配', + }); + } + } + + return { + validWaveIds, + filteredWaveIds, + }; + } + +} + +module.exports = OrderPrintSystemService; diff --git a/app/service/systems/order_review.js b/app/service/systems/order_review.js new file mode 100644 index 0000000..923754a --- /dev/null +++ b/app/service/systems/order_review.js @@ -0,0 +1,495 @@ +'use strict'; + +const OrderBaseService = require('../systemMethods/order/base'); + +/** + * 订单复核数据聚合服务。 + * + * 负责根据运单号反查订单,并输出复核最小数据集。 + */ +class OrderReviewService extends OrderBaseService { + /** + * 创建带业务错误码的异常对象。 + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 规范化运单号。 + * @param {string} waybillCode 运单号。 + * @return {string} 规范化后的运单号。 + */ + normalizeWaybillCode(waybillCode) { + const normalizedWaybillCode = String(waybillCode || '').trim(); + if (!normalizedWaybillCode) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedWaybillCode; + } + + /** + * 判断是否为锁定状态。 + * @param {string} lockStatus 锁定状态。 + * @return {boolean} 是否锁定。 + */ + isLockedStatus(lockStatus) { + return String(lockStatus || '').trim() !== 'none'; + } + + /** + * 判断是否为拦截状态(除 none 外一律视为已拦截)。 + * @param {string} interceptStatus 拦截状态。 + * @return {boolean} 是否拦截。 + */ + isInterceptStatus(interceptStatus) { + return this.isInterceptedOrderStatus(interceptStatus); + } + + /** + * 将模型记录转换为普通对象。 + * @param {*} record 模型记录。 + * @return {Object|null} 普通对象。 + */ + toPlainRecord(record) { + if (!record) { + return null; + } + + if (typeof record.get === 'function') { + return record.get({ plain: true }); + } + + return record; + } + + /** + * 解析订单商品快照。 + * @param {*} itemSnapshot 商品快照字段。 + * @return {Object} 解析后的快照对象。 + */ + parseItemSnapshot(itemSnapshot) { + if (!itemSnapshot) { + return {}; + } + + if (typeof itemSnapshot === 'object') { + return itemSnapshot; + } + + if (typeof itemSnapshot === 'string') { + try { + const parsed = JSON.parse(itemSnapshot); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch (error) { + return {}; + } + } + + return {}; + } + + /** + * 根据运单号读取有效快递记录。 + * @param {string} waybillCode 运单号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 快递记录。 + */ + async findOrderExpressByWaybill(waybillCode, warehouseId) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('订单快递模型未初始化', 500); + } + + const expressRow = await orderExpressModel.findOne({ + where: { + waybill_code: waybillCode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (!expressRow) { + throw this.createBusinessError('运单不存在', 404); + } + + return expressRow; + } + + /** + * 根据订单ID读取订单头。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 订单头。 + */ + async findOrderById(orderId, warehouseId) { + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + + const orderRow = await orderModel.findOne({ + where: orderWhere, + attributes: [ + 'id', + 'warehouse_id', + 'wave_id', + 'wave_no', + 'items_weight', + 'packages_weight', + 'items_total', + 'items_count', + 'lock_status', + 'intercept_status', + ], + raw: true, + }); + + if (!orderRow) { + throw this.createBusinessError('订单不存在', 404); + } + + return orderRow; + } + + /** + * 读取订单明细。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 明细列表。 + */ + async findOrderItems(orderId, warehouseId) { + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const rows = await orderItemsModel.findAll({ + where: { + order_id: orderId, + }, + attributes: [ + 'id', + 'order_id', + 'item_id', + 'item_code', + 'item_name', + 'plan_qty', + 'stock_id', + 'item_snapshot', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 批量读取商品条码映射。 + * @param {number[]} stockIds 商品ID列表。 + * @return {Promise>} 条码映射。 + */ + async loadBarcodesByStockIds(stockIds = []) { + const uniqueStockIds = Array.from(new Set((Array.isArray(stockIds) ? stockIds : []) + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0))); + const barcodeMap = new Map(); + + if (uniqueStockIds.length === 0) { + return barcodeMap; + } + + const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode; + if (!stockBarcodeModel || typeof stockBarcodeModel.findAll !== 'function') { + return barcodeMap; + } + + const barcodeRows = await stockBarcodeModel.findAll({ + where: { + stock_id: { + [this.app.Sequelize.Op.in]: uniqueStockIds, + }, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + + for (const item of Array.isArray(barcodeRows) ? barcodeRows : []) { + const stockId = Number(item && item.stock_id || 0); + const barcode = String(item && item.barcode || '').trim(); + + if (!stockId || !barcode) { + continue; + } + + if (!barcodeMap.has(stockId)) { + barcodeMap.set(stockId, []); + } + + barcodeMap.get(stockId).push(barcode); + } + + return barcodeMap; + } + + /** + * 批量读取商品图片映射。 + * @param {number[]} stockIds 商品ID列表。 + * @return {Promise>} 图片映射。 + */ + async loadImagesByStockIds(stockIds = []) { + const uniqueStockIds = Array.from(new Set((Array.isArray(stockIds) ? stockIds : []) + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0))); + const imageMap = new Map(); + + if (uniqueStockIds.length === 0) { + return imageMap; + } + + const fileReferenceModel = this.ctx.model && this.ctx.model.FileReference; + const fileModel = this.ctx.model && this.ctx.model.File; + + if (!fileReferenceModel || typeof fileReferenceModel.findAll !== 'function' || !fileModel) { + return imageMap; + } + + const imageRows = await fileReferenceModel.findAll({ + where: { + business_type: 'stock', + business_id: { + [this.app.Sequelize.Op.in]: uniqueStockIds, + }, + }, + include: [{ + model: fileModel, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + }); + + for (const item of Array.isArray(imageRows) ? imageRows : []) { + const row = this.toPlainRecord(item); + const stockId = Number(row && row.business_id || 0); + const imageUrl = String( + row && row.file && row.file.file_url + || row && row.file_url + || row && row.url + || row && row.file_path + || '' + ).trim(); + + if (!stockId || !imageUrl) { + continue; + } + + if (!imageMap.has(stockId)) { + imageMap.set(stockId, []); + } + + imageMap.get(stockId).push(imageUrl); + } + + return imageMap; + } + + /** + * 查询波次信息。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 波次信息。 + */ + async findWaveById(waveId, warehouseId) { + const normalizedWaveId = Number(waveId || 0); + if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) { + return null; + } + + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') { + return null; + } + + return await waveBatchModel.findOne({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + } + + /** + * 读取团购波次拦截列表。 + * @param {Object} order 当前命中订单。 + * @return {Promise} 拦截列表。 + */ + async buildGroupInterceptList(order = {}) { + const waveId = Number(order && order.wave_id || 0); + const warehouseId = Number(order && order.warehouse_id || 0); + + if (!waveId || !warehouseId) { + return []; + } + + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const interceptRows = await orderModel.findAll({ + where: { + wave_id: waveId, + warehouse_id: warehouseId, + intercept_status: { + [this.app.Sequelize.Op.ne]: 'none', + }, + }, + attributes: [ 'id', 'intercept_status', 'lock_status' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const normalizedRows = Array.isArray(interceptRows) ? interceptRows : []; + if (normalizedRows.length === 0) { + return []; + } + + const orderIds = normalizedRows + .map(item => Number(item && item.id || 0)) + .filter(item => Number.isFinite(item) && item > 0); + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + let waybillRows = []; + if (orderExpressModel && typeof orderExpressModel.findAll === 'function' && orderIds.length > 0) { + waybillRows = await orderExpressModel.findAll({ + where: { + order_id: { + [this.app.Sequelize.Op.in]: orderIds, + }, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'order_id', 'waybill_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + } + + const firstWaybillMap = new Map(); + for (const row of Array.isArray(waybillRows) ? waybillRows : []) { + const orderId = Number(row && row.order_id || 0); + const waybillCode = String(row && row.waybill_code || '').trim(); + if (!orderId || !waybillCode || firstWaybillMap.has(orderId)) { + continue; + } + + firstWaybillMap.set(orderId, waybillCode); + } + + return normalizedRows.map(item => { + const orderId = Number(item && item.id || 0); + return { + order_id: orderId, + waybill_code: firstWaybillMap.get(orderId) || null, + intercept_status: String(item && item.intercept_status || '').trim() || 'none', + lock_status: String(item && item.lock_status || '').trim() || 'none', + }; + }); + } + + /** + * 根据运单号拉取复核最小数据集。 + * @param {Object} payload 入参。 + * @param {string} payload.waybillCode 运单号。 + * @return {Promise} 复核数据。 + */ + async pullReviewDataByWaybill(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { waybillCode } = requestData; + + const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); + const warehouseId = Number(this.getWarehouseId() || 0); + if (!warehouseId) { + throw this.createBusinessError('参数错误', 400); + } + + const expressRow = await this.findOrderExpressByWaybill(normalizedWaybillCode, warehouseId); + const orderId = Number(expressRow && expressRow.order_id || 0); + if (!orderId) { + throw this.createBusinessError('订单不存在', 404); + } + + const orderRow = await this.findOrderById(orderId, warehouseId); + const itemRows = await this.findOrderItems(orderId, warehouseId); + const stockIds = itemRows + .map(item => Number(item && item.stock_id || 0)) + .filter(item => Number.isFinite(item) && item > 0); + const barcodeMap = await this.loadBarcodesByStockIds(stockIds); + const imageMap = await this.loadImagesByStockIds(stockIds); + + const details = itemRows.map(item => { + const snapshot = this.parseItemSnapshot(item && item.item_snapshot); + const stockId = Number(item && item.stock_id || 0); + const barcodes = barcodeMap.get(stockId) || []; + const images = imageMap.get(stockId) || []; + + return { + order_item_id: Number(item && item.id || 0), + item_id: Number(item && item.item_id || 0) || null, + stock_id: stockId || null, + sku_code: String(item && item.item_code || snapshot.item_code || '').trim() || null, + item_name: String(item && item.item_name || snapshot.item_name || '').trim() || null, + should_review_qty: Number(item && item.plan_qty || 0), + image: images[0] || null, + images, + barcode: barcodes[0] || null, + barcodes, + }; + }); + + const lockStatus = String(orderRow && orderRow.lock_status || '').trim() || 'none'; + const interceptStatus = String(orderRow && orderRow.intercept_status || '').trim() || 'none'; + const warnings = []; + if (this.isLockedStatus(lockStatus)) { + warnings.push('订单处于锁定状态,请确认后再复核'); + } + if (this.isInterceptStatus(interceptStatus)) { + warnings.push('订单处于拦截状态,请先处理拦截'); + } + + const waveRow = await this.findWaveById(orderRow && orderRow.wave_id, warehouseId); + const isGroupOrder = Number(waveRow && waveRow.wave_type || 0) === 1; + const interceptList = isGroupOrder + ? await this.buildGroupInterceptList(orderRow) + : []; + + const totalPieceCount = Number(orderRow && orderRow.items_total || 0); + const totalSkuCount = Number(orderRow && orderRow.items_count || 0); + const fallbackSkuCount = details.reduce((count, item) => { + const skuCode = String(item && item.sku_code || '').trim(); + return skuCode ? count + 1 : count; + }, 0); + const fallbackPieceCount = details.reduce((count, item) => count + Number(item && item.should_review_qty || 0), 0); + + return { + order_id: Number(orderRow && orderRow.id || 0), + waybill_code: String(expressRow && expressRow.waybill_code || normalizedWaybillCode).trim(), + wave_no: String(orderRow && orderRow.wave_no || '').trim() || null, + total_weight: orderRow && orderRow.items_weight != null ? Number(orderRow.items_weight) : null, + packages_weight: orderRow && orderRow.packages_weight != null ? Number(orderRow.packages_weight) : null, + total_piece_count: totalPieceCount > 0 ? totalPieceCount : fallbackPieceCount, + total_sku_count: totalSkuCount > 0 ? totalSkuCount : fallbackSkuCount, + lock_status: lockStatus, + intercept_status: interceptStatus, + is_group_order: isGroupOrder, + warnings, + intercept_list: interceptList, + details, + }; + } +} + +module.exports = OrderReviewService; diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js new file mode 100644 index 0000000..b40734c --- /dev/null +++ b/app/service/systems/order_storage_allocation.js @@ -0,0 +1,3482 @@ +'use strict'; + +const MainService = require('../main'); + +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); +const { isLockedOrderStatus } = require('../../lib/lock_guard'); + +const STORAGE_STATUS_FIN = 'fin'; +const STORAGE_STATUS_ERROR = 'error'; +const ORDER_STATUS_CANCEL = 'cancel'; +const ORDER_STEP_EXCEPTION = 3; +const ALLOCATION_LOG_SAMPLE_LIMIT = 20; +/** SN 状态中代表「已随订单发出」的集合(复核提交后写入 VERIFIED) */ +const SN_SHIPPED_STATUS_SET = new Set([ 'VERIFIED', 'REISSUED' ]); + +/** + * 规范化块状日志的输出值。 + * + * @param {unknown} payload 日志载荷。 + * @param {WeakSet} [seen] 循环引用跟踪集。 + * @return {unknown} 规范化后的值。 + */ +function normalizeAllocationLogPayload(payload, seen = new WeakSet()) { + if (payload instanceof Error) { + return { + name: payload.name, + message: payload.message, + stack: payload.stack, + }; + } + + if (payload === null || typeof payload !== 'object') { + if (typeof payload === 'bigint') { + return payload.toString(); + } + + return payload; + } + + if (payload instanceof Date) { + return payload.toISOString(); + } + + if (seen.has(payload)) { + return '[Circular]'; + } + + seen.add(payload); + + if (Array.isArray(payload)) { + return payload.map(item => normalizeAllocationLogPayload(item, seen)); + } + + const normalized = {}; + for (const [ key, value ] of Object.entries(payload)) { + normalized[key] = normalizeAllocationLogPayload(value, seen); + } + + return normalized; +} + +/** + * 格式化块状日志文本。 + * + * @param {string} title 日志标题。 + * @param {unknown} payload 日志载荷。 + * @return {string} 块状日志文本。 + */ +function formatAllocationLogBlock(title, payload) { + const normalizedPayload = normalizeAllocationLogPayload(payload); + let payloadText; + + if (typeof normalizedPayload === 'string') { + payloadText = normalizedPayload; + } else { + try { + const stringifiedPayload = JSON.stringify(normalizedPayload, null, 2); + payloadText = stringifiedPayload === undefined ? String(payload) : stringifiedPayload; + } catch (error) { + payloadText = JSON.stringify({ + message: error.message, + originalPayload: String(payload), + }, null, 2); + } + } + + return [ + '==============', + `时间:${Date.now()}`, + String(title || ''), + payloadText, + '==============', + ].join('\n'); +} + +/** + * 输出块状文本日志。 + * + * @param {string} title 日志标题。 + * @param {unknown} payload 日志载荷。 + * @return {void} + */ +function writeAllocationTextLog(title, payload) { + process.stdout.write(`${formatAllocationLogBlock(title, payload)}\n`); +} + +/** + * 生成数组日志摘要,避免输出全量数据。 + * + * @param {Array} list 原始数组。 + * @param {number} [limit=ALLOCATION_LOG_SAMPLE_LIMIT] 采样数量上限。 + * @return {{count: number, sample: Array}} 摘要信息。 + */ +function summarizeArrayForLog(list, limit = ALLOCATION_LOG_SAMPLE_LIMIT) { + const normalizedList = Array.isArray(list) ? list : []; + + return { + count: normalizedList.length, + sample: normalizedList.slice(0, limit), + }; +} + +/** + * 将输入值规范化为布尔值。 + * + * @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 {number|string} stockId 库存 ID。 + * @param {Array} storageRows 储位库存列表。 + * @return {Object} 储位库存摘要。 + */ +function summarizeStorageRows(stockId, storageRows = []) { + const rows = Array.isArray(storageRows) ? storageRows : []; + const firstRow = rows[0] || {}; + + return { + stock_id: Number(stockId) || 0, + rowCount: rows.length, + availableQuantityTotal: rows.reduce((sum, row) => sum + toNumber(row.available_quantity, 0), 0), + enabledCount: rows.filter(row => normalizeBooleanFlag(row.is_enabled, true)).length, + firstStorageId: Number(firstRow.id) || 0, + firstSpaceId: Number(firstRow.space_id) || 0, + }; +} + +/** + * 对可分配库存按优先级排序。 + * + * @param {Object} left 左侧库存。 + * @param {Object} right 右侧库存。 + * @return {number} 排序结果。 + */ +function compareStorageRows(left, right) { + 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); +} + +/** + * 判断库存行是否属于可参与本次分配的库位。 + * + * 允许存储储位(allowStorageSpace=true)时不限制库位类型; + * 否则仅库位类型同时满足「允许分配(allow_allocation=1)」且「已启用(is_active=1)」的库存行可参与分配。 + * + * @param {Object} storageRow 库存行。 + * @param {boolean} allowStorageSpace 是否允许存储储位参与分配。 + * @return {boolean} 是否可参与分配。 + */ +function isAllocatableStorageRow(storageRow, allowStorageSpace) { + if (allowStorageSpace) { + return true; + } + + const locationType = storageRow && storageRow.locationType ? storageRow.locationType : {}; + return toNumber(locationType.allow_allocation, 0) === 1 + && toNumber(locationType.is_active, 0) === 1; +} + +/** + * 生成库位类型限制导致的缺货原因文本。 + * + * @param {Object} diagnostics 库位类型限制统计。 + * @param {number} diagnostics.totalRows 原始库位行数。 + * @param {number} diagnostics.allowAllocationFilteredRows allow_allocation 过滤行数。 + * @param {number} diagnostics.isActiveFilteredRows is_active 过滤行数。 + * @return {string} 缺货原因文本。 + */ +function buildLocationTypeRestrictionReason(diagnostics = {}) { + const totalRows = toNumber(diagnostics.totalRows, 0); + const allowAllocationFilteredRows = toNumber(diagnostics.allowAllocationFilteredRows, 0); + const isActiveFilteredRows = toNumber(diagnostics.isActiveFilteredRows, 0); + + if (totalRows <= 0) { + return ''; + } + + const reasonParts = []; + + if (allowAllocationFilteredRows > 0) { + reasonParts.push('库位类型不可分配'); + } + + if (isActiveFilteredRows > 0) { + reasonParts.push('库位类型未启用'); + } + + return reasonParts.join('/'); +} + +/** + * 诊断库存是否因库位类型限制导致无可分配库位。 + * + * @param {Object} options 参数。 + * @param {Object} options.ctx 请求上下文。 + * @param {Object} options.Op Sequelize 操作符集合。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {number} options.stockId 库存 ID。 + * @param {Object} options.transaction 事务对象。 + * @param {Map} options.cache 诊断缓存。 + * @return {Promise} 诊断结果。 + */ +async function diagnoseStorageTypeRestriction(options = {}) { + const { + ctx, + Op, + warehouseId, + stockId, + transaction, + cache, + } = options; + + const normalizedStockId = toNumber(stockId, 0); + if (normalizedStockId <= 0 || !ctx || !Op) { + return { + totalRows: 0, + allowAllocationFilteredRows: 0, + isActiveFilteredRows: 0, + reason: '', + }; + } + + if (cache instanceof Map && cache.has(normalizedStockId)) { + return cache.get(normalizedStockId); + } + + const rawStorageRows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: warehouseId, + stock_id: normalizedStockId, + is_enabled: 1, + delete_at: null, + available_quantity: { + [Op.gt]: 0, + }, + }, + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + required: true, + attributes: [ 'id' ], + include: [ + { + model: ctx.model.LocationType, + as: 'locationType', + required: true, + attributes: [ 'id', 'allow_allocation', 'is_active' ], + }, + ], + }, + ], + transaction, + }); + + let allowAllocationFilteredRows = 0; + let isActiveFilteredRows = 0; + + for (const storageRow of Array.isArray(rawStorageRows) ? rawStorageRows : []) { + const plainStorage = toPlainRecord(storageRow) || {}; + const space = toPlainRecord(plainStorage.space) || {}; + const locationType = toPlainRecord(space.locationType) || {}; + + if (toNumber(locationType.allow_allocation, 0) !== 1) { + allowAllocationFilteredRows += 1; + } + + if (toNumber(locationType.is_active, 0) !== 1) { + isActiveFilteredRows += 1; + } + } + + const diagnostics = { + totalRows: Array.isArray(rawStorageRows) ? rawStorageRows.length : 0, + allowAllocationFilteredRows, + isActiveFilteredRows, + reason: '', + }; + + diagnostics.reason = buildLocationTypeRestrictionReason(diagnostics); + + if (cache instanceof Map) { + cache.set(normalizedStockId, diagnostics); + } + + return diagnostics; +} + +/** + * 生成库存不足提示文本。 + * + * @param {Array} shortageItems 缺货条目。 + * @return {string} 提示文本。 + */ +function buildShortageMessage(shortageItems = []) { + const parts = shortageItems + .filter(item => item && Number(item.stock_id) > 0) + .map(item => { + const shortageReason = String(item.reason || '').trim(); + const reasonText = shortageReason ? `,原因:${shortageReason}` : ''; + + return `sku(${item.stock_id}),数量:${item.required_quantity},库位数量:${item.allocated_quantity}${reasonText}`; + }); + + 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)); +} + +/** + * 规范化取消储位分配相关入参。 + * + * 仅保留订单 ID 归一化结果,不再接收或透传存储位开关字段。 + * + * @param {Object} data 请求体。 + * @return {{ orderIds: number[], forbiddenWarehouseKeys: string[] }} 规范化结果。 + */ +function normalizeCancelStorageAllocationRequest(data = {}) { + const requestData = data && typeof data === 'object' ? data : {}; + const forbiddenWarehouseKeys = [ 'warehouse_id', 'warehouseId' ] + .filter(key => Object.prototype.hasOwnProperty.call(requestData, key)); + + return { + orderIds: normalizeOrderIds(requestData), + forbiddenWarehouseKeys, + }; +} + +/** + * 订单储位分配公共服务。 + * 负责订单、库存、库位的分配编排,并写入 wms_picking。 + */ +class OrderStorageAllocationService extends MainService { + /** + * 按订单批量分配储位。 + * + * 入参支持以下字段: + * - `allow_storage_location` / `allowStorageLocation` / `is_allow_storage` / `isAllowStorage` + * - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id` + * + * 分配规则: + * - 先过滤掉已经完成储位分配的订单 + * - 默认只从库位类型允许分配且启用的储位中分配(排除存储储位); + * allow_storage_location=true 或货主关闭存拣分离(storage_separation=0)时, + * 不再限制库位类型,允许存储储位参与分配 + * - FIFO 先按生产日期,再按入库时间 + * - 库存不足时按订单顺序尽量分配,并将不足订单标记为异常 + * + * @param {Object} data 请求体。 + * @return {Promise} 分配结果。 + */ + async allocatePicking(data = {}) { + const { ctx, app } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const progressCallback = typeof requestData.progress_callback === 'function' + ? requestData.progress_callback + : null; + // 优先使用调用方显式传入的仓库ID(Qimen 等无登录用户上下文的链路 ctx.user 为空) + const warehouseId = toNumber( + requestData.warehouse_id + ?? requestData.warehouseId + ?? ctx.user?.store_id + ?? ctx.user?.warehouse_id, + 0 + ); + const orderIds = normalizeOrderIds(requestData); + const allowStorageLocation = normalizeBooleanFlag( + requestData.allow_storage_location + ?? requestData.allowStorageLocation + ?? requestData.is_allow_storage + ?? requestData.isAllowStorage + ); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 入口入参', { + requestData, + warehouseId, + orderIds, + allowStorageLocation, + }); + + if (warehouseId <= 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 缺少仓库上下文,直接返回', { + requestData, + warehouseId, + orderIds, + allowStorageLocation, + }); + return { + code: 400, + message: '缺少仓库上下文', + data: null, + }; + } + + if (orderIds.length === 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单ID为空,直接返回', { + requestData, + warehouseId, + orderIds, + allowStorageLocation, + }); + return { + code: 400, + message: '订单ID不能为空', + data: null, + }; + } + + const transaction = await ctx.model.transaction(); + const { Op } = app.Sequelize; + const now = new Date(); + const notifyProgress = async payload => { + if (typeof progressCallback !== 'function') { + return; + } + + try { + await progressCallback(payload); + } catch (error) { + if (ctx.logger && typeof ctx.logger.warn === 'function') { + ctx.logger.warn('[OrderStorageAllocationService.allocatePicking] 上报进度回调失败: %s', error && error.message ? error.message : error); + } + } + }; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务已创建', { + warehouseId, + orderIds, + allowStorageLocation, + }); + + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const pickingModel = ctx.model.Picking; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 模型加载完成', { + warehouseId, + hasOrderModel: Boolean(orderModel), + hasOrderItemModel: Boolean(orderItemModel), + hasPickingModel: Boolean(pickingModel), + }); + + 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, + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单主表查询完成', { + warehouseId, + requestedOrderCount: orderIds.length, + requestedOrderSampleIds: orderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + orderRowCount: Array.isArray(orderRows) ? orderRows.length : 0, + }); + + 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 = []; + const errorRetryOrderIds = []; + + for (const orderId of orderIds) { + const orderRow = orderMap.get(orderId); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单前', { + orderId, + hasOrderRow: Boolean(orderRow), + storageStatus: orderRow ? orderRow.storage_status : null, + }); + + if (!orderRow) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + skipped_reason: 'not_found', + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { + orderId, + skippedReason: 'not_found', + }); + continue; + } + + if (String(orderRow.status || '').trim() === ORDER_STATUS_CANCEL) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + order_status: orderRow.status, + skipped_reason: 'order_cancelled', + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { + orderId, + skippedReason: 'order_cancelled', + }); + continue; + } + + if (isInterceptedOrderStatus(orderRow && orderRow.intercept_status)) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + intercept_status: orderRow.intercept_status, + skipped_reason: 'intercepted', + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { + orderId, + interceptStatus: orderRow.intercept_status, + skippedReason: 'intercepted', + }); + continue; + } + + if (isLockedOrderStatus(orderRow && orderRow.lock_status)) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + lock_status: orderRow.lock_status, + skipped_reason: 'locked', + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { + orderId, + lockStatus: orderRow.lock_status, + skippedReason: 'locked', + }); + 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', + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { + orderId, + skippedReason: 'already_allocated', + }); + continue; + } + + pendingOrderIds.push(orderId); + + if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_ERROR) { + errorRetryOrderIds.push(orderId); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单进入待分配列表', { + orderId, + storageStatus: orderRow.storage_status, + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + }); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单过滤完成', { + requestedOrderCount: orderIds.length, + pendingOrderCount: pendingOrderIds.length, + skippedOrderCount: skippedOrders.length, + errorRetryOrderCount: errorRetryOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + errorRetryOrderSampleIds: errorRetryOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + }); + + if (pendingOrderIds.length === 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无需分配的订单,准备提交事务', { + warehouseId, + skippedOrderCount: skippedOrders.length, + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + }); + await transaction.commit(); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务提交完成', { + warehouseId, + requestedOrderCount: orderIds.length, + pendingOrderCount: pendingOrderIds.length, + skippedOrderCount: skippedOrders.length, + requestedOrderSampleIds: orderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + }); + 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, + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细查询完成', { + warehouseId, + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + orderItemRowCount: Array.isArray(orderItemRows) ? orderItemRows.length : 0, + }); + + 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); + + // 静态盘点锁定:与「库存不足」同流程——命中锁定的订单标记失败(storage_status=error/order_flag), + // 其余订单继续正常分配,不整单中断(最终由 shortage_order_ids / shortage_messages 返回) + const staticLockRowByStock = new Map(); + const stockCheckService = ctx.service && ctx.service.systems && ctx.service.systems.stockCheck; + if (stockIds.length > 0 && stockCheckService && typeof stockCheckService.getStaticLockConflict === 'function') { + try { + const lockConflict = await stockCheckService.getStaticLockConflict({ + warehouseId, + stockIds, + actionLabel: '分配储位', + }); + if (lockConflict.locked) { + for (const row of lockConflict.rows) { + staticLockRowByStock.set(Number(row.stock_id), row); + } + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 命中静态盘点锁定,相关订单将标记分配失败', { + warehouseId, + orderIds, + lockedStockIds: [ ...staticLockRowByStock.keys() ], + message: lockConflict.message, + }); + } + } catch (error) { + // 锁定查询异常不阻断分配主流程(按未锁定处理),仅记录日志 + if (ctx.logger && typeof ctx.logger.warn === 'function') { + ctx.logger.warn(`[OrderStorageAllocationService.allocatePicking] 静态盘点锁定查询失败: ${error && error.message}`); + } + } + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细归集完成', { + warehouseId, + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + stockIdCount: stockIds.length, + stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + }); + + 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, + }); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主记录预锁定完成', { + warehouseId, + stockIdCount: stockIds.length, + stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + }); + + 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', 'pick_sequence', 'pick_priority' ], + include: [ + { + model: ctx.model.LocationType, + as: 'locationType', + required: true, + attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ], + // 不在 SQL 层过滤库位类型:存拣分离策略按库存(货主)维度生效, + // 无法在批量 SQL 的 include where 中按 stock_id 分组表达, + // 统一在下方按 allowStorageSpace 逐 SKU 过滤。 + }, + ], + }, + ], + transaction, + lock: transaction.LOCK.UPDATE, + order: [[ 'id', 'ASC' ]], + }) + : []; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 可分配库存查询完成', { + warehouseId, + stockIdCount: stockIds.length, + stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + storageRowCount: Array.isArray(storageRows) ? storageRows.length : 0, + allowStorageLocation, + }); + + 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(), + }; + + const stockId = Number(normalizedStorage.stock_id); + const currentStorageRows = storageRowsByStockId.get(stockId) || []; + currentStorageRows.push(normalizedStorage); + storageRowsByStockId.set(stockId, currentStorageRows); + } + + for (const [ stockId, storageRowsForStock ] of storageRowsByStockId.entries()) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存可分配摘要', summarizeStorageRows(stockId, storageRowsForStock)); + } + + const policyCache = new Map(); + const shortageReasonCache = new Map(); + const pickingRows = []; + const storageAllocationMap = new Map(); + const orderResults = []; + const totalCount = pendingOrderIds.length; + let processedCount = 0; + + // 按订单维度跟踪已锁定的库存记录,用于缺货订单的原子回滚。 + // Map> + const orderLockRecords = new Map(); + + // 对于 storage_status='error' 的重分配订单,先清理旧的 picking 记录并释放已锁定的库存 + if (errorRetryOrderIds.length > 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 检测到 error 重试订单,开始清理旧数据', { + warehouseId, + errorRetryOrderIds, + errorRetryOrderCount: errorRetryOrderIds.length, + }); + + const oldPickingRecords = await pickingModel.findAll({ + where: { + order_id: { [Op.in]: errorRetryOrderIds }, + status: 'pending', + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 查询到旧的 picking 记录', { + warehouseId, + oldPickingCount: Array.isArray(oldPickingRecords) ? oldPickingRecords.length : 0, + }); + + if (Array.isArray(oldPickingRecords) && oldPickingRecords.length > 0) { + for (const record of oldPickingRecords) { + const storageId = toNumber(record.storage_id, 0); + const quantity = toNumber(record.quantity, 0); + + if (storageId > 0 && quantity > 0) { + await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定', { + warehouseId, + orderId: toNumber(record.order_id, 0), + storageId, + quantity, + }); + } + } + + await pickingModel.destroy({ + where: { + order_id: { [Op.in]: errorRetryOrderIds }, + status: 'pending', + }, + transaction, + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已删除旧的 picking 记录', { + warehouseId, + errorRetryOrderIds, + deletedCount: oldPickingRecords.length, + }); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] error 订单旧数据清理完成', { + warehouseId, + errorRetryOrderIds, + }); + } + + await notifyProgress({ + status: 'running', + total_count: totalCount, + processed_count: processedCount, + }); + + for (const orderId of pendingOrderIds) { + const orderRow = orderMap.get(orderId); + if (!orderRow) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 处理订单时发现订单缺失', { + orderId, + }); + continue; + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 开始处理订单', { + orderId, + orderRow, + }); + + 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); + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细准备完成', { + orderId, + orderItemCount: orderItems.length, + orderItemIds: orderItems.map(item => toNumber(item.id, 0)), + }); + + const shortageItems = []; + const storageRowErrors = []; + let allocatedQuantityForOrder = 0; + + // 静态盘点锁定:本订单明细中含锁定商品时,整单标记失败(与库存不足同流程) + const lockedStockIdsInOrder = []; + for (const orderItem of orderItems) { + const lockedStockId = toNumber(orderItem.stock_id, 0); + if (lockedStockId > 0 && staticLockRowByStock.has(lockedStockId) && !lockedStockIdsInOrder.includes(lockedStockId)) { + lockedStockIdsInOrder.push(lockedStockId); + } + } + const staticLockMessage = lockedStockIdsInOrder.length > 0 + ? `静态盘点锁定:${lockedStockIdsInOrder.map(lockedStockId => { + const lockRow = staticLockRowByStock.get(lockedStockId) || {}; + const checkNos = (Array.isArray(lockRow.check_nos) ? lockRow.check_nos : []).filter(Boolean).join('/'); + return checkNos ? `sku(${lockedStockId}) 盘点单 ${checkNos}` : `sku(${lockedStockId})`; + }).join('|')}` + : ''; + if (staticLockMessage) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单命中静态盘点锁定,跳过分配', { + orderId, + lockedStockIds: lockedStockIdsInOrder, + staticLockMessage, + }); + } + + for (const orderItem of orderItems) { + const stockId = toNumber(orderItem.stock_id, 0); + const requiredQuantity = toNumber(orderItem.plan_qty ?? orderItem.planQty ?? orderItem.count ?? 0, 0); + + // 静态盘点锁定商品:不参与分配(不查储位、不加锁),整单由 staticLockMessage 标记失败 + if (stockId > 0 && staticLockRowByStock.has(stockId)) { + continue; + } + + if (stockId <= 0 || requiredQuantity <= 0) { + shortageItems.push({ + stock_id: stockId, + required_quantity: requiredQuantity > 0 ? requiredQuantity : 0, + allocated_quantity: 0, + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细无效或缺少库存,记为缺货', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + requiredQuantity, + }); + 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; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 读取库存策略完成', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + policyEntry, + storage_separation: policyEntry?.policyConfig?.storage_separation, + allowStorageLocation, + storageSeparationEnabled, + allowStorageSpace, + }); + + const storageRowsForStock = storageRowsByStockId.get(stockId) || []; + const candidateStorageRows = storageRowsForStock + .slice() + .filter(storageRow => isAllocatableStorageRow(storageRow, allowStorageSpace)) + .sort((left, right) => compareStorageRows(left, right)); + + let shortageReason = ''; + let shortageDiagnostics = null; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 计算候选库存完成', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + storageRowCountBeforeFilter: storageRowsForStock.length, + candidateStorageRowCountAfterFilter: candidateStorageRows.length, + allowStorageSpace, + candidateStorageIds: candidateStorageRows.map(storageRow => storageRow.id), + }); + + if (candidateStorageRows.length === 0) { + shortageDiagnostics = allowStorageSpace + ? null + : await diagnoseStorageTypeRestriction({ + ctx, + Op, + warehouseId, + stockId, + transaction, + cache: shortageReasonCache, + }); + shortageReason = shortageDiagnostics + ? String(shortageDiagnostics.reason || '').trim() + : ''; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无候选库位,标记缺货原因', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + requiredQuantity, + policyEntry: { + storage_separation: policyEntry?.policyConfig?.storage_separation, + allow_storage_location: policyEntry?.policyConfig?.allow_storage_location, + }, + storageRowsSummary: summarizeStorageRows(stockId, storageRowsForStock), + allowStorageSpace, + shortageDiagnostics, + shortageReason, + }); + } + + 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) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 候选库存已无可用数量,跳过', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + storageId: storageRow.id, + currentAvailable, + }); + continue; + } + + const allocationQuantity = Math.min(remainingQuantity, currentAvailable); + if (allocationQuantity <= 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 计算出的分配数量无效,跳过', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + storageId: storageRow.id, + currentAvailable, + remainingQuantity, + }); + continue; + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备锁定库存', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + storageId: storageRow.id, + storageRowSummary: { + storageId: storageRow.id, + spaceId: toNumber(storageRow.space_id, 0) || 0, + availableQuantity: currentAvailable, + lockedQuantity: toNumber(storageRow.locked_quantity, 0), + productionDate: storageRow.production_date || null, + inboundTime: storageRow.inbound_time || null, + }, + allocationQuantity, + remainingQuantity, + currentAvailable, + }); + + const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); + const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0); + + await ctx.service.systems.storage.index.lockQuantity(storageRow.id, allocationQuantity, { transaction }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + storageId: storageRow.id, + allocationQuantity, + }); + + // 写入储位锁定流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'LOCK', + warehouse_id: warehouseId, + store_id: storageRow.store_id, + stock_id: stockId, + storage_id: storageRow.id, + space_id: storageRow.space_id, + quantity: allocationQuantity, + before_quantity: storageRow.quantity, + after_quantity: storageRow.quantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: beforeLockedQuantity + allocationQuantity, + before_intercept_locked_quantity: beforeInterceptLockedQuantity, + after_intercept_locked_quantity: beforeInterceptLockedQuantity, + batch_no: storageRow.batch_no, + inventory_type: storageRow.inventory_type, + order_type: 'PICKING_LOCK', + order_no: String(orderId), + order_id: orderId, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '分配储位(库存锁定)', + }, { 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); + + const spaceId = toNumber(storageRow.space_id, 0); + if (!spaceId) { + storageRowErrors.push({ storage_id: storageRow.id, reason: '库位未设置' }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,跳过该库存行', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + storageId: storageRow.id, + spaceId: storageRow.space_id, + }); + // 释放刚才 lockQuantity 加的锁,防止 locked_quantity 泄漏 + await ctx.service.systems.storage.index.unlockQuantity( + storageRow.id, allocationQuantity, { transaction } + ); + + // 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity + storageRow.available_quantity = currentAvailable; + storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity; + + // 回退 remainingQuantity:未分配成功的数量加回去 + remainingQuantity += allocationQuantity; + + // 回退 allocatedQuantityForItem + allocatedQuantityForItem -= allocationQuantity; + + // 回退 allocatedQuantityForOrder + allocatedQuantityForOrder -= allocationQuantity; + + // 回退 storageAllocationMap 中的累加值 + const prevStorageQty = storageAllocationMap.get(storageRow.id) || 0; + const newStorageQty = prevStorageQty - allocationQuantity; + if (newStorageQty <= 0) { + storageAllocationMap.delete(storageRow.id); + } else { + storageAllocationMap.set(storageRow.id, newStorageQty); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退内存计数器', { + orderId, + storageId: storageRow.id, + allocationQuantity, + prevStorageQty, + newStorageQty, + rollback: { + remainingQuantity, + allocatedQuantityForItem, + allocatedQuantityForOrder, + storageAvailableQuantity: storageRow.available_quantity, + storageLockedQuantity: storageRow.locked_quantity, + }, + }); + + continue; + } + + // 记录本次成功锁定(lockQuantity + spaceId 有效),用于订单级别缺货回滚 + const orderLockList = orderLockRecords.get(orderId) || []; + orderLockList.push({ storageId: storageRow.id, stockId: storageRow.stock_id, quantity: allocationQuantity }); + orderLockRecords.set(orderId, orderLockList); + + pickingRows.push({ + order_id: orderId, + order_item_id: toNumber(orderItem.id, 0), + warehouse_id: warehouseId, + storage_id: storageRow.id, + stock_id: toNumber(storageRow.stock_id, 0) || null, + 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) { + // 确保每个明细的缺货原因独立计算,避免候选库位为空时的诊断原因 + // 被错误地复用到候选库位非空但仍不足的明细上 + const finalShortageReason = candidateStorageRows.length === 0 + ? shortageReason + : (shortageReason || '库存不足'); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备写入缺货条目', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + requiredQuantity, + allocatedQuantity: allocatedQuantityForItem, + remainingQuantity, + candidateCount: candidateStorageRows.length, + shortageReason, + finalShortageReason, + }); + shortageItems.push({ + stock_id: stockId, + required_quantity: requiredQuantity, + allocated_quantity: allocatedQuantityForItem, + reason: finalShortageReason, + }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细存在缺货', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + requiredQuantity, + allocatedQuantityForItem, + remainingQuantity, + shortageReason, + finalShortageReason, + }); + } + } + + const shortageMessage = buildShortageMessage(shortageItems); + + const spaceErrorMessage = storageRowErrors.length > 0 && shortageMessage + ? `库位未设置(storage_id:${storageRowErrors.map(e => e.storage_id).join(',')})` + : ''; + const finalShortageMessage = [ staticLockMessage, shortageMessage, spaceErrorMessage ].filter(Boolean).join('|'); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单缺货信息汇总', { + orderId, + shortageItems, + storageRowErrors, + shortageMessage, + finalShortageMessage, + }); + + // 单订单原子性分配:如果本订单有缺货,回滚该订单所有已成功锁定的库存, + // 并从 pickingRows 中移除该订单的所有记录,确保同一事务内该订单不留任何 locked_quantity。 + if (finalShortageMessage) { + const orderLocks = orderLockRecords.get(orderId); + if (Array.isArray(orderLocks) && orderLocks.length > 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 开始回滚订单已锁定库存', { + orderId, + orderLockCount: orderLocks.length, + orderLocks, + }); + + for (const lockRecord of orderLocks) { + await ctx.service.systems.storage.index.unlockQuantity( + lockRecord.storageId, lockRecord.quantity, { transaction } + ); + + // 回退 storageAllocationMap 中的累加值 + const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0; + const newStorageQty = prevStorageQty - lockRecord.quantity; + if (newStorageQty <= 0) { + storageAllocationMap.delete(lockRecord.storageId); + } else { + storageAllocationMap.set(lockRecord.storageId, newStorageQty); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已回滚单条库存锁定', { + orderId, + storageId: lockRecord.storageId, + quantity: lockRecord.quantity, + prevStorageQty, + newStorageQty, + }); + } + + // 回退订单级别的已分配数量计数器 + allocatedQuantityForOrder = 0; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单锁定库存回滚完成,已重置 allocatedQuantityForOrder', { + orderId, + }); + } + + // 从 pickingRows 中移除该订单的所有记录。 + // 使用反向遍历 + splice 避免索引漂移,保持 pickingRows 顺序。 + for (let pickIdx = pickingRows.length - 1; pickIdx >= 0; pickIdx -= 1) { + if (pickingRows[pickIdx].order_id === orderId) { + pickingRows.splice(pickIdx, 1); + } + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已从 pickingRows 移除缺货订单记录', { + orderId, + remainingPickingCount: pickingRows.length, + }); + } + + const orderUpdateValues = finalShortageMessage + ? { + storage_status: STORAGE_STATUS_ERROR, + step: ORDER_STEP_EXCEPTION, + order_flag: finalShortageMessage, + updated_at: now, + } + : { + storage_status: STORAGE_STATUS_FIN, + order_flag: '', + updated_at: now, + }; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备更新订单状态', { + orderId, + orderUpdateValues, + allocatedQuantityForOrder, + }); + + await orderModel.update(orderUpdateValues, { + where: { + id: orderId, + warehouse_id: warehouseId, + status: { + [ctx.app.Sequelize.Op.ne]: 'cancel', + }, + }, + transaction, + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单状态更新完成', { + orderId, + orderUpdateValues, + }); + + orderResults.push({ + order_id: orderId, + storage_status: orderUpdateValues.storage_status, + allocated_quantity: allocatedQuantityForOrder, + shortage_message: finalShortageMessage || '', + status: finalShortageMessage ? 'error' : 'success', + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 当前订单处理结束', { + orderId, + orderResult: orderResults[orderResults.length - 1], + }); + + processedCount += 1; + await notifyProgress({ + status: 'running', + total_count: totalCount, + processed_count: processedCount, + }); + } + + if (pickingRows.length > 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 写入 picking 明细', { + warehouseId, + pickingCount: pickingRows.length, + }); + await pickingModel.bulkCreate(pickingRows, { + transaction, + }); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备提交事务', { + warehouseId, + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + skippedOrderCount: skippedOrders.length, + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + orderResultSummary: summarizeArrayForLog(orderResults), + stockLockSummary: [], + storageLockSummary: summarizeArrayForLog(Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ + storage_id: storageId, + locked_quantity: quantity, + }))), + }); + + await transaction.commit(); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务提交完成', { + warehouseId, + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + skippedOrderCount: skippedOrders.length, + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + orderResultSummary: summarizeArrayForLog(orderResults), + }); + + const errorOrderResults = orderResults.filter(item => item.status === 'error'); + const successOrderResults = orderResults.filter(item => item.status === 'success'); + const successOrderIds = successOrderResults + .map(item => toNumber(item.order_id, 0)) + .filter(orderId => orderId > 0); + + if (successOrderIds.length > 0) { + try { + await ctx.service.systems.orderPendingException.reversePendingException({ + ids: successOrderIds, + }); + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 待处理异常清理完成', { + warehouseId, + successOrderIds, + }); + } catch (reverseError) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 待处理异常清理失败,仅记录日志', { + warehouseId, + successOrderIds, + error: reverseError, + }); + + if (ctx.logger && typeof ctx.logger.error === 'function') { + ctx.logger.error('[OrderStorageAllocationService.allocatePicking] reversePendingException failed', { + warehouseId, + successOrderIds, + error: reverseError, + }); + } + } + } + + const shortageMessages = errorOrderResults + .map(item => item.shortage_message) + .filter(Boolean); + + const responseData = { + 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: [], + storage_lock_summary: Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ + storage_id: storageId, + locked_quantity: quantity, + })), + shortage_messages: shortageMessages, + }; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 最终返回摘要', { + code: 200, + message: shortageMessages.length > 0 + ? '储位分配完成,部分订单库存不足' + : '储位分配完成', + responseDataSummary: { + requestedOrderIds: summarizeArrayForLog(responseData.requested_order_ids), + pendingOrderIds: summarizeArrayForLog(responseData.pending_order_ids), + allocatedOrderIds: summarizeArrayForLog(responseData.allocated_order_ids), + shortageOrderIds: summarizeArrayForLog(responseData.shortage_order_ids), + skippedOrders: summarizeArrayForLog(responseData.skipped_orders), + orders: summarizeArrayForLog(responseData.orders), + stockLockSummary: [], + storageLockSummary: summarizeArrayForLog(responseData.storage_lock_summary), + shortageMessages: summarizeArrayForLog(responseData.shortage_messages), + pickingCount: responseData.picking_count, + }, + }); + + return { + code: 200, + message: shortageMessages.length > 0 + ? '储位分配完成,部分订单库存不足' + : '储位分配完成', + data: responseData, + }; + } catch (error) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 发生异常,准备回滚事务', { + warehouseId, + orderIds, + error, + }); + await transaction.rollback(); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务回滚完成', { + warehouseId, + orderIds, + error, + }); + throw error; + } + } + + /** + * 兼容旧调用名称的储位分配入口。 + * + * @param {Object} data 请求体。 + * @return {Promise} 分配结果。 + */ + async allocateStorage(data = {}) { + writeAllocationTextLog('[OrderStorageAllocationService.allocateStorage] 入口入参', data); + + const result = await this.allocatePicking(data); + + writeAllocationTextLog('[OrderStorageAllocationService.allocateStorage] 返回结果', result); + + return result; + } + + /** + * 待处理订单同步入口。 + * + * 先完成订单查询、过滤与分组,再按 `create_channel` 路由到 + * `orderAsync.syncQmOrders`、`orderAsync.syncManualOrders`、`orderAsync.syncApiOrders`、 + * `orderAsync.syncStockoutOrders` 四个处理入口。 + * + * SN(序列号管理)订单不做无差别拦截:仅当「SN 明细未齐套(每个序列号明细的已发出 SN 数量 + * 少于 plan_qty)」或「订单未复核完成」时才拦截(failed_reason=sn_batch_forbidden); + * 齐套且已复核的 SN 订单与普通订单一样参与回传。 + * + * @param {Object} data 请求体。 + * @return {Promise} 同步结果。 + */ + async syncOrderIds(data = {}) { + const { ctx } = this; + const unallocatedPostStatus = 'none'; + const fastFailReason = '快递状态未分配,禁止同步'; + const snBatchForbiddenReason = 'SN订单SN明细未齐套或未复核完成,不允许回传'; + const requestData = data && typeof data === 'object' ? data : {}; + const normalizeNumber = (value, defaultValue = 0) => { + const numericValue = Number(value); + return Number.isFinite(numericValue) ? numericValue : defaultValue; + }; + const normalizeOrderIds = request => { + const rawValues = []; + + if (Array.isArray(request.order_ids)) { + rawValues.push(...request.order_ids); + } else if (Array.isArray(request.orderIds)) { + rawValues.push(...request.orderIds); + } else if (Array.isArray(request.ids)) { + rawValues.push(...request.ids); + } else if (typeof request.order_ids === 'string') { + rawValues.push(...request.order_ids.split(',')); + } else if (typeof request.orderIds === 'string') { + rawValues.push(...request.orderIds.split(',')); + } else if (typeof request.ids === 'string') { + rawValues.push(...request.ids.split(',')); + } else if (request.order_ids !== undefined && request.order_ids !== null && request.order_ids !== '') { + rawValues.push(request.order_ids); + } else if (request.orderIds !== undefined && request.orderIds !== null && request.orderIds !== '') { + rawValues.push(request.orderIds); + } else if (request.ids !== undefined && request.ids !== null && request.ids !== '') { + rawValues.push(request.ids); + } else if (request.order_id !== undefined && request.order_id !== null && request.order_id !== '') { + rawValues.push(request.order_id); + } else if (request.orderId !== undefined && request.orderId !== null && request.orderId !== '') { + rawValues.push(request.orderId); + } else if (request.id !== undefined && request.id !== null && request.id !== '') { + rawValues.push(request.id); + } + + const orderIds = rawValues + .map(value => Number(String(value).trim())) + .filter(value => Number.isFinite(value) && value > 0); + + return Array.from(new Set(orderIds)); + }; + const normalizeCreateChannel = value => String(value || '').trim().toUpperCase() || 'MANUAL'; + const toPlainRecord = record => { + if (!record) { + return null; + } + + if (typeof record.get === 'function') { + return record.get({ plain: true }); + } + + return record; + }; + const groupOrdersByCreateChannel = orders => { + const groupedOrderMap = new Map(); + + for (const order of Array.isArray(orders) ? orders : []) { + if (!order || typeof order !== 'object') { + continue; + } + + const createChannel = normalizeCreateChannel(order.create_channel); + let groupedOrder = groupedOrderMap.get(createChannel); + + if (!groupedOrder) { + groupedOrder = { + create_channel: createChannel, + order_ids: [], + order_count: 0, + orders: [], + }; + groupedOrderMap.set(createChannel, groupedOrder); + } + + const orderId = normalizeNumber(order.id, 0); + if (orderId > 0) { + groupedOrder.order_ids.push(orderId); + } + + groupedOrder.order_count += 1; + groupedOrder.orders.push({ + id: orderId, + delivery_order_code: String(order.delivery_order_code || '').trim(), + create_channel: createChannel, + sync_status: String(order.sync_status || '').trim() || 'padding', + express_code: String(order.express_code || '').trim(), + post_status: String(order.post_status || '').trim() || 'none', + storage_status: String(order.storage_status || '').trim() || 'none', + }); + } + + return Array.from(groupedOrderMap.values()); + }; + + const orderIds = normalizeOrderIds(requestData); + // 优先使用调用方传入的 warehouse_id(异步模式下 ctx.user 可能失效), + // 兜底从 ctx.user 或 requestData 中读取 + const warehouseId = normalizeNumber( + requestData.warehouse_id + ?? ctx.user?.store_id + ?? ctx.user?.warehouse_id, + 0 + ); + const now = new Date(); + // 请求ID(用于 Redis 进度缓存) + const requestId = String(requestData.request_id || requestData.requestId || '').trim(); + + 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(); + + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderRows = await orderModel.findAll({ + where: { + id: { + [ctx.app.Sequelize.Op.in]: orderIds, + }, + warehouse_id: warehouseId, + // 排除已同步完成的订单,防止重复提交 + // 注意:不能排除 padding,因为 padding 是新订单的默认值(模型 defaultValue) + sync_status: { + [ctx.app.Sequelize.Op.notIn]: [ 'fin' ], + }, + // 排除已取消的订单,防止已取消订单被回传 + status: { + [ctx.app.Sequelize.Op.notIn]: [ 'cancel' ], + }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const orderMap = new Map(); + console.log('orderRows', JSON.stringify(orderRows)); + for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { + const plainOrder = toPlainRecord(orderRow); + if (!plainOrder || !Number(plainOrder.id)) { + continue; + } + + orderMap.set(Number(plainOrder.id), plainOrder); + } + + // SN(序列号管理)订单回传前置校验:通过订单明细 stock_id 反查 stock_warehouse.is_sn_mgmt, + // 只有「每个序列号明细的 SN 数量齐套」且「订单已复核」时才允许回传; + // 齐套但未复核、或已复核但 SN 未齐套,一律标记快速失败,避免把缺 SN 的发货单回传平台。 + const snOrderIdSet = new Set(); + const snBlockedOrderIdSet = new Set(); + const existingOrderIds = Array.from(orderMap.keys()); + if (existingOrderIds.length > 0) { + try { + const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const stockModel = ctx.model.StockWarehouse; + const orderItemSnModel = ctx.model.OrderItemSn; + + if (orderItemModel && typeof orderItemModel.findAll === 'function' && stockModel && typeof stockModel.findAll === 'function') { + const orderItemRows = await orderItemModel.findAll({ + where: { + order_id: { + [ctx.app.Sequelize.Op.in]: existingOrderIds, + }, + }, + attributes: [ 'id', 'order_id', 'stock_id', 'plan_qty' ], + raw: true, + }); + + const stockIds = [ ...new Set((Array.isArray(orderItemRows) ? orderItemRows : []) + .map(row => Number(row && row.stock_id || 0)) + .filter(stockId => Number.isFinite(stockId) && stockId > 0)) ]; + + if (stockIds.length > 0) { + const stockRows = await stockModel.findAll({ + where: { + id: { + [ctx.app.Sequelize.Op.in]: stockIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'is_sn_mgmt' ], + raw: true, + }); + + const snStockIdSet = new Set((Array.isArray(stockRows) ? stockRows : []) + .filter(row => String(row && row.is_sn_mgmt || '').trim().toUpperCase() === 'Y') + .map(row => Number(row && row.id || 0)) + .filter(stockId => Number.isFinite(stockId) && stockId > 0)); + + // 订单 -> 序列号明细(order_item_id + plan_qty) + const snItemsByOrderId = new Map(); + for (const row of (Array.isArray(orderItemRows) ? orderItemRows : [])) { + const orderId = Number(row && row.order_id || 0); + const stockId = Number(row && row.stock_id || 0); + if (!snStockIdSet.has(stockId) || orderId <= 0) { + continue; + } + + snOrderIdSet.add(orderId); + if (!snItemsByOrderId.has(orderId)) { + snItemsByOrderId.set(orderId, []); + } + snItemsByOrderId.get(orderId).push({ + order_item_id: Number(row && row.id || 0), + plan_qty: Number(row && row.plan_qty || 0), + }); + } + + if (snOrderIdSet.size > 0) { + const snModelAvailable = Boolean(orderItemSnModel) + && typeof orderItemSnModel.findAll === 'function'; + + // 明细 -> 已发出的 SN 编码集合(去重,避免重复录入被重复计数) + const shippedSnCodeMap = new Map(); + if (snModelAvailable) { + const snRows = await orderItemSnModel.findAll({ + where: { + warehouse_id: warehouseId, + order_id: { + [ctx.app.Sequelize.Op.in]: Array.from(snOrderIdSet), + }, + }, + attributes: [ 'order_id', 'order_item_id', 'sn_code', 'sn_status' ], + raw: true, + }); + + for (const row of (Array.isArray(snRows) ? snRows : [])) { + const snStatus = String(row && row.sn_status || '').trim().toUpperCase(); + if (!SN_SHIPPED_STATUS_SET.has(snStatus)) { + continue; + } + const itemKey = `${Number(row && row.order_id || 0)}:${Number(row && row.order_item_id || 0)}`; + if (!shippedSnCodeMap.has(itemKey)) { + shippedSnCodeMap.set(itemKey, new Set()); + } + const snCode = String(row && row.sn_code || '').trim(); + if (snCode) { + shippedSnCodeMap.get(itemKey).add(snCode); + } + } + } else { + ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 订单SN模型不可用,SN订单将全部拦截', { + warehouseId, + snOrderIds: Array.from(snOrderIdSet), + }); + } + + for (const orderId of snOrderIdSet) { + const orderRow = orderMap.get(orderId) || {}; + const rechecked = String(orderRow.recheck_status || '').trim() === 'fin'; + const snItems = snItemsByOrderId.get(orderId) || []; + let snCompleted = snModelAvailable; + + if (snCompleted) { + for (const item of snItems) { + // plan_qty 非正整数(脏数据/赠品 0 数量)不参与齐套判定 + if (!Number.isInteger(item.plan_qty) || item.plan_qty <= 0) { + continue; + } + const codes = shippedSnCodeMap.get(`${orderId}:${item.order_item_id}`); + const codeCount = codes ? codes.size : 0; + if (codeCount < item.plan_qty) { + snCompleted = false; + break; + } + } + } + + if (!rechecked || !snCompleted) { + snBlockedOrderIdSet.add(orderId); + } + } + } + } + } + } catch (snDetectError) { + ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] SN订单检测失败', { + warehouseId, + orderIds: existingOrderIds, + message: snDetectError && snDetectError.message, + }); + throw snDetectError; + } + } + + const skippedOrders = []; + const fastFailedOrders = []; + const syncableOrders = []; + + 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.sync_status || '').trim() === 'fin') { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + create_channel: normalizeCreateChannel(orderRow.create_channel), + skipped_reason: 'already_synced', + }); + continue; + } + + // SN 订单仅在「SN 明细未齐套」或「未复核完成」时拦截,齐套且已复核允许回传 + if (snBlockedOrderIdSet.has(orderId)) { + fastFailedOrders.push({ + order_id: orderId, + status: 'failed', + create_channel: normalizeCreateChannel(orderRow.create_channel), + failed_reason: 'sn_batch_forbidden', + message: snBatchForbiddenReason, + }); + continue; + } + + const normalizedPostStatus = String(orderRow.post_status || '').trim() || unallocatedPostStatus; + if (normalizedPostStatus === unallocatedPostStatus) { + fastFailedOrders.push({ + order_id: orderId, + status: 'failed', + create_channel: normalizeCreateChannel(orderRow.create_channel), + post_status: normalizedPostStatus, + failed_reason: 'express_unallocated', + message: fastFailReason, + }); + continue; + } + + syncableOrders.push(orderRow); + } + + // SN 订单和快递未分配订单分开设置 sync_message + const snFailIds = fastFailedOrders + .filter(o => String(o && o.failed_reason || '').trim() === 'sn_batch_forbidden') + .map(o => normalizeNumber(o.order_id, 0)) + .filter(id => id > 0); + const expressFailIds = fastFailedOrders + .filter(o => String(o && o.failed_reason || '').trim() === 'express_unallocated') + .map(o => normalizeNumber(o.order_id, 0)) + .filter(id => id > 0); + + const syncableOrderIds = syncableOrders + .map(order => normalizeNumber(order.id, 0)) + .filter(orderId => orderId > 0); + const createChannelGroups = groupOrdersByCreateChannel(syncableOrders); + + if (syncableOrderIds.length > 0) { + await orderModel.update({ + sync_status: 'padding', + sync_message: '', + updated_at: now, + }, { + where: { + id: { + [ctx.app.Sequelize.Op.in]: syncableOrderIds, + }, + warehouse_id: warehouseId, + }, + transaction, + }); + } + + if (snFailIds.length > 0) { + await orderModel.update({ + sync_status: 'error', + sync_message: snBatchForbiddenReason, + inspection_status: STORAGE_STATUS_ERROR, + step: ORDER_STEP_EXCEPTION, + order_flag: snBatchForbiddenReason, + updated_at: now, + }, { + where: { + id: { [ctx.app.Sequelize.Op.in]: snFailIds }, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, + }, + transaction, + }); + } + + if (expressFailIds.length > 0) { + await orderModel.update({ + sync_status: 'error', + sync_message: fastFailReason, + inspection_status: STORAGE_STATUS_ERROR, + step: ORDER_STEP_EXCEPTION, + order_flag: fastFailReason, + updated_at: now, + }, { + where: { + id: { [ctx.app.Sequelize.Op.in]: expressFailIds }, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, + }, + transaction, + }); + } + + if (snFailIds.length > 0 || expressFailIds.length > 0) { + ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 命中快速失败,已阻断同步派发', { + warehouseId, + snFailIds, + expressFailIds, + }); + } + + await transaction.commit(); + + // ── 写初始进度到 Redis(dispatch handler 内部会递增 processed_count)── + if (requestId) { + const progressCacheKey = `order:pending:sync_order_ids:request:${requestId}`; + try { + await ctx.app.setCacheAsync(progressCacheKey, { + status: 'running', + total_count: syncableOrderIds.length, + processed_count: 0, + progress: 0, + warehouse_id: warehouseId, + update_time: Date.now(), + }, 7200); + } catch (cacheErr) { + ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 初始化进度缓存失败', { + error: cacheErr && cacheErr.message, + }); + } + } + + const routeContext = { + warehouseId, + requestedOrderIds: orderIds, + pendingOrderIds: syncableOrderIds, + request_id: requestId, + }; + const orderAsyncService = this.ctx.service.systems.orderAsync; + + // 并行派发各渠道分组(每个分组独立 try/catch,单渠道异常不阻塞其他渠道) + const dispatchResults = await Promise.all( + createChannelGroups.map(async groupedOrder => { + const createChannel = normalizeCreateChannel(groupedOrder.create_channel); + const groupOrderCount = Number(groupedOrder.order_count || groupedOrder.order_ids?.length || 0); + + try { + let result; + + if (createChannel === 'QM') { + result = await orderAsyncService.syncQmOrders(groupedOrder, routeContext); + } else if (createChannel === 'API') { + result = await orderAsyncService.syncApiOrders(groupedOrder, routeContext); + } else if (createChannel === 'STOCKOUT') { + // 出库单转订单渠道:回传时把快递编码/运单号写回出库单并通知外部, + // 成功后才完成订单同步 + result = await orderAsyncService.syncStockoutOrders(groupedOrder, routeContext); + } else { + result = await orderAsyncService.syncManualOrders(groupedOrder, routeContext); + } + + const dispatchStatus = result && result.status + ? String(result.status).trim() || 'success' + : (result && result.success === false ? 'failed' : 'success'); + + return { + ...result, + status: dispatchStatus, + }; + } catch (channelError) { + // 单渠道异常不影响其他渠道 + ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] 渠道派发异常,已隔离', { + createChannel, + warehouseId, + orderCount: groupOrderCount, + error: channelError && channelError.message ? channelError.message : channelError, + }); + + return { + create_channel: createChannel, + order_ids: Array.isArray(groupedOrder.order_ids) ? groupedOrder.order_ids : [], + order_count: groupOrderCount, + warehouse_id: warehouseId, + handler: 'syncOrderIds', + sync_target: createChannel === 'QM' ? 'qimen' : 'internal', + status: 'failed', + message: channelError && channelError.message ? channelError.message : '渠道派发异常', + success_count: 0, + failed_count: groupOrderCount, + route_state: 'rejected', + }; + } + }) + ); + + // 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,避免重复 + + // 派发完成后,将成功渠道的订单 sync_status 更新为 fin,防止重复同步 + const dispatchedOrderIds = []; + for (let i = 0; i < dispatchResults.length; i++) { + const dr = dispatchResults[i]; + if (dr && String(dr.status || '').trim() === 'success') { + const group = createChannelGroups[i]; + if (group && Array.isArray(group.order_ids)) { + for (const oid of group.order_ids) { + dispatchedOrderIds.push(Number(oid)); + } + } + } + } + + if (dispatchedOrderIds.length > 0) { + try { + await orderModel.update({ + sync_status: 'fin', + sync_message: '', + updated_at: new Date(), + }, { + where: { + id: { [ctx.app.Sequelize.Op.in]: dispatchedOrderIds }, + warehouse_id: warehouseId, + }, + }); + ctx.logger.info('[OrderStorageAllocationService.syncOrderIds] 同步完成,已更新 sync_status=fin', { + warehouseId, + dispatchedCount: dispatchedOrderIds.length, + }); + } catch (finUpdateErr) { + ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] 更新 sync_status=fin 失败', { + warehouseId, + dispatchedCount: dispatchedOrderIds.length, + error: finUpdateErr && finUpdateErr.message, + }); + } + } + + const responseData = { + warehouse_id: warehouseId, + requested_order_ids: orderIds, + pending_order_ids: syncableOrderIds, + skipped_orders: skippedOrders, + create_channel_groups: createChannelGroups, + dispatch_results: dispatchResults, + failed_orders: fastFailedOrders, + orders: [ + ...skippedOrders, + ...fastFailedOrders, + ...syncableOrders.map(order => ({ + order_id: normalizeNumber(order.id, 0), + delivery_order_code: String(order.delivery_order_code || '').trim(), + create_channel: normalizeCreateChannel(order.create_channel), + express_code: String(order.express_code || '').trim(), + sync_status: 'padding', + status: 'pending', + })), + ], + pending_count: syncableOrderIds.length, + skipped_count: skippedOrders.length, + failed_count: fastFailedOrders.length, + create_channel_count: createChannelGroups.length, + dispatch_count: dispatchResults.length, + dispatch_success_count: dispatchResults.filter(item => item.status === 'success').length, + dispatch_failed_count: dispatchResults.filter(item => item.status === 'failed').length, + }; + + return { + code: 200, + message: syncableOrderIds.length > 0 + ? '同步已受理,已生成按来源分组的同步计划' + : (fastFailedOrders.length > 0 ? '同步失败:存在不允许批量回传的订单' : '没有需要同步的订单'), + data: responseData, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 取消待处理订单的储位分配,并回滚相关库存锁定。 + * + * 入参仅支持订单 ID 相关字段: + * - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id` + * - `interceptMode`(可选,布尔值):拦截确认模式,默认 false。 + * - false(普通取消):pending 行解除锁定(可用数量 +q)、fin 行返还实物(可用数量 +q),既有行为不变; + * - true(拦截确认):pending 行作业锁迁移为拦截锁(locked -q、intercept +q、available 不变), + * fin 行实物返还并拦截锁定(quantity +q、intercept +q、available 不变),流水 order_type 记为 + * INTERCEPT_LOCK 且记录 order_id 与 before/after_intercept_locked_quantity 快照。 + * + * 取消分配时仅处理当前用户仓库中已完成储位分配的订单; + * 未分配订单或非完成状态订单会进入 skipped_orders。 + * + * @param {Object} data 请求体。 + * @param {boolean} [data.interceptMode] 拦截确认模式开关。 + * @return {Promise} 取消分配结果。 + */ + async cancelAllocateStorage(data = {}) { + const { ctx, app } = this; + const { orderIds, forbiddenWarehouseKeys } = normalizeCancelStorageAllocationRequest(data); + const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); + const interceptMode = normalizeBooleanFlag(data && data.interceptMode, false); + + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 规范化入参', { + warehouseId, + orderIds, + forbiddenWarehouseKeys, + }); + + if (forbiddenWarehouseKeys.length > 0) { + throw new Error('待处理订单储位取消分配接口不再接受 warehouse_id / warehouseId,请使用当前用户仓库上下文'); + } + + if (warehouseId <= 0) { + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 缺少仓库上下文,直接返回', { + warehouseId, + orderIds, + }); + return { + code: 400, + message: '缺少仓库上下文', + data: null, + }; + } + + if (orderIds.length === 0) { + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 订单ID为空,直接返回', { + warehouseId, + orderIds, + }); + return { + code: 400, + message: '订单ID不能为空', + data: null, + }; + } + + // 支持外部事务:由调用方(如取消订单流程)传入时复用,保证"取消+释放"原子生效 + const externalTransaction = data && data.transaction ? data.transaction : null; + const transaction = externalTransaction || await ctx.model.transaction(); + const { Op } = app.Sequelize; + const now = new Date(); + + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务已创建', { + warehouseId, + orderIds, + hasExternalTransaction: Boolean(externalTransaction), + }); + + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const pickingModel = ctx.model.Picking; + const storageModel = ctx.model.Storage; + + if (!pickingModel || typeof pickingModel.findAll !== 'function' || typeof pickingModel.destroy !== 'function') { + throw new Error('wms_picking 模型不可用'); + } + + if (!storageModel || typeof storageModel.findAll !== 'function') { + throw new Error('wms_storage 模型不可用'); + } + + 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 skippedOrders = []; + const eligibleOrderIds = []; + // 拦截模式:无拣货行(含已软删)或储位已释放但已同步出库的订单, + // 按订单明细补建拦截锁承接总量差,避免可用数漂移 + const interceptNoPickingOrderIds = []; + + for (const orderId of orderIds) { + const orderRow = orderMap.get(orderId); + + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 过滤订单前', { + orderId, + hasOrderRow: Boolean(orderRow), + storageStatus: orderRow ? orderRow.storage_status : null, + }); + + if (!orderRow) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + skipped_reason: 'not_found', + }); + continue; + } + + if (String(orderRow.storage_status || 'none') !== STORAGE_STATUS_FIN) { + // 拦截确认模式:储位已释放但已同步出库的订单(stock 层已扣、storage 层无锁可迁) + // 不直接跳过,登记为拦截锁补建候选,保证可用数守恒 + if (interceptMode && String(orderRow.sync_status || '').trim() === 'fin') { + interceptNoPickingOrderIds.push(orderId); + } + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + storage_status: orderRow.storage_status, + skipped_reason: 'not_allocated', + }); + continue; + } + + eligibleOrderIds.push(orderId); + } + + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 订单过滤完成', { + requestedOrderIds: orderIds, + eligibleOrderIds, + skippedOrders, + }); + + if (eligibleOrderIds.length === 0) { + // 拦截模式下存在无拣货行补建候选(储位已释放但已同步出库)时, + // 继续执行拦截分支完成拦截锁补建,保证可用数守恒 + const hasNoPickingCompensate = interceptMode && interceptNoPickingOrderIds.length > 0; + if (!hasNoPickingCompensate) { + if (!externalTransaction) { + await transaction.commit(); + } + return { + code: 200, + message: '没有需要取消分配的订单', + data: { + warehouse_id: warehouseId, + requested_order_ids: orderIds, + cancellable_order_ids: [], + skipped_orders: skippedOrders, + orders: skippedOrders, + picking_count: 0, + storage_unlock_summary: [], + storage_return_summary: [], + stock_unlock_summary: [], + }, + }; + } + } + + const pickingRows = await pickingModel.findAll({ + where: { + order_id: { + [Op.in]: eligibleOrderIds, + }, + warehouse_id: warehouseId, + status: { + [Op.ne]: 'cancel', + }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const pickingRowsByOrderId = new Map(); + const pendingStorageQuantityMap = new Map(); + const finStorageQuantityMap = new Map(); + const storageIdSet = new Set(); + // 拦截模式(interceptMode)按 (order_id, storage_id) 维度记录数量,供拦截锁迁移与按单回落使用 + const interceptPendingQuantityMap = new Map(); + const interceptFinQuantityMap = new Map(); + // 拦截模式拣货行元信息(space_id/stock_id),供缺行补建 storage 使用 + const interceptPickingMetaMap = new Map(); + + for (const pickingRow of Array.isArray(pickingRows) ? pickingRows : []) { + const plainPicking = toPlainRecord(pickingRow); + const orderId = toNumber(plainPicking?.order_id, 0); + const storageId = toNumber(plainPicking?.storage_id, 0); + const quantity = toNumber(plainPicking?.quantity, 0); + + if (orderId <= 0 || storageId <= 0 || quantity <= 0) { + continue; + } + + const orderPickingRows = pickingRowsByOrderId.get(orderId) || []; + orderPickingRows.push(plainPicking); + pickingRowsByOrderId.set(orderId, orderPickingRows); + + storageIdSet.add(storageId); + // 按状态分流:pending 记录解除锁定(实物不动); + // fin 记录(已拣货)返还实物数量,锁定已在拣货完成时扣减,不再重复扣除 + const pickingStatus = String(plainPicking?.status || '').trim(); + const interceptPairKey = `${orderId}:${storageId}`; + if (!interceptPickingMetaMap.has(interceptPairKey)) { + interceptPickingMetaMap.set(interceptPairKey, { + space_id: toNumber(plainPicking?.space_id, 0), + stock_id: toNumber(plainPicking?.stock_id, 0), + }); + } + if (pickingStatus === 'fin') { + finStorageQuantityMap.set(storageId, (finStorageQuantityMap.get(storageId) || 0) + quantity); + interceptFinQuantityMap.set(interceptPairKey, (interceptFinQuantityMap.get(interceptPairKey) || 0) + quantity); + } else { + pendingStorageQuantityMap.set(storageId, (pendingStorageQuantityMap.get(storageId) || 0) + quantity); + interceptPendingQuantityMap.set(interceptPairKey, (interceptPendingQuantityMap.get(interceptPairKey) || 0) + quantity); + } + } + + const cancellableOrderIds = []; + for (const orderId of eligibleOrderIds) { + if (pickingRowsByOrderId.has(orderId)) { + cancellableOrderIds.push(orderId); + continue; + } + + if (interceptMode) { + // 拦截确认:储位状态为 fin 但无拣货行(已软删/已删除)的订单不跳过, + // 按订单明细补建拦截锁,承接同步出库造成的总量差 + cancellableOrderIds.push(orderId); + interceptNoPickingOrderIds.push(orderId); + continue; + } + + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + storage_status: 'fin', + skipped_reason: 'no_allocation', + }); + } + + if (cancellableOrderIds.length === 0) { + // 拦截模式下存在无拣货行补建候选(储位已释放但已同步出库)时, + // 继续执行拦截分支完成拦截锁补建,保证可用数守恒 + const hasNoPickingCompensate = interceptMode && interceptNoPickingOrderIds.length > 0; + if (!hasNoPickingCompensate) { + if (!externalTransaction) { + await transaction.commit(); + } + return { + code: 200, + message: '没有需要取消分配的订单', + data: { + warehouse_id: warehouseId, + requested_order_ids: orderIds, + cancellable_order_ids: [], + skipped_orders: skippedOrders, + orders: skippedOrders, + picking_count: 0, + storage_unlock_summary: [], + storage_return_summary: [], + stock_unlock_summary: [], + }, + }; + } + } + + const storageRows = await storageModel.findAll({ + where: { + id: { + [Op.in]: Array.from(storageIdSet), + }, + warehouse_id: warehouseId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const storageMap = new Map(); + for (const storageRow of Array.isArray(storageRows) ? storageRows : []) { + const plainStorage = toPlainRecord(storageRow); + if (!plainStorage || !Number(plainStorage.id)) { + continue; + } + + storageMap.set(Number(plainStorage.id), plainStorage); + } + + const storageUnlockSummary = []; + const storageReturnSummary = []; + // 拦截模式无拣货行补建汇总(storage_id -> 补建拦截锁数量),随响应返回供对账追溯 + const interceptCompensateSummaryMap = new Map(); + + if (interceptMode) { + // ── 拦截模式:库存不归还可用,移入拦截锁定字段(intercept_locked_quantity) ── + const interceptUnlockSummaryMap = new Map(); + const interceptReturnSummaryMap = new Map(); + // 按 storage 累计本批次已迁移的锁定/拦截锁定/实物数量变化,保证同库存多订单时流水快照准确 + const interceptLockedDeltaMap = new Map(); + const interceptLockedChangeMap = new Map(); + const interceptQuantityChangeMap = new Map(); + + // 仓库默认库位(缺行补建时使用):优先仓库配置 default_location_id,未设置兜底 1 + let fallbackDefaultSpaceId = 1; + try { + const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder; + const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function' + ? await deliveryOrderService.getStoreSubjectConfig(warehouseId) + : null; + const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0); + if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) { + fallbackDefaultSpaceId = configuredLocationId; + } + } catch (defaultSpaceErr) { + ctx.logger.warn( + `[order_storage_allocation.cancelAllocateStorage] 读取仓库默认库位失败,兜底库位 1: ${defaultSpaceErr.message}` + ); + } + + // pending 记录:作业锁迁移为拦截锁(locked -q、intercept +q、quantity 不变、available 不变) + for (const [ pairKey, quantity ] of interceptPendingQuantityMap.entries()) { + if (quantity <= 0) { + continue; + } + + const [ orderId, storageId ] = pairKey.split(':').map(part => toNumber(part, 0)); + if (orderId <= 0 || storageId <= 0) { + continue; + } + + let storageRow = storageMap.get(storageId); + const orderRow = orderMap.get(orderId) || {}; + const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim() + || 'INTERCEPT_CONFIRM'; + const pickingMeta = interceptPickingMetaMap.get(pairKey) || {}; + + if (!storageRow) { + // 拦截确认缺行补建:货物在库,直接以拦截锁定入账(quantity=q、intercept=q、available=0) + const created = await storageModel.create({ + warehouse_id: warehouseId, + store_id: toNumber(orderRow.store_id, 0) || null, + space_id: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId, + stock_id: toNumber(pickingMeta.stock_id, 0) || 0, + batch_no: String(orderNo).slice(0, 100), + inventory_type: 'ZP', + quantity, + locked_quantity: 0, + intercept_locked_quantity: quantity, + available_quantity: 0, + inbound_time: now, + inbound_order_no: String(orderNo).slice(0, 100), + is_enabled: 1, + created_at: now, + updated_at: now, + }, { transaction }); + const plainCreated = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + storageMap.set(Number(plainCreated.id), plainCreated); + storageRow = plainCreated; + + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式缺行补建库存行', { + orderId, + storageId, + createdStorageId: plainCreated.id, + quantity, + spaceId: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId, + }); + + // 直接写拦截锁定流水(补建行:before=0 → after=quantity) + await ctx.model.StorageTransaction.create({ + transaction_type: 'LOCK', + warehouse_id: warehouseId, + store_id: plainCreated.store_id, + stock_id: plainCreated.stock_id, + storage_id: plainCreated.id, + space_id: plainCreated.space_id, + quantity, + before_quantity: quantity, + after_quantity: quantity, + before_locked_quantity: 0, + after_locked_quantity: 0, + before_intercept_locked_quantity: 0, + after_intercept_locked_quantity: quantity, + batch_no: plainCreated.batch_no, + inventory_type: 'ZP', + order_type: 'INTERCEPT_LOCK', + order_no: orderNo, + order_id: orderId, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '拦截确认(缺行补建并拦截锁定)', + }, { transaction }); + + interceptUnlockSummaryMap.set(Number(plainCreated.id), (interceptUnlockSummaryMap.get(Number(plainCreated.id)) || 0) + quantity); + continue; // 补建行已直接入账,跳过既有迁移逻辑 + } + + const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0) + + (interceptLockedDeltaMap.get(storageId) || 0); + const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0) + + (interceptLockedChangeMap.get(storageId) || 0); + + await ctx.service.systems.storage.index.interceptLockQuantity(storageId, quantity, { + transaction, + }); + + interceptLockedDeltaMap.set(storageId, (interceptLockedDeltaMap.get(storageId) || 0) - quantity); + interceptLockedChangeMap.set(storageId, (interceptLockedChangeMap.get(storageId) || 0) + quantity); + + // 写入拦截锁定流水(作业锁迁移为拦截锁,记录拦截快照) + await ctx.model.StorageTransaction.create({ + transaction_type: 'LOCK', + warehouse_id: warehouseId, + store_id: storageRow.store_id, + stock_id: storageRow.stock_id, + storage_id: storageId, + space_id: storageRow.space_id, + quantity, + before_quantity: storageRow.quantity, + after_quantity: storageRow.quantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: beforeLockedQuantity - quantity, + before_intercept_locked_quantity: beforeInterceptLockedQuantity, + after_intercept_locked_quantity: beforeInterceptLockedQuantity + quantity, + batch_no: storageRow.batch_no, + inventory_type: storageRow.inventory_type, + order_type: 'INTERCEPT_LOCK', + order_no: orderNo, + order_id: orderId, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '拦截确认(作业锁迁移为拦截锁)', + }, { transaction }); + + interceptUnlockSummaryMap.set(storageId, (interceptUnlockSummaryMap.get(storageId) || 0) + quantity); + } + + // fin 记录(已拣货):实物返还并拦截锁定(quantity +q、intercept +q、available 不变) + for (const [ pairKey, returnQuantity ] of interceptFinQuantityMap.entries()) { + if (returnQuantity <= 0) { + continue; + } + + const [ orderId, storageId ] = pairKey.split(':').map(part => toNumber(part, 0)); + if (orderId <= 0 || storageId <= 0) { + continue; + } + + let storageRow = storageMap.get(storageId); + const orderRow = orderMap.get(orderId) || {}; + const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim() + || 'INTERCEPT_CONFIRM'; + const pickingMeta = interceptPickingMetaMap.get(pairKey) || {}; + + if (!storageRow) { + // 拦截确认缺行补建:实物返还并拦截锁定(quantity=q、intercept=q、available=0) + const created = await storageModel.create({ + warehouse_id: warehouseId, + store_id: toNumber(orderRow.store_id, 0) || null, + space_id: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId, + stock_id: toNumber(pickingMeta.stock_id, 0) || 0, + batch_no: String(orderNo).slice(0, 100), + inventory_type: 'ZP', + quantity: returnQuantity, + locked_quantity: 0, + intercept_locked_quantity: returnQuantity, + available_quantity: 0, + inbound_time: now, + inbound_order_no: String(orderNo).slice(0, 100), + is_enabled: 1, + created_at: now, + updated_at: now, + }, { transaction }); + const plainCreated = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + storageMap.set(Number(plainCreated.id), plainCreated); + storageRow = plainCreated; + + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式缺行补建库存行(fin)', { + orderId, + storageId, + createdStorageId: plainCreated.id, + returnQuantity, + }); + + // 直接写拦截锁定流水(补建行:before=0 → after=returnQuantity) + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: plainCreated.store_id, + stock_id: plainCreated.stock_id, + storage_id: plainCreated.id, + space_id: plainCreated.space_id, + quantity: returnQuantity, + before_quantity: returnQuantity, + after_quantity: returnQuantity, + before_locked_quantity: 0, + after_locked_quantity: 0, + before_intercept_locked_quantity: 0, + after_intercept_locked_quantity: returnQuantity, + batch_no: plainCreated.batch_no, + inventory_type: 'ZP', + order_type: 'INTERCEPT_LOCK', + order_no: orderNo, + order_id: orderId, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '拦截确认(缺行补建实物返还并拦截锁定)', + }, { transaction }); + + interceptReturnSummaryMap.set(Number(plainCreated.id), (interceptReturnSummaryMap.get(Number(plainCreated.id)) || 0) + returnQuantity); + continue; // 补建行已直接入账,跳过既有返还逻辑 + } + + const beforeQuantity = toNumber(storageRow.quantity, 0) + + (interceptQuantityChangeMap.get(storageId) || 0); + const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); + const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0) + + (interceptLockedChangeMap.get(storageId) || 0); + + await ctx.service.systems.storage.index.interceptReceiveQuantity(storageId, returnQuantity, { + transaction, + }); + + interceptQuantityChangeMap.set(storageId, (interceptQuantityChangeMap.get(storageId) || 0) + returnQuantity); + interceptLockedChangeMap.set(storageId, (interceptLockedChangeMap.get(storageId) || 0) + returnQuantity); + + // 写入拦截锁定流水(实物返还并拦截锁定,记录拦截快照) + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storageRow.store_id, + stock_id: storageRow.stock_id, + storage_id: storageId, + space_id: storageRow.space_id, + quantity: returnQuantity, + before_quantity: beforeQuantity, + after_quantity: beforeQuantity + returnQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: beforeLockedQuantity, + before_intercept_locked_quantity: beforeInterceptLockedQuantity, + after_intercept_locked_quantity: beforeInterceptLockedQuantity + returnQuantity, + batch_no: storageRow.batch_no, + inventory_type: storageRow.inventory_type, + order_type: 'INTERCEPT_LOCK', + order_no: orderNo, + order_id: orderId, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '拦截确认(已拣货实物返还并拦截锁定)', + }, { transaction }); + + interceptReturnSummaryMap.set(storageId, (interceptReturnSummaryMap.get(storageId) || 0) + returnQuantity); + } + + for (const [ storageId, quantity ] of interceptUnlockSummaryMap.entries()) { + storageUnlockSummary.push({ storage_id: storageId, unlocked_quantity: quantity }); + } + for (const [ storageId, quantity ] of interceptReturnSummaryMap.entries()) { + storageReturnSummary.push({ storage_id: storageId, returned_quantity: quantity }); + } + + // ── 拦截模式无拣货行补建:拣货行已被删除/软删(取消储位分配等路径)的订单, ── + // ── 同步出库已在 stock 层扣减而 storage 层从未扣,拦截锁无行可迁。 ── + // ── 按订单明细数量补建拦截锁(intercept +q、available -q、quantity 不变), ── + // ── 确保可用数守恒:storage 可用 === stock 可用。 ── + if (interceptNoPickingOrderIds.length > 0) { + const orderItemsModel = ctx.model && ctx.model.OrderItemsFactory + && typeof ctx.model.OrderItemsFactory.getCurrentModel === 'function' + ? await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId) + : null; + + if (!orderItemsModel) { + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式无拣货行补建跳过:订单明细模型不可用', { + interceptNoPickingOrderIds, + }); + } else { + const noPickingOrderItems = await orderItemsModel.findAll({ + where: { + order_id: { [Op.in]: interceptNoPickingOrderIds }, + }, + attributes: [ 'order_id', 'stock_id', 'plan_qty' ], + raw: true, + transaction, + }); + + // 按 (order_id, stock_id) 汇总补建量 + const compensatePlanMap = new Map(); // orderId -> [{ stockId, qty }] + for (const item of Array.isArray(noPickingOrderItems) ? noPickingOrderItems : []) { + const itemOrderId = toNumber(item && item.order_id, 0); + const stockId = toNumber(item && item.stock_id, 0); + const qty = toNumber(item && item.plan_qty, 0); + if (itemOrderId <= 0 || stockId <= 0 || qty <= 0) { + continue; + } + const plans = compensatePlanMap.get(itemOrderId) || []; + const existing = plans.find(p => p.stockId === stockId); + if (existing) { + existing.qty += qty; + } else { + plans.push({ stockId, qty }); + } + compensatePlanMap.set(itemOrderId, plans); + } + + // 逐商品查询可用库存行(有行挂锁,无行补建行),并写拦截锁定流水 + for (const orderId of interceptNoPickingOrderIds) { + const plans = compensatePlanMap.get(orderId) || []; + if (plans.length === 0) { + continue; + } + const orderRow = orderMap.get(orderId) || {}; + const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim() + || 'INTERCEPT_CONFIRM'; + const orderStoreId = toNumber(orderRow.store_id, 0) || null; + + for (const plan of plans) { + const { stockId, qty } = plan; + + // 优先找该商品数量最多的未删除行挂锁,保证拦截锁落在真实库存行上 + const candidateRows = await storageModel.findAll({ + where: { + stock_id: stockId, + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }, + order: [[ 'quantity', 'DESC' ]], + lock: transaction ? transaction.LOCK.UPDATE : undefined, + raw: true, + transaction, + }); + + if (candidateRows.length > 0) { + const targetRow = candidateRows[0]; + const beforeInterceptLockedQuantity = toNumber(targetRow.intercept_locked_quantity, 0); + + await ctx.service.systems.storage.index.updateQuantity( + Number(targetRow.id), + 0, + 0, + { transaction, interceptLockedChange: qty } + ); + + await ctx.model.StorageTransaction.create({ + transaction_type: 'LOCK', + warehouse_id: warehouseId, + store_id: Number(targetRow.store_id) || orderStoreId, + stock_id: stockId, + storage_id: Number(targetRow.id), + space_id: Number(targetRow.space_id) || null, + quantity: qty, + before_quantity: Number(targetRow.quantity) || 0, + after_quantity: Number(targetRow.quantity) || 0, + before_locked_quantity: Number(targetRow.locked_quantity) || 0, + after_locked_quantity: Number(targetRow.locked_quantity) || 0, + before_intercept_locked_quantity: beforeInterceptLockedQuantity, + after_intercept_locked_quantity: beforeInterceptLockedQuantity + qty, + batch_no: targetRow.batch_no || null, + inventory_type: targetRow.inventory_type || 'ZP', + order_type: 'INTERCEPT_LOCK', + order_no: orderNo, + order_id: orderId, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '拦截确认(无拣货行补建拦截锁定)', + }, { transaction }); + + interceptCompensateSummaryMap.set( + Number(targetRow.id), + (interceptCompensateSummaryMap.get(Number(targetRow.id)) || 0) + qty + ); + } else { + // 该商品没有任何库存行:按缺行补建(quantity=q、intercept=q、available=0) + const created = await storageModel.create({ + warehouse_id: warehouseId, + store_id: orderStoreId, + space_id: fallbackDefaultSpaceId, + stock_id: stockId, + batch_no: String(orderNo).slice(0, 100), + inventory_type: 'ZP', + quantity: qty, + locked_quantity: 0, + intercept_locked_quantity: qty, + available_quantity: 0, + inbound_time: now, + inbound_order_no: String(orderNo).slice(0, 100), + is_enabled: 1, + created_at: now, + updated_at: now, + }, { transaction }); + const plainCreated = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + + await ctx.model.StorageTransaction.create({ + transaction_type: 'LOCK', + warehouse_id: warehouseId, + store_id: plainCreated.store_id, + stock_id: stockId, + storage_id: plainCreated.id, + space_id: plainCreated.space_id, + quantity: qty, + before_quantity: qty, + after_quantity: qty, + before_locked_quantity: 0, + after_locked_quantity: 0, + before_intercept_locked_quantity: 0, + after_intercept_locked_quantity: qty, + batch_no: plainCreated.batch_no, + inventory_type: 'ZP', + order_type: 'INTERCEPT_LOCK', + order_no: orderNo, + order_id: orderId, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '拦截确认(无拣货行补建库存行并拦截锁定)', + }, { transaction }); + + interceptCompensateSummaryMap.set( + Number(plainCreated.id), + (interceptCompensateSummaryMap.get(Number(plainCreated.id)) || 0) + qty + ); + } + } + } + + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式无拣货行补建完成', { + interceptNoPickingOrderIds, + interceptCompensateSummary: Array.from(interceptCompensateSummaryMap.entries()), + }); + } + } + } else { + // ── 普通取消模式:解除锁定/返还实物,回到可用数量(既有行为不变) ── + // pending 记录:解除锁定,实物库存不动 + for (const [ storageId, quantity ] of pendingStorageQuantityMap.entries()) { + if (quantity <= 0) { + continue; + } + + const storageRow = storageMap.get(storageId); + if (!storageRow) { + throw new Error(`库存记录不存在: ${storageId}`); + } + + const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); + const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0); + + await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { + transaction, + }); + + // 写入储位解锁流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'UNLOCK', + warehouse_id: warehouseId, + store_id: storageRow.store_id, + stock_id: storageRow.stock_id, + storage_id: storageId, + space_id: storageRow.space_id, + quantity, + before_quantity: storageRow.quantity, + after_quantity: storageRow.quantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: beforeLockedQuantity - quantity, + before_intercept_locked_quantity: beforeInterceptLockedQuantity, + after_intercept_locked_quantity: beforeInterceptLockedQuantity, + batch_no: storageRow.batch_no, + inventory_type: storageRow.inventory_type, + order_type: 'PICKING_UNLOCK', + order_no: 'CANCEL_BATCH', + order_id: 0, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '取消分配储位(库存解锁)', + }, { transaction }); + + storageUnlockSummary.push({ + storage_id: storageId, + unlocked_quantity: quantity, + }); + } + + // fin 记录(已拣货):返还实物数量,锁定已在拣货完成时扣减,不再重复扣除 + for (const [ storageId, returnQuantity ] of finStorageQuantityMap.entries()) { + if (returnQuantity <= 0) { + continue; + } + + const storageRow = storageMap.get(storageId); + if (!storageRow) { + throw new Error(`库存记录不存在: ${storageId}`); + } + + const beforeQuantity = toNumber(storageRow.quantity, 0); + const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); + const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0); + + await ctx.service.systems.storage.index.updateQuantity(storageId, returnQuantity, 0, { + transaction, + }); + + // 写入库存返还流水(实物数量增加,锁定不变) + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storageRow.store_id, + stock_id: storageRow.stock_id, + storage_id: storageId, + space_id: storageRow.space_id, + quantity: returnQuantity, + before_quantity: beforeQuantity, + after_quantity: beforeQuantity + returnQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: beforeLockedQuantity, + before_intercept_locked_quantity: beforeInterceptLockedQuantity, + after_intercept_locked_quantity: beforeInterceptLockedQuantity, + batch_no: storageRow.batch_no, + inventory_type: storageRow.inventory_type, + order_type: 'PICK_RETURN', + order_no: 'CANCEL_BATCH', + order_id: 0, + operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', + remark: '取消分配储位(已拣货返还库存)', + }, { transaction }); + + storageReturnSummary.push({ + storage_id: storageId, + returned_quantity: returnQuantity, + }); + } + } + + const cancelPickingIds = []; + for (const orderId of cancellableOrderIds) { + const orderPickingRows = pickingRowsByOrderId.get(orderId) || []; + cancelPickingIds.push(...orderPickingRows.map(row => toNumber(row.id, 0)).filter(pickingId => pickingId > 0)); + } + + if (cancelPickingIds.length > 0) { + await pickingModel.destroy({ + where: { + id: { + [Op.in]: cancelPickingIds, + }, + }, + transaction, + }); + } + + const cancelOrderWhere = { + id: { + [Op.in]: cancellableOrderIds, + }, + warehouse_id: warehouseId, + }; + + await orderModel.update({ + storage_status: 'none', + order_flag: '', + updated_at: now, + }, { + where: cancelOrderWhere, + transaction, + }); + + const updatedOrders = await orderModel.findAll({ + where: cancelOrderWhere, + transaction, + raw: true, + }); + + const updatedOrderMap = new Map(); + for (const updatedOrder of Array.isArray(updatedOrders) ? updatedOrders : []) { + const plainOrder = toPlainRecord(updatedOrder); + if (!plainOrder || !Number(plainOrder.id)) { + continue; + } + + updatedOrderMap.set(Number(plainOrder.id), plainOrder); + } + + const orderResults = cancellableOrderIds + .map(orderId => updatedOrderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + order_id: order.id, + storage_status: order.storage_status, + order_flag: order.order_flag || '', + status: 'success', + })); + + const responseData = { + warehouse_id: warehouseId, + requested_order_ids: orderIds, + cancellable_order_ids: cancellableOrderIds, + skipped_orders: skippedOrders, + orders: [ ...skippedOrders, ...orderResults ], + picking_count: cancelPickingIds.length, + storage_unlock_summary: storageUnlockSummary, + storage_return_summary: storageReturnSummary, + intercept_compensate_summary: Array.from(interceptCompensateSummaryMap.entries()) + .map(([ storageId, quantity ]) => ({ storage_id: storageId, intercept_locked_quantity: quantity })), + stock_unlock_summary: [], + }; + + if (!externalTransaction) { + await transaction.commit(); + } + + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务提交完成', { + warehouseId, + requestedOrderIds: orderIds, + cancellableOrderIds, + skippedOrders, + }); + + return { + code: 200, + message: '取消分配完成', + data: responseData, + }; + } catch (error) { + if (!externalTransaction) { + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 发生异常,准备回滚事务', { + warehouseId, + orderIds, + error, + }); + await transaction.rollback(); + writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务回滚完成', { + warehouseId, + orderIds, + error, + }); + } + throw error; + } + } + + /** + * 按订单 ID 释放拦截锁定数量(拦截锁回落到可用数量)。 + * + * 依据 wms_storage_transaction 中 order_type='INTERCEPT_LOCK' 与 + * order_type='INTERCEPT_UNLOCK' 的流水按 (storage_id, order_id) 汇总净拦截量, + * 净量大于 0 时逐库存行调用 interceptUnlockQuantity 释放拦截锁: + * `intercept_locked_quantity -q`、`available_quantity +q`,`quantity` 与 `locked_quantity` 不变, + * 并写入 INTERCEPT_UNLOCK 流水记录拦截快照(order_id 与订单对应)。 + * 释放量与流水均以订单维度记录,重复调用幂等(净量归零后不再释放)。 + * + * 使用场景: + * - 批量解除拦截(batchUnintercept 后台任务); + * - 退货登记完成(return_received.create)。 + * + * @param {Array} orderIds 订单 ID 数组。 + * @param {Object} [options={}] 执行上下文参数。 + * @param {number|string} [options.warehouseId] 仓库 ID,缺省取当前用户仓库上下文。 + * @param {Object} [options.transaction] 外部事务对象,缺省内部创建事务。 + * @param {string} [options.scene='INTERCEPT_UNLOCK'] 释放场景标识(写入流水 order_no)。 + * @param {string} [options.remark='解除拦截(拦截锁回落到可用数量)'] 流水备注。 + * @param {string} [options.operatorId] 操作人工号 ID,缺省取当前用户上下文。 + * @param {string} [options.operatorName] 操作人名称,缺省取当前用户上下文。 + * @return {Promise} 释放结果,含 order_ids、released_quantity、storage_release_summary。 + */ + async releaseInterceptLocksByOrderIds(orderIds = [], options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const normalizedOrderIds = Array.from(new Set( + (Array.isArray(orderIds) ? orderIds : []) + .map(orderId => toNumber(orderId, 0)) + .filter(orderId => orderId > 0) + )); + + if (normalizedOrderIds.length === 0) { + return { + order_ids: [], + released_quantity: 0, + storage_release_summary: [], + }; + } + + const warehouseId = toNumber(options.warehouseId, 0) > 0 + ? toNumber(options.warehouseId, 0) + : toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); + + if (warehouseId <= 0) { + throw new Error('缺少仓库上下文'); + } + + const scene = String(options.scene || 'INTERCEPT_UNLOCK').trim() || 'INTERCEPT_UNLOCK'; + const remark = String(options.remark || '解除拦截(拦截锁回落到可用数量)').trim(); + const operatorId = String(options.operatorId ?? ctx.user?.employees_id ?? ctx.user?.id ?? ''); + const operatorName = String( + options.operatorName ?? ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '' + ); + + const externalTransaction = options.transaction || null; + const transaction = externalTransaction || await ctx.model.transaction(); + + try { + const groupAttributes = [ + 'storage_id', + 'order_id', + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], + ]; + + // 汇总本批次订单的拦截锁定流水(按 storage_id + order_id 分组) + const lockRows = await ctx.model.StorageTransaction.findAll({ + attributes: groupAttributes, + where: { + warehouse_id: warehouseId, + order_type: 'INTERCEPT_LOCK', + order_id: { [Op.in]: normalizedOrderIds }, + }, + group: [ 'storage_id', 'order_id' ], + transaction, + raw: true, + }); + + const netQuantityMap = new Map(); + for (const row of Array.isArray(lockRows) ? lockRows : []) { + const pairKey = `${toNumber(row.order_id, 0)}:${toNumber(row.storage_id, 0)}`; + netQuantityMap.set(pairKey, toNumber(row.total_quantity, 0)); + } + + if (netQuantityMap.size === 0) { + if (!externalTransaction) { + await transaction.commit(); + } + return { + order_ids: normalizedOrderIds, + released_quantity: 0, + storage_release_summary: [], + }; + } + + const storageIdSet = new Set(); + for (const pairKey of netQuantityMap.keys()) { + const storageId = toNumber(pairKey.split(':')[1], 0); + if (storageId > 0) { + storageIdSet.add(storageId); + } + } + + // 汇总已释放的拦截解锁流水(同一订单维度),净量 = 锁定 - 已释放,保证幂等 + const unlockRows = await ctx.model.StorageTransaction.findAll({ + attributes: groupAttributes, + where: { + warehouse_id: warehouseId, + order_type: 'INTERCEPT_UNLOCK', + order_id: { [Op.in]: normalizedOrderIds }, + storage_id: { [Op.in]: Array.from(storageIdSet) }, + }, + group: [ 'storage_id', 'order_id' ], + transaction, + raw: true, + }); + + for (const row of Array.isArray(unlockRows) ? unlockRows : []) { + const pairKey = `${toNumber(row.order_id, 0)}:${toNumber(row.storage_id, 0)}`; + netQuantityMap.set(pairKey, (netQuantityMap.get(pairKey) || 0) - toNumber(row.total_quantity, 0)); + } + + // 行锁查询库存,并维护每库存行的剩余可释放拦截量,防止多订单同库存行超释 + const storageRows = await ctx.model.Storage.findAll({ + where: { + id: { [Op.in]: Array.from(storageIdSet) }, + warehouse_id: warehouseId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const storageMap = new Map(); + const remainingInterceptByStorage = new Map(); + for (const row of Array.isArray(storageRows) ? storageRows : []) { + const storageId = toNumber(row.id, 0); + storageMap.set(storageId, row); + remainingInterceptByStorage.set(storageId, toNumber(row.intercept_locked_quantity, 0)); + } + + const storageReleaseSummary = []; + let releasedQuantity = 0; + // 已释放拦截量(按 storage 累计),保证同库存行多订单时流水 before/after 快照准确 + const releasedInterceptByStorage = new Map(); + + for (const [ pairKey, netQuantity ] of netQuantityMap.entries()) { + if (netQuantity <= 0) { + continue; + } + + const pairParts = pairKey.split(':'); + const orderId = toNumber(pairParts[0], 0); + const storageId = toNumber(pairParts[1], 0); + if (orderId <= 0 || storageId <= 0) { + continue; + } + + const storageRow = storageMap.get(storageId); + if (!storageRow) { + continue; + } + + const storageRemaining = remainingInterceptByStorage.get(storageId) || 0; + const releaseQuantity = Math.min(netQuantity, storageRemaining); + if (releaseQuantity <= 0) { + continue; + } + + const beforeQuantity = toNumber(storageRow.quantity, 0); + const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); + const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0) + - (releasedInterceptByStorage.get(storageId) || 0); + + await ctx.service.systems.storage.index.interceptUnlockQuantity(storageId, releaseQuantity, { + transaction, + }); + + // 写入拦截解锁流水(记录拦截快照,order_id 与订单对应) + await ctx.model.StorageTransaction.create({ + transaction_type: 'UNLOCK', + warehouse_id: warehouseId, + store_id: storageRow.store_id, + stock_id: storageRow.stock_id, + storage_id: storageId, + space_id: storageRow.space_id, + quantity: releaseQuantity, + before_quantity: beforeQuantity, + after_quantity: beforeQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: beforeLockedQuantity, + before_intercept_locked_quantity: beforeInterceptLockedQuantity, + after_intercept_locked_quantity: beforeInterceptLockedQuantity - releaseQuantity, + batch_no: storageRow.batch_no, + inventory_type: storageRow.inventory_type, + order_type: 'INTERCEPT_UNLOCK', + order_no: scene, + order_id: orderId, + operator_id: operatorId, + operator_name: operatorName, + remark, + }, { transaction }); + + remainingInterceptByStorage.set(storageId, storageRemaining - releaseQuantity); + releasedInterceptByStorage.set(storageId, (releasedInterceptByStorage.get(storageId) || 0) + releaseQuantity); + releasedQuantity += releaseQuantity; + storageReleaseSummary.push({ + storage_id: storageId, + order_id: orderId, + released_quantity: releaseQuantity, + }); + } + + if (!externalTransaction) { + await transaction.commit(); + } + + return { + order_ids: normalizedOrderIds, + released_quantity: releasedQuantity, + storage_release_summary: storageReleaseSummary, + }; + } catch (error) { + if (!externalTransaction) { + await transaction.rollback(); + } + throw error; + } + } + /** + * 分拣缺货补货需求计算。 + * + * 仓库级别的计算,针对当前仓库所有未完成储位分配的订单, + * 计算每个 SKU 在分拣区与存货区的可用库存对比, + * 输出分拣区缺口及建议补货量,供仓库人员决策移库。 + * + * 入参: + * - `warehouse_id`(可选):仓库 ID,不传则使用当前用户上下文 + * + * @param {Object} data 请求体。 + * @return {Promise} 补货需求明细与汇总信息。 + * `list` 每项包含 `is_true_shortage`(两区均无库存时为 true), + * `summary` 包含 `total_true_shortage_skus`(真正缺货的 SKU 数量)。 + */ +} + +module.exports = OrderStorageAllocationService; diff --git a/app/service/systems/pack_task_auto_finish.js b/app/service/systems/pack_task_auto_finish.js new file mode 100644 index 0000000..6eb0f50 --- /dev/null +++ b/app/service/systems/pack_task_auto_finish.js @@ -0,0 +1,142 @@ +'use strict'; + +const MainService = require('../main'); +const { Op } = require('sequelize'); + +const PACK_MODE_GROUP = 2; +const PACK_TASK_FINISHED_STATUS = 2; +const MINUTE_MS = 60 * 1000; + +/** + * 打包任务自动结束服务。 + * 扫描 wms_pack_task 未结束任务,按仓库配置的打包最大时长 + * (散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes,单位分钟) + * 判断是否超时,超时则将结束时间置为开始时间 + 上限时长并标记已完成, + * 同时将该工作台关联摄像头的 OSD 叠加复位为「无任务」。 + */ +class PackTaskAutoFinishService extends MainService { + /** + * 执行打包任务自动结束扫描。 + * + * @return {Promise} 处理统计 { total_scanned, warehouse_count, auto_finished }。 + */ + async executeAutoFinishPackTasks() { + const { ctx, app } = this; + const { PackTask } = app.model || {}; + + if (!PackTask || typeof PackTask.findAll !== 'function') { + return { total_scanned: 0, warehouse_count: 0, auto_finished: 0 }; + } + + const nowMs = Date.now(); + + // 1. 扫描所有未结束的打包任务(status < 2,即待处理/打包中),且已有开始时间 + const tasks = await PackTask.findAll({ + where: { + status: { [Op.lt]: PACK_TASK_FINISHED_STATUS }, + start_time: { [Op.ne]: null }, + }, + attributes: [ 'id', 'warehouse_id', 'pack_mode', 'start_time', 'order_id', 'wave_id', 'workbench_id' ], + }); + + if (tasks.length === 0) { + return { total_scanned: 0, warehouse_count: 0, auto_finished: 0 }; + } + + // 2. 按仓库去重后拉取各仓库配置(缓存优先,模型规范化会补齐默认值) + const warehouseIds = [ ...new Set( + tasks + .map(task => Number(task.warehouse_id || 0)) + .filter(warehouseId => Number.isInteger(warehouseId) && warehouseId > 0) + ) ]; + + const configMap = new Map(); + for (const warehouseId of warehouseIds) { + try { + const subjectConfig = await ctx.service.systems.deliveryOrder.getStoreSubjectConfig(warehouseId); + configMap.set(warehouseId, subjectConfig && typeof subjectConfig === 'object' ? subjectConfig : {}); + } catch (error) { + ctx.logger.warn('[packTaskAutoFinish] 读取仓库 %d 配置失败: %s', warehouseId, error.message); + configMap.set(warehouseId, {}); + } + } + + // 3. 逐条判断超时并自动结束 + let autoFinished = 0; + + for (const task of tasks) { + const warehouseId = Number(task.warehouse_id || 0); + const config = configMap.get(warehouseId) || {}; + + const isGroup = Number(task.pack_mode) === PACK_MODE_GROUP; + const limitMinutes = Number( + isGroup ? config.group_order_pack_max_minutes : config.single_order_pack_max_minutes + ); + + // 未配置有效时长(或非法值)的仓库跳过,不做自动结束 + if (!Number.isInteger(limitMinutes) || limitMinutes <= 0) { + continue; + } + + const startMs = new Date(task.start_time).getTime(); + if (!Number.isFinite(startMs)) { + continue; + } + + const limitMs = limitMinutes * MINUTE_MS; + // 仅当 当前时间 - 开始时间 > 上限时长 时自动结束 + if (nowMs - startMs <= limitMs) { + continue; + } + + // 结束时间 = 开始时间 + 上限时长 + const endTime = new Date(startMs + limitMs); + + await task.update({ + end_time: endTime, + status: PACK_TASK_FINISHED_STATUS, + }); + + // 同步关联订单打包状态(与 workbench._finishPack 语义一致,避免任务已完成但订单停留打包中) + const workbenchService = ctx.service && ctx.service.systems && ctx.service.systems.workbench; + if (workbenchService && typeof workbenchService._updateOrderPackStatus === 'function') { + const isGroupTask = Number(task.pack_mode) === PACK_MODE_GROUP; + const taskWaveId = isGroupTask ? Number(task.wave_id || 0) : 0; + await workbenchService._updateOrderPackStatus(warehouseId, { + orderId: Number(task.order_id || 0), + waveId: taskWaveId, + packStatus: PACK_TASK_FINISHED_STATUS, + caller: 'PackTaskAutoFinish', + }); + } + + // 同步工作台 OSD:任务结束后复位为「无任务」(与 workbench._finishPack 语义一致,避免屏幕残留上一个任务文字) + if (workbenchService && typeof workbenchService._resetPackOsd === 'function') { + await workbenchService._resetPackOsd({ + warehouseId, + workbenchId: Number(task.workbench_id || 0), + }); + } + + autoFinished += 1; + + ctx.logger.info( + '[packTaskAutoFinish] 自动结束超时打包任务 taskId=%d warehouseId=%d packMode=%s limitMinutes=%d start=%s end=%s', + task.id, + warehouseId, + isGroup ? 'group' : 'single', + limitMinutes, + new Date(startMs).toISOString(), + endTime.toISOString() + ); + } + + return { + total_scanned: tasks.length, + warehouse_count: warehouseIds.length, + auto_finished: autoFinished, + }; + } +} + +module.exports = PackTaskAutoFinishService; diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js new file mode 100644 index 0000000..b95ddb2 --- /dev/null +++ b/app/service/systems/pick.js @@ -0,0 +1,3518 @@ +'use strict'; + +const Service = require('egg').Service; + +const { INTERCEPT_STATUS_NONE } = require('../../lib/intercept_guard'); + +const REVIEWED_INSPECTION_STATUS = 'fin'; +const PICK_MODE_VIEW_META_MAP = { + 1: { + mode_code: '1', + mode_name: '团购小波次', + require_box_allocations: true, + }, + 2: { + mode_code: '2', + mode_name: '散单单品单件', + require_box_allocations: false, + }, + 3: { + mode_code: '3', + mode_name: '散单先拣后分', + require_box_allocations: true, + }, + 4: { + mode_code: '4', + mode_name: '边拣边分', + require_box_allocations: true, + }, + 5: { + mode_code: '5', + mode_name: '团购大波次', + require_box_allocations: false, + }, +}; + +class PickSystemService extends Service { + /** + * 按仓库获取订单分表模型。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 订单模型对象。 + */ + async getOrderModel(warehouseId) { + const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + throw this.createBusinessError('订单分表模型工厂不可用', 500); + } + + const model = await factory.getCurrentModel(warehouseId); + if (!model || typeof model.findOne !== 'function' || typeof model.findAll !== 'function') { + throw this.createBusinessError('订单分表模型不可用', 500); + } + + return model; + } + + /** + * 生成带业务状态码的错误对象。 + * + * @param {string} message 错误文案。 + * @param {number} [code=400] 错误码。 + * @param {*} [data=null] 附加数据。 + * @return {Error} 错误对象。 + */ + createBusinessError(message, code = 400, data = null) { + const error = new Error(message); + error.code = code; + if (data && typeof data === 'object' && !Array.isArray(data)) { + error.data = data; + } + return error; + } + + /** + * 获取数据表列名集合。 + * + * 用于在不确定列是否存在时进行安全查询拼装,避免因列缺失导致 SQL 执行失败。 + * + * @param {string} tableName 数据表名。 + * @return {Promise>} 列名集合。 + */ + async getTableColumnSet(tableName) { + const { ctx } = this; + const normalizedTableName = String(tableName || '').trim(); + if (!normalizedTableName) { + return new Set(); + } + + const escapedTableName = normalizedTableName.replace(/`/g, '``'); + + try { + const rows = await ctx.model.query(`SHOW COLUMNS FROM \`${escapedTableName}\``, { + type: ctx.model.QueryTypes.SELECT, + }); + return new Set((Array.isArray(rows) ? rows : []) + .map(row => String(row && row.Field || '').trim()) + .filter(Boolean)); + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 获取表字段失败,table=${normalizedTableName},将按兜底处理: ${error.message}`); + return new Set(); + } + } + + /** + * 读取订单商品分表数据并构建索引。 + * + * 优先使用 OrderItemsFactory 当前分表模型;若模型不可用或查询失败,返回空映射而不抛异常。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.orderItemIds 订单明细ID列表。 + * @return {Promise>} 订单明细映射。 + */ + async loadOrderItemMap(params = {}) { + const { ctx } = this; + const warehouseId = Number(params && params.warehouseId || 0); + const orderItemIds = Array.isArray(params && params.orderItemIds) + ? params.orderItemIds.filter(id => Number.isInteger(id) && id > 0) + : []; + + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderItemIds.length === 0) { + return new Map(); + } + + const factory = ctx.model && ctx.model.OrderItemsFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + return new Map(); + } + + try { + const orderItemModel = await factory.getCurrentModel(warehouseId); + if (!orderItemModel || typeof orderItemModel.findAll !== 'function') { + return new Map(); + } + + const orderItemRows = await orderItemModel.findAll({ + where: { + id: { + [this.app.Sequelize.Op.in]: orderItemIds, + }, + }, + attributes: [ 'id', 'item_code', 'item_name', 'stock_id', 'plan_qty', 'item_snapshot', 'owner_code' ], + raw: true, + }); + + return new Map((Array.isArray(orderItemRows) ? orderItemRows : []) + .map(row => [ Number(row && row.id || 0), row ])); + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 订单商品分表查询失败,将按空字段降级: ${error.message}`); + return new Map(); + } + } + + /** + * 解析订单商品快照 JSON。 + * + * item_snapshot 是下单时从 wms_stock_warehouse 抓取的库存快照, + * 其 item_code / item_name 代表下单时的商品信息,比 order_items 列更准确。 + * + * @param {*} rawSnapshot 原始快照数据。 + * @return {Object} 解析后的快照对象。 + */ + parseItemSnapshot(rawSnapshot) { + if (!rawSnapshot) { + return {}; + } + + if (typeof rawSnapshot === 'string') { + try { + const parsed = JSON.parse(rawSnapshot); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; + } catch (_) { + return {}; + } + } + + if (typeof rawSnapshot === 'object' && !Array.isArray(rawSnapshot)) { + return rawSnapshot; + } + + return {}; + } + + /** + * 生成拣货明细汇总信息。 + * + * @param {Array} pickingDetails 拣货明细列表。 + * @return {{total_lines: number, total_qty: number, distinct_spaces: number, distinct_items: number}} 汇总结果。 + */ + buildPickingSummary(pickingDetails = []) { + const normalizedDetails = Array.isArray(pickingDetails) ? pickingDetails : []; + const distinctSpaceIds = new Set(); + const distinctItemKeys = new Set(); + + for (const detail of normalizedDetails) { + const spaceId = Number(detail && detail.space_id || 0); + if (spaceId > 0) { + distinctSpaceIds.add(spaceId); + } + + const itemCode = String(detail && detail.item_code || '').trim(); + const orderItemId = Number(detail && detail.order_item_id || 0); + if (itemCode) { + distinctItemKeys.add(`code:${itemCode}`); + } else if (orderItemId > 0) { + distinctItemKeys.add(`order_item_id:${orderItemId}`); + } + } + + return { + total_lines: normalizedDetails.length, + total_qty: normalizedDetails.reduce((sum, detail) => sum + Number(detail && detail.quantity || 0), 0), + distinct_spaces: distinctSpaceIds.size, + distinct_items: distinctItemKeys.size, + }; + } + + /** + * 获取拣货模式视图元信息。 + * + * @param {number} pickMode 拣货模式编码。 + * @return {{mode_code: number, mode_name: string, require_box_allocations: boolean}} 视图元信息。 + */ + getPickModeViewMeta(pickMode) { + const normalizedPickMode = Number(pickMode || 0); + const baseMeta = PICK_MODE_VIEW_META_MAP[normalizedPickMode] || { + mode_code: normalizedPickMode || 0, + mode_name: '未知模式', + require_box_allocations: false, + }; + + return { + mode_code: Number(baseMeta.mode_code || 0), + mode_name: String(baseMeta.mode_name || '').trim(), + require_box_allocations: Boolean(baseMeta.require_box_allocations), + }; + } + + /** + * 加载订单与波次映射关系。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID列表。 + * @return {Promise>} 订单ID到wave_id映射。 + */ + async loadOrderWaveMap(params = {}) { + const { ctx } = this; + const warehouseId = Number(params && params.warehouseId || 0); + const orderIds = Array.isArray(params && params.orderIds) + ? params.orderIds.filter(id => Number.isInteger(id) && id > 0) + : []; + + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) { + return new Map(); + } + + try { + const orderModel = await this.getOrderModel(warehouseId); + const orderRows = await orderModel.findAll({ + where: { + id: { + [this.app.Sequelize.Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'wave_id' ], + raw: true, + }); + + return new Map((Array.isArray(orderRows) ? orderRows : []) + .map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ]) + .filter(([ orderId, waveId ]) => orderId > 0 && waveId > 0)); + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 订单wave_id查询失败,将按空映射降级: ${error.message}`); + return new Map(); + } + } + + /** + * 构建按拣货模式区分的拣货形态视图。 + * + * @param {Object} params 构建参数。 + * @param {number} params.pickMode 拣货模式。 + * @param {number} params.taskId 任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.pickingDetails 拣货明细。 + * @param {Array} params.boxRows 框明细。 + * @param {Array} params.taskOrderRows 任务订单关联明细。 + * @param {Map} params.boxMapByNo 框号到框信息映射。 + * @return {Promise} picking_view 结构。 + */ + async buildPickingView(params = {}) { + const { ctx } = this; + const pickMode = Number(params && params.pickMode || 0); + const taskId = Number(params && params.taskId || 0); + const warehouseId = Number(params && params.warehouseId || 0); + const pickingDetails = Array.isArray(params && params.pickingDetails) ? params.pickingDetails : []; + const boxRows = Array.isArray(params && params.boxRows) ? params.boxRows : []; + const taskOrderRows = Array.isArray(params && params.taskOrderRows) ? params.taskOrderRows : []; + const boxMapByNo = params && params.boxMapByNo instanceof Map ? params.boxMapByNo : new Map(); + const pickMeta = this.getPickModeViewMeta(pickMode); + + const groupMap = new Map(); + const buildGroupKey = detail => { + const spaceId = Number(detail && detail.space_id || 0); + const itemCode = String(detail && detail.item_code || '').trim(); + const stockId = Number(detail && detail.stock_id || 0); + if (itemCode) { + return `${spaceId}::${itemCode}`; + } + return `${spaceId}::stock_${stockId}`; + }; + + for (const detail of pickingDetails) { + const groupKey = buildGroupKey(detail); + if (!groupMap.has(groupKey)) { + groupMap.set(groupKey, { + space_id: Number(detail && detail.space_id || 0), + space_name: String(detail && detail.space_name || '').trim(), + location_space: detail && detail.location_space ? detail.location_space : null, + item_code: String(detail && detail.item_code || '').trim(), + item_name: String(detail && detail.item_name || '').trim(), + stock_id: Number(detail && detail.stock_id || 0), + total_qty: 0, + box_allocations: [], + details: [], + store_id: detail.store_id != null ? Number(detail.store_id) : 0, + owner_code: String(detail.owner_code || '').trim(), + store_remark: String(detail.store_remark || '').trim(), + stock: detail.stock || null, + }); + } + const groupItem = groupMap.get(groupKey); + groupItem.total_qty += Number(detail && detail.quantity || 0); + groupItem.details.push(detail); + } + + const allocationMapByGroup = new Map(); + const appendAllocation = (groupKey, boxId, allocatedQty) => { + const normalizedBoxId = Number(boxId || 0); + const normalizedQty = Number(allocatedQty || 0); + if (normalizedBoxId <= 0 || normalizedQty <= 0) { + return; + } + if (!allocationMapByGroup.has(groupKey)) { + allocationMapByGroup.set(groupKey, new Map()); + } + const groupAllocationMap = allocationMapByGroup.get(groupKey); + groupAllocationMap.set( + normalizedBoxId, + Number(groupAllocationMap.get(normalizedBoxId) || 0) + normalizedQty + ); + }; + + if (pickMeta.require_box_allocations) { + if (pickMode === 4) { + const boxNosByOrderId = new Map(); + for (const row of taskOrderRows) { + const orderId = Number(row && row.order_id || 0); + const boxNo = Number(row && row.box_no || 0); + if (orderId <= 0 || boxNo <= 0) { + continue; + } + if (!boxNosByOrderId.has(orderId)) { + boxNosByOrderId.set(orderId, new Set()); + } + boxNosByOrderId.get(orderId).add(boxNo); + } + + for (const [ groupKey, groupItem ] of groupMap) { + for (const detail of groupItem.details) { + const orderId = Number(detail && detail.order_id || 0); + const quantity = Number(detail && detail.quantity || 0); + const boxNos = boxNosByOrderId.get(orderId); + if (!boxNos || quantity <= 0) { + continue; + } + for (const boxNo of boxNos) { + const boxInfo = boxMapByNo.get(Number(boxNo || 0)); + const boxId = Number(boxInfo && boxInfo.box_id || 0); + appendAllocation(groupKey, boxId, quantity); + } + } + } + } else if (pickMode === 1) { + const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave'); + const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND ptw.warehouse_id = :warehouseId' : ''; + const taskWaveRows = await ctx.model.query(` + SELECT + ptw.wave_id, + ptw.box_no + FROM wms_wave_pick_task_wave ptw + WHERE ptw.task_id = :taskId + ${taskWaveWarehouseFilterSql} + ORDER BY ptw.id ASC + `, { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + const waveToBoxNosMap = new Map(); + for (const row of Array.isArray(taskWaveRows) ? taskWaveRows : []) { + const waveId = Number(row && row.wave_id || 0); + const boxNo = Number(row && row.box_no || 0); + if (waveId <= 0 || boxNo <= 0) { + continue; + } + if (!waveToBoxNosMap.has(waveId)) { + waveToBoxNosMap.set(waveId, new Set()); + } + waveToBoxNosMap.get(waveId).add(boxNo); + } + + const orderIds = [ ...new Set(pickingDetails + .map(detail => Number(detail && detail.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + const orderWaveMap = await this.loadOrderWaveMap({ + warehouseId, + orderIds, + }); + + for (const [ groupKey, groupItem ] of groupMap) { + for (const detail of groupItem.details) { + const orderId = Number(detail && detail.order_id || 0); + const quantity = Number(detail && detail.quantity || 0); + const waveId = Number(orderWaveMap.get(orderId) || 0); + const boxNos = waveToBoxNosMap.get(waveId); + if (!boxNos || quantity <= 0) { + continue; + } + for (const boxNo of boxNos) { + const boxInfo = boxMapByNo.get(Number(boxNo || 0)); + const boxId = Number(boxInfo && boxInfo.box_id || 0); + appendAllocation(groupKey, boxId, quantity); + } + } + } + } else if (pickMode === 3) { + const boxMapByRefId = new Map(); + for (const row of boxRows) { + const refId = Number(row && row.ref_id || 0); + const boxId = Number(row && row.box_id || 0); + if (refId <= 0 || boxId <= 0) { + continue; + } + if (!boxMapByRefId.has(refId)) { + boxMapByRefId.set(refId, []); + } + boxMapByRefId.get(refId).push(row); + } + + for (const [ groupKey, groupItem ] of groupMap) { + const stockId = Number(groupItem && groupItem.stock_id || 0); + const targetBoxes = boxMapByRefId.get(stockId); + if (!Array.isArray(targetBoxes) || targetBoxes.length === 0) { + continue; + } + const groupQty = Number(groupItem && groupItem.total_qty || 0); + if (groupQty <= 0) { + continue; + } + for (const boxInfo of targetBoxes) { + appendAllocation(groupKey, Number(boxInfo && boxInfo.box_id || 0), groupQty); + } + } + } + } + + const itemList = Array.from(groupMap.entries()).map(([ groupKey, groupItem ]) => { + const groupAllocationMap = allocationMapByGroup.get(groupKey) || new Map(); + const boxAllocations = pickMeta.require_box_allocations + ? Array.from(groupAllocationMap.entries()) + .map(([ boxId, allocatedQty ]) => { + const boxInfo = boxRows.find(row => Number(row && row.box_id || 0) === Number(boxId || 0)) || {}; + return { + box_id: Number(boxInfo && boxInfo.box_id || 0), + box_no: Number(boxInfo && boxInfo.box_no || 0), + box_type: Number(boxInfo && boxInfo.box_type || 0), + required_qty: Number(boxInfo && boxInfo.required_qty || 0), + picked_qty: Number(boxInfo && boxInfo.picked_qty || 0), + allocated_qty: Number(allocatedQty || 0), + }; + }) + .sort((a, b) => { + const boxNoA = Number(a && a.box_no || 0); + const boxNoB = Number(b && b.box_no || 0); + if (boxNoA !== boxNoB) { + return boxNoA - boxNoB; + } + return Number(a && a.box_id || 0) - Number(b && b.box_id || 0); + }) + : []; + + return { + space_id: Number(groupItem && groupItem.space_id || 0), + space_name: String(groupItem && groupItem.space_name || '').trim(), + location_space: groupItem && groupItem.location_space ? groupItem.location_space : null, + item_code: String(groupItem && groupItem.item_code || '').trim(), + item_name: String(groupItem && groupItem.item_name || '').trim(), + stock_id: Number(groupItem && groupItem.stock_id || 0), + total_qty: Number(groupItem && groupItem.total_qty || 0), + // 拣货要求:取自商品资料链路(getStockDetails),merge_requirements=Y 时已回退为打包要求 + pick_requirements: String( + (groupItem && groupItem.stock && groupItem.stock.pick_requirements) || '' + ).trim(), + box_allocations: boxAllocations, + store_id: groupItem.store_id != null ? Number(groupItem.store_id) : 0, + owner_code: String(groupItem.owner_code || '').trim(), + store_remark: String(groupItem.store_remark || '').trim(), + }; + }); + + itemList.sort((a, b) => { + const sequenceA = Number(a && a.location_space && a.location_space.pick_sequence || 0); + const sequenceB = Number(b && b.location_space && b.location_space.pick_sequence || 0); + if (sequenceA !== sequenceB) { + return sequenceA - sequenceB; + } + + const priorityA = Number(a && a.location_space && a.location_space.pick_priority || 0); + const priorityB = Number(b && b.location_space && b.location_space.pick_priority || 0); + if (priorityA !== priorityB) { + return priorityA - priorityB; + } + + const spaceIdA = Number(a && a.space_id || 0); + const spaceIdB = Number(b && b.space_id || 0); + if (spaceIdA !== spaceIdB) { + return spaceIdA - spaceIdB; + } + + const itemCodeA = String(a && a.item_code || '').trim(); + const itemCodeB = String(b && b.item_code || '').trim(); + return itemCodeA.localeCompare(itemCodeB); + }); + + return { + mode_code: pickMeta.mode_code, + mode_name: pickMeta.mode_name, + require_box_allocations: pickMeta.require_box_allocations, + group_by: 'space+item', + sort_by: [ 'pick_sequence', 'pick_priority', 'space_id', 'item_code' ], + items: itemList, + }; + } + + /** + * 解析订单所属波次信息。 + * + * @param {Object} order 订单记录。 + * @return {{waveId: number, waveNo: string}} 波次信息。 + */ + resolveWaveInfo(order = {}) { + const waveId = Number(order.wave_id || 0); + const waveNo = String(order.wave_no || '').trim(); + return { + waveId: Number.isFinite(waveId) ? waveId : 0, + waveNo, + }; + } + + /** + * 判断订单是否已复核。 + * + * 当前使用 `inspection_status === "fin"` 作为已复核判定。 + * + * @param {Object} order 订单记录。 + * @return {boolean} 是否已复核。 + */ + isOrderReviewed(order = {}) { + return String(order.inspection_status || '').trim() === REVIEWED_INSPECTION_STATUS; + } + + /** + * 根据波次信息构建订单查询条件。 + * + * @param {Object} waveInfo 波次信息。 + * @param {number} warehouseId 仓库ID。 + * @return {Object} Sequelize 查询条件。 + */ + buildWaveOrderWhere(waveInfo = {}, warehouseId) { + const { Op } = this.app.Sequelize; + const where = { + warehouse_id: warehouseId, + }; + + if (waveInfo.waveId > 0 && waveInfo.waveNo) { + where[Op.or] = [ + { wave_id: waveInfo.waveId }, + { wave_no: waveInfo.waveNo }, + ]; + return where; + } + + if (waveInfo.waveId > 0) { + where.wave_id = waveInfo.waveId; + return where; + } + + where.wave_no = waveInfo.waveNo; + return where; + } + + /** + * 按波次信息查询拣货汇总。 + * + * @param {Object} params 查询参数。 + * @param {number} params.orderId 当前订单ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {string} [params.waveNo] 波次号。 + * @param {number} [params.waveId] 波次ID。 + * @param {number} [params.storeId] 货主ID。 + * @param {boolean} params.fullDisplay 是否完整显示。 + * @return {Promise} 波次拣货汇总结果。 + */ + async queryPickingInfo(params = {}) { + const { Op } = this.app.Sequelize; + const { ctx } = this; + const { + orderId, + warehouseId, + waveNo, + waveId, + storeId, + fullDisplay, + } = params; + + const normalizedOrderId = Number(orderId || 0); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + throw this.createBusinessError('order_id 参数不合法', 400); + } + + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const waveInfo = { + waveId: Number(waveId || 0), + waveNo: String(waveNo || '').trim(), + }; + if (waveInfo.waveId <= 0 && !waveInfo.waveNo) { + throw this.createBusinessError('订单未分配波次号,暂无拣货信息', 400); + } + + const orderModel = await this.getOrderModel(normalizedWarehouseId); + + const waveOrderRows = await orderModel.findAll({ + where: this.buildWaveOrderWhere(waveInfo, normalizedWarehouseId), + attributes: [ 'id', 'inspection_status', 'store_id' ], + raw: true, + }); + + const orderIds = Array.isArray(waveOrderRows) + ? waveOrderRows + .map(item => Number(item && item.id || 0)) + .filter(id => id > 0) + : []; + + if (orderIds.length === 0) { + throw this.createBusinessError('未找到波次对应订单', 404); + } + + const orderStatusMap = new Map(); + for (const row of waveOrderRows) { + const id = Number(row && row.id || 0); + if (id <= 0) { + continue; + } + orderStatusMap.set(id, { + inspection_status: String(row && row.inspection_status || '').trim(), + }); + } + + const pickingRows = await ctx.model.Picking.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + warehouse_id: normalizedWarehouseId, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const spaceIds = Array.isArray(pickingRows) + ? Array.from(new Set(pickingRows + .map(item => Number(item && item.space_id || 0)) + .filter(id => id > 0))) + : []; + + const locationRows = spaceIds.length > 0 + ? await ctx.model.LocationSpace.findAll({ + where: { + id: { + [Op.in]: spaceIds, + }, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ + 'id', + 'space_code', + 'custom_name', + 'custom_barcode', + 'zone_id', + 'space_status', + 'is_enabled', + 'pick_sequence', + 'pick_priority', + ], + raw: true, + }) + : []; + + const locationMap = new Map(); + for (const location of Array.isArray(locationRows) ? locationRows : []) { + const locationId = Number(location && location.id || 0); + if (locationId > 0) { + locationMap.set(locationId, location); + } + } + + const currentStoreId = Number(storeId || (waveOrderRows[0] && waveOrderRows[0].store_id) || 0); + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: currentStoreId, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', 'auth_status', 'warehouse_use_status', 'store_use_status' ], + raw: true, + }); + + const fullDisplayFlag = Boolean(fullDisplay); + const allDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => { + const currentOrderId = Number(row && row.order_id || 0); + const orderStatus = orderStatusMap.get(currentOrderId) || { inspection_status: 'none' }; + const reviewed = this.isOrderReviewed(orderStatus); + const spaceId = Number(row && row.space_id || 0); + + return { + id: Number(row && row.id || 0), + order_id: currentOrderId, + order_item_id: Number(row && row.order_item_id || 0), + storage_id: Number(row && row.storage_id || 0), + quantity: Number(row && row.quantity || 0), + space_id: spaceId, + space_name: String(row && row.space_name || ''), + picking_status: String(row && row.status || ''), + inspection_status: orderStatus.inspection_status, + reviewed, + location_space: locationMap.get(spaceId) || null, + store_warehouse: storeWarehouse || null, + }; + }); + + const pendingReviewDetails = allDetails.filter(item => !item.reviewed); + const reviewedDetails = allDetails.filter(item => item.reviewed); + const displayDetails = fullDisplayFlag ? allDetails : pendingReviewDetails; + + const sumQuantity = rows => rows.reduce((sum, item) => sum + Number(item && item.quantity || 0), 0); + + return { + order_id: normalizedOrderId, + wave_id: waveInfo.waveId, + wave_no: waveInfo.waveNo, + full_display: fullDisplayFlag, + summary: { + total_count: allDetails.length, + pending_review_count: pendingReviewDetails.length, + reviewed_count: reviewedDetails.length, + quantity_total: sumQuantity(allDetails), + display_count: displayDetails.length, + display_quantity_total: sumQuantity(displayDetails), + }, + list: displayDetails, + }; + } + + /** + * 按订单ID查询其波次拣货信息。 + * + * @param {Object} params 查询参数。 + * @param {number} params.orderId 订单ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {boolean} params.fullDisplay 是否完整显示。 + * @return {Promise} 波次拣货汇总结果。 + */ + async queryByOrder(params = {}) { + const { + orderId, + warehouseId, + fullDisplay, + } = params; + + const normalizedOrderId = Number(orderId || 0); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + throw this.createBusinessError('order_id 参数不合法', 400); + } + + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const orderModel = await this.getOrderModel(normalizedWarehouseId); + + const order = await orderModel.findOne({ + where: { + id: normalizedOrderId, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'store_id', 'wave_no', 'wave_id' ], + raw: true, + }); + + if (!order) { + throw this.createBusinessError('订单不存在', 404); + } + + const waveInfo = this.resolveWaveInfo(order); + if (waveInfo.waveId <= 0 && !waveInfo.waveNo) { + throw this.createBusinessError('订单未分配波次号,暂无拣货信息', 400); + } + + return await this.queryPickingInfo({ + orderId: normalizedOrderId, + warehouseId: normalizedWarehouseId, + waveNo: waveInfo.waveNo, + waveId: waveInfo.waveId, + storeId: Number(order.store_id || 0), + fullDisplay, + }); + } + + /** + * 查询当前登录用户正在处理中的拣货任务。 + * + * 仅供 PDA 使用:根据当前登录用户上下文(仓库 + 操作人)查询状态为 0/1/2 的最新任务。 + * + * @param {Object} [params={}] 预留参数(当前无需传入)。 + * @return {Promise<{task_id: number|null}>} 当前任务ID,无任务则为 null。 + */ + async wavePickTaskCurrent(params = {}) { + const { ctx } = this; + void params; + + const stateUser = ctx && ctx.state && ctx.state.user && typeof ctx.state.user === 'object' + ? ctx.state.user + : null; + const ctxUser = ctx && ctx.user && typeof ctx.user === 'object' + ? ctx.user + : null; + const currentUser = stateUser || ctxUser || {}; + + const warehouseId = Number( + currentUser.store_id + || currentUser.warehouse_id + || (ctxUser && (ctxUser.store_id || ctxUser.warehouse_id)) + || 0 + ); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const pickUserId = Number( + currentUser.employees_id + || currentUser.operator_id + || currentUser.id + || (ctxUser && (ctxUser.employees_id || ctxUser.operator_id || ctxUser.id)) + || 0 + ); + if (!Number.isInteger(pickUserId) || pickUserId <= 0) { + throw this.createBusinessError('未获取到操作人上下文', 401); + } + + const taskRows = await ctx.model.query(` + SELECT + t.id AS task_id + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + AND t.pick_user_id = :pickUserId + AND t.status IN (0, 1) + ORDER BY t.id DESC + LIMIT 1 + `, { + replacements: { + warehouseId, + pickUserId, + }, + type: ctx.model.QueryTypes.SELECT, + }); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + const taskId = Number(taskRow && taskRow.task_id || 0); + + return { + task_id: Number.isInteger(taskId) && taskId > 0 ? taskId : null, + }; + } + + /** + * 查询拣货任务详情。 + * + * 按 task_id 查询任务主信息,并返回与拣货直接相关的框明细与拣货明细; + * 仅允许任务创建人(pick_user_id)查看。 + * + * @param {Object} params 查询参数。 + * @param {number} params.taskId 任务ID。 + * @param {number} params.operatorId 当前操作人ID。 + * @return {Promise<{task: Object, boxes: Array, picking_details: Array, picking_summary: Object, picking_view: Object}>} 任务详情。 + */ + async wavePickTaskDetail(params = {}) { + const { ctx } = this; + const taskId = Number(params && params.taskId || 0); + const operatorId = Number(params && params.operatorId || 0); + + if (!Number.isInteger(taskId) || taskId <= 0) { + throw this.createBusinessError('task_id 必填且必须为正整数', 400); + } + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw this.createBusinessError('未获取到操作人上下文', 401); + } + + const taskRows = await ctx.model.query(` + SELECT + t.id AS task_id, + t.task_no, + t.status, + t.pick_mode, + t.pick_user_id, + t.start_time AS start_at, + t.finish_time AS finish_at, + t.batch_no, + t.warehouse_id + FROM wms_wave_pick_task t + WHERE t.id = :taskId + LIMIT 1 + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + if (!taskRow) { + throw this.createBusinessError('拣货任务不存在', 404); + } + + const taskPickUserId = Number(taskRow.pick_user_id || 0); + if (!Number.isInteger(taskPickUserId) || taskPickUserId !== operatorId) { + throw this.createBusinessError('当前操作人与任务创建人不一致,无权查看', 403); + } + + // 首次进入详情时补写拣货开始时间,确保后续流程可感知“已开始”。 + if (!taskRow.start_at) { + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET + start_time = NOW(), + update_time = NOW() + WHERE id = :taskId + AND start_time IS NULL + `, { + replacements: { taskId }, + }); + + const startTimeRows = await ctx.model.query(` + SELECT start_time AS start_at + FROM wms_wave_pick_task + WHERE id = :taskId + LIMIT 1 + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }); + const startTimeRow = Array.isArray(startTimeRows) && startTimeRows.length > 0 ? startTimeRows[0] : null; + taskRow.start_at = startTimeRow && startTimeRow.start_at ? startTimeRow.start_at : taskRow.start_at; + } + + const warehouseId = Number(taskRow.warehouse_id || 0); + const pickMode = Number(taskRow.pick_mode || 0); + + // 查询任务关联的波次号 + let taskWaveNo = ''; + try { + const taskWaveNoRows = await ctx.model.query(` + SELECT + wb.wave_no + FROM wms_wave_pick_task_wave ptw + INNER JOIN wms_wave_batch wb ON wb.wave_id = ptw.wave_id + WHERE ptw.task_id = :taskId + ORDER BY ptw.id ASC + LIMIT 1 + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }); + taskWaveNo = Array.isArray(taskWaveNoRows) && taskWaveNoRows.length > 0 + ? String(taskWaveNoRows[0].wave_no || '').trim() + : ''; + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 查询波次号失败,将降级为空: ${error.message}`); + } + + const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order'); + const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave'); + const boxColumnSet = await this.getTableColumnSet('wms_wave_pick_task_box'); + const taskOrderWarehouseFilterSql = taskOrderColumnSet.has('warehouse_id') ? ' AND pto.warehouse_id = :warehouseId' : ''; + const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND ptw.warehouse_id = :warehouseId' : ''; + const boxWarehouseFilterSql = boxColumnSet.has('warehouse_id') ? ' AND b.warehouse_id = :warehouseId' : ''; + const boxExtraSelect = []; + if (boxColumnSet.has('ref_label')) { + boxExtraSelect.push('b.ref_label'); + } + if (boxColumnSet.has('required_qty')) { + boxExtraSelect.push('b.required_qty'); + } + if (boxColumnSet.has('picked_qty')) { + boxExtraSelect.push('b.picked_qty'); + } + if (boxColumnSet.has('ref_id')) { + boxExtraSelect.push('b.ref_id'); + } + + const [ taskOrderRows, boxRows ] = await Promise.all([ + ctx.model.query(` + SELECT + pto.order_id, + pto.box_no, + pto.pick_status + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = :taskId + ${taskOrderWarehouseFilterSql} + ORDER BY pto.id ASC + `, { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }), + ctx.model.query(` + SELECT + b.id AS box_id, + b.box_no, + b.box_type, + b.box_status AS status${boxExtraSelect.length > 0 ? `,\n ${boxExtraSelect.join(',\n ')}` : ''} + FROM wms_wave_pick_task_box b + WHERE b.task_id = :taskId + ${boxWarehouseFilterSql} + ORDER BY b.id ASC + `, { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }), + ]); + + const normalizedTaskOrderRows = Array.isArray(taskOrderRows) ? taskOrderRows : []; + const taskOrderTotal = normalizedTaskOrderRows.length; + const taskOrderPicked = normalizedTaskOrderRows + .filter(row => Number(row && row.pick_status || 0) === 1) + .length; + const taskCompletedByOrder = taskOrderTotal > 0 && taskOrderPicked >= taskOrderTotal; + const taskCompletedByStatus = Number(taskRow && taskRow.status || 0) >= 2; + const isCompleted = taskCompletedByOrder || taskCompletedByStatus; + let orderIds = [ ...new Set(normalizedTaskOrderRows + .map(row => Number(row && row.order_id || 0)) + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ]; + let taskWaveCount = 0; + let orderSource = 'task_order'; + const derivedWaveIds = []; + + if (orderIds.length === 0 && [ 1, 5 ].includes(pickMode)) { + const taskWaveRows = await ctx.model.query(` + SELECT + ptw.wave_id + FROM wms_wave_pick_task_wave ptw + WHERE ptw.task_id = :taskId + ${taskWaveWarehouseFilterSql} + ORDER BY ptw.id ASC + `, { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + const normalizedTaskWaveRows = Array.isArray(taskWaveRows) ? taskWaveRows : []; + taskWaveCount = normalizedTaskWaveRows.length; + const fallbackWaveIds = [ ...new Set(normalizedTaskWaveRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + derivedWaveIds.push(...fallbackWaveIds.slice(0, 5)); + + if (fallbackWaveIds.length > 0) { + const orderModel = await this.getOrderModel(warehouseId); + const fallbackOrderRows = await orderModel.findAll({ + where: { + wave_id: { + [this.app.Sequelize.Op.in]: fallbackWaveIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + }); + + orderIds = [ ...new Set((Array.isArray(fallbackOrderRows) ? fallbackOrderRows : []) + .map(row => Number(row && row.id || 0)) + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ]; + if (orderIds.length > 0) { + orderSource = 'task_wave_fallback'; + } + } + } + + if (orderIds.length > 0) { + const orderModel = await this.getOrderModel(warehouseId); + const orderExpressStatusRows = await orderModel.findAll({ + where: { + id: { + [this.app.Sequelize.Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'post_status' ], + raw: true, + }); + + const orderExpressStatusMap = new Map((Array.isArray(orderExpressStatusRows) ? orderExpressStatusRows : []) + .map(row => [ Number(row && row.id || 0), String(row && row.post_status || '').trim() ])); + const unassignedExpressOrderIds = orderIds + .filter(orderIdItem => { + const expressStatus = orderExpressStatusMap.get(orderIdItem) || ''; + return expressStatus !== 'fin'; + }); + + if (unassignedExpressOrderIds.length > 0) { + throw this.createBusinessError( + '存在未分配快递号订单,是否一键分配快递号?', + 400, + { + action: 'assign_express', + order_ids: unassignedExpressOrderIds, + } + ); + } + } + + const pickingRows = orderIds.length > 0 + ? await ctx.model.Picking.findAll({ + where: { + order_id: { + [this.app.Sequelize.Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'storage_id', 'space_id', 'space_name' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }) + : []; + + const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; + const orderIdSet = new Set(orderIds); + const orderIdsWithPicking = new Set(normalizedPickingRows + .map(row => Number(row && row.order_id || 0)) + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdSet.has(orderIdItem))); + const missingPickingOrderIds = orderIds + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0 && !orderIdsWithPicking.has(orderIdItem)); + const invalidSpaceOrderIds = [ ...new Set(normalizedPickingRows + .filter(row => Number(row && row.space_id || 0) <= 0) + .map(row => Number(row && row.order_id || 0)) + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdSet.has(orderIdItem))) ]; + const unassignedSpaceOrderIds = [ ...new Set([ ...missingPickingOrderIds, ...invalidSpaceOrderIds ]) ]; + if (unassignedSpaceOrderIds.length > 0) { + throw this.createBusinessError( + '存在未分配储位订单,是否一键分配储位?', + 400, + { + action: 'assign_storage', + order_ids: unassignedSpaceOrderIds, + } + ); + } + + ctx.logger.info( + `[pick.wavePickTaskDetail] task_id=${taskId} pick_mode=${pickMode} warehouse_id=${warehouseId} task_order_count=${normalizedTaskOrderRows.length} task_wave_count=${taskWaveCount} derived_order_ids_count=${orderIds.length} picking_rows_count=${Array.isArray(pickingRows) ? pickingRows.length : 0} order_source=${orderSource} order_id_samples=${JSON.stringify(orderIds.slice(0, 5))} wave_id_samples=${JSON.stringify(derivedWaveIds)}` + ); + + const pickingSpaceIds = [ ...new Set((Array.isArray(pickingRows) ? pickingRows : []) + .map(row => Number(row && row.space_id || 0)) + .filter(spaceId => Number.isInteger(spaceId) && spaceId > 0)) ]; + + const locationRows = pickingSpaceIds.length > 0 + ? await ctx.model.LocationSpace.findAll({ + where: { + id: { + [this.app.Sequelize.Op.in]: pickingSpaceIds, + }, + }, + attributes: [ 'id', 'space_code', 'custom_name', 'custom_barcode', 'pick_sequence', 'pick_priority' ], + raw: true, + }) + : []; + + const locationMap = new Map((Array.isArray(locationRows) ? locationRows : []) + .map(row => [ Number(row && row.id || 0), row ])); + + const orderItemIds = [ ...new Set((Array.isArray(pickingRows) ? pickingRows : []) + .map(row => Number(row && row.order_item_id || 0)) + .filter(orderItemId => Number.isInteger(orderItemId) && orderItemId > 0)) ]; + const orderItemMap = await this.loadOrderItemMap({ + warehouseId, + orderItemIds, + }); + + // 通过 stock_warehouse 带缓存的公用链路(getStockDetails)批量查询商品资料, + // 以 stock_id 为准获取 item_code / item_name,与 order/base.js 等链路保持一致。 + const stockIdsForDetail = [ ...new Set( + [ ...orderItemMap.values() ] + .map(row => Number(row && row.stock_id || 0)) + .filter(sid => Number.isInteger(sid) && sid > 0) + ) ]; + const stockDetailMap = new Map(); + if (stockIdsForDetail.length > 0) { + try { + const stockWarehouseSvc = ctx.service && ctx.service.systems && ctx.service.systems.stockWarehouse; + if (stockWarehouseSvc && typeof stockWarehouseSvc.getStockDetails === 'function') { + const stockDetails = await stockWarehouseSvc.getStockDetails(stockIdsForDetail, { warehouseId }); + for (const detail of (Array.isArray(stockDetails) ? stockDetails : [])) { + stockDetailMap.set(Number(detail && detail.id || 0), detail); + } + } + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] getStockDetails 查询失败,将降级使用 order_items 列值: ${error.message}`); + } + } + + // 批量查询货主备注名(wms_store_warehouse.store_remask),按 store_id 映射 + const storeRemarkMap = new Map(); + if (stockDetailMap.size > 0 && ctx.model && ctx.model.StoreWarehouse) { + const storeIdsForRemark = [ ...new Set( + [ ...stockDetailMap.values() ] + .map(detail => Number(detail.store_id || 0)) + .filter(id => id > 0) + ) ]; + if (storeIdsForRemark.length > 0) { + try { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIdsForRemark }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } catch (remarkError) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 查询货主备注失败: ${remarkError.message}`); + } + } + } + + const normalizedBoxRows = Array.isArray(boxRows) ? boxRows : []; + const boxMapByNo = new Map(normalizedBoxRows + .map(row => [ Number(row && row.box_no || 0), row ]) + .filter(([ boxNo ]) => boxNo > 0)); + + // 构建 stock_id → box_no 映射(从 wms_wave_pick_task_box.ref_id),用于给每个拣货明细行标注篮号 + const boxNoByStockId = new Map(); + for (const row of normalizedBoxRows) { + const sid = Number(row && row.ref_id || 0); + const bno = Number(row && row.box_no || 0); + if (sid > 0 && bno > 0 && !boxNoByStockId.has(sid)) { + boxNoByStockId.set(sid, bno); + } + } + + const pickingDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => { + const orderItemId = Number(row && row.order_item_id || 0); + const currentSpaceId = Number(row && row.space_id || 0); + const locationRow = locationMap.get(currentSpaceId) || {}; + const orderItemRow = orderItemMap.get(orderItemId) || {}; + const stockId = Number(orderItemRow.stock_id || 0); + const stockDetail = stockDetailMap.get(stockId) || null; + const itemSnapshot = this.parseItemSnapshot(orderItemRow.item_snapshot); + + // 构建 stock 字段:优先 getStockDetails 完整对象,兜底用 item_snapshot + order_items 拼装 + const stock = stockDetail + ? { ...stockDetail } + : { + id: stockId || null, + item_code: String(itemSnapshot.item_code || orderItemRow.item_code || '').trim(), + item_name: String(itemSnapshot.item_name || orderItemRow.item_name || '').trim(), + sku_property: String(itemSnapshot.sku_property || '').trim(), + stock_unit: String(itemSnapshot.stock_unit || '').trim(), + barcodes: [], + image_url: [], + store_id: 0, + }; + // 确保 owner_code 在 stock 对象上(getStockDetails 不含此字段,需从 order_items 补) + if (!stock.owner_code) { + stock.owner_code = String(orderItemRow.owner_code || '').trim(); + } + // 确保 store_remark 在 stock 对象上(getStockDetails 不含此字段,需从 wms_store_warehouse 补) + const stockStoreId = stock.store_id != null ? Number(stock.store_id) : 0; + if (!stock.store_remark) { + stock.store_remark = storeRemarkMap.get(stockStoreId) || ''; + } + + return { + order_id: Number(row && row.order_id || 0), + box_no: boxNoByStockId.get(stockId) || 0, + order_item_id: orderItemId, + quantity: Number(row && row.quantity || 0), + storage_id: Number(row && row.storage_id || 0), + space_id: currentSpaceId, + space_name: String(row && row.space_name || '').trim(), + location_space: { + space_code: String(locationRow.space_code || '').trim(), + custom_name: String(locationRow.custom_name || '').trim(), + custom_barcode: String(locationRow.custom_barcode || '').trim(), + pick_sequence: Number(locationRow.pick_sequence || 0), + pick_priority: Number(locationRow.pick_priority || 0), + }, + // 优先 stock_warehouse(getStockDetails),兜底 item_snapshot,最终 order_items 列 + item_code: stock.item_code, + item_name: stock.item_name, + stock_id: stockId, + plan_qty: Number(orderItemRow.plan_qty || 0), + item_snapshot: orderItemRow.item_snapshot || null, + store_id: stockStoreId, + owner_code: String(stock.owner_code || '').trim(), + store_remark: String(stock.store_remark || '').trim(), + stock, + }; + }); + + // 排序 picking_details:box_no 已按库位顺序生成,直接按 box_no 升序即可 + pickingDetails.sort((a, b) => { + const boxA = Number(a && a.box_no || 0); + const boxB = Number(b && b.box_no || 0); + if (boxA !== boxB) return boxA - boxB; + + const codeA = String(a && a.item_code || '').trim(); + const codeB = String(b && b.item_code || '').trim(); + return codeA.localeCompare(codeB); + }); + + const pickingSummary = this.buildPickingSummary(pickingDetails); + const pickingView = await this.buildPickingView({ + pickMode, + taskId, + warehouseId, + pickingDetails, + boxRows: normalizedBoxRows, + taskOrderRows: normalizedTaskOrderRows, + boxMapByNo, + }); + + const result = { + task: { + task_id: Number(taskRow.task_id || 0), + task_no: String(taskRow.task_no || '').trim(), + wave_no: taskWaveNo, + status: Number(taskRow.status || 0), + pick_mode: pickMode, + start_at: taskRow.start_at || null, + finish_at: taskRow.finish_at || null, + batch_no: String(taskRow.batch_no || '').trim(), + is_completed: isCompleted, + progress: { + total_orders: taskOrderTotal, + picked_orders: taskOrderPicked, + pending_orders: Math.max(0, taskOrderTotal - taskOrderPicked), + }, + }, + is_completed: isCompleted, + boxes: normalizedBoxRows.map(row => ({ + box_id: Number(row && row.box_id || 0), + box_no: Number(row && row.box_no || 0), + box_type: Number(row && row.box_type || 0), + status: Number(row && row.status || 0), + ref_id: Number(row && row.ref_id || 0), + ref_label: String(row && row.ref_label || '').trim() || null, + required_qty: Number(row && row.required_qty || 0), + picked_qty: Number(row && row.picked_qty || 0), + })), + picking_summary: pickingSummary, + picking_view: pickingView, + }; + + // 团购模式(小波次 pick_mode=1 / 大波次 pick_mode=5)不需要返回拣货明细,减少带宽浪费 + if (pickMode !== 1 && pickMode !== 5) { + result.picking_details = pickingDetails; + } + + return result; + } + + /** + * 解析当前操作人上下文。 + * + * @return {{operatorId: number, operatorName: string, warehouseId: number}} 上下文信息。 + */ + resolveOperatorContext() { + const { ctx } = this; + const stateUser = ctx && ctx.state && ctx.state.user && typeof ctx.state.user === 'object' + ? ctx.state.user + : null; + const ctxUser = ctx && ctx.user && typeof ctx.user === 'object' + ? ctx.user + : null; + const operatorSource = stateUser || ctxUser || {}; + + const operatorId = Number((operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id) || 0); + const operatorName = String( + operatorSource.operator_name + || operatorSource.employees_name + || operatorSource.name + || '' + ).trim() || 'system'; + const warehouseId = Number(operatorSource.store_id || operatorSource.warehouse_id || 0); + + return { + operatorId, + operatorName, + warehouseId, + }; + } + + /** + * 规范化拣货车状态。 + * + * @param {*} status 原始状态。 + * @param {number} [defaultValue=1] 默认状态。 + * @return {number} 规范化后的状态值,仅返回 0 或 1。 + */ + normalizePickCartStatus(status, defaultValue = 1) { + if (status === undefined || status === null || status === '') { + return defaultValue; + } + + const normalized = Number(status); + if (normalized === 0) { + return 0; + } + if (normalized === 1) { + return 1; + } + return Number(defaultValue) === 0 ? 0 : 1; + } + + /** + * 构建拣货车详情输出。 + * + * @param {Object} row 原始数据库记录。 + * @return {Object} 标准化后的详情。 + */ + buildPickCartDetail(row = {}) { + return { + cart_id: Number(row && (row.cart_id || row.id) || 0), + warehouse_id: Number(row && row.warehouse_id || 0), + cart_code: String(row && row.cart_code || '').trim(), + cart_name: String(row && row.cart_name || '').trim(), + status: Number(row && row.status || 0), + current_task_id: Number(row && row.current_task_id || 0) || null, + current_task_no: String(row && row.current_task_no || '').trim() || null, + current_task_status: row && row.current_task_status !== undefined && row.current_task_status !== null + ? Number(row.current_task_status) + : null, + bind_user_id: Number(row && row.bind_user_id || 0) || null, + last_bind_time: row && row.last_bind_time ? row.last_bind_time : null, + last_seen_time: row && row.last_seen_time ? row.last_seen_time : null, + create_time: row && row.create_time ? row.create_time : null, + update_time: row && row.update_time ? row.update_time : null, + }; + } + + /** + * 按 ID 查询拣货车。 + * + * @param {number} cartId 拣货车ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction=null] 事务对象。 + * @return {Promise} 拣货车记录。 + */ + async getPickCartById(cartId, warehouseId, transaction = null) { + const { ctx } = this; + const rows = await ctx.model.query(` + SELECT + c.id AS cart_id, + c.warehouse_id, + c.cart_code, + c.cart_name, + c.status, + c.current_task_id, + c.bind_user_id, + c.last_bind_time, + c.last_seen_time, + c.create_time, + c.update_time, + t.task_no AS current_task_no, + t.status AS current_task_status + FROM wms_pick_cart c + LEFT JOIN wms_wave_pick_task t + ON t.id = c.current_task_id + WHERE c.id = :cartId + AND c.warehouse_id = :warehouseId + LIMIT 1 + `, { + replacements: { + cartId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + }); + + return Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + } + + /** + * 按编码查询拣货车。 + * + * @param {string} cartCode 拣货车编码。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction=null] 事务对象。 + * @return {Promise} 拣货车记录。 + */ + async getPickCartByCode(cartCode, warehouseId, transaction = null) { + const { ctx } = this; + const normalizedCartCode = String(cartCode || '').trim(); + if (!normalizedCartCode) { + return null; + } + + const rows = await ctx.model.query(` + SELECT + c.id AS cart_id, + c.warehouse_id, + c.cart_code, + c.cart_name, + c.status, + c.current_task_id, + c.bind_user_id, + c.last_bind_time, + c.last_seen_time, + c.create_time, + c.update_time, + t.task_no AS current_task_no, + t.status AS current_task_status + FROM wms_pick_cart c + LEFT JOIN wms_wave_pick_task t + ON t.id = c.current_task_id + WHERE c.warehouse_id = :warehouseId + AND c.cart_code = :cartCode + LIMIT 1 + `, { + replacements: { + warehouseId, + cartCode: normalizedCartCode, + }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + }); + + return Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + } + + /** + * 查询拣货车编码是否重复。 + * + * @param {Object} params 查询参数。 + * @param {string} params.cartCode 拣货车编码。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} [params.excludeCartId=0] 排除的拣货车ID。 + * @param {Object} [params.transaction=null] 事务对象。 + * @return {Promise} 查重结果。 + */ + async pickCartCodeDuplicateCheck(params = {}) { + const { ctx } = this; + const cartCode = String(params && params.cartCode || '').trim(); + const warehouseId = Number(params && params.warehouseId || 0); + const excludeCartId = Number(params && params.excludeCartId || 0); + const transaction = params && params.transaction ? params.transaction : null; + + if (!cartCode) { + throw this.createBusinessError('cart_code 必填', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const rows = await ctx.model.query(` + SELECT + c.id AS cart_id, + c.cart_code, + c.cart_name, + c.status + FROM wms_pick_cart c + WHERE c.warehouse_id = :warehouseId + AND c.cart_code = :cartCode + AND (:excludeCartId <= 0 OR c.id <> :excludeCartId) + ORDER BY c.id DESC + LIMIT 1 + `, { + replacements: { + warehouseId, + cartCode, + excludeCartId, + }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + }); + + const row = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + return { + duplicated: Boolean(row), + cart_id: row ? Number(row.cart_id || 0) : null, + cart_code: row ? String(row.cart_code || '').trim() : null, + cart_name: row ? String(row.cart_name || '').trim() : null, + status: row ? Number(row.status || 0) : null, + }; + } + + /** + * 确保拣货车编码未重复。 + * + * @param {string} cartCode 拣货车编码。 + * @param {number} warehouseId 仓库ID。 + * @param {number} [excludeCartId=0] 排除的拣货车ID。 + * @param {Object} [transaction=null] 事务对象。 + * @return {Promise} 无返回值。 + */ + async assertPickCartCodeUnique(cartCode, warehouseId, excludeCartId = 0, transaction = null) { + const duplicateResult = await this.pickCartCodeDuplicateCheck({ + cartCode, + warehouseId, + excludeCartId, + transaction, + }); + + if (duplicateResult.duplicated) { + throw this.createBusinessError('拣货车编码已存在,请勿重复', 409, duplicateResult); + } + } + + /** + * 校验任务存在性与归属。 + * + * @param {number} taskId 任务ID。 + * @param {number} operatorId 操作人ID。 + * @return {Promise} 任务记录。 + */ + async getOwnedTask(taskId, operatorId) { + const { ctx } = this; + const taskRows = await ctx.model.query(` + SELECT + t.id AS task_id, + t.task_no, + t.status, + t.pick_mode, + t.pick_user_id, + t.warehouse_id, + t.start_time, + t.finish_time, + t.ext_json, + t.source, + t.current_cart_id + FROM wms_wave_pick_task t + WHERE t.id = :taskId + LIMIT 1 + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }); + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + if (!taskRow) { + throw this.createBusinessError('拣货任务不存在', 404); + } + + const taskPickUserId = Number(taskRow.pick_user_id || 0); + // source=2 后台抓取创建的任务 pick_user_id 可能为 0,此时跳过归属校验 + if (taskPickUserId !== 0 && (!Number.isInteger(taskPickUserId) || taskPickUserId !== operatorId)) { + throw this.createBusinessError('当前操作人与任务创建人不一致,无权操作', 403); + } + + return taskRow; + } + + /** + * 统计任务订单拣货进度。 + * + * @param {number} taskId 任务ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction] 事务对象。 + * @return {Promise<{totalOrders:number,pickedOrders:number,pendingOrders:number,isCompleted:boolean}>} 进度信息。 + */ + async getTaskPickProgress(taskId, warehouseId, transaction = null) { + const { ctx } = this; + const taskOrderRows = await ctx.model.query(` + SELECT + pto.order_id, + pto.pick_status + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = :taskId + AND pto.warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + }); + + const normalizedRows = Array.isArray(taskOrderRows) ? taskOrderRows : []; + const totalOrders = normalizedRows.length; + const pickedOrders = normalizedRows.filter(row => Number(row && row.pick_status || 0) === 1).length; + const pendingOrders = Math.max(0, totalOrders - pickedOrders); + const isCompleted = totalOrders > 0 && pickedOrders >= totalOrders; + + return { + totalOrders, + pickedOrders, + pendingOrders, + isCompleted, + }; + } + + /** + * 拣货任务中间态提交。 + * + * 用于保存阶段性进度,不进行最终确认。 + * + * @param {Object} params 提交参数。 + * @param {number} params.taskId 任务ID。 + * @param {Object} [params.payload] 阶段性数据。 + * @return {Promise} 保存结果。 + */ + async wavePickTaskSubmit(params = {}) { + const { ctx } = this; + const taskId = Number(params && params.taskId || 0); + const payload = params && typeof params.payload === 'object' && !Array.isArray(params.payload) + ? params.payload + : {}; + + if (!Number.isInteger(taskId) || taskId <= 0) { + throw this.createBusinessError('task_id 必填且必须为正整数', 400); + } + + const { operatorId, operatorName, warehouseId } = this.resolveOperatorContext(); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw this.createBusinessError('未获取到操作人上下文', 401); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const taskRow = await this.getOwnedTask(taskId, operatorId); + const taskStatus = Number(taskRow && taskRow.status || 0); + if ([ 3, 9 ].includes(taskStatus)) { + throw this.createBusinessError('任务已完成或已取消,无法提交中间态', 400); + } + + let extJson = {}; + const extSource = taskRow && taskRow.ext_json; + if (extSource && typeof extSource === 'object' && !Array.isArray(extSource)) { + extJson = { ...extSource }; + } else if (typeof extSource === 'string' && extSource.trim()) { + try { + const parsed = JSON.parse(extSource); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + extJson = { ...parsed }; + } + } catch (_) { + extJson = {}; + } + } + + extJson.pick_intermediate = { + payload, + updated_at: new Date().toISOString(), + operator_id: operatorId, + operator_name: operatorName, + }; + + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = CASE WHEN status = 0 THEN 1 ELSE status END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + ext_json = :extJson, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + extJson: JSON.stringify(extJson), + }, + }); + + const progress = await this.getTaskPickProgress(taskId, warehouseId); + return { + task_id: taskId, + status: 'submitted', + is_completed: progress.isCompleted, + progress: { + total_orders: progress.totalOrders, + picked_orders: progress.pickedOrders, + pending_orders: progress.pendingOrders, + }, + }; + } + + /** + * 拣货任务完全提交。 + * + * 支持两种模式: + * - 1:全部确认(将任务下全部订单标记为已拣) + * - 2:部分确认(仅确认传入 order_ids) + * + * @param {Object} params 提交参数。 + * @param {number} params.taskId 任务ID。 + * @param {number} [params.mode=1] 提交模式:1全部确认,2部分确认。 + * @param {Array} [params.orderIds=[]] 部分确认时的订单ID列表。 + * @return {Promise} 提交结果。 + */ + async wavePickTaskComplete(params = {}) { + const { ctx } = this; + const taskId = Number(params && params.taskId || 0); + const mode = Number(params && params.mode || 1); + const orderIds = [ ...new Set((Array.isArray(params && params.orderIds) ? params.orderIds : []) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (!Number.isInteger(taskId) || taskId <= 0) { + throw this.createBusinessError('task_id 必填且必须为正整数', 400); + } + if (![ 1, 2 ].includes(mode)) { + throw this.createBusinessError('mode 参数不合法,仅支持 1(全部确认) 或 2(部分确认)', 400); + } + + const { operatorId, operatorName, warehouseId } = this.resolveOperatorContext(); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw this.createBusinessError('未获取到操作人上下文', 401); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const taskRow = await this.getOwnedTask(taskId, operatorId); + const taskStatus = Number(taskRow && taskRow.status || 0); + if ([ 3, 9 ].includes(taskStatus)) { + throw this.createBusinessError('任务已完成或已取消,无法再次提交', 400); + } + + // source=1(PDA抓取创建)的任务必须先绑定拣货车才能提交 + // source=2(扫描进任务/后台抓取)不强制要求绑定拣货车 + const taskSource = Number(taskRow && taskRow.source || 0); + const taskCartId = Number(taskRow && taskRow.current_cart_id || 0); + if (taskSource === 1 && taskCartId <= 0) { + throw this.createBusinessError('PDA抓取任务必须先绑定拣货车才能提交', 400); + } + + const transaction = await ctx.model.transaction(); + try { + const taskOrderRows = await ctx.model.query(` + SELECT + pto.order_id, + pto.pick_status + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = :taskId + AND pto.warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedRows = Array.isArray(taskOrderRows) ? taskOrderRows : []; + let taskOrderIds = [ ...new Set(normalizedRows + .map(row => Number(row && row.order_id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + + if (taskOrderIds.length <= 0) { + const pickMode = Number(taskRow.pick_mode || 0); + if ([ 1, 5 ].includes(pickMode)) { + const taskWaveWarehouseFilterSql = (await this.getTableColumnSet('wms_wave_pick_task_wave')).has('warehouse_id') + ? ' AND ptw.warehouse_id = :warehouseId' + : ''; + const taskWaveRows = await ctx.model.query(` + SELECT + ptw.wave_id + FROM wms_wave_pick_task_wave ptw + WHERE ptw.task_id = :taskId + ${taskWaveWarehouseFilterSql} + ORDER BY ptw.id ASC + `, { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedTaskWaveRows = Array.isArray(taskWaveRows) ? taskWaveRows : []; + const fallbackWaveIds = [ ...new Set(normalizedTaskWaveRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + if (fallbackWaveIds.length > 0) { + const orderModel = await this.getOrderModel(warehouseId); + const fallbackOrderRows = await orderModel.findAll({ + where: { + wave_id: { + [this.app.Sequelize.Op.in]: fallbackWaveIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + + taskOrderIds = [ ...new Set((Array.isArray(fallbackOrderRows) ? fallbackOrderRows : []) + .map(row => Number(row && row.id || 0)) + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ]; + } + } + } + + if (taskOrderIds.length <= 0) { + throw this.createBusinessError('任务下无可确认订单', 400); + } + + let targetOrderIds = []; + if (mode === 1) { + targetOrderIds = taskOrderIds; + } else { + if (orderIds.length <= 0) { + throw this.createBusinessError('部分确认模式下 order_ids 不能为空', 400); + } + targetOrderIds = orderIds.filter(id => taskOrderIds.includes(id)); + if (targetOrderIds.length <= 0) { + throw this.createBusinessError('order_ids 未命中当前任务订单', 400); + } + } + + // 检查目标订单是否进入拦截流程,拦截订单直接跳过: + // 不完成拣货、不扣减库存(不取出)、不报错,其余订单照常完成 + // 同时记录打印状态:已打印面单的拦截订单保持不动,不做自动移出波次 + const skippedInterceptedOrders = []; + if (targetOrderIds.length > 0) { + const interceptCheckModel = await this.getOrderModel(warehouseId); + const interceptedOrderRows = await interceptCheckModel.findAll({ + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: targetOrderIds, + }, + intercept_status: { + [this.app.Sequelize.Op.ne]: INTERCEPT_STATUS_NONE, + }, + }, + attributes: [ 'id', 'intercept_status', 'print_status' ], + raw: true, + transaction, + }); + + if (interceptedOrderRows && interceptedOrderRows.length > 0) { + const interceptedOrderIdSet = new Set( + interceptedOrderRows.map(orderRow => Number(orderRow && orderRow.id || 0)) + ); + for (const orderRow of interceptedOrderRows) { + skippedInterceptedOrders.push({ + order_id: Number(orderRow && orderRow.id || 0), + intercept_status: String(orderRow && orderRow.intercept_status || '').trim() || 'none', + print_status: String(orderRow && orderRow.print_status || '').trim().toLowerCase() || 'none', + }); + } + targetOrderIds = targetOrderIds.filter(orderId => !interceptedOrderIdSet.has(orderId)); + } + } + + // 已打印面单的拦截订单保持不动:面单实物已在波次流程中,自动移出会导致 + // 面单与波次记录分离,此类订单需人工通过 wave.batchRemoveOrders 处理 + const printedSkippedOrderIdSet = new Set(skippedInterceptedOrders + .filter(item => { + const printStatus = String(item && item.print_status || '').trim().toLowerCase(); + return printStatus && printStatus !== 'none'; + }) + .map(item => Number(item && item.order_id || 0))); + const keptInterceptedOrderIds = [ ...printedSkippedOrderIdSet ]; + if (keptInterceptedOrderIds.length > 0) { + ctx.logger.warn(`[pick.wavePickTaskComplete] 已打印拦截订单保持不动,不自动移出波次,需人工处理, taskId=${taskId}, orderIds=${keptInterceptedOrderIds.join(',')}`); + } + + // source !== 0(PDA/后台抓取创建的任务)时,被跳过的拦截订单中「未打印」的 + // 直接从波次中移除:订单 wave_id 清零、删除波次索引、回写波次统计, + // 并移除任务订单关联;已打印的保持不动(见上方 keptInterceptedOrderIds) + const removedFromWaveOrderLogItems = []; + const removedFromWaveOrderIds = []; + const affectedWaveIdsForUnbind = []; + if (skippedInterceptedOrders.length > 0 && taskSource !== 0) { + const skippedOrderIds = skippedInterceptedOrders + .map(item => Number(item && item.order_id || 0)) + .filter(orderId => !printedSkippedOrderIdSet.has(orderId)); + const interceptOrderModel = await this.getOrderModel(warehouseId); + const removableRows = await interceptOrderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no' ], + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: skippedOrderIds, + }, + wave_id: { + [this.app.Sequelize.Op.gt]: 0, + }, + }, + raw: true, + transaction, + }); + + const normalizedRemovableRows = Array.isArray(removableRows) ? removableRows : []; + const affectedWaveIds = [ ...new Set(normalizedRemovableRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + affectedWaveIdsForUnbind.push(...affectedWaveIds); + + if (normalizedRemovableRows.length > 0) { + await interceptOrderModel.update({ + wave_id: 0, + wave_no: '', + wave_strategy_version: 0, + wave_scan_result: 0, + }, { + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: normalizedRemovableRows.map(row => Number(row.id)), + }, + }, + transaction, + }); + + for (const row of normalizedRemovableRows) { + removedFromWaveOrderIds.push(Number(row && row.id || 0)); + removedFromWaveOrderLogItems.push({ + orderId: Number(row && row.id || 0), + operationCode: 'ORDER_WAVE_REMOVE', + message: `订单从波次 ${String(row && row.wave_no || '').trim() || '未知波次'} 中移除`, + }); + } + + if (affectedWaveIds.length > 0) { + const waveService = this.ctx.service + && this.ctx.service.systemMethods + && this.ctx.service.systemMethods.order + && this.ctx.service.systemMethods.order.wave; + + // 仅删除拦截单自身的索引行,不重建整波索引: + // 其余订单 wave_index 保持不变(仅跳号),避免与已放货的篮子编号 + // (task_order.box_no / task_box.box_no 为创建时 wave_index 快照)错位, + // 保证复核/打印等按 wave_index 排序的环节仍与实物位置一致。 + if (waveService && typeof waveService.deleteOrderWaveIndexByOrderIds === 'function') { + await waveService.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: normalizedRemovableRows.map(row => Number(row.id)), + transaction, + }); + } + + // 按剩余索引行数回写波次统计(删除后未重建,剩余订单序号保持不变) + const remainingIndexRows = await this.ctx.model.query(` + SELECT wave_id, COUNT(*) AS remaining_count + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + GROUP BY wave_id + `, { + replacements: { + warehouseId, + waveIds: affectedWaveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const remainingCountMap = new Map(); + for (const row of Array.isArray(remainingIndexRows) ? remainingIndexRows : []) { + const waveId = Number(row && row.wave_id || 0); + const remainingCount = Number(row && row.remaining_count || 0); + if (Number.isInteger(waveId) && waveId > 0) { + remainingCountMap.set(waveId, remainingCount); + } + } + + const updatedWaveIds = []; + const emptiedWaveIds = []; + for (const waveId of affectedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + if (remainingCount > 0) { + updatedWaveIds.push(waveId); + } else { + emptiedWaveIds.push(waveId); + } + } + + for (const waveId of updatedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :remainingCount, + processed_orders = LEAST(processed_orders, :remainingCount), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `, { + replacements: { + warehouseId, + waveId, + remainingCount, + }, + transaction, + }); + } + + if (emptiedWaveIds.length > 0) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = 0, + processed_orders = 0, + wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + warehouseId, + waveIds: emptiedWaveIds, + }, + transaction, + }); + } + } + + // 移除任务订单关联记录,任务进度不再包含被移出波次的拦截单 + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `, { + replacements: { + taskId, + warehouseId, + orderIds: normalizedRemovableRows.map(row => Number(row.id)), + }, + transaction, + }); + + // 同步移除拦截单对应的篮子明细(散单模式 box_type=2 绑定订单),避免遗留空盒 + const taskBoxColumnSet = await this.getTableColumnSet('wms_wave_pick_task_box'); + const taskBoxWarehouseFilterSql = taskBoxColumnSet.has('warehouse_id') ? ' AND warehouse_id = :warehouseId' : ''; + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_box + WHERE task_id = :taskId + AND order_id IN (:orderIds) + ${taskBoxWarehouseFilterSql} + `, { + replacements: { + taskId, + warehouseId, + orderIds: normalizedRemovableRows.map(row => Number(row.id)), + }, + transaction, + }); + } + } + + // 目标订单全部被拦截跳过:不做任何拣货/库存变更,直接成功返回 + if (targetOrderIds.length <= 0) { + // mode=1(全部确认)时任务标记完成;mode=2 依据任务进度判断 + const skipProgressBeforeComplete = await this.getTaskPickProgress(taskId, warehouseId, transaction); + const skipTaskCompleted = mode === 1 || skipProgressBeforeComplete.isCompleted; + if (skipTaskCompleted) { + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = 2, + finish_time = CASE WHEN finish_time IS NULL THEN NOW() ELSE finish_time END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + // 同步更新波次关联状态为已拣 + const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave'); + const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND warehouse_id = :warehouseId' : ''; + await this.ctx.model.query(` + UPDATE wms_wave_pick_task_wave + SET status = 1, + pick_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + ${taskWaveWarehouseFilterSql} + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } else { + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = CASE WHEN status = 0 THEN 1 ELSE status END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } + + await transaction.commit(); + const skipProgress = await this.getTaskPickProgress(taskId, warehouseId); + await this._writePickCompleteActionLog({ + taskId, + warehouseId, + operatorId, + operatorName, + targetOrderIds: [], + mode, + isCompleted: skipProgress.isCompleted, + progress: skipProgress, + skippedInterceptedOrders, + }); + await this._afterSkipInterceptedPostActions({ + warehouseId, + operatorId, + operatorName, + removedFromWaveOrderLogItems, + removedFromWaveOrderIds, + affectedWaveIds: affectedWaveIdsForUnbind, + }); + return { + task_id: taskId, + mode, + confirmed_order_ids: [], + skipped_intercepted_order_ids: skippedInterceptedOrders.map(item => item.order_id), + skipped_intercepted_orders: skippedInterceptedOrders, + removed_from_wave_order_ids: removedFromWaveOrderIds, + kept_intercepted_order_ids: keptInterceptedOrderIds, + is_completed: skipProgress.isCompleted, + task_completed: skipTaskCompleted, + progress: { + total_orders: skipProgress.totalOrders, + picked_orders: skipProgress.pickedOrders, + pending_orders: skipProgress.pendingOrders, + }, + }; + } + + // 检查目标订单是否已分配储位(storage_status='fin'),防止订单在波次中被取消储位分配后仍然完成拣货 + if (targetOrderIds.length > 0) { + const orderModel = await this.getOrderModel(warehouseId); + const unallocatedOrders = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: targetOrderIds, + }, + storage_status: { + [this.app.Sequelize.Op.ne]: 'fin', + }, + }, + attributes: [ 'id', 'storage_status' ], + raw: true, + transaction, + }); + + if (unallocatedOrders && unallocatedOrders.length > 0) { + const detailList = unallocatedOrders.map( + o => `订单${o.id}(storage_status=${o.storage_status})` + ).join(';'); + throw this.createBusinessError( + `以下订单未分配储位,无法完成拣货:${detailList}`, + 400 + ); + } + } + + await ctx.model.query(` + UPDATE wms_wave_pick_task_order + SET pick_status = 1, + picked_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `, { + replacements: { + taskId, + warehouseId, + orderIds: targetOrderIds, + }, + transaction, + }); + + const orderModel = await this.getOrderModel(warehouseId); + await orderModel.update({ + pick_status: 'fin', + }, { + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: targetOrderIds, + }, + }, + transaction, + validate: false, + hooks: false, + }); + + // 先查询并锁定 pending 的 picking 记录,汇总各 storage_id 的扣减量 + const pickingSummaryRows = await ctx.model.query(` + SELECT + p.storage_id, + SUM(p.quantity) AS total_qty + FROM wms_picking p + WHERE p.order_id IN (:orderIds) + AND p.warehouse_id = :warehouseId + AND p.status = 'pending' + AND p.deleted_at IS NULL -- 排除软删除记录,防止已删除的 picking 纳入锁定量汇总 + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + GROUP BY p.storage_id + FOR UPDATE + `, { + replacements: { + orderIds: targetOrderIds, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedSummaryRows = Array.isArray(pickingSummaryRows) ? pickingSummaryRows : []; + if (normalizedSummaryRows.length > 0) { + const storageIds = normalizedSummaryRows.map(r => Number(r.storage_id)); + const storageQtyMap = new Map(); + for (const row of normalizedSummaryRows) { + storageQtyMap.set(Number(row.storage_id), Number(row.total_qty) || 0); + } + + // 加行锁校验 locked_quantity >= 扣减数量 + const storageRows = await ctx.model.Storage.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: storageIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'locked_quantity', 'quantity', 'store_id', 'stock_id', 'batch_no', 'inventory_type', 'space_id' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + const locked = Number(sRow.locked_quantity) || 0; + if (locked < deduction) { + throw this.createBusinessError( + `库存记录 ${sid} 锁定数量不足:当前锁定 ${locked},需扣减 ${deduction}`, + 400 + ); + } + } + + // 构建 CASE WHEN 语句 + const caseClauses = normalizedSummaryRows + .map(r => `WHEN ${Number(r.storage_id)} THEN ${Number(r.total_qty)}`) + .join(' '); + + await ctx.model.query(` + UPDATE wms_storage + SET locked_quantity = locked_quantity - CASE id ${caseClauses} END, + quantity = quantity - CASE id ${caseClauses} END, + updated_at = NOW() + WHERE id IN (:storageIds) + AND warehouse_id = :warehouseId + `, { + replacements: { + storageIds, + warehouseId, + }, + transaction, + }); + + // 写入 wms_storage_transaction 出库流水 + const transactionRows = []; + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + if (deduction <= 0) continue; + const beforeQty = Number(sRow.quantity) || 0; + const beforeLocked = Number(sRow.locked_quantity) || 0; + transactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: Number(sRow.store_id) || 0, + stock_id: Number(sRow.stock_id) || 0, + storage_id: sid, + space_id: Number(sRow.space_id) || null, + quantity: deduction, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - deduction), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - deduction), + batch_no: sRow.batch_no || null, + inventory_type: sRow.inventory_type || 'ZP', + order_type: 'PICK_OUTBOUND', + order_no: targetOrderIds.join(',').slice(0, 255), + order_id: taskId, + source_order_codes: targetOrderIds.join(', '), + operator_id: String(operatorId), + operator_name: operatorName, + remark: '拣货完成出库', + created_at: new Date(), + }); + } + + if (transactionRows.length > 0) { + await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); + } + + } + + // 扣减完成后,更新 wms_picking.status 为完成状态(加 status 条件防重复) + await ctx.model.query(` + UPDATE wms_picking + SET status = 'fin', updated_at = NOW() + WHERE order_id IN (:orderIds) + AND warehouse_id = :warehouseId + AND status = 'pending' + AND deleted_at IS NULL -- 排除软删除记录,防止重复标记已完成删除的 picking + `, { + replacements: { + orderIds: targetOrderIds, + warehouseId, + }, + transaction, + }); + + const progress = await this.getTaskPickProgress(taskId, warehouseId, transaction); + // mode=1(全部确认)时任务直接标记完成;mode=2 依据任务进度判断 + const taskCompleted = mode === 1 || progress.isCompleted; + if (taskCompleted) { + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = 2, + finish_time = CASE WHEN finish_time IS NULL THEN NOW() ELSE finish_time END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + // 同步更新波次关联状态为已拣 + const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave'); + const taskWaveWarehouseFilterSql = taskWaveColumnSet.has('warehouse_id') ? ' AND warehouse_id = :warehouseId' : ''; + await ctx.model.query(` + UPDATE wms_wave_pick_task_wave + SET status = 1, + pick_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + ${taskWaveWarehouseFilterSql} + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } else { + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET status = CASE WHEN status = 0 THEN 1 ELSE status END, + start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } + + await transaction.commit(); + + // 写入操作日志 + await this._writePickCompleteActionLog({ + taskId, + warehouseId, + operatorId, + operatorName, + targetOrderIds, + mode, + isCompleted: progress.isCompleted, + progress, + skippedInterceptedOrders, + }); + + // 被移出波次的拦截订单:写订单操作日志 + 触发策略快扫(不影响主流程) + await this._afterSkipInterceptedPostActions({ + warehouseId, + operatorId, + operatorName, + removedFromWaveOrderLogItems, + removedFromWaveOrderIds, + affectedWaveIds: affectedWaveIdsForUnbind, + }); + + // 写入 order_operation_log 拣货完成日志 + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logPayloads = targetOrderIds.map(orderId => ({ + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_PICK_COMPLETE', + operator: { + id: operatorId ? String(operatorId) : null, + name: operatorName || 'system', + }, + extras: { + message: `订单${orderId}拣货完成`, + warehouseId, + externalLogType: 'API', + }, + })); + await operationLogService.createOperationLogs(logPayloads); + } + } catch (e) { + this.ctx.logger.warn('[pick.wavePickTaskComplete] 写入 order_operation_log 失败,不影响主流程', { + error: e && e.message, + targetOrderIds, + }); + } + + // 通知仓库面板刷新(大屏增量更新,失败不影响主流程) + await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId)); + + return { + task_id: taskId, + mode, + confirmed_order_ids: targetOrderIds, + skipped_intercepted_order_ids: skippedInterceptedOrders.map(item => item.order_id), + skipped_intercepted_orders: skippedInterceptedOrders, + removed_from_wave_order_ids: removedFromWaveOrderIds, + kept_intercepted_order_ids: keptInterceptedOrderIds, + is_completed: progress.isCompleted, + task_completed: taskCompleted, + progress: { + total_orders: progress.totalOrders, + picked_orders: progress.pickedOrders, + pending_orders: progress.pendingOrders, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 拦截单跳过后的收尾动作(均不影响主流程): + * 1. 写入被移出波次拦截订单的 ORDER_WAVE_REMOVE 操作日志; + * 2. 触发波次策略快速扫描,让移出波次的订单重新进入可抓取池。 + * + * @param {Object} params 参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人名称。 + * @param {Array} params.removedFromWaveOrderLogItems 波次移除日志项。 + * @param {Array} params.removedFromWaveOrderIds 被移出波次的订单ID。 + * @return {Promise} 无返回值。 + */ + async _afterSkipInterceptedPostActions(params = {}) { + const warehouseId = Number(params && params.warehouseId || 0); + const operatorId = Number(params && params.operatorId || 0); + const operatorName = String(params && params.operatorName || '').trim() || 'system'; + const removedFromWaveOrderLogItems = Array.isArray(params && params.removedFromWaveOrderLogItems) + ? params.removedFromWaveOrderLogItems + : []; + const removedFromWaveOrderIds = Array.isArray(params && params.removedFromWaveOrderIds) + ? params.removedFromWaveOrderIds + : []; + const affectedWaveIds = Array.isArray(params && params.affectedWaveIds) + ? params.affectedWaveIds + : []; + + if (removedFromWaveOrderLogItems.length > 0) { + try { + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logPayloads = removedFromWaveOrderLogItems.map(item => ({ + businessType: 'order', + businessId: `${item.orderId}`, + operationCode: item.operationCode, + operator: { + id: operatorId ? String(operatorId) : null, + name: operatorName, + }, + extras: { + message: item.message, + warehouseId, + externalLogType: 'API', + }, + })); + await operationLogService.createOperationLogs(logPayloads); + } + } catch (e) { + this.ctx.logger.warn('[pick.wavePickTaskComplete] 写入波次移除操作日志失败,不影响主流程', { + error: e && e.message, + }); + } + } + + if (removedFromWaveOrderIds.length > 0) { + try { + const waveService = this.ctx.service + && this.ctx.service.systemMethods + && this.ctx.service.systemMethods.order + && this.ctx.service.systemMethods.order.wave; + if (waveService && typeof waveService.enqueueWaveStrategyQuickScanPostOrderChange === 'function') { + waveService.enqueueWaveStrategyQuickScanPostOrderChange( + warehouseId, + removedFromWaveOrderIds, + { triggerScan: true, source: 'pickSkipInterceptedRemoveWave' } + ); + } + } catch (e) { + this.ctx.logger.warn('[pick.wavePickTaskComplete] 触发波次策略快扫失败,不影响主流程', { + error: e && e.message, + }); + } + } + + // 拦截订单被移出波次后,补触发打印完成解绑车核实: + // 打印链路对含拦截订单的波次无法解绑(拦截订单不可打印),提交拣货移除拦截订单后重查一次, + // 保证任务结束时车能被释放(不影响主流程) + if (affectedWaveIds.length > 0) { + try { + const printService = this.ctx + && this.ctx.service + && this.ctx.service.systemMethods + && this.ctx.service.systemMethods.print; + if (printService && typeof printService.tryUnbindCartAfterPrintComplete === 'function') { + for (const waveId of [ ...new Set(affectedWaveIds) ]) { + await printService.tryUnbindCartAfterPrintComplete(waveId, warehouseId); + } + } + } catch (e) { + this.ctx.logger.warn('[pick.wavePickTaskComplete] 移除拦截订单后补触发解绑车失败,不影响主流程', { + error: e && e.message, + affectedWaveIds, + }); + } + } + } + + /** + * 写入拣货完成操作日志到 wms_wave_pick_action_log(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} params.taskId 波次拣货任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人名称。 + * @param {Array} params.targetOrderIds 确认完成的订单ID列表。 + * @param {number} params.mode 提交模式(1全部确认 2部分确认)。 + * @param {boolean} params.isCompleted 任务是否全部完成。 + * @param {Object} params.progress 任务进度信息。 + * @param {Array} params.skippedInterceptedOrders 被跳过的拦截订单(order_id + intercept_status)。 + * @return {Promise} 无返回值。 + */ + async _writePickCompleteActionLog(params = {}) { + const { + taskId, + warehouseId, + operatorId, + operatorName, + targetOrderIds, + mode, + isCompleted, + progress, + skippedInterceptedOrders, + } = params; + + const requestId = `pick_complete_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: taskId || 0, + warehouseId: warehouseId || 0, + waveId: null, + orderId: Array.isArray(targetOrderIds) && targetOrderIds.length > 0 ? targetOrderIds[0] : null, + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: 'pick_complete', + requestId, + operatorId: operatorId || 0, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify({ + task_id: taskId, + mode, + confirmed_order_ids: targetOrderIds, + confirmed_order_count: Array.isArray(targetOrderIds) ? targetOrderIds.length : 0, + skipped_intercepted_orders: Array.isArray(skippedInterceptedOrders) ? skippedInterceptedOrders : [], + is_completed: isCompleted, + progress: { + total_orders: progress && progress.totalOrders, + picked_orders: progress && progress.pickedOrders, + pending_orders: progress && progress.pendingOrders, + }, + operator_name: operatorName || 'system', + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + } + ); + } + + /** + * PDA 扫码查询拣货车信息。 + * + * @param {Object} params 查询参数。 + * @param {string} params.cartCode 拣货车编码。 + * @return {Promise} 拣货车详情。 + */ + async pickCartScan(params = {}) { + const cartCode = String(params && params.cartCode || '').trim(); + const { warehouseId } = this.resolveOperatorContext(); + + if (!cartCode) { + throw this.createBusinessError('cart_code 必填', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const cartRow = await this.getPickCartByCode(cartCode, warehouseId); + if (!cartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + + return this.buildPickCartDetail(cartRow); + } + + /** + * 绑定拣货任务与拣货车。 + * + * @param {Object} params 绑定参数。 + * @param {number} params.taskId 拣货任务ID。 + * @param {number} [params.cartId] 拣货车ID。 + * @param {string} [params.cartCode] 拣货车编码。 + * @return {Promise} 绑定结果。 + */ + async wavePickTaskBindCart(params = {}) { + const { ctx } = this; + const taskId = Number(params && params.taskId || 0); + const cartId = Number(params && params.cartId || 0); + const cartCode = String(params && params.cartCode || '').trim(); + const { operatorId, warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(taskId) || taskId <= 0) { + throw this.createBusinessError('task_id 必填且必须为正整数', 400); + } + if ((!Number.isInteger(cartId) || cartId <= 0) && !cartCode) { + throw this.createBusinessError('cart_id 或 cart_code 至少传一个', 400); + } + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw this.createBusinessError('未获取到操作人上下文', 401); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const taskRow = await this.getOwnedTask(taskId, operatorId); + const taskStatus = Number(taskRow && taskRow.status || 0); + if ([ 3, 9 ].includes(taskStatus)) { + throw this.createBusinessError('任务已完成或已取消,无法绑定拣货车', 400); + } + if (Number(taskRow && taskRow.warehouse_id || 0) !== warehouseId) { + throw this.createBusinessError('任务不属于当前仓库,无法绑定拣货车', 403); + } + + const targetCartRow = cartId > 0 + ? await this.getPickCartById(cartId, warehouseId) + : await this.getPickCartByCode(cartCode, warehouseId); + if (!targetCartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + if (Number(targetCartRow.status || 0) !== 1) { + throw this.createBusinessError('拣货车已停用,无法绑定', 400); + } + + const targetCartId = Number(targetCartRow.cart_id || 0); + const targetCartCode = String(targetCartRow.cart_code || '').trim(); + + const transaction = await ctx.model.transaction(); + try { + // 检查任务是否已有活跃的车绑定(正常绑定流程,不支持换车,需先解绑) + const taskActiveBindingRows = await ctx.model.query(` + SELECT + b.id, + b.cart_id, + t.current_cart_code_snapshot AS cart_code + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t + ON t.id = b.task_id + WHERE b.task_id = :taskId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + ORDER BY b.id DESC + LIMIT 1 + `, { + replacements: { + taskId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const taskActiveBinding = Array.isArray(taskActiveBindingRows) && taskActiveBindingRows.length > 0 + ? taskActiveBindingRows[0] + : null; + if (taskActiveBinding) { + throw this.createBusinessError('任务已绑定拣货车,请先解绑后再重新绑定', 409, { + task_id: taskId, + cart_id: Number(taskActiveBinding.cart_id || 0), + cart_code: String(taskActiveBinding.cart_code || '').trim() || null, + }); + } + + // 检查车是否已有活跃的任务绑定 + const cartActiveBindingRows = await ctx.model.query(` + SELECT + b.id, + b.task_id, + t.task_no + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t + ON t.id = b.task_id + WHERE b.cart_id = :cartId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + ORDER BY b.id DESC + LIMIT 1 + `, { + replacements: { + cartId: targetCartId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const cartActiveBinding = Array.isArray(cartActiveBindingRows) && cartActiveBindingRows.length > 0 + ? cartActiveBindingRows[0] + : null; + if (cartActiveBinding) { + const boundTaskId = Number(cartActiveBinding.task_id || 0); + if (boundTaskId === taskId) { + throw this.createBusinessError('该任务已绑定此拣货车,无需重复绑定', 409, { + task_id: taskId, + cart_id: targetCartId, + cart_code: targetCartCode, + }); + } + // 车已有其他活跃绑定,无论旧任务状态如何均应阻止 + throw this.createBusinessError('该拣货车已绑定其他任务,请先解绑后再重新绑定', 409, { + task_id: boundTaskId, + task_no: String(cartActiveBinding.task_no || '').trim() || null, + cart_id: targetCartId, + cart_code: targetCartCode, + }); + } + + await ctx.model.query(` + INSERT INTO wms_pick_task_cart_binding ( + task_id, + cart_id, + cart_code_snapshot, + warehouse_id, + bind_user_id, + bind_type, + is_active, + bind_time, + create_time, + update_time + ) VALUES ( + :taskId, + :cartId, + :cartCode, + :warehouseId, + :operatorId, + 1, + 1, + NOW(), + NOW(), + NOW() + ) + `, { + replacements: { + taskId, + cartId: targetCartId, + cartCode: targetCartCode, + warehouseId, + operatorId, + }, + transaction, + }); + + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET current_cart_id = :cartId, + current_cart_code_snapshot = :cartCode, + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + cartId: targetCartId, + cartCode: targetCartCode, + }, + transaction, + }); + + await transaction.commit(); + + const latestCartRow = await this.getPickCartById(targetCartId, warehouseId); + return { + task_id: taskId, + task_no: String(taskRow.task_no || '').trim(), + cart: this.buildPickCartDetail(latestCartRow || targetCartRow), + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 创建拣货车。 + * + * @param {Object} params 创建参数。 + * @param {string} params.cartCode 拣货车编码。 + * @param {string} [params.cartName] 拣货车名称。 + * @param {number} [params.status=1] 状态。 + * @return {Promise} 创建结果。 + */ + async pickCartCreate(params = {}) { + const { ctx } = this; + const cartCode = String(params && params.cartCode || '').trim(); + const cartName = String(params && params.cartName || '').trim(); + const status = this.normalizePickCartStatus(params && params.status, 1); + const { warehouseId } = this.resolveOperatorContext(); + + if (!cartCode) { + throw this.createBusinessError('cart_code 必填', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + // 使用事务:唯一性检查 + INSERT + LAST_INSERT_ID() 在同一连接,避免竞态 + const transaction = await ctx.model.transaction(); + let cartId = 0; + try { + await this.assertPickCartCodeUnique(cartCode, warehouseId, 0, transaction); + + await ctx.model.query(` + INSERT INTO wms_pick_cart ( + warehouse_id, + cart_code, + cart_name, + status, + create_time, + update_time + ) VALUES ( + :warehouseId, + :cartCode, + :cartName, + :status, + NOW(), + NOW() + ) + `, { + replacements: { + warehouseId, + cartCode, + cartName, + status, + }, + transaction, + }); + + const idRows = await ctx.model.query('SELECT LAST_INSERT_ID() AS cart_id', { + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + cartId = Number(Array.isArray(idRows) && idRows.length > 0 ? (idRows[0].cart_id || 0) : 0); + if (!Number.isInteger(cartId) || cartId <= 0) { + throw new Error('cartId 无效'); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error.message === 'cartId 无效') { + throw this.createBusinessError('拣货车创建失败', 500); + } + throw error; + } + + const cartRow = await this.getPickCartById(cartId, warehouseId); + return this.buildPickCartDetail(cartRow || { + cart_id: cartId, + warehouse_id: warehouseId, + cart_code: cartCode, + cart_name: cartName, + status, + }); + } + + /** + * 更新拣货车。 + * + * @param {Object} params 更新参数。 + * @param {number} params.cartId 拣货车ID。 + * @param {string} [params.cartCode] 拣货车编码。 + * @param {string} [params.cartName] 拣货车名称。 + * @param {number} [params.status] 状态。 + * @return {Promise} 更新结果。 + */ + async pickCartUpdate(params = {}) { + const { ctx } = this; + const cartId = Number(params && params.cartId || 0); + const { warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(cartId) || cartId <= 0) { + throw this.createBusinessError('cart_id 必填且必须为正整数', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const cartRow = await this.getPickCartById(cartId, warehouseId); + if (!cartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + + const nextCartCode = params && params.cartCode !== undefined + ? String(params.cartCode || '').trim() + : String(cartRow.cart_code || '').trim(); + const nextCartName = params && params.cartName !== undefined + ? String(params.cartName || '').trim() + : String(cartRow.cart_name || '').trim(); + const nextStatus = params && params.status !== undefined + ? this.normalizePickCartStatus(params.status, Number(cartRow.status || 1)) + : Number(cartRow.status || 1); + + if (!nextCartCode) { + throw this.createBusinessError('cart_code 必填', 400); + } + await this.assertPickCartCodeUnique(nextCartCode, warehouseId, cartId); + if (nextStatus === 0) { + // 通过绑定表检查车是否被活动任务占用 + const activeBindingRows = await ctx.model.query(` + SELECT b.id + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t ON t.id = b.task_id + WHERE b.cart_id = :cartId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + AND t.status IN (0, 1) + LIMIT 1 + `, { + replacements: { cartId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + if (Array.isArray(activeBindingRows) && activeBindingRows.length > 0) { + throw this.createBusinessError('拣货车已绑定活动任务,无法停用', 400); + } + } + + await ctx.model.query(` + UPDATE wms_pick_cart + SET cart_code = :cartCode, + cart_name = :cartName, + status = :status, + update_time = NOW() + WHERE id = :cartId + AND warehouse_id = :warehouseId + `, { + replacements: { + cartId, + warehouseId, + cartCode: nextCartCode, + cartName: nextCartName, + status: nextStatus, + }, + }); + + if (nextCartCode !== String(cartRow.cart_code || '').trim()) { + await ctx.model.query(` + UPDATE wms_pick_task_cart_binding + SET cart_code_snapshot = :cartCode, + update_time = NOW() + WHERE cart_id = :cartId + AND warehouse_id = :warehouseId + AND is_active = 1 + `, { + replacements: { + cartId, + warehouseId, + cartCode: nextCartCode, + }, + }); + + await ctx.model.query(` + UPDATE wms_wave_pick_task + SET current_cart_code_snapshot = :cartCode, + update_time = NOW() + WHERE current_cart_id = :cartId + AND warehouse_id = :warehouseId + `, { + replacements: { + cartId, + warehouseId, + cartCode: nextCartCode, + }, + }); + } + + const latestCartRow = await this.getPickCartById(cartId, warehouseId); + return this.buildPickCartDetail(latestCartRow || { + ...cartRow, + cart_id: cartId, + cart_code: nextCartCode, + cart_name: nextCartName, + status: nextStatus, + }); + } + + /** + * 删除拣货车。 + * + * @param {Object} params 删除参数。 + * @param {number} params.cartId 拣货车ID。 + * @return {Promise} 删除结果。 + */ + async pickCartDelete(params = {}) { + const { ctx } = this; + const cartId = Number(params && params.cartId || 0); + const { warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(cartId) || cartId <= 0) { + throw this.createBusinessError('cart_id 必填且必须为正整数', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const cartRow = await this.getPickCartById(cartId, warehouseId); + if (!cartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + if (Number(cartRow.current_task_id || 0) > 0) { + throw this.createBusinessError('拣货车当前已绑定任务,无法删除', 400); + } + + const bindingRows = await ctx.model.query(` + SELECT id + FROM wms_pick_task_cart_binding + WHERE cart_id = :cartId + AND warehouse_id = :warehouseId + AND is_active = 1 + LIMIT 1 + `, { + replacements: { + cartId, + warehouseId, + }, + type: ctx.model.QueryTypes.SELECT, + }); + if (Array.isArray(bindingRows) && bindingRows.length > 0) { + throw this.createBusinessError('拣货车存在有效绑定记录,无法删除', 400); + } + + await ctx.model.query(` + DELETE FROM wms_pick_cart + WHERE id = :cartId + AND warehouse_id = :warehouseId + LIMIT 1 + `, { + replacements: { + cartId, + warehouseId, + }, + }); + + return { + cart_id: cartId, + deleted: true, + }; + } + + /** + * 批量删除拣货车。已绑定任务或存在有效绑定记录的将被跳过。 + * + * @param {Object} params 删除参数。 + * @param {Array} params.ids 拣货车ID列表。 + * @return {Promise} { deleted_ids, skipped_ids, deleted_count, skipped_count } + */ + async pickCartBatchDelete(params = {}) { + const { ctx } = this; + const rawIds = Array.isArray(params && params.ids) ? params.ids : []; + const { warehouseId } = this.resolveOperatorContext(); + + if (!Array.isArray(rawIds) || rawIds.length === 0) { + throw this.createBusinessError('ids 必填且必须为非空数组', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + // 去重并转为数字,过滤非法值 + const idSet = new Set(); + for (const id of rawIds) { + const num = Number(id); + if (Number.isInteger(num) && num > 0) { + idSet.add(num); + } + } + const ids = Array.from(idSet); + if (ids.length === 0) { + throw this.createBusinessError('ids 中没有合法的拣货车ID', 400); + } + + // 1) 查出当前仓库下这些拣货车的 current_task_id + const cartRows = await ctx.model.query(` + SELECT id, cart_code, current_task_id + FROM wms_pick_cart + WHERE id IN (:ids) + AND warehouse_id = :warehouseId + `, { + replacements: { ids, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + // 2) 查出有效绑定记录 + const bindingRows = await ctx.model.query(` + SELECT cart_id + FROM wms_pick_task_cart_binding + WHERE cart_id IN (:ids) + AND warehouse_id = :warehouseId + AND is_active = 1 + `, { + replacements: { ids, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + const bindingCartIds = new Set( + (Array.isArray(bindingRows) ? bindingRows : []).map(r => Number(r.cart_id || 0)).filter(id => id > 0) + ); + + // 3) 分类:已绑定任务 / 有效绑定记录 → skip;其余 → delete + const skipIds = []; + const deleteIds = []; + for (const row of (Array.isArray(cartRows) ? cartRows : [])) { + const cartId = Number(row.id || 0); + if (Number(row.current_task_id || 0) > 0 || bindingCartIds.has(cartId)) { + skipIds.push(cartId); + } else { + deleteIds.push(cartId); + } + } + + // ids 中存在但 cartRows 中不存在的(不属于该仓库或已不存在),也归入 skip + const foundIds = new Set((Array.isArray(cartRows) ? cartRows : []).map(r => Number(r.id || 0))); + for (const id of ids) { + if (!foundIds.has(id) && !skipIds.includes(id)) { + skipIds.push(id); + } + } + + // 4) 执行删除 + if (deleteIds.length > 0) { + await ctx.model.query(` + DELETE FROM wms_pick_cart + WHERE id IN (:deleteIds) + AND warehouse_id = :warehouseId + `, { + replacements: { deleteIds, warehouseId }, + }); + } + + return { + deleted_ids: deleteIds, + skipped_ids: skipIds, + deleted_count: deleteIds.length, + skipped_count: skipIds.length, + }; + } + + /** + * 查询拣货车详情。 + * + * @param {Object} params 查询参数。 + * @param {number} params.cartId 拣货车ID。 + * @return {Promise} 详情结果。 + */ + async pickCartDetail(params = {}) { + const cartId = Number(params && params.cartId || 0); + const { warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(cartId) || cartId <= 0) { + throw this.createBusinessError('cart_id 必填且必须为正整数', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const cartRow = await this.getPickCartById(cartId, warehouseId); + if (!cartRow) { + throw this.createBusinessError('拣货车不存在', 404); + } + + return this.buildPickCartDetail(cartRow); + } + + /** + * 分页查询拣货车列表。 + * + * @param {Object} params 查询参数。 + * @param {Object} [params.pagination] 分页参数。 + * @param {Object} [params.where] 查询条件。 + * @return {Promise} 列表结果。 + */ + async pickCartList(params = {}) { + const { ctx } = this; + const pagination = params && params.pagination && typeof params.pagination === 'object' + ? params.pagination + : {}; + const where = params && params.where && typeof params.where === 'object' + ? params.where + : {}; + const { warehouseId } = this.resolveOperatorContext(); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const page = Math.max(1, Number(pagination.page || 1)); + const pageSize = Math.min(100, Math.max(1, Number(pagination.pageSize || pagination.page_size || 20))); + const offset = (page - 1) * pageSize; + const keyword = String(where.keyword || '').trim(); + const status = where.status !== undefined && where.status !== null && where.status !== '' + ? this.normalizePickCartStatus(where.status, null) + : null; + const currentTaskId = Number(where.current_task_id || where.currentTaskId || 0); + const replacements = { + warehouseId, + offset, + pageSize, + }; + const filters = [ 'c.warehouse_id = :warehouseId' ]; + + if (keyword) { + replacements.keyword = `%${keyword}%`; + filters.push('(c.cart_code LIKE :keyword OR c.cart_name LIKE :keyword)'); + } + if (status === 0 || status === 1) { + replacements.status = status; + filters.push('c.status = :status'); + } + if (Number.isInteger(currentTaskId) && currentTaskId > 0) { + replacements.currentTaskId = currentTaskId; + filters.push('c.current_task_id = :currentTaskId'); + } + + const whereSql = filters.join(' AND '); + const countRows = await ctx.model.query(` + SELECT COUNT(1) AS total + FROM wms_pick_cart c + WHERE ${whereSql} + `, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + const total = Number(countRows && countRows[0] && countRows[0].total || 0); + + const rows = await ctx.model.query(` + SELECT + c.id AS cart_id, + c.warehouse_id, + c.cart_code, + c.cart_name, + c.status, + c.current_task_id, + c.bind_user_id, + c.last_bind_time, + c.last_seen_time, + c.create_time, + c.update_time, + t.task_no AS current_task_no, + t.status AS current_task_status + FROM wms_pick_cart c + LEFT JOIN wms_wave_pick_task t + ON t.id = c.current_task_id + WHERE ${whereSql} + ORDER BY c.id DESC + LIMIT :offset, :pageSize + `, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + + return { + list: (Array.isArray(rows) ? rows : []).map(row => this.buildPickCartDetail(row)), + pagination: { + page, + pageSize, + total, + totalPages: total > 0 ? Math.ceil(total / pageSize) : 0, + }, + }; + } +} + +module.exports = PickSystemService; diff --git a/app/service/systems/pickCart.js b/app/service/systems/pickCart.js new file mode 100644 index 0000000..4799b0f --- /dev/null +++ b/app/service/systems/pickCart.js @@ -0,0 +1,99 @@ +'use strict'; + +const Service = require('egg').Service; + +class PickCartSystemService extends Service { + /** + * 按拣货车编码扫码查询。 + * + * @param {Object} params 查询参数。 + * @param {string} params.cartCode 拣货车编码。 + * @return {Promise} 拣货车信息。 + */ + async scan(params = {}) { + return await this.service.systems.pick.pickCartScan(params); + } + + /** + * 绑定拣货任务与拣货车。 + * + * @param {Object} params 绑定参数。 + * @return {Promise} 绑定结果。 + */ + async bindTaskCart(params = {}) { + return await this.service.systems.pick.wavePickTaskBindCart(params); + } + + /** + * 创建拣货车。 + * + * @param {Object} params 创建参数。 + * @return {Promise} 创建结果。 + */ + async create(params = {}) { + return await this.service.systems.pick.pickCartCreate(params); + } + + /** + * 更新拣货车。 + * + * @param {Object} params 更新参数。 + * @return {Promise} 更新结果。 + */ + async update(params = {}) { + return await this.service.systems.pick.pickCartUpdate(params); + } + + /** + * 删除拣货车。 + * + * @param {Object} params 删除参数。 + * @return {Promise} 删除结果。 + */ + async delete(params = {}) { + return await this.service.systems.pick.pickCartDelete(params); + } + + /** + * 批量删除拣货车。已绑定任务的将被跳过。 + * + * @param {Object} params 删除参数。 + * @param {Array} params.ids 拣货车ID列表。 + * @return {Promise} 批量删除结果。 + */ + async batchDelete(params = {}) { + return await this.service.systems.pick.pickCartBatchDelete(params); + } + + /** + * 查询拣货车详情。 + * + * @param {Object} params 查询参数。 + * @return {Promise} 详情结果。 + */ + async detail(params = {}) { + return await this.service.systems.pick.pickCartDetail(params); + } + + /** + * 分页查询拣货车列表。 + * + * @param {Object} params 查询参数。 + * @return {Promise} 列表结果。 + */ + async list(params = {}) { + return await this.service.systems.pick.pickCartList(params); + } + + /** + * 拣货车编码查重。 + * + * @param {Object} params 查询参数。 + * @return {Promise} 查重结果。 + */ + async codeDuplicateCheck(params = {}) { + return await this.service.systems.pick.pickCartCodeDuplicateCheck(params); + } +} + +module.exports = PickCartSystemService; diff --git a/app/service/systems/pick_compensation.js b/app/service/systems/pick_compensation.js new file mode 100644 index 0000000..1190437 --- /dev/null +++ b/app/service/systems/pick_compensation.js @@ -0,0 +1,743 @@ +'use strict'; + +const MainService = require('../main'); + +const MAX_BATCH_SIZE = 500; +const COMPENSATION_STATUS = 'fin_compensated'; +const COMPENSATION_ORDER_TYPE = 'PICK_COMPENSATION'; +const CANCELLED_RELEASED_STATUS = 'cancelled_released'; + +/** + * 拣货完成补偿服务。 + * + * 当 wavePickTaskComplete 因历史 BUG 遗漏扣减库存操作时, + * 本服务扫描 wms_picking 中 status='pending' 且订单已迁移到 dispatch 表的记录, + * 以与 wavePickTaskComplete 一致的事务逻辑补扣库存并写入出库流水。 + */ +class PickCompensationService extends MainService { + /** + * 执行全局拣货补偿扫描与补偿。 + * 遍历所有存在 pending 拣货记录的仓库,对符合条件的记录执行补偿。 + * + * @return {Promise<{totalCompensated: number}>} 全局补偿结果。 + */ + async executeCompensation() { + const { ctx } = this; + + // Step 1: 查找所有存在 pending 拣货记录的仓库 + const warehouseRows = await ctx.model.query(` + SELECT DISTINCT warehouse_id + FROM wms_picking + WHERE status = 'pending' + AND warehouse_id > 0 + `, { + type: ctx.model.QueryTypes.SELECT, + }); + + const warehouses = (Array.isArray(warehouseRows) ? warehouseRows : []) + .map(row => Number(row.warehouse_id)) + .filter(id => Number.isInteger(id) && id > 0); + + if (warehouses.length === 0) { + return { totalCompensated: 0 }; + } + + let totalCompensated = 0; + + for (const warehouseId of warehouses) { + try { + const compensated = await this.compensateWarehouse(warehouseId); + totalCompensated += compensated; + } catch (error) { + ctx.logger.error( + `[pick-compensation] 仓库 ${warehouseId} 补偿失败: ${error.message}` + ); + } + } + + return { totalCompensated }; + } + + /** + * 对指定仓库执行单次拣货补偿。 + * 先释放已取消订单的库存锁定,再处理拣货完成的 dispatch 订单补偿。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 本次补偿的拣货记录数。 + */ + async compensateWarehouse(warehouseId) { + const { ctx } = this; + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + + if (!factory || typeof factory.getCurrentModel !== 'function' || typeof factory.getDispatchModel !== 'function') { + ctx.logger.warn(`[pick-compensation] 仓库 ${warehouseId} 订单分表工厂不可用,跳过`); + return 0; + } + + // 获取所有 pending 订单ID + const pendingOrderIds = await this.getPendingOrderIds(warehouseId); + if (pendingOrderIds.length === 0) { + return 0; + } + + const currentModel = await factory.getCurrentModel(warehouseId); + + let compensatedCount = 0; + + // Step A: 释放已取消订单的库存锁定 + const cancelledPickingRows = await this.findPendingPickingForCancelledOrders( + warehouseId, factory, pendingOrderIds + ); + if (cancelledPickingRows.length > 0) { + ctx.logger.info( + `[pick-compensation] 仓库 ${warehouseId} 发现 ${cancelledPickingRows.length} 条已取消订单待释放拣货记录` + ); + const released = await this.releaseCancelledInTransaction(warehouseId, cancelledPickingRows); + compensatedCount += released; + } + + // Step B: 查找符合条件的 dispatch 拣货记录 + const pickingRows = await this.findPendingPickingForDispatchOrders( + warehouseId, factory, currentModel, pendingOrderIds + ); + if (pickingRows.length === 0) { + return compensatedCount; + } + + ctx.logger.info( + `[pick-compensation] 仓库 ${warehouseId} 发现 ${pickingRows.length} 条待补偿拣货记录` + ); + + // Step C: 在事务中执行拣货完成补偿 + const dispatchCompensated = await this.compensateInTransaction(warehouseId, pickingRows); + compensatedCount += dispatchCompensated; + + if (dispatchCompensated > 0) { + const orderIds = [ ...new Set(pickingRows.map(r => Number(r.order_id))) ]; + const pickingIds = pickingRows.map(r => Number(r.id)); + const storageIds = [ ...new Set(pickingRows + .map(r => Number(r.storage_id)) + .filter(id => id > 0)) ]; + + ctx.logger.info( + `[pick-compensation] 仓库 ${warehouseId} 补偿完成:` + + `拣货记录 ${pickingIds.join(',')},` + + `订单 ${orderIds.join(',')},` + + `库存记录 ${storageIds.join(',')}` + ); + } + + return compensatedCount; + } + + /** + * 获取指定仓库下所有待处理拣货记录的订单ID列表。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 待处理的订单ID列表。 + */ + async getPendingOrderIds(warehouseId) { + const { ctx } = this; + + const pendingOrderRows = await ctx.model.query(` + SELECT DISTINCT p.order_id + FROM wms_picking p + WHERE p.status = 'pending' + AND p.warehouse_id = :warehouseId + AND p.warehouse_id > 0 + `, { + replacements: { warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + return (Array.isArray(pendingOrderRows) ? pendingOrderRows : []) + .map(row => Number(row.order_id)) + .filter(id => Number.isInteger(id) && id > 0); + } + + /** + * 查找仓库下待补偿的拣货记录(dispatch 拣货完成场景)。 + * 条件:status='pending',对应订单在 dispatch 表中 pick_status='fin', + * 且订单不在 current 表中(已迁移到配送表)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Object} factory OrderDeliveryFactory 实例。 + * @param {Object} currentModel 订单 current 表的 Sequelize 模型。 + * @param {Array} pendingOrderIds 待处理的订单ID列表。 + * @return {Promise>} 待补偿的拣货记录列表。 + */ + async findPendingPickingForDispatchOrders(warehouseId, factory, currentModel, pendingOrderIds) { + const { ctx, app } = this; + + if (!Array.isArray(pendingOrderIds) || pendingOrderIds.length === 0) { + return []; + } + + // 查询 current 表:哪些订单还在主表中 + const currentOrders = await currentModel.findAll({ + where: { + id: { [app.Sequelize.Op.in]: pendingOrderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + }); + + const currentOrderIdSet = new Set( + (Array.isArray(currentOrders) ? currentOrders : []) + .map(row => Number(row.id)) + ); + + // 查询 dispatch 表:哪些订单 pick_status='fin' + const dispatchModel = await factory.getDispatchModel(warehouseId); + const dispatchOrders = await dispatchModel.findAll({ + where: { + id: { [app.Sequelize.Op.in]: pendingOrderIds }, + warehouse_id: warehouseId, + pick_status: 'fin', + }, + attributes: [ 'id' ], + raw: true, + }); + + const dispatchOrderIdSet = new Set( + (Array.isArray(dispatchOrders) ? dispatchOrders : []) + .map(row => Number(row.id)) + ); + + // 符合条件的订单:在 dispatch 中 pick_status='fin',且不在 current 中 + const eligibleOrderIds = pendingOrderIds.filter( + id => dispatchOrderIdSet.has(id) && !currentOrderIdSet.has(id) + ); + + if (eligibleOrderIds.length === 0) { + return []; + } + + // 查询对应的拣货记录(带 storage_id,限制每批处理上限) + const pickingRows = await ctx.model.query(` + SELECT + p.id, + p.order_id, + p.warehouse_id, + p.storage_id, + p.quantity + FROM wms_picking p + WHERE p.status = 'pending' + AND p.warehouse_id = :warehouseId + AND p.order_id IN (:orderIds) + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + AND p.deleted_at IS NULL -- 排除软删除记录 + ORDER BY p.id ASC + LIMIT :limit + `, { + replacements: { + warehouseId, + orderIds: eligibleOrderIds, + limit: MAX_BATCH_SIZE, + }, + type: ctx.model.QueryTypes.SELECT, + }); + + return Array.isArray(pickingRows) ? pickingRows : []; + } + + /** + * 查找已取消订单关联的待处理拣货记录。 + * 在 pendingOrderIds 中筛选 dispatch 表中 status='cancel' 的订单, + * 返回对应的 wms_picking 记录(status='pending')。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Object} factory OrderDeliveryFactory 实例。 + * @param {Array} pendingOrderIds 待处理的订单ID列表。 + * @return {Promise>} 已取消订单对应的拣货记录列表。 + */ + async findPendingPickingForCancelledOrders(warehouseId, factory, pendingOrderIds) { + const { ctx, app } = this; + + if (!Array.isArray(pendingOrderIds) || pendingOrderIds.length === 0) { + return []; + } + + // 查询 dispatch 表中已取消的订单 + const dispatchModel = await factory.getDispatchModel(warehouseId); + const cancelledOrders = await dispatchModel.findAll({ + where: { + id: { [app.Sequelize.Op.in]: pendingOrderIds }, + warehouse_id: warehouseId, + status: 'cancel', + }, + attributes: [ 'id' ], + raw: true, + }); + + const cancelledOrderIds = (Array.isArray(cancelledOrders) ? cancelledOrders : []) + .map(row => Number(row.id)); + + if (cancelledOrderIds.length === 0) { + return []; + } + + // 查询对应的拣货记录(带 storage_id,限制每批处理上限) + const pickingRows = await ctx.model.query(` + SELECT + p.id, + p.order_id, + p.warehouse_id, + p.storage_id, + p.quantity + FROM wms_picking p + WHERE p.status = 'pending' + AND p.warehouse_id = :warehouseId + AND p.order_id IN (:orderIds) + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + AND p.deleted_at IS NULL -- 排除软删除记录 + ORDER BY p.id ASC + LIMIT :limit + `, { + replacements: { + warehouseId, + orderIds: cancelledOrderIds, + limit: MAX_BATCH_SIZE, + }, + type: ctx.model.QueryTypes.SELECT, + }); + + return Array.isArray(pickingRows) ? pickingRows : []; + } + + /** + * 在事务中释放已取消订单的库存锁定。 + * + * 事务步骤: + * 1. 重新查询 wms_picking(status='pending')汇总各 storage_id 的 SUM(quantity) + * 2. SELECT wms_storage FOR UPDATE + * 3. 校验 locked_quantity >= 解锁数量 + * 4. UPDATE wms_storage 只解锁 locked_quantity(不扣减 quantity) + * 5. UPDATE wms_picking SET status='cancelled_released' + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} cancelledPickingRows 已取消订单关联的拣货记录列表。 + * @return {Promise} 释放成功的拣货记录数。 + */ + async releaseCancelledInTransaction(warehouseId, cancelledPickingRows) { + const { ctx, app } = this; + + if (!Array.isArray(cancelledPickingRows) || cancelledPickingRows.length === 0) { + return 0; + } + + const pickingIds = cancelledPickingRows.map(row => Number(row.id)); + + const transaction = await ctx.model.transaction(); + + try { + // Step 1: 重新查询 wms_picking,确保只处理仍然 status='pending' 的记录 + // 使用 FOR UPDATE 行锁,防止并发事务读取到相同的 picking 记录导致重复释放锁定库存 + const confirmedRows = await ctx.model.query(` + SELECT + p.id, + p.order_id, + p.storage_id, + p.quantity + FROM wms_picking p + WHERE p.id IN (:pickingIds) + AND p.warehouse_id = :warehouseId + AND p.status = 'pending' + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + AND p.deleted_at IS NULL -- 排除软删除记录 + FOR UPDATE + `, { + replacements: { pickingIds, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedConfirmedRows = Array.isArray(confirmedRows) ? confirmedRows : []; + if (normalizedConfirmedRows.length === 0) { + await transaction.rollback(); + return 0; + } + + // 汇总各 storage_id 的 SUM(quantity) + const storageQtyMap = new Map(); + for (const row of normalizedConfirmedRows) { + const sid = Number(row.storage_id); + const qty = Number(row.quantity) || 0; + storageQtyMap.set(sid, (storageQtyMap.get(sid) || 0) + qty); + } + + const storageIds = [ ...storageQtyMap.keys() ]; + + // Step 2: SELECT wms_storage FOR UPDATE + const storageRows = await ctx.model.Storage.findAll({ + where: { + id: { [app.Sequelize.Op.in]: storageIds }, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', 'locked_quantity', 'quantity', + 'store_id', 'stock_id', 'batch_no', 'inventory_type', 'space_id', + ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + // Step 3: 校验 locked_quantity >= 解锁数量 + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + const locked = Number(sRow.locked_quantity) || 0; + if (locked < deduction) { + throw this.createBusinessError( + `库存记录 ${sid} 锁定数量不足:当前锁定 ${locked},需解锁 ${deduction}`, + 400 + ); + } + } + + // Step 4: UPDATE wms_storage 只解锁 locked_quantity(不扣减 quantity) + const summaryRows = []; + for (const [ sid, totalQty ] of storageQtyMap) { + summaryRows.push({ storage_id: sid, total_qty: totalQty }); + } + + const caseClauses = summaryRows + .map(r => `WHEN ${Number(r.storage_id)} THEN ${Number(r.total_qty)}`) + .join(' '); + + const explicitStorageIdList = storageIds.map(id => Number(id)).join(', '); + + await ctx.model.query(` + UPDATE wms_storage + SET locked_quantity = locked_quantity - CASE id ${caseClauses} END, + updated_at = NOW() + WHERE id IN (${explicitStorageIdList}) + AND warehouse_id = :warehouseId + `, { + replacements: { warehouseId }, + transaction, + }); + + // Step 4.5: 写入 wms_storage_transaction 解锁流水 + const unlockTransactionRows = []; + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + if (deduction <= 0) continue; + const beforeQty = Number(sRow.quantity) || 0; + const beforeLocked = Number(sRow.locked_quantity) || 0; + unlockTransactionRows.push({ + transaction_type: 'UNLOCK', + warehouse_id: warehouseId, + store_id: Number(sRow.store_id) || 0, + stock_id: Number(sRow.stock_id) || 0, + storage_id: sid, + space_id: Number(sRow.space_id) || null, + quantity: deduction, + before_quantity: beforeQty, + after_quantity: beforeQty, + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - deduction), + batch_no: sRow.batch_no || null, + inventory_type: sRow.inventory_type || 'ZP', + order_type: 'PICKING_CANCEL_UNLOCK', + order_no: normalizedConfirmedRows + .filter(r => Number(r.storage_id) === sid) + .map(r => String(r.order_id)) + .join(',') + .slice(0, 255), + order_id: 0, + operator_id: '', + operator_name: 'pick_compensation', + remark: '拣货补偿-释放已取消订单库存锁定', + created_at: new Date(), + }); + } + + if (unlockTransactionRows.length > 0) { + await ctx.model.StorageTransaction.bulkCreate(unlockTransactionRows, { transaction }); + } + + // Step 5: UPDATE wms_picking SET status='cancelled_released' + const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); + await ctx.model.query(` + UPDATE wms_picking + SET status = :status, + updated_at = NOW() + WHERE id IN (:pickingIds) + AND warehouse_id = :warehouseId + `, { + replacements: { + status: CANCELLED_RELEASED_STATUS, + pickingIds: compensatedPickingIds, + warehouseId, + }, + transaction, + }); + + await transaction.commit(); + + return compensatedPickingIds.length; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 在事务中执行拣货补偿,与 wavePickTaskComplete 保持一致的逻辑。 + * + * 事务步骤: + * 1. 重新查询 wms_picking(status='pending')汇总各 storage_id 的 SUM(quantity) + * 2. SELECT wms_storage FOR UPDATE + * 3. 校验 locked_quantity >= 扣减数量 + * 4. UPDATE wms_storage 扣减 locked_quantity 和 quantity(CASE WHEN) + * 5. 查询 dispatch 表获取订单的 delivery_order_code 和 source_order_codes, + * 为每个拣货记录 INSERT 一条 wms_storage_transaction(OUTBOUND, PICK_COMPENSATION), + * 同一 storage 的多条记录共享相同的 before/after 数量 + * 6. UPDATE wms_picking SET status='fin_compensated' + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} pickingRows 待补偿的拣货记录列表。 + * @return {Promise} 补偿成功的拣货记录数。 + */ + async compensateInTransaction(warehouseId, pickingRows) { + const { ctx, app } = this; + + if (!Array.isArray(pickingRows) || pickingRows.length === 0) { + return 0; + } + + const pickingIds = pickingRows.map(row => Number(row.id)); + + const transaction = await ctx.model.transaction(); + + try { + // Step 1: 重新查询 wms_picking,确保只处理仍然 status='pending' 的记录 + // 使用 FOR UPDATE 行锁,防止并发事务读取到相同的 picking 记录导致重复扣减库存 + const confirmedRows = await ctx.model.query(` + SELECT + p.id, + p.order_id, + p.storage_id, + p.quantity + FROM wms_picking p + WHERE p.id IN (:pickingIds) + AND p.warehouse_id = :warehouseId + AND p.status = 'pending' + AND p.storage_id IS NOT NULL + AND p.storage_id > 0 + AND p.deleted_at IS NULL -- 排除软删除记录 + FOR UPDATE + `, { + replacements: { pickingIds, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + + const normalizedConfirmedRows = Array.isArray(confirmedRows) ? confirmedRows : []; + if (normalizedConfirmedRows.length === 0) { + await transaction.rollback(); + return 0; + } + + // 汇总各 storage_id 的 SUM(quantity) + const storageQtyMap = new Map(); + for (const row of normalizedConfirmedRows) { + const sid = Number(row.storage_id); + const qty = Number(row.quantity) || 0; + storageQtyMap.set(sid, (storageQtyMap.get(sid) || 0) + qty); + } + + const storageIds = [ ...storageQtyMap.keys() ]; + + // Step 2: SELECT wms_storage FOR UPDATE + const storageRows = await ctx.model.Storage.findAll({ + where: { + id: { [app.Sequelize.Op.in]: storageIds }, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', 'locked_quantity', 'quantity', + 'store_id', 'stock_id', 'batch_no', + 'inventory_type', 'space_id', + ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + // Step 3: 校验 locked_quantity >= 扣减数量 + for (const sRow of storageRows) { + const sid = Number(sRow.id); + const deduction = storageQtyMap.get(sid) || 0; + const locked = Number(sRow.locked_quantity) || 0; + if (locked < deduction) { + throw this.createBusinessError( + `库存记录 ${sid} 锁定数量不足:当前锁定 ${locked},需扣减 ${deduction}`, + 400 + ); + } + } + + // Step 4: UPDATE wms_storage 扣减 locked_quantity 和 quantity(CASE WHEN) + const summaryRows = []; + for (const [ sid, totalQty ] of storageQtyMap) { + summaryRows.push({ storage_id: sid, total_qty: totalQty }); + } + + const caseClauses = summaryRows + .map(r => `WHEN ${Number(r.storage_id)} THEN ${Number(r.total_qty)}`) + .join(' '); + + const explicitStorageIdList = storageIds.map(id => Number(id)).join(', '); + + const [ updateResult ] = await ctx.model.query(` + UPDATE wms_storage + SET locked_quantity = locked_quantity - CASE id ${caseClauses} END, + quantity = quantity - CASE id ${caseClauses} END, + updated_at = NOW() + WHERE id IN (${explicitStorageIdList}) + AND warehouse_id = :warehouseId + `, { + replacements: { warehouseId }, + transaction, + }); + + if (!updateResult || Number(updateResult) === 0) { + ctx.logger.warn( + `[pick-compensation] wms_storage UPDATE 影响 0 行,storageIds=[${explicitStorageIdList}], warehouseId=${warehouseId}` + ); + } else { + ctx.logger.info( + `[pick-compensation] wms_storage UPDATE 影响 ${updateResult} 行,storageIds=[${explicitStorageIdList}], warehouseId=${warehouseId}` + ); + } + + // Step 5: INSERT wms_storage_transaction(每个拣货记录对应一条流水) + const confirmedOrderIds = [ ...new Set(normalizedConfirmedRows.map(r => Number(r.order_id))) ]; + + // 构建 storage_id -> storage row 映射 + const storageRowMap = new Map(); + for (const sRow of storageRows) { + storageRowMap.set(Number(sRow.id), sRow); + } + + // 构建 storage 变更前后的数量映射(同一 storage 多条拣货记录共享相同的 before/after) + const beforeQtyMap = new Map(); + const beforeLockedMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.id); + beforeQtyMap.set(sid, Number(sRow.quantity) || 0); + beforeLockedMap.set(sid, Number(sRow.locked_quantity) || 0); + } + + // 查询 dispatch 表获取 delivery_order_code 和 source_order_codes + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + const dispatchModel = factory && typeof factory.getDispatchModel === 'function' + ? await factory.getDispatchModel(warehouseId) + : null; + + const orderInfoMap = new Map(); + if (dispatchModel && confirmedOrderIds.length > 0) { + const dispatchRows = await dispatchModel.findAll({ + where: { + id: { [app.Sequelize.Op.in]: confirmedOrderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'delivery_order_code', 'source_order_codes' ], + raw: true, + transaction, + }); + for (const dRow of dispatchRows) { + orderInfoMap.set(Number(dRow.id), { + delivery_order_code: dRow.delivery_order_code, + source_order_codes: dRow.source_order_codes, + }); + } + } + + const transactionRows = []; + for (const pickRow of normalizedConfirmedRows) { + const orderId = Number(pickRow.order_id); + const orderInfo = orderInfoMap.get(orderId); + const sid = Number(pickRow.storage_id); + const deduction = Number(pickRow.quantity) || 0; + const sRow = storageRowMap.get(sid); + if (!sRow || deduction <= 0) continue; + + transactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: Number(sRow.store_id) || 0, + stock_id: Number(sRow.stock_id) || 0, + storage_id: sid, + space_id: Number(sRow.space_id) || null, + quantity: deduction, + before_quantity: beforeQtyMap.get(sid), + after_quantity: Math.max(0, beforeQtyMap.get(sid) - (storageQtyMap.get(sid) || 0)), + before_locked_quantity: beforeLockedMap.get(sid), + after_locked_quantity: Math.max(0, beforeLockedMap.get(sid) - (storageQtyMap.get(sid) || 0)), + batch_no: sRow.batch_no || null, + inventory_type: sRow.inventory_type || 'ZP', + order_type: COMPENSATION_ORDER_TYPE, + order_no: orderInfo?.delivery_order_code || String(orderId), + order_id: orderId, + source_order_codes: orderInfo?.source_order_codes || String(orderId), + operator_id: 'system', + operator_name: 'system', + remark: '拣货完成补偿出库', + created_at: new Date(), + }); + } + + if (transactionRows.length > 0) { + await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); + } + + // Step 6: UPDATE wms_picking SET status='fin_compensated' + const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); + await ctx.model.query(` + UPDATE wms_picking + SET status = :compensationStatus, + updated_at = NOW() + WHERE id IN (:pickingIds) + AND warehouse_id = :warehouseId + `, { + replacements: { + compensationStatus: COMPENSATION_STATUS, + pickingIds: compensatedPickingIds, + warehouseId, + }, + transaction, + }); + + await transaction.commit(); + + return compensatedPickingIds.length; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 生成带业务状态码的错误对象。 + * + * @param {string} message 错误文案。 + * @param {number} [code=400] 错误码。 + * @return {Error} 错误对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(message); + error.code = code; + return error; + } +} + +module.exports = PickCompensationService; diff --git a/app/service/systems/platform.js b/app/service/systems/platform.js index fa86c81..8733b5b 100644 --- a/app/service/systems/platform.js +++ b/app/service/systems/platform.js @@ -1,7 +1,1018 @@ // app/service/system/platform.js const Service = require('egg').Service; +const DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS = 600; +const PLATFORM_OAUTH_BIND_SUCCESS_CACHE_PREFIX = 'bind_pdd_code:'; +const PLATFORM_OAUTH_BIND_FAIL_CACHE_PREFIX = 'bind_pdd_code_fail:'; +const PLATFORM_OAUTH_BIND_EVENT_CHANNEL_PREFIX = 'bind_pdd_code_event:'; +const PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS = 60000; + class PlatformService extends Service { + /** + * 获取当前上下文中的仓库ID。 + * + * @return {number} 仓库ID,未获取到时返回 0。 + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); + + if (Number.isFinite(warehouseId) && warehouseId > 0) { + return warehouseId; + } + + return 0; + } + + /** + * 规范化平台授权绑定业务编码。 + * + * @param {*} code 原始业务编码 + * @return {string} 规范化后的业务编码 + */ + normalizePlatformOauthBindCode(code) { + return String(code || '').trim(); + } + + /** + * 获取平台授权绑定成功缓存键。 + * + * @param {string} code 业务编码 + * @return {string} 成功缓存键 + */ + getPlatformOauthBindSuccessCacheKey(code) { + const normalizedCode = this.normalizePlatformOauthBindCode(code); + return `${PLATFORM_OAUTH_BIND_SUCCESS_CACHE_PREFIX}${normalizedCode}`; + } + + /** + * 获取平台授权绑定失败缓存键。 + * + * @param {string} code 业务编码 + * @return {string} 失败缓存键 + */ + getPlatformOauthBindFailCacheKey(code) { + const normalizedCode = this.normalizePlatformOauthBindCode(code); + return `${PLATFORM_OAUTH_BIND_FAIL_CACHE_PREFIX}${normalizedCode}`; + } + + /** + * 获取平台授权绑定事件频道。 + * + * @param {string} code 业务编码 + * @return {string} 事件频道名称 + */ + getPlatformOauthBindEventChannel(code) { + const normalizedCode = this.normalizePlatformOauthBindCode(code); + return `${PLATFORM_OAUTH_BIND_EVENT_CHANNEL_PREFIX}${normalizedCode}`; + } + + /** + * 获取平台授权长轮询超时时间。 + * + * @param {*} timeoutMs 原始超时配置 + * @return {number} 毫秒级超时时间 + */ + getPlatformOauthLongPollTimeoutMs(timeoutMs = PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = Number(timeoutMs); + if (Number.isFinite(waitMs) && waitMs > 0) { + return Math.floor(waitMs); + } + + return PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS; + } + + /** + * 判断是否启用平台授权长轮询。 + * + * @param {Object} data 请求参数 + * @return {boolean} 是否启用长轮询 + */ + shouldUsePlatformOauthLongPoll(data = {}) { + return [ true, 1, '1', 'true' ].includes(data.longPoll) + || [ true, 1, '1', 'true' ].includes(data.long_poll) + || [ true, 1, '1', 'true' ].includes(data.wait); + } + + /** + * 查询平台授权绑定状态。 + * + * @param {string} code 业务编码 + * @return {Promise} 当前绑定状态 + */ + async getPlatformOauthBindState(code) { + const normalizedCode = this.normalizePlatformOauthBindCode(code); + if (!normalizedCode) { + return { + status: 'failed', + message: 'code不能为空', + access_token: '', + }; + } + + const successCacheKey = this.getPlatformOauthBindSuccessCacheKey(normalizedCode); + const failCacheKey = this.getPlatformOauthBindFailCacheKey(normalizedCode); + + let cachedToken = null; + try { + cachedToken = await this.app.getCacheAsync(successCacheKey); + } catch (error) { + this.ctx.logger.error(`[PlatformService.getPlatformOauthBindState] 查询成功缓存异常: ${error.message}`); + } + + const accessToken = typeof cachedToken === 'string' ? cachedToken.trim() : ''; + if (accessToken) { + return { + status: 'success', + message: '授权完成', + access_token: accessToken, + }; + } + + let failedCacheValue = null; + try { + failedCacheValue = await this.app.getCacheAsync(failCacheKey); + } catch (error) { + this.ctx.logger.error(`[PlatformService.getPlatformOauthBindState] 查询失败缓存异常: ${error.message}`); + } + + if (failedCacheValue !== null && failedCacheValue !== undefined && failedCacheValue !== '') { + const failedMessage = failedCacheValue && typeof failedCacheValue === 'object' && failedCacheValue.message + ? String(failedCacheValue.message).trim() + : '绑定失败,请重新授权'; + return { + status: 'failed', + message: failedMessage || '绑定失败,请重新授权', + access_token: '', + }; + } + + return { + status: 'pending', + message: '等待授权完成', + access_token: '', + }; + } + + /** + * 发布平台授权绑定结果事件。 + * + * @param {string} code 业务编码 + * @param {Object} payload 事件负载 + * @return {Promise} 无返回值 + */ + async publishPlatformOauthBindEvent(code, payload = {}) { + const normalizedCode = this.normalizePlatformOauthBindCode(code); + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + + if (!cacheRedis || !normalizedCode) { + return; + } + + const channel = this.getPlatformOauthBindEventChannel(normalizedCode); + const eventData = { + code: normalizedCode, + event_at: new Date().toISOString(), + ...payload, + }; + + try { + await cacheRedis.publish(channel, JSON.stringify(eventData)); + } catch (error) { + this.app.coreLogger.warn(`发布平台授权绑定事件失败: ${error.message}`); + } + } + + /** + * 等待平台授权绑定事件。 + * + * @param {string} code 业务编码 + * @param {number} timeoutMs 超时时间,单位毫秒 + * @return {Promise} 等待结果 + */ + async waitForPlatformOauthBindEvent(code, timeoutMs = PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS) { + const normalizedCode = this.normalizePlatformOauthBindCode(code); + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + if (!cacheRedis || !normalizedCode || typeof cacheRedis.duplicate !== 'function') { + return { + timed_out: true, + reason: 'redis_not_available', + event: null, + }; + } + + const channel = this.getPlatformOauthBindEventChannel(normalizedCode); + const waitMs = this.getPlatformOauthLongPollTimeoutMs(timeoutMs); + const subscriber = cacheRedis.duplicate(); + + return await new Promise(resolve => { + let settled = false; + let timer = null; + + function cleanup() { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + } + + const finalize = result => { + if (settled) { + return; + } + + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + }; + + function onMessage(messageChannel, message) { + if (messageChannel !== channel) { + return; + } + + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = message; + } + + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + }); + } + + function onError(error) { + this.app.coreLogger.warn(`订阅平台授权绑定事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + event: null, + }); + } + + timer = setTimeout(() => { + finalize({ + timed_out: true, + reason: 'timeout', + event: null, + }); + }, waitMs); + + subscriber.on('message', onMessage); + subscriber.on('error', onError); + + Promise.resolve(subscriber.subscribe(channel)).catch(error => { + this.app.coreLogger.warn(`订阅平台授权绑定频道失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_failed', + event: null, + }); + }); + }); + } + + /** + * 监听平台授权绑定结果。 + * + * @param {Object} data 请求参数 + * @param {string} [data.code] 业务编码 + * @param {string} [data.businessCode] 业务编码 + * @param {boolean} [data.longPoll] 是否启用长轮询 + * @param {number} [data.timeoutMs] 超时时间,单位毫秒 + * @return {Promise} 监听结果 + */ + async listenPlatformOauthBind(data = {}) { + const normalizedCode = this.normalizePlatformOauthBindCode(data.code || data.businessCode || data.business_code); + if (!normalizedCode) { + return { + success: false, + code: 0, + data: null, + message: 'code不能为空', + }; + } + + const useLongPoll = this.shouldUsePlatformOauthLongPoll(data); + let bindState = await this.getPlatformOauthBindState(normalizedCode); + + if (bindState.status !== 'pending' || !useLongPoll) { + return { + success: true, + code: 200, + data: { + code: normalizedCode, + status: bindState.status, + access_token: bindState.access_token, + source: 'cache', + }, + message: bindState.message, + }; + } + + const waitResult = await this.waitForPlatformOauthBindEvent(normalizedCode, data.timeoutMs || data.timeout_ms); + bindState = await this.getPlatformOauthBindState(normalizedCode); + + if (bindState.status === 'pending') { + return { + success: true, + code: 200, + data: { + code: normalizedCode, + status: 'pending', + access_token: '', + source: waitResult.timed_out ? 'timeout' : 'event', + }, + message: waitResult.timed_out ? '长轮询结束未检测到授权结果,请继续等待' : '授权状态暂未更新,请继续等待', + }; + } + + return { + success: true, + code: 200, + data: { + code: normalizedCode, + status: bindState.status, + access_token: bindState.access_token, + source: waitResult.timed_out ? 'cache' : 'event', + }, + message: bindState.message, + }; + } + + /** + * 获取平台表的全量字段列表。 + * + * @return {Array} 平台表字段列表。 + */ + getPlatformFullAttributes() { + const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.Platform && this.ctx.model.Platform.rawAttributes; + + if (!rawAttributes || typeof rawAttributes !== 'object') { + return []; + } + + return Object.keys(rawAttributes); + } + + /** + * 获取平台设置表的全量字段列表。 + * + * @return {Array} 平台设置表字段列表。 + */ + getPlatformSettingFullAttributes() { + const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.PlatformSetting && this.ctx.model.PlatformSetting.rawAttributes; + + if (!rawAttributes || typeof rawAttributes !== 'object') { + return []; + } + + return Object.keys(rawAttributes); + } + + /** + * 获取打印平台模型。 + * + * @return {Object|null} 打印平台模型,未注册时返回 null。 + */ + getPrintPlatformModel() { + const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; + + if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function') { + return null; + } + + return printPlatformModel; + } + + /** + * 将 Sequelize 记录转换为普通对象。 + * + * @param {Object} row 原始记录。 + * @return {Object|null} 普通对象。 + */ + toPlainRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + if (typeof row.get === 'function') { + return row.get({ plain: true }); + } + + return row; + } + + /** + * 规范化打印平台主键。 + * + * @param {*} printPlatformId 打印平台主键。 + * @return {number|null} 规范化后的主键。 + */ + normalizePrintPlatformId(printPlatformId) { + const normalizedId = Number(printPlatformId || 0); + + if (!Number.isFinite(normalizedId) || normalizedId <= 0) { + return null; + } + + return normalizedId; + } + + /** + * 批量加载打印平台编码映射。 + * + * 仅以 `wms_platform.print_platform_id -> wms_print_platform.platform_code` + * 为准;缺少模型、主键或关联记录时返回空映射,避免继续误用 sys_platform_code 直连语义。 + * + * @param {Array} platformRows 平台记录列表。 + * @return {Promise>} 打印平台ID到打印平台编码的映射。 + */ + async loadPrintPlatformCodeMap(platformRows = []) { + const printPlatformModel = this.getPrintPlatformModel(); + if (!printPlatformModel) { + return new Map(); + } + + const idSet = new Set(); + for (const platformRow of Array.isArray(platformRows) ? platformRows : []) { + const plainRow = this.toPlainRow(platformRow); + const printPlatformId = this.normalizePrintPlatformId(plainRow && plainRow.print_platform_id); + if (printPlatformId) { + idSet.add(printPlatformId); + } + } + + if (idSet.size <= 0) { + return new Map(); + } + + const rows = await printPlatformModel.findAll({ + attributes: [ 'id', 'platform_code' ], + where: { + id: Array.from(idSet), + }, + raw: true, + }); + + const printPlatformCodeMap = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + const printPlatformId = this.normalizePrintPlatformId(row && row.id); + const printPlatformCode = String(row && row.platform_code || '').trim(); + if (!printPlatformId || !printPlatformCode) { + continue; + } + + printPlatformCodeMap.set(printPlatformId, printPlatformCode); + } + + return printPlatformCodeMap; + } + + /** + * 批量加载打印平台 platid 映射。 + * + * 仅以 `wms_platform.print_platform_id -> wms_print_platform.platid` + * 为准;缺少模型、主键或关联记录时返回空映射。 + * + * @param {Array} platformRows 平台记录列表。 + * @return {Promise>} 打印平台ID到 platid 的映射。 + */ + async loadPrintPlatformPlatidMap(platformRows = []) { + const printPlatformModel = this.getPrintPlatformModel(); + if (!printPlatformModel) { + return new Map(); + } + + const idSet = new Set(); + for (const platformRow of Array.isArray(platformRows) ? platformRows : []) { + const plainRow = this.toPlainRow(platformRow); + const printPlatformId = this.normalizePrintPlatformId(plainRow && plainRow.print_platform_id); + if (printPlatformId) { + idSet.add(printPlatformId); + } + } + + if (idSet.size <= 0) { + return new Map(); + } + + const rows = await printPlatformModel.findAll({ + attributes: [ 'id', 'platid' ], + where: { + id: Array.from(idSet), + }, + raw: true, + }); + + const printPlatformPlatidMap = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + const printPlatformId = this.normalizePrintPlatformId(row && row.id); + const platid = Number(row && row.platid); + if (!printPlatformId || !Number.isFinite(platid)) { + continue; + } + + printPlatformPlatidMap.set(printPlatformId, platid); + } + + return printPlatformPlatidMap; + } + + /** + * 解析平台对应的默认快递接口平台编码。 + * + * 仅信任 `PrintPlatform.platform_code`;若模型未注册、主键缺失、 + * 未匹配到记录或目标字段为空,返回空字符串作为清晰兜底,不再退回旧语义。 + * + * @param {Object} row 平台记录。 + * @param {Map} [printPlatformCodeMap] 打印平台编码映射。 + * @return {string} 默认快递接口平台编码。 + */ + resolveDefaultExpressInterface(row, printPlatformCodeMap = new Map()) { + const plainRow = this.toPlainRow(row); + if (!plainRow) { + return ''; + } + + const nestedPrintPlatform = this.toPlainRow(plainRow.printPlatform); + const nestedPrintPlatformCode = String(nestedPrintPlatform && nestedPrintPlatform.platform_code || '').trim(); + if (nestedPrintPlatformCode) { + return nestedPrintPlatformCode; + } + + const printPlatformId = this.normalizePrintPlatformId(plainRow.print_platform_id); + if (!printPlatformId || !(printPlatformCodeMap instanceof Map)) { + return ''; + } + + const mappedPrintPlatformCode = String(printPlatformCodeMap.get(printPlatformId) || '').trim(); + if (!mappedPrintPlatformCode) { + this.ctx.logger.warn(`[PlatformService.resolveDefaultExpressInterface] print_platform_id=${printPlatformId} 缺少 platform_code,默认快递接口返回空值`); + return ''; + } + + return mappedPrintPlatformCode; + } + + /** + * 解析平台后处理路由编码。 + * + * 路由语义统一使用 `wms_platform.print_platform_id -> wms_print_platform.platform_code`。 + * 若未配置请求平台编码,则回退平台主编码,避免中断历史链路。 + * + * @param {Object} row 平台记录。 + * @param {Map} [printPlatformCodeMap] 打印平台编码映射。 + * @return {string} 平台后处理路由编码。 + */ + resolveRoutePlatformCode(row, printPlatformCodeMap = new Map()) { + const plainRow = this.toPlainRow(row); + if (!plainRow) { + return ''; + } + + const routePlatformCode = this.resolveDefaultExpressInterface(plainRow, printPlatformCodeMap); + if (routePlatformCode) { + return routePlatformCode; + } + + return String(plainRow.code || plainRow.value || '').trim(); + } + + /** + * 生成平台列表缓存键。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {boolean} [systemOnly=false] 是否仅返回系统基础平台列表。 + * @param {boolean} [full=false] 是否返回全量字段。 + * @return {string} 缓存键。 + */ + getPlatformListCacheKey(warehouseId = 0, systemOnly = false, full = false) { + const isFull = [ true, 1, '1', 'true' ].includes(full); + + if (systemOnly) { + return isFull ? 'platform:list:system:full' : 'platform:list:system'; + } + + const normalizedWarehouseId = Number(warehouseId || 0); + + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + return isFull ? `platform:list:${normalizedWarehouseId}:full` : `platform:list:${normalizedWarehouseId}`; + } + + return isFull ? 'platform:list:full' : 'platform:list'; + } + + /** + * 判断全量平台缓存是否存在字段结构过期。 + * + * 当缓存项中存在有效 print_platform_id,但缺少有效 platid 时, + * 认为缓存结构已过期,需要触发重建。 + * + * @param {*} cachedList 缓存中的平台列表。 + * @return {boolean} 是否结构过期。 + */ + isFullPlatformCacheSchemaStale(cachedList) { + if (!Array.isArray(cachedList) || cachedList.length <= 0) { + return false; + } + + return cachedList.some(item => { + if (!item || typeof item !== 'object') { + return false; + } + + const printPlatformId = Number(item.print_platform_id); + if (!Number.isFinite(printPlatformId) || printPlatformId <= 0) { + return false; + } + + return !Number.isFinite(Number(item.platid)); + }); + } + + /** + * 生成平台设置项展示名称。 + * + * @param {string} settingCode 平台设置编码。 + * @param {Object} platformItem 系统平台项。 + * @return {string} 展示名称。 + */ + buildMergedPlatformLabel(settingCode, platformItem) { + const normalizedSettingCode = String(settingCode || '').trim(); + const platformName = String(platformItem && (platformItem.name || platformItem.label || platformItem.code || platformItem.value) || '').trim(); + + if (!normalizedSettingCode) { + return platformName; + } + + if (!platformName) { + return normalizedSettingCode; + } + + return `${normalizedSettingCode} (${platformName})`; + } + + /** + * 规范化系统平台记录。 + * + * @param {Object} row 数据库记录。 + * @param {Map} [printPlatformCodeMap] 打印平台编码映射。 + * @return {Object|null} 规范化后的记录。 + */ + normalizePlatformRow(row, printPlatformCodeMap = new Map()) { + 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 = this.resolveDefaultExpressInterface(row, printPlatformCodeMap); + + return { + code, + name, + default_express_interface: defaultExpressInterface, + value: code, + label: name || code, + platform_code: code, + platform_name: name, + is_system_setting: false, + }; + } + + /** + * 从数据库加载平台设置列表。 + * + * 始终加载 warehouse_id IS NULL 的系统级设置;若 warehouseId 有效,则同时加载对应仓库的仓库级设置。 + * 结果按 code 升序、warehouse_id 降序排列,确保仓库级设置在合并时优先于系统级设置。 + * + * @param {number|string} warehouseId 仓库ID,无效时仅加载系统级设置。 + * @param {boolean} [full=false] 是否返回全量字段。 + * @return {Promise} 平台设置列表。 + */ + async loadPlatformSettingListFromDatabase(warehouseId = 0, full = false) { + const platformSettingModel = this.ctx.model && this.ctx.model.PlatformSetting; + if (!platformSettingModel || typeof platformSettingModel.findAll !== 'function') { + return []; + } + + const normalizedWarehouseId = Number(warehouseId || 0); + const isFull = [ true, 1, '1', 'true' ].includes(full); + const attributes = isFull + ? this.getPlatformSettingFullAttributes() + : [ 'id', 'code', 'platform_code', 'warehouse_id' ]; + + // 构建 where 条件:系统级设置(warehouse_id IS NULL)始终加载 + const whereConditions = [{ warehouse_id: null }]; + + // 仓库级设置:仅在 warehouseId 有效时加载 + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + whereConditions.push({ warehouse_id: normalizedWarehouseId }); + } + + const rows = await platformSettingModel.findAll({ + attributes, + where: { + [this.ctx.app.Sequelize.Op.or]: whereConditions, + }, + order: [[ 'code', 'ASC' ], [ 'warehouse_id', 'DESC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 规范化平台设置记录。 + * + * @param {Object} row 数据库记录。 + * @param {Map} platformMap 系统平台映射。 + * @return {Object|null} 规范化后的记录。 + */ + normalizePlatformSettingRow(row, platformMap) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + const platformCode = String(row.platform_code || '').trim(); + const platformItem = platformMap instanceof Map ? platformMap.get(platformCode) : null; + const label = this.buildMergedPlatformLabel(code, platformItem); + + return { + code, + name: label, + value: code, + label, + is_system_setting: true, + id: row.id === undefined || row.id === null ? null : row.id, + alias: '', + platform_code: String((platformItem && (platformItem.code || platformItem.value)) || platformCode || '').trim(), + platform_name: String((platformItem && (platformItem.name || platformItem.label || platformItem.value)) || '').trim(), + default_express_interface: String((platformItem && platformItem.default_express_interface) || '').trim(), + }; + } + + /** + * 规范化系统平台全量记录。 + * + * @param {Object} row 数据库记录。 + * @param {Map} [printPlatformCodeMap] 打印平台编码映射。 + * @param {Map} [printPlatformPlatidMap] 打印平台 platid 映射。 + * @return {Object|null} 规范化后的全量记录。 + */ + normalizeFullPlatformRow(row, printPlatformCodeMap = new Map(), printPlatformPlatidMap = new Map()) { + const normalizedRow = this.normalizePlatformRow(row, printPlatformCodeMap); + + if (!normalizedRow) { + return null; + } + + const normalizedResult = { + ...row, + ...normalizedRow, + route_platform_code: this.resolveRoutePlatformCode(row, printPlatformCodeMap), + }; + + const plainRow = this.toPlainRow(row); + const printPlatformId = this.normalizePrintPlatformId(plainRow && plainRow.print_platform_id); + if (printPlatformId && printPlatformPlatidMap instanceof Map) { + const platid = printPlatformPlatidMap.get(printPlatformId); + if (Number.isFinite(platid)) { + normalizedResult.platid = platid; + } + } + + return normalizedResult; + } + + /** + * 规范化平台设置全量记录。 + * + * @param {Object} row 数据库记录。 + * @param {Map} platformMap 系统平台映射。 + * @return {Object|null} 规范化后的全量记录。 + */ + normalizeFullPlatformSettingRow(row, platformMap) { + const normalizedRow = this.normalizePlatformSettingRow(row, platformMap); + + if (!normalizedRow) { + return null; + } + + const platformCode = String(row && row.platform_code || '').trim(); + const platformItem = platformMap instanceof Map ? platformMap.get(platformCode) : null; + + return { + ...row, + ...normalizedRow, + route_platform_code: String((platformItem && platformItem.route_platform_code) || '').trim(), + }; + } + + /** + * 合并基础平台列表和平台设置列表。 + * + * @param {Array} platformList 系统平台列表。 + * @param {Array} platformSettingList 平台设置列表。 + * @param {boolean} [full=false] 是否合并全量字段。 + * @return {Array} 合并后的平台列表。 + */ + buildMergedPlatformList(platformList, platformSettingList, full = false) { + const mergedList = []; + const seenCodeMap = new Set(); + const normalizedPlatformList = Array.isArray(platformList) ? platformList : []; + const platformMap = new Map(); + + for (const platformItem of normalizedPlatformList) { + if (!platformItem || typeof platformItem !== 'object') { + continue; + } + + const code = String(platformItem.code || platformItem.value || '').trim(); + if (!code) { + continue; + } + + if (!platformMap.has(code)) { + platformMap.set(code, platformItem); + } + } + + for (const platformItem of normalizedPlatformList) { + if (!platformItem || typeof platformItem !== 'object') { + continue; + } + + const code = String(platformItem.code || platformItem.value || '').trim(); + if (!code || seenCodeMap.has(code)) { + continue; + } + + mergedList.push(platformItem); + seenCodeMap.add(code); + } + + for (const row of Array.isArray(platformSettingList) ? platformSettingList : []) { + const mergedItem = full + ? this.normalizeFullPlatformSettingRow(row, platformMap) + : this.normalizePlatformSettingRow(row, platformMap); + if (!mergedItem) { + continue; + } + + if (seenCodeMap.has(mergedItem.code)) { + const idx = mergedList.findIndex(item => + String(item.code || item.value || '').trim() === mergedItem.code && !item.is_system_setting + ); + if (idx !== -1) { + mergedList[idx] = mergedItem; + } + continue; + } + + mergedList.push(mergedItem); + seenCodeMap.add(mergedItem.code); + } + + return mergedList; + } + + /** + * 从数据库加载系统平台列表。 + * + * @param {boolean} [full=false] 是否返回全量字段。 + * @return {Promise>} 平台列表。 + */ + async loadPlatformListFromDatabase(full = false) { + const query = { + order: [[ 'code', 'ASC' ]], + raw: true, + }; + + if (full) { + const attributes = this.getPlatformFullAttributes(); + if (attributes.length > 0) { + query.attributes = attributes; + } + } else { + query.attributes = [ 'code', 'name', 'print_platform_id' ]; + } + + const rows = await this.ctx.model.Platform.findAll(query); + + if (!Array.isArray(rows)) { + return []; + } + + const printPlatformCodeMap = await this.loadPrintPlatformCodeMap(rows); + const printPlatformPlatidMap = full ? await this.loadPrintPlatformPlatidMap(rows) : new Map(); + + return rows + .map(row => (full + ? this.normalizeFullPlatformRow(row, printPlatformCodeMap, printPlatformPlatidMap) + : this.normalizePlatformRow(row, printPlatformCodeMap))) + .filter(Boolean); + } + + /** + * 获取系统平台列表。 + * + * 该接口只返回系统基础平台数据,不合并仓库自定义映射。 + * + * @return {Promise} 系统平台列表。 + */ + async getSystemPlatformList() { + return await this.loadPlatformListFromDatabase(); + } + + /** + * 获取平台列表。 + * + * 默认先读取系统平台,再按当前仓库合并平台设置;同一编码只保留一条记录。 + * systemOnly 为 true 时仅返回系统平台列表。 + * + * @param {boolean} [systemOnly=false] 是否仅返回系统基础平台列表。 + * @param {boolean} [full=false] 是否返回全量字段。 + * @param {number|null} [warehouseId=null] 仓库ID,传入时使用外部值,否则从 ctx.user.store_id 内部获取。 + * @return {Promise} 平台列表。 + */ + async getPlatformList(systemOnly = false, full = false, warehouseId = null) { + const resolvedWarehouseId = warehouseId !== null && warehouseId !== undefined + ? Number(warehouseId) + : this.getCurrentWarehouseId(); + const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly); + const isFull = [ true, 1, '1', 'true' ].includes(full); + const cacheKey = this.getPlatformListCacheKey(resolvedWarehouseId, isSystemOnly, isFull); + + try { + const cachedList = await this.app.getCacheAsync(cacheKey); + if (cachedList !== null && cachedList !== undefined) { + if (isFull && this.isFullPlatformCacheSchemaStale(cachedList)) { + this.ctx.logger.warn(`[PlatformService.getPlatformList] full缓存缺少有效platid,触发重建: ${cacheKey}`); + + try { + await this.app.delCacheAsync(cacheKey); + } catch (error) { + this.ctx.logger.warn(`[PlatformService.getPlatformList] 删除过期缓存失败,降级为setCacheAsync置空: ${cacheKey}, error: ${error.message}`); + await this.app.setCacheAsync(cacheKey, null, 0); + } + } else { + return Array.isArray(cachedList) ? cachedList : []; + } + } + + if (isSystemOnly) { + const platformList = await this.loadPlatformListFromDatabase(isFull); + await this.app.setCacheAsync(cacheKey, platformList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS); + return platformList; + } + + const [ platformList, platformSettingList ] = await Promise.all([ + this.loadPlatformListFromDatabase(isFull), + this.loadPlatformSettingListFromDatabase(resolvedWarehouseId, isFull), + ]); + + const mergedList = this.buildMergedPlatformList(platformList, platformSettingList, isFull); + await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS); + + return mergedList; + } catch (error) { + this.ctx.logger.error('[PlatformService.getPlatformList] 获取平台列表失败', { + error: error.message, + stack: error.stack, + }); + throw error; + } + } + /** * 检查平台是否存在 * 逻辑: @@ -43,16 +1054,17 @@ class PlatformService extends Service { { model: this.app.model.Platform, as: 'platform', - attributes: [ 'code', 'name', 'default_express_interface' ], + attributes: [ 'code', 'name', 'print_platform_id' ], }, ], }); if (platformSetting && platformSetting.platform) { + const printPlatformCodeMap = await this.loadPrintPlatformCodeMap([ platformSetting.platform ]); // 从设置表中找到,并且有关联的平台信息 platformInfo = { code: platformSetting.platform.code, name: platformSetting.platform.name, - default_express_interface: platformSetting.platform.default_express_interface, + default_express_interface: this.resolveDefaultExpressInterface(platformSetting.platform, printPlatformCodeMap), source: 'setting', // 标记来源 setting_id: platformSetting.id, warehouse_id: warehouseId, @@ -63,14 +1075,15 @@ class PlatformService extends Service { where: { code: platformCode, }, - attributes: [ 'code', 'name', 'default_express_interface' ], + attributes: [ 'code', 'name', 'print_platform_id' ], }); if (basePlatform) { + const printPlatformCodeMap = await this.loadPrintPlatformCodeMap([ basePlatform ]); platformInfo = { code: basePlatform.code, name: basePlatform.name, - default_express_interface: basePlatform.default_express_interface, + default_express_interface: this.resolveDefaultExpressInterface(basePlatform, printPlatformCodeMap), source: 'base', // 标记来源 warehouse_id: warehouseId, }; @@ -135,7 +1148,6 @@ class PlatformService extends Service { * @return {Promise} 平台设置详情 */ async getPlatformSettingDetail(platformCode, warehouseId) { - const { ctx } = this; const cacheKey = `platform_setting_detail:${platformCode}:${warehouseId}`; try { @@ -154,7 +1166,7 @@ class PlatformService extends Service { { model: this.app.model.Platform, as: 'platform', - attributes: [ 'code', 'name', 'default_express_interface' ], + attributes: [ 'code', 'name', 'print_platform_id' ], }, ], }); diff --git a/app/service/systems/polo_api.js b/app/service/systems/polo_api.js new file mode 100644 index 0000000..173632e --- /dev/null +++ b/app/service/systems/polo_api.js @@ -0,0 +1,192 @@ +'use strict'; + +const Service = require('egg').Service; +const PoloApiClient = require('../../lib/polo_api_client'); + +class PoloApiService extends Service { + /** + * @param {object} ctx - Egg 上下文对象。 + */ + constructor(ctx) { + super(ctx); + this.client = new PoloApiClient(ctx); + } + + /** + * 发起 Polo API POST 请求。 + * + * @param {string} method 接口方法名。 + * @param {object|string} [bizcontent={}] 业务参数。 + * @param {object} [config={}] 平台配置。 + * @param {string} [token] 可选 token。 + * @return {Promise} 接口响应数据。 + */ + async request(method, bizcontent = {}, config = {}, token) { + console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent)); + return this.client.request({ + method, + bizcontent, + config, + token, + }); + } + + /** + * 发起 Polo API GET 请求。 + * + * @param {string} method 接口方法名。 + * @param {object|string} [bizcontent={}] 业务参数。 + * @param {object} [config={}] 平台配置。 + * @param {string} [token] 可选 token。 + * @return {Promise} 接口响应数据。 + */ + async get(method, bizcontent = {}, config = {}, token) { + console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent)); + return this.client.get({ + method, + bizcontent, + config, + token, + }); + } + /** + * 快手取号。 + * + * @param {object} [options={}] - 快手取号入参。 + * @param {string} [options.express_id=''] - 快手平台对应的承运商编码。 + * @param {object} [options.wmsOrder={}] - WMS 订单信息。 + * @param {object} [options.expressConfig={}] - 发件方与店铺配置。 + * @return {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 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]; + } + } else { + cnname = 'sp'; + } + + 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', + }; + + 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`; + } + + return this.client.request({ + method, + platid, + bizcontent: { + orders: [ order ], + shoptype, + }, + }); + } +} + +module.exports = PoloApiService; diff --git a/app/service/systems/print/index.js b/app/service/systems/print/index.js index 94d43be..f031d38 100644 --- a/app/service/systems/print/index.js +++ b/app/service/systems/print/index.js @@ -5,41 +5,37 @@ const Service = require('egg').Service; class PrintService extends Service { // 发送信息到打印电脑 async sendToComputer({ warehouse, computerId, data }) { - //发送指令更新打印机状态 + // 发送指令更新打印机状态 const printServiceUrl = this.ctx.app.config.printService.url; - //先获取redis中打印机列表 - let printerListResult = await this.app.redis.get("printer").get(`printer:${computerId}:printerList`); + // 先获取redis中打印机列表 + let printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); let lastUpdateTime = 0; - if(printerListResult){ - //记录上次更新时间,避免频繁发送更新指令 - let printerData = JSON.parse(printerListResult); - console.log("printerData", printerData); + if (printerListResult) { + // 记录上次更新时间,避免频繁发送更新指令 + const printerData = JSON.parse(printerListResult); lastUpdateTime = printerData.updatedAt || 0; } - //不管是否有打印机列表,都先发送指令让打印电脑更新打印机状态和列表 - const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { + // 不管是否有打印机列表,都先发送指令让打印电脑更新打印机状态和列表 + await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { method: 'POST', contentType: 'json', - data: { warehouse, computerId, method: "printer.getWindowsPrinters", data: {} }, + data: { warehouse, computerId, method: 'printer.getWindowsPrinters', data: {} }, dataType: 'json', }); - console.log("lastUpdateTime",lastUpdateTime) - //等待异步获取打印机列表结果,最长等待5秒 + // 等待异步获取打印机列表结果,最长等待5秒 const startTime = Date.now(); while (Date.now() - startTime < 5000) { await new Promise(resolve => setTimeout(resolve, 10)); // 每10ms检查一次 - printerListResult = await this.app.redis.get("printer").get(`printer:${computerId}:printerList`); - let printerData = JSON.parse(printerListResult); - if(printerData.updatedAt && printerData.updatedAt > lastUpdateTime){ - console.log("打印机列表已更新", printerData.updatedAt); - //如果更新了打印机列表,跳出循环 + printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); + const printerData = JSON.parse(printerListResult); + if (printerData.updatedAt && printerData.updatedAt > lastUpdateTime) { + // 如果更新了打印机列表,跳出循环 break; } } - //从redis获取打印机 - printerListResult = await this.app.redis.get("printer").get(`printer:${computerId}:printerList`); + // 从redis获取打印机 + printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); const printerList = JSON.parse(printerListResult); - console.log("sendToComputer printerList", printerList); if (!printerList || !printerList.data || printerList.data.length === 0) { return { success: false, error: '未找到对应的打印机', detail: `computerId: ${computerId} 的打印机列表不存在` }; } @@ -48,17 +44,16 @@ class PrintService extends Service { if (!printerInfo) { return { success: false, error: `打印台没有打印机 ${printer}`, detail: `computerId: ${computerId} 的打印机列表中不存在 printer: ${printer}` }; } - if (printerInfo.workOffline == "TRUE") { + if (printerInfo.workOffline === 'TRUE') { return { success: false, error: `打印机 ${printer} 处于脱机状态`, detail: `computerId: ${computerId} 的打印机 ${printer} 当前处于离线状态` }; } try { const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { method: 'POST', contentType: 'json', - data: { warehouse, computerId, method: "printer.print", data }, + data: { warehouse, computerId, method: 'printer.print', data }, dataType: 'json', }); - console.log(res); return res.data; } catch (err) { @@ -66,8 +61,8 @@ class PrintService extends Service { } } async test() { - const grabnum = "B1157389"; - const datas = await this.app.wsdl("print", [5400, grabnum, "caige"]) + const grabnum = 'B1157389'; + const datas = await this.app.wsdl('print', [ 5400, grabnum, 'caige' ]); this.sendToComputer({ warehouse: '1000028', computerId: '1', data: datas }); } } diff --git a/app/service/systems/print/printData.js b/app/service/systems/print/printData.js new file mode 100644 index 0000000..44d50bb --- /dev/null +++ b/app/service/systems/print/printData.js @@ -0,0 +1,20 @@ +'use strict'; + +const Service = require('egg').Service; + +class PrintDataService extends Service { + + async getPrintData({ printType, orderId }) { + const { ctx } = this; + switch (printType) { + case 'delivery_order': { + const deliveryOrderData = await ctx.service.systems.deliveryOrder.getPrintData({ orderId }); + return deliveryOrderData; + } + default: + return { success: false, error: `不支持的打印类型 ${printType}` }; + } + } +} + +module.exports = PrintDataService; diff --git a/app/service/systems/printComputer.js b/app/service/systems/printComputer.js new file mode 100644 index 0000000..8ae474b --- /dev/null +++ b/app/service/systems/printComputer.js @@ -0,0 +1,311 @@ +'use strict'; + +const Service = require('egg').Service; + +class PrintComputerService extends Service { + /** + * 通知打印服务刷新电脑信息并推送给客户端。 + * @param {number} warehouseId 仓库ID + * @param {number} computerId 电脑ID + * @return {Promise} + */ + async notifyRefreshInfo(warehouseId, computerId) { + const printServiceUrl = this.ctx.app.config.printService.url; + try { + await this.ctx.curl(`${printServiceUrl}/auth/refreshInfo`, { + method: 'POST', + contentType: 'json', + data: { warehouse: warehouseId, computerId }, + dataType: 'json', + }); + } catch (err) { + this.ctx.logger.warn(`通知打印服务刷新电脑 ${computerId} 信息失败: ${err.message}`); + } + } + + /** + * 打印电脑列表(仓库隔离,分页+筛选)。 + * @param {Object} params 查询参数 + * @param {Object} [params.pagination] 分页 { page, pageSize } + * @param {Object} [params.where] 筛选 { is_recording, is_online } + * @return {Promise} { list, pagination } + */ + async list(params = {}) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { pagination = {}, where = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = { + warehouse_id: warehouseId, + deleted_at: null, + }; + + // DB 层筛选:is_recording + if (where.is_recording !== undefined && where.is_recording !== null && where.is_recording !== '') { + queryWhere.is_recording = parseInt(where.is_recording) === 1; + } + + // is_online 筛选参数 + const filterOnline = where.is_online !== undefined && where.is_online !== null && where.is_online !== ''; + const onlineValue = filterOnline ? parseInt(where.is_online) : null; + + const redisPrinter = ctx.app.redis.get('printer'); + + if (filterOnline) { + // 有在线状态筛选:先查全量 DB,Redis 标注后内存过滤再分页 + const allRows = await ctx.model.PrintComputer.findAll({ + where: queryWhere, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + // Redis 标注在线状态 + const enriched = await Promise.all(allRows.map(async row => { + const onlineKey = `warehouse:${warehouseId}:printer:${row.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + row.is_online = onlineInfo ? 1 : 0; + return row; + })); + + // 内存过滤 + const filtered = enriched.filter(row => row.is_online === onlineValue); + const total = filtered.length; + const list = filtered.slice((page - 1) * pageSize, page * pageSize); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < total, + }, + }; + } + + // 无在线状态筛选:DB 分页查询 + const { count, rows } = await ctx.model.PrintComputer.findAndCountAll({ + where: queryWhere, + order: [[ 'id', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + // 从 Redis 读取在线状态并附加到每条记录 + const list = await Promise.all(rows.map(async row => { + const plain = row.get ? row.get({ plain: true }) : row; + const onlineKey = `warehouse:${warehouseId}:printer:${plain.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + plain.is_online = onlineInfo ? 1 : 0; + return plain; + })); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 更新打印电脑。 + * @param {number} id 电脑ID + * @param {Object} data 要更新的字段 { name } + * @return {Promise} 更新后的记录 + */ + async update(id, data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + const fields = {}; + if (data.name !== undefined) { + const name = String(data.name).trim(); + if (!name) throw new Error('电脑名称不能为空'); + fields.name = name; + } + + if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段'); + + await record.update(fields); + + // 通知打印服务推送最新信息给客户端 + await this.notifyRefreshInfo(warehouseId, id); + + return record; + } + + /** + * 设置录制电脑。 + * 会将同仓库下其他已设为录制的电脑取消,再设置当前电脑为录制。 + * @param {number} id 电脑ID + * @param {Object} data { recording_size_value, recording_size_unit, recording_directory } + * @return {Promise} 更新后的记录 + */ + async setRecording(id, data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + // 参数校验 + if (data.recording_size_value === undefined || data.recording_size_value === null) { + throw new Error('录制大小不能为空'); + } + const sizeValue = parseInt(data.recording_size_value); + if (!Number.isInteger(sizeValue) || sizeValue <= 0) { + throw new Error('录制大小必须为正整数'); + } + + const VALID_UNITS = [ 'KB', 'MB', 'GB', 'TB' ]; + const unit = String(data.recording_size_unit || '').trim().toUpperCase(); + if (!VALID_UNITS.includes(unit)) { + throw new Error(`存储单位不合法,支持:${VALID_UNITS.join('/')}`); + } + + const directory = String(data.recording_directory || '').trim(); + if (!directory) { + throw new Error('录制目录不能为空'); + } + + // 校验目标电脑存在 + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + // 先将同仓库下其他已设为录制的电脑取消 + const [ affectedCount ] = await ctx.model.PrintComputer.update( + { + is_recording: false, + recording_size_value: null, + recording_size_unit: null, + recording_directory: null, + }, + { + where: { + warehouse_id: warehouseId, + is_recording: true, + deleted_at: null, + }, + } + ); + + // 设置当前电脑为录制 + await record.update({ + is_recording: true, + recording_size_value: sizeValue, + recording_size_unit: unit, + recording_directory: directory, + }); + + // 通知打印服务推送最新信息:当前电脑 + 被取消的其他电脑 + await this.notifyRefreshInfo(warehouseId, id); + // 查询被取消的其他电脑ID并逐一通知 + if (affectedCount > 0) { + const cancelledComputers = await ctx.model.PrintComputer.findAll({ + where: { + warehouse_id: warehouseId, + is_recording: false, + deleted_at: null, + id: { [ctx.app.Sequelize.Op.ne]: id }, + }, + attributes: [ 'id' ], + raw: true, + order: [[ 'id', 'DESC' ]], + limit: affectedCount, + }); + for (const comp of cancelledComputers) { + await this.notifyRefreshInfo(warehouseId, comp.id); + } + } + + return record; + } + + /** + * 取消录制电脑。 + * @param {number} id 电脑ID + * @return {Promise} 更新后的记录 + */ + async cancelRecording(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + await record.update({ + is_recording: false, + recording_size_value: null, + recording_size_unit: null, + recording_directory: null, + }); + + // 通知打印服务推送最新信息给客户端 + await this.notifyRefreshInfo(warehouseId, id); + + return record; + } + + /** + * 软删除打印电脑。 + * 若存在未删除的关联打印台,则拒绝删除。 + * @param {number} id 电脑ID + * @return {Promise} + */ + async delete(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + // 检查是否有关联的未删除打印台 + const stationCount = await ctx.model.PrintStations.count({ + where: { + computer_id: id, + warehouse_id: warehouseId, + deleted_at: null, + }, + }); + + if (stationCount > 0) { + throw new Error(`该电脑下存在 ${stationCount} 个未删除的打印台,请先删除打印台后再删除电脑`); + } + + await record.update({ deleted_at: new Date() }); + + // 通知打印服务注销电脑连接 + const printServiceUrl = ctx.app.config.printService.url; + try { + await ctx.curl(`${printServiceUrl}/auth/logout`, { + method: 'POST', + contentType: 'json', + data: { warehouse: warehouseId, computerId: id }, + dataType: 'json', + }); + } catch (err) { + ctx.logger.warn(`通知打印服务注销电脑 ${id} 失败: ${err.message}`); + } + } +} + +module.exports = PrintComputerService; diff --git a/app/service/systems/qimen_query.js b/app/service/systems/qimen_query.js index 0c378be..3576900 100644 --- a/app/service/systems/qimen_query.js +++ b/app/service/systems/qimen_query.js @@ -1,156 +1,28 @@ +'use strict'; + const Service = require('egg').Service; -const https = require('https'); -const http = require('http'); +const QimenClient = require('../../lib/qimen_client'); + class QimenQueryService extends Service { + get qimenClient() { + if (!this.app.qimenClient) { + this.app.qimenClient = new QimenClient(this.app); + } + + return this.app.qimenClient; + } async send(method, customerId, data) { - - try { - const wmsAppKey = this.app.config.qimen.appKey; - const baseQueryParams = this.getQueryParams(method, wmsAppKey, '2.0', customerId); - const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service'; - const xmlData = await this.ctx.service.systems.sign.toXml(data); - const queryData = this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine'); - const sign = await this.ctx.service.systems.sign.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5'); - const queryParams = this.addSign(baseQueryParams, sign); - const url = this.generateUrlWithParams(baseUrl, queryParams); - const logData = { - from_key: this.app.config.qimen.appKey, - to_key: wmsAppKey, - method, - sign, - costomer_id: customerId, - v: '2.0', - url, - created_at: new Date(), - body: '', - result: '', - use_time: 0, - }; - const result = await this.sendRequest(url, queryData, logData); - const xmlArray = await this.ctx.service.qimen.parseXmlToArray(result.res); - return { queryId: result.queryId, xmlArray }; - } catch (error) { - throw error; - } - } - - replaceXmlTagsWithString(xmlString, oldTag, newTag) { - // 匹配开始标签(包括属性) - const startTagRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?>`, 'gi'); - - // 匹配结束标签 - const endTagRegex = new RegExp(`<\\s*/\\s*${oldTag}\\s*>`, 'gi'); - - // 匹配自闭合标签 - const selfClosingRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?\\s*/>`, 'gi'); - - return xmlString - .replace(startTagRegex, (match, attributes = '') => { - return `<${newTag}${attributes}>`; - }) - .replace(endTagRegex, ``) - .replace(selfClosingRegex, (match, attributes = '') => { - return `<${newTag}${attributes}/>`; - }); - } - addSign(baseQueryParams, sign) { - return Object.assign({}, baseQueryParams, { sign }); - } - getQueryParams(method, app_key, v, customerId) { - const param = { - method, - format: 'xml', - app_key, - v, - sign_method: 'md5', - customerId, - timestamp: new Date().format(), - }; - return param; - } - generateUrlWithParams(baseUrl, params) { - if (!params || Object.keys(params).length === 0) { - return baseUrl; - } - - const queryString = Object.keys(params) - .map(key => { - const value = params[key]; - // 对参数进行URL编码 - return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; - }) - .join('&'); - - // 检查基础URL是否已包含查询参数 - const separator = baseUrl.includes('?') ? '&' : '?'; - return `${baseUrl}${separator}${queryString}`; - } - async sendRequest(url, requestData) { - const startTime = Date.now(); - const { service } = this; - const logData = {}; - logData.body = requestData; - let httpquery = null; - if (url.indexOf('https://') > -1) { - httpquery = https; - } else { - httpquery = http; - } - - let requestXml; - try { - // 判断 requestData 是否为字符串,如果是字符串则直接使用,否则进行转换 - if (typeof requestData === 'string') { - console.log('requestData 是字符串,直接使用'); - requestXml = requestData; - - // 可选:验证字符串是否是有效的XML - if (requestXml.trim() === '') { - throw new Error('请求数据为空字符串'); - } - } else { - console.log('requestData 不是字符串,调用 formatResponse 进行转换'); - requestXml = await this.ctx.service.qimen.formatResponse(requestData); - } - - // 最终检查XML是否为空 - if (!requestXml || requestXml.trim() === '') { - throw new Error('XML内容为空'); - } - } catch (error) { - throw error; - } - const header = { - 'Content-Type': 'application/xml', - 'Content-Length': Buffer.byteLength(requestXml, 'utf8'), - 'User-Agent': 'EggJS Client', - }; - const options = { - 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); - }); - }); - - req.on('error', error => { - reject(error); - }); - - req.write(requestXml); - req.end(); + return this.qimenClient.send(method, customerId, data, { + ctx: this.ctx, + }); + } + + async sendRequest(url, requestData, logData = {}) { + return this.qimenClient.sendRequest(url, requestData, logData, { + ctx: this.ctx, }); - logData.result = res; - const queryId = await service.qimen.saveQimenLog(logData, startTime); - return { queryId, res }; } } + module.exports = QimenQueryService; diff --git a/app/service/systems/receiving_entry_match.js b/app/service/systems/receiving_entry_match.js new file mode 100644 index 0000000..6e44dcf --- /dev/null +++ b/app/service/systems/receiving_entry_match.js @@ -0,0 +1,2384 @@ +'use strict'; + +const Service = require('egg').Service; + +/** @type {number} 收货单缓存过期时间(秒) */ +const RECEIVING_CACHE_TTL = 300; + +/** @type {number} 收货单查询天数范围 */ +const RECEIVING_LOOKBACK_DAYS = 3; + +/** @type {string} 收货单列表缓存键前缀 */ +const RECEIVING_CACHE_KEY_PREFIX = 'cache:receiving_orders:warehouse:'; + +/** + * 入库单创建后异步匹配收货单并写入绑定关系服务。 + * + * 职责: + * 1. 缓存仓库下近 3 天的收货单列表(Redis,TTL 300s) + * 2. 根据入库单 remark 匹配收货单号 + * 3. 对比入库单明细与收货单明细(SKU + 数量) + * 4. 匹配成功后写入 wms_entry_order_receiving 绑定关系,CREATED 状态转 PENDING + * 5. 覆盖场景标记收货单为"部分入库" + * 6. 新建绑定时按来源回传外部系统(奇门 confirm / OpenAPI entryorder.match) + */ +class ReceivingEntryMatchService extends Service { + + /** + * 入库单创建后的异步匹配入口:根据备注匹配收货单,写入绑定关系并在必要时转换状态。 + * 匹配到收货单后写入 wms_entry_order_receiving 绑定关系; + * 如果入库单当前状态为 CREATED,同步更新为 PENDING; + * 仅在本次确实新建绑定时按来源回传外部系统(奇门 / OpenAPI), + * 回传失败仅记录日志,不影响绑定与状态更新结果。 + * 不阻塞主流程,所有错误仅记录日志。 + * + * @param {number} entryOrderId 入库单 ID + * @return {Promise} + */ + async matchAfterEntryCompleted(entryOrderId) { + const { ctx } = this; + + try { + // 1. 加载入库单及其明细 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { id: entryOrderId, is_enabled: 1, deleted_at: null }, + include: [{ + model: ctx.model.EntryItems, + as: 'items', + required: false, + attributes: [ 'id', 'item_code', 'stock_id', 'count', 'received_quantity', 'inventory_type' ], + }], + }); + + if (!entryOrder) { + ctx.logger.warn(`[ReceivingEntryMatch] 入库单不存在,跳过匹配 entryOrderId=${entryOrderId}`); + return; + } + + const remark = (entryOrder.remark || '').trim(); + if (!remark) { + ctx.logger.info(`[ReceivingEntryMatch] 入库单无备注,跳过匹配 entryOrderId=${entryOrderId}`); + return; + } + + const warehouseId = entryOrder.warehouse_id; + + // 2. 获取近 3 天的收货单列表(带缓存) + const receivingOrders = await this._getRecentReceivingOrders(warehouseId); + + if (!receivingOrders || receivingOrders.length === 0) { + ctx.logger.info(`[ReceivingEntryMatch] 仓库无近期收货单,跳过匹配 warehouseId=${warehouseId}`); + return; + } + + // 3. 从 remark 中提取可能匹配的收货单号 + const matchedReceiving = await this._findReceivingByRemark(remark, receivingOrders, warehouseId); + + if (!matchedReceiving) { + ctx.logger.info(`[ReceivingEntryMatch] remark 中未匹配到收货单号 entryOrderId=${entryOrderId} remark="${remark}"`); + return; + } + + ctx.logger.info( + `[ReceivingEntryMatch] 匹配到收货单 entryOrderId=${entryOrderId} ` + + `receivingId=${matchedReceiving.id} receivingNumber=${matchedReceiving.receiving_number}` + ); + + // 4. 对比明细 + const entryItems = (entryOrder.items || []).map(item => ({ + stockId: item.stock_id, + itemCode: item.item_code, + count: item.count || 0, + receivedQuantity: item.received_quantity || 0, + inventoryType: item.inventory_type || 'ZP', + })); + + const comparisonResult = this._compareDetails(entryItems, matchedReceiving.details || []); + + // 5. 根据对比结果写入绑定关系 + if (comparisonResult.type === 'full_match' || comparisonResult.type === 'receiving_covers_entry') { + // 匹配成功 → 写入 wms_entry_order_receiving 绑定关系,返回本次是否新建绑定 + const bindResult = await this._bindEntryOrderReceiving(entryOrderId, matchedReceiving.id); + + // 若入库单当前状态是 CREATED,更新为 PENDING + if (entryOrder.order_status === 'CREATED') { + await ctx.model.EntryOrder.update( + { order_status: 'PENDING', updated_at: new Date() }, + { where: { id: entryOrderId, order_status: 'CREATED' } } + ); + ctx.logger.info( + `[ReceivingEntryMatch] 入库单状态 CREATED → PENDING entryOrderId=${entryOrderId} ` + + `receivingId=${matchedReceiving.id}` + ); + } + + // receipting_covers_entry 场景额外标记收货单为部分入库 + if (comparisonResult.type === 'receiving_covers_entry') { + await this._markReceivingPartialStorage(matchedReceiving.id, comparisonResult, warehouseId); + } + + // 6. 按来源回传外部系统(奇门 / OpenAPI)。 + // 仅当本次确实新建了绑定关系才回传:重复触发时绑定已存在(created=false), + // 不会重复通知外部;回传失败仅记录 warn 日志,不影响绑定与状态更新结果。 + if (bindResult && bindResult.created) { + try { + const callbackResult = await this._sendCallback(entryOrder, matchedReceiving, 'auto_match'); + if (!callbackResult || !callbackResult.success) { + ctx.logger.warn( + `[ReceivingEntryMatch] 回传失败(不影响绑定结果) entryOrderId=${entryOrderId} ` + + `receivingId=${matchedReceiving.id} ` + + `sourceType=${callbackResult ? callbackResult.sourceType : 'N/A'}` + ); + } + } catch (callbackError) { + ctx.logger.warn( + `[ReceivingEntryMatch] 回传异常(不影响绑定结果) entryOrderId=${entryOrderId} ` + + `receivingId=${matchedReceiving.id}: ${callbackError.message}` + ); + } + } + } else { + // 其他情况(entry 有 receiving 没有的明细,或完全不匹配)→ 不做处理 + ctx.logger.info( + `[ReceivingEntryMatch] 明细对比结果为 ${comparisonResult.type},不触发绑定 ` + + `entryOrderId=${entryOrderId} receivingId=${matchedReceiving.id}` + ); + } + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 异步匹配异常 entryOrderId=${entryOrderId}: ${error.message}`, + error.stack + ); + } + } + + /** + * 写入入库单与收货单的主表级绑定关系。 + * 幂等策略:先查(含软删除)——已存在未删除 → 跳过;已软删除 → 恢复;不存在 → 新建(唯一索引兜底并发)。 + * 仅当本次确实新建绑定行时返回 created=true,调用方据此判断是否需要回传外部系统。 + * + * @param {number} entryOrderId 入库单 ID + * @param {number} receivingId 收货单 ID + * @return {Promise<{created: boolean}>} 本次是否新建了绑定行;已存在/恢复/并发冲突/写入失败时均为 false + */ + async _bindEntryOrderReceiving(entryOrderId, receivingId) { + const { ctx } = this; + + try { + // 先检查是否已存在未删除的绑定记录 + const existing = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: entryOrderId, receiving_id: receivingId }, + paranoid: false, + }); + + if (existing) { + if (existing.deletedAt || existing.deleted_at) { + // 已软删除的记录,恢复它(台账重置为 {},从 0 重新分配) + existing.allocated_quantity = {}; + await existing.restore(); + ctx.logger.info( + `[ReceivingEntryMatch] 恢复已删除的绑定关系 entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + } else { + ctx.logger.info( + `[ReceivingEntryMatch] 绑定关系已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + } + return { created: false }; + } + + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receivingId, + // 新链路绑定行台账初始化为空对象(区别于旧数据 NULL),恢复/分配时从 0 起步 + allocated_quantity: {}, + }); + + ctx.logger.info( + `[ReceivingEntryMatch] 写入绑定关系成功 entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + return { created: true }; + } catch (error) { + // 唯一索引冲突时忽略(并发场景) + if (error.name === 'SequelizeUniqueConstraintError') { + ctx.logger.warn( + `[ReceivingEntryMatch] 绑定关系已存在(并发写入) entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + return { created: false }; + } + ctx.logger.error( + `[ReceivingEntryMatch] 写入绑定关系失败 entryOrderId=${entryOrderId} receivingId=${receivingId}: ${error.message}`, + error.stack + ); + return { created: false }; + } + } + + /** + * 绑定入库单与收货单(主表绑定)。 + * + * 流程: + * 1. 校验入库单状态,仅 CREATED / COMPLETED 允许绑定,其他状态抛错 + * 2. 校验每个收货单:存在、同仓库、同货主、已审核、未取消 + * 3. CREATED:保持原有逻辑,仅逐条写入 EntryOrderReceiving 主表绑定 + * 4. COMPLETED:事务内完成主表绑定 + 收货明细入库进度同步 + 收货单入库状态重算, + * 任一异常整体回滚 + * + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 收货单 ID 列表 + * @param {number} [data.creator_id] 操作人 ID(可选) + * @return {Promise} 绑定结果,含 bound、skipped、summary + */ + async bindEntryOrderReceiving(data = {}) { + const { ctx } = this; + const { entry_order_id: entryOrderId, receiving_ids: receivingIds, creator_id: creatorId } = data || {}; + + // 参数校验 + if (!entryOrderId) { + throw new Error('entry_order_id 不能为空'); + } + if (!Array.isArray(receivingIds) || receivingIds.length === 0) { + throw new Error('receiving_ids 不能为空且必须为数组'); + } + + // ========== 第1步:查询入库单,校验状态 ========== + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); + if (!entryOrder) { + throw new Error('入库单不存在'); + } + // 仅允许 CREATED / COMPLETED 状态绑定;COMPLETED 绑定后同步收货单入库进度 + const ALLOWED_BIND_STATUSES = [ 'CREATED', 'COMPLETED' ]; + if (!ALLOWED_BIND_STATUSES.includes(entryOrder.order_status)) { + throw new Error( + `入库单状态不允许绑定,当前状态: ${entryOrder.order_status},仅 ${ALLOWED_BIND_STATUSES.join('、')} 状态可操作` + ); + } + + const warehouseId = entryOrder.warehouse_id; + + // ========== 第2步:校验每个收货单的有效性 ========== + const validatedReceivings = []; + const failedValidations = []; + + for (const receivingId of receivingIds) { + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, is_deleted: false }, + attributes: [ 'id', 'receiving_number', 'warehouse_id', 'store_id', 'status', 'is_review' ], + }); + + if (!receiving) { + failedValidations.push({ + receiving_id: receivingId, + error_code: 'RECEIVING_NOT_FOUND', + message: '收货单不存在或已删除', + }); + continue; + } + + if (receiving.warehouse_id !== warehouseId) { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'WAREHOUSE_MISMATCH', + message: `收货单 ${receiving.receiving_number} 与入库单不属于同一仓库`, + }); + continue; + } + + if (receiving.store_id !== entryOrder.store_id) { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'OWNER_MISMATCH', + message: `收货单 ${receiving.receiving_number} 与入库单货主不一致`, + }); + continue; + } + + if (receiving.status === 'cancelled') { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'RECEIVING_CANCELLED', + message: `收货单 ${receiving.receiving_number} 已取消`, + }); + continue; + } + + if (!receiving.is_review) { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'RECEIVING_NOT_REVIEWED', + message: `收货单 ${receiving.receiving_number} 未审核`, + }); + continue; + } + + validatedReceivings.push(receiving); + } + + // 有校验失败的收货单 → 直接返回失败 + if (failedValidations.length > 0) { + ctx.logger.info( + `[ReceivingEntryMatch] bindEntryOrderReceiving 收货单校验失败 entryOrderId=${entryOrderId} failed=${failedValidations.length}` + ); + return { + bound: [], + skipped: [], + summary: { bound_count: 0, skipped_count: failedValidations.length }, + }; + } + + // ========== 第3步:写入主表绑定关系 ========== + const boundResults = []; + const skippedResults = []; + + if (entryOrder.order_status === 'COMPLETED') { + // COMPLETED:事务内完成 主表绑定 + 明细入库进度同步 + 主表入库状态重算,失败整体回滚 + try { + const txResult = await this._bindReceivingsWithStorageSync({ + entryOrderId, + entryOrder, + validatedReceivings, + }); + boundResults.push(...txResult.bound); + skippedResults.push(...txResult.skipped); + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] COMPLETED 绑定入库进度同步失败,事务已回滚 entryOrderId=${entryOrderId}: ${error.message}`, + error.stack + ); + throw new Error(`入库单绑定收货单失败,已回滚: ${error.message}`); + } + } else { + // CREATED:逐条写入主表绑定关系,幂等三态: + // 已存在未删除 → 跳过;已软删除(解绑产生)→ 恢复;不存在 → 新建。 + // 注意不能用 findOrCreate:其查询默认排除软删除行,解绑后再绑定同一对 + // (entry_order_id, receiving_id) 会撞唯一索引 uk_entry_order_receiving, + // 抛 SequelizeUniqueConstraintError(message 为 "Validation error")。 + for (const receiving of validatedReceivings) { + try { + const existing = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: entryOrderId, receiving_id: receiving.id }, + paranoid: false, + }); + + let created = false; + let restored = false; + + if (existing) { + if (existing.deletedAt || existing.deleted_at) { + // 解绑产生的软删除行:台账在解绑时已重置为 {},恢复后从 0 重新分配 + existing.allocated_quantity = {}; + await existing.restore(); + restored = true; + ctx.logger.info( + `[ReceivingEntryMatch] 恢复已解绑的绑定关系 entryOrderId=${entryOrderId} receivingId=${receiving.id}` + ); + } else { + ctx.logger.info( + `[ReceivingEntryMatch] 主表绑定已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receiving.id}` + ); + } + } else { + try { + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receiving.id, + // 新链路绑定行台账初始化为空对象(区别于旧数据 NULL) + allocated_quantity: {}, + }); + created = true; + ctx.logger.info( + `[ReceivingEntryMatch] 主表绑定成功 entryOrderId=${entryOrderId} receivingId=${receiving.id}` + ); + } catch (createError) { + // 并发场景:唯一索引冲突视为绑定已建立(与 findOrCreate 幂等语义一致) + if (createError.name === 'SequelizeUniqueConstraintError') { + ctx.logger.warn( + `[ReceivingEntryMatch] 主表绑定已存在(并发写入) entryOrderId=${entryOrderId} ` + + `receivingId=${receiving.id}` + ); + } else { + throw createError; + } + } + } + + boundResults.push({ + receiving_id: receiving.id, + receiving_number: receiving.receiving_number, + created, + restored, + }); + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 主表绑定写入失败 entryOrderId=${entryOrderId} receivingId=${receiving.id}: ${error.message}`, + error.stack + ); + skippedResults.push({ + receiving_id: receiving.id, + receiving_number: receiving.receiving_number, + error_code: 'BINDING_WRITE_FAILED', + message: `写入绑定失败: ${error.message}`, + }); + } + } + } + + ctx.logger.info( + `[ReceivingEntryMatch] bindEntryOrderReceiving 主表绑定完成 entryOrderId=${entryOrderId} bound=${boundResults.length} skipped=${skippedResults.length} creatorId=${creatorId || 'N/A'}` + ); + + return { + bound: boundResults, + skipped: skippedResults, + summary: { + bound_count: boundResults.length, + skipped_count: skippedResults.length, + }, + }; + } + + /** + * 事务内为 COMPLETED 入库单批量绑定收货单并同步入库进度。 + * 逐个收货单完成主表绑定(幂等)与明细入库数量同步; + * 任一非预期异常抛出,整个事务回滚。 + * + * 锁序约定(防死锁):事务内第一步先 FOR UPDATE 锁定入库单主行, + * 再创建绑定行、锁定绑定行与收货明细行(主行 → 绑定行 → 收货明细行)。 + * 同一入库单的并发绑定事务在主行锁上串行排队;排队事务不产生插入/间隙锁, + * 从根因上消除「主行锁 ↔ 未提交插入行间隙锁」的环等待死锁。 + * + * @param {Object} params 参数 + * @param {number} params.entryOrderId 入库单 ID + * @param {Object} params.entryOrder 入库单实例 + * @param {Array} params.validatedReceivings 已通过校验的收货单列表 + * @return {Promise<{bound: Array, skipped: Array}>} 绑定结果,skipped 项含 error_code + */ + async _bindReceivingsWithStorageSync({ entryOrderId, entryOrder, validatedReceivings } = {}) { + const { ctx } = this; + + return await ctx.model.transaction(async transaction => { + // ---------- 0. 统一锁序:先 FOR UPDATE 锁定入库单主行,串行化同一入库单的并发绑定事务 ---------- + await ctx.model.EntryOrder.findByPk(entryOrder.id, { + attributes: [ 'id' ], + lock: transaction.LOCK.UPDATE, + transaction, + }); + + const bound = []; + const skipped = []; + + for (const receiving of validatedReceivings) { + const itemResult = await this._bindOneReceivingAndSyncStorage({ + entryOrderId, + entryOrder, + receiving, + transaction, + }); + + if (itemResult.error_code) { + skipped.push(itemResult); + } else { + bound.push(itemResult); + } + } + + return { bound, skipped }; + }); + } + + /** + * 事务内绑定单个收货单并同步入库进度(COMPLETED 场景)。 + * + * 幂等设计: + * 1. 先查绑定关系(含软删除记录): + * - 已存在且未删除 → 跳过,不重复累加 stored_quantity + * - 已存在但已软删除 → 恢复绑定并同步进度(COMPLETED 状态不允许解绑, + * 软删除记录必然产生于 CREATED/PENDING 阶段,该阶段未做过进度同步) + * - 不存在 → 新建绑定(唯一索引冲突视为并发已建立,跳过同步) + * 2. 仅在本次新建立/恢复绑定时,按入库单明细同步收货单入库进度 + * + * @param {Object} params 参数 + * @param {number} params.entryOrderId 入库单 ID + * @param {Object} params.entryOrder 入库单实例 + * @param {Object} params.receiving 收货单实例 + * @param {Object} params.transaction Sequelize 事务对象 + * @return {Promise} 单条绑定结果;绑定已存在时含 error_code: 'ALREADY_BOUND' + */ + async _bindOneReceivingAndSyncStorage({ entryOrderId, entryOrder, receiving, transaction } = {}) { + const { ctx } = this; + + // ---------- 1. 主表绑定(幂等) ---------- + const existing = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: entryOrderId, receiving_id: receiving.id }, + paranoid: false, + transaction, + }); + + let restored = false; + + if (existing) { + const deletedAt = existing.deletedAt || existing.deleted_at || null; + if (deletedAt) { + // 恢复软删除行(台账在解绑时已重置为 {},此处显式兜底,从 0 重新分配) + existing.allocated_quantity = {}; + await existing.restore({ transaction }); + restored = true; + ctx.logger.info( + `[ReceivingEntryMatch] 恢复已删除的绑定关系并同步入库进度 entryOrderId=${entryOrderId} ` + + `receivingId=${receiving.id}` + ); + } else { + ctx.logger.info( + `[ReceivingEntryMatch] 绑定关系已存在,跳过入库进度同步(幂等) entryOrderId=${entryOrderId} ` + + `receivingId=${receiving.id}` + ); + return { + receiving_id: receiving.id, + receiving_number: receiving.receiving_number, + created: false, + error_code: 'ALREADY_BOUND', + message: '绑定关系已存在,跳过入库进度同步', + }; + } + } else { + try { + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receiving.id, + // 新链路绑定行台账初始化为空对象(区别于旧数据 NULL) + allocated_quantity: {}, + }, { transaction }); + ctx.logger.info( + `[ReceivingEntryMatch] 主表绑定成功 entryOrderId=${entryOrderId} receivingId=${receiving.id}` + ); + } catch (error) { + if (error.name === 'SequelizeUniqueConstraintError') { + ctx.logger.warn( + `[ReceivingEntryMatch] 绑定关系已存在(并发写入),跳过入库进度同步 entryOrderId=${entryOrderId} ` + + `receivingId=${receiving.id}` + ); + return { + receiving_id: receiving.id, + receiving_number: receiving.receiving_number, + created: false, + error_code: 'ALREADY_BOUND', + message: '绑定关系已存在(并发写入),跳过入库进度同步', + }; + } + throw error; + } + } + + // ---------- 2. 同步入库进度 ---------- + const storageSync = await this._syncReceivingStorageByEntryItems({ + entryOrder, + receiving, + transaction, + }); + + return { + receiving_id: receiving.id, + receiving_number: receiving.receiving_number, + created: true, + restored, + storage_sync: storageSync, + }; + } + + /** + * 按入库单明细同步单个收货单的入库进度(事务内,COMPLETED 场景,方案A台账版)。 + * + * 分配算法(修复同 SKU 多绑定超分漏洞): + * 1. 入库单主行 FOR UPDATE 锁由事务入口 _bindReceivingsWithStorageSync 统一前置获取 + * (全局锁序:主行 → 绑定行 → 收货明细行),本方法承接后续锁定步骤 + * 2. FOR UPDATE 行锁该入库单全部未删除绑定行 + 全部绑定收货单明细行 + * 3. 每 SKU 可分配上限 = max(0, 入库单计划数量 − 已向其他未删除绑定分配量), + * 再与当前收货单该 SKU 剩余可入量(actual_quantity − stored_quantity)取小 + * 4. 当前绑定按目标值归一化:多退少补(旧数据超分时回收、亏分时补分配), + * 明细级分配结果回写绑定行台账(allocated_quantity,明细 ID → 数量) + * 5. 重算收货单主表 storage_status,并同步 entry_items.received_quantity 台账口径 + * 6. SKU 不匹配的入库明细:记录日志并跳过,汇总进 unmatched_items + * + * @param {Object} params 参数 + * @param {Object} params.entryOrder 入库单实例 + * @param {Object} params.receiving 收货单实例 + * @param {Object} params.transaction Sequelize 事务对象 + * @return {Promise} 同步结果 { stored_total, matched_item_count, unmatched_items } + */ + async _syncReceivingStorageByEntryItems({ entryOrder, receiving, transaction } = {}) { + const { ctx, app } = this; + + // ---------- 1. 行锁入库单主行:已由事务入口 _bindReceivingsWithStorageSync 前置获取, + // 本方法内不再重复加锁(锁序:主行 → 绑定行 → 收货明细行) ---------- + + // ---------- 2. 行锁该入库单全部未删除绑定行(台账唯一事实来源) ---------- + const bindingRows = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + order: [[ 'id', 'ASC' ]], + lock: transaction.LOCK.UPDATE, + transaction, + }); + + // ---------- 3. 行锁全部绑定收货单的明细行 ---------- + const receivingIds = [ ...new Set(bindingRows.map(b => Number(b.receiving_id)).filter(Boolean)) ]; + const lockedDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [app.Sequelize.Op.in]: receivingIds } }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity', 'storage_status' ], + order: [[ 'id', 'ASC' ]], + lock: transaction.LOCK.UPDATE, + transaction, + raw: true, + }); + const detailById = new Map(lockedDetails.map(d => [ Number(d.id), d ])); + + // ---------- 4. 加载入库单明细并按 stock_id 汇总(计划数量) ---------- + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'item_code', 'stock_id', 'count' ], + raw: true, + transaction, + }); + + const entryQtyMap = new Map(); + const entryCountByStock = new Map(); + for (const item of entryItems) { + const stockId = Number(item.stock_id); + if (!stockId) continue; + const count = Number(item.count) || 0; + if (count <= 0) continue; + entryCountByStock.set(stockId, (entryCountByStock.get(stockId) || 0) + count); + const current = entryQtyMap.get(stockId); + if (current) { + current.count += count; + } else { + entryQtyMap.set(stockId, { stockId, itemCode: item.item_code || '', count }); + } + } + + // ---------- 5. 计算其他绑定(非当前收货单)按 SKU 已占用量 ---------- + const otherAllocatedByStock = new Map(); + for (const binding of bindingRows) { + if (Number(binding.receiving_id) === Number(receiving.id)) continue; + const allocByStock = this._bindingAllocationByStock({ binding, detailById, entryCountByStock }); + for (const [ stockId, qty ] of allocByStock) { + otherAllocatedByStock.set(stockId, (otherAllocatedByStock.get(stockId) || 0) + qty); + } + } + + // ---------- 6. 当前绑定:归一化分配(多退少补),并重建明细级台账 ---------- + const currentBinding = bindingRows.find(b => Number(b.receiving_id) === Number(receiving.id)); + if (!currentBinding) { + ctx.logger.warn( + `[ReceivingEntryMatch] 事务内未找到当前绑定行,跳过入库进度同步 entryOrderId=${entryOrder.id} ` + + `receivingId=${receiving.id}` + ); + return { stored_total: 0, matched_item_count: 0, unmatched_items: [] }; + } + + // 当前绑定已有台账:新链路台账直接解析;旧数据(NULL)按收货侧累计量兜底重建 + const currentLedgerMap = currentBinding.allocated_quantity !== null && currentBinding.allocated_quantity !== undefined + ? this._parseLedgerMap(currentBinding.allocated_quantity) + : this._buildLegacyBaselineLedger({ + detailById, + entryCountByStock, + receivingId: Number(receiving.id), + }); + + const currentAllocatedByStock = new Map(); + for (const [ detailId, qty ] of currentLedgerMap) { + const detail = detailById.get(detailId); + if (!detail) continue; + const stockId = Number(detail.system_product_id); + if (!stockId) continue; + currentAllocatedByStock.set(stockId, (currentAllocatedByStock.get(stockId) || 0) + qty); + } + + // 当前收货单明细(按 SKU 分组,id 升序) + const currentDetailsByStock = new Map(); + for (const detail of lockedDetails) { + if (Number(detail.receiving_id) !== Number(receiving.id)) continue; + const stockId = Number(detail.system_product_id); + if (!stockId) continue; + if (!currentDetailsByStock.has(stockId)) currentDetailsByStock.set(stockId, []); + currentDetailsByStock.get(stockId).push(detail); + } + + const newLedgerMap = new Map(currentLedgerMap); + const unmatchedItems = []; + let storedTotal = 0; + let matchedItemCount = 0; + let changed = false; + + for (const [ stockId, entryItem ] of entryQtyMap) { + const details = currentDetailsByStock.get(stockId) || []; + if (details.length === 0) { + // SKU 不匹配:记录日志并跳过(保持原行为,不影响其他 SKU 与绑定本身) + unmatchedItems.push({ + stock_id: stockId, + item_code: entryItem.itemCode, + count: entryItem.count, + }); + ctx.logger.warn( + `[ReceivingEntryMatch] SKU 不匹配,跳过入库进度同步 entryOrderId=${entryOrder.id} ` + + `receivingId=${receiving.id} stockId=${stockId} itemCode=${entryItem.itemCode} ` + + `count=${entryItem.count}` + ); + continue; + } + + const otherAllocated = otherAllocatedByStock.get(stockId) || 0; + const entryRemaining = Math.max(0, entryItem.count - otherAllocated); + const currentAllocated = currentAllocatedByStock.get(stockId) || 0; + const receivingRemaining = details.reduce( + (sum, d) => sum + Math.max(0, (Number(d.actual_quantity) || 0) - (Number(d.stored_quantity) || 0)), + 0 + ); + // 归一化目标:既不能超过入库单剩余计划,也不能超过收货单剩余可入量 + const target = Math.min(entryRemaining, currentAllocated + receivingRemaining); + const delta = target - currentAllocated; + + if (delta === 0) continue; + + if (delta > 0) { + // 补分配:明细 id 升序,逐行补足剩余可入量,台账同步累加 + let left = delta; + let allocated = 0; + for (const detail of details) { + if (left <= 0) break; + const actual = Number(detail.actual_quantity) || 0; + const stored = Number(detail.stored_quantity) || 0; + const remain = Math.max(0, actual - stored); + if (remain <= 0) continue; + const add = Math.min(left, remain); + const newStored = stored + add; + const storageStatus = newStored >= actual ? 'all' : 'partial'; + await ctx.model.ReceivingDetail.update({ + stored_quantity: newStored, + storage_status: storageStatus, + updated_at: new Date(), + }, { + where: { id: detail.id }, + transaction, + }); + detail.stored_quantity = newStored; + detail.storage_status = storageStatus; + newLedgerMap.set(Number(detail.id), (newLedgerMap.get(Number(detail.id)) || 0) + add); + changed = true; + allocated += add; + left -= add; + } + storedTotal += allocated; + if (allocated > 0) { + matchedItemCount += 1; + } + if (left > 0) { + ctx.logger.warn( + `[ReceivingEntryMatch] 入库数量未完全分配(收货明细剩余可入数量不足) entryOrderId=${entryOrder.id} ` + + `receivingId=${receiving.id} stockId=${stockId} left=${left}` + ); + } + } else { + // 归一化回收:按台账已有分配(明细 id 升序)回收超分部分,避免继续占用其他入库单的可入量 + let left = -delta; + const sortedEntries = [ ...newLedgerMap.entries() ].sort((a, b) => a[0] - b[0]); + for (const [ detailId, ledgerQty ] of sortedEntries) { + if (left <= 0) break; + const detail = detailById.get(detailId); + if (!detail || Number(detail.system_product_id) !== stockId) continue; + const remove = Math.min(left, ledgerQty); + if (remove <= 0) continue; + const stored = Number(detail.stored_quantity) || 0; + const actualRemove = Math.min(remove, stored); + const newStored = Math.max(0, stored - actualRemove); + const actual = Number(detail.actual_quantity) || 0; + const storageStatus = newStored >= actual ? 'all' : (newStored > 0 ? 'partial' : 'none'); + await ctx.model.ReceivingDetail.update({ + stored_quantity: newStored, + storage_status: storageStatus, + updated_at: new Date(), + }, { + where: { id: detail.id }, + transaction, + }); + detail.stored_quantity = newStored; + detail.storage_status = storageStatus; + const remainingLedger = ledgerQty - remove; + if (remainingLedger > 0) { + newLedgerMap.set(detailId, remainingLedger); + } else { + newLedgerMap.delete(detailId); + } + changed = true; + left -= remove; + } + if (left > 0) { + ctx.logger.warn( + `[ReceivingEntryMatch] 归一化回收未完成(台账不足) entryOrderId=${entryOrder.id} ` + + `receivingId=${receiving.id} stockId=${stockId} left=${left}` + ); + } + } + } + + // ---------- 7. 回写当前绑定台账(空台账也写 {},标记新链路已初始化) ---------- + await currentBinding.update({ + allocated_quantity: this._serializeLedgerMap(newLedgerMap), + updated_at: new Date(), + }, { transaction }); + + // ---------- 8. 汇总重算收货单主表 storage_status(基于本收货单全部明细) ---------- + let masterStatus = null; + if (changed) { + const currentRows = lockedDetails.filter(d => Number(d.receiving_id) === Number(receiving.id)); + masterStatus = await this._recalcReceivingStorageStatus(receiving.id, transaction, currentRows); + } + + // ---------- 9. 同步 entry_items.received_quantity(入库单侧台账口径,F3) ---------- + await this._reconcileEntryReceivedQuantity({ + entryOrder, + transaction, + bindingRows, + detailById, + entryCountByStock, + }); + + if (changed) { + ctx.logger.info( + `[ReceivingEntryMatch] 收货单入库进度已同步 receivingId=${receiving.id} ` + + `storageStatus=${masterStatus} storedTotal=${storedTotal} matchedItemCount=${matchedItemCount} ` + + `unmatchedCount=${unmatchedItems.length}` + ); + } else { + ctx.logger.info( + `[ReceivingEntryMatch] 无匹配 SKU 或无可分配数量,收货单入库状态保持不变 receivingId=${receiving.id} ` + + `unmatchedCount=${unmatchedItems.length}` + ); + } + + return { + stored_total: storedTotal, + matched_item_count: matchedItemCount, + unmatched_items: unmatchedItems, + }; + } + + /** + * 解析绑定行数量台账(收货明细ID → 已分配数量)。 + * 兼容对象 / JSON 字符串 / 空值;空值或解析失败返回空 Map。 + * + * @param {Object|string|null} ledgerValue 台账字段原始值 + * @return {Map} detailId → 分配数量 + */ + _parseLedgerMap(ledgerValue) { + const { ctx } = this; + const ledgerMap = new Map(); + if (!ledgerValue) return ledgerMap; + + let parsed = ledgerValue; + if (typeof ledgerValue === 'string') { + try { + parsed = JSON.parse(ledgerValue); + } catch (error) { + ctx.logger.warn(`[ReceivingEntryMatch] 台账 JSON 解析失败,按空台账处理: ${error.message}`); + return ledgerMap; + } + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return ledgerMap; + + for (const [ detailIdKey, qty ] of Object.entries(parsed)) { + const detailId = Number(detailIdKey); + const quantity = Number(qty) || 0; + if (!Number.isFinite(detailId) || detailId <= 0 || quantity <= 0) continue; + ledgerMap.set(detailId, quantity); + } + return ledgerMap; + } + + /** + * 将明细级分配数量 Map 序列化为台账 JSON(空 Map → 空对象,保持"新链路已初始化"语义)。 + * + * @param {Map} ledgerMap detailId → 分配数量 + * @return {Object} 台账 JSON 对象(空对象而非 null) + */ + _serializeLedgerMap(ledgerMap) { + const json = {}; + for (const [ detailId, qty ] of ledgerMap) { + if (!Number.isFinite(detailId) || detailId <= 0) continue; + const quantity = Number(qty) || 0; + if (quantity <= 0) continue; + json[String(detailId)] = quantity; + } + return json; + } + + /** + * 旧数据兜底:为无台账(allocated_quantity 为 null)的绑定行重建明细级分配台账。 + * 以"收货单侧已累计量"为依据:每 SKU 取 min(入库单计划数量, 该收货单该 SKU 明细 stored_quantity 之和), + * 再按明细 id 升序分摊到各收货明细(每行封顶 actual_quantity)。 + * 新链路创建的绑定行台账为 {}(非 null),不会进入该兜底。 + * + * @param {Object} params 参数 + * @param {Map} params.detailById 收货明细快照(id → detail) + * @param {Map} params.entryCountByStock stockId → 入库单计划数量 + * @param {number} params.receivingId 收货单 ID + * @return {Map} detailId → 分配数量 + */ + _buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId } = {}) { + const receivingDetails = []; + for (const detail of detailById.values()) { + if (Number(detail.receiving_id) === Number(receivingId)) receivingDetails.push(detail); + } + receivingDetails.sort((a, b) => Number(a.id) - Number(b.id)); + + const storedByStock = new Map(); + const detailsByStock = new Map(); + for (const detail of receivingDetails) { + const stockId = Number(detail.system_product_id); + if (!stockId) continue; + storedByStock.set(stockId, (storedByStock.get(stockId) || 0) + (Number(detail.stored_quantity) || 0)); + if (!detailsByStock.has(stockId)) detailsByStock.set(stockId, []); + detailsByStock.get(stockId).push(detail); + } + + const ledgerMap = new Map(); + for (const [ stockId, storedTotal ] of storedByStock) { + const entryCount = entryCountByStock.get(stockId) || 0; + let left = Math.min(entryCount, storedTotal); + if (left <= 0) continue; + for (const detail of detailsByStock.get(stockId)) { + if (left <= 0) break; + const actual = Number(detail.actual_quantity) || 0; + const assign = Math.min(left, actual); + if (assign <= 0) continue; + ledgerMap.set(Number(detail.id), assign); + left -= assign; + } + } + return ledgerMap; + } + + /** + * 计算绑定行在 SKU 维度的已分配数量: + * - 台账非 null → 台账按收货明细的 system_product_id 汇总; + * - 台账为 null(旧数据)→ 按收货单侧累计量兜底重建(封顶入库单计划数量)。 + * + * @param {Object} params 参数 + * @param {Object} params.binding 绑定行实例或快照 + * @param {Map} params.detailById 收货明细快照(id → detail) + * @param {Map} params.entryCountByStock stockId → 入库单计划数量 + * @return {Map} stockId → 已分配数量 + */ + _bindingAllocationByStock({ binding, detailById, entryCountByStock } = {}) { + const { ctx } = this; + + if (binding.allocated_quantity !== null && binding.allocated_quantity !== undefined) { + const ledgerMap = this._parseLedgerMap(binding.allocated_quantity); + const byStock = new Map(); + for (const [ detailId, qty ] of ledgerMap) { + const detail = detailById.get(detailId); + if (!detail) { + ctx.logger.warn(`[ReceivingEntryMatch] 台账存在失效收货明细,忽略 detailId=${detailId}`); + continue; + } + const stockId = Number(detail.system_product_id); + if (!stockId) continue; + byStock.set(stockId, (byStock.get(stockId) || 0) + qty); + } + return byStock; + } + + // 旧数据兜底 + const baseline = this._buildLegacyBaselineLedger({ + detailById, + entryCountByStock, + receivingId: Number(binding.receiving_id), + }); + const byStock = new Map(); + for (const [ detailId, qty ] of baseline) { + const detail = detailById.get(detailId); + if (!detail) continue; + const stockId = Number(detail.system_product_id); + if (!stockId) continue; + byStock.set(stockId, (byStock.get(stockId) || 0) + qty); + } + return byStock; + } + + /** + * 按收货单全部明细重算收货单主表 storage_status。 + * 规则:全部明细 stored >= actual → 'all';存在部分入库 → 'partial';全部未入库 → 'none'。 + * + * @param {number} receivingId 收货单 ID + * @param {Object} transaction Sequelize 事务对象 + * @param {Array|null} [detailRows] 已锁定的明细快照(可选,缺省时重新查询) + * @return {Promise} 重算后的 storage_status + */ + async _recalcReceivingStorageStatus(receivingId, transaction, detailRows = null) { + const { ctx } = this; + + const rows = detailRows || await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ 'actual_quantity', 'stored_quantity' ], + raw: true, + transaction, + }); + + let masterStatus = 'none'; + const fullyStored = rows.length > 0 + && rows.every(d => (Number(d.stored_quantity) || 0) >= (Number(d.actual_quantity) || 0)); + if (fullyStored) { + masterStatus = 'all'; + } else if (rows.some(d => (Number(d.stored_quantity) || 0) > 0)) { + masterStatus = 'partial'; + } + + await ctx.model.Receiving.update({ + storage_status: masterStatus, + updated_at: new Date(), + }, { + where: { id: receivingId }, + transaction, + }); + + return masterStatus; + } + + /** + * 重算入库单明细 received_quantity(F3 口径对齐)。 + * 按 stock_id 汇总该入库单全部未删除绑定的台账占用(旧数据按收货侧累计量兜底), + * 再按明细 id 升序分摊到各明细行(每行封顶计划数量), + * 使入库单侧已入库量与各绑定收货单 stored_quantity 之和可对账。 + * + * @param {Object} params 参数 + * @param {Object} params.entryOrder 入库单实例(至少含 id) + * @param {Object} params.transaction Sequelize 事务对象 + * @param {Array|null} [params.bindingRows] 已锁定的绑定行(可选,缺省重新查询) + * @param {Map|null} [params.detailById] 已锁定的收货明细快照(可选) + * @param {Map|null} [params.entryCountByStock] stockId → 计划数量(可选) + * @return {Promise} + */ + async _reconcileEntryReceivedQuantity({ + entryOrder, + transaction, + bindingRows = null, + detailById = null, + entryCountByStock = null, + } = {}) { + const { ctx, app } = this; + + const bindings = bindingRows || await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + raw: true, + transaction, + }); + + let detailsMap = detailById; + if (!detailsMap) { + const receivingIds = [ ...new Set(bindings.map(b => Number(b.receiving_id)).filter(Boolean)) ]; + if (receivingIds.length > 0) { + const rows = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [app.Sequelize.Op.in]: receivingIds } }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'stored_quantity' ], + raw: true, + transaction, + }); + detailsMap = new Map(rows.map(d => [ Number(d.id), d ])); + } else { + detailsMap = new Map(); + } + } + + let countByStock = entryCountByStock; + if (!countByStock) { + countByStock = new Map(); + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'stock_id', 'count' ], + raw: true, + transaction, + }); + for (const item of items) { + const stockId = Number(item.stock_id); + if (!stockId) continue; + countByStock.set(stockId, (countByStock.get(stockId) || 0) + (Number(item.count) || 0)); + } + } + + // 汇总每 SKU 的台账占用 + const allocatedByStock = new Map(); + for (const binding of bindings) { + const allocByStock = this._bindingAllocationByStock({ binding, detailById: detailsMap, entryCountByStock: countByStock }); + for (const [ stockId, qty ] of allocByStock) { + allocatedByStock.set(stockId, (allocatedByStock.get(stockId) || 0) + qty); + } + } + + // 按明细 id 升序分摊到各明细行(封顶计划数量),保持同 SKU 多明细顺序语义 + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], + order: [[ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + const itemsByStock = new Map(); + for (const item of items) { + const stockId = Number(item.stock_id); + if (!stockId) continue; + if (!itemsByStock.has(stockId)) itemsByStock.set(stockId, []); + itemsByStock.get(stockId).push(item); + } + + for (const [ stockId, total ] of allocatedByStock) { + const stockItems = itemsByStock.get(stockId) || []; + let left = Math.min(total, countByStock.get(stockId) || 0); + for (const item of stockItems) { + if (left <= 0) break; + const itemCount = Number(item.count) || 0; + const share = Math.min(left, itemCount); + if (share !== (Number(item.received_quantity) || 0)) { + await ctx.model.EntryItems.update({ + received_quantity: share, + }, { + where: { id: item.id }, + transaction, + }); + } + left -= share; + } + } + } + + /** + * 累计台账:把本次已实际落到收货明细的分配量累加到对应绑定行台账。 + * 供完成链路(quickInbound / commit 非绑定占用 / PDA 明细绑定)在写 stored_quantity 后调用, + * 保证台账与收货单侧进度一致。旧绑定行(台账为 null)先按收货侧累计量兜底初始化。 + * + * @param {Object} params 参数 + * @param {number} params.entryOrderId 入库单 ID + * @param {Map} params.detailDeltaMap 收货明细ID → 本次分配增量 + * @param {Object} params.transaction Sequelize 事务对象 + * @return {Promise} + */ + async recordLedgerAllocation({ entryOrderId, detailDeltaMap, transaction } = {}) { + const { ctx, app } = this; + if (!entryOrderId || !detailDeltaMap || detailDeltaMap.size === 0) return; + + const receivingIds = []; + for (const info of detailDeltaMap.values()) { + if (info && Number(info.receivingId)) receivingIds.push(Number(info.receivingId)); + } + const uniqueReceivingIds = [ ...new Set(receivingIds) ]; + if (uniqueReceivingIds.length === 0) return; + + // 1. 行锁涉及收货单的绑定行 + const bindingRows = await ctx.model.EntryOrderReceiving.findAll({ + where: { + entry_order_id: entryOrderId, + receiving_id: { [app.Sequelize.Op.in]: uniqueReceivingIds }, + deleted_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + const bindingByReceiving = new Map(bindingRows.map(b => [ Number(b.receiving_id), b ])); + + // 2. 读取涉及收货单的全部明细与入库单计划数量(供旧台账兜底初始化) + const detailRows = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [app.Sequelize.Op.in]: uniqueReceivingIds } }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], + raw: true, + transaction, + }); + const detailById = new Map(detailRows.map(d => [ Number(d.id), d ])); + + const entryItemRows = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'stock_id', 'count' ], + raw: true, + transaction, + }); + const entryCountByStock = new Map(); + for (const item of entryItemRows) { + const stockId = Number(item.stock_id); + if (!stockId) continue; + entryCountByStock.set(stockId, (entryCountByStock.get(stockId) || 0) + (Number(item.count) || 0)); + } + + // 3. 逐绑定行回写台账 + for (const [ receivingId, binding ] of bindingByReceiving) { + const ledgerMap = binding.allocated_quantity !== null && binding.allocated_quantity !== undefined + ? this._parseLedgerMap(binding.allocated_quantity) + : this._buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId }); + + let changed = false; + for (const [ detailId, info ] of detailDeltaMap) { + if (Number(info.receivingId) !== receivingId) continue; + const qty = Number(info.quantity) || 0; + if (qty <= 0) continue; + ledgerMap.set(detailId, (ledgerMap.get(detailId) || 0) + qty); + changed = true; + } + if (!changed) continue; + + await binding.update({ + allocated_quantity: this._serializeLedgerMap(ledgerMap), + updated_at: new Date(), + }, { transaction }); + } + } + + /** + * 覆盖台账:绑定模式完成链路(commit)对收货明细 stored_quantity 为直接覆写语义, + * 台账同步覆写对应明细条目(其余明细条目保持不动)。旧绑定行先按收货侧累计量兜底初始化。 + * + * @param {Object} params 参数 + * @param {number} params.entryOrderId 入库单 ID + * @param {Map} params.detailQuantityMap 收货明细ID → 覆写数量 + * @param {Object} params.transaction Sequelize 事务对象 + * @return {Promise} + */ + async setLedgerAllocation({ entryOrderId, detailQuantityMap, transaction } = {}) { + const { ctx, app } = this; + if (!entryOrderId || !detailQuantityMap || detailQuantityMap.size === 0) return; + + const receivingIds = []; + for (const info of detailQuantityMap.values()) { + if (info && Number(info.receivingId)) receivingIds.push(Number(info.receivingId)); + } + const uniqueReceivingIds = [ ...new Set(receivingIds) ]; + if (uniqueReceivingIds.length === 0) return; + + // 1. 行锁涉及收货单的绑定行 + const bindingRows = await ctx.model.EntryOrderReceiving.findAll({ + where: { + entry_order_id: entryOrderId, + receiving_id: { [app.Sequelize.Op.in]: uniqueReceivingIds }, + deleted_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + const bindingByReceiving = new Map(bindingRows.map(b => [ Number(b.receiving_id), b ])); + + // 2. 读取涉及收货单的全部明细与入库单计划数量(供旧台账兜底初始化) + const detailRows = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [app.Sequelize.Op.in]: uniqueReceivingIds } }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], + raw: true, + transaction, + }); + const detailById = new Map(detailRows.map(d => [ Number(d.id), d ])); + + const entryItemRows = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'stock_id', 'count' ], + raw: true, + transaction, + }); + const entryCountByStock = new Map(); + for (const item of entryItemRows) { + const stockId = Number(item.stock_id); + if (!stockId) continue; + entryCountByStock.set(stockId, (entryCountByStock.get(stockId) || 0) + (Number(item.count) || 0)); + } + + // 3. 逐绑定行覆写台账条目 + for (const [ receivingId, binding ] of bindingByReceiving) { + const ledgerMap = binding.allocated_quantity !== null && binding.allocated_quantity !== undefined + ? this._parseLedgerMap(binding.allocated_quantity) + : this._buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId }); + + let changed = false; + for (const [ detailId, info ] of detailQuantityMap) { + if (Number(info.receivingId) !== receivingId) continue; + const qty = Number(info.quantity) || 0; + if (qty <= 0) { + if (ledgerMap.delete(detailId)) changed = true; + } else { + ledgerMap.set(detailId, qty); + changed = true; + } + } + if (!changed) continue; + + await binding.update({ + allocated_quantity: this._serializeLedgerMap(ledgerMap), + updated_at: new Date(), + }, { transaction }); + } + } + + /** + * 回滚入库单绑定的台账占用(作废/解绑共用入口)。 + * 对每个未删除绑定:按台账(旧数据按收货侧累计量兜底)回收该绑定在收货单上的 + * stored_quantity,重算 storage_status,并把台账重置为空对象。 + * 事务内行锁入库单主行与相关收货明细,避免误清其他入库单的占用。 + * + * @param {Object} params 参数 + * @param {number} params.entryOrderId 入库单 ID + * @param {number|null} [params.receivingId] 仅回滚该收货单(解绑场景),null 回滚全部(作废场景) + * @param {boolean} [params.softDeleteBinding=true] 是否软删除绑定行 + * @return {Promise} { rolled_back: Array<{receiving_id, detail_count, rolled_back_quantity}> } + */ + async rollbackEntryOrderBindings({ entryOrderId, receivingId = null, softDeleteBinding = true } = {}) { + const { ctx } = this; + + return await ctx.model.transaction(async transaction => { + // 串行化同一入库单的分配/回滚事务 + await ctx.model.EntryOrder.findByPk(entryOrderId, { + attributes: [ 'id' ], + lock: transaction.LOCK.UPDATE, + transaction, + }); + + const where = { entry_order_id: entryOrderId, deleted_at: null }; + if (receivingId !== null && receivingId !== undefined) { + where.receiving_id = receivingId; + } + const bindingRows = await ctx.model.EntryOrderReceiving.findAll({ + where, + order: [[ 'id', 'ASC' ]], + lock: transaction.LOCK.UPDATE, + transaction, + }); + + const rolledBack = []; + for (const binding of bindingRows) { + const result = await this._rollbackOneBindingStorage({ + binding, + entryOrderId, + transaction, + softDelete: softDeleteBinding, + }); + if (result) rolledBack.push(result); + } + + // 回滚后重算入库单侧 received_quantity(与台账对齐) + await this._reconcileEntryReceivedQuantity({ entryOrder: { id: entryOrderId }, transaction }); + + return { rolled_back: rolledBack }; + }); + } + + /** + * 回滚单条绑定的台账占用:按台账明细条目(旧数据兜底)扣减收货明细 stored_quantity, + * 重算收货单 storage_status,并把绑定台账重置为空对象。 + * + * @param {Object} params 参数 + * @param {Object} params.binding 已行锁的绑定行实例 + * @param {number} params.entryOrderId 入库单 ID + * @param {Object} params.transaction Sequelize 事务对象 + * @param {boolean} [params.softDelete=false] 是否软删除绑定行 + * @return {Promise} 回滚汇总,无可回滚量时返回 null + */ + async _rollbackOneBindingStorage({ binding, entryOrderId, transaction, softDelete = false } = {}) { + const { ctx } = this; + + const receivingId = Number(binding.receiving_id); + const lockedDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity', 'storage_status' ], + order: [[ 'id', 'ASC' ]], + lock: transaction.LOCK.UPDATE, + transaction, + raw: true, + }); + const detailById = new Map(lockedDetails.map(d => [ Number(d.id), d ])); + + const entryItemRows = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'stock_id', 'count' ], + raw: true, + transaction, + }); + const entryCountByStock = new Map(); + for (const item of entryItemRows) { + const stockId = Number(item.stock_id); + if (!stockId) continue; + entryCountByStock.set(stockId, (entryCountByStock.get(stockId) || 0) + (Number(item.count) || 0)); + } + + // 回滚条目:优先台账;旧数据按收货侧累计量兜底 + const ledgerMap = binding.allocated_quantity !== null && binding.allocated_quantity !== undefined + ? this._parseLedgerMap(binding.allocated_quantity) + : this._buildLegacyBaselineLedger({ detailById, entryCountByStock, receivingId }); + + let rolledBackQty = 0; + let touchedCount = 0; + const sortedEntries = [ ...ledgerMap.entries() ].sort((a, b) => a[0] - b[0]); + for (const [ detailId, ledgerQty ] of sortedEntries) { + const detail = detailById.get(detailId); + if (!detail) { + ctx.logger.warn(`[ReceivingEntryMatch] 回滚时台账明细不存在,跳过 detailId=${detailId}`); + continue; + } + const stored = Number(detail.stored_quantity) || 0; + const remove = Math.min(ledgerQty, stored); + if (remove <= 0) continue; + const newStored = stored - remove; + const actual = Number(detail.actual_quantity) || 0; + const storageStatus = newStored >= actual ? 'all' : (newStored > 0 ? 'partial' : 'none'); + await ctx.model.ReceivingDetail.update({ + stored_quantity: newStored, + storage_status: storageStatus, + updated_at: new Date(), + }, { + where: { id: detail.id }, + transaction, + }); + detail.stored_quantity = newStored; + detail.storage_status = storageStatus; + rolledBackQty += remove; + touchedCount += 1; + } + + // 重算收货单主表状态(基于本收货单全部明细,不影响其他入库单占用) + await this._recalcReceivingStorageStatus(receivingId, transaction, lockedDetails); + + // 台账重置为空对象(保留"已初始化"语义,恢复绑定时从 0 重新分配) + await binding.update({ + allocated_quantity: {}, + updated_at: new Date(), + }, { transaction }); + + if (softDelete) { + await binding.destroy({ transaction }); + } + + if (touchedCount === 0) return null; + + return { + receiving_id: receivingId, + detail_count: touchedCount, + rolled_back_quantity: rolledBackQty, + }; + } + + /** + * 获取仓库近 3 天的收货单列表(优先从 Redis 缓存读取)。 + * + * @param {number} warehouseId 仓库 ID + * @return {Promise>} 收货单列表(含明细) + */ + async _getRecentReceivingOrders(warehouseId) { + const { ctx, app } = this; + const cacheKey = `${RECEIVING_CACHE_KEY_PREFIX}${warehouseId}`; + + try { + // 先尝试从缓存读取 + const cached = await app.getCacheAsync(cacheKey); + if (cached) { + ctx.logger.info(`[ReceivingEntryMatch] 命中收货单缓存 warehouseId=${warehouseId}`); + return cached; + } + } catch (cacheErr) { + ctx.logger.warn(`[ReceivingEntryMatch] 读取缓存失败,回退到数据库查询: ${cacheErr.message}`); + } + + // 缓存未命中,从数据库查询 + const threeDaysAgo = new Date(Date.now() - RECEIVING_LOOKBACK_DAYS * 24 * 60 * 60 * 1000); + + const receivingOrders = await ctx.model.Receiving.findAll({ + where: { + warehouse_id: warehouseId, + is_deleted: false, + is_review: 1, + status: [ 'receiving', 'completed' ], + created_at: { [app.Sequelize.Op.gte]: threeDaysAgo }, + }, + attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], + include: [{ + model: ctx.model.ReceivingDetail, + as: 'details', + required: false, + attributes: [ + 'id', 'system_product_id', 'product_name', 'actual_quantity', + 'storage_status', 'stored_quantity', + ], + }], + order: [[ 'created_at', 'DESC' ]], + }); + + const result = receivingOrders.map(order => { + const plain = typeof order.toJSON === 'function' ? order.toJSON() : order; + return { + id: plain.id, + receiving_number: plain.receiving_number, + status: plain.status, + storage_status: plain.storage_status, + details: (plain.details || []).map(d => ({ + id: d.id, + system_product_id: d.system_product_id, + product_name: d.product_name, + actual_quantity: d.actual_quantity, + storage_status: d.storage_status, + stored_quantity: d.stored_quantity || 0, + })), + }; + }); + + // 写入缓存 + try { + await app.setCacheAsync(cacheKey, result, RECEIVING_CACHE_TTL); + ctx.logger.info(`[ReceivingEntryMatch] 收货单缓存已写入 warehouseId=${warehouseId} count=${result.length}`); + } catch (cacheErr) { + ctx.logger.warn(`[ReceivingEntryMatch] 写入缓存失败: ${cacheErr.message}`); + } + + return result; + } + + /** + * 从入库单备注中查找匹配的收货单号。 + * 遍历缓存的收货单号列表,检查 remark 是否包含收货单号。 + * 若匹配到多个,返回最近创建的那一个。 + * + * @param {string} remark 入库单备注 + * @param {Array} receivingOrders 收货单列表 + * @param {number} warehouseId 仓库 ID + * @return {Promise} 匹配到的收货单(含明细),未匹配返回 null + */ + async _findReceivingByRemark(remark, receivingOrders, warehouseId) { + const { ctx } = this; + + // 按字符串包含匹配 + const matchedOrders = []; + for (const order of receivingOrders) { + if (remark.includes(order.receiving_number)) { + matchedOrders.push(order); + } + } + + if (matchedOrders.length === 0) { + return null; + } + + // 多个匹配时取第一个(列表已按 created_at DESC 排序,即最新) + const matched = matchedOrders[0]; + + // 如果缓存的收货单没有 details(可能为空),重新加载 + if (!matched.details || matched.details.length === 0) { + const fullOrder = await ctx.model.Receiving.findOne({ + where: { id: matched.id, warehouse_id: warehouseId, is_deleted: false, is_review: 1 }, + attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], + include: [{ + model: ctx.model.ReceivingDetail, + as: 'details', + required: false, + attributes: [ + 'id', 'system_product_id', 'product_name', 'actual_quantity', + 'storage_status', 'stored_quantity', + ], + }], + }); + + if (!fullOrder) return null; + + const plain = typeof fullOrder.toJSON === 'function' ? fullOrder.toJSON() : fullOrder; + return { + id: plain.id, + receiving_number: plain.receiving_number, + status: plain.status, + storage_status: plain.storage_status, + details: (plain.details || []).map(d => ({ + id: d.id, + system_product_id: d.system_product_id, + product_name: d.product_name, + actual_quantity: d.actual_quantity, + storage_status: d.storage_status, + stored_quantity: d.stored_quantity || 0, + })), + }; + } + + return matched; + } + + /** + * 对比入库单明细与收货单明细。 + * + * 判断规则: + * - full_match:两者 SKU 与数量完全一致 + * - receiving_covers_entry:收货单包含入库单所有明细(SKU 匹配), + * 且收货单至少有一个 SKU 数量多于入库单 + * - entry_exceeds_receiving:入库单有收货单没有的 SKU 或数量超出 + * - no_match:SKU 完全没有交集 + * + * @param {Array} entryItems 入库单明细 [{ stockId, itemCode, count, receivedQuantity, inventoryType }] + * @param {Array} receivingDetails 收货单明细 [{ id, system_product_id, actual_quantity, ... }] + * @return {{ type: string, matchedDetails?: Array, uncoveredDetails?: Array, overageDetails?: Array }} 对比结果对象 + */ + _compareDetails(entryItems, receivingDetails) { + // 构建收货单明细 Map:system_product_id → { actual_quantity, ... } + const receivingMap = new Map(); + for (const detail of receivingDetails) { + const productId = detail.system_product_id; + if (!productId) continue; + const existing = receivingMap.get(productId); + if (existing) { + existing.actual_quantity += (detail.actual_quantity || 0); + } else { + receivingMap.set(productId, { + detailId: detail.id, + system_product_id: productId, + actual_quantity: detail.actual_quantity || 0, + stored_quantity: detail.stored_quantity || 0, + }); + } + } + + // 构建入库单明细 Map:stock_id → { count, receivedQuantity } + const entryMap = new Map(); + for (const item of entryItems) { + const stockId = item.stockId; + if (!stockId) continue; + const existing = entryMap.get(stockId); + if (existing) { + existing.count += (item.count || 0); + existing.receivedQuantity += (item.receivedQuantity || 0); + } else { + entryMap.set(stockId, { + stockId, + itemCode: item.itemCode, + count: item.count || 0, + receivedQuantity: item.receivedQuantity || 0, + inventoryType: item.inventoryType, + }); + } + } + + if (entryMap.size === 0 || receivingMap.size === 0) { + return { type: 'no_match' }; + } + + // 检查入库单每个 SKU 是否在收货单中且数量 ≤ 收货单数量 + let allEntryItemsCovered = true; + let hasReceivingOverage = false; + const matchedDetails = []; // 匹配到的收货单明细 + const uncoveredDetails = []; // 入库单中有但收货单没有/不足的 + + for (const [ stockId, entryItem ] of entryMap) { + const receivingItem = receivingMap.get(stockId); + + if (!receivingItem) { + // 入库单有,收货单没有 → 入库单超出 + allEntryItemsCovered = false; + uncoveredDetails.push({ + stockId, + itemCode: entryItem.itemCode, + entryCount: entryItem.count, + receivingCount: 0, + reason: 'missing_in_receiving', + }); + continue; + } + + if (entryItem.count > receivingItem.actual_quantity) { + // 入库单数量 > 收货单数量 → 入库单超出 + allEntryItemsCovered = false; + uncoveredDetails.push({ + stockId, + itemCode: entryItem.itemCode, + entryCount: entryItem.count, + receivingCount: receivingItem.actual_quantity, + reason: 'entry_exceeds_receiving', + }); + } else if (entryItem.count < receivingItem.actual_quantity) { + // 收货单数量 > 入库单数量 → 存在覆盖余量 + hasReceivingOverage = true; + matchedDetails.push({ + ...receivingItem, + entryCount: entryItem.count, + overage: receivingItem.actual_quantity - entryItem.count, + }); + } else { + // 数量完全相等 + matchedDetails.push({ + ...receivingItem, + entryCount: entryItem.count, + overage: 0, + }); + } + } + + // 检查收货单是否有入库单没有的 SKU + const receivingOnlyItems = []; + for (const [ productId ] of receivingMap) { + if (!entryMap.has(productId)) { + receivingOnlyItems.push(productId); + } + } + + if (!allEntryItemsCovered) { + return { + type: 'entry_exceeds_receiving', + uncoveredDetails, + receivingOnlyItems, + }; + } + + if (hasReceivingOverage || receivingOnlyItems.length > 0) { + return { + type: 'receiving_covers_entry', + matchedDetails, + overageDetails: matchedDetails.filter(d => d.overage > 0), + receivingOnlyItems, + }; + } + + // 所有入库单 SKU 都在收货单中,且数量完全相等,且收货单无额外 SKU + return { + type: 'full_match', + matchedDetails, + }; + } + + /** + * 加载入库单明细并组装为奇门 orderLines 数组(行号从 1 递增)。 + * ownerCode / itemCode / itemId 缺省为空字符串,inventoryType 缺省为 ZP, + * planQty 取计划数量、actualQty 取已入库数量,缺省为 0。 + * @param {Object} entryOrder 入库单实例 + * @return {Promise|null>} 明细行数组;无明细时返回 null + */ + async _queryEntryOrderLines(entryOrder) { + const { ctx } = this; + + // 重新加载入库单明细 + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code', 'received_quantity' ], + raw: true, + }); + + if (!items || items.length === 0) { + return null; + } + + return items.map((item, index) => ({ + orderLineNo: index + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: item.count || 0, + actualQty: item.received_quantity || 0, + })); + } + + /** + * 组装 entryorder.confirm 业务报文(与奇门 taobao.qimen.entryorder.confirm 同层级)。 + * 返回 { entryOrder, orderLines },不包含外层 request 包装, + * 字段与取值逻辑以奇门分支为唯一基准,奇门与 OpenAPI 回传共用。 + * @param {Object} entryOrder 入库单实例 + * @param {Array} orderLines 入库明细行数组 + * @param {Object} [options] 可选配置 + * @param {string} [options.outBizCode] 外部业务编码,缺省时自动生成 RECEIVING_MATCH_时间戳 + * @param {string} [options.remark] 备注 + * @return {{ entryOrder: Object, orderLines: Array }} 组装后的业务报文 + */ + buildEntryOrderConfirmRequest(entryOrder, orderLines, options = {}) { + const { app } = this; + const { outBizCode, remark } = options; + + return { + entryOrder: { + entryOrderCode: entryOrder.entry_order_code, + ownerCode: entryOrder.qimen_owner_code || '', + warehouseCode: entryOrder.qimen_warehouse_code || '', + entryOrderId: entryOrder.id, + entryOrderType: entryOrder.order_type, + outBizCode: outBizCode || `RECEIVING_MATCH_${Date.now()}`, + confirmType: 0, // 0 = 最终确认 + status: 'FULFILLED', + freight: 0, + operateTime: app.formatDate(new Date()), + remark: remark || '', + }, + orderLines, + }; + } + + /** + * 根据入库单来源发送回传。 + * - QM(奇门)→ 调用奇门入库单确认接口回传 + * - API(OpenAPI)→ 查询 ApiApp 回调地址并 POST 回传 + * + * @param {Object} entryOrder 入库单实例 + * @param {Object} receivingOrder 匹配到的收货单 + * @param {string} [matchType='auto_match'] 匹配类型标识,手动匹配时传入 'manual_match' + * @return {Promise<{success: boolean, sourceType: string, detail: Object}>} 回传结果 + */ + async _sendCallback(entryOrder, receivingOrder, matchType = 'auto_match') { + const { ctx } = this; + const sourceType = String(entryOrder.source_type || '').toUpperCase(); + + ctx.logger.info( + `[ReceivingEntryMatch] 准备回传 entryOrderId=${entryOrder.id} ` + + `sourceType=${sourceType} receivingNumber=${receivingOrder.receiving_number}` + ); + + if (sourceType === 'QM') { + const detail = await this._sendQimenCallback(entryOrder, receivingOrder); + return { success: detail.success, sourceType, detail }; + } else if (sourceType === 'API') { + const detail = await this._sendOpenApiCallback(entryOrder, receivingOrder, matchType); + return { success: detail.success, sourceType, detail }; + } + + ctx.logger.info( + `[ReceivingEntryMatch] 来源类型 ${sourceType} 不支持回传 entryOrderId=${entryOrder.id}` + ); + return { success: false, sourceType, detail: { success: false, error: `来源类型 ${sourceType} 不支持回传` } }; + } + + /** + * 奇门回传:复用现有奇门入库单确认接口。 + * + * @param {Object} entryOrder 入库单实例 + * @param {Object} receivingOrder 匹配到的收货单 + * @return {Promise<{success: boolean, error?: string}>} 回传结果 + */ + async _sendQimenCallback(entryOrder, receivingOrder) { + const { ctx, app } = this; + + try { + // 重新加载入库单明细并组装为奇门 orderLines + const orderLines = await this._queryEntryOrderLines(entryOrder); + + if (!orderLines) { + ctx.logger.warn(`[ReceivingEntryMatch] 奇门回传:入库单无明细 entryOrderId=${entryOrder.id}`); + return { success: false, error: '入库单无明细' }; + } + + const request = this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { + outBizCode: `RECEIVING_MATCH_${Date.now()}`, + remark: `匹配收货单${receivingOrder.receiving_number}自动回传`, + }); + + const result = await app.qimenClient.send( + 'taobao.qimen.entryorder.confirm', + entryOrder.qimen_owner_code, + { request }, + { ctx } + ); + + const qimenResult = result && result.xmlArray && result.xmlArray.response; + if (qimenResult && String(qimenResult.flag) === 'success') { + ctx.logger.info( + `[ReceivingEntryMatch] 奇门回传成功 entryOrderId=${entryOrder.id} ` + + `receivingNumber=${receivingOrder.receiving_number}` + ); + return { success: true }; + } + ctx.logger.warn( + `[ReceivingEntryMatch] 奇门回传失败 entryOrderId=${entryOrder.id} ` + + `message=${qimenResult?.message || '未知错误'}` + ); + return { success: false, error: qimenResult?.message || '未知错误' }; + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 奇门回传异常 entryOrderId=${entryOrder.id}: ${error.message}`, + error.stack + ); + return { success: false, error: error.message }; + } + } + + /** + * OpenAPI 回传:查询 ApiApp 回调地址,通过签名鉴权 POST 回传。 + * 报文体与奇门同层级({ request: { entryOrder, orderLines } },外层 request 由发送端自动包裹), + * 与 _sendQimenCallback 共用同一份报文组装。 + * + * @param {Object} entryOrder 入库单实例 + * @param {Object} receivingOrder 匹配到的收货单 + * @param {string} [matchType='auto_match'] 匹配类型标识(仅用于日志,奇门报文无对应位置,不回传) + * @return {Promise<{success: boolean, error?: string, retryCount?: number}>} 回传结果 + */ + async _sendOpenApiCallback(entryOrder, receivingOrder, matchType = 'auto_match') { + const { ctx, app } = this; + + try { + // 通过 store_warehouse 查找 ApiApp + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: entryOrder.store_id, + warehouse_id: entryOrder.warehouse_id, + auth_status: 2, // 已通过 + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!storeWarehouse) { + ctx.logger.warn( + '[ReceivingEntryMatch] OpenAPI回传:未找到授权关系 ' + + `entryOrderId=${entryOrder.id} storeId=${entryOrder.store_id} warehouseId=${entryOrder.warehouse_id}` + ); + return { success: false, error: '未找到授权关系' }; + } + + const apiApp = await ctx.model.ApiApp.findOne({ + where: { + contract_id: storeWarehouse.id, + is_enabled: 1, + callback_url: { + [ app.Sequelize.Op.and ]: [ + { [ app.Sequelize.Op.ne ]: null }, + { [ app.Sequelize.Op.ne ]: '' }, + ], + }, + }, + attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ], + raw: true, + }); + + if (!apiApp || !apiApp.callback_url) { + ctx.logger.warn( + '[ReceivingEntryMatch] OpenAPI回传:未找到有效ApiApp配置 ' + + `entryOrderId=${entryOrder.id} contractId=${storeWarehouse.id}` + ); + return { success: false, error: '未找到有效ApiApp配置' }; + } + + // 组装与奇门同层级的业务报文(entryorder.match 与奇门 entryorder.confirm 共用同一份组装) + const orderLines = await this._queryEntryOrderLines(entryOrder); + + if (!orderLines) { + ctx.logger.warn( + '[ReceivingEntryMatch] OpenAPI回传:入库单无明细 ' + + `entryOrderId=${entryOrder.id} receivingNumber=${receivingOrder.receiving_number}` + ); + return { success: false, error: '入库单无明细' }; + } + + const request = this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { + remark: `匹配收货单${receivingOrder.receiving_number}自动回传`, + }); + + // 使用 OpenAPI 回调服务发送(matchType 仅保留在日志中,不塞入奇门报文) + const result = await ctx.service.openapi.callback.sendWithRetry({ + callbackUrl: apiApp.callback_url, + appKey: apiApp.self_app_key, + selfAppSecret: apiApp.self_app_secret || '', + event: 'entryorder.match', + request, + }); + + if (result.success) { + ctx.logger.info( + `[ReceivingEntryMatch] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + + `callbackUrl=${apiApp.callback_url} matchType=${matchType} retryCount=${result.retryCount}` + ); + return { success: true, retryCount: result.retryCount }; + } + ctx.logger.warn( + `[ReceivingEntryMatch] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` + + `matchType=${matchType} error=${result.error} retryCount=${result.retryCount}` + ); + return { success: false, error: result.error, retryCount: result.retryCount }; + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] OpenAPI回传异常 entryOrderId=${entryOrder.id}: ${error.message}`, + error.stack + ); + return { success: false, error: error.message }; + } + } + + /** + * 标记收货单为"部分入库"。 + * 更新收货单 storage_status 为 'partial',并更新明细的 storage_status 和 stored_quantity。 + * + * @param {number} receivingId 收货单 ID + * @param {Object} comparisonResult 对比结果 + * @param {number} warehouseId 仓库 ID + * @return {Promise<{success: boolean, error?: string}>} 标记结果 + */ + async _markReceivingPartialStorage(receivingId, comparisonResult, warehouseId) { + const { ctx } = this; + + try { + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false }, + }); + + if (!receiving) { + ctx.logger.warn(`[ReceivingEntryMatch] 标记部分入库:收货单不存在 receivingId=${receivingId}`); + return { success: false, error: '收货单不存在' }; + } + + // 更新收货单主表的入库状态 + await receiving.update({ + storage_status: 'partial', + updated_at: new Date(), + }); + + // 更新匹配到的明细:标记为"全部入库",stored_quantity = entryCount + if (comparisonResult.matchedDetails && comparisonResult.matchedDetails.length > 0) { + for (const matched of comparisonResult.matchedDetails) { + await ctx.model.ReceivingDetail.update( + { + storage_status: 'all', + stored_quantity: matched.entryCount || matched.actual_quantity || 0, + updated_at: new Date(), + }, + { where: { id: matched.detailId, receiving_id: receivingId } } + ); + } + } + + // 更新超量明细:标记为"部分入库",stored_quantity = entryCount + if (comparisonResult.overageDetails && comparisonResult.overageDetails.length > 0) { + for (const overage of comparisonResult.overageDetails) { + await ctx.model.ReceivingDetail.update( + { + storage_status: 'partial', + stored_quantity: overage.entryCount || 0, + updated_at: new Date(), + }, + { where: { id: overage.detailId, receiving_id: receivingId } } + ); + } + } + + ctx.logger.info( + `[ReceivingEntryMatch] 收货单已标记为部分入库 receivingId=${receivingId} ` + + `receivingNumber=${receiving.receiving_number}` + ); + return { success: true }; + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 标记部分入库失败 receivingId=${receivingId}: ${error.message}`, + error.stack + ); + return { success: false, error: error.message }; + } + } + + /** + * 内部公共方法:在事务中提交单条入库明细-收货明细绑定。 + * 包含 FOR UPDATE 行锁、可用量二次校验、绑定写入、主表绑定确保。 + * 被 PDA 上架 addItem 流程调用,用于逐条写入明细绑定。 + * + * @param {Object} params 绑定参数 + * @param {number} params.entryItemId 入库单明细 ID + * @param {number} params.receivingDetailId 收货单明细 ID + * @param {number} params.qty 分配数量 + * @param {number} params.expectedSpId 期望的 system_product_id(用于匹配校验,可选) + * @param {number} params.entryOrderId 入库单 ID(用于确保主表绑定存在) + * @param {Object} params.transaction Sequelize 事务对象 + * @throws {Object} 结构化错误对象,包含 error_code、message、detail + * @return {Promise} + */ + async _commitBinding({ entryItemId, receivingDetailId, qty, expectedSpId, entryOrderId, transaction } = {}) { + const { ctx } = this; + + // 1. FOR UPDATE 锁收货明细行 + const lockedDetail = await ctx.model.query( + `SELECT id, actual_quantity, receiving_id, system_product_id + FROM wms_receiving_detail + WHERE id = :rdId FOR UPDATE`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + if (!lockedDetail || lockedDetail.length === 0) { + throw { + error_code: 'RECEIVING_DETAIL_NOT_FOUND', + message: '收货明细不存在', + detail: { receiving_detail_id: receivingDetailId }, + }; + } + + // 2. 校验收货明细与入库商品是否匹配(system_product_id) + if (expectedSpId !== undefined && lockedDetail[0].system_product_id !== expectedSpId) { + throw { + error_code: 'RECEIVING_DETAIL_MISMATCH', + message: '收货明细与入库商品不匹配', + detail: { + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + expected_sp_id: expectedSpId, + actual_sp_id: lockedDetail[0].system_product_id, + }, + }; + } + + // 3. 查已 committed 的分配量(从 InboundDirectLog 查) + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(quantity), 0) AS total + FROM wms_inbound_direct_log + WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0); + if (qty > availableQty) { + throw { + error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY', + message: '分配数量超出可用量', + detail: { available_quantity: availableQty, requested_quantity: qty }, + }; + } + + // 4. 获取入库单信息以写入 InboundDirectLog + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId, { transaction }); + if (!entryOrder) { + throw { + error_code: 'ENTRY_ORDER_NOT_FOUND', + message: '入库单不存在', + detail: { entry_order_id: entryOrderId }, + }; + } + + // 5. 写入明细绑定到 InboundDirectLog + await ctx.model.InboundDirectLog.create({ + warehouse_id: entryOrder.warehouse_id, + store_id: entryOrder.store_id, + stock_id: expectedSpId || 0, + quantity: qty, + inbound_type: 'import', + entry_order_id: entryOrderId, + entry_order_code: entryOrder.entry_order_code, + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + status: 'committed', + creator_id: ctx.currentUser?.id || 0, + operator_id: ctx.currentUser?.employees_id || ctx.currentUser?.id || null, + operator_name: ctx.currentUser?.employees_name || '', + }, { transaction }); + + // 6. 确保主级绑定存在(新链路台账初始化为空对象)。 + // 三态幂等:findOrCreate 默认排除软删除行,解绑后再分配会撞唯一索引, + // 这里改为 paranoid:false 查询 + 恢复软删除行 + 新建(唯一索引冲突视为并发已建立)。 + const receivingId = Number(lockedDetail[0].receiving_id); + const existingBinding = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: entryOrderId, receiving_id: receivingId }, + paranoid: false, + transaction, + }); + + if (existingBinding) { + if (existingBinding.deletedAt || existingBinding.deleted_at) { + existingBinding.allocated_quantity = {}; + await existingBinding.restore({ transaction }); + ctx.logger.info( + `[ReceivingEntryMatch] 恢复已解绑的主表绑定(PDA 分配) entryOrderId=${entryOrderId} ` + + `receivingId=${receivingId}` + ); + } + } else { + try { + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receivingId, + allocated_quantity: {}, + }, { transaction }); + } catch (createError) { + if (createError.name !== 'SequelizeUniqueConstraintError') { + throw createError; + } + ctx.logger.warn( + `[ReceivingEntryMatch] 主表绑定已存在(并发写入) entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + } + } + + // 7. 回写数量台账:本批次对该收货明细的分配量累加到绑定行 + const ledgerDeltaMap = new Map(); + ledgerDeltaMap.set(Number(receivingDetailId), { + receivingId: Number(lockedDetail[0].receiving_id), + quantity: Number(qty), + }); + await this.recordLedgerAllocation({ + entryOrderId, + detailDeltaMap: ledgerDeltaMap, + transaction, + }); + } + + /** + * 解除入库单与收货单的绑定关系。 + * + * 逻辑: + * 1. 校验入库单存在,状态必须是 PENDING 或 CREATED(COMPLETED / CANCELLED 不允许解绑) + * 2. 逐个收货单: + * a. 查 wms_entry_order_receiving 主表绑定是否存在(只查 deleted_at IS NULL) + * b. 查 wms_entry_receiving_binding 明细绑定是否存在(status='committed' 且 deleted_at IS NULL) + * c. 无明细绑定 → 只软删除主表绑定 + * d. 有明细绑定 → 事务中软删除明细绑定 + 软删除主表绑定 + * 3. 不回退入库单状态(PENDING 解绑后仍是 PENDING) + * + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 要解除绑定的收货单 ID 列表 + * @return {Promise} { success: Array, failed: Array, success_count: number, failed_count: number } + */ + async unbindEntryOrderReceiving(data = {}) { + const { ctx } = this; + const { entry_order_id: entryOrderId, receiving_ids: receivingIds } = data || {}; + + // 参数校验 + if (!entryOrderId) { + throw new Error('entry_order_id 不能为空'); + } + if (!Array.isArray(receivingIds) || receivingIds.length === 0) { + throw new Error('receiving_ids 不能为空且必须为数组'); + } + + // ---------- 第1步:校验入库单存在且状态允许解绑 ---------- + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); + if (!entryOrder) { + return { + success: [], + failed: receivingIds.map(rid => ({ + receiving_id: rid, + error_code: 'ENTRY_ORDER_NOT_FOUND', + message: '入库单不存在', + })), + success_count: 0, + failed_count: receivingIds.length, + }; + } + + // 只允许 PENDING 或 CREATED 状态解绑(COMPLETED / CANCELLED 不允许) + if (![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) { + return { + success: [], + failed: receivingIds.map(rid => ({ + receiving_id: rid, + error_code: 'ENTRY_ORDER_STATUS_INVALID', + message: `入库单状态不允许解绑,当前状态: ${entryOrder.order_status}`, + })), + success_count: 0, + failed_count: receivingIds.length, + }; + } + + // ---------- 第2步:逐个收货单处理解绑 ---------- + const success = []; + const failed = []; + + for (const receivingId of receivingIds) { + try { + // 2a. 查主表绑定是否存在 + const mainBinding = await ctx.model.EntryOrderReceiving.findOne({ + where: { + entry_order_id: entryOrderId, + receiving_id: receivingId, + deleted_at: null, + }, + }); + + if (!mainBinding) { + failed.push({ + receiving_id: receivingId, + error_code: 'BINDING_NOT_FOUND', + message: '主表绑定不存在', + }); + continue; + } + + // 2b. 查明细绑定是否存在(从 InboundDirectLog 查 receiving_detail_id 非空的记录) + const detailBindings = await ctx.model.InboundDirectLog.findAll({ + where: { + entry_order_id: entryOrderId, + receiving_detail_id: { [ctx.app.Sequelize.Op.ne]: null }, + status: 'committed', + deleted_at: null, + }, + include: [{ + model: ctx.model.ReceivingDetail, + as: 'receivingDetail', + required: true, + attributes: [], + where: { receiving_id: receivingId }, + }], + attributes: [ 'id', 'receiving_detail_id', 'quantity' ], + }); + + // 2c/2d. 事务内:回滚收货侧占用(台账)+ 重算 storage_status + 软删除绑定(含明细绑定) + const rollbackResult = await ctx.model.transaction(async t => { + // 行锁入库单主行,串行化与绑定分配/其他解绑的并发 + await ctx.model.EntryOrder.findByPk(entryOrderId, { + attributes: [ 'id' ], + lock: t.LOCK.UPDATE, + transaction: t, + }); + + // 事务内重查绑定行并加锁,防止并发绑定/解绑 + const lockedBinding = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: entryOrderId, receiving_id: receivingId, deleted_at: null }, + lock: t.LOCK.UPDATE, + transaction: t, + }); + if (!lockedBinding) { + const bindErr = new Error('主表绑定不存在或已被解绑'); + bindErr.error_code = 'BINDING_NOT_FOUND'; + throw bindErr; + } + + const rollback = await this._rollbackOneBindingStorage({ + binding: lockedBinding, + entryOrderId, + transaction: t, + softDelete: true, + }); + + // 软删除所有明细绑定(InboundDirectLog) + for (const binding of detailBindings) { + await binding.destroy({ transaction: t }); + } + + return rollback; + }); + + const detailIds = detailBindings.map(d => d.receiving_detail_id); + const rolledBackQty = rollbackResult ? rollbackResult.rolled_back_quantity : 0; + + ctx.logger.info( + `[ReceivingEntryMatch] 解绑成功 entryOrderId=${entryOrderId} receivingId=${receivingId} ` + + `releasedDetailCount=${detailBindings.length} rolledBackQty=${rolledBackQty} ` + + `detailIds=[${detailIds.join(',')}]` + ); + + success.push({ + receiving_id: receivingId, + released_detail_ids: detailIds, + released_detail_count: detailBindings.length, + rolled_back_quantity: rolledBackQty, + message: '已解除绑定并回滚收货单入库进度', + }); + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 解绑异常 entryOrderId=${entryOrderId} ` + + `receivingId=${receivingId}: ${error.message}`, + error.stack + ); + failed.push({ + receiving_id: receivingId, + error_code: error && error.error_code ? error.error_code : 'UNBIND_ERROR', + message: `解绑过程异常: ${error.message}`, + }); + } + } + + return { success, failed, success_count: success.length, failed_count: failed.length }; + } + + +} + +module.exports = ReceivingEntryMatchService; diff --git a/app/service/systems/receiving_pending_notice.js b/app/service/systems/receiving_pending_notice.js new file mode 100644 index 0000000..9e1b30e --- /dev/null +++ b/app/service/systems/receiving_pending_notice.js @@ -0,0 +1,930 @@ +'use strict'; + +const MainService = require('../main'); + +/** 通知事件码(需与 notice 固定订阅、notification_webhook 事件注册保持一致) */ +const NOTICE_EVENT = 'receiving_pending_inbound'; +/** 默认提醒时间(HH:mm) */ +const DEFAULT_NOTICE_TIME = '08:30'; +/** 默认超时下限(小时):创建时间距今超过该值才提醒 */ +const DEFAULT_MIN_HOURS = 24; +/** 默认超时上限(小时):创建时间距今超过该值不再提醒 */ +const DEFAULT_MAX_HOURS = 48; +/** 提醒时间命中宽限(分钟):覆盖 5 分钟调度间隔的抖动,配合当日锁保证一天只提醒一次 */ +const DEFAULT_GRACE_MINUTES = 10; +/** 单条通知最多列出的收货单行数(超出只提示剩余数量,避免消息过长) */ +const MAX_NOTICE_ITEMS = 20; +/** 当日执行锁 key 前缀 */ +const DAILY_LOCK_KEY_PREFIX = 'receiving_pending_notice:lock:'; +/** 当日执行锁 TTL(秒) */ +const DAILY_LOCK_TTL_SECONDS = 24 * 60 * 60; +/** 单小时毫秒数 */ +const HOUR_MS = 60 * 60 * 1000; +/** 通知短语最大长度(与仓库设置校验保持一致) */ +const NOTICE_TEMPLATE_MAX_LENGTH = 500; +/** 默认通知短语(仓库/客服群):短语 + 换行 + 明细(一行一条) */ +const DEFAULT_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:'; +/** 默认通知短语(货主群) */ +const DEFAULT_STORE_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:'; +const TIME_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/; +const TEMPLATE_VARIABLE_PATTERN = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g; + +const RECEIVING_STATUS_LABEL = Object.freeze({ + receiving: '收货中', + completed: '收货完成', + cancelled: '已作废', +}); +const STORAGE_STATUS_LABEL = Object.freeze({ + none: '未入库', + waiting: '待入库', + partial: '部分入库', + all: '已全部入库', +}); + +/** + * 两位补零。 + * @param {number} value 数值 + * @return {string} 补零后的字符串 + */ +function pad2(value) { + return String(value).padStart(2, '0'); +} + +/** + * 生成本地日期键,格式为 `YYYYMMDD`。 + * @param {Date} dateValue 日期对象 + * @return {string} 日期键 + */ +function buildDateKey(dateValue) { + return `${dateValue.getFullYear()}${pad2(dateValue.getMonth() + 1)}${pad2(dateValue.getDate())}`; +} + +/** + * 将 `HH:mm` 转为当日分钟数。 + * @param {string} timeText `HH:mm` 文本 + * @return {number} 分钟数,格式非法返回 -1 + */ +function toMinutes(timeText) { + if (!TIME_PATTERN.test(String(timeText || ''))) { + return -1; + } + + const [ hour, minute ] = String(timeText).split(':'); + return Number(hour) * 60 + Number(minute); +} + +/** + * 规范化正整数,非法或空值回退默认值。 + * @param {*} value 原始值 + * @param {number} fallback 兜底值 + * @return {number} 正整数 + */ +function toPositiveInteger(value, fallback) { + const numberValue = Number(value); + if (!Number.isInteger(numberValue) || numberValue <= 0) { + return fallback; + } + + return numberValue; +} + +/** + * 规范化通知短语:空值回退默认短语,超长截断。 + * @param {*} value 原始短语 + * @param {string} fallback 默认短语 + * @return {string} 规范化后的短语 + */ +function normalizeTemplateText(value, fallback) { + const text = String(value === undefined || value === null ? '' : value).trim(); + if (!text) { + return fallback; + } + + return text.length > NOTICE_TEMPLATE_MAX_LENGTH ? text.slice(0, NOTICE_TEMPLATE_MAX_LENGTH) : text; +} + +/** + * 渲染通知短语:替换支持的变量({warehouse}/{store}/{count}/...),未识别的占位符原样保留。 + * @param {string} template 短语模板 + * @param {Object} variables 变量键值对(键为小写变量名) + * @return {string} 渲染后的短语 + */ +function renderNoticeTemplate(template, variables) { + const source = String(template || ''); + if (!source) { + return ''; + } + + const values = variables && typeof variables === 'object' ? variables : {}; + + return source.replace(TEMPLATE_VARIABLE_PATTERN, (match, name) => { + const key = String(name || '').toLowerCase(); + if (!Object.prototype.hasOwnProperty.call(values, key)) { + return match; + } + + const value = values[key]; + return value === undefined || value === null ? '' : String(value); + }); +} + +/** + * 规范化「收货未入库提醒」配置(读取路径不抛错,非法值回退默认)。 + * @param {Object|string|null} rawConfig 原始配置 + * @return {Object} 规范化配置 + */ +function normalizeNoticeConfig(rawConfig) { + let parsed = rawConfig; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + parsed = null; + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + parsed = {}; + } + + const noticeTime = TIME_PATTERN.test(String(parsed.notice_time || '').trim()) + ? String(parsed.notice_time).trim() + : DEFAULT_NOTICE_TIME; + const minHours = toPositiveInteger(parsed.min_hours, DEFAULT_MIN_HOURS); + const rawMaxHours = toPositiveInteger(parsed.max_hours, DEFAULT_MAX_HOURS); + const maxHours = rawMaxHours > minHours ? rawMaxHours : Math.max(DEFAULT_MAX_HOURS, minHours + 1); + + return { + enabled: parsed.enabled === true || parsed.enabled === 1 || parsed.enabled === '1', + noticeTime, + minHours, + maxHours, + noticeTemplate: normalizeTemplateText(parsed.notice_template, DEFAULT_NOTICE_TEMPLATE), + storeNoticeTemplate: normalizeTemplateText(parsed.store_notice_template, DEFAULT_STORE_NOTICE_TEMPLATE), + }; +} + +/** + * 从仓库 subject_config 中读取「收货未入库提醒」配置(兼容 JSON 字符串与缺失字段)。 + * @param {Object|string|null} rawSubject 原始 subject_config + * @return {Object} 规范化配置 + */ +function readNoticeConfigFromSubject(rawSubject) { + let parsed = rawSubject; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + parsed = null; + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return normalizeNoticeConfig(null); + } + + return normalizeNoticeConfig(parsed.receiving_pending_inbound_notice); +} + +/** + * 判断当前时刻是否命中提醒时间(含宽限窗口,宽限不超过 1 天)。 + * @param {string} noticeTime 提醒时间 `HH:mm` + * @param {Date} now 当前时刻(进程本地时间,与仓库配置口径一致) + * @param {number} graceMinutes 宽限分钟 + * @return {boolean} 是否命中 + */ +function isNoticeTimeHit(noticeTime, now, graceMinutes) { + const targetMinutes = toMinutes(noticeTime); + if (targetMinutes < 0) { + return false; + } + + const grace = Math.max(1, Math.min(24 * 60, Math.floor(Number(graceMinutes) || DEFAULT_GRACE_MINUTES))); + const nowMinutes = now.getHours() * 60 + now.getMinutes(); + const diff = nowMinutes - targetMinutes; + + return (diff >= 0 && diff < grace) || (nowMinutes + 24 * 60 - targetMinutes < grace); +} + +/** + * 格式化时间用于消息展示,优先使用应用内格式化器。 + * @param {Object} ctx Egg 上下文 + * @param {*} value 原始时间值 + * @return {string} `YYYY-MM-DD HH:mm:ss`,非法值返回空串 + */ +function formatDateTime(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(); +} + +/** + * 收货未入库提醒服务。 + * + * 按仓库设置 `subject_config.receiving_pending_inbound_notice` 扫描「创建时间超过 + * min_hours 且不足 max_hours 仍未完成入库」的收货单: + * - 绑定货主:通知货主收货群(未配群回退仓库客服群,由 notice 固定订阅回退链实现); + * - 未绑定货主:直接通知仓库客服群。 + * 通知时间(notice_time)与超时区间(min_hours / max_hours)均可在仓库设置中配置。 + */ +class ReceivingPendingNoticeService extends MainService { + /** + * 获取进程内当日锁集合(挂在 app 上,跨 ctx/service 实例共享)。 + * + * 定时任务每轮都会创建新的 service 实例,实例级 Set 无法阻挡后续轮次再次执行, + * 因此进程内降级锁必须使用 app 级共享集合(仅用于 Redis 命令失败/不可用时的降级场景)。 + * + * @return {Set} 进程内当日锁 key 集合 + */ + getMemoryDailyLocks() { + const { app } = this; + if (!app) { + return new Set(); + } + + if (!(app._receivingPendingDailyLocks instanceof Set)) { + app._receivingPendingDailyLocks = new Set(); + } + return app._receivingPendingDailyLocks; + } + + /** + * 读取全部启用仓库的提醒配置。 + * + * @return {Promise>} 仓库配置列表 + */ + async getWarehouseNoticeConfigs() { + const { ctx } = this; + const storeModel = ctx.model && ctx.model.Store; + if (!storeModel || typeof storeModel.findAll !== 'function') { + ctx.logger.warn('[receiving-pending-notice] Store 模型不可用,跳过扫描'); + return []; + } + + const rows = await storeModel.findAll({ + where: { status: 1, deleted_at: null }, + attributes: [ 'id', 'company_name', 'subject_config' ], + order: [[ 'id', 'ASC' ]], + // 取 raw 行:避免模型 getter 对历史脏配置抛错导致整轮扫描中断,缺失字段由 normalizeNoticeConfig 兜默认值 + raw: true, + }); + + return (Array.isArray(rows) ? rows : []) + .map(row => { + const warehouseId = Number(row.id) || 0; + if (warehouseId <= 0) { + return null; + } + + return { + warehouseId, + warehouseName: String(row.company_name || '').trim(), + config: readNoticeConfigFromSubject(row.subject_config), + }; + }) + .filter(item => item && item.config.enabled); + } + + /** + * 查询指定仓库在超时区间内仍未完成入库的收货单。 + * + * @param {number} warehouseId 仓库 ID + * @param {Object} config 规范化后的提醒配置 + * @param {Date} now 当前时刻 + * @return {Promise>} 收货单列表(raw) + */ + async findPendingReceivings(warehouseId, config, now) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const receivingModel = ctx.model && ctx.model.Receiving; + if (!receivingModel || typeof receivingModel.findAll !== 'function') { + return []; + } + + const nowTime = now.getTime(); + + return await receivingModel.findAll({ + where: { + warehouse_id: warehouseId, + is_deleted: false, + status: { [Op.ne]: 'cancelled' }, + // 超过 min_hours 且不足 max_hours + created_at: { + [Op.gte]: new Date(nowTime - config.maxHours * HOUR_MS), + [Op.lte]: new Date(nowTime - config.minHours * HOUR_MS), + }, + [Op.or]: [ + { status: 'receiving' }, + { storage_status: { [Op.ne]: 'all' } }, + ], + }, + attributes: [ + 'id', 'receiving_number', 'store_id', 'store_name', 'status', 'storage_status', + 'created_at', 'delivery_method', 'total_quantity', 'total_boxes', + ], + order: [[ 'created_at', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + } + + /** + * 按货主分组收货单(未绑定货主归入 storeId=0 组)。 + * + * @param {Array} rows 收货单列表 + * @return {Array<{storeId: number, storeName: string, rows: Array}>} 分组结果 + */ + groupByStore(rows) { + const grouped = new Map(); + + for (const row of Array.isArray(rows) ? rows : []) { + const storeId = Number(row && row.store_id) > 0 ? Number(row.store_id) : 0; + if (!grouped.has(storeId)) { + grouped.set(storeId, { + storeId, + storeName: String(row && row.store_name || '').trim(), + rows: [], + }); + } + + grouped.get(storeId).rows.push(row); + } + + return [ ...grouped.values() ]; + } + + /** + * 构造单行收货单展示文本。 + * + * @param {Object} row 收货单记录 + * @param {number} index 序号 + * @param {Object} ctx Egg 上下文 + * @param {boolean} includeStore 是否展示货主(仓库/客服版展示,货主版不展示) + * @return {string} 展示行 + */ + buildRowLine(row, index, ctx, includeStore) { + const number = String(row.receiving_number || row.id || '').trim(); + const createdText = formatDateTime(ctx, row.created_at); + const statusText = String(row.status || '') === 'receiving' + ? RECEIVING_STATUS_LABEL.receiving + : `${RECEIVING_STATUS_LABEL.completed}·${STORAGE_STATUS_LABEL[row.storage_status] || '未入库'}`; + const quantity = Number(row.total_quantity || 0); + const parts = [ + `${index}.${number}`, + includeStore ? `货主:${String(row.store_name || '').trim() || (Number(row.store_id) > 0 ? `ID${row.store_id}` : '未绑定')}` : '', + includeStore && quantity > 0 ? `数量:${quantity}` : '', + createdText ? `创建时间:${createdText}` : '', + `状态:${statusText}`, + ].filter(Boolean); + + return parts.join(' '); + } + + /** + * 格式化日期(YYYY-MM-DD),优先使用应用内格式化器。 + * + * @param {Object} ctx Egg 上下文 + * @param {*} value 原始时间值 + * @return {string} 日期文本 + */ + formatDateOnly(ctx, value) { + 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, 'YYYY-MM-DD'); + } + + return `${dateValue.getFullYear()}-${pad2(dateValue.getMonth() + 1)}-${pad2(dateValue.getDate())}`; + } + + /** + * 构造通知短语的替换变量(未识别的占位符在渲染时原样保留)。 + * + * 可用变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名(未绑定为「未绑定货主」) + * / {store_id} 货主ID / {count} 本批单数 / {min_hours} / {max_hours} / {date} 提醒日期 + * / {numbers} 本批收货单号(最多 20 个,超出以「等 N 单」结尾)。 + * + * @param {Object} options 变量来源 + * @param {Array} options.rows 收货单列表 + * @param {Object} options.config 规范化后的提醒配置 + * @param {string} options.warehouseName 仓库名称 + * @param {number} options.warehouseId 仓库 ID + * @param {number} options.storeId 货主 ID(0 表示未绑定) + * @param {string} options.storeName 货主名称 + * @param {Date} options.now 当前时刻 + * @param {Object} options.ctx Egg 上下文 + * @return {Object} 变量键值对 + */ + buildTemplateVariables({ rows, config, warehouseName, warehouseId, storeId, storeName, now, ctx }) { + const list = Array.isArray(rows) ? rows : []; + const hasStore = Number(storeId) > 0; + const numbers = list + .slice(0, MAX_NOTICE_ITEMS) + .map(row => String(row && (row.receiving_number || row.id) || '').trim()) + .filter(Boolean); + + return { + warehouse: String(warehouseName || '').trim() || `仓库${warehouseId}`, + warehouse_id: String(warehouseId), + store: hasStore ? (String(storeName || '').trim() || `货主${storeId}`) : '未绑定货主', + store_id: hasStore ? String(storeId) : '0', + count: String(list.length), + min_hours: String(config.minHours), + max_hours: String(config.maxHours), + date: this.formatDateOnly(ctx, now), + numbers: numbers.length > 0 + ? `${numbers.join('、')}${list.length > numbers.length ? ` 等 ${list.length} 单` : ''}` + : '', + }; + } + + /** + * 构造消息正文:短语(模板变量替换)+ 换行 + 明细(一行一条)+ 查看链接。 + * + * 短语来自仓库设置(notice_template 仓库/客服群版、store_notice_template 货主群版), + * 为空时回退默认短语。 + * + * @param {Object} options 构造参数 + * @param {Array} options.rows 收货单列表 + * @param {Object} options.config 规范化后的提醒配置 + * @param {string} options.warehouseName 仓库名称 + * @param {number} options.warehouseId 仓库 ID + * @param {number} options.storeId 货主 ID(0 表示未绑定) + * @param {string} options.storeName 货主名称 + * @param {boolean} options.forStore 是否货主版文案 + * @param {string} options.viewUrl 查看链接 + * @param {Date} options.now 当前时刻 + * @param {Object} options.ctx Egg 上下文 + * @return {string} 消息正文 + */ + buildContent({ rows, config, warehouseName, warehouseId, storeId, storeName, forStore, viewUrl, now, ctx }) { + const list = Array.isArray(rows) ? rows : []; + const template = forStore ? config.storeNoticeTemplate : config.noticeTemplate; + const phrase = renderNoticeTemplate(template, this.buildTemplateVariables({ + rows: list, + config, + warehouseName, + warehouseId, + storeId, + storeName, + now, + ctx, + })); + const lines = [ phrase ]; + + list.slice(0, MAX_NOTICE_ITEMS).forEach((row, index) => { + lines.push(this.buildRowLine(row, index + 1, ctx, !forStore)); + }); + + if (list.length > MAX_NOTICE_ITEMS) { + lines.push(`…… 其余 ${list.length - MAX_NOTICE_ITEMS} 单未列出`); + } + + lines.push(`${forStore ? '详情查看' : '快速查看'}:${viewUrl}`); + + return lines.join('\n'); + } + + /** + * 解析通知发送方法,优先 `send`,其次兼容 `index.send`。 + * + * @return {Function|null} 可执行的发送方法 + */ + resolveNoticeSendMethod() { + const { ctx } = this; + 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; + } + + /** + * 发送单个货主批次(或未绑定货主批次)的未入库提醒。 + * + * 货主批次主推其收货群;主推失败(含异常)时自动回退到仓库客服群 + * (见 sendCustomerServiceFallback),保证个别群发送失败不影响其他货主群的通知。 + * + * @param {Object} options 发送参数 + * @param {number} options.warehouseId 仓库 ID + * @param {string} options.warehouseName 仓库名称 + * @param {number} options.storeId 货主 ID,0 表示未绑定货主 + * @param {string} options.storeName 货主名称 + * @param {Array} options.rows 该货主的收货单列表 + * @param {Object} options.config 规范化后的提醒配置 + * @param {Date} options.now 当前时刻 + * @return {Promise} 通知结果(主推结果 + 可选 fallback 回退结果) + */ + async sendPendingNotice({ warehouseId, warehouseName, storeId, storeName, rows, config, now }) { + const { ctx, app } = this; + const sendMethod = this.resolveNoticeSendMethod(); + const hasStore = Number(storeId) > 0; + if (typeof sendMethod !== 'function') { + ctx.logger.warn('[receiving-pending-notice] 通知服务不可用,跳过发送'); + return null; + } + + const warehouseFrontendUrl = String(app.config.frontendUrl || '').trim(); + const storeFrontendUrl = String(app.config.storeFrontendUrl || app.config.frontendUrl || '').trim(); + const content = this.buildContent({ + rows, + config, + warehouseName, + warehouseId, + storeId, + storeName, + forStore: false, + viewUrl: `${warehouseFrontendUrl}/storage/receiving`, + now, + ctx, + }); + const storeContent = hasStore + ? this.buildContent({ + rows, + config, + warehouseName, + warehouseId, + storeId, + storeName, + forStore: true, + viewUrl: `${storeFrontendUrl}/storage/receiving_owner`, + now, + ctx, + }) + : undefined; + + // 主推发送:单批次异常只影响本批次(记录失败并尝试回退),不向上抛出中断其他货主群 + let sendResult = null; + try { + sendResult = await sendMethod({ + warehouseId, + // 未绑定货主时不带 storeId,由 notice 固定订阅回退到仓库客服群 + storeId: hasStore ? Number(storeId) : undefined, + messageType: 'text', + businessName: 'receiving', + event: NOTICE_EVENT, + channel: 'warehouse', + title: `收货未入库提醒(${rows.length} 单)`, + content, + ...(storeContent ? { storeContent } : {}), + // 幂等键:同仓库+同货主+同一天只落一条消息记录 + businessId: `receiving-pending:${warehouseId}:${hasStore ? Number(storeId) : 0}:${buildDateKey(now)}`, + subject: { + id: warehouseId, + type: 'warehouse', + name: warehouseName, + }, + sender: { + id: null, + name: '系统提醒', + }, + metadata: { + warehouseId, + warehouseName, + storeId: hasStore ? Number(storeId) : null, + storeName: String(storeName || '').trim(), + minHours: config.minHours, + maxHours: config.maxHours, + receivingIds: rows.map(row => Number(row.id)).filter(id => id > 0), + receivingNumbers: rows.map(row => String(row.receiving_number || '')).filter(Boolean), + }, + }); + } catch (error) { + ctx.logger.error(`[receiving-pending-notice] 仓库 ${warehouseId} 货主 ${storeId} 批次发送异常: ${error.message}`); + sendResult = { success: false, message: `发送异常: ${error.message}` }; + } + + // 货主收货群主推失败(含异常)时回退仓库客服群,保证部分群失败不遗漏人工跟进 + let fallbackResult = null; + if (hasStore && (!sendResult || sendResult.success !== true)) { + fallbackResult = await this.sendCustomerServiceFallback({ + warehouseId, + warehouseName, + storeId, + storeName, + rows, + config, + now, + }); + } + + return { + ...(sendResult || { success: false, message: '通知发送无结果' }), + ...(fallbackResult ? { fallback: fallbackResult } : {}), + }; + } + + /** + * 货主收货群主推失败时,回退通知仓库客服群人工跟进。 + * + * 复用 notice 固定订阅回退链:不带 storeId 时 receiving_pending_inbound 的 + * store:receiving 目标被跳过,fallbackTargets 命中 warehouse:customer_service。 + * 幂等键使用独立前缀(receiving-pending-fallback),与主推送、其他货主的回退互不干扰。 + * + * @param {Object} options 回退参数 + * @param {number} options.warehouseId 仓库 ID + * @param {string} options.warehouseName 仓库名称 + * @param {number} options.storeId 货主 ID + * @param {string} options.storeName 货主名称 + * @param {Array} options.rows 该货主的收货单列表 + * @param {Object} options.config 规范化后的提醒配置 + * @param {Date} options.now 当前时刻 + * @return {Promise} 回退通知结果(通知服务不可用时返回 null) + */ + async sendCustomerServiceFallback({ warehouseId, warehouseName, storeId, storeName, rows, config, now }) { + const { ctx, app } = this; + const sendMethod = this.resolveNoticeSendMethod(); + if (typeof sendMethod !== 'function') { + return null; + } + + const storeLabel = String(storeName || '').trim() || `货主${storeId}`; + const warehouseFrontendUrl = String(app.config.frontendUrl || '').trim(); + const content = this.buildContent({ + rows, + config, + warehouseName, + warehouseId, + storeId, + storeName, + forStore: false, + viewUrl: `${warehouseFrontendUrl}/storage/receiving`, + now, + ctx, + }); + + try { + return await sendMethod({ + warehouseId, + // 不带 storeId:固定订阅 store:receiving 被跳过,回退链命中仓库客服群 + storeId: undefined, + messageType: 'text', + businessName: 'receiving', + event: NOTICE_EVENT, + channel: 'warehouse', + title: `收货未入库提醒·货主群发送失败(${storeLabel})`, + content: `通知货主【${storeLabel}】收货群推送失败,请人工跟进:\n${content}`, + // 回退幂等键独立于主推送:同一货主同日只回退一条,且互不影响 + businessId: `receiving-pending-fallback:${warehouseId}:${Number(storeId)}:${buildDateKey(now)}`, + subject: { + id: warehouseId, + type: 'warehouse', + name: warehouseName, + }, + sender: { + id: null, + name: '系统提醒', + }, + metadata: { + warehouseId, + warehouseName, + storeId: Number(storeId), + storeName: storeLabel, + fallbackReason: '货主收货群推送失败回退', + receivingIds: rows.map(row => Number(row.id)).filter(id => id > 0), + receivingNumbers: rows.map(row => String(row.receiving_number || '')).filter(Boolean), + }, + }); + } catch (error) { + ctx.logger.error(`[receiving-pending-notice] 仓库 ${warehouseId} 货主 ${storeId} 回退客服群发送异常: ${error.message}`); + return { success: false, message: `回退发送异常: ${error.message}` }; + } + } + + /** + * 扫描并通知单个仓库的超时未入库收货单。 + * + * 各货主群独立发送:单个批次异常/失败只影响该批次(失败自动回退客服群), + * 不中断后续货主群的遍历与通知。 + * + * @param {Object} options 执行参数 + * @param {number} options.warehouseId 仓库 ID + * @param {string} options.warehouseName 仓库名称 + * @param {Object} options.config 规范化后的提醒配置 + * @param {Date} options.now 当前时刻 + * @return {Promise} 执行汇总 + */ + async notifyWarehouse({ warehouseId, warehouseName, config, now }) { + const { ctx } = this; + const rows = await this.findPendingReceivings(warehouseId, config, now); + const summary = { + warehouseId, + warehouseName, + pendingCount: rows.length, + groupCount: 0, + sentCount: 0, + failedCount: 0, + fallbackCount: 0, + }; + + if (rows.length === 0) { + ctx.logger.info(`[receiving-pending-notice] 仓库 ${warehouseId} 无超时未入库收货单`); + return summary; + } + + const groups = this.groupByStore(rows); + for (const group of groups) { + summary.groupCount += 1; + + let result = null; + try { + result = await this.sendPendingNotice({ + warehouseId, + warehouseName, + storeId: group.storeId, + storeName: group.storeName, + rows: group.rows, + config, + now, + }); + } catch (error) { + // 单个货主批次异常不允许中断整仓遍历:该批次计入失败,继续通知其他货主群 + ctx.logger.error( + `[receiving-pending-notice] 仓库 ${warehouseId} 货主 ${group.storeId} 批次异常,` + + `跳过并继续后续货主: ${error.message}` + ); + summary.failedCount += 1; + continue; + } + + if (result && result.success) { + summary.sentCount += 1; + } else { + summary.failedCount += 1; + } + + if (result && result.fallback && result.fallback.success) { + summary.fallbackCount += 1; + ctx.logger.warn( + `[receiving-pending-notice] 仓库 ${warehouseId} 货主 ${group.storeId} 收货群发送失败,已回退仓库客服群人工跟进` + ); + } + } + + ctx.logger.info( + `[receiving-pending-notice] 仓库 ${warehouseId} 提醒完成:未入库 ${summary.pendingCount} 单,` + + `通知 ${summary.groupCount} 个批次,成功 ${summary.sentCount},失败 ${summary.failedCount}` + ); + + return summary; + } + + /** + * 获取 Redis 缓存客户端。 + * + * @return {Object|null} Redis 客户端或 null + */ + getRedisClient() { + const { app } = this; + try { + return app && app.redis && typeof app.redis.get === 'function' ? app.redis.get('cache') : null; + } catch (error) { + return null; + } + } + + /** + * 申请当日执行锁(Redis SET NX;Redis 命令失败/不可用时降级为 app 级进程内集合)。 + * + * SET NX 语义:返回 'OK' 表示抢锁成功;返回 null 表示键已存在(当日锁已被本进程或 + * 其他实例持有),必须直接判定为「未抢到锁」,不能落入进程内兜底——兜底仅用于 Redis + * 不可用的场景,否则每轮调度都会重新获得锁,导致宽限窗口内重复发送。 + * + * @param {string} lockKey 锁 key + * @return {Promise} 是否申请成功 + */ + async acquireDailyLock(lockKey) { + const { ctx } = this; + const redisClient = this.getRedisClient(); + + if (redisClient && typeof redisClient.set === 'function') { + try { + const result = await redisClient.set(lockKey, '1', 'EX', DAILY_LOCK_TTL_SECONDS, 'NX'); + if (result === 'OK') { + return true; + } + // null(键已存在)及其他异常返回值一律视为未抢到锁,禁止落入进程内兜底 + return false; + } catch (error) { + ctx.logger.warn(`[receiving-pending-notice] 当日锁申请失败,降级进程内锁: ${error.message}`); + } + } + + const memoryLocks = this.getMemoryDailyLocks(); + if (memoryLocks.has(lockKey)) { + return false; + } + + memoryLocks.add(lockKey); + return true; + } + + /** + * 释放当日执行锁(发送异常时释放,允许宽限窗口内下一轮重试)。 + * + * @param {string} lockKey 锁 key + * @return {Promise} 无返回值 + */ + async releaseDailyLock(lockKey) { + const { ctx } = this; + this.getMemoryDailyLocks().delete(lockKey); + + const redisClient = this.getRedisClient(); + if (redisClient && typeof redisClient.del === 'function') { + try { + await redisClient.del(lockKey); + } catch (error) { + ctx.logger.warn(`[receiving-pending-notice] 当日锁释放失败: ${error.message}`); + } + } + } + + /** + * 执行一轮收货未入库提醒(供定时任务调用)。 + * + * 命中条件:仓库开启提醒 + 当前时刻落在 notice_time 宽限窗口内 + 当日未执行过。 + * + * @param {Object|null} options 执行参数 + * @param {Date} [options.now] 指定当前时刻(测试用) + * @param {number} [options.graceMinutes] 提醒时间宽限分钟(测试用) + * @return {Promise} 执行汇总 + */ + async execute(options = null) { + const { ctx } = this; + const params = options || {}; + const now = params.now instanceof Date ? params.now : new Date(); + const graceMinutes = Number.isFinite(Number(params.graceMinutes)) && Number(params.graceMinutes) > 0 + ? Number(params.graceMinutes) + : DEFAULT_GRACE_MINUTES; + + const enabledConfigs = await this.getWarehouseNoticeConfigs(); + const dateKey = buildDateKey(now); + const summary = { + checkedWarehouseCount: enabledConfigs.length, + executedWarehouseCount: 0, + pendingCount: 0, + sentCount: 0, + failedCount: 0, + fallbackCount: 0, + results: [], + }; + + for (const item of enabledConfigs) { + if (!isNoticeTimeHit(item.config.noticeTime, now, graceMinutes)) { + continue; + } + + const lockKey = `${DAILY_LOCK_KEY_PREFIX}${item.warehouseId}:${dateKey}`; + const acquired = await this.acquireDailyLock(lockKey); + if (!acquired) { + continue; + } + + try { + const result = await this.notifyWarehouse({ + warehouseId: item.warehouseId, + warehouseName: item.warehouseName, + config: item.config, + now, + }); + summary.executedWarehouseCount += 1; + summary.pendingCount += result.pendingCount; + summary.sentCount += result.sentCount; + summary.failedCount += result.failedCount; + summary.fallbackCount += result.fallbackCount || 0; + summary.results.push(result); + } catch (error) { + // 执行失败释放锁,宽限窗口内的下一轮仍可重试 + await this.releaseDailyLock(lockKey); + summary.failedCount += 1; + ctx.logger.error(`[receiving-pending-notice] 仓库 ${item.warehouseId} 提醒执行失败: ${error.message}`); + } + } + + return summary; + } +} + +module.exports = ReceivingPendingNoticeService; diff --git a/app/service/systems/report.js b/app/service/systems/report.js new file mode 100644 index 0000000..12f457d --- /dev/null +++ b/app/service/systems/report.js @@ -0,0 +1,610 @@ +'use strict'; + +const { Service } = require('egg'); +const { renderSheetByType } = require('../../lib/report/render'); +const { scheduleDateOf } = require('../../lib/report/day_window'); +const QUERIES = require('./report/queries'); + +/** + * 配置驱动通用报表引擎(systems 层)。 + * + * 链路:wms_report_definition(配置:type/file_name/fields) → 内置查询器(QUERIES 注册表) + * → render.js(按类型硬编码字段规格渲染) → excel.generateAndUpload / generateBuffer(产物)。 + * 本服务仅做编排与出口包装,具体口径由查询器实现并注释假设; + * 定义唯一性由 id(主键)承担,plan/log 均按 report_definition_id 关联。 + */ +class ReportService extends Service { + /** + * 按 ID 读取启用的报表定义(is_enabled=1,软删自动排除)。 + * @param {number|string} id 报表定义ID(正整数) + * @return {Promise} 报表定义视图(fields 已解析为字符串数组) + * @throws {Error} ID 非法、模型不可用或定义不存在/停用时抛出 + */ + async getDefinition(id) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDefinition; + if (!model || typeof model.findOne !== 'function') { + throw new Error('报表定义模型 ReportDefinition 不可用'); + } + const normalizedId = Number(id) || 0; + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + throw new Error('报表ID report_id 必须为正整数'); + } + const row = await model.findOne({ + where: { + id: normalizedId, + is_enabled: 1, + }, + raw: true, + }); + if (!row) { + throw new Error(`报表定义不存在或已停用: id=${normalizedId}`); + } + return this.definitionToView(row); + } + + /** + * 解析 fields 字段:数组原样返回、JSON 字符串解析,其余按空数组兜底(元素统一为字符串)。 + * @param {*} value 字段原始值 + * @return {Array} 字段 key 数组 + */ + parseFieldsField(value) { + let list = value; + if (typeof value === 'string' && value.trim()) { + try { + list = JSON.parse(value); + } catch (error) { + this.ctx.logger.warn(`[report] 报表定义 fields JSON 解析失败: ${error.message}`); + return []; + } + } + if (!Array.isArray(list)) { + return []; + } + return list + .map(item => String(item || '').trim()) + .filter(Boolean); + } + + /** + * 报表定义记录转视图对象(fields 统一解析为字符串数组,时间字段透传)。 + * @param {Object} row 报表定义记录(实例或 raw) + * @return {Object|null} 视图对象(记录为空时返回 null) + */ + definitionToView(row) { + if (!row) { + return null; + } + return { + id: Number(row.id) || 0, + name: String(row.name || ''), + type: String(row.type || ''), + file_name: String(row.file_name || ''), + fields: this.parseFieldsField(row.fields), + is_enabled: Number(row.is_enabled ?? 1), + remark: String(row.remark || ''), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + }; + } + + /** + * 读取注册表描述条目(未知类型抛可读错误)。 + * @param {string} type 报表类型(注册方法 key) + * @return {{key: string, title: string, description: string, window: Object, fields: Array}} 描述条目 + * @throws {Error} 类型未注册时抛出 + */ + resolveTypeEntry(type) { + const normalizedType = String(type || '').trim(); + const entries = typeof QUERIES.describe === 'function' ? QUERIES.describe() : []; + const entry = entries.find(item => item && item.key === normalizedType); + if (!entry) { + throw new Error(`未知的报表类型: ${normalizedType}`); + } + return entry; + } + + /** + * 读取查询器函数(未知类型抛错)。 + * @param {string} type 报表类型(注册方法 key) + * @return {Function} 查询器函数 + */ + resolveQuerier(type) { + const normalizedType = String(type || '').trim(); + const querier = QUERIES[normalizedType]; + if (typeof querier !== 'function') { + throw new Error(`未知的报表类型: ${normalizedType}`); + } + return querier; + } + + /** + * 输出注册表全量清单(供 method 层 report.definition.typeList 复用)。 + * @return {Array<{key: string, title: string, description: string, window: Object, fields: Array}>} 注册清单 + */ + listRegisteredTypes() { + return typeof QUERIES.describe === 'function' ? QUERIES.describe() : []; + } + + /** + * 校验勾选字段均为该类型注册字段的子集(顶层字段 key),非法 key 列出可读错误。 + * @param {string} type 报表类型(注册方法 key) + * @param {Array} fields 勾选字段 key 数组 + * @return {Array} 去重后的合法字段 key 数组(保持传入顺序) + * @throws {Error} 含非法字段 key 时抛出 + */ + validateTypeFields(type, fields) { + const entry = this.resolveTypeEntry(type); + const registeredKeys = new Set((Array.isArray(entry.fields) ? entry.fields : []).map(field => field && field.key)); + const safeFields = Array.isArray(fields) ? fields : []; + const seen = new Set(); + const normalized = []; + const illegal = []; + for (const item of safeFields) { + const key = String(item || '').trim(); + if (!key) { + continue; + } + if (!registeredKeys.has(key)) { + if (!illegal.includes(key)) { + illegal.push(key); + } + continue; + } + if (!seen.has(key)) { + seen.add(key); + normalized.push(key); + } + } + if (illegal.length > 0) { + throw new Error( + `fields 含非法字段: ${illegal.join(', ')}` + + `(报表类型 ${type} 可用字段: ${[ ...registeredKeys ].join(', ') || '-'})` + ); + } + return normalized; + } + + /** + * 按字段 key 顺序解析注册字段规格(用于渲染列顺序)。 + * @param {Object} entry 注册表描述条目 + * @param {Array} fields 勾选字段 key 数组 + * @return {Array} 按勾选顺序排列的字段规格清单 + */ + resolveOrderedFields(entry, fields) { + const entryFields = Array.isArray(entry.fields) ? entry.fields : []; + const fieldMap = new Map(entryFields.map(field => [ field && field.key, field ])); + const safeFields = Array.isArray(fields) ? fields : []; + return safeFields + .map(key => fieldMap.get(key)) + .filter(Boolean); + } + + /** + * 构建导出文件名(支持 file_name 模板占位符)。 + * + * 占位符(2026-09-10 扩充,均为本地时区): + * - `{date}`:数据日期(请求 params.bizDate,缺省服务器当天,`YYYY-MM-DD`)——语义不变; + * - `{time}`:生成时刻 `HHmmss`(如 `200745`); + * - `{datetime}`:`{date}_{time}`(如 `2026-09-09_200745`); + * - `{timestamp}`:生成时刻毫秒时间戳(如 `1789136465123`)。 + * + * 用途:同一天多次投递/手动导出同一报表时,文件名带生成时刻可避免 COS 同名覆盖 + *(同名文件会被后一次写覆盖,且 CDN 可能继续回源旧内容)。 + * + * @param {Object} definition 报表定义视图 + * @param {string} [bizDate=''] 数据日期(YYYY-MM-DD,缺省用今天) + * @param {Date} [now=new Date()] 生成时刻(渲染 {time}/{datetime}/{timestamp} 用,可注入供测试) + * @return {string} 文件名 + */ + buildFilename(definition, bizDate = '', now = new Date()) { + const nowDate = now instanceof Date && !Number.isNaN(now.getTime()) ? now : new Date(); + const dateText = String(bizDate || '').trim() || scheduleDateOf(nowDate); + const timeText = `${String(nowDate.getHours()).padStart(2, '0')}` + + `${String(nowDate.getMinutes()).padStart(2, '0')}` + + `${String(nowDate.getSeconds()).padStart(2, '0')}`; + const template = String((definition && definition.file_name) || '').trim() + || `${String((definition && definition.name) || 'report')}_${dateText}.xlsx`; + const filename = template + .replace(/\{datetime\}/g, `${dateText}_${timeText}`) + .replace(/\{date\}/g, dateText) + .replace(/\{time\}/g, timeText) + .replace(/\{timestamp\}/g, String(nowDate.getTime())); + return filename.endsWith('.xlsx') || filename.endsWith('.xls') ? filename : `${filename}.xlsx`; + } + + /** + * 查询数据并翻译为 excel.js 的 sheets 参数(generate/generateBuffer 共用)。 + * @param {Object} options 入参 + * @param {number|string} options.reportId 报表定义ID + * @param {number|null} [options.storeId] 货主ID + * @param {number|null} [options.warehouseId] 仓库ID + * @param {Object} [options.params] 查询器业务参数(如 bizDate) + * @return {Promise<{sheets: Array, filename: string, queryData: Object}>} 翻译结果 + */ + async buildWorkbookSheets({ reportId, storeId = null, warehouseId = null, params = {} }) { + const definition = await this.getDefinition(reportId); + const entry = this.resolveTypeEntry(definition.type); + const querier = this.resolveQuerier(definition.type); + + const queryData = await querier({ + ctx: this.ctx, + storeId, + warehouseId, + params: params || {}, + }); + + const orderedFields = this.resolveOrderedFields(entry, definition.fields); + const sheet = renderSheetByType({ + type: definition.type, + title: entry.title, + fields: orderedFields, + rows: Array.isArray(queryData.rows) ? queryData.rows : [], + windows: Array.isArray(queryData.windows) ? queryData.windows : [], + }); + + return { + sheets: [ sheet ], + filename: this.buildFilename(definition, params && params.bizDate), + queryData, + }; + } + + /** + * 生成报表 Excel 并上传,返回 fileKey/url(供手动导出与货主投递复用)。 + * 上传目录按(报表定义 + 货主/仓库)隔离,保证不同货主的报表文件互不覆盖。 + * @param {Object} options 入参 + * @param {number|string} options.reportId 报表定义ID + * @param {number|null} [options.storeId] 货主ID(货主维度报表必传,有效时按货主隔离上传目录) + * @param {number|null} [options.warehouseId] 仓库ID(货主维度缺省时按仓库隔离上传目录) + * @param {Object} [options.params] 查询器业务参数(如 bizDate) + * @return {Promise<{fileKey: string, url: string, filename: string, size: number}>} 上传结果 + */ + async generate({ reportId, storeId = null, warehouseId = null, params = {} }) { + const { sheets, filename } = await this.buildWorkbookSheets({ + reportId, + storeId, + warehouseId, + params, + }); + + // 上传目录按(报表定义 + 货主/仓库)隔离:同一报表定义下不同货主不得共用同一文件 key, + // 避免后投递货主的文件覆盖先投递货主的文件(货主限制不符缺陷)。 + // storeId 缺省时退化为仓库维度,未传货主/仓库时按 common 兜底(保持手动导出兼容)。 + const normalizedStoreId = Number(storeId) || 0; + const normalizedWarehouseId = Number(warehouseId) || 0; + const ownerSegment = normalizedStoreId > 0 + ? `store-${normalizedStoreId}` + : (normalizedWarehouseId > 0 ? `warehouse-${normalizedWarehouseId}` : 'common'); + + const uploadResult = await this.ctx.service.systems.excel.generateAndUpload({ + filename, + dir: `exports/report/${String(reportId).trim()}/${ownerSegment}`, + category: 'document', + sheets, + }); + + const fileKey = String(uploadResult.fileKey || uploadResult.fileName || '').trim(); + const url = String( + uploadResult.url + || uploadResult.cdnUrl + || uploadResult.cosUrl + || fileKey + || '' + ).trim(); + + return { + fileKey, + url, + filename: String(uploadResult.filename || filename), + size: Number(uploadResult.size) || 0, + }; + } + + /** + * 生成报表 Excel 缓冲(内部入口,供后续复用/直推下载)。 + * @param {Object} options 入参 + * @param {number|string} options.reportId 报表定义ID + * @param {number|null} [options.storeId] 货主ID + * @param {number|null} [options.warehouseId] 仓库ID + * @param {Object} [options.params] 查询器业务参数(如 bizDate) + * @return {Promise<{buffer: Buffer, filename: string, contentType: string}>} 缓冲结果 + */ + async generateBuffer({ reportId, storeId = null, warehouseId = null, params = {} }) { + const { sheets, filename } = await this.buildWorkbookSheets({ + reportId, + storeId, + warehouseId, + params, + }); + + const buffer = await this.ctx.service.systems.excel.generateBuffer({ + bookType: 'xlsx', + sheets, + }); + + return { + buffer, + filename, + contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }; + } + + /** + * 新增/更新报表定义(按 id upsert;未传 id 视为新增)。 + * 更新语义:未传入的字段(undefined)不覆盖既有值;传入非法值会校验报错。 + * 校验项:name 必填、type 必须为注册表已有类型、file_name 必填(新增时)、 + * fields 必须为该类型注册字段的子集。 + * @param {Object} options 入参 + * @param {number} [options.id] 报表定义ID(正整数;不传视为新增) + * @param {string} options.name 报表名称(必填,≤100) + * @param {string} options.type 报表类型(注册方法 key,如 stockFlow;新增必填) + * @param {string} options.fileName 导出文件名模板(支持 {date};新增必填,≤200) + * @param {Array} options.fields 勾选字段 key 数组(新增必填,须为该类型注册字段子集) + * @param {number} [options.isEnabled] 是否启用(0/1) + * @param {string} [options.remark] 备注(≤500) + * @return {Promise} 保存后的报表定义视图 + * @throws {Error} 参数非法、类型未知或字段非法时抛出业务可读错误 + */ + async saveDefinition({ + id, + name = '', + type, + fileName, + fields, + isEnabled, + remark, + } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDefinition; + if (!model || typeof model.findOne !== 'function') { + throw new Error('报表定义模型 ReportDefinition 不可用'); + } + + const normalizedId = id === undefined || id === null || id === '' + ? null + : Number(id) || 0; + if (normalizedId !== null && (!Number.isInteger(normalizedId) || normalizedId <= 0)) { + throw new Error('报表ID id 必须为正整数'); + } + + const normalizedName = String(name || '').trim(); + if (!normalizedName) { + throw new Error('报表名称 name 不能为空'); + } + if (normalizedName.length > 100) { + throw new Error('报表名称 name 不能超过 100 字符'); + } + + // 软删记录也纳入查找(按 id 主键查重,paranoid: false 支持恢复), + // 并复用既有记录 type 完成 fields 校验(避免重复查库) + const existing = normalizedId !== null + ? await this.findDefinitionById(model, normalizedId) + : null; + if (normalizedId !== null && !existing) { + throw new Error(`报表定义不存在: id=${normalizedId}`); + } + + // 未传 type(undefined)不校验也不覆盖既有值;显式传空/未知类型仍报错 + let normalizedType; + if (type !== undefined) { + normalizedType = String(type || '').trim(); + this.resolveTypeEntry(normalizedType); + } + + // 未传 fields(undefined)不校验;显式传值须为该类型注册字段子集 + let normalizedFields; + if (fields !== undefined) { + if (!Array.isArray(fields)) { + throw new Error('报表字段 fields 必须为数组'); + } + // 校验查询器取本次 type,其次取既有记录 type + const fieldsValidationType = normalizedType !== undefined + ? normalizedType + : (existing && existing.type); + if (!fieldsValidationType) { + throw new Error('报表类型 type 不能为空'); + } + normalizedFields = this.validateTypeFields(fieldsValidationType, fields); + } + + // 未传 fileName(undefined)不覆盖既有值;新增时必填 + let normalizedFileName; + if (fileName !== undefined) { + normalizedFileName = String(fileName || '').trim(); + if (!normalizedFileName) { + throw new Error('导出文件名 file_name 不能为空'); + } + if (normalizedFileName.length > 200) { + throw new Error('导出文件名 file_name 不能超过 200 字符'); + } + } + + if (isEnabled !== undefined) { + const enabledNum = Number(isEnabled); + if (enabledNum !== 0 && enabledNum !== 1) { + throw new Error('is_enabled 仅支持 0/1'); + } + } + + // 新增时必须提供 type/file_name/fields(existing 已在上方按 id 查询一次) + if (!existing) { + if (normalizedType === undefined) { + throw new Error('报表类型 type 不能为空'); + } + if (normalizedFileName === undefined) { + throw new Error('导出文件名 file_name 不能为空'); + } + if (normalizedFields === undefined) { + throw new Error('报表字段 fields 不能为空'); + } + } + + const payload = { + name: normalizedName, + }; + if (normalizedType !== undefined) { + payload.type = normalizedType; + } + if (normalizedFileName !== undefined) { + payload.file_name = normalizedFileName; + } + if (normalizedFields !== undefined) { + payload.fields = normalizedFields; + } + if (isEnabled !== undefined) { + payload.is_enabled = Number(isEnabled) ? 1 : 0; + } + if (remark !== undefined) { + payload.remark = String(remark || '').slice(0, 500); + } + + let saved; + if (existing) { + if (existing.deleted_at) { + // 命中软删记录:恢复后按入参更新 + await existing.restore(); + } + await existing.update(payload); + saved = existing; + } else { + const created = await model.create(payload); + saved = created && created.toJSON ? created.toJSON() : created; + } + + return this.definitionToView(saved); + } + + /** + * 按 ID 查找报表定义(paranoid: false,软删记录也返回,供恢复与校验复用)。 + * @param {Object} model ReportDefinition 模型 + * @param {number|null} id 报表定义ID(null 时直接返回 null) + * @return {Promise} 记录实例(含软删记录),不存在返回 null + */ + async findDefinitionById(model, id) { + if (id === null || Number(id) <= 0) { + return null; + } + return model.findOne({ + where: { id: Number(id) }, + paranoid: false, + }); + } + + /** + * 分页查询报表定义列表(name 模糊、type/is_enabled 精确,sortField 白名单)。 + * @param {Object} [options={}] 入参 + * @param {string} [options.nameKeyword=''] name 模糊关键字 + * @param {string} [options.type=''] 报表类型精确筛选(注册方法 key) + * @param {number|string} [options.isEnabled=null] 启用状态精确筛选(0/1) + * @param {Object} [options.pagination={}] 分页 { page, pageSize } + * @param {Object} [options.sort={}] 排序 { sortField, sortOrder } + * @return {Promise<{list: Array, total: number, page: number, pageSize: number}>} 列表结果 + */ + async listDefinitions({ + nameKeyword = '', + type = '', + isEnabled = null, + pagination = {}, + sort = {}, + } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDefinition; + if (!model) { + throw new Error('报表定义模型 ReportDefinition 不可用'); + } + const { Op } = ctx.app.Sequelize; + + const escapeLike = value => String(value || '').replace(/[\\%_]/g, match => `\\${match}`); + + const where = {}; + const normalizedNameKeyword = String(nameKeyword || '').trim(); + if (normalizedNameKeyword) { + where.name = { [Op.like]: `%${escapeLike(normalizedNameKeyword)}%` }; + } + const normalizedType = String(type || '').trim(); + if (normalizedType) { + this.resolveTypeEntry(normalizedType); + where.type = normalizedType; + } + if (isEnabled !== null && isEnabled !== undefined && isEnabled !== '') { + where.is_enabled = Number(isEnabled) ? 1 : 0; + } + + const page = Math.max(1, Math.floor(Number(pagination.page) || 1)); + const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20))); + + const allowedSortFields = [ 'id', 'name', 'type', 'is_enabled', 'created_at', 'updated_at' ]; + const sortField = String(sort.sortField || sort.sort_field || 'id').trim(); + const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC'; + const order = allowedSortFields.includes(sortField) + ? [[ sortField, sortOrder ]] + : [[ 'id', 'DESC' ]]; + + const [ rows, total ] = await Promise.all([ + model.findAll({ + where, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }), + model.count({ where }), + ]); + + return { + list: (Array.isArray(rows) ? rows : []).map(row => this.definitionToView(row)), + total: Number(total) || 0, + page, + pageSize, + }; + } + + /** + * 软删除报表定义。 + * 删除前检查投递计划引用:仅拦截「启用中」的计划,停用计划不阻断—— + * 停用计划不再生产投递任务,历史投递日志按 report_definition_id 关联不受定义删除影响。 + * 重复删除同一 ID 按幂等成功处理,避免前端重复点击报错。 + * @param {Object} options 入参 + * @param {number|string} options.id 报表定义ID(必填,正整数) + * @return {Promise<{id: number, deleted: number}>} 删除结果(deleted 恒为 1) + * @throws {Error} ID 非法、定义不存在或存在启用中的投递计划引用时抛出业务可读错误 + */ + async deleteDefinition({ id } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDefinition; + if (!model) { + throw new Error('报表定义模型 ReportDefinition 不可用'); + } + const normalizedId = Number(id) || 0; + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + throw new Error('报表ID id 必须为正整数'); + } + + // 引用拦截:仅统计启用中的投递计划(enabled=1) + const planModel = ctx.model && ctx.model.ReportDeliveryPlan; + if (planModel && typeof planModel.count === 'function') { + const activePlanCount = await planModel.count({ + where: { + report_definition_id: normalizedId, + enabled: 1, + }, + }); + if (activePlanCount > 0) { + throw new Error(`存在 ${activePlanCount} 个启用的投递计划引用该报表,请先停用计划`); + } + } + + const existing = await this.findDefinitionById(model, normalizedId); + if (!existing) { + throw new Error(`报表定义不存在: id=${normalizedId}`); + } + if (existing.deleted_at) { + return { id: normalizedId, deleted: 1 }; + } + await existing.destroy(); + return { id: normalizedId, deleted: 1 }; + } +} + +module.exports = ReportService; diff --git a/app/service/systems/report/queries/index.js b/app/service/systems/report/queries/index.js new file mode 100644 index 0000000..dd3b914 --- /dev/null +++ b/app/service/systems/report/queries/index.js @@ -0,0 +1,70 @@ +'use strict'; + +const sevenDayStockFlow = require('./sevenDayStockFlow'); +const interceptOrder = require('./interceptOrder'); + +/** + * 报表内置查询器注册表。 + * key 对应 wms_report_definition.type; + * 新增查询器时在此登记,签名统一为 + * async ({ ctx, storeId, warehouseId, params }) => ({ windows, rows, meta })。 + * 每个查询器需在模块上挂载静态字段清单 `fields`(如 module.exports.fields) + * 与缺省窗口参数 `defaultWindow`,供报表引擎 report.definition.typeList 读取。 + * 注意:该对象会作为 service 模块导出,egg 加载器需要在其上挂载 + * `Symbol(EGG_LOADER_ITEM_FULLPATH)` 等内部符号,因此禁止对导出对象使用 + * Object.freeze / Object.seal / Object.preventExtensions。 + * @type {Object} + */ +const QUERIES = { + stockFlow: sevenDayStockFlow, + interceptOrder, +}; + +/** + * 注册表描述元数据:key/title/description/window/fields。 + * @type {Array<{key: string, title: string, description: string, window: Object, fields: Array}>} + */ +const DESCRIPTIONS = [ + { + key: 'stockFlow', + title: '库存变化以及补货报表', + description: '按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、外部编码、' + + '待处理订单占用数、可用库存、7日总出库数量、推荐采购量与是否触发预警', + window: { + ...(sevenDayStockFlow.defaultWindow || { dayCount: 7, cutoverHour: 7 }), + }, + fields: (Array.isArray(sevenDayStockFlow.fields) ? sevenDayStockFlow.fields : []).map(field => ({ ...field })), + }, + { + key: 'interceptOrder', + title: '库内确定拦截订单明细', + description: '按配送表 dispath_time(订单迁移进配送表的时间)统计昨日库内确定拦截订单' + + '(intercept_status=intercepted_at_warehouse),按商品明细展开(一个商品一行),' + + '列与订单导出含明细模式(export_mode=item)一致,仅不含「商品图片」列', + window: { + ...(interceptOrder.defaultWindow || { dayCount: 1, cutoverHour: 0 }), + }, + fields: (Array.isArray(interceptOrder.fields) ? interceptOrder.fields : []).map(field => ({ ...field })), + }, +]; + +/** + * 输出注册表可读描述(含全量字段清单),供 report.definition.typeList 复用。 + * 返回副本,避免调用方误改注册表元数据。 + * @return {Array<{key: string, title: string, description: string, window: Object, fields: Array}>} 注册描述列表 + */ +function describe() { + return DESCRIPTIONS.map(entry => ({ + ...entry, + window: { ...(entry.window || {}) }, + fields: (Array.isArray(entry.fields) ? entry.fields : []).map(field => ({ + ...field, + children: Array.isArray(field.children) ? field.children.map(child => ({ ...child })) : undefined, + })), + })); +} + +// egg 加载器要求导出对象可扩展,describe 作为方法属性挂在 QUERIES 上 +QUERIES.describe = describe; + +module.exports = QUERIES; diff --git a/app/service/systems/report/queries/interceptOrder.js b/app/service/systems/report/queries/interceptOrder.js new file mode 100644 index 0000000..1ba77be --- /dev/null +++ b/app/service/systems/report/queries/interceptOrder.js @@ -0,0 +1,477 @@ +'use strict'; + +const { scheduleDateOf } = require('../../../../lib/report/day_window'); + +/** + * 库内确定拦截订单明细查询器(静态字段清单)。 + * + * 前 46 列与 order.export(export_mode=item,按商品明细展开)的列对齐, + * 仅去掉「商品图片」列(报表渲染不支持内嵌图片,订单导出该列本身也不落地 URL); + * 另附加 3 列(订单导出无): + * `source_order_codes`(平台交易单号,取订单表源单号字段,位置紧跟「外部单号」)、 + * `intercept_notice_time`(通知拦截时间,取配送表 intercept_time,为空时回落 ORDER_INTERCEPT_REQUEST 日志最早时间)、 + * `intercept_confirm_time`(库内确定拦截时间,取配送表 dispath_time)。 + * key 与查询器返回的行字段一一对应,type 统一为 string: + * 渲染层对 string 字段原样输出,不做 zeroToDash/yesNo 转换, + * 从而保证单元格取值与订单导出逐格一致(见 render.js renderCell 口径); + * 两个时间列由查询器格式化为 'YYYY-MM-DD HH:mm:ss' 字符串(与订单导出的时间列同格式)。 + * @type {Array} + */ +const FIELDS = Object.freeze([ + { key: 'id', label: '订单ID', type: 'string' }, + { key: 'delivery_order_code', label: '订单号', type: 'string' }, + { key: 'external_order_code', label: '外部单号', type: 'string' }, + { key: 'source_order_codes', label: '平台交易单号', type: 'string' }, + { key: 'status', label: '订单状态', type: 'string' }, + { key: 'wave_no', label: '波次号', type: 'string' }, + { key: 'wave_index', label: '波次序号', type: 'string' }, + { key: 'store_id', label: '货主', type: 'string' }, + { key: 'sys_platform_name', label: '平台', type: 'string' }, + { key: 'create_channel', label: '来源', type: 'string' }, + { key: 'shop_nick', label: '店铺昵称', type: 'string' }, + { key: 'receiver_name', label: '收件人', type: 'string' }, + { key: 'receiver_mobile', label: '收件人电话', type: 'string' }, + { key: 'receiver_province', label: '省', type: 'string' }, + { key: 'receiver_city', label: '市', type: 'string' }, + { key: 'receiver_district', label: '区', type: 'string' }, + { key: 'receiver_town', label: '镇', type: 'string' }, + { key: 'receiver_detail', label: '详细地址', type: 'string' }, + { key: 'item_name', label: '仓库商品名称', type: 'string' }, + { key: 'item_barcode', label: '商品条码', type: 'string' }, + { key: 'item_quantity', label: '数量', type: 'string' }, + { key: 'logistics_name', label: '物流公司', type: 'string' }, + { key: 'waybill_code', label: '运单号', type: 'string' }, + { key: 'business_type', label: '业务类型', type: 'string' }, + { key: 'logistics_interface_name', label: '运单接口', type: 'string' }, + { key: 'package_material_id', label: '包材ID', type: 'string' }, + { key: 'package_material_code', label: '包材编码', type: 'string' }, + { key: 'package_material_name', label: '包材名称', type: 'string' }, + { key: 'waybill_allocated_at', label: '分配时间', type: 'string' }, + { key: 'items_count', label: '订单商品总类数', type: 'string' }, + { key: 'items_total', label: '订单商品总数', type: 'string' }, + { key: 'items_weight', label: '商品重量', type: 'string' }, + { key: 'weighing_weight', label: '称重重量(g)', type: 'string' }, + { key: 'total_amount', label: '订单金额', type: 'string' }, + { key: 'got_amount', label: '实收金额', type: 'string' }, + { key: 'create_at', label: '创建时间', type: 'string' }, + { key: 'pay_time', label: '支付时间', type: 'string' }, + { key: 'delivery_time', label: '发货时间', type: 'string' }, + { key: 'outbound_status', label: '出库状态', type: 'string' }, + { key: 'inspection_status', label: '复核状态', type: 'string' }, + { key: 'recheck_status', label: '复核完成状态', type: 'string' }, + { key: 'post_status', label: '配货状态', type: 'string' }, + { key: 'pack_status', label: '打包状态', type: 'string' }, + { key: 'remark', label: '备注', type: 'string' }, + { key: 'buyer_message', label: '买家留言', type: 'string' }, + { key: 'seller_message', label: '卖家留言', type: 'string' }, + { key: 'archive_time', label: '归档时间', type: 'string' }, + { key: 'intercept_notice_time', label: '通知拦截时间', type: 'string' }, + { key: 'intercept_confirm_time', label: '库内确定拦截时间', type: 'string' }, +]); + +/** + * 查询器缺省窗口元数据(供 report.definition.typeList 展示)。 + * 本查询器为「单个自然日」粒度:dayCount=1、cutoverHour=0(00:00 切日,非 stockFlow 的 07:00)。 + * @type {{dayCount: number, cutoverHour: number}} + */ +const DEFAULT_WINDOW = Object.freeze({ dayCount: 1, cutoverHour: 0 }); + +/** 查询表位:配送表(订单出库迁移后的表位,dispath_time 为该表独有字段) */ +const DISPATCH_TABLE_TYPE = 'dispatch'; +/** 库内确定拦截状态(order.recheckOrder.confirmIntercept / intercept_auto_confirm 写入值) */ +const INTERCEPTED_AT_WAREHOUSE_STATUS = 'intercepted_at_warehouse'; +/** 明细展开模式(与 order.export export_mode=item 一致:一个商品一行) */ +const EXPORT_MODE_ITEM = 'item'; +/** 单页拉取订单数(复用订单导出分页大小) */ +const DEFAULT_PAGE_SIZE = 1000; +/** 单次报表生成的最大明细行数保护(防御性上限,正常日拦截单量远低于该值) */ +const MAX_EXPORT_ROWS = 200000; +/** 通知拦截(发起拦截请求)操作日志编码:wms_operation_log.operation_code */ +const ORDER_INTERCEPT_REQUEST_CODE = 'ORDER_INTERCEPT_REQUEST'; +/** 拦截时间富化(回查配送表 + 操作日志)单批订单ID数 */ +const ENRICH_CHUNK_SIZE = 500; + +/** + * 两位补零。 + * @param {number} value 数值 + * @return {string} 补零字符串 + */ +function pad2(value) { + return String(value).padStart(2, '0'); +} + +/** + * 本地时区格式化为 'YYYY-MM-DD HH:mm:ss'。 + * @param {Date} date 时间对象 + * @return {string} 格式化结果 + */ +function formatDateTime(date) { + return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}` + + ` ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`; +} + +/** + * 解析统计日与查询区间。 + * + * 规则: + * 1. `params.bizDate`(或 `biz_date`)为合法 `YYYY-MM-DD` 时,按该日自然日整天统计; + * 2. 未传/非法时回落「昨日自然日」,即 [昨日 00:00:00.000, 今日 00:00:00.000); + * 3. **硬约束:统计日不得晚于昨天**——传入今天/未来日期一律回落昨日, + * 保证「今天生成/投递的报表不含今天的数据」(当天新迁入的拦截单只会在次日报表里出现); + * 4. 区间为本地时区半开区间(start 含、end 不含),通过 `new Date(y, m, d)` 构造, + * 规避夏令时导致的步进偏差。 + * + * @param {Object} [params={}] 查询器业务参数 + * @return {{bizDate: string, start: Date, end: Date}} 统计日与区间 + */ +function resolveBizDayWindow(params = {}) { + const safeParams = params && typeof params === 'object' ? params : {}; + const rawBizDate = String(safeParams.bizDate || safeParams.biz_date || '').trim(); + + const now = new Date(); + const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0); + const yesterdayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 0, 0, 0, 0); + + let baseDate = null; + + const matched = /^(\d{4})-(\d{2})-(\d{2})$/.exec(rawBizDate); + if (matched) { + const year = Number(matched[1]); + const month = Number(matched[2]); + const day = Number(matched[3]); + const candidate = new Date(year, month - 1, day, 0, 0, 0, 0); + if ( + candidate.getFullYear() === year + && candidate.getMonth() === month - 1 + && candidate.getDate() === day + ) { + baseDate = candidate; + } + } + + if (!baseDate) { + baseDate = yesterdayStart; + } + + // 今天及以后一律回落昨日:今天生成/投递的报表只含昨天(及更早显式指定日)的数据 + if (baseDate.getTime() >= todayStart.getTime()) { + baseDate = yesterdayStart; + } + + const start = new Date(baseDate.getFullYear(), baseDate.getMonth(), baseDate.getDate(), 0, 0, 0, 0); + const end = new Date(baseDate.getFullYear(), baseDate.getMonth(), baseDate.getDate() + 1, 0, 0, 0, 0); + + return { bizDate: scheduleDateOf(start), start, end }; +} + +/** + * 按字段清单裁剪订单导出行,保证报表列与订单导出 item 模式对齐并丢弃多余键(如 item_image)。 + * @param {Object} row 订单导出行 + * @return {Object} 仅含注册字段的报表行 + */ +function pickReportRow(row = {}) { + const safeRow = row && typeof row === 'object' ? row : {}; + const result = {}; + for (const field of FIELDS) { + const value = safeRow[field.key]; + result[field.key] = value === undefined ? '' : value; + } + return result; +} + +/** + * 安全格式化时间列(与订单导出 formatDateSafe 口径一致:空值/无效值返回空字符串)。 + * @param {*} value 时间原始值 + * @param {Object} app Egg app 实例(取 app.formatDate) + * @return {string} 'YYYY-MM-DD HH:mm:ss' 或空字符串 + */ +function formatTimeValue(value, app) { + if (value === null || value === undefined || value === '' || value === 0) { + return ''; + } + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime()) || date.getTime() <= 0) { + return ''; + } + return app && typeof app.formatDate === 'function' ? app.formatDate(date) : formatDateTime(date); +} + +/** + * 富化报表附加列(按订单ID回查,分片避免大 IN 列表)。 + * + * - `source_order_codes`(平台交易单号):直接取配送表同名字段(`mapOrderExportRow(item)` 不输出该列); + * - `intercept_notice_time`(通知拦截时间):主取配送表 `intercept_time` + * (自 2026-09-10 起该字段为「最近一次发起拦截的通知时刻」,确认拦截不再覆盖, + * 见 `app/lib/intercept_time.js`);该列为空时回落 `wms_operation_log` 中 + * `operation_code = 'ORDER_INTERCEPT_REQUEST'` 的**最早**记录时间(历史数据兼容)。 + * 回查日志按 `business_type='order' + business_id=订单ID + warehouse_id=当前仓库` 三重过滤: + * 订单 ID 按仓库发号,必须同仓隔离,禁止仅凭订单ID跨仓串读。 + * - `intercept_confirm_time`(库内确定拦截时间):取配送表 `dispath_time` + * (订单迁移进配送表的时间;库内确定拦截后订单会走 outbound_status=fin 的自动迁移,故等价于库内确定拦截时刻)。 + * + * 时间列均格式化为 'YYYY-MM-DD HH:mm:ss';查不到值时留空字符串。 + * + * @param {Object} args 入参 + * @param {Object} args.ctx Egg 上下文 + * @param {Object} args.app Egg app 实例(时间格式化) + * @param {Object} args.orderModel 配送表模型(读取 source_order_codes/intercept_time/dispath_time) + * @param {number} args.warehouseId 仓库ID + * @param {Array} args.rows 报表行(原地写入附加列,行内需含订单ID `id`) + * @return {Promise>} 富化后的行数组(同一引用) + */ +async function enrichInterceptFields({ ctx, app, orderModel, warehouseId, rows = [] }) { + const list = Array.isArray(rows) ? rows : []; + if (list.length === 0) { + return list; + } + + const orderIds = [ ...new Set( + list + .map(row => Number(row && row.id) || 0) + .filter(orderId => orderId > 0) + ) ]; + if (orderIds.length === 0) { + return list; + } + + const { Op, fn, col } = app.Sequelize; + const noticeTimeMap = new Map(); + const confirmTimeMap = new Map(); + const sourceOrderCodeMap = new Map(); + const logModel = ctx.model && ctx.model.OperationLog; + + for (let offset = 0; offset < orderIds.length; offset += ENRICH_CHUNK_SIZE) { + const chunk = orderIds.slice(offset, offset + ENRICH_CHUNK_SIZE); + + // 平台交易单号(source_order_codes)+ 通知拦截时间(intercept_time)+ 库内确定拦截时间(dispath_time) + try { + const orderRows = await orderModel.findAll({ + where: { id: { [Op.in]: chunk } }, + attributes: [ 'id', 'source_order_codes', 'intercept_time', 'dispath_time' ], + raw: true, + }); + for (const orderRow of (Array.isArray(orderRows) ? orderRows : [])) { + const orderId = Number(orderRow && orderRow.id) || 0; + if (orderId > 0) { + sourceOrderCodeMap.set(orderId, orderRow.source_order_codes); + noticeTimeMap.set(orderId, orderRow.intercept_time); + confirmTimeMap.set(orderId, orderRow.dispath_time); + } + } + } catch (error) { + ctx.logger.warn( + '[report.interceptOrder] 回查配送表附加列失败,平台交易单号/拦截时间列留空: %s', + error && error.message ? error.message : `${error}` + ); + } + + // 通知拦截时间(兜底,仅补齐主取为空的订单):操作日志最早一条 ORDER_INTERCEPT_REQUEST + if (logModel && typeof logModel.findAll === 'function') { + const pendingIds = chunk.filter( + orderId => orderId > 0 && (noticeTimeMap.get(orderId) === null || noticeTimeMap.get(orderId) === undefined) + ); + if (pendingIds.length === 0) { + continue; + } + try { + const logRows = await logModel.findAll({ + attributes: [ 'business_id', [ fn('MIN', col('created_at')), 'notice_time' ]], + where: { + business_type: 'order', + operation_code: ORDER_INTERCEPT_REQUEST_CODE, + warehouse_id: warehouseId, + business_id: { [Op.in]: pendingIds.map(orderId => String(orderId)) }, + }, + group: [ 'business_id' ], + raw: true, + }); + for (const logRow of (Array.isArray(logRows) ? logRows : [])) { + const orderId = Number(logRow && logRow.business_id) || 0; + if (orderId > 0) { + noticeTimeMap.set(orderId, logRow.notice_time); + } + } + } catch (error) { + ctx.logger.warn( + '[report.interceptOrder] 回查通知拦截操作日志失败,通知拦截时间列留空: %s', + error && error.message ? error.message : `${error}` + ); + } + } + } + + for (const row of list) { + const orderId = Number(row && row.id) || 0; + const sourceOrderCodes = sourceOrderCodeMap.get(orderId); + row.source_order_codes = sourceOrderCodes === null || sourceOrderCodes === undefined + ? '' + : String(sourceOrderCodes); + row.intercept_notice_time = formatTimeValue(noticeTimeMap.get(orderId), app); + row.intercept_confirm_time = formatTimeValue(confirmTimeMap.get(orderId), app); + } + + return list; +} + +/** + * 内置查询器:库内确定拦截订单明细(昨日迁入配送表的库内拦截订单,按商品明细展开)。 + * + * 口径与假设(供测试复核): + * 1. 数据源:配送表 `wms_order_delivery_{warehouseId}_dispatch`,仅取 + * `intercept_status = 'intercepted_at_warehouse'`(库内确定拦截;由 + * `order.recheckOrder.confirmIntercept` 与 `intercept_auto_confirm` 写入,同时 step=4、outbound_status=fin); + * 2. 时间基准:`dispath_time`(订单迁移进配送表的时刻,配送表独有字段,由 + * `orderDeliveryMigration.buildDispatchRow` 写入 `new Date()`); + * 3. 时间范围:默认「昨日自然日」[昨日 00:00:00.000, 今日 00:00:00.000) 本地时区半开区间, + * 可通过 `params.bizDate`(YYYY-MM-DD)指定更早的统计日;非法值回落昨日, + * **今天及以后的日期一律回落昨日**(今天生成/投递的报表永不含今天数据, + * 当天新迁入配送表的拦截单只会在次日报表中出现); + * 4. 明细粒度与列:复用 `orderExport.buildOrderExportPage` → `mapOrderExportRow(row, ctx, 'item')`, + * 因此状态中文翻译、货主备注、条码/商品名回落、运单汇总、包材等取值与订单导出 item 模式逐格一致; + * 列清单 = 订单导出 item 模式 47 列去掉「商品图片」列(46 列)+ 3 列附加列 + * (平台交易单号 source_order_codes、通知拦截时间、库内确定拦截时间,共 49 列); + * 5. 无商品明细的订单输出一行订单级数据(运单字段汇总),与订单导出 item 模式一致; + * 6. 主维度:warehouseId 必填(配送表按仓库分表);storeId > 0 时追加 `store_id` 过滤 + * (货主维度报表与投递),否则为仓库维度全量; + * 7. 排序:按订单 ID 升序分页拉取(单页 1000 单,循环至不足一页); + * 8. 附加列(订单导出 item 模式无此 3 列): + * - `source_order_codes`(平台交易单号)= 配送表 `source_order_codes` 原值 + * (`mapOrderExportRow(item)` 不输出该列,由本查询器回查补充,位置紧跟「外部单号」); + * - `intercept_notice_time`(通知拦截时间)= 配送表 `intercept_time` + * (自 2026-09-10 起为「最近一次发起拦截的通知时刻」,确认拦截不再覆盖; + * 为空时回落 `wms_operation_log` 的 ORDER_INTERCEPT_REQUEST 最早记录,按同仓隔离查询); + * - `intercept_confirm_time`(库内确定拦截时间)= 配送表 `dispath_time` + * (订单迁移进配送表的时间,库内确定拦截后基本都会走出库迁移); + * 两个时间列格式化为 'YYYY-MM-DD HH:mm:ss'; + * 8. 波次序号(wave_index):复用订单导出同款 `attachOrderWaveIndex`,该实现按登录上下文仓库 + * 取值,定时投递(无 ctx.user)场景降级为 0,手工导出(仓库主体)为真实序号。 + * + * @param {Object} args 查询器入参 + * @param {Object} args.ctx Egg 上下文 + * @param {number|null} args.storeId 货主ID(可选,<=0 时不按货主过滤) + * @param {number|null} args.warehouseId 仓库ID(必填) + * @param {Object} [args.params={}] 业务参数(bizDate 统计日覆盖) + * @return {Promise<{windows: Array, rows: Array, meta: Object}>} 查询结果 + */ +async function interceptOrder({ ctx, storeId = null, warehouseId = null, params = {} }) { + const { app } = ctx; + const { Op } = app.Sequelize; + + const normalizedWarehouseId = Number(warehouseId) || 0; + if (normalizedWarehouseId <= 0) { + throw new Error('interceptOrder 查询器缺少仓库维度 warehouseId'); + } + + const { bizDate, start, end } = resolveBizDayWindow(params); + const normalizedStoreId = Number(storeId) || 0; + + const orderExport = ctx.service && ctx.service.systems ? ctx.service.systems.orderExport : null; + if (!orderExport || typeof orderExport.buildOrderExportPage !== 'function') { + throw new Error('订单导出服务不可用,无法复用订单明细口径(orderExport.buildOrderExportPage)'); + } + + const target = orderExport.resolveExportTarget({ tableType: DISPATCH_TABLE_TYPE }); + const orderModel = await orderExport.getOrderModelByTableType(DISPATCH_TABLE_TYPE, normalizedWarehouseId); + + const queryWhere = { + intercept_status: INTERCEPTED_AT_WAREHOUSE_STATUS, + dispath_time: { + [Op.gte]: start, + [Op.lt]: end, + }, + }; + if (normalizedStoreId > 0) { + queryWhere.store_id = normalizedStoreId; + } + + const pageSize = Number(typeof orderExport.getExportPageSize === 'function' + ? orderExport.getExportPageSize() + : 0) || DEFAULT_PAGE_SIZE; + + const rows = []; + let orderCount = 0; + let page = 1; + let truncated = false; + + for (;;) { + const pageResult = await orderExport.buildOrderExportPage({ + page, + pageSize, + queryWhere, + order: [[ 'id', 'ASC' ]], + orderModel, + target, + warehouseId: normalizedWarehouseId, + mode: EXPORT_MODE_ITEM, + }); + + const pageOrderCount = Number(pageResult && pageResult.orderCount) || 0; + if (pageOrderCount <= 0) { + break; + } + + const pageRows = Array.isArray(pageResult && pageResult.exportRows) ? pageResult.exportRows : []; + for (const pageRow of pageRows) { + rows.push(pickReportRow(pageRow)); + if (rows.length >= MAX_EXPORT_ROWS) { + truncated = true; + break; + } + } + + orderCount += pageOrderCount; + if (truncated || pageOrderCount < pageSize) { + break; + } + page += 1; + } + + if (truncated) { + ctx.logger.warn( + '[report.interceptOrder] 明细行数达到上限 %s,已截断(bizDate=%s warehouseId=%s)', + MAX_EXPORT_ROWS, + bizDate, + normalizedWarehouseId + ); + } + + // 附加列:平台交易单号(source_order_codes)+ 通知拦截时间(配送表 intercept_time,日志兜底) + // + 库内确定拦截时间(配送表 dispath_time) + await enrichInterceptFields({ + ctx, + app, + orderModel, + warehouseId: normalizedWarehouseId, + rows, + }); + + const noticeTimeFilledCount = rows.filter(row => String(row.intercept_notice_time || '').trim()).length; + const confirmTimeFilledCount = rows.filter(row => String(row.intercept_confirm_time || '').trim()).length; + + return { + windows: [], + rows, + meta: { + bizDate, + startTime: formatDateTime(start), + endTime: formatDateTime(end), + warehouseId: normalizedWarehouseId, + storeId: normalizedStoreId, + interceptStatus: INTERCEPTED_AT_WAREHOUSE_STATUS, + timeField: 'dispath_time', + orderCount, + rowCount: rows.length, + noticeTimeFilledCount, + confirmTimeFilledCount, + truncated, + }, + }; +} + +module.exports = interceptOrder; +module.exports.fields = FIELDS; +module.exports.defaultWindow = DEFAULT_WINDOW; +// 纯函数导出(供单测/校验脚本复核口径,不作为查询器调用入口) +module.exports.resolveBizDayWindow = resolveBizDayWindow; +module.exports.pickReportRow = pickReportRow; +module.exports.enrichInterceptFields = enrichInterceptFields; diff --git a/app/service/systems/report/queries/sevenDayStockFlow.js b/app/service/systems/report/queries/sevenDayStockFlow.js new file mode 100644 index 0000000..e6a615f --- /dev/null +++ b/app/service/systems/report/queries/sevenDayStockFlow.js @@ -0,0 +1,305 @@ +'use strict'; + +const { buildDayWindows, resolveWindowConfig } = require('../../../../lib/report/day_window'); +const { avgDaysPerWeek, suggestWithCompensate, warnOf } = require('../../../../lib/report/formatters'); + +/** + * 库存变化以及补货报表查询器的静态字段清单(前端可读列元数据,决定导出列顺序)。 + * 仅保留以下 9 组导出列:产品名称/条码/外部编码/每日出入库/待处理订单占用数/ + * 可用库存/7日总出库数量/推荐采购量/是否触发预警。 + * key 与查询器返回的行字段一一对应;computed=true 表示由查询器预计算、非原始表字段; + * asText=true 表示渲染层将该列落地为 Excel 文本单元格(长数字串防科学计数法); + * daily 为数组类型,children 描述每日出入库子字段; + * item_code 列复用原“商品编码”key 以兼容既有报表定义的 fields 勾选,label 改为“外部编码”。 + * @type {Array} + */ +const FIELDS = Object.freeze([ + { key: 'item_name', label: '产品名称', type: 'string' }, + { key: 'barcode', label: '条码', type: 'string', asText: true }, + { key: 'item_code', label: '外部编码', type: 'string', asText: true }, + { + key: 'daily', + label: '每日出入库', + type: 'array', + children: [ + { key: 'ck', label: '出库数', type: 'number' }, + { key: 'rk', label: '入库数', type: 'number' }, + ], + }, + { key: 'pending_occupy', label: '待处理订单占用数', type: 'number' }, + { key: 'available', label: '可用库存', type: 'number' }, + { key: 'ck_total', label: '7日总出库数量', type: 'number' }, + { key: 'suggest', label: '推荐采购量', type: 'number', computed: true }, + { key: 'warn', label: '是否触发预警', type: 'boolean', computed: true }, +]); + +/** + * stockFlow 查询器缺省窗口参数(与旧 7 日出入库口径一致,可被 params 覆盖)。 + * @type {{dayCount: number, cutoverHour: number}} + */ +const DEFAULT_WINDOW = Object.freeze({ dayCount: 7, cutoverHour: 7 }); + +/** + * 内置查询器:库存变化以及补货报表(旧 PHP《7日出入库数据》Wms.php putout_putin_storage7 口径)。 + * + * 口径与假设(供测试复核): + * 1. 窗口:dayCount 个 [D cutoverHour:00, D+1 cutoverHour:00) 本地时区窗口 + * (缺省 7 天、07:00 切点,可由 params.dayCount/cutoverHour 覆盖); + * 2. 流水:wms_stock_transaction,transaction_type IN (INBOUND, OUTBOUND),显式排除 LOCK/UNLOCK, + * 按 created_at 落入窗口,INBOUND→rk、OUTBOUND→ck; + * 3. 可用库存口径:wms_storage(库位级正品明细),inventory_type='ZP'、is_enabled=1、未删除, + * SUM(available_quantity)=可用库存(行内 available 列); + * SUM(quantity)/SUM(locked_quantity)/待出库存等仅保留为行内内部计算字段,已不在导出列清单中; + * 4. 条码口径:wms_stock_barcodes 多值取字典序第一条(表内无主条码标志,旧 PHP 取 MIN(barcode) 语义); + * 5. 外部编码口径:优先 wms_stock_store.item_code(按 stock_id 关联 wms_stock_warehouse.id, + * stock_store 同 stock_id 多条时按 id 升序取第一条非空 item_code,stock_id 为空的记录不参与匹配), + * 未匹配则回落 wms_stock_warehouse.item_code,再无则留空; + * 6. 待处理订单占用数口径:取 wms_stock_warehouse.locked_quantity(仓库商品主表锁定数量, + * 不是 wms_storage 聚合的 locked_quantity 口径); + * 7. 行范围:窗口内有流水 或 有正品库存 的 SKU 均出列,按 item_code 升序、stock_id 升序; + * 8. suggest/warn 由 formatters 注册表计算(低库存补偿:available<20 且 rk_total<20), + * 内部仍计算 rk_total/日均/预计可售天数等字段供判定与复核,但不进入导出列清单。 + * + * @param {Object} args 查询器入参 + * @param {Object} args.ctx Egg 上下文 + * @param {number|null} args.storeId 货主ID(可选,<=0 时不按货主过滤) + * @param {number|null} args.warehouseId 仓库ID(必填) + * @param {Object} [args.params={}] 业务参数(dayCount/cutoverHour 窗口覆盖等) + * @return {Promise<{windows: Array, rows: Array, meta: Object}>} 查询结果 + */ +async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, params = {} }) { + const { app } = ctx; + const { Op } = app.Sequelize; + + const { dayCount, cutoverHour } = resolveWindowConfig(params || {}); + const windows = buildDayWindows({ dayCount, cutoverHour }); + + const normalizedWarehouseId = Number(warehouseId) || 0; + if (normalizedWarehouseId <= 0) { + throw new Error('stockFlow 查询器缺少仓库维度 warehouseId'); + } + const normalizedStoreId = Number(storeId) || 0; + + const windowStart = windows[0].start; + const windowEnd = windows[windows.length - 1].end; + + // 1) 流水聚合(排除 LOCK/UNLOCK) + const transactionWhere = { + warehouse_id: normalizedWarehouseId, + transaction_type: { [Op.in]: [ 'INBOUND', 'OUTBOUND' ] }, + created_at: { + [Op.gte]: new Date(windowStart), + [Op.lt]: new Date(windowEnd), + }, + }; + if (normalizedStoreId > 0) { + transactionWhere.store_id = normalizedStoreId; + } + + const transactionRows = await ctx.model.StockTransaction.findAll({ + where: transactionWhere, + attributes: [ 'stock_id', 'transaction_type', 'quantity', 'created_at' ], + raw: true, + }); + + // stockId → { daily: [{ck, rk}], ckTotal, rkTotal } + const flowMap = new Map(); + const upsertSlot = stockId => { + if (!flowMap.has(stockId)) { + flowMap.set(stockId, { + daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })), + ckTotal: 0, + rkTotal: 0, + }); + } + return flowMap.get(stockId); + }; + + for (const row of transactionRows) { + const stockId = Number(row.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const quantity = Number(row.quantity) || 0; + const createdMs = new Date(row.created_at).getTime(); + let windowIndex = -1; + for (let index = 0; index < windows.length; index += 1) { + if (createdMs >= windows[index].start && createdMs < windows[index].end) { + windowIndex = index; + break; + } + } + if (windowIndex < 0) { + continue; + } + const slot = upsertSlot(stockId); + if (row.transaction_type === 'OUTBOUND') { + slot.daily[windowIndex].ck += quantity; + slot.ckTotal += quantity; + } else { + slot.daily[windowIndex].rk += quantity; + slot.rkTotal += quantity; + } + } + + // 2) 可用/总库存(正品库位明细聚合) + const storageWhere = { + warehouse_id: normalizedWarehouseId, + inventory_type: 'ZP', + is_enabled: 1, + }; + if (normalizedStoreId > 0) { + storageWhere.store_id = normalizedStoreId; + } + + const inventoryRows = await ctx.model.Storage.findAll({ + where: storageWhere, + attributes: [ + 'stock_id', + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ], + ], + group: [ 'stock_id' ], + raw: true, + }); + + const inventoryMap = new Map(); + for (const row of inventoryRows) { + const stockId = Number(row.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const totalQuantity = Number(row.total_quantity) || 0; + const totalAvailable = Number(row.total_available) || 0; + inventoryMap.set(stockId, { + total: totalQuantity, + available: totalAvailable, + locked: Number(row.total_locked) || 0, + pending: totalQuantity - totalAvailable, + }); + } + + // 3) 商品资料与条码(条码多值取字典序第一条,假设:无主条码标志,等价旧 PHP MIN(barcode)) + const stockIds = [ ...new Set([ ...flowMap.keys(), ...inventoryMap.keys() ]) ]; + let stockRows = []; + let stockStoreRows = []; + let barcodeRows = []; + if (stockIds.length > 0) { + [ stockRows, stockStoreRows, barcodeRows ] = await Promise.all([ + ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIds } }, + attributes: [ 'id', 'item_code', 'item_name', 'locked_quantity' ], + raw: true, + }), + ctx.model.StockStore.findAll({ + where: { stock_id: { [Op.in]: stockIds } }, + attributes: [ 'id', 'stock_id', 'item_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }), + ctx.model.StockBarcode.findAll({ + where: { stock_id: { [Op.in]: stockIds } }, + attributes: [ 'stock_id', 'barcode' ], + order: [[ 'barcode', 'ASC' ]], + raw: true, + }), + ]); + } + + const stockMap = new Map(); + for (const row of stockRows) { + stockMap.set(Number(row.id), { + itemCode: String(row.item_code || '').trim(), + itemName: String(row.item_name || '').trim(), + lockedQuantity: Number(row.locked_quantity) || 0, + }); + } + + // 外部编码映射:同 stock_id 多条记录时按 id 升序取第一条非空 item_code(stock_id 为空记录不参与) + const externalCodeMap = new Map(); + for (const row of stockStoreRows) { + const stockId = Number(row.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const itemCode = String(row.item_code || '').trim(); + if (!externalCodeMap.has(stockId) && itemCode) { + externalCodeMap.set(stockId, itemCode); + } + } + + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const stockId = Number(row.stock_id); + const barcode = String(row.barcode || '').trim(); + // 查询已按 barcode 升序,首个即字典序第一条 + if (!barcodeMap.has(stockId) && barcode) { + barcodeMap.set(stockId, barcode); + } + } + + // 4) 组装数据行 + const rows = stockIds.map(stockId => { + const flow = flowMap.get(stockId) || { + daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })), + ckTotal: 0, + rkTotal: 0, + }; + const inventory = inventoryMap.get(stockId) || { total: 0, available: 0, locked: 0, pending: 0 }; + const stock = stockMap.get(stockId) || { itemCode: '', itemName: '', lockedQuantity: 0 }; + const available = inventory.available; + const total = inventory.total; + const ckTotal = flow.ckTotal; + const rkTotal = flow.rkTotal; + const ckAvg = avgDaysPerWeek(ckTotal, dayCount); + const rkAvg = avgDaysPerWeek(rkTotal, dayCount); + // 预计可售天数:日均出库 = ckAvg/10,避免浮点误差改用 (available×10)/ckAvg 取整 + const stockDays = ckAvg > 0 ? Math.floor((available * 10) / ckAvg) : null; + + return { + stock_id: stockId, + // 外部编码:优先 stock_store.item_code,未匹配则回落 stock_warehouse.item_code,再无则留空 + item_code: externalCodeMap.get(stockId) || stock.itemCode, + item_name: stock.itemName, + barcode: barcodeMap.get(stockId) || '', + daily: flow.daily, + ck_total: ckTotal, + rk_total: rkTotal, + available, + total, + pending: inventory.pending, + locked: inventory.locked, + pending_occupy: stock.lockedQuantity, + ck_avg: ckAvg, + rk_avg: rkAvg, + stock_days: stockDays, + suggest: suggestWithCompensate(ckTotal, available, rkTotal), + warn: warnOf(ckTotal, available, rkTotal), + }; + }); + + rows.sort((left, right) => { + if (left.item_code !== right.item_code) { + return left.item_code < right.item_code ? -1 : 1; + } + return left.stock_id - right.stock_id; + }); + + return { + windows, + rows, + meta: { + warehouseId: normalizedWarehouseId, + storeId: normalizedStoreId, + dayCount, + cutoverHour, + }, + }; +} + +module.exports = sevenDayStockFlow; +// 静态字段清单挂到查询器模块上,供报表引擎与注册表 describe 读取(不执行真实数据查询) +module.exports.fields = FIELDS; +// 缺省窗口参数挂到查询器模块上,供注册表 describe 与 report.definition.typeList 读取 +module.exports.defaultWindow = DEFAULT_WINDOW; diff --git a/app/service/systems/reportDelivery.js b/app/service/systems/reportDelivery.js new file mode 100644 index 0000000..d721da5 --- /dev/null +++ b/app/service/systems/reportDelivery.js @@ -0,0 +1,1526 @@ +'use strict'; + +const { Service } = require('egg'); +const { scheduleDateOf } = require('../../lib/report/day_window'); +const { + validateNotifyTemplate, + renderNotifyTemplate, + formatNotifyTime, +} = require('../../lib/report/notifyTemplate'); + +/** + * 货主报表定时投递编排服务(systems 层)。 + * + * 职责: + * 1. dispatch:分钟级扫描 wms_report_delivery_plan(enabled=1),按 HH:mm + 宽限窗口命中后 + * 对每个(货主+报表+数据日期+时间点)幂等生成报表并投递; + * 2. 投递记录状态机与 wms_report_delivery_log.status 一致: + * pending → exporting → delivered / failed / cancelled; + * 3. 失败退避重试(照搬 wms_waybill_allocate_queue 风格:MAX_RETRY=3, + * 退避 = retry_count × 60s);重试扫描条件:status=failed 且 retry_count<3 且 next_retry_at<=now; + * 4. 投递计划/投递记录的增改查(供 systemMethods 薄出口调用)。 + */ + +const DELIVERY_STATUS = Object.freeze({ + PENDING: 'pending', + EXPORTING: 'exporting', + DELIVERED: 'delivered', + FAILED: 'failed', + CANCELLED: 'cancelled', +}); + +/** 投递渠道(渠道已收敛:仅支持 inbox,wecom/link 已弃用) */ +const DELIVERY_CHANNELS = Object.freeze([ 'inbox' ]); +const DEFAULT_CHANNEL = 'inbox'; +const DEFAULT_GRACE_MINUTES = 60; +const MAX_RETRY_COUNT = 3; +const RETRY_BASE_DELAY_MS = 60 * 1000; +const EXPORTING_STALE_MS = 30 * 60 * 1000; +const MAX_ERROR_MESSAGE_LENGTH = 500; +const HHMM_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/; +/** 通知模板长度上限(与表结构 STRING(500) 一致) */ +const NOTIFY_TEMPLATE_MAX_LENGTH = 500; +/** 计划名称长度上限(与表结构 STRING(100) 一致) */ +const PLAN_NAME_MAX_LENGTH = 100; +/** 通知群多选上限 */ +const MAX_NOTIFY_GROUP_IDS = 20; +/** 通知成员多选上限 */ +const MAX_NOTIFY_MEMBER_IDS = 100; + +class ReportDeliveryService extends Service { + // ==================== 计划/记录查询(供 method 层复用) ==================== + + /** + * 校验并规范化投递时间点(HH:mm 格式、去重、升序排序)。 + * @param {Array|string} rawTimes 原始时间点(数组或 JSON 字符串) + * @return {Array} 规范化时间点数组 + * @throws {Error} 含非法格式时抛出 + */ + normalizeScheduleTimes(rawTimes) { + let list = rawTimes; + if (typeof list === 'string') { + try { + list = JSON.parse(list); + } catch (error) { + throw new Error('schedule_times 必须为 HH:mm 字符串数组'); + } + } + if (!Array.isArray(list) || list.length === 0) { + throw new Error('schedule_times 必须为 HH:mm 字符串数组且不能为空'); + } + const seen = new Set(); + const normalized = []; + for (const item of list) { + const timePoint = String(item || '').trim(); + if (!HHMM_PATTERN.test(timePoint)) { + throw new Error(`schedule_times 含非法时间点(需 HH:mm 24 小时制): ${timePoint}`); + } + if (!seen.has(timePoint)) { + seen.add(timePoint); + normalized.push(timePoint); + } + } + normalized.sort(); + return normalized; + } + + /** + * 解析 JSON 数组字段:数组原样、JSON 字符串解析、null/undefined/'' 返回 null。 + * @param {*} value 原始值 + * @param {string} label 字段名(错误提示用) + * @return {Array|null} 数组或 null + * @throws {Error} 非数组或 JSON 解析失败时抛出业务可读错误 + */ + parseJsonArray(value, label) { + if (value === null || value === undefined || value === '') { + return null; + } + let list = value; + if (typeof value === 'string') { + try { + list = JSON.parse(value); + } catch (error) { + throw new Error(`${label} 必须为数组`); + } + } + if (!Array.isArray(list)) { + throw new Error(`${label} 必须为数组`); + } + return list; + } + + /** + * 视图安全的 JSON 数组读取(兼容字符串/数组/null,无法解析时返回 null)。 + * @param {*} value 字段原始值 + * @return {Array|null} 数组或 null + */ + readJsonArray(value) { + if (Array.isArray(value)) { + return value; + } + if (typeof value === 'string' && value.trim()) { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : null; + } catch (error) { + return null; + } + } + return null; + } + + /** + * 视图安全的 JSON 对象读取(兼容对象/字符串/null,无法解析时返回 null)。 + * @param {*} value 字段原始值 + * @return {Object|null} 对象或 null + */ + readJsonObject(value) { + if (value && typeof value === 'object' && !Array.isArray(value)) { + return value; + } + if (typeof value === 'string' && value.trim()) { + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null; + } catch (error) { + return null; + } + } + return null; + } + + /** + * 校验并规范化文本通知模板(长度 ≤500 + 标签白名单)。 + * 空值/null/空串均视为未启用(返回空字符串)。 + * @param {*} value 原始模板值 + * @return {string} 规范化后的模板(未配置时为空字符串) + * @throws {Error} 超长或含白名单外标签时抛出业务可读错误 + */ + normalizeNotifyTemplate(value) { + if (value === null || value === undefined || value === '') { + return ''; + } + const normalized = String(value).trim(); + if (!normalized) { + return ''; + } + if (normalized.length > NOTIFY_TEMPLATE_MAX_LENGTH) { + throw new Error(`通知模板 notify_template 长度不能超过 ${NOTIFY_TEMPLATE_MAX_LENGTH} 字符`); + } + const check = validateNotifyTemplate(normalized); + if (!check.valid) { + throw new Error( + `通知模板含未知标签(仅支持 {time}/{url}/{report_name}/{biz_date}): ${check.invalidTags.join(', ')}` + ); + } + return normalized; + } + + /** + * 校验并规范化计划名称(仅展示字段,不参与幂等/关联逻辑)。 + * undefined=未传入(不覆盖既有值);null/空串/全空白=显式清空(返回 null); + * 非空时 trim 且长度 ≤ PLAN_NAME_MAX_LENGTH,超长抛出业务可读错误。 + * @param {*} value 原始名称值 + * @return {string|null|undefined} 规范化名称(未传入返回 undefined,清空返回 null) + * @throws {Error} 非空且超长时抛出业务可读错误 + */ + normalizePlanName(value) { + if (value === undefined) { + return undefined; + } + if (value === null || value === '') { + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + if (normalized.length > PLAN_NAME_MAX_LENGTH) { + throw new Error(`计划名称 name 长度不能超过 ${PLAN_NAME_MAX_LENGTH} 字符`); + } + return normalized; + } + + /** + * 校验并规范化通知群ID列表(wms_inbox_group.id 数组)。 + * 元素需为正整数、自动去重并升序排序、上限 MAX_NOTIFY_GROUP_IDS;null/空数组均允许(表示未选择群)。 + * @param {*} value 原始值(数组或 JSON 字符串) + * @return {Array|null} 规范化后的正整数数组(去重升序),未选择返回 null + * @throws {Error} 元素非法或超上限时抛出业务可读错误 + */ + normalizeNotifyGroupIds(value) { + const list = this.parseJsonArray(value, '通知群 notify_group_ids'); + if (list === null) { + return null; + } + if (list.length > MAX_NOTIFY_GROUP_IDS) { + throw new Error(`通知群 notify_group_ids 最多选择 ${MAX_NOTIFY_GROUP_IDS} 个群`); + } + const seen = new Set(); + const normalized = []; + for (const item of list) { + const id = Number(item); + if (!Number.isInteger(id) || id <= 0) { + throw new Error(`通知群 notify_group_ids 含非法群ID(需正整数): ${item}`); + } + if (!seen.has(id)) { + seen.add(id); + normalized.push(id); + } + } + normalized.sort((a, b) => a - b); + return normalized; + } + + /** + * 校验并规范化通知成员ID列表(外部 IM 用户 ID 字符串数组)。 + * 元素需为非空字符串、自动去重、上限 MAX_NOTIFY_MEMBER_IDS;null/空数组均允许(表示未选择成员)。 + * @param {*} value 原始值(数组或 JSON 字符串) + * @return {Array|null} 规范化后的字符串数组(去重),未选择返回 null + * @throws {Error} 元素非法或超上限时抛出业务可读错误 + */ + normalizeNotifyMemberIds(value) { + const list = this.parseJsonArray(value, '通知成员 notify_member_ids'); + if (list === null) { + return null; + } + if (list.length > MAX_NOTIFY_MEMBER_IDS) { + throw new Error(`通知成员 notify_member_ids 最多选择 ${MAX_NOTIFY_MEMBER_IDS} 个成员`); + } + const seen = new Set(); + const normalized = []; + for (const item of list) { + const memberId = String(item || '').trim(); + if (!memberId) { + throw new Error('通知成员 notify_member_ids 含空成员ID(需非空字符串)'); + } + if (!seen.has(memberId)) { + seen.add(memberId); + normalized.push(memberId); + } + } + return normalized; + } + + /** + * 校验通知群ID是否全部存在(软删自动排除,不校验 is_blocked: + * 屏蔽属于发送时过滤维度,保存时允许暂被屏蔽的群仍可选中)。 + * @param {Array} groupIds 群ID列表 + * @return {Promise} + * @throws {Error} 存在无效群ID时抛出(列出不存在或已删除的ID) + */ + async validateNotifyGroupExists(groupIds) { + const { ctx } = this; + const model = ctx.model && ctx.model.InboxGroup; + if (!model || typeof model.findAll !== 'function') { + throw new Error('站内信群模型 InboxGroup 不可用,无法校验通知群配置'); + } + const { Op } = ctx.app.Sequelize; + const rows = await model.findAll({ + where: { id: { [Op.in]: groupIds } }, + attributes: [ 'id' ], + raw: true, + }); + const found = new Set((Array.isArray(rows) ? rows : []).map(row => Number(row.id))); + const missing = groupIds.filter(id => !found.has(id)); + if (missing.length > 0) { + throw new Error(`通知群 notify_group_ids 含不存在或已删除的群ID: ${missing.join(', ')}`); + } + } + + /** + * 保存/更新投递计划(存在则更新,不存在则创建;货主+报表定义ID唯一)。 + * @param {Object} options 入参 + * @param {number} options.storeId 货主ID + * @param {number|string} options.reportId 报表定义ID + * @param {Array} options.scheduleTimes 投递时间点(HH:mm) + * @param {string} [options.channel='inbox'] 投递渠道(仅支持 inbox) + * @param {number} [options.lateGraceMinutes=60] 补投宽限分钟 + * @param {string} [options.remark] 备注 + * @param {string|null} [options.name] 计划名称(可空;未传不覆盖,null/空串清空,非空 trim ≤100) + * @param {string} [options.notifyTemplate] 文本通知模板(≤500,白名单标签 {time}/{url}/{report_name}/{biz_date}) + * @param {Array|string} [options.notifyGroupIds] 通知群ID数组(wms_inbox_group.id,≤20) + * @param {Array|string} [options.notifyMemberIds] 通知成员ID数组(外部IM用户ID,≤100) + * @return {Promise} 保存后的计划记录 + * @throws {Error} 参数非法或并发首次保存撞唯一索引且降级重查不到记录时抛出业务可读错误 + */ + async savePlan({ + storeId, + reportId, + scheduleTimes, + channel = DEFAULT_CHANNEL, + lateGraceMinutes = DEFAULT_GRACE_MINUTES, + remark = '', + name, + notifyTemplate, + notifyGroupIds, + notifyMemberIds, + }) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryPlan; + if (!model) { + throw new Error('投递计划模型 ReportDeliveryPlan 不可用'); + } + + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId <= 0) { + throw new Error('货主ID store_id 不能为空'); + } + const normalizedReportId = Number(reportId) || 0; + if (!Number.isInteger(normalizedReportId) || normalizedReportId <= 0) { + throw new Error('报表ID report_id 必须为正整数'); + } + // 校验报表定义存在且启用 + await ctx.service.systems.report.getDefinition(normalizedReportId); + + const normalizedTimes = this.normalizeScheduleTimes(scheduleTimes); + const normalizedChannel = String(channel || DEFAULT_CHANNEL).trim().toLowerCase() || DEFAULT_CHANNEL; + if (!DELIVERY_CHANNELS.includes(normalizedChannel)) { + throw new Error(`投递渠道仅支持 inbox: ${channel}`); + } + const graceMinutes = Math.max(0, Math.min(1440, Math.floor(Number(lateGraceMinutes) || 0))); + + // 计划名称校验(未传入 undefined 时保持既有字段不动,避免更新时误清空) + let normalizedName; + if (name !== undefined) { + normalizedName = this.normalizePlanName(name); + } + + // 文本通知配置校验(未传入 undefined 时保持既有字段不动,避免更新时误清空) + let normalizedNotifyTemplate; + let normalizedNotifyGroupIds; + let normalizedNotifyMemberIds; + if (notifyTemplate !== undefined) { + normalizedNotifyTemplate = this.normalizeNotifyTemplate(notifyTemplate); + } + if (notifyGroupIds !== undefined) { + normalizedNotifyGroupIds = this.normalizeNotifyGroupIds(notifyGroupIds); + if (normalizedNotifyGroupIds !== null && normalizedNotifyGroupIds.length > 0) { + await this.validateNotifyGroupExists(normalizedNotifyGroupIds); + } + } + if (notifyMemberIds !== undefined) { + normalizedNotifyMemberIds = this.normalizeNotifyMemberIds(notifyMemberIds); + } + + const payload = { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + schedule_times: normalizedTimes, + channel: normalizedChannel, + late_grace_minutes: graceMinutes, + remark: String(remark || '').slice(0, 500), + }; + if (normalizedName !== undefined) { + payload.name = normalizedName; + } + if (normalizedNotifyTemplate !== undefined) { + payload.notify_template = normalizedNotifyTemplate; + } + if (normalizedNotifyGroupIds !== undefined) { + payload.notify_group_ids = normalizedNotifyGroupIds; + } + if (normalizedNotifyMemberIds !== undefined) { + payload.notify_member_ids = normalizedNotifyMemberIds; + } + + const existing = await model.findOne({ + where: { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + }, + }); + if (existing) { + await existing.update(payload); + return this.planToView(existing); + } + try { + const created = await model.create(payload); + return this.planToView(created); + } catch (error) { + // 并发首次保存撞 uk_store_report_definition 唯一索引:降级为重查并更新(与 processOne 的 findOrCreate 降级一致) + if (error && error.name === 'SequelizeUniqueConstraintError') { + const winner = await model.findOne({ + where: { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + }, + }); + if (winner) { + await winner.update(payload); + return this.planToView(winner); + } + throw new Error('该货主已存在此报表的投递计划,保存冲突,请重试'); + } + throw error; + } + } + + /** + * 快速复制投递计划到其他货主(货主+报表定义ID唯一,目标已存在同报表定义计划时跳过)。 + * + * 规则: + * 1. id 必须为正整数,源计划不存在(含软删)时抛出业务可读错误; + * 2. storeIds 必须为非空数组且元素为正整数,自动去重; + * 与源计划 store_id 相同的项计入 skipped(原因:与源计划货主相同), + * 全部剔除后为空时仍正常返回(created=[],skipped 标注原因); + * 3. 目标货主必须在 wms_store 存在且状态有效(status 为 1 或 2(正常/审核中), + * 软删自动排除),不存在或状态不合法者计入 skipped(原因:货主不存在或状态异常); + * 4. 目标货主已存在同 report_definition_id 的计划(软删排除)时跳过 + * (原因:已存在同报表定义计划),不覆盖不报错; + * 5. 新建计划时 notify_group_ids / notify_member_ids 置空(null,通知配置不复制), + * enabled 等其余配置字段原样复制(enabled 保持“复制”语义,复制源计划启停状态); + * 6. 批量创建使用事务包裹,保证一致性;并发撞唯一索引时降级为 skipped 不中断其余创建。 + * + * @param {Object} options 入参 + * @param {number|string} options.id 源计划ID(正整数) + * @param {Array} options.storeIds 目标货主ID数组(元素需正整数,允许 JSON 字符串) + * @return {Promise<{created: Array<{id: number, store_id: number}>, skipped: Array<{store_id: number, reason: string}>}>} + * 复制结果:created 为新建成功的计划(id=新计划ID,store_id=目标货主ID), + * skipped 为跳过项(store_id=目标货主ID,reason=跳过原因) + * @throws {Error} id 非法、源计划不存在、storeIds 非空数组校验失败或元素非法时抛出业务可读错误 + */ + async copyPlan({ id, storeIds }) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryPlan; + if (!model) { + throw new Error('投递计划模型 ReportDeliveryPlan 不可用'); + } + + // 源计划校验(findByPk 受 paranoid 约束,软删自动排除,不存在返回 null) + const normalizedId = Number(id) || 0; + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + throw new Error('计划ID无效'); + } + const source = await model.findByPk(normalizedId); + if (!source) { + throw new Error('计划不存在'); + } + + // 目标货主数组校验:非空数组、元素为正整数、自动去重(JSON 字符串兼容,与 save 口径一致) + const rawList = this.parseJsonArray(storeIds, '目标货主 store_ids'); + if (rawList === null || rawList.length === 0) { + throw new Error('目标货主 store_ids 必须为非空数组'); + } + const seen = new Set(); + const targetStoreIds = []; + for (const item of rawList) { + const storeId = Number(item) || 0; + if (!Number.isInteger(storeId) || storeId <= 0) { + throw new Error(`目标货主 store_ids 含非法货主ID(需正整数): ${item}`); + } + if (!seen.has(storeId)) { + seen.add(storeId); + targetStoreIds.push(storeId); + } + } + + const sourceStoreId = Number(source.store_id) || 0; + const skipped = []; + const candidates = []; + for (const storeId of targetStoreIds) { + if (storeId === sourceStoreId) { + skipped.push({ store_id: storeId, reason: '与源计划货主相同' }); + } else { + candidates.push(storeId); + } + } + + // 目标货主存在性校验(wms_store status 为 1 或 2(正常/审核中)均有效,软删自动排除) + const validTargets = []; + if (candidates.length > 0) { + const storeModel = ctx.model && ctx.model.Store; + if (!storeModel || typeof storeModel.findAll !== 'function') { + throw new Error('货主模型 Store 不可用,无法校验目标货主'); + } + const { Op } = ctx.app.Sequelize; + const storeRows = await storeModel.findAll({ + where: { id: { [Op.in]: candidates }, status: { [Op.in]: [ 1, 2 ] } }, + attributes: [ 'id' ], + raw: true, + }); + const foundSet = new Set((Array.isArray(storeRows) ? storeRows : []).map(row => Number(row.id) || 0)); + for (const storeId of candidates) { + if (foundSet.has(storeId)) { + validTargets.push(storeId); + } else { + skipped.push({ store_id: storeId, reason: '货主不存在或状态异常' }); + } + } + } + + const created = []; + if (validTargets.length > 0) { + // 已存在同报表定义计划的目标货主跳过(软删排除,与唯一索引口径一致) + const { Op } = ctx.app.Sequelize; + const existingRows = await model.findAll({ + where: { + store_id: { [Op.in]: validTargets }, + report_definition_id: Number(source.report_definition_id) || 0, + }, + attributes: [ 'store_id' ], + raw: true, + }); + const existingSet = new Set((Array.isArray(existingRows) ? existingRows : []).map(row => Number(row.store_id) || 0)); + const toCreate = []; + for (const storeId of validTargets) { + if (existingSet.has(storeId)) { + skipped.push({ store_id: storeId, reason: '已存在同报表定义计划' }); + } else { + toCreate.push(storeId); + } + } + + if (toCreate.length > 0) { + // 其余配置字段原样复制;通知配置不复制(置空);enabled 原样复制保持“复制”语义 + const payload = { + report_definition_id: Number(source.report_definition_id) || 0, + schedule_times: Array.isArray(source.schedule_times) ? source.schedule_times : [], + channel: String(source.channel || DEFAULT_CHANNEL), + late_grace_minutes: Number(source.late_grace_minutes ?? DEFAULT_GRACE_MINUTES), + name: source.name == null ? null : String(source.name), + remark: source.remark == null ? null : String(source.remark), + notify_template: source.notify_template == null ? null : String(source.notify_template), + notify_group_ids: null, + notify_member_ids: null, + enabled: Number(source.enabled ?? 1), + }; + + const transaction = await ctx.model.transaction(); + try { + for (const storeId of toCreate) { + try { + const row = await model.create({ ...payload, store_id: storeId }, { transaction }); + created.push({ id: Number(row.id) || 0, store_id: storeId }); + } catch (error) { + // 并发下撞 uk_store_report_definition 唯一索引:降级为 skipped,不中断其余创建 + if (error && error.name === 'SequelizeUniqueConstraintError') { + skipped.push({ store_id: storeId, reason: '已存在同报表定义计划' }); + } else { + throw error; + } + } + } + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + } + + return { created, skipped }; + } + + /** + * 计划记录转视图对象。 + * @param {Object} plan 计划记录(实例或 raw) + * @return {Object} 视图对象 + */ + planToView(plan) { + if (!plan) { + return null; + } + return { + id: Number(plan.id) || 0, + store_id: Number(plan.store_id) || 0, + report_definition_id: Number(plan.report_definition_id) || 0, + schedule_times: Array.isArray(plan.schedule_times) ? plan.schedule_times : [], + channel: String(plan.channel || DEFAULT_CHANNEL), + enabled: Number(plan.enabled ?? 1), + late_grace_minutes: Number(plan.late_grace_minutes ?? DEFAULT_GRACE_MINUTES), + name: String(plan.name || ''), + remark: String(plan.remark || ''), + notify_template: String(plan.notify_template || ''), + notify_group_ids: this.readJsonArray(plan.notify_group_ids), + notify_member_ids: this.readJsonArray(plan.notify_member_ids), + created_at: plan.created_at || null, + updated_at: plan.updated_at || null, + }; + } + + /** + * 分页查询投递计划列表。 + * @param {Object} [options={}] 入参 + * @param {number} [options.storeId] 货主ID + * @param {number|string} [options.reportId] 报表定义ID + * @param {number|string} [options.enabled] 启用状态(0/1) + * @param {Object} [options.pagination={}] 分页 { page, pageSize } + * @param {Object} [options.sort={}] 排序 { sortField, sortOrder } + * @return {Promise<{list: Array, total: number, page: number, pageSize: number}>} 列表结果, + * 每条计划含 store_name(货主公司全称,货主已删除或不存在时为空串) + */ + async listPlans({ storeId = null, reportId = null, enabled = null, pagination = {}, sort = {} } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryPlan; + if (!model) { + throw new Error('投递计划模型 ReportDeliveryPlan 不可用'); + } + + const where = {}; + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId > 0) { + where.store_id = normalizedStoreId; + } + const normalizedReportId = Number(reportId) || 0; + if (normalizedReportId > 0) { + where.report_definition_id = normalizedReportId; + } + if (enabled !== null && enabled !== undefined && enabled !== '') { + where.enabled = Number(enabled) ? 1 : 0; + } + + const page = Math.max(1, Math.floor(Number(pagination.page) || 1)); + const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20))); + + const allowedSortFields = [ 'id', 'created_at', 'updated_at', 'store_id', 'report_definition_id' ]; + const sortField = String(sort.sortField || sort.sort_field || 'id').trim(); + const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC'; + const order = allowedSortFields.includes(sortField) + ? [[ sortField, sortOrder ]] + : [[ 'id', 'DESC' ]]; + + const [ rows, total ] = await Promise.all([ + model.findAll({ + where, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }), + model.count({ where }), + ]); + + const planRows = Array.isArray(rows) ? rows : []; + + // 批量查询货主名称(一次 IN 查询避免 N+1):软删除货主自动排除, + // 货主已删除或不存在时 store_name 回退为空串 + const storeIds = [ ...new Set(planRows.map(row => Number(row.store_id) || 0).filter(id => id > 0)) ]; + const storeNameMap = new Map(); + if (storeIds.length > 0) { + const storeModel = ctx.model && ctx.model.Store; + if (storeModel && typeof storeModel.findAll === 'function') { + const { Op } = ctx.app.Sequelize; + const storeRows = await storeModel.findAll({ + where: { id: { [Op.in]: storeIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const storeRow of Array.isArray(storeRows) ? storeRows : []) { + storeNameMap.set(Number(storeRow.id) || 0, String(storeRow.company_name || '')); + } + } + } + + return { + list: planRows.map(row => ({ + id: Number(row.id) || 0, + store_id: Number(row.store_id) || 0, + store_name: storeNameMap.get(Number(row.store_id) || 0) || '', + report_definition_id: Number(row.report_definition_id) || 0, + schedule_times: Array.isArray(row.schedule_times) ? row.schedule_times : [], + channel: String(row.channel || DEFAULT_CHANNEL), + enabled: Number(row.enabled ?? 1), + late_grace_minutes: Number(row.late_grace_minutes ?? DEFAULT_GRACE_MINUTES), + name: String(row.name || ''), + remark: String(row.remark || ''), + notify_template: String(row.notify_template || ''), + notify_group_ids: this.readJsonArray(row.notify_group_ids), + notify_member_ids: this.readJsonArray(row.notify_member_ids), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + })), + total: Number(total) || 0, + page, + pageSize, + }; + } + + /** + * 分页查询投递记录(审计)。 + * @param {Object} [options={}] 入参 + * @param {number} [options.storeId] 货主ID + * @param {number|string} [options.reportId] 报表定义ID + * @param {string} [options.status] 状态过滤 + * @param {Object} [options.pagination={}] 分页 { page, pageSize } + * @param {Object} [options.sort={}] 排序 { sortField, sortOrder } + * @return {Promise<{list: Array, total: number, page: number, pageSize: number}>} 列表结果 + */ + async listLogs({ storeId = null, reportId = null, status = '', pagination = {}, sort = {} } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryLog; + if (!model) { + throw new Error('投递记录模型 ReportDeliveryLog 不可用'); + } + + const where = {}; + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId > 0) { + where.store_id = normalizedStoreId; + } + const normalizedReportId = Number(reportId) || 0; + if (normalizedReportId > 0) { + where.report_definition_id = normalizedReportId; + } + const normalizedStatus = String(status || '').trim(); + if (normalizedStatus && Object.values(DELIVERY_STATUS).includes(normalizedStatus)) { + where.status = normalizedStatus; + } + + const page = Math.max(1, Math.floor(Number(pagination.page) || 1)); + const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20))); + + const allowedSortFields = [ 'id', 'created_at', 'updated_at', 'biz_date', 'delivered_at' ]; + const sortField = String(sort.sortField || sort.sort_field || 'id').trim(); + const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC'; + const order = allowedSortFields.includes(sortField) + ? [[ sortField, sortOrder ]] + : [[ 'id', 'DESC' ]]; + + const [ rows, total ] = await Promise.all([ + model.findAll({ + where, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }), + model.count({ where }), + ]); + + return { + list: (Array.isArray(rows) ? rows : []).map(row => ({ + id: Number(row.id) || 0, + warehouse_id: Number(row.warehouse_id) || 0, + store_id: Number(row.store_id) || 0, + report_definition_id: Number(row.report_definition_id) || 0, + report_name: String(row.report_name || ''), + biz_date: row.biz_date || '', + time_point: String(row.time_point || ''), + status: String(row.status || DELIVERY_STATUS.PENDING), + channel: String(row.channel || DEFAULT_CHANNEL), + file_url: String(row.file_url || ''), + retry_count: Number(row.retry_count) || 0, + next_retry_at: row.next_retry_at || null, + error_message: String(row.error_message || ''), + delivered_at: row.delivered_at || null, + notify_targets: this.readJsonObject(row.notify_targets), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + })), + total: Number(total) || 0, + page, + pageSize, + }; + } + + // ==================== 投递调度 ==================== + + /** + * 计算当前时刻命中的时间点(含 late_grace_minutes 宽限窗口)。 + * 宽限跨零点场景:now 为次日凌晨时,昨日深夜时间点仍可在宽限内命中。 + * @param {Array} scheduleTimes 计划时间点(HH:mm) + * @param {Date} now 触发时刻 + * @param {number} graceMinutes 宽限分钟 + * @return {Array} 命中的时间点 + */ + hitTimePoints(scheduleTimes, now, graceMinutes) { + const normalizedGrace = Math.max(0, Math.min(1440, Math.floor(Number(graceMinutes) || 0))); + const nowMinutes = now.getHours() * 60 + now.getMinutes(); + const hits = []; + for (const timePoint of scheduleTimes) { + const parts = String(timePoint).split(':'); + const timeMinutes = Number(parts[0]) * 60 + Number(parts[1]); + const diff = nowMinutes - timeMinutes; + const wrapDiff = nowMinutes + 24 * 60 - timeMinutes; + if ((diff >= 0 && diff <= normalizedGrace) || wrapDiff <= normalizedGrace) { + hits.push(timePoint); + } + } + return hits; + } + + /** + * 计算触发时刻的数据日期(T-1 本地自然日)。 + * @param {Date} now 触发时刻 + * @return {string} 'YYYY-MM-DD' + */ + bizDateOfTrigger(now) { + return scheduleDateOf(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)); + } + + /** + * 计算命中时间点对应的数据日期(报表数据截止日 = 时间点所属自然日的 T-1)。 + * + * 口径:同一时间点在「正常投递」与「跨零点补投」时必须落在相同 biz_date, + * 保证幂等键 (store_id, report_definition_id, biz_date, time_point) 防重不防漏: + * - 当日命中(timePoint 的 HH:mm <= now 的 HH:mm):时间点属于触发自然日, + * biz_date = 触发日 - 1; + * - 跨零点补投(timePoint 的 HH:mm > now 的 HH:mm,即昨日深夜时间点): + * 时间点属于昨日自然日,biz_date = 昨日 - 1(触发日 - 2), + * 与昨日正常投递口径一致,避免与次日正常投递撞幂等键。 + * + * @param {Date} now 触发时刻 + * @param {string} timePoint 命中的投递时间点(HH:mm) + * @return {string} 'YYYY-MM-DD' + */ + bizDateOfTimePoint(now, timePoint) { + const parts = String(timePoint).split(':'); + const timeMinutes = Number(parts[0]) * 60 + Number(parts[1]); + const nowMinutes = now.getHours() * 60 + now.getMinutes(); + const scheduleDayOffset = timeMinutes > nowMinutes ? -2 : -1; + return scheduleDateOf(new Date(now.getFullYear(), now.getMonth(), now.getDate() + scheduleDayOffset)); + } + + /** + * 解析货主所属仓库:优先首条有效合约(auth_status=2 且未停用),否则回退最早一条合约。 + * 假设:货主报表按单仓库生成,取最早合约的仓库维度(供测试复核)。 + * @param {number} storeId 货主ID + * @return {Promise} 仓库ID,未找到返回 0 + */ + async resolveStoreWarehouse(storeId) { + const { ctx } = this; + const model = ctx.model && ctx.model.StoreWarehouse; + if (!model || typeof model.findAll !== 'function') { + return 0; + } + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId <= 0) { + return 0; + } + const rows = await model.findAll({ + where: { store_id: normalizedStoreId }, + attributes: [ 'store_id', 'warehouse_id', 'auth_status', 'warehouse_use_status' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const list = Array.isArray(rows) ? rows : []; + const active = list.find(row => Number(row.auth_status) === 2 && Number(row.warehouse_use_status) !== 0); + const chosen = active || list[0]; + return chosen ? Number(chosen.warehouse_id) || 0 : 0; + } + + /** + * 投递成功回写(delivered),并落文本通知目标快照(可选)。 + * @param {Object} log 投递记录实例 + * @param {Object} fileResult 生成结果 { fileKey, url, filename } + * @param {Object|null} [notifyTargets=null] 文本通知目标快照 { group_ids, member_ids, notify_text } + * @return {Promise} + */ + async markDelivered(log, fileResult, notifyTargets = null) { + await log.update({ + status: DELIVERY_STATUS.DELIVERED, + // 表结构仅 file_url 一列承载产物地址(无 file_key/task_id 列),url 缺失时退化为 fileKey + file_url: String(fileResult.url || fileResult.fileKey || '').slice(0, 500), + error_message: null, + next_retry_at: null, + delivered_at: new Date(), + notify_targets: notifyTargets || null, + }); + } + + /** + * 投递失败回写(failed + 退避重试,MAX_RETRY=3,照搬 wms_waybill_allocate_queue 风格)。 + * @param {Object} log 投递记录实例 + * @param {string} errorMessage 失败原因 + * @return {Promise} + */ + async markFailed(log, errorMessage) { + const retryCount = Number(log.retry_count) || 0; + const nextCount = retryCount + 1; + const normalizedMessage = String(errorMessage || '报表投递失败').slice(0, MAX_ERROR_MESSAGE_LENGTH); + await log.update({ + status: DELIVERY_STATUS.FAILED, + retry_count: nextCount, + next_retry_at: nextCount >= MAX_RETRY_COUNT + ? null + : new Date(Date.now() + nextCount * RETRY_BASE_DELAY_MS), + error_message: normalizedMessage, + }); + } + + /** + * 置为导出中(exporting),并回填生成报表使用的仓库维度与报表名称快照。 + * @param {Object} log 投递记录实例 + * @param {number} warehouseId 仓库ID + * @param {string} [reportName=''] 报表名称快照 + * @return {Promise} + */ + async markExporting(log, warehouseId, reportName = '') { + await log.update({ + status: DELIVERY_STATUS.EXPORTING, + warehouse_id: Number(warehouseId) || 0, + report_name: String(reportName || '').slice(0, 100), + error_message: null, + }); + } + + /** + * 构建投递通知正文(站内信 inbox 文案)。 + * @param {Object} definition 报表定义 + * @param {string} bizDate 数据日期 + * @param {string} fileUrl 文件链接 + * @return {string} 通知正文 + */ + buildMessageContent(definition, bizDate, fileUrl) { + const reportName = String((definition && definition.name) || '报表'); + return `【${reportName}】${bizDate} 数据报表已生成,点击查看:${fileUrl}`; + } + + /** + * 解析计划配置的通知群(notify_group_ids → 有效群行)。 + * 过滤口径与 sendNotifyIfConfigured 一致:is_blocked=0、软删自动排除、仓库维度一致。 + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {number} options.warehouseId 仓库ID + * @return {Promise>} + * 有效群行列表(未配置群或全部被过滤时返回空数组) + * @throws {Error} 站内信群模型不可用时抛出 + */ + async resolveNotifyGroups({ plan, warehouseId }) { + const { ctx } = this; + const groupIds = this.readJsonArray(plan && plan.notify_group_ids) || []; + if (groupIds.length === 0) { + return []; + } + const inboxGroupModel = ctx.model && ctx.model.InboxGroup; + if (!inboxGroupModel || typeof inboxGroupModel.findAll !== 'function') { + throw new Error('站内信群模型 InboxGroup 不可用,无法解析通知群'); + } + const { Op } = ctx.app.Sequelize; + const rows = await inboxGroupModel.findAll({ + where: { + id: { [Op.in]: groupIds }, + warehouse_id: Number(warehouseId) || 0, + is_blocked: 0, + }, + attributes: [ 'id', 'group_id', 'group_name', 'ext_data' ], + raw: true, + }); + return Array.isArray(rows) ? rows : []; + } + + /** + * 按渠道投递(渠道已收敛,仅支持 inbox 站内信群推送)。 + * + * 规则: + * 1. 历史计划残留 wecom/link 等已弃用渠道时,按 inbox 兜底执行并记录 warn 日志 + * (不直接抛错:避免历史计划在 failed 退避循环中耗尽重试次数后永久卡死); + * 2. 群路由(缺陷 G1 修复):报表文件消息只投递到计划配置的通知群(notify_group_ids), + * 不再投递到任意「货主默认群」,避免未配置投递的群收到推送; + * 未配置通知群的历史计划保持旧行为,回退投递到货主默认站内信群(group_type=store); + * 3. 推送失败(success=false 或消息记录回写 push_status=3)时,立即复用 + * ctx.service.inbox.message.retry 重推一次(重置 push_status=0 异步重推, + * ext_id 幂等复用同一条消息记录,不重复写); + * 4. 重推仍失败(retry 自身抛错)时向上抛错,交由上层 failed 退避循环 + * (MAX_RETRY=3,退避 = retry_count × 60s); + * 5. 完成后按计划配置附带发送文本通知(与投递渠道独立); + * 6. 幂等键含货主维度(report:{store_id}:{report_definition_id}:{biz_date}:{time_point}), + * 不同货主的投递消息互不复用; + * 7. 推送体/消息表 ext_data 一律透传目标群配置的 ext_data(与 notice 推送口径一致), + * 不自行组装报表业务字段(会丢失渠道来源 source,导致桥接投递到错误/缺失渠道)。 + * + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {Object} options.definition 报表定义 + * @param {Object} options.fileResult 生成结果 + * @param {number} options.warehouseId 仓库ID + * @param {number} options.storeId 货主ID + * @param {string} options.bizDate 数据日期 + * @param {string} options.timePoint 命中时间点 + * @param {Date} [options.now=new Date()] 触发时刻(渲染 {time} 用) + * @return {Promise} 文本通知目标快照(未配置通知时返回 null) + * @throws {Error} 投递失败且重推失败时抛出 + */ + async deliverByChannel({ plan, definition, fileResult, warehouseId, storeId, bizDate, timePoint, now = null }) { + const { ctx } = this; + const rawChannel = String(plan.channel || DEFAULT_CHANNEL).trim().toLowerCase() || DEFAULT_CHANNEL; + const fileUrl = String(fileResult.url || fileResult.fileKey || ''); + const reportDefinitionId = Number(plan.report_definition_id) || 0; + // 幂等键含货主维度:不同货主的投递消息不得互相复用/串扰(货主限制不符缺陷) + const idempotentKey = `report:${storeId}:${reportDefinitionId}:${bizDate}:${timePoint}`; + + // 渠道收敛:wecom/link 已弃用,历史残留数据按 inbox 兜底执行,避免历史计划投递卡死 + if (rawChannel !== 'inbox') { + ctx.logger.warn( + `[reportDelivery] 计划投递渠道 ${rawChannel} 已弃用,按 inbox 兜底投递(store_id=${storeId}, report_definition_id=${reportDefinitionId})` + ); + } + + // inbox:站内信群推送(唯一渠道)。 + // 群路由(缺陷 G1 修复):报表文件消息只投递到计划配置的通知群,不再投递到任意「货主默认群」; + // 未配置通知群的历史计划保持旧行为,回退到货主默认站内信群(group_type=store,取最早一条)。 + const configuredGroupIds = this.readJsonArray(plan && plan.notify_group_ids) || []; + let targetGroups; + if (configuredGroupIds.length > 0) { + targetGroups = await this.resolveNotifyGroups({ plan, warehouseId }); + if (targetGroups.length === 0) { + throw new Error(`货主 ${storeId} 配置的通知群不可达(不存在、已删除、被屏蔽或仓库不一致),无法投递`); + } + } else { + const inboxGroupModel = ctx.model && ctx.model.InboxGroup; + if (!inboxGroupModel || typeof inboxGroupModel.findOne !== 'function') { + throw new Error('站内信群模型 InboxGroup 不可用'); + } + const groupRow = await inboxGroupModel.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + group_type: 'store', + is_blocked: 0, + }, + attributes: [ 'group_id', 'group_name', 'ext_data' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (!groupRow || !groupRow.group_id) { + throw new Error(`货主 ${storeId} 未配置站内信群,无法投递`); + } + targetGroups = [ groupRow ]; + } + + const warehouseNotify = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.pushSystemMessage !== 'function') { + throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用'); + } + const pushResults = []; + for (const groupRow of targetGroups) { + const pushResult = await warehouseNotify.pushSystemMessage({ + warehouseId, + storeId, + group: { + group_id: groupRow.group_id, + group_name: groupRow.group_name || '货主群', + ext_data: groupRow.ext_data || null, + }, + content: this.buildMessageContent(definition, bizDate, fileUrl), + extId: idempotentKey, + // ext_data 必须透传群配置(含渠道来源 source 等):自行组装业务字段会丢失渠道信息, + // 导致桥接按错误/缺失渠道投递(与 notice 推送口径一致:extData = group.ext_data) + extData: groupRow.ext_data || null, + }); + pushResults.push(pushResult); + } + + // 推送失败判定(双保险):success=false;或消息记录回写 push_status=3(推送链路异常时兜底识别) + const retryService = ctx.service && ctx.service.inbox && ctx.service.inbox.message; + for (const pushResult of pushResults) { + const messageId = (pushResult && Number(pushResult.messageId)) || 0; + let pushFailed = !pushResult || pushResult.success === false; + if (!pushFailed && messageId > 0) { + const InboxMessage = ctx.model && ctx.model.InboxMessage; + if (InboxMessage && typeof InboxMessage.findOne === 'function') { + try { + const row = await InboxMessage.findOne({ + where: { id: messageId }, + attributes: [ 'push_status' ], + raw: true, + }); + if (row && Number(row.push_status) === 3) { + pushFailed = true; + } + } catch (statusErr) { + ctx.logger.warn(`[reportDelivery] 读取消息推送状态失败: ${statusErr.message}`); + } + } + } + + if (pushFailed) { + const reason = (pushResult && (pushResult.reason || pushResult.error)) || '站内信推送失败'; + // 立即重推一次:复用 inbox.message.retry(重置 push_status=0 并异步重推;ext_id 幂等复用 + // 同一条消息记录,不重复写)。retry 自身抛错视为重推失败,向上抛出进入 failed 退避循环 + if (messageId > 0 && retryService && typeof retryService.retry === 'function') { + try { + await retryService.retry({ warehouseId, id: messageId }); + ctx.logger.warn(`[reportDelivery] 站内信推送失败已受理立即重推(message_id=${messageId}): ${reason}`); + } catch (retryErr) { + const retryReason = retryErr && retryErr.message ? retryErr.message : `${retryErr}`; + throw new Error(`站内信推送失败且重推失败: ${reason} / ${retryReason}`); + } + } else { + throw new Error(reason); + } + } + } + + // 文本通知(可选):与投递渠道独立;未配置时返回 null 保持既有行为不变 + return this.sendNotifyIfConfigured({ + plan, + definition, + fileResult, + warehouseId, + storeId, + bizDate, + timePoint, + now, + }); + } + + /** + * 按计划配置发送文本通知(模板渲染 + 定向群/成员推送)。 + * + * 规则: + * 1. 未配置模板或未选择任何群/成员时直接返回 null(保持既有投递行为不变); + * 2. 通知群(notify_group_ids 内部ID)→ 查 wms_inbox_group 取外部 group_id/group_name, + * 过滤 is_blocked=1、软删自动排除、仓库维度一致;逐群推送(群维度协议字段为单值); + * 3. 通知成员(notify_member_ids 外部IM用户ID)→ 推送体 user_id 直接传数组,不循环拆发; + * 选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送; + * 4. {url} 为空时由渲染器替换为兜底文案(生成中占位),不阻断投递; + * 5. 推送失败抛出异常交由上层走失败退避重试(消息落库按 ext_id 幂等防重); + * 6. 幂等键含货主维度(report:notify:{store_id}:...),不同货主的文本通知互不复用; + * 7. ext_data 透传通知群配置的 ext_data(不自行组装业务字段);仅成员推送(无群)时传 null。 + * + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {Object} options.definition 报表定义 + * @param {Object} options.fileResult 生成结果 + * @param {number} options.warehouseId 仓库ID + * @param {number} options.storeId 货主ID + * @param {string} options.bizDate 数据日期 + * @param {string} options.timePoint 命中时间点 + * @param {Date} [options.now] 触发时刻 + * @return {Promise} 快照 { group_ids, member_ids, notify_text },未配置返回 null + * @throws {Error} 目标不可达或推送失败时抛出 + */ + async sendNotifyIfConfigured({ plan, definition, fileResult, warehouseId, storeId, bizDate, timePoint, now = null }) { + const { ctx } = this; + const template = String((plan && plan.notify_template) || '').trim(); + if (!template) { + return null; + } + const groupIds = this.readJsonArray(plan && plan.notify_group_ids) || []; + const memberIds = this.readJsonArray(plan && plan.notify_member_ids) || []; + if (groupIds.length === 0 && memberIds.length === 0) { + return null; + } + + const reportDefinitionId = Number((plan && plan.report_definition_id) || 0); + const fileUrl = String(fileResult.url || fileResult.fileKey || ''); + const reportName = String((definition && definition.name) || '报表'); + const notifyText = renderNotifyTemplate(template, { + time: formatNotifyTime(now || new Date()), + url: fileUrl, + reportName, + bizDate, + }); + + // 目标解析:内部群ID → 外部群信息(is_blocked=0、软删排除、仓库维度一致), + // 复用 resolveNotifyGroups 与渠道投递保持同一解析口径 + const groups = groupIds.length > 0 + ? await this.resolveNotifyGroups({ plan, warehouseId }) + : []; + + if (groups.length === 0 && memberIds.length === 0) { + throw new Error('文本通知目标不可达(通知群不存在、已删除、被屏蔽或未选择群/成员)'); + } + + const warehouseNotify = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.pushSystemMessage !== 'function') { + throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用'); + } + + // 幂等键含货主维度:不同货主的文本通知不得互相复用/串扰(货主限制不符缺陷) + const notifyExtId = `report:notify:${storeId}:${reportDefinitionId}:${bizDate}:${timePoint}`; + // ext_data 不在此处组装:群推送透传群配置的 ext_data(含渠道来源), + // 仅成员推送(无群)时无群配置可取,按 null 透传 + const commonOptions = { + warehouseId, + storeId, + userIds: memberIds, + content: notifyText, + extId: notifyExtId, + }; + + const sentGroupIds = []; + const results = []; + // 群多选:群维度协议字段为单值(group_id/group_name),逐群推送;成员 user_id 数组随群推送整体透传 + for (const groupRow of groups) { + results.push(await warehouseNotify.pushSystemMessage({ + ...commonOptions, + group: { + group_id: groupRow.group_id, + group_name: groupRow.group_name || '货主群', + ext_data: groupRow.ext_data || null, + }, + extData: groupRow.ext_data || null, + })); + sentGroupIds.push(Number(groupRow.id)); + } + // 仅成员(未选择任何群):单独一次成员推送,user_id 直接传数组不循环拆发(无群配置,ext_data 传 null) + if (memberIds.length > 0 && results.length === 0) { + results.push(await warehouseNotify.pushSystemMessage({ ...commonOptions, extData: null })); + } + + const failed = results.filter(result => !result || result.success === false); + if (failed.length > 0) { + const reason = (failed[0] && (failed[0].reason || failed[0].error)) || '文本通知推送失败'; + throw new Error(`文本通知推送失败: ${reason}`); + } + + return { + group_ids: sentGroupIds, + member_ids: memberIds, + notify_text: notifyText, + }; + } + + /** + * 处理单个(计划 × 时间点)的幂等生成与投递。 + * 货主维度强校验:store_id/report_definition_id 无效时直接抛错,绝不生成跨货主报表。 + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {number} options.storeId 货主ID + * @param {number} options.reportId 报表定义ID + * @param {string} options.timePoint 命中时间点 + * @param {string} options.bizDate 数据日期 + * @param {Date} options.now 触发时刻 + * @return {Promise} 处理结果标记(delivered/failed/skipped) + * @throws {Error} 货主/报表定义维度非法时抛出 + */ + async processOne({ plan, storeId, reportId, timePoint, bizDate, now }) { + const { ctx } = this; + const logModel = ctx.model && ctx.model.ReportDeliveryLog; + if (!logModel) { + throw new Error('投递记录模型 ReportDeliveryLog 不可用'); + } + + // 货主维度强校验:投递报表必须限定货主,避免 store_id 缺失时生成跨货主数据(货主限制不符缺陷) + const normalizedStoreId = Number(storeId) || 0; + const normalizedReportId = Number(reportId) || 0; + if (normalizedStoreId <= 0 || normalizedReportId <= 0) { + throw new Error(`投递计划维度非法(store_id=${storeId}, report_definition_id=${reportId}),拒绝生成报表`); + } + + const uniqueWhere = { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + biz_date: bizDate, + time_point: timePoint, + }; + + let log = await logModel.findOne({ where: uniqueWhere }); + + if (log) { + const status = String(log.status || ''); + if (status !== DELIVERY_STATUS.FAILED) { + // 已投递/投递中/取消的记录直接跳过(幂等) + return 'skipped'; + } + const retryCount = Number(log.retry_count) || 0; + if (retryCount >= MAX_RETRY_COUNT) { + return 'skipped'; + } + const nextRetryAt = log.next_retry_at ? new Date(log.next_retry_at) : null; + if (nextRetryAt && nextRetryAt.getTime() > now.getTime()) { + // 退避未到期 + return 'skipped'; + } + } else { + try { + [ log ] = await logModel.findOrCreate({ + where: uniqueWhere, + defaults: { + ...uniqueWhere, + warehouse_id: 0, + report_name: '', + status: DELIVERY_STATUS.PENDING, + channel: String(plan.channel || DEFAULT_CHANNEL), + }, + }); + } catch (error) { + // 并发撞唯一键时降级为查询 + log = await logModel.findOne({ where: uniqueWhere }); + } + if (log && String(log.status || '') !== DELIVERY_STATUS.PENDING && String(log.status || '') !== DELIVERY_STATUS.FAILED) { + return 'skipped'; + } + } + + if (!log) { + return 'skipped'; + } + + const warehouseId = await this.resolveStoreWarehouse(normalizedStoreId); + if (warehouseId <= 0) { + await this.markFailed(log, `货主 ${normalizedStoreId} 未找到有效合约仓库`); + return 'failed'; + } + + // 读取报表定义一次(报表名称快照 + 投递通知文案共用,生成步骤内部会再按 id 读取) + const definition = await ctx.service.systems.report.getDefinition(normalizedReportId); + await this.markExporting(log, warehouseId, definition.name); + + // 生成上传(失败进入退避重试) + let fileResult; + try { + fileResult = await ctx.service.systems.report.generate({ + reportId: normalizedReportId, + storeId: normalizedStoreId, + warehouseId, + params: { + bizDate, + timePoint, + }, + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.error(`[reportDelivery] 报表生成失败 ${normalizedReportId}/${normalizedStoreId}/${bizDate}/${timePoint}: ${errorMessage}`); + await this.markFailed(log, `报表生成失败: ${errorMessage}`); + return 'failed'; + } + + // 投递(失败进入退避重试) + try { + const notifyTargets = await this.deliverByChannel({ + plan, + definition, + fileResult, + warehouseId, + storeId: normalizedStoreId, + bizDate, + timePoint, + now, + }); + await this.markDelivered(log, fileResult, notifyTargets); + return 'delivered'; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.error(`[reportDelivery] 报表投递失败 ${normalizedReportId}/${normalizedStoreId}/${bizDate}/${timePoint}: ${errorMessage}`); + await this.markFailed(log, `报表投递失败: ${errorMessage}`); + return 'failed'; + } + } + + /** + * 计划时间点解析:兼容数组与 JSON 字符串(防止手工数据写成字符串)。 + * @param {Array|string} value 原始值 + * @return {Array} 时间点数组 + */ + parseScheduleTimes(value) { + if (Array.isArray(value)) { + return value; + } + if (typeof value === 'string' && value.trim()) { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : []; + } catch (error) { + return []; + } + } + return []; + } + + /** + * 分钟级投递调度入口(schedule 调用)。 + * + * 流程: + * 1. 兜底回退:exporting 超过 EXPORTING_STALE_MS 的记录视为进程中断,置为 failed + * 并重置 retry_count=0、next_retry_at=now,交由重试扫描立即重排(防卡死); + * 2. 计划扫描:对每个命中时间点按「时间点归属自然日 - 1」计算 biz_date + * (跨零点补投落漏跑日),幂等生成并投递; + * 3. 重试扫描:status=failed 且 retry_count<3 且 next_retry_at<=now 的记录直接重试, + * 不依赖计划时间点再次命中。 + * @return {Promise} 本轮扫描汇总 { scanned, delivered, failed, skipped } + */ + async dispatch() { + const { ctx, app } = this; + const planModel = ctx.model && ctx.model.ReportDeliveryPlan; + const logModel = ctx.model && ctx.model.ReportDeliveryLog; + if (!planModel || !logModel) { + return { scanned: 0, delivered: 0, failed: 0, skipped: 0 }; + } + + const { Op } = app.Sequelize; + const now = new Date(); + + // 兜底:导出中超过 30 分钟视为进程中断,置为 failed 并重置退避参数(retry_count=0、 + // next_retry_at=now)交给重试链路立即重排。不能回退为 pending:既有 pending 会被 + // processOne 幂等跳过,且重试扫描只捡 failed,会导致该记录永久卡死(缺陷 D1)。 + await logModel.update({ + status: DELIVERY_STATUS.FAILED, + retry_count: 0, + next_retry_at: now, + error_message: '报表导出超时中断,已自动重排投递', + updated_at: now, + }, { + where: { + status: DELIVERY_STATUS.EXPORTING, + updated_at: { + [Op.lt]: new Date(now.getTime() - EXPORTING_STALE_MS), + }, + }, + }); + + const plans = await planModel.findAll({ + where: { enabled: 1 }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const summary = { + scanned: Array.isArray(plans) ? plans.length : 0, + delivered: 0, + failed: 0, + skipped: 0, + }; + + for (const plan of plans || []) { + const scheduleTimes = this.parseScheduleTimes(plan.schedule_times); + if (scheduleTimes.length === 0) { + continue; + } + const graceMinutes = Number(plan.late_grace_minutes ?? DEFAULT_GRACE_MINUTES); + const hits = this.hitTimePoints(scheduleTimes, now, graceMinutes); + if (hits.length === 0) { + continue; + } + + const storeId = Number(plan.store_id) || 0; + const reportId = Number(plan.report_definition_id) || 0; + if (storeId <= 0 || reportId <= 0) { + ctx.logger.warn(`[reportDelivery] 跳过无效计划 id=${plan.id}(store_id=${storeId}, report_definition_id=${reportId})`); + continue; + } + + for (const timePoint of hits) { + try { + // 按命中时间点归属自然日计算 biz_date:跨零点补投落在漏跑日(T-2), + // 与次日正常投递的幂等键互不碰撞(缺陷 D2) + const hitBizDate = this.bizDateOfTimePoint(now, timePoint); + const mark = await this.processOne({ plan, storeId, reportId, timePoint, bizDate: hitBizDate, now }); + if (mark === 'delivered') { + summary.delivered += 1; + } else if (mark === 'failed') { + summary.failed += 1; + } else { + summary.skipped += 1; + } + } catch (error) { + summary.failed += 1; + const errorMessage = error && error.message ? error.message : `${error}`; + ctx.logger.error(`[reportDelivery] 处理异常 ${reportId}/${storeId}/${timePoint}: ${errorMessage}`); + } + } + } + + // 重试扫描:status=failed 且 retry_count<3 且 next_retry_at<=now 的记录 + // (不依赖计划时间点再次命中,退避到期即重试) + const failedLogs = await logModel.findAll({ + where: { + status: DELIVERY_STATUS.FAILED, + retry_count: { [Op.lt]: MAX_RETRY_COUNT }, + next_retry_at: { [Op.lte]: now }, + }, + order: [[ 'id', 'ASC' ]], + limit: 200, + raw: true, + }); + + const retryPlans = new Map(); + for (const failedLog of failedLogs || []) { + const storeId = Number(failedLog.store_id) || 0; + const reportId = Number(failedLog.report_definition_id) || 0; + const bizDate = String(failedLog.biz_date || ''); + const timePoint = String(failedLog.time_point || ''); + if (storeId <= 0 || reportId <= 0 || !bizDate || !timePoint) { + continue; + } + const planKey = `${storeId}:${reportId}`; + let plan = retryPlans.get(planKey); + if (plan === undefined) { + plan = await planModel.findOne({ + where: { + store_id: storeId, + report_definition_id: reportId, + enabled: 1, + }, + raw: true, + }); + retryPlans.set(planKey, plan || null); + } + if (!plan) { + // 计划已停用/删除:不再重试 + continue; + } + try { + const mark = await this.processOne({ plan, storeId, reportId, timePoint, bizDate, now }); + if (mark === 'delivered') { + summary.delivered += 1; + } else if (mark === 'failed') { + summary.failed += 1; + } else { + summary.skipped += 1; + } + } catch (error) { + summary.failed += 1; + const errorMessage = error && error.message ? error.message : `${error}`; + ctx.logger.error(`[reportDelivery] 重试处理异常 ${reportId}/${storeId}/${timePoint}: ${errorMessage}`); + } + } + + return summary; + } +} + +module.exports = ReportDeliveryService; diff --git a/app/service/systems/return_received.js b/app/service/systems/return_received.js new file mode 100644 index 0000000..6e60eea --- /dev/null +++ b/app/service/systems/return_received.js @@ -0,0 +1,1097 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); +const Service = require('egg').Service; + +/** 退回收到导出分页拉取大小 */ +const RETURN_RECEIVED_EXPORT_PAGE_SIZE = 500; + +/** 收件任务缓存键前缀(任务ID → 任务元信息) */ +const RETURN_RECEIVED_TASK_CACHE_KEY_PREFIX = 'return_received_task:'; +/** 收件任务缓存过期秒数(10 分钟) */ +const RETURN_RECEIVED_TASK_CACHE_TTL_SECONDS = 600; +/** 系统预设「历史收件」任务ID(未传任务ID时的默认值) */ +const DEFAULT_RETURN_RECEIVED_TASK_ID = 1; + +/** + * 退回收到模块业务逻辑层。 + * 负责 wms_return_received 的增删查,以及原单反查、货主备注、30 日幂等等核心操作。 + * 所有数据库交互集中在此层,供 systemMethods/returnReceived.js 调用。 + */ +class ReturnReceivedService extends Service { + /** + * 创建带业务错误码的异常对象。 + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 扫码登记退回包裹(30 日内同仓库同单号只写一次,以第一次为准)。 + * 反查原运单判定是否原单退回,命中则回填关联字段并同步标记 is_back='Y', + * 并释放订单对应的拦截锁定库存(intercept_locked_quantity 回落到可用数量)。 + * + * @param {Object} params 登记参数。 + * @param {string} params.waybill_code 退回收件运单号。 + * @param {string} [params.remark] 备注。 + * @param {number|string} [params.return_received_task_id] 收件任务ID,不传默认 1(系统预设「历史收件」)。 + * @return {Promise} 登记结果,含 record、is_original_return、store_remark、is_urgent、duplicated。 + */ + async create({ waybill_code, remark, return_received_task_id }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + const scannerId = ctx.user && ctx.user.employees_id ? Number(ctx.user.employees_id) : 0; + const scannerName = String( + (ctx.user && ctx.user.employees_name) || (ctx.user && ctx.user.real_name) || '' + ).trim(); + + if (!Number.isFinite(scannerId) || scannerId <= 0) { + throw this.createBusinessError('缺少扫描人员工号上下文', 400); + } + + // 收件任务ID校验(缓存优先,未命中穿透数据库建立缓存) + const returnReceivedTaskId = await this._validateReturnReceivedTask(return_received_task_id, warehouseId); + + // 30 日幂等窗口:同仓库 + 同单号,扫描日期在最近 30 天内则视为重复 + const now = new Date(); + const thirtyDaysAgo = new Date(now.getTime()); + thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30); + const scanDate = app.formatDate(now, 'YYYY-MM-DD'); + const windowStart = app.formatDate(thirtyDaysAgo, 'YYYY-MM-DD'); + + // 加急标记:独立查询退回查询记录(wms_return_query_log),与货主归属匹配查询互不影响 + const isUrgent = await this._isUrgentReturnQuery(waybillCode, warehouseId); + + const existing = await ctx.model.ReturnReceived.findOne({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + scan_date: { [Op.gte]: windowStart }, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (existing) { + const enriched = await this._enrichReturn(existing); + return { + record: enriched, + is_original_return: Boolean(enriched.order_express_id), + store_remark: enriched.store_remark || '', + is_urgent: isUrgent, + duplicated: true, + }; + } + + // 反查原运单,判定是否原单退回 + let orderExpressId = null; + let orderId = null; + let storeId = null; + try { + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: waybillCode }, + attributes: [ 'id', 'order_id', 'store_id' ], + raw: true, + }); + if (orderExpress) { + orderExpressId = orderExpress.id; + orderId = orderExpress.order_id; + storeId = orderExpress.store_id; + } + } catch (err) { + ctx.logger.warn(`[returnReceived.create] 反查原运单失败: ${err.message}`); + } + + // 非原单退回:匹配货主登记表(wms_return_query_log,货主查询/登记过退回的运单),把件归属到对应货主 + // 兼容一单多件分段单号:精确 + 剥尾段 + 前缀段 + if (!orderExpressId && !storeId) { + try { + const base = waybillCode.replace(/(?:-\d+){2,}-?$/, ''); + const queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: warehouseId, + store_id: { [Op.gt]: 0 }, + [Op.or]: [ + { waybill_code: waybillCode }, + ...(base !== waybillCode ? [{ waybill_code: base }] : []), + { waybill_code: { [Op.like]: `${base}-%` } }, + ], + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + if (queryLog && Number(queryLog.store_id) > 0) { + storeId = Number(queryLog.store_id); + ctx.logger.info( + `[returnReceived.create] 匹配货主登记表归属: ${waybillCode} -> store_id=${storeId}` + ); + } + } catch (err) { + ctx.logger.warn(`[returnReceived.create] 匹配货主登记表失败: ${err.message}`); + } + } + + const created = await ctx.model.ReturnReceived.create({ + warehouse_id: warehouseId, + waybill_code: waybillCode, + scan_date: scanDate, + scanner_id: scannerId, + scanner_name: scannerName || '未命名', + order_express_id: orderExpressId, + order_id: orderId, + store_id: storeId, + return_received_task_id: returnReceivedTaskId, + remark: remark ? String(remark).slice(0, 500) : null, + }); + + // 原单退回:同步标记 wms_order_express.is_back = 'Y' + if (orderExpressId) { + try { + await ctx.model.OrderExpress.update( + { is_back: 'Y' }, + { where: { id: orderExpressId } } + ); + } catch (err) { + ctx.logger.warn(`[returnReceived.create] 更新运单退回标记失败: ${err.message}`); + } + } + + // 原单退回:处理关联拦截工单 + 更新订单拦截状态(参考库内拦截,不处理库存信息) + if (orderExpressId) { + await this._handleInterceptAfterSale(waybillCode, warehouseId, scannerId, scannerName); + if (orderId) { + await this._updateOrderInterceptStatus(orderId, warehouseId, scannerId, scannerName); + // 注意:退货登记不释放拦截锁定数量——拦截锁的回落由退货货物后续入库处理 + // (入库平账/差异对账链路)统一接管,避免登记环节直接改动库存口径。 + } + } + + const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + const enriched = await this._enrichReturn(createdRow); + + // 通知不在此处即时发送:由定时任务聚合(等 delayMs 无新登记后,按货主合并推送,只对货主查退回时登记过的运单通知) + + return { + record: enriched, + is_original_return: Boolean(enriched.order_express_id), + store_remark: enriched.store_remark || '', + is_urgent: isUrgent, + duplicated: false, + }; + } + + /** + * 校验收件任务ID(缓存优先,未命中穿透数据库建立缓存)。 + * + * 规则: + * 1. 未传任务ID时默认 1(系统预设「历史收件」); + * 2. 任务ID必须为正整数; + * 3. 缓存键 return_received_task:{id} 命中直接使用;未命中查 wms_return_received_task, + * 存在则写缓存(TTL 10 分钟),不存在报错; + * 4. 任务必须属于当前仓库或系统级(warehouse_id=0)。 + * + * @param {number|string|undefined} rawTaskId 入参任务ID。 + * @param {number} warehouseId 当前仓库ID。 + * @return {Promise} 校验通过的任务ID。 + */ + async _validateReturnReceivedTask(rawTaskId, warehouseId) { + const { ctx, app } = this; + + const taskId = rawTaskId === undefined || rawTaskId === null || rawTaskId === '' + ? DEFAULT_RETURN_RECEIVED_TASK_ID + : Number(rawTaskId); + + if (!Number.isInteger(taskId) || taskId <= 0) { + throw this.createBusinessError('收件任务ID不合法', 400); + } + + const cacheKey = RETURN_RECEIVED_TASK_CACHE_KEY_PREFIX + taskId; + let task = await app.getCacheAsync(cacheKey); + if (!task) { + // 缓存未命中:穿透数据库查询并建立缓存 + task = await ctx.model.ReturnReceivedTask.findOne({ + where: { id: taskId }, + attributes: [ 'id', 'warehouse_id', 'title' ], + raw: true, + }); + if (!task) { + throw this.createBusinessError(`收件任务不存在: ${taskId}`, 400); + } + await app.setCacheAsync(cacheKey, { + id: Number(task.id), + warehouse_id: Number(task.warehouse_id || 0), + title: String(task.title || ''), + }, RETURN_RECEIVED_TASK_CACHE_TTL_SECONDS); + } + + // 仓库归属校验:系统级(warehouse_id=0)或当前仓库任务才允许使用 + const taskWarehouseId = Number(task.warehouse_id || 0); + if (taskWarehouseId !== 0 && taskWarehouseId !== Number(warehouseId)) { + throw this.createBusinessError('收件任务不属于当前仓库', 400); + } + + return taskId; + } + + /** + * 判断运单是否存在退回查询记录(加急标记判定口径)。 + * 判定标准:wms_return_query_log 中存在 warehouse_id = 当前仓库 且 waybill_code = 登记运单号(精确匹配)的记录。 + * 查询失败时降级返回 false,不影响登记主流程。 + * + * @param {string} waybillCode 登记运单号。 + * @param {number} warehouseId 当前仓库ID。 + * @return {Promise} 存在退回查询记录返回 true,否则 false。 + */ + async _isUrgentReturnQuery(waybillCode, warehouseId) { + const { ctx } = this; + try { + const queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: Number(warehouseId), + waybill_code: waybillCode, + }, + attributes: [ 'id' ], + raw: true, + }); + return Boolean(queryLog); + } catch (err) { + ctx.logger.warn(`[returnReceived.create] 判断退回查询加急标记失败: ${err.message}`); + return false; + } + } + + /** + * 聚合通知待通知的登记(定时任务调用)。 + * 规则: + * 1. 只通知登记时间早于阈值(默认 5 分钟)的登记,等待新登记防抖合并; + * 2. 只对货主在退回查询登记表(wms_return_query_log)登记过的运单通知; + * 3. 按 仓库+货主 分组,合并成一条消息推送到货主售后群; + * 4. 推送后标记 is_notified=1,不重复通知。 + * + * @param {Object} [opts] 可选参数。 + * @param {number} [opts.delayMs] 防抖窗口毫秒数,不传用 config.inbox.returnReceivedNotifyDelayMs(默认 5 分钟)。 + * @return {Promise} { notified, skipped }。 + */ + async notifyPending(opts = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const delayNum = Number(opts.delayMs); + const delayMs = Number.isFinite(delayNum) && delayNum >= 0 + ? delayNum + : (Number(app.config.inbox?.returnReceivedNotifyDelayMs) || 5 * 60 * 1000); + const before = new Date(Date.now() - delayMs); + + // 待通知登记:已过防抖窗口、有货主、未通知 + const rows = await ctx.model.ReturnReceived.findAll({ + attributes: [ 'id', 'warehouse_id', 'waybill_code', 'store_id' ], + where: { + is_notified: 0, + store_id: { [Op.gt]: 0 }, + created_at: { [Op.lte]: before }, + }, + order: [[ 'id', 'ASC' ]], + limit: 200, + raw: true, + }); + if (rows.length === 0) { + return { notified: 0, skipped: 0 }; + } + + // 过滤:只对货主查退回时登记过的运单通知(匹配货主登记表,兼容分段单号) + const candidates = []; + for (const row of rows) { + const base = String(row.waybill_code || '').replace(/(?:-\d+){2,}-?$/, ''); + try { + const log = await ctx.model.ReturnQueryLog.findOne({ + attributes: [ 'id' ], + where: { + warehouse_id: row.warehouse_id, + [Op.or]: [ + { waybill_code: row.waybill_code }, + ...(base && base !== row.waybill_code ? [{ waybill_code: base }] : []), + ...(base ? [{ waybill_code: { [Op.like]: `${base}-%` } }] : []), + ], + }, + raw: true, + }); + if (log) candidates.push(row); + } catch (err) { + ctx.logger.warn(`[returnReceived.notifyPending] 查货主登记表失败 ${row.waybill_code}: ${err.message}`); + } + } + + const skipped = rows.length - candidates.length; + if (candidates.length === 0) { + return { notified: 0, skipped }; + } + + // 按 仓库+货主 分组聚合 + const buckets = new Map(); + for (const row of candidates) { + const key = `${row.warehouse_id}:${row.store_id}`; + if (!buckets.has(key)) { + buckets.set(key, { warehouse_id: row.warehouse_id, store_id: row.store_id, ids: [], waybills: [] }); + } + const bucket = buckets.get(key); + bucket.ids.push(row.id); + bucket.waybills.push(row.waybill_code); + } + + let notified = 0; + for (const bucket of buckets.values()) { + try { + const groups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ + storeIds: [ bucket.store_id ], + warehouseId: bucket.warehouse_id, + }); + if (groups.length === 0) { + ctx.logger.info( + `[returnReceived.notifyPending] 未找到货主售后群 warehouse=${bucket.warehouse_id} store=${bucket.store_id}` + ); + continue; + } + const content = `退回包裹已扫描登记:\n${bucket.waybills.join('\n')}\n仓库将安排拆包,拆包完成后将自动通知拆包明细`; + for (const g of groups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: bucket.warehouse_id, + group_id: g.group_id, + group_name: g.group_name, + content, + ext_data: g.ext_data || null, + store_id: g.store_id || null, + }); + } + await ctx.model.ReturnReceived.update( + { is_notified: 1 }, + { where: { id: { [Op.in]: bucket.ids } } } + ); + notified += bucket.ids.length; + ctx.logger.info( + `[returnReceived.notifyPending] 聚合通知 warehouse=${bucket.warehouse_id} store=${bucket.store_id} ` + + `groups=${groups.length} count=${bucket.ids.length} waybills=${bucket.waybills.join(',')}` + ); + } catch (err) { + ctx.logger.warn(`[returnReceived.notifyPending] 通知失败: ${err.message}`); + } + } + + return { notified, skipped }; + } + + /** + * 处理退回运单关联的未完结拦截工单(写入「退回包裹已收到」并完结)。 + * 仅更新工单状态,不处理库存信息(参考库内拦截 interceptScan 的工单处理部分)。 + * + * @param {string} waybillCode 退回收件运单号。 + * @param {number} warehouseId 仓库ID。 + * @param {number} operatorId 操作人工号ID。 + * @param {string} operatorName 操作人工号名称。 + * @return {Promise} 无返回值。 + */ + async _handleInterceptAfterSale(waybillCode, warehouseId, operatorId, operatorName) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + try { + const afterSale = await ctx.model.AfterSale.findOne({ + where: { + waybill_no: waybillCode, + warehouse_id: warehouseId, + type: 'order', + sub_type: 'intercept', + deleted_at: null, + status: { [Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + if (!afterSale) { + return; + } + + const operatorSnapshot = JSON.stringify({ + id: String(operatorId || ''), + name: String(operatorName || ''), + }); + + await ctx.service.systems.afterSale.handleWorkOrder({ + id: afterSale.id, + remark: '退回包裹已收到', + targetStatus: 'completed', + resolution: '退回包裹已收到', + attachmentIds: [], + operatorId: Number(operatorId) || 0, + operatorSnapshot, + warehouseId, + }); + } catch (err) { + ctx.logger.warn(`[returnReceived._handleInterceptAfterSale] 处理拦截工单失败, waybill=${waybillCode}, error=${err.message}`); + } + } + + /** + * 更新退回运单关联订单的退回状态并写入操作记录(不处理库存信息)。 + * - current 表(待处理):设置 intercept_status='returned'、step=4、outbound_status='fin' 触发自动转配送表; + * - dispatch 表(配送中):仅更新 intercept_status='returned'; + * - 两条链路均**不写** intercept_time(该字段恒为「最近一次发起拦截的通知时刻」, + * 退回入库不覆盖,见 app/lib/intercept_time.js); + * - 不释放储位分配、不释放订单锁。 + * 兼容 current/dispatch 分表:先查 current 表,不存在再查 dispatch 表。 + * + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} operatorId 操作人工号ID。 + * @param {string} operatorName 操作人工号名称。 + * @return {Promise} 无返回值。 + */ + async _updateOrderInterceptStatus(orderId, warehouseId, operatorId, operatorName) { + const { ctx } = this; + try { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + return; + } + + const where = { id: orderId, warehouse_id: warehouseId }; + const orderAttributes = [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status' ]; + + // 先查 current 表;不存在再查 dispatch 表 + let orderModel = await factory.getCurrentModel(warehouseId); + let order = orderModel && typeof orderModel.findOne === 'function' + ? await orderModel.findOne({ where, attributes: orderAttributes, raw: true }) + : null; + + const isCurrentTable = Boolean(order); + + if (!order && typeof factory.getDispatchModel === 'function') { + orderModel = await factory.getDispatchModel(warehouseId); + order = orderModel && typeof orderModel.findOne === 'function' + ? await orderModel.findOne({ where, attributes: orderAttributes, raw: true }) + : null; + } + + if (!order || !orderModel || typeof orderModel.update !== 'function') { + return; + } + + const updateFields = { + intercept_status: 'returned', + updated_at: new Date(), + }; + + // 待处理表(current):设置 step=4 + outbound_status='fin' 触发自动转配送表 + if (isCurrentTable) { + updateFields.step = 4; + updateFields.outbound_status = 'fin'; + } + + await orderModel.update(updateFields, { where }); + + // 写入订单操作记录 + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: warehouseId, + operationCode: 'ORDER_RETURN_RECEIVED', + operator: { id: String(operatorId || ''), name: String(operatorName || '') }, + extras: { + warehouseId, + orderId, + orderNo, + previousInterceptStatus: String(order.intercept_status || '').trim(), + newInterceptStatus: 'returned', + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn(`[returnReceived._updateOrderInterceptStatus] 写入订单操作日志失败, orderId=${orderId}, error=${logErr.message}`); + } + } catch (err) { + ctx.logger.warn(`[returnReceived._updateOrderInterceptStatus] 更新订单退回状态失败, orderId=${orderId}, error=${err.message}`); + } + } + + /** + * 分页查询退回收到登记列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {number} [pagination.page=1] 页码。 + * @param {number} [pagination.pageSize=20] 每页数量。 + * @param {Object} [sort] 排序参数。 + * @param {string} [sort.sortField] 排序字段。 + * @param {string} [sort.sortOrder] 排序顺序(asc/desc)。 + * @return {Promise} { list: Array, pagination: Object }。 + */ + async list(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildListWhere(where, Op); + const order = this._buildListOrder(sort); + + const { count, rows } = await ctx.model.ReturnReceived.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + const list = []; + for (const row of rows) { + list.push(await this._enrichReturn(row)); + } + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 导出退回收到登记列表(单 Sheet Excel,异步任务模式,与 returnUnpack.export 口径一致)。 + * 复用 list 的 where/sort 语义;仓库隔离由方法层注入 warehouse_id,此处再强制兜底; + * 分页拉取主表全量数据后批量解析货主备注,流式生成 Excel 并上传 COS。 + * + * @param {Object} options 导出选项。 + * @param {Object} [options.where] 标准化 where 条件(与 list 一致)。 + * @param {Object} [options.sort] 排序参数(与 list 一致)。 + * @param {number} [options.warehouseId] 仓库ID(由方法层从上下文注入)。 + * @param {Function} [options.onProgress] 进度回调。 + * @return {Promise} 上传结果与统计信息(含 filename/fileKey/url/cdnUrl/cosUrl/current_count/total_count)。 + */ + async exportList(options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const safeOptions = options && typeof options === 'object' && !Array.isArray(options) ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const warehouseId = Number(safeOptions.warehouseId || 0); + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + // 复用 list 的 where/sort 语义,并强制仓库隔离(服务端注入,前端无需传 warehouse_id) + const queryWhere = this._buildListWhere(where, Op); + queryWhere.warehouse_id = warehouseId; + const order = this._buildListOrder(sort); + + const totalCount = await ctx.model.ReturnReceived.count({ where: queryWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 85, + currentCount: 0, + totalCount, + message: totalCount > 0 ? `已命中 ${totalCount} 条登记记录,开始导出` : '未命中数据,开始生成空文件', + }); + + // ---- 分页拉取主表全量数据(复用 list 的 pageSize 口径,避免单次内存溢出)---- + const pageSize = RETURN_RECEIVED_EXPORT_PAGE_SIZE; + const totalPages = Math.max(1, Math.ceil(totalCount / pageSize)); + const allRows = []; + for (let page = 1; page <= totalPages; page += 1) { + if (allRows.length >= totalCount) { + break; + } + const { rows } = await ctx.model.ReturnReceived.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + for (const row of rows) { + allRows.push(row); + } + await progressHandler({ + status: 'running', + progress: Math.min(55, 10 + Math.round((allRows.length / Math.max(totalCount, 1)) * 45)), + currentCount: allRows.length, + totalCount, + message: `正在拉取登记列表,已完成 ${allRows.length}/${totalCount}`, + }); + // 每页之间稍作让渡,避免长时间阻塞 + await new Promise(resolve => setImmediate(resolve)); + } + + // ---- 批量解析货主备注(避免逐行查询)---- + const storeRemarkMap = await this._resolveStoreRemarkMap(allRows, warehouseId, Op); + const enrichedRows = []; + for (const row of allRows) { + enrichedRows.push(await this._enrichReturn(row, storeRemarkMap)); + } + + await progressHandler({ + status: 'running', + progress: 60, + currentCount: allRows.length, + totalCount, + message: '正在生成 Excel 文件...', + }); + + const exportResult = await this._generateExportExcel(enrichedRows, warehouseId); + + await progressHandler({ + status: 'success', + progress: 100, + currentCount: allRows.length, + totalCount, + message: '导出任务完成', + result: exportResult, + }); + + return { + ...exportResult, + current_count: allRows.length, + total_count: totalCount, + }; + } + + /** + * 生成退回收到导出 Excel(单 Sheet)并上传 COS,返回下载信息。 + * 流式写入临时文件后通过 upload.uploadFile 上传,上传结果落库通知。 + * + * @param {Array} rows 已组装展示字段的登记记录行。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl }。 + */ + async _generateExportExcel(rows = [], warehouseId) { + const { ctx, app } = this; + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-return-received-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `退回收到导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + try { + const worksheet = workbook.addWorksheet('退回收到登记列表'); + worksheet.columns = [ + { header: '运单号', key: 'waybill_code', width: 22 }, + { header: '扫描日期', key: 'scan_date', width: 14 }, + { header: '扫描人员', key: 'scanner_name', width: 14 }, + { header: '是否原单退回', key: 'is_original_return', width: 12 }, + { header: '订单ID', key: 'order_id', width: 14 }, + { header: '货主备注', key: 'store_remark', width: 20 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '登记时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + + for (const row of rows) { + worksheet.addRow({ + waybill_code: normalizeCellValue(row.waybill_code), + scan_date: normalizeCellValue(row.scan_date), + scanner_name: normalizeCellValue(row.scanner_name), + is_original_return: row.is_original_return ? '是' : '否', + order_id: row.order_id || '', + store_remark: normalizeCellValue(row.store_remark), + remark: normalizeCellValue(row.remark), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + worksheet.commit(); + await workbook.commit(); + + // ---- 上传文件(与 returnUnpack 导出口径一致)---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/return_received/${warehouseId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `退回收到登记导出(仓库${warehouseId}),共${rows.length}条登记记录`, + }); + } + + // 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录(兼容 data 包裹),最后才回退 COS key + const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {}; + const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null; + const fileUrlFromRecord = resolvedFileRecord + ? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '') + : ''; + const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || ''; + + return { + filename, + fileKey: safeUploadResult.fileName || uploadKey, + url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey, + cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '', + cosUrl: safeUploadResult.cosUrl || '', + }; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + throw error; + } finally { + // 清理临时文件(不存在或删除失败均忽略) + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (err) { /* ignore */ } + } + } + + /** + * 查询单条退回收到登记详情(含原运单与货主合约备注)。 + * + * @param {number} id 登记记录主键ID。 + * @return {Promise} { record, order_express, store_contract }。 + */ + async detail(id) { + const { ctx } = this; + const record = await this._findByIdChecked(id); + const enriched = await this._enrichReturn(record); + + const orderExpress = record.order_express_id + ? await ctx.model.OrderExpress.findOne({ + where: { id: record.order_express_id }, + attributes: [ + 'id', 'waybill_code', 'order_id', 'store_id', 'warehouse_id', + 'is_back', 'is_intercept', 'logistics_name', 'logistics_code', + ], + raw: true, + }) + : null; + + const storeContract = record.store_id + ? await ctx.model.StoreWarehouse.findOne({ + where: { store_id: record.store_id, warehouse_id: record.warehouse_id }, + attributes: [ + 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', + 'store_use_status', 'warehouse_use_status', + ], + raw: true, + }) + : null; + + return { + record: enriched, + order_express: orderExpress, + store_contract: storeContract, + }; + } + + /** + * 删除单条退回收到登记记录(物理删除)。 + * + * @param {number} id 登记记录主键ID。 + * @return {Promise} 删除结果,含被删除记录 id。 + */ + async delete(id) { + const { ctx } = this; + const record = await this._findByIdChecked(id); + await ctx.model.ReturnReceived.destroy({ where: { id: record.id } }); + return { id: record.id }; + } + + /** + * 按主键查询登记记录,并校验仓库隔离。 + * + * @param {number} id 登记记录主键ID。 + * @return {Promise} 登记记录原始数据。 + */ + async _findByIdChecked(id) { + const { ctx } = this; + const normalizedId = Number(id || 0); + if (!Number.isFinite(normalizedId) || normalizedId <= 0) { + throw this.createBusinessError('id 必填且必须为正整数', 400); + } + + const record = await ctx.model.ReturnReceived.findOne({ + where: { id: normalizedId }, + raw: true, + }); + if (!record) { + throw this.createBusinessError('登记记录不存在', 404); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (warehouseId > 0 && Number(record.warehouse_id) !== warehouseId) { + throw this.createBusinessError('无权访问该登记记录', 403); + } + + return record; + } + + /** + * 组装登记记录展示字段(是否原单退回、货主备注、时间格式化)。 + * + * @param {Object} row 登记记录原始数据。 + * @param {Map} [remarkMap] 预解析的货主备注映射(key=store_id:warehouse_id), + * 传入时跳过逐行查询直接取映射值;不传时逐行查询。 + * @return {Promise} 组装后的记录。 + */ + async _enrichReturn(row, remarkMap = null) { + const { app } = this; + const record = { ...row }; + record.is_original_return = Boolean(record.order_express_id); + if (remarkMap instanceof Map) { + const remarkKey = `${Number(record.store_id || 0)}:${Number(record.warehouse_id || 0)}`; + record.store_remark = remarkMap.get(remarkKey) || ''; + } else { + record.store_remark = await this._resolveStoreRemark(record); + } + // 时间格式化(与 afterSale._formatAfterSaleRow 一致,直接覆盖为本地时间字符串) + record.scan_date = record.scan_date ? app.formatDate(record.scan_date, 'YYYY-MM-DD') : null; + record.created_at = record.created_at ? app.formatDate(record.created_at) : null; + record.updated_at = record.updated_at ? app.formatDate(record.updated_at) : null; + return record; + } + + /** + * 查询货主合约备注名称(wms_store_warehouse.store_remask)。 + * + * @param {Object} record 登记记录。 + * @return {Promise} 货主备注名称,无货主或未命中时返回空字符串。 + */ + async _resolveStoreRemark(record) { + const { ctx } = this; + const storeId = Number(record && record.store_id || 0); + const warehouseId = Number(record && record.warehouse_id || 0); + if (!storeId || !warehouseId) { + return ''; + } + try { + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: [ 'store_remask' ], + raw: true, + }); + return (sw && sw.store_remask) || ''; + } catch (err) { + ctx.logger.warn(`[returnReceived._resolveStoreRemark] 查询货主备注失败: ${err.message}`); + return ''; + } + } + + /** + * 批量解析货主备注映射(store_id:warehouse_id → wms_store_warehouse.store_remask)。 + * 导出时一次查询全部货主合约,避免逐行查询。 + * + * @param {Array} rows 登记记录行数组。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Promise>} key=store_id:warehouse_id → 货主备注映射。 + */ + async _resolveStoreRemarkMap(rows = [], warehouseId, Op) { + const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId || 0); + const storeIds = [ ...new Set( + (Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.store_id || 0)) + .filter(id => Number.isInteger(id) && id > 0) + ) ]; + /** @type {Map} */ + const remarkMap = new Map(); + if (storeIds.length === 0 || !Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return remarkMap; + } + try { + const contracts = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: { [Op.in]: storeIds }, warehouse_id: normalizedWarehouseId }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const contract of contracts) { + const key = `${Number(contract.store_id)}:${normalizedWarehouseId}`; + remarkMap.set(key, contract.store_remask ? String(contract.store_remask) : ''); + } + } catch (err) { + ctx.logger.warn(`[returnReceived.export] 批量解析货主备注失败: ${err.message}`); + } + return remarkMap; + } + + /** + * 根据标准化 where 条件构建 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildListWhere(where = {}, Op) { + const queryWhere = {}; + + const directFields = [ + 'warehouse_id', 'scanner_id', 'store_id', 'order_express_id', 'order_id', + 'waybill_code', 'scan_date', 'created_at', 'updated_at', 'scanner_name', + 'return_received_task_id', + ]; + + for (const field of directFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 是否原单退回(派生字段):true=有关联运单,false=无关联 + if (where.is_original_return !== undefined && where.is_original_return !== null) { + const flag = this._extractConditionValue(where.is_original_return); + if (flag === true || flag === 1 || flag === '1' || flag === 'true') { + queryWhere.order_express_id = { [Op.ne]: null }; + } else { + queryWhere.order_express_id = null; + } + } + + return queryWhere; + } + + /** + * 解析标准化条件值为 Sequelize 可用的条件对象。 + * + * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。 + * @param {Object} Op Sequelize Op 对象。 + * @return {*} Sequelize 条件。 + */ + _resolveConditionValue(condition, Op) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const operator = condition.operator; + const value = condition.value; + + if (!operator) { + return value; + } + + switch (operator) { + case 'eq': + return value; + case 'ne': + return { [Op.ne]: value }; + case 'in': + return { [Op.in]: Array.isArray(value) ? value : [ value ] }; + case 'notin': + return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; + case 'like': + if (Array.isArray(value) && value.length > 0) { + return { + [Op.or]: value.map(item => ({ [Op.like]: `%${item}%` })), + }; + } + return { [Op.like]: `%${value}%` }; + case 'gt': + return { [Op.gt]: value }; + case 'gte': + return { [Op.gte]: value }; + case 'lt': + return { [Op.lt]: value }; + case 'lte': + return { [Op.lte]: value }; + case 'between': + return { [Op.between]: Array.isArray(value) ? value : [ value ] }; + default: + return value; + } + } + + return condition; + } + + /** + * 从条件对象中提取原始 value。 + * + * @param {*} condition 标准化条件。 + * @return {*} 原始值。 + */ + _extractConditionValue(condition) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + if ('value' in condition) { + return condition.value; + } + } + return condition; + } + + /** + * 根据 sort 参数构建 Sequelize 排序数组。 + * + * @param {Object} sort 排序参数。 + * @return {Array>} Sequelize order 数组。 + */ + _buildListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field || 'created_at'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + const allowedSortFields = new Set([ 'id', 'scan_date', 'created_at', 'updated_at', 'waybill_code' ]); + const safeSortField = allowedSortFields.has(sortField) ? sortField : 'created_at'; + + return [[ safeSortField, sortOrder ]]; + } +} + +module.exports = ReturnReceivedService; diff --git a/app/service/systems/return_received_task.js b/app/service/systems/return_received_task.js new file mode 100644 index 0000000..cda7e68 --- /dev/null +++ b/app/service/systems/return_received_task.js @@ -0,0 +1,535 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 批次号前缀(RT=Return(Received) Task) */ +const BATCH_NO_PREFIX = 'RT'; +/** 批次号当日序号位宽(5 位补零) */ +const BATCH_NO_SEQUENCE_WIDTH = 5; +/** 序列表业务类型(wms_number_sequence.biz_type,全局维度 warehouse_id=0) */ +const BATCH_NO_BIZ_TYPE = 'return_received_task_batch_no'; + +/** + * 收件任务模块业务逻辑层(退回收件任务分组)。 + * 负责 wms_return_received_task(收件任务表)的创建与删除。 + * 所有数据库交互集中在此层,供 systemMethods/returnReceivedTask.js 调用。 + */ +class ReturnReceivedTaskService extends Service { + /** + * 创建带业务错误码的异常对象。 + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 创建收件任务。 + * 仓库与创建人均由方法层从登录上下文注入,前端不传; + * 批次号一律由服务端自动生成(RT+YYYYMMDD+5位序号,参考波次号取号机制), + * 不接收外部输入。 + * + * @param {Object} params 创建参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {string} [params.title] 标题(任务名称),缺省为空串。 + * @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。 + * @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。 + * @return {Promise} 新建的收件任务行(时间字段为格式化字符串)。 + * @throws {Error} 参数非法时抛出业务错误(错误码 400)。 + */ + async create({ warehouseId, title, creatorId, creatorName }) { + const { ctx, app } = this; + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + const normalizedTitle = title ? String(title).trim() : ''; + if (normalizedTitle.length > 100) { + throw this.createBusinessError('标题过长(最多100字符)'); + } + + const record = await ctx.model.ReturnReceivedTask.create({ + batch_no: await this.generateBatchNo(), + title: normalizedTitle, + warehouse_id: normalizedWarehouseId, + creator_id: creatorId ? Number(creatorId) : 0, + creator_name: creatorName ? String(creatorName).trim() : '', + }); + + const row = record.get({ plain: true }); + return { + ...row, + created_at: row.created_at ? app.formatDate(row.created_at, 'YYYY-MM-DD HH:mm:ss') : '', + updated_at: row.updated_at ? app.formatDate(row.updated_at, 'YYYY-MM-DD HH:mm:ss') : '', + }; + } + + /** + * 分页查询收件任务列表(仓库隔离由方法层注入 warehouse_id,系统级任务 warehouse_id=0 一并可见)。 + * + * 搜索关键词(where 直接传字符串默认模糊匹配,也支持 {operator, value} 标准结构): + * title(标题)、batch_no(编号)、creator_name(创建人)。 + * 其他字段:id/creator_id/warehouse_id 等值或 in、created_at/updated_at 范围; + * has_register(是否有登记):true=仅看有登记任务,false=仅看无登记任务(按 wms_return_received 引用判定)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {number} [pagination.page=1] 页码。 + * @param {number} [pagination.pageSize=20] 每页数量。 + * @param {Object} [sort] 排序参数。 + * @param {string} [sort.sortField] 排序字段。 + * @param {string} [sort.sortOrder] 排序顺序(asc/desc)。 + * @param {number} [warehouseId=0] 当前仓库ID(由方法层从上下文注入)。 + * 用于把登记数量与「是否有登记」统计限定在当前仓库:系统级任务(如「历史收件」id=1) + * 被各仓库共用,register_count/has_register 只统计当前仓库的登记行,避免跨仓。 + * @return {Promise} { list: Array, pagination: Object }, + * list 每行含 register_count(该任务在当前仓库下的退回收件登记数量,无登记为 0)。 + */ + async list(where = {}, pagination = {}, sort = {}, warehouseId = 0) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + const normalizedWarehouseId = Number(warehouseId); + const statWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : 0; + + const queryWhere = this._buildTaskListWhere(where, Op, statWarehouseId); + const order = this._buildTaskListOrder(sort); + + const { count, rows } = await ctx.model.ReturnReceivedTask.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + // 任务登记数量:按任务ID分组统计当前仓库的登记行数(一次分组查询,避免系统级任务跨仓统计) + const taskIds = rows.map(row => Number(row.id)).filter(id => id > 0); + const registerCountMap = new Map(); + if (taskIds.length > 0) { + const statWhere = { return_received_task_id: { [Op.in]: taskIds } }; + if (statWarehouseId > 0) { + statWhere.warehouse_id = statWarehouseId; + } + const statRows = await ctx.model.ReturnReceived.findAll({ + attributes: [ + 'return_received_task_id', + [ app.Sequelize.fn('COUNT', app.Sequelize.col('return_received_task_id')), 'register_count' ], + ], + where: statWhere, + group: [ 'return_received_task_id' ], + raw: true, + }); + for (const stat of statRows) { + registerCountMap.set(Number(stat.return_received_task_id), Number(stat.register_count || 0)); + } + } + + const list = rows.map(row => ({ + ...row, + register_count: registerCountMap.get(Number(row.id)) || 0, + created_at: row.created_at ? app.formatDate(row.created_at, 'YYYY-MM-DD HH:mm:ss') : '', + updated_at: row.updated_at ? app.formatDate(row.updated_at, 'YYYY-MM-DD HH:mm:ss') : '', + })); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 根据标准化 where 条件构建收件任务列表查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @param {number} [warehouseId=0] 当前仓库ID(has_register 判定按当前仓库过滤,避免跨仓)。 + * @return {Object} Sequelize where 条件。 + */ + _buildTaskListWhere(where = {}, Op, warehouseId = 0) { + const { app } = this; + const queryWhere = {}; + + // 搜索关键词字段:标题/编号/创建人,支持 {operator,value} 标准结构(like 模糊/eq 精确等) + for (const field of [ 'title', 'batch_no', 'creator_name' ]) { + const raw = where[field]; + if (raw === undefined || raw === null) { + continue; + } + queryWhere[field] = this._resolveTaskConditionValue(raw, Op); + } + + // 快捷搜索关键词:在 title/batch_no/creator_name 三个字段中 OR 模糊匹配 + if (where.quickWhere !== undefined && where.quickWhere !== null) { + const quickRaw = this._extractTaskConditionValue(where.quickWhere); + const quickValue = this._extractTaskConditionValue(quickRaw); + if (quickValue !== undefined && quickValue !== null && String(quickValue).trim() !== '') { + const likePattern = { [Op.like]: `%${String(quickValue).trim()}%` }; + queryWhere[Op.or] = [ + { title: likePattern }, + { batch_no: likePattern }, + { creator_name: likePattern }, + ]; + } + } + + // 是否有登记(派生筛选):true=仅看有登记的任务,false=仅看无登记的任务;按当前仓库过滤,避免跨仓 + if (where.has_register !== undefined && where.has_register !== null) { + const hasValue = this._extractTaskConditionValue(where.has_register); + const flag = hasValue === true || hasValue === 1 || hasValue === '1' || hasValue === 'true'; + const registerSubSql = warehouseId > 0 + ? `(SELECT DISTINCT return_received_task_id FROM wms_return_received WHERE warehouse_id = ${Number(warehouseId)})` + : '(SELECT DISTINCT return_received_task_id FROM wms_return_received)'; + queryWhere.id = flag + ? { [Op.in]: app.Sequelize.literal(registerSubSql) } + : { [Op.notIn]: app.Sequelize.literal(registerSubSql) }; + } + + // 数值字段:等值/in/范围 + for (const field of [ 'id', 'creator_id', 'warehouse_id' ]) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveTaskConditionValue(where[field], Op); + } + } + + // 时间字段 + for (const field of [ 'created_at', 'updated_at' ]) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveTaskConditionValue(where[field], Op); + } + } + + return queryWhere; + } + + /** + * 解析标准化条件值为 Sequelize 可用的条件对象。 + * + * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。 + * @param {Object} Op Sequelize Op 对象。 + * @return {*} Sequelize 条件。 + */ + _resolveTaskConditionValue(condition, Op) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const operator = condition.operator; + const value = condition.value; + + if (!operator) { + return value; + } + + switch (operator) { + case 'eq': + return value; + case 'ne': + return { [Op.ne]: value }; + case 'in': + return { [Op.in]: Array.isArray(value) ? value : [ value ] }; + case 'notin': + return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; + case 'like': + return { [Op.like]: `%${value}%` }; + case 'gt': + return { [Op.gt]: value }; + case 'gte': + return { [Op.gte]: value }; + case 'lt': + return { [Op.lt]: value }; + case 'lte': + return { [Op.lte]: value }; + case 'between': + return { [Op.between]: Array.isArray(value) ? value : [ value ] }; + default: + return value; + } + } + + return condition; + } + + /** + * 根据 sort 参数构建 Sequelize 排序数组。 + * + * @param {Object} sort 排序参数。 + * @return {Array>} Sequelize order 数组。 + */ + _buildTaskListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field || 'id'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + const allowedSortFields = new Set([ 'id', 'batch_no', 'created_at', 'updated_at' ]); + const safeSortField = allowedSortFields.has(sortField) ? sortField : 'id'; + + return [[ safeSortField, sortOrder ]]; + } + + /** + * 从条件对象中提取原始 value。 + * + * @param {*} condition 标准化条件。 + * @return {*} 原始值。 + */ + _extractTaskConditionValue(condition) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + if ('value' in condition) { + return condition.value; + } + } + return condition; + } + + /** + * 获取当前日期片段(YYYYMMDD)。 + * + * @return {string} 当前日期片段。 + */ + getCurrentDatePart() { + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; + } + + /** + * 生成收件任务批次号(原子取号,参考波次号 getNextWaveNoSequence 口径)。 + * + * 格式:RT + YYYYMMDD + 5位序号(如 RT2026100500001)。 + * 基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date + * 串行化并发事务,biz_type=return_received_task_batch_no,全局维度 warehouse_id=0), + * 并对齐当日主表已有最大序号(历史编号不跳号); + * upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq, + * 避免 REPEATABLE READ 快照读读到旧值。 + * + * @return {Promise} 批次号。 + */ + async generateBatchNo() { + const { ctx } = this; + const datePart = this.getCurrentDatePart(); + const pattern = `${BATCH_NO_PREFIX}${datePart}%`; + const prefixDatePartLength = BATCH_NO_PREFIX.length + datePart.length; + + // 历史对齐种子:当日主表已有最大序号(无则为 0) + const seedRows = await ctx.model.query( + `SELECT IFNULL(MAX(CAST(SUBSTRING(batch_no, :startPos) AS UNSIGNED)), 0) AS max_seq + FROM wms_return_received_task + WHERE batch_no LIKE :pattern`, + { + replacements: { + pattern, + startPos: prefixDatePartLength + 1, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq || 0); + + // 原子取号:全局维度(warehouse_id=0)按「业务类型+日期」递增,唯一键串行化并发事务 + await ctx.model.query( + `INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at) + VALUES (0, :bizType, :datePart, :seed + 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`, + { + replacements: { + bizType: BATCH_NO_BIZ_TYPE, + datePart, + seed, + }, + } + ); + + // 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化), + // FOR UPDATE 返回最新提交版本,不受旧快照影响 + const seqRows = await ctx.model.query( + `SELECT current_seq + FROM wms_number_sequence + WHERE warehouse_id = 0 AND biz_type = :bizType AND date_part = :datePart + FOR UPDATE`, + { + replacements: { + bizType: BATCH_NO_BIZ_TYPE, + datePart, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const sequence = Number(seqRows && seqRows[0] && seqRows[0].current_seq || 0); + const safeSequence = Number.isInteger(sequence) && sequence > 0 ? sequence : 1; + + return `${BATCH_NO_PREFIX}${datePart}${String(safeSequence).padStart(BATCH_NO_SEQUENCE_WIDTH, '0')}`; + } + + /** + * 批量删除收件任务(硬删除)。 + * + * 规则(逐条分流,不整体报错): + * 1. 任务不存在、系统预设(id=1「历史收件」)、非当前仓库任务 → 计入 skipped_ids; + * 2. 任务下已有收件登记(wms_return_received.return_received_task_id 引用)→ 409 口径计入 skipped_ids; + * 3. 其余任务硬删除,并清理任务缓存 return_received_task:{id}。 + * + * @param {Object} params 批量删除参数。 + * @param {number} params.warehouseId 当前仓库ID(由方法层从上下文注入)。 + * @param {Array|number} params.ids 收件任务ID(数组或单个数值,单次上限 200)。 + * @return {Promise} { total, deleted_count, skipped_count, deleted_ids, skipped_ids }, + * deleted_ids/skipped_ids 保持入参顺序。 + * @throws {Error} 仓库上下文缺失、ids 为空或超过上限时抛出业务错误(错误码 400)。 + */ + async batchDelete(params = {}) { + const { warehouseId, ids } = params; + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + // ids 归一化:单值转数组、去重、只保留正整数 + const idSource = Array.isArray(ids) ? ids : [ ids ]; + const numericIds = [ ...new Set(idSource.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ]; + if (numericIds.length === 0) { + throw this.createBusinessError('ids 不能为空'); + } + if (numericIds.length > 200) { + throw this.createBusinessError('单次最多删除 200 个收件任务'); + } + + // 查询任务(不限定仓库,便于区分「不存在/系统预设/无权」三种跳过原因) + const taskRows = await ctx.model.ReturnReceivedTask.findAll({ + where: { id: { [Op.in]: numericIds } }, + attributes: [ 'id', 'warehouse_id', 'title' ], + raw: true, + }); + const taskMap = new Map(taskRows.map(row => [ Number(row.id), row ])); + + // 登记引用计数(本仓库口径一致:普通任务登记都在本仓库) + const usedRows = await ctx.model.ReturnReceived.findAll({ + attributes: [ + 'return_received_task_id', + [ app.Sequelize.fn('COUNT', app.Sequelize.col('return_received_task_id')), 'register_count' ], + ], + where: { return_received_task_id: { [Op.in]: numericIds } }, + group: [ 'return_received_task_id' ], + raw: true, + }); + const usedCountMap = new Map(); + for (const stat of usedRows) { + usedCountMap.set(Number(stat.return_received_task_id), Number(stat.register_count || 0)); + } + + // 逐条分流(保持入参顺序) + const deletedIds = []; + const skippedIds = []; + for (const taskId of numericIds) { + const row = taskMap.get(taskId); + if (!row) { + skippedIds.push(taskId); + continue; + } + if (Number(row.id) === 1) { + skippedIds.push(taskId); // 系统预设不可删除 + continue; + } + if (Number(row.warehouse_id) !== normalizedWarehouseId) { + skippedIds.push(taskId); // 非本仓库无权操作 + continue; + } + if ((usedCountMap.get(taskId) || 0) > 0) { + skippedIds.push(taskId); // 已有收件登记不可删除 + continue; + } + deletedIds.push(taskId); + } + + if (deletedIds.length > 0) { + await ctx.model.ReturnReceivedTask.destroy({ where: { id: { [Op.in]: deletedIds } } }); + + // 清理任务缓存(登记校验缓存 return_received_task:{id}) + for (const taskId of deletedIds) { + await app.delCacheAsync(`return_received_task:${taskId}`); + } + } + + return { + total: numericIds.length, + deleted_count: deletedIds.length, + skipped_count: skippedIds.length, + deleted_ids: deletedIds, + skipped_ids: skippedIds, + }; + } + + /** + * 删除单个收件任务(兼容入口,硬删除)。 + * 单值语义与批量删除一致:不满足删除条件时抛出对应业务错误(不静默跳过)。 + * + * @param {number|string} taskId 收件任务ID。 + * @param {number} warehouseId 当前仓库ID(由方法层从上下文注入)。 + * @return {Promise} { id, deleted: true }。 + */ + async delete(taskId, warehouseId) { + const { ctx, app } = this; + + const normalizedId = Number(taskId); + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + throw this.createBusinessError('收件任务ID不合法'); + } + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + const task = await ctx.model.ReturnReceivedTask.findOne({ + where: { id: normalizedId }, + attributes: [ 'id', 'warehouse_id', 'title' ], + raw: true, + }); + if (!task) { + throw this.createBusinessError('收件任务不存在', 404); + } + + // 系统预设「历史收件」不可删除 + if (Number(task.id) === 1) { + throw this.createBusinessError('系统预设任务不可删除', 404); + } + + // 归属校验:任务必须属于当前仓库 + if (Number(task.warehouse_id) !== normalizedWarehouseId) { + throw this.createBusinessError('收件任务不存在或无权操作', 404); + } + + // 已有登记不可删除 + const usedCount = await ctx.model.ReturnReceived.count({ + where: { return_received_task_id: normalizedId }, + }); + if (usedCount > 0) { + throw this.createBusinessError('该任务已有收件登记,无法删除', 409); + } + + await ctx.model.ReturnReceivedTask.destroy({ where: { id: normalizedId } }); + + // 清理任务缓存(登记校验缓存 return_received_task:{id}) + await app.delCacheAsync(`return_received_task:${normalizedId}`); + + return { id: normalizedId, deleted: true }; + } +} + +module.exports = ReturnReceivedTaskService; diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js new file mode 100644 index 0000000..242f509 --- /dev/null +++ b/app/service/systems/return_unpack.js @@ -0,0 +1,3568 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); +const Service = require('egg').Service; + +/** 退回拆包导出主表分页拉取大小 */ +const RETURN_UNPACK_EXPORT_PAGE_SIZE = 500; +/** 退回拆包导出明细分批拉取大小 */ +const RETURN_UNPACK_DETAIL_BATCH_SIZE = 100; + +/** + * 退回拆包模块业务逻辑层。 + * 负责 wms_return_unpack(主表)/ wms_return_unpack_detail(明细)/ wms_return_unpack_video(视频)/ + * wms_return_query_log(退回查询记录)的增删查,以及原单反查、货主校验、单号生成等核心操作。 + * 所有数据库交互集中在此层,供 systemMethods/returnUnpack.js 调用。 + */ +class ReturnUnpackService extends Service { + /** + * 获取仓库的录制电脑 ID(带缓存)。 + * 与 order_packing 一致:从 wms_print_computer 按 is_recording=true 获取。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 录制电脑ID,找不到返回 null + */ + async _getRecordingComputerId(warehouseId) { + const cacheKey = `_recordingComputer_${warehouseId}`; + if (this[cacheKey] !== undefined) { + return this[cacheKey]; + } + const row = await this.ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + attributes: [ 'id' ], + raw: true, + }); + this[cacheKey] = row ? row.id : null; + return this[cacheKey]; + } + + /** + * 构建视频完整 URL(与 order.packing 一致)。 + * 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath} + * @param {number} warehouseId 仓库ID + * @param {number|null} recordingComputerId 录制电脑ID + * @param {string} videoPath 视频路径 + * @return {string} 完整 URL + */ + _buildVideoUrl(warehouseId, recordingComputerId, videoPath) { + if (!videoPath || !recordingComputerId) { + return videoPath || ''; + } + return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${videoPath}`; + } + + /** + * 创建带业务错误码的异常对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 开拆包单(明细不在此提交,由 addDetail 逐件录入)。 + * 用 waybill_code 反查原运单判定是否原单退回;未命中原单时再从退回查询记录表反查货主。 + * + * @param {Object} params 开单参数。 + * @param {string} params.waybill_code 拆包的运单号(必填)。 + * @param {Array} [params.camera_ids] 摄像头ID列表。 + * @param {number} [params.return_received_id] 关联退回收到单ID。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 开单结果,含 id、record、is_original_return、store_remark、order、order_items。 + */ + async create({ waybill_code, camera_ids, return_received_id, remark }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + const unpackerId = ctx.user && ctx.user.employees_id ? Number(ctx.user.employees_id) : 0; + const unpackerName = String( + (ctx.user && ctx.user.employees_name) || (ctx.user && ctx.user.real_name) || '' + ).trim(); + + if (!Number.isFinite(unpackerId) || unpackerId <= 0) { + throw this.createBusinessError('缺少拆包人员工号上下文', 400); + } + + // 摄像头ID列表归一化 + let normalizedCameraIds = null; + if (Array.isArray(camera_ids)) { + normalizedCameraIds = camera_ids + .map(item => Number(item)) + .filter(id => Number.isInteger(id) && id > 0); + } + + // 1. 幂等复用:同一仓库同一运单号 3 个月内已开过拆包单时,不重复创建,直接返回已有明细 + const threeMonthsAgo = new Date(); + threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3); + try { + const existingList = await ctx.model.ReturnUnpack.findAll({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + created_at: { [Op.gte]: threeMonthsAgo }, + status: { [Op.ne]: 'cancelled' }, + }, + attributes: [ 'id', 'order_express_id', 'created_at' ], + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + let existing = null; + if (existingList.length > 0) { + existing = existingList[0]; + // 同运单号可能有多张拆包单(并发/重复点击产生的空单):优先复用已录明细的最新单, + // 避免命中最新空单导致"返回明细为空"(按明细表真实计数判断,不依赖主表冗余汇总) + const countRows = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: { [Op.in]: existingList.map(row => row.id) } }, + attributes: [ + 'unpack_id', + [ ctx.model.fn('COUNT', ctx.model.col('id')), 'detail_count' ], + ], + group: [ 'unpack_id' ], + raw: true, + }); + const detailCountMap = new Map( + countRows.map(row => [ Number(row.unpack_id), Number(row.detail_count) || 0 ]) + ); + const withDetails = existingList.find(row => (detailCountMap.get(Number(row.id)) || 0) > 0); + if (withDetails) { + existing = withDetails; + } + } + + if (existing) { + // 复用已有拆包单:返回主表 + 明细 + 视频 + 原订单详情(复用 detail 查询逻辑) + const existingDetail = await this.detail(existing.id); + const existingOrder = (existingDetail.related && existingDetail.related.order) || null; + ctx.logger.info( + `[returnUnpack.create] 运单号 ${waybillCode} 3 个月内已有拆包单 id=${existing.id},直接复用返回明细` + ); + return { + id: existing.id, + record: existingDetail.record, + is_original_return: Boolean(existing.order_express_id), + store_remark: String(existingDetail.record && existingDetail.record.shop_name || ''), + order: existingOrder, + order_items: existingOrder && Array.isArray(existingOrder.items) ? existingOrder.items : null, + reused: true, + }; + } + } catch (err) { + // 查重失败不阻断开单主流程 + ctx.logger.warn(`[returnUnpack.create] 查重已有拆包单失败: ${err.message}`); + } + + // 2. 原单反查:命中则回填原单关联字段 + let orderExpressId = null; + let orderId = null; + let storeId = null; + let sourceOrderCodes = null; + try { + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: waybillCode }, + attributes: [ 'id', 'order_id', 'store_id', 'source_order_codes' ], + raw: true, + }); + if (orderExpress) { + orderExpressId = orderExpress.id; + orderId = orderExpress.order_id; + storeId = orderExpress.store_id; + sourceOrderCodes = orderExpress.source_order_codes || null; + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.create] 反查原运单失败: ${err.message}`); + } + + // 3. 未命中原单:从退回查询记录表反查货主(限最近 3 个月内登记,运单号可能被复用) + if (!orderExpressId) { + try { + const queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + created_at: { [Op.gte]: threeMonthsAgo }, + }, + attributes: [ 'store_id' ], + order: [[ 'created_at', 'DESC' ]], + raw: true, + }); + if (queryLog && queryLog.store_id) { + storeId = queryLog.store_id; + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.create] 反查退回查询记录失败: ${err.message}`); + } + } + + const isOriginalReturn = Boolean(orderExpressId); + + // 4. 货主备注(原单退回 / 反查命中货主时) + const storeRemark = await this._resolveStoreRemark(storeId, warehouseId); + + // 5. 拆包日期/开始时间(单号在下方重试循环内生成) + const now = new Date(); + const unpackDate = app.formatDate(now, 'YYYY-MM-DD'); + + // 6. 插入主表(并发下撞 uk_unpack_no 唯一索引时重新取号重试,最多 5 次,指数退避+随机抖动) + const baseFields = { + warehouse_id: warehouseId, + return_received_id: return_received_id ? Number(return_received_id) || null : null, + waybill_code: waybillCode, + unpack_date: unpackDate, + start_time: now, + end_time: null, + unpacker_id: unpackerId, + unpacker_name: unpackerName || '未命名', + status: 'unpacking', + detail_status: 'none_recognized', + total_items: 0, + total_quantity: 0, + order_express_id: orderExpressId, + order_id: orderId, + store_id: storeId, + source_order_codes: sourceOrderCodes, + shop_name: storeRemark || null, + camera_ids: normalizedCameraIds, + remark: remark ? String(remark).slice(0, 500) : null, + }; + + const createdRow = await this._insertMainWithRetry(baseFields, warehouseId, 'create'); + + // 7. 原订单详情(仅原单退回时拉取,参考 afterSale.detail._resolveOrderDetail) + let order = null; + if (isOriginalReturn && orderId) { + try { + order = await ctx.service.systems.afterSale._resolveOrderDetail(orderId, warehouseId); + } catch (err) { + ctx.logger.warn(`[returnUnpack.create] 拉取原订单详情失败: ${err.message}`); + } + } + + return { + id: createdRow.id, + record: await this._enrichRow(createdRow), + is_original_return: isOriginalReturn, + store_remark: storeRemark, + order, + order_items: order && Array.isArray(order.items) ? order.items : null, + }; + } + + /** + * 运单批量转入退件登记(退回拆包,批量)。 + * 批量入参运单表主键 ID(wms_order_express.id):过滤非正整数 + 去重,单次上限 200; + * 逐单处理,单条失败不阻断主流程。 + * 命中的运单统一标记 wms_order_express.is_back='Y'(不做其他前置条件限制); + * 幂等:同仓库 + 同运单号已存在有效(status != 'cancelled')拆包单时直接复用, + * 复用单明细为空时按订单明细补写(优先 items JSON,为空回退明细分表)。 + * + * @param {Object} params 批量转入参数。 + * @param {Array|number} params.ids 运单表主键ID(wms_order_express.id,单个数值或数组)。 + * @return {Promise} { total, success_count, failed_count, success[], failed[] }, + * 成功项含 waybill_id/waybill_code/unpack_id/unpack_no/reused/detail_count/total_quantity, + * 失败项含 waybill_id/waybill_code(运单命中时)/reason。 + */ + async transferByWaybills({ ids }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 入参归一化:单个数值转数组,过滤非正整数 + 去重 + const rawIds = Array.isArray(ids) ? ids : [ ids ]; + const waybillIds = [ ...new Set( + rawIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0) + ) ]; + + if (waybillIds.length === 0) { + throw this.createBusinessError('ids 不能为空', 400); + } + if (waybillIds.length > 200) { + throw this.createBusinessError('单次最多批量转入 200 个运单', 400); + } + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + // 操作人上下文(与 create 完全一致) + const unpackerId = Number(ctx.user && ctx.user.employees_id || 0); + const unpackerName = String( + (ctx.user && ctx.user.employees_name) || (ctx.user && ctx.user.real_name) || '' + ).trim(); + if (!Number.isFinite(unpackerId) || unpackerId <= 0) { + throw this.createBusinessError('缺少拆包人员工号上下文', 400); + } + + // 批量反查运单:一次查询完成 运单ID + 仓库 命中判定(未命中的 ID 记为失败) + const expressMap = new Map(); + try { + const expressRows = await ctx.model.OrderExpress.findAll({ + where: { id: { [Op.in]: waybillIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'waybill_code', 'order_id', 'store_id', 'source_order_codes', 'business_key' ], + raw: true, + }); + for (const row of expressRows) { + expressMap.set(Number(row.id), row); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 批量反查运单失败: ${err.message}`); + throw this.createBusinessError('反查运单失败,请稍后重试', 500); + } + + /** @type {Array} 成功项列表 */ + const success = []; + /** @type {Array} 失败项列表 */ + const failed = []; + + for (const waybillId of waybillIds) { + const orderExpress = expressMap.get(waybillId) || null; + try { + const item = await this._transferOneWaybill({ + orderExpress, + waybillId, + warehouseId, + unpackerId, + unpackerName, + }); + success.push(item); + } catch (err) { + const reason = (err && err.message) || '转入失败'; + ctx.logger.warn(`[returnUnpack.transferByWaybills] 运单ID ${waybillId} 转入失败: ${reason}`); + failed.push({ + waybill_id: waybillId, + waybill_code: orderExpress ? String(orderExpress.waybill_code || '') : null, + reason, + }); + } + } + + return { + total: waybillIds.length, + success_count: success.length, + failed_count: failed.length, + success, + failed, + }; + } + + /** + * 配送订单批量转退回拆包单。 + * 批量入参订单主键 ID(wms_order_delivery*.id):过滤非正整数 + 去重,单次上限 200; + * 逐单处理,单条失败不阻断主流程。仅「库内拦截」订单(intercept_status=intercepted_at_warehouse, + * 兼容历史值 intercepted)可转换,其余订单(未拦截/其它拦截状态)、已存在有效拆包单的订单、 + * 无运单号/无明细的订单均静默跳过,不报错。 + * 每单新建一张拆包单:waybill_code 取订单主运单号(无运单时回退发货单号), + * 明细按订单原本明细 1:1 复制(product_status 固定 normal),创建后回填主表汇总。 + * + * @param {Object} params 批量转换参数。 + * @param {Array|number} params.ids 订单表主键ID(单个数值或数组)。 + * @return {Promise} { total, success_count, skipped_count, failed_count, success[], skipped[], failed[] }, + * 成功项含 order_id/unpack_id/unpack_no/waybill_code/detail_count/total_quantity, + * 跳过/失败项含 order_id/reason。 + */ + async transferByOrders({ ids }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 入参归一化:单个数值转数组,过滤非正整数 + 去重 + const rawIds = Array.isArray(ids) ? ids : [ ids ]; + const orderIds = [ ...new Set( + rawIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0) + ) ]; + + if (orderIds.length === 0) { + throw this.createBusinessError('ids 不能为空', 400); + } + if (orderIds.length > 200) { + throw this.createBusinessError('单次最多批量转换 200 个订单', 400); + } + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + // 操作人上下文(与 create 完全一致) + const unpackerId = Number(ctx.user && ctx.user.employees_id || 0); + const unpackerName = String( + (ctx.user && ctx.user.employees_name) || (ctx.user && ctx.user.real_name) || '' + ).trim(); + if (!Number.isFinite(unpackerId) || unpackerId <= 0) { + throw this.createBusinessError('缺少拆包人员工号上下文', 400); + } + + // 1. 批量载入订单主记录(序列表定位车道 + 分表批量查询 + 基表兜底) + const orderMap = await this._loadOrdersForTransferByOrders(orderIds, warehouseId); + + // 2. 批量载入订单原本明细(items JSON 优先,为空回退明细分表) + const itemsMap = await this._loadOrderItemsForTransferByOrders(orderMap, warehouseId); + + // 3. 批量载入订单主运单(用于回填拆包单运单号/原运单ID) + const expressMap = await this._resolveOrderExpressForTransferByOrders(orderIds, warehouseId); + + // 4. 已存在有效拆包单(同订单 或 同运单号)→ 静默跳过 + const existingOrderIdSet = new Set(); + const existingWaybillSet = new Set(); + try { + const waybillCodes = [ ...new Set( + [ + ...[ ...expressMap.values() ] + .map(row => String(row && row.waybill_code || '').trim()), + // 无运单的订单以发货单号作为拆包单运单号,查重时一并纳入 + ...orderIds.map(orderId => { + const orderEntry = orderMap.get(orderId); + return String(orderEntry && orderEntry.order && orderEntry.order.delivery_order_code || '').trim(); + }), + ].filter(Boolean) + ) ]; + const orConditions = [{ order_id: { [Op.in]: orderIds } }]; + if (waybillCodes.length > 0) { + orConditions.push({ waybill_code: { [Op.in]: waybillCodes } }); + } + const existingRows = await ctx.model.ReturnUnpack.findAll({ + where: { + warehouse_id: warehouseId, + status: { [Op.ne]: 'cancelled' }, + [Op.or]: orConditions, + }, + attributes: [ 'id', 'order_id', 'waybill_code' ], + raw: true, + }); + for (const row of existingRows) { + const existingOrderId = Number(row.order_id || 0); + if (existingOrderId > 0) { + existingOrderIdSet.add(existingOrderId); + } + const existingWaybillCode = String(row.waybill_code || '').trim(); + if (existingWaybillCode) { + existingWaybillSet.add(existingWaybillCode); + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 查询已有拆包单失败: ${err.message}`); + throw this.createBusinessError('查询已有拆包单失败,请稍后重试', 500); + } + + /** @type {Array} 成功项列表 */ + const success = []; + /** @type {Array} 静默跳过项列表 */ + const skipped = []; + /** @type {Array} 失败项列表 */ + const failed = []; + + const now = new Date(); + const unpackDate = app.formatDate(now, 'YYYY-MM-DD'); + + for (const orderId of orderIds) { + const entry = orderMap.get(orderId) || null; + const order = entry ? entry.order || {} : null; + + // 静默跳过:订单不存在/不属于当前仓库 + if (!order) { + skipped.push({ order_id: orderId, reason: '订单不存在或不属于当前仓库' }); + continue; + } + + // 静默跳过:仅允许库内拦截订单 + if (!this._isWarehouseInterceptedOrderStatus(order.intercept_status)) { + skipped.push({ order_id: orderId, reason: '非库内拦截订单' }); + continue; + } + + // 静默跳过:已有有效拆包单 + if (existingOrderIdSet.has(orderId)) { + skipped.push({ order_id: orderId, reason: '订单已存在拆包单' }); + continue; + } + + const orderExpress = expressMap.get(orderId) || null; + const waybillCode = String( + (orderExpress && orderExpress.waybill_code) || order.delivery_order_code || '' + ).trim(); + if (!waybillCode) { + skipped.push({ order_id: orderId, reason: '订单无运单号,无法创建拆包单' }); + continue; + } + + // 同运单号已有有效拆包单(可能由运单转入等入口创建)→ 静默跳过 + if (existingWaybillSet.has(waybillCode)) { + skipped.push({ order_id: orderId, reason: '运单号已存在拆包单' }); + continue; + } + + const orderItems = itemsMap.get(orderId) || []; + if (orderItems.length === 0) { + skipped.push({ order_id: orderId, reason: '订单无明细可复制' }); + continue; + } + + try { + const storeId = Number(order.store_id || 0) + || Number(orderExpress && orderExpress.store_id || 0) + || null; + const storeRemark = await this._resolveStoreRemark(storeId, warehouseId); + const returnReceivedId = await this._resolveReturnReceivedId(warehouseId, waybillCode); + + const createdRow = await this._insertMainWithRetry({ + warehouse_id: warehouseId, + return_received_id: returnReceivedId, + waybill_code: waybillCode, + unpack_date: unpackDate, + start_time: now, + end_time: null, + unpacker_id: unpackerId, + unpacker_name: unpackerName || '未命名', + status: 'unpacking', + detail_status: 'none_recognized', + total_items: 0, + total_quantity: 0, + order_express_id: orderExpress ? orderExpress.id : null, + order_id: orderId, + store_id: storeId, + source_order_codes: order.source_order_codes + || (orderExpress && orderExpress.source_order_codes) + || null, + shop_name: storeRemark || null, + camera_ids: null, + remark: null, + }, warehouseId, 'transferByOrders'); + + const unpackId = Number(createdRow.id); + + // 明细 1:1 复制订单原本明细(product_status 固定 normal),插入后回填主表汇总 + const detailRows = await this._buildTransferDetailRows(orderItems); + await ctx.model.ReturnUnpackDetail.bulkCreate( + detailRows.map(row => ({ ...row, unpack_id: unpackId, warehouse_id: warehouseId })) + ); + const summary = await this._recalcMain(unpackId, warehouseId); + + // 同批内后续重复订单/运单不再重复创建 + existingOrderIdSet.add(orderId); + existingWaybillSet.add(waybillCode); + + success.push({ + order_id: orderId, + unpack_id: unpackId, + unpack_no: createdRow.unpack_no || '', + waybill_code: waybillCode, + detail_count: summary.total_items, + total_quantity: summary.total_quantity, + }); + } catch (err) { + const reason = (err && err.message) || '转换失败'; + ctx.logger.warn(`[returnUnpack.transferByOrders] 订单ID ${orderId} 转换失败: ${reason}`); + failed.push({ order_id: orderId, reason }); + } + } + + return { + total: orderIds.length, + success_count: success.length, + skipped_count: skipped.length, + failed_count: failed.length, + success, + skipped, + failed, + }; + } + + /** + * 判断订单拦截状态是否为「库内拦截」。 + * 库内确定拦截由 recheckOrder.confirmIntercept / intercept_auto_confirm 写入 + * intercepted_at_warehouse;历史遗留值 intercepted 一并兼容。 + * + * @param {*} status 拦截状态值。 + * @return {boolean} 是否库内拦截。 + */ + _isWarehouseInterceptedOrderStatus(status) { + const normalizedStatus = String(status || '').trim(); + return normalizedStatus === 'intercepted_at_warehouse' || normalizedStatus === 'intercepted'; + } + + /** + * 批量载入订单主记录:序列表定位车道 → 分表批量查询 → 基表兜底。 + * 仅返回属于当前仓库的订单(warehouse_id 为空的历史数据不额外拦截)。 + * + * @param {Array} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} orderId → { order, lane }。 + */ + async _loadOrdersForTransferByOrders(orderIds, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const result = new Map(); + const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ]; + const attributes = [ + 'id', 'warehouse_id', 'store_id', 'delivery_order_code', + 'source_order_codes', 'intercept_status', 'items', + ]; + + const factory = ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + return result; + } + + const laneGetters = { + current: () => factory.getCurrentModel(warehouseId), + history: () => factory.getHistoryModel(warehouseId), + dispatch: () => factory.getDispatchModel(warehouseId), + outsourced: () => factory.getOutsourcedModel(warehouseId), + }; + + // 序列表定位优先:命中车道只查对应分表,未命中按全车道遍历 + const locationMap = new Map(); + try { + if (typeof factory.getOrderLocations === 'function') { + const located = await factory.getOrderLocations(orderIds, warehouseId); + for (const [ orderId, lane ] of located.entries()) { + locationMap.set(Number(orderId), String(lane)); + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 序列表定位失败: ${err.message}`); + } + + const laneOrderIds = new Map(); + for (const orderId of orderIds) { + const lane = locationMap.get(orderId); + const targets = lane && laneGetters[lane] ? [ lane ] : laneLabels; + for (const targetLane of targets) { + if (!laneOrderIds.has(targetLane)) { + laneOrderIds.set(targetLane, []); + } + laneOrderIds.get(targetLane).push(orderId); + } + } + + for (const lane of laneLabels) { + const ids = (laneOrderIds.get(lane) || []).filter(id => !result.has(id)); + if (ids.length === 0) continue; + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findAll !== 'function') continue; + const rows = await model.findAll({ + where: { id: { [Op.in]: ids } }, + attributes, + raw: true, + }); + for (const row of rows) { + const orderId = Number(row.id || 0); + if (orderId <= 0) continue; + if (row.warehouse_id !== null && row.warehouse_id !== undefined + && Number(row.warehouse_id) !== warehouseId) { + continue; + } + result.set(orderId, { order: row, lane }); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 查询 ${lane} 分表失败: ${err.message}`); + } + } + + // 分表均未命中:回退基表(存量订单) + const missingIds = orderIds.filter(id => !result.has(id)); + if (missingIds.length > 0) { + try { + const rows = await ctx.model.OrderDelivery.findAll({ + where: { id: { [Op.in]: missingIds } }, + attributes, + raw: true, + }); + for (const row of rows) { + const orderId = Number(row.id || 0); + if (orderId <= 0) continue; + if (row.warehouse_id !== null && row.warehouse_id !== undefined + && Number(row.warehouse_id) !== warehouseId) { + continue; + } + result.set(orderId, { order: row, lane: null }); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 查询订单基表失败: ${err.message}`); + } + } + + return result; + } + + /** + * 批量载入订单原本明细:优先解析订单 items JSON 数组,为空时按订单所在车道 + * 批量查询明细分表(订单无车道索引时遍历 current/dispatch/history)。 + * 输出统一为下划线字段(stock_id/item_code/item_name/plan_qty),供复制明细使用。 + * + * @param {Map} orderMap 订单载入结果(orderId → { order, lane })。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>>} orderId → 明细行数组。 + */ + async _loadOrderItemsForTransferByOrders(orderMap, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const itemsMap = new Map(); + const laneLabels = [ 'current', 'dispatch', 'history' ]; + + // 1. 订单 items JSON 优先(存量/兼容路径),统一归一化为下划线字段 + const needDbOrderIds = []; + for (const [ orderId, entry ] of orderMap.entries()) { + const inlineItems = this._parseOrderItemsJson(entry && entry.order && entry.order.items); + if (inlineItems.length > 0) { + itemsMap.set(orderId, inlineItems); + } else { + needDbOrderIds.push(orderId); + } + } + + const factory = ctx.model.OrderItemsFactory; + if (!factory || needDbOrderIds.length === 0) { + return itemsMap; + } + + const laneGetters = { + current: () => factory.getCurrentModel(warehouseId), + history: () => factory.getHistoryModel(warehouseId), + dispatch: () => factory.getDispatchModel(warehouseId), + }; + + // 2. 按订单车道分组批量查询(无车道索引的订单遍历三个车道) + const laneOrderIds = new Map(); + for (const orderId of needDbOrderIds) { + const entry = orderMap.get(orderId) || {}; + const lane = entry.lane && laneGetters[entry.lane] ? entry.lane : null; + const targets = lane ? [ lane ] : laneLabels; + for (const targetLane of targets) { + if (!laneOrderIds.has(targetLane)) { + laneOrderIds.set(targetLane, []); + } + laneOrderIds.get(targetLane).push(orderId); + } + } + + for (const lane of laneLabels) { + const ids = (laneOrderIds.get(lane) || []).filter(id => !itemsMap.has(id)); + if (ids.length === 0) continue; + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findAll !== 'function') continue; + const rows = await model.findAll({ + where: { order_id: { [Op.in]: ids } }, + attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty' ], + raw: true, + }); + for (const row of rows) { + const orderId = Number(row.order_id || 0); + if (orderId <= 0) continue; + if (!itemsMap.has(orderId)) { + itemsMap.set(orderId, []); + } + itemsMap.get(orderId).push(row); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 查询 ${lane} 商品明细失败: ${err.message}`); + } + } + + // 3. 指定车道未命中时兜底遍历其余车道(订单与明细分表迁移不同步) + const stillMissingIds = needDbOrderIds.filter(id => !itemsMap.has(id)); + for (const orderId of stillMissingIds) { + for (const lane of laneLabels) { + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findAll !== 'function') continue; + const rows = await model.findAll({ + where: { order_id: orderId }, + attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty' ], + raw: true, + }); + if (rows.length > 0) { + itemsMap.set(orderId, rows); + break; + } + } catch (err) { + // 该车道表可能不存在,继续下一张 + } + } + } + + return itemsMap; + } + + /** + * 解析订单 items JSON 数组(非数组/解析失败返回空数组),并归一化为下划线字段。 + * + * @param {*} raw 订单 items 原始值(字符串或数组)。 + * @return {Array} 明细行数组。 + */ + _parseOrderItemsJson(raw) { + if (!raw) { + return []; + } + let parsed = raw; + if (typeof raw === 'string') { + const trimmed = raw.trim(); + if (!trimmed.startsWith('[')) { + return []; + } + try { + parsed = JSON.parse(trimmed); + } catch (err) { + return []; + } + } + if (!Array.isArray(parsed)) { + return []; + } + return parsed.map(item => ({ + stock_id: item.stock_id !== undefined ? item.stock_id : (item.stockId !== undefined ? item.stockId : null), + item_code: item.item_code !== undefined ? item.item_code : (item.itemCode || ''), + item_name: item.item_name !== undefined ? item.item_name : (item.itemName || ''), + plan_qty: item.plan_qty !== undefined ? item.plan_qty : (item.planQty || 1), + })); + } + + /** + * 批量反查订单主运单(business_key=1 优先,其次最小 id 且有运单号的运单)。 + * + * @param {Array} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} orderId → 运单行。 + */ + async _resolveOrderExpressForTransferByOrders(orderIds, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const result = new Map(); + if (orderIds.length === 0) { + return result; + } + + try { + const rows = await ctx.model.OrderExpress.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ + 'id', 'order_id', 'waybill_code', 'business_key', + 'source_order_codes', 'store_id', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const byOrder = new Map(); + for (const row of rows) { + const orderId = Number(row.order_id || 0); + if (orderId <= 0) continue; + if (!byOrder.has(orderId)) { + byOrder.set(orderId, []); + } + byOrder.get(orderId).push(row); + } + + for (const [ orderId, list ] of byOrder.entries()) { + const withCode = list.filter(row => String(row.waybill_code || '').trim()); + if (withCode.length === 0) continue; + const mainRow = withCode.find(row => Number(row.business_key) === 1) || withCode[0]; + result.set(orderId, mainRow); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 批量反查订单运单失败: ${err.message}`); + } + + return result; + } + + /** + * 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。 + * 仅以 stock_id 识别商品;不指定 stock_id 时一律标注未知商品, + * 不做条码自动匹配(同一商品可能存在多条条码记录/多个 stock_id,自动匹配易误配)。 + * + * @param {Object} params 明细参数。 + * @param {number} params.id 拆包单ID。 + * @param {number} [params.stock_id] 系统商品ID(wms_stock_warehouse.id),为空即无关联货物(商品名称标注未知商品)。 + * @param {string} [params.barcode] 扫描条码(仅作记录,不参与商品匹配)。 + * @param {number} [params.quantity] 数量,默认 1。 + * @param {string} [params.product_status] 产品状态 normal/damaged,默认 normal。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 明细ID + 明细行 + 主表最新汇总。 + */ + async addDetail({ id, stock_id, barcode, quantity, product_status, remark }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const normalizedStockId = stock_id ? Number(stock_id) : null; + const normalizedBarcode = barcode ? String(barcode).trim().slice(0, 100) : null; + const normalizedQuantity = Math.max(1, parseInt(quantity) || 1); + const normalizedStatus = product_status === 'damaged' ? 'damaged' : 'normal'; + + // 识别到系统商品:校验货主归属 + 回填快照 + let isRecognized = 0; + let itemCode = null; + let itemName = null; + let spec = null; + let productSnapshot = null; + + if (normalizedStockId) { + const stock = await ctx.model.StockWarehouse.findOne({ + where: { id: normalizedStockId }, + raw: true, + }); + if (!stock) { + throw this.createBusinessError('系统商品不存在', 404); + } + + // 货主校验:主表已有货主则必须一致;主表货主为空则以首个识别商品回填货主 + const currentStoreId = Number(unpack.store_id || 0); + const stockStoreId = Number(stock.store_id || 0); + if (currentStoreId > 0 && stockStoreId !== currentStoreId) { + throw this.createBusinessError('该商品不属于当前货主,无法录入', 403); + } + + isRecognized = 1; + itemCode = stock.item_code || null; + itemName = stock.item_name || null; + spec = stock.sku_property || null; + productSnapshot = JSON.stringify({ + item_code: stock.item_code || '', + goods_code: stock.goods_code || '', + item_name: stock.item_name || '', + sku_property: stock.sku_property || '', + stock_unit: stock.stock_unit || '', + item_type: stock.item_type || '', + }); + + // 主表货主为空时回填(首个识别商品确定货主),并同步回填自定义店铺名称快照 + if (currentStoreId === 0 && stockStoreId > 0) { + const backfillFields = { store_id: stockStoreId }; + const shopName = await this._resolveStoreRemark(stockStoreId, unpack.warehouse_id); + if (shopName) backfillFields.shop_name = shopName; + await ctx.model.ReturnUnpack.update( + backfillFields, + { where: { id: unpack.id } } + ); + } + } else { + // 未指定系统商品:一律标注未知商品,不做条码自动匹配(同条码可能对应多个 stock_id,易误配) + itemName = '未知商品'; + } + + const created = await ctx.model.ReturnUnpackDetail.create({ + unpack_id: unpack.id, + warehouse_id: unpack.warehouse_id, + barcode: normalizedBarcode, + stock_id: normalizedStockId, + is_recognized: isRecognized, + item_code: itemCode, + item_name: itemName, + spec, + quantity: normalizedQuantity, + product_status: normalizedStatus, + product_snapshot: productSnapshot, + remark: remark ? String(remark).slice(0, 500) : null, + }); + + const summary = await this._recalcMain(unpack.id, unpack.warehouse_id); + + const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + await this._enrichDetailsWithStock([ createdRow ], Number(unpack.warehouse_id || 0)); + return { + detail_id: createdRow.id, + detail: createdRow, + ...summary, + }; + } + + /** + * 更新明细:仅允许更新数量 / 备注(白名单)。 + * + * @param {Object} params 更新参数。 + * @param {number} params.id 拆包单ID。 + * @param {number} params.detail_id 明细ID。 + * @param {number} [params.quantity] 数量。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 更新后的明细 + 主表最新汇总。 + */ + async updateDetail({ id, detail_id, quantity, remark }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const detail = await this._findDetailChecked(unpack.id, detail_id); + + const updateFields = {}; + let quantityChanged = false; + + if (quantity !== undefined && quantity !== null) { + const normalizedQuantity = Math.max(1, parseInt(quantity) || 1); + if (normalizedQuantity !== Number(detail.quantity)) { + updateFields.quantity = normalizedQuantity; + quantityChanged = true; + } + } + if (remark !== undefined && remark !== null) { + updateFields.remark = String(remark).slice(0, 500); + } + + if (Object.keys(updateFields).length === 0) { + await this._enrichDetailsWithStock([ detail ], Number(unpack.warehouse_id || 0)); + return { + detail, + total_items: unpack.total_items, + total_quantity: unpack.total_quantity, + detail_status: unpack.detail_status, + }; + } + + await ctx.model.ReturnUnpackDetail.update(updateFields, { + where: { id: detail.id }, + }); + + const updated = await ctx.model.ReturnUnpackDetail.findOne({ + where: { id: detail.id }, + raw: true, + }); + + let summary = { + total_items: unpack.total_items, + total_quantity: unpack.total_quantity, + detail_status: unpack.detail_status, + }; + if (quantityChanged) { + summary = await this._recalcMain(unpack.id, unpack.warehouse_id); + } + + await this._enrichDetailsWithStock([ updated ], Number(unpack.warehouse_id || 0)); + return { + detail: updated, + ...summary, + }; + } + + /** + * 移除明细:硬删除拆包单下的一条明细。 + * + * @param {Object} params 移除参数。 + * @param {number} params.id 拆包单ID。 + * @param {number} params.detail_id 明细ID。 + * @return {Promise} 删除结果 + 主表最新汇总。 + */ + async removeDetail({ id, detail_id }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const detail = await this._findDetailChecked(unpack.id, detail_id); + + await ctx.model.ReturnUnpackDetail.destroy({ + where: { id: detail.id }, + }); + + const summary = await this._recalcMain(unpack.id, unpack.warehouse_id); + return { + removed_detail_id: detail.id, + ...summary, + }; + } + + /** + * 取消拆包单:仅在未完成(unpacking)状态可删,事务内硬删除主表 + 所有明细。 + * + * @param {Object} params 取消参数。 + * @param {number} params.id 拆包单ID。 + * @return {Promise} 取消结果。 + */ + async cancel({ id }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + await ctx.model.transaction(async transaction => { + await ctx.model.ReturnUnpackDetail.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpackVideo.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpack.destroy({ + where: { id: unpack.id }, + transaction, + }); + }); + + return { id: unpack.id }; + } + + /** + * 按仓库配置的拆包最大录制时长约束提交结束时间。 + * 候选结束时间超过 开始时间+上限时长 时,截断为上限时间点。 + * 开始时间缺失、配置非法或读取失败时不约束,原样返回。 + * + * @param {Object} unpack 拆包单主表记录(需含 id / warehouse_id / start_time)。 + * @param {Date} candidateEndTime 候选结束时间。 + * @return {Promise} 约束后的结束时间。 + */ + async _resolveSubmitEndTime(unpack, candidateEndTime) { + const { ctx } = this; + const candidate = candidateEndTime instanceof Date ? candidateEndTime : new Date(candidateEndTime); + + if (!unpack || !Number.isFinite(candidate.getTime())) { + return candidateEndTime; + } + + const startMs = new Date(unpack.start_time).getTime(); + if (!Number.isFinite(startMs)) { + return candidateEndTime; + } + + let limitMinutes = null; + try { + const warehouseId = Number(unpack.warehouse_id || 0); + const subjectConfig = await ctx.service.systems.deliveryOrder.getStoreSubjectConfig(warehouseId); + limitMinutes = Number(subjectConfig && subjectConfig.return_unpack_max_record_minutes); + } catch (error) { + ctx.logger.warn(`[returnUnpack.submit] 读取仓库拆包时长配置失败: ${error.message}`); + } + + // 未配置有效时长时不约束结束时间 + if (!Number.isInteger(limitMinutes) || limitMinutes <= 0) { + return candidateEndTime; + } + + const maxEndMs = startMs + limitMinutes * 60 * 1000; + if (candidate.getTime() > maxEndMs) { + const cappedEndTime = new Date(maxEndMs); + ctx.logger.info( + `[returnUnpack.submit] 结束时间超过拆包录制上限,截断为上限时间 unpack_id=${unpack.id} ` + + `limitMinutes=${limitMinutes} candidate=${candidate.toISOString()} end=${cappedEndTime.toISOString()}` + ); + return cappedEndTime; + } + + return candidateEndTime; + } + + /** + * 提交确认:未完成拆包单转 completed 终态,回写结束时间(超过仓库配置的 + * 拆包最大录制时长时自动截断为开始时间+上限), + * 并同步更新退回查询记录 is_back=1(标记该运单号已退回)。 + * + * @param {Object} params 提交参数。 + * @param {number} params.id 拆包单ID。 + * @return {Promise} 更新后的主表记录。 + */ + async submit({ id }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const now = new Date(); + const endTime = await this._resolveSubmitEndTime(unpack, now); + await ctx.model.ReturnUnpack.update( + { status: 'completed', end_time: endTime }, + { where: { id: unpack.id } } + ); + + // 同步更新退回查询记录:按 warehouse_id + 运单号(兼容分段单号)反查命中则 is_back=1 + const { Op } = ctx.app.Sequelize; + try { + await ctx.model.ReturnQueryLog.update( + { is_back: 1 }, + { where: { warehouse_id: unpack.warehouse_id, [Op.or]: this._buildWaybillMatch(unpack.waybill_code) } } + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.submit] 更新退回查询记录 is_back 失败: ${err.message}`); + } + + // 拆包完成后按原查询登记来源通知(登记时记录的来源群/用户):推送成功后标记 is_notified=1 + await this._notifyUnpacked(unpack); + + const updated = await ctx.model.ReturnUnpack.findOne({ + where: { id: unpack.id }, + raw: true, + }); + + return { + record: await this._enrichRow(updated), + }; + } + + /** + * 拆包完成后按原查询登记来源通知(不再泛推货主售后群)。 + * 通知集合:仅退回查询登记表中该运单已退回(is_back=1)且未通知(is_notified=0)的记录; + * 按登记来源(group_id + user_id)聚合后逐来源回信:有用户信息时走 writeOutboundReply + * 定向回原查询用户,无用户信息时退化为该群的系统通知;登记时无来源群的记录(如后台 API 登记)不通知。 + * 仅推送成功的登记标记 is_notified=1。 + * + * @param {Object} unpack 拆包单主表记录 + * @return {Promise} 异常仅记日志不阻塞主流程 + */ + async _notifyUnpacked(unpack) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = Number(unpack.warehouse_id || 0); + try { + const processor = ctx.service.inbox && ctx.service.inbox.processor; + if (!processor || typeof processor.pushSystemNotification !== 'function') { + ctx.logger.warn( + `[returnUnpack._notifyUnpacked] inbox processor 不可用,跳过通知 waybill=${unpack.waybill_code}` + ); + return; + } + + const logs = await ctx.model.ReturnQueryLog.findAll({ + attributes: [ 'id', 'store_id', 'waybill_code', 'group_id', 'group_name', 'user_id', 'user_name' ], + where: { + warehouse_id: warehouseId, + [Op.or]: this._buildWaybillMatch(unpack.waybill_code), + is_back: 1, + is_notified: 0, + }, + raw: true, + }); + + if (logs.length === 0) { + ctx.logger.info( + `[returnUnpack._notifyUnpacked] 无待通知的退回查询登记,跳过通知 waybill=${unpack.waybill_code}` + ); + return; + } + + // 按登记来源聚合:key=group_id|user_id → 运单号集合(同一来源的多条登记合并为一条消息) + const buckets = new Map(); + const bucketIds = new Map(); + const skippedIds = []; + for (const log of logs) { + const groupId = String(log.group_id || '').trim(); + if (!groupId) { + // 登记时无来源群(如后台 API 登记):不通知,保留 is_notified=0 + skippedIds.push(log.id); + continue; + } + const userId = String(log.user_id || '').trim(); + const key = `${groupId}\u0000${userId}`; + if (!buckets.has(key)) { + buckets.set(key, { + groupId, + groupName: String(log.group_name || '').trim(), + userId, + userName: String(log.user_name || '').trim(), + waybills: new Set(), + storeId: 0, + }); + bucketIds.set(key, []); + } + const bucket = buckets.get(key); + bucket.waybills.add(log.waybill_code || unpack.waybill_code); + if (!bucket.storeId) bucket.storeId = Number(log.store_id || 0); + bucketIds.get(key).push(log.id); + } + + if (buckets.size === 0) { + ctx.logger.info( + `[returnUnpack._notifyUnpacked] 登记均无来源群信息,跳过通知 waybill=${unpack.waybill_code} skipped=${skippedIds.length}` + ); + return; + } + + // 批量反查群信息(补全 group_name/ext_data/store_id;群已解绑时用登记快照兑底) + const groupMap = new Map(); + const groupIds = [ ...buckets.values() ].map(bucket => bucket.groupId); + try { + const groupRows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id', 'group_name', 'store_id', 'ext_data' ], + where: { group_id: { [Op.in]: groupIds }, warehouse_id: warehouseId }, + raw: true, + }); + for (const g of groupRows) { + groupMap.set(String(g.group_id), g); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._notifyUnpacked] 批量查询群信息失败: ${err.message}`); + } + + // 逐来源回信(一条消息含该来源登记的全部运单) + const notifiedIds = []; + let bucketIdx = 0; + for (const [ key, bucket ] of buckets) { + bucketIdx += 1; + const groupRow = groupMap.get(bucket.groupId) || null; + const groupName = String(bucket.groupName || (groupRow && groupRow.group_name) || '').trim(); + if (!groupName) { + skippedIds.push(...bucketIds.get(key)); + ctx.logger.warn( + `[returnUnpack._notifyUnpacked] 来源群名缺失,跳过通知 group=${bucket.groupId}` + ); + continue; + } + const storeId = bucket.storeId || Number(groupRow && groupRow.store_id) || null; + const extData = (groupRow && groupRow.ext_data) || null; + const waybills = [ ...bucket.waybills ]; + const content = `退回包裹已拆包完成:\n${waybills.join('\n')}\n发送:查退回+运单号,可查看拆包明细`; + try { + if (bucket.userId && bucket.userName && typeof processor.writeOutboundReply === 'function') { + // 定向回原查询用户(登记来源用户信息完整时) + await processor.writeOutboundReply({ + warehouse_id: warehouseId, + group_id: bucket.groupId, + group_name: groupName, + user_id: bucket.userId, + user_name: bucket.userName, + store_id: storeId, + ext_data: extData, + ext_id: `unpack:notify:${unpack.id}:${bucketIdx}`, + }, content, 'ai_reply'); + } else { + // 无用户信息:退化为来源群系统通知 + processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: bucket.groupId, + group_name: groupName, + content, + ext_data: extData, + store_id: storeId, + }); + } + notifiedIds.push(...bucketIds.get(key)); + } catch (err) { + skippedIds.push(...bucketIds.get(key)); + ctx.logger.warn( + `[returnUnpack._notifyUnpacked] 通知失败 group=${bucket.groupId}: ${err.message}` + ); + } + } + + // 仅标记推送成功的登记(失败/无来源的保留 is_notified=0) + if (notifiedIds.length > 0) { + await ctx.model.ReturnQueryLog.update( + { is_notified: 1 }, + { where: { id: { [Op.in]: notifiedIds } } } + ); + } + ctx.logger.info( + `[returnUnpack._notifyUnpacked] 拆包通知完成 waybill=${unpack.waybill_code} ` + + `notified=${notifiedIds.length} skipped=${skippedIds.length} buckets=${buckets.size}` + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack._notifyUnpacked] 拆包通知失败: ${err.message}`); + } + } + + /** + * 强制重新录制拆包视频:重置视频记录状态并推送打印服务强制录制。 + * 参考 order.packing.forceRecord:校验仓库录制电脑在线后,将视频记录重置为 + * created 并清空 video_url,再向打印服务 /record/force 推送 { unpack_id } 触发重新录制。 + * + * @param {Object} params 参数。 + * @param {number} params.id 拆包单ID。 + * @return {Promise} 推送结果 { unpack_id, computer_id, print_service_url, print_service_request, print_service_response }。 + */ + async forceRecord({ id }) { + const { ctx } = this; + + // 拆包单存在性 + 仓库隔离校验(不存在 404 / 跨仓库 403) + const unpack = await this._findByIdChecked(id); + const warehouseId = Number(unpack.warehouse_id || 0); + const unpackId = Number(id); + + // 1. 查找仓库的录制电脑 + const recordingComputer = await ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + raw: true, + }); + if (!recordingComputer) { + throw this.createBusinessError('该仓库无录制电脑,无法强制录制', 400); + } + + // 2. 检查录制电脑是否在线(与 order_packing 相同的 Redis 在线键) + const redisPrinter = ctx.app.redis.get('printer'); + const onlineKey = `warehouse:${warehouseId}:printer:${recordingComputer.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + if (!onlineInfo) { + throw this.createBusinessError('该仓库录制电脑不在线,无法强制录制', 400); + } + + // 3. 重置视频记录状态为 created,触发重新录制 + await ctx.model.ReturnUnpackVideo.update( + { status: 'created', video_url: '' }, + { where: { unpack_id: unpackId, deleted_at: null } } + ); + + // 4. 通知打印服务推送强制录制任务 + const printServiceUrl = ctx.app.config.printService.url; + const requestData = { unpack_id: unpackId }; + let printServiceResponse = null; + try { + const res = await ctx.curl(`${printServiceUrl}/record/force`, { + method: 'POST', + contentType: 'json', + data: requestData, + dataType: 'json', + timeout: 10000, + }); + printServiceResponse = { + status: res.status, + headers: res.headers, + data: res.data, + }; + } catch (err) { + ctx.logger.warn(`[returnUnpack.forceRecord] 通知打印服务强制录制 unpack_id=${unpackId} 失败: ${err.message}`); + throw this.createBusinessError(`通知打印服务失败: ${err.message}`, 500); + } + + return { + unpack_id: unpackId, + computer_id: recordingComputer.id, + print_service_url: `${printServiceUrl}/record/force`, + print_service_request: requestData, + print_service_response: printServiceResponse, + }; + } + + /** + * 分页查询拆包单列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { list, pagination }。 + */ + async list(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildListWhere(where, Op); + const order = this._buildListOrder(sort, 'return_unpack'); + + // 性能与准确性:count 与 rows 分离。findAndCountAll 携带 hasMany include(videos)时, + // Sequelize 生成的是 COUNT(ReturnUnpack.id) + LEFT JOIN 视频表,等于「主表行 × 命中视频条数」, + // 会把 total 放大(生产实测 8483 条拆包单被统计成 16961,与 export 口径对不上), + // 拆开后 count 走单表条件(与 exportUnpack 的 total_count 完全一致),性能也更好。 + const count = await ctx.model.ReturnUnpack.count({ where: queryWhere }); + const rows = count === 0 + ? [] + : await ctx.model.ReturnUnpack.findAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: false, + include: [ + { + model: ctx.model.ReturnUnpackVideo, + as: 'videos', + attributes: [ 'id', 'video_url', 'camera_id', 'status' ], + where: { deleted_at: null }, + required: false, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + attributes: [ 'id', 'custom_name', 'channel_name' ], + required: false, + }, + ], + }, + ], + }); + + const list = []; + for (const row of rows) { + const plain = row && typeof row.toJSON === 'function' ? row.toJSON() : row; + list.push(this._flattenVideos(await this._enrichRow(plain))); + } + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 分页查询拆包明细列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { list, pagination }。 + */ + async detailList(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildDetailListWhere(where, Op); + const order = this._buildListOrder(sort, 'return_unpack_detail'); + + const { count, rows } = await ctx.model.ReturnUnpackDetail.findAndCountAll({ + where: queryWhere, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockWarehouse', + required: false, + }, + ], + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: false, + }); + + const list = rows.map(row => (row && typeof row.toJSON === 'function' ? row.toJSON() : row)); + + // 明细批量附加库存详情(条码/图片等,统一走 stockWarehouse.getStockDetails 通用方法) + const listWarehouseId = list.length > 0 ? Number(list[0].warehouse_id || 0) : 0; + await this._enrichDetailsWithStock(list, listWarehouseId); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 分页查询拆包录像列表(unpack_id 维度,仓库隔离由方法层校验)。 + * + * @param {Object} where 标准化 where 条件对象(unpack_id 必填)。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { list, pagination }。 + */ + async videoList(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildVideoListWhere(where, Op); + const order = this._buildVideoListOrder(sort); + + const { count, rows } = await ctx.model.ReturnUnpackVideo.findAndCountAll({ + where: queryWhere, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + required: false, + }, + ], + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: false, + }); + + // 视频地址拼接 CDN 域名(unpack_id 由方法层强制注入且已通过仓库隔离校验) + const unpackIdRaw = queryWhere.unpack_id; + const unpackId = unpackIdRaw && typeof unpackIdRaw === 'object' ? unpackIdRaw.value : unpackIdRaw; + let warehouseId = 0; + if (unpackId) { + const unpackRow = await ctx.model.ReturnUnpack.findOne({ + where: { id: Number(unpackId) }, + attributes: [ 'warehouse_id' ], + raw: true, + }); + warehouseId = Number(unpackRow && unpackRow.warehouse_id || 0); + } + const recordingComputerId = warehouseId > 0 ? await this._getRecordingComputerId(warehouseId) : null; + + const list = rows + .map(row => (row && typeof row.toJSON === 'function' ? row.toJSON() : row)) + .map(row => { + const camera = row.camera || {}; + return { + id: row.id, + unpack_id: row.unpack_id, + video_url: this._buildVideoUrl(warehouseId, recordingComputerId, row.video_url), + status: row.status || null, + camera_id: row.camera_id || null, + camera_name: (camera.custom_name || camera.channel_name) || null, + remark: row.remark || null, + created_at: row.created_at ? app.formatDate(row.created_at) : null, + updated_at: row.updated_at ? app.formatDate(row.updated_at) : null, + }; + }); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 导出退回拆包数据(双 Sheet:正常退回运单号列表 + 明细表)。 + * 复用 list 的 where/sort 语义;仓库隔离由方法层注入 warehouse_id,此处再强制兑底; + * 分页拉取主表全量数据后批量关联明细/货主名称/快递类型,流式生成 Excel 并上传。 + * + * @param {Object} options 导出选项。 + * @param {Object} [options.where] 标准化 where 条件(与 list 一致)。 + * @param {Object} [options.sort] 排序参数(与 list 一致)。 + * @param {number} [options.warehouseId] 仓库ID(由方法层从上下文注入)。 + * @param {Function} [options.onProgress] 进度回调。 + * @return {Promise} 上传结果与统计信息(含 url/cdnUrl/cosUrl/fileKey/current_count/total_count/total_details/sheet_count, + * url 优先取上传服务返回的完整 URL,兜底取落库记录 file_url/fileUrl,最后才回退 COS key)。 + */ + async exportUnpack(options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const safeOptions = options && typeof options === 'object' && !Array.isArray(options) ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const warehouseId = Number(safeOptions.warehouseId || 0); + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + // 复用 list 的 where/sort 语义,并强制仓库隔离(服务端注入,前端无需传 warehouse_id) + const queryWhere = this._buildListWhere(where, Op); + queryWhere.warehouse_id = warehouseId; + const order = this._buildListOrder(sort, 'return_unpack'); + + const totalCount = await ctx.model.ReturnUnpack.count({ where: queryWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 85, + currentCount: 0, + totalCount, + message: totalCount > 0 ? `已命中 ${totalCount} 条拆包单,开始导出` : '未命中数据,开始生成空文件', + }); + + // ---- 分页拉取主表全量数据 ---- + const allUnpackRows = []; + let page = 1; + while (allUnpackRows.length < totalCount) { + const rows = await ctx.model.ReturnUnpack.findAll({ + where: queryWhere, + order, + limit: RETURN_UNPACK_EXPORT_PAGE_SIZE, + offset: (page - 1) * RETURN_UNPACK_EXPORT_PAGE_SIZE, + raw: true, + }); + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + allUnpackRows.push(...rows); + page += 1; + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((allUnpackRows.length / Math.max(totalCount, 1)) * 20)), + currentCount: allUnpackRows.length, + totalCount, + message: `正在拉取拆包单列表,已完成 ${allUnpackRows.length}/${totalCount}`, + }); + } + + // ---- 批量拉取明细(按 unpack_id 分批) ---- + const unpackIds = allUnpackRows + .map(row => Number(row.id)) + .filter(id => Number.isInteger(id) && id > 0); + /** @type {Map>} */ + const detailsMap = new Map(); + if (unpackIds.length > 0) { + const totalBatches = Math.ceil(unpackIds.length / RETURN_UNPACK_DETAIL_BATCH_SIZE); + for (let batchIdx = 0; batchIdx < unpackIds.length; batchIdx += RETURN_UNPACK_DETAIL_BATCH_SIZE) { + const batchIds = unpackIds.slice(batchIdx, batchIdx + RETURN_UNPACK_DETAIL_BATCH_SIZE); + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: { [Op.in]: batchIds } }, + order: [[ 'unpack_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + for (const detail of details) { + const key = Number(detail.unpack_id); + if (!detailsMap.has(key)) { + detailsMap.set(key, []); + } + detailsMap.get(key).push(detail); + } + const currentBatch = Math.floor(batchIdx / RETURN_UNPACK_DETAIL_BATCH_SIZE) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + currentCount: allUnpackRows.length, + totalCount, + message: `正在拉取拆包明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + const totalDetails = allUnpackRows.reduce( + (sum, row) => sum + (detailsMap.get(Number(row.id)) || []).length, + 0 + ); + + // ---- 批量解析货主名称与快递类型 ---- + const storeNameMap = await this._resolveStoreNameMap(allUnpackRows, Op); + const expressNameMap = await this._resolveExpressNameMap(allUnpackRows, Op); + + await progressHandler({ + status: 'running', + progress: 55, + currentCount: allUnpackRows.length, + totalCount, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-return-unpack-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `退回拆包导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + const formatDateOnly = value => (value ? app.formatDate(value, 'YYYY-MM-DD') : ''); + const formatDateTime = value => (value ? app.formatDate(value) : ''); + + try { + // Sheet 1: 正常退回运单号列表 + const sheet1 = workbook.addWorksheet('正常退回运单号列表'); + const mainColumns = [ + { header: '货主', key: 'store_name', width: 20 }, + { header: '快递号', key: 'waybill_code', width: 22 }, + { header: '商品类数', key: 'total_items', width: 12 }, + { header: '商品总数', key: 'total_quantity', width: 12 }, + { header: '记录人员', key: 'unpacker_name', width: 14 }, + { header: '记录日期', key: 'unpack_date', width: 14 }, + { header: '开始时间', key: 'start_time', width: 20 }, + { header: '结束时间', key: 'end_time', width: 20 }, + { header: '是否原单', key: 'is_original_return', width: 10 }, + { header: '快递类型', key: 'express', width: 14 }, + { header: '自定义店铺', key: 'shop_name', width: 20 }, + { header: '平台单号', key: 'source_order_codes', width: 24 }, + ]; + sheet1.columns = mainColumns; + + for (const row of allUnpackRows) { + const storeId = Number(row.store_id || 0); + const expressId = Number(row.order_express_id || 0); + sheet1.addRow({ + store_name: normalizeCellValue(storeId > 0 ? (storeNameMap.get(storeId) || '') : ''), + waybill_code: normalizeCellValue(row.waybill_code), + total_items: row.total_items, + total_quantity: row.total_quantity, + unpacker_name: normalizeCellValue(row.unpacker_name), + unpack_date: formatDateOnly(row.unpack_date), + start_time: formatDateTime(row.start_time), + end_time: formatDateTime(row.end_time), + is_original_return: row.order_express_id ? '是' : '否', + express: normalizeCellValue(expressId > 0 ? (expressNameMap.get(expressId) || '') : ''), + shop_name: normalizeCellValue(row.shop_name), + source_order_codes: normalizeCellValue(row.source_order_codes), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + currentCount: allUnpackRows.length, + totalCount, + message: '正在写入拆包明细...', + }); + + // Sheet 2: 明细表 + const sheet2 = workbook.addWorksheet('明细表'); + const detailColumns = [ + { header: '货主', key: 'store_name', width: 20 }, + { header: '快递号', key: 'waybill_code', width: 22 }, + { header: '商品名称', key: 'item_name', width: 24 }, + { header: '商品编码', key: 'item_code', width: 18 }, + { header: '条码', key: 'barcode', width: 20 }, + { header: '颜色', key: 'color', width: 12 }, + { header: '规格', key: 'spec', width: 20 }, + { header: '数量', key: 'quantity', width: 10 }, + { header: '是否残次', key: 'is_damaged', width: 10 }, + { header: '记录人员ID', key: 'unpacker_id', width: 14 }, + { header: '记录日期', key: 'unpack_date', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '是否原单', key: 'is_original_return', width: 10 }, + { header: '快递类型', key: 'express', width: 14 }, + { header: '自定义店铺', key: 'shop_name', width: 20 }, + { header: '平台单号', key: 'source_order_codes', width: 24 }, + ]; + sheet2.columns = detailColumns; + + let detailWrittenCount = 0; + for (const row of allUnpackRows) { + const storeId = Number(row.store_id || 0); + const expressId = Number(row.order_express_id || 0); + const storeName = storeId > 0 ? (storeNameMap.get(storeId) || '') : ''; + const expressName = expressId > 0 ? (expressNameMap.get(expressId) || '') : ''; + const details = detailsMap.get(Number(row.id)) || []; + for (const detail of details) { + sheet2.addRow({ + store_name: normalizeCellValue(storeName), + waybill_code: normalizeCellValue(row.waybill_code), + item_name: normalizeCellValue(detail.item_name), + item_code: normalizeCellValue(detail.item_code), + barcode: normalizeCellValue(detail.barcode), + color: this._extractDetailColor(detail), + spec: normalizeCellValue(detail.spec), + quantity: detail.quantity, + is_damaged: detail.product_status === 'damaged' ? '是' : '否', + unpacker_id: row.unpacker_id, + unpack_date: formatDateOnly(row.unpack_date), + remark: normalizeCellValue(detail.remark), + is_original_return: row.order_express_id ? '是' : '否', + express: normalizeCellValue(expressName), + shop_name: normalizeCellValue(row.shop_name), + source_order_codes: normalizeCellValue(row.source_order_codes), + }).commit(); + } + detailWrittenCount += 1; + if (detailWrittenCount % RETURN_UNPACK_DETAIL_BATCH_SIZE === 0 || detailWrittenCount === allUnpackRows.length) { + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((detailWrittenCount / Math.max(allUnpackRows.length, 1)) * 20)), + currentCount: allUnpackRows.length, + totalCount, + message: `正在写入拆包明细,已完成 ${detailWrittenCount}/${allUnpackRows.length} 条拆包单`, + }); + } + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + currentCount: allUnpackRows.length, + totalCount, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/return_unpack/${warehouseId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `退回拆包导出(仓库${warehouseId}),共${totalCount}条拆包单`, + }); + } + + // 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录(兼容 data 包裹),最后才回退 COS key + const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {}; + const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null; + const fileUrlFromRecord = resolvedFileRecord + ? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '') + : ''; + const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || ''; + + const uploadInfo = { + filename, + fileKey: safeUploadResult.fileName || uploadKey, + url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey, + cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '', + cosUrl: safeUploadResult.cosUrl || '', + current_count: allUnpackRows.length, + total_count: totalCount, + total_details: totalDetails, + sheet_count: 2, + }; + + await progressHandler({ + status: 'success', + progress: 100, + currentCount: allUnpackRows.length, + totalCount, + message: '导出任务完成', + result: uploadInfo, + }); + + return uploadInfo; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + throw error; + } finally { + // 清理临时文件(不存在或删除失败均忽略) + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (err) { /* ignore */ } + } + } + + /** + * 批量解析货主名称映射(store_id → wms_store.company_name)。 + * @param {Array} rows 主表行数组。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Promise>} store_id → 货主名称映射。 + */ + async _resolveStoreNameMap(rows = [], Op) { + const { ctx } = this; + const storeIds = [ ...new Set( + (Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.store_id || 0)) + .filter(id => Number.isInteger(id) && id > 0) + ) ]; + /** @type {Map} */ + const nameMap = new Map(); + if (storeIds.length === 0) { + return nameMap; + } + try { + const stores = await ctx.model.Store.findAll({ + where: { id: { [Op.in]: storeIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const store of stores) { + nameMap.set(Number(store.id), store.company_name ? String(store.company_name) : ''); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.export] 批量解析货主名称失败: ${err.message}`); + } + return nameMap; + } + + /** + * 批量解析快递类型映射(order_express_id → wms_order_express.logistics_name)。 + * @param {Array} rows 主表行数组。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Promise>} order_express_id → 快递类型映射。 + */ + async _resolveExpressNameMap(rows = [], Op) { + const { ctx } = this; + const expressIds = [ ...new Set( + (Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.order_express_id || 0)) + .filter(id => Number.isInteger(id) && id > 0) + ) ]; + /** @type {Map} */ + const nameMap = new Map(); + if (expressIds.length === 0) { + return nameMap; + } + try { + const expresses = await ctx.model.OrderExpress.findAll({ + where: { id: { [Op.in]: expressIds } }, + attributes: [ 'id', 'logistics_name' ], + raw: true, + }); + for (const express of expresses) { + nameMap.set(Number(express.id), express.logistics_name ? String(express.logistics_name) : ''); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.export] 批量解析快递类型失败: ${err.message}`); + } + return nameMap; + } + + /** + * 从明细快照/规格中提取颜色(优先 product_snapshot.sku_property,兜底 spec 字段)。 + * 颜色约定以「颜色:xxx」形式出现在 SKU 规格串中,未命中返回空字符串。 + * @param {Object} detail 明细行。 + * @return {string} 颜色文本,未命中返回空字符串。 + */ + _extractDetailColor(detail = {}) { + let spec = detail && detail.spec ? String(detail.spec) : ''; + const snapshot = detail && detail.product_snapshot; + if (snapshot) { + try { + const parsed = typeof snapshot === 'string' ? JSON.parse(snapshot) : snapshot; + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && parsed.sku_property) { + spec = String(parsed.sku_property); + } + } catch (err) { + // 快照解析失败时退回 spec 字段 + } + } + const normalized = String(spec || '').trim(); + if (!normalized) { + return ''; + } + const match = normalized.match(/颜色[::]\s*([^;;,,]+)/); + return match && match[1] ? String(match[1]).trim() : ''; + } + + /** + * 查询拆包单详情:主表 + 明细 + 视频 + 退回收到单 + 原订单详情(原单退回时)。 + * + * @param {number} id 拆包单ID。 + * @return {Promise} 详情对象。 + */ + async detail(id) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + + const record = await ctx.model.ReturnUnpack.findOne({ + where: { id: unpack.id }, + include: [ + { + model: ctx.model.ReturnUnpackDetail, + as: 'details', + required: false, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockWarehouse', + required: false, + }, + ], + }, + { + model: ctx.model.ReturnUnpackVideo, + as: 'videos', + where: { deleted_at: null }, + required: false, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + required: false, + }, + ], + }, + { + model: ctx.model.ReturnReceived, + as: 'returnReceived', + required: false, + }, + ], + raw: false, + }); + + const recordJson = record && typeof record.toJSON === 'function' ? record.toJSON() : record; + + // 明细批量附加库存详情(条码/图片等,统一走 stockWarehouse.getStockDetails 通用方法) + if (recordJson && Array.isArray(recordJson.details)) { + recordJson.details = await this._enrichDetailsWithStock( + recordJson.details, + Number(recordJson.warehouse_id || 0) + ); + } + + // 原订单详情(仅原单退回时返回) + let relatedOrder = null; + if (recordJson && recordJson.order_id) { + try { + relatedOrder = await ctx.service.systems.afterSale._resolveOrderDetail( + recordJson.order_id, + recordJson.warehouse_id + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.detail] 拉取原订单详情失败: ${err.message}`); + } + } + + return { + record: await this._enrichRow(recordJson), + related: { + order: relatedOrder, + }, + }; + } + + /** + * 构建运单号灵活匹配条件:精确单号 + 剥尾段单号 + 前缀段单号。 + * 兼容京东等一单多件的分段单号(如 JDX057904621547-1-1- 与 JDX057904621547 互相匹配)。 + * @param {string} waybillCode 运单号 + * @return {Array} Sequelize Op.or 条件数组 + */ + _buildWaybillMatch(waybillCode) { + const { Op } = this.app.Sequelize; + const code = String(waybillCode || '').trim(); + // 剥掉尾部多段数字段(一单多件格式:-包裹序号-总件数[-]) + const base = code.replace(/(?:-\d+){2,}-?$/, ''); + // 转义 like 通配符,避免输入中的 % _ 扩大匹配范围 + const escapedBase = String(base || '').replace(/[%_\\]/g, m => `\\${m}`); + const or = [{ waybill_code: code }]; + if (base && base !== code) or.push({ waybill_code: base }); + if (escapedBase) or.push({ waybill_code: { [Op.like]: `${escapedBase}-%` } }); + return or; + } + + /** + * 运单号灵活查询:精确单号优先,其次剥尾段单号,再次前缀段。 + * @param {Object} model Sequelize 模型 + * @param {Object} extraWhere 额外查询条件 + * @param {string} waybillCode 运单号 + * @param {string[]} [attributes] 返回字段 + * @param {Array} [order] 排序(默认 created_at DESC, id DESC) + * @return {Promise} 命中的行,未命中返回 null + */ + async _findWaybillFlexible(model, extraWhere, waybillCode, attributes, order) { + const { Op } = this.app.Sequelize; + const code = String(waybillCode || '').trim(); + const base = code.replace(/(?:-\d+){2,}-?$/, ''); + const options = { + where: { ...extraWhere, [Op.or]: this._buildWaybillMatch(code) }, + order: order && order.length > 0 ? order : [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + limit: 5, + raw: true, + }; + if (Array.isArray(attributes) && attributes.length > 0) options.attributes = attributes; + const rows = await model.findAll(options); + if (!rows || rows.length === 0) return null; + const rank = row => (row.waybill_code === code ? 0 : (row.waybill_code === base ? 1 : 2)); + return rows.slice().sort((a, b) => rank(a) - rank(b))[0]; + } + + /** + * 查询退回明细(按运单号,跨退回相关表汇总)。 + * 依次查询:拆包主表+明细+视频(已拆包)→ 退回收到表(已收到未拆包)→ 退回查询登记表(未退回)。 + * 未退回且无登记记录时自动登记到 wms_return_query_log,等待拆包后处理。 + * + * @param {Object} params 查询参数。 + * @param {string} params.waybill_code 退回包裹运单号(必填)。 + * @param {number} params.warehouse_id 仓库ID(必填)。 + * @param {number} [params.store_id] 货主ID(可选,用于货主隔离与未退回登记)。 + * @param {string} [params.group_id] 触发查询的群ID(站内信外部群ID,登记来源)。 + * @param {string} [params.group_name] 触发查询的群名称(登记来源)。 + * @param {string} [params.user_id] 触发查询的用户ID(站内信外部用户ID,登记来源)。 + * @param {string} [params.user_name] 触发查询的用户名称(登记来源)。 + * @return {Promise} { status, waybill_code, warehouse_name, ... }。 + * status:unpacked(已拆包)/ received(已收到未拆包)/ not_returned(未退回)/ hidden(跨货主不可见)。 + */ + async queryByWaybill({ waybill_code, warehouse_id, store_id, group_id, group_name, user_id, user_name } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const warehouseId = Number(warehouse_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + const storeId = Number(store_id || 0); + + // 登记来源(站内信「查退回」触发):群/用户信息写入退回查询登记表,用于追溯与定向通知 + const sourceGroupId = String(group_id || '').trim() || null; + const sourceGroupName = String(group_name || '').trim() || null; + const sourceUserId = String(user_id || '').trim() || null; + const sourceUserName = String(user_name || '').trim() || null; + + const warehouseName = await this._resolveWarehouseName(warehouseId); + + // 1. 已拆包:同一运单号取最新一条有效拆包单(跳过已作废) + // 兼容一单多件分段单号:JDX057904621547 可命中 JDX057904621547-1-1- + const unpack = await this._findWaybillFlexible( + ctx.model.ReturnUnpack, + { warehouse_id: warehouseId, status: { [Op.ne]: 'cancelled' } }, + waybillCode + ); + + if (unpack) { + // 货主隔离:限定货主查询且拆包单已归属其他货主 → 不暴露数据 + if (storeId > 0 && Number(unpack.store_id || 0) > 0 && Number(unpack.store_id) !== storeId) { + return { status: 'hidden', waybill_code: waybillCode, warehouse_name: warehouseName }; + } + + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: unpack.id }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const videos = await ctx.model.ReturnUnpackVideo.findAll({ + where: { unpack_id: unpack.id, deleted_at: null }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 视频地址拼接 CDN 域名(与 order.packing 对齐) + const recordingComputerId = await this._getRecordingComputerId(warehouseId); + for (const video of videos) { + video.video_url = this._buildVideoUrl(warehouseId, recordingComputerId, video.video_url); + } + + // 附加摄像头名称(系统设置的自定义名称优先,通道原始名称兜底) + const videoCameraIds = [ ...new Set(videos.map(v => v.camera_id).filter(id => id)) ]; + const cameraNameMap = new Map(); + if (videoCameraIds.length > 0) { + const cameras = await ctx.model.Camera.findAll({ + attributes: [ 'id', 'custom_name', 'channel_name' ], + where: { id: { [Op.in]: videoCameraIds } }, + raw: true, + }); + for (const camera of cameras) { + cameraNameMap.set(Number(camera.id), String(camera.custom_name || camera.channel_name || '').trim()); + } + } + for (const video of videos) { + video.camera_name = video.camera_id ? (cameraNameMap.get(Number(video.camera_id)) || '') : ''; + } + + let received = null; + if (unpack.return_received_id) { + received = await ctx.model.ReturnReceived.findOne({ + where: { id: unpack.return_received_id }, + raw: true, + }); + } + + const orderInfo = await this._resolveReturnOrderInfo({ + order_express_id: unpack.order_express_id, + order_id: unpack.order_id, + warehouse_id: warehouseId, + store_id: unpack.store_id, + source_order_codes: unpack.source_order_codes, + shop_name: unpack.shop_name, + }); + + return { + status: 'unpacked', + waybill_code: waybillCode, + warehouse_name: warehouseName, + unpack, + details, + videos, + received, + order_info: orderInfo, + }; + } + + // 2. 已收到未拆包:退回收到表登记过(兼容分段单号) + const received = await this._findWaybillFlexible( + ctx.model.ReturnReceived, + { warehouse_id: warehouseId }, + waybillCode + ); + + if (received) { + if (storeId > 0 && Number(received.store_id || 0) > 0 && Number(received.store_id) !== storeId) { + return { status: 'hidden', waybill_code: waybillCode, warehouse_name: warehouseName }; + } + + // 货主确定优先级:入参 store_id > 退回登记表 store_id > 原运单反查 store_id > 0(未知) + let resolvedStoreId = storeId || Number(received.store_id || 0); + if (!resolvedStoreId) { + resolvedStoreId = await this._resolveStoreIdByWaybill(waybillCode, warehouseId); + } + + // 退回登记表货主为空 → 回填变更(后续拆包/通知依赖货主) + if (Number(received.store_id || 0) <= 0 && resolvedStoreId > 0) { + try { + await ctx.model.ReturnReceived.update( + { store_id: resolvedStoreId }, + { where: { id: received.id } } + ); + received.store_id = resolvedStoreId; + ctx.logger.info( + `[returnUnpack.queryByWaybill] 退回登记表回填货主: id=${received.id} store_id=${resolvedStoreId}` + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.queryByWaybill] 回填退回登记表货主失败: ${err.message}`); + } + } + + // 照常登记退回查询记录(幂等:已存在则不重复创建) + let queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + if (!queryLog) { + try { + const created = await ctx.model.ReturnQueryLog.create({ + warehouse_id: warehouseId, + store_id: resolvedStoreId || 0, + waybill_code: waybillCode, + remark: '站内信查询退回自动登记(已收到未拆包)', + is_notified: 0, + is_back: 0, + group_id: sourceGroupId, + group_name: sourceGroupName, + user_id: sourceUserId, + user_name: sourceUserName, + }); + queryLog = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + } catch (err) { + ctx.logger.warn(`[returnUnpack.queryByWaybill] 已收到未拆包登记退回查询记录失败: ${err.message}`); + } + } + + const orderInfo = await this._resolveReturnOrderInfo({ + order_express_id: received.order_express_id, + order_id: received.order_id, + warehouse_id: warehouseId, + store_id: resolvedStoreId || Number(received.store_id || 0), + }); + + return { + status: 'received', + waybill_code: waybillCode, + warehouse_name: warehouseName, + received, + query_log: queryLog, + order_info: orderInfo, + }; + } + + // 3. 未退回:查询退回查询登记表,无登记则自动登记(等待拆包后处理) + const queryLog = await this._findWaybillFlexible( + ctx.model.ReturnQueryLog, + { warehouse_id: warehouseId }, + waybillCode + ); + + if (queryLog) { + return { + status: 'not_returned', + waybill_code: waybillCode, + warehouse_name: warehouseName, + query_log: queryLog, + registered_now: false, + }; + } + + // 货主确定优先级:入参 store_id > 原运单反查 store_id > 0(未知货主) + let regStoreId = storeId; + if (!regStoreId) { + regStoreId = await this._resolveStoreIdByWaybill(waybillCode, warehouseId); + } + + let createdRow = null; + try { + const created = await ctx.model.ReturnQueryLog.create({ + warehouse_id: warehouseId, + store_id: regStoreId || 0, + waybill_code: waybillCode, + remark: '站内信查询退回自动登记', + is_notified: 0, + is_back: 0, + group_id: sourceGroupId, + group_name: sourceGroupName, + user_id: sourceUserId, + user_name: sourceUserName, + }); + createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + } catch (err) { + // 并发/异常兜底:登记失败不影响查询结论,回查已有登记 + ctx.logger.warn(`[returnUnpack.queryByWaybill] 自动登记退回查询记录失败: ${err.message}`); + try { + createdRow = await ctx.model.ReturnQueryLog.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + } catch (e) { + ctx.logger.warn(`[returnUnpack.queryByWaybill] 回查退回查询记录失败: ${e.message}`); + } + } + + return { + status: 'not_returned', + waybill_code: waybillCode, + warehouse_name: warehouseName, + query_log: createdRow, + registered_now: Boolean(createdRow), + }; + } + + /** + * 解析仓库名称(wms_store.company_name)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 仓库名称,查询失败返回空字符串。 + */ + async _resolveWarehouseName(warehouseId) { + const { ctx } = this; + try { + const store = await ctx.model.Store.findOne({ + where: { id: warehouseId }, + attributes: [ 'company_name' ], + raw: true, + }); + return store && store.company_name ? String(store.company_name) : ''; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveWarehouseName] 查询仓库名称失败: ${err.message}`); + return ''; + } + } + + /** + * 按运单号反查货主(wms_order_express)。 + * + * @param {string} waybillCode 运单号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 货主ID,未命中返回 0。 + */ + async _resolveStoreIdByWaybill(waybillCode, warehouseId) { + const { ctx } = this; + try { + // 兼容一单多件分段单号(京东 JDX...-1-1- 等) + const express = await this._findWaybillFlexible( + ctx.model.OrderExpress, + { warehouse_id: warehouseId }, + waybillCode, + [ 'store_id', 'waybill_code' ], + [[ 'id', 'DESC' ]] + ); + return express && Number(express.store_id) > 0 ? Number(express.store_id) : 0; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveStoreIdByWaybill] 反查货主失败: ${err.message}`); + return 0; + } + } + + /** + * 解析退回包裹关联的原单信息:平台交易单号 / 快递 / 自定义店铺名称。 + * 优先取主表快照(source_order_codes / shop_name),为空时实时兜底: + * 交易单号取原运单/原订单的 source_order_codes,店铺名称取货主合约 store_remask。 + * + * @param {Object} params 关联参数。 + * @param {number} [params.order_express_id] 原运单ID。 + * @param {number} [params.order_id] 原订单ID。 + * @param {number} [params.warehouse_id] 仓库ID(分表查询/合约查询用)。 + * @param {number} [params.store_id] 货主ID(自定义店铺名称查询用)。 + * @param {string} [params.source_order_codes] 平台交易单号快照。 + * @param {string} [params.shop_name] 店铺名称快照。 + * @return {Promise<{trade_no: string, express: string, shop_name: string}>} 原单信息。 + */ + async _resolveReturnOrderInfo({ order_express_id, order_id, warehouse_id, store_id, source_order_codes, shop_name } = {}) { + const { ctx } = this; + const info = { + trade_no: String(source_order_codes || '').trim(), + express: '', + shop_name: String(shop_name || '').trim(), + }; + + if (order_express_id) { + try { + const express = await ctx.model.OrderExpress.findOne({ + where: { id: order_express_id }, + attributes: [ 'logistics_name', 'source_order_codes' ], + raw: true, + }); + if (express) { + if (express.logistics_name) info.express = String(express.logistics_name); + if (!info.trade_no && express.source_order_codes) { + info.trade_no = String(express.source_order_codes); + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveReturnOrderInfo] 查询原运单失败: ${err.message}`); + } + } + + if (order_id && !info.trade_no) { + try { + let order = null; + const factory = ctx.model.OrderDeliveryFactory; + if (factory && typeof factory.getCurrentModel === 'function') { + const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ]; + const laneGetters = { + current: () => factory.getCurrentModel(warehouse_id), + history: () => factory.getHistoryModel(warehouse_id), + dispatch: () => factory.getDispatchModel(warehouse_id), + outsourced: () => factory.getOutsourcedModel(warehouse_id), + }; + + // 序列表定位优先:命中车道先查对应分表,未命中按原顺序遍历回退 + try { + if (typeof factory.getOrderLocation === 'function') { + const location = await factory.getOrderLocation(order_id, warehouse_id); + if (location && laneGetters[location]) { + laneLabels.sort((a, b) => (a === location ? -1 : b === location ? 1 : 0)); + } + } + } catch (err) { + // 定位失败忽略,保持遍历顺序 + } + + for (const lane of laneLabels) { + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ where: { id: order_id }, raw: true }); + if (row) { + order = row; + break; + } + } catch (err) { + // 该表可能不存在,继续下一张 + } + } + } + + // 分表均未命中:回退基表(存量订单) + if (!order) { + try { + order = await ctx.model.OrderDelivery.findOne({ + where: { id: order_id }, + attributes: [ 'id', 'source_order_codes', 'source_platform_code', 'logistics_name' ], + raw: true, + }); + } catch (err) { + // 主表查询失败忽略 + } + } + + if (order) { + info.trade_no = String(order.source_order_codes || order.source_platform_code || ''); + if (!info.express && order.logistics_name) info.express = String(order.logistics_name); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveReturnOrderInfo] 查询原订单失败: ${err.message}`); + } + } + + // 自定义店铺名称兜底:货主合约 store_remask + if (!info.shop_name && store_id) { + info.shop_name = await this._resolveStoreRemark(store_id, warehouse_id); + } + + return info; + } + + /** + * 删除拆包单(后台管理,不限制状态):事务内物理删除主表 + 明细,同步软删视频。 + * + * @param {number} id 拆包单ID。 + * @return {Promise} 删除结果。 + */ + async delete(id) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + + await ctx.model.transaction(async transaction => { + await ctx.model.ReturnUnpackDetail.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpackVideo.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpack.destroy({ + where: { id: unpack.id }, + transaction, + }); + }); + + return { id: unpack.id }; + } + + // =========================== + // 辅助方法 + // =========================== + + /** + * 生成拆包单号并插入主表(并发撞 uk_unpack_no 唯一索引时重新取号重试)。 + * 最多重试 5 次,指数退避 + 随机抖动;create 与 transferByWaybills 共用。 + * + * @param {Object} baseFields 主表插入字段(不含 unpack_no)。 + * @param {number} warehouseId 仓库ID(用于取号)。 + * @param {string} scene 调用场景标识(用于日志)。 + * @return {Promise} 创建后的主表记录(JSON 对象)。 + */ + async _insertMainWithRetry(baseFields, warehouseId, scene) { + const { ctx } = this; + const maxAttempts = 5; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + const unpackNo = await this._generateUnpackNo(warehouseId); + try { + const created = await ctx.model.ReturnUnpack.create({ + ...baseFields, + unpack_no: unpackNo, + }); + return created && typeof created.toJSON === 'function' ? created.toJSON() : created; + } catch (err) { + const isUniqueConflict = err && ( + err.name === 'SequelizeUniqueConstraintError' + || (err.parent && err.parent.code === 'ER_DUP_ENTRY') + ); + if (isUniqueConflict && attempt < maxAttempts) { + // 并发撞号:指数退避 + 随机抖动后重新取号重试,降低同一序号再次碰撞概率 + const backoffMs = Math.min(500, attempt * 40) + Math.floor(Math.random() * 60); + ctx.logger.warn( + `[returnUnpack.${scene}] 拆包单号唯一冲突,第 ${attempt} 次重试(退避 ${backoffMs}ms): ${err.message}` + ); + await new Promise(resolve => setTimeout(resolve, backoffMs)); + continue; + } + throw err; + } + } + throw this.createBusinessError('拆包单号生成失败,请重试', 500); + } + + /** + * 处理单个运单的批量转入:校验运单 → 标记退回 → 幂等复用/新建拆包单 → 复制订单明细。 + * 子单(business_key > 1)跳过;一个运单只允许一条有效拆包单。 + * + * @param {Object} params 单运单处理参数。 + * @param {Object|null} params.orderExpress 调用方批量反查得到的运单行;null=不存在或不属于当前仓库。 + * @param {number} params.waybillId 运单表主键ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.unpackerId 拆包人员工号ID。 + * @param {string} params.unpackerName 拆包人员工号名称。 + * @return {Promise} 成功项:{ waybill_id, waybill_code, unpack_id, unpack_no, reused, detail_count, total_quantity }。 + */ + async _transferOneWaybill({ orderExpress, waybillId, warehouseId, unpackerId, unpackerName }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 1. 校验运单(调用方已按 运单ID + 仓库 批量反查,避免跨仓运单被转入本仓拆包单) + if (!orderExpress) { + throw this.createBusinessError('运单不存在', 404); + } + + // 子单不处理:business_key 为空或 1 视为主单,>1 跳过 + if (Number(orderExpress.business_key || 0) > 1) { + throw this.createBusinessError('运单为子单(business_key>1),跳过', 400); + } + + // 运单号是拆包单的必填业务键:未取号的运单无可登记的运单号 + const waybillCode = String(orderExpress.waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('运单号为空,无法转入退件登记', 400); + } + + // 2. 命中的运单统一标记退回(不做其他前置条件限制) + try { + await ctx.model.OrderExpress.update( + { is_back: 'Y' }, + { where: { id: orderExpress.id } } + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 标记运单退回失败 id=${orderExpress.id}: ${err.message}`); + } + + // 3. 幂等复用:同仓库 + 同运单号已存在有效(status != 'cancelled')拆包单时直接复用 + let existing = null; + try { + const existingList = await ctx.model.ReturnUnpack.findAll({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + status: { [Op.ne]: 'cancelled' }, + }, + attributes: [ 'id', 'unpack_no', 'return_received_id', 'order_express_id', 'order_id' ], + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + if (existingList.length > 0) { + existing = existingList[0]; + // 同运单号可能有多张拆包单:优先复用已录明细的最新单(与 create 口径一致) + const countRows = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: { [Op.in]: existingList.map(row => row.id) } }, + attributes: [ + 'unpack_id', + [ ctx.model.fn('COUNT', ctx.model.col('id')), 'detail_count' ], + ], + group: [ 'unpack_id' ], + raw: true, + }); + const detailCountMap = new Map( + countRows.map(row => [ Number(row.unpack_id), Number(row.detail_count) || 0 ]) + ); + const withDetails = existingList.find(row => (detailCountMap.get(Number(row.id)) || 0) > 0); + if (withDetails) { + existing = withDetails; + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 查重已有拆包单失败 ${waybillCode}: ${err.message}`); + } + + // 可选:命中退回收到登记(同仓库 + 同运单号)时回填 return_received_id + const returnReceivedId = await this._resolveReturnReceivedId(warehouseId, waybillCode); + + if (existing) { + const unpackId = Number(existing.id); + + // 复用单明细为空时按规则 4 补写订单明细 + let summary = await this._countDetails(unpackId); + if (summary.detail_count === 0) { + try { + const backfillOrderId = Number(existing.order_id || 0) || Number(orderExpress.order_id || 0); + await this._backfillDetailsFromOrder(unpackId, warehouseId, backfillOrderId); + summary = await this._countDetails(unpackId); + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 复用单补写明细失败 unpack_id=${unpackId}: ${err.message}`); + } + } + + // 主表退回收到单ID为空时回填 + if (returnReceivedId && !existing.return_received_id) { + try { + await ctx.model.ReturnUnpack.update( + { return_received_id: returnReceivedId }, + { where: { id: unpackId } } + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 回填退回收到单失败 unpack_id=${unpackId}: ${err.message}`); + } + } + + return { + waybill_id: waybillId, + waybill_code: waybillCode, + unpack_id: unpackId, + unpack_no: existing.unpack_no || '', + reused: true, + detail_count: summary.detail_count, + total_quantity: summary.total_quantity, + }; + } + + // 4. 新建拆包单:解析关联订单明细(优先 items JSON,为空回退明细分表,复用 afterSale 现成实现) + const orderId = Number(orderExpress.order_id || 0); + let order = null; + if (orderId > 0) { + try { + order = await ctx.service.systems.afterSale._resolveOrderDetail(orderId, warehouseId); + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 拉取订单详情失败 orderId=${orderId}: ${err.message}`); + } + } + + const orderItems = order && Array.isArray(order.items) ? order.items : []; + if (orderItems.length === 0) { + throw this.createBusinessError('运单关联订单无明细可复制', 400); + } + + const storeId = Number(orderExpress.store_id || 0) || Number(order && order.store_id || 0) || null; + const storeRemark = await this._resolveStoreRemark(storeId, warehouseId); + + const now = new Date(); + const unpackDate = app.formatDate(now, 'YYYY-MM-DD'); + + const createdRow = await this._insertMainWithRetry({ + warehouse_id: warehouseId, + return_received_id: returnReceivedId, + waybill_code: waybillCode, + unpack_date: unpackDate, + start_time: now, + end_time: null, + unpacker_id: unpackerId, + unpacker_name: unpackerName || '未命名', + status: 'unpacking', + detail_status: 'none_recognized', + total_items: 0, + total_quantity: 0, + order_express_id: orderExpress.id, + order_id: orderId > 0 ? orderId : null, + store_id: storeId, + source_order_codes: orderExpress.source_order_codes || null, + shop_name: storeRemark || null, + camera_ids: null, + remark: null, + }, warehouseId, 'transferByWaybills'); + + const unpackId = Number(createdRow.id); + + // 5. 复制订单明细(逐行 1:1 复制,不做合并/换算),插入后回填主表汇总 + const detailRows = await this._buildTransferDetailRows(orderItems); + await ctx.model.ReturnUnpackDetail.bulkCreate( + detailRows.map(row => ({ ...row, unpack_id: unpackId, warehouse_id: warehouseId })) + ); + const summary = await this._recalcMain(unpackId, warehouseId); + + return { + waybill_id: waybillId, + waybill_code: waybillCode, + unpack_id: unpackId, + unpack_no: createdRow.unpack_no || '', + reused: false, + detail_count: summary.total_items, + total_quantity: summary.total_quantity, + }; + } + + /** + * 按规则补写拆包单明细:解析关联订单明细(优先 items JSON,为空回退明细分表)并逐行复制写入。 + * + * @param {number} unpackId 拆包单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} orderId 订单ID。 + * @return {Promise} 写入的明细行数。 + */ + async _backfillDetailsFromOrder(unpackId, warehouseId, orderId) { + const { ctx } = this; + if (!orderId || !Number.isFinite(orderId) || orderId <= 0) { + throw this.createBusinessError('未找到关联订单', 404); + } + + let order = null; + try { + order = await ctx.service.systems.afterSale._resolveOrderDetail(orderId, warehouseId); + } catch (err) { + ctx.logger.warn(`[returnUnpack._backfillDetailsFromOrder] 拉取订单详情失败 orderId=${orderId}: ${err.message}`); + } + + const orderItems = order && Array.isArray(order.items) ? order.items : []; + if (orderItems.length === 0) { + throw this.createBusinessError('订单无明细可复制', 400); + } + + const detailRows = await this._buildTransferDetailRows(orderItems); + await ctx.model.ReturnUnpackDetail.bulkCreate( + detailRows.map(row => ({ ...row, unpack_id: unpackId, warehouse_id: warehouseId })) + ); + await this._recalcMain(unpackId, warehouseId); + return detailRows.length; + } + + /** + * 统计拆包单明细行数与总数量(不更新主表)。 + * + * @param {number} unpackId 拆包单ID。 + * @return {Promise} { detail_count, total_quantity }。 + */ + async _countDetails(unpackId) { + const { ctx } = this; + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: unpackId }, + attributes: [ 'quantity' ], + raw: true, + }); + return { + detail_count: details.length, + total_quantity: details.reduce((sum, row) => sum + (Number(row.quantity) || 0), 0), + }; + } + + /** + * 反查退回收到登记单ID(同仓库 + 同运单号,取最新一条),用于主表回填。 + * + * @param {number} warehouseId 仓库ID。 + * @param {string} waybillCode 运单号。 + * @return {Promise} 退回收到单ID,未命中返回 null。 + */ + async _resolveReturnReceivedId(warehouseId, waybillCode) { + const { ctx } = this; + try { + const received = await ctx.model.ReturnReceived.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + attributes: [ 'id' ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + return received ? Number(received.id) || null : null; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveReturnReceivedId] 反查退回收到单失败: ${err.message}`); + return null; + } + } + + /** + * 将订单明细逐行映射为拆包明细行(1:1 复制,不做合并/换算)。 + * 口径参考 addDetail:有 stock_id 记 is_recognized=1;spec 仅在取到库存 sku_property 时填; + * quantity 取订单行 plan_qty(最小 1);product_status 固定 normal; + * product_snapshot 仅在取到库存详情时写入。 + * + * @param {Array} orderItems 订单明细行(来自 afterSale._resolveOrderDetail 的 items)。 + * @return {Promise>} 拆包明细行数组(不含 unpack_id / warehouse_id)。 + */ + async _buildTransferDetailRows(orderItems) { + const { ctx } = this; + const stockIds = [ ...new Set( + orderItems + .map(item => Number(item && item.stock_id)) + .filter(id => Number.isInteger(id) && id > 0) + ) ]; + + /** @type {Map} 库存详情快照映射 */ + const stockMap = new Map(); + if (stockIds.length > 0) { + try { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [this.app.Sequelize.Op.in]: stockIds } }, + attributes: [ + 'id', 'item_code', 'goods_code', 'item_name', + 'sku_property', 'stock_unit', 'item_type', + ], + raw: true, + }); + for (const row of stockRows) { + stockMap.set(Number(row.id), row); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._buildTransferDetailRows] 批量查询库存详情失败: ${err.message}`); + } + } + + return orderItems.map(item => { + const stockId = Number(item && item.stock_id); + const stock = stockId > 0 ? (stockMap.get(stockId) || null) : null; + const isRecognized = stockId > 0 ? 1 : 0; + return { + stock_id: isRecognized ? stockId : null, + is_recognized: isRecognized, + item_code: String((item && item.item_code) || (stock && stock.item_code) || '').slice(0, 50) || null, + item_name: String((item && item.item_name) || (stock && stock.item_name) || '未知商品').slice(0, 255), + spec: stock && stock.sku_property ? String(stock.sku_property).slice(0, 100) : null, + quantity: Math.max(1, parseInt(item && item.plan_qty) || 1), + product_status: 'normal', + product_snapshot: stock ? JSON.stringify({ + item_code: stock.item_code || '', + goods_code: stock.goods_code || '', + item_name: stock.item_name || '', + sku_property: stock.sku_property || '', + stock_unit: stock.stock_unit || '', + item_type: stock.item_type || '', + }) : null, + remark: null, + }; + }); + } + + /** + * 按主键查询拆包单,并校验仓库隔离。 + * + * @param {number} id 拆包单ID。 + * @return {Promise} 拆包单原始数据。 + */ + async _findByIdChecked(id) { + const { ctx } = this; + const normalizedId = Number(id || 0); + if (!Number.isFinite(normalizedId) || normalizedId <= 0) { + throw this.createBusinessError('id 必填且必须为正整数', 400); + } + + const record = await ctx.model.ReturnUnpack.findOne({ + where: { id: normalizedId }, + raw: true, + }); + if (!record) { + throw this.createBusinessError('拆包单不存在', 404); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (warehouseId > 0 && Number(record.warehouse_id) !== warehouseId) { + throw this.createBusinessError('无权访问该拆包单', 403); + } + + return record; + } + + /** + * 校验拆包单处于未完成(unpacking)状态。 + * + * @param {Object} unpack 拆包单记录。 + */ + _assertUnpacking(unpack) { + if (String(unpack.status) !== 'unpacking') { + throw this.createBusinessError('拆包单已提交或已取消,不可操作', 400); + } + } + + /** + * 查询明细并校验属于指定拆包单。 + * + * @param {number} unpackId 拆包单ID。 + * @param {number} detailId 明细ID。 + * @return {Promise} 明细原始数据。 + */ + async _findDetailChecked(unpackId, detailId) { + const { ctx } = this; + const normalizedDetailId = Number(detailId || 0); + if (!Number.isFinite(normalizedDetailId) || normalizedDetailId <= 0) { + throw this.createBusinessError('detail_id 必填且必须为正整数', 400); + } + + const detail = await ctx.model.ReturnUnpackDetail.findOne({ + where: { id: normalizedDetailId, unpack_id: unpackId }, + raw: true, + }); + if (!detail) { + throw this.createBusinessError('明细不存在或不属于该拆包单', 404); + } + + return detail; + } + + /** + * 重算主表汇总字段:total_items / total_quantity / detail_status。 + * + * @param {number} unpackId 拆包单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 最新汇总对象。 + */ + async _recalcMain(unpackId, warehouseId) { + const { ctx } = this; + + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: unpackId }, + attributes: [ 'id', 'quantity', 'is_recognized' ], + raw: true, + }); + + const totalItems = details.length; + const totalQuantity = details.reduce((sum, row) => sum + (Number(row.quantity) || 0), 0); + + let detailStatus = 'none_recognized'; + if (totalItems > 0) { + const recognizedCount = details.filter(row => Number(row.is_recognized) === 1).length; + if (recognizedCount === totalItems) { + detailStatus = 'all_recognized'; + } else if (recognizedCount > 0) { + detailStatus = 'partial_recognized'; + } + } + + await ctx.model.ReturnUnpack.update( + { + total_items: totalItems, + total_quantity: totalQuantity, + detail_status: detailStatus, + }, + { where: { id: unpackId, warehouse_id: warehouseId } } + ); + + return { + total_items: totalItems, + total_quantity: totalQuantity, + detail_status: detailStatus, + }; + } + + /** + * 组装主表展示字段(识别状态派生字段 + 时间格式化 + camera_ids 数组化)。 + * + * @param {Object} row 主表原始数据。 + * @return {Promise} 组装后的记录。 + */ + async _enrichRow(row) { + const { app } = this; + const record = { ...row }; + + record.is_original_return = Boolean(record.order_express_id); + + // 视频派生字段(与 order.packing.list 对齐):记录含 videos 数组时计算 + if (Array.isArray(record.videos)) { + record.has_video = record.videos.length > 0 ? 1 : 2; + record.video_enable = record.videos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2; + + // 视频地址拼接 CDN 域名(与 order.packing 对齐:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path}) + const warehouseId = Number(record.warehouse_id || 0); + if (warehouseId > 0) { + const recordingComputerId = await this._getRecordingComputerId(warehouseId); + record.videos = record.videos.map(v => ({ + ...v, + video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url), + })); + } + } + + // camera_ids 归一化为数组(MySQL JSON 列可能返回字符串) + if (record.camera_ids !== undefined && record.camera_ids !== null) { + if (typeof record.camera_ids === 'string') { + try { + const parsed = JSON.parse(record.camera_ids); + record.camera_ids = Array.isArray(parsed) ? parsed : []; + } catch (err) { + record.camera_ids = []; + } + } else if (!Array.isArray(record.camera_ids)) { + record.camera_ids = []; + } + } else { + record.camera_ids = []; + } + + // 时间格式化 + record.unpack_date = record.unpack_date ? app.formatDate(record.unpack_date, 'YYYY-MM-DD') : null; + record.start_time = record.start_time ? app.formatDate(record.start_time) : null; + record.end_time = record.end_time ? app.formatDate(record.end_time) : null; + record.created_at = record.created_at ? app.formatDate(record.created_at) : null; + record.updated_at = record.updated_at ? app.formatDate(record.updated_at) : null; + + return record; + } + + /** + * 列表场景视频数组扁平化(对齐 order.packing.list 输出口径)。 + * 仅输出前端需要的精简字段(id/video_url/status/camera_id/camera_name); + * detail 等场景的 videos 保持完整关联结构不变。 + * + * @param {Object} row 主表记录(含 videos 关联数组)。 + * @return {Object} 扁平化后的记录。 + */ + _flattenVideos(row) { + if (Array.isArray(row.videos)) { + row.videos = row.videos.map(v => ({ + id: v.id, + video_url: v.video_url, + status: v.status || null, + camera_id: v.camera_id || null, + camera_name: (v.camera && (v.camera.custom_name || v.camera.channel_name)) || null, + })); + } + return row; + } + + /** + * 批量附加库存详情(条码/图片等)到明细行。 + * 统一走 stockWarehouse.getStockDetails 通用方法(带缓存,含 barcodes/image_url/ + * packing_requirements/stock_unit 等字段),为每条有 stock_id 的明细补充 stock 字段; + * 商品失效或查询失败时 stock 为 null(不影响主流程)。 + * + * @param {Array} details 明细行数组(含 stock_id,就地补充 stock 字段)。 + * @param {number} warehouseId 仓库ID(用于库存详情查询的仓库过滤)。 + * @return {Promise>} 补充 stock 字段后的明细行数组。 + */ + async _enrichDetailsWithStock(details, warehouseId) { + const { ctx } = this; + if (!Array.isArray(details) || details.length === 0) { + return details || []; + } + + const stockIds = [ ...new Set( + details + .map(row => Number(row.stock_id)) + .filter(sid => Number.isInteger(sid) && sid > 0) + ) ]; + + /** @type {Map} */ + const stockMap = new Map(); + if (stockIds.length > 0) { + try { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const detail of stockDetails) { + if (detail && detail.id != null) { + stockMap.set(Number(detail.id), detail); + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._enrichDetailsWithStock] 批量获取库存详情失败: ${err.message}`); + } + } + + for (const row of details) { + const stockId = Number(row.stock_id); + row.stock = stockId > 0 ? (stockMap.get(stockId) || null) : null; + } + return details; + } + + /** + * 查询货主合约备注名称(wms_store_warehouse.store_remask)。 + * + * @param {number} storeId 货主ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 货主备注名称,未命中时返回空字符串。 + */ + async _resolveStoreRemark(storeId, warehouseId) { + const { ctx } = this; + const normalizedStoreId = Number(storeId || 0); + const normalizedWarehouseId = Number(warehouseId || 0); + if (!normalizedStoreId || !normalizedWarehouseId) { + return ''; + } + try { + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: normalizedStoreId, warehouse_id: normalizedWarehouseId }, + attributes: [ 'store_remask' ], + raw: true, + }); + return (sw && sw.store_remask) || ''; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveStoreRemark] 查询货主备注失败: ${err.message}`); + return ''; + } + } + + /** + * 生成拆包单号(原子取号)。 + * 格式:RP + YYYYMMDD + 6位序号(如 RP20260813000001)。 + * 取号基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date 串行化并发事务): + * INSERT ... VALUES (:seed + 1) ON DUPLICATE KEY UPDATE + * current_seq = GREATEST(current_seq, :seed) + 1 + * 其中 :seed 为当日主表已有最大序号,保证历史数据对齐(首日启用不撞已有单号); + * upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq, + * 避免 REPEATABLE READ 快照读读到旧值导致撞号或跳号。 + * 注意:不再依赖 LAST_INSERT_ID() 回读,因为 fresh INSERT 时其会被序列表自增主键覆盖。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 拆包单号。 + */ + async _generateUnpackNo(warehouseId) { + const { ctx } = this; + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + const datePart = `${year}${month}${day}`; + const prefix = 'RP'; + const bizType = 'return_unpack'; + + const sequence = await ctx.model.transaction(async transaction => { + // 历史对齐基准:当日主表已有最大序号(无则为 0) + const seedRows = await ctx.model.query( + `SELECT IFNULL(MAX(CAST(RIGHT(unpack_no, 6) AS UNSIGNED)), 0) AS max_seq + FROM wms_return_unpack + WHERE warehouse_id = :warehouseId AND unpack_no LIKE :pattern`, + { + replacements: { warehouseId, pattern: `${prefix}${datePart}%` }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq) || 0; + + // 原子取号:单条 upsert 内按唯一键串行化并发事务递增 current_seq + await ctx.model.query( + `INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at) + VALUES (:warehouseId, :bizType, :datePart, :seed + 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`, + { + replacements: { warehouseId, bizType, datePart, seed }, + transaction, + } + ); + + // 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化), + // FOR UPDATE 返回本事务最新写入值或最新提交版本,不受旧快照影响 + const rows = await ctx.model.query( + `SELECT current_seq + FROM wms_number_sequence + WHERE warehouse_id = :warehouseId AND biz_type = :bizType AND date_part = :datePart + FOR UPDATE`, + { + replacements: { warehouseId, bizType, datePart }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + return Number(rows && rows[0] && rows[0].current_seq) || 1; + }); + + if (sequence > 999999) { + throw this.createBusinessError('当日拆包单号已用尽(序号超过 999999),请联系管理员', 500); + } + + return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`; + } + + /** + * 根据标准化 where 条件构建主表 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * 文本字段(unpack_no / waybill_code / unpacker_name)支持 {operator,value} 标准结构: + * operator=like 时按 LIKE '%值%' 模糊匹配(value 为数组时多值取并集)、eq/in 精确、ne/notin 取反、between 范围等; + * 其中 unpacker_name 为拆包人员工号名称快照列(wms_return_unpack.unpacker_name)。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildListWhere(where = {}, Op) { + const queryWhere = {}; + + // has_video 筛选:1=有视频记录 2=无视频记录(口径对齐 order.packing.list) + if (where.has_video !== undefined && where.has_video !== null) { + const hasVideoValue = Number(where.has_video?.value ?? where.has_video); + if (hasVideoValue === 1 || hasVideoValue === 2) { + const existsSql = 'EXISTS (SELECT 1 FROM wms_return_unpack_video WHERE unpack_id = wms_return_unpack.id AND deleted_at IS NULL)'; + const cond = hasVideoValue === 1 + ? this.app.Sequelize.literal(existsSql) + : this.app.Sequelize.literal(`NOT ${existsSql}`); + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), cond ]; + } + } + + // video_enable 筛选:1=录像可用 2=录像不可用(口径对齐 order.packing.list) + if (where.video_enable !== undefined && where.video_enable !== null) { + const videoEnableValue = Number(where.video_enable?.value ?? where.video_enable); + if (videoEnableValue === 1 || videoEnableValue === 2) { + const existsSql = "EXISTS (SELECT 1 FROM wms_return_unpack_video WHERE unpack_id = wms_return_unpack.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"; + const cond = videoEnableValue === 1 + ? this.app.Sequelize.literal(existsSql) + : this.app.Sequelize.literal(`NOT ${existsSql}`); + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), cond ]; + } + } + + const directFields = [ + 'warehouse_id', 'unpacker_id', 'return_received_id', 'store_id', + 'order_express_id', 'order_id', 'status', 'detail_status', + ]; + + for (const field of directFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 日期/时间范围字段 + const rangeFields = [ 'unpack_date', 'start_time', 'end_time', 'created_at', 'updated_at' ]; + for (const field of rangeFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 文本字段(支持模糊;unpacker_name 为拆包人员工号名称快照列) + const textFields = [ 'unpack_no', 'waybill_code', 'unpacker_name' ]; + for (const field of textFields) { + const condition = where[field]; + if (condition === undefined || condition === null) { + continue; + } + // 空值条件跳过:条件对象取 condition.value,为 null/undefined/纯空白字符串/空数组时不生成该字段条件, + // 避免生成 IS NULL / IN () 等恒空条件(如 unpacker_name 列 NOT NULL,IS NULL 会清空整个列表)。 + // 例外:operator=like 的空数组由 _resolveConditionValue 退化为 '%%'(全匹配、不过滤,既有测试锁定该口径)。 + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const conditionValue = condition.value; + const conditionOperator = String(condition.operator || '').trim().toLowerCase(); + const isEmptyValue = conditionValue === null + || conditionValue === undefined + || (typeof conditionValue === 'string' && conditionValue.trim() === '') + || (Array.isArray(conditionValue) && conditionValue.length === 0 && conditionOperator !== 'like'); + if (isEmptyValue) { + continue; + } + } + queryWhere[field] = this._resolveConditionValue(condition, Op); + } + + return queryWhere; + } + + /** + * 根据标准化 where 条件构建明细表 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildDetailListWhere(where = {}, Op) { + const queryWhere = {}; + + const fields = [ + 'warehouse_id', 'unpack_id', 'stock_id', 'barcode', + 'is_recognized', 'product_status', + ]; + + for (const field of fields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + return queryWhere; + } + + /** + * 构建录像列表 where 条件(unpack_id 必填等值;camera_id/status 可选等值)。 + * + * @param {Object} where 标准化条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildVideoListWhere(where = {}, Op) { + const queryWhere = {}; + + if (where.unpack_id !== undefined && where.unpack_id !== null) { + queryWhere.unpack_id = this._resolveConditionValue(where.unpack_id, Op); + } + if (where.camera_id !== undefined && where.camera_id !== null) { + queryWhere.camera_id = this._resolveConditionValue(where.camera_id, Op); + } + if (where.status !== undefined && where.status !== null) { + queryWhere.status = this._resolveConditionValue(where.status, Op); + } + + return queryWhere; + } + + /** + * 录像列表排序(默认按 id 升序)。 + * + * @param {Object} sort 排序参数。 + * @return {Array>} Sequelize order 数组。 + */ + _buildVideoListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field || 'id'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'asc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + const allowed = new Set([ 'id', 'created_at', 'updated_at', 'camera_id' ]); + const safeSortField = allowed.has(sortField) ? sortField : 'id'; + + return [[ safeSortField, sortOrder ]]; + } + + /** + * 解析标准化条件值为 Sequelize 可用的条件对象。 + * like 分支:value 为标量时保持 LIKE '%值%' 行为不变;value 为数组时按元素做并集模糊 + * (多值 → { [Op.or]: [{ [Op.like]: '%值1%' }, ...] }),数组经 trim/去空归一后为空则退化为 '%%'(全匹配、不过滤)。 + * + * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。 + * @param {Object} Op Sequelize Op 对象。 + * @return {*} Sequelize 条件。 + */ + _resolveConditionValue(condition, Op) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const operator = condition.operator; + const value = condition.value; + + if (!operator) { + return value; + } + + switch (operator) { + case 'eq': + return value; + case 'ne': + return { [Op.ne]: value }; + case 'in': + return { [Op.in]: Array.isArray(value) ? value : [ value ] }; + case 'notin': + return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; + case 'like': { + if (Array.isArray(value)) { + const likeList = value + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(Boolean); + if (likeList.length === 0) { + return { [Op.like]: '%%' }; + } + if (likeList.length === 1) { + return { [Op.like]: `%${likeList[0]}%` }; + } + return { [Op.or]: likeList.map(item => ({ [Op.like]: `%${item}%` })) }; + } + return { [Op.like]: `%${value}%` }; + } + case 'gt': + return { [Op.gt]: value }; + case 'gte': + return { [Op.gte]: value }; + case 'lt': + return { [Op.lt]: value }; + case 'lte': + return { [Op.lte]: value }; + case 'between': + return { [Op.between]: Array.isArray(value) ? value : [ value ] }; + default: + return value; + } + } + + return condition; + } + + /** + * 根据 sort 参数构建 Sequelize 排序数组。 + * + * @param {Object} sort 排序参数。 + * @param {string} scene 场景标识(return_unpack / return_unpack_detail)。 + * @return {Array>} Sequelize order 数组。 + */ + _buildListOrder(sort = {}, scene = 'return_unpack') { + const sortField = sort.sortField || sort.sort_field || 'created_at'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + const mainFields = new Set([ + 'id', 'created_at', 'updated_at', 'unpack_date', 'start_time', 'end_time', + 'unpack_no', 'waybill_code', + ]); + const detailFields = new Set([ 'id', 'created_at', 'updated_at', 'quantity' ]); + + const allowed = scene === 'return_unpack_detail' ? detailFields : mainFields; + const safeSortField = allowed.has(sortField) ? sortField : 'created_at'; + + // 追加主键作为次级排序:排序键可能并列(如 created_at 精确到秒,生产存在同秒多条), + // 并列时 MySQL 返回顺序不稳定,list 翻页与 export 的 offset 分页会出现重复/漏行。 + const order = [[ safeSortField, sortOrder ]]; + if (safeSortField !== 'id') { + order.push([ 'id', sortOrder ]); + } + return order; + } +} + +module.exports = ReturnUnpackService; diff --git a/app/service/systems/return_waybill.js b/app/service/systems/return_waybill.js new file mode 100644 index 0000000..67d2c52 --- /dev/null +++ b/app/service/systems/return_waybill.js @@ -0,0 +1,376 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 未退登记模块业务逻辑层。 + * 复用 wms_return_query_log 表,提供「货主 + 运单号」未退登记的增删查改。 + * 所有数据库交互集中在此层,供 systemMethods/returnWaybill.js 调用。 + */ +class ReturnWaybillService extends Service { + /** + * 创建带业务错误码的异常对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 未退登记(增)。入参:运单号 + 货主ID。 + * 同 warehouse_id + store_id + waybill_code 已存在时返回已有记录(幂等)。 + * + * @param {Object} params 登记参数。 + * @param {string} params.waybill_code 运单号(必填)。 + * @param {number} params.store_id 货主ID(必填)。 + * @param {string} [params.remark] 备注。 + * @return {Promise} { record, duplicated }。 + */ + async create({ waybill_code, store_id, remark }) { + const { ctx } = this; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const storeId = Number(store_id || 0); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createBusinessError('store_id 必填且必须为正整数', 400); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + // 货主合约校验:wms_store_warehouse 存在 store_id + warehouse_id 合约 + await this._assertStoreContract(storeId, warehouseId); + + // 幂等:同仓库+货主+运单号已存在 → 返回已有记录 + const existing = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + waybill_code: waybillCode, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (existing) { + return { record: this._formatRow(existing), duplicated: true }; + } + + const created = await ctx.model.ReturnQueryLog.create({ + warehouse_id: warehouseId, + store_id: storeId, + waybill_code: waybillCode, + remark: remark ? String(remark).slice(0, 500) : null, + is_notified: 0, + is_back: 0, + }); + + const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + return { record: this._formatRow(createdRow), duplicated: false }; + } + + /** + * 修改登记(改)。入参:id + 可改运单号/货主ID/备注。 + * + * @param {Object} params 修改参数。 + * @param {number} params.id 登记记录ID(必填)。 + * @param {string} [params.waybill_code] 运单号。 + * @param {number} [params.store_id] 货主ID。 + * @param {string} [params.remark] 备注。 + * @return {Promise} { record }。 + */ + async update({ id, waybill_code, store_id, remark }) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const record = await this._findByIdChecked(id); + + const updateFields = {}; + const nextWaybillCode = waybill_code !== undefined && waybill_code !== null + ? String(waybill_code).trim() + : record.waybill_code; + if (!nextWaybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const nextStoreId = store_id !== undefined && store_id !== null + ? Number(store_id) + : Number(record.store_id); + if (!Number.isFinite(nextStoreId) || nextStoreId <= 0) { + throw this.createBusinessError('store_id 必填且必须为正整数', 400); + } + + if (waybill_code !== undefined && waybill_code !== null) { + updateFields.waybill_code = nextWaybillCode; + } + if (store_id !== undefined && store_id !== null && Number(store_id) !== Number(record.store_id)) { + // 货主变更时校验新货主合约 + await this._assertStoreContract(nextStoreId, record.warehouse_id); + updateFields.store_id = nextStoreId; + } + if (remark !== undefined && remark !== null) { + updateFields.remark = String(remark).slice(0, 500); + } + + // 冲突防护:改后与另一条同仓库+货主+运单号冲突则拒绝 + const changed = Object.keys(updateFields).length > 0; + if (changed) { + const conflict = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: record.warehouse_id, + store_id: nextStoreId, + waybill_code: nextWaybillCode, + id: { [Op.ne]: record.id }, + }, + attributes: [ 'id' ], + raw: true, + }); + if (conflict) { + throw this.createBusinessError('已存在相同货主 + 运单号的登记记录', 409); + } + + await ctx.model.ReturnQueryLog.update(updateFields, { + where: { id: record.id }, + }); + } + + const updated = await ctx.model.ReturnQueryLog.findOne({ + where: { id: record.id }, + raw: true, + }); + + return { record: this._formatRow(updated) }; + } + + /** + * 分页查询登记列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { list, pagination }。 + */ + async list(where = {}, pagination = {}, sort = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = this._buildListWhere(where, Op); + const order = this._buildListOrder(sort); + + const { count, rows } = await ctx.model.ReturnQueryLog.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + return { + list: rows.map(row => this._formatRow(row)), + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 查询单条登记详情。 + * + * @param {number} id 登记记录ID。 + * @return {Promise} { record }。 + */ + async detail(id) { + const record = await this._findByIdChecked(id); + return { record: this._formatRow(record) }; + } + + /** + * 删除单条登记(物理删除)。 + * + * @param {number} id 登记记录ID。 + * @return {Promise} 删除结果,含被删除记录 id。 + */ + async delete(id) { + const { ctx } = this; + const record = await this._findByIdChecked(id); + await ctx.model.ReturnQueryLog.destroy({ where: { id: record.id } }); + return { id: record.id }; + } + + // =========================== + // 辅助方法 + // =========================== + + /** + * 按主键查询登记记录,并校验仓库隔离。 + * + * @param {number} id 登记记录ID。 + * @return {Promise} 登记记录原始数据。 + */ + async _findByIdChecked(id) { + const { ctx } = this; + const normalizedId = Number(id || 0); + if (!Number.isFinite(normalizedId) || normalizedId <= 0) { + throw this.createBusinessError('id 必填且必须为正整数', 400); + } + + const record = await ctx.model.ReturnQueryLog.findOne({ + where: { id: normalizedId }, + raw: true, + }); + if (!record) { + throw this.createBusinessError('登记记录不存在', 404); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (warehouseId > 0 && Number(record.warehouse_id) !== warehouseId) { + throw this.createBusinessError('无权访问该登记记录', 403); + } + + return record; + } + + /** + * 货主合约校验:wms_store_warehouse 必须存在 store_id + warehouse_id 合约。 + * + * @param {number} storeId 货主ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 校验失败抛业务异常。 + */ + async _assertStoreContract(storeId, warehouseId) { + const { ctx } = this; + const contract = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + if (!contract) { + throw this.createBusinessError('货主在当前仓库无合约关系,无法登记', 400); + } + } + + /** + * 格式化登记记录(时间字段本地化)。 + * + * @param {Object} row 登记记录原始数据。 + * @return {Object} 格式化后的记录。 + */ + _formatRow(row) { + const { app } = this; + const record = { ...row }; + record.created_at = record.created_at ? app.formatDate(record.created_at) : null; + record.updated_at = record.updated_at ? app.formatDate(record.updated_at) : null; + return record; + } + + /** + * 根据标准化 where 条件构建 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildListWhere(where = {}, Op) { + const queryWhere = {}; + + const fields = [ + 'warehouse_id', 'store_id', 'waybill_code', + 'is_notified', 'is_back', 'created_at', 'updated_at', + ]; + + for (const field of fields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + return queryWhere; + } + + /** + * 解析标准化条件值为 Sequelize 可用的条件对象。 + * + * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。 + * @param {Object} Op Sequelize Op 对象。 + * @return {*} Sequelize 条件。 + */ + _resolveConditionValue(condition, Op) { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const operator = condition.operator; + const value = condition.value; + + if (!operator) { + return value; + } + + switch (operator) { + case 'eq': + return value; + case 'ne': + return { [Op.ne]: value }; + case 'in': + return { [Op.in]: Array.isArray(value) ? value : [ value ] }; + case 'notin': + return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; + case 'like': + if (Array.isArray(value) && value.length > 0) { + return { + [Op.or]: value.map(item => ({ [Op.like]: `%${item}%` })), + }; + } + return { [Op.like]: `%${value}%` }; + case 'gt': + return { [Op.gt]: value }; + case 'gte': + return { [Op.gte]: value }; + case 'lt': + return { [Op.lt]: value }; + case 'lte': + return { [Op.lte]: value }; + case 'between': + return { [Op.between]: Array.isArray(value) ? value : [ value ] }; + default: + return value; + } + } + + return condition; + } + + /** + * 根据 sort 参数构建 Sequelize 排序数组。 + * + * @param {Object} sort 排序参数。 + * @return {Array>} Sequelize order 数组。 + */ + _buildListOrder(sort = {}) { + const sortField = sort.sortField || sort.sort_field || 'created_at'; + const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); + const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; + + const allowedSortFields = new Set([ 'id', 'created_at', 'updated_at', 'waybill_code' ]); + const safeSortField = allowedSortFields.has(sortField) ? sortField : 'created_at'; + + return [[ safeSortField, sortOrder ]]; + } +} + +module.exports = ReturnWaybillService; diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js new file mode 100644 index 0000000..185f96a --- /dev/null +++ b/app/service/systems/setting/account.js @@ -0,0 +1,900 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +const RESERVED_EMPLOYEE_NAME = '测试工号保留'; + +class SettingAccountService extends Service { + getListWhereSpecialFieldMap() { + return { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作工号', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + normalizeAccountId(value, fieldName = 'account_id') { + const accountId = Number(value); + if (!Number.isFinite(accountId) || accountId <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return accountId; + } + + getWmsClient() { + return this.ctx.app.mysql.get('wms'); + } + + normalizePhone(phone) { + return typeof phone === 'string' ? phone.trim() : ''; + } + + isValidPhone(phone) { + return /^1[3-9]\d{9}$/.test(phone); + } + + normalizeName(name) { + return typeof name === 'string' ? name.trim() : ''; + } + + normalizeUsername(username) { + return typeof username === 'string' ? username.trim() : ''; + } + + generateUsername() { + const suffix = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; + return `acct_${suffix}`; + } + + async findRawAccountByPhone(phone) { + const rows = await this.getWmsClient().select('wms_account', { + where: { phone }, + columns: [ 'id', 'username', 'phone', 'email', 'real_name', 'status' ], + limit: 1, + }); + return rows && rows.length > 0 ? rows[0] : null; + } + + async findRawAccountByUsername(username) { + const rows = await this.getWmsClient().select('wms_account', { + where: { username }, + columns: [ 'id', 'username', 'phone', 'email', 'real_name', 'status' ], + limit: 1, + }); + return rows && rows.length > 0 ? rows[0] : null; + } + + async getAvatarMeta(employeeId) { + const { ctx } = this; + const avatarRef = await ctx.model.FileReference.findOne({ + where: { + business_type: 'avater', + business_id: String(employeeId), + }, + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ 'id', 'file_url', 'file_name' ], + required: false, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + + return { + avatar_file_id: Number(avatarRef && avatarRef.file_id ? avatarRef.file_id : 0) || null, + avatar_url: avatarRef && avatarRef.file ? avatarRef.file.file_url : '', + avatar_name: avatarRef && avatarRef.file ? avatarRef.file.file_name : '', + }; + } + + async resolveRoleId(data = {}) { + const { ctx } = this; + const explicitRoleId = Number(data.role_id || data.roleId || 0); + if (Number.isFinite(explicitRoleId) && explicitRoleId > 0) { + const role = await ctx.model.Role.findOne({ + where: { + id: explicitRoleId, + status: 1, + }, + }); + if (!role) { + throw this.createError('指定角色不存在或已禁用', 400); + } + return explicitRoleId; + } + + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + throw this.createError('未识别到当前操作人工号,无法继承角色', 400); + } + + const currentRole = await ctx.model.EmployeeRole.findOne({ + where: { employee_id: currentEmployeeId }, + order: [[ 'id', 'ASC' ]], + }); + if (!currentRole) { + throw this.createError('当前操作人工号未绑定角色,无法创建新工号', 400); + } + + return Number(currentRole.role_id); + } + + normalizeRoleIds(ids) { + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of ids) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + return Array.from(new Set(roleIds)); + } + + flattenRoleTreeMeta(roleNodes, idCollector = [], parentMap = new Map()) { + if (!Array.isArray(roleNodes) || roleNodes.length === 0) { + return { idCollector, parentMap }; + } + + for (const node of roleNodes) { + const roleId = Number(node && node.role_id); + if (Number.isFinite(roleId) && roleId > 0) { + idCollector.push(roleId); + parentMap.set(roleId, Number(node && node.pid ? node.pid : 0)); + } + + const children = Array.isArray(node && node.children) ? node.children : []; + this.flattenRoleTreeMeta(children, idCollector, parentMap); + } + + return { idCollector, parentMap }; + } + + async resolveAssignableRoleScope() { + const roleResult = await this.ctx.service.systems.setting.role.list({ + includeDisabled: false, + includeSystem: false, + }); + + const roleTree = roleResult && roleResult.data && Array.isArray(roleResult.data.roles) + ? roleResult.data.roles + : []; + const { idCollector, parentMap } = this.flattenRoleTreeMeta(roleTree, [], new Map()); + return { + roleIdSet: new Set(idCollector), + parentMap, + }; + } + + pruneDescendantRoleIds(roleIds, parentMap) { + const selected = new Set(roleIds); + const pruned = []; + + for (const roleId of roleIds) { + let current = roleId; + let keep = true; + const visited = new Set(); + let parentId = Number(parentMap.get(current) || 0); + + while (Number.isFinite(parentId) && parentId > 0) { + if (visited.has(parentId)) { + break; + } + visited.add(parentId); + + if (selected.has(parentId)) { + keep = false; + break; + } + + current = parentId; + parentId = Number(parentMap.get(current) || 0); + } + + if (keep) { + pruned.push(roleId); + } + } + + return Array.from(new Set(pruned)); + } + + async resolveRequestedRoleIds(data = {}, options = {}) { + const required = options.required === true; + const hasIds = Object.prototype.hasOwnProperty.call(data, 'ids'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'role_ids'); + + if (!hasIds && !hasRoleIds) { + if (required) { + throw this.createError('ids 参数不能为空', 400); + } + return null; + } + + const rawRoleIds = hasIds ? data.ids : data.role_ids; + const roleIds = this.normalizeRoleIds(rawRoleIds); + + const { roleIdSet, parentMap } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + throw this.createError('当前角色范围为空,无法分配角色', 400); + } + + const outOfScopeIds = roleIds.filter(roleId => !roleIdSet.has(roleId)); + if (outOfScopeIds.length > 0) { + throw this.createError(`包含超出当前角色范围的角色ID:${outOfScopeIds.join(',')}`, 400); + } + + return this.pruneDescendantRoleIds(roleIds, parentMap); + } + + async replaceEmployeeRoles(employeeId, roleIds) { + const { ctx } = this; + + await ctx.model.EmployeeRole.destroy({ + where: { + employee_id: employeeId, + }, + }); + + const rows = roleIds.map(roleId => ({ + employee_id: employeeId, + role_id: roleId, + })); + + await ctx.model.EmployeeRole.bulkCreate(rows); + } + + async buildEmployeeRoleGroupMap(employeeIds) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!Array.isArray(employeeIds) || employeeIds.length === 0) { + return new Map(); + } + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeIds, + }, + attributes: [ 'employee_id', 'role_id' ], + raw: true, + }); + + if (employeeRoleRows.length === 0) { + return new Map(); + } + + const roleIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0))); + + const roleRows = await ctx.model.Role.findAll({ + where: { + id: { + [Op.in]: roleIds, + }, + }, + attributes: [ 'id', 'role_code', 'role_name', 'pid', 'status' ], + raw: true, + }); + const roleMap = new Map(roleRows.map(role => [ Number(role.id), role ])); + + const employeeRoleMap = new Map(); + for (const row of employeeRoleRows) { + const employeeId = Number(row.employee_id); + const roleId = Number(row.role_id); + if (!Number.isFinite(employeeId) || employeeId <= 0 || !Number.isFinite(roleId) || roleId <= 0) { + continue; + } + + const role = roleMap.get(roleId); + if (!employeeRoleMap.has(employeeId)) { + employeeRoleMap.set(employeeId, { + role_ids: [], + roles: [], + }); + } + + const target = employeeRoleMap.get(employeeId); + target.role_ids.push(roleId); + target.roles.push({ + role_id: roleId, + role_code: role && role.role_code ? role.role_code : '', + role_name: role && role.role_name ? role.role_name : '', + pid: role ? Number(role.pid || 0) : 0, + status: role ? Number(role.status) : 0, + }); + } + + for (const value of employeeRoleMap.values()) { + value.role_ids = Array.from(new Set(value.role_ids)).sort((a, b) => a - b); + value.roles.sort((a, b) => a.role_id - b.role_id); + } + + return employeeRoleMap; + } + + async buildWechatBindingMap(accountIds) { + if (!Array.isArray(accountIds) || accountIds.length === 0) { + return new Map(); + } + + const normalizedAccountIds = Array.from(new Set(accountIds + .map(accountId => Number(accountId)) + .filter(accountId => Number.isFinite(accountId) && accountId > 0))); + if (normalizedAccountIds.length === 0) { + return new Map(); + } + + const ye4sClient = this.ctx.app.mysql.get('ye4s'); + const bindingRows = await ye4sClient.select('ye4s_user', { + where: { + wms_account_id: normalizedAccountIds, + }, + columns: [ 'id', 'wms_account_id' ], + orders: [[ 'id', 'DESC' ]], + }); + + const bindingMap = new Map(); + for (const row of bindingRows) { + const accountId = Number(row && row.wms_account_id); + const ye4sUserId = Number(row && row.id); + if (!Number.isFinite(accountId) || accountId <= 0 || !Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { + continue; + } + if (!bindingMap.has(accountId)) { + bindingMap.set(accountId, { + is_wechat_bound: true, + ye4s_user_id: ye4sUserId, + }); + } + } + + return bindingMap; + } + + async getOperableEmployeeByAccountId(accountId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const normalizedAccountId = this.normalizeAccountId(accountId, 'user_id'); + const where = { + account_id: normalizedAccountId, + store_id: storeId, + }; + + if (options.includeDisabled !== true) { + where.status = 1; + } + + const employees = await ctx.model.AccountStoreEmployee.findAll({ + where, + order: [[ 'status', 'DESC' ], [ 'id', 'ASC' ]], + }); + + if (employees.length === 0) { + throw this.createError('目标账号不存在或无权限操作', 404); + } + + const { roleIdSet } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + throw this.createError('当前角色范围为空,无法操作目标账号', 400); + } + + const employeeIds = employees + .map(item => Number(item.id)) + .filter(employeeId => Number.isFinite(employeeId) && employeeId > 0); + const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds); + + for (const employee of employees) { + const employeeId = Number(employee.id); + const roleGroup = employeeRoleMap.get(employeeId) || { + role_ids: [], + roles: [], + }; + const hasOutOfScopeRole = roleGroup.role_ids + .some(roleId => !roleIdSet.has(Number(roleId))); + if (!hasOutOfScopeRole) { + return { + employee, + roleGroup, + }; + } + } + + throw this.createError('目标账号超出当前操作范围', 403); + } + + async formatEmployeeRow(employee, options = {}) { + let account = options.account || null; + if (!account) { + account = await this.getWmsClient().get('wms_account', { + id: employee.account_id, + }); + } + const avatar = await this.getAvatarMeta(employee.id); + + return { + employee_id: Number(employee.id), + account_id: Number(employee.account_id), + store_id: Number(employee.store_id), + real_name: employee.real_name || '', + status: Number(employee.status), + created_at: employee.created_at, + updated_at: employee.updated_at, + username: account && account.username ? account.username : '', + phone: account && account.phone ? account.phone : '', + email: account && account.email ? account.email : '', + account_real_name: account && account.real_name ? account.real_name : '', + ...avatar, + }; + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const storeId = this.getCurrentStoreId(); + const currentEmployeeId = this.getCurrentEmployeeId(); + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + parsedResult = parsed.result; + } + + const andConditions = [ + { + store_id: storeId, + }, + ]; + const hasWhereStatus = Object.prototype.hasOwnProperty.call(normalizedWhere, 'status'); + if (!hasWhereStatus) { + const statusFilter = data.includeDisabled === true + ? undefined + : (data.status === 0 || data.status === '0' ? 0 : 1); + if (statusFilter === 0 || statusFilter === 1) { + andConditions.push({ status: statusFilter }); + } + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { real_name: { [Op.like]: `%${keyword}%` } }, + { '$account.username$': { [Op.like]: `%${keyword}%` } }, + { '$account.phone$': { [Op.like]: `%${keyword}%` } }, + { '$account.email$': { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + const employees = await ctx.model.AccountStoreEmployee.findAll({ + where: { + [Op.and]: andConditions, + }, + include: [ + { + model: ctx.model.Account, + as: 'account', + attributes: [ 'id', 'username', 'phone', 'email', 'real_name' ], + required: false, + }, + ], + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + const { roleIdSet } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + return { + code: 200, + data: [], + }; + } + + const employeeIds = employees + .map(employee => Number(employee.id)) + .filter(employeeId => Number.isFinite(employeeId) && employeeId > 0); + const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds); + const accountIds = employees + .map(employee => Number(employee.account_id)) + .filter(accountId => Number.isFinite(accountId) && accountId > 0); + const wechatBindingMap = await this.buildWechatBindingMap(accountIds); + + const list = []; + for (const employee of employees) { + const employeeId = Number(employee.id); + if (currentEmployeeId && employeeId === currentEmployeeId) { + continue; + } + + const roleGroup = employeeRoleMap.get(employeeId) || { + role_ids: [], + roles: [], + }; + + // 只展示当前账号可分配范围内的工号,避免越权操作。 + const hasOutOfScopeRole = roleGroup.role_ids + .some(roleId => !roleIdSet.has(Number(roleId))); + if (hasOutOfScopeRole) { + continue; + } + + const wechatBinding = wechatBindingMap.get(Number(employee.account_id)) || { + is_wechat_bound: false, + ye4s_user_id: null, + }; + + list.push({ + ...await this.formatEmployeeRow(employee, { + account: employee.account, + }), + is_wechat_bound: wechatBinding.is_wechat_bound, + ye4s_user_id: wechatBinding.ye4s_user_id, + role_ids: roleGroup.role_ids, + roles: roleGroup.roles, + }); + } + + return { + code: 200, + data: list, + }; + } + + async add(data = {}) { + const { ctx, service } = this; + let createdAccountId = 0; + + try { + const storeId = this.getCurrentStoreId(); + const phone = this.normalizePhone(data.phone); + const realName = this.normalizeName(data.real_name || data.realName); + const password = typeof data.password === 'string' && data.password.trim() + ? data.password.trim() + : '111111'; + + if (!phone) { + throw this.createError('phone 参数不能为空', 400); + } + if (!this.isValidPhone(phone)) { + throw this.createError('phone 格式不正确', 400); + } + if (!realName) { + throw this.createError('real_name 参数不能为空', 400); + } + if (realName === RESERVED_EMPLOYEE_NAME) { + throw this.createError(`新增工号禁止直接使用保留名称 ${RESERVED_EMPLOYEE_NAME}`, 400); + } + + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); + let account = await this.findRawAccountByPhone(phone); + + if (account && Number(account.status) !== 1) { + throw this.createError('该手机号对应账号已禁用,无法新增工号', 409); + } + + if (!account) { + let username = this.normalizeUsername(data.username); + if (!username) { + username = this.generateUsername(); + } + + const existingUsername = await this.findRawAccountByUsername(username); + if (existingUsername) { + throw this.createError('username 已存在', 409); + } + + const salt = service.systems.auth.user.generateSalt(); + const passwordHash = await service.systems.auth.user.encryptPassword(password, salt); + const email = typeof data.email === 'string' && data.email.trim() + ? data.email.trim() + : `${username}@autotest.local`; + + const insertRet = await this.getWmsClient().insert('wms_account', { + username, + phone, + email, + password_hash: passwordHash, + real_name: realName, + status: 1, + salt, + created_at: new Date(), + updated_at: new Date(), + }); + + createdAccountId = Number(insertRet && insertRet.insertId ? insertRet.insertId : 0); + account = await this.getWmsClient().get('wms_account', { id: createdAccountId }); + } + + const activeBinding = await ctx.model.AccountStoreEmployee.findOne({ + where: { + account_id: account.id, + store_id: storeId, + status: 1, + }, + }); + if (activeBinding) { + throw this.createError('该手机号已绑定当前主体工号', 409); + } + + const { employee } = await service.systems.store.ensureEmployeeRoleBinding({ + accountId: Number(account.id), + storeId, + roleId: roleIds[0], + realName, + }); + + await this.replaceEmployeeRoles(Number(employee.id), roleIds); + + await service.systems.auth.user.clearUserCache(Number(account.id)); + + const formatted = await this.formatEmployeeRow(employee); + return { + code: 200, + data: { + ...formatted, + role_id: roleIds[0], + role_ids: roleIds, + is_new_account: createdAccountId > 0, + }, + }; + } catch (error) { + if (createdAccountId > 0) { + await this.getWmsClient().delete('wms_account', { id: createdAccountId }); + } + throw error; + } + } + + async delete(data = {}) { + const { ctx, service } = this; + + const storeId = this.getCurrentStoreId(); + const currentEmployeeId = this.getCurrentEmployeeId(); + const employeeId = Number(data.employee_id || data.id || 0); + + if (!employeeId) { + throw this.createError('employee_id 参数不能为空', 400); + } + if (currentEmployeeId && employeeId === currentEmployeeId) { + throw this.createError('不允许删除当前登录工号', 400); + } + + const employee = await ctx.model.AccountStoreEmployee.findOne({ + where: { + id: employeeId, + store_id: storeId, + }, + }); + if (!employee) { + throw this.createError('工号不存在或无权限删除', 404); + } + + if (Number(employee.status) !== 1) { + return { + code: 200, + data: { + employee_id: employeeId, + account_id: Number(employee.account_id), + status: 'deleted', + already_deleted: true, + }, + }; + } + + await employee.update({ + status: 0, + updated_at: new Date(), + }); + + await ctx.model.AccountPlatformActive.destroy({ + where: { + employee_id: employeeId, + }, + }); + + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); + + return { + code: 200, + data: { + employee_id: employeeId, + account_id: Number(employee.account_id), + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const { ctx, service } = this; + + const storeId = this.getCurrentStoreId(); + const employeeId = Number(data.employee_id || data.id || 0); + const hasRealName = Object.prototype.hasOwnProperty.call(data, 'real_name') || Object.prototype.hasOwnProperty.call(data, 'realName'); + const hasFileId = Object.prototype.hasOwnProperty.call(data, 'file_id') || Object.prototype.hasOwnProperty.call(data, 'avatar_file_id') || Object.prototype.hasOwnProperty.call(data, 'fileId'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'ids') || Object.prototype.hasOwnProperty.call(data, 'role_ids'); + const realName = this.normalizeName(data.real_name || data.realName); + const fileId = Number(data.file_id || data.avatar_file_id || data.fileId || 0); + + if (!employeeId) { + throw this.createError('employee_id 参数不能为空', 400); + } + if (!hasRoleIds) { + throw this.createError('ids 参数不能为空', 400); + } + if (hasRealName && !realName) { + throw this.createError('real_name 参数不能为空', 400); + } + if (hasFileId && !fileId) { + throw this.createError('file_id 参数不能为空', 400); + } + + const employee = await ctx.model.AccountStoreEmployee.findOne({ + where: { + id: employeeId, + store_id: storeId, + status: 1, + }, + }); + if (!employee) { + throw this.createError('工号不存在或无权限更新', 404); + } + + if (hasRealName && realName !== employee.real_name) { + await employee.update({ + real_name: realName, + updated_at: new Date(), + }); + } + + if (hasFileId) { + const file = await ctx.model.File.findOne({ + where: { + id: fileId, + is_deleted: false, + }, + }); + if (!file) { + throw this.createError('头像文件不存在', 404); + } + + await service.systems.file.ReferenceFile({ + id: employeeId, + type: 'avater', + images: [ + { + file_id: fileId, + sort_order: 0, + }, + ], + }); + } + + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); + await this.replaceEmployeeRoles(employeeId, roleIds); + + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); + + const refreshed = await ctx.model.AccountStoreEmployee.findByPk(employeeId); + const roleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeId, + }, + attributes: [ 'role_id' ], + order: [[ 'role_id', 'ASC' ]], + raw: true, + }); + const boundRoleIds = roleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0); + + return { + code: 200, + data: { + ...await this.formatEmployeeRow(refreshed), + role_ids: Array.from(new Set(boundRoleIds)), + }, + }; + } + + async getBindWechatCode(data = {}) { + const { service } = this.ctx; + const accountId = data.user_id || data.account_id || data.id; + const { employee } = await this.getOperableEmployeeByAccountId(accountId); + const result = await service.systems.auth.user.getBindWechatCodeByAccountId(Number(employee.account_id), data, { + missingAccountMessage: '目标账号不存在,无法生成绑定码', + }); + + if (!result || Number(result.code) !== 200) { + throw this.createError(result && result.message ? result.message : '获取绑定码失败', Number(result && result.code) || 500); + } + + return result; + } + + async unbindWechat(data = {}) { + const { service } = this.ctx; + const accountId = data.user_id || data.account_id || data.id; + const { employee } = await this.getOperableEmployeeByAccountId(accountId); + const result = await service.systems.auth.user.unbindWechatByAccountId(Number(employee.account_id), { + missingAccountMessage: '目标账号不存在,无法解绑', + }); + + if (!result || Number(result.code) !== 200) { + throw this.createError(result && result.message ? result.message : '解绑失败', Number(result && result.code) || 500); + } + + return result; + } +} + +module.exports = SettingAccountService; diff --git a/app/service/systems/setting/express.js b/app/service/systems/setting/express.js new file mode 100644 index 0000000..aa4590f --- /dev/null +++ b/app/service/systems/setting/express.js @@ -0,0 +1,811 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class SettingExpressService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体ID。 + * + * @return {number} 当前仓库主体ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作快递映射', 400); + } + return storeId; + } + + /** + * 生成当前仓库快递列表缓存键。 + * + * @param {number|string} warehouseId 仓库主体ID + * @return {string} 缓存键 + */ + getExpressListCacheKey(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + return `express:list:${normalizedWarehouseId}`; + } + + return 'express:list'; + } + + /** + * 删除指定缓存键。 + * + * @param {string} cacheKey 缓存键 + * @return {Promise} + */ + async deleteCacheByKey(cacheKey) { + if (!cacheKey) { + return; + } + + const { app } = this; + if (app && typeof app.delCacheAsync === 'function') { + await app.delCacheAsync(cacheKey); + return; + } + + if (app && typeof app.setCacheAsync === 'function') { + await app.setCacheAsync(cacheKey, null, 0); + } + } + + /** + * 清理当前仓库快递列表缓存。 + * + * 优先通过 Redis keys 通配扫描删除所有 express:list* 变体, + * 若 Redis 不可用则降级为逐键删除已知命名键,确保核心缓存必清。 + * + * @param {number|string} warehouseId 仓库主体ID + * @return {Promise} + */ + async clearExpressListCache(warehouseId) { + const { app, ctx } = this; + + // 优先:Redis 通配扫描删除所有 express:list* 变体 + try { + const redisClient = app.redis && typeof app.redis.get === 'function' + ? app.redis.get('cache') + : null; + if (redisClient && typeof redisClient.keys === 'function') { + const matchedKeys = await redisClient.keys('express:list*'); + if (Array.isArray(matchedKeys) && matchedKeys.length > 0) { + await redisClient.del(...matchedKeys); + } + } + } catch (err) { + if (ctx && ctx.logger && typeof ctx.logger.warn === 'function') { + ctx.logger.warn( + '[clearExpressListCache] Redis keys 扫描失败,降级为已知键删除: %s', + err.message + ); + } + } + + // 降级:删除已知命名的缓存键 + const normalizedWarehouseId = Number(warehouseId || 0); + const knownKeys = [ + 'express:list', + 'express:list:system', + 'express:list:system:normal', + ]; + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + knownKeys.push(`express:list:${normalizedWarehouseId}`); + } + await Promise.all(knownKeys.map(k => this.deleteCacheByKey(k))); + } + + /** + * 规范化删除 ID 列表。 + * + * 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + normalizeDeleteIds(data = {}) { + const { + ids, + id, + setting_id: settingId, + settingId: camelSettingId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 规范化文本值。 + * + * @param {string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} [maxLength=255] 最大长度 + * @return {string} 规范化后的文本 + */ + normalizeText(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return ''; + } + + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + /** + * 规范化编码值。 + * + * @param {string} value 原始值 + * @param {string} [fieldName='code'] 字段名称 + * @param {number} [maxLength=50] 最大长度 + * @return {string} 规范化后的编码 + */ + normalizeCode(value, fieldName = 'code', maxLength = 50) { + return this.normalizeText(value, fieldName, maxLength).toUpperCase(); + } + + /** + * 规范化分页参数。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return Math.min(Math.floor(num), maxValue); + } + + /** + * 返回 where 字段映射。 + * + * @return {Object} where 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + code: { + field: 'code', + }, + name: { + field: 'name', + }, + express_code: { + field: 'express_code', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 获取系统快递列表。 + * + * @return {Promise} 系统快递列表 + */ + async getSystemExpressList() { + const systemExpressService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.express; + if (!systemExpressService || typeof systemExpressService.getSystemExpressList !== 'function') { + return []; + } + + return await systemExpressService.getSystemExpressList(); + } + + /** + * 构建系统快递映射表。 + * + * @return {Promise>} 系统快递映射表 + */ + async getSystemExpressMap() { + const expressList = await this.getSystemExpressList(); + const expressMap = new Map(); + + for (const expressItem of Array.isArray(expressList) ? expressList : []) { + if (!expressItem || typeof expressItem !== 'object') { + continue; + } + + const code = String(expressItem.code || expressItem.value || '').trim().toUpperCase(); + if (!code) { + continue; + } + + if (!expressMap.has(code)) { + expressMap.set(code, { + code, + name: String(expressItem.name || expressItem.label || '').trim(), + }); + } + } + + return expressMap; + } + + /** + * 规范化映射记录。 + * + * @param {Object} row 数据库记录 + * @param {Map} expressMap 系统快递映射表 + * @return {Object|null} 规范化后的记录 + */ + normalizeSettingRow(row, expressMap) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim().toUpperCase(); + if (!code) { + return null; + } + + const expressCode = String(row.express_code || '').trim().toUpperCase(); + const expressInfo = expressMap instanceof Map ? expressMap.get(expressCode) : null; + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + code, + name: String(row.name || '').trim(), + express_code: expressCode, + express_name: expressInfo ? expressInfo.name : '', + express_label: expressInfo ? expressInfo.name : '', + }; + } + + /** + * 查找当前仓库下的映射记录。 + * + * @param {number} id 映射ID + * @return {Promise} 映射记录 + */ + async findSettingById(id) { + const { ctx } = this; + const setting = await ctx.model.ExpressSetting.findOne({ + where: { + id, + warehouse_id: this.getCurrentStoreId(), + deleted_at: null, + }, + }); + + if (!setting) { + throw this.createError('快递映射不存在或无权限操作', 404); + } + + return setting; + } + + /** + * 查找同仓下的编码冲突记录。 + * + * @param {string} code 映射编码 + * @param {number|null} [excludeId=null] 排除的记录ID + * @return {Promise} 冲突记录 + */ + async findCodeConflict(code, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + code, + deleted_at: null, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.ExpressSetting.findOne({ + where, + attributes: [ 'id', 'code' ], + }); + } + + /** + * 校验系统快递编码是否存在。 + * + * @param {string} expressCode 系统快递编码 + * @param {Map} [expressMap] 系统快递映射表 + * @return {Promise} 系统快递信息 + */ + async ensureSystemExpressExists(expressCode, expressMap = null) { + const normalizedExpressCode = this.normalizeCode(expressCode, 'express_code'); + const resolvedMap = expressMap instanceof Map ? expressMap : await this.getSystemExpressMap(); + const expressInfo = resolvedMap.get(normalizedExpressCode); + + if (!expressInfo) { + throw this.createError('系统快递编码不存在', 400); + } + + return expressInfo; + } + + /** + * 校验同仓编码是否可用。 + * + * @param {string} code 映射编码 + * @param {number|null} [excludeId=null] 排除的记录ID + * @return {Promise} 是否可用 + */ + async ensureCodeAvailable(code, excludeId = null) { + const conflict = await this.findCodeConflict(code, excludeId); + if (conflict) { + throw this.createError('快递编码已被当前仓库使用', 409); + } + return true; + } + + /** + * 解析列表查询条件。 + * + * @param {Object} data 请求参数 + * @return {Object} 查询条件信息 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 查询映射列表。 + * + * @param {Object} data 请求参数 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 分页结果 + */ + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentStoreId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + const andConditions = [ + { + warehouse_id: currentStoreId, + }, + { + deleted_at: null, + }, + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { code: { [Op.like]: `%${keyword}%` } }, + { name: { [Op.like]: `%${keyword}%` } }, + { express_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + const [ expressMap, result ] = await Promise.all([ + this.getSystemExpressMap(), + ctx.model.ExpressSetting.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + attributes: [ 'id', 'warehouse_id', 'code', 'name', 'express_code' ], + order: [[ 'id', 'DESC' ]], + offset, + limit: pageSize, + raw: true, + }), + ]); + + const list = Array.isArray(result && result.rows) + ? result.rows.map(row => this.normalizeSettingRow(row, expressMap)).filter(Boolean) + : []; + + return { + code: 200, + data: { + list, + total: Number(result && result.count ? result.count : 0), + page, + page_size: pageSize, + }, + }; + } + + /** + * 查询系统快递编码和名称列表。 + * + * @return {Promise} 系统快递列表 + */ + async listBase() { + const list = await this.getSystemExpressList(); + return { + code: 200, + data: list, + }; + } + + /** + * 检查编码是否已被占用。 + * + * @param {Object} data 请求参数 + * @param {number} [data.id] 编辑时的映射ID + * @param {string} data.code 映射编码 + * @return {Promise} 唯一性校验结果 + */ + async checkCodeUnique(data = {}) { + const code = this.normalizeCode(data.code, 'code'); + if (!code) { + throw this.createError('code 参数不能为空', 400); + } + + const excludeId = Number(data.id || 0); + const conflict = await this.findCodeConflict(code, excludeId); + + return { + code: 200, + data: { + isUnique: !conflict, + message: conflict ? '快递编码已被当前仓库使用' : 'ok', + }, + }; + } + + /** + * 创建快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + const expressMap = await this.getSystemExpressMap(); + + const code = this.normalizeCode(data.code, 'code'); + const name = this.normalizeText(data.name, 'name', 50); + const expressCode = this.normalizeCode(data.express_code || data.expressCode, 'express_code'); + + if (!code) { + throw this.createError('code 参数不能为空', 400); + } + if (!name) { + throw this.createError('name 参数不能为空', 400); + } + if (!expressCode) { + throw this.createError('express_code 参数不能为空', 400); + } + + const expressInfo = await this.ensureSystemExpressExists(expressCode, expressMap); + await this.ensureCodeAvailable(code); + + const created = await ctx.model.ExpressSetting.create({ + warehouse_id: currentStoreId, + code, + name, + express_code: expressInfo.code, + }); + + await this.clearExpressListCache(currentStoreId); + + return { + code: 200, + data: this.normalizeSettingRow(created.get ? created.get({ plain: true }) : created, expressMap), + }; + } + + /** + * 修改快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const id = Number(data.id || data.setting_id || data.settingId || 0); + if (!Number.isFinite(id) || id <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + const setting = await this.findSettingById(id); + const hasCode = Object.prototype.hasOwnProperty.call(data, 'code'); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasExpressCode = Object.prototype.hasOwnProperty.call(data, 'express_code') + || Object.prototype.hasOwnProperty.call(data, 'expressCode'); + + if (!hasCode && !hasName && !hasExpressCode) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + let expressMap = null; + + if (hasCode) { + const code = this.normalizeCode(data.code, 'code'); + if (!code) { + throw this.createError('code 参数不能为空', 400); + } + await this.ensureCodeAvailable(code, id); + updates.code = code; + } + + if (hasName) { + const name = this.normalizeText(data.name, 'name', 50); + if (!name) { + throw this.createError('name 参数不能为空', 400); + } + updates.name = name; + } + + if (hasExpressCode) { + expressMap = await this.getSystemExpressMap(); + const expressCode = this.normalizeCode(data.express_code || data.expressCode, 'express_code'); + if (!expressCode) { + throw this.createError('express_code 参数不能为空', 400); + } + + const expressInfo = await this.ensureSystemExpressExists(expressCode, expressMap); + updates.express_code = expressInfo.code; + } + + await setting.update(updates); + + await this.clearExpressListCache(this.getCurrentStoreId()); + + if (!expressMap) { + expressMap = await this.getSystemExpressMap(); + } + + return { + code: 200, + data: this.normalizeSettingRow(setting.get ? setting.get({ plain: true }) : setting, expressMap), + }; + } + + /** + * 查询批量删除目标记录。 + * + * @param {Array} ids 删除ID列表 + * @return {Promise>} 目标记录列表 + */ + async findSettingsForDelete(ids) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + return await ctx.model.ExpressSetting.findAll({ + where: { + warehouse_id: this.getCurrentStoreId(), + id: { + [Op.in]: ids, + }, + }, + attributes: [ 'id', 'code', 'deleted_at' ], + raw: true, + }); + } + + /** + * 检查待删除快递编码是否被当前仓库快递接口引用。 + * + * @param {Array} codes 快递设置编码列表 + * @return {Promise} + */ + async ensureDeleteCodesNotReferenced(codes) { + const uniqueCodes = Array.from(new Set( + Array.isArray(codes) + ? codes.map(code => String(code || '').trim()).filter(Boolean) + : [] + )); + + if (uniqueCodes.length === 0) { + return; + } + + const { ctx, app } = this; + const { Op } = app.Sequelize; + const referencedRows = await ctx.model.ExpressInterface.findAll({ + where: { + warehouse_id: this.getCurrentStoreId(), + express_code: { + [Op.in]: uniqueCodes, + }, + }, + attributes: [ 'id', 'express_code' ], + raw: true, + }); + + if (Array.isArray(referencedRows) && referencedRows.length > 0) { + const referencedCodes = Array.from(new Set( + referencedRows + .map(row => String(row && row.express_code || '').trim()) + .filter(Boolean) + )); + + throw this.createError(`存在快递接口引用的快递编码,无法删除:${referencedCodes.join('、')}`, 409); + } + } + + /** + * 删除快递映射。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const ids = this.normalizeDeleteIds(data); + + if (ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const settings = await this.findSettingsForDelete(ids); + if (!Array.isArray(settings) || settings.length !== ids.length) { + throw this.createError('快递映射不存在或无权限操作', 404); + } + + const settingMap = new Map(); + for (const setting of settings) { + if (!setting || typeof setting !== 'object') { + continue; + } + + const settingId = Number(setting.id); + if (Number.isInteger(settingId) && settingId > 0) { + settingMap.set(settingId, setting); + } + } + + const deletedIds = []; + const alreadyDeletedIds = []; + const targetCodes = []; + + for (const id of ids) { + const setting = settingMap.get(id); + if (!setting) { + throw this.createError('快递映射不存在或无权限操作', 404); + } + + targetCodes.push(String(setting.code || '').trim()); + + if (setting.deleted_at) { + alreadyDeletedIds.push(id); + continue; + } + + deletedIds.push(id); + } + + await this.ensureDeleteCodesNotReferenced(targetCodes); + + if (deletedIds.length > 0) { + await ctx.model.transaction(async transaction => { + await ctx.model.ExpressSetting.update({ + deleted_at: new Date(), + }, { + where: { + warehouse_id: this.getCurrentStoreId(), + id: { + [Op.in]: deletedIds, + }, + deleted_at: null, + }, + transaction, + }); + }); + + await this.clearExpressListCache(this.getCurrentStoreId()); + } + + return { + code: 200, + data: { + ids, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } +} + +module.exports = SettingExpressService; diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js new file mode 100644 index 0000000..9fa73fc --- /dev/null +++ b/app/service/systems/setting/expressInterface.js @@ -0,0 +1,1679 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const { buildNotDeletedShopWhere } = require('../../../lib/shop_soft_delete'); + +const DEFAULT_CACHE_TTL_SECONDS = 600; + +class SettingExpressInterfaceService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体 ID。 + * + * @return {number} 当前仓库主体 ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作快递接口', 400); + } + return storeId; + } + + /** + * 生成仓库与平台维度的快递接口缓存键。 + * + * @param {number|string} warehouseId 仓库 ID + * @param {string} platformCode 平台代码 + * @return {string} 缓存键 + */ + getWarehousePlatformCacheKey(warehouseId, platformCode) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); + + return `express_interface:warehouse:${normalizedWarehouseId}:platform:${normalizedPlatformCode}`; + } + + /** + * 删除指定缓存键。 + * + * @param {string} cacheKey 缓存键 + * @return {Promise} + */ + async deleteCacheByKey(cacheKey) { + if (!cacheKey) { + return; + } + + const { app } = this; + if (app && typeof app.delCacheAsync === 'function') { + await app.delCacheAsync(cacheKey); + return; + } + + if (app && typeof app.setCacheAsync === 'function') { + await app.setCacheAsync(cacheKey, null, 0); + } + } + + /** + * 清理当前仓库与平台维度的快递接口缓存。 + * + * @param {number|string} warehouseId 仓库 ID + * @param {string} platformCode 平台代码 + * @return {Promise} + */ + async clearWarehousePlatformCache(warehouseId, platformCode) { + await this.deleteCacheByKey(this.getWarehousePlatformCacheKey(warehouseId, platformCode)); + } + + /** + * 规范化平台代码。 + * + * @param {string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} [maxLength=20] 最大长度 + * @return {string} 规范化后的平台代码 + */ + normalizePlatformCode(value, fieldName, maxLength = 20) { + const normalized = this.normalizeText(value, fieldName, maxLength).toUpperCase(); + if (!normalized) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + return normalized; + } + + /** + * 规范化文本值。 + * + * @param {string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} [maxLength=255] 最大长度 + * @return {string} 规范化后的文本 + */ + normalizeText(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return ''; + } + + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + + return normalized; + } + + /** + * 规范化可选文本值。 + * + * @param {string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} [maxLength=255] 最大长度 + * @return {string|null} 规范化后的文本 + */ + normalizeOptionalText(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return null; + } + + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + + return normalized; + } + + /** + * 规范化可选 JSON 值。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @return {*|null} 规范化后的 JSON 值 + */ + normalizeOptionalJson(value, fieldName) { + if (value === undefined || value === null || value === '') { + return null; + } + + if (typeof value === 'string') { + const normalized = value.trim(); + if (!normalized) { + return null; + } + + try { + return this.clonePlainValue(JSON.parse(normalized)); + } catch (error) { + throw this.createError(`${fieldName} 必须是合法 JSON`, 400); + } + } + + return this.clonePlainValue(value); + } + + /** + * 规范化整数值。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {Object} [options] 额外选项 + * @param {boolean} [options.allowEmpty=false] 是否允许空值 + * @param {number|null} [options.min=null] 最小值 + * @param {number|null} [options.max=null] 最大值 + * @return {number|null} 规范化后的整数 + */ + normalizeInteger(value, fieldName, options = {}) { + const { + allowEmpty = false, + min = null, + max = null, + } = options; + + if (value === undefined || value === null || value === '') { + if (allowEmpty) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const normalized = Number(value); + if (!Number.isInteger(normalized)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (min !== null && normalized < min) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (max !== null && normalized > max) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return normalized; + } + + /** + * 规范化布尔标记。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number|null} [defaultValue=null] 默认值 + * @return {number|null} 规范化后的标记 + */ + normalizeFlag(value, fieldName, defaultValue = null) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (normalized === 0 || normalized === 1) { + return normalized; + } + + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + /** + * 规范化分页参数。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return Math.min(Math.floor(normalized), maxValue); + } + + /** + * 获取列表查询字段映射。 + * + * @return {Object} 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + name: { + field: 'name', + }, + express_code: { + field: 'express_code', + }, + sys_express_code: { + field: 'sys_express_code', + }, + platform_code: { + field: 'platform_code', + }, + shop_id: { + field: 'shop_id', + }, + template_id: { + field: 'template_id', + }, + brandno: { + field: 'brandno', + }, + sender_name: { + field: 'sender_name', + }, + sender_tel: { + field: 'sender_tel', + }, + viewer: { + field: 'viewer', + }, + client_id: { + field: 'client_id', + }, + share_id: { + field: 'share_id', + }, + site_code: { + field: 'site_code', + }, + product_type: { + field: 'product_type', + }, + template_url: { + field: 'template_url', + }, + shop_name: { + field: 'shop_name', + }, + is_enabled: { + field: 'is_enabled', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 解析列表查询条件。 + * + * @param {Object} data 请求参数 + * @return {Object} 查询条件信息 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 获取快递接口联查配置。 + * + * @param {Object} [options={}] 查询选项 + * @return {Array} Sequelize 关联配置。 + */ + getInterfaceInclude(options = {}) { + const { ctx } = this; + const { full = false } = options; + + const includes = [{ + model: ctx.model.Express, + as: 'express', + required: false, + }]; + + if (!full) { + includes[0].attributes = [ 'code', 'name' ]; + } + + if (ctx.model && ctx.model.Shop) { + const shopInclude = { + model: ctx.model.Shop, + as: 'shop', + required: false, + }; + if (!full) { + shopInclude.attributes = [ 'id', 'shop_name' ]; + } + includes.push(shopInclude); + } + + return includes; + } + + /** + * 获取快递接口模型的全量字段。 + * + * @return {Array} 模型字段列表 + */ + getInterfaceFullAttributes() { + const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.ExpressInterface && this.ctx.model.ExpressInterface.rawAttributes; + + if (!rawAttributes || typeof rawAttributes !== 'object') { + return []; + } + + return Object.keys(rawAttributes); + } + + /** + * 校验模型字段是否存在。 + * + * @param {Object} model Sequelize 模型 + * @param {string} fieldName 字段名 + * @param {string} modelName 模型名称 + * @return {boolean} 字段是否存在 + */ + ensureModelFieldExists(model, fieldName, modelName) { + const rawAttributes = model && model.rawAttributes; + + if (!rawAttributes || !Object.prototype.hasOwnProperty.call(rawAttributes, fieldName)) { + throw this.createError(`${modelName}.${fieldName} 字段不存在,无法继续处理`, 500); + } + + return true; + } + + /** + * 根据店铺 ID 解析要同步的店铺与 token 信息。 + * + * @param {number|null} shopId 规范化后的店铺 ID + * @return {Promise} 同步后的店铺绑定信息 + */ + async resolveShopBinding(shopId) { + this.ensureModelFieldExists(this.ctx.model.Shop, 'access_token', 'Shop'); + this.ensureModelFieldExists(this.ctx.model.ExpressInterface, 'token', 'ExpressInterface'); + + if (shopId === null) { + return { + shopId: null, + token: null, + }; + } + + const currentStoreId = this.getCurrentStoreId(); + const shop = await this.ctx.model.Shop.findOne({ + where: { + id: shopId, + warehouse_id: currentStoreId, + ...buildNotDeletedShopWhere(this.app), + }, + attributes: [ 'id', 'warehouse_id', 'access_token' ], + }); + + if (!shop) { + throw this.createError('当前仓库下未找到对应店铺,无法同步快递接口 token', 404); + } + + const plainShop = shop && typeof shop.get === 'function' + ? shop.get({ plain: true }) + : shop; + const normalizedToken = this.normalizeOptionalText(plainShop.access_token, 'access_token', 255); + + return { + shopId: Number(plainShop.id), + token: normalizedToken || null, + }; + } + + /** + * 复制普通对象或数组,避免缓存对象被外部修改。 + * + * @param {*} value 待复制的值 + * @return {*} 复制后的值 + */ + clonePlainValue(value) { + if (Array.isArray(value)) { + return value.map(item => this.clonePlainValue(item)); + } + + if (value && typeof value === 'object') { + const cloned = {}; + for (const [ key, item ] of Object.entries(value)) { + cloned[key] = this.clonePlainValue(item); + } + return cloned; + } + + return value; + } + + /** + * 规范化系统快递记录。 + * + * @param {Object} row 数据库记录 + * @return {Object|null} 规范化后的系统快递信息 + */ + normalizeExpressRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + return { + code: this.normalizeOptionalText(row.code, 'express.code', 50), + name: this.normalizeOptionalText(row.name, 'express.name', 255), + polyapi_code: this.normalizeOptionalText(row.polyapi_code, 'express.polyapi_code', 255), + polyapi_extra_info: row.polyapi_extra_info === undefined ? null : row.polyapi_extra_info, + pdd_code: this.normalizeOptionalText(row.PDD !== undefined ? row.PDD : row.pdd_code, 'express.pdd_code', 255), + ks_code: this.normalizeOptionalText(row.KS !== undefined ? row.KS : row.ks_code, 'express.ks_code', 255), + dyxd_code: this.normalizeOptionalText(row.DY !== undefined ? row.DY : row.dyxd_code, 'express.dyxd_code', 255), + }; + } + + /** + * 判断列表项中的快递编码是否为系统快递编码。 + * + * @param {Object} row 快递接口记录 + * @param {Object|null} express 系统快递信息 + * @return {number} 是系统快递编码返回 1,否则返回 0 + */ + resolveIsSystemExpressCodeFlag(row, express) { + const expressCode = this.normalizeOptionalText(row && row.express_code, 'express_code', 255); + const systemExpressCode = this.normalizeOptionalText( + row && (row.sys_express_code !== undefined && row.sys_express_code !== null ? row.sys_express_code : (express && express.code)), + 'sys_express_code', + 50 + ); + + if (!expressCode || !systemExpressCode) { + return 0; + } + + return expressCode.toUpperCase() === systemExpressCode.toUpperCase() ? 1 : 0; + } + + /** + * 获取平台自建快递编码字段名。 + * + * @param {string} platformCode 平台编码 + * @return {string|null} 平台字段名 + */ + getPlatformExpressColumn(platformCode) { + const normalizedPlatformCode = this.normalizePlatformCode(platformCode, 'platform_code', 20); + const fieldMap = { + KS: 'KS', + KSAPP: 'KS', + PDD: 'PDD', + DYXD: 'DY', + DY: 'DY', + DOUYIN: 'DY', + }; + + return fieldMap[normalizedPlatformCode] || null; + } + + /** + * 校验系统快递编码是否存在。 + * + * @param {string} sysExpressCode 系统快递编码 + * @return {Promise} 系统快递编码 + */ + async ensureSystemExpressCodeExists(sysExpressCode) { + const normalizedSysExpressCode = this.normalizeText(sysExpressCode, 'sys_express_code', 50).toUpperCase(); + const express = await this.ctx.model.Express.findOne({ + where: { + code: normalizedSysExpressCode, + }, + attributes: [ 'code' ], + }); + + if (!express) { + throw this.createError('sys_express_code 未匹配到系统快递编码', 400); + } + + return normalizedSysExpressCode; + } + + /** + * 校验打印平台编码是否存在。 + * + * 当运行环境尚未注册 `PrintPlatform` 模型时跳过校验,保持旧测试桩兼容; + * 已注册模型时统一校验 `wms_print_platform.platform_code`。 + * + * @param {string} platformCode 打印平台编码。 + * @return {Promise} 规范化后的打印平台编码。 + */ + async ensurePrintPlatformExists(platformCode) { + const normalizedPlatformCode = this.normalizePlatformCode(platformCode, 'platform_code', 20); + const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; + + if (!printPlatformModel || typeof printPlatformModel.findOne !== 'function') { + return normalizedPlatformCode; + } + + const printPlatform = await printPlatformModel.findOne({ + where: { + platform_code: normalizedPlatformCode, + }, + attributes: [ 'platform_code' ], + }); + + if (!printPlatform) { + throw this.createError('platform_code 未匹配到打印平台编码', 400); + } + + return normalizedPlatformCode; + } + + /** + * 规范化打印平台记录。 + * + * 返回结构尽量与现有平台/下拉列表风格保持一致。 + * + * @param {Object} row 打印平台记录。 + * @return {Object|null} 规范化后的打印平台数据。 + */ + normalizePrintPlatformRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const platformCode = this.normalizeOptionalText(row.platform_code, 'platform_code', 20); + if (!platformCode) { + return null; + } + + const platformName = this.normalizeOptionalText(row.platform_name, 'platform_name', 100); + const platid = row.platid === undefined || row.platid === null || row.platid === '' + ? null + : String(row.platid); + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + code: platformCode, + name: platformName || platformCode, + value: platformCode, + label: platformName || platformCode, + platform_code: platformCode, + platform_name: platformName, + platid, + status: this.normalizeOptionalText(row.status, 'status', 20) || 'ACTIVE', + remark: this.normalizeOptionalText(row.remark, 'remark', 255), + need_callback_url: this.normalizeOptionalText(row.need_callback_url, 'need_callback_url', 500), + }; + } + + /** + * 获取打印平台全量列表。 + * + * 仅返回未删除且状态为启用的打印平台,供快递接口配置页下拉选择使用。 + * + * @return {Promise>} 打印平台列表。 + */ + async getPrintPlatformList() { + const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; + + if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function') { + return []; + } + + const rows = await printPlatformModel.findAll({ + attributes: [ 'id', 'platform_code', 'platform_name', 'platid', 'status', 'remark', 'need_callback_url' ], + where: { + deleted: 0, + status: 'ACTIVE', + }, + order: [[ 'platform_name', 'ASC' ], [ 'id', 'ASC' ]], + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows + .map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row)) + .map(row => this.normalizePrintPlatformRow(row)) + .filter(Boolean); + } + + /** + * 根据外部快递编码解析系统快递编码。 + * + * @param {Object} data 输入参数 + * @param {string} data.expressCode 外部快递编码 + * @param {string} data.platformCode 平台编码 + * @param {string} [data.sysExpressCode] 显式系统快递编码 + * @return {Promise} 系统快递编码 + */ + async resolveSysExpressCode(data = {}) { + const expressCode = this.normalizeText(data.expressCode, 'express_code', 255).toUpperCase(); + const platformCode = this.normalizePlatformCode(data.platformCode, 'platform_code', 20); + const inputSysExpressCode = data.sysExpressCode; + + if (inputSysExpressCode !== undefined && inputSysExpressCode !== null && String(inputSysExpressCode).trim() !== '') { + return await this.ensureSystemExpressCodeExists(inputSysExpressCode); + } + + const matchedBySystemCode = await this.ctx.model.Express.findOne({ + where: { + code: expressCode, + }, + attributes: [ 'code' ], + }); + if (matchedBySystemCode) { + return this.normalizeText(matchedBySystemCode.code, 'sys_express_code', 50).toUpperCase(); + } + + const platformColumn = this.getPlatformExpressColumn(platformCode); + if (platformColumn) { + const matchedByPlatformCode = await this.ctx.model.Express.findOne({ + where: { + [platformColumn]: expressCode, + }, + attributes: [ 'code' ], + }); + if (matchedByPlatformCode) { + return this.normalizeText(matchedByPlatformCode.code, 'sys_express_code', 50).toUpperCase(); + } + } + + throw this.createError('express_code 未匹配到系统快递编码', 400); + } + + /** + * 规范化快递接口记录。 + * + * @param {Object} row 数据库记录 + * @param {Object} [options={}] 规范化选项 + * @return {Object|null} 规范化后的记录 + */ + normalizeInterfaceRow(row, options = {}) { + if (!row || typeof row !== 'object') { + return null; + } + + const { includeSystemExpressFlag = false } = options; + + const express = this.normalizeExpressRow(row.express && typeof row.express === 'object' ? row.express : null); + + const normalizedRow = { + id: row.id === undefined || row.id === null ? null : Number(row.id), + name: this.normalizeOptionalText(row.name, 'name', 255), + express_code: this.normalizeOptionalText(row.express_code, 'express_code', 255), + sys_express_code: this.normalizeOptionalText(row.sys_express_code, 'sys_express_code', 50), + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + shop_id: row.shop_id === undefined || row.shop_id === null ? null : Number(row.shop_id), + platform_shop_id: row.platform_shop_id === undefined || row.platform_shop_id === null ? null : Number(row.platform_shop_id), + template_id: this.normalizeOptionalText(row.template_id, 'template_id', 50), + paymode: row.paymode === undefined || row.paymode === null ? null : Number(row.paymode), + brandno: this.normalizeOptionalText(row.brandno, 'brandno', 255), + providertype: this.normalizeOptionalText(row.providertype, 'providertype', 50), + providerid: row.providerid === undefined || row.providerid === null ? null : Number(row.providerid), + platform_code: this.normalizeOptionalText(row.platform_code, 'platform_code', 20), + sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50), + sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11), + weight: row.weight === undefined || row.weight === null ? null : Number(row.weight), + weight_type: row.weight_type === undefined || row.weight_type === null ? null : Number(row.weight_type), + viewer: this.normalizeOptionalText(row.viewer, 'viewer', 50), + client_id: this.normalizeOptionalText(row.client_id, 'client_id', 50), + is_enabled: row.is_enabled === undefined || row.is_enabled === null ? null : Number(row.is_enabled), + is_share: row.is_share === undefined || row.is_share === null ? null : Number(row.is_share), + ispickup: row.ispickup === undefined || row.ispickup === null ? null : Number(row.ispickup), + shipperno: this.normalizeOptionalText(row.shipperno, 'shipperno', 255), + template_url: this.normalizeOptionalText(row.template_url, 'template_url', 500), + ext_data: this.clonePlainValue(row.ext_data === undefined ? null : row.ext_data), + province_name: this.normalizeOptionalText(row.province_name, 'province_name', 255), + city_name: this.normalizeOptionalText(row.city_name, 'city_name', 255), + district_name: this.normalizeOptionalText(row.district_name, 'district_name', 255), + address: this.normalizeOptionalText(row.address, 'address', 255), + town_name: this.normalizeOptionalText(row.town_name, 'town_name', 255), + site_code: this.normalizeOptionalText(row.site_code, 'site_code', 255), + product_type: this.normalizeOptionalText(row.product_type, 'product_type', 50), + shop_name: this.normalizeOptionalText( + (row.shop && row.shop.shop_name) || row.shop_name, + 'shop_name', + 255 + ), + express, + express_name: express ? express.name : null, + express_polyapi_extra_info: express ? express.polyapi_extra_info : null, + express_pdd_code: express ? express.pdd_code : null, + }; + + if (includeSystemExpressFlag) { + normalizedRow.is_system_express_code = this.resolveIsSystemExpressCodeFlag(row, express); + } + + return normalizedRow; + } + + /** + * 规范化快递接口的全量记录。 + * + * @param {Object} row 数据库记录 + * @return {Object|null} 规范化后的全量记录 + */ + normalizeFullInterfaceRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const attributes = this.getInterfaceFullAttributes(); + const normalized = {}; + const keys = attributes.length > 0 ? attributes : Object.keys(row); + + for (const key of keys) { + if (Object.prototype.hasOwnProperty.call(row, key)) { + normalized[key] = this.clonePlainValue(row[key]); + } + } + + if (Object.prototype.hasOwnProperty.call(row, 'express')) { + normalized.express = this.clonePlainValue(row.express); + } + + if (Object.prototype.hasOwnProperty.call(row, 'shop')) { + normalized.shop = this.clonePlainValue(row.shop); + } + + return normalized; + } + + /** + * 判断缓存中的仓库平台快递接口数据是否包含店铺联查字段。 + * + * @param {Array} rows 快递接口列表 + * @return {boolean} 是否可直接使用缓存 + */ + hasWarehousePlatformShopData(rows) { + if (!Array.isArray(rows) || rows.length === 0) { + return true; + } + + return rows.every(row => { + if (!row || typeof row !== 'object') { + return false; + } + + if (!Object.prototype.hasOwnProperty.call(row, 'shop_id')) { + return true; + } + + const shopId = row.shop_id; + if (shopId === null || shopId === undefined) { + return true; + } + + return Object.prototype.hasOwnProperty.call(row, 'shop'); + }); + } + + /** + * 规范化快递接口的全量记录数组,并按 weight / id 排序。 + * + * @param {Array|Object} rows 数据库记录数组或单条记录 + * @return {Array} 规范化后的全量记录数组 + */ + normalizeFullInterfaceRows(rows) { + const sourceRows = Array.isArray(rows) + ? rows + : rows ? [ rows ] : []; + + return sourceRows + .map(row => this.normalizeFullInterfaceRow(row)) + .filter(row => row) + .sort((left, right) => { + const leftWeight = left.weight === undefined || left.weight === null + ? Number.POSITIVE_INFINITY + : Number(left.weight); + const rightWeight = right.weight === undefined || right.weight === null + ? Number.POSITIVE_INFINITY + : Number(right.weight); + + if (leftWeight !== rightWeight) { + return leftWeight - rightWeight; + } + + const leftId = left.id === undefined || left.id === null + ? Number.POSITIVE_INFINITY + : Number(left.id); + const rightId = right.id === undefined || right.id === null + ? Number.POSITIVE_INFINITY + : Number(right.id); + + return leftId - rightId; + }); + } + + /** + * 解析仓库与平台代码查询条件。 + * + * @param {Object} data 请求参数 + * @return {Object} 归一化后的仓库与平台信息 + */ + resolveWarehousePlatformTarget(data = {}) { + const warehouseValue = data.warehouse_id !== undefined + ? data.warehouse_id + : data.warehouseId; + const platformValue = data.platform_code !== undefined + ? data.platform_code + : data.platformCode; + + const warehouseId = warehouseValue === undefined + ? this.getCurrentStoreId() + : this.normalizeInteger(warehouseValue, 'warehouse_id', { min: 1 }); + const platformCode = this.normalizePlatformCode(platformValue, 'platform_code', 20); + + return { + warehouseId, + platformCode, + }; + } + + /** + * 查找当前仓库下的快递接口记录。 + * + * @param {number} id 接口 ID + * @return {Promise} 接口记录 + */ + async findInterfaceById(id) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + + const setting = await ctx.model.ExpressInterface.findOne({ + where: { + id, + warehouse_id: currentStoreId, + }, + include: this.getInterfaceInclude(), + }); + + if (!setting) { + throw this.createError('快递接口不存在或无权限操作', 404); + } + + return setting; + } + + /** + * 查找同仓下的快递编码冲突记录。 + * + * @param {string} expressCode 快递编码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 冲突记录 + */ + async findCodeConflict(expressCode, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + express_code: expressCode, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.ExpressInterface.findOne({ + where, + attributes: [ 'id', 'express_code' ], + include: this.getInterfaceInclude(), + }); + } + + /** + * 查找同仓下的平台接口冲突记录。 + * + * @param {string} platformCode 平台代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 冲突记录 + */ + async findInterfaceConflict(platformCode, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + platform_code: platformCode, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.ExpressInterface.findOne({ + where, + attributes: [ 'id', 'platform_code' ], + include: this.getInterfaceInclude(), + }); + } + + /** + * 校验快递编码是否可用。 + * + * @param {string} expressCode 快递编码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 是否可用 + */ + async ensureCodeAvailable(expressCode, excludeId = null) { + const conflict = await this.findCodeConflict(expressCode, excludeId); + if (conflict) { + throw this.createError('快递编码已被当前仓库使用', 409); + } + return true; + } + + /** + * 校验平台接口组合是否可用。 + * + * @param {string} platformCode 平台代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 是否可用 + */ + async ensureInterfaceAvailable(platformCode, excludeId = null) { + const conflict = await this.findInterfaceConflict(platformCode, excludeId); + if (conflict) { + throw this.createError('当前平台和快递接口组合已被使用', 409); + } + return true; + } + + /** + * 获取快递接口列表。 + * + * @param {Object} data 请求参数 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 分页结果 + */ + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentStoreId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + const andConditions = [ + { + warehouse_id: currentStoreId, + }, + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { name: { [Op.like]: `%${keyword}%` } }, + { express_code: { [Op.like]: `%${keyword}%` } }, + { platform_code: { [Op.like]: `%${keyword}%` } }, + { sender_name: { [Op.like]: `%${keyword}%` } }, + { sender_tel: { [Op.like]: `%${keyword}%` } }, + { viewer: { [Op.like]: `%${keyword}%` } }, + { client_id: { [Op.like]: `%${keyword}%` } }, + { province_name: { [Op.like]: `%${keyword}%` } }, + { city_name: { [Op.like]: `%${keyword}%` } }, + { district_name: { [Op.like]: `%${keyword}%` } }, + { site_code: { [Op.like]: `%${keyword}%` } }, + { product_type: { [Op.like]: `%${keyword}%` } }, + { brandno: { [Op.like]: `%${keyword}%` } }, + { shop_name: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + const result = await ctx.model.ExpressInterface.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + include: this.getInterfaceInclude(), + attributes: [ + 'id', 'name', 'express_code', 'warehouse_id', 'shop_id', 'platform_shop_id', 'template_id', 'paymode', 'brandno', 'providertype', 'providerid', 'platform_code', + 'sys_express_code', + 'sender_name', 'sender_tel', 'weight', 'viewer', 'client_id', 'is_share', + 'province_name', 'city_name', 'district_name', 'site_code', + 'product_type', 'weight_type', 'shop_name', 'address', 'town_name', 'ispickup', 'shipperno', 'template_url', 'ext_data', 'is_enabled', + ], + order: [[ 'weight', 'ASC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + + const list = Array.isArray(result && result.rows) + ? result.rows.map(row => this.normalizeInterfaceRow( + row && typeof row.get === 'function' ? row.get({ plain: true }) : row, + { includeSystemExpressFlag: true } + )).filter(Boolean) + : []; + + return { + code: 200, + data: { + list, + total: Number(result && result.count ? result.count : 0), + page, + page_size: pageSize, + }, + }; + } + + /** + * 按仓库和平台代码查询快递接口全量记录。 + * + * 该方法会先尝试读取缓存;缓存未命中时查库并回写缓存。 + * + * @param {Object} data 请求参数 + * @return {Promise} 查询结果,data 为快递接口数组 + */ + async listByWarehousePlatformCode(data = {}) { + const { ctx, app } = this; + const { warehouseId, platformCode } = this.resolveWarehousePlatformTarget(data); + const cacheKey = this.getWarehousePlatformCacheKey(warehouseId, platformCode); + + if (app && typeof app.getCacheAsync === 'function') { + try { + const cachedValue = await app.getCacheAsync(cacheKey); + if (cachedValue !== null && cachedValue !== undefined) { + const normalizedCached = this.normalizeFullInterfaceRows(cachedValue); + if (this.hasWarehousePlatformShopData(normalizedCached)) { + return { + code: 200, + data: normalizedCached, + }; + } + } + } catch (error) { + if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') { + this.ctx.logger.warn('[SettingExpressInterfaceService.listByWarehousePlatformCode] 读取缓存失败', { + error: error.message, + cacheKey, + }); + } + } + } + console.log('查询入参', warehouseId, platformCode); + const settings = await ctx.model.ExpressInterface.findAll({ + where: { + warehouse_id: warehouseId, + platform_code: platformCode, + }, + include: this.getInterfaceInclude({ full: true }), + attributes: this.getInterfaceFullAttributes(), + order: [[ 'weight', 'ASC' ], [ 'id', 'ASC' ]], + }); + + const plainSettings = Array.isArray(settings) + ? settings.map(setting => (setting && typeof setting.get === 'function' + ? setting.get({ plain: true }) + : setting)) + : []; + const normalized = this.normalizeFullInterfaceRows(plainSettings); + + if (normalized && app && typeof app.setCacheAsync === 'function') { + try { + await app.setCacheAsync(cacheKey, normalized, DEFAULT_CACHE_TTL_SECONDS); + } catch (error) { + if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') { + this.ctx.logger.warn('[SettingExpressInterfaceService.listByWarehousePlatformCode] 写入缓存失败', { + error: error.message, + cacheKey, + }); + } + } + } + + return { + code: 200, + data: normalized, + }; + } + + /** + * 创建快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + + const name = this.normalizeText(data.name, 'name', 255); + const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase(); + const platformCode = await this.ensurePrintPlatformExists( + data.platform_code !== undefined ? data.platform_code : data.platformCode + ); + + + if (!name) { + throw this.createError('name 参数不能为空', 400); + } + if (!expressCode) { + throw this.createError('express_code 参数不能为空', 400); + } + if (!platformCode) { + throw this.createError('platform_code 参数不能为空', 400); + } + + const sysExpressCode = await this.resolveSysExpressCode({ + expressCode, + platformCode, + sysExpressCode: data.sys_express_code !== undefined ? data.sys_express_code : data.sysExpressCode, + }); + + const payload = { + warehouse_id: currentStoreId, + name, + express_code: expressCode, + platform_code: platformCode, + sys_express_code: sysExpressCode, + shop_id: this.normalizeInteger(data.shop_id !== undefined ? data.shop_id : data.shopId, 'shop_id', { + allowEmpty: true, + min: 1, + }), + template_id: (() => { + const normalizedTemplateId = this.normalizeOptionalText( + data.template_id !== undefined ? data.template_id : data.templateId, + 'template_id', + 50 + ); + return normalizedTemplateId === '' ? null : normalizedTemplateId; + })(), + paymode: this.normalizeInteger(data.paymode !== undefined ? data.paymode : data.payMode, 'paymode', { + allowEmpty: true, + }), + brandno: (() => { + const normalizedBrandNo = this.normalizeOptionalText( + data.brandno !== undefined ? data.brandno : data.brandNo, + 'brandno', + 255 + ); + return normalizedBrandNo === '' ? null : normalizedBrandNo; + })(), + providertype: (() => { + const normalizedProviderType = this.normalizeOptionalText( + data.providertype !== undefined ? data.providertype : data.providerType, + 'providertype', + 50 + ); + return normalizedProviderType === '' ? null : normalizedProviderType; + })(), + providerid: this.normalizeInteger(data.providerid !== undefined ? data.providerid : data.providerId, 'providerid', { + allowEmpty: true, + }), + sender_name: this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50), + sender_tel: this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11), + weight: this.normalizeInteger(data.weight, 'weight', { + allowEmpty: true, + }), + weight_type: this.normalizeInteger(data.weight_type !== undefined ? data.weight_type : data.weightType, 'weight_type', { + allowEmpty: true, + }), + viewer: this.normalizeOptionalText(data.viewer, 'viewer', 50), + client_id: this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50), + ispickup: this.normalizeFlag(data.ispickup !== undefined ? data.ispickup : data.isPickup, 'ispickup', 0), + shipperno: this.normalizeOptionalText(data.shipperno !== undefined ? data.shipperno : data.shipperNo, 'shipperno', 255), + template_url: this.normalizeOptionalText(data.template_url !== undefined ? data.template_url : data.templateUrl, 'template_url', 500), + ext_data: this.normalizeOptionalJson(data.ext_data !== undefined ? data.ext_data : data.extData, 'ext_data'), + province_name: this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255), + city_name: this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255), + district_name: this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255), + address: this.normalizeOptionalText(data.address, 'address', 255), + town_name: this.normalizeOptionalText(data.town_name || data.townName, 'town_name', 255), + site_code: this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255), + product_type: this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50), + shop_name: this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255), + }; + + const created = await ctx.model.ExpressInterface.create(payload); + const plainCreatedRow = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + const createdSetting = await this.findInterfaceById(Number(plainCreatedRow && plainCreatedRow.id)); + const plainCreated = createdSetting && typeof createdSetting.get === 'function' + ? createdSetting.get({ plain: true }) + : createdSetting; + + await this.clearWarehousePlatformCache(currentStoreId, payload.platform_code); + + return { + code: 200, + data: this.normalizeInterfaceRow(plainCreated), + }; + } + + /** + * 修改快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const id = Number(data.id || data.interface_id || data.interfaceId || 0); + if (!Number.isInteger(id) || id <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + const setting = await this.findInterfaceById(id); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasExpressCode = Object.prototype.hasOwnProperty.call(data, 'express_code') + || Object.prototype.hasOwnProperty.call(data, 'expressCode'); + const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code') + || Object.prototype.hasOwnProperty.call(data, 'platformCode'); + const hasSysExpressCode = Object.prototype.hasOwnProperty.call(data, 'sys_express_code') + || Object.prototype.hasOwnProperty.call(data, 'sysExpressCode'); + const hasSenderName = Object.prototype.hasOwnProperty.call(data, 'sender_name') + || Object.prototype.hasOwnProperty.call(data, 'senderName'); + const hasSenderTel = Object.prototype.hasOwnProperty.call(data, 'sender_tel') + || Object.prototype.hasOwnProperty.call(data, 'senderTel'); + const hasWeight = Object.prototype.hasOwnProperty.call(data, 'weight'); + const hasWeightType = Object.prototype.hasOwnProperty.call(data, 'weight_type') + || Object.prototype.hasOwnProperty.call(data, 'weightType'); + const hasShopId = Object.prototype.hasOwnProperty.call(data, 'shop_id') + || Object.prototype.hasOwnProperty.call(data, 'shopId'); + const hasPlatformShopId = Object.prototype.hasOwnProperty.call(data, 'platform_shop_id') + || Object.prototype.hasOwnProperty.call(data, 'platformShopId'); + const hasTemplateId = Object.prototype.hasOwnProperty.call(data, 'template_id') + || Object.prototype.hasOwnProperty.call(data, 'templateId'); + const hasPaymode = Object.prototype.hasOwnProperty.call(data, 'paymode') + || Object.prototype.hasOwnProperty.call(data, 'payMode'); + const hasBrandNo = Object.prototype.hasOwnProperty.call(data, 'brandno') + || Object.prototype.hasOwnProperty.call(data, 'brandNo'); + const hasProviderType = Object.prototype.hasOwnProperty.call(data, 'providertype') + || Object.prototype.hasOwnProperty.call(data, 'providerType'); + const hasProviderId = Object.prototype.hasOwnProperty.call(data, 'providerid') + || Object.prototype.hasOwnProperty.call(data, 'providerId'); + const hasViewer = Object.prototype.hasOwnProperty.call(data, 'viewer'); + const hasClientId = Object.prototype.hasOwnProperty.call(data, 'client_id') + || Object.prototype.hasOwnProperty.call(data, 'clientId'); + const hasIsPickup = Object.prototype.hasOwnProperty.call(data, 'ispickup') + || Object.prototype.hasOwnProperty.call(data, 'isPickup'); + const hasShipperNo = Object.prototype.hasOwnProperty.call(data, 'shipperno') + || Object.prototype.hasOwnProperty.call(data, 'shipperNo'); + const hasTemplateUrl = Object.prototype.hasOwnProperty.call(data, 'template_url') + || Object.prototype.hasOwnProperty.call(data, 'templateUrl'); + const hasProvinceName = Object.prototype.hasOwnProperty.call(data, 'province_name') + || Object.prototype.hasOwnProperty.call(data, 'provinceName'); + const hasCityName = Object.prototype.hasOwnProperty.call(data, 'city_name') + || Object.prototype.hasOwnProperty.call(data, 'cityName'); + const hasDistrictName = Object.prototype.hasOwnProperty.call(data, 'district_name') + || Object.prototype.hasOwnProperty.call(data, 'districtName'); + const hasAddress = Object.prototype.hasOwnProperty.call(data, 'address'); + const hasTownName = Object.prototype.hasOwnProperty.call(data, 'town_name') + || Object.prototype.hasOwnProperty.call(data, 'townName'); + const hasSiteCode = Object.prototype.hasOwnProperty.call(data, 'site_code') + || Object.prototype.hasOwnProperty.call(data, 'siteCode'); + const hasProductType = Object.prototype.hasOwnProperty.call(data, 'product_type') + || Object.prototype.hasOwnProperty.call(data, 'productType'); + const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name') + || Object.prototype.hasOwnProperty.call(data, 'shopName'); + const hasExtData = Object.prototype.hasOwnProperty.call(data, 'ext_data') + || Object.prototype.hasOwnProperty.call(data, 'extData'); + const hasIsEnabled = Object.prototype.hasOwnProperty.call(data, 'is_enabled') + || Object.prototype.hasOwnProperty.call(data, 'isEnabled'); + + if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSysExpressCode + && !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType + && !hasShopId && !hasPlatformShopId && !hasTemplateId && !hasPaymode && !hasBrandNo + && !hasProviderType && !hasProviderId && !hasViewer && !hasClientId && !hasIsPickup + && !hasShipperNo && !hasTemplateUrl && !hasProvinceName && !hasCityName + && !hasDistrictName && !hasAddress && !hasTownName && !hasSiteCode + && !hasProductType && !hasShopName && !hasExtData && !hasIsEnabled) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + let nextExpressCode = setting.express_code || ''; + let nextPlatformCode = setting.platform_code || ''; + + if (hasName) { + const name = this.normalizeText(data.name, 'name', 255); + if (!name) { + throw this.createError('name 参数不能为空', 400); + } + updates.name = name; + } + + if (hasExpressCode) { + const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase(); + if (!expressCode) { + throw this.createError('express_code 参数不能为空', 400); + } + nextExpressCode = expressCode; + updates.express_code = expressCode; + } + + if (hasPlatformCode) { + const platformCode = this.normalizePlatformCode( + data.platform_code !== undefined ? data.platform_code : data.platformCode, + 'platform_code', + 20 + ); + if (!platformCode) { + throw this.createError('platform_code 参数不能为空', 400); + } + nextPlatformCode = platformCode; + updates.platform_code = platformCode; + } + + nextPlatformCode = await this.ensurePrintPlatformExists(nextPlatformCode); + + if (Object.prototype.hasOwnProperty.call(updates, 'platform_code')) { + updates.platform_code = nextPlatformCode; + } + + if (hasSenderName) { + updates.sender_name = this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50); + } + + if (hasSenderTel) { + updates.sender_tel = this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11); + } + + if (hasWeight) { + updates.weight = this.normalizeInteger(data.weight, 'weight', { + allowEmpty: true, + }); + } + + if (hasWeightType) { + updates.weight_type = this.normalizeInteger(data.weight_type !== undefined ? data.weight_type : data.weightType, 'weight_type', { + allowEmpty: true, + }); + } + + if (hasShopId) { + const normalizedShopId = this.normalizeInteger(data.shop_id !== undefined ? data.shop_id : data.shopId, 'shop_id', { + allowEmpty: true, + min: 1, + }); + const shopBinding = await this.resolveShopBinding(normalizedShopId); + + updates.shop_id = shopBinding.shopId; + updates.token = shopBinding.token; + } + + if (hasPlatformShopId) { + updates.platform_shop_id = this.normalizeInteger( + data.platform_shop_id !== undefined ? data.platform_shop_id : data.platformShopId, + 'platform_shop_id', + { + allowEmpty: true, + min: 1, + } + ); + } + + if (hasTemplateId) { + const normalizedTemplateId = this.normalizeOptionalText( + data.template_id !== undefined ? data.template_id : data.templateId, + 'template_id', + 50 + ); + updates.template_id = normalizedTemplateId === '' ? null : normalizedTemplateId; + } + + if (hasPaymode) { + updates.paymode = this.normalizeInteger( + data.paymode !== undefined ? data.paymode : data.payMode, + 'paymode', + { + allowEmpty: true, + } + ); + } + + if (hasBrandNo) { + const normalizedBrandNo = this.normalizeOptionalText( + data.brandno !== undefined ? data.brandno : data.brandNo, + 'brandno', + 255 + ); + updates.brandno = normalizedBrandNo === '' ? null : normalizedBrandNo; + } + + if (hasProviderType) { + const normalizedProviderType = this.normalizeOptionalText( + data.providertype !== undefined ? data.providertype : data.providerType, + 'providertype', + 50 + ); + updates.providertype = normalizedProviderType === '' ? null : normalizedProviderType; + } + + if (hasProviderId) { + updates.providerid = this.normalizeInteger( + data.providerid !== undefined ? data.providerid : data.providerId, + 'providerid', + { + allowEmpty: true, + } + ); + } + + if (hasViewer) { + updates.viewer = this.normalizeOptionalText(data.viewer, 'viewer', 50); + } + + if (hasClientId) { + updates.client_id = this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50); + } + + if (hasIsPickup) { + updates.ispickup = this.normalizeFlag(data.ispickup !== undefined ? data.ispickup : data.isPickup, 'ispickup', 0); + } + + if (hasShipperNo) { + updates.shipperno = this.normalizeOptionalText(data.shipperno !== undefined ? data.shipperno : data.shipperNo, 'shipperno', 255); + } + + if (hasTemplateUrl) { + updates.template_url = this.normalizeOptionalText( + data.template_url !== undefined ? data.template_url : data.templateUrl, + 'template_url', + 500 + ); + } + + if (hasProvinceName) { + updates.province_name = this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255); + } + + if (hasCityName) { + updates.city_name = this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255); + } + + if (hasDistrictName) { + updates.district_name = this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255); + } + + if (hasAddress) { + updates.address = this.normalizeOptionalText(data.address, 'address', 255); + } + + if (hasTownName) { + updates.town_name = this.normalizeOptionalText(data.town_name || data.townName, 'town_name', 255); + } + + if (hasSiteCode) { + updates.site_code = this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255); + } + + if (hasProductType) { + updates.product_type = this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50); + } + + if (hasShopName) { + updates.shop_name = this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255); + } + + if (hasExtData) { + updates.ext_data = this.normalizeOptionalJson( + data.ext_data !== undefined ? data.ext_data : data.extData, + 'ext_data' + ); + } + + if (hasIsEnabled) { + updates.is_enabled = this.normalizeFlag( + data.is_enabled !== undefined ? data.is_enabled : data.isEnabled, + 'is_enabled', + 1 + ); + } + + if (hasExpressCode || hasPlatformCode || hasSysExpressCode) { + updates.sys_express_code = await this.resolveSysExpressCode({ + expressCode: nextExpressCode, + platformCode: nextPlatformCode, + sysExpressCode: hasSysExpressCode + ? (data.sys_express_code !== undefined ? data.sys_express_code : data.sysExpressCode) + : undefined, + }); + } + + const previousWarehouseId = Number(setting.warehouse_id || this.getCurrentStoreId()); + const previousPlatformCode = this.normalizePlatformCode(setting.platform_code, 'platform_code', 20); + const nextWarehouseId = previousWarehouseId; + const nextCachePlatformCode = Object.prototype.hasOwnProperty.call(updates, 'platform_code') + ? this.normalizePlatformCode(updates.platform_code, 'platform_code', 20) + : previousPlatformCode; + + await setting.update(updates); + + await Promise.all(Array.from(new Set([ + this.getWarehousePlatformCacheKey(previousWarehouseId, previousPlatformCode), + this.getWarehousePlatformCacheKey(nextWarehouseId, nextCachePlatformCode), + ])).map(cacheKey => this.deleteCacheByKey(cacheKey))); + + const refreshedSetting = await this.findInterfaceById(id); + const plainSetting = refreshedSetting && typeof refreshedSetting.get === 'function' + ? refreshedSetting.get({ plain: true }) + : refreshedSetting; + + return { + code: 200, + data: this.normalizeInterfaceRow(plainSetting), + }; + } + + /** + * 删除快递接口。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const id = Number(data.id || data.interface_id || data.interfaceId || 0); + if (!Number.isInteger(id) || id <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + const setting = await this.findInterfaceById(id); + const plainSetting = setting && typeof setting.get === 'function' + ? setting.get({ plain: true }) + : setting; + + await setting.destroy(); + + await this.clearWarehousePlatformCache(plainSetting.warehouse_id, plainSetting.platform_code); + + return { + code: 200, + data: { + id: Number(plainSetting.id), + warehouse_id: Number(plainSetting.warehouse_id), + deleted: true, + }, + }; + } + + /** + * 加载当前仓库下所有快递接口的下拉选项(id + name)。 + * 供 index.loadExpressInterfaces 调用,用于前端下拉框。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.systemExpressCode] 系统快递编码,传入时按 sys_express_code 过滤 + * @return {Promise>} 快递接口下拉列表 + */ + async loadExpressInterfaces(data = {}) { + const { ctx } = this; + const warehouseId = this.getCurrentStoreId(); + const systemExpressCode = String(data.systemExpressCode || '').trim().toUpperCase(); + + const where = { warehouse_id: warehouseId }; + if (systemExpressCode) { + where.sys_express_code = systemExpressCode; + } + + const rows = await ctx.model.ExpressInterface.findAll({ + where, + attributes: [ 'id', 'name' ], + order: [[ 'weight', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return rows.map(row => ({ + value: row.id, + label: row.name || '', + })); + } +} + +module.exports = SettingExpressInterfaceService; diff --git a/app/service/systems/setting/packageMaterial.js b/app/service/systems/setting/packageMaterial.js new file mode 100644 index 0000000..a7431a1 --- /dev/null +++ b/app/service/systems/setting/packageMaterial.js @@ -0,0 +1,651 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class SettingPackageMaterialService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体 ID。 + * + * @return {number} 当前仓库主体 ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作包材', 400); + } + + return storeId; + } + + /** + * 规范化必填文本。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string} 规范化结果 + */ + normalizeRequiredText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + throw this.createError(fieldName + ' 参数不能为空', 400); + } + + const normalized = String(value).trim(); + if (!normalized) { + throw this.createError(fieldName + ' 参数不能为空', 400); + } + + if (normalized.length > maxLength) { + throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); + } + + return normalized; + } + + /** + * 规范化可选文本。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string|null} 规范化结果 + */ + normalizeOptionalText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + return null; + } + + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + + if (normalized.length > maxLength) { + throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); + } + + return normalized; + } + + /** + * 规范化可选小数。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number|null} [min=null] 最小值 + * @return {number|null} 规范化结果 + */ + normalizeOptionalDecimal(value, fieldName, min = null) { + if (value === undefined || value === null || value === '') { + return null; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized)) { + throw this.createError(fieldName + ' 参数不合法', 400); + } + + if (min !== null && normalized < min) { + throw this.createError(fieldName + ' 参数不合法', 400); + } + + return normalized; + } + + /** + * 规范化可选状态值。 + * + * @param {*} value 原始值 + * @param {number} defaultValue 默认值 + * @return {number} 规范化结果 + */ + normalizeStatus(value, defaultValue = 1) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isInteger(normalized) || ![ 0, 1 ].includes(normalized)) { + throw this.createError('status 参数不合法', 400); + } + + return normalized; + } + + /** + * 规范化分页参数。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(fieldName + ' 参数不合法', 400); + } + + return Math.min(Math.floor(normalized), maxValue); + } + + /** + * 规范化删除 ID 列表。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + normalizeDeleteIds(data = {}) { + const { + ids, + id, + material_id: materialId, + materialId: camelMaterialId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 列表 where 字段映射。 + * + * @return {Object} 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + material_code: { + field: 'material_code', + }, + material_name: { + field: 'material_name', + }, + material_type: { + field: 'material_type', + }, + status: { + field: 'status', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 解析列表查询 where。 + * + * @param {Object} data 请求参数 + * @return {Object} 解析结果 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError('where 参数解析失败: ' + parsed.reason, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 规范化包材行数据。 + * + * @param {Object} row 原始行 + * @return {Object|null} 规范化结果 + */ + normalizeMaterialRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + material_code: String(row.material_code || '').trim(), + material_name: String(row.material_name || '').trim(), + material_type: row.material_type === undefined || row.material_type === null ? '' : String(row.material_type).trim(), + spec: row.spec === undefined || row.spec === null ? '' : String(row.spec).trim(), + length: row.length === undefined || row.length === null ? null : Number(row.length), + width: row.width === undefined || row.width === null ? null : Number(row.width), + height: row.height === undefined || row.height === null ? null : Number(row.height), + weight: row.weight === undefined || row.weight === null ? null : Number(row.weight), + cost_price: row.cost_price === undefined || row.cost_price === null ? null : Number(row.cost_price), + status: row.status === undefined || row.status === null ? 1 : Number(row.status), + version: row.version === undefined || row.version === null ? null : Number(row.version), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + }; + } + + /** + * 校验包材编码在当前仓库内唯一。 + * + * @param {number} warehouseId 仓库 ID + * @param {string} materialCode 包材编码 + * @param {number|null} [excludeId=null] 排除 ID + * @return {Promise} 无返回值 + */ + async ensureMaterialCodeUnique(warehouseId, materialCode, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const where = { + warehouse_id: warehouseId, + material_code: materialCode, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + const existing = await ctx.model.PackageMaterial.findOne({ + where, + attributes: [ 'id', 'material_code' ], + }); + + if (existing) { + throw this.createError('material_code 已被当前仓库使用', 409); + } + } + + /** + * 按 ID 查找包材。 + * + * @param {number} id 包材 ID + * @param {number} warehouseId 仓库 ID + * @return {Promise} 包材记录 + */ + async findMaterialById(id, warehouseId) { + const material = await this.ctx.model.PackageMaterial.findOne({ + where: { + id, + warehouse_id: warehouseId, + }, + }); + + if (!material) { + throw this.createError('包材不存在或无权限操作', 404); + } + + return material; + } + + /** + * 创建包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const warehouseId = this.getCurrentStoreId(); + const { + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + } = data || {}; + + const normalizedMaterialCode = this.normalizeRequiredText(materialCode, 'material_code', 64).toUpperCase(); + const normalizedMaterialName = this.normalizeRequiredText(materialName, 'material_name', 128); + const normalizedMaterialType = this.normalizeOptionalText(materialType, 'material_type', 32); + const normalizedSpec = this.normalizeOptionalText(spec, 'spec', 128); + const normalizedStatus = this.normalizeStatus(status, 1); + + await this.ensureMaterialCodeUnique(warehouseId, normalizedMaterialCode); + + const createdRow = await this.ctx.model.PackageMaterial.create({ + warehouse_id: warehouseId, + material_code: normalizedMaterialCode, + material_name: normalizedMaterialName, + material_type: normalizedMaterialType, + spec: normalizedSpec, + length: this.normalizeOptionalDecimal(length, 'length', 0), + width: this.normalizeOptionalDecimal(width, 'width', 0), + height: this.normalizeOptionalDecimal(height, 'height', 0), + weight: this.normalizeOptionalDecimal(weight, 'weight', 0), + cost_price: this.normalizeOptionalDecimal(costPrice, 'cost_price', 0), + status: normalizedStatus, + }); + + return this.normalizeMaterialRow(createdRow && typeof createdRow.get === 'function' ? createdRow.get({ plain: true }) : createdRow); + } + + /** + * 更新包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 更新结果 + */ + async update(data = {}) { + const warehouseId = this.getCurrentStoreId(); + const { + id, + material_id: materialId, + materialId: camelMaterialId, + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + } = data || {}; + + const resolvedId = Number(id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId)); + if (!Number.isInteger(resolvedId) || resolvedId <= 0) { + throw this.createError('id 参数不合法', 400); + } + + const material = await this.findMaterialById(resolvedId, warehouseId); + const updates = {}; + + if (materialCode !== undefined) { + const normalizedMaterialCode = this.normalizeRequiredText(materialCode, 'material_code', 64).toUpperCase(); + await this.ensureMaterialCodeUnique(warehouseId, normalizedMaterialCode, resolvedId); + updates.material_code = normalizedMaterialCode; + } + + if (materialName !== undefined) { + updates.material_name = this.normalizeRequiredText(materialName, 'material_name', 128); + } + + if (materialType !== undefined) { + updates.material_type = this.normalizeOptionalText(materialType, 'material_type', 32); + } + + if (spec !== undefined) { + updates.spec = this.normalizeOptionalText(spec, 'spec', 128); + } + + if (length !== undefined) { + updates.length = this.normalizeOptionalDecimal(length, 'length', 0); + } + + if (width !== undefined) { + updates.width = this.normalizeOptionalDecimal(width, 'width', 0); + } + + if (height !== undefined) { + updates.height = this.normalizeOptionalDecimal(height, 'height', 0); + } + + if (weight !== undefined) { + updates.weight = this.normalizeOptionalDecimal(weight, 'weight', 0); + } + + if (costPrice !== undefined) { + updates.cost_price = this.normalizeOptionalDecimal(costPrice, 'cost_price', 0); + } + + if (status !== undefined) { + updates.status = this.normalizeStatus(status, 1); + } + + if (Object.keys(updates).length > 0) { + await material.update(updates); + } + + return this.normalizeMaterialRow(material && typeof material.get === 'function' ? material.get({ plain: true }) : material); + } + + /** + * 删除包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const ids = this.normalizeDeleteIds(data); + + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const rows = await ctx.model.PackageMaterial.findAll({ + where: { + id: { + [Op.in]: ids, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'material_code' ], + raw: true, + }); + + if (!Array.isArray(rows) || rows.length !== ids.length) { + throw this.createError('存在包材不存在或无权限删除', 404); + } + + const refCount = await ctx.model.OrderExpress.count({ + where: { + warehouse_id: warehouseId, + package_material_id: { + [Op.in]: ids, + }, + }, + }); + + if (Number(refCount) > 0) { + throw this.createError('包材已被订单快递使用,无法删除', 409); + } + + const affectedRows = await ctx.model.PackageMaterial.destroy({ + where: { + id: { + [Op.in]: ids, + }, + warehouse_id: warehouseId, + }, + }); + + return { + deleted: true, + warehouse_id: warehouseId, + ids, + affected_rows: Number(affectedRows || 0), + }; + } + + /** + * 查询包材列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 分页结果 + */ + async get(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + + const andConditions = [ + { + warehouse_id: warehouseId, + }, + ...(Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []), + ]; + + const quickWhereField = parsedResult.rawConditionsByField + && parsedResult.rawConditionsByField.quickWhere + ? parsedResult.rawConditionsByField.quickWhere + : null; + const quickWhereValue = quickWhereField && quickWhereField.value !== undefined + ? String(quickWhereField.value || '').trim() + : ''; + + if (quickWhereValue) { + andConditions.push({ + [Op.or]: [ + { + material_code: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + material_name: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + material_type: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + spec: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + ], + }); + } + + const { rows, count } = await ctx.model.PackageMaterial.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + order: [[ 'id', 'DESC' ]], + limit: pageSize, + offset, + }); + + return { + page, + page_size: pageSize, + total: Number(count || 0), + where: normalizedWhere, + list: (Array.isArray(rows) ? rows : []) + .map(item => this.normalizeMaterialRow(item && typeof item.get === 'function' ? item.get({ plain: true }) : item)) + .filter(Boolean), + }; + } + + /** + * 快捷搜索包材,按关键词模糊匹配编码和名称。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.keyword] 搜索关键词,匹配 material_code 和 material_name + * @return {Promise} 返回对象包含 data 属性,值为匹配结果数组,最多 50 条 + */ + async search(data = {}) { + const { app } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const { keyword } = data || {}; + + const whereCondition = { + warehouse_id: warehouseId, + status: 1, + }; + + if (keyword && String(keyword).trim()) { + const kw = String(keyword).trim(); + const like = `%${kw}%`; + whereCondition[Op.or] = [ + { material_code: { [Op.like]: like } }, + { material_name: { [Op.like]: like } }, + ]; + } + + const rows = await app.model.PackageMaterial.findAll({ + where: whereCondition, + attributes: [ 'id', 'material_code', 'material_name', 'material_type', 'spec', 'status' ], + order: [[ 'id', 'DESC' ]], + limit: 50, + raw: true, + }); + + return { + data: rows, + }; + } +} + +module.exports = SettingPackageMaterialService; diff --git a/app/service/systems/setting/packageSupplier.js b/app/service/systems/setting/packageSupplier.js new file mode 100644 index 0000000..41dca1e --- /dev/null +++ b/app/service/systems/setting/packageSupplier.js @@ -0,0 +1,533 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class SettingPackageSupplierService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体 ID。 + * + * @return {number} 当前仓库主体 ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作包材供应商', 400); + } + + return storeId; + } + + /** + * 规范化必填文本。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string} 规范化结果 + */ + normalizeRequiredText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + throw this.createError(fieldName + ' 参数不能为空', 400); + } + + const normalized = String(value).trim(); + if (!normalized) { + throw this.createError(fieldName + ' 参数不能为空', 400); + } + + if (normalized.length > maxLength) { + throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); + } + + return normalized; + } + + /** + * 规范化可选文本。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string|null} 规范化结果 + */ + normalizeOptionalText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + return null; + } + + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + + if (normalized.length > maxLength) { + throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); + } + + return normalized; + } + + /** + * 规范化可选状态值。 + * + * @param {*} value 原始值 + * @param {number} defaultValue 默认值 + * @return {number} 规范化结果 + */ + normalizeStatus(value, defaultValue = 1) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isInteger(normalized) || ![ 0, 1 ].includes(normalized)) { + throw this.createError('status 参数不合法', 400); + } + + return normalized; + } + + /** + * 规范化分页参数。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(fieldName + ' 参数不合法', 400); + } + + return Math.min(Math.floor(normalized), maxValue); + } + + /** + * 规范化删除 ID 列表。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + normalizeDeleteIds(data = {}) { + const { + ids, + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 列表 where 字段映射。 + * + * @return {Object} 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + supplier_code: { + field: 'supplier_code', + }, + supplier_name: { + field: 'supplier_name', + }, + contact_name: { + field: 'contact_name', + }, + contact_phone: { + field: 'contact_phone', + }, + status: { + field: 'status', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 解析列表查询 where。 + * + * @param {Object} data 请求参数 + * @return {Object} 解析结果 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError('where 参数解析失败: ' + parsed.reason, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 规范化供应商行数据。 + * + * @param {Object} row 原始行 + * @return {Object|null} 规范化结果 + */ + normalizeSupplierRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + supplier_code: String(row.supplier_code || '').trim(), + supplier_name: String(row.supplier_name || '').trim(), + contact_name: row.contact_name === undefined || row.contact_name === null ? '' : String(row.contact_name).trim(), + contact_phone: row.contact_phone === undefined || row.contact_phone === null ? '' : String(row.contact_phone).trim(), + status: row.status === undefined || row.status === null ? 1 : Number(row.status), + version: row.version === undefined || row.version === null ? null : Number(row.version), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + }; + } + + /** + * 校验供应商编码在当前仓库内唯一。 + * + * @param {number} warehouseId 仓库 ID + * @param {string} supplierCode 供应商编码 + * @param {number|null} [excludeId=null] 排除 ID + * @return {Promise} 无返回值 + */ + async ensureSupplierCodeUnique(warehouseId, supplierCode, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const where = { + warehouse_id: warehouseId, + supplier_code: supplierCode, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + const existing = await ctx.model.PackageSupplier.findOne({ + where, + attributes: [ 'id', 'supplier_code' ], + }); + + if (existing) { + throw this.createError('supplier_code 已被当前仓库使用', 409); + } + } + + /** + * 按 ID 查找供应商。 + * + * @param {number} id 供应商 ID + * @param {number} warehouseId 仓库 ID + * @return {Promise} 供应商记录 + */ + async findSupplierById(id, warehouseId) { + const supplier = await this.ctx.model.PackageSupplier.findOne({ + where: { + id, + warehouse_id: warehouseId, + }, + }); + + if (!supplier) { + throw this.createError('供应商不存在或无权限操作', 404); + } + + return supplier; + } + + /** + * 创建供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const warehouseId = this.getCurrentStoreId(); + const { + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + } = data || {}; + + const normalizedSupplierCode = this.normalizeRequiredText(supplierCode, 'supplier_code', 64).toUpperCase(); + const normalizedSupplierName = this.normalizeRequiredText(supplierName, 'supplier_name', 128); + + await this.ensureSupplierCodeUnique(warehouseId, normalizedSupplierCode); + + const createdRow = await this.ctx.model.PackageSupplier.create({ + warehouse_id: warehouseId, + supplier_code: normalizedSupplierCode, + supplier_name: normalizedSupplierName, + contact_name: this.normalizeOptionalText(contactName, 'contact_name', 64), + contact_phone: this.normalizeOptionalText(contactPhone, 'contact_phone', 32), + status: this.normalizeStatus(status, 1), + }); + + return this.normalizeSupplierRow(createdRow && typeof createdRow.get === 'function' ? createdRow.get({ plain: true }) : createdRow); + } + + /** + * 更新供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 更新结果 + */ + async update(data = {}) { + const warehouseId = this.getCurrentStoreId(); + const { + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + } = data || {}; + + const resolvedId = Number(id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId)); + if (!Number.isInteger(resolvedId) || resolvedId <= 0) { + throw this.createError('id 参数不合法', 400); + } + + const supplier = await this.findSupplierById(resolvedId, warehouseId); + const updates = {}; + + if (supplierCode !== undefined) { + const normalizedSupplierCode = this.normalizeRequiredText(supplierCode, 'supplier_code', 64).toUpperCase(); + await this.ensureSupplierCodeUnique(warehouseId, normalizedSupplierCode, resolvedId); + updates.supplier_code = normalizedSupplierCode; + } + + if (supplierName !== undefined) { + updates.supplier_name = this.normalizeRequiredText(supplierName, 'supplier_name', 128); + } + + if (contactName !== undefined) { + updates.contact_name = this.normalizeOptionalText(contactName, 'contact_name', 64); + } + + if (contactPhone !== undefined) { + updates.contact_phone = this.normalizeOptionalText(contactPhone, 'contact_phone', 32); + } + + if (status !== undefined) { + updates.status = this.normalizeStatus(status, 1); + } + + if (Object.keys(updates).length > 0) { + await supplier.update(updates); + } + + return this.normalizeSupplierRow(supplier && typeof supplier.get === 'function' ? supplier.get({ plain: true }) : supplier); + } + + /** + * 删除供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const ids = this.normalizeDeleteIds(data); + + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const rows = await ctx.model.PackageSupplier.findAll({ + where: { + id: { + [Op.in]: ids, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'supplier_code' ], + raw: true, + }); + + if (!Array.isArray(rows) || rows.length !== ids.length) { + throw this.createError('存在供应商不存在或无权限删除', 404); + } + + const affectedRows = await ctx.model.PackageSupplier.destroy({ + where: { + id: { + [Op.in]: ids, + }, + warehouse_id: warehouseId, + }, + }); + + return { + deleted: true, + warehouse_id: warehouseId, + ids, + affected_rows: Number(affectedRows || 0), + }; + } + + /** + * 查询供应商列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 分页结果 + */ + async get(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + + const andConditions = [ + { + warehouse_id: warehouseId, + }, + ...(Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []), + ]; + + const quickWhereField = parsedResult.rawConditionsByField + && parsedResult.rawConditionsByField.quickWhere + ? parsedResult.rawConditionsByField.quickWhere + : null; + const quickWhereValue = quickWhereField && quickWhereField.value !== undefined + ? String(quickWhereField.value || '').trim() + : ''; + + if (quickWhereValue) { + andConditions.push({ + [Op.or]: [ + { + supplier_code: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + supplier_name: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + contact_name: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + contact_phone: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + ], + }); + } + + const { rows, count } = await ctx.model.PackageSupplier.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + order: [[ 'id', 'DESC' ]], + limit: pageSize, + offset, + }); + + return { + page, + page_size: pageSize, + total: Number(count || 0), + where: normalizedWhere, + list: (Array.isArray(rows) ? rows : []) + .map(item => this.normalizeSupplierRow(item && typeof item.get === 'function' ? item.get({ plain: true }) : item)) + .filter(Boolean), + }; + } +} + +module.exports = SettingPackageSupplierService; diff --git a/app/service/systems/setting/permission.js b/app/service/systems/setting/permission.js new file mode 100644 index 0000000..70027a0 --- /dev/null +++ b/app/service/systems/setting/permission.js @@ -0,0 +1,656 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingPermissionService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作权限', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getRole(roleId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + + const role = await ctx.model.Role.findOne({ + where: { + id: roleId, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + }); + + if (!role) { + throw this.createError('角色不存在或无权限操作', 404); + } + + return role; + } + + async getPermission(permissionId, includeDisabled = false) { + const { ctx } = this; + const where = { id: permissionId }; + if (!includeDisabled) { + where.status = 1; + } + + const permission = await ctx.model.Permission.findOne({ where }); + if (!permission) { + throw this.createError('权限不存在或已禁用', 404); + } + + return permission; + } + + /** + * 规范化并校验权限类型 + * @param {string} type 权限类型 + * @return {string} 规范化后的权限类型 + */ + normalizePermissionType(type) { + const normalized = typeof type === 'string' ? type.trim() : ''; + if (!normalized) { + throw this.createError('type 参数不能为空', 400); + } + + const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'workerstation_pages', 'block' ]); + if (!allowedTypes.has(normalized)) { + throw this.createError('type 参数不合法', 400); + } + return normalized; + } + + normalizeOptionalString(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + return ''; + } + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeParentId(value) { + if (value === undefined || value === null || value === '' || Number(value) === 0) { + return null; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError('parent_id 参数不合法', 400); + } + return num; + } + + normalizeSort(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError('sort 参数不合法', 400); + } + return Math.floor(num); + } + + normalizeStatus(value) { + if (value === undefined || value === null || value === '') { + return 1; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError('status 参数不合法', 400); + } + + normalizeBooleanFlag(value, fieldName) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + async getAvailablePermissionIdSet({ includeDisabled = false } = {}) { + const rows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type: null, + keyword: '', + }); + return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0)); + } + + async ensureParentPermissionExists(parentId) { + if (!parentId) { + return; + } + + await this.getPermission(parentId, false); + } + + async ensurePermissionsExist(permissionIds) { + const { ctx } = this; + + const targetRows = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id' ], + raw: true, + }); + if (targetRows.length !== permissionIds.length) { + const found = new Set(targetRows.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(Number(id))); + throw this.createError(`权限不存在:${missing.join(',')}`, 404); + } + + return targetRows; + } + + normalizePermissionIds(inputPermissionIds) { + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组', 400); + } + permissionIds.push(normalized); + } + + return Array.from(new Set(permissionIds)); + } + + normalizeIds(inputIds, fieldName = 'ids') { + if (!Array.isArray(inputIds)) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const ids = []; + for (const item of inputIds) { + const normalized = Number(item); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(`${fieldName} 必须是正整数数组`, 400); + } + ids.push(normalized); + } + if (ids.length === 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + return Array.from(new Set(ids)); + } + + async validatePermissions(permissionIds) { + const { ctx } = this; + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + }); + + if (permissions.length !== permissionIds.length) { + const foundIds = permissions.map(item => Number(item.id)); + const missingIds = permissionIds.filter(item => !foundIds.includes(item)); + throw this.createError(`权限不存在或已禁用:${missingIds.join(',')}`, 400); + } + + return permissions; + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async getCurrentEmployeePermissionIds() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + const roleIds = Array.from(new Set(employeeRoles + .map(item => Number(item.role_id)) + .filter(id => Number.isFinite(id) && id > 0))); + if (roleIds.length === 0) { + return []; + } + + return await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, + }); + } + + async getCurrentRoleId() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return null; + } + + const row = await ctx.model.EmployeeRole.findOne({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const roleId = Number(row && row.role_id); + if (!Number.isFinite(roleId) || roleId <= 0) { + return null; + } + return roleId; + } + + async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '', scopeMode = 'available' } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const where = { + status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, + }; + + if (scopeMode !== 'all') { + const currentPermissionIds = await this.getCurrentEmployeePermissionIds(); + if (currentPermissionIds.length === 0) { + return []; + } + where.id = { + [Op.in]: currentPermissionIds, + }; + } + if (type) { + where.type = type; + } + if (keyword) { + where[Op.or] = [ + { path: { [Op.like]: `%${keyword}%` } }, + { name: { [Op.like]: `%${keyword}%` } }, + { meta_title: { [Op.like]: `%${keyword}%` } }, + ]; + } + + const permissionRows = await ctx.model.Permission.findAll({ + where, + attributes: [ + 'id', + 'path', + 'name', + 'type', + 'status', + 'parent_id', + 'sort', + 'component', + 'redirect', + 'meta_title', + 'meta_icon', + 'hidden', + 'always_show', + ], + order: [ + [ 'sort', 'ASC' ], + [ 'id', 'ASC' ], + ], + }); + + return permissionRows; + } + + async list(data = {}) { + const { ctx } = this; + + const includeDisabled = data.includeDisabled === true; + const roleIdRaw = data.role_id || data.roleId; + const type = typeof data.type === 'string' && data.type.trim() ? data.type.trim() : null; + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + let role = null; + let targetRoleId = roleIdRaw; + if (targetRoleId === undefined || targetRoleId === null || targetRoleId === '') { + targetRoleId = await this.getCurrentRoleId(); + } + if (targetRoleId !== undefined && targetRoleId !== null && targetRoleId !== '') { + const roleId = this.toPositiveNumber(targetRoleId, 'role_id'); + role = await this.getRole(roleId); + } + + // 权限管理页需要展示全量权限树,不能再按当前登录工号已分配权限做裁剪。 + const permissionRows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type, + keyword, + scopeMode: 'all', + }); + + let selectedPermissionSet = new Set(); + let selectAllPermissions = false; + if (role) { + const directPermissionIds = ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions); + if (directPermissionIds.includes('*')) { + selectAllPermissions = true; + } else if (directPermissionIds.length > 0) { + selectedPermissionSet = new Set(directPermissionIds.map(item => Number(item))); + } + } + + const permissions = permissionRows.map(item => ({ + permission_id: Number(item.id), + path: item.path || '', + name: item.name || '', + type: item.type || '', + status: Number(item.status), + parent_id: item.parent_id === null ? null : Number(item.parent_id), + sort: Number(item.sort || 0), + component: item.component || '', + redirect: item.redirect || '', + meta_title: item.meta_title || '', + meta_icon: item.meta_icon || '', + hidden: Number(item.hidden || 0), + always_show: Number(item.always_show || 0), + selected: role ? (selectAllPermissions || selectedPermissionSet.has(Number(item.id))) : false, + })); + + return { + code: 200, + data: { + role_id: role ? Number(role.id) : null, + permissions, + }, + }; + } + + async add(data = {}) { + const { ctx } = this; + + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + + const permissionData = { + path, + type: this.normalizePermissionType(data.type), + name: this.normalizeOptionalString(data.name, 'name', 100) || '', + component: this.normalizeOptionalString(data.component, 'component', 255), + redirect: this.normalizeOptionalString(data.redirect, 'redirect', 255), + meta_title: this.normalizeOptionalString(data.meta_title, 'meta_title', 100), + meta_icon: this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50), + parent_id: this.normalizeParentId(data.parent_id), + sort: this.normalizeSort(data.sort), + hidden: this.normalizeBooleanFlag(data.hidden, 'hidden'), + always_show: this.normalizeBooleanFlag(data.always_show, 'always_show'), + status: this.normalizeStatus(data.status), + }; + + await this.ensureParentPermissionExists(permissionData.parent_id); + + let created = null; + try { + created = await ctx.model.Permission.create(permissionData); + } catch (error) { + throw error; + } + + return { + code: 200, + data: { + permission_id: Number(created.id), + path: created.path || '', + type: created.type || '', + parent_id: created.parent_id === null ? null : Number(created.parent_id), + status: Number(created.status), + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + const permissionIds = this.normalizeIds(data.ids, 'ids'); + + await this.ensurePermissionsExist(permissionIds); + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id', 'status' ], + raw: true, + }); + + const deletedIds = []; + const alreadyDeletedIds = []; + for (const permission of permissions) { + if (Number(permission.status) === 0) { + alreadyDeletedIds.push(Number(permission.id)); + } else { + deletedIds.push(Number(permission.id)); + } + } + + const transaction = await ctx.model.transaction(); + try { + if (deletedIds.length > 0) { + await ctx.model.Permission.update({ + status: 0, + }, { + where: { + id: deletedIds, + }, + transaction, + }); + + await ctx.service.systems.auth.rolePermission.removePermissionsFromAllRoles(deletedIds, { + transaction, + }); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + return { + code: 200, + data: { + ids: permissionIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id'); + await this.ensurePermissionsExist([ permissionId ]); + + const permission = await this.getPermission(permissionId, true); + + const hasPath = Object.prototype.hasOwnProperty.call(data, 'path'); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasType = Object.prototype.hasOwnProperty.call(data, 'type'); + const hasComponent = Object.prototype.hasOwnProperty.call(data, 'component'); + const hasRedirect = Object.prototype.hasOwnProperty.call(data, 'redirect'); + const hasMetaTitle = Object.prototype.hasOwnProperty.call(data, 'meta_title'); + const hasMetaIcon = Object.prototype.hasOwnProperty.call(data, 'meta_icon'); + const hasParentId = Object.prototype.hasOwnProperty.call(data, 'parent_id'); + const hasSort = Object.prototype.hasOwnProperty.call(data, 'sort'); + const hasHidden = Object.prototype.hasOwnProperty.call(data, 'hidden'); + const hasAlwaysShow = Object.prototype.hasOwnProperty.call(data, 'always_show'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + + if (!hasPath && !hasName && !hasType && !hasComponent && !hasRedirect + && !hasMetaTitle && !hasMetaIcon && !hasParentId && !hasSort + && !hasHidden && !hasAlwaysShow && !hasStatus) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + if (hasPath) { + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + updates.path = path; + } + if (hasName) { + updates.name = this.normalizeOptionalString(data.name, 'name', 100) || ''; + } + if (hasType) { + updates.type = this.normalizePermissionType(data.type); + } + if (hasComponent) { + updates.component = this.normalizeOptionalString(data.component, 'component', 255); + } + if (hasRedirect) { + updates.redirect = this.normalizeOptionalString(data.redirect, 'redirect', 255); + } + if (hasMetaTitle) { + updates.meta_title = this.normalizeOptionalString(data.meta_title, 'meta_title', 100); + } + if (hasMetaIcon) { + updates.meta_icon = this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50); + } + if (hasParentId) { + const parentId = this.normalizeParentId(data.parent_id); + if (parentId && parentId === permissionId) { + throw this.createError('parent_id 不能等于 permission_id', 400); + } + await this.ensureParentPermissionExists(parentId); + updates.parent_id = parentId; + } + if (hasSort) { + updates.sort = this.normalizeSort(data.sort); + } + if (hasHidden) { + updates.hidden = this.normalizeBooleanFlag(data.hidden, 'hidden'); + } + if (hasAlwaysShow) { + updates.always_show = this.normalizeBooleanFlag(data.always_show, 'always_show'); + } + if (hasStatus) { + updates.status = this.normalizeStatus(data.status); + } + + await permission.update(updates); + + return { + code: 200, + data: { + permission_id: Number(permission.id), + path: permission.path || '', + type: permission.type || '', + parent_id: permission.parent_id === null ? null : Number(permission.parent_id), + status: Number(permission.status), + }, + }; + } +} + +module.exports = SettingPermissionService; diff --git a/app/service/systems/setting/platform.js b/app/service/systems/setting/platform.js new file mode 100644 index 0000000..b779b3f --- /dev/null +++ b/app/service/systems/setting/platform.js @@ -0,0 +1,799 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class SettingPlatformService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体 ID。 + * + * @return {number} 当前仓库主体 ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作平台设置', 400); + } + return storeId; + } + + /** + * 归一化删除 ID 列表。 + * + * 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + normalizeDeleteIds(data = {}) { + const { + ids, + id, + setting_id: settingId, + settingId: camelSettingId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 生成平台列表缓存键。 + * + * @param {number|string} warehouseId 仓库 ID + * @return {string} 缓存键 + */ + getPlatformListCacheKey(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + return `platform:list:${normalizedWarehouseId}`; + } + + return 'platform:list'; + } + + /** + * 生成平台详情缓存键。 + * + * @param {string} platformCode 平台设置代码 + * @param {number|string} warehouseId 仓库 ID + * @return {string} 缓存键 + */ + getPlatformDetailCacheKey(platformCode, warehouseId) { + return `platform_setting_detail:${platformCode}:${warehouseId}`; + } + + /** + * 生成平台存在性缓存键。 + * + * @param {string} platformCode 平台设置代码 + * @param {number|string} warehouseId 仓库 ID + * @return {string} 缓存键 + */ + getPlatformExistsCacheKey(platformCode, warehouseId) { + return `platform:${platformCode}:${warehouseId}`; + } + + /** + * 删除指定缓存键。 + * + * @param {string} cacheKey 缓存键 + * @return {Promise} + */ + async deleteCacheByKey(cacheKey) { + if (!cacheKey) { + return; + } + + const { app } = this; + if (app && typeof app.delCacheAsync === 'function') { + await app.delCacheAsync(cacheKey); + return; + } + + if (app && typeof app.setCacheAsync === 'function') { + await app.setCacheAsync(cacheKey, null, 0); + } + } + + /** + * 清理平台列表、详情和存在性缓存。 + * + * @param {number|string} warehouseId 仓库 ID + * @param {Array} platformCodes 平台设置代码列表 + * @return {Promise} + */ + async clearPlatformCaches(warehouseId, platformCodes = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + const uniquePlatformCodes = Array.from(new Set( + Array.isArray(platformCodes) + ? platformCodes.map(code => String(code || '').trim()).filter(Boolean) + : [] + )); + + const cacheKeys = [ + this.getPlatformListCacheKey(normalizedWarehouseId), + ...uniquePlatformCodes.flatMap(platformCode => [ + this.getPlatformDetailCacheKey(platformCode, normalizedWarehouseId), + this.getPlatformExistsCacheKey(platformCode, normalizedWarehouseId), + ]), + ]; + + await Promise.all(cacheKeys.map(cacheKey => this.deleteCacheByKey(cacheKey))); + } + + /** + * 规范化必填文本。 + * + * @param {string|number} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string} 规范化后的文本 + */ + normalizeRequiredText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + if (typeof value !== 'string' && typeof value !== 'number') { + throw this.createError(`${fieldName} 参数类型不合法`, 400); + } + + const normalized = String(value).trim(); + if (!normalized) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + + return normalized; + } + + /** + * 规范化可选文本。 + * + * @param {string|number} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string|null} 规范化后的文本 + */ + normalizeOptionalText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + return null; + } + + if (typeof value !== 'string' && typeof value !== 'number') { + throw this.createError(`${fieldName} 参数类型不合法`, 400); + } + + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + + return normalized; + } + + /** + * 规范化整数。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {Object} [options] 额外选项 + * @param {boolean} [options.allowEmpty=false] 是否允许空值 + * @param {number|null} [options.min=null] 最小值 + * @param {number|null} [options.max=null] 最大值 + * @return {number|null} 规范化后的整数 + */ + normalizeInteger(value, fieldName, options = {}) { + const { + allowEmpty = false, + min = null, + max = null, + } = options; + + if (value === undefined || value === null || value === '') { + if (allowEmpty) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const normalized = Number(value); + if (!Number.isInteger(normalized)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (min !== null && normalized < min) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (max !== null && normalized > max) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return normalized; + } + + /** + * 规范化分页参数。 + * + * @param {number|string} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return Math.min(Math.floor(normalized), maxValue); + } + + /** + * 获取列表查询字段映射。 + * + * @return {Object} 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + code: { + field: 'code', + }, + name: { + field: 'name', + }, + platform_code: { + field: 'platform_code', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 解析列表查询条件。 + * + * @param {Object} data 请求参数 + * @return {Object} 查询条件信息 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 生成平台展示标签。 + * + * @param {string} code 设置代码 + * @param {string} platformName 平台名称 + * @return {string} 展示标签 + */ + buildPlatformLabel(code, platformName) { + const normalizedCode = String(code || '').trim(); + const normalizedPlatformName = String(platformName || '').trim(); + + if (!normalizedCode) { + return normalizedPlatformName; + } + + if (!normalizedPlatformName) { + return normalizedCode; + } + + return `${normalizedCode} (${normalizedPlatformName})`; + } + + /** + * 规范化平台设置记录。 + * + * @param {Object} row 数据库记录 + * @return {Object|null} 规范化后的记录 + */ + normalizePlatformRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const platform = row.platform && typeof row.platform === 'object' ? row.platform : null; + const code = this.normalizeOptionalText(row.code, 'code', 50); + if (!code) { + return null; + } + + const platformCode = this.normalizeOptionalText(row.platform_code, 'platform_code', 50) + || this.normalizeOptionalText(platform && platform.code, 'platform_code', 50) + || ''; + const platformName = this.normalizeOptionalText( + row.platform_name !== undefined ? row.platform_name : (platform && platform.name), + 'platform_name', + 255 + ) || ''; + const platformLabel = this.buildPlatformLabel(code, platformName); + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + code, + name: this.normalizeOptionalText(row.name, 'name', 100), + platform_code: platformCode, + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + label: platformLabel, + platform_name: platformName, + platform_label: platformLabel, + platform: platform ? { + code: this.normalizeOptionalText(platform.code, 'platform.code', 50), + name: this.normalizeOptionalText(platform.name, 'platform.name', 255), + // 兼容历史返回结构:platform.platform_code 回退为平台 code。 + platform_code: this.normalizeOptionalText(platform.code, 'platform.code', 50), + } : null, + }; + } + + /** + * 查找当前仓库下的平台设置记录。 + * + * @param {number} id 设置 ID + * @return {Promise} 平台设置记录 + */ + async findSettingById(id) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + + const setting = await ctx.model.PlatformSetting.findOne({ + where: { + id, + warehouse_id: currentStoreId, + }, + include: [ + { + model: ctx.model.Platform, + as: 'platform', + attributes: [ 'code', 'name' ], + required: false, + }, + ], + }); + + if (!setting) { + throw this.createError('平台设置不存在或无权限操作', 404); + } + + return setting; + } + + /** + * 查找同仓下的 code 冲突记录。 + * + * @param {string} code 设置代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 冲突记录 + */ + async findCodeConflict(code, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + code, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.PlatformSetting.findOne({ + where, + attributes: [ 'id', 'code' ], + }); + } + + /** + * 查找同仓下的平台代码冲突记录。 + * + * @param {string} platformCode 平台代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 冲突记录 + */ + async findPlatformCodeConflict(platformCode, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const where = { + warehouse_id: this.getCurrentStoreId(), + platform_code: platformCode, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + return await ctx.model.PlatformSetting.findOne({ + where, + attributes: [ 'id', 'platform_code' ], + }); + } + + /** + * 校验平台是否存在。 + * + * @param {string} platformCode 平台代码 + * @return {Promise} 平台记录 + */ + async ensurePlatformExists(platformCode) { + const { ctx } = this; + const platform = await ctx.model.Platform.findOne({ + where: { + code: platformCode, + }, + attributes: [ 'code', 'name' ], + }); + + if (!platform) { + throw this.createError('platform_code 不存在或不支持', 400); + } + + return platform; + } + + /** + * 校验 code 是否可用。 + * + * @param {string} code 设置代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 是否可用 + */ + async ensureCodeAvailable(code, excludeId = null) { + const conflict = await this.findCodeConflict(code, excludeId); + if (conflict) { + throw this.createError('code 已被当前仓库使用', 409); + } + return true; + } + + /** + * 校验平台代码是否可用。 + * + * @param {string} platformCode 平台代码 + * @param {number|null} [excludeId=null] 排除的记录 ID + * @return {Promise} 是否可用 + */ + async ensurePlatformCodeAvailable(platformCode, excludeId = null) { + const conflict = await this.findPlatformCodeConflict(platformCode, excludeId); + if (conflict) { + throw this.createError('platform_code 已被当前仓库使用', 409); + } + return true; + } + + /** + * 获取平台设置列表。 + * + * @param {Object} data 请求参数 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 分页结果 + */ + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentStoreId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + const andConditions = [ + { + warehouse_id: currentStoreId, + }, + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { code: { [Op.like]: `%${keyword}%` } }, + { name: { [Op.like]: `%${keyword}%` } }, + { platform_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + const result = await ctx.model.PlatformSetting.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + include: [ + { + model: ctx.model.Platform, + as: 'platform', + attributes: [ 'code', 'name' ], + required: false, + }, + ], + attributes: [ 'id', 'code', 'name', 'platform_code', 'warehouse_id' ], + order: [[ 'id', 'DESC' ]], + offset, + limit: pageSize, + }); + + const list = Array.isArray(result && result.rows) + ? result.rows.map(row => this.normalizePlatformRow(row && typeof row.get === 'function' ? row.get({ plain: true }) : row)).filter(Boolean) + : []; + + const total = Array.isArray(result && result.count) + ? result.count.length + : Number(result && result.count ? result.count : 0); + + return { + code: 200, + data: { + list, + total, + page, + page_size: pageSize, + }, + }; + } + + /** + * 创建平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { ctx } = this; + const currentStoreId = this.getCurrentStoreId(); + + const code = this.normalizeRequiredText(data.code, 'code', 50); + const name = this.normalizeRequiredText(data.name, 'name', 100); + const platformCode = this.normalizeRequiredText(data.platform_code !== undefined ? data.platform_code : data.platformCode, 'platform_code', 50); + + const platform = await this.ensurePlatformExists(platformCode); + await this.ensureCodeAvailable(code); + await this.ensurePlatformCodeAvailable(platformCode); + + const created = await ctx.model.PlatformSetting.create({ + warehouse_id: currentStoreId, + code, + name, + platform_code: platformCode, + }); + + const plainCreated = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + + return { + code: 200, + data: this.normalizePlatformRow({ + ...plainCreated, + platform, + }), + }; + } + + /** + * 修改平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 修改结果 + */ + async update(data = {}) { + const id = Number(data.id || data.setting_id || data.settingId || 0); + if (!Number.isInteger(id) || id <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + const setting = await this.findSettingById(id); + const hasCode = Object.prototype.hasOwnProperty.call(data, 'code'); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code') + || Object.prototype.hasOwnProperty.call(data, 'platformCode'); + + if (!hasCode && !hasName && !hasPlatformCode) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + let nextCode = setting.code || ''; + let nextPlatformCode = setting.platform_code || ''; + let platform = setting.platform || null; + + if (hasCode) { + const code = this.normalizeRequiredText(data.code, 'code', 50); + updates.code = code; + nextCode = code; + } + + if (hasName) { + updates.name = this.normalizeRequiredText(data.name, 'name', 100); + } + + if (hasPlatformCode) { + const platformCode = this.normalizeRequiredText(data.platform_code !== undefined ? data.platform_code : data.platformCode, 'platform_code', 50); + platform = await this.ensurePlatformExists(platformCode); + updates.platform_code = platformCode; + nextPlatformCode = platformCode; + } + + if (Object.prototype.hasOwnProperty.call(updates, 'code')) { + await this.ensureCodeAvailable(nextCode, id); + } + + if (Object.prototype.hasOwnProperty.call(updates, 'platform_code')) { + await this.ensurePlatformCodeAvailable(nextPlatformCode, id); + } + + await setting.update(updates); + + const plainSetting = setting && typeof setting.get === 'function' + ? setting.get({ plain: true }) + : setting; + + return { + code: 200, + data: this.normalizePlatformRow({ + ...plainSetting, + platform, + }), + }; + } + + /** + * 删除平台设置。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const ids = this.normalizeDeleteIds(data); + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const { ctx, app } = this; + const currentStoreId = this.getCurrentStoreId(); + const { Op } = app.Sequelize; + + const settings = await ctx.model.PlatformSetting.findAll({ + where: { + warehouse_id: currentStoreId, + id: { + [Op.in]: ids, + }, + }, + attributes: [ 'id', 'code', 'warehouse_id' ], + }); + + if (!Array.isArray(settings) || settings.length !== ids.length) { + throw this.createError('平台设置不存在或无权限操作', 404); + } + + await ctx.model.PlatformSetting.destroy({ + where: { + warehouse_id: currentStoreId, + id: { + [Op.in]: ids, + }, + }, + }); + + await this.clearPlatformCaches( + currentStoreId, + settings.map(setting => setting && setting.code).filter(Boolean) + ); + + const deletedIds = settings.map(setting => Number(setting.id)).filter(id => Number.isInteger(id) && id > 0); + const responseData = { + ids: deletedIds, + warehouse_id: currentStoreId, + deleted: true, + }; + + if (deletedIds.length === 1) { + responseData.id = deletedIds[0]; + } + + return { + code: 200, + data: responseData, + }; + } +} + +module.exports = SettingPlatformService; diff --git a/app/service/systems/setting/print_template.js b/app/service/systems/setting/print_template.js index e64dad8..aef04d3 100644 --- a/app/service/systems/setting/print_template.js +++ b/app/service/systems/setting/print_template.js @@ -1,16 +1,37 @@ 'use strict'; const Service = require('egg').Service; +const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ]; class PrintTemplateService extends Service { + /** + * 标准化并校验业务类型 + * @param {string} businessType 业务类型 + * @param {boolean} required 是否必填 + * @return {string|null} 标准化后的业务类型 + */ + normalizeAndValidateBusinessType(businessType, required = true) { + const normalizedBusinessType = String(businessType || '').trim().toUpperCase(); + if (!normalizedBusinessType) { + if (required) { + throw new Error('business_type 参数不能为空'); + } + return null; + } + if (!SUPPORTED_BUSINESS_TYPES.includes(normalizedBusinessType)) { + throw new Error(`business_type 参数非法,仅支持:${SUPPORTED_BUSINESS_TYPES.join('、')}`); + } + return normalizedBusinessType; + } + /** * 获取指定业务类型的模板列表 * @param {string} businessType 业务类型 * @return {Promise} 模板列表 */ async listTemplatesByType(businessType) { - console.log('获取业务类型模板列表, businessType:', businessType); - return await this.getTemplatesByType(businessType); + const normalizedBusinessType = this.normalizeAndValidateBusinessType(businessType); + return await this.getTemplatesByType(normalizedBusinessType); } /** @@ -25,12 +46,15 @@ class PrintTemplateService extends Service { try { // 1. 获取所有业务类型及打印项 const businessTypeItems = await this.getBusinessTypesAndItem(); - const businessTypes = Object.keys(businessTypeItems); + const businessTypes = SUPPORTED_BUSINESS_TYPES; // 2. 查询所有打印模板,按业务类型分组 const templates = await ctx.model.PrintTemplate.findAll({ where: { status: 'ACTIVE', + business_type: { + [Op.in]: SUPPORTED_BUSINESS_TYPES, + }, warehouse_id: { [Op.or]: [ warehouseId, null ], }, @@ -68,7 +92,7 @@ class PrintTemplateService extends Service { type: 'category', businessType, children, - printItems: businessTypeItems[businessType].groupList || [], + printItems: businessTypeItems[businessType] ? (businessTypeItems[businessType].groupList || []) : [], editable: false, deletable: false, isGeneral: false, @@ -90,14 +114,14 @@ class PrintTemplateService extends Service { async getTemplatesByType(businessType) { const { ctx, app } = this; const { Op } = app.Sequelize; + const normalizedBusinessType = this.normalizeAndValidateBusinessType(businessType); const warehouseId = ctx.user.store_id; - console.log(businessType, warehouseId); try { const templates = await ctx.model.PrintTemplate.findAll({ where: { status: 'ACTIVE', - business_type: businessType, + business_type: normalizedBusinessType, warehouse_id: { [Op.or]: [ warehouseId, null ], }, @@ -107,7 +131,6 @@ class PrintTemplateService extends Service { [ 'create_at', 'DESC' ], ], }); - console.log(`查询到${templates.length}个模板,businessType: ${businessType}, warehouseId: ${warehouseId}`); return templates.map(template => { const { warehouse_id } = template; return { @@ -122,12 +145,17 @@ class PrintTemplateService extends Service { return []; } } + + /** + * 保存打印模板(创建或更新) + * @param {Object} data 模板数据 + * @return {Promise} 保存结果 + */ async save(data) { - const { ctx, app } = this; - const { Op } = app.Sequelize; + const { ctx } = this; const warehouseId = ctx.user.store_id; - console.log('保存打印模板数据:', data); const { id, template_name, business_type, page_width, page_height, template_content } = data; + const normalizedBusinessType = this.normalizeAndValidateBusinessType(business_type, !id); try { if (id) { // 更新现有模板 @@ -142,20 +170,24 @@ class PrintTemplateService extends Service { throw new Error('模板不存在或无权限'); } - await template.update({ + const updatePayload = { template_name, - business_type, page_width, page_height, template_content, - }); + }; + if (normalizedBusinessType) { + updatePayload.business_type = normalizedBusinessType; + } + + await template.update(updatePayload); return { message: '模板更新成功', code: 200 }; } // 创建新模板 await ctx.model.PrintTemplate.create({ template_name, - business_type, + business_type: normalizedBusinessType, page_width, page_height, template_content, @@ -169,7 +201,150 @@ class PrintTemplateService extends Service { ctx.logger.error('保存打印模板失败:', error); throw new Error('保存打印模板失败'); } - }/** + } + + /** + * 创建打印模板 + * @param {Object} data 模板数据 + * @return {Promise} 创建结果 + */ + async createTemplate(data = {}) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const now = new Date(); + const { + template_name, + business_type, + page_width, + page_height, + template_content = [], + is_default = false, + } = data; + + if (!String(template_name || '').trim()) { + throw new Error('template_name 参数不能为空'); + } + + if (page_width === undefined || page_width === null || String(page_width).trim() === '') { + throw new Error('page_width 参数不能为空'); + } + + if (page_height === undefined || page_height === null || String(page_height).trim() === '') { + throw new Error('page_height 参数不能为空'); + } + + const normalizedBusinessType = this.normalizeAndValidateBusinessType(business_type); + const platform = 'default'; + const template_type = 'CUSTOM'; + const template_url = ''; + + const existingTemplate = await ctx.model.PrintTemplate.findOne({ + where: { + business_type: normalizedBusinessType, + platform, + template_type, + warehouse_id: warehouseId, + }, + order: [[ 'id', 'DESC' ]], + }); + + if (existingTemplate) { + if (existingTemplate.status === 'ACTIVE') { + throw new Error('同一业务类型和平台下已存在自定义模板'); + } + + await existingTemplate.update({ + template_name, + page_width, + page_height, + template_content, + template_url, + is_default, + status: 'ACTIVE', + delete_at: null, + update_at: now, + }); + + return { + message: '模板创建成功', + code: 200, + data: { + id: existingTemplate.id, + }, + }; + } + + let created; + try { + created = await ctx.model.PrintTemplate.create({ + template_name, + business_type: normalizedBusinessType, + page_width, + page_height, + template_content, + platform, + template_type, + template_url, + is_default, + warehouse_id: warehouseId, + status: 'ACTIVE', + create_at: now, + update_at: now, + delete_at: null, + }, { + validate: false, + }); + } catch (error) { + if (error?.name === 'SequelizeUniqueConstraintError') { + throw new Error('同一业务类型和平台下已存在自定义模板'); + } + const details = Array.isArray(error?.errors) + ? error.errors.map(item => `${item.path || 'unknown'}:${item.message}`).join(';') + : ''; + const errMsg = [ error?.name, error?.message, details ].filter(Boolean).join(' | '); + throw new Error(errMsg || '模板创建失败'); + } + + return { + message: '模板创建成功', + code: 200, + data: { + id: created.id, + }, + }; + } + + async deleteTemplate(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const template = await ctx.model.PrintTemplate.findOne({ + where: { + id, + warehouse_id: warehouseId, + status: 'ACTIVE', + }, + }); + + if (!template) { + throw new Error('模板不存在或无权限'); + } + + await template.update({ + status: 'DISABLED', + delete_at: new Date(), + update_at: new Date(), + }); + + return { + message: '模板删除成功', + code: 200, + data: { + id, + }, + }; + } + + /** * 获取所有业务类型(用于下拉选择)- 支持分组展示 * @return {Object} 业务类型及打印项列表,包含分组信息 */ @@ -447,11 +622,15 @@ class PrintTemplateService extends Service { layout += ``; } break; - case 'table': + case 'table': { const tableContent = this.renderTable(el, index); layout += `${tableContent}
    `; break; + } case 'shape': + break; + default: + break; } return `${layout} @@ -488,20 +667,28 @@ class PrintTemplateService extends Service { return styleText; } renderTable(el, index) { - const tableText = ''; - const rows = el.rows || []; - // 表头 - let headerTds = ''; - let bodyTds = '<% for(var i=0; i<(_data.items.length); i++) { %>'; - for (let i = 0; i < el.rows; i++) { + const rows = Array.isArray(el.rows) ? el.rows : []; + const fieldCode = String(el.field_code || '').trim(); - headerTds += `${el.headers && el.headers[i] ? el.headers[i] : `列${i + 1}`}`; - bodyTds += `]]>`; + if (!fieldCode || rows.length === 0) { + return ''; } + + let headerTds = ''; + let bodyTds = '<% const tableRows = Array.isArray(_data.items) ? _data.items : []; for (var rowIndex = 0; rowIndex < tableRows.length; rowIndex++) { %>'; + + for (let i = 0; i < rows.length; i++) { + const headerText = el.headers && el.headers[i] ? el.headers[i] : `列${i + 1}`; + headerTds += `${headerText}`; + bodyTds += `]]>`; + } + headerTds += ''; - bodyTds += '<%}%>'; + bodyTds += '<% } %>'; return headerTds + bodyTds; } + + } module.exports = PrintTemplateService; diff --git a/app/service/systems/setting/role.js b/app/service/systems/setting/role.js new file mode 100644 index 0000000..8292ff0 --- /dev/null +++ b/app/service/systems/setting/role.js @@ -0,0 +1,695 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingRoleService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作角色', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getEmployee(employeeId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + const where = { + id: employeeId, + store_id: storeId, + }; + if (!includeDisabled) { + where.status = 1; + } + + const employee = await ctx.model.AccountStoreEmployee.findOne({ where }); + if (!employee) { + throw this.createError('工号不存在或无权限操作', 404); + } + return employee; + } + + normalizeRoleIds(inputRoleIds) { + if (!Array.isArray(inputRoleIds) || inputRoleIds.length === 0) { + throw this.createError('role_ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of inputRoleIds) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('role_ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + + return Array.from(new Set(roleIds)); + } + + async findAssignableRoles(roleIds, storeId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const roles = await ctx.model.Role.findAll({ + where: { + id: roleIds, + status: 1, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + order: [[ 'id', 'ASC' ]], + }); + + if (roles.length !== roleIds.length) { + const foundRoleIds = roles.map(role => Number(role.id)); + const missingRoleIds = roleIds.filter(roleId => !foundRoleIds.includes(roleId)); + throw this.createError(`角色不存在、已禁用或超出当前主体范围:${missingRoleIds.join(',')}`, 400); + } + + return roles; + } + + async clearEmployeeCache(employee) { + const { service } = this.ctx; + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); + } + + async getCurrentEmployeeRoleIds() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const rows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: currentEmployeeId, + }, + attributes: [ 'role_id' ], + }); + + return Array.from(new Set(rows.map(item => Number(item.role_id)).filter(id => Number.isFinite(id) && id > 0))); + } + + collectDescendantRoleIds(roleRows, startRoleIds) { + const childrenMap = new Map(); + for (const row of roleRows) { + const parentId = Number(row.pid || 0); + if (!childrenMap.has(parentId)) { + childrenMap.set(parentId, []); + } + childrenMap.get(parentId).push(Number(row.id)); + } + + const visited = new Set(); + const stack = Array.from(startRoleIds); + while (stack.length > 0) { + const roleId = Number(stack.pop()); + if (!Number.isFinite(roleId) || roleId <= 0 || visited.has(roleId)) { + continue; + } + visited.add(roleId); + const children = childrenMap.get(roleId) || []; + for (const childId of children) { + if (!visited.has(childId)) { + stack.push(childId); + } + } + } + return visited; + } + + async buildRolePermissionMap(roleRows) { + const { service } = this.ctx; + const rows = Array.isArray(roleRows) ? roleRows : []; + const permissionMap = new Map(); + + for (const row of rows) { + const roleId = Number(row && row.id); + if (!Number.isFinite(roleId) || roleId <= 0) { + continue; + } + + const directPermissionIds = service.systems.auth.rolePermission.toApiPermissionIds(row.permissions); + permissionMap.set(roleId, directPermissionIds); + } + + return permissionMap; + } + + buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap = new Map()) { + const nodeMap = new Map(); + for (const row of roleRows) { + const roleId = Number(row.id); + nodeMap.set(roleId, { + role_id: roleId, + role_code: row.role_code || '', + role_name: row.role_name || '', + description: row.description || '', + role_type: Number(row.role_type), + scope: Number(row.scope), + is_system: Number(row.is_system), + status: Number(row.status), + store_id: row.store_id === null ? null : Number(row.store_id), + pid: Number(row.pid || 0), + selected: selectedRoleIdSet.has(roleId), + permission_ids: rolePermissionMap.get(roleId) || [], + children: [], + }); + } + + for (const node of nodeMap.values()) { + const parent = nodeMap.get(node.pid); + if (parent) { + parent.children.push(node); + } + } + + const sortNodes = nodes => { + nodes.sort((a, b) => a.role_id - b.role_id); + for (const item of nodes) { + if (item.children && item.children.length > 0) { + sortNodes(item.children); + } + } + }; + + const roots = Array.from(rootRoleIds) + .map(roleId => nodeMap.get(Number(roleId))) + .filter(Boolean); + sortNodes(roots); + return roots; + } + + normalizeStoreScope(storeId) { + if (storeId === null || storeId === undefined) { + return 0; + } + const num = Number(storeId); + if (!Number.isFinite(num) || num <= 0) { + return 0; + } + return num; + } + + isRoleVisibleInScope(role, currentRoleRows, currentStoreId, includeSystem) { + const roleStoreScope = this.normalizeStoreScope(role.store_id); + + // 当前主体角色默认可见 + if (roleStoreScope === currentStoreId) { + return true; + } + + // includeSystem=true 时,可见系统角色 + if (includeSystem && roleStoreScope === 0) { + return true; + } + + // 当前工号若本身处于系统角色域,至少允许看到系统角色,避免空树。 + const hasSystemCurrentRole = currentRoleRows + .some(item => this.normalizeStoreScope(item.store_id) === 0); + if (hasSystemCurrentRole && roleStoreScope === 0) { + return true; + } + + return false; + } + + normalizePermissionIds(inputPermissionIds) { + if (inputPermissionIds === '*') { + return [ '*' ]; + } + + if (typeof inputPermissionIds === 'string') { + const trimmed = inputPermissionIds.trim(); + if (!trimmed) { + throw this.createError('permission_ids 参数不能为空', 400); + } + if (trimmed === '*') { + return [ '*' ]; + } + + try { + const parsed = JSON.parse(trimmed); + return this.normalizePermissionIds(parsed); + } catch (_) { + if (trimmed.includes(',')) { + return this.normalizePermissionIds(trimmed.split(',')); + } + throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400); + } + } + + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + if (inputPermissionIds.some(item => typeof item === 'string' && item.trim() === '*')) { + return [ '*' ]; + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400); + } + permissionIds.push(Math.floor(normalized)); + } + + return Array.from(new Set(permissionIds)); + } + + normalizePid(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const pid = Number(value); + if (!Number.isFinite(pid) || pid < 0) { + throw this.createError('pid 参数不合法', 400); + } + return pid; + } + + async getManageableRole(roleId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + + const where = { + id: roleId, + store_id: storeId, + is_system: 0, + }; + if (!includeDisabled) { + where.status = 1; + } + + const role = await ctx.model.Role.findOne({ where }); + if (!role) { + throw this.createError('角色不存在、无权限操作或为系统预设角色', 404); + } + return role; + } + + async validatePermissionSet(permissionIds) { + const { ctx } = this; + if (!Array.isArray(permissionIds) || permissionIds.length === 0) { + return; + } + + if (permissionIds.includes('*')) { + return; + } + + const existingPermissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + raw: true, + }); + if (existingPermissions.length !== permissionIds.length) { + const found = new Set(existingPermissions.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(id)); + throw this.createError(`权限不存在或已禁用:${missing.join(',')}`, 400); + } + } + + async replaceRolePermissions(roleId, permissionIds, transaction) { + return await this.ctx.service.systems.auth.rolePermission.assignPermissions(roleId, permissionIds, { + transaction, + }); + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + const includeDisabled = data.includeDisabled === true; + const includeSystem = data.includeSystem === true; + const currentEmployeeId = this.getCurrentEmployeeId(); + + let employee = null; + if (currentEmployeeId) { + employee = await this.getEmployee(currentEmployeeId, { + includeDisabled: true, + }); + } + + // 先拉取当前主体 + 系统角色域,后续按可见规则二次收敛。 + const roleWhere = { + status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, + [Op.or]: [{ store_id: storeId }, { store_id: 0 }, { store_id: null }], + }; + + const roleRows = await ctx.model.Role.findAll({ + where: roleWhere, + attributes: [ + 'id', + 'role_code', + 'role_name', + 'description', + 'role_type', + 'scope', + 'is_system', + 'status', + 'store_id', + 'pid', + 'permissions', + ], + order: [ + [ 'is_system', 'DESC' ], + [ 'id', 'ASC' ], + ], + }); + + const currentRoleIds = await this.getCurrentEmployeeRoleIds(); + if (currentRoleIds.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const roleMap = new Map(roleRows.map(item => [ Number(item.id), item ])); + const currentRoleRows = currentRoleIds + .map(roleId => roleMap.get(roleId)) + .filter(Boolean); + + if (currentRoleRows.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id))); + + // 仅返回当前角色的下级角色树,不返回自己及同级角色。 + const subordinateRootRoleIds = new Set(roleRows + .filter(item => currentRoleIdSet.has(Number(item.pid || 0))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)) + .map(item => Number(item.id))); + + if (subordinateRootRoleIds.size === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const visibleRoleIds = this.collectDescendantRoleIds(roleRows, Array.from(subordinateRootRoleIds)); + + const visibleRoleRows = roleRows + .filter(item => visibleRoleIds.has(Number(item.id))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)); + const rootRoleIds = new Set(visibleRoleRows + .filter(item => subordinateRootRoleIds.has(Number(item.id))) + .map(item => Number(item.id))); + + let selectedRoleIdSet = new Set(); + if (employee) { + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employee.id, + }, + }); + selectedRoleIdSet = new Set(employeeRoles.map(item => Number(item.role_id))); + } + + const rolePermissionMap = await this.buildRolePermissionMap(visibleRoleRows); + const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap); + + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles, + }, + }; + } + + async permission(data = {}) { + return this.ctx.service.systems.setting.permission.list(data); + } + + async add(data = {}) { + const { ctx } = this; + + const storeId = this.getCurrentStoreId(); + const roleCode = typeof data.role_code === 'string' ? data.role_code.trim() : ''; + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + const description = typeof data.description === 'string' ? data.description.trim() : ''; + const roleType = Number(data.role_type || 1); + const scope = Number(data.scope || 1); + const status = data.status === 0 || data.status === '0' ? 0 : 1; + const pid = this.normalizePid(data.pid); + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + const creatorId = Number(this.ctx.user && this.ctx.user.id); + + if (!roleCode) { + throw this.createError('role_code 参数不能为空', 400); + } + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + if (!Number.isFinite(creatorId) || creatorId <= 0) { + throw this.createError('未识别到当前账号,无法创建角色', 400); + } + + await this.validatePermissionSet(permissionIds); + + const transaction = await ctx.model.transaction(); + let createdRole = null; + try { + createdRole = await ctx.model.Role.create({ + role_code: roleCode, + role_name: roleName, + description, + role_type: roleType, + scope, + is_system: 0, + status, + created_by: creatorId, + store_id: storeId, + pid, + }, { transaction }); + + await this.replaceRolePermissions(Number(createdRole.id), permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('role_code 已存在', 409); + } + throw error; + } + + return { + code: 200, + data: { + role_id: Number(createdRole.id), + role_code: createdRole.role_code, + role_name: createdRole.role_name, + permission_ids: permissionIds, + created: true, + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + + const roleIds = this.normalizeRoleIds(data.ids); + const roles = []; + for (const roleId of roleIds) { + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + roles.push(role); + } + + const deletedIds = []; + const alreadyDeletedIds = []; + + const transaction = await ctx.model.transaction(); + try { + for (const role of roles) { + const roleId = Number(role.id); + if (Number(role.status) === 0) { + alreadyDeletedIds.push(roleId); + continue; + } + + await role.update({ + status: 0, + updated_at: new Date(), + }, { transaction }); + deletedIds.push(roleId); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + for (const roleId of deletedIds) { + await this.clearRoleUsersCache(roleId); + } + + return { + code: 200, + data: { + ids: roleIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const { ctx } = this; + + const roleId = this.toPositiveNumber(data.role_id || data.roleId, 'role_id'); + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + + const hasRoleName = Object.prototype.hasOwnProperty.call(data, 'role_name'); + const hasDescription = Object.prototype.hasOwnProperty.call(data, 'description'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + const hasPid = Object.prototype.hasOwnProperty.call(data, 'pid'); + const hasPermissionIds = Object.prototype.hasOwnProperty.call(data, 'permission_ids') + || Object.prototype.hasOwnProperty.call(data, 'permissionIds'); + + if (!hasRoleName && !hasDescription && !hasStatus && !hasPid && !hasPermissionIds) { + throw this.createError('至少需要更新角色信息或 permission_ids', 400); + } + if (!hasPermissionIds) { + throw this.createError('permission_ids 参数不能为空,角色权限需一次性提交', 400); + } + + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + await this.validatePermissionSet(permissionIds); + + const updates = {}; + if (hasRoleName) { + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + updates.role_name = roleName; + } + if (hasDescription) { + updates.description = typeof data.description === 'string' ? data.description.trim() : ''; + } + if (hasStatus) { + const status = data.status === 0 || data.status === '0' ? 0 : 1; + updates.status = status; + } + if (hasPid) { + updates.pid = this.normalizePid(data.pid); + } + updates.updated_at = new Date(); + + const transaction = await ctx.model.transaction(); + try { + if (Object.keys(updates).length > 0) { + await role.update(updates, { transaction }); + } + + await this.replaceRolePermissions(roleId, permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('角色信息冲突(可能 role_code 重复)', 409); + } + throw error; + } + + await this.clearRoleUsersCache(roleId); + + return { + code: 200, + data: { + role_id: roleId, + role_name: role.role_name, + permission_ids: permissionIds, + }, + }; + } +} + +module.exports = SettingRoleService; diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js new file mode 100644 index 0000000..2609d04 --- /dev/null +++ b/app/service/systems/setting/store_warehouse.js @@ -0,0 +1,680 @@ +'use strict'; + +const crypto = require('node:crypto'); +const Service = require('egg').Service; + +const SIGN_TEMP_EXPIRE_SECONDS = 600; +const AUTH_STATUS_LABELS = Object.freeze({ + 1: '申请中', + 2: '已通过', + 3: '已拒绝', + 4: '已解除', + 5: '已过期', +}); + +class SettingStoreWarehouseService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作签约关系', 400); + } + return storeId; + } + + getCurrentAccountId() { + const accountId = Number(this.ctx.user && this.ctx.user.id); + if (!Number.isFinite(accountId) || accountId <= 0) { + throw this.createError('未识别到当前登录账号', 401); + } + return accountId; + } + + toPositiveNumber(value, fieldName, options = {}) { + const { allowEmpty = false } = options; + if (allowEmpty && (value === undefined || value === null || value === '')) { + return null; + } + + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.min(Math.floor(num), maxValue); + } + + normalizeStatusFlag(value, fieldName, defaultValue = null) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + normalizeAuthStatus(value) { + if (value === undefined || value === null || value === '') { + return null; + } + const num = Number(value); + if ([ 1, 2, 3, 4, 5 ].includes(num)) { + return num; + } + throw this.createError('auth_status 参数不合法', 400); + } + + normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.floor(num); + } + + normalizeText(value, fieldName, maxLength = 500) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeDate(value, fieldName, options = {}) { + const { allowNull = true } = options; + if (value === undefined || value === null || value === '') { + if (allowNull) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return date; + } + + normalizeSignAction(value) { + if (value === undefined || value === null || value === '') { + return ''; + } + + const action = String(value).trim(); + if ([ 'preview', 'confirm' ].includes(action)) { + return action; + } + throw this.createError('action 参数不合法', 400); + } + + normalizeTempCode(value) { + const code = String(value || '').trim().toUpperCase(); + if (!code) { + throw this.createError('temp_code 参数不能为空', 400); + } + return code; + } + + getTempCodeCacheKey(tempCode) { + return `store_warehouse:sign:${tempCode}`; + } + + createTempCode() { + return crypto.randomBytes(6).toString('hex').toUpperCase(); + } + + pickRemaskField(currentSubject) { + return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask'; + } + + resolveRemaskValue(data, currentSubject) { + const raw = data.remask !== undefined + ? data.remask + : (currentSubject && currentSubject.isWarehouse ? data.store_remask : data.warehouse_remask); + return this.normalizeText(raw, 'remask', 50); + } + + buildCurrentRemaskPatch(data, currentSubject) { + const remask = this.resolveRemaskValue(data, currentSubject); + if (remask === null) { + return {}; + } + + return { + [this.pickRemaskField(currentSubject)]: remask, + }; + } + + requireCurrentRemaskPatch(data, currentSubject) { + const patch = this.buildCurrentRemaskPatch(data, currentSubject); + if (!Object.keys(patch).length) { + throw this.createError('remask 参数不能为空', 400); + } + return patch; + } + + async saveTempSignPayload(payload) { + const now = Date.now(); + const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString(); + const tempCode = this.createTempCode(); + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { + ...payload, + expires_at: expiresAt, + }, SIGN_TEMP_EXPIRE_SECONDS); + return { + tempCode, + expiresAt, + expiresIn: SIGN_TEMP_EXPIRE_SECONDS, + }; + } + + async getTempSignPayload(tempCode) { + const normalizedCode = this.normalizeTempCode(tempCode); + const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode)); + if (!payload) { + throw this.createError('临时码无效或已过期', 404); + } + return { + tempCode: normalizedCode, + payload, + }; + } + + async clearTempSignPayload(tempCode) { + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + if (cacheRedis && cacheRedis.del) { + await cacheRedis.del(this.getTempCodeCacheKey(tempCode)); + return; + } + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1); + } + + buildTempSignView(tempCode, payload, currentSubject) { + const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]; + const currentSubjectId = Number(currentSubject && currentSubject.id); + const expiresAt = payload.expires_at || null; + const expiresMs = expiresAt ? new Date(expiresAt).getTime() : 0; + + return { + mode: 'preview', + temp_code: tempCode, + expires_at: expiresAt, + expires_in: expiresMs ? Math.max(0, Math.ceil((expiresMs - Date.now()) / 1000)) : 0, + is_participant: participantIds.includes(currentSubjectId), + can_confirm: currentSubjectId > 0 && currentSubjectId === Number(payload.counterparty_id || 0), + initiator: { + id: Number(payload.initiator_subject_id || 0), + role: payload.initiator_role || '', + name: payload.initiator_name || '', + }, + counterparty: { + id: Number(payload.counterparty_id || 0), + role: payload.counterparty_role || '', + name: payload.counterparty_name || '', + }, + sign_info: { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_start: payload.auth_start || null, + auth_end: payload.auth_end || null, + print_quantity: Number(payload.print_quantity || 0), + apply_reason: payload.apply_reason || '', + remask: payload.remask || '', + }, + }; + } + + async getCurrentSubject() { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const subject = await ctx.model.Store.findOne({ + where: { + id: storeId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!subject) { + throw this.createError('当前主体不存在', 404); + } + + return { + id: Number(subject.id), + company_name: subject.company_name || '', + project: subject.project || '', + isWarehouse: subject.project === 'warehouse', + status: Number(subject.status || 0), + }; + } + + async getCounterparty(counterpartyId, expectedRole) { + const { ctx } = this; + const counterparty = await ctx.model.Store.findOne({ + where: { + id: counterpartyId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!counterparty) { + throw this.createError('签约对象不存在', 404); + } + + const isWarehouse = counterparty.project === 'warehouse'; + if (expectedRole === 'warehouse' && !isWarehouse) { + throw this.createError('目标对象不是仓库主体,无法签约', 400); + } + if (expectedRole === 'store' && isWarehouse) { + throw this.createError('目标对象不是货主主体,无法签约', 400); + } + + return counterparty; + } + + buildListWhere(data, currentSubject) { + const where = {}; + + if (currentSubject.isWarehouse) { + where.warehouse_id = currentSubject.id; + } else { + where.store_id = currentSubject.id; + } + + const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true }); + if (relationId) { + where.id = relationId; + } + + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + if (currentSubject.isWarehouse) { + where.store_id = counterpartyId; + } else { + where.warehouse_id = counterpartyId; + } + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const rawUseStatus = data.use_status !== undefined ? data.use_status + : (data.warehouse_use_status !== undefined ? data.warehouse_use_status : data.store_use_status); + const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null); + if (useStatus !== null) { + if (currentSubject.isWarehouse) { + where.warehouse_use_status = useStatus; + } else { + where.store_use_status = useStatus; + } + } + + return where; + } + + getRelationIncludes() { + const { ctx } = this; + return [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + ]; + } + + resolvePairIds(data, currentSubject) { + const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id'; + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName); + + if (currentSubject.isWarehouse) { + return { + storeId: counterpartyId, + warehouseId: currentSubject.id, + counterpartyId, + }; + } + + return { + storeId: currentSubject.id, + warehouseId: counterpartyId, + counterpartyId, + }; + } + + serializeRelation(relation, currentSubject) { + const item = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : (relation || {}); + + const authStatus = Number(item.auth_status || 0); + const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse); + const counterparty = currentIsWarehouse ? item.store : item.warehouse; + const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); + const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : ''); + const counterpartyName = counterparty && counterparty.company_name ? counterparty.company_name : ''; + + let isAuthValid = false; + let remainingDays = 0; + if (authStatus === 2 && item.auth_start && item.auth_end) { + const now = Date.now(); + const start = new Date(item.auth_start).getTime(); + const end = new Date(item.auth_end).getTime(); + if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) { + isAuthValid = true; + remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24))); + } + } + + return { + id: Number(item.id || 0), + store_id: Number(item.store_id || 0), + store_name: storeName, + warehouse_id: Number(item.warehouse_id || 0), + warehouse_name: warehouseName, + counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0, + counterparty_name: counterpartyName, + current_subject_role: currentIsWarehouse ? 'warehouse' : 'store', + auth_status: authStatus, + auth_status_label: AUTH_STATUS_LABELS[authStatus] || '', + apply_reason: item.apply_reason || '', + review_comment: item.review_comment || '', + apply_time: item.apply_time || null, + review_time: item.review_time || null, + auth_start: item.auth_start || null, + auth_end: item.auth_end || null, + actual_end: item.actual_end || null, + print_quantity: Number(item.print_quantity || 0), + applied_by: item.applied_by ? Number(item.applied_by) : null, + reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, + ended_by: item.ended_by ? Number(item.ended_by) : null, + remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), + use_status: currentIsWarehouse + ? Number(item.warehouse_use_status || 0) + : Number(item.store_use_status || 0), + warehouse_use_status: Number(item.warehouse_use_status || 0), + store_use_status: Number(item.store_use_status || 0), + is_auth_valid: isAuthValid, + remaining_days: remainingDays, + }; + } + + async findScopedRelation(data, currentSubject, transaction) { + const { ctx } = this; + const where = currentSubject.isWarehouse + ? { warehouse_id: currentSubject.id } + : { store_id: currentSubject.id }; + + const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true }); + if (relationId) { + where.id = relationId; + } else { + const pair = this.resolvePairIds(data, currentSubject); + where.store_id = pair.storeId; + where.warehouse_id = pair.warehouseId; + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where, + include: this.getRelationIncludes(), + transaction, + }); + + if (!relation) { + throw this.createError('签约关系不存在或无权限操作', 404); + } + + return relation; + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + const where = this.buildListWhere(data, currentSubject); + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + + return { + code: 200, + data: { + list: rows.map(item => { + const serialized = this.serializeRelation(item, currentSubject); + return { + id: serialized.id, + store_id: serialized.store_id, + warehouse_id: serialized.warehouse_id, + counterparty_name: serialized.counterparty_name, + remask: serialized.remask, + use_status: serialized.use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + }; + }), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + async sign(data = {}) { + const action = this.normalizeSignAction(data.action || data.mode); + if (action === 'preview') { + const currentSubject = await this.getCurrentSubject(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + return { + code: 200, + data: { + mode: 'preview', + current_subject: { store_id: currentSubject.id, company_name: currentSubject.company_name, role: currentSubject.isWarehouse ? 'warehouse' : 'store' }, + counterparty: { id: Number(counterparty.id || 0), company_name: counterparty.company_name || '', role: currentSubject.isWarehouse ? 'store' : 'warehouse' }, + }, + }; + } + + const { ctx } = this; + const transaction = await ctx.model.transaction(); + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + if (authEnd && authStart.getTime() > authEnd.getTime()) throw this.createError('auth_end 不能早于 auth_start', 400); + + const relationPatch = { + store_id: pair.storeId, warehouse_id: pair.warehouseId, auth_status: 1, + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), + apply_time: new Date(), print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + review_time: null, auth_start: authStart, auth_end: authEnd, actual_end: null, + applied_by: accountId, reviewed_by: null, ended_by: null, initiator_subject_id: currentSubject.id, + warehouse_use_status: 1, store_use_status: 1, print_quantity_locked: 0, + }; + Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); + + let relation = await ctx.model.StoreWarehouse.findOne({ where: { store_id: pair.storeId, warehouse_id: pair.warehouseId }, transaction }); + const isCreate = !relation; + + if (relation) { + if (relation.applied_by === accountId && relation.auth_status === 1) { + await relation.update(relationPatch, { transaction }); + } else if (relation.applied_by === accountId && relation.auth_status >= 2) { + const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.rollback(); + return { code: 200, data: { mode: 'already_confirmed', exists_status: relation.auth_status, exists_status_label: '已签约', contract: this.trimContract(this.serializeRelation(existing, currentSubject)) } }; + } else { + const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.rollback(); + return { code: 200, data: { mode: 'already_exists', exists_status: relation.auth_status, exists_status_label: relation.auth_status === 2 ? '已签约' : '待确认', contract: this.trimContract(this.serializeRelation(existing, currentSubject)) } }; + } + } else { + relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); + } + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.commit(); + return { code: 200, data: { mode: 'initiate', contract: this.trimContract(this.serializeRelation(result, currentSubject)), action: isCreate ? 'create' : 'update' } }; + } catch (error) { await transaction.rollback(); throw error; } + } + + trimContract(serialized) { + return { id: serialized.id, store_id: serialized.store_id, warehouse_id: serialized.warehouse_id, counterparty_name: serialized.counterparty_name, remask: serialized.remask, use_status: serialized.use_status, auth_status: serialized.auth_status, auth_status_label: serialized.auth_status_label, auth_end: serialized.auth_end, print_quantity: serialized.print_quantity, has_qimen_config: serialized.has_qimen_config }; + } + + async confirmSign(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const relationId = this.toPositiveNumber(data.id, 'id'); + if (!relationId) throw this.createError('id 参数不能为空', 400); + const relation = await ctx.model.StoreWarehouse.findOne({ where: { id: relationId }, include: this.getRelationIncludes(), transaction }); + if (!relation) throw this.createError('签约关系不存在', 404); + if (relation.auth_status !== 1) throw this.createError('当前签约状态不允许确认,仅待签约状态可确认', 400); + const isCurrentStore = relation.store_id === currentSubject.id; + const isCurrentWarehouse = relation.warehouse_id === currentSubject.id; + if (!isCurrentStore && !isCurrentWarehouse) throw this.createError('当前主体不在此签约关系中', 403); + if (relation.initiator_subject_id === currentSubject.id) throw this.createError('发起方不能确认自己的签约申请', 403); + await relation.update({ auth_status: 2, review_time: new Date(), reviewed_by: accountId }, { transaction }); + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.commit(); + return { code: 200, data: { mode: 'confirm', contract: this.trimContract(this.serializeRelation(result, currentSubject)) } }; + } catch (error) { await transaction.rollback(); throw error; } + } + + async rename(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const relationPatch = this.requireCurrentRemaskPatch(data, currentSubject); + + await relation.update(relationPatch, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async unbind(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const nextUseStatus = this.normalizeStatusFlag( + data.use_status !== undefined ? data.use_status : data.warehouse_use_status, + 'warehouse_use_status', 0); + const patch = currentSubject.isWarehouse + ? { warehouse_use_status: nextUseStatus } + : { store_use_status: nextUseStatus }; + + await relation.update(patch, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } +} + +module.exports = SettingStoreWarehouseService; diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js new file mode 100644 index 0000000..7b38ee1 --- /dev/null +++ b/app/service/systems/setting/warehouse.js @@ -0,0 +1,934 @@ +'use strict'; + +const { Service } = require('egg'); + +const INTERNAL_WAVE_STRATEGY_VERSION_KEY = 'wave_strategy_version'; +const DEFAULT_WAVE_STRATEGY_VERSION = 1; +const DEFAULT_INVENTORY_WARNING_RULES = Object.freeze([ + Object.freeze({ name: '01级', key: '#ff4d4f', expire_days: 0, tip_text: '立即报废' }), + Object.freeze({ name: '02级', key: '#ff7a45', expire_days: 30, tip_text: '优先处理' }), + Object.freeze({ name: '03级', key: '#faad14', expire_days: 90, tip_text: '尽快处理' }), + Object.freeze({ name: '04级', key: '#fadb14', expire_days: 180, tip_text: '建议处理' }), + Object.freeze({ name: '05级', key: '#95de64', expire_days: 365, tip_text: '库存关注' }), + Object.freeze({ name: '06级', key: '#52c41a', expire_days: 999999, tip_text: '常规监控' }), +]); + +// 仓库设置字段元信息(对应 wms_store.subject_config) +const WAREHOUSE_SETTING_FIELDS = Object.freeze([ + Object.freeze({ + key: 'max_notice_webhook_count', + name: '最大通知 Webhook 次数', + type: 'integer', + default: 5, + required: false, + description: '单次事件最多触发的 Webhook 通知次数(0-5)', + min: 0, + max: 5, + }), + Object.freeze({ + key: 'max_wave_quantity', + name: '仓库波次最大数量限制', + type: 'integer', + default: 500, + required: false, + description: '控制单个波次允许的最大订单数量,默认 500', + min: 1, + }), + Object.freeze({ + key: 'min_group_order_fetch_quantity', + name: '最小团购订单抓取数量', + type: 'integer', + default: 13, + required: false, + description: '控制团购波次最小抓取订单数量,默认 13', + min: 1, + }), + Object.freeze({ + key: 'auto_grouping_enabled', + name: '自动加团开关', + type: 'flag', + default: false, + required: false, + description: '是否启用订单创建后自动加入团购波次,默认 false(关闭)', + }), + Object.freeze({ + key: 'auto_allocate_express_exclude_remarks', + name: '自动分配快递排除备注', + type: 'string_array', + default: [], + required: false, + description: '订单备注命中任一关键字时,跳过自动分配快递,默认 [](不排除任何订单)', + }), + Object.freeze({ + key: 'inbox_reply_exclude_keywords', + name: '排除快递回复关键词', + type: 'string_array', + default: [], + required: false, + description: '消息命中任一关键词时仅记录工单不发送回信通知,默认 [](正常回信)', + }), + Object.freeze({ + key: 'inbox_push_retry', + name: '站内信推送失败自动重发', + type: 'object', + default: Object.freeze({ + enabled: false, + window_minutes: 30, + }), + required: false, + description: '开启后,站内信回信/系统通知推送失败(如桥接离线返回 wx offline / qiwe offline)由定时任务每 3 分钟自动重发;仅重发失败时间在 window_minutes 内的消息,超出范围不再补发', + item_keys: Object.freeze([ + Object.freeze({ + key: 'enabled', + name: '启用自动重发', + type: 'flag', + default: false, + required: true, + description: '默认否,开启后定时任务才会自动重发推送失败的消息', + }), + Object.freeze({ + key: 'window_minutes', + name: '重发时间范围(分钟)', + type: 'integer', + default: 30, + required: false, + min: 1, + max: 1440, + description: '仅自动重发「失败时间在该范围内」的消息,单位:分钟,默认 30,范围 1-1440;仅在开关开启时生效', + }), + ]), + }), + Object.freeze({ + key: 'default_express_code', + name: '默认快递编码', + type: 'string', + default: 'STO', + required: false, + description: '仓库默认使用的快递编码', + maxLength: 50, + }), + Object.freeze({ + key: 'default_platform_code', + name: '默认平台编码', + type: 'string', + default: 'TB', + required: false, + description: '仓库默认使用的平台编码', + maxLength: 50, + }), + Object.freeze({ + key: 'sender_name', + name: '发件人姓名', + type: 'string', + default: '', + required: false, + description: '仓库默认发件人姓名', + maxLength: 50, + }), + Object.freeze({ + key: 'sender_tel', + name: '发件人电话', + type: 'string', + default: '', + required: false, + description: '仓库默认发件人联系电话', + maxLength: 20, + }), + Object.freeze({ + key: 'province_name', + name: '省份', + type: 'string', + default: '', + required: false, + description: '仓库默认发件省份', + maxLength: 50, + }), + Object.freeze({ + key: 'city_name', + name: '城市', + type: 'string', + default: '', + required: false, + description: '仓库默认发件城市', + maxLength: 50, + }), + Object.freeze({ + key: 'district_name', + name: '区/县', + type: 'string', + default: '', + required: false, + description: '仓库默认发件区/县', + maxLength: 50, + }), + Object.freeze({ + key: 'town_name', + name: '镇/街道', + type: 'string', + default: '', + required: false, + description: '仓库默认发件镇/街道', + maxLength: 50, + }), + Object.freeze({ + key: 'address', + name: '详细地址', + type: 'string', + default: '', + required: false, + description: '仓库默认发件详细地址', + maxLength: 200, + }), + Object.freeze({ + key: 'receiver_address', + name: '仓库收货地址', + type: 'string', + default: '', + required: false, + description: '仓库收货地址(退货/退件收件地址),一行文本', + maxLength: 500, + }), + Object.freeze({ + key: 'group_wave_prefix', + name: '团购波次前缀', + type: 'string', + default: 'B', + required: false, + description: '团购波次编号前缀,最多 5 个字符,默认 B', + maxLength: 5, + }), + Object.freeze({ + key: 'delete_order_wave_prefix', + name: '散单波次前缀', + type: 'string', + default: 'A', + required: false, + description: '散单波次编号前缀,最多 5 个字符,默认 A', + maxLength: 5, + }), + Object.freeze({ + key: 'inventory_warning_rules', + name: '库存预警配置', + type: 'array', + item_keys: [ + Object.freeze({ key: 'name', name: '名称', type: 'string', required: true, description: '预警等级名称' }), + Object.freeze({ key: 'key', name: '颜色标识', type: 'color', required: true, description: '预警颜色值' }), + Object.freeze({ key: 'expire_days', name: '过期天数', type: 'integer', required: true, description: '距过期天数阈值' }), + Object.freeze({ key: 'tip_text', name: '提示语', type: 'string', required: false, description: '预警提示文案' }), + ], + default: DEFAULT_INVENTORY_WARNING_RULES, + required: false, + description: '可配置多个库存预警项,每项包含 name、key、expire_days、tip_text', + }), + Object.freeze({ + key: 'auto_outbound_enabled', + name: '启用自动出库', + type: 'flag', + default: false, + required: false, + description: '是否启用自动出库,默认 false(关闭)。开启后按 auto_outbound_rules 中的规则扫描订单并自动标记出库', + }), + Object.freeze({ + key: 'auto_outbound_rules', + name: '自动出库规则', + type: 'array', + default: [], + required: false, + description: '自动出库规则数组,每项规则独立判断,订单满足任意一条规则即自动出库;空数组时不自动出库。规则前置条件固定为「已复核」(recheck_status=fin)+「已分配储位」(storage_status=fin),未复核订单一律不自动出库', + item_keys: Object.freeze([ + Object.freeze({ key: 'require_pack', name: '需已打包', type: 'flag', required: false, default: true, description: '是否要求已打包(pack_status=fin),默认 true' }), + Object.freeze({ key: 'require_weigh', name: '需已称重', type: 'flag', required: false, default: true, description: '是否要求已称重(weighing_weight>0),默认 true' }), + Object.freeze({ key: 'require_sync', name: '需已同步', type: 'flag', required: false, default: true, description: '是否要求已同步(sync_status=fin),默认 true' }), + Object.freeze({ key: 'exclude_same_day_outbound', name: '不出库当天订单', type: 'flag', required: false, default: true, description: '开启后,按订单复核时间所在日计算:复核时间在「允许当天出库最后时间」之后的订单,需等到该复核日的「放行时间」才自动出库;复核时间早于该最后时间、或为空的订单不受影响' }), + Object.freeze({ key: 'same_day_outbound_deadline_time', name: '允许当天出库最后时间', type: 'string', required: false, default: '06:00', maxLength: 5, min: '00:00', max: '23:59', description: '复核时间早于该时间的订单不受「不出库当天订单」影响,格式 HH:mm(当天内 00:00~23:59),不能大于放行时间。想表达「当天复核的订单全天不出库」时设为 00:00' }), + Object.freeze({ key: 'same_day_outbound_release_time', name: '放行时间', type: 'string', required: false, default: '22:00', maxLength: 5, min: '00:00', max: '47:59', description: '到达该时刻后,该复核日被限制的订单放行。格式 HH:mm,支持跨天 00:00~47:59(24:00 之后的数字表示次日,如 27:00 = 次日 03:00)。常用:23:59 = 当天不放、过了零点出库;27:00 = 到次日 03:00 才出库' }), + ]), + }), + Object.freeze({ + key: 'cutoff_order_enabled', + name: '启用截单', + type: 'flag', + default: 1, + required: false, + description: '启用后,订单创建时间早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),不再自动分配快递和储位,不再自动加团', + }), + Object.freeze({ + key: 'allocate_start_time', + name: '开始自动分配时间', + type: 'string', + default: '08:00', + required: false, + maxLength: 5, + min: '00:00', + max: '23:59', + description: '开始自动分配时间,格式 HH:mm,如 08:00;早于该时间的订单与超过截单时间行为一致,不自动分配快递和储位,不自动加团;晚于截单时间时截单时间视为次日', + }), + Object.freeze({ + key: 'day_start_time', + name: '自然日开始时间', + type: 'string', + default: '06:00', + required: false, + maxLength: 5, + min: '00:00', + max: '23:59', + description: '自然日开始时间(业务日分界点),格式 HH:mm,默认 06:00;今日统计窗口为 [该时间点, 次日该时间点),当前时间早于今日该时间点时窗口从昨日该时间点开始(昨日 06:00 后的订单视为今日)', + }), + Object.freeze({ + key: 'cutoff_order_time', + name: '截单时间', + type: 'string', + default: '18:00', + required: false, + maxLength: 5, + min: '00:00', + max: '23:59', + description: '截单时间,格式 HH:mm,如 18:00', + }), + Object.freeze({ + key: 'after_sale_followup_hours', + name: '售后跟进时间(h)', + type: 'object', + required: false, + description: '按售后类型+子类型设置跟进小时数。_default 为该类型默认值,具体子类型可覆盖', + item_keys: [ + Object.freeze({ key: 'order', name: '订单售后', type: 'object', required: false, description: '订单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'intercept', name: '拦截', type: 'integer', default: 4, min: 1, max: 720 }), + Object.freeze({ key: 'urge', name: '催件', type: 'integer', default: 4, min: 1, max: 720 }), + Object.freeze({ key: 'change_address', name: '改地址', type: 'integer', default: 8, min: 1, max: 720 }), + Object.freeze({ key: 'change_carrier', name: '换快递', type: 'integer', default: 8, min: 1, max: 720 }), + Object.freeze({ key: 'delivery_delay', name: '发货延迟', type: 'integer', default: 12, min: 1, max: 720 }), + Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'quality_issue', name: '质量问题', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'missing_item', name: '少发', type: 'integer', default: 24, min: 1, max: 720 }), + ], + }), + Object.freeze({ key: 'receiving', name: '收货单售后', type: 'object', required: false, description: '收货单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), + ], + }), + Object.freeze({ key: 'entry', name: '入库单售后', type: 'object', required: false, description: '入库单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), + ], + }), + Object.freeze({ key: 'stockout', name: '出库单售后', type: 'object', required: false, description: '出库单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'return_issue', name: '退货异常', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'shortage', name: '少发', type: 'integer', default: 48, min: 1, max: 720 }), + ], + }), + ], + default: Object.freeze({ + order: Object.freeze({ _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 }), + receiving: Object.freeze({ _default: 24, shortage: 48, damage: 48 }), + entry: Object.freeze({ _default: 24, shortage: 48, damage: 48 }), + stockout: Object.freeze({ _default: 24, return_issue: 48, shortage: 48 }), + }), + }), + Object.freeze({ + key: 'single_order_pack_max_minutes', + name: '散单打包最大时长(分钟)', + type: 'integer', + default: 3, + required: false, + description: '散单打包最大时长,单位:分钟,默认 3', + min: 1, + }), + Object.freeze({ + key: 'group_order_pack_max_minutes', + name: '团购打包最大时长(分钟)', + type: 'integer', + default: 40, + required: false, + description: '团购打包最大时长,单位:分钟,默认 40', + min: 1, + }), + Object.freeze({ + key: 'big_group_pack_coefficient', + name: '大团购打包系数', + type: 'number', + default: 3, + required: false, + description: '大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0', + min: 0.1, + }), + Object.freeze({ + key: 'single_weigh_require_pack', + name: '散单称重是否需要打包', + type: 'flag', + default: false, + required: false, + description: '开启后散单称重(订单波次范围 wave_scope 非 1 大团购 / 3 小团购)须处于打包中或已打包(pack_status=padding/fin);未打包或打包异常时拒绝称重并返回错误,默认 false(关闭)', + }), + Object.freeze({ + key: 'stock_warning_enabled', + name: '是否开启库存预警', + type: 'flag', + default: false, + required: false, + description: '开启后,库存数量低于预警数量时触发库存预警,默认 false(关闭)', + }), + Object.freeze({ + key: 'stock_warning_quantity', + name: '库存预警数量', + type: 'integer', + default: 0, + required: false, + description: '库存预警阈值:库存低于该数量时触发预警,默认 0,必须为非负整数', + min: 0, + }), + Object.freeze({ + key: 'stock_static_hours', + name: '商品进入静态时间(小时)', + type: 'number', + default: 168, + required: false, + description: '商品最后一个收/发流水时间超过该小时数即视为进入静态,默认 168 小时,必须大于 0', + min: 0.1, + }), + Object.freeze({ + key: 'return_unpack_max_record_minutes', + name: '拆包最大录制时长(分钟)', + type: 'integer', + default: 5, + required: false, + description: '拆包最大录制时长,单位:分钟,默认 5;超过上限时提交的结束时间自动截断为开始时间+上限', + min: 1, + }), + Object.freeze({ + key: 'default_location_id', + name: '默认库位', + type: 'location', + default: null, + required: false, + description: '仓库未指定库位入库/上架时使用的默认库位(库位ID)', + }), + Object.freeze({ + key: 'receiving_pending_inbound_notice', + name: '收货未入库提醒', + type: 'object', + default: Object.freeze({ + enabled: false, + notice_time: '08:30', + min_hours: 24, + max_hours: 48, + notice_template: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:', + store_notice_template: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:', + }), + required: false, + description: '开启后每天按提醒时间扫描「创建超过 min_hours 且不足 max_hours 仍未完成入库」的收货单,绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群', + item_keys: Object.freeze([ + Object.freeze({ + key: 'enabled', + name: '是否通知收货未入库', + type: 'flag', + default: false, + required: true, + description: '默认否,开启后定时任务才会执行提醒', + }), + Object.freeze({ + key: 'notice_time', + name: '提醒时间', + type: 'string', + default: '08:30', + required: false, + maxLength: 5, + min: '00:00', + max: '23:59', + description: '每日提醒时间,格式 HH:mm,默认 08:30', + }), + Object.freeze({ + key: 'min_hours', + name: '超时下限(小时)', + type: 'integer', + default: 24, + required: false, + min: 1, + description: '收货单创建时间距今超过该小时数才提醒,默认 24', + }), + Object.freeze({ + key: 'max_hours', + name: '超时上限(小时)', + type: 'integer', + default: 48, + required: false, + min: 1, + description: '收货单创建时间距今小于该小时数才提醒,超过则不再提醒,默认 48', + }), + Object.freeze({ + key: 'notice_template', + name: '通知短语(仓库/客服群)', + type: 'string', + default: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:', + required: false, + maxLength: 500, + description: '消息第一行短语,可插入变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名 / {store_id} 货主ID / {count} 单数 / {min_hours} / {max_hours} / {date} 提醒日期 / {numbers} 收货单号;短语后换行逐行列出明细,留空用默认短语', + }), + Object.freeze({ + key: 'store_notice_template', + name: '通知短语(货主群)', + type: 'string', + default: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:', + required: false, + maxLength: 500, + description: '推送给货主群的消息第一行短语,变量同 notice_template,留空用默认短语', + }), + ]), + }), + Object.freeze({ + key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, + name: '仓库波次策略版本号', + type: 'integer', + default: DEFAULT_WAVE_STRATEGY_VERSION, + required: false, + description: '内部字段:仓库波次策略版本号', + min: 0, + hidden: true, + internal: true, + }), +]); + +class SettingWarehouseService extends Service { + /** + * 读取默认快递与平台编码选项,查询失败时自动降级为空列表。 + * + * @return {Promise} 返回字段 key 到 options 的映射。 + */ + async getDefaultCodeFieldOptionsMap() { + const modelContainer = this.ctx && this.ctx.model ? this.ctx.model : (this.app && this.app.model ? this.app.model : {}); + const expressModel = modelContainer && modelContainer.Express; + const platformModel = modelContainer && modelContainer.Platform; + + const fetchOptions = async model => { + if (!model || typeof model.findAll !== 'function') { + return []; + } + + try { + const rows = await model.findAll({ + attributes: [ 'code', 'name' ], + order: [[ 'code', 'ASC' ]], + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows + .map(item => { + const code = item && item.code !== undefined && item.code !== null ? String(item.code) : ''; + if (!code) { + return null; + } + + const name = item && item.name !== undefined && item.name !== null ? String(item.name) : ''; + return { + value: code, + label: name || code, + }; + }) + .filter(Boolean); + } catch (_error) { + return []; + } + }; + + const [ expressOptions, platformOptions ] = await Promise.all([ + fetchOptions(expressModel), + fetchOptions(platformModel), + ]); + + return { + default_express_code: expressOptions, + default_platform_code: platformOptions, + }; + } + + /** + * 规范化仓库波次策略版本号,返回数字。 + * + * @param {number|string|null|undefined} value 原始版本号。 + * @param {Object} [options={}] 额外选项。 + * @param {boolean} [options.useDefaultWhenEmpty=false] 空值时是否使用默认值。 + * @return {number} 规范化后的版本号数字。 + * @throws {Error} 输入不合法时抛出,状态码 400。 + */ + normalizeWaveStrategyVersion(value, options = {}) { + const { useDefaultWhenEmpty = false } = options; + if (value === undefined || value === null || value === '') { + if (useDefaultWhenEmpty) { + return DEFAULT_WAVE_STRATEGY_VERSION; + } + throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400); + } + + if (typeof value === 'number') { + if (!Number.isSafeInteger(value) || value < 0) { + throw this.createError('subject_config.wave_strategy_version 必须是非负整数', 400); + } + return value; + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!/^\d+$/.test(trimmed)) { + throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400); + } + + const numericVersion = Number(trimmed); + if (!Number.isSafeInteger(numericVersion)) { + throw this.createError('subject_config.wave_strategy_version 超出安全整数范围', 400); + } + + return numericVersion; + } + + throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400); + } + + /** + * 规范化 subject_config 内部字段,确保内部字段落库时为数字。 + * + * @param {Object} subjectConfig 原始配置对象。 + * @return {Object} 规范化后的配置对象。 + */ + normalizeSubjectConfigInternalFields(subjectConfig) { + const nextConfig = { + ...(subjectConfig && typeof subjectConfig === 'object' && !Array.isArray(subjectConfig) ? subjectConfig : {}), + }; + + nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY] = this.normalizeWaveStrategyVersion( + nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY], + { useDefaultWhenEmpty: true } + ); + + return nextConfig; + } + + /** + * 对外响应时移除内部字段,避免暴露内部配置。 + * + * @param {Object} subjectConfig 配置对象。 + * @return {Object} 过滤后的配置对象。 + */ + sanitizeSubjectConfigForOutput(subjectConfig) { + const nextConfig = { + ...(subjectConfig && typeof subjectConfig === 'object' && !Array.isArray(subjectConfig) ? subjectConfig : {}), + }; + + delete nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY]; + return nextConfig; + } + + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 从 ctx.user.store_id 获取当前仓库 ID。 + * + * @return {number} 仓库 ID。 + * @throws {Error} 未识别到仓库时抛出,状态码 400。 + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createError('未识别到当前仓库,无法操作仓库设置', 400); + } + return warehouseId; + } + + /** + * 删除指定缓存键。 + * + * @param {string} cacheKey 缓存键。 + * @return {Promise} 无返回值。 + */ + async deleteCacheByKey(cacheKey) { + if (!cacheKey) { + return; + } + + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(cacheKey); + return; + } + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, null, 0); + } + } + + /** + * 清理指定仓库设置相关缓存。 + * + * @param {number|string} warehouseId 仓库 ID。 + * @return {Promise} 无返回值。 + */ + async clearWarehouseSettingCache(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return; + } + + const keys = [ + `delivery_order:store:${normalizedWarehouseId}:subject_config`, + `warehouse:${normalizedWarehouseId}store:${normalizedWarehouseId}:info`, + ]; + + await Promise.all(keys.map(key => this.deleteCacheByKey(key).catch(() => null))); + } + + /** + * 获取仓库设置字段元信息列表。 + * + * @return {Promise} 字段元信息数组(浅拷贝,含 options 拷贝)。 + */ + async getFieldMeta() { + const dynamicOptionsMap = await this.getDefaultCodeFieldOptionsMap(); + + return WAREHOUSE_SETTING_FIELDS + .filter(field => !field.internal && field.key !== INTERNAL_WAVE_STRATEGY_VERSION_KEY) + .map(field => ({ + key: field.key, + name: field.name, + type: field.type, + ...(field.item_keys !== undefined + ? { + item_keys: Array.isArray(field.item_keys) + ? field.item_keys.map(itemKey => (itemKey && typeof itemKey === 'object' ? { ...itemKey } : itemKey)) + : field.item_keys, + } + : {}), + default: field.default, + required: field.required, + description: field.description, + ...((Array.isArray(field.options) || Object.prototype.hasOwnProperty.call(dynamicOptionsMap, field.key)) + ? { + options: (Array.isArray(field.options) ? field.options.map(o => ({ ...o })) : (dynamicOptionsMap[field.key] || [])).map(o => ({ ...o })), + } + : {}), + ...(field.min !== undefined ? { min: field.min } : {}), + ...(field.max !== undefined ? { max: field.max } : {}), + ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}), + ...(field.hidden !== undefined ? { hidden: field.hidden } : {}), + ...(field.internal !== undefined ? { internal: field.internal } : {}), + })); + } + + /** + * 读取当前仓库的设置(wms_store.subject_config)。 + * + * @return {Promise} 包含 warehouse_id 与 subject_config 的对象。 + * @throws {Error} 仓库不存在时抛出,状态码 404。 + */ + async getSettings() { + const warehouseId = this.getCurrentWarehouseId(); + + const store = await this.ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + }); + + if (!store) { + throw this.createError('仓库不存在', 404); + } + + const normalizedSubjectConfig = this.normalizeSubjectConfigInternalFields(store.subject_config); + + return { + warehouse_id: warehouseId, + subject_config: this.sanitizeSubjectConfigForOutput(normalizedSubjectConfig), + }; + } + + /** + * 校验默认库位是否属于当前仓库。 + * + * 传入的 default_location_id 为库位ID(wms_location_space.id),仅当该库位 + * 属于当前仓库且未删除、已启用时才允许写入。 + * + * @param {*} locationIdValue 待校验的库位ID。 + * @param {number} warehouseId 当前仓库 ID。 + * @return {Promise} 无返回值。 + * @throws {Error} 库位ID非法或不属于当前仓库时抛出,状态码 400。 + */ + async validateDefaultLocation(locationIdValue, warehouseId) { + if (locationIdValue === undefined || locationIdValue === null || locationIdValue === '') { + return; + } + + const locationId = Number(locationIdValue); + if (!Number.isInteger(locationId) || locationId <= 0) { + throw this.createError('default_location_id 必须是正整数库位ID', 400); + } + + const locationModel = this.ctx && this.ctx.model && this.ctx.model.LocationSpace; + if (!locationModel || typeof locationModel.findOne !== 'function') { + return; + } + + const locationSpace = await locationModel.findOne({ + where: { + id: locationId, + warehouse_id: warehouseId, + is_enabled: true, + deleted_at: null, + }, + attributes: [ 'id' ], + }); + + if (!locationSpace) { + throw this.createError(`默认库位 ${locationId} 不属于当前仓库`, 400); + } + } + + /** + * 修改当前仓库设置并清理当前仓库缓存。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [data.subject_config] 仓库设置对象,支持部分字段更新。 + * @return {Promise} 更新后的仓库设置。 + */ + async saveSettings(data = {}) { + const warehouseId = this.getCurrentWarehouseId(); + const storeModel = this.ctx.model && this.ctx.model.Store; + + if (!storeModel || typeof storeModel.findByPk !== 'function') { + throw this.createError('Store model 不可用', 500); + } + + const store = await storeModel.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + }); + + if (!store) { + throw this.createError('仓库不存在', 404); + } + + const hasSubjectConfig = Object.prototype.hasOwnProperty.call(data || {}, 'subject_config'); + const nextPatch = hasSubjectConfig ? data.subject_config : null; + if (!nextPatch || typeof nextPatch !== 'object' || Array.isArray(nextPatch)) { + throw this.createError('subject_config 参数不能为空且必须是对象', 400); + } + + // 默认库位必须属于当前仓库(值为库位ID) + if (Object.prototype.hasOwnProperty.call(nextPatch, 'default_location_id')) { + await this.validateDefaultLocation(nextPatch.default_location_id, warehouseId); + } + + // 自动出库规则必须是数组(旧的对象结构已废弃):写路径显式报错,避免被静默重置为默认值 + if (Object.prototype.hasOwnProperty.call(nextPatch, 'auto_outbound_rules')) { + const rawAutoOutboundRules = nextPatch.auto_outbound_rules; + if (rawAutoOutboundRules !== undefined && rawAutoOutboundRules !== null && rawAutoOutboundRules !== '') { + let parsedAutoOutboundRules = rawAutoOutboundRules; + if (typeof parsedAutoOutboundRules === 'string') { + try { + parsedAutoOutboundRules = JSON.parse(parsedAutoOutboundRules); + } catch (error) { + parsedAutoOutboundRules = null; + } + } + if (!Array.isArray(parsedAutoOutboundRules)) { + throw this.createError( + 'subject_config.auto_outbound_rules 必须是数组(每项包含 require_pack/require_weigh/require_sync 等字段),旧对象结构已废弃,请重新配置', + 400 + ); + } + } + } + + const nextPatchForMerge = { + ...nextPatch, + }; + delete nextPatchForMerge[INTERNAL_WAVE_STRATEGY_VERSION_KEY]; + + const mergedConfig = { + ...(store.subject_config && typeof store.subject_config === 'object' ? store.subject_config : {}), + ...nextPatchForMerge, + }; + + const mergedConfigWithInternalDefaults = this.normalizeSubjectConfigInternalFields(mergedConfig); + + let normalizedConfig; + try { + normalizedConfig = typeof storeModel.normalizeSubjectConfig === 'function' + ? storeModel.normalizeSubjectConfig(mergedConfigWithInternalDefaults) + : mergedConfigWithInternalDefaults; + } catch (error) { + throw this.createError(error.message || 'subject_config 参数不合法', Number(error.code) || 400); + } + + await store.update({ + subject_config: normalizedConfig, + }); + + const cacheWarehouseId = warehouseId; + + await this.clearWarehouseSettingCache(cacheWarehouseId); + + return { + warehouse_id: warehouseId, + subject_config: this.sanitizeSubjectConfigForOutput(store.subject_config), + cache_cleared_warehouse_id: cacheWarehouseId, + }; + } + + /** + * 获取当前仓库启用的微信小程序授权配置(wms_wechat_app)。 + * + * 只拉取一条启用记录(is_enabled=1,按 id 升序取第一条),返回值为对象; + * 无可用记录时返回 null(接口 data 为空)。 + * 出于安全考虑不返回 authorizer_refresh_token 长期令牌。 + * + * @return {Promise} 微信小程序配置对象;无可用记录时 null。 + * @throws {Error} 未识别到当前仓库时抛出,状态码 400。 + */ + async getWechatApp() { + const warehouseId = this.getCurrentWarehouseId(); + + const wechatAppModel = this.ctx.model && this.ctx.model.WechatApp; + if (!wechatAppModel || typeof wechatAppModel.findOne !== 'function') { + throw this.createError('WechatApp model 不可用', 500); + } + + const record = await wechatAppModel.findOne({ + where: { + warehouse_id: warehouseId, + is_enabled: 1, + }, + order: [[ 'id', 'ASC' ]], + }); + + if (!record) { + return null; + } + + const plain = record.get ? record.get({ plain: true }) : record; + return { + id: plain.id, + warehouse_id: plain.warehouse_id, + appid: plain.appid, + nickname: plain.nickname, + user_name: plain.user_name, + head_img: plain.head_img, + auth_time: plain.auth_time, + func_info: plain.func_info, + is_enabled: plain.is_enabled, + created_at: plain.created_at, + updated_at: plain.updated_at, + }; + } +} + +module.exports = SettingWarehouseService; diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js new file mode 100644 index 0000000..87f440b --- /dev/null +++ b/app/service/systems/shops.js @@ -0,0 +1,761 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('node:crypto'); +const { + DELETED_SHOP_NAME_PREFIX, + buildNotDeletedShopWhere, +} = require('../../lib/shop_soft_delete'); + +/** + * 店铺业务服务。 + */ +class ShopsService extends Service { + /** + * 生成待授权占位店铺名并校验唯一性(最多重试 5 次)。 + * + * @param {Object} payload 入参 + * @param {number} payload.warehouseId 仓库 ID + * @param {string} payload.platformCode 平台编码 + * @return {Promise} 可用的占位店铺名 + */ + async generatePendingShopName(payload) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const { warehouseId, platformCode } = payload; + const maxRetryTimes = 5; + + for (let attempt = 1; attempt <= maxRetryTimes; attempt++) { + const shopName = `PENDING_${this.generateAuthorizeRandomCode()}`; + + const existed = await ctx.model.Shop.findOne({ + where: { + [Op.and]: [ + { + warehouse_id: warehouseId, + platform_code: platformCode, + shop_name: shopName, + }, + buildNotDeletedShopWhere(app), + ], + }, + attributes: [ 'id' ], + }); + + if (!existed) { + return shopName; + } + } + + throw this.createError('系统生成占位名冲突,请重试', 409); + } + + /** + * 创建业务错误。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库 ID。 + * + * @return {number} 仓库 ID + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createError('未识别到当前仓库', 400); + } + + return warehouseId; + } + + /** + * 规范化字符串参数。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名 + * @param {Object} [options={}] 选项 + * @param {boolean} [options.required=false] 是否必填 + * @param {number} [options.maxLength=255] 最大长度 + * @return {string|null} 规范化结果 + */ + normalizeText(value, fieldName, options = {}) { + const { required = false, maxLength = 255 } = options; + + if (value === undefined || value === null) { + if (required) { + throw this.createError(`${fieldName} 不能为空`, 400); + } + return null; + } + + const normalized = String(value).trim(); + + if (!normalized) { + if (required) { + throw this.createError(`${fieldName} 不能为空`, 400); + } + return null; + } + + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + + return normalized; + } + + /** + * 规范化整数参数。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名 + * @param {Object} [options={}] 选项 + * @param {boolean} [options.required=false] 是否必填 + * @param {number|null} [options.min=null] 最小值 + * @return {number|null} 规范化结果 + */ + normalizeInteger(value, fieldName, options = {}) { + const { required = false, min = null } = options; + + if (value === undefined || value === null || value === '') { + if (required) { + throw this.createError(`${fieldName} 不能为空`, 400); + } + return null; + } + + const normalized = Number(value); + + if (!Number.isInteger(normalized)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + if (min !== null && normalized < min) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + return normalized; + } + + /** + * 校验并标准化平台编码。 + * + * @param {*} platformCode 原始平台编码 + * @return {Promise} 标准化平台编码 + */ + async ensureShopPrintPlatformExists(platformCode) { + const normalizedPlatformCode = this.normalizeText(platformCode, 'platform_code', { + required: true, + maxLength: 50, + }).toUpperCase(); + + const printPlatform = await this.ctx.model.PrintPlatform.findOne({ + where: { + platform_code: normalizedPlatformCode, + deleted: 0, + status: 'ACTIVE', + }, + attributes: [ 'platform_code', 'platform_name', 'auth_base_url' ], + }); + + if (!printPlatform) { + throw this.createError('platform_code 未匹配到打印平台编码', 400); + } + + return normalizedPlatformCode; + } + + /** + * 获取店铺列表字段过滤映射。 + * + * @return {Object} specialFieldMap 映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { field: 'id' }, + platform_code: { field: 'platform_code' }, + custom_name: { field: 'custom_name' }, + shop_name: { field: 'shop_name' }, + status: { field: 'status' }, + quickWhere: { bucket: 'quick' }, + }; + } + + /** + * 构建店铺列表查询条件。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 查询 where + */ + async buildListWhere(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const parsedResult = ctx.whereParsed || { + dynamicConditions: [], + rawConditionsByField: {}, + }; + const whereAndConditions = [ + { + warehouse_id: this.getCurrentWarehouseId(), + }, + buildNotDeletedShopWhere(app), + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) + ? parsedResult.dynamicConditions + : []; + + if (dynamicConditions.length > 0) { + whereAndConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereCondition = parsedResult.rawConditionsByField + ? parsedResult.rawConditionsByField.quickWhere + : null; + const quickWhereValue = quickWhereCondition && typeof quickWhereCondition === 'object' + ? quickWhereCondition.value + : null; + const keyword = String(quickWhereValue || '').trim(); + + if (keyword) { + whereAndConditions.push({ + [Op.or]: [ + { shop_name: { [Op.like]: `%${keyword}%` } }, + { custom_name: { [Op.like]: `%${keyword}%` } }, + { platform_code: { [Op.like]: `%${keyword.toUpperCase()}%` } }, + ], + }); + } + + const normalizedPlatformCode = data.platform_code !== undefined + ? String(data.platform_code || '').trim() + : String(data.platformCode || '').trim(); + + if (normalizedPlatformCode) { + whereAndConditions.push({ + platform_code: await this.ensureShopPrintPlatformExists(normalizedPlatformCode), + }); + } + + return { + [Op.and]: whereAndConditions, + }; + } + + /** + * 规范化分页参数。 + * + * @param {Object} [data={}] 请求参数 + * @return {{page:number,pageSize:number,offset:number}} 分页信息 + */ + normalizePagination(data = {}) { + const pagination = data && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : (data.page !== undefined ? data.page : data.currentPage); + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.pageSize !== undefined ? data.pageSize : data.page_size)); + + const page = Math.max(Number.parseInt(pageSource, 10) || 1, 1); + const pageSize = Math.min(Math.max(Number.parseInt(pageSizeSource, 10) || 20, 1), 200); + + return { + page, + pageSize, + offset: (page - 1) * pageSize, + }; + } + + /** + * 构建店铺关联打印平台查询。 + * + * @return {Array} include 查询配置 + */ + buildShopPrintPlatformInclude() { + return [{ + model: this.ctx.model.PrintPlatform, + as: 'printPlatform', + required: false, + attributes: [ 'platform_code', 'platform_name', 'status' ], + where: { + deleted: 0, + status: 'ACTIVE', + }, + }]; + } + + /** + * 规范化店铺列表输出。 + * + * @param {Object} shopRow 店铺记录 + * @return {Object} 输出结构 + */ + formatShopRow(shopRow) { + const printPlatform = shopRow && typeof shopRow.printPlatform === 'object' + ? shopRow.printPlatform + : null; + + return { + id: shopRow.id, + warehouse_id: shopRow.warehouse_id, + platform_code: shopRow.platform_code, + platform_name: printPlatform ? printPlatform.platform_name || '' : '', + shop_name: shopRow.shop_name, + custom_name: shopRow.custom_name, + status: shopRow.status, + auth_expire_at: shopRow.auth_expire_at, + access_token: shopRow.access_token, + created_at: shopRow.created_at, + updated_at: shopRow.updated_at, + }; + } + + /** + * 查询店铺分页列表。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { ctx } = this; + const { page, pageSize, offset } = this.normalizePagination(data); + const where = await this.buildListWhere(data); + + const result = await ctx.model.Shop.findAndCountAll({ + where, + include: this.buildShopPrintPlatformInclude(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + }); + + const rows = Array.isArray(result && result.rows) ? result.rows : []; + const list = rows.map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row)) + .map(row => this.formatShopRow(row)); + const total = Number(result && result.count ? result.count : 0); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: pageSize > 0 ? Math.ceil(total / pageSize) : 0, + hasNext: page * pageSize < total, + hasPrevious: page > 1, + }, + }; + } + + /** + * 校验店铺名唯一性。 + * + * @param {Object} payload 入参 + * @param {number} payload.warehouseId 仓库 ID + * @param {string} payload.platformCode 平台编码 + * @param {string} payload.shopName 店铺名 + * @param {number|null} [payload.excludeId=null] 排除店铺 ID + * @return {Promise} 无返回 + */ + async ensureShopNameUnique(payload) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const { warehouseId, platformCode, shopName, excludeId = null } = payload; + const where = { + warehouse_id: warehouseId, + platform_code: platformCode, + shop_name: { + [Op.eq]: shopName, + [Op.notLike]: `${DELETED_SHOP_NAME_PREFIX}%`, + }, + }; + + if (excludeId !== null) { + where.id = { [Op.ne]: excludeId }; + } + + const existed = await ctx.model.Shop.findOne({ where, attributes: [ 'id' ] }); + + if (existed) { + throw this.createError('同仓同平台下 shop_name 已存在', 409); + } + } + + /** + * 新增店铺。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 新增结果 + */ + async add(data = {}) { + const { ctx } = this; + const warehouseId = this.getCurrentWarehouseId(); + const platformCode = await this.ensureShopPrintPlatformExists(data.platform_code !== undefined ? data.platform_code : data.platformCode); + const customName = this.normalizeText(data.custom_name !== undefined ? data.custom_name : data.customName, 'custom_name', { + required: true, + maxLength: 100, + }); + const shopName = await this.generatePendingShopName({ + warehouseId, + platformCode, + }); + + const created = await ctx.model.Shop.create({ + warehouse_id: warehouseId, + platform_code: platformCode, + shop_name: shopName, + custom_name: customName, + status: 0, + auth_expire_at: null, + auth_random_code: null, + owner_id: null, + access_token: null, + refresh_token: null, + token_expires_at: null, + refresh_token_expires_at: null, + scope: null, + }); + + const plainRow = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + + return { + id: plainRow.id, + }; + } + + /** + * 读取店铺并校验仓库归属。 + * + * @param {*} shopId 店铺 ID + * @param {Object} [options={}] 选项 + * @param {boolean} [options.allowDeleted=false] 是否允许读取已软删除店铺 + * @return {Promise} 店铺模型实例 + */ + async findShopById(shopId, options = {}) { + const { app, ctx } = this; + const { allowDeleted = false } = options; + const where = { + id: this.normalizeInteger(shopId, 'shop_id', { required: true, min: 1 }), + warehouse_id: this.getCurrentWarehouseId(), + }; + + if (!allowDeleted) { + Object.assign(where, buildNotDeletedShopWhere(app)); + } + + const shop = await ctx.model.Shop.findOne({ where }); + + if (!shop) { + throw this.createError('店铺不存在', 404); + } + + return shop; + } + + /** + * 软删除店铺。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 删除结果 + */ + async del(data = {}) { + const { ctx } = this; + const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId); + const shop = await this.findShopById(shopId); + const normalizedShopId = Number(shop.id); + const expressInterfaceCount = await ctx.model.ExpressInterface.count({ + where: { + warehouse_id: this.getCurrentWarehouseId(), + shop_id: normalizedShopId, + }, + }); + + if (expressInterfaceCount > 0) { + throw this.createError( + `该店铺已被 ${expressInterfaceCount} 个快递接口引用,请先解除绑定后再删除`, + 409 + ); + } + + const deletedSuffix = `${Date.now()}_${crypto.randomBytes(4).toString('hex')}`; + + await shop.update({ + shop_name: `${DELETED_SHOP_NAME_PREFIX}${normalizedShopId}_${deletedSuffix}`, + custom_name: null, + status: 0, + auth_expire_at: null, + auth_random_code: null, + owner_id: null, + access_token: null, + refresh_token: null, + token_expires_at: null, + refresh_token_expires_at: null, + scope: null, + }, { + fields: [ + 'shop_name', + 'custom_name', + 'status', + 'auth_expire_at', + 'auth_random_code', + 'owner_id', + 'access_token', + 'refresh_token', + 'token_expires_at', + 'refresh_token_expires_at', + 'scope', + ], + }); + + return { + deleted: true, + id: normalizedShopId, + }; + } + + /** + * 编辑店铺。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 编辑结果 + */ + async edit(data = {}) { + const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId); + const shop = await this.findShopById(shopId); + const updates = {}; + + const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code') + || Object.prototype.hasOwnProperty.call(data, 'platformCode'); + const hasCustomName = Object.prototype.hasOwnProperty.call(data, 'custom_name') + || Object.prototype.hasOwnProperty.call(data, 'customName'); + const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name') + || Object.prototype.hasOwnProperty.call(data, 'shopName'); + + if (!hasPlatformCode && !hasCustomName && !hasShopName) { + throw this.createError('仅允许修改 platform_code、custom_name 或 shop_name', 400); + } + + if (hasPlatformCode) { + updates.platform_code = await this.ensureShopPrintPlatformExists( + data.platform_code !== undefined ? data.platform_code : data.platformCode + ); + } + + if (hasCustomName) { + updates.custom_name = this.normalizeText( + data.custom_name !== undefined ? data.custom_name : data.customName, + 'custom_name', + { required: true, maxLength: 100 } + ); + } + + if (hasShopName) { + updates.shop_name = this.normalizeText( + data.shop_name !== undefined ? data.shop_name : data.shopName, + 'shop_name', + { required: true, maxLength: 100 } + ); + } + + const nextPlatformCode = updates.platform_code || shop.platform_code; + const nextShopName = updates.shop_name || shop.shop_name; + + await this.ensureShopNameUnique({ + warehouseId: this.getCurrentWarehouseId(), + platformCode: nextPlatformCode, + shopName: nextShopName, + excludeId: Number(shop.id), + }); + + await shop.update(updates, { + fields: Object.keys(updates), + }); + + return { + updated: true, + id: Number(shop.id), + }; + } + + /** + * 生成平台授权预占码。 + * + * @return {string} 预占码 + */ + generateAuthorizeRandomCode() { + return crypto.randomBytes(24).toString('hex'); + } + + /** + * 创建或复用授权预占店铺。 + * + * @param {Object} payload 参数 + * @param {number} payload.warehouseId 仓库 ID + * @param {string} payload.platformCode 平台编码 + * @return {Promise<{shop:Object,authRandomCode:string}>} 预占结果 + */ + async createOrReuseAuthorizeReservation(payload) { + const { ctx, app } = this; + const { warehouseId, platformCode } = payload; + + const pendingShop = await ctx.model.Shop.findOne({ + where: { + warehouse_id: warehouseId, + platform_code: platformCode, + status: 0, + ...buildNotDeletedShopWhere(app), + }, + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + if (pendingShop && String(pendingShop.auth_random_code || '').trim()) { + return { + shop: pendingShop, + authRandomCode: String(pendingShop.auth_random_code).trim(), + }; + } + + const maxRetryCount = 5; + + for (let retryIndex = 0; retryIndex < maxRetryCount; retryIndex++) { + const authRandomCode = this.generateAuthorizeRandomCode(); + + try { + if (pendingShop) { + pendingShop.auth_random_code = authRandomCode; + await pendingShop.save({ fields: [ 'auth_random_code' ] }); + + return { + shop: pendingShop, + authRandomCode, + }; + } + + const createdShop = await ctx.model.Shop.create({ + warehouse_id: warehouseId, + platform_code: platformCode, + shop_name: `PENDING_${authRandomCode}`, + custom_name: null, + status: 0, + auth_expire_at: null, + auth_random_code: authRandomCode, + owner_id: null, + access_token: null, + refresh_token: null, + token_expires_at: null, + refresh_token_expires_at: null, + scope: null, + }); + + return { + shop: createdShop, + authRandomCode, + }; + } catch (error) { + const isUniqueConflict = error && error.name === 'SequelizeUniqueConstraintError'; + + if (isUniqueConflict && retryIndex < maxRetryCount - 1) { + continue; + } + + if (isUniqueConflict) { + throw this.createError('生成唯一授权码失败,请稍后重试', 500); + } + + throw error; + } + } + + throw this.createError('生成唯一授权码失败,请稍后重试', 500); + } + + /** + * 获取店铺授权会话。 + * + * @param {Object} [data={}] 请求参数 + * @return {Promise} 会话信息 + */ + async getAuthorizeSessionKey(data = {}) { + const { ctx } = this; + const authUrl = 'http://61.160.223.183:3012/api'; + + const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId); + const appId = data.appId || ''; + const toUserName = data.toUserName || ''; + const shop = await this.findShopById(shopId, { allowDeleted: false }); + const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop; + const platformCode = await this.ensureShopPrintPlatformExists(shopPlain.platform_code); + // 获取wms_print_platform.platid和request_platform_code + const printPlatform = await ctx.model.PrintPlatform.findOne({ + where: { + platform_code: platformCode, + deleted: 0, + status: 'ACTIVE', + }, + attributes: [ 'get_auth_platform_name' ], + }); + + const platName = printPlatform ? printPlatform.get_auth_platform_name : platformCode; + // 视频号授权不依赖回调地址,允许 callbackurl 为空;其他平台仍必填 + const callbackUrl = this.normalizeText( + data.callbackurl !== undefined ? data.callbackurl : data.callback_url, + 'callbackurl', + { required: platName !== '视频号', maxLength: 500 } + ); + const requestData = { + RedirectCodeUrl: callbackUrl, + command: 'saveShop', + platName, + shopName: shopPlain.shop_name, + }; + if (platName === '电商京东') { + requestData.VenderID = shopPlain.id; + } + if (platName === '视频号') { + if (!appId || !toUserName) { + throw this.createError('视频号授权需要提供 appId 和 toUserName', 400); + } + requestData.appId = appId; + requestData.toUserName = toUserName; + delete requestData.RedirectCodeUrl; + } + // 缓存最后一次授权查询请求数据,便于排查问题 + await this.app.setCacheAsync('last_query_auth_polo', JSON.stringify(requestData), 3600); + + const respone = await ctx.curl(authUrl, { + method: 'POST', + dataType: 'json', + timeout: 15000, + data: requestData, + }); + await this.app.setCacheAsync('last_respone_auth_polo', JSON.stringify(respone), 3600); + if (respone.data && respone.data.code === 0) { + const sessionKey = respone.data.data || null; + if (sessionKey) { + await shop.update({ + access_token: sessionKey, + status: 1, + }, { + fields: [ 'access_token', 'status' ], + }); + return { message: '获取授权成功' }; + } + throw this.createError('获取授权失败,未返回 sessionKey', 500); + + } + throw this.createError(`获取授权失败:${respone.data ? respone.data.msg : '接口请求异常'}`, 500); + } +} + +module.exports = ShopsService; diff --git a/app/service/systems/sign.js b/app/service/systems/sign.js index 2fecd2d..32667b6 100644 --- a/app/service/systems/sign.js +++ b/app/service/systems/sign.js @@ -158,8 +158,9 @@ class SignService extends Service { /** * HMAC MD5加密 - * @param data - * @param secret + * @param {string} data 待签名内容 + * @param {string} secret 签名密钥 + * @return {Buffer} 加密结果 */ encryptHMAC(data, secret) { const hmac = crypto.createHmac('md5', secret); @@ -169,8 +170,9 @@ class SignService extends Service { /** * HMAC SHA256加密 - * @param data - * @param secret + * @param {string} data 待签名内容 + * @param {string} secret 签名密钥 + * @return {Buffer} 加密结果 */ encryptHMACSHA256(data, secret) { const hmac = crypto.createHmac('sha256', secret); @@ -180,7 +182,8 @@ class SignService extends Service { /** * MD5加密 - * @param data + * @param {string} data 待签名内容 + * @return {Buffer} 加密结果 */ encryptMD5(data) { return crypto.createHash('md5').update(data, 'utf8').digest(); @@ -188,7 +191,8 @@ class SignService extends Service { /** * 二进制转十六进制字符串(大写) - * @param bytes + * @param {Buffer} bytes 二进制数据 + * @return {string} 十六进制字符串 */ byte2hex(bytes) { return Buffer.from(bytes).toString('hex').toUpperCase(); diff --git a/app/service/systems/sn_code_rule.js b/app/service/systems/sn_code_rule.js new file mode 100644 index 0000000..750bd0a --- /dev/null +++ b/app/service/systems/sn_code_rule.js @@ -0,0 +1,235 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 单条 SN 码规则的匹配位置:前缀 */ +const MATCH_TYPE_PREFIX = 'prefix'; +/** 单条 SN 码规则的匹配位置:后缀 */ +const MATCH_TYPE_SUFFIX = 'suffix'; +/** 单条 SN 码规则的处理方式:整个扫码内容作为 SN 码 */ +const KEEP_MODE_FULL = 'full'; +/** 单条 SN 码规则的处理方式:去掉匹配到的前缀/后缀后作为 SN 码 */ +const KEEP_MODE_STRIP = 'strip'; + +const MATCH_TYPE_SET = new Set([ MATCH_TYPE_PREFIX, MATCH_TYPE_SUFFIX ]); +const KEEP_MODE_SET = new Set([ KEEP_MODE_FULL, KEEP_MODE_STRIP ]); +/** 单个商品最多可配置的 SN 码规则条数 */ +const MAX_RULE_COUNT = 20; +/** 前缀/后缀字符串最大长度 */ +const MAX_MATCH_VALUE_LENGTH = 64; +/** 扫码内容(用于匹配校验)最大长度,与 wms_order_item_sn.sn_code 的 VARCHAR(512) 对齐 */ +const MAX_SN_CODE_LENGTH = 512; + +/** + * 商品 SN 码规则服务。 + * + * 规则用于把「扫到的码」加工成真正入库的 SN 码,一条规则三步: + * 1. match_type:匹配位置,prefix=前缀 / suffix=后缀; + * 2. match_value:要匹配的前缀或后缀字符串; + * 3. keep_mode:full=整个扫码内容作为 SN 码 / strip=去掉匹配到的前缀或后缀后再作为 SN 码。 + * + * 存储形如: + * [{ "match_type": "prefix", "match_value": "YGP", "keep_mode": "strip" }] + * 多条规则按数组顺序匹配,命中第一条即生效。 + */ +class SnCodeRuleService extends Service { + /** + * 推断单条规则字段在其它调用处的可用性(供外部判断常量使用)。 + * @return {Object} 规则常量。 + */ + getConstants() { + return { + matchTypes: [ MATCH_TYPE_PREFIX, MATCH_TYPE_SUFFIX ], + keepModes: [ KEEP_MODE_FULL, KEEP_MODE_STRIP ], + maxRuleCount: MAX_RULE_COUNT, + maxMatchValueLength: MAX_MATCH_VALUE_LENGTH, + }; + } + + /** + * 把任意来源的规则内容解析为数组(不做元素合法性校验)。 + * 兼容 JSON 字符串、数组、null/undefined;其它类型抛错。 + * + * @param {*} rawRules 原始规则内容。 + * @return {Object[]} 规则数组(未逐条校验)。 + */ + parseRules(rawRules) { + if (rawRules === undefined || rawRules === null) { + return []; + } + if (Array.isArray(rawRules)) { + return rawRules; + } + if (typeof rawRules === 'string') { + const text = rawRules.trim(); + if (!text) { + return []; + } + let parsed; + try { + parsed = JSON.parse(text); + } catch { + throw new Error('SN码规则格式不正确,必须是合法的 JSON 数组'); + } + if (!Array.isArray(parsed)) { + throw new Error('SN码规则格式不正确,必须是数组'); + } + return parsed; + } + throw new Error('SN码规则格式不正确,必须是数组'); + } + + /** + * 读取并校验规则;非法内容返回空数组,用于查询回显(不抛错)。 + * + * @param {*} rawRules 原始规则内容(数据库列值)。 + * @return {Object[]} 规范化后的规则数组。 + */ + toRuleList(rawRules) { + try { + return this.normalizeRules(rawRules); + } catch { + return []; + } + } + + /** + * 校验并规范化保存入参中的 SN 码规则。 + * + * @param {*} rawRules 前端传入的规则(数组或 JSON 字符串),支持 match_type/matchType 等写法。 + * @return {Object[]} 规范化后的规则数组:{ match_type, match_value, keep_mode }。 + */ + normalizeRules(rawRules) { + const parsed = this.parseRules(rawRules); + if (parsed.length > MAX_RULE_COUNT) { + throw new Error(`SN码规则最多配置${MAX_RULE_COUNT}条`); + } + + const normalized = []; + const seenKeys = new Set(); + + parsed.forEach((rawRule, index) => { + const position = index + 1; + const rule = this.isPlainObject(rawRule) ? rawRule : null; + if (!rule) { + throw new Error(`第${position}条SN码规则格式不正确,必须是对象`); + } + + const matchType = this.normalizeMatchType(rule.match_type ?? rule.matchType ?? rule.type); + if (!matchType) { + throw new Error(`第${position}条SN码规则的匹配位置(match_type)只能是 prefix(前缀)或 suffix(后缀)`); + } + + const matchValue = this.normalizeMatchValue(rule.match_value ?? rule.matchValue ?? rule.value); + if (!matchValue) { + throw new Error(`第${position}条SN码规则的匹配内容(match_value)不能为空`); + } + if (matchValue.length > MAX_MATCH_VALUE_LENGTH) { + throw new Error(`第${position}条SN码规则的匹配内容(match_value)长度不能超过${MAX_MATCH_VALUE_LENGTH}个字符`); + } + + const keepMode = this.normalizeKeepMode(rule.keep_mode ?? rule.keepMode ?? rule.mode); + if (!keepMode) { + throw new Error(`第${position}条SN码规则的处理方式(keep_mode)只能是 full(全码)或 strip(去掉前缀/后缀)`); + } + + const uniqueKey = `${matchType}|${matchValue}|${keepMode}`; + if (seenKeys.has(uniqueKey)) { + throw new Error(`第${position}条SN码规则与前面的规则重复:${matchType}「${matchValue}」${keepMode}`); + } + seenKeys.add(uniqueKey); + + normalized.push({ + match_type: matchType, + match_value: matchValue, + keep_mode: keepMode, + }); + }); + + return normalized; + } + + /** + * 按规则把扫码内容加工成 SN 码;未命中任何规则时返回原码。 + * + * @param {string} rawCode 扫码内容。 + * @param {Object[]} rules 已规范化的规则数组。 + * @return {{ matched: boolean, rule: Object|null, sn_code: string, reason?: string }} 匹配结果。 + */ + matchSnCode(rawCode, rules = []) { + const code = String(rawCode === undefined || rawCode === null ? '' : rawCode).trim(); + if (!code) { + return { matched: false, rule: null, sn_code: '', reason: 'empty_code' }; + } + if (code.length > MAX_SN_CODE_LENGTH) { + return { matched: false, rule: null, sn_code: code, reason: 'code_too_long' }; + } + + const ruleList = this.toRuleList(rules); + for (const rule of ruleList) { + if (rule.match_type === MATCH_TYPE_PREFIX && !code.startsWith(rule.match_value)) { + continue; + } + if (rule.match_type === MATCH_TYPE_SUFFIX && !code.endsWith(rule.match_value)) { + continue; + } + + let snCode = code; + if (rule.keep_mode === KEEP_MODE_STRIP) { + const start = rule.match_type === MATCH_TYPE_PREFIX ? rule.match_value.length : 0; + const end = rule.match_type === MATCH_TYPE_SUFFIX ? code.length - rule.match_value.length : code.length; + snCode = code.slice(start, end); + } + + if (!snCode) { + return { matched: true, rule, sn_code: '', reason: 'empty_after_strip' }; + } + return { matched: true, rule, sn_code: snCode }; + } + + return { matched: false, rule: null, sn_code: code }; + } + + /** + * 规范化匹配位置。 + * @param {*} rawValue 原始值。 + * @return {string} 'prefix' / 'suffix',非法返回空串。 + */ + normalizeMatchType(rawValue) { + const value = String(rawValue === undefined || rawValue === null ? '' : rawValue).trim().toLowerCase(); + return MATCH_TYPE_SET.has(value) ? value : ''; + } + + /** + * 规范化处理方式。 + * @param {*} rawValue 原始值。 + * @return {string} 'full' / 'strip',非法返回空串。 + */ + normalizeKeepMode(rawValue) { + const value = String(rawValue === undefined || rawValue === null ? '' : rawValue).trim().toLowerCase(); + return KEEP_MODE_SET.has(value) ? value : ''; + } + + /** + * 清洗前缀/后缀字符串:去首尾空白,把 undefined/null 转空串。 + * @param {*} rawValue 原始值。 + * @return {string} 清洗后的字符串。 + */ + normalizeMatchValue(rawValue) { + if (rawValue === undefined || rawValue === null) { + return ''; + } + return String(rawValue).trim(); + } + + /** + * 判断是否普通对象。 + * @param {*} value 待判断值。 + * @return {boolean} 是否普通对象。 + */ + isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; + } +} + +module.exports = SnCodeRuleService; diff --git a/app/service/systems/space.js b/app/service/systems/space.js index 7c20188..86d492e 100644 --- a/app/service/systems/space.js +++ b/app/service/systems/space.js @@ -2,12 +2,14 @@ const Service = require('egg').Service; class spaceService extends Service { - constructor(ctx) { - super(ctx); - } - async searchSpace(data) { + /** + * 按关键字查询库位(单个关键字)。 + * + * @param {string} [keyword] 搜索关键字,为空时返回当前仓库下前 50 条。 + * @return {Promise} 库位列表(最多 50 条)。 + */ + async _searchByKeyword(keyword) { const { ctx, app } = this; - const { keyword } = data; const warehouseId = ctx.user.store_id; // 构建基础查询条件:warehouse_id 为当前仓库或 null @@ -38,13 +40,18 @@ class spaceService extends Service { [app.Sequelize.Op.like]: searchKeyword, }, }, + { + custom_name: { + [app.Sequelize.Op.like]: searchKeyword, + }, + }, ], }, ], }; } - const results = await app.model.LocationSpace.findAll({ + return app.model.LocationSpace.findAll({ where: whereCondition, attributes: [ 'id', 'space_code', 'custom_barcode', 'custom_name', @@ -53,8 +60,31 @@ class spaceService extends Service { limit: 50, subQuery: false, }); + } + + async searchSpace(data) { + const { keyword } = data; + const results = await this._searchByKeyword(keyword); return { code: 200, data: results, total: results.length }; } + + /** + * 批量按关键字查询库位。 + * + * @param {Object} data 请求数据。 + * @param {Array} data.keywords 搜索关键字数组。 + * @return {Promise} data 为与 keywords 一一对应的库位列表数组, + * 无记录时对应项为空数组 []。 + */ + async searchSpaces(data) { + const { keywords } = data; + const keywordList = Array.isArray(keywords) ? keywords : []; + const resultList = await Promise.all( + keywordList.map(keyword => this._searchByKeyword(keyword)) + ); + + return { code: 200, data: resultList, total: resultList.length }; + } } module.exports = spaceService; diff --git a/app/service/systems/stock_check.js b/app/service/systems/stock_check.js new file mode 100644 index 0000000..b28d078 --- /dev/null +++ b/app/service/systems/stock_check.js @@ -0,0 +1,6377 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); +const Service = require('egg').Service; + +/** 盘点范围类型枚举(wms_stock_check.type) */ +const STOCK_CHECK_TYPES = Object.freeze([ 'store', 'goods', 'location' ]); +/** 盘点方式枚举(wms_stock_check.mode) */ +const STOCK_CHECK_MODES = Object.freeze([ 'open', 'blind' ]); +/** 允许添加明细的主表状态 */ +const ADD_DETAIL_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]); +/** 单次批量添加库位明细允许的最大库位ID数量 */ +const STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS = 200; +/** 允许盘点作业上报/完成的主表状态 */ +const REPORT_ALLOWED_STATUSES = Object.freeze([ 'approved', 'checking' ]); +/** + * 单次上报实盘数量上限(wms_stock_check_record.quantity 为 int(12) 有符号列, + * 实际可存上限 2147483647;超限直接落库会抛 Out of range 变成 500)。 + */ +const REPORT_MAX_QUANTITY = 2147483647; +/** 允许提交审核的主表状态 */ +const SUBMIT_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]); +/** 允许取消的主表状态 */ +const CANCEL_ALLOWED_STATUSES = Object.freeze([ 'created', 'submitted', 'rejected' ]); +/** + * 静态盘点锁定中口径:is_static=1 且主表状态为「未结束」的任务(审核完成即开始锁定, + * 盘点作业中持续锁定;提交审核前、已完成/已取消/已驳回均不锁定)。 + */ +const STATIC_LOCK_ALLOWED_STATUSES = Object.freeze([ 'approved', 'checking' ]); +/** 静态盘点锁定缓存键前缀(按仓库维度缓存 stock_id 集合) */ +const STATIC_LOCK_CACHE_KEY_PREFIX = 'stock_check:static_lock:'; +/** 静态盘点锁定代次键前缀(状态流转时递增,供回源前后一致性校验防脏读) */ +const STATIC_LOCK_GENERATION_KEY_PREFIX = 'stock_check:static_lock_gen:'; +/** 锁定代次进程内回退计数(Redis 不可用时使用) */ +const STATIC_LOCK_GENERATION_LOCAL = new Map(); +/** 静态盘点锁定缓存 TTL(秒):状态流转时主动重建,此处仅作兜底过期 */ +const STATIC_LOCK_CACHE_TTL_SECONDS = 300; +/** + * 进程内 singleflight 表(键=缓存键,值=回源 Promise): + * 缓存未命中/失效瞬间的并发查询共用同一次数据库回源,避免瞬时击穿。 + */ +const STATIC_LOCK_INFLIGHT = new Map(); + +/** + * 有效库位过滤 SQL(库位未删除且所属 zone 存在且未删除)。 + * 无头库位(zone 不存在/已删除)不纳入盘点范围:明细生成、商品作业视图库位枚举均按此过滤。 + */ +const VALID_SPACE_SQL = '(SELECT ls.id FROM wms_location_space ls ' + + 'JOIN wms_location_zone z ON z.id = ls.zone_id AND z.deleted_at IS NULL ' + + 'WHERE ls.deleted_at IS NULL)'; + +/** 盘点范围类型中文标签 */ +const STOCK_CHECK_TYPE_LABELS = Object.freeze({ + store: '按货主', + goods: '按商品', + location: '按库位', +}); +/** 盘点方式中文标签 */ +const STOCK_CHECK_MODE_LABELS = Object.freeze({ + open: '明盘', + blind: '盲盘', +}); +/** 主表状态中文标签 */ +const STOCK_CHECK_STATUS_LABELS = Object.freeze({ + created: '已创建', + submitted: '待审核', + rejected: '已驳回', + approved: '审核完成', + checking: '盘点作业中', + completed: '已完成', + cancelled: '已取消', +}); +/** 明细盘点进度中文标签(主表 detail_status) */ +const STOCK_CHECK_DETAIL_PROGRESS_LABELS = Object.freeze({ + none_checked: '未盘', + partial_checked: '部分已盘', + all_checked: '全部已盘', +}); + +/** + * 库存盘点模块业务逻辑层。 + * 负责 wms_stock_check(主表)/ wms_stock_check_detail(明细)的状态机流转与增删查, + * 以及导出 Excel 生成与 COS 上传等核心操作。 + * 所有数据库交互集中在此层,供 systemMethods/stock/check.js 调用。 + */ +class StockCheckService extends Service { + /** + * 创建带业务错误码的异常对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 获取当前日期片段(YYYYMMDD)。 + * + * @return {string} 当前日期片段。 + */ + _getCurrentDatePart() { + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; + } + + /** + * 生成盘点单号。 + * 格式:PD + YYYYMMDD + 6位序号(如 PD20260929000001)。 + * 序号全局递增(不按仓库隔离):uk_check_no 为全局唯一索引,按仓各自从 1 起会跨仓撞号; + * 并发创建时的撞号由 create 方法的唯一键重试兜底(参照收货单 receiving_number 口径)。 + * + * @return {Promise} 盘点单号。 + */ + async generateCheckNo() { + const { ctx } = this; + const datePart = this._getCurrentDatePart(); + const prefix = 'PD'; + const pattern = `${prefix}${datePart}%`; + + const rows = await ctx.model.query( + ` + SELECT check_no + FROM wms_stock_check + WHERE check_no LIKE :pattern + ORDER BY check_no DESC + LIMIT 1 + `, + { + replacements: { pattern }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const latestNo = String(rows && rows[0] && rows[0].check_no || '').trim(); + let sequence = 1; + if (latestNo) { + const match = latestNo.match(/(\d{6})$/); + const lastSequence = match ? Number(match[1]) : 0; + if (Number.isInteger(lastSequence) && lastSequence > 0) { + sequence = lastSequence + 1; + } + } + + return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`; + } + + /** + * 判断创建盘点任务异常是否由单号唯一键冲突引起。 + * 参照收货单 isReceivingNumberDuplicateError 口径:ER_DUP_ENTRY 且命中 check_no 唯一索引。 + * + * @param {Error} error 创建异常。 + * @return {boolean} 是单号重复错误返回 true。 + */ + isCheckNoDuplicateError(error) { + const parentCode = error && error.parent && error.parent.code; + const sqlMessage = String((error && error.parent && error.parent.sqlMessage) || error.message || ''); + return parentCode === 'ER_DUP_ENTRY' && /uk_check_no|check_no/i.test(sqlMessage); + } + + /** + * 将主表行格式化为对外输出结构(补齐可空字段默认值)。 + * + * @param {Object} row 主表原始行数据。 + * @return {Object} 格式化后的主表行。 + */ + _formatCheckRow(row = {}) { + return { + id: row.id, + check_no: row.check_no, + title: row.title || '', + type: row.type || 'location', + mode: row.mode || 'open', + store_id: row.store_id || null, + is_static: Number(row.is_static) === 1 ? 1 : 0, + status: row.status || 'created', + detail_status: row.detail_status || 'none_checked', + start_time: row.start_time || null, + end_time: row.end_time || null, + creator_id: row.creator_id || 0, + creator_name: row.creator_name || '', + total_items: row.total_items || 0, + checked_items: row.checked_items || 0, + diff_items: row.diff_items || 0, + remark: row.remark || '', + created_at: row.created_at || null, + updated_at: row.updated_at || null, + }; + } + + /** + * 将 ID 入参(单值或数组)归一化为去重后的正整数列表。 + * + * @param {number|Array} values 原始 ID 入参。 + * @return {Array} 去重后的正整数 ID 列表。 + */ + _normalizeIdList(values) { + const list = Array.isArray(values) ? values : [ values ]; + return [ ...new Set(list.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ]; + } + + /** + * 将库位编码入参(单值或数组)归一化为去重后的非空字符串列表(保持传入顺序)。 + * + * @param {string|Array} values 原始库位编码入参。 + * @return {Array} 去重后的非空库位编码列表。 + */ + _normalizeCodeList(values) { + const list = Array.isArray(values) ? values : [ values ]; + return [ ...new Set( + list + .map(value => (value === null || value === undefined ? '' : String(value)).trim()) + .filter(Boolean) + ) ]; + } + + /** + * 将日期值格式化为本地时间字符串(YYYY-MM-DD HH:mm:ss),供 Excel 导出使用。 + * + * @param {*} value 日期值(Date 实例或可解析字符串/数字)。 + * @return {string} 格式化后的本地时间字符串,非法值返回空字符串。 + */ + _formatLocalDateTime(value) { + if (!value) { + return ''; + } + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + return ''; + } + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + const hours = String(date.getHours()).padStart(2, '0'); + const minutes = String(date.getMinutes()).padStart(2, '0'); + const seconds = String(date.getSeconds()).padStart(2, '0'); + return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; + } + + /** + * 按仓库隔离维度查询盘点主表。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} id 主表ID。 + * @return {Promise} 主表模型实例,不存在时返回 null。 + */ + async _findCheck(warehouseId, id) { + return this.ctx.model.StockCheck.findOne({ + where: { id: Number(id), warehouse_id: Number(warehouseId) }, + }); + } + + /** + * 计算盘点任务范围口径的条数汇总(total_items / checked_items,纯查询无副作用)。 + * 商品范围(scope_type=goods)按商品(stock_id)去重计数(一个商品多个库位明细行合并为 1 项), + * 库位范围(scope_type=location)按明细行计数;已盘口径:明细存在盘点作业记录 + * (wms_stock_check_record),商品范围按「商品下任一明细行有记录」计已盘。 + * + * @param {number} checkId 盘点任务ID。 + * @return {Promise} { total_items, checked_items }。 + */ + async _countScopeSummary(checkId) { + const { ctx } = this; + const checkIdNumber = Number(checkId); + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkIdNumber }, + attributes: [ 'id', 'scope_type', 'stock_id' ], + raw: true, + }); + const recordRows = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkIdNumber }, + attributes: [ 'detail_id' ], + raw: true, + }); + const checkedDetailIds = new Set(recordRows.map(row => Number(row.detail_id))); + + const goodsStockIds = new Set(); + const checkedGoodsStockIds = new Set(); + let locationCount = 0; + let checkedLocationCount = 0; + for (const detailRow of detailRows) { + if ((detailRow.scope_type || 'goods') === 'location') { + locationCount++; + if (checkedDetailIds.has(Number(detailRow.id))) { + checkedLocationCount++; + } + continue; + } + const stockId = Number(detailRow.stock_id); + goodsStockIds.add(stockId); + if (checkedDetailIds.has(Number(detailRow.id))) { + checkedGoodsStockIds.add(stockId); + } + } + + return { + total_items: goodsStockIds.size + locationCount, + checked_items: checkedGoodsStockIds.size + checkedLocationCount, + }; + } + + /** + * 重算盘点主表的盘点进度汇总(checked_items / diff_items / detail_status)。 + * 计数口径(与 _countScopeSummary 一致):商品范围(scope_type=goods)按商品(stock_id) + * 去重计数,库位范围按明细行计数;明细已盘口径:该明细存在盘点作业记录(wms_stock_check_record)。 + * 差异口径:商品范围按商品聚合判断(商品实盘合计 ≠ 账面快照 system_quantity 合计即该商品有差异, + * 仅存在作业记录的商品计入,未盘商品不提前计差异——finish 时按实盘 0 计盘亏); + * 库位范围行内任一商品「实盘合计 ≠ 账面」即该行有差异,按明细去重计数, + * 库位行账面 = wms_storage 按 (space_id, stock_id) 汇总(location_id 为空时账面按 0); + * 未知商品(stock_id 为空)无账面,按 barcode 维度归组,实盘 > 0 即盘盈、必然计入差异; + * detail_status 按已盘明细占比自动重算:none_checked → partial_checked → all_checked。 + * + * @param {number} checkId 盘点任务ID。 + * @return {Promise} 重算后的汇总信息(含 finish 复用的按明细/按商品/未知商品聚合数据)。 + */ + async _recalcCheckSummary(checkId) { + const { ctx } = this; + const { Op, literal } = ctx.app.Sequelize; + + const checkIdNumber = Number(checkId); + const detailWhere = { check_id: checkIdNumber }; + + // 范围口径汇总:商品范围按商品(stock_id)计数,库位范围按明细行计数 + const scopeSummary = await this._countScopeSummary(checkIdNumber); + const totalItems = scopeSummary.total_items; + const checkedItems = scopeSummary.checked_items; + + // 明细与作业记录 + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: detailWhere, + attributes: [ 'id', 'scope_type', 'stock_id', 'system_quantity', 'location_id' ], + raw: true, + }); + const recordRows = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkIdNumber }, + attributes: [ 'detail_id', 'stock_id', 'barcode', 'item_name', 'quantity', 'is_empty' ], + raw: true, + }); + + // 按明细聚合作业记录:明细总实盘 + 按商品分组实盘 + 未知商品按条码分组实盘 + const checkedQuantityByDetail = new Map(); + const stockQuantityByDetail = new Map(); + const unknownQuantityByDetail = new Map(); + const emptyDetailIds = new Set(); + for (const record of recordRows) { + const detailId = Number(record.detail_id); + // 空库位标记:不参与商品/数量聚合(差异按该库位账面单独判断) + if (record.is_empty) { + emptyDetailIds.add(detailId); + continue; + } + const stockId = Number(record.stock_id); + const quantity = Number(record.quantity) || 0; + checkedQuantityByDetail.set(detailId, (checkedQuantityByDetail.get(detailId) || 0) + quantity); + if (!Number.isInteger(stockId) || stockId <= 0) { + // 未知商品(stock_id 为空):按条码维度归组(无账面,差异 = 实盘 = 盘盈) + const barcodeKey = String(record.barcode || '').trim() || 'unknown'; + if (!unknownQuantityByDetail.has(detailId)) { + unknownQuantityByDetail.set(detailId, new Map()); + } + const byBarcode = unknownQuantityByDetail.get(detailId); + const unknownAgg = byBarcode.get(barcodeKey) || { + barcode: String(record.barcode || '').trim() || null, + item_name: record.item_name || null, + checked: 0, + }; + unknownAgg.checked += quantity; + byBarcode.set(barcodeKey, unknownAgg); + continue; + } + if (!stockQuantityByDetail.has(detailId)) { + stockQuantityByDetail.set(detailId, new Map()); + } + const byStock = stockQuantityByDetail.get(detailId); + const agg = byStock.get(stockId) || { checked: 0 }; + agg.checked += quantity; + byStock.set(stockId, agg); + } + + // 库位行账面:wms_storage 按 (space_id, stock_id) SUM(可用数量),并附到按商品聚合 + const storageQuantityMap = new Map(); + const locationDetailRows = detailRows.filter(row => (row.scope_type || 'goods') === 'location'); + const goodsDetailRows = detailRows.filter(row => (row.scope_type || 'goods') !== 'location'); + if (locationDetailRows.length > 0) { + const locationIds = [ ...new Set(locationDetailRows + .filter(row => row.location_id) + .map(row => Number(row.location_id))) ]; + const stockIds = new Set(); + for (const locationRow of locationDetailRows) { + const byStock = stockQuantityByDetail.get(Number(locationRow.id)); + if (!byStock) { + continue; + } + for (const stockId of byStock.keys()) { + stockIds.add(stockId); + } + } + if (locationIds.length > 0 && stockIds.size > 0) { + const storageRows = await ctx.model.Storage.findAll({ + where: { + space_id: { [Op.in]: locationIds }, + stock_id: { [Op.in]: [ ...stockIds ] }, + }, + attributes: [ + 'space_id', + 'stock_id', + [ literal('SUM(available_quantity)'), 'totalQuantity' ], + ], + group: [ 'space_id', 'stock_id' ], + raw: true, + }); + for (const storageRow of storageRows) { + storageQuantityMap.set( + `${Number(storageRow.space_id)}_${Number(storageRow.stock_id)}`, + Number(storageRow.totalQuantity) || 0 + ); + } + } + // 账面附到按商品聚合(location_id 为空时账面按 0) + for (const locationRow of locationDetailRows) { + const byStock = stockQuantityByDetail.get(Number(locationRow.id)); + if (!byStock) { + continue; + } + const locationId = locationRow.location_id ? Number(locationRow.location_id) : 0; + for (const [ stockId, agg ] of byStock) { + agg.system = locationId > 0 ? (storageQuantityMap.get(`${locationId}_${stockId}`) || 0) : 0; + } + } + } + + // 空库位标记明细的库位账面汇总(差异口径:账面有库存即盘亏) + const emptyLocationSystemMap = new Map(); + if (emptyDetailIds.size > 0) { + const emptyDetailRows = detailRows.filter(row => emptyDetailIds.has(Number(row.id))); + const emptyLocationIds = [ ...new Set(emptyDetailRows + .filter(row => row.location_id) + .map(row => Number(row.location_id))) ]; + if (emptyLocationIds.length > 0) { + const emptyStorageRows = await ctx.model.Storage.findAll({ + where: { space_id: { [Op.in]: emptyLocationIds } }, + attributes: [ + 'space_id', + [ literal('SUM(available_quantity)'), 'totalQuantity' ], + ], + group: [ 'space_id' ], + raw: true, + }); + const systemBySpace = new Map(emptyStorageRows.map(row => [ + Number(row.space_id), + Number(row.totalQuantity) || 0, + ])); + for (const emptyRow of emptyDetailRows) { + const emptyLocationId = emptyRow.location_id ? Number(emptyRow.location_id) : 0; + emptyLocationSystemMap.set( + Number(emptyRow.id), + emptyLocationId > 0 ? (systemBySpace.get(emptyLocationId) || 0) : 0 + ); + } + } else { + for (const emptyRow of emptyDetailRows) { + emptyLocationSystemMap.set(Number(emptyRow.id), 0); + } + } + } + + // 差异项数:库位范围按明细行去重计数(行内任一商品实盘≠账面即该行有差异; + // 未知商品(stock_id 为空)无账面,实盘 > 0 即盘盈、必然计入差异; + // 空库位标记明细:账面有库存即盘亏差异(标记空与实际不符)); + // 商品范围按商品聚合计数(实盘合计 ≠ 账面快照合计即该商品有差异,仅存在作业记录的商品计入, + // 未盘商品不提前计差异——finish 时按实盘 0 计盘亏) + let diffItems = 0; + for (const detailRow of locationDetailRows) { + const detailId = Number(detailRow.id); + if (emptyDetailIds.has(detailId)) { + if ((emptyLocationSystemMap.get(detailId) || 0) > 0) { + diffItems++; + } + continue; + } + const byStock = stockQuantityByDetail.get(detailId); + const byUnknown = unknownQuantityByDetail.get(detailId); + if ((!byStock || byStock.size === 0) && (!byUnknown || byUnknown.size === 0)) { + continue; + } + let hasDiff = false; + for (const agg of (byStock ? byStock.values() : [])) { + if (agg.checked !== (agg.system || 0)) { + hasDiff = true; + break; + } + } + if (!hasDiff && byUnknown) { + for (const agg of byUnknown.values()) { + if (agg.checked > 0) { + hasDiff = true; + break; + } + } + } + if (hasDiff) { + diffItems++; + } + } + + // 商品范围差异:按商品(stock_id)聚合判断(多个库位明细行合并为一个商品) + const goodsCheckedByStock = new Map(); + const goodsSnapshotByStock = new Map(); + for (const detailRow of goodsDetailRows) { + const stockId = Number(detailRow.stock_id); + goodsSnapshotByStock.set( + stockId, + (goodsSnapshotByStock.get(stockId) || 0) + Number(detailRow.system_quantity || 0) + ); + const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id)); + if (checkedQuantity !== undefined) { + goodsCheckedByStock.set( + stockId, + (goodsCheckedByStock.get(stockId) || 0) + checkedQuantity + ); + } + } + for (const [ stockId, checkedQuantity ] of goodsCheckedByStock) { + if (checkedQuantity !== (goodsSnapshotByStock.get(stockId) || 0)) { + diffItems++; + } + } + + const detailStatus = totalItems === 0 || checkedItems === 0 + ? 'none_checked' + : (checkedItems >= totalItems ? 'all_checked' : 'partial_checked'); + + await ctx.model.StockCheck.update( + { + checked_items: checkedItems, + diff_items: diffItems, + detail_status: detailStatus, + }, + { where: { id: checkIdNumber } } + ); + + return { + total_items: totalItems, + checked_items: checkedItems, + diff_items: diffItems, + detail_status: detailStatus, + checked_quantity_by_detail: checkedQuantityByDetail, + stock_quantity_by_detail: stockQuantityByDetail, + unknown_quantity_by_detail: unknownQuantityByDetail, + }; + } + + /** + * 创建盘点任务(空任务)。 + * 生成单号 PD+YYYYMMDD+6位序号,初始状态 created,明细进度 none_checked。 + * + * @param {Object} params 创建参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {string} [params.title] 盘点名称/主题。 + * @param {string} [params.type='location'] 盘点范围类型:location/store/goods。 + * @param {string} [params.mode='open'] 盘点方式:open=明盘/blind=盲盘; + * 按库位盘点(location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。 + * @param {number} [params.storeId] 货主ID(按货主盘点时必填)。 + * @param {boolean|number} [params.isStatic] 是否静态盘点(纯标记):true/'true'/1/'1' 记为静态, + * 缺省与其他值为普通盘点;**仅对商品盘点(store/goods)有效**,按库位盘点(location)一律为 0 + * (忽略入参);静态盘点定式创建的任务自动置 1。 + * @param {string} [params.remark] 备注。 + * 盘点日期固定为今天,前端不传。 + * @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。 + * @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。 + * @return {Promise} 新建的盘点任务信息。 + * @throws {Error} 参数非法时抛出业务错误(错误码 400)。 + */ + async create(params = {}) { + const { + warehouseId, + title, + type, + mode, + storeId, + isStatic, + remark, + creatorId, + creatorName, + } = params; + const { ctx } = this; + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + const normalizedType = type ? String(type).trim() : 'location'; + if (!STOCK_CHECK_TYPES.includes(normalizedType)) { + throw this.createBusinessError(`盘点范围类型不合法,仅支持 ${STOCK_CHECK_TYPES.join('/')}`); + } + + let normalizedMode = mode ? String(mode).trim() : 'open'; + if (!STOCK_CHECK_MODES.includes(normalizedMode)) { + throw this.createBusinessError(`盘点方式不合法,仅支持 ${STOCK_CHECK_MODES.join('/')}`); + } + // 按库位盘点一律盲盘,不管前端传入什么; + // 按商品盘点(store/goods)按传入值(默认明盘) + if (normalizedType === 'location') { + normalizedMode = 'blind'; + } + + const normalizedStoreId = storeId !== undefined && storeId !== null && storeId !== '' + ? Number(storeId) + : null; + if (normalizedType === 'store' && (!Number.isInteger(normalizedStoreId) || normalizedStoreId <= 0)) { + throw this.createBusinessError('按货主盘点时必须指定货主'); + } + + // 是否静态盘点:纯标记(true/'true'/1/'1' 视为开启,缺省/其他值为普通盘点); + // 仅对商品盘点有效——按库位盘点(type=location)一律为 0,忽略入参 + const isStaticRequested = isStatic === true || isStatic === 'true' || isStatic === 1 || isStatic === '1'; + const normalizedIsStatic = normalizedType === 'location' || !isStaticRequested ? 0 : 1; + + // 创建盘点任务(并发下撞 uk_check_no 唯一键时自动重取单号,参照收货单口径,最多重试 5 次) + const maxCreateRetries = 5; + let record = null; + for (let attempt = 1; attempt <= maxCreateRetries; attempt++) { + const checkNo = await this.generateCheckNo(); + try { + record = await ctx.model.StockCheck.create({ + warehouse_id: normalizedWarehouseId, + check_no: checkNo, + title: title ? String(title).trim() : null, + type: normalizedType, + mode: normalizedMode, + store_id: normalizedStoreId, + is_static: normalizedIsStatic, + scope_snapshot: null, + status: 'created', + detail_status: 'none_checked', + creator_id: creatorId ? Number(creatorId) : 0, + creator_name: creatorName || null, + remark: remark ? String(remark).trim() : null, + }); + break; + } catch (error) { + if (this.isCheckNoDuplicateError(error) && attempt < maxCreateRetries) { + ctx.logger.warn(`[StockCheckCreateRetry] check_no 冲突,准备重试第 ${attempt + 1} 次`, { + warehouse_id: normalizedWarehouseId, + }); + continue; + } + throw error; + } + } + + const plainRecord = record.get({ plain: true }); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: plainRecord.id, + operationCode: 'STOCK_CHECK_CREATE', + operationAction: 'CREATE', + changeSummary: `创建盘点任务:单号 ${plainRecord.check_no},范围类型 ${STOCK_CHECK_TYPE_LABELS[normalizedType]},盘点方式 ${STOCK_CHECK_MODE_LABELS[normalizedMode]}${normalizedIsStatic ? ',静态盘点' : ''}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: normalizedWarehouseId, + checkNo: plainRecord.check_no, + type: normalizedType, + mode: normalizedMode, + isStatic: normalizedIsStatic, + message: `创建盘点任务 ${plainRecord.check_no}(${STOCK_CHECK_TYPE_LABELS[normalizedType]}/${STOCK_CHECK_MODE_LABELS[normalizedMode]}${normalizedIsStatic ? '/静态' : ''})`, + }, + }); + + return this._formatCheckRow(plainRecord); + } + + /** + * 批量解析货主名称映射。 + * 优先取合约表 wms_store_warehouse.store_remask(货主备注名称,按 store_id + warehouse_id), + * 无合约或备注为空时回退 wms_store.company_name(公司全称)。 + * + * @param {Array} storeIds 货主ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} store_id → 货主名称。 + */ + async _resolveStoreNameMap(storeIds, warehouseId) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const normalizedIds = [ ...new Set((storeIds || []).map(v => Number(v)).filter(v => v > 0)) ]; + const resultMap = new Map(); + if (normalizedIds.length === 0) return resultMap; + + const contractRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: normalizedIds }, + warehouse_id: Number(warehouseId), + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const row of contractRows) { + resultMap.set(Number(row.store_id), row.store_remask || ''); + } + + const storeRows = await ctx.model.Store.findAll({ + where: { id: { [Op.in]: normalizedIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const row of storeRows) { + if (!resultMap.get(Number(row.id))) { + resultMap.set(Number(row.id), row.company_name || ''); + } + } + + return resultMap; + } + + /** + * 构建时间范围查询条件。 + * 支持:[from, to] 数组(between)/ 单值(>=)/ 空值忽略。 + * + * @param {*} value 时间范围入参(数组或单值)。 + * @param {Object} Op Sequelize 操作符对象。 + * @return {Object|null} Sequelize where 条件片段,无有效值返回 null。 + */ + _buildTimeRangeCondition(value, Op) { + if (Array.isArray(value)) { + const [ from, to ] = value; + const fromDate = from ? new Date(from) : null; + const toDate = to ? new Date(to) : null; + if (fromDate && !Number.isNaN(fromDate.getTime()) && toDate && !Number.isNaN(toDate.getTime())) { + return { [Op.between]: [ fromDate, toDate ] }; + } + if (fromDate && !Number.isNaN(fromDate.getTime())) { + return { [Op.gte]: fromDate }; + } + if (toDate && !Number.isNaN(toDate.getTime())) { + return { [Op.lte]: toDate }; + } + return null; + } + if (value === undefined || value === null || value === '') { + return null; + } + const parsedDate = new Date(value); + if (Number.isNaN(parsedDate.getTime())) { + return null; + } + return { [Op.gte]: parsedDate }; + } + + /** + * 将单值/数组归一化为字符串列表(供 type/mode/status 等枚举筛选)。 + * + * @param {*} value 原始值。 + * @return {Array} 归一化后的字符串列表。 + */ + _normalizeEnumValues(value) { + const list = Array.isArray(value) ? value : [ value ]; + return [ ...new Set(list + .map(item => String(item === null || item === undefined ? '' : item).trim()) + .filter(Boolean)) ]; + } + + /** + * 拉取盘点任务列表。 + * 支持筛选:status(状态,单值或数组)、type(范围类型)、mode(盘点方式)、 + * store_id(货主)、keyword(单号/标题模糊)、created_at(创建时间范围)、 + * start_time(盘点开始时间范围)、end_time(盘点结束时间范围)与分页。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {string|Array} [params.status] 状态筛选。 + * @param {string|Array} [params.type] 范围类型筛选。 + * @param {string|Array} [params.mode] 盘点方式筛选。 + * @param {number|string} [params.storeId] 货主筛选。 + * @param {string} [params.keyword] 关键字(盘点单号/标题模糊匹配)。 + * @param {*} [params.createdAt] 创建时间筛选(单值=当天起,[from,to]=区间)。 + * @param {*} [params.startTime] 盘点开始时间筛选。 + * @param {*} [params.endTime] 盘点结束时间筛选。 + * @param {Object} [params.pagination] 分页参数。 + * @return {Promise} { rows, total, page, pageSize }。 + */ + async list(params = {}) { + const { + warehouseId, + status, + type, + mode, + storeId, + keyword, + createdAt, + startTime, + endTime, + pagination = {}, + } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + + const where = { warehouse_id: Number(warehouseId) }; + + if (status !== undefined && status !== null && status !== '') { + const statusList = this._normalizeEnumValues(status); + if (statusList.length === 1) { + where.status = statusList[0]; + } else if (statusList.length > 1) { + where.status = { [Op.in]: statusList }; + } + } + + if (type !== undefined && type !== null && type !== '') { + const typeList = this._normalizeEnumValues(type); + if (typeList.length === 1) { + where.type = typeList[0]; + } else if (typeList.length > 1) { + where.type = { [Op.in]: typeList }; + } + } + + if (mode !== undefined && mode !== null && mode !== '') { + const modeList = this._normalizeEnumValues(mode); + if (modeList.length === 1) { + where.mode = modeList[0]; + } else if (modeList.length > 1) { + where.mode = { [Op.in]: modeList }; + } + } + + if (storeId !== undefined && storeId !== null && storeId !== '') { + where.store_id = Number(storeId); + } + + const createdRange = this._buildTimeRangeCondition(createdAt, Op); + if (createdRange) { + where.created_at = createdRange; + } + const startRange = this._buildTimeRangeCondition(startTime, Op); + if (startRange) { + where.start_time = startRange; + } + const endRange = this._buildTimeRangeCondition(endTime, Op); + if (endRange) { + where.end_time = endRange; + } + + const keywordValue = keyword ? String(keyword).trim() : ''; + if (keywordValue) { + where[Op.or] = [ + { check_no: { [Op.like]: `%${keywordValue}%` } }, + { title: { [Op.like]: `%${keywordValue}%` } }, + ]; + } + + const { count, rows } = await ctx.model.StockCheck.findAndCountAll({ + where, + order: [[ 'id', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + // 补齐货主名称(合约货主备注优先、公司全称兜底) + const storeNameMap = await this._resolveStoreNameMap( + rows.map(row => row.store_id), + warehouseId + ); + const formattedRows = rows.map(row => ({ + ...row, + store_name: storeNameMap.get(Number(row.store_id)) || '', + })); + + return { rows: formattedRows, total: count, page, pageSize }; + } + + /** + * 拉取盘点定式清单。 + * 转调 stockCheckPatterns.listPatterns(),返回全部可用定式(id/name/description/type)。 + * + * @return {Promise} { patterns, total }。 + */ + async patternList() { + const { ctx } = this; + const patterns = ctx.service.systems.stockCheckPatterns.listPatterns(); + return { patterns, total: patterns.length }; + } + + /** + * 按定式快速创建盘点任务。 + * 按定式收集盘点对象(goods 型得到 stock_ids、location 型得到库位编码列表), + * 无符合条件对象时拒绝创建(错误码 400);创建后主表状态直接为 submitted(待审核)、 + * detail_status=none_checked、total_items 按明细重算;static 定式在任务创建成功后 + * 把命中的 stock_id 写入 wms_stock_static_check_task(写失败不影响主流程)。 + * + * @param {Object} params 创建参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {string} params.patternId 定式ID(pattern_id)。 + * @param {string} [params.title] 盘点名称/主题,缺省取定式 name。 + * @param {string} [params.remark] 备注。 + * @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。 + * @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。 + * 盘点方式由定式范围类型固定:库位类定式一律盲盘(blind)、商品类定式一律明盘(open); + * 盘点日期固定为今天,前端不传。 + * @return {Promise} { check, total_items, pattern_id }。 + * @throws {Error} 仓库上下文缺失/定式不存在/参数非法/无符合条件对象时抛出业务错误(错误码 400)。 + */ + async patternCreate(params = {}) { + const { + warehouseId, + patternId, + title, + remark, + creatorId, + creatorName, + } = params; + const { ctx } = this; + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + const normalizedPatternId = String(patternId || '').trim(); + const pattern = normalizedPatternId + ? ctx.service.systems.stockCheckPatterns.getPatternById(normalizedPatternId) + : null; + if (!pattern) { + throw this.createBusinessError('盘点定式不存在'); + } + + // 盘点方式由定式范围类型固定:库位类一律盲盘、商品类一律明盘(前端不传) + const normalizedMode = pattern.type === 'location' ? 'blind' : 'open'; + // 静态定式创建的任务标记为静态盘点(纯标记,不改变流程与数量口径); + // 静态盘点仅对商品盘点有效,库位类定式一律 0 + const normalizedIsStatic = pattern.id === 'static' && pattern.type !== 'location' ? 1 : 0; + + const normalizedTitle = title ? String(title).trim() : pattern.name; + + // 按定式收集盘点对象 + const collected = await ctx.service.systems.stockCheckPatterns.collectById(pattern.id, { + warehouseId: normalizedWarehouseId, + }); + const stockIds = Array.isArray(collected && collected.stock_ids) ? collected.stock_ids : []; + const locations = Array.isArray(collected && collected.locations) ? collected.locations : []; + if (pattern.type === 'location' && locations.length === 0) { + throw this.createBusinessError('当前仓库没有账面为空的库位'); + } + if (pattern.type === 'goods' && stockIds.length === 0) { + throw this.createBusinessError('没有符合条件的商品'); + } + + // 创建主表(并发下撞 uk_check_no 唯一键时自动重取单号,最多重试 5 次) + const maxCreateRetries = 5; + let record = null; + for (let attempt = 1; attempt <= maxCreateRetries; attempt++) { + const checkNo = await this.generateCheckNo(); + try { + record = await ctx.model.StockCheck.create({ + warehouse_id: normalizedWarehouseId, + check_no: checkNo, + title: normalizedTitle, + type: pattern.type, + mode: normalizedMode, + store_id: null, + is_static: normalizedIsStatic, + scope_snapshot: null, + status: 'submitted', + detail_status: 'none_checked', + creator_id: creatorId ? Number(creatorId) : 0, + creator_name: creatorName || null, + remark: remark ? String(remark).trim() : null, + total_items: 0, + }); + break; + } catch (error) { + if (this.isCheckNoDuplicateError(error) && attempt < maxCreateRetries) { + ctx.logger.warn(`[StockCheckPatternCreateRetry] check_no 冲突,准备重试第 ${attempt + 1} 次`, { + warehouse_id: normalizedWarehouseId, + pattern_id: pattern.id, + }); + continue; + } + throw error; + } + } + + // 明细写入(goods 型按商品快照,location 型按库位) + const toCreate = []; + if (pattern.type === 'goods') { + await this._addGoodsDetailRows({ + checkId: record.id, + check: record, + warehouseId: normalizedWarehouseId, + numericStockIds: stockIds, + toCreate, + skippedItems: [], + invalidStockIds: [], + }); + } else { + const codes = [ ...new Set( + locations + .map(location => String(location && location.location_code || '').trim()) + .filter(Boolean) + ) ]; + await this._addLocationDetailRows({ + checkId: record.id, + warehouseId: normalizedWarehouseId, + codes, + toCreate, + skippedItems: [], + invalidLocations: [], + }); + } + if (toCreate.length > 0) { + await ctx.model.StockCheckDetail.bulkCreate(toCreate); + } + + // 重算并更新主表 total_items(商品范围按商品计数,库位范围按明细行计数) + const scopeSummary = await this._countScopeSummary(record.id); + const totalItems = scopeSummary.total_items; + await record.update({ total_items: totalItems }); + const plainRecord = record.get({ plain: true }); + + // static 定式:任务创建成功后写入静态盘点任务关联记录(失败不影响主流程) + if (pattern.id === 'static' && stockIds.length > 0) { + try { + await ctx.model.StockStaticCheckTask.bulkCreate( + stockIds.map(stockId => ({ + stock_id: Number(stockId), + task_time: new Date(), + })) + ); + } catch (error) { + ctx.logger.warn( + `[StockCheckPatternCreate] 写入静态盘点任务关联记录失败 pattern=${pattern.id}: ${error && error.message}` + ); + } + } + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: plainRecord.id, + operationCode: 'STOCK_CHECK_CREATE', + operationAction: 'CREATE', + changeSummary: `按定式创建盘点任务:单号 ${plainRecord.check_no},定式 ${pattern.name}(${pattern.id}),范围类型 ${STOCK_CHECK_TYPE_LABELS[pattern.type]},盘点方式 ${STOCK_CHECK_MODE_LABELS[normalizedMode]}${normalizedIsStatic ? ',静态盘点' : ''}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: normalizedWarehouseId, + patternId: pattern.id, + checkNo: plainRecord.check_no, + total_items: totalItems, + message: `按定式创建盘点任务 ${plainRecord.check_no}(${pattern.name}/${pattern.id})`, + }, + }); + + return { + check: this._formatCheckRow(plainRecord), + total_items: totalItems, + pattern_id: pattern.id, + }; + } + + /** + * 添加盘点明细(商品或库位,按任务盘点类型决定)。 + * 仅 created/rejected 状态允许;store/goods 类型按 stock_ids 添加商品行(商品必须属于 + * 任务货主);location 类型按 locations(库位编码,兼容旧调用)或 location_ids + * (库位ID,直接查库校验,不再解析编码)添加库位行,两者都传时 location_ids 优先、 + * locations 忽略;location 未传库位且未传库位ID时自动拉取全仓库启用库位(原全盘语义); + * 已存在的同盘点项跳过(幂等),重算主表 total_items。 + * + * @param {Object} params 添加明细参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number|Array} [params.stockIds] 商品库存ID列表(wms_stock_warehouse.id,按商品盘点类型使用)。 + * @param {string|Array} [params.locations] 库位编码列表(按库位盘点类型使用,兼容旧调用; + * 与 locationIds 同时传入时被忽略)。 + * @param {number|Array} [params.locationIds] 库位ID列表(wms_location_space.id,按库位盘点类型使用; + * 与 locations 同时传入时优先使用)。 + * @return {Promise} { added, skipped, invalid_stock_ids, invalid_locations, invalid_location_ids, total_items }。 + * @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。 + */ + async addDetail(params = {}) { + const { warehouseId, id, stockIds, locations, locationIds } = params; + const { ctx } = this; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!ADD_DETAIL_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许添加明细`); + } + + const checkType = String(check.type || 'location').trim(); + const isGoodsScope = checkType === 'store' || checkType === 'goods'; + const isLocationScope = checkType === 'location'; + if (!isGoodsScope && !isLocationScope) { + throw this.createBusinessError(`盘点范围类型不合法(${checkType})`); + } + const numericStockIds = this._normalizeIdList(stockIds); + const locationCodes = this._normalizeCodeList(locations); + const numericLocationIds = this._normalizeIdList(locationIds); + + // 按盘点类型校验入参维度(商品与库位互斥) + if (isGoodsScope && locationCodes.length > 0) { + throw this.createBusinessError('当前盘点类型按商品盘点,请传 stock_ids'); + } + if (isGoodsScope && numericLocationIds.length > 0) { + throw this.createBusinessError('当前盘点类型按商品盘点,不能添加库位明细'); + } + if (isLocationScope && numericStockIds.length > 0) { + throw this.createBusinessError('当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)'); + } + + const toCreate = []; + const skippedItems = []; + const invalidStockIds = []; + const invalidLocations = []; + const invalidLocationIds = []; + + if (isGoodsScope) { + if (numericStockIds.length === 0) { + throw this.createBusinessError('请至少选择一个商品'); + } + await this._addGoodsDetailRows({ + checkId, + check, + warehouseId, + numericStockIds, + toCreate, + skippedItems, + invalidStockIds, + }); + } else if (isLocationScope) { + // location_ids 优先:两者都传时忽略 locations,直接按 ID 查库校验(不再解析编码) + if (numericLocationIds.length > 0) { + await this._addLocationRowsByIds({ + checkId, + warehouseId, + numericLocationIds, + toCreate, + skippedItems, + invalidLocationIds, + }); + } else { + let codes = locationCodes; + // 未显式传库位时自动拉取全仓库启用库位(原全盘语义); + // 排除无头库位:zone 必须存在且未删除 + if (codes.length === 0) { + const enabledSpaces = await ctx.model.LocationSpace.findAll({ + where: { warehouse_id: Number(warehouseId), is_enabled: true }, + attributes: [ 'space_code' ], + include: [{ + model: ctx.model.LocationZone, + as: 'zone', + attributes: [], + required: true, + }], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + codes = [ ...new Set(enabledSpaces + .map(space => String(space.space_code || '').trim()) + .filter(Boolean)) ]; + if (codes.length === 0) { + throw this.createBusinessError('当前仓库没有启用库位,无法按全盘自动生成盘点范围'); + } + } + await this._addLocationDetailRows({ + checkId, + warehouseId, + codes, + toCreate, + skippedItems, + invalidLocations, + }); + } + } + + if (toCreate.length > 0) { + await ctx.model.StockCheckDetail.bulkCreate(toCreate); + } + + // 重算主表 total_items(商品范围按商品计数,库位范围按明细行计数) + const scopeSummary = await this._countScopeSummary(checkId); + const totalItems = scopeSummary.total_items; + await check.update({ total_items: totalItems }); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_ADD_DETAIL', + operationAction: 'UPDATE', + changeSummary: `添加盘点明细:新增 ${toCreate.length},跳过 ${skippedItems.length},无效商品 ${invalidStockIds.length},无效库位 ${invalidLocations.length},无效库位ID ${invalidLocationIds.length}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + added: toCreate.length, + skipped: skippedItems.length, + invalidStockIds, + invalidLocations, + invalidLocationIds, + message: `添加盘点明细 ${toCreate.length} 条,跳过 ${skippedItems.length} 条`, + }, + }); + + return { + added: toCreate.length, + skipped: skippedItems.length, + invalid_stock_ids: invalidStockIds, + invalid_locations: invalidLocations, + invalid_location_ids: invalidLocationIds, + total_items: totalItems, + }; + } + + /** + * 批量添加库位明细(兼容入口,薄封装转调 addDetail 的库位ID直查路径)。 + * 入参库位ID列表,服务端直接按 ID 查库校验,不经过 space_code 二次解析; + * 转发前保留旧口径的参数校验(任务ID不能为空、库位ID不能为空、单次上限 200), + * 任务存在性/状态/类型分派校验统一由 addDetail 处理; + * 返回结构从 addDetail 映射为 { added, skipped, invalid_location_ids, total_items } + * (过滤 invalid_locations/invalid_stock_ids),保持原返回口径不变。 + * + * @param {Object} params 批量添加库位明细参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number|Array} params.locationIds 库位ID列表(wms_location_space.id,单次上限 200)。 + * @return {Promise} { added, skipped, invalid_location_ids, total_items }。 + * @throws {Error} 参数非法或状态不允许时抛出业务错误(错误码 400): + * - 盘点任务ID不能为空 + * - 请至少选择一个库位 + * - 单次最多添加 200 个库位 + * 其余校验(任务不存在/状态不允许/商品任务不可添加库位明细)由 addDetail 透传同款错误。 + */ + async addLocationDetail(params = {}) { + const { warehouseId, id, locationIds } = params; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + // 库位ID归一化(去重正整数)与数量上限校验(保留旧口径,转发前拦截) + const numericLocationIds = this._normalizeIdList(locationIds); + if (numericLocationIds.length === 0) { + throw this.createBusinessError('请至少选择一个库位'); + } + if (numericLocationIds.length > STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS) { + throw this.createBusinessError(`单次最多添加 ${STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS} 个库位`); + } + + // 转调 addDetail(库位ID直查路径,空 stockIds/locations),过滤出兼容返回结构 + const result = await this.addDetail({ + warehouseId, + id, + stockIds: [], + locations: [], + locationIds: numericLocationIds, + }); + + return { + added: result.added, + skipped: result.skipped, + invalid_location_ids: result.invalid_location_ids, + total_items: result.total_items, + }; + } + + /** + * 生成按商品盘点明细的待创建行(store/goods 类型)。 + * 商品必须属于当前仓库;任务货主非空时商品货主必须与任务货主一致,否则记入 invalidStockIds; + * 已存在同 check_id+stock_id 的明细跳过(幂等)。 + * + * @param {Object} params 生成参数。 + * @param {number} params.checkId 盘点任务ID。 + * @param {Object} params.check 盘点主表模型实例(含 store_id)。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.numericStockIds 归一化后的商品ID列表。 + * @param {Array} params.toCreate 待创建行收集数组(原地追加)。 + * @param {Array} params.skippedItems 跳过项收集数组(原地追加)。 + * @param {Array} params.invalidStockIds 非法商品ID收集数组(原地追加)。 + * @return {Promise} 无返回值。 + */ + async _addGoodsDetailRows(params = {}) { + const { + checkId, + check, + warehouseId, + numericStockIds, + toCreate, + skippedItems, + invalidStockIds, + } = params; + const { ctx } = this; + const { Op, literal } = ctx.app.Sequelize; + + // 按 stock_ids 查询库存商品快照(限定当前仓库,自动过滤已删除) + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: numericStockIds }, + warehouse_id: Number(warehouseId), + }, + raw: true, + }); + const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); + + // 幂等:已存在同 stock_id 的明细跳过(同商品整体跳过,兼容历史单行与拆行) + const existingRows = await ctx.model.StockCheckDetail.findAll({ + where: { + check_id: checkId, + stock_id: { [Op.in]: numericStockIds }, + }, + attributes: [ 'stock_id' ], + raw: true, + }); + const existingStockIds = new Set(existingRows.map(item => Number(item.stock_id))); + + // 商品在本仓库的启用库存库位(按库位拆分明细行:商品任务必须按库位盘点, + // 一个商品多个库位对应多行,各行账面 = 该库位库存 SUM(可用数量);无库存库位商品不可盘点; + // 库位有效性:仅统计有效库位(所属 zone 存在且未删除),无头库位(zone 不存在/已删除)不纳入盘点) + const storageRows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: Number(warehouseId), + stock_id: { [Op.in]: numericStockIds }, + is_enabled: 1, + space_id: { + [Op.in]: literal(VALID_SPACE_SQL), + }, + }, + attributes: [ + 'stock_id', + 'space_id', + [ literal('SUM(available_quantity)'), 'totalQuantity' ], + ], + group: [ 'stock_id', 'space_id' ], + raw: true, + }); + const stockStorageMap = new Map(); + for (const storageRow of storageRows) { + const stockId = Number(storageRow.stock_id); + if (!stockStorageMap.has(stockId)) { + stockStorageMap.set(stockId, []); + } + stockStorageMap.get(stockId).push({ + spaceId: Number(storageRow.space_id), + quantity: Number(storageRow.totalQuantity) || 0, + }); + } + const storageSpaceIds = [ ...new Set(storageRows.map(row => Number(row.space_id))) ]; + let spaceCodeMap = new Map(); + if (storageSpaceIds.length > 0) { + const spaceRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [Op.in]: storageSpaceIds } }, + attributes: [ 'id', 'space_code' ], + raw: true, + }); + spaceCodeMap = new Map(spaceRows.map(item => [ Number(item.id), String(item.space_code || '').trim() ])); + } + + // 货主限制:任务货主非空时,商品货主必须与任务货主一致(限制非本货主商品加入盘点) + const checkStoreId = check.store_id !== null && check.store_id !== undefined + ? Number(check.store_id) + : 0; + + for (const stockId of numericStockIds) { + const stock = stockMap.get(stockId); + if (!stock) { + invalidStockIds.push(stockId); + continue; + } + if (checkStoreId > 0 && Number(stock.store_id) !== checkStoreId) { + invalidStockIds.push(stockId); + continue; + } + if (existingStockIds.has(stockId)) { + skippedItems.push(stockId); + continue; + } + const stockLocations = stockStorageMap.get(stockId) || []; + if (stockLocations.length === 0) { + // 商品在仓库中没有启用库存库位 → 不可加入盘点 + invalidStockIds.push(stockId); + continue; + } + for (const stockLocation of stockLocations) { + toCreate.push({ + check_id: checkId, + warehouse_id: Number(warehouseId), + scope_type: 'goods', + stock_id: stockId, + item_code: stock.item_code, + item_name: stock.item_name || null, + spec: stock.sku_property || null, + batch_no: null, + system_quantity: stockLocation.quantity, + location_id: stockLocation.spaceId, + location_code: spaceCodeMap.get(stockLocation.spaceId) || null, + }); + } + } + } + + /** + * 生成按库位盘点明细的待创建行(location 类型)。 + * 按 space_code 匹配 wms_location_space(warehouse_id + space_code), + * 不存在的编码记入 invalidLocations;已存在同 check_id+location_code 的明细跳过(幂等)。 + * + * @param {Object} params 生成参数。 + * @param {number} params.checkId 盘点任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.codes 归一化后的库位编码列表。 + * @param {Array} params.toCreate 待创建行收集数组(原地追加)。 + * @param {Array} params.skippedItems 跳过项收集数组(原地追加)。 + * @param {Array} params.invalidLocations 非法库位编码收集数组(原地追加)。 + * @return {Promise} 无返回值。 + */ + async _addLocationDetailRows(params = {}) { + const { checkId, warehouseId, codes, toCreate, skippedItems, invalidLocations } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const spaceRows = await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: Number(warehouseId), + space_code: { [Op.in]: codes }, + }, + attributes: [ 'id', 'space_code' ], + // 库位有效性:zone 必须存在且未删除(无头库位记入 invalidLocations,与不存在同口径) + include: [{ + model: ctx.model.LocationZone, + as: 'zone', + attributes: [], + required: true, + }], + raw: true, + }); + const spaceByCode = new Map(spaceRows.map(item => [ String(item.space_code), item ])); + + // 幂等:已存在同 location_code 的明细跳过 + const existingRows = await ctx.model.StockCheckDetail.findAll({ + where: { + check_id: checkId, + location_code: { [Op.in]: codes }, + }, + attributes: [ 'location_code' ], + raw: true, + }); + const existingLocationCodes = new Set(existingRows + .map(item => String(item.location_code || '').trim()) + .filter(Boolean)); + + for (const code of codes) { + const space = spaceByCode.get(code); + if (!space) { + invalidLocations.push(code); + continue; + } + if (existingLocationCodes.has(code)) { + skippedItems.push(code); + continue; + } + toCreate.push({ + check_id: checkId, + warehouse_id: Number(warehouseId), + scope_type: 'location', + stock_id: null, + item_code: null, + item_name: null, + spec: null, + batch_no: null, + system_quantity: 0, + location_id: Number(space.id), + location_code: String(space.space_code), + }); + } + } + + /** + * 生成按库位盘点明细的待创建行(库位ID直查路径,location 类型)。 + * 直接按 wms_location_space.id 查库校验(warehouse_id 仓库隔离),不经过 space_code 二次解析; + * 查不到的 ID 记入 invalidLocationIds(不报错);库位编码为空(脏数据)或已存在 + * 同 check_id+location_code 的明细跳过(uk_check_location 唯一索引口径,幂等), + * 跳过项按库位ID记入 skippedItems;供 addDetail 与 addLocationDetail 共用。 + * + * @param {Object} params 生成参数。 + * @param {number} params.checkId 盘点任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.numericLocationIds 归一化后的库位ID列表。 + * @param {Array} params.toCreate 待创建行收集数组(原地追加)。 + * @param {Array} params.skippedItems 跳过项收集数组(原地追加,记库位ID)。 + * @param {Array} params.invalidLocationIds 非法库位ID收集数组(原地追加)。 + * @return {Promise} 无返回值。 + */ + async _addLocationRowsByIds(params = {}) { + const { + checkId, + warehouseId, + numericLocationIds, + toCreate, + skippedItems, + invalidLocationIds, + } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + // 直接按 ID 查库校验(仓库隔离),查不到的 ID 记入 invalidLocationIds(不报错); + // 库位有效性:zone 必须存在且未删除(无头库位同样记入 invalidLocationIds) + const spaceRows = await ctx.model.LocationSpace.findAll({ + where: { + id: { [Op.in]: numericLocationIds }, + warehouse_id: Number(warehouseId), + }, + attributes: [ 'id', 'space_code' ], + include: [{ + model: ctx.model.LocationZone, + as: 'zone', + attributes: [], + required: true, + }], + raw: true, + }); + const spaceById = new Map(spaceRows.map(item => [ Number(item.id), item ])); + + // 幂等:已存在同 check_id+location_code 的明细跳过(uk_check_location 唯一索引口径) + const spaceCodes = [ ...new Set(spaceRows + .map(item => String(item.space_code || '').trim()) + .filter(Boolean)) ]; + const existingLocationCodes = new Set(); + if (spaceCodes.length > 0) { + const existingRows = await ctx.model.StockCheckDetail.findAll({ + where: { + check_id: checkId, + location_code: { [Op.in]: spaceCodes }, + }, + attributes: [ 'location_code' ], + raw: true, + }); + for (const row of existingRows) { + const code = String(row.location_code || '').trim(); + if (code) { + existingLocationCodes.add(code); + } + } + } + + for (const locationId of numericLocationIds) { + const space = spaceById.get(locationId); + if (!space) { + invalidLocationIds.push(locationId); + continue; + } + const spaceCode = String(space.space_code || '').trim(); + // 库位编码为空(脏数据)或已存在同库位明细行:跳过,避免撞 uk_check_location + if (!spaceCode || existingLocationCodes.has(spaceCode)) { + skippedItems.push(locationId); + continue; + } + existingLocationCodes.add(spaceCode); + toCreate.push({ + check_id: checkId, + warehouse_id: Number(warehouseId), + scope_type: 'location', + stock_id: null, + item_code: null, + item_name: null, + spec: null, + batch_no: null, + system_quantity: 0, + location_id: Number(space.id), + location_code: spaceCode, + }); + } + } + + /** + * 删除盘点明细(批量:从任务中移除一个或多个商品/库位范围行)。 + * 仅主表状态 created/rejected(ADD_DETAIL_ALLOWED_STATUSES)允许删除; + * 明细存在作业记录(wms_stock_check_record)时一并防御性删除(正常流程该状态不应有记录); + * 查不到的明细 ID 计入 skipped_ids 不报错;删除后重算主表 total_items。 + * 注意:响应结构由旧版 { detail_id, deleted, total_items } 变更为 + * { deleted_count, deleted_ids, skipped_ids, total_items }。 + * + * @param {Object} params 删除参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {Array|number} params.detailIds 盘点明细ID数组(单值自动转数组,单次上限 200)。 + * @return {Promise} { deleted_count, deleted_ids, skipped_ids, total_items }; + * deleted_ids/skipped_ids 均保持入参顺序。 + * @throws {Error} 参数非法、任务不存在、状态不允许或明细为空/超限时抛出业务错误(错误码 400)。 + */ + async detailDelete(params = {}) { + const { warehouseId, id, detailIds } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!ADD_DETAIL_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许删除明细`); + } + + const numericDetailIds = this._normalizeIdList(detailIds); + if (numericDetailIds.length === 0) { + throw this.createBusinessError('请至少选择一个明细'); + } + if (numericDetailIds.length > 200) { + throw this.createBusinessError('单次最多删除 200 条明细'); + } + + // 仓库隔离查询明细:id in ids + check_id + warehouse_id;查不到的 ID 计入 skipped_ids(不报错) + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { + id: { [Op.in]: numericDetailIds }, + check_id: checkId, + warehouse_id: Number(warehouseId), + }, + attributes: [ 'id' ], + raw: true, + }); + const foundIdSet = new Set(detailRows.map(row => Number(row.id))); + const deletedIds = []; + const skippedIds = []; + for (const detailId of numericDetailIds) { + if (foundIdSet.has(detailId)) { + deletedIds.push(detailId); + } else { + skippedIds.push(detailId); + } + } + + if (deletedIds.length > 0) { + await ctx.model.StockCheckDetail.destroy({ + where: { id: { [Op.in]: deletedIds } }, + }); + + // 防御性处理:若这些明细存在作业记录(正常流程 created/rejected 不应有记录),一并删除 + await ctx.model.StockCheckRecord.destroy({ + where: { + detail_id: { [Op.in]: deletedIds }, + check_id: checkId, + warehouse_id: Number(warehouseId), + }, + }); + } + + // 删除明细后重算主表 total_items(商品范围按商品计数,库位范围按明细行计数) + const scopeSummary = await this._countScopeSummary(checkId); + const totalItems = scopeSummary.total_items; + await check.update({ total_items: totalItems }); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_DELETE_DETAIL', + operationAction: 'UPDATE', + changeSummary: `删除盘点明细:单号 ${check.check_no},删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(warehouseId), + checkNo: check.check_no, + detailIds: deletedIds, + skippedIds, + deletedCount: deletedIds.length, + skippedCount: skippedIds.length, + message: `删除盘点明细:单号 ${check.check_no},删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`, + }, + }); + + return { + deleted_count: deletedIds.length, + deleted_ids: deletedIds, + skipped_ids: skippedIds, + total_items: totalItems, + }; + } + + /** + * 拉取盘点任务详情(只返回任务本身信息)。 + * 不返回明细范围行与盘点作业聚合(明细范围行/盘点结果请调用 result, + * 作业记录明细请调用 recordList,盘点作业数据请调用 workData)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { check },check 为盘点主表信息(_formatCheckRow 口径), + * 并附 profit_total(盘盈合计数量)/loss_total(盘亏合计数量,正数口径,与 finish 一致)。 + * @throws {Error} 任务不存在时抛出业务错误(错误码 400)。 + */ + async detail(params = {}) { + const { warehouseId, id } = params; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + + // 数量差异汇总(盘盈/盘亏数量,口径与 finish 一致;无作业记录时均为 0) + const diffSummary = await this._calcQuantityDiffSummary(checkId); + + return { + check: { + ...this._formatCheckRow(check.get({ plain: true })), + profit_total: diffSummary.profit_total, + loss_total: diffSummary.loss_total, + }, + }; + } + + /** + * 构建静态盘点锁定缓存键(按仓库维度)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {string} 缓存键。 + */ + _staticLockCacheKey(warehouseId) { + return `${STATIC_LOCK_CACHE_KEY_PREFIX}${Number(warehouseId) || 0}`; + } + + /** + * 查询「静态盘点锁定中」的库存商品列表(公共查询,供库存操作前判断是否可动)。 + * + * 口径:主表 is_static=1 且状态为 approved(审核完成)/checking(盘点作业中)的任务, + * 取其商品范围明细(scope_type=goods)的 stock_id 去重集合——即这些商品的库位正在静态盘点, + * 出入库/移库等库存操作应被限制;任务提交审核前(created/submitted/rejected)与 + * 已完成(completed)/已取消(cancelled)不锁定。 + * + * 缓存:结果按仓库维度缓存在 `stock_check:static_lock:{warehouseId}`(TTL 300 秒兜底, + * Redis 优先、不可用时降级进程内缓存);审核/完成/取消/批量删除等状态流转时**立即重建缓存** + * (不是简单删除再等下次回源),空集合也会被缓存(不会因「当前没有锁定商品」反复回源)。 + * 同一进程内并发未命中用 singleflight 去重,只回源一次。返回 cached 标识本次是否命中缓存。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {boolean} [params.forceRefresh] 跳过缓存强制回源重建(内部/排障用)。 + * @return {Promise} { warehouse_id, stock_ids, rows, total, cached, updated_at }; + * rows 每个 stock_id 一条:{ stock_id, item_code, item_name, check_ids, check_nos, location_codes }。 + */ + async staticLockList(params = {}) { + const { warehouseId, forceRefresh } = params; + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + const cacheKey = this._staticLockCacheKey(normalizedWarehouseId); + if (forceRefresh !== true && forceRefresh !== 'true' && forceRefresh !== 1) { + const cachedPayload = await this._readStaticLockCache(cacheKey); + if (cachedPayload) { + return cachedPayload; + } + } + + const payload = await this._loadStaticLockCache(normalizedWarehouseId); + return payload; + } + + /** + * 读取锁定缓存(命中时补齐 cached=true)。 + * + * @param {string} cacheKey 缓存键。 + * @return {Promise} 缓存载荷(已格式化)或 null。 + */ + async _readStaticLockCache(cacheKey) { + const { ctx } = this; + const cachedPayload = await ctx.app.getCacheAsync(cacheKey); + if (!cachedPayload || !Array.isArray(cachedPayload.rows)) { + return null; + } + return { + warehouse_id: Number(cachedPayload.warehouse_id) || 0, + stock_ids: cachedPayload.stock_ids || [], + rows: cachedPayload.rows, + total: cachedPayload.rows.length, + cached: true, + updated_at: cachedPayload.updated_at || null, + }; + } + + /** + * 回源数据库并写入缓存(进程内 singleflight:同仓库并发未命中只回源一次)。 + * + * 防脏读(写缓存乐观锁):回源前后各读一次「锁定代次」(状态流转时由 + * refreshStaticLockCache 递增),两次不一致说明查询期间有并发状态流转, + * 本次结果可能是旧快照 → **放弃写入缓存**(删除缓存,交给下一次查询/该次流转的重建), + * 避免用旧快照覆盖新缓存。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 格式化后的载荷(cached=false;未写缓存时同样带 skipped_write 标识)。 + */ + async _loadStaticLockCache(warehouseId) { + const { ctx } = this; + const cacheKey = this._staticLockCacheKey(warehouseId); + const inflight = STATIC_LOCK_INFLIGHT.get(cacheKey); + if (inflight) { + return inflight; + } + + const task = (async () => { + const generationBefore = await this._readStaticLockGeneration(warehouseId); + const rows = await this._queryStaticLockRows(warehouseId); + const generationAfter = await this._readStaticLockGeneration(warehouseId); + const payload = { + warehouse_id: Number(warehouseId), + stock_ids: rows.map(row => row.stock_id), + rows, + updated_at: new Date().toISOString(), + }; + + if (generationBefore !== generationAfter) { + // 查询期间有状态流转:不写入旧快照,删掉缓存让下一次读取回源 + ctx.logger.warn(`[StockCheckStaticLock] 回源期间发生状态流转,跳过写缓存 warehouse=${warehouseId}(gen ${generationBefore} → ${generationAfter})`); + await this.clearStaticLockCache(warehouseId); + return { + ...payload, + total: rows.length, + cached: false, + cache_skipped: true, + }; + } + + await ctx.app.setCacheAsync(cacheKey, payload, STATIC_LOCK_CACHE_TTL_SECONDS); + return { + ...payload, + total: rows.length, + cached: false, + }; + })(); + + STATIC_LOCK_INFLIGHT.set(cacheKey, task); + try { + return await task; + } finally { + STATIC_LOCK_INFLIGHT.delete(cacheKey); + } + } + + /** + * 查询静态锁定商品行(数据库口径,无缓存):is_static=1 且 approved/checking 任务的商品明细。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 按 stock_id 升序的聚合行。 + */ + async _queryStaticLockRows(warehouseId) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const checkRows = await ctx.model.StockCheck.findAll({ + where: { + warehouse_id: Number(warehouseId), + is_static: 1, + status: { [Op.in]: STATIC_LOCK_ALLOWED_STATUSES }, + }, + attributes: [ 'id', 'check_no' ], + raw: true, + }); + if (checkRows.length === 0) { + return []; + } + + const checkNoById = new Map(checkRows.map(row => [ Number(row.id), String(row.check_no || '') ])); + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { + check_id: { [Op.in]: [ ...checkNoById.keys() ] }, + scope_type: 'goods', + }, + attributes: [ 'check_id', 'stock_id', 'item_code', 'item_name', 'location_code' ], + raw: true, + }); + + const aggByStock = new Map(); + for (const detailRow of detailRows) { + const stockId = Number(detailRow.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const agg = aggByStock.get(stockId) || { + stock_id: stockId, + item_code: detailRow.item_code || null, + item_name: detailRow.item_name || null, + check_ids: [], + check_nos: [], + location_codes: [], + }; + const detailCheckId = Number(detailRow.check_id); + if (!agg.check_ids.includes(detailCheckId)) { + agg.check_ids.push(detailCheckId); + agg.check_nos.push(checkNoById.get(detailCheckId) || ''); + } + const locationCode = String(detailRow.location_code || '').trim(); + if (locationCode && !agg.location_codes.includes(locationCode)) { + agg.location_codes.push(locationCode); + } + aggByStock.set(stockId, agg); + } + + return [ ...aggByStock.values() ].sort((left, right) => left.stock_id - right.stock_id); + } + + /** + * 重建静态盘点锁定缓存(状态流转后立即同步,避免「删除缓存 → 下次查询才回源」的空窗)。 + * 顺序:先递增锁定代次(使并发回源中的旧快照自动作废)→ 回源 → 写回缓存; + * 重建失败时降级为删除缓存(下次查询回源),并记录 warn 日志,不影响主流程。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async refreshStaticLockCache(warehouseId) { + const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return; + } + try { + // 代次必须在回源查询之前递增:并发中的旧回源读到代次变化会放弃写缓存 + await this._bumpStaticLockGeneration(normalizedWarehouseId); + await this._loadStaticLockCache(normalizedWarehouseId); + } catch (error) { + ctx.logger.warn(`[StockCheckStaticLock] 重建静态锁定缓存失败 warehouse=${normalizedWarehouseId}: ${error && error.message}`); + await this.clearStaticLockCache(normalizedWarehouseId); + } + } + + /** + * 构建锁定代次缓存键(状态流转时递增,用于回源前后一致性校验)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {string} 代次键。 + */ + _staticLockGenerationKey(warehouseId) { + return `${STATIC_LOCK_GENERATION_KEY_PREFIX}${Number(warehouseId) || 0}`; + } + + /** + * 读取锁定代次(Redis 不可用时回退进程内计数)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 代次值(无记录为 0)。 + */ + async _readStaticLockGeneration(warehouseId) { + const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId); + const redis = ctx.app.redis && typeof ctx.app.redis.get === 'function' ? ctx.app.redis.get('cache') : null; + if (redis && typeof redis.get === 'function') { + try { + const value = await redis.get(this._staticLockGenerationKey(normalizedWarehouseId)); + if (value !== null && value !== undefined) { + return Number(value) || 0; + } + } catch (error) { + ctx.logger.warn(`[StockCheckStaticLock] 读取锁定代次失败,回退进程内计数 warehouse=${normalizedWarehouseId}: ${error && error.message}`); + } + } + return STATIC_LOCK_GENERATION_LOCAL.get(normalizedWarehouseId) || 0; + } + + /** + * 递增锁定代次(Redis INCR 原子递增;不可用时退化为进程内计数)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 递增后的代次值。 + */ + async _bumpStaticLockGeneration(warehouseId) { + const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId); + const redis = ctx.app.redis && typeof ctx.app.redis.get === 'function' ? ctx.app.redis.get('cache') : null; + if (redis && typeof redis.incr === 'function') { + try { + const value = await redis.incr(this._staticLockGenerationKey(normalizedWarehouseId)); + return Number(value) || 0; + } catch (error) { + ctx.logger.warn(`[StockCheckStaticLock] 递增锁定代次失败,回退进程内计数 warehouse=${normalizedWarehouseId}: ${error && error.message}`); + } + } + const nextValue = (STATIC_LOCK_GENERATION_LOCAL.get(normalizedWarehouseId) || 0) + 1; + STATIC_LOCK_GENERATION_LOCAL.set(normalizedWarehouseId, nextValue); + return nextValue; + } + + /** + * 删除静态盘点锁定缓存(Redis 与进程内缓存同时清理;下次查询回源重建)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async clearStaticLockCache(warehouseId) { + const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return; + } + try { + await ctx.app.delCacheAsync(this._staticLockCacheKey(normalizedWarehouseId)); + } catch (error) { + ctx.logger.warn(`[StockCheckStaticLock] 清除静态锁定缓存失败 warehouse=${normalizedWarehouseId}: ${error && error.message}`); + } + } + + /** + * 判断指定商品当前是否处于静态盘点锁定中(供库存操作前置校验,读缓存)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number|Array} params.stockId 商品库存ID(单值或数组)。 + * @return {Promise} { locked, locked_stock_ids, rows, cached }; + * locked=true 表示至少有一个商品在锁定集合中;rows 仅返回命中的商品行。 + */ + async isStockStaticLocked(params = {}) { + const { warehouseId, stockId } = params; + + const stockIds = this._normalizeIdList(stockId); + if (stockIds.length === 0) { + throw this.createBusinessError('商品ID不能为空'); + } + + const lockList = await this.staticLockList({ warehouseId }); + const stockIdSet = new Set(stockIds.map(id => Number(id))); + const hitRows = lockList.rows.filter(row => stockIdSet.has(Number(row.stock_id))); + + return { + locked: hitRows.length > 0, + locked_stock_ids: hitRows.map(row => Number(row.stock_id)), + rows: hitRows, + cached: lockList.cached, + }; + } + + /** + * 查询商品是否被静态盘点锁定,并生成可直接返回/抛出的冲突文案(供库存操作前置拦截)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number|Array} params.stockIds 商品库存ID(单值或数组)。 + * @param {string} [params.actionLabel] 被禁止的操作名(用于文案,如「移库」「分配储位」)。 + * @return {Promise} { locked, rows, message };locked=false 时 rows 为空数组、message 为空串。 + */ + async getStaticLockConflict(params = {}) { + const { warehouseId, stockIds, actionLabel } = params; + + const normalizedStockIds = this._normalizeIdList(stockIds); + if (normalizedStockIds.length === 0) { + return { locked: false, rows: [], message: '' }; + } + + const result = await this.isStockStaticLocked({ warehouseId, stockId: normalizedStockIds }); + if (!result.locked) { + return { locked: false, rows: [], message: '' }; + } + + const actionText = String(actionLabel || '该操作').trim() || '该操作'; + const detailText = result.rows + .map(row => { + const stockText = row.item_code ? `${row.item_code}(${row.stock_id})` : String(row.stock_id); + const checkNos = (Array.isArray(row.check_nos) ? row.check_nos : []).filter(Boolean).join('/'); + return checkNos ? `${stockText} 盘点单 ${checkNos}` : stockText; + }) + .join(';'); + + return { + locked: true, + rows: result.rows, + message: `商品正在静态盘点中,禁止${actionText}:${detailText}`, + }; + } + + /** + * 收集任务商品范围明细覆盖的商品ID(去重升序),用于完成/释放锁定追溯。 + * + * @param {number} checkId 盘点任务ID。 + * @return {Promise>} 商品库存ID列表(升序;库位任务为空数组)。 + */ + async _collectGoodsStockIds(checkId) { + const { ctx } = this; + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: Number(checkId), scope_type: 'goods' }, + attributes: [ 'stock_id' ], + raw: true, + }); + return [ ...new Set(detailRows + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ] + .sort((left, right) => left - right); + } + + /** + * 拉取盘点明细结果(后台查看明细口径,仅展示盘点前/盘点后明细使用)。 + * 任务尚无作业记录(盘点前,如 created/rejected/submitted 待提交状态)时,rows 直接返回 + * wms_stock_check_detail 明细范围行原始数据(商品/库位/商品快照/账面快照),供后台查看盘点范围; + * 存在作业记录后,商品范围(scope_type=goods)按商品合并输出(一个商品一行,多个库位明细行合并), + * 行内 locations 输出该商品所在库位与账面快照数量;库位范围(scope_type=location) + * 按明细行输出,行内按商品聚合作业记录并从 wms_storage 补齐账面数量。 + * 未知商品(记录 stock_id 为空)按 barcode 维度归组,行级额外输出 unknown_items; + * 每条作业记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { check, rows, total };无作业记录时 rows=wms_stock_check_detail 明细范围行 + * (id/check_id/warehouse_id/scope_type/stock_id/location_id/location_code/item_code/item_name/spec/ + * batch_no/system_quantity/remark/created_at/updated_at,total=明细行数,check 为主表信息); + * 有作业记录时:商品范围按商品聚合(一个商品一行): + * 行含商品快照(item_code/item_name/spec/batch_no)+ system_quantity(账面快照合计)+ 已盘聚合 + * (checked_quantity=记录数量合计、diff_quantity=实盘-账面快照合计、is_diff、status、location_codes、 + * checkers、last_checked_at)、records(该商品全部作业记录,每条含 barcode/item_name/images)与 + * locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }]—— + * system_quantity 为该库位账面快照(创建明细时落库,盘点时做快照)、quantity 为该库位实盘合计 + * (未盘库位为 0),仅作业记录存在而快照不存在的库位追加在末尾(system_quantity=0)); + * 库位范围行输出 { ...row, scope_type: 'location', stocks },stocks 按商品聚合该明细下记录 + * [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }], + * 账面数量查 wms_storage SUM(available_quantity)(=可用数量,不含锁定待出库),行级 checked_quantity 为行内合计、 + * diff_quantity 为行内各商品差异代数和; + * 未知商品单独输出行级 unknown_items [{ barcode, item_name, checked_quantity }] + * (无账面,差异 = 实盘 - 0 = 盘盈,已计入行级 checked_quantity/diff_quantity/is_diff)。 + * @throws {Error} 任务不存在时抛出业务错误(错误码 400)。 + */ + async result(params = {}) { + const { warehouseId, id } = params; + const { ctx } = this; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const records = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 盘点前(尚无作业记录,如待提交状态):直接返回明细范围行(wms_stock_check_detail), + // 供后台查看盘点范围明细(本接口不再作为盘点作业数据提供) + if (records.length === 0) { + return { + check: this._formatCheckRow(check.get({ plain: true })), + rows: detailRows, + total: detailRows.length, + }; + } + + // 挂载作业记录图片(FileReference business_type=stock_check_record,与收货 receivingItem 口径一致) + await this._attachRecordImages(records); + + const rows = await this._buildDetailAggregations({ detailRows, recordRows: records }); + + // 主表计数按聚合行口径同步输出(商品范围按商品计数):历史任务主表可能残留 + // 按库位拆行写入的 total_items/checked_items/diff_items,响应口径以聚合行为准 + const formattedCheck = this._formatCheckRow(check.get({ plain: true })); + formattedCheck.total_items = rows.length; + formattedCheck.checked_items = rows.filter(row => row.status === 'checked').length; + formattedCheck.diff_items = rows.filter(row => row.is_diff === 1).length; + + return { + check: formattedCheck, + rows, + total: rows.length, + }; + } + + /** + * 为盘点作业记录挂载图片列表(图片独立维护,仿收货 receivingItem 口径)。 + * 查询 wms_file_reference(business_type=stock_check_record,business_id in 记录ID)并关联 + * wms_file 取 file_url,每条记录挂载 images: [{ id: file_id, url }],无图片返回空数组; + * 直接修改传入记录对象的 images 字段,无返回值。 + * + * @param {Array} records 作业记录原始行(每条需含 id 字段)。 + * @return {Promise} 无返回值。 + */ + async _attachRecordImages(records = []) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const normalizedRecords = Array.isArray(records) ? records : []; + const recordIds = [ ...new Set(normalizedRecords + .map(record => Number(record && record.id)) + .filter(recordId => Number.isInteger(recordId) && recordId > 0)) ]; + if (recordIds.length === 0) { + return; + } + + const imageRefs = await ctx.model.FileReference.findAll({ + where: { + business_type: 'stock_check_record', + business_id: { [Op.in]: recordIds.map(String) }, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: true, + }], + order: [[ 'display_order', 'ASC' ], [ 'id', 'ASC' ]], + }); + + const imageMap = new Map(); + for (const ref of imageRefs) { + const businessId = String(ref.business_id); + if (!imageMap.has(businessId)) { + imageMap.set(businessId, []); + } + imageMap.get(businessId).push({ + id: ref.file_id, + url: ref.file ? ref.file.file_url : null, + }); + } + + for (const record of normalizedRecords) { + record.images = imageMap.get(String(record.id)) || []; + } + } + + /** + * 构建盘点明细聚合行。 + * 商品范围(scope_type=goods):按商品(stock_id)合并输出(一个商品一行,多个库位明细行合并)—— + * 行含账面快照合计与商品所在库位列表(每库位 system_quantity 账面快照 + quantity 实盘合计); + * 库位范围(scope_type=location):按明细行输出,行内按商品聚合作业记录, + * 并从 wms_storage 补齐各商品账面数量;未知商品按 barcode 维度归组输出 unknown_items。 + * + * @param {Object} params 聚合参数。 + * @param {Array} params.detailRows 明细原始行。 + * @param {Array} params.recordRows 作业记录原始行。 + * @return {Promise>} 格式化后的聚合行列表(按首条明细 id 升序)。 + */ + async _buildDetailAggregations(params = {}) { + const { detailRows, recordRows } = params; + const { ctx } = this; + const { Op, literal } = ctx.app.Sequelize; + + // 按明细聚合作业记录 + const recordsByDetail = new Map(); + for (const record of recordRows) { + const detailRowId = Number(record.detail_id); + if (!recordsByDetail.has(detailRowId)) { + recordsByDetail.set(detailRowId, []); + } + recordsByDetail.get(detailRowId).push(record); + } + + // 分拣:商品范围行按 stock_id 分组合并(按商品盘点一行一商品),库位范围行按明细行处理 + const locationRows = []; + const goodsGroups = new Map(); + for (const detailRow of detailRows) { + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + if (scopeType === 'location') { + locationRows.push(detailRow); + continue; + } + const stockId = Number(detailRow.stock_id); + if (!goodsGroups.has(stockId)) { + goodsGroups.set(stockId, []); + } + goodsGroups.get(stockId).push(detailRow); + } + + // 库位行需要:记录商品快照(wms_stock_warehouse)与库位账面(wms_storage 可用数量) + const stockIds = new Set(); + for (const detailRow of locationRows) { + const detailRecords = recordsByDetail.get(Number(detailRow.id)) || []; + for (const record of detailRecords) { + if (record.stock_id) { + stockIds.add(Number(record.stock_id)); + } + } + } + let stockMap = new Map(); + if (stockIds.size > 0) { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: [ ...stockIds ] } }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + raw: true, + }); + stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); + } + + // 库位行账面:wms_storage 按 (space_id, stock_id) SUM(可用数量) + const storageQuantityMap = new Map(); + if (locationRows.length > 0 && stockIds.size > 0) { + const locationIds = [ ...new Set(locationRows + .filter(row => row.location_id) + .map(row => Number(row.location_id))) ]; + if (locationIds.length > 0) { + const storageRows = await ctx.model.Storage.findAll({ + where: { + space_id: { [Op.in]: locationIds }, + stock_id: { [Op.in]: [ ...stockIds ] }, + }, + attributes: [ + 'space_id', + 'stock_id', + [ literal('SUM(available_quantity)'), 'totalQuantity' ], + ], + group: [ 'space_id', 'stock_id' ], + raw: true, + }); + for (const storageRow of storageRows) { + storageQuantityMap.set( + `${Number(storageRow.space_id)}_${Number(storageRow.stock_id)}`, + Number(storageRow.totalQuantity) || 0 + ); + } + } + } + + // 商品范围:按商品合并输出(账面快照按库位明细行汇总,实盘按作业记录聚合) + const formattedRows = []; + for (const groupRows of goodsGroups.values()) { + const row = this._formatMergedGoodsAggregationRow({ groupRows, recordsByDetail }); + formattedRows.push({ row, firstDetailId: Number(groupRows[0].id) }); + } + const locationFormatted = await Promise.all(locationRows.map(detailRow => this._formatDetailAggregationRow({ + detailRow, + recordsByDetail, + stockMap, + storageQuantityMap, + }))); + for (const item of locationFormatted) { + formattedRows.push({ row: item, firstDetailId: Number(item.id) }); + } + + return formattedRows + .sort((left, right) => left.firstDetailId - right.firstDetailId) + .map(item => item.row); + } + + /** + * 将同商品的多个库位明细行合并格式化为一条商品聚合输出行(按商品盘点一行一商品)。 + * 行含商品快照 + system_quantity(账面快照合计,各库位明细行 system_quantity 之和)+ + * locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }]: + * system_quantity 为该库位账面快照(创建明细时落库,盘点时做快照)、quantity 为该库位实盘合计 + * (未盘库位为 0;仅作业记录存在而快照不存在的库位追加在末尾,system_quantity=0))+ + * checked_quantity(作业记录数量合计)/diff_quantity(实盘-账面快照合计)/is_diff/status/location_codes/ + * checkers/last_checked_at/records/unknown_items,与库位范围行输出字段口径一致。 + * + * @param {Object} params 格式化参数。 + * @param {Array} params.groupRows 同商品明细原始行(按明细 id 升序)。 + * @param {Map>} params.recordsByDetail 按明细ID分组的作业记录。 + * @return {Object} 格式化后的商品聚合行。 + */ + _formatMergedGoodsAggregationRow(params = {}) { + const { groupRows, recordsByDetail } = params; + const firstRow = groupRows[0]; + + // 该商品全部作业记录(按明细 id 升序 → 记录 id 升序) + const detailRecords = []; + for (const groupRow of groupRows) { + const rows = recordsByDetail.get(Number(groupRow.id)) || []; + detailRecords.push(...rows); + } + + // 已盘聚合(与库位范围行口径一致) + const locationCodes = [ ...new Set(detailRecords + .map(record => String(record.location_code || '').trim()) + .filter(Boolean)) ]; + const checkers = [ ...new Set(detailRecords + .map(record => String(record.checker_name || '').trim()) + .filter(Boolean)) ]; + const lastCheckedAt = detailRecords.length > 0 + ? detailRecords[detailRecords.length - 1].checked_at + : null; + + // 未知商品(stock_id 为空)按 barcode 维度归组(无账面,差异 = 实盘 - 0 = 盘盈); + // 空库位标记记录不参与未知商品聚合 + const unknownByBarcode = new Map(); + for (const record of detailRecords) { + if (record.is_empty) { + continue; + } + const recordStockId = Number(record.stock_id); + if (Number.isInteger(recordStockId) && recordStockId > 0) { + continue; + } + const recordBarcode = String(record.barcode || '').trim() || null; + const barcodeKey = recordBarcode || 'unknown'; + const unknownAgg = unknownByBarcode.get(barcodeKey) || { + barcode: recordBarcode, + item_name: record.item_name || null, + checked: 0, + }; + unknownAgg.checked += Number(record.quantity) || 0; + unknownByBarcode.set(barcodeKey, unknownAgg); + } + const unknownItems = [ ...unknownByBarcode.values() ] + .sort((left, right) => String(left.barcode || '').localeCompare(String(right.barcode || ''))) + .map(agg => ({ + barcode: agg.barcode, + item_name: agg.item_name, + checked_quantity: agg.checked, + })); + + // 账面快照库位(创建明细时落库,盘点时做快照,按明细 id 升序) + const locations = groupRows.map(groupRow => ({ + location_id: groupRow.location_id !== null && groupRow.location_id !== undefined + ? Number(groupRow.location_id) + : null, + location_code: groupRow.location_code !== null && groupRow.location_code !== undefined + ? String(groupRow.location_code).trim() + : null, + system_quantity: Number(groupRow.system_quantity) || 0, + quantity: 0, + })); + const snapshotIndexByCode = new Map(); + const snapshotIndexByLocationId = new Map(); + locations.forEach((location, index) => { + if (location.location_code) { + snapshotIndexByCode.set(location.location_code, index); + } + if (location.location_id !== null && location.location_id !== undefined) { + snapshotIndexByLocationId.set(location.location_id, index); + } + }); + + // 按库位聚合作业记录(库位为空归入"无库位"分组,location_code 为 null),按首条记录 id 升序 + const locationGroups = new Map(); + for (const record of detailRecords) { + const recordLocationCode = record.location_code !== null && record.location_code !== undefined + ? String(record.location_code).trim() + : ''; + if (!locationGroups.has(recordLocationCode)) { + locationGroups.set(recordLocationCode, { + location_id: recordLocationCode ? (Number(record.location_id) || null) : null, + location_code: recordLocationCode || null, + quantity: 0, + first_record_id: Number(record.id) || 0, + }); + } + const locationGroup = locationGroups.get(recordLocationCode); + locationGroup.quantity += Number(record.quantity) || 0; + } + + // 已盘库位与账面快照库位合并:优先按库位编码匹配、其次按库位ID兜底; + // 未命中快照的已盘库位(商品移动后新出现的库位)追加在末尾 + const extraGroups = []; + for (const group of locationGroups.values()) { + const groupCode = group.location_code || ''; + let targetIndex = groupCode ? snapshotIndexByCode.get(groupCode) : undefined; + if (targetIndex === undefined && group.location_id !== null && group.location_id !== undefined) { + targetIndex = snapshotIndexByLocationId.get(group.location_id); + } + if (targetIndex === undefined) { + extraGroups.push(group); + continue; + } + const target = locations[targetIndex]; + target.quantity = group.quantity; + if ((target.location_id === null || target.location_id === undefined) && group.location_id != null) { + target.location_id = group.location_id; + } + if (!target.location_code && group.location_code) { + target.location_code = group.location_code; + } + } + extraGroups + .sort((left, right) => left.first_record_id - right.first_record_id) + .forEach(group => { + locations.push({ + location_id: group.location_id, + location_code: group.location_code, + system_quantity: 0, + quantity: group.quantity, + }); + }); + + const systemQuantity = locations.reduce((sum, location) => sum + location.system_quantity, 0); + const checkedQuantity = detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0); + const diffQuantity = checkedQuantity - systemQuantity; + + return { + ...firstRow, + scope_type: 'goods', + location_id: null, + location_code: null, + system_quantity: systemQuantity, + location_codes: locationCodes, + checkers, + last_checked_at: lastCheckedAt, + records: detailRecords, + locations, + checked_quantity: detailRecords.length > 0 ? checkedQuantity : null, + diff_quantity: detailRecords.length > 0 ? diffQuantity : null, + is_diff: detailRecords.length > 0 && diffQuantity !== 0 ? 1 : 0, + status: detailRecords.length > 0 ? 'checked' : 'unchecked', + unknown_items: unknownItems, + }; + } + + /** + * 将单条库位范围明细格式化为聚合输出行(商品范围行由 _formatMergedGoodsAggregationRow 合并处理)。 + * 按商品聚合作业记录输出 stocks 列表(含 wms_storage 账面与差异); + * 未知商品(记录 stock_id 为空)按 barcode 维度归组,行级输出 unknown_items: + * [{ barcode, item_name, checked_quantity }](无账面,差异 = 实盘 - 0 = 盘盈, + * 已计入行级 checked_quantity/diff_quantity/is_diff),stocks 保持只输出已知商品。 + * + * @param {Object} params 格式化参数。 + * @param {Object} params.detailRow 明细原始行。 + * @param {Map>} params.recordsByDetail 按明细ID分组的作业记录。 + * @param {Map} params.stockMap 商品快照映射。 + * @param {Map} params.storageQuantityMap 库位商品账面数量映射(键 `${space_id}_${stock_id}`)。 + * @return {Object} 格式化后的明细行。 + */ + async _formatDetailAggregationRow(params = {}) { + const { detailRow, recordsByDetail, stockMap, storageQuantityMap } = params; + const { ctx } = this; + const { literal } = ctx.app.Sequelize; + const detailRowId = Number(detailRow.id); + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + const detailRecords = recordsByDetail.get(detailRowId) || []; + + const locationCodes = [ ...new Set(detailRecords + .map(record => String(record.location_code || '').trim()) + .filter(Boolean)) ]; + const checkers = [ ...new Set(detailRecords + .map(record => String(record.checker_name || '').trim()) + .filter(Boolean)) ]; + const lastCheckedAt = detailRecords.length > 0 + ? detailRecords[detailRecords.length - 1].checked_at + : null; + + // 按库位聚合作业记录(库位为空归入"无库位"分组,location_code 为 null),按首条记录 id 升序 + const locationGroups = new Map(); + for (const record of detailRecords) { + const recordLocationCode = record.location_code !== null && record.location_code !== undefined + ? String(record.location_code).trim() + : ''; + if (!locationGroups.has(recordLocationCode)) { + locationGroups.set(recordLocationCode, { + location_id: recordLocationCode ? (Number(record.location_id) || null) : null, + location_code: recordLocationCode || null, + quantity: 0, + first_record_id: Number(record.id) || 0, + }); + } + const locationGroup = locationGroups.get(recordLocationCode); + locationGroup.quantity += Number(record.quantity) || 0; + } + const locations = [ ...locationGroups.values() ] + .sort((left, right) => left.first_record_id - right.first_record_id) + .map(locationGroup => ({ + location_id: locationGroup.location_id, + location_code: locationGroup.location_code, + quantity: locationGroup.quantity, + })); + + // 未知商品(stock_id 为空)按 barcode 维度归组(无账面,差异 = 实盘 - 0 = 盘盈); + // 空库位标记记录不参与未知商品聚合 + const unknownByBarcode = new Map(); + for (const record of detailRecords) { + if (record.is_empty) { + continue; + } + const recordStockId = Number(record.stock_id); + if (Number.isInteger(recordStockId) && recordStockId > 0) { + continue; + } + const recordBarcode = String(record.barcode || '').trim() || null; + const barcodeKey = recordBarcode || 'unknown'; + const unknownAgg = unknownByBarcode.get(barcodeKey) || { + barcode: recordBarcode, + item_name: record.item_name || null, + checked: 0, + }; + unknownAgg.checked += Number(record.quantity) || 0; + unknownByBarcode.set(barcodeKey, unknownAgg); + } + const unknownItems = [ ...unknownByBarcode.values() ] + .sort((left, right) => String(left.barcode || '').localeCompare(String(right.barcode || ''))) + .map(agg => ({ + barcode: agg.barcode, + item_name: agg.item_name, + checked_quantity: agg.checked, + })); + + const base = { + ...detailRow, + scope_type: scopeType, + location_codes: locationCodes, + checkers, + last_checked_at: lastCheckedAt, + records: detailRecords, + locations, + }; + + // 库位范围行:按商品聚合记录,账面从 wms_storage 取(location_id 为空时账面按 0); + // 空库位标记:无商品聚合,账面有库存即盘亏(差异 = -账面总量) + const isEmptyLocation = detailRecords.some(record => record.is_empty); + const locationId = detailRow.location_id !== null && detailRow.location_id !== undefined + ? Number(detailRow.location_id) + : 0; + let locationSystemTotal = 0; + if (isEmptyLocation && locationId > 0) { + const emptyStorageRows = await ctx.model.Storage.findAll({ + where: { space_id: locationId }, + attributes: [[ literal('SUM(available_quantity)'), 'totalQuantity' ]], + raw: true, + }); + locationSystemTotal = Number(emptyStorageRows[0] && emptyStorageRows[0].totalQuantity) || 0; + } + if (isEmptyLocation) { + return { + ...base, + is_empty: true, + checked_quantity: 0, + diff_quantity: locationSystemTotal > 0 ? -locationSystemTotal : 0, + is_diff: locationSystemTotal > 0 ? 1 : 0, + status: 'checked', + stocks: [], + unknown_items: unknownItems, + }; + } + + const quantityByStock = new Map(); + for (const record of detailRecords) { + const stockId = Number(record.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const agg = quantityByStock.get(stockId) || { checked: 0 }; + agg.checked += Number(record.quantity) || 0; + quantityByStock.set(stockId, agg); + } + let checkedQuantity = 0; + let diffQuantitySum = 0; + let hasDiff = false; + const stocks = [ ...quantityByStock.keys() ] + .sort((left, right) => left - right) + .map(stockId => { + const agg = quantityByStock.get(stockId); + const stock = stockMap.get(stockId) || {}; + const systemQuantity = locationId > 0 + ? (storageQuantityMap.get(`${locationId}_${stockId}`) || 0) + : 0; + const diffQuantity = agg.checked - systemQuantity; + checkedQuantity += agg.checked; + diffQuantitySum += diffQuantity; + if (diffQuantity !== 0) { + hasDiff = true; + } + return { + stock_id: stockId, + item_code: stock.item_code || null, + item_name: stock.item_name || null, + system_quantity: systemQuantity, + checked_quantity: agg.checked, + diff_quantity: diffQuantity, + }; + }); + + // 未知商品无账面:实盘全部计入行级已盘数量与盘盈差异(必然差异) + for (const agg of unknownByBarcode.values()) { + checkedQuantity += agg.checked; + diffQuantitySum += agg.checked; + if (agg.checked > 0) { + hasDiff = true; + } + } + + return { + ...base, + is_empty: false, + stocks, + unknown_items: unknownItems, + checked_quantity: detailRecords.length > 0 ? checkedQuantity : null, + diff_quantity: detailRecords.length > 0 ? diffQuantitySum : null, + is_diff: hasDiff ? 1 : 0, + status: detailRecords.length > 0 ? 'checked' : 'unchecked', + }; + } + + /** + * 按条码解析系统商品ID(未知商品上报回填用)。 + * 查询 wms_stock_barcodes 按 barcode + warehouse_id 匹配条码,再校验 wms_stock_warehouse + * 中该商品确实属于本仓库(StockBarcode 关联 StockWarehouse),命中返回 stock_id,未命中返回 0。 + * + * @param {string} barcodeValue 扫描到的条码/编码。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 命中的库存商品ID(wms_stock_warehouse.id),未命中返回 0。 + */ + async _resolveStockIdByBarcode(barcodeValue, warehouseId) { + const { ctx } = this; + const normalizedBarcode = String(barcodeValue || '').trim(); + if (!normalizedBarcode) { + return 0; + } + const barcodeRow = await ctx.model.StockBarcode.findOne({ + where: { barcode: normalizedBarcode, warehouse_id: Number(warehouseId) }, + attributes: [ 'stock_id' ], + raw: true, + }); + const matchedStockId = barcodeRow ? Number(barcodeRow.stock_id) : 0; + if (!Number.isInteger(matchedStockId) || matchedStockId <= 0) { + return 0; + } + const stockRow = await ctx.model.StockWarehouse.findOne({ + where: { id: matchedStockId, warehouse_id: Number(warehouseId) }, + attributes: [ 'id' ], + raw: true, + }); + return stockRow ? matchedStockId : 0; + } + + /** + * 按库位编码解析库位ID(仅命中分区存在且未删除的有效库位行)。 + * 同仓库同编码可能同时存在多条库位(历史重复库位、分区已删除的无头库位, + * 唯一索引含 deleted_at 且 NULL 不去重),此处取稳定口径: + * 优先该商品有启用库存的库位行,其次 ID 最小的有效行。 + * + * @param {number} warehouseId 仓库ID。 + * @param {string} locationCode 库位编码。 + * @param {number} [stockId] 商品库存ID(wms_stock_warehouse.id,用于优先命中库存所在库位)。 + * @return {Promise} 库位ID,未命中返回 0。 + */ + async _resolveLocationIdByCode(warehouseId, locationCode, stockId) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const normalizedCode = String(locationCode || '').trim(); + if (!normalizedCode) { + return 0; + } + const spaceRows = await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: Number(warehouseId), + space_code: normalizedCode, + }, + attributes: [ 'id' ], + // 库位有效性:zone 必须存在且未删除(无头库位不参与匹配) + include: [{ + model: ctx.model.LocationZone, + as: 'zone', + attributes: [], + required: true, + }], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const candidateIds = (Array.isArray(spaceRows) ? spaceRows : []) + .map(row => Number(row && row.id)) + .filter(id => Number.isInteger(id) && id > 0); + if (candidateIds.length === 0) { + return 0; + } + if (candidateIds.length === 1 || !(Number(stockId) > 0)) { + return candidateIds[0]; + } + const storageRow = await ctx.model.Storage.findOne({ + where: { + warehouse_id: Number(warehouseId), + stock_id: Number(stockId), + space_id: { [Op.in]: candidateIds }, + is_enabled: 1, + }, + attributes: [ 'space_id' ], + raw: true, + }); + const storageSpaceId = storageRow ? Number(storageRow.space_id) : 0; + return storageSpaceId > 0 ? storageSpaceId : candidateIds[0]; + } + + /** + * 盘点作业上报(覆盖式)。 + * 仅 approved/checking 状态允许;商品明细行固定上报明细商品(入参商品不一致报错), + * 库位明细行必须指定商品且商品必须属于本仓库,库位以明细库位为准(入参库位不一致报错); + * 同明细 + 同商品 + 同库位编码重复上报时更新已有记录的 + * quantity/checker_id/checker_name/checked_at(保留原 location_id,若本次新匹配到 location_id 则回填), + * 不再新增;未传库位编码时以 space_id 对应库位的编码落库; + * **space_id 必传**(wms_location_space.id,须属于本仓库且分区有效),库位以该 ID 为准, + * location 编码入参仅做一致性校验(不一致报 400),服务端不再按编码猜库位; + * 主表 approved 自动转 checking;重算 checked_items / diff_items / detail_status。 + * 静态盘点(is_static=1)商品范围任务额外要求「该商品已完全拣货」:仓库内该商品 + * wms_storage SUM(locked_quantity) > 0(存在已分配储位、尚未拣出的在途出库)时拒绝上报, + * 返回 400「商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货」。 + * 数据库层由唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全。 + * + * 未知商品上报口径(stock_id 与 barcode 至少传一项): + * - 传了 stock_id:按已知商品走现有逻辑(本仓库校验等); + * - 未传 stock_id 但传了 barcode:先按条码匹配系统商品(wms_stock_barcodes 按 + * barcode + 本仓库,关联 StockWarehouse 校验),命中则回填 stock_id 按已知商品处理; + * 未命中则记录 stock_id=NULL + barcode + item_name(item_name 缺省为 barcode); + * - 都未传:沿用现有报错口径(商品行缺商品信息报 400 / 库位行缺商品报 400)。 + * 覆盖式查重:已知商品 where { detail_id, stock_id, location_code } 不变; + * 未知商品 where { detail_id, stock_id: null, barcode, location_code }(应用层查重, + * 唯一索引不约束 NULL 行,并发兜底逻辑对未知商品同样降级更新)。 + * + * @param {Object} params 上报参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number} params.detailId 明细ID。 + * @param {string} [params.location] 库位编码(可选,仅做一致性校验;库位以 spaceId 为准)。 + * @param {number} params.spaceId 库位ID(wms_location_space.id,必传):必须属于本仓库且分区有效, + * 缺失报 400「缺少库位ID(space_id)」;与 location 编码不一致或(库位明细行)与明细库位不一致同样 400。 + * @param {number} params.quantity 实盘数量(>=0 且 <= 2147483647)。 + * @param {number} [params.stockId] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。 + * @param {string} [params.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品, + * 未命中记为未知商品)。 + * @param {string} [params.itemName] 未知商品名称(缺省为 barcode;已知商品忽略)。 + * @param {boolean} [params.is_empty] 空库位标记(仅库位盘点明细支持;标记空时商品/条码/数量均不参与)。 + * @param {number} [params.checkerId] 盘点人账户ID(由方法层从上下文注入)。 + * @param {string} [params.checkerName] 盘点人名称快照(由方法层从上下文注入)。 + * @return {Promise} { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }; + * record 为作业记录全字段(含 barcode/item_name)。 + * @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。 + */ + + /** + * 标记库位为空(库位盘点模式专属,转调 report 的空库位标记口径)。 + * 仅任务范围为库位(type=location)时允许:非库位任务报 400; + * 状态仅 approved/checking;明细必须属于本任务且为库位范围行(scope_type=location)。 + * 行为与 report(is_empty=true) 完全一致:写/更新空标记记录(stock_id/barcode/item_name 为空、 + * quantity=0、is_empty=1)、清除该明细商品记录、主表 approved→checking、 + * 重算 checked_items/diff_items/detail_status、写入操作日志。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number} params.detailId 库位明细ID。 + * @param {number} [params.checkerId] 盘点人账户ID(由方法层从上下文注入)。 + * @param {string} [params.checkerName] 盘点人名称快照(由方法层从上下文注入)。 + * @return {Promise} 与 report 一致:{ record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。 + * @throws {Error} 任务不存在、状态不允许、非库位任务、明细不存在或明细非库位行时抛出业务错误(错误码 400)。 + */ + async markEmpty(params = {}) { + const { warehouseId, id, detailId, checkerId, checkerName } = params; + + const checkId = Number(id); + const detailRowId = Number(detailId); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + if (!Number.isInteger(detailRowId) || detailRowId <= 0) { + throw this.createBusinessError('盘点明细ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许盘点作业`); + } + const normalizedType = String(check.type || '').trim(); + if (normalizedType !== 'location') { + throw this.createBusinessError('仅库位盘点任务支持空库位标记'); + } + + // 明细必须属于本任务且为库位范围行(scope_type=location) + const detail = await this.ctx.model.StockCheckDetail.findOne({ + where: { id: detailRowId, check_id: checkId, warehouse_id: Number(warehouseId) }, + }); + if (!detail) { + throw this.createBusinessError('盘点明细不存在'); + } + if ((detail.scope_type || 'goods') !== 'location') { + throw this.createBusinessError('仅库位盘点明细支持空库位标记'); + } + + // 转调 report 空库位标记口径(查重/互斥/汇总/日志统一); + // report 要求必传 space_id,这里按明细库位编码解析有效库位(明细库位可能指向无头库位) + const resolvedSpaceId = await this._resolveLocationIdByCode( + Number(warehouseId), + String(detail.location_code || '').trim() + ); + if (resolvedSpaceId <= 0) { + throw this.createBusinessError('盘点明细库位无效(库位不存在或所属分区已删除)'); + } + return this.report({ + warehouseId, + id: checkId, + detailId: detailRowId, + spaceId: resolvedSpaceId, + is_empty: true, + checkerId, + checkerName, + }); + } + + async report(params = {}) { + const { + warehouseId, + id, + detailId, + location, + spaceId: spaceIdInput, + quantity, + stockId, + barcode, + itemName, + is_empty: isEmptyInput, + checkerId, + checkerName, + } = params; + const { ctx } = this; + + // 空库位标记:仅库位明细行支持;标记空时商品/条码/数量均不参与(数量恒为 0) + const normalizedIsEmpty = isEmptyInput === true || isEmptyInput === 'true' || isEmptyInput === 1; + + const checkId = Number(id); + const detailRowId = Number(detailId); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + // detail_id 可选:goods 汇总视图行不再带明细ID,允许按 id + stock_id + space_id 反查该商品明细 + let resolvedDetailRowId = Number.isInteger(detailRowId) && detailRowId > 0 ? detailRowId : 0; + const inputStockIdRaw = stockId !== undefined && stockId !== null && stockId !== '' + ? Number(stockId) + : 0; + if (resolvedDetailRowId === 0 && !(Number.isInteger(inputStockIdRaw) && inputStockIdRaw > 0)) { + throw this.createBusinessError('盘点明细ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许盘点作业`); + } + + const quantityValue = normalizedIsEmpty ? 0 : Number(quantity); + if (!normalizedIsEmpty && (!Number.isInteger(quantityValue) || quantityValue < 0)) { + throw this.createBusinessError('实盘数量必须为不小于0的整数'); + } + if (!normalizedIsEmpty && quantityValue > REPORT_MAX_QUANTITY) { + throw this.createBusinessError(`实盘数量不能超过 ${REPORT_MAX_QUANTITY}`); + } + + // 明细定位:传了 detail_id 直接用;未传时按 id + stock_id + space_id 反查该商品的库位明细 + // (goods 汇总视图行不再输出明细ID,前端可只回传商品与库位) + let detail = null; + if (resolvedDetailRowId > 0) { + detail = await ctx.model.StockCheckDetail.findOne({ + where: { id: resolvedDetailRowId, check_id: checkId, warehouse_id: Number(warehouseId) }, + }); + if (!detail) { + throw this.createBusinessError('盘点明细不存在'); + } + } else { + const candidateSpaceId = Number(spaceIdInput); + const detailScope = { + check_id: checkId, + warehouse_id: Number(warehouseId), + stock_id: inputStockIdRaw, + }; + if (Number.isInteger(candidateSpaceId) && candidateSpaceId > 0) { + detail = await ctx.model.StockCheckDetail.findOne({ + where: { ...detailScope, location_id: candidateSpaceId }, + }); + } + if (!detail) { + detail = await ctx.model.StockCheckDetail.findOne({ + where: detailScope, + order: [[ 'id', 'ASC' ]], + }); + } + if (!detail) { + throw this.createBusinessError('盘点明细不存在(该商品不在本任务盘点范围内,或库位盘点任务需传 detail_id)'); + } + resolvedDetailRowId = Number(detail.id); + } + + const scopeType = (detail.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + if (normalizedIsEmpty && scopeType !== 'location') { + throw this.createBusinessError('仅库位盘点明细支持空库位标记'); + } + const inputStockId = stockId !== undefined && stockId !== null && stockId !== '' + ? Number(stockId) + : 0; + const inputBarcode = barcode !== undefined && barcode !== null && String(barcode).trim() !== '' + ? String(barcode).trim() + : ''; + // 未知商品名称:仅未知商品记录落库,缺省为条码 + const inputItemName = itemName !== undefined && itemName !== null && String(itemName).trim() !== '' + ? String(itemName).trim() + : ''; + // 必填库位ID(wms_location_space.id):必须属于本仓库且所属分区有效。 + // 不允许按编码猜库位(同仓库同编码可能有多条历史重复/无头库位),缺失即 400 由调用方补传 + const inputSpaceId = spaceIdInput !== undefined && spaceIdInput !== null && spaceIdInput !== '' + ? Number(spaceIdInput) + : 0; + if (!Number.isInteger(inputSpaceId) || inputSpaceId <= 0) { + throw this.createBusinessError('缺少库位ID(space_id),请传取回数据中的 space_id'); + } + const inputLocationRow = await ctx.model.LocationSpace.findOne({ + where: { id: inputSpaceId, warehouse_id: Number(warehouseId) }, + attributes: [ 'id', 'space_code' ], + include: [{ + model: ctx.model.LocationZone, + as: 'zone', + attributes: [], + required: true, + }], + raw: true, + }); + if (!inputLocationRow) { + throw this.createBusinessError('上报库位不存在、不属于当前仓库或所属分区已删除'); + } + const inputLocationCode = String(inputLocationRow.space_code || '').trim(); + if (!inputLocationCode) { + throw this.createBusinessError('上报库位的库位编码为空,无法上报'); + } + // 入参库位编码(可选):仅做一致性校验,库位以 space_id 对应的库位行为准 + const inputLocationCodeParam = location !== undefined && location !== null && String(location).trim() !== '' + ? String(location).trim() + : ''; + + let normalizedStockId = 0; + let normalizedBarcode = null; + let normalizedItemName = null; + let isUnknownGoods = false; + let locationCode = ''; + let locationId = null; + + if (scopeType === 'goods') { + // 商品行:商品固定为明细商品,入参传了不同商品直接报错 + normalizedStockId = Number(detail.stock_id); + if (!Number.isInteger(normalizedStockId) || normalizedStockId <= 0) { + throw this.createBusinessError('盘点明细缺少商品信息'); + } + if (inputStockId > 0 && inputStockId !== normalizedStockId) { + throw this.createBusinessError('上报商品与盘点明细商品不一致'); + } + if (inputStockId <= 0 && inputBarcode) { + // 仅传条码:先尝试回填系统商品;命中且与明细商品一致按已知商品处理,未命中记为未知商品 + const matchedStockId = await this._resolveStockIdByBarcode(inputBarcode, Number(warehouseId)); + if (matchedStockId > 0) { + if (matchedStockId !== normalizedStockId) { + throw this.createBusinessError('上报商品与盘点明细商品不一致'); + } + normalizedBarcode = inputBarcode; + } else { + isUnknownGoods = true; + normalizedStockId = 0; + normalizedBarcode = inputBarcode; + normalizedItemName = inputItemName || inputBarcode; + } + } else if (inputBarcode) { + normalizedBarcode = inputBarcode; + } + // 库位以 space_id 对应的库位行为准(必填);location 编码仅做一致性校验 + if (inputLocationCodeParam && inputLocationCodeParam !== inputLocationCode) { + throw this.createBusinessError('上报库位编码与库位ID不一致'); + } + locationCode = inputLocationCode; + locationId = Number(inputLocationRow.id); + } else { + // 库位行:以明细库位为准 + locationCode = String(detail.location_code || '').trim(); + if (!locationCode) { + throw this.createBusinessError('盘点明细缺少库位信息'); + } + if (inputLocationCodeParam && inputLocationCodeParam !== locationCode) { + throw this.createBusinessError('上报库位与盘点明细库位不一致'); + } + if (inputLocationCode !== locationCode) { + throw this.createBusinessError('上报库位与盘点明细库位不一致'); + } + locationId = Number(inputLocationRow.id); + + if (normalizedIsEmpty) { + // 空库位标记:不要求商品,stock_id/barcode/item_name 均为空、quantity=0 + normalizedStockId = 0; + normalizedBarcode = null; + normalizedItemName = null; + isUnknownGoods = false; + } else if (inputStockId <= 0 && !inputBarcode) { + throw this.createBusinessError('按库位盘点时必须指定商品'); + } else if (inputStockId <= 0 && inputBarcode) { + // 仅传条码:先尝试回填系统商品;命中按已知商品处理,未命中记为未知商品 + const matchedStockId = await this._resolveStockIdByBarcode(inputBarcode, Number(warehouseId)); + if (matchedStockId > 0) { + normalizedStockId = matchedStockId; + normalizedBarcode = inputBarcode; + } else { + isUnknownGoods = true; + normalizedStockId = 0; + normalizedBarcode = inputBarcode; + normalizedItemName = inputItemName || inputBarcode; + } + } else { + // 传了 stock_id:现有校验口径(商品必须属于本仓库) + const stock = await ctx.model.StockWarehouse.findOne({ + where: { + id: inputStockId, + warehouse_id: Number(warehouseId), + }, + attributes: [ 'id' ], + raw: true, + }); + if (!stock) { + throw this.createBusinessError('上报商品不属于本仓库'); + } + normalizedStockId = inputStockId; + if (inputBarcode) { + normalizedBarcode = inputBarcode; + } + } + } + + // 静态盘点要求「该商品已完全拣货」:商品仍有锁定量说明存在已分配储位但尚未拣出的在途出库, + // 此时上报的实盘数与账面快照之间会夹着这批货,差异不可信,直接拒绝上报 + if (Number(check.is_static) === 1 && scopeType === 'goods' && normalizedStockId > 0) { + const stockLockedMap = await this._fetchStockLockedQuantityMap(warehouseId, [ normalizedStockId ]); + if ((stockLockedMap.get(normalizedStockId) || 0) > 0) { + throw this.createBusinessError('商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货'); + } + } + + const now = new Date(); + + // 覆盖式上报:已知商品按同明细 + 同商品 + 同库位编码(库位编码来自 space_id 对应库位)更新已有记录, + // 依赖唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全; + // 未知商品唯一索引不约束 NULL 行,按同明细 + 同条码 + 同库位编码在应用层查重; + // 空库位标记按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新 + const existingRecordWhere = normalizedIsEmpty + ? { + detail_id: resolvedDetailRowId, + is_empty: true, + location_code: locationCode, + } + : (isUnknownGoods + ? { + detail_id: resolvedDetailRowId, + stock_id: null, + barcode: normalizedBarcode, + location_code: locationCode, + } + : { + detail_id: resolvedDetailRowId, + stock_id: normalizedStockId, + location_code: locationCode, + }); + const existingRecord = await ctx.model.StockCheckRecord.findOne({ + where: existingRecordWhere, + }); + + const normalizedCheckerId = checkerId ? Number(checkerId) : null; + const normalizedCheckerName = checkerName || null; + let record = null; + let mode = 'created'; + if (existingRecord) { + // 保留原 location_id,若本次新匹配到 location_id 则回填 + const resolvedLocationId = locationId !== null && locationId !== undefined + ? locationId + : existingRecord.location_id; + const updatePatch = { + quantity: quantityValue, + checker_id: normalizedCheckerId, + checker_name: normalizedCheckerName, + checked_at: now, + location_id: resolvedLocationId, + }; + if (normalizedBarcode !== null) { + updatePatch.barcode = normalizedBarcode; + } + if (normalizedItemName !== null) { + updatePatch.item_name = normalizedItemName; + } + await existingRecord.update(updatePatch); + record = existingRecord.get({ plain: true }); + mode = 'updated'; + } else { + try { + const createdRecord = await ctx.model.StockCheckRecord.create({ + check_id: checkId, + warehouse_id: Number(warehouseId), + detail_id: resolvedDetailRowId, + stock_id: (isUnknownGoods || normalizedIsEmpty) ? null : normalizedStockId, + barcode: normalizedBarcode, + item_name: normalizedItemName, + is_empty: normalizedIsEmpty, + location_id: locationId, + location_code: locationCode, + quantity: quantityValue, + checker_id: normalizedCheckerId, + checker_name: normalizedCheckerName, + checked_at: now, + }); + record = createdRecord.get({ plain: true }); + } catch (error) { + // 并发下撞唯一索引 uk_detail_stock_location(已知商品):降级为更新已有记录,避免调用方收到 500; + // 未知商品唯一索引不约束 NULL 行,同样按查重条件降级更新兜底 + const isDuplicate = (error && error.name === 'SequelizeUniqueConstraintError') + || (error && error.original && error.original.code === 'ER_DUP_ENTRY'); + if (!isDuplicate) { + throw error; + } + const latestRecord = await ctx.model.StockCheckRecord.findOne({ + where: existingRecordWhere, + }); + if (!latestRecord) { + throw error; + } + const resolvedLocationId = locationId !== null && locationId !== undefined + ? locationId + : latestRecord.location_id; + const updatePatch = { + quantity: quantityValue, + checker_id: normalizedCheckerId, + checker_name: normalizedCheckerName, + checked_at: now, + location_id: resolvedLocationId, + }; + if (normalizedBarcode !== null) { + updatePatch.barcode = normalizedBarcode; + } + if (normalizedItemName !== null) { + updatePatch.item_name = normalizedItemName; + } + await latestRecord.update(updatePatch); + record = latestRecord.get({ plain: true }); + mode = 'updated'; + } + } + + // 空库位标记与商品记录互斥:确认库位为空后清除该明细下商品记录;上报商品后清除该明细下空标记 + if (normalizedIsEmpty) { + await ctx.model.StockCheckRecord.destroy({ + where: { detail_id: resolvedDetailRowId, is_empty: false }, + }); + } else { + await ctx.model.StockCheckRecord.destroy({ + where: { detail_id: resolvedDetailRowId, is_empty: true }, + }); + } + + // 主表 approved → checking 自动转移;盘点开始时间=第一个盘点明细写入的时间 + // (start_time 为空则补写,保证任何状态下首个明细落盘时间都被记录) + const checkPatch = {}; + if (check.status === 'approved') { + checkPatch.status = 'checking'; + } + if (!check.start_time) { + checkPatch.start_time = now; + } + if (Object.keys(checkPatch).length > 0) { + await check.update(checkPatch); + } + + // 重算 checked_items / diff_items / detail_status + const summary = await this._recalcCheckSummary(checkId); + + // 写入操作日志(失败不影响主流程) + // message 补充库位编码/库位ID(原 message 只有明细与数量,事后无法定位是哪个库位被上报), + // before_changes 落明细快照与本次上报字段,供追溯 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_REPORT', + operationAction: 'UPDATE', + changeSummary: normalizedIsEmpty + ? `盘点作业上报:明细 ${resolvedDetailRowId} 确认库位 ${locationCode || '未指定'} 为空` + : `盘点作业上报:明细 ${resolvedDetailRowId},库位 ${locationCode || '未指定'},实盘 ${quantityValue}${normalizedBarcode ? `,条码 ${normalizedBarcode}` : ''}(${mode === 'created' ? '新增' : '更新'})`, + beforeChanges: { + check_no: check.check_no, + detail_id: resolvedDetailRowId, + scope_type: scopeType, + stock_id: normalizedStockId > 0 ? normalizedStockId : null, + location_code: locationCode || '', + location_id: locationId !== null && locationId !== undefined ? Number(locationId) : null, + detail_location_code: String(detail.location_code || '').trim() || null, + detail_location_id: detail.location_id !== null && detail.location_id !== undefined + ? Number(detail.location_id) + : null, + quantity: quantityValue, + barcode: normalizedBarcode, + is_unknown_goods: isUnknownGoods, + is_empty: normalizedIsEmpty, + mode, + record_id: Number(record && record.id) || null, + }, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + detailId: resolvedDetailRowId, + locationCode, + locationId: locationId !== null && locationId !== undefined ? Number(locationId) : null, + quantity: quantityValue, + barcode: normalizedBarcode, + isUnknownGoods, + is_empty: normalizedIsEmpty, + mode, + message: normalizedIsEmpty + ? `盘点作业上报:明细 ${resolvedDetailRowId} 确认库位 ${locationCode || '未指定'}${locationId ? `(#${locationId})` : ''} 为空` + : `盘点作业上报:明细 ${resolvedDetailRowId},库位 ${locationCode || '未指定'}${locationId ? `(#${locationId})` : ''},实盘 ${quantityValue}`, + }, + }); + + return { + record, + detail_id: resolvedDetailRowId, + mode, + total_items: summary.total_items, + checked_items: summary.checked_items, + diff_items: summary.diff_items, + detail_status: summary.detail_status, + }; + } + + /** + * 拉取盘点作业记录列表。 + * 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;rows 每条为作业记录全字段 + + * 商品快照列(item_code/item_name,从明细表查得)按记录 id 倒序; + * 未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、名称列显示上报名称快照(item_name); + * 每条记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} [params.id] 盘点任务ID(可选)。 + * @param {number} [params.detailId] 明细ID(可选)。 + * @param {Object} [params.pagination] 分页参数。 + * @return {Promise} { rows, total, page, pageSize };rows 每条含 barcode/item_name 与 + * images: [{ id: file_id, url }]。 + * @throws {Error} 未传任务ID或明细ID时抛出业务错误(错误码 400)。 + */ + async recordList(params = {}) { + const { warehouseId, id, detailId, pagination = {} } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const checkId = id !== undefined && id !== null && id !== '' ? Number(id) : 0; + const normalizedDetailId = detailId !== undefined && detailId !== null && detailId !== '' ? Number(detailId) : 0; + const hasCheckId = Number.isInteger(checkId) && checkId > 0; + const hasDetailId = Number.isInteger(normalizedDetailId) && normalizedDetailId > 0; + if (!hasCheckId && !hasDetailId) { + throw this.createBusinessError('请至少提供盘点任务ID或明细ID'); + } + + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + + const where = { warehouse_id: Number(warehouseId) }; + if (hasCheckId) { + where.check_id = checkId; + } + if (hasDetailId) { + where.detail_id = normalizedDetailId; + } + + const { count, rows } = await ctx.model.StockCheckRecord.findAndCountAll({ + where, + order: [[ 'id', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + // 挂载作业记录图片(FileReference business_type=stock_check_record,与收货 receivingItem 口径一致) + await this._attachRecordImages(rows); + + // 商品快照列从明细表补齐(未命中 getStockDetails 时兜底) + const detailIds = [ ...new Set(rows.map(row => Number(row.detail_id))) ]; + let itemByDetailId = new Map(); + if (detailIds.length > 0) { + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { id: { [Op.in]: detailIds } }, + attributes: [ 'id', 'item_code', 'item_name', 'spec' ], + raw: true, + }); + itemByDetailId = new Map(detailRows.map(item => [ Number(item.id), item ])); + } + + // 商品基础信息批量取(与 workData 口径一致:getStockDetails 带缓存)+ 货主名映射 + const stockIds = [ ...new Set(rows + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + let stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId: Number(warehouseId), + }); + stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ])); + } + const storeIds = [ ...stockDetailMap.values() ] + .map(item => Number(item.store_id)) + .filter(storeId => Number.isInteger(storeId) && storeId > 0); + const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId); + + const formattedRows = rows.map(row => { + const item = itemByDetailId.get(Number(row.detail_id)) || {}; + const recordStockId = Number(row.stock_id); + const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0; + const stockDetail = isUnknownGoods ? {} : (stockDetailMap.get(recordStockId) || {}); + const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : []; + const storeId = !isUnknownGoods && stockDetail.store_id != null ? Number(stockDetail.store_id) : null; + return { + ...row, + // 空串表示"无库位"分组,接口返回口径统一为 null + location_code: String(row.location_code || '').trim() !== '' ? row.location_code : null, + // 未知商品(stock_id 为空):商品编码列显示扫描条码、名称列显示上报名称快照,无商品/货主信息; + // 已知商品按 workData 口径:商品信息批量取自 getStockDetails(未命中回退明细商品快照), + // 货主名经 _resolveStoreNameMap 解析 + item_code: isUnknownGoods + ? (String(row.barcode || '').trim() || null) + : (stockDetail.item_code || item.item_code || null), + item_name: isUnknownGoods + ? (String(row.item_name || row.barcode || '').trim() || null) + : (stockDetail.item_name || item.item_name || null), + spec: isUnknownGoods ? null : (stockDetail.sku_property || item.spec || null), + store_id: storeId, + store_name: storeId ? (storeNameMap.get(storeId) || null) : null, + barcode: isUnknownGoods + ? (String(row.barcode || '').trim() || null) + : ((barcodes[0] && barcodes[0].barcode) || (String(row.barcode || '').trim() || null)), + }; + }); + + return { rows: formattedRows, total: count, page, pageSize }; + } + + /** + * 拉取盘点作业数据(视图由任务类型与 is_goods 驱动,view 入参已废弃忽略)。 + * 视图解析规则: + * - 任务范围为库位(type=location):一律按库位视图(location)返回,无视 view/is_goods 入参; + * - 任务范围为商品(type=goods/store):默认聚合库位视图(space);仅 is_goods=true 时按商品视图(goods)返回。 + * 三视图行结构: + * location=库位结构,以任务库位范围行(scope_type=location)为列表, + * 行内挂该库位的盘点作业记录 goods 子列表(已知商品与未知商品均入内, + * has_unknown 标记是否含未知商品); + * goods=商品结构,按商品(stock_id)汇总,一个商品一行——同商品的多个库位明细行 + * (scope_type=goods,按「商品+库位」拆行)合并:行内挂跨明细按库位合并的作业记录 + * (locations 每项含该库位明细ID detail_id),明盘(mode=open)返回账面快照合计/已盘合计/差异, + * 盲盘(mode=blind)不返回任何数量字段;逐库位明细/汇总请调用 workDataDetail(id + stock_id); + * space=聚合库位列表,以任务商品所在库位为列表(仅按库位拣货顺序 pick_sequence 升序 + * 排序,pick_priority/库位 id 不参与,同值保持库位查询顺序),行内挂该库位的任务商品与账面/实盘数量,盲盘不返回数量字段; + * 若任务无对应范围行(如 location 视图无库位范围行),rows 返回空数组。 + * 分页:pagination.{page,pageSize}(与 stock_check.list 口径一致;未传或非法时默认 page=1、 + * pageSize=20,上限 200),先构建全量行再按页切片;rows 为当前页行、total 为全部行数, + * 并返回 page/pageSize。 + * + * 不返回任务主表信息(check)——任务信息请调用 detail; + * 响应返回 view(服务端实际解析出的视图类型 location/goods/space),供调用方判断 rows 行结构。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {boolean} [params.isGoods] 商品任务是否按商品视图返回(true=goods 视图); + * 缺省为 false(聚合库位 space 视图);库位任务无视该参数。 + * @param {string} [params.keyword] 关键字(仅库位任务 location 视图生效):按行 + * location_code/location_name 模糊匹配(不区分大小写)过滤后返回;非库位任务忽略。 + * @param {boolean} [params.onlyAbnormal] 只看未盘和差异(可选,向后兼容):过滤在 keyword 之后、 + * 分页切片之前完成,三视图均生效——location 视图仅保留 status=unchecked 或 has_unknown=true 的行; + * goods 视图仅保留未盘行(locations 均无 record_ids)或明盘差异行(is_diff=1); + * space 视图按行内 goods 子项过滤(status=unchecked 或明盘 checked_quantity≠system_quantity), + * 过滤后 goods 为空的行整体移除;盲盘无数量字段仅按未盘过滤;total 为过滤后行数。 + * @param {Object} [params.pagination] 分页配置 { page, pageSize }。 + * @return {Promise} { view, rows, total, page, pageSize };view 为解析后的视图类型 + * (location=库位结构/goods=商品结构/space=聚合库位结构);rows 结构按解析后的视图不同: + * location 行含 detail_id/location_id/location_code/location_name/status/has_unknown/ + * checked_at/checkers/goods(已知商品与未知商品记录均入 goods,未知商品 stock_id=null); + * goods 行含 stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/locations + * (明盘另含 system_quantity(账面快照合计)/checked_quantity/diff_quantity/is_diff; + * 静态盘点另含 picking_completed(1=该商品已完成拣货/0=未完成,判定口径=仓库内该商品锁定量为 0) + * 与明盘下的 locked_quantity(该商品仓库内锁定量合计)); + * space 行含 id/space_code/custom_barcode/custom_name/goods(goods 子项在静态盘点时 + * 另含 picking_completed,口径与 goods 视图行一致)。 + * @throws {Error} 任务不存在或任务状态非 approved/checking 时抛出业务错误(错误码 400)。 + */ + async workData(params = {}) { + const { warehouseId, id, isGoods, keyword, pagination = {}, onlyAbnormal } = params; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${STOCK_CHECK_STATUS_LABELS[check.status] || check.status})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取`); + } + + // 视图解析:库位范围任务一律 location 视图(无视 view/is_goods); + // 商品范围任务默认 space(聚合库位),仅 is_goods=true 时 goods 视图 + const normalizedType = String(check.type || '').trim(); + const goodsViewRequested = isGoods === true || isGoods === 'true' || isGoods === 1; + const resolvedView = normalizedType === 'location' + ? 'location' + : (goodsViewRequested ? 'goods' : 'space'); + + // 静态盘点(is_static=1)账面取明细快照,非静态取当前 wms_storage 账面 + const isStatic = Number(check.is_static) === 1; + const allRows = resolvedView === 'location' + ? await this._buildLocationWorkRows(warehouseId, checkId) + : (resolvedView === 'goods' + ? await this._buildGoodsWorkRows(warehouseId, checkId, check.mode, isStatic) + : await this._buildSpaceWorkRows(warehouseId, checkId, check.mode, isStatic)); + + // keyword 过滤:仅库位任务(location 视图)启用,按行 location_code/location_name + // 模糊匹配(不区分大小写)过滤任务明细后再分页;非库位任务忽略该参数 + const normalizedKeyword = String(keyword || '').trim().toLowerCase(); + const keywordFilteredRows = resolvedView === 'location' && normalizedKeyword + ? allRows.filter(row => + String(row.location_code || '').toLowerCase().includes(normalizedKeyword) + || String(row.location_name || '').toLowerCase().includes(normalizedKeyword)) + : allRows; + + // only_abnormal 过滤:仅保留"未盘或有差异"的行(与 keyword 过滤叠加,三视图均生效); + // 未传/非 true(false/0/空串/缺省)不过滤 + const abnormalRequested = onlyAbnormal === true || onlyAbnormal === 'true' || onlyAbnormal === 1; + const filteredRows = abnormalRequested + ? this._filterAbnormalWorkRows(resolvedView, keywordFilteredRows, check.mode !== 'blind') + : keywordFilteredRows; + + // 分页切片:page 默认 1、pageSize 默认 20(上限 200),非法值回退默认 + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + const offset = (page - 1) * pageSize; + + return { + view: resolvedView, + rows: filteredRows.slice(offset, offset + pageSize), + total: filteredRows.length, + page, + pageSize, + }; + } + + /** + * only_abnormal 过滤:仅保留"未盘或有差异"的行(workData 专用,过滤在分页切片之前完成)。 + * 语义按视图区分: + * - location 视图:保留 status=unchecked(未盘)或 has_unknown=true(含未知商品记录,未知商品无账面、 + * 差异=实盘-0=盘盈,视为差异)的行;空库位标记(is_empty)后 status=checked 视为已盘点、不保留; + * - goods 视图:未盘口径为 locations 均无 record_ids(无任何作业记录);差异口径为明盘 is_diff=1; + * 盲盘(isOpen=false)无数量字段,仅按未盘过滤(已盘行全部移除); + * - space 视图:按行内 goods 子项过滤——保留 status=unchecked 的子项,明盘另保留 + * checked_quantity≠system_quantity(数量差异)的子项;过滤后 goods 为空的行整体移除。 + * + * @param {string} view 服务端解析出的视图类型(location/goods/space)。 + * @param {Array} rows 待过滤的作业数据行(keyword 过滤之后的全量行)。 + * @param {boolean} isOpen 是否明盘(true=明盘含数量字段,false=盲盘无数量字段)。 + * @return {Array} 过滤后的行列表。 + */ + _filterAbnormalWorkRows(view, rows, isOpen) { + if (view === 'location') { + return rows.filter(row => row.status === 'unchecked' || row.has_unknown === true); + } + if (view === 'goods') { + return rows.filter(row => { + const hasRecords = Array.isArray(row.locations) + && row.locations.some(location => location + && Array.isArray(location.record_ids) + && location.record_ids.length > 0); + if (!hasRecords) { + return true; + } + return isOpen && row.is_diff === 1; + }); + } + // space 视图:按行内 goods 子项过滤,过滤后 goods 为空的行整体移除 + return rows + .map(row => ({ + ...row, + goods: (Array.isArray(row.goods) ? row.goods : []).filter(item => { + if (!item) { + return false; + } + if (item.status === 'unchecked') { + return true; + } + return isOpen && Number(item.checked_quantity) !== Number(item.system_quantity); + }), + })) + .filter(row => Array.isArray(row.goods) && row.goods.length > 0); + } + + /** + * 拉取盘点作业数据(space 视图分页版)。 + * 行结构与 workData space 视图行一致(id=库位ID/location_id 同义库位ID/space_code/custom_barcode/custom_name/goods), + * 商品任务(scope_type=goods)按库位聚合;传入 location_id 时只返回该库位行(total=1), + * 不传时按分页返回全部库位行。静态盘点(is_static=1)时 goods 子项含 picking_completed + * (1=该商品已完成拣货/0=未完成,口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0, + * 按商品维度判定,明盘盲盘均返回)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number|string} [params.locationId] 库位ID(wms_location_space.id), + * 传入时只返回该库位行(兼容 location_id 写法)。 + * @param {Object} [params.pagination] 分页配置 { page, pageSize }。 + * @return {Promise} { view:'space', rows, total, page, pageSize }。 + * @throws {Error} 任务不存在或任务状态非 approved/checking 时抛出业务错误(错误码 400)。 + */ + async workDataSpaceDetails(params = {}) { + const { warehouseId, id, locationId, pagination = {} } = params; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${STOCK_CHECK_STATUS_LABELS[check.status] || check.status})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取`); + } + + const normalizedLocationId = Number(locationId); + const hasLocationFilter = Number.isInteger(normalizedLocationId) && normalizedLocationId > 0; + + const allRows = await this._buildSpaceWorkRows( + warehouseId, + checkId, + check.mode, + Number(check.is_static) === 1 + ); + + // 库位过滤:传入 location_id 时只保留该库位行 + const filteredRows = hasLocationFilter + ? allRows.filter(row => Number(row.id) === normalizedLocationId) + : allRows; + + // 分页切片:page 默认 1、pageSize 默认 20(上限 200),非法值回退默认 + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + const offset = (page - 1) * pageSize; + + return { + view: 'space', + rows: filteredRows.slice(offset, offset + pageSize), + total: filteredRows.length, + page, + pageSize, + }; + } + + /** + * 拉取盘点作业数据明细(单行/商品钻取版)。 + * + * 两种入参与返回: + * - 库位明细(detail_id,scope_type=location):返回单行,结构与 workData location 视图单行一致 + * (detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/ + * checked_at/checkers/goods),便于作业端按明细ID刷新单行数据; + * - 商品(id=盘点任务ID + stock_id,或 detail_id 指向商品范围行):返回该商品的库位分行数据 + + * 汇总数据 { check_id, stock_id, 商品信息, summary, rows }: + * summary 为商品级汇总(明盘含 system_quantity 账面快照合计/checked_quantity 实盘合计/ + * diff_quantity/is_diff;盲盘不含数量字段); + * rows 为该商品每个库位一行(detail_id 该库位明细ID/location_id 与同义 space_id 库位ID/ + * location_code 库位编码,明盘另含 system_quantity 该库位当前账面(可用数量)/ + * snapshot_quantity 该库位账面快照/locked_quantity 锁定数量/checked_quantity 该库位实盘/ + * diff_quantity 该库位差异(实盘-快照),另有 checked_at/checker_name/record_ids/images); + * 静态盘点另在顶层返回 picking_completed(1=该商品已完成拣货/0=未完成,判定口径=仓库内该商品 + * wms_storage SUM(locked_quantity) 是否为 0)与明盘下的 locked_quantity(仓库内锁定量合计)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} [params.id] 盘点任务ID(商品钻取必传,与 stockId 搭配)。 + * @param {number} [params.stockId] 商品库存ID(wms_stock_warehouse.id,商品钻取必传)。 + * @param {number} [params.detailId] 盘点明细ID(库位明细必传;商品明细可只传本参数,按明细商品钻取)。 + * @return {Promise} 库位明细返回 location 单行;商品返回 { check_id, stock_id, 商品信息, summary, rows }。 + * @throws {Error} 明细/商品不在任务范围内、任务状态非 approved/checking 时抛业务错误(错误码 400)。 + */ + async workDataDetail(params = {}) { + const { ctx } = this; + const { warehouseId, detailId, id: checkIdInput, stockId } = params; + + const normalizedDetailId = Number(detailId); + const normalizedCheckId = Number(checkIdInput); + const normalizedStockId = Number(stockId); + const hasDetailId = Number.isInteger(normalizedDetailId) && normalizedDetailId > 0; + const hasStockScope = Number.isInteger(normalizedCheckId) && normalizedCheckId > 0 + && Number.isInteger(normalizedStockId) && normalizedStockId > 0; + if (!hasDetailId && !hasStockScope) { + throw this.createBusinessError('请提供盘点明细ID(detail_id),或盘点任务ID(id)+商品ID(stock_id)'); + } + + let detailRow = null; + if (hasDetailId) { + detailRow = await ctx.model.StockCheckDetail.findOne({ + where: { id: normalizedDetailId, warehouse_id: Number(warehouseId) }, + raw: true, + }); + if (!detailRow) { + throw this.createBusinessError('盘点明细不存在'); + } + } else { + // 商品钻取:任务 + 商品 → 该商品的库位明细行(取明细 id 最小的一条定位商品与任务) + detailRow = await ctx.model.StockCheckDetail.findOne({ + where: { + check_id: normalizedCheckId, + warehouse_id: Number(warehouseId), + stock_id: normalizedStockId, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (!detailRow) { + throw this.createBusinessError('盘点明细不存在(该商品不在本任务盘点范围内)'); + } + } + + const check = await this._findCheck(warehouseId, Number(detailRow.check_id)); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${STOCK_CHECK_STATUS_LABELS[check.status] || check.status})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取`); + } + + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + + // 商品(scope_type=goods):返回该商品的库位分行数据 + 汇总数据 + if (scopeType === 'goods') { + const isStatic = Number(check.is_static) === 1; + const goodsRows = await this._buildGoodsWorkRows( + warehouseId, + Number(detailRow.check_id), + check.mode, + isStatic + ); + const goodsRow = goodsRows.find(item => Number(item.stock_id) === Number(detailRow.stock_id)); + if (!goodsRow) { + throw this.createBusinessError('盘点明细不存在'); + } + return this._formatGoodsWorkDetail(goodsRow, check.mode, Number(detailRow.check_id)); + } + + // 库位明细:返回 location 视图单行 + const rows = await this._buildLocationWorkRows(warehouseId, Number(detailRow.check_id)); + const row = rows.find(item => Number(item.detail_id) === normalizedDetailId); + if (!row) { + throw this.createBusinessError('盘点明细不存在'); + } + return row; + } + + /** + * 将 goods 视图聚合行格式化为商品钻取结果:汇总数据(summary)+ 按库位分行数据(rows)。 + * open(明盘)输出数量字段;blind(盲盘)不返回任何数量字段(仅库位与作业记录信息)。 + * + * @param {Object} goodsRow goods 视图单行(_buildGoodsWorkRows 输出)。 + * @param {string} mode 盘点方式:open=明盘/blind=盲盘。 + * @param {number} checkId 盘点任务ID。 + * @return {Object} { check_id, stock_id, 商品信息, summary, rows }。 + */ + _formatGoodsWorkDetail(goodsRow, mode, checkId) { + const isOpen = mode !== 'blind'; + const locations = Array.isArray(goodsRow.locations) ? goodsRow.locations : []; + const rows = locations.map(location => { + const detailRowId = location && location.detail_id !== undefined ? location.detail_id : null; + const row = { + // 该库位对应的盘点明细ID(商品按库位拆行,可为 null:库位已无明细但有作业记录) + detail_id: detailRowId, + // 库位ID(wms_location_space.id):location_id 与 space_id 同值,可直接回传 stock.check.report + location_id: location ? location.location_id : null, + space_id: location ? location.space_id : null, + location_code: location ? location.location_code : null, + checked_at: location ? location.checked_at : null, + checker_name: location ? location.checker_name : null, + record_ids: location && Array.isArray(location.record_ids) ? location.record_ids : [], + images: location && Array.isArray(location.images) ? location.images : [], + }; + if (isOpen) { + const checkedQuantity = Number(location && location.quantity) || 0; + const snapshotQuantity = Number(location && location.snapshot_quantity) || 0; + // system_quantity 为本次参与差异计算的账面(静态=快照,非静态=当前 storage) + const bookQuantity = Number(location && location.system_quantity) || 0; + row.system_quantity = bookQuantity; + row.storage_quantity = Number(location && location.storage_quantity) || 0; + row.locked_quantity = Number(location && location.locked_quantity) || 0; + row.snapshot_quantity = snapshotQuantity; + row.checked_quantity = checkedQuantity; + row.diff_quantity = checkedQuantity - bookQuantity; + } + return row; + }); + + const detail = { + check_id: Number(checkId) || null, + stock_id: Number(goodsRow.stock_id) || null, + item_code: goodsRow.item_code || null, + item_name: goodsRow.item_name || null, + spec: goodsRow.spec || null, + store_id: goodsRow.store_id !== undefined ? goodsRow.store_id : null, + store_name: goodsRow.store_name || null, + barcode: goodsRow.barcode || null, + images: Array.isArray(goodsRow.images) ? goodsRow.images : [], + // 账面取值来源:静态盘点=明细快照(盘点基准冻结),非静态=当前 wms_storage 账面 + is_static: Number(goodsRow.is_static) === 1 ? 1 : 0, + book_source: goodsRow.book_source === 'snapshot' ? 'snapshot' : 'storage', + rows, + }; + // 静态盘点:该商品是否已完成拣货(1=已完成/0=未完成);盲盘不输出锁定量数值 + if (Number(goodsRow.is_static) === 1) { + detail.picking_completed = Number(goodsRow.picking_completed) === 1 ? 1 : 0; + if (isOpen) { + detail.locked_quantity = Number(goodsRow.locked_quantity) || 0; + } + } + if (isOpen) { + detail.summary = { + system_quantity: Number(goodsRow.system_quantity) || 0, + checked_quantity: Number(goodsRow.checked_quantity) || 0, + diff_quantity: Number(goodsRow.diff_quantity) || 0, + is_diff: Number(goodsRow.is_diff) || 0, + }; + } + return detail; + } + + /** + * 构建 location 视图行:以任务库位范围行为列表,行内挂该库位的盘点作业记录。 + * 已知商品子列表 goods 的商品基础信息(item_code/item_name/条码/图片/货主)批量取自 + * stockWarehouse.getStockDetails,货主名经 _resolveStoreNameMap 解析; + * 未知商品子列表 unknown 输出记录快照字段(barcode/item_name/images,图片经 _attachRecordImages 挂载); + * 库位名称 custom_name 兜底 space_code,库位编码优先明细快照、缺失时回退库位表。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} checkId 盘点任务ID。 + * @return {Promise>} 库位视图行列表(按明细 id 升序)。 + */ + async _buildLocationWorkRows(warehouseId, checkId) { + const { ctx } = this; + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'location' }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const records = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 挂载作业记录图片(FileReference business_type=stock_check_record,与 result 口径一致) + await this._attachRecordImages(records); + + // 库位名称(custom_name 兜底 space_code),库位编码优先明细快照、缺失时回退库位表 + const locationIds = [ ...new Set(detailRows + .map(row => Number(row.location_id)) + .filter(locationId => Number.isInteger(locationId) && locationId > 0)) ]; + let locationMap = new Map(); + if (locationIds.length > 0) { + const locationRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [ctx.app.Sequelize.Op.in]: locationIds } }, + attributes: [ 'id', 'space_code', 'custom_name' ], + raw: true, + }); + locationMap = new Map(locationRows.map(row => [ Number(row.id), row ])); + } + + // 按明细聚合作业记录 + const recordsByDetail = new Map(); + for (const record of records) { + const detailId = Number(record.detail_id); + if (!recordsByDetail.has(detailId)) { + recordsByDetail.set(detailId, []); + } + recordsByDetail.get(detailId).push(record); + } + + // 已知商品基础信息批量取(getStockDetails 带缓存)与货主名映射 + const stockIds = [ ...new Set(records + .map(record => Number(record.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + let stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId: Number(warehouseId), + }); + stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ])); + } + const storeIds = [ ...stockDetailMap.values() ] + .map(item => Number(item.store_id)) + .filter(storeId => Number.isInteger(storeId) && storeId > 0); + const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId); + + return detailRows.map(detailRow => { + const detailId = Number(detailRow.id); + const detailRecords = recordsByDetail.get(detailId) || []; + const locationRow = locationMap.get(Number(detailRow.location_id) || 0); + const locationCode = String( + detailRow.location_code || (locationRow && locationRow.space_code) || '' + ).trim() || null; + const locationName = locationCode + ? ((locationRow && (locationRow.custom_name || locationRow.space_code)) || locationCode) + : null; + + const goods = []; + const checkerSet = new Set(); + let lastCheckedAt = null; + let hasUnknown = false; + let isEmptyLocation = false; + for (const record of detailRecords) { + const checkerName = String(record.checker_name || '').trim(); + if (checkerName) { + checkerSet.add(checkerName); + } + if (record.checked_at && (!lastCheckedAt || new Date(record.checked_at) > new Date(lastCheckedAt))) { + lastCheckedAt = record.checked_at; + } + // 空库位标记记录:不计入 goods 子列表,行级输出 is_empty 标记 + if (record.is_empty) { + isEmptyLocation = true; + continue; + } + const stockId = Number(record.stock_id); + if (Number.isInteger(stockId) && stockId > 0) { + const stockDetail = stockDetailMap.get(stockId) || {}; + const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : []; + const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null; + goods.push({ + record_id: record.id, + stock_id: stockId, + item_code: stockDetail.item_code || null, + item_name: stockDetail.item_name || null, + barcode: (barcodes[0] && barcodes[0].barcode) || null, + images: Array.isArray(record.images) ? record.images : [], + store_id: storeId, + store_name: storeNameMap.get(storeId) || null, + quantity: Number(record.quantity) || 0, + checked_at: record.checked_at || null, + checker_name: checkerName || null, + }); + } else { + // 未知商品(stock_id 为空)同样进入 goods 子列表,输出记录快照字段 + hasUnknown = true; + goods.push({ + record_id: record.id, + stock_id: null, + item_code: String(record.barcode || '').trim() || null, + item_name: String(record.item_name || record.barcode || '').trim() || null, + barcode: String(record.barcode || '').trim() || null, + images: Array.isArray(record.images) ? record.images : [], + store_id: null, + store_name: null, + quantity: Number(record.quantity) || 0, + checked_at: record.checked_at || null, + checker_name: checkerName || null, + }); + } + } + + const rowLocationId = detailRow.location_id !== null && detailRow.location_id !== undefined + ? Number(detailRow.location_id) + : null; + return { + detail_id: detailId, + location_id: rowLocationId, + // space_id 为 location_id 的同义字段,供调用方直接回传 stock.check.report + space_id: rowLocationId, + location_code: locationCode, + location_name: locationName, + status: detailRecords.length > 0 ? 'checked' : 'unchecked', + has_unknown: hasUnknown, + is_empty: isEmptyLocation, + checked_at: lastCheckedAt, + checkers: [ ...checkerSet ], + goods, + }; + }); + } + + /** + * 构建 goods 视图行:按商品(stock_id)汇总输出,一个商品一行; + * 同商品的库位明细行(scope_type=goods,按「商品+库位」拆行、唯一键 check_id+stock_id+location_id) + * 合并为一行:行级数量跨明细合计(账面快照合计、作业记录按库位合并), + * locations 每项带该库位明细行ID(detail_id)与账面快照(snapshot_quantity,明盘)供逐库位上报/钻取; + * stock_id 为空/异常的明细行无法按商品归并,各自成行。 + * locations 为商品所在全部库位(wms_storage 中该商品的 space_id 集合,按拣货路径排序): + * 明盘(mode=open)每库位含 system_quantity(该库位账面数量,wms_storage space+stock + * SUM(available_quantity),无库存记录库位为 0)、locked_quantity(该库位锁定数量, + * wms_storage space+stock SUM(locked_quantity))与 quantity(该库位盘点数量=实盘合计,未盘库位为 0),三者区分开; + * 盲盘(mode=blind)只显示库位(location_code)不含任何数量字段;已盘库位额外含 + * checked_at/checker_name/record_ids/images,未盘库位这些字段为 null/空数组; + * 商品库存已无记录但已盘的库位(仅记录库位)追加在末尾。 + * 明盘行级返回 system_quantity(账面快照合计=该商品各库位明细行快照之和)/ + * checked_quantity(已盘合计)/diff_quantity/is_diff; + * 静态盘点(is_static=1)另返回 picking_completed(1=该商品已完成拣货/0=未完成, + * 口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0)与明盘下的 locked_quantity + * (该商品仓库内锁定量合计;盲盘不输出该数值); + * 商品基础信息批量取自 stockWarehouse.getStockDetails(未命中回退明细商品快照), + * 货主名经 _resolveStoreNameMap 解析。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} checkId 盘点任务ID。 + * @param {string} mode 盘点方式:open=明盘/blind=盲盘。 + * @param {boolean} [isStatic=false] 是否静态盘点(is_static=1):true=账面取明细快照, + * false=账面取当前 wms_storage(可用数量)。 + * @return {Promise>} 商品视图行列表(按商品首个明细 id 升序)。 + */ + async _buildGoodsWorkRows(warehouseId, checkId, mode, isStatic = false) { + const { ctx } = this; + const { Op, fn, col, literal } = ctx.app.Sequelize; + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'goods' }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const records = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 挂载作业记录图片(FileReference business_type=stock_check_record,与 result 口径一致) + await this._attachRecordImages(records); + + const isOpen = mode !== 'blind'; + + // 商品基础信息批量取(getStockDetails 带缓存,未命中回退明细商品快照)与货主名映射 + const stockIds = [ ...new Set(detailRows + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + + // 静态盘点:拣货完成判定——商品在仓库内仍存在锁定量(wms_storage SUM(locked_quantity) > 0) + // 即说明有已分配储位但未拣出的在途出库,拣货未完成(report 对未完成拣货的商品拒绝上报) + const stockLockedQuantityMap = isStatic + ? await this._fetchStockLockedQuantityMap(warehouseId, stockIds) + : new Map(); + + let stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId: Number(warehouseId), + }); + stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ])); + } + const storeIds = [ ...stockDetailMap.values() ] + .map(item => Number(item.store_id)) + .filter(storeId => Number.isInteger(storeId) && storeId > 0); + const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId); + + // 商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id + // 同时按 stock+space 汇总账面数量(该库位系统库存,口径=可用数量)与锁定数量, + // 供明盘 locations.system_quantity / locked_quantity 使用 + const stockSpaceIdsMap = new Map(); + const stockSpaceQuantityMap = new Map(); + const allSpaceIds = new Set(); + if (stockIds.length > 0) { + const storageRows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: Number(warehouseId), + stock_id: { [Op.in]: stockIds }, + is_enabled: 1, + // 排除无头库位(与明细生成口径一致) + space_id: { [Op.in]: literal(VALID_SPACE_SQL) }, + }, + attributes: [ + 'stock_id', + 'space_id', + [ literal('SUM(available_quantity)'), 'system_quantity' ], + [ fn('SUM', col('locked_quantity')), 'locked_quantity' ], + ], + group: [ 'stock_id', 'space_id' ], + raw: true, + }); + for (const storageRow of storageRows) { + const stockId = Number(storageRow.stock_id); + if (!stockSpaceIdsMap.has(stockId)) { + stockSpaceIdsMap.set(stockId, []); + stockSpaceQuantityMap.set(stockId, new Map()); + } + const spaceId = Number(storageRow.space_id); + stockSpaceIdsMap.get(stockId).push(spaceId); + stockSpaceQuantityMap.get(stockId).set(spaceId, { + system_quantity: Number(storageRow.system_quantity) || 0, + locked_quantity: Number(storageRow.locked_quantity) || 0, + }); + allSpaceIds.add(spaceId); + } + } + + // 库位表(space_code + 拣货路径),按拣货路径排序:pick_sequence 升序、pick_priority 降序(同值按 id 升序兜底) + let sortedSpaceRows = []; + if (allSpaceIds.size > 0) { + const locationRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [Op.in]: [ ...allSpaceIds ] } }, + attributes: [ 'id', 'space_code', 'pick_sequence', 'pick_priority' ], + raw: true, + }); + sortedSpaceRows = locationRows.sort((left, right) => { + const sequenceDiff = Number(left.pick_sequence || 0) - Number(right.pick_sequence || 0); + if (sequenceDiff !== 0) { + return sequenceDiff; + } + const priorityDiff = Number(right.pick_priority || 0) - Number(left.pick_priority || 0); + if (priorityDiff !== 0) { + return priorityDiff; + } + return Number(left.id) - Number(right.id); + }); + } + const spaceCodeByStockMap = new Map(); + const spaceQuantityByStockMap = new Map(); + // 库位编码 → 有效库位ID(同编码多条时取拣货顺序第一条):供 goods 视图 locations[] 回传 location_id, + // 让调用方能直接把库位ID回传 stock.check.report(否则只有编码,服务端只能按编码猜库位) + const spaceIdByCodeMap = new Map(); + for (const row of sortedSpaceRows) { + const spaceCode = String(row.space_code || '').trim(); + if (spaceCode && !spaceIdByCodeMap.has(spaceCode)) { + spaceIdByCodeMap.set(spaceCode, Number(row.id)); + } + } + // 已盘库位(当前库存已无该商品)补查有效库位ID,口径与 workData space 视图一致(zone 存在未删除) + const uncoveredRecordCodes = [ ...new Set(records + .map(record => String(record.location_code || '').trim()) + .filter(code => code && !spaceIdByCodeMap.has(code))) ]; + if (uncoveredRecordCodes.length > 0) { + const uncoveredRows = await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: Number(warehouseId), + space_code: { [Op.in]: uncoveredRecordCodes }, + }, + attributes: [ 'id', 'space_code' ], + include: [{ + model: ctx.model.LocationZone, + as: 'zone', + attributes: [], + required: true, + }], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const row of uncoveredRows) { + const spaceCode = String(row.space_code || '').trim(); + if (spaceCode && !spaceIdByCodeMap.has(spaceCode)) { + spaceIdByCodeMap.set(spaceCode, Number(row.id)); + } + } + } + for (const [ stockId, spaceIds ] of stockSpaceIdsMap.entries()) { + const spaceRowMap = new Map(sortedSpaceRows.map(row => [ Number(row.id), row ])); + const orderedRows = spaceIds + .map(spaceId => spaceRowMap.get(spaceId)) + .filter(Boolean) + .sort((left, right) => sortedSpaceRows.indexOf(left) - sortedSpaceRows.indexOf(right)); + spaceCodeByStockMap.set( + stockId, + orderedRows.map(row => String(row.space_code || '').trim()) + ); + const quantityByCode = new Map(); + for (const row of orderedRows) { + const spaceCode = String(row.space_code || '').trim(); + const spaceQuantity = (stockSpaceQuantityMap.get(stockId) || new Map()).get(Number(row.id)) || {}; + quantityByCode.set(spaceCode, { + system_quantity: Number(spaceQuantity.system_quantity) || 0, + locked_quantity: Number(spaceQuantity.locked_quantity) || 0, + }); + } + spaceQuantityByStockMap.set(stockId, quantityByCode); + } + + // 按明细聚合作业记录 + const recordsByDetail = new Map(); + for (const record of records) { + const detailId = Number(record.detail_id); + if (!recordsByDetail.has(detailId)) { + recordsByDetail.set(detailId, []); + } + recordsByDetail.get(detailId).push(record); + } + + // 按商品汇总:同商品的库位明细行合并为一组(分组顺序沿用明细 id 升序); + // stock_id 为空/异常的明细行无法按商品归并,各自成组(保持单行输出) + const detailGroups = []; + const groupIndexByStock = new Map(); + for (const detailRow of detailRows) { + const detailStockId = Number(detailRow.stock_id); + const groupKey = Number.isInteger(detailStockId) && detailStockId > 0 + ? `stock_${detailStockId}` + : `detail_${Number(detailRow.id)}`; + if (!groupIndexByStock.has(groupKey)) { + groupIndexByStock.set(groupKey, detailGroups.length); + detailGroups.push([]); + } + detailGroups[groupIndexByStock.get(groupKey)].push(detailRow); + } + + return detailGroups.map(groupRows => { + const firstDetailRow = groupRows[0]; + const stockId = Number(firstDetailRow.stock_id); + // 该商品全部明细的作业记录(明细 id 升序 → 记录 id 升序) + const detailRecords = []; + for (const groupRow of groupRows) { + detailRecords.push(...(recordsByDetail.get(Number(groupRow.id)) || [])); + } + // 库位编码 → 该库位明细行(明细ID + 账面快照):供逐库位钻取/上报回传, + // 同编码多条时取明细 id 最小的一行(正常数据唯一键已保证一个商品一个库位一行) + const detailByLocationCode = new Map(); + for (const groupRow of groupRows) { + const groupRowCode = String(groupRow.location_code || '').trim(); + if (!groupRowCode || detailByLocationCode.has(groupRowCode)) { + continue; + } + detailByLocationCode.set(groupRowCode, { + detail_id: Number(groupRow.id), + snapshot_quantity: Number(groupRow.system_quantity) || 0, + }); + } + const stockDetail = stockDetailMap.get(stockId) || {}; + const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : []; + const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null; + + const row = { + stock_id: stockId, + item_code: stockDetail.item_code || firstDetailRow.item_code || null, + item_name: stockDetail.item_name || firstDetailRow.item_name || null, + spec: stockDetail.sku_property || firstDetailRow.spec || null, + store_id: storeId, + store_name: storeNameMap.get(storeId) || null, + barcode: (barcodes[0] && barcodes[0].barcode) || null, + images: stockDetail.image_url || [], + // 账面取值来源:静态盘点=明细快照(盘点基准冻结),非静态=当前 wms_storage 账面 + is_static: isStatic ? 1 : 0, + book_source: isStatic ? 'snapshot' : 'storage', + locations: [], + }; + // 静态盘点:该商品是否已完成拣货(1=已完成/0=未完成,判定口径=仓库内该商品锁定量是否为 0); + // 盲盘不输出锁定量数值(与盲盘不含数量字段口径一致),仅输出完成标记 + if (isStatic) { + const lockedQuantity = stockLockedQuantityMap.get(stockId) || 0; + row.picking_completed = lockedQuantity > 0 ? 0 : 1; + if (isOpen) { + row.locked_quantity = lockedQuantity; + } + } + if (isOpen) { + row.system_quantity = 0; + row.checked_quantity = 0; + row.diff_quantity = 0; + row.is_diff = 0; + } + + // 按库位聚合该明细的作业记录(库位为空归入"无库位"分组,按首条记录 id 升序) + const locationGroups = new Map(); + for (const record of detailRecords) { + const recordLocationCode = record.location_code !== null && record.location_code !== undefined + ? String(record.location_code).trim() + : ''; + if (!locationGroups.has(recordLocationCode)) { + locationGroups.set(recordLocationCode, { + location_code: recordLocationCode || null, + quantity: 0, + first_record_id: Number(record.id) || 0, + checked_at: null, + checker_name: null, + record_ids: [], + images: [], + }); + } + const group = locationGroups.get(recordLocationCode); + group.quantity += Number(record.quantity) || 0; + group.record_ids.push(Number(record.id) || 0); + for (const image of (Array.isArray(record.images) ? record.images : [])) { + if (!group.images.some(item => item && Number(item.id) === Number(image.id))) { + group.images.push(image); + } + } + if (record.checked_at && (!group.checked_at || new Date(record.checked_at) > new Date(group.checked_at))) { + group.checked_at = record.checked_at; + group.checker_name = String(record.checker_name || '').trim() || null; + } + } + + // locations:商品所在全部库位(基础列表),已盘库位合并作业信息,未盘库位为空信息; + // 商品库存已无记录但已盘的库位(仅记录库位)追加在末尾 + const baseLocationCodes = (spaceCodeByStockMap.get(stockId) || []).filter(code => code !== ''); + const mergedLocationCodes = new Set(baseLocationCodes); + const extraGroups = []; + for (const [ code, group ] of locationGroups.entries()) { + if (code && !mergedLocationCodes.has(code)) { + extraGroups.push(group); + } + } + + const buildLocationItem = (code, group) => { + const locationIdValue = (code && spaceIdByCodeMap.get(code)) || (group && group.location_id) || null; + const locationDetail = detailByLocationCode.get(code || '') || null; + const locationItem = { + // 库位ID(wms_location_space.id):优先有效库位行,其次作业记录回填值; + // space_id 供调用方直接回传 stock.check.report(location_id 为兼容别名) + location_id: locationIdValue, + space_id: locationIdValue, + location_code: code || null, + // 该库位对应的盘点明细ID(商品按库位拆行);无明细快照的库位为 null + detail_id: locationDetail ? locationDetail.detail_id : null, + checked_at: group ? group.checked_at : null, + checker_name: group ? group.checker_name : null, + record_ids: group ? group.record_ids : [], + images: group ? group.images : [], + }; + if (isOpen) { + // 明盘:逐库位账面按任务是否静态取值——静态盘点取该库位明细快照(盘点基准冻结), + // 非静态取当前 wms_storage 账面(可用数量);两者同时输出便于对照, + // system_quantity 始终为「本次参与差异计算的账面」 + const spaceQuantity = (spaceQuantityByStockMap.get(stockId) || new Map()).get(code || '') || {}; + const storageQuantity = Number(spaceQuantity.system_quantity) || 0; + const snapshotQuantity = locationDetail ? locationDetail.snapshot_quantity : 0; + locationItem.system_quantity = isStatic ? snapshotQuantity : storageQuantity; + locationItem.storage_quantity = storageQuantity; + locationItem.locked_quantity = Number(spaceQuantity.locked_quantity) || 0; + locationItem.snapshot_quantity = snapshotQuantity; + locationItem.quantity = group ? group.quantity : 0; + } + return locationItem; + }; + + row.locations = [ + ...baseLocationCodes.map(code => buildLocationItem(code, locationGroups.get(code) || null)), + ...extraGroups + .sort((left, right) => left.first_record_id - right.first_record_id) + .map(group => buildLocationItem(group.location_code, group)), + ]; + + // "无库位"分组(记录 location_code 为空)追加在末尾 + const emptyLocationGroup = locationGroups.get(''); + if (emptyLocationGroup) { + row.locations.push(buildLocationItem(null, emptyLocationGroup)); + } + + if (isOpen && row.locations.length > 0) { + // 行级账面 = 各库位账面(按静态/非静态口径取值)之和 + row.system_quantity = row.locations.reduce( + (sum, item) => sum + (Number(item.system_quantity) || 0), + 0 + ); + row.checked_quantity = row.locations.reduce((sum, item) => sum + (Number(item.quantity) || 0), 0); + // 差异仅对存在作业记录的行计算(未盘行差异保持 0,避免误显盘亏) + if (detailRecords.length > 0) { + row.diff_quantity = row.checked_quantity - row.system_quantity; + row.is_diff = row.diff_quantity !== 0 ? 1 : 0; + } + } + + return row; + }); + } + + /** + * 构建 space 视图行:以任务商品(scope_type=goods 的 stock_id 集合)所在的库位为列表。 + * 库位集合取 wms_storage(warehouse_id + stock_id 在集合内 + is_enabled=1 且未删除,DISTINCT space_id) + * ∪ 作业记录库位(上报库位与明细库位编码一致时归并到明细固化 location_id, + * 无头库位归并到同编码有效库位,避免同编码出现重复行), + * 库位仅按拣货顺序排序:pick_sequence 升序(pick_priority/库位 id 不参与排序, + * 同值保持库位查询顺序); + * 行内 goods 为该库位下的任务商品:明盘含 system_quantity(wms_storage space+stock + * SUM(available_quantity))、locked_quantity(wms_storage space+stock SUM(locked_quantity)) + * 与 checked_quantity(该商品在该库位的实盘合计),盲盘不返回任何数量字段; + * 静态盘点(is_static=1)goods 子项另含 picking_completed(1=该商品已完成拣货/0=未完成, + * 口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0,按商品维度判定,明盘盲盘均返回); + * status 已盘口径:该 (库位, 商品) 存在作业记录(兼容按明细 + 库位编码命中); + * 未在 wms_storage 有库位的商品不入列表(无库位可聚)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} checkId 盘点任务ID。 + * @param {string} mode 盘点方式:open=明盘/blind=盲盘。 + * @param {boolean} [isStatic=false] 是否静态盘点(is_static=1):true=账面取明细快照, + * false=账面取当前 wms_storage(可用数量)。 + * @return {Promise>} 聚合库位视图行列表(按拣货路径排序)。 + */ + async _buildSpaceWorkRows(warehouseId, checkId, mode, isStatic = false) { + const { ctx } = this; + const { Op, fn, col, literal } = ctx.app.Sequelize; + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'goods' }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const stockIds = [ ...new Set(detailRows + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + if (stockIds.length === 0) { + return []; + } + + const isOpen = mode !== 'blind'; + + // 静态盘点:拣货完成判定——商品在仓库内仍存在锁定量(wms_storage SUM(locked_quantity) > 0) + // 即说明有已分配储位但未拣出的在途出库,拣货未完成;判定按商品维度(非库位维度), + // 同一商品在各库位行上的 picking_completed 取值一致 + const stockLockedQuantityMap = isStatic + ? await this._fetchStockLockedQuantityMap(warehouseId, stockIds) + : new Map(); + + const records = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 挂载作业记录图片(FileReference business_type=stock_check_record,与 result 口径一致) + await this._attachRecordImages(records); + + // 商品基础信息批量取(getStockDetails 带缓存,未命中回退明细商品快照)与货主名映射 + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId: Number(warehouseId), + }); + const stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ])); + const storeIds = [ ...stockDetailMap.values() ] + .map(item => Number(item.store_id)) + .filter(storeId => Number.isInteger(storeId) && storeId > 0); + const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId); + const detailByStockId = new Map(detailRows.map(row => [ Number(row.stock_id), row ])); + const detailById = new Map(detailRows.map(row => [ Number(row.id), row ])); + // 明细按「库位 + 商品」索引:同一商品分布在多个库位时,库位行应取本库位对应的明细 + const detailByStockSpace = new Map( + detailRows.map(row => [ `${Number(row.location_id)}_${Number(row.stock_id)}`, row ]) + ); + + // 任务商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id, + // 同时按 (space_id, stock_id) 汇总账面数量(口径=可用数量)与锁定数量 + const storageRows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: Number(warehouseId), + stock_id: { [Op.in]: stockIds }, + is_enabled: 1, + // 排除无头库位(与明细生成口径一致) + space_id: { [Op.in]: literal(VALID_SPACE_SQL) }, + }, + attributes: [ + 'space_id', + 'stock_id', + [ literal('SUM(available_quantity)'), 'totalQuantity' ], + [ fn('SUM', col('locked_quantity')), 'totalLockedQuantity' ], + ], + group: [ 'space_id', 'stock_id' ], + raw: true, + }); + // 记录库位归一:上报库位与明细库位编码一致时以明细固化库位为准, + // 避免同仓库同编码存在多条库位(历史重复库位/无头库位)时同一编码在视图里出现两行 + const recordSpaceIdMap = new Map(); + for (const record of records) { + const recordCode = String(record.location_code || '').trim(); + const recordDetail = detailById.get(Number(record.detail_id)); + const detailLocationCode = recordDetail ? String(recordDetail.location_code || '').trim() : ''; + const detailLocationId = recordDetail ? Number(recordDetail.location_id) || 0 : 0; + const recordSpaceId = recordCode && detailLocationCode === recordCode && detailLocationId > 0 + ? detailLocationId + : Number(record.location_id) || 0; + recordSpaceIdMap.set(Number(record.id), recordSpaceId); + } + + // 无头库位(分区不存在/已删除)不直接入视图:同仓库同编码多条库位时会出现自定义字段为空的幽灵行, + // 统一归并到同编码的有效库位(优先该商品有启用库存的库位,其次 ID 最小) + const recordSpaceIdList = [ ...new Set([ ...recordSpaceIdMap.values() ].filter(spaceId => spaceId > 0)) ]; + if (recordSpaceIdList.length > 0) { + const validRecordSpaceRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [Op.in]: recordSpaceIdList } }, + attributes: [ 'id' ], + include: [{ + model: ctx.model.LocationZone, + as: 'zone', + attributes: [], + required: true, + }], + raw: true, + }); + const validRecordSpaceIdSet = new Set(validRecordSpaceRows.map(row => Number(row.id))); + const invalidRecordSpaceIds = recordSpaceIdList.filter(spaceId => !validRecordSpaceIdSet.has(spaceId)); + if (invalidRecordSpaceIds.length > 0) { + const invalidRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [Op.in]: invalidRecordSpaceIds } }, + attributes: [ 'id', 'space_code' ], + raw: true, + }); + const invalidSpaceCodeMap = new Map( + invalidRows.map(row => [ Number(row.id), String(row.space_code || '').trim() ]) + ); + const fallbackCodes = [ ...new Set([ ...invalidSpaceCodeMap.values() ].filter(Boolean)) ]; + const fallbackRows = fallbackCodes.length === 0 ? [] : await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: Number(warehouseId), + space_code: { [Op.in]: fallbackCodes }, + }, + attributes: [ 'id', 'space_code' ], + include: [{ + model: ctx.model.LocationZone, + as: 'zone', + attributes: [], + required: true, + }], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const fallbackIdsByCode = new Map(); + for (const row of fallbackRows) { + const code = String(row.space_code || '').trim(); + if (!fallbackIdsByCode.has(code)) { + fallbackIdsByCode.set(code, []); + } + fallbackIdsByCode.get(code).push(Number(row.id)); + } + const storageKeySet = new Set( + storageRows.map(row => `${Number(row.space_id)}_${Number(row.stock_id)}`) + ); + for (const record of records) { + const recordId = Number(record.id); + const currentSpaceId = recordSpaceIdMap.get(recordId) || 0; + if (!invalidRecordSpaceIds.includes(currentSpaceId)) { + continue; + } + const code = invalidSpaceCodeMap.get(currentSpaceId) + || String(record.location_code || '').trim(); + const candidates = fallbackIdsByCode.get(code) || []; + if (candidates.length === 0) { + continue; + } + const recordStockId = Number(record.stock_id) || 0; + const stockHit = recordStockId > 0 + ? candidates.find(spaceId => storageKeySet.has(`${spaceId}_${recordStockId}`)) + : 0; + recordSpaceIdMap.set(recordId, stockHit || candidates[0]); + } + } + } + + // 作业记录库位:优先已回填 location_id;未回填的按库位编码匹配 wms_location_space 补查, + // 保证商品库存已无记录时(如盘点前库存已出空)space 视图仍能展示已盘库位行 + // (编码一致时已在上面归并到明细固化库位)。 + const recordSpaceIds = []; + const recordLocationCodes = []; + for (const record of records) { + const recordSpaceId = recordSpaceIdMap.get(Number(record.id)) || 0; + if (recordSpaceId > 0) { + if (!recordSpaceIds.includes(recordSpaceId)) { + recordSpaceIds.push(recordSpaceId); + } + } else { + const locationCode = String(record.location_code || '').trim(); + if (locationCode && !recordLocationCodes.includes(locationCode)) { + recordLocationCodes.push(locationCode); + } + } + } + let codeMatchedLocationRows = []; + if (recordLocationCodes.length > 0) { + codeMatchedLocationRows = await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: Number(warehouseId), + space_code: { [Op.in]: recordLocationCodes }, + }, + attributes: [ 'id', 'space_code', 'custom_barcode', 'custom_name', 'pick_sequence' ], + raw: true, + }); + for (const row of codeMatchedLocationRows) { + const matchedSpaceId = Number(row.id); + if (!recordSpaceIds.includes(matchedSpaceId)) { + recordSpaceIds.push(matchedSpaceId); + } + } + } + + const storageSpaceIds = [ ...new Set(storageRows.map(row => Number(row.space_id))) ]; + const spaceIds = [ ...new Set([ ...storageSpaceIds, ...recordSpaceIds ]) ]; + if (spaceIds.length === 0) { + return []; + } + + const locationRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [Op.in]: spaceIds } }, + attributes: [ 'id', 'space_code', 'custom_barcode', 'custom_name', 'pick_sequence' ], + raw: true, + }); + + // 库位仅按拣货顺序排序:pick_sequence 升序(pick_priority/库位 id 不参与排序, + // 同值保持库位查询顺序,依赖 Array.sort 稳定排序) + const sortedLocations = locationRows.sort((left, right) => + Number(left.pick_sequence || 0) - Number(right.pick_sequence || 0) + ); + + // 库位商品账面/锁定映射(键 `${space_id}_${stock_id}`) + const storageQuantityMap = new Map(); + for (const storageRow of storageRows) { + storageQuantityMap.set( + `${Number(storageRow.space_id)}_${Number(storageRow.stock_id)}`, + { + system_quantity: Number(storageRow.totalQuantity) || 0, + locked_quantity: Number(storageRow.totalLockedQuantity) || 0, + } + ); + } + + // 按库位归集任务商品存储行 + const storageBySpace = new Map(); + for (const storageRow of storageRows) { + const spaceId = Number(storageRow.space_id); + if (!storageBySpace.has(spaceId)) { + storageBySpace.set(spaceId, []); + } + storageBySpace.get(spaceId).push(storageRow); + } + + // 按 (detail_id, location_code) 聚合作业记录(已盘口径与实盘合计用) + const recordsByDetailLocation = new Map(); + for (const record of records) { + const detailId = Number(record.detail_id); + const locationCode = String(record.location_code || '').trim(); + const key = `${detailId}_${locationCode}`; + if (!recordsByDetailLocation.has(key)) { + recordsByDetailLocation.set(key, []); + } + recordsByDetailLocation.get(key).push(record); + } + + // 按 (detail_id, space_id) 聚合作业记录(库位编码大小写/回填差异时兜底按库位ID命中) + const codeToSpaceIdMap = new Map( + codeMatchedLocationRows.map(row => [ String(row.space_code || '').trim(), Number(row.id) ]) + ); + const recordsByDetailSpace = new Map(); + // 记录按「库位 + 商品」归集:跨明细上报(记录明细与库位不一致)时仍能命中对应库位行 + const recordsBySpaceStock = new Map(); + // 仅记录库位(当前库存无该商品)按库位归集记录,供 space 视图补行 + const recordsBySpace = new Map(); + for (const record of records) { + let spaceId = recordSpaceIdMap.get(Number(record.id)) || 0; + if (!spaceId) { + spaceId = codeToSpaceIdMap.get(String(record.location_code || '').trim()) || 0; + } + if (!spaceId) { + continue; + } + const detailId = Number(record.detail_id); + const detailSpaceKey = `${detailId}_${spaceId}`; + if (!recordsByDetailSpace.has(detailSpaceKey)) { + recordsByDetailSpace.set(detailSpaceKey, []); + } + recordsByDetailSpace.get(detailSpaceKey).push(record); + + const recordStockId = Number(record.stock_id) || 0; + if (recordStockId > 0) { + const spaceStockKey = `${spaceId}_${recordStockId}`; + if (!recordsBySpaceStock.has(spaceStockKey)) { + recordsBySpaceStock.set(spaceStockKey, []); + } + recordsBySpaceStock.get(spaceStockKey).push(record); + } + + if (!recordsBySpace.has(spaceId)) { + recordsBySpace.set(spaceId, []); + } + recordsBySpace.get(spaceId).push(record); + } + + return sortedLocations.map(locationRow => { + const spaceId = Number(locationRow.id); + const spaceCode = String(locationRow.space_code || '').trim(); + // 库存行 + 仅记录库位(当前库存已无该商品)的已知商品补行 + const spaceStorageRows = storageBySpace.get(spaceId) || []; + const knownStorageStockIds = new Set(spaceStorageRows.map(row => Number(row.stock_id))); + const mergedRows = [ ...spaceStorageRows ]; + for (const record of recordsBySpace.get(spaceId) || []) { + const recordStockId = Number(record.stock_id) || 0; + if (recordStockId > 0 && !knownStorageStockIds.has(recordStockId)) { + mergedRows.push({ space_id: spaceId, stock_id: recordStockId, totalQuantity: 0, totalLockedQuantity: 0 }); + knownStorageStockIds.add(recordStockId); + } + } + const goods = mergedRows + .sort((left, right) => Number(left.stock_id) - Number(right.stock_id)) + .map(storageRow => { + const stockId = Number(storageRow.stock_id); + const detailRow = detailByStockSpace.get(`${spaceId}_${stockId}`) || detailByStockId.get(stockId); + if (!detailRow) { + return null; + } + const stockDetail = stockDetailMap.get(stockId) || {}; + const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : []; + const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null; + const detailId = Number(detailRow.id); + const locationRecords = recordsBySpaceStock.get(`${spaceId}_${stockId}`) + || recordsByDetailSpace.get(`${detailId}_${spaceId}`) + || recordsByDetailLocation.get(`${detailId}_${spaceCode}`) + || []; + // 作业照片与记录ID(供前端展示与编辑/移除记录) + const recordImages = []; + const recordIds = []; + for (const record of locationRecords) { + recordIds.push(Number(record.id) || 0); + for (const image of (Array.isArray(record.images) ? record.images : [])) { + if (!recordImages.some(item => item && Number(item.id) === Number(image.id))) { + recordImages.push(image); + } + } + } + const item = { + detail_id: detailId, + stock_id: stockId, + item_code: stockDetail.item_code || detailRow.item_code || null, + item_name: stockDetail.item_name || detailRow.item_name || null, + spec: stockDetail.sku_property || detailRow.spec || null, + store_id: storeId, + store_name: storeNameMap.get(storeId) || null, + barcode: (barcodes[0] && barcodes[0].barcode) || null, + images: recordImages, + record_ids: recordIds, + }; + if (isOpen) { + const storageQuantity = storageQuantityMap.get(`${spaceId}_${stockId}`) || {}; + const liveQuantity = Number(storageQuantity.system_quantity) || 0; + const snapshotQuantity = Number(detailRow.system_quantity) || 0; + // 账面取值:静态盘点=明细快照(盘点基准冻结),非静态=当前 wms_storage 账面 + item.system_quantity = isStatic ? snapshotQuantity : liveQuantity; + item.storage_quantity = liveQuantity; + item.locked_quantity = Number(storageQuantity.locked_quantity) || 0; + item.snapshot_quantity = snapshotQuantity; + item.checked_quantity = locationRecords.reduce( + (sum, record) => sum + (Number(record.quantity) || 0), + 0 + ); + } + // 静态盘点:该商品是否已完成拣货(1=已完成/0=未完成,按商品维度判定—— + // 仓库内该商品锁定量为 0 才算完成;盲盘同样输出,便于上报前拦截提示) + if (isStatic) { + item.picking_completed = (stockLockedQuantityMap.get(stockId) || 0) > 0 ? 0 : 1; + } + item.status = locationRecords.length > 0 ? 'checked' : 'unchecked'; + return item; + }) + .filter(item => item !== null); + + return { + // 库位字段对齐库位查询惯例(index.searchSpace:id/space_code/custom_barcode/custom_name); + // location_id / space_id 均为 id 的同义字段,上报 stock.check.report 时以 space_id 必传 + id: spaceId, + location_id: spaceId, + space_id: spaceId, + space_code: spaceCode || null, + custom_barcode: locationRow.custom_barcode != null && String(locationRow.custom_barcode).trim() !== '' + ? String(locationRow.custom_barcode).trim() + : null, + custom_name: locationRow.custom_name != null && String(locationRow.custom_name).trim() !== '' + ? String(locationRow.custom_name).trim() + : null, + goods, + }; + }); + } + + /** + * 批量删除盘点作业记录(按行清除盘点信息)。 + * 仅主表状态 approved/checking 允许删除;记录不存在或不属于该任务/仓库时计入 skipped_ids 不报错; + * 删除后重算 checked_items/diff_items/detail_status(明细记录删光后该明细回到未盘),主表状态不回退; + * 同时清理被删记录的图片引用(FileReference business_type=stock_check_record,失败仅告警不影响主流程)。 + * 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版 { record_id, deleted, ...summary } + * 变更为 { deleted_count, deleted_ids, skipped_ids, ...summary }。 + * + * @param {Object} params 删除参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {Array|number} params.recordIds 作业记录ID数组(单值自动转数组,单次上限 200; + * 方法层已兼容 record_ids/recordIds/record_id 写法)。 + * @return {Promise} { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status }; + * deleted_ids/skipped_ids 均保持入参顺序。 + * @throws {Error} 参数非法、任务不存在或状态不允许时抛出业务错误(错误码 400)。 + */ + async recordDelete(params = {}) { + const { warehouseId, id, recordIds } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许删除作业记录`); + } + + const numericRecordIds = this._normalizeIdList(recordIds); + if (numericRecordIds.length === 0) { + throw this.createBusinessError('请至少选择一条作业记录'); + } + if (numericRecordIds.length > 200) { + throw this.createBusinessError('单次最多删除 200 条作业记录'); + } + + // 仓库隔离查询记录:id in ids + check_id + warehouse_id;查不到的 ID 计入 skipped_ids(不报错) + const recordRows = await ctx.model.StockCheckRecord.findAll({ + where: { + id: { [Op.in]: numericRecordIds }, + check_id: checkId, + warehouse_id: Number(warehouseId), + }, + attributes: [ 'id' ], + raw: true, + }); + const foundIdSet = new Set(recordRows.map(row => Number(row.id))); + const deletedIds = []; + const skippedIds = []; + for (const recordId of numericRecordIds) { + if (foundIdSet.has(recordId)) { + deletedIds.push(recordId); + } else { + skippedIds.push(recordId); + } + } + + if (deletedIds.length > 0) { + await ctx.model.StockCheckRecord.destroy({ + where: { id: { [Op.in]: deletedIds } }, + }); + + // 清理被删记录的图片引用(图片独立维护,仿收货口径):失败仅告警,不影响主流程 + try { + await ctx.model.FileReference.destroy({ + where: { + business_type: 'stock_check_record', + business_id: { [Op.in]: deletedIds.map(String) }, + }, + }); + } catch (error) { + ctx.logger.warn(`[stock.check.recordDelete] 清理作业记录图片引用失败: ${error && error.message ? error.message : error}`); + } + } + + // 重算 checked_items / diff_items / detail_status(明细记录删光后该明细回到未盘),主表状态不回退 + const summary = await this._recalcCheckSummary(checkId); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_DELETE_RECORD', + operationAction: 'UPDATE', + changeSummary: `批量删除盘点作业记录 ${deletedIds.length} 条(跳过 ${skippedIds.length} 条)`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + deletedIds, + skippedIds, + message: `批量删除盘点作业记录 ${deletedIds.length} 条`, + }, + }); + + return { + deleted_count: deletedIds.length, + deleted_ids: deletedIds, + skipped_ids: skippedIds, + total_items: summary.total_items, + checked_items: summary.checked_items, + diff_items: summary.diff_items, + detail_status: summary.detail_status, + }; + } + + /** + * 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。 + * 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记), + * 该库位回到未盘状态;仅任务范围为库位(type=location)且状态 approved/checking 时允许; + * 删除后重算 checked_items/diff_items/detail_status,主表状态不回退; + * 同时清理被删记录的图片引用(失败仅告警不影响主流程)。 + * + * @param {Object} params 清除参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number} params.locationId 库位ID(wms_location_space.id)。 + * @return {Promise} { detail_id, location_id, deleted_count, total_items, checked_items, diff_items, detail_status }。 + * @throws {Error} 参数非法、任务不存在、状态不允许、非库位任务或库位不在任务范围内时抛出业务错误(错误码 400)。 + */ + async recheckClearLocation(params = {}) { + const { warehouseId, id, locationId } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const checkId = Number(id); + const normalizedLocationId = Number(locationId); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + if (!Number.isInteger(normalizedLocationId) || normalizedLocationId <= 0) { + throw this.createBusinessError('库位ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许清除库位盘点信息`); + } + const normalizedType = String(check.type || '').trim(); + if (normalizedType !== 'location') { + throw this.createBusinessError('仅库位盘点任务支持重盘清除库位'); + } + + const detail = await ctx.model.StockCheckDetail.findOne({ + where: { + check_id: checkId, + warehouse_id: Number(warehouseId), + location_id: normalizedLocationId, + scope_type: 'location', + }, + attributes: [ 'id', 'location_id', 'location_code' ], + }); + if (!detail) { + throw this.createBusinessError('该库位不在盘点任务范围内'); + } + const detailId = Number(detail.id); + + // 删除该明细全部作业记录(含空库位标记) + const recordRows = await ctx.model.StockCheckRecord.findAll({ + where: { detail_id: detailId, check_id: checkId }, + attributes: [ 'id' ], + raw: true, + }); + const deletedCount = recordRows.length; + if (deletedCount > 0) { + await ctx.model.StockCheckRecord.destroy({ + where: { + detail_id: detailId, + check_id: checkId, + warehouse_id: Number(warehouseId), + }, + }); + + // 清理被删记录的图片引用:失败仅告警,不影响主流程 + try { + await ctx.model.FileReference.destroy({ + where: { + business_type: 'stock_check_record', + business_id: { [Op.in]: recordRows.map(row => String(row.id)) }, + }, + }); + } catch (error) { + ctx.logger.warn(`[stock.check.recheckClearLocation] 清理作业记录图片引用失败: ${error && error.message ? error.message : error}`); + } + } + + // 重算 checked_items / diff_items / detail_status(该库位回到未盘),主表状态不回退 + const summary = await this._recalcCheckSummary(checkId); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_CLEAR_LOCATION', + operationAction: 'UPDATE', + changeSummary: `重盘清除库位 ${String(detail.location_code || '').trim() || normalizedLocationId}:删除作业记录 ${deletedCount} 条`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + detailId, + locationId: normalizedLocationId, + locationCode: String(detail.location_code || '').trim(), + message: `重盘清除库位:删除作业记录 ${deletedCount} 条`, + }, + }); + + return { + detail_id: detailId, + location_id: normalizedLocationId, + deleted_count: deletedCount, + total_items: summary.total_items, + checked_items: summary.checked_items, + diff_items: summary.diff_items, + detail_status: summary.detail_status, + }; + } + + /** + * 计算任务数量差异汇总(盘盈/盘亏/差异明细数,纯查询无副作用)。 + * + * 口径: + * - 商品范围(scope_type=goods):按商品聚合(一行一商品,多个库位明细行合并)—— + * 已盘商品差异 = 商品实盘合计 - 账面快照 system_quantity 合计;未盘商品按实盘 0 处理 + * (差异 = -账面快照合计,即盘亏); + * - 库位行(scope_type=location):按商品聚合 vs wms_storage 账面;未盘库位行无法枚举商品, + * 不计差异; + * - 未知商品(记录 stock_id 为空)无账面:实盘 > 0 即盘盈,必然计入差异。 + * 盘亏合计以正数返回(loss_total 为正数口径)。 + * + * @param {number} checkId 盘点任务ID。 + * @return {Promise} { diff_items, profit_total, loss_total }。 + */ + async _calcQuantityDiffSummary(checkId) { + const { ctx } = this; + + const summary = await this._recalcCheckSummary(checkId); + const checkedQuantityByDetail = summary.checked_quantity_by_detail || new Map(); + const stockQuantityByDetail = summary.stock_quantity_by_detail || new Map(); + const unknownQuantityByDetail = summary.unknown_quantity_by_detail || new Map(); + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: Number(checkId) }, + attributes: [ 'id', 'scope_type', 'stock_id', 'system_quantity' ], + raw: true, + }); + let profitTotal = 0; + let lossTotal = 0; + let diffItems = 0; + // 商品范围:按商品聚合(一行一商品,多个库位明细行合并)—— + // 已盘商品差异 = 商品实盘合计 - 账面快照合计;未盘商品按实盘 0 处理(差异 = -账面快照合计,即盘亏) + const goodsByStock = new Map(); + for (const detailRow of detailRows) { + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + if (scopeType !== 'goods') { + continue; + } + const stockId = Number(detailRow.stock_id); + const agg = goodsByStock.get(stockId) || { snapshot: 0, checked: 0, hasRecords: false }; + agg.snapshot += Number(detailRow.system_quantity || 0); + const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id)); + if (checkedQuantity !== undefined) { + agg.hasRecords = true; + agg.checked += checkedQuantity; + } + goodsByStock.set(stockId, agg); + } + for (const agg of goodsByStock.values()) { + const diffQuantity = agg.hasRecords ? agg.checked - agg.snapshot : -agg.snapshot; + if (diffQuantity !== 0) { + diffItems++; + if (diffQuantity > 0) { + profitTotal += diffQuantity; + } else { + lossTotal += Math.abs(diffQuantity); + } + } + } + for (const detailRow of detailRows) { + const detailId = Number(detailRow.id); + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + if (scopeType !== 'location') { + continue; + } + // 库位行:按商品聚合 vs wms_storage 账面;未盘库位行无法枚举商品,不计差异 + const byStock = stockQuantityByDetail.get(detailId); + const byUnknown = unknownQuantityByDetail.get(detailId); + if ((!byStock || byStock.size === 0) && (!byUnknown || byUnknown.size === 0)) { + continue; + } + let rowDiff = false; + for (const agg of (byStock ? byStock.values() : [])) { + const diffQuantity = agg.checked - (agg.system || 0); + if (diffQuantity !== 0) { + rowDiff = true; + if (diffQuantity > 0) { + profitTotal += diffQuantity; + } else { + lossTotal += Math.abs(diffQuantity); + } + } + } + // 未知商品无账面:实盘 > 0 即盘盈、必然计入差异 + for (const agg of (byUnknown ? byUnknown.values() : [])) { + if (agg.checked > 0) { + rowDiff = true; + profitTotal += agg.checked; + } + } + if (rowDiff) { + diffItems++; + } + } + + return { + diff_items: diffItems, + profit_total: profitTotal, + loss_total: lossTotal, + }; + } + + /** + * 完成盘点作业(允许部分未盘完成)。 + * 仅 approved/checking 状态允许;未盘商品明细按实盘 0 处理(差异 = -账面快照,计入盘亏与 diff_items); + * 已盘明细按作业记录聚合差异(盘盈合计 / 盘亏合计):商品行聚合 vs system_quantity 快照, + * 库位行按商品聚合 vs wms_storage 账面(space_id 为空时账面按 0,未盘库位行因无法枚举商品不计差异); + * 未知商品(stock_id 为空)无账面:差异 = 实盘 - 0 = 盘盈,计入盘盈合计与 diff_items; + * 完成后主表置 completed、写 end_time、detail_status=all_checked,并返回差异汇总与未盘明细数。 + * + * @param {Object} params 完成参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { id, status, total_items, checked_items, unchecked_items, diff_items, + * profit_total, loss_total, released_stock_ids }(released_stock_ids=本任务覆盖的商品ID, + * 完成即释放静态锁定;库位任务为空数组)。 + * @throws {Error} 状态不允许时抛出业务错误(错误码 400)。 + */ + async finish(params = {}) { + const { warehouseId, id } = params; + const { ctx } = this; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许完成盘点`); + } + + // 范围口径汇总:商品范围按商品计数,库位范围按明细行计数(与 _recalcCheckSummary 一致) + const scopeSummary = await this._countScopeSummary(checkId); + const totalItems = scopeSummary.total_items; + const checkedItems = scopeSummary.checked_items; + const uncheckedItems = totalItems - checkedItems; + + // 数量差异汇总(盘盈/盘亏/差异明细数,口径见 _calcQuantityDiffSummary) + const diffSummary = await this._calcQuantityDiffSummary(checkId); + const diffItems = diffSummary.diff_items; + const profitTotal = diffSummary.profit_total; + const lossTotal = diffSummary.loss_total; + + // 完成前先记录本任务覆盖的商品(完成=释放锁定,供响应与日志追溯) + const releasedStockIds = await this._collectGoodsStockIds(checkId); + + await check.update({ + status: 'completed', + end_time: new Date(), + detail_status: 'all_checked', + checked_items: checkedItems, + diff_items: diffItems, + }); + // 任务结束:清除静态锁定缓存,释放本任务商品(is_static=1 时其余锁定任务仍保留) + await this.refreshStaticLockCache(warehouseId); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_FINISH', + operationAction: 'UPDATE', + changeSummary: `完成盘点:差异明细 ${diffItems},盘盈 ${profitTotal},盘亏 ${lossTotal},未盘 ${uncheckedItems}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + diffItems, + profitTotal, + lossTotal, + checkedItems, + uncheckedItems, + releasedStockIds, + message: `完成盘点:差异 ${diffItems} 项,盘盈 ${profitTotal},盘亏 ${lossTotal}${releasedStockIds.length > 0 ? `,释放静态锁定商品 ${releasedStockIds.length} 个` : ''}`, + }, + }); + + return { + id: checkId, + status: 'completed', + total_items: totalItems, + checked_items: checkedItems, + unchecked_items: uncheckedItems, + diff_items: diffItems, + profit_total: profitTotal, + loss_total: lossTotal, + released_stock_ids: releasedStockIds, + }; + } + + /** + * 查询商品在仓库内的锁定量合计(wms_storage SUM(locked_quantity)),用于判定是否已完成拣货。 + * 分配储位(拣货锁库)只把 available_quantity 搬成 locked_quantity;拣货完成时 + * quantity 与 locked_quantity 同时扣减、available_quantity 不变。因此 + * locked_quantity > 0 即表示该商品仍有「已分配储位、尚未拣出」的在途出库,拣货未完成; + * locked_quantity = 0 即该商品已完全拣货。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array|number} stockIds 商品库存ID(wms_stock_warehouse.id),单值自动转数组。 + * @return {Promise>} stock_id → 锁定量合计(无库存记录的商品不在 Map 中)。 + */ + async _fetchStockLockedQuantityMap(warehouseId, stockIds) { + const { ctx } = this; + const { Op, literal } = ctx.app.Sequelize; + + const numericStockIds = [ ...new Set((Array.isArray(stockIds) ? stockIds : [ stockIds ]) + .map(stockId => Number(stockId)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + if (numericStockIds.length === 0) { + return new Map(); + } + + const rows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: Number(warehouseId), + stock_id: { [Op.in]: numericStockIds }, + is_enabled: 1, + }, + attributes: [ + 'stock_id', + [ literal('SUM(locked_quantity)'), 'lockedQuantity' ], + ], + group: [ 'stock_id' ], + raw: true, + }); + return new Map(rows.map(row => [ Number(row.stock_id), Number(row.lockedQuantity) || 0 ])); + } + + /** + * 刷新商品范围明细行的账面快照(盘点基准)。 + * 商品范围(scope_type=goods)任务把各明细行 system_quantity 刷新为该库位当时的可用数量 + * SUM(available_quantity)(= 库存总量 − 锁定数量 − 拦截锁定数量;库存记录不存在时按 0): + * 账面只统计可用数量,不把 locked_quantity(已分配储位、待拣出库)计入: + * 分配储位只搬 available→locked(账面不变),拣货完成同时扣 quantity 与 locked、 + * available 不变,因此「可用数量」口径在静态盘点窗口内对拣货动作不敏感。 + * - 提交审核时调用(保证 result/差异对比使用提交时点的账面); + * - 审核通过时再次调用(盘点基准以「审核完成=开始盘点」时刻为准,覆盖提交后到达的出入库); + * 库位范围(scope_type=location)账面实时查 wms_storage,不处理。 + * + * @param {number} checkId 盘点任务ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 刷新(含值变化)的明细行数。 + */ + async _refreshGoodsBookSnapshot(checkId, warehouseId) { + const { ctx } = this; + const { Op, literal } = ctx.app.Sequelize; + + const checkIdNumber = Number(checkId); + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkIdNumber, scope_type: 'goods' }, + raw: true, + }); + if (detailRows.length === 0) { + return 0; + } + + const stockIds = [ ...new Set(detailRows + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + + // 按 (stock_id, space_id) 聚合当前账面:SUM(可用数量) + const storageQuantityMap = new Map(); + if (stockIds.length > 0) { + const storageRows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: Number(warehouseId), + stock_id: { [Op.in]: stockIds }, + is_enabled: 1, + }, + attributes: [ + 'stock_id', + 'space_id', + [ literal('SUM(available_quantity)'), 'totalQuantity' ], + ], + group: [ 'stock_id', 'space_id' ], + raw: true, + }); + for (const storageRow of storageRows) { + storageQuantityMap.set( + `${Number(storageRow.stock_id)}_${Number(storageRow.space_id)}`, + Number(storageRow.totalQuantity) || 0 + ); + } + } + + // 逐明细行刷新库位级账面快照(刷新时点账面,库存记录不存在时按 0) + let refreshedCount = 0; + for (const detailRow of detailRows) { + const systemQuantity = storageQuantityMap.get( + `${Number(detailRow.stock_id)}_${Number(detailRow.location_id)}` + ) || 0; + if (Number(detailRow.system_quantity || 0) === systemQuantity) { + continue; + } + await ctx.model.StockCheckDetail.update( + { system_quantity: systemQuantity }, + { where: { id: detailRow.id } } + ); + refreshedCount++; + } + return refreshedCount; + } + + /** + * 完成盘点任务(提交审核)。 + * 仅 created/rejected 状态允许;校验 total_items>0 后置为 submitted; + * 库位范围明细(scope_type=location)缺少库位(location_id 为空或 location_code 为空)时不可提交。 + * + * @param {Object} params 提交参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { id, status }。 + * @throws {Error} 状态不允许、没有明细或存在缺少库位的明细时抛出业务错误(错误码 400)。 + */ + async submit(params = {}) { + const { warehouseId, id } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!SUBMIT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许提交审核`); + } + if (Number(check.total_items) <= 0) { + throw this.createBusinessError('盘点任务还没有明细行,无法提交审核'); + } + + // 盘点明细缺库位(location_id 为空或 location_code 为空)不可提交(脏数据防御): + // 库位范围明细天然必须带库位;商品范围明细按「商品 + 库位」拆行后同样必须带库位 + const missingLocationCount = await ctx.model.StockCheckDetail.count({ + where: { + check_id: checkId, + [Op.or]: [ + { location_id: null }, + { location_code: null }, + { location_code: '' }, + ], + }, + }); + if (missingLocationCount > 0) { + throw this.createBusinessError('存在缺少库位的盘点明细,无法提交审核'); + } + + // 提交审核时刷新商品范围明细行账面快照(提交时点账面=盘点基准, + // 快照失败则提交失败,保证「提交即快照」);审核通过时会再次刷新到「开始盘点」时点 + await this._refreshGoodsBookSnapshot(checkId, Number(warehouseId)); + + await check.update({ status: 'submitted' }); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_SUBMIT', + operationAction: 'UPDATE', + changeSummary: `提交审核盘点任务 ${check.check_no}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + message: `提交审核盘点任务 ${check.check_no}`, + }, + }); + + return { + id: checkId, + status: 'submitted', + }; + } + + /** + * 取消盘点任务。 + * 仅 created/submitted/rejected 状态允许;取消后置为 cancelled(终态)。 + * + * @param {Object} params 取消参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { id, status }。 + * @throws {Error} 状态不允许时抛出业务错误(错误码 400)。 + */ + async cancel(params = {}) { + const { warehouseId, id } = params; + const { ctx } = this; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!CANCEL_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许取消`); + } + + await check.update({ status: 'cancelled' }); + await this.refreshStaticLockCache(warehouseId); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_CANCEL', + operationAction: 'UPDATE', + changeSummary: `取消盘点任务 ${check.check_no}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + message: `取消盘点任务 ${check.check_no}`, + }, + }); + + return { + id: checkId, + status: 'cancelled', + }; + } + + /** + * 审核盘点任务。 + * 仅 submitted 状态允许;approve → approved,reject → rejected(reason 可选写入备注)。 + * + * @param {Object} params 审核参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {string} params.action 审核动作:approve=通过,reject=驳回。 + * @param {string} [params.reason] 驳回原因(写入备注)。 + * @return {Promise} { id, status, snapshot_refreshed }(snapshot_refreshed=本次刷新的商品明细快照行数,驳回为 0)。 + * @throws {Error} 状态不允许或动作非法时抛出业务错误(错误码 400)。 + */ + async audit(params = {}) { + const { warehouseId, id, action, reason } = params; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const actionValue = action ? String(action).trim() : ''; + if (actionValue !== 'approve' && actionValue !== 'reject') { + throw this.createBusinessError('审核动作仅支持 approve/reject'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (check.status !== 'submitted') { + throw this.createBusinessError(`当前状态(${check.status})不允许审核`); + } + + // 驳回原因:入参优先,为空时回退主表现有备注 + const reasonValue = reason !== undefined && reason !== null && String(reason).trim() !== '' + ? String(reason).trim() + : check.remark; + + if (actionValue === 'approve') { + // 审核完成即开始盘点基准:再次刷新商品范围明细快照(覆盖提交后到达的出入库), + // 并失效静态锁定缓存(is_static=1 的任务此刻起进入锁定集合) + const refreshedCount = await this._refreshGoodsBookSnapshot(checkId, Number(warehouseId)); + await check.update({ status: 'approved' }); + await this.refreshStaticLockCache(warehouseId); + return await this._writeAuditLogAndResult({ + check, + checkId, + warehouseId, + actionValue, + reasonValue, + refreshedCount, + }); + } + + await check.update({ + status: 'rejected', + remark: reasonValue, + }); + await this.refreshStaticLockCache(warehouseId); + + return await this._writeAuditLogAndResult({ + check, + checkId, + warehouseId, + actionValue, + reasonValue, + refreshedCount: 0, + }); + } + + /** + * 审核完成后写入操作日志并返回审核结果(审计分支共用)。 + * + * @param {Object} params 参数。 + * @param {Object} params.check 盘点主表模型实例。 + * @param {number} params.checkId 盘点任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {string} params.actionValue 审核动作:approve/reject。 + * @param {string} [params.reasonValue] 驳回原因。 + * @param {number} params.refreshedCount 刷新快照的明细行数(驳回为 0)。 + * @return {Promise} { id, status, snapshot_refreshed }。 + */ + async _writeAuditLogAndResult(params = {}) { + const { check, checkId, warehouseId, actionValue, reasonValue, refreshedCount } = params; + const { ctx } = this; + + const refreshedSuffix = actionValue === 'approve' && refreshedCount > 0 + ? `,刷新账面快照 ${refreshedCount} 行` + : ''; + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_AUDIT', + operationAction: 'UPDATE', + changeSummary: actionValue === 'approve' + ? `审核通过盘点任务 ${check.check_no}${refreshedSuffix}` + : `审核驳回盘点任务 ${check.check_no}${reasonValue ? `,原因:${reasonValue}` : ''}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + action: actionValue, + reason: actionValue === 'reject' ? reasonValue : '', + snapshotRefreshed: refreshedCount, + message: actionValue === 'approve' + ? `审核通过盘点任务 ${check.check_no}${refreshedSuffix}` + : `审核驳回盘点任务 ${check.check_no}${reasonValue ? `,原因:${reasonValue}` : ''}`, + }, + }); + + return { + id: checkId, + status: actionValue === 'approve' ? 'approved' : 'rejected', + snapshot_refreshed: refreshedCount, + }; + } + + /** + * 批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过)。 + * 入参 ids 归一化为去重后的正整数(单次上限 200); + * 按 id in ids + warehouse_id 查询主表做仓库隔离; + * 状态分流:status=cancelled 的任务级联删除,其他状态及查不到的任务计入 skipped_ids; + * 删除级联顺序(事务内):先删作业记录(StockCheckRecord where check_id in 删除集), + * 再删明细(StockCheckDetail where check_id in 删除集),最后删主表(StockCheck where id in 删除集)。 + * + * @param {Object} params 批量删除参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {Array|number} params.ids 盘点任务ID(数组或单个数值)。 + * @return {Promise} { total, deleted_count, skipped_count, deleted_ids, skipped_ids }; + * total=入参去重后数量,deleted_ids/skipped_ids 均保持入参顺序。 + * @throws {Error} 缺少仓库上下文、ids 为空或超过单次上限时抛出业务错误(错误码 400)。 + */ + async batchDelete(params = {}) { + const { warehouseId, ids } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + const numericIds = this._normalizeIdList(ids); + if (numericIds.length === 0) { + throw this.createBusinessError('ids 不能为空'); + } + if (numericIds.length > 200) { + throw this.createBusinessError('单次最多删除 200 个盘点任务'); + } + + // 仓库隔离查询主表:id in ids + warehouse_id + const checkRows = await ctx.model.StockCheck.findAll({ + where: { + id: { [Op.in]: numericIds }, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'status' ], + raw: true, + }); + const checkMap = new Map(checkRows.map(row => [ Number(row.id), row ])); + + // 状态分流:仅 cancelled 删除;其他状态及查不到的任务计入 skipped_ids(保持入参顺序) + const deletedIds = []; + const skippedIds = []; + for (const checkId of numericIds) { + const row = checkMap.get(checkId); + if (row && row.status === 'cancelled') { + deletedIds.push(checkId); + } else { + skippedIds.push(checkId); + } + } + + // 级联删除(事务):作业记录 → 明细 → 主表 + if (deletedIds.length > 0) { + await ctx.model.transaction(async transaction => { + await ctx.model.StockCheckRecord.destroy({ + where: { check_id: { [Op.in]: deletedIds } }, + transaction, + }); + await ctx.model.StockCheckDetail.destroy({ + where: { check_id: { [Op.in]: deletedIds } }, + transaction, + }); + await ctx.model.StockCheck.destroy({ + where: { id: { [Op.in]: deletedIds } }, + transaction, + }); + }); + await this.refreshStaticLockCache(normalizedWarehouseId); + } + + // 事务提交后写入操作日志(不随事务回滚残留,失败不影响主流程) + if (deletedIds.length > 0) { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: deletedIds[0], + operationCode: 'STOCK_CHECK_BATCH_DELETE', + operationAction: 'DELETE', + changeSummary: `批量删除盘点任务:删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: normalizedWarehouseId, + deletedIds, + skippedIds, + deletedCount: deletedIds.length, + skippedCount: skippedIds.length, + message: `批量删除盘点任务:删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`, + }, + }); + } + + return { + total: numericIds.length, + deleted_count: deletedIds.length, + skipped_count: skippedIds.length, + deleted_ids: deletedIds, + skipped_ids: skippedIds, + }; + } + + /** + * 盘点任务导出:查询任务与作业记录 → Sheet1「盘点单」一行一个盘点任务、 + * Sheet2「盘点明细」一行一条实际盘点记录(商品/库位/实盘数量/盘点人/时间, + * 不导出未盘的任务范围行)→ 流式生成 Excel → COS 上传。 + * 未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、商品名称列显示上报名称快照 + * (item_name);已知商品维持现有口径。通过 onProgress 回调实时推送进度。 + * + * @param {Object} params 导出参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {Array} params.ids 盘点任务ID数组。 + * @param {Function} [params.onProgress] 进度回调。 + * @return {Promise} 导出结果,包含文件下载信息与数量统计。 + * @throws {Error} 没有可导出的任务时抛出业务错误(错误码 400)。 + */ + async exportStockChecks(params = {}) { + const { warehouseId, ids, onProgress } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const reportProgress = async (status, progress, message, extra = {}) => { + if (typeof onProgress === 'function') { + await onProgress({ status, progress, message, ...extra }); + } + }; + + await reportProgress('running', 5, '正在准备导出数据...'); + + const numericIds = this._normalizeIdList(ids); + if (numericIds.length === 0) { + throw this.createBusinessError('请至少选择一个盘点任务'); + } + + const checks = await ctx.model.StockCheck.findAll({ + where: { + id: { [Op.in]: numericIds }, + warehouse_id: Number(warehouseId), + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (checks.length === 0) { + throw this.createBusinessError('未找到可导出的盘点任务'); + } + + // 盘点明细导出:直接拉作业记录(实际盘过的库位+数量),不按任务范围行展开(任务明细不导出) + const recordRows = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: { [Op.in]: numericIds } }, + order: [[ 'check_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + // 商品快照(item_code/item_name)从 wms_stock_warehouse 补齐(库位行的记录没有商品快照) + const stockIds = [ ...new Set(recordRows.map(row => Number(row.stock_id)).filter(id => Number.isInteger(id) && id > 0)) ]; + let stockMap = new Map(); + if (stockIds.length > 0) { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIds } }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }); + stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); + } + + const recordsGrouped = new Map(); + for (const row of recordRows) { + const recordStockId = Number(row.stock_id); + const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0; + const stock = stockMap.get(recordStockId) || {}; + const checkId = Number(row.check_id); + if (!recordsGrouped.has(checkId)) { + recordsGrouped.set(checkId, []); + } + recordsGrouped.get(checkId).push({ + ...row, + // 未知商品(stock_id 为空):商品编码列显示扫描条码、商品名称列显示上报名称快照; + // 已知商品维持现有口径(wms_stock_warehouse 商品快照) + item_code: isUnknownGoods ? (String(row.barcode || '').trim() || null) : (stock.item_code || null), + item_name: isUnknownGoods ? (String(row.item_name || row.barcode || '').trim() || null) : (stock.item_name || null), + }); + } + + const totalCount = recordRows.length; + await reportProgress('running', 10, `共 ${checks.length} 个盘点任务、${totalCount} 条盘点明细,开始导出...`, { + totalCount, + currentCount: 0, + }); + + const exportResult = await this._generateAndUploadStockCheckExcel(checks, recordsGrouped, { + totalCount, + onProgress, + }); + + await reportProgress('success', 100, '导出完成', { + totalCount, + currentCount: totalCount, + result: exportResult, + }); + + return { + ...exportResult, + total_count: totalCount, + current_count: totalCount, + }; + } + + /** + * 生成盘点导出 Excel(Sheet1=盘点单行,Sheet2=盘点明细(作业记录:库位+数量+盘点人+时间)) + * 并上传 COS,返回下载信息。 + * 与售后/退回拆包导出口径一致:流式写临时文件 → uploadFile → uploadSuccessNotify。 + * + * @param {Array} checks 盘点任务主表行。 + * @param {Map>} recordsGrouped 按 check_id 分组的作业记录行(含 item_code/item_name 快照)。 + * @param {Object} [options] 附加选项。 + * @param {number} [options.totalCount] 作业记录总行数(用于进度计算)。 + * @param {Function} [options.onProgress] 进度回调。 + * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl }。 + */ + async _generateAndUploadStockCheckExcel(checks = [], recordsGrouped = new Map(), options = {}) { + const { totalCount = 0, onProgress } = options; + const { ctx } = this; + + const reportProgress = async (status, progress, message, extra = {}) => { + if (typeof onProgress === 'function') { + await onProgress({ status, progress, message, ...extra }); + } + }; + + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-stock-check-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `库存盘点导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + try { + // ---- Sheet1:盘点单行(一行一个盘点任务) ---- + const checksSheet = workbook.addWorksheet('盘点单'); + checksSheet.addRow([ + '盘点单号', + '盘点名称', + '盘点范围', + '盘点方式', + '盘点状态', + '盘点进度', + '货主ID', + '创建人', + '明细行数', + '已盘行数', + '差异行数', + '开始时间', + '结束时间', + '备注', + ]).commit(); + + for (const check of checks) { + checksSheet.addRow([ + check.check_no || '', + check.title || '', + STOCK_CHECK_TYPE_LABELS[check.type] || check.type || '', + STOCK_CHECK_MODE_LABELS[check.mode] || check.mode || '', + STOCK_CHECK_STATUS_LABELS[check.status] || check.status || '', + STOCK_CHECK_DETAIL_PROGRESS_LABELS[check.detail_status] || check.detail_status || '', + check.store_id === null || check.store_id === undefined ? '' : Number(check.store_id), + check.creator_name || '', + Number(check.total_items) || 0, + Number(check.checked_items) || 0, + Number(check.diff_items) || 0, + this._formatLocalDateTime(check.start_time), + this._formatLocalDateTime(check.end_time), + check.remark || '', + ]).commit(); + } + checksSheet.commit(); + + // ---- Sheet2:盘点明细(作业记录:一行一条实际盘点记录,不含未盘的任务范围行) ---- + const detailsSheet = workbook.addWorksheet('盘点明细'); + detailsSheet.addRow([ + '盘点单号', + '商品编码', + '商品名称', + '库位编码', + '实盘数量', + '盘点人', + '盘点时间', + ]).commit(); + + let currentCount = 0; + for (const check of checks) { + const checkId = Number(check.id); + const rows = recordsGrouped.get(checkId) || []; + + for (const row of rows) { + detailsSheet.addRow([ + check.check_no || '', + row.is_empty ? '(空库位)' : (row.item_code || ''), + row.is_empty ? '' : (row.item_name || ''), + String(row.location_code || '').trim() !== '' ? row.location_code : '', + row.is_empty ? 0 : (Number(row.quantity) || 0), + row.checker_name || '', + this._formatLocalDateTime(row.checked_at), + ]).commit(); + + currentCount++; + // 每 200 行汇报一次进度 + if (currentCount % 200 === 0 || currentCount === totalCount) { + const progress = 10 + Math.floor((currentCount / Math.max(1, totalCount)) * 80); + await reportProgress('running', progress, `正在导出... (${currentCount}/${totalCount})`, { + totalCount, + currentCount, + }); + } + } + } + detailsSheet.commit(); + + await workbook.commit(); + + await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: totalCount }); + + // ---- 上传文件(与 afterSale/return_unpack 导出口径一致)---- + const uploadInfo = await this._uploadExportExcelFile(filePath, filename, { + businessType: 'stockCheckExport', + description: `库存盘点导出,共 ${checks.length} 个盘点任务、${totalCount} 条盘点明细`, + }); + + return uploadInfo; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + ctx.logger.error(`[stock.check.export] 生成/上传 Excel 失败: ${error.message}`); + throw error; + } finally { + await fsp.rm(tempDir, { recursive: true, force: true }); + } + } + + /** + * 上传导出的 Excel 文件(与 afterSale/return_unpack 导出口径一致): + * 流式上传 → uploadFile → uploadSuccessNotify 落库,返回下载信息。 + * + * @param {string} filePath 本地临时文件路径。 + * @param {string} filename 文件名。 + * @param {Object} [options] 附加选项。 + * @param {string} [options.businessType] 业务类型(默认 stockCheckExport)。 + * @param {string} [options.description] 文件描述。 + * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl }。 + */ + async _uploadExportExcelFile(filePath, filename, options = {}) { + const { ctx } = this; + const businessType = options.businessType || 'stockCheckExport'; + const description = options.description || ''; + + const uploadService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/stock_check/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType, + description, + }); + } + + // 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录,最后回退 COS key + const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {}; + const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null; + const fileUrlFromRecord = resolvedFileRecord + ? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '') + : ''; + const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || ''; + + return { + filename, + fileKey: safeUploadResult.fileName || uploadKey, + url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey, + cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '', + cosUrl: safeUploadResult.cosUrl || '', + }; + } + + /** + * 盘点明细导出(单任务,按盘点范围分流): + * - 商品范围(scope_type=goods)固定两个 sheet: + * Sheet1「汇总和差异」——每商品一行(盘点单号/商品编码/条码(wms_stock_barcodes 第一条)/ + * 商品名称/规格/账面数量(快照合计)/盘点数量/差异数量/差异类型(盘盈|盘亏,未盘留空); + * 未知商品(条码维度,无账面、差异=实盘=盘盈)追加在末尾; + * Sheet2「库位明细」——直接按作业记录(wms_stock_check_record)一行一条实际盘点记录 + * (库位编码/数量(实盘)/条码/商品名称;未知商品条码=扫描条码)。 + * - 库位范围(scope_type=location):Sheet「盘点明细」——库位编码/商品编码/商品名称/盘点数量 + * (作业记录口径,未知商品编码=扫描条码,空库位标记商品为空、数量 0)。 + * 流式生成 Excel → COS 上传;通过 onProgress 回调实时推送进度。 + * + * @param {Object} params 导出参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {Function} [params.onProgress] 进度回调。 + * @return {Promise} 导出结果,包含文件下载信息与 total_count。 + * @throws {Error} 任务不存在或参数非法时抛出业务错误(错误码 400)。 + */ + async exportCheckDetail(params = {}) { + const { warehouseId, id, onProgress } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const reportProgress = async (status, progress, message, extra = {}) => { + if (typeof onProgress === 'function') { + await onProgress({ status, progress, message, ...extra }); + } + }; + + await reportProgress('running', 5, '正在准备导出数据...'); + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const records = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const isLocationScope = detailRows.length > 0 + && detailRows.every(row => (row.scope_type || 'goods') === 'location'); + + // 商品范围:复用 result 的商品合并聚合(账面=快照、实盘=作业记录聚合) + let goodsRows = []; + if (!isLocationScope) { + goodsRows = (await this._buildDetailAggregations({ detailRows, recordRows: records })) + .filter(row => row.scope_type === 'goods'); + } + + // 库位范围商品快照(库位行的作业记录不带商品快照列) + const stockIds = [ ...new Set(records + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + let stockMap = new Map(); + if (stockIds.length > 0) { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIds } }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }); + stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); + } + + // 商品范围:商品条码(wms_stock_barcodes 按 stock_id 取第一条,库位明细 sheet 的条码列) + const barcodeMap = new Map(); + if (!isLocationScope) { + const goodsStockIds = [ ...new Set(goodsRows + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + if (goodsStockIds.length > 0) { + const barcodeRows = await ctx.model.StockBarcode.findAll({ + where: { + warehouse_id: Number(warehouseId), + stock_id: { [Op.in]: goodsStockIds }, + }, + attributes: [ 'stock_id', 'barcode' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const barcodeRow of barcodeRows) { + const barcodeStockId = Number(barcodeRow.stock_id); + if (!barcodeMap.has(barcodeStockId)) { + barcodeMap.set(barcodeStockId, String(barcodeRow.barcode || '').trim()); + } + } + } + } + + // 库位显示覆盖:自定义名称优先 → 自定义编码次之 → 最后才显示库位编码 + const locationDisplayMap = new Map(); + const recordLocationCodes = [ ...new Set(records + .map(record => String(record.location_code || '').trim()) + .filter(Boolean)) ]; + if (recordLocationCodes.length > 0) { + const spaceRows = await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: Number(warehouseId), + space_code: { [Op.in]: recordLocationCodes }, + }, + attributes: [ 'space_code', 'custom_name', 'custom_barcode' ], + raw: true, + }); + for (const spaceRow of spaceRows) { + const code = String(spaceRow.space_code || '').trim(); + if (!code) { + continue; + } + const candidate = { + custom_name: String(spaceRow.custom_name || '').trim(), + custom_barcode: String(spaceRow.custom_barcode || '').trim(), + }; + // 同仓库同编码可能有多条库位(历史重复/无头库位):优先保留有自定义名称的行, + // 避免空值行后写覆盖,导致导出回退成库位编码 + const existing = locationDisplayMap.get(code); + const shouldReplace = !existing + || (!existing.custom_name && candidate.custom_name) + || (!existing.custom_name && !candidate.custom_name && candidate.custom_barcode); + if (shouldReplace) { + locationDisplayMap.set(code, candidate); + } + } + } + + const totalCount = isLocationScope + ? records.length + : goodsRows.reduce( + (sum, row) => sum + 1 + (Array.isArray(row.unknown_items) ? row.unknown_items.length : 0), + 0 + ) + records.length; + + await reportProgress('running', 10, `正在导出盘点明细(共 ${totalCount} 行)...`, { + totalCount, + currentCount: 0, + }); + + const exportResult = await this._generateAndUploadCheckDetailExcel({ + check: check.get({ plain: true }), + isLocationScope, + goodsRows, + records, + stockMap, + barcodeMap, + locationDisplayMap, + totalCount, + onProgress, + }); + + await reportProgress('success', 100, '导出完成', { + totalCount, + currentCount: totalCount, + result: exportResult, + }); + + return { + ...exportResult, + total_count: totalCount, + current_count: totalCount, + }; + } + + /** + * 库位编码显示覆盖:自定义名称优先 → 自定义编码(custom_barcode)次之 → 库位编码(space_code)兜底; + * 库位编码为空或无匹配库位时返回空/库位编码。 + * + * @param {string} locationCode 作业记录库位编码。 + * @param {Map} locationDisplayMap 库位编码 → { custom_name, custom_barcode } 映射。 + * @return {string} 显示用的库位文本。 + */ + _resolveLocationDisplayCode(locationCode, locationDisplayMap = new Map()) { + const code = String(locationCode || '').trim(); + if (!code) { + return ''; + } + const space = locationDisplayMap.get(code); + if (!space) { + return code; + } + return space.custom_name || space.custom_barcode || code; + } + + /** + * 生成盘点明细导出 Excel 并上传 COS(Sheet 结构随盘点范围变化,见 exportCheckDetail)。 + * + * @param {Object} params 生成参数。 + * @param {Object} params.check 盘点主表行。 + * @param {boolean} params.isLocationScope 是否库位范围盘点。 + * @param {Array} params.goodsRows 商品范围聚合行(result 口径)。 + * @param {Array} params.records 作业记录原始行。 + * @param {Map} params.stockMap 商品快照映射(库位范围用)。 + * @param {Map} params.barcodeMap 商品条码映射(商品范围库位明细 sheet 用)。 + * @param {Map} params.locationDisplayMap 库位显示覆盖映射(库位编码 → { custom_name, custom_barcode })。 + * @param {number} params.totalCount 总行数(进度计算用)。 + * @param {Function} [params.onProgress] 进度回调。 + * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl }。 + */ + async _generateAndUploadCheckDetailExcel(params = {}) { + const { + check, + isLocationScope, + goodsRows = [], + records = [], + stockMap = new Map(), + barcodeMap = new Map(), + locationDisplayMap = new Map(), + totalCount = 0, + onProgress, + } = params; + const { ctx } = this; + + const reportProgress = async (status, progress, message, extra = {}) => { + if (typeof onProgress === 'function') { + await onProgress({ status, progress, message, ...extra }); + } + }; + + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-stock-check-detail-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `盘点明细导出_${check.check_no || check.id}_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + try { + const checkNo = String(check.check_no || ''); + let currentCount = 0; + const reportRowProgress = async () => { + currentCount++; + if (currentCount % 200 === 0 || currentCount === totalCount) { + const progress = 10 + Math.floor((currentCount / Math.max(1, totalCount)) * 80); + await reportProgress('running', progress, `正在导出... (${currentCount}/${totalCount})`, { + totalCount, + currentCount, + }); + } + }; + + if (isLocationScope) { + // ---- 库位范围:库位 / 商品 / 盘点数量 ---- + const sheet = workbook.addWorksheet('盘点明细'); + sheet.addRow([ '库位编码', '商品编码', '商品名称', '盘点数量' ]).commit(); + for (const record of records) { + const recordStockId = Number(record.stock_id); + const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0; + const stock = stockMap.get(recordStockId) || {}; + sheet.addRow([ + this._resolveLocationDisplayCode(record.location_code, locationDisplayMap), + record.is_empty ? '' : (isUnknownGoods ? String(record.barcode || '').trim() : (stock.item_code || '')), + record.is_empty ? '' : (isUnknownGoods ? String(record.item_name || record.barcode || '').trim() : (stock.item_name || '')), + record.is_empty ? 0 : (Number(record.quantity) || 0), + ]).commit(); + await reportRowProgress(); + } + sheet.commit(); + } else { + // ---- 商品范围:汇总和差异 + 库位明细 两个 sheet ---- + const summarySheet = workbook.addWorksheet('汇总和差异'); + summarySheet.addRow([ + '盘点单号', + '商品编码', + '条码', + '商品名称', + '规格', + '账面数量', + '盘点数量', + '差异数量', + '差异类型', + ]).commit(); + const locationSheet = workbook.addWorksheet('库位明细'); + locationSheet.addRow([ '库位编码', '数量', '条码', '商品名称' ]).commit(); + + for (const row of goodsRows) { + const hasRecords = Array.isArray(row.records) && row.records.length > 0; + const diffQuantity = hasRecords ? (Number(row.diff_quantity) || 0) : 0; + summarySheet.addRow([ + checkNo, + row.item_code || '', + barcodeMap.get(Number(row.stock_id)) || '', + row.item_name || '', + row.spec || '', + Number(row.system_quantity) || 0, + hasRecords ? (Number(row.checked_quantity) || 0) : '', + hasRecords ? diffQuantity : '', + !hasRecords ? '' : (diffQuantity > 0 ? '盘盈' : (diffQuantity < 0 ? '盘亏' : '')), + ]).commit(); + await reportRowProgress(); + + // 未知商品(条码维度,无账面,差异=实盘=盘盈;商品编码列即扫描条码,条码列留空避免重复) + for (const unknownItem of (Array.isArray(row.unknown_items) ? row.unknown_items : [])) { + const checkedQuantity = Number(unknownItem.checked_quantity) || 0; + summarySheet.addRow([ + checkNo, + unknownItem.barcode || '', + '', + unknownItem.item_name || '', + '', + 0, + checkedQuantity, + checkedQuantity, + '盘盈', + ]).commit(); + await reportRowProgress(); + } + } + + // 库位明细:直接按作业记录(wms_stock_check_record)一行一条实际盘点记录 + const itemNameByStock = new Map(goodsRows + .filter(row => row.stock_id) + .map(row => [ Number(row.stock_id), row.item_name || '' ])); + for (const record of records) { + const recordStockId = Number(record.stock_id); + const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0; + locationSheet.addRow([ + this._resolveLocationDisplayCode(record.location_code, locationDisplayMap), + record.is_empty ? 0 : (Number(record.quantity) || 0), + record.is_empty ? '' : (isUnknownGoods ? String(record.barcode || '').trim() : (barcodeMap.get(recordStockId) || '')), + record.is_empty ? '' : (isUnknownGoods ? String(record.item_name || record.barcode || '').trim() : (itemNameByStock.get(recordStockId) || '')), + ]).commit(); + await reportRowProgress(); + } + + summarySheet.commit(); + locationSheet.commit(); + } + + await workbook.commit(); + + await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: totalCount }); + + const uploadInfo = await this._uploadExportExcelFile(filePath, filename, { + businessType: 'stockCheckDetailExport', + description: `盘点明细导出 ${check.check_no || check.id},共 ${totalCount} 行`, + }); + + return uploadInfo; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + ctx.logger.error(`[stock.check.exportDetail] 生成/上传 Excel 失败: ${error.message}`); + throw error; + } finally { + await fsp.rm(tempDir, { recursive: true, force: true }); + } + } +} + +module.exports = StockCheckService; diff --git a/app/service/systems/stock_check_patterns.js b/app/service/systems/stock_check_patterns.js new file mode 100644 index 0000000..2e03ecf --- /dev/null +++ b/app/service/systems/stock_check_patterns.js @@ -0,0 +1,449 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 静态盘点:仓库未配置 stock_static_hours 时使用的默认阈值小时数 */ +const DEFAULT_STATIC_HOURS = 168; + +/** + * 盘点定式定义集合(代码注册,不建表)。 + * 字段说明: + * - id:定式唯一标识(method 层 pattern_id 入参); + * - name:定式名称(创建任务时作为默认标题); + * - description:定式描述(含对象收集口径); + * - type:对应盘点任务 type(location=按库位 / goods=按商品); + * - collect:对象收集函数名(本服务内实现,入参 { warehouseId }, + * 返回 { locations: [{location_id, location_code}] } 或 { stock_ids: [...] })。 + */ +const STOCK_CHECK_PATTERNS = Object.freeze([ + Object.freeze({ + id: 'empty_location', + name: '空库位盘点', + description: '自动收集当前仓库所有「账面为空」的启用库位:wms_location_space(warehouse_id 匹配且 is_enabled=1)中,在 wms_storage 不存在任何 quantity>0 库存记录的库位(LEFT JOIN 判空)', + type: 'location', + collect: 'collectEmptyLocation', + }), + Object.freeze({ + id: 'mis_shipment', + name: '错发盘点', + description: '自动收集所有登记过错发工单(wms_after_sale.type=order 且 sub_type=mis_shipment)关联订单的商品:工单状态口径为「凡登记过即纳入,排除已关闭(closed)/已取消(cancelled)工单」,取工单 order_id 集合查询订单明细分表(OrderItemsFactory.getCurrentModel)后按 stock_id 去重', + type: 'goods', + collect: 'collectMisShipment', + }), + Object.freeze({ + id: 'expiring', + name: '临期盘点', + description: '自动收集所有开启保质期管理(wms_stock_warehouse.is_shelf_life_mgmt=Y)且存在临期库存的商品:在 wms_storage 存在 quantity>0 且 expiry_date 非空、expiry_date <= 当前时间+该商品 remaining_threshold_days 天的库存记录(商品维度去重;remaining_threshold_days 为 0 时按已到期 expiry_date <= 当前时间处理)', + type: 'goods', + collect: 'collectExpiring', + }), + Object.freeze({ + id: 'static', + name: '静态盘点', + description: '自动收集所有停收停发超过时间的商品:商品最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction)距今超过仓库配置 stock_static_hours 小时(默认 168 小时),无流水的商品按 wms_stock_warehouse.create_at 计算;已存在 wms_stock_static_check_task 记录的 stock_id(已进入静态已盘点商品)自动排除,创建任务成功后把命中的 stock_id 写入该表', + type: 'goods', + collect: 'collectStatic', + }), + Object.freeze({ + id: 'warning', + name: '预警盘点', + description: '自动收集所有到达库存预警线的商品:wms_stock_warehouse.quantity < 仓库配置 stock_warning_quantity(商品维度去重);要求仓库配置 stock_warning_enabled=true 才可执行,未开启时返回 400「未开启库存预警」', + type: 'goods', + collect: 'collectWarning', + }), +]); + +/** + * 盘点定式注册服务(供 systems.stockCheck 转调)。 + * 职责:维护定式清单、提供定式对象收集函数,不直接落库盘点主表。 + */ +class StockCheckPatternsService extends Service { + /** + * 创建带业务错误码的异常对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 判断是否为普通对象(非数组、非 null)。 + * + * @param {*} value 待判断值。 + * @return {boolean} 是普通对象返回 true。 + */ + _isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); + } + + /** + * 归一化 subject_config(兼容 JSON 字符串与对象)。 + * + * @param {*} raw 原始配置值。 + * @return {Object} 配置对象,非法时返回空对象。 + */ + _normalizeSubjectConfig(raw) { + if (this._isPlainObject(raw)) { + return raw; + } + if (typeof raw === 'string') { + const trimmed = raw.trim(); + if (!trimmed) { + return {}; + } + try { + const parsed = JSON.parse(trimmed); + return this._isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } + } + return {}; + } + + /** + * 判断布尔标志是否开启(兼容 true / 1 / '1' / 'true')。 + * + * @param {*} value 标志值。 + * @return {boolean} 开启返回 true。 + */ + _isTruthyFlag(value) { + return value === true + || value === 1 + || value === '1' + || String(value || '').trim().toLowerCase() === 'true'; + } + + /** + * 读取当前仓库设置(wms_store.subject_config)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} subject_config 对象,读取失败返回空对象。 + */ + async _getWarehouseSubjectConfig(warehouseId) { + const { ctx } = this; + try { + const storeModel = ctx.model && ctx.model.Store; + if (!storeModel || typeof storeModel.findByPk !== 'function') { + return {}; + } + const store = await storeModel.findByPk(Number(warehouseId), { + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + return this._normalizeSubjectConfig(store && store.subject_config); + } catch (error) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockCheckPatterns] 读取仓库设置失败 warehouseId=${warehouseId}: ${error && error.message}` + ); + return {}; + } + } + + /** + * 读取静态盘点阈值小时数(仓库配置 stock_static_hours,默认 168)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 阈值小时数。 + */ + async _resolveStaticHours(warehouseId) { + const subjectConfig = await this._getWarehouseSubjectConfig(warehouseId); + const configHours = Number(subjectConfig.stock_static_hours || 0); + return Number.isFinite(configHours) && configHours > 0 ? configHours : DEFAULT_STATIC_HOURS; + } + + /** + * 执行裸 SQL 查询并返回行数组。 + * + * @param {string} sql 查询语句(命名占位符 :name)。 + * @param {Object} [replacements={}] 占位符替换值。 + * @return {Promise>} 查询结果行数组。 + */ + async _queryRows(sql, replacements = {}) { + const { ctx } = this; + const rows = await ctx.model.query(sql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + return Array.isArray(rows) ? rows : []; + } + + /** + * 将 ID 列表归一化为去重后的正整数列表。 + * + * @param {Array<*>} values 原始 ID 列表。 + * @return {Array} 去重后的正整数列表。 + */ + _normalizePositiveIntegerList(values) { + const list = Array.isArray(values) ? values : []; + return [ ...new Set( + list + .map(value => Number(value)) + .filter(value => Number.isInteger(value) && value > 0) + ) ]; + } + + /** + * 拉取定式清单(仅对外字段,不含内部执行函数)。 + * + * @return {Array} 定式数组,每项含 id/name/description/type。 + */ + listPatterns() { + return STOCK_CHECK_PATTERNS.map(pattern => ({ + id: pattern.id, + name: pattern.name, + description: pattern.description, + type: pattern.type, + })); + } + + /** + * 按定式 ID 查询定式定义。 + * + * @param {string|number} patternId 定式ID。 + * @return {Object|null} 定式定义,不存在返回 null。 + */ + getPatternById(patternId) { + const normalized = String(patternId || '').trim(); + return STOCK_CHECK_PATTERNS.find(pattern => pattern.id === normalized) || null; + } + + /** + * 按定式 ID 收集盘点对象(goods 型返回 stock_ids,location 型返回库位列表)。 + * + * @param {string|number} patternId 定式ID。 + * @param {Object} [context={}] 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids } 或 { locations },定式不存在返回 null。 + */ + async collectById(patternId, context = {}) { + const pattern = this.getPatternById(patternId); + if (!pattern || typeof this[pattern.collect] !== 'function') { + return null; + } + return this[pattern.collect](context); + } + + /** + * 空库位定式:收集账面为空的启用库位。 + * 口径:wms_location_space(warehouse_id 匹配、is_enabled=1、未删除、库位有效—— + * 所属 zone 存在且未删除,排除无头库位)在 + * wms_storage 不存在任何 quantity>0 且未删除的库存记录(LEFT JOIN 判空)。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { locations: [{ location_id, location_code }] }。 + */ + async collectEmptyLocation(context = {}) { + const warehouseId = Number(context.warehouseId); + const rows = await this._queryRows( + ` + SELECT ls.id AS location_id, ls.space_code AS location_code + FROM wms_location_space ls + JOIN wms_location_zone z + ON z.id = ls.zone_id + AND z.deleted_at IS NULL + LEFT JOIN wms_storage st + ON st.space_id = ls.id + AND st.delete_at IS NULL + AND st.quantity > 0 + WHERE ls.warehouse_id = :warehouseId + AND ls.is_enabled = 1 + AND ls.deleted_at IS NULL + AND st.id IS NULL + ORDER BY ls.id ASC + `, + { warehouseId } + ); + const locations = rows + .filter(row => row && row.location_id) + .map(row => ({ + location_id: Number(row.location_id), + location_code: String(row.location_code || '').trim(), + })); + return { locations }; + } + + /** + * 错发定式:收集登记过错发工单的订单关联商品。 + * 口径:wms_after_sale(warehouse_id 匹配、type=order、sub_type=mis_shipment、未删除) + * 中排除已关闭(closed)/已取消(cancelled)工单,其余状态一律纳入; + * 取 order_id 集合查询订单明细分表(OrderItemsFactory.getCurrentModel)后按 stock_id 去重。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids: number[] }。 + */ + async collectMisShipment(context = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = Number(context.warehouseId); + + const afterSaleRows = await ctx.model.AfterSale.findAll({ + where: { + warehouse_id: warehouseId, + type: 'order', + sub_type: 'mis_shipment', + status: { [Op.notIn]: [ 'closed', 'cancelled' ] }, + deleted_at: null, + }, + attributes: [ 'order_id' ], + raw: true, + }); + const orderIds = this._normalizePositiveIntegerList( + (Array.isArray(afterSaleRows) ? afterSaleRows : []).map(row => row && row.order_id) + ); + if (orderIds.length === 0) { + return { stock_ids: [] }; + } + + const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const itemRows = await orderItemsModel.findAll({ + where: { order_id: { [Op.in]: orderIds } }, + attributes: [ 'stock_id' ], + raw: true, + }); + const stockIds = this._normalizePositiveIntegerList( + (Array.isArray(itemRows) ? itemRows : []).map(row => row && row.stock_id) + ); + return { stock_ids: stockIds }; + } + + /** + * 临期定式:收集开启保质期管理且存在临期库存的商品。 + * 口径:wms_stock_warehouse(warehouse_id 匹配、is_valid=Y、未删除、is_shelf_life_mgmt=Y) + * 关联 wms_storage(quantity>0、expiry_date 非空、未删除)按 stock_id 取最早到期日: + * remaining_threshold_days>0 时最早到期日 <= 当前时间+阈值天数, + * remaining_threshold_days<=0(含空)时按已到期处理(最早到期日 <= 当前时间),商品维度去重。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids: number[] }。 + */ + async collectExpiring(context = {}) { + const warehouseId = Number(context.warehouseId); + const rows = await this._queryRows( + ` + SELECT sw.id AS stock_id + FROM wms_stock_warehouse sw + INNER JOIN ( + SELECT stock_id, MIN(expiry_date) AS min_expiry_date + FROM wms_storage + WHERE warehouse_id = :warehouseId + AND quantity > 0 + AND expiry_date IS NOT NULL + AND delete_at IS NULL + GROUP BY stock_id + ) st ON st.stock_id = sw.id + WHERE sw.warehouse_id = :warehouseId + AND sw.is_valid = 'Y' + AND sw.deleted_at IS NULL + AND sw.is_shelf_life_mgmt = 'Y' + AND ( + (COALESCE(sw.remaining_threshold_days, 0) > 0 + AND st.min_expiry_date <= DATE_ADD(NOW(), INTERVAL COALESCE(sw.remaining_threshold_days, 0) DAY)) + OR + (COALESCE(sw.remaining_threshold_days, 0) <= 0 + AND st.min_expiry_date <= NOW()) + ) + ORDER BY sw.id ASC + `, + { warehouseId } + ); + return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) }; + } + + /** + * 静态定式:收集停收停发超过阈值的商品。 + * 口径:商品最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction,命中 + * warehouse_id+transaction_type+stock_id 索引)距今超过仓库配置 + * stock_static_hours 小时(默认 168 小时),无流水的商品按 + * wms_stock_warehouse.create_at 计算;排除 wms_stock_static_check_task + * 已有记录(未删除)的 stock_id,商品维度去重。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids: number[] }。 + */ + async collectStatic(context = {}) { + const warehouseId = Number(context.warehouseId); + const staticHours = await this._resolveStaticHours(warehouseId); + const cutoff = new Date(Date.now() - staticHours * 3600 * 1000); + const rows = await this._queryRows( + ` + SELECT sw.id AS stock_id + FROM wms_stock_warehouse sw + LEFT JOIN ( + SELECT stock_id, MAX(last_flow_at) AS last_flow_at + FROM ( + SELECT stock_id, MAX(created_at) AS last_flow_at + FROM wms_stock_transaction + WHERE warehouse_id = :warehouseId + AND transaction_type = 'INBOUND' + GROUP BY stock_id + UNION ALL + SELECT stock_id, MAX(created_at) AS last_flow_at + FROM wms_stock_transaction + WHERE warehouse_id = :warehouseId + AND transaction_type = 'OUTBOUND' + GROUP BY stock_id + ) flow_union + GROUP BY stock_id + ) t ON t.stock_id = sw.id + WHERE sw.warehouse_id = :warehouseId + AND sw.is_valid = 'Y' + AND sw.deleted_at IS NULL + AND COALESCE(t.last_flow_at, sw.create_at) < :cutoff + AND NOT EXISTS ( + SELECT 1 + FROM wms_stock_static_check_task sct + WHERE sct.stock_id = sw.id + AND sct.deleted_at IS NULL + ) + ORDER BY sw.id ASC + `, + { warehouseId, cutoff } + ); + return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) }; + } + + /** + * 预警定式:收集到达库存预警线的商品。 + * 口径:仓库配置 stock_warning_enabled=true 时才可执行(未开启抛 400「未开启库存预警」), + * 收集 wms_stock_warehouse(warehouse_id 匹配、is_valid=Y、未删除)中 + * quantity < stock_warning_quantity 的商品,商品维度去重。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids: number[] }。 + * @throws {Error} 未开启库存预警时抛出业务错误(错误码 400)。 + */ + async collectWarning(context = {}) { + const warehouseId = Number(context.warehouseId); + const subjectConfig = await this._getWarehouseSubjectConfig(warehouseId); + if (!this._isTruthyFlag(subjectConfig.stock_warning_enabled)) { + throw this.createBusinessError('未开启库存预警'); + } + const threshold = Number(subjectConfig.stock_warning_quantity || 0); + const rows = await this._queryRows( + ` + SELECT id AS stock_id + FROM wms_stock_warehouse + WHERE warehouse_id = :warehouseId + AND is_valid = 'Y' + AND deleted_at IS NULL + AND quantity < :threshold + ORDER BY id ASC + `, + { warehouseId, threshold } + ); + return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) }; + } +} + +module.exports = StockCheckPatternsService; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index ecb0e04..09c2880 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1,14 +1,17 @@ 'use strict'; const Service = require('egg').Service; +const { + parseWhereConditions, + buildSequelizeCondition: buildSequelizeConditionUtil, + processConditionValue: processConditionValueUtil, + isEmptyValue: isEmptyValueUtil, + normalizeDate: normalizeDateUtil, +} = require('../../lib/query_condition_parser'); class stockStoreService extends Service { - constructor(ctx) { - super(ctx); - } async create(stockData) { const { app, - ctx, service, } = this; const warehouseId = stockData.warehouse_id; @@ -132,6 +135,7 @@ class stockStoreService extends Service { return result; } async convertToQimenFormat(stockData) { + const { app } = this; const result = { // 商品信息 item: { @@ -147,8 +151,8 @@ class stockStoreService extends Service { width: parseFloat(stockData.width) || 0, height: parseFloat(stockData.height) || 0, volume: parseFloat(stockData.volume) || 0, - grossWeight: parseFloat(stockData.gross_weight) || 0, - netWeight: parseFloat(stockData.net_weight) || 0, + grossWeight: parseFloat(stockData.gross_weight) || 0, // 单位 g,Qimen 接口输出 + netWeight: parseFloat(stockData.net_weight) || 0, // 单位 g,Qimen 接口输出 // 分类信息 categoryId: stockData.category_id || 0, @@ -168,22 +172,20 @@ class stockStoreService extends Service { // 其他信息 barCode: stockData.barcode || '', isValid: stockData.is_valid === 'Y' ? 'Y' : 'N', - createTime: stockData.create_time ? new Date(stockData.create_time).format() : '', + createTime: stockData.create_time ? app.formatDate(stockData.create_time) : '', }, }; return result; } async getItemInfoWithCache(itemId) { const { - ctx, - app, - } = this; // 使用 ctx.model 而非 app.model + app, ctx, + } = this; const cacheKey = `item:info:${itemId}`; try { // 1. 尝试从缓存获取 const cached = await app.getCacheAsync(cacheKey); - console.log('缓存》》》》', cached); if (cached !== null && cached !== undefined) { app.logger.debug('[ItemCacheHit]', itemId); @@ -197,11 +199,10 @@ class stockStoreService extends Service { // 2. 缓存未命中,查询数据库 app.logger.debug('[ItemCacheMiss]', itemId); - console.log('缓存》》》》', itemId); // ⭐ 关键修复:使用 raw: true 获取纯对象 const itemInfo = await ctx.model.StockStore.findByPk(itemId, { - attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ], // 按需增加字段 + attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code', 'item_name' ], // 按需增加字段 raw: true, // ⭐ 必须:转换为纯 JavaScript 对象 }); @@ -219,7 +220,6 @@ class stockStoreService extends Service { await app.setCacheAsync(cacheKey, nullMarker, 120); return null; // 明确返回 null - } catch (error) { app.logger.error('[getItemInfoWithCache] 查询失败', { itemId, @@ -246,10 +246,18 @@ class stockStoreService extends Service { // 数据库也失败,向上抛出 throw new Error(`查询商品信息失败: ${dbError.message}`); } - throw error; } } - async getItemStorages(itemId, transaction) { + /** + * 查询商品对应的库存记录与可用量。 + * + * @param {number|string} itemId 商品 ID(StockStore.id)。 + * @param {Object|null} transaction 数据库事务。 + * @param {Object} [opts] 可选配置。 + * @param {number} [opts.stockId] 当传入有效的 stockId 时,跳过 StockStore 映射层,直接使用该 stockId 查询 StockWarehouse。 + * @return {Promise} 库存查询结果。 + */ + async getItemStorages(itemId, transaction, opts = {}) { const { ctx, app, @@ -257,6 +265,72 @@ class stockStoreService extends Service { const cacheKey = `storages:${itemId}`; try { + const { stockId } = opts; + + // stockId 快速路径:跳过 StockStore 映射,直接用 stockId 查 StockWarehouse + if (Number.isFinite(stockId) && stockId > 0) { + const stockWarehouse = await ctx.model.StockWarehouse.findOne({ + where: { + id: stockId, + is_valid: 'Y', + deleted_at: null, + }, + attributes: [ + 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight', + ], + transaction, + lock: transaction?.LOCK?.UPDATE, + raw: true, + }); + + if (stockWarehouse) { + const quantity = parseInt(stockWarehouse.quantity) || 0; + const lockedQuantity = parseInt(stockWarehouse.locked_quantity) || 0; + const canUse = quantity - lockedQuantity; + const grossWeight = parseInt(stockWarehouse.gross_weight) || 0; + + const storage = { + id: stockWarehouse.id, + storeId: Number(stockWarehouse.store_id) || 0, + warehouseId: Number(stockWarehouse.warehouse_id) || 0, + quantity, + lockedQuantity, + canUse, + grossWeight, + _updatedAt: Date.now(), + exists: true, + }; + + // 异步更新缓存 + const cached = await app.getCacheAsync(cacheKey); + if (!cached) { + const ttl = this._calculateCacheTTL(storage); + app.setCacheAsync(cacheKey, storage, ttl); + } + + return { + success: true, + data: { + stock: { + id: itemId, + stock_id: stockId, + store_id: storage.storeId, + warehouse_id: storage.warehouseId, + }, + storage, + }, + }; + } + + // stockWarehouse 不存在 + app.logger.warn(`[库存记录缺失-stockId快速路径] itemId=${itemId}, stockId=${stockId}`); + return { + success: false, + error: '已更改未同步推送到仓库', + data: null, + }; + } + // 1. 获取商品信息 const itemInfo = await this.getItemInfoWithCache(itemId); @@ -286,14 +360,17 @@ class stockStoreService extends Service { if (cached) { storage = cached; fromCache = true; - if (storage && storage.canUse === 0) { - app.logger.debug(`[缓存快速失败] 商品 ${itemId} 可用库存为0`); - return { - success: false, - error: '库存不足', - data: null, - _fromCache: true, - }; + if (storage && storage.canUse <= 0) { + const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(itemInfo.stock_id, transaction); + if (!policyConfig.allowOversell) { + app.logger.debug(`[缓存快速失败] 商品 ${itemId} 可用库存为0`); + return { + success: false, + error: '库存不足', + data: null, + _fromCache: true, + }; + } } } @@ -306,7 +383,7 @@ class stockStoreService extends Service { deleted_at: null, }, attributes: [ - 'id', 'quantity', 'locked_quantity', 'gross_weight', + 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight', ], transaction, lock: transaction?.LOCK?.UPDATE, @@ -316,11 +393,13 @@ class stockStoreService extends Service { if (stockWarehouse) { const quantity = parseInt(stockWarehouse.quantity) || 0; const lockedQuantity = parseInt(stockWarehouse.locked_quantity) || 0; - const canUse = Math.max(0, quantity - lockedQuantity); + const canUse = quantity - lockedQuantity; const grossWeight = parseInt(stockWarehouse.gross_weight) || 0; storage = { id: stockWarehouse.id, + storeId: Number(stockWarehouse.store_id) || 0, + warehouseId: Number(stockWarehouse.warehouse_id) || 0, quantity, lockedQuantity, canUse, @@ -355,10 +434,15 @@ class stockStoreService extends Service { stock: { id: itemInfo.id, stock_id: itemInfo.stock_id, + store_id: storage && storage.storeId ? storage.storeId : undefined, + warehouse_id: storage && storage.warehouseId ? storage.warehouseId : undefined, warehouse_code: itemInfo.warehouse_code, item_code: itemInfo.item_code, }, storage, + allow_oversell: storage && storage.canUse <= 0 + ? (await this.getStoreWarehousePolicyConfigByStockId(itemInfo.stock_id, transaction)).allowOversell + : undefined, }, error: null, _fromCache: fromCache, @@ -380,14 +464,14 @@ class stockStoreService extends Service { /** * 计算缓存时间 - * @param storage + * @param {Object} storage - 库存对象 */ _calculateCacheTTL(storage) { if (!storage || !storage._exists || !storage._isValid) { return 5; // 无效库存缓存5秒 } - if (storage.canUse === 0) { + if (storage.canUse <= 0) { return 10; // 无库存缓存10秒 } @@ -400,185 +484,361 @@ class stockStoreService extends Service { /** * 清理缓存 - * @param itemId + * @param {number|string} itemId - 商品ID */ async clearItemStorageCache(itemId) { const { app, } = this; const cacheKey = `storages:${itemId}`; - try { - await app.delCacheAsync(cacheKey); - app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`); - } catch (error) { - app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message); + if (app && typeof app.delCacheAsync === 'function') { + try { + await app.delCacheAsync(cacheKey); + app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`); + } catch (error) { + app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message); + } + return; + } + + if (app && typeof app.setCacheAsync === 'function') { + try { + await app.setCacheAsync(cacheKey, null, 0); + app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`); + } catch (error) { + app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message); + } } } - async lockItemStorages(stockWarehouseId, quantity, transaction) { - const { - ctx, - app, - } = this; - // 输入验证 - const lockQty = parseInt(quantity); - if (!stockWarehouseId || isNaN(lockQty) || lockQty === 0) { - return { - success: false, - error: `参数错误:库存ID无效或数量为0 (ID: ${stockWarehouseId}, Qty: ${quantity})`, - data: null, - }; + /** + * 在给定事务中执行库存写操作,未传入事务时自动创建并提交回滚。 + * + * @param {Object} externalTransaction 外部传入的数据库事务 + * @param {Function} handler 业务处理函数 + * @return {Promise<*>} 业务处理结果 + */ + async _runWithTransaction(externalTransaction, handler) { + const { ctx } = this; + + if (externalTransaction) { + return handler(externalTransaction, true); } - const isLocking = lockQty > 0; // true=加锁,false=减锁 - const absQty = Math.abs(lockQty); - + const internalTransaction = await ctx.model.transaction(); try { - // 1. 查询并锁定记录(悲观锁) - const stockRecord = await ctx.model.StockWarehouse.findOne({ + const result = await handler(internalTransaction, false); + await internalTransaction.commit(); + return result; + } catch (error) { + await internalTransaction.rollback(); + throw error; + } + } + + /** + * 按货主和仓库获取签约策略配置(带缓存,用于锁外预取)。 + * + * @param {number} storeId 货主ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} { allowOversell: boolean, relation: Object|null } + */ + async getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId) { + const { ctx, app } = this; + const normalizedStoreId = Number(storeId || 0); + const normalizedWarehouseId = Number(warehouseId || 0); + + if (normalizedStoreId <= 0 || normalizedWarehouseId <= 0) { + return { allowOversell: false, relation: null }; + } + + const cacheKey = `sw_policy:${normalizedStoreId}:${normalizedWarehouseId}`; + + // 1. 先查缓存 + const cached = await app.getCacheAsync(cacheKey); + if (cached) { + return cached; + } + + // 2. 缓存未命中,查 DB(无事务) + const relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: normalizedStoreId, + warehouse_id: normalizedWarehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + attributes: [ 'id', 'policy_config', 'auth_status', 'warehouse_use_status', 'store_use_status' ], + raw: true, + }); + + if (!relation) { + const fallback = { allowOversell: false, relation: null }; + await app.setCacheAsync(cacheKey, fallback, 300); + return fallback; + } + + const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; + const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function' + ? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id) + : null; + + const result = { + allowOversell: Number(policyConfig && policyConfig.allow_oversell) === 1, + relation, + }; + + await app.setCacheAsync(cacheKey, result, 300); + return result; + } + + /** + * 获取库存对应的货主-仓库签约策略配置。 + * + * @param {number|Object} stockWarehouseId 库存 ID 或库存记录。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise} 策略配置对象,包含 relation、policyConfig、allowOversell。 + */ + async getStoreWarehousePolicyConfigByStockId(stockWarehouseId, transaction = null) { + const { ctx } = this; + const stockRecord = stockWarehouseId && typeof stockWarehouseId === 'object' + ? stockWarehouseId + : await ctx.model.StockWarehouse.findOne({ where: { - id: stockWarehouseId, + id: Number(stockWarehouseId || 0), is_valid: 'Y', deleted_at: null, }, + attributes: [ 'id', 'store_id', 'warehouse_id' ], transaction, - lock: transaction.LOCK.UPDATE, // 行级锁 - raw: false, // 需要实例以使用方法 + raw: true, }); - // 检查记录是否存在 - if (!stockRecord) { - return { - success: false, - error: `库存记录不存在或已失效 (ID: ${stockWarehouseId})`, - data: null, - }; - } + const storeId = Number(stockRecord && stockRecord.store_id) || 0; + const warehouseId = Number(stockRecord && stockRecord.warehouse_id) || 0; - // 2. 业务规则校验 - if (isLocking) { - // 加锁操作:检查可用库存是否足够 - const availableQty = stockRecord.quantity - stockRecord.locked_quantity; - if (availableQty < absQty) { - return { - success: false, - error: `库存不足,可用 ${availableQty},需求 ${absQty}`, - data: { - available: availableQty, - required: absQty, - recordId: stockWarehouseId, - }, - }; - } - - // 检查锁定后是否会导致超卖 - const newLocked = stockRecord.locked_quantity + absQty; - if (newLocked > stockRecord.quantity) { - return { - success: false, - error: `锁定后会导致超卖,总库存 ${stockRecord.quantity},锁定后 ${newLocked}`, - data: null, - }; - } - } else { - // 减锁操作:检查已锁定库存是否足够释放 - if (stockRecord.locked_quantity < absQty) { - return { - success: false, - error: `释放数量超过已锁定库存,已锁 ${stockRecord.locked_quantity},尝试释放 ${absQty}`, - data: null, - }; - } - - // 检查释放后锁定数是否为负 - const newLocked = stockRecord.locked_quantity - absQty; - if (newLocked < 0) { - return { - success: false, - error: `释放后锁定库存为负值: ${newLocked}`, - data: null, - }; - } - } - - // 3. 执行锁定/释放操作 - let updateResult; - if (isLocking) { - // 加锁:增加 locked_quantity - updateResult = await stockRecord.increment('locked_quantity', { - by: absQty, - transaction, - silent: true, - }); - app.logger.info( - `[库存锁定] ID: ${stockWarehouseId}, 增加锁定: +${absQty}, 锁定后: ${stockRecord.locked_quantity + absQty}` - ); - } else { - // 减锁:减少 locked_quantity(确保不小于0) - updateResult = await stockRecord.decrement('locked_quantity', { - by: absQty, - transaction, - silent: true, - }); - app.logger.info( - `[库存释放] ID: ${stockWarehouseId}, 减少锁定: -${absQty}, 锁定后: ${stockRecord.locked_quantity - absQty}` - ); - } - - // 4. 获取更新后的数据(可选) - await stockRecord.reload({ - transaction, - }); - - // 5. 返回成功结果 + if (storeId <= 0 || warehouseId <= 0) { return { - success: true, - data: { - id: stockWarehouseId, - action: isLocking ? 'lock' : 'unlock', - quantity: absQty, - beforeLocked: isLocking ? stockRecord.locked_quantity - absQty : stockRecord.locked_quantity + - absQty, - afterLocked: stockRecord.locked_quantity, - totalQuantity: stockRecord.quantity, - available: stockRecord.quantity - stockRecord.locked_quantity, - updatedAt: stockRecord.update_at, - }, - error: null, + relation: null, + policyConfig: null, + allowOversell: false, }; + } - } catch (error) { - app.logger.error('[lockItemStorages] 系统异常', { - stockWarehouseId, - quantity, - isLocking, - error: error.message, - stack: error.stack, - }); + const relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + attributes: [ 'id', 'policy_config', 'auth_status', 'warehouse_use_status', 'store_use_status' ], + transaction, + raw: true, + }); - // 根据错误类型返回 - if (error.name && error.name.includes('Sequelize')) { + if (!relation) { + return { + relation: null, + policyConfig: null, + allowOversell: false, + }; + } + + const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; + const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function' + ? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id, transaction) + : null; + + return { + relation, + policyConfig, + allowOversell: Number(policyConfig && policyConfig.allow_oversell) === 1, + }; + } + + /** + * 统一修改 wms_stock_warehouse.locked_quantity 并写入 stock_transaction 流水。 + * 所有对 locked_quantity 的写操作必须通过此函数,禁止直接 increment/decrement/update。 + * + * @param {number} stockId StockWarehouse.id。 + * @param {number} change 变更量,正数为加锁,负数为解锁。 + * @param {Object} currentTransaction 数据库事务对象。 + * @param {Object} [meta={}] 元信息。 + * @param {boolean} [meta.allowOversell=false] 是否允许超卖,为 true 时跳过可用库存校验。 + * @param {boolean} [meta.skipTransactionLog=false] 是否跳过流水写入。 + * @param {string} [meta.orderType] 订单类型,用于流水。 + * @param {string} [meta.orderNo] 订单号。 + * @param {number} [meta.orderId] 订单ID。 + * @param {string} [meta.remark] 备注。 + * @param {string} [meta.operatorId] 操作人ID。 + * @param {string} [meta.operatorName] 操作人姓名。 + * @return {Promise<{success: boolean, error?: string, data?: Object}>} 修改结果,失败时携带错误信息。 + */ + async updateLockedQuantity(stockId, change, currentTransaction, meta = {}) { + const { ctx, app } = this; + const absQty = Math.abs(change); + const isLocking = change > 0; + + if (!stockId || absQty <= 0) { + return { success: false, error: `参数无效: stockId=${stockId}, change=${change}` }; + } + + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + transaction: currentTransaction, + lock: currentTransaction.LOCK.UPDATE, + attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity' ], + raw: false, + }); + + if (!stockRecord) { + return { success: false, error: `库存记录不存在或已失效 (ID: ${stockId})` }; + } + + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLocked = Number(stockRecord.locked_quantity) || 0; + + // 加锁校验:可用库存(允许超卖时跳过此校验) + if (isLocking && meta.allowOversell !== true) { + const availableQty = beforeQuantity - beforeLocked; + if (availableQty < absQty) { return { success: false, - error: `数据库操作失败: ${error.message}`, - data: null, + error: `库存不足,可用 ${availableQty},需求 ${absQty}`, + data: { available: availableQty, required: absQty }, }; } + } + // 解锁校验:锁定库存足够 + if (!isLocking && beforeLocked < absQty) { return { success: false, - error: `系统错误: ${error.message}`, - data: null, + error: `释放数量超过已锁定库存,已锁 ${beforeLocked},尝试释放 ${absQty}`, }; } + + // 执行写操作 + await stockRecord.increment('locked_quantity', { + by: change, + transaction: currentTransaction, + silent: true, + }); + + const afterLocked = beforeLocked + change; + const afterQuantity = beforeQuantity; // locked_quantity 变更不影响 quantity + + // 写入流水(除非显式跳过) + const skipLog = meta.skipTransactionLog === true; + if (!skipLog && ctx.service && ctx.service.systems && ctx.service.systems.stockTransaction) { + // 锁定操作使用 LOCK 类型,释放操作(如取消订单)使用 UNLOCK + await ctx.service.systems.stockTransaction.create({ + transaction_type: isLocking ? 'LOCK' : 'UNLOCK', + warehouse_id: stockRecord.warehouse_id, + store_id: stockRecord.store_id, + stock_id: stockId, + quantity: absQty, + order_type: meta.orderType || null, + order_no: meta.orderNo || null, + order_id: meta.orderId || null, + operator_id: meta.operatorId || String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), + operator_name: meta.operatorName || ctx.user?.employees_name || '', + remark: meta.remark || `库存${isLocking ? '锁定' : '释放'}`, + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLocked, + after_locked_quantity: afterLocked, + created_at: new Date(), + }, { transaction: currentTransaction }); + } + + app.logger.info( + `[库存${isLocking ? '锁定' : '释放'}] ID: ${stockId}, ${isLocking ? '+' : '-'}${absQty}, 锁定后: ${afterLocked}` + ); + + return { + success: true, + data: { + id: stockId, + action: isLocking ? 'lock' : 'unlock', + quantity: absQty, + beforeLocked, + afterLocked, + totalQuantity: afterQuantity, + available: afterQuantity - afterLocked, + }, + }; + } + + /** + * 锁定或释放库存。 + * + * @param {number|string} stockWarehouseId 库存主键。 + * @param {number} quantity 锁定数量,负数表示释放。 + * @param {Object|null} transaction 数据库事务。 + * @param {Object|null} [oversellConfig=null] 可选预取策略配置,用于避免锁内查DB。 + * @param {Object} [meta={}] 可选元信息,透传给 updateLockedQuantity 用于流水记录。 + * @return {Promise} 锁定结果。 + */ + async lockItemStorages(stockWarehouseId, quantity, transaction, oversellConfig = null, meta = {}) { + const { app } = this; + + const lockQty = parseInt(quantity); + if (!stockWarehouseId || isNaN(lockQty) || lockQty === 0) { + return { success: false, error: '参数错误:库存ID无效或数量为0', data: null }; + } + + const isLocking = lockQty > 0; + const absQty = Math.abs(lockQty); + + try { + return await this._runWithTransaction(transaction, async currentTransaction => { + const allowOversell = oversellConfig ? oversellConfig.allowOversell : false; + + const result = await this.updateLockedQuantity(stockWarehouseId, lockQty, currentTransaction, { + remark: meta.remark || (isLocking ? '出库单创建锁定' : '出库单创建解锁'), + orderType: meta.orderType || null, + orderNo: meta.orderNo || null, + orderId: meta.orderId || null, + allowOversell: isLocking ? allowOversell : undefined, + }); + + if (!result.success) { + return result; + } + + const { beforeLocked, afterLocked, totalQuantity } = result.data; + return { + success: true, + data: { + id: stockWarehouseId, + action: isLocking ? 'lock' : 'unlock', + quantity: absQty, + beforeLocked, + afterLocked, + totalQuantity, + available: totalQuantity - afterLocked, + }, + error: null, + }; + }); + } catch (error) { + app.logger.error('[lockItemStorages] 系统异常', { stockWarehouseId, quantity, isLocking, error: error.message }); + if (error.name && error.name.includes('Sequelize')) { + return { success: false, error: `数据库操作失败: ${error.message}`, data: null }; + } + return { success: false, error: `系统错误: ${error.message}`, data: null }; + } } /** * 商品入库服务 * @param {number} itemId 商品ID (StockStore.id) * @param {number} quantity 入库数量(正数) * @param {Object} transaction 数据库事务 + * @param {Object} [opts] 可选配置,透传给 getItemStorages。 */ - async inbound(itemId, quantity, transaction) { + async inbound(itemId, quantity, transaction, opts = {}) { const { ctx, app, @@ -594,73 +854,167 @@ class stockStoreService extends Service { } try { - // 2. 获取商品和库存信息(复用) - const stockResult = await this.getItemStorages(itemId, transaction); + return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { + // 2. 获取商品和库存信息(复用) + const stockResult = await this.getItemStorages(itemId, currentTransaction, opts); - if (!stockResult.success) { - // 入库失败:商品不存在或未绑定 - return stockResult; - } - const { - stock, - storage, - } = stockResult.data; + if (!stockResult.success) { + if (hasExternalTransaction) { + throw new Error(stockResult.error); + } + return stockResult; + } + + const { storage } = stockResult.data; + + // 3. 执行库存增加 + if (!storage.exists) { + const failureResult = { + success: false, + error: '库存记录不存在,首次入库需要完整参数', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + + const beforeQuantity = Number(storage.quantity) || 0; + const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; - // 3. 执行库存增加 - let result; - if (storage.exists) { // 非首次入库:更新现有记录(只增加quantity) - result = await ctx.model.StockWarehouse.increment('quantity', { + const [ affectedRows ] = await ctx.model.StockWarehouse.increment('quantity', { by: inboundQty, where: { id: storage.id, is_valid: 'Y', deleted_at: null, }, - transaction, + transaction: currentTransaction, + }); + + if (!affectedRows || affectedRows === 0) { + const failureResult = { + success: false, + error: '商品库存记录不存在或已失效,入库失败', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + + const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { + transaction: currentTransaction, + raw: true, + }); + + const afterQuantity = Number(updatedRecord.quantity) || 0; + const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0; + + // 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据) + if (beforeQuantity <= 0) { + const nonNegativeDelta = Math.max(0, afterQuantity) - Math.max(0, beforeQuantity); + const offsetQty = await ctx.service.systems.storage.index.offsetGapOnInbound(storage.id, inboundQty, { + transaction: currentTransaction, + maxOffset: nonNegativeDelta, + orderNo: 'STOCK_STORE_INBOUND', + operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''), + operatorName: ctx.user?.employees_name || '', + }); + if (offsetQty > 0) { + app.logger.info(`[入库] 负库存回填平账,冲销 GAP 挂账 ${offsetQty} 件 stockId=${storage.id}`); + } + } + + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, + store_id: ctx.user.store_id, + stock_id: storage.id, + storage_id: null, + space_id: null, + quantity: inboundQty, + batch_no: null, + inventory_type: 'ZP', + order_type: 'STOCK_STORE_INBOUND', + order_no: null, + order_id: null, + receiving_id: null, + entry_order_id: null, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '商品入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { + transaction: currentTransaction, + }); + + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, + store_id: ctx.user.store_id, + stock_id: storage.id, + storage_id: null, + space_id: null, + quantity: inboundQty, + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + batch_no: null, + inventory_type: 'ZP', + order_type: 'STOCK_STORE_INBOUND', + order_no: null, + order_id: null, + source_order_codes: null, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '商品入库', + created_at: new Date(), + }, { + transaction: currentTransaction, }); app.logger.info('[入库] 更新现有库存', { itemId, stockId: storage.id, quantity: inboundQty, - before: storage.quantity, - after: storage.quantity + inboundQty, + before: beforeQuantity, + after: afterQuantity, }); - } else { - // 首次入库:需要创建库存记录(stock_id应该已存在) - // 注意:这里需要更多信息,如warehouse_id等,实际场景可能需要额外参数 - return { - success: false, - error: '库存记录不存在,首次入库需要完整参数', - data: null, - }; - } - // 4. 获取更新后的数据 - const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { - transaction, - raw: true, + await this.clearItemStorageCache(itemId); + + return { + success: true, + data: { + itemId, + stockId: storage.id, + action: 'inbound', + quantity: inboundQty, + beforeQuantity, + afterQuantity, + beforeLocked: beforeLockedQuantity, + afterLocked: afterLockedQuantity, + available: afterQuantity - afterLockedQuantity, + updatedAt: updatedRecord.update_at, + }, + error: null, + }; }); - return { - success: true, - data: { - itemId, - stockId: storage.id, - action: 'inbound', - quantity: inboundQty, - beforeQuantity: storage.quantity, - afterQuantity: updatedRecord.quantity, - beforeLocked: storage.lockedQuantity, - afterLocked: updatedRecord.locked_quantity, - available: updatedRecord.quantity - updatedRecord.locked_quantity, - updatedAt: updatedRecord.update_at, - }, - error: null, - }; - } catch (error) { + if (transaction) { + throw error; + } + app.logger.error('[inbound] 入库失败', { itemId, quantity, @@ -675,17 +1029,189 @@ class stockStoreService extends Service { }; } } + + /** + * 规范化出库元信息,兼容驼峰与下划线字段。 + * + * @param {Object} meta 出库元信息。 + * @return {Object} 规范化后的订单上下文。 + */ + normalizeOutboundMeta(meta = {}) { + const normalized = meta && typeof meta === 'object' ? meta : {}; + const orderIdRaw = normalized.orderId + ?? normalized.order_id + ?? normalized.deliveryOrderId + ?? normalized.delivery_order_id + ?? normalized.id; + const orderItemIdRaw = normalized.orderItemId ?? normalized.order_item_id; + const sourceOrderCodesRaw = normalized.sourceOrderCodes ?? normalized.source_order_codes; + const orderNoRaw = normalized.orderNo + ?? sourceOrderCodesRaw + ?? normalized.order_no + ?? normalized.deliveryOrderCode + ?? normalized.delivery_order_code; + const orderId = Number(orderIdRaw); + const orderItemId = Number(orderItemIdRaw); + const orderNo = String(orderNoRaw || '').trim(); + const sourceOrderCodes = String(sourceOrderCodesRaw || '').trim(); + + return { + orderId: Number.isFinite(orderId) && orderId > 0 ? orderId : null, + orderItemId: Number.isFinite(orderItemId) && orderItemId > 0 ? orderItemId : null, + orderNo: orderNo || null, + sourceOrderCodes: sourceOrderCodes || null, + }; + } + + /** + * 查询订单明细对应的拣货分配记录。 + * + * @param {number|null} orderId 订单 ID。 + * @param {number|null} orderItemId 订单明细 ID。 + * @param {Object|null} transaction 事务对象。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 拣货分配列表。 + */ + async getPickingRowsForOutbound(orderId, orderItemId, transaction, warehouseId) { + const { ctx } = this; + const pickingModel = ctx.model && ctx.model.Picking; + + if (!pickingModel || typeof pickingModel.findAll !== 'function') { + return []; + } + + if (!orderId || !orderItemId) { + return []; + } + + const rows = await pickingModel.findAll({ + where: { + order_id: orderId, + order_item_id: orderItemId, + warehouse_id: warehouseId, + }, + attributes: [ 'storage_id', 'space_id', 'quantity' ], + order: [[ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 批量查询拣货行对应的库存批次号(wms_storage.batch_no)。 + * + * @param {Array} pickingRows 拣货分配记录列表 + * @param {Object|null} transaction 事务对象 + * @return {Promise>} storage_id → batch_no 映射表 + */ + async getPickingBatchMap(pickingRows, transaction) { + const { ctx, app } = this; + const map = new Map(); + if (!Array.isArray(pickingRows) || pickingRows.length === 0) { + return map; + } + + const storageIds = [ ...new Set(pickingRows.map(r => Number(r.storage_id)).filter(id => id > 0)) ]; + if (storageIds.length === 0) { + return map; + } + + try { + const storageRows = await ctx.model.Storage.findAll({ + where: { id: { [app.Sequelize.Op.in]: storageIds } }, + attributes: [ 'id', 'batch_no' ], + raw: true, + transaction, + }); + for (const sr of storageRows) { + if (sr && sr.batch_no) { + map.set(Number(sr.id), String(sr.batch_no).trim()); + } + } + } catch (error) { + app.logger.warn(`[getPickingBatchMap] 查询 storage batch_no 失败,降级跳过: ${error.message}`); + } + + return map; + } + + /** + * 生成出库流水写入明细,优先按拣货分配逐条记录。 + * + * @param {Object} options 参数集合。 + * @param {number} options.outboundQty 本次出库总数量。 + * @param {Array} options.pickingRows 拣货分配记录。 + * @param {Object} options.basePayload 流水公共字段。 + * @param {Map} options.pickingBatchMap storage_id → batch_no 映射表。 + * @return {Array} 待写入的出库流水列表。 + */ + buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload, pickingBatchMap = new Map() }) { + const payloads = []; + const normalizedRows = Array.isArray(pickingRows) ? pickingRows : []; + let consumedQty = 0; + + for (const pickingRow of normalizedRows) { + const remainingQty = outboundQty - consumedQty; + if (remainingQty <= 0) { + break; + } + + const pickingQty = Number(pickingRow && pickingRow.quantity) || 0; + if (pickingQty <= 0) { + continue; + } + + const transactionQty = Math.min(pickingQty, remainingQty); + const storageId = pickingRow && pickingRow.storage_id ? Number(pickingRow.storage_id) : null; + const batchNo = storageId ? (pickingBatchMap.get(storageId) || null) : null; + + payloads.push({ + ...basePayload, + storage_id: storageId, + space_id: pickingRow && pickingRow.space_id ? Number(pickingRow.space_id) : null, + quantity: transactionQty, + batch_no: batchNo || basePayload.batch_no || null, + }); + consumedQty += transactionQty; + } + + if (payloads.length === 0) { + return [{ + ...basePayload, + storage_id: null, + space_id: null, + quantity: outboundQty, + }]; + } + + if (consumedQty < outboundQty) { + payloads.push({ + ...basePayload, + storage_id: null, + space_id: null, + quantity: outboundQty - consumedQty, + }); + } + + return payloads; + } + /** * 商品出库服务 * @param {number} itemId 商品ID (StockStore.id) * @param {number} quantity 出库数量(正数) * @param {Object} transaction 数据库事务 + * @param {Object} meta 出库元信息(订单、明细等) + * @param {Object} [opts] 可选配置,透传给 getItemStorages。 */ - async outbound(itemId, quantity, transaction) { + async outbound(itemId, quantity, transaction, meta = {}, opts = {}) { const { ctx, app, } = this; + const outboundMeta = this.normalizeOutboundMeta(meta); // 1. 参数验证 const outboundQty = parseInt(quantity); @@ -698,108 +1224,188 @@ class stockStoreService extends Service { } try { - // 2. 获取商品和库存信息(复用) - const stockResult = await this.getItemStorages(itemId, transaction); + return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { + // 2. 获取商品和库存信息(复用) + const stockResult = await this.getItemStorages(itemId, currentTransaction, opts); - if (!stockResult.success) { - return stockResult; - } + if (!stockResult.success) { + if (hasExternalTransaction) { + throw new Error(stockResult.error); + } + return stockResult; + } - const { - stock, - storage, - } = stockResult.data; + const { storage } = stockResult.data; - // 3. 检查库存是否足够出库 - if (!storage.exists) { - return { - success: false, - error: '库存记录不存在,无法出库', - data: null, + // 3. 检查库存是否足够出库 + if (!storage.exists) { + const failureResult = { + success: false, + error: '库存记录不存在,无法出库', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + + const beforeQuantity = Number(storage.quantity) || 0; + const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; + + const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(storage.id, currentTransaction); + const allowOversell = policyConfig.allowOversell === true; + + // 关键检查:总库存是否足够,启用超卖时放行负库存结果 + if (beforeQuantity < outboundQty && !allowOversell) { + const failureResult = { + success: false, + error: `总库存不足,当前 ${beforeQuantity},需求 ${outboundQty}`, + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + + // 关键检查:锁定库存是否足够扣减 + if (beforeLockedQuantity < outboundQty) { + const failureResult = { + success: false, + error: `锁定库存不足,已锁定 ${beforeLockedQuantity},需求 ${outboundQty}`, + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + + // 4. 执行出库扣减:先调用核心函数处理 locked_quantity,再单独扣减 quantity + const lockResult = await this.updateLockedQuantity(storage.id, -outboundQty, currentTransaction, { + skipTransactionLog: true, + remark: '订单出库', + orderType: 'STOCK_STORE_OUTBOUND', + orderNo: outboundMeta.orderNo, + orderId: outboundMeta.orderId, + }); + + if (!lockResult.success) { + if (hasExternalTransaction) { + throw new Error(lockResult.error); + } + return lockResult; + } + + // 同步扣减 quantity + const qtyResult = await ctx.model.StockWarehouse.update({ + quantity: app.Sequelize.literal(`quantity - ${outboundQty}`), + update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { id: storage.id, is_valid: 'Y', deleted_at: null }, + transaction: currentTransaction, + }); + + if (qtyResult[0] === 0) { + const failureResult = { success: false, error: '出库失败:库存已被其他操作修改', data: null }; + if (hasExternalTransaction) throw new Error(failureResult.error); + return failureResult; + } + + // 5. 获取更新后的数据 + const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { + transaction: currentTransaction, + raw: true, + }); + + const afterQuantity = Number(updatedRecord.quantity) || 0; + const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0; + + let pickingRows = []; + if (outboundMeta.orderId && outboundMeta.orderItemId) { + try { + const pickingWarehouseId = Number(storage.warehouse_id || updatedRecord.warehouse_id || ctx.user.store_id || 0); + pickingRows = await this.getPickingRowsForOutbound(outboundMeta.orderId, outboundMeta.orderItemId, currentTransaction, pickingWarehouseId); + } catch (error) { + app.logger.warn(`[outbound] 读取拣货分配失败,降级为单条出库流水: ${error.message}`); + } + } + + // 获取拣货行对应的库存批次号(wms_storage.batch_no) + const pickingBatchMap = await this.getPickingBatchMap(pickingRows, currentTransaction); + + const baseTransactionPayload = { + transaction_type: 'OUTBOUND', + warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, + store_id: storage.storeId || updatedRecord.store_id || ctx.user.store_id, + stock_id: storage.id, + batch_no: null, + inventory_type: 'ZP', + order_type: 'STOCK_STORE_OUTBOUND', + order_no: outboundMeta.orderNo, + order_id: outboundMeta.orderId, + source_order_codes: outboundMeta.sourceOrderCodes, + receiving_id: null, + entry_order_id: null, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '订单出库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), }; - } - // 关键检查:总库存是否足够 - if (storage.quantity < outboundQty) { - return { - success: false, - error: `总库存不足,当前 ${storage.quantity},需求 ${outboundQty}`, - data: null, - }; - } + const transactionPayloads = this.buildOutboundTransactionPayloads({ + outboundQty, + pickingRows, + basePayload: baseTransactionPayload, + pickingBatchMap, + }); - // 关键检查:锁定库存是否足够扣减 - if (storage.lockedQuantity < outboundQty) { - return { - success: false, - error: `锁定库存不足,已锁定 ${storage.lockedQuantity},需求 ${outboundQty}`, - data: null, - }; - } + for (const payload of transactionPayloads) { + await ctx.service.systems.stockTransaction.create(payload, { + transaction: currentTransaction, + }); + } - // 4. 执行出库扣减(同时减少quantity和locked_quantity) - const result = await ctx.model.StockWarehouse.update({ - quantity: app.Sequelize.literal(`quantity - ${outboundQty}`), - locked_quantity: app.Sequelize.literal(`locked_quantity - ${outboundQty}`), - update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, { - where: { - id: storage.id, - is_valid: 'Y', - deleted_at: null, - // 乐观锁条件:确保更新时库存仍然足够 - quantity: { - [app.Sequelize.Op.gte]: outboundQty, - }, - locked_quantity: { - [app.Sequelize.Op.gte]: outboundQty, - }, - }, - transaction, - }); - - if (result[0] === 0) { - return { - success: false, - error: '出库失败:库存已被其他操作修改', - data: null, - }; - } - - // 5. 获取更新后的数据 - const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { - transaction, - raw: true, - }); - - app.logger.info('[出库] 成功', { - itemId, - stockId: storage.id, - quantity: outboundQty, - beforeQuantity: storage.quantity, - afterQuantity: updatedRecord.quantity, - beforeLocked: storage.lockedQuantity, - afterLocked: updatedRecord.locked_quantity, - }); - - return { - success: true, - data: { + app.logger.info('[出库] 成功', { itemId, stockId: storage.id, - action: 'outbound', quantity: outboundQty, - beforeQuantity: storage.quantity, - afterQuantity: updatedRecord.quantity, - beforeLocked: storage.lockedQuantity, - afterLocked: updatedRecord.locked_quantity, - available: updatedRecord.quantity - updatedRecord.locked_quantity, - updatedAt: updatedRecord.update_at, - }, - error: null, - }; + beforeQuantity, + afterQuantity, + beforeLocked: beforeLockedQuantity, + afterLocked: afterLockedQuantity, + }); + + await this.clearItemStorageCache(itemId); + + return { + success: true, + data: { + itemId, + stockId: storage.id, + action: 'outbound', + quantity: outboundQty, + beforeQuantity, + afterQuantity, + beforeLocked: beforeLockedQuantity, + afterLocked: afterLockedQuantity, + available: afterQuantity - afterLockedQuantity, + updatedAt: updatedRecord.update_at, + }, + error: null, + }; + }); } catch (error) { + if (transaction) { + throw error; + } + app.logger.error('[outbound] 出库失败', { itemId, quantity, @@ -846,6 +1452,7 @@ class stockStoreService extends Service { warehouse_id: warehouseId, store_id: sourceData.store_id, deleted_at: null, + is_valid: 'Y', }, attributes: [ 'id' ], raw: true, @@ -899,6 +1506,9 @@ class stockStoreService extends Service { // 其他字段 packing_requirements: sourceData.packing_requirements || '', + pick_requirements: sourceData.pick_requirements || '', + recheck_requirements: sourceData.recheck_requirements || '', + merge_requirements: sourceData.merge_requirements || 'Y', create_at: now, update_at: now, is_valid: 'Y', @@ -957,6 +1567,7 @@ class stockStoreService extends Service { goods_code: sourceData.goods_code, warehouse_id: warehouseId, is_valid: 'Y', + deleted_at: null, }, attributes: [ 'id' ], raw: true, @@ -1008,13 +1619,14 @@ class stockStoreService extends Service { * @param {Object} sortParams - 排序参数 * @param {string} sortParams.sortField - 排序字段,默认'create_at' * @param {string} sortParams.sortOrder - 排序方式,默认'DESC' + * @param {number} externalWarehouseId - 外部传入的仓库ID,缺省取当前用户仓库上下文 + * @param {number} externalStoreId - 外部传入的货主ID,缺省不按货主过滤 * @return {Promise} 返回查询结果 */ - async getWarehouseStock(where, pageParams = {}, sortParams = {}) { + async getWarehouseStock(where, pageParams = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) { const { ctx, app, - config, } = this; const { Sequelize, @@ -1023,6 +1635,15 @@ class stockStoreService extends Service { Op, } = Sequelize; + // 仓库ID:优先使用外部传入,否则取当前用户上下文 + const warehouseId = Number.isFinite(externalWarehouseId) && externalWarehouseId > 0 + ? externalWarehouseId + : ctx.user.store_id; + // 货主ID:外部传入时按货主维度查询(不限定仓库) + const storeId = Number.isFinite(externalStoreId) && externalStoreId > 0 + ? externalStoreId + : 0; + try { // 设置默认参数 const { @@ -1049,61 +1670,133 @@ class stockStoreService extends Service { const prohibitedQueryOptions = { where: {}, }; + const storeOutStockQueryOptions = { + where: {}, + }; // 添加默认条件 - queryOptions.where[Op.and] = [{ - warehouse_id: ctx.user.store_id, - }, - { - is_valid: 'Y', - }, - { - deleted_at: null, - }, - ]; + if (storeId > 0) { + // 按货主维度查询(不限定仓库) + queryOptions.where[Op.and] = [{ + store_id: storeId, + }, + { + is_valid: 'Y', + }, + { + deleted_at: null, + }, + ]; + } else { + queryOptions.where[Op.and] = [{ + warehouse_id: warehouseId, + }, + { + is_valid: 'Y', + }, + { + deleted_at: null, + }, + ]; + } barcodeQueryOptions.where[Op.and] = []; prohibitedQueryOptions.where[Op.and] = []; + storeOutStockQueryOptions.where[Op.and] = []; // 检测并处理条码查询条件 let hasBarcodeCondition = false; - let hasProhibitedCondition = false; + let hasBoundItemCondition = false; + let boundItemValue = null; let barcodeCondition = null; + let parsedBarcodeInput = null; + + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? ctx.where + : (where && typeof where === 'object' ? where : {}); // 处理动态查询条件 - if (where && Object.keys(where).length > 0) { - const dynamicConditions = []; - const prohibitedConditions = []; - const barcodedynamicConditions = []; + if (normalizedWhere && Object.keys(normalizedWhere).length > 0) { + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, + has_requirements: { + bucket: 'requirement', + }, + keyword: { + bucket: 'keyword', + }, + }, + }); - for (const fieldKey in where) { - const condition = where[fieldKey]; - - if (this.isEmptyValue(condition.value)) { - continue; + if (!parsed.ok) { + return { + code: 400, + data: { + list: [], + pagination: { + page: parseInt(page), + pageSize: parseInt(pageSize), + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + }, + message: `筛选条件解析失败: ${parsed.reason}`, + }; } - // 检查是否是条码查询 - if (fieldKey === 'barcode') { - hasBarcodeCondition = true; - barcodeCondition = this.buildSequelizeCondition(fieldKey, condition, app); - if (barcodeCondition) { - barcodedynamicConditions.push(barcodeCondition); - } - continue; // 暂不添加到动态条件中 - } - if (fieldKey === 'prohibited_type') { - condition.field = 'id'; - hasProhibitedCondition = true; - const prohibitedCondition = this.buildSequelizeCondition('id', condition, app); - if (prohibitedCondition) { - prohibitedConditions.push(prohibitedCondition); - } - continue; - } - // 其他字段的处理 - const sequelizeCondition = this.buildSequelizeCondition(fieldKey, condition, app); - if (sequelizeCondition) { - dynamicConditions.push(sequelizeCondition); - } + parsedResult = parsed.result; + } + + const { + dynamicConditions, + bucketConditions, + bucketFlags, + rawConditionsByField, + } = parsedResult; + + const barcodeDynamicConditions = bucketConditions.barcode || []; + const prohibitedConditions = bucketConditions.prohibited || []; + const storeOutStockConditions = bucketConditions.storeOutStock || []; + + hasBarcodeCondition = Boolean(bucketFlags.barcode); + hasProhibitedCondition = Boolean(bucketFlags.prohibited); + hasBoundItemCondition = Boolean(bucketFlags.storeOutStock); + barcodeCondition = barcodeDynamicConditions[0] || null; + parsedBarcodeInput = rawConditionsByField.barcode || null; + + if (hasBoundItemCondition && rawConditionsByField.has_bound_item) { + boundItemValue = rawConditionsByField.has_bound_item.value; + } + + // keyword 快捷搜索:模糊匹配商品编码/名称/货物编码 + const keywordInput = rawConditionsByField.keyword || null; + const keywordValue = keywordInput && typeof keywordInput === 'object' + ? keywordInput.value + : keywordInput; + if (keywordValue !== undefined && keywordValue !== null && String(keywordValue).trim() !== '') { + const kw = `%${String(keywordValue).trim()}%`; + queryOptions.where[Op.and].push({ + [Op.or]: [ + { item_code: { [Op.like]: kw } }, + { item_name: { [Op.like]: kw } }, + { goods_code: { [Op.like]: kw } }, + ], + }); } if (dynamicConditions.length > 0) { @@ -1111,17 +1804,71 @@ class stockStoreService extends Service { [Op.and]: dynamicConditions, }); } - if (barcodedynamicConditions.length > 0) { + + // 作业要求虚拟筛选:是否有作业要求 + // 值:Y=有作业要求(拣货/复核/打包任一非空),N=无作业要求, + // pick/recheck/packing=对应要求不为空(大小写不敏感) + const rawRequirementCondition = rawConditionsByField.has_requirements; + if (rawRequirementCondition) { + const flagValue = rawRequirementCondition.value; + const normalizedFlag = String(flagValue === undefined || flagValue === null ? '' : flagValue).trim().toLowerCase(); + const isYes = flagValue === true || flagValue === 1 || normalizedFlag === 'y' + || normalizedFlag === 'true' || normalizedFlag === '1' + || normalizedFlag === '是' || normalizedFlag === '有'; + const isNo = flagValue === false || flagValue === 0 || normalizedFlag === 'n' + || normalizedFlag === 'false' || normalizedFlag === '0' + || normalizedFlag === '否' || normalizedFlag === '无'; + const singleFieldNameMap = { + packing: 'packing_requirements', + pick: 'pick_requirements', + recheck: 'recheck_requirements', + }; + const singleFieldName = singleFieldNameMap[normalizedFlag] || ''; + + if (isYes || isNo || singleFieldName) { + const requirementFieldNames = singleFieldName + ? [ singleFieldName ] + : [ 'packing_requirements', 'pick_requirements', 'recheck_requirements' ]; + const requirementFieldConditions = requirementFieldNames.map(fieldName => (isNo + ? { [fieldName]: { [Op.or]: [ null, '' ] } } + : { [fieldName]: { [Op.and]: [{ [Op.ne]: '' }, { [Op.not]: null }] } })); + queryOptions.where[Op.and].push(isNo + ? { [Op.and]: requirementFieldConditions } + : { [Op.or]: requirementFieldConditions }); + } + } + if (barcodeDynamicConditions.length > 0) { barcodeQueryOptions.where[Op.and].push({ - [Op.and]: barcodedynamicConditions, + [Op.and]: barcodeDynamicConditions, }); } + if (prohibitedConditions.length > 0) { prohibitedQueryOptions.where[Op.and].push({ [Op.and]: prohibitedConditions, }); } + if (storeOutStockConditions.length > 0) { + storeOutStockQueryOptions.where[Op.and].push({ + [Op.and]: storeOutStockConditions, + }); + } + + // has_bound_item 的「未绑定」场景:通过 NOT EXISTS 子查询在主表 where 上直接过滤 + const isBoundFalse = boundItemValue === false + || boundItemValue === 0 + || String(boundItemValue || '').trim().toLowerCase() === 'false' + || String(boundItemValue || '').trim() === '0' + || String(boundItemValue || '').trim().toLowerCase() === 'n'; + + if (hasBoundItemCondition && isBoundFalse) { + queryOptions.where[Op.and].push( + Sequelize.literal( + 'NOT EXISTS (SELECT 1 FROM wms_stock_store WHERE wms_stock_store.stock_id = stock_warehouse.id)' + ) + ); + } } // 如果有条码查询条件,先查询匹配的库存ID @@ -1131,11 +1878,11 @@ class stockStoreService extends Service { let barcodeValues = []; // 根据不同的条件格式提取条码值 - if (where.barcode.value) { - if (Array.isArray(where.barcode.value)) { - barcodeValues = where.barcode.value; - } else if (typeof where.barcode.value === 'string') { - barcodeValues = [ where.barcode.value ]; + if (parsedBarcodeInput && parsedBarcodeInput.value) { + if (Array.isArray(parsedBarcodeInput.value)) { + barcodeValues = parsedBarcodeInput.value; + } else if (typeof parsedBarcodeInput.value === 'string') { + barcodeValues = [ parsedBarcodeInput.value ]; } } @@ -1143,7 +1890,8 @@ class stockStoreService extends Service { // 构建条码查询条件 const barcodeWhere = {}; - if (where.barcode.operator === 'eq') { + const barcodeOperator = String(parsedBarcodeInput.operator || 'like').toLowerCase(); + if (barcodeOperator === 'eq') { // 精确查询 if (barcodeValues.length === 1) { barcodeWhere.barcode = barcodeValues[0]; @@ -1152,7 +1900,7 @@ class stockStoreService extends Service { [Op.in]: barcodeValues, }; } - } else if (where.barcode.operator === 'like') { + } else if (barcodeOperator === 'like') { // 模糊查询 if (barcodeValues.length === 1) { barcodeWhere.barcode = { @@ -1196,12 +1944,6 @@ class stockStoreService extends Service { hasPrevious: false, hasNext: false, }, - summary: { - total_quantity: 0, - total_locked: 0, - total_available: 0, - total_items: 0, - }, }, message: '查询成功', }; @@ -1219,57 +1961,96 @@ class stockStoreService extends Service { // 处理排序 const validSortFields = [ 'id', 'item_code', 'item_name', 'quantity', 'locked_quantity', - 'tag_price', 'retail_price', 'create_at', 'update_at', + 'tag_price', 'retail_price', 'create_at', 'update_at', 'available_quantity', ]; const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at'; const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; - queryOptions.order.push([ actualSortField, actualSortOrder ]); + if (actualSortField === 'available_quantity') { + queryOptions.order.push([ Sequelize.literal('(quantity - locked_quantity)'), actualSortOrder ]); + } else { + queryOptions.order.push([ actualSortField, actualSortOrder ]); + } // 计算分页偏移量 const offset = (page - 1) * pageSize; + // 确定「外部商品绑定-已绑定」场景是否需要 INNER JOIN StockStore + const isBoundTrue = hasBoundItemCondition && ( + boundItemValue === true + || boundItemValue === 1 + || String(boundItemValue || '').trim().toLowerCase() === 'true' + || String(boundItemValue || '').trim() === '1' + || String(boundItemValue || '').trim().toLowerCase() === 'y' + ); + + // 构建 include 数组 + let storeStockInclude; + + if (storeId > 0) { + // 按货主维度查询:确保 store_warehouse 关联同时匹配 store_id 和 warehouse_id,避免一对多导致行重复 + storeStockInclude = { + model: ctx.model.StoreWarehouse, + as: 'store_stock', + attributes: [ 'warehouse_remask' ], + where: { + store_id: storeId, + warehouse_use_status: 1, + [Op.and]: Sequelize.where( + Sequelize.col('stock_warehouse.warehouse_id'), + '=', + Sequelize.col('store_stock.warehouse_id') + ), + }, + required: false, + include: [{ + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'company_name' ], + required: false, + }], + }; + } else { + storeStockInclude = ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: true, + attributes: [ 'store_remask' ], + }); + } + + const includes = [ + storeStockInclude, + { + ...prohibitedQueryOptions, + model: ctx.model.ProhibitedType, + as: 'prohibited', + attributes: [ 'type_name' ], + required: hasProhibitedCondition, + }, + ]; + + if (isBoundTrue) { + includes.push({ + model: ctx.model.StockStore, + as: 'store_out_stock', + attributes: [], + required: true, + }); + } + // 执行查询:获取总数和数据 const [ total, data ] = await Promise.all([ // 获取总数 ctx.model.StockWarehouse.count({ where: queryOptions.where, - include: [{ - model: ctx.model.StoreWarehouse, - as: 'store_stock', - attributes: [ 'store_remask' ], - where: { - use_status: 1, - }, - required: true, - }, { - ...prohibitedQueryOptions, - model: ctx.model.ProhibitedType, - as: 'prohibited', - attributes: [ 'type_name' ], - required: hasProhibitedCondition, - }], + include: includes, distinct: true, }), // 获取分页数据 ctx.model.StockWarehouse.findAll({ ...queryOptions, - include: [{ - model: ctx.model.StoreWarehouse, - as: 'store_stock', - attributes: [ 'store_remask' ], - where: { - use_status: 1, - }, - required: true, - }, { - ...prohibitedQueryOptions, - model: ctx.model.ProhibitedType, - as: 'prohibited', - attributes: [ 'type_name' ], - required: hasProhibitedCondition, - }], + include: includes, limit: parseInt(pageSize), offset: parseInt(offset), distinct: true, // 确保去重 @@ -1282,33 +2063,63 @@ class stockStoreService extends Service { const hasPrevious = page > 1; const hasNext = page < totalPages; - // 批量查询条码信息 + // 批量查询条码和图片信息(直接查 DB,不走 getStockDetails 缓存) const stockIds = data.map(item => item.id); - let barcodes = []; - let images = []; + const stockDetailsMap = new Map(); if (stockIds.length > 0) { - barcodes = await ctx.model.StockBarcode.findAll({ - where: { - stock_id: { - [Op.in]: stockIds, + // 并行查询条码和图片表(无缓存),避免影响其他接口对 getStockDetails 缓存的使用 + const [ barcodeRows, imageRows ] = await Promise.all([ + app.model.StockBarcode.findAll({ + where: { stock_id: { [ Op.in ]: stockIds } }, + attributes: [ 'id', 'barcode', 'stock_id' ], + raw: true, + }), + app.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { [ Op.in ]: stockIds.map(String) }, }, - }, - raw: true, - }); - images = await ctx.model.FileReference.findAll({ - where: { - business_type: 'stock', - business_id: { - [Op.in]: stockIds, - }, - }, - include: [{ - model: ctx.model.File, - as: 'file', - attributes: [ 'file_url' ], - required: true, - }], - }); + include: [{ + model: app.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + raw: true, + }), + ]); + + // 按 stock_id 分组条码 + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const sid = row.stock_id; + const bc = (row.barcode && String(row.barcode).trim()) || ''; + if (!bc) continue; + if (!barcodeMap.has(sid)) { + barcodeMap.set(sid, []); + } + barcodeMap.get(sid).push(bc); + } + + // 按 stock_id 分组图片 + const imageMap = new Map(); + for (const row of imageRows) { + const sid = Number(row.business_id); + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (!url) continue; + if (!imageMap.has(sid)) { + imageMap.set(sid, []); + } + imageMap.get(sid).push(url); + } + + for (const item of data) { + const sid = item.id; + stockDetailsMap.set(sid, { + barcodes: barcodeMap.get(sid) || [], + images: imageMap.get(sid) || [], + }); + } } // 处理数据,添加一些计算字段 @@ -1317,21 +2128,22 @@ class stockStoreService extends Service { const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed( 2) : 0; - // 过滤该商品的条码 - const itemBarcodes = barcodes - .filter(barcode => barcode.stock_id === item.id) - .map(barcode => barcode.barcode); - const { - cos, - } = config; - const { - cdnurl, - } = cos; - const itemImages = images - .filter(images => parseInt(images.business_id) === item.id) - .map(images => images.file.file_url); + // 从直接的 DB 查询结果获取该商品的条码和图片 + const stockDetail = stockDetailsMap.get(item.id); + const itemBarcodes = stockDetail ? stockDetail.barcodes : []; + const itemImages = stockDetail ? stockDetail.images : []; + // 货主维度:仓库备注兜底仓库主体名 + let warehouseRemask = ''; + if (storeId > 0) { + warehouseRemask = (item['store_stock.warehouse_remask'] || '') + || (item['store_stock.warehouse.company_name'] || ''); + delete item['store_stock.warehouse_remask']; + delete item['store_stock.warehouse']; + delete item['store_stock.warehouse.company_name']; + } return { ...item, + ...(storeId > 0 ? { warehouse_remask: warehouseRemask } : {}), barcodes: itemBarcodes, images: itemImages, available_quantity: availableQuantity, @@ -1344,21 +2156,6 @@ class stockStoreService extends Service { }; }); - // 添加汇总信息 - const summary = { - total_quantity: data.reduce((sum, item) => sum + item.quantity, 0), - total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0), - total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item - .locked_quantity), 0), - total_items: data.length, - // 如果有条码查询,添加匹配统计 - ...(hasBarcodeCondition && { - barcode_matched_count: matchedStockIds.length, - barcode_search_value: where.barcode.value, - }), - }; - - return { code: 200, data: { @@ -1371,9 +2168,8 @@ class stockStoreService extends Service { hasPrevious, hasNext, }, - summary, queryInfo: { - conditions: where, + conditions: normalizedWhere, sortField: actualSortField, sortOrder: actualSortOrder, hasBarcodeSearch: hasBarcodeCondition, @@ -1396,18 +2192,264 @@ class stockStoreService extends Service { hasPrevious: false, hasNext: false, }, - summary: { - total_quantity: 0, - total_locked: 0, - total_available: 0, - total_items: 0, - }, }, message: `查询失败: ${error.message}`, }; } } + /** + * 导出仓库商品列表。 + * 说明:复用 getWarehouseStock 的筛选与排序语义,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} where 筛选条件 + * @param {Object} sortParams 排序参数 + * @param {string} [sortParams.sortField] 排序字段 + * @param {string} [sortParams.sortOrder] 排序方向(ASC|DESC) + * @return {Promise} 导出上传结果(含 url/fileKey 等) + */ + async exportWarehouseStock(where = {}, sortParams = {}) { + const { ctx } = this; + const warehouseId = ctx.user && ctx.user.store_id ? ctx.user.store_id : 'common'; + const pageSize = 500; + let page = 1; + let hasNext = true; + const rows = []; + + while (hasNext) { + const pageResult = await this.getWarehouseStock(where, { + page, + pageSize, + }, sortParams); + + if (!pageResult || pageResult.code !== 200) { + throw new Error(pageResult && pageResult.message ? pageResult.message : '导出仓库商品失败'); + } + + const list = pageResult.data && Array.isArray(pageResult.data.list) ? pageResult.data.list : []; + + // 收集可能的 storeIds,用于回退查询 store_remask(优先取 item.store_id,其次 item['store_warehouse.store_id']) + const storeIds = []; + for (const item of list) { + const sid = item.store_id || item['store_warehouse.store_id']; + if (sid && !storeIds.includes(Number(sid))) { + storeIds.push(Number(sid)); + } + } + + // 查询 StoreWarehouse 获取 store_remask(如果可用) + const storeMap = new Map(); + try { + if (storeIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) { + const { Op } = ctx.app.Sequelize; + const storeRows = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { + store_id: { [Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + raw: true, + }); + for (const r of storeRows || []) { + storeMap.set(Number(r.store_id), r.store_remask); + } + } + } catch (e) { + // 查询失败不影响导出,记录日志并继续 + ctx && ctx.logger && ctx.logger.warn && ctx.logger.warn('[exportWarehouseStock] 查询 StoreWarehouse 失败', e && e.message); + } + + for (const item of list) { + const storeId = Number(item.store_id || item['store_warehouse.store_id'] || 0); + const store_remask = item.store_remask || item['store_warehouse.store_remask'] || storeMap.get(storeId) || ''; + rows.push({ + id: item.id, + item_code: item.item_code, + goods_code: item.goods_code || '', + item_name: item.item_name, + brand_name: item.brand_name || '', + sku_property: item.sku_property || '', + stock_unit: item.stock_unit || '', + tag_price: item.tag_price || '', + retail_price: item.retail_price || '', + gross_weight: item.gross_weight || '', + need_recheck: String(item.need_recheck || 'Y') === 'Y' ? '需要' : '不需要', + store_remask, + barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '', + quantity: item.quantity, + locked_quantity: item.locked_quantity, + available_quantity: item.available_quantity, + lock_rate_display: item.lock_rate_display, + create_at_display: item.create_at_display, + update_at_display: item.update_at_display, + }); + } + + hasNext = Boolean(pageResult.data && pageResult.data.pagination && pageResult.data.pagination.hasNext); + page += 1; + } + + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: `仓库商品导出_${dateToken}.xlsx`, + dir: `exports/stock/warehouse/${warehouseId}`, + category: 'document', + sheets: [{ + name: '仓库商品', + columns: [ + { header: 'SKU', key: 'id' }, + { header: '商品编码', key: 'item_code' }, + { header: '货物编码', key: 'goods_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '品牌', key: 'brand_name' }, + { header: '规格', key: 'sku_property' }, + { header: '库存单位', key: 'stock_unit' }, + { header: '标价', key: 'tag_price' }, + { header: '零售价', key: 'retail_price' }, + { header: '毛重', key: 'gross_weight' }, + { header: '是否需要复核', key: 'need_recheck' }, + { header: '货主', key: 'store_remask' }, + { header: '条码', key: 'barcodes' }, + { header: '库存', key: 'quantity' }, + { header: '锁定库存', key: 'locked_quantity' }, + { header: '可用库存', key: 'available_quantity' }, + { header: '锁定率', key: 'lock_rate_display' }, + { header: '创建时间', key: 'create_at_display' }, + { header: '更新时间', key: 'update_at_display' }, + ], + rows, + }], + }); + } + + /** + * 导出外仓商品列表。 + * 说明:复用 getWarehouseStock 的外部货主维度筛选语义,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} where 筛选条件 + * @param {Object} sortParams 排序参数 + * @param {string} [sortParams.sortField] 排序字段 + * @param {string} [sortParams.sortOrder] 排序方向(ASC|DESC) + * @param {number} [externalWarehouseId=0] 外部仓库ID(0 表示按货主维度查) + * @param {number} [externalStoreId=0] 外部货主ID + * @return {Promise} 导出上传结果(含 url/fileKey 等) + */ + async exportExternalWarehouseStock(where = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) { + const { ctx } = this; + const warehouseId = externalWarehouseId > 0 ? externalWarehouseId : (ctx.user && ctx.user.store_id ? ctx.user.store_id : 'common'); + const pageSize = 500; + let page = 1; + let hasNext = true; + const rows = []; + + while (hasNext) { + const pageResult = await this.getWarehouseStock(where, { + page, + pageSize, + }, sortParams, externalWarehouseId, externalStoreId); + + if (!pageResult || pageResult.code !== 200) { + throw new Error(pageResult && pageResult.message ? pageResult.message : '导出外仓商品失败'); + } + + const list = pageResult.data && Array.isArray(pageResult.data.list) ? pageResult.data.list : []; + + // 收集可能的 storeIds,用于回退查询 store_remask(优先取 item.store_id,其次 item['store_warehouse.store_id']) + const storeIds = []; + for (const item of list) { + const sid = item.store_id || item['store_warehouse.store_id']; + if (sid && !storeIds.includes(Number(sid))) { + storeIds.push(Number(sid)); + } + } + + // 查询 StoreWarehouse 获取 store_remask(如果可用) + const storeMap = new Map(); + try { + if (storeIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) { + const { Op } = ctx.app.Sequelize; + const storeWhere = { store_id: { [Op.in]: storeIds } }; + if (externalWarehouseId > 0) { + storeWhere.warehouse_id = externalWarehouseId; + } + const storeRows = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: storeWhere, + raw: true, + }); + for (const r of storeRows || []) { + storeMap.set(Number(r.store_id), r.store_remask); + } + } + } catch (e) { + ctx && ctx.logger && ctx.logger.warn && ctx.logger.warn('[exportExternalWarehouseStock] 查询 StoreWarehouse 失败', e && e.message); + } + + for (const item of list) { + const storeId = Number(item.store_id || item['store_warehouse.store_id'] || 0); + const storeRemask = item.store_remask || item['store_warehouse.store_remask'] || storeMap.get(storeId) || ''; + rows.push({ + id: item.id, + item_code: item.item_code, + goods_code: item.goods_code || '', + item_name: item.item_name, + brand_name: item.brand_name || '', + sku_property: item.sku_property || '', + stock_unit: item.stock_unit || '', + tag_price: item.tag_price || '', + retail_price: item.retail_price || '', + gross_weight: item.gross_weight || '', + need_recheck: String(item.need_recheck || 'Y') === 'Y' ? '需要' : '不需要', + store_remask: storeRemask, + barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '', + quantity: item.quantity, + locked_quantity: item.locked_quantity, + available_quantity: item.available_quantity, + lock_rate_display: item.lock_rate_display, + create_at_display: item.create_at_display, + update_at_display: item.update_at_display, + }); + } + + hasNext = Boolean(pageResult.data && pageResult.data.pagination && pageResult.data.pagination.hasNext); + page += 1; + } + + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: `外仓商品导出_${dateToken}.xlsx`, + dir: `exports/stock/warehouse/${warehouseId}`, + category: 'document', + sheets: [{ + name: '外仓商品', + columns: [ + { header: 'SKU', key: 'id' }, + { header: '商品编码', key: 'item_code' }, + { header: '货物编码', key: 'goods_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '品牌', key: 'brand_name' }, + { header: '规格', key: 'sku_property' }, + { header: '库存单位', key: 'stock_unit' }, + { header: '标价', key: 'tag_price' }, + { header: '零售价', key: 'retail_price' }, + { header: '毛重', key: 'gross_weight' }, + { header: '是否需要复核', key: 'need_recheck' }, + { header: '货主', key: 'store_remask' }, + { header: '条码', key: 'barcodes' }, + { header: '库存', key: 'quantity' }, + { header: '锁定库存', key: 'locked_quantity' }, + { header: '可用库存', key: 'available_quantity' }, + { header: '锁定率', key: 'lock_rate_display' }, + { header: '创建时间', key: 'create_at_display' }, + { header: '更新时间', key: 'update_at_display' }, + ], + rows, + }], + }); + } + /** * 构建Sequelize查询条件 * @param {string} fieldKey - 字段键名 @@ -1416,180 +2458,11 @@ class stockStoreService extends Service { * @return {Object|null} Sequelize条件对象 */ buildSequelizeCondition(fieldKey, condition, app) { - const { - Sequelize, - } = app; - const { - operator = 'eq', value, type, isMultiple, - } = condition; - - // 处理字段名 - const fieldName = condition.field || fieldKey; - - // 特殊值处理 - const processedValue = this.processConditionValue(value, type); - // 根据操作符构建条件 - switch (operator.toLowerCase()) { - case 'eq': - return { - [fieldName]: processedValue, - }; - - case 'ne': - return { - [fieldName]: { - [Sequelize.Op.ne]: processedValue, - }, - }; - - case 'contains': - case 'like': - // 处理多值情况 - if (Array.isArray(processedValue) && processedValue.length > 0) { - // 多个值使用 OR 连接 - return { - [Sequelize.Op.or]: processedValue.map(val => ({ - [fieldName]: { - [Sequelize.Op.like]: `%${val}%`, - }, - })), - }; - } - // 单个值正常处理 - return { - [fieldName]: { - [Sequelize.Op.like]: `%${processedValue}%`, - }, - }; - - case 'startswith': - // 处理多值情况 - if (Array.isArray(processedValue) && processedValue.length > 0) { - return { - [Sequelize.Op.or]: processedValue.map(val => ({ - [fieldName]: { - [Sequelize.Op.like]: `${val}%`, - }, - })), - }; - } - return { - [fieldName]: { - [Sequelize.Op.like]: `${processedValue}%`, - }, - }; - - case 'endswith': - // 处理多值情况 - if (Array.isArray(processedValue) && processedValue.length > 0) { - return { - [Sequelize.Op.or]: processedValue.map(val => ({ - [fieldName]: { - [Sequelize.Op.like]: `%${val}`, - }, - })), - }; - } - return { - [fieldName]: { - [Sequelize.Op.like]: `%${processedValue}`, - }, - }; - - case 'gt': - return { - [fieldName]: { - [Sequelize.Op.gt]: processedValue, - }, - }; - - case 'lt': - return { - [fieldName]: { - [Sequelize.Op.lt]: processedValue, - }, - }; - - case 'ge': - return { - [fieldName]: { - [Sequelize.Op.gte]: processedValue, - }, - }; - - case 'le': - return { - [fieldName]: { - [Sequelize.Op.lte]: processedValue, - }, - }; - - case 'in': - return Array.isArray(processedValue) ? { - [fieldName]: { - [Sequelize.Op.in]: processedValue, - }, - } : - null; - - case 'notin': - return Array.isArray(processedValue) ? { - [fieldName]: { - [Sequelize.Op.notIn]: processedValue, - }, - } : - null; - - case 'between': - return Array.isArray(processedValue) && processedValue.length === 2 ? { - [fieldName]: { - [Sequelize.Op.between]: processedValue, - }, - } : - null; - - case 'notbetween': - return Array.isArray(processedValue) && processedValue.length === 2 ? { - [fieldName]: { - [Sequelize.Op.notBetween]: processedValue, - }, - } : - null; - - case 'isnull': - return { - [fieldName]: { - [Sequelize.Op.is]: null, - }, - }; - - case 'isnotnull': - return { - [fieldName]: { - [Sequelize.Op.not]: null, - }, - }; - - case 'regexp': - return { - [fieldName]: { - [Sequelize.Op.regexp]: processedValue, - }, - }; - - case 'notregexp': - return { - [fieldName]: { - [Sequelize.Op.notRegexp]: processedValue, - }, - }; - - default: - // 默认使用等于操作符 - return { - [fieldName]: processedValue, - }; + const parsed = buildSequelizeConditionUtil(fieldKey, condition, app); + if (!parsed.ok) { + return null; } + return parsed.condition; } /** @@ -1599,40 +2472,12 @@ class stockStoreService extends Service { * @return {any} 处理后的值 */ processConditionValue(value, type) { - if (value === undefined || value === null) { - return value; - } - - switch (type) { - case 'boolean': - // 处理布尔值:true/Y -> 'Y', false/N -> 'N' - if (value === true || value === 'true' || value === 'Y' || value === 'y') { - return 'Y'; - } - if (value === false || value === 'false' || value === 'N' || value === 'n') { - return 'N'; - } - return value; - - case 'date': - case 'daterange': - // 确保日期格式正确 - if (Array.isArray(value)) { - return value.map(v => this.normalizeDate(v)); - } - return this.normalizeDate(value); - - case 'number': - // 转换为数字 - const num = parseFloat(value); - return isNaN(num) ? value : num; - case 'text': - return value.split(','); - default: - return value; - } + return processConditionValueUtil(value, type); } + normalizeDate(value) { + return normalizeDateUtil(value); + } /** * 格式化日期显示 @@ -1660,19 +2505,7 @@ class stockStoreService extends Service { * @return {boolean} 是否为空 */ isEmptyValue(value) { - if (value === undefined || value === null) { - return true; - } - - if (typeof value === 'string' && value.trim() === '') { - return true; - } - - if (Array.isArray(value) && value.length === 0) { - return true; - } - - return false; + return isEmptyValueUtil(value); } async getProhibitedType() { const { @@ -1752,13 +2585,12 @@ class stockStoreService extends Service { return barcodes; } async handleBatchChange() { - const { ctx, service, app } = this; + const { ctx, app } = this; const { Op } = app.Sequelize; - const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit' ]; + const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements', 'managementFlags', 'stock_unit', 'need_recheck', 'warning_quantity' ]; const { ids, method, value } = ctx.request.body; - console.log('批量修改参数', ctx.request.body); try { // 1. 参数验证 @@ -1785,7 +2617,8 @@ class stockStoreService extends Service { where: { id: { [Op.in]: ids }, warehouse_id: warehouseId, - delete_at: null, + deleted_at: null, + is_valid: 'Y', }, attributes: [ 'id' ], }); @@ -1815,10 +2648,10 @@ class stockStoreService extends Service { }; } else if (method === 'gross_weight') { - // 毛重应该是数字 - const updateValue = parseFloat(value); - if (isNaN(updateValue) || updateValue < 0) { - return { message: '毛重必须是有效的正数', code: 405 }; + // 毛重必须为正整数(单位 g) + const updateValue = parseInt(value, 10); + if (isNaN(updateValue) || updateValue < 0 || !Number.isInteger(Number(value))) { + return { message: '毛重必须是有效的正整数(单位 g)', code: 405 }; } updateData = { gross_weight: updateValue, @@ -1826,6 +2659,42 @@ class stockStoreService extends Service { update_by: ctx.user.id || ctx.user.username, }; + } else if (method === 'need_recheck') { + // 是否需要复核:Y=需要复核,N=不需要复核 + const updateValue = String(value).trim().toUpperCase(); + if (![ 'Y', 'N' ].includes(updateValue)) { + return { message: '是否需要复核必须是 Y(需要复核)或 N(不需要复核)', code: 405 }; + } + updateData = { + need_recheck: updateValue, + update_at: new Date(), + update_by: ctx.user.id || ctx.user.username, + }; + + } else if (method === 'warning_quantity') { + // 库存预警数量:必须为非负整数 + const updateValue = parseInt(value, 10); + if (isNaN(updateValue) || updateValue < 0 || !Number.isInteger(Number(value))) { + return { message: '库存预警数量必须是非负整数', code: 405 }; + } + updateData = { + warning_quantity: updateValue, + update_at: new Date(), + update_by: ctx.user.id || ctx.user.username, + }; + + } else if (method === 'merge_requirements') { + // 要求是否合并:Y=合并,N=不合并 + const updateValue = String(value).trim().toUpperCase(); + if (![ 'Y', 'N' ].includes(updateValue)) { + return { message: '要求合并必须是 Y(合并)或 N(不合并)', code: 405 }; + } + updateData = { + merge_requirements: updateValue, + update_at: new Date(), + update_by: ctx.user.id || ctx.user.username, + }; + } else if (method === 'managementFlags') { // 管理标识是对象格式,需要更新三个独立字段 if (typeof value !== 'object') { @@ -1872,6 +2741,17 @@ class stockStoreService extends Service { delete_at: null, }, }); + + // 5.1 清除商品详情缓存(bulk update 不触发实例级 afterUpdate hook) + if (affectedRows > 0) { + const detailCacheSvc = ctx.service && ctx.service.systems && ctx.service.systems.stockWarehouse; + if (detailCacheSvc && typeof detailCacheSvc.invalidateStockDetailCache === 'function') { + await Promise.allSettled( + ids.map(stockId => detailCacheSvc.invalidateStockDetailCache(Number(stockId), warehouseId)) + ); + } + } + return { message: `成功修改 ${affectedRows} 条记录`, code: 200, @@ -1895,7 +2775,6 @@ class stockStoreService extends Service { const { ctx, service, } = this; - console.log('条码修改提交', data); const { id, barcodes, @@ -1974,14 +2853,13 @@ class stockStoreService extends Service { const { ctx, } = this; - console.log(data); const { stock_id = null, store_id = null, page = 1, pageSize = 20, item_code = '', item_name = '', } = data || {}; - const warehouseId = ctx.user.store_id; + // 优先使用 systemMethods 层校验后传入的 warehouse_id + const warehouseId = Number(data._warehouseId || 0) || ctx.user.store_id; let barcodes = []; let warehouseStock = null; - console.log(stock_id); let total = 0; if (stock_id) { barcodes = await ctx.model.StockStore.findAll({ @@ -2014,10 +2892,18 @@ class stockStoreService extends Service { } else { const StockWarehouseWhere = { warehouse_id: warehouseId, + deleted_at: null, + is_valid: 'Y', + }; + // 过滤条件必须落在主表(wms_stock_store),include 为 LEFT JOIN 时 + // 条件只会进 ON 子句,无法过滤主表,会导致跨货主/跨仓库数据泄漏。 + const StockStoreWhere = { + warehouse_id: warehouseId, + delete_at: null, + is_valid: 'Y', }; - const StockStoreWhere = {}; if (store_id) { - StockWarehouseWhere.store_id = store_id; + StockStoreWhere.store_id = store_id; } if (item_code) { const processedValue = item_code.split(','); @@ -2041,19 +2927,13 @@ class stockStoreService extends Service { [ total, barcodes ] = await Promise.all([ ctx.model.StockStore.count({ where: StockStoreWhere, - attributes: [ - 'item_code', 'item_name', 'app_key', 'create_from', 'id', 'stock_id', - ], include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', - attributes: [ 'id' ], + attributes: [ 'id', 'store_id' ], where: StockWarehouseWhere, required: false, }], - limit: parseInt(pageSize), - offset: parseInt(offset), - raw: true, }), ctx.model.StockStore.findAll({ where: StockStoreWhere, @@ -2063,7 +2943,7 @@ class stockStoreService extends Service { include: [{ model: ctx.model.StockWarehouse, as: 'warehouse_stock', - attributes: [ 'id' ], + attributes: [ 'id', 'store_id' ], where: StockWarehouseWhere, required: false, }], @@ -2073,22 +2953,33 @@ class stockStoreService extends Service { }), ]); } - console.log('barcodes>>>>', barcodes); + // 批量查询奇门应用名称 + const appKeys = [ ...new Set(barcodes.map(item => item.app_key).filter(Boolean)) ]; + const qimenAppMap = new Map(); + if (appKeys.length > 0) { + const qimenApps = await ctx.model.QimenApp.findAll({ + where: { app_key: appKeys }, + attributes: [ 'app_key', 'name' ], + raw: true, + }); + for (const app of qimenApps) { + qimenAppMap.set(app.app_key, app.name || ''); + } + } + const results = barcodes.map(item => { return { app_key: item.app_key, - create_from: item.create_from == 'qimen' ? '奇门' : 'API', + create_from: item.create_from === 'qimen' ? '奇门' : 'API', id: item.id, - app_name: item.app_key, + app_name: qimenAppMap.get(item.app_key) || item.app_key, item_code: item.item_code, stock_id: item['warehouse_stock.id'], hasBind: !!item.stock_id, item_name: item.item_name, }; }); - console.log('warehouseStock>>>', warehouseStock); - const get_store_id = warehouseStock ? warehouseStock.store_id : barcodes[0]['warehouse_stock.store_id']; - console.log('get_store_id>>>', get_store_id); + const get_store_id = warehouseStock ? warehouseStock.store_id : (barcodes[0] ? barcodes[0]['warehouse_stock.store_id'] : null); return { rows: results, store_id: get_store_id, @@ -2109,7 +3000,7 @@ class stockStoreService extends Service { const storeStock = await ctx.model.StockStore.findOne({ where: { warehouse_id: warehouseId, - deleted_at: null, + delete_at: null, id, }, attributes: [ @@ -2124,6 +3015,7 @@ class stockStoreService extends Service { where: { warehouse_id: warehouseId, deleted_at: null, + is_valid: 'Y', id: warehouse_stock, }, attributes: [ @@ -2145,7 +3037,6 @@ class stockStoreService extends Service { }); return 1; } catch (e) { - console.log(e); throw e; } } @@ -2162,7 +3053,7 @@ class stockStoreService extends Service { const storeStock = await ctx.model.StockStore.findOne({ where: { warehouse_id: warehouseId, - deleted_at: null, + delete_at: null, id, }, attributes: [ @@ -2182,14 +3073,20 @@ class stockStoreService extends Service { }); return 1; } catch (e) { - console.log(e); throw e; } } + /** + * 查询库存商品详情。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.id 库存商品 ID。 + * @return {Promise} 库存商品详情。 + */ async getInfo(data) { const { - ctx, + ctx, service, } = this; const { id, @@ -2199,6 +3096,7 @@ class stockStoreService extends Service { where: { warehouse_id: warehouseId, deleted_at: null, + is_valid: 'Y', id, }, attributes: [ @@ -2208,11 +3106,17 @@ class stockStoreService extends Service { 'is_batch_mgmt', 'is_shelf_life_mgmt', 'is_sn_mgmt', + 'sn_code_rules', + 'need_recheck', + 'goods_code', 'item_code', 'item_name', 'length', 'net_weight', 'packing_requirements', + 'pick_requirements', + 'recheck_requirements', + 'merge_requirements', 'prohibited_id', 'retail_price', 'sku_property', @@ -2223,36 +3127,85 @@ class stockStoreService extends Service { 'width', 'enable_box_spec', 'quantity_per_box', + 'warning_quantity', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'box_volume', + 'inbound_min_days', + 'outbound_min_days', + 'remaining_threshold_days', + 'shelf_life_days', 'store_id', ], raw: true, }); stock.enable_box_spec = !!stock.enable_box_spec; + // SN 码规则统一输出为数组(兼容数据库 JSON 列返回字符串的情况) + stock.sn_code_rules = service.systems.snCodeRule.toRuleList(stock.sn_code_rules); + // 要求合并开关归一化(默认合并);合并时拣货/复核要求统一用打包要求覆盖输出 + stock.packing_requirements = stock.packing_requirements || ''; + stock.merge_requirements = stock.merge_requirements || 'Y'; + stock.pick_requirements = stock.merge_requirements === 'Y' + ? stock.packing_requirements + : (stock.pick_requirements || ''); + stock.recheck_requirements = stock.merge_requirements === 'Y' + ? stock.packing_requirements + : (stock.recheck_requirements || ''); return stock; } + /** + * 更新仓库商品资料,并在启用保质期管理时校验保质期相关字段。 + * + * @param {Object} data 请求体,包含商品主键及待更新字段。 + * @return {Promise} 返回更新后的商品详情。 + */ async saveWarehouseStock(data) { const { ctx, service } = this; const warehouseId = ctx.user.store_id; const { - item_code, store_id, item_name, sku_property, stock_unit, - packing_requirements, length, width, height, volume, + item_code, item_name, goods_code, sku_property, stock_unit, + packing_requirements, pick_requirements, recheck_requirements, merge_requirements, length, width, height, volume, + volume_cm3, volumeCm3, gross_weight, net_weight, tag_price, retail_price, is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, prohibited_id, brand_name, managementFlags, 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, + box_volume_m3, boxVolumeM3, + shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, + need_recheck, + warning_quantity, + sn_code_rules, snCodeRules, } = data; + const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3; + const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3; const prohibited_id_tmp = !prohibited_id ? null : parseInt(prohibited_id); // 1. 参数验证 this.validateSaveParams(data); + // SN 码规则:仅当入参显式带了字段时才更新(支持传 [] 清空),格式非法直接报错 + const rawSnCodeRules = sn_code_rules !== undefined ? sn_code_rules : snCodeRules; + const normalizedSnCodeRules = rawSnCodeRules === undefined + ? undefined + : service.systems.snCodeRule.normalizeRules(rawSnCodeRules); + + 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. 开启事务 @@ -2263,6 +3216,7 @@ class stockStoreService extends Service { where: { id, deleted_at: null, + is_valid: 'Y', warehouse_id: ctx.user.store_id, }, transaction, @@ -2272,17 +3226,34 @@ class stockStoreService extends Service { throw new Error('商品不存在'); } + const hasInputItemCode = Object.prototype.hasOwnProperty.call(data, 'item_code'); + if (hasInputItemCode) { + const itemCodeUniqueResult = await this.checkItemCodeUnique( + id, + item_code, + stock_info.store_id, + stock_info.warehouse_id + ); + if (!itemCodeUniqueResult || !itemCodeUniqueResult.isUnique) { + throw new Error('商品编码已存在,请检查后重试'); + } + } + // 4. 准备更新数据 const updateData = { item_code, item_name, + goods_code, sku_property, stock_unit, packing_requirements, + pick_requirements, + recheck_requirements, + merge_requirements, length, width, height, - volume, + volume: normalizedVolume, gross_weight, net_weight, tag_price, @@ -2291,6 +3262,7 @@ class stockStoreService extends Service { is_sn_mgmt: is_sn_mgmt || false, is_shelf_life_mgmt: is_shelf_life_mgmt || false, is_batch_mgmt: is_batch_mgmt || false, + need_recheck, prohibited_id: prohibited_id_tmp, brand_name, ...(managementFlags && { management_flags: managementFlags }), @@ -2301,20 +3273,25 @@ class stockStoreService extends Service { box_length, box_width, box_height, - box_volume, + box_volume: normalizedBoxVolume, box_remark, + shelf_life_days, + inbound_min_days, + outbound_min_days, + remaining_threshold_days, + warning_quantity, + ...(normalizedSnCodeRules !== undefined && { sn_code_rules: normalizedSnCodeRules }), updated_at: new Date(), }; - console.log('更新数据', updateData); // 5. 清除空值 Object.keys(updateData).forEach(key => { - if (key != 'prohibited_id' && (updateData[key] === undefined || updateData[key] === null)) { + if (key !== 'prohibited_id' && (updateData[key] === undefined || updateData[key] === null)) { delete updateData[key]; } }); // 6. 执行更新 - const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, { + await ctx.model.StockWarehouse.update(updateData, { where: { id, warehouse_id: ctx.user.store_id, @@ -2336,9 +3313,17 @@ class stockStoreService extends Service { warehouseId, }, }); + // 7. 提交事务 await transaction.commit(); + // 7.1 清除商品详情缓存(getStockDetails 缓存,bulk update 不触发实例级 afterUpdate hook) + try { + await service.systems.stockWarehouse.invalidateStockDetailCache(id, warehouseId); + } catch (cacheError) { + ctx.logger.warn(`saveWarehouseStock 清除商品详情缓存失败: ${cacheError.message}`); + } + // 8. 返回更新后的数据 return await this.getInfo({ id }); @@ -2362,23 +3347,30 @@ class stockStoreService extends Service { const { ctx, service } = this; const warehouseId = ctx.user.store_id; const { - item_code, store_id, item_name, sku_property, stock_unit, - packing_requirements, length, width, height, volume, + item_code, store_id, item_name, goods_code, sku_property, stock_unit, + packing_requirements, pick_requirements, recheck_requirements, merge_requirements, length, width, height, volume, gross_weight, net_weight, tag_price, retail_price, is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, prohibited_id, brand_name, managementFlags, 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, barcode, + box_width, box_height, box_volume, box_remark, + need_recheck, + warning_quantity, + sn_code_rules, snCodeRules, } = data; // 1. 参数验证 this.validateSaveParams(data, false); + // SN 码规则:创建时未传则存空数组 + const rawSnCodeRules = sn_code_rules !== undefined ? sn_code_rules : snCodeRules; + const normalizedSnCodeRules = rawSnCodeRules === undefined + ? [] + : service.systems.snCodeRule.normalizeRules(rawSnCodeRules); let checkItemCodeUnique = {}; try { checkItemCodeUnique = await this.checkItemCodeUnique(null, item_code, store_id, warehouseId); } catch (e) { - console.log(e); throw (e); } if (checkItemCodeUnique && !checkItemCodeUnique.isUnique) { @@ -2387,9 +3379,13 @@ class stockStoreService extends Service { const insertData = { item_code, item_name, + goods_code, sku_property, stock_unit, packing_requirements, + pick_requirements, + recheck_requirements, + merge_requirements: merge_requirements || 'Y', length, width, height, @@ -2403,6 +3399,7 @@ class stockStoreService extends Service { is_sn_mgmt: is_sn_mgmt || false, is_shelf_life_mgmt: is_shelf_life_mgmt || false, is_batch_mgmt: is_batch_mgmt || false, + need_recheck: need_recheck || 'Y', prohibited_id, brand_name, ...(managementFlags && { management_flags: managementFlags }), @@ -2410,6 +3407,7 @@ class stockStoreService extends Service { quantity_per_box, box_gross_weight, box_net_weight, + warning_quantity, item_type: 'ZC', level: 'C', store_id, @@ -2419,29 +3417,13 @@ class stockStoreService extends Service { box_height, box_volume, box_remark, + sn_code_rules: normalizedSnCodeRules, updated_at: new Date(), }; const transaction = await ctx.model.transaction(); try { // 2. 开启事务 const createdRecord = await ctx.model.StockWarehouse.create(insertData, transaction); - const barcodes_arr = barcode.split(';'); - const existingFileIds = []; - const toCreate = barcodes_arr.filter(item => !existingFileIds.includes(item)); - // 批量操作 - const promises = []; - console.log('createdRecord', createdRecord.id); - if (toCreate.length > 0) { - const refData = toCreate.map(item => ({ - stock_id: createdRecord.id, - barcode: item, - warehouse_id: warehouseId, - created_at: new Date(), - })); - console.log('refData', refData); - promises.push(ctx.model.StockBarcode.bulkCreate(refData, { transaction })); - await Promise.all(promises); - } await service.systems.operationLog.createOperationLog({ businessType: 'stock', businessId: createdRecord.id, @@ -2457,7 +3439,6 @@ class stockStoreService extends Service { await transaction.commit(); return await this.getInfo({ id: createdRecord.id }); } catch (e) { - console.log(e); if (transaction) { await transaction.rollback(); } @@ -2481,8 +3462,18 @@ class stockStoreService extends Service { throw new Error('启用箱规时,每箱数量必须大于0'); } + // 是否需要复核:仅允许 Y(需要)/ N(不需要) + if (data.need_recheck !== undefined && data.need_recheck !== null && ![ 'Y', 'N' ].includes(String(data.need_recheck).trim())) { + throw new Error('need_recheck 必须是 Y(需要复核)或 N(不需要复核)'); + } + + // 要求是否合并:仅允许 Y(合并)/ N(不合并) + if (data.merge_requirements !== undefined && data.merge_requirements !== null && ![ 'Y', 'N' ].includes(String(data.merge_requirements).trim())) { + throw new Error('merge_requirements 必须是 Y(合并)或 N(不合并)'); + } + // 数值类型验证 - const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ]; + const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight', 'warning_quantity' ]; for (const field of numericFields) { if (data[field] && isNaN(Number(data[field]))) { throw new Error(`${field} 必须是有效的数字`); @@ -2490,48 +3481,60 @@ class stockStoreService extends Service { } } async stockLog() { - + return undefined; } - async checkItemCodeUnique(id, item_code, store_id, warehouse_id) { - const { ctx } = this; + /** + * 校验商品编码在指定仓库与货主维度下是否唯一。 + * @param {number|null} item_id 商品ID(编辑场景用于排除自身) + * @param {string} item_code 商品编码 + * @param {number} owner_id 货主ID + * @param {number} warehouse_id 仓库ID + * @return {Promise<{unique:boolean,isUnique:boolean,message?:string}>} 唯一性校验结果 + */ + async checkItemCodeUnique(item_id, item_code, owner_id, warehouse_id) { + const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; try { - // 检查条码是否被其他仓位使用(排除当前仓位) - let whereId = null; - if (id) { - whereId = { - id: { - [Op.ne]: id, // 排除当前仓位ID - }, + const normalizedItemCode = String(item_code || '').trim(); + const where = { + item_code: normalizedItemCode, + store_id: owner_id, + warehouse_id, + deleted_at: null, + is_valid: 'Y', + }; + + if (item_id) { + where.id = { + [Op.ne]: item_id, }; } - const where = { - [Op.and]: [ - whereId, - { item_code }, - { store_id }, - { warehouse_id }, - { deleted_at: null }, // 未删除的记录 - ], - }; + const space = await ctx.model.StockWarehouse.findOne({ where, attributes: [ 'id' ], }); - // 如果没有找到重复的条码,返回唯一 if (!space) { - return { isUnique: true }; + return { unique: true, isUnique: true }; } - return { isUnique: false, message: '商品编码已被使用' }; + return { unique: false, isUnique: false, message: '商品编码已存在' }; } catch (error) { ctx.logger.error('检查商品编码唯一性失败:', error); - return { isUnique: false, message: '商品编码检测失败' }; + return { unique: false, isUnique: false, message: '商品编码检测失败' }; } } + /** + * 批量删除仓库商品资料(软删除)。 + * 删除前会校验:1) 是否存在库存;2) 是否被待处理订单(step 1/2/3 且未取消)引用。 + * 任一校验不通过的商品会被移入不可删除列表并返回原因。 + * @param {Object} data 请求参数 + * @param {Array} data.ids 待删除的商品ID列表 + * @return {Promise} 删除结果,含 deletedProducts、undeletableProducts、failedIds 及 summary + */ async handleBatchDelete(data) { - const { ctx } = this; + const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; const { ids } = data; @@ -2544,6 +3547,7 @@ class stockStoreService extends Service { [Op.and]: [ { id: { [Op.in]: ids } }, { deleted_at: null }, + { is_valid: 'Y' }, ], }; @@ -2558,11 +3562,9 @@ class stockStoreService extends Service { required: false, // 使用left join,因为可能没有库存记录 }, ], - attributes: [ 'id', 'item_name', 'quantity', 'return_quantity' ], + attributes: [ 'id', 'item_name', 'quantity', 'return_quantity', 'warehouse_id' ], }); - console.log('查询到的商品资料:', JSON.stringify(products, null, 2)); - if (products.length === 0) { return { code: 200, message: '未找到对应的商品资料或已删除', data: [] }; } @@ -2605,9 +3607,6 @@ class stockStoreService extends Service { } }); - console.log('可以删除的商品:', deletableProducts); - console.log('不能删除的商品:', undeletableProducts); - if (deletableProducts.length === 0) { return { code: 405, @@ -2619,6 +3618,111 @@ class stockStoreService extends Service { }; } + // 2.5 检查待处理订单引用:step in [1,2,3] 且 status != 'cancel' 的订单引用了该商品时不允许删除 + const deletableIdSet = new Set(deletableProducts.map(p => p.id)); + // 构建 stockId → warehouseId 映射 + const stockWarehouseMap = new Map(); + for (const product of products) { + if (deletableIdSet.has(product.id)) { + stockWarehouseMap.set(product.id, Number(product.warehouse_id) || 0); + } + } + // 按仓库分组 + const warehouseStockMap = new Map(); + for (const [ stockId, warehouseId ] of stockWarehouseMap) { + if (!warehouseStockMap.has(warehouseId)) { + warehouseStockMap.set(warehouseId, []); + } + warehouseStockMap.get(warehouseId).push(stockId); + } + + const orderReferencedMap = new Map(); // stockId → pendingOrderCount + const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory; + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + + if (orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function' + && orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { + for (const [ warehouseId, stockIds ] of warehouseStockMap) { + if (!warehouseId || stockIds.length === 0) continue; + + try { + const orderItemsModel = await orderItemsFactory.getCurrentModel(warehouseId); + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + + // 查询该仓库下引用了待删除商品的订单明细 + const orderItems = await orderItemsModel.findAll({ + where: { stock_id: { [Op.in]: stockIds } }, + attributes: [ 'stock_id', 'order_id' ], + raw: true, + }); + + if (orderItems.length === 0) continue; + + const orderIds = [ ...new Set(orderItems.map(oi => oi.order_id)) ]; + + // 查询这些订单中处于待处理状态(step 1/2/3 且未取消)的 + const pendingOrders = await orderDeliveryModel.findAll({ + where: { + id: { [Op.in]: orderIds }, + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (pendingOrders.length === 0) continue; + + const pendingOrderIds = new Set(pendingOrders.map(po => po.id)); + + // 统计每个 stock_id 被待处理订单引用的数量 + for (const oi of orderItems) { + if (pendingOrderIds.has(oi.order_id)) { + const sid = oi.stock_id; + orderReferencedMap.set(sid, (orderReferencedMap.get(sid) || 0) + 1); + } + } + } catch (err) { + ctx.logger.warn(`[handleBatchDelete] 检查待处理订单引用失败(仓库${warehouseId}): ${err.message}`); + // 检查失败时不阻塞删除,仅记录日志 + } + } + } + + // 将存在待处理订单引用的商品从可删除列表移至不可删除列表 + if (orderReferencedMap.size > 0) { + const newDeletable = []; + for (const product of deletableProducts) { + const pendingCount = orderReferencedMap.get(product.id) || 0; + if (pendingCount > 0) { + undeletableProducts.push({ + ...product, + reason: `该商品已被 ${pendingCount} 个待处理订单引用,无法删除。请先处理相关订单后再删除。`, + }); + } else { + newDeletable.push(product); + } + } + // 用过滤后的列表替换原可删除列表 + deletableProducts.length = 0; + deletableProducts.push(...newDeletable); + } + + if (deletableProducts.length === 0) { + const blockedReasons = undeletableProducts + .filter(p => p.reason) + .map(p => `${p.name}: ${p.reason}`) + .join(';'); + return { + code: 405, + message: '所有选中的商品均无法删除', + data: { + undeletableProducts, + message: blockedReasons || '所选商品均无法删除', + }, + }; + } + // 3. 执行删除(软删除) const deletableIds = deletableProducts.map(p => p.id); @@ -2693,7 +3797,7 @@ class stockStoreService extends Service { } async deleteUnit(data) { const { id } = data; - const { ctx, app } = this; + const { ctx } = this; const unitExit = await ctx.model.StockUnit.findOne({ where: { id, @@ -2713,7 +3817,7 @@ class stockStoreService extends Service { } async deleteProhibited(data) { const { id } = data; - const { ctx, app } = this; + const { ctx } = this; const unitExit = await ctx.model.ProhibitedType.findOne({ where: { id, @@ -2731,8 +3835,19 @@ class stockStoreService extends Service { }); return { message: '删除成功', code: 200 }; } + /** + * 快捷搜索仓库商品并补全库存管理标记。 + * 支持多词 OR 搜索:使用中英文逗号 `,` `,`、换行 `\n`、回车 `\r` 分隔多个关键词, + * 任意一个词在 item_code、item_name、goods_code 或条形码中命中即返回该商品。 + * @param {Object} data 请求体 + * @param {string} [data.keyword] 搜索关键字,支持多词以逗号/换行分隔进行 OR 匹配 + * @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 } = data; + const { keyword, store_id = null, with_stock = false, is_batch = false } = data; const { ctx, app } = this; const { Op } = app.Sequelize; const warehouseId = ctx.user.store_id; @@ -2741,6 +3856,7 @@ class stockStoreService extends Service { const whereCondition = { warehouse_id: warehouseId, deleted_at: null, + is_valid: 'Y', }; // 如果有传入store_id,则添加store_id条件 @@ -2751,40 +3867,79 @@ class stockStoreService extends Service { // 准备关联查询的条件 const includeConditions = []; - // 如果有搜索关键词,创建搜索条件 + // 如果有搜索关键词,按分隔符拆分为多个词进行 OR 匹配 if (keyword && keyword.trim()) { - const searchKeyword = `%${keyword.trim()}%`; + // 按分隔符拆词:中英文逗号、换行、回车、管道符、空格 + const keywords = keyword + .split(/[,\n\r,\|\s]+/) + .map(k => k.trim()) + .filter(k => k.length > 0); - // 先构建主表的搜索条件 - const stockWarehouseConditions = { - [Op.or]: [ - { item_code: { [Op.like]: searchKeyword } }, - { item_name: { [Op.like]: searchKeyword } }, - { goods_code: { [Op.like]: searchKeyword } }, - ], - }; + if (keywords.length === 1) { + // 单个词,保持原逻辑 + const searchKeyword = `%${keywords[0]}%`; - // 添加条形码关联查询条件 - includeConditions.push({ - model: app.model.StockBarcode, - as: 'barcodes', - attributes: [ 'barcode' ], - required: false, // 使用LEFT JOIN - where: { - barcode: { [Op.like]: searchKeyword }, - }, - }); + const stockWarehouseConditions = { + [Op.or]: [ + { item_code: { [Op.like]: searchKeyword } }, + { item_name: { [Op.like]: searchKeyword } }, + { goods_code: { [Op.like]: searchKeyword } }, + ], + }; - // 合并搜索条件 - whereCondition[Op.or] = [ - stockWarehouseConditions, - // 如果barcodes表有匹配的记录,则也返回该商品 - { - '$barcodes.barcode$': { [Op.like]: searchKeyword }, - }, - ]; - } else { - // 如果没有关键词,也包含barcodes关联(但不需要where条件) + includeConditions.push({ + model: app.model.StockBarcode, + as: 'barcodes', + attributes: [ 'barcode' ], + required: false, + where: { + barcode: { [Op.like]: searchKeyword }, + }, + }); + + whereCondition[Op.or] = [ + stockWarehouseConditions, + { + '$barcodes.barcode$': { [Op.like]: searchKeyword }, + }, + ]; + } else if (keywords.length > 1) { + // 多个词,OR 包装:每个词在 item_code/item_name/goods_code/barcode 任一命中即可 + const stockWarehouseConditions = { + [Op.or]: keywords.flatMap(kw => { + const like = `%${kw}%`; + return [ + { item_code: { [Op.like]: like } }, + { item_name: { [Op.like]: like } }, + { goods_code: { [Op.like]: like } }, + ]; + }), + }; + + includeConditions.push({ + model: app.model.StockBarcode, + as: 'barcodes', + attributes: [ 'barcode' ], + required: false, + where: { + [Op.or]: keywords.map(kw => ({ + barcode: { [Op.like]: `%${kw}%` }, + })), + }, + }); + + whereCondition[Op.or] = [ + stockWarehouseConditions, + ...keywords.map(kw => ({ + '$barcodes.barcode$': { [Op.like]: `%${kw}%` }, + })), + ]; + } + // keywords.length === 0 时不加搜索条件,走 else 分支 + } + + if (!includeConditions.some(c => c.as === 'barcodes')) { + // 如果没有关键词或关键词全为空,也包含 barcodes 关联(但不需要 where 条件) includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', @@ -2792,20 +3947,24 @@ class stockStoreService extends Service { required: false, }); } - includeConditions.push({ - model: app.model.StoreWarehouse, - as: 'store_stock', + includeConditions.push(app.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, attributes: [ 'store_id', 'store_remask' ], - }); + })); // 执行查询 - console.log('查询商品===》'); const results = await app.model.StockWarehouse.findAll({ where: whereCondition, attributes: [ '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', + 'gross_weight', ], order: [[ 'create_at', 'DESC' ]], limit: 50, @@ -2819,10 +3978,128 @@ 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; }); + // 批查商品图片(与 stock.warehouse.list 一致:wms_file_reference + wms_file) + if (formattedResults.length > 0) { + const stockIds = formattedResults.map(r => r.id); + const imageRows = await app.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { [Op.in]: stockIds.map(String) }, + }, + include: [{ + model: app.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + order: [[ 'display_order', 'ASC' ]], + raw: true, + }); + + const imageMap = new Map(); + for (const row of imageRows) { + const sid = Number(row.business_id); + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (!url) continue; + if (!imageMap.has(sid)) imageMap.set(sid, []); + imageMap.get(sid).push(url); + } + + for (const item of formattedResults) { + item.images = imageMap.get(item.id) || []; + } + } + + // with_stock=true 时关联查询库存数据 + if (with_stock && formattedResults.length > 0) { + const stockIds = formattedResults.map(r => r.id); + const storageWhere = { + stock_id: { [Op.in]: stockIds }, + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }; + + const storageRows = await app.model.Storage.findAll({ + where: storageWhere, + attributes: [ + 'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'intercept_locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', + 'inbound_order_no', 'supplier_batch_no', 'created_at', + ], + include: [{ + model: app.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }], + order: [[ 'created_at', 'DESC' ]], + }); + + // 按 stock_id 分组 + const storageMap = new Map(); + for (const row of storageRows) { + const plain = row.get({ plain: true }); + const key = plain.stock_id; + if (!storageMap.has(key)) { + storageMap.set(key, []); + } + storageMap.get(key).push(plain); + } + + for (const item of formattedResults) { + const storageList = storageMap.get(item.id) || []; + + if (is_batch) { + // is_batch=true:逐条批次明细返回,不分组 + item.storage = storageList; + } else { + // is_batch=false(默认):按库位分组汇总 + const mergedMap = new Map(); + for (const s of storageList) { + const spaceKey = s.space_id; + if (mergedMap.has(spaceKey)) { + const existing = mergedMap.get(spaceKey); + existing.quantity += Number(s.quantity) || 0; + existing.locked_quantity += Number(s.locked_quantity) || 0; + existing.intercept_locked_quantity += Number(s.intercept_locked_quantity) || 0; + existing.available_quantity = existing.quantity - existing.locked_quantity + - existing.intercept_locked_quantity; + } else { + const quantity = Number(s.quantity) || 0; + const lockedQuantity = Number(s.locked_quantity) || 0; + const interceptLockedQuantity = Number(s.intercept_locked_quantity) || 0; + mergedMap.set(spaceKey, { + space_id: s.space_id, + inventory_type: s.inventory_type, + quantity, + locked_quantity: lockedQuantity, + intercept_locked_quantity: interceptLockedQuantity, + available_quantity: quantity - lockedQuantity - interceptLockedQuantity, + space: s.space, + }); + } + } + item.storage = Array.from(mergedMap.values()); + } + } + } + return { code: 200, data: formattedResults, @@ -2837,5 +4114,166 @@ class stockStoreService extends Service { }; } } + + /** + * 查询商品的库存明细(storage 表)。 + * @param {Object} data 请求体 + * @param {number} data.stock_id 商品库存ID(stock_warehouse.id) + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 库存明细分页结果 + */ + async getStockDetail(data) { + const { ctx, app } = this; + const warehouseId = ctx.user.store_id; + const { stock_id, pagination = {}, group_by_batch = false } = data; + + if (!stock_id) { + return { code: 0, message: '参数 stock_id 不能为空' }; + } + + try { + // 校验商品归属当前仓库 + const stockItem = await app.model.StockWarehouse.findOne({ + where: { + id: stock_id, + warehouse_id: warehouseId, + deleted_at: null, + is_valid: 'Y', + }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity' ], + raw: true, + }); + + if (!stockItem) { + return { code: 0, message: '商品不存在或不属于当前仓库' }; + } + + const { page = 1, pageSize = 20 } = pagination; + const offset = (page - 1) * pageSize; + + const storageWhere = { + stock_id, + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }; + + if (group_by_batch) { + // 区分批次:按原逻辑返回每一条库存明细 + const { count, rows } = await app.model.Storage.findAndCountAll({ + where: storageWhere, + attributes: [ + 'id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', + 'inbound_order_no', 'supplier_batch_no', 'created_at', + ], + include: [{ + model: app.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }], + order: [[ 'created_at', 'DESC' ]], + offset, + limit: pageSize, + }); + + return { + code: 200, + data: { + stockItem, + storageList: rows, + pagination: { + page, + pageSize, + total: count, + }, + }, + }; + } + + // 不区分批次:按 space_id 合并库存数据 + const allRows = await app.model.Storage.findAll({ + where: storageWhere, + attributes: [ + 'id', 'space_id', 'inventory_type', + 'quantity', 'locked_quantity', 'intercept_locked_quantity', 'created_at', + ], + include: [{ + model: app.model.LocationSpace, + as: 'space', + attributes: [ + 'id', + 'space_code', + 'custom_name', + ], + required: false, + }], + order: [ + [ + 'created_at', + 'DESC', + ], + ], + }); + + // 按 space_id 合并 + const mergedMap = new Map(); + for (const row of allRows) { + const plain = row.get({ plain: true }); + const key = plain.space_id; + if (mergedMap.has(key)) { + const existing = mergedMap.get(key); + existing.quantity += Number(plain.quantity) || 0; + existing.locked_quantity += Number(plain.locked_quantity) || 0; + existing.intercept_locked_quantity += Number(plain.intercept_locked_quantity) || 0; + existing.available_quantity = existing.quantity - existing.locked_quantity + - existing.intercept_locked_quantity; + } else { + const quantity = Number(plain.quantity) || 0; + const lockedQuantity = Number(plain.locked_quantity) || 0; + const interceptLockedQuantity = Number(plain.intercept_locked_quantity) || 0; + mergedMap.set(key, { + id: plain.id, + space_id: plain.space_id, + batch_no: null, + inventory_type: plain.inventory_type, + quantity, + locked_quantity: lockedQuantity, + intercept_locked_quantity: interceptLockedQuantity, + available_quantity: quantity - lockedQuantity - interceptLockedQuantity, + production_date: null, + expiry_date: null, + inbound_time: null, + inbound_order_no: null, + supplier_batch_no: null, + created_at: plain.created_at, + space: plain.space, + }); + } + } + + const mergedList = Array.from(mergedMap.values()); + const total = mergedList.length; + const storageList = mergedList.slice(offset, offset + pageSize); + + return { + code: 200, + data: { + stockItem, + storageList, + pagination: { + page, + pageSize, + total, + }, + }, + }; + } catch (error) { + ctx.logger.error(`查询商品库存明细失败, stock_id: ${stock_id}`, error); + return { code: 0, message: '查询库存明细失败,请稍后重试' }; + } + } } module.exports = stockStoreService; diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js new file mode 100644 index 0000000..93f9891 --- /dev/null +++ b/app/service/systems/stock_transaction.js @@ -0,0 +1,1372 @@ +'use strict'; + +const Service = require('egg').Service; + +class StockTransactionService extends Service { + + /** + * 规范化入库流水的单据字段。 + * + * 约束: + * 1) transaction_type=INBOUND 时,order_id 必须写 null; + * 2) 其他类型保持上游值不变。 + * + * @param {Object} data 流水数据。 + * @param {number|null|undefined} orderId 候选单据ID。 + * @return {number|null} 规范化后的单据ID。 + */ + normalizeInboundOrderId(data = {}, orderId) { + if (data.transaction_type === 'INBOUND') { + return null; + } + return orderId ?? null; + } + + /** + * 判断当前流水是否属于订单出库链路。 + * + * 说明: + * 1) 仅 OUTBOUND 才可能是订单出库; + * 2) 允许上游传入多种 order_type,只要具备订单出库特征均视为订单出库; + * 3) 订单ID合法性由 resolveOutboundOrderReference 统一校验。 + * + * @param {Object} data 流水数据。 + * @return {boolean} 是否为订单出库流水。 + */ + isOrderOutboundTransaction(data = {}) { + if (data.transaction_type !== 'OUTBOUND') { + return false; + } + + const normalizedOrderType = String(data.order_type || '').trim(); + const sourceOrderCodes = String(data.source_order_codes || '').trim(); + const remark = String(data.remark || '').trim(); + + return Boolean( + sourceOrderCodes + || normalizedOrderType === 'STOCK_STORE_OUTBOUND' + || normalizedOrderType === 'ORDER' + || remark === '订单出库' + ); + } + + /** + * 规范化订单出库流水的单据字段。 + * + * 约束: + * 1) order_id 必须是订单主键 ID; + * 2) order_no 必须写订单 source_order_codes。 + * 3) batch_no 必须以订单 wave_no 为准(无 wave_no 时写 null)。 + * + * @param {Object} data 流水数据。 + * @param {Object} options 写入选项。 + * @return {Promise<{orderId: number|null, orderNo: string|null, batchNo: string|null}>} 规范化后的单据字段。 + */ + async resolveOutboundOrderReference(data = {}, options = {}) { + const { ctx } = this; + const isOrderOutbound = this.isOrderOutboundTransaction(data); + + if (!isOrderOutbound) { + return { + orderId: data.order_id ?? null, + orderNo: data.order_no ?? null, + batchNo: data.batch_no ?? null, + }; + } + + const orderId = Number(data.order_id); + if (!Number.isFinite(orderId) || orderId <= 0) { + throw new Error('订单出库流水 order_id 必须为订单主键 id'); + } + + let sourceOrderCodes = String(data.source_order_codes || '').trim(); + + // 兜底查询 source_order_codes(仅当调用方未传入时),用 try-catch 防止拖垮事务 + const orderDeliveryModel = ctx.model && ctx.model.OrderDelivery; + if (!sourceOrderCodes && orderDeliveryModel && typeof orderDeliveryModel.findOne === 'function') { + try { + const orderRow = await orderDeliveryModel.findOne({ + where: { id: orderId }, + attributes: [ 'id', 'source_order_codes' ], + raw: true, + transaction: options.transaction, + }); + if (orderRow) { + sourceOrderCodes = String(orderRow.source_order_codes || '').trim(); + } + } catch (error) { + ctx.logger.warn(`[resolveOutboundOrderReference] 查询订单 source_order_codes 失败,降级跳过: ${error.message}`); + } + } + + if (!sourceOrderCodes) { + throw new Error(`订单出库流水 order_no 必须使用 source_order_codes,订单ID: ${orderId}`); + } + + return { + orderId, + orderNo: sourceOrderCodes, + batchNo: data.batch_no ?? null, + }; + } + + /** + * 统一写入库存流水记录。 + * + * @param {Object} data 流水数据 + * @param {string} data.transaction_type 出入库类型 + * @param {number} data.warehouse_id 仓库ID + * @param {number} data.store_id 货主ID + * @param {number} data.stock_id 商品库存ID + * @param {number} data.quantity 变动数量 + * @param {string} [data.batch_no] 批次号 + * @param {string} [data.order_type] 关联单据类型 + * @param {string} [data.order_no] 关联单据号 + * @param {number} [data.order_id] 关联单据ID + * @param {number} [data.receiving_id] 关联收货单ID + * @param {number} [data.entry_order_id] 关联入库单ID + * @param {string} [data.operator_id] 操作人ID + * @param {string} [data.operator_name] 操作人名称 + * @param {string} [data.remark] 备注 + * @param {number} [data.before_quantity] 变更前总库存数量 + * @param {number} [data.after_quantity] 变更后总库存数量 + * @param {number} [data.before_locked_quantity] 变更前锁定数量 + * @param {number} [data.after_locked_quantity] 变更后锁定数量 + * @param {Date} [data.created_at] 创建时间 + * @param {Object} [options] 写入选项 + * @param {Object} [options.transaction] 数据库事务 + * @return {Promise} 新增的流水记录 + */ + async create(data = {}, options = {}) { + const { ctx } = this; + + if (!options.transaction) { + throw new Error('stockTransaction.create 缺少 transaction,库存流水写入必须在事务中执行'); + } + + const quantity = Number(data.quantity); + if (!data.transaction_type) { + throw new Error('transaction_type 必填'); + } + if (!data.warehouse_id) { + throw new Error('warehouse_id 必填'); + } + if (!data.store_id) { + throw new Error('store_id 必填'); + } + if (!data.stock_id) { + throw new Error('stock_id 必填'); + } + if (!Number.isFinite(quantity) || quantity <= 0) { + throw new Error('quantity 必须为正数'); + } + + const isOrderOutbound = this.isOrderOutboundTransaction(data); + const normalizedOrderReference = await this.resolveOutboundOrderReference(data, options); + const normalizedOrderType = isOrderOutbound ? 'ORDER' : (data.order_type ?? null); + const normalizedBatchNo = isOrderOutbound ? normalizedOrderReference.batchNo : (data.batch_no ?? null); + + const normalizedOrderId = this.normalizeInboundOrderId(data, normalizedOrderReference.orderId); + + const payload = { + transaction_type: data.transaction_type, + warehouse_id: data.warehouse_id, + store_id: data.store_id, + stock_id: data.stock_id, + quantity, + batch_no: normalizedBatchNo, + order_type: normalizedOrderType, + order_no: normalizedOrderReference.orderNo, + order_id: normalizedOrderId, + receiving_id: data.receiving_id ?? null, + entry_order_id: data.entry_order_id ?? null, + operator_id: data.operator_id ?? null, + operator_name: data.operator_name ?? null, + remark: data.remark ?? null, + before_quantity: data.before_quantity ?? null, + after_quantity: data.after_quantity ?? null, + before_locked_quantity: data.before_locked_quantity ?? null, + after_locked_quantity: data.after_locked_quantity ?? null, + created_at: data.created_at || new Date(), + }; + + const row = await ctx.model.StockTransaction.create(payload, options); + + // 订单出入库(收/发)后商品离开静态状态:硬删除静态通知/盘点任务关联记录(失败不影响主流程) + if (data.transaction_type === 'INBOUND' || data.transaction_type === 'OUTBOUND') { + await Promise.all([ + this.clearStaticNoticeByStockId(data.stock_id, options), + this.clearStaticCheckTaskByStockId(data.stock_id, options), + ]); + } + + return row; + } + + /** + * 硬删除指定商品的静态通知记录。 + * + * 商品一旦有新的收/发流水即离开静态状态,历史通知记录不再有意义, + * 因此在流水写入成功后直接物理删除(不走软删)。 + * 清理失败不影响出入库主流程(仅记录 warn)。 + * + * @param {number} stockId 商品库存ID + * @param {Object} [options] 写入选项 + * @param {Object} [options.transaction] 数据库事务(建议与流水写入同一事务) + * @return {Promise} 删除行数(异常时返回 0) + */ + async clearStaticNoticeByStockId(stockId, options = {}) { + const { ctx } = this; + const numericStockId = Number(stockId); + if (!Number.isFinite(numericStockId) || numericStockId <= 0) { + return 0; + } + try { + const noticeModel = ctx.model && ctx.model.StockStaticNotice; + if (!noticeModel) { + return 0; + } + return await noticeModel.destroy({ + where: { stock_id: numericStockId }, + force: true, // 硬删除(paranoid 表需 force 才能物理删除) + ...(options && options.transaction ? { transaction: options.transaction } : {}), + }); + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockTransaction.clearStaticNoticeByStockId] 清理静态通知记录失败 stockId=${numericStockId}: ${err && err.message}` + ); + return 0; + } + } + + /** + * 硬删除指定商品的静态盘点任务关联记录。 + * + * 商品一旦有新的收/发流水即离开静态状态,已创建的盘点任务关联不再有意义, + * 因此在流水写入成功后直接物理删除(不走软删)。 + * 清理失败不影响出入库主流程(仅记录 warn)。 + * + * @param {number} stockId 商品库存ID + * @param {Object} [options] 写入选项 + * @param {Object} [options.transaction] 数据库事务(建议与流水写入同一事务) + * @return {Promise} 删除行数(异常时返回 0) + */ + async clearStaticCheckTaskByStockId(stockId, options = {}) { + const { ctx } = this; + const numericStockId = Number(stockId); + if (!Number.isFinite(numericStockId) || numericStockId <= 0) { + return 0; + } + try { + const taskModel = ctx.model && ctx.model.StockStaticCheckTask; + if (!taskModel) { + return 0; + } + return await taskModel.destroy({ + where: { stock_id: numericStockId }, + force: true, // 硬删除(paranoid 表需 force 才能物理删除) + ...(options && options.transaction ? { transaction: options.transaction } : {}), + }); + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockTransaction.clearStaticCheckTaskByStockId] 清理静态盘点任务关联记录失败 stockId=${numericStockId}: ${err && err.message}` + ); + return 0; + } + } + + /** + * 查询库位维度出入库流水逐条明细(wms_storage_transaction)。 + * 与 stock.transaction.list 形态一致:裸 SQL 列白名单 + COUNT 分页 + 排序白名单, + * 不做聚合,仅查询当前仓库数据,并关联商品信息(stockItem)。 + * @param {Object} [options] 查询选项 + * @param {number} options.warehouseId 仓库ID(必填,由 method 层从当前上下文注入) + * @param {string|Date|null} [options.startTime] 开始时间(闭区间下限,created_at >= startTime) + * @param {string|Date|null} [options.endTime] 结束时间(闭区间上限,created_at <= endTime) + * @param {Array} [options.storeIds] 货主ID数组 + * @param {Array} [options.stockIds] 商品库存ID数组 + * @param {number} [options.spaceId] 库位ID + * @param {string} [options.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode/SKU ID 模糊匹配) + * @param {string} [options.transactionType] 流水类型(INBOUND/OUTBOUND/TRANSFER_OUT/TRANSFER_IN/LOCK/UNLOCK) + * @param {string} [options.orderType] 单据类型 + * @param {string} [options.orderNo] 单据号(模糊匹配) + * @param {string} [options.batchNo] 批次号 + * @param {string} [options.inventoryType] 库存类型(ZP/CC/JS/XS/ZT/DJ/FP) + * @param {string} [options.operatorName] 操作人姓名(模糊匹配) + * @param {number} [options.orderId] 发货单ID + * @param {Object} [options.sort] 排序参数 { sortField, sortOrder } + * @param {Object} [options.pagination] 分页参数 { page, pageSize } + * @return {Promise} { list, pagination } + */ + async list(options = {}) { + const { ctx, app } = this; + const { + warehouseId, + startTime, + endTime, + storeIds: rawStoreIds, + stockIds: rawStockIds, + spaceId, + keyword, + transactionType, + orderType, + orderNo, + batchNo, + inventoryType, + operatorName, + orderId, + sort = {}, + pagination = {}, + } = options; + + if (!warehouseId) { + return { + list: [], + pagination: { page: 1, pageSize: 20, total: 0, totalPages: 0 }, + }; + } + + // keyword 快捷搜索:解析为 stock_id IN 条件,无匹配时直接返回空列表 + let stockIds = Array.isArray(rawStockIds) + ? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + const normalizedKeyword = String(keyword || '').trim(); + if (normalizedKeyword && stockIds.length === 0) { + stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', Number(warehouseId)); + if (stockIds.length === 0) { + return { + list: [], + pagination: { page: 1, pageSize: 20, total: 0, totalPages: 0 }, + }; + } + } + + const { whereSQL, replacements } = this._buildStorageTransactionWhere({ + warehouseId, + startTime, + endTime, + storeIds: rawStoreIds, + stockIds, + spaceId, + transactionType, + orderType, + orderNo, + batchNo, + inventoryType, + operatorName, + orderId, + }); + + // 排序白名单,非法字段回退默认排序(created_at DESC) + const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id', 'space_id' ]); + const sortFieldRaw = String(sort.sortField || 'created_at').trim(); + const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at'; + const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase(); + const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC'; + + // 分页 + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + const offset = (page - 1) * pageSize; + + // 查询总数 + const countResult = await ctx.model.query( + `SELECT COUNT(*) AS total FROM wms_storage_transaction t ${whereSQL}`, + { + replacements, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + const total = countResult && countResult[0] ? Number(countResult[0].total) : 0; + + // 明细白名单:显式列出列名,避免模型整行序列化引入未预期字段 + const rows = await ctx.model.query(` + SELECT + t.id, + t.created_at, + t.transaction_type, + t.warehouse_id, + t.store_id, + t.stock_id, + t.storage_id, + t.space_id, + t.quantity, + t.before_quantity, + t.after_quantity, + t.before_locked_quantity, + t.after_locked_quantity, + t.before_intercept_locked_quantity, + t.after_intercept_locked_quantity, + t.batch_no, + t.inventory_type, + t.order_type, + t.order_no, + t.order_id, + t.source_order_codes, + t.operator_id, + t.operator_name, + t.remark, + sw.id AS sw_id, + sw.item_code AS sw_item_code, + sw.item_name AS sw_item_name, + sw.sku_property AS sw_sku_property, + sw.stock_unit AS sw_stock_unit + FROM wms_storage_transaction t + LEFT JOIN wms_stock_warehouse sw ON sw.id = t.stock_id + ${whereSQL} + ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder} + LIMIT :limit OFFSET :offset + `, { + replacements: { ...replacements, limit: pageSize, offset }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const safeRows = Array.isArray(rows) ? rows : []; + const list = safeRows.map(item => ({ + id: Number(item.id), + created_at: item.created_at ? app.formatDate(item.created_at) : '', + transaction_type: item.transaction_type || '', + warehouse_id: Number(item.warehouse_id) || 0, + store_id: Number(item.store_id) || 0, + stock_id: Number(item.stock_id) || 0, + storage_id: Number(item.storage_id) || 0, + space_id: Number(item.space_id) || 0, + quantity: Number(item.quantity) || 0, + before_quantity: Number(item.before_quantity) || 0, + after_quantity: Number(item.after_quantity) || 0, + before_locked_quantity: Number(item.before_locked_quantity) || 0, + after_locked_quantity: Number(item.after_locked_quantity) || 0, + before_intercept_locked_quantity: Number(item.before_intercept_locked_quantity) || 0, + after_intercept_locked_quantity: Number(item.after_intercept_locked_quantity) || 0, + batch_no: item.batch_no || '', + inventory_type: item.inventory_type || '', + order_type: item.order_type || '', + order_no: item.order_no || '', + order_id: Number(item.order_id) || 0, + source_order_codes: item.source_order_codes || '', + operator_id: item.operator_id || '', + operator_name: item.operator_name || '', + remark: item.remark || '', + stockItem: item.sw_id !== null && item.sw_id !== undefined + ? { + id: Number(item.sw_id) || 0, + item_code: item.sw_item_code || '', + item_name: item.sw_item_name || '', + sku_property: item.sw_sku_property || '', + stock_unit: item.sw_stock_unit || '', + } + : null, + })); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } + + /** + * 组装库位维度流水查询条件白名单(wms_storage_transaction)。 + * 所有条件显式拼装,避免动态 where 注入未知字段;list 与导出共用。 + * @param {Object} params 归一化后的查询参数 + * @param {number} params.warehouseId 仓库ID + * @param {string|Date|null} [params.startTime] 开始时间 + * @param {string|Date|null} [params.endTime] 结束时间 + * @param {Array} [params.storeIds] 货主ID数组 + * @param {Array} [params.stockIds] 商品库存ID数组 + * @param {number} [params.spaceId] 库位ID + * @param {string} [params.transactionType] 流水类型 + * @param {string} [params.orderType] 单据类型 + * @param {string} [params.orderNo] 单据号(模糊) + * @param {string} [params.batchNo] 批次号 + * @param {string} [params.inventoryType] 库存类型 + * @param {string} [params.operatorName] 操作人(模糊) + * @param {number} [params.orderId] 发货单ID + * @return {{whereSQL: string, replacements: Object}} WHERE 子句与查询参数 + */ + _buildStorageTransactionWhere({ + warehouseId, + startTime, + endTime, + storeIds: rawStoreIds, + stockIds, + spaceId, + transactionType, + orderType, + orderNo, + batchNo, + inventoryType, + operatorName, + orderId, + } = {}) { + const whereClauses = [ 't.warehouse_id = :warehouseId' ]; + const replacements = { warehouseId: Number(warehouseId) }; + + if (startTime !== undefined && startTime !== null && startTime !== '') { + const startMs = new Date(startTime).getTime(); + if (!Number.isNaN(startMs)) { + whereClauses.push('t.created_at >= :startTime'); + replacements.startTime = startTime; + } + } + + if (endTime !== undefined && endTime !== null && endTime !== '') { + const endMs = new Date(endTime).getTime(); + if (!Number.isNaN(endMs)) { + whereClauses.push('t.created_at <= :endTime'); + replacements.endTime = endTime; + } + } + + const storeIds = Array.isArray(rawStoreIds) + ? rawStoreIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (storeIds.length > 0) { + whereClauses.push('t.store_id IN (:storeIds)'); + replacements.storeIds = storeIds; + } + + const normalizedStockIds = Array.isArray(stockIds) ? stockIds : []; + if (normalizedStockIds.length > 0) { + whereClauses.push('t.stock_id IN (:stockIds)'); + replacements.stockIds = normalizedStockIds; + } + + const normalizedSpaceId = Number(spaceId); + if (Number.isInteger(normalizedSpaceId) && normalizedSpaceId > 0) { + whereClauses.push('t.space_id = :spaceId'); + replacements.spaceId = normalizedSpaceId; + } + + if (transactionType) { + whereClauses.push('t.transaction_type = :transactionType'); + replacements.transactionType = String(transactionType).trim(); + } + + if (orderType) { + whereClauses.push('t.order_type = :orderType'); + replacements.orderType = String(orderType).trim(); + } + + if (orderNo) { + whereClauses.push('t.order_no LIKE :orderNo'); + replacements.orderNo = `%${String(orderNo).trim()}%`; + } + + if (batchNo) { + whereClauses.push('t.batch_no = :batchNo'); + replacements.batchNo = String(batchNo).trim(); + } + + if (inventoryType) { + whereClauses.push('t.inventory_type = :inventoryType'); + replacements.inventoryType = String(inventoryType).trim(); + } + + if (operatorName) { + whereClauses.push('t.operator_name LIKE :operatorName'); + replacements.operatorName = `%${String(operatorName).trim()}%`; + } + + const normalizedOrderId = Number(orderId); + if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) { + whereClauses.push('t.order_id = :orderId'); + replacements.orderId = normalizedOrderId; + } + + return { + whereSQL: `WHERE ${whereClauses.join(' AND ')}`, + replacements, + }; + } + + /** + * 根据关键字解析匹配的 stock_id 列表。 + * 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。 + * @param {string} keyword 搜索关键字 + * @param {string} primaryDimCol 主维度列名(warehouse_id 或 store_id) + * @param {number} primaryDimVal 主维度值 + * @return {Promise} 匹配的 stock_id 列表 + */ + async _resolveKeywordToStockIds(keyword, primaryDimCol, primaryDimVal) { + const { ctx, app } = this; + const normalizedKeyword = String(keyword || '').trim(); + if (!normalizedKeyword) { + return []; + } + + const likePattern = `%${normalizedKeyword}%`; + const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null; + const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : ''; + + const stockRows = await ctx.model.query(` + SELECT DISTINCT sw.id AS stock_id + FROM wms_stock_warehouse sw + WHERE sw.${primaryDimCol} = :primaryDimVal + AND ( + sw.item_code LIKE :keyword + OR sw.item_name LIKE :keyword + OR sw.goods_code LIKE :keyword + ${extraIdCondition} + ) + `, { + replacements: { primaryDimVal, keyword: likePattern, exactStockId }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const barcodeRows = await ctx.model.query(` + SELECT DISTINCT sb.stock_id + FROM wms_stock_barcodes sb + INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.${primaryDimCol} = :primaryDimVal + WHERE sb.barcode LIKE :keyword + `, { + replacements: { primaryDimVal, keyword: likePattern }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const stockIdSet = new Set(); + for (const row of stockRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + for (const row of barcodeRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + + return [ ...stockIdSet ]; + } + + /** + * 查询商品出入库流水列表(原始记录,不做聚合)。 + * 仓库侧:按 warehouseId 限定;货主侧:按 storeId 限定。 + * @param {Object} options 查询参数 + * @param {number} [options.warehouseId] 仓库ID(仓库侧必传) + * @param {number} [options.storeId] 货主ID(货主侧必传) + * @param {string|Date|null} [options.startTime] 开始时间 + * @param {string|Date|null} [options.endTime] 结束时间 + * @param {Array} [options.storeIds] 货主ID数组(仓库侧筛选) + * @param {Array} [options.warehouseIds] 仓库ID数组(货主侧筛选) + * @param {Array} [options.stockIds] 商品库存ID数组 + * @param {string} [options.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode/SKU ID 模糊匹配) + * @param {string} [options.transactionType] 流水类型 + * @param {string} [options.orderType] 单据类型 + * @param {string} [options.orderNo] 单据号 + * @param {string} [options.batchNo] 批次号 + * @param {number} [options.entryOrderId] 入库单ID + * @param {number} [options.receivingId] 收货单ID + * @param {number} [options.orderId] 发货单ID + * @param {Object} [options.sort] 排序参数 + * @param {Object} [options.pagination] 分页参数 + * @param {string} [options.mode] 模式 'warehouse'/'store',用于 keyword 解析时决定主维度 + * @return {Promise} { list, pagination } + */ + async queryList(options = {}) { + const { ctx, app } = this; + const { + warehouseId, + storeId, + startTime, + endTime, + storeIds, + warehouseIds, + stockIds: rawStockIds, + keyword, + ids, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort = {}, + pagination = {}, + mode = 'warehouse', + } = options; + + // keyword 解析为 stock_ids + let resolvedStockIds = Array.isArray(rawStockIds) + ? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + const normalizedKeyword = String(keyword || '').trim(); + let keywordResolvedEmpty = false; + if (normalizedKeyword && resolvedStockIds.length === 0) { + const isStoreMode = mode === 'store'; + const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id'; + const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId); + if (primaryDimVal > 0) { + resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal); + if (resolvedStockIds.length === 0) { + // keyword 无匹配商品,避免退化为查询全部流水 + keywordResolvedEmpty = true; + } + } + } + + const whereClauses = []; + const replacements = {}; + + if (keywordResolvedEmpty) { + whereClauses.push('1 = 0'); + } + + // 数据范围限定:仓库侧或货主侧 + if (warehouseId !== undefined && warehouseId !== null) { + whereClauses.push('t.warehouse_id = :warehouseId'); + replacements.warehouseId = Number(warehouseId); + } + + if (storeId !== undefined && storeId !== null) { + whereClauses.push('t.store_id = :storeId'); + replacements.storeId = Number(storeId); + } + + // 时间范围 + if (startTime !== undefined && startTime !== null && startTime !== '') { + const startMs = new Date(startTime).getTime(); + if (!Number.isNaN(startMs)) { + whereClauses.push('t.created_at >= :startTime'); + replacements.startTime = startTime; + } + } + + if (endTime !== undefined && endTime !== null && endTime !== '') { + const endMs = new Date(endTime).getTime(); + if (!Number.isNaN(endMs)) { + whereClauses.push('t.created_at <= :endTime'); + replacements.endTime = endTime; + } + } + + // 货主筛选(仓库侧) + const normalizedStoreIds = Array.isArray(storeIds) + ? storeIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedStoreIds.length > 0) { + whereClauses.push('t.store_id IN (:storeIds)'); + replacements.storeIds = normalizedStoreIds; + } + + // 仓库筛选(货主侧) + const normalizedWarehouseIds = Array.isArray(warehouseIds) + ? warehouseIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedWarehouseIds.length > 0) { + whereClauses.push('t.warehouse_id IN (:warehouseIds)'); + replacements.warehouseIds = normalizedWarehouseIds; + } + + // 商品筛选 + const normalizedStockIds = resolvedStockIds; + if (normalizedStockIds.length > 0) { + whereClauses.push('t.stock_id IN (:stockIds)'); + replacements.stockIds = normalizedStockIds; + } + + // 记录ID筛选(精确导出选中记录) + const normalizedIds = Array.isArray(ids) + ? ids.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedIds.length > 0) { + whereClauses.push('t.id IN (:ids)'); + replacements.ids = normalizedIds; + } + + // 流水类型 + if (transactionType) { + whereClauses.push('t.transaction_type = :transactionType'); + replacements.transactionType = String(transactionType).trim(); + } + + // 单据类型 + if (orderType) { + whereClauses.push('t.order_type = :orderType'); + replacements.orderType = String(orderType).trim(); + } + + // 单据号(模糊匹配) + if (orderNo) { + whereClauses.push('t.order_no LIKE :orderNo'); + replacements.orderNo = `%${String(orderNo).trim()}%`; + } + + // 批次号 + if (batchNo) { + whereClauses.push('t.batch_no = :batchNo'); + replacements.batchNo = String(batchNo).trim(); + } + + // 入库单ID + if (entryOrderId !== undefined && entryOrderId !== null) { + const eid = Number(entryOrderId); + if (Number.isInteger(eid) && eid > 0) { + whereClauses.push('t.entry_order_id = :entryOrderId'); + replacements.entryOrderId = eid; + } + } + + // 收货单ID + if (receivingId !== undefined && receivingId !== null) { + const rid = Number(receivingId); + if (Number.isInteger(rid) && rid > 0) { + whereClauses.push('t.receiving_id = :receivingId'); + replacements.receivingId = rid; + } + } + + // 发货单ID + if (orderId !== undefined && orderId !== null) { + const oid = Number(orderId); + if (Number.isInteger(oid) && oid > 0) { + whereClauses.push('t.order_id = :orderId'); + replacements.orderId = oid; + } + } + + const whereSQL = whereClauses.length > 0 + ? `WHERE ${whereClauses.join(' AND ')}` + : ''; + + // 排序 + const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id' ]); + const sortFieldRaw = String(sort.sortField || 'created_at').trim(); + const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at'; + const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase(); + const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC'; + + // 分页 + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + const offset = (page - 1) * pageSize; + + // 查询总数 + const countResult = await ctx.model.query( + `SELECT COUNT(*) AS total FROM wms_stock_transaction t ${whereSQL}`, + { + replacements, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + const total = countResult && countResult[0] ? Number(countResult[0].total) : 0; + + // 查询列表 + const rows = await ctx.model.query( + `SELECT + t.id, + t.created_at, + t.transaction_type, + t.warehouse_id, + t.store_id, + t.stock_id, + t.quantity, + t.before_quantity, + t.after_quantity, + t.before_locked_quantity, + t.after_locked_quantity, + t.batch_no, + t.order_type, + t.order_no, + t.order_id, + t.receiving_id, + t.entry_order_id, + t.operator_name, + t.remark + FROM wms_stock_transaction t + ${whereSQL} + ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder} + LIMIT :limit OFFSET :offset + `, + { + replacements: { ...replacements, limit: pageSize, offset }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + const safeRows = Array.isArray(rows) ? rows : []; + const list = safeRows.map(item => ({ + id: Number(item.id), + created_at: item.created_at ? app.formatDate(item.created_at) : '', + transaction_type: item.transaction_type || '', + warehouse_id: Number(item.warehouse_id) || 0, + store_id: Number(item.store_id) || 0, + stock_id: Number(item.stock_id) || 0, + quantity: Number(item.quantity) || 0, + before_quantity: Number(item.before_quantity) || 0, + after_quantity: Number(item.after_quantity) || 0, + before_locked_quantity: Number(item.before_locked_quantity) || 0, + after_locked_quantity: Number(item.after_locked_quantity) || 0, + batch_no: item.batch_no || '', + order_type: item.order_type || '', + order_no: item.order_no || '', + order_id: Number(item.order_id) || 0, + receiving_id: Number(item.receiving_id) || 0, + entry_order_id: Number(item.entry_order_id) || 0, + operator_name: item.operator_name || '', + remark: item.remark || '', + })); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } + + /** + * 导出商品出入库流水列表为 Excel。 + * 与 queryList 使用相同的查询条件,但不分页(导出上限 50000 条)。 + * @param {Object} options 查询参数(与 queryList 一致,忽略 pagination) + * @param {string} [options.mode] 导出模式:'warehouse' 仓库侧 / 'store' 货主侧 + * @return {Promise} Excel 导出结果 { url, filename } + */ + async exportList(options = {}) { + const { ctx, app } = this; + const { + warehouseId, + storeId, + startTime, + endTime, + storeIds, + warehouseIds, + stockIds: rawStockIds, + keyword, + ids, + transactionType, + orderType, + orderNo, + batchNo, + entryOrderId, + receivingId, + orderId, + sort = {}, + mode = 'warehouse', + } = options; + + // keyword 解析为 stock_ids + let resolvedStockIds = Array.isArray(rawStockIds) + ? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + const normalizedKeyword = String(keyword || '').trim(); + let keywordResolvedEmpty = false; + if (normalizedKeyword && resolvedStockIds.length === 0) { + const isStoreMode = mode === 'store'; + const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id'; + const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId); + if (primaryDimVal > 0) { + resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal); + if (resolvedStockIds.length === 0) { + // keyword 无匹配商品,避免退化为导出全部流水 + keywordResolvedEmpty = true; + } + } + } + + const isStoreMode = mode === 'store'; + const whereClauses = []; + const replacements = {}; + + if (keywordResolvedEmpty) { + whereClauses.push('1 = 0'); + } + + // 数据范围限定 + if (warehouseId !== undefined && warehouseId !== null) { + whereClauses.push('t.warehouse_id = :warehouseId'); + replacements.warehouseId = Number(warehouseId); + } + + if (storeId !== undefined && storeId !== null) { + whereClauses.push('t.store_id = :storeId'); + replacements.storeId = Number(storeId); + } + + if (startTime !== undefined && startTime !== null && startTime !== '') { + const startMs = new Date(startTime).getTime(); + if (!Number.isNaN(startMs)) { + whereClauses.push('t.created_at >= :startTime'); + replacements.startTime = startTime; + } + } + + if (endTime !== undefined && endTime !== null && endTime !== '') { + const endMs = new Date(endTime).getTime(); + if (!Number.isNaN(endMs)) { + whereClauses.push('t.created_at <= :endTime'); + replacements.endTime = endTime; + } + } + + const normalizedStoreIds = Array.isArray(storeIds) + ? storeIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedStoreIds.length > 0) { + whereClauses.push('t.store_id IN (:storeIds)'); + replacements.storeIds = normalizedStoreIds; + } + + const normalizedWarehouseIds = Array.isArray(warehouseIds) + ? warehouseIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedWarehouseIds.length > 0) { + whereClauses.push('t.warehouse_id IN (:warehouseIds)'); + replacements.warehouseIds = normalizedWarehouseIds; + } + + const normalizedStockIds = resolvedStockIds; + if (normalizedStockIds.length > 0) { + whereClauses.push('t.stock_id IN (:stockIds)'); + replacements.stockIds = normalizedStockIds; + } + + // 记录ID筛选(精确导出选中记录) + const normalizedIds = Array.isArray(ids) + ? ids.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (normalizedIds.length > 0) { + whereClauses.push('t.id IN (:ids)'); + replacements.ids = normalizedIds; + } + + if (transactionType) { + whereClauses.push('t.transaction_type = :transactionType'); + replacements.transactionType = String(transactionType).trim(); + } + + if (orderType) { + whereClauses.push('t.order_type = :orderType'); + replacements.orderType = String(orderType).trim(); + } + + if (orderNo) { + whereClauses.push('t.order_no LIKE :orderNo'); + replacements.orderNo = `%${String(orderNo).trim()}%`; + } + + if (batchNo) { + whereClauses.push('t.batch_no = :batchNo'); + replacements.batchNo = String(batchNo).trim(); + } + + if (entryOrderId !== undefined && entryOrderId !== null) { + const eid = Number(entryOrderId); + if (Number.isInteger(eid) && eid > 0) { + whereClauses.push('t.entry_order_id = :entryOrderId'); + replacements.entryOrderId = eid; + } + } + + if (receivingId !== undefined && receivingId !== null) { + const rid = Number(receivingId); + if (Number.isInteger(rid) && rid > 0) { + whereClauses.push('t.receiving_id = :receivingId'); + replacements.receivingId = rid; + } + } + + if (orderId !== undefined && orderId !== null) { + const oid = Number(orderId); + if (Number.isInteger(oid) && oid > 0) { + whereClauses.push('t.order_id = :orderId'); + replacements.orderId = oid; + } + } + + const whereSQL = whereClauses.length > 0 + ? `WHERE ${whereClauses.join(' AND ')}` + : ''; + + const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id' ]); + const sortFieldRaw = String(sort.sortField || 'created_at').trim(); + const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at'; + const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase(); + const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC'; + + const EXPORT_MAX = 50000; + const rows = await ctx.model.query( + `SELECT + t.id, + t.created_at, + t.transaction_type, + t.warehouse_id, + t.store_id, + t.stock_id, + t.quantity, + t.before_quantity, + t.after_quantity, + t.before_locked_quantity, + t.after_locked_quantity, + t.batch_no, + t.order_type, + t.order_no, + t.order_id, + t.receiving_id, + t.entry_order_id, + t.operator_name, + t.remark + FROM wms_stock_transaction t + ${whereSQL} + ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder} + LIMIT ${EXPORT_MAX} + `, + { + replacements, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + + const safeRows = Array.isArray(rows) ? rows : []; + const excelRows = safeRows.map((item, index) => { + const qty = Number(item.quantity) || 0; + const beforeQty = Number(item.before_quantity) || 0; + const afterQty = Number(item.after_quantity) || 0; + const beforeLocked = Number(item.before_locked_quantity) || 0; + const afterLocked = Number(item.after_locked_quantity) || 0; + const lockedChange = afterLocked - beforeLocked; + + return { + 序号: index + 1, + 创建时间: item.created_at ? app.formatDate(item.created_at) : '', + 流水类型: item.transaction_type || '', + 仓库ID: Number(item.warehouse_id) || 0, + 货主ID: Number(item.store_id) || 0, + 商品ID: Number(item.stock_id) || 0, + 库存变动量: qty, + 库存变更前: beforeQty, + 库存变更后: afterQty, + 锁定变动量: lockedChange, + 锁定变更前: beforeLocked, + 锁定变更后: afterLocked, + 批次号: item.batch_no || '', + 单据类型: item.order_type || '', + 单据号: item.order_no || '', + 收货单ID: Number(item.receiving_id) || 0, + 入库单ID: Number(item.entry_order_id) || 0, + 发货单ID: Number(item.order_id) || 0, + 操作人: item.operator_name || '', + 备注: item.remark || '', + }; + }); + + const titleSuffix = isStoreMode ? '货主侧' : '仓库侧'; + const warehouseIdForPath = warehouseId || storeId || 'unknown'; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: `商品流水_${titleSuffix}_${warehouseIdForPath}_${Date.now()}.xlsx`, + dir: `exports/stock/transaction/${warehouseIdForPath}`, + category: 'document', + sheets: [ + { + name: '商品流水', + columns: [ + { header: '序号', key: '序号' }, + { header: '创建时间', key: '创建时间' }, + { header: '流水类型', key: '流水类型' }, + { header: '仓库ID', key: '仓库ID' }, + { header: '货主ID', key: '货主ID' }, + { header: '商品ID', key: '商品ID' }, + { header: '库存变动量', key: '库存变动量' }, + { header: '库存变更前', key: '库存变更前' }, + { header: '库存变更后', key: '库存变更后' }, + { header: '锁定变动量', key: '锁定变动量' }, + { header: '锁定变更前', key: '锁定变更前' }, + { header: '锁定变更后', key: '锁定变更后' }, + { header: '批次号', key: '批次号' }, + { header: '单据类型', key: '单据类型' }, + { header: '单据号', key: '单据号' }, + { header: '收货单ID', key: '收货单ID' }, + { header: '入库单ID', key: '入库单ID' }, + { header: '发货单ID', key: '发货单ID' }, + { header: '操作人', key: '操作人' }, + { header: '备注', key: '备注' }, + ], + rows: excelRows, + }, + ], + }); + } + + /** + * 导出库位维度出入库流水明细为 Excel(wms_storage_transaction)。 + * 与 list 使用相同查询条件,但不分页(导出上限 50000 条)。 + * @param {Object} options 查询参数(与 list 一致,忽略 pagination) + * @return {Promise} Excel 导出结果 { url, filename } + */ + async exportStorageList(options = {}) { + const { ctx, app } = this; + const { + warehouseId, + startTime, + endTime, + storeIds: rawStoreIds, + stockIds: rawStockIds, + spaceId, + keyword, + transactionType, + orderType, + orderNo, + batchNo, + inventoryType, + operatorName, + orderId, + sort = {}, + } = options; + + // keyword 快捷搜索:解析为 stock_id IN 条件,无匹配时导出空表 + let stockIds = Array.isArray(rawStockIds) + ? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + const normalizedKeyword = String(keyword || '').trim(); + let keywordResolvedEmpty = false; + if (normalizedKeyword && stockIds.length === 0) { + stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', Number(warehouseId)); + if (stockIds.length === 0) { + keywordResolvedEmpty = true; + } + } + + let whereSQL; + let replacements; + if (keywordResolvedEmpty) { + whereSQL = 'WHERE 1 = 0'; + replacements = {}; + } else { + ({ whereSQL, replacements } = this._buildStorageTransactionWhere({ + warehouseId, + startTime, + endTime, + storeIds: rawStoreIds, + stockIds, + spaceId, + transactionType, + orderType, + orderNo, + batchNo, + inventoryType, + operatorName, + orderId, + })); + } + + // 排序白名单,与 list 一致 + const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id', 'space_id' ]); + const sortFieldRaw = String(sort.sortField || 'created_at').trim(); + const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at'; + const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase(); + const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC'; + + const EXPORT_MAX = 50000; + const rows = await ctx.model.query(` + SELECT + t.id, + t.created_at, + t.transaction_type, + t.warehouse_id, + t.store_id, + t.stock_id, + t.storage_id, + t.space_id, + t.quantity, + t.before_quantity, + t.after_quantity, + t.before_locked_quantity, + t.after_locked_quantity, + t.before_intercept_locked_quantity, + t.after_intercept_locked_quantity, + t.batch_no, + t.inventory_type, + t.order_type, + t.order_no, + t.order_id, + t.source_order_codes, + t.operator_id, + t.operator_name, + t.remark + FROM wms_storage_transaction t + ${whereSQL} + ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder} + LIMIT ${EXPORT_MAX} + `, { + replacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const safeRows = Array.isArray(rows) ? rows : []; + const excelRows = safeRows.map((item, index) => ({ + 序号: index + 1, + 创建时间: item.created_at ? app.formatDate(item.created_at) : '', + 流水类型: item.transaction_type || '', + 仓库ID: Number(item.warehouse_id) || 0, + 货主ID: Number(item.store_id) || 0, + 商品ID: Number(item.stock_id) || 0, + 库位库存ID: Number(item.storage_id) || 0, + 库位ID: Number(item.space_id) || 0, + 库存变动量: Number(item.quantity) || 0, + 库存变更前: Number(item.before_quantity) || 0, + 库存变更后: Number(item.after_quantity) || 0, + 锁定变更前: Number(item.before_locked_quantity) || 0, + 锁定变更后: Number(item.after_locked_quantity) || 0, + 拦截锁定变更前: Number(item.before_intercept_locked_quantity) || 0, + 拦截锁定变更后: Number(item.after_intercept_locked_quantity) || 0, + 批次号: item.batch_no || '', + 库存类型: item.inventory_type || '', + 单据类型: item.order_type || '', + 单据号: item.order_no || '', + 发货单ID: Number(item.order_id) || 0, + 来源订单号: item.source_order_codes || '', + 操作人ID: item.operator_id || '', + 操作人: item.operator_name || '', + 备注: item.remark || '', + })); + + const warehouseIdForPath = Number(warehouseId) || 'unknown'; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: `库位流水_${warehouseIdForPath}_${Date.now()}.xlsx`, + dir: `exports/storage/transaction/${warehouseIdForPath}`, + category: 'document', + sheets: [ + { + name: '库位流水', + columns: [ + { header: '序号', key: '序号' }, + { header: '创建时间', key: '创建时间' }, + { header: '流水类型', key: '流水类型' }, + { header: '仓库ID', key: '仓库ID' }, + { header: '货主ID', key: '货主ID' }, + { header: '商品ID', key: '商品ID' }, + { header: '库位库存ID', key: '库位库存ID' }, + { header: '库位ID', key: '库位ID' }, + { header: '库存变动量', key: '库存变动量' }, + { header: '库存变更前', key: '库存变更前' }, + { header: '库存变更后', key: '库存变更后' }, + { header: '锁定变更前', key: '锁定变更前' }, + { header: '锁定变更后', key: '锁定变更后' }, + { header: '拦截锁定变更前', key: '拦截锁定变更前' }, + { header: '拦截锁定变更后', key: '拦截锁定变更后' }, + { header: '批次号', key: '批次号' }, + { header: '库存类型', key: '库存类型' }, + { header: '单据类型', key: '单据类型' }, + { header: '单据号', key: '单据号' }, + { header: '发货单ID', key: '发货单ID' }, + { header: '来源订单号', key: '来源订单号' }, + { header: '操作人ID', key: '操作人ID' }, + { header: '操作人', key: '操作人' }, + { header: '备注', key: '备注' }, + ], + rows: excelRows, + }, + ], + }); + } +} + +module.exports = StockTransactionService; diff --git a/app/service/systems/stock_warehouse.js b/app/service/systems/stock_warehouse.js new file mode 100644 index 0000000..69100bd --- /dev/null +++ b/app/service/systems/stock_warehouse.js @@ -0,0 +1,481 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 仓库商品详情缓存的 key 前缀模板。 + * 最终 key 格式:cache:stock_detail:{warehouseId}:{stockId} + */ +const STOCK_DETAIL_CACHE_KEY_PREFIX = 'cache:stock_detail'; +/** 仓库商品详情缓存默认 TTL(秒) */ +const DEFAULT_STOCK_DETAIL_CACHE_TTL = 300; +/** 缓存读取并发批大小 */ +const CACHE_READ_BATCH_SIZE = 200; +/** 缓存写入并发批大小 */ +const CACHE_WRITE_BATCH_SIZE = 100; + +class StockWarehouseService extends Service { + /** + * 构建仓库商品详情缓存的 Redis key。 + * @param {number} warehouseId 仓库ID + * @param {number} stockId 仓库商品ID + * @return {string} 缓存 key + */ + _buildStockDetailCacheKey(warehouseId, stockId) { + return `${STOCK_DETAIL_CACHE_KEY_PREFIX}:${warehouseId}:${stockId}`; + } + + /** + * 批量获取仓库商品详情(带缓存)。 + * 先按 stockId 逐个查缓存,未命中的批量查数据库, + * 然后将数据库结果写入缓存后合并返回。 + * 作为通用公共服务,所有模块均可调用。 + * + * @param {number[]} stockIds 要查询的 StockWarehouse ID 列表 + * @param {Object} [options={}] 选项 + * @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id) + * @param {number} [options.cacheTTL=300] 缓存过期时间(秒) + * @return {Promise}>>} 商品详情列表 + */ + async getStockDetails(stockIds, options = {}) { + const { ctx, app } = this; + const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options; + // 用 !== undefined 代替 != null:显式传 null 表示跳过 warehouse 过滤(如货主侧查询) + const warehouseId = options.warehouseId !== undefined ? options.warehouseId : ctx.user.store_id; + + if (!Array.isArray(stockIds) || stockIds.length === 0) { + return []; + } + + const uniqueStockIds = [ ...new Set(stockIds.map(id => Number(id))) ]; + const cacheHits = new Map(); + const missedStockIds = []; + + // 第一步:分批并发查缓存(避免逐个串行 await 叠加 N 次 Redis 往返延迟) + for (let i = 0; i < uniqueStockIds.length; i += CACHE_READ_BATCH_SIZE) { + const batch = uniqueStockIds.slice(i, i + CACHE_READ_BATCH_SIZE); + const batchResults = await Promise.all(batch.map(async stockId => { + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + const cached = await app.getCacheAsync(cacheKey); + return { stockId, cached, hit: cached !== null && cached !== undefined }; + } catch { + // 缓存读取异常时降级为查数据库 + return { stockId, cached: null, hit: false }; + } + })); + for (const item of batchResults) { + if (item.hit) { + cacheHits.set(item.stockId, item.cached); + } else { + missedStockIds.push(item.stockId); + } + } + } + + // 第二步:批量查数据库(只查未命中的 stockId) + /** @type {Map} */ + const dbResults = new Map(); + if (missedStockIds.length > 0) { + const stockWhere = { id: { [app.Sequelize.Op.in]: missedStockIds }, is_valid: 'Y' }; + if (warehouseId != null) { + stockWhere.warehouse_id = warehouseId; + } + + // 并行查询三表:库存主表、条码、图片(避免 N×M 笛卡尔积膨胀,在应用层做 join) + const [ stockRows, barcodeRows, imageRows ] = await Promise.all([ + ctx.model.StockWarehouse.findAll({ + where: stockWhere, + attributes: [ + 'id', 'item_code', 'item_name', 'sku_property', + 'quantity', 'locked_quantity', 'is_batch_mgmt', + 'is_shelf_life_mgmt', 'is_images', 'need_recheck', + 'store_id', 'packing_requirements', 'pick_requirements', + 'recheck_requirements', 'merge_requirements', 'stock_unit', + ], + raw: true, + }), + ctx.model.StockBarcode.findAll({ + where: { stock_id: { [app.Sequelize.Op.in]: missedStockIds } }, + attributes: [ 'id', 'barcode', 'stock_id' ], + raw: true, + }), + ctx.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { [app.Sequelize.Op.in]: missedStockIds.map(String) }, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + order: [[ 'display_order', 'ASC' ]], + raw: true, + }), + ]); + + // 按 stock_id 分组条码 + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const sid = row.stock_id; + if (!barcodeMap.has(sid)) { + barcodeMap.set(sid, []); + } + barcodeMap.get(sid).push({ + id: row.id, + barcode: row.barcode, + }); + } + + // 按 business_id(即 stock_id)分组图片URL + const imageUrlMap = new Map(); + for (const row of imageRows) { + const sid = Number(row.business_id); + if (!imageUrlMap.has(sid)) { + imageUrlMap.set(sid, []); + } + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (url) { + imageUrlMap.get(sid).push(url); + } + } + + // 组装每个 stock 的完整详情,并收集缓存写入任务 + const cacheWriteTasks = []; + for (const row of stockRows) { + const detail = { + id: row.id, + item_code: row.item_code, + item_name: row.item_name, + sku_property: row.sku_property || '', + quantity: row.quantity || 0, + locked_quantity: row.locked_quantity || 0, + is_batch_mgmt: row.is_batch_mgmt || 'N', + is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N', + is_images: row.is_images || 'N', + need_recheck: row.need_recheck || 'Y', + store_id: row.store_id != null ? Number(row.store_id) : 0, + packing_requirements: row.packing_requirements || '', + pick_requirements: (row.merge_requirements || 'Y') === 'Y' + ? (row.packing_requirements || '') + : (row.pick_requirements || ''), + recheck_requirements: (row.merge_requirements || 'Y') === 'Y' + ? (row.packing_requirements || '') + : (row.recheck_requirements || ''), + merge_requirements: row.merge_requirements || 'Y', + stock_unit: row.stock_unit || '', + image_url: imageUrlMap.get(row.id) || [], + barcodes: barcodeMap.get(row.id) || [], + }; + dbResults.set(row.id, detail); + + // 第三步:写入缓存(收集任务,稍后统一分批并发执行) + cacheWriteTasks.push({ + key: this._buildStockDetailCacheKey(warehouseId, row.id), + value: detail, + ttl: cacheTTL, + }); + } + + // 对于数据库中也不存在的 stockId,写入空标记防止缓存穿透 + for (const stockId of missedStockIds) { + if (!dbResults.has(stockId)) { + cacheWriteTasks.push({ + key: this._buildStockDetailCacheKey(warehouseId, stockId), + value: null, + // 用较短的 TTL 缓存空结果,避免缓存穿透 + ttl: Math.min(cacheTTL, 60), + }); + } + } + + // 分批并发写缓存(缓存写入失败不影响主流程) + for (let i = 0; i < cacheWriteTasks.length; i += CACHE_WRITE_BATCH_SIZE) { + const batch = cacheWriteTasks.slice(i, i + CACHE_WRITE_BATCH_SIZE); + await Promise.all(batch.map(task => app.setCacheAsync(task.key, task.value, task.ttl).catch(() => {}))); + } + } + + // 第四步:合并缓存命中 + 数据库结果,保持原始 stockIds 顺序 + const result = []; + for (const stockId of uniqueStockIds) { + if (cacheHits.has(stockId)) { + const cached = cacheHits.get(stockId); + // 空标记(防穿透缓存)跳过 + if (cached !== null && cached !== undefined) { + // 兼容旧缓存格式:image_url 可能是字符串,统一转为数组 + if (cached && typeof cached.image_url === 'string') { + cached.image_url = cached.image_url ? [ cached.image_url ] : []; + } + if (cached && !Array.isArray(cached.image_url)) { + cached.image_url = []; + } + // 兼容旧缓存:无 need_recheck 时补默认(需要复核) + if (cached && cached.need_recheck == null) { + cached.need_recheck = 'Y'; + } + // 兼容旧缓存:无要求合并开关时按默认合并处理;无拣货/复核要求时按合并规则回退为打包要求 + if (cached && cached.merge_requirements == null) { + cached.merge_requirements = 'Y'; + } + if (cached && cached.pick_requirements == null) { + cached.pick_requirements = (cached.merge_requirements || 'Y') === 'Y' + ? (cached.packing_requirements || '') + : ''; + } + if (cached && cached.recheck_requirements == null) { + cached.recheck_requirements = (cached.merge_requirements || 'Y') === 'Y' + ? (cached.packing_requirements || '') + : ''; + } + result.push(cached); + } + } else if (dbResults.has(stockId)) { + result.push(dbResults.get(stockId)); + } + } + + return result; + } + + /** + * 使指定仓库商品的详情缓存失效。 + * 在商品资料更新、图片变更、条码变更时调用。 + * + * @param {number} stockId 仓库商品ID + * @param {number} warehouseId 仓库ID + * @return {Promise} + */ + async invalidateStockDetailCache(stockId, warehouseId) { + const { app } = this; + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + await app.delCacheAsync(cacheKey); + } catch { + // 删除缓存失败不影响主流程 + } + } + + /** + * 读取商品库存预警数量(内部方法)。 + * + * 优先级: + * 1. 商品单独设置了预警数量(warning_quantity > 0)→ 取商品设置数; + * 2. 货主(stock.store_id 对应 wms_store)开启库存预警(stock_warning_enabled) + * 且配置了预警数量(stock_warning_quantity > 0)→ 取货主设置数; + * 3. 以上均不满足 → 返回 0(不预警)。 + * + * @param {number|string} stockId 仓库商品ID(wms_stock_warehouse.id)。 + * @return {Promise} 库存预警数量(非负整数),读取异常时返回 0。 + */ + async getStockWarningQuantity(stockId) { + const { ctx } = this; + const normalizedStockId = Number(stockId || 0); + if (!Number.isFinite(normalizedStockId) || normalizedStockId <= 0) { + return 0; + } + + try { + const stockModel = ctx.model && ctx.model.StockWarehouse; + if (!stockModel || typeof stockModel.findOne !== 'function') { + return 0; + } + + const stock = await stockModel.findOne({ + where: { id: normalizedStockId, is_valid: 'Y', deleted_at: null }, + attributes: [ 'id', 'store_id', 'warning_quantity' ], + raw: true, + }); + if (!stock) { + return 0; + } + + // 商品单独设置优先 + const productWarningQuantity = Number(stock.warning_quantity || 0); + if (Number.isInteger(productWarningQuantity) && productWarningQuantity > 0) { + return productWarningQuantity; + } + + // 货主配置:开启且数量 > 0 才生效 + const storeId = Number(stock.store_id || 0); + if (storeId > 0) { + const storeModel = ctx.model && ctx.model.Store; + if (storeModel && typeof storeModel.findByPk === 'function') { + const store = await storeModel.findByPk(storeId, { + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + const subjectConfig = store && store.subject_config + ? store.subject_config + : {}; + const enabled = subjectConfig.stock_warning_enabled === true + || subjectConfig.stock_warning_enabled === 1 + || String(subjectConfig.stock_warning_enabled || '').trim().toLowerCase() === 'true'; + const storeWarningQuantity = Number(subjectConfig.stock_warning_quantity || 0); + if (enabled && Number.isInteger(storeWarningQuantity) && storeWarningQuantity > 0) { + return storeWarningQuantity; + } + } + } + + return 0; + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockWarehouse.getStockWarningQuantity] 读取库存预警数量失败 stockId=${normalizedStockId}: ${err && err.message}` + ); + return 0; + } + } + + /** + * 查询静态商品列表(仓库级)。 + * + * 静态判定:商品最后一个收(INBOUND)/发(OUTBOUND)流水时间超过阈值小时数 + * 即视为进入静态;无收发流水记录的商品以创建时间(create_at)为基准。 + * 阈值优先取入参 hours,缺省读仓库配置 subject_config.stock_static_hours(默认 168 小时)。 + * + * @param {Object} [options={}] 选项。 + * @param {number} [options.warehouseId] 仓库ID,缺省取 ctx.user.store_id。 + * @param {number} [options.hours] 静态时间阈值(小时),缺省读仓库配置。 + * @param {number} [options.page=1] 页码。 + * @param {number} [options.pageSize=20] 每页条数。 + * @return {Promise<{list: Array, pagination: {page:number, pageSize:number, total:number, totalPages:number}}>} + * list 每项含 id/item_code/item_name/sku_property/stock_unit/store_id/quantity/locked_quantity/ + * gross_weight/warning_quantity/create_at/last_flow_at/static_hours/is_static。 + */ + async getStaticStockList(options = {}) { + const { ctx } = this; + const requestData = options && typeof options === 'object' ? options : {}; + const warehouseId = Number(requestData.warehouseId || (ctx.user && ctx.user.store_id) || 0); + const page = Number(requestData.page || 1) > 0 ? Math.floor(Number(requestData.page)) : 1; + const pageSize = Number(requestData.pageSize || 20) > 0 + ? Math.min(500, Math.floor(Number(requestData.pageSize))) + : 20; + const emptyPagination = { + page, + pageSize, + total: 0, + totalPages: 0, + }; + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return { list: [], pagination: emptyPagination }; + } + + // 阈值小时数:入参优先,否则仓库配置(默认 168) + let staticHours = Number(requestData.hours); + if (!Number.isFinite(staticHours) || staticHours <= 0) { + staticHours = 168; + try { + const storeModel = ctx.model && ctx.model.Store; + if (storeModel && typeof storeModel.findByPk === 'function') { + const store = await storeModel.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + const subjectConfig = store && store.subject_config ? store.subject_config : {}; + const configHours = Number(subjectConfig.stock_static_hours || 0); + if (Number.isFinite(configHours) && configHours > 0) { + staticHours = configHours; + } + } + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockWarehouse.getStaticStockList] 读取仓库静态时间配置失败,按默认 168 小时: ${err && err.message}` + ); + } + } + + const cutoff = new Date(Date.now() - staticHours * 3600 * 1000); + + const fromSql = ` + FROM wms_stock_warehouse sw + LEFT JOIN ( + SELECT stock_id, MAX(last_flow_at) AS last_flow_at + FROM ( + SELECT stock_id, MAX(created_at) AS last_flow_at + FROM wms_stock_transaction + WHERE warehouse_id = :warehouseId + AND transaction_type = 'INBOUND' + GROUP BY stock_id + UNION ALL + SELECT stock_id, MAX(created_at) AS last_flow_at + FROM wms_stock_transaction + WHERE warehouse_id = :warehouseId + AND transaction_type = 'OUTBOUND' + GROUP BY stock_id + ) flow_union + GROUP BY stock_id + ) t ON t.stock_id = sw.id + WHERE sw.warehouse_id = :warehouseId + AND sw.is_valid = 'Y' + AND sw.deleted_at IS NULL + AND COALESCE(t.last_flow_at, sw.create_at) < :cutoff + `; + const listSql = ` + SELECT sw.id, sw.item_code, sw.item_name, sw.sku_property, sw.stock_unit, + sw.store_id, sw.quantity, sw.locked_quantity, sw.gross_weight, + sw.warning_quantity, sw.create_at, t.last_flow_at + ${fromSql} + ORDER BY COALESCE(t.last_flow_at, sw.create_at) ASC + LIMIT :limit OFFSET :offset + `; + const countSql = ` + SELECT COUNT(1) AS total + ${fromSql} + `; + + const { QueryTypes } = ctx.model; + const baseReplacements = { + warehouseId, + cutoff, + }; + const offset = (page - 1) * pageSize; + + const [ countRows, listRows ] = await Promise.all([ + ctx.model.query(countSql, { + replacements: baseReplacements, + type: QueryTypes.SELECT, + }), + ctx.model.query(listSql, { + replacements: { ...baseReplacements, limit: pageSize, offset }, + type: QueryTypes.SELECT, + }), + ]); + + const total = Number( + (Array.isArray(countRows) && countRows.length > 0 ? countRows[0].total : 0) || 0 + ); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + const list = (Array.isArray(listRows) ? listRows : []).map(row => ({ + id: Number(row && row.id || 0), + item_code: String(row && row.item_code || '').trim(), + item_name: String(row && row.item_name || '').trim(), + sku_property: String(row && row.sku_property || '').trim(), + stock_unit: String(row && row.stock_unit || '').trim(), + store_id: row && row.store_id != null ? Number(row.store_id) : 0, + quantity: Number(row && row.quantity || 0), + locked_quantity: Number(row && row.locked_quantity || 0), + gross_weight: Number(row && row.gross_weight || 0), + warning_quantity: Number(row && row.warning_quantity || 0), + create_at: row && row.create_at ? row.create_at : null, + last_flow_at: row && row.last_flow_at ? row.last_flow_at : null, + static_hours: staticHours, + is_static: true, + })); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages, + }, + }; + } +} + +module.exports = StockWarehouseService; diff --git a/app/service/systems/stockout_order.js b/app/service/systems/stockout_order.js new file mode 100644 index 0000000..9d15204 --- /dev/null +++ b/app/service/systems/stockout_order.js @@ -0,0 +1,560 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 非订单出库单(stockout)领域服务。 + * + * 抽离原 `qimenMethods/stockout.js` 的核心实现,供奇门(stockout.create/query) + * 与开放 API(openapi stockout.create/query)薄适配层共用: + * - 落库 `wms_order_stockout` 主表 + `wms_order_stockout_items` 明细表; + * - 创建时按明细计划数量锁定库存(库存锁标记 `QM_STOCKOUT`,与取消/确认/转单释放口径一致)。 + * + * 入参沿用奇门报文结构 `data.request.deliveryOrder` / `data.request.orderLines`, + * 上下文(storeId/warehouseId/warehouseCode/appKey/sourceType)由调用方通过 + * `options` 显式传入,避免领域服务实例依赖 setInfo 状态。 + */ +class StockoutOrderService extends MainService { + + /** + * 解析出库单快递编码(独立于订单兜底链)。 + * + * 口径: + * 1. 货主开启 enable_external_express_code 且传了 logisticsCode 时,按 + * wms_express_setting 映射 → 系统快递列表匹配; + * 2. 未传 / 未开启 / 匹配不到 → 使用出库单兜底快递编码 + * (stockout_default_express_code,默认 ZT 自提),不回退订单默认快递; + * 不走订单的快递策略漏斗(matchPolicy)。 + * 解析失败仅告警不阻断建单(快递为空,可在确认前手工补填)。 + * + * @param {Object} deliveryOrder 出库单头信息(奇门 deliveryOrder 节点)。 + * @param {Object} context 上下文,需包含 storeId / warehouseId。 + * @return {Promise<{ expressCode: string|null, expressName: string|null }>} 解析结果。 + */ + async resolveStockoutExpress(deliveryOrder = {}, context = {}) { + const { ctx } = this; + const { storeId, warehouseId } = context; + + let expressCode = null; + let expressName = null; + + try { + const deliveryOrderService = ctx.service.systems.deliveryOrder; + const policyConfig = await deliveryOrderService.getStoreWarehousePolicyConfig(storeId, warehouseId); + const expressList = await ctx.service.systems.express.getExpressList(); + const findExpress = code => { + const upperCode = String(code || '').trim().toUpperCase(); + if (!upperCode || !Array.isArray(expressList)) { + return null; + } + return expressList.find(item => item + && String(item.code || item.value || '').trim().toUpperCase() === upperCode) || null; + }; + const externalCode = String(deliveryOrder.logisticsCode || '').trim(); + const enableExternal = deliveryOrderService.normalizePolicyFlag( + policyConfig && policyConfig.enable_external_express_code + ); + + if (enableExternal && externalCode) { + // 1) wms_express_setting 外部编码映射 → 系统快递编码 + const settingSnapshot = await deliveryOrderService.resolveExpressSettingSnapshot(externalCode, warehouseId); + if (settingSnapshot && settingSnapshot.expressCode) { + const sysCode = String(settingSnapshot.expressCode).trim(); + const sysItem = findExpress(sysCode); + expressCode = sysCode; + expressName = sysItem + ? String(sysItem.name || sysItem.label || sysCode).trim() + : String(settingSnapshot.name || sysCode).trim(); + } else { + // 2) 系统快递列表直接匹配 + const matched = findExpress(externalCode); + if (matched) { + expressCode = String(matched.code || matched.value || externalCode).trim(); + expressName = String(matched.name || matched.label || expressCode).trim(); + } + } + } + + if (!expressCode) { + // 兜底:出库单兜底快递编码(货主配置,默认 ZT 自提),不回退订单默认快递 + const fallbackCode = String(policyConfig && policyConfig.stockout_default_express_code || '').trim() || 'ZT'; + const fallbackItem = findExpress(fallbackCode); + expressCode = fallbackItem + ? String(fallbackItem.code || fallbackItem.value || fallbackCode).trim() + : fallbackCode; + expressName = fallbackItem + ? String(fallbackItem.name || fallbackItem.label || fallbackCode).trim() + : fallbackCode; + } + } catch (err) { + ctx.logger.warn(`[stockout.create] 快递编码解析失败,保持为空: ${err.message}`); + } + + return { expressCode, expressName }; + } + + /** + * 创建出库单。 + * + * 将请求的 deliveryOrder / orderLines 写入 `wms_order_stockout` 主表和 + * `wms_order_stockout_items` 明细表,并库存锁定,整个过程在一个数据库事务内完成, + * 失败自动回滚。 + * + * @param {Object} data 请求体,遵循奇门报文结构。 + * @param {Object} data.request 请求数据。 + * @param {Object} data.request.deliveryOrder 出库单头信息。 + * @param {Object} data.request.orderLines 出库单明细。 + * @param {Object|Object[]} data.request.orderLines.orderLine 明细行(单条为对象,多条为数组)。 + * @param {Object} options 上下文与来源。 + * @param {number} options.storeId 货主ID。 + * @param {number} options.warehouseId 仓库ID。 + * @param {string} [options.warehouseCode] 仓库编码。 + * @param {string} [options.appKey] 开放接口 app_key(用于 StockStore 降级匹配)。 + * @param {string} [options.sourceType='QM'] 来源类型(QM / API / WMS)。 + * @return {Promise} 返回 success / fail 结果。 + */ + async create(data, options = {}) { + const { app, ctx } = this; + const { storeId, warehouseId, warehouseCode, appKey } = options; + const sourceType = options.sourceType || 'QM'; + const { deliveryOrder, orderLines } = data.request; + + // 单条 orderLine 转为数组 + let orderLine = orderLines && orderLines.orderLine; + if (orderLine && orderLine.orderLineNo) { + orderLine = [ orderLine ]; + } + + if (!orderLine || !Array.isArray(orderLine) || orderLine.length === 0) { + return this.fail('创建出库单失败,失败原因:\n没有有效的订单明细数据'); + } + + const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length; + + // 快递编码解析 + const { expressCode, expressName } = await this.resolveStockoutExpress(deliveryOrder, { + storeId, + warehouseId, + }); + + // 收件人信息解析(receiverInfo 13 个标准字段落库,供转订单与确认回传使用) + const receiver = deliveryOrder.receiverInfo && typeof deliveryOrder.receiverInfo === 'object' + ? deliveryOrder.receiverInfo + : {}; + const receiverFields = { + receiver_company: receiver.company, + receiver_name: receiver.name, + receiver_zip_code: receiver.zipCode, + receiver_tel: receiver.tel, + receiver_mobile: receiver.mobile, + receiver_email: receiver.email, + receiver_country_code: receiver.countryCode, + receiver_province: receiver.province, + receiver_city: receiver.city, + receiver_area: receiver.area, + receiver_town: receiver.town, + receiver_detail_address: receiver.detailAddress, + receiver_id: receiver.id, + }; + for (const key of Object.keys(receiverFields)) { + const rawValue = receiverFields[key]; + receiverFields[key] = rawValue === undefined || rawValue === null + ? null + : String(rawValue).trim() || null; + } + + // 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细 + const errors = []; + const items = []; + for (let i = 0; i < orderLine.length; i++) { + const line = orderLine[i]; + let wmsStock = await app.model.StockStore.findByPk(line.itemId); + // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 + if (wmsStock && Number(wmsStock.store_id) !== Number(storeId)) { + wmsStock = null; + } + // 外部渠道 itemId 可能是平台商品标识或条码而非 WMS 主键, + // 主键查不到或跨货主时降级按 item_code + 仓库货主维度查找 + if (!wmsStock && line.itemCode) { + const stockWhere = { + item_code: line.itemCode, + warehouse_id: warehouseId, + store_id: storeId, + }; + if (appKey) { + stockWhere.app_key = appKey; + } + wmsStock = await app.model.StockStore.findOne({ where: stockWhere }); + } + if (!wmsStock) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库` + ); + continue; + } + if (!wmsStock.stock_id) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》wms无对应关系\n请联系仓库关联创建商品` + ); + continue; + } + const planQty = parseInt(line.planQty) || 0; + if (planQty <= 0) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n计划数量必须大于0` + ); + continue; + } + items.push({ + orderLineNo: line.orderLineNo, + ownerCode: line.ownerCode, + itemCode: line.itemCode, + // item_id 统一写入实际匹配到的 StockStore 主键 id(纯数字), + // 避免调用方把「编码+名称」等非数字值放进 itemId 时写入 BIGINT 列 + // 触发 MySQL 严格模式报错(与 entry_order 建单口径一致) + itemId: wmsStock.id, + itemName: line.itemName, + planQty, + inventoryType: line.inventoryType, + stockId: wmsStock.stock_id, + }); + } + + if (errors.length > 0) { + return this.fail(`创建出库单失败,失败原因:\n${errors.join('\n')}`); + } + + // 预取超卖配置,避免每次 lockItemStorages 在锁内回退查 DB + const oversellConfig = await ctx.service.systems.stockStore + .getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId); + + // 第二步:在事务中写入主表 + 库存锁定 + 明细表 + const transaction = await ctx.model.transaction(); + try { + const order = await ctx.model.OrderStockout.create( + { + stockout_order_code: deliveryOrder.deliveryOrderCode, + order_type: deliveryOrder.orderType, + total_order_lines: totalOrderLines, + order_create_time: deliveryOrder.createTime + ? new Date(deliveryOrder.createTime) + : null, + remark: deliveryOrder.remark || null, + express_code: expressCode, + express_name: expressName, + ...receiverFields, + warehouse_id: warehouseId, + store_id: storeId, + qimen_owner_code: items[0].ownerCode, + qimen_warehouse_code: warehouseCode, + source_type: sourceType, + created_at: new Date(), + updated_at: new Date(), + }, + { transaction } + ); + + const orderId = order.id; + + // 库存锁定:按 stockId 升序排序后逐个加锁,避免死锁 + const sortedItems = [ ...items ].sort((a, b) => a.stockId - b.stockId); + for (const item of sortedItems) { + const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stockId, + item.planQty, + transaction, + oversellConfig, + { orderType: 'QM_STOCKOUT', orderNo: deliveryOrder.deliveryOrderCode, orderId } + ); + if (!lockResult.success) { + throw new Error( + `SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》\n库存锁定失败: ${lockResult.error}` + ); + } + } + + // 批量创建明细 + const now = new Date(); + const itemRecords = items.map(item => ({ + order_id: orderId, + order_line_no: item.orderLineNo, + owner_code: item.ownerCode, + item_code: item.itemCode, + item_id: item.itemId, + item_name: item.itemName, + plan_qty: item.planQty, + inventory_type: item.inventoryType, + stock_id: item.stockId, + created_at: now, + updated_at: now, + })); + + await ctx.model.OrderStockoutItems.bulkCreate(itemRecords, { + transaction, + validate: true, + }); + + await transaction.commit(); + + return this.success('出库单创建成功', { + stockoutOrderId: order.id, + stockoutOrderCode: order.stockout_order_code, + }); + } catch (err) { + await transaction.rollback(); + ctx.logger.error('[stockout.create] 事务写入失败:', err); + return this.fail(`创建出库单失败,失败原因:\n${err.message}`); + } + } + + /** + * 查询出库单。 + * + * 根据 deliveryOrderCode 查 `wms_order_stockout` 主表, + * 然后关联查 `wms_order_stockout_items` 明细,返回标准结构。 + * + * @param {Object} data 请求体,遵循奇门报文结构。 + * @param {Object} data.request 请求数据。 + * @param {Object} data.request.deliveryOrder 出库单查询条件。 + * @param {string} data.request.deliveryOrder.deliveryOrderCode 出库单号。 + * @return {Promise} 返回 success / fail 结果。 + */ + async query(data) { + const { app, ctx } = this; + const { deliveryOrderCode } = data.request.deliveryOrder; + + // 查主表 + const order = await ctx.model.OrderStockout.findOne({ + where: { stockout_order_code: deliveryOrderCode }, + }); + if (!order) { + return this.fail('未找到出库单'); + } + + // 查明细 + const items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: order.id }, + order: [[ 'order_line_no', 'ASC' ]], + }); + + return this.success('成功', { + totalLines: items.length, + deliveryOrder: { + deliveryOrderCode: order.stockout_order_code, + deliveryOrderId: order.id, + warehouseCode: order.qimen_warehouse_code, + orderType: order.order_type, + status: order.order_status, + createTime: order.order_create_time ? app.formatDate(order.order_create_time) : null, + remark: order.remark || '', + }, + orderLines: { + orderLine: items.map(item => ({ + orderLineNo: item.order_line_no, + ownerCode: item.owner_code, + itemCode: item.item_code, + itemId: item.item_id, + itemName: item.item_name, + planQty: item.plan_qty, + inventoryType: item.inventory_type, + })), + }, + }); + } + + /** + * 取消出库单(奇门 / openapi / systemMethods 共用)。 + * + * 定位方式:优先按 stockoutOrderCode,其次按 id;上下文(storeId / warehouseId / + * operatorLabel)一律由 options 显式传入,不读取 ctx.user。仅 CREATED / PENDING + * 状态允许取消:事务内(行锁)释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK + * 流水),状态置 CANCELLED 并写操作日志;已 CANCELLED 幂等返回成功; + * COMPLETED / TRANSFERRED 等其他状态拒绝取消。 + * 取消成功后不需要向奇门 / 开放平台回传任何事件。 + * + * @param {Object} data 请求体。 + * @param {string} [data.stockoutOrderCode] 出库单号(优先)。 + * @param {number} [data.id] 出库单ID。 + * @param {Object} options 上下文。 + * @param {number|null} [options.storeId] 货主ID(有值时参与定位条件)。 + * @param {number} options.warehouseId 仓库ID。 + * @param {string} [options.operatorLabel] 操作人标识(写入操作日志,如 qimen:xxx / openapi:xxx)。 + * @return {Promise} 统一成功/失败包装响应,成功时返回 id / stockout_order_code / order_status。 + */ + async cancel(data = {}, options = {}) { + const { ctx } = this; + const { storeId, warehouseId, operatorLabel } = options; + const stockoutOrderCode = String(data.stockoutOrderCode || '').trim(); + const id = Number(data.id || 0); + const normalizedWarehouseId = Number(warehouseId) || 0; + + if (normalizedWarehouseId <= 0) { + return this.fail('缺少仓库上下文'); + } + + if (!stockoutOrderCode && !(id > 0)) { + return this.fail('出库单号不能为空'); + } + + // 定位条件:仓库 + 货主(有值时)+ 软删除过滤;单号优先,否则按 ID + const where = { + warehouse_id: normalizedWarehouseId, + deleted_at: null, + }; + if (storeId !== undefined && storeId !== null && storeId !== '') { + where.store_id = Number(storeId); + } + if (stockoutOrderCode) { + where.stockout_order_code = stockoutOrderCode; + } else { + where.id = id; + } + + const transaction = await ctx.model.transaction(); + let order; + try { + // 行锁防并发取消 / 确认 / 转单 + order = await ctx.model.OrderStockout.findOne({ + where, + transaction, + lock: transaction.LOCK.UPDATE, + }); + if (!order) { + await transaction.rollback(); + return this.fail('未找到对应的出库单'); + } + + // 幂等:已取消直接返回成功,不重复释放库存 + if (String(order.order_status || '').trim() === 'CANCELLED') { + await transaction.rollback(); + return this.success('取消出库单成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_status: 'CANCELLED', + }); + } + + // 状态守卫:仅 CREATED / PENDING 允许取消(与 storage.stockout.cancel 同口径) + if (!order.canCancel || !order.canCancel()) { + await transaction.rollback(); + return this.fail(`出库单当前状态(${order.order_status})不允许取消`); + } + + const items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: order.id }, + raw: true, + transaction, + }); + + // 释放创建时占用的库存锁定(口径与 storage.stockout.cancel 完全一致) + let releasedQty = 0; + for (const item of items) { + const qty = Number(item.plan_qty) || 0; + if (qty <= 0) continue; + const releaseResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stock_id, + -qty, + transaction, + null, + { + orderType: 'QM_STOCKOUT', + orderNo: order.stockout_order_code, + orderId: order.id, + remark: '出库单取消释放锁定', + } + ); + if (!releaseResult.success) { + // 已释放过(锁定不足)视为幂等成功,避免阻断重试 + const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存'); + if (alreadyReleased) { + ctx.logger.warn(`[stockout.cancel] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`); + continue; + } + throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`); + } + releasedQty += qty; + } + + await ctx.model.OrderStockout.update( + { order_status: 'CANCELLED', sync_message: '已取消', updated_at: new Date() }, + { where: { id: order.id }, transaction } + ); + + await this._writeStockoutOperationLog( + order, + 'STOCKOUT_CANCEL', + `出库单已取消,释放锁定库存 ${releasedQty}`, + { + transaction, + warehouseId: normalizedWarehouseId, + operator: { id: null, name: operatorLabel || 'system' }, + } + ); + + await transaction.commit(); + } catch (err) { + try { + await transaction.rollback(); + } catch (rollbackErr) { + ctx.logger.error('[stockout.cancel] 事务回滚失败:', rollbackErr); + } + ctx.logger.error(`[stockout.cancel] 取消失败: ${err.message}`); + return this.fail(`取消失败:${err.message}`); + } + + ctx.logger.info(`[stockout.cancel] 取消完成: ${order.stockout_order_code}`); + return this.success('取消出库单成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_status: 'CANCELLED', + }); + } + + /** + * 写 wms_operation_log 操作日志(businessType=stockout),失败仅告警不影响主流程。 + * + * 与 systemMethods/storage/stockout 历史日志口径一致;操作人 / 仓库信息由 + * options 显式传入,不读取 ctx.user(供奇门 / openapi 等无登录用户上下文渠道复用)。 + * + * @param {Object} order 出库单实例或行。 + * @param {string} operationCode 操作编码(如 STOCKOUT_CANCEL)。 + * @param {string} message 日志内容。 + * @param {Object} [options={}] 选项。 + * @param {Object} [options.transaction] 数据库事务对象。 + * @param {number|null} [options.warehouseId] 仓库ID,缺省回退出库单自身 warehouse_id。 + * @param {Object} [options.operator={}] 操作人信息,含 id / name。 + * @return {Promise} 无返回值。 + */ + async _writeStockoutOperationLog(order, operationCode, message, options = {}) { + const { ctx } = this; + const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (!opLogService || typeof opLogService.createOperationLogs !== 'function') { + ctx.logger.warn('[stockout] 操作日志服务不可用,跳过记录'); + return; + } + const operator = options.operator || {}; + try { + await opLogService.createOperationLogs([ + { + businessType: 'stockout', + businessId: order.id, + operationCode, + operator: { + id: operator.id ?? null, + name: String(operator.name || 'system'), + }, + extras: { + warehouseId: options.warehouseId ?? order.warehouse_id ?? null, + message, + externalLogType: 'NONE', + }, + }, + ], { transaction: options.transaction }); + } catch (err) { + ctx.logger.warn(`[stockout] 写操作日志失败: ${err.message}`); + } + } + +} + +module.exports = StockoutOrderService; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js new file mode 100644 index 0000000..e0f523b --- /dev/null +++ b/app/service/systems/storage/entry.js @@ -0,0 +1,3290 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +const ENTRY_EXPORT_PAGE_SIZE = 200; +const ENTRY_ITEMS_FETCH_BATCH_SIZE = 100; + +class EntryService extends Service { + /** + * 将费用记录筛选值归一化为 0/1。 + * @param {unknown} rawValue 原始筛选值 + * @return {number|null} 归一化结果,无法识别时返回 null + */ + normalizeExpenseRecordValue(rawValue) { + if (rawValue === true) return 1; + if (rawValue === false) return 0; + + if (rawValue === 1 || rawValue === '1') return 1; + if (rawValue === 0 || rawValue === '0') return 0; + + if (typeof rawValue === 'string') { + const normalized = rawValue.trim().toLowerCase(); + if ([ 'true', 'yes', 'y' ].includes(normalized)) return 1; + if ([ 'false', 'no', 'n' ].includes(normalized)) return 0; + } + + return null; + } + + /** + * 归一化 expense_record 条件,兼容 eq/in/布尔值写法。 + * @param {Object|number|string|boolean} condition 原始条件 + * @return {Object|null} 标准化后的条件,无法识别时返回 null + */ + normalizeExpenseRecordCondition(condition) { + const isObjectCondition = condition && typeof condition === 'object' && !Array.isArray(condition); + if (!isObjectCondition) { + const normalizedValue = this.normalizeExpenseRecordValue(condition); + if (normalizedValue === null) { + return null; + } + return { + operator: 'eq', + value: normalizedValue, + }; + } + + const operator = String(condition.operator || 'eq').trim().toLowerCase(); + const values = this.normalizeFilterValues(condition) + .map(item => this.normalizeExpenseRecordValue(item)) + .filter(item => item !== null); + + if (values.length === 0) { + return null; + } + + if (operator === 'in') { + return { + operator: 'in', + value: [ ...new Set(values) ], + }; + } + + return { + operator: 'eq', + value: values[0], + }; + } + + /** + * 将筛选值归一化为数组。 + * @param {Object} condition 条件对象 + * @return {Array} 归一化后的值数组 + */ + normalizeFilterValues(condition = {}) { + const value = condition && Object.prototype.hasOwnProperty.call(condition, 'value') + ? condition.value + : undefined; + + if (Array.isArray(value)) { + return value; + } + + if (value === undefined || value === null) { + return []; + } + + return [ value ]; + } + + /** + * 构建入库单-库存流水 EXISTS 子查询条件。 + * @param {string} fieldName 流水字段名 + * @param {Object} condition 条件对象 + * @return {Object|null} Sequelize.where 条件,无法构建时返回 null + */ + buildEntryStockTransactionExistsCondition(fieldName, condition = {}) { + const { app } = this; + const db = app.model; + const values = this.normalizeFilterValues(condition) + .map(item => (typeof item === 'string' ? item.trim() : item)) + .filter(item => item !== '' && item !== undefined && item !== null); + + if (values.length === 0) { + return null; + } + + const operator = String(condition.operator || 'eq').trim().toLowerCase(); + const escapedColumn = `st.${fieldName}`; + const escapedValues = values.map(item => db.escape(item)); + + let valueClause = ''; + if (operator === 'in') { + valueClause = `${escapedColumn} IN (${escapedValues.join(',')})`; + } else if (operator === 'like' || operator === 'contains') { + const likeClauses = values.map(item => `${escapedColumn} LIKE ${db.escape(`%${String(item)}%`)}`); + valueClause = likeClauses.length === 1 ? likeClauses[0] : `(${likeClauses.join(' OR ')})`; + } else { + valueClause = `${escapedColumn} = ${escapedValues[0]}`; + } + + const sql = `EXISTS ( + SELECT 1 + FROM wms_stock_transaction st + WHERE st.entry_order_id = wms_entry_order.id + AND ${valueClause} + )`; + + return app.Sequelize.where(app.Sequelize.literal(sql), 1); + } + + /** + * 预处理入库单列表筛选条件,兼容历史别名并构建扩展筛选。 + * @param {Object} normalizedWhere 标准化后的 where 条件 + * @return {{where: Object, extraConditions: Array, errorMessage: string}} 预处理结果 + */ + /** + * 根据 hasReceiving 虚拟字段构建入库单 ID 筛选条件。 + * @param {boolean} hasReceiving true=已绑定,false=未绑定 + * @return {Promise} Sequelize where 条件,无需额外筛选时返回 null + */ + async buildHasReceivingCondition(hasReceiving) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + attributes: [[ app.Sequelize.fn('DISTINCT', app.Sequelize.col('entry_order_id')), 'entry_order_id' ]], + where: { deleted_at: null }, + raw: true, + }); + + const boundIds = bindings.map(item => item.entry_order_id); + + if (hasReceiving === true) { + if (boundIds.length === 0) { + return { id: { [Op.eq]: null } }; + } + return { id: { [Op.in]: boundIds } }; + } + + if (boundIds.length === 0) { + return null; + } + return { id: { [Op.notIn]: boundIds } }; + } + + /** + * 预处理入库单列表筛选条件,兼容历史别名并构建扩展筛选。 + * @param {Object} normalizedWhere 标准化后的 where 条件 + * @return {Promise<{where: Object, extraConditions: Array, errorMessage: string}>} 预处理结果 + */ + async preprocessEntryListWhere(normalizedWhere = {}) { + const { ctx } = this; + const whereForParse = normalizedWhere && typeof normalizedWhere === 'object' + ? { ...normalizedWhere } + : {}; + const extraConditions = []; + + if (whereForParse.erp_remark && !whereForParse.remark) { + whereForParse.remark = whereForParse.erp_remark; + } + delete whereForParse.erp_remark; + + const batchCondition = whereForParse.batch_no || whereForParse.batch; + if (batchCondition) { + const existsCondition = this.buildEntryStockTransactionExistsCondition('batch_no', batchCondition); + if (existsCondition) { + extraConditions.push(existsCondition); + } + } + delete whereForParse.batch_no; + delete whereForParse.batch; + + if (whereForParse.operator_id) { + const existsCondition = this.buildEntryStockTransactionExistsCondition('operator_id', whereForParse.operator_id); + if (existsCondition) { + extraConditions.push(existsCondition); + } + } + delete whereForParse.operator_id; + + // 处理虚拟字段 hasReceiving:从 where 中剥离,构建绑定/未绑定筛选条件 + if (Object.prototype.hasOwnProperty.call(whereForParse, 'hasReceiving')) { + const rawHasReceiving = whereForParse.hasReceiving; + delete whereForParse.hasReceiving; + + if (rawHasReceiving === true || rawHasReceiving === false) { + const receivingCondition = await this.buildHasReceivingCondition(rawHasReceiving); + if (receivingCondition) { + extraConditions.push(receivingCondition); + } + } + } + + if (Object.prototype.hasOwnProperty.call(whereForParse, 'expense_record')) { + const hasExpenseRecordField = Boolean( + ctx.model + && ctx.model.EntryOrder + && ctx.model.EntryOrder.rawAttributes + && ctx.model.EntryOrder.rawAttributes.expense_record + ); + if (!hasExpenseRecordField) { + return { + where: {}, + extraConditions: [], + errorMessage: '当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级', + }; + } + + const normalizedExpenseRecord = this.normalizeExpenseRecordCondition(whereForParse.expense_record); + if (normalizedExpenseRecord) { + whereForParse.expense_record = normalizedExpenseRecord; + } else { + delete whereForParse.expense_record; + } + } + + return { + where: whereForParse, + extraConditions, + errorMessage: '', + }; + } + + /** + * 入库单列表查询,复用 where 解构工具。 + * @param {Object} where 筛选条件对象 + * @param {Object} pageParams 分页参数 + * @param {Object} sortParams 排序参数 + * @param {string} [mode='warehouse'] 查询模式:warehouse=仓库侧(按 warehouse_id 过滤),store=货主侧(按 store_id 过滤) + * @return {Promise} code/data/message 结构 + */ + async list(where = {}, pageParams = {}, sortParams = {}, mode = 'warehouse') { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const page = Math.max(Number(pageParams.page) || 1, 1); + const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1); + + const sortField = sortParams.sortField || 'created_at'; + const sortOrder = String(sortParams.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', + 'entry_order_code', + 'order_type', + 'order_status', + 'order_create_time', + 'created_at', + 'updated_at', + 'total_order_lines', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + const isStoreMode = String(mode).toLowerCase() === 'store'; + // 参考 stock.report.search:从 ctx.user.store_id 提取主维度 ID, + // Number(undefined)=NaN(falsy),防止 Sequelize 静默剔除 undefined 键导致过滤失效 + const rawPrimaryId = Number(ctx.user && ctx.user.store_id); + const storeId = isStoreMode ? rawPrimaryId : null; + const warehouseId = isStoreMode ? null : rawPrimaryId; + + if (isStoreMode && !storeId) { + return { + code: 400, + message: '用户未绑定货主,无法查询货主侧入库单', + data: { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total: 0, pending: 0, creating: 0, created: 0, completed: 0, cancelled: 0 }, + }, + }; + } + if (!isStoreMode && !warehouseId) { + return { + code: 400, + message: '用户未绑定仓库,无法查询入库单', + data: { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total: 0, pending: 0, creating: 0, created: 0, completed: 0, cancelled: 0 }, + }, + }; + } + + const baseWhere = isStoreMode + ? { store_id: storeId, is_enabled: 1, deleted_at: null } + : { warehouse_id: warehouseId, is_enabled: 1, deleted_at: null }; + + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (where && typeof where === 'object' ? { ...where } : {}); + + const { + where: parsedSourceWhere, + extraConditions, + errorMessage, + } = await this.preprocessEntryListWhere(normalizedWhere); + + if (errorMessage) { + return { + code: 400, + message: errorMessage, + data: { + list: [], + pagination: { + page, + pageSize, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + summary: { + total: 0, + pending: 0, + creating: 0, + created: 0, + completed: 0, + cancelled: 0, + }, + }, + }; + } + + const parsed = parseWhereConditions({ + where: parsedSourceWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (!parsed.ok) { + return { + code: 400, + message: `筛选条件解析失败: ${parsed.reason}`, + data: { + list: [], + pagination: { + page, + pageSize, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + summary: { + total: 0, + pending: 0, + creating: 0, + created: 0, + completed: 0, + cancelled: 0, + }, + }, + }; + } + const parsedResult = parsed.result; + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || parsedSourceWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : null; + + const andConditions = [ baseWhere ]; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const kw = String(quickWhereValue).trim(); + const receivingDetailId = Number(kw); + const escapedKw = app.model.escape(`%${kw}%`); + const orConditions = [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + // 搜索收货单号(wms_receiving.receiving_number),通过绑定表关联 + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving r ON r.id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND r.receiving_number LIKE ${escapedKw} + )` + ), 1), + // 搜索收货单明细 ID(箱唛/托盘唛唯一编码,精确数字匹配);仅当 kw 是有效正数时追加 EXISTS + ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND rd.id = ${receivingDetailId} + )` + ), 1), + ] : []), + ]; + andConditions.push({ [Op.or]: orConditions }); + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + if (extraConditions.length > 0) { + andConditions.push({ [Op.and]: extraConditions }); + } + + const finalWhere = { [Op.and]: andConditions }; + + const include = [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name' ], + required: false, + }, + ]; + + const { count, rows } = await ctx.model.EntryOrder.findAndCountAll({ + where: finalWhere, + include, + order: [[ actualSortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + distinct: true, + }); + + // 批量查询收货单绑定信息 + const entryOrderIds = rows.map(row => row.id); + /** @type {Map>} */ + const receivingBindingsMap = new Map(); + if (entryOrderIds.length > 0) { + const allBindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: { [Op.in]: entryOrderIds }, deleted_at: null }, + include: [ + { + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ], + required: false, + }, + ], + order: [[ 'id', 'ASC' ]], + }); + + for (const binding of allBindings) { + const eid = binding.entry_order_id; + if (!receivingBindingsMap.has(eid)) { + receivingBindingsMap.set(eid, []); + } + receivingBindingsMap.get(eid).push(binding); + } + } + + // 批量聚合当前页入库单的商品总数量(计划数)与已入库数量 + /** @type {Map} */ + const quantityMap = new Map(); + if (entryOrderIds.length > 0) { + const quantityRows = await ctx.model.EntryItems.findAll({ + attributes: [ + 'order_id', + [ Sequelize.fn('SUM', Sequelize.col('count')), 'total_quantity' ], + [ Sequelize.fn('SUM', Sequelize.col('received_quantity')), 'received_quantity' ], + ], + where: { order_id: { [Op.in]: entryOrderIds } }, + group: [ 'order_id' ], + raw: true, + }); + for (const item of quantityRows) { + quantityMap.set(Number(item.order_id), { + total_quantity: Number(item.total_quantity) || 0, + received_quantity: Number(item.received_quantity) || 0, + }); + } + } + + // 为每行附加收货单绑定信息与数量汇总 + const enrichedRows = rows.map(row => { + const rowJSON = row.toJSON ? row.toJSON() : row; + const bindings = receivingBindingsMap.get(row.id) || []; + const quantity = quantityMap.get(row.id) || { total_quantity: 0, received_quantity: 0 }; + return { + ...rowJSON, + total_quantity: quantity.total_quantity, + received_quantity: quantity.received_quantity, + receivingBindings: bindings, + hasReceiving: bindings.length > 0, + }; + }); + + const statusRows = await ctx.model.EntryOrder.findAll({ + attributes: [ + 'order_status', + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ], + ], + where: finalWhere, + group: [ 'order_status' ], + raw: true, + }); + + const summary = { + total: count, + pending: 0, + creating: 0, + created: 0, + completed: 0, + cancelled: 0, + }; + statusRows.forEach(item => { + const statusKey = String(item.order_status || '').toLowerCase(); + if (Object.prototype.hasOwnProperty.call(summary, statusKey)) { + summary[statusKey] = Number(item.count) || 0; + } + }); + + return { + code: 200, + message: '查询成功', + data: { + list: enrichedRows, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page < Math.ceil(count / pageSize), + }, + summary, + }, + }; + } + + /** + * 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。 + * 返回入库单基本信息、商品明细(含计划数量与已完成数量)、收货单绑定关系。 + * @param {Object} data 请求参数 + * @param {number} data.id 入库单主键 ID(必填) + * @param {string} [mode='warehouse'] 查询维度:'warehouse' 按仓库校验权限(默认),'store' 按货主校验权限 + * @return {Promise} code/data/message 结构 + * - data.entryOrder: { id, entry_order_code, order_status, total_order_lines, store_remask } + * - data.total_quantity: 应入库总数量(明细 planned 之和) + * - data.received_quantity: 已入库总数量(明细 completed 之和) + * - data.items: [{ id, stock_id, planned, completed, stock, bindings }] + * - data.receivingBindings: [{ id, receiving_id, receiving }] + */ + async get(data = {}, mode = 'warehouse') { + const { ctx, app } = this; + const id = Number(data.id || 0); + + if (!id) { + return { code: 400, message: 'id 参数不能为空', data: null }; + } + + const entryOrder = await ctx.model.EntryOrder.findByPk(id, { + include: [ + { + model: ctx.model.EntryItems, + as: 'items', + required: false, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + required: false, + }, + ], + }, + { + model: ctx.model.EntryOrderReceiving, + as: 'receivingBindings', + required: false, + include: [ + { + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ], + required: false, + }, + ], + }, + ], + }); + + if (!entryOrder) { + return { code: 404, message: '入库单不存在', data: null }; + } + + const isStoreMode = String(mode).toLowerCase() === 'store'; + const rawPrimaryId = Number(ctx.user && ctx.user.store_id); + + // 校验权限:仓库模式校验 warehouse_id,货主模式校验 store_id + if (isStoreMode) { + if (entryOrder.store_id !== rawPrimaryId || !entryOrder.is_enabled) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + } else { + if (entryOrder.warehouse_id !== rawPrimaryId || !entryOrder.is_enabled) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + } + + // 查询货主商家备注 + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: entryOrder.store_id, warehouse_id: entryOrder.warehouse_id }, + attributes: [ 'store_remask' ], + raw: true, + }); + + // 查询该入库单下已有的导入/PDA 入库记录(显式过滤软删除,仅统计未删除记录) + const directLogs = await ctx.model.InboundDirectLog.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + order: [[ 'created_at', 'ASC' ]], + }); + + // 将直接入库记录按 entry_item_id 关联到明细 + // 优先使用 entry_item_id 精确匹配(绑定模式),其次回退到 stock_id 匹配(非绑定模式) + const itemDirectLogs = {}; + for (const log of directLogs) { + // 绑定模式下 entry_item_id 已设置,优先用它定位明细行 + const itemByEntryItemId = log.entry_item_id + ? entryOrder.items.find(i => String(i.id) === String(log.entry_item_id)) + : null; + const item = itemByEntryItemId || entryOrder.items.find( + i => String(i.stock_id) === String(log.stock_id) + ); + const key = item ? String(item.id) : `stock_${log.stock_id}`; + if (!itemDirectLogs[key]) itemDirectLogs[key] = []; + itemDirectLogs[key].push({ + id: log.id, + stock_id: log.stock_id, + quantity: log.quantity, + inbound_type: log.inbound_type, + space_id: log.space_id, + remark: log.remark, + operator_id: log.operator_id, + operator_name: log.operator_name, + created_at: log.created_at, + }); + } + + // 将入库单层级的收货单绑定扁平化 + const receivingBindings = (entryOrder.receivingBindings && entryOrder.receivingBindings.length > 0) + ? entryOrder.receivingBindings.map(rb => ({ + id: rb.id, + receiving_id: rb.receiving_id, + receiving: rb.receiving || null, + })) + : []; + + // 收集所有 stock_id,通过 getStockDetails 批量获取带缓存的商品详情 + const stockIds = [ ...new Set( + (entryOrder.items || []) + .map(item => Number(item.stock_id)) + .filter(sid => sid && sid > 0) + ) ]; + + /** @type {Map} */ + const stockMap = new Map(); + if (stockIds.length > 0) { + // 货主模式下传 null 跳过 warehouse 过滤,避免 store_id 误当 warehouse_id 导致查不到商品 + const stockWarehouseId = isStoreMode ? null : rawPrimaryId; + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId: stockWarehouseId }); + for (const detail of stockDetails) { + stockMap.set(detail.id, detail); + } + } + + // 组装明细(精简字段,突出已入/总数) + const items = (entryOrder.items || []).map(item => { + const planQty = Number(item.count) || 0; + const logKey = String(item.id); + const logs = itemDirectLogs[logKey] || []; + const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0); + // 优先使用已持久化的 received_quantity(commit 后由系统写入), + // 若为 0 则回退到 InboundDirectLog 汇总(尚未提交时的导入量), + // 确保绑定收货明细场景下 completed 口径与 received_quantity 一致。 + const receivedQty = Number(item.received_quantity) || 0; + const completed = receivedQty > 0 ? receivedQty : directInQty; + + const stockDetail = stockMap.get(Number(item.stock_id)); + const stock = stockDetail + ? (s => { delete s.quantity; delete s.locked_quantity; return s; })({ ...stockDetail }) + : null; + + return { + id: item.id, + stock_id: item.stock_id, + planned: planQty, + completed, + stock, + }; + }); + + // 收集所有 InboundDirectLog 中的 space_id,批量查询库位名称 + /** @type {Map} space_id -> space_name */ + const spaceNameMap = new Map(); + const allSpaceIds = [ ...new Set( + Object.values(itemDirectLogs) + .flat() + .map(log => log.space_id) + .filter(sid => sid != null) + ) ]; + if (allSpaceIds.length > 0) { + const spaces = await ctx.model.LocationSpace.findAll({ + where: { id: { [app.Sequelize.Op.in]: allSpaceIds } }, + attributes: [ 'id', 'custom_name', 'space_code' ], + raw: true, + }); + for (const sp of spaces) { + spaceNameMap.set(sp.id, sp.custom_name || sp.space_code || ''); + } + } + + // 批量查询已绑定的收货明细列表 + const entryItemIds = items.map(i => i.id).filter(Boolean); + /** @type {Map>} 按 entry_item_id 分组 */ + const bindingsMap = new Map(); + if (entryItemIds.length > 0) { + const bindingRows = await ctx.model.InboundDirectLog.findAll({ + where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + receiving_detail_id: { [app.Sequelize.Op.ne]: null }, + deleted_at: null, + }, + attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'quantity', 'status' ], + raw: true, + }); + + if (bindingRows.length > 0) { + const detailIds = [ ...new Set(bindingRows.map(b => b.receiving_detail_id).filter(Boolean)) ]; + const validDetailIds = new Set(); + if (detailIds.length > 0) { + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: { [app.Sequelize.Op.in]: detailIds } }, + attributes: [ 'id' ], + raw: true, + }); + for (const d of details) { + validDetailIds.add(d.id); + } + } + + for (const b of bindingRows) { + const key = b.entry_item_id; + if (!bindingsMap.has(key)) { + bindingsMap.set(key, []); + } + bindingsMap.get(key).push({ + detail_id: b.receiving_detail_id, + binding_id: b.id, + allocated_quantity: b.quantity || 0, + }); + } + } + } + + // 将 bindings 挂到对应 item,并补充库位信息 + for (const item of items) { + const bindings = bindingsMap.get(item.id) || []; + const logKey = String(item.id); + const directLogsForItem = itemDirectLogs[logKey] || []; + + if (bindings.length === 0 && directLogsForItem.length > 0) { + const firstWithSpace = directLogsForItem.find(l => l.space_id); + if (firstWithSpace) { + item.bindings = [{ + space_id: firstWithSpace.space_id, + space_name: spaceNameMap.get(Number(firstWithSpace.space_id)) || '', + }]; + } else { + item.bindings = []; + } + } else { + const firstWithSpace = directLogsForItem.find(l => l.space_id); + const sid = firstWithSpace ? firstWithSpace.space_id : null; + item.bindings = bindings.map(b => ({ + ...b, + space_id: sid, + space_name: sid != null ? (spaceNameMap.get(Number(sid)) || '') : '', + })); + } + } + + return { + code: 200, + message: '查询成功', + data: { + entryOrder: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + order_status: entryOrder.order_status, + total_order_lines: entryOrder.total_order_lines, + store_remask: (storeWarehouse && storeWarehouse.store_remask) || '', + }, + total_quantity: items.reduce((sum, item) => sum + (Number(item.planned) || 0), 0), + received_quantity: items.reduce((sum, item) => sum + (Number(item.completed) || 0), 0), + items, + receivingBindings, + }, + }; + } + + /** + * 为 entry items 批量补充可匹配的收货单明细及剩余可用量。 + * 匹配规则:entry_item.stock_id 即 wms_stock_warehouse.id,与 wms_receiving_detail.system_product_id 直接对应。 + * 只返回收货单状态为未完成(status NOT IN ('completed','cancelled'))且未完全入库(storage_status IN ('none','partial'))的明细。 + * @param {Object[]} items 扁平化后的 entry items 数组 + * @param {number} warehouseId 仓库ID + * @return {Promise} 补充了 available_receiving_details 的 items + */ + async enrichItemsWithAvailableReceivingDetails(items, warehouseId) { + if (!Array.isArray(items) || items.length === 0) return items; + + const { ctx } = this; + const stockIds = [ ...new Set(items.map(i => Number(i.stock_id)).filter(Boolean)) ]; + if (stockIds.length === 0) return items; + + // stock_id 即 wms_stock_warehouse.id + // wms_receiving_detail.system_product_id 也指向 wms_stock_warehouse.id + // 所以映射关系就是 id → id,只需确认 stock_warehouse 记录存在 + const swRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [ctx.app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + const stockIdToSystemProductId = new Map(); + for (const row of swRows) { + stockIdToSystemProductId.set(Number(row.id), Number(row.id)); + } + const systemProductIds = [ ...new Set(stockIdToSystemProductId.values()) ]; + if (systemProductIds.length === 0) return items; + + // 批量查询收货单明细可用量 + const rows = await ctx.model.query( + `SELECT + rd.id AS receiving_detail_id, + rd.receiving_id, + rd.system_product_id, + r.receiving_number, + rd.actual_quantity, + COALESCE(SUM(erb.quantity), 0) AS allocated_quantity, + rd.actual_quantity - COALESCE(SUM(erb.quantity), 0) AS available_quantity + FROM wms_receiving_detail rd + INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.is_deleted = false + LEFT JOIN wms_inbound_direct_log erb + ON erb.receiving_detail_id = rd.id + AND erb.status = 'committed' + AND erb.deleted_at IS NULL + WHERE rd.system_product_id IN (:systemProductIds) + AND r.status NOT IN ('completed', 'cancelled') + AND rd.storage_status IN ('none', 'partial') + GROUP BY rd.id, rd.receiving_id, rd.system_product_id, r.receiving_number, rd.actual_quantity + HAVING available_quantity > 0 + ORDER BY rd.system_product_id, available_quantity DESC`, + { replacements: { systemProductIds }, type: ctx.model.QueryTypes.SELECT } + ); + + // 按 system_product_id 分组 + const mapBySystemProductId = new Map(); + for (const row of rows) { + const spid = Number(row.system_product_id); + if (!mapBySystemProductId.has(spid)) mapBySystemProductId.set(spid, []); + mapBySystemProductId.get(spid).push({ + receiving_id: Number(row.receiving_id), + receiving_number: String(row.receiving_number || '').trim(), + receiving_detail_id: Number(row.receiving_detail_id), + actual_quantity: Number(row.actual_quantity || 0), + allocated_quantity: Number(row.allocated_quantity || 0), + available_quantity: Number(row.available_quantity || 0), + }); + } + + // 为每个 item 挂载 + return items.map(item => { + const sid = Number(item.stock_id); + const spid = stockIdToSystemProductId.get(sid) || 0; + return { + ...item, + available_receiving_details: spid > 0 ? (mapBySystemProductId.get(spid) || []) : [], + }; + }); + } + + /** + * 归一化作废入参中的入库单 ID 列表。 + * 优先使用 ids;未传 ids 时回退到 id。 + * @param {Object} data 请求体 + * @return {{ ok: boolean, ids?: number[], code?: number, message?: string }} 归一化结果 + */ + normalizeCancelEntryOrderIds(data = {}) { + const hasIdsField = Object.prototype.hasOwnProperty.call(data, 'ids'); + const hasIdField = Object.prototype.hasOwnProperty.call(data, 'id'); + + if (!hasIdsField && !hasIdField) { + return { + ok: false, + code: 400, + message: 'id 或 ids 必填', + }; + } + + const rawIds = hasIdsField ? data.ids : [ data.id ]; + + if (hasIdsField) { + if (!Array.isArray(rawIds) || rawIds.length === 0) { + return { + ok: false, + code: 400, + message: 'ids 必须是非空数组', + }; + } + } else if (!Number.isInteger(Number(rawIds[0])) || Number(rawIds[0]) <= 0) { + return { + ok: false, + code: 400, + message: 'id 必填且必须为正整数', + }; + } + + const normalizedIds = []; + for (const rawId of rawIds) { + const normalizedId = Number(rawId); + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + return { + ok: false, + code: 400, + message: 'ids 必须为正整数数组', + }; + } + normalizedIds.push(normalizedId); + } + + return { + ok: true, + ids: [ ...new Set(normalizedIds) ], + }; + } + + /** + * 查询当前仓库可访问的入库单。 + * 默认仓库取 ctx.user.store_id,外部渠道可通过 warehouseId 显式覆盖。 + * @param {number} id 入库单ID + * @param {number} [warehouseId] 仓库ID,缺省取 ctx.user.store_id + * @return {Promise} 入库单实例 + */ + async getOwnedEntryOrderById(id, warehouseId = null) { + const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId) || Number(ctx.user?.store_id) || 0; + return await ctx.model.EntryOrder.findOne({ + where: { + id, + warehouse_id: normalizedWarehouseId, + is_enabled: 1, + deleted_at: null, + }, + }); + } + + /** + * 作废入库单(系统方法入口与奇门 / openapi 外部渠道共用)。 + * + * 定位方式: + * - 传 data.entryOrderCode(或 data.entry_order_code)时按单号定位,定位条件带 + * is_enabled / deleted_at / warehouse_id,有 storeId 时追加货主条件; + * - 否则回退 data.id / data.ids(系统方法入口口径不变)。 + * + * options 为外部渠道扩展,系统方法入口不传时行为与文案与历史版本完全一致: + * - warehouseId:覆盖仓库上下文(默认 ctx.user.store_id); + * - storeId:有值时参与定位; + * - operatorLabel:覆盖操作人(写入回传与操作日志); + * - skipExternalSync:true 时跳过 QM 来源的 qimenEntrySync 取消回传; + * - idempotent:true 时已作废(CANCELLED)按幂等成功处理; + * - notFoundMessage:未找到时的错误文案(默认「入库单不存在或无权访问」)。 + * + * @param {Object} data 请求体 + * @param {number} [data.id] 单个入库单ID + * @param {number[]} [data.ids] 批量入库单ID数组 + * @param {string} [data.entryOrderCode] 入库单号(外部渠道按单号定位,优先) + * @param {Object} [options] 可选上下文(外部渠道扩展,系统方法入口不传) + * @return {Promise} { code, message, data } 结构 + */ + async cancel(data = {}, options = {}) { + const { ctx } = this; + const { + warehouseId: optWarehouseId, + storeId: optStoreId, + operatorLabel, + skipExternalSync = false, + idempotent = false, + notFoundMessage, + } = options; + + // 仓库上下文:外部渠道通过 options.warehouseId 覆盖,系统方法入口取 ctx.user.store_id + const warehouseId = Number(optWarehouseId) || Number(ctx.user?.store_id) || 0; + + // 操作人:外部渠道通过 options.operatorLabel 覆盖,系统方法入口取 ctx.user + const operator = String(operatorLabel || '').trim() + ? { id: null, name: String(operatorLabel).trim() } + : { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }; + + const notFoundText = String(notFoundMessage || '').trim() || '入库单不存在或无权访问'; + + // 按单号定位(外部渠道),优先于 id / ids + const entryOrderCode = String(data.entryOrderCode || data.entry_order_code || '').trim(); + if (entryOrderCode) { + const where = { + entry_order_code: entryOrderCode, + warehouse_id: warehouseId, + is_enabled: 1, + deleted_at: null, + }; + if (optStoreId !== undefined && optStoreId !== null && optStoreId !== '') { + where.store_id = Number(optStoreId); + } + + const entryOrder = await ctx.model.EntryOrder.findOne({ where }); + if (!entryOrder) { + return { + code: 404, + message: notFoundText, + data: null, + }; + } + + const guard = this._guardCancelEntryOrder(entryOrder, idempotent); + if (guard) { + return { + code: guard.code, + message: guard.message, + data: guard.code === 200 ? { ids: [ entryOrder.id ] } : null, + }; + } + + return await this._doCancelEntryOrder(entryOrder, { operator, skipExternalSync }); + } + + // 按 id / ids 定位(系统方法入口,行为与文案保持不变) + const normalizedResult = this.normalizeCancelEntryOrderIds(data); + if (!normalizedResult.ok) { + return { + code: normalizedResult.code || 400, + message: normalizedResult.message || '参数错误', + data: null, + }; + } + + const orderIds = normalizedResult.ids || []; + + for (const orderId of orderIds) { + const entryOrder = await this.getOwnedEntryOrderById(orderId, warehouseId); + if (!entryOrder) { + return { + code: 404, + message: notFoundText, + data: null, + }; + } + + const guard = this._guardCancelEntryOrder(entryOrder, idempotent); + if (guard) { + if (guard.code === 200) continue; // 幂等:已作废跳过,继续处理剩余单据 + return { + code: guard.code, + message: guard.message, + data: null, + }; + } + + const cancelResult = await this._doCancelEntryOrder(entryOrder, { operator, skipExternalSync }); + if (cancelResult.code !== 200) { + return cancelResult; + } + } + + return { + code: 200, + message: '作废成功', + data: { ids: orderIds }, + }; + } + + /** + * 作废入库单的状态守卫校验。 + * 返回 null 表示允许继续作废;返回 { code, message } 表示拦截; + * 幂等模式下已作废返回 { code: 200 }(由调用方决定跳过或直接成功), + * 且幂等判定优先于回传状态判定(已作废单据的回传状态不影响重试幂等)。 + * @param {Object} entryOrder 入库单实例 + * @param {boolean} idempotent 是否幂等模式(已作废视为成功) + * @return {{ code: number, message: string }|null} 守卫结果 + */ + _guardCancelEntryOrder(entryOrder, idempotent = false) { + // 幂等模式:已作废优先按成功处理(外部渠道重试口径) + if (idempotent && entryOrder.order_status === 'CANCELLED') { + return { + code: 200, + message: '作废成功', + }; + } + + // sync_status=SUCCESS 不可取消 + if (entryOrder.sync_status === 'SUCCESS') { + return { + code: 400, + message: '入库单已完成回传,不可取消', + }; + } + + if (entryOrder.order_status === 'COMPLETED') { + return { + code: 400, + message: '已完成入库单不允许作废', + }; + } + + if (entryOrder.order_status === 'CANCELLED') { + return { + code: 400, + message: '入库单已作废', + }; + } + + return null; + } + + /** + * 执行单个入库单的作废动作:QM 来源发送取消同步(actualQty 全 0)、 + * 状态置 CANCELLED、回退收货单占用、写 ENTRY_ORDER_CANCEL 操作日志。 + * @param {Object} entryOrder 入库单实例 + * @param {Object} [context] 上下文 + * @param {Object} [context.operator] 操作人信息 { id, name } + * @param {boolean} [context.skipExternalSync] 是否跳过 QM 取消同步回传 + * @return {Promise} { code, message, data } 结构 + */ + async _doCancelEntryOrder(entryOrder, context = {}) { + const { ctx } = this; + const { operator = {}, skipExternalSync = false } = context; + + // QM 来源需发送取消同步(外部渠道不回传时跳过) + if (String(entryOrder.source_type) === 'QM' && !skipExternalSync) { + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code' ], + raw: true, + }); + + const orderLines = (entryItems || []).map((item, idx) => ({ + orderLineNo: idx + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: item.count || 0, + actualQty: 0, // 全部为 0,通知 ERP 关闭 + })); + + const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ + entryOrder, + orderLines, + outBizCode: `CANCEL_${Date.now()}`, + remark: '入库单取消', + operator, + }); + + if (!syncResult.success) { + return { + code: 500, + message: `取消失败: ${syncResult.message}`, + data: null, + }; + } + } + + // 更新状态 + await entryOrder.update({ + order_status: 'CANCELLED', + updated_at: new Date(), + }); + + // 回退关联收货单的入库状态,避免死锁 + await this._rollbackReceivingStorageStatus(entryOrder.id); + + // 写操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'ENTRY_ORDER_CANCEL', + operator, + extras: { + warehouseId: entryOrder.warehouse_id, + message: '入库单已取消', + }, + }); + + return { + code: 200, + message: '作废成功', + data: { ids: [ entryOrder.id ] }, + }; + } + + /** + * 回退入库单关联收货单的入库状态(入库单作废时调用)。 + * 按绑定行数量台账逐单回收本入库单在收货单上的占用(不影响其他入库单的占用), + * 并清空台账;失败不阻塞主流程,仅打印日志。 + * @param {number} entryOrderId 入库单ID + * @return {Promise} + */ + async _rollbackReceivingStorageStatus(entryOrderId) { + const { ctx } = this; + try { + const result = await ctx.service.systems.receivingEntryMatch.rollbackEntryOrderBindings({ + entryOrderId, + receivingId: null, + softDeleteBinding: false, + }); + + ctx.logger.info( + `[storage.entry.cancel] 入库单 ${entryOrderId} 作废,已按台账回退收货单入库状态,` + + `rolledBack=${JSON.stringify((result && result.rolled_back) || [])}` + ); + } catch (err) { + ctx.logger.error( + `[storage.entry.cancel] 回退收货单入库状态失败,entryOrderId=${entryOrderId},err=${err.message}` + ); + } + } + + + /** + * 按商品增量添加导入/PDA 直接入库记录(转发到 inboundDirectLog)。 + * @param {Object} data 请求体 + * @param {string} data.entry_order_code 入库单号 + * @param {number} [data.stock_id] 商品SKU ID(单条模式) + * @param {number} [data.quantity] 本次入库数量(单条模式) + * @param {string} [data.inbound_type] 入库方式(单条模式) + * @param {Array} [data.items] 商品列表(批量模式) + * @return {Promise} code/data/message 结构 + */ + async addItem(data = {}) { + const { ctx } = this; + return await ctx.service.systems.inboundDirectLog.addItem(data); + } + + /** + * 提交确认完成导入/PDA 直接入库(转发到 inboundDirectLog)。 + * @param {string} entryOrderCode 入库单号 + * @return {Promise} code/data/message 结构 + */ + async commit(entryOrderCode) { + const { ctx } = this; + return await ctx.service.systems.inboundDirectLog.commit(entryOrderCode); + } + + /** + * 移除一条导入/PDA 直接入库记录(转发到 inboundDirectLog)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库记录ID + * @return {Promise} code/data/message 结构 + */ + async removeItem(data = {}) { + const { ctx } = this; + return await ctx.service.systems.inboundDirectLog.removeItem(data); + } + + /** + * 查询入库单已绑定收货单中匹配指定 stock_id 的收货明细列表。 + * 用于 PDA 导入时选择要绑定的收货明细。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单 ID + * @param {number} data.stock_id 商品 stock_id + * @return {Promise} { code, message, data: { list: [{ receiving_detail_id, receiving_id, receiving_number, actual_quantity, used_quantity, available_quantity, system_product_id }] } } + */ + async getReceivingDetailsForBind(data = {}) { + const { ctx, app } = this; + const entryOrderId = Number(data.entry_order_id); + const stockId = Number(data.stock_id); + + if (!entryOrderId || !stockId) { + return { code: 400, message: 'entry_order_id 和 stock_id 必填', data: null }; + } + + // 1. 查入库单绑定的收货单 ID 列表 + const orderReceivings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrderId, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); + if (!orderReceivings.length) { + return { code: 200, message: 'ok', data: { list: [] } }; + } + const receivingIds = orderReceivings.map(r => r.receiving_id); + + // 2. 查收货明细(system_product_id = stockId,且收货单未取消/未删除) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { + system_product_id: stockId, + receiving_id: receivingIds, + deleted_at: null, + }, + attributes: [ 'id', 'receiving_id', 'actual_quantity', 'system_product_id' ], + include: [{ + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status' ], + where: { status: { [ app.Sequelize.Op.ne ]: 'cancelled' }, deleted_at: null }, + required: true, + }], + raw: false, + }); + + // 3. 查每个明细的已占用数量(pending + committed) + const detailIds = details.map(d => d.id); + const usedMap = new Map(); + if (detailIds.length > 0) { + const usedRows = await ctx.model.query( + `SELECT receiving_detail_id, COALESCE(SUM(quantity), 0) AS used_qty + FROM wms_inbound_direct_log + WHERE receiving_detail_id IN (:ids) + AND status IN ('pending', 'committed') + AND deleted_at IS NULL + GROUP BY receiving_detail_id`, + { + replacements: { ids: detailIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + for (const row of usedRows) { + usedMap.set(row.receiving_detail_id, Number(row.used_qty)); + } + } + + // 4. 组装返回 + const list = details.map(d => { + const rid = d.id; + const used = usedMap.get(rid) || 0; + return { + receiving_detail_id: rid, + receiving_id: d.receiving_id, + receiving_number: d.receiving?.receiving_number || '', + actual_quantity: d.actual_quantity || 0, + used_quantity: used, + available_quantity: Math.max(0, (d.actual_quantity || 0) - used), + system_product_id: d.system_product_id, + }; + }); + + return { code: 200, message: 'ok', data: { list } }; + } + + /** + * 拉取入库单绑定的收货单中,指定商品的可用容器列表(收货明细)。 + * 用于 PDA 上架时选择容器。 + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.stock_id 商品stock_id + * @return {Promise} { code, message, data: { list, total } } + */ + async containerList(data = {}) { + const { ctx, app } = this; + const warehouseId = ctx.user?.store_id; + const entryOrderId = Number(data.entry_order_id); + const stockId = Number(data.stock_id); + + // 参数校验 + if (!warehouseId) { + return { code: 0, message: '用户未绑定仓库', data: null }; + } + if (!entryOrderId || entryOrderId <= 0) { + return { code: 0, message: 'entry_order_id 不能为空', data: null }; + } + if (!stockId || stockId <= 0) { + return { code: 0, message: 'stock_id 不能为空', data: null }; + } + + try { + // 1. 验证入库单存在且属于当前仓库 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + id: entryOrderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!entryOrder) { + return { code: 0, message: '入库单不存在或无权访问', data: null }; + } + + // 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表 + const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrderId, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); + + const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean); + if (receivingIds.length === 0) { + return { code: 200, message: 'ok', data: { list: [], total: 0 } }; + } + + // 3. 查询指定商品的所有收货明细(不再一刀切排除已绑定,改为按可用量过滤) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { + system_product_id: stockId, + receiving_id: { [app.Sequelize.Op.in]: receivingIds }, + }, + raw: true, + }); + + // 4. 查询每个明细的已入库数量(pending + committed,与 getReceivingDetailsForBind 一致) + const detailIds = details.map(d => d.id); + const usedMap = new Map(); + if (detailIds.length > 0) { + const usedRows = await ctx.model.query( + `SELECT receiving_detail_id, COALESCE(SUM(quantity), 0) AS used_qty + FROM wms_inbound_direct_log + WHERE receiving_detail_id IN (:ids) + AND status IN ('pending', 'committed') + AND deleted_at IS NULL + GROUP BY receiving_detail_id`, + { + replacements: { ids: detailIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + for (const row of usedRows) { + usedMap.set(row.receiving_detail_id, Number(row.used_qty)); + } + } + + // 5. 收集所有明细的 system_product_id,批量获取 stock 详情 + const stockIdSet = new Set(); + for (const d of details) { + if (d.system_product_id != null) { + stockIdSet.add(Number(d.system_product_id)); + } + } + const stockIds = [ ...stockIdSet ]; + + /** @type {Map} */ + const stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const sd of stockDetails) { + if (sd && sd.id != null) { + stockDetailMap.set(sd.id, sd); + } + } + } + + // 6. 组装返回结果:actual_quantity 扣除已入库数量,只返回有可用量的明细 + const list = details + .map(detail => { + const used = usedMap.get(detail.id) || 0; + const available = Math.max(0, (detail.actual_quantity || 0) - used); + return { + detail_id: detail.id, + receiving_id: detail.receiving_id, + barcode: detail.barcode || '', + product_name: detail.product_name || '', + actual_quantity: available, + receiving_status: detail.receiving_status || '', + stock: stockDetailMap.get(Number(detail.system_product_id)) || null, + }; + }) + .filter(detail => detail.actual_quantity > 0); + + return { + code: 200, + message: 'ok', + data: { + list, + total: list.length, + }, + }; + } catch (error) { + ctx.logger.error('[storage.entry.containerList] 查询容器列表失败', error); + return { code: 500, message: `服务器错误: ${error.message}`, data: null }; + } + } + + /** + * 快捷直入后回写绑定收货单的明细已入库数量与入库状态(事务内)。 + * 按 stock_id(=收货明细 system_product_id)把本次入库量依次分配到收货明细上, + * 每个明细最多分配其剩余可入数量(actual_quantity - stored_quantity), + * 分配后更新明细 stored_quantity/storage_status,并按各明细实际入库量 + * (stored_quantity 与 actual_quantity 比较)汇总更新收货单主表 storage_status: + * 全部明细均已足量入库才置 all,否则有部分入库置 partial,全部未入库置 none。 + * @param {Object} params 参数 + * @param {Array} params.receivingDetailRows 收货明细快照 [{ id, receiving_id, system_product_id, actual_quantity, stored_quantity }] + * @param {Map} params.stockInboundQtyMap stock_id -> 本次入库量 + * @param {Object} params.transaction Sequelize 事务对象 + * @param {number} [params.entryOrderId] 入库单 ID(传入时同步累加数量台账) + * @return {Promise} + */ + async _applyReceivingInboundUsage({ receivingDetailRows, stockInboundQtyMap, transaction, entryOrderId = null }) { + const { ctx, app } = this; + + if (!receivingDetailRows || receivingDetailRows.length === 0) return; + + // 1. 事务内行锁重新读取收货明细,避免并发超额分配 + const detailIds = receivingDetailRows.map(d => d.id); + const lockedDetails = await ctx.model.ReceivingDetail.findAll({ + where: { id: { [app.Sequelize.Op.in]: detailIds } }, + lock: transaction.LOCK.UPDATE, + order: [[ 'id', 'ASC' ]], + transaction, + raw: true, + }); + + // 2. 按 system_product_id(=stock_id)分组,同一商品多条明细按 id 升序依次分配 + const detailsByStock = new Map(); + for (const d of lockedDetails) { + const spid = Number(d.system_product_id); + if (!spid) continue; + if (!detailsByStock.has(spid)) detailsByStock.set(spid, []); + detailsByStock.get(spid).push(d); + } + + const touchedReceivingIds = new Set(); + const detailDeltaMap = new Map(); + + // 3. 逐商品分配本次入库量:使用了多少就写多少 + for (const [ stockId, plan ] of stockInboundQtyMap) { + let left = Number(plan.inboundQty) || 0; + const details = detailsByStock.get(Number(stockId)) || []; + for (const detail of details) { + if (left <= 0) break; + const actual = Number(detail.actual_quantity) || 0; + const stored = Number(detail.stored_quantity) || 0; + const remain = Math.max(0, actual - stored); + if (remain <= 0) continue; + const delta = Math.min(left, remain); + const newStored = stored + delta; + const storageStatus = newStored >= actual ? 'all' : 'partial'; + await ctx.model.ReceivingDetail.update({ + stored_quantity: newStored, + storage_status: storageStatus, + updated_at: new Date(), + }, { + where: { id: detail.id }, + transaction, + }); + touchedReceivingIds.add(Number(detail.receiving_id)); + detailDeltaMap.set(Number(detail.id), { + receivingId: Number(detail.receiving_id), + quantity: delta, + }); + left -= delta; + } + } + + // 4. 按实际入库量汇总更新收货单主表 storage_status: + // 全部明细均已足量入库(stored >= actual)→ all;存在部分入库 → partial;全部未入库 → none + for (const receivingId of touchedReceivingIds) { + const allDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ 'actual_quantity', 'stored_quantity' ], + raw: true, + transaction, + }); + + let masterStatus = 'none'; + const fullyStored = allDetails.length > 0 + && allDetails.every(d => (Number(d.stored_quantity) || 0) >= (Number(d.actual_quantity) || 0)); + if (fullyStored) { + masterStatus = 'all'; + } else if (allDetails.some(d => (Number(d.stored_quantity) || 0) > 0)) { + masterStatus = 'partial'; + } + + await ctx.model.Receiving.update({ + storage_status: masterStatus, + updated_at: new Date(), + }, { + where: { id: receivingId }, + transaction, + }); + } + + ctx.logger.info( + `[storage.entry] 已回写收货单入库状态,receivingIds=[${[ ...touchedReceivingIds ].join(',')}]` + ); + + // 5. 同步数量台账:本次落到各收货明细的分配量累加到对应绑定行 + if (entryOrderId && detailDeltaMap.size > 0) { + await ctx.service.systems.receivingEntryMatch.recordLedgerAllocation({ + entryOrderId, + detailDeltaMap, + transaction, + }); + } + } + + /** + * 快捷直入/虚拟入库:将入库单明细直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 + * 有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量的部分直入, + * 并回写收货单明细已入库数量;未绑定收货单时按明细计划数量全量直入。 + * 有绑定收货单时回写 is_virtual_inbound=0(非虚拟入库),无绑定收货单时回写 is_virtual_inbound=1(虚拟入库)。 + * 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @param {number} [data.noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0) + * @return {Promise} code/data/message 结构 + */ + async quickInbound(data = {}) { + const { ctx, app } = this; + const orderId = Number(data.id || 0); + const noNeedNotice = Number(data.noNeedNotice) || 0; + + if (!orderId) { + return { + code: 400, + message: 'id 必填', + data: null, + }; + } + + // 1. 校验入库单 + const entryOrder = await this.getOwnedEntryOrderById(orderId); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + + if (entryOrder.order_status !== 'CREATED') { + if (entryOrder.order_status === 'CANCELLED') { + return { + code: 400, + message: '已作废入库单不允许快捷入库', + data: null, + }; + } + if (entryOrder.order_status === 'COMPLETED') { + return { + code: 400, + message: '入库单已完成,请勿重复提交', + data: null, + }; + } + return { + code: 400, + message: `入库单状态不允许快捷直入,当前状态:${entryOrder.order_status}`, + data: null, + }; + } + + // 2. 查询入库单所有明细 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + }); + + if (!entryItems.length) { + return { + code: 400, + message: '请先添加入库明细', + data: null, + }; + } + + // 2.1 查询绑定收货单("已绑定"状态),按 stock_id 聚合收货明细剩余可入数量 + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); + const receivingIds = [ ...new Set((bindings || []).map(b => Number(b.receiving_id)).filter(Boolean)) ]; + + // 收货明细快照(用于事务内行锁回写),stockRemainingMap: null=未绑定(全量直入) + let receivingDetailsSnapshot = []; + let stockRemainingMap = null; + if (receivingIds.length > 0) { + const boundDetails = await ctx.model.ReceivingDetail.findAll({ + where: { + receiving_id: { [app.Sequelize.Op.in]: receivingIds }, + system_product_id: { [app.Sequelize.Op.ne]: null }, + }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ], + raw: true, + }); + receivingDetailsSnapshot = boundDetails; + stockRemainingMap = new Map(); + for (const d of boundDetails) { + const spid = Number(d.system_product_id); + const remaining = Math.max(0, (Number(d.actual_quantity) || 0) - (Number(d.stored_quantity) || 0)); + stockRemainingMap.set(spid, (stockRemainingMap.get(spid) || 0) + remaining); + } + } + + // 2.2 按入库单明细计算实际直入数量:有绑定时只取收货单中有交集(stock_id)且剩余可入的数量 + const inboundPlans = entryItems.map(item => { + const planQty = Number(item.count) || 0; + let inboundQty = planQty; + if (stockRemainingMap) { + const stockId = Number(item.stock_id) || 0; + if (!stockId || !stockRemainingMap.has(stockId)) { + inboundQty = 0; // 收货单无交集商品,跳过 + } else { + const remaining = stockRemainingMap.get(stockId) || 0; + inboundQty = Math.min(planQty, remaining); + stockRemainingMap.set(stockId, remaining - inboundQty); + } + } + return { item, planQty, inboundQty }; + }); + + const effectivePlans = inboundPlans.filter(p => p.inboundQty > 0); + if (effectivePlans.length === 0) { + return { + code: 400, + message: stockRemainingMap + ? '收货单中无交集商品或剩余可入数量不足,无法快捷直入' + : '入库明细数量均为0,无法快捷直入', + data: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code }, + }; + } + + // 存在被截断/跳过的明细时按部分入库回传(confirmType=1, PARTFULFILLED) + const isPartialInbound = inboundPlans.some(p => p.inboundQty < p.planQty); + + // ===== 阶段一 + 阶段二合并为统一调用 ===== + const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ + entryOrder, + orderLines: effectivePlans.map((plan, idx) => ({ + orderLineNo: idx + 1, + ownerCode: plan.item.owner_code || '', + itemCode: plan.item.item_code || '', + itemId: plan.item.item_id || '', + inventoryType: plan.item.inventory_type || 'ZP', + planQty: plan.planQty, + actualQty: plan.inboundQty, + })), + isFin: !isPartialInbound, + outBizCode: `DIRECT_INBOUND_${Date.now()}`, + remark: '导入/PDA直接入库提交', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + onSuccess: async eo => { + const warehouseId = eo.warehouse_id; + const storeId = eo.store_id; + const batchNo = eo.entry_order_code; + const hardcodedSpaceId = 2; + const transaction = await ctx.model.transaction(); + + const processedStockIds = new Set(); + let totalInboundQty = 0; + let totalPlanQty = 0; + + // 按 stock_id 汇总本次实际入库量与库存类型(有绑定收货单时实际入库量 ≤ 计划量) + const stockPlanMap = new Map(); + for (const plan of inboundPlans) { + totalPlanQty += plan.planQty; + if (plan.inboundQty <= 0) continue; + const stockId = Number(plan.item.stock_id); + if (!stockId) continue; + const cur = stockPlanMap.get(stockId) || { inboundQty: 0, inventoryType: plan.item.inventory_type || 'ZP' }; + cur.inboundQty += plan.inboundQty; + stockPlanMap.set(stockId, cur); + totalInboundQty += plan.inboundQty; + } + + if (totalInboundQty <= 0) { + throw new Error('无有效可入明细,快捷直入失败'); + } + + try { + // 回写入库单明细:本次实际入库多少写多少(跳过明细写 0) + for (const plan of inboundPlans) { + await ctx.model.EntryItems.update({ + received_quantity: plan.inboundQty, + }, { + where: { id: plan.item.id }, + transaction, + }); + } + + for (const [ stockId, plan ] of stockPlanMap) { + const planQty = plan.inboundQty; + const inventoryType = plan.inventoryType; + + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!stockRecord) { + throw new Error(`商品库存记录不存在或已失效,无法入库: stock_id=${stockId}`); + } + + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await stockRecord.increment('quantity', { by: planQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + // 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据) + if (beforeQuantity <= 0) { + const nonNegativeDelta = Math.max(0, Number(stockRecord.quantity) || 0) - Math.max(0, beforeQuantity); + await ctx.service.systems.storage.index.offsetGapOnInbound(stockId, planQty, { + transaction, + maxOffset: nonNegativeDelta, + orderNo: eo.entry_order_code || 'QUICK_INBOUND', + orderId: eo.id, + operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''), + operatorName: ctx.user?.employees_name || '', + }); + } + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: planQty, + batch_no: batchNo, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '快捷直入/虚拟入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + + const storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let storageId = null; + let storageBeforeQty = 0; + let storageAfterQty = 0; + let storageBeforeLockedQty = 0; + let storageAfterLockedQty = 0; + let storageBeforeInterceptQty = 0; + let storageAfterInterceptQty = 0; + + if (storageRecord) { + storageBeforeQty = Number(storageRecord.quantity) || 0; + storageAfterQty = storageBeforeQty + planQty; + storageBeforeLockedQty = Number(storageRecord.locked_quantity) || 0; + storageAfterLockedQty = storageBeforeLockedQty; + storageBeforeInterceptQty = Number(storageRecord.intercept_locked_quantity) || 0; + storageAfterInterceptQty = storageBeforeInterceptQty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${planQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${planQty}`), + entry_order_id: eo.id, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + updated_at: new Date(), + }, { + where: { id: storageRecord.id }, + transaction, + }); + storageId = storageRecord.id; + } else { + storageBeforeQty = 0; + storageAfterQty = planQty; + storageBeforeLockedQty = 0; + storageAfterLockedQty = 0; + + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: planQty, + locked_quantity: 0, + available_quantity: planQty, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + receiving_id: null, + entry_order_id: eo.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + storageId = createdStorage.id; + } + + // 写入库位维度库存流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + storage_id: storageId, + space_id: hardcodedSpaceId, + quantity: planQty, + before_quantity: storageBeforeQty, + after_quantity: storageAfterQty, + before_locked_quantity: storageBeforeLockedQty, + after_locked_quantity: storageAfterLockedQty, + before_intercept_locked_quantity: storageBeforeInterceptQty, + after_intercept_locked_quantity: storageAfterInterceptQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: 'entry_order', + order_no: eo.entry_order_code, + order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '快捷直入/虚拟入库', + created_at: new Date(), + }, { transaction }); + } + + // 回写绑定收货单明细已入库数量与入库状态(有绑定收货单时) + if (receivingDetailsSnapshot.length > 0) { + await this._applyReceivingInboundUsage({ + receivingDetailRows: receivingDetailsSnapshot, + stockInboundQtyMap: stockPlanMap, + transaction, + entryOrderId: eo.id, + }); + } + + await eo.update({ + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + // 有绑定收货单 → 非虚拟入库(0);无绑定收货单 → 虚拟入库(1) + is_virtual_inbound: receivingIds.length > 0 ? 0 : 1, + sync_message: JSON.stringify({ + completedAt: new Date(), + totalQuantity: totalInboundQty, + planQuantity: totalPlanQty, + itemCount: processedStockIds.size, + source: 'quick_inbound', + }), + updated_at: new Date(), + }, { transaction }); + + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: eo.id, + operationCode: 'QUICK_INBOUND', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: eo.warehouse_id, + message: `快捷直入完成,共 ${processedStockIds.size} 种商品,总数量 ${totalInboundQty}`, + }, + transaction, + }); + + await transaction.commit(); + + // 入库完成通知货主(失败不影响主流程);noNeedNotice=1 时跳过通知 + if (noNeedNotice !== 1) { + try { + await ctx.service.systems.inboundDirectLog.notifyEntryOrderCompleted(eo); + } catch (noticeErr) { + ctx.logger.warn('[storage.entry.quickInbound] 入库完成通知货主失败,不影响业务', noticeErr); + } + } + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; + } + }, + }); + + if (!syncResult.success) { + return { + code: 500, + message: syncResult.message, + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + sync_status: 'FAILED', + }, + }; + } + + return { + code: 200, + message: '快捷入库完成', + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + items_count: effectivePlans.length, + total_quantity: effectivePlans.reduce((s, p) => s + p.inboundQty, 0), + plan_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0), + }, + }; + } + + /** + * 入库单商品与收货单商品对照视图(支持多个收货单)。 + * 以入库单明细为对比主体:多个收货单的明细先合并为一个整体, + * 再与入库单明细做一次对照,每个入库明细只输出一行, + * 避免多收货单时入库计划数量被重复展开。 + * + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单ID + * @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用) + * @param {number} [data.receiving_id] 单个收货单ID(向后兼容,receiving_ids 优先) + * @return {Promise} code/data/message 结构 + */ + async receivingCompare(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const entryOrderId = Number(data.entry_order_id || 0); + const warehouseId = ctx.user.store_id; + + // 入参处理:receiving_ids 优先,receiving_id 向后兼容 + let receivingIds = data.receiving_ids; + if (!Array.isArray(receivingIds) || receivingIds.length === 0) { + const singleId = Number(data.receiving_id || 0); + if (singleId) { + receivingIds = [ singleId ]; + } else { + return { code: 400, message: 'receiving_ids 或 receiving_id 必填', data: null }; + } + } + receivingIds = [ ...new Set(receivingIds.map(id => Number(id)).filter(Boolean)) ]; + + if (!entryOrderId) { + return { code: 400, message: 'entry_order_id 必填', data: null }; + } + + // 1. 校验入库单存在性 + const entryOrder = await this.getOwnedEntryOrderById(entryOrderId); + if (!entryOrder) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + + // 2. 查询入库单明细 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], + raw: true, + }); + + // 3. 批量校验收货单(同仓库、未删除),无效的进入 errors + const receivingOrders = await ctx.model.Receiving.findAll({ + where: { + id: { [Op.in]: receivingIds }, + warehouse_id: warehouseId, + is_deleted: false, + }, + attributes: [ 'id', 'receiving_number' ], + raw: true, + }); + const receivingOrderMap = new Map(receivingOrders.map(row => [ Number(row.id), row ])); + const errors = []; + for (const receivingId of receivingIds) { + if (!receivingOrderMap.has(receivingId)) { + errors.push({ + receiving_id: receivingId, + status: 'error', + error_code: 'RECEIVING_NOT_FOUND', + error_message: '收货单不存在或无权访问', + }); + } + } + const validReceivingIds = [ ...receivingOrderMap.keys() ]; + + // 4. 合并所有有效收货单的明细,再与入库单做一次对照 + let receivingDetails = []; + if (validReceivingIds.length > 0) { + receivingDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [Op.in]: validReceivingIds } }, + attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'product_name' ], + raw: true, + }); + } + + const merged = await this._buildMergedComparison({ + warehouseId, + entryItems, + receivingDetails, + receivingOrderMap, + }); + + return { + code: 200, + message: '查询成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrder.entry_order_code, + comparison: merged.comparison, + receiving_only: merged.receivingOnly, + summary: merged.summary, + errors, + total_summary: { + total_receivings: receivingIds.length, + matched_count: validReceivingIds.length, + error_count: errors.length, + }, + }, + }; + } + + /** + * 将多个收货单的明细合并后,与入库单明细做一次对照。 + * 每个入库明细只输出一行(matched/entry_only),匹配时合并各收货单数量, + * 并通过 receiving_sources 列出各收货单来源明细。 + * + * @param {Object} params 参数 + * @param {number} params.warehouseId 仓库ID + * @param {Object[]} params.entryItems 入库单明细列表 + * @param {Object[]} params.receivingDetails 已合并的收货单明细列表 + * @param {Map} params.receivingOrderMap 有效收货单 Map(id → 收货单记录) + * @return {Promise} { comparison, receivingOnly, summary } + */ + async _buildMergedComparison(params = {}) { + const { ctx, app } = this; + const { warehouseId, entryItems, receivingDetails, receivingOrderMap } = params; + + // 收集所有 stock_id,批量查询商品信息 + const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ]; + const receivingSystemProductIds = [ ...new Set(receivingDetails.map(d => Number(d.system_product_id)).filter(Boolean)) ]; + const allStockIds = [ ...new Set([ ...entryStockIds, ...receivingSystemProductIds ]) ]; + const stockDetailMap = new Map(); + if (allStockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(allStockIds, { warehouseId }); + for (const detail of stockDetails) { + stockDetailMap.set(Number(detail.id), detail); + } + } + + // 仓库范围内有效的入库商品 stock_id(与原逻辑一致:仅匹配本仓库库存记录) + const validEntryStockIds = new Set(entryStockIds); + if (entryStockIds.length > 0) { + const swRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: entryStockIds }, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + validEntryStockIds.clear(); + for (const row of swRows) { + validEntryStockIds.add(Number(row.id)); + } + } + + // 查询已分配量(限定本入库单的 entry_items,避免全局绑定干扰) + const receivingDetailIds = receivingDetails.map(d => Number(d.id)); + const entryItemIds = entryItems.map(ei => Number(ei.id)); + const allocatedMap = new Map(); + if (receivingDetailIds.length > 0 && entryItemIds.length > 0) { + const bindingRows = await ctx.model.InboundDirectLog.findAll({ + attributes: [ + 'receiving_detail_id', + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_allocated' ], + ], + where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + receiving_detail_id: { [app.Sequelize.Op.in]: receivingDetailIds }, + status: { [app.Sequelize.Op.in]: [ 'pending', 'committed' ] }, + deleted_at: null, + }, + group: [ 'receiving_detail_id' ], + raw: true, + }); + for (const row of bindingRows) { + allocatedMap.set(Number(row.receiving_detail_id), Number(row.total_allocated) || 0); + } + } + + // 按 stock_id 索引收货明细,供合并匹配 + const detailsByStockId = new Map(); + for (const rd of receivingDetails) { + const stockId = Number(rd.system_product_id) || 0; + if (stockId <= 0) continue; + if (!detailsByStockId.has(stockId)) { + detailsByStockId.set(stockId, []); + } + detailsByStockId.get(stockId).push(rd); + } + + // 组装单个收货明细的来源信息 + const buildSource = rd => { + const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; + const allocated = allocatedMap.get(Number(rd.id)) || 0; + const quantity = Number(rd.actual_quantity) || 0; + return { + receiving_id: Number(rd.receiving_id), + receiving_number: (receivingOrderMap.get(Number(rd.receiving_id)) || {}).receiving_number || '', + receiving_detail_id: Number(rd.id), + receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '', + receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '', + receiving_actual_quantity: quantity, + receiving_allocated: allocated, + receiving_available: Math.max(0, quantity - allocated), + }; + }; + + // 构建对照视图:以入库单明细为主,每个入库明细只输出一行 + const comparison = []; + const matchedReceivingDetailIds = new Set(); + + for (const entryItem of entryItems) { + const stockId = Number(entryItem.stock_id || 0); + const stockDetail = stockDetailMap.get(stockId) || null; + const matchedDetails = stockId > 0 && validEntryStockIds.has(stockId) + ? (detailsByStockId.get(stockId) || []) + : []; + + if (matchedDetails.length > 0) { + const sources = []; + for (const rd of matchedDetails) { + matchedReceivingDetailIds.add(Number(rd.id)); + sources.push(buildSource(rd)); + } + const mergedQuantity = sources.reduce((sum, source) => sum + source.receiving_actual_quantity, 0); + const mergedAllocated = sources.reduce((sum, source) => sum + source.receiving_allocated, 0); + comparison.push({ + entry_item_id: Number(entryItem.id), + stock_id: stockId, + warehouse_item_code: (stockDetail && stockDetail.item_code) || '', + warehouse_item_name: (stockDetail && stockDetail.item_name) || '', + warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', + entry_count: Number(entryItem.count) || 0, + entry_received: Number(entryItem.received_quantity) || 0, + match_status: 'matched', + receiving_quantity: mergedQuantity, + receiving_allocated: mergedAllocated, + receiving_available: Math.max(0, mergedQuantity - mergedAllocated), + receiving_sources: sources, + }); + } else { + comparison.push({ + entry_item_id: Number(entryItem.id), + stock_id: stockId, + warehouse_item_code: (stockDetail && stockDetail.item_code) || '', + warehouse_item_name: (stockDetail && stockDetail.item_name) || '', + warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', + entry_count: Number(entryItem.count) || 0, + entry_received: Number(entryItem.received_quantity) || 0, + match_status: 'entry_only', + receiving_quantity: 0, + receiving_allocated: 0, + receiving_available: 0, + receiving_sources: [], + }); + } + } + + // 收货单中多余的商品(合并后仍未匹配到任何入库明细的收货明细,按商品合并) + const receivingOnlyMap = new Map(); + for (const rd of receivingDetails) { + if (matchedReceivingDetailIds.has(Number(rd.id))) continue; + const stockId = rd.system_product_id != null ? Number(rd.system_product_id) : null; + const source = buildSource(rd); + const key = stockId === null || Number.isNaN(stockId) ? '__none__' : String(stockId); + if (receivingOnlyMap.has(key)) { + const existing = receivingOnlyMap.get(key); + existing.receiving_actual_quantity += source.receiving_actual_quantity; + existing.receiving_allocated += source.receiving_allocated; + existing.receiving_available = Math.max(0, existing.receiving_available + source.receiving_available); + if (!existing.receiving_product_name && source.receiving_product_name) { + existing.receiving_product_name = source.receiving_product_name; + } + existing.receiving_sources.push(source); + } else { + receivingOnlyMap.set(key, { + stock_id: stockId, + receiving_product_code: source.receiving_product_code, + receiving_product_name: source.receiving_product_name, + receiving_actual_quantity: source.receiving_actual_quantity, + receiving_allocated: source.receiving_allocated, + receiving_available: source.receiving_available, + receiving_sources: [ source ], + }); + } + } + const receivingOnly = [ ...receivingOnlyMap.values() ]; + + // 汇总 + const matchedItems = comparison.filter(c => c.match_status === 'matched').length; + const entryOnlyItems = comparison.filter(c => c.match_status === 'entry_only').length; + + return { + comparison, + receivingOnly, + summary: { + total_entry_items: entryItems.length, + matched_items: matchedItems, + entry_only_items: entryOnlyItems, + receiving_only_items: receivingOnly.length, + }, + }; + } + + /** + * 导出入库单列表及明细(两 Sheet)。 + * Sheet1: 入库单列表(wms_entry_order 关键字段) + * Sheet2: 入库单明细(wms_entry_items + wms_stock_warehouse) + * + * @param {Object} options 导出参数 + * @param {Object} [options.where] 筛选条件(与 list 一致) + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportEntryOrders(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = this.isPlainObject ? (this.isPlainObject(options) ? options : {}) : (options && typeof options === 'object' ? options : {}); + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + throw new Error('用户未绑定仓库,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'entry_order_code', 'order_type', 'order_status', + 'order_create_time', 'created_at', 'updated_at', 'total_order_lines', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + const baseWhere = { warehouse_id: warehouseId, is_enabled: 1, deleted_at: null }; + + // ---- 复用 list 的 where 构建逻辑 ---- + const normalizedWhere = { ...where }; + const { + where: parsedSourceWhere, + extraConditions, + errorMessage, + } = await this.preprocessEntryListWhere(normalizedWhere); + + if (errorMessage) { + throw new Error(errorMessage); + } + + const parsed = parseWhereConditions({ + where: parsedSourceWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + const parsedResult = parsed.result; + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || parsedSourceWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : null; + + const andConditions = [ baseWhere ]; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const kw = String(quickWhereValue).trim(); + const receivingDetailId = Number(kw); + const escapedKw = app.model.escape(`%${kw}%`); + const orConditions = [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving r ON r.id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND r.receiving_number LIKE ${escapedKw} + )` + ), 1), + ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND rd.id = ${receivingDetailId} + )` + ), 1), + ] : []), + ]; + andConditions.push({ [Op.or]: orConditions }); + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + if (extraConditions.length > 0) { + andConditions.push({ [Op.and]: extraConditions }); + } + + const finalWhere = { [Op.and]: andConditions }; + + // ---- 分页拉取入库单列表 ---- + const pageSize = ENTRY_EXPORT_PAGE_SIZE; + const totalCount = await ctx.model.EntryOrder.count({ where: finalWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 90, + message: totalCount > 0 ? `已命中 ${totalCount} 条入库单,开始导出` : '未命中数据,开始生成空文件', + }); + + // 收集所有入库单 ID,供后续批量查明细 + const allEntryOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.EntryOrder.findAll({ + where: finalWhere, + order: [[ actualSortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allEntryOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取入库单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + // 收集所有入库单 ID + const allEntryOrderIds = allEntryOrders.map(r => Number(r.id)).filter(Boolean); + + // ---- 分批拉取入库单明细 ---- + /** @type {Map>} entry_order_id → items */ + const itemsMap = new Map(); + /** @type {Set} 所有涉及的商品 stock_id */ + const allStockIds = new Set(); + + if (allEntryOrderIds.length > 0) { + const batchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allEntryOrderIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += batchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + batchSize); + + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: { [Op.in]: batchIds } }, + order: [[ 'order_id', 'ASC' ], [ 'order_line_no', 'ASC' ]], + raw: true, + }); + + for (const item of items) { + const eid = Number(item.order_id); + if (!itemsMap.has(eid)) { + itemsMap.set(eid, []); + } + itemsMap.get(eid).push(item); + if (item.stock_id) { + allStockIds.add(Number(item.stock_id)); + } + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取入库单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + // ---- 批量查询商品名称(wms_stock_warehouse) ---- + /** @type {Map} stock_id → { item_name, sku_property, item_code } */ + const stockInfoMap = new Map(); + if (allStockIds.size > 0) { + const stockIdsArr = [ ...allStockIds ]; + try { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIdsArr }, warehouse_id: warehouseId }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + raw: true, + }); + for (const s of stockRows) { + stockInfoMap.set(Number(s.id), { + item_code: s.item_code || '', + item_name: s.item_name || '', + sku_property: s.sku_property || '', + }); + } + } catch (err) { + ctx.logger.warn(`[exportEntryOrders] 批量查询商品信息失败: ${err.message}`); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-entry-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `入库单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + // Sheet 1: 入库单列表 + const sheet1 = workbook.addWorksheet('入库单列表'); + const entryOrderColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '业务类型', key: 'order_type', width: 10 }, + { header: '采购单号', key: 'purchase_order_code', width: 22 }, + { header: '订单状态', key: 'order_status', width: 12 }, + { header: '供应商编码', key: 'supplier_code', width: 16 }, + { header: '供应商名称', key: 'supplier_name', width: 24 }, + { header: '物流公司', key: 'logistics_name', width: 20 }, + { header: '运单号', key: 'express_code', width: 22 }, + { header: '货主', key: 'store_name', width: 24 }, + { header: '仓库', key: 'warehouse_name', width: 24 }, + { header: '总行数', key: 'total_order_lines', width: 10 }, + { header: '来源类型', key: 'source_type', width: 10 }, + { header: '状态', key: 'sync_status', width: 12 }, + { header: 'ERP备注', key: 'remark', width: 30 }, + { header: '费用记录', key: 'expense_record', width: 10 }, + { header: '预期到货时间', key: 'expect_start_time', width: 20 }, + { header: '最迟预期到货时间', key: 'expect_end_time', width: 20 }, + { header: '订单创建时间', key: 'order_create_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = entryOrderColumns; + + const statusLabelMap = { + CREATING: '创建中', + CREATED: '已创建', + PENDING: '已审核', + COMPLETED: '已完成', + CANCELLED: '已作废', + }; + + const syncStatusLabelMap = { + PENDING: '待同步', + SUCCESS: '成功', + FAILED: '失败', + }; + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const orderTypeLabelMap = { + SCRK: '收货入库', + LYRK: '领用入库', + CCRK: '残次入库', + CGRK: '采购入库', + DBRK: '调拨入库', + QTRK: '其他入库', + B2BRK: 'B2B入库', + XNRK: '虚拟入库', + SHRK: '损耗入库', + }; + + for (const row of allEntryOrders) { + sheet1.addRow({ + entry_order_code: normalizeCellValue(row.entry_order_code), + order_type: orderTypeLabelMap[row.order_type] || row.order_type || '', + purchase_order_code: normalizeCellValue(row.purchase_order_code), + order_status: statusLabelMap[row.order_status] || row.order_status || '', + supplier_code: normalizeCellValue(row.supplier_code), + supplier_name: normalizeCellValue(row.supplier_name), + logistics_name: normalizeCellValue(row.logistics_name), + express_code: normalizeCellValue(row.express_code), + store_name: normalizeCellValue(row.store_name), + warehouse_name: normalizeCellValue(row.warehouse_name), + total_order_lines: row.total_order_lines, + source_type: normalizeCellValue(row.source_type), + sync_status: syncStatusLabelMap[row.sync_status] || row.sync_status || '', + remark: normalizeCellValue(row.remark), + expense_record: row.expense_record === 1 ? '是' : (row.expense_record === 0 ? '否' : ''), + expect_start_time: normalizeCellValue(row.expect_start_time), + expect_end_time: normalizeCellValue(row.expect_end_time), + order_create_time: normalizeCellValue(row.order_create_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入入库单明细...', + }); + + // Sheet 2: 入库单明细 + const sheet2 = workbook.addWorksheet('入库单明细'); + const entryItemColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '入库单ID', key: 'entry_order_id', width: 12 }, + { header: '行号', key: 'order_line_no', width: 8 }, + { header: '商品编码', key: 'item_code', width: 20 }, + { header: '商品名称', key: 'item_name', width: 28 }, + { header: '商品规格', key: 'sku_property', width: 24 }, + { header: '计划入库数量', key: 'plan_quantity', width: 14 }, + { header: '已收货数量', key: 'received_quantity', width: 14 }, + { header: '已通知数量', key: 'confirm_quantity', width: 14 }, + { header: '库存类型', key: 'inventory_type', width: 14 }, + { header: '外部业务编码', key: 'out_biz_code', width: 24 }, + { header: '货主编码', key: 'owner_code', width: 16 }, + { header: '商品ID', key: 'item_id', width: 12 }, + { header: '商品SKU ID', key: 'stock_id', width: 12 }, + ]; + sheet2.columns = entryItemColumns; + + // 构建 entry_order_code 映射 + const entryOrderCodeMap = new Map(); + for (const row of allEntryOrders) { + entryOrderCodeMap.set(Number(row.id), row.entry_order_code || ''); + } + + // 按入库单分页写入明细 + const itemBatchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalEntryOrders = allEntryOrderIds.length; + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += itemBatchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const eid of batchIds) { + const entryOrderCode = entryOrderCodeMap.get(eid) || ''; + const items = itemsMap.get(eid) || []; + + for (const item of items) { + const stockId = Number(item.stock_id || 0); + const stockInfo = stockInfoMap.get(stockId) || {}; + + sheet2.addRow({ + entry_order_code: entryOrderCode, + entry_order_id: eid, + order_line_no: item.order_line_no ?? '', + item_code: stockInfo.item_code || item.item_code || '', + item_name: stockInfo.item_name || '', + sku_property: stockInfo.sku_property || '', + plan_quantity: item.count ?? 0, + received_quantity: item.received_quantity ?? 0, + confirm_quantity: item.confirm_quantity ?? 0, + inventory_type: normalizeCellValue(item.inventory_type), + out_biz_code: normalizeCellValue(item.out_biz_code), + owner_code: normalizeCellValue(item.owner_code), + item_id: normalizeCellValue(item.item_id), + stock_id: item.stock_id ?? '', + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalEntryOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入入库单明细,已完成 ${itemWrittenCount}/${totalEntryOrders} 条入库单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/entry/${warehouseId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'entryExport', + businessId: `${warehouseId}`, + uploaderType: ctx?.user?.role || 'system_api', + uploaderDept: ctx?.user?.department || '', + }); + } + + const result = { + filename, + fileKey: uploadResult.fileName, + url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '', + cdnUrl: uploadResult.cdnUrl || uploadResult.url || '', + cosUrl: uploadResult.cosUrl || '', + total_count: totalCount, + fileRecord: fileRecord?.data || fileRecord || null, + }; + + // 清理临时目录 + await fsp.rm(tempDir, { recursive: true, force: true }); + + await progressHandler({ + status: 'success', + progress: 100, + message: '导出完成', + result, + }); + + return result; + } + + /** + * 导出货主侧入库单列表(双 sheet:入库单列表 + 入库单明细)。 + * 复用 list 的筛选与排序语义,以货主维度(store_id)过滤,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件(与 listStore 一致) + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportStoreEntryOrders(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = options && typeof options === 'object' ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + const storeId = Number(ctx.user && ctx.user.store_id); + if (!storeId) { + throw new Error('用户未绑定货主,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'entry_order_code', 'order_type', 'order_status', + 'order_create_time', 'created_at', 'updated_at', 'total_order_lines', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + const baseWhere = { store_id: storeId, is_enabled: 1, deleted_at: null }; + + // ---- 复用 listStore 的 where 构建逻辑 ---- + const normalizedWhere = { ...where }; + const { + where: parsedSourceWhere, + extraConditions, + errorMessage, + } = await this.preprocessEntryListWhere(normalizedWhere); + + if (errorMessage) { + throw new Error(errorMessage); + } + + const parsed = parseWhereConditions({ + where: parsedSourceWhere, + app, + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + const parsedResult = parsed.result; + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || parsedSourceWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : null; + + const andConditions = [ baseWhere ]; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const kw = String(quickWhereValue).trim(); + const receivingDetailId = Number(kw); + const escapedKw = app.model.escape(`%${kw}%`); + const orConditions = [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving r ON r.id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND r.receiving_number LIKE ${escapedKw} + )` + ), 1), + ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND rd.id = ${receivingDetailId} + )` + ), 1), + ] : []), + ]; + andConditions.push({ [Op.or]: orConditions }); + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + if (extraConditions.length > 0) { + andConditions.push({ [Op.and]: extraConditions }); + } + + const finalWhere = { [Op.and]: andConditions }; + + // ---- 分页拉取入库单列表 ---- + const pageSize = ENTRY_EXPORT_PAGE_SIZE; + const totalCount = await ctx.model.EntryOrder.count({ where: finalWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 90, + message: totalCount > 0 ? `已命中 ${totalCount} 条货主侧入库单,开始导出` : '未命中数据,开始生成空文件', + }); + + const allEntryOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.EntryOrder.findAll({ + where: finalWhere, + order: [[ actualSortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allEntryOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取货主侧入库单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + const allEntryOrderIds = allEntryOrders.map(r => Number(r.id)).filter(Boolean); + + // ---- 分批拉取入库单明细 ---- + /** @type {Map>} */ + const itemsMap = new Map(); + /** @type {Set} */ + const allStockIds = new Set(); + + if (allEntryOrderIds.length > 0) { + const batchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allEntryOrderIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += batchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + batchSize); + + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: { [Op.in]: batchIds } }, + order: [[ 'order_id', 'ASC' ], [ 'order_line_no', 'ASC' ]], + raw: true, + }); + + for (const item of items) { + const eid = Number(item.order_id); + if (!itemsMap.has(eid)) { + itemsMap.set(eid, []); + } + itemsMap.get(eid).push(item); + if (item.stock_id) { + allStockIds.add(Number(item.stock_id)); + } + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取货主侧入库单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + // ---- 批量查询商品名称(按 store_id) ---- + /** @type {Map} */ + const stockInfoMap = new Map(); + if (allStockIds.size > 0) { + const stockIdsArr = [ ...allStockIds ]; + try { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIdsArr }, store_id: storeId }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + raw: true, + }); + for (const s of stockRows) { + stockInfoMap.set(Number(s.id), { + item_code: s.item_code || '', + item_name: s.item_name || '', + sku_property: s.sku_property || '', + }); + } + } catch (err) { + ctx.logger.warn(`[exportStoreEntryOrders] 批量查询商品信息失败: ${err.message}`); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-store-entry-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `货主侧入库单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const statusLabelMap = { + CREATING: '创建中', + CREATED: '已创建', + PENDING: '已审核', + COMPLETED: '已完成', + CANCELLED: '已作废', + }; + + const syncStatusLabelMap = { + PENDING: '待同步', + SUCCESS: '成功', + FAILED: '失败', + }; + + const orderTypeLabelMap = { + SCRK: '收货入库', + LYRK: '领用入库', + CCRK: '残次入库', + CGRK: '采购入库', + DBRK: '调拨入库', + QTRK: '其他入库', + B2BRK: 'B2B入库', + XNRK: '虚拟入库', + SHRK: '损耗入库', + }; + + // Sheet 1: 入库单列表(货主侧,不显示仓库字段) + const sheet1 = workbook.addWorksheet('入库单列表'); + const entryOrderColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '业务类型', key: 'order_type', width: 10 }, + { header: '采购单号', key: 'purchase_order_code', width: 22 }, + { header: '订单状态', key: 'order_status', width: 12 }, + { header: '供应商编码', key: 'supplier_code', width: 16 }, + { header: '供应商名称', key: 'supplier_name', width: 24 }, + { header: '物流公司', key: 'logistics_name', width: 20 }, + { header: '运单号', key: 'express_code', width: 22 }, + { header: '仓库', key: 'warehouse_name', width: 24 }, + { header: '总行数', key: 'total_order_lines', width: 10 }, + { header: '来源类型', key: 'source_type', width: 10 }, + { header: '状态', key: 'sync_status', width: 12 }, + { header: 'ERP备注', key: 'remark', width: 30 }, + { header: '费用记录', key: 'expense_record', width: 10 }, + { header: '预期到货时间', key: 'expect_start_time', width: 20 }, + { header: '最迟预期到货时间', key: 'expect_end_time', width: 20 }, + { header: '订单创建时间', key: 'order_create_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = entryOrderColumns; + + for (const row of allEntryOrders) { + sheet1.addRow({ + entry_order_code: normalizeCellValue(row.entry_order_code), + order_type: orderTypeLabelMap[row.order_type] || row.order_type || '', + purchase_order_code: normalizeCellValue(row.purchase_order_code), + order_status: statusLabelMap[row.order_status] || row.order_status || '', + supplier_code: normalizeCellValue(row.supplier_code), + supplier_name: normalizeCellValue(row.supplier_name), + logistics_name: normalizeCellValue(row.logistics_name), + express_code: normalizeCellValue(row.express_code), + warehouse_name: normalizeCellValue(row.warehouse_name), + total_order_lines: row.total_order_lines, + source_type: normalizeCellValue(row.source_type), + sync_status: syncStatusLabelMap[row.sync_status] || row.sync_status || '', + remark: normalizeCellValue(row.remark), + expense_record: row.expense_record === 1 ? '是' : (row.expense_record === 0 ? '否' : ''), + expect_start_time: normalizeCellValue(row.expect_start_time), + expect_end_time: normalizeCellValue(row.expect_end_time), + order_create_time: normalizeCellValue(row.order_create_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入入库单明细...', + }); + + // Sheet 2: 入库单明细 + const sheet2 = workbook.addWorksheet('入库单明细'); + const entryItemColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '入库单ID', key: 'entry_order_id', width: 12 }, + { header: '行号', key: 'order_line_no', width: 8 }, + { header: '商品编码', key: 'item_code', width: 20 }, + { header: '商品名称', key: 'item_name', width: 28 }, + { header: '商品规格', key: 'sku_property', width: 24 }, + { header: '计划入库数量', key: 'plan_quantity', width: 14 }, + { header: '已收货数量', key: 'received_quantity', width: 14 }, + { header: '已通知数量', key: 'confirm_quantity', width: 14 }, + { header: '库存类型', key: 'inventory_type', width: 14 }, + { header: '外部业务编码', key: 'out_biz_code', width: 24 }, + { header: '货主编码', key: 'owner_code', width: 16 }, + { header: '商品ID', key: 'item_id', width: 12 }, + { header: '商品SKU ID', key: 'stock_id', width: 12 }, + ]; + sheet2.columns = entryItemColumns; + + const entryOrderCodeMap = new Map(); + for (const row of allEntryOrders) { + entryOrderCodeMap.set(Number(row.id), row.entry_order_code || ''); + } + + const itemBatchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalEntryOrders = allEntryOrderIds.length; + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += itemBatchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const eid of batchIds) { + const entryOrderCode = entryOrderCodeMap.get(eid) || ''; + const items = itemsMap.get(eid) || []; + + for (const item of items) { + const stockId = Number(item.stock_id || 0); + const stockInfo = stockInfoMap.get(stockId) || {}; + + sheet2.addRow({ + entry_order_code: entryOrderCode, + entry_order_id: eid, + order_line_no: item.order_line_no ?? '', + item_code: stockInfo.item_code || item.item_code || '', + item_name: stockInfo.item_name || '', + sku_property: stockInfo.sku_property || '', + plan_quantity: item.count ?? 0, + received_quantity: item.received_quantity ?? 0, + confirm_quantity: item.confirm_quantity ?? 0, + inventory_type: normalizeCellValue(item.inventory_type), + out_biz_code: normalizeCellValue(item.out_biz_code), + owner_code: normalizeCellValue(item.owner_code), + item_id: normalizeCellValue(item.item_id), + stock_id: item.stock_id ?? '', + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalEntryOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入入库单明细,已完成 ${itemWrittenCount}/${totalEntryOrders} 条入库单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/entry/store/${storeId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `货主侧入库单导出(货主${storeId}),共${totalCount}条入库单`, + }); + } + + // 清理临时文件 + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ } + + const uploadInfo = fileRecord || uploadResult; + const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url + ? uploadInfo.url + : (typeof uploadResult === 'object' ? uploadResult.fileName : ''); + + await progressHandler({ + status: 'running', + progress: 100, + message: '货主侧导出完成', + result: { url: fileUrl, fileKey: uploadKey }, + }); + + return { + url: fileUrl, + fileKey: uploadKey, + total: totalCount, + totalDetails: allEntryOrderIds.reduce((sum, eid) => sum + (itemsMap.get(eid) || []).length, 0), + }; + } + +} + +module.exports = EntryService; 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/index.js b/app/service/systems/storage/index.js index 3362140..f441181 100644 --- a/app/service/systems/storage/index.js +++ b/app/service/systems/storage/index.js @@ -2,7 +2,495 @@ const Service = require('egg').Service; class IndexService extends Service { - async index() { + + async findByStockAndBatch(stockId, batchNo, inventoryType = 'ZP') { + const { ctx } = this; + + return await ctx.model.Storage.findOne({ + where: { + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'space_code', 'custom_name' ], + }, + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [[ 'company_name', 'store_name' ]], + }, + ], + }); + } + + async findBySpace(spaceId) { + const { ctx } = this; + + return await ctx.model.Storage.findAll({ + where: { + space_id: spaceId, + is_enabled: 1, + delete_at: null, + }, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'product_code', 'product_name' ], + }, + ], + order: [[ 'inbound_time', 'ASC' ]], + }); + } + + async findAvailableByWarehouse(warehouseId, stockId = null) { + const { ctx, app } = this; + const where = { + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + available_quantity: { [app.Sequelize.Op.gt]: 0 }, + }; + + if (stockId) { + where.stock_id = stockId; + } + + return await ctx.model.Storage.findAll({ + where, + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'space_code', 'custom_name' ], + }, + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'product_code', 'product_name' ], + }, + ], + order: [ + [ 'expiry_date', 'ASC' ], + [ 'inbound_time', 'ASC' ], + ], + }); + } + + async findExpiringSoon(days = 30) { + const { ctx, app } = this; + const expiryDate = new Date(); + expiryDate.setDate(expiryDate.getDate() + days); + + return await ctx.model.Storage.findAll({ + where: { + expiry_date: { + [app.Sequelize.Op.between]: [ new Date(), expiryDate ], + }, + is_enabled: 1, + delete_at: null, + quantity: { [app.Sequelize.Op.gt]: 0 }, + }, + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [[ 'company_name', 'store_name' ]], + }, + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'product_code', 'product_name' ], + }, + ], + order: [[ 'expiry_date', 'ASC' ]], + }); + } + + /** + * 更新库存数量、锁定数量与拦截锁定数量,并按统一口径重算可用数量。 + * + * 可用数量统一口径: + * `available_quantity = quantity - locked_quantity - intercept_locked_quantity`。 + * + * @param {number} id 库存记录 ID。 + * @param {number} quantityChange 库存数量变化量(正数为增加,负数为减少)。 + * @param {number} [lockedChange=0] 锁定数量变化量。 + * @param {Object} [options={}] 执行上下文与事务参数。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @param {number} [options.interceptLockedChange=0] 拦截锁定数量变化量(正数为拦截锁定,负数为释放; + * 允许结果为负值:差异对账场景下 storage 比 stock 少的差异以负拦截锁定入账,可用数量等量回补)。 + * @return {Promise} 更新后的库存记录。 + */ + async updateQuantity(id, quantityChange, lockedChange = 0, options = {}) { + const { ctx } = this; + const interceptLockedChange = Number((options && options.interceptLockedChange) || 0); + const applyUpdate = async transaction => { + const storage = await ctx.model.Storage.findByPk(id, { + transaction, + lock: transaction ? transaction.LOCK.UPDATE : undefined, + }); + + if (!storage) { + throw new Error('库存记录不存在'); + } + + const newQuantity = storage.quantity + quantityChange; + const newLocked = storage.locked_quantity + lockedChange; + const newInterceptLocked = Number(storage.intercept_locked_quantity || 0) + interceptLockedChange; + + if (newQuantity < 0) { + throw new Error('库存数量不能为负数'); + } + + if (newLocked < 0) { + throw new Error('锁定数量无效'); + } + + // 拦截锁定允许为负(差异对账:storage 比 stock 少的差异以负值入账,可用数量回补); + // 上界仍禁止超过库存数量;锁定数量仍禁止为负 + if (newInterceptLocked > newQuantity) { + throw new Error('拦截锁定数量无效'); + } + + // 总和上界:锁定与拦截锁定之和不能超过库存数量; + // 等价于锁定后可用不为负(available ≥ 0)。 + // 负拦截锁(差异对账补回)时锁定量可超过 quantity,但总和上限口径不变, + // 保证补回的可用数量可真实被锁定使用。 + if (newLocked + newInterceptLocked > newQuantity) { + throw new Error('锁定数量与拦截锁定数量之和不能超过库存数量'); + } + + const updateData = { + quantity: newQuantity, + locked_quantity: newLocked, + intercept_locked_quantity: newInterceptLocked, + available_quantity: newQuantity - newLocked - newInterceptLocked, + updated_at: new Date(), + }; + + await storage.update(updateData, { + transaction, + }); + return storage; + }; + + if (options.transaction) { + return await applyUpdate(options.transaction); + } + + return await ctx.model.transaction(async transaction => { + return await applyUpdate(transaction); + }); + } + + /** + * 锁定指定库存记录的可用数量。 + * + * @param {number} id 库存记录 ID。 + * @param {number} quantity 需要锁定的数量。 + * @param {Object} [options={}] 执行上下文与事务参数。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @param {string} [options.source] 调用来源标识。 + * @param {string} [options.caller] 调用方标识。 + * @param {string} [options.from] 来源模块标识。 + * @param {string} [options.action] 操作标识。 + * @return {Promise} 更新后的库存记录。 + */ + async lockQuantity(id, quantity, options = {}) { + return await this.updateQuantity(id, 0, quantity, options); + } + + /** + * 解除指定库存记录的锁定数量(锁定数量减少,可用数量等量增加)。 + * + * @param {number} id 库存记录 ID。 + * @param {number} quantity 需要解除锁定的数量。 + * @param {Object} [options={}] 执行上下文与事务参数。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @return {Promise} 更新后的库存记录。 + */ + async unlockQuantity(id, quantity, options = {}) { + return await this.updateQuantity(id, 0, -quantity, options); + } + + /** + * 从可用数量中分配锁定指定数量(锁定数量增加,可用数量等量减少)。 + * + * @param {number} id 库存记录 ID。 + * @param {number} quantity 需要分配锁定的数量。 + * @param {Object} [options={}] 执行上下文与事务参数。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @return {Promise} 更新后的库存记录。 + */ + async allocateQuantity(id, quantity, options = {}) { + const { ctx } = this; + const storage = await ctx.model.Storage.findByPk(id, { + transaction: options.transaction, + }); + + if (!storage) { + throw new Error('库存记录不存在'); + } + + if (storage.available_quantity < quantity) { + throw new Error('可用数量不足'); + } + + return await this.updateQuantity(id, 0, quantity, options); + } + + /** + * 将作业锁定数量迁移为拦截锁定数量(拦截确认专用,pending 拣货行)。 + * + * 库存总量与可用数量均不变,仅将锁定类型从 `locked_quantity` 迁移到 `intercept_locked_quantity`: + * `locked_quantity -q`、`intercept_locked_quantity +q`、`quantity` 与 `available_quantity` 不变。 + * + * @param {number} id 库存记录 ID。 + * @param {number} quantity 需要迁移为拦截锁定的数量。 + * @param {Object} [options={}] 执行上下文与事务参数。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @return {Promise} 更新后的库存记录。 + */ + async interceptLockQuantity(id, quantity, options = {}) { + return await this.updateQuantity(id, 0, -quantity, { + ...options, + interceptLockedChange: quantity, + }); + } + + /** + * 实物返还并拦截锁定(拦截确认专用,fin 已拣货行)。 + * + * 库存总量与拦截锁定数量等量增加,可用数量不变: + * `quantity +q`、`intercept_locked_quantity +q`、`locked_quantity` 与 `available_quantity` 不变。 + * + * @param {number} id 库存记录 ID。 + * @param {number} quantity 需要返还并拦截锁定的数量。 + * @param {Object} [options={}] 执行上下文与事务参数。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @return {Promise} 更新后的库存记录。 + */ + async interceptReceiveQuantity(id, quantity, options = {}) { + return await this.updateQuantity(id, quantity, 0, { + ...options, + interceptLockedChange: quantity, + }); + } + + /** + * 释放拦截锁定数量,使其回落到可用数量(解除拦截/退货登记专用)。 + * + * 库存总量与作业锁定数量不变,拦截锁定数量减少、可用数量等量增加: + * `intercept_locked_quantity -q`、`available_quantity +q`、`quantity` 与 `locked_quantity` 不变。 + * + * @param {number} id 库存记录 ID。 + * @param {number} quantity 需要释放的拦截锁定数量。 + * @param {Object} [options={}] 执行上下文与事务参数。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @return {Promise} 更新后的库存记录。 + */ + async interceptUnlockQuantity(id, quantity, options = {}) { + return await this.updateQuantity(id, 0, 0, { + ...options, + interceptLockedChange: -quantity, + }); + } + + /** + * 入库回填平账:负库存入库时,按入库量冲销该商品的 GAP 补建行挂账。 + * + * 背景:差异对账(INTERCEPT_GAP)对无行/截断差异会补建 GAP- 前缀库存行承载拦截锁定; + * 当负库存商品真实入库回填时,将补建行挂账按入库量冲销(quantity/intercept 同减), + * 账归真实入库数据,避免补建挂账与真实入库叠加造成虚账。 + * + * 冲销口径:每行冲销量 m = min(入库量, 行 quantity, 行 intercept_locked_quantity); + * available 按统一口径重算(quantity 与 intercept 同减,available 不变); + * 写 INTERCEPT_GAP(UNLOCK 方向)冲销流水,保留快照可追溯。 + * + * 冲销上限:差异基准为 max(SW.quantity, 0),只有 SW 在非负区间的增量才会收窄差异; + * SW 在负数区间回填(如 -10→0)不改变基准,不冲销。因此调用方应传入 + * options.maxOffset = max(0, 入库后SW) - max(0, 入库前SW),缺省时按入库量冲销(兼容)。 + * + * @param {number} stockId 商品SKU ID(wms_stock_warehouse.id)。 + * @param {number} qty 本次入库数量。 + * @param {Object} [options={}] 执行上下文与事务参数。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @param {number} [options.maxOffset] 冲销上限(推荐传 SW 非负区间增量,缺省=入库量)。 + * @param {string} [options.orderNo] 入库单号/来源标识(流水追溯)。 + * @param {number} [options.orderId] 关联订单/入库单 ID。 + * @param {string} [options.operatorId] 操作人 ID。 + * @param {string} [options.operatorName] 操作人名。 + * @return {Promise} 实际冲销量。 + */ + async offsetGapOnInbound(stockId, qty, options = {}) { + const { ctx, app } = this; + const inboundQty = Number(qty) || 0; + if (!stockId || inboundQty <= 0) return 0; + + const maxOffset = options.maxOffset !== undefined && options.maxOffset !== null + ? Math.max(0, Number(options.maxOffset) || 0) + : inboundQty; + if (maxOffset <= 0) return 0; + + const apply = async transaction => { + const gapRows = await ctx.model.Storage.findAll({ + where: { + stock_id: stockId, + is_enabled: 1, + delete_at: null, + [app.Sequelize.Op.or]: [ + { batch_no: { [app.Sequelize.Op.like]: 'GAP-%' } }, + { inbound_order_no: { [app.Sequelize.Op.like]: 'GAP-%' } }, + ], + }, + order: [[ 'id', 'ASC' ]], + lock: transaction ? transaction.LOCK.UPDATE : undefined, + transaction, + }); + + let remain = inboundQty; + let offsetTotal = 0; + let offsetBudget = maxOffset; + + for (const row of gapRows) { + if (remain <= 0 || offsetBudget <= 0) break; + const gapQty = Number(row.quantity) || 0; + const gapIntercept = Number(row.intercept_locked_quantity) || 0; + const offsetQty = Math.min(remain, offsetBudget, Math.min(gapQty, gapIntercept)); + if (offsetQty <= 0) continue; + + const newQty = gapQty - offsetQty; + const newIntercept = gapIntercept - offsetQty; + const lockedQty = Number(row.locked_quantity) || 0; + + await row.update({ + quantity: newQty, + intercept_locked_quantity: newIntercept, + available_quantity: newQty - lockedQty - newIntercept, + updated_at: new Date(), + }, { transaction }); + + // 冲销流水(UNLOCK 方向,快照守恒:after = before - offsetQty) + await ctx.model.StorageTransaction.create({ + transaction_type: 'UNLOCK', + warehouse_id: row.warehouse_id, + store_id: row.store_id, + stock_id: stockId, + storage_id: row.id, + space_id: row.space_id, + quantity: offsetQty, + before_quantity: gapQty, + after_quantity: newQty, + before_locked_quantity: lockedQty, + after_locked_quantity: lockedQty, + before_intercept_locked_quantity: gapIntercept, + after_intercept_locked_quantity: newIntercept, + batch_no: row.batch_no, + inventory_type: row.inventory_type, + order_type: 'INTERCEPT_GAP', + order_no: String(options.orderNo || 'INBOUND_GAP_OFFSET').slice(0, 255), + order_id: Number(options.orderId || 0) || null, + operator_id: options.operatorId || null, + operator_name: options.operatorName || '', + remark: '入库回填平账(冲销差异挂账)', + created_at: new Date(), + }, { transaction }); + + remain -= offsetQty; + offsetBudget -= offsetQty; + offsetTotal += offsetQty; + } + + return offsetTotal; + }; + + if (options.transaction) { + return await apply(options.transaction); + } + + return await ctx.model.transaction(async transaction => { + return await apply(transaction); + }); + } + + async getStockSummary(warehouseId) { + const { ctx, app } = this; + + return await ctx.model.Storage.findAll({ + attributes: [ + 'stock_id', + 'inventory_type', + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ], + ], + where: { + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }, + group: [ 'stock_id', 'inventory_type' ], + raw: true, + }); + } + + async getSpaceUsage(spaceId) { + const { ctx, app } = this; + const result = await ctx.model.Storage.findAll({ + attributes: [ + 'inventory_type', + [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'record_count' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], + ], + where: { + space_id: spaceId, + is_enabled: 1, + delete_at: null, + }, + group: [ 'inventory_type' ], + raw: true, + }); + + const usage = { + normal: 0, + defective: 0, + damaged: 0, + frozen: 0, + total: 0, + }; + + result.forEach(item => { + let type; + switch (item.inventory_type) { + case 'ZP': + type = 'normal'; + break; + case 'CC': + type = 'defective'; + break; + case 'JS': + case 'XS': + type = 'damaged'; + break; + case 'DJ': + type = 'frozen'; + break; + default: + return; + } + + usage[type] = parseInt(item.total_quantity, 10) || 0; + usage.total += usage[type]; + }); + + return usage; } } diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js new file mode 100644 index 0000000..d16d8b9 --- /dev/null +++ b/app/service/systems/storage/inventory.js @@ -0,0 +1,3424 @@ +'use strict'; + +const Service = require('egg').Service; +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * 库存明细(逐条)模式允许的排序字段白名单(wms_storage 真实列), + * 防止非法字段进入 ORDER BY 导致 SQL 报错或注入。 + */ +const STORAGE_BATCH_SORT_FIELD_WHITELIST = new Set([ + 'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', + 'created_at', 'updated_at', +]); + +/** + * 库存汇总(按 stock_id 合并)模式允许的排序字段 → 聚合别名映射。 + * 汇总查询中 quantity/locked_quantity/available_quantity 等为 SUM/MIN/MAX 别名, + * MySQL 支持 ORDER BY 别名,因此直接按别名排序。 + */ +const STORAGE_AGGREGATE_ORDER_FIELD_MAP = { + quantity: 'quantity', + locked_quantity: 'locked_quantity', + available_quantity: 'available_quantity', + batch_count: 'batch_count', + first_inbound_time: 'first_inbound_time', + last_inbound_time: 'last_inbound_time', + production_date: 'production_date', + expiry_date: 'expiry_date', +}; + +/** + * 计算库存批次的保质期预警状态。 + * + * @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 {Array} warningRules 库存预警规则 + * @return {Array<{name: string, key: string, tip_text: string, min_days: number, max_days: number}>} 规则区间列表 + */ +function buildInventoryWarningRanges(warningRules = []) { + if (!Array.isArray(warningRules) || !warningRules.length) { + return []; + } + + const sortedRules = warningRules + .filter(rule => rule && typeof rule === 'object') + .map(rule => ({ + name: rule.name, + key: rule.key, + tip_text: rule.tip_text === undefined || rule.tip_text === null ? '' : String(rule.tip_text), + expire_days: Number(rule.expire_days), + })) + .filter(rule => Number.isInteger(rule.expire_days) && rule.expire_days >= 0) + .sort((a, b) => a.expire_days - b.expire_days); + + let previousMax = null; + return sortedRules.map(rule => { + const minDays = previousMax === null ? 0 : previousMax + 1; + const maxDays = rule.expire_days; + previousMax = maxDays; + return { + name: rule.name, + key: rule.key, + tip_text: rule.tip_text, + min_days: minDays, + max_days: maxDays, + }; + }); +} + +/** + * 根据剩余天数命中库存预警规则并返回响应字段。 + * + * @param {number|null} remainingDays 到期剩余天数 + * @param {Array} warningRanges 预警规则区间 + * @return {{expiry_remaining_days: (number|null), inventory_warning_level: (string|null), inventory_warning_color: (string|null), inventory_warning_range: ({min_days: number, max_days: number}|null), inventory_warning_tip_text: (string|null)}} 预警输出字段 + */ +function getInventoryWarningPayload(remainingDays, warningRanges = []) { + if (!Number.isInteger(remainingDays) || !Array.isArray(warningRanges) || !warningRanges.length) { + return { + expiry_remaining_days: null, + inventory_warning_level: null, + inventory_warning_color: null, + inventory_warning_range: null, + inventory_warning_tip_text: null, + }; + } + + const matchedRange = warningRanges.find(rule => ( + remainingDays >= rule.min_days && remainingDays <= rule.max_days + )); + + if (!matchedRange) { + return { + expiry_remaining_days: remainingDays, + inventory_warning_level: null, + inventory_warning_color: null, + inventory_warning_range: null, + inventory_warning_tip_text: null, + }; + } + + return { + expiry_remaining_days: remainingDays, + inventory_warning_level: matchedRange.name || null, + inventory_warning_color: matchedRange.key || null, + inventory_warning_range: { + min_days: matchedRange.min_days, + max_days: matchedRange.max_days, + }, + inventory_warning_tip_text: matchedRange.tip_text, + }; +} + +/** + * 将库存商品上的标记值规范化为布尔值。 + * + * @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; +} + +/** + * 批量加载库存商品的条码与图片附属信息。 + * 复用 stock_warehouse.getStockDetails 缓存查询。 + * + * @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 }; + } + + try { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + uniqueStockIds, + {} + ); + for (const detail of stockDetails) { + const stockId = Number(detail.id); + if (!stockId) { + continue; + } + + // 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + const barcodes = detail.barcodes + .map(bc => String(bc.barcode || '').trim()) + .filter(Boolean); + if (barcodes.length > 0) { + barcodesByStockId.set(stockId, barcodes); + } + } + + // 提取图片(兼容数组/字符串格式) + const imageUrls = Array.isArray(detail.image_url) + ? detail.image_url.map(u => String(u || '').trim()).filter(Boolean) + : (detail.image_url ? [ String(detail.image_url).trim() ] : []); + if (imageUrls.length > 0) { + imagesByStockId.set(stockId, imageUrls); + } + } + } 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) || []; + } +} + +/** + * 解析并规范化库存效期维护入参中的日期值(统一输出 'YYYY-MM-DD')。 + * + * 规则: + * - `undefined`:未传该字段(不更新,返回 provided=false); + * - `null` / 空串:清空该字段(provided=true 且 value=null); + * - `'YYYY-MM-DD'` / `'YYYY/MM/DD'` / `'YYYY-MM-DD HH:mm:ss'` / ISO 字符串 / Date: + * 仅取日期部分并校验为真实存在的日期,规范化为 'YYYY-MM-DD'; + * - 其它:视为非法(invalid=true),由调用方返回参数错误。 + * + * @param {unknown} value 待解析的日期值 + * @return {{provided: boolean, value: (string|null), invalid: boolean}} 解析结果 + */ +function parseStorageDateInput(value) { + if (value === undefined) { + return { provided: false, value: null, invalid: false }; + } + + if (value === null || (typeof value === 'string' && value.trim() === '')) { + return { provided: true, value: null, invalid: false }; + } + + let year; + let month; + let day; + + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + return { provided: true, value: null, invalid: true }; + } + year = value.getFullYear(); + month = value.getMonth() + 1; + day = value.getDate(); + } else { + const matched = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})([T\s].*)?$/.exec(String(value).trim()); + if (!matched) { + return { provided: true, value: null, invalid: true }; + } + year = Number(matched[1]); + month = Number(matched[2]); + day = Number(matched[3]); + } + + const parsed = new Date(year, month - 1, day); + const isValidDate = parsed.getFullYear() === year + && parsed.getMonth() === month - 1 + && parsed.getDate() === day; + + if (!isValidDate || year < 1900 || year > 2999) { + return { provided: true, value: null, invalid: true }; + } + + return { + provided: true, + value: `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`, + invalid: false, + }; +} + +class InventoryService extends Service { + + /** + * 静态盘点锁定校验(移库等库存操作前置拦截)。 + * 商品若处于静态盘点锁定中(stock_check.is_static=1 且任务 approved/checking),返回冲突文案; + * 若 stockCheck 服务不可用(单测桩等)则视为未锁定,不阻断既有流程。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array|number} stockIds 商品库存ID(单值或数组)。 + * @param {string} actionLabel 被禁止的操作名(文案用)。 + * @return {Promise<{locked: boolean, message: string, rows: Array}>} 锁定冲突信息。 + */ + async _getStaticLockConflict(warehouseId, stockIds, actionLabel) { + const { ctx } = this; + const stockCheckService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.stockCheck; + if (!stockCheckService || typeof stockCheckService.getStaticLockConflict !== 'function') { + return { locked: false, message: '', rows: [] }; + } + const normalizedWarehouseId = Number(warehouseId) || 0; + if (normalizedWarehouseId <= 0) { + return { locked: false, message: '', rows: [] }; + } + try { + return await stockCheckService.getStaticLockConflict({ + warehouseId: normalizedWarehouseId, + stockIds, + actionLabel, + }); + } catch (error) { + // 锁定查询失败不阻断库存主流程(缓存/DB 异常时按未锁定处理),仅记录告警 + if (ctx.logger && typeof ctx.logger.warn === 'function') { + ctx.logger.warn(`[InventoryStaticLock] 查询静态盘点锁定失败 action=${actionLabel}: ${error && error.message}`); + } + return { locked: false, message: '', rows: [] }; + } + } + + /** + * 计算单条库存记录的可用数量,口径与 `updateQuantity` 保持一致: + * `available = quantity - locked_quantity - intercept_locked_quantity`。 + * + * 同时与库内 `available_quantity` 字段取较小值:`available_quantity` 为页面展示口径, + * 任一字段显示为 0(例如被拦截锁定)时都不允许移库,避免把锁定/拦截锁定库存移走。 + * + * @param {Object} record wms_storage 记录 + * @return {number} 可用数量(不小于 0) + */ + _resolveAvailableQuantity(record) { + const quantity = Number(record?.quantity || 0); + const lockedQuantity = Number(record?.locked_quantity || 0); + const interceptLockedQuantity = Number(record?.intercept_locked_quantity || 0); + const physicalAvailable = quantity - lockedQuantity - interceptLockedQuantity; + const storedAvailable = Number(record?.available_quantity); + const available = Number.isFinite(storedAvailable) + ? Math.min(physicalAvailable, storedAvailable) + : physicalAvailable; + return Math.max(available, 0); + } + + /** + * 计算单条库存记录中不可移库的数量(锁定 + 拦截锁定)。 + * + * @param {Object} record wms_storage 记录 + * @return {number} 锁定与拦截锁定数量之和 + */ + _resolveLockedQuantity(record) { + const lockedQuantity = Number(record?.locked_quantity || 0); + const interceptLockedQuantity = Number(record?.intercept_locked_quantity || 0); + return lockedQuantity + interceptLockedQuantity; + } + + /** + * 写入移库双向库位流水(移库出/移库入)。 + * + * 说明: + * 1) before/after 与锁定字段均写同值快照,避免被识别为普通出入库数量变化; + * 2) 仅记录移库行为本身,不绑定订单字段。 + * + * @param {Object} data 入参 + * @param {Object} data.transaction 数据库事务 + * @param {Object} data.srcRecord 源库存记录 + * @param {number} data.transferQuantity 移库数量 + * @param {number} data.sourceSpaceId 源库位ID + * @param {number} data.targetSpaceId 目标库位ID + * @param {number|null} data.targetStorageId 目标库存记录ID + * @param {number} data.totalSnapshotQuantity stock_id 总库存快照数量 + * @param {number} data.totalSnapshotLockedQuantity stock_id 总锁定快照数量 + * @return {Promise} 无返回值 + */ + async createTransferStockTransactions(data = {}) { + const { ctx } = this; + + const operatorId = ctx.user?.employees_id || ctx.user?.id || null; + const operatorName = ctx.user?.employees_name || ''; + + const totalSnapshotQuantity = Number(data.totalSnapshotQuantity) || 0; + const totalSnapshotLockedQuantity = Number(data.totalSnapshotLockedQuantity) || 0; + // 拦截锁定快照:wms_stock_warehouse 层无该字段,取源库位行值(移库不动拦截锁,before=after) + const sourceInterceptLockedQuantity = Number(data.srcRecord?.intercept_locked_quantity) || 0; + + await ctx.model.StorageTransaction.create({ + transaction_type: 'TRANSFER_OUT', + warehouse_id: data.srcRecord.warehouse_id, + store_id: data.srcRecord.store_id, + stock_id: data.srcRecord.stock_id, + storage_id: data.srcRecord.id, + space_id: data.sourceSpaceId, + quantity: data.transferQuantity, + batch_no: data.srcRecord.batch_no, + inventory_type: data.srcRecord.inventory_type, + order_type: null, + order_no: null, + order_id: null, + operator_id: operatorId, + operator_name: operatorName, + remark: '移库出', + before_quantity: totalSnapshotQuantity, + after_quantity: totalSnapshotQuantity, + before_locked_quantity: totalSnapshotLockedQuantity, + after_locked_quantity: totalSnapshotLockedQuantity, + before_intercept_locked_quantity: sourceInterceptLockedQuantity, + after_intercept_locked_quantity: sourceInterceptLockedQuantity, + source_order_codes: null, + created_at: new Date(), + }, { + transaction: data.transaction, + }); + + await ctx.model.StorageTransaction.create({ + transaction_type: 'TRANSFER_IN', + warehouse_id: data.srcRecord.warehouse_id, + store_id: data.srcRecord.store_id, + stock_id: data.srcRecord.stock_id, + storage_id: data.targetStorageId, + space_id: data.targetSpaceId, + quantity: data.transferQuantity, + batch_no: data.srcRecord.batch_no, + inventory_type: data.srcRecord.inventory_type, + order_type: null, + order_no: null, + order_id: null, + operator_id: operatorId, + operator_name: operatorName, + remark: '移库入', + before_quantity: totalSnapshotQuantity, + after_quantity: totalSnapshotQuantity, + before_locked_quantity: totalSnapshotLockedQuantity, + after_locked_quantity: totalSnapshotLockedQuantity, + before_intercept_locked_quantity: sourceInterceptLockedQuantity, + after_intercept_locked_quantity: sourceInterceptLockedQuantity, + source_order_codes: null, + created_at: new Date(), + }, { + transaction: data.transaction, + }); + } + + /** + * 移库(库位转移):将单条库存从一个库位移动到另一个库位。 + * 支持部分/全量移库、目标库位合并。 + * + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(必填) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} [data.quantity] 移库数量(可选,默认全部移动) + * @return {Promise} code/data/message 结构 + */ + async transferLocation(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // ────────── 1. 参数校验 ────────── + const storageId = Number(data.storage_id || 0); + if (!storageId) { + return { code: 400, message: 'storage_id 必填', data: null }; + } + + const targetSpaceId = Number(data.target_space_id || 0); + if (!targetSpaceId) { + return { code: 400, message: 'target_space_id 必填', data: null }; + } + + if (data.quantity !== undefined && data.quantity !== null) { + const qty = Number(data.quantity); + if (!Number.isFinite(qty) || qty <= 0) { + return { code: 400, message: 'quantity 必须为正数', data: null }; + } + } + + // ────────── 2. 开事务 ────────── + const transaction = await ctx.model.transaction(); + + try { + // ────────── 3. 锁定并校验原库存记录 ────────── + const srcRecord = await ctx.model.Storage.findOne({ + where: { + id: storageId, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!srcRecord) { + await transaction.rollback(); + return { code: 404, message: `库存记录不存在: storage_id=${storageId}`, data: null }; + } + + const warehouseId = srcRecord.warehouse_id; + + // 静态盘点锁定校验:商品在静态盘点中禁止移库 + const lockConflict = await this._getStaticLockConflict(warehouseId, [ srcRecord.stock_id ], '移库'); + if (lockConflict.locked) { + await transaction.rollback(); + return { code: 400, message: lockConflict.message, data: null }; + } + + const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({ + where: { id: srcRecord.stock_id }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + transaction, + }); + if (!stockWarehouseSnapshot) { + await transaction.rollback(); + return { code: 404, message: `商品SKU不存在: stock_id=${srcRecord.stock_id}`, data: null }; + } + + // ────────── 4. 校验目标库位 ────────── + const targetSpace = await ctx.model.LocationSpace.findOne({ + where: { + id: targetSpaceId, + is_enabled: true, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!targetSpace) { + await transaction.rollback(); + return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null }; + } + if (targetSpace.warehouse_id !== warehouseId) { + await transaction.rollback(); + return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null }; + } + if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) { + await transaction.rollback(); + return { + code: 400, + message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`, + data: null, + }; + } + + // ────────── 5. 处理移库 ────────── + const availableQty = this._resolveAvailableQuantity(srcRecord); + const transferQty = (data.quantity !== undefined && data.quantity !== null) + ? Number(data.quantity) + : availableQty; + + // 校验移库数量 + if (availableQty <= 0) { + await transaction.rollback(); + return { + code: 400, + message: `库存记录 ${storageId} 可用数量为 0(锁定 ${Number(srcRecord.locked_quantity) || 0}、拦截锁定 ${Number(srcRecord.intercept_locked_quantity) || 0}),不可移库`, + data: null, + }; + } + if (transferQty > availableQty) { + await transaction.rollback(); + return { + code: 400, + message: `库存记录 ${storageId} 可用数量不足:可用 ${availableQty},请求移库 ${transferQty}`, + data: null, + }; + } + + // 原库位与目标库位相同则直接返回 + if (srcRecord.space_id === targetSpaceId) { + await transaction.rollback(); + return { + code: 200, + message: '原库位与目标库位相同,无需移库', + data: { + storage_id: storageId, + target_space_id: targetSpaceId, + transfer_quantity: 0, + status: 'skipped', + }, + }; + } + + const beforeSnapshot = { + storage_id: storageId, + space_id: srcRecord.space_id, + quantity: srcRecord.quantity, + available_quantity: srcRecord.available_quantity, + }; + + const isFullTransfer = (transferQty === srcRecord.quantity); + + // 查找目标库位是否已有相同 stock_id + batch_no + inventory_type 的记录 + const existingTarget = await ctx.model.Storage.findOne({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, // 排除自身(全量移库时直接改 space_id 的情况) + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let afterSnapshot; + let targetStorageId = null; + // 原库位统计变化 + const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + // 目标库位统计变化 + const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + + if (existingTarget) { + // ── 目标库位已有同规格记录:合并数量 ── + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${transferQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${transferQty}`), + updated_at: new Date(), + }, { + where: { id: existingTarget.id }, + transaction, + }); + + if (isFullTransfer) { + // 全量移库且合并:硬删除原记录,释放唯一键 + await ctx.model.Storage.destroy({ + where: { id: storageId }, + force: true, + transaction, + }); + srcSpaceDelta.qtyDelta -= srcRecord.quantity; + // 检查原库位该 SKU 是否还有其他记录 + const remainingSku = await ctx.model.Storage.count({ + where: { + space_id: srcRecord.space_id, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, + }, + transaction, + }); + if (remainingSku === 0) { + srcSpaceDelta.skuDelta -= 1; + } + } else { + // 部分移库:减少原记录数量 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${transferQty}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`), + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + srcSpaceDelta.qtyDelta -= transferQty; + } + + // 目标库位数量增加 + tgtSpaceDelta.qtyDelta += transferQty; + // 目标库位该 SKU 之前已有记录,skuDelta 不变 + + targetStorageId = existingTarget.id; + afterSnapshot = { + merged_into: existingTarget.id, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + source_deleted: isFullTransfer, + }; + } else if (isFullTransfer) { + // ── 全量移库 & 目标无同规格记录:直接修改 space_id ── + await ctx.model.Storage.update({ + space_id: targetSpaceId, + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + + srcSpaceDelta.qtyDelta -= srcRecord.quantity; + // 检查原库位该 SKU 是否还有其他记录 + const remainingSku = await ctx.model.Storage.count({ + where: { + space_id: srcRecord.space_id, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, + }, + transaction, + }); + if (remainingSku === 0) { + srcSpaceDelta.skuDelta -= 1; + } + + // 目标库位新增一个 SKU + const existingSkuInTarget = await ctx.model.Storage.count({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, // 排掉自身(此时 space_id 已更新,但事务内逻辑用旧值) + }, + transaction, + }); + if (existingSkuInTarget === 0) { + tgtSpaceDelta.skuDelta += 1; + } + tgtSpaceDelta.qtyDelta += srcRecord.quantity; + + targetStorageId = storageId; + afterSnapshot = { + storage_id: storageId, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + source_deleted: false, + }; + } else { + // ── 部分移库 & 目标无同规格记录:减少原记录数量,新建目标记录 ── + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${transferQty}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`), + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + + const newRecord = await ctx.model.Storage.create({ + warehouse_id: srcRecord.warehouse_id, + store_id: srcRecord.store_id, + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + quantity: transferQty, + locked_quantity: 0, + available_quantity: transferQty, + production_date: srcRecord.production_date, + expiry_date: srcRecord.expiry_date, + inbound_time: srcRecord.inbound_time, + inbound_order_no: srcRecord.inbound_order_no, + receiving_id: srcRecord.receiving_id, + entry_order_id: srcRecord.entry_order_id, + supplier_id: srcRecord.supplier_id, + supplier_batch_no: srcRecord.supplier_batch_no, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + + srcSpaceDelta.qtyDelta -= transferQty; + // 原库位 SKU 数不变(原记录仍在) + + // 目标库位:新增 SKU + const existingSkuInTarget = await ctx.model.Storage.count({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + // count 包含刚 create 的记录,如果只有 1 条说明之前没有 + if (existingSkuInTarget <= 1) { + tgtSpaceDelta.skuDelta += 1; + } + tgtSpaceDelta.qtyDelta += transferQty; + + targetStorageId = newRecord.id; + afterSnapshot = { + new_storage_id: newRecord.id, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + source_deleted: false, + }; + } + + await this.createTransferStockTransactions({ + transaction, + srcRecord, + transferQuantity: transferQty, + sourceSpaceId: srcRecord.space_id, + targetSpaceId, + targetStorageId, + totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0, + totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0, + }); + + // ────────── 记录操作日志(事务内) ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'storage', + businessId: storageId, + operationCode: 'STORAGE_TRANSFER_LOCATION', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + }, + beforeChanges: beforeSnapshot, + afterChanges: afterSnapshot, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.transferLocation] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 6. 更新库位统计 ────────── + const updateSpaceStats = async (spaceId, delta) => { + if (delta.qtyDelta === 0 && delta.skuDelta === 0) return; + const updateFields = {}; + if (delta.qtyDelta !== 0) { + updateFields.current_quantity = app.Sequelize.literal( + `GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)` + ); + } + if (delta.skuDelta !== 0) { + updateFields.current_sku_count = app.Sequelize.literal( + `GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)` + ); + } + await ctx.model.LocationSpace.update(updateFields, { + where: { id: spaceId }, + transaction, + }); + }; + + await updateSpaceStats(srcRecord.space_id, srcSpaceDelta); + await updateSpaceStats(targetSpaceId, tgtSpaceDelta); + + // ────────── 7. 提交事务 ────────── + await transaction.commit(); + + ctx.logger.info('[inventory.transferLocation] 移库完成', { + warehouse_id: warehouseId, + storage_id: storageId, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + }); + + return { + code: 200, + message: '移库完成', + data: { + storage_id: storageId, + stock_id: srcRecord.stock_id, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + status: 'success', + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[inventory.transferLocation] 移库异常', { + storage_id: storageId, + target_space_id: targetSpaceId, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + throw error; + } + } + + /** + * 按库位+商品维度移库。 + * 自动查找该库位下该商品的所有 storage 记录,按 quantity ASC 逐条扣减并合并移动到目标库位。 + * + * @param {Object} data 请求体 + * @param {number} data.space_id 原库位ID(必填) + * @param {number} data.stock_id 商品SKU ID(必填,对应 wms_stock_warehouse.id) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} data.quantity 移库数量(必填) + * @return {Promise} code/data/message 结构 + * + * 说明: + * 1) 可用量口径与 `updateQuantity` 一致:`quantity - locked_quantity - intercept_locked_quantity`, + * 并与库内 `available_quantity` 取较小值;锁定/拦截锁定(`available_quantity=0`)的记录一律不参与移库; + * 2) 只按请求数量移库(不足整条时按数量拆分),不会清空库位;目标库位已有同批次同类型记录时合并; + * 3) 循环结束后复核实际移库量,未移满请求数量(并发改动、可用量不足等)时整单回滚并返回 409, + * 不会出现"提示成功但少移"的情况;成功时返回真实移库数量 `transfer_quantity` 与 + * 移库后原库位该商品剩余可用量 `remaining_quantity`、剩余锁定/拦截锁定数量 + * `remaining_locked_quantity`(并发写入原库位的新记录不会被本次移库带走)。 + */ + async transferByProduct(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // ────────── 1. 参数校验 ────────── + const spaceId = Number(data.space_id || 0); + const stockId = Number(data.stock_id || 0); + const targetSpaceId = Number(data.target_space_id || 0); + const quantity = Number(data.quantity || 0); + + if (!spaceId) { + return { code: 400, message: 'space_id 必填', data: null }; + } + if (!stockId) { + return { code: 400, message: 'stock_id 必填', data: null }; + } + if (!targetSpaceId) { + return { code: 400, message: 'target_space_id 必填', data: null }; + } + if (!Number.isFinite(quantity) || quantity <= 0) { + return { code: 400, message: 'quantity 必须为正数', data: null }; + } + + // ────────── 2. 批次管理校验 ────────── + const stockWarehouse = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId }, + attributes: [ 'id', 'is_batch_mgmt' ], + }); + if (!stockWarehouse) { + return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null }; + } + if (stockWarehouse.is_batch_mgmt === 'Y') { + return { + code: 400, + message: '该商品已开启批次管理,请使用按库存记录移库(transferLocation)', + data: null, + }; + } + + // ────────── 3. 原库位与目标库位相同 ────────── + if (spaceId === targetSpaceId) { + return { + code: 200, + message: '原库位与目标库位相同,无需移库', + data: { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: 0, + affected_storage_count: 0, + status: 'skipped', + }, + }; + } + + // ────────── 4. 开事务 ────────── + const transaction = await ctx.model.transaction(); + + try { + // ────────── 5. 查找并锁定原库存记录 ────────── + const srcRecords = await ctx.model.Storage.findAll({ + where: { + space_id: spaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + order: [[ 'quantity', 'ASC' ]], + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!srcRecords.length) { + await transaction.rollback(); + return { code: 404, message: `原库位 ${spaceId} 下未找到商品 ${stockId} 的库存记录`, data: null }; + } + + // 静态盘点锁定校验:商品在静态盘点中禁止移库 + const lockConflict = await this._getStaticLockConflict( + Number(srcRecords[0].warehouse_id) || 0, + [ stockId ], + '移库' + ); + if (lockConflict.locked) { + await transaction.rollback(); + return { code: 400, message: lockConflict.message, data: null }; + } + + const totalAvailable = srcRecords.reduce( + (sum, r) => sum + this._resolveAvailableQuantity(r), + 0 + ); + if (quantity > totalAvailable) { + await transaction.rollback(); + return { + code: 400, + message: `可用数量不足:可用 ${totalAvailable},请求移库 ${quantity}`, + data: null, + }; + } + + const warehouseId = srcRecords[0].warehouse_id; + + const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + transaction, + }); + if (!stockWarehouseSnapshot) { + await transaction.rollback(); + return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null }; + } + + // ────────── 6. 校验目标库位 ────────── + const targetSpace = await ctx.model.LocationSpace.findOne({ + where: { + id: targetSpaceId, + is_enabled: true, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!targetSpace) { + await transaction.rollback(); + return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null }; + } + if (targetSpace.warehouse_id !== warehouseId) { + await transaction.rollback(); + return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null }; + } + if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) { + await transaction.rollback(); + return { + code: 400, + message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`, + data: null, + }; + } + + // ────────── 7. 逐条扣减并移库 ────────── + let remainingQty = quantity; + let affectedCount = 0; + const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + + // 预先记录目标库位是否已有该 SKU(用于事后计算 skuDelta) + const tgtSkuCountBefore = await ctx.model.Storage.count({ + where: { + space_id: targetSpaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + + for (const srcRecord of srcRecords) { + if (remainingQty <= 0) break; + + const available = this._resolveAvailableQuantity(srcRecord); + const toTransfer = Math.min(available, remainingQty); + if (toTransfer <= 0) continue; + + affectedCount++; + const isFullTransfer = (toTransfer === srcRecord.quantity); + let targetStorageId = null; + + // ── 在目标库位查找同 stock_id + batch_no + inventory_type 的记录 ── + const existingTarget = await ctx.model.Storage.findOne({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: srcRecord.id }, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (existingTarget) { + // 目标已有同规格记录:合并数量 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${toTransfer}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${toTransfer}`), + updated_at: new Date(), + }, { + where: { id: existingTarget.id }, + transaction, + }); + + if (isFullTransfer) { + // 全量:硬删除原记录,释放唯一键 + await ctx.model.Storage.destroy({ + where: { id: srcRecord.id }, + force: true, + transaction, + }); + } else { + // 部分:减少原记录 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${toTransfer}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`), + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + } + + targetStorageId = existingTarget.id; + } else if (isFullTransfer) { + // 全量移库 & 目标无同规格记录:直接改 space_id + await ctx.model.Storage.update({ + space_id: targetSpaceId, + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + + targetStorageId = srcRecord.id; + } else { + // 部分移库 & 目标无同规格记录:减少原记录,新建目标记录 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${toTransfer}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`), + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + + const newRecord = await ctx.model.Storage.create({ + warehouse_id: srcRecord.warehouse_id, + store_id: srcRecord.store_id, + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + quantity: toTransfer, + locked_quantity: 0, + available_quantity: toTransfer, + production_date: srcRecord.production_date, + expiry_date: srcRecord.expiry_date, + inbound_time: srcRecord.inbound_time, + inbound_order_no: srcRecord.inbound_order_no, + receiving_id: srcRecord.receiving_id, + entry_order_id: srcRecord.entry_order_id, + supplier_id: srcRecord.supplier_id, + supplier_batch_no: srcRecord.supplier_batch_no, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + + targetStorageId = newRecord.id; + } + + await this.createTransferStockTransactions({ + transaction, + srcRecord, + transferQuantity: toTransfer, + sourceSpaceId: srcRecord.space_id, + targetSpaceId, + targetStorageId, + totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0, + totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0, + }); + + srcSpaceDelta.qtyDelta -= toTransfer; + tgtSpaceDelta.qtyDelta += toTransfer; + remainingQty -= toTransfer; + } + + // ── 复核实际移库数量:若循环因记录被并发改动/可用量不足而提前结束,整单回滚,避免"提示成功但少移" ── + if (remainingQty > 0) { + await transaction.rollback(); + ctx.logger.warn('[inventory.transferByProduct] 实际移库数量不足,已回滚', { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + request_quantity: quantity, + transferred_quantity: quantity - remainingQty, + remaining_quantity: remainingQty, + available_snapshot: totalAvailable, + }); + return { + code: 409, + message: `可用库存不足:请求移库 ${quantity},实际只移了 ${quantity - remainingQty},剩余 ${remainingQty} 未移库,请刷新库存后重试`, + data: { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: 0, + remaining_quantity: remainingQty, + status: 'rolled_back', + }, + }; + } + + const transferredQuantity = quantity - remainingQty; + + // ── 复核原库位剩余可用量:并发写入的新记录不会被本次移库带走,需明确回给调用方 ── + const remainRows = await ctx.model.Storage.findAll({ + where: { + space_id: spaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + const remainingQuantity = remainRows.reduce( + (sum, r) => sum + this._resolveAvailableQuantity(r), + 0 + ); + const remainingLockedQuantity = remainRows.reduce( + (sum, r) => sum + this._resolveLockedQuantity(r), + 0 + ); + + // ── 计算 SKU 维度统计变化 ── + const remainingSrcSku = await ctx.model.Storage.count({ + where: { + space_id: spaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + if (remainingSrcSku === 0) { + srcSpaceDelta.skuDelta -= 1; + } + + if (tgtSkuCountBefore === 0) { + // 操作前目标库位没有该 SKU,现在有了 + tgtSpaceDelta.skuDelta += 1; + } + + // ────────── 8. 操作日志 ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'storage', + businessId: spaceId, + operationCode: 'STORAGE_TRANSFER_BY_PRODUCT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: transferredQuantity, + remaining_quantity: remainingQuantity, + remaining_locked_quantity: remainingLockedQuantity, + affected_storage_count: affectedCount, + }, + beforeChanges: { + space_id: spaceId, + stock_id: stockId, + total_available: totalAvailable, + source_record_count: srcRecords.length, + }, + afterChanges: { + target_space_id: targetSpaceId, + transfer_quantity: transferredQuantity, + affected_storage_count: affectedCount, + }, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.transferByProduct] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 9. 更新库位统计 ────────── + const updateSpaceStats = async (updateSpaceId, delta) => { + if (delta.qtyDelta === 0 && delta.skuDelta === 0) return; + const updateFields = {}; + if (delta.qtyDelta !== 0) { + updateFields.current_quantity = app.Sequelize.literal( + `GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)` + ); + } + if (delta.skuDelta !== 0) { + updateFields.current_sku_count = app.Sequelize.literal( + `GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)` + ); + } + await ctx.model.LocationSpace.update(updateFields, { + where: { id: updateSpaceId }, + transaction, + }); + }; + + await updateSpaceStats(spaceId, srcSpaceDelta); + await updateSpaceStats(targetSpaceId, tgtSpaceDelta); + + // ────────── 10. 提交事务 ────────── + await transaction.commit(); + + ctx.logger.info('[inventory.transferByProduct] 按商品移库完成', { + warehouse_id: warehouseId, + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: transferredQuantity, + remaining_quantity: remainingQuantity, + remaining_locked_quantity: remainingLockedQuantity, + affected_storage_count: affectedCount, + }); + + return { + code: 200, + message: '按商品移库完成', + data: { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: transferredQuantity, + remaining_quantity: remainingQuantity, + remaining_locked_quantity: remainingLockedQuantity, + affected_storage_count: affectedCount, + warehouse_id: warehouseId, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[inventory.transferByProduct] 按商品移库异常', { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + quantity, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + if (error.name === 'SequelizeUniqueConstraintError') { + return { + code: 409, + message: '目标库位已存在该商品同批次同类型的库存记录,合并移库失败,请稍后重试或使用 transferLocation 逐条移库', + data: null, + }; + } + + if (error.name === 'SequelizeValidationError') { + ctx.logger.error('[inventory.transferByProduct] Sequelize 校验失败', { + errors: error.errors?.map(e => ({ path: e.path, message: e.message, value: e.value })), + }); + return { code: 400, message: `数据校验失败: ${error.errors?.map(e => e.message).join('; ') || error.message}`, data: null }; + } + + throw error; + } + } + + /** + * 维护当前库存的生产日期与到期日期(wms_storage.production_date / expiry_date)。 + * + * 口径说明: + * 1) 按库存记录维度维护(单条 storage_id),仓库上下文来自当前登录用户(ctx.user.store_id), + * 跨仓库的 storage_id 一律按「不存在」处理; + * 2) 两个日期字段至少传一个;未传的字段保持库内原值;传 null 或空串表示清空该字段; + * 3) 日期支持 'YYYY-MM-DD' / 'YYYY/MM/DD' / 'YYYY-MM-DD HH:mm:ss' / ISO 字符串, + * 内部统一按 'YYYY-MM-DD' 落库; + * 4) 校验合并后的生产日期不得晚于到期日期(未传字段取库内现值参与比较); + * 5) 更新前后完全一致时直接返回 changed=false,不写库、不记日志。 + * + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(wms_storage.id,必填) + * @param {string|Date|null} [data.production_date] 生产日期(传 null/空串表示清空) + * @param {string|Date|null} [data.expiry_date] 到期日期(传 null/空串表示清空) + * @return {Promise<{code: number, message: string, data: (Object|null)}>} 统一 code/message/data 结构 + */ + async updateExpiry(data = {}) { + const { ctx } = this; + const requestData = data && typeof data === 'object' ? data : {}; + + // ────────── 1. 参数校验 ────────── + const storageId = Number(requestData.storage_id || 0); + if (!Number.isInteger(storageId) || storageId <= 0) { + return { code: 400, message: 'storage_id 必填且必须为正整数', data: null }; + } + + const productionDateInput = parseStorageDateInput(requestData.production_date); + const expiryDateInput = parseStorageDateInput(requestData.expiry_date); + + if (productionDateInput.invalid) { + return { code: 400, message: 'production_date 格式非法,须为 YYYY-MM-DD', data: null }; + } + + if (expiryDateInput.invalid) { + return { code: 400, message: 'expiry_date 格式非法,须为 YYYY-MM-DD', data: null }; + } + + if (!productionDateInput.provided && !expiryDateInput.provided) { + return { code: 400, message: 'production_date 与 expiry_date 至少传入一个', data: null }; + } + + const warehouseId = Number(ctx.user && (ctx.user.store_id ?? ctx.user.warehouse_id)) || 0; + if (warehouseId <= 0) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 事务内加锁维护 ────────── + const transaction = await ctx.model.transaction(); + + try { + const storageRecord = await ctx.model.Storage.findOne({ + where: { + id: storageId, + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!storageRecord) { + await transaction.rollback(); + return { code: 404, message: `库存记录不存在或无权访问: storage_id=${storageId}`, data: null }; + } + + const beforeProductionDate = parseStorageDateInput(storageRecord.production_date).value; + const beforeExpiryDate = parseStorageDateInput(storageRecord.expiry_date).value; + + const nextProductionDate = productionDateInput.provided + ? productionDateInput.value + : beforeProductionDate; + const nextExpiryDate = expiryDateInput.provided + ? expiryDateInput.value + : beforeExpiryDate; + + // 合并后校验:生产日期不能晚于到期日期 + if (nextProductionDate && nextExpiryDate && nextProductionDate > nextExpiryDate) { + await transaction.rollback(); + return { + code: 400, + message: `生产日期(${nextProductionDate})不能晚于到期日期(${nextExpiryDate})`, + data: null, + }; + } + + const baseData = { + storage_id: storageId, + warehouse_id: warehouseId, + store_id: storageRecord.store_id, + space_id: storageRecord.space_id, + stock_id: storageRecord.stock_id, + batch_no: storageRecord.batch_no, + }; + + if (nextProductionDate === beforeProductionDate && nextExpiryDate === beforeExpiryDate) { + await transaction.rollback(); + return { + code: 200, + message: '生产日期与到期日期均无变化,未做修改', + data: { + ...baseData, + production_date: beforeProductionDate, + expiry_date: beforeExpiryDate, + changed: false, + }, + }; + } + + await ctx.model.Storage.update({ + production_date: nextProductionDate, + expiry_date: nextExpiryDate, + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + + const changeSummary = []; + if (nextProductionDate !== beforeProductionDate) { + changeSummary.push(`生产日期 ${beforeProductionDate || '空'} → ${nextProductionDate || '空'}`); + } + if (nextExpiryDate !== beforeExpiryDate) { + changeSummary.push(`到期日期 ${beforeExpiryDate || '空'} → ${nextExpiryDate || '空'}`); + } + + // ────────── 3. 记录操作日志(失败仅告警,不影响主流程) ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'storage', + businessId: storageId, + operationCode: 'STORAGE_UPDATE_EXPIRY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + message: changeSummary.join(';'), + }, + beforeChanges: { + ...baseData, + production_date: beforeProductionDate, + expiry_date: beforeExpiryDate, + }, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.updateExpiry] 写入操作日志失败,不影响业务', logErr); + } + + await transaction.commit(); + + ctx.logger.info('[inventory.updateExpiry] 库存效期维护完成', { + warehouse_id: warehouseId, + storage_id: storageId, + production_date: nextProductionDate, + expiry_date: nextExpiryDate, + }); + + return { + code: 200, + message: '更新成功', + data: { + ...baseData, + production_date: nextProductionDate, + expiry_date: nextExpiryDate, + before_production_date: beforeProductionDate, + before_expiry_date: beforeExpiryDate, + changed: true, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[inventory.updateExpiry] 库存效期维护异常', { + storage_id: storageId, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + throw error; + } + } + + /** + * 根据商品快捷搜索关键字解析匹配的 stock_id 列表(仓库维度)。 + * 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、 + * 条码(barcode)、SKU ID(纯数字时精确匹配)模糊匹配。 + * + * @param {string} keyword 搜索关键字 + * @param {number} warehouseId 仓库ID + * @return {Promise} 匹配的 stock_id 列表 + */ + async resolveStockQueryToStockIds(keyword = '', warehouseId) { + const { ctx, app } = this; + const normalizedKeyword = String(keyword || '').trim(); + if (!normalizedKeyword || !warehouseId) { + return []; + } + + const likePattern = `%${normalizedKeyword}%`; + const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null; + const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : ''; + + const stockRows = await ctx.model.query(` + SELECT DISTINCT sw.id AS stock_id + FROM wms_stock_warehouse sw + WHERE sw.warehouse_id = :warehouseId + AND ( + sw.item_code LIKE :keyword + OR sw.item_name LIKE :keyword + OR sw.goods_code LIKE :keyword + ${extraIdCondition} + ) + `, { + replacements: { warehouseId, keyword: likePattern, exactStockId }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const barcodeRows = await ctx.model.query(` + SELECT DISTINCT sb.stock_id + FROM wms_stock_barcodes sb + INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.warehouse_id = :warehouseId + WHERE sb.barcode LIKE :keyword + `, { + replacements: { warehouseId, keyword: likePattern }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const stockIdSet = new Set(); + for (const row of stockRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + for (const row of barcodeRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + + return [ ...stockIdSet ]; + } + + /** + * 查询库存列表。 + * + * 支持按批次明细或合并模式返回库存,并补充商品条码、图片附件、保质期预警和货主名称。 + * 货主名称来源于货主签约表的 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'] 排序字段(明细模式支持 wms_storage 真实列;汇总模式仅支持 quantity/locked_quantity/available_quantity/batch_count/first_inbound_time/last_inbound_time/production_date/expiry_date,其余回退 last_inbound_time) + * @param {string} [sortParams.sortOrder='DESC'] 排序方向 + * @param {boolean} [groupByBatch=false] 是否按批次明细返回 + * @param {string|string[]} [stockQuery=''] 商品快捷搜索关键字(来自 where.stock_query,按商品编码/名称/货物编码/条码/SKU ID 模糊匹配,解析为 stock_id 过滤;支持数组,多关键字取并集) + * @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果 + */ + async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false, stockQuery = '') { + const { ctx, app } = this; + const { Op, fn, col, literal } = app.Sequelize; + const nowMs = Date.now(); + + const warehouseId = ctx.user.store_id; + const page = Math.max(Number(pageParams.page || pageParams.currentPage || 1) || 1, 1); + const pageSize = Math.max(Number(pageParams.pageSize || 20) || 20, 1); + const sortField = sortParams.sortField || sortParams.sort_field || 'created_at'; + const sortOrder = sortParams.sortOrder || sortParams.sort_order || 'DESC'; + const safeSortOrder = String(sortOrder).toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + // 明细模式按真实列排序;汇总模式按聚合别名排序(默认 last_inbound_time,与历史行为一致) + const batchSortField = STORAGE_BATCH_SORT_FIELD_WHITELIST.has(sortField) ? sortField : 'created_at'; + const aggregateOrderField = STORAGE_AGGREGATE_ORDER_FIELD_MAP[sortField] || 'last_inbound_time'; + + // 基础条件 + const baseWhere = { + [Op.and]: [ + { warehouse_id: warehouseId }, + { is_enabled: 1 }, + { delete_at: null }, + // 仅返回有量库存:明细模式过滤 quantity=0 的行,汇总模式过滤总量为 0 的商品 + { quantity: { [Op.gt]: 0 } }, + ], + }; + + // 动态 where 条件 + const parsed = ctx.whereParsed; + if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { + baseWhere[Op.and].push(...parsed.dynamicConditions); + } + + // stock_query 快捷搜索:按商品编码/名称/货物编码/条码/SKU ID 解析为 stock_id IN 条件 + // 兼容单关键字(字符串)与多关键字(数组):多关键字逐项解析后取 stock_id 并集 + const stockQueryKeywords = (Array.isArray(stockQuery) ? stockQuery : [ stockQuery ]) + .map(keyword => String(keyword || '').trim()) + .filter(Boolean); + if (stockQueryKeywords.length > 0) { + const stockIdSet = new Set(); + for (const keyword of stockQueryKeywords) { + const matchedStockIds = await this.resolveStockQueryToStockIds(keyword, warehouseId); + for (const stockId of matchedStockIds) { + stockIdSet.add(stockId); + } + } + if (stockIdSet.size > 0) { + baseWhere[Op.and].push({ stock_id: { [Op.in]: [ ...stockIdSet ] } }); + } else { + // stock_query 无匹配结果,直接返回空列表 + return { + list: [], + pagination: { + page, + pageSize, + total: 0, + totalPages: 0, + }, + }; + } + } + + const offset = (page - 1) * pageSize; + const limit = pageSize; + + if (groupByBatch) { + const inventoryWarningRanges = await this._loadInventoryWarningRanges(warehouseId, 'getInventoryList'); + + // 按批次明细:逐条返回 + const { count: total, rows } = await ctx.model.Storage.findAndCountAll({ + where: baseWhere, + order: [[ batchSortField, safeSortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ + 'id', + 'item_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + include: [ + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, + attributes: [ 'store_id', 'store_remask' ], + }), + ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + }); + + const list = this._formatBatchStorageRows(rows, inventoryWarningRanges, nowMs); + + await enrichInventoryStockAttachments(ctx, list); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } + + // 不按批次:仅按 stock_id 合并(跨库位、跨库存类型汇总) + const groupFields = [ 'stock_id' ]; + + const countResult = await ctx.model.Storage.count({ + where: baseWhere, + group: groupFields, + }); + const total = Array.isArray(countResult) ? countResult.length : countResult; + + const rows = await ctx.model.Storage.findAll({ + where: baseWhere, + attributes: [ + 'stock_id', + [ fn('MIN', col('wms_storage.warehouse_id')), 'warehouse_id' ], + [ fn('MIN', col('wms_storage.store_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' ], + [ fn('MIN', col('wms_storage.inbound_time')), 'first_inbound_time' ], + [ fn('MAX', col('wms_storage.inbound_time')), 'last_inbound_time' ], + [ fn('COUNT', col('wms_storage.id')), 'batch_count' ], + ], + group: groupFields, + order: [[ literal(aggregateOrderField), safeSortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ + 'id', + 'item_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + include: [ + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, + attributes: [ 'store_id', 'store_remask' ], + }), + ], + required: false, + }, + ], + raw: true, + nest: true, + }); + + 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.store_name = row.stock?.store_name || null; + 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: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } + + /** + * 按商品查询库存明细:返回指定 stock_id 下所有数量大于 1 的 storage 行。 + * 支持两种模式: + * - group_by_space=false(默认,不汇总):逐条返回明细,结构与 storage.inventory.list + * 明细模式一致(含批次/效期/库存预警字段); + * - group_by_space=true(按库位汇总):先筛 quantity > 1 的明细行,再按 space_id + * 汇总数量(quantity/locked_quantity/available_quantity),返回行含库位/商品信息, + * 不包含批次与效期/预警字段。 + * + * @param {number} stockId 商品SKU ID(wms_stock_warehouse.id,必填) + * @param {boolean} [groupBySpace=false] 是否按库位汇总 + * @return {Promise} code/message/data 结构,data 中为 { list: [...] } + */ + async getStorageListByStockId(stockId, groupBySpace = false) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // ────────── 1. 参数校验 ────────── + const normalizedStockId = Number(stockId); + if (!Number.isInteger(normalizedStockId) || normalizedStockId <= 0) { + return { code: 400, message: 'stock_id 必填且必须为正整数', data: null }; + } + + const warehouseId = ctx.user && ctx.user.store_id; + if (!warehouseId) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 先筛 quantity > 1 的库存明细(两种模式共用同一查询) ────────── + const nowMs = Date.now(); + const inventoryWarningRanges = await this._loadInventoryWarningRanges(warehouseId, 'getStorageListByStockId'); + + const rows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: warehouseId, + stock_id: normalizedStockId, + quantity: { [Op.gt]: 1 }, + is_enabled: 1, + delete_at: null, + }, + order: [[ 'id', 'DESC' ]], + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ + 'id', + 'item_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + include: [ + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, + attributes: [ 'store_id', 'store_remask' ], + }), + ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + }); + + // ────────── 3. 按模式格式化返回 ────────── + if (groupBySpace) { + // 按库位汇总:汇总数量,不返回批次/效期/预警字段 + const list = this._aggregateStorageRowsBySpace(rows); + await enrichInventoryStockAttachments(ctx, list); + return { code: 200, message: 'ok', data: { list } }; + } + + // 不汇总:逐条明细(含效期/库存预警字段) + const list = this._formatBatchStorageRows(rows, inventoryWarningRanges, nowMs); + await enrichInventoryStockAttachments(ctx, list); + + return { + code: 200, + message: 'ok', + data: { list }, + }; + } + + /** + * 按库位查询库存商品列表:传入 space_id,先判断该库位是否为当前仓库的库位, + * 是则返回该库位下有量库存(quantity > 0)的商品列表,按商品(stock_id)汇总为一条。 + * 商品信息统一走 stock_warehouse 通用链路(getStockDetails),返回 stock_warehouse 通用属性 + * (item_code/item_name/sku_property/stock_unit/is_batch_mgmt/is_shelf_life_mgmt/ + * packing_requirements/need_recheck/barcodes/image_url 等)。 + * + * @param {number} spaceId 库位ID(wms_location_space.id,必填) + * @return {Promise} code/message/data 结构,data 为 { space, list } + */ + async getStorageListBySpaceId(spaceId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // ────────── 1. 参数校验 ────────── + const normalizedSpaceId = Number(spaceId); + if (!Number.isInteger(normalizedSpaceId) || normalizedSpaceId <= 0) { + return { code: 400, message: 'space_id 必填且必须为正整数', data: null }; + } + + const warehouseId = ctx.user && ctx.user.store_id; + if (!warehouseId) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 判断该库位是否属于当前仓库 ────────── + const space = await ctx.model.LocationSpace.findOne({ + where: { + id: normalizedSpaceId, + warehouse_id: warehouseId, + deleted_at: null, + }, + attributes: [ 'id', 'warehouse_id', 'space_code', 'custom_name', 'space_status' ], + raw: true, + }); + + if (!space) { + // 区分「库位不存在」与「库位存在但不属于当前仓库」 + const spaceInOtherWarehouse = await ctx.model.LocationSpace.findOne({ + where: { id: normalizedSpaceId, deleted_at: null }, + attributes: [ 'id', 'warehouse_id' ], + raw: true, + }); + if (spaceInOtherWarehouse) { + return { code: 400, message: `库位 ${normalizedSpaceId} 不属于当前仓库`, data: null }; + } + return { code: 404, message: `库位不存在: space_id=${normalizedSpaceId}`, data: null }; + } + + const spaceInfo = { + id: Number(space.id), + warehouse_id: Number(space.warehouse_id), + space_code: space.space_code || '', + custom_name: space.custom_name || '', + space_status: space.space_status || '', + }; + + // ────────── 3. 查询该库位下有量库存明细(quantity > 0) ────────── + const rows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: warehouseId, + space_id: normalizedSpaceId, + quantity: { [Op.gt]: 0 }, + is_enabled: 1, + delete_at: null, + }, + attributes: [ + 'id', 'warehouse_id', 'store_id', 'space_id', 'stock_id', + 'batch_no', 'inventory_type', 'quantity', 'locked_quantity', + 'intercept_locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', + ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + if (!rows.length) { + return { code: 200, message: 'ok', data: { space: spaceInfo, list: [] } }; + } + + // ────────── 4. 商品通用属性:统一走 stock_warehouse 通用链路(getStockDetails) ────────── + const stockIds = [ ...new Set(rows.map(row => Number(row.stock_id)).filter(Boolean)) ]; + const stockDetailMap = new Map(); + try { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const detail of (Array.isArray(stockDetails) ? stockDetails : [])) { + stockDetailMap.set(Number(detail && detail.id || 0), detail); + } + } catch (error) { + ctx.logger?.warn?.('[storage.inventory] getStorageListBySpaceId 查询商品通用属性失败,stock 降级为 null', { + error: error.message, + }); + } + + // ────────── 5. 货主名称:按当前仓库收敛的签约表 store_remask ────────── + const storeRemarkMap = new Map(); + const storeIds = [ ...new Set(rows.map(row => Number(row.store_id || 0)).filter(Boolean)) ]; + if (storeIds.length > 0) { + try { + const storeRows = await ctx.model.StoreWarehouse.findAll({ + where: { warehouse_id: warehouseId, store_id: { [Op.in]: storeIds } }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const row of storeRows) { + storeRemarkMap.set(Number(row.store_id), row.store_remask || ''); + } + } catch (error) { + ctx.logger?.warn?.('[storage.inventory] getStorageListBySpaceId 查询货主名称失败,store_name 降级为 null', { + error: error.message, + }); + } + } + + // ────────── 6. 按商品(stock_id)汇总为一条 ────────── + const list = this._aggregateStorageRowsByStock(rows, spaceInfo, stockDetailMap, storeRemarkMap); + + return { + code: 200, + message: 'ok', + data: { space: spaceInfo, list }, + }; + } + + /** + * 将同一库位下的库存明细行按商品(stock_id)汇总:汇总数量并统计批次数与最早/最晚入库时间。 + * 商品字段取自 stock_warehouse 通用属性(getStockDetails 返回值,未命中时为 null)。 + * + * @param {Array} rows wms_storage 明细行(Sequelize 实例或 plain 对象) + * @param {Object} [spaceInfo] 库位信息(space_code/custom_name 平铺到每行) + * @param {Map} [stockDetailMap] stock_id → stock_warehouse 通用属性 + * @param {Map} [storeRemarkMap] store_id → 货主名称(store_remask) + * @return {Array} 按商品汇总后的列表 + */ + _aggregateStorageRowsByStock(rows = [], spaceInfo = null, stockDetailMap = null, storeRemarkMap = null) { + const { app } = this; + const location = spaceInfo || {}; + const stockMap = stockDetailMap || new Map(); + const storeMap = storeRemarkMap || new Map(); + const groupedMap = new Map(); + + for (const item of rows) { + const row = item && typeof item.get === 'function' ? item.get({ plain: true }) : item; + const stockId = Number(row.stock_id || 0); + if (!stockId) { + continue; + } + + const quantity = Number(row.quantity || 0); + const lockedQuantity = Number(row.locked_quantity || 0); + const interceptLockedQuantity = Number(row.intercept_locked_quantity || 0); + const availableQuantity = Number(row.available_quantity || 0); + const inboundTimeMs = row.inbound_time ? new Date(row.inbound_time).getTime() : null; + + const existing = groupedMap.get(stockId); + if (!existing) { + groupedMap.set(stockId, { + warehouse_id: row.warehouse_id, + store_id: row.store_id, + space_id: Number(row.space_id || 0), + stock_id: stockId, + quantity, + locked_quantity: lockedQuantity, + intercept_locked_quantity: interceptLockedQuantity, + available_quantity: availableQuantity, + batch_count: 1, + first_inbound_time: inboundTimeMs, + last_inbound_time: inboundTimeMs, + }); + continue; + } + + existing.quantity += quantity; + existing.locked_quantity += lockedQuantity; + existing.intercept_locked_quantity += interceptLockedQuantity; + existing.available_quantity += availableQuantity; + existing.batch_count += 1; + if (inboundTimeMs !== null && (existing.first_inbound_time === null || inboundTimeMs < existing.first_inbound_time)) { + existing.first_inbound_time = inboundTimeMs; + } + if (inboundTimeMs !== null && (existing.last_inbound_time === null || inboundTimeMs > existing.last_inbound_time)) { + existing.last_inbound_time = inboundTimeMs; + } + } + + return [ ...groupedMap.values() ].map(row => ({ + ...row, + space_code: location.space_code || '', + space_name: location.custom_name || location.space_code || '', + store_name: storeMap.get(Number(row.store_id || 0)) || null, + stock: stockMap.get(row.stock_id) || null, + first_inbound_time: row.first_inbound_time ? app.formatDate(row.first_inbound_time) : '', + last_inbound_time: row.last_inbound_time ? app.formatDate(row.last_inbound_time) : '', + })); + } + + /** + * 将库存明细行按库位(space_id)汇总:汇总 quantity/locked_quantity/available_quantity, + * 统计批次数并取最早/最晚入库时间。汇总行不含批次与效期字段,保留商品/库位关联信息。 + * + * @param {Array} rows Sequelize 实例数组(或 plain 对象数组) + * @return {Array} 按库位汇总后的数组 + */ + _aggregateStorageRowsBySpace(rows = []) { + const { app } = this; + const groupedMap = new Map(); + + for (const item of rows) { + const row = item && typeof item.get === 'function' ? item.get({ plain: true }) : item; + const spaceId = Number(row.space_id || 0); + const quantity = Number(row.quantity || 0); + const lockedQuantity = Number(row.locked_quantity || 0); + const availableQuantity = Number(row.available_quantity || 0); + const inboundTimeMs = row.inbound_time ? new Date(row.inbound_time).getTime() : null; + + const existing = groupedMap.get(spaceId); + if (!existing) { + groupedMap.set(spaceId, { + warehouse_id: row.warehouse_id, + store_id: row.store_id, + space_id: spaceId, + stock_id: row.stock_id, + quantity, + locked_quantity: lockedQuantity, + available_quantity: availableQuantity, + batch_count: 1, + first_inbound_time: inboundTimeMs, + last_inbound_time: inboundTimeMs, + stock: row.stock || null, + space: row.space || null, + }); + continue; + } + + existing.quantity += quantity; + existing.locked_quantity += lockedQuantity; + existing.available_quantity += availableQuantity; + existing.batch_count += 1; + if (inboundTimeMs !== null && (existing.first_inbound_time === null || inboundTimeMs < existing.first_inbound_time)) { + existing.first_inbound_time = inboundTimeMs; + } + if (inboundTimeMs !== null && (existing.last_inbound_time === null || inboundTimeMs > existing.last_inbound_time)) { + existing.last_inbound_time = inboundTimeMs; + } + } + + return [ ...groupedMap.values() ].map(row => { + const formatted = { ...row }; + if (formatted.stock) { + formatted.stock = { + ...formatted.stock, + is_batch_mgmt_enabled: toBooleanFlag(formatted.stock.is_batch_mgmt), + store_name: formatted.stock.store_stock?.store_remask || null, + }; + delete formatted.stock.store_stock; + delete formatted.stock.is_batch_mgmt; + } + // 货主名称提升到根层级,便于前端直接使用 + formatted.store_name = formatted.stock?.store_name || null; + formatted.first_inbound_time = formatted.first_inbound_time ? app.formatDate(formatted.first_inbound_time) : ''; + formatted.last_inbound_time = formatted.last_inbound_time ? app.formatDate(formatted.last_inbound_time) : ''; + return formatted; + }); + } + + /** + * 读取当前仓库货主配置中的库存预警规则,并转换为按到期天数递增的区间配置。 + * + * @param {number} warehouseId 仓库ID(货主ID) + * @param {string} logTag 日志标记 + * @return {Promise>} 库存预警规则区间列表 + */ + async _loadInventoryWarningRanges(warehouseId, logTag = 'storage.inventory') { + const { ctx } = this; + try { + const store = await ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + }); + const normalizedSubjectConfig = ctx.model.Store.normalizeSubjectConfig( + store ? store.subject_config : null + ); + return buildInventoryWarningRanges( + normalizedSubjectConfig && Array.isArray(normalizedSubjectConfig.inventory_warning_rules) + ? normalizedSubjectConfig.inventory_warning_rules + : [] + ); + } catch (error) { + ctx.logger.warn(`[${logTag}] 库存预警规则读取失败: ${error.message}`); + return []; + } + } + + /** + * 将库存批次明细查询结果整理为接口返回格式: + * 货主名称提升、批次管理标记布尔化、日期格式化、效期与库存预警字段填充。 + * + * @param {Array} rows Sequelize 实例数组(或 plain 对象数组) + * @param {Array} inventoryWarningRanges 库存预警规则区间 + * @param {number} nowMs 当前时间戳 + * @return {Array} 格式化后的明细数组 + */ + _formatBatchStorageRows(rows = [], inventoryWarningRanges = [], nowMs = Date.now()) { + const { app } = this; + return rows.map(item => { + const row = item && typeof item.get === 'function' ? item.get({ plain: true }) : item; + const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs); + const inventoryWarningPayload = getInventoryWarningPayload( + shelfLifeWarningState.remainingDays, + inventoryWarningRanges + ); + 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.store_name = row.stock?.store_name || null; + 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; + row.expiry_remaining_days = inventoryWarningPayload.expiry_remaining_days; + row.inventory_warning_level = inventoryWarningPayload.inventory_warning_level; + row.inventory_warning_color = inventoryWarningPayload.inventory_warning_color; + row.inventory_warning_range = inventoryWarningPayload.inventory_warning_range; + row.inventory_warning_tip_text = inventoryWarningPayload.inventory_warning_tip_text; + return row; + }); + } + + /** + * 收货单快捷入库:判断货主配置是否允许收货单快捷入库,不允许直接返回失败; + * 允许的话使用收货单的明细创建入库单,相同 stock_id 的合并为一条,汇集总数。 + * 在 wms_entry_order_receiving 表建立绑定关系,入库单自动审批到 PENDING 状态。 + * + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} code/data/message 结构,data 中包含创建的入库单信息 + */ + async quickPutaway(data = {}) { + const { ctx, app } = this; + const receivingId = Number(data.receiving_id || 0); + + // ────────── 1. 参数校验 ────────── + if (!receivingId) { + return { code: 400, message: 'receiving_id 必填', data: null }; + } + + const warehouseId = ctx.user.store_id; + if (!warehouseId) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 加载收货单主表及明细 ────────── + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false }, + }); + + if (!receiving) { + return { code: 404, message: `收货单不存在或无权访问: receiving_id=${receivingId}`, data: null }; + } + + if (receiving.status === 'cancelled') { + return { code: 400, message: '收货单已作废,不允许快捷入库', data: null }; + } + + if (receiving.status !== 'completed') { + return { code: 400, message: `收货单状态不允许快捷入库,当前状态: ${receiving.status},仅 completed 状态可操作`, data: null }; + } + + if (!receiving.is_review) { + return { code: 400, message: '收货单未审核,不允许快捷入库', data: null }; + } + + const storeId = receiving.store_id; + + // ────────── 3. 检查货主配置:是否允许收货单快捷入库 ────────── + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId, warehouse_use_status: 1 }, + attributes: [ 'id', 'policy_config' ], + }); + + if (!storeWarehouse) { + return { code: 400, message: '货主仓库签约关系不存在', data: null }; + } + + const policyConfig = storeWarehouse.policy_config || {}; + const allowQuickPutaway = Number(policyConfig.allow_receiving_quick_putaway) === 1; + + if (!allowQuickPutaway) { + return { code: 400, message: '货主未开启收货单快捷入库功能,请联系管理员开启', data: null }; + } + + // ────────── 4. 加载收货单明细 ────────── + const receivingDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ + 'id', 'system_product_id', 'actual_quantity', 'product_name', + 'batch_number', 'production_date', 'expiry_date', + 'storage_status', 'stored_quantity', + ], + }); + + if (!receivingDetails || receivingDetails.length === 0) { + return { code: 400, message: '收货单无明细,无法创建入库单', data: null }; + } + + // ────────── 5. 按 stock_id(system_product_id)分组,合并数量 ────────── + /** @type {Map} */ + const groupedMap = new Map(); + + for (const detail of receivingDetails) { + const stockId = Number(detail.system_product_id); + if (!stockId) { + // 跳过未匹配系统商品的明细 + continue; + } + + const qty = Number(detail.actual_quantity) || 0; + if (qty <= 0) { + continue; + } + + const existing = groupedMap.get(stockId); + if (existing) { + existing.total_quantity += qty; + existing.detail_ids.push(detail.id); + } else { + groupedMap.set(stockId, { + system_product_id: stockId, + total_quantity: qty, + product_name: detail.product_name || '', + batch_number: detail.batch_number || '', + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + detail_ids: [ detail.id ], + }); + } + } + + if (groupedMap.size === 0) { + return { code: 400, message: '收货单中所有明细均未关联系统商品,无法创建入库单', data: null }; + } + + const groupedItems = Array.from(groupedMap.values()); + + // ────────── 6. 批量查询 stock_warehouse 获取 stock_id 对应的商品信息 ────────── + const stockIds = groupedItems.map(item => item.system_product_id); + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'item_code', 'item_name', 'stock_unit', 'is_valid' ], + raw: true, + }); + const stockMap = new Map(); + for (const row of stockRows) { + stockMap.set(Number(row.id), row); + } + + // 校验所有 stock_id 是否存在且有效 + const missingStockIds = stockIds.filter(sid => !stockMap.has(sid)); + if (missingStockIds.length > 0) { + return { + code: 400, + message: `以下商品在当前仓库中不存在或已失效: stock_id=${missingStockIds.join(',')}`, + data: null, + }; + } + + // ────────── 7. 开事务,创建入库单及明细 ────────── + const transaction = await ctx.model.transaction(); + + try { + // 获取货主和仓库名称快照 + const storeData = await ctx.service.systems.store.getStoreName(storeId); + const storeName = (storeData.code === 200 && storeData.data) ? storeData.data.company_name : ''; + const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId); + const warehouseName = (warehouseData.code === 200 && warehouseData.data) ? warehouseData.data.company_name : ''; + + // 生成入库单号 + const entryOrderCode = await this._generateEntryOrderCode(warehouseId, storeId, transaction); + + // 创建入库单主表(状态直接设为 PENDING) + const entryOrder = await ctx.model.EntryOrder.create({ + entry_order_code: entryOrderCode, + order_type: 'SCRK', + total_order_lines: groupedItems.length, + order_create_time: new Date(), + source_type: 'WMS', + order_status: 'PENDING', + sync_status: 'PENDING', + is_enabled: 1, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + warehouse_name: warehouseName, + remark: `收货单${receiving.receiving_number}快捷入库`, + expense_record: 0, + }, { transaction }); + + const entryOrderId = entryOrder.id; + + // 创建入库单明细(按合并后的分组) + for (let i = 0; i < groupedItems.length; i++) { + const group = groupedItems[i]; + const stockInfo = stockMap.get(group.system_product_id); + + await ctx.model.EntryItems.create({ + order_id: entryOrderId, + out_biz_code: '', + order_line_no: i + 1, + owner_code: '', + item_code: stockInfo ? stockInfo.item_code : '', + item_id: 0, + count: group.total_quantity, + inventory_type: 'ZP', + stock_id: group.system_product_id, + received_quantity: 0, + confirm_quantity: 0, + }, { transaction }); + } + + // ────────── 8. 写入 wms_entry_order_receiving 绑定关系 ────────── + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receivingId, + }, { transaction }); + + // ────────── 9. 更新收货单主表 storage_status ────────── + // 快捷入库后收货单进入"等待入库"状态(后续可通过 matchPutaway 补全) + const [ affectedRows ] = await ctx.model.Receiving.update({ + storage_status: 'waiting', + updated_at: new Date(), + }, { + where: { id: receivingId, storage_status: 'none' }, + transaction, + }); + + if (affectedRows === 0) { + await transaction.rollback(); + return { code: 400, message: '收货单入库状态已变更,可能已被其他操作处理,禁止重复快捷入库', data: null }; + } + + // ────────── 10. 更新收货单明细的 storage_status 为 waiting,stored_quantity 为对应用量 ────────── + for (const group of groupedItems) { + for (const detailId of group.detail_ids) { + const detailRow = receivingDetails.find(d => d.id === detailId); + if (!detailRow) continue; + + // 该明细的总量和已入库量 + const detailTotalQty = Number(detailRow.actual_quantity) || 0; + // 该明细在本次合并中的贡献量按比例计入(简化:按该明细数量在合并总量中的占比) + const detailRatio = group.total_quantity > 0 ? detailTotalQty / group.total_quantity : 0; + const thisStoredQty = Math.round(detailRatio * group.total_quantity); + + const newStoredQty = Math.min(detailTotalQty, (Number(detailRow.stored_quantity) || 0) + thisStoredQty); + // 明细实际数量表示的是该明细的收货量,合并后该 SKU 的明细可能有多条 + // 简化:如果该明细被完全用完则设为 all,否则 waiting(等待手工上架) + const newStorageStatus = newStoredQty >= detailTotalQty ? 'all' : 'waiting'; + + await ctx.model.ReceivingDetail.update({ + storage_status: newStorageStatus, + stored_quantity: newStoredQty, + updated_at: new Date(), + }, { + where: { id: detailId }, + transaction, + }); + } + } + + // ────────── 11. 操作日志 ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrderId, + operationCode: 'ENTRY_ORDER_QUICK_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + storeId, + receivingId, + entryOrderCode, + receivingNumber: receiving.receiving_number, + totalLines: groupedItems.length, + }, + transaction, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.quickPutaway] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 12. 提交事务 ────────── + await transaction.commit(); + + ctx.logger.info(`[inventory.quickPutaway] 快捷入库完成 entryOrderId=${entryOrderId} receivingId=${receivingId} lines=${groupedItems.length}`); + + return { + code: 200, + message: '快捷入库成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrderCode, + order_status: 'PENDING', + receiving_id: receivingId, + total_lines: groupedItems.length, + total_quantity: groupedItems.reduce((sum, g) => sum + g.total_quantity, 0), + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error(`[inventory.quickPutaway] 快捷入库异常 receivingId=${receivingId}: ${error.message}`, error.stack); + return { code: 500, message: `系统异常: ${error.message}`, data: null }; + } + } + + /** + * 收货单直入库存(一步完成):直接写入 wms_storage 库位库存并生成入库单。 + * + * 与 quickPutaway(转入库单,不写库存,明细按 stock_id 合并)的区别: + * - 入库单明细与收货单明细一一对应(不合并),每行按收货明细的库位 space_id 入库; + * - 直接写 wms_storage / wms_stock_warehouse 库存并写入出入库流水,入库单一步置为 COMPLETED。 + * + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} code/data/message 结构,data 中包含创建的入库单信息 + */ + async directPutaway(data = {}) { + const { ctx, app } = this; + const receivingId = Number(data.receiving_id || 0); + + // ────────── 1. 参数校验 ────────── + if (!receivingId) { + return { code: 400, message: 'receiving_id 必填', data: null }; + } + + const warehouseId = ctx.user.store_id; + if (!warehouseId) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 加载收货单主表 ────────── + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false }, + }); + + if (!receiving) { + return { code: 404, message: `收货单不存在或无权访问: receiving_id=${receivingId}`, data: null }; + } + + if (receiving.status === 'cancelled') { + return { code: 400, message: '收货单已作废,不允许直入库存', data: null }; + } + + if (receiving.status !== 'completed') { + return { code: 400, message: `收货单状态不允许直入库存,当前状态: ${receiving.status},仅 completed 状态可操作`, data: null }; + } + + if (!receiving.is_review) { + return { code: 400, message: '收货单未审核,不允许直入库存', data: null }; + } + + const storeId = receiving.store_id; + + // 默认库位:优先使用仓库设置 default_location_id,未设置则兜底库位 1 + let defaultSpaceId = 1; + try { + const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder; + const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function' + ? await deliveryOrderService.getStoreSubjectConfig(warehouseId) + : null; + const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0); + if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) { + defaultSpaceId = configuredLocationId; + } + } catch (error) { + ctx.logger.warn('[inventory.directPutaway] 读取仓库默认库位失败,兜底库位 1: %s', error.message); + } + + // ────────── 3. 检查货主配置:是否允许收货单直入库存 ────────── + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId, warehouse_use_status: 1 }, + attributes: [ 'id', 'policy_config' ], + }); + + if (!storeWarehouse) { + return { code: 400, message: '货主仓库签约关系不存在', data: null }; + } + + const policyConfig = storeWarehouse.policy_config || {}; + const allowDirectPutaway = Number(policyConfig.allow_receiving_direct_putaway) === 1; + + if (!allowDirectPutaway) { + return { code: 400, message: '货主未开启收货单直入库存功能,请联系管理员开启', data: null }; + } + + // ────────── 4. 加载收货单明细 ────────── + const receivingDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ + 'id', 'system_product_id', 'actual_quantity', 'product_name', + 'batch_number', 'production_date', 'expiry_date', + 'space_id', 'storage_status', 'stored_quantity', + ], + }); + + if (!receivingDetails || receivingDetails.length === 0) { + return { code: 400, message: '收货单无明细,无法直入库存', data: null }; + } + + // 过滤出需要入库的明细(排除已全部入库的) + const pendingDetails = receivingDetails.filter( + d => d.storage_status !== 'all' && Number(d.actual_quantity) > 0 + ); + + if (pendingDetails.length === 0) { + return { code: 400, message: '收货单所有明细均已入库,禁止重复直入库存', data: null }; + } + + // 待入库明细必须全部已匹配系统商品 + const unmatchedDetails = pendingDetails.filter(d => !d.system_product_id); + if (unmatchedDetails.length > 0) { + const names = unmatchedDetails.map(d => d.product_name).join('、'); + return { code: 400, message: `以下商品未匹配系统商品,请先绑定: ${names}`, data: null }; + } + + // ────────── 5. 批量查询 stock_warehouse 校验商品有效 ────────── + const stockIds = [ ...new Set(pendingDetails.map(d => Number(d.system_product_id))) ]; + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'item_code', 'item_name', 'stock_unit', 'is_valid' ], + raw: true, + }); + const stockMap = new Map(); + for (const row of stockRows) { + stockMap.set(Number(row.id), row); + } + + const missingStockIds = stockIds.filter(sid => !stockMap.has(sid)); + if (missingStockIds.length > 0) { + return { + code: 400, + message: `以下商品在当前仓库中不存在或已失效: stock_id=${missingStockIds.join(',')}`, + data: null, + }; + } + + // ────────── 6. 开事务:创建入库单 + 直接写库存 ────────── + const transaction = await ctx.model.transaction(); + + try { + // 锁定收货单行,防止并发重复直入 + const lockedReceiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId }, + lock: transaction.LOCK.UPDATE, + transaction, + attributes: [ 'id', 'storage_status' ], + }); + if (!lockedReceiving) { + await transaction.rollback(); + return { code: 404, message: '收货单不存在', data: null }; + } + if (lockedReceiving.storage_status === 'all') { + await transaction.rollback(); + return { code: 400, message: '收货单已全部入库,禁止重复直入库存', data: null }; + } + + // 获取货主和仓库名称快照 + const storeData = await ctx.service.systems.store.getStoreName(storeId); + const storeName = (storeData.code === 200 && storeData.data) ? storeData.data.company_name : ''; + const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId); + const warehouseName = (warehouseData.code === 200 && warehouseData.data) ? warehouseData.data.company_name : ''; + + // 生成入库单号(SCRK) + const entryOrderCode = await this._generateEntryOrderCode(warehouseId, storeId, transaction); + + // 创建入库单主表(直入:一步完成,直接 COMPLETED) + const entryOrder = await ctx.model.EntryOrder.create({ + entry_order_code: entryOrderCode, + order_type: 'SCRK', + total_order_lines: pendingDetails.length, + order_create_time: new Date(), + source_type: 'WMS', + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + is_enabled: 1, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + warehouse_name: warehouseName, + remark: `收货单${receiving.receiving_number}直入库存`, + expense_record: 0, + }, { transaction }); + + const entryOrderId = entryOrder.id; + + // ────────── 7. 创建入库单明细:与收货明细一一对应(不合并) ────────── + // 记录 收货明细ID → 入库明细ID 映射,用于写入 wms_inbound_direct_log + const entryItemIdByDetailId = new Map(); + for (let i = 0; i < pendingDetails.length; i++) { + const detail = pendingDetails[i]; + const stockInfo = stockMap.get(Number(detail.system_product_id)); + const detailQty = Number(detail.actual_quantity) || 0; + + const entryItem = await ctx.model.EntryItems.create({ + order_id: entryOrderId, + out_biz_code: '', + order_line_no: i + 1, + owner_code: '', + item_code: stockInfo ? stockInfo.item_code : '', + item_id: 0, + count: detailQty, + inventory_type: 'ZP', + stock_id: Number(detail.system_product_id), + received_quantity: detailQty, + confirm_quantity: 0, + }, { transaction }); + + entryItemIdByDetailId.set(detail.id, entryItem.id); + } + + // ────────── 8. 写入 wms_entry_order_receiving 主表级绑定 ────────── + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receivingId, + }, { transaction }); + + // ────────── 9. 更新 StockWarehouse 总库存(按 stock_id 聚合) ────────── + const stockQtyMap = new Map(); + for (const detail of pendingDetails) { + const sid = Number(detail.system_product_id); + const qty = Number(detail.actual_quantity) || 0; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + qty); + } + + // stock(wms_stock_warehouse)变更摘要,供操作日志记录 + const stockChangeSummaries = []; + + for (const [ sid, inboundQty ] of stockQtyMap) { + // 悲观行锁 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: sid, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!stockRecord) { + throw new Error(`商品库存记录不存在或已失效,无法直入库存: stock_id=${sid}`); + } + + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + // 商品维度流水(SCRK) + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: sid, + quantity: inboundQty, + batch_no: entryOrderCode, + inventory_type: 'ZP', + order_type: 'SCRK', + order_no: entryOrderCode, + entry_order_id: entryOrderId, + receiving_id: receivingId, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '收货单直入库存', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + + // 收集 stock 变更摘要(wms_stock_warehouse 总量变更) + stockChangeSummaries.push({ + stock_id: sid, + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + change_quantity: inboundQty, + }); + } + + // ────────── 10. 写 wms_storage 库位库存(按收货明细库位 space_id 逐明细写入) ────────── + // storage(wms_storage)变更笔数,供操作日志记录 + let storageWriteCount = 0; + + for (const detail of pendingDetails) { + const sid = Number(detail.system_product_id); + const qty = Number(detail.actual_quantity) || 0; + if (qty <= 0) continue; + + // 收货明细有库位则按其库位入库,否则使用仓库默认库位(未设置时兜底库位 1) + const spaceId = Number(detail.space_id) > 0 ? Number(detail.space_id) : defaultSpaceId; + const batchNo = detail.batch_number || entryOrderCode; + const productionDate = detail.production_date || null; + const expiryDate = detail.expiry_date || null; + const inventoryType = 'ZP'; + + // 查找 库位+SKU+批次+类型 已有的库存记录(悲观行锁) + const sRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: sid, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let sId = null; + let sBeforeQty = 0; + let sAfterQty = 0; + let sBeforeLockedQty = 0; + let sAfterLockedQty = 0; + let sBeforeInterceptQty = 0; + let sAfterInterceptQty = 0; + + if (sRecord) { + if (Number(sRecord.stock_id) !== Number(sid)) { + throw new Error( + `直入库存归属冲突: storage_id=${sRecord.id} 当前 stock_id=${sRecord.stock_id}, ` + + `本次入库 stock_id=${sid}, space_id=${spaceId}, batch_no=${batchNo}` + ); + } + sBeforeQty = Number(sRecord.quantity) || 0; + sAfterQty = sBeforeQty + qty; + sBeforeLockedQty = Number(sRecord.locked_quantity) || 0; + sAfterLockedQty = sBeforeLockedQty; + sBeforeInterceptQty = Number(sRecord.intercept_locked_quantity) || 0; + sAfterInterceptQty = sBeforeInterceptQty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${qty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${qty}`), + entry_order_id: entryOrderId, + inbound_time: new Date(), + inbound_order_no: entryOrderCode, + production_date: productionDate, + expiry_date: expiryDate, + receiving_id: receivingId, + updated_at: new Date(), + }, { + where: { id: sRecord.id }, + transaction, + }); + sId = sRecord.id; + } else { + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: spaceId, + stock_id: sid, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: qty, + locked_quantity: 0, + available_quantity: qty, + inbound_time: new Date(), + inbound_order_no: entryOrderCode, + receiving_id: receivingId, + entry_order_id: entryOrderId, + supplier_id: null, + supplier_batch_no: null, + production_date: productionDate, + expiry_date: expiryDate, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + sId = createdStorage.id; + sAfterQty = qty; + sAfterLockedQty = 0; + } + + storageWriteCount += 1; + + // 库位维度流水(order_type 与现有 storage.entry.commit 链路一致:entry_order) + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: sid, + storage_id: sId, + space_id: spaceId, + quantity: qty, + before_quantity: sBeforeQty, + after_quantity: sAfterQty, + before_locked_quantity: sBeforeLockedQty, + after_locked_quantity: sAfterLockedQty, + before_intercept_locked_quantity: sBeforeInterceptQty, + after_intercept_locked_quantity: sAfterInterceptQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: 'entry_order', + order_no: entryOrderCode, + order_id: entryOrderId, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '收货单直入库存', + created_at: new Date(), + }, { transaction }); + + // 写入导入/PDA 入库记录(status=committed,与 storage.entry.commit 链路一致)。 + // 该表被 storage.receiving.scanDetail、storage.entry.getDirectInboundItems、 + // getReceivingDetailsForBind 的可用数量占用统计等读取,直入也必须写入以保持口径一致。 + await ctx.model.InboundDirectLog.create({ + warehouse_id: warehouseId, + store_id: storeId, + stock_id: sid, + quantity: qty, + inbound_type: 'import', + entry_order_id: entryOrderId, + entry_order_code: entryOrderCode, + entry_item_id: entryItemIdByDetailId.get(detail.id) || 0, + receiving_detail_id: detail.id, + space_id: spaceId, + status: 'committed', + remark: '收货单直入库存', + operator_id: ctx.user?.employees_id || ctx.user?.id || null, + operator_name: ctx.user?.employees_name || '', + }, { transaction }); + } + + // ────────── 11. 回填收货单明细与主表入库状态 ────────── + for (const detail of pendingDetails) { + await ctx.model.ReceivingDetail.update({ + stored_quantity: Number(detail.actual_quantity) || 0, + storage_status: 'all', + updated_at: new Date(), + }, { + where: { id: detail.id }, + transaction, + }); + } + + // 收货单主表 storage_status:统计全部明细状态 + const allStatusRows = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ 'storage_status' ], + raw: true, + transaction, + }); + const allStored = allStatusRows.length > 0 + && allStatusRows.every(d => d.storage_status === 'all'); + await ctx.model.Receiving.update({ + storage_status: allStored ? 'all' : 'partial', + updated_at: new Date(), + }, { + where: { id: receivingId }, + transaction, + }); + + // ────────── 12. 操作日志(entry_order / storage / stock 三种业务维度全量记录) ────────── + try { + const totalDirectQty = pendingDetails.reduce((sum, d) => sum + (Number(d.actual_quantity) || 0), 0); + await ctx.service.systems.operationLog.createOperationLogs([ + { + businessType: 'entry_order', + businessId: entryOrderId, + operationCode: 'ENTRY_ORDER_DIRECT_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + message: `收货单${receiving.receiving_number}直入库存完成,生成入库单${entryOrderCode},共 ${pendingDetails.length} 行明细、${totalDirectQty} 件`, + }, + }, + { + businessType: 'storage', + businessId: entryOrderId, + operationCode: 'STORAGE_DIRECT_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + message: `直入库存写入 wms_storage 库位库存 ${storageWriteCount} 笔(按收货明细库位),共 ${totalDirectQty} 件,入库单号 ${entryOrderCode}`, + }, + }, + { + businessType: 'stock', + businessId: entryOrderId, + operationCode: 'STOCK_DIRECT_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + message: `直入库存更新 wms_stock_warehouse 总库存 ${stockChangeSummaries.length} 个 SKU,共 ${totalDirectQty} 件,变更明细: ${JSON.stringify(stockChangeSummaries)}`, + }, + }, + ], { transaction }); + } catch (logErr) { + ctx.logger.warn('[inventory.directPutaway] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 13. 提交事务 ────────── + await transaction.commit(); + + // 入库完成通知货主(失败不影响主流程) + try { + await ctx.service.systems.inboundDirectLog.notifyEntryOrderCompleted(entryOrder); + } catch (noticeErr) { + ctx.logger.warn('[inventory.directPutaway] 入库完成通知货主失败,不影响业务', noticeErr); + } + + ctx.logger.info(`[inventory.directPutaway] 直入库存完成 entryOrderId=${entryOrderId} receivingId=${receivingId} lines=${pendingDetails.length}`); + + return { + code: 200, + message: '直入库存成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrderCode, + order_status: 'COMPLETED', + receiving_id: receivingId, + total_lines: pendingDetails.length, + total_quantity: pendingDetails.reduce((sum, d) => sum + (Number(d.actual_quantity) || 0), 0), + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error(`[inventory.directPutaway] 直入库存异常 receivingId=${receivingId}: ${error.message}`, error.stack); + return { code: 500, message: `系统异常: ${error.message}`, data: null }; + } + } + + /** + * 导出库存列表(异步任务内部调用,生成 Excel 并上传)。 + * + * where 条件通过 ctx.whereParsed 读取(与 getInventoryList 完全一致), + * 调用方需先执行 prepareWhereContext 设置 ctx.whereParsed。 + * + * 支持两种导出模式: + * - stock_location:按 stock_id + space_id(库位)聚合,汇总数量 + * - storage:按 storage_id 逐条导出明细 + * + * @param {Object} sortParams 排序参数 { sortField, sortOrder } + * @param {boolean} groupByBatch 是否按批次导出(false=聚合,true=逐条明细) + * @return {Promise} 导出上传结果(含 url/fileKey 等) + */ + async exportInventoryList(sortParams = {}, groupByBatch = false) { + const { ctx, app } = this; + const { Op, fn, col, literal } = app.Sequelize; + const warehouseId = ctx.user.store_id; + const { sortField = 'id', sortOrder = 'DESC' } = sortParams; + const safeSortOrder = String(sortOrder).toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const batchSortField = STORAGE_BATCH_SORT_FIELD_WHITELIST.has(sortField) ? sortField : 'id'; + const aggregateOrderField = STORAGE_AGGREGATE_ORDER_FIELD_MAP[sortField] || 'last_inbound_time'; + const pageSize = 500; + let page = 1; + let hasNext = true; + const rows = []; + + // 构建基础 where 条件(与 getInventoryList 完全一致) + const baseWhere = { + [Op.and]: [ + { warehouse_id: warehouseId }, + { is_enabled: 1 }, + { delete_at: null }, + // 仅导出有量库存:明细模式过滤 quantity=0 的行,汇总模式过滤总量为 0 的商品 + { quantity: { [Op.gt]: 0 } }, + ], + }; + + // 动态 where 条件(与 getInventoryList 一致:从 ctx.whereParsed 读取) + const parsed = ctx.whereParsed; + if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { + baseWhere[Op.and].push(...parsed.dynamicConditions); + } + + if (groupByBatch) { + // ────── group_by_batch=true:按 storage_id 逐条导出明细 ────── + while (hasNext) { + const { rows: pageRows } = await ctx.model.Storage.findAndCountAll({ + where: baseWhere, + attributes: [ + 'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', 'inbound_order_no', + 'supplier_batch_no', 'store_id', 'warehouse_id', + 'created_at', 'updated_at', + ], + order: [[ batchSortField, safeSortOrder ]], + offset: (page - 1) * pageSize, + limit: pageSize, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + raw: true, + nest: true, + }); + + if (pageRows.length === 0) { + hasNext = false; + break; + } + + // 收集 store_id 批量查询货主名称 + const storeIds = [ ...new Set(pageRows.map(r => Number(r.store_id)).filter(Boolean)) ]; + const storeMap = new Map(); + if (storeIds.length > 0) { + try { + const storeRows = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { store_id: { [Op.in]: storeIds }, warehouse_id: warehouseId }, + raw: true, + }); + for (const sr of storeRows) { + storeMap.set(Number(sr.store_id), sr.store_remask || ''); + } + } catch (_e) { /* ignore */ } + } + + for (const row of pageRows) { + rows.push({ + storage_id: row.id, + stock_id: row.stock_id, + item_code: row.stock?.item_code || '', + item_name: row.stock?.item_name || '', + sku_property: row.stock?.sku_property || '', + stock_unit: row.stock?.stock_unit || '', + store_name: storeMap.get(Number(row.store_id)) || '', + space_code: row.space?.space_code || '', + space_name: row.space?.custom_name || '', + batch_no: row.batch_no || '', + inventory_type: row.inventory_type || '', + quantity: row.quantity, + locked_quantity: row.locked_quantity, + available_quantity: row.available_quantity, + production_date: row.production_date ? app.formatDate(row.production_date) : '', + expiry_date: row.expiry_date ? app.formatDate(row.expiry_date) : '', + inbound_time: row.inbound_time ? app.formatDate(row.inbound_time) : '', + inbound_order_no: row.inbound_order_no || '', + supplier_batch_no: row.supplier_batch_no || '', + created_at: row.created_at ? app.formatDate(row.created_at) : '', + updated_at: row.updated_at ? app.formatDate(row.updated_at) : '', + }); + } + + hasNext = pageRows.length >= pageSize; + page += 1; + } + } else { + // ────── group_by_batch=false(默认):按 stock_id + space_id 聚合 ────── + const groupFields = [ 'stock_id', 'space_id' ]; + + while (hasNext) { + const pageRows = await ctx.model.Storage.findAll({ + where: baseWhere, + attributes: [ + 'stock_id', + 'space_id', + [ fn('MIN', col('wms_storage.store_id')), 'store_id' ], + [ 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' ], + [ fn('COUNT', col('wms_storage.id')), 'batch_count' ], + [ fn('MAX', col('wms_storage.inbound_time')), 'last_inbound_time' ], + [ fn('MIN', col('wms_storage.created_at')), 'first_created_at' ], + [ fn('MAX', col('wms_storage.updated_at')), 'last_updated_at' ], + ], + group: groupFields, + order: [[ literal(aggregateOrderField), safeSortOrder ]], + offset: (page - 1) * pageSize, + limit: pageSize, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + raw: true, + nest: true, + }); + + if (pageRows.length === 0) { + hasNext = false; + break; + } + + // 收集 store_id 批量查询货主名称 + const storeIds = [ ...new Set(pageRows.map(r => Number(r.store_id)).filter(Boolean)) ]; + const storeMap = new Map(); + if (storeIds.length > 0) { + try { + const storeRows = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { store_id: { [Op.in]: storeIds }, warehouse_id: warehouseId }, + raw: true, + }); + for (const sr of storeRows) { + storeMap.set(Number(sr.store_id), sr.store_remask || ''); + } + } catch (_e) { /* ignore */ } + } + + for (const row of pageRows) { + rows.push({ + stock_id: row.stock_id, + space_id: row.space_id, + item_code: row.stock?.item_code || '', + item_name: row.stock?.item_name || '', + sku_property: row.stock?.sku_property || '', + stock_unit: row.stock?.stock_unit || '', + store_name: storeMap.get(Number(row.store_id)) || '', + space_code: row.space?.space_code || '', + space_name: row.space?.custom_name || '', + quantity: row.quantity, + locked_quantity: row.locked_quantity, + available_quantity: row.available_quantity, + batch_count: row.batch_count, + last_inbound_time: row.last_inbound_time ? app.formatDate(row.last_inbound_time) : '', + created_at: row.first_created_at ? app.formatDate(row.first_created_at) : '', + updated_at: row.last_updated_at ? app.formatDate(row.last_updated_at) : '', + }); + } + + hasNext = pageRows.length >= pageSize; + page += 1; + } + } + + // ── 批量填充商品条码和图片(复用 loadStockAttachments 缓存查询)── + if (rows.length > 0) { + const stockIds = [ ...new Set( + rows.map(r => Number(r.stock_id || 0)).filter(Boolean) + ) ]; + const { barcodesByStockId, imagesByStockId } = await loadStockAttachments(ctx, stockIds); + + for (const row of rows) { + const sid = Number(row.stock_id || 0); + row.barcodes = sid ? (barcodesByStockId.get(sid) || []).join(', ') : ''; + row.image_url = sid ? ((imagesByStockId.get(sid) || [])[0] || '') : ''; + } + } + + // 生成 Excel + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`; + + const modeLabel = groupByBatch ? '库存明细' : '库存汇总'; + const sheetName = groupByBatch ? '库存明细' : '库存汇总(按商品+库位)'; + + const columns = groupByBatch + ? [ + { header: '库存记录ID', key: 'storage_id' }, + { header: '商品编码', key: 'item_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '规格', key: 'sku_property' }, + { header: '库存单位', key: 'stock_unit' }, + { header: '货主', key: 'store_name' }, + { header: '库位编码', key: 'space_code' }, + { header: '库位名称', key: 'space_name' }, + { header: '条码', key: 'barcodes' }, + { header: '图片', key: 'image_url' }, + { header: '批次号', key: 'batch_no' }, + { header: '库存类型', key: 'inventory_type' }, + { header: '数量', key: 'quantity' }, + { header: '锁定数量', key: 'locked_quantity' }, + { header: '可用数量', key: 'available_quantity' }, + { header: '生产日期', key: 'production_date' }, + { header: '过期日期', key: 'expiry_date' }, + { header: '入库时间', key: 'inbound_time' }, + { header: '入库单号', key: 'inbound_order_no' }, + { header: '供应商批次号', key: 'supplier_batch_no' }, + { header: '创建时间', key: 'created_at' }, + { header: '更新时间', key: 'updated_at' }, + ] + : [ + { header: '商品编码', key: 'item_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '规格', key: 'sku_property' }, + { header: '库存单位', key: 'stock_unit' }, + { header: '货主', key: 'store_name' }, + { header: '条码', key: 'barcodes' }, + { header: '图片', key: 'image_url' }, + { header: '库位编码', key: 'space_code' }, + { header: '库位名称', key: 'space_name' }, + { header: '总库存', key: 'quantity' }, + { header: '锁定库存', key: 'locked_quantity' }, + { header: '可用库存', key: 'available_quantity' }, + { header: '批次数', key: 'batch_count' }, + { header: '最近入库时间', key: 'last_inbound_time' }, + { header: '创建时间', key: 'created_at' }, + { header: '更新时间', key: 'updated_at' }, + ]; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: `${modeLabel}导出_${dateToken}.xlsx`, + dir: `exports/storage/inventory/${warehouseId}`, + category: 'document', + sheets: [{ + name: sheetName, + columns, + rows, + }], + }); + } + + /** + * 生成入库单号。 + * 格式:SCRK + 年月日 + 4位流水号 + * + * @param {number} warehouseId 仓库ID + * @param {number} storeId 货主ID + * @param {Object} transaction 数据库事务 + * @return {Promise} 生成的入库单号 + */ + async _generateEntryOrderCode(warehouseId, storeId, transaction) { + const { ctx, app } = this; + const now = new Date(); + const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; + const prefix = `SCRK${dateStr}`; + + // 查询当天该仓库下已有的最大入库单号(全局唯一,不区分货主,避免多货主场景下重复) + const lastOrder = await ctx.model.EntryOrder.findOne({ + where: { + entry_order_code: { [app.Sequelize.Op.like]: `${prefix}%` }, + warehouse_id: warehouseId, + }, + order: [[ 'entry_order_code', 'DESC' ]], + attributes: [ 'entry_order_code' ], + transaction, + raw: true, + paranoid: false, + lock: transaction.LOCK.UPDATE, + }); + + let seq = 1; + if (lastOrder && lastOrder.entry_order_code) { + const seqPart = lastOrder.entry_order_code.slice(prefix.length); + const seqNum = parseInt(seqPart, 10); + if (!Number.isNaN(seqNum)) { + seq = seqNum + 1; + } + } + + return `${prefix}${String(seq).padStart(4, '0')}`; + } +} + +module.exports = InventoryService; diff --git a/app/service/systems/storage/management.js b/app/service/systems/storage/management.js new file mode 100644 index 0000000..09a0a68 --- /dev/null +++ b/app/service/systems/storage/management.js @@ -0,0 +1,422 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 将输入值转换为有限数字。 + * + * @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; +} + +/** + * 库存管理服务层。 + * 负责库存分布分析、补货需求计算等库存管理相关业务逻辑。 + */ +class StorageManagementService extends Service { + /** + * 分拣缺货补货需求计算。 + * + * 仓库级别的计算,针对当前仓库所有未完成储位分配的订单, + * 计算每个 SKU 在分拣区与存货区的可用库存对比, + * 输出分拣区缺口及建议补货量,供仓库人员决策移库。 + * + * 仓库 ID 从用户上下文(ctx.user.store_id / ctx.user.warehouse_id)自动获取,无需显式传入。 + * + * @param {Object} [options={}] 可选项。 + * @param {Object} [options.pagination] 分页参数。 + * @param {number} [options.pagination.page=1] 页码,默认 1。 + * @param {number} [options.pagination.pageSize=20] 每页大小,默认 20。 + * @param {Object} [options.sort] 排序参数。 + * @param {string} [options.sort.sortField='shortage'] 排序字段,默认 shortage。 + * @param {string} [options.sort.sortOrder='DESC'] 排序方向,ASC/DESC。 + * @param {number[]} [options.storeIds] 货主筛选:仅返回指定货主的 SKU,空数组表示不筛选。 + * @return {Promise} 补货需求明细、汇总与分页信息。 + */ + async replenishmentDemand(options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 货主筛选集合(空数组 = 不筛选) + const storeIds = Array.isArray(options.storeIds) ? options.storeIds : []; + const storeFilterSet = storeIds.length > 0 ? new Set(storeIds) : null; + + // 仓库上下文:从用户上下文获取 + const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); + + if (warehouseId <= 0) { + throw new Error('缺少仓库上下文'); + } + + // 1) 获取订单模型和明细模型 + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + + // 2) 查询当前仓库所有未完成储位分配的订单(排除待审核 step=1) + const pendingOrders = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + storage_status: { [Op.ne]: 'fin' }, + step: { [Op.ne]: 1 }, + delete_at: null, + }, + attributes: [ 'id' ], + raw: true, + }); + + const targetOrderIds = (Array.isArray(pendingOrders) ? pendingOrders : []) + .map(row => toNumber(row && row.id, 0)) + .filter(id => id > 0); + + if (targetOrderIds.length === 0) { + return { list: [], summary: { total_skus: 0, total_shortage_skus: 0, total_replenishment_needed: 0, total_true_shortage_skus: 0 } }; + } + + // 3) 查询订单明细,汇总每个 SKU 的需求量 + const itemRows = await orderItemModel.findAll({ + where: { + order_id: { [Op.in]: targetOrderIds }, + }, + attributes: [ 'stock_id', 'plan_qty' ], + raw: true, + }); + + const demandByStockId = new Map(); + const stockIdSet = new Set(); + + for (const row of Array.isArray(itemRows) ? itemRows : []) { + const stockId = toNumber(row.stock_id, 0); + const qty = toNumber(row.plan_qty, 0); + if (stockId <= 0 || qty <= 0) continue; + + demandByStockId.set(stockId, (demandByStockId.get(stockId) || 0) + qty); + stockIdSet.add(stockId); + } + + const allStockIds = Array.from(stockIdSet); + + if (allStockIds.length === 0) { + return { list: [], summary: { total_skus: 0, total_shortage_skus: 0, total_replenishment_needed: 0, total_true_shortage_skus: 0 } }; + } + + // 4) 查询 SKU 基础信息(先严格,漏掉的宽松兜底) + const stockWarehouseRows = allStockIds.length > 0 + ? await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: allStockIds }, + warehouse_id: warehouseId, + is_valid: 'Y', + deleted_at: null, + }, + attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], + raw: true, + }) + : []; + + const stockInfoMap = new Map(); + const hitStockIds = new Set(); + + for (const row of Array.isArray(stockWarehouseRows) ? stockWarehouseRows : []) { + const stockId = toNumber(row.id, 0); + if (stockId <= 0) continue; + stockInfoMap.set(stockId, { + store_id: toNumber(row.store_id, 0), + stock_code: String(row.item_code || ''), + stock_name: String(row.item_name || ''), + }); + hitStockIds.add(stockId); + } + + // 宽松兜底:查询未命中的 SKU(去掉 is_valid 和 warehouse_id 限制) + const missedStockIds = allStockIds.filter(id => !hitStockIds.has(id)); + if (missedStockIds.length > 0) { + const fallbackRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: missedStockIds }, + deleted_at: null, + }, + attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], + raw: true, + }); + + for (const row of Array.isArray(fallbackRows) ? fallbackRows : []) { + const stockId = toNumber(row.id, 0); + if (stockId <= 0 || stockInfoMap.has(stockId)) continue; + stockInfoMap.set(stockId, { + store_id: toNumber(row.store_id, 0), + stock_code: String(row.item_code || ''), + stock_name: String(row.item_name || ''), + }); + } + } + + // 终极兜底:连已删除的也查 + const stillMissedStockIds = allStockIds.filter(id => !stockInfoMap.has(id)); + if (stillMissedStockIds.length > 0) { + const finalFallbackRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: stillMissedStockIds }, + }, + attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], + raw: true, + }); + + for (const row of Array.isArray(finalFallbackRows) ? finalFallbackRows : []) { + const stockId = toNumber(row.id, 0); + if (stockId <= 0 || stockInfoMap.has(stockId)) continue; + stockInfoMap.set(stockId, { + store_id: toNumber(row.store_id, 0), + stock_code: String(row.item_code || ''), + stock_name: String(row.item_name || ''), + }); + } + } + + // 4.5) 查询货主名称与 SKU 条码 + const ownerStoreIds = Array.from( + new Set( + Array.from(stockInfoMap.values()) + .map(info => toNumber(info.store_id, 0)) + .filter(id => id > 0) + ) + ); + + const [ storeWarehouseRows, storeRows, barcodeRows ] = await Promise.all([ + ownerStoreIds.length > 0 + ? ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: ownerStoreIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }) + : [], + ownerStoreIds.length > 0 + ? ctx.model.Store.findAll({ + where: { id: { [Op.in]: ownerStoreIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], + ctx.model.StockBarcode.findAll({ + where: { stock_id: { [Op.in]: allStockIds } }, + attributes: [ 'id', 'stock_id', 'barcode' ], + raw: true, + }), + ]); + + // 货主名称:签约表备注名 store_remask 优先,商家表 company_name 兜底 + const storeNameMap = new Map(); + for (const row of Array.isArray(storeRows) ? storeRows : []) { + const storeId = toNumber(row.id, 0); + if (storeId > 0) storeNameMap.set(storeId, String(row.company_name || '')); + } + for (const row of Array.isArray(storeWarehouseRows) ? storeWarehouseRows : []) { + const storeId = toNumber(row.store_id, 0); + const remask = String(row.store_remask || '').trim(); + if (storeId > 0 && remask) storeNameMap.set(storeId, remask); + } + + // SKU 条码按 stock_id 分组 + const barcodeMap = new Map(); + for (const row of Array.isArray(barcodeRows) ? barcodeRows : []) { + const stockId = toNumber(row.stock_id, 0); + if (stockId <= 0) continue; + const barcodeList = barcodeMap.get(stockId) || []; + barcodeList.push({ + id: toNumber(row.id, 0), + barcode: String(row.barcode || ''), + }); + barcodeMap.set(stockId, barcodeList); + } + + // 5) 查询所有可用库存(不区分分拣/存货区),再按库位类型分类汇总 + const storageRows = allStockIds.length > 0 + ? await ctx.model.Storage.findAll({ + where: { + warehouse_id: warehouseId, + stock_id: { [Op.in]: allStockIds }, + is_enabled: 1, + delete_at: null, + available_quantity: { [Op.gt]: 0 }, + }, + attributes: [ 'stock_id', 'available_quantity', 'space_id' ], + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + required: true, + attributes: [ 'id', 'space_code', 'custom_name' ], + include: [ + { + model: ctx.model.LocationType, + as: 'locationType', + required: true, + attributes: [ 'id', 'allow_allocation', 'is_active' ], + }, + ], + }, + ], + }) + : []; + + // 按 SKU 汇总分拣区与存货区可用库存 + const pickZoneQtyByStockId = new Map(); + const storageZoneQtyByStockId = new Map(); + // 存货区库位明细(用于补货库位推荐) + const storageZoneLocationsByStockId = new Map(); + + for (const storageRow of Array.isArray(storageRows) ? storageRows : []) { + const plainStorage = toPlainRecord(storageRow); + if (!plainStorage) continue; + + const stockId = toNumber(plainStorage.stock_id, 0); + const availableQty = toNumber(plainStorage.available_quantity, 0); + if (stockId <= 0 || availableQty <= 0) continue; + + const space = toPlainRecord(plainStorage.space) || {}; + const locationType = toPlainRecord(space.locationType) || {}; + const allowAllocation = toNumber(locationType.allow_allocation, 0); + const isActive = toNumber(locationType.is_active, 0); + + if (allowAllocation === 1 && isActive === 1) { + // 分拣区 + pickZoneQtyByStockId.set(stockId, (pickZoneQtyByStockId.get(stockId) || 0) + availableQty); + } else { + // 存货区 + storageZoneQtyByStockId.set(stockId, (storageZoneQtyByStockId.get(stockId) || 0) + availableQty); + + // 收集存货区库位明细 + const locationList = storageZoneLocationsByStockId.get(stockId) || []; + locationList.push({ + space_code: String(space.space_code || ''), + space_name: String(space.custom_name || space.space_code || ''), + available_quantity: availableQty, + }); + storageZoneLocationsByStockId.set(stockId, locationList); + } + } + + // 6) 组装输出 + const list = []; + let totalShortageSkus = 0; + let totalReplenishmentNeeded = 0; + let totalTrueShortageSkus = 0; + + for (const stockId of allStockIds) { + const info = stockInfoMap.get(stockId) || { stock_code: `SKU#${stockId}`, stock_name: `商品#${stockId}` }; + + // 货主筛选:仅返回指定货主的 SKU + if (storeFilterSet && !storeFilterSet.has(info.store_id || 0)) continue; + + const totalDemand = demandByStockId.get(stockId) || 0; + const pickZoneQty = pickZoneQtyByStockId.get(stockId) || 0; + const storageZoneQty = storageZoneQtyByStockId.get(stockId) || 0; + const shortage = Math.max(0, totalDemand - pickZoneQty); + const replenishmentNeeded = Math.min(shortage, storageZoneQty); + const replenishmentStatus = storageZoneQty >= shortage ? 'replenishable' : 'true_shortage'; + + // 补货库位信息:按可用库存降序取前 5 条 + const rawLocations = storageZoneLocationsByStockId.get(stockId) || []; + rawLocations.sort((a, b) => (b.available_quantity - a.available_quantity)); + const replenishmentLocations = rawLocations.slice(0, 5); + + if (shortage > 0) { + list.push({ + stock_id: stockId, + stock_code: info.stock_code, + stock_name: info.stock_name, + store_id: info.store_id || 0, + store_name: storeNameMap.get(info.store_id) || '', + barcodes: barcodeMap.get(stockId) || [], + pick_zone_quantity: pickZoneQty, + storage_zone_quantity: storageZoneQty, + total_demand: totalDemand, + shortage, + replenishment_needed: replenishmentNeeded, + replenishment_status: replenishmentStatus, + replenishment_locations: replenishmentLocations, + }); + + totalShortageSkus += 1; + totalReplenishmentNeeded += replenishmentNeeded; + if (replenishmentStatus === 'true_shortage') { + totalTrueShortageSkus += 1; + } + } + } + + // 7) 排序 + const paginationInput = options.pagination || {}; + const sortInput = options.sort || options.order || {}; + const sortField = String(sortInput.sortField || sortInput.field || 'shortage').trim(); + const sortOrderRaw = String(sortInput.sortOrder || sortInput.direction || 'DESC').toUpperCase().trim(); + const sortOrder = sortOrderRaw === 'ASC' ? 1 : -1; + const allowedSortFields = new Set([ + 'stock_id', + 'pick_zone_quantity', + 'storage_zone_quantity', + 'total_demand', + 'shortage', + 'replenishment_needed', + ]); + const effectiveSortField = allowedSortFields.has(sortField) ? sortField : 'shortage'; + + list.sort((a, b) => { + const aVal = a[effectiveSortField] ?? 0; + const bVal = b[effectiveSortField] ?? 0; + return (aVal - bVal) * sortOrder; + }); + + // 8) 内存分页 + const page = Math.max(1, toNumber(paginationInput.page, 1)); + const pageSize = Math.max(1, toNumber(paginationInput.pageSize, 20)); + const total = list.length; + const totalPages = Math.ceil(total / pageSize); + const startIndex = (page - 1) * pageSize; + const pagedList = list.slice(startIndex, startIndex + pageSize); + + return { + list: pagedList, + pagination: { + page, + pageSize, + total, + totalPages, + }, + summary: { + total_skus: totalShortageSkus, + total_shortage_skus: totalShortageSkus, + total_replenishment_needed: totalReplenishmentNeeded, + total_true_shortage_skus: totalTrueShortageSkus, + }, + }; + } +} + +module.exports = StorageManagementService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 15e5149..8e88e6c 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1,12 +1,59 @@ 'use strict'; +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const DAY_MS = 24 * 60 * 60 * 1000; + +const RECEIVING_EXPORT_PAGE_SIZE = 200; +const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 100; + +function getStartOfDayMs(value) { + const date = new Date(value); + if (Number.isNaN(date.getTime())) return null; + date.setHours(0, 0, 0, 0); + return date.getTime(); +} + +/** + * 判断到期日期是否早于当前日期。 + * @param {string|Date|number} expiryDate 到期日期 + * @param {Date} [currentDate=new Date()] 当前日期 + * @return {boolean} 是否已过期 + */ +function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) { + const expiryStartMs = getStartOfDayMs(expiryDate); + if (expiryStartMs === null) return false; + + const currentStartMs = getStartOfDayMs(currentDate); + if (currentStartMs === null) return false; + + return expiryStartMs < currentStartMs; +} + class ReceivingService extends Service { - async getReceivingList(where, pageParams = {}, sortParams = {}) { + /** + * 查询收货单列表。 + * @param {Object} where 动态筛选条件 + * @param {Object} [pageParams] 分页参数 + * @param {number} [pageParams.page=1] 页码 + * @param {number} [pageParams.pageSize=20] 每页条数 + * @param {Object} [sortParams] 排序参数 + * @param {Object} [options] 额外选项 + * @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单 + * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 + * @param {string|string[]} [options.stock_query_where] 可选,按商品维度过滤:搜索条码/商品编码/商品ID,返回明细中含匹配商品的收货单(支持字符串或字符串数组,多个关键字取并集) + * @return {Promise} 列表、分页与汇总信息 + */ + async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) { const { ctx, app, - config, } = this; const { Sequelize, @@ -14,155 +61,292 @@ class ReceivingService extends Service { const { Op, } = Sequelize; - console.log(pageParams); const { page = 1, pageSize = 20, } = pageParams; try { - // 设置默认参数 - - const { sortField = 'id', sortOrder = 'DESC', } = sortParams; + const { filterDepleted = false, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere } = options; - // 构建基础查询条件 const queryOptions = { - where: {}, + where: { + [Op.and]: [ + { + warehouse_id: ctx.user.store_id, + }, + ], + }, order: [], attributes: { exclude: [ 'deleted_at' ], }, }; - const prohibitedQueryOptions = { - where: {}, - }; - // 添加默认条件 - queryOptions.where[Op.and] = [{ - warehouse_id: ctx.user.store_id, - }, - ]; - prohibitedQueryOptions.where[Op.and] = []; - // 检测并处理条码查询条件 - const hasBarcodeCondition = false; - const barcodeCondition = null; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? ctx.where + : (where && typeof where === 'object' ? where : {}); - // 处理动态查询条件 - if (where && Object.keys(where).length > 0) { - const dynamicConditions = []; - const prohibitedConditions = []; - const barcodedynamicConditions = []; + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); - for (const fieldKey in where) { - const condition = where[fieldKey]; - - if (this.isEmptyValue(condition.value)) { - continue; - } - - // 检查是否是快捷查询,快捷查询字段 - if (fieldKey === 'quickWhere') { - dynamicConditions.push({ [Op.or]: { - store_name: { - [Sequelize.Op.like]: `%${condition.value}%`, + if (!parsed.ok) { + return { + code: 400, + data: { + list: [], + pagination: { + page: parseInt(page), + pageSize: parseInt(pageSize), + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, }, - receiving_number: { - [Sequelize.Op.like]: `%${condition.value}%`, + summary: { + total_quantity: 0, + total_locked: 0, + total_available: 0, + total_items: 0, }, - tracking_number: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - creator_snapshot: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - license_plate: { - [Sequelize.Op.like]: `%${condition.value}%`, - }, - } }); - continue; // 暂不添加到动态条件中 - } - // 其他字段的处理 - const sequelizeCondition = this.buildSequelizeCondition(fieldKey, condition, app); - console.log('sequelizeCondition', fieldKey, condition, sequelizeCondition); - if (sequelizeCondition) { - dynamicConditions.push(sequelizeCondition); - } - } - if (dynamicConditions.length > 0) { - queryOptions.where[Op.and].push({ - [Op.and]: dynamicConditions, - }); + }, + message: `筛选条件解析失败: ${parsed.reason}`, + }; } + parsedResult = parsed.result; } - // 处理排序 - const validSortFields = [ - 'id', 'item_code', 'quantity', 'locked_quantity', - 'tag_price', 'retail_price', 'create_at', 'update_at', - ]; + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && !this.isEmptyValue(quickWhereRaw.value)) { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + receiving_number: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + tracking_number: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + creator_snapshot: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + license_plate: { + [Sequelize.Op.like]: `%${quickValue}%`, + }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ + [Op.and]: dynamicConditions, + }); + } + + const validSortFields = [ + 'id', 'receiving_number', 'status', 'create_at', 'update_at', 'store_id', + ]; const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at'; const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; queryOptions.order.push([ actualSortField, actualSortOrder ]); - // 计算分页偏移量 const offset = (page - 1) * pageSize; + const include = [ + { + model: ctx.model.StoreWarehouse, + as: 'store', + attributes: [ 'store_remask' ], + where: { + warehouse_use_status: 1, + warehouse_id: ctx.user.store_id, + }, + required: false, + }, + { + model: ctx.model.AccountStoreEmployee, + as: 'creator', + attributes: [ 'real_name' ], + required: true, + }, + ]; - // 执行查询:获取总数和数据 - const [ total, data ] = await Promise.all([ - // 获取总数 - ctx.model.Receiving.count({ + // 可选过滤:排除无可再用量的收货单 + let filteredReceivingIds = null; + if (filterDepleted) { + const candidateRows = await ctx.model.Receiving.findAll({ + attributes: [ 'id' ], where: queryOptions.where, - include: [{ - model: ctx.model.StoreWarehouse, - as: 'store', - attributes: [ 'store_remask' ], + include, + distinct: true, + raw: true, + }); + const candidateIds = candidateRows.map(r => r.id); + + if (candidateIds.length > 0) { + // 1. 候选收货单明细的 actual_quantity 总和(按 receiving_id 分组) + const detailSums = await ctx.model.ReceivingDetail.findAll({ + attributes: [ + 'receiving_id', + [ Sequelize.fn('SUM', Sequelize.col('actual_quantity')), 'total_actual' ], + ], + where: { receiving_id: { [Op.in]: candidateIds } }, + group: [ 'receiving_id' ], + raw: true, + }); + const totalActualMap = {}; + for (const row of detailSums) { + totalActualMap[row.receiving_id] = Number(row.total_actual) || 0; + } + + // 2. 这些明细对应的 committed 绑定量(按 receiving_detail_id 分组) + const detailIds = detailSums.length > 0 + ? (await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'id' ], + where: { receiving_id: { [Op.in]: candidateIds } }, + raw: true, + })).map(r => r.id) + : []; + + const committedByDetailId = {}; + if (detailIds.length > 0) { + const bindingRows = await ctx.model.InboundDirectLog.findAll({ + attributes: [ + 'receiving_detail_id', + [ Sequelize.fn('SUM', Sequelize.col('quantity')), 'committed_sum' ], + ], + where: { + receiving_detail_id: { [Op.in]: detailIds }, + status: 'committed', + }, + group: [ 'receiving_detail_id' ], + raw: true, + }); + for (const row of bindingRows) { + committedByDetailId[row.receiving_detail_id] = Number(row.committed_sum) || 0; + } + } + + // 3. 计算每个收货单的剩余可用量 = SUM(actual_quantity) - SUM(committed) + const idToDetailIdsMap = {}; + if (detailIds.length > 0) { + const detailIdRows = await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'id', 'receiving_id' ], + where: { id: { [Op.in]: detailIds } }, + raw: true, + }); + for (const d of detailIdRows) { + if (!idToDetailIdsMap[d.receiving_id]) idToDetailIdsMap[d.receiving_id] = []; + idToDetailIdsMap[d.receiving_id].push(d.id); + } + } + + const remainingByReceivingId = {}; + for (const receivingId of candidateIds) { + const totalActual = totalActualMap[receivingId] || 0; + const detailIdList = idToDetailIdsMap[receivingId] || []; + const totalCommitted = detailIdList.reduce((sum, did) => sum + (committedByDetailId[did] || 0), 0); + remainingByReceivingId[receivingId] = totalActual - totalCommitted; + } + + // 过滤:只保留剩余可用量 > 0 的收货单 + filteredReceivingIds = candidateIds.filter(id => remainingByReceivingId[id] > 0); + } else { + filteredReceivingIds = []; + } + } + + // 可选过滤:按入库单商品交集过滤(只返回 system_product_id 有交集的收货单) + let intersectionFilteredIds = null; + if (entryOrderId) { + // 1. 查该入库单的所有 entry_items → stock_id 集合 + const entryItemRows = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'stock_id' ], + raw: true, + }); + const entrySpIdSet = new Set(entryItemRows.map(r => r.stock_id).filter(Boolean)); + + if (entrySpIdSet.size === 0) { + // 入库单无明细 → 不返回任何收货单 + intersectionFilteredIds = []; + } else { + // 2. 查所有收货单明细,找出 system_product_id 在 entrySpIdSet 中的收货单 ID + const matchingDetailRows = await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'receiving_id' ], where: { - use_status: 1, + system_product_id: { [Op.in]: [ ...entrySpIdSet ] }, }, - required: false, - }, { - model: ctx.model.AccountStoreEmployee, - as: 'creator', - attributes: [ 'real_name' ], - required: true, - }], + group: [ 'receiving_id' ], + raw: true, + }); + intersectionFilteredIds = matchingDetailRows.map(r => r.receiving_id); + } + } + + // 可选过滤:按 stock_query_where(商品条码/编码/ID)过滤,支持字符串或字符串数组 + let stockQueryFilteredIds = null; + const stockQueryKeywords = Array.isArray(stockQueryWhere) + ? stockQueryWhere.map(v => String(v).trim()).filter(Boolean) + : (typeof stockQueryWhere === 'string' && stockQueryWhere.trim() !== '' ? [ stockQueryWhere.trim() ] : []); + if (stockQueryKeywords.length > 0) { + stockQueryFilteredIds = await this._resolveStockQueryReceivingIds(stockQueryKeywords); + } + + // 合并 filterDepleted / entry_order_id / stock_query_where 的过滤结果(多组启用时取交集) + let combinedFilteredIds = null; + const idFilterSets = [ filteredReceivingIds, intersectionFilteredIds, stockQueryFilteredIds ] + .filter(arr => arr !== null) + .map(arr => new Set(arr)); + if (idFilterSets.length > 0) { + const [ first, ...rest ] = idFilterSets; + combinedFilteredIds = [ ...first ].filter(id => rest.every(set => set.has(id))); + } + + // 如果启用了过滤,用过滤后的 ID 做最终查询 + const finalWhere = combinedFilteredIds !== null + ? { id: { [Op.in]: combinedFilteredIds } } + : queryOptions.where; + + const [ total, data ] = await Promise.all([ + ctx.model.Receiving.count({ + where: finalWhere, + include, distinct: true, }), - - // 获取分页数据 ctx.model.Receiving.findAll({ ...queryOptions, - include: [{ - model: ctx.model.StoreWarehouse, - as: 'store', - attributes: [ 'store_remask' ], - where: { - use_status: 1, - }, - required: false, - }, { - model: ctx.model.AccountStoreEmployee, - as: 'creator', - attributes: [ 'real_name' ], - required: true, - }], + where: finalWhere, + include, limit: parseInt(pageSize), offset: parseInt(offset), - distinct: true, // 确保去重 + distinct: true, raw: true, }), ]); - // 计算分页信息 const totalPages = Math.ceil(total / pageSize); const hasPrevious = page > 1; const hasNext = page < totalPages; - // 批量查询条码信息 const stockIds = data.map(item => item.id); let images = []; if (stockIds.length > 0) { @@ -173,58 +357,50 @@ class ReceivingService extends Service { [Op.in]: stockIds, }, }, - include: [{ - model: ctx.model.File, - as: 'file', - attributes: [ 'file_url' ], - required: true, - }], + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: true, + }, + ], }); } - // 处理数据,添加一些计算字段 - const processedData = data.map(item => { - const availableQuantity = Math.max(0, item.quantity - item.locked_quantity); - const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed( - 2) : 0; + // 补充货主名称:合约表 store_remask 优先、公司全称兜底(快照 store_name 可能缺失或过期) + const storeNameMap = await this._resolveReceivingStoreNameMap( + data.map(item => item.store_id), + ctx.user.store_id + ); - const { - cos, - } = config; - const { - cdnurl, - } = cos; + const processedData = data.map(item => { + // 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数量 + const availableQuantity = Math.max(0, item.total_quantity || 0); + const lockRate = 0; const itemImages = images - .filter(images => parseInt(images.business_id) === item.id) - .map(images => images.file.file_url); + .filter(row => parseInt(row.business_id) === item.id) + .map(row => row.file.file_url); return { ...item, + // 货主名称:实时解析优先(货主备注 → 公司全称),缺失时回退主表快照 + store_name: storeNameMap.get(Number(item.store_id)) || item.store_name || '', images: itemImages, available_quantity: availableQuantity, lock_rate: parseFloat(lockRate), lock_rate_display: `${lockRate}%`, - create_at_display: item.create_at ? this.formatDate(item.create_at) : '', - update_at_display: item.update_at ? this.formatDate(item.update_at) : '', - // 标记是否通过条码查询匹配 - is_barcode_matched: hasBarcodeCondition && matchedStockIds.includes(item.id), + create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '', + update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '', }; }); - // 添加汇总信息 const summary = { - total_quantity: data.reduce((sum, item) => sum + item.quantity, 0), - total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0), - total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item - .locked_quantity), 0), + total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), + total_locked: 0, + total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), total_items: data.length, - // 如果有条码查询,添加匹配统计 - ...(hasBarcodeCondition && { - barcode_matched_count: matchedStockIds.length, - barcode_search_value: where.barcode.value, - }), }; - return { code: 200, data: { @@ -239,15 +415,14 @@ class ReceivingService extends Service { }, summary, queryInfo: { - conditions: where, + conditions: normalizedWhere, sortField: actualSortField, sortOrder: actualSortOrder, - hasBarcodeSearch: hasBarcodeCondition, + hasBarcodeSearch: stockQueryKeywords.length > 0, }, }, message: '查询成功', }; - } catch (error) { ctx.logger.error('[StockService.getWarehouseStock] 查询失败:', error); return { @@ -273,6 +448,1376 @@ class ReceivingService extends Service { }; } } + + /** + * 按商品关键字解析收货单 ID 列表。 + * 搜索范围: + * 1) wms_stock_warehouse.item_code(商品编码)模糊匹配 + * 2) wms_stock_warehouse.id 精确匹配(关键字为纯数字时) + * 3) wms_stock_barcodes.barcode(条码)模糊匹配 + * 再通过 wms_receiving_detail.system_product_id 关联回收货单。 + * @param {string|string[]} keywords 搜索关键字(字符串或字符串数组,多个关键字取并集) + * @return {Promise} 收货单 ID 数组;关键字为空返回 null + */ + async _resolveStockQueryReceivingIds(keywords) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + + const keywordList = (Array.isArray(keywords) ? keywords : [ keywords ]) + .map(v => String(v).trim()) + .filter(Boolean); + if (keywordList.length === 0) return null; + + const stockIds = new Set(); + + // 1. 商品编码 / 商品ID 匹配(wms_stock_warehouse) + const stockWhere = { + [Op.or]: keywordList.map(k => ({ item_code: { [Op.like]: `%${k}%` } })), + }; + keywordList.forEach(k => { + if (/^\d+$/.test(k)) { + stockWhere[Op.or].push({ id: Number(k) }); + } + }); + const stockRows = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id' ], + where: stockWhere, + raw: true, + }); + stockRows.forEach(row => stockIds.add(Number(row.id))); + + // 2. 条码匹配(wms_stock_barcodes → stock_id) + const barcodeRows = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id' ], + where: { + [Op.or]: keywordList.map(k => ({ barcode: { [Op.like]: `%${k}%` } })), + }, + raw: true, + }); + barcodeRows.forEach(row => stockIds.add(Number(row.stock_id))); + + if (stockIds.size === 0) return []; + + // 3. 通过明细表关联回收货单 + const detailRows = await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'receiving_id' ], + where: { + system_product_id: { [Op.in]: [ ...stockIds ] }, + }, + group: [ 'receiving_id' ], + raw: true, + }); + + return [ ...new Set(detailRows.map(row => row.receiving_id)) ]; + } + + /** + * 批量解析收货单货主名称映射。 + * 货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称,按 store_id + warehouse_id 维度), + * 无合约或备注为空时回退 wms_store.company_name(公司全称)。 + * @param {Array} storeIds 货主ID列表 + * @param {number} warehouseId 仓库ID + * @return {Promise>} store_id → 货主名称 + */ + async _resolveReceivingStoreNameMap(storeIds, warehouseId) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const normalizedIds = [ ...new Set((storeIds || []).map(v => Number(v)).filter(v => v > 0)) ]; + const resultMap = new Map(); + if (normalizedIds.length === 0) return resultMap; + + // 1. 合约表货主备注名称 + const contractRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: normalizedIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const row of contractRows) { + resultMap.set(Number(row.store_id), row.store_remask || ''); + } + + // 2. 货主公司全称兜底 + const storeRows = await ctx.model.Store.findAll({ + where: { id: { [Op.in]: normalizedIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const row of storeRows) { + if (!resultMap.get(Number(row.id))) { + resultMap.set(Number(row.id), row.company_name || ''); + } + } + + return resultMap; + } + + /** + * 货主侧收货单列表查询。 + * 以 store_id 为维度查询收货单,支持分页、多条件筛选与排序。 + * @param {Object} where 动态筛选条件 + * @param {number} storeId 货主ID(必填) + * @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 {Object} [options] 额外选项 + * @param {string|string[]} [options.stock_query_where] 可选,按商品维度过滤:搜索条码/商品编码/商品ID,返回明细中含匹配商品的收货单(支持字符串或字符串数组,多个关键字取并集) + * @return {Promise} 列表、分页与汇总信息 + */ + async getStoreReceivingList(where, storeId, pageParams = {}, sortParams = {}, options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const { page = 1, pageSize = 20 } = pageParams; + const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; + const { stock_query_where: stockQueryWhere } = options; + + try { + const queryOptions = { + where: { + [Op.and]: [ + { store_id: storeId }, + ], + }, + order: [], + attributes: { + exclude: [ 'deleted_at' ], + }, + }; + + const normalizedWhere = where && typeof where === 'object' ? where : {}; + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (!parsed.ok) { + return { + code: 400, + data: { + list: [], + pagination: { page: Number(page), pageSize: Number(pageSize), total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 }, + }, + message: `筛选条件解析失败: ${parsed.reason}`, + }; + } + parsedResult = parsed.result; + } + + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { [Sequelize.Op.like]: `%${quickValue}%` }, + receiving_number: { [Sequelize.Op.like]: `%${quickValue}%` }, + tracking_number: { [Sequelize.Op.like]: `%${quickValue}%` }, + creator_snapshot: { [Sequelize.Op.like]: `%${quickValue}%` }, + license_plate: { [Sequelize.Op.like]: `%${quickValue}%` }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions }); + } + + const validSortFields = [ 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id' ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + queryOptions.order.push([ actualSortField, actualSortOrder ]); + + const offset = (page - 1) * pageSize; + + // 可选过滤:按 stock_query_where(商品条码/编码/ID)过滤,支持字符串或字符串数组 + let stockQueryFilteredIds = null; + const stockQueryKeywords = Array.isArray(stockQueryWhere) + ? stockQueryWhere.map(v => String(v).trim()).filter(Boolean) + : (typeof stockQueryWhere === 'string' && stockQueryWhere.trim() !== '' ? [ stockQueryWhere.trim() ] : []); + if (stockQueryKeywords.length > 0) { + stockQueryFilteredIds = await this._resolveStockQueryReceivingIds(stockQueryKeywords); + } + + const finalWhere = stockQueryFilteredIds !== null + ? { id: { [Op.in]: stockQueryFilteredIds } } + : queryOptions.where; + + const [ total, data ] = await Promise.all([ + ctx.model.Receiving.count({ + where: finalWhere, + distinct: true, + }), + ctx.model.Receiving.findAll({ + ...queryOptions, + where: finalWhere, + limit: Number(pageSize), + offset: Number(offset), + distinct: true, + raw: true, + }), + ]); + + const totalPages = Math.ceil(total / pageSize); + const hasPrevious = page > 1; + const hasNext = page < totalPages; + + // 获取收货单图片 + const stockIds = data.map(item => item.id); + let images = []; + if (stockIds.length > 0) { + images = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receiving', + business_id: { [Op.in]: stockIds }, + }, + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: true, + }, + ], + }); + } + + const processedData = data.map(item => { + const availableQuantity = Math.max(0, item.total_quantity || 0); + const itemImages = images + .filter(row => Number(row.business_id) === item.id) + .map(row => row.file.file_url); + // 从 creator_snapshot 解析操作人姓名 + let creatorName = ''; + try { + if (item.creator_snapshot) { + const snapshot = JSON.parse(item.creator_snapshot); + creatorName = snapshot.name || ''; + } + } catch (_) { + // ignore parse error + } + return { + ...item, + images: itemImages, + available_quantity: availableQuantity, + lock_rate: 0, + lock_rate_display: '0%', + creator_name: creatorName, + create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '', + update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '', + }; + }); + + const summary = { + total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), + total_locked: 0, + total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), + total_items: data.length, + }; + + return { + code: 200, + data: { + list: processedData, + pagination: { + page: Number(page), + pageSize: Number(pageSize), + total, + totalPages, + hasPrevious, + hasNext, + }, + summary, + queryInfo: { + conditions: normalizedWhere, + sortField: actualSortField, + sortOrder: actualSortOrder, + hasBarcodeSearch: stockQueryKeywords.length > 0, + }, + }, + message: '查询成功', + }; + } catch (error) { + ctx.logger.error('[ReceivingService.getStoreReceivingList] 查询失败:', error); + return { + code: 500, + data: { + list: [], + pagination: { page: Number(page || 1), pageSize: Number(pageSize || 20), total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 }, + }, + message: `查询失败: ${error.message}`, + }; + } + } + /** + * 获取收货单详情(主单 + 明细分页 + 图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {Object} data.pagination 分页参数 + * @return {Promise} 详情数据,明细中的 space_id 会优先展示自定义库位名称,其次展示库位编码, + * 并补充 space_id_raw 兼容原始ID;每个明细项同时返回 stock_id(商品/库存ID,语义与 system_product_id 一致,缺失时为 null) + */ + async getReceivingDetail(data) { + const { id, pagination } = data; + const { page, pageSize } = pagination; + const { ctx, app } = this; + const { Op } = app.Sequelize; + // 获取用户仓库ID,增加错误处理 + const warehouseId = ctx.user?.store_id; + if (!warehouseId) { + return { code: 0, message: '用户未绑定仓库', data: {} }; + } + try { + // 1. 查询收货单主表 + const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } }); + if (!receiving) { + return { code: 0, message: '无记录或无权访问', data: {} }; + } + // 补充货主名称:合约表 store_remask 优先、公司全称兜底(快照 store_name 可能缺失或过期) + if (Number(receiving.store_id || 0) > 0) { + const detailStoreNameMap = await this._resolveReceivingStoreNameMap( + [ receiving.store_id ], + Number(receiving.warehouse_id || warehouseId) + ); + const resolvedStoreName = detailStoreNameMap.get(Number(receiving.store_id)); + if (resolvedStoreName) { + receiving.store_name = resolvedStoreName; + } + } + // 2. 查询收货单明细,按分页 + const receivingItems = await app.model.ReceivingDetail.findAll({ + where: { receiving_id: id }, + include: [{ + model: app.model.LocationSpace, + as: 'receiving_space', + attributes: [ 'id', 'custom_name', 'space_code' ], + required: false, + }], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + // 获取明细总数 + const totalItems = await app.model.ReceivingDetail.count({ where: { receiving_id: id } }); + // 组装分页信息 + const detailPagination = { + total: totalItems, + currentPage: page, + pageSize, + totalPages: Math.ceil(totalItems / pageSize), + hasPrevious: page > 1, + hasNext: page < Math.ceil(totalItems / pageSize), + }; + + // 3. 获取明细ID数组 + const receivingItemsIds = receivingItems.map(item => item.id); + // 4. 查询明细图片(如果明细数量大于0) + const itemImagesMap = {}; // 用于存储每个明细的图片 + if (receivingItemsIds.length > 0) { + const receivingItemsImages = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receivingItem', + business_id: { [Op.in]: receivingItemsIds }, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: true, + }], + }); + // 将图片按明细ID分组,并转换为前端可直接使用的链接 + for (const image of receivingItemsImages) { + if (!itemImagesMap[image.business_id]) { + itemImagesMap[image.business_id] = []; + } + itemImagesMap[image.business_id].push({ + id: image.file_id, + url: image.file.file_url, + }); + } + } + // 5. 将图片合并到对应的明细中 + const items = receivingItems.map(item => { + const detail = item.toJSON(); + const { receiving_space: receivingSpace, ...detailBase } = detail; + const spaceName = receivingSpace?.custom_name || receivingSpace?.space_code || null; + return { + ...detailBase, + // 商品/库存ID,语义与 system_product_id 一致,缺失时兜底为 null + stock_id: detailBase.system_product_id ?? null, + space_id_raw: detailBase.space_id ?? null, + space_name: spaceName, + custom_space_name: receivingSpace?.custom_name ?? null, + space_id: spaceName, + box_remainder: detail.box_remainder ?? 0, + box_weight: detail.box_weight ?? 0, + images: itemImagesMap[item.id] || [], + }; + }); + // 6. 查询主表的图片 + const receivingImages = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receiving', + business_id: id, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: true, + }], + }); + // 7. 组装返回数据 + receiving.dataValues.details = items; // 包含图片链接的明细数据 + receiving.dataValues.images = receivingImages.map(image => ({ + id: image.file_id, + url: image.file.file_url, + })); // 包含主表图片链接 + receiving.dataValues.pagination = detailPagination; // 包含分页信息 + return { code: 200, message: '查询成功', data: { receiving } }; + + } catch (error) { + console.error('获取收货单详情失败:', error); + return { code: 500, message: '服务器错误', data: {} }; + } + } + /** + * 批量作废收货单。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @return {Promise} 作废处理结果 + */ + async batchCancelReceiving(data) { + const { ids } = data; + const { ctx } = this; + const { Op } = ctx.model.Sequelize; + const warehouse_id = ctx.user.store_id; + try { + // 先查询这些单据是否都存在且状态允许作废 + const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } }); + if (receivings.length !== ids.length) { + return { code: 0, message: '部分单据不存在或无权访问', data: {} }; + } + const invalidStatus = receivings.find(r => r.status !== 'receiving'); + if (invalidStatus) { + return { code: 0, message: '部分单据状态不允许作废', data: {} }; + } + // 批量更新状态为cancelled + await ctx.model.Receiving.update({ status: 'cancelled' }, { where: { id: { [Op.in]: ids }, warehouse_id } }); + + // 批量记录操作日志 + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + const payloads = ids.map(receivingId => ({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_BATCH_CANCEL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: null, + })); + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(payloads); + } + } catch (logErr) { + ctx.logger.warn('[receiving.batchCancelReceiving] 写入操作日志失败,不影响业务', logErr); + } + + return { code: 200, message: '批量作废成功', data: {} }; + + } catch (error) { + console.error('批量作废收货单失败:', error); + return { code: 500, message: '服务器错误', data: {} }; + } + } + /** + * 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @param {string} [data.remark] 驳回理由(覆盖原备注) + * @return {Promise} 操作结果 + */ + async rejectReceiving(data) { + const { ids, remark } = data; + const { ctx } = this; + const { Op } = ctx.model.Sequelize; + const warehouse_id = ctx.user.store_id; + + if (!Array.isArray(ids) || ids.length === 0) { + return { code: 0, message: '收货单ID不能为空', data: {} }; + } + + const reviewerName = String(ctx.user?.employees_name || '').trim(); + const reviewerEmployeeId = ctx.user?.employees_id || null; + + try { + const receivings = await ctx.model.Receiving.findAll({ + where: { id: { [Op.in]: ids }, warehouse_id }, + }); + + if (receivings.length !== ids.length) { + return { code: 0, message: '部分单据不存在或无权访问', data: {} }; + } + + const nonCompleted = receivings.find(r => r.status !== 'completed'); + if (nonCompleted) { + return { code: 0, message: '只有状态为收货完成的收货单才能驳回', data: {} }; + } + + const alreadyReviewed = receivings.find(r => Number(r.is_review) === 1); + if (alreadyReviewed) { + return { code: 0, message: '存在已审核的收货单,无法驳回', data: {} }; + } + + const alreadyStored = receivings.find(r => r.storage_status === 'partial' || r.storage_status === 'all'); + if (alreadyStored) { + return { code: 0, message: '存在已入库的收货单,无法驳回', data: {} }; + } + + const updateData = { + status: 'receiving', + reviewer_name: reviewerName || null, + reviewer_employee_id: reviewerEmployeeId || null, + }; + if (remark !== undefined && remark !== null) { + updateData.remark = String(remark).trim() || null; + } + + await ctx.model.Receiving.update(updateData, { + where: { id: { [Op.in]: ids }, warehouse_id }, + }); + + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + const payloads = ids.map(receivingId => ({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_REJECT', + operator: { + id: reviewerEmployeeId || ctx.user?.id, + name: reviewerName, + }, + extras: { + warehouseId: warehouse_id, + remark: updateData.remark || '', + }, + beforeChanges: null, + })); + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(payloads); + } + } catch (logErr) { + ctx.logger.warn('[receiving.rejectReceiving] 写入操作日志失败,不影响业务', logErr); + } + + // 发送驳回通知 + try { + const rawNoticeService = ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + const receivingSummaries = receivings.map(item => { + let creator = null; + const rawSnapshot = item && item.creator_snapshot; + if (rawSnapshot && typeof rawSnapshot === 'string') { + try { + creator = JSON.parse(rawSnapshot); + } catch (error) { + creator = null; + } + } else if (rawSnapshot && typeof rawSnapshot === 'object') { + creator = rawSnapshot; + } + + return { + id: Number(item && item.id), + receiving_number: String(item && item.receiving_number || ''), + creator: creator ? { + id: creator.id || creator.employees_id || null, + employees_id: creator.employees_id || creator.id || null, + name: String(creator.name || creator.real_name || '').trim() || null, + } : null, + }; + }); + + if (noticeService) { + await Promise.all(receivingSummaries.map(item => noticeService.send({ + warehouseId: warehouse_id, + messageType: 'text', + businessName: 'receiving', + event: 'receiving_rejected', + channel: 'warehouse', + title: `收货单 ${item.receiving_number || item.id} 已被驳回`, + content: [ + `驳回人:${reviewerName || '未知'}`, + `驳回理由:${updateData.remark || '无'}`, + `收货单ID:${item.id || ''}`, + `收货单号:${item.receiving_number || '无'}`, + `收货创建人:${item.creator && item.creator.name || '无'}`, + '请及时处理重新提交完成收货', + ].join('\n') + '。', + businessId: item.id || ids[0], + subject: { + id: warehouse_id, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: reviewerEmployeeId || ctx.user?.id || null, + name: reviewerName, + }, + metadata: { + receiving_id: item.id || null, + receiving_number: item.receiving_number || '', + receiving_creator: item.creator && item.creator.name ? item.creator.name : null, + warehouseId: warehouse_id, + remark: updateData.remark || '', + }, + }))); + } + } catch (notifyErr) { + ctx.logger.warn('[receiving.rejectReceiving] 发送驳回通知失败,不影响业务', notifyErr); + } + + return { code: 200, message: '驳回成功', data: { count: ids.length } }; + } catch (error) { + ctx.logger.error('[receiving.rejectReceiving] 驳回收货单失败', error); + return { code: 500, message: '服务器错误', data: {} }; + } + } + + /** + * 批量审核收货单:校验所有单据的状态后,用事务批量更新审核信息。 + * 任意一张不符合条件则整批失败并回滚。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @return {Promise} 操作结果 + */ + async reviewReceiving(data) { + const { ids } = data; + const { ctx } = this; + const { Op } = ctx.model.Sequelize; + const warehouse_id = ctx.user.store_id; + + if (!Array.isArray(ids) || ids.length === 0) { + return { code: 0, message: '收货单ID不能为空', data: {} }; + } + + const normalizedIds = Array.from(new Set(ids.map(Number).filter(n => Number.isFinite(n) && n > 0))); + if (normalizedIds.length === 0) { + return { code: 0, message: '收货单ID格式不正确', data: {} }; + } + + const reviewerName = String(ctx.user?.employees_name || '').trim() || null; + const reviewerEmployeeId = ctx.user?.employees_id || null; + + const transaction = await ctx.model.transaction(); + try { + // 加行锁查询,防止并发审核 + const receivings = await ctx.model.Receiving.findAll({ + where: { id: { [Op.in]: normalizedIds }, warehouse_id }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (receivings.length !== normalizedIds.length) { + await transaction.rollback(); + return { code: 0, message: '部分单据不存在或无权访问', data: {} }; + } + + // 逐条校验,收集所有不符合的收货单 + const errors = []; + for (const r of receivings) { + if (r.status !== 'completed') { + errors.push(`收货单 ${r.receiving_number || r.id} 状态非收货完成`); + } + if (r.detail_status !== 'all_matched') { + errors.push(`收货单 ${r.receiving_number || r.id} 明细未全部匹配`); + } + if (r.storage_status !== 'none') { + errors.push(`收货单 ${r.receiving_number || r.id} 已存在入库记录`); + } + if (!r.store_id) { + errors.push(`收货单 ${r.receiving_number || r.id} 未绑定货主`); + } + if (Number(r.is_review) === 1) { + errors.push(`收货单 ${r.receiving_number || r.id} 已审核,无需重复操作`); + } + } + + if (errors.length > 0) { + await transaction.rollback(); + return { code: 0, message: errors.join(';'), data: {} }; + } + + // MySQL 二次状态核实:确保 WHERE 条件精准匹配,防止并发竞争 + const updateResult = await ctx.model.Receiving.update( + { + is_review: 1, + reviewer_name: reviewerName, + reviewer_employee_id: reviewerEmployeeId, + }, + { + where: { + id: { [Op.in]: normalizedIds }, + warehouse_id, + [Op.or]: [ + { is_review: 0 }, + { is_review: null }, + ], + }, + transaction, + } + ); + + const affectedRows = Array.isArray(updateResult) + ? Number(updateResult[0] || 0) + : Number(updateResult || 0); + + if (affectedRows !== normalizedIds.length) { + await transaction.rollback(); + return { code: 0, message: '收货单审核状态已变化,请刷新后重试', data: {} }; + } + + // 写操作日志(失败不影响业务) + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + const payloads = normalizedIds.map(receivingId => ({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_REVIEW', + operator: { + id: reviewerEmployeeId || ctx.user?.id, + name: reviewerName || '', + }, + extras: { warehouseId: warehouse_id }, + beforeChanges: null, + transaction, + })); + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(payloads, { transaction }); + } + } catch (logErr) { + ctx.logger.warn('[receiving.reviewReceiving] 写入操作日志失败,不影响业务', logErr); + } + + await transaction.commit(); + + // 逐单发送审核完成通知(文字 + 文件,失败不影响业务) + const reviewer = { + employees_id: reviewerEmployeeId, + employees_name: reviewerName, + name: reviewerName, + id: reviewerEmployeeId, + }; + + for (const r of receivings) { + const receivingSnapshot = { + ...(typeof r.toJSON === 'function' ? r.toJSON() : r), + is_review: 1, + reviewer_name: reviewerName, + reviewer_employee_id: reviewerEmployeeId, + updated_at: new Date(), + }; + + ctx.logger.info('[receiving.reviewReceiving] 开始处理单据通知', { + receiving_id: r.id, + receiving_number: r.receiving_number, + reviewer: reviewerName, + }); + + // 0. 加载明细并反查货主商品编码(通知文案与报表共用,失败不影响主流程) + let details = []; + let itemCodeMap = new Map(); + try { + details = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: r.id }, + }); + itemCodeMap = await this.resolveReviewDetailItemCodeMap(details); + } catch (detailErr) { + ctx.logger.error('[receiving.reviewReceiving] 加载明细失败', { + receiving_id: r.id, + receiving_number: r.receiving_number, + error: detailErr.message, + }); + } + + // 1. 加载明细与图片,生成 Excel 报表(复用步骤 0 已加载的明细,为空时回退重新查询) + let reviewReport = null; + try { + let reportDetails = details; + if (reportDetails.length === 0) { + reportDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: r.id }, + }); + } + + const detailIds = reportDetails.map(d => String(d.id)); + const detailImageMap = new Map(); + if (detailIds.length > 0) { + const detailImageRefs = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receivingItem', + business_id: { [Op.in]: detailIds }, + }, + include: [{ model: ctx.model.File, as: 'file', attributes: [ 'file_url' ], required: true }], + }); + detailImageRefs.forEach(ref => { + const bid = String(ref.business_id); + if (!detailImageMap.has(bid)) detailImageMap.set(bid, []); + detailImageMap.get(bid).push(ref); + }); + } + + const receivingImages = await ctx.model.FileReference.findAll({ + where: { business_type: 'receiving', business_id: r.id }, + include: [{ model: ctx.model.File, as: 'file', attributes: [ 'file_url' ], required: true }], + }); + + const stats = { + total_details: reportDetails.length, + matched_details: reportDetails.filter(d => d.system_product_id).length, + unmatched_details: reportDetails.filter(d => !d.system_product_id).length, + total_quantity: reportDetails.reduce((sum, d) => sum + (d.actual_quantity || 0), 0), + }; + + const excelService = ctx.service && ctx.service.systems && ctx.service.systems.excel; + if (excelService && typeof excelService.generateAndUpload === 'function') { + const receivingNumber = String(r.receiving_number || r.id).replace(/[\\/:*?"<>|]/g, '_'); + reviewReport = await excelService.generateAndUpload({ + filename: `receiving_review_${receivingNumber}.xlsx`, + dir: `exports/receiving/reviewed/${warehouse_id}`, + category: 'document', + saveRecord: true, + businessType: 'receivingReviewReport', + businessId: r.id, + expireDays: 90, + sheets: this.buildReviewReportSheets({ + receiving: { ...receivingSnapshot, details: reportDetails }, + reviewer, + stats, + detailImageMap, + receivingImages, + }), + }); + } + + ctx.logger.info('[receiving.reviewReceiving] Excel报表生成结果', { + receiving_id: r.id, + receiving_number: r.receiving_number, + success: !!reviewReport, + url: reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || ''), + }); + } catch (reportErr) { + ctx.logger.error('[receiving.reviewReceiving] Excel报表生成失败,回退正文展示明细列表', { + receiving_id: r.id, + error: reportErr.message, + }); + } + + // 2. 发送审核完成通知:Excel 生成成功直接带下载链接,失败则回退正文展示全部明细 + try { + const noticeResult = await this.sendReviewNotice({ + receiving: receivingSnapshot, + reviewer, + reviewReport, + details, + itemCodeMap, + }); + ctx.logger.info('[receiving.reviewReceiving] 审核完成通知结果', { + receiving_id: r.id, + receiving_number: r.receiving_number, + hasReport: !!reviewReport, + success: !!(noticeResult && noticeResult.success), + message: noticeResult && noticeResult.message, + matchedHookCount: Number(noticeResult && noticeResult.data && noticeResult.data.matchedHookCount || 0), + sentCount: Number(noticeResult && noticeResult.data && noticeResult.data.sentCount || 0), + failedCount: Number(noticeResult && noticeResult.data && noticeResult.data.failedCount || 0), + reportUrl: reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || ''), + }); + } catch (noticeErr) { + ctx.logger.error('[receiving.reviewReceiving] 审核完成通知发送失败', { + receiving_id: r.id, + error: noticeErr.message, + }); + } + + ctx.logger.info('[receiving.reviewReceiving] 单据通知处理完成', { + receiving_id: r.id, + receiving_number: r.receiving_number, + hasReport: !!reviewReport, + }); + } + + return { code: 200, message: '审核成功', data: { count: normalizedIds.length } }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[receiving.reviewReceiving] 审核收货单失败', error); + return { code: 500, message: `审核失败: ${error.message}`, data: {} }; + } + } + + /** + * 构建审核完成 Excel 报表 sheets,复用收货完成报表结构,但标注"审核人"而非"完成人"。 + * @param {Object} options 构建参数 + * @param {Object} options.receiving 收货单(需含 details 数组) + * @param {Object} [options.reviewer={}] 审核人信息 + * @param {Object} [options.stats={}] 明细统计 + * @param {Map} [options.detailImageMap] 明细图片 Map(key=detail.id字符串) + * @param {Array} [options.receivingImages] 收货单主图片数组 + * @return {Array} sheets 数组 + */ + buildReviewReportSheets({ + receiving, + reviewer = {}, + stats = {}, + detailImageMap = new Map(), + receivingImages = [], + }) { + const details = Array.isArray(receiving && receiving.details) + ? receiving.details.map(item => (typeof item.toJSON === 'function' ? item.toJSON() : item)) + : []; + const mainImageUrls = (Array.isArray(receivingImages) ? receivingImages : []) + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + + const rows = []; + const embeddedImages = []; + const styledRows = []; + const summaryImageColumnIndex = 3; + const detailColumns = [ + '序号', '商品名称', '条码', + '数量', '重量', '箱数', '托数', + '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', + ]; + const detailImageColumnIndex = detailColumns.length; + const maxDetailImageCount = Math.max( + 1, + ...details.map(detail => { + const imgs = Array.isArray(detailImageMap.get(String(detail.id))) + ? detailImageMap.get(String(detail.id)) + : []; + return imgs + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean).length; + }) + ); + + const buildLinkCell = urls => { + const normalized = (Array.isArray(urls) ? urls : [ urls ]) + .map(item => String(item || '').trim()) + .filter(Boolean); + if (normalized.length === 0) return ''; + return { text: normalized.join('\n'), hyperlink: normalized[0], tooltip: normalized.join('\n') }; + }; + + const pushRow = (cells = [], options = {}) => { + rows.push(cells); + const rowIndex = rows.length; + const maxCol = Math.max(Number(options.toCol || cells.length || 1), 1); + if (options.style || options.height) { + styledRows.push({ + row: rowIndex, + fromCol: Math.max(Number(options.fromCol || 1), 1), + toCol: maxCol, + style: options.style || null, + height: options.height || null, + }); + } + return rowIndex; + }; + + pushRow([]); + + const reviewerName = reviewer.employees_name || reviewer.real_name || reviewer.name || ''; + const reviewedAt = receiving.updated_at || new Date(); + + [ + [ '收货单ID', receiving && receiving.id ], + [ '收货单号', receiving && receiving.receiving_number ], + [ '货主', receiving && receiving.store_name ], + [ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ], + ...this.getCompletionContactFields(receiving), + [ '总明细数', stats.total_details || details.length ], + [ '已匹配明细数', stats.matched_details || 0 ], + [ '未匹配明细数', stats.unmatched_details || 0 ], + [ '总数量', stats.total_quantity || 0 ], + [ '总箱数', receiving && receiving.total_boxes ], + [ '总托盘数', receiving && receiving.total_pallets ], + [ '审核人', reviewerName ], + [ '审核时间', this.formatReportDate(reviewedAt) ], + [ '备注', receiving && receiving.remark ], + ].forEach(([ field, value ]) => { + pushRow([ field, value ], { + toCol: 2, + style: { alignment: { vertical: 'top', wrapText: true } }, + }); + }); + + if (mainImageUrls.length === 0) { + pushRow([ '收货图片', '无' ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true } } }); + } else { + const summaryLinkCell = buildLinkCell(mainImageUrls); + const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill(''); + const firstImageRowIndex = pushRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], { + toCol: 2 + imagePlaceholders.length, + height: 88, + style: { alignment: { vertical: 'top', wrapText: true } }, + }); + mainImageUrls.forEach((imageUrl, index) => { + embeddedImages.push({ row: firstImageRowIndex, col: summaryImageColumnIndex + index, url: imageUrl, width: 96, height: 96, fallbackText: `收货图片${index + 1}` }); + }); + } + + pushRow([]); + pushRow(detailColumns, { + toCol: detailColumns.length, + height: 22, + style: { + font: { bold: true, color: { argb: 'FF1F1F1F' } }, + fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFD9EAF7' } }, + alignment: { horizontal: 'center', vertical: 'middle', wrapText: true }, + }, + }); + + if (details.length === 0) { + pushRow([ '', '', '无明细' ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true } } }); + } else { + details.forEach((detail, index) => { + const imgs = Array.isArray(detailImageMap.get(String(detail.id))) + ? detailImageMap.get(String(detail.id)) + : []; + const imgUrls = imgs + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + const imageSlotCount = Math.max(imgUrls.length, 1); + const linkCell = buildLinkCell(imgUrls); + const rowCells = [ + index + 1, + detail.product_name || '', + detail.barcode || '', + detail.actual_quantity || 0, + detail.weight || 0, + detail.box_quantity || 0, + detail.pallet_quantity || 0, + detail.batch_number || '', + this.formatReportDate(detail.production_date), + this.formatReportDate(detail.expiry_date), + detail.remark || '', + linkCell, + ...Array(imageSlotCount).fill(''), + ]; + const targetRow = pushRow(rowCells, { + toCol: rowCells.length, + height: imgUrls.length > 0 ? 88 : null, + style: { alignment: { vertical: 'top', wrapText: true } }, + }); + imgUrls.forEach((imageUrl, imageIndex) => { + embeddedImages.push({ row: targetRow, col: detailImageColumnIndex + imageIndex, url: imageUrl, width: 96, height: 96, fallbackText: `图片${imageIndex + 1}` }); + }); + }); + } + + return [ + { + name: '审核明细', + rows, + widths: [ + 16, 28, 18, 10, 10, 10, 10, 18, 18, 18, 24, 42, 18, + ...Array(Math.max(maxDetailImageCount - 1, 0)).fill(18), + ], + embeddedImages, + styledRows, + skipHeader: true, + forceExcelJs: true, + }, + ]; + } + + /** + * 发送收货单创建/首次绑定货主通知(receiving_store_bound)。 + * 车牌号/快递单号始终展示登记状态:已登记显示「车牌号:X 已登记」「快递单号:X 已登记」,未登记显示「车牌号:无」「快递单号:无」。 + * 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。 + * @param {Object} options 发送参数 + * @param {Object} options.receiving 收货单快照 + * @param {string|null} [options.storeName=null] 货主名称(优先用合约备注) + * @return {Promise} 发送结果 + */ + async sendStoreBoundNotice({ receiving, storeName = null } = {}) { + const { ctx } = this; + const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + if (!receiving || !noticeService) return null; + + const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0); + const storeId = Number(receiving.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId) || storeId <= 0) { + return null; + } + + const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim(); + const storeLabel = String(storeName || receiving.store_name || '').trim() || '货主'; + const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim(); + + const licensePlate = String(receiving.license_plate || '').trim(); + const trackingNumber = String(receiving.tracking_number || '').trim(); + const vehicleInfoLines = [ + licensePlate ? `车牌号:${licensePlate} 已登记` : '车牌号:无', + trackingNumber ? `快递单号:${trackingNumber} 已登记` : '快递单号:无', + ]; + + const receiverName = this.resolveReceivingCreatorName(receiving); + + const contentLines = [ + `收货单号:${receivingNumber} 正在收货`, + `货主:${storeLabel}`, + ...vehicleInfoLines, + `收货人:${receiverName || '无'}`, + ]; + const content = [ ...contentLines ].join('\n') + '。'; + const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。'; + + return await noticeService.send({ + warehouseId, + storeId, + messageType: 'text', + businessName: 'receiving', + event: 'receiving_store_bound', + channel: 'warehouse', + title: `收货单${receivingNumber}正在收货`, + content, + storeContent, + businessId: receiving.id, + subject: { + id: warehouseId, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: (ctx.user && (ctx.user.employees_id || ctx.user.id)) || null, + name: (ctx.user && ctx.user.employees_name) || '', + }, + metadata: { + receivingId: receiving.id, + receivingNumber, + warehouseId, + storeId, + }, + }); + } + + /** + * 解析收货单创建人(收货人)姓名:优先 creator_snapshot 快照,回退当前操作人。 + * @param {Object} receiving 收货单快照 + * @return {string} 姓名,无则空字符串 + */ + resolveReceivingCreatorName(receiving = {}) { + const { ctx } = this; + const rawSnapshot = receiving.creator_snapshot || null; + let name = ''; + + if (typeof rawSnapshot === 'string' && rawSnapshot.trim()) { + try { + const snapshot = JSON.parse(rawSnapshot); + name = String(snapshot && (snapshot.name || snapshot.employees_name || snapshot.real_name) || '').trim(); + } catch (_) { + /* 快照解析失败忽略 */ + } + } else if (rawSnapshot && typeof rawSnapshot === 'object') { + name = String(rawSnapshot.name || rawSnapshot.employees_name || rawSnapshot.real_name || '').trim(); + } + + if (!name) { + name = String((ctx.user && ctx.user.employees_name) || '').trim(); + } + + return name; + } + + /** + * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。 + * @param {Object} options 发送参数 + * @param {Object} options.receiving 收货单快照 + * @param {Object} [options.reviewer={}] 审核人信息 + * @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知) + * @param {Array|null} [options.details=null] 收货明细列表(用于通知文案展示全部明细) + * @param {Map|null} [options.itemCodeMap=null] system_product_id → item_code 映射 + * @return {Promise} 发送结果 + */ + async sendReviewNotice({ + receiving, + reviewer = {}, + reviewReport = null, + details = null, + itemCodeMap = null, + } = {}) { + const { ctx } = this; + const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + if (!receiving || !receiving.id || !noticeService) return null; + + const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) return null; + + const storeId = Number(receiving.store_id || 0); + const reviewerName = String(reviewer.employees_name || reviewer.real_name || reviewer.name || '').trim(); + const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim(); + const reportUrl = String( + (reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || reviewReport.fileUrl)) || '' + ).trim(); + + const detailList = Array.isArray(details) ? details : []; + const codeMap = itemCodeMap instanceof Map ? itemCodeMap : new Map(); + const productLines = detailList.map((detail, index) => { + const stockId = Number(detail.system_product_id || 0); + const itemCode = (stockId > 0 && codeMap.get(stockId)) || String(detail.barcode || '').trim() || '未知编码'; + const productName = String(detail.product_name || '').trim() || '未知商品'; + const quantity = Number(detail.actual_quantity || 0); + return `${index + 1}.${itemCode} ${productName} ${quantity}`; + }); + const contentLines = [ `收货单号:${receivingNumber} 完成收货审核` ]; + if (reportUrl) { + contentLines.push('', `审核明细下载:${reportUrl}`); + } else if (productLines.length > 0) { + contentLines.push('', '商品:', ...productLines); + } + contentLines.push('', `请及时提交入库单入库,入库单务必备注${receivingNumber}`); + const content = contentLines.join('\n') + '。'; + + return await noticeService.send({ + warehouseId, + storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined, + messageType: 'text', + businessName: 'receiving', + event: 'receiving_reviewed', + channel: 'warehouse', + title: `收货单${receivingNumber}完成收货审核`, + content, + businessId: receiving.id, + subject: { + id: warehouseId, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: reviewer.employees_id || reviewer.id || null, + name: reviewerName, + }, + metadata: { + receivingId: receiving.id, + receivingNumber, + warehouseId, + reviewReport: reportUrl ? { fileKey: reviewReport.fileKey || '', url: reportUrl } : null, + }, + }); + } + + /** + * 反查商品编码:收货明细 system_product_id 优先反查 wms_stock_store.stock_id 取 item_code; + * 无对应货主商品资料时兜底取 wms_stock_warehouse.item_code(库存商品维度)。 + * @param {Array} details 收货明细列表(含 system_product_id) + * @return {Promise>} system_product_id → item_code + */ + async resolveReviewDetailItemCodeMap(details = []) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const codeMap = new Map(); + if (!Array.isArray(details) || details.length === 0) return codeMap; + + const stockIds = [ ...new Set( + details.map(detail => Number(detail.system_product_id || 0)).filter(id => Number.isFinite(id) && id > 0) + ) ]; + if (stockIds.length === 0) return codeMap; + + // 1. 货主商品资料:wms_stock_store.stock_id → item_code(失败不影响主流程) + let rows = []; + try { + rows = await ctx.model.StockStore.findAll({ + where: { + stock_id: { [Op.in]: stockIds }, + delete_at: null, + }, + attributes: [ 'stock_id', 'item_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + } catch (storeErr) { + ctx.logger.warn(`[resolveReviewDetailItemCodeMap] 反查货主商品资料失败: ${storeErr.message}`); + } + + rows.forEach(row => { + const stockId = Number(row.stock_id); + if (!stockId || codeMap.has(stockId)) return; + const itemCode = String(row.item_code || '').trim(); + if (itemCode) codeMap.set(stockId, itemCode); + }); + + // 2. 兜底:无对应 stock_store 时取 wms_stock_warehouse.item_code + const missingStockIds = stockIds.filter(id => !codeMap.has(id)); + if (missingStockIds.length > 0) { + try { + const warehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: missingStockIds }, + deleted_at: null, + }, + attributes: [ 'id', 'item_code' ], + raw: true, + }); + + warehouseRows.forEach(row => { + const stockId = Number(row.id); + if (!stockId || codeMap.has(stockId)) return; + const itemCode = String(row.item_code || '').trim(); + if (itemCode) codeMap.set(stockId, itemCode); + }); + } catch (warehouseErr) { + ctx.logger.warn(`[resolveReviewDetailItemCodeMap] 兜底反查仓库商品失败: ${warehouseErr.message}`); + } + } + + return codeMap; + } + isEmptyValue(value) { if (value === undefined || value === null) { return true; @@ -300,7 +1845,7 @@ class ReceivingService extends Service { Sequelize, } = app; const { - operator = 'eq', value, type, isMultiple, + operator = 'eq', value, type, } = condition; // 处理字段名 @@ -503,8 +2048,6 @@ class ReceivingService extends Service { // 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间 if (Array.isArray(value) && value.length === 2) { const [ startDate, endDate ] = value; - console.log(startDate, endDate); - console.log(startDate ? service.main.normalizeDate(startDate, false) : null, endDate ? service.main.normalizeDate(endDate, true) : null); return [ startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00 endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59 @@ -513,12 +2056,11 @@ class ReceivingService extends Service { return value; case 'number': - // 转换为数字 + { const num = parseFloat(value); return isNaN(num) ? value : num; - + } case 'text': - // 文本类型,支持逗号分隔 if (typeof value === 'string') { return value.split(',').map(item => item.trim()); } @@ -528,6 +2070,54 @@ class ReceivingService extends Service { return value; } } + + buildReceivingNumberPrefix(date = new Date()) { + const dateStr = Math.floor(date.getTime() / (1000 * 60 * 60 * 24)); + return `R${dateStr}`; + } + + async generateNextReceivingNumber(prefix) { + const { app } = this.ctx; + const suffixStartIndex = prefix.length + 1; + + const maxReceiving = await app.model.Receiving.findOne({ + attributes: [ 'receiving_number' ], + where: { + receiving_number: { + [app.Sequelize.Op.like]: `${prefix}%`, + }, + }, + order: [ + [ app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC' ], + [ 'receiving_number', 'DESC' ], + ], + }); + + let sequence = 1; + if (maxReceiving && maxReceiving.receiving_number) { + const lastNumStr = String(maxReceiving.receiving_number).slice(prefix.length); + const lastNum = Number.parseInt(lastNumStr, 10); + if (Number.isFinite(lastNum) && lastNum > 0) { + sequence = lastNum + 1; + } + } + + const seqLen = Math.max(3, String(sequence).length); + return `${prefix}${String(sequence).padStart(seqLen, '0')}`; + } + + isReceivingNumberDuplicateError(error) { + const parentCode = error && error.parent && error.parent.code; + const sqlMessage = String((error && error.parent && error.parent.sqlMessage) || error.message || ''); + return parentCode === 'ER_DUP_ENTRY' + && /uk_receiving_number|receiving_number/i.test(sqlMessage); + } + + /** + * 创建收货单并生成收货单号。 + * @param {Object} data 创建参数 + * @return {Promise} 新建结果(含 id 与 receiving_number) + */ async create(data) { const { delivery_method, @@ -555,74 +2145,115 @@ class ReceivingService extends Service { id: creator_id, }; - // 2. 生成收货单号 (格式: R + 时间戳的day + 3位序列号,如: RR20231215001) - const now = new Date(); - console.log('当前时间:', now); - const dateStr = Math.floor(now.getTime() / (1000 * 60 * 60 * 24)); // 时间戳到今日的天数 - const prefix = `R${dateStr}`; + // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引, + // 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。 + const now = new Date(); + const prefix = this.buildReceivingNumberPrefix(now); - // 查找当天最大的收货单号 - const maxReceiving = await app.model.Receiving.findOne({ - where: { - receiving_number: { - [app.Sequelize.Op.like]: `${prefix}%`, - }, - warehouse_id - }, - order: [[ 'receiving_number', 'DESC' ]], - }); - - let sequence = 1; - if (maxReceiving) { - // 提取最大收货单号的序号部分 - const lastNumStr = maxReceiving.receiving_number.replace(prefix, ''); - const lastNum = parseInt(lastNumStr); - sequence = lastNum + 1; - } - - // 序号动态长度:<1000用3位,<10000用4位,>=10000用5位 - let seqLen = 3; - if (sequence >= 1000 && sequence < 10000) seqLen = 4; - if (sequence >= 10000) seqLen = 5; - const receiving_number = `${prefix}${sequence.toString().padStart(seqLen, '0')}`; // 3. 获取店铺名称(如果有货主) let store_name = null; if (store_id) { const store = await app.model.StoreWarehouse.findOne({ - where: { store_id }, + where: { + store_id, + warehouse_id, + warehouse_use_status: 1, + }, }); if (store) { - store_name = store.store_name; + store_name = store.store_remask; } } - // 4. 创建收货单记录 - const receivingData = { - receiving_number, - creator_id, - creator_snapshot: JSON.stringify(creator_snapshot), - status: status || 'receiving', - detail_status: 'unmatched', - storage_status: 'none', - delivery_method, - license_plate: delivery_method === 'truck' ? license_plate : null, - tracking_number: delivery_method !== 'truck' && delivery_method !== 'other' ? tracking_number : null, - loading_method, - video_device_id: video_device_id || null, - total_boxes: parseInt(total_boxes) || 0, - total_pallets: parseInt(total_pallets) || 0, - total_items: 0, - total_quantity: 0, - warehouse_id, - remark: remark || null, - store_name, - store_id: store_id || null, - receiving_start_time: new Date(), - is_deleted: false, - }; + // 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号) + const maxCreateRetries = 5; + let result = null; + let lastCreateError = null; - // 5. 保存到数据库 - const result = await app.model.Receiving.create(receivingData); + for (let attempt = 1; attempt <= maxCreateRetries; attempt++) { + const receiving_number = await this.generateNextReceivingNumber(prefix); + const receivingData = { + receiving_number, + creator_id, + creator_snapshot: JSON.stringify(creator_snapshot), + status: status || 'receiving', + detail_status: 'unmatched', + storage_status: 'none', + delivery_method, + license_plate: delivery_method === 'truck' ? license_plate : null, + tracking_number: delivery_method !== 'truck' && delivery_method !== 'other' ? tracking_number : null, + loading_method, + video_device_id: video_device_id || null, + total_boxes: parseInt(total_boxes) || 0, + total_pallets: parseInt(total_pallets) || 0, + total_items: 0, + total_quantity: 0, + warehouse_id, + remark: remark || null, + store_name, + store_id: store_id || null, + receiving_start_time: new Date(), + is_deleted: false, + }; + + try { + result = await app.model.Receiving.create(receivingData); + break; + } catch (error) { + lastCreateError = error; + if (this.isReceivingNumberDuplicateError(error) && attempt < maxCreateRetries) { + ctx.logger.warn(`[ReceivingCreateRetry] receiving_number 冲突,准备重试第 ${attempt + 1} 次`, { + prefix, + warehouse_id, + }); + continue; + } + throw error; + } + } + + if (!result) { + throw lastCreateError || new Error('创建收货任务失败'); + } + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: result.id, + operationCode: 'RECEIVING_CREATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.create] 写入操作日志失败,不影响业务', logErr); + } + + // 创建时已绑定货主 → 通知货主正在收货(失败不影响主流程) + if (Number(result.store_id || 0) > 0) { + try { + await this.sendStoreBoundNotice({ + receiving: { + id: result.id, + receiving_number: result.receiving_number, + warehouse_id: result.warehouse_id, + store_id: result.store_id, + store_name: result.store_name, + license_plate: result.license_plate, + tracking_number: result.tracking_number, + creator_snapshot: result.creator_snapshot, + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[receiving.create] 通知货主失败,不影响业务', noticeErr); + } + } return { code: 200, @@ -639,6 +2270,380 @@ class ReceivingService extends Service { }; } } + + /** + * 按ID修改收货单基础信息。 + * @param {Object} data 修改参数 + * @param {number} data.id 收货单ID + * @return {Promise} 修改结果 + */ + async save(data = {}) { + const { + id, + delivery_method, + license_plate, + loading_method, + remark, + status, + store_id, + total_boxes, + total_pallets, + tracking_number, + video_device_id, + } = data; + + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id); + const receivingId = Number(id || 0); + + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库', + }; + } + + if (receivingId <= 0) { + return { + code: 400, + message: '收货单ID不能为空', + }; + } + + const transaction = await ctx.model.transaction(); + + try { + const receiving = await ctx.model.Receiving.findOne({ + where: { + id: receivingId, + warehouse_id: warehouseId, + is_deleted: false, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!receiving) { + await transaction.rollback(); + return { + code: 404, + message: '收货单不存在或无权访问', + }; + } + + if (receiving.status === 'cancelled') { + await transaction.rollback(); + return { + code: 400, + message: '已取消的收货单不允许修改', + }; + } + + let storeName = receiving.store_name || null; + if (Object.prototype.hasOwnProperty.call(data, 'store_id')) { + const normalizedStoreId = Number(store_id || 0); + if (normalizedStoreId > 0) { + const storeRelation = await ctx.model.StoreWarehouse.findOne({ + where: { + warehouse_id: warehouseId, + store_id: normalizedStoreId, + warehouse_use_status: 1, + }, + attributes: [ 'store_id', 'store_remask' ], + transaction, + }); + + if (!storeRelation) { + await transaction.rollback(); + return { + code: 404, + message: '货主不存在或未与当前仓库建立有效签约关系', + }; + } + + storeName = storeRelation.store_remask || null; + } else { + storeName = null; + } + } + + const updateData = { + updated_at: new Date(), + }; + + if (delivery_method !== undefined) { + updateData.delivery_method = delivery_method; + updateData.license_plate = delivery_method === 'truck' + ? (license_plate === undefined ? (receiving.license_plate || null) : (license_plate || null)) + : null; + updateData.tracking_number = delivery_method !== 'truck' && delivery_method !== 'other' + ? (tracking_number === undefined ? (receiving.tracking_number || null) : (tracking_number || null)) + : null; + } else { + if (license_plate !== undefined) { + updateData.license_plate = receiving.delivery_method === 'truck' ? (license_plate || null) : null; + } + if (tracking_number !== undefined) { + updateData.tracking_number = receiving.delivery_method !== 'truck' && receiving.delivery_method !== 'other' + ? (tracking_number || null) + : null; + } + } + + if (loading_method !== undefined) { + updateData.loading_method = loading_method; + } + if (remark !== undefined) { + updateData.remark = remark || null; + } + if (status !== undefined) { + updateData.status = status || 'receiving'; + } + if (Object.prototype.hasOwnProperty.call(data, 'store_id')) { + updateData.store_id = Number(store_id || 0) > 0 ? Number(store_id) : null; + updateData.store_name = storeName; + } + if (total_boxes !== undefined) { + updateData.total_boxes = parseInt(total_boxes) || 0; + } + if (total_pallets !== undefined) { + updateData.total_pallets = parseInt(total_pallets) || 0; + } + if (video_device_id !== undefined) { + updateData.video_device_id = video_device_id || null; + } + + await ctx.model.Receiving.update(updateData, { + where: { + id: receivingId, + warehouse_id: warehouseId, + }, + transaction, + }); + + await transaction.commit(); + + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_UPDATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + delivery_method: receiving.delivery_method, + license_plate: receiving.license_plate, + loading_method: receiving.loading_method, + remark: receiving.remark, + status: receiving.status, + store_id: receiving.store_id, + store_name: receiving.store_name, + total_boxes: receiving.total_boxes, + total_pallets: receiving.total_pallets, + tracking_number: receiving.tracking_number, + video_device_id: receiving.video_device_id, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.save] 写入操作日志失败,不影响业务', logErr); + } + + return { + code: 200, + id: receivingId, + receiving_number: receiving.receiving_number, + message: '收货单修改成功', + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[receiving.save] 修改收货单失败', error); + return { + code: 0, + message: `修改失败: ${error.message}`, + }; + } + } + + /** + * 绑定收货单货主。 + * 规则: + * 1. 已取消收货单禁止绑定; + * 2. 收货中/已完成状态下,若已存在货主,则禁止重复绑定; + * 3. 仅允许绑定与当前仓库存在有效签约关系的货主。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {number} data.store_id 货主ID + * @return {Promise} 绑定结果 + */ + async bindStore(data) { + const { ctx } = this; + const { id, store_id } = data || {}; + const warehouseId = Number(ctx.user && ctx.user.store_id); + const receivingId = Number(id || 0); + const storeId = Number(store_id || 0); + + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库', + }; + } + + if (receivingId <= 0) { + return { + code: 400, + message: '收货单ID不能为空', + }; + } + + if (storeId <= 0) { + return { + code: 400, + message: '货主ID不能为空', + }; + } + + const transaction = await ctx.model.transaction(); + + try { + const receiving = await ctx.model.Receiving.findOne({ + where: { + id: receivingId, + warehouse_id: warehouseId, + is_deleted: false, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!receiving) { + await transaction.rollback(); + return { + code: 404, + message: '收货单不存在或无权访问', + }; + } + + if (receiving.status === 'cancelled') { + await transaction.rollback(); + return { + code: 400, + message: '已取消的收货单不允许绑定货主', + }; + } + + if ([ 'receiving', 'completed' ].includes(receiving.status) && Number(receiving.store_id || 0) > 0) { + await transaction.rollback(); + return { + code: 400, + message: '当前收货单已有货主,拒绝重复绑定', + }; + } + + const storeRelation = await ctx.model.StoreWarehouse.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + warehouse_use_status: 1, + }, + attributes: [ 'store_id', 'store_remask' ], + transaction, + }); + + if (!storeRelation) { + await transaction.rollback(); + return { + code: 404, + message: '货主不存在或未与当前仓库建立有效签约关系', + }; + } + + const storeName = storeRelation.store_remask || null; + await ctx.model.Receiving.update({ + store_id: storeId, + store_name: storeName, + updated_at: new Date(), + }, { + where: { + id: receivingId, + warehouse_id: warehouseId, + }, + transaction, + }); + + await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_BIND_STORE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + store_id: receiving.store_id, + store_name: receiving.store_name, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.bindStore] 写入操作日志失败,不影响业务', logErr); + } + + // 首次绑定货主 → 通知货主正在收货(失败不影响主流程) + try { + await this.sendStoreBoundNotice({ + receiving: { + id: receivingId, + receiving_number: receiving.receiving_number, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + license_plate: receiving.license_plate, + tracking_number: receiving.tracking_number, + creator_snapshot: receiving.creator_snapshot, + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[receiving.bindStore] 通知货主失败,不影响业务', noticeErr); + } + + return { + code: 200, + message: '绑定货主成功', + data: { + id: receivingId, + store_id: storeId, + store_name: storeName, + status: receiving.status, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('绑定收货单货主失败:', error); + return { + code: 500, + message: `绑定货主失败: ${error.message}`, + }; + } + } + + /** + * 查询单个收货单完整信息(含明细、图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @return {Promise} 单据详情 + */ async get(data) { const { id } = data; const { ctx, app } = this; @@ -646,7 +2651,6 @@ class ReceivingService extends Service { // 获取用户仓库ID,增加错误处理 const warehouseId = ctx.user?.store_id; - const creator_id = ctx.user.employees_id; if (!warehouseId) { return { code: 0, message: '用户未绑定仓库', data: {} }; } @@ -663,7 +2667,8 @@ class ReceivingService extends Service { as: 'store', attributes: [ 'store_remask' ], where: { - use_status: 1, + warehouse_use_status: 1, + warehouse_id: warehouseId, }, required: false, }, { @@ -678,7 +2683,6 @@ class ReceivingService extends Service { if (!receiving) { return { code: 0, message: '无记录或无权访问', data: {} }; } - console.log('查询收货单明细'); // 2. 查询收货单明细 const receivingItems = await app.model.ReceivingDetail.findAll({ where: { @@ -731,8 +2735,12 @@ class ReceivingService extends Service { // 5. 将图片合并到对应的明细中 const items = receivingItems.map(item => { const itemData = item.toJSON(); - itemData.images = itemImagesMap[item.id] || []; // 获取该明细的图片,如果没有则为空数组 - return itemData; + return { + ...itemData, + box_remainder: itemData.box_remainder ?? 0, + box_weight: itemData.box_weight ?? 0, + images: itemImagesMap[item.id] || [], // 获取该明细的图片,如果没有则为空数组 + }; }); // 6. 查询主表的图片 @@ -766,9 +2774,21 @@ class ReceivingService extends Service { return { code: 500, message: '服务器错误', data: {} }; } } + + /** + * 向收货单新增一条收货明细。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID + * @param {Object} [data.item] 可选的明细字段 + * @return {Promise} 明细列表与默认选中ID + * @description 未传 `item` 时,保持原有空白明细创建行为;传入 `item` 时,合并默认值后交由 Sequelize 校验与写入,并由服务端覆盖 `receiving_id` 与 `creator_id`。 + */ async addDetail(data) { const ctx = this.ctx; const { receiving_id } = data; + const item = data && data.item && typeof data.item === 'object' && !Array.isArray(data.item) + ? data.item + : {}; // 获取当前用户信息 const creator_id = ctx.user.employees_id; @@ -794,8 +2814,22 @@ class ReceivingService extends Service { } try { - // 创建默认的收货明细 - const newDetail = await ctx.model.ReceivingDetail.create({ + // 默认库位:优先使用仓库设置 default_location_id,未设置则兜底库位 1 + let defaultSpaceId = 1; + try { + const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder; + const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function' + ? await deliveryOrderService.getStoreSubjectConfig(warehouse_id) + : null; + const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0); + if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) { + defaultSpaceId = configuredLocationId; + } + } catch (error) { + ctx.logger.warn('[receiving.addDetail] 读取仓库默认库位失败,兜底库位 1: %s', error.message); + } + + const defaultDetail = { receiving_id, product_name: '新商品', barcode: '', @@ -810,11 +2844,18 @@ class ReceivingService extends Service { production_date: null, expiry_date: null, remark: '', - space_id: 1, + space_id: defaultSpaceId, + creator_id, + }; + + // 允许前端传入可选明细字段,但服务端字段始终覆盖。 + const newDetail = await ctx.model.ReceivingDetail.create({ + ...defaultDetail, + ...item, + receiving_id, creator_id, }); - // 获取更新后的明细列表 const allDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, @@ -843,6 +2884,28 @@ class ReceivingService extends Service { }); await this.updateReceivingStats(receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receiving_id, + operationCode: 'RECEIVING_ADD_DETAIL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: { + detail_id: newDetail.id, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.addDetail] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '添加成功', @@ -861,6 +2924,261 @@ class ReceivingService extends Service { } } + /** + * 绑定或改绑收货单明细的系统商品。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 收货单明细ID(兼容 `id`) + * @param {number} data.system_product_id 商品ID + * @return {Promise} 绑定结果 + */ + async bindDetailProduct(data) { + const { ctx, app } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id); + const detailId = Number((data && (data.detail_id || data.id)) || 0); + const systemProductId = Number((data && data.system_product_id) || 0); + + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库', + }; + } + + if (detailId <= 0) { + return { + code: 400, + message: '收货单明细ID不能为空', + }; + } + + if (systemProductId <= 0) { + return { + code: 400, + message: '商品ID不能为空', + }; + } + + try { + const receivingDetail = await app.model.ReceivingDetail.findOne({ + where: { id: detailId }, + include: [ + { + model: app.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name', 'status', 'is_review' ], + where: { + warehouse_id: warehouseId, + }, + required: true, + }, + ], + }); + + if (!receivingDetail) { + return { + code: 404, + message: '收货单明细不存在', + }; + } + + if (Number(receivingDetail.receiving?.is_review) === 1) { + return { + code: 400, + message: '收货单已审核,禁止绑定或改绑商品', + }; + } + + if (String(receivingDetail.receiving?.status || '') === 'cancelled') { + return { + code: 400, + message: '收货单已作废,禁止绑定或改绑商品', + }; + } + + const stockWarehouse = await app.model.StockWarehouse.findOne({ + where: { + id: systemProductId, + warehouse_id: warehouseId, + }, + include: [ + app.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, + attributes: [ 'store_id', 'store_remask' ], + }), + { + model: app.model.StockBarcode, + as: 'barcodes', + attributes: [ 'barcode' ], + required: false, + }, + ], + }); + + if (!stockWarehouse) { + return { + code: 404, + message: '商品不存在或不属于当前仓库', + }; + } + + const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0); + const receivingStoreId = Number(receivingDetail.receiving?.store_id || 0); + + // 货主校验:收货单已有货主时,只允许绑定同一货主的商品 + if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) { + return { + code: 400, + message: '该商品不属于当前收货单的货主,不允许绑定', + }; + } + + // 收货单无货主时,自动设置为当前商品的货主 + let autoBindStore = false; + if (receivingStoreId <= 0 && productStoreId > 0) { + const storeName = stockWarehouse.store_stock?.store_remask || null; + await app.model.Receiving.update({ + store_id: productStoreId, + store_name: storeName, + updated_at: new Date(), + }, { + where: { id: receivingDetail.receiving_id, warehouse_id: warehouseId }, + }); + autoBindStore = true; + } + + const barcodes = Array.isArray(stockWarehouse.barcodes) + ? stockWarehouse.barcodes.map(item => item && item.barcode).filter(Boolean) + : []; + + let productSnapshot = {}; + if (receivingDetail.product_snapshot) { + try { + productSnapshot = JSON.parse(receivingDetail.product_snapshot) || {}; + } catch { + productSnapshot = {}; + } + } + + const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商品'; + const updateData = { + system_product_id: systemProductId, + product_name: productName, + product_snapshot: JSON.stringify({ + ...productSnapshot, + system_product_id: systemProductId, + product_name: productName, + store_id: productStoreId || productSnapshot.store_id || null, + store_name: stockWarehouse.store_stock?.store_remask || productSnapshot.store_name || null, + updated_at: new Date(), + }), + }; + + // 判断是否为改绑(明细之前已绑定过其他商品) + const isRebind = receivingDetail.system_product_id + && Number(receivingDetail.system_product_id) !== systemProductId; + + // 如果收货明细有条码且商品尚未包含该条码,则自动为商品新增条码 + // 但改绑操作不写入条码(条码属于旧商品上下文,不应污染新商品) + const detailBarcode = String(receivingDetail.barcode || '').trim(); + if (!isRebind && detailBarcode && !barcodes.includes(detailBarcode)) { + try { + await app.model.StockBarcode.create({ + stock_id: systemProductId, + warehouse_id: warehouseId, + barcode: detailBarcode, + }); + barcodes.push(detailBarcode); + } catch (barcodeErr) { + // 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业务 + ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在)', barcodeErr); + } + } + + if (barcodes.length > 0) { + updateData.barcode = barcodes.join(';'); + } + // 毛重处理:stock_warehouse 有毛重时以商品毛重为准; + // 毛重为 0 时,用收货明细的重量回写覆盖 stock_warehouse 的毛重 + const swGrossWeight = Number(stockWarehouse.gross_weight) || 0; + const detailWeight = Number(receivingDetail.weight) || 0; + if (swGrossWeight > 0) { + updateData.weight = swGrossWeight; + } else if (detailWeight > 0) { + try { + await app.model.StockWarehouse.update({ + gross_weight: detailWeight, + updated_at: new Date(), + }, { + where: { id: systemProductId }, + }); + updateData.weight = detailWeight; + } catch (weightErr) { + // 毛重回写失败仅记录日志,不阻断绑定业务 + ctx.logger.warn('[receiving.bindDetailProduct] 回写商品毛重失败,不影响业务', weightErr); + } + } + if (stockWarehouse.enable_box_spec) { + updateData.boxes_per_pallet = stockWarehouse.quantity_per_box || receivingDetail.boxes_per_pallet || 0; + updateData.box_height = stockWarehouse.box_height || receivingDetail.box_height || 0; + updateData.box_width = stockWarehouse.box_width || receivingDetail.box_width || 0; + updateData.box_length = stockWarehouse.box_length || receivingDetail.box_length || 0; + } + + await ctx.model.ReceivingDetail.update(updateData, { + where: { id: detailId }, + }); + + await this.updateReceivingStats(receivingDetail.receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingDetail.receiving_id, + operationCode: 'RECEIVING_BIND_PRODUCT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + detail_id: detailId, + old_system_product_id: receivingDetail.system_product_id, + new_system_product_id: systemProductId, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.bindDetailProduct] 写入操作日志失败,不影响业务', logErr); + } + + const responseData = { + detail_id: detailId, + receiving_id: receivingDetail.receiving_id, + system_product_id: systemProductId, + product_name: productName, + }; + if (autoBindStore) { + responseData.auto_bind_store_id = productStoreId; + responseData.auto_bind_store_name = stockWarehouse.store_stock?.store_remask || null; + } + + return { + code: 200, + message: autoBindStore ? '绑定商品成功,已自动设置货主' : '绑定商品成功', + data: responseData, + }; + } catch (error) { + ctx.logger.error('绑定收货单明细商品失败:', error); + return { + code: 500, + message: `绑定商品失败: ${error.message}`, + }; + } + } + async updateDetail(data) { const ctx = this.ctx; const { id, ...updateData } = data; @@ -1034,11 +3352,11 @@ class ReceivingService extends Service { const stockWarehouse = await ctx.model.StockWarehouse.findOne({ where: { id: stock_id }, include: [ - { - model: ctx.model.StoreWarehouse, - as: 'store_stock', + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId: ctx.user.store_id, + required: false, attributes: [ 'store_id', 'store_remask' ], - }, + }), ], }); @@ -1072,7 +3390,9 @@ class ReceivingService extends Service { where: { warehouse_id: warehouseId, id: receivingId, - status: 'receiving', + status: { + [Op.ne]: 'cancelled', + }, }, lock: transaction.LOCK.UPDATE, transaction, @@ -1099,7 +3419,6 @@ class ReceivingService extends Service { }, transaction, }); - console.log('matchedDetail第一个有绑定的商品', matchedDetail); if (matchedDetail && matchedDetail.system_product_id) { try { // 调用 getStockStoreInfo 获取库存信息 @@ -1156,6 +3475,7 @@ class ReceivingService extends Service { }; // 只在有值且收货单当前没有这些值时更新 store 信息 + const firstBoundStore = !!storeId && !receiving.store_id; if (storeId && !receiving.store_id) { updateData.store_id = storeId; updateData.store_name = storeName; @@ -1175,6 +3495,26 @@ class ReceivingService extends Service { // 6. 提交事务 await transaction.commit(); + // 首次自动绑定货主 → 通知货主正在收货(失败不影响主流程) + if (firstBoundStore) { + try { + await this.sendStoreBoundNotice({ + receiving: { + id: receivingId, + receiving_number: receiving.receiving_number, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + license_plate: receiving.license_plate, + tracking_number: receiving.tracking_number, + creator_snapshot: receiving.creator_snapshot, + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[receiving.updateReceivingStats] 通知货主失败,不影响业务', noticeErr); + } + } + ctx.logger.info(`成功更新收货单 ${receivingId} 的统计信息`); } catch (error) { @@ -1182,20 +3522,25 @@ class ReceivingService extends Service { if (transaction) { await transaction.rollback(); } - console.log(error); ctx.logger.error('更新收货单统计失败:', error); throw error; } } + /** + * 删除收货单明细并回算统计。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 明细ID + * @return {Promise} 删除结果,data.details 为删除后剩余明细列表(字段与 getReceivingDetail 明细项保持一致,含 stock_id) + */ async deleteDetail(data) { const ctx = this.ctx; const { detail_id } = data; - const creator_id = ctx.user.employees_id; const warehouse_id = ctx.user.store_id; - // 验证明细是否存在 + // 验证明细是否存在(通过收货单的 warehouse_id 做权限校验,不限制 creator_id, + // 以允许同一仓库下不同操作员删除彼此创建的明细,与 get 方法行为保持一致) const detail = await ctx.model.ReceivingDetail.findOne({ - where: { id: detail_id, creator_id }, + where: { id: detail_id }, include: [ { model: ctx.model.Receiving, @@ -1266,6 +3611,9 @@ class ReceivingService extends Service { } } + // 商品/库存ID,与 getReceivingDetail 明细项字段保持一致,缺失时兜底为 null + detailData.stock_id = detailData.system_product_id ?? null; + return detailData; }); @@ -1276,6 +3624,30 @@ class ReceivingService extends Service { selectId = remainingDetails[0].id; } await this.updateReceivingStats(receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receiving_id, + operationCode: 'RECEIVING_DELETE_DETAIL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: { + detail_id, + product_name: detail.product_name, + actual_quantity: detail.actual_quantity, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.deleteDetail] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '删除成功', @@ -1293,6 +3665,11 @@ class ReceivingService extends Service { }; } } + /** + * 修改收货明细。 + * @param {Object} data 收货明细修改参数 + * @return {Promise} 修改结果 + */ async detailChange(data) { const { ctx, app } = this; const warehouseId = ctx.user.store_id; @@ -1318,8 +3695,9 @@ class ReceivingService extends Service { box_height, box_length, weight, + box_remainder, // 箱余数 + box_weight, // 箱重量 } = data; - console.log('barcode', barcode); // 2. 验证必填字段 if (!id) { return { @@ -1335,7 +3713,6 @@ class ReceivingService extends Service { }; } - // 3. 获取收货明细信息 const receivingDetail = await app.model.ReceivingDetail.findOne({ where: { id }, @@ -1361,6 +3738,12 @@ class ReceivingService extends Service { }; } + if (expiry_date && expiry_date !== undefined && isExpiryDateBeforeToday(expiry_date)) { + return { + code: 400, + message: '到期日期已过期,不能录入收货', + }; + } // 5. 验证箱规数据 if (box_quantity !== undefined && box_quantity < 0) { @@ -1377,6 +3760,20 @@ class ReceivingService extends Service { }; } + if (box_remainder !== undefined && box_remainder < 0) { + return { + code: 400, + message: '箱余数不能为负数', + }; + } + + if (box_weight !== undefined && box_weight < 0) { + return { + code: 400, + message: '箱重量不能为负数', + }; + } + // 6. 准备更新数据 const updateData = { actual_quantity, @@ -1393,6 +3790,8 @@ class ReceivingService extends Service { if (box_width !== undefined) updateData.box_width = box_width || 0; if (box_height !== undefined) updateData.box_height = box_height || 0; if (weight !== undefined) updateData.weight = weight || 0; + if (box_remainder !== undefined) updateData.box_remainder = box_remainder || 0; + if (box_weight !== undefined) updateData.box_weight = box_weight || 0; // 批次信息 if (batch_number !== undefined) updateData.batch_number = batch_number; @@ -1411,11 +3810,11 @@ class ReceivingService extends Service { warehouse_id: warehouseId, }, include: [ - { - model: app.model.StoreWarehouse, - as: 'store_stock', + app.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, attributes: [ 'store_id', 'store_remask' ], - }, + }), { model: app.model.StockBarcode, as: 'barcodes', @@ -1428,7 +3827,6 @@ class ReceivingService extends Service { if (stockWarehouse) { // 更新商品相关信息 updateData.system_product_id = system_product_id; - console.log('商品信息', stockWarehouse); // 使用系统商品的条码(如果前端没有提供) const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || []; updateData.barcode = updateData.barcode || barcodes.join(';'); @@ -1473,13 +3871,36 @@ class ReceivingService extends Service { updateData.space_id = space_id; } } - console.log('更新收货明细', updateData); // 8. 更新收货明细 await ctx.model.ReceivingDetail.update(updateData, { where: { id }, }); - console.log('更新收货明细2'); await this.updateReceivingStats(receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receiving_id, + operationCode: 'RECEIVING_UPDATE_DETAIL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + detail_id: id, + product_name: receivingDetail.product_name, + actual_quantity: receivingDetail.actual_quantity, + system_product_id: receivingDetail.system_product_id, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.detailChange] 写入操作日志失败,不影响业务', logErr); + } + // 9. 返回成功响应 return { code: 200, @@ -1490,6 +3911,8 @@ class ReceivingService extends Service { product_name: receivingDetail.product_name, barcode: receivingDetail.barcode, system_product_id: receivingDetail.system_product_id, + box_remainder: updateData.box_remainder !== undefined ? updateData.box_remainder : receivingDetail.box_remainder, + box_weight: updateData.box_weight !== undefined ? updateData.box_weight : receivingDetail.box_weight, updated_at: receivingDetail.updated_at, }, message: '修改成功', @@ -1604,6 +4027,27 @@ class ReceivingService extends Service { // 8. 提交事务 await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_CANCEL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + previous_status: receiving.status, + invalid_reason, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.invalid] 写入操作日志失败,不影响业务', logErr); + } return { code: 200, @@ -1620,7 +4064,6 @@ class ReceivingService extends Service { }; } catch (error) { - console.log(error); // 10. 回滚事务 if (transaction) { await transaction.rollback(); @@ -1637,6 +4080,505 @@ class ReceivingService extends Service { throw error; } } + formatReportDate(value) { + if (!value) { + return ''; + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + return ''; + } + + return date.toLocaleString('zh-CN', { hour12: false }); + } + + formatDeliveryMethod(value) { + const methodMap = { + truck: '货车', + express: '快递', + air_freight: '空运', + sea_freight: '海运', + other: '其他', + }; + + const normalizedValue = String(value || '').trim(); + return methodMap[normalizedValue] || normalizedValue; + } + + /** + * 获取完成收货时需要展示的联系字段。 + * @param {Object} receiving 收货单快照。 + * @return {Array} 需要展示的联系字段列表。 + */ + getCompletionContactFields(receiving) { + const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim(); + + if (deliveryMethod === 'truck') { + return [[ '车牌号', receiving && receiving.license_plate ]]; + } + + if (deliveryMethod === 'express') { + return [[ '物流单号', receiving && receiving.tracking_number ]]; + } + + return []; + } + + /** + * 生成收货完成报表的工作表数据。 + * @param {Object} options 报表参数。 + * @param {Object} options.receiving 收货单快照。 + * @param {Object} [options.operator={}] 操作人信息。 + * @param {Object} [options.stats={}] 收货统计数据。 + * @param {Map} [options.detailImageMap=new Map()] 明细图片映射。 + * @param {Array} [options.receivingImages=[]] 收货单图片列表。 + * @return {Array} 工作表列表。 + */ + buildCompletionReportSheets({ + receiving, + operator = {}, + stats = {}, + detailImageMap = new Map(), + receivingImages = [], + }) { + const details = Array.isArray(receiving && receiving.details) + ? receiving.details.map(item => (typeof item.toJSON === 'function' ? item.toJSON() : item)) + : []; + const mainImageUrls = (Array.isArray(receivingImages) ? receivingImages : []) + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + + const rows = []; + const embeddedImages = []; + const styledRows = []; + const summaryImageColumnIndex = 3; + const detailColumns = [ + '序号', '商品名称', '条码', + '数量', '重量', '箱数', '托数', + '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', + ]; + const detailImageColumnIndex = detailColumns.length; + const maxDetailImageCount = Math.max( + 1, + ...details.map(detail => { + const detailImages = Array.isArray(detailImageMap.get(String(detail.id))) + ? detailImageMap.get(String(detail.id)) + : []; + const detailImageUrls = detailImages + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + return detailImageUrls.length; + }) + ); + + const buildLinkCell = urls => { + const normalizedUrls = (Array.isArray(urls) ? urls : [ urls ]) + .map(item => String(item || '').trim()) + .filter(Boolean); + + if (normalizedUrls.length === 0) { + return ''; + } + + return { + text: normalizedUrls.join('\n'), + hyperlink: normalizedUrls[0], + tooltip: normalizedUrls.join('\n'), + }; + }; + + const pushReportRow = (cells = [], options = {}) => { + rows.push(cells); + const rowIndex = rows.length; + const maxCol = Math.max(Number(options.toCol || cells.length || 1), 1); + + if (options.style || options.height) { + styledRows.push({ + row: rowIndex, + fromCol: Math.max(Number(options.fromCol || 1), 1), + toCol: maxCol, + style: options.style || null, + height: options.height || null, + }); + } + + return rowIndex; + }; + + pushReportRow([]); + + [ + [ '收货单ID', receiving && receiving.id ], + [ '收货单号', receiving && receiving.receiving_number ], + [ '货主', receiving && receiving.store_name ], + [ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ], + ...this.getCompletionContactFields(receiving), + [ '总明细数', stats.total_details || details.length ], + [ '已匹配明细数', stats.matched_details || 0 ], + [ '未匹配明细数', stats.unmatched_details || 0 ], + [ '总数量', stats.total_quantity || 0 ], + [ '总箱数', receiving && receiving.total_boxes ], + [ '总托盘数', receiving && receiving.total_pallets ], + [ '完成人', operator.employees_name || operator.real_name || operator.name || '' ], + [ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ], + [ '备注', receiving && receiving.remark ], + ].forEach(([ field, value ]) => { + pushReportRow([ field, value ], { + toCol: 2, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + }); + + if (mainImageUrls.length === 0) { + pushReportRow([ '收货图片', '无' ], { + toCol: 2, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + } else { + const summaryLinkCell = buildLinkCell(mainImageUrls); + const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill(''); + const firstImageRowIndex = pushReportRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], { + toCol: 2 + imagePlaceholders.length, + height: 88, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + + mainImageUrls.forEach((imageUrl, index) => { + embeddedImages.push({ + row: firstImageRowIndex, + col: summaryImageColumnIndex + index, + url: imageUrl, + width: 96, + height: 96, + fallbackText: `收货图片${index + 1}`, + }); + }); + } + + pushReportRow([]); + + pushReportRow(detailColumns, { + toCol: detailColumns.length, + height: 22, + style: { + font: { bold: true, color: { argb: 'FF1F1F1F' } }, + fill: { + type: 'pattern', + pattern: 'solid', + fgColor: { argb: 'FFD9EAF7' }, + }, + alignment: { horizontal: 'center', vertical: 'middle', wrapText: true }, + }, + }); + + if (details.length === 0) { + pushReportRow([ '', '', '无明细' ], { + toCol: detailColumns.length, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + } else { + details.forEach((detail, index) => { + const detailImages = Array.isArray(detailImageMap.get(String(detail.id))) + ? detailImageMap.get(String(detail.id)) + : []; + const detailImageUrls = detailImages + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + const imageSlotCount = Math.max(detailImageUrls.length, 1); + const linkCell = buildLinkCell(detailImageUrls); + + const rowCells = [ + index + 1, + detail.product_name || '', + detail.barcode || '', + detail.actual_quantity || 0, + detail.weight || 0, + detail.box_quantity || 0, + detail.pallet_quantity || 0, + detail.batch_number || '', + this.formatReportDate(detail.production_date), + this.formatReportDate(detail.expiry_date), + detail.remark || '', + linkCell, + ...Array(imageSlotCount).fill(''), + ]; + + const targetRow = pushReportRow(rowCells, { + toCol: rowCells.length, + height: detailImageUrls.length > 0 ? 88 : null, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + + detailImageUrls.forEach((imageUrl, imageIndex) => { + embeddedImages.push({ + row: targetRow, + col: detailImageColumnIndex + imageIndex, + url: imageUrl, + width: 96, + height: 96, + fallbackText: `图片${imageIndex + 1}`, + }); + }); + }); + } + + return [ + { + name: '收货清单', + rows, + widths: [ + 16, 28, 18, 10, 10, 10, 10, 18, 18, 18, 24, 42, 18, + ...Array(Math.max(maxDetailImageCount - 1, 0)).fill(18), + ], + embeddedImages, + styledRows, + skipHeader: true, + forceExcelJs: true, + }, + ]; + } + + async uploadCompletionExcelReport({ + receiving, + operator = {}, + stats = {}, + detailImageMap = new Map(), + receivingImages = [], + }) { + const { ctx } = this; + const excelService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.excel; + + if (!receiving || !receiving.id || !excelService || typeof excelService.generateAndUpload !== 'function') { + return null; + } + + const receivingNumber = String(receiving.receiving_number || receiving.id).replace(/[\\/:*?"<>|]/g, '_'); + + return await excelService.generateAndUpload({ + filename: `收货明细(已完成收货)_${receivingNumber}.xlsx`, + dir: `exports/receiving/completed/${ctx.user.store_id || receiving.warehouse_id || 'common'}`, + category: 'document', + saveRecord: true, + businessType: 'receivingReport', + businessId: receiving.id, + expireDays: 90, + sheets: this.buildCompletionReportSheets({ + receiving, + operator, + stats, + detailImageMap, + receivingImages, + }), + }); + } + + /** + * 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件。 + * @param {Object} options 通知参数 + * @param {Object} options.receiving 收货单快照 + * @param {Object} [options.operator={}] 操作人信息 + * @param {Object} [options.stats={}] 收货统计 + * @param {Object|null} [options.completionReport=null] 完成报表信息 + * @return {Promise} 通知发送结果,若条件不满足则返回 null + */ + async sendCompletionNotice({ + receiving, + operator = {}, + stats = {}, + completionReport = null, + } = {}) { + const { ctx } = this; + const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + if (!receiving || !receiving.id || !noticeService) { + return null; + } + + const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return null; + } + + const storeId = Number(receiving.store_id || 0); + const matchedDetails = Number(stats.matched_details || 0); + const unmatchedDetails = Number(stats.unmatched_details || 0); + const totalQuantity = Number(stats.total_quantity || 0); + const operatorName = String(operator.employees_name || operator.real_name || operator.name || '').trim(); + const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim() || String(receiving.id); + const reportUrl = String( + (completionReport && (completionReport.url || completionReport.cdnUrl || completionReport.cosUrl || completionReport.fileUrl)) || '' + ).trim(); + const reportFileName = String( + (completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx` + ).trim(); + const detailItems = Array.isArray(receiving.details) ? receiving.details : []; + const normalizedDetails = detailItems.map(item => ({ + id: Number(item.id || 0), + product_name: item.product_name || '', + barcode: item.barcode || '', + actual_quantity: Number(item.actual_quantity || 0), + box_quantity: Number(item.box_quantity || 0), + pallet_quantity: Number(item.pallet_quantity || 0), + box_remainder: Number(item.box_remainder || 0), + box_weight: Number(item.box_weight || 0), + weight: Number(item.weight || 0), + })); + const totalBoxRemainder = normalizedDetails.reduce((sum, item) => sum + Number(item.box_remainder || 0), 0); + const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0); + const title = `收货单${receivingNumber}已完成`; + const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); + // 收货完成只通知仓库收货群,不再通知货主(货主端链接不再生成) + const warehouseFrontendUrl = String(ctx.app.config.frontendUrl || '').trim(); + const contentLines = [ + `收货单号:${receivingNumber} 已完成`, + `货主:${receiving.store_name || '未知'}`, + `来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, + ...contactLines, + `总明细数:${Number(stats.total_details || 0)}件`, + `匹配商品:${matchedDetails}件`, + `未匹配商品:${unmatchedDetails}件`, + `总数量:${totalQuantity}`, + `总箱数:${receiving.total_boxes || 0}`, + `总箱余数:${totalBoxRemainder}`, + `总箱重:${totalBoxWeight}`, + `总托盘数:${receiving.total_pallets || 0}`, + operatorName ? `完成人:${operatorName}` : '', + `开始时间:${this.formatReportDate(receiving.created_at)}`, + `完成时间:${this.formatReportDate(receiving.receiving_end_time)}`, + `备注:${receiving.remark || '无'}`, + ].filter(Boolean); + const content = [ ...contentLines, `快速查看:${warehouseFrontendUrl}/storage/receiving?id=${receivingNumber}` ].join('\n') + '。'; + + return await noticeService.send({ + warehouseId, + storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined, + messageType: reportUrl ? 'file' : 'text', + businessName: 'receiving', + event: 'receiving_completed', + channel: 'warehouse', + title, + content, + url: reportUrl || undefined, + fileName: reportUrl ? reportFileName : '', + mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '', + businessId: receiving.id, + subject: { + id: warehouseId, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: operator.employees_id || operator.id || null, + name: operatorName, + }, + metadata: { + receivingId: receiving.id, + receivingNumber, + warehouseId, + storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : null, + stats: { + total_details: Number(stats.total_details || 0), + matched_details: matchedDetails, + unmatched_details: unmatchedDetails, + total_quantity: totalQuantity, + }, + }, + }); + } + + /** + * 发送收货完成未匹配商品货主通知(receiving_store_unmatched),提醒货主核实未匹配商品资料。 + * 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。 + * @param {Object} options 发送参数 + * @param {Object} options.receiving 收货单快照 + * @param {Array} [options.unmatchedDetails=[]] 未匹配明细列表(含 barcode/product_name) + * @return {Promise} 发送结果 + */ + async sendStoreUnmatchedNotice({ receiving, unmatchedDetails = [] } = {}) { + const { ctx } = this; + const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + if (!receiving || !noticeService || !Array.isArray(unmatchedDetails) || unmatchedDetails.length === 0) { + return null; + } + + const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0); + const storeId = Number(receiving.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId) || storeId <= 0) { + return null; + } + + const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim(); + const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim(); + const barcodeLines = unmatchedDetails.map((detail, index) => `${index + 1}.${String(detail.barcode || '').trim() || '无条码'},`); + const contentLines = [ + `收货单号:${receivingNumber} 提交完成收货,有未匹配商品资料`, + '条码:', + ...barcodeLines, + '核实是否是新商品未推送资料', + `详情以及收货图片查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}`, + '如果没有账户请联系人工客服开通', + ]; + const content = contentLines.join('\n') + '。'; + + return await noticeService.send({ + warehouseId, + storeId, + messageType: 'text', + businessName: 'receiving', + event: 'receiving_store_unmatched', + channel: 'warehouse', + title: `收货单${receivingNumber}有未匹配商品资料`, + content, + storeContent: content, + businessId: receiving.id, + subject: { + id: warehouseId, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: (ctx.user && (ctx.user.employees_id || ctx.user.id)) || null, + name: (ctx.user && ctx.user.employees_name) || '', + }, + metadata: { + receivingId: receiving.id, + receivingNumber, + warehouseId, + storeId, + unmatchedBarcodes: unmatchedDetails.map(detail => detail.barcode || ''), + }, + }); + } + + /** + * 完成收货单:校验明细、更新状态并写入库存。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {string} [data.remark] 完成备注 + * @return {Promise} 完成结果 + */ async completeReceiving(data) { const { ctx, app } = this; const warehouseId = ctx.user.store_id; @@ -1658,7 +4600,27 @@ class ReceivingService extends Service { model: ctx.model.ReceivingDetail, as: 'details', required: false, - attributes: [ 'id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight' ], + attributes: [ + 'id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight', + 'box_quantity', 'pallet_quantity', 'box_remainder', 'box_weight', + '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', + ], + }], }], }); @@ -1672,6 +4634,7 @@ class ReceivingService extends Service { // 2. 状态检查 if (receiving.status === 'completed') { + await transaction.rollback(); return { code: 200, message: '收货单已完成', @@ -1695,94 +4658,136 @@ class ReceivingService extends Service { }; } - // 4. 校验所有明细的完成条件 - const invalidDetails = []; + // 4. 校验明细数量:不允许存在数量为 0 的明细 + const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0); + if (zeroQuantityDetails.length > 0) { + await transaction.rollback(); + const errorMsg = zeroQuantityDetails.length === 1 + ? `商品“${zeroQuantityDetails[0].product_name || '未命名商品'}”的数量为0,请填写实际收货数量` + : `有${zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`; + return { + success: false, + code: 'DETAIL_QUANTITY_ZERO', + message: errorMsg, + data: { + invalid_details: zeroQuantityDetails.map(d => ({ + detail_id: d.id, + item_name: d.product_name || '未命名商品', + actual_quantity: Number(d.actual_quantity || 0), + })), + }, + }; + } + + 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); + const images = await ctx.model.FileReference.findAll({ where: { business_type: 'receivingItem', business_id: { [Op.in]: detailsIds, }, + warehouse_id: warehouseId, }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], transaction, }); - // 按照业务ID分组照片 const imageMap = new Map(); images.forEach(image => { const businessId = String(image.business_id).trim(); if (!imageMap.has(businessId)) { imageMap.set(businessId, []); } - imageMap.get(businessId).push(image); + + imageMap.get(businessId).push({ + id: image.file_id, + url: (image.file && image.file.file_url) || image.file_url || image.url || image.file_path || '', + }); }); - console.log('imageMap', imageMap); - - // 检查未绑定系统商品的明细 - for (const detail of receiving.details) { - // 先检查是否有对应的图片数组 - const businessId = String(detail.id).trim(); - const imageArray = imageMap.get(businessId); - - // 这里的关键修复:不仅要检查数组是否存在且有长度,还要检查数组中的元素是否有实际的数据 - const hasPhoto = imageArray && - imageArray.length > 0 && - imageArray.some(img => { - // 检查图片对象是否有实际的数据 - return img.dataValues || - img.file_path || - img.url || - (img._options && Object.keys(img._options).length > 0); - }); - const hasBarcode = !!detail.barcode && detail.barcode.trim() !== ''; - const hasWeight = detail.weight > 0; - const hasCount = detail.actual_quantity > 0; - console.log('detailInfo', hasBarcode, hasWeight, hasCount); - - if (!hasPhoto || !hasBarcode || !hasWeight || !hasCount) { - const itemName = detail.product_name || '未命名商品'; - invalidDetails.push({ - detail_id: detail.id, - item_name: itemName, - missing_fields: [ - !hasPhoto && '照片', - !hasBarcode && '条码', - !hasWeight && '重量', - !hasCount && '数量', - ].filter(Boolean), - }); - } - } - - // 5. 如果有不符合条件的明细,返回错误 - if (invalidDetails.length > 0) { - await transaction.rollback(); - - const errorMsg = invalidDetails.length === 1 - ? `商品"${invalidDetails[0].item_name}"缺少${invalidDetails[0].missing_fields.join('、')}` - : `有${invalidDetails.length}个商品缺少必要信息`; - - return { - success: false, - code: 'DETAIL_INCOMPLETE', - message: errorMsg, - data: { - invalid_details: invalidDetails, - total_details: receiving.details.length, - matched_details: receiving.details.filter(d => d.system_product_id).length, - unmatched_details: unmatchedDetails.length, - }, - }; - } - - - // 7. 获取操作人信息 + // 5. 获取操作人信息 const operator = ctx.user; // 8. 更新收货单状态 @@ -1793,7 +4798,6 @@ class ReceivingService extends Service { updated_at: now, }; - // 更新备注 if (remark) { const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : ''; updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name} ${remark}`; @@ -1815,21 +4819,96 @@ class ReceivingService extends Service { total_quantity: receiving.details.reduce((sum, d) => sum + (d.actual_quantity || 0), 0), }; - if (stats.matched_details > 0) { - // 通知 - await ctx.service.systems.notification.send({ - type: 'system', - title: `收货单${receiving.receiving_number}已完成`, - content: `收货单${receiving.receiving_number}已完成,匹配商品${stats.matched_details}件,未匹配商品${stats.unmatched_details}件。`, - bussinessType: 'receiving', - bussinessId: receiving.id, + // 10. 提交事务 + await transaction.commit(); + + // 10.1 清除收货单缓存,确保下次入库完成时匹配到最新收货单列表 + const receivingCacheKey = `cache:receiving_orders:warehouse:${warehouseId}`; + app.delCacheAsync(receivingCacheKey).catch(cacheErr => { + ctx.logger.warn(`[receiving.completeReceiving] 清除收货单缓存失败: ${cacheErr.message}`, { cacheKey: receivingCacheKey }); + }); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: id, + operationCode: 'RECEIVING_COMPLETE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + previous_status: receiving.status, + stats, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.completeReceiving] 写入操作日志失败,不影响业务', logErr); + } + + const receivingSnapshot = { + ...(typeof receiving.toJSON === 'function' ? receiving.toJSON() : receiving), + ...updateData, + }; + + const completionNoticePayload = { + receiving: receivingSnapshot, + operator, + stats, + }; + + // 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知。 + try { + const textNoticeResult = await this.sendCompletionNotice(completionNoticePayload); + ctx.logger.info('收货完成文字通知结果', { + receiving_id: id, + receiving_number: receiving.receiving_number, + warehouseId, + success: !!(textNoticeResult && textNoticeResult.success), + message: textNoticeResult && textNoticeResult.message, + matchedHookCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.matchedHookCount || 0), + sentCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.sentCount || 0), + failedCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.failedCount || 0), + }); + } catch (notifyError) { + ctx.logger.error(`收货完成文字通知发送失败: ${notifyError.message}`, { + receiving_id: id, + warehouseId, + error: notifyError.stack, }); } - // 11. 提交事务 - await transaction.commit(); + // 11.1 存在未匹配商品明细且已绑定货主时,通知货主核实商品资料(失败不影响主流程) + if (unmatchedDetails.length > 0 && Number(receiving.store_id || 0) > 0) { + try { + const unmatchedNoticeResult = await this.sendStoreUnmatchedNotice({ + receiving: receivingSnapshot, + unmatchedDetails: unmatchedDetails.map(detail => ({ + barcode: detail.barcode, + product_name: detail.product_name, + })), + }); + ctx.logger.info('收货完成未匹配商品货主通知结果', { + receiving_id: id, + receiving_number: receiving.receiving_number, + warehouseId, + unmatchedCount: unmatchedDetails.length, + success: !!(unmatchedNoticeResult && unmatchedNoticeResult.success), + message: unmatchedNoticeResult && unmatchedNoticeResult.message, + }); + } catch (notifyError) { + ctx.logger.error(`收货完成未匹配商品货主通知发送失败: ${notifyError.message}`, { + receiving_id: id, + warehouseId, + error: notifyError.stack, + }); + } + } - // 记录操作日志 ctx.logger.info('收货单已完成', { receiving_id: id, receiving_number: receiving.receiving_number, @@ -1837,8 +4916,18 @@ class ReceivingService extends Service { stats, }); + // 异步补全商品图片与毛重,不阻塞主进程 + this._syncProductDataFromReceiving({ + receivingId: id, + warehouseId, + details: receiving.details, + }).catch(err => { + ctx.logger.warn('[receiving._syncProductDataFromReceiving] 异步补全失败,不影响业务', err.message); + }); + return { success: true, + code: 200, message: '收货完成成功', data: { receiving_id: id, @@ -1846,12 +4935,12 @@ class ReceivingService extends Service { completed_at: now, completed_by: operator.employees_name, stats, + completion_report: null, }, }; } catch (error) { - // 12. 回滚事务 - if (transaction) { + if (transaction && !transaction.finished) { await transaction.rollback(); } @@ -1861,7 +4950,6 @@ class ReceivingService extends Service { error: error.stack, }); - // 如果是已知的业务错误,返回具体信息 if (error.code && error.code.startsWith('DETAIL_')) { return { success: false, @@ -1870,7 +4958,6 @@ class ReceivingService extends Service { }; } - // 其他错误 return { success: false, code: 'SYSTEM_ERROR', @@ -1878,6 +4965,1209 @@ class ReceivingService extends Service { }; } } + + /** + * 收货完成后异步补全商品资料:绑定图片、补填毛重。 + * + * 遍历当前收货单所有已绑定系统商品的明细: + * 1. 若该明细有收货图片,且商品在 wms_file_reference 中已有商品图片(business_type='stock'、 + * business_id=商品ID)引用总数 <= 2,则将收货图片复制为商品图片(FileReference,按 file_id 去重), + * 并将商品的 is_images 更新为 'Y';若已有图片总数 > 2,则跳过该商品的图片复制与 is_images 更新, + * 避免商品图片无限累积。 + * 2. 若商品 gross_weight 为 0 或 null,且明细的 weight > 0,则将商品毛重更新为该明细的 weight。 + * + * 商品已有图片计数采用一次性批量查询(避免 N+1),口径为跨来源总量(不区分 created_by), + * 并按 warehouse_id 隔离;查询结果同时用于 file_id 内存去重与计数。 + * + * 本方法在收货完成后异步调用,不阻塞主进程,任何异常只记录日志,不影响业务。 + * + * @param {Object} options 参数对象 + * @param {number} options.receivingId 收货单 ID + * @param {number} options.warehouseId 仓库 ID + * @param {Array} options.details 收货明细数组(来自 completeReceiving 中已加载的 details) + * @return {Promise} + */ + async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) { + const { ctx, app } = this; + + // 只处理已绑定系统商品的明细 + const boundDetails = (Array.isArray(details) ? details : []).filter( + d => d && Number(d.system_product_id) > 0 + ); + + if (boundDetails.length === 0) return; + + // -------- 批量预统计商品已有商品图片引用(跨来源总量,不区分 created_by),避免逐条 N+1 查询 -------- + const productIds = Array.from(new Set(boundDetails.map(d => Number(d.system_product_id)))); + const stockImageRefs = await app.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: productIds.map(id => String(id)), + warehouse_id: warehouseId, + }, + attributes: [ 'business_id', 'file_id' ], + raw: true, + }); + + // 商品已有图片计数表:商品ID(字符串) -> 已有图片总数 + const stockImageCountMap = new Map(); + // 商品已有图片 file_id 表:商品ID(字符串) -> Set(内存去重用) + const stockImageFileIdMap = new Map(); + for (const ref of stockImageRefs) { + const productKey = ref.business_id; + stockImageCountMap.set(productKey, (stockImageCountMap.get(productKey) || 0) + 1); + if (!stockImageFileIdMap.has(productKey)) { + stockImageFileIdMap.set(productKey, new Set()); + } + stockImageFileIdMap.get(productKey).add(ref.file_id); + } + + for (const detail of boundDetails) { + const systemProductId = Number(detail.system_product_id); + try { + // -------- 查询当前商品资料 -------- + const stock = await app.model.StockWarehouse.findOne({ + where: { + id: systemProductId, + warehouse_id: warehouseId, + deleted_at: null, + }, + attributes: [ 'id', 'is_images', 'gross_weight' ], + raw: true, + }); + + if (!stock) continue; + + // -------- 1. 商品图片补全 -------- + // 查询该明细是否有收货图片 + const detailImageRefs = await app.model.FileReference.findAll({ + where: { + business_type: 'receivingItem', + business_id: String(detail.id), + warehouse_id: warehouseId, + }, + attributes: [ 'file_id' ], + raw: true, + }); + + if (detailImageRefs.length > 0) { + const productKey = String(systemProductId); + const existingStockImageCount = stockImageCountMap.get(productKey) || 0; + + if (existingStockImageCount > 2) { + // 规则:已有图片数 > 2 时不再复制收货图片,也不更新 is_images,避免商品图片无限累积 + ctx.logger.info( + `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已有图片 ${existingStockImageCount} 张(>2),跳过图片复制(收货单 ${receivingId} 明细 ${detail.id})` + ); + } else { + // 使用批量预统计的已有 file_id 做内存去重,避免重复复制 + const existingStockImageFileIds = stockImageFileIdMap.get(productKey) || new Set(); + + const toCreate = detailImageRefs + .filter(ref => !existingStockImageFileIds.has(ref.file_id)) + .map(ref => ({ + file_id: ref.file_id, + business_type: 'stock', + business_id: productKey, + warehouse_id: warehouseId, + display_order: 0, + created_by: 'system', + created_at: new Date(), + })); + + if (toCreate.length > 0) { + await app.model.FileReference.bulkCreate(toCreate, { ignoreDuplicates: true }); + + // 同步内存映射:同一收货单内同一商品的多个明细不会重复复制、也不会突破图片数上限 + const createdFileIds = toCreate.map(ref => ref.file_id); + stockImageCountMap.set( + productKey, + (stockImageCountMap.get(productKey) || 0) + createdFileIds.length + ); + const mergedFileIds = new Set(existingStockImageFileIds); + createdFileIds.forEach(fileId => mergedFileIds.add(fileId)); + stockImageFileIdMap.set(productKey, mergedFileIds); + } + + // 更新商品 is_images 标记 + await app.model.StockWarehouse.update( + { is_images: 'Y' }, + { where: { id: systemProductId } } + ); + + ctx.logger.info( + `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复制 ${toCreate.length} 张(收货单 ${receivingId} 明细 ${detail.id})` + ); + } + } + + // -------- 2. 毛重补全 -------- + const currentWeight = parseFloat(stock.gross_weight) || 0; + const detailWeight = parseFloat(detail.weight) || 0; + if (currentWeight <= 0 && detailWeight > 0) { + await app.model.StockWarehouse.update( + { gross_weight: detailWeight }, + { where: { id: systemProductId } } + ); + + ctx.logger.info( + `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛重 ${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})` + ); + } + } catch (err) { + // 单条明细失败不中断后续处理 + ctx.logger.error( + `[_syncProductDataFromReceiving] 处理明细 ${detail.id} (商品 ${systemProductId}) 失败: ${err.message}` + ); + } + } + } + + /** + * PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细。 + * 搜索策略: + * 1. 通过 entry_order_id → wms_entry_order_receiving 查出关联的 receiving_id 列表; + * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤); + * 3. 收集明细的 system_product_id,批量调用 getStockDetails 获取条码信息; + * 4. 在内存中遍历明细进行精确匹配: + * - 若 barcode 为纯数字,优先按明细 ID 精确匹配; + * - 再按 getStockDetails 返回的 barcodes[].barcode 精确匹配商品条码; + * 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)。 + * @param {number} entryOrderId 入库单ID + * @param {string} barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID) + * @return {Promise} 包含 code、message 与匹配明细列表 data.list 的结果对象 + */ + async scanDetail(entryOrderId, barcode) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const warehouseId = ctx.user?.store_id; + + // 参数校验 + if (!warehouseId) { + return { code: 0, message: '用户未绑定仓库', data: null }; + } + if (!entryOrderId || Number(entryOrderId) <= 0) { + return { code: 0, message: '入库单ID不能为空', data: null }; + } + if (!barcode || String(barcode).trim() === '') { + return { code: 0, message: '扫描条码不能为空', data: null }; + } + + const normalizedBarcode = String(barcode).trim(); + const normalizedEntryOrderId = Number(entryOrderId); + + try { + // 1. 验证入库单存在且属于当前仓库 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + id: normalizedEntryOrderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!entryOrder) { + return { code: 0, message: '入库单不存在或无权访问', data: null }; + } + + // 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表 + const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: normalizedEntryOrderId }, + attributes: [ 'receiving_id' ], + raw: true, + }); + + const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean); + if (receivingIds.length === 0) { + return { code: 0, message: '该入库单尚未关联收货单', data: null }; + } + + // 校验所有 receiving 属于当前仓库 + const validReceivings = await ctx.model.Receiving.findAll({ + where: { id: { [Op.in]: receivingIds }, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + const validReceivingIds = validReceivings.map(r => r.id); + if (validReceivingIds.length === 0) { + return { code: 1, message: '收货单不存在或不属于当前仓库', list: [], total: 0 }; + } + + // 2.5 获取入库单的所有合法 stock_id(用于校验收货明细的 system_product_id) + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: normalizedEntryOrderId }, + attributes: [ 'stock_id' ], + raw: true, + }); + const validStockIds = [ ...new Set(entryItems.map(ei => ei.stock_id).filter(Boolean)) ]; + if (validStockIds.length === 0) { + return { code: 0, message: '入库单无明细,无法匹配收货明细', data: null }; + } + + // 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) + const notBoundCondition = app.Sequelize.literal( + 'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' + ); + + // 3. 查出所有未绑定的收货明细(不再在 SQL 层做 barcode 模糊匹配) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { + [Op.and]: [ + { receiving_id: { [Op.in]: validReceivingIds } }, + { system_product_id: { [Op.in]: validStockIds } }, + notBoundCondition, + ], + }, + raw: true, + }); + + if (details.length === 0) { + return { code: 0, message: '未找到可用的收货明细', data: null }; + } + + // 4. 收集所有明细的 system_product_id,批量调用 getStockDetails 获取条码 + const stockIdSet = new Set(); + for (const d of details) { + if (d.system_product_id != null) { + stockIdSet.add(Number(d.system_product_id)); + } + } + const stockIds = [ ...stockIdSet ]; + + /** @type {Map} */ + const stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const sd of stockDetails) { + if (sd && sd.id != null) { + stockDetailMap.set(sd.id, sd); + } + } + } + + // 5. 在内存中遍历明细,精确匹配,收集所有命中 + const isNumericBarcode = /^\d+$/.test(normalizedBarcode); + const matchedDetails = []; + + for (const detail of details) { + // 优先按明细 ID 精确匹配(托盘唛头场景) + if (isNumericBarcode && detail.id === Number(normalizedBarcode)) { + const sd = stockDetailMap.get(Number(detail.system_product_id)); + if (sd) { + matchedDetails.push(detail); + } + continue; + } + + // 按商品条码精确匹配 + const stockDetail = stockDetailMap.get(detail.system_product_id); + if (stockDetail && Array.isArray(stockDetail.barcodes)) { + const barcodeMatch = stockDetail.barcodes.some( + bc => bc.barcode === normalizedBarcode + ); + if (barcodeMatch) { + matchedDetails.push(detail); + } + } + } + + if (matchedDetails.length === 0) { + return { code: 0, message: '未找到匹配的收货明细', data: null }; + } + + const list = matchedDetails.map(matchedDetail => { + const sd = stockDetailMap.get(Number(matchedDetail.system_product_id)); + const stockBarcode = (sd && Array.isArray(sd.barcodes) && sd.barcodes.length > 0) + ? (sd.barcodes[0].barcode || '') + : ''; + return { + detail_id: matchedDetail.id, + receiving_id: matchedDetail.receiving_id, + barcode: stockBarcode || matchedDetail.barcode || '', + product_name: matchedDetail.product_name || '', + actual_quantity: matchedDetail.actual_quantity || 0, + receiving_status: matchedDetail.receiving_status || '', + stock: sd || null, + }; + }); + + return { + code: 200, + message: '查询成功', + data: { + list, + total: list.length, + }, + }; + } catch (error) { + ctx.logger.error('[receiving.scanDetail] 扫码定位收货明细失败', error); + return { code: 500, message: `服务器错误: ${error.message}`, data: null }; + } + } + + /** + * 导出收货单列表(双 sheet:收货单列表 + 收货单明细)。 + * 复用 getStoreReceivingList 的筛选与排序语义,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件 + * @param {number} options.storeId 货主ID + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportReceivingList(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = options && typeof options === 'object' ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const warehouseId = Number(ctx.user && ctx.user.store_id); + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + if (!warehouseId) { + throw new Error('用户未绑定仓库,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + // 构建 where 条件(与 getReceivingList 一致,按仓库维度) + const queryOptions = { + where: { [Op.and]: [{ warehouse_id: warehouseId }] }, + }; + + const normalizedWhere = { ...where }; + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + parsedResult = parsed.result; + } + + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { [Op.like]: `%${quickValue}%` }, + receiving_number: { [Op.like]: `%${quickValue}%` }, + tracking_number: { [Op.like]: `%${quickValue}%` }, + creator_snapshot: { [Op.like]: `%${quickValue}%` }, + license_plate: { [Op.like]: `%${quickValue}%` }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions }); + } + + // ---- 分页拉取收货单列表 ---- + const totalCount = await ctx.model.Receiving.count({ + where: queryOptions.where, + distinct: true, + }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 85, + message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件', + }); + + const allReceivingOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.Receiving.findAll({ + where: queryOptions.where, + order: [[ actualSortField, sortOrder ]], + limit: RECEIVING_EXPORT_PAGE_SIZE, + offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allReceivingOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + // ---- 批量拉取收货单明细 ---- + const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean); + /** @type {Map>} receiving_id → details */ + const detailsMap = new Map(); + + if (allReceivingIds.length > 0) { + const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allReceivingIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize); + + const details = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [Op.in]: batchIds } }, + order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + for (const detail of details) { + const rid = Number(detail.receiving_id); + if (!detailsMap.has(rid)) { + detailsMap.set(rid, []); + } + detailsMap.get(rid).push(detail); + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `收货单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const statusLabelMap = { + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStatusLabelMap = { + all_matched: '全部匹配', + partial_matched: '部分匹配', + unmatched: '未匹配', + }; + + const storageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + const deliveryMethodLabelMap = { + truck: '货车', + express: '快递', + air_freight: '空运', + sea_freight: '海运', + other: '其他', + }; + + const loadingMethodLabelMap = { + with_pallet: '带托盘', + without_pallet: '不带托盘', + }; + + // Sheet 1: 收货单列表 + const sheet1 = workbook.addWorksheet('收货单列表'); + const receivingColumns = [ + { header: '收货单ID', key: 'id', width: 10 }, + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '货主', key: 'store_name', width: 20 }, + { header: '收货状态', key: 'status_label', width: 12 }, + { header: '明细匹配状态', key: 'detail_status_label', width: 14 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '来货方式', key: 'delivery_method_label', width: 12 }, + { header: '车牌号', key: 'license_plate', width: 14 }, + { header: '快递单号', key: 'tracking_number', width: 22 }, + { header: '装卸方式', key: 'loading_method_label', width: 12 }, + { header: '总商品种类', key: 'total_items', width: 12 }, + { header: '总数量', key: 'total_quantity', width: 12 }, + { header: '总箱数', key: 'total_boxes', width: 10 }, + { header: '总托盘数', key: 'total_pallets', width: 10 }, + { header: '审核状态', key: 'is_review_label', width: 10 }, + { header: '创建人', key: 'creator_name', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '收货开始时间', key: 'receiving_start_time', width: 20 }, + { header: '收货结束时间', key: 'receiving_end_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = receivingColumns; + + for (const row of allReceivingOrders) { + let creatorName = ''; + try { + if (row.creator_snapshot) { + const snapshot = JSON.parse(row.creator_snapshot); + creatorName = snapshot.name || ''; + } + } catch (_) { /* ignore */ } + + sheet1.addRow({ + id: row.id, + receiving_number: normalizeCellValue(row.receiving_number), + store_name: normalizeCellValue(row.store_name), + status_label: statusLabelMap[row.status] || row.status || '', + detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '', + storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '', + delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '', + license_plate: normalizeCellValue(row.license_plate), + tracking_number: normalizeCellValue(row.tracking_number), + loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '', + total_items: row.total_items, + total_quantity: row.total_quantity, + total_boxes: row.total_boxes, + total_pallets: row.total_pallets, + is_review_label: row.is_review === 1 ? '已审核' : '未审核', + creator_name: creatorName, + remark: normalizeCellValue(row.remark), + receiving_start_time: normalizeCellValue(row.receiving_start_time), + receiving_end_time: normalizeCellValue(row.receiving_end_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入收货单明细...', + }); + + // Sheet 2: 收货单明细 + const sheet2 = workbook.addWorksheet('收货单明细'); + const detailColumns = [ + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '收货单ID', key: 'receiving_id', width: 12 }, + { header: '明细ID', key: 'detail_id', width: 10 }, + { header: '商品名称', key: 'product_name', width: 28 }, + { header: '商品条码', key: 'barcode', width: 20 }, + { header: '系统商品ID', key: 'system_product_id', width: 14 }, + { header: '实际收货数量', key: 'actual_quantity', width: 14 }, + { header: '箱数', key: 'box_quantity', width: 10 }, + { header: '托盘数', key: 'pallet_quantity', width: 10 }, + { header: '收货状态', key: 'receiving_status_label', width: 12 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '已入库数量', key: 'stored_quantity', width: 12 }, + { header: '批次号', key: 'batch_number', width: 16 }, + { header: '生产日期', key: 'production_date', width: 14 }, + { header: '到期日期', key: 'expiry_date', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '创建时间', key: 'created_at', width: 20 }, + ]; + sheet2.columns = detailColumns; + + // 构建 receiving_number 映射 + const receivingCodeMap = new Map(); + for (const row of allReceivingOrders) { + receivingCodeMap.set(Number(row.id), row.receiving_number || ''); + } + + const detailReceivingStatusLabelMap = { + pending: '待收货', + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStorageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + // 按收货单分页写入明细 + const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalReceivingOrders = allReceivingIds.length; + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const rid of batchIds) { + const receivingNumber = receivingCodeMap.get(rid) || ''; + const details = detailsMap.get(rid) || []; + + for (const detail of details) { + sheet2.addRow({ + receiving_number: receivingNumber, + receiving_id: rid, + detail_id: detail.id, + product_name: normalizeCellValue(detail.product_name), + barcode: normalizeCellValue(detail.barcode), + system_product_id: normalizeCellValue(detail.system_product_id), + actual_quantity: detail.actual_quantity, + box_quantity: detail.box_quantity, + pallet_quantity: detail.pallet_quantity, + receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '', + storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '', + stored_quantity: detail.stored_quantity, + batch_number: normalizeCellValue(detail.batch_number), + production_date: normalizeCellValue(detail.production_date), + expiry_date: normalizeCellValue(detail.expiry_date), + remark: normalizeCellValue(detail.remark), + created_at: normalizeCellValue(detail.created_at), + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/receiving/${warehouseId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `收货单导出(仓库${warehouseId}),共${totalCount}条收货单`, + }); + } + + // 清理临时文件 + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ } + + const uploadInfo = fileRecord || uploadResult; + const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url + ? uploadInfo.url + : (typeof uploadResult === 'object' ? uploadResult.fileName : ''); + + await progressHandler({ + status: 'running', + progress: 100, + message: '导出完成', + result: { url: fileUrl, fileKey: uploadKey, total: totalCount }, + }); + + return { + url: fileUrl, + fileKey: uploadKey, + total: totalCount, + totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0), + }; + } + + /** + * 导出货主侧收货单列表(双 sheet:收货单列表 + 收货单明细)。 + * 复用 getStoreReceivingList 的筛选与排序语义,以货主 store_id 过滤,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件(与 getStoreReceivingList 一致) + * @param {number} options.storeId 货主ID + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportStoreReceivingList(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = options && typeof options === 'object' ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const storeId = Number(safeOptions.storeId); + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + if (!storeId) { + throw new Error('货主ID不能为空,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + // 构建 where 条件(与 getStoreReceivingList 一致,按货主维度) + const queryOptions = { + where: { [Op.and]: [{ store_id: storeId }] }, + }; + + const normalizedWhere = { ...where }; + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + parsedResult = parsed.result; + } + + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { [Op.like]: `%${quickValue}%` }, + receiving_number: { [Op.like]: `%${quickValue}%` }, + tracking_number: { [Op.like]: `%${quickValue}%` }, + creator_snapshot: { [Op.like]: `%${quickValue}%` }, + license_plate: { [Op.like]: `%${quickValue}%` }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions }); + } + + // ---- 分页拉取收货单列表 ---- + const RECEIVING_EXPORT_PAGE_SIZE = 200; + const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 50; + + const totalCount = await ctx.model.Receiving.count({ + where: queryOptions.where, + distinct: true, + }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 85, + message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件', + }); + + const allReceivingOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.Receiving.findAll({ + where: queryOptions.where, + order: [[ actualSortField, sortOrder ]], + limit: RECEIVING_EXPORT_PAGE_SIZE, + offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allReceivingOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + // ---- 批量拉取收货单明细 ---- + const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean); + /** @type {Map>} receiving_id → details */ + const detailsMap = new Map(); + + if (allReceivingIds.length > 0) { + const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allReceivingIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize); + + const details = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [Op.in]: batchIds } }, + order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + for (const detail of details) { + const rid = Number(detail.receiving_id); + if (!detailsMap.has(rid)) { + detailsMap.set(rid, []); + } + detailsMap.get(rid).push(detail); + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-store-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `收货单导出(货主)_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const statusLabelMap = { + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStatusLabelMap = { + all_matched: '全部匹配', + partial_matched: '部分匹配', + unmatched: '未匹配', + }; + + const storageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + const deliveryMethodLabelMap = { + truck: '货车', + express: '快递', + air_freight: '空运', + sea_freight: '海运', + other: '其他', + }; + + const loadingMethodLabelMap = { + with_pallet: '带托盘', + without_pallet: '不带托盘', + }; + + // Sheet 1: 收货单列表 + const sheet1 = workbook.addWorksheet('收货单列表'); + const receivingColumns = [ + { header: '收货单ID', key: 'id', width: 10 }, + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '货主', key: 'store_name', width: 20 }, + { header: '收货状态', key: 'status_label', width: 12 }, + { header: '明细匹配状态', key: 'detail_status_label', width: 14 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '来货方式', key: 'delivery_method_label', width: 12 }, + { header: '车牌号', key: 'license_plate', width: 14 }, + { header: '快递单号', key: 'tracking_number', width: 22 }, + { header: '装卸方式', key: 'loading_method_label', width: 12 }, + { header: '总商品种类', key: 'total_items', width: 12 }, + { header: '总数量', key: 'total_quantity', width: 12 }, + { header: '总箱数', key: 'total_boxes', width: 10 }, + { header: '总托盘数', key: 'total_pallets', width: 10 }, + { header: '审核状态', key: 'is_review_label', width: 10 }, + { header: '创建人', key: 'creator_name', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '收货开始时间', key: 'receiving_start_time', width: 20 }, + { header: '收货结束时间', key: 'receiving_end_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = receivingColumns; + + for (const row of allReceivingOrders) { + let creatorName = ''; + try { + if (row.creator_snapshot) { + const snapshot = JSON.parse(row.creator_snapshot); + creatorName = snapshot.name || ''; + } + } catch (_) { /* ignore */ } + + sheet1.addRow({ + id: row.id, + receiving_number: normalizeCellValue(row.receiving_number), + store_name: normalizeCellValue(row.store_name), + status_label: statusLabelMap[row.status] || row.status || '', + detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '', + storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '', + delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '', + license_plate: normalizeCellValue(row.license_plate), + tracking_number: normalizeCellValue(row.tracking_number), + loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '', + total_items: row.total_items, + total_quantity: row.total_quantity, + total_boxes: row.total_boxes, + total_pallets: row.total_pallets, + is_review_label: row.is_review === 1 ? '已审核' : '未审核', + creator_name: creatorName, + remark: normalizeCellValue(row.remark), + receiving_start_time: normalizeCellValue(row.receiving_start_time), + receiving_end_time: normalizeCellValue(row.receiving_end_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入收货单明细...', + }); + + // Sheet 2: 收货单明细 + const sheet2 = workbook.addWorksheet('收货单明细'); + const detailColumns = [ + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '收货单ID', key: 'receiving_id', width: 12 }, + { header: '明细ID', key: 'detail_id', width: 10 }, + { header: '商品名称', key: 'product_name', width: 28 }, + { header: '商品条码', key: 'barcode', width: 20 }, + { header: '系统商品ID', key: 'system_product_id', width: 14 }, + { header: '实际收货数量', key: 'actual_quantity', width: 14 }, + { header: '箱数', key: 'box_quantity', width: 10 }, + { header: '托盘数', key: 'pallet_quantity', width: 10 }, + { header: '收货状态', key: 'receiving_status_label', width: 12 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '已入库数量', key: 'stored_quantity', width: 12 }, + { header: '批次号', key: 'batch_number', width: 16 }, + { header: '生产日期', key: 'production_date', width: 14 }, + { header: '到期日期', key: 'expiry_date', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '创建时间', key: 'created_at', width: 20 }, + ]; + sheet2.columns = detailColumns; + + const receivingCodeMap = new Map(); + for (const row of allReceivingOrders) { + receivingCodeMap.set(Number(row.id), row.receiving_number || ''); + } + + const detailReceivingStatusLabelMap = { + pending: '待收货', + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStorageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalReceivingOrders = allReceivingIds.length; + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const rid of batchIds) { + const receivingNumber = receivingCodeMap.get(rid) || ''; + const details = detailsMap.get(rid) || []; + + for (const detail of details) { + sheet2.addRow({ + receiving_number: receivingNumber, + receiving_id: rid, + detail_id: detail.id, + product_name: normalizeCellValue(detail.product_name), + barcode: normalizeCellValue(detail.barcode), + system_product_id: normalizeCellValue(detail.system_product_id), + actual_quantity: detail.actual_quantity, + box_quantity: detail.box_quantity, + pallet_quantity: detail.pallet_quantity, + receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '', + storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '', + stored_quantity: detail.stored_quantity, + batch_number: normalizeCellValue(detail.batch_number), + production_date: normalizeCellValue(detail.production_date), + expiry_date: normalizeCellValue(detail.expiry_date), + remark: normalizeCellValue(detail.remark), + created_at: normalizeCellValue(detail.created_at), + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/receiving/store/${storeId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `收货单导出(货主${storeId}),共${totalCount}条收货单`, + }); + } + + // 清理临时文件 + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ } + + const uploadInfo = fileRecord || uploadResult; + const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url + ? uploadInfo.url + : (typeof uploadResult === 'object' ? uploadResult.fileName : ''); + + await progressHandler({ + status: 'running', + progress: 100, + message: '导出完成', + result: { url: fileUrl, fileKey: uploadKey, total: totalCount }, + }); + + return { + url: fileUrl, + fileKey: uploadKey, + total: totalCount, + totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0), + }; + } + } module.exports = ReceivingService; + diff --git a/app/service/systems/storage/report.js b/app/service/systems/storage/report.js new file mode 100644 index 0000000..12abc58 --- /dev/null +++ b/app/service/systems/storage/report.js @@ -0,0 +1,1963 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const Service = require('egg').Service; +const ExcelJS = require('exceljs'); + +// 发货单分表表位顺序(兜底扫描用)与物理表名白名单:wms_order_delivery_{warehouseId}[_dispatch|_history|_outsourced] +const DELIVERY_SHARD_TABLE_TYPES = [ 'current', 'dispatch', 'history', 'outsourced' ]; +const SHARD_DELIVERY_TABLE_PATTERN = /^wms_order_delivery_\d+(_dispatch|_history|_outsourced)?$/; + +/** + * 将输入转换为时间戳。 + * @param {string|Date|number|null|undefined} value 时间值 + * @return {number|null} 时间戳,无法解析时返回 null + */ +function toTimeMs(value) { + if (value === undefined || value === null || value === '') { + return null; + } + + const date = value instanceof Date ? value : new Date(value); + const time = date.getTime(); + return Number.isNaN(time) ? null : time; +} + +/** + * 归一化布尔值。 + * @param {boolean|string|number|null|undefined} value 原始值 + * @return {boolean} 归一化后的布尔值 + */ +function normalizeBoolean(value) { + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return value === 1; + } + + if (typeof value === 'string') { + const normalized = value.trim().toLowerCase(); + return [ '1', 'true', 'y', 'yes', '是' ].includes(normalized); + } + + return false; +} + +/** + * 归一化货主ID数组。 + * @param {Array|number|string|null|undefined} rawStoreIds 原始货主ID + * @return {number[]} 归一化后的货主ID数组 + */ +function normalizeStoreIds(rawStoreIds) { + const list = Array.isArray(rawStoreIds) ? rawStoreIds : [ rawStoreIds ]; + return [ ...new Set( + list + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0) + ) ]; +} + +/** + * 数值安全转换。 + * @param {unknown} value 原始值 + * @return {number} 数值 + */ +function toNumber(value) { + const num = Number(value); + return Number.isFinite(num) ? num : 0; +} + +/** + * 将时间值格式化为日期令牌。 + * @param {string|Date|number|null|undefined} value 时间值 + * @return {string} yyyymmdd 格式日期,无法解析时返回空字符串 + */ +function formatDateToken(value) { + const timeMs = toTimeMs(value); + if (timeMs === null) { + return ''; + } + + const date = new Date(timeMs); + const year = String(date.getFullYear()); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; +} + +/** + * 将时间值格式化为统一可读字符串。 + * @param {string|Date|number|null|undefined} value 时间值 + * @return {string} yyyy-mm-dd hh:mm:ss 格式字符串 + */ +function formatDateTime(value) { + const timeMs = toTimeMs(value); + if (timeMs === null) { + return ''; + } + + const date = new Date(timeMs); + const year = String(date.getFullYear()); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + const hour = String(date.getHours()).padStart(2, '0'); + const minute = String(date.getMinutes()).padStart(2, '0'); + const second = String(date.getSeconds()).padStart(2, '0'); + return `${year}-${month}-${day} ${hour}:${minute}:${second}`; +} + +/** + * 将库存流水类型转换为中文显示。 + * @param {string|null|undefined} transactionType 流水类型 + * @return {string} 中文类型,未知值返回去除前后空白后的原始内容 + */ +function formatTransactionType(transactionType) { + const rawType = typeof transactionType === 'string' ? transactionType.trim() : String(transactionType || '').trim(); + const normalizedType = rawType.toUpperCase(); + + if (normalizedType === 'INBOUND') { + return '入库'; + } + + if (normalizedType === 'OUTBOUND') { + return '出库'; + } + + if (normalizedType === 'TRANSFER_OUT') { + return '移库出'; + } + + if (normalizedType === 'TRANSFER_IN') { + return '移库入'; + } + + if (normalizedType === 'LOCK') { + return '锁定'; + } + + return rawType; +} + +const SORT_FIELD_WHITE_LIST = new Set([ 'stock_id', 'item_code', 'item_name', 'begin_total', 'inbound_total', 'outbound_total', 'end_total' ]); + +/** 字符串排序字段集合(按字典序比较),其余白名单字段按数值比较 */ +const STRING_SORT_FIELD_SET = new Set([ 'item_code', 'item_name' ]); + +/** + * 归一化排序参数。 + * @param {Object|null|undefined} sort 排序入参 + * @param {string} [sort.sortField] 排序字段(白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total) + * @param {string} [sort.sortOrder] 排序顺序 + * @return {{sortField: string, sortOrder: 'ASC'|'DESC'}|null} 合法排序参数 + */ +function normalizeSort(sort) { + if (!sort || typeof sort !== 'object') { + return null; + } + + const rawSortField = typeof sort.sortField === 'string' ? sort.sortField.trim() : ''; + const rawSortOrder = typeof sort.sortOrder === 'string' ? sort.sortOrder.trim().toUpperCase() : ''; + if (!SORT_FIELD_WHITE_LIST.has(rawSortField)) { + return null; + } + + if (rawSortOrder !== 'ASC' && rawSortOrder !== 'DESC') { + return null; + } + + return { + sortField: rawSortField, + sortOrder: rawSortOrder, + }; +} + +/** + * 默认排序比较器。 + * @param {Object} a 列表项A + * @param {Object} b 列表项B + * @param {boolean} isBySpace 是否按库位输出 + * @return {number} 比较结果 + */ +function compareByDefaultOrder(a, b, isBySpace) { + if (a.store_id !== b.store_id) { + return a.store_id - b.store_id; + } + + if (a.stock_id !== b.stock_id) { + return a.stock_id - b.stock_id; + } + + if (!isBySpace) { + return 0; + } + + return Number(a.space_id || 0) - Number(b.space_id || 0); +} + +/** + * 对最终结果做统一排序。 + * @param {Object[]} list 原始结果列表 + * @param {boolean} isBySpace 是否按库位输出 + * @param {Object|null|undefined} sort 排序参数 + * @return {Object[]} 排序后的结果列表 + */ +function sortReportList(list, isBySpace, sort) { + const normalizedSort = normalizeSort(sort); + if (!normalizedSort) { + return list.sort((a, b) => compareByDefaultOrder(a, b, isBySpace)); + } + + const { sortField, sortOrder } = normalizedSort; + const direction = sortOrder === 'DESC' ? -1 : 1; + const isStringSort = STRING_SORT_FIELD_SET.has(sortField); + + return list.sort((a, b) => { + let cmp; + if (isStringSort) { + cmp = String(a[sortField] || '').localeCompare(String(b[sortField] || '')); + } else { + const aValue = toNumber(a[sortField]); + const bValue = toNumber(b[sortField]); + cmp = aValue === bValue ? 0 : aValue - bValue; + } + if (cmp !== 0) { + return cmp * direction; + } + return compareByDefaultOrder(a, b, isBySpace); + }); +} + +/** + * 根据区间流水构建“首条before、末条after”的快照映射。 + * @param {Object[]} rows 区间流水列表 + * @param {(row: Object) => string|null} resolveKey 键解析函数 + * @return {Map} 快照映射 + */ +function buildIntervalEdgeMap(rows, resolveKey) { + const edgeMap = new Map(); + const safeRows = Array.isArray(rows) ? rows : []; + + for (const row of safeRows) { + const key = resolveKey(row); + if (!key) { + continue; + } + + const beforeQuantity = toNumber(row.before_quantity); + const afterQuantity = toNumber(row.after_quantity); + + if (!edgeMap.has(key)) { + edgeMap.set(key, { + begin_total: beforeQuantity, + end_total: afterQuantity, + has_snapshot: true, + }); + continue; + } + + const snapshot = edgeMap.get(key); + snapshot.end_total = afterQuantity; + } + + return edgeMap; +} + +/** + * 根据 start_time 之前流水构建“最近一条 after”的期初快照映射。 + * @param {Object[]} rows start_time 之前流水列表 + * @param {(row: Object) => string|null} resolveKey 键解析函数 + * @return {Map} 期初快照映射 + */ +function buildPreStartAfterMap(rows, resolveKey) { + const latestSnapshotMap = new Map(); + const safeRows = Array.isArray(rows) ? rows : []; + + for (const row of safeRows) { + const key = resolveKey(row); + if (!key) { + continue; + } + + const createdAtMs = toTimeMs(row.created_at); + const rowId = toNumber(row.id); + const current = latestSnapshotMap.get(key); + if (!current) { + latestSnapshotMap.set(key, { + after_quantity: toNumber(row.after_quantity), + created_at_ms: createdAtMs, + id: rowId, + }); + continue; + } + + const currentCreatedAtMs = current.created_at_ms; + const shouldReplace = (createdAtMs !== null && currentCreatedAtMs === null) + || (createdAtMs !== null && currentCreatedAtMs !== null && createdAtMs > currentCreatedAtMs) + || (createdAtMs === currentCreatedAtMs && rowId > current.id); + + if (shouldReplace) { + current.after_quantity = toNumber(row.after_quantity); + current.created_at_ms = createdAtMs; + current.id = rowId; + } + } + + const snapshotMap = new Map(); + for (const [ key, value ] of latestSnapshotMap.entries()) { + snapshotMap.set(key, toNumber(value.after_quantity)); + } + + return snapshotMap; +} + +/** + * 将 SQL WHERE 子句数组中的表别名 t. 重绑定为指定别名,便于在派生表子查询中复用同一组条件。 + * @param {string[]} clauses WHERE 子句数组 + * @param {string} alias 目标表别名 + * @return {string[]} 重绑定后的子句数组 + */ +function rebindTableAlias(clauses, alias) { + return clauses.map(clause => String(clause).replace(/\bt\./g, `${alias}.`)); +} + +/** 默认分页每页条数 */ +const DEFAULT_PAGE_SIZE = 20; +/** 导出全量分页大小(导出必须全量,避免默认分页截断汇总与明细) */ +const EXPORT_FULL_PAGE_SIZE = 1000000; + +/** + * 对已排序的结果列表做内存分页切片。 + * 分页参数未传或非法时回退默认分页:page=1、pageSize=20。 + * @param {Object[]} list 已排序列表 + * @param {Object|null|undefined} pagination 分页参数 { page, pageSize }(兼容 page_size) + * @return {{items: Object[], meta: {page: number, pageSize: number, total: number, totalPages: number, hasPrevious: boolean, hasNext: boolean}}} 分页结果 + */ +function paginateList(list, pagination) { + const hasPagination = pagination && typeof pagination === 'object'; + const rawPage = hasPagination ? Number(pagination.page) : NaN; + const rawPageSize = hasPagination + ? Number(pagination.pageSize !== undefined ? pagination.pageSize : pagination.page_size) + : NaN; + + const page = Number.isInteger(rawPage) && rawPage >= 1 ? rawPage : 1; + const pageSize = Number.isInteger(rawPageSize) && rawPageSize >= 1 ? rawPageSize : DEFAULT_PAGE_SIZE; + + const total = Array.isArray(list) ? list.length : 0; + const totalPages = Math.ceil(total / pageSize) || 1; + const offset = (page - 1) * pageSize; + const items = list.slice(offset, offset + pageSize); + + return { + items, + meta: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }; +} + +/** + * 获取报表流水数据源配置。 + * @param {boolean} isBySpace 是否按库位维度统计 + * @return {{tableName: string, spaceSelectSql: string, spaceGroupSql: string, spaceOrderSql: string}} 配置对象 + */ +function resolveTransactionSourceConfig(isBySpace) { + if (isBySpace) { + return { + tableName: 'wms_storage_transaction', + // 历史库位流水可能存在空 space_id,统一回退到 0 作为“未知库位”口径,避免统计漏数。 + spaceSelectSql: 'COALESCE(t.space_id, 0) AS space_id', + spaceGroupSql: ', COALESCE(t.space_id, 0)', + spaceOrderSql: ', COALESCE(t.space_id, 0) ASC', + }; + } + + return { + tableName: 'wms_stock_transaction', + spaceSelectSql: '0 AS space_id', + spaceGroupSql: '', + spaceOrderSql: '', + }; +} + +class StorageReportService extends Service { + /** + * 加载库存报表导出所需的名称映射。 + * @param {Object} options 参数 + * @param {number[]} [options.stockIds=[]] 商品库存ID列表 + * @param {number[]} [options.storeIds=[]] 货主ID列表 + * @param {number[]} [options.spaceIds=[]] 库位ID列表 + * @param {boolean} [options.includeBarcode=false] 是否加载条码映射 + * @param {number[]} [options.entryOrderIds=[]] 入库单ID列表 + * @param {number[]} [options.orderIds=[]] 出库单ID列表 + * @param {number|null} [options.warehouseId=null] 仓库ID + * @param {Map} [options.orderWarehouseMap] 订单ID到仓库ID映射(货主模式跨仓库场景下用于运单同仓校验) + * @return {Promise} 映射对象 + */ + async loadReportReferenceMaps({ + stockIds = [], + storeIds = [], + spaceIds = [], + includeBarcode = false, + entryOrderIds = [], + orderIds = [], + warehouseId = null, + orderWarehouseMap = null, + } = {}) { + const { ctx, app } = this; + const normalizedStockIds = [ ...new Set((stockIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedStoreIds = [ ...new Set((storeIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedSpaceIds = [ ...new Set((spaceIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedEntryOrderIds = [ ...new Set((entryOrderIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedOrderIds = [ ...new Set((orderIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedWarehouseId = Number(warehouseId); + + // 从 getStockDetails 获取商品名称、条码信息 + const stockMap = new Map(); + const barcodeMap = new Map(); + if (normalizedStockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + normalizedStockIds, + { warehouseId } // store 模式下为 null → 跳过 warehouse 过滤 + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + stockMap.set(sid, { + id: sid, + item_name: detail.item_name, + item_code: detail.item_code, + }); + // 提取条码 + if (includeBarcode && Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + const barcodeSet = new Set(); + for (const bc of detail.barcodes) { + const barcode = String(bc.barcode || '').trim(); + if (barcode) { + barcodeSet.add(barcode); + } + } + barcodeMap.set(sid, barcodeSet); + } + } + } + + const [ storeRows, spaceRows, entryOrderRows, orderDeliveryRows, orderExpressRows, storeWarehouseRows ] = await Promise.all([ + normalizedStoreIds.length > 0 + ? ctx.model.Store.findAll({ + where: { + id: normalizedStoreIds, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], + normalizedSpaceIds.length > 0 + ? ctx.model.LocationSpace.findAll({ + where: { + id: normalizedSpaceIds, + }, + attributes: [ 'id', 'custom_name', 'space_code' ], + raw: true, + }) + : [], + normalizedEntryOrderIds.length > 0 + ? ctx.model.query( + 'SELECT id, entry_order_code, express_code, logistics_code, logistics_name, source_type FROM wms_entry_order WHERE id IN (:ids)', + { + replacements: { ids: normalizedEntryOrderIds }, + type: app.Sequelize.QueryTypes.SELECT, + } + ) + : [], + this.loadOrderDeliveryRows(normalizedOrderIds, warehouseId, orderWarehouseMap), + normalizedOrderIds.length > 0 + ? (async () => { + // 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID, + // 禁止仅凭订单ID跨仓串读运单号。 + // 仓库模式:直接用当前仓库ID过滤;货主模式:按订单所属仓库分组查询。 + const resultRows = []; + const querySql = 'SELECT order_id, waybill_code FROM wms_order_express WHERE order_id IN (:ids) AND warehouse_id = :warehouseId'; + if (Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0) { + resultRows.push(...await ctx.model.query( + querySql, + { + replacements: { ids: normalizedOrderIds, warehouseId: normalizedWarehouseId }, + type: app.Sequelize.QueryTypes.SELECT, + } + )); + } else if (orderWarehouseMap instanceof Map && orderWarehouseMap.size > 0) { + const idsByWarehouse = new Map(); + for (const orderId of normalizedOrderIds) { + const orderWarehouseId = Number(orderWarehouseMap.get(orderId)); + if (!Number.isInteger(orderWarehouseId) || orderWarehouseId <= 0) { + continue; + } + if (!idsByWarehouse.has(orderWarehouseId)) { + idsByWarehouse.set(orderWarehouseId, []); + } + idsByWarehouse.get(orderWarehouseId).push(orderId); + } + for (const [ orderWarehouseId, warehouseOrderIds ] of idsByWarehouse.entries()) { + resultRows.push(...await ctx.model.query( + querySql, + { + replacements: { ids: warehouseOrderIds, warehouseId: orderWarehouseId }, + type: app.Sequelize.QueryTypes.SELECT, + } + )); + } + } + return resultRows; + })() + : [], + normalizedStoreIds.length > 0 && Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [app.Sequelize.Op.in]: normalizedStoreIds }, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }) + : [], + ]); + + const storeMap = new Map((storeRows || []).map(item => [ Number(item.id), item ])); + const spaceMap = new Map((spaceRows || []).map(item => [ Number(item.id), item ])); + + // 入库单映射:entry_order_id → { entry_order_code, express_code, logistics_code, logistics_name, source_type } + const entryOrderMap = new Map(); + for (const eo of (Array.isArray(entryOrderRows) ? entryOrderRows : [])) { + entryOrderMap.set(Number(eo.id), eo); + } + + // 发货单映射:order_id → source_order_codes + const orderDeliveryMap = new Map(); + for (const od of (Array.isArray(orderDeliveryRows) ? orderDeliveryRows : [])) { + orderDeliveryMap.set(Number(od.id), od); + } + + // 运单映射:order_id → waybill_code(取第一条) + const orderExpressMap = new Map(); + for (const oe of (Array.isArray(orderExpressRows) ? orderExpressRows : [])) { + const oid = Number(oe.order_id); + if (oid > 0 && !orderExpressMap.has(oid)) { + orderExpressMap.set(oid, String(oe.waybill_code || '').trim()); + } + } + + // 货主自定义名称映射:store_id → store_remask + const storeWarehouseMap = new Map(); + for (const sw of (Array.isArray(storeWarehouseRows) ? storeWarehouseRows : [])) { + const sid = Number(sw.store_id); + if (sid > 0 && !storeWarehouseMap.has(sid)) { + storeWarehouseMap.set(sid, String(sw.store_remask || '').trim()); + } + } + + return { + stockMap, + storeMap, + spaceMap, + barcodeMap, + entryOrderMap, + orderDeliveryMap, + orderExpressMap, + storeWarehouseMap, + }; + } + + /** + * 读取发货单(配送)基础字段:delivery_order_code / source_order_codes。 + * 发货单按仓库分表,单体表 wms_order_delivery 在分表环境下为空;因此先按仓库查询 + * 订单位置索引表 wms_order_id_location_{仓库} 取得 location(current/dispatch/history/outsourced), + * 直达对应分表取值;索引缺失(存量未回填)或指针失效时,退回逐表位扫描。 + * @param {number[]} orderIds 订单ID列表 + * @param {number|null} warehouseId 仓库ID(仓库模式为当前仓库;货主模式为 null,按订单所属仓库分组) + * @param {Map|null} orderWarehouseMap 订单ID → 所属仓库ID(货主模式) + * @return {Promise>} 命中的发货单记录 + */ + async loadOrderDeliveryRows(orderIds = [], warehouseId = null, orderWarehouseMap = null) { + const { ctx, app } = this; + const normalizedOrderIds = [ ...new Set((orderIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + if (normalizedOrderIds.length === 0) { + return []; + } + + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + const defaultWarehouseId = Number(warehouseId) > 0 ? Number(warehouseId) : 0; + + // 按仓库分组:货主模式优先用行所属仓库,缺失时回落仓库模式仓库ID + const idsByWarehouse = new Map(); + for (const orderId of normalizedOrderIds) { + const rowWarehouseId = orderWarehouseMap && typeof orderWarehouseMap.get === 'function' + ? Number(orderWarehouseMap.get(orderId)) + : 0; + const shardWarehouseId = rowWarehouseId > 0 ? rowWarehouseId : defaultWarehouseId; + if (shardWarehouseId <= 0) { + continue; + } + if (!idsByWarehouse.has(shardWarehouseId)) { + idsByWarehouse.set(shardWarehouseId, []); + } + idsByWarehouse.get(shardWarehouseId).push(orderId); + } + + /** + * 查询单个仓库分表,返回命中行与未命中的订单ID。 + * @param {number} shardWarehouseId 仓库ID + * @param {string} tableType 表位类型 + * @param {number[]} ids 订单ID列表 + * @return {Promise<{rows: Array, unresolvedIds: number[]}>} 查询结果 + */ + const queryShardTable = async (shardWarehouseId, tableType, ids) => { + const tableName = factory && typeof factory.generateTableName === 'function' + ? factory.generateTableName(shardWarehouseId, tableType) + : ''; + if (ids.length === 0 || !SHARD_DELIVERY_TABLE_PATTERN.test(String(tableName))) { + return { rows: [], unresolvedIds: ids }; + } + try { + const shardRows = await ctx.model.query( + `SELECT id, delivery_order_code, source_order_codes FROM ${tableName} WHERE id IN (:ids)`, + { + replacements: { ids }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + const safeRows = Array.isArray(shardRows) ? shardRows : []; + const foundIdSet = new Set(safeRows.map(row => Number(row.id))); + return { rows: safeRows, unresolvedIds: ids.filter(id => !foundIdSet.has(id)) }; + } catch (error) { + // 分表可能尚未创建:命中“表不存在”时静默跳过(回退流水单据号),其余异常告警后继续 + const isMissingTable = /ER_NO_SUCH_TABLE|doesn't exist|does not exist/i.test(String(error && error.message)); + if (!isMissingTable) { + ctx.logger.warn(`[loadOrderDeliveryRows] 查询 ${tableName} 失败,跳过该表位: ${error.message}`); + } + return { rows: [], unresolvedIds: ids }; + } + }; + + const rows = []; + for (const [ shardWarehouseId, warehouseOrderIds ] of idsByWarehouse) { + // 1) 位置索引表:orderId → location,命中时直达对应分表 + let locationMap = new Map(); + if (factory && typeof factory.getOrderLocations === 'function') { + try { + const resolvedLocations = await factory.getOrderLocations(warehouseOrderIds, shardWarehouseId); + if (resolvedLocations instanceof Map) { + locationMap = resolvedLocations; + } + } catch (error) { + ctx.logger.warn(`[loadOrderDeliveryRows] 查询订单位置索引失败,退回逐表位扫描: ${error.message}`); + } + } + + const idsByLocation = new Map(); + let unresolvedIds = []; + for (const orderId of warehouseOrderIds) { + const location = String(locationMap.get(orderId) || '').trim(); + if (DELIVERY_SHARD_TABLE_TYPES.includes(location)) { + if (!idsByLocation.has(location)) { + idsByLocation.set(location, []); + } + idsByLocation.get(location).push(orderId); + } else { + // 无位置记录(存量订单未回填索引) + unresolvedIds.push(orderId); + } + } + + for (const [ tableType, locationOrderIds ] of idsByLocation) { + const located = await queryShardTable(shardWarehouseId, tableType, locationOrderIds); + rows.push(...located.rows); + // 位置指针可能过期(订单已迁移但指针未更新),未命中的订单继续兜底 + unresolvedIds.push(...located.unresolvedIds); + } + + // 2) 兜底:无位置记录或指针失效时逐表位扫描 + for (const tableType of DELIVERY_SHARD_TABLE_TYPES) { + if (unresolvedIds.length === 0) { + break; + } + const scanned = await queryShardTable(shardWarehouseId, tableType, unresolvedIds); + rows.push(...scanned.rows); + unresolvedIds = scanned.unresolvedIds; + } + } + + return rows; + } + + /** + * 构建库存报表导出文件名。 + * @param {string|Date|null|undefined} startTime 开始时间 + * @param {string|Date|null|undefined} endTime 结束时间 + * @param {string|number} [uniqueToken=''] 唯一后缀:重复导出同一时间范围时避免同名对象覆盖、CDN 命中旧文件 + * @return {string} 导出文件名 + */ + buildExportFilename(startTime, endTime, uniqueToken = '') { + const startToken = formatDateToken(startTime); + const endToken = formatDateToken(endTime); + const todayToken = formatDateToken(new Date()); + const normalizedToken = String(uniqueToken ?? '').trim(); + const suffix = normalizedToken ? `_${normalizedToken}` : ''; + + if (startToken && endToken) { + return `库存报表_${startToken}_${endToken}${suffix}.xlsx`; + } + + if (startToken) { + return `库存报表_${startToken}${suffix}.xlsx`; + } + + if (endToken) { + return `库存报表_${endToken}${suffix}.xlsx`; + } + + return `库存报表_${todayToken}${suffix}.xlsx`; + } + + /** + * 导出库存流水统计报表。 + * @param {string|Date|null} startTime 开始时间(闭区间下限) + * @param {string|Date|null} endTime 结束时间(闭区间上限) + * @param {boolean|string|number} [bySpace=false] 是否按库位返回 + * @param {Array|number|string|null} [storeIds=[]] 货主ID列表 + * @param {Object} [sort] 排序参数 + * @param {string} [sort.sortField] 排序字段 + * @param {string} [sort.sortOrder] 排序顺序 + * @param {string} [exportMode] 导出模式(仅仓库侧生效):'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录;货主侧固定只导出出入库流水 + * @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度 + * @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤) + * @param {string} [keyword=''] 商品关键字(模糊匹配) + * @param {Function} [onProgress=null] 进度回调:async ({ status, progress, currentCount, totalCount, message, result }) => void + * @return {Promise} excel 上传结果 + */ + async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '', searchMode = 'warehouse', stockIds = null, keyword = '', onProgress = null) { + const { ctx, app } = this; + const isStoreMode = searchMode === 'store'; + // 导出必须全量:显式传大分页,避免默认分页(pageSize=20)截断汇总与明细白名单 + const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort, searchMode, stockIds, keyword, { page: 1, pageSize: EXPORT_FULL_PAGE_SIZE }); + if (!searchResult || searchResult.code !== 200) { + return searchResult; + } + + const summaryList = Array.isArray(searchResult.data && searchResult.data.list) + ? searchResult.data.list + : []; + const rawPrimaryId = Number(ctx.user && ctx.user.store_id); + const storeId = isStoreMode ? rawPrimaryId : null; + const warehouseId = isStoreMode ? null : rawPrimaryId; + const startTimeMs = toTimeMs(startTime); + const endTimeMs = toTimeMs(endTime); + const normalizedStoreIds = normalizeStoreIds(storeIds); + const isBySpace = normalizeBoolean(bySpace); + + // 主维度:仓库模式用 warehouse_id,货主模式用 store_id + const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id'; + const primaryDimVal = isStoreMode ? storeId : warehouseId; + const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId'; + // 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤) + const secondaryIds = normalizedStoreIds; + const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id'; + const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds'; + + const whereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ]; + const replacements = { + [primaryDimAlias]: primaryDimVal, + }; + + if (startTimeMs !== null) { + whereClauses.push('t.created_at >= :startTime'); + replacements.startTime = startTime; + } + + if (endTimeMs !== null) { + whereClauses.push('t.created_at <= :endTime'); + replacements.endTime = endTime; + } + + if (secondaryIds.length > 0) { + whereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`); + replacements[secondaryDimAlias] = secondaryIds; + } + + const normalizedExportMode = String(exportMode || '').trim(); + if (isStoreMode) { + // 货主侧口径:变更记录只包含出入库流水,锁定/解锁(LOCK/UNLOCK)一律不导出,无视 exportMode + whereClauses.push('t.transaction_type NOT IN (:excludeStoreTypes)'); + replacements.excludeStoreTypes = [ 'LOCK', 'UNLOCK' ]; + } else if (normalizedExportMode !== 'item') { + whereClauses.push('t.transaction_type != :excludeLockType'); + replacements.excludeLockType = 'LOCK'; + } + + // 明细商品范围与汇总对齐:keyword/stock_ids 过滤后的汇总 stock 白名单同步作用于明细, + // 避免导出与汇总无关商品的变更记录 + const summaryStockIds = [ ...new Set(summaryList.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + if (summaryStockIds.length === 0) { + // 汇总无数据时明细也不应导出任何流水 + whereClauses.push('0 = 1'); + } else { + whereClauses.push('t.stock_id IN (:detailStockIds)'); + replacements.detailStockIds = summaryStockIds; + } + + const detailTransactionTable = isBySpace ? 'wms_storage_transaction' : 'wms_stock_transaction'; + const detailSpaceSelectSql = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id' : '0 AS space_id'; + const detailInventoryTypeSelectSql = isBySpace ? 't.inventory_type' : '\'\' AS inventory_type'; + const detailReceivingIdSelectSql = isBySpace ? 'NULL AS receiving_id' : 't.receiving_id'; + const detailEntryOrderIdSelectSql = isBySpace ? 'NULL AS entry_order_id' : 't.entry_order_id'; + + const progressHandler = typeof onProgress === 'function' ? onProgress : async () => {}; + + // 明细总数:仅用于进度展示,COUNT 一次(秒级) + const totalCountRows = await ctx.model.query( + `SELECT COUNT(*) AS cnt FROM ${detailTransactionTable} t WHERE ${whereClauses.join(' AND ')}`, + { + replacements, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + const detailTotalCount = Array.isArray(totalCountRows) && totalCountRows.length > 0 + ? Number(totalCountRows[0].cnt) + : 0; + + await progressHandler({ + status: 'running', + progress: detailTotalCount > 0 ? 5 : 90, + currentCount: 0, + totalCount: detailTotalCount, + message: detailTotalCount > 0 ? `已命中 ${detailTotalCount} 条变更记录,开始导出` : '未命中变更记录,开始生成文件', + }); + + // 汇总 sheet 数据(汇总量小,全内存构建) + const summaryColumns = [ + { header: '开始时间', key: 'start_time' }, + { header: '结束时间', key: 'end_time' }, + { header: '货主ID', key: 'store_id' }, + { header: '货主名称', key: 'store_name' }, + { header: '仓库ID', key: 'warehouse_id' }, + { header: '仓库名称', key: 'warehouse_name' }, + { header: '商品库存ID', key: 'stock_id' }, + { header: '商品编码', key: 'item_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '条码', key: 'barcode' }, + ...(isBySpace + ? [ + { header: '库位ID', key: 'space_id' }, + { header: '库位名称', key: 'space_name' }, + ] + : []), + { header: '期初', key: 'begin_total' }, + { header: '入库', key: 'inbound_total' }, + { header: '出库', key: 'outbound_total' }, + { header: '期末', key: 'end_total' }, + ]; + + const summarySheetRows = summaryList.map(item => ({ + start_time: item.start_time || '', + end_time: item.end_time || '', + store_id: toNumber(item.store_id), + store_name: item.store_name || '', + warehouse_id: toNumber(item.warehouse_id), + warehouse_name: item.warehouse_name || '', + stock_id: toNumber(item.stock_id), + item_code: item.item_code || '', + item_name: item.item_name || '', + barcode: item.barcode || '', + ...(isBySpace + ? { + space_id: toNumber(item.space_id), + space_name: item.space_name || '', + } + : {}), + begin_total: toNumber(item.begin_total), + inbound_total: toNumber(item.inbound_total), + outbound_total: toNumber(item.outbound_total), + end_total: toNumber(item.end_total), + })); + + const detailColumns = [ + { header: '时间', key: 'created_at' }, + { header: '类型', key: 'transaction_type' }, + { header: '货主名称', key: 'store_name' }, + { header: '自定义店铺名称', key: 'store_remask' }, + { header: '商品库存ID', key: 'stock_id' }, + { header: '商品编码', key: 'item_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '条码', key: 'barcode' }, + { header: '变动数量', key: 'quantity' }, + { header: '变更前库存', key: 'before_quantity' }, + { header: '变更后库存', key: 'after_quantity' }, + { header: '变更前锁定', key: 'before_locked_quantity' }, + { header: '变更后锁定', key: 'after_locked_quantity' }, + { header: '批次号', key: 'batch_no' }, + { header: '库存类型', key: 'inventory_type' }, + { header: '单据类型', key: 'order_type' }, + { header: '单据号', key: 'order_no' }, + { header: '单据ID', key: 'order_id' }, + { header: '奇门入库单号', key: 'qimen_entry_order_code' }, + { header: '平台交易单号', key: 'platform_trade_no' }, + { header: '运单号', key: 'waybill_no' }, + { header: '入库单运单号', key: 'entry_order_waybill_no' }, + { header: '入库单快递公司', key: 'entry_order_express_company' }, + { header: '收货单ID', key: 'receiving_id' }, + { header: '入库单ID', key: 'entry_order_id' }, + { header: '操作人', key: 'operator_name' }, + { header: '备注', key: 'remark' }, + ]; + + // 明细游标分页:按主键 id 升序分批拉取(id 自增序≈插入序), + // 流式写入 ExcelJS stream,避免一次性把全部明细与单元格留在内存。 + const detailBatchSize = 5000; + // 文件名带时间戳:同一时间范围重复导出会覆盖同名对象,CDN/浏览器会继续命中旧文件 + const filename = this.buildExportFilename(startTime, endTime, Date.now()); + let tempDir = null; + let workbook = null; + let currentCount = 0; + let cursorId = 0; + + try { + tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'wms-stock-report-export-')); + const filePath = path.join(tempDir, filename); + workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const summaryWorksheet = workbook.addWorksheet('汇总'); + summaryWorksheet.columns = summaryColumns.map(column => ({ header: column.header, key: column.key })); + for (const row of summarySheetRows) { + summaryWorksheet.addRow(row); + } + summaryWorksheet.commit(); + + const detailWorksheet = workbook.addWorksheet('变更记录'); + detailWorksheet.columns = detailColumns.map(column => ({ header: column.header, key: column.key })); + + for (;;) { + const batchReplacements = { ...replacements, cursorId }; + const batchWhereClauses = [ ...whereClauses, 't.id > :cursorId' ]; + const batchRows = await ctx.model.query(` + SELECT + t.id, + t.created_at, + t.transaction_type, + t.store_id, + t.warehouse_id, + t.stock_id, + ${detailSpaceSelectSql}, + t.quantity, + t.before_quantity, + t.after_quantity, + t.before_locked_quantity, + t.after_locked_quantity, + t.batch_no, + ${detailInventoryTypeSelectSql}, + t.order_type, + t.order_no, + t.order_id, + ${detailReceivingIdSelectSql}, + ${detailEntryOrderIdSelectSql}, + t.operator_name, + t.remark + FROM ${detailTransactionTable} t + WHERE ${batchWhereClauses.join(' AND ')} + ORDER BY t.id ASC + LIMIT ${detailBatchSize} + `, { + replacements: batchReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const safeBatchRows = Array.isArray(batchRows) ? batchRows : []; + if (safeBatchRows.length === 0) { + break; + } + + // 本批富化:仅针对本批涉及的商品/货主/库位/入库单/订单加载映射 + const batchStockIds = [ ...new Set(safeBatchRows.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const batchStoreIds = [ ...new Set(safeBatchRows.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const batchSpaceIds = [ ...new Set(safeBatchRows.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const batchEntryOrderIds = [ ...new Set(safeBatchRows.map(item => Number(item.entry_order_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const batchOrderIds = [ ...new Set(safeBatchRows.map(item => Number(item.order_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + + // 货主模式:从流水明细按订单ID收集所属仓库,用于运单查询强制同仓校验 + const batchOrderWarehouseMap = new Map(); + for (const item of safeBatchRows) { + const orderId = Number(item.order_id); + const rowWarehouseId = Number(item.warehouse_id); + if (Number.isInteger(orderId) && orderId > 0 && Number.isInteger(rowWarehouseId) && rowWarehouseId > 0) { + batchOrderWarehouseMap.set(orderId, rowWarehouseId); + } + } + + const maps = await this.loadReportReferenceMaps({ + stockIds: batchStockIds, + storeIds: batchStoreIds, + spaceIds: batchSpaceIds, + includeBarcode: true, + entryOrderIds: batchEntryOrderIds, + orderIds: batchOrderIds, + warehouseId, + orderWarehouseMap: batchOrderWarehouseMap, + }); + + let lastRow = null; + for (const item of safeBatchRows) { + const exportRow = this.buildDetailExportRow(item, maps); + lastRow = detailWorksheet.addRow(exportRow); + currentCount += 1; + const rowId = Number(item.id); + if (Number.isInteger(rowId) && rowId > cursorId) { + cursorId = rowId; + } + } + // 行级 commit:仅 flush 到当前批次末行(worksheet.commit 是终态,不能在中间调用) + if (lastRow) { + lastRow.commit(); + } + + await progressHandler({ + status: 'running', + progress: detailTotalCount > 0 + ? Math.min(95, Math.max(5, Math.round(5 + (currentCount / detailTotalCount) * 90))) + : 95, + currentCount, + totalCount: detailTotalCount, + message: detailTotalCount > 0 ? `已完成 ${currentCount}/${detailTotalCount} 条变更记录` : '变更记录生成完成', + }); + + // 本批不满一页说明已到末尾,避免再发一次空查询 + if (safeBatchRows.length < detailBatchSize) { + break; + } + } + + detailWorksheet.commit(); + await workbook.commit(); + + const uploadResult = await ctx.service.systems.excel.uploadExistingFile({ + filePath, + filename, + dir: `exports/storage/report/${warehouseId || storeId || 'common'}`, + category: 'document', + }); + + await progressHandler({ + status: 'success', + progress: 100, + currentCount, + totalCount: detailTotalCount, + message: '导出任务完成', + result: uploadResult, + }); + + return uploadResult; + } catch (error) { + if (workbook && workbook.stream && typeof workbook.stream.destroy === 'function') { + workbook.stream.destroy(); + } + throw error; + } finally { + if (tempDir) { + await fs.promises.rm(tempDir, { recursive: true, force: true }).catch(() => {}); + } + } + } + + /** + * 将一条流水明细行映射为导出 sheet 行。 + * @param {Object} item 流水明细行 + * @param {Object} maps 名称映射集合(loadReportReferenceMaps 返回值) + * @return {Object} 导出 sheet 行 + */ + buildDetailExportRow(item, maps = {}) { + const stockId = toNumber(item.stock_id); + const storeId = toNumber(item.store_id); + const stock = maps.stockMap && maps.stockMap.get(stockId) || {}; + const store = maps.storeMap && maps.storeMap.get(storeId) || {}; + const barcodeSet = maps.barcodeMap ? maps.barcodeMap.get(stockId) : null; + + const entryOrderId = toNumber(item.entry_order_id); + const entryOrder = entryOrderId > 0 && maps.entryOrderMap ? (maps.entryOrderMap.get(entryOrderId) || {}) : {}; + const isQimenEntry = entryOrder.source_type === 'QM'; + + const orderId = toNumber(item.order_id); + const orderDelivery = orderId > 0 && maps.orderDeliveryMap ? (maps.orderDeliveryMap.get(orderId) || {}) : {}; + const waybillCode = maps.orderExpressMap ? (maps.orderExpressMap.get(orderId) || '') : ''; + + // 运单号:出库取 order_express.waybill_code,入库取 entry_order.express_code + const generalWaybillNo = waybillCode + || (entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : ''); + + return { + created_at: formatDateTime(item.created_at), + transaction_type: formatTransactionType(item.transaction_type), + store_id: storeId, + store_name: store.company_name || '', + store_remask: maps.storeWarehouseMap ? (maps.storeWarehouseMap.get(storeId) || '') : '', + stock_id: stockId, + item_code: stock.item_code || '', + item_name: stock.item_name || '', + barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', + quantity: toNumber(item.quantity), + before_quantity: toNumber(item.before_quantity), + after_quantity: toNumber(item.after_quantity), + before_locked_quantity: toNumber(item.before_locked_quantity), + after_locked_quantity: toNumber(item.after_locked_quantity), + batch_no: item.batch_no || '', + inventory_type: item.inventory_type || '', + order_type: item.order_type || '', + order_no: String(orderDelivery.delivery_order_code || item.order_no || '').trim(), + order_id: orderId, + receiving_id: toNumber(item.receiving_id), + entry_order_id: entryOrderId, + operator_name: item.operator_name || '', + remark: item.remark || '', + // 新增字段 + qimen_entry_order_code: isQimenEntry ? String(entryOrder.entry_order_code || '').trim() : '', + platform_trade_no: String(orderDelivery.source_order_codes || item.order_no || '').trim(), + entry_order_waybill_no: entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : '', + entry_order_express_company: entryOrderId > 0 ? String(entryOrder.logistics_name || '').trim() : '', + waybill_no: String(generalWaybillNo || '').trim(), + }; + } + + /** + * 根据关键字解析匹配的 stock_id 列表。 + * 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)模糊匹配。 + * @param {string} keyword 搜索关键字 + * @param {string} primaryDimCol 主维度列名(warehouse_id 或 store_id) + * @param {number} primaryDimVal 主维度值 + * @return {Promise} 匹配的 stock_id 列表 + */ + async _resolveKeywordToStockIds(keyword, primaryDimCol, primaryDimVal) { + const { ctx, app } = this; + const normalizedKeyword = String(keyword || '').trim(); + if (!normalizedKeyword) { + return []; + } + + const likePattern = `%${normalizedKeyword}%`; + // 如果 keyword 为纯数字,同时支持按 stock_id(SKU ID)精确匹配 + const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null; + + // 从 wms_stock_warehouse 按 item_code / item_name / goods_code / id(SKU) 模糊匹配 + const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : ''; + const stockRows = await ctx.model.query(` + SELECT DISTINCT sw.id AS stock_id + FROM wms_stock_warehouse sw + WHERE sw.${primaryDimCol} = :primaryDimVal + AND ( + sw.item_code LIKE :keyword + OR sw.item_name LIKE :keyword + OR sw.goods_code LIKE :keyword + ${extraIdCondition} + ) + `, { + replacements: { primaryDimVal, keyword: likePattern, exactStockId }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + // 从 wms_stock_barcodes 按 barcode 模糊匹配 + const barcodeRows = await ctx.model.query(` + SELECT DISTINCT sb.stock_id + FROM wms_stock_barcodes sb + INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.${primaryDimCol} = :primaryDimVal + WHERE sb.barcode LIKE :keyword + `, { + replacements: { primaryDimVal, keyword: likePattern }, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const stockIdSet = new Set(); + for (const row of stockRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + for (const row of barcodeRows) { + const sid = Number(row.stock_id); + if (sid > 0) stockIdSet.add(sid); + } + + return [ ...stockIdSet ]; + } + + /** + * 查询库存流水统计报表。 + * 规则: + * 1) 期初优先取 start_time 之前最后一条流水的 after_quantity。 + * 2) 若 start_time 之前无流水,期初回退到区间内首条流水的 before_quantity。 + * 3) 期末取区间内末条流水的 after_quantity。 + * 4) 若维度键在区间内无流水,期末回退到期初(库存未变动,保持“期末 = 期初 + 入库 - 出库”恒等)。 + * 5) by_space=false 时按 stock_id+store_id 维度输出;by_space=true 时按 stock_id+space_id+store_id 维度输出。 + * + * @param {string|Date|null} startTime 开始时间(闭区间下限) + * @param {string|Date|null} endTime 结束时间(闭区间上限) + * @param {boolean|string|number} [bySpace=false] 是否按库位返回 + * @param {Array|number|string|null} [storeIds=[]] 货主ID列表(store模式为仓库ID列表) + * @param {Object} [sort] 排序参数 + * @param {string} [sort.sortField] 排序字段(begin_total、inbound_total、outbound_total、end_total) + * @param {string} [sort.sortOrder] 排序顺序(ASC、DESC,大小写不敏感) + * @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度 + * @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤),与 keyword 互斥 + * @param {string} [keyword=''] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配),与 stockIds 互斥 + * @param {Object|null} [pagination=null] 分页参数 { page, pageSize }(兼容 page_size);未传或非法时默认 page=1、pageSize=20,仅对当前页行加载名称信息 + * @return {Promise} code/data/message 结构 + */ + async search(startTime, endTime, bySpace = false, storeIds = [], sort = null, searchMode = 'warehouse', stockIds = null, keyword = '', pagination = null) { + const { ctx, app } = this; + const isStoreMode = searchMode === 'store'; + const rawPrimaryId = Number(ctx.user && ctx.user.store_id); + const storeId = isStoreMode ? rawPrimaryId : null; + const warehouseId = isStoreMode ? null : rawPrimaryId; + + if (!isStoreMode && !warehouseId) { + return { + code: 400, + message: '用户未绑定仓库', + data: { list: [] }, + }; + } + if (isStoreMode && !storeId) { + return { + code: 400, + message: '用户未绑定货主', + data: { list: [] }, + }; + } + + // 主维度:仓库模式用 warehouse_id,货主模式用 store_id + const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id'; + const primaryDimVal = isStoreMode ? storeId : warehouseId; + const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId'; + + // 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤) + const secondaryIds = normalizeStoreIds(storeIds); + const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id'; + const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds'; + + const startTimeMs = toTimeMs(startTime); + const endTimeMs = toTimeMs(endTime); + + if (startTime !== undefined && startTime !== null && startTime !== '' && startTimeMs === null) { + return { + code: 400, + message: 'start_time 参数不合法', + data: { list: [] }, + }; + } + + if (endTime !== undefined && endTime !== null && endTime !== '' && endTimeMs === null) { + return { + code: 400, + message: 'end_time 参数不合法', + data: { list: [] }, + }; + } + + if (startTimeMs !== null && endTimeMs !== null && startTimeMs > endTimeMs) { + return { + code: 400, + message: 'start_time 不能大于 end_time', + data: { list: [] }, + }; + } + + const isBySpace = normalizeBoolean(bySpace); + + // 归一化 stock_ids:优先使用 keyword 解析,其次使用显式传入的 stockIds + let resolvedStockIds = null; + const normalizedKeyword = String(keyword || '').trim(); + if (normalizedKeyword) { + resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal); + if (resolvedStockIds.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [], pagination: paginateList([], pagination).meta }, + }; + } + } else if (stockIds !== null && stockIds !== undefined) { + const rawIds = Array.isArray(stockIds) ? stockIds.flat() : [ stockIds ]; + resolvedStockIds = [ ...new Set( + rawIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + ) ]; + if (resolvedStockIds.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [], pagination: paginateList([], pagination).meta }, + }; + } + } + + let baseStockRows = []; + let baseStorageRows = []; + if (!isBySpace) { + const baseWhereClauses = [ `sw.${primaryDimCol} = :${primaryDimAlias}` ]; + const baseReplacements = { + [primaryDimAlias]: primaryDimVal, + }; + + if (secondaryIds.length > 0) { + baseWhereClauses.push(`sw.${secondaryDimCol} IN (:${secondaryDimAlias})`); + baseReplacements[secondaryDimAlias] = secondaryIds; + } + + baseStockRows = await ctx.model.query(` + SELECT + sw.id AS stock_id, + sw.store_id, + sw.warehouse_id, + sw.quantity, + sw.item_code, + sw.item_name + FROM wms_stock_warehouse sw + WHERE ${baseWhereClauses.join(' AND ')} + `, { + replacements: baseReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + // 如果指定了 stock_id 过滤,仅保留匹配的 stock 行 + if (resolvedStockIds !== null) { + const stockIdSet = new Set(resolvedStockIds); + baseStockRows = baseStockRows.filter(row => stockIdSet.has(Number(row.stock_id))); + } + + if (!Array.isArray(baseStockRows) || baseStockRows.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [], pagination: paginateList([], pagination).meta }, + }; + } + } else { + const baseWhereClauses = [ `s.${primaryDimCol} = :${primaryDimAlias}`, 's.delete_at IS NULL' ]; + const baseReplacements = { + [primaryDimAlias]: primaryDimVal, + }; + + if (secondaryIds.length > 0) { + baseWhereClauses.push(`s.${secondaryDimCol} IN (:${secondaryDimAlias})`); + baseReplacements[secondaryDimAlias] = secondaryIds; + } + + baseStorageRows = await ctx.model.query(` + SELECT + s.stock_id, + COALESCE(s.space_id, 0) AS space_id, + s.store_id, + s.warehouse_id, + SUM(s.quantity) AS quantity, + MAX(sw.item_code) AS item_code, + MAX(sw.item_name) AS item_name + FROM wms_storage s + LEFT JOIN wms_stock_warehouse sw ON sw.id = s.stock_id + WHERE ${baseWhereClauses.join(' AND ')} + GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id, s.warehouse_id + `, { + replacements: baseReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + // 如果指定了 stock_id 过滤,仅保留匹配的 stock 行 + if (resolvedStockIds !== null) { + const stockIdSet = new Set(resolvedStockIds); + baseStorageRows = baseStorageRows.filter(row => stockIdSet.has(Number(row.stock_id))); + } + + baseStorageRows = Array.isArray(baseStorageRows) ? baseStorageRows : []; + } + + const rangeWhereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ]; + const rangeReplacements = { + [primaryDimAlias]: primaryDimVal, + }; + + if (startTimeMs !== null) { + rangeWhereClauses.push('t.created_at >= :startTime'); + rangeReplacements.startTime = startTime; + } + + if (endTimeMs !== null) { + rangeWhereClauses.push('t.created_at <= :endTime'); + rangeReplacements.endTime = endTime; + } + + if (secondaryIds.length > 0) { + rangeWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`); + rangeReplacements[secondaryDimAlias] = secondaryIds; + } + + if (!isBySpace) { + const baseStockIds = [ + ...new Set(baseStockRows.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)), + ]; + if (baseStockIds.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [], pagination: paginateList([], pagination).meta }, + }; + } + + rangeWhereClauses.push('t.stock_id IN (:baseStockIds)'); + rangeReplacements.baseStockIds = baseStockIds; + } + + const transactionSource = resolveTransactionSourceConfig(isBySpace); + + const rangeRowsSql = ` + SELECT + t.stock_id, + ${transactionSource.spaceSelectSql}, + t.store_id, + SUM(CASE WHEN t.transaction_type = 'INBOUND' THEN t.quantity ELSE 0 END) AS inbound_total, + SUM(CASE WHEN t.transaction_type = 'OUTBOUND' THEN t.quantity ELSE 0 END) AS outbound_total + FROM ${transactionSource.tableName} t + WHERE ${rangeWhereClauses.join(' AND ')} + GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id + `; + + const rangeRows = await ctx.model.query(rangeRowsSql, { + replacements: rangeReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const safeRangeRows = Array.isArray(rangeRows) ? rangeRows : []; + + // 区间内首/末条快照:在 SQL 端按维度键聚合取极值行,每组仅返回 1 行 + // (before_quantity 取首条、after_quantity 取末条),避免把区间内全部流水明细拉回 Node 内存归并。 + // 兼容 MySQL 5.7:不使用窗口函数,采用派生表聚合 MIN/MAX(created_at) + 标量子查询取极值 id 回表。 + const intervalEdgeRows = await ctx.model.query(` + SELECT + g.stock_id, + g.space_id, + g.store_id, + ft.before_quantity, + lt.after_quantity, + ft.created_at + FROM ( + SELECT + t.stock_id, + ${transactionSource.spaceSelectSql}, + t.store_id, + MIN(t.created_at) AS _min_ct, + MAX(t.created_at) AS _max_ct + FROM ${transactionSource.tableName} t + WHERE ${rangeWhereClauses.join(' AND ')} + GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id + ) g + LEFT JOIN ${transactionSource.tableName} ft + ON ft.id = ( + SELECT MIN(t2.id) + FROM ${transactionSource.tableName} t2 + WHERE ${rebindTableAlias(rangeWhereClauses, 't2').join(' AND ')}${isBySpace ? ' AND COALESCE(t2.space_id, 0) = g.space_id' : ''} AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id + AND t2.created_at = g._min_ct + ) + LEFT JOIN ${transactionSource.tableName} lt + ON lt.id = ( + SELECT MAX(t3.id) + FROM ${transactionSource.tableName} t3 + WHERE ${rebindTableAlias(rangeWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''} AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id + AND t3.created_at = g._max_ct + ) + ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC + `, { + replacements: rangeReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + let preStartSnapshotRows = []; + if (startTimeMs !== null) { + const preStartWhereClauses = [ + `t.${primaryDimCol} = :${primaryDimAlias}`, + 't.created_at < :startTime', + ]; + const preStartReplacements = { + [primaryDimAlias]: primaryDimVal, + startTime, + }; + + if (secondaryIds.length > 0) { + preStartWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`); + preStartReplacements[secondaryDimAlias] = secondaryIds; + } + + if (!isBySpace) { + preStartWhereClauses.push('t.stock_id IN (:baseStockIds)'); + preStartReplacements.baseStockIds = rangeReplacements.baseStockIds; + } + + // start_time 之前的期初快照:SQL 端按维度键聚合取最新一条流水,每组仅返回 1 行, + // 避免把全部历史流水明细拉回 Node 内存归并。兼容 MySQL 5.7(聚合 + 标量子查询取极值 id 回表)。 + preStartSnapshotRows = await ctx.model.query(` + SELECT + g.stock_id, + g.space_id, + g.store_id, + lt.after_quantity, + lt.created_at + FROM ( + SELECT + t.stock_id, + ${transactionSource.spaceSelectSql}, + t.store_id, + MAX(t.created_at) AS _max_ct + FROM ${transactionSource.tableName} t + WHERE ${preStartWhereClauses.join(' AND ')} + GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id + ) g + LEFT JOIN ${transactionSource.tableName} lt + ON lt.id = ( + SELECT MAX(t3.id) + FROM ${transactionSource.tableName} t3 + WHERE ${rebindTableAlias(preStartWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''} AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id + AND t3.created_at = g._max_ct + ) + ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC + `, { + replacements: preStartReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + } + + if (!isBySpace) { + const edgeByStockStore = buildIntervalEdgeMap(intervalEdgeRows, row => { + const stockId = Number(row.stock_id); + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + return null; + } + return `${stockId}_${storeId}`; + }); + const preStartAfterByStockStore = buildPreStartAfterMap(preStartSnapshotRows, row => { + const stockId = Number(row.stock_id); + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + return null; + } + return `${stockId}_${storeId}`; + }); + + const rangeSumByStockStore = new Map(); + for (const row of safeRangeRows) { + const stockId = Number(row.stock_id); + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + continue; + } + const stockStoreKey = `${stockId}_${storeId}`; + if (!rangeSumByStockStore.has(stockStoreKey)) { + rangeSumByStockStore.set(stockStoreKey, { + inbound_total: 0, + outbound_total: 0, + }); + } + const current = rangeSumByStockStore.get(stockStoreKey); + current.inbound_total += toNumber(row.inbound_total); + current.outbound_total += toNumber(row.outbound_total); + } + + const groupedList = baseStockRows + .map(row => { + const stockId = Number(row.stock_id); + const storeId = Number(row.store_id); + const whId = Number(row.warehouse_id) || 0; + const stockStoreKey = `${stockId}_${storeId}`; + const snapshot = edgeByStockStore.get(stockStoreKey); + const rangeSum = rangeSumByStockStore.get(stockStoreKey); + const preStartAfter = preStartAfterByStockStore.get(stockStoreKey); + const hasSnapshot = snapshot && snapshot.has_snapshot; + const hasPreStartSnapshot = preStartAfterByStockStore.has(stockStoreKey); + let beginTotal = 0; + if (hasPreStartSnapshot) { + beginTotal = toNumber(preStartAfter); + } else if (hasSnapshot) { + beginTotal = toNumber(snapshot && snapshot.begin_total); + } + + // 区间内无流水时,期末回退到期初,保证“期末 = 期初 + 入库 - 出库”恒等 + const endTotal = hasSnapshot ? toNumber(snapshot && snapshot.end_total) : beginTotal; + + return { + start_time: startTime || null, + end_time: endTime || null, + stock_id: stockId, + store_id: storeId, + warehouse_id: whId, + begin_total: beginTotal, + end_total: endTotal, + inbound_total: toNumber(rangeSum && rangeSum.inbound_total), + outbound_total: toNumber(rangeSum && rangeSum.outbound_total), + store_name: '', + warehouse_name: '', + // item_code/item_name 取快照查询结果,供按 item_code/item_name 排序使用; + // 最终展示值以 getStockDetails 为准(本字段作为回退) + item_name: row.item_name || '', + barcode: '', + item_code: row.item_code || '', + }; + }) + .filter(item => item.stock_id > 0 && item.store_id > 0); + + // 先按最终规则排序,再做分页切片:仅对当前页行填充名称信息, + // 避免全量 SKU 的商品详情缓存/DB 查询(大数据量下为耗时大头)。 + sortReportList(groupedList, false, sort); + const pageResult = paginateList(groupedList, pagination); + const pageItems = pageResult.items; + + const groupedStockIds = [ ...new Set(pageItems.map(item => item.stock_id).filter(Boolean)) ]; + const storeIdList = [ ...new Set(pageItems.map(item => item.store_id).filter(Boolean)) ]; + const warehouseIdList = [ ...new Set(pageItems.map(item => item.warehouse_id).filter(Boolean)) ]; + + // 复用 getStockDetails 获取商品名称和条码 + // store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品 + const stockDetailOpts = isStoreMode ? { warehouseId: null } : {}; + const stockMap = new Map(); + const barcodesByStock = new Map(); + if (groupedStockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + groupedStockIds, + stockDetailOpts + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + stockMap.set(sid, { + id: sid, + item_name: detail.item_name, + item_code: detail.item_code, + }); + // 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + const barcodeSet = new Set(); + for (const bc of detail.barcodes) { + const barcode = String(bc.barcode || '').trim(); + if (barcode) { + barcodeSet.add(barcode); + } + } + barcodesByStock.set(sid, barcodeSet); + } + } + } + + const storeRows = storeIdList.length > 0 + ? await ctx.model.Store.findAll({ + where: { + id: storeIdList, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : []; + + const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); + + const warehouseRows = warehouseIdList.length > 0 + ? await ctx.model.Store.findAll({ + where: { + id: warehouseIdList, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : []; + + const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ])); + + const list = pageItems + .map(item => { + const stock = stockMap.get(item.stock_id) || {}; + const store = storeMap.get(item.store_id) || {}; + const warehouse = warehouseMap.get(item.warehouse_id) || {}; + const barcodeSet = barcodesByStock.get(item.stock_id); + + return { + ...item, + store_name: store.company_name || '', + warehouse_name: warehouse.company_name || '', + item_name: stock.item_name || item.item_name || '', + item_code: stock.item_code || item.item_code || '', + barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', + }; + }); + + return { + code: 200, + message: '查询成功', + data: { list, pagination: pageResult.meta }, + }; + } + + const baseEntryByKey = new Map(); + for (const row of baseStorageRows) { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + const whId = Number(row.warehouse_id) || 0; + if (!stockId || !storeId) { + continue; + } + + const baseKey = `${stockId}_${spaceId}_${storeId}`; + baseEntryByKey.set(baseKey, { + stock_id: stockId, + space_id: spaceId, + store_id: storeId, + warehouse_id: whId, + quantity: toNumber(row.quantity), + item_code: row.item_code || '', + item_name: row.item_name || '', + }); + } + + for (const row of safeRangeRows) { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + const whId = Number(row.warehouse_id) || 0; + if (!stockId || !storeId) { + continue; + } + + const baseKey = `${stockId}_${spaceId}_${storeId}`; + if (!baseEntryByKey.has(baseKey)) { + baseEntryByKey.set(baseKey, { + stock_id: stockId, + space_id: spaceId, + store_id: storeId, + warehouse_id: whId, + quantity: 0, + item_code: '', + item_name: '', + }); + } + } + + const baseEntries = [ ...baseEntryByKey.values() ]; + if (baseEntries.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [], pagination: paginateList([], pagination).meta }, + }; + } + + const edgeByBaseKey = buildIntervalEdgeMap(intervalEdgeRows, row => { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + return null; + } + return `${stockId}_${spaceId}_${storeId}`; + }); + const preStartAfterByBaseKey = buildPreStartAfterMap(preStartSnapshotRows, row => { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + return null; + } + return `${stockId}_${spaceId}_${storeId}`; + }); + + const rangeByBaseKey = new Map(); + for (const row of safeRangeRows) { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + continue; + } + const baseKey = `${stockId}_${spaceId}_${storeId}`; + rangeByBaseKey.set(baseKey, { + inbound_total: toNumber(row.inbound_total), + outbound_total: toNumber(row.outbound_total), + }); + } + + const groupedMap = new Map(); + for (const row of baseEntries) { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + const whId = Number(row.warehouse_id) || 0; + const baseKey = `${stockId}_${spaceId}_${storeId}`; + const snapshot = edgeByBaseKey.get(baseKey) || { + begin_total: 0, + end_total: 0, + has_snapshot: false, + }; + const preStartAfter = preStartAfterByBaseKey.get(baseKey); + const hasPreStartSnapshot = preStartAfterByBaseKey.has(baseKey); + const rangeSum = rangeByBaseKey.get(baseKey) || { + inbound_total: 0, + outbound_total: 0, + }; + + const targetKey = baseKey; + + if (!groupedMap.has(targetKey)) { + groupedMap.set(targetKey, { + start_time: startTime || null, + end_time: endTime || null, + stock_id: stockId, + store_id: storeId, + warehouse_id: whId, + ...(isBySpace ? { space_id: spaceId } : {}), + begin_total: 0, + end_total: 0, + inbound_total: 0, + outbound_total: 0, + store_name: '', + warehouse_name: '', + // item_code/item_name 取库存快照查询结果,供按 item_code/item_name 排序使用 + item_name: row.item_name || '', + barcode: '', + item_code: row.item_code || '', + space_name: '', + }); + } + + const current = groupedMap.get(targetKey); + const beginTotal = hasPreStartSnapshot + ? toNumber(preStartAfter) + : snapshot.has_snapshot + ? toNumber(snapshot.begin_total) + : 0; + // 区间内无流水时,期末回退到期初,保证“期末 = 期初 + 入库 - 出库”恒等 + const endTotal = snapshot.has_snapshot ? toNumber(snapshot.end_total) : beginTotal; + current.begin_total += beginTotal; + current.end_total += endTotal; + current.inbound_total += toNumber(rangeSum.inbound_total); + current.outbound_total += toNumber(rangeSum.outbound_total); + } + + const groupedList = [ ...groupedMap.values() ]; + + // 先按最终规则排序,再做分页切片:仅对当前页行填充名称信息,避免全量 SKU 详情查询 + sortReportList(groupedList, isBySpace, sort); + const pageResult = paginateList(groupedList, pagination); + const pageItems = pageResult.items; + + const groupedStockIds = [ ...new Set(pageItems.map(item => item.stock_id).filter(Boolean)) ]; + const storeIdList = [ ...new Set(pageItems.map(item => item.store_id).filter(Boolean)) ]; + const warehouseIdList = [ ...new Set(pageItems.map(item => item.warehouse_id).filter(Boolean)) ]; + const spaceIds = isBySpace + ? [ ...new Set(pageItems.map(item => item.space_id).filter(id => Number(id) > 0)) ] + : []; + + // 复用 getStockDetails 获取商品名称和条码 + // store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品 + const stockDetailOptsSpace = isStoreMode ? { warehouseId: null } : {}; + const stockMap = new Map(); + const barcodesByStock = new Map(); + if (groupedStockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + groupedStockIds, + stockDetailOptsSpace + ); + for (const detail of stockDetails) { + const sid = Number(detail.id); + stockMap.set(sid, { + id: sid, + item_name: detail.item_name, + item_code: detail.item_code, + }); + // 提取条码 + if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { + const barcodeSet = new Set(); + for (const bc of detail.barcodes) { + const barcode = String(bc.barcode || '').trim(); + if (barcode) { + barcodeSet.add(barcode); + } + } + barcodesByStock.set(sid, barcodeSet); + } + } + } + + const [ storeRows, spaceRows, warehouseRows ] = await Promise.all([ + storeIdList.length > 0 + ? ctx.model.Store.findAll({ + where: { + id: storeIdList, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], + isBySpace && spaceIds.length > 0 + ? ctx.model.LocationSpace.findAll({ + where: { + id: spaceIds, + }, + attributes: [ 'id', 'custom_name', 'space_code' ], + raw: true, + }) + : [], + warehouseIdList.length > 0 + ? ctx.model.Store.findAll({ + where: { + id: warehouseIdList, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], + ]); + + const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); + const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ])); + const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ])); + + const list = pageItems + .map(item => { + const stock = stockMap.get(item.stock_id) || {}; + const store = storeMap.get(item.store_id) || {}; + const warehouse = warehouseMap.get(item.warehouse_id) || {}; + const barcodeSet = barcodesByStock.get(item.stock_id); + const space = isBySpace ? (spaceMap.get(Number(item.space_id)) || {}) : null; + + const merged = { + ...item, + store_name: store.company_name || '', + warehouse_name: warehouse.company_name || '', + item_name: stock.item_name || item.item_name || '', + item_code: stock.item_code || item.item_code || '', + barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', + }; + + if (isBySpace) { + merged.space_name = space.custom_name || space.space_code || ''; + } + + return merged; + }); + + return { + code: 200, + message: '查询成功', + data: { list, pagination: pageResult.meta }, + }; + } +} + +module.exports = StorageReportService; diff --git a/app/service/systems/storage/stock_warehouse.js b/app/service/systems/storage/stock_warehouse.js new file mode 100644 index 0000000..64ff1fb --- /dev/null +++ b/app/service/systems/storage/stock_warehouse.js @@ -0,0 +1,213 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 仓库商品详情缓存的 key 前缀模板。 + * 最终 key 格式:cache:stock_detail:{warehouseId}:{stockId} + */ +const STOCK_DETAIL_CACHE_KEY_PREFIX = 'cache:stock_detail'; +/** 仓库商品详情缓存默认 TTL(秒) */ +const DEFAULT_STOCK_DETAIL_CACHE_TTL = 300; + +class StockWarehouseService extends Service { + /** + * 构建仓库商品详情缓存的 Redis key。 + * @param {number} warehouseId 仓库ID + * @param {number} stockId 仓库商品ID + * @return {string} 缓存 key + */ + _buildStockDetailCacheKey(warehouseId, stockId) { + return `${STOCK_DETAIL_CACHE_KEY_PREFIX}:${warehouseId}:${stockId}`; + } + + /** + * 批量获取仓库商品详情(带缓存)。 + * 先按 stockId 逐个查缓存,未命中的批量查数据库, + * 然后将数据库结果写入缓存后合并返回。 + * 作为通用公共服务,所有模块均可调用。 + * + * @param {number[]} stockIds 要查询的 StockWarehouse ID 列表 + * @param {Object} [options={}] 选项 + * @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id) + * @param {number} [options.cacheTTL=300] 缓存过期时间(秒) + * @return {Promise}>>} 商品详情列表 + */ + async getStockDetails(stockIds, options = {}) { + const { ctx, app } = this; + const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options; + const warehouseId = options.warehouseId != null ? options.warehouseId : ctx.user.store_id; + + if (!Array.isArray(stockIds) || stockIds.length === 0) { + return []; + } + + const uniqueStockIds = [ ...new Set(stockIds.map(id => Number(id))) ]; + const cacheHits = new Map(); + const missedStockIds = []; + + // 第一步:逐个查缓存 + for (const stockId of uniqueStockIds) { + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + const cached = await app.getCacheAsync(cacheKey); + if (cached !== null && cached !== undefined) { + cacheHits.set(stockId, cached); + } else { + missedStockIds.push(stockId); + } + } catch { + // 缓存读取异常时降级为查数据库 + missedStockIds.push(stockId); + } + } + + // 第二步:批量查数据库(只查未命中的 stockId) + /** @type {Map} */ + const dbResults = new Map(); + if (missedStockIds.length > 0) { + const stockWhere = { id: { [app.Sequelize.Op.in]: missedStockIds }, is_valid: 'Y' }; + if (warehouseId != null) { + stockWhere.warehouse_id = warehouseId; + } + + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: stockWhere, + attributes: [ + 'id', 'item_code', 'item_name', 'sku_property', + 'quantity', 'locked_quantity', 'is_batch_mgmt', + 'is_shelf_life_mgmt', 'image_url', 'is_images', + 'need_recheck', + 'store_id', 'packing_requirements', 'pick_requirements', + 'recheck_requirements', 'merge_requirements', 'stock_unit', + ], + raw: true, + }); + + // 批量查询所有未命中 stockId 的条码 + const barcodeRows = await ctx.model.StockBarcode.findAll({ + where: { stock_id: { [app.Sequelize.Op.in]: missedStockIds } }, + attributes: [ 'id', 'barcode', 'sku_property', 'stock_id' ], + raw: true, + }); + + // 按 stock_id 分组条码 + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const sid = row.stock_id; + if (!barcodeMap.has(sid)) { + barcodeMap.set(sid, []); + } + barcodeMap.get(sid).push({ + id: row.id, + barcode: row.barcode, + sku_property: row.sku_property, + }); + } + + // 组装每个 stock 的完整详情 + for (const row of stockRows) { + const detail = { + id: row.id, + item_code: row.item_code, + item_name: row.item_name, + sku_property: row.sku_property || '', + quantity: row.quantity || 0, + locked_quantity: row.locked_quantity || 0, + is_batch_mgmt: row.is_batch_mgmt || 'N', + is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N', + image_url: row.image_url || '', + is_images: row.is_images || 'N', + need_recheck: row.need_recheck || 'Y', + store_id: row.store_id != null ? Number(row.store_id) : 0, + packing_requirements: row.packing_requirements || '', + pick_requirements: (row.merge_requirements || 'Y') === 'Y' + ? (row.packing_requirements || '') + : (row.pick_requirements || ''), + recheck_requirements: (row.merge_requirements || 'Y') === 'Y' + ? (row.packing_requirements || '') + : (row.recheck_requirements || ''), + merge_requirements: row.merge_requirements || 'Y', + stock_unit: row.stock_unit || '', + barcodes: barcodeMap.get(row.id) || [], + }; + dbResults.set(row.id, detail); + + // 第三步:写入缓存 + const cacheKey = this._buildStockDetailCacheKey(warehouseId, row.id); + try { + await app.setCacheAsync(cacheKey, detail, cacheTTL); + } catch { + // 缓存写入失败不影响主流程 + } + } + + // 对于数据库中也不存在的 stockId,写入空标记防止缓存穿透 + for (const stockId of missedStockIds) { + if (!dbResults.has(stockId)) { + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + // 用较短的 TTL 缓存空结果,避免缓存穿透 + await app.setCacheAsync(cacheKey, null, Math.min(cacheTTL, 60)); + } catch { + // 忽略缓存写入失败 + } + } + } + } + + // 第四步:合并缓存命中 + 数据库结果,保持原始 stockIds 顺序 + const result = []; + for (const stockId of uniqueStockIds) { + if (cacheHits.has(stockId)) { + const cached = cacheHits.get(stockId); + // 空标记(防穿透缓存)跳过 + if (cached !== null && cached !== undefined) { + // 兼容旧缓存:无 need_recheck 时补默认(需要复核) + if (cached.need_recheck == null) { + cached.need_recheck = 'Y'; + } + // 兼容旧缓存:无要求合并开关时按默认合并处理;无拣货/复核要求时按合并规则回退为打包要求 + if (cached.merge_requirements == null) { + cached.merge_requirements = 'Y'; + } + if (cached.pick_requirements == null) { + cached.pick_requirements = (cached.merge_requirements || 'Y') === 'Y' + ? (cached.packing_requirements || '') + : ''; + } + if (cached.recheck_requirements == null) { + cached.recheck_requirements = (cached.merge_requirements || 'Y') === 'Y' + ? (cached.packing_requirements || '') + : ''; + } + result.push(cached); + } + } else if (dbResults.has(stockId)) { + result.push(dbResults.get(stockId)); + } + } + + return result; + } + + /** + * 使指定仓库商品的详情缓存失效。 + * 在商品资料更新、图片变更、条码变更时调用。 + * + * @param {number} stockId 仓库商品ID + * @param {number} warehouseId 仓库ID + * @return {Promise} + */ + async invalidateStockDetailCache(stockId, warehouseId) { + const { app } = this; + const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); + try { + await app.delCacheAsync(cacheKey); + } catch { + // 删除缓存失败不影响主流程 + } + } +} + +module.exports = StockWarehouseService; diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 5fa210a..f093303 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -2,14 +2,103 @@ const Service = require('egg').Service; class StoreService extends Service { + normalizeSubjectConfigInput(data = {}) { + const rawSubjectConfig = data.subject_config !== undefined ? data.subject_config : data.subjectConfig; + if (this.app.model.Store && typeof this.app.model.Store.normalizeSubjectConfig === 'function') { + return this.app.model.Store.normalizeSubjectConfig(rawSubjectConfig); + } + + return { + max_notice_webhook_count: 5, + default_express_code: 'STO', + default_platform_code: 'TB', + }; + } + + validateStoreData(data = {}) { + const errors = []; + + const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ]; + for (const field of requiredFields) { + if (!data[field]) { + errors.push(`${field} 不能为空`); + } + } + + if (data.company_name && (data.company_name.length < 1 || data.company_name.length > 200)) { + errors.push('公司名称长度应在1-200个字符之间'); + } + + if (data.contact_email && data.contact_email.trim() !== '') { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(data.contact_email)) { + errors.push('联系邮箱格式不正确'); + } + } + + if (data.subject_config !== undefined || data.subjectConfig !== undefined) { + try { + this.normalizeSubjectConfigInput(data); + } catch (error) { + errors.push(error.message); + } + } + + return errors; + } + + async checkCompanyNameExists(companyName, excludeId = null) { + const where = { + company_name: companyName, + }; + + if (excludeId) { + where.id = { + [this.app.Sequelize.Op.ne]: excludeId, + }; + } + + const store = await this.app.model.Store.findOne({ where }); + return !!store; + } + + async findByAccountId(accountId) { + return await this.app.model.Store.findOne({ + where: { + account_id: accountId, + status: 1, + }, + }); + } + + async findAllEnabled() { + return await this.app.model.Store.findAll({ + where: { + status: 1, + }, + order: [[ 'company_name', 'ASC' ]], + }); + } + + async findAllWarehouses() { + return await this.app.model.Store.findAll({ + where: { + status: 1, + project: 'warehouse', + }, + order: [[ 'company_name', 'ASC' ]], + }); + } + /** - * 根据ID获取商家信息 - * @param storeId - */ + * 根据ID获取商家信息。 + * @param {number|string} storeId 商家ID + * @return {Promise} 查询结果 + */ async getStoreName(storeId) { try { const store = await this.app.model.Store.findByPk(storeId, { - attributes: [ 'id', 'company_name', 'status', 'is_warehouse' ], + attributes: [ 'id', 'company_name', 'status' ], }); if (!store) { @@ -36,10 +125,11 @@ class StoreService extends Service { } /** - * 获取商家仓库备注名 - * @param storeId - * @param warehouseId - */ + * 获取商家仓库备注名。 + * @param {number|string} storeId 商家ID + * @param {number|string} warehouseId 仓库ID + * @return {Promise} 查询结果 + */ async getStoreRemaskName(storeId, warehouseId) { try { const relation = await this.app.model.StoreWarehouse.findOne({ @@ -73,9 +163,10 @@ class StoreService extends Service { } /** - * 创建商家(不需要审核) - * @param data - */ + * 创建商家(不需要审核)。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async createStore(data) { const { ctx, @@ -120,6 +211,18 @@ class StoreService extends Service { }; } + let subjectConfig = null; + try { + subjectConfig = this.normalizeSubjectConfigInput(data); + } catch (error) { + await transaction.rollback(); + return { + code: 400, + message: error.message, + data: null, + }; + } + // 创建商家 const storeData = { company_name: data.company_name, @@ -134,10 +237,9 @@ class StoreService extends Service { status: 1, // 直接启用 created_by: userId, is_warehouse: 0, // 默认不是仓库 - logo_url: data.logo_url, - domain: data.domain, auth_start: data.auth_start, auth_end: data.auth_end, + subject_config: subjectConfig, }; const store = await ctx.model.Store.create(storeData, { @@ -146,9 +248,25 @@ class StoreService extends Service { // 为创建者自动分配商家管理员角色 const role_id = await this.assignAdminRoleToCreator(store.id, userId, data.contact_person, transaction); - console.log(role_id); await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: store.id, + operationCode: 'STORE_CREATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: {}, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[store.createStore] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '商家创建成功', @@ -180,9 +298,10 @@ class StoreService extends Service { } /** - * 创建仓库(需要审核) - * @param data - */ + * 创建仓库(需要审核)。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async createWarehouse(data) { const { ctx, @@ -227,6 +346,18 @@ class StoreService extends Service { }; } + let subjectConfig = null; + try { + subjectConfig = this.normalizeSubjectConfigInput(data); + } catch (error) { + await transaction.rollback(); + return { + code: 400, + message: error.message, + data: null, + }; + } + // 创建仓库(也是商家,但 is_warehouse = 1) const warehouseData = { company_name: data.company_name, @@ -241,10 +372,9 @@ class StoreService extends Service { status: 1, // 直接通过 created_by: userId, is_warehouse: 1, // 标记为仓库 - logo_url: data.logo_url, - domain: data.domain, auth_start: new Date(), // 设置当前时间为授权开始时间 auth_end: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 默认授权7天试用 + subject_config: subjectConfig, }; const warehouse = await ctx.model.Store.create(warehouseData, { @@ -254,6 +384,24 @@ class StoreService extends Service { const role_id = await this.assignAdminRoleToCreator(warehouse.id, userId, data.contact_person, transaction, false); await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: warehouse.id, + operationCode: 'STORE_CREATE_WAREHOUSE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: {}, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[store.createWarehouse] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '仓库创建申请已提交,等待审核', @@ -285,9 +433,10 @@ class StoreService extends Service { } /** - * 加入商家 - * @param data - */ + * 加入商家。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async joinStore(data) { const { ctx, @@ -296,7 +445,6 @@ class StoreService extends Service { try { const userId = ctx.userId || (ctx.user && ctx.user.id); - console.log('申请参数', data); // 验证必填字段 if (!data.employees_name) { return { @@ -315,7 +463,6 @@ class StoreService extends Service { transaction, }); - // 生成加入链接(用于分享给管理员) const joinToken = this.generateJoinToken(userId, data.store_id); @@ -335,7 +482,6 @@ class StoreService extends Service { transaction, }); - await transaction.commit(); return { @@ -349,7 +495,6 @@ class StoreService extends Service { } catch (error) { await transaction.rollback(); - console.log('error', error); return { code: 500, message: '创建申请链接失败', @@ -359,9 +504,10 @@ class StoreService extends Service { } /** - * 加入仓库 - * @param data - */ + * 加入仓库。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async joinWarehouse(data) { const { ctx, @@ -370,7 +516,6 @@ class StoreService extends Service { try { const userId = ctx.userId || (ctx.user && ctx.user.id); - console.log('申请参数', data); // 验证必填字段 if (!data.employees_name) { return { @@ -389,7 +534,6 @@ class StoreService extends Service { transaction, }); - // 生成加入链接(用于分享给管理员) const joinToken = this.generateJoinToken(userId, data.store_id); @@ -409,7 +553,6 @@ class StoreService extends Service { transaction, }); - await transaction.commit(); return { @@ -423,7 +566,6 @@ class StoreService extends Service { } catch (error) { await transaction.rollback(); - console.log('error', error); return { code: 500, message: '创建申请链接失败', @@ -435,13 +577,66 @@ class StoreService extends Service { // ==================== 辅助方法 ==================== /** - * 为创建者分配管理员角色 - * @param storeId - * @param userId - * @param realName - * @param transaction - * @param isStore - */ + * 确保工号与角色已绑定。 + * @param {Object} options 绑定参数 + * @param {number|string} options.accountId 账号ID + * @param {number|string} options.storeId 主体ID + * @param {number|string} options.roleId 角色ID + * @param {string} [options.realName] 真实姓名 + * @param {Object} options.transaction 事务对象 + * @return {Promise} 绑定结果 + */ + async ensureEmployeeRoleBinding({ accountId, storeId, roleId, realName = '', transaction }) { + const { ctx } = this; + + const [ employee ] = await ctx.model.AccountStoreEmployee.findOrCreate({ + where: { + account_id: accountId, + store_id: storeId, + }, + defaults: { + account_id: accountId, + store_id: storeId, + status: 1, + real_name: realName || '', + }, + transaction, + }); + + const shouldRefreshEmployee = Number(employee.status) !== 1 + || (realName && employee.real_name !== realName); + + if (shouldRefreshEmployee) { + await employee.update({ + status: 1, + real_name: realName || employee.real_name || '', + }, { transaction }); + } + + const [ employeeRole ] = await ctx.model.EmployeeRole.findOrCreate({ + where: { + employee_id: employee.id, + role_id: roleId, + }, + defaults: { + employee_id: employee.id, + role_id: roleId, + }, + transaction, + }); + + return { employee, employeeRole }; + } + + /** + * 为创建者分配管理员角色。 + * @param {number|string} storeId 主体ID + * @param {number|string} userId 账号ID + * @param {string} realName 真实姓名 + * @param {Object} transaction 事务对象 + * @param {boolean} [isStore=true] 是否为商家主体 + * @return {Promise} 工号实例 + */ async assignAdminRoleToCreator(storeId, userId, realName, transaction, isStore = true) { const { ctx, @@ -451,7 +646,7 @@ class StoreService extends Service { const role_code = isStore ? 'store_admin_default' : 'warehouse_admin_default'; const adminRole = await ctx.model.Role.findOne({ where: { - store_id: 0, + store_id: null, role_code, }, }); @@ -460,27 +655,24 @@ class StoreService extends Service { throw new Error(`未初始化${role_code}管理员角色`); } - // 分配角色给创建者 - const storerole = await ctx.model.AccountStoreRole.create({ - account_id: userId, - store_id: storeId, - role_id: adminRole.id, - status: 1, - real_name: realName || '', - assigned_by: userId, - }, { + const { employee } = await this.ensureEmployeeRoleBinding({ + accountId: userId, + storeId, + roleId: adminRole.id, + realName: realName || '', transaction, }); - return storerole; + + return employee; } - /** - * 生成加入令牌 - * @param userId - * @param storeId - * @param type - */ + * 生成加入令牌。 + * @param {number|string} userId 账号ID + * @param {number|string} storeId 主体ID + * @param {string} [type='store'] 令牌类型 + * @return {string} 加入令牌 + */ generateJoinToken(userId, storeId, type = 'store') { const crypto = require('crypto'); const timestamp = Date.now(); @@ -492,9 +684,10 @@ class StoreService extends Service { } /** - * 发送通知 - * @param notificationData - */ + * 发送通知。 + * @param {Object} notificationData 通知数据 + * @return {Promise} + */ async sendNotification(notificationData) { const { ctx, @@ -512,9 +705,10 @@ class StoreService extends Service { } /** - * 发送通知给系统管理员 - * @param notificationData - */ + * 发送通知给系统管理员。 + * @param {Object} notificationData 通知数据 + * @return {Promise} + */ async sendNotificationToAdmins(notificationData) { const { ctx, @@ -545,8 +739,6 @@ class StoreService extends Service { ctx, } = this; try { - console.log('ctx', ctx.user.store_id); - const userId = ctx.user.id; const storeId = ctx.user.store_id; // 验证必填字段 if (!data.code) { @@ -557,7 +749,6 @@ class StoreService extends Service { }; } const code = data.code; - console.log('申请参数', userId, storeId, code); const applyData = await ctx.model.StoreJoin.findOne({ where: { join_token: code, @@ -590,7 +781,6 @@ class StoreService extends Service { }, }; } catch (error) { - console.log('error', error); return { code: 500, message: '请求失败', @@ -614,7 +804,7 @@ class StoreService extends Service { } // 2. 验证store_id - if (ctx.user.store_id != data.store_id) { + if (ctx.user.store_id !== data.store_id) { await transaction.rollback(); return { code: 400, @@ -626,8 +816,6 @@ class StoreService extends Service { const { code, audit_status, role_ids } = data; const store_id = ctx.user.store_id; - console.log('申请参数', data); - // 3. 查找申请记录 const applyData = await ctx.model.StoreJoin.findOne({ where: { @@ -675,27 +863,13 @@ class StoreService extends Service { const { account_id, real_name } = applyData; for (const role of roles) { - // 检查是否已存在该角色分配 - const existingRole = await ctx.model.AccountStoreRole.findOne({ - where: { - account_id, - store_id, - role_id: role.id, - status: 1, - }, + await this.ensureEmployeeRoleBinding({ + accountId: account_id, + storeId: store_id, + roleId: role.id, + realName: real_name || '', transaction, }); - - if (!existingRole) { - await ctx.model.AccountStoreRole.create({ - account_id, - store_id, - role_id: role.id, - status: 1, - real_name, - join_token: code, - }, { transaction }); - } } // 更新申请记录状态 @@ -746,7 +920,6 @@ class StoreService extends Service { data: null, }; - } catch (error) { await transaction.rollback(); console.error('审核申请出错:', error); @@ -768,27 +941,132 @@ class StoreService extends Service { } } async loadStores() { - const { app, ctx } = this; + const { ctx } = this; try { - const stores = await ctx.model.StoreWarehouse.findAll({ + const rows = await ctx.model.StoreWarehouse.findAll({ where: { - use_status: 1, + warehouse_use_status: 1, warehouse_id: ctx.user.store_id, }, - attributes: [ - [ 'store_id', 'value' ], // store_id 字段别名为 value - [ 'store_remask', 'label' ], // store_remask 字段别名为 label + attributes: [ 'store_id', 'store_remask' ], + include: [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'company_name' ], + required: false, + }, ], - raw: true, // 可选:返回纯JSON数据 + raw: true, }); - return stores; + return rows.map(row => ({ + value: row.store_id, + label: row.store_remask || (row['store.company_name'] || ''), + })); } catch (error) { ctx.logger.error('[Service.loadStores] 查询失败:', error); throw error; } } + async loadWarehouses() { + const { ctx } = this; + + try { + const rows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_use_status: 1, + store_id: ctx.user.store_id, + }, + attributes: [ 'warehouse_id', 'warehouse_remask' ], + include: [ + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'company_name' ], + required: false, + }, + ], + raw: true, + }); + + return rows.map(row => ({ + value: row.warehouse_id, + label: row.warehouse_remask || (row['warehouse.company_name'] || ''), + })); + } catch (error) { + ctx.logger.error('[Service.loadWarehouses] 查询失败:', error); + throw error; + } + } + + /** + * 生成货主绑群码。 + * 查询货主与仓库的有效合约,生成 12 位随机码并存入缓存(5分钟有效)。 + * + * @param {Object} data 请求数据。 + * @param {number} data.storeId 货主ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 systemMethods 层注入)。 + * @param {string} [data.subType] 群子类型:after_sales / finance / receiving。 + * @return {Promise} { code: 绑群码 }。 + */ + async bindCode(data = {}) { + const { ctx } = this; + const storeId = Number(data.storeId); + const warehouseId = Number(data.warehouseId); + + if (!Number.isFinite(storeId) || storeId <= 0) { + throw new Error('storeId 无效'); + } + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('缺少仓库信息,请确认已登录并选择了仓库'); + } + + const contract = await ctx.model.StoreWarehouse.findOne({ + attributes: [ 'id', 'store_id', 'warehouse_id', 'initiator_subject_id' ], + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + raw: true, + }); + + if (!contract) { + throw new Error(`货主 ${storeId} 在仓库 ${warehouseId} 无有效合约`); + } + + const subType = String(data.subType || '').trim(); + const VALID_SUB_TYPES = [ 'after_sales', 'finance', 'receiving' ]; + if (subType && !VALID_SUB_TYPES.includes(subType)) { + throw new Error(`无效的子类型: ${subType},可选值: ${VALID_SUB_TYPES.join(' / ')}`); + } + + const code = Math.random().toString(36).slice(2, 8) + .toUpperCase() + + Math.random().toString(36).slice(2, 8) + .toUpperCase(); + const cacheKey = `chat:bind:${warehouseId}:${code}`; + + const cacheValue = { + store_id: contract.store_id, + initiator_subject_id: contract.initiator_subject_id || null, + warehouse_id: contract.warehouse_id, + group_type: 'store', + sub_type: subType || null, + }; + + await ctx.app.setCacheAsync(cacheKey, cacheValue, 300); + + ctx.logger.info( + `[store bindCode] 生成绑群码 code=${code} ` + + `store_id=${contract.store_id} warehouse_id=${warehouseId}` + ); + + return { code }; + } } module.exports = StoreService; diff --git a/app/service/systems/store_express_binding_policy.js b/app/service/systems/store_express_binding_policy.js new file mode 100644 index 0000000..c6f1732 --- /dev/null +++ b/app/service/systems/store_express_binding_policy.js @@ -0,0 +1,698 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 订单自定义店铺-快递绑定策略业务服务。 + */ +class StoreExpressBindingPolicyService extends Service { + /** + * 获取当前仓库 ID。 + * @return {number} 仓库 ID + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createError('未识别到当前仓库', 400); + } + return warehouseId; + } + + /** + * 创建业务错误。 + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 规范化字符串参数。 + * @param {*} value 原始值 + * @param {string} fieldName 字段名 + * @param {Object} [options={}] 选项 + * @return {string|null} 规范化结果 + */ + normalizeText(value, fieldName, options = {}) { + const { required = false, maxLength = 255 } = options; + if (value === undefined || value === null) { + if (required) throw this.createError(`${fieldName} 不能为空`, 400); + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + if (required) throw this.createError(`${fieldName} 不能为空`, 400); + return null; + } + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + /** + * 规范化整数参数。 + * @param {*} value 原始值 + * @param {string} fieldName 字段名 + * @param {Object} [options={}] 选项 + * @return {number|null} 规范化结果 + */ + normalizeInteger(value, fieldName, options = {}) { + const { required = false, min = null } = options; + if (value === undefined || value === null || value === '') { + if (required) throw this.createError(`${fieldName} 不能为空`, 400); + return null; + } + const normalized = Number(value); + if (!Number.isInteger(normalized)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (min !== null && normalized < min) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return normalized; + } + + /** + * 规范化重量段类型。 + * @param {*} value 原始值 + * @return {number|null} NULL 或 0/1/2/3 + */ + normalizeWeightType(value) { + if (value === undefined || value === null || value === '') return 0; + const v = Number(value); + if (![ 0, 1, 2, 3 ].includes(v)) throw this.createError('weight_type 不合法,仅支持 0/1/2/3(常规/轻货/重货/冷链)', 400); + return v; + } + + /** + * 校验快递编码是否存在。 + * @param {string} expressCode 快递编码 + * @param value + * @param fieldName + * @return {Promise} 标准化快递编码 + */ + normalizeJsonArray(value, fieldName) { + if (value === undefined || value === null || value === '') return null; + if (Array.isArray(value)) return value.length > 0 ? value : null; + if (typeof value === 'string') { + try { const parsed = JSON.parse(value); if (Array.isArray(parsed)) return parsed.length > 0 ? parsed : null; } catch (e) {} + } + throw this.createError(fieldName + ' 必须是字符串数组', 400); + } + + async ensureExpressExists(expressCode) { + const { ctx } = this; + const normalizedCode = this.normalizeText(expressCode, 'express_code', { + required: true, + maxLength: 50, + }); + + // 使用合并后的快递列表(含系统快递 + 仓库自定义映射) + const expressList = await ctx.service.systems.express.getExpressList(); + const found = Array.isArray(expressList) + ? expressList.find(item => item && String(item.code || item.value || '').trim() === normalizedCode) + : null; + + if (!found) { + throw this.createError(`快递编码 "${normalizedCode}" 不存在`, 400); + } + + return normalizedCode; + } + + /** + * 获取列表字段过滤映射。 + * @return {Object} specialFieldMap + */ + getListWhereSpecialFieldMap() { + return { + id: { field: 'id' }, + custom_name: { field: 'custom_name' }, + shop_name: { field: 'shop_name' }, + store_ids: { field: 'store_ids' }, + express_code: { field: 'express_code' }, + priority: { field: 'priority' }, + is_enabled: { field: 'is_enabled' }, + prohibited_type_id: { field: 'prohibited_type_id' }, + regions: { field: 'regions' }, + exclude_regions: { field: 'exclude_regions' }, + min_weight_g: { field: 'min_weight_g' }, + max_weight_g: { field: 'max_weight_g' }, + weight_type: { field: 'weight_type' }, + creator_id: { field: 'creator_id' }, + quickWhere: { bucket: 'quick' }, + }; + } + + /** + * 构建列表查询条件。 + * @param {Object} [data={}] 请求参数 + * @return {Object} where 条件 + */ + buildListWhere(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const parsedResult = ctx.whereParsed || { + dynamicConditions: [], + rawConditionsByField: {}, + }; + const whereAndConditions = [ + { warehouse_id: this.getCurrentWarehouseId() }, + { deleted_at: null }, + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) + ? parsedResult.dynamicConditions + : []; + + if (dynamicConditions.length > 0) { + whereAndConditions.push({ [Op.and]: dynamicConditions }); + } + + // 快速搜索:按 custom_name 模糊匹配 + const quickWhereCondition = parsedResult.rawConditionsByField + ? parsedResult.rawConditionsByField.quickWhere + : null; + const quickWhereValue = quickWhereCondition && typeof quickWhereCondition === 'object' + ? quickWhereCondition.value + : null; + const keyword = String(quickWhereValue || '').trim(); + + if (keyword) { + whereAndConditions.push({ + [Op.or]: [ + { custom_name: { [Op.like]: `%${keyword}%` } }, + { express_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + return { [Op.and]: whereAndConditions }; + } + + /** + * 规范化分页参数。 + * @param {Object} [data={}] 请求参数 + * @return {{ page: number, pageSize: number, offset: number }} + */ + normalizePagination(data = {}) { + const pagination = data && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined + ? pagination.page + : (data.page !== undefined ? data.page : data.currentPage); + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.pageSize !== undefined ? data.pageSize : data.page_size)); + + const page = Math.max(Number.parseInt(pageSource, 10) || 1, 1); + const pageSize = Math.min(Math.max(Number.parseInt(pageSizeSource, 10) || 20, 1), 200); + + return { page, pageSize, offset: (page - 1) * pageSize }; + } + + /** + * 规范化策略记录输出。 + * @param {Object} row 策略记录 + * @return {Object} 输出结构 + */ + formatPolicyRow(row) { + return { + id: row.id, + warehouse_id: row.warehouse_id, + custom_name: row.custom_name, + shop_name: row.shop_name, + store_ids: row.store_ids, + store_names: row._store_names || null, + express_code: row.express_code, + express_name: row._express_name || row.express_code || null, + priority: row.priority, + is_enabled: row.is_enabled, + prohibited_type_id: row.prohibited_type_id, + prohibited_type_names: row._prohibited_type_names || null, + regions: row.regions, + exclude_regions: row.exclude_regions, + min_weight_g: row.min_weight_g, + max_weight_g: row.max_weight_g, + weight_type: row.weight_type, + remark: row.remark, + creator_id: row.creator_id, + created_at: row.created_at, + updated_at: row.updated_at, + }; + } + + /** + * 查询策略分页列表。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { ctx } = this; + const { page, pageSize, offset } = this.normalizePagination(data); + const where = this.buildListWhere(data); + + const result = await ctx.model.StoreExpressBindingPolicy.findAndCountAll({ + where, + order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + }); + + const rows = Array.isArray(result && result.rows) ? result.rows : []; + const plainRows = rows.map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row)); + + // 批量解析货主名称 & 违禁品名称 + const allStoreIds = new Set(); + const allProhibitedIds = new Set(); + for (const row of plainRows) { + if (Array.isArray(row.store_ids)) { + row.store_ids.forEach(id => allStoreIds.add(id)); + } + if (Array.isArray(row.prohibited_type_id)) { + row.prohibited_type_id.forEach(id => allProhibitedIds.add(id)); + } + } + + const storeNameMap = new Map(); + if (allStoreIds.size > 0) { + const stores = await ctx.model.Store.findAll({ + where: { id: [ ...allStoreIds ] }, + attributes: [ 'id', 'company_name' ], + }); + for (const s of stores) { + storeNameMap.set(s.id, s.company_name); + } + } + + const prohibitedNameMap = new Map(); + if (allProhibitedIds.size > 0) { + const types = await ctx.model.ProhibitedType.findAll({ + where: { id: [ ...allProhibitedIds ] }, + attributes: [ 'id', 'type_name' ], + }); + for (const t of types) { + prohibitedNameMap.set(t.id, t.type_name); + } + } + + // 批量解析快递名称(含系统快递 + 自定义映射) + const allExpressCodes = new Set(); + for (const row of plainRows) { + if (row.express_code) allExpressCodes.add(row.express_code); + } + const expressNameMap = new Map(); + if (allExpressCodes.size > 0) { + try { + const expressList = await ctx.service.systems.express.getExpressList(); + for (const item of (Array.isArray(expressList) ? expressList : [])) { + const code = String(item && (item.code || item.value) || '').trim(); + if (code && allExpressCodes.has(code)) { + expressNameMap.set(code, String(item.name || item.label || code).trim()); + } + } + } catch (_) { /* 快递列表查询失败不影响列表 */ } + } + + // 将名称数组挂到临时属性上 + for (const row of plainRows) { + if (Array.isArray(row.store_ids)) { + row._store_names = row.store_ids.map(id => storeNameMap.get(id) || String(id)); + } + if (Array.isArray(row.prohibited_type_id)) { + row._prohibited_type_names = row.prohibited_type_id.map(id => prohibitedNameMap.get(id) || String(id)); + } + if (row.express_code) { + row._express_name = expressNameMap.get(row.express_code) || row.express_code; + } + } + + const list = plainRows.map(row => this.formatPolicyRow(row)); + const total = Number(result && result.count ? result.count : 0); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: pageSize > 0 ? Math.ceil(total / pageSize) : 0, + hasNext: page * pageSize < total, + hasPrevious: page > 1, + }, + }; + } + + /** + * 校验自定义名称在同仓库下唯一(排除自身)。 + * @param {Object} payload 入参 + * @return {Promise} + */ + async ensureCustomNameUnique(payload) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const { warehouseId, customName, excludeId = null } = payload; + + const where = { + warehouse_id: warehouseId, + custom_name: customName, + deleted_at: null, + }; + + if (excludeId !== null) { + where.id = { [Op.ne]: excludeId }; + } + + const existed = await ctx.model.StoreExpressBindingPolicy.findOne({ + where, + attributes: [ 'id' ], + }); + + if (existed) { + throw this.createError('同仓库下策略名称已存在', 409); + } + } + + /** + * 新增策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 新增结果 + */ + async add(data = {}) { + const { ctx } = this; + const warehouseId = this.getCurrentWarehouseId(); + + const customName = this.normalizeText( + data.custom_name !== undefined ? data.custom_name : data.customName, + 'custom_name', + { required: true, maxLength: 100 } + ); + + const expressCode = await this.ensureExpressExists( + data.express_code !== undefined ? data.express_code : data.expressCode + ); + + const priority = this.normalizeInteger( + data.priority !== undefined ? data.priority : 0, + 'priority', + { required: false } + ); + + const isEnabled = data.is_enabled !== undefined + ? Number(data.is_enabled) + : (data.isEnabled !== undefined ? Number(data.isEnabled) : 1); + if (![ 0, 1 ].includes(isEnabled)) { + throw this.createError('is_enabled 参数不合法,仅支持 0 或 1', 400); + } + + const regions = this.normalizeJsonArray( + data.regions !== undefined ? data.regions : null, + 'regions' + ); + + const shopName = this.normalizeJsonArray( + data.shop_name !== undefined ? data.shop_name : data.shopName, + 'shop_name' + ); + + const storeIds = this.normalizeJsonArray( + data.store_ids !== undefined ? data.store_ids : data.storeIds, + 'store_ids' + ); + + const excludeRegions = this.normalizeJsonArray( + data.exclude_regions !== undefined ? data.exclude_regions : data.excludeRegions, + 'exclude_regions' + ); + + const minWeightG = this.normalizeInteger( + data.min_weight_g !== undefined ? data.min_weight_g : data.minWeightG, + 'min_weight_g' + ); + + const maxWeightG = this.normalizeInteger( + data.max_weight_g !== undefined ? data.max_weight_g : data.maxWeightG, + 'max_weight_g' + ); + + const weightType = this.normalizeWeightType( + data.weight_type !== undefined ? data.weight_type : data.weightType + ); + + const prohibitedTypeIds = this.normalizeJsonArray( + data.prohibited_type_id !== undefined ? data.prohibited_type_id : data.prohibitedTypeId, + 'prohibited_type_id' + ); + + const remark = this.normalizeText( + data.remark !== undefined ? data.remark : null, + 'remark', + { maxLength: 500 } + ); + + const creatorId = this.normalizeInteger( + data.creator_id !== undefined ? data.creator_id : data.creatorId, + 'creator_id' + ); + + // 校验名称唯一性 + await this.ensureCustomNameUnique({ warehouseId, customName }); + + const created = await ctx.model.StoreExpressBindingPolicy.create({ + warehouse_id: warehouseId, + custom_name: customName, + express_code: expressCode, + priority: priority ?? 0, + is_enabled: isEnabled, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeIds, + remark, + creator_id: creatorId, + }); + + // 清理当前仓库策略缓存 + try { + await ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId); + } catch (_) { + // 缓存清理失败不影响主流程 + } + + const plainRow = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + + return { id: plainRow.id }; + } + + /** + * 读取策略并校验仓库归属。 + * @param {*} policyId 策略 ID + * @return {Promise} 策略模型实例 + */ + async findPolicyById(policyId) { + const { ctx } = this; + const id = this.normalizeInteger(policyId, 'id', { required: true, min: 1 }); + + const policy = await ctx.model.StoreExpressBindingPolicy.findOne({ + where: { + id, + warehouse_id: this.getCurrentWarehouseId(), + deleted_at: null, + }, + }); + + if (!policy) { + throw this.createError('策略不存在', 404); + } + + return policy; + } + + /** + * 编辑策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 编辑结果 + */ + async edit(data = {}) { + const id = data.id !== undefined ? data.id : data.policy_id; + + const policy = await this.findPolicyById(id); + const warehouseId = this.getCurrentWarehouseId(); + const updateFields = {}; + + // custom_name + const customName = data.custom_name !== undefined + ? data.custom_name + : (data.customName !== undefined ? data.customName : undefined); + if (customName !== undefined) { + const normalized = this.normalizeText(customName, 'custom_name', { maxLength: 100 }); + if (normalized && normalized !== policy.custom_name) { + await this.ensureCustomNameUnique({ + warehouseId, + customName: normalized, + excludeId: Number(policy.id), + }); + } + updateFields.custom_name = normalized; + } + + // express_code + const expressCode = data.express_code !== undefined + ? data.express_code + : (data.expressCode !== undefined ? data.expressCode : undefined); + if (expressCode !== undefined) { + updateFields.express_code = await this.ensureExpressExists(expressCode); + } + + // priority + const priority = data.priority !== undefined ? data.priority : undefined; + if (priority !== undefined) { + updateFields.priority = this.normalizeInteger(priority, 'priority'); + } + + // is_enabled + const isEnabled = data.is_enabled !== undefined + ? data.is_enabled + : (data.isEnabled !== undefined ? data.isEnabled : undefined); + if (isEnabled !== undefined) { + const val = Number(isEnabled); + if (![ 0, 1 ].includes(val)) { + throw this.createError('is_enabled 参数不合法,仅支持 0 或 1', 400); + } + updateFields.is_enabled = val; + } + + // regions + const regions = data.regions !== undefined ? data.regions : undefined; + if (regions !== undefined) { + updateFields.regions = this.normalizeJsonArray(regions, 'regions'); + } + + // shop_name + const shopName = data.shop_name !== undefined + ? data.shop_name + : (data.shopName !== undefined ? data.shopName : undefined); + if (shopName !== undefined) { + updateFields.shop_name = this.normalizeJsonArray(shopName, 'shop_name'); + } + + // store_ids + const storeIds = data.store_ids !== undefined + ? data.store_ids + : (data.storeIds !== undefined ? data.storeIds : undefined); + if (storeIds !== undefined) { + updateFields.store_ids = this.normalizeJsonArray(storeIds, 'store_ids'); + } + + // exclude_regions + const excludeRegions = data.exclude_regions !== undefined + ? data.exclude_regions + : (data.excludeRegions !== undefined ? data.excludeRegions : undefined); + if (excludeRegions !== undefined) { + updateFields.exclude_regions = this.normalizeJsonArray(excludeRegions, 'exclude_regions'); + } + + // min_weight_g + const minWeightG = data.min_weight_g !== undefined + ? data.min_weight_g + : (data.minWeightG !== undefined ? data.minWeightG : undefined); + if (minWeightG !== undefined) { + updateFields.min_weight_g = this.normalizeInteger(minWeightG, 'min_weight_g'); + } + + // max_weight_g + const maxWeightG = data.max_weight_g !== undefined + ? data.max_weight_g + : (data.maxWeightG !== undefined ? data.maxWeightG : undefined); + if (maxWeightG !== undefined) { + updateFields.max_weight_g = this.normalizeInteger(maxWeightG, 'max_weight_g'); + } + + // weight_type + const weightType = data.weight_type !== undefined + ? data.weight_type + : (data.weightType !== undefined ? data.weightType : undefined); + if (weightType !== undefined) { + updateFields.weight_type = this.normalizeWeightType(weightType); + } + + // prohibited_type_id + const prohibitedTypeIds = data.prohibited_type_id !== undefined + ? data.prohibited_type_id + : (data.prohibitedTypeId !== undefined ? data.prohibitedTypeId : undefined); + if (prohibitedTypeIds !== undefined) { + updateFields.prohibited_type_id = this.normalizeJsonArray(prohibitedTypeIds, 'prohibited_type_id'); + } + + // remark + const remark = data.remark !== undefined ? data.remark : undefined; + if (remark !== undefined) { + updateFields.remark = this.normalizeText(remark, 'remark', { maxLength: 500 }); + } + + // creator_id + const creatorId = data.creator_id !== undefined + ? data.creator_id + : (data.creatorId !== undefined ? data.creatorId : undefined); + if (creatorId !== undefined) { + updateFields.creator_id = this.normalizeInteger(creatorId, 'creator_id'); + } + + if (Object.keys(updateFields).length === 0) { + throw this.createError('没有需要更新的字段', 400); + } + + await policy.update(updateFields); + + // 清理当前仓库策略缓存 + try { + await this.ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId); + } catch (_) { + // 缓存清理失败不影响主流程 + } + + const updated = policy && typeof policy.get === 'function' + ? policy.get({ plain: true }) + : policy; + + return { id: updated.id }; + } + + /** + * 软删除策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 删除结果 + */ + async del(data = {}) { + const id = data.id !== undefined ? data.id : data.policy_id; + + const policy = await this.findPolicyById(id); + const now = new Date(); + + await policy.update({ deleted_at: now, is_enabled: 0 }); + + // 清理当前仓库策略缓存 + try { + const warehouseId = Number(policy.warehouse_id); + if (warehouseId > 0) { + await this.ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId); + } + } catch (_) { + // 缓存清理失败不影响主流程 + } + + return { id: Number(policy.id) }; + } +} + +module.exports = StoreExpressBindingPolicyService; diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js new file mode 100644 index 0000000..562a256 --- /dev/null +++ b/app/service/systems/store_warehouse.js @@ -0,0 +1,3701 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); +const Service = require('egg').Service; +const { Op } = require('sequelize'); + +const SIGN_TEMP_EXPIRE_SECONDS = 600; +// 签约关系级接口配置统一按货主开放接口维护,仓库开放接口仅用于仓库级应用(apiApp 模块) +const CONTRACT_OPEN_API_CODE = 'OPEN_API'; +const WAREHOUSE_OPEN_API_CODE = 'OPEN_API_WAREHOUSE'; +const DEFAULT_CALLBACK_URL_MAX_LENGTH = 500; +const AUTH_STATUS_LABELS = Object.freeze({ + 1: '申请中', + 2: '已通过', + 3: '已拒绝', + 4: '已解除', + 5: '已过期', +}); + +const CHANGE_TYPE_LABEL_MAP = Object.freeze({ + manual_adjust: '人工调整', + order_deduct: '订单扣减', +}); + +const BUSINESS_TYPE_LABEL_MAP = Object.freeze({ + order_express: '快递订单', +}); + +class SettingStoreWarehouseService extends Service { + /** + * 创建统一错误对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=500] HTTP 状态码。 + * @return {Error} 带 code 属性的错误对象。 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前登录主体的货主 ID。 + * + * @return {number} 当前主体的货主 ID。 + * @throws {Error} 当无法识别当前主体时抛出,状态码为 400。 + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作签约关系', 400); + } + return storeId; + } + + /** + * 获取当前登录账号 ID。 + * + * @return {number} 当前登录账号 ID。 + * @throws {Error} 当无法识别当前登录账号时抛出,状态码为 401。 + */ + getCurrentAccountId() { + const accountId = Number(this.ctx.user && this.ctx.user.id); + if (!Number.isFinite(accountId) || accountId <= 0) { + throw this.createError('未识别到当前登录账号', 401); + } + return accountId; + } + + /** + * 将输入值规范化为正数。 + * + * @param {*} value 待转换的值。 + * @param {string} fieldName 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowEmpty=false] 是否允许空值返回 null。 + * @return {number|null} 规范化后的正数或 null。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ + toPositiveNumber(value, fieldName, options = {}) { + const { allowEmpty = false } = options; + if (allowEmpty && (value === undefined || value === null || value === '')) { + return null; + } + + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + /** + * 规范化分页参数。 + * + * @param {*} value 待处理的页码或分页大小。 + * @param {string} fieldName 字段名。 + * @param {number} defaultValue 默认值。 + * @param {number} maxValue 最大值。 + * @return {number} 规范化后的分页值。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.min(Math.floor(num), maxValue); + } + + /** + * 规范化状态标记。 + * + * @param {*} value 待处理的状态值。 + * @param {string} fieldName 字段名。 + * @param {number|null} [defaultValue=null] 默认值。 + * @return {number|null} 0、1 或默认值。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ + normalizeStatusFlag(value, fieldName, defaultValue = null) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + /** + * 规范化签约状态。 + * + * @param {*} value 待处理的签约状态值。 + * @return {number|null} 合法的签约状态或 null。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ + normalizeAuthStatus(value) { + if (value === undefined || value === null || value === '') { + return null; + } + const num = Number(value); + if ([ 1, 2, 3, 4, 5 ].includes(num)) { + return num; + } + throw this.createError('auth_status 参数不合法', 400); + } + + /** + * 规范化非负整数。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 非负整数。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ + normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.floor(num); + } + + /** + * 规范化整数。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowZero=true] 是否允许 0。 + * @return {number} 整数值。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ + normalizeInteger(value, fieldName, options = {}) { + const { allowZero = true } = options; + if (value === undefined || value === null || value === '') { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const num = Number(value); + if (!Number.isFinite(num) || !Number.isInteger(num)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (!allowZero && num === 0) { + throw this.createError(`${fieldName} 不能为 0`, 400); + } + return num; + } + + /** + * 规范化文本内容。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {number} [maxLength=500] 最大长度。 + * @return {string|null} 规范化后的文本或 null。 + * @throws {Error} 文本超长时抛出,状态码为 400。 + */ + normalizeText(value, fieldName, maxLength = 500) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + /** + * 规范化区间整数。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {number} defaultValue 默认值。 + * @param {number} minValue 最小值。 + * @param {number} maxValue 最大值。 + * @return {number} 区间内的整数。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ + normalizeIntegerRange(value, fieldName, defaultValue, minValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num < minValue || num > maxValue) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.floor(num); + } + + /** + * 规范化邮箱地址。 + * + * @param {*} value 待处理的邮箱值。 + * @return {string|null} 合法邮箱或 null。 + * @throws {Error} 邮箱格式非法时抛出,状态码为 400。 + */ + normalizeEmail(value) { + const email = this.normalizeText(value, 'email', 100); + if (!email) { + return null; + } + + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + throw this.createError('email 参数不合法', 400); + } + return email; + } + + /** + * 获取策略配置字段清单。 + * + * @return {Array} 策略配置字段数组。 + */ + getPolicyConfigFieldList() { + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldList !== 'function') { + return []; + } + 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(); + } + + /** + * 规范化策略配置内容。 + * + * @param {*} value 待处理的配置值。 + * @param {string} [fieldName='policy_config'] 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowEmpty=false] 是否允许空值。 + * @param {boolean} [options.sanitizeOnly=false] 是否仅做清洗不做强校验。 + * @return {*|null} 规范化后的策略配置。 + * @throws {Error} 模型未提供规则或参数非法时抛出,对应状态码为 400/500。 + */ + normalizePolicyConfig(value, fieldName = 'policy_config', options = {}) { + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.normalizePolicyConfig !== 'function') { + throw this.createError('StoreWarehouse model 未定义 policy_config 规则', 500); + } + + try { + return storeWarehouseModel.normalizePolicyConfig(value, { + fieldName, + allowEmpty: options.allowEmpty === true, + sanitizeOnly: options.sanitizeOnly === true, + }); + } catch (error) { + throw this.createError(error.message || `${fieldName} 参数不合法`, Number(error.code) || 400); + } + } + + /** + * 生成策略配置缓存键。 + * + * @param {number|string} contractId 合同 ID。 + * @return {string} 缓存键。 + */ + getPolicyConfigCacheKey(contractId) { + return `store_warehouse:policy:${contractId}`; + } + + /** + * 判断表中是否存在 policy_config 字段。 + * + * @return {Promise} 是否存在该字段。 + */ + async hasPolicyConfigColumn() { + if (this._hasPolicyConfigColumn !== undefined) { + return this._hasPolicyConfigColumn; + } + + try { + const [ columns ] = await this.app.model.query( + "SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'" + ); + this._hasPolicyConfigColumn = Array.isArray(columns) && columns.length > 0; + } catch { + this._hasPolicyConfigColumn = false; + } + return this._hasPolicyConfigColumn; + } + + /** + * 按合同 ID 读取策略配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise<*>} 规范化后的策略配置。 + */ + async loadPolicyConfigByContractId(contractId, transaction = null) { + const normalizedId = Number(contractId || 0); + if (normalizedId <= 0) { + return null; + } + + if (await this.hasPolicyConfigColumn()) { + const [ rows ] = await this.app.model.query( + 'SELECT policy_config FROM wms_store_warehouse WHERE id = :id LIMIT 1', + { + replacements: { id: normalizedId }, + transaction, + } + ); + const row = Array.isArray(rows) ? rows[0] : null; + const raw = row ? row.policy_config : null; + + return this.normalizePolicyConfig(raw, 'policy_config', { + allowEmpty: true, + sanitizeOnly: true, + }); + } + + const cached = await this.app.getCacheAsync(this.getPolicyConfigCacheKey(normalizedId)); + return this.normalizePolicyConfig(cached, 'policy_config', { + allowEmpty: true, + sanitizeOnly: true, + }); + } + + /** + * 按合同 ID 保存策略配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {*} policyConfig 策略配置内容。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise} 无返回值。 + * @throws {Error} 合同 ID 非法时抛出,状态码为 400。 + */ + async savePolicyConfigByContractId(contractId, policyConfig, transaction = null) { + const normalizedId = Number(contractId || 0); + if (normalizedId <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + if (await this.hasPolicyConfigColumn()) { + await this.app.model.query( + 'UPDATE wms_store_warehouse SET policy_config = :policy_config, updated_at = NOW() WHERE id = :id', + { + replacements: { + id: normalizedId, + policy_config: JSON.stringify(policyConfig), + }, + transaction, + } + ); + } else { + await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); + } + + // 清除签约策略缓存(sw_policy:{storeId}:{warehouseId}): + // 该缓存内嵌 policy_config 快照与 allowOversell 判定,策略变更(如开启允许超卖)后必须失效, + // 否则奇门推送订单会继续读取旧快照,导致超卖开关生效前仍提示库存不足。 + const relation = await this.ctx.model.StoreWarehouse.findByPk(normalizedId, { + attributes: [ 'store_id', 'warehouse_id' ], + raw: true, + }); + if (relation) { + await this.app.delCacheAsync(`sw_policy:${relation.store_id}:${relation.warehouse_id}`); + } + } + + /** + * 获取策略配置默认值。 + * + * @return {Object} 策略配置默认值对象。 + */ + getPolicyConfigDefaults() { + return this.getPolicyConfigFieldList().reduce((result, field) => { + result[field.key] = field.default; + return result; + }, {}); + } + + /** + * 将策略配置与默认值合并。 + * + * @param {*} policyConfig 已保存的策略配置。 + * @return {Object} 合并后的策略配置对象。 + */ + mergePolicyConfigWithDefaults(policyConfig) { + const defaults = this.getPolicyConfigDefaults(); + if (!policyConfig || typeof policyConfig !== 'object') { + return defaults; + } + + return { + ...defaults, + ...policyConfig, + }; + } + + /** + * 按合同 ID 读取带默认值的策略配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise} 带默认值的策略配置对象。 + */ + async getEffectivePolicyConfigByContractId(contractId, transaction = null) { + const policyConfig = await this.loadPolicyConfigByContractId(contractId, transaction); + return this.mergePolicyConfigWithDefaults(policyConfig); + } + + /** + * 校验当前主体是否为仓库主体。 + * + * @param {Object} currentSubject 当前主体。 + * @param {string} [actionLabel='签约配置'] 操作名称。 + * @return {void} + * @throws {Error} 当前主体不是仓库主体时抛出,状态码为 403。 + */ + ensureWarehouseSubject(currentSubject, actionLabel = '签约配置') { + if (!currentSubject || !currentSubject.isWarehouse) { + throw this.createError(`仅仓库主体可维护${actionLabel}`, 403); + } + } + + /** + * 获取通知服务实例。 + * + * @return {Object|null} 通知服务或 null。 + */ + getNoticeService() { + const rawNoticeService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.notice; + if (rawNoticeService && typeof rawNoticeService.send === 'function') { + return rawNoticeService; + } + if (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function') { + return rawNoticeService.index; + } + return null; + } + + /** + * 发送面单余额调整通知。 + * + * @param {Object} options 通知参数。 + * @param {Object} [options.relation] 签约关系。 + * @param {Object} [options.currentSubject] 当前主体。 + * @param {Object} [options.changeLog] 调整日志。 + * @param {number} [options.operatorId] 操作人 ID。 + * @param {number} [options.changeQuantity] 变更数量。 + * @param {number} [options.balanceBefore] 调整前余额。 + * @param {number} [options.balanceAfter] 调整后余额。 + * @param {string} [options.reason] 调整原因。 + * @return {Promise} 通知发送结果或 null。 + */ + async sendPrintQuantityAdjustNotice({ + relation, + currentSubject, + changeLog, + operatorId, + changeQuantity, + balanceBefore, + balanceAfter, + reason, + } = {}) { + const noticeService = this.getNoticeService(); + if (!noticeService || !relation) { + return null; + } + + const relationData = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : (relation || {}); + const storeName = relationData.store_remask || (relationData.store && relationData.store.company_name) || ''; + const warehouseName = relationData.warehouse_remask || (relationData.warehouse && relationData.warehouse.company_name) || ''; + const operatorName = String( + (this.ctx.user && (this.ctx.user.real_name || this.ctx.user.employees_name || this.ctx.user.name || this.ctx.user.username)) || '' + ).trim(); + const changeLabel = changeQuantity === 0 + ? '无变化' + : changeQuantity > 0 + ? `增加 ${changeQuantity}` + : `扣减 ${Math.abs(changeQuantity)}`; + + return await noticeService.send({ + warehouseId: Number(relationData.warehouse_id || 0), + storeId: Number(relationData.store_id || 0) || undefined, + messageType: 'text', + businessName: 'store_warehouse', + event: 'store_warehouse_print_quantity_adjusted', + title: '货主面单余额已更新', + content: [ + warehouseName ? `仓库:${warehouseName}` : '', + storeName ? `货主:${storeName}` : '', + `设置余额:${balanceAfter}`, + `变更:${changeLabel}`, + `余额:${balanceBefore} -> ${balanceAfter}`, + `原因:${reason}`, + operatorName ? `操作人:${operatorName}` : '', + ].filter(Boolean).join(';'), + businessId: Number((changeLog && changeLog.id) || relationData.id || 0), + subject: { + id: Number(currentSubject && currentSubject.id || relationData.warehouse_id || 0), + type: currentSubject && currentSubject.isWarehouse ? 'warehouse' : 'store', + name: currentSubject && currentSubject.company_name ? currentSubject.company_name : warehouseName, + }, + sender: { + id: Number(operatorId || 0) || null, + name: operatorName, + }, + metadata: { + contractId: Number(relationData.id || 0), + storeId: Number(relationData.store_id || 0), + warehouseId: Number(relationData.warehouse_id || 0), + changeType: String(changeLog && changeLog.change_type || 'manual_adjust'), + businessType: changeLog && changeLog.business_type ? String(changeLog.business_type) : null, + businessId: changeLog && changeLog.business_id !== undefined && changeLog.business_id !== null + ? Number(changeLog.business_id) + : null, + changeQuantity, + balanceBefore, + balanceAfter, + reason, + }, + }); + } + + /** + * 解析签约关系 ID。 + * + * @param {Object} [data={}] 请求参数。 + * @return {number|null} 关系 ID 或 null。 + */ + resolveRelationId(data = {}) { + return this.toPositiveNumber( + data.id !== undefined ? data.id : (data.contract_id !== undefined ? data.contract_id : data.relation_id), + 'id', + { allowEmpty: true } + ); + } + + /** + * 规范化日期值。 + * + * @param {*} value 待处理的日期值。 + * @param {string} fieldName 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowNull=true] 是否允许空值。 + * @return {Date|null} 规范化后的日期对象或 null。 + * @throws {Error} 日期非法时抛出,状态码为 400。 + */ + normalizeDate(value, fieldName, options = {}) { + const { allowNull = true } = options; + if (value === undefined || value === null || value === '') { + if (allowNull) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return date; + } + + /** + * 规范化签约动作。 + * + * @param {*} value 待处理的动作值。 + * @return {string} 规范化后的动作值。 + * @throws {Error} 动作非法时抛出,状态码为 400。 + */ + normalizeSignAction(value) { + if (value === undefined || value === null || value === '') { + return ''; + } + + const action = String(value).trim(); + if ([ 'preview', 'confirm' ].includes(action)) { + return action; + } + throw this.createError('action 参数不合法', 400); + } + + /** + * 规范化临时码。 + * + * @param {*} value 待处理的临时码。 + * @return {string} 大写后的临时码。 + * @throws {Error} 临时码为空或非法时抛出,状态码为 400。 + */ + normalizeTempCode(value) { + const code = String(value || '').trim().toUpperCase(); + if (!code) { + throw this.createError('temp_code 参数不能为空', 400); + } + return code; + } + + /** + * 生成临时码缓存键。 + * + * @param {string} tempCode 临时码。 + * @return {string} 缓存键。 + */ + getTempCodeCacheKey(tempCode) { + return `store_warehouse:sign:${tempCode}`; + } + + /** + * 生成临时码。 + * + * @return {string} 临时码。 + */ + createTempCode() { + return crypto.randomBytes(6).toString('hex').toUpperCase(); + } + + /** + * 选择当前主体对应的脱敏字段。 + * + * @param {Object} currentSubject 当前主体。 + * @return {string} 脱敏字段名。 + */ + pickRemaskField(currentSubject) { + return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask'; + } + + /** + * 解析脱敏展示名称。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {string|null} 脱敏名称。 + */ + resolveRemaskValue(data, currentSubject) { + const raw = data.remask !== undefined + ? data.remask + : (currentSubject && currentSubject.isWarehouse ? data.store_remask : data.warehouse_remask); + return this.normalizeText(raw, 'remask', 50); + } + + /** + * 构建当前主体的脱敏字段更新内容。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 待更新字段对象。 + */ + buildCurrentRemaskPatch(data, currentSubject) { + const remask = this.resolveRemaskValue(data, currentSubject); + if (remask === null) { + return {}; + } + + return { + [this.pickRemaskField(currentSubject)]: remask, + }; + } + + /** + * 构建强制要求的脱敏字段更新内容。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 待更新字段对象。 + * @throws {Error} 未提供脱敏名称时抛出,状态码为 400。 + */ + requireCurrentRemaskPatch(data, currentSubject) { + const patch = this.buildCurrentRemaskPatch(data, currentSubject); + if (!Object.keys(patch).length) { + throw this.createError('remask 参数不能为空', 400); + } + return patch; + } + + /** + * 保存临时签约载荷。 + * + * @param {Object} payload 临时载荷。 + * @return {Promise} 保存后的临时码信息。 + */ + async saveTempSignPayload(payload) { + const now = Date.now(); + const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString(); + const tempCode = this.createTempCode(); + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { + ...payload, + expires_at: expiresAt, + }, SIGN_TEMP_EXPIRE_SECONDS); + return { + tempCode, + expiresAt, + expiresIn: SIGN_TEMP_EXPIRE_SECONDS, + }; + } + + /** + * 读取临时签约载荷。 + * + * @param {string} tempCode 临时码。 + * @return {Promise} 临时码与载荷信息。 + * @throws {Error} 临时码无效或已过期时抛出,状态码为 404。 + */ + async getTempSignPayload(tempCode) { + const normalizedCode = this.normalizeTempCode(tempCode); + const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode)); + if (!payload) { + throw this.createError('临时码无效或已过期', 404); + } + return { + tempCode: normalizedCode, + payload, + }; + } + + /** + * 清理临时签约载荷。 + * + * @param {string} tempCode 临时码。 + * @return {Promise} 无返回值。 + */ + async clearTempSignPayload(tempCode) { + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + if (cacheRedis && cacheRedis.del) { + await cacheRedis.del(this.getTempCodeCacheKey(tempCode)); + return; + } + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1); + } + + /** + * 构建临时签约预览视图。 + * + * @param {string} tempCode 临时码。 + * @param {Object} payload 临时载荷。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 预览视图对象。 + */ + buildTempSignView(tempCode, payload, currentSubject) { + const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]; + const currentSubjectId = Number(currentSubject && currentSubject.id); + const expiresAt = payload.expires_at || null; + const expiresMs = expiresAt ? new Date(expiresAt).getTime() : 0; + + return { + mode: 'preview', + temp_code: tempCode, + expires_at: expiresAt, + expires_in: expiresMs ? Math.max(0, Math.ceil((expiresMs - Date.now()) / 1000)) : 0, + is_participant: participantIds.includes(currentSubjectId), + can_confirm: currentSubjectId > 0 && currentSubjectId === Number(payload.counterparty_id || 0), + initiator: { + id: Number(payload.initiator_subject_id || 0), + role: payload.initiator_role || '', + name: payload.initiator_name || '', + }, + counterparty: { + id: Number(payload.counterparty_id || 0), + role: payload.counterparty_role || '', + name: payload.counterparty_name || '', + }, + sign_info: { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_start: payload.auth_start || null, + auth_end: payload.auth_end || null, + print_quantity: Number(payload.print_quantity || 0), + apply_reason: payload.apply_reason || '', + remask: payload.remask || '', + }, + }; + } + + /** + * 获取当前主体信息。 + * + * @return {Promise} 当前主体对象。 + * @throws {Error} 当前主体不存在时抛出,状态码为 404。 + */ + async getCurrentSubject() { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const subject = await ctx.model.Store.findOne({ + where: { + id: storeId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!subject) { + throw this.createError('当前主体不存在', 404); + } + + return { + id: Number(subject.id), + company_name: subject.company_name || '', + project: subject.project || '', + isWarehouse: subject.project === 'warehouse', + status: Number(subject.status || 0), + }; + } + + /** + * 获取签约对方主体信息(不校验项目角色,仓库可签仓库、货主可签货主)。 + * + * @param {number} counterpartyId 对方主体 ID。 + * @param {string} [_expectedRole] 期望角色(已废弃,保留参数兼容)。 + * @return {Promise} 对方主体对象。 + * @throws {Error} 对方主体不存在时抛出,状态码为 404。 + */ + async getCounterparty(counterpartyId, _expectedRole) { + const { ctx } = this; + const counterparty = await ctx.model.Store.findOne({ + where: { + id: counterpartyId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!counterparty) { + throw this.createError('签约对象不存在', 404); + } + + return counterparty; + } + + /** + * 构建列表查询条件(按 store_id 维度)。 + * + * 当前主体始终作为 store_id 方(货主方/消费方),对方为 warehouse_id 方(仓库方/提供方)。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} where 查询条件。 + */ + buildListWhereByStoreId(data, currentSubject) { + const where = { + store_id: currentSubject.id, + }; + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } + + const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + where.warehouse_id = counterpartyId; + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status; + const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null); + if (useStatus !== null) { + where.store_use_status = useStatus; + } + + return where; + } + + /** + * 构建列表查询条件(兼容旧逻辑,保留以供其他方法使用)。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} where 查询条件。 + * @deprecated 新代码请使用 buildListWhereByStoreId。 + */ + buildListWhere(data, currentSubject) { + const where = {}; + + if (currentSubject.isWarehouse) { + where.warehouse_id = currentSubject.id; + } else { + where.store_id = currentSubject.id; + } + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } + + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + if (currentSubject.isWarehouse) { + where.store_id = counterpartyId; + } else { + where.warehouse_id = counterpartyId; + } + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const rawUseStatus = data.use_status !== undefined ? data.use_status + : (data.warehouse_use_status !== undefined ? data.warehouse_use_status : data.store_use_status); + const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null); + if (useStatus !== null) { + if (currentSubject.isWarehouse) { + where.warehouse_use_status = useStatus; + } else { + where.store_use_status = useStatus; + } + } + + return where; + } + + /** + * 获取签约关系关联模型。 + * + * @return {Array} 关联配置数组。 + */ + getRelationIncludes() { + const { ctx } = this; + return [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + ]; + } + + /** + * 生成奇门合同缓存键。 + * + * @param {string} appKey 应用标识。 + * @param {string} customerId 客户标识。 + * @param {string} warehouseCode 仓库编码。 + * @return {string} 缓存键。 + */ + getQimenContractCacheKey(appKey, customerId, warehouseCode) { + return `contract:${appKey}:${customerId}:${warehouseCode}`; + } + + /** + * 清理奇门合同缓存。 + * + * @param {Array} configs 配置列表。 + * @return {Promise} 无返回值。 + */ + async clearQimenContractCache(configs = []) { + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + const keys = [ ...new Set(configs.map(item => { + const record = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : item; + if (!record) { + return ''; + } + + const appKey = String(record.qimen_app_key || '').trim(); + const customerId = String(record.qimen_customer_id || '').trim(); + const warehouseCode = String(record.qimen_warehouse_code || '').trim(); + if (!appKey || !customerId || !warehouseCode) { + return ''; + } + return this.getQimenContractCacheKey(appKey, customerId, warehouseCode); + }).filter(Boolean)) ]; + + if (!keys.length) { + return; + } + + if (cacheRedis && cacheRedis.del) { + await cacheRedis.del(...keys); + return; + } + + await Promise.all(keys.map(key => this.app.setCacheAsync(key, null, 1).catch(() => null))); + } + + /** + * 获取接口类型。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [options={}] 选项。 + * @param {boolean} [options.allowDisabled=false] 是否允许禁用接口类型。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @param {boolean} [options.requireId=false] 是否必须传入 interface_type_id。 + * @param {string|null} [options.interfaceCategory=null] 接口分类。 + * @return {Promise} 接口类型对象。 + * @throws {Error} 参数非法或接口类型不存在时抛出,状态码为 400/404。 + */ + async getApiInterfaceType(data = {}, options = {}) { + const { ctx } = this; + const { allowDisabled = false, transaction = null, requireId = false, interfaceCategory = null } = options; + const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); + if (requireId && !interfaceTypeId) { + throw this.createError('interface_type_id 参数不能为空', 400); + } + + const where = {}; + if (interfaceCategory) { + where.interface_category = interfaceCategory; + } + if (!allowDisabled) { + where.is_enabled = 1; + } + if (interfaceTypeId) { + where.id = interfaceTypeId; + } + + const interfaceType = await ctx.model.InterfaceType.findOne({ + where, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + order: [[ 'id', 'ASC' ]], + transaction, + }); + + if (!interfaceType) { + throw this.createError(interfaceTypeId ? '指定的接口类型不存在或不可用' : '未配置可用的接口类型', 404); + } + + return interfaceType; + } + + /** + * 获取奇门接口类型。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [options={}] 选项。 + * @return {Promise} 接口类型对象。 + */ + async getQimenInterfaceType(data = {}, options = {}) { + return this.getApiInterfaceType(data, options); + } + + /** + * 解析签约关系级接口类型。 + * + * 签约关系上的接口配置统一按货主开放接口(OPEN_API)落库: + * 传入仓库开放接口(OPEN_API_WAREHOUSE)时映射为货主开放接口,避免货主侧创建仓库接口。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [options={}] 选项。 + * @param {boolean} [options.allowDisabled=false] 是否允许禁用接口类型(查询过滤时可放宽)。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @return {Promise} 接口类型对象。 + * @throws {Error} 接口类型不存在(400/404)或缺失货主开放接口类型(404)时抛出。 + */ + async resolveContractApiInterfaceType(data = {}, options = {}) { + const { ctx } = this; + const { transaction = null, allowDisabled = false } = options; + const interfaceType = await this.getApiInterfaceType(data, { transaction, requireId: true, allowDisabled }); + if (interfaceType.interface_code !== WAREHOUSE_OPEN_API_CODE) { + return interfaceType; + } + + const storeInterfaceType = await ctx.model.InterfaceType.findOne({ + where: { + interface_code: CONTRACT_OPEN_API_CODE, + ...(allowDisabled ? {} : { is_enabled: 1 }), + }, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + transaction, + }); + if (!storeInterfaceType) { + throw this.createError('未配置可用的货主开放接口类型', 404); + } + + ctx.logger.warn( + '[storeWarehouse.saveApiConfig] interface_type_id=%s 为仓库开放接口,签约关系级配置按货主开放接口(id=%s)落库', + interfaceType.id, + storeInterfaceType.id + ); + return storeInterfaceType; + } + + /** + * 获取签约关系级接口配置的默认回调地址。 + * + * 回调地址不由调用方传入,统一取 config.openapi.defaultCallbackUrl。 + * + * @return {string|null} 默认回调地址;未配置或超出长度限制时返回 null。 + */ + getDefaultApiCallbackUrl() { + const openApiConfig = this.app && this.app.config ? this.app.config.openapi : null; + const rawValue = openApiConfig ? openApiConfig.defaultCallbackUrl : ''; + if (rawValue === undefined || rawValue === null) { + return null; + } + const normalized = String(rawValue).trim(); + if (!normalized) { + return null; + } + if (normalized.length > DEFAULT_CALLBACK_URL_MAX_LENGTH) { + this.ctx.logger.warn( + '[storeWarehouse.saveApiConfig] config.openapi.defaultCallbackUrl 长度超过 %s,已忽略', + DEFAULT_CALLBACK_URL_MAX_LENGTH + ); + return null; + } + return normalized; + } + + /** + * 根据奇门 AppKey 解析客户标识。 + * + * @param {string|null} qimenAppKey 奇门应用 AppKey。 + * @param {Object} [options={}] 查询选项。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @return {Promise} 命中的客户标识;未传 AppKey 时返回 null。 + * @throws {Error} 当 AppKey 不存在或未配置 customer_id 时抛出,状态码为 400。 + */ + async resolveQimenCustomerIdByAppKey(qimenAppKey, options = {}) { + const { ctx } = this; + const { transaction = null } = options; + const normalizedAppKey = this.normalizeText(qimenAppKey, 'qimen_app_key', 100); + if (!normalizedAppKey) { + return null; + } + + const qimenApp = await ctx.model.QimenApp.findOne({ + where: { + app_key: normalizedAppKey, + }, + attributes: [ 'id', 'app_key', 'customer_id' ], + transaction, + }); + + if (!qimenApp) { + throw this.createError('未找到与 qimen_app_key 对应的奇门应用配置', 400); + } + + const customerId = this.normalizeText(qimenApp.customer_id, 'customer_id', 100); + if (!customerId) { + throw this.createError('对应的奇门应用未配置 customer_id,无法保存接口配置', 400); + } + + return customerId; + } + + /** + * 根据奇门 AppKey 列表查询 ERP 名称映射。 + * + * @param {Array} appKeys 奇门 AppKey 列表。 + * @param {Object} [options={}] 查询选项。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @return {Promise>} AppKey 到 ERP 名称的映射。 + */ + async getQimenErpNameMapByAppKeys(appKeys = [], options = {}) { + const { ctx } = this; + const { transaction = null } = options; + const normalizedAppKeys = [ ...new Set( + appKeys + .map(value => this.normalizeText(value, 'qimen_app_key', 100, { allowEmpty: true })) + .filter(Boolean) + ) ]; + + if (!normalizedAppKeys.length) { + return new Map(); + } + + const rows = await ctx.model.QimenApp.findAll({ + where: { + app_key: normalizedAppKeys, + }, + attributes: [ 'app_key', 'name' ], + raw: true, + transaction, + }); + + return new Map(rows.map(item => [ + String(item.app_key || ''), + String(item.name || ''), + ])); + } + + /** + * 序列化奇门配置。 + * + * @param {Object} config 配置实例或普通对象。 + * @return {Object|null} 序列化后的配置对象。 + */ + serializeQimenConfig(config) { + if (!config) { + return null; + } + + const item = config && typeof config.get === 'function' + ? config.get({ plain: true }) + : config; + const interfaceType = item.interface_type || {}; + + return { + id: Number(item.id || 0), + interface_type_id: Number(item.interface_type_id || 0), + interface_code: interfaceType.interface_code || item.interface_code || '', + interface_name: interfaceType.interface_name || item.interface_name || '', + interface_category: interfaceType.interface_category || item.interface_category || '', + erp_name: item.erp_name || item.erpName || '', + contract_id: Number(item.contract_id || 0), + warehouse_id: item.warehouse_id ? Number(item.warehouse_id) : null, + app_name: item.app_name || '', + self_app_key: item.self_app_key || '', + self_app_secret: item.self_app_secret || '', + qimen_app_key: item.qimen_app_key || '', + qimen_customer_id: item.qimen_customer_id || '', + qimen_warehouse_code: item.qimen_warehouse_code || '', + api_version: item.api_version || '', + sign_method: item.sign_method || '', + rate_limit: Number(item.rate_limit || 0), + timeout_seconds: Number(item.timeout_seconds || 0), + contact_person: item.contact_person || '', + contact_phone: item.contact_phone || '', + email: item.email || '', + is_enabled: Number(item.is_enabled || 0), + created_at: item.created_at || null, + updated_at: item.updated_at || null, + callback_url: item.callback_url || '', + }; + } + + /** + * 获取奇门配置映射。 + * + * @param {Array} contractIds 合同 ID 列表。 + * @param {Object} [options={}] 选项。 + * @param {boolean} [options.allowDisabled=true] 是否允许禁用接口类型。 + * @param {number|null} [options.interfaceTypeId=null] 指定接口类型 ID。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @return {Promise} 合同 ID 到配置的映射。 + */ + async getQimenConfigMap(contractIds = [], options = {}) { + const { ctx } = this; + const { allowDisabled = true, interfaceTypeId = null, transaction = null } = options; + const normalizedContractIds = [ ...new Set(contractIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0)) ]; + + if (!normalizedContractIds.length || !ctx.model.ApiApp || !ctx.model.InterfaceType) { + return new Map(); + } + + const where = { + contract_id: normalizedContractIds, + }; + if (interfaceTypeId) { + const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, { + allowDisabled, + transaction, + }); + where.interface_type_id = Number(interfaceType.id || 0); + } + + const rows = await ctx.model.ApiApp.findAll({ + where, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + transaction, + }); + + const configMap = new Map(); + for (const row of rows) { + const contractId = Number(row.contract_id || 0); + if (!contractId || configMap.has(contractId)) { + continue; + } + configMap.set(contractId, this.serializeQimenConfig(row)); + } + + return configMap; + } + + /** + * 获取单个奇门配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {Object} [options={}] 选项。 + * @return {Promise} 单个配置对象或 null。 + */ + async getSingleQimenConfig(contractId, options = {}) { + const configMap = await this.getQimenConfigMap([ contractId ], options); + return configMap.get(Number(contractId)) || null; + } + + /** + * 解析成对的合同主体 ID。 + * + * 规则:当前主体(签约发起方)始终为 store_id 方(货主方/消费方), + * 对方始终为 warehouse_id 方(仓库方/提供方)。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 包含 storeId、warehouseId、counterpartyId 的对象。 + * @throws {Error} 对方主体参数非法时抛出,状态码为 400。 + */ + resolvePairIds(data, currentSubject) { + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (data.store_id && Number(data.store_id) !== currentSubject.id ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id / 对方主体ID'); + + return { + storeId: currentSubject.id, + warehouseId: counterpartyId, + counterpartyId, + }; + } + + /** + * 序列化签约关系。 + * + * @param {Object} relation 签约关系实例或普通对象。 + * @param {Object} currentSubject 当前主体。 + * @param {Object|null} [qimenConfig=null] 奇门配置。 + * @return {Object} 序列化后的签约关系对象。 + */ + serializeRelation(relation, currentSubject, qimenConfig = null) { + const item = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : (relation || {}); + const normalizedQimenConfig = qimenConfig !== null + ? qimenConfig + : (item.qimen_config ? this.serializeQimenConfig(item.qimen_config) : null); + + const authStatus = Number(item.auth_status || 0); + const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse); + const subjectId = currentSubject ? Number(currentSubject.id) : 0; + + // 根据当前主体在 store_id 还是 warehouse_id 判定对方主体(兼容新旧签约数据) + const subjectIsStore = subjectId > 0 && subjectId === Number(item.store_id || 0); + const subjectIsWarehouse = subjectId > 0 && subjectId === Number(item.warehouse_id || 0); + const counterparty = subjectIsStore ? item.warehouse : item.store; + const counterpartyRole = counterparty && counterparty.project === 'warehouse' ? 'warehouse' : 'store'; + + const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); + const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : ''); + const counterpartyName = counterparty && counterparty.company_name ? counterparty.company_name : ''; + + let isAuthValid = false; + let remainingDays = 0; + if (authStatus === 2 && item.auth_start && item.auth_end) { + const now = Date.now(); + const start = new Date(item.auth_start).getTime(); + const end = new Date(item.auth_end).getTime(); + if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) { + isAuthValid = true; + remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24))); + } + } + + return { + id: Number(item.id || 0), + store_id: Number(item.store_id || 0), + store_name: storeName, + warehouse_id: Number(item.warehouse_id || 0), + warehouse_name: warehouseName, + counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0, + counterparty_name: counterpartyName, + counterparty_role: counterpartyRole, + current_subject_role: currentIsWarehouse ? 'warehouse' : 'store', + auth_status: authStatus, + auth_status_label: AUTH_STATUS_LABELS[authStatus] || '', + apply_reason: item.apply_reason || '', + review_comment: item.review_comment || '', + apply_time: item.apply_time || null, + review_time: item.review_time || null, + auth_start: item.auth_start || null, + auth_end: item.auth_end || null, + actual_end: item.actual_end || null, + print_quantity: Number(item.print_quantity || 0), + print_quantity_locked: Number(item.print_quantity_locked || 0), + applied_by: item.applied_by ? Number(item.applied_by) : null, + reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, + ended_by: item.ended_by ? Number(item.ended_by) : null, + remask: subjectIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), + use_status: subjectIsWarehouse + ? Number(item.warehouse_use_status || 0) + : Number(item.store_use_status || 0), + warehouse_use_status: Number(item.warehouse_use_status || 0), + store_use_status: Number(item.store_use_status || 0), + is_auth_valid: isAuthValid, + remaining_days: remainingDays, + api_config: normalizedQimenConfig || null, + apiConfig: normalizedQimenConfig || null, + }; + } + + /** + * 获取受限范围内的签约关系(兼容新旧签约数据)。 + * + * 新数据:当前主体在 store_id(发起方/消费方)。 + * 旧数据:仓库主体可能在 warehouse_id(提供方)。 + * 使用 OR 查询两边,确保新旧数据都能被操作。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @param {Object} transaction 事务对象。 + * @return {Promise} 签约关系实例。 + * @throws {Error} 签约关系不存在或无权限操作时抛出,状态码为 404。 + */ + async findScopedRelation(data, currentSubject, transaction) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const scopedWhere = {}; + + const relationId = this.resolveRelationId(data); + if (relationId) { + scopedWhere.id = relationId; + } else { + const pair = this.resolvePairIds(data, currentSubject); + scopedWhere.store_id = pair.storeId; + scopedWhere.warehouse_id = pair.warehouseId; + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where: { + ...scopedWhere, + [Op.or]: [ + { store_id: currentSubject.id }, + { warehouse_id: currentSubject.id }, + ], + }, + include: this.getRelationIncludes(), + transaction, + }); + + if (!relation) { + throw this.createError('签约关系不存在或无权限操作', 404); + } + + return relation; + } + + /** + * 构建货主侧签约列表查询条件(仓库在 warehouse_id 方,对方货主在 store_id 方)。 + * + * 供 listForStore / exportListForStore 复用,保证列表与导出的筛选语义一致。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} where 查询条件。 + */ + buildListForStoreWhere(data = {}, currentSubject) { + const { Op } = this.app.Sequelize; + + // 仓库查看自己签约的货主列表:仓库在 warehouse_id 方,货主在 store_id 方 + const where = { + warehouse_id: currentSubject.id, + }; + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } + + const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.store_id, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + // 对方(货主)在 store_id 方 + where.store_id = counterpartyId; + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const rawUseStatus = data.use_status !== undefined ? data.use_status : data.warehouse_use_status; + if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') { + where.warehouse_use_status = Number(rawUseStatus); + } + + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + return where; + } + + /** + * 货主侧查询签约关系列表(兼容新旧签约数据)。 + * + * 使用 OR 查询 store_id / warehouse_id 两边,确保新旧签约数据都能被正确展示。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async listForStore(data = {}) { + const { ctx } = this; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + // 仓库查看自己签约的货主列表:仓库在 warehouse_id 方,货主在 store_id 方 + const where = this.buildListForStoreWhere(data, currentSubject); + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + + const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0); + const qimenConfigMap = contractIds.length + ? await this.getQimenConfigMap(contractIds) + : new Map(); + + return { + code: 200, + data: { + list: rows.map(item => { + const serialized = this.serializeRelation(item, currentSubject); + serialized.has_qimen_config = qimenConfigMap.has(serialized.id); + return { + id: serialized.id, + store_id: serialized.store_id, + warehouse_id: serialized.warehouse_id, + counterparty_id: serialized.counterparty_id, + counterparty_name: serialized.counterparty_name, + counterparty_role: serialized.counterparty_role, + remask: serialized.remask, + use_status: serialized.use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + has_qimen_config: serialized.has_qimen_config, + needs_my_confirm: Number(item.auth_status || 0) === 1 + && Number(item.initiator_subject_id || 0) !== currentSubject.id, + }; + }), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + /** + * 导出货主侧签约列表(与 storeWarehouse.store.list / listForStore 筛选语义一致)。 + * + * 全量查询当前主体(仓库在 warehouse_id 方)可见的签约关系,生成 Excel 上传至 COS。 + * 忽略分页参数,复用 buildListForStoreWhere 的筛选条件;每行输出与 listForStore 对齐的 + * 序列化字段(含 has_qimen_config、needs_my_confirm),并对角色/启用状态/有效性等做中文展示。 + * + * @param {Object} [data={}] 请求参数(与 listForStore 一致,page/page_size 被忽略)。 + * @return {Promise} 包含 filename、fileKey、url、cdnUrl、cosUrl、total_count 的对象。 + */ + async exportListForStore(data = {}) { + const { ctx } = this; + const currentSubject = await this.getCurrentSubject(); + const where = this.buildListForStoreWhere(data, currentSubject); + + // 全量查询所有匹配记录(不翻页),与列表使用相同关联与排序 + const rows = await ctx.model.StoreWarehouse.findAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + // 奇门配置映射(与列表一致) + const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0); + const qimenConfigMap = contractIds.length + ? await this.getQimenConfigMap(contractIds) + : new Map(); + + // 生成 Excel + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'store_relation_export_')); + const filename = `货主签约列表_${currentSubject.id}_${Date.now()}.xlsx`; + const filePath = path.join(tempDir, filename); + + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: true, + useSharedStrings: true, + }); + const worksheet = workbook.addWorksheet('货主签约列表'); + + worksheet.columns = [ + { header: '签约关系ID', key: 'id', width: 14 }, + { header: '货主ID', key: 'store_id', width: 10 }, + { header: '货主名称', key: 'store_name', width: 24 }, + { header: '仓库ID', key: 'warehouse_id', width: 10 }, + { header: '仓库名称', key: 'warehouse_name', width: 24 }, + { header: '对方主体ID', key: 'counterparty_id', width: 12 }, + { header: '对方主体名称', key: 'counterparty_name', width: 24 }, + { header: '对方主体角色', key: 'counterparty_role_label', width: 12 }, + { header: '备注名', key: 'remask', width: 20 }, + { header: '当前视角启用状态', key: 'use_status_label', width: 16 }, + { header: '货主侧启用状态', key: 'store_use_status_label', width: 16 }, + { header: '仓库侧启用状态', key: 'warehouse_use_status_label', width: 16 }, + { header: '签约状态', key: 'auth_status_label', width: 12 }, + { header: '签约是否有效', key: 'is_auth_valid_label', width: 14 }, + { header: '剩余有效天数', key: 'remaining_days', width: 14 }, + { header: '面单余额', key: 'print_quantity', width: 12 }, + { header: '锁定面单余额', key: 'print_quantity_locked', width: 14 }, + { header: '授权开始时间', key: 'auth_start', width: 22 }, + { header: '授权结束时间', key: 'auth_end', width: 22 }, + { header: '实际结束时间', key: 'actual_end', width: 22 }, + { header: '申请时间', key: 'apply_time', width: 22 }, + { header: '审核时间', key: 'review_time', width: 22 }, + { header: '申请原因', key: 'apply_reason', width: 30 }, + { header: '审核评语', key: 'review_comment', width: 30 }, + { header: '是否已配置奇门', key: 'has_qimen_config_label', width: 16 }, + { header: '是否需要我确认', key: 'needs_my_confirm_label', width: 16 }, + ]; + + const roleLabel = role => { + if (role === 'warehouse') return '仓库'; + if (role === 'store') return '货主'; + return role ? String(role) : ''; + }; + const statusLabel = value => (Number(value) === 1 ? '启用' : '禁用'); + const yesNoLabel = value => (value ? '是' : '否'); + + for (const item of rows) { + const serialized = this.serializeRelation(item, currentSubject); + const hasQimenConfig = qimenConfigMap.has(serialized.id); + worksheet.addRow({ + id: serialized.id, + store_id: serialized.store_id, + store_name: serialized.store_name || '', + warehouse_id: serialized.warehouse_id, + warehouse_name: serialized.warehouse_name || '', + counterparty_id: serialized.counterparty_id, + counterparty_name: serialized.counterparty_name || '', + counterparty_role_label: roleLabel(serialized.counterparty_role), + remask: serialized.remask || '', + use_status_label: statusLabel(serialized.use_status), + store_use_status_label: statusLabel(serialized.store_use_status), + warehouse_use_status_label: statusLabel(serialized.warehouse_use_status), + auth_status_label: serialized.auth_status_label || '', + is_auth_valid_label: yesNoLabel(serialized.is_auth_valid), + remaining_days: serialized.remaining_days, + print_quantity: serialized.print_quantity, + print_quantity_locked: serialized.print_quantity_locked, + auth_start: serialized.auth_start ? String(serialized.auth_start) : '', + auth_end: serialized.auth_end ? String(serialized.auth_end) : '', + actual_end: serialized.actual_end ? String(serialized.actual_end) : '', + apply_time: serialized.apply_time ? String(serialized.apply_time) : '', + review_time: serialized.review_time ? String(serialized.review_time) : '', + apply_reason: serialized.apply_reason || '', + review_comment: serialized.review_comment || '', + has_qimen_config_label: yesNoLabel(hasQimenConfig), + needs_my_confirm_label: yesNoLabel( + Number(item.auth_status || 0) === 1 + && Number(item.initiator_subject_id || 0) !== currentSubject.id + ), + }).commit(); + } + + worksheet.commit(); + await workbook.commit(); + + // 上传至 COS + const uploadService = ctx.service && ctx.service.systems && ctx.service.systems.upload; + let uploadResult = {}; + if (uploadService && typeof uploadService.uploadFile === 'function') { + const stat = await fsp.stat(filePath); + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + uploadResult = await uploadService.uploadFile(uploadStream, { + key: `export/store_relation/${currentSubject.id}/${filename}`, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + if (typeof uploadService.uploadSuccessNotify === 'function') { + await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'storeRelationListExport', + businessId: String(currentSubject.id), + uploaderType: ctx.user?.role || 'system_api', + uploaderDept: ctx.user?.department || '', + }).catch(err => { + ctx.logger.warn('[storeWarehouse.exportListForStore] 上传通知失败: %s', err.message); + }); + } + } + + // 清理临时文件 + try { + await fsp.rm(tempDir, { recursive: true, force: true }); + } catch (cleanErr) { + ctx.logger.warn('[storeWarehouse.exportListForStore] 清理临时文件失败: %s', cleanErr.message); + } + + return { + filename, + fileKey: uploadResult.fileName || '', + url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '', + cdnUrl: uploadResult.cdnUrl || uploadResult.url || '', + cosUrl: uploadResult.cosUrl || '', + total_count: rows.length, + }; + } + + /** + * 仓库侧查询签约关系列表(兼容新旧签约数据)。 + * + * 使用 OR 查询 store_id / warehouse_id 两边,确保新旧签约数据都能被正确展示。 + * 支持查询仓库与外部合作仓库的关系。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async listForWarehouse(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + // 货主查看自己签约的仓库列表:货主在 store_id 方,仓库在 warehouse_id 方 + const where = { + store_id: currentSubject.id, + }; + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } + + const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + // 对方(仓库)在 warehouse_id 方 + where.warehouse_id = counterpartyId; + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status; + if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') { + where.store_use_status = Number(rawUseStatus); + } + + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + + const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0); + const qimenConfigMap = contractIds.length + ? await this.getQimenConfigMap(contractIds) + : new Map(); + + return { + code: 200, + data: { + list: rows.map(item => { + const serialized = this.serializeRelation(item, currentSubject); + serialized.has_qimen_config = qimenConfigMap.has(serialized.id); + return { + id: serialized.id, + store_id: serialized.store_id, + store_name: serialized.store_name, + warehouse_id: serialized.warehouse_id, + warehouse_name: serialized.warehouse_name, + counterparty_id: serialized.counterparty_id, + counterparty_name: serialized.counterparty_name, + counterparty_role: serialized.counterparty_role, + remask: serialized.remask, + use_status: serialized.store_use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + has_qimen_config: serialized.has_qimen_config, + needs_my_confirm: Number(item.auth_status || 0) === 1 + && Number(item.initiator_subject_id || 0) !== currentSubject.id, + }; + }), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + /** + * 查询签约关系列表(旧版,保留向后兼容)。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + * @deprecated 新代码请使用 listForStore 或 listForWarehouse。 + */ + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + const where = this.buildListWhere(data, currentSubject); + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + + const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0); + const qimenConfigMap = contractIds.length + ? await this.getQimenConfigMap(contractIds) + : new Map(); + + return { + code: 200, + data: { + list: rows.map(item => { + const serialized = this.serializeRelation(item, currentSubject); + serialized.has_qimen_config = qimenConfigMap.has(serialized.id); + return { + id: serialized.id, + store_id: serialized.store_id, + warehouse_id: serialized.warehouse_id, + counterparty_name: serialized.counterparty_name, + remask: serialized.remask, + use_status: serialized.use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + has_qimen_config: serialized.has_qimen_config, + needs_my_confirm: Number(item.auth_status || 0) === 1 + && Number(item.initiator_subject_id || 0) !== currentSubject.id, + }; + }), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + /** + * 发起或确认签约。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async sign(data = {}) { + const action = this.normalizeSignAction(data.action || data.mode); + if (action === 'preview') { + const currentSubject = await this.getCurrentSubject(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + return { + code: 200, + data: { + mode: 'preview', + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + counterparty: { + id: Number(counterparty.id || 0), + company_name: counterparty.company_name || '', + role: counterparty.project === 'warehouse' ? 'warehouse' : 'store', + }, + }, + }; + } + + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + if (authEnd && authStart.getTime() > authEnd.getTime()) { + throw this.createError('auth_end 不能早于 auth_start', 400); + } + + const relationPatch = { + store_id: pair.storeId, + warehouse_id: pair.warehouseId, + auth_status: 1, + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), + apply_time: new Date(), + print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + review_time: null, + auth_start: authStart, + auth_end: authEnd, + actual_end: null, + applied_by: accountId, + reviewed_by: null, + ended_by: null, + initiator_subject_id: currentSubject.id, + warehouse_use_status: 1, + store_use_status: 1, + print_quantity_locked: 0, + }; + + Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); + + let relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: pair.storeId, + warehouse_id: pair.warehouseId, + }, + transaction, + }); + const isCreate = !relation; + + if (relation) { + if (relation.applied_by === accountId && relation.auth_status === 1) { + await relation.update(relationPatch, { transaction }); + } else if (relation.applied_by === accountId && relation.auth_status >= 2) { + const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.rollback(); + return { + code: 200, + data: { + mode: 'already_confirmed', + exists_status: relation.auth_status, + exists_status_label: '已签约', + contract: this.trimContract(this.serializeRelation(existing, currentSubject)), + }, + }; + } else { + const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); + await transaction.rollback(); + return { + code: 200, + data: { + mode: 'already_exists', + exists_status: relation.auth_status, + exists_status_label: relation.auth_status === 2 ? '已签约' : '待确认', + contract: this.trimContract(this.serializeRelation(existing, currentSubject)), + }, + }; + } + } else { + relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); + } + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + const wasExisting = !!relation._previousDataValues; + + await transaction.commit(); + + return { + code: 200, + data: { + mode: 'initiate', + contract: this.trimContract(this.serializeRelation(result, currentSubject)), + action: isCreate ? 'create' : 'update', + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 精简签约对象,仅保留前端需要的字段。 + * @param serialized + */ + trimContract(serialized) { + return { + id: serialized.id, + store_id: serialized.store_id, + warehouse_id: serialized.warehouse_id, + counterparty_name: serialized.counterparty_name, + remask: serialized.remask, + use_status: serialized.use_status, + auth_status: serialized.auth_status, + auth_status_label: serialized.auth_status_label, + auth_end: serialized.auth_end, + print_quantity: serialized.print_quantity, + has_qimen_config: serialized.has_qimen_config, + }; + } + + /** + * 确认签约:对方主体确认待签约的申请,状态从 1(申请中)变为 2(已通过)。 + * 发起方不能确认自己的申请。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number} data.id 签约关系ID。 + * @return {Promise} 接口响应对象。 + */ + async confirmSign(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const relationId = this.resolveRelationId(data); + + if (!relationId) { + throw this.createError('id 参数不能为空', 400); + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where: { id: relationId }, + include: this.getRelationIncludes(), + transaction, + }); + + if (!relation) { + throw this.createError('签约关系不存在', 404); + } + + if (relation.auth_status !== 1) { + throw this.createError('当前签约状态不允许确认,仅待签约状态可确认', 400); + } + + // 确定当前主体在签约中的角色 + const isCurrentStore = relation.store_id === currentSubject.id; + const isCurrentWarehouse = relation.warehouse_id === currentSubject.id; + + if (!isCurrentStore && !isCurrentWarehouse) { + throw this.createError('当前主体不在此签约关系中', 403); + } + + // 发起签约的主体不能确认自己的申请,必须由对方主体确认 + if (relation.initiator_subject_id === currentSubject.id) { + throw this.createError('发起方不能确认自己的签约申请', 403); + } + + await relation.update({ + auth_status: 2, + review_time: new Date(), + reviewed_by: accountId, + }, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + mode: 'confirm', + contract: this.trimContract(this.serializeRelation(result, currentSubject)), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 修改签约关系脱敏名称。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async rename(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const relationPatch = this.requireCurrentRemaskPatch(data, currentSubject); + + await relation.update(relationPatch, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_RENAME', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.rename] 写入操作日志失败,不影响业务', logErr); + } + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject, qimenConfig), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 调整面单余额。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async adjustPrintQuantity(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + this.ensureWarehouseSubject(currentSubject, '面单余额'); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const operatorId = this.getCurrentAccountId(); + const targetQuantityField = [ + [ 'print_quantity', data.print_quantity ], + [ 'target_quantity', data.target_quantity ], + [ 'change_quantity', data.change_quantity ], + [ 'adjust_quantity', data.adjust_quantity ], + ].find(([ , value ]) => value !== undefined && value !== null && value !== ''); + if (!targetQuantityField) { + throw this.createError('print_quantity / target_quantity / change_quantity / adjust_quantity 参数不能为空', 400); + } + const [ targetQuantityFieldName, targetQuantityRaw ] = targetQuantityField; + const targetQuantity = this.normalizeInteger(targetQuantityRaw, targetQuantityFieldName, { allowZero: true }); + if (targetQuantity < 0) { + throw this.createError(`${targetQuantityFieldName} 参数不合法`, 400); + } + const reason = this.normalizeText(data.reason, 'reason', 500); + if (!reason) { + throw this.createError('reason 参数不能为空', 400); + } + + const businessType = this.normalizeText(data.business_type, 'business_type', 50); + const businessId = data.business_id === undefined || data.business_id === null || data.business_id === '' + ? null + : this.toPositiveNumber(data.business_id, 'business_id'); + const balanceBefore = Number(relation.print_quantity || 0); + const balanceAfter = targetQuantity; + const changeQuantity = balanceAfter - balanceBefore; + + await relation.update({ + print_quantity: balanceAfter, + }, { transaction }); + + const changeLogRecord = await ctx.model.StoreWarehousePrintQuantityLog.create({ + contract_id: Number(relation.id || 0), + store_id: Number(relation.store_id || 0), + warehouse_id: Number(relation.warehouse_id || 0), + change_type: 'manual_adjust', + business_type: businessType, + business_id: businessId, + change_quantity: changeQuantity, + balance_before: balanceBefore, + balance_after: balanceAfter, + reason, + operator_id: operatorId, + created_by: operatorId, + }, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + const changeLog = changeLogRecord && typeof changeLogRecord.get === 'function' + ? changeLogRecord.get({ plain: true }) + : (changeLogRecord || {}); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_ADJUST_PRINT_QUANTITY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.adjustPrintQuantity] 写入操作日志失败,不影响业务', logErr); + } + + await this.sendPrintQuantityAdjustNotice({ + relation: result, + currentSubject, + changeLog, + operatorId, + changeQuantity, + balanceBefore, + balanceAfter, + reason, + }).catch(error => { + ctx.logger.warn(`[storeWarehouse.adjustPrintQuantity] 通知发送失败: ${error.message}`); + }); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject, qimenConfig), + change_log: { + id: Number(changeLog.id || 0), + contract_id: Number(changeLog.contract_id || relation.id || 0), + change_type: String(changeLog.change_type || 'manual_adjust'), + business_type: changeLog.business_type ? String(changeLog.business_type) : null, + business_id: changeLog.business_id !== undefined && changeLog.business_id !== null + ? Number(changeLog.business_id) + : null, + change_quantity: Number(changeLog.change_quantity || 0), + balance_before: Number(changeLog.balance_before !== undefined ? changeLog.balance_before : balanceBefore), + balance_after: Number(changeLog.balance_after !== undefined ? changeLog.balance_after : balanceAfter), + reason: changeLog.reason || reason, + operator_id: Number(changeLog.operator_id || operatorId), + created_at: changeLog.created_at || null, + }, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 按货主查询面单余额变更日志(分页)。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.store_id 货主 ID。 + * @param {Object} [data.where] 动态筛选条件。 + * @param {Object} [data.pagination] 分页对象。 + * @param {number|string} [data.pagination.page] 页码。 + * @param {number|string} [data.pagination.page_size] 每页条数。 + * @return {Promise} 接口响应对象。 + */ + async queryPrintQuantityLogs(data = {}) { + const { ctx } = this; + const currentSubject = await this.getCurrentSubject(); + const storeId = this.toPositiveNumber(data.store_id, 'store_id'); + const pagination = data.pagination && typeof data.pagination === 'object' + ? data.pagination + : {}; + const page = this.normalizePage(pagination.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(pagination.page_size, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + if (!currentSubject.isWarehouse && Number(currentSubject.id) !== Number(storeId)) { + throw this.createError('仅可查询当前货主的面单余额变更日志', 403); + } + + const where = { + store_id: Number(storeId), + }; + + if (currentSubject.isWarehouse) { + where.warehouse_id = Number(currentSubject.id); + } + + const dynamicConditions = this.ctx.whereParsed && Array.isArray(this.ctx.whereParsed.dynamicConditions) + ? this.ctx.whereParsed.dynamicConditions.filter(Boolean) + : []; + + if (dynamicConditions.length > 0) { + where[Op.and] = dynamicConditions; + } + + const { rows, count } = await ctx.model.StoreWarehousePrintQuantityLog.findAndCountAll({ + where, + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + }); + + // 收集所有需要回填姓名的操作人 ID + const accountIdSet = new Set(); + for (const item of rows) { + const payload = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : (item || {}); + if (payload.operator_id) accountIdSet.add(Number(payload.operator_id)); + if (payload.created_by) accountIdSet.add(Number(payload.created_by)); + } + const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0); + + // 批量查询账号姓名 + const accountNameMap = {}; + if (accountIds.length > 0) { + try { + const accounts = await ctx.model.Account.findAll({ + attributes: [ 'id', 'real_name' ], + where: { id: { [Op.in]: accountIds } }, + raw: true, + }); + for (const acc of accounts) { + accountNameMap[Number(acc.id)] = acc.real_name || ''; + } + } catch (err) { + ctx.logger.warn('[queryPrintQuantityLogs] 批量查询操作人姓名失败,不影响主流程: %s', err.message); + } + } + + const total = Number(count || 0); + const totalPages = total > 0 ? Math.ceil(total / pageSize) : 0; + + return { + code: 200, + data: { + list: rows.map(item => { + const payload = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : (item || {}); + + const operatorId = payload.operator_id !== undefined && payload.operator_id !== null + ? Number(payload.operator_id) + : null; + const createdBy = payload.created_by !== undefined && payload.created_by !== null + ? Number(payload.created_by) + : null; + + return { + id: Number(payload.id || 0), + contract_id: Number(payload.contract_id || 0), + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + change_type: payload.change_type ? String(payload.change_type) : '', + change_type_label: CHANGE_TYPE_LABEL_MAP[payload.change_type] || payload.change_type || '', + business_type: payload.business_type ? String(payload.business_type) : null, + business_type_label: payload.business_type + ? (BUSINESS_TYPE_LABEL_MAP[payload.business_type] || payload.business_type) + : '-', + business_id: payload.business_id !== undefined && payload.business_id !== null + ? Number(payload.business_id) + : null, + change_quantity: Number(payload.change_quantity || 0), + balance_before: Number(payload.balance_before || 0), + balance_after: Number(payload.balance_after || 0), + reason: payload.reason || '', + operator_id: operatorId, + operator_name: operatorId ? (accountNameMap[operatorId] || '') : '', + created_by: createdBy, + created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '', + created_at: payload.created_at || null, + updated_at: payload.updated_at || null, + }; + }), + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: totalPages > 0 && page < totalPages, + }, + }, + }; + } + + /** + * 导出面单余额变更日志。 + * 查询所有匹配条件的记录,生成 Excel 文件上传至 COS,返回下载信息。 + * + * @param {Object} data 请求数据。 + * @param {number|string} data.store_id 货主ID(必填)。 + * @param {Object} [data.where] 动态筛选条件,与 queryPrintQuantityLogs 的 where 语义一致。 + * @return {Promise} 包含 url、fileKey、filename 的对象。 + */ + async exportPrintQuantityLogs(data = {}) { + const { ctx } = this; + const currentSubject = await this.getCurrentSubject(); + const storeId = this.toPositiveNumber(data.store_id, 'store_id'); + + if (!currentSubject.isWarehouse && Number(currentSubject.id) !== Number(storeId)) { + throw this.createError('仅可导出当前货主的面单余额变更日志', 403); + } + + const where = { + store_id: Number(storeId), + }; + + if (currentSubject.isWarehouse) { + where.warehouse_id = Number(currentSubject.id); + } + + const dynamicConditions = this.ctx.whereParsed && Array.isArray(this.ctx.whereParsed.dynamicConditions) + ? this.ctx.whereParsed.dynamicConditions.filter(Boolean) + : []; + + if (dynamicConditions.length > 0) { + where[Op.and] = dynamicConditions; + } + + // 查询全部匹配记录 + const rows = await ctx.model.StoreWarehousePrintQuantityLog.findAll({ + where, + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + // 收集操作人 ID,批量查询姓名 + const accountIdSet = new Set(); + for (const item of rows) { + if (item.operator_id) accountIdSet.add(Number(item.operator_id)); + if (item.created_by) accountIdSet.add(Number(item.created_by)); + } + const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0); + const accountNameMap = {}; + if (accountIds.length > 0) { + const accounts = await ctx.model.Account.findAll({ + attributes: [ 'id', 'real_name' ], + where: { id: { [Op.in]: accountIds } }, + raw: true, + }); + for (const acc of accounts) { + accountNameMap[Number(acc.id)] = acc.real_name || ''; + } + } + + // 生成 Excel + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'print_qty_log_export_')); + const filename = `面单余额变更日志_${storeId}_${Date.now()}.xlsx`; + const filePath = path.join(tempDir, filename); + + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: true, + useSharedStrings: true, + }); + const worksheet = workbook.addWorksheet('面单余额变更日志'); + + worksheet.columns = [ + { header: '记录ID', key: 'id', width: 10 }, + { header: '签约关系ID', key: 'contract_id', width: 14 }, + { header: '货主ID', key: 'store_id', width: 10 }, + { header: '仓库ID', key: 'warehouse_id', width: 10 }, + { header: '变更类型', key: 'change_type_label', width: 12 }, + { header: '业务来源类型', key: 'business_type_label', width: 14 }, + { header: '业务关联ID', key: 'business_id', width: 14 }, + { header: '变更数量', key: 'change_quantity', width: 12 }, + { header: '变更前余额', key: 'balance_before', width: 14 }, + { header: '变更后余额', key: 'balance_after', width: 14 }, + { header: '变更原因', key: 'reason', width: 30 }, + { header: '操作人', key: 'operator_name', width: 14 }, + { header: '创建人', key: 'created_by_name', width: 14 }, + { header: '创建时间', key: 'created_at', width: 22 }, + { header: '更新时间', key: 'updated_at', width: 22 }, + ]; + + for (const item of rows) { + const operatorId = item.operator_id !== undefined && item.operator_id !== null + ? Number(item.operator_id) + : null; + const createdBy = item.created_by !== undefined && item.created_by !== null + ? Number(item.created_by) + : null; + + worksheet.addRow({ + id: Number(item.id || 0), + contract_id: Number(item.contract_id || 0), + store_id: Number(item.store_id || 0), + warehouse_id: Number(item.warehouse_id || 0), + change_type_label: CHANGE_TYPE_LABEL_MAP[item.change_type] || item.change_type || '', + business_type_label: item.business_type + ? (BUSINESS_TYPE_LABEL_MAP[item.business_type] || item.business_type) + : '-', + business_id: item.business_id !== undefined && item.business_id !== null + ? Number(item.business_id) + : '', + change_quantity: Number(item.change_quantity || 0), + balance_before: Number(item.balance_before || 0), + balance_after: Number(item.balance_after || 0), + reason: item.reason || '', + operator_name: operatorId ? (accountNameMap[operatorId] || '') : '', + created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '', + created_at: item.created_at ? String(item.created_at) : '', + updated_at: item.updated_at ? String(item.updated_at) : '', + }).commit(); + } + + worksheet.commit(); + await workbook.commit(); + + // 上传至 COS + const uploadService = ctx.service && ctx.service.systems && ctx.service.systems.upload; + let uploadResult = {}; + if (uploadService && typeof uploadService.uploadFile === 'function') { + const stat = await fsp.stat(filePath); + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + uploadResult = await uploadService.uploadFile(uploadStream, { + key: `export/print_quantity_log/${storeId}/${filename}`, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + if (typeof uploadService.uploadSuccessNotify === 'function') { + await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'printQuantityLogExport', + businessId: String(storeId), + uploaderType: ctx.user?.role || 'system_api', + uploaderDept: ctx.user?.department || '', + }).catch(err => { + ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 上传通知失败: %s', err.message); + }); + } + } + + // 清理临时文件 + try { + await fsp.rm(tempDir, { recursive: true, force: true }); + } catch (cleanErr) { + ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 清理临时文件失败: %s', cleanErr.message); + } + + return { + filename, + fileKey: uploadResult.fileName || '', + url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '', + cdnUrl: uploadResult.cdnUrl || uploadResult.url || '', + cosUrl: uploadResult.cosUrl || '', + total_count: rows.length, + }; + } + + /** + * 获取策略配置字段。 + * + * @return {Promise} 接口响应对象。 + */ + async getPolicyConfigFields() { + return { + code: 200, + data: await this.getPolicyConfigFieldMetaList(), + }; + } + + /** + * 获取签约策略配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async getPolicyConfig(data = {}) { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + }); + const policyConfig = await this.getEffectivePolicyConfigByContractId(relation.id); + + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + policy_config: policyConfig, + contract: this.serializeRelation(relation, currentSubject, qimenConfig), + }, + }; + } + + /** + * 保存签约策略配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async savePolicyConfig(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + this.ensureWarehouseSubject(currentSubject, '签约策略配置'); + const policyConfig = this.normalizePolicyConfig( + data.policy_config !== undefined ? data.policy_config : data.policy + ); + await this.savePolicyConfigByContractId(relation.id, policyConfig, transaction); + const effectivePolicyConfig = this.mergePolicyConfigWithDefaults(policyConfig); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + await this.invalidateContractConfigCache(relation.warehouse_id, relation.store_id).catch(() => null); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_SAVE_POLICY_CONFIG', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.savePolicyConfig] 写入操作日志失败,不影响业务', logErr); + } + + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + policy_config: effectivePolicyConfig, + contract: this.serializeRelation(result, currentSubject, qimenConfig), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 查询接口配置列表。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async listApiConfig(data = {}) { + const { ctx } = this; + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject); + const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); + + const where = { + contract_id: Number(relation.id || 0), + }; + if (interfaceTypeId) { + // 签约关系级配置没有仓库开放接口,传 3 时按货主开放接口过滤 + const interfaceType = await this.resolveContractApiInterfaceType( + { interface_type_id: interfaceTypeId }, + { allowDisabled: true } + ); + where.interface_type_id = Number(interfaceType.id || 0); + } + + const rows = await ctx.model.ApiApp.findAll({ + where, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + const qimenAppKeys = rows + .map(item => { + const plainItem = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : item; + const interfaceCategory = plainItem?.interface_type?.interface_category || plainItem?.interface_category || ''; + if (interfaceCategory !== 'QM_WMS') { + return null; + } + return plainItem?.qimen_app_key || null; + }) + .filter(Boolean); + const qimenErpNameMap = await this.getQimenErpNameMapByAppKeys(qimenAppKeys); + + const list = rows.map(item => { + const plainItem = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : item; + const interfaceCategory = plainItem?.interface_type?.interface_category || plainItem?.interface_category || ''; + const erpName = interfaceCategory === 'QM_WMS' + ? (qimenErpNameMap.get(String(plainItem?.qimen_app_key || '')) || '') + : ''; + + return this.serializeQimenConfig({ + ...plainItem, + erp_name: erpName, + }); + }); + const primaryApiConfig = list.length ? list[0] : null; + + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + contract: this.serializeRelation(relation, currentSubject, primaryApiConfig), + list, + total: list.length, + }, + }; + } + + /** + * 保存接口配置。 + * + * 签约关系级配置统一按货主开放接口维护:传入仓库开放接口(interface_type_id=3)时按货主开放接口落库, + * 回调地址不再取入参,统一使用 config.openapi.defaultCallbackUrl。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async saveApiConfig(data = {}) { + const { ctx, app } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const interfaceType = await this.resolveContractApiInterfaceType(data, { transaction }); + const isOpenApi = interfaceType.interface_category === 'OPEN_API'; + const isQimenWms = interfaceType.interface_category === 'QM_WMS'; + + // 奇门相关字段:QM_WMS 必填,OPEN_API 不需要 + let qimenAppKey = null; + let qimenCustomerId = null; + let qimenWarehouseCode = null; + + // 外部入参优先,未传入时才从 qimen_app 表解析 + const externalCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100); + + if (isQimenWms) { + qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100); + if (!qimenAppKey) { + throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400); + } + qimenCustomerId = externalCustomerId || await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }); + qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100); + if (!qimenWarehouseCode) { + throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400); + } + } else { + // OPEN_API: 奇门字段可选输入 + qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null; + qimenCustomerId = externalCustomerId + || (qimenAppKey ? await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }) : null); + qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null; + } + + const appName = this.normalizeText(data.app_name, 'app_name', 200); + if (!appName) { + throw this.createError('app_name 参数不能为空', 400); + } + const apiVersion = this.normalizeText(data.api_version, 'api_version', 50) || '1.0'; + const signMethod = (this.normalizeText(data.sign_method, 'sign_method', 50) || 'md5').toLowerCase(); + if (![ 'md5', 'hmac', 'sha256' ].includes(signMethod)) { + throw this.createError('sign_method 参数不合法', 400); + } + + const rateLimit = this.normalizeIntegerRange(data.rate_limit, 'rate_limit', 1000, 1, 100000); + const timeoutSeconds = this.normalizeIntegerRange(data.timeout_seconds, 'timeout_seconds', 30, 1, 300); + const contactPerson = this.normalizeText(data.contact_person, 'contact_person', 100); + const contactPhone = this.normalizeText(data.contact_phone, 'contact_phone', 20); + const email = this.normalizeEmail(data.email); + const isEnabled = this.normalizeStatusFlag(data.is_enabled, 'is_enabled', 1); + + const where = { + interface_type_id: Number(interfaceType.id || 0), + contract_id: Number(relation.id || 0), + }; + let config = await ctx.model.ApiApp.findOne({ + where, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + transaction, + }); + + const { Op } = app.Sequelize; + // 重复检测:按接口类型不同检查策略 + let duplicateConfig = null; + if (isQimenWms && qimenAppKey && qimenWarehouseCode) { + const duplicateWhere = { + interface_type_id: Number(interfaceType.id || 0), + qimen_app_key: qimenAppKey, + qimen_warehouse_code: qimenWarehouseCode, + }; + if (config && config.id) { + duplicateWhere.id = { [Op.ne]: config.id }; + } + duplicateConfig = await ctx.model.ApiApp.findOne({ + where: duplicateWhere, + attributes: [ 'id', 'contract_id' ], + transaction, + }); + if (duplicateConfig) { + throw this.createError('该 AppKey 和仓库编码 已绑定其他签约关系', 409); + } + } + + // OPEN_API: 创建时自动生成 self_app_key 和 self_app_secret + let selfAppKey = null; + let selfAppSecret = null; + if (isOpenApi) { + if (config) { + // 更新时保留已有密钥 + selfAppKey = config.self_app_key; + selfAppSecret = config.self_app_secret; + } else { + // 创建时生成新密钥 + const crypto = require('crypto'); + selfAppKey = `WMS${crypto.randomBytes(16).toString('hex').toUpperCase()}`; + selfAppSecret = crypto.randomBytes(32).toString('hex'); + } + } + + const configPayload = { + app_name: appName, + interface_type_id: Number(interfaceType.id || 0), + contract_id: Number(relation.id || 0), + warehouse_id: relation.warehouse_id ? Number(relation.warehouse_id) : null, + self_app_key: selfAppKey, + self_app_secret: selfAppSecret, + qimen_app_key: qimenAppKey, + qimen_customer_id: qimenCustomerId, + qimen_warehouse_code: qimenWarehouseCode, + api_version: apiVersion, + sign_method: signMethod, + rate_limit: rateLimit, + timeout_seconds: timeoutSeconds, + contact_person: contactPerson || null, + contact_phone: contactPhone || null, + email, + callback_url: this.getDefaultApiCallbackUrl(), + is_enabled: isEnabled, + }; + + const previousConfig = config ? this.serializeQimenConfig(config) : null; + const action = config ? 'update' : 'create'; + if (config) { + await config.update(configPayload, { transaction }); + } else { + config = await ctx.model.ApiApp.create(configPayload, { transaction }); + } + + const savedConfig = await ctx.model.ApiApp.findByPk(config.id, { + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + transaction, + }); + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const apiConfig = this.serializeQimenConfig(savedConfig); + + await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_SAVE_API_CONFIG', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.saveApiConfig] 写入操作日志失败,不影响业务', logErr); + } + + await this.clearQimenContractCache([ previousConfig, apiConfig ]).catch(error => { + ctx.logger.warn('[storeWarehouse.saveApiConfig] 清理奇门缓存失败: %s', error.message); + }); + + return { + code: 200, + data: { + action, + contract: this.serializeRelation(result, currentSubject, apiConfig), + api_config: apiConfig, + apiConfig, + }, + }; + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('接口配置已存在,请检查应用名或 AppKey / 仓库编码 是否重复', 409); + } + if (error && error.name === 'SequelizeValidationError') { + const message = error.errors && error.errors.length ? error.errors[0].message : '接口配置参数校验失败'; + throw this.createError(message, 400); + } + throw error; + } + } + + /** + * 删除奇门接口配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async deleteQimenConfig(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + this.ensureWarehouseSubject(currentSubject, '接口配置'); + const interfaceType = await this.getApiInterfaceType(data, { + allowDisabled: true, + transaction, + }); + const config = await ctx.model.ApiApp.findOne({ + where: { + contract_id: Number(relation.id || 0), + interface_type_id: Number(interfaceType.id || 0), + }, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + transaction, + }); + + if (!config) { + throw this.createError('接口配置不存在', 404); + } + + const removedConfig = this.serializeQimenConfig(config); + await config.destroy({ transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_DELETE_API_CONFIG', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 写入操作日志失败,不影响业务', logErr); + } + + await this.clearQimenContractCache([ removedConfig ]).catch(error => { + ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 清理奇门缓存失败: %s', error.message); + }); + + return { + code: 200, + data: { + deleted: true, + contract: this.serializeRelation(result, currentSubject, null), + api_config: null, + apiConfig: null, + removed: removedConfig, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 解绑签约关系。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ + async unbind(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const nextUseStatus = this.normalizeStatusFlag( + data.use_status !== undefined ? data.use_status : data.warehouse_use_status, + 'warehouse_use_status', 0); + const patch = currentSubject.isWarehouse + ? { warehouse_use_status: nextUseStatus } + : { store_use_status: nextUseStatus }; + + await relation.update(patch, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_UNBIND', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.unbind] 写入操作日志失败,不影响业务', logErr); + } + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject, qimenConfig), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 生成货主合约配置缓存键。 + * + * @param {number|string} warehouseId 仓库 ID。 + * @param {number|string} storeId 货主 ID。 + * @return {string} 缓存键。 + */ + getContractConfigCacheKey(warehouseId, storeId) { + return `store_warehouse:contract_config:${Number(warehouseId || 0)}:${Number(storeId || 0)}`; + } + + /** + * 使货主合约配置缓存失效。 + * + * @param {number|string} warehouseId 仓库 ID。 + * @param {number|string} storeId 货主 ID。 + * @return {Promise} 无返回值。 + */ + async invalidateContractConfigCache(warehouseId, storeId) { + const key = this.getContractConfigCacheKey(warehouseId, storeId); + try { + const cacheRedis = this.app.redis && this.app.redis.get && this.app.redis.get('cache'); + if (cacheRedis && typeof cacheRedis.del === 'function') { + await cacheRedis.del(key); + return; + } + await this.app.setCacheAsync(key, null, 1); + } catch (error) { + this.ctx.logger.warn('[storeWarehouse.invalidateContractConfigCache] 缓存失效失败: %s', error.message); + } + } + + /** + * 按仓库 ID 和货主 ID 读取合约配置,优先读缓存。 + * + * 缓存在 savePolicyConfig 或合约状态变更后立即失效。 + * + * @param {number|string} warehouseId 仓库 ID。 + * @param {number|string} storeId 货主 ID。 + * @return {Promise} 合约配置对象,不存在时返回 null。 + */ + async getContractConfig(warehouseId, storeId) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedStoreId = Number(storeId || 0); + if (normalizedWarehouseId <= 0 || normalizedStoreId <= 0) { + return null; + } + + const cacheKey = this.getContractConfigCacheKey(normalizedWarehouseId, normalizedStoreId); + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (cached !== null && cached !== undefined) { + return cached; + } + } catch (error) { + this.ctx.logger.warn('[storeWarehouse.getContractConfig] 读取缓存失败: %s', error.message); + } + + const row = await this.ctx.model.StoreWarehouse.findOne({ + where: { + warehouse_id: normalizedWarehouseId, + store_id: normalizedStoreId, + }, + attributes: [ 'id', 'store_id', 'warehouse_id', 'auth_status', 'policy_config' ], + raw: true, + }); + + if (!row) { + return null; + } + + const rawPolicyConfig = this.normalizePolicyConfig(row.policy_config, 'policy_config', { + allowEmpty: true, + sanitizeOnly: true, + }); + const config = { + id: row.id, + store_id: row.store_id, + warehouse_id: row.warehouse_id, + auth_status: row.auth_status, + policy_config: this.mergePolicyConfigWithDefaults(rawPolicyConfig), + }; + + try { + await this.app.setCacheAsync(cacheKey, config, 600); + } catch (error) { + this.ctx.logger.warn('[storeWarehouse.getContractConfig] 写入缓存失败: %s', error.message); + } + + return config; + } + + /** + * 仓库代货主一键开户:注册账号、创建货主、签约三步合并。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} data.username 必填,登录账号。 + * @param {string} data.password 必填,初始密码。 + * @param {string} [data.real_name] 可选,真实姓名。 + * @param {string} data.company_name 必填,公司全称。 + * @param {string} data.business_license 必填,营业执照号。 + * @param {string} data.contact_person 必填,联系人。 + * @param {string} data.contact_phone 必填,联系电话。 + * @param {string} [data.legal_person] 可选,法人代表。 + * @param {string} [data.contact_email] 可选,联系邮箱。 + * @param {string} [data.address] 可选,公司地址。 + * @param {string} [data.industry] 可选,所属行业。 + * @param {string} [data.auth_start] 可选,授权开始日期,默认当天。 + * @param {string} [data.auth_end] 可选,授权结束日期。 + * @param {number} [data.print_quantity=0] 可选,初始面单余额。 + * @param {string} [data.apply_reason='仓库代开户'] 可选,申请原因。 + * @param {string} [data.store_remask] 可选,货主备注名(≤50字符);不传或为空时默认取公司全称(截断 50 字符)填充。 + * @param {string} [data.warehouse_remask] 可选,仓库备注名(≤50字符)。 + * @return {Promise} 包含 store_id、account_id、contract_id、company_name、username 的响应对象。 + * @throws {Error} 当前主体不是仓库时抛出 403,账号/公司名重复时抛出 409,参数校验失败时抛出 400。 + */ + async openAccount(data = {}) { + const { ctx } = this; + + // 1. 获取当前主体,必须是仓库 + const currentSubject = await this.getCurrentSubject(); + if (!currentSubject.isWarehouse) { + throw this.createError('仅仓库主体可执行代开户操作', 403); + } + + // 2. 获取当前账号 ID + const accountId = this.getCurrentAccountId(); + + // 3. 密码自动生成 + if (!data.password) { + data.password = crypto.randomBytes(8).toString('base64').replace(/[+/=]/g, '') + .slice(0, 12); + } + + // 4. 必填字段校验 + const requiredFields = [ 'username', 'company_name', 'contact_person' ]; + for (const field of requiredFields) { + if (!data[field]) { + throw this.createError(`${field} 参数不能为空`, 400); + } + } + + // 5. 公司名称唯一性校验 + const existingStore = await ctx.model.Store.findOne({ + where: { company_name: data.company_name }, + }); + if (existingStore) { + throw this.createError('公司名称已存在', 409); + } + + // 6. 账号唯一性校验 + const existingAccount = await ctx.model.Account.findOne({ + where: { username: data.username }, + }); + if (existingAccount) { + throw this.createError('账号已存在', 409); + } + + // 7. 备注长度校验 + const storeRemask = this.normalizeText(data.store_remask, 'store_remask', 50); + const warehouseRemask = this.normalizeText(data.warehouse_remask, 'warehouse_remask', 50); + + // 8. 规范化日期 + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + + // 9. 在事务中依次执行注册、创建货主、签约 + const transaction = await ctx.model.transaction(); + + try { + // a. 创建账号 + // email 兜底:不传时生成占位邮箱,避免 Account model 的 notEmpty + isEmail 校验报错 + const email = data.contact_email + ? data.contact_email + : `${data.username}@placeholder.local`; + // real_name 兜底:不传时使用 contact_person(必填字段,长度 ≥ 2),避免 notEmpty + len[2,50] 校验报错 + const realName = data.real_name || data.contact_person; + + const registerResult = await ctx.service.systems.auth.user.register({ + username: data.username, + password: data.password, + email, + real_name: realName, + }, transaction); + const userId = registerResult.userId; + + // b. 创建货主 + const storeData = { + company_name: data.company_name, + business_license: data.business_license, + legal_person: data.legal_person || null, + contact_phone: data.contact_phone || '-', + contact_email: data.contact_email || null, + contact_person: data.contact_person, + address: data.address || null, + industry: data.industry || null, + account_id: userId, + status: 1, + created_by: accountId, + is_warehouse: 0, + auth_end: authEnd, + }; + + const store = await ctx.model.Store.create(storeData, { transaction }); + + // c. 创建签约关系(auth_status=2 已通过,仓库代开户无需审核) + const relationData = { + store_id: store.id, + warehouse_id: currentSubject.id, + auth_status: 2, + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000) || '仓库代开户', + apply_time: new Date(), + print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + print_quantity_locked: 0, + review_time: new Date(), + auth_start: authStart, + auth_end: authEnd, + actual_end: null, + applied_by: accountId, + reviewed_by: accountId, + ended_by: null, + warehouse_use_status: 1, + store_use_status: 1, + }; + + // store_remask 兜底:代开户未传货主备注名(或传空)时,默认取公司全称前 50 字符, + // 保证货主名称(签约表 store_remask 优先)在列表/导出中始终有值,与项目回退 company_name 口径一致 + relationData.store_remask = storeRemask + ? storeRemask + : String(store.company_name || '').slice(0, 50); + if (warehouseRemask !== null) { + relationData.warehouse_remask = warehouseRemask; + } + + const relation = await ctx.model.StoreWarehouse.create(relationData, { transaction }); + + // d. 分配货主管理员角色 + try { + await ctx.service.systems.store.assignAdminRoleToCreator( + store.id, + userId, + data.real_name || '', + transaction, + true + ); + } catch (roleErr) { + throw this.createError(`分配管理员角色失败: ${roleErr.message}`, 500); + } + + await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_OPEN_ACCOUNT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(currentSubject.id), + storeId: Number(store.id), + accountId: Number(userId), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.openAccount] 写入操作日志失败,不影响业务', logErr); + } + + return { + code: 200, + data: { + store_id: store.id, + account_id: userId, + contract_id: relation.id, + company_name: store.company_name, + username: data.username, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 为货主创建用户:按用户名查询账号,不存在则注册账号并返回随机生成的密码, + * 两种情况统一完成货主工号绑定与货主管理员角色(wms_role.id=5)授权,幂等执行。 + * 货主审核中(wms_store.status=2)时自动转为启用(1)。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} data.username 用户名(必填,3-50 位字母、数字或下划线)。 + * @param {number|string} data.store_id 货主 ID(必填)。 + * @return {Promise} 响应对象,data 包含 account_id、username、store_id、created; + * 仅新建账号时返回 password 明文密码。 + * @throws {Error} 参数缺失或格式非法时抛出 400,货主不存在时抛出 404, + * 货主管理员角色未初始化时抛出 500。 + */ + async createUser(data = {}) { + const { ctx } = this; + const { + username: rawUsername, + store_id: rawStoreId, + } = data; + + // 1. 校验必填参数 + const username = this.normalizeText(rawUsername, 'username', 50); + if (!username) { + throw this.createError('username 参数不能为空', 400); + } + if (!/^[a-zA-Z0-9_]{3,50}$/.test(username)) { + throw this.createError('用户名格式不合法,需为 3-50 位字母、数字或下划线', 400); + } + const storeId = this.toPositiveNumber(rawStoreId, 'store_id'); + + // 2. 校验货主存在(同时取 status 用于后续审核中状态修正) + const store = await ctx.model.Store.findOne({ + where: { id: storeId }, + attributes: [ 'id', 'status' ], + }); + if (!store) { + throw this.createError('货主不存在', 404); + } + + // 3. 查询账号是否存在 + const existingAccount = await ctx.model.Account.findOne({ + where: { username }, + attributes: [ 'id', 'username' ], + }); + + // 4. 随机生成密码(仅新建账号时使用) + const randomPassword = crypto.randomBytes(8).toString('base64').replace(/[+/=]/g, '') + .slice(0, 12); + + // 5. 事务内执行账号创建与授权绑定 + const transaction = await ctx.model.transaction(); + + try { + // 5.0 货主审核中(status=2)时自动转为启用(1),store 实例在事务外查询,更新时显式传入事务 + if (Number(store.status) === 2) { + await store.update({ status: 1 }, { transaction }); + } + + let accountId = null; + let created = false; + + if (existingAccount) { + // 账号已存在:不创建、不返回密码 + accountId = Number(existingAccount.id); + created = false; + } else { + // 账号不存在:复用注册服务,email/real_name 使用占位兜底 + const registerResult = await ctx.service.systems.auth.user.register({ + username, + password: randomPassword, + email: `${username}@placeholder.local`, + real_name: username, + }, transaction); + accountId = Number(registerResult.userId); + created = true; + } + + // 6. 货主工号绑定(幂等:已存在但 status=0 时恢复为 1) + const [ employee ] = await ctx.model.AccountStoreEmployee.findOrCreate({ + where: { + account_id: accountId, + store_id: storeId, + }, + defaults: { + account_id: accountId, + store_id: storeId, + status: 1, + real_name: username, + }, + transaction, + }); + + if (Number(employee.status) !== 1) { + await employee.update({ + status: 1, + }, { transaction }); + } + + // 7. 确认货主管理员角色(wms_role.id=5)已初始化 + const storeAdminRole = await ctx.model.Role.findByPk(5, { transaction }); + if (!storeAdminRole) { + throw this.createError('货主管理员角色(id=5)未初始化', 500); + } + + // 8. 授予货主管理员角色(幂等:findOrCreate) + await ctx.model.EmployeeRole.findOrCreate({ + where: { + employee_id: employee.id, + role_id: 5, + }, + defaults: { + employee_id: employee.id, + role_id: 5, + }, + transaction, + }); + + await transaction.commit(); + + // 9. 记录操作日志(不影响业务主流程) + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: storeId, + operationCode: 'STORE_CREATE_USER', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + storeId: Number(storeId), + accountId: Number(accountId), + created, + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.createUser] 写入操作日志失败,不影响业务', logErr); + } + + // 10. 组装响应:仅新建账号时返回明文密码 + const resultData = { + account_id: accountId, + username, + store_id: storeId, + created, + }; + if (created) { + resultData.password = randomPassword; + } + + return { + code: 200, + data: resultData, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } +} + +module.exports = SettingStoreWarehouseService; diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index b25a8e2..2213650 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -4,7 +4,6 @@ const Service = require('egg').Service; const COS = require('cos-nodejs-sdk-v5'); const path = require('path'); const crypto = require('crypto'); -const { v4: uuidv4 } = require('uuid'); const dayjs = require('dayjs'); class UploadService extends Service { @@ -12,8 +11,37 @@ class UploadService extends Service { super(ctx); this.initCOS(); } + + /** + * 获取腾讯云公共配置。 + * + * 说明:优先读取独立的腾讯云公共配置,若不存在则回退到兼容的 COS 配置, + * 以保证历史配置方式仍然可用。 + * + * @return {Object} 腾讯云公共配置对象 + */ + getTencentCloudConfig() { + const tencentCloudConfig = this.config.tencentCloud || {}; + const cosConfig = this.config.cos || {}; + + return { + appId: tencentCloudConfig.appId ?? cosConfig.appId, + secretId: tencentCloudConfig.secretId ?? cosConfig.secretId, + secretKey: tencentCloudConfig.secretKey ?? cosConfig.secretKey, + }; + } + + /** + * 获取 COS 产品配置。 + * + * @return {Object} COS 产品配置对象 + */ + getCosConfig() { + return this.config.cos || {}; + } + initCOS() { - const { secretId, secretKey } = this.config.cos; + const { secretId, secretKey } = this.getTencentCloudConfig(); this.cos = new COS({ SecretId: secretId, SecretKey: secretKey, @@ -23,13 +51,14 @@ class UploadService extends Service { /** * 获取上传参数 - 使用与PHP一致的算法 - * @param fileInfo + * @param {Object} fileInfo 上传参数对象 */ async getUploadParams(fileInfo) { const { ctx } = this; + const cosConfig = this.getCosConfig(); + const tencentCloudConfig = this.getTencentCloudConfig(); const warehouseId = ctx.user.store_id; - console.log('fileInfo', fileInfo); - const { fileName, fileType, fileSize, type, id, md5 } = fileInfo; + const { fileName, fileType, fileSize, type, md5 } = fileInfo; if (md5) { const existingFile = await ctx.model.File.findOne({ @@ -52,29 +81,46 @@ class UploadService extends Service { } } // 验证文件 - this.validateFileInfo({ fileName, fileType, fileSize }); + this.validateFileInfo({ fileName, fileSize }); const warehouse_quota = await this.app.model.query( - 'SELECT * FROM vw_warehouse_quota WHERE warehouse_id = :warehouseId', + `SELECT + s.id AS warehouse_id, + COALESCE(s.quota_bytes, 0) AS quota_bytes, + COALESCE(SUM(CASE WHEN f.is_deleted = 0 OR f.is_deleted IS NULL THEN f.file_size ELSE 0 END), 0) AS used_bytes, + GREATEST( + COALESCE(s.quota_bytes, 0) - COALESCE(SUM(CASE WHEN f.is_deleted = 0 OR f.is_deleted IS NULL THEN f.file_size ELSE 0 END), 0), + 0 + ) AS remaining_bytes + FROM wms_store s + LEFT JOIN wms_file f ON f.warehouse_id = s.id + WHERE s.id = :warehouseId + GROUP BY s.id, s.quota_bytes`, { replacements: { warehouseId }, type: this.app.model.QueryTypes.SELECT, } ); - const remaining_bytes = warehouse_quota[0].remaining_bytes; - if (remaining_bytes - fileSize < 0) { - return { - error: true, - msg: '空间配额已满', - }; + const warehouseQuota = Array.isArray(warehouse_quota) ? warehouse_quota[0] : null; + const remainingBytes = warehouseQuota ? Number(warehouseQuota.remaining_bytes) : NaN; + if (Number.isFinite(remainingBytes)) { + if (remainingBytes - fileSize < 0) { + return { + error: true, + msg: '空间配额已满', + }; + } + } else { + this.ctx.logger.warn( + `仓库配额查询结果无效,跳过配额拦截,warehouseId=${warehouseId}, quotaRow=${JSON.stringify(warehouseQuota)}` + ); } - console.log('空间计算剩余可用', remaining_bytes - fileSize); // 生成文件名 const cosFileName = this.generateFileName(fileName, fileType, type, md5); // 获取当前时间戳 const now = Math.floor(Date.now() / 1000); - const expire = now + this.config.cos.expire; + const expire = now + cosConfig.expire; const keyTime = `${now};${expire}`; // 使用与PHP一致的算法生成签名 @@ -83,11 +129,11 @@ class UploadService extends Service { // 构建返回参数 return { fileName: cosFileName, - uploadUrl: `https://${this.config.cos.bucket}.cos.${this.config.cos.region}.myqcloud.com`, - bucket: this.config.cos.bucket, - region: this.config.cos.region, + uploadUrl: `https://${cosConfig.bucket}.cos.${cosConfig.region}.myqcloud.com`, + bucket: cosConfig.bucket, + region: cosConfig.region, signature: { - secretId: this.config.cos.secretId, + secretId: tencentCloudConfig.secretId, signature, keyTime, key: cosFileName, @@ -97,7 +143,7 @@ class UploadService extends Service { key: cosFileName, policy, 'q-sign-algorithm': 'sha1', - 'q-ak': this.config.cos.secretId, + 'q-ak': tencentCloudConfig.secretId, 'q-sign-time': keyTime, 'q-key-time': keyTime, 'q-signature': signature, @@ -116,7 +162,7 @@ class UploadService extends Service { md5, }, // 有效期 - expires: this.config.cos.expire, + expires: cosConfig.expire, // 前端需要的额外参数 frontendConfig: this.getFrontendConfig(fileType, fileSize), isNew: true, @@ -127,12 +173,12 @@ class UploadService extends Service { * 生成策略和签名 - 与PHP算法完全一致 * 参考你的PHP代码: * $signature = hash_hmac('sha1', sha1($policy), hash_hmac('sha1', $keytime, $config['secretKey'])); - * @param key - * @param startTime - * @param expireTime + * @param {string} key 文件 key + * @param {number} startTime 开始时间戳 + * @param {number} expireTime 过期时间戳 */ generatePolicyAndSignature(key, startTime, expireTime) { - const { secretId, secretKey, bucket } = this.config.cos; + const { secretId, secretKey } = this.getTencentCloudConfig(); const keyTime = `${startTime};${expireTime}`; // 1. 生成策略 - 与PHP完全一致 @@ -165,12 +211,6 @@ class UploadService extends Service { const signature = outerHmac.digest('hex'); // 最终的签名 // 调试信息 - console.log('策略原始内容:', policyString); - console.log('策略Base64:', policyBase64); - console.log('keyTime:', keyTime); - console.log('signKey (内层HMAC):', signKey); - console.log('policyHash (SHA1):', policyHash); - console.log('signature (外层HMAC):', signature); return { policy: policyBase64, @@ -181,16 +221,30 @@ class UploadService extends Service { }; } /** - * 验证文件信息 - * @param root0 - * @param root0.fileName - * @param root0.fileType - * @param root0.fileSize + * 解析单次上传的文件大小上限。 + * 优先使用调用方传入的 options.maxSizeBytes,否则回退到 cos.maxsize 配置。 + * @param {Object} options 上传选项。 + * @return {number} 文件大小上限(字节)。 */ - validateFileInfo({ fileName, fileType, fileSize }) { - const { maxsize, mimetype } = this.config.cos; + resolveUploadMaxSizeBytes(options = {}) { + const requested = options && options.maxSizeBytes; + if (typeof requested === 'number' && Number.isFinite(requested) && requested > 0) { + return requested; + } - // 验证文件大小 + const { maxsize } = this.getCosConfig(); + return this.parseSizeToBytes(maxsize); + } + /** + * 验证文件信息 + * @param {Object} root0 文件信息对象 + * @param {string} root0.fileName 文件名 + * @param {number} root0.fileSize 文件大小 + */ + validateFileInfo({ fileName, fileSize }) { + const { maxsize, mimetype } = this.getCosConfig(); + + // 验证文件大小(使用 cos.maxsize 配置) const maxSizeBytes = this.parseSizeToBytes(maxsize); if (fileSize > maxSizeBytes) { throw new Error(`文件大小不能超过 ${this.formatFileSize(maxSizeBytes)}`); @@ -209,13 +263,13 @@ class UploadService extends Service { /** * 生成文件唯一名称 - * @param fileName - * @param fileType - * @param category - * @param md5 + * @param {string} fileName 原始文件名 + * @param {string} fileType 文件类型 + * @param {string} category 分类 + * @param {string} md5 文件 MD5 */ generateFileName(fileName, fileType, category = '', md5) { - const { savekey, dirs } = this.config.cos; + const { savekey, dirs } = this.getCosConfig(); const ext = path.extname(fileName); const name = path.basename(fileName, ext); const timestamp = dayjs().format('YYYYMMDDHHmmss'); @@ -243,14 +297,14 @@ class UploadService extends Service { .replace('{filemd5}', md5) .replace('{.suffix}', ext); - // 添加目录前缀并规范化路径 - const fullPath = path.posix.join(result).replace(/\/\//g, '/'); + // 添加目录前缀并规范化路径,去除前导 / 防止与 CDN 域名拼接时产生 // + const fullPath = path.posix.join(result).replace(/\/\//g, '/').replace(/^\/+/, ''); return fullPath; } /** * 解析文件大小字符串为字节数 - * @param sizeStr + * @param {string|number} sizeStr 文件大小字符串或字节数 */ parseSizeToBytes(sizeStr) { if (typeof sizeStr === 'number') { @@ -277,7 +331,7 @@ class UploadService extends Service { /** * 格式化文件大小 - * @param bytes + * @param {number} bytes 字节数 */ formatFileSize(bytes) { if (bytes === 0) return '0 B'; @@ -291,11 +345,11 @@ class UploadService extends Service { /** * 获取前端配置 - * @param fileType - * @param fileSize + * @param {string} fileType 文件类型 + * @param {number} fileSize 文件大小 */ getFrontendConfig(fileType, fileSize) { - const { chunkSize } = this.config.cos; + const { chunkSize } = this.getCosConfig(); return { useMultipart: fileSize > 5 * 1024 * 1024, @@ -310,11 +364,11 @@ class UploadService extends Service { /** * 服务器端上传文件 - * @param fileStream - * @param options + * @param {Object} fileStream 文件流对象 + * @param {Object} options 上传选项 */ async uploadFile(fileStream, options = {}) { - const { bucket, region } = this.config.cos; + const { bucket, region, uploadurl, cdnurl } = this.getCosConfig(); try { this.validateFile(fileStream, options); @@ -336,9 +390,9 @@ class UploadService extends Service { return { fileName, - cosUrl: `${this.config.cos.uploadurl}/${fileName}`, - cdnUrl: `${this.config.cos.cdnurl}/${fileName}`, - url: `${this.config.cos.cdnurl}/${fileName}`, + cosUrl: `${uploadurl}/${fileName}`, + cdnUrl: `${cdnurl}/${fileName}`, + url: `${cdnurl}/${fileName}`, etag: result.ETag, location: result.Location, uploadAt: new Date().toISOString(), @@ -349,16 +403,59 @@ class UploadService extends Service { } } + /** + * 服务器端上传 Buffer(小文件直传,如前端裁剪后的头像)。 + * + * @param {Buffer} buffer 文件内容 Buffer。 + * @param {Object} options 上传选项(key 必传或由 generateFileName 生成; + * maxSizeBytes 覆盖大小上限;mimetype 限定后缀)。 + * @return {Promise} 上传结果(fileName/url/cdnUrl/cosUrl/etag 等)。 + */ + async uploadBuffer(buffer, options = {}) { + const { bucket, region, uploadurl, cdnurl } = this.getCosConfig(); + if (!Buffer.isBuffer(buffer) || buffer.length === 0) { + throw new Error('上传内容为空'); + } + + const filename = options.filename || 'image.png'; + this.validateFile({ filename, fileSize: buffer.length }, options); + + const fileName = options.key || this.generateFileName( + filename, + options.mimeType || 'image/png', + options.category + ); + + const result = await this.cos.putObject({ + Bucket: bucket, + Region: region, + Key: fileName, + Body: buffer, + ContentLength: buffer.length, + }); + + return { + fileName, + cosUrl: `${uploadurl}/${fileName}`, + cdnUrl: `${cdnurl}/${fileName}`, + url: `${cdnurl}/${fileName}`, + etag: result.ETag, + location: result.Location, + uploadAt: new Date().toISOString(), + }; + } + /** * 验证文件 - * @param fileStream - * @param options + * @param {Object} fileStream 文件流对象 + * @param {Object} options 上传选项 */ validateFile(fileStream, options = {}) { - const { maxsize, mimetype } = this.config.cos; + const { mimetype } = this.getCosConfig(); const { filename, fileSize } = fileStream; - const maxSizeBytes = this.parseSizeToBytes(maxsize); + // 验证文件大小:单次上传可通过 options.maxSizeBytes 覆盖上限,否则使用 cos.maxsize 配置 + const maxSizeBytes = this.resolveUploadMaxSizeBytes(options); if (fileSize > maxSizeBytes) { throw new Error(`文件大小不能超过 ${this.formatFileSize(maxSizeBytes)}`); } @@ -388,7 +485,7 @@ class UploadService extends Service { */ async uploadSuccessNotify(data) { const { ctx } = this; - console.log('上传成功', data); + const cosConfig = this.getCosConfig(); try { // 从上下文获取用户信息(根据你的实际用户认证方式) const warehouseId = ctx.user?.store_id || ctx.query.warehouseId || ctx.request.body.warehouseId; @@ -400,32 +497,82 @@ class UploadService extends Service { this.ctx.logger.warn('上传成功通知缺少用户信息,使用默认值'); } + const resolvedFileKey = String(data.url || data.fileKey || '').replace(/^\/+/, ''); + const resolvedFileName = String(data.fileName || data.name || path.basename(resolvedFileKey || 'file')); + const resolvedFileSize = Number(data.fileSize || data.size || 0); + // 生成完整的访问URL - const fileUrl = `${this.config.cos.cdnurl || this.config.cos.uploadurl}/${data.url}`; + const fileUrl = `${cosConfig.cdnurl || cosConfig.uploadurl}/${resolvedFileKey}`; + + // 对外通知时对路径段做 URL 编码(保留 / 分隔符),兼容含中文文件名的历史记录 + const encodeFileUrl = rawUrl => { + const slashIdx = rawUrl.indexOf('/', rawUrl.indexOf('//') + 2); + if (slashIdx === -1) return rawUrl; + const base = rawUrl.slice(0, slashIdx); + const keyPart = rawUrl.slice(slashIdx + 1); + return `${base}/${keyPart.split('/').map(seg => encodeURIComponent(seg)).join('/')}`; + }; + const fileUrlEncoded = encodeFileUrl(fileUrl); // 计算哈希值(如果前端没有提供) - let md5Hash = data.md5; + let md5Hash = data.md5Hash || data.md5 || ''; + let sha1Hash = data.sha1Hash || data.sha1 || ''; if (!md5Hash && data.fileContent) { - // 如果有文件内容,可以计算哈希 md5Hash = crypto.createHash('md5').update(data.fileContent).digest('hex'); } + if (!sha1Hash && data.fileContent) { + sha1Hash = crypto.createHash('sha1').update(data.fileContent).digest('hex'); + } + + const resolvedFileType = String(data.fileType || data.category || data.type || 'document'); + const resolvedMimeType = String(data.mimeType || data.type || this.getMimeType(data.fileName || data.name || 'file.xlsx')); + const defaultExpireDays = data.businessType === 'receivingReport' ? 90 : 0; + const requestedExpireDays = Number(data.expireDays || defaultExpireDays || 0); + let resolvedExpireTime = data.expireTime || data.expire_time || null; + + if (!resolvedExpireTime && Number.isFinite(requestedExpireDays) && requestedExpireDays > 0) { + resolvedExpireTime = new Date(Date.now() + requestedExpireDays * 24 * 60 * 60 * 1000); + } + + if (resolvedExpireTime) { + const expireDate = resolvedExpireTime instanceof Date ? resolvedExpireTime : new Date(resolvedExpireTime); + resolvedExpireTime = Number.isNaN(expireDate.getTime()) ? null : expireDate; + } + + if (!md5Hash) { + const fallbackFingerprint = JSON.stringify({ + warehouseId: warehouseId || 0, + url: resolvedFileKey, + fileName: resolvedFileName, + fileSize: resolvedFileSize, + mimeType: resolvedMimeType, + }); + md5Hash = crypto.createHash('md5').update(fallbackFingerprint).digest('hex'); + } + + if (!sha1Hash) { + sha1Hash = crypto.createHash('sha1').update(`${md5Hash}:${resolvedFileKey || fileUrl}`).digest('hex'); + } + // 构建数据库记录 const fileRecord = { warehouse_id: warehouseId || 0, // 默认为0或使用默认仓库 - file_key: data.url, + file_key: resolvedFileKey, file_url: fileUrl, - file_name: data.name, - file_size: data.size, - file_type: data.type, - mime_type: data.type, - md5_hash: md5Hash || '', + file_name: resolvedFileName, + file_size: resolvedFileSize, + file_type: resolvedFileType, + mime_type: resolvedMimeType, + md5_hash: md5Hash, + sha1_hash: sha1Hash, storage_mode: 'cos', storage_class: 'standard', uploader_id: userId?.toString() || '0', uploader_name: userName, uploader_dept: data.uploaderDept || '', + expire_time: resolvedExpireTime || null, created_at: new Date(), }; @@ -440,12 +587,27 @@ class UploadService extends Service { }); if (existingFile) { + if (resolvedExpireTime && (!existingFile.expire_time || new Date(existingFile.expire_time).getTime() < resolvedExpireTime.getTime())) { + await existingFile.update({ + expire_time: resolvedExpireTime, + updated_at: new Date(), + }); + } + + if (data.businessType && data.businessId) { + await this.createFileReference(existingFile.id, data.businessType, data.businessId, { + warehouseId, + createdBy: userName, + }); + } + this.ctx.logger.info(`文件已存在,返回已有记录: ${existingFile.file_url}`); return { fileId: existingFile.id, - fileUrl: existingFile.file_url, + fileUrl: encodeFileUrl(existingFile.file_url), fileKey: existingFile.file_key, fileName: existingFile.file_name, + expireTime: resolvedExpireTime || existingFile.expire_time || null, isNew: false, }; } @@ -456,10 +618,13 @@ class UploadService extends Service { // 根据业务类型创建引用关系(如果需要) if (data.businessType && data.businessId) { - await this.createFileReference(savedFile.id, data.businessType, data.businessId); + await this.createFileReference(savedFile.id, data.businessType, data.businessId, { + warehouseId, + createdBy: userName, + }); } - this.ctx.logger.info(`文件记录保存成功: ${savedFile.id} - ${data.fileName}`); + this.ctx.logger.info(`文件记录保存成功: ${savedFile.id} - ${resolvedFileName}`); // 返回成功响应 return { @@ -467,11 +632,11 @@ class UploadService extends Service { message: '文件上传成功', data: { fileId: savedFile.id, - fileUrl, - fileKey: data.fileKey, - fileName: data.fileName, - fileSize: data.fileSize, - mimeType: data.mimeType, + fileUrl: fileUrlEncoded, + fileKey: resolvedFileKey, + fileName: resolvedFileName, + fileSize: resolvedFileSize, + mimeType: resolvedMimeType, isNew: true, createdAt: savedFile.created_at, }, @@ -499,7 +664,7 @@ class UploadService extends Service { /** * 根据文件名获取MIME类型 - * @param fileName + * @param {string} fileName 文件名 */ getMimeType(fileName) { const ext = path.extname(fileName).toLowerCase(); @@ -530,28 +695,68 @@ class UploadService extends Service { /** * 创建文件业务引用关系 - * @param fileId - * @param businessType - * @param businessId + * @param {number|string} fileId 文件 ID + * @param {string} businessType 业务类型 + * @param {number|string} businessId 业务 ID + * @param {Object} [options] 可选参数 + * @param {number|string} [options.warehouseId] 仓库 ID + * @param {string} [options.createdBy] 创建人 + * @param {number} [options.displayOrder] 显示顺序 */ - async createFileReference(fileId, businessType, businessId) { + async createFileReference(fileId, businessType, businessId, options = {}) { const { ctx } = this; try { - // 如果有文件引用模型 - if (ctx.model.FileReference) { - const reference = await ctx.model.FileReference.create({ - file_id: fileId, - business_type: businessType, - business_id: businessId, - created_at: new Date(), - }); - - this.ctx.logger.info(`文件引用关系创建成功: fileId=${fileId}, businessType=${businessType}, businessId=${businessId}`); - return reference; + if (!ctx.model.FileReference) { + return null; } - return null; + const warehouseId = Number( + options.warehouseId || ctx.user?.store_id || ctx.query.warehouseId || ctx.request.body.warehouseId || 0 + ) || 0; + const createdBy = String( + options.createdBy || ctx.user?.real_name || ctx.user?.username || ctx.user?.id || 'system' + ).trim() || 'system'; + const normalizedBusinessType = String(businessType || '').trim(); + const normalizedBusinessId = String(businessId || '').trim(); + const displayOrder = Number(options.displayOrder || 0) || 0; + + if (!fileId || !normalizedBusinessType || !normalizedBusinessId) { + this.ctx.logger.warn('创建文件引用关系参数不完整,已跳过', { + fileId, + businessType: normalizedBusinessType, + businessId: normalizedBusinessId, + }); + return null; + } + + if (typeof ctx.model.FileReference.findOne === 'function') { + const existingReference = await ctx.model.FileReference.findOne({ + where: { + file_id: fileId, + warehouse_id: warehouseId, + business_type: normalizedBusinessType, + business_id: normalizedBusinessId, + }, + }); + + if (existingReference) { + return existingReference; + } + } + + const reference = await ctx.model.FileReference.create({ + file_id: fileId, + warehouse_id: warehouseId, + business_type: normalizedBusinessType, + business_id: normalizedBusinessId, + display_order: displayOrder, + created_by: createdBy, + created_at: new Date(), + }); + + this.ctx.logger.info(`文件引用关系创建成功: fileId=${fileId}, businessType=${normalizedBusinessType}, businessId=${normalizedBusinessId}`); + return reference; } catch (error) { this.ctx.logger.error(`创建文件引用关系失败: ${error.message}`); return null; @@ -560,14 +765,14 @@ class UploadService extends Service { /** * 上传完成回调接口 - 供前端调用 - * @param callbackData + * @param {Object} callbackData 回调数据 */ async handleUploadCallback(callbackData) { const { ctx } = this; try { // 解析回调数据 - const { key, size, mimeType, etag, location, businessInfo } = callbackData; + const { key, size, mimeType, businessInfo } = callbackData; // 构建文件信息 const fileInfo = { diff --git a/app/service/systems/video_record_request.js b/app/service/systems/video_record_request.js new file mode 100644 index 0000000..b8d588c --- /dev/null +++ b/app/service/systems/video_record_request.js @@ -0,0 +1,826 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 业务类型:打包视频 */ +const BIZ_TYPE_PACK = 'pack'; +/** 业务类型:退件拆包视频 */ +const BIZ_TYPE_UNPACK = 'unpack'; + +/** + * 补录请求状态机。 + * pending(待推送) → requested(已推送) → recording(录制中) → completed(已完成) / failed(失败) + */ +const STATUS = Object.freeze({ + PENDING: 'pending', + REQUESTED: 'requested', + RECORDING: 'recording', + COMPLETED: 'completed', + FAILED: 'failed', +}); + +/** 在途状态(此状态内的请求不重复推送) */ +const ACTIVE_STATUSES = Object.freeze([ STATUS.PENDING, STATUS.REQUESTED, STATUS.RECORDING ]); + +/** 终态状态(已由 settleStatuses 收敛,等待 notifyResults 回信) */ +const TERMINAL_STATUSES = Object.freeze([ STATUS.COMPLETED, STATUS.FAILED ]); + +/** 超时失败原因前缀:settleStatuses 写入,notifyResults 据此区分回信文案 */ +const TIMEOUT_ERROR_PREFIX = '重新录制超时'; + +/** 幂等复用窗口:窗口内同一业务对象重复查询只复用已有请求,不重复推送(默认 10 分钟) */ +const REUSE_WINDOW_MS = 10 * 60 * 1000; + +/** 推送失败原因字段最大长度 */ +const ERROR_MAX_LENGTH = 500; + +/** + * 转人工通知的目标群:仓库群的客服群(warehouse/customer_service)。 + * 取值需与 app/service/inbox/groups.js 中 warehouse 的 subTypes 一致。 + */ +const MANUAL_HANDLING_SUB_TYPE = 'customer_service'; + +/** + * 视频补录请求服务层。 + * + * 场景:站内信查询"打包视频 / 退件拆包视频"时若视频不可用(无视频记录或全部 failed), + * 由本服务登记补录请求(状态机落库 wms_video_record_request)并向录制服务推送强制录制, + * 推送口径与 order.packing.forceRecord / returnUnpack.forceRecord 完全一致: + * 查录制电脑(wms_print_computer is_recording=true)→ 校验 Redis 在线键 → + * 重置视频记录为 created → POST {printService.url}/record/force。 + */ +class VideoRecordRequestService extends Service { + + /** + * 查询仓库的录制电脑(wms_print_computer is_recording=true)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 录制电脑行,找不到返回 null。 + */ + async _getRecordingComputer(warehouseId) { + const { ctx } = this; + const row = await ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + attributes: [ 'id', 'name', 'warehouse_id' ], + raw: true, + }); + return row || null; + } + + /** + * 校验录制电脑是否在线(与 forceRecord 相同的 Redis 在线键)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} computerId 录制电脑ID。 + * @return {Promise} 是否在线。 + */ + async _isComputerOnline(warehouseId, computerId) { + const { ctx } = this; + try { + const redisPrinter = ctx.app.redis.get('printer'); + const onlineInfo = await redisPrinter.get(`warehouse:${warehouseId}:printer:${computerId}`); + return Boolean(onlineInfo); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 录制电脑在线校验失败 wh=${warehouseId} cid=${computerId}: ${err.message}`); + return false; + } + } + + /** + * 重置视频记录为 created 并清空 video_url(与 forceRecord 同口径,触发重新录制)。 + * + * @param {string} bizType 业务类型 pack/unpack。 + * @param {number} bizId 业务ID(pack_task_id / unpack_id)。 + * @return {Promise} + */ + async _resetVideoRecords(bizType, bizId) { + const { ctx } = this; + if (bizType === BIZ_TYPE_UNPACK) { + await ctx.model.ReturnUnpackVideo.update( + { status: 'created', video_url: '' }, + { where: { unpack_id: bizId, deleted_at: null } } + ); + return; + } + await ctx.model.PackTaskVideo.update( + { status: 'created', video_url: '' }, + { where: { pack_task_id: bizId, deleted_at: null } } + ); + } + + /** + * 判断已有请求是否处于幂等复用窗口内。 + * + * @param {Object} row 请求记录行。 + * @return {boolean} true=窗口内(不重复推送)。 + */ + _withinReuseWindow(row) { + const base = row.last_request_at || row.updated_at; + if (!base) return false; + return Date.now() - new Date(base).getTime() < REUSE_WINDOW_MS; + } + + /** + * 标记请求推送失败(无录制电脑 / 电脑不在线 / 打印服务异常)。 + * + * @param {Object} params 参数。 + * @param {number} params.requestId 请求记录ID。 + * @param {string} params.error 失败原因。 + * @param {number|null} [params.computerId] 录制电脑ID。 + * @return {Promise} 统一的请求结果对象。 + */ + async _markFailed({ requestId, error, computerId = null }) { + const { ctx } = this; + const message = String(error || '推送强制录制失败').slice(0, ERROR_MAX_LENGTH); + await ctx.model.VideoRecordRequest.update( + { + status: STATUS.FAILED, + request_error: message, + print_computer_id: computerId, + last_request_at: new Date(), + remark: '视频不可用,推送强制录制失败', + }, + { where: { id: requestId } } + ); + return { request_id: requestId, status: STATUS.FAILED, pushed: false, reused: false, error: message }; + } + + /** + * 打包任务视频补录请求。 + * + * @param {Object} params 参数。 + * @param {number} params.warehouse_id 仓库ID。 + * @param {number} params.pack_task_id 打包任务ID(wms_pack_task.id)。 + * @param {string} [params.waybill_code] 触发查询的运单号。 + * @param {number} [params.store_id] 货主ID。 + * @param {string} [params.group_id] 触发查询的群ID。 + * @param {string} [params.group_name] 触发查询的群名称。 + * @param {string} [params.user_id] 触发查询的用户ID。 + * @param {string} [params.user_name] 触发查询的用户名称。 + * @param {string} [params.source] 触发来源。 + * @return {Promise} { request_id, status, pushed, reused, error }。 + */ + async requestPackVideo({ warehouse_id, pack_task_id, waybill_code = '', store_id = 0, group_id = '', group_name = '', user_id = '', user_name = '', source = 'inbox' } = {}) { + return this.requestFor({ + biz_type: BIZ_TYPE_PACK, + biz_id: pack_task_id, + warehouse_id, + waybill_code, + store_id, + group_id, + group_name, + user_id, + user_name, + source, + }); + } + + /** + * 退件拆包视频补录请求。 + * + * @param {Object} params 参数。 + * @param {number} params.warehouse_id 仓库ID。 + * @param {number} params.unpack_id 拆包单ID(wms_return_unpack.id)。 + * @param {string} [params.waybill_code] 触发查询的运单号。 + * @param {number} [params.store_id] 货主ID。 + * @param {string} [params.group_id] 触发查询的群ID。 + * @param {string} [params.group_name] 触发查询的群名称。 + * @param {string} [params.user_id] 触发查询的用户ID。 + * @param {string} [params.user_name] 触发查询的用户名称。 + * @param {string} [params.source] 触发来源。 + * @return {Promise} { request_id, status, pushed, reused, error }。 + */ + async requestUnpackVideo({ warehouse_id, unpack_id, waybill_code = '', store_id = 0, group_id = '', group_name = '', user_id = '', user_name = '', source = 'inbox' } = {}) { + return this.requestFor({ + biz_type: BIZ_TYPE_UNPACK, + biz_id: unpack_id, + warehouse_id, + waybill_code, + store_id, + group_id, + group_name, + user_id, + user_name, + source, + }); + } + + /** + * 通用补录请求:登记请求记录(状态机起点 pending)→ 推送录制服务 → 推进状态。 + * + * 幂等:同一仓库 + 业务对象在复用窗口内已有在途(pending/requested/recording)请求时直接复用, + * 不重复推送;超窗口或上次 failed 时复活同一条记录重新推送(避免同一业务对象堆积多条记录)。 + * + * @param {Object} params 参数。 + * @param {string} params.biz_type 业务类型 pack/unpack。 + * @param {number} params.biz_id 业务ID。 + * @param {number} params.warehouse_id 仓库ID。 + * @param {string} [params.waybill_code] 触发查询的运单号。 + * @param {number} [params.store_id] 货主ID。 + * @param {string} [params.group_id] 触发查询的群ID。 + * @param {string} [params.group_name] 触发查询的群名称。 + * @param {string} [params.user_id] 触发查询的用户ID。 + * @param {string} [params.user_name] 触发查询的用户名称。 + * @param {string} [params.source] 触发来源。 + * @return {Promise} { request_id, status, pushed, reused, error }。 + */ + async requestFor({ biz_type, biz_id, warehouse_id, waybill_code = '', store_id = 0, group_id = '', group_name = '', user_id = '', user_name = '', source = 'inbox' } = {}) { + const { ctx } = this; + + const bizType = biz_type === BIZ_TYPE_UNPACK ? BIZ_TYPE_UNPACK : BIZ_TYPE_PACK; + const bizId = Number(biz_id || 0); + const warehouseId = Number(warehouse_id || 0); + if (!bizId || !warehouseId) { + return { request_id: null, status: null, pushed: false, reused: false, error: '缺少业务ID或仓库上下文' }; + } + + // 触发查询的群/人员(供后续录制结果回发原群、@原用户) + const groupId = String(group_id || '').slice(0, 100); + const groupName = String(group_name || '').slice(0, 100); + const userId = String(user_id || '').slice(0, 100); + const userName = String(user_name || '').slice(0, 100); + + // 1. 幂等:查该业务对象最近一条请求记录 + const latest = await ctx.model.VideoRecordRequest.findOne({ + where: { warehouse_id: warehouseId, biz_type: bizType, biz_id: bizId, deleted_at: null }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + if (latest && latest.status !== STATUS.COMPLETED && this._withinReuseWindow(latest)) { + return { + request_id: latest.id, + status: latest.status, + pushed: false, + reused: true, + error: latest.request_error || null, + }; + } + + // 2. 写入请求记录(状态机起点 pending);已有未完成记录则复活复用 + let requestId = latest && latest.status !== STATUS.COMPLETED ? latest.id : null; + if (requestId) { + await ctx.model.VideoRecordRequest.update( + { + status: STATUS.PENDING, + store_id: Number(store_id || 0) || Number(latest.store_id || 0), + waybill_code: String(waybill_code || '') || latest.waybill_code, + group_id: groupId || latest.group_id, + group_name: groupName || latest.group_name, + user_id: userId || latest.user_id, + user_name: userName || latest.user_name, + source: source || latest.source, + print_computer_id: null, + request_error: null, + remark: '视频不可用,重新发起补录', + }, + { where: { id: requestId } } + ); + } else { + const created = await ctx.model.VideoRecordRequest.create({ + warehouse_id: warehouseId, + store_id: Number(store_id || 0), + biz_type: bizType, + biz_id: bizId, + waybill_code: String(waybill_code || ''), + group_id: groupId || null, + group_name: groupName || null, + user_id: userId || null, + user_name: userName || null, + source: source || 'inbox', + status: STATUS.PENDING, + request_count: 0, + remark: '视频不可用,自动发起补录', + }); + requestId = created && created.id; + } + + // 3. 录制电脑存在性 + 在线校验(不满足写入 failed,不阻断业务查询) + const computer = await this._getRecordingComputer(warehouseId); + if (!computer) { + return { ...(await this._markFailed({ requestId, error: '该仓库无录制电脑,无法推送重新录制' })), biz_type: bizType, biz_id: bizId }; + } + const online = await this._isComputerOnline(warehouseId, computer.id); + if (!online) { + return { + ...(await this._markFailed({ requestId, error: '录制电脑不在线,无法推送重新录制', computerId: computer.id })), + biz_type: bizType, + biz_id: bizId, + }; + } + + // 4. 重置视频记录为 created(与 forceRecord 一致) + try { + await this._resetVideoRecords(bizType, bizId); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 重置视频记录失败 biz=${bizType}:${bizId}: ${err.message}`); + } + + // 5. 推送录制服务(打印服务 /record/force) + const printServiceUrl = ctx.app.config.printService.url; + const requestData = bizType === BIZ_TYPE_UNPACK ? { unpack_id: bizId } : { pack_task_id: bizId }; + try { + const res = await ctx.curl(`${printServiceUrl}/record/force`, { + method: 'POST', + contentType: 'json', + data: requestData, + dataType: 'json', + timeout: 10000, + }); + if (res.status >= 400) { + return { + ...(await this._markFailed({ requestId, error: `录制服务返回 ${res.status}`, computerId: computer.id })), + biz_type: bizType, + biz_id: bizId, + }; + } + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 推送强制录制失败 biz=${bizType}:${bizId}: ${err.message}`); + return { + ...(await this._markFailed({ requestId, error: `通知录制服务失败: ${err.message}`, computerId: computer.id })), + biz_type: bizType, + biz_id: bizId, + }; + } + + // 6. 推送成功 → 状态推进为 requested(request_count 自增) + await ctx.model.VideoRecordRequest.update( + { + status: STATUS.REQUESTED, + request_count: ctx.app.Sequelize.literal('request_count + 1'), + last_request_at: new Date(), + print_computer_id: computer.id, + request_error: null, + remark: '视频不可用,已推送重新录制', + }, + { where: { id: requestId } } + ); + + ctx.logger.info(`[videoRecordRequest] 已推送重新录制 biz=${bizType}:${bizId} wh=${warehouseId} cid=${computer.id}`); + + return { request_id: requestId, status: STATUS.REQUESTED, pushed: true, reused: false, error: null, biz_type: bizType, biz_id: bizId }; + } + + /** + * 依据视频记录推进请求状态(查询命中视频时调用)。 + * + * 规则:有可用视频(video_url 非空且非 failed)→ completed; + * 有录制中记录 → recording;全部 failed → failed;其余保持不变。 + * + * 结果以视频原表为准,不回写 video_url(同一业务对象可能存在多路视频)。 + * + * @param {Object} params 参数。 + * @param {string} params.biz_type 业务类型 pack/unpack。 + * @param {number} params.biz_id 业务ID。 + * @param {Array} params.videos 视频记录数组(含 video_url/status)。 + * @return {Promise} { status, changed },无在途请求时返回 null。 + */ + async syncByVideos({ biz_type, biz_id, videos } = {}) { + const { ctx } = this; + const bizType = biz_type === BIZ_TYPE_UNPACK ? BIZ_TYPE_UNPACK : BIZ_TYPE_PACK; + const bizId = Number(biz_id || 0); + if (!bizId) return null; + + const list = Array.isArray(videos) ? videos.filter(Boolean) : []; + const { Op } = ctx.app.Sequelize; + + const row = await ctx.model.VideoRecordRequest.findOne({ + where: { + biz_type: bizType, + biz_id: bizId, + status: { [Op.in]: ACTIVE_STATUSES }, + deleted_at: null, + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + if (!row) return null; + + const available = list.find(v => v.video_url && v.status !== 'failed'); + let target = null; + if (available) target = STATUS.COMPLETED; + else if (list.some(v => v.status === 'recording')) target = STATUS.RECORDING; + else if (list.length > 0 && list.every(v => v.status === 'failed')) target = STATUS.FAILED; + + if (!target || target === row.status) return { status: row.status, changed: false }; + + const updates = { status: target }; + await ctx.model.VideoRecordRequest.update(updates, { where: { id: row.id } }); + + return { status: target, changed: true }; + } + + /** + * 状态收敛:把「在途」的补录请求推进为终态(completed / failed),不做任何通知。 + * + * 定时任务的第一步(先收敛状态、再统一通知),与通知步骤解耦: + * - 有可用视频且无仍在录制(或已超时)→ completed(超时窗口内仍缺摄像头时先交付已有的); + * - 视频记录全部 failed → failed(录制服务返回失败); + * - 超过 timeoutMs 仍无可用视频 → failed(超时); + * - 其余(仍在录制中且未超时)→ 本轮不动,等下一轮; + * - 记录缺少 warehouse_id / biz_id(永远无法处理)→ failed,避免每分钟占用扫描窗口。 + * + * 说明:一个打包任务 / 拆包单可能对应多路摄像头视频(多条 wms_*_video 记录), + * 因此以视频原表为准:有可用视频即算成功,权威视频列表由查询链路输出(见 notifyResults)。 + * + * @param {Object} [options] 参数。 + * @param {number} [options.limit] 单轮处理条数上限,默认取 config.inbox.videoRecordNotifyLimit(10)。 + * @param {number} [options.timeoutMs] 超时阈值(毫秒),默认取 config.inbox.videoRecordNotifyTimeoutMs(1 小时)。 + * @return {Promise} { scanned, completed, failed, timeout, invalid, skipped }。 + */ + async settleStatuses(options = {}) { + const { ctx } = this; + const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {}; + const limit = Math.max(1, Number(options.limit) || Number(inboxConfig.videoRecordNotifyLimit) || 10); + const timeoutMs = Math.max( + 0, + Number(options.timeoutMs) || Number(inboxConfig.videoRecordNotifyTimeoutMs) || 60 * 60 * 1000 + ); + const { Op } = ctx.app.Sequelize; + + const rows = await ctx.model.VideoRecordRequest.findAll({ + where: { + status: { [Op.in]: ACTIVE_STATUSES }, + is_notified: 0, + deleted_at: null, + }, + // last_request_at 是组合索引 idx_status_notified_last_request 的第三列,按它排序可避免 filesort + order: [[ 'last_request_at', 'ASC' ], [ 'id', 'ASC' ]], + limit, + raw: true, + }); + + const stat = { scanned: rows.length, completed: 0, failed: 0, timeout: 0, invalid: 0, skipped: 0 }; + + for (const row of rows) { + try { + const warehouseId = Number(row.warehouse_id || 0); + const bizId = Number(row.biz_id || 0); + if (!warehouseId || !bizId) { + // 关键字段缺失 → 永远无法处理,直接收敛为失败,避免每分钟占用扫描窗口 + await ctx.model.VideoRecordRequest.update( + { status: STATUS.FAILED, request_error: '记录缺少仓库/业务对象,无法处理' }, + { where: { id: row.id } } + ); + stat.invalid += 1; + continue; + } + + // 1. 读视频记录(打包/拆包分表) + const videos = row.biz_type === BIZ_TYPE_UNPACK + ? await ctx.model.ReturnUnpackVideo.findAll({ + attributes: [ 'id', 'video_url', 'status' ], + where: { unpack_id: bizId, deleted_at: null }, + raw: true, + }) + : await ctx.model.PackTaskVideo.findAll({ + attributes: [ 'id', 'video_url', 'status' ], + where: { pack_task_id: bizId, deleted_at: null }, + raw: true, + }); + const list = Array.isArray(videos) ? videos : []; + const statusOf = v => String(v.status || ''); + // 多路视频:需"有可用视频 且 无仍在录制",避免只出一路就误判完成 + const hasAvailable = list.some(v => v.video_url && statusOf(v) !== 'failed'); + const hasRecording = list.some(v => statusOf(v) === 'recording'); + const allFailed = list.length > 0 && list.every(v => statusOf(v) === 'failed'); + + // 2. 超时判定(以最近一次请求时间为准) + const base = row.last_request_at || row.updated_at || row.created_at; + const ageMs = base ? Date.now() - new Date(base).getTime() : 0; + const timedOut = timeoutMs > 0 && ageMs >= timeoutMs; + + let updates = null; + if (hasAvailable && (!hasRecording || timedOut)) { + updates = { + status: STATUS.COMPLETED, + request_error: hasRecording ? '部分摄像头仍在录制,已先交付可用视频' : null, + }; + stat.completed += 1; + } else if (allFailed) { + updates = { status: STATUS.FAILED, request_error: '录制服务返回失败' }; + stat.failed += 1; + } else if (timedOut) { + updates = { + status: STATUS.FAILED, + request_error: `${TIMEOUT_ERROR_PREFIX}(${Math.round(timeoutMs / 60000)} 分钟)未产出视频`, + }; + stat.timeout += 1; + } else { + // 仍在录制中且未超时:等下一轮 + stat.skipped += 1; + continue; + } + + await ctx.model.VideoRecordRequest.update(updates, { where: { id: row.id } }); + ctx.logger.info( + `[videoRecordRequest] 补录状态收敛 id=${row.id} biz=${row.biz_type}:${bizId} status=${updates.status}` + ); + } catch (err) { + stat.skipped += 1; + ctx.logger.warn(`[videoRecordRequest] 补录状态收敛失败 id=${row.id}: ${err.message}`); + } + } + + return stat; + } + + /** + * 补录结果通知:扫描「已收敛为终态且未通知」的补录请求,回信到原群(失败时转人工)。 + * + * 前置条件:状态已由 settleStatuses 收敛为 completed / failed; + * 本方法不再读视频表、也不再做超时判定,只负责取文案 + 回信 + 转人工。 + * + * 处理规则(每轮最多 limit 条,按 last_request_at 升序): + * - status=completed → 复用「原查询链路」文案(queryPackVideo / queryReturn 的输出, + * 含全部视频地址与拆包明细)回信;取不到文案时不标记,下一轮重试; + * - status=failed → 回「已转人工处理」,同时向仓库群的客服群推人工处理通知; + * - 无群信息 → 仍标记 is_notified=1(remark 说明)避免卡死扫描窗口; + * - 回信抛错 → 不标记,下一轮重试。 + * + * 回信对象优先用记录里存下的群/人员(writeOutboundReply 定向回原用户); + * 缺少用户信息时退化为群系统通知(pushSystemNotification)。 + * + * @param {Object} [options] 参数。 + * @param {number} [options.limit] 单轮处理条数上限,默认取 config.inbox.videoRecordNotifyLimit(10)。 + * @return {Promise} { scanned, notified, completed, failed, timeout, skipped }。 + */ + async notifyResults(options = {}) { + const { ctx } = this; + const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {}; + const limit = Math.max(1, Number(options.limit) || Number(inboxConfig.videoRecordNotifyLimit) || 10); + const { Op } = ctx.app.Sequelize; + + const rows = await ctx.model.VideoRecordRequest.findAll({ + where: { + status: { [Op.in]: TERMINAL_STATUSES }, + is_notified: 0, + deleted_at: null, + }, + // last_request_at 是组合索引 idx_status_notified_last_request 的第三列,按它排序可避免 filesort + order: [[ 'last_request_at', 'ASC' ], [ 'id', 'ASC' ]], + limit, + raw: true, + }); + + const stat = { scanned: rows.length, notified: 0, completed: 0, failed: 0, timeout: 0, skipped: 0 }; + + for (const row of rows) { + try { + const waybill = row.waybill_code || '-'; + let content = null; + // 非空表示本条需转人工(failed),由仓库群的客服群邀请真人接手 + let manualReason = null; + + if (row.status === STATUS.COMPLETED) { + // 录制成功:按「原查询链路」取结果文案,与用户自己发一次查询看到的完全一致 + const message = await this._buildResultMessage(row); + if (!message) { + // 取不到结果文案:本轮不标记,下一轮重试 + stat.skipped += 1; + continue; + } + content = message; + stat.completed += 1; + } else { + const isTimeout = String(row.request_error || '').startsWith(TIMEOUT_ERROR_PREFIX); + content = `【视频补录${isTimeout ? '超时' : '失败'}】\n运单号:${waybill}\n已转人工处理,请稍后留意群内回复`; + manualReason = row.request_error || '录制服务返回失败'; + if (isTimeout) stat.timeout += 1; + stat.failed += 1; + } + + // 回信到原群(失败时不标记,下一轮重试;无群信息时标记避免卡住扫描窗口) + const updates = { is_notified: 1, notified_at: new Date() }; + const sent = await this._replyResult(row, content); + if (sent) { + if (manualReason) updates.remark = '已转人工处理'; + await ctx.model.VideoRecordRequest.update(updates, { where: { id: row.id } }); + stat.notified += 1; + ctx.logger.info( + `[videoRecordRequest] 补录结果已通知 id=${row.id} biz=${row.biz_type}:${row.biz_id} status=${row.status}` + ); + // 失败/超时:额外邀请仓库客服群真人接手 + if (manualReason) { + await this._notifyManualHandling(row, manualReason); + } + } else { + await ctx.model.VideoRecordRequest.update( + { ...updates, remark: '无群信息,未推送通知' }, + { where: { id: row.id } } + ); + stat.skipped += 1; + ctx.logger.warn(`[videoRecordRequest] 补录结果无群信息未通知 id=${row.id} waybill=${waybill}`); + } + } catch (err) { + stat.skipped += 1; + ctx.logger.warn(`[videoRecordRequest] 补录结果通知处理失败 id=${row.id}: ${err.message}`); + } + } + + return stat; + } + + /** + * 复用「原查询链路」取结果文案(录制成功后回原链路取值)。 + * + * - 打包:调 inbox.functions `queryPackVideo(keyword=运单号)`,与用户发“打包视频+运单号”同一条链路; + * - 拆包:调 inbox.functions `queryReturn(waybill_code=运单号)`,与用户发“查退回+运单号”同一条链路。 + * + * 这两个函数是站内信函数注册表里的原实现,因此输出(含多路视频地址、拆包明细等)与用户主动查询完全一致; + * 由于可用性/货主鉴权依赖 inboxContext,这里按补录记录里存的群/人员临时还原上下文,用后恢复。 + * + * @param {Object} row 补录请求记录。 + * @return {Promise} 查询链路产出的模板文案,取不到时返回 null。 + */ + async _buildResultMessage(row) { + const { ctx } = this; + const waybill = String(row.waybill_code || '').trim(); + if (!waybill) return null; + + const functionsSvc = ctx.service.inbox && ctx.service.inbox.functions; + if (!functionsSvc || typeof functionsSvc.callFunction !== 'function') { + ctx.logger.warn('[videoRecordRequest] inbox.functions 不可用,无法按原查询链路取结果'); + return null; + } + + const warehouseId = Number(row.warehouse_id || 0); + const groupId = String(row.group_id || '').trim(); + let groupRow = null; + if (groupId) { + try { + groupRow = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_id', 'group_name', 'group_type', 'sub_type' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 查群信息失败 group=${groupId}: ${err.message}`); + } + } + + const prevContext = ctx.inboxContext; + ctx.inboxContext = { + warehouse_id: warehouseId, + store_id: Number(row.store_id || 0) || null, + group_id: groupId || null, + group_name: String(row.group_name || '').trim() || (groupRow && groupRow.group_name) || null, + user_id: String(row.user_id || '').trim() || null, + user_name: String(row.user_name || '').trim() || null, + group_type: (groupRow && groupRow.group_type) || null, + sub_type: (groupRow && groupRow.sub_type) || null, + }; + + try { + const result = row.biz_type === BIZ_TYPE_UNPACK + ? await functionsSvc.callFunction('queryReturn', { waybill_code: waybill }) + : await functionsSvc.callFunction('queryPackVideo', { keyword: waybill }); + if (!result || result.success === false) { + ctx.logger.warn( + `[videoRecordRequest] 原查询链路取结果失败 waybill=${waybill}: ${(result && result.error) || 'unknown'}` + ); + return null; + } + const message = result.data && result.data.message ? String(result.data.message).trim() : ''; + return message || null; + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 原查询链路取结果异常 waybill=${waybill}: ${err.message}`); + return null; + } finally { + ctx.inboxContext = prevContext; + } + } + + /** + * 失败/超时转人工:向仓库群的客服群推系统通知,邀请真人接手。 + * + * 群范围:wms_inbox_group 中同仓库 `group_type='warehouse'` 且 `sub_type='customer_service'`(客服) + * 的未屏蔽群;未命中时不外发,仅记 warn 日志(不退化发送到其他仓库群,避免误扰)。 + * + * @param {Object} row 补录请求记录。 + * @param {string} reason 需人工处理的原因(录制失败 / 超时)。 + * @return {Promise} 已通知的内部群数量。 + */ + async _notifyManualHandling(row, reason) { + const { ctx } = this; + const warehouseId = Number(row.warehouse_id || 0); + const processor = ctx.service.inbox && ctx.service.inbox.processor; + if (!warehouseId || !processor || typeof processor.pushSystemNotification !== 'function') return 0; + + let groups = []; + try { + groups = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id', 'group_name', 'sub_type', 'ext_data' ], + where: { + warehouse_id: warehouseId, + group_type: 'warehouse', + sub_type: MANUAL_HANDLING_SUB_TYPE, + is_blocked: 0, + }, + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 查仓库客服群失败 wh=${warehouseId}: ${err.message}`); + return 0; + } + + if (!Array.isArray(groups) || groups.length === 0) { + ctx.logger.warn( + `[videoRecordRequest] 仓库 ${warehouseId} 未配置客服群(warehouse/${MANUAL_HANDLING_SUB_TYPE}),转人工通知未发出 waybill=${row.waybill_code || '-'}` + ); + return 0; + } + + const bizLabel = row.biz_type === BIZ_TYPE_UNPACK ? '退件拆包视频' : '打包视频'; + const content = [ + '【视频补录需人工处理】', + `运单号:${row.waybill_code || '-'}`, + `类型:${bizLabel}`, + `仓库:${warehouseId}`, + `原因:${reason || '录制未成功'}`, + '请核实录制电脑/摄像头后人工处理,并回原群同步结果', + ].join('\n'); + + let notified = 0; + for (const g of groups) { + if (!g || !g.group_id) continue; + processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content, + ext_data: g.ext_data || null, + store_id: null, + }); + notified += 1; + } + + ctx.logger.info( + `[videoRecordRequest] 已邀请人工处理 waybill=${row.waybill_code || '-'} groups=${notified} reason=${reason}` + ); + return notified; + } + + /** + * 把补录结果回信到原群。 + * + * 有用户信息时走 writeOutboundReply(定向回原用户);否则退化到 pushSystemNotification(群提醒)。 + * 群名与渠道扩展信息优先从 wms_inbox_group 现查,缺失时用补录记录里的快照值。 + * + * @param {Object} row 补录请求记录。 + * @param {string} content 回信内容。 + * @return {Promise} 是否已发起回信(无群信息时返回 false)。 + */ + async _replyResult(row, content) { + const { ctx } = this; + const warehouseId = Number(row.warehouse_id || 0); + const groupId = String(row.group_id || '').trim(); + const processor = ctx.service.inbox && ctx.service.inbox.processor; + if (!groupId || !processor) return false; + + let groupRow = null; + try { + groupRow = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_id', 'group_name', 'store_id', 'ext_data' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 查询群信息失败 group=${groupId}: ${err.message}`); + } + + const groupName = String(row.group_name || (groupRow && groupRow.group_name) || '').trim(); + if (!groupName) return false; + + const storeId = Number(row.store_id || 0) || Number(groupRow && groupRow.store_id) || null; + const extData = (groupRow && groupRow.ext_data) || null; + const userId = String(row.user_id || '').trim(); + const userName = String(row.user_name || '').trim(); + + if (userId && userName && typeof processor.writeOutboundReply === 'function') { + await processor.writeOutboundReply({ + warehouse_id: warehouseId, + group_id: groupId, + group_name: groupName, + user_id: userId, + user_name: userName, + store_id: storeId, + ext_data: extData, + ext_id: `video:record:${row.id}`, + }, content, 'ai_reply'); + return true; + } + + processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: groupId, + group_name: groupName, + content, + ext_data: extData, + store_id: storeId, + }); + return true; + } +} + +module.exports = VideoRecordRequestService; diff --git a/app/service/systems/warehouseNotify.js b/app/service/systems/warehouseNotify.js new file mode 100644 index 0000000..026ac7d --- /dev/null +++ b/app/service/systems/warehouseNotify.js @@ -0,0 +1,572 @@ +'use strict'; + +const { Service } = require('egg'); +const crypto = require('crypto'); +const { normalizeExtDataSource } = require('../../lib/inbox_channel'); + +/** 仓库接口类型 ID(interface_type_id=3) */ +const WAREHOUSE_INTERFACE_TYPE_ID = 3; +/** 请求超时(毫秒) */ +const REQUEST_TIMEOUT_MS = 10000; +/** 日志内容长度上限 */ +const LOG_BODY_MAX = 65535; + +/** + * 仓库接口消息推送服务(出站方向:WMS → 外部系统)。 + * 复用仓库开放接口出站协议(MD5 签名 + ApiApp.callback_url), + * 供统一通知服务与 inbox 回执复用同一套发送与日志链路。 + */ +class WarehouseNotifyService extends Service { + /** + * 截断日志内容到上限长度。 + * @param {*} value 原始值。 + * @return {string} 截断后的字符串。 + */ + truncateLogBody(value) { + const str = typeof value === 'string' ? value : JSON.stringify(value || ''); + if (str.length > LOG_BODY_MAX) { + return str.substring(0, LOG_BODY_MAX); + } + return str; + } + + /** + * 获取仓库 ApiApp 回调配置(URL + 签名凭证)。 + * 兼容旧调用:默认取承接 notify.reply 的首个应用。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调配置。 + */ + async getCallbackConfig(warehouseId) { + return await this.getCallbackConfigByMethod(warehouseId, 'notify.reply'); + } + + /** + * 按 method 获取仓库 ApiApp 回调配置(取候选列表中首个应用)。 + * @param {number} warehouseId 仓库 ID。 + * @param {string} method 出站 method(如 notify.reply)。 + * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调配置。 + */ + async getCallbackConfigByMethod(warehouseId, method) { + const list = await this.listCallbackConfigs(warehouseId, method); + const first = list[0] || {}; + return { + url: first.url || null, + appKey: first.appKey || null, + appSecret: first.appSecret || null, + }; + } + + /** + * 判断应用的 callback_functions 是否承接指定 method(兼容 JSON 字符串形式)。 + * @param {*} callbackFunctions 应用承接的 method 列表(数组或 JSON 字符串)。 + * @param {string} method 目标 method。 + * @return {boolean} 是否承接。 + */ + containsCallbackMethod(callbackFunctions, method) { + let list = callbackFunctions; + if (typeof list === 'string') { + try { + list = JSON.parse(list); + } catch (error) { + list = null; + } + } + if (!Array.isArray(list)) return false; + const methodStr = String(method || '').trim(); + return list.map(item => String(item || '').trim()).includes(methodStr); + } + + /** + * 查询仓库下承接指定 method 的全部回调候选应用(按 id 升序)。 + * callback_functions 为空/未勾选的应用不承接任何回调(不放行)。 + * @param {number} warehouseId 仓库 ID。 + * @param {string} method 出站 method。 + * @return {Promise>} 候选列表。 + */ + async listCallbackConfigs(warehouseId, method) { + const { ctx } = this; + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return []; + } + + const apiAppModel = ctx.model && ctx.model.ApiApp; + if (!apiAppModel || typeof apiAppModel.findAll !== 'function') { + return []; + } + + try { + const rows = await apiAppModel.findAll({ + attributes: [ 'id', 'callback_url', 'self_app_key', 'self_app_secret', 'callback_functions' ], + where: { + warehouse_id: warehouseId, + interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, + is_enabled: 1, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return rows + .filter(row => this.containsCallbackMethod(row.callback_functions, method)) + .map(row => ({ + appId: Number(row.id), + url: row.callback_url || null, + appKey: row.self_app_key || null, + appSecret: row.self_app_secret || null, + })); + } catch (error) { + ctx.logger.warn(`[warehouseNotify] 查询回调配置列表失败: ${error.message}`); + return []; + } + } + + /** + * 按来源应用收敛候选:来源应用承接时只发给它,避免多应用错投; + * 来源缺失或未承接时保持原有候选顺序(兼容旧行为)并记录告警。 + * @param {Array} candidates 候选应用列表(含 appKey)。 + * @param {string|null} preferredAppKey 期望的目标应用 AppKey。 + * @param {number} warehouseId 仓库 ID。 + * @return {Array} 收敛后的候选列表。 + */ + orderCandidatesBySource(candidates, preferredAppKey, warehouseId) { + const list = Array.isArray(candidates) ? candidates : []; + if (list.length <= 1) return list; + + const appKey = String(preferredAppKey || '').trim(); + if (!appKey) { + this.ctx.logger.warn( + `[warehouseNotify] 无法确定来源应用,按候选顺序尝试 warehouse=${warehouseId} candidates=${list.length}` + ); + return list; + } + + const matched = list.filter(item => String(item.appKey || '').trim() === appKey); + if (matched.length > 0) return matched; + + this.ctx.logger.warn( + `[warehouseNotify] 来源应用未承接回调,按候选顺序兜底 warehouse=${warehouseId} source_app=${appKey} candidates=${list.length}` + ); + return list; + } + + /** + * 读取群的创建来源应用 AppKey(仅 source_type='api' 时有效)。 + * @param {string} groupId 外部群 ID。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 来源应用 AppKey。 + */ + async resolveGroupSourceAppKey(groupId, warehouseId) { + const { ctx } = this; + const groupIdStr = String(groupId || '').trim(); + if (!groupIdStr || !Number(warehouseId)) return null; + + try { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'source_type', 'source_extra' ], + where: { group_id: groupIdStr, warehouse_id: Number(warehouseId) }, + raw: true, + }); + if (!group || String(group.source_type || '') !== 'api') return null; + return String(group.source_extra || '').trim() || null; + } catch (error) { + ctx.logger.warn(`[warehouseNotify] 查询群来源失败: ${error.message}`); + return null; + } + } + + /** + * 计算 MD5 签名:MD5(appSecret + timestamp + bodyJson)。 + * @param {Object} options 签名参数。 + * @param {string} options.appSecret 应用密钥。 + * @param {number} options.timestamp Unix 秒时间戳。 + * @param {string} options.bodyJson 请求体 JSON 字符串。 + * @return {string} 签名 hex。 + */ + buildSignature({ appSecret, timestamp, bodyJson }) { + return appSecret + ? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex') + : ''; + } + + /** + * 写入仓库接口日志(失败仅记日志不抛出)。 + * @param {Object} options 日志参数。 + * @param {string} [options.appKey] API 应用 AppKey。 + * @param {string} [options.method] 请求方法名。 + * @param {number} [options.warehouseId] 仓库 ID。 + * @param {string} [options.url] 请求 URL。 + * @param {number} [options.httpStatus] HTTP 状态码。 + * @param {*} [options.body] 请求体。 + * @param {*} [options.result] 响应体。 + * @param {number} [options.useTime] 耗时(毫秒)。 + * @return {Promise} + */ + async writeLog({ + appKey, + method, + warehouseId, + url, + httpStatus, + body, + result, + useTime, + } = {}) { + const { ctx } = this; + const logModel = ctx.model && ctx.model.WarehouseLog; + if (!logModel || typeof logModel.create !== 'function') { + return; + } + + try { + await logModel.create({ + log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), + app_key: appKey || null, + method, + warehouse_id: warehouseId || null, + url: url || null, + http_status: httpStatus || null, + body: this.truncateLogBody(body), + result: this.truncateLogBody(result), + use_time: useTime || null, + created_at: new Date(), + }); + } catch (logErr) { + ctx.logger.error('[warehouseNotify] 日志写入失败: ' + logErr.message); + } + } + + /** + * 单次回调推送尝试(复用 MD5 签名 + POST 协议,成功/失败均写日志)。 + * @param {Object} options 尝试参数。 + * @param {Object} options.config 候选应用 { appId, url, appKey, appSecret }。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {string} options.method 出站 method。 + * @param {Object} options.body 请求体。 + * @return {Promise} 单次结果 { success, appId, httpStatus, response, error }。 + */ + async pushOnce({ config, warehouseId, method, body }) { + const { ctx } = this; + const bodyJson = JSON.stringify(body); + const timestamp = Math.floor(Date.now() / 1000); + const sign = this.buildSignature({ + appSecret: config.appSecret, + timestamp, + bodyJson, + }); + + const queryString = [ + `app_key=${encodeURIComponent(config.appKey || '')}`, + `method=${encodeURIComponent(method)}`, + `timestamp=${timestamp}`, + `sign=${encodeURIComponent(sign)}`, + ].join('&'); + const separator = config.url.includes('?') ? '&' : '?'; + const url = `${config.url}${separator}${queryString}`; + const startTime = Date.now(); + + try { + const curlResult = await ctx.curl(url, { + method: 'POST', + dataType: 'json', + contentType: 'json', + data: body, + headers: { 'Content-Type': 'application/json' }, + timeout: REQUEST_TIMEOUT_MS, + }); + + // HTTP 200 且 body.code=200(或未返回 code)→ 推送成功 + const pushOk = curlResult && curlResult.status === 200 + && (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200); + + await this.writeLog({ + appKey: config.appKey, + method, + warehouseId, + url, + httpStatus: curlResult ? curlResult.status : null, + body: bodyJson, + result: curlResult ? curlResult.data || {} : {}, + useTime: Date.now() - startTime, + }); + + return { + success: pushOk, + appId: config.appId, + httpStatus: curlResult ? curlResult.status : null, + response: curlResult ? (curlResult.data || null) : null, + error: pushOk ? null : '回调返回非200或code非200', + }; + } catch (error) { + await this.writeLog({ + appKey: config.appKey, + method, + warehouseId, + url, + httpStatus: null, + body: bodyJson, + result: 'Error: ' + error.message, + useTime: Date.now() - startTime, + }); + + return { + success: false, + appId: config.appId, + httpStatus: null, + response: null, + error: error.message, + }; + } + } + + /** + * 向仓库 ApiApp 回调地址推送消息(MD5 签名 + POST)。 + * 路由规则:查承接该 method 的全部候选应用(按 id 升序)逐个尝试, + * 第一个成功即返回;全部失败返回失败且不改动任何接口配置。 + * 传入 preferredAppKey 时优先只发给该应用(来源亲和),避免多应用场景错投。 + * @param {Object} options 推送参数。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {string} [options.method='notify.reply'] 出站 method。 + * @param {Object} [options.data={}] 消息数据(包裹在 body.data 中)。 + * @param {string} [options.preferredAppKey=null] 期望的目标应用 AppKey。 + * @return {Promise} 推送结果(含 attempts 明细)。 + */ + async push({ warehouseId, method = 'notify.reply', data = {}, preferredAppKey = null } = {}) { + const { ctx } = this; + const methodStr = String(method || '').trim() || 'notify.reply'; + + const candidates = this.orderCandidatesBySource( + await this.listCallbackConfigs(warehouseId, methodStr), + preferredAppKey, + warehouseId + ); + if (candidates.length === 0) { + ctx.logger.info(`[warehouseNotify] 仓库 ${warehouseId} 无应用承接回调 method=${methodStr},跳过推送`); + return { + success: false, + skipped: true, + reason: '无应用承接该回调 method(callback_functions 未勾选或应用未启用)', + warehouseId, + method: methodStr, + attempts: [], + }; + } + + const body = { code: 200, data }; + const attempts = []; + for (const config of candidates) { + const attempt = await this.pushOnce({ config, warehouseId, method: methodStr, body }); + attempts.push(attempt); + if (attempt.success) { + return { + success: true, + skipped: false, + warehouseId, + method: methodStr, + appId: config.appId, + httpStatus: attempt.httpStatus, + response: attempt.response, + attempts, + }; + } + } + + ctx.logger.warn(`[warehouseNotify] 仓库 ${warehouseId} method=${methodStr} 全部 ${candidates.length} 个候选应用尝试失败`); + return { + success: false, + skipped: false, + warehouseId, + method: methodStr, + attempts, + error: `全部 ${candidates.length} 个回调应用尝试失败`, + }; + } + + /** + * 向指定群(可选)与成员(可选)推送系统级业务通知(复用 notify.reply,type=system)。 + * 对方接口只处理 content 内容,推送体仅保留协议必需字段: + * type / content / ext_id / group_id / group_name / user_id / timestamp。 + * 推送前写入 wms_inbox_message(direction=outbound,source_type=system), + * 推送后按结果回写 push_status(2=已送达 / 3=失败)与 push_response。 + * 幂等去重:同 ext_id 的消息已送达(push_status=2)时直接跳过推送, + * 避免定时任务宽限窗口重复执行/多实例并发导致同一群重复收到相同通知; + * 未送达(0/1/3)时复用同一消息记录重推。 + * + * 向后兼容:不传 userIds 且传入 group 时,行为与旧版本完全一致 + * (校验、幂等 ext_id、落库字段、推送体均不变)。 + * + * @param {Object} options 推送参数。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {number} [options.storeId] 货主 ID。 + * @param {Object|null} [options.group=null] 目标群 { group_id, group_name, ext_data } + * (新增允许为 null:仅成员推送场景)。 + * @param {Array|null} [options.userIds=null] 目标成员外部 IM 用户 ID 数组 + * (新增,目标侧协议支持 user_id 数组:整体透传不循环拆发)。 + * @param {string} [options.content=''] 通知正文。 + * @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。 + * @param {Object} [options.extData] 群扩展数据(渠道信息,落库与推送透传)。 + * @return {Promise} 推送结果(含 messageId)。 + */ + async pushSystemMessage({ + warehouseId, + storeId = null, + group = null, + userIds = null, + content = '', + extId = null, + extData = null, + } = {}) { + const { ctx } = this; + const groupId = String((group && group.group_id) || '').trim(); + const groupName = String((group && group.group_name) || '').trim(); + // 按群ID格式校正渠道来源(@chatroom→wx / 纯数字→qiwe),避免通知投递到错误渠道 + const normalizedExtData = normalizeExtDataSource(groupId, extData); + // 成员ID规范化:仅接受字符串数组,去重并过滤空值(向后兼容:旧调用不传时为空数组) + const normalizedUserIds = Array.isArray(userIds) + ? [ ...new Set(userIds.map(item => String(item || '').trim()).filter(Boolean)) ] + : []; + + // 向后兼容:无群且无成员时保持旧版 skip 语义(原判断 !groupId || !groupName) + if (!groupId && normalizedUserIds.length === 0) { + return { + success: false, + skipped: true, + reason: '目标群缺少 group_id 或 group_name', + warehouseId, + }; + } + // 指定了群但缺群名:与旧版一致返回 skip(群维度协议要求 group_name) + if (groupId && !groupName) { + return { + success: false, + skipped: true, + reason: '目标群缺少 group_id 或 group_name', + warehouseId, + }; + } + + // 幂等 ext_id:业务单号 + 事件 + 目标维度(群优先、仅成员时按成员集合), + // 网络重推时复用同一条消息记录;超长时降级哈希兜底 + const sourceExtId = String(extId || `sys:notice:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`); + const memberKey = normalizedUserIds.length > 0 ? `members:${normalizedUserIds.join(',')}` : ''; + const targetKey = groupId || memberKey; + let uniqueExtId = `sys:notice:${sourceExtId}:${targetKey}`; + if (uniqueExtId.length > 128) { + const digest = crypto.createHash('md5') + .update(uniqueExtId) + .digest('hex') + .slice(0, 12); + uniqueExtId = `sys:notice:${sourceExtId.slice(0, 100)}:${digest}`; + } + + const InboxMessage = ctx.model && ctx.model.InboxMessage; + const normalizedContent = String(content || '').trim() || '系统通知'; + let messageId = null; + + if (InboxMessage) { + try { + const existing = await InboxMessage.findOne({ + where: { ext_id: uniqueExtId }, + attributes: [ 'id', 'push_status' ], + paranoid: false, + }); + if (existing) { + messageId = Number(existing.id); + // 幂等去重:同 ext_id 消息已送达(push_status=2)时跳过推送, + // 防止重复轮次/多实例并发导致同一群重复收到相同通知; + // 未送达(0/1/3)时保留重推机会(复用同一消息记录回写推送结果) + if (Number(existing.push_status) === 2) { + return { + success: true, + skipped: true, + reason: '消息已送达,跳过重复推送', + warehouseId, + method: 'notify.reply', + messageId, + }; + } + } else { + const created = await InboxMessage.create({ + ext_id: uniqueExtId, + warehouse_id: Number(warehouseId || 0), + store_id: Number(storeId || 0) > 0 ? Number(storeId) : null, + direction: 'outbound', + parent_id: null, + source_type: 'system', + source_extra: 'notice', + target_type: 'api', + group_id: groupId || null, + // 成员数组仅随推送体 user_id 透传并记录在 report_delivery_log.notify_targets 快照中, + // 消息表 user_id 列(STRING(100))不承载数组,避免超长截断 + user_id: null, + group_name: groupName || null, + user_name: null, + content: normalizedContent, + ext_data: normalizedExtData, + flags: {}, + push_status: 1, + push_started_at: new Date(), + }); + messageId = Number(created.id); + } + } catch (messageErr) { + ctx.logger.warn('[warehouseNotify] 写消息表失败: ' + messageErr.message); + } + } + + // 推送体:群字段仅指定群时携带;成员 user_id 直接传数组(目标侧协议支持),不循环拆发 + const pushData = { + type: 'system', + content: normalizedContent, + ext_id: sourceExtId, + ext_data: normalizedExtData, + timestamp: Math.floor(Date.now() / 1000), + }; + if (groupId) { + pushData.group_id = groupId; + pushData.group_name = groupName; + } + if (normalizedUserIds.length > 0) { + pushData.user_id = normalizedUserIds; + } + + // 群来源应用优先:同一仓库多应用承接 notify.reply 时避免系统通知错投渠道 + const preferredAppKey = await this.resolveGroupSourceAppKey(groupId, warehouseId); + const result = await this.push({ + warehouseId, + method: 'notify.reply', + data: pushData, + preferredAppKey, + }); + + // 回写推送状态(失败仅记日志,不影响业务) + if (InboxMessage && messageId) { + try { + if (result.success) { + await InboxMessage.update({ + push_status: 2, + push_response: { + http_status: result.httpStatus, + body: result.response || null, + }, + pushed_at: new Date(), + }, { where: { id: messageId } }); + } else { + await InboxMessage.update({ + push_status: 3, + push_response: { + http_status: result.httpStatus, + body: result.response || null, + error: result.error || result.reason || '推送失败', + }, + }, { where: { id: messageId } }); + } + } catch (updateErr) { + ctx.logger.warn('[warehouseNotify] 回写推送状态失败: ' + updateErr.message); + } + } + + return { ...result, messageId }; + } +} + +module.exports = WarehouseNotifyService; diff --git a/app/service/systems/warehouse_panel.js b/app/service/systems/warehouse_panel.js new file mode 100644 index 0000000..4becb7f --- /dev/null +++ b/app/service/systems/warehouse_panel.js @@ -0,0 +1,1113 @@ +'use strict'; + +const Service = require('egg').Service; + +// 面板数据缓存 TTL(秒):缓存期内直接复用;过期视为无最后更新时间,重新聚合并兜底设置 +const PANEL_CACHE_TTL_SECONDS = 300; +// 缓存键前缀(按仓库存储:{prefix}:lastChangeAt:{warehouseId}) +const PANEL_CACHE_KEY_PREFIX = 'index:warehousePanel'; + +// 订单履约链路环节定义(每环节按未/已两个数值输出;field 为订单分表状态字段) +const FULFILLMENT_STAGES = [ + { key: 'alloc', icon: 'alloc', undone: '未分配', done: '已分配', field: 'post_status' }, + { key: 'print', icon: 'print', undone: '未打印', done: '已打印', field: 'print_status' }, + { key: 'pick', icon: 'pick', undone: '未拣货', done: '已拣货', field: 'pick_status' }, + { key: 'recheck', icon: 'recheck', undone: '未复核', done: '已复核', field: 'recheck_status' }, + { key: 'pack', icon: 'pack', undone: '未打包', done: '已打包', field: 'pack_status' }, + { key: 'ship', icon: 'ship', undone: '待出库', done: '已出库', field: 'outbound_status' }, +]; + +// 拣货任务活跃状态(排除 9=已取消) +const PICK_TASK_ACTIVE_STATUSES = [ 0, 1, 2, 3 ]; + +class WarehousePanelService extends Service { + /** + * 面板缓存键(按仓库存储)。 + * + * @param {number|string} warehouseId 仓库 ID + * @return {string} 缓存键 + */ + getPanelCacheKey(warehouseId) { + return `${PANEL_CACHE_KEY_PREFIX}:lastChangeAt:${warehouseId}`; + } + + /** + * 通知面板数据已变化(公共方法):更新对应仓库的最后更新时间戳,供大屏增量轮询感知新数据。 + * 只写时间戳(整值替换,data 自然失效),面板接口下次拉取时会查库重建数据。 + * 供拣货完成/复核完成/打包完成等业务写路径调用;失败仅告警不影响主流程。 + * + * @param {number|string} warehouseId 仓库 ID + * @return {Promise} 写入的时间戳(Unix 秒);失败返回 0 + */ + async touchLastChangeAt(warehouseId) { + try { + const key = this.getPanelCacheKey(Number(warehouseId)); + const nowTs = Math.floor(Date.now() / 1000); + await this.app.setCacheAsync(key, { last_change_at: nowTs }, PANEL_CACHE_TTL_SECONDS); + return nowTs; + } catch (error) { + const logger = this.ctx.logger; + if (logger && typeof logger.warn === 'function') { + logger.warn(`[WarehousePanel] 更新最后更新时间失败 warehouseId=${warehouseId}: ${error && error.message}`); + } + return 0; + } + } + + /** + * 读取仓库自然日开始时间(wms_store.subject_config.day_start_time)。 + * + * 配置缺失/非法/查询异常时回退默认 06:00。 + * + * @param {number} warehouseId 仓库 ID + * @return {Promise} HH:mm 格式时间(如 06:00) + */ + async getWarehouseDayStartTime(warehouseId) { + try { + const store = await this.ctx.model.Store.findOne({ + where: { id: warehouseId, project: 'warehouse' }, + attributes: [ 'subject_config' ], + raw: true, + }); + let config = store && store.subject_config ? store.subject_config : {}; + if (typeof config === 'string') { + try { + config = JSON.parse(config); + } catch (parseError) { + config = {}; + } + } + const raw = config.day_start_time; + if (typeof raw === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(raw)) { + return raw; + } + return '06:00'; + } catch (error) { + const logger = this.ctx.logger; + if (logger && typeof logger.warn === 'function') { + logger.warn(`[WarehousePanel] 读取自然日开始时间失败,回退 06:00: ${error.message}`); + } + return '06:00'; + } + } + + /** + * 解析业务日窗口 [businessStart, businessEnd)。 + * + * 业务日从配置的 day_start_time 开始持续 24 小时;当前时间早于今日该时间点时, + * 窗口从昨日该时间点开始(昨日该时间点后的订单视为今日)。 + * + * @param {number} warehouseId 仓库 ID + * @param {Date} now 当前时间 + * @return {Promise>} [ 业务日开始, 业务日结束 ] + */ + async resolveBusinessDayRange(warehouseId, now) { + const dayStartTime = await this.getWarehouseDayStartTime(warehouseId); + const [ hh, mm ] = dayStartTime.split(':').map(Number); + let businessStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hh, mm, 0, 0); + if (now < businessStart) { + businessStart = new Date(businessStart.getTime() - 86400000); + } + return [ businessStart, new Date(businessStart.getTime() + 86400000) ]; + } + + /** + * 获取面板数据。 + * + * 最后更新时间一般由外部驱动(业务数据变化时写入缓存键的 last_change_at); + * 本方法仅在缓存中没有最后更新时间时,才查库拉取数据并兜底设置最后更新时间。 + * + * 拉取逻辑: + * - 缓存有最后更新时间:is_change=false(传入时间戳不小于缓存时间戳)时返回空 data(节约流量); + * is_change=true 时优先输出缓存数据;缓存无数据(外部只驱动了时间戳)则查库补数据并保留外部时间戳; + * - 缓存无最后更新时间(未命中/过期):查库拉数据并设置最后更新时间。 + * + * is_change 语义:传入时间戳小于缓存最后更改时间戳时为 true。 + * + * @param {number} warehouseId 仓库 ID + * @param {Object} [options] 选项 + * @param {number} [options.lastChangeAt=0] 客户端持有的最后更改时间戳 + * @return {Promise} 组装后的面板数据(含 title/fulfillment/stageOverview 等数据块) + */ + async getPanelData(warehouseId, options = {}) { + const lastChangeAt = Number(options.lastChangeAt || 0); + + const cacheKey = this.getPanelCacheKey(warehouseId); + const cached = await this.app.getCacheAsync(cacheKey); + + // 缓存有最后更新时间 + if (cached && cached.last_change_at) { + const cachedTs = Number(cached.last_change_at); + const isChange = lastChangeAt < cachedTs; + + // 未变化:空 data 节约流量,不查库 + if (!isChange) { + return { is_change: false, last_change_at: cachedTs, data: {} }; + } + + // 已有缓存数据:直接输出,不查库 + if (cached.data) { + return { is_change: true, last_change_at: cachedTs, data: cached.data }; + } + + // 外部只驱动了最后更新时间(无缓存数据):查库拉数据补入缓存,保留外部时间戳 + const data = await this.buildPanelData(warehouseId); + await this.app.setCacheAsync(cacheKey, { last_change_at: cachedTs, data }, PANEL_CACHE_TTL_SECONDS); + return { is_change: true, last_change_at: cachedTs, data }; + } + + // 缓存无最后更新时间:查库拉数据并设置最后更新时间 + const data = await this.buildPanelData(warehouseId); + const nowTs = Math.floor(Date.now() / 1000); + await this.app.setCacheAsync(cacheKey, { last_change_at: nowTs, data }, PANEL_CACHE_TTL_SECONDS); + return { is_change: true, last_change_at: nowTs, data }; + } + + /** + * 聚合全部面板数据块。 + * + * 各数据块独立容错:单块查询失败时该块返回 null(前端按字段缺失处理),不影响其他块。 + * + * @param {number} warehouseId 仓库 ID + * @return {Promise} 组装后的面板数据(含 title/fulfillment/stageOverview 等数据块) + */ + async buildPanelData(warehouseId) { + const { ctx } = this; + const { model } = ctx; + const { Op } = this.app.Sequelize; + + const now = new Date(); + const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + // 业务日窗口(仓库配置 day_start_time,默认 06:00):昨日 06:00 后的订单视为今日 + const [ businessStart, businessEnd ] = await this.resolveBusinessDayRange(warehouseId, now); + + const factory = model.OrderDeliveryFactory; + const [ currentModel, dispatchModel ] = await Promise.all([ + factory.getCurrentModel(warehouseId), + factory.getDispatchModel(warehouseId), + ]); + const currentTableName = currentModel.getTableName(); + const dispatchTableName = dispatchModel.getTableName(); + + const pendingBase = { + step: { [Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Op.ne]: 'padding' }, + status: { [Op.ne]: 'cancel' }, + }; + + const blocks = await Promise.all([ + this.queryFulfillment(currentModel, dispatchModel, pendingBase, warehouseId, businessStart, businessEnd) + .catch(error => this.logBlockError('fulfillment', error)), + this.queryStageOverview(warehouseId, currentModel, dispatchModel, pendingBase, businessStart, businessEnd) + .catch(error => this.logBlockError('stageOverview', error)), + this.queryB2b(currentModel, dispatchModel, businessStart, businessEnd) + .catch(error => this.logBlockError('b2b', error)), + this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, true, businessStart, businessEnd) + .catch(error => this.logBlockError('groupPicking', error)), + this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, false, businessStart, businessEnd) + .catch(error => this.logBlockError('scatterPicking', error)), + this.queryPackingBlock(warehouseId, businessStart, businessEnd, true) + .catch(error => this.logBlockError('groupPacking', error)), + this.queryPackingBlock(warehouseId, businessStart, businessEnd, false) + .catch(error => this.logBlockError('scatterPacking', error)), + this.queryTrend(currentModel, dispatchModel, pendingBase, businessStart, businessEnd) + .catch(error => this.logBlockError('trend', error)), + this.queryWeeklyIntercept(currentModel, dispatchModel, todayStart) + .catch(error => this.logBlockError('weeklyEfficiency', error)), + ]); + + const [ fulfillment, stageOverview, b2b, groupPicking, scatterPicking, groupPacking, scatterPacking, trend, weeklyEfficiency ] = blocks; + + // 趋势补充总单量字段(与 fulfillment.total 同口径:待处理订单池 + 配送表今日出库; + // fulfillment 块失败时兜底 0) + if (trend) { + trend.total = fulfillment ? (fulfillment.total || 0) : 0; + } + + const data = { + title: ctx.user?.store_name || '', + fulfillment, + stageOverview, + b2b, + groupPicking, + scatterPicking, + groupPacking, + scatterPacking, + trend, + weeklyEfficiency, + }; + + return data; + } + + /** + * 记录数据块聚合失败日志(返回 null,前端按字段缺失处理)。 + * + * @param {string} blockName 数据块名 + * @param {Error} error 异常 + * @return {null} 恒返回 null(调用方将对应数据块置空) + */ + logBlockError(blockName, error) { + const logger = this.ctx.logger; + if (logger && typeof logger.warn === 'function') { + logger.warn(`[WarehousePanel] 数据块聚合失败,已跳过: ${blockName}`, error.message); + } + return null; + } + + /** + * 订单履约链路:6 个环节 × 未/已 + 分母 + 今日退回指标。 + * + * 配送表补数:已出库订单会从常用表迁移到配送分表(outbound_status=fin); + * 各环节未* = 池内未完成 + 配送表今日出库未完成(真实状态); + * 各环节已* 口径:分配/打印/拣货/打包从订单表状态获取(池内 fin + 配送表今日出库 fin, + * 保证已分配≥已打印≥已拣货≥已复核≥已打包的流程约束), + * 复核=今日复核时间(recheck_time)双表、出库=今日出库数。 + * + * 今日退回收件数/今日拆包件数:按 wms_return_received / wms_return_unpack + * 的 created_at 落在今日(含今天 00:00)且仓库匹配统计,以两项追加在 + * items 数组末尾(label/icon/value 与环节项同构)。 + * + * @param {Object} currentModel 常用分表模型 + * @param {Object} dispatchModel 配送分表模型 + * @param {Object} pendingBase 待处理基础过滤 + * @param {number} warehouseId 仓库 ID + * @param {Date} todayStart 今日开始 + * @param {Date} tomorrowStart 明日开始 + * @return {Promise} { total, items }(items 末尾追加今日退件/今日拆包两项) + */ + async queryFulfillment(currentModel, dispatchModel, pendingBase, warehouseId, todayStart, tomorrowStart) { + const { model } = this.ctx; + const { Op } = this.app.Sequelize; + const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart }; + + // 配送表今日出库且未取消:出库环节已*(今日出库数)与总数叠加(已迁移订单) + const dispatchTodayBase = { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }; + + const totalCountPromise = currentModel.count({ where: pendingBase }); + const dispatchTodayCountPromise = dispatchModel.count({ where: dispatchTodayBase }); + // 各环节已* 口径:分配/打印/拣货/打包均从订单表状态获取(池内 fin + 配送表今日出库 fin), + // 保证已分配 ≥ 已打印 ≥ 已拣货 ≥ 已复核 ≥ 已打包 的流程约束; + // 注:打包环节此前用「今日打包任务订单数」口径,会大于已复核(打包任务快照含未复核/重复计入), + // 已改回订单状态存量口径(pack_status=fin);复核=今日复核时间、出库=今日出库数 + const todayAllocOrdersPromise = Promise.all([ + currentModel.count({ where: { ...pendingBase, post_status: 'fin' } }), + dispatchModel.count({ where: { ...dispatchTodayBase, post_status: 'fin' } }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); + const todayPrintOrdersPromise = Promise.all([ + currentModel.count({ where: { ...pendingBase, print_status: 'fin' } }), + dispatchModel.count({ where: { ...dispatchTodayBase, print_status: 'fin' } }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); + const todayPickOrdersPromise = Promise.all([ + currentModel.count({ where: { ...pendingBase, pick_status: 'fin' } }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + pick_status: 'fin', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); + const todayPackOrdersPromise = Promise.all([ + currentModel.count({ where: { ...pendingBase, pack_status: 'fin' } }), + dispatchModel.count({ where: { ...dispatchTodayBase, pack_status: 'fin' } }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); + const todayRecheckOrdersPromise = Promise.all([ + currentModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange } }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + recheck_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); + const returnReceivedTodayPromise = model.ReturnReceived.count({ + where: { warehouse_id: warehouseId, created_at: todayRange }, + }); + const returnUnpackTodayPromise = model.ReturnUnpack.count({ + where: { warehouse_id: warehouseId, created_at: todayRange }, + }); + const stageCounts = await Promise.all(FULFILLMENT_STAGES.map(async stage => { + const [ undoneCurrent, dispatchFin, dispatchTodayOutbound, todayAlloc, todayPrint, todayPick, todayRecheck, todayPack ] = await Promise.all([ + currentModel.count({ + where: { + ...pendingBase, + [Op.or]: [ + { [stage.field]: { [Op.ne]: 'fin' } }, + { [stage.field]: { [Op.is]: null } }, + ], + }, + }), + dispatchModel.count({ + where: { ...dispatchTodayBase, [stage.field]: 'fin' }, + }), + dispatchTodayCountPromise, + todayAllocOrdersPromise, + todayPrintOrdersPromise, + todayPickOrdersPromise, + todayRecheckOrdersPromise, + todayPackOrdersPromise, + ]); + // 已* 按环节取今日作业口径数据源;出库环节=今日出库数; + // 未* = 池内未完成 + 配送表今日出库未完成(真实状态) + const doneTodayMap = { + post_status: todayAlloc, + print_status: todayPrint, + pick_status: todayPick, + recheck_status: todayRecheck, + pack_status: todayPack, + outbound_status: dispatchTodayOutbound, + }; + const doneToday = doneTodayMap[stage.field] || 0; + return { + undone: undoneCurrent + (dispatchTodayOutbound - dispatchFin), + done: doneToday, + }; + })); + + const [ total, dispatchTodayOutbound, returnReceivedToday, returnUnpackToday ] = await Promise.all([ + totalCountPromise, + dispatchTodayCountPromise, + returnReceivedTodayPromise, + returnUnpackTodayPromise, + ]); + const items = []; + FULFILLMENT_STAGES.forEach((stage, index) => { + const counts = stageCounts[index] || { undone: 0, done: 0 }; + items.push({ label: stage.undone, icon: stage.icon, value: counts.undone || 0 }); + items.push({ label: stage.done, icon: stage.icon, value: counts.done || 0 }); + }); + items.push({ label: '今日退件', icon: 'returnReceived', value: returnReceivedToday || 0 }); + items.push({ label: '今日拆包', icon: 'returnUnpack', value: returnUnpackToday || 0 }); + + return { total: (total || 0) + dispatchTodayOutbound, items }; + } + + /** + * 执行一条 count 原生 SQL 并返回计数。 + * + * @param {string} sql SQL 文本 + * @param {Object} replacements 替换参数 + * @return {Promise} 计数结果 + */ + async countSql(sql, replacements) { + const rows = await this.ctx.model.query(sql, { + replacements, + type: this.ctx.model.QueryTypes.SELECT, + }); + const first = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + return Number(first && first.cnt || 0); + } + + /** + * 作业环节概览:总量 + 拦截 + 5 张环节卡(缺数据源的字段不写入)。 + * + * @param {number} warehouseId 仓库 ID + * @param {Object} currentModel 常用分表模型 + * @param {Object} dispatchModel 配送分表模型(已出库订单迁移目标,今日出库双表合计) + * @param {Object} pendingBase 待处理基础过滤 + * @param {Date} todayStart 今日开始 + * @param {Date} tomorrowStart 明日开始 + * @return {Promise} { totalOrders, interceptOrders, stages } + */ + async queryStageOverview(warehouseId, currentModel, dispatchModel, pendingBase, todayStart, tomorrowStart) { + const { model } = this.ctx; + const { Op } = this.app.Sequelize; + const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart }; + + const [ + totalPending, + todayOutbound, + interceptOrders, + receivingToday, + receivingDoing, + shelfDoing, + pickToday, + pickDoing, + pickAbnormal, + recheckToday, + recheckDoing, + recheckAbnormal, + packToday, + packDoing, + packAbnormal, + ] = await Promise.all([ + currentModel.count({ where: pendingBase }), + Promise.all([ + currentModel.count({ + where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: todayRange }, + }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), + currentModel.count({ + where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } }, + }), + model.Receiving.count({ where: { warehouse_id: warehouseId, created_at: todayRange } }), + model.Receiving.count({ where: { warehouse_id: warehouseId, status: 'receiving' } }), + model.Receiving.count({ + where: { warehouse_id: warehouseId, storage_status: { [Op.in]: [ 'waiting', 'partial' ] } }, + }), + Promise.all([ + currentModel.count({ where: { ...pendingBase, pick_status: 'fin' } }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + pick_status: 'fin', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), + // 拣货中订单数:订单表 pick_status='padding'(池内 + 配送表今日出库,与已拣货同源订单表口径) + Promise.all([ + currentModel.count({ where: { ...pendingBase, pick_status: 'padding' } }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + pick_status: 'padding', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), + Promise.all([ + currentModel.count({ where: { ...pendingBase, pick_status: 'error' } }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + pick_status: 'error', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), + Promise.all([ + currentModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange } }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + recheck_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), + model.WaveBatch.count({ + where: { + warehouse_id: warehouseId, + recheck_start_time: { [Op.not]: null }, + wave_status: { [Op.in]: [ 3, 4 ] }, + }, + }), + Promise.all([ + currentModel.count({ where: { ...pendingBase, recheck_status: 'error' } }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + recheck_status: 'error', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), + this.countSql( + `SELECT + (SELECT COUNT(*) FROM wms_pack_task + WHERE warehouse_id = :warehouseId + AND create_time >= :start AND create_time < :end + AND status = 2 AND deleted_at IS NULL + AND pack_mode != 2) + + + (SELECT COUNT(*) FROM wms_order_wave_index + WHERE wave_id IN ( + SELECT DISTINCT wave_id FROM wms_pack_task + WHERE warehouse_id = :warehouseId + AND create_time >= :start AND create_time < :end + AND status = 2 AND deleted_at IS NULL + AND pack_mode = 2 + )) AS cnt`, + { warehouseId, start: todayStart, end: tomorrowStart } + ), + // 打包中订单数:订单表 pack_status='padding'(池内 + 配送表今日出库,与未打包/已打包同源订单表口径) + Promise.all([ + currentModel.count({ where: { ...pendingBase, pack_status: 'padding' } }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + pack_status: 'padding', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), + // 打包异常订单数:订单表 pack_status='error'(池内 + 配送表今日出库,与打包中同源订单表口径) + Promise.all([ + currentModel.count({ where: { ...pendingBase, pack_status: 'error' } }), + dispatchModel.count({ + where: { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + pack_status: 'error', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }, + }), + ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), + ]); + + const stages = [ + { + key: 'receiving', + name: '收货', + icon: 'car', + tone: 'green', + today: receivingToday, + doing: receivingDoing, + }, + { + key: 'shelf', + name: '上架', + icon: 'rack', + tone: 'amber', + doing: shelfDoing, + }, + { + key: 'pick', + name: '拣货', + icon: 'cart', + tone: 'blue', + today: pickToday, + doing: pickDoing, + abnormal: pickAbnormal, + }, + { + key: 'recheck', + name: '复核', + icon: 'scan', + tone: 'violet', + today: recheckToday, + doing: recheckDoing, + abnormal: recheckAbnormal, + }, + { + key: 'pack', + name: '打包', + icon: 'box', + tone: 'cyan', + today: packToday, + doing: packDoing, + abnormal: packAbnormal, + }, + ]; + + return { + totalOrders: totalPending + todayOutbound, + interceptOrders, + stages, + }; + } + + /** + * B2B 今日出库统计(常用表 + 配送表双表聚合)。 + * + * @param {Object} currentModel 常用分表模型 + * @param {Object} dispatchModel 配送分表模型 + * @param {Date} todayStart 今日开始 + * @param {Date} tomorrowStart 明日开始 + * @return {Promise} { orders, goods, sku } + */ + async queryB2b(currentModel, dispatchModel, todayStart, tomorrowStart) { + const { Op, fn, col, literal } = this.app.Sequelize; + const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart }; + const where = { + is_b2b: 'Y', + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + delivery_time: todayRange, + }; + const attrs = [ + [ fn('COUNT', literal('*')), 'orders' ], + [ fn('SUM', col('items_total')), 'goods' ], + [ fn('SUM', col('items_count')), 'sku' ], + ]; + + const [ currentAgg, dispatchAgg ] = await Promise.all([ + currentModel.findOne({ attributes: attrs, where, raw: true }), + dispatchModel.findOne({ attributes: attrs, where, raw: true }), + ]); + + return { + orders: Number(currentAgg?.orders || 0) + Number(dispatchAgg?.orders || 0), + goods: Number(currentAgg?.goods || 0) + Number(dispatchAgg?.goods || 0), + sku: Number(currentAgg?.sku || 0) + Number(dispatchAgg?.sku || 0), + }; + } + + /** + * 拣货统计块(团购 wave_scope IN (1,3);散单其余)。 + * + * orders/goods/sku/wave 汇总按订单表状态口径(池内 pick fin + 配送表今日出库 pick fin, + * 与 fulfillment 已拣货一致,保证团购+散单=已拣货); + * top 按今日创建任务(pick_mode 1,5 团购 / 2,3,4 散单)按人聚合(任务口径)。 + * + * @param {number} warehouseId 仓库 ID + * @param {string} currentTableName 常用分表名 + * @param {string} dispatchTableName 配送分表名 + * @param {boolean} isGroup true=团购(wave_scope 1/3);false=散单(其余) + * @param {Date} todayStart 今日开始 + * @param {Date} tomorrowStart 明日开始 + * @return {Promise} { orders, goods, sku, wave, top } + */ + async queryPickingBlock(warehouseId, currentTableName, dispatchTableName, isGroup, todayStart, tomorrowStart) { + const { model } = this.ctx; + const { QueryTypes } = model; + + const scopeWhere = isGroup ? 'wave_scope IN (1, 3)' : 'wave_scope NOT IN (1, 3)'; + const pickModes = isGroup ? [ 1, 5 ] : [ 2, 3, 4 ]; + const replacements = { + warehouseId, + pickModes, + activeStatuses: PICK_TASK_ACTIVE_STATUSES, + start: todayStart, + end: tomorrowStart, + }; + + // top:今日创建任务按人聚合(任务口径) + const taskWindowWhere = ` + t.warehouse_id = :warehouseId AND t.pick_mode IN (:pickModes) + AND t.create_time >= :start AND t.create_time < :end + AND t.status IN (:activeStatuses) + `; + + // 汇总:订单表状态口径(池内 pick fin + 配送表今日出库 pick fin,与已拣货一致) + const summarySql = (tableName, whereFragment) => ` + SELECT COUNT(*) AS orders, COALESCE(SUM(items_total), 0) AS goods, + COALESCE(SUM(items_count), 0) AS sku, + COUNT(DISTINCT CASE WHEN wave_id > 0 THEN wave_id END) AS wave + FROM \`${tableName}\` WHERE ${whereFragment} + `; + const poolWhere = ` + step IN (1, 2, 3) AND outbound_status != 'padding' AND status != 'cancel' + AND pick_status = 'fin' AND ${scopeWhere} + `; + const dispatchWhere = ` + status != 'cancel' AND outbound_status = 'fin' AND pick_status = 'fin' + AND dispatch_lane IN ('m4', 'm5') + AND delivery_time >= :start AND delivery_time < :end AND ${scopeWhere} + `; + + const [ currentRows, dispatchRows, topRows ] = await Promise.all([ + model.query(summarySql(currentTableName, poolWhere), { replacements, type: QueryTypes.SELECT }), + model.query(summarySql(dispatchTableName, dispatchWhere), { replacements, type: QueryTypes.SELECT }), + model.query(` + SELECT t.pick_user_id AS user_id, t.pick_user_name AS name, + COALESCE(SUM(t.order_count), 0) AS orders, COALESCE(SUM(t.wave_count), 0) AS waves + FROM wms_wave_pick_task t + WHERE ${taskWindowWhere} + GROUP BY t.pick_user_id, t.pick_user_name + ORDER BY orders DESC + LIMIT 5 + `, { replacements, type: QueryTypes.SELECT }), + ]); + + const current = Array.isArray(currentRows) && currentRows.length > 0 ? currentRows[0] : {}; + const dispatch = Array.isArray(dispatchRows) && dispatchRows.length > 0 ? dispatchRows[0] : {}; + const summary = { + orders: Number(current.orders || 0) + Number(dispatch.orders || 0), + goods: Number(current.goods || 0) + Number(dispatch.goods || 0), + sku: Number(current.sku || 0) + Number(dispatch.sku || 0), + wave: Number(current.wave || 0) + Number(dispatch.wave || 0), + }; + + // top 的 goods/sku 仍按任务口径(订单表无拣货人,无法按人拆分) + const [ , topGoodsSkuRows ] = await this.queryPickingGoodsSku( + currentTableName, dispatchTableName, taskWindowWhere, replacements + ); + + const topGoodsSkuMap = new Map(); + (topGoodsSkuRows || []).forEach(row => { + topGoodsSkuMap.set(String(row.user_id), { goods: Number(row.goods || 0), sku: Number(row.sku || 0) }); + }); + + const top = (topRows || []).map((row, index) => { + const goodsSku = topGoodsSkuMap.get(String(row.user_id)) || { goods: 0, sku: 0 }; + return { + rank: index + 1, + name: row.name || '', + orders: Number(row.orders || 0), + goods: goodsSku.goods, + sku: goodsSku.sku, + wave: Number(row.waves || 0), + }; + }); + + return { + orders: summary.orders, + goods: summary.goods, + sku: summary.sku, + wave: summary.wave, + top, + }; + } + + /** + * 查询拣货任务的 goods/sku(总量 + 按人分组),经任务订单关联表 join 订单分表。 + * + * @param {string} currentTableName 常用分表名 + * @param {string} dispatchTableName 配送分表名 + * @param {string} taskWindowWhere 任务窗口 where 片段 + * @param {Object} replacements 替换参数 + * @return {Promise>} [ 总量行, top 行数组 ] + */ + async queryPickingGoodsSku(currentTableName, dispatchTableName, taskWindowWhere, replacements) { + const { model } = this.ctx; + const { QueryTypes } = model; + + // 任务订单关联表缺失的任务(如 pick_mode=1 团购任务,实测 60 个任务 3862 单无 pto 记录) + // 按 wave_id 从订单分表统计,避免 goods/sku 漏算;有 pto 记录的仍走 pto 精确统计 + const taskWindowWhere2 = taskWindowWhere.replace(/\bt\./g, 't2.'); + + const goodsSkuSelect = tableName => ` + SELECT COALESCE(SUM(x.items_total), 0) AS goods, COALESCE(SUM(x.items_count), 0) AS sku + FROM ( + SELECT od.items_total, od.items_count + FROM wms_wave_pick_task t + JOIN wms_wave_pick_task_order pto ON pto.task_id = t.id + JOIN \`${tableName}\` od ON od.id = pto.order_id AND od.status != 'cancel' + WHERE ${taskWindowWhere} + UNION ALL + SELECT od2.items_total, od2.items_count + FROM wms_wave_pick_task t2 + JOIN \`${tableName}\` od2 ON od2.wave_id = t2.wave_id AND od2.status != 'cancel' + WHERE ${taskWindowWhere2} AND t2.wave_id > 0 + AND NOT EXISTS (SELECT 1 FROM wms_wave_pick_task_order pto2 WHERE pto2.task_id = t2.id) + ) x + `; + + // 第一分支必须限定今日任务窗口(同 goodsSkuSelect):否则 pto 全历史关联订单分表, + // 派生子查询 g 物化扫描百万行(生产慢日志实测 1.75M 行 / 9.4s 超时) + const taskWindowWhereTp = taskWindowWhere.replace(/\bt\./g, 'tp.'); + + const topGoodsSkuSelect = tableName => ` + SELECT t.pick_user_id AS user_id, COALESCE(SUM(g.items_total), 0) AS goods, COALESCE(SUM(g.items_count), 0) AS sku + FROM wms_wave_pick_task t + JOIN ( + SELECT tp.id AS task_id, od.items_total, od.items_count + FROM wms_wave_pick_task tp + JOIN wms_wave_pick_task_order pto ON pto.task_id = tp.id + JOIN \`${tableName}\` od ON od.id = pto.order_id AND od.status != 'cancel' + WHERE ${taskWindowWhereTp} + UNION ALL + SELECT t2.id AS task_id, od2.items_total, od2.items_count + FROM wms_wave_pick_task t2 + JOIN \`${tableName}\` od2 ON od2.wave_id = t2.wave_id AND od2.status != 'cancel' + WHERE ${taskWindowWhere2} AND t2.wave_id > 0 + AND NOT EXISTS (SELECT 1 FROM wms_wave_pick_task_order pto2 WHERE pto2.task_id = t2.id) + ) g ON g.task_id = t.id + WHERE ${taskWindowWhere} + GROUP BY t.pick_user_id + `; + + const [ currentRows, dispatchRows, topCurrentRows, topDispatchRows ] = await Promise.all([ + model.query(goodsSkuSelect(currentTableName), { replacements, type: QueryTypes.SELECT }), + model.query(goodsSkuSelect(dispatchTableName), { replacements, type: QueryTypes.SELECT }), + model.query(topGoodsSkuSelect(currentTableName), { replacements, type: QueryTypes.SELECT }), + model.query(topGoodsSkuSelect(dispatchTableName), { replacements, type: QueryTypes.SELECT }), + ]); + + const current = Array.isArray(currentRows) && currentRows.length > 0 ? currentRows[0] : {}; + const dispatch = Array.isArray(dispatchRows) && dispatchRows.length > 0 ? dispatchRows[0] : {}; + const totalGoodsSku = { + goods: Number(current.goods || 0) + Number(dispatch.goods || 0), + sku: Number(current.sku || 0) + Number(dispatch.sku || 0), + }; + + const topGoodsSkuMap = new Map(); + [ ...(topCurrentRows || []), ...(topDispatchRows || []) ].forEach(row => { + const key = String(row.user_id); + const prev = topGoodsSkuMap.get(key) || { goods: 0, sku: 0 }; + topGoodsSkuMap.set(key, { + goods: prev.goods + Number(row.goods || 0), + sku: prev.sku + Number(row.sku || 0), + }); + }); + + return [ totalGoodsSku, [ ...topGoodsSkuMap.entries() ].map(([ user_id, item ]) => ({ user_id, ...item })) ]; + } + + /** + * 打包统计块(按波次范围区分:wave_scope 1 大团购/3 小团购为团购块,其余为散单块)。 + * + * 口径:今日创建(create_time 今日)且已完成(status = 2)且未删除的任务 + * (打包中 status=1 不计入,见 stageOverview doing 打包中任务数); + * orders 按打包模式统计——pack_mode=2(团购模式)按 pack_quantity(波次订单数快照) + * 求和,pack_mode=1 散单每任务 1 单; + * 团购块 top 按打包台(wms_workbench.name)聚合;散单块 top 按打包员 + * (pack_task_packer.account_name)聚合。 + * + * @param {number} warehouseId 仓库 ID + * @param {Date} todayStart 今日开始 + * @param {Date} tomorrowStart 明日开始 + * @param {boolean} isGroup true=团购(wave_scope 1/3,top 按打包台);false=散单(wave_scope 非 1/3,top 按打包员) + * @return {Promise} 团购 { orders, goods, sku, wave, top };散单 { orders, goods, sku, top }(无 wave) + */ + async queryPackingBlock(warehouseId, todayStart, tomorrowStart, isGroup) { + const { model } = this.ctx; + const { QueryTypes } = model; + + const scopeWhere = isGroup ? 'pt.wave_scope IN (1, 3)' : 'pt.wave_scope NOT IN (1, 3)'; + // 订单数口径:pack_mode=2(团购模式,含 wave_scope=3 小团购)按 pack_quantity 求和;散单每任务 1 单 + const ordersExpr = 'SUM(CASE WHEN pt.pack_mode = 2 THEN pt.pack_quantity ELSE 1 END) AS orders'; + const replacements = { warehouseId, start: todayStart, end: tomorrowStart }; + const taskWindowWhere = ` + pt.warehouse_id = :warehouseId AND ${scopeWhere} + AND pt.create_time >= :start AND pt.create_time < :end + AND pt.status = 2 AND pt.deleted_at IS NULL + `; + + // 团购块按打包台聚合;散单块按打包员聚合 + const topSql = isGroup + ? ` + SELECT COALESCE(w.name, '未指定打包台') AS name, ${ordersExpr}, + COALESCE(SUM(pt.item_quantity), 0) AS goods, + COALESCE(SUM(pt.sku_count), 0) AS sku, + COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave + FROM wms_pack_task pt + LEFT JOIN wms_workbench w ON w.id = pt.workbench_id AND w.deleted_at IS NULL + WHERE ${taskWindowWhere} + GROUP BY pt.workbench_id, w.name + ORDER BY orders DESC + LIMIT 5 + ` + : ` + SELECT pp.account_name AS name, ${ordersExpr}, + COALESCE(SUM(pt.item_quantity), 0) AS goods, + COALESCE(SUM(pt.sku_count), 0) AS sku, + COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave + FROM wms_pack_task pt + JOIN wms_pack_task_packer pp ON pp.pack_task_id = pt.id AND pp.deleted_at IS NULL + WHERE ${taskWindowWhere} + GROUP BY pp.account_name + ORDER BY orders DESC + LIMIT 5 + `; + + const [ summaryRows, topRows ] = await Promise.all([ + model.query(` + SELECT ${ordersExpr}, COALESCE(SUM(pt.item_quantity), 0) AS goods, + COALESCE(SUM(pt.sku_count), 0) AS sku, + COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave + FROM wms_pack_task pt + WHERE ${taskWindowWhere} + `, { replacements, type: QueryTypes.SELECT }), + model.query(topSql, { replacements, type: QueryTypes.SELECT }), + ]); + + const summary = Array.isArray(summaryRows) && summaryRows.length > 0 ? summaryRows[0] : {}; + const top = (topRows || []).map((row, index) => { + const item = { + rank: index + 1, + name: row.name || '', + orders: Number(row.orders || 0), + goods: Number(row.goods || 0), + sku: Number(row.sku || 0), + }; + // 仅团购块输出波次数(散单块无波次语义) + if (isGroup) { + item.wave = Number(row.wave || 0); + } + return item; + }); + + const result = { + orders: Number(summary.orders || 0), + goods: Number(summary.goods || 0), + sku: Number(summary.sku || 0), + top, + }; + if (isGroup) { + result.wave = Number(summary.wave || 0); + } + return result; + } + + /** + * 今日订单实时趋势(业务日窗口 24 点,label 从仓库自然日开始时间起每小时一点,到次日自然日开始时间)。 + * created_count:业务日窗口内下单量(池内待处理 + 配送表今日出库订单,按订单创建时间落桶) + * 按小时累计(最后一点=业务日内下单总量);窗口即业务日:未到次日自然日开始时间时 + * 为 [今日自然日开始时间, 次日自然日开始时间),凌晨(已过零点)时为 [昨日自然日开始时间, 今日自然日开始时间)。 + * + * @param {Object} currentModel 常用分表模型 + * @param {Object} dispatchModel 配送分表模型 + * @param {Object} pendingBase 待处理基础过滤 + * @param {Date} todayStart 业务日开始时间(仓库自然日 day_start_time) + * @param {Date} tomorrowStart 业务日结束时间(次日自然日开始时间) + * @return {Promise} { max, points },points 每项 { label, created_count } + */ + async queryTrend(currentModel, dispatchModel, pendingBase, todayStart, tomorrowStart) { + const { Op, fn, col, literal } = this.app.Sequelize; + + // 横轴 24 点:从自然日开始时间起每小时一点(跨天,label=桶起点 HH:00) + const points = []; + const bucketByHour = new Map(); + for (let index = 0; index < 24; index++) { + const bucketStart = new Date(todayStart.getTime() + index * 3600000); + bucketByHour.set(bucketStart.getHours(), index); + points.push({ + label: `${String(bucketStart.getHours()).padStart(2, '0')}:00`, + created_count: 0, + }); + } + const bucketIndexOf = hour => { + const bucket = bucketByHour.get(Number(hour)); + return bucket === undefined ? 0 : bucket; + }; + + // 下单量按创建时间落桶(池内待处理 + 配送表今日出库,窗口=业务日 [todayStart, tomorrowStart)) + const dispatchTodayBase = { + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + delivery_time: { [Op.gte]: todayStart, [Op.lt]: tomorrowStart }, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, + }; + const [ + createdRows, + dispatchCreatedRows, + ] = await Promise.all([ + currentModel.findAll({ + attributes: [ + [ fn('HOUR', col('create_at')), 'hour' ], + [ fn('COUNT', literal('*')), 'count' ], + ], + where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: tomorrowStart } }, + group: [ 'hour' ], + raw: true, + }), + dispatchModel.findAll({ + attributes: [ + [ fn('HOUR', col('create_at')), 'hour' ], + [ fn('COUNT', literal('*')), 'count' ], + ], + where: { ...dispatchTodayBase, create_at: { [Op.gte]: todayStart, [Op.lt]: tomorrowStart } }, + group: [ 'hour' ], + raw: true, + }), + ]); + + [ ...(createdRows || []), ...(dispatchCreatedRows || []) ].forEach(row => { + points[bucketIndexOf(row.hour)].created_count += Number(row.count || 0); + }); + + // 累计口径:每点为截至该小时结束的累计总数(最后一点=业务日内下单总量) + for (let index = 1; index < points.length; index++) { + points[index].created_count += points[index - 1].created_count; + } + + const peak = points.reduce( + (maxValue, point) => Math.max(maxValue, point.created_count), + 0 + ); + const max = Math.max(Math.ceil(peak / 10) * 10, 10); + + return { max, points }; + } + + /** + * 近 7 日拦截量按天统计(时间锚点:intercept_time,为空时回落 create_at)。 + * + * 吞吐量(throughput)口径未定义,暂不输出;仅输出 days[].intercept。 + * + * @param {Object} currentModel 常用分表模型 + * @param {Object} dispatchModel 配送分表模型 + * @param {Date} todayStart 今日开始 + * @return {Promise} { days } + */ + async queryWeeklyIntercept(currentModel, dispatchModel, todayStart) { + const { Op, fn, col, literal } = this.app.Sequelize; + const sevenDaysAgo = new Date(todayStart.getTime() - 6 * 86400000); + const tomorrowStart = new Date(todayStart.getTime() + 86400000); + const anchor = fn('COALESCE', col('intercept_time'), col('create_at')); + const where = { + [Op.and]: [ + { intercept_status: { [Op.not]: null, [Op.ne]: 'none' } }, + this.app.Sequelize.where(anchor, { [Op.gte]: sevenDaysAgo, [Op.lt]: tomorrowStart }), + ], + }; + const attributes = [ + [ fn('DATE', anchor), 'day' ], + [ fn('COUNT', literal('*')), 'count' ], + ]; + + const [ currentRows, dispatchRows ] = await Promise.all([ + currentModel.findAll({ attributes, where, group: [ 'day' ], raw: true }), + dispatchModel.findAll({ attributes, where, group: [ 'day' ], raw: true }), + ]); + + const dayMap = new Map(); + [ ...(currentRows || []), ...(dispatchRows || []) ].forEach(row => { + const dayKey = this.normalizeDayKey(row.day); + if (!dayKey) { + return; + } + dayMap.set(dayKey, (dayMap.get(dayKey) || 0) + Number(row.count || 0)); + }); + + const days = []; + for (let offset = 6; offset >= 0; offset--) { + const day = new Date(todayStart.getTime() - offset * 86400000); + const dayKey = this.formatDateKey(day); + const label = `${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`; + days.push({ label, intercept: dayMap.get(dayKey) || 0 }); + } + + return { days }; + } + + /** + * 归一化日期分组键(DATE() 结果可能为 Date 对象或 'YYYY-MM-DD' 字符串)。 + * + * @param {*} value 分组值 + * @return {string} 'YYYY-MM-DD' + */ + normalizeDayKey(value) { + if (!value) { + return ''; + } + if (value instanceof Date) { + return this.formatDateKey(value); + } + const text = String(value); + return text.length >= 10 ? text.slice(0, 10) : text; + } + + /** + * 格式化为本地日期键 'YYYY-MM-DD'。 + * + * @param {Date} date 日期 + * @return {string} 'YYYY-MM-DD' + */ + formatDateKey(date) { + return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; + } +} + +module.exports = WarehousePanelService; diff --git a/app/service/systems/wave_batch_closure.js b/app/service/systems/wave_batch_closure.js new file mode 100644 index 0000000..0ac0a47 --- /dev/null +++ b/app/service/systems/wave_batch_closure.js @@ -0,0 +1,481 @@ +// app/service/systems/wave_batch_closure.js +'use strict'; + +const MainService = require('../main'); + +// 活动中的波次状态(batchList 可见口径) +const ACTIVE_WAVE_STATUSES = [ 0, 1 ]; +// 终结态:复核完成(与 recheckOrder 复核完成路径一致,使波次从 batchList 中自然消失) +const CLOSED_WAVE_STATUS = 5; +// 创建不足该分钟数的波次不参与自动终结,避免与创建事务并发误判。 +// 2026-10-09 事故:PDA 策略抓取建波(B2026100900660,07:04:04)后订单绑定延迟至 07:16:37 +// (窗口约 12 分钟),5 分钟门槛不够,波次在建波与订单绑定之间被误判为空而终结。 +// 提至 30 分钟,覆盖正常建波+绑定流程(含慢事务、请求重试、流程中断后补做)的窗口。 +const WAVE_MIN_AGE_MINUTES = 30; +// 判空抽样核对条数:订单表判空但索引表仍有行的波次,按索引指向的订单抽样核对订单表 +// 是否存在这些行,用于识别「读偏」(分表重建/复制期间订单表读到半成品空表)。 +const WAVE_INDEX_PROBE_LIMIT = 50; +// 单次 SQL IN 列表的波次数量上限 +const WAVE_ID_BATCH_SIZE = 500; +// 判空二次确认:同一波次需连续两轮(间隔不小于该毫秒数)都判定为空,才允许终结。 +// 用于规避"批量解波/订单迁移进行中"造成的瞬时空表误判(2026-09-12 生产事故)。 +const EMPTY_CONFIRM_MIN_INTERVAL_MS = 30 * 1000; +// 判空二次确认状态缓存键(记录上一轮判空结果与首次判定时间) +const EMPTY_CONFIRM_CACHE_KEY = 'schedule:sync_finished_wave_batch:empty_confirm'; +// 判空二次确认状态缓存 TTL(秒) +const EMPTY_CONFIRM_CACHE_TTL_SECONDS = 3600; +// 判空二次确认状态最多保留的波次数量(防御性上限) +const EMPTY_CONFIRM_MAX_WAVE_COUNT = 10000; +// 日志中最多打印的波次数量(避免日志爆量) +const LOG_WAVE_ID_LIMIT = 200; + +/** + * 提取 UPDATE 语句实际影响行数。 + * + * @param {*} updateResult Sequelize query 返回值(UPDATE 通常为 [undefined, metadata])。 + * @return {number} 影响行数,无法识别时返回 0。 + */ +function extractAffectedRows(updateResult) { + const metadata = Array.isArray(updateResult) ? updateResult[1] : updateResult; + const rawCount = metadata + && (metadata.affectedRows !== undefined + ? metadata.affectedRows + : metadata.affectedCount !== undefined + ? metadata.affectedCount + : metadata.rowCount); + const count = Number(rawCount); + return Number.isFinite(count) && count > 0 ? count : 0; +} + +/** + * 格式化波次ID列表用于日志输出(超长时截断)。 + * + * @param {Array} waveIds 波次ID列表。 + * @return {string} 日志用字符串。 + */ +function formatWaveIdListForLog(waveIds) { + const list = Array.isArray(waveIds) ? waveIds : []; + if (list.length <= LOG_WAVE_ID_LIMIT) { + return list.join(','); + } + + return `${list.slice(0, LOG_WAVE_ID_LIMIT).join(',')},...(共${list.length}个)`; +} + +/** + * 波次批次自动终结服务。 + * + * 背景:波次内订单全部离开待处理表后(发货迁移配送表、库内拦截确认、取消等), + * 若相关路径未回写 wms_wave_batch,波次会停留在 wave_status IN (0,1), + * 导致 order.wave.batchList 展示 0 单波次。 + * + * 本服务按仓库扫描活动波次,对"待处理表中已无任何订单"的波次, + * 将 wave_status 收敛为 5(复核完成),使其从批次列表中消失。 + */ +class WaveBatchClosureService extends MainService { + /** + * 扫描并关闭"订单已全部离表"的活动波次。 + * + * 判空需通过"二次确认":同一波次连续两轮(间隔不小于 confirmMinIntervalMs) + * 都被判定为空才允许终结。这样即使某一瞬间待处理表查不到该波次订单 + * (批量解波、出库迁移、外部 DDL 等并发场景),也不会被误判为 0 单波次。 + * + * @param {Object} [options={}] 执行选项。 + * @param {boolean} [options.dryRun=false] 仅盘点不更新(用于验证命中范围)。 + * @param {number} [options.confirmMinIntervalMs] 判空二次确认最小间隔(毫秒),传 0 表示跳过确认、首轮即终结。 + * @return {Promise} 执行结果汇总。 + */ + async closeFinishedWaves(options = {}) { + const { ctx } = this; + const startedAt = Date.now(); + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const dryRun = Boolean(normalizedOptions.dryRun); + const confirmMinIntervalMs = this.normalizeConfirmIntervalMs(normalizedOptions.confirmMinIntervalMs); + const confirmEnabled = !dryRun && confirmMinIntervalMs > 0; + + const candidateRows = await ctx.model.query( + `SELECT wave_id, wave_no, warehouse_id, wave_status, total_orders + FROM wms_wave_batch + WHERE wave_status IN (:waveStatuses) + AND total_orders > 0 + AND create_time < (UTC_TIMESTAMP() - INTERVAL ${WAVE_MIN_AGE_MINUTES} MINUTE)`, + { + replacements: { waveStatuses: ACTIVE_WAVE_STATUSES }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + // 按仓库分组,过滤非法数据 + const warehouseWaveMap = new Map(); + for (const row of (Array.isArray(candidateRows) ? candidateRows : [])) { + const warehouseId = Number(row && row.warehouse_id || 0); + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0 + || !Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + if (!warehouseWaveMap.has(warehouseId)) { + warehouseWaveMap.set(warehouseId, []); + } + warehouseWaveMap.get(warehouseId).push({ + waveId, + waveNo: String(row && row.wave_no || '').trim(), + warehouseId, + }); + } + + const warehouseIds = Array.from(warehouseWaveMap.keys()); + const emptyWaves = []; + const unboundWaves = []; + const misreadWaves = []; + const probeFailedWaves = []; + + for (const warehouseId of warehouseIds) { + const waves = warehouseWaveMap.get(warehouseId); + let currentTableName = ''; + try { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.generateTableName !== 'function') { + throw new Error('订单工厂不可用'); + } + currentTableName = factory.generateTableName(warehouseId, 'current'); + } catch (error) { + ctx.logger.warn(`[wave-batch-closure] 生成仓库 ${warehouseId} 订单表名失败,跳过: ${error.message}`); + continue; + } + + // 分批查询待处理表中仍存在订单的波次 + const existingWaveIds = new Set(); + let warehouseQueryFailed = false; + for (let offset = 0; offset < waves.length; offset += WAVE_ID_BATCH_SIZE) { + const batchWaves = waves.slice(offset, offset + WAVE_ID_BATCH_SIZE); + const batchWaveIds = batchWaves.map(item => item.waveId); + try { + const existingRows = await ctx.model.query( + `SELECT DISTINCT wave_id + FROM ${currentTableName} + WHERE wave_id IN (:waveIds)`, + { + replacements: { waveIds: batchWaveIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + for (const row of (Array.isArray(existingRows) ? existingRows : [])) { + const waveId = Number(row && row.wave_id || 0); + if (Number.isInteger(waveId) && waveId > 0) { + existingWaveIds.add(waveId); + } + } + } catch (error) { + warehouseQueryFailed = true; + ctx.logger.warn(`[wave-batch-closure] 查询仓库 ${warehouseId} 待处理表失败,跳过该仓库: ${error.message}`); + break; + } + } + + if (warehouseQueryFailed) { + continue; + } + + // 交叉校验波次索引表:订单绑定与索引重建同事务,索引行是「订单曾绑定过」的强信号。 + // 订单表判空但索引非空 → 可能是正常离表(发货迁移不删索引),也可能是读偏, + // 由后续抽样核对区分;订单表与索引表双空 → 订单从未绑定(建波中间态)或全量清空异常。 + const indexedWaveIds = new Set(); + let indexQueryFailed = false; + for (let offset = 0; offset < waves.length; offset += WAVE_ID_BATCH_SIZE) { + const batchWaves = waves.slice(offset, offset + WAVE_ID_BATCH_SIZE); + const batchWaveIds = batchWaves.map(item => item.waveId); + try { + const indexRows = await ctx.model.query( + `SELECT DISTINCT wave_id + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds)`, + { + replacements: { + warehouseId, + waveIds: batchWaveIds, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + for (const row of (Array.isArray(indexRows) ? indexRows : [])) { + const waveId = Number(row && row.wave_id || 0); + if (Number.isInteger(waveId) && waveId > 0) { + indexedWaveIds.add(waveId); + } + } + } catch (error) { + indexQueryFailed = true; + ctx.logger.warn(`[wave-batch-closure] 查询仓库 ${warehouseId} 波次索引表失败,跳过该仓库: ${error.message}`); + break; + } + } + + if (indexQueryFailed) { + continue; + } + + // 分类判定 + for (const item of waves) { + const { waveId } = item; + if (existingWaveIds.has(waveId)) { + continue; // 待处理表仍有订单,正常活动波次 + } + if (!indexedWaveIds.has(waveId)) { + // 订单表与索引表双空:订单从未绑定(建波与绑定之间的中间态)或全量清空异常, + // 一律不自动终结(宁可漏关,不可误关),交由人工/后续流程处理。 + unboundWaves.push(item); + continue; + } + + // 订单表空但索引仍有行:抽样核对索引指向的订单是否真的已离开订单表。 + // 注意 MySQL 不支持 IN (SELECT ... LIMIT n),此处用 JOIN 派生表(FROM 子句 LIMIT 合法)。 + let probeCount = null; + try { + const probeRows = await ctx.model.query( + `SELECT COUNT(*) AS probe_count + FROM ${currentTableName} o + INNER JOIN ( + SELECT order_id + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT ${WAVE_INDEX_PROBE_LIMIT} + ) idx ON idx.order_id = o.id`, + { + replacements: { warehouseId, waveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + probeCount = Number(Array.isArray(probeRows) && probeRows[0] && probeRows[0].probe_count || 0); + } catch (error) { + probeFailedWaves.push(item); + ctx.logger.warn(`[wave-batch-closure] 仓库 ${warehouseId} 波次 ${waveId} 索引抽样核对失败,本轮不终结: ${error.message}`); + continue; + } + + if (Number.isFinite(probeCount) && probeCount > 0) { + // 索引指向的订单仍存在于待处理表:判空属于读偏(分表重建/复制等),不终结 + misreadWaves.push(item); + } else { + emptyWaves.push(item); + } + } + } + + const candidateCount = Array.from(warehouseWaveMap.values()).reduce((sum, waves) => sum + waves.length, 0); + + // 二次确认:只有"上一轮也判空"且距首次判空已满 confirmMinIntervalMs 的波次才允许终结 + const now = Date.now(); + const previousState = confirmEnabled ? await this.readEmptyConfirmState() : null; + const previousWaveIds = Array.isArray(previousState && previousState.waveIds) + ? previousState.waveIds + : []; + const previousWaveIdSet = new Set(previousWaveIds); + const previousRoundAt = Number(previousState && previousState.roundAt || 0); + const previousStateUsable = Number.isFinite(previousRoundAt) + && previousRoundAt > 0 + && (now - previousRoundAt) >= confirmMinIntervalMs; + + const confirmedWaves = []; + const pendingConfirmWaves = []; + for (const item of emptyWaves) { + if (!confirmEnabled || (previousStateUsable && previousWaveIdSet.has(item.waveId))) { + confirmedWaves.push(item); + } else { + pendingConfirmWaves.push(item); + } + } + + if (confirmEnabled) { + // 状态仍在确认窗口内时保留首次判定时间,避免调度频率高于确认间隔时永远无法确认 + const nextRoundAt = previousRoundAt > 0 && !previousStateUsable ? previousRoundAt : now; + await this.writeEmptyConfirmState({ + roundAt: nextRoundAt, + waveIds: emptyWaves.map(item => item.waveId), + }); + } + + const confirmedWaveIds = confirmedWaves.map(item => item.waveId); + + let closedRowCount = 0; + if (!dryRun && confirmedWaveIds.length > 0) { + for (let offset = 0; offset < confirmedWaveIds.length; offset += WAVE_ID_BATCH_SIZE) { + const batchWaveIds = confirmedWaveIds.slice(offset, offset + WAVE_ID_BATCH_SIZE); + const updateResult = await ctx.model.query( + `UPDATE wms_wave_batch + SET wave_status = :closedStatus, + processed_orders = total_orders, + check_time = UTC_TIMESTAMP(), + update_time = UTC_TIMESTAMP() + WHERE wave_id IN (:waveIds) + AND wave_status IN (:waveStatuses) + AND total_orders > 0`, + { + replacements: { + closedStatus: CLOSED_WAVE_STATUS, + waveIds: batchWaveIds, + waveStatuses: ACTIVE_WAVE_STATUSES, + }, + type: ctx.model.QueryTypes.UPDATE, + } + ); + closedRowCount += extractAffectedRows(updateResult); + } + } + + const result = { + dryRun, + confirm_min_interval_ms: confirmMinIntervalMs, + candidate_count: candidateCount, + empty_count: emptyWaves.length, + confirmed_count: confirmedWaves.length, + closed_count: dryRun ? 0 : closedRowCount, + pending_confirm_count: pendingConfirmWaves.length, + pending_confirm_wave_ids: pendingConfirmWaves.map(item => item.waveId), + empty_wave_ids: emptyWaves.map(item => item.waveId), + unbound_count: unboundWaves.length, + unbound_wave_ids: unboundWaves.map(item => item.waveId), + misread_count: misreadWaves.length, + misread_wave_ids: misreadWaves.map(item => item.waveId), + probe_failed_count: probeFailedWaves.length, + probe_failed_wave_ids: probeFailedWaves.map(item => item.waveId), + warehouse_ids: warehouseIds, + closed_waves: confirmedWaves, + duration_ms: Date.now() - startedAt, + }; + + if (unboundWaves.length > 0) { + ctx.logger.warn( + `[wave-batch-closure] ${unboundWaves.length} 个波次订单表与索引表双空(疑似建波未完成或全量清空异常),` + + `不自动终结: ${formatWaveIdListForLog(unboundWaves.map(item => item.waveId))}` + ); + } + if (misreadWaves.length > 0) { + ctx.logger.warn( + `[wave-batch-closure] ${misreadWaves.length} 个波次判空与索引抽样核对不一致(疑似读偏),` + + `不自动终结: ${formatWaveIdListForLog(misreadWaves.map(item => item.waveId))}` + ); + } + + if (confirmedWaves.length > 0 || pendingConfirmWaves.length > 0 + || unboundWaves.length > 0 || misreadWaves.length > 0 || probeFailedWaves.length > 0) { + const pendingSuffix = pendingConfirmWaves.length > 0 + ? ` pendingWaves=${formatWaveIdListForLog(result.pending_confirm_wave_ids)}` + : ''; + const confirmedSuffix = confirmedWaveIds.length > 0 + ? ` waves=${formatWaveIdListForLog(confirmedWaveIds)}` + : ''; + const unboundSuffix = unboundWaves.length > 0 + ? ` unbound=${unboundWaves.length}` + : ''; + const misreadSuffix = misreadWaves.length > 0 + ? ` misread=${misreadWaves.length}` + : ''; + const probeFailedSuffix = probeFailedWaves.length > 0 + ? ` probeFailed=${probeFailedWaves.length}` + : ''; + ctx.logger.info( + `[wave-batch-closure] 波次终结结果 dryRun=${dryRun} candidate=${candidateCount}` + + ` confirmed=${confirmedWaves.length} closedRows=${result.closed_count}` + + ` pendingConfirm=${pendingConfirmWaves.length}${pendingSuffix}${confirmedSuffix}` + + `${unboundSuffix}${misreadSuffix}${probeFailedSuffix}` + ); + } + + return result; + } + + /** + * 归一化判空二次确认最小间隔。 + * + * @param {*} rawValue 原始入参。 + * @return {number} 毫秒数;未传/非法/负数时回落默认值,0 表示跳过确认。 + */ + normalizeConfirmIntervalMs(rawValue) { + if (rawValue === undefined || rawValue === null || rawValue === '') { + return EMPTY_CONFIRM_MIN_INTERVAL_MS; + } + + const numberValue = Number(rawValue); + if (!Number.isFinite(numberValue) || numberValue < 0) { + return EMPTY_CONFIRM_MIN_INTERVAL_MS; + } + + return Math.floor(numberValue); + } + + /** + * 读取上一轮判空二次确认状态。 + * + * 缓存不可用或读取异常时返回 null,调用方据此跳过本轮终结(宁可漏关,不可误关)。 + * + * @return {Promise<{ roundAt: number, waveIds: Array }|null>} 上一轮状态。 + */ + async readEmptyConfirmState() { + const { ctx } = this; + const app = ctx && ctx.app; + if (!app || typeof app.getCacheAsync !== 'function') { + ctx.logger.warn('[wave-batch-closure] 判空二次确认状态缓存不可用,本轮不终结任何波次'); + return null; + } + + try { + const cached = await app.getCacheAsync(EMPTY_CONFIRM_CACHE_KEY); + if (cached === undefined || cached === null) { + return null; + } + + const state = typeof cached === 'string' ? JSON.parse(cached) : cached; + if (!state || typeof state !== 'object') { + return null; + } + + return { + roundAt: Number(state.roundAt || 0), + waveIds: Array.isArray(state.waveIds) + ? state.waveIds.map(waveId => Number(waveId)).filter(waveId => Number.isInteger(waveId) && waveId > 0) + : [], + }; + } catch (error) { + ctx.logger.warn(`[wave-batch-closure] 读取判空二次确认状态失败,本轮不终结任何波次: ${error.message}`); + return null; + } + } + + /** + * 写入本轮判空二次确认状态(供下一轮确认)。 + * + * @param {{ roundAt: number, waveIds: Array }} state 状态。 + * @return {Promise} 无返回值。 + */ + async writeEmptyConfirmState(state) { + const { ctx } = this; + const app = ctx && ctx.app; + if (!app || typeof app.setCacheAsync !== 'function') { + return; + } + + try { + const waveIds = Array.isArray(state && state.waveIds) + ? state.waveIds.slice(0, EMPTY_CONFIRM_MAX_WAVE_COUNT) + : []; + await app.setCacheAsync( + EMPTY_CONFIRM_CACHE_KEY, + { + roundAt: Number(state && state.roundAt || Date.now()), + waveIds, + }, + EMPTY_CONFIRM_CACHE_TTL_SECONDS + ); + } catch (error) { + ctx.logger.warn(`[wave-batch-closure] 写入判空二次确认状态失败: ${error.message}`); + } + } +} + +module.exports = WaveBatchClosureService; diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js new file mode 100644 index 0000000..1c9ceb8 --- /dev/null +++ b/app/service/systems/waybill.js @@ -0,0 +1,1909 @@ +'use strict'; + +const MainService = require('../main'); +const ExcelJS = require('exceljs'); +const fs = require('fs'); +const fsp = require('fs').promises; +const path = require('path'); +const os = require('os'); + +/** 出站回调 method:批量查询运单揽收状态 */ +const WAYBILL_RECEIVE_EVENT = 'waybill.getreceive'; + +/** 单次回调最多携带的运单号数量(waybill.getreceive 外部接口上限 10 单) */ +const WAYBILL_RECEIVE_MAX_BATCH = 10; + +/** 揽收状态合法取值(与 wms_order_express.is_galaxy_receive 枚举一致) */ +const WAYBILL_RECEIVE_FLAGS = [ 'Y', 'N' ]; + +/** + * 揽收查询回调的签名模式:外部接口按 methods/warehouse_notify.json 协议验签 + * (md5(appSecret + timestamp + bodyJson)),与 /openapi 入站的 canonicalQuery 口径不同。 + */ +const WAYBILL_RECEIVE_SIGN_MODE = 'simple'; + +/** 出站回调 method:查询运单物流轨迹 */ +const WAYBILL_TRACE_EVENT = 'waybill.getTrace'; + +/** 轨迹查询回调签名模式:与揽收查询一致(仓库通知协议) */ +const WAYBILL_TRACE_SIGN_MODE = WAYBILL_RECEIVE_SIGN_MODE; + +/** + * 业务逻辑层:waybill(运单号快速查询)。 + */ +class WaybillService extends MainService { + /** + * 根据运单号查询有效订单ID,并返回该订单所属波次下所有订单ID列表。 + * + * 查询流程: + * 1. 通过运单号查询 wms_order_express 表获取 order_id 和 warehouse_id。 + * 2. 通过 order_id 遍历多表(current/history/dispatch)获取 wave_id 和 wave_no。 + * 3. 若有有效波次(wave_id > 0),遍历多表查询该波次下所有订单的 ID 列表。 + * + * @param {Object} params 查询参数。 + * @param {string} params.waybill_code 运单号,不可为空。 + * @return {Promise} 包含 order_id 和 waves 数组的对象。 + * @throws {Error} 当 waybill_code 为空或未找到匹配记录时抛出业务错误。 + */ + async toOrder({ waybill_code: waybillCode }) { + const { ctx } = this; + + if (!waybillCode || !String(waybillCode).trim()) { + this.throwError('运单号不能为空'); + } + + const userWarehouseId = ctx.user && ctx.user.store_id ? ctx.user.store_id : null; + const expressWhere = { + waybill_code: String(waybillCode).trim(), + status: 1, + }; + if (userWarehouseId) { + expressWhere.warehouse_id = userWarehouseId; + } + const record = await ctx.model.OrderExpress.findOne({ + where: expressWhere, + attributes: [ 'order_id', 'warehouse_id' ], + raw: true, + }); + + if (!record) { + this.throwError('未找到该运单号对应的订单'); + } + + const { order_id: orderId, warehouse_id: expressWarehouseId } = record; + + // 获取 warehouse_id:优先从 ctx.user.store_id,回退到运单记录中的 warehouse_id + const warehouseId = + (ctx.user && ctx.user.store_id) ? ctx.user.store_id : expressWarehouseId; + + // 构建多表遍历查询队列:current → history → dispatch + const orderDeliveryFactory = + ctx.model && ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { + label: 'current', + getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId), + }, + { + label: 'history', + getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId), + }, + { + label: 'dispatch', + getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId), + }, + ]; + + // 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历 + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId); + if (preferredLocation) { + tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (_err) { /* 定位失败,保持原遍历顺序 */ } + + // 遍历多表查询订单的 wave_id 和 wave_no + let orderRow = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') { + continue; + } + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no' ], + raw: true, + }); + if (row) { + orderRow = row; + break; + } + } catch (_err) { + continue; + } + } + + // 无订单记录或 wave_id 无效,返回空 waves + if (!orderRow || !orderRow.wave_id || Number(orderRow.wave_id) <= 0) { + return { order_id: orderId, waves: [] }; + } + + const { wave_id: waveId, wave_no: waveNo } = orderRow; + + // 遍历多表查询该波次下所有订单的 ID 列表 + const orderIds = []; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findAll !== 'function') { + continue; + } + const rows = await model.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + for (const row of rows) { + if (!orderIds.includes(row.id)) { + orderIds.push(row.id); + } + } + } catch (_err) { + continue; + } + } + + return { + order_id: orderId, + waves: [ + { + wave_id: waveId, + wave_no: waveNo, + order_ids: orderIds, + }, + ], + }; + } + + /** + * 解析主单号筛选条件(单值 / 数组 / 标准 where 对象),返回对应订单ID列表。 + * 先按主单号(business_key=1)在 wms_order_express 中定位 order_id,调用方再据此查询订单下所有运单(主+子)。 + * + * @param {*} mainWaybillCode 主单号条件值(字符串 / 字符串数组 / {operator,value} 标准化对象)。 + * @param {number} warehouseId 仓库ID(仓库隔离)。 + * @return {Promise<{empty: boolean, orderIds: number[]}>} empty=true 表示所有主单号均不存在,调用方应直接返回空结果;orderIds 去重后的订单ID列表。 + */ + async resolveMainWaybillOrderIds(mainWaybillCode, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const codes = (Array.isArray(mainWaybillCode) ? mainWaybillCode : [ mainWaybillCode ]) + .map(code => (code === undefined || code === null ? '' : String(code).trim())) + .filter(code => code !== ''); + + if (codes.length === 0) { + return { empty: false, orderIds: [] }; + } + + const mainRecords = await ctx.model.OrderExpress.findAll({ + where: { + waybill_code: { [Op.in]: codes }, + business_key: 1, + warehouse_id: warehouseId, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + if (!mainRecords || mainRecords.length === 0) { + return { empty: true, orderIds: [] }; + } + + const orderIds = []; + for (const record of mainRecords) { + const orderId = Number(record.order_id); + if (Number.isFinite(orderId) && !orderIds.includes(orderId)) { + orderIds.push(orderId); + } + } + if (orderIds.length === 0) { + return { empty: true, orderIds: [] }; + } + + return { empty: false, orderIds }; + } + + /** + * 构建运单查询条件(与 waybill.warehouse.list 完全一致的筛选口径,不含分页与排序)。 + * 供列表查询与「按条件批量更新揽收状态」共用,避免两处筛选逻辑漂移。 + * + * @param {Object} [rawWhere={}] 原始筛选条件(支持 operator/value 格式)。 + * @param {number} warehouseId 仓库ID(强制隔离,非空)。 + * @return {Promise<{ empty: boolean, queryWhere: Object }>} empty=true 表示条件已确定无匹配(如主单号均不存在)。 + */ + async buildListQueryWhere(rawWhere = {}, warehouseId) { + const { app } = this; + const { Op } = app.Sequelize; + + // 标准化 where 条件:将前端 operator/value 格式(如 {operator:"contains", value:"YT..."})统一转为标准条件对象 + const where = this.normalizeWhereParams(rawWhere); + + /** + * 从 where 条件中提取实际值。 + * 标准化后的条件为 {operator, value} 对象,本函数提取 .value; + * 对于未标准化的原始值(string/number)直接返回。 + * @param {*} c 条件值 + * @param {*} defaultValue 默认值 + * @return {*} 提取后的实际值 + */ + const val = (c, defaultValue) => { + if (c === undefined || c === null) return defaultValue; + if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value; + return c; + }; + + // 构建查询条件 + const queryWhere = { warehouse_id: warehouseId }; + + // 主单号查询:先通过主单号(支持单值/数组)定位 order_id,再查这些订单下所有运单(主+子) + const mainResolved = await this.resolveMainWaybillOrderIds(val(where.mainWaybillCode), warehouseId); + if (mainResolved.empty) { + // 主单号均不存在,条件已确定无匹配 + return { empty: true, queryWhere }; + } + if (mainResolved.orderIds.length > 0) { + // 单主单保持标量 order_id(向后兼容),多主单使用 Op.in + queryWhere.order_id = mainResolved.orderIds.length === 1 + ? mainResolved.orderIds[0] + : { [Op.in]: mainResolved.orderIds }; + } + + // 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like) + const waybillCode = val(where.waybillCode); + if (Array.isArray(waybillCode)) { + const waybillCodeList = waybillCode + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(item => item !== ''); + if (waybillCodeList.length > 0) { + queryWhere.waybill_code = { [Op.in]: waybillCodeList }; + } + } else if (waybillCode && String(waybillCode).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(waybillCode).trim()}%` }; + } + + // 订单ID等值 + const orderId = val(where.orderId); + if (orderId !== undefined && orderId !== null && String(orderId).trim() !== '') { + queryWhere.order_id = Number(orderId); + } + + // 订单号模糊搜索 + // TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释 + // if (where.orderNo && String(where.orderNo).trim()) { + // queryWhere.delivery_order_code = { [Op.like]: `%${String(where.orderNo).trim()}%` }; + // } + + // 物流公司编码等值 + const logisticsCode = val(where.logisticsCode); + if (logisticsCode && String(logisticsCode).trim()) { + queryWhere.logistics_code = String(logisticsCode).trim(); + } + + // 物流接口ID等值 + const logisticsInterfaceId = val(where.logisticsInterfaceId); + if (logisticsInterfaceId !== undefined && logisticsInterfaceId !== null && String(logisticsInterfaceId).trim() !== '') { + queryWhere.logistics_interface_id = Number(logisticsInterfaceId); + } + + // 平台编码等值 + const platformCode = val(where.platformCode); + if (platformCode && String(platformCode).trim()) { + queryWhere.platform_code = String(platformCode).trim(); + } + + // 运单状态等值 + const statusVal = val(where.status); + if (statusVal !== undefined && statusVal !== null && String(statusVal).trim() !== '') { + queryWhere.status = Number(statusVal); + } + + // 是否退回 + const isBack = val(where.isBack); + if (isBack && String(isBack).trim()) { + queryWhere.is_back = String(isBack).trim(); + } + + // 是否拦截 + const isIntercept = val(where.isIntercept); + if (isIntercept && String(isIntercept).trim()) { + queryWhere.is_intercept = String(isIntercept).trim(); + } + + // 是否揽收 + const isGalaxyReceive = val(where.isGalaxyReceive); + if (isGalaxyReceive && String(isGalaxyReceive).trim()) { + queryWhere.is_galaxy_receive = String(isGalaxyReceive).trim(); + } + + // 运单类型:主单号 / 子单号 + const waybillType = val(where.waybillType); + if (waybillType && String(waybillType).trim()) { + const type = String(waybillType).trim(); + if (type === 'main' || type === '1') { + queryWhere.business_key = 1; + } else if (type === 'child' || type === '2') { + queryWhere.business_key = { [Op.gt]: 1 }; + } + } + + // 货主ID等值 + const storeId = val(where.storeId); + if (storeId !== undefined && storeId !== null && String(storeId).trim() !== '') { + queryWhere.store_id = Number(storeId); + } + + // 包材ID等值 + const packageMaterialId = val(where.packageMaterialId); + if (packageMaterialId !== undefined && packageMaterialId !== null && String(packageMaterialId).trim() !== '') { + queryWhere.package_material_id = Number(packageMaterialId); + } + + // 是否已称重 + const hasWeighingWeight = val(where.hasWeighingWeight); + if (hasWeighingWeight !== undefined && hasWeighingWeight !== null && String(hasWeighingWeight).trim() !== '') { + const hasWeight = String(hasWeighingWeight).trim(); + if (hasWeight === 'true') { + queryWhere.weighing_weight = { [Op.gt]: 0 }; + } else if (hasWeight === 'false') { + queryWhere.weighing_weight = { [Op.eq]: 0 }; + } + } + + // 关键词模糊搜索 + const keyword = val(where.keyword); + if (keyword && String(keyword).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(keyword).trim()}%` }; + } + + // 创建时间范围:createdAt 支持 {operator:'between', value:[start,end]}(兼容 createAt 别名) + const createdAtRange = val(where.createdAt) ?? val(where.createAt); + if (Array.isArray(createdAtRange)) { + const [ unifiedCreateAtStart, unifiedCreateAtEnd ] = createdAtRange; + if (unifiedCreateAtStart && String(unifiedCreateAtStart).trim()) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: new Date(unifiedCreateAtStart) }; + } + if (unifiedCreateAtEnd && String(unifiedCreateAtEnd).trim()) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: new Date(unifiedCreateAtEnd) }; + } + } + // 兼容旧写法:createdAtStart / createdAtEnd + const createdAtStart = val(where.createdAtStart); + if (createdAtStart && String(createdAtStart).trim()) { + const startDate = this.normalizeDate(String(createdAtStart).trim(), false); + if (startDate) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; + } + } + const createdAtEnd = val(where.createdAtEnd); + if (createdAtEnd && String(createdAtEnd).trim()) { + const endDate = this.normalizeDate(String(createdAtEnd).trim(), true); + if (endDate) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate }; + } + } + + return { empty: false, queryWhere }; + } + + /** + * 按筛选条件解析运单号列表(用于按条件批量更新揽收状态)。 + * 复用 buildListQueryWhere,条件口径与 waybill.warehouse.list 完全一致;不含分页/排序。 + * + * @param {Object} options 查询参数。 + * @param {Object} [options.where={}] 筛选条件(同 list)。 + * @param {number} options.warehouseId 仓库ID。 + * @param {number} options.limit 最大返回数量(超出即判定超限,不做截断)。 + * @return {Promise<{ codes: Array, exceeded: boolean }>} 运单号列表与是否超限。 + */ + async resolveWaybillCodesByWhere({ where: rawWhere = {}, warehouseId, limit }) { + const maxCount = Math.max(Number(limit) || 0, 1); + const { empty, queryWhere } = await this.buildListQueryWhere(rawWhere, warehouseId); + if (empty) { + return { codes: [], exceeded: false }; + } + + const rows = await this.ctx.model.OrderExpress.findAll({ + attributes: [ 'waybill_code' ], + where: queryWhere, + limit: maxCount + 1, + raw: true, + }); + + if (rows.length > maxCount) { + return { codes: [], exceeded: true }; + } + + const codes = [ ...new Set(rows.map(row => String(row.waybill_code || '').trim()).filter(Boolean)) ]; + return { codes, exceeded: false }; + } + + /** + * 运单列表查询(仓库侧)。 + * 按仓库维度查询运单号列表,支持分页、多条件筛选、排序。 + * 核心查询仅使用 wms_order_express 单表(利用快照字段), + * 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。 + * + * @param {Object} [options={}] 查询参数。 + * @param {Object} [options.where] 筛选条件,支持 waybillCode(字符串模糊匹配 / 字符串数组精确匹配)/ mainWaybillCode(字符串 / 字符串数组精确匹配,数组时返回多个主单对应订单下的运单)/ orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。 + * @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。 + * @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。 + * @return {Promise} 运单列表与分页信息 { list, pagination }。 + */ + async list({ where: rawWhere = {}, pagination = {}, sort = {} } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 仓库隔离 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + this.throwError('用户未绑定仓库,无法查询运单'); + } + + // 分页参数 + const page = Math.max(Number(pagination.page) || 1, 1); + const pageSize = Math.min(Math.max(Number(pagination.pageSize) || 20, 1), 500); + + // 排序参数 + const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ]; + const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at'; + const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC'; + + // 查询条件:与「按条件批量更新揽收状态」共用同一套筛选口径 + const { empty, queryWhere } = await this.buildListQueryWhere(rawWhere, warehouseId); + if (empty) { + return { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0 }, + }; + } + const { count, rows } = await ctx.model.OrderExpress.findAndCountAll({ + where: queryWhere, + attributes: [ + 'id', 'waybill_code', 'order_id', 'business_key', 'status', + 'warehouse_id', 'store_id', + 'delivery_order_code', 'source_order_codes', + 'logistics_code', 'logistics_name', + 'logistics_interface_id', 'logistics_interface_name', + 'platform_code', + 'is_back', 'is_intercept', 'is_galaxy_receive', + 'weighing_weight', + 'package_material_id', 'package_material_name_snapshot', + 'create_at', + ], + order: [[ sortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + if (rows.length === 0) { + return { + list: [], + pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize) }, + }; + } + + // 提取所有唯一的 order_id + const orderIds = [ ...new Set(rows.map(r => r.order_id).filter(Boolean)) ]; + + // SELF JOIN:查询同 order_id 下 business_key=1 的主单号(强制同仓校验,避免跨仓串读) + const mainWaybillMap = new Map(); + if (orderIds.length > 0) { + const mainRecords = await ctx.model.OrderExpress.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + business_key: 1, + warehouse_id: warehouseId, + }, + attributes: [ 'order_id', 'waybill_code' ], + raw: true, + }); + for (const rec of mainRecords) { + if (!mainWaybillMap.has(rec.order_id)) { + mainWaybillMap.set(rec.order_id, rec.waybill_code); + } + } + } + + // 提取运单号列表,用于查询打印信息 + const waybillCodes = rows.map(r => r.waybill_code).filter(Boolean); + + // 查询货主备注名称(store_warehouse.store_remask) + const storeRemarkMap = new Map(); + const storeWarehouseKeys = rows + .filter(r => r.store_id && r.warehouse_id) + .map(r => `${r.store_id}:${r.warehouse_id}`); + const uniqueKeys = [ ...new Set(storeWarehouseKeys) ]; + if (uniqueKeys.length > 0 && ctx.model.StoreWarehouse) { + const swConditions = uniqueKeys.map(key => { + const [ storeId, whId ] = key.split(':'); + return { store_id: Number(storeId), warehouse_id: Number(whId) }; + }); + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { [Op.or]: swConditions }, + attributes: [ 'store_id', 'warehouse_id', 'store_remask' ], + raw: true, + }); + for (const sw of swRows) { + storeRemarkMap.set(`${sw.store_id}:${sw.warehouse_id}`, sw.store_remask || ''); + } + } + + // 查询打印记录(次数和最近打印时间) + const printInfoMap = new Map(); + if (waybillCodes.length > 0) { + const printRecords = await ctx.model.ExpressPrintRecord.findAll({ + where: { express_no: { [Op.in]: waybillCodes } }, + attributes: [ + 'express_no', + [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'print_count' ], + [ app.Sequelize.fn('MAX', app.Sequelize.col('print_time')), 'last_print_at' ], + ], + group: [ 'express_no' ], + raw: true, + }); + for (const pr of printRecords) { + printInfoMap.set(pr.express_no, { + print_count: Number(pr.print_count) || 0, + last_print_at: pr.last_print_at || null, + }); + } + } + + // 组装响应列表 + const list = rows.map(row => { + const wbCode = row.waybill_code || ''; + const mainCode = mainWaybillMap.get(row.order_id) || wbCode; + const printInfo = printInfoMap.get(wbCode) || { print_count: 0, last_print_at: null }; + + return { + id: row.id, + waybill_code: wbCode, + main_waybill_code: mainCode, + waybill_type: Number(row.business_key) === 1 ? '主单号' : '子单号', + order_id: row.order_id, + order_no: row.delivery_order_code || row.source_order_codes || '', + source_order_codes: row.source_order_codes || '', + warehouse_id: row.warehouse_id, + warehouse_name: '', + store_id: row.store_id || 0, + store_name: '', + store_remark_name: storeRemarkMap.get(`${row.store_id}:${row.warehouse_id}`) || '', + business_key: row.business_key, + status: row.status, + status_text: row.status === 1 ? '已分配' : '未分配', + logistics_code: row.logistics_code || '', + logistics_name: row.logistics_name || '', + logistics_interface_id: row.logistics_interface_id || 0, + logistics_interface_name: row.logistics_interface_name || '', + platform_code: row.platform_code || '', + is_back: row.is_back || 'N', + is_intercept: row.is_intercept || 'N', + is_galaxy_receive: row.is_galaxy_receive || 'N', + weighing_weight: row.weighing_weight || 0, + weighing_weight_display: row.weighing_weight > 0 ? `${(row.weighing_weight / 1000).toFixed(2)} kg` : '0 kg', + package_material_id: row.package_material_id || 0, + package_material_name: row.package_material_name_snapshot || '', + print_count: printInfo.print_count, + last_print_at: printInfo.last_print_at ? this.app.formatDate(printInfo.last_print_at) : null, + create_at: row.create_at ? this.app.formatDate(row.create_at) : null, + }; + }); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + }, + }; + } + + /** + * 运单详情查询(仓库侧)。 + * 查询单个运单的完整信息,包含关联订单、兄弟运单、打印记录、打包信息。 + * + * @param {Object} options 查询参数。 + * @param {number} [options.id] 运单记录ID。 + * @param {string} [options.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。 + * @return {Promise} 运单详情。 + * @throws {Error} 当运单不存在或参数无效时抛出业务错误。 + */ + async detail({ id, waybillCode } = {}) { + const { ctx } = this; + + // 仓库隔离 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + this.throwError('用户未绑定仓库,无法查询运单'); + } + + // 构建查询条件 + const expressWhere = { warehouse_id: warehouseId }; + if (waybillCode && String(waybillCode).trim()) { + expressWhere.waybill_code = String(waybillCode).trim(); + } else if (id !== undefined && id !== null && String(id).trim() !== '') { + expressWhere.id = Number(id); + } else { + this.throwError('运单ID或运单号不能为空'); + } + + // 查询运单主记录 + const record = await ctx.model.OrderExpress.findOne({ + where: expressWhere, + raw: true, + }); + + if (!record) { + this.throwError('未找到该运单'); + } + + const orderId = record.order_id; + + // 查询同订单下所有运单(兄弟运单) + const siblingWaybills = await ctx.model.OrderExpress.findAll({ + where: { order_id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'waybill_code', 'business_key' ], + order: [[ 'business_key', 'ASC' ]], + raw: true, + }); + + const mainWaybillRecord = siblingWaybills.find(s => Number(s.business_key) === 1); + const mainWaybillCode = mainWaybillRecord ? mainWaybillRecord.waybill_code : (record.waybill_code || ''); + + const siblingList = siblingWaybills.map(s => ({ + waybill_code: s.waybill_code || '', + business_key: s.business_key, + waybill_type: Number(s.business_key) === 1 ? '主单号' : '子单号', + })); + + // 通过 OrderDeliveryFactory 多表遍历查询订单信息 + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + let orderInfo = null; + if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') { + continue; + } + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ + 'id', 'delivery_order_code', 'warehouse_id', 'store_id', + 'wave_id', 'wave_no', 'order_type', 'store_name', + ], + raw: true, + }); + if (row) { + orderInfo = { + order_id: row.id, + order_no: row.delivery_order_code || '', + warehouse_id: row.warehouse_id, + // TODO: 快照列未落库,暂时填空;快照就绪后替换为 record.warehouse_name_snapshot + warehouse_name: '', + store_id: row.store_id || 0, + store_name: row.store_name || '', + wave_id: row.wave_id || 0, + wave_no: row.wave_no || '', + order_type: row.order_type || 'delivery', + }; + break; + } + } catch (_err) { + continue; + } + } + } + + // 若遍历失败,用已有信息兜底 + // TODO: 快照列未落库,暂用空值兜底;快照就绪后替换为 record.xxx_snapshot + if (!orderInfo) { + orderInfo = { + order_id: orderId, + order_no: '', + warehouse_id: record.warehouse_id, + warehouse_name: '', + store_id: 0, + store_name: '', + wave_id: 0, + wave_no: '', + order_type: 'delivery', + }; + } + + // 查询打印记录 + let printRecords = []; + if (record.waybill_code) { + printRecords = await ctx.model.ExpressPrintRecord.findAll({ + where: { express_no: record.waybill_code }, + attributes: [ + 'id', 'printer_name', 'template_id', 'platform', + 'print_time', + ], + order: [[ 'print_time', 'DESC' ]], + raw: true, + }); + } + + // 组装详情响应 + return { + id: record.id, + waybill_code: record.waybill_code || '', + main_waybill_code: mainWaybillCode, + waybill_type: Number(record.business_key) === 1 ? '主单号' : '子单号', + business_key: record.business_key, + sibling_waybills: siblingList, + order: orderInfo, + logistics: { + logistics_code: record.logistics_code || '', + logistics_name: record.logistics_name || '', + logistics_interface_id: record.logistics_interface_id || 0, + logistics_interface_name: record.logistics_interface_name || '', + platform_code: record.platform_code || '', + }, + status_info: { + status: record.status, + status_text: record.status === 1 ? '已分配' : '未分配', + is_back: record.is_back || 'N', + is_intercept: record.is_intercept || 'N', + is_galaxy_receive: record.is_galaxy_receive || 'N', + }, + weight: { + weighing_weight: record.weighing_weight || 0, + weighing_weight_display: record.weighing_weight > 0 + ? `${(record.weighing_weight / 1000).toFixed(2)} kg` + : '0 kg', + }, + package: { + package_material_id: record.package_material_id || 0, + package_material_name: record.package_material_name_snapshot || '', + }, + print_records: printRecords.map(pr => ({ + id: pr.id, + printer_name: pr.printer_name || '', + template_id: pr.template_id || 0, + template_name: '', + platform: pr.platform || '', + printed_at: pr.print_time ? this.app.formatDate(pr.print_time) : null, + })), + print_count: printRecords.length, + printinfo: record.printinfo || null, + ver: record.ver || '', + retry_count: record.retry_count || 0, + create_at: record.create_at ? this.app.formatDate(record.create_at) : null, + delete_at: record.delete_at ? this.app.formatDate(record.delete_at) : null, + }; + } + + /** + * 运单导出(仓库侧)。 + * 复用 list 的筛选逻辑,分批查询,支持进度回调。 + * + * @param {Object} options 导出参数。 + * @param {Object} [options.where={}] 筛选条件(同 list,另支持 ids:运单ID数组,精确过滤)。 + * @param {Object} [options.sort={}] 排序参数(同 list)。 + * @param {string[]} [options.exportFields] 需要导出的字段列表,不传则导出全部字段。 + * @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。 + * @return {Promise} 导出结果 { list, current_count, total_count, url }。 + */ + async export({ where: rawWhere = {}, sort = {}, exportFields, onProgress } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 标准化 where 条件 + const where = this.normalizeWhereParams(rawWhere); + /** + * 从标准化后的 where 条件中提取实际值。 + * @param {*} c 条件值 + * @param {*} defaultValue 默认值 + * @return {*} 提取后的实际值 + */ + const val = (c, defaultValue) => { + if (c === undefined || c === null) return defaultValue; + if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value; + return c; + }; + + // 仓库隔离 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + this.throwError('用户未绑定仓库,无法导出运单'); + } + + // 排序参数 + const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ]; + const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at'; + const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC'; + + // 构建查询条件(同 list) + const queryWhere = { warehouse_id: warehouseId }; + + // 指定运单ID列表(勾选导出,按 wms_order_express.id 精确过滤) + const idsExport = val(where.ids); + if (Array.isArray(idsExport) && idsExport.length > 0) { + const idList = idsExport + .map(id => Number(id)) + .filter(id => Number.isFinite(id) && id > 0); + if (idList.length > 0) { + queryWhere.id = { [Op.in]: idList }; + } + } + + // 主单号查询(支持单值/数组,与 list 保持一致) + const mainResolvedExport = await this.resolveMainWaybillOrderIds(val(where.mainWaybillCode), warehouseId); + if (mainResolvedExport.empty) { + if (typeof onProgress === 'function') { + await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } }); + } + return { list: [], current_count: 0, total_count: 0, url: '' }; + } + if (mainResolvedExport.orderIds.length > 0) { + // 单主单保持标量 order_id(向后兼容),多主单使用 Op.in + queryWhere.order_id = mainResolvedExport.orderIds.length === 1 + ? mainResolvedExport.orderIds[0] + : { [Op.in]: mainResolvedExport.orderIds }; + } + + // 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like),与 list 保持一致 + const waybillCodeExport = val(where.waybillCode); + if (Array.isArray(waybillCodeExport)) { + const waybillCodeListExport = waybillCodeExport + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(item => item !== ''); + if (waybillCodeListExport.length > 0) { + queryWhere.waybill_code = { [Op.in]: waybillCodeListExport }; + } + } else if (waybillCodeExport && String(waybillCodeExport).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(waybillCodeExport).trim()}%` }; + } + const orderIdExport = val(where.orderId); + if (orderIdExport !== undefined && orderIdExport !== null && String(orderIdExport).trim() !== '') { + queryWhere.order_id = Number(orderIdExport); + } + // TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释 + const logisticsCodeExport = val(where.logisticsCode); + if (logisticsCodeExport && String(logisticsCodeExport).trim()) { + queryWhere.logistics_code = String(logisticsCodeExport).trim(); + } + const logisticsInterfaceIdExport = val(where.logisticsInterfaceId); + if (logisticsInterfaceIdExport !== undefined && logisticsInterfaceIdExport !== null && String(logisticsInterfaceIdExport).trim() !== '') { + queryWhere.logistics_interface_id = Number(logisticsInterfaceIdExport); + } + const platformCodeExport = val(where.platformCode); + if (platformCodeExport && String(platformCodeExport).trim()) { + queryWhere.platform_code = String(platformCodeExport).trim(); + } + const statusExport = val(where.status); + if (statusExport !== undefined && statusExport !== null && String(statusExport).trim() !== '') { + queryWhere.status = Number(statusExport); + } + const isBackExport = val(where.isBack); + if (isBackExport && String(isBackExport).trim()) { + queryWhere.is_back = String(isBackExport).trim(); + } + const isInterceptExport = val(where.isIntercept); + if (isInterceptExport && String(isInterceptExport).trim()) { + queryWhere.is_intercept = String(isInterceptExport).trim(); + } + const isGalaxyReceiveExport = val(where.isGalaxyReceive); + if (isGalaxyReceiveExport && String(isGalaxyReceiveExport).trim()) { + queryWhere.is_galaxy_receive = String(isGalaxyReceiveExport).trim(); + } + const waybillTypeExport = val(where.waybillType); + if (waybillTypeExport && String(waybillTypeExport).trim()) { + const type = String(waybillTypeExport).trim(); + if (type === 'main' || type === '1') { + queryWhere.business_key = 1; + } else if (type === 'child' || type === '2') { + queryWhere.business_key = { [Op.gt]: 1 }; + } + } + // 货主ID等值 + const storeIdExport = val(where.storeId); + if (storeIdExport !== undefined && storeIdExport !== null && String(storeIdExport).trim() !== '') { + queryWhere.store_id = Number(storeIdExport); + } + const packageMaterialIdExport = val(where.packageMaterialId); + if (packageMaterialIdExport !== undefined && packageMaterialIdExport !== null && String(packageMaterialIdExport).trim() !== '') { + queryWhere.package_material_id = Number(packageMaterialIdExport); + } + const hasWeighingWeightExport = val(where.hasWeighingWeight); + if (hasWeighingWeightExport !== undefined && hasWeighingWeightExport !== null && String(hasWeighingWeightExport).trim() !== '') { + const hasWeight = String(hasWeighingWeightExport).trim(); + if (hasWeight === 'true') { + queryWhere.weighing_weight = { [Op.gt]: 0 }; + } else if (hasWeight === 'false') { + queryWhere.weighing_weight = { [Op.eq]: 0 }; + } + } + const keywordExport = val(where.keyword); + if (keywordExport && String(keywordExport).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(keywordExport).trim()}%` }; + } + // 创建时间范围:createdAt 支持 {operator:'between', value:[start,end]}(兼容 createAt 别名) + const createdAtRangeExport = val(where.createdAt) ?? val(where.createAt); + if (Array.isArray(createdAtRangeExport)) { + const [ unifiedCreateAtStartExport, unifiedCreateAtEndExport ] = createdAtRangeExport; + if (unifiedCreateAtStartExport && String(unifiedCreateAtStartExport).trim()) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: new Date(unifiedCreateAtStartExport) }; + } + if (unifiedCreateAtEndExport && String(unifiedCreateAtEndExport).trim()) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: new Date(unifiedCreateAtEndExport) }; + } + } + // 兼容旧写法:createdAtStart / createdAtEnd + const createdAtStartExport = val(where.createdAtStart); + if (createdAtStartExport && String(createdAtStartExport).trim()) { + const startDate = this.normalizeDate(String(createdAtStartExport).trim(), false); + if (startDate) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; + } + } + const createdAtEndExport = val(where.createdAtEnd); + if (createdAtEndExport && String(createdAtEndExport).trim()) { + const endDate = this.normalizeDate(String(createdAtEndExport).trim(), true); + if (endDate) { + queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate }; + } + } + + // 先统计总数 + if (typeof onProgress === 'function') { + await onProgress({ status: 'running', progress: 10, currentCount: 0, totalCount: 0, message: '正在统计数据…' }); + } + const totalCount = await ctx.model.OrderExpress.count({ where: queryWhere }); + + if (totalCount === 0) { + if (typeof onProgress === 'function') { + await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } }); + } + return { list: [], current_count: 0, total_count: 0, url: '' }; + } + + if (typeof onProgress === 'function') { + await onProgress({ status: 'running', progress: 15, currentCount: 0, totalCount, message: `共 ${totalCount} 条,正在导出…` }); + } + + // 分批查询(避免大数据量内存溢出) + const EXPORT_PAGE_SIZE = 500; + const allRows = []; + const totalPages = Math.ceil(totalCount / EXPORT_PAGE_SIZE); + + for (let page = 0; page < totalPages; page++) { + const pageRows = await ctx.model.OrderExpress.findAll({ + where: queryWhere, + attributes: [ + 'id', 'waybill_code', 'order_id', 'business_key', 'status', + 'warehouse_id', 'store_id', + 'delivery_order_code', 'source_order_codes', + 'logistics_code', 'logistics_name', + 'logistics_interface_id', 'logistics_interface_name', + 'platform_code', + 'is_back', 'is_intercept', 'is_galaxy_receive', + 'weighing_weight', + 'package_material_id', 'package_material_name_snapshot', + 'create_at', + ], + order: [[ sortField, sortOrder ]], + limit: EXPORT_PAGE_SIZE, + offset: page * EXPORT_PAGE_SIZE, + raw: true, + }); + allRows.push(...pageRows); + + // 进度回调(15% ~ 90%) + if (typeof onProgress === 'function') { + const progress = 15 + Math.round(75 * (page + 1) / totalPages); + await onProgress({ + status: 'running', + progress, + currentCount: allRows.length, + totalCount, + message: `已导出 ${allRows.length} / ${totalCount} 条`, + }); + } + } + + // 提取所有唯一的 order_id,SELF JOIN 主单号 + const orderIds = [ ...new Set(allRows.map(r => r.order_id).filter(Boolean)) ]; + const mainWaybillMap = new Map(); + if (orderIds.length > 0) { + const mainRecords = await ctx.model.OrderExpress.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + business_key: 1, + }, + attributes: [ 'order_id', 'waybill_code' ], + raw: true, + }); + for (const rec of mainRecords) { + if (!mainWaybillMap.has(rec.order_id)) { + mainWaybillMap.set(rec.order_id, rec.waybill_code); + } + } + } + + // 预定义全部导出字段映射 + const allFieldMap = { + id: r => r.id, + waybill_code: r => r.waybill_code || '', + main_waybill_code: r => mainWaybillMap.get(r.order_id) || r.waybill_code || '', + waybill_type: r => (Number(r.business_key) === 1 ? '主单号' : '子单号'), + order_id: r => r.order_id, + order_no: r => r.delivery_order_code || r.source_order_codes || '', + source_order_codes: r => r.source_order_codes || '', + warehouse_id: r => r.warehouse_id, + warehouse_name: () => '', + store_id: r => r.store_id || 0, + store_name: () => '', + business_key: r => r.business_key, + status: r => r.status, + status_text: r => (r.status === 1 ? '已分配' : '未分配'), + logistics_code: r => r.logistics_code || '', + logistics_name: r => r.logistics_name || '', + logistics_interface_id: r => r.logistics_interface_id || 0, + logistics_interface_name: r => r.logistics_interface_name || '', + platform_code: r => r.platform_code || '', + is_back: r => r.is_back || 'N', + is_intercept: r => r.is_intercept || 'N', + is_galaxy_receive: r => r.is_galaxy_receive || 'N', + weighing_weight: r => r.weighing_weight || 0, + weighing_weight_display: r => (r.weighing_weight > 0 ? `${(r.weighing_weight / 1000).toFixed(2)} kg` : '0 kg'), + package_material_id: r => r.package_material_id || 0, + package_material_name: r => r.package_material_name_snapshot || '', + create_at: r => (r.create_at ? this.app.formatDate(r.create_at) : null), + }; + + // 确定导出字段集 + const fields = Array.isArray(exportFields) && exportFields.length > 0 + ? exportFields.filter(f => allFieldMap[f]) + : Object.keys(allFieldMap); + + const list = allRows.map(row => { + const item = {}; + for (const field of fields) { + item[field] = allFieldMap[field](row); + } + return item; + }); + + if (typeof onProgress === 'function') { + await onProgress({ + status: 'running', + progress: 95, + currentCount: allRows.length, + totalCount, + message: '正在生成导出文件…', + }); + } + + // 生成 Excel 文件并上传 + const result = await this.buildWaybillExportFile({ + list, + fields, + warehouseId, + totalCount: allRows.length, + }); + + if (typeof onProgress === 'function') { + await onProgress({ + status: 'success', + progress: 100, + currentCount: allRows.length, + totalCount, + message: '导出完成', + result, + }); + } + + return result; + } + + /** + * 生成运单导出 Excel 文件并上传,返回下载链接。 + * @param {Object} options 导出选项。 + * @param {Array} options.list 导出数据列表。 + * @param {string[]} options.fields 导出字段列表。 + * @param {number} options.warehouseId 仓库ID。 + * @param {number} options.totalCount 总条数。 + * @return {Promise} { current_count, total_count, url }。 + */ + async buildWaybillExportFile({ list, fields, warehouseId, totalCount } = {}) { + const { ctx } = this; + + // 列名中文映射 + const COLUMN_LABELS = { + id: 'ID', + waybill_code: '运单号', + main_waybill_code: '主单号', + waybill_type: '运单类型', + order_id: '订单ID', + order_no: '订单号', + source_order_codes: '原始订单号', + warehouse_id: '仓库ID', + warehouse_name: '仓库名称', + store_id: '货主ID', + store_name: '货主名称', + business_key: '拆单序号', + status: '状态', + status_text: '状态', + logistics_code: '物流编码', + logistics_name: '物流名称', + logistics_interface_id: '物流接口ID', + logistics_interface_name: '物流接口名称', + platform_code: '平台编码', + is_back: '是否退回', + is_intercept: '是否拦截', + is_galaxy_receive: '是否揽收', + weighing_weight: '称重重量(g)', + weighing_weight_display: '称重重量', + package_material_id: '包材ID', + package_material_name: '包材名称', + create_at: '创建时间', + }; + + // 生成 Excel + const workbook = new ExcelJS.Workbook(); + const worksheet = workbook.addWorksheet('运单导出'); + + // 写表头 + const headerRow = worksheet.addRow(fields.map(f => COLUMN_LABELS[f] || f)); + headerRow.font = { bold: true }; + headerRow.alignment = { horizontal: 'center' }; + + // 写数据 + for (const row of list) { + worksheet.addRow(fields.map(f => (row[f] !== undefined && row[f] !== null ? row[f] : ''))); + } + + // 保存到临时文件 + const now = new Date(); + const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `运单导出_${dateStr}.xlsx`; + const tmpDir = os.tmpdir(); + const filePath = path.join(tmpDir, `waybill_export_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.xlsx`); + + await workbook.xlsx.writeFile(filePath); + + // 上传文件 + const uploadService = ctx?.service?.systems?.upload; + let url = ''; + let fileKey = ''; + + if (uploadService && typeof uploadService.uploadFile === 'function') { + try { + const stat = await fsp.stat(filePath); + const safeWarehouseId = String(warehouseId || 'unknown'); + const randomToken = Math.random().toString(36).slice(2, 8); + const uploadKey = `exports/waybill/${safeWarehouseId}/${Date.now()}_${randomToken}.xlsx`; + + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + url = uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || ''; + fileKey = uploadResult.fileName || ''; + + // 记录上传文件 + if (typeof uploadService.uploadSuccessNotify === 'function') { + await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'waybillExport', + businessId: `${warehouseId}`, + uploaderType: ctx?.user?.role || 'system_api', + uploaderDept: ctx?.user?.department || '', + }); + } + } catch (uploadError) { + ctx.logger.error('[WaybillService.buildWaybillExportFile] 文件上传失败', { + error: uploadError.message, + filename, + }); + } + } + + // 清理临时文件 + try { + await fsp.unlink(filePath); + } catch (_e) { + // 忽略清理错误 + } + + return { + current_count: totalCount, + total_count: totalCount, + url, + fileKey, + filename, + }; + } + + /** + * 批量查询运单揽收状态(出站回调 waybill.getreceive)。 + * + * 业务报文:`{ waybill_codes: [...] }`,经 `openapi.callback.sendByAppKey` 统一 + * 包装为 `{ request: { waybill_codes: [...] } }` 发送(与其它出站回调一致)。 + * 运单号会按 `buildWaybillQueryCodeMap` 规则补寄件电话后四位(`运单号|后四位`)。 + * 外部返回 `[{ waybill_code, is_galaxy_receive: 1|0 }]`,兼容 `{ code, data: [...] }` 包装 + * 与 `'Y'/'N'` 字符串取值;命中结果按 waybill_code + warehouse_id 回写 + * `wms_order_express.is_galaxy_receive`。 + * + * 目标应用:未显式传 appKey 时,取该仓库下 callback_functions 勾选了 + * waybill.getreceive 的首个应用(按 id 升序),口径与 notify.reply 的路由一致。 + * + * @param {Object} options 查询参数。 + * @param {number} options.warehouseId 仓库 ID,用于回写隔离。 + * @param {Array} options.waybillCodes 运单号列表。 + * @param {string} [options.appKey] 指定目标应用 AppKey,不传则按仓库订阅关系解析。 + * @param {Function} [options.onProgress] 进度回调,每批完成后触发 + * ({ status, progress, currentCount, totalCount, message, updated, unchanged, failed })。 + * @return {Promise} 结果 { success, event, app_key, total, updated, unchanged, not_found, failed, reason }。 + */ + async queryReceiveStatus({ warehouseId, waybillCodes, appKey = '', onProgress = null } = {}) { + const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId) || 0; + const codes = this.normalizeWaybillCodes(waybillCodes); + const base = { + success: false, + event: WAYBILL_RECEIVE_EVENT, + app_key: String(appKey || '').trim(), + total: codes.length, + updated: 0, + unchanged: 0, + not_found: [], + failed: [], + }; + + if (codes.length === 0) { + return { ...base, reason: '运单号不能为空' }; + } + if (!normalizedWarehouseId) { + return { ...base, reason: '缺少仓库ID' }; + } + + const targetAppKey = base.app_key + || await this.resolveReceiveQueryAppKey(normalizedWarehouseId); + if (!targetAppKey) { + return { + ...base, + skipped: true, + reason: '无应用承接该回调 method(callback_functions 未勾选或应用未启用)', + }; + } + + const callbackService = ctx.service.openapi && ctx.service.openapi.callback; + if (!callbackService || typeof callbackService.sendByAppKey !== 'function') { + return { ...base, app_key: targetAppKey, reason: 'OpenAPI 回调服务不可用' }; + } + + const statusMap = new Map(); + const failed = []; + const queryCodeMap = await this.buildWaybillQueryCodeMap({ + warehouseId: normalizedWarehouseId, + waybillCodes: codes, + }); + let processedCount = 0; + for (let offset = 0; offset < codes.length; offset += WAYBILL_RECEIVE_MAX_BATCH) { + const batch = codes.slice(offset, offset + WAYBILL_RECEIVE_MAX_BATCH); + const result = await callbackService.sendByAppKey({ + appKey: targetAppKey, + event: WAYBILL_RECEIVE_EVENT, + request: { waybill_codes: batch.map(code => queryCodeMap.get(code) || code) }, + signMode: WAYBILL_RECEIVE_SIGN_MODE, + }); + + if (!result || result.success !== true) { + const error = String(result && result.error || '未知错误'); + ctx.logger.warn('[WaybillService.queryReceiveStatus] 揽收查询回调失败', { + warehouseId: normalizedWarehouseId, + appKey: targetAppKey, + batchSize: batch.length, + error, + }); + for (const code of batch) { + failed.push({ waybill_code: code, reason: `回调失败: ${error}` }); + } + } else if (this.extractReceiveError(result.response)) { + // HTTP 200 但业务码非成功(如验签失败 code=401):整批计失败,避免静默当作「无数据」 + const error = this.extractReceiveError(result.response); + ctx.logger.warn('[WaybillService.queryReceiveStatus] 外部接口返回业务失败', { + warehouseId: normalizedWarehouseId, + appKey: targetAppKey, + batchSize: batch.length, + error, + }); + for (const code of batch) { + failed.push({ waybill_code: code, reason: `外部接口返回失败: ${error}` }); + } + } else { + for (const row of this.extractReceiveRows(result.response)) { + const code = this.stripWaybillCodeSuffix(String(row && (row.waybill_code || row.waybillCode) || '').trim()); + if (!code) continue; + const flag = this.normalizeReceiveFlag(row.is_galaxy_receive); + if (!flag) { + failed.push({ waybill_code: code, reason: 'is_galaxy_receive 取值非法' }); + continue; + } + statusMap.set(code, flag); + } + } + + processedCount += batch.length; + await this.reportReceiveProgress(onProgress, { + processedCount, + totalCount: codes.length, + failedCount: failed.length, + }); + } + + const queriedCodes = [ ...statusMap.keys() ]; + if (queriedCodes.length === 0) { + return { ...base, app_key: targetAppKey, failed }; + } + + const { Op } = this.app.Sequelize; + const rows = await ctx.model.OrderExpress.findAll({ + attributes: [ 'waybill_code', 'is_galaxy_receive' ], + where: { + waybill_code: { [Op.in]: queriedCodes }, + warehouse_id: normalizedWarehouseId, + }, + raw: true, + }); + + const existingMap = new Map(rows.map(row => [ String(row.waybill_code || ''), String(row.is_galaxy_receive || 'N') ])); + const notFound = queriedCodes.filter(code => !existingMap.has(code)); + + let updated = 0; + let unchanged = 0; + for (const flag of WAYBILL_RECEIVE_FLAGS) { + const targets = []; + for (const [ code, current ] of existingMap.entries()) { + if (statusMap.get(code) !== flag) continue; + if (current === flag) { + unchanged++; + continue; + } + targets.push(code); + } + if (targets.length === 0) continue; + + const [ affected ] = await ctx.model.OrderExpress.update( + { is_galaxy_receive: flag }, + { + where: { + waybill_code: { [Op.in]: targets }, + warehouse_id: normalizedWarehouseId, + }, + } + ); + updated += Number(affected) || targets.length; + } + + ctx.logger.info('[WaybillService.queryReceiveStatus] 揽收状态同步完成', { + warehouseId: normalizedWarehouseId, + appKey: targetAppKey, + total: codes.length, + queried: queriedCodes.length, + updated, + unchanged, + notFound: notFound.length, + failed: failed.length, + }); + + return { + ...base, + success: true, + app_key: targetAppKey, + updated, + unchanged, + not_found: notFound, + failed, + }; + } + + /** + * 触发揽收查询进度回调(未传 onProgress 时静默跳过)。 + * 进度按已处理条数计算并封顶 99%,剩余 1% 由调用方在任务完成时置 100%。 + * @param {Function|null} onProgress 调用方进度回调。 + * @param {Object} options 进度数据。 + * @param {number} options.processedCount 已处理运单号数量。 + * @param {number} options.totalCount 运单号总数。 + * @param {number} options.failedCount 已失败数量。 + * @return {Promise} 无返回值。 + */ + async reportReceiveProgress(onProgress, { processedCount, totalCount, failedCount } = {}) { + if (typeof onProgress !== 'function') return; + + const total = Number(totalCount) || 0; + const processed = Math.min(Number(processedCount) || 0, total); + const progress = total > 0 + ? Math.min(99, Math.round((processed / total) * 100)) + : 0; + + await onProgress({ + status: 'running', + progress, + currentCount: processed, + totalCount: total, + message: `已查询 ${processed}/${total} 单${failedCount > 0 ? `(失败 ${failedCount})` : ''}`, + failedCount: Number(failedCount) || 0, + }); + } + + /** + * 规范化运单号:转字符串、去空格、去空、去重。 + * @param {Array} waybillCodes 原始运单号列表。 + * @return {Array} 规范化后的运单号列表。 + */ + normalizeWaybillCodes(waybillCodes) { + if (!Array.isArray(waybillCodes)) return []; + return [ ...new Set(waybillCodes.map(code => String(code || '').trim()).filter(Boolean)) ]; + } + + /** + * 去掉运单号上的 `|电话后四位` 查询后缀,还原成纯运单号。 + * @param {string} code 运单号(可能带后缀)。 + * @return {string} 纯运单号。 + */ + stripWaybillCodeSuffix(code) { + const text = String(code === undefined || code === null ? '' : code).trim(); + const index = text.indexOf('|'); + return index === -1 ? text : text.slice(0, index).trim(); + } + + /** + * 取寄件电话的后四位(非数字字符先剔除)。 + * @param {string} tel 寄件电话。 + * @return {string} 后四位数字,位数不足时返回空字符串。 + */ + extractSenderTelLast4(tel) { + const digits = String(tel === undefined || tel === null ? '' : tel).replace(/\D/g, ''); + return digits.length >= 4 ? digits.slice(-4) : ''; + } + + /** + * 构建出站查询的运单号映射(原始运单号 → 出站查询值)。 + * + * 外部快递接口(中通轨迹/揽收查询)要求 `运单号|收寄件人手机号后四位` 才能查询: + * 按 warehouse_id 命中 `wms_order_express` 后,用 `logistics_interface_id` 取 + * `wms_express_interface.sender_tel` 的后四位拼接。未命中运单、未关联物流接口 + * 或接口未配置电话时,保持原始运单号发送。 + * + * @param {Object} options 参数。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {Array} options.waybillCodes 原始运单号列表。 + * @return {Promise>} 原始运单号 → 出站查询运单号。 + */ + async buildWaybillQueryCodeMap({ warehouseId, waybillCodes = [] } = {}) { + const { ctx } = this; + const codes = this.normalizeWaybillCodes(waybillCodes); + const map = new Map(codes.map(code => [ code, code ])); + if (codes.length === 0) return map; + + const OrderExpress = ctx.model && ctx.model.OrderExpress; + const ExpressInterface = ctx.model && ctx.model.ExpressInterface; + if (!OrderExpress || !ExpressInterface) return map; + + const { Op } = this.app.Sequelize; + const normalizedWarehouseId = Number(warehouseId) || 0; + const expressWhere = { waybill_code: { [Op.in]: codes } }; + if (normalizedWarehouseId) { + expressWhere.warehouse_id = normalizedWarehouseId; + } + + let expressRows = []; + try { + expressRows = await OrderExpress.findAll({ + attributes: [ 'waybill_code', 'logistics_interface_id' ], + where: expressWhere, + raw: true, + }); + } catch (e) { + ctx.logger.warn('[WaybillService.buildWaybillQueryCodeMap] 查询运单快递信息失败', { + warehouseId: normalizedWarehouseId, + error: e && e.message ? e.message : `${e}`, + }); + return map; + } + + const interfaceIdByCode = new Map(); + for (const row of expressRows || []) { + const code = this.stripWaybillCodeSuffix(String(row && row.waybill_code || '').trim()); + const interfaceId = Number(row && row.logistics_interface_id) || 0; + if (!code || !interfaceId || interfaceIdByCode.has(code)) continue; + interfaceIdByCode.set(code, interfaceId); + } + if (interfaceIdByCode.size === 0) return map; + + let interfaceRows = []; + try { + interfaceRows = await ExpressInterface.findAll({ + attributes: [ 'id', 'sender_tel' ], + where: { id: { [Op.in]: [ ...new Set(interfaceIdByCode.values()) ] } }, + raw: true, + }); + } catch (e) { + ctx.logger.warn('[WaybillService.buildWaybillQueryCodeMap] 查询快递接口配置失败', { + warehouseId: normalizedWarehouseId, + error: e && e.message ? e.message : `${e}`, + }); + return map; + } + + const telById = new Map( + (interfaceRows || []).map(row => [ Number(row && row.id) || 0, row && row.sender_tel ]) + ); + for (const [ code, interfaceId ] of interfaceIdByCode.entries()) { + const last4 = this.extractSenderTelLast4(telById.get(interfaceId)); + if (last4) { + map.set(code, `${code}|${last4}`); + } + } + return map; + } + + /** + * 解析揽收查询的目标应用:取仓库下勾选了 waybill.getreceive 的首个应用(按 id 升序)。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 目标应用 AppKey,无承接应用时返回空字符串。 + */ + async resolveReceiveQueryAppKey(warehouseId) { + const warehouseNotify = this.service.systems && this.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.listCallbackConfigs !== 'function') { + return ''; + } + + const candidates = await warehouseNotify.listCallbackConfigs( + Number(warehouseId) || 0, + WAYBILL_RECEIVE_EVENT + ); + const first = Array.isArray(candidates) ? candidates[0] : null; + return String(first && first.appKey || '').trim(); + } + + /** + * 从回调响应中提取运单行,兼容裸露数组与 { code, data: [...] } 包装。 + * @param {*} response 回调响应体。 + * @return {Array} 运单行列表。 + */ + extractReceiveRows(response) { + if (Array.isArray(response)) return response; + if (!response || typeof response !== 'object') return []; + if (Array.isArray(response.data)) return response.data; + if (Array.isArray(response.waybills)) return response.waybills; + if (response.data && Array.isArray(response.data.waybills)) return response.data.waybills; + return []; + } + + /** + * 提取外部接口的业务失败信息(HTTP 200 但 code 非成功)。 + * 成功码口径:0 / 1 / 200;无法识别 code 的结构(含裸数组)返回空串。 + * @param {*} response 回调响应体。 + * @return {string} 失败原因,非失败时返回空串。 + */ + extractReceiveError(response) { + if (!response || typeof response !== 'object' || Array.isArray(response)) return ''; + + const rawCode = response.code; + if (rawCode === undefined || rawCode === null || rawCode === '') return ''; + + const code = Number(rawCode); + if (!Number.isFinite(code) || [ 0, 1, 200 ].includes(code)) return ''; + + return String(response.msg || response.message || `外部接口返回 code=${code}`); + } + + /** + * 归一揽收状态:支持 1/0、'Y'/'N'、布尔值与常见同义词,无法识别时返回 null。 + * @param {*} value 外部返回值。 + * @return {'Y'|'N'|null} 归一后的状态。 + */ + normalizeReceiveFlag(value) { + if (value === true) return 'Y'; + if (value === false) return 'N'; + + const text = String(value === undefined || value === null ? '' : value).trim().toUpperCase(); + if ([ '1', 'Y', 'YES', 'TRUE' ].includes(text)) return 'Y'; + if ([ '0', 'N', 'NO', 'FALSE' ].includes(text)) return 'N'; + return null; + } + + /** + * 实时查询单个运单的物流轨迹(出站回调 waybill.getTrace)。 + * + * 纯回源:不落库、不读本地表;请求与 `waybill.getreceive` 一致 + * (`{ request: { waybill_codes: [waybillCode] } }`,运单号同样会补寄件电话后四位 + * `运单号|后四位`),响应兼容 + * `[{ waybillNo, trace }]` / `{ waybillNo, trace }` / `{ code, data: [...] }`。 + * + * @param {Object} options 查询参数。 + * @param {number} options.warehouseId 仓库 ID(仅用于日志与揽收联动)。 + * @param {string} options.waybillCode 运单号。 + * @param {string} [options.appKey] 指定目标应用 AppKey,不传则按仓库订阅关系解析。 + * @return {Promise<{success: boolean, traces: Array, app_key: string, empty: boolean, reason?: string, error?: string}>} 轨迹列表。 + */ + async fetchTracesByWaybill({ warehouseId, waybillCode, appKey = '' } = {}) { + const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId) || 0; + const normalizedCode = String(waybillCode || '').trim(); + + if (!normalizedCode) { + return { success: false, traces: [], app_key: '', empty: false, reason: '运单号不能为空' }; + } + if (!normalizedWarehouseId) { + return { success: false, traces: [], app_key: '', empty: false, reason: '缺少仓库ID' }; + } + + const targetAppKey = String(appKey || '').trim() + || await this.resolveTraceQueryAppKey(normalizedWarehouseId); + if (!targetAppKey) { + return { + success: false, + traces: [], + app_key: '', + empty: false, + reason: '无应用承接该回调 method(callback_functions 未勾选或应用未启用)', + }; + } + + const callbackService = ctx.service.openapi && ctx.service.openapi.callback; + if (!callbackService || typeof callbackService.sendByAppKey !== 'function') { + return { success: false, traces: [], app_key: targetAppKey, empty: false, reason: 'OpenAPI 回调服务不可用' }; + } + + const queryCodeMap = await this.buildWaybillQueryCodeMap({ + warehouseId: normalizedWarehouseId, + waybillCodes: [ normalizedCode ], + }); + + const result = await callbackService.sendByAppKey({ + appKey: targetAppKey, + event: WAYBILL_TRACE_EVENT, + request: { waybill_codes: [ queryCodeMap.get(normalizedCode) || normalizedCode ] }, + signMode: WAYBILL_TRACE_SIGN_MODE, + }); + + if (!result || result.success !== true) { + const error = String(result && result.error || '未知错误'); + ctx.logger.warn('[WaybillService.fetchTracesByWaybill] 轨迹查询回调失败', { + warehouseId: normalizedWarehouseId, + appKey: targetAppKey, + waybillCode: normalizedCode, + error, + }); + return { success: false, traces: [], app_key: targetAppKey, empty: false, error }; + } + + const businessError = this.extractReceiveError(result.response); + if (businessError) { + ctx.logger.warn('[WaybillService.fetchTracesByWaybill] 外部接口返回业务失败', { + warehouseId: normalizedWarehouseId, + appKey: targetAppKey, + waybillCode: normalizedCode, + error: businessError, + }); + return { success: false, traces: [], app_key: targetAppKey, empty: false, error: businessError }; + } + + const rows = this.extractTraceRows(result.response); + const matched = rows.find(row => { + const code = this.stripWaybillCodeSuffix( + String(row && (row.waybillNo || row.waybill_no || row.waybillCode) || '').trim() + ); + return code === normalizedCode; + }) || rows[0] || null; + + const traces = this.normalizeTraceList(matched) + .map(trace => this.normalizeTraceItem(trace)) + .sort((a, b) => { + const timeA = a.op_time_raw ? a.op_time_raw.getTime() : 0; + const timeB = b.op_time_raw ? b.op_time_raw.getTime() : 0; + return timeB - timeA; + }) + .map(item => { + const output = { ...item }; + delete output.op_time_raw; + return output; + }); + + return { + success: true, + traces, + app_key: targetAppKey, + empty: traces.length === 0, + }; + } + + /** + * 归一单条轨迹字段(外部字段名 → 接口输出字段名)。 + * @param {Object} trace 外部轨迹对象。 + * @return {Object} 归一后的轨迹(含内部排序用 op_time_raw)。 + */ + normalizeTraceItem(trace = {}) { + const opTime = this.parseTraceTime(trace.opTime || trace.op_time); + return { + op_time: opTime ? this.formatTimestamp(opTime) : '', + op_time_raw: opTime, + out_biz_code: String(trace.outBizCode || trace.out_biz_code || '').trim(), + memo: String(trace.memo || '').trim(), + op_org_city_name: String(trace.opOrgCityName || trace.op_org_city_name || '').trim(), + weight: this.parseTraceWeight(trace.weight), + scan_type: String(trace.scanType || trace.scan_type || '').trim(), + raw_data: trace, + }; + } + + /** + * 把时间格式化为 'YYYY-MM-DD HH:mm:ss'(本地时间)。 + * @param {Date} date 时间对象。 + * @return {string} 格式化后的时间字符串。 + */ + formatTimestamp(date) { + const pad = num => String(num).padStart(2, '0'); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; + } + + /** + * 解析轨迹查询的目标应用:取仓库下勾选了 waybill.getTrace 的首个应用(按 id 升序)。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 目标应用 AppKey,无承接应用时返回空字符串。 + */ + async resolveTraceQueryAppKey(warehouseId) { + const warehouseNotify = this.service.systems && this.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.listCallbackConfigs !== 'function') { + return ''; + } + + const candidates = await warehouseNotify.listCallbackConfigs( + Number(warehouseId) || 0, + WAYBILL_TRACE_EVENT + ); + const first = Array.isArray(candidates) ? candidates[0] : null; + return String(first && first.appKey || '').trim(); + } + + /** + * 从回调响应中提取轨迹行,兼容裸数组、单个对象与 { code, data: [...] } 包装。 + * @param {*} response 回调响应体。 + * @return {Array} 轨迹行列表(每行含 waybillNo + trace)。 + */ + extractTraceRows(response) { + if (Array.isArray(response)) return response; + if (!response || typeof response !== 'object') return []; + if (Array.isArray(response.data)) return response.data; + if (Array.isArray(response.traces)) return response.traces; + if (response.data && Array.isArray(response.data.traces)) return response.data.traces; + if (response.data && Array.isArray(response.data.results)) return response.data.results; + if (response.data && typeof response.data === 'object') return [ response.data ]; + if (response.waybillNo || response.waybill_no || response.trace || response.traces) return [ response ]; + return []; + } + + /** + * 归一单个运单的轨迹列表:trace 支持对象或数组,另兼容 traces / traceList。 + * @param {Object} row 外部返回的单行。 + * @return {Array} 轨迹对象数组。 + */ + normalizeTraceList(row) { + if (!row || typeof row !== 'object') return []; + const candidates = [ row.trace, row.traces, row.traceList, row.trace_list ]; + const list = []; + for (const item of candidates) { + if (Array.isArray(item)) { + list.push(...item.filter(one => one && typeof one === 'object')); + } else if (item && typeof item === 'object') { + list.push(item); + } + } + return list; + } + + /** + * 解析轨迹重量:外部可能返回数字或字符串(如 "0.99"),统一转保留 3 位小数的数字。 + * @param {*} value 外部返回值。 + * @return {number} 重量,非法值返回 0。 + */ + parseTraceWeight(value) { + if (value === undefined || value === null || value === '') return 0; + const num = Number(String(value).trim().replace(/,/g, '')); + if (!Number.isFinite(num)) return 0; + return Math.round(num * 1000) / 1000; + } + + /** + * 解析轨迹操作时间:支持 'YYYY-MM-DD HH:mm:ss' 与 ISO 字符串,非法值返回 null。 + * @param {*} value 外部返回值。 + * @return {Date|null} 解析后的时间。 + */ + parseTraceTime(value) { + const text = String(value === undefined || value === null ? '' : value).trim(); + if (!text) return null; + const normalized = text.includes('T') ? text : text.replace(' ', 'T'); + const date = new Date(normalized); + return Number.isNaN(date.getTime()) ? null : date; + } + + /** + * 按轨迹把运单标记为已揽收(is_galaxy_receive='Y')。 + * 仅把非 Y(含 NULL)的行升级为 Y,已为 Y 的不重复更新;按仓库隔离。 + * + * @param {Object} options 参数。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {Array} options.waybillCodes 有轨迹的运单号。 + * @return {Promise} 实际更新行数。 + */ + async markReceiveByTraces({ warehouseId, waybillCodes = [] } = {}) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const codes = [ ...new Set((waybillCodes || []).map(code => String(code || '').trim()).filter(Boolean)) ]; + if (codes.length === 0) return 0; + + try { + const [ affected ] = await ctx.model.OrderExpress.update( + { is_galaxy_receive: 'Y' }, + { + where: { + waybill_code: { [Op.in]: codes }, + warehouse_id: Number(warehouseId) || 0, + [Op.or]: [ + { is_galaxy_receive: { [Op.ne]: 'Y' } }, + { is_galaxy_receive: { [Op.is]: null } }, + ], + }, + } + ); + const count = Number(affected) || 0; + if (count > 0) { + ctx.logger.info('[WaybillService.markReceiveByTraces] 轨迹命中,揽收状态已置 Y', { + warehouseId, + waybills: codes.length, + updated: count, + }); + } + return count; + } catch (error) { + // 揽收状态是轨迹查询的附带收益,失败只记日志,不影响轨迹返回 + ctx.logger.warn(`[WaybillService.markReceiveByTraces] 更新揽收状态失败: ${error.message}`); + return 0; + } + } +} + +module.exports = WaybillService; diff --git a/app/service/systems/wechat.js b/app/service/systems/wechat.js new file mode 100644 index 0000000..d3b1a5d --- /dev/null +++ b/app/service/systems/wechat.js @@ -0,0 +1,1880 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('node:crypto'); +const WechatOpenClient = require('../../lib/wechat_open_client'); + +const STATE_TTL_SECONDS = 600; + +// 系统默认用户须知的保留 appid(种子行,不面向真实小程序),供首次授权时作为第一版复制 +const SYSTEM_AGREEMENT_APPID = 'system'; + +/** + * 生成登录码:{uuid, form} JSON 的 base64 字符串。 + * uuid 格式为 `{id}_{6位随机数}`(id 为 wms_user_oauth.id),form 固定 wechat; + * 登录码一次性消费,校验时 base64 解码即可取回 uuid/form。 + * @param {number|string} id wms_user_oauth.id(主键)。 + * @return {string} base64 登录码。 + */ +function buildLoginCode(id) { + const payload = { + uuid: `${id}_${String(Math.floor(Math.random() * 1000000)).padStart(6, '0')}`, + form: 'wechat', + }; + return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'); +} + +/** + * 微信开放平台授权业务(systems 层)。 + * 供 systemMethods.wechat 与 wechatOpen controller 复用底层客户端。 + */ +class WechatSystemsService extends Service { + /** + * 生成微信开放平台小程序授权链接(PC 版)。 + * state 为随机串,仓库信息缓存到 Redis(key: wechat_auth_state:{state}), + * 授权回跳 /Authorization 时凭 state 取回仓库并落库绑定。 + * @param {object} data 入参。 + * @param {number} [data.warehouse_id] 仓库ID,缺省取当前登录用户所属仓库。 + * @return {Promise<{auth_url: string, state: string, expires_in: number}>} 授权链接。 + */ + async getAuthUrl(data = {}) { + const { ctx, app } = this; + const config = app.config.wechatOpen || {}; + + const warehouseId = (data && data.warehouse_id) || (ctx.user && ctx.user.store_id) || null; + if (!warehouseId) throw new Error('仓库ID不能为空'); + if (!config.redirect_uri) throw new Error('wechatOpen.redirect_uri 未配置'); + + const client = new WechatOpenClient(ctx); + + // 1. state = 随机串,缓存仓库信息(用于授权回跳时绑定仓库) + const state = `wx${Date.now()}${crypto.randomBytes(6).toString('hex')}`; + await client.saveAuthState(state, warehouseId, STATE_TTL_SECONDS); + + // 2. 获取预授权码 + const preAuthCode = await client.createPreAuthCode(); + + // 3. 组装 PC 端授权链接 + // - auth_type:授权账号类型(1=仅公众号,2=仅小程序,3=公众号+小程序;这里业务只有小程序,用 2)。 + // 注意 auth_type 不是"权限范围",权限范围由 category_id_list / 商家在授权页勾选控制。 + // - category_id_list:指定权限集 id 列表(竖线分隔)。业务所需:18=小程序代码管理(commit/submit_audit/ + // queryauth/get_qrcode 等)、86=体验版二维码;getTemplateList/jscode2session/快速注册不需要商家权限集。 + // 前提:18/86 必须在微信开放平台后台「权限集」中配置并全网发布,否则商家授权页看不到。 + // - 微信 componentloginpage 不支持 state 参数:state 必须拼进 redirect_uri 的 query, + // 授权完成后微信回跳时会保留 redirect_uri 已有参数并追加 auth_code/expires_in, + // 后端凭 state 从缓存取回仓库绑定信息。 + const stateSep = config.redirect_uri.includes('?') ? '&' : '?'; + const redirectUriWithState = `${config.redirect_uri}${stateSep}state=${encodeURIComponent(state)}`; + const authUrl = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage' + + `?component_appid=${encodeURIComponent(config.component_appid)}` + + `&pre_auth_code=${encodeURIComponent(preAuthCode)}` + + `&redirect_uri=${encodeURIComponent(redirectUriWithState)}` + + '&auth_type=2' + + '&category_id_list=18|86'; + + return { auth_url: authUrl, state, expires_in: STATE_TTL_SECONDS }; + } + + /** + * 解析微信应用记录:支持按主键 `app_id` 或按小程序原始 `appid` 定位。 + * + * 为什么需要两种入参: + * - `app_id`(wms_wechat_app.id):PC 端后台等已知业务库的场景; + * - `appid`(wx.getAccountInfoSync().miniProgram.appId):**开放平台第三方平台的模板小程序**场景。 + * 同一份模板代码授权给多个仓库后会生成不同 AppID 的小程序,构建期无法写死, + * 只能由小程序端在**运行时**取真实 AppID 上报,后端反查授权记录。 + * + * 优先级:`app_id` > `appid`(两者都传时以主键为准,保持向后兼容)。 + * + * @param {object} data 入参。 + * @param {number|string} [data.app_id] wms_wechat_app.id。 + * @param {string} [data.appid] 小程序原始 AppID。 + * @return {Promise<{record: object|null, message: string}>} 应用记录;失败时 record 为 null 并给出原因。 + */ + async resolveWechatApp(data = {}) { + const { ctx } = this; + + const appId = Number(data.app_id); + if (Number.isInteger(appId) && appId > 0) { + const record = await ctx.model.WechatApp.findByPk(appId); + if (!record) return { record: null, message: '微信应用不存在' }; + return { record, message: '' }; + } + + const appid = typeof data.appid === 'string' ? data.appid.trim() : ''; + if (appid) { + // appid 在 wms_wechat_app 上有唯一索引 uk_appid;过滤 is_enabled 与 getWechatApp 口径一致 + const record = await ctx.model.WechatApp.findOne({ + where: { appid, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) return { record: null, message: `小程序未授权或已停用:${appid}` }; + return { record, message: '' }; + } + + return { record: null, message: '缺少 app_id / appid 参数' }; + } + + /** + * 小程序登录码登录(免登录):wx.login 的 code 换取 openid/session_key,查/建 wms_user_oauth。 + * + * 参考 auth.login 返回结构;wms_user_oauth 无记录时创建记录(user_id=0 未绑定), + * JWT payload 记录 oauth_id(wms_user_oauth.id,区别于正常登录的用户 id 字段)。 + * + * @param {object} data 入参。 + * @param {string} data.code wx.login 获取的 code。 + * @param {number|string} [data.app_id] wms_wechat_app.id(主键),优先级最高。 + * @param {string} [data.appid] 小程序原始 AppID(如 wx3xxxxx),按 appid 反查应用记录。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 登录结果。 + */ + async loginByCode(data = {}) { + const { ctx, app } = this; + + const code = typeof data.code === 'string' ? data.code.trim() : ''; + if (!code) { + return { success: false, data: null, code: 0, message: '缺少 code 参数' }; + } + + const { record: wechatApp, message } = await this.resolveWechatApp(data); + if (!wechatApp) { + return { success: false, data: null, code: 0, message }; + } + if (Number(wechatApp.is_enabled) !== 1) { + return { success: false, data: null, code: 0, message: '微信应用已停用' }; + } + const appId = wechatApp.id; + + const client = new WechatOpenClient(ctx); + const session = await client.jscode2session(wechatApp.appid, code); + + const nowSec = Math.floor(Date.now() / 1000); + const where = { app_id: appId, provider: 'wechat', openid: session.openid }; + + // 协议版本:loginByCode 时自动更新到该小程序最新协议版本 id(无需前端传入) + const latestAgreement = await ctx.model.WechatAgreementVersion.findOne({ + where: { appid: wechatApp.appid }, + order: [[ 'id', 'DESC' ]], + attributes: [ 'id' ], + raw: true, + }); + const latestAgreementVersionId = latestAgreement ? Number(latestAgreement.id) : null; + + let oauth = await ctx.model.UserOauth.findOne({ where }); + if (oauth) { + await oauth.update({ + unionid: session.unionid || oauth.unionid || null, + session_key: session.session_key || oauth.session_key || null, + login_time: nowSec, + login_count: (Number(oauth.login_count) || 0) + 1, + agreement_version_id: latestAgreementVersionId, + }); + } else { + oauth = await ctx.model.UserOauth.create({ + user_id: 0, + app_id: appId, + provider: 'wechat', + platform: 'mp', + unionid: session.unionid || null, + openid: session.openid, + session_key: session.session_key || null, + login_time: nowSec, + login_count: 1, + agreement_version_id: latestAgreementVersionId, + }); + // 用主键 id 生成登录码并回写 + await oauth.update({ login_code: buildLoginCode(oauth.id) }); + } + + // JWT:记录 oauth_id(wms_user_oauth.id),区别于正常登录的用户 id 字段 + const tokenPayload = { + id: Number(oauth.user_id) || 0, + oauth_id: oauth.id, + platform_code: ctx.header.platform || 'miniprogram', + }; + const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, { + expiresIn: app.config.jwt.expiresIn, + }); + + return { + success: true, + data: { + token, + user: { + id: Number(oauth.user_id) || 0, + oauth_id: oauth.id, + openid: oauth.openid, + unionid: oauth.unionid || '', + nickname: oauth.nickname || '', + headimgurl: oauth.headimgurl || '', + login_time: oauth.login_time, + login_count: oauth.login_count, + }, + }, + code: 200, + message: '登录成功', + }; + } + + /** + * 获取当前微信登录用户的登录码(至少微信登录)。 + * 凭 ctx.oauth(微信登录态,JWT oauth_id 解析)定位 wms_user_oauth 记录: + * - 已有 login_code:直接返回; + * - 无 login_code:生成({uuid:`{id}_{6位随机}`,form:'wechat'} 的 base64)并写入后返回。 + * + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getMyLoginCode() { + const { ctx } = this; + const oauth = ctx.oauth; + if (!oauth || !oauth.id) { + return { success: false, data: null, code: 0, message: '请使用微信登录' }; + } + + if (oauth.login_code) { + return { success: true, data: { login_code: oauth.login_code, oauth_id: oauth.id }, code: 200, message: '获取成功' }; + } + + const loginCode = buildLoginCode(oauth.id); + await ctx.model.UserOauth.update( + { login_code: loginCode }, + { where: { id: oauth.id } } + ); + return { success: true, data: { login_code: loginCode, oauth_id: oauth.id }, code: 200, message: '获取成功' }; + } + + /** + * 绑定用户(微信登录态中间层接口):传入用户名密码,一致则绑定 wms_user_oauth.user_id + * 并签发绑定后的新 token(id=账号ID,oauth_id 保留)。 + * + * 已绑定(user_id>0)时仅允许本人幂等调用(凭据一致返回已绑定),不允许换绑。 + * + * @param {object} data 入参。 + * @param {string} data.username 用户名/手机号/邮箱。 + * @param {string} data.password 密码。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 绑定结果。 + */ + async bindUser(data = {}) { + const { ctx, app } = this; + + const oauthId = Number(ctx.oauthId || (ctx.oauth && ctx.oauth.id) || 0); + if (!Number.isInteger(oauthId) || oauthId <= 0) { + return { success: false, data: null, code: 401, message: '微信登录态不存在' }; + } + + const username = typeof data.username === 'string' ? data.username.trim() : ''; + const password = typeof data.password === 'string' ? data.password : ''; + if (!username || !password) { + return { success: false, data: null, code: 0, message: '用户名和密码不能为空' }; + } + + const record = await ctx.model.UserOauth.findByPk(oauthId); + if (!record) { + return { success: false, data: null, code: 0, message: '微信登录态不存在' }; + } + + const authService = ctx.service.systems.auth.user; + + // 已绑定:只允许本人幂等调用(凭据一致返回已绑定),不允许换绑 + if (Number(record.user_id) > 0) { + const bindAccount = await ctx.model.Account.findByPk(record.user_id); + const isOwner = (bindAccount && String(bindAccount.username || '').trim() === username) + ? await bindAccount.verifyPassword(password) + : false; + if (isOwner) { + return this.buildBindResult(record, bindAccount, ctx, app, '已绑定'); + } + return { success: false, data: null, code: 0, message: '该微信已绑定其他账号,无法更换绑定' }; + } + + // 校验账号密码(复用登录的查找与状态校验) + const account = await authService.findUserByIdentifier(username, 'auto'); + if (!account) { + return { success: false, data: null, code: 0, message: '用户名或密码错误' }; + } + try { + authService.checkUserStatus(account); + } catch (statusError) { + return { success: false, data: null, code: 0, message: statusError.message || '账号状态异常' }; + } + const isPasswordValid = await account.verifyPassword(password); + if (!isPasswordValid) { + return { success: false, data: null, code: 0, message: '用户名或密码错误' }; + } + + // 绑定并签发新 token(token 中 id 指向绑定账号) + await record.update({ + user_id: account.id, + login_time: Math.floor(Date.now() / 1000), + }); + + return this.buildBindResult(record, account, ctx, app, '绑定成功'); + } + + /** + * 组装绑定结果并签发绑定后的 JWT。 + * + * @param {Object} record wms_user_oauth 记录实例。 + * @param {Object} account wms_account 记录实例。 + * @param {Object} ctx Egg 上下文。 + * @param {Object} app Egg 应用。 + * @param {string} message 提示文案。 + * @return {Object} 统一绑定结果。 + */ + buildBindResult(record, account, ctx, app, message) { + const tokenPayload = { + id: account.id, + oauth_id: record.id, + platform_code: ctx.header.platform || 'miniprogram', + }; + const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, { + expiresIn: app.config.jwt.expiresIn, + }); + + return { + success: true, + data: { + token, + user: { + id: account.id, + username: account.username || '', + real_name: account.real_name || '', + phone: account.phone || '', + oauth_id: record.id, + openid: record.openid, + unionid: record.unionid || '', + nickname: record.nickname || '', + headimgurl: record.headimgurl || '', + }, + }, + code: 200, + message, + }; + } + + /** + * 按工号绑定微信(需登录需权限,PC 管理员操作):传入工号 id(wms_account_store_employee.id) + * 与微信绑定记录 id(wms_user_oauth.id),查工号关联的账号 id(account_id),校验后写入 + * wms_user_oauth.user_id 完成绑定;不签发 token(不改变当前登录态)。 + * + * 已绑定同一账号时幂等返回成功;已绑定其他账号、工号已解除/不属于当前仓库、 + * 微信记录非 wechat 或不属于当前仓库小程序、账号被禁用时拒绝。 + * + * @param {object} data 入参。 + * @param {number} data.id 工号 id(wms_account_store_employee.id)。 + * @param {number} data.oauth_id 微信绑定记录 id(wms_user_oauth.id,来自 wechat.userList 结果)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 绑定结果。 + */ + async bindByEmployee(data = {}) { + const { ctx } = this; + + const employeeId = Number(data.id); + const oauthId = Number(data.oauth_id); + if (!Number.isInteger(employeeId) || employeeId <= 0) { + return { success: false, data: null, code: 0, message: 'id(工号 id)为必填' }; + } + if (!Number.isInteger(oauthId) || oauthId <= 0) { + return { success: false, data: null, code: 0, message: 'oauth_id(微信绑定记录 id)为必填' }; + } + + // 工号存在且有效 + const employee = await ctx.model.AccountStoreEmployee.findByPk(employeeId, { raw: true }); + if (!employee) { + return { success: false, data: null, code: 0, message: '工号不存在' }; + } + if (Number(employee.status) !== 1) { + return { success: false, data: null, code: 0, message: '工号已解除,无法绑定' }; + } + const accountId = Number(employee.account_id); + if (!Number.isInteger(accountId) || accountId <= 0) { + return { success: false, data: null, code: 0, message: '工号未关联账号' }; + } + + // 只能操作当前仓库的工号 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (Number.isInteger(warehouseId) && warehouseId > 0 && Number(employee.store_id) !== warehouseId) { + return { success: false, data: null, code: 0, message: '工号不属于当前仓库' }; + } + + // 微信绑定记录 + const oauth = await ctx.model.UserOauth.findByPk(oauthId, { raw: true }); + if (!oauth) { + return { success: false, data: null, code: 0, message: '微信绑定记录不存在' }; + } + if (String(oauth.provider || '').trim() !== 'wechat') { + return { success: false, data: null, code: 0, message: '该记录不是微信登录记录' }; + } + if (Number(oauth.user_id) > 0 && Number(oauth.user_id) !== accountId) { + return { success: false, data: null, code: 0, message: '该微信已绑定其他账号,无法更换绑定' }; + } + + // 微信记录所属应用须为当前仓库启用的小程序(oauth.app_id 关联 wms_wechat_app.id) + if (Number(oauth.app_id) > 0 && Number.isInteger(warehouseId) && warehouseId > 0) { + const wechatApp = await ctx.model.WechatApp.findOne({ + where: { id: Number(oauth.app_id) }, + attributes: [ 'id', 'warehouse_id' ], + raw: true, + }); + if (!wechatApp) { + return { success: false, data: null, code: 0, message: '微信记录关联的应用不存在' }; + } + if (Number(wechatApp.warehouse_id) > 0 && Number(wechatApp.warehouse_id) !== warehouseId) { + return { success: false, data: null, code: 0, message: '微信记录不属于当前仓库的小程序' }; + } + } + + // 账号存在且未禁用 + const account = await ctx.model.Account.findByPk(accountId, { raw: true }); + if (!account) { + return { success: false, data: null, code: 0, message: '工号关联的账号不存在' }; + } + if (Number(account.status) !== 1) { + return { success: false, data: null, code: 0, message: '工号关联的账号已被禁用' }; + } + + // 写绑定(幂等:已绑定同一账号直接返回成功) + const alreadyBound = Number(oauth.user_id) === accountId; + if (!alreadyBound) { + await ctx.model.UserOauth.update( + { user_id: accountId }, + { where: { id: oauthId } } + ); + } + + return { + success: true, + data: { + oauth_id: oauthId, + openid: oauth.openid, + unionid: oauth.unionid || '', + nickname: oauth.nickname || '', + already_bound: alreadyBound, + employee: { + id: Number(employee.id), + account_id: accountId, + store_id: Number(employee.store_id), + real_name: employee.real_name || '', + }, + account: { + id: Number(account.id), + username: account.username || '', + real_name: account.real_name || '', + }, + }, + code: 200, + message: alreadyBound ? '该微信已绑定此工号账号' : '绑定成功', + }; + } + + /** + * 获取小程序用户须知富文本(免登录):传入 appId(小程序 AppID),按 appid 查询 + * wms_wechat_app.user_agreement 返回;Redis 缓存 24 小时(key wechat:userAgreement:{appid}), + * 有缓存直接使用缓存。 + * + * @param {object} data 入参。 + * @param {string} data.appId 小程序 AppID(wx...)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getUserAgreementText(data = {}) { + const { ctx } = this; + + const appid = typeof data.appId === 'string' ? data.appId.trim() : ''; + if (!appid) { + return { success: false, data: null, code: 0, message: 'appId(小程序 AppID)为必填' }; + } + + const client = new WechatOpenClient(ctx); + const CACHE_KEY = `wechat:userAgreement:${appid}`; + const CACHE_TTL_SECONDS = 24 * 3600; + + const cached = await client.cacheGet(CACHE_KEY); + if (cached !== null && cached !== undefined) { + try { + const parsed = JSON.parse(cached); + if (parsed && typeof parsed === 'object' && parsed.version_id !== undefined) { + return { success: true, data: { appid, ...parsed, from_cache: true }, code: 200, message: '获取成功' }; + } + } catch (e) { + // 缓存格式异常,忽略并重新查库 + } + } + + // 拉取只拉最新版本(副表 wms_wechat_agreement_version,id 自增即最新) + const record = await ctx.model.WechatAgreementVersion.findOne({ + where: { appid }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + if (!record) { + return { success: false, data: null, code: 0, message: '未找到对应小程序或该小程序暂无用户须知' }; + } + + const payload = { + version_id: Number(record.id), + text: record.content || '', + }; + await client.cacheSet(CACHE_KEY, JSON.stringify(payload), CACHE_TTL_SECONDS); + + return { success: true, data: { appid, ...payload, from_cache: false }, code: 200, message: '获取成功' }; + } + + /** + * 获取当前仓库小程序用户须知(需登录):按 ctx.user.store_id 取启用小程序, + * 无小程序时提示「无小程序,需要先绑定」。 + * + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getUserAgreement() { + const { ctx } = this; + + const record = await this.findWarehouseWechatApp(ctx); + if (!record) { + return { success: false, data: null, code: 0, message: '无小程序,需要先绑定' }; + } + + const latest = await this.findLatestAgreementVersion(ctx, record.appid); + if (!latest) { + return { success: false, data: null, code: 0, message: '该小程序暂无用户须知' }; + } + + return { + success: true, + data: { + appid: record.appid, + nickname: record.nickname || '', + version_id: Number(latest.id), + text: latest.content || '', + }, + code: 200, + message: '获取成功', + }; + } + + /** + * 设置当前仓库小程序用户须知(需登录):提交一次自动新增版本(直接插入,id 自增即最新), + * 并清除 getUserAgreementText 的 24h 缓存;无小程序时提示「无小程序,需要先绑定」。 + * + * @param {object} data 入参。 + * @param {string} data.text 用户须知富文本(可传空字符串)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async setUserAgreement(data = {}) { + const { ctx } = this; + + if (!Object.prototype.hasOwnProperty.call(data, 'text') || typeof data.text !== 'string') { + return { success: false, data: null, code: 0, message: 'text(用户须知富文本)为必填且须为字符串' }; + } + + const record = await this.findWarehouseWechatApp(ctx); + if (!record) { + return { success: false, data: null, code: 0, message: '无小程序,需要先绑定' }; + } + + const appid = record.appid; + + // 提交一次自动新增版本:直接插入新行,id 自增即最新(无需维护版本号) + const created = await ctx.model.WechatAgreementVersion.create({ + appid, + content: data.text, + }); + + // 清除 24h 缓存,避免 getUserAgreementText 拉到旧内容 + const client = new WechatOpenClient(ctx); + await client.cacheDel(`wechat:userAgreement:${appid}`); + + return { + success: true, + data: { + appid, + nickname: record.nickname || '', + version_id: Number(created.id), + text: data.text, + }, + code: 200, + message: '设置成功', + }; + } + + /** + * 按当前登录仓库取启用的小程序(供 getUserAgreement/setUserAgreement 复用)。 + * + * @param {object} ctx Egg 上下文。 + * @return {Promise} wms_wechat_app 行(raw);未识别仓库或无小程序返回 null。 + */ + async findWarehouseWechatApp(ctx) { + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return null; + } + return ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + } + + /** + * 取指定 appid 的最新协议版本(副表 wms_wechat_agreement_version,id 自增即最新, + * ORDER BY id DESC)。 + * + * @param {object} ctx Egg 上下文。 + * @param {string} appid 小程序 AppID。 + * @return {Promise} 版本行(raw);无版本返回 null。 + */ + async findLatestAgreementVersion(ctx, appid) { + return ctx.model.WechatAgreementVersion.findOne({ + where: { appid }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + } + + /** + * 首次授权的小程序自动写入系统默认用户须知作为第一版(幂等:已有任意版本则跳过)。 + * + * 系统默认内容来自 wms_wechat_agreement_version 中 appid='system' 的最新一条记录; + * 后续 PC 端 setUserAgreement 可继续追加新版本。 + * + * @param {string} appid 小程序 AppID。 + * @return {Promise} + */ + async ensureDefaultAgreementVersion(appid) { + const { ctx } = this; + if (!appid) return; + + const existing = await ctx.model.WechatAgreementVersion.findOne({ + where: { appid }, + attributes: [ 'id' ], + raw: true, + }); + if (existing) return; + + const systemDefault = await ctx.model.WechatAgreementVersion.findOne({ + where: { appid: SYSTEM_AGREEMENT_APPID }, + order: [[ 'id', 'DESC' ]], + attributes: [ 'content' ], + raw: true, + }); + if (!systemDefault || !systemDefault.content) { + ctx.logger.warn(`[wechat] 缺少系统默认用户须知(appid=${SYSTEM_AGREEMENT_APPID}),跳过写入 appid=${appid}`); + return; + } + + await ctx.model.WechatAgreementVersion.create({ appid, content: systemDefault.content }); + } + + /** + * 获取指定协议版本内容(需登录免权限):传入版本记录 id(wms_wechat_agreement_version.id, + * 可在 wechat.userList 的 agreement_version_id 获取),校验该版本对应 appid 属于当前仓库的 + * 启用小程序后返回协议内容。 + * + * @param {object} data 入参。 + * @param {number} data.id 协议版本记录 id。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getAgreementVersion(data = {}) { + const { ctx } = this; + + const versionId = Number(data.id); + if (!Number.isInteger(versionId) || versionId <= 0) { + return { success: false, data: null, code: 0, message: 'id(协议版本记录 id)为必填' }; + } + + const version = await ctx.model.WechatAgreementVersion.findByPk(versionId, { raw: true }); + if (!version) { + return { success: false, data: null, code: 0, message: '协议版本不存在' }; + } + + // 校验仓库:该版本的 appid 必须属于当前仓库的启用小程序 + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + const app = await ctx.model.WechatApp.findOne({ + where: { appid: version.appid, warehouse_id: warehouseId, is_enabled: 1 }, + attributes: [ 'id', 'appid', 'nickname' ], + raw: true, + }); + if (!app) { + return { success: false, data: null, code: 0, message: '该协议版本不属于当前仓库的小程序' }; + } + + return { + success: true, + data: { + id: Number(version.id), + appid: version.appid, + nickname: app.nickname || '', + text: version.content || '', + created_at: version.created_at || null, + }, + code: 200, + message: '获取成功', + }; + } + + /** + * 清理未使用且非最终版的用户须知历史版本(真实删除,释放 MySQL 磁盘空间)。 + * + * 保留规则:① 各 appid 的最终版(id 最大);② 被 wms_user_oauth.agreement_version_id + * 引用的版本(老用户可能仍停留在旧协议)。其余版本真实删除(模型 paranoid=false)。 + * 由定时任务 app/schedule/wechat_agreement_cleanup.js 每 1 小时调用一次。 + * + * @param {number} [batchSize] 单批删除条数(默认 500)。 + * @return {Promise<{deleted: number, kept_latest: number, kept_in_use: number, total: number}>} 清理统计。 + */ + async cleanupUnusedAgreementVersions(batchSize = 500) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + + const versions = await ctx.model.WechatAgreementVersion.findAll({ + attributes: [ 'id', 'appid' ], + raw: true, + }); + if (versions.length === 0) { + return { deleted: 0, kept_latest: 0, kept_in_use: 0, total: 0 }; + } + + // 各 appid 最终版(id 最大) + const latestIdByAppid = new Map(); + for (const v of versions) { + const cur = latestIdByAppid.get(v.appid); + if (!cur || Number(v.id) > cur.id) { + latestIdByAppid.set(v.appid, { id: Number(v.id) }); + } + } + + // 被 oauth 引用的版本(正在使用) + const oauthRows = await ctx.model.UserOauth.findAll({ + where: { agreement_version_id: { [Op.ne]: null } }, + attributes: [ 'agreement_version_id' ], + raw: true, + }); + const usedIds = new Set(); + for (const row of oauthRows) { + usedIds.add(Number(row.agreement_version_id)); + } + + // 未使用且非最终版 → 真实删除 + const deleteIds = []; + for (const v of versions) { + const id = Number(v.id); + const latest = latestIdByAppid.get(v.appid); + if (usedIds.has(id) || (latest && latest.id === id)) { + continue; + } + deleteIds.push(id); + } + + let deleted = 0; + const chunkSize = Number(batchSize) > 0 ? Math.floor(Number(batchSize)) : 500; + for (let i = 0; i < deleteIds.length; i += chunkSize) { + const chunk = deleteIds.slice(i, i + chunkSize); + const destroyed = await ctx.model.WechatAgreementVersion.destroy({ + where: { id: chunk }, + }); + deleted += Number(destroyed) || 0; + } + + return { + deleted, + kept_latest: latestIdByAppid.size, + kept_in_use: usedIds.size, + total: versions.length, + }; + } + + /** + * 确认登录码(需登录,PC/Web 端已登录用户),复用旧 user.getLoginWechatCode 生成的码。 + * + * 使用当前鉴权账号反查 ye4s_user(wms_account_id=当前账号),将 ye4s_user_id 写入旧登录码 + * 缓存(user:wechat:login:code:{code} 与 user:wechat:login:client:{client_code} 双写), + * 小程序端按旧链路 user.getLoginWechatCode 轮询到后直接返回登录成功。 + * + * @param {object} data 入参。 + * @param {string} data.code 旧登录码(6 位字母+数字)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async pushLoginCode(data = {}) { + const { ctx, app } = this; + + const accountId = Number(ctx.userId || (ctx.user && ctx.user.id)); + if (!Number.isInteger(accountId) || accountId <= 0) { + return { success: false, data: null, code: 401, message: '未登录' }; + } + + const authService = ctx.service.systems.auth.user; + const code = authService.parseWechatBindCode(data.code); + if (!code) { + return { success: false, data: null, code: 0, message: '登录码格式不正确' }; + } + + // 读旧登录码缓存(user:wechat:login:code:{code}),从中取 client_code + const cachedState = await app.getCacheAsync(authService.getWechatLoginCodeCacheKey(code)); + const clientCode = authService.parseWechatBindCode(cachedState && cachedState.client_code); + if (!cachedState || !clientCode) { + return { success: false, data: null, code: 0, message: '登录码不存在或已过期' }; + } + + // 反查当前账号的 ye4s 绑定(旧链路凭 ye4s_user_id 完成登录) + const ye4sBinding = await authService.findYe4sBindingByAccountId(accountId); + const ye4sUserId = Number(ye4sBinding && ye4sBinding.id); + if (!Number.isInteger(ye4sUserId) || ye4sUserId <= 0) { + return { success: false, data: null, code: 0, message: '当前账号未绑定微信登录账号,无法确认' }; + } + + // 双写:旧轮询方读 client key 时即可直接登录 + const nextState = { + ...cachedState, + ye4s_user_id: ye4sUserId, + confirmed_by: accountId, + confirmed_at: Math.floor(Date.now() / 1000), + }; + const ttl = authService.getRemainingSecondsByExpiresAt(cachedState.expires_at, 60); + await Promise.all([ + authService.setWechatLoginClientCache(clientCode, nextState, ttl), + authService.setWechatLoginCodeCache(code, nextState, ttl), + ]); + + // 发布登录事件,唤醒已打开的长轮询请求(否则要等 60s 超时后才会重读缓存) + await authService.publishWechatLoginEvent(clientCode, { ye4s_user_id: ye4sUserId }); + + return { success: true, data: { code, client_code: clientCode, status: 'success' }, code: 200, message: '登录已确认' }; + } + + /** + * 查询当前仓库小程序的认证状态(需登录,权限集 18)。 + * + * 判定顺序: + * 1) 本地 wms_wechat_app.verify_type_id >= 0(已认证)→ 直接返回本地认证信息,不调微信; + * 2) 未认证(null/-1)→ taskid(入参优先,其次库中 auth_task_id)调微信 wxa/sec/queryauth 查进度; + * 3) 未认证且无 taskid → 返回「尚未认证且无认证任务」状态(code 200,is_verified=false)。 + * 查询成功回写 auth_task_id/auth_task_status/auth_apply_status;apply_status=4(认证通过)时回写 verify_type_id=0。 + * + * @param {object} data 入参。 + * @param {string} [data.taskid] 认证任务 id(发起认证接口 wxa/sec/wxaapi/wxaauth 返回;缺省用库中 auth_task_id)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 认证状态结果。 + */ + async queryauth(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + const VERIFY_TYPE_TEXT = { + [-1]: '未认证', + 0: '微信认证', + 1: '新浪微博认证', + 3: '资质通过未名称认证', + 4: '资质通过+微博认证', + }; + + // 1) 已认证:直接返回本地认证信息(不再调微信查进度) + const verifyTypeId = record.verify_type_id === null || record.verify_type_id === undefined + ? null + : Number(record.verify_type_id); + if (verifyTypeId !== null && verifyTypeId >= 0) { + return { + success: true, + data: { + is_verified: true, + appid: record.appid, + verify_type_id: verifyTypeId, + verify_type_text: VERIFY_TYPE_TEXT[verifyTypeId] || '已认证', + principal_name: record.principal_name, + signature: record.signature, + service_type_id: record.service_type_id, + account_status: record.account_status, + }, + code: 200, + message: '小程序已认证', + }; + } + + // 2) 未认证:taskid 入参优先,其次库中 auth_task_id + let taskid = typeof data.taskid === 'string' ? data.taskid.trim() : ''; + if (!taskid && record.auth_task_id) { + taskid = String(record.auth_task_id).trim(); + } + if (!taskid) { + return { + success: true, + data: { is_verified: false, appid: record.appid, taskid: null, task_status: null, apply_status: null }, + code: 200, + message: '尚未认证,且无认证任务', + }; + } + + // 3) 查认证进度(微信 wxa/sec/queryauth) + const client = new WechatOpenClient(ctx); + const result = await client.queryMiniProgramAuth(record.appid, record.authorizer_refresh_token, taskid); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `查询认证状态失败: ${errmsg}` }; + } + + const TASK_STATUS_TEXT = { + 0: '初始状态', 1: '任务超时(24小时内有效)', 2: '用户授权拒绝', 3: '用户授权同意', + 4: '发起人脸流程', 5: '人脸认证失败', 6: '人脸认证ok', 7: '已提交手机号下发验证码', + 8: '手机验证失败', 9: '手机验证成功', 11: '创建认证审核单失败', 12: '创建认证审核单成功', + 14: '验证失败', 15: '等待支付', + }; + const APPLY_STATUS_TEXT = { + 0: '审核单不存在', 1: '待支付', 2: '审核中', 3: '打回重填', 4: '认证通过', 5: '认证最终失败', + }; + + const applyStatus = result.apply_status !== undefined ? Number(result.apply_status) : null; + + // 认证任务ID与状态落库(发起认证接口返回的 taskid 亦通过本接口回写); + // 认证通过(apply_status=4)时回写 verify_type_id=0(微信认证),后续 queryauth 直接返回认证信息 + await record.update({ + auth_task_id: taskid, + auth_task_status: result.task_status !== undefined ? Number(result.task_status) : null, + auth_apply_status: applyStatus, + ...(applyStatus === 4 ? { verify_type_id: 0 } : {}), + }); + + return { + success: true, + data: { + ...result, + appid: record.appid, + is_verified: applyStatus === 4, + task_status_text: TASK_STATUS_TEXT[Number(result.task_status)] || '未知', + apply_status_text: applyStatus !== null ? (APPLY_STATUS_TEXT[applyStatus] || '未知') : '', + }, + code: 200, + message: applyStatus === 4 ? '认证通过' : '查询成功', + }; + } + + /** + * 发起小程序认证(需登录,wxa/sec/wxaauth 新版接口,代商家调用需权限集 18)。 + * + * 后端分步:图片字段传 COS 文件 URL(http/https),后端下载文件 → wxa/sec/uploadauthmaterial + * 换 mediaid → 替换请求体 → 以 { auth_data } 包裹调 wxaauth 一步提交。 + * 成功后回写 wms_wechat_app.auth_task_id/auth_apply_status,返回 taskid/auth_url。 + * + * @param {object} data 入参(新版 wxaauth auth_data 字段白名单: + * customer_type/account_name/account_name_type/pay_type/third_party_phone 与 + * contact_info{name,email} 必填;invoice_info/qualification/qualification_other/ + * account_supplemental/auth_identification/auth_ident_material/service_appid/taskid 可选; + * 图片字段 qualification、qualification_other[]、account_supplemental[]、 + * auth_ident_material[] 支持传 COS URL,后端自动换 mediaid;其余字段透传)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async wxaauth(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + // 已认证不允许重复发起 + const verifyTypeId = record.verify_type_id === null || record.verify_type_id === undefined + ? null + : Number(record.verify_type_id); + if (verifyTypeId !== null && verifyTypeId >= 0) { + return { success: false, data: null, code: 0, message: '小程序已认证,无需重复发起' }; + } + + // 判断授权权限:需包含代码管理权限集 18 + if (!this.hasFuncScope(record.func_info, 18)) { + return { success: false, data: null, code: 0, message: '小程序未授权代码管理权限(权限集 18),请重新授权' }; + } + + // 新版 auth_data 字段白名单透传(2024 版小程序认证接口) + const ALLOWED_KEYS = [ + 'customer_type', 'taskid', 'contact_info', 'invoice_info', + 'qualification', 'qualification_other', 'account_name', 'account_name_type', + 'account_supplemental', 'pay_type', 'auth_identification', 'auth_ident_material', + 'third_party_phone', 'service_appid', + ]; + const authData = {}; + for (const key of ALLOWED_KEYS) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + authData[key] = data[key]; + } + } + + // 必填校验 + if (authData.customer_type === undefined || authData.customer_type === null || authData.customer_type === '') { + return { success: false, data: null, code: 0, message: 'customer_type 为必填(1 企业 / 12 个体工商户 / 15 个人)' }; + } + if (!authData.account_name) { + return { success: false, data: null, code: 0, message: 'account_name(小程序账号名称)为必填' }; + } + if (authData.account_name_type === undefined || authData.account_name_type === null || authData.account_name_type === '') { + return { success: false, data: null, code: 0, message: 'account_name_type 为必填(1 基于自选词汇 / 2 基于商标)' }; + } + if (authData.pay_type === undefined || authData.pay_type === null || authData.pay_type === '') { + return { success: false, data: null, code: 0, message: 'pay_type 为必填(1 消耗服务商预购包 / 2 小程序开发者自行支付)' }; + } + if (!authData.third_party_phone) { + return { success: false, data: null, code: 0, message: 'third_party_phone(第三方联系电话)为必填' }; + } + const contactInfo = authData.contact_info; + if (!contactInfo || typeof contactInfo !== 'object' || !contactInfo.name || !contactInfo.email) { + return { success: false, data: null, code: 0, message: 'contact_info.name / contact_info.email 为必填' }; + } + + const client = new WechatOpenClient(ctx); + + // 分步①:图片字段传 COS URL 时,后端下载并上传微信换 mediaid + try { + await this.resolveBodyMedia(authData, client, record); + } catch (e) { + return { success: false, data: null, code: 0, message: e.message || '上传认证材料失败' }; + } + + // 分步②:发起认证(请求体为 { auth_data } 包裹) + const result = await client.wxaauth(record.appid, record.authorizer_refresh_token, { auth_data: authData }); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `发起认证失败: ${errmsg}` }; + } + + // 回写认证任务 ID 与状态(taskid 供 queryauth 查询进度) + await record.update({ + auth_task_id: typeof result.taskid === 'string' ? result.taskid : String(result.taskid || ''), + auth_task_status: null, + auth_apply_status: result.apply_status !== undefined ? Number(result.apply_status) : null, + }); + + return { + success: true, + data: { appid: record.appid, ...result }, + code: 200, + message: '认证已发起,请前往微信完成认证', + }; + } + + /** + * 将请求体中的图片字段从 COS URL 替换为微信 mediaid(http/https 开头的值视为 COS URL, + * 其余值视为已是 mediaid 原样保留)。 + * + * 新版字段:qualification(单张字符串)、qualification_other/account_supplemental/ + * auth_ident_material(字符串数组)。 + * + * @param {object} body wxaauth auth_data 请求体(就地修改)。 + * @param {WechatOpenClient} client 微信客户端。 + * @param {object} record wms_wechat_app 记录。 + * @return {Promise} + */ + async resolveBodyMedia(body, client, record) { + // 单张字符串图片字段 + if (typeof body.qualification === 'string' && body.qualification) { + body.qualification = await this.resolveMediaValue(body.qualification, client, record); + } + + // 字符串数组图片字段 + for (const key of [ 'qualification_other', 'account_supplemental', 'auth_ident_material' ]) { + if (Array.isArray(body[key])) { + for (let i = 0; i < body[key].length; i++) { + if (typeof body[key][i] === 'string' && body[key][i]) { + body[key][i] = await this.resolveMediaValue(body[key][i], client, record); + } + } + } + } + } + + /** + * 单个图片字段解析:http/https 开头(COS URL)→ 下载 → uploadauthmaterial 换 mediaid; + * 其他值视为已传 mediaid 原样返回。 + * + * @param {string} value 字段值。 + * @param {WechatOpenClient} client 微信客户端。 + * @param {object} record wms_wechat_app 记录。 + * @return {Promise} mediaid。 + */ + async resolveMediaValue(value, client, record) { + const trimmed = String(value).trim(); + if (!/^https?:\/\//i.test(trimmed)) { + return value; + } + + const buffer = await this.downloadFromUrl(trimmed); + // 新版 uploadauthmaterial 限制:图片 ≤2M + if (buffer.length > 2 * 1024 * 1024) { + throw new Error(`上传认证材料失败(${trimmed}): 图片超过 2M 限制`); + } + const filename = this.resolveMediaFilename(trimmed); + const result = await client.uploadAuthMedia(record.appid, record.authorizer_refresh_token, buffer, filename); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + throw new Error(`上传认证材料失败(${filename}): ${errmsg}`); + } + if (!result.media_id) { + throw new Error(`上传认证材料失败(${filename}): 微信未返回 mediaid`); + } + return result.media_id; + } + + /** + * 下载 COS 文件 URL 内容为 Buffer。 + * + * @param {string} url 文件 URL。 + * @return {Promise} 文件内容。 + */ + async downloadFromUrl(url) { + const response = await this.ctx.curl(url, { + method: 'GET', + timeout: 30000, + }); + if (!response || !response.data || !Buffer.isBuffer(response.data) || response.data.length === 0) { + throw new Error(`下载文件失败: ${url}`); + } + return response.data; + } + + /** + * 从 URL 提取图片文件名(path 扩展名限定 jpg/jpeg/png,默认 image.jpg)。 + * + * @param {string} url 文件 URL。 + * @return {string} 文件名。 + */ + resolveMediaFilename(url) { + try { + const pathname = decodeURIComponent(url.split('?')[0].split('#')[0]); + const match = pathname.match(/\/([^/]+\.(jpe?g|png))$/i); + if (match) return match[1]; + } catch (e) { + // ignore + } + return 'image.jpg'; + } + + /** + * 快速注册企业小程序(需登录,fastregisterweapp?action=create)。 + * + * 注册任务创建后法人微信会收到模板消息做人脸核身;审核结果通过 + * notify_third_fasteregister 事件推送到授权事件接收 URL。 + * + * @param {object} data 入参。 + * @param {string} data.name 企业名(与工商登记一致;无主体名称个体工商户填「个体户+法人姓名」)。 + * @param {string} data.code 企业代码。 + * @param {number} data.code_type 企业代码类型:1 统一社会信用代码(18位)、2 组织机构代码(9位)、3 营业执照注册号(15位)。 + * @param {string} data.legal_persona_wechat 法人微信号。 + * @param {string} data.legal_persona_name 法人姓名。 + * @param {string} [data.component_phone] 第三方联系电话。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async registerMiniprogram(data = {}) { + const { ctx } = this; + + const name = typeof data.name === 'string' ? data.name.trim() : ''; + const code = typeof data.code === 'string' ? data.code.trim() : ''; + const codeType = Number(data.code_type); + const legalPersonaWechat = typeof data.legal_persona_wechat === 'string' ? data.legal_persona_wechat.trim() : ''; + const legalPersonaName = typeof data.legal_persona_name === 'string' ? data.legal_persona_name.trim() : ''; + const componentPhone = typeof data.component_phone === 'string' ? data.component_phone.trim() : ''; + + if (!name || !code || !legalPersonaWechat || !legalPersonaName) { + return { success: false, data: null, code: 0, message: '缺少参数: name/code/legal_persona_wechat/legal_persona_name 均为必填' }; + } + if (![ 1, 2, 3 ].includes(codeType)) { + return { success: false, data: null, code: 0, message: 'code_type 必须为 1(统一社会信用代码)/2(组织机构代码)/3(营业执照注册号)' }; + } + + const client = new WechatOpenClient(ctx); + const result = await client.fastRegisterWeapp('create', { + name, + code, + code_type: codeType, + legal_persona_wechat: legalPersonaWechat, + legal_persona_name: legalPersonaName, + component_phone: componentPhone, + }); + + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `注册小程序失败: ${errmsg}` }; + } + + return { + success: true, + data: { ...result }, + code: 200, + message: '注册任务已创建,法人确认与审核结果将通过 notify_third_fasteregister 事件推送', + }; + } + + /** + * 更新微信账号资料(微信登录态中间层,仅未绑定真实用户的微信账号)。 + * + * 前端(小程序)在未绑定账号时更新自己的昵称/头像(nickname/headimgurl), + * 已绑定真实用户的账号不支持修改。 + * + * @param {object} data 入参。 + * @param {string} [data.nickname] 昵称(≤255 字符)。 + * @param {string} [data.headimgurl] 头像 URL(≤500 字符)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async updateInfo(data = {}) { + const { ctx } = this; + + const oauthId = Number(ctx.oauthId || (ctx.oauth && ctx.oauth.id) || 0); + if (!Number.isInteger(oauthId) || oauthId <= 0) { + return { success: false, data: null, code: 401, message: '微信登录态不存在' }; + } + + const record = await ctx.model.UserOauth.findByPk(oauthId); + if (!record) { + return { success: false, data: null, code: 0, message: '微信登录态不存在' }; + } + if (Number(record.user_id) > 0) { + return { success: false, data: null, code: 0, message: '账号已绑定,不支持修改微信资料' }; + } + + const hasNickname = typeof data.nickname === 'string'; + const hasHeadimgurl = typeof data.headimgurl === 'string'; + if (!hasNickname && !hasHeadimgurl) { + return { success: false, data: null, code: 0, message: '缺少需要更新的字段: nickname/headimgurl' }; + } + + const patch = {}; + if (hasNickname) { + const nickname = data.nickname.trim(); + if (nickname.length > 255) { + return { success: false, data: null, code: 0, message: 'nickname 长度不能超过 255 字符' }; + } + patch.nickname = nickname; + } + if (hasHeadimgurl) { + const headimgurl = data.headimgurl.trim(); + if (headimgurl.length > 500) { + return { success: false, data: null, code: 0, message: 'headimgurl 长度不能超过 500 字符' }; + } + patch.headimgurl = headimgurl; + } + + await record.update(patch); + + return { + success: true, + data: { + oauth_id: record.id, + nickname: record.nickname || '', + headimgurl: record.headimgurl || '', + }, + code: 200, + message: '更新成功', + }; + } + + /** + * 生成头像上传 COS key(不依赖仓库上下文,未绑定微信账号也可用)。 + * + * @return {string} COS key。 + */ + buildHeadimgKey() { + const now = new Date(); + const pad = value => String(value).padStart(2, '0'); + const timestamp = [ + now.getFullYear(), + pad(now.getMonth() + 1), + pad(now.getDate()), + pad(now.getHours()), + pad(now.getMinutes()), + pad(now.getSeconds()), + ].join(''); + const random = Math.random().toString(36).substring(2, 10); + return `headimg/wechat/${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}/${timestamp}${random}.png`; + } + + /** + * 上传微信账号头像(微信登录态中间层,至少微信登录即可,未绑定也可)。 + * + * 前端裁剪后以 base64 上传(data URL 或裸 base64),限制:仅 PNG、大小小于 500K; + * 上传成功后回写 wms_user_oauth.headimgurl 并返回 URL。 + * + * @param {object} data 入参。 + * @param {string} data.image 裁剪后的 PNG 图片 base64(支持 data:image/png;base64, 前缀)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async uploadHeadimg(data = {}) { + const { ctx } = this; + + const oauthId = Number(ctx.oauthId || (ctx.oauth && ctx.oauth.id) || 0); + if (!Number.isInteger(oauthId) || oauthId <= 0) { + return { success: false, data: null, code: 401, message: '微信登录态不存在' }; + } + + const raw = typeof data.image === 'string' ? data.image.trim() : ''; + if (!raw) { + return { success: false, data: null, code: 0, message: '缺少 image 参数' }; + } + + let base64 = raw; + if (raw.startsWith('data:')) { + const commaIndex = raw.indexOf(','); + if (commaIndex === -1) { + return { success: false, data: null, code: 0, message: '图片数据格式不正确' }; + } + base64 = raw.slice(commaIndex + 1); + } + + let buffer = null; + try { + buffer = Buffer.from(base64, 'base64'); + } catch (e) { + buffer = null; + } + if (!buffer || buffer.length === 0) { + return { success: false, data: null, code: 0, message: '图片数据解析失败' }; + } + + // 大小限制:小于 500K + if (buffer.length >= 500 * 1024) { + return { success: false, data: null, code: 0, message: '图片大小不能超过 500K' }; + } + + // 仅 PNG:校验文件头魔数 + const PNG_MAGIC = Buffer.from([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a ]); + if (buffer.length < PNG_MAGIC.length || !buffer.subarray(0, PNG_MAGIC.length).equals(PNG_MAGIC)) { + return { success: false, data: null, code: 0, message: '仅支持 PNG 图片,请裁剪后重新上传' }; + } + + const uploadService = ctx.service.systems.upload; + if (!uploadService || typeof uploadService.uploadBuffer !== 'function') { + return { success: false, data: null, code: 0, message: '上传服务不可用' }; + } + + const uploadResult = await uploadService.uploadBuffer(buffer, { + filename: 'headimg.png', + mimeType: 'image/png', + category: 'image', + key: this.buildHeadimgKey(), + maxSizeBytes: 500 * 1024, + }); + + // 回写 wms_user_oauth.headimgurl(记录不存在也不阻断返回) + const record = await ctx.model.UserOauth.findByPk(oauthId); + if (record) { + await record.update({ headimgurl: uploadResult.url }); + } + + return { + success: true, + data: { + oauth_id: oauthId, + url: uploadResult.url, + headimgurl: uploadResult.url, + }, + code: 200, + message: '上传成功', + }; + } + + /** + * 获取小程序模板库列表(需登录),只拉取普通模板(template_type=0),不缓存(每次实时拉取)。 + * + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getTemplateList() { + const { ctx } = this; + + const client = new WechatOpenClient(ctx); + + const result = await client.getTemplateList(0); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `获取模板列表失败: ${errmsg}` }; + } + + const list = Array.isArray(result.template_list) ? result.template_list : []; + + return { success: true, data: { list }, code: 200, message: '获取成功' }; + } + + /** + * 判断授权权限集合中是否包含指定权限集 ID。 + * + * @param {string|Array} funcInfo wms_wechat_app.func_info(JSON 字符串或数组)。 + * @param {number} scopeId 权限集 ID。 + * @return {boolean} 包含返回 true。 + */ + hasFuncScope(funcInfo, scopeId) { + try { + const list = typeof funcInfo === 'string' ? JSON.parse(funcInfo || '[]') : (Array.isArray(funcInfo) ? funcInfo : []); + return list.some(item => Number(item && item.funcscope_category && item.funcscope_category.id) === scopeId); + } catch (e) { + return false; + } + } + + /** + * 将 api_get_authorizer_info 返回转为 wms_wechat_app 落库补丁。 + * + * @param {object} authorizerInfo authorizer_info。 + * @param {object} authorizationInfo authorization_info(可选)。 + * @return {object} 落库字段补丁。 + */ + buildAuthorizerPatch(authorizerInfo, authorizationInfo = {}) { + const info = authorizerInfo || {}; + const patch = {}; + if (info.nick_name) patch.nickname = info.nick_name; + if (info.user_name) patch.user_name = info.user_name; + if (info.head_img) patch.head_img = info.head_img; + if (info.principal_name !== undefined) patch.principal_name = info.principal_name; + if (info.signature !== undefined) patch.signature = info.signature; + if (info.alias !== undefined) patch.alias = info.alias; + if (info.qrcode_url !== undefined) patch.qrcode_url = info.qrcode_url; + if (info.service_type_info) patch.service_type_id = Number(info.service_type_info.id); + if (info.verify_type_info) patch.verify_type_id = Number(info.verify_type_info.id); + if (info.account_status !== undefined) patch.account_status = Number(info.account_status); + if (info.register_type !== undefined) patch.register_type = Number(info.register_type); + if (info.business_info) patch.business_info = JSON.stringify(info.business_info); + if (info.MiniProgramInfo) patch.mini_program_info = JSON.stringify(info.MiniProgramInfo); + if (authorizationInfo && Array.isArray(authorizationInfo.func_info)) { + patch.func_info = JSON.stringify(authorizationInfo.func_info); + } + if (authorizationInfo && authorizationInfo.authorizer_refresh_token) { + patch.authorizer_refresh_token = authorizationInfo.authorizer_refresh_token; + } + return patch; + } + + /** + * 获取并同步当前仓库小程序的基础信息(需登录,api_get_authorizer_info)。 + * + * 调微信拉取授权账号详情(authorizer_info + authorization_info),将基础信息/ + * 认证类型/权限集等落库 wms_wechat_app 后返回完整数据。 + * + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getAuthorizerInfo() { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + const client = new WechatOpenClient(ctx); + const detail = await client.getAuthorizerDetail(record.appid); + if (!detail || (!detail.authorizer_info && !detail.authorization_info)) { + return { success: false, data: detail || null, code: 0, message: '获取授权账号详情失败' }; + } + + const patch = this.buildAuthorizerPatch(detail.authorizer_info, detail.authorization_info || {}); + if (Object.keys(patch).length > 0) { + await record.update(patch); + } + + return { + success: true, + data: { + appid: record.appid, + authorizer_info: detail.authorizer_info || null, + authorization_info: detail.authorization_info || null, + }, + code: 200, + message: '获取成功', + }; + } + + /** + * 上传代码并生成体验版(需登录,wxa/commit,代商家调用需权限集 18)。 + * + * 流程:取当前仓库启用小程序 → 校验入参 → 校验授权权限集 18 → 从模板库取模板 + * (校验存在并取模板的 user_version/user_desc 作为版本号与代码描述,不需要外部传) + * → ext_json 由后端默认生成({ extEnable: true, extAppid: 小程序appid },前端不传) + * → 调微信 commit → 成功后回写 wms_wechat_app.template_id/user_version。 + * + * @param {object} data 入参。 + * @param {number|string} data.template_id 代码模板 ID(getTemplateList 获取,允许 0:普通模板库模板 ID 从 0 开始)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async commit(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + // template_id 允许 0:普通模板库的模板 ID 从 0 开始,0 表示第一个模板(微信官方 wxa/commit 示例即 "0") + const templateId = Number(data.template_id); + if (!Number.isInteger(templateId) || templateId < 0) { + return { success: false, data: null, code: 0, message: 'template_id 必须为非负整数' }; + } + + // 判断授权权限:需包含代码管理权限集 18 + if (!this.hasFuncScope(record.func_info, 18)) { + return { success: false, data: null, code: 0, message: '小程序未授权代码管理权限(权限集 18),请重新授权' }; + } + + const client = new WechatOpenClient(ctx); + + // 从模板库取模板:校验存在,并直接取模板的 user_version/user_desc 作为上传版本号与代码描述(不需要外部传) + const templateResult = await client.getTemplateList(0); + if (!templateResult || Number(templateResult.errcode) !== 0) { + const errmsg = templateResult && templateResult.errmsg ? templateResult.errmsg : (templateResult ? JSON.stringify(templateResult) : '无响应'); + return { success: false, data: templateResult || null, code: 0, message: `获取模板列表失败: ${errmsg}` }; + } + + const list = Array.isArray(templateResult.template_list) ? templateResult.template_list : []; + const template = list.find(item => Number(item.template_id) === templateId); + if (!template) { + return { success: false, data: null, code: 0, message: `模板不存在: template_id=${templateId}` }; + } + + const userVersion = typeof template.user_version === 'string' ? template.user_version.trim() : ''; + if (!userVersion || userVersion.length > 64) { + return { success: false, data: null, code: 0, message: '模板缺少合法版本号(user_version 必填且长度不能超过 64 字符),请先在模板库设置版本号' }; + } + + const userDesc = typeof template.user_desc === 'string' ? template.user_desc.trim() : ''; + if (!userDesc) { + return { success: false, data: null, code: 0, message: '模板缺少代码描述(user_desc),请先在模板库设置代码描述' }; + } + + // ext_json 由后端默认生成:只开启 extEnable 与 extAppid,前端不传 + const extJson = JSON.stringify({ extEnable: true, extAppid: record.appid }); + + const result = await client.commitTemplate(record.appid, record.authorizer_refresh_token, { + template_id: templateId, + ext_json: extJson, + user_version: userVersion, + user_desc: userDesc, + }); + + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `上传代码失败: ${errmsg}` }; + } + + // 上传成功,记录模板 id 与版本号 + await record.update({ template_id: templateId, user_version: userVersion }); + + return { + success: true, + data: { appid: record.appid, template_id: templateId, user_version: userVersion, user_desc: userDesc, ext_json: extJson, ...result }, + code: 200, + message: '上传成功,已生成体验版', + }; + } + + /** + * 提交代码审核(需登录,wxa/submit_audit,代商家调用需权限集 18)。 + * + * 仅当前无审核中的版本(audit_status != 1)时允许提交;成功后记录 + * audit_status=1(审核中)与 audit_id(微信审核单 ID)。 + * + * @param {object} data 入参(微信 submit_audit 请求体字段,均为可选: + * item_list/feedback_info/feedback_stuff/preview_info/version_desc/ + * privacy_api_not_use/order_info/ugc_declare)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async submitAudit(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + // 判断授权权限:需包含代码管理权限集 18 + if (!this.hasFuncScope(record.func_info, 18)) { + return { success: false, data: null, code: 0, message: '小程序未授权代码管理权限(权限集 18),请重新授权' }; + } + + // 仅未审核(audit_status != 1)时允许提交 + if (Number(record.audit_status) === 1) { + return { success: false, data: null, code: 0, message: '已有审核中的版本,请等待审核结果' }; + } + + // 白名单透传微信请求体字段 + const ALLOWED_KEYS = [ 'item_list', 'feedback_info', 'feedback_stuff', 'preview_info', 'version_desc', 'privacy_api_not_use', 'order_info', 'ugc_declare' ]; + const body = {}; + for (const key of ALLOWED_KEYS) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + body[key] = data[key]; + } + } + + const client = new WechatOpenClient(ctx); + const result = await client.submitAudit(record.appid, record.authorizer_refresh_token, body); + + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `提交代码审核失败: ${errmsg}` }; + } + + const auditId = Number(result.auditid); + await record.update({ + audit_status: 1, + audit_id: Number.isFinite(auditId) ? auditId : null, + audit_reason: '', + }); + + return { + success: true, + data: { appid: record.appid, auditid: result.auditid }, + code: 200, + message: '提交审核成功', + }; + } + + /** + * 生成体验版二维码 COS key。 + * + * @param {number} warehouseId 仓库 ID。 + * @return {string} COS key。 + */ + buildTrialQrCodeKey(warehouseId) { + const now = new Date(); + const pad = value => String(value).padStart(2, '0'); + const timestamp = [ + now.getFullYear(), + pad(now.getMonth() + 1), + pad(now.getDate()), + pad(now.getHours()), + pad(now.getMinutes()), + pad(now.getSeconds()), + ].join(''); + const random = Math.random().toString(36).substring(2, 10); + return `qrcode/wechat/${warehouseId}/${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}/${timestamp}${random}.jpg`; + } + + /** + * 获取体验版二维码(需登录,wxa/get_qrcode,代商家调用需权限集 18 或 86)。 + * + * 微信返回的二维码图片(jpeg)转存 COS,返回 URL。 + * + * @param {object} data 入参。 + * @param {string} [data.path] 扫码后进入的页面路径(可选,如 page/index?action=1)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getTrialQRCode(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + // 判断授权权限:需包含权限集 18(代码管理)或 86(体验版二维码) + if (!this.hasFuncScope(record.func_info, 18) && !this.hasFuncScope(record.func_info, 86)) { + return { success: false, data: null, code: 0, message: '小程序未授权相关权限(权限集 18/86),请重新授权' }; + } + + const path = typeof data.path === 'string' ? data.path.trim() : ''; + + const client = new WechatOpenClient(ctx); + const result = await client.getTrialQRCode(record.appid, record.authorizer_refresh_token, path); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `获取体验版二维码失败: ${errmsg}` }; + } + + const uploadService = ctx.service.systems.upload; + if (!uploadService || typeof uploadService.uploadBuffer !== 'function') { + return { success: false, data: null, code: 0, message: '上传服务不可用' }; + } + + const uploadResult = await uploadService.uploadBuffer(result.buffer, { + filename: 'QRCode.jpg', + mimeType: 'jpg', + category: 'image', + key: this.buildTrialQrCodeKey(warehouseId), + maxSizeBytes: 2 * 1024 * 1024, + }); + + return { + success: true, + data: { appid: record.appid, url: uploadResult.url }, + code: 200, + message: '获取成功', + }; + } + + /** + * 拉取当前仓库小程序(wms_wechat_app)的用户列表(wms_user_oauth)。 + * + * 口径:当前登录用户所属仓库(ctx.user.store_id)下启用的小程序; + * 可选 app_id 指定单个应用(须属于当前仓库且启用,否则报错)。 + * 支持 where(operator 结构,由 method 层 prepareWhereContext 解析)、 + * pagination(page/pageSize)、sort(sortField/sortOrder 白名单)。 + * 响应排除 session_key/access_token/refresh_token 等敏感字段,并附 is_bound(user_id>0); + * 并附 agreement_version_id(协议版本id,loginByCode 自动回写,可供 getAgreementVersion 拉取协议内容)。 + * + * @param {object} data 入参。 + * @param {number} [data.app_id] 指定 wms_wechat_app.id(可选)。 + * @param {object} [data.pagination] 分页 { page, pageSize }。 + * @param {object} [data.sort] 排序 { sortField, sortOrder }。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async userList(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + // 1. 定位当前仓库启用的小程序(可选 app_id 指定单个,须属于当前仓库) + const requestedAppId = Number(data.app_id); + const hasRequestedAppId = Number.isInteger(requestedAppId) && requestedAppId > 0; + const appWhere = { warehouse_id: warehouseId, is_enabled: 1 }; + if (hasRequestedAppId) { + appWhere.id = requestedAppId; + } + const apps = await ctx.model.WechatApp.findAll({ + where: appWhere, + attributes: [ 'id', 'appid', 'nickname' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (!Array.isArray(apps) || apps.length === 0) { + const message = hasRequestedAppId + ? '指定小程序不属于当前仓库或已停用' + : '当前仓库未授权小程序'; + return { success: false, data: null, code: 0, message }; + } + const appIds = apps + .map(item => Number(item.id)) + .filter(id => Number.isInteger(id) && id > 0); + + // 2. where:复用 method 层 prepareWhereContext 的解析结果;兼容直接调用时自行解析 + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const { parseWhereConditions } = require('../../lib/query_condition_parser'); + const rawWhere = data && data.where && typeof data.where === 'object' ? data.where : {}; + const parsed = parseWhereConditions({ where: rawWhere, app }); + if (!parsed.ok) { + return { success: false, data: null, code: 0, message: `where 参数解析失败: ${parsed.reason}` }; + } + parsedResult = parsed.result; + } + + const andConditions = [ + { provider: 'wechat' }, + { app_id: { [Op.in]: appIds } }, + ]; + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + // 3. 分页 + 排序 + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const page = Math.max(Number(pagination.page) || 1, 1); + const pageSize = Math.max(Number(pagination.pageSize) || 20, 1); + const sort = data.sort && typeof data.sort === 'object' ? data.sort : {}; + const validSortFields = [ + 'id', + 'user_id', + 'app_id', + 'openid', + 'unionid', + 'nickname', + 'sex', + 'login_time', + 'login_count', + 'agreement_version_id', + 'created_at', + 'updated_at', + ]; + const sortField = validSortFields.includes(String(sort.sortField || '').trim()) + ? String(sort.sortField).trim() + : 'updated_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + + // 4. 查询(排除敏感 token 字段) + const { count, rows } = await ctx.model.UserOauth.findAndCountAll({ + where: { [Op.and]: andConditions }, + attributes: { + exclude: [ 'session_key', 'refresh_token', 'access_token', 'expire_in', 'expire_time', 'login_code' ], + }, + order: [[ sortField, sortOrder ], [ 'id', 'DESC' ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + const list = rows.map(row => ({ + ...row, + id: Number(row.id), + user_id: Number(row.user_id), + app_id: Number(row.app_id), + agreement_version_id: row.agreement_version_id === null || row.agreement_version_id === undefined + ? null + : Number(row.agreement_version_id), + is_bound: Number(row.user_id) > 0, + })); + + return { + success: true, + data: { + list, + apps: apps.map(item => ({ + id: Number(item.id), + appid: item.appid, + nickname: item.nickname || '', + })), + pagination: { page, pageSize, total: count }, + }, + code: 200, + message: '获取成功', + }; + } +} + +// 挂载静态方法,供登录码校验/重置等场景复用 +WechatSystemsService.buildLoginCode = buildLoginCode; + +module.exports = WechatSystemsService; diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js new file mode 100644 index 0000000..3bb2a61 --- /dev/null +++ b/app/service/systems/workbench.js @@ -0,0 +1,4382 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('node:crypto'); + +const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); + +/** @type {string} 工作台波次订单实时计数缓存 key 前缀(最终 key:{前缀}:{warehouseId}:{waveId}) */ +const WAVE_ORDER_COUNT_CACHE_KEY_PREFIX = 'cache:workbench:wave_order_count'; +/** @type {number} 工作台波次订单实时计数缓存 TTL(秒),TTL 内分表 COUNT 只执行一次 */ +const WAVE_ORDER_COUNT_CACHE_TTL_SECONDS = 15; +/** @type {string} 工作台波次商品总件数缓存 key 前缀(最终 key:{前缀}:{warehouseId}:{waveId}) */ +const WAVE_ITEMS_TOTAL_CACHE_KEY_PREFIX = 'cache:workbench:wave_items_total'; +/** @type {number} 工作台波次商品总件数缓存 TTL(秒),TTL 内分表 SUM 只执行一次 */ +const WAVE_ITEMS_TOTAL_CACHE_TTL_SECONDS = 15; +/** @type {string} 工作台波次商品 SKU 聚合缓存 key 前缀(最终 key:{前缀}:{warehouseId}:{waveId}) */ +const WAVE_ITEMS_SUMMARY_CACHE_KEY_PREFIX = 'cache:workbench:wave_items_summary'; +/** @type {number} 工作台波次商品 SKU 聚合缓存 TTL(秒),TTL 内分表聚合只执行一次 */ +const WAVE_ITEMS_SUMMARY_CACHE_TTL_SECONDS = 15; + +/** @type {string} 工作台绑定会话缓存 key 前缀(client_code 维度,最终 key:{前缀}{clientCode}) */ +const WORKBENCH_BIND_CLIENT_CACHE_PREFIX = 'workbench:bind:client:'; +/** @type {string} 工作台绑定码缓存 key 前缀(code 维度,供 bind 反查会话,最终 key:{前缀}{code}) */ +const WORKBENCH_BIND_CODE_CACHE_PREFIX = 'workbench:bind:code:'; +/** @type {string} 工作台 token → 信息缓存 key 前缀(最终 key:workbench:token:{token}) */ +const WORKBENCH_TOKEN_CACHE_PREFIX = 'workbench:token:'; +/** @type {string} 工作台打包上下文缓存 key 前缀(最终 key:{前缀}{key},key 由 queryOrder 返回) */ +const WORKBENCH_PACK_CTX_CACHE_PREFIX = 'workbench:packctx:'; +/** @type {number} 工作台打包上下文缓存有效期(秒,queryOrder 扫码后 packOrder 消费窗口) */ +const WORKBENCH_PACK_CTX_CACHE_TTL_SECONDS = 1200; +/** @type {string} 工作台打包上下文 key 前缀 */ +const WORKBENCH_PACK_CTX_KEY_PREFIX = 'wpck'; +/** @type {number} 工作台绑定码缓存有效期(秒) */ +const WORKBENCH_BIND_CACHE_TTL_SECONDS = 120; +/** @type {number} 工作台 token 信息缓存有效期(秒) */ +const WORKBENCH_TOKEN_CACHE_TTL_SECONDS = 300; +/** @type {number} 工作台绑定长轮询超时(毫秒) */ +const WORKBENCH_BIND_LONG_POLL_TIMEOUT_MS = 60000; +/** @type {number} 工作台绑定长轮询检查间隔(毫秒) */ +const WORKBENCH_BIND_POLL_INTERVAL_MS = 1000; +/** @type {string} 工作台登录码前缀(登录码总长度 64 位) */ +const WORKBENCH_LOGIN_CODE_PREFIX = 'wblc'; +/** @type {number} 工作台登录码随机段长度(64 - 前缀长度 = 60 位十六进制) */ +const WORKBENCH_LOGIN_CODE_RANDOM_HEX_LENGTH = 64 - WORKBENCH_LOGIN_CODE_PREFIX.length; +/** @type {string} 工作台绑定码 / client_code 字符集 */ +const WORKBENCH_BIND_CODE_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; +/** @type {number} 工作台绑定码 / client_code 长度 */ +const WORKBENCH_BIND_CODE_LENGTH = 6; + +/** @type {string} 摄像头 OSD 叠加文字缓存 key 前缀(最终 key:osd_{workbenchId}) */ +const OSD_CACHE_KEY_PREFIX = 'osd_'; +/** @type {number} 摄像头 OSD 叠加文字缓存有效期(秒) */ +const OSD_CACHE_TTL_SECONDS = 3600; +/** @type {string} 打包任务结束(空闲态)时的摄像头 OSD 叠加文字 */ +const OSD_IDLE_TEXT = '无任务'; +/** @type {number} 打包开始(下发 OSD)时工作台摄像头跳转的预置点编号 */ +const PACK_PRESET_GOTO_ID = 1; + +class WorkbenchService extends Service { + /** + * 查询工作台列表(仓库隔离 + 软删除过滤) + * @param {Object} params - { pagination, where } + * @returns {Promise<{list: Array, pagination: Object}>} + */ + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = ctx.user.store_id; + const { pagination = {}, where = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = { + warehouse_id: warehouseId, + }; + + // 白名单字段筛选 + if (where.name) { + queryWhere.name = { [Op.like]: `%${where.name}%` }; + } + if (where.status !== undefined && where.status !== null && where.status !== '') { + queryWhere.status = parseInt(where.status); + } + + const { count, rows } = await ctx.model.Workbench.findAndCountAll({ + where: queryWhere, + attributes: { exclude: [ 'token' ] }, + order: [['created_at', 'DESC']], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + return { + list: rows, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 查询单个工作台详情 + * @param {number} id - 工作台 ID + * @returns {Promise} + */ + async detail(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.Workbench.findOne({ + where: { id, warehouse_id: warehouseId }, + attributes: { exclude: [ 'token' ] }, + }); + + if (!record) { + throw new Error('工作台不存在或无权访问'); + } + + return record; + } + + /** + * 创建工作台 + * @param {Object} data - { name, type, status, device_ids, remark } + * @returns {Promise} + */ + async create(data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + if (!data.name || !String(data.name).trim()) { + throw new Error('工作台名称不能为空'); + } + + const record = await ctx.model.Workbench.create({ + warehouse_id: warehouseId, + name: String(data.name).trim(), + type: data.type || 'personal', + status: data.status !== undefined ? parseInt(data.status) : 1, + device_ids: data.device_ids || null, + login_code: await this.generateUniqueWorkbenchLoginCode(), + remark: data.remark ? String(data.remark).trim() : null, + }); + + return record; + } + + /** + * 更新工作台 + * @param {number} id - 工作台 ID + * @param {Object} data - 要更新的字段 { name, type, status, device_ids, remark } + * @returns {Promise} + */ + async update(id, data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.Workbench.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!record) { + throw new Error('工作台不存在或无权操作'); + } + + const updateFields = {}; + if (data.name !== undefined) updateFields.name = String(data.name).trim(); + if (data.type !== undefined) updateFields.type = data.type; + if (data.status !== undefined) updateFields.status = parseInt(data.status); + if (data.device_ids !== undefined) updateFields.device_ids = data.device_ids; + if (data.remark !== undefined) updateFields.remark = data.remark ? String(data.remark).trim() : null; + + if (Object.keys(updateFields).length === 0) { + throw new Error('没有需要更新的字段'); + } + + await record.update(updateFields); + return record; + } + + /** + * 软删除工作台 + * @param {number} id - 工作台 ID + * @returns {Promise} + */ + async delete(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.Workbench.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!record) { + throw new Error('工作台不存在或无权操作'); + } + + await record.destroy(); // paranoid: true → 自动设置 deleted_at + } + + /** + * 绑定/解绑摄像头到工作台 + * @param {number} id - 工作台 ID + * @param {number[]} cameraIds - 摄像头 ID 数组,传空数组或 null 表示解绑 + * @returns {Promise} + */ + async bindCamera(id, cameraIds) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.Workbench.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + if (!record) throw new Error('工作台不存在或无权操作'); + + const ids = Array.isArray(cameraIds) ? cameraIds : []; + if (ids.length > 0) { + const cameras = await ctx.model.Camera.findAll({ + where: { id: ids, warehouse_id: warehouseId }, + attributes: ['id'], + }); + const validIds = cameras.map(c => c.id); + const invalidIds = ids.filter(cid => !validIds.includes(cid)); + if (invalidIds.length > 0) { + throw new Error(`摄像头 ${invalidIds.join(', ')} 不存在或无权操作`); + } + } + + await record.update({ device_ids: ids.length > 0 ? ids : null }); + return record; + } + + /** + * 工作台业务入口 + * @param {string} name - 业务名称(如 queryOrder) + * @param {*} data - 业务数据 + * @returns {Promise} + */ + async business(name, data) { + const { ctx } = this; + ctx.logger.info('[Systems.Workbench.business] 收到业务调度 name=%s data=%j', name, data); + + switch (name) { + case 'queryOrder': + case 'query': + return await this._queryOrder(data || {}); + case 'packOrder': { + // 新 key 模式:只凭 key 从后端缓存取订单信息(防篡改); + // 不传 key 时旧参数模式兼容(过渡期保留)。 + const bizData = data || {}; + const bizKey = String(bizData.key || '').trim(); + if (bizKey) { + const cachedCtx = await this._loadPackCtx(bizData); + return await this._packOrder({ + delivery_order_code: cachedCtx.delivery_order_code, + order_id: cachedCtx.order_id, + wave_no: cachedCtx.wave_no, + wave_scope: cachedCtx.wave_scope, + waybill_code: cachedCtx.waybill_code, + warehouse_id: Number(cachedCtx.warehouse_id || 0), + workbench_id: cachedCtx.workbench_id != null ? Number(cachedCtx.workbench_id) : null, + }); + } + // 旧参数模式:order_id 不接受设备上报(仅 key 模式由后端缓存注入,防篡改), + // 避免设备用外部键/主键交叉传参造成查单口径漂移 + const { order_id: _ignoredOrderId, ...legacyPackParams } = bizData; + return await this._packOrder(legacyPackParams); + } + case 'finishPack': + return await this._finishPack(data || {}); + case 'sendWeight': + return await this._sendWeight(data || {}); + case '': + default: + throw new Error(`不支持的业务类型: ${name}`); + } + } + + /** + * 凭打包上下文 key 从缓存拉取打包参数(queryOrder 扫码时写入,20 分钟有效)。 + * 只信任后端缓存内容,body 其它字段一律忽略(防篡改)。 + * @param {Object} data - { key } + * @return {Promise} 缓存内容(warehouse_id/workbench_id/order_id/delivery_order_code/wave_no/wave_scope/waybill_code/is_sandan) + * @throws {Error} key 缺失或上下文过期 + */ + async _loadPackCtx(data = {}) { + const { app } = this; + const ctxKey = String((data && data.key) || '').trim(); + if (!ctxKey) { + throw new Error('缺少打包上下文 key,请先扫码'); + } + let cachedCtx = null; + try { + cachedCtx = await app.getCacheAsync(this.getWorkbenchPackCtxCacheKey(ctxKey)); + } catch (cacheErr) { + app.coreLogger.warn(`读取打包上下文缓存失败: ${cacheErr.message}`); + } + if (!cachedCtx || !Number(cachedCtx.order_id)) { + throw new Error('打包上下文已过期,请重新扫码'); + } + return cachedCtx; + } + + /** + * 实时统计波次下的订单数量(并发遍历 current + dispatch 分表) + * + * current 与 dispatch 两张分表的 COUNT 相互独立,使用 Promise.all 并发执行, + * 将缓存未命中时的实时统计耗时从两张表串行累加压缩为单表耗时级别; + * 单张分表查询失败时按 0 处理,不影响另一张表的统计结果。 + * + * @param {number} warehouseId 仓库ID + * @param {number} waveId 波次ID + * @return {Promise} 波次下 current + dispatch 两张分表的订单总数 + */ + async _countWaveOrders(warehouseId, waveId) { + const { ctx } = this; + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + const counts = await Promise.all(tableOrders.map(async entry => { + try { + const model = await entry.getModel(); + if (!model) return 0; + return await model.count({ where: { wave_id: waveId, warehouse_id: warehouseId } }); + } catch (_err) { return 0; } + })); + return counts.reduce((total, count) => total + count, 0); + } + + /** + * 团购波次订单实时计数(带 Redis 短 TTL 缓存兜底) + * + * 分表 COUNT 无可用索引时扫描行数大、耗时长(生产实测 680~730ms/次)。 + * wave_batch.total_orders 为多处异步维护的快照值,存在漂移风险,不能直接替代实时计数, + * 因此对实时计数结果按 (warehouseId, waveId) 维度做短 TTL 缓存: + * TTL 内重复查询直接命中缓存,缓存不可用或读取失败时降级为实时统计。 + * + * @param {number} warehouseId 仓库ID + * @param {number} waveId 波次ID + * @return {Promise} 波次下 current + dispatch 两张分表的订单总数 + */ + async _countWaveOrdersCached(warehouseId, waveId) { + const { ctx, app } = this; + const cacheKey = `${WAVE_ORDER_COUNT_CACHE_KEY_PREFIX}:${warehouseId}:${waveId}`; + + if (app && typeof app.getCacheAsync === 'function') { + try { + const cached = await app.getCacheAsync(cacheKey); + if (cached !== null && cached !== undefined) { + const parsed = Number(cached); + if (Number.isFinite(parsed) && parsed >= 0) { + return parsed; + } + } + } catch (cacheReadErr) { + ctx.logger.warn('[Workbench._countWaveOrdersCached] 读取缓存失败,降级为实时计数: %s', cacheReadErr.message); + } + } + + const total = await this._countWaveOrders(warehouseId, waveId); + + if (app && typeof app.setCacheAsync === 'function') { + try { + await app.setCacheAsync(cacheKey, total, WAVE_ORDER_COUNT_CACHE_TTL_SECONDS); + } catch (cacheWriteErr) { + ctx.logger.warn('[Workbench._countWaveOrdersCached] 写入缓存失败,不影响本次返回: %s', cacheWriteErr.message); + } + } + + return total; + } + + /** + * 实时统计波次下的商品总件数(并发遍历 current + dispatch 分表,SUM(items_total)) + * + * items_total 为订单级商品总数(权威字段,非 SKU 品种数),对波次内 current 与 dispatch + * 两张分表分别执行 SUM 并使用 Promise.all 并发执行,将缓存未命中时的实时统计耗时 + * 从两张表串行累加压缩为单表耗时级别;单张分表查询失败时按 0 处理,不影响另一张表。 + * + * @param {number} warehouseId 仓库ID + * @param {number} waveId 波次ID + * @return {Promise} 波次下 current + dispatch 两张分表的商品总件数之和 + */ + async _sumWaveItemsTotal(warehouseId, waveId) { + const { ctx } = this; + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + const sums = await Promise.all(tableOrders.map(async entry => { + try { + const model = await entry.getModel(); + if (!model) return 0; + const sum = await model.sum('items_total', { where: { wave_id: waveId, warehouse_id: warehouseId } }); + return Number(sum) || 0; + } catch (_err) { return 0; } + })); + return sums.reduce((total, sum) => total + sum, 0); + } + + /** + * 团购波次商品总件数统计(带 Redis 短 TTL 缓存兜底) + * + * 分表 SUM 与订单计数 COUNT 同属无索引扫描,生产耗时长,因此与 _countWaveOrdersCached + * 保持一致:按 (warehouseId, waveId) 维度做 15s 短 TTL 缓存,TTL 内重复查询直接命中; + * 缓存不可用或读取失败时降级为实时统计。打包状态变更(packOrder/finishPack)会主动失效 + * 工作台 token 缓存(含 current_wave 快照),本短缓存在 TTL 到期后自动重建最新值。 + * + * @param {number} warehouseId 仓库ID + * @param {number} waveId 波次ID + * @return {Promise} 波次下 current + dispatch 两张分表的商品总件数之和 + */ + async _sumWaveItemsTotalCached(warehouseId, waveId) { + const { ctx, app } = this; + const cacheKey = `${WAVE_ITEMS_TOTAL_CACHE_KEY_PREFIX}:${warehouseId}:${waveId}`; + + if (app && typeof app.getCacheAsync === 'function') { + try { + const cached = await app.getCacheAsync(cacheKey); + if (cached !== null && cached !== undefined) { + const parsed = Number(cached); + if (Number.isFinite(parsed) && parsed >= 0) { + return parsed; + } + } + } catch (cacheReadErr) { + ctx.logger.warn('[Workbench._sumWaveItemsTotalCached] 读取缓存失败,降级为实时统计: %s', cacheReadErr.message); + } + } + + const total = await this._sumWaveItemsTotal(warehouseId, waveId); + + if (app && typeof app.setCacheAsync === 'function') { + try { + await app.setCacheAsync(cacheKey, total, WAVE_ITEMS_TOTAL_CACHE_TTL_SECONDS); + } catch (cacheWriteErr) { + ctx.logger.warn('[Workbench._sumWaveItemsTotalCached] 写入缓存失败,不影响本次返回: %s', cacheWriteErr.message); + } + } + + return total; + } + + /** + * 获取波次下订单ID(遍历 current + dispatch 分表)。 + * 默认排除拦截订单(intercept_status 空值按 none 处理), + * 团购打包日志只写给非拦截订单,拦截订单跳过。 + * @param {number} warehouseId + * @param {number} waveId + * @param {boolean} [excludeIntercepted=true] 是否排除拦截订单 + * @returns {Promise} + */ + async _getWaveOrderIds(warehouseId, waveId, excludeIntercepted = true) { + const { ctx } = this; + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + const orderIds = []; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const where = { wave_id: waveId, warehouse_id: warehouseId }; + if (excludeIntercepted) { + where.intercept_status = { [ctx.app.Sequelize.Op.in]: [ 'none', null ] }; + } + const rows = await model.findAll({ + where, + attributes: [ 'id' ], + raw: true, + }); + orderIds.push(...rows.map(r => r.id)); + } catch (_err) { continue; } + } + return [ ...new Set(orderIds) ]; + } + + /** + * 打包任务字段白名单:只有这些字段的变化才会记入操作日志 + */ + PACK_OPLOG_FIELD_WHITELIST = new Set([ + 'pack_mode', + 'pack_quantity', + 'item_quantity', + 'sku_count', + 'workbench_id', + 'wave_no', + ]); + + /** + * 打包任务字段中文翻译 + */ + PACK_OPLOG_FIELD_LABEL = { + pack_mode: '打包模式', + pack_quantity: '打包数量', + item_quantity: '商品总数量', + sku_count: '商品种类数', + workbench_id: '工作台', + wave_no: '波次号', + }; + + /** + * 打包任务字段值翻译 + */ + PACK_OPLOG_VALUE_LABEL = { + pack_mode: { 1: '散单', 2: '团购' }, + }; + + /** + * 构建打包操作日志的变更描述。 + * 工作台展示名称而非 ID(名称缺失时降级为 ID)。 + * @param {Object} packData 打包数据 + * @param {string} [workbenchName] 工作台名称 + * @returns {string} 变更描述 + */ + _buildPackChangeSummary(packData, workbenchName) { + const whitelist = this.PACK_OPLOG_FIELD_WHITELIST; + const fieldLabel = this.PACK_OPLOG_FIELD_LABEL; + const valueLabel = this.PACK_OPLOG_VALUE_LABEL; + + const parts = []; + for (const [ key, value ] of Object.entries(packData)) { + if (!whitelist.has(key) || value === undefined || value === null) continue; + const label = fieldLabel[key] || key; + let valStr; + if (key === 'workbench_id') { + valStr = workbenchName || String(value); + } else { + valStr = (valueLabel[key] && valueLabel[key][value] !== undefined) + ? valueLabel[key][value] + : String(value); + } + parts.push(`${label}: ${valStr}`); + } + return parts.join(','); + } + + /** + * 写入打包操作日志。 + * - 散单:写入单个订单操作日志 + * - 团购:批量写入波次下所有订单的操作日志 + * 写入失败不影响主流程。 + * + * @param {Object} options + * @param {number} options.warehouseId 仓库ID + * @param {number} options.orderId 当前订单ID + * @param {number} options.waveId 波次ID + * @param {string} options.waveNo 波次号 + * @param {number} options.isSandan 是否散单(1=散单 0=团购) + * @param {Object} options.packData 打包数据(用于变更描述) + * @param {Array} options.users 打包人员列表 + * @param {string} [options.workbenchName] 工作台名称(日志展示用,缺失时展示工作台ID) + */ + async _writePackOperationLog({ warehouseId, orderId, waveId, waveNo, isSandan, packData, users, workbenchName }) { + const { ctx } = this; + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + return; + } + + // 操作人信息:从 users 中取第一个作为主操作人 + const operator = { + id: users && users[0] ? String(users[0].wms_account_id || users[0].id || '') : null, + name: users && users[0] ? (users[0].real_name || '') : null, + }; + + const changeSummary = this._buildPackChangeSummary(packData, workbenchName); + const operationCode = isSandan === 1 ? 'ORDER_PACK' : 'ORDER_PACK_GROUP'; + const isFinish = Number(packData && packData.status) >= 2; + const actionText = isFinish ? '打包完成' : '开始打包'; + + if (isSandan === 1) { + // 散单:写入单个订单操作日志 + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId), + operationCode, + operator, + extras: { + warehouseId, + message: `散单${actionText}:${changeSummary}`, + }, + }]); + ctx.logger.info('[Workbench._writePackOperationLog] 散单操作日志已写入 orderId=%d', orderId); + } else { + // 团购:批量写入波次下所有非拦截订单的操作日志(拦截订单跳过,不写日志) + if (!waveId || waveId <= 0) { + // 无波次ID时按散单处理 + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId), + operationCode, + operator, + extras: { + warehouseId, + message: `${actionText}:${changeSummary}`, + }, + }]); + return; + } + + const waveOrderIds = await this._getWaveOrderIds(warehouseId, waveId); + if (waveOrderIds.length === 0) { + // 波次下无订单,只写当前订单 + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId), + operationCode, + operator, + extras: { + warehouseId, + message: `${actionText}(波次 ${waveNo || waveId}):${changeSummary}`, + }, + }]); + return; + } + + const messagePrefix = `${isFinish ? '团购打包完成' : '团购开始打包'}(波次 ${waveNo || waveId},共${waveOrderIds.length}单):`; + const payloads = waveOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(oid), + operationCode, + operator, + extras: { + warehouseId, + message: `${messagePrefix}${changeSummary}`, + }, + })); + + await operationLogService.createOperationLogs(payloads); + ctx.logger.info('[Workbench._writePackOperationLog] 团购操作日志已批量写入 waveNo=%s orderCount=%d', + waveNo || waveId, waveOrderIds.length); + } + } catch (e) { + ctx.logger.warn('[Workbench._writePackOperationLog] 写入操作日志失败,不影响主流程', { + error: e && e.message, + orderId, + waveId, + warehouseId, + }); + } + } + + /** + * 更新订单打包状态字段(散单按订单ID更新单笔,团购按波次批量更新), + * 并同步补确认打印状态:扫描打包代表面单已真实存在,确认打印状态未写入 + * (confirm_print_status 为 none/null)时补为 fin(团购按波次补、散单按单补), + * 补后递增统计版本号驱动 confirmPrintUnclaimedWaveCount 长轮询。 + * 遍历 current + dispatch 分表,异常仅记录日志不影响主流程。 + * 团购批量更新时跳过拦截订单(intercept_status 空值按 none 处理)。 + * + * @param {number} warehouseId 仓库ID + * @param {Object} options + * @param {number} options.orderId 订单ID(散单使用) + * @param {number} options.waveId 波次ID(>0 时按团购批量更新) + * @param {number|string} options.packStatus 任务状态数值(1=打包中 2=已完成) + * @param {string} [options.caller] 调用方标识(仅用于日志) + * @returns {Promise} 实际写入的 pack_status 值 + */ + async _updateOrderPackStatus(warehouseId, { orderId, waveId, packStatus, caller = 'Workbench' }) { + const { ctx } = this; + const statusNum = parseInt(packStatus); + // 任务状态 <2(0待处理/1打包中)或未传一律视为打包中;>=2 视为已完成 + const orderPackStatus = (Number.isNaN(statusNum) || statusNum < 2) ? 'padding' : 'fin'; + const orderUpdateData = { pack_status: orderPackStatus }; + // 扫描打包即代表面单已真实存在:确认打印状态未写入时补上(团购按波次补、散单按单补) + const confirmUpdateData = { confirm_print_status: 'fin' }; + const confirmBackfillWhere = { + confirm_print_status: { [ctx.app.Sequelize.Op.in]: [ 'none', null ] }, + }; + let confirmBackfilled = false; + + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + if (waveId > 0) { + // 团购:批量更新波次下所有未拦截订单 + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const affected = await model.update(orderUpdateData, { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + intercept_status: { [ctx.app.Sequelize.Op.in]: [ 'none', null ] }, + }, + }); + if (affected[0] > 0) { + ctx.logger.info('[%s._updateOrderPackStatus] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d', + caller, waveId, orderPackStatus, entry.label, affected[0]); + } + + // 波次补确认打印状态(仅未写入的订单) + const confirmAffected = await model.update(confirmUpdateData, { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + intercept_status: { [ctx.app.Sequelize.Op.in]: [ 'none', null ] }, + ...confirmBackfillWhere, + }, + }); + if (confirmAffected[0] > 0) { + confirmBackfilled = true; + ctx.logger.info('[%s._updateOrderPackStatus] 团购波次补确认打印状态 waveId=%d table=%s affected=%d', + caller, waveId, entry.label, confirmAffected[0]); + } + } catch (err) { + ctx.logger.warn('[%s._updateOrderPackStatus] 更新分表 %s 失败: %s', caller, entry.label, err.message); + } + } + } else { + // 散单:按订单ID更新单个订单 + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const affected = await model.update(orderUpdateData, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + if (affected[0] > 0) { + ctx.logger.info('[%s._updateOrderPackStatus] 更新订单打包状态 orderId=%d pack_status=%s table=%s', + caller, orderId, orderPackStatus, entry.label); + + // 按单补确认打印状态(仅未写入时) + try { + const confirmAffected = await model.update(confirmUpdateData, { + where: { + id: orderId, + warehouse_id: warehouseId, + ...confirmBackfillWhere, + }, + }); + if (confirmAffected[0] > 0) { + confirmBackfilled = true; + ctx.logger.info('[%s._updateOrderPackStatus] 散单补确认打印状态 orderId=%d table=%s', + caller, orderId, entry.label); + } + } catch (confirmErr) { + ctx.logger.warn('[%s._updateOrderPackStatus] 补确认打印状态失败 orderId=%d table=%s: %s', + caller, orderId, entry.label, confirmErr.message); + } + break; + } + } catch (err) { + ctx.logger.warn('[%s._updateOrderPackStatus] 更新分表 %s 失败: %s', caller, entry.label, err.message); + } + } + } + + // 补了确认打印后递增统计版本号,驱动 confirmPrintUnclaimedWaveCount 长轮询 + if (confirmBackfilled) { + try { + const waveService = ctx.service + && ctx.service.systemMethods + && ctx.service.systemMethods.order + && ctx.service.systemMethods.order.wave; + if (waveService && typeof waveService.bumpConfirmPrintUnclaimedWaveVersion === 'function') { + await waveService.bumpConfirmPrintUnclaimedWaveVersion(warehouseId); + } + } catch (err) { + ctx.logger.warn('[%s._updateOrderPackStatus] 统计版本号递增失败: %s', caller, err.message); + } + } + + // 通知仓库面板刷新(大屏增量更新,失败不影响主流程) + await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId)); + + return orderPackStatus; + } + + /** + * 打包任务写入:根据发货单号查询订单并创建/更新打包任务记录。 + * 兼容一单多号(主单号/子单号):传入 waybill_code 时按「订单 + 运单号」维度 + * 记录打包流水与去重,主/子单号流水互不覆盖;未传时保持订单维度(兼容旧设备端)。 + * 打包人:上报了 users(business 旧链路)以上报为准,未上报(token+key 新链路)自动回填工作台绑定成员。 + * 波次范围(wave_scope):优先取上报值(0-4 整数),非法/缺省时兜底取订单行 wave_scope, + * 服务端复查落库,防止前端失真;写入 wms_pack_task.wave_scope。 + * 响应附大团购倒计时字段:wave_scope=1 时下发 pack_wait_seconds(大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数,秒) + * 与 pack_start_time(开始打包时间,毫秒时间戳)供前端倒计时;其他波次两字段均为 0。 + * @param {Object} params - { delivery_order_code, order_id, wave_no, wave_scope, warehouse_id, workbench_id, status, pack_time, waybill_code, users } + * @param {number} [params.order_id] 订单主键(key 模式由扫码上下文注入,优先用它定位订单; + * 发货单号唯一性仅为「单号+货主+仓库」,跨货主可重复,不作为首选查单键) + * @param {string} [params.waybill_code] 扫描打包的运单号(可选,用于运单维度记录流水) + * @param {number} [params.wave_scope] 波次范围(0未分配 1大团购 2散单 3小团购 4单品单件,可选) + * @returns {Promise} 打包结果 { task_id, order_id, delivery_order_code, wave_no, isSandan, pack_mode, status, pack_wait_seconds, pack_start_time, batch? } + */ + async _packOrder(params) { + const { ctx } = this; + const { delivery_order_code: deliveryOrderCode, order_id: orderIdParam, wave_no: waveNo, + wave_scope: waveScopeParam, + warehouse_id: inputWarehouseId, workbench_id: workbenchIdRaw, + status: packStatus, pack_time: packTime, + wave_total_orders: waveTotalOrders, + items_count: itemsCount, + items_total: itemsTotal, + waybill_code: waybillCodeParam, + users: usersParam } = params; + + if (!deliveryOrderCode && !(Number.isInteger(Number(orderIdParam)) && Number(orderIdParam) > 0)) { + throw new Error('发货单号不能为空'); + } + if (!inputWarehouseId) throw new Error('仓库ID不能为空'); + + const warehouseId = parseInt(inputWarehouseId); + // 防护 NaN:parseInt 对非数字字符串返回 NaN,会导致 Sequelize 生成非法 SQL + const workbenchId = (workbenchIdRaw !== undefined && workbenchIdRaw !== null && workbenchIdRaw !== '') + ? parseInt(workbenchIdRaw) + : null; + const validWorkbenchId = (workbenchId !== null && !isNaN(workbenchId) && workbenchId > 0) + ? workbenchId + : null; + const packTimeMs = packTime ? Number(packTime) * 1000 : Date.now(); + + // 步骤1:查找订单(current → dispatch 分表遍历) + // 优先按订单主键定位:发货单号唯一索引为 (delivery_order_code, store_id, warehouse_id), + // 跨货主可重复,按「发货单号 + 仓库」反查在撞号时会串到别的货主的订单(历史缺陷); + // 仅在无 order_id(旧参数模式)或主键未命中时,才按发货单号兜底。 + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + const normalizedOrderIdParam = Number(orderIdParam); + const hasOrderIdParam = Number.isInteger(normalizedOrderIdParam) && normalizedOrderIdParam > 0; + + const findOneInTables = async where => { + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const row = await model.findOne({ where, raw: true }); + if (row) return row; + } catch (_err) { continue; } + } + return null; + }; + + const orderByPrimaryKey = hasOrderIdParam + ? await findOneInTables({ id: normalizedOrderIdParam, warehouse_id: warehouseId }) + : null; + const orderRow = orderByPrimaryKey + || await findOneInTables({ delivery_order_code: deliveryOrderCode, warehouse_id: warehouseId }); + + if (!orderRow) throw new Error(`未找到发货单 [${deliveryOrderCode}]`); + + // 主键与发货单号反查结果不一致时留痕(主键优先,防止串单) + if (hasOrderIdParam && Number(orderRow.id) !== normalizedOrderIdParam) { + ctx.logger.warn('[Workbench._packOrder] order_id 未命中、改按发货单号兜底命中 orderIdParam=%d hitOrderId=%d deliveryOrderCode=%s', + normalizedOrderIdParam, Number(orderRow.id), deliveryOrderCode); + } + if (deliveryOrderCode && orderRow.delivery_order_code + && String(orderRow.delivery_order_code) !== String(deliveryOrderCode)) { + ctx.logger.warn('[Workbench._packOrder] 发货单号与命中订单不一致,以订单主键为准 orderId=%d passed=%s hit=%s', + Number(orderRow.id), deliveryOrderCode, orderRow.delivery_order_code); + } + + const orderId = orderRow.id; + const waveId = orderRow.wave_id || 0; + const actualWaveNo = waveNo || orderRow.wave_no || ''; + + // 步骤2:获取波次信息,判断散单/团购 + let waveType = null; + let totalOrders = 0; + let isSandan = 1; + if (waveId > 0) { + try { + const waveBatch = await ctx.model.WaveBatch.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: ['wave_type', 'total_orders'], + raw: true, + }); + if (waveBatch) { + waveType = waveBatch.wave_type; + isSandan = Number(waveType) === 1 ? 0 : 1; + // 实时统计波次订单数(而非依赖 wave_batch.total_orders 快照) + totalOrders = await this._countWaveOrders(warehouseId, waveId); + } + } catch (_err) { /* ignore */ } + } + + // 拦截流程中的订单不允许打包: + // - 散单:直接拒绝(保持原行为); + // - 团购波次:静默跳过并视为完成(返回完成结构,不带任何提示字段), + // 不创建打包任务、不写操作日志,不阻断波次整体提交完成。 + if (isInterceptedOrderStatus(orderRow.intercept_status)) { + if (isSandan === 0) { + ctx.logger.info('[Workbench._packOrder] 团购波次拦截订单静默跳过 waveId=%d waveNo=%s orderId=%d deliveryOrderCode=%s', + waveId, actualWaveNo, orderId, deliveryOrderCode); + return { + order_id: orderId, + delivery_order_code: deliveryOrderCode, + wave_no: actualWaveNo, + isSandan: 0, + pack_mode: 2, + status: 2, + pack_wait_seconds: 0, + pack_start_time: 0, + batch: { wave_id: waveId, wave_no: actualWaveNo, wave_type: waveType, total_orders: totalOrders }, + }; + } + throw new Error(`订单已被拦截,无法打包 [${deliveryOrderCode}]`); + } + + // 步骤2.5:解析运单号归属(仅散单,兼容一单多号:主单号 business_key=1 / 子单号 business_key>1)。 + // 设备端扫描打包传入运单号时,按「订单 + 运单号」维度记录打包流水, + // 避免同一订单下主/子单号打包互相覆盖(散单去重)或被误判为已打包; + // 团购为波次维度打包,不使用运单号。 + let packWaybillCode = null; + if (isSandan === 1 && waybillCodeParam) { + const normalizedWaybill = String(waybillCodeParam).trim(); + if (normalizedWaybill) { + try { + const waybillRow = await ctx.model.OrderExpress.findOne({ + where: { + order_id: orderId, + warehouse_id: warehouseId, + waybill_code: normalizedWaybill, + status: 1, + }, + attributes: [ 'waybill_code', 'business_key' ], + raw: true, + }); + if (waybillRow) { + packWaybillCode = waybillRow.waybill_code; + ctx.logger.info('[Workbench._packOrder] 按运单维度打包 orderId=%d waybill=%s business_key=%d', + orderId, packWaybillCode, Number(waybillRow.business_key) || 1); + } else { + ctx.logger.warn('[Workbench._packOrder] 运单号不属于该订单,降级为订单维度打包 orderId=%d waybill=%s', + orderId, normalizedWaybill); + } + } catch (waybillErr) { + ctx.logger.warn('[Workbench._packOrder] 运单归属解析失败,降级为订单维度打包: %s', waybillErr.message); + } + } + } + + // 步骤3:获取工作台 device_ids 与名称(名称用于操作日志展示) + let deviceIds = null; + let workbenchName = ''; + if (validWorkbenchId) { + try { + const wb = await ctx.model.Workbench.findByPk(validWorkbenchId, { + attributes: [ 'name', 'device_ids' ], + raw: true, + }); + deviceIds = wb && wb.device_ids ? wb.device_ids : null; + workbenchName = (wb && wb.name) || ''; + } catch (_err) { /* ignore */ } + } + + // 步骤4:同一工作台有新的打包任务时,关闭上一个未结束的任务 + // 旧任务关闭会先把 OSD 复位为「无任务」,该 Promise 由步骤7.5 串行等待,避免复位覆盖新任务文字 + let previousTaskOsdResetPromise = null; + if (validWorkbenchId) { + const previousTask = await ctx.model.PackTask.findOne({ + where: { + workbench_id: validWorkbenchId, + warehouse_id: warehouseId, + order_id: { [ctx.app.Sequelize.Op.ne]: orderId }, + status: { [ctx.app.Sequelize.Op.lt]: 2 }, + }, + }); + if (previousTask) { + const previousEndTime = await this.resolvePackTaskEndTime(previousTask, new Date(packTimeMs)); + await previousTask.update({ end_time: previousEndTime, status: 2 }); + ctx.logger.info('[Workbench._packOrder] 关闭上一个未结束任务 taskId=%d orderId=%d workbenchId=%d', + previousTask.id, previousTask.order_id, validWorkbenchId); + + // 同步旧任务关联订单打包状态(与 _finishPack 语义一致,避免旧订单 pack_status 停留打包中) + const prevIsGroupTask = Number(previousTask.pack_mode) === 2; + const prevTaskWaveId = prevIsGroupTask ? Number(previousTask.wave_id || 0) : 0; + await this._updateOrderPackStatus(warehouseId, { + orderId: Number(previousTask.order_id || 0), + waveId: prevTaskWaveId, + packStatus: 2, + caller: 'Workbench._packOrder.closePrevious', + }); + + // 旧任务已结束:OSD 复位为「无任务」(不阻塞请求,步骤7.5 会等其完成后再下发新任务文字) + previousTaskOsdResetPromise = this._resetPackOsd({ + warehouseId, + workbenchId: validWorkbenchId, + }); + } + } + + // 步骤5:去重 — 散单按 order_id(未传运单号时)/order_id+waybill_code(传运单号时) + // 物理删除旧记录,团购按 wave_no 物理删除旧记录; + // 一单多号场景按运单维度去重,主单号/子单号的打包流水互不覆盖; + // 传运单号时同时清理同订单历史订单级(waybill_code 为空)旧流水, + // 避免空值幽灵记录导致其它运单被误判为已打包。 + if (isSandan === 1) { + // 散单去重:先收集旧任务ID清理关联打包人,再物理移除旧任务 + const sandanDedupeWhere = { order_id: orderId, warehouse_id: warehouseId }; + if (packWaybillCode) { + sandanDedupeWhere[ctx.app.Sequelize.Op.or] = [ + { waybill_code: packWaybillCode }, + { waybill_code: null }, + ]; + } + const oldTasks = await ctx.model.PackTask.findAll({ + where: sandanDedupeWhere, + attributes: ['id'], + raw: true, + paranoid: false, + }); + if (oldTasks.length > 0) { + const oldTaskIds = oldTasks.map(t => t.id); + await ctx.model.PackTaskPacker.destroy({ + where: { pack_task_id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + await ctx.model.PackTask.destroy({ + where: { id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + ctx.logger.info('[Workbench._packOrder] 散单去重:物理删除 %d 条旧记录 orderId=%d', oldTasks.length, orderId); + } + } else { + // 团购:按 wave_no 去重,先收集旧任务ID清理关联打包人,再物理移除旧任务 + if (actualWaveNo) { + const oldTasks = await ctx.model.PackTask.findAll({ + where: { wave_no: actualWaveNo, warehouse_id: warehouseId }, + attributes: ['id'], + raw: true, + paranoid: false, + }); + if (oldTasks.length > 0) { + const oldTaskIds = oldTasks.map(t => t.id); + await ctx.model.PackTaskPacker.destroy({ + where: { pack_task_id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + await ctx.model.PackTask.destroy({ + where: { id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + ctx.logger.info('[Workbench._packOrder] 团购去重:物理删除 %d 条旧记录 waveNo=%s', oldTasks.length, actualWaveNo); + } + } + } + + // 步骤6:创建新的打包任务 + // 设备端未传/非法 status 一律归一化为 1(打包中),避免 NaN 入库与日志异常 + const parsedPackStatus = Number.parseInt(packStatus, 10); + const normalizedPackStatus = Number.isFinite(parsedPackStatus) ? parsedPackStatus : 1; + + // 服务端复查落库口径:打包数量/商品总件数/商品种类数均以服务端为准, + // 散单取订单分表(orderRow),团购取波次实时统计(totalOrders + 波次商品 SKU 聚合), + // 设备端上报值仅作交叉校验日志,不直接落库,防止前端输入失真。 + let packQuantity = 1; + let packItemQuantity = Number(orderRow.items_total) || 0; + let packSkuCount = Number(orderRow.items_count) || 0; + + if (isSandan === 0) { + // 团购:打包数量 = 波次实时订单数(步骤2 已统计,异常兜底 1) + packQuantity = Number.isFinite(totalOrders) && totalOrders > 0 ? totalOrders : 1; + // 团购:商品总件数/商品种类数 = 波次商品 SKU 聚合(15s 短缓存兜底,异常降级为扫描订单值) + let waveItemsSummary = []; + try { + waveItemsSummary = await this._fetchWaveItemsSummary(warehouseId, waveId); + } catch (summaryErr) { + ctx.logger.warn('[Workbench._packOrder] 波次商品聚合失败,商品件数降级为扫描订单值: %s', summaryErr.message); + } + if (Array.isArray(waveItemsSummary) && waveItemsSummary.length > 0) { + packSkuCount = waveItemsSummary.length; + const waveItemsTotal = waveItemsSummary.reduce((sum, item) => sum + (Number(item.plan_qty) || 0), 0); + if (waveItemsTotal > 0) { + packItemQuantity = waveItemsTotal; + } + } + } + + // 交叉校验:设备端上报值与服务端复查不一致时仅记日志,落库以服务端为准 + const deviceWaveTotal = (waveTotalOrders !== undefined && waveTotalOrders !== null && waveTotalOrders !== '') + ? parseInt(waveTotalOrders) + : 0; + const deviceItemsTotal = (itemsTotal !== undefined && itemsTotal !== null && itemsTotal !== '') + ? parseInt(itemsTotal) + : 0; + const deviceItemsCount = (itemsCount !== undefined && itemsCount !== null && itemsCount !== '') + ? parseInt(itemsCount) + : 0; + if (isSandan === 0 && Number.isFinite(deviceWaveTotal) && deviceWaveTotal > 0 && deviceWaveTotal !== packQuantity) { + ctx.logger.info('[Workbench._packOrder] 打包数量复查不一致 waveId=%d 设备端=%d 服务端=%d(以服务端为准)', + waveId, deviceWaveTotal, packQuantity); + } + if (Number.isFinite(deviceItemsTotal) && deviceItemsTotal > 0 && deviceItemsTotal !== packItemQuantity) { + ctx.logger.info('[Workbench._packOrder] 商品总件数复查不一致 orderId=%d waveId=%d 设备端=%d 服务端=%d(以服务端为准)', + orderId, waveId, deviceItemsTotal, packItemQuantity); + } + if (Number.isFinite(deviceItemsCount) && deviceItemsCount > 0 && deviceItemsCount !== packSkuCount) { + ctx.logger.info('[Workbench._packOrder] 商品种类数复查不一致 orderId=%d waveId=%d 设备端=%d 服务端=%d(以服务端为准)', + orderId, waveId, deviceItemsCount, packSkuCount); + } + + // 波次范围(wave_scope)服务端复查:优先取上报值(0-4 整数),非法/缺省时兜底取订单行值 + const parsedWaveScope = Number.parseInt(waveScopeParam, 10); + const orderWaveScope = Number(orderRow.wave_scope) || 0; + const normalizedWaveScope = Number.isFinite(parsedWaveScope) && parsedWaveScope >= 0 && parsedWaveScope <= 4 + ? parsedWaveScope + : (orderWaveScope >= 0 && orderWaveScope <= 4 ? orderWaveScope : 0); + + const packData = { + order_id: orderId, + warehouse_id: warehouseId, + workbench_id: validWorkbenchId, + wave_id: waveId, + wave_no: actualWaveNo, + wave_scope: normalizedWaveScope, + waybill_code: packWaybillCode, // 散单运单维度打包时记录运单号;未传运单号(旧设备端)或团购保持 null + pack_mode: isSandan === 0 ? 2 : 1, // 1=散单 2=团购 + status: normalizedPackStatus, + pack_quantity: packQuantity, + item_quantity: packItemQuantity, + sku_count: packSkuCount, + start_time: new Date(packTimeMs), + end_time: normalizedPackStatus >= 2 ? new Date(packTimeMs) : null, + device_ids: deviceIds, + }; + + const packTask = await ctx.model.PackTask.create(packData); + ctx.logger.info('[Workbench._packOrder] 创建打包任务 taskId=%d orderId=%d', packTask.id, orderId); + + // 打包任务状态已变更(新建任务,且可能已关闭上一个未结束任务), + // 失效对应工作台 token 缓存,保证 getWorkbenchInfo 尽快返回最新打包中信息。 + await this.invalidateWorkbenchTokenCacheByWorkbenchId(validWorkbenchId); + + // 步骤6.5:更新订单的打包状态字段(散单按订单更新,团购按波次批量更新) + // 传 packData.status(已归一化,缺省为 1),避免设备端未传 status 时订单被误写为已完成 + await this._updateOrderPackStatus(warehouseId, { + orderId, + waveId: isSandan === 1 ? 0 : waveId, + packStatus: packData.status, + caller: 'Workbench._packOrder', + }); + + // 步骤7:写入打包人员信息 + // 上报了 users(business 旧链路)时以上报为准;未上报(token+key 新链路)时 + // 自动回填该工作台绑定成员(成员登入/登出链路 bindMember/removeMember 已持久化到 wms_workbench_member)。 + let users = Array.isArray(usersParam) && usersParam.length > 0 ? usersParam : []; + if (users.length === 0 && validWorkbenchId) { + try { + const members = await this.listWorkbenchMembers(validWorkbenchId); + users = members.map(m => ({ + wms_account_id: m.user_id != null ? m.user_id : null, + id: m.user_id != null ? m.user_id : null, + real_name: m.user_name || '', + })); + if (users.length > 0) { + ctx.logger.info('[Workbench._packOrder] 自动回填工作台绑定成员 %d 人 workbenchId=%d', + users.length, validWorkbenchId); + } + } catch (memberErr) { + // 成员查询失败不阻断打包主流程,打包人保持为空 + ctx.logger.warn('[Workbench._packOrder] 查询工作台绑定成员失败,打包人保持为空: %s', memberErr.message); + } + } + let operatorText = ''; + if (users.length > 0) { + // account_id 未知时写 null(表列允许 NULL):唯一索引 uix_pack_task_account 对 + // NULL 不生效,避免多人打包(account_id 全为 0)时违反唯一约束导致主流程中断。 + // 真实账号仍按 account_id 去重;无账号时按姓名去重。 + const seenPackerKeys = new Set(); + const packerRecords = []; + for (const user of users) { + const accountIdRaw = user.wms_account_id != null + ? user.wms_account_id + : (user.id != null ? user.id : null); + const accountId = accountIdRaw != null ? (parseInt(accountIdRaw) || null) : null; + const accountName = user.real_name || ''; + const dedupeKey = accountId !== null ? `id:${accountId}` : `name:${accountName}`; + if (seenPackerKeys.has(dedupeKey)) continue; + seenPackerKeys.add(dedupeKey); + packerRecords.push({ + pack_task_id: packTask.id, + account_id: accountId, + account_name: accountName, + seq: packerRecords.length, + }); + } + if (packerRecords.length > 0) { + await ctx.model.PackTaskPacker.bulkCreate(packerRecords); + } + operatorText = users.map(u => u.real_name || '').filter(Boolean).join(','); + // 回写 operator_text 到打包任务 + await packTask.update({ operator_text: operatorText }); + ctx.logger.info('[Workbench._packOrder] 写入 %d 个打包人员 operatorText=%s', users.length, operatorText); + } + + // 步骤7.5:下发 OSD 叠加到工作台绑定的摄像头(带 Redis 缓存去重) + const cameraIds = Array.isArray(deviceIds) ? deviceIds : []; + if (cameraIds.length > 0) { + let osdText = ''; + if (isSandan === 1) { + // 散单:优先打包时传入的运单号(一单多号时展示当前打包运单), + // 未传时查订单首个运单,兜底发货单号 + let osdWaybill = packWaybillCode; + if (!osdWaybill) { + const expressRecord = await ctx.model.OrderExpress.findOne({ + where: { order_id: orderId, warehouse_id: warehouseId }, + attributes: ['waybill_code'], + raw: true, + }); + osdWaybill = (expressRecord && expressRecord.waybill_code) || ''; + } + osdText = osdWaybill || deliveryOrderCode; + } else { + // 团购:波次号+总量 + osdText = `波次${actualWaveNo} 共${totalOrders}单`; + } + + // 缓存写入 + 逐台摄像头下发整体异步执行,不阻塞打包主流程 + const applyOsd = async () => { + // 写入 OSD 缓存 + try { + const osdCacheKey = `${OSD_CACHE_KEY_PREFIX}${validWorkbenchId}`; + await this.app.setCacheAsync(osdCacheKey, osdText, OSD_CACHE_TTL_SECONDS); + ctx.logger.info('[Workbench._packOrder] OSD缓存已写入 workbenchId=%d text=%s', + validWorkbenchId, osdText); + } catch (cacheErr) { + ctx.logger.warn('[Workbench._packOrder] OSD缓存写入失败 workbenchId=%d err=%s', + validWorkbenchId, cacheErr.message); + } + + const OsdClient = require('../../lib/osd_client'); + const osdClient = new OsdClient(ctx); + const PtzClient = require('../../lib/ptz_client'); + const ptzClient = new PtzClient(ctx); + + try { + await Promise.all(cameraIds.map(async cameraId => { + try { + const camera = await ctx.model.Camera.findOne({ + where: { id: cameraId, warehouse_id: warehouseId }, + raw: true, + }); + if (!camera || !camera.ip) return; + + // 打包开始:先跳转预设点1(机位复位),失败仅告警,不影响 OSD 下发 + try { + const presetResult = await ptzClient.presetGoto({ + camera, + warehouseId, + presetId: PACK_PRESET_GOTO_ID, + }); + if (!presetResult.success) { + ctx.logger.warn('[Workbench._packOrder] 预设点跳转失败 cameraId=%d presetId=%d error=%s', + cameraId, PACK_PRESET_GOTO_ID, presetResult.error || '打印服务返回异常'); + } + } catch (presetErr) { + ctx.logger.warn('[Workbench._packOrder] 预设点跳转异常 cameraId=%d err=%s', cameraId, presetErr.message); + } + + const result = await osdClient.setOsd({ + camera, + warehouseId, + text: osdText, + }); + + if (!result.success) { + ctx.logger.warn('[Workbench._packOrder] OSD下发失败 cameraId=%d error=%s', + cameraId, result.error || '打印服务返回异常'); + } + } catch (err) { + ctx.logger.warn('[Workbench._packOrder] OSD下发异常 cameraId=%d err=%s', cameraId, err.message); + } + })); + } catch (err) { + ctx.logger.warn('[Workbench._packOrder] OSD批量下发异常 err=%s', err.message); + } + }; + + // 若本请求关闭了上一个未结束任务,需等 OSD 复位为「无任务」完成后再下发新任务文字 + const osdTask = previousTaskOsdResetPromise + ? previousTaskOsdResetPromise.then(applyOsd) + : applyOsd(); + + osdTask.catch(err => { + ctx.logger.warn('[Workbench._packOrder] OSD下发流程异常 err=%s', err.message); + }); + } + + // 步骤8:写入操作日志(散单写单个订单,团购批量写波次所有订单) + await this._writePackOperationLog({ + warehouseId, + orderId, + waveId, + waveNo: actualWaveNo, + isSandan, + packData, + users, + workbenchName, + }); + + const result = { + task_id: packTask.id, + order_id: orderId, + delivery_order_code: deliveryOrderCode, + wave_no: actualWaveNo, + isSandan, + pack_mode: packData.pack_mode, + status: packData.status, + }; + + // 大团购波次(wave_scope=1)下发倒计时字段供前端展示: + // pack_wait_seconds = 大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数(秒), + // pack_start_time = 开始打包时间(毫秒时间戳);其他波次一律下发 0(不参与倒计时)。 + // 打包人数取该工作台当前打包成员数;人数为 0 时任务已被成员全部登出流程自动结束, + // 不会出现 0 人任务,仍按 1 兜底防除零。 + let packWaitSeconds = 0; + let packStartTime = 0; + if (normalizedWaveScope === 1) { + const coefficient = await this._getBigGroupPackCoefficient(warehouseId); + const packMemberCount = Array.isArray(users) && users.length > 0 ? users.length : 1; + packWaitSeconds = packQuantity * coefficient / packMemberCount; + packStartTime = packTimeMs; + } + result.pack_wait_seconds = packWaitSeconds; + result.pack_start_time = packStartTime; + + // 团购单附加波次总量 + if (isSandan === 0) { + result.batch = { wave_id: waveId, wave_no: actualWaveNo, wave_type: waveType, total_orders: totalOrders }; + } + + return result; + } + + /** + * 按仓库配置的打包最大时长约束任务结束时间。 + * 候选结束时间超过 开始时间+上限时长 时,截断为上限时间点。 + * 未配置有效时长或开始时间非法时不做约束,原样返回。 + * + * @param {Object} packTask 打包任务实例(需含 warehouse_id / pack_mode / start_time) + * @param {Date|string} endTime 候选结束时间 + * @return {Promise} 约束后的结束时间 + */ + async resolvePackTaskEndTime(packTask, endTime) { + const { ctx } = this; + const candidate = endTime instanceof Date ? endTime : new Date(endTime); + + if (!packTask || !Number.isFinite(candidate.getTime())) { + return endTime; + } + + const startMs = new Date(packTask.start_time).getTime(); + if (!Number.isFinite(startMs)) { + return endTime; + } + + const isGroup = Number(packTask.pack_mode) === 2; + let limitMinutes = null; + + try { + const warehouseId = Number(packTask.warehouse_id || 0); + const subjectConfig = await ctx.service.systems.deliveryOrder.getStoreSubjectConfig(warehouseId); + const rawMinutes = isGroup + ? subjectConfig.group_order_pack_max_minutes + : subjectConfig.single_order_pack_max_minutes; + limitMinutes = Number(rawMinutes); + } catch (error) { + ctx.logger.warn('[Workbench.resolvePackTaskEndTime] 读取仓库配置失败: %s', error.message); + } + + // 未配置有效时长时不约束结束时间 + if (!Number.isInteger(limitMinutes) || limitMinutes <= 0) { + return endTime; + } + + const maxEndMs = startMs + limitMinutes * 60 * 1000; + if (candidate.getTime() > maxEndMs) { + const cappedEndTime = new Date(maxEndMs); + ctx.logger.info( + '[Workbench.resolvePackTaskEndTime] 结束时间超过打包上限,截断为上限时间 taskId=%d packMode=%s limitMinutes=%d end=%s', + packTask.id, + isGroup ? 'group' : 'single', + limitMinutes, + cappedEndTime.toISOString() + ); + return cappedEndTime; + } + + return endTime; + } + + /** + * 工作台打包完成:传入工作台ID,查找最后一个未结束的打包任务并结束 + * @param {Object} params - { workbench_id, warehouse_id } + * @returns {Promise} + */ + async _finishPack(params) { + const { ctx } = this; + const { workbench_id: workbenchIdRaw, warehouse_id: inputWarehouseId } = params; + + if (!inputWarehouseId) throw new Error('仓库ID不能为空'); + + const warehouseId = parseInt(inputWarehouseId); + const workbenchId = (workbenchIdRaw !== undefined && workbenchIdRaw !== null && workbenchIdRaw !== '') + ? parseInt(workbenchIdRaw) + : null; + const validWorkbenchId = (workbenchId !== null && !isNaN(workbenchId) && workbenchId > 0) + ? workbenchId + : null; + + if (!validWorkbenchId) throw new Error('工作台ID不能为空'); + + // 查找该工作台最后一个未结束的打包任务(按 id 倒序取最新) + const lastTask = await ctx.model.PackTask.findOne({ + where: { + workbench_id: validWorkbenchId, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.lt]: 2 }, + }, + order: [[ 'id', 'DESC' ]], + }); + + if (!lastTask) { + ctx.logger.info('[Workbench._finishPack] 工作台 %d 无未结束的打包任务', validWorkbenchId); + return { workbench_id: validWorkbenchId, finished: false, message: '无未结束的打包任务' }; + } + + const now = new Date(); + const endTime = await this.resolvePackTaskEndTime(lastTask, now); + await lastTask.update({ end_time: endTime, status: 2 }); + + // 打包任务已结束,失效对应工作台 token 缓存,保证 getWorkbenchInfo 尽快返回最新打包中信息。 + await this.invalidateWorkbenchTokenCacheByWorkbenchId(validWorkbenchId); + + ctx.logger.info('[Workbench._finishPack] 工作台 %d 结束打包任务 taskId=%d orderId=%d', + validWorkbenchId, lastTask.id, lastTask.order_id); + + // 打包任务结束:复位工作台摄像头 OSD 为「无任务」(异步执行,不阻塞主流程) + this._resetPackOsd({ warehouseId, workbenchId: validWorkbenchId }).catch(err => { + ctx.logger.warn('[Workbench._finishPack] OSD复位异常 workbenchId=%d err=%s', + validWorkbenchId, err.message); + }); + + // 同步更新关联订单打包状态:散单更新单笔订单,团购批量更新波次下所有未拦截订单 + const isGroupTask = Number(lastTask.pack_mode) === 2; + const taskOrderId = Number(lastTask.order_id || 0); + const taskWaveId = isGroupTask ? Number(lastTask.wave_id || 0) : 0; + await this._updateOrderPackStatus(warehouseId, { + orderId: taskOrderId, + waveId: taskWaveId, + packStatus: 2, + caller: 'Workbench._finishPack', + }); + + // 写入完成操作日志(团购批量写波次订单,操作人取自任务记录 operator_text) + let workbenchName = ''; + try { + const wb = await ctx.model.Workbench.findByPk(validWorkbenchId, { + attributes: [ 'name' ], + raw: true, + }); + workbenchName = (wb && wb.name) || ''; + } catch (_err) { /* ignore */ } + + const operatorText = String(lastTask.operator_text || ''); + await this._writePackOperationLog({ + warehouseId, + orderId: taskOrderId, + waveId: taskWaveId, + waveNo: lastTask.wave_no || '', + isSandan: isGroupTask ? 0 : 1, + packData: { + pack_mode: lastTask.pack_mode, + status: 2, + pack_quantity: lastTask.pack_quantity, + item_quantity: lastTask.item_quantity, + sku_count: lastTask.sku_count, + workbench_id: validWorkbenchId, + wave_no: lastTask.wave_no, + }, + users: operatorText ? [{ real_name: operatorText }] : [], + workbenchName, + }); + + return { + workbench_id: validWorkbenchId, + finished: true, + task_id: lastTask.id, + order_id: lastTask.order_id, + end_time: endTime, + }; + } + + /** + * 打包任务结束后复位工作台摄像头 OSD 叠加文字为「无任务」。 + * 覆盖所有结束路径:工作台手动结束(_finishPack)、新任务关闭旧任务(_packOrder)、 + * 定时任务自动结束(packTaskAutoFinish)。 + * - 回写 Redis osd_{workbenchId} 缓存为「无任务」,避免缓存残留上一个任务文字; + * - 逐台摄像头下发「无任务」,失败仅打印告警,不影响打包主流程; + * - 内部已捕获全部异常,永不 reject。 + * + * @param {Object} params - { warehouseId, workbenchId } + * @return {Promise} 无返回值 + */ + async _resetPackOsd(params = {}) { + const { ctx } = this; + const warehouseId = parseInt(params.warehouseId); + const workbenchId = parseInt(params.workbenchId); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) return; + if (!Number.isInteger(workbenchId) || workbenchId <= 0) return; + + // 1. 回写 OSD 缓存为「无任务」,与摄像头实际叠加文字保持一致 + try { + await this.app.setCacheAsync( + `${OSD_CACHE_KEY_PREFIX}${workbenchId}`, + OSD_IDLE_TEXT, + OSD_CACHE_TTL_SECONDS + ); + } catch (cacheErr) { + ctx.logger.warn('[Workbench._resetPackOsd] OSD缓存写入失败 workbenchId=%d err=%s', + workbenchId, cacheErr.message); + } + + // 2. 查询工作台绑定的摄像头 + let deviceIds = null; + try { + const wb = await ctx.model.Workbench.findByPk(workbenchId, { + attributes: [ 'device_ids' ], + raw: true, + }); + deviceIds = wb && wb.device_ids ? wb.device_ids : null; + } catch (err) { + ctx.logger.warn('[Workbench._resetPackOsd] 读取工作台绑定设备失败 workbenchId=%d err=%s', + workbenchId, err.message); + return; + } + + const cameraIds = Array.isArray(deviceIds) ? deviceIds : []; + if (cameraIds.length === 0) return; + + const OsdClient = require('../../lib/osd_client'); + const osdClient = new OsdClient(ctx); + + await Promise.all(cameraIds.map(async cameraId => { + try { + const camera = await ctx.model.Camera.findOne({ + where: { id: cameraId, warehouse_id: warehouseId }, + raw: true, + }); + if (!camera || !camera.ip) return; + + const result = await osdClient.setOsd({ + camera, + warehouseId, + text: OSD_IDLE_TEXT, + }); + + if (!result.success) { + ctx.logger.warn('[Workbench._resetPackOsd] OSD复位失败 cameraId=%d error=%s', + cameraId, result.error || '打印服务返回异常'); + } + } catch (err) { + ctx.logger.warn('[Workbench._resetPackOsd] OSD复位异常 cameraId=%d err=%s', cameraId, err.message); + } + })); + + ctx.logger.info('[Workbench._resetPackOsd] 打包任务结束,OSD已复位为「%s」workbenchId=%d cameras=%d', + OSD_IDLE_TEXT, workbenchId, cameraIds.length); + } + + /** + * 称重上报:条码(sn) → 运单号 → 更新称重重量 + * 支持散单直接更新和团购波次批量称重 + * @param {Object} params - { barcode, weight(克), warehouseId } + * @returns {Promise} weighing_weight/total_weight 单位为 g + */ + async _sendWeight(params) { + const { ctx } = this; + const { barcode, weight, warehouseId: inputWarehouseId } = params; + + // 参数校验 + if (!barcode || !String(barcode).trim()) { + throw new Error('条码(sn)不能为空'); + } + if (weight === null || weight === undefined || String(weight).trim() === '') { + throw new Error('重量(weight)不能为空'); + } + if (!inputWarehouseId) { + throw new Error('仓库ID不能为空'); + } + + const normalizedBarcode = String(barcode).trim(); + const warehouseId = parseInt(inputWarehouseId); + + // 校验重量格式(入参单位:克),必须大于0 + const weightText = String(weight).trim(); + if (!/^\d+$/.test(weightText)) { + throw new Error('重量格式非法,必须为正整数(单位 g)'); + } + const weightGram = Number(weightText); + if (!Number.isFinite(weightGram) || weightGram <= 0) { + throw new Error('重量必须大于0'); + } + // DB 存储单位已统一为 g,无需转换 + const normalizedWeight = weightGram; + + // 步骤1:条码 → 运单记录(按 waybill_code + warehouse_id 精确匹配) + const expressRow = await ctx.model.OrderExpress.findOne({ + where: { + waybill_code: normalizedBarcode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ], + raw: true, + }); + + if (!expressRow) { + throw new Error(`未找到条码 [${normalizedBarcode}] 对应的运单记录`); + } + + const orderId = Number(expressRow.order_id); + + // 步骤2:遍历 current → history → dispatch 分表查找订单及波次信息 + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + // 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历 + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId); + if (preferredLocation) { + tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (_err) { /* 定位失败,保持原遍历顺序 */ } + + let orderRow = null; + let orderDeliveryModel = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no', 'wave_scope', 'pack_status', 'items_weight', 'intercept_status' ], + raw: true, + }); + if (row) { + orderRow = row; + orderDeliveryModel = model; + break; + } + } catch (_err) { + ctx.logger.warn('[Workbench._sendWeight] 查询表 %s 失败: %s', entry.label, _err.message); + continue; + } + } + + if (!orderRow) { + throw new Error(`未找到运单对应的订单 [id=${orderId}, warehouse=${warehouseId}]`); + } + + // 拦截流程中的订单不允许称重 + if (isInterceptedOrderStatus(orderRow.intercept_status)) { + throw new Error(`订单已被拦截,无法称重 [${normalizedBarcode}]`); + } + + // 散单称重前置校验:开启「散单称重是否需要打包」后,波次范围非大团购(1)/小团购(3)的未打包订单禁止称重 + await this._assertSingleWeighPackedForWeigh(orderRow, warehouseId); + + const waveId = Number(orderRow.wave_id || 0); + + // 步骤3:散单(wave_id=0)→ 仅更新该运单的称重重量 + if (waveId === 0) { + await ctx.model.OrderExpress.update( + { weighing_weight: normalizedWeight }, + { where: { id: Number(expressRow.id) } } + ); + + ctx.logger.info('[Workbench._sendWeight] 散单称重 barcode=%s orderId=%d weightG=%s', + normalizedBarcode, orderId, normalizedWeight); + + // 回写订单表 packages_weight:所有包裹总重量 = 该订单全部有效运单称重之和 + const packagesWeight = await ctx.service.systems.orderExpress._syncOrderPackagesWeight( + orderId, warehouseId, orderDeliveryModel + ); + + // 写入操作日志 + await this._writeWeighOpLog({ + orderId, + barcode: normalizedBarcode, + weightGram, + normalizedWeight, + warehouseId, + }); + + return { + barcode: normalizedBarcode, + waybill_code: normalizedBarcode, + order_id: orderId, + weighing_weight: normalizedWeight, + packages_weight: packagesWeight, + items_weight: Number(orderRow.items_weight || 0), + mode: 'single', + }; + } + + // 步骤4:查询波次类型,判断是否为团购波次 + const waveRow = await ctx.model.WaveBatch.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 非团购波次 → 降级为散单逻辑 + if (!waveRow || Number(waveRow.wave_type) !== 1) { + await ctx.model.OrderExpress.update( + { weighing_weight: normalizedWeight }, + { where: { id: Number(expressRow.id) } } + ); + + ctx.logger.info('[Workbench._sendWeight] 非团购波次称重 barcode=%s orderId=%d weightG=%s waveType=%s', + normalizedBarcode, orderId, normalizedWeight, waveRow ? waveRow.wave_type : 'N/A'); + + // 回写订单表 packages_weight:所有包裹总重量 = 该订单全部有效运单称重之和 + const packagesWeight = await ctx.service.systems.orderExpress._syncOrderPackagesWeight( + orderId, warehouseId, orderDeliveryModel + ); + + // 写入操作日志 + await this._writeWeighOpLog({ + orderId, + barcode: normalizedBarcode, + weightGram, + normalizedWeight, + warehouseId, + }); + + return { + barcode: normalizedBarcode, + waybill_code: normalizedBarcode, + order_id: orderId, + weighing_weight: normalizedWeight, + packages_weight: packagesWeight, + items_weight: Number(orderRow.items_weight || 0), + mode: 'single', + }; + } + + // 步骤5:团购波次(wave_type=1)→ 批量更新波次下所有运单的称重重量 + const { Op } = ctx.app.Sequelize; + const waveOrders = await orderDeliveryModel.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id', 'intercept_status' ], + raw: true, + }); + + if (!waveOrders || waveOrders.length === 0) { + throw new Error('波次下未找到订单'); + } + + // 波次内拦截订单不参与批量称重 + const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + const orderIds = (Array.isArray(waveOrders) ? waveOrders : []) + .filter(o => !isInterceptedOrderStatus(o && o.intercept_status)) + .map(o => Number(o.id)); + if (interceptedWaveOrderIds.length > 0) { + ctx.logger.info('[Workbench._sendWeight] 波次内拦截订单不参与称重 waveId=%d orderIds=%s', + waveId, interceptedWaveOrderIds.join(',')); + } + const totalCount = orderIds.length; + + await ctx.model.OrderExpress.update( + { weighing_weight: normalizedWeight }, + { + where: { + order_id: { [Op.in]: orderIds }, + delete_at: null, + warehouse_id: warehouseId, + }, + } + ); + + // 回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部运单称重之和) + await ctx.service.systems.orderExpress._syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel); + + ctx.logger.info('[Workbench._sendWeight] 团购波次批量称重 barcode=%s waveId=%d waveNo=%s orderCount=%d weightG=%s', + normalizedBarcode, waveId, waveRow.wave_no, totalCount, normalizedWeight); + + // 写入操作日志(团购波次:逐订单批量写入) + await this._writeWeighOpLog({ + orderId, + barcode: normalizedBarcode, + weightGram, + normalizedWeight, + warehouseId, + waveId, + waveNo: String(waveRow.wave_no || ''), + waveOrderIds: orderIds, + }); + + return { + barcode: normalizedBarcode, + waybill_code: normalizedBarcode, + wave_id: waveId, + wave_no: String(waveRow.wave_no || ''), + weighing_weight: normalizedWeight, + total_weight: normalizedWeight * totalCount, + order_count: totalCount, + items_weight: Number(orderRow.items_weight || 0), + mode: 'wave', + }; + } + + /** + * 散单称重前置校验(工作台):开启仓库配置「散单称重是否需要打包」后, + * 波次范围(wave_scope)非 1(大团购)/ 3(小团购)的订单,打包中或已打包 + * (pack_status = padding/fin)时允许称重。 + * + * 配置读取与提示文案复用 systems/order_express,避免多处判定逻辑漂移; + * 当前订单行已含 wave_scope/pack_status,故无需重复查询订单表。 + * 配置服务不可用时静默跳过,不阻断称重主流程。 + * + * @param {Object} orderRow 订单行(需包含 wave_scope/pack_status) + * @param {number} warehouseId 仓库ID + * @return {Promise} 无返回值;未打包或打包异常时抛出错误 + */ + async _assertSingleWeighPackedForWeigh(orderRow, warehouseId) { + const waveScope = Number((orderRow && orderRow.wave_scope) || 0); + if (waveScope === 1 || waveScope === 3) { + return; + } + + const orderExpressService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.orderExpress; + if (!orderExpressService || typeof orderExpressService.isSingleWeighRequirePack !== 'function') { + return; + } + + const requirePack = await orderExpressService.isSingleWeighRequirePack(warehouseId); + if (!requirePack) { + return; + } + + const packStatus = String((orderRow && orderRow.pack_status) || '').trim(); + if (packStatus === 'fin' || packStatus === 'padding') { + return; + } + + const message = typeof orderExpressService.buildWeighPackBlockedMessage === 'function' + ? orderExpressService.buildWeighPackBlockedMessage() + : '订单未打包'; + throw new Error(message); + } + + /** + * 写入称重操作日志(内部方法,失败不影响主流程) + * @param {Object} opts + * @param {number} opts.orderId 触发订单ID + * @param {string} opts.barcode 条码/运单号 + * @param {number} opts.weightGram 称重重量(克) + * @param {number} opts.normalizedWeight 称重重量(克) + * @param {number} opts.warehouseId 仓库ID + * @param {number} [opts.waveId] 波次ID(团购时传入) + * @param {string} [opts.waveNo] 波次号 + * @param {number[]} [opts.waveOrderIds] 波次下所有订单ID(团购时传入,逐条写日志) + */ + async _writeWeighOpLog(opts = {}) { + const { ctx } = this; + const { + orderId, barcode, weightGram, normalizedWeight, warehouseId, + waveId, waveNo, waveOrderIds, + } = opts; + + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + return; + } + + const isWave = waveId && waveId > 0 && Array.isArray(waveOrderIds) && waveOrderIds.length > 0; + const operator = { id: '', name: 'system' }; + + if (isWave) { + // 团购波次:逐订单批量写入操作日志 + const orderCount = waveOrderIds.length; + const message = `工作台团购波次称重 ${normalizedWeight}g,波次 ${waveNo || waveId},共 ${orderCount} 单,触发条码 ${barcode}`; + const payloads = waveOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(oid), + operationCode: 'ORDER_WEIGH', + operator, + extras: { + warehouseId, + message, + barcode, + weightGram, + weighingWeight: normalizedWeight, + waveId, + waveNo: waveNo || '', + orderCount, + }, + })); + + await operationLogService.createOperationLogs(payloads); + ctx.logger.info('[Workbench._writeWeighOpLog] 团购称重操作日志已批量写入 waveId=%d orderCount=%d', + waveId, orderCount); + } else { + // 散单:单条操作日志 + const payload = { + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_WEIGH', + operator, + extras: { + warehouseId, + message: `工作台称重 ${normalizedWeight}g,条码 ${barcode}`, + barcode, + weightGram, + weighingWeight: normalizedWeight, + orderId, + }, + }; + + await operationLogService.createOperationLogs([ payload ]); + ctx.logger.info('[Workbench._writeWeighOpLog] 散单称重操作日志已写入 orderId=%d barcode=%s', + orderId, barcode); + } + } catch (e) { + ctx.logger.warn('[Workbench._writeWeighOpLog] 写入操作日志失败,不影响主流程', { + error: e && e.message, + orderId, + barcode, + }); + } + } + + /** + * 实时聚合波次商品明细(无缓存,供 _fetchWaveItemsSummary 调用)。 + * 口径:波次下全部未拦截订单(current + dispatch 分表)的商品明细行按 SKU 聚合计划数量 + * (stock_id 优先作聚合键,缺省按 item_code+item_name),并合并 stock 详情(条码/图片/包装要求/是否需要复核); + * 任一环节异常均降级返回空数组,不抛错。 + * @param {number} warehouseId 仓库ID + * @param {number} waveId 波次ID + * @return {Promise>} 波次商品聚合数组(结构与散单 items 一致,另附 is_wave_summary=true) + */ + async _aggregateWaveItems(warehouseId, waveId) { + const { ctx } = this; + try { + const orderIds = await this._getWaveOrderIds(warehouseId, waveId, true); + if (!orderIds || orderIds.length === 0) return []; + + const orderItemsFactory = ctx.model.OrderItemsFactory; + const itemTables = [ + { getModel: () => orderItemsFactory.getCurrentModel(warehouseId) }, + { getModel: () => orderItemsFactory.getDispatchModel(warehouseId) }, + ]; + + const itemRows = []; + for (const entry of itemTables) { + try { + const model = await entry.getModel(); + if (!model) continue; + const rows = await model.findAll({ + where: { order_id: { [ctx.app.Sequelize.Op.in]: orderIds } }, + attributes: [ + 'id', 'order_id', 'item_id', 'item_code', 'item_name', + 'plan_qty', 'actual_price', 'stock_id', 'order_line_no', + 'inventory_type', + ], + raw: true, + }); + itemRows.push(...rows); + } catch (_err) { continue; } + } + + if (itemRows.length === 0) return []; + + // 按 SKU 聚合(stock_id 优先作聚合键,缺省按 item_code+item_name) + const aggregateMap = new Map(); + for (const row of itemRows) { + const stockId = Number(row.stock_id || 0); + const itemCode = String(row.item_code || '').trim(); + const itemName = String(row.item_name || '').trim(); + const key = stockId > 0 ? `stock:${stockId}` : `code:${itemCode}||${itemName}`; + if (!key) continue; + const planQty = Number(row.plan_qty || 0); + if (!aggregateMap.has(key)) { + aggregateMap.set(key, { + stock_id: stockId, + item_id: row.item_id, + item_code: itemCode, + item_name: itemName, + plan_qty: 0, + inventory_type: row.inventory_type || '', + }); + } + aggregateMap.get(key).plan_qty += planQty; + } + + const aggregates = Array.from(aggregateMap.values()); + const stockIds = [ ...new Set(aggregates.map(a => a.stock_id).filter(id => id > 0)) ]; + const stockMap = new Map(); + if (stockIds.length > 0) { + try { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const detail of stockDetails) { + stockMap.set(Number(detail.id), detail); + } + } catch (stockErr) { + ctx.logger.warn('[Workbench._aggregateWaveItems] 查询 stock 详情失败: %s', stockErr.message); + } + } + + return aggregates.map(agg => { + const stock = stockMap.get(agg.stock_id) || {}; + return { + id: 0, + order_id: 0, + item_id: agg.item_id, + item_code: agg.item_code || stock.item_code || '', + item_name: agg.item_name || stock.item_name || '', + plan_qty: agg.plan_qty, + actual_price: null, + stock_id: agg.stock_id, + order_line_no: '', + inventory_type: agg.inventory_type || '', + sku_property: stock.sku_property || '', + stock_unit: stock.stock_unit || '', + barcodes: stock.barcodes || [], + image_url: stock.image_url || [], + packing_requirements: String(stock.packing_requirements || '').trim(), + pick_requirements: String(stock.pick_requirements || '').trim(), + recheck_requirements: String(stock.recheck_requirements || '').trim(), + merge_requirements: String(stock.merge_requirements || 'Y').trim(), + need_recheck: String(stock.need_recheck || 'Y').trim(), + is_wave_summary: true, + }; + }); + } catch (err) { + ctx.logger.warn('[Workbench._aggregateWaveItems] 聚合波次商品失败 waveId=%d: %s', waveId, err.message); + return []; + } + } + + /** + * 团购波次商品 SKU 聚合汇总(带 Redis 短 TTL 缓存兜底,供 getWorkbenchInfo 团购任务 items 返回)。 + * 波次商品明细量大(动辄数百单),逐单返回明细开销高且无必要, + * 因此按 (warehouseId, waveId) 维度做 15s 短缓存(与 _countWaveOrdersCached/_sumWaveItemsTotalCached 同款): + * TTL 内重复查询直接命中缓存,缓存不可用或读取失败时降级为实时聚合。 + * @param {number} warehouseId 仓库ID + * @param {number} waveId 波次ID + * @return {Promise>} 波次商品汇总数组(异常降级为空数组) + */ + async _fetchWaveItemsSummary(warehouseId, waveId) { + const { ctx, app } = this; + const cacheKey = `${WAVE_ITEMS_SUMMARY_CACHE_KEY_PREFIX}:${warehouseId}:${waveId}`; + + if (app && typeof app.getCacheAsync === 'function') { + try { + const cached = await app.getCacheAsync(cacheKey); + if (Array.isArray(cached)) { + return cached; + } + } catch (cacheReadErr) { + ctx.logger.warn('[Workbench._fetchWaveItemsSummary] 读取缓存失败,降级为实时聚合: %s', cacheReadErr.message); + } + } + + const items = await this._aggregateWaveItems(warehouseId, waveId); + + if (app && typeof app.setCacheAsync === 'function') { + try { + await app.setCacheAsync(cacheKey, items, WAVE_ITEMS_SUMMARY_CACHE_TTL_SECONDS); + } catch (cacheWriteErr) { + ctx.logger.warn('[Workbench._fetchWaveItemsSummary] 写入缓存失败,不影响本次返回: %s', cacheWriteErr.message); + } + } + + return items; + } + + /** + * 查询订单商品明细并合并 stock 详情(供 _queryOrder 与 buildCurrentPackingInfo 复用)。 + * - 商品明细来自 OrderItemsFactory 分表(sourceTable=dispatch 查配送明细表,其余查 current); + * - stock 详情(条码/图片/包装要求等)经 stockWarehouse.getStockDetails 批量查询(自带缓存); + * - 任一环节异常均降级返回空数组,不抛错。 + * @param {number} orderId 订单ID + * @param {number} warehouseId 仓库ID + * @param {string} [sourceTable] 订单所在分表(dispatch|current),决定明细分表选择 + * @return {Promise>} 商品明细数组(含 item_code/item_name/plan_qty/barcodes/image_url 等) + */ + async _fetchOrderItemsDetail(orderId, warehouseId, sourceTable) { + const { ctx } = this; + let items = []; + try { + const getItemsModel = sourceTable === 'dispatch' + ? () => ctx.model.OrderItemsFactory.getDispatchModel(warehouseId) + : () => ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const itemsModel = await getItemsModel(); + if (itemsModel) { + const orderItems = await itemsModel.findAll({ + where: { order_id: orderId }, + attributes: [ + 'id', 'order_id', 'item_id', 'item_code', 'item_name', + 'plan_qty', 'actual_price', 'stock_id', 'order_line_no', + 'inventory_type', 'item_snapshot', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (orderItems.length > 0) { + // 收集所有 stock_id,批量查询 stock 详情(带缓存) + const stockIds = [ ...new Set( + orderItems.map(item => Number(item.stock_id)).filter(id => id > 0) + ) ]; + + /** @type {Map} */ + const stockMap = new Map(); + if (stockIds.length > 0) { + try { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( + stockIds, + { warehouseId } + ); + for (const detail of stockDetails) { + stockMap.set(Number(detail.id), detail); + } + } catch (stockErr) { + ctx.logger.warn('[Workbench._fetchOrderItemsDetail] 查询 stock 详情失败: %s', stockErr.message); + } + } + + // 组装 items,合并 stock 信息 + items = orderItems.map(item => { + const stockId = Number(item.stock_id); + const stock = stockMap.get(stockId) || {}; + return { + id: item.id, + order_id: item.order_id, + item_id: item.item_id, + item_code: item.item_code || stock.item_code || '', + item_name: item.item_name || stock.item_name || '', + plan_qty: item.plan_qty, + actual_price: item.actual_price, + stock_id: stockId, + order_line_no: item.order_line_no || '', + inventory_type: item.inventory_type || '', + sku_property: stock.sku_property || '', + stock_unit: stock.stock_unit || '', + barcodes: stock.barcodes || [], + image_url: stock.image_url || '', + packing_requirements: String(stock.packing_requirements || '').trim(), + pick_requirements: String(stock.pick_requirements || '').trim(), + recheck_requirements: String(stock.recheck_requirements || '').trim(), + merge_requirements: String(stock.merge_requirements || 'Y').trim(), + need_recheck: String(stock.need_recheck || 'Y').trim(), + }; + }); + } + } + } catch (itemsErr) { + ctx.logger.warn('[Workbench._fetchOrderItemsDetail] 查询订单商品失败 orderId=%d: %s', orderId, itemsErr.message); + } + return items; + } + + /** + * 统计当前工作台打包成员人数(wms_workbench_member 未软删除记录)。 + * 查询失败或结果为 0 时按 1 兜底:成员全部登出时未结束任务已被自动结束, + * 正常流程不会出现 0 人任务,兜底仅防除零。 + * @param {number} workbenchId 工作台ID + * @return {Promise} 打包成员人数(至少 1) + */ + async _countCurrentPackMembers(workbenchId) { + const { ctx } = this; + try { + const count = await ctx.model.WorkbenchMember.count({ + where: { workbench_id: workbenchId }, + }); + if (Number.isInteger(count) && count > 0) { + return count; + } + } catch (countErr) { + ctx.logger.warn('[Workbench._countCurrentPackMembers] 统计打包成员失败: %s', countErr.message); + } + return 1; + } + + /** + * 读取仓库「大团购打包系数」配置(wms_store.subject_config.big_group_pack_coefficient)。 + * 走 deliveryOrder.getStoreSubjectConfig 公共读取链路(带缓存);配置读取失败 + * 或值非法时降级为默认系数 3(秒/单),保证时间闸门兜底可用。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 大团购打包系数(秒/单),大于 0 + */ + async _getBigGroupPackCoefficient(warehouseId) { + const DEFAULT_COEFFICIENT = 3; + try { + const deliveryOrderService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.deliveryOrder; + if (deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function') { + const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(warehouseId); + const coefficient = Number(subjectConfig && subjectConfig.big_group_pack_coefficient); + if (Number.isFinite(coefficient) && coefficient > 0) { + return coefficient; + } + } + } catch (configErr) { + this.ctx.logger.warn('[Workbench._getBigGroupPackCoefficient] 读取仓库配置失败,使用默认系数: %s', configErr.message); + } + return DEFAULT_COEFFICIENT; + } + + /** + * 条码查订单:条码 → wms_order_express → 待处理/配送订单详情。 + * 散单(isSandan=1)时在响应 order 对象中额外返回 intercept_flag / pack_flag 两个 0/1 标志: + * 拦截状态(intercept_status)不等于 none 时 intercept_flag=1,否则 0; + * pack_flag 按运单维度判定(该运单号已有打包流水为 1,主/子单号互不影响)。 + * order 对象始终包含 picker_id / picker_name:通过 wave_id 关联拣货任务取拣货人, + * 散单无波次或未分配拣货人时为 null / 空串。 + * 大团购打包时长闸门:当前工作台存在进行中的大团购打包任务时,判断是否已到 + * 「大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数」秒:未到时仅允许查询本波次订单, + * 其他波次订单返回「打包时长不足」错误;已到时不受限制。 + * 查询成功时生成一次性打包上下文 key(20 分钟有效)写入 Redis, + * 响应附 key 供 workbench.packOrder 消费,打包参数由后端维护防篡改。 + * @param {Object} params - { barcode, warehouseId, workbenchId } + * @return {Promise} 查询结果 { key, barcode, waybill_code, isSandan, store_remark, express, order, items, source_table, batch? } + */ + async _queryOrder(params) { + const { ctx } = this; + const { barcode, warehouseId: inputWarehouseId, workbench_id: workbenchIdRaw } = params; + const workbenchId = (workbenchIdRaw !== undefined && workbenchIdRaw !== null && workbenchIdRaw !== '') + ? parseInt(workbenchIdRaw) + : null; + const validQueryWorkbenchId = (workbenchId !== null && !isNaN(workbenchId) && workbenchId > 0) + ? workbenchId + : null; + + if (!barcode || !String(barcode).trim()) { + throw new Error('条码不能为空'); + } + if (!inputWarehouseId || !String(inputWarehouseId).trim()) { + throw new Error('仓库ID不能为空'); + } + + const normalizedBarcode = String(barcode).trim(); + const warehouseId = parseInt(inputWarehouseId); + + // 步骤1:条码 → order_id + warehouse_id(必须限制仓库) + const expressRecord = await ctx.model.OrderExpress.findOne({ + where: { + waybill_code: normalizedBarcode, + warehouse_id: warehouseId, + status: 1, + }, + attributes: ['order_id', 'warehouse_id', 'waybill_code', 'logistics_name', 'weighing_weight', 'package_material_name_snapshot'], + raw: true, + }); + + if (!expressRecord) { + throw new Error(`未找到条码 [${normalizedBarcode}] 对应的运单记录`); + } + + const { order_id: orderId, waybill_code: waybillCode } = expressRecord; + + // 步骤2:序列表定位优先(命中则先查对应分表),未命中按 current → dispatch 回退遍历 + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + try { + if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') { + const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId); + if (preferredLocation) { + tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0)); + } + } + } catch (locErr) { + ctx.logger.warn('[Workbench._queryOrder] 序列表定位失败,按默认顺序遍历: %s', locErr.message); + } + + let orderRow = null; + let sourceTable = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + raw: true, + }); + if (row) { + orderRow = row; + sourceTable = entry.label; + break; + } + } catch (_err) { + ctx.logger.warn('[Workbench._queryOrder] 查询表 %s 失败: %s', entry.label, _err.message); + continue; + } + } + + if (!orderRow) { + throw new Error(`未在待处理或配送表中找到订单 [id=${orderId}, warehouse=${warehouseId}]`); + } + + ctx.logger.info('[Workbench._queryOrder] 条码=%s 命中 orderId=%d source=%s', + normalizedBarcode, orderId, sourceTable); + + // 步骤3:判断波次类型(散单 vs 团购),团购需返回波次总量 + let waveType = null; + let totalBatchOrders = 0; + let isSandan = 1; // 默认散单 + + const waveId = orderRow.wave_id; + if (waveId && Number(waveId) > 0) { + try { + // 查询波次信息 + const waveBatch = await ctx.model.WaveBatch.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: ['wave_id', 'wave_type', 'total_orders'], + raw: true, + }); + + if (waveBatch) { + waveType = waveBatch.wave_type; + // wave_type=1 → 团购单(isSandan=0); 其他(2=散单等) → 散单(isSandan=1) + if (Number(waveType) === 1) { + isSandan = 0; + // 仅团购单组装波次总量:实时统计带短 TTL 缓存; + // 散单不再触发分表 COUNT,避免 680ms+ 的无用扫描 + totalBatchOrders = await this._countWaveOrdersCached(warehouseId, waveId); + } else { + isSandan = 1; + } + } + } catch (waveErr) { + ctx.logger.warn('[Workbench._queryOrder] 查询波次信息失败 waveId=%d: %s', waveId, waveErr.message); + } + } + + // 步骤3.5:大团购打包时长闸门。 + // 打包任务已落库 wave_scope,直接按 wave_scope=1 快捷判定当前工作台是否有 + // 进行中的大团购任务(status<2,任务已结束则不计)需要限制下一个任务的开始时间: + // - 未到「大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数」秒时: + // 仅允许查询本波次订单,其他波次订单返回「打包时长不足」错误; + // - 已到时:不受限制,正常下发。 + if (validQueryWorkbenchId) { + let packTimeGateNotReached = false; + let currentTaskWaveId = 0; + try { + const currentPackTask = await ctx.model.PackTask.findOne({ + where: { + workbench_id: validQueryWorkbenchId, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.lt]: 2 }, + wave_scope: 1, + wave_id: { [ctx.app.Sequelize.Op.gt]: 0 }, + }, + attributes: [ 'id', 'wave_id', 'pack_quantity', 'start_time', 'create_time' ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + if (currentPackTask) { + const coefficient = await this._getBigGroupPackCoefficient(warehouseId); + const startMs = currentPackTask.start_time + ? new Date(currentPackTask.start_time).getTime() + : (currentPackTask.create_time ? new Date(currentPackTask.create_time).getTime() : Date.now()); + const currentPackQuantity = Number(currentPackTask.pack_quantity) > 0 + ? Number(currentPackTask.pack_quantity) + : 1; + const packMemberCount = await this._countCurrentPackMembers(validQueryWorkbenchId); + const requiredSeconds = currentPackQuantity * coefficient / packMemberCount; + const elapsedSeconds = Math.floor((Date.now() - startMs) / 1000); + if (elapsedSeconds < requiredSeconds) { + packTimeGateNotReached = true; + currentTaskWaveId = Number(currentPackTask.wave_id) || 0; + } + } + } catch (timeGateErr) { + ctx.logger.warn('[Workbench._queryOrder] 大团购打包时长闸门检查失败: %s', timeGateErr && timeGateErr.message); + } + + if (packTimeGateNotReached && Number(waveId) !== currentTaskWaveId) { + throw new Error('打包时长不足'); + } + } + + // 步骤4:查询订单商品明细 + 关联 stock 详情(带缓存,公共方法 _fetchOrderItemsDetail) + const items = await this._fetchOrderItemsDetail(orderId, warehouseId, sourceTable); + + // 步骤5:查询货主备注(从合约表 store_warehouse.store_remask) + let storeRemark = ''; + const storeId = Number(orderRow.store_id || 0); + if (storeId > 0) { + try { + const swRow = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: ['store_remask'], + raw: true, + }); + storeRemark = (swRow && swRow.store_remask) ? String(swRow.store_remask).trim() : ''; + } catch (swErr) { + ctx.logger.warn('[Workbench._queryOrder] 查询货主备注失败 storeId=%d: %s', storeId, swErr.message); + } + } + + // 步骤6:散单标志位计算 + // - 拦截标志:订单级拦截状态(空值归一化为 none,非 none 记 1,否则 0); + // - 打包标志:按运单维度判定(一单多号场景下主单号/子单号互不影响)—— + // 查询该运单号是否已有打包流水(wms_pack_task.waybill_code), + // 历史订单级流水(waybill_code 为空)兜底命中; + // 避免用订单级 pack_status(任一运单打包即非 none)导致「主单号打包后子单号被误判为已打包」。 + // 团购(isSandan=0)不返回该标志,不执行查询。 + const normalizedInterceptStatus = String(orderRow.intercept_status || '').trim() || 'none'; + const interceptFlag = normalizedInterceptStatus === 'none' ? 0 : 1; + let packFlag = 0; + if (isSandan === 1) { + try { + const waybillPackTask = await ctx.model.PackTask.findOne({ + where: { + warehouse_id: warehouseId, + order_id: orderId, + [ctx.app.Sequelize.Op.or]: [ + { waybill_code: waybillCode }, + { waybill_code: null }, + ], + }, + attributes: [ 'id' ], + raw: true, + }); + packFlag = waybillPackTask ? 1 : 0; + } catch (packTaskErr) { + // 打包流水查询失败时降级为订单级 pack_status 判定,避免阻断查询 + ctx.logger.warn('[Workbench._queryOrder] 查询运单打包流水失败 orderId=%d: %s', orderId, packTaskErr.message); + const normalizedPackStatus = String(orderRow.pack_status || '').trim() || 'none'; + packFlag = normalizedPackStatus === 'none' ? 0 : 1; + } + } + + // 步骤6.5:查询拣货人(通过波次关联拣货任务;散单无波次时为 null/空串) + let pickerId = null; + let pickerName = ''; + if (waveId && Number(waveId) > 0) { + try { + const pickerRows = await ctx.model.query( + ` + SELECT t.pick_user_id, t.pick_user_name + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + AND t.pick_user_id IS NOT NULL + ORDER BY t.create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: Number(waveId), warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const pickerRow = Array.isArray(pickerRows) && pickerRows.length > 0 ? pickerRows[0] : null; + if (pickerRow && pickerRow.pick_user_id != null) { + pickerId = Number(pickerRow.pick_user_id); + pickerName = String(pickerRow.pick_user_name || '').trim(); + } + } catch (pickerErr) { + ctx.logger.warn('[Workbench._queryOrder] 查询拣货人失败 waveId=%d: %s', waveId, pickerErr.message); + } + } + + const result = { + barcode: normalizedBarcode, + waybill_code: waybillCode, + isSandan, + store_remark: storeRemark, + express: { + logistics_name: expressRecord.logistics_name, + weighing_weight: expressRecord.weighing_weight, + package_material_name: expressRecord.package_material_name_snapshot || '', + }, + order: { + id: orderRow.id, + delivery_order_code: orderRow.delivery_order_code, + order_type: orderRow.order_type, + warehouse_id: orderRow.warehouse_id, + store_id: orderRow.store_id, + status: orderRow.status, + step: orderRow.step, + wave_id: orderRow.wave_id, + wave_no: orderRow.wave_no, + wave_scope: orderRow.wave_scope, + post_status: orderRow.post_status, + pick_status: orderRow.pick_status, + pack_status: orderRow.pack_status, + intercept_status: orderRow.intercept_status, + recheck_status: orderRow.recheck_status, + outbound_status: orderRow.outbound_status, + items_count: orderRow.items_count, + items_total: orderRow.items_total, + items_weight: orderRow.items_weight, + packages_weight: orderRow.packages_weight, + source_platform_code: orderRow.source_platform_code, + logistics_name: orderRow.logistics_name, + picker_id: pickerId, + picker_name: pickerName, + create_at: orderRow.create_at, + updated_at: orderRow.updated_at, + }, + items, + source_table: sourceTable, + }; + + // 散单附加拦截/打包 0/1 标志(原始状态字段仍保留在 order 中,不破坏既有调用方) + if (isSandan === 1) { + result.order.intercept_flag = interceptFlag; + result.order.pack_flag = packFlag; + } + + // 团购单附加波次总量信息 + if (isSandan === 0) { + result.batch = { + wave_id: waveId, + wave_no: orderRow.wave_no, + wave_type: waveType, + total_orders: totalBatchOrders, + }; + } + + // 步骤7:生成打包上下文 key 写入缓存(20 分钟有效),packOrder 凭 key 拉取参数。 + // 缓存内容为打包所需参数(订单号/波次号/运单号/归属仓库与工作台),由后端维护防篡改; + // 写入失败仅告警不阻断查询,key 仍返回(消费端读取失败会提示重新扫码)。 + const packCtxKey = this.generatePackCtxKey(); + const packCtx = { + warehouse_id: warehouseId, + workbench_id: validQueryWorkbenchId, + order_id: orderRow.id, + delivery_order_code: orderRow.delivery_order_code, + wave_no: orderRow.wave_no || '', + wave_scope: orderRow.wave_scope, + waybill_code: waybillCode, + is_sandan: isSandan, + }; + try { + await ctx.app.setCacheAsync( + this.getWorkbenchPackCtxCacheKey(packCtxKey), + packCtx, + WORKBENCH_PACK_CTX_CACHE_TTL_SECONDS + ); + result.key = packCtxKey; + } catch (cacheErr) { + ctx.logger.warn('[Workbench._queryOrder] 写入打包上下文缓存失败 key=%s: %s', packCtxKey, cacheErr.message); + } + + return result; + } + + /** + * 生成打包上下文 key(前缀 wpck + 随机段)。 + * @return {string} 打包上下文 key + */ + generatePackCtxKey() { + return WORKBENCH_PACK_CTX_KEY_PREFIX + this.generateRandomChars(WORKBENCH_BIND_CODE_CHARSET, 32); + } + + /** + * 打包上下文缓存 key。 + * @param {string} ctxKey 打包上下文 key(queryOrder 响应返回) + * @return {string} Redis 缓存 key + */ + getWorkbenchPackCtxCacheKey(ctxKey) { + return `${WORKBENCH_PACK_CTX_CACHE_PREFIX}${ctxKey}`; + } + + // ==================== 绑定码 / 登录码 / 令牌 ==================== + + /** + * 工作台绑定会话缓存 key(client_code 维度) + * @param {string} clientCode 客户端编码 + * @return {string} 缓存 key + */ + getWorkbenchBindClientCacheKey(clientCode) { + return `${WORKBENCH_BIND_CLIENT_CACHE_PREFIX}${clientCode}`; + } + + /** + * 工作台绑定码缓存 key(code 维度) + * @param {string} code 绑定码 + * @return {string} 缓存 key + */ + getWorkbenchBindCodeCacheKey(code) { + return `${WORKBENCH_BIND_CODE_CACHE_PREFIX}${code}`; + } + + /** + * 工作台 token 信息缓存 key + * @param {string} token 工作台令牌 + * @return {string} 缓存 key + */ + getWorkbenchTokenCacheKey(token) { + return `${WORKBENCH_TOKEN_CACHE_PREFIX}${token}`; + } + + /** + * 生成指定字符集与长度的随机串。 + * @param {string} charset 字符集 + * @param {number} length 长度 + * @return {string} 随机串 + */ + generateRandomChars(charset, length) { + let result = ''; + for (let i = 0; i < length; i++) { + result += charset[crypto.randomInt(0, charset.length)]; + } + return result; + } + + /** + * 生成工作台令牌(64 位十六进制)。 + * @return {string} token + */ + generateWorkbenchToken() { + return crypto.randomBytes(32).toString('hex'); + } + + /** + * 生成工作台登录码(前缀 wblc + 60 位十六进制随机段,总长度 64 位)。 + * @return {string} login_code + */ + generateWorkbenchLoginCode() { + return WORKBENCH_LOGIN_CODE_PREFIX + + crypto.randomBytes(WORKBENCH_LOGIN_CODE_RANDOM_HEX_LENGTH / 2).toString('hex'); + } + + /** + * 标准化绑定码 / client_code:去空格转大写,仅接受 6 位大写字母+数字。 + * @param {string} code 原始编码 + * @return {string|null} 标准化结果,非法返回 null + */ + normalizeWorkbenchBindCode(code) { + const normalized = typeof code === 'string' ? code.trim().toUpperCase() : ''; + if (!/^[A-Z0-9]{6}$/.test(normalized)) { + return null; + } + return normalized; + } + + /** + * 生成全局唯一的登录码(查库去重,最多 5 次尝试)。 + * @return {Promise} 唯一登录码 + */ + async generateUniqueWorkbenchLoginCode() { + const { ctx } = this; + for (let attempt = 0; attempt < 5; attempt++) { + const code = this.generateWorkbenchLoginCode(); + const exists = await ctx.model.Workbench.findOne({ + where: { login_code: code }, + attributes: [ 'id' ], + raw: true, + }); + if (!exists) { + return code; + } + } + throw new Error('生成登录码失败,请稍后重试'); + } + + /** + * 生成唯一的 client_code(缓存去重)。 + * @param {number} [maxAttempts=200] 最大尝试次数 + * @return {Promise} 唯一 client_code + */ + async createUniqueWorkbenchClientCode(maxAttempts = 200) { + for (let attempt = 0; attempt < maxAttempts; attempt++) { + const code = this.generateRandomChars(WORKBENCH_BIND_CODE_CHARSET, WORKBENCH_BIND_CODE_LENGTH); + const cacheKey = this.getWorkbenchBindClientCacheKey(code); + const exists = await this.app.getCacheAsync(cacheKey); + if (!exists) { + return code; + } + } + throw new Error('生成客户端编码失败,请稍后重试'); + } + + /** + * 生成唯一的绑定码(缓存去重)。 + * @param {number} [maxAttempts=200] 最大尝试次数 + * @return {Promise} 唯一绑定码 + */ + async createUniqueWorkbenchBindCode(maxAttempts = 200) { + for (let attempt = 0; attempt < maxAttempts; attempt++) { + const code = this.generateRandomChars(WORKBENCH_BIND_CODE_CHARSET, WORKBENCH_BIND_CODE_LENGTH); + const cacheKey = this.getWorkbenchBindCodeCacheKey(code); + const exists = await this.app.getCacheAsync(cacheKey); + if (!exists) { + return code; + } + } + throw new Error('生成绑定码失败,请稍后重试'); + } + + /** + * 构建绑定会话状态。 + * @param {string} clientCode 客户端编码 + * @param {string} code 绑定码 + * @param {Object} [extra={}] 附加字段 + * @return {Object} 会话状态 + */ + buildWorkbenchBindState(clientCode, code, extra = {}) { + return { + client_code: clientCode, + code, + status: 'pending', + workbench_id: null, + token: null, + updated_at: new Date().toISOString(), + expires_at: Date.now() + WORKBENCH_BIND_CACHE_TTL_SECONDS * 1000, + ...extra, + }; + } + + /** + * 按缓存剩余时间计算 TTL(秒)。 + * @param {number} expiresAt 过期时间戳(毫秒) + * @param {number} [fallbackTtl] 兜底 TTL + * @return {number} 剩余秒数(至少 1 秒) + */ + getWorkbenchBindRemainingSeconds(expiresAt, fallbackTtl = WORKBENCH_BIND_CACHE_TTL_SECONDS) { + const ts = Number(expiresAt); + if (!Number.isFinite(ts) || ts <= 0) { + return fallbackTtl; + } + return Math.max(1, Math.ceil((ts - Date.now()) / 1000)); + } + + /** + * 写入绑定会话状态(client_code 与 code 两个维度)。 + * @param {Object} state 会话状态 + * @param {number} [ttl] 过期秒数 + * @return {Promise} + */ + async setWorkbenchBindState(state, ttl = WORKBENCH_BIND_CACHE_TTL_SECONDS) { + if (!state || !state.client_code || !state.code) { + return; + } + await Promise.all([ + this.app.setCacheAsync(this.getWorkbenchBindClientCacheKey(state.client_code), state, ttl), + this.app.setCacheAsync(this.getWorkbenchBindCodeCacheKey(state.code), state, ttl), + ]); + } + + /** + * 创建新的绑定会话(新 client_code + 新绑定码)。 + * @return {Promise<{client_code: string, code: string, state: Object}>} 会话信息 + */ + async createWorkbenchBindSession() { + const clientCode = await this.createUniqueWorkbenchClientCode(); + const code = await this.createUniqueWorkbenchBindCode(); + const state = this.buildWorkbenchBindState(clientCode, code); + await this.setWorkbenchBindState(state, WORKBENCH_BIND_CACHE_TTL_SECONDS); + return { client_code: clientCode, code, state }; + } + + /** + * 为已有 client_code 重新生成绑定码并更新缓存(旧绑定码缓存同步失效)。 + * @param {string} clientCode 客户端编码 + * @param {Object|null} [previousState] 旧会话状态,含旧绑定码时删除旧 code 维度缓存 + * @return {Promise<{code: string, state: Object}>} 新绑定码与会话状态 + */ + async refreshWorkbenchBindCode(clientCode, previousState = null) { + const oldCode = previousState && typeof previousState.code === 'string' ? previousState.code : ''; + if (oldCode) { + try { + await this.app.delCacheAsync(this.getWorkbenchBindCodeCacheKey(oldCode)); + } catch (delErr) { + this.app.coreLogger.warn(`删除旧工作台绑定码缓存失败: ${delErr.message}`); + } + } + + const code = await this.createUniqueWorkbenchBindCode(); + const state = this.buildWorkbenchBindState(clientCode, code); + await this.setWorkbenchBindState(state, WORKBENCH_BIND_CACHE_TTL_SECONDS); + return { code, state }; + } + + /** + * 格式化绑定码接口返回数据。 + * @param {Object} state 会话状态 + * @return {Object} 对外数据 + */ + formatWorkbenchBindData(state) { + const expiresAt = Number(state.expires_at || 0); + return { + client_code: state.client_code || '', + code: state.code || '', + status: state.status || 'pending', + workbench_id: state.workbench_id || null, + token: state.token || null, + updated_at: state.updated_at || new Date().toISOString(), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + }; + } + + /** + * 等待绑定完成(轮询 client_code 维度缓存状态)。 + * @param {string} clientCode 客户端编码 + * @param {number} [timeoutMs] 超时毫秒 + * @return {Promise<{timed_out: boolean, state: Object|null}>} 等待结果 + */ + async waitForWorkbenchBindComplete(clientCode, timeoutMs = WORKBENCH_BIND_LONG_POLL_TIMEOUT_MS) { + const startedAt = Date.now(); + const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + while (Date.now() - startedAt < timeoutMs) { + await sleep(WORKBENCH_BIND_POLL_INTERVAL_MS); + let state = null; + try { + state = await this.app.getCacheAsync(this.getWorkbenchBindClientCacheKey(clientCode)); + } catch (error) { + this.app.coreLogger.warn(`读取工作台绑定缓存失败: ${error.message}`); + } + if (state && state.status === 'bound' && state.token) { + return { timed_out: false, state }; + } + } + return { timed_out: true, state: null }; + } + + /** + * 获取工作台绑定码(供 index.getWorkbenchBindCode)。 + * - 不传 client_code:创建新会话并返回 client_code + 绑定码; + * - 传 client_code 且缓存存在:等待绑定完成返回 token,超时则重新生成绑定码后返回; + * - 传 client_code 但缓存不存在:重新生成绑定码后返回。 + * @param {Object} [data={}] - { clientCode | client_code } + * @return {Promise} { success, code, data, message } + */ + async getWorkbenchBindCode(data = {}) { + const { app } = this; + try { + const rawClientCode = typeof data.clientCode === 'string' + ? data.clientCode + : (typeof data.client_code === 'string' ? data.client_code : ''); + const hasInputClientCode = !!rawClientCode && rawClientCode.trim().length > 0; + + if (!hasInputClientCode) { + const session = await this.createWorkbenchBindSession(); + return { + success: true, + code: 200, + data: this.formatWorkbenchBindData(session.state), + message: '工作台绑定码已生成', + }; + } + + const clientCode = this.normalizeWorkbenchBindCode(rawClientCode); + if (!clientCode) { + return { + success: false, + code: 0, + statusCode: 400, + data: null, + message: '无效的客户端编码格式', + }; + } + + const clientCacheKey = this.getWorkbenchBindClientCacheKey(clientCode); + let cachedState = null; + try { + cachedState = await app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取工作台绑定码缓存失败: ${cacheErr.message}`); + } + + // 传入 client_code 但缓存不存在:按新会话处理,重新生成绑定码后返回。 + if (!cachedState) { + const refreshed = await this.refreshWorkbenchBindCode(clientCode); + return { + success: true, + code: 200, + data: this.formatWorkbenchBindData(refreshed.state), + message: '绑定码缓存已过期,已重新生成', + }; + } + + // 绑定已完成:直接返回 token。 + if (cachedState.status === 'bound' && cachedState.token) { + return { + success: true, + code: 200, + data: this.formatWorkbenchBindData(cachedState), + message: '绑定成功', + }; + } + + // 长轮询等待绑定完成。 + const waitResult = await this.waitForWorkbenchBindComplete(clientCode, WORKBENCH_BIND_LONG_POLL_TIMEOUT_MS); + if (!waitResult.timed_out && waitResult.state && waitResult.state.status === 'bound' && waitResult.state.token) { + return { + success: true, + code: 200, + data: this.formatWorkbenchBindData(waitResult.state), + message: '绑定成功', + }; + } + + // 超时兜底:重读一次缓存,避免刷新瞬间恰好绑定完成而覆盖结果。 + try { + cachedState = await app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取工作台绑定码缓存失败: ${cacheErr.message}`); + } + if (cachedState && cachedState.status === 'bound' && cachedState.token) { + return { + success: true, + code: 200, + data: this.formatWorkbenchBindData(cachedState), + message: '绑定成功', + }; + } + + // 超时:重新生成绑定码后才返回数据(旧绑定码缓存同步失效)。 + const refreshed = await this.refreshWorkbenchBindCode(clientCode, cachedState); + return { + success: true, + code: 200, + data: this.formatWorkbenchBindData(refreshed.state), + message: '等待绑定超时,已刷新绑定码', + }; + } catch (error) { + app.coreLogger.error(`获取工作台绑定码失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取工作台绑定码失败,请稍后重试', + }; + } + } + + /** + * 格式化工作台主表字段(不含 token、login_code 敏感字段,不含成员列表)。 + * 成员列表由 buildWorkbenchTokenInfo 统一组装。 + * @param {Object} record 工作台记录(模型实例或普通对象) + * @return {Object} 工作台主表对外信息 + */ + formatWorkbenchTokenInfo(record) { + const plain = record && typeof record.get === 'function' + ? record.get({ plain: true }) + : (record || {}); + return { + id: plain.id, + warehouse_id: plain.warehouse_id, + name: plain.name, + status: plain.status, + type: plain.type, + remark: plain.remark, + device_ids: plain.device_ids, + created_at: plain.created_at, + updated_at: plain.updated_at, + }; + } + + /** + * 查询工作台未软删除的成员列表(轻量字段,供缓存组装与接口返回)。 + * @param {number} workbenchId 工作台 ID + * @return {Promise>} 成员列表 + */ + async listWorkbenchMembers(workbenchId) { + const { ctx } = this; + const rows = await ctx.model.WorkbenchMember.findAll({ + where: { workbench_id: workbenchId }, + attributes: [ 'id', 'user_id', 'user_name' ], + order: [[ 'id', 'ASC' ]], + }); + return rows.map(row => ({ + id: row.id, + user_id: row.user_id, + user_name: row.user_name, + })); + } + + /** + * 查询工作台当前未结束的打包任务列表(status < 2,按 id 倒序)。 + * 判定口径与 _packOrder/_finishPack 保持一致:0=待处理、1=打包中均视为未结束。 + * @param {number} workbenchId 工作台 ID + * @param {number} warehouseId 仓库 ID + * @return {Promise>} 未结束打包任务列表(raw 行) + */ + async listCurrentPackTasks(workbenchId, warehouseId) { + const { ctx } = this; + return await ctx.model.PackTask.findAll({ + where: { + workbench_id: workbenchId, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.lt]: 2 }, + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + } + + /** + * 组装工作台当前正在打包的波次与订单信息(供 workbench.getWorkbenchInfo 返回)。 + * - current_wave:最新一条团购(pack_mode=2)未结束任务对应的波次信息,无则为空对象; + * - current_orders:全部未结束打包任务列表(含发货单号、波次号、任务状态、商品件数/SKU 数等): + * 散单任务(pack_mode=1)items 为单笔订单商品明细(含条码/图片/包装要求/是否需要复核); + * 团购任务(pack_mode=2)items 为波次商品 SKU 聚合汇总(波次内全部未拦截订单按 SKU 聚合计划数量,15s 短缓存兜底, + * 元素另附 is_wave_summary=true),供工作台退出/刷新后恢复任务上下文。 + * 任一环节异常均降级为空对象/空数组/空明细,不影响主信息返回。 + * @param {number} workbenchId 工作台 ID + * @param {number} warehouseId 仓库 ID + * @return {Promise<{current_wave: Object, current_orders: Array}>} 当前打包中波次与订单 + */ + async buildCurrentPackingInfo(workbenchId, warehouseId) { + const { ctx } = this; + try { + if (!Number.isInteger(workbenchId) || workbenchId <= 0) { + return { current_wave: {}, current_orders: [] }; + } + const tasks = await this.listCurrentPackTasks(workbenchId, warehouseId); + if (!tasks || tasks.length === 0) { + return { current_wave: {}, current_orders: [] }; + } + + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let currentWave = {}; + const currentOrders = []; + for (const task of tasks) { + // 按订单ID补齐发货单号与订单关键字段(current → dispatch 分表遍历,与 _packOrder 口径一致) + let deliveryOrderCode = ''; + let orderRow = null; + let sourceTable = ''; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const row = await model.findOne({ + where: { id: Number(task.order_id || 0), warehouse_id: warehouseId }, + attributes: [ 'delivery_order_code', 'order_type', 'store_id', 'items_count', 'items_total' ], + raw: true, + }); + if (row) { + deliveryOrderCode = row.delivery_order_code || ''; + orderRow = row; + sourceTable = entry.label; + break; + } + } catch (_err) { continue; } + } + + const isGroup = Number(task.pack_mode) === 2; + + // 散单任务补充单笔订单商品明细;团购任务补充波次商品 SKU 聚合汇总(15s 短缓存兜底), + // 均供工作台退出/刷新后恢复任务上下文(异常降级为空数组) + let items = []; + if (!isGroup && Number(task.order_id || 0) > 0 && sourceTable) { + try { + items = await this._fetchOrderItemsDetail(Number(task.order_id), warehouseId, sourceTable); + } catch (itemsErr) { + ctx.logger.warn('[Workbench.buildCurrentPackingInfo] 查询散单商品明细失败 orderId=%d: %s', + Number(task.order_id), itemsErr.message); + } + } else if (isGroup && Number(task.wave_id || 0) > 0) { + try { + items = await this._fetchWaveItemsSummary(warehouseId, Number(task.wave_id)); + } catch (itemsErr) { + ctx.logger.warn('[Workbench.buildCurrentPackingInfo] 查询团购波次商品汇总失败 waveId=%d: %s', + Number(task.wave_id), itemsErr.message); + } + } + + // 散单任务补齐货主备注与运单信息(物流公司/称重重量/包材名称,与 workbench.queryOrder 的 + // store_remark/express 口径一致,供前端填充展示;团购为波次维度不适用,保持空)。 + let storeRemark = ''; + let express = null; + if (!isGroup && Number(task.order_id || 0) > 0) { + const orderId = Number(task.order_id); + const storeId = Number((orderRow && orderRow.store_id) || 0); + const [ swRow, expressRow ] = await Promise.all([ + storeId > 0 + ? ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: [ 'store_remask' ], + raw: true, + }).catch(swErr => { + ctx.logger.warn('[Workbench.buildCurrentPackingInfo] 查询货主备注失败 orderId=%d: %s', orderId, swErr.message); + return null; + }) + : Promise.resolve(null), + (async () => { + const expressWhere = { + order_id: orderId, + warehouse_id: warehouseId, + status: 1, + }; + if (task.waybill_code) { + expressWhere.waybill_code = task.waybill_code; + } + return await ctx.model.OrderExpress.findOne({ + where: expressWhere, + attributes: [ 'waybill_code', 'logistics_name', 'weighing_weight', 'package_material_name_snapshot' ], + raw: true, + }); + })().catch(expressErr => { + ctx.logger.warn('[Workbench.buildCurrentPackingInfo] 查询运单信息失败 orderId=%d: %s', orderId, expressErr.message); + return null; + }), + ]); + storeRemark = (swRow && swRow.store_remask) ? String(swRow.store_remask).trim() : ''; + if (expressRow) { + express = { + waybill_code: expressRow.waybill_code || '', + logistics_name: expressRow.logistics_name || '', + weighing_weight: expressRow.weighing_weight, + package_material_name: expressRow.package_material_name_snapshot || '', + }; + } + } + + currentOrders.push({ + task_id: task.id, + order_id: task.order_id, + delivery_order_code: deliveryOrderCode, + wave_id: Number(task.wave_id || 0), + wave_no: task.wave_no || '', + pack_mode: Number(task.pack_mode || 1), + status: Number(task.status || 0), + pack_quantity: Number(task.pack_quantity || 0), + item_quantity: Number(task.item_quantity || 0), + sku_count: Number(task.sku_count || 0), + waybill_code: task.waybill_code || '', + order_type: (orderRow && orderRow.order_type) || '', + store_id: Number((orderRow && orderRow.store_id) || 0), + store_remark: storeRemark, + express, + items_count: Number((orderRow && orderRow.items_count) || 0), + items_total: Number((orderRow && orderRow.items_total) || 0), + items, + operator_text: task.operator_text || '', + start_time: task.start_time, + }); + + // 团购任务(pack_mode=2)作为当前波次,只取最新一条未结束任务 + if (isGroup && !currentWave.task_id && Number(task.wave_id) > 0) { + // 订单数与商品总件数并行统计(各自带 15s 短 TTL 缓存,缓存命中后几乎零开销) + const [ orderCount, itemsTotal ] = await Promise.all([ + this._countWaveOrdersCached(warehouseId, Number(task.wave_id)), + this._sumWaveItemsTotalCached(warehouseId, Number(task.wave_id)), + ]); + currentWave = { + task_id: task.id, + wave_id: Number(task.wave_id), + wave_no: task.wave_no || '', + status: Number(task.status || 0), + order_count: orderCount, + items_total: itemsTotal, + operator_text: task.operator_text || '', + start_time: task.start_time, + }; + } + } + + return { current_wave: currentWave, current_orders: currentOrders }; + } catch (err) { + ctx.logger.warn('[Workbench.buildCurrentPackingInfo] 查询当前打包信息失败,降级为空: %s', err.message); + return { current_wave: {}, current_orders: [] }; + } + } + + /** + * 按工作台 ID 失效 token 信息缓存(workbench:token:{token})。 + * packOrder/finishPack 打包状态变更后调用,保证 getWorkbenchInfo 尽快返回最新打包中信息; + * 工作台未绑定 token 或缓存删除失败时静默降级,不影响主流程。 + * @param {number} workbenchId 工作台 ID + * @return {Promise} + */ + async invalidateWorkbenchTokenCacheByWorkbenchId(workbenchId) { + const { ctx, app } = this; + if (!Number.isInteger(workbenchId) || workbenchId <= 0) return; + try { + const wb = await ctx.model.Workbench.findByPk(workbenchId, { + attributes: [ 'token' ], + raw: true, + }); + const token = wb && typeof wb.token === 'string' ? wb.token : ''; + if (token) { + await app.delCacheAsync(this.getWorkbenchTokenCacheKey(token)); + ctx.logger.info('[Workbench.invalidateWorkbenchTokenCacheByWorkbenchId] 打包状态变更,已失效工作台 token 缓存 workbenchId=%d', workbenchId); + } + } catch (err) { + ctx.logger.warn('[Workbench.invalidateWorkbenchTokenCacheByWorkbenchId] 失效工作台 token 缓存失败 workbenchId=%d err=%s', workbenchId, err.message); + } + } + + /** + * 组装工作台 token 缓存/接口完整信息:主表字段 + 未软删除的成员列表 + 当前正在打包的波次/订单。 + * 成员查询失败时降级为空数组,打包信息查询失败时降级为空对象/空数组,均不影响主表信息返回。 + * @param {Object} record 工作台记录(模型实例或普通对象) + * @return {Promise} 对外信息(含 members 成员列表、current_wave 当前波次、current_orders 当前打包订单) + */ + async buildWorkbenchTokenInfo(record) { + const { app } = this; + const info = this.formatWorkbenchTokenInfo(record); + let members = []; + try { + members = await this.listWorkbenchMembers(info.id); + } catch (memberErr) { + app.coreLogger.warn(`查询工作台成员失败: ${memberErr.message}`); + } + // 当前正在打包的波次与订单信息(内部已做异常降级,不抛错) + const packing = await this.buildCurrentPackingInfo(info.id, Number(info.warehouse_id || 0)); + return { + ...info, + members, + ...packing, + }; + } + + /** + * 绑定工作台:校验缓存绑定码 + 工作台归属后写入随机 token(供 workbench.bind)。 + * - 成功后在 wms_workbench.token 写入随机生成的 token; + * - 写入 token 时同步更新 token_updated_at,供 token 超期强制下线定时任务判定; + * - 若工作台已有 token,删除旧 workbench:token:{token} 缓存; + * - 写入新 token 信息缓存(含成员列表 members),供 workbench.getWorkbenchInfo 返回; + * - 更新绑定会话状态为 bound,供 index.getWorkbenchBindCode 长轮询返回 token。 + * @param {Object} data - { code, id } + * @return {Promise} { success, code, data, message } + */ + async bindWorkbench(data = {}) { + const { ctx, app } = this; + try { + const warehouseId = ctx.user && ctx.user.store_id; + const rawCode = typeof data.code === 'string' ? data.code : ''; + const code = this.normalizeWorkbenchBindCode(rawCode); + const workbenchId = Number(data.id ?? data.workbench_id ?? data.workbenchId); + + if (!code) { + return { + success: false, + code: 0, + statusCode: 400, + data: null, + message: '绑定码格式无效', + }; + } + if (!Number.isInteger(workbenchId) || workbenchId <= 0) { + return { + success: false, + code: 0, + statusCode: 400, + data: null, + message: '工作台ID不能为空或无效', + }; + } + + const codeCacheKey = this.getWorkbenchBindCodeCacheKey(code); + let codeState = null; + try { + codeState = await app.getCacheAsync(codeCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取工作台绑定码缓存失败: ${cacheErr.message}`); + } + if (!codeState || codeState.status === 'bound') { + return { + success: false, + code: 0, + statusCode: 400, + data: null, + message: '绑定码不存在或已过期', + }; + } + + const record = await ctx.model.Workbench.findOne({ + where: { id: workbenchId, warehouse_id: warehouseId }, + }); + if (!record) { + return { + success: false, + code: 0, + statusCode: 404, + data: null, + message: '工作台不存在或无权操作', + }; + } + + const newToken = this.generateWorkbenchToken(); + const oldToken = typeof record.token === 'string' ? record.token : ''; + // 若工作台已有 token,删除旧 token 缓存。 + if (oldToken && oldToken !== newToken) { + await app.delCacheAsync(this.getWorkbenchTokenCacheKey(oldToken)); + } + + await record.update({ token: newToken, token_updated_at: new Date() }); + + // 写入 token → 工作台信息缓存(含成员列表)。 + await app.setCacheAsync( + this.getWorkbenchTokenCacheKey(newToken), + await this.buildWorkbenchTokenInfo(record), + WORKBENCH_TOKEN_CACHE_TTL_SECONDS + ); + + // 更新绑定会话状态,供长轮询侧返回 token。 + const remainingTtl = this.getWorkbenchBindRemainingSeconds(codeState.expires_at, WORKBENCH_BIND_CACHE_TTL_SECONDS); + const boundState = { + ...codeState, + status: 'bound', + workbench_id: record.id, + token: newToken, + updated_at: new Date().toISOString(), + }; + await this.setWorkbenchBindState(boundState, remainingTtl); + + return { + success: true, + code: 200, + data: { + id: record.id, + workbench_id: record.id, + token: newToken, + }, + message: '绑定成功', + }; + } catch (error) { + app.coreLogger.error(`工作台绑定失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '工作台绑定失败,请稍后重试', + }; + } + } + + /** + * 通过 token 获取工作台信息(供 workbench.getWorkbenchInfo)。 + * 统一走 resolveWorkbenchContext 校验:无 token 返回失败(401)、token 无效返回失败(403); + * 缓存优先(workbench:token:{token}),未命中查库并回填缓存; + * 缓存与返回数据均包含未软删除成员列表 members 与当前打包信息。 + * @param {Object} [data={}] - { token } + * @return {Promise} { success, code, data, message, statusCode } + */ + async getWorkbenchInfoByToken(data = {}) { + const { app } = this; + try { + const rawToken = typeof data.token === 'string' ? data.token.trim() : ''; + + // 统一 token 校验(无 token 401、无效 403),解析成功后写入 ctx 备用 + const resolved = await this.resolveWorkbenchContext(rawToken); + if (!resolved.success) return resolved; + + // 缓存优先:命中直接返回(含 members 与当前打包信息),未命中基于记录组装并回填 + const info = resolved.cached || await this.buildWorkbenchTokenInfo(resolved.data); + if (!resolved.cached && info) { + await app.setCacheAsync( + this.getWorkbenchTokenCacheKey(rawToken), + info, + WORKBENCH_TOKEN_CACHE_TTL_SECONDS + ); + } + return { success: true, code: 200, data: info, message: 'ok' }; + } catch (error) { + app.coreLogger.error(`通过 token 获取工作台信息失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取工作台信息失败,请稍后重试', + }; + } + } + + /** + * 统计数值保留 2 位小数(四舍五入)。 + * @param {number} value 原始数值 + * @return {number} 保留 2 位小数后的数值 + */ + _round2(value) { + return Math.round(Number(value) * 100) / 100; + } + + /** + * 格式化时间为 'YYYY-MM-DD HH:mm:ss'(本地时间,供接口返回展示)。 + * @param {Date} date 日期对象 + * @return {string} 格式化后的时间字符串 + */ + _formatPackCountTime(date) { + const pad = n => String(n).padStart(2, '0'); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; + } + + /** + * 计算打包统计时间窗口(班次口径): + * 本地时间当日 08:00 至次日 08:00(左闭右开); + * 当前本地时间早于 08:00 时,窗口为昨日 08:00 至今日 08:00。 + * @return {{startTime: Date, endTime: Date}} 窗口起止时间 + */ + buildWorkbenchPackCountTimeRange() { + const now = new Date(); + let startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0); + if (now.getTime() < startTime.getTime()) { + startTime = new Date(startTime.getTime() - 86400000); + } + return { startTime, endTime: new Date(startTime.getTime() + 86400000) }; + } + + /** + * 通过 token 获取当前工作台的班次打包统计(供 workbench.getWorkbenchCount)。 + * + * 统一走 resolveWorkbenchContext 校验:无 token 返回 401、token 无效返回 403; + * 仓库与工作台均由 token 解析注入,禁止前端传值。 + * + * 统计窗口:本地时间当日 08:00 → 次日 08:00;当前时间早于 08:00 时为昨日 08:00 → 今日 08:00。 + * - 个人工作台(type=personal):统计「涉及本人」的打包数据(本人 = 工作台成员 user_id, + * 范围 = 本工作台产生的任务 ∪ 本人作为打包人参与的任务),返回: + * group_wave_count 团购波次数量(pack_mode=2 且 wave_id>0 去重)、 + * group_order_count 团购订单数量(团购任务 pack_quantity 求和)、 + * single_order_count 散单数量(pack_mode=1 任务数)、 + * group_single_ratio 团散(团购波次数/散单数,保留 2 位小数,散单为 0 时 null)、 + * avg_piece_count 均件数(本人打包任务按 订单数量/人数 折算后求和,保留 2 位小数: + * 本人作为打包人参与的任务按任务实际打包人数均分,本工作台单人任务整单计入)。 + * - 团体工作台(type=group):统计「涉及本工作台」的打包数据,返回: + * group_wave_count 团购波次数量、group_order_count 团购订单数量(团购任务 pack_quantity 快照求和)、 + * single_order_count 散单数量。 + * + * 只查 wms_pack_task / wms_pack_task_packer,全部走现有/配套索引 + * (idx_warehouse_create_time / idx_workbench_create_time / uix_pack_task_account), + * 不做订单分表实时统计,避免慢 SQL。 + * + * @param {Object} [data={}] - { token } + * @return {Promise} { success, code, data, message, statusCode } + */ + async getWorkbenchCountByToken(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + try { + const rawToken = typeof data.token === 'string' ? data.token.trim() : ''; + + // 统一 token 校验(无 token 401、无效 403),解析成功后写入 ctx 备用 + const resolved = await this.resolveWorkbenchContext(rawToken); + if (!resolved.success) return resolved; + + const workbench = resolved.data; + const workbenchId = Number(workbench.id); + const warehouseId = Number(workbench.warehouse_id || 0); + const isGroup = workbench.type === 'group'; + const { startTime, endTime } = this.buildWorkbenchPackCountTimeRange(); + + // 窗口内打包任务:团体工作台只取本工作台(走 idx_workbench_create_time), + // 个人工作台取本仓库窗口内全部任务(走 idx_warehouse_create_time)再按人过滤。 + const taskWhere = { + warehouse_id: warehouseId, + create_time: { [Op.gte]: startTime, [Op.lt]: endTime }, + }; + if (isGroup) { + taskWhere.workbench_id = workbenchId; + } + const tasks = await ctx.model.PackTask.findAll({ + where: taskWhere, + attributes: [ 'id', 'wave_id', 'pack_mode', 'pack_quantity', 'workbench_id' ], + raw: true, + }); + + // 团体工作台:按本工作台任务直接统计 + if (isGroup) { + const groupTasks = tasks.filter(task => Number(task.pack_mode) === 2); + const singleTasks = tasks.filter(task => Number(task.pack_mode) === 1); + const waveIdSet = new Set(groupTasks.map(task => Number(task.wave_id)).filter(id => id > 0)); + const groupOrderCount = groupTasks.reduce((sum, task) => sum + (Number(task.pack_quantity) || 0), 0); + + return { + success: true, + code: 200, + data: { + workbench_id: workbenchId, + workbench_type: workbench.type, + time_range: { + start_time: this._formatPackCountTime(startTime), + end_time: this._formatPackCountTime(endTime), + }, + group_wave_count: waveIdSet.size, + group_order_count: groupOrderCount, + single_order_count: singleTasks.length, + }, + message: 'ok', + }; + } + + // 个人工作台:本人 = 工作台成员 user_id(个人工作台通常只有一名成员) + let personUserId = null; + try { + const members = await this.listWorkbenchMembers(workbenchId); + const userIds = members + .map(member => Number(member.user_id)) + .filter(id => Number.isInteger(id) && id > 0); + personUserId = userIds.length > 0 ? userIds[0] : null; + } catch (memberErr) { + ctx.logger.warn('[Workbench.getWorkbenchCount] 查询工作台成员失败,按本工作台任务统计: %s', memberErr.message); + } + + // 本工作台产生的任务 + const workbenchTaskIds = new Set( + tasks.filter(task => Number(task.workbench_id) === workbenchId).map(task => Number(task.id)) + ); + + // 本人作为打包人参与的任务(分批 IN 查询,避免单次 IN 列表过长) + const participatedTaskIds = new Set(); + const taskIds = tasks.map(task => Number(task.id)); + if (personUserId !== null && taskIds.length > 0) { + const batchSize = 500; + for (let offset = 0; offset < taskIds.length; offset += batchSize) { + const idChunk = taskIds.slice(offset, offset + batchSize); + const packerRows = await ctx.model.PackTaskPacker.findAll({ + where: { pack_task_id: { [Op.in]: idChunk }, account_id: personUserId }, + attributes: [ 'pack_task_id' ], + raw: true, + }); + for (const row of packerRows) { + participatedTaskIds.add(Number(row.pack_task_id)); + } + } + } + + // 统计对象任务集合:本工作台任务 ∪ 本人作为打包人参与的任务 + const personalTaskIdSet = new Set([ ...workbenchTaskIds, ...participatedTaskIds ]); + + // 统计各任务的打包人数(供均件数折算使用) + const packerCountMap = new Map(); + if (personalTaskIdSet.size > 0) { + const personalIds = [ ...personalTaskIdSet ]; + const batchSize = 500; + for (let offset = 0; offset < personalIds.length; offset += batchSize) { + const idChunk = personalIds.slice(offset, offset + batchSize); + const packerRows = await ctx.model.PackTaskPacker.findAll({ + where: { pack_task_id: { [Op.in]: idChunk } }, + attributes: [ 'pack_task_id' ], + raw: true, + }); + for (const row of packerRows) { + const key = Number(row.pack_task_id); + packerCountMap.set(key, (packerCountMap.get(key) || 0) + 1); + } + } + } + + const personalTasks = tasks.filter(task => personalTaskIdSet.has(Number(task.id))); + const groupTasks = personalTasks.filter(task => Number(task.pack_mode) === 2); + const singleTasks = personalTasks.filter(task => Number(task.pack_mode) === 1); + const waveIdSet = new Set(groupTasks.map(task => Number(task.wave_id)).filter(id => id > 0)); + const groupOrderCount = groupTasks.reduce((sum, task) => sum + (Number(task.pack_quantity) || 0), 0); + + // 均件数:本人打包的每个任务按 订单数量/人数 折算后求和(保留 2 位小数): + // 本人作为打包人参与的任务按任务实际打包人数均分(缺省 1); + // 本工作台任务未记录到本人时视为单人打包(整单计入本人)。 + let avgPieceCount = 0; + for (const task of personalTasks) { + const taskId = Number(task.id); + const orderCount = Number(task.pack_mode) === 2 ? (Number(task.pack_quantity) || 0) : 1; + if (orderCount <= 0) continue; + if (participatedTaskIds.has(taskId)) { + const packerCount = packerCountMap.get(taskId) || 1; + avgPieceCount += orderCount / packerCount; + } else if (workbenchTaskIds.has(taskId)) { + avgPieceCount += orderCount; + } + } + + const singleOrderCount = singleTasks.length; + const groupWaveCount = waveIdSet.size; + + return { + success: true, + code: 200, + data: { + workbench_id: workbenchId, + workbench_type: workbench.type, + time_range: { + start_time: this._formatPackCountTime(startTime), + end_time: this._formatPackCountTime(endTime), + }, + group_wave_count: groupWaveCount, + group_order_count: groupOrderCount, + single_order_count: singleOrderCount, + group_single_ratio: singleOrderCount > 0 ? this._round2(groupWaveCount / singleOrderCount) : null, + avg_piece_count: this._round2(avgPieceCount), + }, + message: 'ok', + }; + } catch (error) { + app.coreLogger.error(`获取工作台打包统计失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取工作台打包统计失败,请稍后重试', + }; + } + } + + /** + * 通过 login_code 获取工作台 token(供 index.LoginWorkbenchByCode)。 + * 按 wms_workbench.login_code 查询;查无工作台返回失败(403); + * 工作台尚无 token 时自动生成并持久化(等价于补绑定), + * 生成并持久化 token 时同步更新 token_updated_at,供 token 超期强制下线定时任务判定。 + * 回填的 token 信息缓存包含成员列表 members。 + * @param {Object} [data={}] - { loginCode | login_code } + * @return {Promise} { success, code, data, message } + */ + async loginWorkbenchByCode(data = {}) { + const { ctx, app } = this; + try { + const rawLoginCode = typeof data.loginCode === 'string' + ? data.loginCode.trim() + : (typeof data.login_code === 'string' ? data.login_code.trim() : ''); + if (!rawLoginCode) { + return { + success: false, + code: 0, + statusCode: 400, + data: null, + message: 'login_code 不能为空', + }; + } + + const record = await ctx.model.Workbench.findOne({ + where: { login_code: rawLoginCode }, + }); + if (!record) { + return { + success: false, + code: 0, + statusCode: 403, + data: null, + message: '工作台不存在或登录码无效', + }; + } + + let token = typeof record.token === 'string' ? record.token : ''; + if (!token) { + token = this.generateWorkbenchToken(); + await record.update({ token, token_updated_at: new Date() }); + } + + await app.setCacheAsync( + this.getWorkbenchTokenCacheKey(token), + await this.buildWorkbenchTokenInfo(record), + WORKBENCH_TOKEN_CACHE_TTL_SECONDS + ); + + return { + success: true, + code: 200, + data: { + id: record.id, + workbench_id: record.id, + name: record.name, + token, + }, + message: '登录成功', + }; + } catch (error) { + app.coreLogger.error(`通过登录码获取工作台 token 失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '工作台登录失败,请稍后重试', + }; + } + } + + /** + * 重置工作台登录码(供 workbench.resetLoginCode)。 + * 重置登录码的同时重置工作台 token: + * - 生成新 login_code 与新 token,一并持久化到 wms_workbench(旧 login_code 随即失效), + * 持久化新 token 时同步更新 token_updated_at,供 token 超期强制下线定时任务判定; + * - 删除旧 workbench:token:{旧token} 缓存,使旧 token 随即失效; + * - 立即回填新 token 信息缓存(含成员列表),设备端拿到新 token 即可继续工作, + * 回填口径与 bindWorkbench / loginWorkbenchByCode 保持一致。 + * @param {number} id - 工作台 ID + * @return {Promise<{id: number, login_code: string, token: string}>} 新登录码与新 token + */ + async resetLoginCode(id) { + const { ctx, app } = this; + const warehouseId = ctx.user.store_id; + const workbenchId = Number(id); + + if (!Number.isInteger(workbenchId) || workbenchId <= 0) { + throw new Error('工作台ID不能为空或无效'); + } + + const record = await ctx.model.Workbench.findOne({ + where: { id: workbenchId, warehouse_id: warehouseId }, + }); + if (!record) { + throw new Error('工作台不存在或无权操作'); + } + + const loginCode = await this.generateUniqueWorkbenchLoginCode(); + const newToken = this.generateWorkbenchToken(); + const oldToken = typeof record.token === 'string' ? record.token : ''; + // 先删除旧 token 缓存(旧 token 随即失效),再持久化新 login_code 与新 token + if (oldToken && oldToken !== newToken) { + await app.delCacheAsync(this.getWorkbenchTokenCacheKey(oldToken)); + } + await record.update({ login_code: loginCode, token: newToken, token_updated_at: new Date() }); + + // 立即回填新 token 信息缓存(含成员列表),避免设备端首次请求额外查库 + await app.setCacheAsync( + this.getWorkbenchTokenCacheKey(newToken), + await this.buildWorkbenchTokenInfo(record), + WORKBENCH_TOKEN_CACHE_TTL_SECONDS + ); + + return { id: record.id, login_code: loginCode, token: newToken }; + } + + /** + * 清理 token 超期未更新的工作台,强制其下线(供 workbench_token_expire 定时任务调用)。 + * 判定口径:token 非空(非 NULL/非空串)且 token_updated_at 早于过期时间点; + * 按 id 升序分批处理(批大小 batchSize),单条失败不影响整批: + * - 置 token=NULL、token_updated_at=NULL(设备下次调用 token 校验返回 403,需用登录码重新登录); + * - 删除对应 workbench:token:{旧token} 缓存,使旧 token 随即失效; + * - 更新时以「id + 旧 token」为条件,避免误清并发重绑产生的新 token。 + * @param {Object} [data={}] - { expiredBefore, batchSize } + * @param {Date} [data.expiredBefore] 过期时间点(token_updated_at 早于该时间视为过期) + * @param {number} [data.batchSize=50] 每批处理条数 + * @return {Promise<{total_scanned: number, total_cleared: number, total_failed: number}>} 本轮清理汇总 + */ + async clearExpiredWorkbenchTokens(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const expiredBefore = data.expiredBefore instanceof Date ? data.expiredBefore : new Date(); + const batchSize = Math.min(200, Math.max(1, parseInt(data.batchSize) || 50)); + const summary = { total_scanned: 0, total_cleared: 0, total_failed: 0 }; + + let lastId = 0; + // 按 id 升序分批拉取过期工作台,直至无更多记录 + for (;;) { + const rows = await ctx.model.Workbench.findAll({ + where: { + id: { [Op.gt]: lastId }, + [Op.and]: [ + { token: { [Op.ne]: null } }, + { token: { [Op.ne]: '' } }, + ], + token_updated_at: { [Op.lt]: expiredBefore }, + }, + attributes: [ 'id', 'token' ], + order: [[ 'id', 'ASC' ]], + limit: batchSize, + raw: true, + }); + if (!rows || rows.length === 0) break; + lastId = Number(rows[rows.length - 1].id); + summary.total_scanned += rows.length; + + for (const row of rows) { + const oldToken = typeof row.token === 'string' ? row.token : ''; + try { + const affected = await ctx.model.Workbench.update( + { token: null, token_updated_at: null }, + { where: { id: row.id, token: oldToken } } + ); + if (!affected || !affected[0]) { + ctx.logger.warn(`[workbench-token-expire] workbenchId=${row.id} 更新未生效(token 可能已被并发变更),跳过`); + continue; + } + if (oldToken) { + await app.delCacheAsync(this.getWorkbenchTokenCacheKey(oldToken)); + } + summary.total_cleared += 1; + ctx.logger.info(`[workbench-token-expire] workbenchId=${row.id} 已清除过期 token,设备下次请求将返回 403 并需重新登录`); + } catch (error) { + summary.total_failed += 1; + ctx.logger.error(`[workbench-token-expire] workbenchId=${row.id} 清除过期 token 失败: ${error.message}`); + } + } + } + + return summary; + } + + // ==================== 工作台成员(用户登录副表) ==================== + + /** + * 解析工作台上下文(公共 token 校验入口,供免登录免鉴权的 token 自校验接口复用)。 + * + * 校验口径: + * - token 为空/缺失 → 失败(statusCode=401),对外统一返回 401; + * - token 无效/工作台不存在(含软删除)→ 失败(statusCode=403),保持既有口径不变。 + * + * 解析成功后写入 ctx 备用(供后续业务方法按仓库限定查询/写入,禁止跨仓库操作): + * - ctx.workbenchToken:trim 后的原始 token; + * - ctx.workbenchId:工作台 ID(number); + * - ctx.workbenchWarehouseId:工作台所属仓库 ID(number)。 + * + * 缓存命中与未命中统一走同一出口:缓存命中时仍回库确认工作台存在(防软删除后缓存残留), + * 未命中时查库并回填 token 信息缓存(含成员列表 members)。 + * + * @param {string} token 工作台令牌(可为空字符串/undefined) + * @return {Promise} { success, code, data, cached, message, statusCode } + * success=true 时 data 为工作台记录(模型实例)、cached 为 token 信息缓存(未命中时为回填信息); + * success=false 时 statusCode 为 401/403 + */ + async resolveWorkbenchContext(token) { + const { ctx, app } = this; + const rawToken = typeof token === 'string' ? token.trim() : ''; + if (!rawToken) { + return { + success: false, + code: 0, + statusCode: 401, + data: null, + message: '工作台 token 不能为空', + }; + } + + const tokenCacheKey = this.getWorkbenchTokenCacheKey(rawToken); + let cached = null; + try { + cached = await app.getCacheAsync(tokenCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取工作台 token 缓存失败: ${cacheErr.message}`); + } + + let record = null; + if (cached && cached.id) { + record = await ctx.model.Workbench.findOne({ + where: { id: cached.id }, + }); + } + if (!record) { + record = await ctx.model.Workbench.findOne({ + where: { token: rawToken }, + }); + if (record) { + // 缓存未命中:查库成功后回填 token 信息缓存(含成员列表 members) + cached = await this.buildWorkbenchTokenInfo(record); + await app.setCacheAsync(tokenCacheKey, cached, WORKBENCH_TOKEN_CACHE_TTL_SECONDS); + } + } + + if (!record) { + return { + success: false, + code: 0, + statusCode: 403, + data: null, + message: '工作台不存在或 token 无效', + }; + } + + // 写入上下文备用:后续业务方法按仓库限定查询,禁止跨仓库操作 + ctx.workbenchToken = rawToken; + ctx.workbenchId = Number(record.id); + ctx.workbenchWarehouseId = Number(record.warehouse_id || 0); + + return { + success: true, + code: 200, + data: record, + cached, + message: 'ok', + }; + } + + /** + * 通过 token 解析工作台记录(缓存优先,未命中查库并回填缓存)。 + * 基于 resolveWorkbenchContext 实现:无 token 时返回 null(统一 401 口径由调用方处理)。 + * 回填的 token 信息缓存包含成员列表 members。 + * @param {string} token 工作台令牌 + * @return {Promise} 工作台记录(模型实例),未命中返回 null + */ + async resolveWorkbenchByToken(token) { + const resolved = await this.resolveWorkbenchContext(token); + return resolved && resolved.success ? resolved.data : null; + } + + /** + * 工作台打包上报(供 workbench.packOrder,免登录免鉴权,以工作台 token 鉴权)。 + * 推荐 key 模式:前端先经 workbench.queryOrder 扫码拿到 key(20 分钟有效), + * 打包只传 token + key,订单信息一律由后端从缓存拉取(防篡改); + * 不传 key 时旧参数模式兼容(过渡期保留,后续版本将移除)。 + * 仓库与工作台均由 token 解析注入,禁止前端传值。 + * 打包状态变更后由 _packOrder 内部主动失效 token 缓存,保证 getWorkbenchInfo 及时返回最新信息。 + * @param {Object} [data={}] - { token, key }(推荐)或旧参数模式 { token, delivery_order_code, ... } + * @return {Promise} { success, code, data, message, statusCode } + * success=true 时 data 为 _packOrder 返回的任务信息;失败时 statusCode 为 401/403/400 + */ + async packOrderByToken(data = {}) { + const { ctx } = this; + // 新链路(token+key / 旧参数过渡)一律不接收 users:打包人由 _packOrder 自动回填工作台绑定成员。 + // 仅 business(packOrder) 旧链路支持上报 users。 + const { token, key, users: _ignoredUsers, ...legacyParams } = data || {}; + + const resolved = await this.resolveWorkbenchContext(token); + if (!resolved.success) return resolved; + + const warehouseId = ctx.workbenchWarehouseId; + if (!warehouseId) { + return { + success: false, + code: 0, + statusCode: 403, + data: null, + message: '工作台未绑定有效仓库', + }; + } + + // 新 key 模式优先;不传 key 时旧参数模式兼容(过渡期保留) + const ctxKey = String(key || '').trim(); + let packParams; + if (ctxKey) { + let cachedCtx = null; + try { + cachedCtx = await this._loadPackCtx({ key: ctxKey }); + } catch (loadErr) { + return { + success: false, + code: 0, + statusCode: 400, + data: null, + message: loadErr.message || '打包上下文已过期,请重新扫码', + }; + } + // 归属校验:防跨仓库/跨工作台消费他人扫码上下文 + if (Number(cachedCtx.warehouse_id || 0) !== Number(warehouseId)) { + return { + success: false, + code: 0, + statusCode: 403, + data: null, + message: '打包上下文与当前仓库不匹配', + }; + } + if (cachedCtx.workbench_id != null && Number(cachedCtx.workbench_id) !== Number(ctx.workbenchId)) { + return { + success: false, + code: 0, + statusCode: 403, + data: null, + message: '打包上下文与当前工作台不匹配', + }; + } + packParams = { + delivery_order_code: cachedCtx.delivery_order_code, + // 订单主键由后端扫码上下文注入:发货单号唯一性仅为 (单号, 货主, 仓库), + // 跨货主可重复,按单号+仓库反查会串单,故打包以主键为准 + order_id: cachedCtx.order_id, + wave_no: cachedCtx.wave_no, + waybill_code: cachedCtx.waybill_code, + }; + } else { + // 旧参数模式:order_id 不接受设备上报(仅 key 模式由后端缓存注入,防篡改) + const { order_id: _ignoredOrderId, ...restLegacyParams } = legacyParams || {}; + packParams = restLegacyParams; + } + + const result = await this._packOrder({ + ...packParams, + warehouse_id: warehouseId, + workbench_id: ctx.workbenchId, + }); + return { success: true, code: 200, data: result, message: 'ok' }; + } + + /** + * 工作台打包完成(供 workbench.finishPack,免登录免鉴权,以工作台 token 鉴权)。 + * warehouse_id/workbench_id 均由 token 解析出的工作台上下文注入,禁止前端传入。 + * 任务结束后由 _finishPack 内部主动失效 token 缓存,保证 getWorkbenchInfo 及时返回最新信息。 + * @param {Object} [data={}] - { token } + * @return {Promise} { success, code, data, message, statusCode } + * success=true 时 data 为 _finishPack 返回的完成信息;失败时 statusCode 为 401/403 + */ + async finishPackByToken(data = {}) { + const { ctx } = this; + const { token } = data || {}; + + const resolved = await this.resolveWorkbenchContext(token); + if (!resolved.success) return resolved; + + const warehouseId = ctx.workbenchWarehouseId; + if (!warehouseId) { + return { + success: false, + code: 0, + statusCode: 403, + data: null, + message: '工作台未绑定有效仓库', + }; + } + + const result = await this._finishPack({ + workbench_id: ctx.workbenchId, + warehouse_id: warehouseId, + }); + return { success: true, code: 200, data: result, message: 'ok' }; + } + + /** + * 工作台称重上报(供 workbench.sendWeight,免登录免鉴权,以工作台 token 鉴权)。 + * warehouse_id 由 token 解析出的工作台上下文注入,禁止前端传入; + * 其余入参与 business(sendWeight) 分支一致,重量单位为克。 + * @param {Object} [data={}] - { token, barcode, weight } + * @return {Promise} { success, code, data, message, statusCode } + * success=true 时 data 为 _sendWeight 返回的称重结果(weighing_weight/total_weight 单位 g); + * 失败时 statusCode 为 401/403 + */ + async sendWeightByToken(data = {}) { + const { ctx } = this; + const { token, barcode, weight } = data || {}; + + const resolved = await this.resolveWorkbenchContext(token); + if (!resolved.success) return resolved; + + const warehouseId = ctx.workbenchWarehouseId; + if (!warehouseId) { + return { + success: false, + code: 0, + statusCode: 403, + data: null, + message: '工作台未绑定有效仓库', + }; + } + + const result = await this._sendWeight({ barcode, weight, warehouseId }); + return { success: true, code: 200, data: result, message: 'ok' }; + } + + /** + * 条码查询订单(供 workbench.queryOrder,免登录免鉴权,以工作台 token 鉴权)。 + * warehouse_id 由 token 解析出的工作台上下文注入,禁止前端传入, + * 防止跨仓库查单;body 传入的 warehouse_id/workbench_id 一律忽略。 + * 只读查询,不涉及缓存失效;其余入参与 business(queryOrder) 分支一致。 + * @param {Object} [data={}] - { token, barcode } + * @return {Promise} { success, code, data, message, statusCode } + * success=true 时 data 为 _queryOrder 返回的条码查询订单结果;失败时 statusCode 为 401/403 + */ + async queryOrderByToken(data = {}) { + const { ctx } = this; + const { token, barcode } = data || {}; + + const resolved = await this.resolveWorkbenchContext(token); + if (!resolved.success) return resolved; + + const warehouseId = ctx.workbenchWarehouseId; + if (!warehouseId) { + return { + success: false, + code: 0, + statusCode: 403, + data: null, + message: '工作台未绑定有效仓库', + }; + } + + const result = await this._queryOrder({ + barcode, + warehouseId, + workbench_id: ctx.workbenchId, + }); + return { success: true, code: 200, data: result, message: 'ok' }; + } + + /** + * 标准化成员行 ID 列表:支持数组、单值、逗号分隔字符串,去重后仅保留正整数。 + * @param {*} ids 原始行 ID 入参 + * @return {number[]} 标准化后的行 ID 列表 + */ + normalizeWorkbenchMemberIds(ids) { + const source = Array.isArray(ids) ? ids : (ids === undefined || ids === null ? [] : [ ids ]); + const values = []; + source.forEach(item => { + if (typeof item === 'string' && item.includes(',')) { + item.split(',').forEach(part => values.push(part.trim())); + } else { + values.push(item); + } + }); + return [ ...new Set(values + .map(item => Number(item)) + .filter(n => Number.isInteger(n) && n > 0)) ]; + } + + /** + * 成员全部登出后自动结束该工作台所有未结束的打包任务。 + * 与 _finishPack 语义一致:每个任务置 status=2 并写 end_time, + * 同步回写订单打包状态(散单按订单、团购按波次,并补确认打印状态), + * 写完成操作日志、复位 OSD、失效 token 缓存。 + * 单个任务处理失败仅告警不阻断,整体异常吞掉不抛出,不影响移除成员主流程。 + * @param {Object} params - { workbenchId, warehouseId } + * @return {Promise<{finished: number, task_ids: number[]}>} 已结束任务数与ID列表 + */ + async _finishAllPackTasksByMemberLogout({ workbenchId, warehouseId }) { + const { ctx } = this; + const validWorkbenchId = Number(workbenchId || 0); + const validWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(validWorkbenchId) || validWorkbenchId <= 0) { + return { finished: 0, task_ids: [] }; + } + try { + const tasks = await ctx.model.PackTask.findAll({ + where: { + workbench_id: validWorkbenchId, + warehouse_id: validWarehouseId, + status: { [ctx.app.Sequelize.Op.lt]: 2 }, + }, + order: [[ 'id', 'DESC' ]], + }); + if (!tasks || tasks.length === 0) { + ctx.logger.info('[Workbench._finishAllPackTasksByMemberLogout] 工作台 %d 无未结束的打包任务', validWorkbenchId); + return { finished: 0, task_ids: [] }; + } + + const now = new Date(); + const finishedTaskIds = []; + for (const task of tasks) { + try { + const endTime = await this.resolvePackTaskEndTime(task, now); + await task.update({ end_time: endTime, status: 2 }); + finishedTaskIds.push(task.id); + + const isGroupTask = Number(task.pack_mode) === 2; + await this._updateOrderPackStatus(validWarehouseId, { + orderId: Number(task.order_id || 0), + waveId: isGroupTask ? Number(task.wave_id || 0) : 0, + packStatus: 2, + caller: 'Workbench._finishAllPackTasksByMemberLogout', + }); + + // 写完成操作日志(操作人取自任务记录 operator_text) + try { + const operatorText = String(task.operator_text || ''); + await this._writePackOperationLog({ + warehouseId: validWarehouseId, + orderId: Number(task.order_id || 0), + waveId: isGroupTask ? Number(task.wave_id || 0) : 0, + waveNo: task.wave_no || '', + isSandan: isGroupTask ? 0 : 1, + packData: { + pack_mode: task.pack_mode, + status: 2, + pack_quantity: task.pack_quantity, + item_quantity: task.item_quantity, + sku_count: task.sku_count, + workbench_id: validWorkbenchId, + wave_no: task.wave_no, + }, + users: operatorText ? [{ real_name: operatorText }] : [], + workbenchName: '', + }); + } catch (logErr) { + ctx.logger.warn('[Workbench._finishAllPackTasksByMemberLogout] 写操作日志失败 taskId=%d: %s', task.id, logErr.message); + } + } catch (taskErr) { + ctx.logger.warn('[Workbench._finishAllPackTasksByMemberLogout] 结束任务失败 taskId=%d: %s', task.id, taskErr.message); + } + } + + // OSD 复位为「无任务」(异步执行,不阻塞主流程) + this._resetPackOsd({ warehouseId: validWarehouseId, workbenchId: validWorkbenchId }).catch(err => { + ctx.logger.warn('[Workbench._finishAllPackTasksByMemberLogout] OSD复位异常 workbenchId=%d err=%s', validWorkbenchId, err.message); + }); + + // 打包任务已结束,失效 token 缓存,保证 getWorkbenchInfo 尽快返回最新打包信息 + await this.invalidateWorkbenchTokenCacheByWorkbenchId(validWorkbenchId); + + ctx.logger.info('[Workbench._finishAllPackTasksByMemberLogout] 成员全部登出,自动结束打包任务 %d 个 workbenchId=%d', + finishedTaskIds.length, validWorkbenchId); + return { finished: finishedTaskIds.length, task_ids: finishedTaskIds }; + } catch (err) { + ctx.logger.warn('[Workbench._finishAllPackTasksByMemberLogout] 自动结束打包任务失败 workbenchId=%d: %s', validWorkbenchId, err.message); + return { finished: 0, task_ids: [] }; + } + } + + /** + * 移除工作台成员(供 workbench.removeMember,免登录免鉴权,以工作台 token 鉴权)。 + * 统一走 resolveWorkbenchContext 校验:无 token 返回失败(401)、token 无效返回失败(403); + * 解析成功后仅删除归属于该工作台的成员行(软删除), + * 并清除对应 token 信息缓存,保证接口尽快返回最新成员。 + * 移除后若该工作台已无任何成员,自动结束其所有未结束的打包任务 + * (与 _finishPack 语义一致,响应附 auto_finished_pack)。 + * @param {Object} [data={}] - { ids, token } + * @return {Promise} { success, code, data, message, statusCode } + */ + async removeWorkbenchMember(data = {}) { + const { ctx, app } = this; + try { + // 统一 token 校验(无 token 401、无效 403),解析成功后写入 ctx 备用 + const resolved = await this.resolveWorkbenchContext(data.token); + if (!resolved.success) return resolved; + const rawToken = ctx.workbenchToken; + + const memberIds = this.normalizeWorkbenchMemberIds(data.ids ?? data.memberIds ?? data.member_ids); + if (memberIds.length === 0) { + return { + success: false, + code: 0, + statusCode: 400, + data: null, + message: '成员行ID不能为空或无效', + }; + } + + const workbench = resolved.data; + + const rows = await ctx.model.WorkbenchMember.findAll({ + where: { id: memberIds, workbench_id: workbench.id }, + attributes: [ 'id' ], + }); + const matchedIds = rows.map(row => row.id); + if (matchedIds.length === 0) { + return { + success: false, + code: 0, + statusCode: 404, + data: null, + message: '未找到可移除的成员', + }; + } + + await ctx.model.WorkbenchMember.destroy({ + where: { id: matchedIds, workbench_id: workbench.id }, + }); + + // 成员全部登出(剩余成员为 0)时,自动结束该工作台未结束的打包任务, + // 同步订单打包状态、写操作日志、复位 OSD(与 _finishPack 语义一致)。 + let autoFinishedPack = { finished: 0, task_ids: [] }; + try { + const remainingCount = await ctx.model.WorkbenchMember.count({ + where: { workbench_id: workbench.id }, + }); + if (remainingCount === 0) { + autoFinishedPack = await this._finishAllPackTasksByMemberLogout({ + workbenchId: workbench.id, + warehouseId: Number(workbench.warehouse_id || 0), + }); + } + } catch (memberCountErr) { + // 剩余成员统计或自动结束失败仅告警,不阻断成员移除主流程 + app.coreLogger.warn(`成员登出后自动结束打包检查失败: ${memberCountErr.message}`); + } + + // 成员变更后清除 token 信息缓存,下次获取工作台信息立即反映最新成员。 + await app.delCacheAsync(this.getWorkbenchTokenCacheKey(rawToken)); + + return { + success: true, + code: 200, + data: { + removed: matchedIds.length, + ids: matchedIds, + auto_finished_pack: autoFinishedPack, + }, + message: '移除成功', + }; + } catch (error) { + app.coreLogger.error(`移除工作台成员失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '移除工作台成员失败,请稍后重试', + }; + } + } + + /** + * 绑定工作台成员(供 workbench.bindMember,免登录免鉴权,以工作台 token 鉴权)。 + * 统一走 resolveWorkbenchContext 校验:无 token 返回失败(401)、token 无效返回失败(403); + * 入参用户ID(可空,兼容非系统账号用户)+ 姓名(必填)+ 工作台 token; + * 绑定成功后清除对应 token 信息缓存,保证接口尽快返回最新成员。 + * @param {Object} [data={}] - { userId | user_id, userName | user_name | name, token } + * @return {Promise} { success, code, data, message, statusCode } + */ + async bindWorkbenchMember(data = {}) { + const { ctx, app } = this; + try { + // 统一 token 校验(无 token 401、无效 403),解析成功后写入 ctx 备用 + const resolved = await this.resolveWorkbenchContext(data.token); + if (!resolved.success) return resolved; + const rawToken = ctx.workbenchToken; + + const rawUserName = typeof data.userName === 'string' + ? data.userName + : (typeof data.user_name === 'string' + ? data.user_name + : (typeof data.name === 'string' ? data.name : '')); + const userName = rawUserName.trim(); + if (!userName) { + return { + success: false, + code: 0, + statusCode: 400, + data: null, + message: '姓名不能为空', + }; + } + + const rawUserId = data.userId ?? data.user_id; + const userId = rawUserId === null || rawUserId === undefined || rawUserId === '' + ? null + : Number(rawUserId); + if (userId !== null && (!Number.isInteger(userId) || userId <= 0)) { + return { + success: false, + code: 0, + statusCode: 400, + data: null, + message: '用户ID无效', + }; + } + + const workbench = resolved.data; + + const member = await ctx.model.WorkbenchMember.create({ + workbench_id: workbench.id, + user_id: userId, + user_name: userName, + }); + + // 成员变更后清除 token 信息缓存,下次获取工作台信息立即反映最新成员。 + await app.delCacheAsync(this.getWorkbenchTokenCacheKey(rawToken)); + + return { + success: true, + code: 200, + data: { + id: member.id, + workbench_id: member.workbench_id, + user_id: member.user_id, + user_name: member.user_name, + }, + message: '绑定成功', + }; + } catch (error) { + app.coreLogger.error(`绑定工作台成员失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '绑定工作台成员失败,请稍后重试', + }; + } + } +} + +module.exports = WorkbenchService; diff --git a/app/service/warehouse.js b/app/service/warehouse.js new file mode 100644 index 0000000..0b21fbe --- /dev/null +++ b/app/service/warehouse.js @@ -0,0 +1,294 @@ +'use strict'; + +const Service = require('egg').Service; + +const WAREHOUSE_INTERFACE_TYPE_ID = 3; + +class WarehouseService extends Service { + /** + * 解析 warehouse method,拆分为服务路径与动作名。 + * @param {string} methodName method 名称。 + * @return {{ servicePath: string, actionName: string }} 解析结果。 + */ + resolveWarehouseMethod(methodName = '') { + const method = String(methodName || '').trim(); + const parts = method.split('.').filter(Boolean); + const actionName = parts.pop() || ''; + const servicePath = parts.join('.'); + + return { + servicePath, + actionName, + }; + } + + /** + * 根据服务路径查找 warehouseMethods 下的目标服务。 + * @param {string} servicePath 服务路径。 + * @return {Object|null} 目标服务实例。 + */ + getWarehouseMethodService(servicePath = '') { + const { ctx } = this; + const pathSegments = String(servicePath || '').split('.').filter(Boolean); + let methodService = ctx.service.warehouseMethods; + + if (pathSegments.length === 0) { + return methodService; + } + + for (const segment of pathSegments) { + methodService = methodService && methodService[segment]; + } + + return methodService || null; + } + + /** + * 分发 warehouse method 到 warehouseMethods 目录。 + * 分发前统一注入仓库上下文(warehouseId/appKey)。 + * @param {string} methodName method 名称。 + * @param {Object} body 请求体。 + * @param {Object} query 请求 query。 + * @param {Object} warehouseInfo 仓库上下文信息。 + * @return {Promise} method 执行结果。 + */ + async dispatchWarehouseMethod(methodName, body, query, warehouseInfo) { + const { servicePath, actionName } = this.resolveWarehouseMethod(methodName); + const methodService = this.getWarehouseMethodService(servicePath); + + if (!methodService || typeof methodService[actionName] !== 'function') { + return { + ok: false, + httpStatus: 400, + code: 400, + message: `warehouse method 不存在: ${methodName}`, + data: null, + }; + } + + // 统一注入仓库上下文到方法服务实例 + if (warehouseInfo && typeof methodService.setInfo === 'function') { + methodService.setInfo( + null, // storeId + warehouseInfo.warehouseId, + warehouseInfo.appKey, + null, // customerId + null // warehouseCode + ); + } + + const methodResult = await methodService[actionName]({ + body, + query, + }); + + return { + ok: true, + httpStatus: 200, + code: 1, + message: 'ok', + data: methodResult, + }; + } + + /** + * 校验 warehouse 基础 query 参数。 + * @param {Object} query 请求 query 参数。 + * @return {boolean} 是否通过基础参数校验。 + */ + validateWarehouseParams(query) { + const requiredFields = [ 'method', 'v', 'timestamp' ]; + for (const field of requiredFields) { + if (!query || !query[field]) { + return false; + } + } + + if (typeof query.method !== 'string' || !query.method.includes('.')) { + return false; + } + + return true; + } + + /** + * 读取并解析 JSON 请求体。 + * @return {Promise} 解析后的 JSON 对象。 + */ + async parseJsonBody() { + const { ctx } = this; + let jsonData = ''; + + if (ctx.request.rawBody) { + jsonData = ctx.request.rawBody; + } else if (ctx.request.body !== undefined) { + jsonData = typeof ctx.request.body === 'string' + ? ctx.request.body + : JSON.stringify(ctx.request.body); + } else { + jsonData = await new Promise((resolve, reject) => { + let data = ''; + ctx.req.on('data', chunk => { + data += chunk; + }); + ctx.req.on('end', () => { + resolve(data); + }); + ctx.req.on('error', reject); + }); + } + + jsonData = jsonData ? String(jsonData) : ''; + if (!jsonData || jsonData.trim() === '') { + return { + ok: false, + httpStatus: 400, + code: 400, + message: 'json数据为空', + data: null, + }; + } + + try { + return JSON.parse(jsonData); + } catch (error) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: 'json数据解析错误', + data: null, + }; + } + } + + /** + * 提取并归一化 warehouse 所需的 appKey 与 sign。 + * @param {Object} query 请求 query 参数。 + * @return {{ appKey: string, providedSign: string }} 归一化后的关键信息。 + */ + normalizeSignFields(query = {}) { + const appKey = String(query.app_key || query.appkey || query.self_app_key || '').trim(); + const providedSign = String(query.sign || query.signature || '').trim(); + + return { + appKey, + providedSign, + }; + } + + /** + * 处理 warehouse 请求并返回统一结果。 + * 核心差异:使用 interface_type_id=3(仓库级),无需合约关联,直接取 warehouse_id。 + * @return {Promise} 统一结果对象。 + */ + async processRequest() { + const { ctx } = this; + const query = ctx.query || {}; + + if (!this.validateWarehouseParams(query)) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: '参数缺失或错误: method/v/timestamp', + data: null, + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, + }; + } + + // 时间戳时效校验(±10分钟) + const nowTs = Math.floor(Date.now() / 1000); + const reqTs = Number(query.timestamp); + if (!Number.isFinite(reqTs) || Math.abs(nowTs - reqTs) > 600) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: `时间戳已过期或无效,服务器时间: ${nowTs}`, + data: null, + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, + }; + } + + const body = await this.parseJsonBody(); + if (body && body.ok === false) { + return { + ...body, + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, + }; + } + + const { appKey, providedSign } = this.normalizeSignFields(query); + if (!appKey) { + return { + ok: false, + httpStatus: 400, + code: 400, + message: '参数缺失或错误: app_key', + data: null, + warehouseId: null, + appKey: null, + }; + } + + const { systems: systemsService } = ctx.service; + const apiSignService = systemsService.apiSign; + + // 仓库级验签:interface_type_id = 3 + const verifyResult = await apiSignService.verifyRequestSignByAppKey({ + appKey, + query, + body, + providedSign, + interfaceTypeId: WAREHOUSE_INTERFACE_TYPE_ID, + }); + + if (!verifyResult.ok) { + return { + ok: false, + httpStatus: 401, + code: 401, + message: `签名校验失败: ${verifyResult.message}`, + data: null, + warehouseId: null, + appKey, + }; + } + + // 仓库级无需合约关联,直接使用 api_app.warehouse_id + const warehouseId = verifyResult.warehouseId; + if (!warehouseId) { + return { + ok: false, + httpStatus: 403, + code: 403, + message: 'API 应用未绑定仓库', + data: null, + warehouseId: null, + appKey: verifyResult.appKey, + }; + } + + const queryWithAppKey = { + ...query, + app_key: verifyResult.appKey, + }; + + const dispatchResult = await this.dispatchWarehouseMethod(query.method, body, queryWithAppKey, { + warehouseId, + appKey: verifyResult.appKey, + }); + + return { + ...dispatchResult, + warehouseId, + appKey: verifyResult.appKey, + }; + } +} + +module.exports = WarehouseService; diff --git a/app/service/warehouseMethods/inbox.js b/app/service/warehouseMethods/inbox.js new file mode 100644 index 0000000..2427ed6 --- /dev/null +++ b/app/service/warehouseMethods/inbox.js @@ -0,0 +1,78 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 仓库开放 API — 站内信模块处理器。 + * 接收仓库级外部适配器推送的 inbox.push 请求, + * 统一委托 app/service/inbox/receiver.receive 处理写库与异步推送。 + */ +class WarehouseInboxService extends MainService { + /** + * 仓库 API 消息入站入口。 + * warehouse_id 从验签后上下文注入,禁止外部传入。 + * @param {Object} options 请求参数。 + * @param {Object} options.body 请求体。 + * @return {Promise} 入站结果。 + */ + async push({ body = {} } = {}) { + const { ctx } = this; + const { warehouseId, appKey } = this.getInfo(); + + // 安全边界:warehouse_id 一律从验签后上下文获取 + if (!warehouseId) { + throw new Error('缺少仓库信息'); + } + + // 安全边界:校验必填参数 + if (!body.requestId || !String(body.requestId).trim()) { + throw new Error('requestId 不能为空'); + } + + // 构造 ext_id + const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`; + + // 解析消息原始发送时间(可选,用于历史消息过滤) + const sendTime = this.parseSendTime(body.sendTime); + + // 构造入站数据并委托给 inbox receiver + const result = await ctx.service.inbox.receiver.receive({ + ext_id: extId, + warehouse_id: warehouseId, + direction: 'inbound', + parent_id: body.parentId || null, + source_type: 'api', + source_extra: String(appKey || ''), + target_type: body.targetType || 'im', + group_name: body.groupName || null, + user_name: body.userName || null, + group_id: body.groupId || null, + user_id: body.userId || null, + content: body.content || null, + ext_data: body.extData || null, + flags: body.flags || {}, + send_time: sendTime, + }); + + return result; + } + + /** + * 解析外部传入的消息发送时间。 + * 支持毫秒时间戳、秒时间戳、ISO 时间字符串;解析失败返回 null。 + * @param {number|string|null} value 外部传入的 sendTime。 + * @return {number|null} 毫秒时间戳,解析失败返回 null。 + */ + parseSendTime(value) { + if (value == null || value === '') return null; + if (typeof value === 'number' && Number.isFinite(value)) { + if (value > 1e12) return Math.floor(value); // 毫秒 + if (value > 1e8) return Math.floor(value * 1000); // 秒 + return null; + } + const ms = Date.parse(String(value)); + return Number.isFinite(ms) ? ms : null; + } +} + +module.exports = WarehouseInboxService; diff --git a/app/service/warehouseMethods/index.js b/app/service/warehouseMethods/index.js new file mode 100644 index 0000000..78da1d1 --- /dev/null +++ b/app/service/warehouseMethods/index.js @@ -0,0 +1,22 @@ +'use strict'; + +const MainService = require('../main'); + +class WarehouseIndexService extends MainService { + /** + * 心跳接口,返回服务可用性与仓库上下文信息。 + * @return {Promise} 心跳响应。 + */ + async ping() { + const { warehouseId, appKey } = this.getInfo(); + + return { + warehouse_id: warehouseId, + app_key: appKey, + server_time: Math.floor(Date.now() / 1000), + status: 'ok', + }; + } +} + +module.exports = WarehouseIndexService; diff --git a/app/service/warehouseMethods/store.js b/app/service/warehouseMethods/store.js new file mode 100644 index 0000000..a4c8d68 --- /dev/null +++ b/app/service/warehouseMethods/store.js @@ -0,0 +1,88 @@ +'use strict'; + +const MainService = require('../main'); + +class WarehouseStoreService extends MainService { + /** + * 查询当前仓库下已授权的货主列表。 + * 返回货主基本信息(id、公司名、联系人、联系电话、授权状态)。 + * @param {Object} options 请求参数。 + * @param {Object} options.body 请求体。 + * @return {Promise} 货主列表。 + */ + async list({ body = {} } = {}) { + const { ctx } = this; + const { warehouseId } = this.getInfo(); + + const page = Math.max(1, Number(body.page) || 1); + const pageSize = Math.min(100, Math.max(1, Number(body.pageSize) || 20)); + + // 通过 store_warehouse 关联查询已授权的货主 + const { StoreWarehouse, Store } = ctx.model; + + const where = { + warehouse_id: warehouseId, + auth_status: 2, // 已通过 + warehouse_use_status: 1, // 仓库侧可用 + }; + + const { count: total, rows } = await StoreWarehouse.findAndCountAll({ + attributes: [ + 'id', + 'store_id', + 'auth_status', + 'auth_start', + 'auth_end', + 'store_remask', + 'warehouse_remask', + ], + where, + include: [ + { + model: Store, + as: 'store', + attributes: [ + 'id', + 'company_name', + 'contact_person', + 'contact_phone', + 'status', + ], + required: true, + where: { + status: 1, // 启用 + }, + }, + ], + offset: (page - 1) * pageSize, + limit: pageSize, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + const list = rows.map(row => ({ + store_id: row['store.id'], + company_name: row['store.company_name'], + contact_person: row['store.contact_person'], + contact_phone: row['store.contact_phone'], + contract_id: row.id, + auth_status: row.auth_status, + auth_start: row.auth_start, + auth_end: row.auth_end, + store_remask: row.store_remask, + warehouse_remask: row.warehouse_remask, + })); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } +} + +module.exports = WarehouseStoreService; diff --git a/app/view/platform_oauth_callback.html b/app/view/platform_oauth_callback.html new file mode 100644 index 0000000..53a8c4b --- /dev/null +++ b/app/view/platform_oauth_callback.html @@ -0,0 +1,147 @@ + + + + + + <%= title %> + + + +
    +
    +

    <%= title %>

    +
    用于人工核对平台授权回调参数与预授权码处理状态
    +
    + +
    + 综合结果:<%= resultText %> +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    平台返回 code<%= code || '-' %>
    平台返回 state<%= state || '-' %>
    去前缀后的 state<%= normalizedState || '-' %>
    解析出的 platform_code<%= platformCode || '-' %>
    解析出的 auth_random_code<%= authRandomCode || '-' %>
    是否找到预授权码记录<%= hasShop ? '是' : '否' %>
    预授权码是否已处理<%= isProcessedText %>
    平台是否正确<%= isPlatformMatchedText %>
    记录中的 platform_code<%= shopPlatformCode || '-' %>
    记录中的 status<%= shopStatus === null ? '-' : shopStatus %>
    +
    +
    + + \ No newline at end of file diff --git a/app/view/wechat_auth_callback.html b/app/view/wechat_auth_callback.html new file mode 100644 index 0000000..ad2fb97 --- /dev/null +++ b/app/view/wechat_auth_callback.html @@ -0,0 +1,104 @@ + + + + + + <%= title %> + + + +
    +
    +

    <%= title %>

    +
    +
    <%= resultText %>
    +
    + <% if (resultLevel === 'success') { %> +
    +
    小程序AppID
    +
    <%= appid %>
    +
    +
    +
    小程序名称
    +
    <%= nickname || '-' %>
    +
    +
    +
    绑定仓库ID
    +
    <%= warehouseId === null || warehouseId === undefined ? '-' : warehouseId %>
    +
    +
    授权信息已保存,可返回系统查看小程序列表。
    + <% } else { %> +
    请返回系统重新发起授权。
    + <% } %> +
    +
    + + diff --git a/config/config.default.js b/config/config.default.js index 8cfba58..685f0fd 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -1,5 +1,9 @@ -/* - * @param {Egg.EggAppInfo} appInfo app info +const path = require('node:path'); + +/** + * 生成应用默认配置。 + * @param {Egg.EggAppInfo} appInfo 应用信息。 + * @return {Egg.EggAppConfig} 应用配置。 */ module.exports = appInfo => { /** @@ -13,25 +17,25 @@ module.exports = appInfo => { // add your middleware config here config.middleware = []; - // add your user config here const userConfig = { // myAppName: 'egg', }; + const tencentCloudConfig = require('./tencent-cloud'); config.redis = { clients: { cache: { port: 6379, - host: '112.124.21.102', + host: '127.0.0.1', password: 'qwe2019@', db: 10, }, printer: { port: 6379, - host: '112.124.21.102', + host: '127.0.0.1', password: 'qwe2019@', db: 11, - } + }, }, }; config.security = { @@ -43,24 +47,112 @@ module.exports = appInfo => { appKey: 23535631, security: 'd0cbd3935e3afa2b42b5dc600c08a795', }; + // 微信开放平台第三方平台(组件)配置:接收授权事件推送与调用授权方接口。 + // 值可被 config.local.js / config.prod.js 覆盖。 + config.wechatOpen = { + component_appid: 'wx6e91ec813bcb7eec', + component_secret: '8e76ea205dcc1d3e506ce6c102375bdd', + token: 'lujS6QH8jUkabwOwMuAqe9odz7', + encoding_aes_key: 'lujS6QH8jUkabwOwMuAqe9odz7jmKEnT37XMahpSmrU', + api_base: 'https://api.weixin.qq.com', + // 授权完成后的回跳地址(微信开放平台授权链接 redirect_uri,须为系统 /Authorization 路由; + // 域名须在微信开放平台登记为授权回调域名,前端 nginx 已将 /Authorization 代理到本系统) + redirect_uri: 'https://wms.wms.gztbyc.com/Authorization', + }; + config.deepseek = { + apiKey: process.env.DEEPSEEK_API_KEY || '', + baseUrl: 'https://api.deepseek.com', + }; + + // 开放接口(OpenAPI)配置 + config.openapi = { + // 签约关系级接口配置的默认回调地址:不再由接口配置入参维护,保存时统一写入该值。 + // 为空时不写入 callback_url(回调通知需在 config.local.js / config.prod.js 等环境配置中补齐) + defaultCallbackUrl: '', + }; + + // 站内信模块配置 + config.inbox = { + imageBaseUrl: '', // 商品图片域名,为空时用请求 ctx.host + // 历史消息过滤:消息原始发送时间距今超过该阈值(毫秒)则跳过 AI 处理,防止补推历史消息被当成新工单 + historyMessageMaxAgeMs: 10 * 60 * 1000, + // AI 兜底开关:规则引擎未命中时是否回退 AI 推理(默认关闭,节省费用;开启后未命中消息走 AI) + aiFallback: false, + // 退回收件登记聚合通知防抖窗口(毫秒):等该时长无新登记后合并推送,默认 5 分钟 + returnReceivedNotifyDelayMs: 5 * 60 * 1000, + // 视频补录结果通知:单轮处理条数上限(定时任务每 1 分钟扫一次) + videoRecordNotifyLimit: 10, + // 视频补录结果通知:超时阈值(毫秒),超过仍无录像则按超时回信并终止,避免长期占用扫描窗口 + videoRecordNotifyTimeoutMs: 60 * 60 * 1000, + // 出站推送失败自动重推:全局总开关(默认 true;置 false 后所有仓库都不再自动重推;仓库是否启用由仓库设置的 inbox_push_retry.enabled 决定,默认关闭) + pushRetryEnabled: true, + // 出站推送失败自动重推:兜底失败时间窗(毫秒,默认 30 分钟);仓库设置项 inbox_push_retry.window_minutes 优先(缺省/非法时用本值) + pushRetryWindowMs: 30 * 60 * 1000, + // 出站推送失败自动重推:单仓单轮最多重推条数(定时任务每 3 分钟扫一次) + pushRetryLimit: 20, + }; + + config.tencentCloud = { + ...tencentCloudConfig, + }; config.cos = { - appId: 1234567890, - secretId: 'AKIDeFhx1tQ5PYVYP9K8PXUFoazHRPBlpTXP', - secretKey: 'pcHtKbhcKqDNLqEQRIxRjpjRHxTnvGQT', + ...config.tencentCloud, bucket: 'ye4s-1255377868', region: 'ap-guangzhou', uploadurl: 'https://ye4s-1255377868.cos.ap-guangzhou.myqcloud.com', cdnurl: 'https://ye4s.file.gzxunren.com', - savekey: '/{warehouseId}/{dir}/{year}{mon}{day}/{filemd5}{.suffix}', + savekey: '{warehouseId}/{dir}/{year}{mon}{day}/{filemd5}{.suffix}', expire: 600, maxsize: '100M', mimetype: 'jpg,png,bmp,jpeg,gif,zip,rar,xls,xlsx,apk', apiupload: 1, dirs: { - image: '/images/', - document: '/documents/', - apk: '/apks/', - temp: '/temp/', // 临时文件目录 + image: 'images/', + document: 'documents/', + apk: 'apks/', + temp: 'temp/', // 临时文件目录 + }, + }; + config.fileWriter = { + baseDir: path.join(appInfo.baseDir, 'runtime', 'file-writer'), + maxFileSize: 100 * 1024 * 1024, + maxFileLines: 2000, + maxConsumeRecordsPerWindow: 1000, + maxConsumeRecordsPerRun: 1000, + writeWindowSeconds: 1, + maxWriteRecordsPerWindow: 1000, + retentionDays: 7, + cleanupIntervalMs: 60 * 60 * 1000, + sequenceWidth: 4, + stateMapMaxEntries: 256, + fileExtension: '.log', + progressExtension: '.progress', + }; + // 日志落盘目录:显式声明,避免依赖 $HOME 的隐式默认值 + // (生产 HOME=/root 时 egg 默认会落到 /root/logs/wms;此处固定下来便于查询与清理) + config.logPaths = { + base: process.env.WMS_LOG_DIR || (process.platform === 'win32' + ? path.join(appInfo.baseDir, 'logs') + : '/root/logs/wms'), + }; + // 文件日志只保留 WARN/ERROR:INFO(含 egg-sequelize 逐条 SQL 日志)不再落盘, + // 避免 wms-web.log 每天增长约 2GB 撑爆根分区(/ 仅 40G)。 + // consoleLevel 仍为 INFO,本地开发在终端照常看到 INFO,不受影响。 + // 与线上 /www/wwwroot/qimen/v1、v2 的手工配置保持一致(生产 config 不参与 deploy,由人工维护)。 + config.logger = { + dir: config.logPaths.base, + level: 'WARN', + consoleLevel: 'INFO', + }; + // 接口流水日志(已替代 wms_system_log 表,该表已下线):一行一条,字段沿用旧表结构并平铺。 + // formatter 直接返回 message,不改写内容;整行形如 `HH:mm:ss {JSON}` + // (行首时分秒前缀由 app/lib/api_log_sink.js 加上,行尾 eol 由 egg-logger 追加)。 + config.customLogger = { + apiLog: { + file: path.join(config.logPaths.base, 'wms-api.log'), + level: 'INFO', + consoleLevel: 'NONE', + formatter: meta => meta.message, }, }; config.fileTypes = { @@ -105,27 +197,35 @@ module.exports = appInfo => { 'audio/x-m4a': 'audio', }; config.cors = { - origin: '*', // 允许所有源,生产环境应指定具体域名 + origin: ctx => ctx.get('Origin'), // 动态返回请求源,配合 credentials: true 使用 allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS', + exposeHeaders: 'Authorization', credentials: true, // 允许携带 cookie }; config.mysql = { clients: { wms: { - host: '10.10.0.1', + host: '127.0.0.1', port: '3306', user: 'wms', password: 'P6j3YTHTpirepYWz', database: 'wms', }, + ye4s: { + host: '127.0.0.1', + port: '3306', + user: 'ye4s', + password: 'H@8h^QE4N$L.F_*', + database: 'ye4s', + }, }, app: true, agent: false, }; exports.sequelize = { dialect: 'mysql', - host: '10.10.0.1', + host: '112.124.21.102', port: 3306, database: 'wms', username: 'wms', @@ -138,7 +238,7 @@ module.exports = appInfo => { deletedAt: 'deleted_at', // 软删除字段名 }, pool: { - max: 5, + max: 225, min: 1, idle: 10000, acquire: 30000, @@ -147,24 +247,120 @@ module.exports = appInfo => { config.jwt = { expiresIn: 14400, + renewThreshold: 7200, secret: 'E5#ex.g@,GfL_8?', }; - /*config.view = { + config.view = { defaultViewEngine: 'ejs', mapping: { '.html': 'ejs', }, - };*/ + }; config.cluster = { listen: { port: 6060, // 使用其他端口避免冲突 hostname: '0.0.0.0', }, }; - config.printService = { - url: 'http://localhost:4050', + config.poloapi = { + }; + config.debug = false; // 生成环境默认关闭 debug,开发环境通过 config.local.js 开启 + config.platformOauthReservationCodePrefix = ''; + config.printService = { + url: 'http://printer.wms.gztbyc.com', + }; + // 仓库侧前端地址(通知文案快速查看链接) + config.frontendUrl = 'http://wms.wms.gztbyc.com'; + // 货主侧前端地址(货主群通知使用,与仓库侧不同) + config.storeFrontendUrl = 'http://store.wms.gztbyc.com'; + config.printRetryCompensation = { + enable: false, + intervalMs: 60 * 1000, + batchSize: 50, + force: false, + }; + // 工作台 token 超期强制下线定时任务配置 + config.workbenchTokenExpire = { + enable: true, + // 扫描间隔(毫秒),默认每小时扫描一次;开发环境可在 config.local.js 覆盖为短循环 + scanIntervalMs: 60 * 60 * 1000, + // token 有效期阈值(毫秒):token_updated_at 距今超过该时长则强制下线(默认 3 个月,按 30 天/月折算) + maxAgeMs: 3 * 30 * 24 * 60 * 60 * 1000, + // 单轮批处理大小(按 id 升序分批) + batchSize: 50, + }; + // 微信用户须知版本清理定时任务配置(每 1 小时执行,真实删除未使用且非最终版的历史版本释放磁盘空间) + config.wechatAgreementCleanup = { + // 开关:false 时不注册本定时任务 + enable: true, + // 触发 cron(秒 分 时 日 月 周):默认每 1 小时整点;本地环境可在 config.local.js 覆盖为短间隔 + cron: '0 0 * * * *', + // 单批硬删除行数(按 id 分批,走主键索引) + batchSize: 500, + }; + // 配送表(dispatch) → 历史表(history) 归档定时任务配置 + // 每日凌晨 06:00 把配送表超期订单(连同商品明细)迁入历史表,并更新订单索引表位置指针 + config.orderDeliveryArchive = { + // 开关:false 时不注册本定时任务 + enable: true, + // 触发 cron(秒 分 时 日 月 周):默认每日凌晨 06:00;本地环境可在 config.local.js 覆盖为短间隔 + cron: '0 0 6 * * *', + // 归档门槛一:订单创建时间(create_at)距今超过该月数即归档(dispath_time 为 NULL 的存量单只靠此条) + archiveAfterMonths: 4, + // 归档门槛二:迁移进配送表时间(dispath_time)距今超过该月数即归档 + dispatchStayMonths: 3, + // 单批条数(单批一个事务:写历史表 + 更新位置指针 + 删源行) + batchSize: 1000, + // 单仓库单轮最多批次数(异常情况下防死循环) + maxBatchesPerWarehouse: 200, + // 单轮总时长上限(毫秒):用尽后停止本轮,剩余订单下一轮继续(避免闯入业务高峰) + maxRunMs: 30 * 60 * 1000, + // 单批查询超时(毫秒) + queryTimeoutMs: 60 * 1000, + // 单批事务遇到死锁/锁等待的最大尝试次数 + batchMaxAttempts: 3, + // 跨进程互斥锁 TTL(秒),需覆盖单轮最长执行时间;进程被杀后锁到期自动释放 + lockTtlSeconds: 30 * 60, + }; + // 打印自定义区模板出口域名 + config.customAreaBaseUrl = 'https://api.ye4s.com'; + // 仓库前端独立部署:证书部署目录。 + // 保存接口(setting.warehouse.saveFrontCert)已不再写暂存文件,证书/私钥内容直接入库; + // 该目录保留供未来定时任务(Egg schedule 或外部 crontab)从库内 cert_pem/cert_key 读取内容后写 nginx 证书目录使用。 + config.frontConfig = { + certStagingDir: '/data/wms/cert-staging', + // 前端独立部署:域名验证(DNS TXT 校验) + cname: '', // 用户把域名 CNAME 指向的目标(未验证时返回给前端展示) + domainVerify: { + enable: true, // 是否注册域名验证定时任务 + interval: '10m', // 扫描间隔 + lockTtlSeconds: 600, // Redis 跨进程锁 TTL(略大于 interval) + // 单轮最多处理行数:单行最坏耗时 ≈ (DoH 端点数 3 + 系统 DNS 兜底 1) × timeoutMs(3000ms) = 12s, + // 20 行最坏 ≈ 240s,明显小于 lockTtlSeconds(600s) 与扫描间隔 interval(600s),跨进程锁不会被下一轮抢走 + batchSize: 20, + // DoH 端点列表(多端点按序尝试,任一端点拿到 TXT 值即立即返回,不再询问后续端点): + // 1) https://dns.alidns.com/resolve 阿里公共 DNS 的 JSON 接口,默认主解析器; + // 2) https://223.5.5.5/resolve 阿里公共 DNS 的 IP 直连入口(同一后端,域名侧解析异常时兜底); + // 3) https://doh.pub/dns-query 腾讯 doh.pub,保留但置于最后。 + // 为什么把 doh.pub 放最后:其负缓存(NODATA)可能长时间滞后于权威服务器。 + // 实测案例:主机 wmsv-aa4adaab13.wms.wms.gztbyc.com 的 TXT 记录 ddd9ae51cf95b488db544f23ccd01e7b 真实存在 + // (8.8.8.8 / 223.5.5.5 / nslookup / AliDNS DoH 四方一致),而 doh.pub 返回 Status=0 且 Answer 为空 + // (同一主机 A 查询亦 NODATA,其 SOA 序列号 2026081813 旧于 TXT 查询的 2026082815),重复两次结果一致。 + dohUrls: [ + 'https://dns.alidns.com/resolve', + 'https://223.5.5.5/resolve', + 'https://doh.pub/dns-query', + ], + // 兼容键(历史单端点配置):dohUrls 缺失/非法时 getDomainVerifyConfig() 回退用 [dohUrl];多端点生效后不应再依赖本键 + dohUrl: 'https://doh.pub/dns-query', + // 单个 DoH 端点、以及系统 DNS 兜底单次查询的超时(毫秒) + timeoutMs: 3000, + maxAttempts: 20, // 超过后不再自动重试(仍可手动 checkDomain) + }, + }; + return { ...config, ...userConfig, diff --git a/config/deploy.config.example.cjs b/config/deploy.config.example.cjs new file mode 100644 index 0000000..25d3a2a --- /dev/null +++ b/config/deploy.config.example.cjs @@ -0,0 +1,24 @@ +module.exports = { + production: { + host: '__FILL_SSH_HOST__', + port: 22, + username: '__FILL_SSH_USERNAME__', + privateKeyPath: 'C:/Users/your-user/.ssh/id_rsa', + deployRoot: '/www/wwwroot/qimen', + sharedDirs: [ 'logs', 'run', 'temp' ], + keepBackups: 5, + preDeployCommands: [ + 'node -v', + 'npm -v', + ], + postDeployCommands: [ + 'npm install --production', + 'npm run stop || true', + 'npm start', + ], + healthCheckUrl: 'http://127.0.0.1:6060/', + sshOptions: [ + 'StrictHostKeyChecking=accept-new', + ], + }, +}; \ No newline at end of file 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/database/config.js b/database/config.js new file mode 100644 index 0000000..9d0727a --- /dev/null +++ b/database/config.js @@ -0,0 +1,191 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); + +/** + * 判断值是否为普通对象(非数组、非 null)。 + * @param {*} value 待判断的值。 + * @return {boolean} 是普通对象返回 true。 + */ +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +/** + * 深合并两个普通对象,返回新对象,不修改入参。 + * @param {object} target 目标对象。 + * @param {object} source 来源对象。 + * @return {object} 合并后的新对象。 + */ +function mergeDeep(target, source) { + const output = isPlainObject(target) ? { ...target } : {}; + if (!isPlainObject(source)) { + return output; + } + + for (const [ key, value ] of Object.entries(source)) { + if (isPlainObject(value) && isPlainObject(output[key])) { + output[key] = mergeDeep(output[key], value); + } else if (isPlainObject(value)) { + output[key] = mergeDeep({}, value); + } else { + output[key] = value; + } + } + + return output; +} + +/** + * 加载 Egg 配置文件,兼容工厂函数与普通对象两种形式。 + * @param {string} configPath 配置文件绝对路径。 + * @return {object} 解析后的配置对象,文件不存在时返回空对象。 + */ +function loadEggConfig(configPath) { + if (!fs.existsSync(configPath)) { + return {}; + } + + const configFactory = require(configPath); + const config = typeof configFactory === 'function' + ? configFactory({ name: 'sequelize-cli', baseDir: path.dirname(path.dirname(configPath)) }) + : configFactory; + + return isPlainObject(config) ? config : {}; +} + +/** + * 从 Egg 配置中解析指定名称的 MySQL 客户端。 + * @param {object} appConfig Egg 应用配置。 + * @param {string} clientName MySQL 客户端名称。 + * @return {object} 解析出的 MySQL 客户端连接配置。 + * @throws {Error} 找不到指定客户端时抛出异常。 + */ +function resolveMysqlClient(appConfig, clientName) { + const clients = appConfig && appConfig.mysql && appConfig.mysql.clients; + if (clients && clients[clientName]) { + return clients[clientName]; + } + + if (appConfig && appConfig.mysql && appConfig.mysql.host) { + return appConfig.mysql; + } + + throw new Error(`MySQL client "${clientName}" not found in Egg config.`); +} + +/** + * 解析数据库连接目标标记,防止 NODE_ENV 残留导致误连生产库。 + * 优先级:WMS_DB_TARGET(显式标记) > NODE_ENV(兜底判断)。 + * @param {string | undefined} envTarget 显式目标标记(WMS_DB_TARGET 环境变量值)。 + * @param {string | undefined} nodeEnv NODE_ENV 环境变量值。 + * @return {{ target: string, source: string, explicit: boolean }} 解析结果:target 为 'production' 或 'local',source 为判定来源,explicit 表示是否显式指定。 + */ +function resolveDbTarget(envTarget, nodeEnv) { + const explicit = String(envTarget || '').trim().toLowerCase(); + if (explicit === 'production' || explicit === 'prod') { + return { target: 'production', source: 'WMS_DB_TARGET', explicit: true }; + } + if (explicit === 'local' || explicit === 'dev' || explicit === 'development') { + return { target: 'local', source: 'WMS_DB_TARGET', explicit: true }; + } + if (explicit) { + console.warn(`[DB-CONFIG] 未知的 WMS_DB_TARGET="${explicit}",已忽略并回退到 NODE_ENV 判断;可选值:local | production`); + } + + const nodeEnvLower = String(nodeEnv || '').trim().toLowerCase(); + return { + target: nodeEnvLower === 'production' ? 'production' : 'local', + source: nodeEnvLower === 'production' ? 'NODE_ENV' : 'default', + explicit: false, + }; +} + +/** + * 打印数据库连接目标提示(输出到 stderr,避免污染 stdout 上的 JSON 结果)。 + * production 目标额外打印醒目告警,提醒操作者确认连接目标。 + * @param {{ host: string, port: (number|string), database: string }} client 解析后的 MySQL 连接配置。 + * @param {{ target: string, source: string }} resolved 目标解析结果。 + * @return {void} + */ +function printDbTargetNotice(client, resolved) { + const detail = `host=${client.host} port=${client.port} database=${client.database} (判定来源: ${resolved.source})`; + if (resolved.target === 'production') { + console.warn(''); + console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); + console.warn('[DB-CONFIG] ⚠ 警告:当前解析为【生产数据库】连接目标'); + console.warn(`[DB-CONFIG] ⚠ ${detail}`); + console.warn('[DB-CONFIG] ⚠ 请确认这是预期环境;如属误判,请设置 WMS_DB_TARGET=local 强制使用开发库配置。'); + console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); + console.warn(''); + } else { + console.warn(`[DB-CONFIG] 数据库连接目标: ${detail}`); + } +} + +const projectRoot = path.resolve(__dirname, '..'); + +// 解析连接目标:显式标记 WMS_DB_TARGET 优先于 NODE_ENV 兜底判断, +// 避免终端残留 NODE_ENV=production 导致迁移/脚本误连生产库 +const dbTarget = resolveDbTarget(process.env.WMS_DB_TARGET, process.env.NODE_ENV); +const isProductionTarget = dbTarget.target === 'production'; + +let mysqlClient; +if (process.env.DB_HOST) { + mysqlClient = { + host: process.env.DB_HOST, + port: process.env.DB_PORT || 3306, + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_NAME || 'wms', + }; + printDbTargetNotice(mysqlClient, { target: 'manual', source: 'DB_HOST' }); +} else { + const defaultConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.default.js')); + const localConfig = isProductionTarget ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.js')); + const appConfig = mergeDeep(defaultConfig, localConfig); + const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms'; + if (isProductionTarget) { + const sequelizeConfig = appConfig && appConfig.sequelize; + if (sequelizeConfig && sequelizeConfig.host) { + mysqlClient = { + host: sequelizeConfig.host, + port: sequelizeConfig.port || 3306, + user: sequelizeConfig.username || sequelizeConfig.user, + password: sequelizeConfig.password, + database: sequelizeConfig.database || 'wms', + }; + } else { + mysqlClient = resolveMysqlClient(appConfig, clientName); + } + } else { + mysqlClient = resolveMysqlClient(appConfig, clientName); + } + printDbTargetNotice(mysqlClient, dbTarget); +} + +const baseConfig = { + username: mysqlClient.user, + password: mysqlClient.password, + database: mysqlClient.database, + host: mysqlClient.host, + port: Number(mysqlClient.port || 3306), + dialect: 'mysql', + logging: false, + define: { + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: true, + deletedAt: 'deleted_at', + }, +}; + +module.exports = { + development: { ...baseConfig }, + test: { ...baseConfig }, + production: { ...baseConfig }, + // 解析出的连接目标元信息,供迁移脚本等调用方做断言与提示(不影响 sequelize-cli 读取 env 配置) + dbTarget, +}; diff --git a/database/designs/after-sale-v2-design.md b/database/designs/after-sale-v2-design.md new file mode 100644 index 0000000..a9f44f4 --- /dev/null +++ b/database/designs/after-sale-v2-design.md @@ -0,0 +1,853 @@ +# 售后模块 V2 设计方案 + +> **状态**: 📋 v1 初稿,待评审 +> **设计日期**: 2026-08-09 +> **设计人**: wms-doc-agent +> **模块**: 售后管理(After-Sale) +> **表**: 2 张 — `wms_after_sale`(售后主表)、`wms_after_sale_detail`(售后进度步骤表) +> **说明**: 本文档为全新设计,替代已移除的旧版 `wms_after_sale_work_order` + `wms_after_sale_work_order_step` 体系。 + +--- + +## 一、设计背景 + +### 1.1 旧版问题 + +旧版售后工单(`after_sale_work_order` + `after_sale_work_order_step`)已于 2026-08-09 通过迁移 `20260809120000-drop-wms-after-sale-work-order.js` 正式移除。旧版存在以下核心问题: + +1. **多态关联难以维护**:使用 `business_type` + `business_sub_type` + `business_id` 三元组关联业务单据,导致: + - 查询需要动态拼接 JOIN 条件,性能差 + - 无法利用数据库外键约束保证数据完整性 + - 业务类型枚举膨胀,新增业务类型需改动多处代码 +2. **不支持多单据共存**:一个售后单只能关联一种业务单据,实际场景中退货退款往往同时涉及运单、发货订单、收货单等多张单据 +3. **覆盖场景不足**:旧版仅覆盖工单流转,未涵盖理赔、投诉等售后场景 +4. **缺少明细层级**:无法记录售后单中的商品明细(退什么货、换什么货、赔多少钱) + +### 1.2 V2 设计目标 + +| 目标 | 说明 | +|------|------| +| **废弃多态关联** | 每种业务单据使用独立字段,类型安全、查询高效 | +| **支持多单据共存** | 一个售后单可同时关联运单、发货订单、入库单、出库单、收货单等 | +| **覆盖全场景** | 按单据维度分类(订单/收货单/入库单/出库单),售后动作(退货/换货/理赔/投诉等)通过进度步骤体现 | +| **进度追溯** | `wms_after_sale_detail` 记录售后处理进度步骤,支持按步骤序号追踪操作人、操作动作、处理时间 | +| **可追溯** | 完整记录创建人、处理人、最终处理结果、完结时间 | + +### 1.3 与旧版核心差异 + +| 维度 | 旧版(已移除) | V2(本设计) | +|------|---------------|-------------| +| 主表 | `wms_after_sale_work_order` | `wms_after_sale` | +| 子表 | `wms_after_sale_work_order_step`(工单步骤流转) | `wms_after_sale_detail`(售后进度步骤) | +| 单据关联 | 多态三元组 `business_type + business_sub_type + business_id` | 每种单据独立字段组,可多个同时有值 | +| 多单据共存 | ❌ 不支持 | ✅ 支持 | +| 理赔 | ❌ 不支持 | ✅ 内建仓库理赔(`claim_needed / claim_amount / claim_status`)和运方理赔(`carrier_claim_needed / carrier_claim_amount / carrier_claim_status`) | +| 进度步骤 | ❌ `after_sale_work_order_step` | ✅ `wms_after_sale_detail` 记录步骤序号/操作人/操作动作/耗时 | +| 商品明细 | ❌ 无 | ❌ 不再独立建表,商品明细可存入 `remark` 或扩展 JSON 字段 | + +--- + +## 二、ER 图 + +```mermaid +erDiagram + wms_after_sale ||--o{ wms_after_sale_detail : "1:N" + + wms_after_sale { + BIGINT id PK "主键" + BIGINT warehouse_id "仓库ID" + BIGINT store_id "货主ID" + VARCHAR after_sale_no UK "售后单号,唯一" + VARCHAR type "售后类型" + VARCHAR sub_type "售后子类型" + VARCHAR status "状态" + INT priority "优先级" + VARCHAR title "标题" + TEXT description "描述" + BIGINT creator_id "创建人" + BIGINT inbox_message_id "关联消息ID" + VARCHAR role_group "角色组" + TEXT resolution "最终处理结果" + DATETIME resolved_at "完结时间" + TINYINT claim_needed "仓库理赔标记" + DECIMAL claim_amount "仓库理赔金额(元)" + VARCHAR claim_status "仓库理赔状态" + TINYINT carrier_claim_needed "运方理赔标记" + DECIMAL carrier_claim_amount "运方理赔金额(元)" + VARCHAR carrier_claim_status "运方理赔状态" + BIGINT waybill_id "运单ID" + VARCHAR waybill_no "运单号" + BIGINT order_delivery_id "发货订单ID" + VARCHAR order_delivery_no "发货订单号" + BIGINT entry_order_id "入库单ID" + VARCHAR entry_order_no "入库单号" + BIGINT order_stockout_id "出库单ID" + VARCHAR order_stockout_no "出库单号" + BIGINT receiving_id "收货单ID" + VARCHAR receiving_no "收货单号" + DATETIME created_at "创建时间" + DATETIME updated_at "更新时间" + DATETIME deleted_at "软删除" + } + + wms_after_sale_detail { + BIGINT id PK "主键" + BIGINT after_sale_id FK "关联售后主表" + VARCHAR step_status "步骤记录时主表状态" + BIGINT operator_id "操作人ID" + TEXT operator_snapshot "操作人信息快照" + VARCHAR action "操作动作" + TEXT remark "处理备注" + DATETIME started_at "步骤开始时间" + DATETIME completed_at "步骤完成时间" + DATETIME created_at "创建时间" + DATETIME updated_at "更新时间" + DATETIME deleted_at "软删除" + } +``` + +### 关联关系说明 + +``` +wms_after_sale + ├─ warehouse_id → stores.id(仓库,逻辑关联) + ├─ store_id → stores.id(货主,逻辑关联) + ├─ creator_id → accounts.id(创建人,逻辑关联) + ├─ inbox_message_id → wms_inbox_message.id(站内信消息,逻辑关联) + ├─ waybill_id → wms_order_express.id(运单,逻辑关联) + ├─ order_delivery_id → wms_order_delivery.id(发货订单,逻辑关联) + ├─ entry_order_id → wms_entry_order.id(入库单,逻辑关联) + ├─ order_stockout_id → wms_order_stockout.id(出库单,逻辑关联) + └─ receiving_id → wms_receiving.id(收货单,逻辑关联) + +wms_after_sale_detail + └─ after_sale_id → wms_after_sale.id(级联删除) +``` + +> **注意**:所有关联均为逻辑关联(不做物理外键),遵循项目现有惯例。 + +--- + +## 三、数据库表 + +### 3.1 表 A:售后主表 `wms_after_sale` + +#### 3.1.1 基础字段 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 仓库ID | +| `store_id` | `BIGINT UNSIGNED` | — | NULL | 货主ID | + +#### 3.1.2 售后信息 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `after_sale_no` | `VARCHAR(50)` | ✅ | — | **售后单号**,唯一索引。生成规则:前缀 `AS` + 日期 `YYYYMMDD` + 6 位序号(当天同仓库自增),如 `AS20260809000001`。参考波次号 `wave_no` 生成逻辑。 | +| `type` | `VARCHAR(20)` | ✅ | — | 售后类型,枚举见 §3.1.6 | +| `sub_type` | `VARCHAR(50)` | ✅ | — | 售后子类型,枚举见 §3.1.6,与 type 组成二级分类 | +| `status` | `VARCHAR(20)` | ✅ | `pending` | 售后状态,枚举及流转见 §五 | +| `priority` | `INT(11)` | ✅ | 0 | 优先级,数值越大越优先(0=普通,10=紧急) | +| `title` | `VARCHAR(200)` | ✅ | — | 售后标题(简要描述) | +| `description` | `TEXT` | — | NULL | 售后详细描述 | + +#### 3.1.3 人员信息 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `creator_id` | `BIGINT UNSIGNED` | ✅ | — | 创建人账户ID(关联 `accounts` 表) | +| `role_group` | `VARCHAR(50)` | — | NULL | 当前处理角色组,用于角色维度查询待处理工单和转单。枚举见 §3.1.6。NULL 表示未分配。 | +| `inbox_message_id` | `BIGINT UNSIGNED` | — | NULL | 关联 `wms_inbox_message.id`(站内信消息主键)。为空表示无关联信息,非空表示该售后单由对应站内信消息创建或关联。 | + +#### 3.1.4 处理结果 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `resolution` | `TEXT` | — | NULL | 最终处理结果说明 | +| `resolved_at` | `DATETIME` | — | NULL | 完结时间(状态变为 `completed` 时写入) | + +#### 3.1.5 仓库理赔 & 运方理赔 + +**仓库理赔**: + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `claim_needed` | `TINYINT(1)` | ✅ | 0 | 仓库理赔标记:0=不需要,1=需要 | +| `claim_amount` | `DECIMAL(12,2)` | — | NULL | 仓库理赔金额,单位:人民币(元),claim_needed=1 时可填写 | +| `claim_status` | `VARCHAR(20)` | — | NULL | 仓库理赔状态,枚举见 §3.1.6,仅 `claim_needed=1` 时有意义 | + +**运方理赔**: + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `carrier_claim_needed` | `TINYINT(1)` | ✅ | 0 | 运方理赔标记:0=不需要,1=需要 | +| `carrier_claim_amount` | `DECIMAL(12,2)` | — | NULL | 运方理赔金额,单位:人民币(元),carrier_claim_needed=1 时可填写 | +| `carrier_claim_status` | `VARCHAR(20)` | — | NULL | 运方理赔状态,枚举见 §3.1.6,仅 `carrier_claim_needed=1` 时有意义 | + +#### 3.1.6 类型与状态枚举 + +**售后类型 `type` + 售后子类型 `sub_type`**: + +> 售后类型表示售后单主要关联的业务单据类型,售后子类型表示具体售后原因分类,两者组成二级分类。具体的售后动作(退货/换货/理赔/投诉等)通过进度步骤和最终处理结果体现。 + +| type | 说明 | sub_type | +|------|------|----------| +| `order` | 订单 | `damage` 破损, `missing_item` 少发, `mis_shipment` 错发, `wrong_sku` 错品, `quality_issue` 质量问题, `delivery_delay` 发货延迟, `logistics_issue` 物流异常, `rejected` 客户拒收, `intercept` 拦截, `verify_delivery` 核实签收, `urge` 催件, `extra_item` 多发, `change_address` 改地址, `change_carrier` 换快递, `weight_issue` 重量异常, `freight_issue` 运费争议, `other` 其他 | +| `receiving` | 收货单 | `shortage` 少货, `damage` 破损, `wrong_sku` 错品, `quality_issue` 质量问题, `other` 其他 | +| `entry` | 入库单 | `shortage` 少货, `damage` 破损, `wrong_sku` 错品, `quality_issue` 质量问题, `other` 其他 | +| `stockout` | 出库单 | `return_issue` 退货异常, `wrong_outbound` 错发, `shortage` 少发, `other` 其他 | + +**Model 层常量定义**(`app/model/after_sale.js`): + +```javascript +// app/model/after_sale.js 中的常量定义 +const AFTER_SALE_TYPES = [ + { + name: '订单', + type: 'order', + subType: [ + { name: '破损', value: 'damage' }, + { name: '少发', value: 'missing_item' }, + { name: '错发', value: 'mis_shipment' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '发货延迟', value: 'delivery_delay' }, + { name: '物流异常', value: 'logistics_issue' }, + { name: '客户拒收', value: 'rejected' }, + { name: '拦截', value: 'intercept' }, + { name: '核实签收', value: 'verify_delivery' }, + { name: '催件', value: 'urge' }, + { name: '多发', value: 'extra_item' }, + { name: '改地址', value: 'change_address' }, + { name: '换快递', value: 'change_carrier' }, + { name: '重量异常', value: 'weight_issue' }, + { name: '运费争议', value: 'freight_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '收货单', + type: 'receiving', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '入库单', + type: 'entry', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '出库单', + type: 'stockout', + subType: [ + { name: '退货异常', value: 'return_issue' }, + { name: '错发', value: 'wrong_outbound' }, + { name: '少发', value: 'shortage' }, + { name: '其他', value: 'other' }, + ], + }, +]; +``` + +**角色组 `role_group`**: + +| 值 | 说明 | +|----|------| +| `customer_service` | 客服组 | +| `warehouse` | 仓库组 | +| `finance` | 财务组 | + +> 设计理由:运方(快递公司)是外部角色,不登录 WMS 系统,不纳入内部角色组。 + +**售后状态 `status`**: + +| 值 | 说明 | +|----|------| +| `pending` | 待处理 | +| `processing` | 处理中 | +| `pending_feedback` | 等待外部反馈(内部处理完成,等待外部反馈后再决定是否继续处理) | +| `completed` | 已完成 | +| `closed` | 已关闭 | +| `cancelled` | 已取消 | + +**理赔状态(仓库理赔 & 运方理赔通用枚举)**: + +| 值 | 说明 | +|----|------| +| `pending` | 待理赔 | +| `reviewing` | 审核中 | +| `approved` | 已通过 | +| `paid` | 已打款 | +| `monthly` | 月结 | +| `rejected` | 已拒绝 | + +#### 3.1.7 单据关联字段(核心设计) + +> **设计要点**:每种业务单据使用独立字段组(ID + 单号冗余),替代旧版多态关联。多个字段组可同时有值,实现"一个售后单关联多种单据"。 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `waybill_id` | `BIGINT UNSIGNED` | — | NULL | 运单ID(关联 `wms_order_express.id`) | +| `waybill_no` | `VARCHAR(50)` | — | NULL | 运单号(冗余字段,方便查询展示) | +| `order_delivery_id` | `BIGINT UNSIGNED` | — | NULL | 发货订单ID(关联 `wms_order_delivery.id`) | +| `order_delivery_no` | `VARCHAR(50)` | — | NULL | 发货订单号(冗余字段) | +| `entry_order_id` | `BIGINT UNSIGNED` | — | NULL | 入库单ID(关联 `wms_entry_order.id`) | +| `entry_order_no` | `VARCHAR(50)` | — | NULL | 入库单号(冗余字段) | +| `order_stockout_id` | `BIGINT UNSIGNED` | — | NULL | 出库单/退货出库单ID(关联 `wms_order_stockout.id`) | +| `order_stockout_no` | `VARCHAR(50)` | — | NULL | 出库单号(冗余字段) | +| `receiving_id` | `BIGINT UNSIGNED` | — | NULL | 收货单ID(关联 `wms_receiving.id`) | +| `receiving_no` | `VARCHAR(50)` | — | NULL | 收货单号(冗余字段) | + +> **冗余字段说明**:`_no` 后缀字段为冗余存储,目的是在售后列表查询时避免 JOIN 各业务表。写入时从对应业务表同步取数,后续若业务表单号变更需同步更新(建议通过业务 hook 或定时任务保证最终一致)。 + +#### 3.1.8 时间戳 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `created_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP` | 创建时间 | +| `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | +| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | + +--- + +### 3.2 表 B:售后进度步骤表 `wms_after_sale_detail` + +用于记录售后单的处理进度步骤(谁在什么时间做了什么操作)。步骤按 `created_at` 自然时间排序,通过 `action` 描述步骤内容,可记录步骤开始/完成时间、操作人及操作快照。 + +#### 3.2.1 字段定义 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `after_sale_id` | `BIGINT UNSIGNED` | ✅ | — | 关联售后主表ID(`wms_after_sale.id`) | +| `step_status` | `VARCHAR(20)` | ✅ | `processing` | 步骤记录时售后主表的状态,与 `wms_after_sale.status` 完全一致: pending / processing / completed / closed / cancelled。每次写入步骤时取主表当前 status 快照 | +| `operator_id` | `BIGINT UNSIGNED` | — | NULL | 操作人账户ID(关联 `accounts` 表);可为空,外部系统回调/自动触发的步骤无人操作 | +| `operator_snapshot` | `TEXT` | — | NULL | 操作人信息快照(JSON),如 `{"name":"张三","role":"客服"}`,防止账户删除后历史丢失 | +| `action` | `VARCHAR(100)` | — | NULL | 操作动作描述,如"确认收货"、"审核驳回"、"发起退款" | +| `remark` | `TEXT` | — | NULL | 处理备注 | +| `started_at` | `DATETIME` | — | NULL | 步骤开始时间 | +| `completed_at` | `DATETIME` | — | NULL | 步骤完成时间 | +| `created_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP` | 创建时间 | +| `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | +| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | + +#### 3.2.2 步骤状态 `step_status` 说明 + +`step_status` 与 `wms_after_sale.status` 完全一致(类型、枚举均相同),每次写入步骤时记录步骤发生时主表的当前状态快照。枚举值: + +| 值 | 说明 | +|----|------| +| `pending` | 待处理 | +| `processing` | 处理中 | +| `completed` | 已完成 | +| `closed` | 已关闭 | +| `cancelled` | 已取消 | + +> **设计考量**:`step_status` 记录的是"该步骤发生时,售后主表处于什么状态",而非步骤本身的"进行中/已完成"标记。这使得每条步骤都能直接追溯到该步骤执行时的工单状态上下文,无需 JOIN 主表查阅历史状态。步骤按 `created_at` 自然时间排序。 + +### 3.2.3 附件关联 + +售后进度步骤可通过 `wms_file_reference` 表挂载附件(如破损照片、签收凭证、理赔单据等)。 + +**绑定方式:** + +| wms_file_reference 字段 | 值 | 说明 | +|--------------------------|-----|------| +| `business_type` | `after_sale_detail` | 售后进度步骤 | +| `business_id` | `{wms_after_sale_detail.id}` | 步骤主键ID | + +**典型场景:** +- 仓库验货步骤上传破损商品照片 +- 客服接单步骤上传客户提供的聊天截图 +- 运方理赔步骤上传快递破损证明 +- 退款步骤上传打款凭证截图 + +**查询示例:** +```sql +-- 查询某售后单所有步骤的附件 +SELECT f.*, fr.business_id AS step_id +FROM wms_file_reference fr +JOIN wms_file f ON f.id = fr.file_id +WHERE fr.business_type = 'after_sale_detail' + AND fr.business_id IN ( + SELECT id FROM wms_after_sale_detail WHERE after_sale_id = ? + ); +``` + +--- + +## 四、索引设计 + +### 4.1 `wms_after_sale` 索引 + +| 索引名 | 字段 | 类型 | 说明 | +|--------|------|------|------| +| `PRIMARY` | `id` | 主键 | — | +| `uk_after_sale_no` | `after_sale_no` | 唯一 | 售后单号唯一约束 | +| `idx_warehouse_status` | `warehouse_id`, `status`, `deleted_at` | 普通 | 按仓库+状态查询售后列表(最高频) | +| `idx_warehouse_type` | `warehouse_id`, `type`, `deleted_at` | 普通 | 按仓库+类型筛选 | +| `idx_type_subtype` | `warehouse_id`, `type`, `sub_type`, `deleted_at` | 普通 | 按仓库+类型+子类型筛选 | +| `idx_store_id` | `store_id`, `deleted_at` | 普通 | 按货主查询 | +| `idx_creator_id` | `creator_id`, `deleted_at` | 普通 | 按创建人查询 | +| `idx_role_group` | `role_group`, `status`, `deleted_at` | 普通 | 按角色组+状态查询待处理工单(角色维度) | +| `idx_created_at` | `warehouse_id`, `created_at` | 普通 | 按仓库+时间排序分页 | +| `idx_waybill_id` | `waybill_id` | 普通 | 按运单反查售后单 | +| `idx_order_delivery_id` | `order_delivery_id` | 普通 | 按发货订单反查售后单 | +| `idx_entry_order_id` | `entry_order_id` | 普通 | 按入库单反查售后单 | +| `idx_order_stockout_id` | `order_stockout_id` | 普通 | 按出库单反查售后单 | +| `idx_receiving_id` | `receiving_id` | 普通 | 按收货单反查售后单 | +| `idx_carrier_claim_status` | `carrier_claim_status` | 普通 | 按运方理赔状态筛选 | +| `idx_inbox_message_id` | `inbox_message_id` | 普通 | 按站内信消息反查售后单 | + +### 4.2 `wms_after_sale_detail` 索引 + +| 索引名 | 字段 | 类型 | 说明 | +|--------|------|------|------| +| `PRIMARY` | `id` | 主键 | — | +| `idx_after_sale_id` | `after_sale_id` | 普通 | 按售后单查询进度步骤(最高频) | +| `idx_operator_id` | `operator_id` | 普通 | 按操作人查询其处理的步骤 | + +--- + +## 五、状态流转 + +```mermaid +stateDiagram-v2 + [*] --> pending: 创建售后单 + pending --> processing: 指派处理人 / 开始处理 + pending --> cancelled: 取消 + processing --> pending_feedback: 内部处理完毕,等待外部反馈 + processing --> completed: 处理完成 + processing --> closed: 强制关闭 + pending_feedback --> processing: 收到外部反馈,继续处理 + pending_feedback --> completed: 外部反馈确认完成 + completed --> [*] + closed --> [*] + cancelled --> [*] +``` + +| 流转 | 触发条件 | 说明 | +|------|---------|------| +| `pending` → `processing` | 指派处理人 or 手动开始处理 | 通过 `wms_after_sale_detail` 记录的处理步骤追踪 | +| `pending` → `cancelled` | 创建人取消 | 仅待处理状态可取消 | +| `processing` → `pending_feedback` | 内部处理完毕,等待外部反馈 | 如已将拦截信息发给运方,等待运方反馈拦截结果 | +| `processing` → `completed` | 处理完毕 | 写入 `resolution` + `resolved_at` | +| `processing` → `closed` | 管理员强制关闭 | 如重复单、无效单等 | +| `pending_feedback` → `processing` | 收到外部反馈,继续处理 | 如运方反馈已拦截/未拦截,回到内部通知客户 | +| `pending_feedback` → `completed` | 外部反馈确认完成 | 如平台退款回调确认到账 | + +**理赔状态流转**(仓库理赔 & 运方理赔通用):`pending` → `reviewing` → `approved` → `paid`,任意阶段可 → `rejected`,或走 `monthly`(月结)通道。 + +> `wms_after_sale_detail` 即操作日志:每条进度步骤记录操作人、操作动作、处理备注、开始/完成时间,已完整覆盖状态变更追踪需求,无需额外日志表。 + +--- + +## 六、典型使用场景 + +### 场景1:订单售后(退货退款,关联运单 + 收货单) + +``` +售后单 type=order, sub_type=damage, role_group=customer_service +├─ inbox_message_id: 12345(关联站内信消息,客户发送"破损"指令触发) +├─ waybill_id / waybill_no: 客户寄回的快递单号 +├─ receiving_id / receiving_no: 仓库收货单 +└─ 进度步骤: + ├─ step_status=processing, operator_id=1001, action=客服接单-受理退货申请 + ├─ step_status=processing, operator_id=2001, action=仓库收货-确认收货入库 + └─ step_status=processing, action=退款打款 +``` + +> **转单说明**:当客服接单后发现需要仓库核实实物时,可将 `role_group` 从 `customer_service` 更新为 `warehouse`,仓库组即可在自己的待办列表中看到该工单。 + +### 场景2:订单售后(换货,关联运单 + 发货订单) + +``` +售后单 type=order, sub_type=quality_issue +├─ waybill_id / waybill_no: 客户寄回的快递单号 +├─ order_delivery_id / order_delivery_no: 仓库补发的发货订单 +└─ 进度步骤: + ├─ step_status=processing, action=客服接单-确认换货申请 + ├─ step_status=processing, action=退回入库-客户退回商品已入库 + └─ step_status=processing, action=补发换货-仓库补发新商品 +``` + +### 场景3:订单售后(仓库理赔) + +``` +售后单 type=order, sub_type=damage +├─ claim_needed=1, claim_amount=50.00, claim_status=pending +└─ 进度步骤: + ├─ step_status=processing, action=客服接单-受理仓库理赔 + ├─ step_status=processing, action=核实定损, remark=仓库出库破损, 核定赔偿50元 + └─ step_status=processing, action=审批打款 +``` + +### 场景3b:订单售后(运方理赔) + +``` +售后单 type=order, sub_type=logistics_issue +├─ carrier_claim_needed=1, carrier_claim_amount=200.00, carrier_claim_status=pending +├─ waybill_id / waybill_no: 涉损运单 +└─ 进度步骤: + ├─ step_status=processing, action=客服接单-受理运方理赔 + ├─ step_status=processing, action=核实定损, remark=运输途中破损, 核定赔偿200元 + └─ step_status=processing, action=快递审批 +``` + +> **说明**:仓库理赔与运方理赔可同时存在(如货物在仓库出库&运输途中均发生破损),分别使用 `claim_*` 和 `carrier_claim_*` 字段组记录。 + +### 场景4:订单售后(多单据共存:退货退款 + 运单 + 收货单 + 出库单) + +``` +售后单 type=order, sub_type=damage, role_group=warehouse +├─ waybill_id / waybill_no: 客户退货快递 +├─ receiving_id / receiving_no: 仓库收货单 +├─ order_stockout_id / order_stockout_no: 退货出库单 +└─ 进度步骤: + ├─ step_status=processing, action=客服接单-批量退货受理 + ├─ step_status=processing, operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2) + ├─ step_status=processing, action=退货入库 + └─ step_status=processing, action=退款打款 +``` + +> **说明**:此场景中 `role_group=warehouse` 表示当前由仓库组负责验货入库环节;验货完成后如需财务退款,转单时将 `role_group` 更新为 `finance`。 + +--- + +## 七、迁移计划 + +### 7.1 迁移文件 + +``` +database/migrations/YYYYMMDDHHMMSS-create-wms-after-sale.js +database/migrations/YYYYMMDDHHMMSS-create-wms-after-sale-detail.js +``` + +### 7.2 Model 文件 + +``` +app/model/after_sale.js → wms_after_sale +app/model/after_sale_detail.js → wms_after_sale_detail +``` + +### 7.3 后续扩展(不纳入本期) + +| 扩展项 | 说明 | +|--------|------| +| 批量创建 | 按运单号/订单号批量生成售后单 | +| 自动创建规则 | 如收到退货快递自动创建售后单 | +| 售后统计看板 | 按仓库/类型/状态统计售后量、理赔金额等 | + +--- + +## 八、版本记录 + +| 版本 | 日期 | 变更内容 | 作者 | +|------|------|---------|------| +| v1 | 2026-08-09 | 初稿,待评审 | wms-doc-agent | + +--- + +## 九、权限设计 + +售后模块的角色组通过 `wms_permission` 表中 `type='block'` 的权限条目来承载,与主表 `role_group` 字段一一对应。 + +### 9.1 Block 权限(角色组区分) + +> ID 516-523 为售后模块固定 ID。 + +| ID | meta_title | type | 对应 role_group | +|----|-----------|------|-----------------| +| 516 | 售后-客服组 | `block` | `customer_service` | +| 517 | 售后-仓库组 | `block` | `warehouse` | +| 518 | 售后-财务组 | `block` | `finance` | + +> 生产组主管(role_code=03)和拣货组组长(role_code=021)使用仓库组 block(517),共享仓库组视角。 + +### 9.2 页面权限 + +| ID | path | meta_title | type | parent_id | +|----|------|-----------|------|-----------| +| 519 | `afterSale` | 售后管理 | `web_pages` | null | +| 520 | `afterSale.list` | 售后列表 | `web_pages` | 519 | +| 521 | `afterSale.detail` | 售后明细 | `web_pages` | 519 | + +### 9.3 API 权限 + +| ID | path | meta_title | type | +|----|------|-----------|------| +| 522 | `afterSale.workList` | API:售后工作列表查询 | `api` | +| 523 | `afterSale.auditList` | API:售后审计列表查询 | `api` | +| 508 | `afterSale.detail` | API:售后明细查询 | `api` | +| 509 | `afterSale.create` | API:创建售后单 | `api` | +| 510 | `afterSale.update` | API:更新售后单 | `api` | +| 511 | `afterSale.transfer` | API:售后转单 | `api` | +| 512 | `afterSale.handleWorkOrder` | API:处理工单 | `api` | +| 513 | `afterSale.registerClaim` | API:登记理赔 | `api` | +| 514 | `afterSale.export` | API:售后导出 | `api` | +| 515 | `afterSale.exportTaskProgress` | API:导出进度查询 | `api` | + +### 9.4 角色权限绑定 + +| 角色 | 角色组 block | 页面 | API | +|------|------------|------|-----| +| 客服 | 516 | 519, 520, 521 | 522, 523, 508, 509, 510, 511, 512, 513, 514, 515 | +| 仓库 | 517 | 519, 520, 521 | 522, 508, 510, 512 | +| 生产组-主管 | 517 | 519, 520, 521 | 522, 508, 510, 512 | +| 拣货组-组长 | 517 | 519, 520, 521 | 522, 508, 510, 512 | +| 财务 | 518 | 519, 520, 521 | 522, 508 | +| 经理 | — | 519, 520, 521 | 522, 523, 508, 509, 510, 511, 512, 513, 514, 515 | + +> - 客服:全部权限(创建、更新、转单、查理赔) +> - 仓库:只读查询 + 更新处理结果 +> - 生产组-主管 / 拣货组-组长:共享仓库组视角(同仓库组权限),处理退货验货入库等实物操作。普通生产组员工不授权任何售后权限。 +> - 财务:只读查询(理赔审核通过财务系统操作,不走 WMS) +> - 经理:全部售后权限 + +> **生产组其他角色**(普通员工、复核、其他普工)不授权任何售后权限。 +> **财务组角色**:role_code=`finance`,role_name=`财务组`,自动创建并授权。 + +--- + +## 十、Methods API 设计 + +### 10.1 概述 + +售后模块 API method 统一以 `afterSale.` 为前缀,使用 `/system` 网关接入。工作列表与审计列表分离,导出采用异步任务模式。 + +### 10.2 列表一:工作列表 `afterSale.workList` + +**定位**:仓库内员工看到自己角色组需要处理的工单。 + +**可见性规则:** +- 创建时 `role_group` 默认为 `customer_service`,仅客服组可见 +- 转单后(如 `customer_service` → `warehouse`),原角色组不再可见,目标角色组可见 +- 用户通过角色绑定的 block 权限(516/517/518)确定可见哪些 role_group +- **核心逻辑**:`WHERE role_group IN (用户拥有的售后block对应的role_group)` 且 `status != 'completed' AND status != 'cancelled'` + +**method 定义:** +```json +{ + "method": "afterSale.workList", + "description": "售后工作列表。仅返回当前用户角色组负责的待处理工单。创建时默认进入客服组,转单后原组不可见、目标组可见。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body", "description": "分页参数 page/pageSize" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "筛选条件:支持 type/sub_type/status/priority/after_sale_no/waybill_no 等字段筛选,以及 quickWhere 快捷搜索" }, + { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数 sortField/sortOrder,默认按 priority DESC, created_at DESC" } + ], + "response": [ + { "name": "list", "type": "array", "required": true, "description": "售后工单列表" }, + { "name": "pagination", "type": "object", "required": true, "description": "分页信息" } + ] +} +``` + +### 10.3 列表二:审计列表 `afterSale.auditList` + +**定位**:所有售后单全局视图,不限角色组,用于审计和管理。 + +**可见性规则:** +- 所有 `status` 的工单均可见(包括 completed/cancelled) +- 不限 `role_group` +- 与工作列表共享 where/sort/pagination 参数格式 + +**method 定义:** +```json +{ + "method": "afterSale.auditList", + "description": "售后审计列表。全局售后单视图,不限角色组、不限状态,用于审计和统计分析。入参与 afterSale.workList 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "同 workList,额外支持 claim_status/carrier_claim_status 筛选" }, + { "name": "sort", "type": "object", "required": false, "source": "body" } + ], + "response": [ + { "name": "list", "type": "array", "required": true }, + { "name": "pagination", "type": "object", "required": true } + ] +} +``` + +### 10.4 导出接口 `afterSale.export` + `afterSale.exportTaskProgress` + +参考项目现有导出模式(`order.export` / `order.exportTaskProgress`)。 + +**`afterSale.export`:** +```json +{ + "method": "afterSale.export", + "description": "提交售后审计列表导出任务(异步)。入参 where/sort 与 afterSale.auditList 完全一致。提交后立即返回 task_id,后台异步执行 Excel 生成并上传 COS。通过 afterSale.exportTaskProgress 查询进度和下载链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "where", "type": "object", "required": false, "source": "body", "description": "查询条件,与 afterSale.auditList 的 where 语义一致" }, + { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数,与 afterSale.auditList 的 sort 语义一致" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true, "description": "导出任务ID" }, + { "name": "status", "type": "string", "required": true, "description": "submitted/running/success/failed" }, + { "name": "progress", "type": "number", "required": true, "description": "0-100" }, + { "name": "message", "type": "string", "required": true } + ] +} +``` + +**`afterSale.exportTaskProgress`:** +```json +{ + "method": "afterSale.exportTaskProgress", + "description": "查询售后导出任务进度和下载链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "task_id", "type": "string", "required": true, "source": "body", "description": "导出任务ID" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true }, + { "name": "status", "type": "string", "required": true }, + { "name": "progress", "type": "number", "required": true }, + { "name": "download_url", "type": "string", "required": false, "description": "status=success 时返回 Excel 下载链接" }, + { "name": "error", "type": "string", "required": false, "description": "status=failed 时返回错误信息" } + ] +} +``` + +### 10.5 其他 methods + +| method | 说明 | 权限 | +|--------|------|------| +| `afterSale.create` | 创建售后单 | 客服 | +| `afterSale.detail` | 售后明细(主表+步骤列表) | 全部 | +| `afterSale.update` | 更新售后单 | 客服/仓库 | +| `afterSale.transfer` | 转单(更新 role_group) | 客服 | +| `afterSale.handleWorkOrder` | 处理工单(写步骤+绑附件) | 当前 role_group 匹配的用户 | +| `afterSale.registerClaim` | 登记售后理赔信息(仓库理赔+运方理赔) | 客服 | + +### 10.6 导出流程说明 + +导出流程参考项目现有异步导出模式(`order.export`): + +1. 客户端调用 `afterSale.export` 提交导出任务,服务端生成 `task_id`,在 Redis 中初始化任务状态为 `submitted` +2. 通过 `setImmediate` 启动异步执行,立即返回 `task_id` 给客户端 +3. 后台任务分页查询售后数据,使用 ExcelJS 流式写入 Excel 文件 +4. Excel 生成完成后上传至 COS,获取下载链接 +5. 更新 Redis 中任务状态为 `success`,并写入 `download_url` +6. 若任一步骤失败,更新任务状态为 `failed`,并写入错误信息 +7. 客户端轮询 `afterSale.exportTaskProgress` 获取进度和下载链接 + +**Redis 缓存规范:** +- Key 格式:`after_sale_export_task_{task_id}` +- TTL:30 分钟(任务完成后自动过期) + +### 10.7 处理工单 `afterSale.handleWorkOrder` + +```json +{ + "method": "afterSale.handleWorkOrder", + "description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。步骤 action 由服务端固定为\"处理工单\",前端无需传入。status 不填或填错默认 processing。非客服组处理完成后自动转回客服组继续跟进。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID(wms_after_sale.id)" }, + { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态: processing | completed | closed | cancelled。不填或填错默认 processing。注意:pending 不适用于处理操作" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组,如 [123, 456]。处理时自动绑定到本次步骤。" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true, "description": "本次写入的 wms_after_sale_detail.id" }, + { "name": "after_sale_id", "type": "integer", "required": true } + ], + "errors": [ + { "code": 400, "message": "工单不存在或参数缺失" }, + { "code": 500, "message": "处理失败" } + ] +} +``` + +**处理流程:** + +1. 校验工单 `id` 存在,且当前用户 `role_group` 与工单 `role_group` 匹配(否则 403) +2. 从登录上下文(JWT token)提取操作人 `operator_id` 和 `operator_snapshot` +3. 写入 `wms_after_sale_detail`: + - `step_status` = 主表当前 status(由 safeStatus 决定,不填或填错默认 processing) + - `action` = 服务端固定 `"处理工单"` + - `remark` = 入参 `remark` + - `operator_id` / `operator_snapshot` = 当前用户 + - `started_at = now`, `completed_at = now` +4. 若传入了 `attachment_ids`,遍历写入 `wms_file_reference`: + - `business_type = 'after_sale_detail'` + - `business_id` = 刚写入的 `detail.id` + - `file_id = attachment_id` +5. 更新 `wms_after_sale.status`:始终写入 safeStatus(默认 processing,白名单校验,不含 pending) +6. 若当前 `role_group` ≠ `'customer_service'` 且 status ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进) +7. 若 status = `'completed'`,同时写入 `resolution` 和 `resolved_at` + +### 10.8 理赔登记 `afterSale.registerClaim` + +```json +{ + "method": "afterSale.registerClaim", + "description": "登记售后理赔信息。一次性填入仓库理赔和运方理赔的全部字段,同时写入进度步骤。两套理赔字段可同时填写(双赔场景)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID" }, + { "name": "claim_needed", "type": "integer", "required": false, "source": "body", "description": "仓库理赔标记:0/1" }, + { "name": "claim_amount", "type": "number", "required": false, "source": "body", "description": "仓库理赔金额(元)" }, + { "name": "claim_status", "type": "string", "required": false, "source": "body", "description": "仓库理赔状态:pending/reviewing/approved/paid/monthly/rejected" }, + { "name": "carrier_claim_needed", "type": "integer", "required": false, "source": "body", "description": "运方理赔标记:0/1" }, + { "name": "carrier_claim_amount", "type": "number", "required": false, "source": "body", "description": "运方理赔金额(元)" }, + { "name": "carrier_claim_status", "type": "string", "required": false, "source": "body", "description": "运方理赔状态:pending/reviewing/approved/paid/monthly/rejected" }, + { "name": "action", "type": "string", "required": true, "source": "body", "description": "操作动作描述,如"登记仓库理赔"、"登记运方理赔"" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注,如"快递破损核定赔200元"" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组(破损照片、理赔单据等)" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true, "description": "本次写入的步骤ID" }, + { "name": "after_sale_id", "type": "integer", "required": true } + ], + "errors": [ + { "code": 400, "message": "工单不存在或参数缺失" }, + { "code": 500, "message": "登记失败" } + ] +} +``` + +**处理流程:** + +1. 校验工单 `id` 存在 +2. 从登录上下文提取操作人信息 +3. 更新 `wms_after_sale` 中传入的非空理赔字段(`claim_needed/amount/status`、`carrier_claim_needed/amount/status`) +4. 写入 `wms_after_sale_detail`(step_status=主表当前 status,action/remark/operator) +5. 若有 `attachment_ids`,绑定到本次步骤 + +**使用场景:** +- 单赔:只传仓库理赔字段组,运方字段不传 +- 单赔:只传运方理赔字段组,仓库字段不传 +- 双赔:同时传两套字段(仓库+运输途中均破损) + +--- + +## 十一、待评审事项 + +- [ ] 售后单号 `after_sale_no` 生成规则:格式已确定为 `AS + YYYYMMDD + 6位序号`(如 `AS20260809000001`),待确认序号从 1 起始还是从指定起始值起 +- [ ] 仓库理赔(`claim_status`)和运方理赔(`carrier_claim_status`)是否需要更细粒度的流转(如:待审核 → 审核通过 → 已打款 → 月结) +- [ ] 进度步骤表是否需要记录商品明细信息(如退货 SKU/数量),或通过 `remark` JSON 扩展存储 +- [ ] 单据关联字段是否需要扩展到更多类型(如质检单 `quality_check_id`) +- [ ] 是否需要支持售后单之间的关联(如换货单关联原退货单) diff --git a/database/designs/inbox-message-module-design.md b/database/designs/inbox-message-module-design.md new file mode 100644 index 0000000..14e4651 --- /dev/null +++ b/database/designs/inbox-message-module-design.md @@ -0,0 +1,441 @@ +# 站内信(Inbox)模块设计方案 + +> **状态**: 📋 设计中 +> **设计日期**: 2026-08-03 +> **设计人**: wms-test-agent +> **模块**: `app/service/inbox/`,独立文件模块 +> **表**: 1 张 — `wms_inbox_message` + +--- + +## 一、概念 + +消息推送状态追踪表。不重复存储消息内容(消息体由 IM 回调 / API 请求各自管理),只记录**谁发来的、要推到哪、推送状态**。收件(inbound)和回信(outbound)共表,`direction` + `parent_id` 形成对话链。 + +``` + inbound(外部 → WMS) outbound(WMS → 外部) + ┌──────────────────────┐ ┌──────────────────────┐ + │ IM 回调 / API push │ │ 系统回信 / 工单通知 │ + └──────────┬───────────┘ └──────────┬───────────┘ + │ │ + ▼ ▼ + ┌─────────────────────────────────────────┐ + │ wms_inbox_message(同一张表) │ + │ │ + │ direction: inbound │ outbound │ + │ parent_id: NULL │ parent_id: 原消息ID │ + │ │ + │ "IM msg_001 → API app_10 → success" │ + │ "WMS 回复 → 企微 Bot → success" │ + └─────────────────────────────────────────┘ + │ + ▼ setImmediate async push + dispatch → HTTP POST / Bot API +``` + +--- + +## 二、数据库表 + +### `wms_inbox_message` + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `ext_id` | `VARCHAR(128)` | ✅ | — | **外部唯一消息主键**(IM msgId / API requestId 等),唯一索引,幂等去重 | +| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 所属仓库 | +| `store_id` | `BIGINT UNSIGNED` | — | NULL | 关联货主 | +| `direction` | `VARCHAR(10)` | ✅ | `inbound` | `inbound`=外部→WMS 收件 / `outbound`=WMS→外部 回信 | +| `parent_id` | `BIGINT UNSIGNED` | — | NULL | 关联消息 ID(回信时指向原消息,形成对话链) | + +#### 来源 / 目标 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `source_type` | `VARCHAR(20)` | ✅ | `im` / `api` | +| `source_extra` | `VARCHAR(100)` | — | 附加信息(IM 平台 / API app_id) | +| `target_type` | `VARCHAR(20)` | ✅ | `im` / `api` | +| `target_channel` | `VARCHAR(50)` | ✅ | 目标渠道:`wecom` / `dingtalk` / `feishu` / `warehouse_api` / `webhook` | +| `target_url` | `VARCHAR(500)` | ✅ | 推送目标 URL(IM Bot webhook 地址 / API 回调地址) | + +> **安全设计**: +> - `target_url` 不含 secret。IM Bot URL 中 token 已内嵌,API 推送时 secret 从 `ApiApp.self_app_secret` 查。 +> - **出站签名**:推送到仓库开放 API 时,使用与该仓库 ApiApp 相同的 MD5 签名算法(`canonicalQuery + self_app_secret + bodySign`),接收方用同一 `app_key` 验证。IM 通道则使用各自 Bot 的原生鉴权。 + +> **inbound vs outbound 的 source/target 语义**: +> ``` +> inbound(外部→WMS):source=外部来源 target=WMS 内部要转发到的渠道 +> outbound(WMS→外部):source=WMS 内部 target=要推送到的外部渠道 +> ``` +| `ref_code` | `VARCHAR(100)` | — | 外部引用编码,推送/回执时原样携带 | +| `ext_data` | `JSON` | — | **外部透传数据**,外部传入任意 JSON,WMS 不解析,回信时原样返回 | +| `flags` | `JSON` | — | **处理标记**,外部传入控制 WMS 处理行为,见下表 | + +> **`flags` 支持的标记**: +> ```json +> { +> "skip_ai_parse": true, // 跳过智能解析(内部员工发信时设为 true) +> "skip_auto_reply": true, // 跳过自动回复 +> "skip_forward": true // 仅存档,不转发 +> } +> ``` +> 外部不传 → 默认全部开启(智能解析 + 自动回复 + 转发)。内部系统调用 `inbox.push` 时按需关闭特定行为。 + +#### 推送状态 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `push_status` | `TINYINT(4)` | ✅ | 0 | 0=待推送 1=推送中 2=已送达 3=失败 | +| `push_started_at` | `DATETIME` | — | NULL | 开始推送时间(僵尸检测:超 5 分钟仍为 1 → 重置为 0) | +| `retry_count` | `INT(11)` | ✅ | 0 | 已重试次数 | +| `push_response` | `JSON` | — | NULL | 目标响应(http_status, body, error) | +| `pushed_at` | `DATETIME` | — | NULL | 推送完成时间 | + +> **防重机制**:`push_status` 字段本身即状态流转,不需要额外流转表。使用乐观锁 `UPDATE SET push_status=1 WHERE push_status=0` 保证单条消息不会被重复取走。`push_started_at` 用于进程崩溃后的僵尸恢复。 + +#### 关联(后续) + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `work_order_id` | `BIGINT UNSIGNED` | — | 🔮 关联工单 | +| `work_order_no` | `VARCHAR(50)` | — | 🔮 工单号 | + +#### 时间 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `created_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP | | +| `updated_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP ON UPDATE | | +| `deleted_at` | `DATETIME` | — | NULL | 软删除 | + +### 索引 + +| 索引名 | 字段 | 用途 | +|--------|------|------| +| `PRIMARY` | `id` | — | +| `uk_ext_id` | `ext_id` UNIQUE | 外部幂等去重 | +| `idx_warehouse_status` | `warehouse_id, push_status` | 按仓库+状态查询 | +| `idx_warehouse_direction` | `warehouse_id, direction, created_at` | 收件/回信列表 | +| `idx_parent` | `parent_id` | 对话链查询 | +| `idx_created_at` | `created_at` | 时间范围 | + +> **`ext_id` 唯一键防碰撞**:不同来源的消息 ID 可能重复(IM msgId 与 API requestId 撞车)。入库时按来源加前缀: +> ``` +> IM 消息: ext_id = `im:wecom:${msg.msgId}` +> API 消息: ext_id = `api:${apiAppId}:${body.requestId}` +> 系统回信: ext_id = `sys:${uuid}` +> ``` +> 前缀保证不同来源的消息不会因 ID 相同而误判为重复。 + +> **容量规划**:`BIGINT UNSIGNED` 主键容量无限。单表 InnoDB 建议 ≤ 5000 万行。以 100 仓 × 日均 5000 条 = 日 50 万条计,达到上限需 ~100 天。届时加 `PARTITION BY HASH(warehouse_id) PARTITIONS 16` 即可水平扩展,无需分库分表,代码零改动。 + +### 安全边界(强制) + +| 边界 | 规则 | +|------|------| +| **warehouse_id 归属** | 禁止外部传入。IM 路径从回调解析获取,API 路径从验签后 `ctx.warehouseId` 获取 | +| **ext_id 前缀** | `im:{platform}:{msgId}` / `api:{appId}:{requestId}` / `sys:{uuid}`,receiver 入站时统一格式 | +| **target_url SSRF** | 仅允许 `https://`,禁止内网 IP(127.0.0.1/10.x/172.16-31.x/192.168.x) | +| **dispatch 超时** | HTTP 请求超时 10s,超时视为失败进入重试 | +| **setImmediate 异常** | `try/catch` 包裹,异常写入 `push_response.error`,`push_status=3` | +| **target_channel 校验** | `dispatch[channel]` 不存在时返回明确错误,不静默丢弃 | +| **僵尸恢复** | 启动时 + 每 5 分钟定时执行 `UPDATE push_status=0 WHERE push_status=1 AND push_started_at < NOW()-5MIN` | +| **推送 body 大小** | 限制 64KB,超限拒绝写入 | + +--- + +## 三、推送流程 + +``` +receiver.receive() + │ + ├─ 1. 幂等检查(ext_id 已存在 → 直接返回) + ├─ 2. INSERT(push_status=0) + └─ 3. setImmediate(() => asyncPush(record)) + │ + ├─ UPDATE push_status=1(推送中) + ├─ dispatch(target_channel, target_url) + │ ├─ 成功 → UPDATE push_status=2, pushed_at=NOW() + │ └─ 失败 → retry_count++ + │ ├─ < 3 次 → setTimeout(delay, asyncPush) 指数退避重试 + │ └─ ≥ 3 次 → UPDATE push_status=3(终态) + └─ 返回 +``` + +**指数退避**:30s → 60s → 120s,最多重试 3 次。 + +**关键**:不依赖定时任务轮询,利用 Node.js 事件循环的 `setImmediate` + `setTimeout` 在同一个进程内异步完成推送与重试。 + +--- + +## 四、两个接收入口 + +### IM 消息入站 + +``` +企微/钉钉/飞书 Bot 回调 → receiver.receive({ + // warehouse_id 由 IM 回调解析 / 签名验证后从上下文获取,不外部传入 + source_type: 'im', + ext_id: `im:wecom:${msg.msgId}`, + source_extra: 'wecom', + + target_type: 'api', + target_channel: 'warehouse_api', + target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx', + ref_code: msg.userId, + ext_data: { conversation_id: msg.conversationId }, + flags: {}, + + warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入 +}) +``` + +### 仓库 API 消息入站 + +``` +POST /warehouse?method=inbox.push → receiver.receive({ + // warehouse_id 由仓库 API 验签后从 ApiApp 解析,不外部传入 + source_type: 'api', + ext_id: `api:${ctx.apiAppId}:${body.requestId}`, + source_extra: String(ctx.apiAppId), + + target_type: 'im', + target_channel: body.targetChannel || 'wecom', + target_url: body.targetUrl, + ref_code: body.refCode, + ext_data: body.extData, + flags: body.flags || {}, + + warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入 +}) +``` + +### 系统回信(outbound) + +``` +WMS 内部(工单通知/状态更新)→ receiver.reply({ + parent_id: 1, // 原消息 ID + target_type: 'im', + target_channel: 'wecom', + target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx', + ref_code: 'TICKET-001', + ext_data: { ... }, // 继承原消息 ext_data + + warehouse_id: ctx.warehouseId, // ← WMS 内部上下文 +}) +// 自动写入 direction=outbound, parent_id=1 +// 推送成功后,可通过 inbox.thread 查完整对话链 +``` + +--- + +## 五、API + +### 5.1 内部管理 (`inbox.*`) + +| method | 说明 | +|--------|------| +| `inbox.list` | 消息列表(`direction` 区分收件/回信) | +| `inbox.detail` | 消息详情(含 push_response) | +| `inbox.thread` | 对话链(原消息 + 所有回信) | +| `inbox.reply` | 系统回信(写入 outbound 记录 + 异步推送) | +| `inbox.retry` | 手动重推 | +| `inbox.stats` | 推送统计 | + +### 5.2 仓库 API (`inbox.push`) + +`POST /warehouse?method=inbox.push` + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `body.sourceType` | `string` | ✅ | 来源类型:`im` / `api` | +| `body.sourceChannel` | `string` | — | 来源渠道(IM 平台 / API 标识) | +| `body.requestId` | `string` | ✅ | 来源请求 ID(组成 ext_id) | +| `body.targetChannel` | `string` | ✅ | 目标渠道 | +| `body.targetUrl` | `string` | ✅ | 推送目标 URL | +| `body.refCode` | `string` | — | 引用编码 | +| `body.extData` | `object` | — | 透传数据 | +| `body.flags` | `object` | — | 处理标记 `{ skip_ai_parse, skip_auto_reply, skip_forward }` | +| `body.storeId` | `number` | — | 关联货主 | + +--- + +## 六、异步推送实现 + +不启动独立 consumer,利用 Egg.js / Node.js 原生异步能力: + +```javascript +// receiver.js +async receive(data) { + // 1. 幂等检查 + const exist = await this.ctx.model.InboxMessage.findOne({ + where: { ext_id: data.ext_id }, + }); + if (exist) return { ok: true, id: exist.id, ext_id: data.ext_id }; + + // 2. 写入记录 + const record = await this.ctx.model.InboxMessage.create({ + ext_id: data.ext_id, + warehouse_id: data.warehouse_id, + source_type: data.source_type, + source_extra: data.source_extra, + target_type: data.target_type, + target_channel: data.target_channel, + target_url: data.target_url, + ref_code: data.ref_code, + ext_data: data.ext_data, + flags: data.flags || {}, + push_status: 0, + }); + + // 3. 异步后台推送(不阻塞响应) + setImmediate(() => this.asyncPush(record)); + + return { ok: true, id: record.id, ext_id: data.ext_id }; +} + +async asyncPush(record, attempt = 0) { + // 乐观锁:仅 push_status=0 时可取走,防重 + const [ updated ] = await InboxMessage.update( + { push_status: 1, push_started_at: new Date() }, + { where: { id: record.id, push_status: attempt === 0 ? 0 : 3 } } + ); + if (!updated) return; // 已被其他进程取走 + + try { + // API 渠道:用仓库 ApiApp 生成 MD5 签名,接收方同密钥验证 + const payload = { ref_code: record.ref_code, ext_data: record.ext_data }; + const signedUrl = record.target_type === 'api' + ? await this.signRequest(record, payload) + : record.target_url; + + const res = await this.ctx.service.inbox.dispatch[record.target_channel].push( + signedUrl, payload + ); + await record.update({ + push_status: 2, + push_response: { http_status: res.status, body: res.data }, + pushed_at: new Date(), + }); + } catch (err) { + const next = attempt + 1; + await record.update({ push_status: 3, retry_count: next, push_response: { error: err.message } }); + + if (next < 3) { + const delay = 30000 * Math.pow(2, attempt); // 30s → 60s → 120s + setTimeout(() => this.asyncPush(record, next), delay); + } + } +} +``` + +**不需要**:定时任务、消息队列、独立 worker 进程。 + +> **僵尸恢复**:进程崩溃导致 `push_status=1` 的记录卡死时,启动时执行 `UPDATE SET push_status=0 WHERE push_status=1 AND push_started_at < NOW() - INTERVAL 5 MINUTE` 即可复活。 + +> **出站签名**:推送到 `target_type=api` 时,使用仓库 ApiApp 的 `self_app_secret` 生成 MD5 签名附加到 URL query: +> ``` +> signedUrl = target_url +> + '?app_key=' + apiApp.self_app_key +> + '×tamp=' + now +> + '&sign=' + md5(queryString + self_app_secret + md5(body)) +> ``` +> 接收方(仓库开放侧)可用同一 `app_key` 调用 `apiSignLib.verifyRequestSign()` 验证。IM 通道(wecom/dingtalk/feishu)使用各自 Bot 原生鉴权,不走此签名。 + +--- + +## 七、模块结构 + +**分层原则**:API 入口只做校验与签名,统一委托 `app/service/inbox/` 处理写库与推送逻辑。`methods/` 仅放接口定义,不放业务代码。 + +``` +入口层(校验 + 签名) 统一处理层(写库 + 推送) 数据层 +────────────────────────── ────────────────────────── ────── +app/controller/ app/service/inbox/ app/model/ + im.js ─────────────┐ ┌─ receiver.js inbox_message.js + warehouse.js ──────┤ │ 统一接收(幂等去重) ↑ + ├──调用──→ │ 写库(INSERT) │ + app/service/im.js ─┘ │ 异步推送(setImmediate) │ + │ │ 重试(setTimeout 指数退避) │ + │ │ │ + │ ├─ index.js │ + │ │ 列表/详情/重推/统计 │ + │ │ │ + │ └─ dispatch/ │ + │ base.js ← 统一出站:查 ApiApp、取密钥、签名、发 HTTP │ + │ webhook.js ← 继承 base,HTTP POST │ + │ wecom.js ← 继承 base,企微 Bot │ + │ dingtalk.js ← 继承 base,钉钉 Bot │ + │ feishu.js ← 继承 base,飞书 Bot │ + │ │ +methods/ (仅接口定义,不放逻辑) │ + warehouse.json ← inbox.push 参数声明 │ + system.json ← inbox.* 参数声明 │ +``` + +> **关键**:`app/service/inbox/` 是独立的统一处理目录,所有写库、推送、重试逻辑集中在此。后续新增渠道只需在 `dispatch/` 下加一个文件,不影响其他层。 + +### 统一出站基类 `dispatch/base.js` + +所有渠道 dispatch 继承此基类,统一处理查密钥、签名、发 HTTP: + +```javascript +// dispatch/base.js +class OutboundBase { + constructor(ctx) { this.ctx = ctx; } + + // 获取仓库 ApiApp 密钥(IM 渠道无需签名,返回 null) + async getApiApp(warehouseId) { + return await this.ctx.service.systems.apiSign.getApiAppConfigByAppKey( + /* appKey from warehouse */, WAREHOUSE_INTERFACE_TYPE_ID + ); + } + + // 生成 MD5 签名(复用 apiSignLib) + signRequest(url, body, secret) { + const query = { app_key: secret.appKey, timestamp: Math.floor(Date.now() / 1000) }; + const { sign } = apiSignLib.signRequest({ query, body, selfAppSecret: secret.selfAppSecret }); + return `${url}?app_key=${query.app_key}×tamp=${query.timestamp}&sign=${sign}`; + } + + // 统一发送(子类可覆盖签名逻辑) + async post(url, body) { /* axios/post */ } + + // 子类必须实现 + async push(record) { throw new Error('子类实现'); } +} +``` + +> **调用链**:`receiver.asyncPush()` → `dispatch[channel].push(record)` → 基类 `signRequest()` + `post()` → 外部。各渠道只关注消息格式转换,签名和 HTTP 由基类统一处理。 + +### 与现有系统集成 + +``` +app/controller/im.js(已有) + → IM 回调签名校验后 → ctx.service.inbox.receiver.receive({ source_type: 'im', ... }) + +app/controller/warehouse.js(已有) + → method=inbox.push → ctx.service.inbox.receiver.receive({ source_type: 'api', ... }) + +methods/warehouse.json(修改) + → 新增 inbox.push 方法定义,注册到 warehouse 开放接口方法列表 +``` + +--- + +## 八、文件变更清单 + +| 文件 | 操作 | +|------|------| +| `database/migrations/{ts}-create-inbox-message.js` | 新增 DDL | +| `app/model/inbox_message.js` | 新增 | +| `app/service/inbox/index.js` | 新增 | +| `app/service/inbox/receiver.js` | 新增(统一接收 + 写库 + 异步推送入口) | +| `app/service/inbox/dispatch/base.js` | 新增(统一出站:查密钥 + 签名 + HTTP) | +| `app/service/inbox/dispatch/webhook.js` | 新增(HTTP POST 推送) | +| `app/service/inbox/dispatch/wecom.js` | 新增(企微 Bot) | +| `app/service/inbox/dispatch/dingtalk.js` | 新增(钉钉 Bot) | +| `app/service/inbox/dispatch/feishu.js` | 新增(飞书 Bot) | +| `app/controller/inbox.js` | 新增 | +| `methods/warehouse.json` | 新增 `inbox.push` | +| `methods/system.json` | 新增 `inbox.*` | diff --git a/database/designs/store-express-binding-policy-design.md b/database/designs/store-express-binding-policy-design.md new file mode 100644 index 0000000..4c48653 --- /dev/null +++ b/database/designs/store-express-binding-policy-design.md @@ -0,0 +1,138 @@ +# 订单自定义店铺-快递绑定策略 设计方案 + +> **状态**: 📋 设计中 +> **设计日期**: 2026-08-03 +> **模块**: 订单快递分配策略 +> **表**: 1 张 — `wms_store_express_binding_policy` + +--- + +## 一、背景与目的 + +在 WMS 系统中,订单的快递分配目前依赖以下路径: + +1. `store_warehouse.policy_config.auto_allocate_express` 控制是否自动分配 +2. `express_interface` 表提供「仓库 + 店铺 + 平台 + 快递」的接口配置映射 +3. 货主 `subject_config.default_express_code` 提供默认快递 + +**痛点**:无法根据业务场景灵活配置"某个仓库下,某店铺(或某货主)强制使用/优先使用某快递"的策略。例如: + +- 仓库 A 的拼多多店铺「旗舰店」必须走中通(ZTO),而「奥莱店」走圆通(YTO) +- 同一店铺在不同条件下(如收件省份、商品类型)使用不同快递 +- 多人同时管理时需要记录创建人、创建时间,方便追溯 + +**解决方案**:新增 `wms_store_express_binding_policy` 表,支持自定义店铺-快递绑定策略,按优先级匹配。 + +--- + +## 二、数据库表 + +### `wms_store_express_binding_policy` + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 仓库ID,策略所属仓库 | +| `custom_name` | `VARCHAR(100)` | ✅ | — | 自定义店铺标签名称(自由文本,与系统店铺无关) | +| `express_code` | `VARCHAR(50)` | ✅ | — | 绑定的快递编码(关联 wms_express.code) | +| `priority` | `INT(11)` | ✅ | 0 | 优先级,数值越大越优先匹配 | +| `is_enabled` | `TINYINT(1)` | ✅ | 1 | 是否启用:0=停用,1=启用 | +| `match_condition` | `JSON` | — | NULL | 附加匹配条件(见下方说明) | +| `remark` | `VARCHAR(500)` | — | NULL | 备注说明 | +| `creator_id` | `BIGINT UNSIGNED` | — | NULL | 创建人账户ID(关联 accounts 表) | +| `created_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP | 创建时间 | +| `updated_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP ON UPDATE | 更新时间 | +| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | + +### 索引设计 + +| 索引名 | 字段 | 说明 | +|--------|------|------| +| `PRIMARY` | `id` | 主键 | +| `idx_warehouse_enabled` | `warehouse_id`, `is_enabled`, `deleted_at` | 按仓库查询启用策略 | +| `idx_warehouse_express` | `warehouse_id`, `express_code`, `deleted_at` | 按仓库+快递反查绑定 | + +### `match_condition` 字段说明(JSON,可选) + +用于扩展匹配条件,可进一步按以下维度过滤: + +```jsonc +{ + "platform_codes": ["PDD", "TB"], // 限定平台编码 + "provinces": ["广东省", "浙江省"], // 限定收件省份 + "cities": ["广州市", "杭州市"], // 限定收件城市 + "item_codes": ["SKU001", "SKU002"], // 限定商品编码 + "min_weight_g": 0, // 最小重量(g),NULL=不限制 + "max_weight_g": 5000, // 最大重量(g),NULL=不限制 + "min_amount": 0, // 最小金额(元),NULL=不限制 + "max_amount": 1000 // 最大金额(元),NULL=不限制 +} +``` + +## 三、匹配逻辑(伪代码) + +``` +1. 查询 wms_store_express_binding_policy + WHERE warehouse_id = :warehouseId + AND is_enabled = 1 + AND deleted_at IS NULL + ORDER BY priority DESC, id ASC + +2. 遍历结果集,对每条策略: + a. 若 match_condition 为空 → 命中,返回 express_code + b. 若 match_condition 不为空 → 逐条件判断: + - platform_codes:订单平台编码是否在列表中 + - provinces / cities:收件地址省/市是否在列表中 + - item_codes:订单商品编码是否命中 + - min/max_weight_g:订单总重量是否在范围内 + - min/max_amount:订单总金额是否在范围内 + c. 所有条件 AND 全部满足 → 命中,返回 express_code + +3. 若未命中任何策略 → 回退到原有默认逻辑 + (express_interface 匹配 → subject_config.default_express_code) +``` + +## 四、与现有表的关系 + +``` +wms_store_express_binding_policy + ├─ warehouse_id → stores.id(逻辑关联,不做物理外键) + ├─ express_code → wms_express.code(逻辑关联) + └─ creator_id → accounts.id(逻辑关联) +``` + +## 五、典型使用场景 + +### 场景1:按自定义店铺标签绑定快递 + +```sql +INSERT INTO wms_store_express_binding_policy + (warehouse_id, custom_name, express_code, priority, creator_id) +VALUES + (1000000, '旗舰店-中通', 'ZTO', 10, 10001); +``` + +### 场景2:按自定义店铺标签+省份绑定快递(偏远地区走邮政) + +```sql +INSERT INTO wms_store_express_binding_policy + (warehouse_id, custom_name, express_code, priority, match_condition, creator_id) +VALUES + (1000000, '偏远地区邮政', 'EMS', 20, + '{"provinces":["新疆维吾尔自治区","西藏自治区","青海省"]}', 10001); +``` + +### 场景3:全局默认快递 + +```sql +INSERT INTO wms_store_express_binding_policy + (warehouse_id, custom_name, express_code, priority, creator_id) +VALUES + (1000000, '全局顺丰', 'SF', 5, 10001); +``` + +## 六、后续扩展 + +- 策略命中日志:记录每次快递分配命中了哪条策略,便于分析调整 +- 策略生效时间段:增加 `start_time` / `end_time` 支持定时策略(如大促期间切换快递) +- 策略复制:支持跨仓库复制策略配置 diff --git a/database/designs/waybill-module-design.md b/database/designs/waybill-module-design.md new file mode 100644 index 0000000..d3baadf --- /dev/null +++ b/database/designs/waybill-module-design.md @@ -0,0 +1,772 @@ +# 运单号模块设计方案(仓库侧) + +> **状态**: 🔧 开发中(索引已就绪,快照字段待 dev 实现写入逻辑后执行) +> **设计日期**: 2026-07-29 +> **设计人**: wms-db-agent +> **说明**: 本文档仅输出设计方案,不执行代码实现。审阅通过后再进入开发。 +> **命名空间**: `waybill.warehouse.*`(仓库侧操作);后续预留 `waybill.store.*`(货主侧操作),本期不实现。 + +--- + +## 一、需求概述 + +当前系统缺少独立的运单号查询与管理界面。运单数据(`wms_order_express`)始终依附于订单上下文——运单信息仅通过订单详情接口(`xxx.detail`)的 `expresses[]` 字段返回,或通过 `index.toOrder` 做运单号→订单反查。实际业务中需要: + +1. **运单号列表(仓库侧)**:按仓库维度,独立查询所有运单号,支持多条件筛选、分页,支持主单号/子单号关联展示与查询 +2. **运单详情(仓库侧)**:查看单个运单的完整信息,包含关联订单、打印记录、打包状态、称重信息 +3. **运单导出(仓库侧)**:支持按筛选条件导出运单列表 + +> **主单号/子单号规则**(沿用已有业务约定):同一 `order_id` 下,`business_key = 1` 的运单为**主单号**,`business_key > 1` 的运单为**子单号**(即拆单产生的子运单)。该规则已在 `order_export.js` 导出逻辑中使用。 +> +> **命名空间规划**:`waybill.warehouse.*` 本期实现(仓库侧操作);后续按需扩展 `waybill.store.*`(货主侧操作,按 `store_id` 维度查询)。两套接口共享底层 `systems/waybill.js` 业务逻辑,仅入口鉴权与数据隔离维度不同。 + +--- + +## 二、数据模型分析 + +### 2.1 核心表:`wms_order_express`(运单表,已有) + +当前表结构(关键字段): + +| 字段 | 类型 | 说明 | +|------|------|------| +| `id` | `BIGINT(20) UNSIGNED` PK | 主键 | +| `waybill_code` | `VARCHAR(50)` | **运单号** | +| `order_id` | `BIGINT(20)` | 订单ID | +| `warehouse_id` | `BIGINT(20) UNSIGNED` | 仓库ID | +| `store_id` | `BIGINT(20) UNSIGNED` | 🆕 货主ID | +| `business_key` | `INTEGER(3)` | 拆单序号(1=主单号,>1=子单号) | +| `status` | `TINYINT(1)` DEFAULT 0 | 状态(1=已分配,0=未分配) | +| `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID | +| `logistics_code` | `VARCHAR(50)` | 物流公司编码 | +| `logistics_name` | `VARCHAR(50)` | 物流公司名称 | +| `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID | +| `logistics_interface_name` | `VARCHAR(50)` | 物流接口名称 | +| `platform_code` | `VARCHAR(50)` | 平台编码 | +| `is_galaxy_receive` | `ENUM('Y','N')` | 是否揽收 | +| `is_back` | `ENUM('Y','N')` | 是否退回 | +| `is_intercept` | `ENUM('Y','N')` | 是否拦截 | +| `weighing_weight` | `INT(11)` DEFAULT 0 | 称重重量(g) | +| `package_material_id` | `BIGINT(20) UNSIGNED` | 包材ID | +| `package_material_name_snapshot` | `VARCHAR(128)` | 包材名称快照 | +| `printinfo` | `TEXT('long')` | 打印信息 | +| `ver` | `VARCHAR(50)` | 打印版本号 | +| `retry_count` | `TINYINT(3)` | 重试次数 | +| `create_at` | `DATE` | 创建时间 | +| `delete_at` | `DATE` | 删除时间 | + +**现有索引**: + +| 索引名 | 字段 | 类型 | +|--------|------|------| +| `PRIMARY` | `id` | 主键 | +| `uk_order_id_business_key` | `order_id, business_key` | 唯一 | +| `idx_waybill_code` | `waybill_code` | 普通 | +| `idx_create_at` | `create_at` | 普通 | +| `idx_wms_order_express_package_material_id` | `package_material_id` | 普通 | +| `idx_warehouse_store` | `store_id, warehouse_id` | 普通(货主+仓库组合过滤,迁移 `20261109235000`) | + +### 2.2 关联表 + +| 表名 | 关联字段 | 用途 | +|------|---------|------| +| `wms_order_delivery`(current/history/dispatch) | `order_id` | 订单信息(订单号、货主、波次等) | +| `wms_express` | `logistics_code` ↔ `code` | 物流公司名称(统一展示名) | +| `express_print_record` | `express_no` ↔ `waybill_code` | 打印记录(打印时间、打印机、模板) | +| `pack_task` | `waybill_code` | 打包任务(打包状态、打包人、打包时间) | +| `package_material` | `package_material_id` ↔ `id` | 包材详情 | + +> **轨迹不落库(2026-11-11 调整)**:物流轨迹改为**全部实时回源**,`wms_order_express_trace` 表与模型已删除(迁移 `20261111205500-drop-wms-order-express-trace.js`)。轨迹查询不再有本地表,也不再存在 1:N 关联。 + +### 2.3 索引评估 + +当前 `wms_order_express` 表的索引不足以支撑运单列表场景的高频查询: + +| 缺失索引 | 原因 | +|---------|------| +| `idx_warehouse_id_status` | 运单列表按仓库+状态是最常见查询 | +| `idx_logistics_code` | 按物流公司筛选运单 | +| `idx_logistics_interface_id` | 按快递接口ID筛选运单 | +| `idx_warehouse_id_create_at` | 仓库+时间范围排序分页 | +| `idx_order_id_business_key` | 已有 `uk_order_id_business_key` 唯一索引,可同时覆盖主单号 SELF JOIN 查询 | + +> **索引迁移**:以下索引已通过迁移文件 `20260729140000-add-waybill-list-indexes.js` 正式创建,见 §五 文件变更清单。 + +**Y/N 标记列单列索引(2026-11-11 新增)**:`is_back` / `is_intercept` / `is_galaxy_receive` 三列此前无索引,而它们是列表常用筛选条件(且用于「批量更新揽收状态」的条件圈选)。迁移 `20261111041500-add-yn-flag-indexes-to-order-express.js` 为三列分别建立单列索引(`idx_is_back` / `idx_is_intercept` / `idx_is_galaxy_receive`,`ALGORITHM=INPLACE, LOCK=NONE` 在线创建)。不同筛选方向各自独立命中,故不建联合索引。 + +**默认值**:三列默认值均为 `'N'`(模型 `defaultValue` + 数据库 `DEFAULT 'N'`),存量 NULL 已由迁移 `20261111033000-init-is-back-intercept-receive-to-n.js` 回填为 `'N'`(`Y` 不动)。 + +### 2.4 主单号/子单号关联关系 + +**规则**(沿用系统已有约定): + +- 同一 `order_id` 下,`business_key = 1` → **主单号**(main waybill) +- 同一 `order_id` 下,`business_key > 1` → **子单号**(child waybill) +- 该规则已在 `app/service/systems/order_export.js` 第 444 行使用:`business_key === 1 ? '主单号' : '子单号'` + +**查询方式**: + +- **正向查(子→主)**:在 `wms_order_express` 上做 SELF JOIN,`t1.order_id = t2.order_id AND t2.business_key = 1` 获取主单号 +- **反向查(主→子)**:通过 `order_id` + `business_key > 1` 查子单号;或通过主单号 `waybill_code` 先定位 `order_id`,再查该订单下所有运单 + +**注意**: +- 大部分运单 `business_key = 1`(未拆单),此时主单号 = 运单号本身 +- 仅拆单场景下存在 `business_key > 1` 的子单号 + +### 2.5 快照字段评估(待开发实现) + +> **状态**:字段和迁移已准备就绪,但**创建运单号时写入快照值的逻辑尚未实现**(属于 dev 任务范围)。当前快照列为空,列表仍需 JOIN 订单表。 + +**原则**:运单列表应尽量避免 JOIN `wms_order_delivery`(current/history/dispatch 多表)和 `store` 表,通过快照字段冗余订单关键信息到 `wms_order_express`。 + +**现有快照字段**: + +| 字段 | 快照内容 | 覆盖场景 | +|------|---------|---------| +| `package_material_name_snapshot` | 包材名称 | ✅ 避 JOIN `package_material` | + +**待新增快照字段**(需配合 dev 改造创建运单号逻辑): + +| 快照列 | 类型 | 替代的 JOIN | 写入时机 | +|--------|------|-----------|---------| +| `delivery_order_code` | `VARCHAR(50)` | `order_delivery.delivery_order_code` | 运单号分配成功时(express.js) | +| `store_id_snapshot` | `BIGINT(20) UNSIGNED` | `order_delivery.store_id` | 同上 | +| `store_name_snapshot` | `VARCHAR(128)` | `store.name`(货主表) | 同上 | +| `warehouse_name_snapshot` | `VARCHAR(128)` | `store.name`(仓库表) | 同上 | + +> **迁移文件**:`20260729130000-add-waybill-order-snapshots.js` 已创建但**已回滚**,待 dev 实现写入逻辑后再执行。 + +--- + +## 三、接口设计 + +### 3.1 模块概览 + +| 项目 | 说明 | +|------|------| +| 模块名 | `waybill.warehouse` | +| 接口路径 | `POST /system`,body 中 `method` 字段为 `waybill.warehouse.{方法名}` | +| 请求方式 | 全部 `POST`,参数放在 `body` 内 | +| 鉴权 | 全部接口需登录,暂不做细粒度鉴权 | +| 数据隔离 | 按 `warehouse_id` 隔离(仓库侧视角,见 §3.1.1 仓库隔离策略) | +| 后续扩展 | 预留 `waybill.store.*`(货主侧,按 `store_id` 隔离),本期不实现 | + +### 3.1.1 仓库隔离策略(已核实) + +**核实结论**:仓库隔离策略与系统现有模式一致,无需调整。 + +**请求上下文来源**(系统统一约定): + +| 项目 | 值 | 说明 | +|------|-----|------| +| 仓库ID来源 | `ctx.user.store_id` | 全系统统一:`ctx.user.store_id` 即为当前操作用户所属仓库的 `warehouse_id` | +| 后备方案 | 无(必须登录) | 未登录用户无法访问,不存在 `store_id` 为空的情况 | +| 注入方式 | WHERE 条件自动追加 | 在 `systems/waybill.js` 中 `const warehouseId = Number(ctx.user.store_id)`,追加 `warehouse_id = warehouseId` 到所有查询的 WHERE 子句 | +| 注入时机 | 业务层(systems) | 不在入口层(systemMethods)注入,保持业务层职责单一 | + +**参考依据**(系统内一致使用 `ctx.user.store_id` 作为 warehouse_id): + +| 文件 | 行号/位置 | 用法 | +|------|----------|------| +| `systems/waybill.js`(现有 toOrder) | 第 29 行 | `ctx.user && ctx.user.store_id ? ctx.user.store_id : null` | +| `systemMethods/index.js` | 第 1593 行 | `ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null` | +| `systemMethods/print.js` | 第 725 行 | `ctx.user.store_id` | +| `systemMethods/stock/transaction.js` | 第 32 行 | `Number(this.ctx.user && this.ctx.user.store_id)` | +| `systemMethods/storage/management.js` | JSDoc 注释 | "仓库 ID 从用户上下文(ctx.user.store_id / ctx.user.warehouse_id)自动获取" | + +> **注**:部分文件也支持 `ctx.user.warehouse_id` 作为备选来源(如 `storage/management.js`),但 `ctx.user.store_id` 是全系统主要来源,且 `wms_order_express` 表中的 `warehouse_id` 字段语义上对应 `store_id`。本期统一使用 `ctx.user.store_id`。 + +### 3.2 文件规划 + +``` +app/service/systemMethods/waybill/warehouse.js ← 入口层(鉴权、参数校验、委托) +app/service/systems/waybill.js ← 业务层(扩展:新增 list/detail/export 方法) +methods/system.json ← API 文档(新增 waybill.warehouse group) +``` + +> **注意**: +> - `app/service/systems/waybill.js` 已有 `toOrder()` 方法(运单反查),新方法将添加到同一文件中。 +> - 目录 `systemMethods/waybill/` 预留 `store.js`(货主侧入口),本期仅创建 `warehouse.js`。 + +### 3.3 调用链路 + +``` +POST /system { method: "waybill.warehouse.list", ... } + → app/router.js + → app/service/system.js + → app/service/systemMethods/waybill/warehouse.js ← 鉴权 + 参数校验 + → app/service/systems/waybill.js ← 业务逻辑 + DB操作 + → ctx.model.OrderExpress ← Sequelize Model + → ctx.model.OrderDeliveryFactory ← 订单信息补充 + → ctx.model.Express ← 物流公司名称 + → ctx.model.ExpressPrintRecord ← 打印记录 +``` + +--- + +### 3.4 接口清单 + +| # | method | 描述 | 需登录 | 需鉴权 | +|---|--------|------|--------|--------| +| 1 | `waybill.warehouse.list` | 运单列表-仓库侧(分页+筛选) | ✓ | ✗ | +| 2 | `waybill.warehouse.detail` | 运单详情-仓库侧(含订单/打印/打包/称重信息) | ✓ | ✗ | +| 3 | `waybill.warehouse.export` | 运单导出-仓库侧(按筛选条件) | ✓ | ✗ | +| 4 | `waybill.warehouse.exportTaskProgress` | 运单导出任务进度查询 | ✓ | ✗ | +| 5 | `waybill.warehouse.updateReceive` | 批量更新运单是否揽收(走出站回调 `waybill.getreceive`,异步任务) | ✓ | ✗ | +| 6 | `waybill.warehouse.updateReceiveTaskProgress` | 揽收状态更新任务进度查询 | ✓ | ✗ | +| 7 | `waybill.warehouse.getTrace` | 查询单个运单的全部物流轨迹(实时回源,不分页) | ✓ | ✗ | + +> **预留接口(本期不实现)**: +> +> | # | method | 描述 | +> |---|--------|------| +> | 8 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) | +> | 9 | `waybill.store.detail` | 运单详情-货主侧 | +> | 10 | `waybill.store.export` | 运单导出-货主侧 | + +--- + +### 3.5 `waybill.warehouse.list` — 运单列表(仓库侧) + +**功能说明**:查询运单号列表,支持分页与多条件筛选。仓库隔离(自动注入 `warehouse_id`)。 + +#### 请求参数 + +```json +{ + "method": "waybill.warehouse.list", + "pagination": { + "page": 1, + "pageSize": 20 + }, + "where": { + "waybillCode": "", + "mainWaybillCode": "", + "waybillType": "", + "orderId": null, + "orderNo": "", + "storeId": null, + "logisticsCode": "", + "logisticsInterfaceId": null, + "platformCode": "", + "status": null, + "isBack": null, + "isIntercept": null, + "isGalaxyReceive": null, + "packageMaterialId": null, + "hasWeighingWeight": null, + "keyword": "", + "createdAtStart": "", + "createdAtEnd": "" + }, + "sort": { + "field": "create_at", + "order": "desc" + } +} +``` + +> `where.mainWaybillCode` 支持字符串或字符串数组:`"SF1234567890"`(单主单)或 `["SF1234567890", "SF0987654321"]`(多主单,按 `IN` 精确匹配)。上例以单值展示。 + +#### 参数说明 + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `pagination` | `object` | ✗ | 分页参数 `{ page, pageSize }`,默认 page=1, pageSize=20 | +| `where` | `object` | ✗ | 筛选条件,所有字段均为可选 | +| `where.waybillCode` | `string` | ✗ | 运单号(模糊搜索) | +| `where.mainWaybillCode` | `string \| string[]` | ✗ | **主单号**(精确匹配,2026-10-04 起支持数组)。单值:先通过主单号定位 `order_id`,再返回该订单下所有运单(主+子);数组:按 `Op.in` 匹配多个主单号,返回这些主单对应订单下的全部运单。与 `waybillCode` 同时传入时按 AND 叠加,不做互斥优先级处理。空数组/全空值不加该条件;主单号均不存在时直接返回空列表 | +| `where.waybillType` | `string` | ✗ | 🆕 **运单类型**:`"main"`/`"1"`=主单号(`business_key=1`),`"child"`/`"2"`=子单号(`business_key>1`) | +| `where.orderId` | `number` | ✗ | 订单ID(等值) | +| `where.orderNo` | `string` | ✗ | ⛔ **暂不可用**:订单号(待快照字段 `delivery_order_code` 落库后启用 LIKE 模糊搜索) | +| `where.storeId` | `number` | ✗ | 货主ID(等值,直读 `store_id` 列) | +| `where.logisticsCode` | `string` | ✗ | 物流公司编码(等值) | +| `where.logisticsInterfaceId` | `number` | ✗ | **物流接口ID**(等值),对应 `wms_order_express.logistics_interface_id`,用于按快递接口筛选运单列表 | +| `where.platformCode` | `string` | ✗ | 平台编码(等值),如 PDD/DY/KS/JD/CAINIAO/SPH/XHS | +| `where.status` | `number` | ✗ | 运单状态:`0`=未分配,`1`=已分配 | +| `where.isBack` | `string` | ✗ | 是否退回:`Y`/`N` | +| `where.isIntercept` | `string` | ✗ | 是否拦截:`Y`/`N` | +| `where.isGalaxyReceive` | `string` | ✗ | 是否揽收:`Y`/`N` | +| `where.packageMaterialId` | `number` | ✗ | 包材ID(等值) | +| `where.hasWeighingWeight` | `boolean` | ✗ | 是否已称重:`true`=weighing_weight>0,`false`=weighing_weight=0 | +| `where.keyword` | `string` | ✗ | 关键词:匹配运单号(`waybill_code`)、主单号(`main_waybill_code`)、订单号(需 JOIN) | +| `where.createdAtStart` | `string` | ✗ | 创建时间起始(YYYY-MM-DD) | +| `where.createdAtEnd` | `string` | ✗ | 创建时间截止(YYYY-MM-DD) | +| `sort` | `object` | ✗ | 排序 `{ field, order }`,默认 `create_at desc` | +| `sort.field` | `string` | ✗ | 排序字段:`create_at` / `weighing_weight` / `id` | +| `sort.order` | `string` | ✗ | 排序方向:`asc` / `desc`,默认 `desc` | + +#### 响应格式 + +```json +{ + "list": [ + { + "id": 123456, + "waybill_code": "SF1234567890", + "main_waybill_code": "SF1234567890", + "waybill_type": "主单号", + "order_id": 78901, + "order_no": "PO202607290001", + "warehouse_id": 1, + "warehouse_name": "默认仓库", + "store_id": 10, + "store_name": "测试货主", + "business_key": 1, + "status": 1, + "status_text": "已分配", + "logistics_interface_id": 3, + "logistics_code": "SF", + "logistics_name": "顺丰速运", + "logistics_interface_name": "顺丰标准", + "platform_code": "PDD", + "platform_name": "拼多多", + "is_back": "N", + "is_intercept": "N", + "is_galaxy_receive": "N", + "weighing_weight": 1250, + "weighing_weight_display": "1.25 kg", + "package_material_id": 5, + "package_material_name": "3号纸箱", + "print_count": 2, + "last_print_at": "2026-07-29 10:30:00", + "create_at": "2026-07-29 08:00:00" + } + ], + "pagination": { + "page": 1, + "pageSize": 20, + "total": 156, + "totalPages": 8 + } +} +``` + +#### 响应字段说明 + +| 字段 | 类型 | 来源 | 说明 | +|------|------|------|------| +| `id` | `number` | `wms_order_express.id` | 运单记录ID | +| `waybill_code` | `string` | `wms_order_express.waybill_code` | 运单号(当前运单的运单号) | +| `main_waybill_code` | `string` | SELF JOIN 同 order 下 `business_key=1` | **主单号**。当 `business_key=1` 时等于 `waybill_code` 本身;当 `business_key>1` 时通过 SELF JOIN 查找同 `order_id` 下 `business_key=1` 的运单号 | +| `waybill_type` | `string` | 计算字段 | 运单类型:`business_key=1` → `"主单号"`,`business_key>1` → `"子单号"` | +| `order_id` | `number` | `wms_order_express.order_id` | 订单ID | +| `order_no` | `string` | JOIN 订单表 | 订单号(`delivery_order_code`)。待快照字段 + 写入逻辑实现后可改为直读 | +| `warehouse_id` | `number` | `wms_order_express.warehouse_id` | 仓库ID | +| `warehouse_name` | `string` | JOIN `store` 表 | 仓库名称。待快照字段 + 写入逻辑实现后可改为直读 | +| `store_id` | `number` | JOIN 订单表 | 货主ID。待快照字段 + 写入逻辑实现后可改为直读 | +| `store_name` | `string` | JOIN `store` 表 | 货主名称。待快照字段 + 写入逻辑实现后可改为直读 | +| `business_key` | `number` | `wms_order_express.business_key` | 拆单序号 | +| `status` | `number` | `wms_order_express.status` | 状态:0/1 | +| `status_text` | `string` | 前端映射 | 状态文本 | +| `logistics_code` | `string` | `wms_order_express.logistics_code` | 物流公司编码 | +| `logistics_name` | `string` | `wms_order_express.logistics_name` | 物流公司名称 | +| `logistics_interface_id` | `number` | `wms_order_express.logistics_interface_id` | 物流接口ID | +| `logistics_interface_name` | `string` | `wms_order_express.logistics_interface_name` | 物流接口名称 | +| `platform_code` | `string` | `wms_order_express.platform_code` | 平台编码 | +| `platform_name` | `string` | 前端映射 | 平台名称 | +| `is_back` | `string` | `wms_order_express.is_back` | 是否退回 | +| `is_intercept` | `string` | `wms_order_express.is_intercept` | 是否拦截 | +| `is_galaxy_receive` | `string` | `wms_order_express.is_galaxy_receive` | 是否揽收 | +| `weighing_weight` | `number` | `wms_order_express.weighing_weight` | 称重重量(g) | +| `weighing_weight_display` | `string` | 格式化 | 称重重量可读展示 | +| `package_material_id` | `number` | `wms_order_express.package_material_id` | 包材ID | +| `package_material_name` | `string` | `wms_order_express.package_material_name_snapshot` | 包材名称 | +| `print_count` | `number` | COUNT `express_print_record` | 打印次数 | +| `last_print_at` | `string` | MAX `express_print_record.created_at` | 最近打印时间 | +| `create_at` | `string` | `wms_order_express.create_at` | 运单创建时间 | + +#### 查询逻辑要点 + +1. **仓库隔离**:自动注入 `warehouse_id = ctx.user.store_id`(系统统一约定,`ctx.user.store_id` 即为当前用户所属仓库ID)。所有查询 WHERE 条件自动追加 `warehouse_id`,不可由前端入参覆盖 +2. **主单号关联查询**:每条运单记录通过 SELF JOIN(`t1.order_id = t2.order_id AND t2.business_key = 1`)获取主单号 `main_waybill_code`。当 `business_key = 1` 时,主单号就是自身 `waybill_code`;当 `business_key > 1` 时,需要 JOIN 获取主单号 +3. **按主单号入参查询**:当 `where.mainWaybillCode` 传入时,先通过主单号 `waybill_code` 定位 `order_id`,再返回该订单下所有运单(主+子)。**支持单值 / 数组**(2026-10-04):单值保持 `WHERE waybill_code = ? AND business_key = 1 AND warehouse_id = ?` → `WHERE order_id = ?`(标量,向后兼容);数组按 `WHERE waybill_code IN (?, ?) AND business_key = 1 AND warehouse_id = ?` → `WHERE order_id IN (?, ?)`(去重后 `Op.in`),返回多个主单对应订单下的全部运单;元素自动 trim 并过滤空值,全部主单号不存在时直接返回空列表,空数组/全空值数组不添加该条件 +4. **按物流接口ID查询**:直接 `WHERE logistics_interface_id = ?`,等值匹配 +5. **订单号模糊搜索**:当 `where.orderNo` 或 `where.keyword` 匹配到非纯数字运单号时,需要 JOIN 订单表(current/history/dispatch)进行 `delivery_order_code LIKE` 匹配 +6. **打印次数**:通过子查询或 LEFT JOIN + GROUP BY `express_print_record.express_no = waybill_code` 聚合 +7. **性能注意**:打印次数聚合查询在数据量大时可能成为瓶颈,建议仅在 detail 接口返回 + +> **性能优化策略**(建议): +> - **方案 A(推荐)**:列表仅查 `wms_order_express` 原生字段,不 JOIN 订单/打印/打包表。`print_count` 通过批量异步查询补充,或仅在 detail 接口返回。 +> - **方案 B**:列表即 JOIN,但需确保索引覆盖良好。 +> +> **快照字段优化(待实现)**:新增快照列 + 创建运单号时写入快照值后,可彻底去掉订单表和 store 表的 JOIN。迁移文件 `20260729130000-add-waybill-order-snapshots.js` 已就绪,待 dev 实现写入逻辑后执行。 + +--- + +### 3.6 `waybill.warehouse.detail` — 运单详情(仓库侧) + +**功能说明**:查看单个运单的完整信息,包含关联订单、打印记录、打包信息。 + +#### 请求参数 + +```json +{ + "method": "waybill.warehouse.detail", + "id": 123456 +} +``` + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `id` | `number` | ✓ | 运单记录ID(`wms_order_express.id`) | +| `waybillCode` | `string` | ✗ | 运单号(与 id 二选一,waybillCode 优先) | + +#### 响应格式 + +```json +{ + "id": 123456, + "waybill_code": "SF1234567890", + "main_waybill_code": "SF1234567890", + "waybill_type": "主单号", + "business_key": 1, + "sibling_waybills": [ + { "waybill_code": "SF1234567890", "business_key": 1, "waybill_type": "主单号" }, + { "waybill_code": "SF1234567891", "business_key": 2, "waybill_type": "子单号" } + ], + "order": { + "order_id": 78901, + "order_no": "PO202607290001", + "warehouse_id": 1, + "warehouse_name": "默认仓库", + "store_id": 10, + "store_name": "测试货主", + "wave_id": 500, + "wave_no": "W202607290001", + "order_type": "delivery" + }, + "logistics": { + "logistics_code": "SF", + "logistics_name": "顺丰速运", + "logistics_interface_id": 3, + "logistics_interface_name": "顺丰标准", + "platform_code": "PDD" + }, + "status_info": { + "status": 1, + "status_text": "已分配", + "is_back": "N", + "is_intercept": "N", + "is_galaxy_receive": "N" + }, + "weight": { + "weighing_weight": 1250, + "weighing_weight_display": "1.25 kg" + }, + "package": { + "package_material_id": 5, + "package_material_name": "3号纸箱" + }, + "print_records": [ + { + "id": 1001, + "printer_name": "打印机-01", + "template_id": 2, + "template_name": "顺丰标准面单", + "platform": "PDD", + "printed_at": "2026-07-29 10:30:00" + } + ], + "print_count": 2, + "printinfo": "{...}", + "ver": "v2.1", + "retry_count": 0, + "create_at": "2026-07-29 08:00:00", + "delete_at": null +} +``` + +#### 查询逻辑要点 + +1. 查询 `wms_order_express` 主记录 +2. 通过 `order_id` 查询同订单下所有运单组成 `sibling_waybills`(含各运单的 `waybill_code`、`business_key`、`waybill_type`) +3. 通过 `order_id` → `OrderDeliveryFactory` 多表遍历查找订单信息 +4. LEFT JOIN `wms_express` 获取物流公司统一名称 +5. LEFT JOIN `pack_task` ON `waybill_code` 获取打包信息 +6. LEFT JOIN `express_print_record` ON `express_no = waybill_code` 获取打印记录列表 +7. 仓库隔离校验 + +--- + +### 3.7 `waybill.warehouse.export` — 运单导出(仓库侧) + +**功能说明**:按筛选条件导出运单列表为 Excel。复用 `waybill.warehouse.list` 的筛选逻辑,去掉分页,全量导出。 + +#### 请求参数 + +同 `waybill.warehouse.list`,不含 `pagination` 参数,可选增加 `exportFields` 指定导出字段。 + +```json +{ + "method": "waybill.warehouse.export", + "where": { "...": "同 waybill.warehouse.list" }, + "sort": { "...": "同 waybill.warehouse.list" }, + "exportFields": ["waybill_code", "order_no", "logistics_name", "weighing_weight", "create_at"] +} +``` + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `where` | `object` | ✗ | 同 `waybill.warehouse.list` 的筛选条件 | +| `sort` | `object` | ✗ | 同 `waybill.warehouse.list` 的排序 | +| `exportFields` | `string[]` | ✗ | 需要导出的字段列表,不传则导出全部字段 | + +--- + +### 3.8 `waybill.warehouse.updateReceive` / `waybill.warehouse.updateReceiveTaskProgress` — 批量更新是否揽收(仓库侧) + +**功能说明**:`wms_order_express.is_galaxy_receive` 此前只有创建默认值 `N`,没有任何写入来源。本接口按运单号调用**外部访问接口**查询揽收状态并回写,链路不读取本地库的揽收标记。 + +#### 调用链路 + +``` +waybill.warehouse.updateReceive(入口层:参数校验 + 接口配置预检 + 建任务) + → systems/waybill.js#queryReceiveStatus(每批 ≤10 单,逐批回写 + 回调进度) + → openapi/callback.js#sendByAppKey(event = waybill.getreceive) + → 回写 wms_order_express.is_galaxy_receive(waybill_code + warehouse_id 隔离) +``` + +#### 请求参数 + +两种用法二选一(`waybillCodes` 优先): + +```json +{ "method": "waybill.warehouse.updateReceive", "waybillCodes": ["YT1234567890", "SF1234567890"] } +``` + +```json +{ + "method": "waybill.warehouse.updateReceive", + "where": { "isGalaxyReceive": "N", "logisticsCode": "YTO", "createdAt": ["2026-11-01", "2026-11-11"] } +} +``` + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `waybillCodes` | `string[]` | ✗ | 运单号列表,内部按 10 单一批调用外部接口 | +| `waybill_codes` | `string[]` | ✗ | `waybillCodes` 的下划线别名 | +| `where` | `object` | ✗ | **与 `waybill.warehouse.list` 完全一致的筛选条件**(不含 `pagination` / `sort`);仅传 `where` 时由 `buildListQueryWhere` 解析运单号后再走同一任务链路 | + +`where` 支持的字段与列表一致:`waybillCode` / `mainWaybillCode` / `orderId` / `orderNo` / `logisticsCode` / `logisticsInterfaceId` / `platformCode` / `status` / `isBack` / `isIntercept` / `isGalaxyReceive` / `waybillType` / `storeId` / `packageMaterialId` / `hasWeighingWeight` / `keyword` / `createdAt`(含 `createAt` 别名、`createdAtStart`/`createdAtEnd` 旧写法)。 + +约束: +- 两者都不传 → 失败「运单号不能为空,或传入 where 筛选条件」 +- `where` 匹配数 **> 5000** → 失败「符合条件的运单超过 5000 条,请缩小筛选范围或直接传 waybillCodes」(不截断,避免误更新) +- `where` 匹配 0 条 → 失败「未匹配到符合条件的运单」 + +#### 外部接口约定(`waybill.getreceive`) + +- 请求体:`{ "request": { "waybill_codes": [...] } }`(由 `sendByAppKey` 统一包装,单批最多 10 单) +- 签名:`sign = MD5(appSecret + timestamp + bodyJson)`(仓库通知协议,`signMode=simple`);**不使用** `/openapi` 入站的 `canonicalQuery` 口径。外部接收端(如 `new_wms_notify`)按该协议验签,用旧口径会返回 `{"code":401,"msg":"签名验证失败"}` +- 响应:裸数组 `[{ "waybill_code": "YT...", "is_galaxy_receive": 1 }]`,兼容 `{ code, data: [...] }` 与 `{ data: { waybills: [...] } }` +- 取值:`1`/`0`、`'Y'`/`'N'`(大小写不敏感)、布尔;非法值计入 `failed`,不写库 +- 业务失败:HTTP 200 但 `code` 非 `0/1/200` 时整批计入 `failed` +- 目标应用:该仓库 `callback_functions` 勾选 `waybill.getreceive` 的首个启用应用(按 `id` 升序) + +#### 失败前置校验(不进入任务流程) + +仓库下无任何应用承接 `waybill.getreceive` 时,`updateReceive` 直接返回失败(不创建任务、不写进度缓存): + +``` +如需更新运单是否揽收信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口 +``` + +#### 任务进度 + +`task_id` 前缀 `waybill_receive_`,Redis 缓存键前缀 `waybill_receive_task_`(与导出的 `waybill_export_` 互相隔离)。状态流转 `submitted → running → success/failed`,`result` 返回 `{ total, updated, unchanged, not_found, failed }`。 + +```json +{ + "method": "waybill.warehouse.updateReceiveTaskProgress", + "task_id": "waybill_receive_1000028_1731190000000_ab12cd34" +} +``` + +--- + +### 3.9 `waybill.warehouse.getTrace` — 查询运单物流轨迹(仓库侧,实时回源) + +**功能说明**:按运单号**实时**调用外部访问接口 `waybill.getTrace` 查询轨迹,一次返回全部轨迹(不分页),按 `op_time` 倒序。 + +- **不做本地存储**:`wms_order_express_trace` 表与模型已删除(迁移 `20261111205500-drop-wms-order-express-trace.js`),每次查询都回源 +- **揽收联动**:轨迹非空时把该运单 `wms_order_express.is_galaxy_receive` 置为 `Y`(只升不降,失败只记日志不阻断查询) +- **失败口径**:未配置承接应用或外部接口异常时直接返回失败(无本地兜底);`trace: []` 属于正常结果(`success` + `total=0`) + +#### 调用链路 + +``` +waybill.warehouse.getTrace(入口层:参数校验 + 接口配置预检) + → systems/waybill.js#fetchTracesByWaybill(单运单实时查询 + 归一排序) + → openapi/callback.js#sendByAppKey(event = waybill.getTrace,signMode=simple) + → systems/waybill.js#markReceiveByTraces(命中轨迹则置 is_galaxy_receive=Y) +``` + +#### 请求 / 响应 + +```json +{ "method": "waybill.warehouse.getTrace", "waybillCode": "770358128188071" } +``` + +```json +{ + "waybill_code": "770358128188071", + "total": 2, + "received_updated": 1, + "list": [ + { + "op_time": "2026-11-11 10:43:00", + "out_biz_code": "770358128188071_510902_1794255999000_120", + "memo": "【广州市】快件已发往 山东济南转运中心", + "op_org_city_name": "广州市", + "weight": 0.99, + "scan_type": "收件", + "raw_data": { "opTime": "2026-11-11 10:43:00" } + } + ] +} +``` + +#### 外部接口约定(`waybill.getTrace`) + +- 请求体:`{ "request": { "waybill_codes": ["770358128188071"] } }`(单运单);签名同 `waybill.getreceive`(`MD5(appSecret + timestamp + bodyJson)`) +- 响应:`[{ "waybillNo": "...", "trace": [ { "opTime", "outBizCode", "memo", "opOrgCityName", "weight", "scanType" } ] }]`,`trace` 可为对象或数组,另兼容 `{ code, data: [...] }` 与单个对象返回 +- `trace: []` 表示暂无轨迹;`weight` 支持字符串小数(`"0.99"`) +- 目标应用:该仓库 `callback_functions` 勾选 `waybill.getTrace` 的首个启用应用(按 `id` 升序) + +--- + +## 四、`methods/system.json` 变更 + +在 `methods.groups[]` 中新增 `waybill.warehouse` group: + +```json +{ + "name": "waybill.warehouse", + "description": "运单号管理(仓库侧)", + "methods": [ + { + "method": "waybill.warehouse.list", + "description": "运单列表(分页+筛选)。仓库隔离。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ "... 参数定义 ..." ], + "response": [ "... 返回值定义 ..." ] + }, + { + "method": "waybill.warehouse.detail", + "description": "运单详情(含订单/打印/打包信息)。仓库隔离。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ "... 参数定义 ..." ], + "response": [ "... 返回值定义 ..." ] + }, + { + "method": "waybill.warehouse.export", + "description": "运单导出。仓库隔离。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ "... 参数定义 ..." ], + "response": [ "... 返回值定义 ..." ] + } + ] +} +``` + +> **预留 group(本期不实现)**:`waybill.store` — 运单号管理(货主侧),按 `store_id` 隔离。 +> +> 完整的 `methods/system.json` method 定义(含 params/response 的 children 详情)在代码实现阶段由 `wms-doc-agent` 补齐。 + +--- + +## 五、文件变更清单 + +| 操作 | 文件路径 | 说明 | +|------|---------|------| +| **新增** | `app/service/systemMethods/waybill/warehouse.js` | 入口层(仓库侧):继承 `MainService`,`systemInit` 声明免鉴权方法,参数校验,委托 `systems/waybill.js` | +| **预留** | `app/service/systemMethods/waybill/store.js` | 入口层(货主侧):本期不创建,后续按需新增 | +| **修改** | `app/service/systems/waybill.js` | 业务层:在现有 `toOrder()` 方法基础上新增 `list()`、`detail()`、`export()` 方法 | +| **修改** | `methods/system.json` | 新增 `waybill.warehouse` group,注册 3 个 method 定义 | +| **新增** | `database/migrations/20260729140000-add-waybill-list-indexes.js` | 迁移文件:新增 4 个索引(✅ 已执行) | +| **新增** | `database/migrations/20260730000000-add-store-id-to-wms-order-express.js` | 迁移文件:新增 `store_id` 货主ID列(✅ 已执行) | +| **新增** | `database/migrations/20261109235000-add-warehouse-store-index-to-wms-order-express.js` | 迁移文件:新增 `idx_warehouse_store (store_id, warehouse_id)` 索引(生产已手工创建,待按流程执行记录) | + +--- + +## 六、安全约束 + +| 约束 | 说明 | +|------|------| +| 仓库隔离 | 所有查询自动注入 `warehouse_id = ctx.user.store_id`(系统统一约定),仅返回当前用户所属仓库数据,不可由入参覆盖 | +| 只读 | 本模块一期仅提供只读查询,不涉及运单创建/修改/删除 | +| 鉴权 | 全部接口仅需登录,暂不做细粒度权限校验(与订单列表保持一致) | + +--- + +## 七、与现有功能的边界划分 + +| 现有功能 | 所属 method | 与新模块关系 | +|---------|------------|-------------| +| 运单号反查订单 | `index.toOrder` | **保留**,独立于新模块。用于 PDA 扫运单号快速定位订单 | +| 订单详情中的运单信息 | `order.detail → expresses[]` | **保留**,不变。新模块提供运单维度的独立视图 | +| 运单包材绑定 | `order.bindExpressPackageMaterial*` | **保留**,不变。仍按订单维度操作 | +| 运单称重更新 | `order.updateExpressWeighingWeight` | **保留**,不变。仍按订单维度操作 | +| 快递号分配 | `order.pendingOrder.allocateExpressCode` | **保留**,不变。仍按订单维度操作 | +| 订单导出(运单模式) | `order.export (export_mode=waybill)` | **保留**,不变。与新模块 `waybill.warehouse.export` 并存 | + +> **核心原则**:新模块不修改任何现有接口,仅新增运单维度的独立查询能力。现有订单维度的运单操作全部保持不动。 + +--- + +## 八、后续扩展方向(不在本期范围) + +| 扩展 | 说明 | +|------|------| +| 运单拦截/解拦截 | 批量操作运单状态 | +| 运单退回标记 | 标记运单退回并记录原因 | +| 运单打印管理 | 批量补打、重新推送电子面单 | +| 运单异常列表 | 独立展示分配失败/打印失败的运单 | +| 运单物流轨迹 | 对接物流轨迹查询接口 | + +--- + +## 九、审阅检查点 + +- [ ] 接口设计是否满足业务需求(运单号独立列表 + 详情) +- [x] ~~仓库隔离策略是否正确~~ → 已核实:全系统统一使用 `ctx.user.store_id` 作为 warehouse_id,与现有模式一致 +- [ ] 列表字段是否完整(是否需要增减字段) +- [ ] 快照字段写入逻辑:需在创建运单号(express.js)时同步写入快照列值(dev 任务) +- [ ] 是否需要新增数据库索引(已明确需要,`20260729140000` 已执行) +- [ ] 与现有 `index.toOrder`、`order.*` 接口的边界是否清晰 + +### 当前筛选条件(共 18 项,16 可用 + 2 待快照) + +| # | 参数 | 类型 | 匹配 | 状态 | +|---|------|------|------|------| +| — | `warehouse_id` | — | = | ✅ 自动注入 | +| 1 | `waybillCode` | string | LIKE | ✅ | +| 2 | `mainWaybillCode` | string \| string[] | 精确→order_id(数组 Op.in) | ✅ 🆕 | +| 3 | `waybillType` | string | `main/1`→bk=1, `child/2`→bk>1 | ✅ 🆕 | +| 4 | `orderId` | number | = | ✅ | +| 5 | `orderNo` | string | LIKE | ⛔ 待快照 | +| 6 | `storeId` | number | = | ✅ 直读 `store_id` | +| 7 | `logisticsCode` | string | = | ✅ | +| 8 | `logisticsInterfaceId` | number | = | ✅ | +| 9 | `platformCode` | string | = | ✅ | +| 10 | `status` | number | = | ✅ | +| 11 | `isBack` | string | = | ✅ | +| 12 | `isIntercept` | string | = | ✅ | +| 13 | `isGalaxyReceive` | string | = | ✅ | +| 14 | `packageMaterialId` | number | = | ✅ | +| 15 | `hasWeighingWeight` | boolean | true→>0, false→=0 | ✅ | +| 16 | `keyword` | string | LIKE waybill_code | ✅ | +| 17 | `createdAtStart` | string YYYY-MM-DD | >= | ✅ | +| 18 | `createdAtEnd` | string YYYY-MM-DD | <= | ✅ | + +### 排序 + +| field | order | 默认 | +|-------|-------|------| +| `create_at` | asc/desc | desc | +| `weighing_weight` | asc/desc | — | +| `id` | asc/desc | — | diff --git a/database/migrations/20260504000000-baseline.js b/database/migrations/20260504000000-baseline.js new file mode 100644 index 0000000..7219927 --- /dev/null +++ b/database/migrations/20260504000000-baseline.js @@ -0,0 +1,109 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +/** + * Baseline migration - 2026-05-04 + * 以 SequelizeMeta.sql 为基准,定义当前数据库完整结构。 + * 生产环境:请将本文件名插入 SequelizeMeta 表,标记为已执行。 + * 新环境:直接运行 db:migrate,本文件会创建所有表结构。 + */ +module.exports = { + up: async queryInterface => { + const sqlRaw = fs.readFileSync( + path.join(__dirname, '../../SequelizeMeta.sql'), + 'utf8' + ); + + // 预处理:去掉 DROP TABLE,改为 CREATE TABLE IF NOT EXISTS,跳过 SequelizeMeta 表 + const sql = sqlRaw + .replace(/SET NAMES utf8mb4;\r?\n/g, '') + .replace(/DROP TABLE IF EXISTS `SequelizeMeta`;\r?\nCREATE TABLE[\s\S]*?ROW_FORMAT = Dynamic;\r?\n/m, '') + .replace(/DROP TABLE IF EXISTS `[^`]+`;\r?\n/g, '') + .replace(/CREATE TABLE `/g, 'CREATE TABLE IF NOT EXISTS `') + .replace(/SET FOREIGN_KEY_CHECKS = 1;?/g, ''); + + // 按分号+换行切割,逐条执行 + const statements = sql + .split(/;\s*\r?\n/) + .map(s => s.trim()) + .filter(s => s && !s.startsWith('--') && !s.startsWith('/*') && s !== 'SET FOREIGN_KEY_CHECKS = 0'); + + // 先禁用外键检查 + await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0'); + for (const stmt of statements) { + if (stmt) { + await queryInterface.sequelize.query(stmt + ';'); + } + } + await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 1'); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0'); + // 按外键依赖逆序删除 + const tables = [ + 'wms_account_platform_active', + 'wms_employee_role', + 'wms_wave_batch', + 'wms_picking', + 'wms_picking_strategy', + 'wms_operation_log', + 'wms_notification_send_log', + 'wms_notification_webhook', + 'wms_stock_transaction', + 'wms_storage', + 'wms_receiving_detail', + 'wms_receiving', + 'wms_order_express_print_data', + 'wms_order_express', + 'wms_entry_items', + 'wms_entry_order', + 'wms_file_reference', + 'wms_file', + 'wms_i18n_translations', + 'wms_i18n_keys', + 'wms_express_print_record', + 'wms_print_log', + 'wms_express_interface', + 'wms_express_setting', + 'wms_embargo_policies', + 'wms_prohibited_type', + 'wms_location_space', + 'wms_location_zone', + 'wms_location_type', + 'wms_print_station_express', + 'wms_print_stations', + 'wms_print_template', + 'wms_platform_print_config', + 'wms_print_record', + 'wms_print_computer', + 'wms_print_items', + 'wms_print_log', + 'wms_system_log', + 'wms_stock_unit', + 'wms_stock_warehouse', + 'wms_stock_store', + 'wms_api_app', + 'wms_interface_type', + 'wms_account_store_employee', + 'wms_role', + 'wms_permission', + 'wms_platfrom_setting', + 'wms_fast_where', + 'wms_qimen_log', + 'wms_qimen_apps', + 'wms_express_product_type', + 'wms_express', + 'wms_account_login_log', + 'wms_store_warehouse', + 'wms_store', + 'wms_account', + ]; + for (const table of tables) { + await queryInterface.sequelize.query(`DROP TABLE IF EXISTS \`${table}\``); + } + await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 1'); + }, +}; diff --git a/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js b/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js new file mode 100644 index 0000000..c309e73 --- /dev/null +++ b/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js @@ -0,0 +1,90 @@ +'use strict'; + +/** + * 打印迁移阶段对应的数据库连接上下文信息。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {'up'|'down'} phase 迁移阶段。 + * @param {string} table 迁移目标表名。 + * @return {Promise} 无返回值。 + */ +const logMigrationDbContext = async (queryInterface, phase, table) => { + try { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user' + ); + const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {}; + console.log( + `[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}` + ); + } catch (error) { + console.warn( + `[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}` + ); + } +}; + +/** + * Migration: add box_remainder and box_weight to wms_receiving_detail + * - box_remainder: INT NOT NULL DEFAULT 0 COMMENT '箱余数' + * - box_weight: DECIMAL(10,2) NOT NULL DEFAULT '0.00' COMMENT '箱重量(kg)' + * + * Idempotent: uses queryInterface.describeTable to only add if missing. + * + * Raw SQL (MySQL 8+ supports IF NOT EXISTS): + * ALTER TABLE `wms_receiving_detail` + * ADD COLUMN IF NOT EXISTS `box_remainder` INT NOT NULL DEFAULT 0 COMMENT '箱余数', + * ADD COLUMN IF NOT EXISTS `box_weight` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '箱重量(kg`)'; + * + * If MySQL < 8 (no IF NOT EXISTS), use INFORMATION_SCHEMA checks before ALTER. + */ + +module.exports = { + /** + * 执行正向迁移,按需新增收货明细箱字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const table = 'wms_receiving_detail'; + await logMigrationDbContext(queryInterface, 'up', table); + const columns = await queryInterface.describeTable(table); + + if (!columns.box_remainder) { + await queryInterface.addColumn(table, 'box_remainder', { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '箱余数', + }); + } + + if (!columns.box_weight) { + await queryInterface.addColumn(table, 'box_weight', { + type: Sequelize.DECIMAL(10, 2), + allowNull: false, + defaultValue: '0.00', + comment: '箱重量(kg)', + }); + } + }, + + /** + * 执行回滚迁移,按需删除收货明细箱字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + down: async (queryInterface, Sequelize) => { + const table = 'wms_receiving_detail'; + await logMigrationDbContext(queryInterface, 'down', table); + const columns = await queryInterface.describeTable(table); + + if (columns.box_remainder) { + await queryInterface.removeColumn(table, 'box_remainder'); + } + if (columns.box_weight) { + await queryInterface.removeColumn(table, 'box_weight'); + } + }, +}; diff --git a/database/migrations/20260507002000-rename-wms_picking_strategy-to-wms_wave_strategy.js b/database/migrations/20260507002000-rename-wms_picking_strategy-to-wms_wave_strategy.js new file mode 100644 index 0000000..786dc12 --- /dev/null +++ b/database/migrations/20260507002000-rename-wms_picking_strategy-to-wms_wave_strategy.js @@ -0,0 +1,37 @@ +'use strict'; + +/** + * 将拣货策略表重命名为波次策略表。 + * 幂等处理:仅在源表存在且目标表不存在时执行重命名。 + */ +module.exports = { + /** + * 升级迁移:wms_picking_strategy -> wms_wave_strategy。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + */ + up: async queryInterface => { + const sourceTable = 'wms_picking_strategy'; + const targetTable = 'wms_wave_strategy'; + const allTables = await queryInterface.showAllTables(); + const tableNames = new Set(allTables.map(table => (typeof table === 'string' ? table : table.tableName))); + + if (tableNames.has(sourceTable) && !tableNames.has(targetTable)) { + await queryInterface.renameTable(sourceTable, targetTable); + } + }, + + /** + * 回滚迁移:wms_wave_strategy -> wms_picking_strategy。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + */ + down: async queryInterface => { + const sourceTable = 'wms_wave_strategy'; + const targetTable = 'wms_picking_strategy'; + const allTables = await queryInterface.showAllTables(); + const tableNames = new Set(allTables.map(table => (typeof table === 'string' ? table : table.tableName))); + + if (tableNames.has(sourceTable) && !tableNames.has(targetTable)) { + await queryInterface.renameTable(sourceTable, targetTable); + } + }, +}; diff --git a/database/migrations/20260507100000-create-wms_order_wave_strategy_match.js b/database/migrations/20260507100000-create-wms_order_wave_strategy_match.js new file mode 100644 index 0000000..3456fc5 --- /dev/null +++ b/database/migrations/20260507100000-create-wms_order_wave_strategy_match.js @@ -0,0 +1,70 @@ +'use strict'; + +/** + * Migration: 创建 wms_order_wave_strategy_match 表 + * + * 记录每个订单命中的全部波次策略 ID,作为快速扫描结果的副表存储。 + * 不与分仓主表做物理外键,靠应用层逻辑维护一致性。 + * + * 索引: + * idx_warehouse_order (warehouse_id, order_id) — 按订单删除/查询 + * idx_warehouse_strategy (warehouse_id, strategy_id) — 按策略聚合统计 + */ + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tableExists = await queryInterface.showAllTables() + .then(tables => tables.includes('wms_order_wave_strategy_match')); + + if (tableExists) { + return; + } + + await queryInterface.createTable('wms_order_wave_strategy_match', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: Sequelize.INTEGER(10), + allowNull: false, + comment: '仓库ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '订单ID,逻辑关联分仓主表,不做物理外键', + }, + strategy_id: { + type: Sequelize.INTEGER(10), + allowNull: false, + comment: '命中的波次策略ID', + }, + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '写入时间', + }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_unicode_ci', + comment: '订单波次策略命中明细表', + }); + + await queryInterface.addIndex('wms_order_wave_strategy_match', [ 'warehouse_id', 'order_id' ], { + name: 'idx_warehouse_order', + }); + + await queryInterface.addIndex('wms_order_wave_strategy_match', [ 'warehouse_id', 'strategy_id' ], { + name: 'idx_warehouse_strategy', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable('wms_order_wave_strategy_match'); + }, +}; diff --git a/database/migrations/20260508123000-create-wave-pick-task-tables.js b/database/migrations/20260508123000-create-wave-pick-task-tables.js new file mode 100644 index 0000000..f496bfb --- /dev/null +++ b/database/migrations/20260508123000-create-wave-pick-task-tables.js @@ -0,0 +1,1108 @@ +'use strict'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建通用时间字段。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {{create_time: object, update_time: object}} 时间字段定义。 + */ +const buildTimeColumns = Sequelize => ({ + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, +}); + +/** + * 创建波次拣货任务主表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createWavePickTaskTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_task', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_no: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '任务编号', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + wave_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '波次ID', + }, + pick_mode: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '拣货模式:1-小团购 2-单品单件 3-先拣后分 4-边拣边分 5-大团购', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0-待开始 1-拣货中 2-待复核 3-已完成 9-已取消', + }, + source: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '任务来源:1-PDA 2-后台', + }, + wave_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '波次数量', + }, + order_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '订单数量', + }, + box_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '框数量', + }, + batch_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '领单批次号', + }, + pick_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货员ID', + }, + pick_user_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货员名称', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_user_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '复核员名称', + }, + current_cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前绑定拣货车ID', + }, + current_cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '当前绑定车码快照', + }, + review_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '复核状态:0-未就绪 1-待复核 2-复核中 3-复核通过 4-复核异常', + }, + review_version: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '复核并发版本号', + }, + review_start_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核开始时间', + }, + review_finish_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核结束时间', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + review_remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '复核备注', + }, + device_id: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '设备ID', + }, + expire_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '任务过期时间', + }, + transfer_from_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '转移来源任务ID', + }, + transfer_to_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '转移目标任务ID', + }, + start_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '开始拣货时间', + }, + finish_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '完成拣货时间', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核完成时间', + }, + remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '备注', + }, + ext_json: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展信息', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货任务主表', + }); + + await queryInterface.addIndex('wms_wave_pick_task', [ 'task_no' ], { + unique: true, + name: 'uk_task_no', + }); + await queryInterface.addIndex('wms_wave_pick_task', [ 'warehouse_id', 'status' ], { + name: 'idx_warehouse_status', + }); + await queryInterface.addIndex('wms_wave_pick_task', [ 'pick_user_id', 'status' ], { + name: 'idx_pick_user_status', + }); + await queryInterface.addIndex('wms_wave_pick_task', [ 'warehouse_id', 'review_status' ], { + name: 'idx_warehouse_review_status', + }); + await queryInterface.addIndex('wms_wave_pick_task', [ 'current_cart_id', 'review_status' ], { + name: 'idx_current_cart_review_status', + }); +}; + +/** + * 创建任务与波次关联表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createTaskWaveTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_task_wave', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + wave_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '波次ID', + }, + wave_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '波次号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '波次状态:0-待拣 1-已拣 2-异常', + }, + bind_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '绑定时间', + }, + pick_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货完成时间', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货任务与波次关联表', + }); + + await queryInterface.addIndex('wms_wave_pick_task_wave', [ 'task_id', 'wave_id' ], { + unique: true, + name: 'uk_task_wave', + }); + await queryInterface.addIndex('wms_wave_pick_task_wave', [ 'warehouse_id', 'wave_id' ], { + name: 'idx_warehouse_wave', + }); +}; + +/** + * 创建任务订单明细表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createTaskOrderTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_task_order', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + wave_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '波次ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '订单ID', + }, + order_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '订单号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货车码快照', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + pick_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '拣货状态:0-待拣货 1-已拣货', + }, + review_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '复核状态:0-待复核 1-已复核 2-异常', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + review_remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '复核备注', + }, + exception_reason: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '异常原因', + }, + picked_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货完成时间', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核完成时间', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货任务订单表', + }); + + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'task_id', 'order_id' ], { + unique: true, + name: 'uk_task_order', + }); + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'warehouse_id', 'order_id' ], { + name: 'idx_warehouse_order', + }); + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'task_id', 'pick_status' ], { + name: 'idx_task_pick_status', + }); + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'task_id', 'review_status' ], { + name: 'idx_task_review_status', + }); + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'cart_id' ], { + name: 'idx_cart_id', + }); +}; + +/** + * 创建任务箱明细表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createTaskBoxTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_task_box', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '订单ID', + }, + box_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '箱号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + box_type: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '框类型:1-SKU框 2-订单框 3-波次框', + }, + ref_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '关联ID(SKU或订单或波次)', + }, + ref_label: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '关联展示标签', + }, + required_qty: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '应放数量', + }, + picked_qty: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '已放数量', + }, + box_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '箱状态:0-待拣货 1-已拣货 2-已复核', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-缺件 3-多件', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核时间', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货任务箱明细表', + }); + + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'task_id', 'box_code' ], { + unique: true, + name: 'uk_task_box', + }); + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'order_id' ], { + name: 'idx_order_id', + }); + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'task_id', 'box_status' ], { + name: 'idx_task_box_status', + }); + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'task_id', 'box_no' ], { + name: 'idx_task_box_no', + }); + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'ref_id' ], { + name: 'idx_ref_id', + }); +}; + +/** + * 创建拣货车表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPickCartTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_pick_cart', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + cart_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '拣货车编码', + }, + cart_name: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '拣货车名称', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-停用 1-启用', + }, + current_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前绑定任务ID', + }, + bind_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前绑定人ID', + }, + last_bind_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近绑定时间', + }, + last_seen_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近扫码时间', + }, + ext_json: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展信息', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '拣货车主表', + }); + + await queryInterface.addIndex('wms_pick_cart', [ 'warehouse_id', 'cart_code' ], { + unique: true, + name: 'uk_warehouse_cart_code', + }); + await queryInterface.addIndex('wms_pick_cart', [ 'status' ], { + name: 'idx_status', + }); + await queryInterface.addIndex('wms_pick_cart', [ 'current_task_id' ], { + name: 'idx_current_task_id', + }); +}; + +/** + * 创建任务拣货车绑定表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createTaskCartBindingTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_pick_task_cart_binding', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '车码快照', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + bind_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '绑定人ID', + }, + bind_type: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '绑定类型:1-领单绑定 2-换车绑定 3-管理员改绑', + }, + unbind_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '解绑人ID', + }, + is_active: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '是否有效绑定:0-无效 1-有效', + }, + bind_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '绑定时间', + }, + unbind_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '解绑时间', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '任务拣货车绑定关系表', + }); + + await queryInterface.addIndex('wms_pick_task_cart_binding', [ 'task_id', 'is_active' ], { + name: 'idx_task_active', + }); + await queryInterface.addIndex('wms_pick_task_cart_binding', [ 'cart_id', 'is_active' ], { + name: 'idx_cart_active', + }); + await queryInterface.addIndex('wms_pick_task_cart_binding', [ 'warehouse_id', 'is_active' ], { + name: 'idx_warehouse_active', + }); +}; + +/** + * 创建订单拣货轨迹表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createOrderPickTraceTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_order_pick_trace', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '订单ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '任务ID', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货车码快照', + }, + pick_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货员ID', + }, + pick_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货时间', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核时间', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + event_type: { + type: Sequelize.STRING(32), + allowNull: false, + comment: '轨迹事件类型', + }, + event_desc: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '轨迹描述', + }, + operator_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '操作人名称', + }, + snapshot: { + type: Sequelize.JSON, + allowNull: true, + comment: '轨迹快照', + }, + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '订单拣货轨迹审计表', + }); + + await queryInterface.addIndex('wms_order_pick_trace', [ 'warehouse_id', 'order_id', 'create_time' ], { + name: 'idx_warehouse_order_create_time', + }); + await queryInterface.addIndex('wms_order_pick_trace', [ 'task_id' ], { + name: 'idx_task_id', + }); + await queryInterface.addIndex('wms_order_pick_trace', [ 'cart_id', 'create_time' ], { + name: 'idx_cart_id_create_time', + }); +}; + +/** + * 创建波次拣货动作日志表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createWavePickActionLogTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_action_log', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + wave_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '波次ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '订单ID', + }, + sku_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '商品ID', + }, + location_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '库位ID', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + qty_delta: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '数量变化', + }, + action_type: { + type: Sequelize.STRING(32), + allowNull: false, + comment: '动作类型(enter_location/scan_sku/put_box/rollback/exception)', + }, + request_id: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '幂等请求ID', + }, + operator_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '操作人ID', + }, + device_id: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '设备ID', + }, + seq_no: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '序列号', + }, + snapshot: { + type: Sequelize.JSON, + allowNull: true, + comment: '动作快照', + }, + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货动作日志表', + }); + + await queryInterface.addIndex('wms_wave_pick_action_log', [ 'request_id' ], { + unique: true, + name: 'uk_request_id', + }); + await queryInterface.addIndex('wms_wave_pick_action_log', [ 'task_id', 'create_time' ], { + name: 'idx_task_create_time', + }); + await queryInterface.addIndex('wms_wave_pick_action_log', [ 'warehouse_id', 'action_type', 'create_time' ], { + name: 'idx_warehouse_action_time', + }); + await queryInterface.addIndex('wms_wave_pick_action_log', [ 'order_id', 'create_time' ], { + name: 'idx_order_create_time', + }); +}; + +/** + * 创建波次拣货断点检查点表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createWavePickCheckpointTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_checkpoint', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + pick_user_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '拣货员ID', + }, + device_id: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '设备ID', + }, + current_location_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前库位ID', + }, + current_sku_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前商品ID', + }, + current_box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '当前框号', + }, + picked_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '已拣数量', + }, + remaining_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '剩余数量', + }, + last_event_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '最新事件ID', + }, + last_seq_no: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '最新序列号', + }, + checkpoint_json: { + type: Sequelize.JSON, + allowNull: true, + comment: '检查点快照', + }, + version: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '乐观锁版本号', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货断点检查点表', + }); + + await queryInterface.addIndex('wms_wave_pick_checkpoint', [ 'task_id', 'pick_user_id', 'device_id' ], { + unique: true, + name: 'uk_task_user_device', + }); + await queryInterface.addIndex('wms_wave_pick_checkpoint', [ 'task_id', 'update_time' ], { + name: 'idx_task_update_time', + }); + await queryInterface.addIndex('wms_wave_pick_checkpoint', [ 'pick_user_id', 'device_id' ], { + name: 'idx_user_device', + }); +}; + +module.exports = { + /** + * 执行正向迁移,创建波次拣货任务相关 9 张新表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const existingTables = await getExistingTableSet(queryInterface); + + if (!existingTables.has('wms_wave_pick_task')) { + await createWavePickTaskTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_task'); + } + if (!existingTables.has('wms_wave_pick_task_wave')) { + await createTaskWaveTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_task_wave'); + } + if (!existingTables.has('wms_wave_pick_task_order')) { + await createTaskOrderTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_task_order'); + } + if (!existingTables.has('wms_wave_pick_task_box')) { + await createTaskBoxTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_task_box'); + } + if (!existingTables.has('wms_pick_cart')) { + await createPickCartTable(queryInterface, Sequelize); + existingTables.add('wms_pick_cart'); + } + if (!existingTables.has('wms_pick_task_cart_binding')) { + await createTaskCartBindingTable(queryInterface, Sequelize); + existingTables.add('wms_pick_task_cart_binding'); + } + if (!existingTables.has('wms_order_pick_trace')) { + await createOrderPickTraceTable(queryInterface, Sequelize); + existingTables.add('wms_order_pick_trace'); + } + if (!existingTables.has('wms_wave_pick_action_log')) { + await createWavePickActionLogTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_action_log'); + } + if (!existingTables.has('wms_wave_pick_checkpoint')) { + await createWavePickCheckpointTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_checkpoint'); + } + }, + + /** + * 执行回滚迁移,按依赖逆序删除波次拣货任务相关 9 张表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + await queryInterface.dropTable('wms_wave_pick_checkpoint'); + await queryInterface.dropTable('wms_wave_pick_action_log'); + await queryInterface.dropTable('wms_order_pick_trace'); + await queryInterface.dropTable('wms_pick_task_cart_binding'); + await queryInterface.dropTable('wms_pick_cart'); + await queryInterface.dropTable('wms_wave_pick_task_box'); + await queryInterface.dropTable('wms_wave_pick_task_order'); + await queryInterface.dropTable('wms_wave_pick_task_wave'); + await queryInterface.dropTable('wms_wave_pick_task'); + }, +}; diff --git a/database/migrations/20260508140000-add-source-to-wave-batch.js b/database/migrations/20260508140000-add-source-to-wave-batch.js new file mode 100644 index 0000000..fd6f149 --- /dev/null +++ b/database/migrations/20260508140000-add-source-to-wave-batch.js @@ -0,0 +1,56 @@ +'use strict'; + +/** + * 获取表字段定义。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +module.exports = { + /** + * 正向迁移:为波次表新增 source 字段。 + * + * 字段语义:0-普通波次 1-管理后台策略任务 2-PDA策略任务 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + up: async queryInterface => { + const tableName = 'wms_wave_batch'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (!columnsBefore.source) { + await queryInterface.sequelize.query(` + ALTER TABLE wms_wave_batch + ADD COLUMN source TINYINT NOT NULL DEFAULT 0 + COMMENT '来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务' + AFTER update_time + `); + } + + const columnsAfter = await getTableColumns(queryInterface, tableName); + if (!columnsAfter.source) { + throw new Error('迁移失败:wms_wave_batch.source 字段不存在'); + } + }, + + /** + * 回滚迁移:删除波次表 source 字段。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const tableName = 'wms_wave_batch'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (columnsBefore.source) { + await queryInterface.removeColumn(tableName, 'source'); + } + }, +}; diff --git a/database/migrations/20260508150000-add-source-to-wave-pick-task.js b/database/migrations/20260508150000-add-source-to-wave-pick-task.js new file mode 100644 index 0000000..09061ef --- /dev/null +++ b/database/migrations/20260508150000-add-source-to-wave-pick-task.js @@ -0,0 +1,50 @@ +'use strict'; + +/** + * 获取表字段定义。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +module.exports = { + /** + * 正向迁移:为拣货任务表补充 source 字段。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const tableName = 'wms_wave_pick_task'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (!columnsBefore.source) { + await queryInterface.addColumn(tableName, 'source', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '任务来源:1-PDA 2-后台', + }); + } + }, + + /** + * 回滚迁移:若 source 字段存在则删除。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const tableName = 'wms_wave_pick_task'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (columnsBefore.source) { + await queryInterface.removeColumn(tableName, 'source'); + } + }, +}; diff --git a/database/migrations/20260508163000-repair-wave-pick-task-schema-drift.js b/database/migrations/20260508163000-repair-wave-pick-task-schema-drift.js new file mode 100644 index 0000000..9dce366 --- /dev/null +++ b/database/migrations/20260508163000-repair-wave-pick-task-schema-drift.js @@ -0,0 +1,349 @@ +'use strict'; + +/** + * 获取表字段定义。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +/** + * 返回需要补齐的字段定义映射。 + * + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Record>} 表字段映射。 + */ +const getRepairColumnDefinitions = Sequelize => ({ + wms_wave_pick_task: { + wave_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '波次数量', + }, + order_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '订单数量', + }, + box_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '框数量', + }, + batch_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '领单批次号', + }, + pick_user_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货员名称', + }, + review_user_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '复核员名称', + }, + current_cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前绑定拣货车ID', + }, + current_cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '当前绑定车码快照', + }, + review_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '复核状态:0-未就绪 1-待复核 2-复核中 3-复核通过 4-复核异常', + }, + review_version: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '复核并发版本号', + }, + review_start_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核开始时间', + }, + review_finish_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核结束时间', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + review_remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '复核备注', + }, + device_id: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '设备ID', + }, + expire_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '任务过期时间', + }, + transfer_from_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '转移来源任务ID', + }, + transfer_to_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '转移目标任务ID', + }, + }, + wms_wave_pick_task_wave: { + wave_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '波次号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '波次状态:0-待拣 1-已拣 2-异常', + }, + bind_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '绑定时间', + }, + pick_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货完成时间', + }, + }, + wms_wave_pick_task_order: { + order_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '订单号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货车码快照', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + review_remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '复核备注', + }, + exception_reason: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '异常原因', + }, + }, + wms_wave_pick_task_box: { + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + box_type: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '框类型:1-SKU框 2-订单框 3-波次框', + }, + ref_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '关联ID(SKU或订单或波次)', + }, + ref_label: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '关联展示标签', + }, + required_qty: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '应放数量', + }, + picked_qty: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '已放数量', + }, + }, + wms_pick_cart: { + last_seen_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近扫码时间', + }, + }, + wms_pick_task_cart_binding: { + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '车码快照', + }, + bind_type: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '绑定类型:1-领单绑定 2-换车绑定 3-管理员改绑', + }, + }, + wms_order_pick_trace: { + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货车码快照', + }, + pick_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货员ID', + }, + pick_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货时间', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核时间', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + }, +}); + +/** + * 按字段映射执行幂等新增列。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Record>} repairColumnDefinitions 表字段映射。 + * @return {Promise} 无返回值。 + */ +const addMissingColumns = async (queryInterface, repairColumnDefinitions) => { + const tableNames = Object.keys(repairColumnDefinitions); + + for (const tableName of tableNames) { + const columnsBefore = await getTableColumns(queryInterface, tableName); + const columnEntries = Object.entries(repairColumnDefinitions[tableName]); + + for (const [ columnName, columnDefinition ] of columnEntries) { + if (!columnsBefore[columnName]) { + await queryInterface.addColumn(tableName, columnName, columnDefinition); + } + } + } +}; + +/** + * 按字段映射执行幂等删除列。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Record>} repairColumnDefinitions 表字段映射。 + * @return {Promise} 无返回值。 + */ +const removeExistingColumns = async (queryInterface, repairColumnDefinitions) => { + const tableNames = Object.keys(repairColumnDefinitions); + + for (const tableName of tableNames) { + const columnsBefore = await getTableColumns(queryInterface, tableName); + const columnEntries = Object.keys(repairColumnDefinitions[tableName]); + + for (const columnName of columnEntries) { + if (columnsBefore[columnName]) { + await queryInterface.removeColumn(tableName, columnName); + } + } + } +}; + +module.exports = { + /** + * 正向迁移:修复拣货任务相关表的字段漂移问题。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const repairColumnDefinitions = getRepairColumnDefinitions(Sequelize); + await addMissingColumns(queryInterface, repairColumnDefinitions); + }, + + /** + * 回滚迁移:回退本迁移新增的字段(仅在字段存在时删除)。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + down: async (queryInterface, Sequelize) => { + const repairColumnDefinitions = getRepairColumnDefinitions(Sequelize); + await removeExistingColumns(queryInterface, repairColumnDefinitions); + }, +}; diff --git a/database/migrations/20260511120000-add-wave-prefix-to-wms_wave_strategy.js b/database/migrations/20260511120000-add-wave-prefix-to-wms_wave_strategy.js new file mode 100644 index 0000000..4b6d708 --- /dev/null +++ b/database/migrations/20260511120000-add-wave-prefix-to-wms_wave_strategy.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_wave_strategy', 'wave_prefix', { + type: Sequelize.STRING(5), + allowNull: true, + comment: '策略波次前缀(优先于仓库前缀)', + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_wave_strategy', 'wave_prefix'); + }, +}; diff --git a/database/migrations/20260513090000-add-last-login-time-to-wms_print_computer.js b/database/migrations/20260513090000-add-last-login-time-to-wms_print_computer.js new file mode 100644 index 0000000..984a5be --- /dev/null +++ b/database/migrations/20260513090000-add-last-login-time-to-wms_print_computer.js @@ -0,0 +1,27 @@ +'use strict'; + +module.exports = { + /** + * 为打印台电脑表新增上次登录时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'last_login_time', { + type: Sequelize.DATE, + allowNull: true, + comment: '上次登录时间', + }); + }, + + /** + * 回滚删除打印台电脑表的上次登录时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'last_login_time'); + }, +}; diff --git a/database/migrations/20260513113000-create-wms_order_wave_index.js b/database/migrations/20260513113000-create-wms_order_wave_index.js new file mode 100644 index 0000000..50ba5d6 --- /dev/null +++ b/database/migrations/20260513113000-create-wms_order_wave_index.js @@ -0,0 +1,86 @@ +'use strict'; + +module.exports = { + /** + * 创建订单波次顺序副表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.createTable('wms_order_wave_index', { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }, + order_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单ID', + }, + wave_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '波次ID', + }, + wave_index: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单在波次中的全局顺序', + }, + platforms_index: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单在平台分组内顺序', + }, + create_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + comment: '订单波次顺序定位副表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex('wms_order_wave_index', [ 'warehouse_id', 'order_id' ], { + name: 'uk_warehouse_order', + unique: true, + }); + await queryInterface.addIndex('wms_order_wave_index', [ 'warehouse_id', 'wave_id' ], { + name: 'idx_warehouse_wave', + }); + await queryInterface.addIndex('wms_order_wave_index', [ 'warehouse_id', 'wave_id', 'wave_index' ], { + name: 'idx_warehouse_wave_index', + }); + await queryInterface.addIndex('wms_order_wave_index', [ 'warehouse_id', 'wave_id', 'platforms_index' ], { + name: 'idx_warehouse_wave_platform_index', + }); + }, + + /** + * 回滚删除订单波次顺序副表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.dropTable('wms_order_wave_index'); + }, +}; diff --git a/database/migrations/20260514110000-add-subject-config-to-wms_print_stations.js b/database/migrations/20260514110000-add-subject-config-to-wms_print_stations.js new file mode 100644 index 0000000..84c7224 --- /dev/null +++ b/database/migrations/20260514110000-add-subject-config-to-wms_print_stations.js @@ -0,0 +1,37 @@ +'use strict'; + +module.exports = { + /** + * 为打印台表新增主体配置字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableDefinition = await queryInterface.describeTable('wms_print_stations'); + if (tableDefinition.subject_config) { + return; + } + + await queryInterface.addColumn('wms_print_stations', 'subject_config', { + type: Sequelize.JSON, + allowNull: true, + comment: '打印台主体配置', + }); + }, + + /** + * 回滚删除打印台表主体配置字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableDefinition = await queryInterface.describeTable('wms_print_stations'); + if (!tableDefinition.subject_config) { + return; + } + + await queryInterface.removeColumn('wms_print_stations', 'subject_config'); + }, +}; diff --git a/database/migrations/20260514123000-drop-wms_print_station_express.js b/database/migrations/20260514123000-drop-wms_print_station_express.js new file mode 100644 index 0000000..eebd9c2 --- /dev/null +++ b/database/migrations/20260514123000-drop-wms_print_station_express.js @@ -0,0 +1,85 @@ +'use strict'; + +module.exports = { + /** + * 删除已弃用的打印台快递关联表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + 'DROP TABLE IF EXISTS `wms_print_station_express`' + ); + }, + + /** + * 回滚重建打印台快递关联表(核心字段与唯一索引)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.createTable('wms_print_station_express', { + id: { + type: Sequelize.INTEGER.UNSIGNED, + autoIncrement: true, + primaryKey: true, + allowNull: false, + comment: '主键ID', + }, + print_station_id: { + type: Sequelize.STRING(255), + allowNull: false, + comment: '打印台ID', + }, + express_id: { + type: Sequelize.STRING(255), + allowNull: false, + comment: '快递公司ID', + }, + express_name: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '快递公司名称', + }, + printer_name: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '打印机名称', + }, + creator_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '创建人ID', + }, + creator_name: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '创建人名称', + }, + create_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '创建时间', + }, + update_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '更新时间', + }, + deleted: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '删除标记:0未删除,1已删除', + }, + }); + + await queryInterface.addIndex('wms_print_station_express', { + fields: [ 'print_station_id', 'express_id', 'deleted' ], + unique: true, + name: 'uk_print_station_express', + }); + }, +}; diff --git a/database/migrations/20260514150000-add-workerstation-pages-to-wms_permission-type.js b/database/migrations/20260514150000-add-workerstation-pages-to-wms_permission-type.js new file mode 100644 index 0000000..f966b74 --- /dev/null +++ b/database/migrations/20260514150000-add-workerstation-pages-to-wms_permission-type.js @@ -0,0 +1,52 @@ +'use strict'; + +module.exports = { + /** + * 扩展权限类型枚举,新增 workerstation_pages。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.changeColumn('wms_permission', 'type', { + type: Sequelize.ENUM( + 'web_pages', + 'pda_pages', + 'btns', + 'api', + 'miniprogram_pages', + 'block', + 'workerstation_pages' + ), + allowNull: false, + defaultValue: 'web_pages', + comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块,workerstation_pages:工作台菜单)', + }); + }, + + /** + * 回滚权限类型枚举,先将 workerstation_pages 转换为 web_pages。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + "UPDATE `wms_permission` SET `type` = 'web_pages' WHERE `type` = 'workerstation_pages'" + ); + + await queryInterface.changeColumn('wms_permission', 'type', { + type: Sequelize.ENUM( + 'web_pages', + 'pda_pages', + 'btns', + 'api', + 'miniprogram_pages', + 'block' + ), + allowNull: false, + defaultValue: 'web_pages', + comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块)', + }); + }, +}; diff --git a/database/migrations/20260514173000-add-component-to-wms_platform.js b/database/migrations/20260514173000-add-component-to-wms_platform.js new file mode 100644 index 0000000..c71ff28 --- /dev/null +++ b/database/migrations/20260514173000-add-component-to-wms_platform.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为 wms_platform 新增 component 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 component 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_platform'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.component) { + return; + } + + await queryInterface.addColumn(tableName, 'component', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '打印组件标识', + }); + }, + + /** + * 回滚迁移:删除 component 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_platform'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.component) { + return; + } + + await queryInterface.removeColumn(tableName, 'component'); + }, +}; diff --git a/database/migrations/20260516093000-alter-wms-stock-transaction-order-no-and-transaction-type.js b/database/migrations/20260516093000-alter-wms-stock-transaction-order-no-and-transaction-type.js new file mode 100644 index 0000000..855cf39 --- /dev/null +++ b/database/migrations/20260516093000-alter-wms-stock-transaction-order-no-and-transaction-type.js @@ -0,0 +1,61 @@ +'use strict'; + +/** + * 调整 wms_stock_transaction 的单据号字段类型并扩展出入库类型枚举。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移: + * 1. order_no 由 STRING(100) 调整为 TEXT; + * 2. transaction_type 增加 TRANSFER_OUT、TRANSFER_IN 枚举值。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.changeColumn('wms_stock_transaction', 'order_no', { + type: Sequelize.TEXT, + allowNull: true, + comment: '关联单据号', + }); + + await queryInterface.changeColumn('wms_stock_transaction', 'transaction_type', { + type: Sequelize.ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'), + allowNull: false, + comment: '出入库类型(含移库)', + }); + }, + + /** + * 回滚迁移: + * 1. 先将移库枚举值映射回原有枚举,避免收缩 ENUM 失败; + * 2. transaction_type 回退为仅 INBOUND、OUTBOUND; + * 3. order_no 回退为 STRING(100)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + "UPDATE wms_stock_transaction SET transaction_type = 'OUTBOUND' WHERE transaction_type = 'TRANSFER_OUT'" + ); + await queryInterface.sequelize.query( + "UPDATE wms_stock_transaction SET transaction_type = 'INBOUND' WHERE transaction_type = 'TRANSFER_IN'" + ); + + await queryInterface.changeColumn('wms_stock_transaction', 'transaction_type', { + type: Sequelize.ENUM('INBOUND', 'OUTBOUND'), + allowNull: false, + comment: '出入库类型', + }); + + await queryInterface.changeColumn('wms_stock_transaction', 'order_no', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '关联单据号', + }); + }, +}; diff --git a/database/migrations/20260516110000-create-wms-storage-transaction.js b/database/migrations/20260516110000-create-wms-storage-transaction.js new file mode 100644 index 0000000..7c019ab --- /dev/null +++ b/database/migrations/20260516110000-create-wms-storage-transaction.js @@ -0,0 +1,187 @@ +'use strict'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 创建库位维度出入库流水表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createStorageTransactionTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_storage_transaction', { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + transaction_type: { + type: Sequelize.ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'), + allowNull: false, + comment: '出入库类型', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + stock_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品库存ID,关联 wms_stock_warehouse.id', + }, + storage_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位库存ID,关联 wms_storage.id', + }, + space_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + quantity: { + type: Sequelize.INTEGER(12), + allowNull: false, + comment: '变动数量(正数)', + }, + before_quantity: { + type: Sequelize.INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }, + after_quantity: { + type: Sequelize.INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }, + before_locked_quantity: { + type: Sequelize.INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }, + after_locked_quantity: { + type: Sequelize.INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }, + batch_no: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '批次号', + }, + inventory_type: { + type: Sequelize.ENUM('ZP', 'CC', 'JS', 'XS', 'ZT', 'DJ', 'FP'), + allowNull: true, + defaultValue: 'ZP', + comment: '库存类型', + }, + order_type: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '关联单据类型', + }, + order_no: { + type: Sequelize.TEXT, + allowNull: true, + comment: '关联单据号', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联单据ID', + }, + source_order_codes: { + type: Sequelize.TEXT, + allowNull: true, + comment: '来源订单号集合', + }, + operator_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '操作人名称', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '库位维度出入库流水记录表', + }); + + await queryInterface.addIndex('wms_storage_transaction', [ 'storage_id' ], { + name: 'idx_storage_id', + }); + await queryInterface.addIndex('wms_storage_transaction', [ 'stock_id' ], { + name: 'idx_stock_id', + }); + await queryInterface.addIndex('wms_storage_transaction', [ 'warehouse_id', 'created_at' ], { + name: 'idx_warehouse_time', + }); + await queryInterface.addIndex('wms_storage_transaction', [ 'order_type', 'order_id' ], { + name: 'idx_order', + }); + await queryInterface.addIndex('wms_storage_transaction', [ 'created_at' ], { + name: 'idx_created_at', + }); +}; + +/** + * 新增库位维度出入库流水表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + const tableSet = await getExistingTableSet(queryInterface); + if (tableSet.has('wms_storage_transaction')) { + return; + } + + await createStorageTransactionTable(queryInterface, Sequelize); +}; + +/** + * 回滚删除库位维度出入库流水表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async queryInterface => { + const tableSet = await getExistingTableSet(queryInterface); + if (!tableSet.has('wms_storage_transaction')) { + return; + } + + await queryInterface.dropTable('wms_storage_transaction'); +}; diff --git a/database/migrations/20260516123000-alter-wms-stock-transaction-drop-storage-fields-and-shrink-enum.js b/database/migrations/20260516123000-alter-wms-stock-transaction-drop-storage-fields-and-shrink-enum.js new file mode 100644 index 0000000..5ed68cf --- /dev/null +++ b/database/migrations/20260516123000-alter-wms-stock-transaction-drop-storage-fields-and-shrink-enum.js @@ -0,0 +1,96 @@ +'use strict'; + +/** + * 判断表字段是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 字段名。 + * @return {Promise} 字段是否存在。 + */ +const hasColumn = async (queryInterface, tableName, columnName) => { + const tableDef = await queryInterface.describeTable(tableName); + return Object.prototype.hasOwnProperty.call(tableDef, columnName); +}; + +/** + * 收敛 wms_stock_transaction 字段与枚举: + * 1) transaction_type 仅保留 INBOUND/OUTBOUND; + * 2) 删除 storage_id/space_id/inventory_type 三列。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + await queryInterface.sequelize.query( + `UPDATE wms_stock_transaction + SET transaction_type = 'OUTBOUND' + WHERE transaction_type = 'TRANSFER_OUT'` + ); + + await queryInterface.sequelize.query( + `UPDATE wms_stock_transaction + SET transaction_type = 'INBOUND' + WHERE transaction_type = 'TRANSFER_IN'` + ); + + await queryInterface.changeColumn('wms_stock_transaction', 'transaction_type', { + type: Sequelize.ENUM('INBOUND', 'OUTBOUND'), + allowNull: false, + comment: '出入库类型', + }); + + if (await hasColumn(queryInterface, 'wms_stock_transaction', 'storage_id')) { + await queryInterface.removeColumn('wms_stock_transaction', 'storage_id'); + } + + if (await hasColumn(queryInterface, 'wms_stock_transaction', 'space_id')) { + await queryInterface.removeColumn('wms_stock_transaction', 'space_id'); + } + + if (await hasColumn(queryInterface, 'wms_stock_transaction', 'inventory_type')) { + await queryInterface.removeColumn('wms_stock_transaction', 'inventory_type'); + } +}; + +/** + * 回滚恢复 wms_stock_transaction 字段与枚举: + * 1) 恢复 storage_id/space_id/inventory_type 三列; + * 2) transaction_type 恢复 TRANSFER_OUT/TRANSFER_IN 枚举值。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async (queryInterface, Sequelize) => { + if (!(await hasColumn(queryInterface, 'wms_stock_transaction', 'storage_id'))) { + await queryInterface.addColumn('wms_stock_transaction', 'storage_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位库存ID,关联 wms_storage.id', + }); + } + + if (!(await hasColumn(queryInterface, 'wms_stock_transaction', 'space_id'))) { + await queryInterface.addColumn('wms_stock_transaction', 'space_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }); + } + + if (!(await hasColumn(queryInterface, 'wms_stock_transaction', 'inventory_type'))) { + await queryInterface.addColumn('wms_stock_transaction', 'inventory_type', { + type: Sequelize.ENUM('ZP', 'CC', 'JS', 'XS', 'ZT', 'DJ', 'FP'), + allowNull: true, + defaultValue: 'ZP', + comment: '库存类型', + }); + } + + await queryInterface.changeColumn('wms_stock_transaction', 'transaction_type', { + type: Sequelize.ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'), + allowNull: false, + comment: '出入库类型', + }); +}; diff --git a/database/migrations/20260519110000-add-expense-record-to-wms-entry-order.js b/database/migrations/20260519110000-add-expense-record-to-wms-entry-order.js new file mode 100644 index 0000000..58b8086 --- /dev/null +++ b/database/migrations/20260519110000-add-expense-record-to-wms-entry-order.js @@ -0,0 +1,33 @@ +'use strict'; + +/** + * 为入库单主表增加费用是否记录字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 expense_record 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_entry_order', 'expense_record', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '费用是否记录', + }); + }, + + /** + * 回滚迁移:删除 expense_record 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + await queryInterface.removeColumn('wms_entry_order', 'expense_record'); + }, +}; diff --git a/database/migrations/20260519183000-create-wms-review-task.js b/database/migrations/20260519183000-create-wms-review-task.js new file mode 100644 index 0000000..990b0c8 --- /dev/null +++ b/database/migrations/20260519183000-create-wms-review-task.js @@ -0,0 +1,252 @@ +'use strict'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建通用时间字段。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {{create_time: object, update_time: object, deleted_at: object}} 时间字段定义。 + */ +const buildTimeColumns = Sequelize => ({ + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '删除时间', + }, +}); + +/** + * 创建单表复核任务明细表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createReviewTaskTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_recheck_task', { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + review_no: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '复核单号', + }, + line_no: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 1, + comment: '明细序号', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + task_type: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '任务类型:1=散单 2=团购波次', + }, + source_task_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_wave_pick_task.id', + }, + wave_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '波次ID', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID', + }, + order_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '订单号', + }, + package_seq: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 1, + comment: '包裹序号', + }, + expected_waybill_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '预期运单号', + }, + waybill_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '实扫运单号', + }, + task_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0=待开始 1=复核中 2=完成 3=异常 9=取消', + }, + scan_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '扫描状态:0=未扫 1=已扫 2=异常', + }, + review_emp_no: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '复核人工号', + }, + review_emp_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '复核人姓名', + }, + scan_emp_no: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '扫描人工号', + }, + scan_emp_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '扫描人姓名', + }, + device_id: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '设备ID', + }, + start_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '开始时间', + }, + finish_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '完成时间', + }, + scan_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '扫描时间', + }, + remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '备注', + }, + ext_json: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展信息JSON', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '单表复核任务明细表', + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'review_no', 'line_no' ], { + name: 'uk_review_no_line_no', + unique: true, + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'review_no', 'waybill_no' ], { + name: 'uk_review_no_waybill_no', + unique: true, + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'warehouse_id', 'task_status' ], { + name: 'idx_warehouse_task_status', + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'warehouse_id', 'task_type' ], { + name: 'idx_warehouse_task_type', + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'warehouse_id', 'review_no' ], { + name: 'idx_warehouse_review_no', + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'source_task_id' ], { + name: 'idx_source_task_id', + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'wave_id' ], { + name: 'idx_wave_id', + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'order_id' ], { + name: 'idx_order_id', + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'waybill_no' ], { + name: 'idx_waybill_no', + }); + + await queryInterface.addIndex('wms_recheck_task', [ 'review_no', 'scan_status' ], { + name: 'idx_review_no_scan_status', + }); +}; + +/** + * 新增单表复核任务明细表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + const tableSet = await getExistingTableSet(queryInterface); + if (tableSet.has('wms_recheck_task')) { + return; + } + + await createReviewTaskTable(queryInterface, Sequelize); +}; + +/** + * 回滚删除单表复核任务明细表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async queryInterface => { + const tableSet = await getExistingTableSet(queryInterface); + if (!tableSet.has('wms_recheck_task')) { + return; + } + + await queryInterface.dropTable('wms_recheck_task'); +}; diff --git a/database/migrations/20260519193000-create-wms-pack-task-tables.js b/database/migrations/20260519193000-create-wms-pack-task-tables.js new file mode 100644 index 0000000..46187a8 --- /dev/null +++ b/database/migrations/20260519193000-create-wms-pack-task-tables.js @@ -0,0 +1,212 @@ +'use strict'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建通用时间字段。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {{create_time: object, update_time: object, deleted_at: object}} 时间字段定义。 + */ +const buildTimeColumns = Sequelize => ({ + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '删除时间', + }, +}); + +/** + * 创建打包任务主表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPackTaskTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_pack_task', { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + pack_mode: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '打包模式:1=散单 2=团购', + }, + status: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0=待处理', + }, + primary_packer_emp_id: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '主打包人工号ID', + }, + primary_packer_emp_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '主打包人工号', + }, + primary_packer_name: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '主打包人姓名', + }, + packers_snapshot: { + type: Sequelize.JSON, + allowNull: true, + comment: '打包人快照:散单对象/团购数组', + }, + meta: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展信息JSON', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '打包任务主表', + }); + + await queryInterface.addIndex('wms_pack_task', [ 'order_id' ], { + name: 'idx_order_id', + }); + + await queryInterface.addIndex('wms_pack_task', [ 'primary_packer_emp_id' ], { + name: 'idx_primary_packer_emp_id', + }); + + await queryInterface.addIndex('wms_pack_task', [ 'pack_mode', 'status' ], { + name: 'idx_pack_mode_status', + }); +}; + +/** + * 创建打包任务-打包人关系表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPackTaskPackerTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_pack_task_packer', { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + pack_task_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '打包任务ID', + }, + emp_id: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + comment: '打包人工号ID', + }, + emp_no: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '打包人工号', + }, + emp_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '打包人姓名', + }, + seq: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '排序序号', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '打包任务-打包人关系表', + }); + + await queryInterface.addIndex('wms_pack_task_packer', [ 'pack_task_id', 'emp_id' ], { + name: 'uix_pack_task_emp', + unique: true, + }); + + await queryInterface.addIndex('wms_pack_task_packer', [ 'emp_id' ], { + name: 'idx_emp_id', + }); + + await queryInterface.addIndex('wms_pack_task_packer', [ 'pack_task_id' ], { + name: 'idx_pack_task_id', + }); +}; + +/** + * 创建打包任务相关表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + const tableSet = await getExistingTableSet(queryInterface); + + if (!tableSet.has('wms_pack_task')) { + await createPackTaskTable(queryInterface, Sequelize); + } + + if (!tableSet.has('wms_pack_task_packer')) { + await createPackTaskPackerTable(queryInterface, Sequelize); + } +}; + +/** + * 回滚删除打包任务相关表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async queryInterface => { + const tableSet = await getExistingTableSet(queryInterface); + + if (tableSet.has('wms_pack_task_packer')) { + await queryInterface.dropTable('wms_pack_task_packer'); + } + + if (tableSet.has('wms_pack_task')) { + await queryInterface.dropTable('wms_pack_task'); + } +}; diff --git a/database/migrations/20260519200000-add-print-task-code-to-wms-print-record.js b/database/migrations/20260519200000-add-print-task-code-to-wms-print-record.js new file mode 100644 index 0000000..07469c7 --- /dev/null +++ b/database/migrations/20260519200000-add-print-task-code-to-wms-print-record.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为打印记录表新增自定义打印任务编码字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 print_task_code 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_print_record'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.print_task_code) { + return; + } + + await queryInterface.addColumn(tableName, 'print_task_code', { + type: Sequelize.TEXT, + allowNull: true, + comment: '自定义打印任务编码,多个编码以逗号分隔', + }); + }, + + /** + * 回滚迁移:删除 print_task_code 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_print_record'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.print_task_code) { + return; + } + + await queryInterface.removeColumn(tableName, 'print_task_code'); + }, +}; diff --git a/database/migrations/20260519210000-create-wms-print-task-map.js b/database/migrations/20260519210000-create-wms-print-task-map.js new file mode 100644 index 0000000..9096fea --- /dev/null +++ b/database/migrations/20260519210000-create-wms-print-task-map.js @@ -0,0 +1,105 @@ +'use strict'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +/** + * 创建打印任务去重映射表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPrintTaskMapTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_print_task_map', { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_code: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '打印任务编码', + }, + print_record_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联打印记录ID', + }, + provider: { + type: Sequelize.STRING(64), + allowNull: true, + comment: 'provider返回任务ID或标识', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + comment: '打印任务唯一映射表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); +}; + +/** + * 新增打印任务唯一映射表(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + const tableName = 'wms_print_task_map'; + const tableSet = await getExistingTableSet(queryInterface); + if (!tableSet.has(tableName)) { + await createPrintTaskMapTable(queryInterface, Sequelize); + } + + const indexNameSet = await getIndexNameSet(queryInterface, tableName); + if (!indexNameSet.has('uix_task_code')) { + await queryInterface.addIndex(tableName, [ 'task_code' ], { + name: 'uix_task_code', + unique: true, + }); + } +}; + +/** + * 回滚删除打印任务唯一映射表(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async queryInterface => { + const tableName = 'wms_print_task_map'; + const tableSet = await getExistingTableSet(queryInterface); + if (!tableSet.has(tableName)) { + return; + } + + await queryInterface.dropTable(tableName); +}; diff --git a/database/migrations/20260519223000-add-association-fields-to-wms-print-record.js b/database/migrations/20260519223000-add-association-fields-to-wms-print-record.js new file mode 100644 index 0000000..98e6ae8 --- /dev/null +++ b/database/migrations/20260519223000-add-association-fields-to-wms-print-record.js @@ -0,0 +1,179 @@ +'use strict'; + +/** + * 获取打印记录表字段定义。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async queryInterface => { + return queryInterface.describeTable('wms_print_record'); +}; + +/** + * 获取打印记录表索引名称集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 索引名称集合。 + */ +const getIndexNameSet = async queryInterface => { + const indexes = await queryInterface.showIndex('wms_print_record'); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +/** + * 执行迁移:为打印记录新增关联字段与索引(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + const tableName = 'wms_print_record'; + const columns = await getTableColumns(queryInterface); + + if (!columns.request_code) { + await queryInterface.addColumn(tableName, 'request_code', { + type: Sequelize.STRING(128), + allowNull: true, + comment: '请求参数码', + }); + } + + if (!columns.wave_id) { + await queryInterface.addColumn(tableName, 'wave_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '波次ID', + }); + } + + if (!columns.wave_no) { + await queryInterface.addColumn(tableName, 'wave_no', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '波次号', + }); + } + + if (!columns.platform_code) { + await queryInterface.addColumn(tableName, 'platform_code', { + type: Sequelize.STRING(32), + allowNull: true, + comment: '平台编码', + }); + } + + if (!columns.platform_name) { + await queryInterface.addColumn(tableName, 'platform_name', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '平台名称', + }); + } + + if (!columns.sys_logistics_code) { + await queryInterface.addColumn(tableName, 'sys_logistics_code', { + type: Sequelize.STRING(32), + allowNull: true, + comment: '系统快递编码', + }); + } + + if (!columns.sys_logistics_name) { + await queryInterface.addColumn(tableName, 'sys_logistics_name', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '系统快递名称', + }); + } + + const indexNameSet = await getIndexNameSet(queryInterface); + + if (!indexNameSet.has('idx_request_code')) { + await queryInterface.addIndex(tableName, [ 'request_code' ], { + name: 'idx_request_code', + }); + } + + if (!indexNameSet.has('idx_wave_id')) { + await queryInterface.addIndex(tableName, [ 'wave_id' ], { + name: 'idx_wave_id', + }); + } + + if (!indexNameSet.has('idx_platform_code')) { + await queryInterface.addIndex(tableName, [ 'platform_code' ], { + name: 'idx_platform_code', + }); + } + + if (!indexNameSet.has('idx_sys_logistics_code')) { + await queryInterface.addIndex(tableName, [ 'sys_logistics_code' ], { + name: 'idx_sys_logistics_code', + }); + } + + if (!indexNameSet.has('idx_wave_platform_status')) { + await queryInterface.addIndex(tableName, [ 'wave_id', 'platform_code', 'status' ], { + name: 'idx_wave_platform_status', + }); + } +}; + +/** + * 回滚迁移:移除打印记录关联字段与索引(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async queryInterface => { + const tableName = 'wms_print_record'; + const indexNameSet = await getIndexNameSet(queryInterface); + + if (indexNameSet.has('idx_wave_platform_status')) { + await queryInterface.removeIndex(tableName, 'idx_wave_platform_status'); + } + + if (indexNameSet.has('idx_sys_logistics_code')) { + await queryInterface.removeIndex(tableName, 'idx_sys_logistics_code'); + } + + if (indexNameSet.has('idx_platform_code')) { + await queryInterface.removeIndex(tableName, 'idx_platform_code'); + } + + if (indexNameSet.has('idx_wave_id')) { + await queryInterface.removeIndex(tableName, 'idx_wave_id'); + } + + if (indexNameSet.has('idx_request_code')) { + await queryInterface.removeIndex(tableName, 'idx_request_code'); + } + + const columns = await getTableColumns(queryInterface); + + if (columns.sys_logistics_name) { + await queryInterface.removeColumn(tableName, 'sys_logistics_name'); + } + + if (columns.sys_logistics_code) { + await queryInterface.removeColumn(tableName, 'sys_logistics_code'); + } + + if (columns.platform_name) { + await queryInterface.removeColumn(tableName, 'platform_name'); + } + + if (columns.platform_code) { + await queryInterface.removeColumn(tableName, 'platform_code'); + } + + if (columns.wave_no) { + await queryInterface.removeColumn(tableName, 'wave_no'); + } + + if (columns.wave_id) { + await queryInterface.removeColumn(tableName, 'wave_id'); + } + + if (columns.request_code) { + await queryInterface.removeColumn(tableName, 'request_code'); + } +}; diff --git a/database/migrations/20260519230000-add-retry-fields-to-wms-print-record.js b/database/migrations/20260519230000-add-retry-fields-to-wms-print-record.js new file mode 100644 index 0000000..7700b09 --- /dev/null +++ b/database/migrations/20260519230000-add-retry-fields-to-wms-print-record.js @@ -0,0 +1,195 @@ +'use strict'; + +/** + * 获取打印记录表字段定义。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async queryInterface => { + return queryInterface.describeTable('wms_print_record'); +}; + +/** + * 获取打印记录表索引名称集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 索引名称集合。 + */ +const getIndexNameSet = async queryInterface => { + const indexes = await queryInterface.showIndex('wms_print_record'); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +/** + * 执行迁移:为打印记录表新增补偿重试字段与索引(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + const tableName = 'wms_print_record'; + const columns = await getTableColumns(queryInterface); + + if (!columns.send_status) { + await queryInterface.addColumn(tableName, 'send_status', { + type: Sequelize.STRING(32), + allowNull: false, + defaultValue: 'pending', + comment: '发送状态', + }); + } + + if (!columns.print_status) { + await queryInterface.addColumn(tableName, 'print_status', { + type: Sequelize.STRING(32), + allowNull: false, + defaultValue: 'unknown', + comment: '打印状态', + }); + } + + if (!columns.retry_count) { + await queryInterface.addColumn(tableName, 'retry_count', { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '已重试次数', + }); + } + + if (!columns.max_retry_count) { + await queryInterface.addColumn(tableName, 'max_retry_count', { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 3, + comment: '最大重试次数', + }); + } + + if (!columns.next_retry_at) { + await queryInterface.addColumn(tableName, 'next_retry_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '下次重试时间', + }); + } + + if (!columns.last_retry_at) { + await queryInterface.addColumn(tableName, 'last_retry_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '最后重试时间', + }); + } + + if (!columns.fail_code) { + await queryInterface.addColumn(tableName, 'fail_code', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '失败编码', + }); + } + + if (!columns.retry_of_print_id) { + await queryInterface.addColumn(tableName, 'retry_of_print_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '补偿来源打印记录ID', + }); + } + + const indexNameSet = await getIndexNameSet(queryInterface); + + if (!indexNameSet.has('idx_send_status')) { + await queryInterface.addIndex(tableName, [ 'send_status' ], { + name: 'idx_send_status', + }); + } + + if (!indexNameSet.has('idx_print_status')) { + await queryInterface.addIndex(tableName, [ 'print_status' ], { + name: 'idx_print_status', + }); + } + + if (!indexNameSet.has('idx_next_retry_at')) { + await queryInterface.addIndex(tableName, [ 'next_retry_at' ], { + name: 'idx_next_retry_at', + }); + } + + if (!indexNameSet.has('idx_retry_of_print_id')) { + await queryInterface.addIndex(tableName, [ 'retry_of_print_id' ], { + name: 'idx_retry_of_print_id', + }); + } + + if (!indexNameSet.has('idx_print_status_next_retry')) { + await queryInterface.addIndex(tableName, [ 'print_status', 'next_retry_at' ], { + name: 'idx_print_status_next_retry', + }); + } +}; + +/** + * 回滚迁移:移除打印记录表补偿重试字段与索引(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async queryInterface => { + const tableName = 'wms_print_record'; + const indexNameSet = await getIndexNameSet(queryInterface); + + if (indexNameSet.has('idx_print_status_next_retry')) { + await queryInterface.removeIndex(tableName, 'idx_print_status_next_retry'); + } + + if (indexNameSet.has('idx_retry_of_print_id')) { + await queryInterface.removeIndex(tableName, 'idx_retry_of_print_id'); + } + + if (indexNameSet.has('idx_next_retry_at')) { + await queryInterface.removeIndex(tableName, 'idx_next_retry_at'); + } + + if (indexNameSet.has('idx_print_status')) { + await queryInterface.removeIndex(tableName, 'idx_print_status'); + } + + if (indexNameSet.has('idx_send_status')) { + await queryInterface.removeIndex(tableName, 'idx_send_status'); + } + + const columns = await getTableColumns(queryInterface); + + if (columns.retry_of_print_id) { + await queryInterface.removeColumn(tableName, 'retry_of_print_id'); + } + + if (columns.fail_code) { + await queryInterface.removeColumn(tableName, 'fail_code'); + } + + if (columns.last_retry_at) { + await queryInterface.removeColumn(tableName, 'last_retry_at'); + } + + if (columns.next_retry_at) { + await queryInterface.removeColumn(tableName, 'next_retry_at'); + } + + if (columns.max_retry_count) { + await queryInterface.removeColumn(tableName, 'max_retry_count'); + } + + if (columns.retry_count) { + await queryInterface.removeColumn(tableName, 'retry_count'); + } + + if (columns.print_status) { + await queryInterface.removeColumn(tableName, 'print_status'); + } + + if (columns.send_status) { + await queryInterface.removeColumn(tableName, 'send_status'); + } +}; diff --git a/database/migrations/20260520101000-rename-wms-review-task-to-recheck-task.js b/database/migrations/20260520101000-rename-wms-review-task-to-recheck-task.js new file mode 100644 index 0000000..81c6778 --- /dev/null +++ b/database/migrations/20260520101000-rename-wms-review-task-to-recheck-task.js @@ -0,0 +1,45 @@ +'use strict'; + +/** + * 获取当前数据库已存在的表名集合(兼容 showAllTables 返回字符串或对象)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 升级迁移:将 wms_review_task 重命名为 wms_recheck_task。 + * 仅在旧表存在且新表不存在时执行,其他情况安全跳过。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async queryInterface => { + const sourceTable = 'wms_review_task'; + const targetTable = 'wms_recheck_task'; + const tableSet = await getExistingTableSet(queryInterface); + + if (tableSet.has(sourceTable) && !tableSet.has(targetTable)) { + await queryInterface.renameTable(sourceTable, targetTable); + } +}; + +/** + * 回滚迁移:将 wms_recheck_task 重命名回 wms_review_task。 + * 仅在旧表存在且新表不存在时执行,其他情况安全跳过。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async queryInterface => { + const sourceTable = 'wms_recheck_task'; + const targetTable = 'wms_review_task'; + const tableSet = await getExistingTableSet(queryInterface); + + if (tableSet.has(sourceTable) && !tableSet.has(targetTable)) { + await queryInterface.renameTable(sourceTable, targetTable); + } +}; diff --git a/database/migrations/20260521090000-add-customer-id-to-wms-qimen-apps.js b/database/migrations/20260521090000-add-customer-id-to-wms-qimen-apps.js new file mode 100644 index 0000000..6d560fa --- /dev/null +++ b/database/migrations/20260521090000-add-customer-id-to-wms-qimen-apps.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为奇门应用配置表新增 customer_id 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 customer_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_qimen_apps'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.customer_id) { + return; + } + + await queryInterface.addColumn(tableName, 'customer_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '客户标识', + }); + }, + + /** + * 回滚迁移:删除 customer_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_qimen_apps'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.customer_id) { + return; + } + + await queryInterface.removeColumn(tableName, 'customer_id'); + }, +}; diff --git a/database/migrations/20260521113000-add-ext-data-to-wms-express-interface.js b/database/migrations/20260521113000-add-ext-data-to-wms-express-interface.js new file mode 100644 index 0000000..e7ed9b2 --- /dev/null +++ b/database/migrations/20260521113000-add-ext-data-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增扩展信息字段 ext_data。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 ext_data 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.ext_data) { + return; + } + + await queryInterface.addColumn(tableName, 'ext_data', { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展信息', + }); + }, + + /** + * 回滚迁移:删除 ext_data 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.ext_data) { + return; + } + + await queryInterface.removeColumn(tableName, 'ext_data'); + }, +}; diff --git a/database/migrations/20260522103000-create-shops.js b/database/migrations/20260522103000-create-shops.js new file mode 100644 index 0000000..c47ad1d --- /dev/null +++ b/database/migrations/20260522103000-create-shops.js @@ -0,0 +1,128 @@ +'use strict'; + +const TABLE_NAME = 'wms_shops'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 创建店铺表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createShopsTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + platform_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '平台编码', + }, + shop_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '店铺名称', + }, + status: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '授权状态:0=未授权,1=已授权', + }, + auth_expire_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '授权到期时间', + }, + auth_random_code: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '授权随机码', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '店铺表', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'platform_code' ], { + name: 'idx_platform_code', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { + name: 'idx_status', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'platform_code', 'shop_name' ], { + name: 'uk_warehouse_platform_shop_name', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'auth_random_code' ], { + name: 'uk_auth_random_code', + unique: true, + }); +}; + +module.exports = { + /** + * 创建店铺表及索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTables = await getExistingTableSet(queryInterface); + if (!existingTables.has(TABLE_NAME)) { + await createShopsTable(queryInterface, Sequelize); + } + }, + + /** + * 回滚删除店铺表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + void Sequelize; + + const existingTables = await getExistingTableSet(queryInterface); + if (existingTables.has(TABLE_NAME)) { + await queryInterface.dropTable(TABLE_NAME); + } + }, +}; diff --git a/database/migrations/20260522110000-add-auth-base-url-to-wms_platform.js b/database/migrations/20260522110000-add-auth-base-url-to-wms_platform.js new file mode 100644 index 0000000..2e47399 --- /dev/null +++ b/database/migrations/20260522110000-add-auth-base-url-to-wms_platform.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为 wms_platform 新增 auth_base_url 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 auth_base_url 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_platform'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.auth_base_url) { + return; + } + + await queryInterface.addColumn(tableName, 'auth_base_url', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '授权基础地址', + }); + }, + + /** + * 回滚迁移:删除 auth_base_url 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_platform'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.auth_base_url) { + return; + } + + await queryInterface.removeColumn(tableName, 'auth_base_url'); + }, +}; diff --git a/database/migrations/20260522123000-add-auth-result-fields-to-wms-shops.js b/database/migrations/20260522123000-add-auth-result-fields-to-wms-shops.js new file mode 100644 index 0000000..67f9722 --- /dev/null +++ b/database/migrations/20260522123000-add-auth-result-fields-to-wms-shops.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * 为店铺表新增授权结果字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增授权结果字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_shops'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.owner_id) { + await queryInterface.addColumn(tableName, 'owner_id', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '平台店铺/主体ID', + }); + } + + if (!columns.access_token) { + await queryInterface.addColumn(tableName, 'access_token', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '访问令牌', + }); + } + + if (!columns.refresh_token) { + await queryInterface.addColumn(tableName, 'refresh_token', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '刷新令牌', + }); + } + + if (!columns.token_expires_at) { + await queryInterface.addColumn(tableName, 'token_expires_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '访问令牌过期时间', + }); + } + + if (!columns.refresh_token_expires_at) { + await queryInterface.addColumn(tableName, 'refresh_token_expires_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '刷新令牌过期时间', + }); + } + + if (!columns.scope) { + await queryInterface.addColumn(tableName, 'scope', { + type: Sequelize.JSON, + allowNull: true, + comment: '授权范围', + }); + } + }, + + /** + * 回滚迁移:删除授权结果字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_shops'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.scope) { + await queryInterface.removeColumn(tableName, 'scope'); + } + + if (columns.refresh_token_expires_at) { + await queryInterface.removeColumn(tableName, 'refresh_token_expires_at'); + } + + if (columns.token_expires_at) { + await queryInterface.removeColumn(tableName, 'token_expires_at'); + } + + if (columns.refresh_token) { + await queryInterface.removeColumn(tableName, 'refresh_token'); + } + + if (columns.access_token) { + await queryInterface.removeColumn(tableName, 'access_token'); + } + + if (columns.owner_id) { + await queryInterface.removeColumn(tableName, 'owner_id'); + } + }, +}; diff --git a/database/migrations/20260522133000-add-custom-name-to-wms-shops.js b/database/migrations/20260522133000-add-custom-name-to-wms-shops.js new file mode 100644 index 0000000..1621a4a --- /dev/null +++ b/database/migrations/20260522133000-add-custom-name-to-wms-shops.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 为店铺表新增自定义名称字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增店铺自定义名称字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_shops'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.custom_name) { + await queryInterface.addColumn(tableName, 'custom_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '店铺自定义名称', + }); + } + }, + + /** + * 回滚迁移:删除店铺自定义名称字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_shops'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.custom_name) { + await queryInterface.removeColumn(tableName, 'custom_name'); + } + }, +}; diff --git a/database/migrations/20260522143000-add-shop-id-to-wms-express-interface.js b/database/migrations/20260522143000-add-shop-id-to-wms-express-interface.js new file mode 100644 index 0000000..0a33f7c --- /dev/null +++ b/database/migrations/20260522143000-add-shop-id-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增店铺 ID 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增店铺 ID 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.shop_id) { + return; + } + + await queryInterface.addColumn(tableName, 'shop_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '店铺ID', + }); + }, + + /** + * 回滚迁移:删除店铺 ID 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.shop_id) { + return; + } + + await queryInterface.removeColumn(tableName, 'shop_id'); + }, +}; diff --git a/database/migrations/20260523120000-expand-device-length-on-wms-system-log.js b/database/migrations/20260523120000-expand-device-length-on-wms-system-log.js new file mode 100644 index 0000000..e1f6d5a --- /dev/null +++ b/database/migrations/20260523120000-expand-device-length-on-wms-system-log.js @@ -0,0 +1,61 @@ +'use strict'; + +/** + * 扩容系统日志表 device 字段长度到 100。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:将 wms_system_log.device 调整为 VARCHAR(100)(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_system_log'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.device) { + return; + } + + const currentLength = Number(columns.device.length || 0); + if (currentLength >= 100) { + return; + } + + await queryInterface.changeColumn(tableName, 'device', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '设备', + }); + }, + + /** + * 回滚迁移:将 wms_system_log.device 调整回 VARCHAR(10)(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const tableName = 'wms_system_log'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.device) { + return; + } + + const currentLength = Number(columns.device.length || 0); + if (currentLength > 0 && currentLength <= 10) { + return; + } + + await queryInterface.changeColumn(tableName, 'device', { + type: Sequelize.STRING(10), + allowNull: true, + comment: '设备', + }); + }, +}; diff --git a/database/migrations/20260523130000-add-cainiao-to-wms-express.js b/database/migrations/20260523130000-add-cainiao-to-wms-express.js new file mode 100644 index 0000000..f7e1114 --- /dev/null +++ b/database/migrations/20260523130000-add-cainiao-to-wms-express.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递基础信息表新增菜鸟编码字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 CAINIAO 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.CAINIAO) { + return; + } + + await queryInterface.addColumn(tableName, 'CAINIAO', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '菜鸟编码', + }); + }, + + /** + * 回滚迁移:删除 CAINIAO 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.CAINIAO) { + return; + } + + await queryInterface.removeColumn(tableName, 'CAINIAO'); + }, +}; diff --git a/database/migrations/20260524093000-add-is-hide-goods-to-wms-express-interface.js b/database/migrations/20260524093000-add-is-hide-goods-to-wms-express-interface.js new file mode 100644 index 0000000..21f6f24 --- /dev/null +++ b/database/migrations/20260524093000-add-is-hide-goods-to-wms-express-interface.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * 为快递接口配置表新增是否隐藏物品信息字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 is_hide_goods 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.is_hide_goods) { + return; + } + + await queryInterface.addColumn(tableName, 'is_hide_goods', { + type: Sequelize.TINYINT(1), + allowNull: true, + defaultValue: 0, + comment: '是否隐藏物品信息', + }); + }, + + /** + * 回滚迁移:删除 is_hide_goods 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.is_hide_goods) { + return; + } + + await queryInterface.removeColumn(tableName, 'is_hide_goods'); + }, +}; diff --git a/database/migrations/20260524110000-create-wms-print-platform.js b/database/migrations/20260524110000-create-wms-print-platform.js new file mode 100644 index 0000000..cb876b9 --- /dev/null +++ b/database/migrations/20260524110000-create-wms-print-platform.js @@ -0,0 +1,142 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +/** + * 创建打印平台元数据表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPrintPlatformTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + platform_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '打印平台编码', + }, + platform_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '打印平台名称', + }, + status: { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'ACTIVE', + comment: '状态', + }, + remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '备注', + }, + create_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '软删除标记:0-未删除,1-已删除', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '打印平台元数据表', + }); +}; + +/** + * 确保打印平台元数据表索引存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +const ensurePrintPlatformIndexes = async queryInterface => { + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + + if (!indexNameSet.has('uk_platform_code')) { + await queryInterface.addIndex(TABLE_NAME, [ 'platform_code' ], { + name: 'uk_platform_code', + unique: true, + }); + } + + if (!indexNameSet.has('idx_status')) { + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { + name: 'idx_status', + }); + } +}; + +module.exports = { + /** + * 创建打印平台元数据表及索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTables = await getExistingTableSet(queryInterface); + if (!existingTables.has(TABLE_NAME)) { + await createPrintPlatformTable(queryInterface, Sequelize); + } + + await ensurePrintPlatformIndexes(queryInterface); + }, + + /** + * 回滚删除打印平台元数据表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + void Sequelize; + + const existingTables = await getExistingTableSet(queryInterface); + if (existingTables.has(TABLE_NAME)) { + await queryInterface.dropTable(TABLE_NAME); + } + }, +}; diff --git a/database/migrations/20260524113000-add-print-platform-id-to-wms-platform.js b/database/migrations/20260524113000-add-print-platform-id-to-wms-platform.js new file mode 100644 index 0000000..e0f2295 --- /dev/null +++ b/database/migrations/20260524113000-add-print-platform-id-to-wms-platform.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为 wms_platform 新增 print_platform_id 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 print_platform_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_platform'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.print_platform_id) { + return; + } + + await queryInterface.addColumn(tableName, 'print_platform_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联打印平台ID', + }); + }, + + /** + * 回滚迁移:删除 print_platform_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_platform'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.print_platform_id) { + return; + } + + await queryInterface.removeColumn(tableName, 'print_platform_id'); + }, +}; diff --git a/database/migrations/20260524120000-drop-unused-fields-from-wms-print-platform.js b/database/migrations/20260524120000-drop-unused-fields-from-wms-print-platform.js new file mode 100644 index 0000000..56980f5 --- /dev/null +++ b/database/migrations/20260524120000-drop-unused-fields-from-wms-print-platform.js @@ -0,0 +1,117 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const SORT_INDEX_NAME = 'idx_sort'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 获取指定表的字段定义。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 字段定义映射。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +module.exports = { + /** + * 正向迁移:幂等删除打印平台表中的废弃字段与排序索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const existingTables = await getExistingTableSet(queryInterface); + if (!existingTables.has(TABLE_NAME)) { + return; + } + + const columns = await getTableColumns(queryInterface, TABLE_NAME); + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + + if (indexNameSet.has(SORT_INDEX_NAME)) { + await queryInterface.removeIndex(TABLE_NAME, SORT_INDEX_NAME); + } + + if (columns.sort) { + await queryInterface.removeColumn(TABLE_NAME, 'sort'); + } + + if (columns.aliases) { + await queryInterface.removeColumn(TABLE_NAME, 'aliases'); + } + + if (columns.template_file) { + await queryInterface.removeColumn(TABLE_NAME, 'template_file'); + } + }, + + /** + * 回滚迁移:幂等恢复打印平台表中的废弃字段与排序索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const existingTables = await getExistingTableSet(queryInterface); + if (!existingTables.has(TABLE_NAME)) { + return; + } + + const columns = await getTableColumns(queryInterface, TABLE_NAME); + + if (!columns.aliases) { + await queryInterface.addColumn(TABLE_NAME, 'aliases', { + type: Sequelize.JSON, + allowNull: true, + comment: '平台别名数组', + }); + } + + if (!columns.template_file) { + await queryInterface.addColumn(TABLE_NAME, 'template_file', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '默认模板文件名', + }); + } + + if (!columns.sort) { + await queryInterface.addColumn(TABLE_NAME, 'sort', { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '排序值', + }); + } + + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + if (!indexNameSet.has(SORT_INDEX_NAME)) { + await queryInterface.addIndex(TABLE_NAME, [ 'sort' ], { + name: SORT_INDEX_NAME, + }); + } + }, +}; diff --git a/database/migrations/20260524130000-switch-express-interface-platform-fk-to-print-platform.js b/database/migrations/20260524130000-switch-express-interface-platform-fk-to-print-platform.js new file mode 100644 index 0000000..591e0bc --- /dev/null +++ b/database/migrations/20260524130000-switch-express-interface-platform-fk-to-print-platform.js @@ -0,0 +1,248 @@ +'use strict'; + +const SOURCE_TABLE = 'wms_express_interface'; +const SOURCE_COLUMN = 'platform_code'; +const OLD_TARGET_TABLE = 'wms_platform'; +const OLD_TARGET_COLUMN = 'code'; +const NEW_TARGET_TABLE = 'wms_print_platform'; +const NEW_TARGET_COLUMN = 'platform_code'; +const NEW_CONSTRAINT_NAME = 'fk_wms_express_interface_print_platform_code'; + +/** + * 获取数据库中的真实表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 安全读取指定表字段定义。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Set} existingTableSet 已存在表名集合。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义;表不存在时返回 null。 + */ +const getTableColumns = async (queryInterface, existingTableSet, tableName) => { + if (!existingTableSet.has(tableName)) { + return null; + } + + return queryInterface.describeTable(tableName); +}; + +/** + * 查询指定列上的外键信息。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 源表名。 + * @param {string} columnName 源列名。 + * @return {Promise>} 外键信息列表。 + */ +const getColumnForeignKeys = async (queryInterface, tableName, columnName) => { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT + kcu.CONSTRAINT_NAME AS constraintName, + kcu.TABLE_NAME AS tableName, + kcu.COLUMN_NAME AS columnName, + kcu.REFERENCED_TABLE_NAME AS referencedTableName, + kcu.REFERENCED_COLUMN_NAME AS referencedColumnName, + rc.UPDATE_RULE AS updateRule, + rc.DELETE_RULE AS deleteRule + FROM information_schema.KEY_COLUMN_USAGE kcu + INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS rc + ON rc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA + AND rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME + AND rc.TABLE_NAME = kcu.TABLE_NAME + WHERE kcu.CONSTRAINT_SCHEMA = DATABASE() + AND kcu.TABLE_NAME = :tableName + AND kcu.COLUMN_NAME = :columnName + AND kcu.REFERENCED_TABLE_NAME IS NOT NULL + `, + { + replacements: { + tableName, + columnName, + }, + } + ); + + return rows; +}; + +/** + * 删除指定列上指向目标表目标列的所有外键。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} sourceTable 源表名。 + * @param {string} sourceColumn 源列名。 + * @param {string} targetTable 目标表名。 + * @param {string} targetColumn 目标列名。 + * @return {Promise} 无返回值。 + */ +const dropForeignKeysByReference = async ( + queryInterface, + sourceTable, + sourceColumn, + targetTable, + targetColumn +) => { + const foreignKeys = await getColumnForeignKeys(queryInterface, sourceTable, sourceColumn); + + for (const foreignKey of foreignKeys) { + if ( + foreignKey.referencedTableName === targetTable && + foreignKey.referencedColumnName === targetColumn + ) { + await queryInterface.removeConstraint(sourceTable, foreignKey.constraintName); + } + } +}; + +/** + * 判断指定引用关系外键是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} sourceTable 源表名。 + * @param {string} sourceColumn 源列名。 + * @param {string} targetTable 目标表名。 + * @param {string} targetColumn 目标列名。 + * @return {Promise} 是否已存在。 + */ +const hasForeignKeyReference = async ( + queryInterface, + sourceTable, + sourceColumn, + targetTable, + targetColumn +) => { + const foreignKeys = await getColumnForeignKeys(queryInterface, sourceTable, sourceColumn); + + return foreignKeys.some(foreignKey => ( + foreignKey.referencedTableName === targetTable && + foreignKey.referencedColumnName === targetColumn + )); +}; + +/** + * 为指定列添加目标外键。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} sourceTable 源表名。 + * @param {string} sourceColumn 源列名。 + * @param {string} targetTable 目标表名。 + * @param {string} targetColumn 目标列名。 + * @param {string} constraintName 外键名称。 + * @return {Promise} 无返回值。 + */ +const addForeignKey = async ( + queryInterface, + sourceTable, + sourceColumn, + targetTable, + targetColumn, + constraintName +) => { + await queryInterface.addConstraint(sourceTable, { + fields: [ sourceColumn ], + type: 'foreign key', + name: constraintName, + references: { + table: targetTable, + field: targetColumn, + }, + onUpdate: 'RESTRICT', + onDelete: 'RESTRICT', + }); +}; + +module.exports = { + /** + * 将快递接口平台外键从平台表切换到打印平台表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + const sourceColumns = await getTableColumns(queryInterface, existingTableSet, SOURCE_TABLE); + const targetColumns = await getTableColumns(queryInterface, existingTableSet, NEW_TARGET_TABLE); + + if (!sourceColumns || !sourceColumns[SOURCE_COLUMN] || !targetColumns || !targetColumns[NEW_TARGET_COLUMN]) { + return; + } + + await dropForeignKeysByReference( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + OLD_TARGET_TABLE, + OLD_TARGET_COLUMN + ); + + const hasNewForeignKey = await hasForeignKeyReference( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + NEW_TARGET_TABLE, + NEW_TARGET_COLUMN + ); + + if (!hasNewForeignKey) { + await addForeignKey( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + NEW_TARGET_TABLE, + NEW_TARGET_COLUMN, + NEW_CONSTRAINT_NAME + ); + } + }, + + /** + * 回滚快递接口平台外键到原平台表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + const sourceColumns = await getTableColumns(queryInterface, existingTableSet, SOURCE_TABLE); + const oldTargetColumns = await getTableColumns(queryInterface, existingTableSet, OLD_TARGET_TABLE); + + if (!sourceColumns || !sourceColumns[SOURCE_COLUMN]) { + return; + } + + await dropForeignKeysByReference( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + NEW_TARGET_TABLE, + NEW_TARGET_COLUMN + ); + + if (!oldTargetColumns || !oldTargetColumns[OLD_TARGET_COLUMN]) { + return; + } + + const hasOldForeignKey = await hasForeignKeyReference( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + OLD_TARGET_TABLE, + OLD_TARGET_COLUMN + ); + + if (!hasOldForeignKey) { + await addForeignKey( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + OLD_TARGET_TABLE, + OLD_TARGET_COLUMN, + 'fk_wms_express_interface_platform_code' + ); + } + }, +}; diff --git a/database/migrations/20260524153000-switch-shop-platform-fk-to-print-platform.js b/database/migrations/20260524153000-switch-shop-platform-fk-to-print-platform.js new file mode 100644 index 0000000..2f05641 --- /dev/null +++ b/database/migrations/20260524153000-switch-shop-platform-fk-to-print-platform.js @@ -0,0 +1,242 @@ +'use strict'; + +const SOURCE_TABLE = 'wms_shops'; +const SOURCE_COLUMN = 'platform_code'; +const OLD_TARGET_TABLE = 'wms_platform'; +const OLD_TARGET_COLUMN = 'code'; +const NEW_TARGET_TABLE = 'wms_print_platform'; +const NEW_TARGET_COLUMN = 'platform_code'; +const NEW_CONSTRAINT_NAME = 'fk_wms_shops_print_platform_code'; + +/** + * 获取数据库中的真实表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 安全读取指定表字段定义。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Set} existingTableSet 已存在表名集合。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义;表不存在时返回 null。 + */ +const getTableColumns = async (queryInterface, existingTableSet, tableName) => { + if (!existingTableSet.has(tableName)) { + return null; + } + + return queryInterface.describeTable(tableName); +}; + +/** + * 查询指定列上的外键信息。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 源表名。 + * @param {string} columnName 源列名。 + * @return {Promise>} 外键信息列表。 + */ +const getColumnForeignKeys = async (queryInterface, tableName, columnName) => { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT + kcu.CONSTRAINT_NAME AS constraintName, + kcu.TABLE_NAME AS tableName, + kcu.COLUMN_NAME AS columnName, + kcu.REFERENCED_TABLE_NAME AS referencedTableName, + kcu.REFERENCED_COLUMN_NAME AS referencedColumnName + FROM information_schema.KEY_COLUMN_USAGE kcu + WHERE kcu.CONSTRAINT_SCHEMA = DATABASE() + AND kcu.TABLE_NAME = :tableName + AND kcu.COLUMN_NAME = :columnName + AND kcu.REFERENCED_TABLE_NAME IS NOT NULL + `, + { + replacements: { + tableName, + columnName, + }, + } + ); + + return rows; +}; + +/** + * 删除指定列上指向目标表目标列的所有外键。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} sourceTable 源表名。 + * @param {string} sourceColumn 源列名。 + * @param {string} targetTable 目标表名。 + * @param {string} targetColumn 目标列名。 + * @return {Promise} 无返回值。 + */ +const dropForeignKeysByReference = async ( + queryInterface, + sourceTable, + sourceColumn, + targetTable, + targetColumn +) => { + const foreignKeys = await getColumnForeignKeys(queryInterface, sourceTable, sourceColumn); + + for (const foreignKey of foreignKeys) { + if ( + foreignKey.referencedTableName === targetTable + && foreignKey.referencedColumnName === targetColumn + ) { + await queryInterface.removeConstraint(sourceTable, foreignKey.constraintName); + } + } +}; + +/** + * 判断指定引用关系外键是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} sourceTable 源表名。 + * @param {string} sourceColumn 源列名。 + * @param {string} targetTable 目标表名。 + * @param {string} targetColumn 目标列名。 + * @return {Promise} 是否已存在。 + */ +const hasForeignKeyReference = async ( + queryInterface, + sourceTable, + sourceColumn, + targetTable, + targetColumn +) => { + const foreignKeys = await getColumnForeignKeys(queryInterface, sourceTable, sourceColumn); + + return foreignKeys.some(foreignKey => ( + foreignKey.referencedTableName === targetTable + && foreignKey.referencedColumnName === targetColumn + )); +}; + +/** + * 为指定列添加目标外键。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} sourceTable 源表名。 + * @param {string} sourceColumn 源列名。 + * @param {string} targetTable 目标表名。 + * @param {string} targetColumn 目标列名。 + * @param {string} constraintName 外键名称。 + * @return {Promise} 无返回值。 + */ +const addForeignKey = async ( + queryInterface, + sourceTable, + sourceColumn, + targetTable, + targetColumn, + constraintName +) => { + await queryInterface.addConstraint(sourceTable, { + fields: [ sourceColumn ], + type: 'foreign key', + name: constraintName, + references: { + table: targetTable, + field: targetColumn, + }, + onUpdate: 'RESTRICT', + onDelete: 'RESTRICT', + }); +}; + +module.exports = { + /** + * 将店铺平台外键切换到打印平台表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + const sourceColumns = await getTableColumns(queryInterface, existingTableSet, SOURCE_TABLE); + const targetColumns = await getTableColumns(queryInterface, existingTableSet, NEW_TARGET_TABLE); + + if (!sourceColumns || !sourceColumns[SOURCE_COLUMN] || !targetColumns || !targetColumns[NEW_TARGET_COLUMN]) { + return; + } + + await dropForeignKeysByReference( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + OLD_TARGET_TABLE, + OLD_TARGET_COLUMN + ); + + const hasNewForeignKey = await hasForeignKeyReference( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + NEW_TARGET_TABLE, + NEW_TARGET_COLUMN + ); + + if (!hasNewForeignKey) { + await addForeignKey( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + NEW_TARGET_TABLE, + NEW_TARGET_COLUMN, + NEW_CONSTRAINT_NAME + ); + } + }, + + /** + * 回滚店铺平台外键到原平台表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + const sourceColumns = await getTableColumns(queryInterface, existingTableSet, SOURCE_TABLE); + const oldTargetColumns = await getTableColumns(queryInterface, existingTableSet, OLD_TARGET_TABLE); + + if (!sourceColumns || !sourceColumns[SOURCE_COLUMN]) { + return; + } + + await dropForeignKeysByReference( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + NEW_TARGET_TABLE, + NEW_TARGET_COLUMN + ); + + if (!oldTargetColumns || !oldTargetColumns[OLD_TARGET_COLUMN]) { + return; + } + + const hasOldForeignKey = await hasForeignKeyReference( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + OLD_TARGET_TABLE, + OLD_TARGET_COLUMN + ); + + if (!hasOldForeignKey) { + await addForeignKey( + queryInterface, + SOURCE_TABLE, + SOURCE_COLUMN, + OLD_TARGET_TABLE, + OLD_TARGET_COLUMN, + 'fk_wms_shops_platform_code' + ); + } + }, +}; diff --git a/database/migrations/20260524170000-migrate-auth-base-url-to-wms-print-platform.js b/database/migrations/20260524170000-migrate-auth-base-url-to-wms-print-platform.js new file mode 100644 index 0000000..2b246c2 --- /dev/null +++ b/database/migrations/20260524170000-migrate-auth-base-url-to-wms-print-platform.js @@ -0,0 +1,93 @@ +'use strict'; + +const PLATFORM_TABLE_NAME = 'wms_platform'; +const PRINT_PLATFORM_TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'auth_base_url'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 安全读取指定表字段定义。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Set} existingTableSet 已存在表名集合。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义;表不存在时返回 null。 + */ +const getTableColumns = async (queryInterface, existingTableSet, tableName) => { + if (!existingTableSet.has(tableName)) { + return null; + } + + return queryInterface.describeTable(tableName); +}; + +/** + * 构建授权基础地址字段定义。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Object} 字段定义。 + */ +const buildAuthBaseUrlColumn = Sequelize => ({ + type: Sequelize.STRING(255), + allowNull: true, + comment: '授权基础地址', +}); + +module.exports = { + /** + * 正向迁移:将授权基础地址字段迁移到打印平台表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTableSet = await getExistingTableSet(queryInterface); + const printPlatformColumns = await getTableColumns(queryInterface, existingTableSet, PRINT_PLATFORM_TABLE_NAME); + const platformColumns = await getTableColumns(queryInterface, existingTableSet, PLATFORM_TABLE_NAME); + + if (printPlatformColumns && !printPlatformColumns[COLUMN_NAME]) { + await queryInterface.addColumn( + PRINT_PLATFORM_TABLE_NAME, + COLUMN_NAME, + buildAuthBaseUrlColumn(Sequelize) + ); + } + + if (platformColumns && platformColumns[COLUMN_NAME]) { + await queryInterface.removeColumn(PLATFORM_TABLE_NAME, COLUMN_NAME); + } + }, + + /** + * 回滚迁移:将授权基础地址字段恢复到平台表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const existingTableSet = await getExistingTableSet(queryInterface); + const printPlatformColumns = await getTableColumns(queryInterface, existingTableSet, PRINT_PLATFORM_TABLE_NAME); + const platformColumns = await getTableColumns(queryInterface, existingTableSet, PLATFORM_TABLE_NAME); + + if (platformColumns && !platformColumns[COLUMN_NAME]) { + await queryInterface.addColumn( + PLATFORM_TABLE_NAME, + COLUMN_NAME, + buildAuthBaseUrlColumn(Sequelize) + ); + } + + if (printPlatformColumns && printPlatformColumns[COLUMN_NAME]) { + await queryInterface.removeColumn(PRINT_PLATFORM_TABLE_NAME, COLUMN_NAME); + } + }, +}; diff --git a/database/migrations/20260524173000-add-template-url-to-wms-express-interface.js b/database/migrations/20260524173000-add-template-url-to-wms-express-interface.js new file mode 100644 index 0000000..4e53333 --- /dev/null +++ b/database/migrations/20260524173000-add-template-url-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增模板链接字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 template_url 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.template_url) { + return; + } + + await queryInterface.addColumn(tableName, 'template_url', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '打印模板链接', + }); + }, + + /** + * 回滚迁移:删除 template_url 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.template_url) { + return; + } + + await queryInterface.removeColumn(tableName, 'template_url'); + }, +}; diff --git a/database/migrations/20260524190000-add-ver-to-wms-order-express.js b/database/migrations/20260524190000-add-ver-to-wms-order-express.js new file mode 100644 index 0000000..67c1996 --- /dev/null +++ b/database/migrations/20260524190000-add-ver-to-wms-order-express.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为订单快递表新增打印版本号字段 ver。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 ver 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_order_express'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.ver) { + return; + } + + await queryInterface.addColumn(tableName, 'ver', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '打印版本号', + }); + }, + + /** + * 回滚迁移:删除 ver 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_order_express'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.ver) { + return; + } + + await queryInterface.removeColumn(tableName, 'ver'); + }, +}; diff --git a/database/migrations/20260525103000-add-platid-to-wms-print-platform.js b/database/migrations/20260525103000-add-platid-to-wms-print-platform.js new file mode 100644 index 0000000..ddbba30 --- /dev/null +++ b/database/migrations/20260525103000-add-platid-to-wms-print-platform.js @@ -0,0 +1,68 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'platid'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建打印平台 platid 字段定义。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Object} 字段定义。 + */ +const buildPlatidColumn = Sequelize => ({ + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '平台ID', +}); + +module.exports = { + /** + * 执行迁移:为打印平台表新增 platid 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildPlatidColumn(Sequelize)); + }, + + /** + * 回滚迁移:删除打印平台表的 platid 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260525113000-add-request-platform-code-to-wms-print-platform.js b/database/migrations/20260525113000-add-request-platform-code-to-wms-print-platform.js new file mode 100644 index 0000000..6cf65a8 --- /dev/null +++ b/database/migrations/20260525113000-add-request-platform-code-to-wms-print-platform.js @@ -0,0 +1,68 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'request_platform_code'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建打印平台请求平台编码字段定义。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Object} 字段定义。 + */ +const buildRequestPlatformCodeColumn = Sequelize => ({ + type: Sequelize.STRING(50), + allowNull: true, + comment: '请求平台编码', +}); + +module.exports = { + /** + * 执行迁移:为打印平台表新增 request_platform_code 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildRequestPlatformCodeColumn(Sequelize)); + }, + + /** + * 回滚迁移:删除打印平台表的 request_platform_code 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260525143000-drop-platform-code-from-wms-platform.js b/database/migrations/20260525143000-drop-platform-code-from-wms-platform.js new file mode 100644 index 0000000..f3f6eed --- /dev/null +++ b/database/migrations/20260525143000-drop-platform-code-from-wms-platform.js @@ -0,0 +1,61 @@ +'use strict'; + +const TABLE_NAME = 'wms_platform'; +const COLUMN_NAME = 'platform_code'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +module.exports = { + /** + * 正向迁移:幂等删除 wms_platform.platform_code。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const existingTables = await getExistingTableSet(queryInterface); + if (!existingTables.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, + + /** + * 回滚迁移:幂等恢复 wms_platform.platform_code。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const existingTables = await getExistingTableSet(queryInterface); + if (!existingTables.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.STRING(255), + allowNull: true, + comment: '平台编码', + }); + }, +}; diff --git a/database/migrations/20260526100000-add-need-callback-url-to-wms-print-platform.js b/database/migrations/20260526100000-add-need-callback-url-to-wms-print-platform.js new file mode 100644 index 0000000..a6e89e2 --- /dev/null +++ b/database/migrations/20260526100000-add-need-callback-url-to-wms-print-platform.js @@ -0,0 +1,69 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'need_callback_url'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建打印平台是否需要回调地址字段定义。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Object} 字段定义。 + */ +const buildNeedCallbackUrlColumn = Sequelize => ({ + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否需要回调地址:0-否,1-是', +}); + +module.exports = { + /** + * 执行迁移:为打印平台表新增 need_callback_url 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildNeedCallbackUrlColumn(Sequelize)); + }, + + /** + * 回滚迁移:删除打印平台表的 need_callback_url 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260527103000-alter-auth-base-url-type-on-wms-print-platform.js b/database/migrations/20260527103000-alter-auth-base-url-type-on-wms-print-platform.js new file mode 100644 index 0000000..e4e1d36 --- /dev/null +++ b/database/migrations/20260527103000-alter-auth-base-url-type-on-wms-print-platform.js @@ -0,0 +1,95 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'auth_base_url'; + +/** + * 归一化字段类型文本,便于进行幂等判断。 + * @param {Object} columnDefinition 字段定义。 + * @return {string} 归一化后的类型文本。 + */ +const normalizeColumnType = columnDefinition => { + return String(columnDefinition && columnDefinition.type ? columnDefinition.type : '') + .toLowerCase() + .replace(/\s+/g, ''); +}; + +/** + * 判断字段是否为 TEXT 类型。 + * @param {Object} columnDefinition 字段定义。 + * @return {boolean} 是否为 TEXT 类型。 + */ +const isTextType = columnDefinition => { + const normalizedType = normalizeColumnType(columnDefinition); + return normalizedType.includes('text'); +}; + +/** + * 判断字段是否为 VARCHAR(255) 类型。 + * @param {Object} columnDefinition 字段定义。 + * @return {boolean} 是否为 VARCHAR(255) 类型。 + */ +const isVarchar255Type = columnDefinition => { + const normalizedType = normalizeColumnType(columnDefinition); + return normalizedType.includes('varchar(255)'); +}; + +module.exports = { + /** + * 执行迁移:将 wms_print_platform.auth_base_url 调整为 TEXT(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tableNames = await queryInterface.showAllTables(); + const existingTableSet = new Set( + tableNames.map(table => (typeof table === 'string' ? table : table.tableName)) + ); + + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + const targetColumn = columns[COLUMN_NAME]; + if (!targetColumn || isTextType(targetColumn)) { + return; + } + + await queryInterface.changeColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.TEXT, + allowNull: true, + comment: '授权基础地址', + }); + }, + + /** + * 回滚迁移:将 wms_print_platform.auth_base_url 回滚为 STRING(255)(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const tableNames = await queryInterface.showAllTables(); + const existingTableSet = new Set( + tableNames.map(table => (typeof table === 'string' ? table : table.tableName)) + ); + + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + const targetColumn = columns[COLUMN_NAME]; + if (!targetColumn || isVarchar255Type(targetColumn)) { + return; + } + + await queryInterface.changeColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.STRING(255), + allowNull: true, + comment: '授权基础地址', + }); + }, +}; diff --git a/database/migrations/20260527114000-add-get-auth-platform-name-to-wms-print-platform.js b/database/migrations/20260527114000-add-get-auth-platform-name-to-wms-print-platform.js new file mode 100644 index 0000000..57450c4 --- /dev/null +++ b/database/migrations/20260527114000-add-get-auth-platform-name-to-wms-print-platform.js @@ -0,0 +1,69 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'get_auth_platform_name'; + +/** + * 判断目标字段是否已存在。 + * @param {Object} columns 字段定义集合。 + * @return {boolean} 字段是否存在。 + */ +const hasTargetColumn = columns => { + return Boolean(columns && columns[COLUMN_NAME]); +}; + +module.exports = { + /** + * 正向迁移:为打印平台表新增获取授权平台名称字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tableNames = await queryInterface.showAllTables(); + const existingTableSet = new Set( + tableNames.map(table => (typeof table === 'string' ? table : table.tableName)) + ); + + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (hasTargetColumn(columns)) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.STRING(100), + allowNull: true, + comment: '获取授权平台名称', + }); + }, + + /** + * 回滚迁移:删除打印平台表的获取授权平台名称字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + void Sequelize; + + const tableNames = await queryInterface.showAllTables(); + const existingTableSet = new Set( + tableNames.map(table => (typeof table === 'string' ? table : table.tableName)) + ); + + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!hasTargetColumn(columns)) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260527220000-migrate-wms-express-code-dyxd-to-dy.js b/database/migrations/20260527220000-migrate-wms-express-code-dyxd-to-dy.js new file mode 100644 index 0000000..045259f --- /dev/null +++ b/database/migrations/20260527220000-migrate-wms-express-code-dyxd-to-dy.js @@ -0,0 +1,160 @@ +'use strict'; + +const TABLE_NAME = 'wms_express'; +const OLD_CODE = 'DYXD'; +const NEW_CODE = 'DY'; + +/** + * 规范化 showAllTables 返回的表名。 + * @param {string|Object} table 表名或表对象。 + * @return {string} 规范化后的表名。 + */ +const normalizeTableName = table => { + if (typeof table === 'string') { + return table; + } + + return table && typeof table === 'object' + ? (table.tableName || table.name || '') + : ''; +}; + +/** + * 检查目标表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 目标表是否存在。 + */ +const hasTargetTable = async queryInterface => { + const allTables = await queryInterface.showAllTables(); + const tableSet = new Set((allTables || []).map(normalizeTableName)); + return tableSet.has(TABLE_NAME); +}; + +/** + * 读取指定编码的快递记录。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} code 快递编码。 + * @return {Promise} 快递记录;不存在时返回 null。 + */ +const findExpressByCode = async (queryInterface, code) => { + const rows = await queryInterface.sequelize.query( + `SELECT * FROM ${TABLE_NAME} WHERE code = :code LIMIT 1`, + { + type: queryInterface.sequelize.QueryTypes.SELECT, + replacements: { code }, + } + ); + + return rows && rows[0] ? rows[0] : null; +}; + +/** + * 升级迁移:将 wms_express.code 从 DYXD 迁移为 DY。 + * + * 冲突处理策略: + * 1. 仅存在 DYXD:直接改为 DY; + * 2. 同时存在 DY 与 DYXD:将 DYXD 的空值补齐到 DY,再删除 DYXD; + * 3. 不存在 DYXD:视为已完成,保持幂等。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + void Sequelize; + + if (!(await hasTargetTable(queryInterface))) { + return; + } + + const oldRow = await findExpressByCode(queryInterface, OLD_CODE); + if (!oldRow) { + return; + } + + const newRow = await findExpressByCode(queryInterface, NEW_CODE); + + if (!newRow) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET code = :newCode WHERE code = :oldCode`, + { + replacements: { + newCode: NEW_CODE, + oldCode: OLD_CODE, + }, + } + ); + return; + } + + await queryInterface.sequelize.transaction(async transaction => { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} + SET + name = COALESCE(NULLIF(name, ''), :oldName), + KS = COALESCE(NULLIF(KS, ''), :oldKS), + PDD = COALESCE(NULLIF(PDD, ''), :oldPDD), + DYXD = COALESCE(NULLIF(DYXD, ''), :oldDYXD), + CAINIAO = COALESCE(NULLIF(CAINIAO, ''), :oldCAINIAO), + polyapi_extra_info = COALESCE(polyapi_extra_info, :oldPolyapiExtraInfo) + WHERE code = :newCode`, + { + replacements: { + newCode: NEW_CODE, + oldName: oldRow.name, + oldKS: oldRow.KS, + oldPDD: oldRow.PDD, + oldDYXD: oldRow.DYXD, + oldCAINIAO: oldRow.CAINIAO, + oldPolyapiExtraInfo: oldRow.polyapi_extra_info, + }, + transaction, + } + ); + + await queryInterface.sequelize.query( + `DELETE FROM ${TABLE_NAME} WHERE code = :oldCode`, + { + replacements: { oldCode: OLD_CODE }, + transaction, + } + ); + }); +}; + +/** + * 回滚迁移:将 wms_express.code 从 DY 恢复为 DYXD。 + * + * 仅在 DYXD 不存在时执行恢复;若已存在 DYXD 则跳过,避免主键冲突。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async (queryInterface, Sequelize) => { + void Sequelize; + + if (!(await hasTargetTable(queryInterface))) { + return; + } + + const oldRow = await findExpressByCode(queryInterface, OLD_CODE); + if (oldRow) { + return; + } + + const newRow = await findExpressByCode(queryInterface, NEW_CODE); + if (!newRow) { + return; + } + + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET code = :oldCode WHERE code = :newCode`, + { + replacements: { + oldCode: OLD_CODE, + newCode: NEW_CODE, + }, + } + ); +}; diff --git a/database/migrations/20260527233000-rename-wms-express-column-dyxd-to-dy.js b/database/migrations/20260527233000-rename-wms-express-column-dyxd-to-dy.js new file mode 100644 index 0000000..f9f35a1 --- /dev/null +++ b/database/migrations/20260527233000-rename-wms-express-column-dyxd-to-dy.js @@ -0,0 +1,126 @@ +'use strict'; + +const TABLE_NAME = 'wms_express'; +const OLD_COLUMN = 'DYXD'; +const NEW_COLUMN = 'DY'; + +/** + * 规范化 showAllTables 返回的表名。 + * @param {string|Object} table 表名或表对象。 + * @return {string} 规范化后的表名。 + */ +const normalizeTableName = table => { + if (typeof table === 'string') { + return table; + } + + return table && typeof table === 'object' + ? (table.tableName || table.name || '') + : ''; +}; + +/** + * 检查目标表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 表是否存在。 + */ +const hasTargetTable = async queryInterface => { + const allTables = await queryInterface.showAllTables(); + const tableSet = new Set((allTables || []).map(normalizeTableName)); + return tableSet.has(TABLE_NAME); +}; + +/** + * 合并列值:当目标列为空时,用源列值补齐。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Object} transaction Sequelize 事务对象。 + * @param {string} targetColumn 目标列名。 + * @param {string} sourceColumn 源列名。 + * @return {Promise} 无返回值。 + */ +const mergeColumnValues = async (queryInterface, transaction, targetColumn, sourceColumn) => { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} + SET ${targetColumn} = COALESCE(NULLIF(${targetColumn}, ''), ${sourceColumn}) + WHERE ${sourceColumn} IS NOT NULL AND ${sourceColumn} <> ''`, + { + transaction, + } + ); +}; + +/** + * 执行升级迁移:将 wms_express.DYXD 重命名为 DY(幂等)。 + * + * 处理策略: + * 1. 仅存在 DYXD:使用 renameColumn 改名为 DY。 + * 2. 同时存在 DY 与 DYXD:将 DYXD 的非空值补齐到 DY,再删除 DYXD。 + * 3. 不存在 DYXD:视为已完成,直接跳过。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + void Sequelize; + + if (!(await hasTargetTable(queryInterface))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + const hasOldColumn = Object.prototype.hasOwnProperty.call(columns, OLD_COLUMN); + const hasNewColumn = Object.prototype.hasOwnProperty.call(columns, NEW_COLUMN); + + if (!hasOldColumn) { + return; + } + + if (!hasNewColumn) { + await queryInterface.renameColumn(TABLE_NAME, OLD_COLUMN, NEW_COLUMN); + return; + } + + await queryInterface.sequelize.transaction(async transaction => { + await mergeColumnValues(queryInterface, transaction, NEW_COLUMN, OLD_COLUMN); + await queryInterface.removeColumn(TABLE_NAME, OLD_COLUMN, { transaction }); + }); +}; + +/** + * 执行回滚迁移:将 wms_express.DY 回滚为 DYXD(幂等)。 + * + * 处理策略: + * 1. 仅存在 DY:使用 renameColumn 改名回 DYXD。 + * 2. 同时存在 DY 与 DYXD:将 DY 的非空值补齐到 DYXD,再删除 DY。 + * 3. 不存在 DY:视为已回滚,直接跳过。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async (queryInterface, Sequelize) => { + void Sequelize; + + if (!(await hasTargetTable(queryInterface))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + const hasOldColumn = Object.prototype.hasOwnProperty.call(columns, OLD_COLUMN); + const hasNewColumn = Object.prototype.hasOwnProperty.call(columns, NEW_COLUMN); + + if (!hasNewColumn) { + return; + } + + if (!hasOldColumn) { + await queryInterface.renameColumn(TABLE_NAME, NEW_COLUMN, OLD_COLUMN); + return; + } + + await queryInterface.sequelize.transaction(async transaction => { + await mergeColumnValues(queryInterface, transaction, OLD_COLUMN, NEW_COLUMN); + await queryInterface.removeColumn(TABLE_NAME, NEW_COLUMN, { transaction }); + }); +}; diff --git a/database/migrations/20260528090000-create-wms-package-material-and-supplier.js b/database/migrations/20260528090000-create-wms-package-material-and-supplier.js new file mode 100644 index 0000000..dac0f3a --- /dev/null +++ b/database/migrations/20260528090000-create-wms-package-material-and-supplier.js @@ -0,0 +1,283 @@ +'use strict'; + +const PACKAGE_MATERIAL_TABLE = 'wms_package_material'; +const PACKAGE_SUPPLIER_TABLE = 'wms_package_supplier'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +/** + * 创建包材表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPackageMaterialTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(PACKAGE_MATERIAL_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + material_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '包材编码', + }, + material_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '包材名称', + }, + material_type: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '包材类型', + }, + spec: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '规格描述', + }, + length: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + comment: '长度(cm)', + }, + width: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + comment: '宽度(cm)', + }, + height: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + comment: '高度(cm)', + }, + weight: { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '重量(kg)', + }, + cost_price: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + comment: '成本单价', + }, + status: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:0=禁用,1=启用', + }, + version: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '包材信息表', + }); +}; + +/** + * 创建包材供应商表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPackageSupplierTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(PACKAGE_SUPPLIER_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + supplier_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '供应商编码', + }, + supplier_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '供应商名称', + }, + contact_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '联系人', + }, + contact_phone: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '联系电话', + }, + status: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:0=禁用,1=启用', + }, + version: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '包材供应商表', + }); +}; + +/** + * 确保包材表索引存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +const ensurePackageMaterialIndexes = async queryInterface => { + const indexNameSet = await getIndexNameSet(queryInterface, PACKAGE_MATERIAL_TABLE); + + if (!indexNameSet.has('idx_wms_package_material_warehouse_id')) { + await queryInterface.addIndex(PACKAGE_MATERIAL_TABLE, [ 'warehouse_id' ], { + name: 'idx_wms_package_material_warehouse_id', + }); + } + + if (!indexNameSet.has('uk_wms_package_material_warehouse_material_code')) { + await queryInterface.addIndex(PACKAGE_MATERIAL_TABLE, [ 'warehouse_id', 'material_code' ], { + name: 'uk_wms_package_material_warehouse_material_code', + unique: true, + }); + } +}; + +/** + * 确保包材供应商表索引存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +const ensurePackageSupplierIndexes = async queryInterface => { + const indexNameSet = await getIndexNameSet(queryInterface, PACKAGE_SUPPLIER_TABLE); + + if (!indexNameSet.has('idx_wms_package_supplier_warehouse_id')) { + await queryInterface.addIndex(PACKAGE_SUPPLIER_TABLE, [ 'warehouse_id' ], { + name: 'idx_wms_package_supplier_warehouse_id', + }); + } + + if (!indexNameSet.has('uk_wms_package_supplier_warehouse_supplier_code')) { + await queryInterface.addIndex(PACKAGE_SUPPLIER_TABLE, [ 'warehouse_id', 'supplier_code' ], { + name: 'uk_wms_package_supplier_warehouse_supplier_code', + unique: true, + }); + } +}; + +module.exports = { + /** + * 创建包材与包材供应商表及索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTables = await getExistingTableSet(queryInterface); + + if (!existingTables.has(PACKAGE_MATERIAL_TABLE)) { + await createPackageMaterialTable(queryInterface, Sequelize); + } + + if (!existingTables.has(PACKAGE_SUPPLIER_TABLE)) { + await createPackageSupplierTable(queryInterface, Sequelize); + } + + await ensurePackageMaterialIndexes(queryInterface); + await ensurePackageSupplierIndexes(queryInterface); + }, + + /** + * 回滚删除包材与包材供应商表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + void Sequelize; + + const existingTables = await getExistingTableSet(queryInterface); + + if (existingTables.has(PACKAGE_SUPPLIER_TABLE)) { + await queryInterface.dropTable(PACKAGE_SUPPLIER_TABLE); + } + + if (existingTables.has(PACKAGE_MATERIAL_TABLE)) { + await queryInterface.dropTable(PACKAGE_MATERIAL_TABLE); + } + }, +}; diff --git a/database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js b/database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js new file mode 100644 index 0000000..9e31495 --- /dev/null +++ b/database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js @@ -0,0 +1,74 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; +const MATERIAL_ID_COLUMN = 'package_material_id'; +const MATERIAL_NAME_SNAPSHOT_COLUMN = 'package_material_name_snapshot'; +const MATERIAL_ID_INDEX = 'idx_wms_order_express_package_material_id'; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +module.exports = { + /** + * 执行迁移:为订单快递表新增包材字段并补齐索引(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (!columns[MATERIAL_ID_COLUMN]) { + await queryInterface.addColumn(TABLE_NAME, MATERIAL_ID_COLUMN, { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID', + }); + } + + if (!columns[MATERIAL_NAME_SNAPSHOT_COLUMN]) { + await queryInterface.addColumn(TABLE_NAME, MATERIAL_NAME_SNAPSHOT_COLUMN, { + type: Sequelize.STRING(128), + allowNull: true, + comment: '包材名称快照', + }); + } + + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + if (!indexNameSet.has(MATERIAL_ID_INDEX)) { + await queryInterface.addIndex(TABLE_NAME, [ MATERIAL_ID_COLUMN ], { + name: MATERIAL_ID_INDEX, + }); + } + }, + + /** + * 回滚迁移:删除订单快递表包材字段及索引(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const columns = await queryInterface.describeTable(TABLE_NAME); + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + + if (indexNameSet.has(MATERIAL_ID_INDEX)) { + await queryInterface.removeIndex(TABLE_NAME, MATERIAL_ID_INDEX); + } + + if (columns[MATERIAL_NAME_SNAPSHOT_COLUMN]) { + await queryInterface.removeColumn(TABLE_NAME, MATERIAL_NAME_SNAPSHOT_COLUMN); + } + + if (columns[MATERIAL_ID_COLUMN]) { + await queryInterface.removeColumn(TABLE_NAME, MATERIAL_ID_COLUMN); + } + }, +}; diff --git a/database/migrations/20260528100000-drop-platid-from-wms-platform.js b/database/migrations/20260528100000-drop-platid-from-wms-platform.js new file mode 100644 index 0000000..bdb38f5 --- /dev/null +++ b/database/migrations/20260528100000-drop-platid-from-wms-platform.js @@ -0,0 +1,68 @@ +'use strict'; + +const TABLE_NAME = 'wms_platform'; +const COLUMN_NAME = 'platid'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建 wms_platform.platid 字段定义。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Object} 字段定义。 + */ +const buildPlatidColumn = Sequelize => ({ + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '平台ID', +}); + +module.exports = { + /** + * 正向迁移:幂等删除 wms_platform.platid。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, + + /** + * 回滚迁移:幂等恢复 wms_platform.platid。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildPlatidColumn(Sequelize)); + }, +}; diff --git a/database/migrations/20260528110000-add-weighing-weight-to-wms-order-express.js b/database/migrations/20260528110000-add-weighing-weight-to-wms-order-express.js new file mode 100644 index 0000000..65d9211 --- /dev/null +++ b/database/migrations/20260528110000-add-weighing-weight-to-wms-order-express.js @@ -0,0 +1,41 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; +const WEIGHING_WEIGHT_COLUMN = 'weighing_weight'; + +module.exports = { + /** + * 执行迁移:为订单快递表新增称重重量字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (columns[WEIGHING_WEIGHT_COLUMN]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, WEIGHING_WEIGHT_COLUMN, { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '称重重量(kg)', + }); + }, + + /** + * 回滚迁移:删除订单快递表称重重量字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (!columns[WEIGHING_WEIGHT_COLUMN]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, WEIGHING_WEIGHT_COLUMN); + }, +}; diff --git a/database/migrations/20260529110000-add-sph-xhs-dw-jd-to-wms-express.js b/database/migrations/20260529110000-add-sph-xhs-dw-jd-to-wms-express.js new file mode 100644 index 0000000..08a8dfa --- /dev/null +++ b/database/migrations/20260529110000-add-sph-xhs-dw-jd-to-wms-express.js @@ -0,0 +1,78 @@ +'use strict'; + +/** + * 为快递基础信息表新增 SPH/XHS/DW/JD 编码字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 SPH/XHS/DW/JD 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.SPH) { + await queryInterface.addColumn(tableName, 'SPH', { + type: Sequelize.STRING(255), + allowNull: true, + comment: 'SPH编码', + }); + } + + if (!columns.XHS) { + await queryInterface.addColumn(tableName, 'XHS', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '小红书编码', + }); + } + + if (!columns.DW) { + await queryInterface.addColumn(tableName, 'DW', { + type: Sequelize.STRING(255), + allowNull: true, + comment: 'DW编码', + }); + } + + if (!columns.JD) { + await queryInterface.addColumn(tableName, 'JD', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '京东编码', + }); + } + }, + + /** + * 回滚迁移:删除 SPH/XHS/DW/JD 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.SPH) { + await queryInterface.removeColumn(tableName, 'SPH'); + } + + if (columns.XHS) { + await queryInterface.removeColumn(tableName, 'XHS'); + } + + if (columns.DW) { + await queryInterface.removeColumn(tableName, 'DW'); + } + + if (columns.JD) { + await queryInterface.removeColumn(tableName, 'JD'); + } + }, +}; diff --git a/database/migrations/20260530090000-add-template-id-to-wms-express-interface.js b/database/migrations/20260530090000-add-template-id-to-wms-express-interface.js new file mode 100644 index 0000000..11a7159 --- /dev/null +++ b/database/migrations/20260530090000-add-template-id-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增模板 ID 字段 template_id。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 template_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.template_id) { + return; + } + + await queryInterface.addColumn(tableName, 'template_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '模板ID', + }); + }, + + /** + * 回滚迁移:删除 template_id 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.template_id) { + return; + } + + await queryInterface.removeColumn(tableName, 'template_id'); + }, +}; diff --git a/database/migrations/20260530100000-add-platform-shop-id-to-wms-express-interface.js b/database/migrations/20260530100000-add-platform-shop-id-to-wms-express-interface.js new file mode 100644 index 0000000..0fb4099 --- /dev/null +++ b/database/migrations/20260530100000-add-platform-shop-id-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增平台店铺 ID 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增平台店铺 ID 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.platform_shop_id) { + return; + } + + await queryInterface.addColumn(tableName, 'platform_shop_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '平台店铺ID', + }); + }, + + /** + * 回滚迁移:删除平台店铺 ID 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.platform_shop_id) { + return; + } + + await queryInterface.removeColumn(tableName, 'platform_shop_id'); + }, +}; diff --git a/database/migrations/20260530110000-add-brandno-to-wms-express-interface.js b/database/migrations/20260530110000-add-brandno-to-wms-express-interface.js new file mode 100644 index 0000000..00de169 --- /dev/null +++ b/database/migrations/20260530110000-add-brandno-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增品牌编码字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 brandno 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.brandno) { + return; + } + + await queryInterface.addColumn(tableName, 'brandno', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '品牌编码', + }); + }, + + /** + * 回滚迁移:删除 brandno 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.brandno) { + return; + } + + await queryInterface.removeColumn(tableName, 'brandno'); + }, +}; diff --git a/database/migrations/20260531120000-add-providertype-to-wms-express-interface.js b/database/migrations/20260531120000-add-providertype-to-wms-express-interface.js new file mode 100644 index 0000000..c32e13c --- /dev/null +++ b/database/migrations/20260531120000-add-providertype-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增服务商类型字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 providertype 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.providertype) { + return; + } + + await queryInterface.addColumn(tableName, 'providertype', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '服务商类型编码', + }); + }, + + /** + * 回滚迁移:删除 providertype 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.providertype) { + return; + } + + await queryInterface.removeColumn(tableName, 'providertype'); + }, +}; diff --git a/database/migrations/20260531123000-add-paymode-to-wms-express-interface.js b/database/migrations/20260531123000-add-paymode-to-wms-express-interface.js new file mode 100644 index 0000000..f75dffe --- /dev/null +++ b/database/migrations/20260531123000-add-paymode-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增付款方式字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 paymode 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.paymode) { + return; + } + + await queryInterface.addColumn(tableName, 'paymode', { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '付款方式', + }); + }, + + /** + * 回滚迁移:删除 paymode 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.paymode) { + return; + } + + await queryInterface.removeColumn(tableName, 'paymode'); + }, +}; diff --git a/database/migrations/20260601100000-add-providerid-to-wms-express-interface.js b/database/migrations/20260601100000-add-providerid-to-wms-express-interface.js new file mode 100644 index 0000000..c39bf9c --- /dev/null +++ b/database/migrations/20260601100000-add-providerid-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增服务商ID字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 providerid 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.providerid) { + return; + } + + await queryInterface.addColumn(tableName, 'providerid', { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '服务商ID', + }); + }, + + /** + * 回滚迁移:删除 providerid 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.providerid) { + return; + } + + await queryInterface.removeColumn(tableName, 'providerid'); + }, +}; diff --git a/database/migrations/20260602103000-create-wms-order-item-sn-and-log.js b/database/migrations/20260602103000-create-wms-order-item-sn-and-log.js new file mode 100644 index 0000000..3a77b37 --- /dev/null +++ b/database/migrations/20260602103000-create-wms-order-item-sn-and-log.js @@ -0,0 +1,326 @@ +'use strict'; + +const ORDER_ITEM_SN_TABLE = 'wms_order_item_sn'; +const ORDER_ITEM_SN_LOG_TABLE = 'wms_order_item_sn_log'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +/** + * 创建订单明细 SN 当前关系表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createOrderItemSnTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(ORDER_ITEM_SN_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + order_item_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID', + }, + sn_code: { + type: Sequelize.STRING(128), + allowNull: false, + comment: 'SN编码', + }, + sn_status: { + type: Sequelize.STRING(32), + allowNull: false, + defaultValue: 'BOUND', + comment: 'SN状态:BOUND/VERIFIED/RETURNED/REISSUED/INVALID', + }, + verify_status: { + type: Sequelize.STRING(32), + allowNull: false, + defaultValue: 'UNVERIFIED', + comment: '核验状态:UNVERIFIED/PASS/FAIL', + }, + bound_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '绑定时间', + }, + verified_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '核验时间', + }, + returned_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '退回时间', + }, + reissued_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '重发时间', + }, + version: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '订单明细SN当前关系与状态表', + }); +}; + +/** + * 创建订单明细 SN 状态变更流水表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createOrderItemSnLogTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(ORDER_ITEM_SN_LOG_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + sn_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联SN主表ID', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + order_item_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID', + }, + sn_code: { + type: Sequelize.STRING(128), + allowNull: false, + comment: 'SN编码', + }, + from_sn_status: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '变更前SN状态', + }, + to_sn_status: { + type: Sequelize.STRING(32), + allowNull: false, + comment: '变更后SN状态', + }, + verify_status: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '本次状态变更后的核验状态', + }, + action_type: { + type: Sequelize.STRING(32), + allowNull: false, + comment: '动作类型:BIND/VERIFY/RETURN/REISSUE/UNBIND', + }, + remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '备注', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人ID', + }, + operated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '操作时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '订单明细SN状态变更流水表', + }); +}; + +/** + * 确保订单明细 SN 当前关系表索引存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +const ensureOrderItemSnIndexes = async queryInterface => { + const indexNameSet = await getIndexNameSet(queryInterface, ORDER_ITEM_SN_TABLE); + + if (!indexNameSet.has('uk_wms_order_item_sn_warehouse_sn_code')) { + await queryInterface.addIndex(ORDER_ITEM_SN_TABLE, [ 'warehouse_id', 'sn_code' ], { + name: 'uk_wms_order_item_sn_warehouse_sn_code', + unique: true, + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_warehouse_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_TABLE, [ 'warehouse_id' ], { + name: 'idx_wms_order_item_sn_warehouse_id', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_order_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_TABLE, [ 'order_id' ], { + name: 'idx_wms_order_item_sn_order_id', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_order_item_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_TABLE, [ 'order_item_id' ], { + name: 'idx_wms_order_item_sn_order_item_id', + }); + } +}; + +/** + * 确保订单明细 SN 流水表索引存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +const ensureOrderItemSnLogIndexes = async queryInterface => { + const indexNameSet = await getIndexNameSet(queryInterface, ORDER_ITEM_SN_LOG_TABLE); + + if (!indexNameSet.has('idx_wms_order_item_sn_log_sn_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_LOG_TABLE, [ 'sn_id' ], { + name: 'idx_wms_order_item_sn_log_sn_id', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_log_sn_code')) { + await queryInterface.addIndex(ORDER_ITEM_SN_LOG_TABLE, [ 'sn_code' ], { + name: 'idx_wms_order_item_sn_log_sn_code', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_log_order_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_LOG_TABLE, [ 'order_id' ], { + name: 'idx_wms_order_item_sn_log_order_id', + }); + } + + if (!indexNameSet.has('idx_wms_order_item_sn_log_order_item_id')) { + await queryInterface.addIndex(ORDER_ITEM_SN_LOG_TABLE, [ 'order_item_id' ], { + name: 'idx_wms_order_item_sn_log_order_item_id', + }); + } +}; + +module.exports = { + /** + * 创建订单明细 SN 主表与流水表及索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTables = await getExistingTableSet(queryInterface); + + if (!existingTables.has(ORDER_ITEM_SN_TABLE)) { + await createOrderItemSnTable(queryInterface, Sequelize); + } + + if (!existingTables.has(ORDER_ITEM_SN_LOG_TABLE)) { + await createOrderItemSnLogTable(queryInterface, Sequelize); + } + + await ensureOrderItemSnIndexes(queryInterface); + await ensureOrderItemSnLogIndexes(queryInterface); + }, + + /** + * 回滚删除订单明细 SN 主表与流水表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + void Sequelize; + + const existingTables = await getExistingTableSet(queryInterface); + + if (existingTables.has(ORDER_ITEM_SN_LOG_TABLE)) { + await queryInterface.dropTable(ORDER_ITEM_SN_LOG_TABLE); + } + + if (existingTables.has(ORDER_ITEM_SN_TABLE)) { + await queryInterface.dropTable(ORDER_ITEM_SN_TABLE); + } + }, +}; diff --git a/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js b/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js new file mode 100644 index 0000000..c78b0ae --- /dev/null +++ b/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js @@ -0,0 +1,102 @@ +'use strict'; + +const TABLE_NAME = 'wms_express_setting'; +const UNIQUE_INDEX_NAME = 'platform_code'; +const NEW_INDEX_NAME = 'idx_express_warehouse'; +const FK_NAME = 'wms_express_setting_ibfk_1'; + +/** + * 检查指定表中是否存在指定名称的索引(通过 SHOW INDEX 做幂等判断)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 索引是否存在。 + */ +const hasIndex = async (queryInterface, tableName, indexName) => { + const [ rows ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`, + { replacements: { indexName } } + ); + return rows && rows.length > 0; +}; + +/** + * 检查指定外键约束是否存在(通过 information_schema 做幂等判断)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} constraintName 约束名。 + * @return {Promise} 外键是否存在。 + */ +const hasForeignKey = async (queryInterface, tableName, constraintName) => { + const [ rows ] = await queryInterface.sequelize.query( + `SELECT CONSTRAINT_NAME + FROM information_schema.TABLE_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND CONSTRAINT_NAME = :constraintName + AND CONSTRAINT_TYPE = 'FOREIGN KEY'`, + { replacements: { tableName, constraintName } } + ); + return rows && rows.length > 0; +}; + +module.exports = { + /** + * 正向迁移:先删除外键依赖,再删除唯一索引,最后添加普通索引替代。 + * 原因:同一系统快递编码(express_code)允许对应多个自定义编码(code), + * 原 UNIQUE KEY `platform_code` ON (`express_code`, `warehouse_id`) 约束过紧, + * 且该索引被外键 `wms_express_setting_ibfk_1`(express_code → wms_express.code)依赖。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + // 1. 先删除依赖该索引的外键约束 + if (await hasForeignKey(queryInterface, TABLE_NAME, FK_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP FOREIGN KEY \`${FK_NAME}\`;` + ); + } + + // 2. 删除原来的唯一索引 + if (await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${UNIQUE_INDEX_NAME}\`;` + ); + } + + // 3. 添加普通索引替代(用于查询性能) + if (!(await hasIndex(queryInterface, TABLE_NAME, NEW_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${NEW_INDEX_NAME}\` (express_code, warehouse_id);` + ); + } + }, + + /** + * 回滚迁移:恢复唯一索引与外键约束。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + // 1. 删除替代的普通索引 + if (await hasIndex(queryInterface, TABLE_NAME, NEW_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${NEW_INDEX_NAME}\`;` + ); + } + + // 2. 恢复唯一索引(幂等:已存在则跳过) + if (!(await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD UNIQUE INDEX \`${UNIQUE_INDEX_NAME}\` (express_code, warehouse_id);` + ); + } + + // 3. 恢复外键约束(幂等:已存在则跳过) + if (!(await hasForeignKey(queryInterface, TABLE_NAME, FK_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD CONSTRAINT \`${FK_NAME}\` FOREIGN KEY (express_code) REFERENCES wms_express (code);` + ); + } + }, +}; diff --git a/database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js b/database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js new file mode 100644 index 0000000..decfcc8 --- /dev/null +++ b/database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js @@ -0,0 +1,62 @@ +'use strict'; + +/** + * 将快递接口配置表的 template_id 列从 BIGINT 改为 VARCHAR(50), + * 以支持快手等平台返回的字符串模板 ID(如 "EBSTO11")。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:将 template_id 列类型从 BIGINT 改为 VARCHAR(50)(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.template_id) { + return; + } + + // 如果已经是 VARCHAR 类型则跳过(幂等) + if (columns.template_id.type && String(columns.template_id.type).toUpperCase().includes('VARCHAR')) { + return; + } + + await queryInterface.changeColumn(tableName, 'template_id', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '模板ID', + }); + }, + + /** + * 回滚迁移:将 template_id 列类型从 VARCHAR(50) 改回 BIGINT(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.template_id) { + return; + } + + // 如果已经是 BIGINT 类型则跳过(幂等) + if (columns.template_id.type && String(columns.template_id.type).toUpperCase().includes('BIGINT')) { + return; + } + + await queryInterface.changeColumn(tableName, 'template_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '模板ID', + }); + }, +}; diff --git a/database/migrations/20260606042732-add-auto-increment-to-wms-order-items-partitions.js b/database/migrations/20260606042732-add-auto-increment-to-wms-order-items-partitions.js new file mode 100644 index 0000000..50ffc60 --- /dev/null +++ b/database/migrations/20260606042732-add-auto-increment-to-wms-order-items-partitions.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * 修复 wms_order_items 分表的 id 列缺少 AUTO_INCREMENT 的问题。 + * + * 背景:sync({ alter: true }) 修了所有字段但没有检测到 id 缺少 AUTO_INCREMENT, + * 需要手动为以下分表补充: + * - wms_order_items_100000_dispatch + * - wms_order_items_100000_history + * - wms_order_items_1000028 + * + * @param {import('sequelize').QueryInterface} queryInterface + * @param {import('sequelize')} Sequelize + * @return {Promise} + */ +module.exports.up = async (queryInterface, Sequelize) => { + const tables = [ + 'wms_order_items_100000_dispatch', + 'wms_order_items_100000_history', + 'wms_order_items_1000028', + ]; + + for (const table of tables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT` + ); + } +}; + +/** + * 回滚:移除 AUTO_INCREMENT(恢复为普通 BIGINT UNSIGNED NOT NULL)。 + * + * @param {import('sequelize').QueryInterface} queryInterface + * @param {import('sequelize')} Sequelize + * @return {Promise} + */ +module.exports.down = async (queryInterface, Sequelize) => { + const tables = [ + 'wms_order_items_100000_dispatch', + 'wms_order_items_100000_history', + 'wms_order_items_1000028', + ]; + + for (const table of tables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY id BIGINT UNSIGNED NOT NULL` + ); + } +}; diff --git a/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js b/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js new file mode 100644 index 0000000..f05f548 --- /dev/null +++ b/database/migrations/20260607120000-drop-uk-warehouse-platform-shop-name.js @@ -0,0 +1,67 @@ +'use strict'; + +const TABLE_NAME = 'wms_shops'; +const UNIQUE_INDEX_NAME = 'uk_warehouse_platform_shop_name'; +const PLAIN_INDEX_NAME = 'idx_warehouse_platform_shop_name'; + +/** + * 检查指定表中是否存在指定名称的索引(通过 SHOW INDEX 做幂等判断)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 索引是否存在。 + */ +const hasIndex = async (queryInterface, tableName, indexName) => { + const [ rows ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`, + { replacements: { indexName } } + ); + return rows && rows.length > 0; +}; + +module.exports = { + /** + * 正向迁移:删除唯一约束,改为普通索引。 + * 原因:菜鸟 OAuth 授权回调时,预授权记录(status=0)与已授权记录(status=1)因同名店铺 + * 触发 UNIQUE KEY `uk_warehouse_platform_shop_name` 约束冲突,导致 MySQL UPDATE 失败。 + * 故将此唯一约束降为普通索引,仅保留查询性能。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + // 1. 删除唯一索引 + if (await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${UNIQUE_INDEX_NAME}\`;` + ); + } + + // 2. 添加普通索引(仅用于查询性能) + if (!(await hasIndex(queryInterface, TABLE_NAME, PLAIN_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${PLAIN_INDEX_NAME}\` (warehouse_id, platform_code, shop_name);` + ); + } + }, + + /** + * 回滚迁移:恢复唯一约束。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + // 1. 删除普通索引 + if (await hasIndex(queryInterface, TABLE_NAME, PLAIN_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${PLAIN_INDEX_NAME}\`;` + ); + } + + // 2. 恢复唯一索引(幂等:已存在则跳过) + if (!(await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD UNIQUE INDEX \`${UNIQUE_INDEX_NAME}\` (warehouse_id, platform_code, shop_name);` + ); + } + }, +}; diff --git a/database/migrations/20260608-add-api-permissions.js b/database/migrations/20260608-add-api-permissions.js new file mode 100644 index 0000000..a14c03c --- /dev/null +++ b/database/migrations/20260608-add-api-permissions.js @@ -0,0 +1,243 @@ +'use strict'; + +/** + * 补齐 wms_permission 表的 API 权限记录: + * 1. 新增约 50 条 type='api' 的权限记录(幂等:先查后插) + * 2. 修正 28 条现有记录的 meta_title(原值统一为"获取审核信息接口") + * + * 幂等设计: + * - 新增:先查询 path + type='api' 是否已存在,已存在则跳过 + * - 修正:UPDATE ... WHERE id = N AND meta_title = '获取审核信息接口' + */ + +const TABLE = 'wms_permission'; + +/** + * 批量查询指定 path 是否已存在 type='api' 的记录。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {string[]} paths 待查询的 path 列表 + * @return {Promise>} 已存在的 path 集合 + */ +const getExistingApiPaths = async (queryInterface, paths) => { + const placeholders = paths.map(() => '?').join(', '); + const [ rows ] = await queryInterface.sequelize.query( + `SELECT path FROM \`${TABLE}\` WHERE type = 'api' AND path IN (${placeholders})`, + { replacements: paths } + ); + return new Set(rows.map(r => r.path)); +}; + +/** + * 正向迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ +module.exports.up = async queryInterface => { + // ─── 1. 新增 50 条 API 权限 ───────────────────────────────── + const newPermissions = [ + // warehouse 模块 + { path: 'warehouse.getWarehouseZones', meta_title: '获取所有仓库' }, + { path: 'warehouse.create', meta_title: '创建实体库' }, + { path: 'warehouse.update', meta_title: '更新仓库元素' }, + { path: 'warehouse.delete', meta_title: '删除仓库元素' }, + { path: 'warehouse.toggleActive', meta_title: '切换仓库元素启用状态' }, + { path: 'warehouse.getPath', meta_title: '获取仓库路径' }, + { path: 'warehouse.getPickPath', meta_title: '获取拣货路径' }, + { path: 'warehouse.updateRackPosition', meta_title: '更新货架位置' }, + { path: 'warehouse.recalculatePickPath', meta_title: '重算拣货路径' }, + { path: 'warehouse.updateNeighbors', meta_title: '更新相邻仓位' }, + { path: 'warehouse.getAreaRacks', meta_title: '获取区域货架' }, + { path: 'warehouse.getWarehouseTree', meta_title: '获取仓库树' }, + { path: 'warehouse.getChildren', meta_title: '获取仓库子元素' }, + { path: 'warehouse.updateSpaceInfo', meta_title: '修改仓位信息' }, + { path: 'warehouse.batchUpdateSpaceInfo', meta_title: '批量修改仓位信息' }, + { path: 'warehouse.exportRackSpaces', meta_title: '导出货架仓位' }, + // shops 模块 + { path: 'shops.list', meta_title: '店铺列表' }, + { path: 'shops.add', meta_title: '新增店铺' }, + { path: 'shops.del', meta_title: '删除店铺' }, + { path: 'shops.edit', meta_title: '编辑店铺' }, + { path: 'shops.GetAuthorizeSessionKey', meta_title: '获取授权SessionKey' }, + // stock.warehouse 模块 + { path: 'stock.warehouse.saveWarehouseStock', meta_title: '保存商品资料' }, + { path: 'stock.warehouse.createWarehouseStock', meta_title: '创建仓库商品' }, + { path: 'stock.warehouse.import', meta_title: '商品导入' }, + { path: 'stock.warehouse.saveWarehouseStockBarcode', meta_title: '修改商品条码' }, + { path: 'stock.warehouse.bindItem', meta_title: '绑定货主商品' }, + { path: 'stock.warehouse.unbindItem', meta_title: '解绑货主商品' }, + { path: 'stock.warehouse.handleBatchDelete', meta_title: '批量删除仓库商品' }, + { path: 'stock.warehouse.handleBatchChange', meta_title: '批量修改商品' }, + // index 模块 + { path: 'index.ReferenceFile', meta_title: '图片引用设置' }, + { path: 'index.test', meta_title: '测试接口' }, + { path: 'index.getShopList', meta_title: '获取仓库店铺列表' }, + { path: 'index.getShopExpressList', meta_title: '获取店铺签约快递' }, + { path: 'index.createPlatformOauthReservation', meta_title: '创建平台授权预留码' }, + // order 模块 + { path: 'order.bindExpressPackageMaterial', meta_title: '绑定快递包材' }, + { path: 'order.pullReviewDataByWaybill', meta_title: '按运单拉取复核数据' }, + // order.wave 模块 + { path: 'order.wave.waveStrategyCreate', meta_title: '波次策略新增' }, + { path: 'order.wave.waveStrategyUpdate', meta_title: '波次策略修改' }, + { path: 'order.wave.wavePickTaskCancel', meta_title: '拣货任务取消' }, + { path: 'order.wave.previewWaveStrategyNextFetchOrderCount', meta_title: '预演策略抓取数量' }, + // order.* 明细模块 + { path: 'order.pendingOrder.detail', meta_title: '待处理订单明细' }, + { path: 'order.archiveOrder.detail', meta_title: '归档订单明细' }, + { path: 'order.deliveryOrder.detail', meta_title: '配送订单明细' }, + { path: 'order.deliveryExpectionOrder.detail', meta_title: '配送异常订单明细' }, + { path: 'order.entrustOrder.detail', meta_title: '委托外仓订单明细' }, + { path: 'order.reviewOrder.detail', meta_title: '待审核订单明细' }, + { path: 'order.outboundOrder.detail', meta_title: '待出库订单明细' }, + { path: 'order.expectionOrder.detail', meta_title: '异常订单明细' }, + // storage.inventory 模块 + { path: 'storage.inventory.quickPutaway', meta_title: '快递入库' }, + // store 模块 + { path: 'store.getStoreRoles', meta_title: '获取审核信息' }, + { path: 'store.auditApply', meta_title: '提交审核' }, + // storeWarehouse.store 模块 + { path: 'storeWarehouse.store.adjustPrintQuantity', meta_title: '货主余额变更' }, + { path: 'storeWarehouse.store.queryPrintQuantityLogs', meta_title: '货主面单余额查询' }, + ]; + + const allPaths = newPermissions.map(p => p.path); + const existingPaths = await getExistingApiPaths(queryInterface, allPaths); + + const toInsert = newPermissions.filter(p => !existingPaths.has(p.path)); + + if (toInsert.length > 0) { + // 构建批量 INSERT 语句,name 与 path 保持一致 + const values = toInsert + .map( + p => `('${p.path.replace(/'/g, "\\'")}', '${p.path.replace(/'/g, "\\'")}', '${p.meta_title.replace(/'/g, "\\'")}', 'api', 1, NOW(), NOW())` + ) + .join(',\n'); + + await queryInterface.sequelize.query(` + INSERT INTO \`${TABLE}\` (path, name, meta_title, type, status, created_at, update_at) + VALUES ${values} + `); + } + + console.log( + `[Migration] wms_permission API 权限新增:共 ${newPermissions.length} 条,` + + `已存在 ${newPermissions.length - toInsert.length} 条,实际插入 ${toInsert.length} 条` + ); + + // ─── 2. 修正 28 条现有记录的 meta_title ──────────────────── + const corrections = [ + { id: 52, meta_title: '获取审核信息' }, + { id: 84, meta_title: '获取COS上传配置' }, + { id: 85, meta_title: '获取快递列表' }, + { id: 86, meta_title: '自动翻译新键' }, + { id: 87, meta_title: '上传成功通知' }, + { id: 88, meta_title: '获取订单模型列表' }, + { id: 89, meta_title: '绑定货主商品到仓库' }, + { id: 90, meta_title: '创建禁售规则' }, + { id: 91, meta_title: '创建单位' }, + { id: 92, meta_title: '创建仓库商品' }, + { id: 93, meta_title: '删除禁售规则' }, + { id: 94, meta_title: '删除单位' }, + { id: 95, meta_title: '批量修改商品' }, + { id: 96, meta_title: '批量删除商品' }, + { id: 97, meta_title: '保存商品资料' }, + { id: 98, meta_title: '修改商品条码' }, + { id: 99, meta_title: '解除绑定货主商品' }, + { id: 100, meta_title: '添加收货明细' }, + { id: 101, meta_title: '删除收货明细' }, + { id: 102, meta_title: '保存收货单' }, + { id: 103, meta_title: '创建货架' }, + { id: 104, meta_title: '创建货架含仓位' }, + { id: 105, meta_title: '重算拣货路径' }, + { id: 106, meta_title: '更新相邻仓位' }, + { id: 107, meta_title: '更新货架位置' }, + { id: 108, meta_title: '获取商品信息' }, + { id: 306, meta_title: '获取订单模型列表' }, + { id: 307, meta_title: '获取区域货架' }, + ]; + + let correctedCount = 0; + for (const { id, meta_title } of corrections) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET meta_title = :meta_title, update_at = NOW() + WHERE id = :id AND meta_title = '获取审核信息接口'`, + { replacements: { id, meta_title } } + ); + // result 为 affectedRows(MySQL)或 rowCount + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + correctedCount++; + } + } + + console.log( + `[Migration] wms_permission meta_title 修正:共 ${corrections.length} 条,` + + `实际修正 ${correctedCount} 条` + ); + + // ─── 3. 修正 10 条 meta_title 为 "path+接口" 格式的记录 ────── + const pathLikeCorrections = [ + { id: 347, path: 'warehouse.getChildren', meta_title: '获取仓库子元素' }, + { id: 348, path: 'warehouse.toggleActive', meta_title: '切换仓库启用状态' }, + { id: 349, path: 'warehouse.getPath', meta_title: '获取仓库路径' }, + { id: 350, path: 'warehouse.getPickPath', meta_title: '获取拣货路径' }, + { id: 351, path: 'storage.receiving.save', meta_title: '保存收货单' }, + { id: 367, path: 'shops.list', meta_title: '店铺列表' }, + { id: 368, path: 'shops.add', meta_title: '新增店铺' }, + { id: 369, path: 'shops.del', meta_title: '删除店铺' }, + { id: 370, path: 'shops.edit', meta_title: '编辑店铺' }, + { id: 371, path: 'shop.GetAuthorizeSessionKey', meta_title: '获取授权SessionKey' }, + ]; + + let pathLikeCorrectedCount = 0; + for (const { id, meta_title } of pathLikeCorrections) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET meta_title = :meta_title, update_at = NOW() + WHERE id = :id AND meta_title LIKE '%接口'`, + { replacements: { id, meta_title } } + ); + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + pathLikeCorrectedCount++; + } + } + + console.log( + `[Migration] wms_permission "path+接口" 格式修正:共 ${pathLikeCorrections.length} 条,` + + `实际修正 ${pathLikeCorrectedCount} 条` + ); + + // ── 3b. 修正 setting.permission.add/delete/update 的 meta_title ── + const permissionCrudCorrections = [ + { id: 119, path: 'setting.permission.add', meta_title: '新增权限' }, + { id: 120, path: 'setting.permission.delete', meta_title: '删除权限' }, + { id: 121, path: 'setting.permission.update', meta_title: '修改权限' }, + ]; + + let permCrudCorrectedCount = 0; + for (const { id, path, meta_title } of permissionCrudCorrections) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET meta_title = :meta_title, update_at = NOW() + WHERE id = :id AND meta_title = :oldMetaTitle`, + { replacements: { id, meta_title, oldMetaTitle: path } } + ); + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + permCrudCorrectedCount++; + } + } + + console.log( + `[Migration] wms_permission setting.permission CRUD 修正:共 ${permissionCrudCorrections.length} 条,` + + `实际修正 ${permCrudCorrectedCount} 条` + ); +}; + +/** + * 回滚迁移:无法安全回滚 meta_title 修正与新增记录(可能已被后续业务引用), + * 仅输出提示信息。 + * @return {Promise} 无返回值 + */ +module.exports.down = async () => { + console.log( + '[Migration] wms_permission API 权限补齐脚本无安全回滚方案,' + + '如需回滚请手动处理 meta_title 与新增记录。' + ); +}; diff --git a/database/migrations/20260608033847-set-role-preset-permissions.js b/database/migrations/20260608033847-set-role-preset-permissions.js new file mode 100644 index 0000000..9266da7 --- /dev/null +++ b/database/migrations/20260608033847-set-role-preset-permissions.js @@ -0,0 +1,169 @@ +'use strict'; + +/** + * 系统角色(is_system=1)预设权限迁移 + * + * 背景: + * wms_permission 表已扩容到 349 条(6 种类型),当前系统角色的 permissions + * 字段(JSON 数组)覆盖范围不足,新增的 API/pda_pages/workerstation_pages 等 + * 权限未被纳入旧的角色预设中。 + * + * 范围: + * - 仅更新 is_system=1 的角色(12 个,排除 id=2 仓库管理员和 id=7 超级管理员, + * 二者保持 "*" 不变) + * - 仅使用 status=1 的活跃权限 + * - 不修改 wms_permission 表 + * + * 幂等设计: + * UPDATE wms_role SET permissions = ? WHERE id = ? AND is_system = 1 + */ + +const TABLE = 'wms_role'; + +/** @type {{id: number, role_code: string, permissions: string, desc: string}[]} */ +const ROLE_UPDATES = [ + { + id: 5, + role_code: 'store_admin_default', + name: '货主管理员', + // 货主管理员:web_pages(设置4,货主17,成员审核50,货主列表244,店铺模块366), block(商家基础数据48), api(货主/店铺相关 52,53,308,363,364,365,367-372,376,379,380) + permissions: '[4,17,48,50,52,53,244,308,363,364,365,366,367,368,369,370,371,372,376,379,380]', + old: '[4,48,50,52,53]', + }, + { + id: 8, + role_code: '2', + name: '经理', + // 经理:全部 status=1 权限(206条),排除权限管理(5,7,119,120,121)、测试(187,245,378) + permissions: '[1,4,6,8,9,11,12,13,14,15,16,17,18,19,20,21,22,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121,244]', + }, + { + id: 26, + role_code: 'warehouse', + name: '仓库组-主管', + // 仓库组-主管:全部活跃权限排除权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据模块(16)、测试(187,245,378) + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 27, + role_code: 'warehouse_role', + name: '仓库组-员工', + // 仓库组-员工:同仓库组-主管,排除权限管理、财务、数据模块、测试 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 28, + role_code: '05', + name: '客服组-主管', + // 客服组-主管:排除权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据(16)、测试(187,245,378)、PDA拣货/复核/打包/补货、工位称重/退件 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[1,4-121,244-336]', + }, + { + id: 30, + role_code: '04', + name: '客服组-员工', + // 客服组-员工:同客服组-主管 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[1,4-121,244-336]', + }, + { + id: 29, + role_code: '03', + name: '生产组-主管', + // 生产组-主管:全部活跃权限排除权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据(16)、测试(187,245,378) + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 31, + role_code: '002', + name: '生产组-员工', + // 生产组-员工:同生产组-主管 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 32, + role_code: '021', + name: '生产组-拣货', + // 生产组-拣货:排除复核发货(266-269)、打包(270-276)、权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据(16)、测试(187,245,378)、工位站(356,359,360) + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,357,358,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 33, + role_code: '0113', + name: '拣货组组员', + // 拣货组组员:同生产组-拣货 + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,257,258,259,260,261,262,263,264,265,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,357,358,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 34, + role_code: '024', + name: '生产组-复核', + // 生产组-复核:排除拣货(257-265)、打包(270-276)、权限管理(5,6,7,119,120,121)、财务(28,31-37)、数据(16)、测试(187,245,378) + permissions: '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,266,267,268,269,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, + { + id: 36, + role_code: '0211', + name: '其他普工', + // 其他普工:排除设置模块(4-9,40,41,80,81,336,366,375)、财务、数据、测试、系统、敏感API、仓库管理API、视频 + permissions: '[1,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,43,44,45,46,48,49,50,54,55,57,58,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,79,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,108,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,309,333,334,335,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,357,358,361,364,365,370,373,374,376,377,379,380,381,382,383,384]', + old: '[4-121]', + }, +]; + +/** + * 正向迁移:更新 12 个系统角色的 permissions 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ +module.exports.up = async queryInterface => { + let updatedCount = 0; + + for (const role of ROLE_UPDATES) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() + WHERE id = :id AND is_system = 1`, + { replacements: { id: role.id, permissions: role.permissions } } + ); + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + updatedCount++; + } + } + + console.log( + `[Migration] wms_role 预设权限更新:共 ${ROLE_UPDATES.length} 个角色,实际更新 ${updatedCount} 个` + ); +}; + +/** + * 回滚迁移:恢复到旧的 permissions 值。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ +module.exports.down = async queryInterface => { + let revertedCount = 0; + + for (const role of ROLE_UPDATES) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() + WHERE id = :id AND is_system = 1`, + { replacements: { id: role.id, permissions: role.old } } + ); + if (result && (result.affectedRows > 0 || result.rowCount > 0 || result.changedRows > 0)) { + revertedCount++; + } + } + + console.log( + `[Migration] wms_role 预设权限回滚:共 ${ROLE_UPDATES.length} 个角色,实际回滚 ${revertedCount} 个` + ); +}; diff --git a/database/migrations/20260611100000-add-warehouse-id-to-wms-picking.js b/database/migrations/20260611100000-add-warehouse-id-to-wms-picking.js new file mode 100644 index 0000000..1de4197 --- /dev/null +++ b/database/migrations/20260611100000-add-warehouse-id-to-wms-picking.js @@ -0,0 +1,22 @@ +'use strict'; + +/** + * 为 wms_picking 表新增 warehouse_id 字段及索引。 + */ +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE wms_picking + ADD COLUMN warehouse_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT '仓库ID' AFTER order_item_id, + ADD INDEX idx_wms_picking_warehouse_id (warehouse_id) + `); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE wms_picking + DROP INDEX idx_wms_picking_warehouse_id, + DROP COLUMN warehouse_id + `); + }, +}; diff --git a/database/migrations/20260611180000-add-shrk-to-entry-order-type.js b/database/migrations/20260611180000-add-shrk-to-entry-order-type.js new file mode 100644 index 0000000..80f7c47 --- /dev/null +++ b/database/migrations/20260611180000-add-shrk-to-entry-order-type.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_type ENUM('SCRK','LYRK','CCRK','CGRK','DBRK','QTRK','B2BRK','XNRK','SHRK') NOT NULL COMMENT '业务类型'" + ); + }, + down: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_type ENUM('SCRK','LYRK','CCRK','CGRK','DBRK','QTRK','B2BRK','XNRK') NOT NULL COMMENT '业务类型'" + ); + }, +}; diff --git a/database/migrations/20260611190000-merge-created-to-pending.js b/database/migrations/20260611190000-merge-created-to-pending.js new file mode 100644 index 0000000..418992d --- /dev/null +++ b/database/migrations/20260611190000-merge-created-to-pending.js @@ -0,0 +1,30 @@ +'use strict'; + +module.exports = { + /** + * 将 CREATED 状态合并到 PENDING: + * 1. 先把现有 CREATED 行更新为 PENDING + * 2. 再 ALTER TABLE 去掉 CREATED 枚举值 + * @param queryInterface + */ + up: async queryInterface => { + // 先更新现有 CREATED 行 + await queryInterface.sequelize.query( + "UPDATE wms_entry_order SET order_status = 'PENDING', updated_at = NOW() WHERE order_status = 'CREATED'" + ); + // 再修改 ENUM 列定义,移除 CREATED + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED','CREATING') NOT NULL DEFAULT 'PENDING' COMMENT '订单状态'" + ); + }, + + /** + * 回滚:将 CREATED 加回 ENUM(数据不回退,因为无法区分哪些行原本是 CREATED) + * @param queryInterface + */ + down: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED','CREATED','CREATING') NOT NULL DEFAULT 'PENDING' COMMENT '订单状态'" + ); + }, +}; diff --git a/database/migrations/20260615143000-create-wms-package-material-item-relation.js b/database/migrations/20260615143000-create-wms-package-material-item-relation.js new file mode 100644 index 0000000..3ea2cbd --- /dev/null +++ b/database/migrations/20260615143000-create-wms-package-material-item-relation.js @@ -0,0 +1,150 @@ +'use strict'; + +const TABLE_NAME = 'wms_package_material_item_relation'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + items_hash: { + type: Sequelize.CHAR(32), + allowNull: false, + comment: '订单商品结构MD5指纹', + }, + items_crc: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + comment: '订单商品结构CRC32校验', + }, + package_material_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '包材ID', + }, + package_material_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '包材编码(快照)', + }, + package_material_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '包材名称(快照)', + }, + package_material_spec: { + type: Sequelize.STRING(128), + allowNull: true, + defaultValue: '', + comment: '规格(快照)', + }, + package_material_type: { + type: Sequelize.STRING(32), + allowNull: true, + defaultValue: '', + comment: '类型(快照)', + }, + length: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '长(cm)快照', + }, + width: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '宽(cm)快照', + }, + height: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '高(cm)快照', + }, + weight: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '重量(kg)快照', + }, + bind_count: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '累计绑定次数', + }, + last_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '最近订单ID', + }, + last_waybill_code: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: '', + comment: '最近运单号', + }, + last_bind_user_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '最近操作用户ID', + }, + last_bind_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近绑定时间', + }, + is_active: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '包材当前是否启用', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + delete_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'items_hash', 'items_crc', 'package_material_id' ], { + unique: true, + name: 'uk_item_material', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'is_active', 'items_hash', 'bind_count' ], { + name: 'idx_lookup', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260615160000-alter-uk-interface-warehouse.js b/database/migrations/20260615160000-alter-uk-interface-warehouse.js new file mode 100644 index 0000000..29b00e8 --- /dev/null +++ b/database/migrations/20260615160000-alter-uk-interface-warehouse.js @@ -0,0 +1,34 @@ +'use strict'; + +module.exports = { + /** + * 修改 wms_api_app 表的唯一键 uk_interface_warehouse: + * 从 (qimen_app_key, qimen_customer_id) 改为 (qimen_app_key, qimen_warehouse_code) + * @param queryInterface + */ + up: async queryInterface => { + // 1. 删除旧唯一键 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse' + ); + // 2. 创建新唯一键 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_warehouse_code)' + ); + }, + + /** + * 回滚:恢复为 (qimen_app_key, qimen_customer_id) + * @param queryInterface + */ + down: async queryInterface => { + // 1. 删除新唯一键 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse' + ); + // 2. 恢复旧唯一键 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_customer_id)' + ); + }, +}; diff --git a/database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js b/database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js new file mode 100644 index 0000000..5337fdf --- /dev/null +++ b/database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js @@ -0,0 +1,20 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.changeColumn('wms_platfrom_setting', 'warehouse_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '仓库ID,NULL表示系统级设置', + }); + }, + + async down(queryInterface, Sequelize) { + // 回滚前需确认没有 warehouse_id=NULL 的数据,否则回滚会失败 + await queryInterface.changeColumn('wms_platfrom_setting', 'warehouse_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID', + }); + }, +}; diff --git a/database/migrations/20260618150000-create-wms-entry-receiving-binding.js b/database/migrations/20260618150000-create-wms-entry-receiving-binding.js new file mode 100644 index 0000000..07706ca --- /dev/null +++ b/database/migrations/20260618150000-create-wms-entry-receiving-binding.js @@ -0,0 +1,86 @@ +'use strict'; + +const TABLE_NAME = 'wms_entry_receiving_binding'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + entry_item_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '入库明细ID', + }, + receiving_detail_id: { + type: Sequelize.INTEGER, + allowNull: false, + comment: '收货明细ID', + }, + allocated_quantity: { + type: Sequelize.INTEGER, + allowNull: false, + comment: '预分配数量', + }, + status: { + type: Sequelize.ENUM('pending', 'committed', 'released'), + allowNull: false, + defaultValue: 'pending', + comment: '绑定状态:pending-待提交 committed-已提交 released-已释放', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人ID', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'entry_item_id' ], { + name: 'idx_entry_item_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'receiving_detail_id' ], { + name: 'idx_receiving_detail_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { + name: 'idx_status', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'entry_item_id', 'receiving_detail_id', 'status' ], { + unique: true, + name: 'uk_entry_receiving', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260621100000-create-wms-combo-goods.js b/database/migrations/20260621100000-create-wms-combo-goods.js new file mode 100644 index 0000000..bffeb3e --- /dev/null +++ b/database/migrations/20260621100000-create-wms-combo-goods.js @@ -0,0 +1,232 @@ +'use strict'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 幂等添加 custom_code 字段和索引(适用于表已存在但缺少新字段的场景)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const ensureCustomCodeColumnAndIndex = async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable('wms_combo_goods'); + if (!tableInfo.custom_code) { + await queryInterface.addColumn('wms_combo_goods', 'custom_code', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '自定义编码(前端可输入,按货主唯一)', + }); + } + + const indexes = await queryInterface.showIndex('wms_combo_goods'); + const hasIndex = indexes.some(idx => idx.name === 'uk_store_custom_code'); + if (!hasIndex) { + await queryInterface.addIndex('wms_combo_goods', [ 'warehouse_id', 'custom_code' ], { + name: 'uk_store_custom_code', + }); + } +}; + +/** + * 创建组合商品主表 `wms_combo_goods`。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createComboGoodsTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_combo_goods', { + id: { + type: Sequelize.INTEGER(11), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + combo_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '组合商品编码,业务唯一标识', + }, + combo_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '组合商品名称', + }, + custom_code: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '自定义编码(前端可输入,按货主唯一)', + }, + combo_sku_id: { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '组合商品关联的 wms_goods_sku.id', + }, + status: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:1-启用 0-停用', + }, + warehouse_id: { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '绑定仓库ID,NULL表示全局', + }, + remark: { + type: Sequelize.STRING(256), + allowNull: true, + comment: '备注', + }, + creator_id: { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '创建人ID', + }, + editor_id: { + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '最后编辑人ID', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'combo_code' ], { + unique: true, + name: 'uk_combo_code', + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'combo_sku_id' ], { + name: 'idx_combo_sku_id', + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'status' ], { + name: 'idx_status', + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + + await queryInterface.addIndex('wms_combo_goods', [ 'warehouse_id', 'custom_code' ], { + name: 'uk_store_custom_code', + }); +}; + +/** + * 创建组合商品明细表 `wms_combo_goods_item`。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createComboGoodsItemTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_combo_goods_item', { + id: { + type: Sequelize.INTEGER(11), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + combo_id: { + type: Sequelize.INTEGER(11), + allowNull: false, + comment: '关联 wms_combo_goods.id', + }, + item_goods_sku_id: { + type: Sequelize.INTEGER(11), + allowNull: false, + comment: '子商品SKU ID,关联 wms_goods_sku.id', + }, + item_quantity: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 1, + comment: '子商品数量(整数件数)', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序序号,越小越靠前', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + await queryInterface.addIndex('wms_combo_goods_item', [ 'combo_id' ], { + name: 'idx_combo_id', + }); + + await queryInterface.addIndex('wms_combo_goods_item', [ 'item_goods_sku_id' ], { + name: 'idx_item_goods_sku_id', + }); + + await queryInterface.addIndex('wms_combo_goods_item', [ 'combo_id', 'item_goods_sku_id' ], { + unique: true, + name: 'uk_combo_sku', + }); +}; + +module.exports = { + /** + * 执行 migration:创建组合商品主表与明细表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const existingTables = await getExistingTableSet(queryInterface); + + if (!existingTables.has('wms_combo_goods')) { + await createComboGoodsTable(queryInterface, Sequelize); + } else { + await ensureCustomCodeColumnAndIndex(queryInterface, Sequelize); + } + + if (!existingTables.has('wms_combo_goods_item')) { + await createComboGoodsItemTable(queryInterface, Sequelize); + } + }, + + /** + * 回滚 migration:删除组合商品明细表与主表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + await queryInterface.dropTable('wms_combo_goods_item'); + await queryInterface.dropTable('wms_combo_goods'); + }, +}; diff --git a/database/migrations/20260622100000-create-wms-inbound-direct-log.js b/database/migrations/20260622100000-create-wms-inbound-direct-log.js new file mode 100644 index 0000000..d02cc4a --- /dev/null +++ b/database/migrations/20260622100000-create-wms-inbound-direct-log.js @@ -0,0 +1,101 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbound_direct_log'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + stock_id: { + type: Sequelize.BIGINT(20), + allowNull: false, + comment: '商品SKU ID,关联 wms_stock_warehouse.id', + }, + quantity: { + type: Sequelize.INTEGER(12), + allowNull: false, + comment: '入库数量', + }, + inbound_type: { + type: Sequelize.ENUM('import', 'pda'), + allowNull: false, + comment: '入库方式:import-导入入库 pda-PDA入库', + }, + entry_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID(可选),关联 wms_entry_order.id', + }, + entry_order_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '入库单号(冗余,方便查询)', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注(如导入文件名、PDA操作备注等)', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '操作人名称', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'stock_id' ], { + name: 'idx_stock_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'inbound_type' ], { + name: 'idx_inbound_type', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'entry_order_id' ], { + name: 'idx_entry_order_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], { + name: 'idx_created_at', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260622110000-add-space-id-to-wms-inbound-direct-log.js b/database/migrations/20260622110000-add-space-id-to-wms-inbound-direct-log.js new file mode 100644 index 0000000..7e407d8 --- /dev/null +++ b/database/migrations/20260622110000-add-space-id-to-wms-inbound-direct-log.js @@ -0,0 +1,25 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbound_direct_log'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (!exists) return; + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.space_id) return; + + await queryInterface.addColumn(TABLE_NAME, 'space_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '存放库位ID,关联 wms_location_space.id;为空时 commit 默认使用 1', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'space_id'); + }, +}; diff --git a/database/migrations/20260622150000-seed-receipt-print-items.js b/database/migrations/20260622150000-seed-receipt-print-items.js new file mode 100644 index 0000000..5467e01 --- /dev/null +++ b/database/migrations/20260622150000-seed-receipt-print-items.js @@ -0,0 +1,67 @@ +'use strict'; + +/** + * 预置 ENTRY_ORDER(入库单)业务类型的打印项配置。 + * + * 幂等设计:基于唯一索引 (business_type, platform, field_code) 做 INSERT IGNORE, + * 不会重复插入已存在的记录。 + */ + +const TABLE = 'wms_print_items'; + +const ENTRY_ORDER_PRINT_ITEMS = [ + // ─── 入库单信息(group: entry_order_info) ────────────────── + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '入库单号', field_code: 'entry_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 1, required: true, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '业务类型', field_code: 'order_type', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 2, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '订单状态', field_code: 'order_status', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 3, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '采购单号', field_code: 'purchase_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 4, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '供应商名称', field_code: 'supplier_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 5, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库名称', field_code: 'warehouse_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 6, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '货主名称', field_code: 'store_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 7, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '物流公司', field_code: 'logistics_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 8, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '运单号', field_code: 'express_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 9, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '订单创建时间', field_code: 'order_create_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 10, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '预期到货时间', field_code: 'expect_start_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 11, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '备注', field_code: 'remark', field_type: 'textarea', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 12, required: false, status: 1 }, + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '单据总行数', field_code: 'total_order_lines', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 13, required: false, status: 1 }, + + // ─── 入库明细表格(is_table = true) ───────────────────────── + { business_type: 'ENTRY_ORDER', platform: 'default', field_name: '入库明细', field_code: 'items', field_type: 'text', is_table: true, table_config: { columns: 6, headers: [ '商品编码', '商品名称', '条码', '计划数量', '已收数量', '库存类型' ] }, group_field: 'entry_items', group_label: '入库明细', group_sort: 2, sort_order: 1, required: false, status: 1 }, +]; + +module.exports.up = async queryInterface => { + // 基于唯一索引做幂等插入 + const { sequelize } = queryInterface; + for (const item of ENTRY_ORDER_PRINT_ITEMS) { + await sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` + (business_type, platform, field_name, field_code, field_type, is_table, table_config, group_field, group_label, group_sort, sort_order, required, status, created_at, updated_at) + VALUES (:business_type, :platform, :field_name, :field_code, :field_type, :is_table, :table_config, :group_field, :group_label, :group_sort, :sort_order, :required, :status, NOW(), NOW())`, + { + replacements: { + business_type: item.business_type, + platform: item.platform, + field_name: item.field_name, + field_code: item.field_code, + field_type: item.field_type, + is_table: item.is_table ? 1 : 0, + table_config: item.table_config ? JSON.stringify(item.table_config) : null, + group_field: item.group_field || null, + group_label: item.group_label || null, + group_sort: item.group_sort || 0, + sort_order: item.sort_order || 0, + required: item.required ? 1 : 0, + status: item.status, + }, + type: sequelize.QueryTypes.INSERT, + } + ); + } +}; + +module.exports.down = async queryInterface => { + const { sequelize } = queryInterface; + await sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE business_type = 'ENTRY_ORDER' AND platform = 'default'` + ); +}; diff --git a/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js b/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js new file mode 100644 index 0000000..35f106a --- /dev/null +++ b/database/migrations/20260623120000-add-created-status-to-wms-entry-order.js @@ -0,0 +1,30 @@ +'use strict'; + +module.exports = { + /** + * 为 wms_entry_order 增加 CREATED 状态: + * ENUM 顺序: CREATING → CREATED → PENDING → CONFIRMED → PARTIAL_RECEIVED → COMPLETED → CANCELLED + * 默认值改为 CREATED + * @param queryInterface + */ + up: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('CREATING','CREATED','PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED') NOT NULL DEFAULT 'CREATED' COMMENT '订单状态'" + ); + }, + + /** + * 回滚: + * 1. 先将 CREATED 行更新为 PENDING + * 2. 再移除 CREATED 枚举值,恢复默认值 PENDING + * @param queryInterface + */ + down: async queryInterface => { + await queryInterface.sequelize.query( + "UPDATE wms_entry_order SET order_status = 'PENDING', updated_at = NOW() WHERE order_status = 'CREATED'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('CREATING','PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED') NOT NULL DEFAULT 'PENDING' COMMENT '订单状态'" + ); + }, +}; diff --git a/database/migrations/20260623130000-remove-confirmed-partial-received.js b/database/migrations/20260623130000-remove-confirmed-partial-received.js new file mode 100644 index 0000000..3aaf117 --- /dev/null +++ b/database/migrations/20260623130000-remove-confirmed-partial-received.js @@ -0,0 +1,33 @@ +'use strict'; + +module.exports = { + /** + * 从 wms_entry_order.order_status ENUM 中移除 CONFIRMED 和 PARTIAL_RECEIVED + * 简化状态:CREATING → CREATED → PENDING → COMPLETED → CANCELLED + * + * 前置条件: + * - CONFIRMED 行数为 0,无需迁移 + * - PARTIAL_RECEIVED 的 11 行改为 PENDING + * @param queryInterface + */ + up: async queryInterface => { + // 将 PARTIAL_RECEIVED 和 CONFIRMED 记录统一刷成 PENDING + await queryInterface.sequelize.query( + "UPDATE wms_entry_order SET order_status = 'PENDING', updated_at = NOW() WHERE order_status IN ('CONFIRMED', 'PARTIAL_RECEIVED')" + ); + // 缩小 ENUM:移除 CONFIRMED / PARTIAL_RECEIVED,保留 5 个状态 + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('CREATING','CREATED','PENDING','COMPLETED','CANCELLED') NOT NULL DEFAULT 'CREATED' COMMENT '订单状态'" + ); + }, + + /** + * 回滚:恢复 CONFIRMED 和 PARTIAL_RECEIVED 到 ENUM 中(不回滚数据) + * @param queryInterface + */ + down: async queryInterface => { + await queryInterface.sequelize.query( + "ALTER TABLE wms_entry_order MODIFY COLUMN order_status ENUM('CREATING','CREATED','PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED') NOT NULL DEFAULT 'CREATED' COMMENT '订单状态'" + ); + }, +}; diff --git a/database/migrations/20260623140000-create-entry-order-receiving.js b/database/migrations/20260623140000-create-entry-order-receiving.js new file mode 100644 index 0000000..d020aa8 --- /dev/null +++ b/database/migrations/20260623140000-create-entry-order-receiving.js @@ -0,0 +1,66 @@ +'use strict'; + +const TABLE_NAME = 'wms_entry_order_receiving'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + entry_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '入库单ID,关联 wms_entry_order.id', + }, + receiving_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '收货单ID,关联 wms_receiving.id', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'entry_order_id' ], { + name: 'idx_entry_order_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'receiving_id' ], { + name: 'idx_receiving_id', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'entry_order_id', 'receiving_id' ], { + unique: true, + name: 'uk_entry_order_receiving', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260629-add-waiting-storage-status.js b/database/migrations/20260629-add-waiting-storage-status.js new file mode 100644 index 0000000..7bd14e3 --- /dev/null +++ b/database/migrations/20260629-add-waiting-storage-status.js @@ -0,0 +1,76 @@ +'use strict'; + +/** + * 打印迁移阶段对应的数据库连接上下文信息。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {'up'|'down'} phase 迁移阶段。 + * @param {string} table 迁移目标表名。 + * @return {Promise} 无返回值。 + */ +const logMigrationDbContext = async (queryInterface, phase, table) => { + try { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user' + ); + const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {}; + console.log( + `[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}` + ); + } catch (error) { + console.warn( + `[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}` + ); + } +}; + +/** + * Migration: 为 wms_receiving 和 wms_receiving_detail 表的 storage_status 列新增 waiting 枚举值 + * + * 正向 SQL: + * ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'; + * ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'; + * + * 回滚 SQL: + * ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'; + * ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'; + */ + +const UP_SQL_RECEIVING = 'ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM(\'none\',\'waiting\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库\''; +const DOWN_SQL_RECEIVING = 'ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM(\'none\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, partial-部分入库, all-全部入库\''; + +const UP_SQL_DETAIL = 'ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM(\'none\',\'waiting\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库\''; +const DOWN_SQL_DETAIL = 'ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM(\'none\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, partial-部分入库, all-全部入库\''; + +module.exports = { + /** + * 执行正向迁移,为 storage_status 列新增 waiting 枚举值。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + await logMigrationDbContext(queryInterface, 'up', 'wms_receiving'); + await queryInterface.sequelize.query(UP_SQL_RECEIVING); + console.log('[Migration] wms_receiving.storage_status 已新增 waiting 枚举值'); + + await logMigrationDbContext(queryInterface, 'up', 'wms_receiving_detail'); + await queryInterface.sequelize.query(UP_SQL_DETAIL); + console.log('[Migration] wms_receiving_detail.storage_status 已新增 waiting 枚举值'); + }, + + /** + * 执行回滚迁移,移除 waiting 枚举值,恢复为原有枚举。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + down: async (queryInterface, Sequelize) => { + await logMigrationDbContext(queryInterface, 'down', 'wms_receiving'); + await queryInterface.sequelize.query(DOWN_SQL_RECEIVING); + console.log('[Migration] wms_receiving.storage_status 已移除 waiting 枚举值'); + + await logMigrationDbContext(queryInterface, 'down', 'wms_receiving_detail'); + await queryInterface.sequelize.query(DOWN_SQL_DETAIL); + console.log('[Migration] wms_receiving_detail.storage_status 已移除 waiting 枚举值'); + }, +}; diff --git a/database/migrations/20260630160000-create-wms-order-stockout.js b/database/migrations/20260630160000-create-wms-order-stockout.js new file mode 100644 index 0000000..609fc87 --- /dev/null +++ b/database/migrations/20260630160000-create-wms-order-stockout.js @@ -0,0 +1,309 @@ +'use strict'; + +const MAIN_TABLE = 'wms_order_stockout'; +const ITEMS_TABLE = 'wms_order_stockout_items'; + +/** + * 创建奇门出库单主表与明细表。 + * + * - wms_order_stockout:出库单主表(对应奇门 stockout.create 的 节点) + * - wms_order_stockout_items:出库明细表(对应 节点) + * + * 幂等:如果表已存在则跳过创建。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + + const exists = name => + tables.some(t => (typeof t === 'string' ? t : t.tableName) === name); + + // ----------------------- 主表 ----------------------- + if (!exists(MAIN_TABLE)) { + await queryInterface.createTable(MAIN_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + stockout_order_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '出库单号(对应奇门 deliveryOrderCode)', + }, + order_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '业务类型(JYCK/HHCK/BFCK/QTCK 等)', + }, + total_order_lines: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '单据总行数', + }, + order_create_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '订单创建时间(对应奇门 createTime)', + }, + source_type: { + type: Sequelize.ENUM('WMS', 'API', 'QM'), + allowNull: false, + defaultValue: 'QM', + comment: '来源类型', + }, + order_status: { + type: Sequelize.ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'), + allowNull: false, + defaultValue: 'CREATED', + comment: '订单状态', + }, + sync_status: { + type: Sequelize.ENUM('PENDING', 'SUCCESS', 'FAILED'), + allowNull: false, + defaultValue: 'PENDING', + comment: '同步状态', + }, + sync_message: { + type: Sequelize.TEXT, + allowNull: true, + comment: '同步返回信息', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + store_name: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '货主名称快照', + }, + warehouse_name: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '仓库名称快照', + }, + qimen_owner_code: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '奇门货主code(对应 ownerCode)', + }, + qimen_warehouse_code: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '奇门仓库code(对应 warehouseCode)', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + extend_props: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展属性', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 唯一索引:(stockout_order_code, warehouse_id, store_id) + await queryInterface.addIndex(MAIN_TABLE, [ 'stockout_order_code', 'warehouse_id', 'store_id' ], { + unique: true, + name: 'uk_stockout_order_code', + }); + + // 辅助查询索引 + await queryInterface.addIndex(MAIN_TABLE, [ 'order_type' ], { + name: 'idx_order_type', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'order_status' ], { + name: 'idx_order_status', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'sync_status' ], { + name: 'idx_sync_status', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'source_type' ], { + name: 'idx_source_type', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'warehouse_id', 'store_id' ], { + name: 'idx_warehouse_store', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'order_create_time' ], { + name: 'idx_order_create_time', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'is_enabled' ], { + name: 'idx_is_enabled', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + + // ----------------------- 明细表 ----------------------- + if (!exists(ITEMS_TABLE)) { + await queryInterface.createTable(ITEMS_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '出库单ID,外键关联 wms_order_stockout.id', + }, + out_biz_code: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '外部业务编码(幂等键)', + }, + order_line_no: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '订单行号(对应奇门 orderLineNo)', + }, + owner_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '货主编码(对应奇门 ownerCode)', + }, + item_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '商品编码(对应奇门 itemCode)', + }, + item_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: 'WMS商品ID(对应奇门 itemId)', + }, + item_name: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '商品名称', + }, + plan_qty: { + type: Sequelize.INTEGER(12), + allowNull: true, + comment: '计划数量(对应奇门 planQty)', + }, + actual_qty: { + type: Sequelize.INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实发数量', + }, + inventory_type: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '库存类型(ZP正品/CC残次等)', + }, + stock_id: { + type: Sequelize.BIGINT(20), + allowNull: true, + comment: '库存ID,外键关联 wms_stock_warehouse.id', + }, + extend_props: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展属性', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + // 唯一索引:(order_id, order_line_no) + await queryInterface.addIndex(ITEMS_TABLE, [ 'order_id', 'order_line_no' ], { + unique: true, + name: 'uk_order_line_no', + }); + + // 辅助索引 + await queryInterface.addIndex(ITEMS_TABLE, [ 'order_id' ], { + name: 'idx_order_id', + }); + await queryInterface.addIndex(ITEMS_TABLE, [ 'stock_id' ], { + name: 'idx_stock_id', + }); + await queryInterface.addIndex(ITEMS_TABLE, [ 'item_code' ], { + name: 'idx_item_code', + }); + await queryInterface.addIndex(ITEMS_TABLE, [ 'out_biz_code' ], { + name: 'idx_out_biz_code', + }); + + // 外键约束 + await queryInterface.addConstraint(ITEMS_TABLE, { + fields: [ 'order_id' ], + type: 'foreign key', + name: 'fk_items_order_id', + references: { + table: MAIN_TABLE, + field: 'id', + }, + onDelete: 'CASCADE', + onUpdate: 'CASCADE', + }); + + await queryInterface.addConstraint(ITEMS_TABLE, { + fields: [ 'stock_id' ], + type: 'foreign key', + name: 'fk_items_stock_id', + references: { + table: 'wms_stock_warehouse', + field: 'id', + }, + onDelete: 'RESTRICT', + onUpdate: 'CASCADE', + }); + } + }, + + down: async queryInterface => { + await queryInterface.dropTable(ITEMS_TABLE); + await queryInterface.dropTable(MAIN_TABLE); + }, +}; diff --git a/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js b/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js new file mode 100644 index 0000000..dd0c5df --- /dev/null +++ b/database/migrations/20260702-add-lock-unlock-to-wms-storage-transaction.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * 为 wms_storage_transaction.transaction_type ENUM 增加 LOCK / UNLOCK。 + * LOCK:分配储位锁定 + * UNLOCK:取消分配储位解锁 + */ +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_storage_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN', 'LOCK', 'UNLOCK' + ) NOT NULL COMMENT '交易类型:INBOUND入库 OUTBOUND出库 TRANSFER_OUT移出 TRANSFER_IN移入 LOCK分配储位锁定 UNLOCK取消分配储位解锁' + `); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_storage_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN' + ) NOT NULL COMMENT '出入库类型' + `); + }, +}; diff --git a/database/migrations/20260702-alter-print-template-business-type.js b/database/migrations/20260702-alter-print-template-business-type.js new file mode 100644 index 0000000..625a797 --- /dev/null +++ b/database/migrations/20260702-alter-print-template-business-type.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * 扩展 wms_print_template 表 business_type 字段长度:VARCHAR(10) → VARCHAR(50)。 + * + * 背景:business_type 原有长度 10,无法容纳 ENTRY_ORDER(11 字符), + * 需要与 wms_print_items.business_type VARCHAR(50) 保持一致。 + */ + +module.exports.up = async queryInterface => { + const { sequelize } = queryInterface; + + await sequelize.query( + `ALTER TABLE \`wms_print_template\` + MODIFY COLUMN \`business_type\` VARCHAR(50) NOT NULL COMMENT '类型'` + ); +}; + +module.exports.down = async queryInterface => { + const { sequelize } = queryInterface; + + // 注意:如果表中已存在 business_type 长度超过 10 的数据(如 ENTRY_ORDER), + // 此回滚会因数据截断而失败。执行前请确认数据已清理或回迁。 + await sequelize.query( + `ALTER TABLE \`wms_print_template\` + MODIFY COLUMN \`business_type\` VARCHAR(10) NOT NULL COMMENT '类型'` + ); +}; diff --git a/database/migrations/20260703000000-add-binding-fields-to-wms-inbound-direct-log.js b/database/migrations/20260703000000-add-binding-fields-to-wms-inbound-direct-log.js new file mode 100644 index 0000000..7ff40f3 --- /dev/null +++ b/database/migrations/20260703000000-add-binding-fields-to-wms-inbound-direct-log.js @@ -0,0 +1,100 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbound_direct_log'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (!exists) return; + + const columns = await queryInterface.describeTable(TABLE_NAME); + + // 新增 entry_item_id 字段 + if (!columns.entry_item_id) { + await queryInterface.addColumn(TABLE_NAME, 'entry_item_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '入库明细ID', + }); + } + + // 新增 receiving_detail_id 字段 + if (!columns.receiving_detail_id) { + await queryInterface.addColumn(TABLE_NAME, 'receiving_detail_id', { + type: Sequelize.INTEGER(11), + allowNull: true, + defaultValue: null, + comment: '收货明细ID,绑定收货时使用', + }); + } + + // 新增 status 字段 + if (!columns.status) { + await queryInterface.addColumn(TABLE_NAME, 'status', { + type: Sequelize.ENUM('pending', 'committed', 'released'), + allowNull: true, + defaultValue: null, + comment: '绑定状态:pending=待提交 committed=已提交 released=已释放,非绑定模式为NULL', + }); + } + + // 新增 updated_at 字段 + if (!columns.updated_at) { + await queryInterface.addColumn(TABLE_NAME, 'updated_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '更新时间', + }); + } + + // 新增 deleted_at 字段(软删除) + if (!columns.deleted_at) { + await queryInterface.addColumn(TABLE_NAME, 'deleted_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }); + } + + // 新增索引 idx_entry_item_id + await queryInterface.addIndex(TABLE_NAME, [ 'entry_item_id' ], { + name: 'idx_entry_item_id', + }); + + // 新增索引 idx_receiving_detail_id + await queryInterface.addIndex(TABLE_NAME, [ 'receiving_detail_id' ], { + name: 'idx_receiving_detail_id', + }); + + // 新增索引 idx_status + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { + name: 'idx_status', + }); + + // 新增唯一约束 uk_entry_receiving_binding + await queryInterface.addIndex(TABLE_NAME, [ 'entry_item_id', 'receiving_detail_id', 'status' ], { + name: 'uk_entry_receiving_binding', + unique: true, + }); + }, + + down: async queryInterface => { + // 移除唯一约束 + await queryInterface.removeIndex(TABLE_NAME, 'uk_entry_receiving_binding'); + // 移除索引 + await queryInterface.removeIndex(TABLE_NAME, 'idx_status'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_receiving_detail_id'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_entry_item_id'); + + // 移除字段 + await queryInterface.removeColumn(TABLE_NAME, 'deleted_at'); + await queryInterface.removeColumn(TABLE_NAME, 'updated_at'); + await queryInterface.removeColumn(TABLE_NAME, 'status'); + await queryInterface.removeColumn(TABLE_NAME, 'receiving_detail_id'); + await queryInterface.removeColumn(TABLE_NAME, 'entry_item_id'); + }, +}; diff --git a/database/migrations/20260703000001-migrate-binding-data-to-inbound-direct-log.js b/database/migrations/20260703000001-migrate-binding-data-to-inbound-direct-log.js new file mode 100644 index 0000000..7ec574e --- /dev/null +++ b/database/migrations/20260703000001-migrate-binding-data-to-inbound-direct-log.js @@ -0,0 +1,184 @@ +'use strict'; + +/** + * 数据迁移:将 wms_entry_receiving_binding 存量数据迁移到 wms_inbound_direct_log。 + * + * 背景: + * - wms_entry_receiving_binding 的"入库明细 ↔ 收货明细"绑定能力已迁移到 wms_inbound_direct_log。 + * - 本 migration 负责将 wms_entry_receiving_binding 中的历史数据同步到 wms_inbound_direct_log。 + * + * 字段映射(source → target): + * - entry_item_id / receiving_detail_id / allocated_quantity→quantity / status / creator_id→operator_id + * - created_at→created_at / updated_at→updated_at / deleted_at→deleted_at + * + * 关联补全: + * - entry_order_id / entry_order_code / warehouse_id / store_id:通过 wms_entry_items + wms_entry_order + * - stock_id:从 wms_entry_items + * - inbound_type:固定 'pda' + * - space_id:固定 0 + * + * @description 迁移脚本:20260703000001 + */ + +/** 目标表名 */ +const TARGET_TABLE = 'wms_inbound_direct_log'; +/** 源表名 */ +const SOURCE_TABLE = 'wms_entry_receiving_binding'; + +/** + * 规范化 showAllTables 返回的表名。 + * @param {string|Object} table 表名或表对象。 + * @return {string} 规范化后的表名。 + */ +const normalizeTableName = table => { + if (typeof table === 'string') return table; + return table && typeof table === 'object' ? (table.tableName || table.name || '') : ''; +}; + +/** + * 检查源表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 源表是否存在。 + */ +const hasSourceTable = async queryInterface => { + const allTables = await queryInterface.showAllTables(); + const tableSet = new Set((allTables || []).map(normalizeTableName)); + return tableSet.has(SOURCE_TABLE); +}; + +/** + * 检查目标表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 目标表是否存在。 + */ +const hasTargetTable = async queryInterface => { + const allTables = await queryInterface.showAllTables(); + const tableSet = new Set((allTables || []).map(normalizeTableName)); + return tableSet.has(TARGET_TABLE); +}; + +/** + * 统计源表总行数。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 源表总行数。 + */ +const countSourceRows = async queryInterface => { + const [ rows ] = await queryInterface.sequelize.query( + `SELECT COUNT(*) AS cnt FROM ${SOURCE_TABLE}`, + { type: queryInterface.sequelize.QueryTypes.SELECT } + ); + return rows ? rows.cnt : 0; +}; + +/** + * 正向迁移:从 wms_entry_receiving_binding 迁移数据到 wms_inbound_direct_log。 + * + * 去重策略:按 (entry_item_id, receiving_detail_id, status) GROUP BY 去重, + * 重复组保留 id 最小的一条,其余跳过并打印数量。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + void Sequelize; + + // 幂等:源表不存在则跳过 + if (!(await hasSourceTable(queryInterface))) { + console.log('wms_entry_receiving_binding 表不存在,跳过迁移'); + return; + } + + // 幂等:目标表不存在则跳过 + if (!(await hasTargetTable(queryInterface))) { + console.log('wms_inbound_direct_log 表不存在,跳过迁移'); + return; + } + + const totalRows = await countSourceRows(queryInterface); + console.log(`wms_entry_receiving_binding 总行数:${totalRows}`); + + if (totalRows === 0) { + console.log('无数据需要迁移,跳过'); + return; + } + + // 统计去重后跳过的行数 + const [ dupResult ] = await queryInterface.sequelize.query( + `SELECT COUNT(*) AS skip_cnt + FROM ${SOURCE_TABLE} + WHERE id NOT IN ( + SELECT MIN(id) + FROM ${SOURCE_TABLE} + GROUP BY entry_item_id, receiving_detail_id, status + )`, + { type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const skipCount = dupResult ? dupResult.skip_cnt : 0; + if (skipCount > 0) { + console.log(`检测到 ${skipCount} 条重复记录(按 entry_item_id + receiving_detail_id + status 分组去重),将被跳过`); + } + + // 执行 INSERT INTO ... SELECT + const [ insertResult ] = await queryInterface.sequelize.query( + `INSERT INTO ${TARGET_TABLE} + (entry_item_id, receiving_detail_id, quantity, status, + operator_id, created_at, updated_at, deleted_at, + entry_order_id, entry_order_code, warehouse_id, store_id, + stock_id, inbound_type, space_id) + SELECT + b.entry_item_id, + b.receiving_detail_id, + b.allocated_quantity, + b.status, + b.creator_id, + b.created_at, + b.updated_at, + b.deleted_at, + ei.order_id, + eo.entry_order_code, + eo.warehouse_id, + eo.store_id, + ei.stock_id, + 'pda', + 0 + FROM ${SOURCE_TABLE} b + LEFT JOIN wms_entry_items ei ON b.entry_item_id = ei.id + LEFT JOIN wms_entry_order eo ON ei.order_id = eo.id + WHERE b.id IN ( + SELECT MIN(id) + FROM ${SOURCE_TABLE} + GROUP BY entry_item_id, receiving_detail_id, status + )`, + { type: queryInterface.sequelize.QueryTypes.INSERT } + ); + + const insertedCount = insertResult ? (Array.isArray(insertResult) ? insertResult.length : insertResult[1]) : 0; + console.log(`迁移完成:成功插入 ${insertedCount} 行`); +}; + +/** + * 回滚迁移:删除从 wms_entry_receiving_binding 迁移过来的数据。 + * + * 删除条件:receiving_detail_id IS NOT NULL AND entry_item_id IS NOT NULL + * (仅删除有绑定关系的记录,不影响原有 direct-log 数据) + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async queryInterface => { + if (!(await hasTargetTable(queryInterface))) { + console.log('wms_inbound_direct_log 表不存在,跳过回滚'); + return; + } + + const [ deleteResult ] = await queryInterface.sequelize.query( + `DELETE FROM ${TARGET_TABLE} + WHERE receiving_detail_id IS NOT NULL + AND entry_item_id IS NOT NULL`, + { type: queryInterface.sequelize.QueryTypes.DELETE } + ); + + const deletedCount = deleteResult || 0; + console.log(`回滚完成:删除 ${deletedCount} 行`); +}; diff --git a/database/migrations/20260706-add-lock-to-wms-stock-transaction.js b/database/migrations/20260706-add-lock-to-wms-stock-transaction.js new file mode 100644 index 0000000..89c1f08 --- /dev/null +++ b/database/migrations/20260706-add-lock-to-wms-stock-transaction.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 为 wms_stock_transaction.transaction_type ENUM 增加 LOCK。 + * LOCK:库存锁定流水(如分配订单锁定库存)。 + */ +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_stock_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'LOCK' + ) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定' + `); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_stock_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND' + ) NOT NULL COMMENT '出入库类型' + `); + }, +}; diff --git a/database/migrations/20260706-rename-use-status-and-add-store-use-status.js b/database/migrations/20260706-rename-use-status-and-add-store-use-status.js new file mode 100644 index 0000000..beee4a0 --- /dev/null +++ b/database/migrations/20260706-rename-use-status-and-add-store-use-status.js @@ -0,0 +1,25 @@ +'use strict'; + +/** + * 将 wms_store_warehouse.use_status 重命名为 warehouse_use_status, + * 并新增 store_use_status 供货主端独立控制使用状态。 + */ +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_store_warehouse + CHANGE COLUMN use_status warehouse_use_status INT(1) NOT NULL DEFAULT 1 COMMENT '仓库侧使用状态:0-不可用,1-可用', + ADD COLUMN store_use_status INT(1) NOT NULL DEFAULT 1 COMMENT '货主侧使用状态:0-不可用,1-可用' AFTER warehouse_use_status + `); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_store_warehouse + DROP COLUMN store_use_status, + CHANGE COLUMN warehouse_use_status use_status INT(1) NOT NULL DEFAULT 1 COMMENT '使用状态,0-不可用,1-可用(SKU可见,货主可见,即使解约了)' + `); + }, +}; diff --git a/database/migrations/20260707-add-initiator-subject-id-to-store-warehouse.js b/database/migrations/20260707-add-initiator-subject-id-to-store-warehouse.js new file mode 100644 index 0000000..9699f88 --- /dev/null +++ b/database/migrations/20260707-add-initiator-subject-id-to-store-warehouse.js @@ -0,0 +1,24 @@ +'use strict'; + +/** + * wms_store_warehouse 增加 initiator_subject_id 记录发起方主体 ID, + * 用于区分签-约发起方(与 applied_by 账号 ID 互补)。 + */ +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_store_warehouse + ADD COLUMN initiator_subject_id BIGINT(20) UNSIGNED NULL COMMENT '发起方主体ID(wms_store.id)' + AFTER ended_by + `); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_store_warehouse + DROP COLUMN initiator_subject_id + `); + }, +}; diff --git a/database/migrations/20260708000000-add-stock-id-to-wms-picking.js b/database/migrations/20260708000000-add-stock-id-to-wms-picking.js new file mode 100644 index 0000000..d9ac4f6 --- /dev/null +++ b/database/migrations/20260708000000-add-stock-id-to-wms-picking.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * 为 wms_picking 表新增 stock_id 字段及联合索引。 + * + * 用途:消除面单打印自定义区对 wms_order_items 明细表的强依赖, + * 使打印链路可通过 wms_picking.stock_id 直读商品信息与条码数据。 + */ +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE wms_picking + ADD COLUMN stock_id BIGINT(20) DEFAULT NULL COMMENT '商品SKU ID' AFTER storage_id, + ADD INDEX idx_wms_picking_warehouse_stock (warehouse_id, stock_id) + `); + + // 回填已有 picking 记录的 stock_id(通过 storage 链路补全) + await queryInterface.sequelize.query(` + UPDATE wms_picking p + INNER JOIN wms_storage s ON p.storage_id = s.id + SET p.stock_id = s.stock_id + WHERE p.stock_id IS NULL + AND p.storage_id IS NOT NULL + `); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE wms_picking + DROP INDEX idx_wms_picking_warehouse_stock, + DROP COLUMN stock_id + `); + }, +}; diff --git a/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js b/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js new file mode 100644 index 0000000..aa5e3c2 --- /dev/null +++ b/database/migrations/20260710000000-fix-custom-barcode-unique-to-per-warehouse.js @@ -0,0 +1,20 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // 将 custom_barcode 唯一索引从全局改为仓库级别 + await queryInterface.removeIndex('wms_location_space', 'uk_custom_barcode'); + await queryInterface.addIndex('wms_location_space', [ 'warehouse_id', 'custom_barcode', 'deleted_at' ], { + name: 'uk_warehouse_custom_barcode', + unique: true, + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeIndex('wms_location_space', 'uk_warehouse_custom_barcode'); + await queryInterface.addIndex('wms_location_space', [ 'custom_barcode' ], { + name: 'uk_custom_barcode', + unique: true, + }); + }, +}; diff --git a/database/migrations/20260711160000-add-unlock-to-wms-stock-transaction.js b/database/migrations/20260711160000-add-unlock-to-wms-stock-transaction.js new file mode 100644 index 0000000..614be53 --- /dev/null +++ b/database/migrations/20260711160000-add-unlock-to-wms-stock-transaction.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 为 wms_stock_transaction.transaction_type ENUM 增加 UNLOCK。 + * UNLOCK:库存释放流水(如取消订单释放创建锁)。 + */ +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_stock_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'LOCK', 'UNLOCK' + ) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定 UNLOCK解锁' + `); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query(` + ALTER TABLE wms_stock_transaction + MODIFY COLUMN transaction_type ENUM( + 'INBOUND', 'OUTBOUND', 'LOCK' + ) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定' + `); + }, +}; diff --git a/database/migrations/20260712-add-store-receiving-permission.js b/database/migrations/20260712-add-store-receiving-permission.js new file mode 100644 index 0000000..a43e266 --- /dev/null +++ b/database/migrations/20260712-add-store-receiving-permission.js @@ -0,0 +1,163 @@ +'use strict'; + +/** + * 货主侧收货单页面权限及 API 权限迁移。 + * + * 变更内容: + * 1. 新增 web_pages 权限:收货单(货主) — 货主平台侧收货单列表页面 + * 2. 新增 api 权限:account_platform.getStoreReceivingList — 货主侧收货单查询接口 + * 3. 将上述权限授权给 货主管理员(store_admin_default, id=5) 角色 + * + * 幂等设计: + * - 先查后插(按 path + type 唯一性判断) + * - 角色权限更新使用 JSON 数组合并去重 + */ + +const TABLE_PERMISSION = 'wms_permission'; +const TABLE_ROLE = 'wms_role'; + +const STORE_ADMIN_ROLE_ID = 5; + +/** @type {{path: string, name: string|null, meta_title: string, type: string, parent_id: number|null, sort: number}[]} */ +const NEW_PERMISSIONS = [ + { + path: 'receiving_owner', + name: 'OwnerReceiving', + meta_title: '收货单(货主)', + type: 'web_pages', + parent_id: 18, // 库存 + sort: 0, + component: '@/views/storage/receiving_owner/index', + }, + { + path: 'storage.receiving.getStoreReceivingList', + name: 'storage.receiving.getStoreReceivingList', + meta_title: '货主侧收货单列表查询', + type: 'api', + parent_id: null, + sort: 0, + component: null, + }, +]; + +/** + * 获取角色当前权限 ID 数组。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @return {Promise} 权限ID数组 + */ +async function getRolePermissionIds(queryInterface, roleId) { + const [ rows ] = await queryInterface.sequelize.query( + `SELECT permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + if (!rows || rows.length === 0) return []; + + const raw = rows[0].permissions; + if (!raw) return []; + + try { + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) { + return parsed.map(Number).filter(n => Number.isFinite(n) && n > 0); + } + } catch (_) { + // ignore + } + + return []; +} + +/** + * 保存角色权限。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @param {number[]} permissionIds 权限ID数组 + * @return {Promise} + */ +async function saveRolePermissions(queryInterface, roleId, permissionIds) { + const unique = Array.from(new Set(permissionIds)).sort((a, b) => a - b); + const json = JSON.stringify(unique); + + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_ROLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :roleId`, + { replacements: { roleId, permissions: json } } + ); +} + +/** + * 正向迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.up = async queryInterface => { + const insertedIds = []; + + for (const perm of NEW_PERMISSIONS) { + const [ existing ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type LIMIT 1`, + { replacements: { path: perm.path, type: perm.type } } + ); + + if (existing && existing.length > 0) { + console.log(`[Migration] 权限已存在,跳过: ${perm.path} (type=${perm.type}, id=${existing[0].id})`); + insertedIds.push(existing[0].id); + continue; + } + + const [ result ] = await queryInterface.sequelize.query( + `INSERT INTO \`${TABLE_PERMISSION}\` (path, name, component, meta_title, type, parent_id, sort, status, created_at, update_at) + VALUES (:path, :name, :component, :meta_title, :type, :parent_id, :sort, 1, NOW(), NOW())`, + { replacements: { ...perm } } + ); + + const newId = result; + console.log(`[Migration] 新增权限: ${perm.path} (type=${perm.type}, id=${newId})`); + insertedIds.push(newId); + } + + // 更新 货主管理员 角色权限 + const currentIds = await getRolePermissionIds(queryInterface, STORE_ADMIN_ROLE_ID); + const mergedIds = Array.from(new Set([ ...currentIds, ...insertedIds ])).sort((a, b) => a - b); + + console.log(`[Migration] 货主管理员(id=${STORE_ADMIN_ROLE_ID}) 权限更新: [${currentIds.join(',')}] -> [${mergedIds.join(',')}]`); + await saveRolePermissions(queryInterface, STORE_ADMIN_ROLE_ID, mergedIds); + + console.log(`[Migration] 完成:新增 ${insertedIds.length} 条权限,角色权限已更新`); +}; + +/** + * 回滚迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.down = async queryInterface => { + // 1. 从角色权限中移除新增的权限 ID + const pathsToRemove = NEW_PERMISSIONS.map(p => p.path); + + const [ permRows ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path IN (:paths) AND type IN (:types)`, + { + replacements: { + paths: pathsToRemove, + types: NEW_PERMISSIONS.map(p => p.type), + }, + } + ); + + const idsToRemove = permRows.map(r => r.id); + const currentIds = await getRolePermissionIds(queryInterface, STORE_ADMIN_ROLE_ID); + const filteredIds = currentIds.filter(id => !idsToRemove.includes(id)); + + await saveRolePermissions(queryInterface, STORE_ADMIN_ROLE_ID, filteredIds); + console.log(`[Migration Rollback] 角色权限已移除: ${idsToRemove.join(',')}`); + + // 2. 删除新增的权限记录 + for (const perm of NEW_PERMISSIONS) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type`, + { replacements: { path: perm.path, type: perm.type } } + ); + console.log(`[Migration Rollback] 已删除权限: ${perm.path}`); + } +}; diff --git a/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js b/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js new file mode 100644 index 0000000..93286cf --- /dev/null +++ b/database/migrations/20260713150000-set-auto-increment-wms-order-delivery-1000028.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 紧急修复:将 wms_order_delivery_1000028 自增值提升至 15000+ + // 原因:表重建后 AUTO_INCREMENT 被重置为 151,与历史水位差距过大 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 15000' + ); + }, + + async down(queryInterface) { + // 回滚:重置为默认(MAX(id)+1) + await queryInterface.sequelize.query( + 'ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 1' + ); + }, +}; diff --git a/database/migrations/20260715160000-create-wms-workbench.js b/database/migrations/20260715160000-create-wms-workbench.js new file mode 100644 index 0000000..53ca5f5 --- /dev/null +++ b/database/migrations/20260715160000-create-wms-workbench.js @@ -0,0 +1,89 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '工作台名称(用户自定义)', + }, + barcode: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '工作台条码(用户自定义,仓库内唯一)', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 仓库隔离查询 + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + + // 条码检索 + await queryInterface.addIndex(TABLE_NAME, [ 'barcode' ], { + name: 'idx_barcode', + }); + + // 仓库级别唯一条码(含软删除,遵循 location_space 同款模式) + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'barcode', 'deleted_at' ], { + unique: true, + name: 'uk_warehouse_barcode', + }); + + // 软删除查询优化 + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260715170000-add-type-to-wms-workbench.js b/database/migrations/20260715170000-add-type-to-wms-workbench.js new file mode 100644 index 0000000..4e10f28 --- /dev/null +++ b/database/migrations/20260715170000-add-type-to-wms-workbench.js @@ -0,0 +1,19 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'type', { + type: Sequelize.ENUM('personal', 'group'), + allowNull: false, + defaultValue: 'personal', + comment: '工作台类型:personal-个人工作台 group-团体工作台', + after: 'status', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'type'); + }, +}; diff --git a/database/migrations/20260715180000-extend-wms-pack-task.js b/database/migrations/20260715180000-extend-wms-pack-task.js new file mode 100644 index 0000000..54a3dbb --- /dev/null +++ b/database/migrations/20260715180000-extend-wms-pack-task.js @@ -0,0 +1,160 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + // 1. 仓库隔离 + await queryInterface.addColumn(TABLE_NAME, 'warehouse_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + after: 'order_id', + }); + + // 2. 工作台关联 + await queryInterface.addColumn(TABLE_NAME, 'workbench_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '工作台ID,关联 wms_workbench.id', + after: 'warehouse_id', + }); + + // 3. 波次信息 + await queryInterface.addColumn(TABLE_NAME, 'wave_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '波次ID', + after: 'workbench_id', + }); + await queryInterface.addColumn(TABLE_NAME, 'wave_no', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '波次号', + after: 'wave_id', + }); + + // 4. 运单号 + await queryInterface.addColumn(TABLE_NAME, 'waybill_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '运单号', + after: 'wave_no', + }); + + // 5. 打包数量 + await queryInterface.addColumn(TABLE_NAME, 'pack_quantity', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '打包数量(件数)', + after: 'waybill_code', + }); + + // 6. 作业时间 + await queryInterface.addColumn(TABLE_NAME, 'start_time', { + type: Sequelize.DATE, + allowNull: true, + comment: '开始打包时间', + after: 'pack_quantity', + }); + await queryInterface.addColumn(TABLE_NAME, 'end_time', { + type: Sequelize.DATE, + allowNull: true, + comment: '结束打包时间', + after: 'start_time', + }); + + // 7. 作业人员(兼容多人的自由文本) + await queryInterface.addColumn(TABLE_NAME, 'operator_text', { + type: Sequelize.TEXT, + allowNull: true, + comment: '作业人员(自由文本,如多人逗号分隔)', + after: 'end_time', + }); + + // 8. 设备IDS(JSON列表) + await queryInterface.addColumn(TABLE_NAME, 'device_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '设备ID列表,如 [1,2,3]', + after: 'operator_text', + }); + + // 9. 包材信息 + await queryInterface.addColumn(TABLE_NAME, 'package_material_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID,关联 wms_package_material.id', + after: 'device_ids', + }); + await queryInterface.addColumn(TABLE_NAME, 'package_material_snapshot', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '包材快照(编码+名称)', + after: 'package_material_id', + }); + + // 10. 称重 + await queryInterface.addColumn(TABLE_NAME, 'weighing_weight', { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '打包称重(kg)', + after: 'package_material_snapshot', + }); + + // 11. 异常 + await queryInterface.addColumn(TABLE_NAME, 'abnormal_reason', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '异常原因', + after: 'weighing_weight', + }); + + // 12. 备注 + await queryInterface.addColumn(TABLE_NAME, 'remark', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + after: 'abnormal_reason', + }); + + // 13. 修改 status 注释以包含更多状态 + await queryInterface.changeColumn(TABLE_NAME, 'status', { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0=待处理 1=打包中 2=已完成 3=异常', + }); + + // ======== 索引 ======== + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'workbench_id' ], { name: 'idx_workbench_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'wave_id' ], { name: 'idx_wave_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'start_time' ], { name: 'idx_start_time' }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); + }, + + down: async queryInterface => { + const cols = [ + 'remark', 'abnormal_reason', 'weighing_weight', + 'package_material_snapshot', 'package_material_id', + 'device_ids', 'operator_text', 'end_time', 'start_time', + 'pack_quantity', 'waybill_code', 'wave_no', 'wave_id', + 'workbench_id', 'warehouse_id', + ]; + for (const col of cols) { + await queryInterface.removeColumn(TABLE_NAME, col); + } + + await queryInterface.removeIndex(TABLE_NAME, 'idx_status'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_start_time'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_waybill_code'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_wave_id'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_workbench_id'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id'); + }, +}; diff --git a/database/migrations/20260715190000-remove-redundant-packer-fields.js b/database/migrations/20260715190000-remove-redundant-packer-fields.js new file mode 100644 index 0000000..93bab49 --- /dev/null +++ b/database/migrations/20260715190000-remove-redundant-packer-fields.js @@ -0,0 +1,36 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task'; + +module.exports = { + up: async queryInterface => { + // 打包人信息已由 wms_pack_task_packer 子表承载,删除主表冗余字段 + await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_emp_id'); + await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_emp_no'); + await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_name'); + await queryInterface.removeColumn(TABLE_NAME, 'packers_snapshot'); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'primary_packer_emp_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '主打包人工号ID', + }); + await queryInterface.addColumn(TABLE_NAME, 'primary_packer_emp_no', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '主打包人工号', + }); + await queryInterface.addColumn(TABLE_NAME, 'primary_packer_name', { + type: Sequelize.STRING(128), + allowNull: true, + comment: '主打包人姓名', + }); + await queryInterface.addColumn(TABLE_NAME, 'packers_snapshot', { + type: Sequelize.JSON, + allowNull: true, + comment: '打包人快照:散单对象/团购数组', + }); + }, +}; diff --git a/database/migrations/20260715200000-remove-redundant-material-fields.js b/database/migrations/20260715200000-remove-redundant-material-fields.js new file mode 100644 index 0000000..e40cb8e --- /dev/null +++ b/database/migrations/20260715200000-remove-redundant-material-fields.js @@ -0,0 +1,36 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task'; + +module.exports = { + up: async queryInterface => { + // 包材/称重/异常已由 wms_order_express 表(按运单号维度)承载,删除冗余 + await queryInterface.removeColumn(TABLE_NAME, 'package_material_id'); + await queryInterface.removeColumn(TABLE_NAME, 'package_material_snapshot'); + await queryInterface.removeColumn(TABLE_NAME, 'weighing_weight'); + await queryInterface.removeColumn(TABLE_NAME, 'abnormal_reason'); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'package_material_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID,关联 wms_package_material.id', + }); + await queryInterface.addColumn(TABLE_NAME, 'package_material_snapshot', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '包材快照(编码+名称)', + }); + await queryInterface.addColumn(TABLE_NAME, 'weighing_weight', { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '打包称重(kg)', + }); + await queryInterface.addColumn(TABLE_NAME, 'abnormal_reason', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '异常原因', + }); + }, +}; diff --git a/database/migrations/20260715210000-add-device-ids-to-wms-workbench.js b/database/migrations/20260715210000-add-device-ids-to-wms-workbench.js new file mode 100644 index 0000000..a76c697 --- /dev/null +++ b/database/migrations/20260715210000-add-device-ids-to-wms-workbench.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'device_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids', + after: 'remark', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'device_ids'); + }, +}; diff --git a/database/migrations/20260715220000-create-wms-camera-server.js b/database/migrations/20260715220000-create-wms-camera-server.js new file mode 100644 index 0000000..5e2dc93 --- /dev/null +++ b/database/migrations/20260715220000-create-wms-camera-server.js @@ -0,0 +1,98 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera_server'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '服务器名称', + }, + brand: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '品牌(如 Hikvision/Dahua)', + }, + public_ip: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '公网IP', + }, + internal_ip: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '内网IP', + }, + port: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 80, + comment: '端口号', + }, + username: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '登录账号', + }, + password: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '登录密码', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260715220001-create-wms-camera.js b/database/migrations/20260715220001-create-wms-camera.js new file mode 100644 index 0000000..328ddc3 --- /dev/null +++ b/database/migrations/20260715220001-create-wms-camera.js @@ -0,0 +1,88 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + server_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属录像服务器ID,关联 wms_camera_server.id', + }, + channel_id: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + comment: '通道编号(DVR/NVR 上的物理通道号)', + }, + channel_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '通道原始名称', + }, + custom_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '自定义摄像头名称', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'server_id' ], { name: 'idx_server_id' }); + // 同一服务器下通道号唯一 + await queryInterface.addIndex(TABLE_NAME, [ 'server_id', 'channel_id', 'deleted_at' ], { + unique: true, + name: 'uk_server_channel', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260715230000-create-wms-pack-task-video.js b/database/migrations/20260715230000-create-wms-pack-task-video.js new file mode 100644 index 0000000..32a871c --- /dev/null +++ b/database/migrations/20260715230000-create-wms-pack-task-video.js @@ -0,0 +1,72 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task_video'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + pack_task_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '打包任务ID,关联 wms_pack_task.id', + }, + camera_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '摄像头设备ID,关联 wms_camera.id', + }, + video_url: { + type: Sequelize.STRING(500), + allowNull: false, + comment: '视频地址(录像回放URL)', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-无效 1-有效', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id' ], { name: 'idx_pack_task_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'camera_id' ], { name: 'idx_camera_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260717150000-add-camera-device-fields.js b/database/migrations/20260717150000-add-camera-device-fields.js new file mode 100644 index 0000000..46ce25e --- /dev/null +++ b/database/migrations/20260717150000-add-camera-device-fields.js @@ -0,0 +1,55 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera'; + +/** + * 新增摄像头设备信息字段:IP、SDK端口、型号、序列号、码流类型。 + * 用于保存 NVR 服务器返回的摄像头详细设备信息。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = [ + { + name: 'ip', + def: { type: Sequelize.STRING(50), allowNull: true, comment: '摄像头IP地址', after: 'channel_name' }, + }, + { + name: 'port', + def: { type: Sequelize.INTEGER.UNSIGNED, allowNull: true, comment: 'SDK管理端口(通常2020/8000)', after: 'ip' }, + }, + { + name: 'model', + def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头型号', after: 'port' }, + }, + { + name: 'serial_number', + def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头序列号', after: 'model' }, + }, + { + name: 'stream_type', + def: { type: Sequelize.STRING(20), allowNull: true, comment: '码流类型(auto/main/sub)', after: 'serial_number' }, + }, + ]; + + for (const col of columns) { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (!tableInfo[col.name]) { + await queryInterface.addColumn(TABLE_NAME, col.name, col.def); + console.log(`[Migration] wms_camera.${col.name} 已添加`); + } else { + console.log(`[Migration] wms_camera.${col.name} 已存在,跳过`); + } + } + }, + + down: async queryInterface => { + const columns = [ 'stream_type', 'serial_number', 'model', 'port', 'ip' ]; + for (const col of columns) { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (tableInfo[col]) { + await queryInterface.removeColumn(TABLE_NAME, col); + console.log(`[Migration] wms_camera.${col} 已移除`); + } + } + }, +}; diff --git a/database/migrations/20260718160000-split-camera-server-port.js b/database/migrations/20260718160000-split-camera-server-port.js new file mode 100644 index 0000000..e3f4b10 --- /dev/null +++ b/database/migrations/20260718160000-split-camera-server-port.js @@ -0,0 +1,89 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera_server'; + +/** + * 将 wms_camera_server.port 拆分为 public_port(远程/公网端口)和 internal_port(本地/内网端口)。 + * 原因:远程访问端口和本地访问端口通常不同(如 NAT 映射),需要分别存储。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + + // 1. 添加 public_port + if (!tableInfo.public_port) { + await queryInterface.addColumn(TABLE_NAME, 'public_port', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '远程/公网端口', + after: 'internal_ip', + }); + console.log('[Migration] wms_camera_server.public_port 已添加'); + } else { + console.log('[Migration] wms_camera_server.public_port 已存在,跳过'); + } + + // 2. 添加 internal_port + if (!tableInfo.internal_port) { + await queryInterface.addColumn(TABLE_NAME, 'internal_port', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '本地/内网端口', + after: 'public_port', + }); + console.log('[Migration] wms_camera_server.internal_port 已添加'); + } else { + console.log('[Migration] wms_camera_server.internal_port 已存在,跳过'); + } + + // 3. 将旧 port 数据迁移到 public_port 和 internal_port(保留旧值,后续可按需调整) + if (tableInfo.port) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET public_port = port, internal_port = port WHERE port IS NOT NULL` + ); + console.log('[Migration] wms_camera_server.port 数据已复制到 public_port 和 internal_port'); + + // 4. 删除旧 port 列 + await queryInterface.removeColumn(TABLE_NAME, 'port'); + console.log('[Migration] wms_camera_server.port 列已删除'); + } else { + console.log('[Migration] wms_camera_server.port 列不存在,跳过迁移和删除'); + } + }, + + down: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + + // 恢复 port 列 + if (!tableInfo.port) { + await queryInterface.addColumn(TABLE_NAME, 'port', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 80, + comment: '端口号', + after: 'internal_ip', + }); + console.log('[Migration] wms_camera_server.port 列已恢复'); + } + + // 将 public_port 数据回写到 port(优先使用 internal_port) + if (tableInfo.public_port || tableInfo.internal_port) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET port = COALESCE(internal_port, public_port) WHERE internal_port IS NOT NULL OR public_port IS NOT NULL` + ); + console.log('[Migration] port 数据已从 public_port/internal_port 回写'); + } + + // 删除 public_port + if (tableInfo.public_port) { + await queryInterface.removeColumn(TABLE_NAME, 'public_port'); + console.log('[Migration] wms_camera_server.public_port 列已删除'); + } + + // 删除 internal_port + if (tableInfo.internal_port) { + await queryInterface.removeColumn(TABLE_NAME, 'internal_port'); + console.log('[Migration] wms_camera_server.internal_port 列已删除'); + } + }, +}; diff --git a/database/migrations/20260718170000-fix-supervisor-cs-permissions.js b/database/migrations/20260718170000-fix-supervisor-cs-permissions.js new file mode 100644 index 0000000..4a11bca --- /dev/null +++ b/database/migrations/20260718170000-fix-supervisor-cs-permissions.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * 修复:客服组-主管 补充缺失权限,使其不低于下属(客服组-员工) + * + * 背景: + * 迁移 20260608033847 的设计意图是「客服组-主管」与「客服组-员工」权限一致。 + * 但后续新增权限时,主管遗漏了 5 个权限,导致员工(162个) > 主管(159个) 的越级现象。 + * + * 变更: + * - 客服组-主管 (id=28) 补充 [62, 63, 363, 396, 397] 共 5 个权限 + * - 补后:主管 164 个权限 > 员工 162 个权限(主管额外保留 309, 392) + * + * 补充权限明细: + * | ID | 路径 | 名称 | 类型 | + * |-----|-----------------------------------------------|-------------|-----------| + * | 62 | stock.saveWarehouseStock | 保存商品资料 | api | + * | 63 | stock.saveWarehouseStockBarcode | 修改商品条码 | api | + * | 363 | storeWarehouse.store.queryPrintQuantityLogs | 货主面单余额 | api | + * | 396 | shipperSigning | 外部仓库 | web_pages | + * | 397 | storeWarehouse.store.confirmSign | 签约确定 | api | + */ + +const TABLE = 'wms_role'; +const ROLE_ID = 28; + +const NEW_PERMISSIONS = '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,54,62,63,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,356,357,361,363,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384,386,387,388,389,390,391,392,396,397,416,417,418,420,421,422,424,425,426,427,428,429,430,431,432]'; + +const OLD_PERMISSIONS = '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,54,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,356,357,361,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384,386,387,388,389,390,391,392,416,417,418,420,421,422,424,425,426,427,428,429,430,431,432]'; + +/** + * @param {import('sequelize').QueryInterface} queryInterface + */ +module.exports.up = async queryInterface => { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() + WHERE id = :id AND is_system = 1`, + { replacements: { id: ROLE_ID, permissions: NEW_PERMISSIONS } } + ); + + const affected = result?.affectedRows ?? result?.rowCount ?? result?.changedRows ?? 0; + console.log(`[Migration] 客服组-主管(id=${ROLE_ID}) 权限补充:补充 5 个权限,实际更新 ${affected} 行`); +}; + +/** + * @param {import('sequelize').QueryInterface} queryInterface + */ +module.exports.down = async queryInterface => { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW() + WHERE id = :id AND is_system = 1`, + { replacements: { id: ROLE_ID, permissions: OLD_PERMISSIONS } } + ); + + const affected = result?.affectedRows ?? result?.rowCount ?? result?.changedRows ?? 0; + console.log(`[Migration] 客服组-主管(id=${ROLE_ID}) 权限回滚:实际回滚 ${affected} 行`); +}; diff --git a/database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js b/database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js new file mode 100644 index 0000000..305666e --- /dev/null +++ b/database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // 去掉 creator_id 列的 ZEROFILL 属性,避免零填充字符串导致查询匹配问题 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_receiving_detail MODIFY COLUMN creator_id bigint(20) unsigned NOT NULL' + ); + }, + + async down(queryInterface, Sequelize) { + // 回滚:恢复 ZEROFILL 属性 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_receiving_detail MODIFY COLUMN creator_id bigint(20) unsigned zerofill NOT NULL' + ); + }, +}; diff --git a/database/migrations/20260719120000-add-packing-flow-permission.js b/database/migrations/20260719120000-add-packing-flow-permission.js new file mode 100644 index 0000000..8a13f36 --- /dev/null +++ b/database/migrations/20260719120000-add-packing-flow-permission.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 在"数据"(id=16)菜单下新增"打包流水"页面权限 + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at, type) + VALUES (449, 'PackingFlow', '@/views/storage/packingflow/index', 'PackingFlow', '', '打包流水', '', 0, 0, 16, 1, 1, NOW(), NOW(), 'web_pages') + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id = 449 AND path = 'PackingFlow' + `); + }, +}; diff --git a/database/migrations/20260719130000-grant-packing-review-permissions.js b/database/migrations/20260719130000-grant-packing-review-permissions.js new file mode 100644 index 0000000..bf91711 --- /dev/null +++ b/database/migrations/20260719130000-grant-packing-review-permissions.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 给客服及以上角色追加 打包流水(449) 和 复核流水(450) 权限 + // 排除 permissions='*' 的角色(已有全部权限) + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', 449, '$', 450), + updated_at = NOW() + WHERE id IN (5, 8, 26, 27, 28, 29, 30, 31, 32, 33, 34) + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '449', '$') = 0 + `); + }, + + async down(queryInterface) { + // 回滚:从角色权限中移除 449 和 450 + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + JSON_REMOVE(permissions, JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '449'))), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '450')) + ), + updated_at = NOW() + WHERE id IN (5, 8, 26, 27, 28, 29, 30, 31, 32, 33, 34) + AND permissions IS NOT NULL + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '449', '$') = 1 + `); + }, +}; diff --git a/database/migrations/20260719150000-refactor-pack-task-packer-fields.js b/database/migrations/20260719150000-refactor-pack-task-packer-fields.js new file mode 100644 index 0000000..123beee --- /dev/null +++ b/database/migrations/20260719150000-refactor-pack-task-packer-fields.js @@ -0,0 +1,76 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task_packer'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + // 0. 清空已有数据(字段结构变更,emp 字段无法映射到新字段) + await queryInterface.bulkDelete(TABLE_NAME, {}); + + // 1. 删除旧索引 + await queryInterface.removeIndex(TABLE_NAME, 'uix_pack_task_emp'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_emp_id'); + + // 2. 删除旧字段 + await queryInterface.removeColumn(TABLE_NAME, 'emp_id'); + await queryInterface.removeColumn(TABLE_NAME, 'emp_no'); + await queryInterface.removeColumn(TABLE_NAME, 'emp_name'); + + // 3. 新增 account 字段 + await queryInterface.addColumn(TABLE_NAME, 'account_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '账号ID,关联 wms_account.id', + }); + await queryInterface.addColumn(TABLE_NAME, 'account_name', { + type: Sequelize.STRING(128), + allowNull: false, + comment: '账号姓名快照', + }); + + // 4. 建新索引 + await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id', 'account_id' ], { + name: 'uix_pack_task_account', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'account_id' ], { + name: 'idx_account_id', + }); + }, + + down: async (queryInterface, Sequelize) => { + // 1. 删除新索引 + await queryInterface.removeIndex(TABLE_NAME, 'uix_pack_task_account'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_account_id'); + + // 2. 删除新字段 + await queryInterface.removeColumn(TABLE_NAME, 'account_id'); + await queryInterface.removeColumn(TABLE_NAME, 'account_name'); + + // 3. 恢复旧字段 + await queryInterface.addColumn(TABLE_NAME, 'emp_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + comment: '打包人工号ID', + }); + await queryInterface.addColumn(TABLE_NAME, 'emp_no', { + type: Sequelize.STRING(64), + allowNull: false, + comment: '打包人工号', + }); + await queryInterface.addColumn(TABLE_NAME, 'emp_name', { + type: Sequelize.STRING(128), + allowNull: false, + comment: '打包人姓名', + }); + + // 4. 恢复旧索引 + await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id', 'emp_id' ], { + name: 'uix_pack_task_emp', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'emp_id' ], { + name: 'idx_emp_id', + }); + }, +}; diff --git a/database/migrations/20260720160000-add-print-qty-log-export-permissions.js b/database/migrations/20260720160000-add-print-qty-log-export-permissions.js new file mode 100644 index 0000000..b10acfe --- /dev/null +++ b/database/migrations/20260720160000-add-print-qty-log-export-permissions.js @@ -0,0 +1,202 @@ +'use strict'; + +/** + * 面单余额变更日志导出权限迁移。 + * + * 变更内容: + * 1. 新增 2 条 api 权限记录: + * - storeWarehouse.store.exportPrintQuantityLogs — 导出面单余额变更日志 + * - storeWarehouse.store.exportPrintQuantityLogsTaskProgress — 查询导出任务进度 + * 2. 将上述权限授权给 财务以上角色组: + * - 货主管理员 (id=5) + * - 经理 (id=8) + * (超级管理员 id=2/7 的 permissions='*' 无需更新) + * + * 幂等设计: + * - 先查后插(按 path + type 唯一性判断) + * - 角色权限更新使用 JSON 数组合并去重 + */ + +const TABLE_PERMISSION = 'wms_permission'; +const TABLE_ROLE = 'wms_role'; + +/** 需要授权的角色ID(财务以上:货主管理员 + 经理) */ +const TARGET_ROLE_IDS = [ 5, 8 ]; + +/** @type {{path: string, name: string, meta_title: string, type: string}[]} */ +const NEW_PERMISSIONS = [ + { + path: 'storeWarehouse.store.exportPrintQuantityLogs', + name: 'storeWarehouse.store.exportPrintQuantityLogs', + meta_title: '导出面单余额变更日志', + type: 'api', + }, + { + path: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress', + name: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress', + meta_title: '查询面单余额导出任务进度', + type: 'api', + }, +]; + +/** + * 获取角色当前权限 ID 数组。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @return {Promise} 权限ID数组 + */ +async function getRolePermissionIds(queryInterface, roleId) { + const [ rows ] = await queryInterface.sequelize.query( + `SELECT permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + if (!rows || rows.length === 0) return []; + + const raw = rows[0].permissions; + if (!raw || raw === '*') return []; + + try { + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) { + return parsed.map(Number).filter(n => Number.isFinite(n) && n > 0); + } + } catch (_) { + // ignore + } + + return []; +} + +/** + * 保存角色权限。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @param {number[]} permissionIds 权限ID数组 + * @return {Promise} + */ +async function saveRolePermissions(queryInterface, roleId, permissionIds) { + const unique = Array.from(new Set(permissionIds)).sort((a, b) => a - b); + const json = JSON.stringify(unique); + + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_ROLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :roleId`, + { replacements: { roleId, permissions: json } } + ); +} + +/** + * 正向迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.up = async queryInterface => { + // ─── 1. 插入新权限记录 ───────────────────────────────── + const insertedIds = []; + + for (const perm of NEW_PERMISSIONS) { + const [ existing ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type LIMIT 1`, + { replacements: { path: perm.path, type: perm.type } } + ); + + if (existing && existing.length > 0) { + console.log(`[Migration] 权限已存在: ${perm.path} (id=${existing[0].id})`); + insertedIds.push(Number(existing[0].id)); + continue; + } + + const [ result ] = await queryInterface.sequelize.query( + `INSERT INTO \`${TABLE_PERMISSION}\` (path, name, meta_title, type, status, created_at, update_at) + VALUES (:path, :name, :meta_title, :type, 1, NOW(), NOW())`, + { replacements: { path: perm.path, name: perm.name, meta_title: perm.meta_title, type: perm.type } } + ); + + const newId = Number(result); + insertedIds.push(newId); + console.log(`[Migration] 新增权限: ${perm.path} (id=${newId})`); + } + + // ─── 2. 授权给财务以上角色组 ────────────────────────── + for (const roleId of TARGET_ROLE_IDS) { + const [ roleRows ] = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + + if (!roleRows || roleRows.length === 0) { + console.log(`[Migration] 角色不存在: id=${roleId}`); + continue; + } + + const raw = roleRows[0].permissions; + // 跳过 permissions='*' 的角色(已拥有全部权限) + if (raw === '*') { + console.log(`[Migration] 角色 id=${roleId} 已有全部权限(*),跳过`); + continue; + } + + const currentIds = await getRolePermissionIds(queryInterface, roleId); + const newIds = insertedIds.filter(id => !currentIds.includes(id)); + + if (newIds.length === 0) { + console.log(`[Migration] 角色 id=${roleId} 已拥有目标权限,跳过`); + continue; + } + + const merged = [ ...currentIds, ...newIds ]; + await saveRolePermissions(queryInterface, roleId, merged); + console.log(`[Migration] 角色 id=${roleId} 授权成功,新增权限: [${newIds.join(', ')}]`); + } + + console.log( + '[Migration] 面单余额导出权限迁移完成:' + + `新增 ${NEW_PERMISSIONS.length} 条权限,授权 ${TARGET_ROLE_IDS.length} 个角色` + ); +}; + +/** + * 回滚迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.down = async queryInterface => { + // ─── 1. 从角色权限中移除新增的权限ID ───────────────── + const allPaths = NEW_PERMISSIONS.map(p => p.path); + + for (const roleId of TARGET_ROLE_IDS) { + const [ roleRows ] = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + + if (!roleRows || roleRows.length === 0) continue; + + const raw = roleRows[0].permissions; + if (!raw || raw === '*') continue; + + const currentIds = await getRolePermissionIds(queryInterface, roleId); + // 查询需要移除的权限ID + const [ permRows ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path IN (:paths) AND type = 'api'`, + { replacements: { paths: allPaths } } + ); + const removeIds = permRows.map(r => Number(r.id)); + const filtered = currentIds.filter(id => !removeIds.includes(id)); + + if (filtered.length !== currentIds.length) { + await saveRolePermissions(queryInterface, roleId, filtered); + console.log(`[Migration] 角色 id=${roleId} 已移除导出权限`); + } + } + + // ─── 2. 删除新增的权限记录 ─────────────────────────── + for (const perm of NEW_PERMISSIONS) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type`, + { replacements: { path: perm.path, type: perm.type } } + ); + console.log(`[Migration] 已删除权限: ${perm.path}`); + } + + console.log('[Migration] 面单余额导出权限回滚完成'); +}; diff --git a/database/migrations/20260724100000-add-is-enabled-to-wms-express-interface.js b/database/migrations/20260724100000-add-is-enabled-to-wms-express-interface.js new file mode 100644 index 0000000..08ade1d --- /dev/null +++ b/database/migrations/20260724100000-add-is-enabled-to-wms-express-interface.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_express_interface', 'is_enabled', { + type: Sequelize.TINYINT(1), + allowNull: true, + defaultValue: 1, + comment: '是否启用(1=启用,0=停用)', + after: 'is_hide_goods', + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_express_interface', 'is_enabled'); + }, +}; diff --git a/database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js b/database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js new file mode 100644 index 0000000..9eb4535 --- /dev/null +++ b/database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印台电脑表新增"是否作为录制电脑"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'is_recording', { + type: Sequelize.BOOLEAN, + allowNull: false, + defaultValue: false, + comment: '是否作为录制电脑,1-是,0-否', + }); + }, + + /** + * 回滚删除打印台电脑表的"是否作为录制电脑"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'is_recording'); + }, +}; diff --git a/database/migrations/20260725120000-unify-weight-fields-to-int-g.js b/database/migrations/20260725120000-unify-weight-fields-to-int-g.js new file mode 100644 index 0000000..5d3c35a --- /dev/null +++ b/database/migrations/20260725120000-unify-weight-fields-to-int-g.js @@ -0,0 +1,171 @@ +'use strict'; + +/** + * 统一所有重量字段为 INT 类型,单位统一为 g(克)。 + * + * 说明:原字段注释/类型写错(注释标 kg 实际存的是 g), + * 数据本身已为克,迁移只做类型转换 + 注释修正,不做数值缩放。 + * + * 涉及表/字段: + * wms_location_space : max_weight, current_weight (DECIMAL → INT) + * wms_order_delivery_100000* : items_weight (DECIMAL → INT) + * wms_order_express : weighing_weight (DECIMAL(10,3) → INT) + * wms_package_material : weight (DECIMAL(10,3) → INT) + * wms_package_material_item_relation: weight (DECIMAL → INT) + * wms_receiving_detail : box_weight (DECIMAL → INT) + * wms_receiving_detail : weight (已为INT, 仅更新注释) + * wms_stock_store : gross_weight, net_weight (DECIMAL → INT) + * wms_stock_warehouse : gross_weight, net_weight (DECIMAL → INT) + * wms_stock_warehouse : box_gross_weight, box_net_weight (已为INT, 仅更新注释) + */ + +module.exports = { + async up(queryInterface, Sequelize) { + // ===================== wms_location_space ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN max_weight INT(11) DEFAULT 0 COMMENT '最大承重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN current_weight INT(11) DEFAULT 0 COMMENT '当前重量(g)'" + ); + + // ===================== wms_order_delivery 分表 ===================== + const orderDeliveryTables = [ + 'wms_order_delivery_100000', + 'wms_order_delivery_100000_dispatch', + 'wms_order_delivery_100000_history', + 'wms_order_delivery_100000_outsourced', + 'wms_order_delivery_1000028', + 'wms_order_delivery_1000028_dispatch', + 'wms_order_delivery_1000028_history', + 'wms_order_delivery_1000028_outsourced', + ]; + + for (const table of orderDeliveryTables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY COLUMN items_weight INT(11) NOT NULL DEFAULT 0 COMMENT '总重量(g)'` + ); + } + + // ===================== wms_order_express ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_order_express MODIFY COLUMN weighing_weight INT(11) DEFAULT 0 COMMENT '称重重量(g)'" + ); + + // ===================== wms_package_material ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)'" + ); + + // ===================== wms_package_material_item_relation ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material_item_relation MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)快照'" + ); + + // ===================== wms_receiving_detail ===================== + // weight: 已为 INT(g),仅补注释 + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)'" + ); + // box_weight: DECIMAL → INT(g) + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN box_weight INT(11) NOT NULL DEFAULT 0 COMMENT '箱重量(g)'" + ); + + // ===================== wms_stock_store ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN gross_weight INT(11) DEFAULT 0 COMMENT '毛重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN net_weight INT(11) DEFAULT 0 COMMENT '净重(g)'" + ); + + // ===================== wms_stock_warehouse ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN gross_weight INT(11) DEFAULT 0 COMMENT '毛重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN net_weight INT(11) DEFAULT 0 COMMENT '净重(g)'" + ); + // box_gross_weight / box_net_weight: 已为INT, 仅补注释 + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_gross_weight INT(11) DEFAULT 0 COMMENT '箱毛重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_net_weight INT(11) DEFAULT 0 COMMENT '箱净重(g)'" + ); + }, + + async down(queryInterface, Sequelize) { + // ===================== wms_location_space ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN max_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '最大承重(kg)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN current_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '当前重量(kg)'" + ); + + // ===================== wms_order_delivery 分表 ===================== + const orderDeliveryTables = [ + 'wms_order_delivery_100000', + 'wms_order_delivery_100000_dispatch', + 'wms_order_delivery_100000_history', + 'wms_order_delivery_100000_outsourced', + 'wms_order_delivery_1000028', + 'wms_order_delivery_1000028_dispatch', + 'wms_order_delivery_1000028_history', + 'wms_order_delivery_1000028_outsourced', + ]; + + for (const table of orderDeliveryTables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY COLUMN items_weight DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)'` + ); + } + + // ===================== wms_order_express ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_order_express MODIFY COLUMN weighing_weight DECIMAL(10,3) DEFAULT 0.000 COMMENT '称重重量(kg)'" + ); + + // ===================== wms_package_material ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material MODIFY COLUMN weight DECIMAL(10,3) DEFAULT 0.000 COMMENT '重量(kg)'" + ); + + // ===================== wms_package_material_item_relation ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material_item_relation MODIFY COLUMN weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '重量(kg)快照'" + ); + + // ===================== wms_receiving_detail ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量g'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN box_weight DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '箱重量(kg)'" + ); + + // ===================== wms_stock_store ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN gross_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '毛重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN net_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '净重'" + ); + + // ===================== wms_stock_warehouse ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN gross_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '毛重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN net_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '净重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_gross_weight INT(11) DEFAULT 0 COMMENT '箱毛重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_net_weight INT(11) DEFAULT 0 COMMENT '箱净重'" + ); + }, +}; diff --git a/database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js b/database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js new file mode 100644 index 0000000..29469be --- /dev/null +++ b/database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印台电脑表新增软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'deleted_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }); + }, + + /** + * 回滚删除打印台电脑表的软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'deleted_at'); + }, +}; diff --git a/database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js b/database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js new file mode 100644 index 0000000..2fa89e0 --- /dev/null +++ b/database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印台表新增软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_stations', 'deleted_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }); + }, + + /** + * 回滚删除打印台表的软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_stations', 'deleted_at'); + }, +}; diff --git a/database/migrations/20260725150000-add-print-computer-permissions.js b/database/migrations/20260725150000-add-print-computer-permissions.js new file mode 100644 index 0000000..3fb6c96 --- /dev/null +++ b/database/migrations/20260725150000-add-print-computer-permissions.js @@ -0,0 +1,86 @@ +'use strict'; + +module.exports = { + /** + * 新增打印电脑模块 API 权限,并授权客服主管及以上角色。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const now = new Date(); + + // 1. 插入 3 条 API 权限 + const permissions = [ + { path: 'print_computer.list', name: '打印电脑-列表', type: 'api', status: 1, created_at: now, update_at: now }, + { path: 'print_computer.update', name: '打印电脑-更新', type: 'api', status: 1, created_at: now, update_at: now }, + { path: 'print_computer.delete', name: '打印电脑-删除', type: 'api', status: 1, created_at: now, update_at: now }, + ]; + + await queryInterface.bulkInsert('wms_permission', permissions); + + // 2. 查询刚插入的权限 ID + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT id FROM wms_permission WHERE path IN (\'print_computer.list\', \'print_computer.update\', \'print_computer.delete\') ORDER BY id' + ); + const ids = rows.map(r => r.id); + if (ids.length !== 3) { + throw new Error(`权限插入异常:期望 3 条,实际 ${ids.length} 条`); + } + + // 3. 授权客服主管及以上角色(排除 permissions='*' 的超级管理员角色) + const roleIds = [ 2, 5, 7, 8, 22, 26, 28, 29 ]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 0 + `); + } + }, + + /** + * 回滚:删除权限记录并从角色权限中移除。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const paths = [ 'print_computer.list', 'print_computer.update', 'print_computer.delete' ]; + + // 1. 查询权限 ID + const [ rows ] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')` + ); + const ids = rows.map(r => r.id); + + // 2. 从角色权限中移除 + const roleIds = [ 2, 5, 7, 8, 22, 26, 28, 29 ]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '${permId}')) + ), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 1 + `); + } + + // 3. 删除权限记录 + await queryInterface.bulkDelete('wms_permission', { + path: { [Sequelize.Op.in]: paths }, + }); + }, +}; diff --git a/database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js b/database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js new file mode 100644 index 0000000..dd12a85 --- /dev/null +++ b/database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js @@ -0,0 +1,42 @@ +'use strict'; + +module.exports = { + /** + * 为打印电脑表新增录制相关字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_size_value', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }); + await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', { + type: Sequelize.STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }); + await queryInterface.addColumn('wms_print_computer', 'remote_play_url', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '远程播放地址', + }); + }, + + /** + * 回滚删除录制相关字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'remote_play_url'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_value'); + }, +}; diff --git a/database/migrations/20260725170000-add-recording-permissions.js b/database/migrations/20260725170000-add-recording-permissions.js new file mode 100644 index 0000000..384bdad --- /dev/null +++ b/database/migrations/20260725170000-add-recording-permissions.js @@ -0,0 +1,82 @@ +'use strict'; + +module.exports = { + /** + * 新增打印电脑录制相关 API 权限,并授权客服主管及以上角色。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const now = new Date(); + + // 1. 插入 2 条 API 权限 + const permissions = [ + { path: 'print_computer.setRecording', name: '打印电脑-设置录制', type: 'api', status: 1, created_at: now, update_at: now }, + { path: 'print_computer.cancelRecording', name: '打印电脑-取消录制', type: 'api', status: 1, created_at: now, update_at: now }, + ]; + + await queryInterface.bulkInsert('wms_permission', permissions); + + // 2. 查询刚插入的权限 ID + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT id FROM wms_permission WHERE path IN (\'print_computer.setRecording\', \'print_computer.cancelRecording\') ORDER BY id' + ); + const ids = rows.map(r => r.id); + if (ids.length !== 2) { + throw new Error(`权限插入异常:期望 2 条,实际 ${ids.length} 条`); + } + + // 3. 授权客服主管及以上角色 + const roleIds = [ 2, 5, 7, 8, 22, 26, 28, 29 ]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 0 + `); + } + }, + + /** + * 回滚:删除权限记录并从角色权限中移除。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const paths = [ 'print_computer.setRecording', 'print_computer.cancelRecording' ]; + + const [ rows ] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')` + ); + const ids = rows.map(r => r.id); + + const roleIds = [ 2, 5, 7, 8, 22, 26, 28, 29 ]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '${permId}')) + ), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 1 + `); + } + + await queryInterface.bulkDelete('wms_permission', { + path: { [Sequelize.Op.in]: paths }, + }); + }, +}; diff --git a/database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js b/database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js new file mode 100644 index 0000000..e20fdd0 --- /dev/null +++ b/database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印电脑表新增录制目录字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_directory', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径,如 D:/record', + }); + }, + + /** + * 回滚删除录制目录字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'recording_directory'); + }, +}; diff --git a/database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js b/database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js new file mode 100644 index 0000000..df61b10 --- /dev/null +++ b/database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = { + /** + * 为打包任务表新增"商品数量"和"商品种类数"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_pack_task', 'item_quantity', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品总数量', + }); + + await queryInterface.addColumn('wms_pack_task', 'sku_count', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品种类数(SKU数)', + }); + }, + + /** + * 回滚删除打包任务表的"商品数量"和"商品种类数"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_pack_task', 'sku_count'); + await queryInterface.removeColumn('wms_pack_task', 'item_quantity'); + }, +}; diff --git a/database/migrations/20260726120000-update-pack-task-video-status-enum.js b/database/migrations/20260726120000-update-pack-task-video-status-enum.js new file mode 100644 index 0000000..087eaa6 --- /dev/null +++ b/database/migrations/20260726120000-update-pack-task-video-status-enum.js @@ -0,0 +1,59 @@ +'use strict'; + +/** + * wms_pack_task_video.status 字段改为 ENUM 类型。 + * + * 变更前:TINYINT(无明确语义) + * 变更后:ENUM('created', 'completed', 'failed') + * - created = 已创建 + * - completed = 已完成 + * - failed = 失败 + * + * 现有数据映射:status=1 → 'created' + */ + +module.exports = { + async up(queryInterface, Sequelize) { + // 新增临时列 + await queryInterface.sequelize.query( + "ALTER TABLE wms_pack_task_video ADD COLUMN status_new ENUM('created','completed','failed') NOT NULL DEFAULT 'created' COMMENT '状态:已创建/已完成/失败' AFTER status" + ); + + // 迁移现有数据:TINYINT 1 → 'created' + await queryInterface.sequelize.query( + "UPDATE wms_pack_task_video SET status_new = 'created' WHERE status = 1" + ); + + // 删除旧列 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_pack_task_video DROP COLUMN status' + ); + + // 新列改名为 status + await queryInterface.sequelize.query( + "ALTER TABLE wms_pack_task_video CHANGE COLUMN status_new status ENUM('created','completed','failed') NOT NULL DEFAULT 'created' COMMENT '状态:已创建/已完成/失败'" + ); + }, + + async down(queryInterface, Sequelize) { + // 新增临时 TINYINT 列 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_pack_task_video ADD COLUMN status_new TINYINT NOT NULL DEFAULT 1 AFTER status' + ); + + // 回退数据:'created' → 1 + await queryInterface.sequelize.query( + "UPDATE wms_pack_task_video SET status_new = 1 WHERE status = 'created'" + ); + + // 删除 ENUM 列 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_pack_task_video DROP COLUMN status' + ); + + // 改名为 status + await queryInterface.sequelize.query( + 'ALTER TABLE wms_pack_task_video CHANGE COLUMN status_new status TINYINT NOT NULL DEFAULT 1' + ); + }, +}; diff --git a/database/migrations/20260726130000-add-recording-status-pack-task-video.js b/database/migrations/20260726130000-add-recording-status-pack-task-video.js new file mode 100644 index 0000000..4bf006d --- /dev/null +++ b/database/migrations/20260726130000-add-recording-status-pack-task-video.js @@ -0,0 +1,26 @@ +'use strict'; + +/** + * wms_pack_task_video.status 增加「录制中」状态。 + * + * 变更前:ENUM('created','completed','failed') + * 变更后:ENUM('created','recording','completed','failed') + * - created = 已创建 + * - recording = 录制中(新增) + * - completed = 已完成 + * - failed = 失败 + */ + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + "ALTER TABLE wms_pack_task_video MODIFY COLUMN status ENUM('created','recording','completed','failed') NOT NULL DEFAULT 'created' COMMENT '状态:已创建/录制中/已完成/失败'" + ); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + "ALTER TABLE wms_pack_task_video MODIFY COLUMN status ENUM('created','completed','failed') NOT NULL DEFAULT 'created' COMMENT '状态:已创建/已完成/失败'" + ); + }, +}; diff --git a/database/migrations/20260728000000-remove-remote-play-url-from-wms-print-computer.js b/database/migrations/20260728000000-remove-remote-play-url-from-wms-print-computer.js new file mode 100644 index 0000000..89e21fd --- /dev/null +++ b/database/migrations/20260728000000-remove-remote-play-url-from-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 移除打印电脑表的 remote_play_url 字段(未被使用)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'remote_play_url'); + }, + + /** + * 回滚:恢复 remote_play_url 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'remote_play_url', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '远程播放地址', + }); + }, +}; diff --git a/database/migrations/20260728100000-remove-recording-config-fields-from-wms-print-computer.js b/database/migrations/20260728100000-remove-recording-config-fields-from-wms-print-computer.js new file mode 100644 index 0000000..8e3c3cd --- /dev/null +++ b/database/migrations/20260728100000-remove-recording-config-fields-from-wms-print-computer.js @@ -0,0 +1,43 @@ +'use strict'; + +module.exports = { + /** + * 移除打印电脑表的录制配置字段(recording_size_value / recording_size_unit / recording_directory), + * 这些字段不再由 WMS 侧管理。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'recording_directory'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_value'); + }, + + /** + * 回滚:恢复录制配置字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_size_value', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }); + await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', { + type: Sequelize.STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }); + await queryInterface.addColumn('wms_print_computer', 'recording_directory', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径', + }); + }, +}; diff --git a/database/migrations/20260728110000-restore-recording-directory-to-wms-print-computer.js b/database/migrations/20260728110000-restore-recording-directory-to-wms-print-computer.js new file mode 100644 index 0000000..40133b5 --- /dev/null +++ b/database/migrations/20260728110000-restore-recording-directory-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 恢复 wms_print_computer 的 recording_directory 字段(录制目录路径)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_directory', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径', + }); + }, + + /** + * 回滚:移除 recording_directory 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'recording_directory'); + }, +}; diff --git a/database/migrations/20260728120000-restore-recording-size-fields-to-wms-print-computer.js b/database/migrations/20260728120000-restore-recording-size-fields-to-wms-print-computer.js new file mode 100644 index 0000000..cbe848f --- /dev/null +++ b/database/migrations/20260728120000-restore-recording-size-fields-to-wms-print-computer.js @@ -0,0 +1,35 @@ +'use strict'; + +module.exports = { + /** + * 恢复 wms_print_computer 的 recording_size_value 和 recording_size_unit 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_size_value', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }); + await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', { + type: Sequelize.STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }); + }, + + /** + * 回滚:移除 recording_size_value 和 recording_size_unit 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_value'); + }, +}; diff --git a/database/migrations/20260729140000-add-waybill-list-indexes.js b/database/migrations/20260729140000-add-waybill-list-indexes.js new file mode 100644 index 0000000..049fad5 --- /dev/null +++ b/database/migrations/20260729140000-add-waybill-list-indexes.js @@ -0,0 +1,84 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +module.exports = { + /** + * 执行迁移:为运单表新增运单列表高频查询索引(幂等)。 + * + * 新增索引: + * - idx_warehouse_id_status:仓库+状态筛选(最常见查询组合) + * - idx_logistics_code:物流公司筛选 + * - idx_logistics_interface_id:快递接口ID筛选 + * - idx_warehouse_id_create_at:仓库+时间范围排序分页 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + + if (!indexNameSet.has('idx_warehouse_id_status')) { + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_id_status', + fields: [ 'warehouse_id', 'status' ], + }); + } + + if (!indexNameSet.has('idx_logistics_code')) { + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_logistics_code', + fields: [ 'logistics_code' ], + }); + } + + if (!indexNameSet.has('idx_logistics_interface_id')) { + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_logistics_interface_id', + fields: [ 'logistics_interface_id' ], + }); + } + + if (!indexNameSet.has('idx_warehouse_id_create_at')) { + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_id_create_at', + fields: [ 'warehouse_id', 'create_at' ], + }); + } + }, + + /** + * 回滚迁移:移除运单列表查询索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + + if (indexNameSet.has('idx_warehouse_id_status')) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id_status'); + } + if (indexNameSet.has('idx_logistics_code')) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_logistics_code'); + } + if (indexNameSet.has('idx_logistics_interface_id')) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_logistics_interface_id'); + } + if (indexNameSet.has('idx_warehouse_id_create_at')) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id_create_at'); + } + }, +}; diff --git a/database/migrations/20260730000000-add-camera-username-password.js b/database/migrations/20260730000000-add-camera-username-password.js new file mode 100644 index 0000000..2ba43b6 --- /dev/null +++ b/database/migrations/20260730000000-add-camera-username-password.js @@ -0,0 +1,43 @@ +'use strict'; + +const TABLE_NAME = 'wms_camera'; + +/** + * 新增摄像头认证字段:username(用户名)、password(密码)。 + * 用于保存摄像头登录认证信息。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = [ + { + name: 'username', + def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头登录用户名', after: 'stream_type' }, + }, + { + name: 'password', + def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头登录密码', after: 'username' }, + }, + ]; + + for (const col of columns) { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (!tableInfo[col.name]) { + await queryInterface.addColumn(TABLE_NAME, col.name, col.def); + console.log(`[Migration] wms_camera.${col.name} 已添加`); + } else { + console.log(`[Migration] wms_camera.${col.name} 已存在,跳过`); + } + } + }, + + down: async queryInterface => { + const columns = [ 'password', 'username' ]; + for (const col of columns) { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (tableInfo[col]) { + await queryInterface.removeColumn(TABLE_NAME, col); + console.log(`[Migration] wms_camera.${col} 已回滚删除`); + } + } + }, +}; diff --git a/database/migrations/20260730000000-add-store-id-to-wms-order-express.js b/database/migrations/20260730000000-add-store-id-to-wms-order-express.js new file mode 100644 index 0000000..b2cab63 --- /dev/null +++ b/database/migrations/20260730000000-add-store-id-to-wms-order-express.js @@ -0,0 +1,49 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; +const COLUMN_NAME = 'store_id'; + +/** + * 获取指定表的列名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 列名集合。 + */ +const getColumnNameSet = async (queryInterface, tableName) => { + const columns = await queryInterface.describeTable(tableName); + return new Set(Object.keys(columns)); +}; + +module.exports = { + /** + * 执行迁移:为运单表新增货主ID字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingColumns = await getColumnNameSet(queryInterface, TABLE_NAME); + + if (!existingColumns.has(COLUMN_NAME)) { + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }); + } + }, + + /** + * 回滚迁移:移除运单表的货主ID字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const existingColumns = await getColumnNameSet(queryInterface, TABLE_NAME); + + if (existingColumns.has(COLUMN_NAME)) { + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + } + }, +}; diff --git a/database/migrations/20260730160000-backfill-order-express-logistics-code-name.js b/database/migrations/20260730160000-backfill-order-express-logistics-code-name.js new file mode 100644 index 0000000..9d6ccdd --- /dev/null +++ b/database/migrations/20260730160000-backfill-order-express-logistics-code-name.js @@ -0,0 +1,83 @@ +'use strict'; + +/** + * 回填 wms_order_express 表的 logistics_code 和 logistics_name。 + * + * 背景:取号成功后写入 wms_order_express 时引用了不存在的字段 + * listByWarehousePlatformCode.logistics_code / logistics_name, + * 导致 6w+ 条记录该两字段为空。 + * + * 本迁移通过 logistics_interface_id 关联 wms_express_interface.sys_express_code, + * 再通过 wms_express.name 获取快递名称,完成数据回填。 + */ +module.exports = { + async up(queryInterface) { + const [ results ] = await queryInterface.sequelize.query(` + SELECT COUNT(*) AS cnt + FROM wms_order_express oe + JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id + WHERE (oe.logistics_code IS NULL OR oe.logistics_code = '') + AND ei.sys_express_code IS NOT NULL + AND ei.sys_express_code != '' + `); + + const affectedCount = (results && results[0] && results[0].cnt) || 0; + console.log(`[backfill-order-express-logistics] 预计回填 ${affectedCount} 条记录`); + + if (affectedCount === 0) { + console.log('[backfill-order-express-logistics] 无需回填,跳过'); + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_order_express oe + JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id + LEFT JOIN wms_express e ON e.code = ei.sys_express_code + SET + oe.logistics_code = ei.sys_express_code, + oe.logistics_name = COALESCE(e.name, ei.sys_express_code) + WHERE (oe.logistics_code IS NULL OR oe.logistics_code = '') + AND ei.sys_express_code IS NOT NULL + AND ei.sys_express_code != '' + `); + + console.log(`[backfill-order-express-logistics] 成功回填 ${affectedCount} 条记录`); + }, + + async down(queryInterface) { + // 回滚:仅清空通过本迁移回填的记录(条件:logistics_code 等于对应 sys_express_code) + const [ results ] = await queryInterface.sequelize.query(` + SELECT COUNT(*) AS cnt + FROM wms_order_express oe + JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id + WHERE oe.logistics_code = ei.sys_express_code + AND oe.logistics_code IS NOT NULL + AND oe.logistics_code != '' + AND ei.sys_express_code IS NOT NULL + AND ei.sys_express_code != '' + `); + + const rollbackCount = (results && results[0] && results[0].cnt) || 0; + console.log(`[backfill-order-express-logistics] 预计回滚 ${rollbackCount} 条记录`); + + if (rollbackCount === 0) { + console.log('[backfill-order-express-logistics] 无需回滚,跳过'); + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_order_express oe + JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id + SET + oe.logistics_code = '', + oe.logistics_name = '' + WHERE oe.logistics_code = ei.sys_express_code + AND oe.logistics_code IS NOT NULL + AND oe.logistics_code != '' + AND ei.sys_express_code IS NOT NULL + AND ei.sys_express_code != '' + `); + + console.log(`[backfill-order-express-logistics] 成功回滚 ${rollbackCount} 条记录`); + }, +}; diff --git a/database/migrations/20260730170000-add-delivery-order-code-to-wms-order-express.js b/database/migrations/20260730170000-add-delivery-order-code-to-wms-order-express.js new file mode 100644 index 0000000..8514419 --- /dev/null +++ b/database/migrations/20260730170000-add-delivery-order-code-to-wms-order-express.js @@ -0,0 +1,30 @@ +'use strict'; + +/** + * 为 wms_order_express 表新增 delivery_order_code 和 source_order_codes 字段。 + * + * 用途:运单记录需要关联对应的发货单号和原始订单号,便于运单追溯和导出。 + * 字段格式参考 wms_order_delivery 表的同名字段。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_order_express', 'delivery_order_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '发货单号', + after: 'warehouse_id', + }); + + await queryInterface.addColumn('wms_order_express', 'source_order_codes', { + type: Sequelize.TEXT, + allowNull: true, + comment: '来源订单号集合', + after: 'delivery_order_code', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_order_express', 'delivery_order_code'); + await queryInterface.removeColumn('wms_order_express', 'source_order_codes'); + }, +}; diff --git a/database/migrations/20260730200000-backfill-wms-order-express-store-id.js b/database/migrations/20260730200000-backfill-wms-order-express-store-id.js new file mode 100644 index 0000000..88df70b --- /dev/null +++ b/database/migrations/20260730200000-backfill-wms-order-express-store-id.js @@ -0,0 +1,72 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; + +/** + * 回填 wms_order_express.store_id。 + * 从对应的仓库分表(current → history → dispatch)中获取 store_id。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +async function backfill(queryInterface) { + // 获取所有不同的 warehouse_id + const [ warehouses ] = await queryInterface.sequelize.query( + `SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE store_id IS NULL AND warehouse_id IS NOT NULL` + ); + + if (!warehouses || warehouses.length === 0) { + return; + } + + for (const row of warehouses) { + const warehouseId = row.warehouse_id; + const tableTypes = [ + `wms_order_delivery_${warehouseId}`, // current(配送表 / 待处理表) + `wms_order_delivery_${warehouseId}_history`, // history + `wms_order_delivery_${warehouseId}_dispatch`, // dispatch + ]; + + for (const deliveryTable of tableTypes) { + try { + const [ result ] = await queryInterface.sequelize.query(` + UPDATE ${TABLE_NAME} e + INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id + SET e.store_id = d.store_id + WHERE e.store_id IS NULL AND d.store_id IS NOT NULL + `); + console.log(` warehouse=${warehouseId} table=${deliveryTable} rows=${result.info || result}`); + } catch (err) { + // 表可能不存在,跳过 + if (err && err.parent && err.parent.code === 'ER_NO_SUCH_TABLE') { + continue; + } + console.warn(` warehouse=${warehouseId} table=${deliveryTable} error=${err.message}`); + } + } + } +} + +module.exports = { + /** + * 执行迁移:回填 store_id。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + await backfill(queryInterface); + }, + + /** + * 回滚迁移:将 store_id 置为 NULL。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET store_id = NULL` + ); + }, +}; diff --git a/database/migrations/20260730210000-backfill-order-express-delivery-fields.js b/database/migrations/20260730210000-backfill-order-express-delivery-fields.js new file mode 100644 index 0000000..46bff59 --- /dev/null +++ b/database/migrations/20260730210000-backfill-order-express-delivery-fields.js @@ -0,0 +1,60 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; + +/** + * 回填 wms_order_express 的 delivery_order_code 和 source_order_codes。 + * 从对应的仓库分表(current → history → dispatch)中获取。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +async function backfill(queryInterface) { + const [ warehouses ] = await queryInterface.sequelize.query( + `SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE delivery_order_code IS NULL AND warehouse_id IS NOT NULL` + ); + + if (!warehouses || warehouses.length === 0) { + return; + } + + for (const row of warehouses) { + const warehouseId = row.warehouse_id; + const tableTypes = [ + `wms_order_delivery_${warehouseId}`, + `wms_order_delivery_${warehouseId}_history`, + `wms_order_delivery_${warehouseId}_dispatch`, + ]; + + for (const deliveryTable of tableTypes) { + try { + const [ result ] = await queryInterface.sequelize.query(` + UPDATE ${TABLE_NAME} e + INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id + SET e.delivery_order_code = COALESCE(e.delivery_order_code, d.delivery_order_code), + e.source_order_codes = COALESCE(e.source_order_codes, d.source_order_codes) + WHERE (e.delivery_order_code IS NULL OR e.source_order_codes IS NULL) + AND (d.delivery_order_code IS NOT NULL OR d.source_order_codes IS NOT NULL) + `); + console.log(` warehouse=${warehouseId} table=${deliveryTable} rows=${result.info || result}`); + } catch (err) { + if (err && err.parent && err.parent.code === 'ER_NO_SUCH_TABLE') { + continue; + } + console.warn(` warehouse=${warehouseId} table=${deliveryTable} error=${err.message}`); + } + } + } +} + +module.exports = { + async up(queryInterface, Sequelize) { + await backfill(queryInterface); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET delivery_order_code = NULL, source_order_codes = NULL` + ); + }, +}; diff --git a/database/migrations/20260801120000-add-apiApp-permissions.js b/database/migrations/20260801120000-add-apiApp-permissions.js new file mode 100644 index 0000000..486d856 --- /dev/null +++ b/database/migrations/20260801120000-add-apiApp-permissions.js @@ -0,0 +1,80 @@ +'use strict'; + +/** + * 为 apiApp 仓库 API 应用管理模块创建权限并授权给客服组-主管及以上角色。 + * + * 固定 ID(开发库 & 生产库 wms_permission 当前 max_id 均为 463): + * 464 — 父级菜单 "API应用管理" + * 465 — apiApp.list + * 466 — apiApp.detail + * 467 — apiApp.create + * 468 — apiApp.update + * 469 — apiApp.delete + * 470 — apiApp.regenerateSecret + * + * 授权角色(permissions 不为 "*" 的 主管/经理 级角色): + * 8 — 经理 + * 26 — 仓库组-主管 + * 28 — 客服组-主管 + * 29 — 生产组-主管 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 插入父级权限 (type=web_pages, sort=1, status=1) ── + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (464, 'apiApp', NULL, 'API应用管理', NULL, 'API应用管理', NULL, 0, 0, NULL, 'web_pages', 1, 1, NOW(), NOW()) + `); + + // ── 2. 插入 6 个接口权限 ── + const methods = [ + [ 465, 'apiApp.list' ], + [ 466, 'apiApp.detail' ], + [ 467, 'apiApp.create' ], + [ 468, 'apiApp.update' ], + [ 469, 'apiApp.delete' ], + [ 470, 'apiApp.regenerateSecret' ], + ]; + + for (const [ id, method ] of methods) { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${method}', NULL, 0, 0, 464, 'api', 0, 1, NOW(), NOW()) + `); + } + + // ── 3. 给 客服组-主管及以上角色 追加新权限 ID ── + // 只更新 permissions 为显式列表(非 "*")的角色 + const newIdSuffix = ', 465, 466, 467, 468, 469, 470'; + + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]') + WHERE id IN (8, 26, 28, 29) + AND permissions != '*' + AND permissions IS NOT NULL + AND LENGTH(permissions) > 2 + `); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + // ── 1. 从角色权限中移除新增的 ID ── + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = REPLACE(permissions, ', 465, 466, 467, 468, 469, 470', '') + WHERE id IN (8, 26, 28, 29) + `); + + // ── 2. 删除 6 个接口权限 ── + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id IN (465, 466, 467, 468, 469, 470)' + ); + + // ── 3. 删除父级权限 ── + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id = 464' + ); + }, +}; diff --git a/database/migrations/20260803120000-create-inbox-message.js b/database/migrations/20260803120000-create-inbox-message.js new file mode 100644 index 0000000..1e6a8d3 --- /dev/null +++ b/database/migrations/20260803120000-create-inbox-message.js @@ -0,0 +1,197 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_message'; + +module.exports = { + /** + * 创建站内信消息表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + ext_id: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '外部唯一消息主键(IM msgId / API requestId 等),用于幂等去重', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + direction: { + type: Sequelize.STRING(10), + allowNull: false, + defaultValue: 'inbound', + comment: '消息方向:inbound=外部→WMS收件 / outbound=WMS→外部回信', + }, + parent_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联消息ID(回信时指向原消息,形成对话链)', + }, + source_type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '来源类型:im / api', + }, + source_extra: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '来源附加信息(IM 平台 / API app_id)', + }, + target_type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '目标类型:im / api', + }, + target_channel: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '目标渠道(仅供参考,出站路由由外部系统负责)', + }, + group_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群名称(外部传入)', + }, + user_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户名称(外部传入)', + }, + group_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部群ID', + }, + user_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部用户ID', + }, + content: { + type: Sequelize.TEXT, + allowNull: true, + comment: '消息正文/摘要,用于列表展示和关键词搜索', + }, + ext_data: { + type: Sequelize.JSON, + allowNull: true, + comment: '外部透传数据,外部传入任意JSON,WMS不解析,回信时原样返回', + }, + flags: { + type: Sequelize.JSON, + allowNull: true, + comment: '处理标记,外部传入控制WMS处理行为', + }, + push_status: { + type: Sequelize.TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '推送状态:0=待推送 1=推送中 2=已送达 3=失败', + }, + push_started_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '开始推送时间(僵尸检测:超5分钟仍为1则重置为0)', + }, + retry_count: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '已重试次数', + }, + push_response: { + type: Sequelize.JSON, + allowNull: true, + comment: '目标响应(http_status, body, error)', + }, + pushed_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '推送完成时间', + }, + work_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联工单ID(预留)', + }, + work_order_no: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '工单号(预留)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 唯一索引 — 外部幂等去重 + await queryInterface.addIndex(TABLE_NAME, [ 'ext_id' ], { + unique: true, + name: 'uk_ext_id', + }); + + // 仓库+状态查询 + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'push_status' ], { + name: 'idx_warehouse_status', + }); + + // 仓库+方向+时间 + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'direction', 'created_at' ], { + name: 'idx_warehouse_direction', + }); + + // 对话链查询 + await queryInterface.addIndex(TABLE_NAME, [ 'parent_id' ], { + name: 'idx_parent', + }); + + // 时间范围查询 + await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], { + name: 'idx_created_at', + }); + }, + + /** + * 回滚站内信消息表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 迁移回滚结果。 + */ + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260803150000-create-wms-store-express-binding-policy.js b/database/migrations/20260803150000-create-wms-store-express-binding-policy.js new file mode 100644 index 0000000..0fe917b --- /dev/null +++ b/database/migrations/20260803150000-create-wms-store-express-binding-policy.js @@ -0,0 +1,129 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + /** + * 创建订单自定义店铺-快递绑定策略表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID,策略所属仓库', + }, + custom_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '自定义策略名称,便于人工识别', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID(stores.id),NULL=适用所有货主', + }, + shop_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '店铺ID(shops.id),NULL=适用所有店铺', + }, + express_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '绑定的快递编码(wms_express.code)', + }, + priority: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先匹配', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用,1=启用', + }, + match_condition: { + type: Sequelize.JSON, + allowNull: true, + comment: '附加匹配条件(JSON):platform_codes/provinces/cities/item_codes/min_weight_g/max_weight_g/min_amount/max_amount', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注说明', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人账户ID(accounts.id)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '订单自定义店铺-快递绑定策略表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + // 索引:按仓库查询启用策略 + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_enabled', + fields: [ 'warehouse_id', 'is_enabled', 'deleted_at' ], + }); + + // 索引:按仓库+货主+店铺精确匹配 + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_store_shop', + fields: [ 'warehouse_id', 'store_id', 'shop_id', 'deleted_at' ], + }); + + // 索引:按仓库+快递反查绑定店铺 + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_express', + fields: [ 'warehouse_id', 'express_code', 'deleted_at' ], + }); + }, + + /** + * 回滚:删除表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + down: async (queryInterface, Sequelize) => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js b/database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js new file mode 100644 index 0000000..dc79c57 --- /dev/null +++ b/database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js @@ -0,0 +1,40 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + /** + * 移除冗余字段 store_id / shop_id 及其索引。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_store_shop'); + await queryInterface.removeColumn(TABLE_NAME, 'store_id'); + await queryInterface.removeColumn(TABLE_NAME, 'shop_id'); + }, + + /** + * 回滚:恢复 store_id / shop_id 列及索引。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'store_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID(stores.id),NULL=适用所有货主', + }); + await queryInterface.addColumn(TABLE_NAME, 'shop_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '店铺ID(shops.id),NULL=适用所有店铺', + }); + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_store_shop', + fields: [ 'warehouse_id', 'store_id', 'shop_id', 'deleted_at' ], + }); + }, +}; diff --git a/database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js b/database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js new file mode 100644 index 0000000..dd485a9 --- /dev/null +++ b/database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'prohibited_type_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '违禁品类型ID(关联 wms_prohibited_type.id),NULL=不限制违禁品', + after: 'match_condition', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'prohibited_type_id'); + }, +}; diff --git a/database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js b/database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js new file mode 100644 index 0000000..9453a0a --- /dev/null +++ b/database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js @@ -0,0 +1,31 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'match_condition'); + await queryInterface.addColumn(TABLE_NAME, 'provinces', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定省份,逗号分隔,如"广东省,浙江省",NULL=不限制', + after: 'is_enabled', + }); + await queryInterface.addColumn(TABLE_NAME, 'cities', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定城市,逗号分隔,如"广州市,杭州市",NULL=不限制', + after: 'provinces', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'cities'); + await queryInterface.removeColumn(TABLE_NAME, 'provinces'); + await queryInterface.addColumn(TABLE_NAME, 'match_condition', { + type: Sequelize.JSON, + allowNull: true, + comment: '附加匹配条件(JSON)', + }); + }, +}; diff --git a/database/migrations/20260803170000-add-weight-range-to-binding-policy.js b/database/migrations/20260803170000-add-weight-range-to-binding-policy.js new file mode 100644 index 0000000..5c2073d --- /dev/null +++ b/database/migrations/20260803170000-add-weight-range-to-binding-policy.js @@ -0,0 +1,25 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'min_weight_g', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '最小重量(克),NULL=不限制', + after: 'cities', + }); + await queryInterface.addColumn(TABLE_NAME, 'max_weight_g', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '最大重量(克),NULL=不限制', + after: 'min_weight_g', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'max_weight_g'); + await queryInterface.removeColumn(TABLE_NAME, 'min_weight_g'); + }, +}; diff --git a/database/migrations/20260803170500-add-weight-type-to-binding-policy.js b/database/migrations/20260803170500-add-weight-type-to-binding-policy.js new file mode 100644 index 0000000..4dd20d5 --- /dev/null +++ b/database/migrations/20260803170500-add-weight-type-to-binding-policy.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'weight_type', { + type: Sequelize.TINYINT(1), + allowNull: true, + comment: '重量段类型:NULL=不限制/0=常规/1=轻货/2=重货/3=冷链', + after: 'max_weight_g', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'weight_type'); + }, +}; diff --git a/database/migrations/20260803171000-make-weight-type-required.js b/database/migrations/20260803171000-make-weight-type-required.js new file mode 100644 index 0000000..7e6f6e7 --- /dev/null +++ b/database/migrations/20260803171000-make-weight-type-required.js @@ -0,0 +1,23 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'weight_type', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '重量段类型:0=常规/1=轻货/2=重货/3=冷链', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'weight_type', { + type: Sequelize.TINYINT(1), + allowNull: true, + defaultValue: null, + comment: '重量段类型:NULL=不限制/0=常规/1=轻货/2=重货/3=冷链', + }); + }, +}; diff --git a/database/migrations/20260804090000-merge-provinces-cities-to-regions.js b/database/migrations/20260804090000-merge-provinces-cities-to-regions.js new file mode 100644 index 0000000..b7d5945 --- /dev/null +++ b/database/migrations/20260804090000-merge-provinces-cities-to-regions.js @@ -0,0 +1,30 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'cities'); + await queryInterface.removeColumn(TABLE_NAME, 'provinces'); + await queryInterface.addColumn(TABLE_NAME, 'regions', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定地区,逗号分隔,如"广东省,广州市,深圳市",NULL=不限制', + after: 'is_enabled', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'regions'); + await queryInterface.addColumn(TABLE_NAME, 'provinces', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定省份', + }); + await queryInterface.addColumn(TABLE_NAME, 'cities', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定城市', + }); + }, +}; diff --git a/database/migrations/20260804091000-add-exclude-regions.js b/database/migrations/20260804091000-add-exclude-regions.js new file mode 100644 index 0000000..77285cf --- /dev/null +++ b/database/migrations/20260804091000-add-exclude-regions.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'exclude_regions', { + type: Sequelize.TEXT, + allowNull: true, + comment: '排除地区,逗号分隔,如"新疆维吾尔自治区,西藏自治区",NULL=不排除', + after: 'regions', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'exclude_regions'); + }, +}; diff --git a/database/migrations/20260804100000-add-shop-name.js b/database/migrations/20260804100000-add-shop-name.js new file mode 100644 index 0000000..c1dbe5b --- /dev/null +++ b/database/migrations/20260804100000-add-shop-name.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'shop_name', { + type: Sequelize.TEXT, + allowNull: true, + comment: '包含店铺名称,逗号分隔,NULL=不限制', + after: 'custom_name', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'shop_name'); + }, +}; diff --git a/database/migrations/20260804101000-add-store-ids.js b/database/migrations/20260804101000-add-store-ids.js new file mode 100644 index 0000000..2e9aabb --- /dev/null +++ b/database/migrations/20260804101000-add-store-ids.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'store_ids', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定货主ID,逗号分隔,NULL=不限制', + after: 'shop_name', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'store_ids'); + }, +}; diff --git a/database/migrations/20260804110000-change-text-to-json.js b/database/migrations/20260804110000-change-text-to-json.js new file mode 100644 index 0000000..95722c1 --- /dev/null +++ b/database/migrations/20260804110000-change-text-to-json.js @@ -0,0 +1,19 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'regions', { type: Sequelize.JSON, allowNull: true, comment: '限定地区,字符串数组' }); + await queryInterface.changeColumn(TABLE_NAME, 'exclude_regions', { type: Sequelize.JSON, allowNull: true, comment: '排除地区,字符串数组' }); + await queryInterface.changeColumn(TABLE_NAME, 'shop_name', { type: Sequelize.JSON, allowNull: true, comment: '包含店铺名称,字符串数组' }); + await queryInterface.changeColumn(TABLE_NAME, 'store_ids', { type: Sequelize.JSON, allowNull: true, comment: '限定货主ID,数字数组' }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'regions', { type: Sequelize.TEXT, allowNull: true, comment: '限定地区,逗号分隔' }); + await queryInterface.changeColumn(TABLE_NAME, 'exclude_regions', { type: Sequelize.TEXT, allowNull: true, comment: '排除地区,逗号分隔' }); + await queryInterface.changeColumn(TABLE_NAME, 'shop_name', { type: Sequelize.TEXT, allowNull: true, comment: '包含店铺名称,逗号分隔' }); + await queryInterface.changeColumn(TABLE_NAME, 'store_ids', { type: Sequelize.TEXT, allowNull: true, comment: '限定货主ID,逗号分隔' }); + }, +}; diff --git a/database/migrations/20260804120000-add-content-to-inbox-message.js b/database/migrations/20260804120000-add-content-to-inbox-message.js new file mode 100644 index 0000000..4cd1c9b --- /dev/null +++ b/database/migrations/20260804120000-add-content-to-inbox-message.js @@ -0,0 +1,33 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_message'; +const COLUMN_NAME = 'content'; + +module.exports = { + /** + * 为站内信消息表添加消息正文字段。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) return; + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.TEXT, + allowNull: true, + comment: '消息正文/摘要,用于列表展示和关键词搜索', + after: 'target_channel', + }); + }, + + /** + * 回滚:移除消息正文字段。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 迁移回滚结果。 + */ + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260804120000-change-prohibited-to-json.js b/database/migrations/20260804120000-change-prohibited-to-json.js new file mode 100644 index 0000000..f2b1f9b --- /dev/null +++ b/database/migrations/20260804120000-change-prohibited-to-json.js @@ -0,0 +1,21 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'prohibited_type_id', { + type: Sequelize.JSON, + allowNull: true, + comment: '违禁品类型ID数组(关联 wms_prohibited_type.id),如[1,2],NULL=不限制违禁品', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'prohibited_type_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '违禁品类型ID(关联 wms_prohibited_type.id),NULL=不限制违禁品', + }); + }, +}; diff --git a/database/migrations/20260804130000-create-inbox-block.js b/database/migrations/20260804130000-create-inbox-block.js new file mode 100644 index 0000000..2e22c45 --- /dev/null +++ b/database/migrations/20260804130000-create-inbox-block.js @@ -0,0 +1,57 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_block'; + +module.exports = { + /** + * 创建站内信屏蔽表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群名称', + }, + user_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户名称', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'group_name', 'user_name' ], { + unique: true, + name: 'uk_group_user', + }); + }, + + /** + * 回滚:删除站内信屏蔽表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 迁移回滚结果。 + */ + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260804140000-create-inbox-group.js b/database/migrations/20260804140000-create-inbox-group.js new file mode 100644 index 0000000..875af02 --- /dev/null +++ b/database/migrations/20260804140000-create-inbox-group.js @@ -0,0 +1,92 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + if (tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME)) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '群名称', + }, + group_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部群ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + group_type: { + type: Sequelize.ENUM('store', 'warehouse', 'express'), + allowNull: true, + comment: '群类型: store=货主 warehouse=仓库 express=快递', + }, + sub_type: { + type: Sequelize.STRING(20), + allowNull: true, + comment: '群子类型', + }, + source_type: { + type: Sequelize.STRING(20), + allowNull: true, + comment: '来源类型:im / api / system', + }, + source_extra: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '来源附加信息', + }, + is_blocked: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否屏蔽 0=否 1=是', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'group_name', 'warehouse_id' ], { + unique: true, + name: 'uk_group_warehouse', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260805120000-add-express-fields-to-inbox-group.js b/database/migrations/20260805120000-add-express-fields-to-inbox-group.js new file mode 100644 index 0000000..926880e --- /dev/null +++ b/database/migrations/20260805120000-add-express-fields-to-inbox-group.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 为 wms_inbox_group 添加快递相关字段: + * - express_interfaces:快递接口ID列表(逗号分隔) + * - system_express_code:系统快递编码 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING } = Sequelize; + + // 检查列是否已存在 + const tableInfo = await queryInterface.describeTable('wms_inbox_group'); + + if (!tableInfo.express_interfaces) { + await queryInterface.addColumn('wms_inbox_group', 'express_interfaces', { + type: STRING(500), + allowNull: true, + comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)', + }); + } + + if (!tableInfo.system_express_code) { + await queryInterface.addColumn('wms_inbox_group', 'system_express_code', { + type: STRING(50), + allowNull: true, + comment: '系统快递编码(仅群类型为 express 时必填)', + }); + } + }, + + down: async queryInterface => { + const tableInfo = await queryInterface.describeTable('wms_inbox_group'); + + if (tableInfo.express_interfaces) { + await queryInterface.removeColumn('wms_inbox_group', 'express_interfaces'); + } + if (tableInfo.system_express_code) { + await queryInterface.removeColumn('wms_inbox_group', 'system_express_code'); + } + }, +}; diff --git a/database/migrations/20260805130000-add-inbox-menu-permissions.js b/database/migrations/20260805130000-add-inbox-menu-permissions.js new file mode 100644 index 0000000..6306340 --- /dev/null +++ b/database/migrations/20260805130000-add-inbox-menu-permissions.js @@ -0,0 +1,73 @@ +'use strict'; + +/** + * 新增「消息和自动回复」根菜单及「群列表」「消息记录」子页面。 + * + * 固定 ID(开发库 & 生产库 wms_permission 当前 max_id 均为 491): + * 492 — 父级菜单 "消息和自动回复" + * 493 — inbox.groups(群列表) + * 494 — inbox.messages(消息记录) + * + * 授权角色(permissions 不为 "*" 的 主管/经理 级角色): + * 8 — 经理 + * 26 — 仓库组-主管 + * 28 — 客服组-主管 + * 29 — 生产组-主管 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 插入父级权限 (type=web_pages, sort=13) ── + // 使用 INSERT IGNORE 兼容生产环境已有数据(路径相同但名称可能略有差异) + await queryInterface.sequelize.query(` + INSERT IGNORE INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (492, '/inbox', NULL, '消息和自动回复', NULL, '消息和自动回复', NULL, 0, 0, NULL, 'web_pages', 13, 1, NOW(), NOW()) + `); + + // ── 2. 插入子页面权限 ── + // 群列表 + await queryInterface.sequelize.query(` + INSERT IGNORE INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (493, '/inbox/groups', NULL, 'inbox.groups', NULL, '群列表', NULL, 0, 0, 492, 'web_pages', 0, 1, NOW(), NOW()) + `); + + // 消息记录 + await queryInterface.sequelize.query(` + INSERT IGNORE INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (494, '/inbox/messages', NULL, 'inbox.messages', NULL, '消息记录', NULL, 0, 0, 492, 'web_pages', 1, 1, NOW(), NOW()) + `); + + // ── 3. 给 客服组-主管及以上角色 追加权限 ID(幂等:已包含则跳过)── + const newIdSuffix = ', 492, 493, 494'; + + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]') + WHERE id IN (8, 26, 28, 29) + AND permissions != '*' + AND permissions IS NOT NULL + AND LENGTH(permissions) > 2 + AND permissions NOT LIKE '% 492,%' + `); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + // ── 1. 从角色权限中移除新增的 ID ── + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = REPLACE(permissions, ', 492, 493, 494', '') + WHERE id IN (8, 26, 28, 29) + `); + + // ── 2. 删除子页面权限 ── + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id IN (493, 494)' + ); + + // ── 3. 删除父级权限 ── + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id = 492' + ); + }, +}; diff --git a/database/migrations/20260805140000-add-inbox-indexes.js b/database/migrations/20260805140000-add-inbox-indexes.js new file mode 100644 index 0000000..974cf49 --- /dev/null +++ b/database/migrations/20260805140000-add-inbox-indexes.js @@ -0,0 +1,73 @@ +'use strict'; + +/** + * 为站内信消息表和群表补充查询索引。 + * + * wms_inbox_message: + * - idx_warehouse_group_created: (warehouse_id, group_id, created_at) + * 用于按群拉取消息列表(最常用查询)。 + * + * wms_inbox_group: + * - idx_group_id: (group_id) + * 用于 receiver/processor 中按 group_id 查找群。 + * - idx_warehouse_group_id: (warehouse_id, group_id) + * 用于按仓库+群ID定位群。 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + // ── wms_inbox_message 索引 ── + const msgTableInfo = await queryInterface.describeTable('wms_inbox_message'); + + // 检查已有索引(通过尝试添加,重复则忽略) + try { + await queryInterface.addIndex('wms_inbox_message', { + fields: [ 'warehouse_id', 'group_id', 'created_at' ], + name: 'idx_warehouse_group_created', + }); + console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已创建'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已存在,跳过'); + } else { + throw e; + } + } + + // ── wms_inbox_group 索引 ── + try { + await queryInterface.addIndex('wms_inbox_group', { + fields: [ 'group_id' ], + name: 'idx_group_id', + }); + console.log('[idx] wms_inbox_group.idx_group_id 已创建'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[idx] wms_inbox_group.idx_group_id 已存在,跳过'); + } else { + throw e; + } + } + + try { + await queryInterface.addIndex('wms_inbox_group', { + fields: [ 'warehouse_id', 'group_id' ], + name: 'idx_warehouse_group_id', + }); + console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已创建'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已存在,跳过'); + } else { + throw e; + } + } + }, + + // eslint-disable-next-line no-unused-vars + down: async (queryInterface, Sequelize) => { + await queryInterface.removeIndex('wms_inbox_message', 'idx_warehouse_group_created'); + await queryInterface.removeIndex('wms_inbox_group', 'idx_group_id'); + await queryInterface.removeIndex('wms_inbox_group', 'idx_warehouse_group_id'); + }, +}; diff --git a/database/migrations/20260805150000-add-group-api-permissions.js b/database/migrations/20260805150000-add-group-api-permissions.js new file mode 100644 index 0000000..0464573 --- /dev/null +++ b/database/migrations/20260805150000-add-group-api-permissions.js @@ -0,0 +1,53 @@ +'use strict'; + +/** + * 为 inbox.group.* 方法创建 API 权限记录。 + * + * 固定 ID(当前 max_id=494): + * 495 — inbox.group.list + * 496 — inbox.group.disable + * 497 — inbox.group.update + * 498 — inbox.group.messages + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const methods = [ + [ 495, 'inbox.group.list' ], + [ 496, 'inbox.group.disable' ], + [ 497, 'inbox.group.update' ], + [ 498, 'inbox.group.messages' ], + ]; + + for (const [ id, method ] of methods) { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${method}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='${method}', meta_title='API:${method}', type='api' + `); + } + + // 授权给客服组-主管及以上角色 + const newIdSuffix = ', 495, 496, 497, 498'; + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]') + WHERE id IN (8, 26, 28, 29) + AND permissions != '*' + AND permissions IS NOT NULL + AND LENGTH(permissions) > 2 + `); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id IN (495, 496, 497, 498)' + ); + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = REPLACE(permissions, ', 495, 496, 497, 498', '') + WHERE id IN (8, 26, 28, 29) + `); + }, +}; diff --git a/database/migrations/20260805160000-expand-item-snapshot-key.js b/database/migrations/20260805160000-expand-item-snapshot-key.js new file mode 100644 index 0000000..d7914cb --- /dev/null +++ b/database/migrations/20260805160000-expand-item-snapshot-key.js @@ -0,0 +1,90 @@ +'use strict'; + +/** + * 扩大 wms_wave_batch.item_snapshot_key 列容量以容纳多商品订单的快照键。 + * + * 背景: + * buildItemSnapshotKey 将订单中每个商品的 stock_id、item_code、 + * item_name、barcode、quantity 用 :: 拼接,多个商品再用 | 连接。 + * 当订单包含较多商品或商品名较长时,快照键极易超过原 VARCHAR(255) 上限, + * 导致 INSERT 时报 "Data too long for column 'item_snapshot_key'"。 + * + * 变更: + * 1. item_snapshot_key: VARCHAR(255) → VARCHAR(1024) + * (与 item_detail_machine 容量保持一致) + * 2. 索引 idx_wave_snapshot_key: 全列索引 → 前缀索引(191) + * (与 idx_wave_item_machine_prefix 前缀长度一致, + * 兼容 utf8mb4 下的 InnoDB 索引键长度限制) + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + // ── 1. 先删旧全列索引(否则 changeColumn 1024 会触发 3072 字节限制)── + try { + await queryInterface.removeIndex('wms_wave_batch', 'idx_wave_snapshot_key'); + console.log('[migrate] 已移除旧全列索引 idx_wave_snapshot_key'); + } catch (e) { + // 索引可能不存在(如全新库或已执行过),忽略 + const msg = String(e.message || ''); + if (!msg.includes('check that it exists') && !msg.includes('exist')) { + console.warn('[migrate] 移除索引 idx_wave_snapshot_key 时出现非预期错误:', msg); + } + } + + // ── 2. 修改列容量 ── + await queryInterface.changeColumn('wms_wave_batch', 'item_snapshot_key', { + type: Sequelize.STRING(1024), + allowNull: true, + comment: '结构快照键(与 item_detail_machine 一致,1024 长度以容纳多商品订单的快照)', + }); + console.log('[migrate] wms_wave_batch.item_snapshot_key VARCHAR(255) → VARCHAR(1024)'); + + // ── 3. 创建前缀索引 ── + try { + await queryInterface.sequelize.query( + 'ALTER TABLE wms_wave_batch ADD INDEX idx_wave_snapshot_key (item_snapshot_key(191))' + ); + console.log('[migrate] 已创建前缀索引 idx_wave_snapshot_key(item_snapshot_key(191))'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[migrate] 前缀索引 idx_wave_snapshot_key 已存在,跳过'); + } else { + throw e; + } + } + }, + + // eslint-disable-next-line no-unused-vars + down: async (queryInterface, Sequelize) => { + // ── 还原索引为全列索引 ── + try { + await queryInterface.removeIndex('wms_wave_batch', 'idx_wave_snapshot_key'); + console.log('[migrate:down] 已移除前缀索引 idx_wave_snapshot_key'); + } catch (e) { + if (!(e.message && e.message.includes('check that it exists'))) { + console.warn('[migrate:down] 移除索引时出现非预期错误:', e.message); + } + } + + try { + await queryInterface.sequelize.query( + 'ALTER TABLE wms_wave_batch ADD INDEX idx_wave_snapshot_key (item_snapshot_key)' + ); + console.log('[migrate:down] 已还原全列索引 idx_wave_snapshot_key'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[migrate:down] 全列索引 idx_wave_snapshot_key 已存在,跳过'); + } else { + throw e; + } + } + + // ── 还原列容量 ── + await queryInterface.changeColumn('wms_wave_batch', 'item_snapshot_key', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '结构快照键', + }); + console.log('[migrate:down] wms_wave_batch.item_snapshot_key VARCHAR(1024) → VARCHAR(255)'); + }, +}; diff --git a/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js b/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js new file mode 100644 index 0000000..303c981 --- /dev/null +++ b/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 为 wms_inbox_message 新增 ai_thoughts 字段。 + * 存储 AI 多轮推理的思考过程数组。 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable('wms_inbox_message'); + if (!tableInfo.ai_thoughts) { + await queryInterface.addColumn('wms_inbox_message', 'ai_thoughts', { + type: Sequelize.JSON, + allowNull: true, + comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]', + }); + } + }, + + // eslint-disable-next-line no-unused-vars + down: async queryInterface => { + const tableInfo = await queryInterface.describeTable('wms_inbox_message'); + if (tableInfo.ai_thoughts) { + await queryInterface.removeColumn('wms_inbox_message', 'ai_thoughts'); + } + }, +}; diff --git a/database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js b/database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js new file mode 100644 index 0000000..c7efcc3 --- /dev/null +++ b/database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js @@ -0,0 +1,21 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.ai_enabled) return; + + await queryInterface.addColumn(TABLE_NAME, 'ai_enabled', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'ai_enabled'); + }, +}; diff --git a/database/migrations/20260806160000-drop-target-channel-from-inbox-message.js b/database/migrations/20260806160000-drop-target-channel-from-inbox-message.js new file mode 100644 index 0000000..aea30e1 --- /dev/null +++ b/database/migrations/20260806160000-drop-target-channel-from-inbox-message.js @@ -0,0 +1,20 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_message'; + +module.exports = { + up: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns.target_channel) return; + + await queryInterface.removeColumn(TABLE_NAME, 'target_channel'); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'target_channel', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook', + }); + }, +}; diff --git a/database/migrations/20260806200000-create-wms-warehouse-log.js b/database/migrations/20260806200000-create-wms-warehouse-log.js new file mode 100644 index 0000000..3d9573e --- /dev/null +++ b/database/migrations/20260806200000-create-wms-warehouse-log.js @@ -0,0 +1,108 @@ +'use strict'; + +/** + * 创建仓库开放 API 请求日志表。 + * 记录 /warehouse 入口的每次请求:app_key、method、warehouse_id、 + * 请求体、响应体、HTTP 状态码、耗时等。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING, INTEGER, BIGINT, TEXT, DATE } = Sequelize; + + await queryInterface.createTable('wms_warehouse_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '自增主键', + }, + log_id: { + type: STRING(32), + allowNull: false, + unique: true, + comment: '日志唯一ID(WL-{timestamp}-{random})', + }, + app_key: { + type: STRING(64), + allowNull: true, + comment: 'API 应用 AppKey', + }, + method: { + type: STRING(100), + allowNull: true, + comment: '请求方法名(如 inbox.push)', + }, + warehouse_id: { + type: INTEGER(10), + allowNull: true, + comment: '仓库 ID', + }, + url: { + type: TEXT, + allowNull: true, + comment: '请求 URL', + }, + http_status: { + type: INTEGER(5), + allowNull: true, + comment: 'HTTP 状态码', + }, + body: { + type: TEXT('long'), + allowNull: true, + comment: '请求体(最大 65535 字符)', + }, + result: { + type: TEXT('long'), + allowNull: true, + comment: '响应体(最大 65535 字符)', + }, + use_time: { + type: INTEGER(12), + allowNull: true, + comment: '耗时(毫秒)', + }, + created_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + }); + + // 索引 + await queryInterface.addIndex('wms_warehouse_log', { + name: 'uk_log_id', + unique: true, + fields: [ 'log_id' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_app_key', + fields: [ 'app_key' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_method', + fields: [ 'method' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_created_at', + fields: [ 'created_at' ], + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable('wms_warehouse_log'); + }, +}; diff --git a/database/migrations/20260807100000-change-ai-enabled-default-to-0.js b/database/migrations/20260807100000-change-ai-enabled-default-to-0.js new file mode 100644 index 0000000..c5ebcf7 --- /dev/null +++ b/database/migrations/20260807100000-change-ai-enabled-default-to-0.js @@ -0,0 +1,27 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +/** + * 修改 ai_enabled 默认值从 1 改为 0。 + * 新创建的群默认关闭 AI 自动回复,需管理员手动开启。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'ai_enabled', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'ai_enabled', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }); + }, +}; diff --git a/database/migrations/20260807110000-switch-inbox-block-to-ids.js b/database/migrations/20260807110000-switch-inbox-block-to-ids.js new file mode 100644 index 0000000..2033b23 --- /dev/null +++ b/database/migrations/20260807110000-switch-inbox-block-to-ids.js @@ -0,0 +1,83 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_block'; + +/** + * 将屏蔽表从 group_name/user_name 切换为 group_id/user_id + warehouse_id。 + * 群名称和用户名可能变更或含特殊字符,改用稳定ID。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + // 1. 新增 warehouse_id(不允许为空,给历史数据默认值 0) + const cols = await queryInterface.describeTable(TABLE_NAME); + if (!cols.warehouse_id) { + await queryInterface.addColumn(TABLE_NAME, 'warehouse_id', { + type: Sequelize.INTEGER(10), + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }); + } + + // 2. 新增 group_id + if (!cols.group_id) { + await queryInterface.addColumn(TABLE_NAME, 'group_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群ID', + }); + } + + // 3. 新增 user_id + if (!cols.user_id) { + await queryInterface.addColumn(TABLE_NAME, 'user_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户ID', + }); + } + + // 4. 检查是否已有旧列,有则删除 + const colsAfter = await queryInterface.describeTable(TABLE_NAME); + if (colsAfter.group_name) { + await queryInterface.removeColumn(TABLE_NAME, 'group_name'); + } + if (colsAfter.user_name) { + await queryInterface.removeColumn(TABLE_NAME, 'user_name'); + } + + // 5. 添加唯一索引 + await queryInterface.addIndex(TABLE_NAME, { + name: 'uk_warehouse_group_user', + unique: true, + fields: [ 'warehouse_id', 'group_id', 'user_id' ], + }); + }, + + down: async (queryInterface, Sequelize) => { + // 回滚:恢复旧列 + const cols = await queryInterface.describeTable(TABLE_NAME); + if (!cols.group_name) { + await queryInterface.addColumn(TABLE_NAME, 'group_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群名称', + }); + } + if (!cols.user_name) { + await queryInterface.addColumn(TABLE_NAME, 'user_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户名称', + }); + } + + // 删除新列 + if (cols.group_id) await queryInterface.removeColumn(TABLE_NAME, 'group_id'); + if (cols.user_id) await queryInterface.removeColumn(TABLE_NAME, 'user_id'); + if (cols.warehouse_id) await queryInterface.removeColumn(TABLE_NAME, 'warehouse_id'); + + // 删除唯一索引 + await queryInterface.removeIndex(TABLE_NAME, 'uk_warehouse_group_user'); + }, +}; diff --git a/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js b/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js new file mode 100644 index 0000000..8c1386e --- /dev/null +++ b/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js @@ -0,0 +1,44 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 为出库单主表添加运单号字段。 + * + * - express_code:回传运单号(单个),奇门 stockout.confirm 回传时使用,为空则拒绝确认 + * - express_codes:运单号列表(JSON 数组),支持多包裹场景 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + if (!columns.express_code) { + await queryInterface.addColumn(TABLE, 'express_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '回传运单号(奇门 stockout.confirm 回传使用,为空则拒绝确认)', + }); + } + + if (!columns.express_codes) { + await queryInterface.addColumn(TABLE, 'express_codes', { + type: Sequelize.JSON, + allowNull: true, + comment: '运单号列表(JSON 数组,支持多包裹场景)', + }); + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + + if (columns.express_code) { + await queryInterface.removeColumn(TABLE, 'express_code'); + } + + if (columns.express_codes) { + await queryInterface.removeColumn(TABLE, 'express_codes'); + } + }, +}; + diff --git a/database/migrations/20260807130000-add-stockout-api-permissions.js b/database/migrations/20260807130000-add-stockout-api-permissions.js new file mode 100644 index 0000000..f4b39d5 --- /dev/null +++ b/database/migrations/20260807130000-add-stockout-api-permissions.js @@ -0,0 +1,84 @@ +'use strict'; + +/** + * 为 storage.stockout.* 添加 API 权限并授权。 + * + * 权限 ID(固定): + * 504 — storage.stockout.list 出库单列表 + * 505 — storage.stockout.listItems 出库单明细 + * 506 — storage.stockout.confirm 出库单确认 + * 507 — storage.stockout.updateExpress 更新运单号 + * + * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) + */ +module.exports = { + up: async queryInterface => { + // ===== 第一步:写入权限行 ===== + const perms = [ + [ 504, 'storage.stockout.list', '出库单列表' ], + [ 505, 'storage.stockout.listItems', '出库单明细' ], + [ 506, 'storage.stockout.confirm', '出库单确认' ], + [ 507, 'storage.stockout.updateExpress', '更新运单号' ], + ]; + + for (const [ id, method, desc ] of perms) { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${desc}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='${method}', meta_title='API:${desc}', type='api' + `); + } + + // ===== 第二步:授权给客服组员工及以上角色 ===== + const roleIds = [ 8, 26, 28, 29, 30 ]; // 经理 + 各主管 + 客服组-员工 + const newPermIds = [ 504, 505, 506, 507 ]; + + for (const roleId of roleIds) { + for (const permId of newPermIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 0 + `); + } + } + }, + + down: async queryInterface => { + // 移除授权 + const roleIds = [ 8, 26, 28, 29, 30 ]; + const permIdStr = '504, 505, 506, 507'; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + JSON_REMOVE( + JSON_REMOVE( + JSON_REMOVE(permissions, JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '504'))), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '505')) + ), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '506')) + ), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '507')) + ), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + `); + } + + // 删除权限行 + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id IN (504, 505, 506, 507) + `); + }, +}; diff --git a/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js b/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js new file mode 100644 index 0000000..158b5e0 --- /dev/null +++ b/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js @@ -0,0 +1,56 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 拆分运单号字段: + * - express_code 保持为快递公司编码(如 SF、STO) + * - 新增 express_name:快递公司名称(如 顺丰、申通) + * - 新增 waybill_code:单个运单号 + * - 新增 waybill_codes:运单号列表(JSON 数组) + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + if (!columns.express_name) { + await queryInterface.addColumn(TABLE, 'express_name', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '快递公司名称(由 express_code 自动解析)', + }); + } + + if (!columns.waybill_code) { + await queryInterface.addColumn(TABLE, 'waybill_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '运单号', + }); + } + + if (!columns.waybill_codes) { + await queryInterface.addColumn(TABLE, 'waybill_codes', { + type: Sequelize.JSON, + allowNull: true, + comment: '运单号列表(JSON 数组,支持多包裹场景)', + }); + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + + if (columns.express_name) { + await queryInterface.removeColumn(TABLE, 'express_name'); + } + + if (columns.waybill_code) { + await queryInterface.removeColumn(TABLE, 'waybill_code'); + } + + if (columns.waybill_codes) { + await queryInterface.removeColumn(TABLE, 'waybill_codes'); + } + }, +}; diff --git a/database/migrations/20260808100000-add-delivery-code-store-index.js b/database/migrations/20260808100000-add-delivery-code-store-index.js new file mode 100644 index 0000000..8bcba00 --- /dev/null +++ b/database/migrations/20260808100000-add-delivery-code-store-index.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // Query 3 关联查询:delivery_order_code + store_id 联合索引(最高频缺失索引) + await queryInterface.addIndex('wms_order_express', [ 'delivery_order_code', 'store_id' ], { + name: 'idx_delivery_code_store', + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeIndex('wms_order_express', 'idx_delivery_code_store'); + }, +}; diff --git a/database/migrations/20260809120000-drop-wms-after-sale-work-order.js b/database/migrations/20260809120000-drop-wms-after-sale-work-order.js new file mode 100644 index 0000000..ec379c2 --- /dev/null +++ b/database/migrations/20260809120000-drop-wms-after-sale-work-order.js @@ -0,0 +1,256 @@ +'use strict'; + +const TABLE_MAIN = 'wms_after_sale_work_order'; +const TABLE_STEP = 'wms_after_sale_work_order_step'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + // 先删子表(步骤表),再删主表(工单表) + await queryInterface.dropTable(TABLE_STEP); + await queryInterface.dropTable(TABLE_MAIN); + }, + + down: async (queryInterface, Sequelize) => { + // ========== 1. 重建主表:wms_after_sale_work_order ========== + await queryInterface.createTable(TABLE_MAIN, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + work_order_no: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后工单号,唯一', + }, + business_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '关联业务类型', + }, + business_sub_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '关联业务子类型', + }, + business_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联业务单据主键ID(多态关联)', + }, + business_no: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '关联业务单据号(冗余)', + }, + direction: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '记账方向:0=未确定 1=入库 2=出库', + }, + status: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '工单状态:0=待处理 1=处理中 2=已完成 3=已关闭 9=已取消', + }, + priority: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 50, + comment: '优先级:1~100,数字越大优先级越高', + }, + title: { + type: Sequelize.STRING(200), + allowNull: false, + comment: '工单标题/摘要', + }, + description: { + type: Sequelize.TEXT, + allowNull: true, + comment: '问题描述', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人ID,关联 account.id;0 表示 AI 自动接待', + }, + creator_snapshot: { + type: Sequelize.TEXT, + allowNull: true, + comment: '创建人信息快照(JSON格式)', + }, + assignee_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '当前处理人ID,关联 account.id', + }, + parent_work_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '父工单ID,自关联本表;非空时表示子工单', + }, + current_step: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '当前进度,值为当前正在处理的 step_order 序号', + }, + claim_needed: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '是否需要理赔:0=不需要 1=需要', + }, + claim_amount: { + type: Sequelize.DECIMAL(12, 2), + allowNull: true, + defaultValue: 0.00, + comment: '理赔金额(元)', + }, + claim_status: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '理赔状态:0=未理赔 1=已理赔(单笔结清) 2=月结', + }, + resolution: { + type: Sequelize.TEXT, + allowNull: true, + comment: '处理结果说明', + }, + resolved_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '解决时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_MAIN, ['work_order_no'], { unique: true, name: 'uk_work_order_no' }); + await queryInterface.addIndex(TABLE_MAIN, ['warehouse_id'], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['store_id'], { name: 'idx_store_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['business_type', 'business_sub_type', 'business_id'], { name: 'idx_business_type_subtype_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['status'], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_MAIN, ['assignee_id'], { name: 'idx_assignee_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['parent_work_order_id'], { name: 'idx_parent_work_order_id' }); + await queryInterface.addIndex(TABLE_MAIN, ['priority'], { name: 'idx_priority' }); + await queryInterface.addIndex(TABLE_MAIN, ['claim_status'], { name: 'idx_claim_status' }); + await queryInterface.addIndex(TABLE_MAIN, ['created_at'], { name: 'idx_created_at' }); + await queryInterface.addIndex(TABLE_MAIN, ['deleted_at'], { name: 'idx_deleted_at' }); + + // ========== 2. 重建子表:wms_after_sale_work_order_step ========== + await queryInterface.createTable(TABLE_STEP, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + work_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '工单ID,关联 wms_after_sale_work_order.id', + }, + step_order: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '步骤序号(从1开始递增)', + }, + step_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '步骤名称', + }, + step_status: { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作员工ID,关联 account.id', + }, + operator_snapshot: { + type: Sequelize.TEXT, + allowNull: true, + comment: '操作人信息快照(JSON格式)', + }, + action: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '操作动作描述', + }, + remark: { + type: Sequelize.TEXT, + allowNull: true, + comment: '处理备注', + }, + started_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '步骤开始时间', + }, + completed_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '步骤完成时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_STEP, ['work_order_id'], { name: 'idx_work_order_id' }); + await queryInterface.addIndex(TABLE_STEP, ['operator_id'], { name: 'idx_operator_id' }); + await queryInterface.addIndex(TABLE_STEP, ['deleted_at'], { name: 'idx_deleted_at' }); + await queryInterface.addIndex(TABLE_STEP, ['work_order_id', 'step_order', 'deleted_at'], { unique: true, name: 'uk_work_order_step' }); + }, +}; diff --git a/database/migrations/20260809130000-create-wms-after-sale.js b/database/migrations/20260809130000-create-wms-after-sale.js new file mode 100644 index 0000000..68eae7b --- /dev/null +++ b/database/migrations/20260809130000-create-wms-after-sale.js @@ -0,0 +1,293 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '货主ID', + }, + after_sale_no: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后单号,唯一,生成规则:AS+YYYYMMDD+6位序号', + }, + type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '售后类型:order/receiving/entry/stockout', + }, + sub_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后子类型,与 type 组成二级分类', + }, + status: { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '售后状态:pending/processing/completed/closed/cancelled', + }, + priority: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先(0=普通,10=紧急)', + }, + title: { + type: Sequelize.STRING(200), + allowNull: false, + comment: '售后标题/简要描述', + }, + description: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '售后详细描述', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人账户ID', + }, + role_group: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '当前处理角色组:customer_service/warehouse/finance', + }, + inbox_message_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '关联站内信消息ID(wms_inbox_message.id)', + }, + resolution: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '最终处理结果说明', + }, + resolved_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '完结时间(状态变为 completed 时写入)', + }, + claim_needed: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '仓库理赔标记:0=不需要,1=需要', + }, + claim_amount: { + type: Sequelize.DECIMAL(12, 2), + allowNull: true, + defaultValue: null, + comment: '仓库理赔金额,单位:元', + }, + claim_status: { + type: Sequelize.STRING(20), + allowNull: true, + defaultValue: null, + comment: '仓库理赔状态:pending/reviewing/approved/paid/monthly/rejected', + }, + carrier_claim_needed: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '运方理赔标记:0=不需要,1=需要', + }, + carrier_claim_amount: { + type: Sequelize.DECIMAL(12, 2), + allowNull: true, + defaultValue: null, + comment: '运方理赔金额,单位:元', + }, + carrier_claim_status: { + type: Sequelize.STRING(20), + allowNull: true, + defaultValue: null, + comment: '运方理赔状态:pending/reviewing/approved/paid/monthly/rejected', + }, + waybill_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '运单ID(关联 wms_order_express.id)', + }, + waybill_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '运单号(冗余)', + }, + order_delivery_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '发货订单ID(关联 wms_order_delivery.id)', + }, + order_delivery_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '发货订单号(冗余)', + }, + entry_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '入库单ID(关联 wms_entry_order.id)', + }, + entry_order_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '入库单号(冗余)', + }, + order_stockout_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '出库单ID(关联 wms_order_stockout.id)', + }, + order_stockout_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '出库单号(冗余)', + }, + receiving_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '收货单ID(关联 wms_receiving.id)', + }, + receiving_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '收货单号(冗余)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + // 唯一索引 — 售后单号 + await queryInterface.addIndex(TABLE_NAME, ['after_sale_no'], { + unique: true, + name: 'uk_after_sale_no', + }); + + // 仓库+状态查询(最高频) + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'status', 'deleted_at'], { + name: 'idx_warehouse_status', + }); + + // 仓库+类型筛选 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'type', 'deleted_at'], { + name: 'idx_warehouse_type', + }); + + // 仓库+类型+子类型筛选 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'type', 'sub_type', 'deleted_at'], { + name: 'idx_type_subtype', + }); + + // 货主查询 + await queryInterface.addIndex(TABLE_NAME, ['store_id', 'deleted_at'], { + name: 'idx_store_id', + }); + + // 创建人查询 + await queryInterface.addIndex(TABLE_NAME, ['creator_id', 'deleted_at'], { + name: 'idx_creator_id', + }); + + // 角色组+状态查询 + await queryInterface.addIndex(TABLE_NAME, ['role_group', 'status', 'deleted_at'], { + name: 'idx_role_group', + }); + + // 仓库+时间排序分页 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'created_at'], { + name: 'idx_created_at', + }); + + // 运单反查 + await queryInterface.addIndex(TABLE_NAME, ['waybill_id'], { + name: 'idx_waybill_id', + }); + + // 发货订单反查 + await queryInterface.addIndex(TABLE_NAME, ['order_delivery_id'], { + name: 'idx_order_delivery_id', + }); + + // 入库单反查 + await queryInterface.addIndex(TABLE_NAME, ['entry_order_id'], { + name: 'idx_entry_order_id', + }); + + // 出库单反查 + await queryInterface.addIndex(TABLE_NAME, ['order_stockout_id'], { + name: 'idx_order_stockout_id', + }); + + // 收货单反查 + await queryInterface.addIndex(TABLE_NAME, ['receiving_id'], { + name: 'idx_receiving_id', + }); + + // 运方理赔状态筛选 + await queryInterface.addIndex(TABLE_NAME, ['carrier_claim_status'], { + name: 'idx_carrier_claim_status', + }); + + // 站内信消息反查 + await queryInterface.addIndex(TABLE_NAME, ['inbox_message_id'], { + name: 'idx_inbox_message_id', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260809130100-create-wms-after-sale-detail.js b/database/migrations/20260809130100-create-wms-after-sale-detail.js new file mode 100644 index 0000000..4a139ec --- /dev/null +++ b/database/migrations/20260809130100-create-wms-after-sale-detail.js @@ -0,0 +1,100 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale_detail'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + after_sale_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联售后主表ID(wms_after_sale.id)', + }, + step_status: { + type: Sequelize.TINYINT(3).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '操作人账户ID(关联 accounts 表)', + }, + operator_snapshot: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '操作人信息快照(JSON),防止账户删除后历史丢失', + }, + action: { + type: Sequelize.STRING(100), + allowNull: true, + defaultValue: null, + comment: '操作动作描述', + }, + remark: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '处理备注', + }, + started_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '步骤开始时间', + }, + completed_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '步骤完成时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + // 按售后单查询进度步骤(最高频) + await queryInterface.addIndex(TABLE_NAME, ['after_sale_id'], { + name: 'idx_after_sale_id', + }); + + // 按操作人查询 + await queryInterface.addIndex(TABLE_NAME, ['operator_id'], { + name: 'idx_operator_id', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260809130200-add-after-sale-permissions.js b/database/migrations/20260809130200-add-after-sale-permissions.js new file mode 100644 index 0000000..d4f2901 --- /dev/null +++ b/database/migrations/20260809130200-add-after-sale-permissions.js @@ -0,0 +1,97 @@ +'use strict'; + +/** + * 新增售后模块权限记录(固定 ID 策略,确保开发/生产一致)。 + * + * 新增权限明细: + * Block(角色组维度): + * 516 — 售后-客服组 + * 517 — 售后-仓库组 + * 518 — 售后-财务组 + * + * Web Pages(菜单/页面): + * 519 — afterSale 售后管理(根菜单) + * 520 — afterSale.list 售后列表 + * 521 — afterSale.detail 售后明细 + * + * API: + * 522 — afterSale.workList API:售后工作列表查询 + * 523 — afterSale.auditList API:售后审计列表查询 + * 508 — afterSale.detail API:售后明细查询 + * 509 — afterSale.create API:创建售后单 + * 510 — afterSale.update API:更新售后单 + * 511 — afterSale.transfer API:售后转单 + * 512 — afterSale.handleWorkOrder API:处理工单 + * 513 — afterSale.registerClaim API:登记理赔 + * 514 — afterSale.export API:售后导出 + * 515 — afterSale.exportTaskProgress API:导出进度查询 + * + * 幂等设计:使用 INSERT IGNORE,已存在的 id 不会重复插入。 + */ + +const TABLE = 'wms_permission'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. Block 权限(角色组维度,用于权限分配分组)── + const blocks = [ + [516, null, null, '售后-客服组', null, '售后-客服组', null, 0, 0, null, 'block', 0, 1], + [517, null, null, '售后-仓库组', null, '售后-仓库组', null, 0, 0, null, 'block', 0, 1], + [518, null, null, '售后-财务组', null, '售后-财务组', null, 0, 0, null, 'block', 0, 1], + ]; + + for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of blocks) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] } + ); + } + + // ── 2. Web Pages 权限(菜单/页面)── + const pages = [ + [519, 'afterSale', null, 'afterSale', null, '售后管理', null, 0, 0, null, 'web_pages', 14, 1], + [520, 'afterSale.list', null, 'afterSale.list', null, '售后列表', null, 0, 0, 519, 'web_pages', 0, 1], + [521, 'afterSale.detail', null, 'afterSale.detail', null, '售后明细', null, 0, 0, 519, 'web_pages', 1, 1], + ]; + + for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of pages) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] } + ); + } + + // ── 3. API 权限 ── + const apis = [ + [522, 'afterSale.workList', 'API:售后工作列表查询'], + [523, 'afterSale.auditList', 'API:售后审计列表查询'], + [508, 'afterSale.detail', 'API:售后明细查询'], + [509, 'afterSale.create', 'API:创建售后单'], + [510, 'afterSale.update', 'API:更新售后单'], + [511, 'afterSale.transfer', 'API:售后转单'], + [512, 'afterSale.handleWorkOrder', 'API:处理工单'], + [513, 'afterSale.registerClaim', 'API:登记理赔'], + [514, 'afterSale.export', 'API:售后导出'], + [515, 'afterSale.exportTaskProgress', 'API:导出进度查询'], + ]; + + for (const [id, path, meta_title] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, null, path, null, meta_title, null, 0, 0, null, 'api', 0, 1] } + ); + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [516, 517, 518, 519, 520, 521, 522, 523, 508, 509, 510, 511, 512, 513, 514, 515]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/database/migrations/20260809140000-add-after-sale-workorder-pages.js b/database/migrations/20260809140000-add-after-sale-workorder-pages.js new file mode 100644 index 0000000..370dd2f --- /dev/null +++ b/database/migrations/20260809140000-add-after-sale-workorder-pages.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 新增售后模块页面权限(售后工单 + 工单列表)。 + * + * 新增: + * Web Pages: + * 524 — afterSale.workOrder 售后工单(根菜单) + * 525 — afterSale.workOrder.list 工单列表(子页面,parent_id=524) + * + * 幂等设计:使用 INSERT IGNORE,已存在的 id 不会重复插入。 + */ + +const TABLE = 'wms_permission'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const pages = [ + [524, 'afterSale.workOrder', null, 'afterSale.workOrder', null, '售后工单', null, 0, 0, null, 'web_pages', 15, 1], + [525, 'afterSale.workOrder.list', null, 'afterSale.workOrder.list', null, '工单列表', null, 0, 0, 524, 'web_pages', 0, 1], + ]; + + for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of pages) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] } + ); + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [524, 525]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/database/migrations/20260809140100-grant-after-sale-workorder-pages.js b/database/migrations/20260809140100-grant-after-sale-workorder-pages.js new file mode 100644 index 0000000..1e4f238 --- /dev/null +++ b/database/migrations/20260809140100-grant-after-sale-workorder-pages.js @@ -0,0 +1,103 @@ +'use strict'; + +/** + * 为售后模块新增页面权限授权,并创建财务组角色。 + * + * 操作: + * 1. 新建财务组角色(role_code='finance') + * 2. 为以下角色追加页面权限 524 (afterSale.workOrder)、525 (afterSale.workOrder.list): + * - 经理 (role_code=2) + * - 客服组-主管 (role_code=05) + * - 客服组-员工 (role_code=04) + * - 仓库组-主管 (role_code=warehouse) + * - 仓库组-员工 (role_code=warehouse_role) + * - 生产组-主管 (role_code=03) + * - 生产组-拣货 (role_code=021) + * + * 幂等设计: + * - 财务组角色使用 INSERT IGNORE,已存在则跳过 + * - 权限追加使用 JSON_ARRAY_APPEND,不重复添加 + */ + +const NEW_PAGE_IDS = [524, 525]; + +// 财务组基础权限:block(518) + 所有web_pages(519,520,521,524,525) + 只读API(522,508) +const FINANCE_PERMISSIONS = [518, 519, 520, 521, 524, 525, 522, 508]; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { sequelize } = queryInterface; + + // ── 1. 创建财务组角色(如果不存在)── + await sequelize.query(` + INSERT IGNORE INTO wms_role (role_code, role_name, description, role_type, scope, is_system, status, pid, created_by, permissions, created_at, updated_at) + VALUES ('finance', '财务组', '售后模块财务审核角色', 1, 1, 1, 1, 8, 1, ?, NOW(), NOW()) + `, { + replacements: [JSON.stringify(FINANCE_PERMISSIONS)], + }); + + // ── 2. 为已有角色追加页面权限 ── + const targetRoleCodes = ['2', '05', '04', 'warehouse', 'warehouse_role', '03', '021']; + + for (const roleCode of targetRoleCodes) { + for (const permId of NEW_PAGE_IDS) { + // 仅当该角色的 permissions 数组中不包含此权限ID时才追加 + // JSON_CONTAINS 检查是否已存在 + // 注意:permissions 列为 LONGTEXT,JSON 函数需显式 CAST + // 安全守卫:permissions 必须是合法 JSON 数组(以 [ 开头且非 NULL), + // 避免在非法 JSON(如旧版范围格式 [4-121])或 NULL 上执行 JSON_ARRAY_APPEND 导致权限被清空。 + await sequelize.query( + `UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(CAST(permissions AS JSON), '$', CAST(? AS UNSIGNED)), + updated_at = NOW() + WHERE role_code = ? + AND permissions IS NOT NULL + AND permissions != '' + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND LEFT(permissions, 1) = '[' + AND JSON_CONTAINS(CAST(permissions AS JSON), CAST(? AS JSON), '$') = 0`, + { replacements: [permId, roleCode, String(permId)] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const { sequelize } = queryInterface; + + // ── 1. 移除财务组角色 ── + await sequelize.query( + "DELETE FROM wms_role WHERE role_code = 'finance'" + ); + + // ── 2. 从各角色移除页面权限 ── + const targetRoleCodes = ['2', '05', '04', 'warehouse', 'warehouse_role', '03', '021']; + + for (const roleCode of targetRoleCodes) { + for (const permId of NEW_PAGE_IDS) { + // 从 JSON 数组中移除指定值(MySQL 5.7+ 无直接 JSON_REMOVE_BY_VALUE,用 JSON_SEARCH) + // 注意:permissions 列为 LONGTEXT,JSON 函数需显式 CAST + // 安全守卫:同 up(),防止在非法 JSON 上操作 + await sequelize.query( + `UPDATE wms_role + SET permissions = JSON_REMOVE( + CAST(permissions AS JSON), + REPLACE(JSON_UNQUOTE(JSON_SEARCH(CAST(permissions AS JSON), 'one', CAST(? AS CHAR), NULL, '$')), '', '') + ), + updated_at = NOW() + WHERE role_code = ? + AND permissions IS NOT NULL + AND permissions != '' + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND LEFT(permissions, 1) = '[' + AND JSON_CONTAINS(CAST(permissions AS JSON), CAST(? AS JSON), '$') = 1`, + { replacements: [permId, roleCode, String(permId)] } + ); + } + } + }, +}; diff --git a/database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js b/database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js new file mode 100644 index 0000000..eeff6e7 --- /dev/null +++ b/database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js @@ -0,0 +1,27 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale_detail'; + +module.exports = { + up: async queryInterface => { + // 将 step_status 从 TINYINT 改为 VARCHAR(20),与 wms_after_sale.status 枚举保持一致 + // 使用原生 SQL 一步完成:改类型 + 更新已有数据为 processing + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN step_status VARCHAR(20) NOT NULL DEFAULT 'processing' COMMENT '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled'` + ); + // 已有数据(原 TINYINT 值)统一回填为 processing + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_NAME}\` SET step_status = 'processing'` + ); + }, + + down: async queryInterface => { + // 回退:先更新数据,再改回 TINYINT + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_NAME}\` SET step_status = '2'` + ); + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN step_status TINYINT(3) UNSIGNED NOT NULL DEFAULT 2 COMMENT '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过'` + ); + }, +}; diff --git a/database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js b/database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js new file mode 100644 index 0000000..b90618d --- /dev/null +++ b/database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js @@ -0,0 +1,17 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD COLUMN followup_at DATETIME NULL DEFAULT NULL COMMENT '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进' AFTER resolved_at` + ); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP COLUMN followup_at` + ); + }, +}; diff --git a/database/migrations/20260811120000-add-ext-data-to-inbox-group.js b/database/migrations/20260811120000-add-ext-data-to-inbox-group.js new file mode 100644 index 0000000..402f25e --- /dev/null +++ b/database/migrations/20260811120000-add-ext-data-to-inbox-group.js @@ -0,0 +1,20 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.ext_data) return; + + await queryInterface.addColumn(TABLE_NAME, 'ext_data', { + type: Sequelize.JSON, + allowNull: true, + comment: '群扩展数据(IM平台信息等)', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'ext_data'); + }, +}; diff --git a/database/migrations/20260812120000-add-order-id-to-after-sale.js b/database/migrations/20260812120000-add-order-id-to-after-sale.js new file mode 100644 index 0000000..0b0c1f8 --- /dev/null +++ b/database/migrations/20260812120000-add-order-id-to-after-sale.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_after_sale', 'order_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID(关联 wms_order.id),快递反馈建单时从 wms_order_express.order_id 填入', + after: 'waybill_no', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_after_sale', 'order_id'); + }, +}; diff --git a/database/migrations/20260812150000-remove-order-delivery-id-from-after-sale.js b/database/migrations/20260812150000-remove-order-delivery-id-from-after-sale.js new file mode 100644 index 0000000..84edcab --- /dev/null +++ b/database/migrations/20260812150000-remove-order-delivery-id-from-after-sale.js @@ -0,0 +1,40 @@ +'use strict'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING, BIGINT } = Sequelize; + const tableName = 'wms_after_sale'; + + // 检查列是否存在 + const [columns] = await queryInterface.sequelize.query( + `SHOW COLUMNS FROM \`${tableName}\` LIKE 'order_delivery_id'` + ); + if (Array.isArray(columns) && columns.length > 0) { + await queryInterface.removeColumn(tableName, 'order_delivery_id'); + } + + const [columns2] = await queryInterface.sequelize.query( + `SHOW COLUMNS FROM \`${tableName}\` LIKE 'order_delivery_no'` + ); + if (Array.isArray(columns2) && columns2.length > 0) { + await queryInterface.removeColumn(tableName, 'order_delivery_no'); + } + }, + + down: async (queryInterface, Sequelize) => { + const { STRING, BIGINT } = Sequelize; + const tableName = 'wms_after_sale'; + + await queryInterface.addColumn(tableName, 'order_delivery_id', { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '发货订单ID(关联 wms_order_delivery.id)', + }); + + await queryInterface.addColumn(tableName, 'order_delivery_no', { + type: STRING(50), + allowNull: true, + comment: '发货订单号(冗余字段)', + }); + }, +}; diff --git a/database/migrations/20260812160000-create-wms-return-received.js b/database/migrations/20260812160000-create-wms-return-received.js new file mode 100644 index 0000000..bd4c4a3 --- /dev/null +++ b/database/migrations/20260812160000-create-wms-return-received.js @@ -0,0 +1,87 @@ +'use strict'; + +/** + * 创建退回收到登记表 wms_return_received。 + * + * 字段:仓库隔离 warehouse_id、退回收件运单号 waybill_code、扫描日期 scan_date、 + * 扫描人员 scanner_id/scanner_name、运单关联 order_express_id/order_id/store_id(非必填)。 + * + * 索引: + * idx_warehouse_waybill_scan_date(30 日幂等查询) + * idx_warehouse_scan_date(仓库+日期隔离查询) + * idx_scanner_id / idx_order_express_id / idx_store_id + */ + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE } = Sequelize; + await queryInterface.createTable('wms_return_received', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '退回收件运单号(扫描到的退回包裹单号)', + }, + scan_date: { + type: DATE, + allowNull: false, + comment: '扫描收到日期', + }, + scanner_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '扫描人员工号ID(employees_id)', + }, + scanner_name: { + type: STRING(50), + allowNull: false, + comment: '扫描人员工号名称快照(employees_name / real_name)', + }, + order_express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '运单表关联字段,关联 wms_order_express.id;非必填', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID,方便快速匹配;非必填', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,原单退回时回填,用于查货主备注', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex('wms_return_received', [ 'warehouse_id', 'waybill_code', 'scan_date' ], { name: 'idx_warehouse_waybill_scan_date' }); + await queryInterface.addIndex('wms_return_received', [ 'warehouse_id', 'scan_date' ], { name: 'idx_warehouse_scan_date' }); + await queryInterface.addIndex('wms_return_received', [ 'scanner_id' ], { name: 'idx_scanner_id' }); + await queryInterface.addIndex('wms_return_received', [ 'order_express_id' ], { name: 'idx_order_express_id' }); + await queryInterface.addIndex('wms_return_received', [ 'store_id' ], { name: 'idx_store_id' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable('wms_return_received'); + }, +}; diff --git a/database/migrations/20260813100000-create-return-received-permissions.js b/database/migrations/20260813100000-create-return-received-permissions.js new file mode 100644 index 0000000..bfc1ef0 --- /dev/null +++ b/database/migrations/20260813100000-create-return-received-permissions.js @@ -0,0 +1,98 @@ +'use strict'; + +/** + * 退回收到模块权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID): + * 527 — returnReceived.create API:退回收件扫码登记 + * 528 — returnReceived.list API:退回收件列表查询 + * 529 — returnReceived.delete API:退回收件删除 + * + * 角色授权(系统预设角色,不含通配符角色): + * 527(扫码登记)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 528(列表)、529(删除)→ 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 527: [ 27, 26 ], + 528: [ 30, 28 ], + 529: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 527, 'returnReceived.create', 'API:退回收件扫码登记' ], + [ 528, 'returnReceived.list', 'API:退回收件列表查询' ], + [ 529, 'returnReceived.delete', 'API:退回收件删除' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [ 527, 528, 529 ]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/database/migrations/20260813110000-add-return-received-menu-permission.js b/database/migrations/20260813110000-add-return-received-menu-permission.js new file mode 100644 index 0000000..38823d6 --- /dev/null +++ b/database/migrations/20260813110000-add-return-received-menu-permission.js @@ -0,0 +1,82 @@ +'use strict'; + +/** + * 快递菜单下新增 web_pages 子菜单「快递收件」(id=530),并授权客服员工及以上角色。 + * + * 权限明细: + * 530 — returnReceived(web_pages 菜单,parent_id=19 快递/物流) + * + * 角色授权(系统预设角色,不含通配符角色): + * 530 → 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建菜单权限;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 530: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 web_pages 菜单权限(固定 ID,parent_id=19 快递/物流)── + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ 530, 'returnReceived', '@/views/express/returnReceived/index', 'returnReceived', null, '快递收件', null, 0, 0, 19, 'web_pages', 1, 1 ] } + ); + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 530` + ); + }, +}; diff --git a/database/migrations/20260813120000-create-wms-return-unpack.js b/database/migrations/20260813120000-create-wms-return-unpack.js new file mode 100644 index 0000000..582d33e --- /dev/null +++ b/database/migrations/20260813120000-create-wms-return-unpack.js @@ -0,0 +1,145 @@ +'use strict'; + +/** + * 创建退回拆包主表 wms_return_unpack。 + * + * 字段:仓库隔离 warehouse_id、拆包单号 unpack_no(RP+YYYYMMDD+6位序号)、 + * 关联退回收到单 return_received_id(非必填)、运单号 waybill_code、拆包日期 unpack_date、 + * 起止时间 start_time/end_time、拆包人 unpacker_id/unpacker_name、状态 status/detail_status、 + * 汇总 total_items/total_quantity、原单关联 order_express_id/order_id/store_id(非必填)、 + * 摄像头列表 camera_ids(JSON)、备注 remark。 + * + * 索引: + * uk_unpack_no(单号唯一) + * idx_warehouse_unpack_date(仓库+日期隔离查询) + * idx_return_received_id / idx_waybill_code / idx_order_express_id + * idx_unpacker_id / idx_start_time / idx_store_id + */ + +const TABLE_NAME = 'wms_return_unpack'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + unpack_no: { + type: STRING(50), + allowNull: false, + comment: '拆包单号,RP+YYYYMMDD+6位序号', + }, + return_received_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联退回收到表 wms_return_received.id;非必填', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '拆包的运单号(退回包裹运单号)', + }, + unpack_date: { + type: DATE, + allowNull: false, + comment: '拆包日期', + }, + start_time: { + type: DATE, + allowNull: true, + comment: '拆包开始时间', + }, + end_time: { + type: DATE, + allowNull: true, + comment: '拆包结束时间', + }, + unpacker_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '拆包人员工号ID(employees_id)', + }, + unpacker_name: { + type: STRING(50), + allowNull: false, + comment: '拆包人员工号名称快照(employees_name / real_name)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'unpacking', + comment: '拆包状态:unpacking/completed/cancelled', + }, + detail_status: { + type: STRING(30), + allowNull: false, + defaultValue: 'none_recognized', + comment: '明细识别状态:none_recognized/partial_recognized/all_recognized', + }, + total_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '物品种类数(明细行数)', + }, + total_quantity: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '物品总数量(明细数量合计)', + }, + order_express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '原运单ID,关联 wms_order_express.id;原单退回时回填', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '原订单ID,便于快速匹配;原单退回时回填', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,原单退回/识别到系统商品时回填', + }, + camera_ids: { + type: Sequelize.JSON, + allowNull: true, + comment: '摄像头ID列表,如 [1,2,3](参考 wms_pack_task.device_ids)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'unpack_no' ], { unique: true, name: 'uk_unpack_no' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'unpack_date' ], { name: 'idx_warehouse_unpack_date' }); + await queryInterface.addIndex(TABLE_NAME, [ 'return_received_id' ], { name: 'idx_return_received_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'order_express_id' ], { name: 'idx_order_express_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'unpacker_id' ], { name: 'idx_unpacker_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'start_time' ], { name: 'idx_start_time' }); + await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: 'idx_store_id' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260813120100-create-wms-return-unpack-detail.js b/database/migrations/20260813120100-create-wms-return-unpack-detail.js new file mode 100644 index 0000000..df251fe --- /dev/null +++ b/database/migrations/20260813120100-create-wms-return-unpack-detail.js @@ -0,0 +1,110 @@ +'use strict'; + +/** + * 创建退回拆包明细表 wms_return_unpack_detail。 + * + * 字段:关联主表 unpack_id、仓库冗余 warehouse_id、扫描条码 barcode(可空,仅记录)、 + * 系统商品 stock_id(可空,关联 wms_stock_warehouse.id)、识别标记 is_recognized、 + * 快照 item_code/item_name/spec/product_snapshot、数量 quantity、产品状态 product_status、备注 remark。 + * + * 索引: + * idx_unpack_id(按拆包单查明细,最高频) + * idx_warehouse_barcode(仓库+条码) + * idx_stock_id(按系统商品反查) + * idx_barcode(按条码查询) + * + * 说明:同一拆包单内可能多次扫描同一条码,明细不设 barcode 唯一约束。 + */ + +const TABLE_NAME = 'wms_return_unpack_detail'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, DATE, TEXT, TINYINT } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + unpack_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联拆包主表 wms_return_unpack.id', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + barcode: { + type: STRING(100), + allowNull: true, + comment: '扫描条码(前端可选传入,仅作记录;后端不用于识别)', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_stock_warehouse.id;识别到系统商品时回填,非识别为空', + }, + is_recognized: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否识别:1=识别到系统商品,0=非识别物品', + }, + item_code: { + type: STRING(50), + allowNull: true, + comment: '商品编码快照(识别时回填)', + }, + item_name: { + type: STRING(255), + allowNull: true, + comment: '物品名称(识别时回填;非识别时可手工补录)', + }, + spec: { + type: STRING(100), + allowNull: true, + comment: '规格快照(sku_property)', + }, + quantity: { + type: INTEGER(11), + allowNull: false, + defaultValue: 1, + comment: '数量', + }, + product_status: { + type: STRING(20), + allowNull: false, + defaultValue: 'normal', + comment: '产品状态:normal-正常,damaged-破损', + }, + product_snapshot: { + type: TEXT, + allowNull: true, + comment: '商品信息快照(JSON),识别时回填,防止商品资料变更后历史丢失', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'unpack_id' ], { name: 'idx_unpack_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'barcode' ], { name: 'idx_warehouse_barcode' }); + await queryInterface.addIndex(TABLE_NAME, [ 'stock_id' ], { name: 'idx_stock_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'barcode' ], { name: 'idx_barcode' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260813120200-create-wms-return-unpack-video.js b/database/migrations/20260813120200-create-wms-return-unpack-video.js new file mode 100644 index 0000000..268e531 --- /dev/null +++ b/database/migrations/20260813120200-create-wms-return-unpack-video.js @@ -0,0 +1,66 @@ +'use strict'; + +/** + * 创建退回拆包视频记录表 wms_return_unpack_video(参考 wms_pack_task_video)。 + * + * 字段:关联主表 unpack_id、摄像头 camera_id(非必填)、视频地址 video_url、状态 status、 + * 备注 remark、软删除 deleted_at(paranoid)。 + * + * 索引:idx_unpack_id(按拆包单查视频)、idx_camera_id(按摄像头反查)、idx_deleted_at(软删除优化)。 + */ + +const TABLE_NAME = 'wms_return_unpack_video'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE, ENUM } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + unpack_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联拆包主表 wms_return_unpack.id', + }, + camera_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '摄像头设备ID,关联 wms_camera.id', + }, + video_url: { + type: STRING(500), + allowNull: false, + comment: '视频地址(录像回放URL)', + }, + status: { + type: ENUM('created', 'recording', 'completed', 'failed'), + allowNull: false, + defaultValue: 'created', + comment: '状态:created/recording/completed/failed', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + deleted_at: { type: DATE, allowNull: true, comment: '软删除时间' }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'unpack_id' ], { name: 'idx_unpack_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'camera_id' ], { name: 'idx_camera_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260813120300-create-wms-return-query-log.js b/database/migrations/20260813120300-create-wms-return-query-log.js new file mode 100644 index 0000000..80e46f3 --- /dev/null +++ b/database/migrations/20260813120300-create-wms-return-query-log.js @@ -0,0 +1,75 @@ +'use strict'; + +/** + * 创建退回查询记录表 wms_return_query_log。 + * + * 用途:登记「货主未退回、但做过查询退回」的运单号,仓库 + 货主隔离。 + * 创建拆包单未命中原单时,据此反查运单号对应的货主并回写 store_id(限最近 3 个月内登记)。 + * is_back / is_notified 供定时任务扫描拆包通知;拆包单提交确认时更新 is_back=1。 + * + * 索引: + * idx_warehouse_store_waybill(仓库+货主+运单号,核心) + * idx_warehouse_store(仓库+货主隔离查询) + * idx_waybill_code(按运单号查询) + */ + +const TABLE_NAME = 'wms_return_query_log'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE, TINYINT } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(隔离维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(隔离维度)', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '查询过的运单号', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + is_notified: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否已通知:0=未通知,1=已通知', + }, + is_back: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否退回:0=未退回,1=已退回', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'store_id', 'waybill_code' ], { name: 'idx_warehouse_store_waybill' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'store_id' ], { name: 'idx_warehouse_store' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260813130000-create-return-unpack-permissions.js b/database/migrations/20260813130000-create-return-unpack-permissions.js new file mode 100644 index 0000000..7890329 --- /dev/null +++ b/database/migrations/20260813130000-create-return-unpack-permissions.js @@ -0,0 +1,119 @@ +'use strict'; + +/** + * 退回拆包模块权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 540-549,550 预留): + * 540 — returnUnpack.create API:退回拆包开单 + * 541 — returnUnpack.addDetail API:退回拆包录明细 + * 542 — returnUnpack.updateDetail API:退回拆包更新明细 + * 543 — returnUnpack.removeDetail API:退回拆包移除明细 + * 544 — returnUnpack.cancel API:退回拆包取消 + * 545 — returnUnpack.submit API:退回拆包提交确认 + * 546 — returnUnpack.list API:退回拆包列表查询 + * 547 — returnUnpack.detailList API:退回拆包明细列表 + * 548 — returnUnpack.detail API:退回拆包详情 + * 549 — returnUnpack.delete API:退回拆包删除 + * + * 角色授权(系统预设角色,不含通配符角色): + * 作业类(540-545)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 查询/删除类(546-549)→ 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 540: [ 27, 26 ], + 541: [ 27, 26 ], + 542: [ 27, 26 ], + 543: [ 27, 26 ], + 544: [ 27, 26 ], + 545: [ 27, 26 ], + 546: [ 30, 28 ], + 547: [ 30, 28 ], + 548: [ 30, 28 ], + 549: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 540, 'returnUnpack.create', 'API:退回拆包开单' ], + [ 541, 'returnUnpack.addDetail', 'API:退回拆包录明细' ], + [ 542, 'returnUnpack.updateDetail', 'API:退回拆包更新明细' ], + [ 543, 'returnUnpack.removeDetail', 'API:退回拆包移除明细' ], + [ 544, 'returnUnpack.cancel', 'API:退回拆包取消' ], + [ 545, 'returnUnpack.submit', 'API:退回拆包提交确认' ], + [ 546, 'returnUnpack.list', 'API:退回拆包列表查询' ], + [ 547, 'returnUnpack.detailList', 'API:退回拆包明细列表' ], + [ 548, 'returnUnpack.detail', 'API:退回拆包详情' ], + [ 549, 'returnUnpack.delete', 'API:退回拆包删除' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [ 540, 541, 542, 543, 544, 545, 546, 547, 548, 549 ]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js b/database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js new file mode 100644 index 0000000..33c8646 --- /dev/null +++ b/database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js @@ -0,0 +1,118 @@ +'use strict'; + +/** + * 补齐 wms_order_delivery 基表相对模型缺失的 25 列。 + * + * 背景:app/model/order_delivery.js 声明 92 个字段,但基表只有 67 列, + * 缺列导致按模型全字段 SELECT(如 afterSale._resolveOrderDetail 先查基表)时 + * 报 Unknown column 'extend_props' 等错误。 + * 分表(wms_order_delivery_100000 等)均已有这些列,本迁移以分表结构为参照补齐基表。 + * + * 修复后 afterSale._resolveOrderDetail 查基表不再抛错(查无数据时回退工厂分表)。 + */ + +const TABLE_NAME = 'wms_order_delivery'; + +/** 缺失列定义(类型/是否可空/默认值/注释),与分表结构一致 */ +const MISSING_COLUMNS = [ + { name: 'extend_props', type: 'JSON', allowNull: true, defaultValue: null, comment: '订单扩展属性' }, + { name: 'create_channel', type: 'STRING(20)', allowNull: false, defaultValue: 'MANUAL', comment: '创建来源渠道' }, + { name: 'sys_platform_code', type: 'STRING(50)', allowNull: true, defaultValue: null, comment: '系统平台编码' }, + { name: 'sys_platform_name', type: 'STRING(200)', allowNull: true, defaultValue: null, comment: '系统平台名称' }, + { name: 'buyer_message', type: 'STRING(500)', allowNull: true, defaultValue: null, comment: '买家留言' }, + { name: 'seller_message', type: 'STRING(500)', allowNull: true, defaultValue: null, comment: '卖家留言' }, + { name: 'remark', type: 'STRING(500)', allowNull: true, defaultValue: null, comment: '备注' }, + { name: 'sys_logistics_code', type: 'STRING(50)', allowNull: true, defaultValue: null, comment: '系统物流公司编码' }, + { name: 'sys_logistics_name', type: 'STRING(200)', allowNull: true, defaultValue: null, comment: '系统物流公司名称' }, + { name: 'basket_number', type: 'STRING(50)', allowNull: true, defaultValue: null, comment: '筐号' }, + { name: 'from_key', type: 'INTEGER(11)', allowNull: true, defaultValue: null, comment: '来源键' }, + { name: 'items', type: 'TEXT', allowNull: true, defaultValue: null, comment: '商品JSON字符串' }, + { name: 'items_count', type: 'SMALLINT(5).UNSIGNED', allowNull: false, defaultValue: 0, comment: '商品种类数' }, + { name: 'items_total', type: 'INTEGER(10).UNSIGNED', allowNull: false, defaultValue: 0, comment: '商品总数' }, + { name: 'items_weight', type: 'INTEGER(11)', allowNull: false, defaultValue: 0, comment: '总重量(g)' }, + { name: 'items_hash', type: 'CHAR(32)', allowNull: false, defaultValue: '', comment: 'MD5哈希值(32位)' }, + { name: 'items_crc', type: 'INTEGER(10).UNSIGNED', allowNull: false, defaultValue: 0, comment: 'CRC32校验码' }, + { name: 'wave_id', type: 'BIGINT(20)', allowNull: false, defaultValue: 0, comment: '波次ID,0表示未分配' }, + { name: 'wave_no', type: 'STRING(50)', allowNull: false, defaultValue: '', comment: '波次号,空字符串表示未分配' }, + { name: 'wave_strategy_version', type: 'INTEGER(10)', allowNull: false, defaultValue: 0, comment: '波次策略版本号' }, + { name: 'wave_scan_result', type: 'INTEGER(10)', allowNull: false, defaultValue: 0, comment: '波次扫描结果,0未扫描' }, + { name: 'sended_status', type: 'ENUM', enumValues: [ 'none', 'padding', 'fin', 'error' ], allowNull: true, defaultValue: 'none', comment: '发货状态机' }, + { name: 'recheck_status', type: 'STRING(20)', allowNull: true, defaultValue: 'none', comment: '复核状态' }, + { name: 'recheck_time', type: 'DATE', allowNull: true, defaultValue: null, comment: '复核时间' }, + { name: 'print_lock_status', type: 'ENUM', enumValues: [ 'none', 'warehouse' ], allowNull: true, defaultValue: 'none', comment: '打印锁定状态机' }, +]; + +/** + * 将列定义转为 Sequelize 字段描述。 + * + * @param {Object} Sequelize Sequelize 构造器。 + * @param {Object} def 列定义(name/type/allowNull/defaultValue/comment)。 + * @return {Object} Sequelize addColumn 字段描述。 + */ +function toColumnDef(Sequelize, def) { + let type; + if (def.type === 'ENUM') { + type = Sequelize.ENUM(...def.enumValues); + } else if (def.type === 'JSON') { + type = Sequelize.JSON; + } else if (def.type === 'DATE') { + type = Sequelize.DATE; + } else if (def.type === 'TEXT') { + type = Sequelize.TEXT; + } else if (def.type === 'CHAR(32)') { + type = Sequelize.CHAR(32); + } else { + const match = def.type.match(/^([A-Z]+)(?:\(([^)]+)\))?(?:\.([A-Z]+))?$/); + if (!match) { + throw new Error(`无法解析列类型: ${def.type}`); + } + const base = match[1]; + const args = match[2] ? match[2].split(',').map(s => Number(s.trim())) : []; + const unsigned = Boolean(match[3] && match[3] === 'UNSIGNED'); + switch (base) { + case 'STRING': + type = Sequelize.STRING(args[0]); + break; + case 'INTEGER': + type = Sequelize.INTEGER(args[0]); + break; + case 'BIGINT': + type = Sequelize.BIGINT(args[0]); + break; + case 'SMALLINT': + type = Sequelize.SMALLINT(args[0]); + break; + default: + throw new Error(`无法解析列类型: ${def.type}`); + } + if (unsigned) { + type = type.UNSIGNED; + } + } + + const columnDef = { + type, + allowNull: def.allowNull, + comment: def.comment, + }; + if (def.defaultValue !== null && def.defaultValue !== undefined) { + columnDef.defaultValue = def.defaultValue; + } + return columnDef; +} + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + for (const def of MISSING_COLUMNS) { + await queryInterface.addColumn(TABLE_NAME, def.name, toColumnDef(Sequelize, def)); + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + for (const def of MISSING_COLUMNS) { + await queryInterface.removeColumn(TABLE_NAME, def.name); + } + }, +}; diff --git a/database/migrations/20260813150000-create-wms-number-sequence.js b/database/migrations/20260813150000-create-wms-number-sequence.js new file mode 100644 index 0000000..9763d05 --- /dev/null +++ b/database/migrations/20260813150000-create-wms-number-sequence.js @@ -0,0 +1,63 @@ +'use strict'; + +/** + * 创建业务单号序列表 wms_number_sequence。 + * + * 用途:按「仓库 + 业务类型 + 日期」维度原子分配单号序号, + * 取代「查当日最大序号+1」的并发撞号方案。 + * 取号 SQL:INSERT ... ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(current_seq + 1) + * (同连接内再 SELECT LAST_INSERT_ID() 取回本次分配序号)。 + * + * 索引:uk_warehouse_biz_date(仓库+业务类型+日期 唯一,原子取号的幂等键)。 + */ + +const TABLE_NAME = 'wms_number_sequence'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, CHAR, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(序号隔离维度)', + }, + biz_type: { + type: STRING(30), + allowNull: false, + comment: '业务类型,如 return_unpack(退回拆包单号)', + }, + date_part: { + type: CHAR(8), + allowNull: false, + comment: '日期片段 YYYYMMDD', + }, + current_seq: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '当前已分配序号(原子递增)', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'biz_type', 'date_part' ], { + unique: true, + name: 'uk_warehouse_biz_date', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260813160000-create-return-waybill-permissions.js b/database/migrations/20260813160000-create-return-waybill-permissions.js new file mode 100644 index 0000000..8710091 --- /dev/null +++ b/database/migrations/20260813160000-create-return-waybill-permissions.js @@ -0,0 +1,104 @@ +'use strict'; + +/** + * 运单退回登记模块权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 551-555,550 预留): + * 551 — returnWaybill.create API:运单退回登记 + * 552 — returnWaybill.update API:运单退回登记修改 + * 553 — returnWaybill.list API:运单退回登记列表 + * 554 — returnWaybill.detail API:运单退回登记详情 + * 555 — returnWaybill.delete API:运单退回登记删除 + * + * 角色授权(系统预设角色,不含通配符角色): + * 作业类(551-552)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 查询/删除类(553-555)→ 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 551: [ 27, 26 ], + 552: [ 27, 26 ], + 553: [ 30, 28 ], + 554: [ 30, 28 ], + 555: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 551, 'returnWaybill.create', 'API:运单退回登记' ], + [ 552, 'returnWaybill.update', 'API:运单退回登记修改' ], + [ 553, 'returnWaybill.list', 'API:运单退回登记列表' ], + [ 554, 'returnWaybill.detail', 'API:运单退回登记详情' ], + [ 555, 'returnWaybill.delete', 'API:运单退回登记删除' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [ 551, 552, 553, 554, 555 ]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/database/migrations/20260813170000-add-return-unpack-order-info.js b/database/migrations/20260813170000-add-return-unpack-order-info.js new file mode 100644 index 0000000..f0f5a9c --- /dev/null +++ b/database/migrations/20260813170000-add-return-unpack-order-info.js @@ -0,0 +1,36 @@ +'use strict'; + +/** + * wms_return_unpack 主表补充订单信息快照字段: + * - source_order_codes:平台交易单号(原单退回时回填,来源 wms_order_express.source_order_codes) + * - shop_name:店铺名称(货主自定义店铺名称快照,来源 wms_store_warehouse.store_remask) + * + * 用途:退回查询(查退回模板消息)直接取主表快照,避免依赖原运单/订单表实时关联。 + */ + +const TABLE_NAME = 'wms_return_unpack'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { STRING } = Sequelize; + await queryInterface.addColumn(TABLE_NAME, 'source_order_codes', { + type: STRING(500), + allowNull: true, + comment: '平台交易单号快照(原单退回时回填)', + after: 'store_id', + }); + await queryInterface.addColumn(TABLE_NAME, 'shop_name', { + type: STRING(50), + allowNull: true, + comment: '店铺名称快照(货主自定义店铺名称 store_remask)', + after: 'source_order_codes', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn(TABLE_NAME, 'shop_name'); + await queryInterface.removeColumn(TABLE_NAME, 'source_order_codes'); + }, +}; diff --git a/database/migrations/20260815100000-fix-inbox-group-unique-index.js b/database/migrations/20260815100000-fix-inbox-group-unique-index.js new file mode 100644 index 0000000..1d70c66 --- /dev/null +++ b/database/migrations/20260815100000-fix-inbox-group-unique-index.js @@ -0,0 +1,138 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +/** 合并重复记录时允许从重复行补齐到保留行的字段 */ +const FILLABLE_FIELDS = [ + 'store_id', + 'group_type', + 'sub_type', + 'source_type', + 'source_extra', + 'express_interfaces', + 'system_express_code', +]; + +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName); +} + +async function dropIndexIfExists(queryInterface, tableName, indexName) { + if (await indexExists(queryInterface, tableName, indexName)) { + await queryInterface.removeIndex(tableName, indexName); + console.log(`[idx] ${tableName}.${indexName} 已删除`); + } +} + +async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) { + if (await indexExists(queryInterface, tableName, indexName)) { + console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`); + return; + } + await queryInterface.addIndex(tableName, options.fields, { + name: indexName, + unique: !!options.unique, + }); + console.log(`[idx] ${tableName}.${indexName} 已创建`); +} + +/** + * 合并 (warehouse_id, group_id) 相同的重复群记录,为唯一索引铺路。 + * 保留策略:is_blocked=0(启用)优先,其次 created_at 最早; + * 群名称取 updated_at 最新一条的名称;其余字段为空时从重复行补齐;其余行软删除。 + * + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} + */ +async function mergeDuplicateGroups(queryInterface) { + const q = queryInterface.sequelize; + + const dupGroups = await q.query( + `SELECT warehouse_id, group_id + FROM \`${TABLE_NAME}\` + WHERE group_id IS NOT NULL AND group_id <> '' AND deleted_at IS NULL + GROUP BY warehouse_id, group_id + HAVING COUNT(*) > 1`, + { type: q.QueryTypes.SELECT } + ); + + for (const g of dupGroups) { + const rows = await q.query( + `SELECT * FROM \`${TABLE_NAME}\` + WHERE warehouse_id = ? AND group_id = ? AND deleted_at IS NULL + ORDER BY is_blocked ASC, created_at ASC, id ASC`, + { replacements: [ g.warehouse_id, g.group_id ], type: q.QueryTypes.SELECT } + ); + if (!rows || rows.length < 2) continue; + + const keep = rows[0]; + const nameRow = [ ...rows ].sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))[0]; + const dropIds = rows.filter(r => r.id !== keep.id).map(r => r.id); + + const updates = {}; + if (keep.group_name !== nameRow.group_name) { + updates.group_name = nameRow.group_name; + } + for (const field of FILLABLE_FIELDS) { + if (keep[field] === null || keep[field] === undefined || keep[field] === '') { + for (const row of rows) { + if (row.id === keep.id) continue; + if (row[field] !== null && row[field] !== undefined && row[field] !== '') { + updates[field] = row[field]; + break; + } + } + } + } + + if (Object.keys(updates).length > 0) { + const setClauses = Object.keys(updates).map(k => `\`${k}\` = ?`).join(', '); + await q.query( + `UPDATE \`${TABLE_NAME}\` SET ${setClauses}, updated_at = NOW() WHERE id = ?`, + { replacements: [ ...Object.values(updates), keep.id ] } + ); + console.log(`[dedupe] 保留 id=${keep.id} group_id=${g.group_id},更新: ${JSON.stringify(updates)}`); + } + + const placeholders = dropIds.map(() => '?').join(','); + await q.query( + `UPDATE \`${TABLE_NAME}\` SET deleted_at = NOW() WHERE id IN (${placeholders}) AND deleted_at IS NULL`, + { replacements: dropIds } + ); + console.log(`[dedupe] 软删除 id=${dropIds.join(',')} group_id=${g.group_id}`); + } +} + +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + // 1. 清理 (warehouse_id, group_id) 重复记录,否则唯一索引无法创建 + await mergeDuplicateGroups(queryInterface); + + // 2. 删除错误的唯一索引 uk_group_warehouse(group_name, warehouse_id) + // 群名称会变化,不应作为唯一约束维度 + await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_group_warehouse'); + + // 3. 删除与唯一索引覆盖范围重复的普通索引 idx_warehouse_group_id + await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_warehouse_group_id'); + + // 4. 新建唯一索引 (warehouse_id, group_id) + // group_id 允许 NULL,MySQL 唯一索引允许多个 NULL,不影响无群ID的记录 + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_warehouse_group_id', { + fields: [ 'warehouse_id', 'group_id' ], + unique: true, + }); + }, + + down: async queryInterface => { + await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_warehouse_group_id'); + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_warehouse_group_id', { + fields: [ 'warehouse_id', 'group_id' ], + }); + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_group_warehouse', { + fields: [ 'group_name', 'warehouse_id' ], + unique: true, + }); + }, +}; diff --git a/database/migrations/20260817120000-add-inbox-group-reset-permission.js b/database/migrations/20260817120000-add-inbox-group-reset-permission.js new file mode 100644 index 0000000..e60f410 --- /dev/null +++ b/database/migrations/20260817120000-add-inbox-group-reset-permission.js @@ -0,0 +1,117 @@ +'use strict'; + +/** + * inbox.group.reset 群类型清空接口权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 558,556 已被「运单退回」web 页面占用): + * 558 — inbox.group.reset API:清空群类型配置(重置群) + * + * 角色授权(客服员工及以上链路): + * 30(客服组-员工) → 28(客服组-主管) → 8(经理,通配符 * 自动拥有) + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 558: [ 30, 28, 8 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 558, 'inbox.group.reset', 'API:清空群类型配置' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = typeof record.permissions === 'string' + ? JSON.parse(record.permissions) + : record.permissions; + } catch (e) { + perms = null; + } + + if (!Array.isArray(perms)) { + continue; + } + + if (!perms.includes(permId)) { + perms.push(permId); + perms.sort((a, b) => Number(a) - Number(b)); + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + 'DELETE FROM `wms_permission` WHERE id = 558' + ); + + const roleIds = [ 30, 28, 8 ]; + for (const roleId of roleIds) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record || record.permissions === '*') { + continue; + } + + let perms; + try { + perms = typeof record.permissions === 'string' + ? JSON.parse(record.permissions) + : record.permissions; + } catch (e) { + perms = null; + } + if (!Array.isArray(perms) || !perms.includes(558)) { + continue; + } + + perms = perms.filter(p => p !== 558); + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + }, +}; diff --git a/database/migrations/20260818190000-alter-wms-order-items-ext-code-to-text.js b/database/migrations/20260818190000-alter-wms-order-items-ext-code-to-text.js new file mode 100644 index 0000000..4c3e8c8 --- /dev/null +++ b/database/migrations/20260818190000-alter-wms-order-items-ext-code-to-text.js @@ -0,0 +1,79 @@ +'use strict'; + +/** + * 将订单商品表 ext_code 列从 VARCHAR(50) 改为 TEXT。 + * + * 背景: + * wms_order_items.ext_code 原为 VARCHAR(50),上游平台(奇门/仓库接口)下发的 + * 商品外部编码可能超过 50 字符,INSERT 时报 + * "Data too long for column 'ext_code' at row 1",导致整个订单创建失败。 + * + * 变更: + * 1. 主表 wms_order_items 及全部已有分表 wms_order_items_{warehouseId} + * (含 _dispatch/_history 后缀)的 ext_code 列统一改为 TEXT。 + * 2. 模型定义同步改为 TEXT(app/model/order_items.js),后续新建分表直接 + * 使用 TEXT,OrderItemsFactory 的结构对齐逻辑不会再回退该列。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 + * @return {Promise} 无返回值 + */ +async function listOrderItemsTables(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_items' OR TABLE_NAME LIKE 'wms_order_items\\_%') + `); + + return (Array.isArray(rows) ? rows : []).map(row => row.TABLE_NAME); +} + +async function hasColumn(queryInterface, tableName, columnName) { + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return (Array.isArray(columns) ? columns : []).length > 0; +} + +module.exports = { + up: async queryInterface => { + const tableNames = await listOrderItemsTables(queryInterface); + let alteredCount = 0; + + for (const tableName of tableNames) { + if (!(await hasColumn(queryInterface, tableName, 'ext_code'))) { + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` MODIFY \`ext_code\` TEXT NULL COMMENT '外部编码'` + ); + alteredCount += 1; + } + + console.log(`[migrate] wms_order_items ext_code → TEXT,共处理 ${alteredCount} 张表`); + }, + + down: async queryInterface => { + const tableNames = await listOrderItemsTables(queryInterface); + + for (const tableName of tableNames) { + if (!(await hasColumn(queryInterface, tableName, 'ext_code'))) { + continue; + } + + // 注意:若已有数据超过 50 字符,回滚会失败,需先人工截断数据 + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` MODIFY \`ext_code\` VARCHAR(50) NULL COMMENT '外部编码'` + ); + } + }, +}; diff --git a/database/migrations/20260820120000-alter-wms-wave-batch-item-detail-machine-to-text.js b/database/migrations/20260820120000-alter-wms-wave-batch-item-detail-machine-to-text.js new file mode 100644 index 0000000..b88ac11 --- /dev/null +++ b/database/migrations/20260820120000-alter-wms-wave-batch-item-detail-machine-to-text.js @@ -0,0 +1,120 @@ +'use strict'; + +/** + * 将 wms_wave_batch.item_detail_machine 列从 VARCHAR(1024) 改为 TEXT。 + * + * 背景: + * buildMachineStructureToken 生成的结构标识为 + * `v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key`, + * 其中 item_part 与 item_snapshot_key 均经 encodeURIComponent 编码, + * 多商品订单下编码后的长度可能远超 1024,抓取分组 INSERT 时报 + * "Data too long for column 'item_detail_machine' at row 1"。 + * + * 变更: + * 1. wms_wave_batch.item_detail_machine: VARCHAR(1024) → TEXT + * 2. 索引 idx_wave_item_machine_prefix 维持前缀索引 + * (item_detail_machine(191)),TEXT 列前缀索引仍合法; + * 若存量环境存在全列索引则先删除。 + * 3. 模型定义同步改为 TEXT(app/model/wave_batch.js)。 + */ + +const TABLE_NAME = 'wms_wave_batch'; +const COLUMN_NAME = 'item_detail_machine'; +const INDEX_NAME = 'idx_wave_item_machine_prefix'; + +async function hasColumn(queryInterface, tableName, columnName) { + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return (Array.isArray(columns) ? columns : []).length > 0; +} + +async function listColumnIndexes(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT DISTINCT INDEX_NAME, SUB_PART + FROM INFORMATION_SCHEMA.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return Array.isArray(rows) ? rows : []; +} + +module.exports = { + up: async queryInterface => { + if (!(await hasColumn(queryInterface, TABLE_NAME, COLUMN_NAME))) { + console.log(`[migrate] ${TABLE_NAME}.${COLUMN_NAME} 列不存在,跳过`); + return; + } + + // ── 1. 全列索引对 TEXT 无效(无前缀),先删除存量全列索引 ── + const existingIndexes = await listColumnIndexes(queryInterface, TABLE_NAME, COLUMN_NAME); + for (const idx of existingIndexes) { + const indexName = String(idx.INDEX_NAME || '').trim(); + const subPart = idx.SUB_PART === null || idx.SUB_PART === undefined + ? null + : Number(idx.SUB_PART); + if (!indexName || subPart) { + continue; + } + + try { + await queryInterface.removeIndex(TABLE_NAME, indexName); + console.log(`[migrate] 已移除全列索引 ${indexName}(TEXT 列要求前缀索引)`); + } catch (e) { + const msg = String(e && e.message || ''); + if (!msg.includes('check that it exists') && !msg.includes('exist')) { + console.warn(`[migrate] 移除全列索引 ${indexName} 时出现非预期错误: ${msg}`); + } + } + } + + // ── 2. 修改列类型为 TEXT ── + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY \`${COLUMN_NAME}\` TEXT NULL COMMENT '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key'` + ); + console.log(`[migrate] ${TABLE_NAME}.${COLUMN_NAME} VARCHAR(1024) → TEXT`); + + // ── 3. 确保前缀索引存在 ── + const remainingIndexes = await listColumnIndexes(queryInterface, TABLE_NAME, COLUMN_NAME); + if (remainingIndexes.length === 0) { + try { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${INDEX_NAME}\` (\`${COLUMN_NAME}\`(191))` + ); + console.log(`[migrate] 已创建前缀索引 ${INDEX_NAME}(${COLUMN_NAME}(191))`); + } catch (e) { + const msg = String(e && e.message || ''); + if (!msg.includes('Duplicate')) { + throw e; + } + console.log(`[migrate] 前缀索引 ${INDEX_NAME} 已存在,跳过`); + } + } + }, + + down: async queryInterface => { + if (!(await hasColumn(queryInterface, TABLE_NAME, COLUMN_NAME))) { + console.log(`[migrate:down] ${TABLE_NAME}.${COLUMN_NAME} 列不存在,跳过`); + return; + } + + // 注意:若已有数据超过 1024 字符,回滚会失败,需先人工截断数据 + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY \`${COLUMN_NAME}\` VARCHAR(1024) NULL COMMENT '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key'` + ); + console.log(`[migrate:down] ${TABLE_NAME}.${COLUMN_NAME} TEXT → VARCHAR(1024)`); + }, +}; diff --git a/database/migrations/20260822140000-add-unique-wave-no-to-wms-wave-batch.js b/database/migrations/20260822140000-add-unique-wave-no-to-wms-wave-batch.js new file mode 100644 index 0000000..736edf0 --- /dev/null +++ b/database/migrations/20260822140000-add-unique-wave-no-to-wms-wave-batch.js @@ -0,0 +1,254 @@ +'use strict'; + +/** + * wms_wave_batch.wave_no 唯一化。 + * + * 背景:并发创建波次时「查当日最大序号+1」存在竞态,可能产生 wave_no 相同的多行 + * (不同 wave_id、不同订单组),导致两组订单共用一个波次号。 + * + * 本迁移: + * 1. 修复存量重复波次号:同一 wave_no 保留最早(wave_id 最小)一行, + * 其余行按「前缀+日期+下一个空闲序号」重新编号,并同步引用方数据 + * (订单表四个车道、拣货任务波次关联表、打印记录、打包任务)的 wave_no; + * 2. 移除冗余的非唯一索引 idx_wave_no(若存在); + * 3. 新增唯一索引 uniq_wave_no(若已人工添加则跳过,保证幂等)。 + */ + +const TABLE_NAME = 'wms_wave_batch'; + +/** + * 归一化索引字段名(Sequelize 各版本返回 string 或 { attribute } 对象)。 + * + * @param {Array} fields 索引字段列表。 + * @return {Array} 字段名字符串列表。 + */ +function normalizeIndexFields(fields) { + return (Array.isArray(fields) ? fields : []) + .map(field => String( + typeof field === 'string' ? field : (field && (field.attribute || field.name || '')) + ).trim()) + .filter(Boolean); +} + +/** + * 判断索引列表是否包含指定名称的非唯一/唯一 wave_no 索引。 + * + * @param {Array} indexes showIndex 结果。 + * @param {string} indexName 索引名称。 + * @param {boolean} unique 是否唯一索引。 + * @return {boolean} 是否存在。 + */ +function hasWaveNoIndex(indexes, indexName, unique) { + return (Array.isArray(indexes) ? indexes : []).some(index => { + if (!index || index.name !== indexName) { + return false; + } + const fields = normalizeIndexFields(index.fields); + return fields.length === 1 && fields[0] === 'wave_no' && Boolean(index.unique) === unique; + }); +} + +/** + * 查询存量重复的波次号。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @return {Promise>} 重复波次号列表。 + */ +async function fetchDuplicateWaveNos(queryInterface) { + return await queryInterface.sequelize.query( + `SELECT wave_no, COUNT(*) AS cnt + FROM ${TABLE_NAME} + GROUP BY wave_no + HAVING COUNT(*) > 1 + ORDER BY wave_no ASC`, + { type: queryInterface.sequelize.QueryTypes.SELECT } + ); +} + +/** + * 计算「前缀+日期」片段下下一个空闲波次号。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @param {string} prefixDate 波次号前缀+日期片段(如 B20260822)。 + * @return {Promise} 下一个空闲波次号。 + */ +async function buildNextFreeWaveNo(queryInterface, prefixDate) { + const startPos = String(prefixDate).length + 1; + const rows = await queryInterface.sequelize.query( + `SELECT IFNULL(MAX(CAST(SUBSTRING(wave_no, :startPos) AS UNSIGNED)), 0) + 1 AS seq + FROM ${TABLE_NAME} + WHERE wave_no LIKE :pattern`, + { + replacements: { startPos, pattern: `${prefixDate}%` }, + type: queryInterface.sequelize.QueryTypes.SELECT, + } + ); + const seq = Number(rows && rows[0] && rows[0].seq || 1); + return `${prefixDate}${String(seq).padStart(5, '0')}`; +} + +/** + * 判断波次号是否已存在。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @param {string} waveNo 波次号。 + * @return {Promise} 是否已存在。 + */ +async function waveNoExists(queryInterface, waveNo) { + const rows = await queryInterface.sequelize.query( + `SELECT wave_id FROM ${TABLE_NAME} WHERE wave_no = :waveNo LIMIT 1`, + { replacements: { waveNo }, type: queryInterface.sequelize.QueryTypes.SELECT } + ); + return Array.isArray(rows) && rows.length > 0; +} + +/** + * 更新指定表内该波次的 wave_no(表不存在时跳过)。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @param {string} tableName 表名。 + * @param {number} warehouseId 仓库ID。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 新波次号。 + * @return {Promise} 无返回值。 + */ +async function updateTableWaveNo(queryInterface, tableName, warehouseId, waveId, waveNo) { + const checkRows = await queryInterface.sequelize.query( + `SELECT TABLE_NAME + FROM information_schema.TABLES + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName`, + { replacements: { tableName }, type: queryInterface.sequelize.QueryTypes.SELECT } + ); + if (!Array.isArray(checkRows) || checkRows.length === 0) { + return; + } + + await queryInterface.sequelize.query( + `UPDATE \`${tableName}\` + SET wave_no = :waveNo + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + AND wave_no <> :waveNo`, + { replacements: { waveNo, warehouseId, waveId } } + ); +} + +/** + * 同步某波次被重编号后所有引用方表中的 wave_no。 + * + * @param {Object} queryInterface Sequelize 查询接口。 + * @param {number} warehouseId 仓库ID。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 新波次号。 + * @return {Promise} 无返回值。 + */ +async function syncWaveNoReferences(queryInterface, warehouseId, waveId, waveNo) { + if (Number.isInteger(warehouseId) && warehouseId > 0) { + await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}`, warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_history`, warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_dispatch`, warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_outsourced`, warehouseId, waveId, waveNo); + } + await updateTableWaveNo(queryInterface, 'wms_wave_pick_task_wave', warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, 'wms_print_record', warehouseId, waveId, waveNo); + await updateTableWaveNo(queryInterface, 'wms_pack_task', warehouseId, waveId, waveNo); +} + +module.exports = { + async up(queryInterface) { + // 1. 修复存量重复波次号:同一 wave_no 保留最早一行,其余重新编号 + const duplicateRows = await fetchDuplicateWaveNos(queryInterface); + for (const dup of (Array.isArray(duplicateRows) ? duplicateRows : [])) { + const waveNo = String(dup && dup.wave_no || '').trim(); + if (!waveNo) { + continue; + } + + const rows = await queryInterface.sequelize.query( + `SELECT wave_id, warehouse_id + FROM ${TABLE_NAME} + WHERE wave_no = :waveNo + ORDER BY wave_id ASC`, + { replacements: { waveNo }, type: queryInterface.sequelize.QueryTypes.SELECT } + ); + if (!Array.isArray(rows) || rows.length <= 1) { + continue; + } + + const prefixDate = waveNo.replace(/\d+$/, ''); + if (!prefixDate) { + throw new Error(`波次号 ${waveNo} 无字母前缀,无法自动重编号,请人工处理`); + } + + // 保留最早(wave_id 最小)的一行,其余行重新编号 + for (let index = 1; index < rows.length; index += 1) { + const row = rows[index]; + const waveId = Number(row && row.wave_id || 0); + const warehouseId = Number(row && row.warehouse_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + let nextWaveNo = await buildNextFreeWaveNo(queryInterface, prefixDate); + let guard = 0; + while (guard < 100 && await waveNoExists(queryInterface, nextWaveNo)) { + nextWaveNo = await buildNextFreeWaveNo(queryInterface, prefixDate); + guard += 1; + } + if (guard >= 100) { + throw new Error(`波次号 ${waveNo} 重新编号失败:无法找到空闲编号`); + } + + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} + SET wave_no = :nextWaveNo, update_time = NOW() + WHERE wave_id = :waveId`, + { replacements: { nextWaveNo, waveId } } + ); + + // 同步引用方数据 + await syncWaveNoReferences(queryInterface, warehouseId, waveId, nextWaveNo); + } + } + + // 2. 二次校验:修复后不应再有重复波次号 + const residualRows = await fetchDuplicateWaveNos(queryInterface); + if ((Array.isArray(residualRows) ? residualRows : []).length > 0) { + const residual = residualRows.map(row => String(row && row.wave_no || '').trim()).filter(Boolean); + throw new Error(`wms_wave_batch 修复后仍存在重复波次号: ${residual.join(', ')}`); + } + + // 3. 读取索引现状 + const indexes = await queryInterface.showIndex(TABLE_NAME); + + // 4. 移除冗余非唯一索引(若存在) + if (hasWaveNoIndex(indexes, 'idx_wave_no', false)) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_wave_no'); + } + + // 5. 新增唯一索引(若已人工添加则跳过,保证幂等) + if (!hasWaveNoIndex(indexes, 'uniq_wave_no', true)) { + await queryInterface.addIndex(TABLE_NAME, [ 'wave_no' ], { + unique: true, + name: 'uniq_wave_no', + }); + } + }, + + async down(queryInterface) { + const indexes = await queryInterface.showIndex(TABLE_NAME); + + // 回滚:移除唯一索引 + if (hasWaveNoIndex(indexes, 'uniq_wave_no', true)) { + await queryInterface.removeIndex(TABLE_NAME, 'uniq_wave_no'); + } + + // 回滚:恢复非唯一索引(若不存在) + if (!hasWaveNoIndex(indexes, 'idx_wave_no', false)) { + await queryInterface.addIndex(TABLE_NAME, [ 'wave_no' ], { + unique: false, + name: 'idx_wave_no', + }); + } + }, +}; diff --git a/database/migrations/20260823120000-add-return-unpack-video-list-permission.js b/database/migrations/20260823120000-add-return-unpack-video-list-permission.js new file mode 100644 index 0000000..9e96402 --- /dev/null +++ b/database/migrations/20260823120000-add-return-unpack-video-list-permission.js @@ -0,0 +1,82 @@ +'use strict'; + +/** + * 退回拆包录像分页列表权限迁移(returnUnpack.videoList)。 + * + * 权限明细: + * 560 — returnUnpack.videoList API:退回拆包录像列表 + * + * 角色授权(与查询类 546-549 一致): + * → 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 560: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID 560)── + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ 560, 'returnUnpack.videoList', null, 'returnUnpack.videoList', null, 'API:退回拆包录像列表', null, 0, 0, null, 'api', 0, 1 ] } + ); + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 560` + ); + }, +}; diff --git a/database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js b/database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js new file mode 100644 index 0000000..ac9338e --- /dev/null +++ b/database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_stock_warehouse', 'need_recheck', { + type: Sequelize.CHAR(1), + allowNull: false, + defaultValue: 'Y', + comment: '是否需要复核:Y=需要复核,N=不需要复核', + after: 'is_batch_mgmt', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_stock_warehouse', 'need_recheck'); + }, +}; diff --git a/database/migrations/20260824-add-direct-putaway-permission.js b/database/migrations/20260824-add-direct-putaway-permission.js new file mode 100644 index 0000000..54fd2de --- /dev/null +++ b/database/migrations/20260824-add-direct-putaway-permission.js @@ -0,0 +1,52 @@ +'use strict'; + +/** + * 新增 storage.inventory.directPutaway(收货单直入库存)API 权限记录。 + * + * 幂等设计:先查询 path + type='api' 是否已存在,已存在则跳过。 + */ + +const TABLE = 'wms_permission'; + +module.exports.up = async queryInterface => { + const permissions = [ + { path: 'storage.inventory.directPutaway', meta_title: '收货单直入库存' }, + ]; + + const paths = permissions.map(p => p.path); + const placeholders = paths.map(() => '?').join(', '); + const [ rows ] = await queryInterface.sequelize.query( + `SELECT path FROM \`${TABLE}\` WHERE type = 'api' AND path IN (${placeholders})`, + { replacements: paths } + ); + const existingPaths = new Set(rows.map(r => r.path)); + + const toInsert = permissions.filter(p => !existingPaths.has(p.path)); + + if (toInsert.length > 0) { + const values = toInsert + .map( + p => `('${p.path.replace(/'/g, "\\'")}', '${p.path.replace(/'/g, "\\'")}', '${p.meta_title.replace(/'/g, "\\'")}', 'api', 1, NOW(), NOW())` + ) + .join(',\n'); + + await queryInterface.sequelize.query(` + INSERT INTO \`${TABLE}\` (path, name, meta_title, type, status, created_at, update_at) + VALUES ${values} + `); + } + + console.log( + `[Migration] wms_permission API 权限新增:共 ${permissions.length} 条,` + + `已存在 ${permissions.length - toInsert.length} 条,实际插入 ${toInsert.length} 条` + ); +}; + +module.exports.down = async queryInterface => { + const paths = [ 'storage.inventory.directPutaway' ]; + const placeholders = paths.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE type = 'api' AND path IN (${placeholders})`, + { replacements: paths } + ); +}; diff --git a/database/migrations/20260825120000-add-return-unpack-force-record-permission.js b/database/migrations/20260825120000-add-return-unpack-force-record-permission.js new file mode 100644 index 0000000..05f6fe6 --- /dev/null +++ b/database/migrations/20260825120000-add-return-unpack-force-record-permission.js @@ -0,0 +1,82 @@ +'use strict'; + +/** + * 退回拆包强制录制权限迁移(returnUnpack.forceRecord)。 + * + * 权限明细: + * 562 — returnUnpack.forceRecord API:退回拆包强制录制 + * + * 角色授权(与作业类 540-545 一致): + * → 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 562: [ 27, 26 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID 562)── + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ 562, 'returnUnpack.forceRecord', null, 'returnUnpack.forceRecord', null, 'API:退回拆包强制录制', null, 0, 0, null, 'api', 0, 1 ] } + ); + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 562` + ); + }, +}; diff --git a/database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js b/database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js new file mode 100644 index 0000000..327aa8f --- /dev/null +++ b/database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js @@ -0,0 +1,66 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 为出库单主表添加收件人信息字段(对应奇门 stockout.create 报文 receiverInfo 节点)。 + * + * 字段与奇门 receiverInfo 一一对应,列名统一加 receiver_ 前缀避免与订单表口径混淆。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + const receiverColumns = [ + { name: 'receiver_company', type: Sequelize.STRING(200), comment: '收件人公司名称(receiverInfo.company)' }, + { name: 'receiver_name', type: Sequelize.STRING(50), comment: '收件人姓名(receiverInfo.name)' }, + { name: 'receiver_zip_code', type: Sequelize.STRING(50), comment: '收件人邮编(receiverInfo.zipCode)' }, + { name: 'receiver_tel', type: Sequelize.STRING(50), comment: '收件人固定电话(receiverInfo.tel)' }, + { name: 'receiver_mobile', type: Sequelize.STRING(50), comment: '收件人移动电话(receiverInfo.mobile)' }, + { name: 'receiver_email', type: Sequelize.STRING(50), comment: '收件人电子邮箱(receiverInfo.email)' }, + { name: 'receiver_country_code', type: Sequelize.STRING(50), comment: '收件人国家二字码(receiverInfo.countryCode)' }, + { name: 'receiver_province', type: Sequelize.STRING(50), comment: '收件人省份(receiverInfo.province)' }, + { name: 'receiver_city', type: Sequelize.STRING(50), comment: '收件人城市(receiverInfo.city)' }, + { name: 'receiver_area', type: Sequelize.STRING(50), comment: '收件人区域(receiverInfo.area)' }, + { name: 'receiver_town', type: Sequelize.STRING(50), comment: '收件人村镇(receiverInfo.town)' }, + { name: 'receiver_detail_address', type: Sequelize.STRING(200), comment: '收件人详细地址(receiverInfo.detailAddress)' }, + { name: 'receiver_id', type: Sequelize.STRING(50), comment: '收件人证件号(receiverInfo.id)' }, + ]; + + for (const item of receiverColumns) { + if (!columns[item.name]) { + await queryInterface.addColumn(TABLE, item.name, { + type: item.type, + allowNull: true, + comment: item.comment, + }); + } + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + + const receiverColumnNames = [ + 'receiver_company', + 'receiver_name', + 'receiver_zip_code', + 'receiver_tel', + 'receiver_mobile', + 'receiver_email', + 'receiver_country_code', + 'receiver_province', + 'receiver_city', + 'receiver_area', + 'receiver_town', + 'receiver_detail_address', + 'receiver_id', + ]; + + for (const name of receiverColumnNames) { + if (columns[name]) { + await queryInterface.removeColumn(TABLE, name); + } + } + }, +}; diff --git a/database/migrations/20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js b/database/migrations/20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js new file mode 100644 index 0000000..e6376e1 --- /dev/null +++ b/database/migrations/20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js @@ -0,0 +1,68 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 出库单补充迁移: + * 1. order_status ENUM 追加 TRANSFERRED(已转订单),转订单成功后使用该状态; + * 2. 新增平台字段 source_platform_code / source_platform_name(修改接口"平台相关"与转订单回传使用)。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + // 1. order_status ENUM 追加 TRANSFERRED(保持默认值与原注释) + const statusType = String(columns.order_status && columns.order_status.type || '').toUpperCase(); + if (statusType && !statusType.includes("'TRANSFERRED'")) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_order_stockout` MODIFY COLUMN `order_status` ' + + 'ENUM(\'CREATING\',\'CREATED\',\'PENDING\',\'COMPLETED\',\'CANCELLED\',\'TRANSFERRED\') ' + + 'NOT NULL DEFAULT \'CREATED\' ' + + 'COMMENT \'订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废, TRANSFERRED=已转订单\'' + ); + } + + // 2. 平台字段 + if (!columns.source_platform_code) { + await queryInterface.addColumn(TABLE, 'source_platform_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '来源平台编码(转订单时优先使用,为空时兜底平台)', + }); + } + + if (!columns.source_platform_name) { + await queryInterface.addColumn(TABLE, 'source_platform_name', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '来源平台名称快照', + }); + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + + // 已转订单的行先回退为已作废,再收缩 ENUM + const statusType = String(columns.order_status && columns.order_status.type || '').toUpperCase(); + if (statusType && statusType.includes("'TRANSFERRED'")) { + await queryInterface.sequelize.query( + 'UPDATE `wms_order_stockout` SET `order_status` = \'CANCELLED\' WHERE `order_status` = \'TRANSFERRED\'' + ); + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_order_stockout` MODIFY COLUMN `order_status` ' + + 'ENUM(\'CREATING\',\'CREATED\',\'PENDING\',\'COMPLETED\',\'CANCELLED\') ' + + 'NOT NULL DEFAULT \'CREATED\' ' + + 'COMMENT \'订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废\'' + ); + } + + if (columns.source_platform_code) { + await queryInterface.removeColumn(TABLE, 'source_platform_code'); + } + + if (columns.source_platform_name) { + await queryInterface.removeColumn(TABLE, 'source_platform_name'); + } + }, +}; diff --git a/database/migrations/20260826090000-add-stockout-updateInfo-permission.js b/database/migrations/20260826090000-add-stockout-updateInfo-permission.js new file mode 100644 index 0000000..260c3e5 --- /dev/null +++ b/database/migrations/20260826090000-add-stockout-updateInfo-permission.js @@ -0,0 +1,58 @@ +'use strict'; + +/** + * 为 storage.stockout.updateInfo 添加 API 权限并授权。 + * + * 权限 ID(固定):563 — storage.stockout.updateInfo 修改出库单信息 + * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) + */ +module.exports = { + up: async queryInterface => { + // ===== 第一步:写入权限行 ===== + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (563, 'storage.stockout.updateInfo', NULL, 'storage.stockout.updateInfo', NULL, 'API:修改出库单信息', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='storage.stockout.updateInfo', meta_title='API:修改出库单信息', type='api' + `); + + // ===== 第二步:授权给经理及各主管/客服员工角色 ===== + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(563 AS UNSIGNED)), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '563', '$') = 0 + `); + } + }, + + down: async queryInterface => { + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '563')) + ), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + `); + } + + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id = 563 + `); + }, +}; diff --git a/database/migrations/20260826093000-add-stockout-cancel-permission.js b/database/migrations/20260826093000-add-stockout-cancel-permission.js new file mode 100644 index 0000000..134694e --- /dev/null +++ b/database/migrations/20260826093000-add-stockout-cancel-permission.js @@ -0,0 +1,56 @@ +'use strict'; + +/** + * 为 storage.stockout.cancel 添加 API 权限并授权。 + * + * 权限 ID(固定):564 — storage.stockout.cancel 出库单取消 + * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) + */ +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (564, 'storage.stockout.cancel', NULL, 'storage.stockout.cancel', NULL, 'API:出库单取消', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='storage.stockout.cancel', meta_title='API:出库单取消', type='api' + `); + + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(564 AS UNSIGNED)), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '564', '$') = 0 + `); + } + }, + + down: async queryInterface => { + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '564')) + ), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + `); + } + + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id = 564 + `); + }, +}; diff --git a/database/migrations/20260826100000-add-stockout-listLogs-permission.js b/database/migrations/20260826100000-add-stockout-listLogs-permission.js new file mode 100644 index 0000000..d31f701 --- /dev/null +++ b/database/migrations/20260826100000-add-stockout-listLogs-permission.js @@ -0,0 +1,56 @@ +'use strict'; + +/** + * 为 storage.stockout.listLogs 添加 API 权限并授权。 + * + * 权限 ID(固定):565 — storage.stockout.listLogs 出库单操作日志查询 + * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) + */ +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (565, 'storage.stockout.listLogs', NULL, 'storage.stockout.listLogs', NULL, 'API:出库单操作日志', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='storage.stockout.listLogs', meta_title='API:出库单操作日志', type='api' + `); + + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(565 AS UNSIGNED)), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '565', '$') = 0 + `); + } + }, + + down: async queryInterface => { + const roleIds = [ 8, 26, 28, 29, 30 ]; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '565')) + ), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + `); + } + + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id = 565 + `); + }, +}; diff --git a/database/migrations/20260826120000-allow-null-account-id-in-wms-pack-task-packer.js b/database/migrations/20260826120000-allow-null-account-id-in-wms-pack-task-packer.js new file mode 100644 index 0000000..579b517 --- /dev/null +++ b/database/migrations/20260826120000-allow-null-account-id-in-wms-pack-task-packer.js @@ -0,0 +1,50 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task_packer'; + +/** + * 允许 account_id 为 NULL。 + * 背景:打包任务写入多名打包人时,PDA 上传的 wms_account_id 可能为 null, + * 旧代码统一兜底为 0,多人场景下多条 (pack_task_id, account_id=0) 违反 + * 唯一索引 uix_pack_task_account,导致 bulkCreate 抛 UniqueConstraintError, + * 进而中断 _packOrder 后续步骤(OSD 下发、操作日志)。 + * MySQL 唯一索引对 NULL 不生效,故未知账号改为写 NULL。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + const col = tableInfo.account_id; + if (!col) { + throw new Error(`[Migration] ${TABLE_NAME}.account_id 不存在`); + } + if (col.allowNull === false) { + await queryInterface.changeColumn(TABLE_NAME, 'account_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '账号ID,关联 wms_account.id;未知账号为 NULL', + }); + console.log(`[Migration] ${TABLE_NAME}.account_id 已改为允许 NULL`); + } else { + console.log(`[Migration] ${TABLE_NAME}.account_id 已允许 NULL,跳过`); + } + }, + + down: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + const col = tableInfo.account_id; + if (!col) return; + + if (col.allowNull === true) { + // 回滚前把 NULL 归位为 0,避免改回 NOT NULL 失败 + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET account_id = 0 WHERE account_id IS NULL` + ); + await queryInterface.changeColumn(TABLE_NAME, 'account_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '账号ID,关联 wms_account.id', + }); + console.log(`[Migration] ${TABLE_NAME}.account_id 已恢复为 NOT NULL`); + } + }, +}; diff --git a/database/migrations/20260827160000-create-wms-waybill-allocate-queue.js b/database/migrations/20260827160000-create-wms-waybill-allocate-queue.js new file mode 100644 index 0000000..0db2247 --- /dev/null +++ b/database/migrations/20260827160000-create-wms-waybill-allocate-queue.js @@ -0,0 +1,107 @@ +'use strict'; + +/** + * 创建订单创建后自动分配快递的消费队列表 wms_waybill_allocate_queue。 + * + * 背景:订单创建后的异步流程原为逐单直接取号,大批量订单创建时会产生 N 条并发 + * createWaybillCode 回写事务与结算事务的 AB-BA 死锁(wms_store_warehouse 与 + * wms_order_express 锁序相反)。改造为创建时只入队(截单/未审核不入队),由定时 + * 任务按仓库+货主串行批量消费。 + * + * 字段: + * - order_id / business_key:待分配运单的订单与业务键(与 wms_order_express 一致) + * - warehouse_id / store_id:消费分组与数据隔离维度 + * - status:pending(待消费)/ processing(消费中)/ done(完成)/ failed(超限失败) + * - retry_count / next_retry_at / error_message:重试与失败信息 + * + * 索引: + * - uk_order_id_business_key:幂等入队唯一键 + * - idx_status_id:消费拉取(status=pending 按 id 升序) + * - idx_status_updated_at:处理中兜底恢复扫描 + */ + +const TABLE_NAME = 'wms_waybill_allocate_queue'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, INTEGER, STRING, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID(关联订单分表)', + }, + business_key: { + type: INTEGER(3), + allowNull: false, + defaultValue: 1, + comment: '业务键(与 wms_order_express.business_key 一致)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(消费分组与数据隔离维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '货主ID(消费分组维度)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/processing/done/failed', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可消费时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'order_id', 'business_key' ], { + name: 'uk_order_id_business_key', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'status', 'id' ], { + name: 'idx_status_id', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'status', 'updated_at' ], { + name: 'idx_status_updated_at', + }); + }, + + async down(queryInterface) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260827170000-add-is-notified-to-wms-return-received.js b/database/migrations/20260827170000-add-is-notified-to-wms-return-received.js new file mode 100644 index 0000000..9eddc36 --- /dev/null +++ b/database/migrations/20260827170000-add-is-notified-to-wms-return-received.js @@ -0,0 +1,29 @@ +'use strict'; + +const TABLE = 'wms_return_received'; + +/** + * 退回收件登记表新增 is_notified 字段: + * 标记"登记已通知货主群"(0=未通知,1=已通知)。 + * 供定时任务聚合通知(等 5 分钟无新登记后按货主合并推送,只对货主查退回时登记过的运单通知)。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + if (!columns.is_notified) { + await queryInterface.addColumn(TABLE, 'is_notified', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '登记是否已通知货主群:0=未通知,1=已通知', + }); + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + if (columns.is_notified) { + await queryInterface.removeColumn(TABLE, 'is_notified'); + } + }, +}; diff --git a/database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js b/database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js new file mode 100644 index 0000000..b8631f5 --- /dev/null +++ b/database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js @@ -0,0 +1,40 @@ +'use strict'; + +const TABLE = 'wms_entry_order'; + +/** + * 入库单主表新增 is_virtual_inbound 字段: + * 标记该入库单是否为虚拟入库(0=否,1=是)。 + * 快捷直入时,无绑定收货单的入库单为虚拟入库,有绑定收货单的为非虚拟入库。 + */ +module.exports = { + /** + * 执行迁移:新增 is_virtual_inbound 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + if (!columns.is_virtual_inbound) { + await queryInterface.addColumn(TABLE, 'is_virtual_inbound', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否虚拟入库:0=否 1=是', + }); + } + }, + + /** + * 回滚迁移:删除 is_virtual_inbound 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + if (columns.is_virtual_inbound) { + await queryInterface.removeColumn(TABLE, 'is_virtual_inbound'); + } + }, +}; diff --git a/database/migrations/20260829120000-create-wms-report-delivery-tables.js b/database/migrations/20260829120000-create-wms-report-delivery-tables.js new file mode 100644 index 0000000..5ff551a --- /dev/null +++ b/database/migrations/20260829120000-create-wms-report-delivery-tables.js @@ -0,0 +1,321 @@ +'use strict'; + +/** + * 创建报表投递三表:报表模板定义 / 货主投递计划 / 投递记录。 + * + * 背景:货主侧 7 日出入库报表采用「配置驱动 + 定时投递」方案: + * 报表模板可配置上新(免发版),每个货主可配置每日多个投递时间点, + * 由分钟级扫描调度命中后生成报表并按渠道投递。 + * + * 三表职责: + * - wms_report_definition:报表模板定义(code/name/scope + output/source/sheet 三段 JSON 配置) + * - wms_report_delivery_plan:货主每日投递计划(schedule_times JSON 时间点数组) + * - wms_report_delivery_log:投递记录(pending→exporting→delivered/failed/cancelled 状态机 + 退避重试) + * + * 约定: + * - 逻辑关联、无物理外键(与项目现状一致) + * - 唯一索引按项目惯例含 deleted_at,避免软删后重建撞唯一键 + * - 幂等键 uk_store_report_biz_time 保证同一货主同一报表同一数据日期同一时间点不重复投递 + */ + +const TABLE_DEFINITION = 'wms_report_definition'; +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, INTEGER, STRING, TINYINT, DATE, DATEONLY, ENUM } = Sequelize; + const tables = await queryInterface.showAllTables(); + const tableNames = tables.map(t => (typeof t === 'string' ? t : t.tableName)); + + if (!tableNames.includes(TABLE_DEFINITION)) { + await queryInterface.createTable(TABLE_DEFINITION, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + code: { + type: STRING(100), + allowNull: false, + comment: '报表编码,全局唯一(如 week_inout_7d)', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '报表名称', + }, + scope: { + type: ENUM('warehouse', 'store', 'open'), + allowNull: false, + defaultValue: 'warehouse', + comment: '适用维度:warehouse=仓库 store=货主 open=通用', + }, + description: { + type: STRING(500), + allowNull: true, + comment: '报表描述', + }, + output_config: { + type: Sequelize.JSON, + allowNull: true, + comment: '输出配置(文件名/目录等)', + }, + source_config: { + type: Sequelize.JSON, + allowNull: true, + comment: '数据源配置(查询器 key + 窗口参数)', + }, + sheet_config: { + type: Sequelize.JSON, + allowNull: true, + comment: '工作表配置(列定义/合并/样式/行过滤/列级 format)', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + remark: { + type: STRING(500), + allowNull: true, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '报表模板定义表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex(TABLE_DEFINITION, [ 'code', 'deleted_at' ], { + unique: true, + name: 'uk_code', + }); + await queryInterface.addIndex(TABLE_DEFINITION, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + + if (!tableNames.includes(TABLE_PLAN)) { + await queryInterface.createTable(TABLE_PLAN, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_code: { + type: STRING(100), + allowNull: false, + comment: '报表编码(wms_report_definition.code)', + }, + schedule_times: { + type: Sequelize.JSON, + allowNull: false, + comment: '每日投递时间点数组,如 ["08:30","17:00"](HH:mm)', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道:wecom=企业微信 inbox=站内信群 link=链接', + }, + enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + late_grace_minutes: { + type: INTEGER(11), + allowNull: false, + defaultValue: 60, + comment: '补投宽限分钟:重启/漏跑后在该窗口内补投,超窗作废', + }, + remark: { + type: STRING(500), + allowNull: true, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '货主报表投递计划表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex(TABLE_PLAN, [ 'store_id', 'report_code', 'deleted_at' ], { + unique: true, + name: 'uk_store_report_code', + }); + await queryInterface.addIndex(TABLE_PLAN, [ 'enabled', 'deleted_at' ], { + name: 'idx_enabled_deleted', + }); + await queryInterface.addIndex(TABLE_PLAN, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + + if (!tableNames.includes(TABLE_LOG)) { + await queryInterface.createTable(TABLE_LOG, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID(生成报表时注入的仓库维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_code: { + type: STRING(100), + allowNull: false, + comment: '报表编码(wms_report_definition.code)', + }, + biz_date: { + type: DATEONLY, + allowNull: false, + comment: '数据日期(T-1 自然日)', + }, + time_point: { + type: STRING(5), + allowNull: false, + comment: '命中的投递时间点(HH:mm)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/exporting/delivered/failed/cancelled', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道快照:wecom=企业微信 inbox=站内信群 link=链接', + }, + file_url: { + type: STRING(500), + allowNull: true, + comment: '报表文件下载链接(COS 带有效期)', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可投递时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + delivered_at: { + type: DATE, + allowNull: true, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '报表投递记录表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex(TABLE_LOG, [ 'store_id', 'report_code', 'biz_date', 'time_point', 'deleted_at' ], { + unique: true, + name: 'uk_store_report_biz_time', + }); + await queryInterface.addIndex(TABLE_LOG, [ 'status', 'id' ], { + name: 'idx_status_id', + }); + await queryInterface.addIndex(TABLE_LOG, [ 'status', 'updated_at' ], { + name: 'idx_status_updated_at', + }); + await queryInterface.addIndex(TABLE_LOG, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + }, + + async down(queryInterface) { + await queryInterface.dropTable(TABLE_LOG); + await queryInterface.dropTable(TABLE_PLAN); + await queryInterface.dropTable(TABLE_DEFINITION); + }, +}; diff --git a/database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js b/database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js new file mode 100644 index 0000000..d167664 --- /dev/null +++ b/database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js @@ -0,0 +1,77 @@ +'use strict'; + +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +/** + * 报表投递通知能力增强: + * - wms_report_delivery_plan 新增 notify_template(文本通知模板)、 + * notify_group_ids(通知群ID数组)、notify_member_ids(通知成员ID数组) + * - wms_report_delivery_log 新增 notify_targets(本次实际投递的群/成员快照,审计回放) + * + * 全部字段可空,不影响存量投递计划与投递记录。 + */ +module.exports = { + /** + * 执行迁移:依次新增通知相关字段(幂等:已存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + up: async (queryInterface, Sequelize) => { + const planColumns = await queryInterface.describeTable(TABLE_PLAN); + if (!planColumns.notify_template) { + await queryInterface.addColumn(TABLE_PLAN, 'notify_template', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '文本通知模板,支持 {time}/{url}/{report_name}/{biz_date} 标签', + }); + } + if (!planColumns.notify_group_ids) { + await queryInterface.addColumn(TABLE_PLAN, 'notify_group_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '通知群ID数组(wms_inbox_group.id,多选;空=不指定群)', + }); + } + if (!planColumns.notify_member_ids) { + await queryInterface.addColumn(TABLE_PLAN, 'notify_member_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '通知成员ID数组(外部IM用户ID,多选;目标侧支持数组)', + }); + } + + const logColumns = await queryInterface.describeTable(TABLE_LOG); + if (!logColumns.notify_targets) { + await queryInterface.addColumn(TABLE_LOG, 'notify_targets', { + type: Sequelize.JSON, + allowNull: true, + comment: '投递目标快照:{group_ids:[],member_ids:[]}(本次实际发送的群/成员,审计回放)', + }); + } + }, + + /** + * 回滚迁移:按新增顺序的逆序删除字段(幂等:不存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + down: async queryInterface => { + const planColumns = await queryInterface.describeTable(TABLE_PLAN); + if (planColumns.notify_member_ids) { + await queryInterface.removeColumn(TABLE_PLAN, 'notify_member_ids'); + } + if (planColumns.notify_group_ids) { + await queryInterface.removeColumn(TABLE_PLAN, 'notify_group_ids'); + } + if (planColumns.notify_template) { + await queryInterface.removeColumn(TABLE_PLAN, 'notify_template'); + } + + const logColumns = await queryInterface.describeTable(TABLE_LOG); + if (logColumns.notify_targets) { + await queryInterface.removeColumn(TABLE_LOG, 'notify_targets'); + } + }, +}; diff --git a/database/migrations/20260829170000-normalize-report-channel-to-inbox.js b/database/migrations/20260829170000-normalize-report-channel-to-inbox.js new file mode 100644 index 0000000..4390062 --- /dev/null +++ b/database/migrations/20260829170000-normalize-report-channel-to-inbox.js @@ -0,0 +1,55 @@ +'use strict'; + +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +/** + * 报表投递渠道收敛为 inbox(wecom/link 已弃用)。 + * + * - wms_report_delivery_plan.channel:默认值 wecom → inbox,comment 收敛 + * - wms_report_delivery_log.channel:默认值 wecom → inbox,comment 收敛 + * - 存量数据归一化:channel IN ('wecom','link') 的行统一更新为 'inbox' + * + * down 仅回退列默认值与 comment;数据 UPDATE 不回退(历史行无法还原原渠道)。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + // 1. 计划表:默认值 + comment 收敛 + await queryInterface.changeColumn(TABLE_PLAN, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道:inbox=站内信群(wecom/link 已弃用)', + }); + await queryInterface.sequelize.query( + `UPDATE ${TABLE_PLAN} SET channel = 'inbox' WHERE channel IN ('wecom', 'link')` + ); + + // 2. 记录表:默认值 + comment 收敛 + await queryInterface.changeColumn(TABLE_LOG, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道快照:inbox=站内信群(wecom/link 已弃用)', + }); + await queryInterface.sequelize.query( + `UPDATE ${TABLE_LOG} SET channel = 'inbox' WHERE channel IN ('wecom', 'link')` + ); + }, + + async down(queryInterface, Sequelize) { + // 仅回退默认值与 comment;存量数据不回退(已归一化为 inbox 的行无法还原原渠道) + await queryInterface.changeColumn(TABLE_PLAN, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道:wecom=企业微信 inbox=站内信群 link=链接', + }); + await queryInterface.changeColumn(TABLE_LOG, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道快照:wecom=企业微信 inbox=站内信群 link=链接', + }); + }, +}; diff --git a/database/migrations/20260829180000-add-inbox-group-select-permissions.js b/database/migrations/20260829180000-add-inbox-group-select-permissions.js new file mode 100644 index 0000000..f31ebf1 --- /dev/null +++ b/database/migrations/20260829180000-add-inbox-group-select-permissions.js @@ -0,0 +1,121 @@ +'use strict'; + +/** + * 为群选择 / 群成员选择下拉接口创建 API 权限记录并授权。 + * + * 权限明细(固定 ID,当前迁移内 max_id=565): + * 566 — inbox.group.quickList API:群快速查询 + * 567 — inbox.group.members API:群成员列表 + * + * 角色授权(客服组-主管及以上): + * 26(仓库组-主管) → 28(客服组-主管) → 29(生产组-主管) → 8(经理) + * 超级管理员(7)/仓库管理员(2) 已持有 * 通配符,自动拥有,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 566: [ 26, 28, 29, 8 ], + 567: [ 26, 28, 29, 8 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 566, 'inbox.group.quickList', 'API:群快速查询' ], + [ 567, 'inbox.group.members', 'API:群成员列表' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = typeof record.permissions === 'string' + ? JSON.parse(record.permissions) + : record.permissions; + } catch (e) { + perms = null; + } + + if (!Array.isArray(perms)) { + continue; + } + + if (!perms.includes(permId)) { + perms.push(permId); + perms.sort((a, b) => Number(a) - Number(b)); + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + 'DELETE FROM `wms_permission` WHERE id IN (566, 567)' + ); + + const permIds = [ 566, 567 ]; + for (const roleId of Object.values(PERMISSION_ROLES).flat()) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record || record.permissions === '*') { + continue; + } + + let perms; + try { + perms = typeof record.permissions === 'string' + ? JSON.parse(record.permissions) + : record.permissions; + } catch (e) { + perms = null; + } + if (!Array.isArray(perms) || !perms.some(p => permIds.includes(p))) { + continue; + } + + perms = perms.filter(p => !permIds.includes(p)); + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + }, +}; diff --git a/database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js b/database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js new file mode 100644 index 0000000..9c3d221 --- /dev/null +++ b/database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js @@ -0,0 +1,133 @@ +'use strict'; + +/** + * queryOrder 波次计数性能优化:为 current/dispatch 分表增加 wave_id 前导索引。 + * + * 背景: + * - app/service/systems/workbench.js 的 _countWaveOrders 会对 current + dispatch 两族分表执行 + * `SELECT COUNT(*) FROM ... WHERE wave_id=? AND warehouse_id=?`; + * - 现有索引 `idx_{wh}_current_wave` 为 (status, wave_id),前导列 status 不在谓词中, + * 生产 dispatch 分表(约 25.38 万行 / 524MB)需全表扫描约 12.69 万行; + * - 本迁移动态枚举 `wms_order_delivery_{wh}` 与 `wms_order_delivery_{wh}_dispatch`, + * 为每张分表新增二级索引 `idx_{wh}_current_wave_id (wave_id)`。 + * + * 设计说明: + * - 分表按仓库隔离,warehouse_id 在单张分表内为常量,索引无需包含 warehouse_id; + * - 使用 ALGORITHM=INPLACE, LOCK=NONE(MySQL 5.6+ 支持在线加二级索引), + * 不重建表、不锁写,适合低峰期执行; + * - 幂等:索引已存在则跳过;索引命名与 app/model/order_delivery_table_schema.js + * 的 buildIndexOptions 即将补充的定义一致,避免应用运行时 drift 同步重复建索引。 + * + * ⚠️ 本文件为「未执行」草案,仅在用户完成风险确认后,通过迁移流程执行。 + */ + +const SHARD_PATTERNS = [ + { type: 'current', pattern: /^wms_order_delivery_(\d+)$/ }, + { type: 'dispatch', pattern: /^wms_order_delivery_(\d+)_dispatch$/ }, +]; + +/** + * 解析分表名。 + * @param {string} tableName 表名。 + * @return {{ type: string, warehouseId: string }|null} 解析结果。 + */ +function parseShardTableName(tableName) { + for (const item of SHARD_PATTERNS) { + const match = item.pattern.exec(tableName); + if (match) { + return { type: item.type, warehouseId: match[1] }; + } + } + return null; +} + +/** + * 构建 wave_id 前导索引名(与 buildIndexOptions 命名一致)。 + * @param {string} warehouseId 仓库ID。 + * @return {string} 索引名。 + */ +function buildWaveIdIndexName(warehouseId) { + return `idx_${warehouseId}_current_wave_id`; +} + +/** + * 列举库内所有 current/dispatch 分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 分表名列表。 + */ +async function listManagedShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => parseShardTableName(name)); +} + +/** + * 判断索引是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 是否存在。 + */ +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(index => { + const name = String(index && (index.name || index.Key_name || index.key_name) || ''); + return name.toLowerCase() === String(indexName).toLowerCase(); + }); +} + +module.exports = { + /** + * 执行迁移:为 current/dispatch 分表增加 wave_id 前导索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const shards = await listManagedShards(queryInterface); + const results = []; + + for (const tableName of shards) { + const parsed = parseShardTableName(tableName); + const indexName = buildWaveIdIndexName(parsed.warehouseId); + + if (await indexExists(queryInterface, tableName, indexName)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` ADD INDEX \`${indexName}\` (\`wave_id\`), ALGORITHM=INPLACE, LOCK=NONE` + ); + results.push({ tableName, action: 'added', indexName }); + } + + console.log('[20260830100000-add-wave-id-index] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除 wave_id 前导索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const shards = await listManagedShards(queryInterface); + + for (const tableName of shards) { + const parsed = parseShardTableName(tableName); + const indexName = buildWaveIdIndexName(parsed.warehouseId); + + if (!(await indexExists(queryInterface, tableName, indexName))) { + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP INDEX \`${indexName}\`, ALGORITHM=INPLACE, LOCK=NONE` + ); + } + }, +}; diff --git a/database/migrations/20260830120000-restructure-report-definition-by-id.js b/database/migrations/20260830120000-restructure-report-definition-by-id.js new file mode 100644 index 0000000..3ca6f12 --- /dev/null +++ b/database/migrations/20260830120000-restructure-report-definition-by-id.js @@ -0,0 +1,166 @@ +'use strict'; + +/** + * 报表定义模型重构:code 关联 → 主键 id 关联。 + * + * 背景:报表定义模型已重构(definition 以主键 id 唯一,删除 code/scope/description + * 及 output_config/source_config/sheet_config 三个 JSON 配置列,新增 type/file_name/fields; + * plan/log 改用 report_definition_id 关联定义),本迁移同步数据库结构。 + * + * 三步改造: + * 1. wms_report_definition:删 uk_code,加 type/file_name/fields 三列,回填 id=1 + * 存量数据,物理删除已软删的 e2e 演示行(id=2),删除 code/scope/description + * 及三个 JSON 配置列,最后去掉 type 默认值(新配置必须显式声明类型); + * 2. wms_report_delivery_plan:加 report_definition_id 并回填,唯一键 + * uk_store_report_code → uk_store_report_definition; + * 3. wms_report_delivery_log:加 report_definition_id/report_name 并回填, + * 唯一键 uk_store_report_biz_time 改为基于 report_definition_id。 + * + * 执行顺序说明(关键约束):plan/log 的回填依赖 definition.code 关联 + * (JOIN ... ON d.code = p.report_code),因此 definition 旧列(含 code)的删除 + * 被延后到 plan/log 回填核验通过之后执行,最终表结构与规格逐项一致。 + * + * down 不可逆:旧列及其数据已被物理删除,无法从库内还原,故 down 直接抛错, + * 如需回退请从备份恢复。 + */ + +const TABLE_DEFINITION = 'wms_report_definition'; +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +// id=1 存量报表勾选字段 key 数组(与代码侧 stockFlow 查询器字段规格一致) +const STOCK_FLOW_FIELDS = [ + 'item_code', 'item_name', 'barcode', 'daily', 'ck_total', 'rk_total', 'available', + 'total', 'pending', 'locked', 'ck_avg', 'rk_avg', 'stock_days', 'suggest', 'warn', +]; + +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + const q = sql => sequelize.query(sql); + const log = msg => console.log(`[report-definition-by-id] ${msg}`); + + /** + * 执行计数校验 SQL,返回行数;不满足期望时抛错,阻止后续破坏性 DDL。 + * @param {string} sql 返回 cnt 列的 SELECT COUNT 语句。 + * @param {number} expected 期望的行数。 + * @param {string} message 校验失败时的错误描述。 + */ + const assertCount = async (sql, expected, message) => { + const [ rows ] = await q(sql); + const count = Number(rows[0].cnt); + console.log(`[report-definition-by-id] 核验:${message}(实际 ${count},期望 ${expected})`); + if (count !== expected) { + throw new Error(`[report-definition-by-id] ${message} 核验失败:实际 ${count},期望 ${expected}`); + } + }; + + // ============ Step 1(前半):wms_report_definition 结构准备 ============ + // 1.1 删除 uk_code 唯一索引(code 即将废弃) + await queryInterface.removeIndex(TABLE_DEFINITION, 'uk_code'); + log('definition:已删除唯一索引 uk_code'); + + // 1.2 新增 type / file_name / fields 三列(按规格顺序放在 name 之后) + await q(`ALTER TABLE \`${TABLE_DEFINITION}\` + ADD COLUMN \`type\` VARCHAR(50) NOT NULL DEFAULT 'stockFlow' COMMENT '报表类型(内置查询器注册 key)' AFTER \`name\`, + ADD COLUMN \`file_name\` VARCHAR(200) NOT NULL DEFAULT '' COMMENT '导出文件名模板(支持 {date} 占位)' AFTER \`type\`, + ADD COLUMN \`fields\` JSON NULL COMMENT '勾选字段 key 数组' AFTER \`file_name\``); + log('definition:已新增 type/file_name/fields 三列'); + + // 1.3 回填 id=1 存量数据(7日出入库报表) + await q(`UPDATE \`${TABLE_DEFINITION}\` SET + \`type\` = 'stockFlow', + \`file_name\` = '7日出入库_{date}', + \`fields\` = JSON_ARRAY(${STOCK_FLOW_FIELDS.map(f => `'${f}'`).join(', ')}) + WHERE \`id\` = 1`); + log('definition:已回填 id=1 的 type/file_name/fields'); + + // 1.4 物理删除已软删的 e2e 演示行(id=2) + await q(`DELETE FROM \`${TABLE_DEFINITION}\` + WHERE \`id\` = 2 AND \`deleted_at\` IS NOT NULL AND \`code\` = 'e2e_demo_report'`); + log('definition:已删除软删状态下的 e2e 演示行(id=2)'); + + // ============ Step 2:wms_report_delivery_plan 改 id 关联 ============ + // 2.1 新增 report_definition_id(按规格顺序放在 store_id 之后) + await q(`ALTER TABLE \`${TABLE_PLAN}\` + ADD COLUMN \`report_definition_id\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 + COMMENT '报表定义ID(wms_report_definition.id)' AFTER \`store_id\``); + log('plan:已新增 report_definition_id'); + + // 2.2 按 code 关联回填(必须在 definition.code 删除前完成) + await q(`UPDATE \`${TABLE_PLAN}\` p + JOIN \`${TABLE_DEFINITION}\` d ON d.\`code\` = p.\`report_code\` + SET p.\`report_definition_id\` = d.\`id\``); + log('plan:已按 code 关联回填 report_definition_id'); + + // 2.3 核验:report_definition_id=0 的行数必须为 0,否则抛出异常 + await assertCount( + `SELECT COUNT(*) AS cnt FROM \`${TABLE_PLAN}\` WHERE \`report_definition_id\` = 0`, + 0, + 'plan 回填后 report_definition_id=0 的行数必须为 0' + ); + + // 2.4 删除旧唯一键与 report_code,建立新唯一键 + await queryInterface.removeIndex(TABLE_PLAN, 'uk_store_report_code'); + await q(`ALTER TABLE \`${TABLE_PLAN}\` DROP COLUMN \`report_code\``); + await q(`ALTER TABLE \`${TABLE_PLAN}\` + ADD UNIQUE INDEX \`uk_store_report_definition\` (\`store_id\`, \`report_definition_id\`, \`deleted_at\`)`); + log('plan:已切换唯一键 uk_store_report_definition 并删除 report_code'); + + // ============ Step 3:wms_report_delivery_log 改 id 关联 ============ + // 3.1 新增 report_definition_id / report_name(按规格顺序放在 store_id 之后) + await q(`ALTER TABLE \`${TABLE_LOG}\` + ADD COLUMN \`report_definition_id\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 + COMMENT '报表定义ID(wms_report_definition.id)' AFTER \`store_id\`, + ADD COLUMN \`report_name\` VARCHAR(100) NULL + COMMENT '报表名称快照(投递时定义 name)' AFTER \`report_definition_id\``); + log('log:已新增 report_definition_id/report_name'); + + // 3.2 按 code 关联回填(必须在 definition.code 删除前完成) + await q(`UPDATE \`${TABLE_LOG}\` l + JOIN \`${TABLE_DEFINITION}\` d ON d.\`code\` = l.\`report_code\` + SET l.\`report_definition_id\` = d.\`id\`, l.\`report_name\` = d.\`name\``); + log('log:已按 code 关联回填 report_definition_id/report_name'); + + // 3.3 核验:report_definition_id=0 的行数必须为 0,否则抛出异常 + await assertCount( + `SELECT COUNT(*) AS cnt FROM \`${TABLE_LOG}\` WHERE \`report_definition_id\` = 0`, + 0, + 'log 回填后 report_definition_id=0 的行数必须为 0' + ); + + // 3.4 删除旧唯一键与 report_code,建立新唯一键 + await queryInterface.removeIndex(TABLE_LOG, 'uk_store_report_biz_time'); + await q(`ALTER TABLE \`${TABLE_LOG}\` DROP COLUMN \`report_code\``); + await q(`ALTER TABLE \`${TABLE_LOG}\` + ADD UNIQUE INDEX \`uk_store_report_biz_time\` + (\`store_id\`, \`report_definition_id\`, \`biz_date\`, \`time_point\`, \`deleted_at\`)`); + log('log:已切换唯一键 uk_store_report_biz_time 并删除 report_code'); + + // ============ Step 1(后半):删除 definition 旧列并收尾 ============ + // plan/log 回填已核验通过,此时删除 definition 旧列(含 code)是安全的 + await q(`ALTER TABLE \`${TABLE_DEFINITION}\` + DROP COLUMN \`code\`, + DROP COLUMN \`scope\`, + DROP COLUMN \`description\`, + DROP COLUMN \`output_config\`, + DROP COLUMN \`source_config\`, + DROP COLUMN \`sheet_config\``); + log('definition:已删除 code/scope/description 及三个 JSON 配置列'); + + // 去掉 type 默认值:新配置行必须显式声明报表类型 + await q(`ALTER TABLE \`${TABLE_DEFINITION}\` ALTER COLUMN \`type\` DROP DEFAULT`); + log('definition:已去掉 type 默认值'); + + log('全部完成'); + }, + + async down() { + // 本迁移破坏性删除旧列数据(code/scope/description 及三个 JSON 配置列、 + // e2e 演示行、plan/log 的 report_code 列),库内已无原始数据可还原,不可自动回滚。 + throw new Error( + '[report-definition-by-id] 本迁移不可逆:definition 旧列及其数据、e2e 演示行、plan/log 的 report_code 列已被删除,' + + '库内无法还原原始数据。如需回退,请从备份恢复数据库或手工重建相关列与数据。' + ); + }, +}; diff --git a/database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js b/database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js new file mode 100644 index 0000000..e928331 --- /dev/null +++ b/database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js @@ -0,0 +1,56 @@ +'use strict'; + +const TABLE_PLAN = 'wms_report_delivery_plan'; + +/** + * 为报表投递计划表新增计划名称字段 name。 + * + * 背景:报表投递计划在管理端列表/详情展示时需要展示计划名称(前端展示用), + * 因此为 wms_report_delivery_plan 新增 name 列,按规格位于 report_definition_id 之后。 + * + * 全部存量计划允许 name 为空(可空列),不影响既有投递计划与投递逻辑。 + */ +module.exports = { + /** + * 执行迁移:新增 name 列(幂等:已存在则跳过)。 + * + * 说明:sequelize 的 addColumn 不支持指定列位置(AFTER), + * 为满足「位于 report_definition_id 之后」的规格要求, + * 使用原生 DDL 控制列位置,与项目既有迁移 + * (restructure-report-definition-by-id)的做法一致。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async up(queryInterface) { + const { sequelize } = queryInterface; + const columns = await queryInterface.describeTable(TABLE_PLAN); + + // 幂等保护:已存在 name 列时跳过 + if (columns.name) { + return; + } + + await sequelize.query( + `ALTER TABLE \`${TABLE_PLAN}\` + ADD COLUMN \`name\` VARCHAR(100) NULL COMMENT '计划名称(前端展示用)' + AFTER \`report_definition_id\`` + ); + }, + + /** + * 回滚迁移:删除 name 列(幂等:不存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const columns = await queryInterface.describeTable(TABLE_PLAN); + + // 幂等保护:不存在 name 列时跳过 + if (!columns.name) { + return; + } + + await queryInterface.removeColumn(TABLE_PLAN, 'name'); + }, +}; diff --git a/database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js b/database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js new file mode 100644 index 0000000..da87944 --- /dev/null +++ b/database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js @@ -0,0 +1,59 @@ +'use strict'; + +/** + * 为站内信群表补充货主维度查询索引。 + * + * 背景:inbox.group.quickList 接口支持双维度过滤: + * - store_id(货主维度)→ wms_inbox_group.store_id 列 + * - warehouse_id(仓库维度)→ wms_inbox_group.warehouse_id 列 + * 两者可单独或同时(AND)过滤。store_id 列此前无索引, + * 单独按货主过滤或与仓库 AND 过滤时会走全表扫描。 + * + * wms_inbox_group: + * - idx_store_id: (store_id) + * 用于按货主维度过滤群列表。warehouse_id 维度已由唯一索引 + * uk_warehouse_group_id(warehouse_id, group_id) 的前导列覆盖,无需新增仓库单列索引; + * 双条件 AND 场景由 idx_store_id 与 uk_warehouse_group_id 组合命中, + * 群表数据量小,单列索引已足够,不引入复合索引以控制索引维护成本。 + */ + +const TABLE_NAME = 'wms_inbox_group'; +const INDEX_NAME = 'idx_store_id'; + +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName); +} + +async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) { + if (await indexExists(queryInterface, tableName, indexName)) { + console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`); + return; + } + await queryInterface.addIndex(tableName, options.fields, { + name: indexName, + unique: !!options.unique, + }); + console.log(`[idx] ${tableName}.${indexName} 已创建`); +} + +async function dropIndexIfExists(queryInterface, tableName, indexName) { + if (await indexExists(queryInterface, tableName, indexName)) { + await queryInterface.removeIndex(tableName, indexName); + console.log(`[idx] ${tableName}.${indexName} 已删除`); + } +} + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + await addIndexIfNotExists(queryInterface, TABLE_NAME, INDEX_NAME, { + fields: [ 'store_id' ], + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await dropIndexIfExists(queryInterface, TABLE_NAME, INDEX_NAME); + }, +}; diff --git a/database/migrations/20260901000000-add-intercept-locked-quantity-to-wms-storage.js b/database/migrations/20260901000000-add-intercept-locked-quantity-to-wms-storage.js new file mode 100644 index 0000000..6c09242 --- /dev/null +++ b/database/migrations/20260901000000-add-intercept-locked-quantity-to-wms-storage.js @@ -0,0 +1,75 @@ +'use strict'; + +/** + * 打印迁移阶段对应的数据库连接上下文信息。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {'up'|'down'} phase 迁移阶段。 + * @param {string} table 迁移目标表名。 + * @return {Promise} 无返回值。 + */ +const logMigrationDbContext = async (queryInterface, phase, table) => { + try { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user' + ); + const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {}; + console.log( + `[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}` + ); + } catch (error) { + console.warn( + `[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}` + ); + } +}; + +/** + * Migration: add intercept_locked_quantity to wms_storage + * - intercept_locked_quantity: INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量' + * + * Idempotent: uses queryInterface.describeTable to only add if missing. + * + * Raw SQL (MySQL 8+ supports IF NOT EXISTS): + * ALTER TABLE `wms_storage` + * ADD COLUMN IF NOT EXISTS `intercept_locked_quantity` INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量'; + * + * If MySQL < 8 (no IF NOT EXISTS), use INFORMATION_SCHEMA checks before ALTER. + */ + +module.exports = { + /** + * 执行正向迁移,按需新增库存拦截锁定数量字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const table = 'wms_storage'; + await logMigrationDbContext(queryInterface, 'up', table); + const columns = await queryInterface.describeTable(table); + + if (!columns.intercept_locked_quantity) { + await queryInterface.addColumn(table, 'intercept_locked_quantity', { + type: Sequelize.INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '拦截锁定数量', + }); + } + }, + + /** + * 执行回滚迁移,按需删除库存拦截锁定数量字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const table = 'wms_storage'; + await logMigrationDbContext(queryInterface, 'down', table); + const columns = await queryInterface.describeTable(table); + + if (columns.intercept_locked_quantity) { + await queryInterface.removeColumn(table, 'intercept_locked_quantity'); + } + }, +}; diff --git a/database/migrations/20260901000200-add-intercept-locked-snapshots-to-wms-storage-transaction.js b/database/migrations/20260901000200-add-intercept-locked-snapshots-to-wms-storage-transaction.js new file mode 100644 index 0000000..df0feb7 --- /dev/null +++ b/database/migrations/20260901000200-add-intercept-locked-snapshots-to-wms-storage-transaction.js @@ -0,0 +1,84 @@ +'use strict'; + +/** + * 打印迁移阶段对应的数据库连接上下文信息。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {'up'|'down'} phase 迁移阶段。 + * @param {string} table 迁移目标表名。 + * @return {Promise} 无返回值。 + */ +const logMigrationDbContext = async (queryInterface, phase, table) => { + try { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user' + ); + const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {}; + console.log( + `[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}` + ); + } catch (error) { + console.warn( + `[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}` + ); + } +}; + +/** + * Migration: add intercept locked quantity snapshots to wms_storage_transaction + * - before_intercept_locked_quantity: INT NULL COMMENT '变更前拦截锁定数量' + * - after_intercept_locked_quantity: INT NULL COMMENT '变更后拦截锁定数量' + * + * 与既有 before/after_locked_quantity 快照字段保持一致: + * 可空(NULL)、无默认值,由写入逻辑维护。 + * + * Idempotent: uses queryInterface.describeTable to only add if missing. + */ + +module.exports = { + /** + * 执行正向迁移,按需新增拦截锁定数量快照字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const table = 'wms_storage_transaction'; + await logMigrationDbContext(queryInterface, 'up', table); + const columns = await queryInterface.describeTable(table); + + if (!columns.before_intercept_locked_quantity) { + await queryInterface.addColumn(table, 'before_intercept_locked_quantity', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '变更前拦截锁定数量', + }); + } + + if (!columns.after_intercept_locked_quantity) { + await queryInterface.addColumn(table, 'after_intercept_locked_quantity', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '变更后拦截锁定数量', + }); + } + }, + + /** + * 执行回滚迁移,按需删除拦截锁定数量快照字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const table = 'wms_storage_transaction'; + await logMigrationDbContext(queryInterface, 'down', table); + const columns = await queryInterface.describeTable(table); + + if (columns.before_intercept_locked_quantity) { + await queryInterface.removeColumn(table, 'before_intercept_locked_quantity'); + } + + if (columns.after_intercept_locked_quantity) { + await queryInterface.removeColumn(table, 'after_intercept_locked_quantity'); + } + }, +}; diff --git a/database/migrations/20260902100000-add-packing-list-query-index.js b/database/migrations/20260902100000-add-packing-list-query-index.js new file mode 100644 index 0000000..040a7ed --- /dev/null +++ b/database/migrations/20260902100000-add-packing-list-query-index.js @@ -0,0 +1,19 @@ +'use strict'; + +/** + * order.packing.list 慢查询优化配套索引。 + * 列表默认按 create_time DESC 排序(_buildListOrder),原 idx_warehouse_id 单列索引 + * 命中后需 filesort 全仓库行数(生产实测 33722 行),新增 (warehouse_id, create_time) + * 复合索引消除 filesort,加速默认列表与导出查询。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.addIndex('wms_pack_task', [ 'warehouse_id', 'create_time' ], { + name: 'idx_warehouse_create_time', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('wms_pack_task', 'idx_warehouse_create_time'); + }, +}; diff --git a/database/migrations/20260903100000-add-login-code-token-to-wms-workbench.js b/database/migrations/20260903100000-add-login-code-token-to-wms-workbench.js new file mode 100644 index 0000000..f96dc58 --- /dev/null +++ b/database/migrations/20260903100000-add-login-code-token-to-wms-workbench.js @@ -0,0 +1,89 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName); +} + +async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) { + if (await indexExists(queryInterface, tableName, indexName)) { + console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`); + return; + } + await queryInterface.addIndex(tableName, options.fields, { + name: indexName, + unique: !!options.unique, + }); + console.log(`[idx] ${tableName}.${indexName} 已创建`); +} + +async function dropIndexIfExists(queryInterface, tableName, indexName) { + if (await indexExists(queryInterface, tableName, indexName)) { + await queryInterface.removeIndex(tableName, indexName); + console.log(`[idx] ${tableName}.${indexName} 已删除`); + } +} + +/** + * Migration: add login_code / token to wms_workbench + * - login_code: VARCHAR(64) NULL COMMENT '工作台登录码(前缀+随机,64位,全局唯一)' + * - token: VARCHAR(64) NULL COMMENT '工作台令牌(随机64位,绑定后生成)' + * + * Idempotent: 通过 describeTable / showIndex 判断后仅补齐缺失部分。 + */ + +module.exports = { + /** + * 执行正向迁移:新增 login_code、token 两列与 uk_login_code、idx_token 索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (!columns.login_code) { + await queryInterface.addColumn(TABLE_NAME, 'login_code', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '工作台登录码(前缀+随机,64位,全局唯一)', + }); + } + + if (!columns.token) { + await queryInterface.addColumn(TABLE_NAME, 'token', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '工作台令牌(随机64位,绑定后生成)', + }); + } + + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_login_code', { + fields: [ 'login_code' ], + unique: true, + }); + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_token', { + fields: [ 'token' ], + }); + }, + + /** + * 执行回滚迁移:删除索引与新增列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_login_code'); + await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_token'); + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.login_code) { + await queryInterface.removeColumn(TABLE_NAME, 'login_code'); + } + if (columns.token) { + await queryInterface.removeColumn(TABLE_NAME, 'token'); + } + }, +}; diff --git a/database/migrations/20260903150000-create-wms-workbench-member.js b/database/migrations/20260903150000-create-wms-workbench-member.js new file mode 100644 index 0000000..6e13f27 --- /dev/null +++ b/database/migrations/20260903150000-create-wms-workbench-member.js @@ -0,0 +1,86 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench_member'; + +/** + * Migration: create wms_workbench_member(工作台成员/用户登录副表) + * - user_id 允许为空:非系统账号用户(如未注册 wms_account 的硬件操作员)以 NULL 记录,名称存 user_name 快照。 + * - 软删除(deleted_at),移除成员通过 workbench.removeMember 完成。 + * + * Idempotent: 表已存在时跳过创建。 + */ + +module.exports = { + /** + * 执行正向迁移:创建工作台成员副表与索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + workbench_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '工作台ID,关联 wms_workbench.id', + }, + user_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '账号ID,关联 wms_account.id;非系统账号用户为 NULL', + }, + user_name: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '成员名称快照(非系统账号用户显示名)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 按工作台查询成员 + await queryInterface.addIndex(TABLE_NAME, [ 'workbench_id' ], { + name: 'idx_workbench_id', + }); + + // 按账号反查成员 + await queryInterface.addIndex(TABLE_NAME, [ 'user_id' ], { + name: 'idx_user_id', + }); + }, + + /** + * 执行回滚迁移:删除工作台成员副表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260903180000-remove-barcode-from-wms-workbench.js b/database/migrations/20260903180000-remove-barcode-from-wms-workbench.js new file mode 100644 index 0000000..9dd21d0 --- /dev/null +++ b/database/migrations/20260903180000-remove-barcode-from-wms-workbench.js @@ -0,0 +1,77 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName); +} + +async function dropIndexIfExists(queryInterface, tableName, indexName) { + if (await indexExists(queryInterface, tableName, indexName)) { + await queryInterface.removeIndex(tableName, indexName); + console.log(`[idx] ${tableName}.${indexName} 已删除`); + } +} + +async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) { + if (await indexExists(queryInterface, tableName, indexName)) { + console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`); + return; + } + await queryInterface.addIndex(tableName, options.fields, { + name: indexName, + unique: !!options.unique, + }); + console.log(`[idx] ${tableName}.${indexName} 已创建`); +} + +/** + * Migration: remove barcode from wms_workbench(工作台条码字段未使用,下线) + * - 删除列 barcode VARCHAR(100) + * - 删除索引 idx_barcode、uk_warehouse_barcode(仓库级唯一条码索引) + * + * Idempotent: 通过 describeTable / showIndex 判断后仅删除存在部分。 + */ + +module.exports = { + /** + * 执行正向迁移:先删索引,再删 barcode 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + up: async queryInterface => { + await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_warehouse_barcode'); + await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_barcode'); + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.barcode) { + await queryInterface.removeColumn(TABLE_NAME, 'barcode'); + } + }, + + /** + * 执行回滚迁移:恢复 barcode 列与索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + down: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns.barcode) { + await queryInterface.addColumn(TABLE_NAME, 'barcode', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '工作台条码(用户自定义,仓库内唯一)', + }); + } + + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_barcode', { + fields: [ 'barcode' ], + }); + await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_warehouse_barcode', { + fields: [ 'warehouse_id', 'barcode', 'deleted_at' ], + unique: true, + }); + }, +}; diff --git a/database/migrations/20260904120000-add-batch-no-array-to-wms-wave-pick-task.js b/database/migrations/20260904120000-add-batch-no-array-to-wms-wave-pick-task.js new file mode 100644 index 0000000..5a0e794 --- /dev/null +++ b/database/migrations/20260904120000-add-batch-no-array-to-wms-wave-pick-task.js @@ -0,0 +1,62 @@ +'use strict'; + +/** + * 为拣货任务表 wms_wave_pick_task 增加 batch_no_array 字段。 + * + * 背景: + * 一个拣货任务可能涉及多个波次,此前任务主表未冗余波次号, + * 统计/查询需要关联 wms_wave_pick_task_wave,不便。 + * + * 变更: + * 1. wms_wave_pick_task 新增 batch_no_array:TEXT,可空, + * 存储逗号分隔的波次号列表,如 'WAVE202401001,WAVE202401002', + * 便于 FIND_IN_SET / LIKE 等统计与查询。 + */ + +/** + * 获取表字段定义。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +module.exports = { + /** + * 正向迁移:为拣货任务表补充 batch_no_array 字段。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const tableName = 'wms_wave_pick_task'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (!columnsBefore.batch_no_array) { + await queryInterface.addColumn(tableName, 'batch_no_array', { + type: Sequelize.TEXT, + allowNull: true, + comment: '波次号列表(逗号分隔),方便统计和查询', + }); + } + }, + + /** + * 回滚迁移:若 batch_no_array 字段存在则删除。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const tableName = 'wms_wave_pick_task'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (columnsBefore.batch_no_array) { + await queryInterface.removeColumn(tableName, 'batch_no_array'); + } + }, +}; diff --git a/database/migrations/20260904130000-add-claim-operator-to-wms-wave-batch.js b/database/migrations/20260904130000-add-claim-operator-to-wms-wave-batch.js new file mode 100644 index 0000000..00c1f17 --- /dev/null +++ b/database/migrations/20260904130000-add-claim-operator-to-wms-wave-batch.js @@ -0,0 +1,74 @@ +'use strict'; + +/** + * 为波次表 wms_wave_batch 增加领料人字段。 + * + * 背景: + * 整波领单(pick.waveClaimScan)是波次级操作,此前仅写入订单操作日志 + * (ORDER_WAVE_CLAIM),波次表无领料人记录,不便于核对领料人与领料时间。 + * + * 变更: + * 1. wms_wave_batch 新增 claim_operator:VARCHAR(50),可空,领料人姓名。 + * 2. wms_wave_batch 新增 claim_time:DATETIME,可空,领料时间。 + * 3. 模型定义同步更新(app/model/wave_batch.js)。 + */ + +const TABLE_NAME = 'wms_wave_batch'; + +/** + * 获取表字段定义。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +module.exports = { + /** + * 正向迁移:为波次表补充领料人、领料时间字段。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME); + + if (!columnsBefore.claim_operator) { + await queryInterface.addColumn(TABLE_NAME, 'claim_operator', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '领料人', + }); + } + + if (!columnsBefore.claim_time) { + await queryInterface.addColumn(TABLE_NAME, 'claim_time', { + type: Sequelize.DATE, + allowNull: true, + comment: '领料时间', + }); + } + }, + + /** + * 回滚迁移:若领料字段存在则删除。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME); + + if (columnsBefore.claim_time) { + await queryInterface.removeColumn(TABLE_NAME, 'claim_time'); + } + + if (columnsBefore.claim_operator) { + await queryInterface.removeColumn(TABLE_NAME, 'claim_operator'); + } + }, +}; diff --git a/database/migrations/20260904140000-add-claim-operator-to-wms-wave-pick-task.js b/database/migrations/20260904140000-add-claim-operator-to-wms-wave-pick-task.js new file mode 100644 index 0000000..3322c73 --- /dev/null +++ b/database/migrations/20260904140000-add-claim-operator-to-wms-wave-pick-task.js @@ -0,0 +1,73 @@ +'use strict'; + +/** + * 为拣货任务表 wms_wave_pick_task 增加领料人字段。 + * + * 背景: + * 整波领单(pick.waveClaimScan)会回写订单表 claim_operator_id/claim_operator; + * 拣货任务创建时需从订单冗余领料人,便于任务列表追溯领料人。 + * + * 变更: + * 1. wms_wave_pick_task 新增 claim_operator_id:BIGINT,可空,领料人工号ID。 + * 2. wms_wave_pick_task 新增 claim_operator:VARCHAR(50),可空,领料人姓名。 + */ + +const TABLE_NAME = 'wms_wave_pick_task'; + +/** + * 获取表字段定义。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +module.exports = { + /** + * 正向迁移:为拣货任务表补充领料人工号与姓名字段。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME); + + if (!columnsBefore.claim_operator_id) { + await queryInterface.addColumn(TABLE_NAME, 'claim_operator_id', { + type: Sequelize.BIGINT, + allowNull: true, + comment: '领料人工号ID', + }); + } + + if (!columnsBefore.claim_operator) { + await queryInterface.addColumn(TABLE_NAME, 'claim_operator', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '领料人', + }); + } + }, + + /** + * 回滚迁移:若领料字段存在则删除。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME); + + if (columnsBefore.claim_operator) { + await queryInterface.removeColumn(TABLE_NAME, 'claim_operator'); + } + + if (columnsBefore.claim_operator_id) { + await queryInterface.removeColumn(TABLE_NAME, 'claim_operator_id'); + } + }, +}; diff --git a/database/migrations/20260905100000-add-wave-scope-to-order-delivery.js b/database/migrations/20260905100000-add-wave-scope-to-order-delivery.js new file mode 100644 index 0000000..3e28159 --- /dev/null +++ b/database/migrations/20260905100000-add-wave-scope-to-order-delivery.js @@ -0,0 +1,105 @@ +'use strict'; + +/** + * 订单表增加 wave_scope(波次范围)字段。 + * + * 取值约定(与 order 工作台虚拟筛选 wave_scope 一致): + * - 0 = 未分配波次 + * - 1 = 团购 + * - 2 = 散单 + * 默认 0。 + * + * 覆盖范围: + * - 基表 wms_order_delivery; + * - 全部仓库分表 wms_order_delivery_{wh}(current)及 + * _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。 + * + * 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js + * 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +const COLUMN_NAME = 'wave_scope'; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为基表与全部分表增加 wave_scope 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.addColumn(tableName, COLUMN_NAME, { + type: Sequelize.TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '波次范围:0未分配波次 1团购 2散单', + }); + results.push({ tableName, action: 'added' }); + } + + console.log('[20260905100000-add-wave-scope-to-order-delivery] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除 base 与全部分表的 wave_scope 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'missing' }); + continue; + } + + await queryInterface.removeColumn(tableName, COLUMN_NAME); + results.push({ tableName, action: 'removed' }); + } + + console.log('[20260905100000-add-wave-scope-to-order-delivery] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20260905130000-backfill-order-wave-scope.js b/database/migrations/20260905130000-backfill-order-wave-scope.js new file mode 100644 index 0000000..a042b20 --- /dev/null +++ b/database/migrations/20260905130000-backfill-order-wave-scope.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * 存量订单回填 wave_scope(波次范围)字段。 + * + * 口径(与波次生成写入逻辑 resolveWaveScopeByWaveMeta 一致): + * - 0 = 未分配波次(wave_id = 0,默认值无需更新); + * - 1 = 大团购:wms_wave_batch.wave_type = 1 且 source = 0; + * - 3 = 小团购:wms_wave_batch.wave_type = 1 且 source = 2; + * - 2 = 散单:其余有波次的订单(wave_type = 2,或 wave_type = 1 且 source = 1, + * 或 wave_id 指向的波次已不存在)。 + * + * 覆盖范围:基表 wms_order_delivery 与全部仓库分表 + * (current/history/dispatch/outsourced)。 + * + * 幂等:按 CASE 规则全量覆盖写入,重复执行结果一致。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 提取受影响行数。 + * @param {*} updateResult query 返回结果。 + * @return {number} 受影响行数。 + */ +function extractAffectedRows(updateResult) { + if (Array.isArray(updateResult)) { + const meta = updateResult[1]; + return Number(meta && (meta.affectedRows || meta.affectedCount || meta.rowCount) || 0); + } + if (updateResult && typeof updateResult === 'object') { + return Number(updateResult.affectedRows || updateResult.affectedCount || updateResult.rowCount || 0); + } + return 0; +} + +module.exports = { + /** + * 执行迁移:按波次类型/来源回填 wave_scope。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + const updateResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` o + LEFT JOIN wms_wave_batch wb ON wb.wave_id = o.wave_id + SET o.wave_scope = CASE + WHEN wb.wave_type = 1 AND wb.source = 0 THEN 1 + WHEN wb.wave_type = 1 AND wb.source = 2 THEN 3 + ELSE 2 + END + WHERE o.wave_id > 0 + `); + results.push({ tableName, affectedRows: extractAffectedRows(updateResult) }); + } + + console.log('[20260905130000-backfill-order-wave-scope] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:将已分配波次订单的 wave_scope 重置为 0(未回填状态)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + const updateResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET wave_scope = 0 + WHERE wave_id > 0 + `); + results.push({ tableName, affectedRows: extractAffectedRows(updateResult) }); + } + + console.log('[20260905130000-backfill-order-wave-scope] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20260906100000-backfill-order-wave-scope-single.js b/database/migrations/20260906100000-backfill-order-wave-scope-single.js new file mode 100644 index 0000000..bf73946 --- /dev/null +++ b/database/migrations/20260906100000-backfill-order-wave-scope-single.js @@ -0,0 +1,129 @@ +'use strict'; + +/** + * 存量订单治理:单品单件散单波次订单回填 wave_scope = 4。 + * + * 口径(与代码写入逻辑 resolveWaveScopeByWaveMeta 一致): + * - 订单 wave_id > 0; + * - 波次 wms_wave_batch.wave_type = 2(散单); + * - 该波次最新拣货任务 pick_mode = 2(单品单件,1-小团购 2-单品单件 3-先拣后分 4-边拣边分 5-大团购)。 + * + * pick_mode 取“每波次最新任务”:wms_wave_pick_task(wave_id 直连)与 + * wms_wave_pick_task_wave(任务-波次关联)两个来源取 id 最大的一条。 + * MySQL 5.7 兼容(不使用窗口函数)。 + * + * 覆盖范围:基表 wms_order_delivery 与全部仓库分表(current/history/dispatch/outsourced)。 + * 幂等:按条件覆盖写入,重复执行结果一致。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +/** 每波次最新拣货任务的 pick_mode 派生表 SQL(两个来源取 id 最大,DISTINCT 去重防止直连/关联重复行放大) */ +const LATEST_PICK_MODE_SQL = ` + SELECT u2.wave_id, u2.pick_mode + FROM ( + SELECT DISTINCT wave_id, pick_mode, id + FROM ( + SELECT wave_id, pick_mode, id FROM wms_wave_pick_task + UNION ALL + SELECT tw.wave_id, t.pick_mode, t.id + FROM wms_wave_pick_task_wave tw + JOIN wms_wave_pick_task t ON t.id = tw.task_id + ) u + ) u2 + JOIN ( + SELECT wave_id, MAX(id) AS max_id + FROM ( + SELECT wave_id, id FROM wms_wave_pick_task + UNION ALL + SELECT tw.wave_id, t.id + FROM wms_wave_pick_task_wave tw + JOIN wms_wave_pick_task t ON t.id = tw.task_id + ) v + GROUP BY wave_id + ) latest ON latest.wave_id = u2.wave_id AND latest.max_id = u2.id +`; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 提取受影响行数。 + * @param {*} updateResult query 返回结果。 + * @return {number} 受影响行数。 + */ +function extractAffectedRows(updateResult) { + if (Array.isArray(updateResult)) { + const meta = updateResult[1]; + return Number(meta && (meta.affectedRows || meta.affectedCount || meta.rowCount) || 0); + } + if (updateResult && typeof updateResult === 'object') { + return Number(updateResult.affectedRows || updateResult.affectedCount || updateResult.rowCount || 0); + } + return 0; +} + +module.exports = { + /** + * 执行迁移:单品单件散单波次订单 wave_scope 置为 4。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + const updateResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` o + JOIN wms_wave_batch wb ON wb.wave_id = o.wave_id + JOIN ( + ${LATEST_PICK_MODE_SQL} + ) pm ON pm.wave_id = o.wave_id + SET o.wave_scope = 4 + WHERE o.wave_id > 0 + AND wb.wave_type = 2 + AND pm.pick_mode = 2 + `); + results.push({ tableName, affectedRows: extractAffectedRows(updateResult) }); + } + + console.log('[20260906100000-backfill-order-wave-scope-single] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:单品单件(wave_scope=4)订单回置为散单(2)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + const updateResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET wave_scope = 2 + WHERE wave_scope = 4 + `); + results.push({ tableName, affectedRows: extractAffectedRows(updateResult) }); + } + + console.log('[20260906100000-backfill-order-wave-scope-single] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20260906110000-add-token-updated-at-to-wms-workbench.js b/database/migrations/20260906110000-add-token-updated-at-to-wms-workbench.js new file mode 100644 index 0000000..c3c9e13 --- /dev/null +++ b/database/migrations/20260906110000-add-token-updated-at-to-wms-workbench.js @@ -0,0 +1,63 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +/** + * Migration: add token_updated_at to wms_workbench + * - token_updated_at: DATETIME NULL,记录工作台 token 最后更新时间。 + * + * 背景:定时任务将扫描工作台,若 token 超过 3 个月未更新则强制清除 token 使设备下线, + * 因此需要记录每个工作台 token 的最后更新时间。 + * + * 回填策略: + * - 有 token 的行:token_updated_at = updated_at。token 列由 20260903100000 迁移新增, + * 绑定/刷新 token 时同步更新 updated_at,取 updated_at 是当前最接近「token 最后变更」的时间; + * - 无 token 的行:保持 NULL(从未绑定 token,不参与过期扫描)。 + * - 回填语句同时显式赋值 updated_at = updated_at:表结构上 updated_at 带 + * ON UPDATE CURRENT_TIMESTAMP,显式赋值可阻止其被回填动作顶替为迁移执行时间。 + * + * Idempotent: 通过 describeTable 判断后仅补齐缺失部分,回填按幂等条件覆盖。 + */ +module.exports = { + /** + * 执行正向迁移:新增 token_updated_at 列并回填存量数据。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (!columns.token_updated_at) { + await queryInterface.addColumn(TABLE_NAME, 'token_updated_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '工作台 token 最后更新时间(无 token 时为 NULL)', + }); + console.log('[token_updated_at] 列已新增'); + } else { + console.log('[token_updated_at] 列已存在,跳过新增'); + } + + const result = await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET token_updated_at = updated_at, updated_at = updated_at WHERE (token IS NOT NULL AND token != '') AND token_updated_at IS NULL` + ); + const affected = Array.isArray(result) + ? Number((result[1] && (result[1].affectedRows || result[1].affectedCount || result[1].rowCount)) || 0) + : Number((result && (result.affectedRows || result.affectedCount || result.rowCount)) || 0); + console.log(`[token_updated_at] 回填完成,影响行数: ${affected}`); + }, + + /** + * 执行回滚迁移:删除 token_updated_at 列(回填数据随之删除)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.token_updated_at) { + await queryInterface.removeColumn(TABLE_NAME, 'token_updated_at'); + console.log('[token_updated_at] 列已删除'); + } + }, +}; diff --git a/database/migrations/20260907100000-add-intercept-time-to-order-delivery.js b/database/migrations/20260907100000-add-intercept-time-to-order-delivery.js new file mode 100644 index 0000000..6a148ca --- /dev/null +++ b/database/migrations/20260907100000-add-intercept-time-to-order-delivery.js @@ -0,0 +1,106 @@ +'use strict'; + +/** + * 订单表增加 intercept_time(拦截时间)字段。 + * + * 背景:订单表当前仅维护 intercept_status 状态机,无拦截发生时间点; + * 业务需要直接记录订单进入拦截流程/库内拦截确认的时间,避免依赖 + * 操作日志/售后工单反查。新增本列用于拦截时间直查。 + * + * 取值约定:DATETIME,可空;订单未进入拦截流程时为 NULL, + * 拦截状态发生关键变更(拦截发起/库内拦截确认)时由业务写入。 + * + * 覆盖范围: + * - 基表 wms_order_delivery; + * - 全部仓库分表 wms_order_delivery_{wh}(current)及 + * _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。 + * + * 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js + * 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +const COLUMN_NAME = 'intercept_time'; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为基表与全部分表增加 intercept_time 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.addColumn(tableName, COLUMN_NAME, { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '拦截时间(进入拦截流程/库内拦截确认时写入)', + }); + results.push({ tableName, action: 'added' }); + } + + console.log('[20260907100000-add-intercept-time-to-order-delivery] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除基表与全部分表的 intercept_time 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'missing' }); + continue; + } + + await queryInterface.removeColumn(tableName, COLUMN_NAME); + results.push({ tableName, action: 'removed' }); + } + + console.log('[20260907100000-add-intercept-time-to-order-delivery] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20260907120000-add-dispath-time-to-order-delivery-dispatch.js b/database/migrations/20260907120000-add-dispath-time-to-order-delivery-dispatch.js new file mode 100644 index 0000000..02102f6 --- /dev/null +++ b/database/migrations/20260907120000-add-dispath-time-to-order-delivery-dispatch.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * 配送表增加 dispath_time(迁移进配送表时间)字段。 + * + * 背景:出库订单从当前表迁移进配送表时整行复制源数据, + * 缺少订单进入配送域的落库时间点;业务需要直接记录迁移时刻供查询与审计。 + * + * 取值约定:DATETIME,可空;迁移链路 + * app/service/systems/order_delivery_migration.js 的 buildDispatchRow + * 在写入配送表时设置 new Date(),源表不写该字段。 + * + * 覆盖范围(仅配送表独有,不加基表/当前分表/history/outsourced): + * - 全部配送分表 wms_order_delivery_{wh}_dispatch。 + * + * 幂等:列已存在则跳过。配送表模型由 app/model/order_delivery_factory.js + * 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。 + */ + +const DISPATCH_SHARD_PATTERN = /^wms_order_delivery_(\d+)_dispatch$/; + +const COLUMN_NAME = 'dispath_time'; + +/** + * 列举库内全部配送分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 配送分表名列表。 + */ +async function listDispatchShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\\_dispatch\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => DISPATCH_SHARD_PATTERN.test(name)); +} + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为全部配送分表增加 dispath_time 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tables = await listDispatchShards(queryInterface); + const results = []; + + for (const tableName of tables) { + if (await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.addColumn(tableName, COLUMN_NAME, { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '订单迁移进配送表的时间', + }); + results.push({ tableName, action: 'added' }); + } + + console.log('[20260907120000-add-dispath-time-to-order-delivery-dispatch] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除全部配送分表的 dispath_time 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = await listDispatchShards(queryInterface); + const results = []; + + for (const tableName of tables) { + if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'missing' }); + continue; + } + + await queryInterface.removeColumn(tableName, COLUMN_NAME); + results.push({ tableName, action: 'removed' }); + } + + console.log('[20260907120000-add-dispath-time-to-order-delivery-dispatch] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20260907140000-drop-logo-url-and-domain-from-wms-store.js b/database/migrations/20260907140000-drop-logo-url-and-domain-from-wms-store.js new file mode 100644 index 0000000..9b4e33e --- /dev/null +++ b/database/migrations/20260907140000-drop-logo-url-and-domain-from-wms-store.js @@ -0,0 +1,22 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + await queryInterface.removeColumn('wms_store', 'logo_url'); + await queryInterface.removeColumn('wms_store', 'domain'); + }, + + async down(queryInterface, Sequelize) { + const { STRING } = Sequelize; + await queryInterface.addColumn('wms_store', 'logo_url', { + type: STRING(255), + allowNull: true, + comment: 'logo链接', + }); + await queryInterface.addColumn('wms_store', 'domain', { + type: STRING(100), + allowNull: true, + comment: '绑定域名', + }); + }, +}; diff --git a/database/migrations/20260907150000-create-wms-warehouse-front-config.js b/database/migrations/20260907150000-create-wms-warehouse-front-config.js new file mode 100644 index 0000000..acde72f --- /dev/null +++ b/database/migrations/20260907150000-create-wms-warehouse-front-config.js @@ -0,0 +1,177 @@ +'use strict'; + +const FRONT_CONFIG_TABLE = 'wms_warehouse_front_config'; + +/** + * Migration: 仓库伪独立部署专表(单表终版)。 + * - wms_warehouse_front_config:每仓库一行(一仓一域一证书),保存仓库前端 + * 个性化配置(Logo / 标题 / 登录页图 / 主题)、证书元信息(只存路径不存 + * 证书内容)与 nginx 同步状态机(pending → success/failed)。 + * - 证书启用/停用由整行删除或 sync_status 表达;证书到期由 cert_expire_at + * 判断,不单独保留证书 status 列。 + * - domain 可空列唯一索引(uk_domain):MySQL 可空列唯一索引允许多个 NULL, + * 非空值的唯一性需应用层校验(详见对应 Model 注释)。 + * - 演进说明:原双表方案(wms_warehouse_front_config + wms_warehouse_cert) + * 已废弃;旧版迁移仅在开发库执行过且两表均为空,已 undo 后以本单表版本 + * 重跑。生产库从未执行过本迁移,一次发布窗口直接执行本文件即可。 + * + * Idempotent: 表已存在时跳过创建。 + */ + +/** + * 判断表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 存在返回 true。 + */ +async function tableExists(queryInterface, tableName) { + const tables = await queryInterface.showAllTables(); + return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName); +} + +/** + * 同步状态机字段(nginx 配置下发同步)。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Object} 字段定义。 + */ +function syncStateFields(Sequelize) { + return { + sync_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '同步状态:0-待同步,1-同步成功,2-同步失败', + }, + sync_attempts: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '同步尝试次数', + }, + last_sync_error: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '最近一次同步失败原因', + }, + last_synced_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近一次同步成功时间', + }, + }; +} + +/** + * 时间戳字段(创建/更新时间),与项目既有建表迁移一致。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Object} 字段定义。 + */ +function timestampFields(Sequelize) { + return { + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }; +} + +module.exports = { + /** + * 执行正向迁移:创建仓库前端配置表(单表,含证书元信息)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + if (await tableExists(queryInterface, FRONT_CONFIG_TABLE)) { + return; + } + + await queryInterface.createTable(FRONT_CONFIG_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID,关联 wms_store.id(is_warehouse=1),每仓一行', + }, + domain: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '仓库自持域名;可空列唯一索引允许多个 NULL,非空值唯一性需应用层校验', + }, + title: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '站点标题', + }, + logo_url: { + type: Sequelize.STRING(255), + allowNull: true, + comment: 'Logo地址', + }, + login_bg_url: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '登录页背景图地址', + }, + theme: { + type: Sequelize.JSON, + allowNull: true, + defaultValue: null, + comment: '主题配置JSON(颜色/布局等)', + }, + cert_path: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '证书文件路径(只存路径不存内容)', + }, + key_path: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '私钥文件路径(只存路径不存内容)', + }, + cert_expire_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '证书到期时间', + }, + ...syncStateFields(Sequelize), + ...timestampFields(Sequelize), + }); + + await queryInterface.addIndex(FRONT_CONFIG_TABLE, [ 'store_id' ], { + name: 'uk_store_id', + unique: true, + }); + await queryInterface.addIndex(FRONT_CONFIG_TABLE, [ 'domain' ], { + name: 'uk_domain', + unique: true, + }); + await queryInterface.addIndex(FRONT_CONFIG_TABLE, [ 'sync_status' ], { + name: 'idx_sync_status', + }); + }, + + /** + * 回滚:删除仓库前端配置表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + await queryInterface.dropTable(FRONT_CONFIG_TABLE); + }, +}; diff --git a/database/migrations/20260907160000-add-allocated-quantity-to-wms-entry-order-receiving.js b/database/migrations/20260907160000-add-allocated-quantity-to-wms-entry-order-receiving.js new file mode 100644 index 0000000..b75d5f8 --- /dev/null +++ b/database/migrations/20260907160000-add-allocated-quantity-to-wms-entry-order-receiving.js @@ -0,0 +1,72 @@ +'use strict'; + +/** + * wms_entry_order_receiving 绑定表增加 allocated_quantity(数量台账)字段。 + * + * 背景:入库单-收货单绑定后按入库单计划数量向收货单明细累加 stored_quantity, + * 同一入库单绑定多个收货单时会重复全额分配(合计超出计划数量)。 + * 修复方案 A:在绑定行上维护数量台账(收货明细ID → 已分配数量), + * 分配时按 SKU 封顶 min(入库单计划数 − 其他绑定已分配量, 收货明细剩余可入量)。 + * + * 取值约定:JSON,可空。 + * - NULL:迁移前的历史绑定行(未初始化台账,业务代码按“收货单侧已累计量”兜底重建); + * - {}:新链路创建/解绑清零后的空台账; + * - {"": }:明细级分配数量台账。 + * + * 幂等:列已存在则跳过。仅基表(无分表)。 + */ + +const TABLE_NAME = 'wms_entry_order_receiving'; + +const COLUMN_NAME = 'allocated_quantity'; + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为绑定表增加 allocated_quantity 台账列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] up skip: ${TABLE_NAME}.${COLUMN_NAME} exists`); + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.JSON, + allowNull: true, + defaultValue: null, + comment: '数量台账:收货明细ID→已分配数量(JSON对象);null 表示旧数据未初始化', + }); + + console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] up added: ${TABLE_NAME}.${COLUMN_NAME}`); + }, + + /** + * 回滚迁移:移除台账列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] down skip: ${TABLE_NAME}.${COLUMN_NAME} missing`); + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + console.log(`[20260907160000-add-allocated-quantity-to-wms-entry-order-receiving] down removed: ${TABLE_NAME}.${COLUMN_NAME}`); + }, +}; diff --git a/database/migrations/20260907170000-add-favicon-url-to-wms-warehouse-front-config.js b/database/migrations/20260907170000-add-favicon-url-to-wms-warehouse-front-config.js new file mode 100644 index 0000000..1e2ba59 --- /dev/null +++ b/database/migrations/20260907170000-add-favicon-url-to-wms-warehouse-front-config.js @@ -0,0 +1,58 @@ +'use strict'; + +const TABLE_NAME = 'wms_warehouse_front_config'; +const COLUMN_NAME = 'favicon_url'; + +/** + * 判断表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 存在返回 true。 + */ +async function tableExists(queryInterface, tableName) { + const tables = await queryInterface.showAllTables(); + return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName); +} + +module.exports = { + /** + * 执行正向迁移:为仓库前端配置表新增 favicon_url(站点 favicon 图标地址,幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (!(await tableExists(queryInterface, TABLE_NAME))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.STRING(255), + allowNull: true, + comment: '站点 favicon 图标地址', + }); + }, + + /** + * 回滚迁移:删除 favicon_url 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!(await tableExists(queryInterface, TABLE_NAME))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260908100000-add-cert-pem-to-wms-warehouse-front-config.js b/database/migrations/20260908100000-add-cert-pem-to-wms-warehouse-front-config.js new file mode 100644 index 0000000..1fa7a85 --- /dev/null +++ b/database/migrations/20260908100000-add-cert-pem-to-wms-warehouse-front-config.js @@ -0,0 +1,91 @@ +'use strict'; + +const TABLE_NAME = 'wms_warehouse_front_config'; +const CERT_PEM_COLUMN = 'cert_pem'; +const CERT_KEY_COLUMN = 'cert_key'; + +/** + * Migration: 仓库前端配置表新增证书内容列(证书 PEM 文本直接入库)。 + * + * 背景: + * 原方案证书内容只存路径(cert_path/key_path),由保存接口写暂存文件后部署; + * 现改为证书 PEM 文本直接入库,由定时任务拉取后写文件部署。 + * 证书链 fullchain PEM 一般 2~10KB,TEXT(上限 64KB)足够,且项目内长文本 + * 列惯例使用 TEXT(如 20260818190000 wms_order_items.ext_code 改 TEXT); + * 不选 VARCHAR(16384):utf8mb4 下 16K 字符已触发 MySQL 5.7 行大小限制风险, + * 且 PEM 长度无硬上限,TEXT 更稳。 + * + * 列说明: + * - cert_pem:证书 PEM 内容(私钥不在内); + * - cert_key:私钥 PEM 内容; + * - 均允许为 NULL(未上传证书时为空),无需索引; + * - 敏感内容:仅由定时任务读取,禁止写入日志/接口响应。 + * + * Idempotent: up 列已存在时跳过、down 列不存在时跳过。 + */ + +/** + * 判断表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 存在返回 true。 + */ +async function tableExists(queryInterface, tableName) { + const tables = await queryInterface.showAllTables(); + return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName); +} + +module.exports = { + /** + * 执行正向迁移:新增 cert_pem / cert_key 两列(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (!(await tableExists(queryInterface, TABLE_NAME))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (!columns[CERT_PEM_COLUMN]) { + await queryInterface.addColumn(TABLE_NAME, CERT_PEM_COLUMN, { + type: Sequelize.TEXT, + allowNull: true, + comment: '证书 PEM 内容(私钥不在内);内容仅由定时任务读取,禁止写入日志/接口响应', + after: 'cert_path', + }); + } + + if (!columns[CERT_KEY_COLUMN]) { + await queryInterface.addColumn(TABLE_NAME, CERT_KEY_COLUMN, { + type: Sequelize.TEXT, + allowNull: true, + comment: '私钥 PEM 内容;内容仅由定时任务读取,禁止写入日志/接口响应', + after: 'key_path', + }); + } + }, + + /** + * 回滚迁移:删除 cert_pem / cert_key 两列(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!(await tableExists(queryInterface, TABLE_NAME))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (columns[CERT_PEM_COLUMN]) { + await queryInterface.removeColumn(TABLE_NAME, CERT_PEM_COLUMN); + } + + if (columns[CERT_KEY_COLUMN]) { + await queryInterface.removeColumn(TABLE_NAME, CERT_KEY_COLUMN); + } + }, +}; diff --git a/database/migrations/20260908120000-add-recheck-start-time-to-wms-wave-batch.js b/database/migrations/20260908120000-add-recheck-start-time-to-wms-wave-batch.js new file mode 100644 index 0000000..fded58b --- /dev/null +++ b/database/migrations/20260908120000-add-recheck-start-time-to-wms-wave-batch.js @@ -0,0 +1,71 @@ +'use strict'; + +/** + * 为波次表 wms_wave_batch 增加复核开始时间字段。 + * + * 背景: + * 复核扫描接口 order.recheckOrder.scanOrder 首次成功加载某波次的复核视图时, + * 需要记录该波次的复核开始时间用于统计与审计;此前波次表仅有复核完成时间 + * (check_time,校验时间),缺少复核开始时间,二者语义不同不可复用。 + * + * 变更: + * 1. wms_wave_batch 新增 recheck_start_time:DATETIME,可空、无默认值,复核开始时间。 + * 2. 不回填任何历史数据(对既有数据零影响,仅后续首次扫描时写入)。 + * 3. 模型定义同步更新(app/model/wave_batch.js)。 + * + * 幂等:字段已存在则跳过;回滚时字段不存在则跳过。 + */ + +const TABLE_NAME = 'wms_wave_batch'; +const COLUMN_NAME = 'recheck_start_time'; +const FILE_TAG = '[20260908120000-add-recheck-start-time-to-wms-wave-batch]'; + +/** + * 获取表字段定义。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +module.exports = { + /** + * 正向迁移:为波次表补充复核开始时间字段(字段已存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME); + + if (!columnsBefore[COLUMN_NAME]) { + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.DATE, + allowNull: true, + comment: '复核开始时间', + after: 'check_result', + }); + console.log(`${FILE_TAG} up: added column ${COLUMN_NAME} on ${TABLE_NAME}`); + } else { + console.log(`${FILE_TAG} up: skip, column ${COLUMN_NAME} already exists on ${TABLE_NAME}`); + } + }, + + /** + * 回滚迁移:若复核开始时间字段存在则删除。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME); + + if (columnsBefore[COLUMN_NAME]) { + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + console.log(`${FILE_TAG} down: removed column ${COLUMN_NAME} on ${TABLE_NAME}`); + } else { + console.log(`${FILE_TAG} down: skip, column ${COLUMN_NAME} not exists on ${TABLE_NAME}`); + } + }, +}; diff --git a/database/migrations/20260910100000-create-wms-video-record-request.js b/database/migrations/20260910100000-create-wms-video-record-request.js new file mode 100644 index 0000000..3c44f3f --- /dev/null +++ b/database/migrations/20260910100000-create-wms-video-record-request.js @@ -0,0 +1,127 @@ +'use strict'; + +/** + * 创建视频补录请求记录表 wms_video_record_request。 + * + * 背景:站内信查询"打包视频/退件拆包视频"时若视频不可用(无视频记录或全部 failed), + * 除回复用户外还需登记一条补录请求并推送录制服务重新录制,本表用于记录请求与状态机。 + * + * 状态机:pending(待推送) → requested(已推送) → recording(录制中) → completed(已完成) / failed(失败) + * + * 字段:仓库/货主隔离、业务对象(biz_type=pack/unpack + biz_id)、运单号、状态、推送次数、 + * 录制电脑、失败原因、回写视频地址、结果通知标记、备注、软删除 deleted_at(paranoid)。 + * + * 索引:idx_warehouse_biz(按业务对象查在途请求)、idx_waybill_code(按单号追溯)、 + * idx_status(按状态筛选)、idx_deleted_at(软删除优化)。 + */ + +const TABLE_NAME = 'wms_video_record_request'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, INTEGER, STRING, DATE, ENUM, TINYINT } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '货主ID,0=未知', + }, + biz_type: { + type: ENUM('pack', 'unpack'), + allowNull: false, + comment: '业务类型:pack-打包视频 unpack-退件拆包视频', + }, + biz_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '业务ID:pack=wms_pack_task.id,unpack=wms_return_unpack.id', + }, + waybill_code: { + type: STRING(64), + allowNull: true, + comment: '触发查询的运单号', + }, + source: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '触发来源:inbox-站内信查询', + }, + status: { + type: ENUM('pending', 'requested', 'recording', 'completed', 'failed'), + allowNull: false, + defaultValue: 'pending', + comment: '状态机:pending-待推送 requested-已推送 recording-录制中 completed-已完成 failed-失败', + }, + request_count: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '推送录制服务次数', + }, + last_request_at: { + type: DATE, + allowNull: true, + comment: '最近一次请求录制服务时间(含推送失败)', + }, + print_computer_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '录制电脑ID,关联 wms_print_computer.id', + }, + request_error: { + type: STRING(500), + allowNull: true, + comment: '推送失败原因(无录制电脑/电脑不在线/打印服务异常)', + }, + video_url: { + type: STRING(500), + allowNull: true, + comment: '录制完成后回写的视频地址', + }, + is_notified: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '录制结果是否已通知查询方:0=未通知,1=已通知', + }, + notified_at: { + type: DATE, + allowNull: true, + comment: '录制结果通知时间', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + deleted_at: { type: DATE, allowNull: true, comment: '软删除时间' }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'biz_type', 'biz_id' ], { name: 'idx_warehouse_biz' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260911100000-add-inbox-fields-to-wms-video-record-request.js b/database/migrations/20260911100000-add-inbox-fields-to-wms-video-record-request.js new file mode 100644 index 0000000..6f13a61 --- /dev/null +++ b/database/migrations/20260911100000-add-inbox-fields-to-wms-video-record-request.js @@ -0,0 +1,58 @@ +'use strict'; + +/** + * 视频补录请求表新增「查询来源」字段:触发查询的站内信群与人员。 + * + * 背景:站内信查询打包/拆包视频命中"视频不可用"时写入补录请求, + * 此前只记录了仓库/货主/业务对象,缺少「是谁在哪个群问的」, + * 导致后续「录制结果通知」无法回发到原群并 @ 原用户。 + * + * 新增字段(均可空,兼容历史数据): + * - group_id / group_name:触发查询的群(回信必填) + * - user_id / user_name :触发查询的用户(回信必填,system 场景可空) + * + * 幂等:逐列 describeTable 判断后再 ADD,可重复执行。 + */ + +const TABLE = 'wms_video_record_request'; + +module.exports = { + /** + * 新增群/人员来源字段。 + * + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + const additions = [ + [ 'group_id', { type: Sequelize.STRING(100), allowNull: true, comment: '触发查询的群ID(站内信外部群ID,回信必填)' }], + [ 'group_name', { type: Sequelize.STRING(100), allowNull: true, comment: '触发查询的群名称' }], + [ 'user_id', { type: Sequelize.STRING(100), allowNull: true, comment: '触发查询的用户ID(站内信外部用户ID,回信必填)' }], + [ 'user_name', { type: Sequelize.STRING(100), allowNull: true, comment: '触发查询的用户名称' }], + ]; + + for (const [ name, definition ] of additions) { + if (!columns[name]) { + await queryInterface.addColumn(TABLE, name, definition); + } + } + }, + + /** + * 回滚:移除群/人员来源字段。 + * + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + for (const name of [ 'group_id', 'group_name', 'user_id', 'user_name' ]) { + if (columns[name]) { + await queryInterface.removeColumn(TABLE, name); + } + } + }, +}; diff --git a/database/migrations/20260911120000-update-wms-video-record-request-notify-index.js b/database/migrations/20260911120000-update-wms-video-record-request-notify-index.js new file mode 100644 index 0000000..382f2cf --- /dev/null +++ b/database/migrations/20260911120000-update-wms-video-record-request-notify-index.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 调整视频补录请求表(wms_video_record_request)的定时扫描索引。 + * + * 背景:结果通知定时任务(app/schedule/notify_video_record_result.js,每分钟一次) + * 的取数条件是「在途 + 未通知」: + * + * WHERE status IN ('pending','requested','recording') + * AND is_notified = 0 + * AND deleted_at IS NULL + * ORDER BY id ASC LIMIT 10 + * + * 单列 idx_status 只能命中 status 一层,随后还要回表按 is_notified 过滤; + * 后续若按「超时」维度拆查询,还会用到 last_request_at 范围条件。 + * + * 因此: + * - 新增 idx_status_notified_last_request (status, is_notified, last_request_at) + * - 移除冗余的 idx_status(新索引以 status 为最左前缀,可覆盖原查询场景) + * + * 幂等:先 showIndex 判断存在性再增删,可重复执行。 + */ + +const TABLE_NAME = 'wms_video_record_request'; + +const OLD_INDEX = 'idx_status'; +const NEW_INDEX = 'idx_status_notified_last_request'; + +/** + * 获取指定表的索引名集合。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async queryInterface => { + const indexes = await queryInterface.showIndex(TABLE_NAME); + return new Set( + (Array.isArray(indexes) ? indexes : []) + .map(index => String(index && index.name ? index.name : '').trim()) + .filter(Boolean) + ); +}; + +module.exports = { + /** + * 执行迁移:新增覆盖扫描条件的组合索引,并移除冗余单列索引。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const indexNameSet = await getIndexNameSet(queryInterface); + + if (!indexNameSet.has(NEW_INDEX)) { + await queryInterface.addIndex(TABLE_NAME, { + name: NEW_INDEX, + fields: [ 'status', 'is_notified', 'last_request_at' ], + }); + } + + if (indexNameSet.has(OLD_INDEX)) { + await queryInterface.removeIndex(TABLE_NAME, OLD_INDEX); + } + }, + + /** + * 回滚迁移:恢复单列 idx_status,移除组合索引。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const indexNameSet = await getIndexNameSet(queryInterface); + + if (indexNameSet.has(NEW_INDEX)) { + await queryInterface.removeIndex(TABLE_NAME, NEW_INDEX); + } + + if (!indexNameSet.has(OLD_INDEX)) { + await queryInterface.addIndex(TABLE_NAME, { + name: OLD_INDEX, + fields: [ 'status' ], + }); + } + }, +}; diff --git a/database/migrations/20260912100000-add-need-oms-waybill-to-order-delivery.js b/database/migrations/20260912100000-add-need-oms-waybill-to-order-delivery.js new file mode 100644 index 0000000..c7c9122 --- /dev/null +++ b/database/migrations/20260912100000-add-need-oms-waybill-to-order-delivery.js @@ -0,0 +1,106 @@ +'use strict'; + +/** + * 订单表增加 need_oms_waybill(是否需要回 OMS 取号)字段。 + * + * 背景:openapi 创建的订单存在“回到上游 OMS 取运单号”的诉求,需要把该标记 + * 落到订单表以便后续流程判断;非 openapi 创建来源一律默认 0。 + * + * 取值约定: + * - 0 = 不需要回 OMS 取号(默认,非 openapi 来源); + * - 1 = 需要回 OMS 取号(仅 openapi 创建来源使用)。 + * + * 覆盖范围: + * - 基表 wms_order_delivery; + * - 全部仓库分表 wms_order_delivery_{wh}(current)及 + * _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。 + * + * 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js + * 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +const COLUMN_NAME = 'need_oms_waybill'; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为基表与全部分表增加 need_oms_waybill 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.addColumn(tableName, COLUMN_NAME, { + type: Sequelize.TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '是否需要回OMS取号:0不需要 1需要(仅openapi创建来源使用,其他默认0)', + }); + results.push({ tableName, action: 'added' }); + } + + console.log('[20260912100000-add-need-oms-waybill-to-order-delivery] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除基表与全部分表的 need_oms_waybill 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'missing' }); + continue; + } + + await queryInterface.removeColumn(tableName, COLUMN_NAME); + results.push({ tableName, action: 'removed' }); + } + + console.log('[20260912100000-add-need-oms-waybill-to-order-delivery] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20260915100000-add-return-unpack-transfer-waybills-permission.js b/database/migrations/20260915100000-add-return-unpack-transfer-waybills-permission.js new file mode 100644 index 0000000..b20b0f4 --- /dev/null +++ b/database/migrations/20260915100000-add-return-unpack-transfer-waybills-permission.js @@ -0,0 +1,88 @@ +'use strict'; + +/** + * 退回拆包「运单批量转入退件登记」权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 568,当前迁移内最大已用 ID=567): + * 568 — returnUnpack.transferByWaybills API:运单批量转入退件登记 + * + * 角色授权(系统预设角色,不含通配符角色): + * 作业类(568)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 568: [ 27, 26 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 568, 'returnUnpack.transferByWaybills', 'API:运单批量转入退件登记' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 568` + ); + }, +}; diff --git a/database/migrations/20260916100000-create-wms-after-sale-type-tables.js b/database/migrations/20260916100000-create-wms-after-sale-type-tables.js new file mode 100644 index 0000000..00b2e6c --- /dev/null +++ b/database/migrations/20260916100000-create-wms-after-sale-type-tables.js @@ -0,0 +1,303 @@ +'use strict'; + +/** + * 创建售后类型/子类型自定义表,支持以仓库为维度做隔离。 + * + * 表结构: + * 1. wms_after_sale_type:售后类型表 + * 2. wms_after_sale_sub_type:售后子类型表(type 编码关联类型表) + * + * 隔离语义: + * - warehouse_id = NULL 且 is_system = 1:系统级类型,全部仓库可读(不允许编辑/删除)。 + * - warehouse_id = 仓库ID 且 is_system = 0:仓库自定义类型,仅该仓库可见。 + * + * 数据播种: + * 将当前 wms_after_sale 已有的售后类型/子类型枚举(order/receiving/entry/stockout + * 及其全部子类型)作为系统级(warehouse_id=NULL, is_system=1)写入两表。 + * 由于 MySQL 唯一索引对 NULL 不生效,播种采用"先查后插"保证幂等。 + */ + +const TYPE_TABLE = 'wms_after_sale_type'; +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; + +/** + * 现有售后类型 + 子类型枚举(与 app/model/after_sale.js 的 AFTER_SALE_TYPES 保持一致)。 + * @type {Array<{type: string, name: string, subTypes: Array<{sub_type: string, name: string}>}>} + */ +const SYSTEM_AFTER_SALE_TYPES = [ + { + type: 'order', + name: '订单', + subTypes: [ + { sub_type: 'damage', name: '破损' }, + { sub_type: 'missing_item', name: '少发' }, + { sub_type: 'mis_shipment', name: '错发' }, + { sub_type: 'wrong_sku', name: '错品' }, + { sub_type: 'quality_issue', name: '质量问题' }, + { sub_type: 'delivery_delay', name: '发货延迟' }, + { sub_type: 'logistics_issue', name: '物流异常' }, + { sub_type: 'rejected', name: '客户拒收' }, + { sub_type: 'intercept', name: '拦截' }, + { sub_type: 'verify_delivery', name: '核实签收' }, + { sub_type: 'urge', name: '催件' }, + { sub_type: 'extra_item', name: '多发' }, + { sub_type: 'change_address', name: '改地址' }, + { sub_type: 'change_carrier', name: '换快递' }, + { sub_type: 'pickup', name: '揽收' }, + { sub_type: 'weight_issue', name: '重量异常' }, + { sub_type: 'freight_issue', name: '运费争议' }, + { sub_type: 'other', name: '其他' }, + ], + }, + { + type: 'receiving', + name: '收货单', + subTypes: [ + { sub_type: 'shortage', name: '少货' }, + { sub_type: 'damage', name: '破损' }, + { sub_type: 'wrong_sku', name: '错品' }, + { sub_type: 'quality_issue', name: '质量问题' }, + { sub_type: 'other', name: '其他' }, + ], + }, + { + type: 'entry', + name: '入库单', + subTypes: [ + { sub_type: 'shortage', name: '少货' }, + { sub_type: 'damage', name: '破损' }, + { sub_type: 'wrong_sku', name: '错品' }, + { sub_type: 'quality_issue', name: '质量问题' }, + { sub_type: 'other', name: '其他' }, + ], + }, + { + type: 'stockout', + name: '出库单', + subTypes: [ + { sub_type: 'return_issue', name: '退货异常' }, + { sub_type: 'wrong_outbound', name: '错发' }, + { sub_type: 'shortage', name: '少发' }, + { sub_type: 'other', name: '其他' }, + ], + }, +]; + +/** + * 查询系统级类型/子类型是否已存在(warehouse_id IS NULL 的行)。 + * @param {object} queryInterface Sequelize QueryInterface 实例 + * @param {string} table 表名 + * @param {string} where 额外 where 条件(可含 :name 占位符) + * @param {object} replacements 占位符替换值 + * @return {Promise} 已存在返回 true + */ +async function findSystemIds(queryInterface, table, where, replacements) { + const rows = await queryInterface.sequelize.query( + `SELECT id FROM \`${table}\` WHERE ${where} AND warehouse_id IS NULL AND is_system = 1 LIMIT 1`, + { replacements, type: queryInterface.sequelize.QueryTypes.SELECT } + ); + return rows.length > 0; +} + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + + // ─── 1. 售后类型表 ───────────────────────────────────────── + if (!exists(TYPE_TABLE)) { + await queryInterface.createTable(TYPE_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义,仅该仓库可见)', + }, + type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '售后类型编码:order/receiving/entry/stockout,仓库自定义可自定义编码', + }, + name: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后类型名称', + }, + is_system: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否系统级:1=系统级(全部仓库可读,不允许编辑/删除),0=仓库自定义', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序值,越小越靠前', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + // 仓库内类型编码唯一(系统级 warehouse_id=NULL 不参与唯一约束,系统编码唯一性由应用层保证) + await queryInterface.addIndex(TYPE_TABLE, [ 'type', 'warehouse_id' ], { + unique: true, + name: 'uk_type_warehouse', + }); + await queryInterface.addIndex(TYPE_TABLE, [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + await queryInterface.addIndex(TYPE_TABLE, [ 'is_system' ], { + name: 'idx_is_system', + }); + } + + // ─── 2. 售后子类型表 ─────────────────────────────────────── + if (!exists(SUB_TYPE_TABLE)) { + await queryInterface.createTable(SUB_TYPE_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义,仅该仓库可见)', + }, + type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '所属售后类型编码(对应 wms_after_sale_type.type)', + }, + sub_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后子类型编码,与 type 组成二级分类(与 wms_after_sale.sub_type 对应)', + }, + name: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后子类型名称', + }, + is_system: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否系统级:1=系统级(全部仓库可读,不允许编辑/删除),0=仓库自定义', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序值,越小越靠前', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + // 同一类型下仓库内子类型编码唯一 + await queryInterface.addIndex(SUB_TYPE_TABLE, [ 'type', 'sub_type', 'warehouse_id' ], { + unique: true, + name: 'uk_type_subtype_warehouse', + }); + await queryInterface.addIndex(SUB_TYPE_TABLE, [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + await queryInterface.addIndex(SUB_TYPE_TABLE, [ 'is_system' ], { + name: 'idx_is_system', + }); + } + + // ─── 3. 播种现有类型为系统级(先查后插,幂等) ─────────────── + const now = new Date(); + for (const [ typeIndex, item ] of SYSTEM_AFTER_SALE_TYPES.entries()) { + const typeExists = await findSystemIds(queryInterface, TYPE_TABLE, '`type` = :type', { type: item.type }); + if (!typeExists) { + await queryInterface.bulkInsert(TYPE_TABLE, [{ + warehouse_id: null, + type: item.type, + name: item.name, + is_system: 1, + is_enabled: 1, + sort_order: typeIndex + 1, + created_at: now, + updated_at: now, + }]); + } + + const subTypeRows = []; + for (const [ subIndex, sub ] of item.subTypes.entries()) { + const subExists = await findSystemIds( + queryInterface, + SUB_TYPE_TABLE, + '`type` = :type AND `sub_type` = :subType', + { type: item.type, subType: sub.sub_type } + ); + if (!subExists) { + subTypeRows.push({ + warehouse_id: null, + type: item.type, + sub_type: sub.sub_type, + name: sub.name, + is_system: 1, + is_enabled: 1, + sort_order: subIndex + 1, + created_at: now, + updated_at: now, + }); + } + } + if (subTypeRows.length > 0) { + await queryInterface.bulkInsert(SUB_TYPE_TABLE, subTypeRows); + } + } + }, + + down: async queryInterface => { + await queryInterface.dropTable(SUB_TYPE_TABLE); + await queryInterface.dropTable(TYPE_TABLE); + }, +}; diff --git a/database/migrations/20260916150000-create-wms-after-sale-keyword.js b/database/migrations/20260916150000-create-wms-after-sale-keyword.js new file mode 100644 index 0000000..78114c1 --- /dev/null +++ b/database/migrations/20260916150000-create-wms-after-sale-keyword.js @@ -0,0 +1,162 @@ +'use strict'; + +/** + * 创建售后关键词表 wms_after_sale_keyword:关键词 → 售后子类型 映射。 + * + * 语义: + * - 多个关键词可对应同一个售后子类型(1:N),一个关键词在同一仓库内唯一(只映射一个子类型)。 + * - 仓库维度隔离:warehouse_id=NULL + is_system=1 为系统级关键词,全部仓库可见; + * warehouse_id=仓库ID + is_system=0 为仓库自定义关键词,仅该仓库可见。 + * - 匹配优先级:sort_order 小者优先(AI 按关键词推断子类型时,先取仓库自定义+系统级合并列表, + * 按关键词长度降序、sort_order 升序匹配)。 + * + * 数据播种:将 app/service/inbox/rules.js 中硬编码的 EXPRESS_SUB_TYPE_RULES + * (快递反馈→订单售后子类型 8 组关键词)作为系统级写入本表。 + * 由于 MySQL 唯一索引对 NULL 不生效,播种采用"先查后插"保证幂等。 + */ + +const TABLE = 'wms_after_sale_keyword'; +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; + +/** + * 系统级预设关键词(来源:inbox/rules.js EXPRESS_SUB_TYPE_RULES,type=order)。 + * @type {Array<{sub_type: string, keywords: string[]}>} + */ +const SYSTEM_KEYWORD_RULES = [ + { sub_type: 'verify_delivery', keywords: [ '核实签收', '签收核实', '已签收', '签收' ] }, + { sub_type: 'damage', keywords: [ '破损', '坏了', '破损件' ] }, + { sub_type: 'missing_item', keywords: [ '少发', '漏发', '发少' ] }, + { sub_type: 'change_address', keywords: [ '改地址', '地址更改', '改址' ] }, + { sub_type: 'change_carrier', keywords: [ '换快递', '改快递' ] }, + { sub_type: 'urge', keywords: [ '催件', '催派', '催促' ] }, + { sub_type: 'delivery_delay', keywords: [ '发货延迟', '延迟发货', '催发货' ] }, + { sub_type: 'rejected', keywords: [ '拒收' ] }, +]; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE); + + // ─── 建表 ───────────────────────────────────────────────── + if (!exists) { + await queryInterface.createTable(TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义,仅该仓库可见)', + }, + sub_type_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + keyword: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '关键词,命中即映射到对应售后子类型', + }, + is_system: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否系统级:1=系统级(全部仓库可读,不允许编辑/删除),0=仓库自定义', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '匹配优先级,数值小者优先(同长度命中时生效)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + // 同一仓库内关键词唯一(系统级 warehouse_id=NULL 不参与唯一约束,由应用层保证) + await queryInterface.addIndex(TABLE, [ 'keyword', 'warehouse_id' ], { + unique: true, + name: 'uk_keyword_warehouse', + }); + await queryInterface.addIndex(TABLE, [ 'sub_type_id' ], { + name: 'idx_sub_type_id', + }); + await queryInterface.addIndex(TABLE, [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + await queryInterface.addIndex(TABLE, [ 'is_system' ], { + name: 'idx_is_system', + }); + } + + // ─── 播种系统级关键词(先查后插,幂等) ──────────────────── + const { sequelize } = queryInterface; + const now = new Date(); + for (const [ ruleIndex, rule ] of SYSTEM_KEYWORD_RULES.entries()) { + // 定位系统级订单子类型(warehouse_id IS NULL) + const subRows = await sequelize.query( + `SELECT id FROM \`${SUB_TYPE_TABLE}\` + WHERE type = 'order' AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 + LIMIT 1`, + { replacements: { subType: rule.sub_type }, type: sequelize.QueryTypes.SELECT } + ); + if (subRows.length === 0) { + console.warn(`[MIGRATION] 跳过播种:未找到系统级子类型 order.${rule.sub_type}`); + continue; + } + const subTypeId = subRows[0].id; + + const rows = []; + for (const [ kwIndex, kw ] of rule.keywords.entries()) { + const existsRows = await sequelize.query( + `SELECT id FROM \`${TABLE}\` + WHERE keyword = :kw AND warehouse_id IS NULL AND is_system = 1 + LIMIT 1`, + { replacements: { kw }, type: sequelize.QueryTypes.SELECT } + ); + if (existsRows.length === 0) { + rows.push({ + warehouse_id: null, + sub_type_id: subTypeId, + keyword: kw, + is_system: 1, + is_enabled: 1, + sort_order: ruleIndex * 100 + kwIndex, + created_at: now, + updated_at: now, + }); + } + } + if (rows.length > 0) { + await queryInterface.bulkInsert(TABLE, rows); + } + } + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE); + }, +}; diff --git a/database/migrations/20260916160000-create-wms-inbox-number-rule-and-link-sub-type.js b/database/migrations/20260916160000-create-wms-inbox-number-rule-and-link-sub-type.js new file mode 100644 index 0000000..43cf4cb --- /dev/null +++ b/database/migrations/20260916160000-create-wms-inbox-number-rule-and-link-sub-type.js @@ -0,0 +1,91 @@ +'use strict'; + +/** + * 创建取号规则表 wms_inbox_number_rule。 + * + * 语义:从接收到的消息中,关键词命中售后子类型后,按该子类型关联的取号规则 + * 用正则从消息文本中提取符合规则的单据号,用于替代硬编码的下一步处理。 + * 子类型与规则的关联见 20260916162000-create-sub-type-number-rule-relation.js(多对多)。 + * + * 提取目标类型(target)枚举: + * - waybill_no 运单号 + * - receiving_no 收货单号 + * - entry_order_no 入库单号 + * - stockout_no 出库单号 + * - order_no 订单编号 + * - source_order_codes 交易平台订单编号(多个合成) + * - express_name 快递名称 + * - plate_no 车牌号 + */ + +const RULE_TABLE = 'wms_inbox_number_rule'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + + // ─── 1. 建取号规则表 ─────────────────────────────────────── + if (!exists(RULE_TABLE)) { + await queryInterface.createTable(RULE_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '规则名称,如:运单号提取/收货单号提取/平台订单号提取', + }, + target: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '提取目标类型:waybill_no/receiving_no/entry_order_no/stockout_no/order_no/source_order_codes/express_name/plate_no', + }, + regexp: { + type: Sequelize.STRING(500), + allowNull: false, + comment: '取号正则(JS 正则源字符串,不含首尾斜杠,支持全局匹配)', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '规则尝试顺序,数值小者优先', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + await queryInterface.addIndex(RULE_TABLE, [ 'name' ], { + unique: true, + name: 'uk_name', + }); + await queryInterface.addIndex(RULE_TABLE, [ 'target' ], { + name: 'idx_target', + }); + } + }, + + down: async queryInterface => { + const tables = await queryInterface.showAllTables(); + + const ruleExists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === RULE_TABLE); + if (ruleExists) { + await queryInterface.dropTable(RULE_TABLE); + } + }, +}; diff --git a/database/migrations/20260916161000-cleanup-legacy-wms-number-rule.js b/database/migrations/20260916161000-cleanup-legacy-wms-number-rule.js new file mode 100644 index 0000000..dfe2616 --- /dev/null +++ b/database/migrations/20260916161000-cleanup-legacy-wms-number-rule.js @@ -0,0 +1,36 @@ +'use strict'; + +/** + * 清理旧命名的取号规则表 wms_number_rule(已改名为 wms_inbox_number_rule)。 + * + * 背景:20260916160000 迁移最初以表名 wms_number_rule 在开发库执行过, + * 后与 wms_number_sequence 存在语义混淆风险,改名为 wms_inbox_number_rule。 + * 本迁移仅负责开发库旧表清理与旧 SequelizeMeta 记录清理;生产库从未执行旧表名, + * up 中幂等跳过。 + */ + +const LEGACY_TABLE = 'wms_number_rule'; +const LEGACY_MIGRATION_NAME = '20260916160000-create-wms-number-rule-and-link-sub-type.js'; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const legacyExists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === LEGACY_TABLE); + + // 旧表清理(仅开发库存在;旧表无数据,直接删除) + if (legacyExists) { + await queryInterface.dropTable(LEGACY_TABLE); + } + + // 旧迁移记录清理(仅开发库有该记录) + await sequelize.query( + 'DELETE FROM SequelizeMeta WHERE name = :name', + { replacements: { name: LEGACY_MIGRATION_NAME } } + ); + }, + + down: async () => { + // 旧表不重建(改名后不可逆回旧命名) + }, +}; diff --git a/database/migrations/20260916162000-create-sub-type-number-rule-relation.js b/database/migrations/20260916162000-create-sub-type-number-rule-relation.js new file mode 100644 index 0000000..ebb8be1 --- /dev/null +++ b/database/migrations/20260916162000-create-sub-type-number-rule-relation.js @@ -0,0 +1,92 @@ +'use strict'; + +/** + * 创建售后子类型与取号规则的多对多中间表 wms_after_sale_sub_type_rule, + * 并清理旧单列设计(number_rule_id,仅开发库存在)。 + * + * 语义:一个售后子类型可关联多个取号规则(如"改快递"需同时取运单号与平台订单号), + * 一个取号规则可被多个子类型复用。sort_order 表示同一子类型下规则的提取顺序。 + */ + +const RELATION_TABLE = 'wms_after_sale_sub_type_rule'; +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + + // ─── 1. 建中间表 ─────────────────────────────────────────── + if (!exists(RELATION_TABLE)) { + await queryInterface.createTable(RELATION_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + sub_type_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + number_rule_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '取号规则ID(关联 wms_inbox_number_rule.id)', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '同一子类型下规则的提取顺序,数值小者优先', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + await queryInterface.addIndex(RELATION_TABLE, [ 'sub_type_id', 'number_rule_id' ], { + unique: true, + name: 'uk_sub_type_rule', + }); + await queryInterface.addIndex(RELATION_TABLE, [ 'number_rule_id' ], { + name: 'idx_number_rule_id', + }); + } + + // ─── 2. 清理旧单列设计(仅开发库存在,生产幂等跳过) ───────── + if (exists(SUB_TYPE_TABLE)) { + const subTypeColumns = await queryInterface.describeTable(SUB_TYPE_TABLE); + if (subTypeColumns.number_rule_id) { + const indexes = await queryInterface.showIndex(SUB_TYPE_TABLE); + const legacyIndex = indexes.find( + i => (typeof i === 'string' ? i : i.name) === 'idx_number_rule_id' + ); + if (legacyIndex) { + await queryInterface.removeIndex(SUB_TYPE_TABLE, 'idx_number_rule_id'); + } + await queryInterface.removeColumn(SUB_TYPE_TABLE, 'number_rule_id'); + } + } + }, + + down: async queryInterface => { + const tables = await queryInterface.showAllTables(); + const relationExists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === RELATION_TABLE); + if (relationExists) { + await queryInterface.dropTable(RELATION_TABLE); + } + // 旧单列不恢复(已被多对多中间表取代) + }, +}; diff --git a/database/migrations/20260916170000-seed-inbox-number-rules.js b/database/migrations/20260916170000-seed-inbox-number-rules.js new file mode 100644 index 0000000..65203cd --- /dev/null +++ b/database/migrations/20260916170000-seed-inbox-number-rules.js @@ -0,0 +1,79 @@ +'use strict'; + +/** + * 播种取号规则数据:把 app/service/inbox/rules.js 现有硬编码的提取方法 + * (extractWaybills / extractOrders / EXPRESS_NAMES)落库为 wms_inbox_number_rule 规则。 + * + * 幂等设计:基于唯一索引 uk_name 做 INSERT IGNORE,不会重复插入。 + * + * 说明:现有提取逻辑中正则之外的部分(运单号过滤:手机号/座机/日期戳/售后单号; + * 订单号兜底取纯数字)仍由代码兜底处理,正则列只存核心匹配源串。 + */ + +const TABLE = 'wms_inbox_number_rule'; + +const SEED_RULES = [ + { + name: '运单号提取', + target: 'waybill_no', + // 对应 extractWaybills 的核心匹配:[A-Za-z0-9_-]{10,24}(过滤逻辑由代码兜底) + regexp: '[A-Za-z0-9_-]{10,24}', + sort_order: 1, + }, + { + name: '订单编号提取', + target: 'order_no', + // 对应 extractOrders 优先规则:SYS/SO/DD 前缀及字母数字混合号 + regexp: '(? { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE); + if (!exists) { + throw new Error(`表 ${TABLE} 不存在,请先执行 20260916160000-create-wms-inbox-number-rule-and-link-sub-type.js`); + } + + const { sequelize } = queryInterface; + for (const rule of SEED_RULES) { + await sequelize.query( + 'INSERT IGNORE INTO `' + TABLE + '` (name, target, `regexp`, sort_order, created_at, updated_at) ' + + 'VALUES (:name, :target, :regexp, :sortOrder, NOW(), NOW())', + { + replacements: { + name: rule.name, + target: rule.target, + regexp: rule.regexp, + sortOrder: rule.sort_order, + }, + type: sequelize.QueryTypes.INSERT, + } + ); + } + }, + + down: async queryInterface => { + const names = SEED_RULES.map(r => r.name); + await queryInterface.sequelize.query( + 'DELETE FROM `' + TABLE + '` WHERE name IN (:names)', + { replacements: { names } } + ); + }, +}; diff --git a/database/migrations/20260916180000-seed-sub-type-number-rule-relations.js b/database/migrations/20260916180000-seed-sub-type-number-rule-relations.js new file mode 100644 index 0000000..3c69d7f --- /dev/null +++ b/database/migrations/20260916180000-seed-sub-type-number-rule-relations.js @@ -0,0 +1,106 @@ +'use strict'; + +/** + * 播种系统级售后子类型与取号规则的关联数据(多对多中间表)。 + * + * 映射来源:order 类型系统子类型的消息处理需求—— + * - 改地址/换快递:需运单号 + 平台订单号(改快递操作需要对应平台单号) + * - 其余子类型:目前仅需运单号 + * + * 幂等设计:基于唯一索引 uk_sub_type_rule(sub_type_id, number_rule_id) 做 INSERT IGNORE, + * 不会重复插入已存在的关联。子类型按(type=order + warehouse_id IS NULL)定位, + * 规则按 name 定位。 + */ + +const RELATION_TABLE = 'wms_after_sale_sub_type_rule'; +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const RULE_TABLE = 'wms_inbox_number_rule'; + +/** 子类型编码 → 规则名称列表(按 sort_order 顺序) */ +const SUB_TYPE_RULE_MAP = [ + { sub_type: 'verify_delivery', rules: [ '运单号提取' ] }, + { sub_type: 'damage', rules: [ '运单号提取' ] }, + { sub_type: 'missing_item', rules: [ '运单号提取' ] }, + { sub_type: 'change_address', rules: [ '运单号提取', '平台订单号提取' ] }, + { sub_type: 'change_carrier', rules: [ '运单号提取', '平台订单号提取' ] }, + { sub_type: 'urge', rules: [ '运单号提取' ] }, + { sub_type: 'delivery_delay', rules: [ '运单号提取' ] }, + { sub_type: 'rejected', rules: [ '运单号提取' ] }, +]; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + + for (const item of SUB_TYPE_RULE_MAP) { + // 定位系统级 order 子类型 + const subRows = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1', + { + replacements: { type: 'order', subType: item.sub_type }, + type: sequelize.QueryTypes.SELECT, + } + ); + if (subRows.length === 0) { + console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${item.sub_type}`); + continue; + } + const subTypeId = subRows[0].id; + + for (const [ ruleIndex, ruleName ] of item.rules.entries()) { + const ruleRows = await sequelize.query( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1', + { replacements: { name: ruleName }, type: sequelize.QueryTypes.SELECT } + ); + if (ruleRows.length === 0) { + console.warn(`[MIGRATION] 跳过:未找到取号规则 ${ruleName}`); + continue; + } + const ruleId = ruleRows[0].id; + + await sequelize.query( + 'INSERT IGNORE INTO `' + RELATION_TABLE + '` ' + + '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) ' + + 'VALUES (:subTypeId, :ruleId, :sortOrder, NOW(), NOW())', + { + replacements: { subTypeId, ruleId, sortOrder: ruleIndex + 1 }, + type: sequelize.QueryTypes.INSERT, + } + ); + } + } + }, + + down: async queryInterface => { + const { sequelize } = queryInterface; + for (const item of SUB_TYPE_RULE_MAP) { + const subRows = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1', + { + replacements: { type: 'order', subType: item.sub_type }, + type: sequelize.QueryTypes.SELECT, + } + ); + if (subRows.length === 0) continue; + const subTypeId = subRows[0].id; + + const ruleRows = await sequelize.query( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE name IN (:names)', + { + replacements: { names: item.rules }, + type: sequelize.QueryTypes.SELECT, + } + ); + if (ruleRows.length === 0) continue; + const ruleIds = ruleRows.map(r => r.id); + + await sequelize.query( + 'DELETE FROM `' + RELATION_TABLE + '` ' + + 'WHERE sub_type_id = :subTypeId AND number_rule_id IN (:ruleIds)', + { replacements: { subTypeId, ruleIds } } + ); + } + }, +}; diff --git a/database/migrations/20260916190000-create-wms-after-sale-reply.js b/database/migrations/20260916190000-create-wms-after-sale-reply.js new file mode 100644 index 0000000..ccdaf72 --- /dev/null +++ b/database/migrations/20260916190000-create-wms-after-sale-reply.js @@ -0,0 +1,94 @@ +'use strict'; + +/** + * 创建售后自定义回复表 wms_after_sale_reply。 + * + * 语义:消息关键词命中售后子类型并完成处理后,按子类型返回自定义回复文案。 + * - 系统级(warehouse_id=NULL):全部仓库可读的默认回复。 + * - 仓库级(warehouse_id=仓库ID):该仓库自定义回复,设置了自动覆盖系统级 + * (读取时优先仓库级,无仓库级再回退系统级)。 + * - 每个仓库每种子类型只允许一条仓库级回复(唯一索引 uk_warehouse_sub_type 保证); + * 系统级每种子类型只允许一条,由应用层校验(MySQL 唯一索引对 NULL 不生效)。 + */ + +const TABLE = 'wms_after_sale_reply'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE); + if (exists) return; + + await queryInterface.createTable(TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID(NULL=系统级默认回复;非NULL=仓库级自定义回复,覆盖系统级)', + }, + sub_type_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + reply: { + type: Sequelize.TEXT, + allowNull: false, + comment: '自定义回复文案(支持换行,可含占位符)', + }, + is_reply: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否回复:1=命中后回复,0=静默不回复', + }, + no_number_hint: { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '未取到单据号时的引导语(如:请提供运单号;为空则用默认引导语)', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用(停用视为未设置,回退系统级)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + // 仓库级:每仓库每子类型唯一(系统级 warehouse_id=NULL 由应用层保证唯一) + await queryInterface.addIndex(TABLE, [ 'warehouse_id', 'sub_type_id' ], { + unique: true, + name: 'uk_warehouse_sub_type', + }); + await queryInterface.addIndex(TABLE, [ 'sub_type_id' ], { + name: 'idx_sub_type_id', + }); + await queryInterface.addIndex(TABLE, [ 'is_enabled' ], { + name: 'idx_is_enabled', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE); + }, +}; diff --git a/database/migrations/20260916191000-add-reply-fields.js b/database/migrations/20260916191000-add-reply-fields.js new file mode 100644 index 0000000..ea92b86 --- /dev/null +++ b/database/migrations/20260916191000-add-reply-fields.js @@ -0,0 +1,54 @@ +'use strict'; + +/** + * 给 wms_after_sale_reply 补两列(开发库补丁,生产幂等跳过)。 + * + * 背景:20260916190000 建表迁移在开发库执行后补充了两个字段设计—— + * - is_reply:是否回复(1=命中后回复,0=静默不回复) + * - no_number_hint:未取到单据号时的引导语 + * 原迁移文件已同步更新,生产执行时会直接带两列,本迁移在生产幂等跳过。 + */ + +const TABLE = 'wms_after_sale_reply'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE); + if (!exists) return; + + const columns = await queryInterface.describeTable(TABLE); + if (!columns.is_reply) { + await queryInterface.addColumn(TABLE, 'is_reply', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否回复:1=命中后回复,0=静默不回复', + after: 'reply', + }); + } + if (!columns.no_number_hint) { + await queryInterface.addColumn(TABLE, 'no_number_hint', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '未取到单据号时的引导语(如:请提供运单号;为空则用默认引导语)', + after: 'is_reply', + }); + } + }, + + down: async queryInterface => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE); + if (!exists) return; + + const columns = await queryInterface.describeTable(TABLE); + if (columns.no_number_hint) { + await queryInterface.removeColumn(TABLE, 'no_number_hint'); + } + if (columns.is_reply) { + await queryInterface.removeColumn(TABLE, 'is_reply'); + } + }, +}; diff --git a/database/migrations/20260916192000-seed-vehicle-plate-rule.js b/database/migrations/20260916192000-seed-vehicle-plate-rule.js new file mode 100644 index 0000000..ab9ef7a --- /dev/null +++ b/database/migrations/20260916192000-seed-vehicle-plate-rule.js @@ -0,0 +1,53 @@ +'use strict'; + +/** + * 播种"车牌提取"取号规则到 wms_inbox_number_rule。 + * + * 正则说明:中国车牌(含传统蓝牌/黄牌与新能源绿牌,兼容"·"分隔点): + * - 省简称 + 发牌机关字母 + 5 位号码(传统) + * - 省简称 + 字母 + D/F 开头 6 位号码(新能源) + * - 末位兼容 挂/学/警/港/澳 等特殊字符 + * + * 幂等设计:基于唯一索引 uk_name 做 INSERT IGNORE。 + */ + +const TABLE = 'wms_inbox_number_rule'; + +const SEED_RULE = { + name: '车牌提取', + target: 'plate_no', + regexp: '[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][·.]?(?:[DF][A-HJ-NP-Z0-9]{5}|[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])', + sort_order: 5, +}; + +module.exports = { + up: async queryInterface => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE); + if (!exists) { + throw new Error(`表 ${TABLE} 不存在,请先执行 20260916160000-create-wms-inbox-number-rule-and-link-sub-type.js`); + } + + const { sequelize } = queryInterface; + await sequelize.query( + 'INSERT IGNORE INTO `' + TABLE + '` (name, target, `regexp`, sort_order, created_at, updated_at) ' + + 'VALUES (:name, :target, :regexp, :sortOrder, NOW(), NOW())', + { + replacements: { + name: SEED_RULE.name, + target: SEED_RULE.target, + regexp: SEED_RULE.regexp, + sortOrder: SEED_RULE.sort_order, + }, + type: sequelize.QueryTypes.INSERT, + } + ); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query( + 'DELETE FROM `' + TABLE + '` WHERE name = :name', + { replacements: { name: SEED_RULE.name } } + ); + }, +}; diff --git a/database/migrations/20260916192100-fix-plate-regexp.js b/database/migrations/20260916192100-fix-plate-regexp.js new file mode 100644 index 0000000..5329d6f --- /dev/null +++ b/database/migrations/20260916192100-fix-plate-regexp.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 修正"车牌提取"规则正则(开发库已插入旧正则,生产幂等)。 + * + * 问题:旧正则 alternation 顺序导致新能源 6 位尾号被截断 + * ("粤BD12345" 匹配成 "粤BD1234")。 + * 修正:新能源分支 [DF][A-HJ-NP-Z0-9]{5} 前置优先,传统 5 位尾号分支靠后。 + */ + +const TABLE = 'wms_inbox_number_rule'; + +const FIXED_REGEXP = '[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][·.]?(?:[DF][A-HJ-NP-Z0-9]{5}|[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query( + 'UPDATE `' + TABLE + '` SET `regexp` = :regexp, updated_at = NOW() WHERE name = :name', + { replacements: { name: '车牌提取', regexp: FIXED_REGEXP } } + ); + }, + + // eslint-disable-next-line no-unused-vars + down: async queryInterface => { + // 回滚不做(旧正则有截断缺陷,不回退) + }, +}; diff --git a/database/migrations/20260916210000-create-wms-inbox-arrival-register.js b/database/migrations/20260916210000-create-wms-inbox-arrival-register.js new file mode 100644 index 0000000..86c357d --- /dev/null +++ b/database/migrations/20260916210000-create-wms-inbox-arrival-register.js @@ -0,0 +1,53 @@ +'use strict'; + +/** + * 创建到货登记表 wms_inbox_arrival_register。 + * + * 用途:货主/仓库群发送"到货+车牌号"时,AI 提取车牌号并登记, + * 记录货主ID、仓库ID、登记时间(created_at)、车牌号。 + * + * 索引: + * idx_warehouse_plate(仓库+车牌查询某车牌在该仓库的登记记录) + * idx_store_id(按货主查询) + */ + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE } = Sequelize; + await queryInterface.createTable('wms_inbox_arrival_register', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID(仓库群登记时无货主,允许为空)', + }, + license_plate: { + type: STRING(20), + allowNull: false, + comment: '车牌号', + }, + created_at: { type: DATE, allowNull: false, comment: '登记时间' }, + updated_at: { type: DATE, allowNull: false, comment: '更新时间' }, + }); + + await queryInterface.addIndex('wms_inbox_arrival_register', [ 'warehouse_id', 'license_plate' ], { name: 'idx_warehouse_plate' }); + await queryInterface.addIndex('wms_inbox_arrival_register', [ 'store_id' ], { name: 'idx_store_id' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable('wms_inbox_arrival_register'); + }, +}; diff --git a/database/migrations/20260916213000-fix-plate-regexp-yue-variant.js b/database/migrations/20260916213000-fix-plate-regexp-yue-variant.js new file mode 100644 index 0000000..36f0d79 --- /dev/null +++ b/database/migrations/20260916213000-fix-plate-regexp-yue-variant.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 修复"车牌提取"规则正则:省份简称兼容异体字。 + * + * 问题:用户输入"粵BEH9852到货"(粵 U+7CB5 为"粤 U+7CA4"的异体写法), + * 旧正则只含简体"粤",无法匹配导致"未识别到车牌号"。 + * 修正:省份字符类中"粤"后补充异体"粵"。 + */ + +const TABLE = 'wms_inbox_number_rule'; + +const FIXED_REGEXP = '[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤粵青藏川宁琼使领][A-HJ-NP-Z][·.]?(?:[DF][A-HJ-NP-Z0-9]{5}|[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query( + 'UPDATE `' + TABLE + '` SET `regexp` = :regexp, updated_at = NOW() WHERE name = :name', + { replacements: { name: '车牌提取', regexp: FIXED_REGEXP } } + ); + }, + + // eslint-disable-next-line no-unused-vars + down: async queryInterface => { + // 回滚不做(旧正则有异体字漏匹配缺陷,不回退) + }, +}; diff --git a/database/migrations/20260916223000-add-consumed-to-wms-inbox-arrival-register.js b/database/migrations/20260916223000-add-consumed-to-wms-inbox-arrival-register.js new file mode 100644 index 0000000..927eb02 --- /dev/null +++ b/database/migrations/20260916223000-add-consumed-to-wms-inbox-arrival-register.js @@ -0,0 +1,32 @@ +'use strict'; + +/** + * 到货登记表增加消费字段(离场登记)。 + * + * 用途:离场方法(departure)命中 6 小时内未消费的登记后, + * 标记 consumed=1 并记录 consumed_at,防止重复离场。 + */ + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { TINYINT, DATE } = Sequelize; + await queryInterface.addColumn('wms_inbox_arrival_register', 'consumed', { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否已消费(离场登记)0=未消费 1=已消费', + }); + await queryInterface.addColumn('wms_inbox_arrival_register', 'consumed_at', { + type: DATE, + allowNull: true, + comment: '消费时间(离场时间)', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_inbox_arrival_register', 'consumed_at'); + await queryInterface.removeColumn('wms_inbox_arrival_register', 'consumed'); + }, +}; diff --git a/database/migrations/20260917100000-add-template-reply-enabled-to-inbox-group.js b/database/migrations/20260917100000-add-template-reply-enabled-to-inbox-group.js new file mode 100644 index 0000000..c4e60f9 --- /dev/null +++ b/database/migrations/20260917100000-add-template-reply-enabled-to-inbox-group.js @@ -0,0 +1,30 @@ +'use strict'; + +/** + * wms_inbox_group 增加「是否模板消息回复」开关列。 + * 与 ai_enabled(是否AI回复)并列:ai_enabled 控制是否启用 AI 处理, + * template_reply_enabled 控制命中处理后是否以模板消息形式回复(关闭则走普通文本回复)。 + */ + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.template_reply_enabled) return; + + await queryInterface.addColumn(TABLE_NAME, 'template_reply_enabled', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否启用模板消息回复: 0=关闭(普通文本回复) 1=开启(模板消息回复)', + after: 'ai_enabled', + }); + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns.template_reply_enabled) return; + await queryInterface.removeColumn(TABLE_NAME, 'template_reply_enabled'); + }, +}; diff --git a/database/migrations/20260917110000-create-after-sale-function-and-relation.js b/database/migrations/20260917110000-create-after-sale-function-and-relation.js new file mode 100644 index 0000000..489e2c0 --- /dev/null +++ b/database/migrations/20260917110000-create-after-sale-function-and-relation.js @@ -0,0 +1,227 @@ +'use strict'; + +/** + * 创建售后处理函数表 wms_after_sale_function 与 子类型-函数关系表 + * wms_after_sale_sub_type_function,并播种系统预设数据。 + * + * 语义(新消息处理链路): + * 消息命中售后子类型 → 查关系表取该子类型的处理方法(function_code) + * → 从 inbox functions registry 按 function_code 调用 handler。 + * - 系统预设子类型:固定关联(本迁移 seed,不可改)。 + * - 仓库自定义子类型:可自行选择处理方法(增删关系)。 + * 处理函数在代码注册(registry)时同步 upsert 到函数表;本迁移先播种 + * 现有 register 的售后处理类函数,保证表不空。 + * + * 注:queryOrder/queryReturn/queryPackVideo/queryWeight 等查询类函数 + * 走规则引擎关键词路由,不属于售后子类型处理链路,不入此表。 + */ + +const FUNCTION_TABLE = 'wms_after_sale_function'; +const RELATION_TABLE = 'wms_after_sale_sub_type_function'; +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; + +/** 系统预设处理函数(function_code 与 inbox/functions.js register 名一致) */ +const SYSTEM_FUNCTIONS = [ + { function_code: 'interceptWaybill', name: '拦截处理', description: '批量创建拦截售后工单,设置订单/运单拦截状态并通知快递售后群' }, + { function_code: 'requestPickup', name: '揽收处理', description: '创建揽收售后工单,原文转发快递揽收群(无揽收群回退售后群)' }, + { function_code: 'cancelIntercept', name: '取消拦截处理', description: '取消拦截:已有工单追加记录,无工单按拦截规则创建并通知快递群' }, + { function_code: 'handleStoreFeedback', name: '货主问题反馈', description: '错发/破损/多发/少发类反馈建工单(货主售后群,不转发快递群)' }, + { function_code: 'changeAddr', name: '改地址/催退回/催件', description: '改地址/催退回/催件诉求建工单并原文转发快递售后群' }, + { function_code: 'weishoudao', name: '核实签收', description: '核实签收诉求建工单并转发快递售后群核实' }, + { function_code: 'changeExpress', name: '改快递', description: '未分配快递的待处理订单修改目标快递' }, + { function_code: 'createPostnum', name: '出单/分配快递号', description: '已审核未取号订单提交分配快递号并回传平台' }, + { function_code: 'handleExpressFeedback', name: '快递群通用反馈', description: '快递群反馈:已有工单追加记录,无工单按运单自动建单(AI 传入 type/sub_type)' }, +]; + +/** 系统预设子类型 → 处理函数(固定关联) */ +const SYSTEM_SUB_TYPE_FUNCTIONS = [ + { sub_type: 'intercept', functions: [ 'interceptWaybill' ] }, + { sub_type: 'pickup', functions: [ 'requestPickup' ] }, + { sub_type: 'damage', functions: [ 'handleStoreFeedback' ] }, + { sub_type: 'missing_item', functions: [ 'handleStoreFeedback' ] }, + { sub_type: 'mis_shipment', functions: [ 'handleStoreFeedback' ] }, + { sub_type: 'extra_item', functions: [ 'handleStoreFeedback' ] }, + { sub_type: 'change_address', functions: [ 'changeAddr' ] }, + { sub_type: 'rejected', functions: [ 'changeAddr' ] }, + { sub_type: 'urge', functions: [ 'changeAddr' ] }, + { sub_type: 'verify_delivery', functions: [ 'weishoudao' ] }, + { sub_type: 'change_carrier', functions: [ 'changeExpress' ] }, + { sub_type: 'delivery_delay', functions: [ 'createPostnum' ] }, +]; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + const { sequelize } = queryInterface; + + // ─── 1. 函数表 ───────────────────────────────────────────── + if (!exists(FUNCTION_TABLE)) { + await queryInterface.createTable(FUNCTION_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + function_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '处理函数编码(与 inbox functions registry 注册名一致)', + }, + name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '处理函数名称', + }, + description: { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '处理函数说明', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序值,越小越靠前', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + await queryInterface.addIndex(FUNCTION_TABLE, [ 'function_code' ], { + unique: true, + name: 'uk_function_code', + }); + } + + // ─── 2. 关系表 ───────────────────────────────────────────── + if (!exists(RELATION_TABLE)) { + await queryInterface.createTable(RELATION_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + sub_type_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + function_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '处理函数ID(关联 wms_after_sale_function.id)', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '同子类型下处理函数执行顺序,数值小者优先', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + await queryInterface.addIndex(RELATION_TABLE, [ 'sub_type_id', 'function_id' ], { + unique: true, + name: 'uk_sub_type_function', + }); + await queryInterface.addIndex(RELATION_TABLE, [ 'function_id' ], { + name: 'idx_function_id', + }); + } + + // ─── 3. 播种系统预设函数(INSERT IGNORE 基于 uk_function_code) ── + for (const [ idx, fn ] of SYSTEM_FUNCTIONS.entries()) { + await sequelize.query( + 'INSERT IGNORE INTO `' + FUNCTION_TABLE + '` ' + + '(function_code, name, description, is_enabled, sort_order, created_at, updated_at) ' + + 'VALUES (:code, :name, :description, 1, :sortOrder, NOW(), NOW())', + { + replacements: { + code: fn.function_code, + name: fn.name, + description: fn.description, + sortOrder: idx + 1, + }, + type: sequelize.QueryTypes.INSERT, + } + ); + } + + // ─── 4. 播种系统预设子类型 → 函数固定关联 ──────────────────── + for (const item of SYSTEM_SUB_TYPE_FUNCTIONS) { + const subRows = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1', + { + replacements: { type: 'order', subType: item.sub_type }, + type: sequelize.QueryTypes.SELECT, + } + ); + if (subRows.length === 0) { + console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${item.sub_type}`); + continue; + } + const subTypeId = subRows[0].id; + + for (const [ fnIndex, code ] of item.functions.entries()) { + const fnRows = await sequelize.query( + 'SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :code LIMIT 1', + { replacements: { code }, type: sequelize.QueryTypes.SELECT } + ); + if (fnRows.length === 0) { + console.warn(`[MIGRATION] 跳过:未找到处理函数 ${code}`); + continue; + } + const functionId = fnRows[0].id; + + await sequelize.query( + 'INSERT IGNORE INTO `' + RELATION_TABLE + '` ' + + '(sub_type_id, function_id, sort_order, created_at, updated_at) ' + + 'VALUES (:subTypeId, :functionId, :sortOrder, NOW(), NOW())', + { + replacements: { subTypeId, functionId, sortOrder: fnIndex + 1 }, + type: sequelize.QueryTypes.INSERT, + } + ); + } + } + }, + + down: async queryInterface => { + await queryInterface.dropTable(RELATION_TABLE); + await queryInterface.dropTable(FUNCTION_TABLE); + }, +}; diff --git a/database/migrations/20260917120000-create-after-sale-sub-type-group-relation.js b/database/migrations/20260917120000-create-after-sale-sub-type-group-relation.js new file mode 100644 index 0000000..c92a5cd --- /dev/null +++ b/database/migrations/20260917120000-create-after-sale-sub-type-group-relation.js @@ -0,0 +1,134 @@ +'use strict'; + +/** + * 创建 群类型 ↔ 售后子类型 关联表 wms_after_sale_sub_type_group。 + * + * 语义:多个群类型可对应同一个售后子类型(多对多),表示该子类型的 + * 售后诉求可以在哪些类型的群中发起/处理。群粒度精确到子类型: + * group_type=store/warehouse/express,sub_group=群子类型 + * (store: after_sales/finance/receiving;warehouse: customer_service/...;express: pickup/after_sales)。 + * - is_system=1:系统预设关联(系统级子类型的默认分配),锁定不可更改。 + * - is_system=0:自定义关联(仓库自定义子类型可自行选择群类型)。 + */ + +const TABLE = 'wms_after_sale_sub_type_group'; +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; + +/** 系统预设:order 类型系统级子类型 → 群类型+群子类型(依据现有函数 groups 声明) */ +const SYSTEM_SUB_TYPE_GROUPS = [ + // 货主售后群(bound:store:after_sales) + { sub_type: 'intercept', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'warehouse', sub_group: 'customer_service' }] }, + { sub_type: 'pickup', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'warehouse', sub_group: 'customer_service' }] }, + { sub_type: 'damage', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'missing_item', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'mis_shipment', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'extra_item', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'change_address', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'rejected', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'urge', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'verify_delivery', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'change_carrier', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'delivery_delay', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] }, + { sub_type: 'logistics_issue', groups: [{ group_type: 'express', sub_group: 'after_sales' }] }, +]; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + const { sequelize } = queryInterface; + + // ─── 建表 ───────────────────────────────────────────────── + if (!exists(TABLE)) { + await queryInterface.createTable(TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + sub_type_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)', + }, + group_type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '群类型:store=货主群 / warehouse=仓库群 / express=快递群', + }, + sub_group: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '群子类型:store(after_sales/finance/receiving)、warehouse(customer_service/...)、express(pickup/after_sales)', + }, + is_system: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否系统预设关联:1=系统级子类型默认分配(锁定不可改),0=自定义', + }, + sort_order: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '排序值,越小越靠前', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + await queryInterface.addIndex(TABLE, [ 'sub_type_id', 'group_type', 'sub_group' ], { + unique: true, + name: 'uk_sub_type_group', + }); + await queryInterface.addIndex(TABLE, [ 'group_type', 'sub_group' ], { + name: 'idx_group_type', + }); + } + + // ─── 播种系统预设关联(INSERT IGNORE 基于 uk_sub_type_group) ── + for (const item of SYSTEM_SUB_TYPE_GROUPS) { + const subRows = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1', + { + replacements: { type: 'order', subType: item.sub_type }, + type: sequelize.QueryTypes.SELECT, + } + ); + if (subRows.length === 0) { + console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${item.sub_type}`); + continue; + } + const subTypeId = subRows[0].id; + + for (const [ idx, g ] of item.groups.entries()) { + await sequelize.query( + 'INSERT IGNORE INTO `' + TABLE + '` ' + + '(sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) ' + + 'VALUES (:subTypeId, :groupType, :subGroup, 1, :sortOrder, NOW(), NOW())', + { + replacements: { subTypeId, groupType: g.group_type, subGroup: g.sub_group, sortOrder: idx + 1 }, + type: sequelize.QueryTypes.INSERT, + } + ); + } + } + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE); + }, +}; diff --git a/database/migrations/20260917121000-add-sub-group-to-sub-type-group-relation.js b/database/migrations/20260917121000-add-sub-group-to-sub-type-group-relation.js new file mode 100644 index 0000000..e29f4d1 --- /dev/null +++ b/database/migrations/20260917121000-add-sub-group-to-sub-type-group-relation.js @@ -0,0 +1,68 @@ +'use strict'; + +/** + * 群类型-子类型关联表补充群子类型维度(开发库补丁,生产幂等跳过)。 + * + * 背景:20260917120000 建表时关联粒度只有主群类型,后补充 sub_group + * (群子类型)维度。原迁移已改为最终版(生产执行直接含 sub_group), + * 本迁移仅开发库:加列 + 按主类型回填子类型 + 重建唯一索引。 + * 回填规则与最终版 seed 一致:store/express→after_sales,warehouse→customer_service。 + */ + +const TABLE = 'wms_after_sale_sub_type_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE); + if (!exists) return; + + const columns = await queryInterface.describeTable(TABLE); + // 生产已含 sub_group(17120000 最终版)→ 跳过 + if (columns.sub_group) return; + + const { sequelize } = queryInterface; + + // 1. 加列 + await queryInterface.addColumn(TABLE, 'sub_group', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: '', + comment: '群子类型:store(after_sales/finance/receiving)、warehouse(customer_service/...)、express(pickup/after_sales)', + after: 'group_type', + }); + + // 2. 按主类型回填(与最终版 seed 一致) + await sequelize.query( + 'UPDATE `' + TABLE + '` SET sub_group = :afterSales WHERE group_type IN (:store, :express)', + { replacements: { afterSales: 'after_sales', store: 'store', express: 'express' } } + ); + await sequelize.query( + 'UPDATE `' + TABLE + '` SET sub_group = :customerService WHERE group_type = :warehouse', + { replacements: { customerService: 'customer_service', warehouse: 'warehouse' } } + ); + + // 3. 重建索引(旧 uk_sub_type_group 为 (sub_type_id, group_type),升级为含 sub_group) + const indexes = await queryInterface.showIndex(TABLE); + const legacyIndex = indexes.find(i => (typeof i === 'string' ? i : i.name) === 'uk_sub_type_group'); + if (legacyIndex) { + await queryInterface.removeIndex(TABLE, 'uk_sub_type_group'); + } + await queryInterface.addIndex(TABLE, [ 'sub_type_id', 'group_type', 'sub_group' ], { + unique: true, + name: 'uk_sub_type_group', + }); + + const legacyIdx = indexes.find(i => (typeof i === 'string' ? i : i.name) === 'idx_group_type'); + if (legacyIdx) { + await queryInterface.removeIndex(TABLE, 'idx_group_type'); + } + await queryInterface.addIndex(TABLE, [ 'group_type', 'sub_group' ], { + name: 'idx_group_type', + }); + }, + + down: async () => { + // 不回退(生产最终版即含 sub_group) + }, +}; diff --git a/database/migrations/20260917130000-fix-v2-rule-gaps.js b/database/migrations/20260917130000-fix-v2-rule-gaps.js new file mode 100644 index 0000000..83bd2a0 --- /dev/null +++ b/database/migrations/20260917130000-fix-v2-rule-gaps.js @@ -0,0 +1,85 @@ +'use strict'; + +/** + * 修复 v2 回信引擎配置链数据缺口(幂等,先查后插)。 + * + * 1. change_carrier(换快递)子类型关联"快递名称提取"取号规则: + * 换快递函数 changeExpress 需要目标快递(express 入参), + * 原种子只关联了运单号 + 平台单号,缺 express_name。 + * 2. 关键词表补充 intercept(拦截)/ pickup(揽收)子类型关键词: + * 原 22 个关键词仅覆盖 8 个子类型,拦截/揽收在 v2 引擎命中不了。 + */ + +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const RULE_TABLE = 'wms_inbox_number_rule'; +const RELATION_TABLE = 'wms_after_sale_sub_type_rule'; +const KEYWORD_TABLE = 'wms_after_sale_keyword'; + +/** 补充关键词(与 v1 函数 keywords 语义一致)。 */ +const MISSING_KEYWORDS = [ + { sub_type: 'intercept', keywords: [ '拦截', '退回', '召回', '追回', '取消快递' ] }, + { sub_type: 'pickup', keywords: [ '揽收', '上门取件', '取件', '退货取件' ] }, +]; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(SUB_TYPE_TABLE) || !exists(RULE_TABLE)) return; + + // ─── 1. change_carrier 关联 express_name 规则 ───────────────── + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL LIMIT 1', + { replacements: { type: 'order', subType: 'change_carrier' } } + ); + const [ ruleRows ] = await sequelize.query( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE target = :target AND name = :name LIMIT 1', + { replacements: { target: 'express_name', name: '快递名称提取' } } + ); + if (subRows.length > 0 && ruleRows.length > 0 && exists(RELATION_TABLE)) { + const subTypeId = subRows[0].id; + const ruleId = ruleRows[0].id; + const [ relRows ] = await sequelize.query( + 'SELECT id FROM `' + RELATION_TABLE + '` WHERE sub_type_id = :sid AND number_rule_id = :rid LIMIT 1', + { replacements: { sid: subTypeId, rid: ruleId } } + ); + if (relRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + RELATION_TABLE + '` (sub_type_id, number_rule_id, sort_order, created_at, updated_at) VALUES (:sid, :rid, 3, NOW(), NOW())', + { replacements: { sid: subTypeId, rid: ruleId } } + ); + } + } + + // ─── 2. 关键词补充(先查后插,MySQL 唯一索引对 NULL warehouse 不生效) ─── + if (exists(KEYWORD_TABLE)) { + for (const rule of MISSING_KEYWORDS) { + const [ subRows2 ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL LIMIT 1', + { replacements: { type: 'order', subType: rule.sub_type } } + ); + if (subRows2.length === 0) continue; + const subTypeId = subRows2[0].id; + let sortOrder = 0; + for (const kw of rule.keywords) { + const [ kwRows ] = await sequelize.query( + 'SELECT id FROM `' + KEYWORD_TABLE + '` WHERE keyword = :kw AND warehouse_id IS NULL LIMIT 1', + { replacements: { kw } } + ); + if (kwRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + KEYWORD_TABLE + '` (warehouse_id, sub_type_id, keyword, is_system, is_enabled, sort_order, created_at, updated_at) VALUES (NULL, :sid, :kw, 1, 1, :so, NOW(), NOW())', + { replacements: { sid: subTypeId, kw, so: sortOrder } } + ); + } + sortOrder += 1; + } + } + } + }, + + down: async () => { + // 不回退(种子类数据) + }, +}; diff --git a/database/migrations/20260917140000-add-extend-props-to-inbox-message.js b/database/migrations/20260917140000-add-extend-props-to-inbox-message.js new file mode 100644 index 0000000..861a234 --- /dev/null +++ b/database/migrations/20260917140000-add-extend-props-to-inbox-message.js @@ -0,0 +1,36 @@ +'use strict'; + +/** + * wms_inbox_message 增加 extend_props 列(回执扩展属性持久化,幂等)。 + * + * 背景:出站回执 notify.reply 的 extend_props(如开门指令等空文案回执的驱动属性) + * 此前只在首推时随报文发出,不落库。手动/定时重推时无法恢复 extend_props, + * 且 content 为空的 extend_props 回执被重推扫描直接跳过。加列后: + * - 首推写库持久化;重推从记录原样带回; + * - 空文案但含 extend_props 的出站记录可被重推。 + */ + +const TABLE = 'wms_inbox_message'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE); + if (!exists) return; + + const columns = await queryInterface.describeTable(TABLE); + if (columns.extend_props) return; + + await queryInterface.addColumn(TABLE, 'extend_props', { + type: Sequelize.JSON, + allowNull: true, + defaultValue: null, + comment: '回执扩展属性(notify.reply 的 extend_props),重推时原样带回', + after: 'ext_data', + }); + }, + + down: async () => { + // 不回退(新列无副作用) + }, +}; diff --git a/database/migrations/20260918000000-seed-help-instruction.js b/database/migrations/20260918000000-seed-help-instruction.js new file mode 100644 index 0000000..79a64af --- /dev/null +++ b/database/migrations/20260918000000-seed-help-instruction.js @@ -0,0 +1,123 @@ +'use strict'; + +/** + * 播种 v2 系统级「帮助 → 指令」链路(幂等,先查后插)。 + * + * - wms_after_sale_type:系统级 type=help(帮助) + * - wms_after_sale_sub_type:系统级 type=help / sub_type=instruction(指令) + * - wms_after_sale_keyword:系统级关键词「指令」「帮助」→ instruction + * - wms_after_sale_function:插入 code=help 函数行(后续启动 sync 会刷新 name/description/is_enabled) + * - wms_after_sale_sub_type_function:instruction ↔ help 函数关联 + * - wms_after_sale_sub_type_group:help 子类型白名单(store.after_sales / warehouse.customer_service / express.after_sales) + * - wms_after_sale_reply:系统级回复模板「支持以下命令:\n{back_text}」(仓库可自定义覆盖) + * + * help 子类型无需取号规则(不关联),help 函数由代码注册表硬编码启用。 + */ + +const TYPE_TABLE = 'wms_after_sale_type'; +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const KEYWORD_TABLE = 'wms_after_sale_keyword'; +const FUNCTION_TABLE = 'wms_after_sale_function'; +const REL_FN_TABLE = 'wms_after_sale_sub_type_function'; +const REL_GROUP_TABLE = 'wms_after_sale_sub_type_group'; +const REPLY_TABLE = 'wms_after_sale_reply'; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(SUB_TYPE_TABLE)) return; + + const q1 = async (sql, replacements) => { + const [ rows ] = await sequelize.query(sql, { replacements }); + return rows && rows.length > 0 ? rows[0] : null; + }; + + // ─── 1. 系统级类型 help ───────────────────────────────────── + if (exists(TYPE_TABLE) && !(await q1('SELECT id FROM `' + TYPE_TABLE + '` WHERE type = :t AND warehouse_id IS NULL LIMIT 1', { t: 'help' }))) { + await sequelize.query( + 'INSERT INTO `' + TYPE_TABLE + '` (warehouse_id, type, name, is_system, is_enabled, sort_order, created_at, updated_at) VALUES (NULL, :t, :n, 1, 1, 100, NOW(), NOW())', + { replacements: { t: 'help', n: '帮助' } } + ); + } + + // ─── 2. 系统级子类型 instruction ──────────────────────────── + let subId = await q1('SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', { t: 'help', s: 'instruction' }); + if (!subId) { + await sequelize.query( + 'INSERT INTO `' + SUB_TYPE_TABLE + '` (warehouse_id, type, sub_type, name, is_system, is_enabled, sort_order, created_at, updated_at) VALUES (NULL, :t, :s, :n, 1, 1, 0, NOW(), NOW())', + { replacements: { t: 'help', s: 'instruction', n: '指令' } } + ); + subId = await q1('SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', { t: 'help', s: 'instruction' }); + } + const instructionId = subId.id; + + // ─── 3. 系统级关键词「指令」「帮助」 ───────────────────────── + if (exists(KEYWORD_TABLE)) { + let order = 0; + for (const kw of [ '指令', '帮助' ]) { + const dup = await q1('SELECT id FROM `' + KEYWORD_TABLE + '` WHERE keyword = :k AND warehouse_id IS NULL LIMIT 1', { k: kw }); + if (!dup) { + await sequelize.query( + 'INSERT INTO `' + KEYWORD_TABLE + '` (warehouse_id, sub_type_id, keyword, is_system, is_enabled, sort_order, created_at, updated_at) VALUES (NULL, :sid, :k, 1, 1, :so, NOW(), NOW())', + { replacements: { sid: instructionId, k: kw, so: order } } + ); + } + order += 1; + } + } + + // ─── 4. help 函数行(sync 启动后刷新 name/description/is_enabled) ─── + let helpFn = null; + if (exists(FUNCTION_TABLE)) { + helpFn = await q1('SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :c LIMIT 1', { c: 'help' }); + if (!helpFn) { + await sequelize.query( + 'INSERT INTO `' + FUNCTION_TABLE + '` (function_code, name, description, is_enabled, sort_order, created_at, updated_at) VALUES (:c, :n, :d, 1, 0, NOW(), NOW())', + { replacements: { c: 'help', n: '帮助', d: '帮助指令:枚举当前仓库可见的售后类型与子类型(含关键词),返回可用指令清单(back_text)' } } + ); + helpFn = await q1('SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :c LIMIT 1', { c: 'help' }); + } + } + + // ─── 5. instruction ↔ help 函数关联 ───────────────────────── + if (exists(REL_FN_TABLE) && helpFn) { + const dup = await q1('SELECT id FROM `' + REL_FN_TABLE + '` WHERE sub_type_id = :s AND function_id = :f LIMIT 1', { s: instructionId, f: helpFn.id }); + if (!dup) { + await sequelize.query( + 'INSERT INTO `' + REL_FN_TABLE + '` (sub_type_id, function_id, sort_order, created_at, updated_at) VALUES (:s, :f, 1, NOW(), NOW())', + { replacements: { s: instructionId, f: helpFn.id } } + ); + } + } + + // ─── 6. help 子类型群白名单(三类群均可触发) ──────────────── + if (exists(REL_GROUP_TABLE)) { + for (const [ gt, sg ] of [[ 'store', 'after_sales' ], [ 'warehouse', 'customer_service' ], [ 'express', 'after_sales' ]]) { + const dup = await q1('SELECT id FROM `' + REL_GROUP_TABLE + '` WHERE sub_type_id = :s AND group_type = :g AND sub_group = :sg LIMIT 1', { s: instructionId, g: gt, sg }); + if (!dup) { + await sequelize.query( + 'INSERT INTO `' + REL_GROUP_TABLE + '` (sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) VALUES (:s, :g, :sg, 1, 0, NOW(), NOW())', + { replacements: { s: instructionId, g: gt, sg } } + ); + } + } + } + + // ─── 7. 系统级回复模板(仓库可自定义覆盖) ─────────────────── + if (exists(REPLY_TABLE)) { + const dup = await q1('SELECT id FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :s AND warehouse_id IS NULL LIMIT 1', { s: instructionId }); + if (!dup) { + await sequelize.query( + 'INSERT INTO `' + REPLY_TABLE + '` (warehouse_id, sub_type_id, reply, is_reply, no_number_hint, is_enabled, created_at, updated_at) VALUES (NULL, :s, :r, 1, NULL, 1, NOW(), NOW())', + { replacements: { s: instructionId, r: '支持以下命令:\n{back_text}' } } + ); + } + } + }, + + down: async () => { + // 不回退(系统预设种子) + }, +}; diff --git a/database/migrations/20260918100000-add-create-work-order-to-reply.js b/database/migrations/20260918100000-add-create-work-order-to-reply.js new file mode 100644 index 0000000..eb37fcf --- /dev/null +++ b/database/migrations/20260918100000-add-create-work-order-to-reply.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * wms_after_sale_reply 增加 create_work_order 列(幂等)。 + * + * 语义:是否登记工单。1=函数正常创建售后工单(默认); + * 0=函数照常执行(符合入参即执行),但函数内部跳过工单登记 + * (引擎注入 ctx.inboxContext.skip_work_order 标记,建单函数在建单前检查)。 + */ + +const TABLE = 'wms_after_sale_reply'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE); + if (!exists) return; + + const columns = await queryInterface.describeTable(TABLE); + if (columns.create_work_order) return; + + await queryInterface.addColumn(TABLE, 'create_work_order', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否登记工单:1=函数正常创建工单(默认),0=函数照常执行但内部跳过工单登记', + after: 'is_reply', + }); + }, + + down: async () => { + // 不回退(新列无副作用) + }, +}; diff --git a/database/migrations/20260918110000-seed-system-reply-all.js b/database/migrations/20260918110000-seed-system-reply-all.js new file mode 100644 index 0000000..600fb62 --- /dev/null +++ b/database/migrations/20260918110000-seed-system-reply-all.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * 补齐全部系统级子类型的系统级回复配置(幂等,先查后插)。 + * + * - 对每个系统级子类型(warehouse_id IS NULL)补一条系统级回复: + * reply='{back_text}'(默认走函数返回内容兜底,help 类占位渲染), + * is_reply=1(是否回复统一由回复配置控制)、create_work_order=1、is_enabled=1; + * - 已存在回复配置的子类型跳过; + * - 仓库自定义子类型不播种(由仓库自行创建仓库级回复)。 + */ + +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const REPLY_TABLE = 'wms_after_sale_reply'; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(SUB_TYPE_TABLE) || !exists(REPLY_TABLE)) return; + + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE warehouse_id IS NULL' + ); + const [ replyRows ] = await sequelize.query( + 'SELECT sub_type_id FROM `' + REPLY_TABLE + '` WHERE warehouse_id IS NULL' + ); + const hasReply = new Set(replyRows.map(r => Number(r.sub_type_id))); + + let inserted = 0; + for (const row of subRows) { + const sid = Number(row.id); + if (hasReply.has(sid)) continue; + await sequelize.query( + 'INSERT INTO `' + REPLY_TABLE + '` (warehouse_id, sub_type_id, reply, is_reply, create_work_order, no_number_hint, is_enabled, created_at, updated_at) VALUES (NULL, :sid, :reply, 1, 1, NULL, 1, NOW(), NOW())', + { replacements: { sid, reply: '{back_text}' } } + ); + inserted += 1; + } + console.log(`[seed-system-reply-all] inserted=${inserted}`); + }, + + down: async () => { + // 不回退(系统预设种子) + }, +}; diff --git a/database/migrations/20260918120000-seed-system-no-number-hint.js b/database/migrations/20260918120000-seed-system-no-number-hint.js new file mode 100644 index 0000000..76284cd --- /dev/null +++ b/database/migrations/20260918120000-seed-system-no-number-hint.js @@ -0,0 +1,59 @@ +'use strict'; + +/** + * 补齐系统级回复配置的「取号失败引导语」基础配置(幂等,只填空值行)。 + * + * 现状:系统级回复行 no_number_hint 全部为 NULL,取号失败时依赖代码内置默认值。 + * 本次把基础引导语写入系统级配置: + * - 子类型关联了 target='express_name' 取号规则(如 change_carrier 改快递)→ 快递指定提示; + * - 其余子类型 → 默认运单号提示。 + * 仓库级行不处理(留空时仍走代码兜底)。 + */ + +const REPLY_TABLE = 'wms_after_sale_reply'; +const REL_TABLE = 'wms_after_sale_sub_type_rule'; +const RULE_TABLE = 'wms_inbox_number_rule'; + +const HINT_EXPRESS = '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)'; +const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)'; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(REPLY_TABLE)) return; + + // 关联 express_name 取号规则的子类型集合 + let expressIds = new Set(); + if (exists(REL_TABLE) && exists(RULE_TABLE)) { + const [ relRows ] = await sequelize.query( + 'SELECT DISTINCT rel.sub_type_id FROM `' + REL_TABLE + '` rel ' + + 'JOIN `' + RULE_TABLE + '` r ON r.id = rel.number_rule_id WHERE r.target = :t', + { replacements: { t: 'express_name' } } + ); + expressIds = new Set(relRows.map(r => Number(r.sub_type_id))); + } + + const [ rows ] = await sequelize.query( + 'SELECT id, sub_type_id FROM `' + REPLY_TABLE + '` ' + + 'WHERE warehouse_id IS NULL AND (no_number_hint IS NULL OR no_number_hint = :empty)', + { replacements: { empty: '' } } + ); + + let updated = 0; + for (const row of rows) { + const hint = expressIds.has(Number(row.sub_type_id)) ? HINT_EXPRESS : HINT_DEFAULT; + await sequelize.query( + 'UPDATE `' + REPLY_TABLE + '` SET no_number_hint = :hint WHERE id = :id', + { replacements: { hint, id: row.id } } + ); + updated += 1; + } + console.log(`[seed-system-no-number-hint] updated=${updated}`); + }, + + down: async () => { + // 不回退(系统预设种子) + }, +}; diff --git a/database/migrations/20260918150000-fix-no-number-hint-scope.js b/database/migrations/20260918150000-fix-no-number-hint-scope.js new file mode 100644 index 0000000..5728a44 --- /dev/null +++ b/database/migrations/20260918150000-fix-no-number-hint-scope.js @@ -0,0 +1,63 @@ +'use strict'; + +/** + * 修正系统级「取号失败引导语」范围(幂等,按子类型取号规则重算): + * - 子类型关联了 target='express_name' 取号规则(如 change_carrier)→ 快递指定提示; + * - 子类型关联了其他取号规则 → 默认运单号提示; + * - 子类型无任何取号规则(如 help 指令、无取号环节的类型)→ 清空(取号失败分支不会触发,展示空)。 + */ + +const REPLY_TABLE = 'wms_after_sale_reply'; +const REL_TABLE = 'wms_after_sale_sub_type_rule'; +const RULE_TABLE = 'wms_inbox_number_rule'; + +const HINT_EXPRESS = '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)'; +const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)'; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(REPLY_TABLE)) return; + + let expressIds = new Set(); + let ruleIds = new Set(); + if (exists(REL_TABLE) && exists(RULE_TABLE)) { + const [ exRows ] = await sequelize.query( + 'SELECT DISTINCT rel.sub_type_id FROM `' + REL_TABLE + '` rel ' + + 'JOIN `' + RULE_TABLE + '` r ON r.id = rel.number_rule_id WHERE r.target = :t', + { replacements: { t: 'express_name' } } + ); + expressIds = new Set(exRows.map(r => Number(r.sub_type_id))); + const [ anyRows ] = await sequelize.query( + 'SELECT DISTINCT sub_type_id FROM `' + REL_TABLE + '`' + ); + ruleIds = new Set(anyRows.map(r => Number(r.sub_type_id))); + } + + const [ rows ] = await sequelize.query( + 'SELECT id, sub_type_id FROM `' + REPLY_TABLE + '` WHERE warehouse_id IS NULL' + ); + + let updated = 0; + let cleared = 0; + for (const row of rows) { + const sid = Number(row.sub_type_id); + let hint = null; + if (expressIds.has(sid)) hint = HINT_EXPRESS; + else if (ruleIds.has(sid)) hint = HINT_DEFAULT; + if (hint === null) cleared += 1; + await sequelize.query( + 'UPDATE `' + REPLY_TABLE + '` SET no_number_hint = :hint WHERE id = :id', + { replacements: { hint, id: row.id } } + ); + updated += 1; + } + console.log(`[fix-no-number-hint-scope] updated=${updated} cleared=${cleared}`); + }, + + down: async () => { + // 不回退(数据修正) + }, +}; diff --git a/database/migrations/20260918160000-help-whitelist-all-groups.js b/database/migrations/20260918160000-help-whitelist-all-groups.js new file mode 100644 index 0000000..7668864 --- /dev/null +++ b/database/migrations/20260918160000-help-whitelist-all-groups.js @@ -0,0 +1,56 @@ +'use strict'; + +/** + * help(指令)子类型群白名单改为通配:所有群都支持(幂等)。 + * + * 原播种为 store.after_sales / warehouse.customer_service / express.after_sales 三条精确白名单, + * 其他群子类型(如 store.receiving)无法触发指令。改为 group_type='*' 通配行, + * 引擎 _groupAllowed 对 '*' 直接放行;help 函数 groups=[COMMON] 本身所有群可用。 + */ + +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const REL_GROUP_TABLE = 'wms_after_sale_sub_type_group'; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(SUB_TYPE_TABLE) || !exists(REL_GROUP_TABLE)) return; + + const q1 = async (sql, replacements) => { + const [ rows ] = await sequelize.query(sql, { replacements }); + return rows && rows.length > 0 ? rows[0] : null; + }; + + const sub = await q1( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', + { t: 'help', s: 'instruction' } + ); + if (!sub) return; + const sid = sub.id; + + const wildcard = await q1( + 'SELECT id FROM `' + REL_GROUP_TABLE + '` WHERE sub_type_id = :s AND group_type = :g LIMIT 1', + { s: sid, g: '*' } + ); + if (wildcard) { + console.log('[help-whitelist-all-groups] 已存在通配白名单,跳过'); + return; + } + + const [ del ] = await sequelize.query( + 'DELETE FROM `' + REL_GROUP_TABLE + '` WHERE sub_type_id = :s', + { replacements: { s: sid } } + ); + await sequelize.query( + 'INSERT INTO `' + REL_GROUP_TABLE + '` (sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) VALUES (:s, :g, :sg, 1, 0, NOW(), NOW())', + { replacements: { s: sid, g: '*', sg: '' } } + ); + console.log(`[help-whitelist-all-groups] deleted=${del.affectedRows || 0} inserted-wildcard=1`); + }, + + down: async () => { + // 不回退(语义修正) + }, +}; diff --git a/database/migrations/20260919100000-add-workbench-create-time-index-to-wms-pack-task.js b/database/migrations/20260919100000-add-workbench-create-time-index-to-wms-pack-task.js new file mode 100644 index 0000000..84c167c --- /dev/null +++ b/database/migrations/20260919100000-add-workbench-create-time-index-to-wms-pack-task.js @@ -0,0 +1,19 @@ +'use strict'; + +/** + * workbench.getWorkbenchCount 慢查询优化配套索引。 + * 班次统计按 (workbench_id, create_time) 过滤窗口内打包任务,原 idx_workbench_id 单列索引 + * 命中后仍需过滤该工作台全部历史行,新增 (workbench_id, create_time) 复合索引 + * 使窗口过滤走索引范围扫描,避免长跨度扫描导致慢 SQL。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.addIndex('wms_pack_task', [ 'workbench_id', 'create_time' ], { + name: 'idx_workbench_create_time', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('wms_pack_task', 'idx_workbench_create_time'); + }, +}; diff --git a/database/migrations/20260920100000-add-confirm-print-status-to-order-delivery.js b/database/migrations/20260920100000-add-confirm-print-status-to-order-delivery.js new file mode 100644 index 0000000..2ec03c3 --- /dev/null +++ b/database/migrations/20260920100000-add-confirm-print-status-to-order-delivery.js @@ -0,0 +1,107 @@ +'use strict'; + +/** + * 订单表增加 confirm_print_status(确认打印状态)字段。 + * + * 背景:订单表已有 print_status(打印状态机,由打印回执/波次标记更新), + * 现增加确认打印状态:打印完成后,操作员真实扫描面单(运单号)进行确认, + * 确认后写入 confirm_print_status='fin',用于记录「面单已实际打印并核对」。 + * + * 取值约定: + * - none = 未确认打印(默认); + * - fin = 已确认打印(扫描面单确认)。 + * + * 覆盖范围: + * - 全部仓库分表 wms_order_delivery_{wh}(current)及 + * _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。 + * + * 说明:基表 wms_order_delivery 业务不使用(订单均写入分表),本迁移 + * 不对基表加列。基表上仍存在的兜底查询均带 attributes 白名单,不会 + * 因模型新增字段触发 Unknown column。 + * + * 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js + * 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。 + */ + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +const COLUMN_NAME = 'confirm_print_status'; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为基表与全部分表增加 confirm_print_status 列。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tables = await listOrderShards(queryInterface); + const results = []; + + for (const tableName of tables) { + if (await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.addColumn(tableName, COLUMN_NAME, { + type: Sequelize.ENUM('none', 'fin'), + allowNull: true, + defaultValue: 'none', + comment: '确认打印状态机(打印完成后真实扫描面单确认)', + }); + results.push({ tableName, action: 'added' }); + } + + console.log('[20260920100000-add-confirm-print-status-to-order-delivery] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除基表与全部分表的 confirm_print_status 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = await listOrderShards(queryInterface); + const results = []; + + for (const tableName of tables) { + if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'missing' }); + continue; + } + + await queryInterface.removeColumn(tableName, COLUMN_NAME); + results.push({ tableName, action: 'removed' }); + } + + console.log('[20260920100000-add-confirm-print-status-to-order-delivery] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20260921110000-add-waybill-rule-to-intercept-pickup.js b/database/migrations/20260921110000-add-waybill-rule-to-intercept-pickup.js new file mode 100644 index 0000000..a54cfad --- /dev/null +++ b/database/migrations/20260921110000-add-waybill-rule-to-intercept-pickup.js @@ -0,0 +1,111 @@ +'use strict'; + +/** + * 修复拦截/揽收子类型缺少「运单号提取」取号规则关联的问题。 + * + * 背景: + * - 20260917130000 为 intercept(拦截)/ pickup(揽收)补充了关键词,使其能被 v2 引擎命中; + * - 但未关联取号规则。v2 规则引擎 _extractNumbers 在该子类型无规则时返回 [](非 null), + * 不会进入「取号失败」分支,而是直接执行 interceptWaybill / requestPickup, + * 函数因缺运单号返回硬编码错误「请提供运单号」,绕过了回复表配置的取号失败引导语; + * - 20260918150000 又因这两个子类型无取号规则而清空了其系统级 no_number_hint。 + * + * 本次修复(幂等): + * 1. 为系统级 intercept / pickup 子类型关联「运单号提取」取号规则(依赖唯一索引 + * uk_sub_type_rule 做 INSERT IGNORE); + * 2. 将系统级回复行空的 no_number_hint 补为默认运单号引导语(只填空值行)。 + * + * 修复后链路:消息「拦截」→ 命中关键词 → 关联规则存在但未提取到运单号 → extracted=null + * → 返回取号失败引导语(回复表 no_number_hint → 代码默认值兜底)。 + */ + +const REL_TABLE = 'wms_after_sale_sub_type_rule'; +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const RULE_TABLE = 'wms_inbox_number_rule'; +const REPLY_TABLE = 'wms_after_sale_reply'; + +const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)'; +const RULE_NAME = '运单号提取'; +const SUB_TYPES = [ 'intercept', 'pickup' ]; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(REL_TABLE) || !exists(SUB_TYPE_TABLE) || !exists(RULE_TABLE)) return; + + const [ ruleRows ] = await sequelize.query( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1', + { replacements: { name: RULE_NAME } } + ); + if (ruleRows.length === 0) { + console.warn(`[MIGRATION] 跳过:未找到取号规则 ${RULE_NAME}`); + return; + } + const ruleId = ruleRows[0].id; + + let inserted = 0; + for (const subType of SUB_TYPES) { + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1', + { replacements: { type: 'order', subType } } + ); + if (subRows.length === 0) { + console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${subType}`); + continue; + } + await sequelize.query( + 'INSERT IGNORE INTO `' + REL_TABLE + '` ' + + '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :rid, 1, NOW(), NOW())', + { replacements: { sid: subRows[0].id, rid: ruleId } } + ); + inserted += 1; + } + console.log(`[MIGRATION] 取号规则关联插入 ${inserted} 条`); + + // 补充系统级回复行的取号失败引导语(只填空值行) + if (exists(REPLY_TABLE)) { + const [ replyRows ] = await sequelize.query( + 'SELECT r.id FROM `' + REPLY_TABLE + '` r ' + + 'JOIN `' + SUB_TYPE_TABLE + '` st ON st.id = r.sub_type_id ' + + 'WHERE r.warehouse_id IS NULL AND st.type = :type AND st.sub_type IN (:subTypes) ' + + 'AND (r.no_number_hint IS NULL OR r.no_number_hint = :empty)', + { replacements: { type: 'order', subTypes: SUB_TYPES, empty: '' } } + ); + for (const row of replyRows) { + await sequelize.query( + 'UPDATE `' + REPLY_TABLE + '` SET no_number_hint = :hint WHERE id = :id', + { replacements: { hint: HINT_DEFAULT, id: row.id } } + ); + } + console.log(`[MIGRATION] 补充取号失败引导语 ${replyRows.length} 行`); + } + }, + + down: async queryInterface => { + const { sequelize } = queryInterface; + + const [ ruleRows ] = await sequelize.query( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1', + { replacements: { name: RULE_NAME } } + ); + if (ruleRows.length === 0) return; + + for (const subType of SUB_TYPES) { + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1', + { replacements: { type: 'order', subType } } + ); + if (subRows.length === 0) continue; + await sequelize.query( + 'DELETE FROM `' + REL_TABLE + '` WHERE sub_type_id = :sid AND number_rule_id = :rid', + { replacements: { sid: subRows[0].id, rid: ruleRows[0].id } } + ); + } + // 引导语不回退(数据修正,与既有种子迁移 down 语义一致) + }, +}; diff --git a/database/migrations/20260921120000-add-keywords-and-waybill-rule-mis-shipment-extra-item.js b/database/migrations/20260921120000-add-keywords-and-waybill-rule-mis-shipment-extra-item.js new file mode 100644 index 0000000..71006ac --- /dev/null +++ b/database/migrations/20260921120000-add-keywords-and-waybill-rule-mis-shipment-extra-item.js @@ -0,0 +1,147 @@ +'use strict'; + +/** + * 错发(mis_shipment)/ 多发(extra_item)子类型配置补齐:关键词 + 运单号取号规则 + 引导语。 + * + * 背景: + * - v1 引擎(inbox/rules.js STORE_RULES)中错发/多发分别有关键词且 waybill:true: + * 错发:错发、发错(fn=handleStoreFeedback, issueType=wrong) + * 多发:多发、发多(fn=handleStoreFeedback, issueType=multiple) + * - v2 关键词表 wms_after_sale_keyword 中这两个子类型无任何关键词,无法命中; + * 且无「运单号提取」取号规则关联 → v2 引擎 _extractNumbers 返回 [], + * 直接执行 handleStoreFeedback,缺单号时返回函数硬编码错误「请提供运单号」, + * 取号失败引导语分支不可达(与拦截/揽收同款问题)。 + * + * 本次修复(幂等): + * 1. 将 v1 既有关键词作为系统级默认关键词写入(先查后插,NULL 仓库不参与唯一约束); + * 2. 为系统级错发/多发子类型关联「运单号提取」取号规则(INSERT IGNORE 依赖唯一索引 uk_sub_type_rule); + * 3. 将系统级回复行空的 no_number_hint 补为默认运单号引导语(只填空值行,仓库级行不动)。 + */ + +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const KEYWORD_TABLE = 'wms_after_sale_keyword'; +const REL_TABLE = 'wms_after_sale_sub_type_rule'; +const RULE_TABLE = 'wms_inbox_number_rule'; +const REPLY_TABLE = 'wms_after_sale_reply'; + +const RULE_NAME = '运单号提取'; +const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)'; + +/** 子类型编码 → 默认关键词(与 v1 STORE_RULES 一致) */ +const SUB_TYPE_KEYWORDS = [ + { sub_type: 'mis_shipment', keywords: [ '错发', '发错' ] }, + { sub_type: 'extra_item', keywords: [ '多发', '发多' ] }, +]; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(SUB_TYPE_TABLE) || !exists(KEYWORD_TABLE)) return; + + // ─── 1. 默认关键词(先查后插,NULL 仓库不参与唯一约束) ───────── + let inserted = 0; + for (const rule of SUB_TYPE_KEYWORDS) { + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1', + { replacements: { type: 'order', subType: rule.sub_type } } + ); + if (subRows.length === 0) { + console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${rule.sub_type}`); + continue; + } + const subTypeId = subRows[0].id; + let sortOrder = 0; + for (const kw of rule.keywords) { + const [ kwRows ] = await sequelize.query( + 'SELECT id FROM `' + KEYWORD_TABLE + '` WHERE keyword = :kw AND warehouse_id IS NULL LIMIT 1', + { replacements: { kw } } + ); + if (kwRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + KEYWORD_TABLE + '` ' + + '(warehouse_id, sub_type_id, keyword, is_system, is_enabled, sort_order, created_at, updated_at) ' + + 'VALUES (NULL, :sid, :kw, 1, 1, :so, NOW(), NOW())', + { replacements: { sid: subTypeId, kw, so: sortOrder } } + ); + inserted += 1; + } + sortOrder += 1; + } + } + console.log(`[MIGRATION] 默认关键词插入 ${inserted} 条`); + + // ─── 2. 运单号取号规则关联(INSERT IGNORE,依赖 uk_sub_type_rule) ── + if (exists(REL_TABLE) && exists(RULE_TABLE)) { + const [ ruleRows ] = await sequelize.query( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1', + { replacements: { name: RULE_NAME } } + ); + if (ruleRows.length > 0) { + const ruleId = ruleRows[0].id; + let relInserted = 0; + for (const rule of SUB_TYPE_KEYWORDS) { + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1', + { replacements: { type: 'order', subType: rule.sub_type } } + ); + if (subRows.length === 0) continue; + await sequelize.query( + 'INSERT IGNORE INTO `' + REL_TABLE + '` ' + + '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :rid, 1, NOW(), NOW())', + { replacements: { sid: subRows[0].id, rid: ruleId } } + ); + relInserted += 1; + } + console.log(`[MIGRATION] 取号规则关联插入 ${relInserted} 条`); + } else { + console.warn(`[MIGRATION] 跳过:未找到取号规则 ${RULE_NAME}`); + } + } + + // ─── 3. 系统级空引导语回填(只填空值行) ───────────────────── + if (exists(REPLY_TABLE)) { + const [ replyRows ] = await sequelize.query( + 'SELECT r.id FROM `' + REPLY_TABLE + '` r ' + + 'JOIN `' + SUB_TYPE_TABLE + '` st ON st.id = r.sub_type_id ' + + 'WHERE r.warehouse_id IS NULL AND st.type = :type AND st.sub_type IN (:subTypes) ' + + 'AND (r.no_number_hint IS NULL OR r.no_number_hint = :empty)', + { replacements: { type: 'order', subTypes: SUB_TYPE_KEYWORDS.map(x => x.sub_type), empty: '' } } + ); + for (const row of replyRows) { + await sequelize.query( + 'UPDATE `' + REPLY_TABLE + '` SET no_number_hint = :hint WHERE id = :id', + { replacements: { hint: HINT_DEFAULT, id: row.id } } + ); + } + console.log(`[MIGRATION] 补充取号失败引导语 ${replyRows.length} 行`); + } + }, + + down: async queryInterface => { + const { sequelize } = queryInterface; + + // 回滚取号规则关联;关键词与引导语不回退(种子类数据,与既有迁移 down 语义一致) + const [ ruleRows ] = await sequelize.query( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1', + { replacements: { name: RULE_NAME } } + ); + if (ruleRows.length === 0) return; + for (const rule of SUB_TYPE_KEYWORDS) { + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1', + { replacements: { type: 'order', subType: rule.sub_type } } + ); + if (subRows.length === 0) continue; + await sequelize.query( + 'DELETE FROM `' + REL_TABLE + '` WHERE sub_type_id = :sid AND number_rule_id = :rid', + { replacements: { sid: subRows[0].id, rid: ruleRows[0].id } } + ); + } + }, +}; diff --git a/database/migrations/20260921130000-add-cancel-intercept-sub-type.js b/database/migrations/20260921130000-add-cancel-intercept-sub-type.js new file mode 100644 index 0000000..18a14d6 --- /dev/null +++ b/database/migrations/20260921130000-add-cancel-intercept-sub-type.js @@ -0,0 +1,203 @@ +'use strict'; + +/** + * 订单类型新增系统级子类型「取消拦截」(cancel_intercept),并补齐 v2 配置链。 + * + * 背景: + * - v1 引擎(inbox/rules.js STORE_RULES)与代码函数表均有 cancelIntercept + * (关键词:取消拦截/撤销拦截/解除拦截/不拦截/不用拦截,waybill:true); + * - v2 的售后子类型表 wms_after_sale_sub_type 中没有该子类型,导致 v2 引擎 + * 无法把「取消拦截」类消息路由到 cancelIntercept 函数(帮助清单缺项)。 + * + * 本次修复(幂等,先查后插;INSERT IGNORE 依赖既有唯一索引): + * 1. 插入系统级子类型 cancel_intercept(sort_order=10,紧跟拦截之后), + * 并将原 sort_order>=10 的系统级 order 子类型顺延 +1; + * 2. 关键词 5 条:取消拦截/撤销拦截/解除拦截/不拦截/不用拦截; + * 3. 群类型白名单:store:after_sales + warehouse:customer_service(与函数 groups 一致); + * 4. 子类型-函数关系:cancelIntercept; + * 5. 取号规则关联:运单号提取(waybill); + * 6. 系统级回复行:reply={back_text}、is_reply=1、create_work_order=1、 + * no_number_hint=默认运单号引导语、is_enabled=1。 + */ + +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const KEYWORD_TABLE = 'wms_after_sale_keyword'; +const GROUP_REL_TABLE = 'wms_after_sale_sub_type_group'; +const FUNCTION_TABLE = 'wms_after_sale_function'; +const FUNC_REL_TABLE = 'wms_after_sale_sub_type_function'; +const RULE_TABLE = 'wms_inbox_number_rule'; +const RULE_REL_TABLE = 'wms_after_sale_sub_type_rule'; +const REPLY_TABLE = 'wms_after_sale_reply'; + +const SUB_TYPE_CODE = 'cancel_intercept'; +const SUB_TYPE_NAME = '取消拦截'; +const SUB_TYPE_SORT = 10; // 紧跟拦截(9)之后 +const KEYWORDS = [ '取消拦截', '撤销拦截', '解除拦截', '不拦截', '不用拦截' ]; +const GROUP_WHITELIST = [ + { group_type: 'store', sub_group: 'after_sales' }, + { group_type: 'warehouse', sub_group: 'customer_service' }, +]; +const FUNCTION_CODE = 'cancelIntercept'; +const RULE_NAME = '运单号提取'; +const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)'; + +module.exports = { + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(SUB_TYPE_TABLE)) return; + + // ─── 1. 子类型(先查;不存在则顺延 sort_order 并插入) ───────── + let [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL LIMIT 1', + { replacements: { type: 'order', subType: SUB_TYPE_CODE } } + ); + if (subRows.length === 0) { + await sequelize.query( + 'UPDATE `' + SUB_TYPE_TABLE + '` SET sort_order = sort_order + 1 ' + + 'WHERE type = :type AND warehouse_id IS NULL AND sort_order >= :sort', + { replacements: { type: 'order', sort: SUB_TYPE_SORT } } + ); + await sequelize.query( + 'INSERT INTO `' + SUB_TYPE_TABLE + '` ' + + '(warehouse_id, type, sub_type, name, is_system, is_enabled, sort_order, created_at, updated_at) ' + + 'VALUES (NULL, :type, :subType, :name, 1, 1, :sort, NOW(), NOW())', + { replacements: { type: 'order', subType: SUB_TYPE_CODE, name: SUB_TYPE_NAME, sort: SUB_TYPE_SORT } } + ); + [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL LIMIT 1', + { replacements: { type: 'order', subType: SUB_TYPE_CODE } } + ); + console.log(`[MIGRATION] 子类型插入 order.${SUB_TYPE_CODE},原 sort_order>=${SUB_TYPE_SORT} 已顺延`); + } + if (subRows.length === 0) { + console.warn(`[MIGRATION] 跳过:子类型 order.${SUB_TYPE_CODE} 缺失且插入失败`); + return; + } + const subTypeId = subRows[0].id; + + // ─── 2. 关键词(先查后插,NULL 仓库不参与唯一约束) ───────── + if (exists(KEYWORD_TABLE)) { + let kwInserted = 0; + for (const [ idx, kw ] of KEYWORDS.entries()) { + const [ kwRows ] = await sequelize.query( + 'SELECT id FROM `' + KEYWORD_TABLE + '` WHERE keyword = :kw AND warehouse_id IS NULL LIMIT 1', + { replacements: { kw } } + ); + if (kwRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + KEYWORD_TABLE + '` ' + + '(warehouse_id, sub_type_id, keyword, is_system, is_enabled, sort_order, created_at, updated_at) ' + + 'VALUES (NULL, :sid, :kw, 1, 1, :so, NOW(), NOW())', + { replacements: { sid: subTypeId, kw, so: idx } } + ); + kwInserted += 1; + } + } + console.log(`[MIGRATION] 关键词插入 ${kwInserted} 条`); + } + + // ─── 3. 群类型白名单(INSERT IGNORE,依赖 uk_sub_type_group) ── + if (exists(GROUP_REL_TABLE)) { + let grpInserted = 0; + for (const [ idx, g ] of GROUP_WHITELIST.entries()) { + await sequelize.query( + 'INSERT IGNORE INTO `' + GROUP_REL_TABLE + '` ' + + '(sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :groupType, :subGroup, 1, :so, NOW(), NOW())', + { replacements: { sid: subTypeId, groupType: g.group_type, subGroup: g.sub_group, so: idx + 1 } } + ); + grpInserted += 1; + } + console.log(`[MIGRATION] 群白名单插入 ${grpInserted} 条`); + } + + // ─── 4. 子类型-函数关系(INSERT IGNORE,依赖 uk_sub_type_function) ── + if (exists(FUNC_REL_TABLE) && exists(FUNCTION_TABLE)) { + const [ fnRows ] = await sequelize.query( + 'SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :code LIMIT 1', + { replacements: { code: FUNCTION_CODE } } + ); + if (fnRows.length > 0) { + await sequelize.query( + 'INSERT IGNORE INTO `' + FUNC_REL_TABLE + '` ' + + '(sub_type_id, function_id, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :fid, 1, NOW(), NOW())', + { replacements: { sid: subTypeId, fid: fnRows[0].id } } + ); + console.log(`[MIGRATION] 函数关系插入 ${FUNCTION_CODE}`); + } else { + console.warn(`[MIGRATION] 跳过:未找到处理函数 ${FUNCTION_CODE}`); + } + } + + // ─── 5. 运单号取号规则关联(INSERT IGNORE,依赖 uk_sub_type_rule) ── + if (exists(RULE_REL_TABLE) && exists(RULE_TABLE)) { + const [ ruleRows ] = await sequelize.query( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1', + { replacements: { name: RULE_NAME } } + ); + if (ruleRows.length > 0) { + await sequelize.query( + 'INSERT IGNORE INTO `' + RULE_REL_TABLE + '` ' + + '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :rid, 1, NOW(), NOW())', + { replacements: { sid: subTypeId, rid: ruleRows[0].id } } + ); + console.log(`[MIGRATION] 取号规则关联插入 ${RULE_NAME}`); + } else { + console.warn(`[MIGRATION] 跳过:未找到取号规则 ${RULE_NAME}`); + } + } + + // ─── 6. 系统级回复行(先查后插) ───────────────────────────── + if (exists(REPLY_TABLE)) { + const [ replyRows ] = await sequelize.query( + 'SELECT id FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL LIMIT 1', + { replacements: { sid: subTypeId } } + ); + if (replyRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + REPLY_TABLE + '` ' + + '(warehouse_id, sub_type_id, reply, is_reply, create_work_order, no_number_hint, is_enabled, created_at, updated_at) ' + + 'VALUES (NULL, :sid, :reply, 1, 1, :hint, 1, NOW(), NOW())', + { replacements: { sid: subTypeId, reply: '{back_text}', hint: HINT_DEFAULT } } + ); + console.log('[MIGRATION] 系统级回复行插入 1 行'); + } + } + }, + + down: async queryInterface => { + const { sequelize } = queryInterface; + + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL LIMIT 1', + { replacements: { type: 'order', subType: SUB_TYPE_CODE } } + ); + if (subRows.length === 0) return; + const subTypeId = subRows[0].id; + + // 回滚关联与配置(关键词/回复行/白名单/函数/取号规则) + await sequelize.query('DELETE FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + KEYWORD_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + GROUP_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + FUNC_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + RULE_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } }); + + // 删除子类型并恢复 sort_order 顺延 + await sequelize.query( + 'DELETE FROM `' + SUB_TYPE_TABLE + '` WHERE id = :sid', + { replacements: { sid: subTypeId } } + ); + await sequelize.query( + 'UPDATE `' + SUB_TYPE_TABLE + '` SET sort_order = sort_order - 1 ' + + 'WHERE type = :type AND warehouse_id IS NULL AND sort_order > :sort', + { replacements: { type: 'order', sort: SUB_TYPE_SORT } } + ); + }, +}; diff --git a/database/migrations/20260921140000-create-wms-user-oauth.js b/database/migrations/20260921140000-create-wms-user-oauth.js new file mode 100644 index 0000000..494d6de --- /dev/null +++ b/database/migrations/20260921140000-create-wms-user-oauth.js @@ -0,0 +1,139 @@ +'use strict'; + +/** + * 创建用户第三方授权表 wms_user_oauth。 + * + * 用途:保存用户通过第三方厂商(如微信、小程序)OAuth 登录后的授权信息, + * 包括用户画像(昵称/头像/地区)、平台凭证(openid/unionid)与令牌信息 + * (session_key/access_token/refresh_token 及过期时间)。 + * + * 索引: + * - uk_provider_openid:厂商 + 平台ID 唯一,同一用户在同一厂商/平台下仅一条绑定。 + * - idx_user_id:按用户查询其全部授权绑定。 + */ + +const TABLE_NAME = 'wms_user_oauth'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, TINYINT, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + user_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '用户ID(关联 account.id)', + }, + provider: { + type: STRING(50), + allowNull: false, + comment: '厂商,如 wechat/mini_program', + }, + platform: { + type: STRING(50), + allowNull: true, + comment: '平台,如 h5/app/mp', + }, + unionid: { + type: STRING(50), + allowNull: true, + comment: '厂商统一ID(同一厂商跨应用唯一,部分平台无)', + }, + openid: { + type: STRING(50), + allowNull: false, + comment: '平台内唯一ID', + }, + nickname: { + type: STRING(255), + allowNull: true, + comment: '昵称', + }, + sex: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '性别:0=未知,1=男,2=女', + }, + country: { + type: STRING(50), + allowNull: true, + comment: '国家', + }, + province: { + type: STRING(50), + allowNull: true, + comment: '省', + }, + city: { + type: STRING(50), + allowNull: true, + comment: '市', + }, + headimgurl: { + type: STRING(500), + allowNull: true, + comment: '头像URL', + }, + login_time: { + type: INTEGER(11), + allowNull: true, + comment: '最近登录时间(unix秒级时间戳)', + }, + login_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '累计登录次数', + }, + expire_in: { + type: INTEGER(11), + allowNull: true, + comment: '令牌过期周期(秒)', + }, + expire_time: { + type: INTEGER(11), + allowNull: true, + comment: '令牌过期时间(unix秒级时间戳)', + }, + session_key: { + type: STRING(45), + allowNull: true, + comment: '会话密钥(微信小程序登录态)', + }, + refresh_token: { + type: STRING(110), + allowNull: true, + comment: '刷新令牌', + }, + access_token: { + type: STRING(110), + allowNull: true, + comment: '访问令牌', + }, + created_at: { type: DATE, allowNull: false, comment: '创建时间' }, + updated_at: { type: DATE, allowNull: false, comment: '更新时间' }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'provider', 'openid' ], { + unique: true, + name: 'uk_provider_openid', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'user_id' ], { + name: 'idx_user_id', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260921150000-create-wms-wechat-app.js b/database/migrations/20260921150000-create-wms-wechat-app.js new file mode 100644 index 0000000..e5e47a5 --- /dev/null +++ b/database/migrations/20260921150000-create-wms-wechat-app.js @@ -0,0 +1,108 @@ +'use strict'; + +/** + * 创建微信开放平台授权小程序表 wms_wechat_app。 + * + * 用途:仓库(主体)在微信开放平台将自己主体下的小程序授权给本系统提供服务, + * 记录小程序授权信息(appid/名称/授权令牌)与仓库的绑定关系(warehouse_id)。 + * 小程序归属仓库主体,1 个仓库可授权多个小程序。 + * + * 令牌说明: + * - authorizer_refresh_token:授权方刷新令牌,长期有效,用于刷新接口调用凭证。 + * - authorizer_access_token:授权方接口调用凭证,约 2 小时有效,过期后用 + * refresh_token 刷新并回写本表。 + * + * 索引: + * - uk_appid:appid 唯一(同一小程序只允许授权一次)。 + * - idx_warehouse_id:按仓库查询其已授权小程序列表。 + */ + +const TABLE_NAME = 'wms_wechat_app'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, TINYINT, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(小程序归属主体,绑定关系)', + }, + appid: { + type: STRING(64), + allowNull: false, + comment: '小程序AppID', + }, + nickname: { + type: STRING(100), + allowNull: true, + comment: '小程序名称', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '小程序原始ID(gh_xxx)', + }, + head_img: { + type: STRING(500), + allowNull: true, + comment: '小程序头像URL', + }, + app_secret: { + type: STRING(64), + allowNull: true, + comment: '小程序密钥(按需配置)', + }, + authorizer_refresh_token: { + type: STRING(255), + allowNull: true, + comment: '授权方刷新令牌(长期有效)', + }, + authorizer_access_token: { + type: STRING(512), + allowNull: true, + comment: '授权方接口调用凭证(约2小时有效)', + }, + access_token_expire_time: { + type: INTEGER(11), + allowNull: true, + comment: '接口调用凭证过期时间(unix秒级时间戳)', + }, + auth_time: { + type: INTEGER(11), + allowNull: true, + comment: '授权时间(unix秒级时间戳)', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:1=启用,0=停用', + }, + created_at: { type: DATE, allowNull: false, comment: '创建时间' }, + updated_at: { type: DATE, allowNull: false, comment: '更新时间' }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'appid' ], { + unique: true, + name: 'uk_appid', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { + name: 'idx_warehouse_id', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260921150100-add-app-id-to-wms-user-oauth.js b/database/migrations/20260921150100-add-app-id-to-wms-user-oauth.js new file mode 100644 index 0000000..fbfeab8 --- /dev/null +++ b/database/migrations/20260921150100-add-app-id-to-wms-user-oauth.js @@ -0,0 +1,44 @@ +'use strict'; + +/** + * wms_user_oauth 增加应用映射字段 app_id。 + * + * 背景:微信 openid 是「小程序 appid」维度唯一,同一用户在不同小程序下 + * openid 不同。为使用户授权记录能定位到对应小程序应用(wms_wechat_app), + * 以便取该应用自己的 access_token 处理,新增 app_id 关联字段。 + * + * 索引调整: + * - 删除 uk_provider_openid(provider + openid), + * 改为 uk_app_provider_openid(app_id + provider + openid)。 + * - 注意:MySQL 唯一索引对 NULL 不生效,app_id 为 NULL 的记录(非小程序 + * 厂商场景)不参与唯一约束,写入时需业务侧先查后插保证幂等。 + */ + +const TABLE_NAME = 'wms_user_oauth'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT } = Sequelize; + await queryInterface.addColumn(TABLE_NAME, 'app_id', { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '微信应用ID(关联 wms_wechat_app.id),用于取对应应用 token 处理', + }); + + await queryInterface.removeIndex(TABLE_NAME, 'uk_provider_openid'); + await queryInterface.addIndex(TABLE_NAME, [ 'app_id', 'provider', 'openid' ], { + unique: true, + name: 'uk_app_provider_openid', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.removeIndex(TABLE_NAME, 'uk_app_provider_openid'); + await queryInterface.addIndex(TABLE_NAME, [ 'provider', 'openid' ], { + unique: true, + name: 'uk_provider_openid', + }); + await queryInterface.removeColumn(TABLE_NAME, 'app_id'); + }, +}; diff --git a/database/migrations/20260921150200-alter-wms-wechat-app.js b/database/migrations/20260921150200-alter-wms-wechat-app.js new file mode 100644 index 0000000..3142f15 --- /dev/null +++ b/database/migrations/20260921150200-alter-wms-wechat-app.js @@ -0,0 +1,43 @@ +'use strict'; + +/** + * wms_wechat_app 表结构微调,适配微信开放平台授权事件推送。 + * + * 1. warehouse_id 改为可空: + * 授权事件(authorized/updateauthorized)由微信开放平台推送,推送时 + * 仓库绑定关系尚未确定(参考流程为授权后由回跳页面再绑定仓库), + * 因此授权阶段允许 warehouse_id 为 NULL(NULL=待绑定)。 + * 2. 新增 func_info(TEXT): + * 保存授权方授权给第三方平台的权限集合(api_query_auth 返回的 + * authorization_info.func_info JSON 字符串)。 + */ + +const TABLE_NAME = 'wms_wechat_app'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { TEXT } = Sequelize; + + await queryInterface.changeColumn(TABLE_NAME, 'warehouse_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '仓库ID(绑定关系,NULL=已授权待绑定仓库)', + }); + + await queryInterface.addColumn(TABLE_NAME, 'func_info', { + type: TEXT, + allowNull: true, + comment: '授权权限集合(JSON 字符串,来自 api_query_auth)', + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn(TABLE_NAME, 'func_info'); + + await queryInterface.changeColumn(TABLE_NAME, 'warehouse_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(小程序归属主体,绑定关系)', + }); + }, +}; diff --git a/database/migrations/20260921150300-trim-wms-wechat-app.js b/database/migrations/20260921150300-trim-wms-wechat-app.js new file mode 100644 index 0000000..59464f5 --- /dev/null +++ b/database/migrations/20260921150300-trim-wms-wechat-app.js @@ -0,0 +1,44 @@ +'use strict'; + +/** + * 精简 wms_wechat_app 表字段。 + * + * 背景:令牌类字段改为由 Redis 管理(与参考实现一致),DB 只保留 + * 授权状态、绑定关系与长期凭证: + * - authorizer_access_token:约 2 小时过期、高频变化,Redis 缓存 + TTL 管理, + * 落库无意义,移除。 + * - access_token_expire_time:配合 access_token 的过期时间,随 access_token + * 一起由 Redis TTL 管理,移除。 + * - app_secret:第三方平台模式下调用授权方接口使用 component_access_token / + * authorizer_access_token,无需小程序密钥,移除。 + * - authorizer_refresh_token 保留落库:长期凭证,防 Redis 清空后需重新授权。 + */ + +const TABLE_NAME = 'wms_wechat_app'; + +module.exports = { + async up(queryInterface) { + await queryInterface.removeColumn(TABLE_NAME, 'authorizer_access_token'); + await queryInterface.removeColumn(TABLE_NAME, 'access_token_expire_time'); + await queryInterface.removeColumn(TABLE_NAME, 'app_secret'); + }, + + async down(queryInterface, Sequelize) { + const { STRING, INTEGER } = Sequelize; + await queryInterface.addColumn(TABLE_NAME, 'app_secret', { + type: STRING(64), + allowNull: true, + comment: '小程序密钥(按需配置)', + }); + await queryInterface.addColumn(TABLE_NAME, 'access_token_expire_time', { + type: INTEGER(11), + allowNull: true, + comment: '接口调用凭证过期时间(unix秒级时间戳)', + }); + await queryInterface.addColumn(TABLE_NAME, 'authorizer_access_token', { + type: STRING(512), + allowNull: true, + comment: '授权方接口调用凭证(约2小时有效)', + }); + }, +}; diff --git a/database/migrations/20260922090000-add-login-code-to-wms-user-oauth.js b/database/migrations/20260922090000-add-login-code-to-wms-user-oauth.js new file mode 100644 index 0000000..f634526 --- /dev/null +++ b/database/migrations/20260922090000-add-login-code-to-wms-user-oauth.js @@ -0,0 +1,32 @@ +'use strict'; + +/** + * wms_user_oauth 增加 login_code 字段。 + * + * 用途:扫码登录码(小程序授权/扫码登录场景),生成方式与 + * wms_workbench.login_code 保持一致(前缀 + 随机,64 位,全局唯一, + * 登录码为一次性凭证,消费后作废)。 + */ + +const TABLE_NAME = 'wms_user_oauth'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { STRING } = Sequelize; + await queryInterface.addColumn(TABLE_NAME, 'login_code', { + type: STRING(64), + allowNull: true, + comment: '登录码(前缀+随机,64位,全局唯一)', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'login_code' ], { + unique: true, + name: 'uk_login_code', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex(TABLE_NAME, 'uk_login_code'); + await queryInterface.removeColumn(TABLE_NAME, 'login_code'); + }, +}; diff --git a/database/migrations/20260922100000-expand-login-code-length.js b/database/migrations/20260922100000-expand-login-code-length.js new file mode 100644 index 0000000..e626f08 --- /dev/null +++ b/database/migrations/20260922100000-expand-login-code-length.js @@ -0,0 +1,30 @@ +'use strict'; + +/** + * 扩展 wms_user_oauth.login_code 长度:64 → 128。 + * + * 原因:login_code 为 {uuid, id_6} JSON 的 base64,长度约 96 字符, + * 原 VARCHAR(64) 写入时报 Data too long。 + */ + +const TABLE_NAME = 'wms_user_oauth'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { STRING } = Sequelize; + await queryInterface.changeColumn(TABLE_NAME, 'login_code', { + type: STRING(128), + allowNull: true, + comment: '登录码({uuid,id_6} JSON 的 base64,一次性消费)', + }); + }, + + async down(queryInterface, Sequelize) { + const { STRING } = Sequelize; + await queryInterface.changeColumn(TABLE_NAME, 'login_code', { + type: STRING(64), + allowNull: true, + comment: '登录码(前缀+随机,64位,全局唯一)', + }); + }, +}; diff --git a/database/migrations/20260922160000-add-template-id-to-wms-wechat-app.js b/database/migrations/20260922160000-add-template-id-to-wms-wechat-app.js new file mode 100644 index 0000000..f8810e0 --- /dev/null +++ b/database/migrations/20260922160000-add-template-id-to-wms-wechat-app.js @@ -0,0 +1,24 @@ +'use strict'; + +/** + * wms_wechat_app 增加「当前上传的代码模板ID」字段 template_id。 + * + * 用于记录第三方平台代开发小程序最近一次 wxa/commit 上传代码使用的模板 ID。 + */ + +const TABLE_NAME = 'wms_wechat_app'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn(TABLE_NAME, 'template_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '当前上传的代码模板ID(wxa/commit 成功后记录)', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn(TABLE_NAME, 'template_id'); + }, +}; diff --git a/database/migrations/20260922170000-add-audit-fields-to-wms-wechat-app.js b/database/migrations/20260922170000-add-audit-fields-to-wms-wechat-app.js new file mode 100644 index 0000000..7f3bd79 --- /dev/null +++ b/database/migrations/20260922170000-add-audit-fields-to-wms-wechat-app.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * wms_wechat_app 增加代码审核相关字段: + * - user_version:当前上传的代码版本号(wxa/commit 成功后记录) + * - audit_status:代码审核状态 0=未提交 1=审核中 2=审核通过 3=审核驳回 + * - audit_id:微信审核单 ID(auditid) + * - audit_reason:审核驳回原因 + */ + +const TABLE_NAME = 'wms_wechat_app'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn(TABLE_NAME, 'user_version', { + type: Sequelize.STRING(64), + allowNull: true, + defaultValue: null, + comment: '当前上传的代码版本号(wxa/commit 成功后记录)', + }); + await queryInterface.addColumn(TABLE_NAME, 'audit_status', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '代码审核状态:0=未提交,1=审核中,2=审核通过,3=审核驳回', + }); + await queryInterface.addColumn(TABLE_NAME, 'audit_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '微信审核单ID(wxa/submit_audit 返回的 auditid)', + }); + await queryInterface.addColumn(TABLE_NAME, 'audit_reason', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '代码审核驳回原因', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn(TABLE_NAME, 'user_version'); + await queryInterface.removeColumn(TABLE_NAME, 'audit_status'); + await queryInterface.removeColumn(TABLE_NAME, 'audit_id'); + await queryInterface.removeColumn(TABLE_NAME, 'audit_reason'); + }, +}; diff --git a/database/migrations/20260922180000-add-authorizer-info-fields-to-wms-wechat-app.js b/database/migrations/20260922180000-add-authorizer-info-fields-to-wms-wechat-app.js new file mode 100644 index 0000000..7888c7e --- /dev/null +++ b/database/migrations/20260922180000-add-authorizer-info-fields-to-wms-wechat-app.js @@ -0,0 +1,64 @@ +'use strict'; + +/** + * wms_wechat_app 补充授权账号基础信息与认证相关字段: + * - 基础信息(api_get_authorizer_info):principal_name/signature/alias/qrcode_url/ + * service_type_id/verify_type_id/account_status/register_type/business_info/mini_program_info + * - 认证任务与状态(wxa/sec/queryauth):auth_task_id/auth_task_status/auth_apply_status + */ + +const TABLE_NAME = 'wms_wechat_app'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn(TABLE_NAME, 'principal_name', { + type: Sequelize.STRING(100), allowNull: true, defaultValue: null, comment: '主体名称', + }); + await queryInterface.addColumn(TABLE_NAME, 'signature', { + type: Sequelize.STRING(500), allowNull: true, defaultValue: null, comment: '小程序账号介绍', + }); + await queryInterface.addColumn(TABLE_NAME, 'alias', { + type: Sequelize.STRING(100), allowNull: true, defaultValue: null, comment: '微信号(可能为空)', + }); + await queryInterface.addColumn(TABLE_NAME, 'qrcode_url', { + type: Sequelize.STRING(500), allowNull: true, defaultValue: null, comment: '二维码图片URL', + }); + await queryInterface.addColumn(TABLE_NAME, 'service_type_id', { + type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '账号类型id(0 普通小程序等)', + }); + await queryInterface.addColumn(TABLE_NAME, 'verify_type_id', { + type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '认证类型id(-1 未认证,0 微信认证,1 新浪微博认证,3 资质通过未名称认证,4 同3+微博)', + }); + await queryInterface.addColumn(TABLE_NAME, 'account_status', { + type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '账号状态(1 正常,14 已注销,16 已封禁,18 已告警,19 已冻结)', + }); + await queryInterface.addColumn(TABLE_NAME, 'register_type', { + type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '小程序注册方式(0 普通,6 法人扫脸创建企业小程序等)', + }); + await queryInterface.addColumn(TABLE_NAME, 'business_info', { + type: Sequelize.STRING(500), allowNull: true, defaultValue: null, comment: '功能开通状况 JSON(open_pay/open_shake/open_scan/open_card/open_store)', + }); + await queryInterface.addColumn(TABLE_NAME, 'mini_program_info', { + type: Sequelize.TEXT, allowNull: true, defaultValue: null, comment: '小程序配置信息 JSON(network/categories/visit_status)', + }); + await queryInterface.addColumn(TABLE_NAME, 'auth_task_id', { + type: Sequelize.STRING(64), allowNull: true, defaultValue: null, comment: '微信认证任务ID(发起认证接口 wxa/sec/wxaapi/wxaauth 返回)', + }); + await queryInterface.addColumn(TABLE_NAME, 'auth_task_status', { + type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '认证任务流程状态(wxa/sec/queryauth task_status 0-15)', + }); + await queryInterface.addColumn(TABLE_NAME, 'auth_apply_status', { + type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '认证审核单状态(wxa/sec/queryauth apply_status 0-5)', + }); + }, + + async down(queryInterface) { + for (const col of [ + 'principal_name', 'signature', 'alias', 'qrcode_url', 'service_type_id', + 'verify_type_id', 'account_status', 'register_type', 'business_info', + 'mini_program_info', 'auth_task_id', 'auth_task_status', 'auth_apply_status', + ]) { + await queryInterface.removeColumn(TABLE_NAME, col); + } + }, +}; diff --git a/database/migrations/20260923100000-add-return-query-return-sub-type.js b/database/migrations/20260923100000-add-return-query-return-sub-type.js new file mode 100644 index 0000000..a7df766 --- /dev/null +++ b/database/migrations/20260923100000-add-return-query-return-sub-type.js @@ -0,0 +1,225 @@ +'use strict'; + +/** + * 新增系统级售后类型「退回」(return)与子类型「查退回」(query_return), + * 并补齐 v2 可配置回信引擎的完整配置链。 + * + * 背景: + * - v1 引擎(inbox/rules.js STORE_RULES / WAREHOUSE_RULES)与代码函数表均有 + * queryReturn(关键词:查退回/是否已退回/查退件/查件,waybill:true); + * - v2 的 wms_after_sale_type / wms_after_sale_sub_type 中没有「退回」类型与 + * 「查退回」子类型,导致 v2 引擎无法把「查退回」类消息路由到 queryReturn 函数。 + * + * 本次新增(幂等,先查后插): + * 1. 系统级类型 return(退回,sort_order=5,紧跟出库单之后、帮助之前); + * 2. 系统级子类型 return.query_return(查退回,sort_order=1); + * 3. 关键词 8 条:查退回/查退件/退回查询/退回明细/查拆包/退件查询/退回进度/是否已退回; + * 4. 群类型白名单:group_type='*' 全通配(queryReturn 函数 groups=[COMMON],所有群可用); + * 5. 子类型-函数关系:queryReturn; + * 6. 取号规则关联:运单号提取(waybill); + * 7. 系统级回复行:reply={back_text}、is_reply=1、create_work_order=0(纯查询不建工单)、 + * no_number_hint=查退回专属引导语、is_enabled=1。 + */ + +const TYPE_TABLE = 'wms_after_sale_type'; +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const KEYWORD_TABLE = 'wms_after_sale_keyword'; +const GROUP_REL_TABLE = 'wms_after_sale_sub_type_group'; +const FUNCTION_TABLE = 'wms_after_sale_function'; +const FUNC_REL_TABLE = 'wms_after_sale_sub_type_function'; +const RULE_TABLE = 'wms_inbox_number_rule'; +const RULE_REL_TABLE = 'wms_after_sale_sub_type_rule'; +const REPLY_TABLE = 'wms_after_sale_reply'; + +const TYPE_CODE = 'return'; +const TYPE_NAME = '退回'; +const SUB_TYPE_CODE = 'query_return'; +const SUB_TYPE_NAME = '查退回'; +const KEYWORDS = [ '查退回', '查退件', '退回查询', '退回明细', '查拆包', '退件查询', '退回进度', '是否已退回' ]; +const FUNCTION_CODE = 'queryReturn'; +const RULE_NAME = '运单号提取'; +const HINT_DEFAULT = '请提供运单号(发送:查退回+运单号,多个单号用逗号或空格分隔)\n例:查退回 SF123'; + +module.exports = { + /** + * 新增系统级「退回」类型与「查退回」子类型配置链(幂等)。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 无返回值。 + */ + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(SUB_TYPE_TABLE)) return; + + const q = async (sql, replacements) => { + const [ rows ] = await sequelize.query(sql, { replacements }); + return rows; + }; + + // ─── 1. 系统级类型 return(先查后插) ──────────────────────── + if (exists(TYPE_TABLE)) { + const typeRows = await q( + 'SELECT id FROM `' + TYPE_TABLE + '` WHERE type = :t AND warehouse_id IS NULL LIMIT 1', + { t: TYPE_CODE } + ); + if (typeRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + TYPE_TABLE + '` ' + + '(warehouse_id, type, name, is_system, is_enabled, sort_order, created_at, updated_at) ' + + 'VALUES (NULL, :t, :n, 1, 1, :so, NOW(), NOW())', + { replacements: { t: TYPE_CODE, n: TYPE_NAME, so: 5 } } + ); + console.log(`[MIGRATION] 类型插入 ${TYPE_CODE}(${TYPE_NAME})`); + } + } + + // ─── 2. 系统级子类型 return.query_return(先查后插) ───────── + let subRows = await q( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', + { t: TYPE_CODE, s: SUB_TYPE_CODE } + ); + if (subRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + SUB_TYPE_TABLE + '` ' + + '(warehouse_id, type, sub_type, name, is_system, is_enabled, sort_order, created_at, updated_at) ' + + 'VALUES (NULL, :t, :s, :n, 1, 1, 1, NOW(), NOW())', + { replacements: { t: TYPE_CODE, s: SUB_TYPE_CODE, n: SUB_TYPE_NAME } } + ); + subRows = await q( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', + { t: TYPE_CODE, s: SUB_TYPE_CODE } + ); + console.log(`[MIGRATION] 子类型插入 ${TYPE_CODE}.${SUB_TYPE_CODE}`); + } + if (subRows.length === 0) { + console.warn(`[MIGRATION] 跳过:子类型 ${TYPE_CODE}.${SUB_TYPE_CODE} 缺失且插入失败`); + return; + } + const subTypeId = subRows[0].id; + + // ─── 3. 关键词(先查后插) ────────────────────────────────── + if (exists(KEYWORD_TABLE)) { + let kwInserted = 0; + for (const [ idx, kw ] of KEYWORDS.entries()) { + const kwRows = await q( + 'SELECT id FROM `' + KEYWORD_TABLE + '` WHERE keyword = :kw AND warehouse_id IS NULL LIMIT 1', + { kw } + ); + if (kwRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + KEYWORD_TABLE + '` ' + + '(warehouse_id, sub_type_id, keyword, is_system, is_enabled, sort_order, created_at, updated_at) ' + + 'VALUES (NULL, :sid, :kw, 1, 1, :so, NOW(), NOW())', + { replacements: { sid: subTypeId, kw, so: idx } } + ); + kwInserted += 1; + } + } + console.log(`[MIGRATION] 关键词插入 ${kwInserted} 条`); + } + + // ─── 4. 群类型白名单:全通配(函数 groups=[COMMON]) ───────── + if (exists(GROUP_REL_TABLE)) { + const grpRows = await q( + 'SELECT id FROM `' + GROUP_REL_TABLE + '` WHERE sub_type_id = :sid AND group_type = :g LIMIT 1', + { sid: subTypeId, g: '*' } + ); + if (grpRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + GROUP_REL_TABLE + '` ' + + '(sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :g, :sg, 1, 0, NOW(), NOW())', + { replacements: { sid: subTypeId, g: '*', sg: '' } } + ); + console.log('[MIGRATION] 群白名单插入通配行'); + } + } + + // ─── 5. 子类型-函数关系:queryReturn ─────────────────────── + if (exists(FUNC_REL_TABLE) && exists(FUNCTION_TABLE)) { + const fnRows = await q( + 'SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :code LIMIT 1', + { code: FUNCTION_CODE } + ); + if (fnRows.length > 0) { + await sequelize.query( + 'INSERT IGNORE INTO `' + FUNC_REL_TABLE + '` ' + + '(sub_type_id, function_id, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :fid, 1, NOW(), NOW())', + { replacements: { sid: subTypeId, fid: fnRows[0].id } } + ); + console.log(`[MIGRATION] 函数关系插入 ${FUNCTION_CODE}`); + } else { + console.warn(`[MIGRATION] 跳过:未找到处理函数 ${FUNCTION_CODE}`); + } + } + + // ─── 6. 运单号取号规则关联 ────────────────────────────────── + if (exists(RULE_REL_TABLE) && exists(RULE_TABLE)) { + const ruleRows = await q( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :n LIMIT 1', + { n: RULE_NAME } + ); + if (ruleRows.length > 0) { + await sequelize.query( + 'INSERT IGNORE INTO `' + RULE_REL_TABLE + '` ' + + '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :rid, 1, NOW(), NOW())', + { replacements: { sid: subTypeId, rid: ruleRows[0].id } } + ); + console.log(`[MIGRATION] 取号规则关联插入 ${RULE_NAME}`); + } else { + console.warn(`[MIGRATION] 跳过:未找到取号规则 ${RULE_NAME}`); + } + } + + // ─── 7. 系统级回复行(先查后插;纯查询不建工单) ───────────── + if (exists(REPLY_TABLE)) { + const replyRows = await q( + 'SELECT id FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL LIMIT 1', + { sid: subTypeId } + ); + if (replyRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + REPLY_TABLE + '` ' + + '(warehouse_id, sub_type_id, reply, is_reply, create_work_order, no_number_hint, is_enabled, created_at, updated_at) ' + + 'VALUES (NULL, :sid, :reply, 1, 0, :hint, 1, NOW(), NOW())', + { replacements: { sid: subTypeId, reply: '{back_text}', hint: HINT_DEFAULT } } + ); + console.log('[MIGRATION] 系统级回复行插入 1 行'); + } + } + }, + + /** + * 回滚:删除「查退回」子类型的全部关联配置与子类型、类型行。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const { sequelize } = queryInterface; + + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', + { replacements: { t: TYPE_CODE, s: SUB_TYPE_CODE } } + ); + if (subRows.length === 0) return; + const subTypeId = subRows[0].id; + + await sequelize.query('DELETE FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + KEYWORD_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + GROUP_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + FUNC_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + RULE_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + SUB_TYPE_TABLE + '` WHERE id = :sid', { replacements: { sid: subTypeId } }); + + await sequelize.query( + 'DELETE FROM `' + TYPE_TABLE + '` WHERE type = :t AND warehouse_id IS NULL', + { replacements: { t: TYPE_CODE } } + ); + }, +}; diff --git a/database/migrations/20260923120000-add-user-agreement-to-wms-wechat-app.js b/database/migrations/20260923120000-add-user-agreement-to-wms-wechat-app.js new file mode 100644 index 0000000..cb7a555 --- /dev/null +++ b/database/migrations/20260923120000-add-user-agreement-to-wms-wechat-app.js @@ -0,0 +1,24 @@ +'use strict'; + +/** + * wms_wechat_app 增加用户须知富文本字段(只做加字段): + * - user_agreement:用户须知(富文本 longText),供 wechat.getUserAgreementText/ + * wechat.getUserAgreement/wechat.setUserAgreement 读写。 + */ + +const TABLE_NAME = 'wms_wechat_app'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn(TABLE_NAME, 'user_agreement', { + type: Sequelize.TEXT('long'), + allowNull: true, + defaultValue: null, + comment: '用户须知(富文本 longText)', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn(TABLE_NAME, 'user_agreement'); + }, +}; diff --git a/database/migrations/20260923130000-user-agreement-versioning.js b/database/migrations/20260923130000-user-agreement-versioning.js new file mode 100644 index 0000000..516dcdc --- /dev/null +++ b/database/migrations/20260923130000-user-agreement-versioning.js @@ -0,0 +1,84 @@ +'use strict'; + +/** + * 用户须知改为副表版本管理(2026-09-23): + * 1. 移除 wms_wechat_app.user_agreement 字段(富文本改为副表存储); + * 2. 新增副表 wms_wechat_agreement_version:appid + 数字版本号 + 富文本, + * 提交一次自动新增版本,拉取只取最新版本; + * 3. wms_user_oauth 增加 agreement_version_id(协议版本id),loginByCode 时自动更新到最新。 + */ + +const APP_TABLE = 'wms_wechat_app'; +const VERSION_TABLE = 'wms_wechat_agreement_version'; +const OAUTH_TABLE = 'wms_user_oauth'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.removeColumn(APP_TABLE, 'user_agreement'); + + await queryInterface.createTable(VERSION_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + appid: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '小程序AppID(关联 wms_wechat_app.appid)', + }, + version: { + type: Sequelize.INTEGER, + allowNull: false, + comment: '协议版本号(数字,同一 appid 内自动+1)', + }, + content: { + type: Sequelize.TEXT('long'), + allowNull: true, + defaultValue: null, + comment: '用户须知富文本内容', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + comment: '微信用户须知版本表(副表,提交一次新增一个版本)', + }); + await queryInterface.addIndex(VERSION_TABLE, [ 'appid', 'version' ], { + unique: true, + name: 'uk_appid_version', + }); + await queryInterface.addIndex(VERSION_TABLE, [ 'appid' ], { + name: 'idx_appid', + }); + + await queryInterface.addColumn(OAUTH_TABLE, 'agreement_version_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '协议版本ID(关联 wms_wechat_agreement_version.id,loginByCode 时自动更新到最新)', + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn(OAUTH_TABLE, 'agreement_version_id'); + await queryInterface.dropTable(VERSION_TABLE); + await queryInterface.addColumn(APP_TABLE, 'user_agreement', { + type: Sequelize.TEXT('long'), + allowNull: true, + defaultValue: null, + comment: '用户须知(富文本 longText)', + }); + }, +}; diff --git a/database/migrations/20260923140000-drop-version-from-wechat-agreement-version.js b/database/migrations/20260923140000-drop-version-from-wechat-agreement-version.js new file mode 100644 index 0000000..25f4a8c --- /dev/null +++ b/database/migrations/20260923140000-drop-version-from-wechat-agreement-version.js @@ -0,0 +1,29 @@ +'use strict'; + +/** + * 用户须知版本表去掉 version 数字版本号,直接用 id 自增(2026-09-23): + * - 删除唯一索引 uk_appid_version(appid,version); + * - 删除 version 列;最新版本判定改为 ORDER BY id DESC。 + */ + +const TABLE_NAME = 'wms_wechat_agreement_version'; + +module.exports = { + async up(queryInterface) { + await queryInterface.removeIndex(TABLE_NAME, 'uk_appid_version'); + await queryInterface.removeColumn(TABLE_NAME, 'version'); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.addColumn(TABLE_NAME, 'version', { + type: Sequelize.INTEGER, + allowNull: true, + defaultValue: null, + comment: '协议版本号(数字,同一 appid 内自动+1)', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'appid', 'version' ], { + unique: true, + name: 'uk_appid_version', + }); + }, +}; diff --git a/database/migrations/20260923150000-create-method-doc-tables.js b/database/migrations/20260923150000-create-method-doc-tables.js new file mode 100644 index 0000000..9a63563 --- /dev/null +++ b/database/migrations/20260923150000-create-method-doc-tables.js @@ -0,0 +1,171 @@ +'use strict'; + +/** + * API 方法文档库表化(2026-09-23): + * - wms_api_method_doc:方法文档表(methods/system.json 的维护源) + * - wms_method_doc_meta:文档元信息表(docName 维度单行:描述/全局 headers/version/updatedAt) + * + * methods/system.json 由导出脚本 script/method-doc-export.cjs 生成,docs 页面仍读文件。 + */ + +const DOC_TABLE = 'wms_api_method_doc'; +const META_TABLE = 'wms_method_doc_meta'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable(DOC_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + method: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '方法名(如 wechat.userList)', + }, + module: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '模块标识(group.module,如 wechat)', + }, + group_name: { + type: Sequelize.STRING(128), + allowNull: false, + defaultValue: '', + comment: '分组名称(groupName)', + }, + description: { + type: Sequelize.TEXT, + allowNull: true, + comment: '接口说明', + }, + is_need_login: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否需登录', + }, + is_need_auth: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否需权限鉴权', + }, + headers: { + type: Sequelize.TEXT('long'), + allowNull: true, + comment: '请求头(JSON 数组文本,LONGTEXT 保留原键序)', + }, + params: { + type: Sequelize.TEXT('long'), + allowNull: true, + comment: '入参(JSON 数组文本,LONGTEXT 保留原键序)', + }, + response: { + type: Sequelize.TEXT('long'), + allowNull: true, + comment: '响应字段(JSON 数组文本,LONGTEXT 保留原键序)', + }, + errors: { + type: Sequelize.TEXT('long'), + allowNull: true, + comment: '错误码(JSON 数组文本,LONGTEXT 保留原键序)', + }, + group_sort: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '分组排序(导入时的原始顺序)', + }, + item_sort: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '组内排序(导入时的原始顺序)', + }, + status: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:1 启用 0 下线(导出时排除)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + comment: 'API 方法文档表(methods/system.json 的库表化维护源)', + }); + await queryInterface.addIndex(DOC_TABLE, [ 'method' ], { + unique: true, + name: 'uk_method', + }); + await queryInterface.addIndex(DOC_TABLE, [ 'module' ], { + name: 'idx_module', + }); + await queryInterface.addIndex(DOC_TABLE, [ 'status', 'module', 'group_sort', 'item_sort' ], { + name: 'idx_export_order', + }); + + await queryInterface.createTable(META_TABLE, { + id: { + type: Sequelize.TINYINT, + primaryKey: true, + allowNull: false, + comment: '固定 1(单行)', + }, + doc_name: { + type: Sequelize.STRING(64), + allowNull: false, + unique: true, + comment: '文档名(system/qimen...)', + }, + module: { + type: Sequelize.STRING(64), + allowNull: false, + defaultValue: 'system', + comment: '文档顶层 module', + }, + description: { + type: Sequelize.TEXT, + allowNull: true, + comment: '文档顶层描述', + }, + headers: { + type: Sequelize.TEXT('long'), + allowNull: true, + comment: '文档全局请求头(JSON 数组文本,LONGTEXT 保留原键序)', + }, + version: { + type: Sequelize.STRING(32), + allowNull: false, + defaultValue: '0.3.0', + comment: '文档版本(顶层 version)', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间(顶层 updatedAt)', + }, + }, { + comment: 'API 文档元信息表(docName 维度单行)', + }); + }, + + async down(queryInterface) { + await queryInterface.dropTable(META_TABLE); + await queryInterface.dropTable(DOC_TABLE); + }, +}; diff --git a/database/migrations/20260923160000-method-doc-text-columns.js b/database/migrations/20260923160000-method-doc-text-columns.js new file mode 100644 index 0000000..4c1f1e2 --- /dev/null +++ b/database/migrations/20260923160000-method-doc-text-columns.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * 文档表 JSON 列改为 LONGTEXT(2026-09-23): + * MySQL JSON 列会归一化对象键序(如 value/name → name/value),导致导出 system.json + * 与原件产生大量无意义 diff。改为 LONGTEXT 存原始 JSON 文本,导出时原样解析,保证无损往返。 + */ + +const DOC_TABLE = 'wms_api_method_doc'; +const META_TABLE = 'wms_method_doc_meta'; + +module.exports = { + async up(queryInterface, Sequelize) { + const columns = [ + [ 'headers', '请求头(JSON 数组文本)' ], + [ 'params', '入参(JSON 数组文本)' ], + [ 'response', '响应字段(JSON 数组文本)' ], + [ 'errors', '错误码(JSON 数组文本)' ], + ]; + for (const [ name, comment ] of columns) { + await queryInterface.changeColumn(DOC_TABLE, name, { + type: Sequelize.TEXT('long'), + allowNull: true, + comment, + }); + } + await queryInterface.changeColumn(META_TABLE, 'headers', { + type: Sequelize.TEXT('long'), + allowNull: true, + comment: '文档全局请求头(JSON 数组文本)', + }); + }, + + async down(queryInterface, Sequelize) { + const columns = [ 'headers', 'params', 'response', 'errors' ]; + for (const name of columns) { + await queryInterface.changeColumn(DOC_TABLE, name, { + type: Sequelize.JSON, + allowNull: true, + comment: name, + }); + } + await queryInterface.changeColumn(META_TABLE, 'headers', { + type: Sequelize.JSON, + allowNull: true, + comment: '文档全局请求头(JSON 数组)', + }); + }, +}; diff --git a/database/migrations/20260923170000-method-doc-payload-column.js b/database/migrations/20260923170000-method-doc-payload-column.js new file mode 100644 index 0000000..58b6bab --- /dev/null +++ b/database/migrations/20260923170000-method-doc-payload-column.js @@ -0,0 +1,25 @@ +'use strict'; + +/** + * 方法文档表增加 payload 列(2026-09-23): + * 原始条目含 status/notes/requestBody 等扩展字段,结构化列无法覆盖。 + * payload 存整个 method 条目的原始 JSON 文本,导入/导出按原文无损往返; + * 结构化列(method/module/group_name/description/is_need_login/is_need_auth/headers/params/response/errors) + * 仅用于检索过滤,导出优先使用 payload。 + */ + +const DOC_TABLE = 'wms_api_method_doc'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn(DOC_TABLE, 'payload', { + type: Sequelize.TEXT('long'), + allowNull: true, + comment: 'method 条目完整 JSON 文本(含 status/notes/requestBody 等扩展字段,无损往返用)', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn(DOC_TABLE, 'payload'); + }, +}; diff --git a/database/migrations/20260923180000-add-created-at-index-to-wms-return-received.js b/database/migrations/20260923180000-add-created-at-index-to-wms-return-received.js new file mode 100644 index 0000000..e218a68 --- /dev/null +++ b/database/migrations/20260923180000-add-created-at-index-to-wms-return-received.js @@ -0,0 +1,20 @@ +'use strict'; + +/** + * wms_return_received 补充登记时间索引。 + * returnReceived.list 默认按 created_at desc 排序且支持 created_at 范围筛选, + * 仓库隔离为 warehouse_id,原表仅有 (warehouse_id, scan_date) 等索引, + * 登记时间过滤与排序会退化为全表扫描 + filesort,新增 (warehouse_id, created_at) + * 复合索引使范围过滤与默认排序走索引。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.addIndex('wms_return_received', [ 'warehouse_id', 'created_at' ], { + name: 'idx_warehouse_created_at', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('wms_return_received', 'idx_warehouse_created_at'); + }, +}; diff --git a/database/migrations/20260924100000-add-query-pack-video-sub-type.js b/database/migrations/20260924100000-add-query-pack-video-sub-type.js new file mode 100644 index 0000000..5ca9fbf --- /dev/null +++ b/database/migrations/20260924100000-add-query-pack-video-sub-type.js @@ -0,0 +1,201 @@ +'use strict'; + +/** + * 订单类型新增系统级子类型「打包视频查询」(query_pack_video),并补齐 v2 配置链。 + * + * 背景: + * - v1 引擎(inbox/rules.js STORE_RULES / WAREHOUSE_RULES)与代码函数表均有 + * queryPackVideo(关键词:打包视频/装箱视频,waybill:true); + * - v2 的 wms_after_sale_sub_type 中没有该子类型,导致 v2 引擎无法把 + * 「打包视频」类消息路由到 queryPackVideo 函数。 + * + * 本次新增(幂等,先查后插): + * 1. 系统级子类型 order.query_pack_video(打包视频查询,sort_order=20 末尾追加); + * 2. 关键词 5 条:打包视频/打包录像/装箱视频/打包监控/录像; + * 3. 群类型白名单:store:after_sales + warehouse:customer_service(与函数 groups 一致); + * 4. 子类型-函数关系:queryPackVideo; + * 5. 取号规则关联:运单号提取(waybill); + * 6. 系统级回复行:reply={back_text}、is_reply=1、create_work_order=0(纯查询不建工单)、 + * no_number_hint=打包视频专属引导语、is_enabled=1。 + */ + +const SUB_TYPE_TABLE = 'wms_after_sale_sub_type'; +const KEYWORD_TABLE = 'wms_after_sale_keyword'; +const GROUP_REL_TABLE = 'wms_after_sale_sub_type_group'; +const FUNCTION_TABLE = 'wms_after_sale_function'; +const FUNC_REL_TABLE = 'wms_after_sale_sub_type_function'; +const RULE_TABLE = 'wms_inbox_number_rule'; +const RULE_REL_TABLE = 'wms_after_sale_sub_type_rule'; +const REPLY_TABLE = 'wms_after_sale_reply'; + +const TYPE_CODE = 'order'; +const SUB_TYPE_CODE = 'query_pack_video'; +const SUB_TYPE_NAME = '打包视频查询'; +const KEYWORDS = [ '打包视频', '打包录像', '装箱视频', '打包监控', '录像' ]; +const GROUP_WHITELIST = [ + { group_type: 'store', sub_group: 'after_sales' }, + { group_type: 'warehouse', sub_group: 'customer_service' }, +]; +const FUNCTION_CODE = 'queryPackVideo'; +const RULE_NAME = '运单号提取'; +const HINT_DEFAULT = '请提供运单号(发送:打包视频+运单号,多个单号用逗号或空格分隔)\n例:打包视频 SF123'; + +module.exports = { + /** + * 新增系统级「打包视频查询」子类型配置链(幂等)。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 无返回值。 + */ + up: async queryInterface => { + const { sequelize } = queryInterface; + const tables = await queryInterface.showAllTables(); + const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t); + if (!exists(SUB_TYPE_TABLE)) return; + + const q = async (sql, replacements) => { + const [ rows ] = await sequelize.query(sql, { replacements }); + return rows; + }; + + // ─── 1. 系统级子类型 order.query_pack_video(先查后插) ────── + let subRows = await q( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', + { t: TYPE_CODE, s: SUB_TYPE_CODE } + ); + if (subRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + SUB_TYPE_TABLE + '` ' + + '(warehouse_id, type, sub_type, name, is_system, is_enabled, sort_order, created_at, updated_at) ' + + 'VALUES (NULL, :t, :s, :n, 1, 1, :so, NOW(), NOW())', + { replacements: { t: TYPE_CODE, s: SUB_TYPE_CODE, n: SUB_TYPE_NAME, so: 20 } } + ); + subRows = await q( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', + { t: TYPE_CODE, s: SUB_TYPE_CODE } + ); + console.log(`[MIGRATION] 子类型插入 ${TYPE_CODE}.${SUB_TYPE_CODE}`); + } + if (subRows.length === 0) { + console.warn(`[MIGRATION] 跳过:子类型 ${TYPE_CODE}.${SUB_TYPE_CODE} 缺失且插入失败`); + return; + } + const subTypeId = subRows[0].id; + + // ─── 2. 关键词(先查后插) ────────────────────────────────── + if (exists(KEYWORD_TABLE)) { + let kwInserted = 0; + for (const [ idx, kw ] of KEYWORDS.entries()) { + const kwRows = await q( + 'SELECT id FROM `' + KEYWORD_TABLE + '` WHERE keyword = :kw AND warehouse_id IS NULL LIMIT 1', + { kw } + ); + if (kwRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + KEYWORD_TABLE + '` ' + + '(warehouse_id, sub_type_id, keyword, is_system, is_enabled, sort_order, created_at, updated_at) ' + + 'VALUES (NULL, :sid, :kw, 1, 1, :so, NOW(), NOW())', + { replacements: { sid: subTypeId, kw, so: idx } } + ); + kwInserted += 1; + } + } + console.log(`[MIGRATION] 关键词插入 ${kwInserted} 条`); + } + + // ─── 3. 群类型白名单(INSERT IGNORE,与函数 groups 一致) ──── + if (exists(GROUP_REL_TABLE)) { + let grpInserted = 0; + for (const [ idx, g ] of GROUP_WHITELIST.entries()) { + await sequelize.query( + 'INSERT IGNORE INTO `' + GROUP_REL_TABLE + '` ' + + '(sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :groupType, :subGroup, 1, :so, NOW(), NOW())', + { replacements: { sid: subTypeId, groupType: g.group_type, subGroup: g.sub_group, so: idx + 1 } } + ); + grpInserted += 1; + } + console.log(`[MIGRATION] 群白名单插入 ${grpInserted} 条`); + } + + // ─── 4. 子类型-函数关系:queryPackVideo ───────────────────── + if (exists(FUNC_REL_TABLE) && exists(FUNCTION_TABLE)) { + const fnRows = await q( + 'SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :code LIMIT 1', + { code: FUNCTION_CODE } + ); + if (fnRows.length > 0) { + await sequelize.query( + 'INSERT IGNORE INTO `' + FUNC_REL_TABLE + '` ' + + '(sub_type_id, function_id, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :fid, 1, NOW(), NOW())', + { replacements: { sid: subTypeId, fid: fnRows[0].id } } + ); + console.log(`[MIGRATION] 函数关系插入 ${FUNCTION_CODE}`); + } else { + console.warn(`[MIGRATION] 跳过:未找到处理函数 ${FUNCTION_CODE}`); + } + } + + // ─── 5. 运单号取号规则关联 ────────────────────────────────── + if (exists(RULE_REL_TABLE) && exists(RULE_TABLE)) { + const ruleRows = await q( + 'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :n LIMIT 1', + { n: RULE_NAME } + ); + if (ruleRows.length > 0) { + await sequelize.query( + 'INSERT IGNORE INTO `' + RULE_REL_TABLE + '` ' + + '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) ' + + 'VALUES (:sid, :rid, 1, NOW(), NOW())', + { replacements: { sid: subTypeId, rid: ruleRows[0].id } } + ); + console.log(`[MIGRATION] 取号规则关联插入 ${RULE_NAME}`); + } else { + console.warn(`[MIGRATION] 跳过:未找到取号规则 ${RULE_NAME}`); + } + } + + // ─── 6. 系统级回复行(先查后插;纯查询不建工单) ───────────── + if (exists(REPLY_TABLE)) { + const replyRows = await q( + 'SELECT id FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL LIMIT 1', + { sid: subTypeId } + ); + if (replyRows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + REPLY_TABLE + '` ' + + '(warehouse_id, sub_type_id, reply, is_reply, create_work_order, no_number_hint, is_enabled, created_at, updated_at) ' + + 'VALUES (NULL, :sid, :reply, 1, 0, :hint, 1, NOW(), NOW())', + { replacements: { sid: subTypeId, reply: '{back_text}', hint: HINT_DEFAULT } } + ); + console.log('[MIGRATION] 系统级回复行插入 1 行'); + } + } + }, + + /** + * 回滚:删除「打包视频查询」子类型的全部关联配置与子类型行。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const { sequelize } = queryInterface; + + const [ subRows ] = await sequelize.query( + 'SELECT id FROM `' + SUB_TYPE_TABLE + '` ' + + 'WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', + { replacements: { t: TYPE_CODE, s: SUB_TYPE_CODE } } + ); + if (subRows.length === 0) return; + const subTypeId = subRows[0].id; + + await sequelize.query('DELETE FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + KEYWORD_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + GROUP_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + FUNC_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + RULE_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } }); + await sequelize.query('DELETE FROM `' + SUB_TYPE_TABLE + '` WHERE id = :sid', { replacements: { sid: subTypeId } }); + }, +}; diff --git a/database/migrations/20260924120000-add-domain-verify-to-wms-warehouse-front-config.js b/database/migrations/20260924120000-add-domain-verify-to-wms-warehouse-front-config.js new file mode 100644 index 0000000..9550877 --- /dev/null +++ b/database/migrations/20260924120000-add-domain-verify-to-wms-warehouse-front-config.js @@ -0,0 +1,186 @@ +'use strict'; + +const TABLE_NAME = 'wms_warehouse_front_config'; +const DOMAIN_STATUS_COLUMN = 'domain_status'; +const DOMAIN_STATUS_INDEX_NAME = 'idx_domain_status'; + +/** + * Migration: 仓库前端配置表新增域名验证(DNS TXT 校验)相关列与索引。 + * + * 背景: + * 前端独立部署需要用户把自持域名解析到平台,必须校验域名归属,避免非自持域名 + * 被指向平台(域名误配/抢注、证书误签)。方案为 DNS TXT 校验:后端为每个仓库 + * 生成一次性校验主机名(wmsv-<10 位 hex>.<域名>)与校验值(32 位 hex),用户在 + * 该子域配置 TXT 记录,后端解析比对通过后置为已验证。未通过验证的域名不得上传 + * 证书(frontConfig.saveCert 前置闸门),公共按域名拉取同以 domain_status=1 为闸门。 + * + * 新增列: + * - domain_status : 域名验证状态:0-未验证,1-已验证,2-验证失败(NOT NULL,默认 0); + * - domain_verify_host : 待校验 TXT 记录主机名(wmsv-<随机码>.<域名>); + * - domain_verify_token : 待校验 TXT 记录值(32 位 hex); + * - domain_verified_at : 域名验证通过时间; + * - domain_verify_attempts : 验证尝试次数(定时任务自增,超过 maxAttempts 后停止自动重试); + * - domain_last_error : 最近一次验证失败原因(脱敏截断,≤500 字符)。 + * 新增索引: + * - idx_domain_status:域名验证定时任务按 domain_status 扫描待验证行的查询索引。 + * + * ⚠ 存量数据回填(本次迁移的关键动作): + * 升级前已写入 domain 的行,其域名在线上已生效(nginx 已在按域名提供服务),必须 + * 视为「已验证」,否则新加入的 domain_status=1 闸门会在升级瞬间把生产现有域名 + * 全部断掉(证书上传被拒、公共拉取被拒)。 + * 回填 SQL:UPDATE ... SET domain_status = 1 + * WHERE domain IS NOT NULL AND domain <> '' AND domain_status = 0。 + * 回填只在本次真正新增 domain_status 列的那一次执行:迁移允许重复执行,若列已存在 + * 仍继续回填,会把「升级后新设置但尚未验证」的域名误标为已验证。 + * domain_verified_at 保持 NULL:历史生效时间不可考,不写入虚假时间。 + * + * Idempotent: 列/索引已存在时跳过;down 逐索引、逐列判存在后删除。 + */ + +/** + * 判断表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 存在返回 true。 + */ +async function tableExists(queryInterface, tableName) { + const tables = await queryInterface.showAllTables(); + return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName); +} + +/** + * 判断索引是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 存在返回 true。 + */ +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(item => (typeof item === 'string' ? item : item.name) === indexName); +} + +module.exports = { + /** + * 执行正向迁移:新增域名验证相关列与索引,并回填存量已生效域名(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (!(await tableExists(queryInterface, TABLE_NAME))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + const domainStatusAdded = !columns[DOMAIN_STATUS_COLUMN]; + + if (domainStatusAdded) { + await queryInterface.addColumn(TABLE_NAME, DOMAIN_STATUS_COLUMN, { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '域名验证状态:0-未验证,1-已验证,2-验证失败', + after: 'domain', + }); + } + + if (!columns.domain_verify_host) { + await queryInterface.addColumn(TABLE_NAME, 'domain_verify_host', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '待校验 TXT 记录主机名(wmsv-<随机码>.<域名>)', + after: 'domain_status', + }); + } + + if (!columns.domain_verify_token) { + await queryInterface.addColumn(TABLE_NAME, 'domain_verify_token', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '待校验 TXT 记录值(32 位 hex)', + after: 'domain_verify_host', + }); + } + + if (!columns.domain_verified_at) { + await queryInterface.addColumn(TABLE_NAME, 'domain_verified_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '域名验证通过时间', + after: 'domain_verify_token', + }); + } + + if (!columns.domain_verify_attempts) { + await queryInterface.addColumn(TABLE_NAME, 'domain_verify_attempts', { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '域名验证尝试次数', + after: 'domain_verified_at', + }); + } + + if (!columns.domain_last_error) { + await queryInterface.addColumn(TABLE_NAME, 'domain_last_error', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '最近一次域名验证失败原因', + after: 'domain_verify_attempts', + }); + } + + if (!(await indexExists(queryInterface, TABLE_NAME, DOMAIN_STATUS_INDEX_NAME))) { + await queryInterface.addIndex(TABLE_NAME, [ DOMAIN_STATUS_COLUMN ], { + name: DOMAIN_STATUS_INDEX_NAME, + }); + } + + // 存量回填:升级前已写入 domain 的行在线上已生效,必须视为「已验证」, + // 否则 domain_status=1 闸门会在升级瞬间断掉生产现有域名。 + // 仅在本次真正新增该列时执行(重复执行迁移不得把新设置但未验证的域名误标为已验证), + // WHERE 仍带 domain_status = 0 守卫,重复执行同样安全。 + if (domainStatusAdded) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE \`${TABLE_NAME}\` + SET \`domain_status\` = 1 + WHERE \`domain\` IS NOT NULL + AND \`domain\` <> '' + AND \`domain_status\` = 0` + ); + const affectedRows = Number(result && result.affectedRows !== undefined ? result.affectedRows : result) || 0; + console.log(`[migration] ${TABLE_NAME} 存量域名回填 domain_status=1,影响行数=${affectedRows}`); + } + }, + + /** + * 回滚迁移:删除域名验证相关索引与列(幂等)。 + * 注意:回滚会一并丢弃域名验证状态与校验记录,域名将退回「无验证闸门」状态。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!(await tableExists(queryInterface, TABLE_NAME))) { + return; + } + + if (await indexExists(queryInterface, TABLE_NAME, DOMAIN_STATUS_INDEX_NAME)) { + await queryInterface.removeIndex(TABLE_NAME, DOMAIN_STATUS_INDEX_NAME); + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + for (const columnName of [ + 'domain_last_error', + 'domain_verify_attempts', + 'domain_verified_at', + 'domain_verify_token', + 'domain_verify_host', + DOMAIN_STATUS_COLUMN, + ]) { + if (columns[columnName]) { + await queryInterface.removeColumn(TABLE_NAME, columnName); + } + } + }, +}; diff --git a/database/migrations/20260924150000-add-wave-scope-to-pack-task.js b/database/migrations/20260924150000-add-wave-scope-to-pack-task.js new file mode 100644 index 0000000..6005e39 --- /dev/null +++ b/database/migrations/20260924150000-add-wave-scope-to-pack-task.js @@ -0,0 +1,72 @@ +'use strict'; + +/** + * 打包任务表 wms_pack_task 增加 wave_scope(波次范围)字段。 + * + * 取值约定(与 wms_order_delivery.wave_scope 一致): + * - 0 = 未分配波次 + * - 1 = 大团购 + * - 2 = 散单 + * - 3 = 小团购 + * - 4 = 单品单件 + * 默认 0。 + * + * 来源:workbench.packOrder 创建打包任务时落库,值由服务端复查 + * (优先取打包上下文上报值,非法/缺省时兜底取订单行 wave_scope)。 + * + * 幂等:列已存在则跳过。 + */ + +const TABLE_NAME = 'wms_pack_task'; + +const COLUMN_NAME = 'wave_scope'; + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为 wms_pack_task 增加 wave_scope 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log('[20260924150000-add-wave-scope-to-pack-task] up: 列已存在,跳过'); + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.TINYINT(4), + allowNull: false, + defaultValue: 0, + comment: '波次范围:0未分配波次 1大团购 2散单 3小团购 4单品单件', + }); + console.log('[20260924150000-add-wave-scope-to-pack-task] up: 已为 wms_pack_task 添加 wave_scope 列'); + }, + + /** + * 回滚迁移:移除 wms_pack_task 的 wave_scope 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log('[20260924150000-add-wave-scope-to-pack-task] down: 列不存在,跳过'); + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + console.log('[20260924150000-add-wave-scope-to-pack-task] down: 已移除 wms_pack_task 的 wave_scope 列'); + }, +}; diff --git a/database/migrations/20260924160000-add-source-ids-to-wms-return-query-log.js b/database/migrations/20260924160000-add-source-ids-to-wms-return-query-log.js new file mode 100644 index 0000000..3549df8 --- /dev/null +++ b/database/migrations/20260924160000-add-source-ids-to-wms-return-query-log.js @@ -0,0 +1,50 @@ +'use strict'; + +const TABLE = 'wms_return_query_log'; + +/** + * 退回查询记录表新增登记来源字段:group_id / group_name / user_id / user_name。 + * 站内信「查退回」触发登记时写入查询来源的群/用户信息(后台 API 登记路径为 null), + * 用于登记追溯与后续定向回信。字段口径与 wms_video_record_request 保持一致。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + if (!columns.group_id) { + await queryInterface.addColumn(TABLE, 'group_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '触发查询的群ID(站内信外部群ID)', + }); + } + if (!columns.group_name) { + await queryInterface.addColumn(TABLE, 'group_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '触发查询的群名称', + }); + } + if (!columns.user_id) { + await queryInterface.addColumn(TABLE, 'user_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '触发查询的用户ID(站内信外部用户ID)', + }); + } + if (!columns.user_name) { + await queryInterface.addColumn(TABLE, 'user_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '触发查询的用户名称', + }); + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + if (columns.group_id) await queryInterface.removeColumn(TABLE, 'group_id'); + if (columns.group_name) await queryInterface.removeColumn(TABLE, 'group_name'); + if (columns.user_id) await queryInterface.removeColumn(TABLE, 'user_id'); + if (columns.user_name) await queryInterface.removeColumn(TABLE, 'user_name'); + }, +}; diff --git a/database/migrations/20260924180000-add-pending-domain-to-wms-warehouse-front-config.js b/database/migrations/20260924180000-add-pending-domain-to-wms-warehouse-front-config.js new file mode 100644 index 0000000..b66c587 --- /dev/null +++ b/database/migrations/20260924180000-add-pending-domain-to-wms-warehouse-front-config.js @@ -0,0 +1,220 @@ +'use strict'; + +const TABLE_NAME = 'wms_warehouse_front_config'; +const PENDING_DOMAIN_INDEX_NAME = 'idx_pending_domain'; +const RETIRED_DOMAIN_INDEX_NAME = 'idx_retired_domain'; + +/** + * Migration: 仓库前端配置表新增「两阶段域名切换」相关列与索引。 + * + * 背景(为什么需要这次改造): + * 原实现 frontConfig.setDomain 是「设置即生效」——一次调用就把 domain 改成新域名、 + * domain_status 归零并清空证书。后果是旧域名立刻被 frontConfig.getByDomain 判为 + * 「域名未配置」(404),而 nginx 侧旧域名 server 块还在,出现「页面能打开但拉不到配置」 + * 的中间态;用户改错域名也无法回滚。 + * + * 方案(方案 B·两阶段切换,待验证域名与生效域名分离): + * 1. 第一阶段(frontConfig.setDomain):只把新域名登记到 pending_domain 并下发 TXT 校验码, + * 生效域名 domain、domain_status、domain_verified_at、证书与同步状态一律不动; + * 2. 第二阶段(frontConfig.checkDomain 手动触发 / app/schedule/domain_verify_scan.js 定时扫描): + * TXT 校验通过后由 frontConfig.promotePendingDomain 一次性把 pending_domain 提升为 + * domain(domain_status=1),同时把旧域名写入 retired_domain 下线队列、清空证书并重置同步状态。 + * 旧域名的 nginx 配置与证书文件由外部证书脚本按 retired_domain 删除后置 NULL(本次不改脚本)。 + * + * 新增列(全部可空或带默认值,无需数据回填): + * - pending_domain : 待验证域名(STRING(100),验证通过后才提升为生效域名 domain); + * - pending_verify_host : 待验证域名的 TXT 记录主机名(STRING(255),wmsv-<随机码>.<待验证域名>); + * - pending_verify_token : 待验证域名的 TXT 记录值(STRING(64),32 位 hex); + * - pending_verify_attempts: 待验证域名校验尝试次数(INTEGER,NOT NULL,默认 0); + * - pending_last_error : 待验证域名最近一次失败原因(STRING(500),脱敏截断); + * - pending_created_at : 发起域名切换的时间(DATE); + * - retired_domain : 待下线旧域名(STRING(100),域名提升时写入,外部脚本删除其 + * nginx 配置与证书文件后置 NULL); + * - retired_at : 旧域名进入下线队列的时间(DATE)。 + * 新增索引: + * - idx_pending_domain:域名验证定时任务按 pending_domain 扫描待验证行的查询索引(普通索引); + * - idx_retired_domain:外部证书脚本按 retired_domain 扫描待下线旧域名的查询索引(普通索引)。 + * + * 为什么无需回填: + * 8 个新列要么可空、要么带默认值 0,存量行的 pending_* 一律为 NULL / 0 → 语义就是 + * 「没有待验证域名」,生效域名 domain / domain_status / 证书 / 同步状态全部保持原值, + * 升级瞬间行为与升级前一致(唯一变化是下次 setDomain 会走两阶段,属预期变更)。 + * 注意:pending_domain 只有普通索引(非唯一),并发提交同一域名理论上仍可能同时写入两行, + * 最终由 domain 上的唯一索引在「提升」阶段兜底(提升冲突会保留待验证状态并记入错误)。 + * + * Idempotent: 列/索引已存在时跳过;down 先删索引、再按倒序删列(均判存在后执行)。 + */ + +/** + * 判断表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 存在返回 true。 + */ +async function tableExists(queryInterface, tableName) { + const tables = await queryInterface.showAllTables(); + return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName); +} + +/** + * 判断索引是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 存在返回 true。 + */ +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(item => (typeof item === 'string' ? item : item.name) === indexName); +} +module.exports = { + /** + * 执行正向迁移:新增两阶段域名切换相关列与索引(幂等,无数据回填)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (!(await tableExists(queryInterface, TABLE_NAME))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + + // 列定义表:after 显式指定列序,pending 组紧随域名验证组,retired 组接在 pending 组之后 + const columnDefs = [ + { + name: 'pending_domain', + after: 'domain_last_error', + definition: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '待验证域名:setDomain 只登记到本列,TXT 校验通过后才提升为生效域名 domain', + }, + }, + { + name: 'pending_verify_host', + after: 'pending_domain', + definition: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '待验证域名的 TXT 记录主机名(wmsv-<随机码>.<待验证域名>)', + }, + }, + { + name: 'pending_verify_token', + after: 'pending_verify_host', + definition: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '待验证域名的 TXT 记录值(32 位 hex)', + }, + }, + { + name: 'pending_verify_attempts', + after: 'pending_verify_token', + definition: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '待验证域名校验尝试次数', + }, + }, + { + name: 'pending_last_error', + after: 'pending_verify_attempts', + definition: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '待验证域名最近一次失败原因', + }, + }, + { + name: 'pending_created_at', + after: 'pending_last_error', + definition: { + type: Sequelize.DATE, + allowNull: true, + comment: '发起域名切换的时间', + }, + }, + { + name: 'retired_domain', + after: 'pending_created_at', + definition: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '待下线旧域名:域名提升时写入,外部证书脚本删除其 nginx 配置与证书文件后置 NULL', + }, + }, + { + name: 'retired_at', + after: 'retired_domain', + definition: { + type: Sequelize.DATE, + allowNull: true, + comment: '旧域名进入下线队列的时间', + }, + }, + ]; + + for (const item of columnDefs) { + if (!columns[item.name]) { + await queryInterface.addColumn(TABLE_NAME, item.name, { + ...item.definition, + after: item.after, + }); + } + } + + if (!(await indexExists(queryInterface, TABLE_NAME, PENDING_DOMAIN_INDEX_NAME))) { + await queryInterface.addIndex(TABLE_NAME, [ 'pending_domain' ], { + name: PENDING_DOMAIN_INDEX_NAME, + }); + } + + if (!(await indexExists(queryInterface, TABLE_NAME, RETIRED_DOMAIN_INDEX_NAME))) { + await queryInterface.addIndex(TABLE_NAME, [ 'retired_domain' ], { + name: RETIRED_DOMAIN_INDEX_NAME, + }); + } + }, + /** + * 回滚迁移:删除两阶段域名切换相关索引与列(幂等)。 + * + * 注意:回滚会一并丢弃待验证域名与下线队列(pending_* / retired_*), + * 但不会改动生效域名 domain、domain_status、证书与同步状态,因此不影响线上已生效域名。 + * 回滚后代码若仍为两阶段版本,setDomain / checkDomain 会因缺少 pending_* 列而报错, + * 需与代码版本一并回退。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!(await tableExists(queryInterface, TABLE_NAME))) { + return; + } + + for (const indexName of [ RETIRED_DOMAIN_INDEX_NAME, PENDING_DOMAIN_INDEX_NAME ]) { + if (await indexExists(queryInterface, TABLE_NAME, indexName)) { + await queryInterface.removeIndex(TABLE_NAME, indexName); + } + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + // 倒序删除(与 up 的列序相反):先删 retired 组,再删 pending 组 + for (const columnName of [ + 'retired_at', + 'retired_domain', + 'pending_created_at', + 'pending_last_error', + 'pending_verify_attempts', + 'pending_verify_token', + 'pending_verify_host', + 'pending_domain', + ]) { + if (columns[columnName]) { + await queryInterface.removeColumn(TABLE_NAME, columnName); + } + } + }, +}; diff --git a/database/migrations/20260925100000-create-wms-client-error-log.js b/database/migrations/20260925100000-create-wms-client-error-log.js new file mode 100644 index 0000000..b498b4d --- /dev/null +++ b/database/migrations/20260925100000-create-wms-client-error-log.js @@ -0,0 +1,115 @@ +'use strict'; + +/** + * 创建客户端错误日志暂存表 wms_client_error_log。 + * + * 背景:Android/iOS/Web 等设备端将运行时错误日志上报到服务端暂存, + * 供人工/后台查询分析跟踪 bug。接口入口 index.uploadClientErrorLog + * (免登录、免权限、免鉴权,保留系统日志)。 + * + * 字段:客户端类型/版本、设备标识、系统版本/型号、错误类型、错误信息与堆栈、 + * 附加上下文 extra、report_uuid(客户端生成,唯一索引幂等去重)、 + * client_time(客户端发生时间,仅参考)、created_at(服务端写入时间)。 + * + * 索引:idx_created_at、idx_client_type_app_version、idx_device_id、uk_report_uuid(唯一)。 + */ + +const TABLE_NAME = 'wms_client_error_log'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE, TEXT } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + client_type: { + type: STRING(32), + allowNull: false, + defaultValue: '', + comment: '客户端类型:android/ios/web 等', + }, + app_version: { + type: STRING(64), + allowNull: false, + defaultValue: '', + comment: '客户端版本号', + }, + device_id: { + type: STRING(128), + allowNull: false, + defaultValue: '', + comment: '设备唯一标识', + }, + os_version: { + type: STRING(64), + allowNull: false, + defaultValue: '', + comment: '操作系统版本', + }, + device_model: { + type: STRING(128), + allowNull: false, + defaultValue: '', + comment: '设备型号', + }, + error_type: { + type: STRING(64), + allowNull: false, + defaultValue: '', + comment: '错误类型/等级', + }, + error_message: { + type: TEXT, + allowNull: true, + comment: '错误信息(服务端截断上限 5000 字符)', + }, + error_stack: { + type: TEXT('medium'), + allowNull: true, + comment: '错误堆栈(服务端截断上限 65535 字符)', + }, + extra: { + type: TEXT, + allowNull: true, + comment: '附加上下文(JSON 字符串,服务端截断上限 65535 字符)', + }, + report_uuid: { + type: STRING(64), + allowNull: false, + defaultValue: '', + comment: '客户端上报幂等ID(唯一索引,重复上报静默成功)', + }, + client_time: { + type: DATE, + allowNull: true, + comment: '客户端错误发生时间(仅参考,不作为记录时间)', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '服务端写入时间(统一取服务器当前时间)', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], { name: 'idx_created_at' }); + await queryInterface.addIndex(TABLE_NAME, [ 'client_type', 'app_version' ], { name: 'idx_client_type_app_version' }); + await queryInterface.addIndex(TABLE_NAME, [ 'device_id' ], { name: 'idx_device_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'report_uuid' ], { name: 'uk_report_uuid', unique: true }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260927090000-offline-wms-system-log.js b/database/migrations/20260927090000-offline-wms-system-log.js new file mode 100644 index 0000000..efb330a --- /dev/null +++ b/database/migrations/20260927090000-offline-wms-system-log.js @@ -0,0 +1,106 @@ +'use strict'; + +/** + * 下线 wms_system_log(接口流水表)。 + * + * 背景:接口流水已改为经 Egg 自定义 logger(`config.customLogger.apiLog`)平铺写入 + * `/root/logs/wms/wms-api.log`,应用侧不再有任何写入路径;生产库该表已膨胀到 + * 687,030 行 / DATA_LENGTH 19,357 MB(约 18.9 GB),而 DATA_FREE 仅 5 MB —— + * 单纯按保留期删行不会把空间还给操作系统,必须整表下线才能回收磁盘。 + * + * ⚠️ 本迁移会永久丢弃表内历史数据。如需留档,请在执行前先自行导出: + * mysqldump -h127.0.0.1 -uwms -p wms wms_system_log | gzip > /root/wms_system_log-$(date +%F).sql.gz + * + * 幂等:up 用 DROP TABLE IF EXISTS;down 先探测表存在性再重建。 + * + * 同批次一起下线的代码(见同批改动): + * - app/model/system_log.js (已删除) + * - app/service/systems/system_log.js (已删除,60 天保留期清理服务) + * - app/schedule/system_log_cleanup.js (已删除,每日 03:00 清理定时任务) + * - app/lib/api_log_sink.js (移除 writeToDb 回滚入库分支) + * - config/config.default.js (移除 systemLog / systemLogCleanup) + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:删除 wms_system_log 表(幂等)。 + * + * 说明:该表对 wms_store 有外键(wms_system_log.store_id → wms_store.id), + * 属"出边"外键,删除子表不影响父表,无需先关闭 FOREIGN_KEY_CHECKS; + * 已确认库内没有指向 wms_system_log 的入边外键、视图或触发器。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async up(queryInterface) { + const tableName = 'wms_system_log'; + // 用 information_schema 探测而非依赖异常:MySQL 5.7 / 8.0 的 IF EXISTS 行为一致但便于记录日志 + const [[ probe ]] = await queryInterface.sequelize.query( + 'SELECT COUNT(*) AS cnt FROM information_schema.TABLES' + + ' WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName', + { replacements: { tableName } } + ); + if (!Number(probe && probe.cnt)) { + return; + } + + const [[ size ]] = await queryInterface.sequelize.query( + 'SELECT ROUND(DATA_LENGTH / 1024 / 1024) AS data_mb, ROUND(INDEX_LENGTH / 1024 / 1024) AS idx_mb, TABLE_ROWS AS est_rows' + + ' FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName', + { replacements: { tableName } } + ); + await queryInterface.sequelize.query(`DROP TABLE IF EXISTS \`${tableName}\``); + // eslint-disable-next-line no-console + console.log( + `[offline-wms-system-log] 已删除 ${tableName}(原估算行数=${size && size.est_rows}` + + ` 数据=${size && size.data_mb}MB 索引=${size && size.idx_mb}MB)` + ); + }, + + /** + * 回滚迁移:按原结构重建空的 wms_system_log 表(幂等,不恢复数据)。 + * + * 直接用原生 DDL 重建,而不是 queryInterface.createTable —— 后者在 MySQL 下 + * 默认字符集是 utf8(即 utf8mb3),也不会生成原始的 + * `created_at datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP`; + * 只有原生 DDL 才能让回滚后的结构与下线前完全一致。 + * + * ⚠️ 表内数据不会恢复;需要留档请在 up 之前自行 mysqldump。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_system_log'; + const tables = await queryInterface.showAllTables(); + if (tables.includes(tableName)) { + return; + } + + await queryInterface.sequelize.query( + `CREATE TABLE \`${tableName}\` (` + + ' `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT,' + + ' `method` varchar(100) DEFAULT NULL,' + + ' `v` varchar(50) DEFAULT NULL,' + + ' `url` text,' + + ' `created_at` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,' + + ' `body` longtext,' + + ' `result` longtext,' + + ' `use_time` int DEFAULT NULL,' + + ' `updated_at` datetime DEFAULT NULL,' + + ' `delete_at` datetime DEFAULT NULL,' + + ' `headers` text,' + + ' `auth` text,' + + ' `store_id` bigint UNSIGNED DEFAULT NULL,' + + ' `device` varchar(100) DEFAULT NULL COMMENT \'设备\',' + + ' PRIMARY KEY (`id`),' + + ' KEY `store_id` (`store_id`),' + + ' CONSTRAINT `wms_system_log_ibfk_1` FOREIGN KEY (`store_id`)' + + ' REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION' + + ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci' + ); + }, +}; diff --git a/database/migrations/20260928120000-create-wms-org-unit.js b/database/migrations/20260928120000-create-wms-org-unit.js new file mode 100644 index 0000000..79f7174 --- /dev/null +++ b/database/migrations/20260928120000-create-wms-org-unit.js @@ -0,0 +1,153 @@ +'use strict'; + +const TABLE_NAME = 'wms_org_unit'; + +/** + * Migration: create wms_org_unit(组织架构表) + * + * 背景:系统多仓库多主体,各仓库自行维护自己的组织架构(部门/子部门层级), + * 用于工单派发、组级消息推送、入职默认权限等场景。本表与角色表(wms_role) + * 分离:角色管"能做什么",组织架构管"归属哪个组"。 + * + * 字段说明: + * - warehouse_id:所属仓库,多主体数据隔离维度,部门树不允许跨仓挂接。 + * - parent_id:父部门ID,NULL 表示根部门;挂接时必须与 warehouse_id 同仓(服务层校验)。 + * - path:冗余层级路径(如 /1/5/9/),用前缀 LIKE 一次查询整棵子树,避免递归。 + * - leader_id:部门/子部门管理员(关联 wms_account.id),可空。 + * - admin_role_ids:管理员默认角色集(关联 wms_role.id),任命管理员时自动分配。 + * - default_role_ids:部门默认角色集(关联 wms_role.id),成员入职挂本部门时自动分配。 + * - code:部门编码,仓库内唯一(NULL 不参与唯一约束,允许多个未编码部门)。 + * + * 索引:idx_warehouse_parent、idx_parent_id、uk_warehouse_code(唯一)、 + * idx_path、idx_status。 + * + * Idempotent: 表已存在时跳过创建。 + */ + +module.exports = { + /** + * 执行正向迁移:创建组织架构表与索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属仓库ID,关联 wms_store.id', + }, + parent_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '父部门ID,NULL=根部门;必须与 warehouse_id 同仓', + }, + name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '部门名称', + }, + code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '部门编码(仓库内唯一)', + }, + leader_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '部门管理员账号ID,关联 wms_account.id', + }, + admin_role_ids: { + type: Sequelize.JSON, + allowNull: true, + comment: '管理员默认角色集,关联 wms_role.id,如 [3,8];任命管理员时自动分配', + }, + default_role_ids: { + type: Sequelize.JSON, + allowNull: true, + comment: '部门默认角色集,关联 wms_role.id,如 [3,8];成员入职挂本部门时自动分配', + }, + path: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '层级路径,如 /1/5/9/(根部门为 /{id}/),用于一次查询整棵子树', + }, + sort: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '同级排序,越小越靠前', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-停用 1-启用', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 按仓库查部门树(取根 + 挂接校验) + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'parent_id' ], { + name: 'idx_warehouse_parent', + }); + + // 按父部门查子部门 + await queryInterface.addIndex(TABLE_NAME, [ 'parent_id' ], { + name: 'idx_parent_id', + }); + + // 仓库内部门编码唯一 + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'code' ], { + name: 'uk_warehouse_code', + unique: true, + }); + + // 路径前缀查询子树 + await queryInterface.addIndex(TABLE_NAME, [ 'path' ], { + name: 'idx_path', + }); + + // 启用状态过滤 + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { + name: 'idx_status', + }); + }, + + /** + * 执行回滚迁移:删除组织架构表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260929100000-add-callback-functions-to-wms-api-app.js b/database/migrations/20260929100000-add-callback-functions-to-wms-api-app.js new file mode 100644 index 0000000..5bdb94c --- /dev/null +++ b/database/migrations/20260929100000-add-callback-functions-to-wms-api-app.js @@ -0,0 +1,55 @@ +'use strict'; + +/** + * wms_api_app 新增 callback_functions 字段(出站回调 method 路由)。 + * + * 语义:应用承接的出站回调 method 列表(JSON 数组)。 + * 为空/未勾选 = 不承接任何回调;出站回调按 warehouse_id + method 自动路由到 + * 勾选了该 method 的应用,多个应用按 id 升序逐个尝试,全部失败不改配置。 + * + * A 方案存量回填:仓库接口类型(OPEN_API_WAREHOUSE)下启用的应用 + * 默认承接 notify.reply,升级后站内信推送不受影响。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + const { sequelize } = queryInterface; + + // 幂等:列已存在则跳过 + const [ columns ] = await sequelize.query( + "SHOW COLUMNS FROM `wms_api_app` LIKE 'callback_functions'" + ); + if (columns.length === 0) { + await queryInterface.addColumn('wms_api_app', 'callback_functions', { + type: Sequelize.JSON, + allowNull: true, + comment: '承接的出站回调 method 列表(空/未勾选=不承接任何回调;按 method 自动路由)', + }); + } + + // 存量回填:按 interface_code 查仓库接口类型 ID(避免硬编码数字漂移) + const [ interfaceRows ] = await sequelize.query( + "SELECT id FROM wms_interface_type WHERE interface_code = 'OPEN_API_WAREHOUSE' LIMIT 1" + ); + const interfaceTypeId = interfaceRows && interfaceRows.length + ? Number(interfaceRows[0].id) + : 3; + + await sequelize.query( + 'UPDATE wms_api_app SET callback_functions = JSON_ARRAY(\'notify.reply\') ' + + 'WHERE interface_type_id = :interfaceTypeId AND is_enabled = 1 ' + + 'AND (callback_functions IS NULL OR JSON_LENGTH(callback_functions) = 0)', + { replacements: { interfaceTypeId } } + ); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + + const [ columns ] = await sequelize.query( + "SHOW COLUMNS FROM `wms_api_app` LIKE 'callback_functions'" + ); + if (columns.length > 0) { + await queryInterface.removeColumn('wms_api_app', 'callback_functions'); + } + }, +}; diff --git a/database/migrations/20260929100000-create-wms-stock-check.js b/database/migrations/20260929100000-create-wms-stock-check.js new file mode 100644 index 0000000..60d19a9 --- /dev/null +++ b/database/migrations/20260929100000-create-wms-stock-check.js @@ -0,0 +1,147 @@ +'use strict'; + +/** + * 创建库存盘点主表 wms_stock_check。 + * + * 字段:仓库隔离 warehouse_id、盘点单号 check_no(PD+YYYYMMDD+6位序号,唯一)、 + * 盘点名称 title、盘点范围类型 type(all全盘/store按货主/goods按商品/location按库位)、 + * 盘点方式 mode(open明盘/blind盲盘)、货主 store_id、范围条件快照 scope_snapshot(JSON)、 + * 状态 status(pending/in_progress/checked/confirmed/completed/cancelled)、 + * 明细盘点状态 detail_status(none_checked/partial_checked/all_checked)、 + * 盘点日期 check_date、起止时间 start_time/end_time、创建人 creator_id/creator_name、 + * 汇总 total_items/checked_items/diff_items、备注 remark。 + * + * 索引: + * uk_check_no(单号唯一) + * idx_warehouse_check_date(仓库+盘点日期隔离查询) + * idx_warehouse_status(仓库+状态) + * idx_store_id / idx_creator_id + */ + +const TABLE_NAME = 'wms_stock_check'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + check_no: { + type: STRING(50), + allowNull: false, + comment: '盘点单号,唯一,生成规则:PD+YYYYMMDD+6位序号', + }, + title: { + type: STRING(200), + allowNull: true, + comment: '盘点名称/主题,非必填', + }, + type: { + type: STRING(20), + allowNull: false, + defaultValue: 'all', + comment: '盘点范围类型:all=全盘,store=按货主,goods=按商品,location=按库位', + }, + mode: { + type: STRING(20), + allowNull: false, + defaultValue: 'open', + comment: '盘点方式:open=明盘(可见账面数量),blind=盲盘(不可见账面数量)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID,按货主盘点时必填(type=store)', + }, + scope_snapshot: { + type: JSON_TYPE, + allowNull: true, + comment: '盘点范围条件快照(JSON),如商品ID列表/库位ID列表,供盘点对比与追溯', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '盘点状态:pending=待盘点,in_progress=盘点中,checked=已盘待确认,confirmed=已确认,completed=已完成,cancelled=已取消', + }, + detail_status: { + type: STRING(30), + allowNull: false, + defaultValue: 'none_checked', + comment: '明细盘点进度:none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘', + }, + check_date: { + type: DATE, + allowNull: false, + comment: '盘点日期', + }, + start_time: { + type: DATE, + allowNull: true, + comment: '实际开始时间', + }, + end_time: { + type: DATE, + allowNull: true, + comment: '实际结束时间', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人账户ID', + }, + creator_name: { + type: STRING(50), + allowNull: true, + comment: '创建人名称快照', + }, + total_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '明细行数(盘点任务总行数)', + }, + checked_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '已盘行数', + }, + diff_items: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '差异行数(账面与实盘不一致的行数)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'check_no' ], { unique: true, name: 'uk_check_no' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'check_date' ], { name: 'idx_warehouse_check_date' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'status' ], { name: 'idx_warehouse_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: 'idx_store_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'creator_id' ], { name: 'idx_creator_id' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260929101000-create-wms-stock-check-detail.js b/database/migrations/20260929101000-create-wms-stock-check-detail.js new file mode 100644 index 0000000..400d5d1 --- /dev/null +++ b/database/migrations/20260929101000-create-wms-stock-check-detail.js @@ -0,0 +1,143 @@ +'use strict'; + +/** + * 创建库存盘点明细表 wms_stock_check_detail。 + * + * 字段:关联主表 check_id、仓库冗余 warehouse_id、库存商品 stock_id(关联 wms_stock_warehouse.id)、 + * 库位 location_id/location_code(关联 wms_location_space.id + 编码快照)、 + * 商品快照 item_code/item_name/spec、批次号 batch_no、账面数量 system_quantity、 + * 实盘数量 check_quantity(可空=未盘)、差异数量 diff_quantity(=实盘-账面,正盘盈负盘亏)、 + * 差异标记 is_diff、明细状态 status(unchecked/checked/confirmed)、 + * 盘点人 checker_id/checker_name、盘点时间 checked_at、备注 remark。 + * + * 索引: + * idx_check_id(按盘点单查明细,最高频) + * idx_warehouse_stock(仓库+商品) + * idx_stock_id(按商品反查) + * idx_location_id(按库位反查) + * idx_is_diff(差异行筛选) + */ + +const TABLE_NAME = 'wms_stock_check_detail'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, DATE, TINYINT } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + check_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点主表 wms_stock_check.id', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '库存商品ID,关联 wms_stock_warehouse.id', + }, + location_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID,关联 wms_location_space.id;无库位商品为空', + }, + location_code: { + type: STRING(50), + allowNull: true, + comment: '库位编码快照(space_code)', + }, + item_code: { + type: STRING(50), + allowNull: false, + comment: '商品编码快照', + }, + item_name: { + type: STRING(255), + allowNull: true, + comment: '商品名称快照', + }, + spec: { + type: STRING(100), + allowNull: true, + comment: '规格快照(sku_property)', + }, + batch_no: { + type: STRING(100), + allowNull: true, + comment: '批次号,批次管理商品时记录', + }, + system_quantity: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '账面数量(生成盘点任务时的系统库存快照)', + }, + check_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '实盘数量;未盘点时为空', + }, + diff_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '差异数量 = 实盘数量 - 账面数量;正数盘盈,负数盘亏;未盘点时为空', + }, + is_diff: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否有差异:1=有差异,0=无差异', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'unchecked', + comment: '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认', + }, + checker_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '盘点人账户ID', + }, + checker_name: { + type: STRING(50), + allowNull: true, + comment: '盘点人名称快照', + }, + checked_at: { + type: DATE, + allowNull: true, + comment: '盘点时间', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注(如差异原因说明)', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'check_id' ], { name: 'idx_check_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'stock_id' ], { name: 'idx_warehouse_stock' }); + await queryInterface.addIndex(TABLE_NAME, [ 'stock_id' ], { name: 'idx_stock_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'location_id' ], { name: 'idx_location_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'is_diff' ], { name: 'idx_is_diff' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260929110000-align-stock-check-status-machine.js b/database/migrations/20260929110000-align-stock-check-status-machine.js new file mode 100644 index 0000000..952accc --- /dev/null +++ b/database/migrations/20260929110000-align-stock-check-status-machine.js @@ -0,0 +1,43 @@ +'use strict'; + +const CHECK_TABLE_NAME = 'wms_stock_check'; +const DETAIL_TABLE_NAME = 'wms_stock_check_detail'; + +/** + * 库存盘点状态机对齐迁移。 + * 主表 wms_stock_check.status 的 defaultValue 由 'pending' 改为 'created', + * 注释更新为新状态机枚举;detail_status 与明细表 status 的注释同步更新(字段类型不变)。 + */ +module.exports = { + up: async queryInterface => { + // 主表 status:默认值 pending → created,注释更新为新状态机枚举 + await queryInterface.sequelize.query( + `ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'created' COMMENT '盘点状态机:created=已创建(空任务),submitted=待审核,rejected=已驳回,approved=审核完成(待盘点作业),checking=盘点作业中,completed=已完成,cancelled=已取消'` + ); + + // 主表 detail_status:注释同步更新(类型与默认值不变) + await queryInterface.sequelize.query( + `ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`detail_status\` VARCHAR(30) NOT NULL DEFAULT 'none_checked' COMMENT '明细盘点进度(按已盘明细占比自动重算):none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘'` + ); + + // 明细表 status:注释同步更新(类型与默认值不变) + await queryInterface.sequelize.query( + `ALTER TABLE \`${DETAIL_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'unchecked' COMMENT '明细状态:unchecked=未盘,checked=已盘'` + ); + }, + + down: async queryInterface => { + // 回退:恢复旧默认值与旧注释 + await queryInterface.sequelize.query( + `ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '盘点状态:pending=待盘点,in_progress=盘点中,checked=已盘待确认,confirmed=已确认,completed=已完成,cancelled=已取消'` + ); + + await queryInterface.sequelize.query( + `ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`detail_status\` VARCHAR(30) NOT NULL DEFAULT 'none_checked' COMMENT '明细盘点进度:none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘'` + ); + + await queryInterface.sequelize.query( + `ALTER TABLE \`${DETAIL_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'unchecked' COMMENT '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认'` + ); + }, +}; diff --git a/database/migrations/20260929110000-seed-api-app-list-callback-functions-permission.js b/database/migrations/20260929110000-seed-api-app-list-callback-functions-permission.js new file mode 100644 index 0000000..d7a45e7 --- /dev/null +++ b/database/migrations/20260929110000-seed-api-app-list-callback-functions-permission.js @@ -0,0 +1,40 @@ +'use strict'; + +/** + * apiApp.listCallbackFunctions(出站回调 method 注册表拉取)API 权限记录迁移。 + * + * 权限明细(固定 ID 636,当前迁移内最大已用 ID=635): + * 636 — apiApp.listCallbackFunctions API:出站回调方法注册表 + * + * 角色授权:与同组 apiApp 权限(465-470)口径一致——该组权限仅对 + * permissions='*' 的通配角色(超管/经理/仓库管理员)开放, + * 无任何非通配角色持有,因此本迁移仅插入权限记录,不做角色注入。 + * + * 幂等:INSERT IGNORE 创建权限记录。 + */ + +const TABLE = 'wms_permission'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const apis = [ + [ 636, 'apiApp.listCallbackFunctions', 'API:出站回调方法注册表' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 636 AND path = 'apiApp.listCallbackFunctions'` + ); + }, +}; diff --git a/database/migrations/20260929120000-split-stock-check-detail-create-record.js b/database/migrations/20260929120000-split-stock-check-detail-create-record.js new file mode 100644 index 0000000..9fe1150 --- /dev/null +++ b/database/migrations/20260929120000-split-stock-check-detail-create-record.js @@ -0,0 +1,184 @@ +'use strict'; + +/** + * 拆分盘点明细表:明细表只保留盘点商品(stock_id + 商品快照), + * 盘点作业产生的库位/数量信息下沉到新建的 wms_stock_check_record(盘点作业记录表)。 + * + * 变更内容: + * 1. wms_stock_check_detail 移除作业字段: + * location_id / location_code(库位信息) + * check_quantity / diff_quantity / is_diff(实盘数量与差异) + * status / checker_id / checker_name / checked_at(盘点状态与盘点人) + * 2. 新建 wms_stock_check_record(盘点作业记录,一个明细可在多个库位多次上报): + * check_id(关联主表,冗余)、warehouse_id(冗余隔离)、detail_id(关联明细)、 + * stock_id(冗余,商品维度查询)、location_id(space_code 匹配时回填)、 + * location_code(库位编码)、quantity(实盘数量)、checker_id / checker_name、 + * checked_at(上报时间)、remark、created_at / updated_at。 + * + * 索引(wms_stock_check_record): + * idx_check_id(按任务查记录) + * idx_detail_id(按明细查记录) + * idx_stock_id(按商品反查) + * idx_warehouse_location(仓库+库位) + */ + +const DETAIL_TABLE_NAME = 'wms_stock_check_detail'; +const RECORD_TABLE_NAME = 'wms_stock_check_record'; + +/** 明细表需要移除的作业字段 */ +const DROP_COLUMNS = [ + 'location_id', + 'location_code', + 'check_quantity', + 'diff_quantity', + 'is_diff', + 'status', + 'checker_id', + 'checker_name', + 'checked_at', +]; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const { BIGINT, STRING, INTEGER, DATE } = Sequelize; + + // 1) 明细表移除作业字段 + for (const columnName of DROP_COLUMNS) { + await queryInterface.removeColumn(DETAIL_TABLE_NAME, columnName); + } + + // 2) 新建盘点作业记录表 + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === RECORD_TABLE_NAME); + if (!exists) { + await queryInterface.createTable(RECORD_TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + check_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点主表 wms_stock_check.id(冗余,便于按任务查记录)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + detail_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点明细 wms_stock_check_detail.id', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id', + }, + location_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID,关联 wms_location_space.id;库位编码匹配时回填,未匹配为空', + }, + location_code: { + type: STRING(50), + allowNull: true, + comment: '库位编码(盘点上报的库位)', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实盘数量(不小于0的整数)', + }, + checker_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '盘点人账户ID', + }, + checker_name: { + type: STRING(50), + allowNull: true, + comment: '盘点人名称快照', + }, + checked_at: { + type: DATE, + allowNull: true, + comment: '上报时间', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'check_id' ], { name: 'idx_check_id' }); + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'detail_id' ], { name: 'idx_detail_id' }); + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'stock_id' ], { name: 'idx_stock_id' }); + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'warehouse_id', 'location_code' ], { name: 'idx_warehouse_location' }); + } + }, + + down: async (queryInterface, Sequelize) => { + const { BIGINT, STRING, INTEGER, DATE, TINYINT } = Sequelize; + + // 删除记录表 + await queryInterface.dropTable(RECORD_TABLE_NAME); + + // 恢复明细表作业字段 + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'location_id', { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID,关联 wms_location_space.id;无库位商品为空', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'location_code', { + type: STRING(50), + allowNull: true, + comment: '库位编码快照(space_code)', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'check_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '实盘数量;未盘点时为空', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'diff_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '差异数量 = 实盘数量 - 账面数量;正数盘盈,负数盘亏;未盘点时为空', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'is_diff', { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否有差异:1=有差异,0=无差异', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'status', { + type: STRING(20), + allowNull: false, + defaultValue: 'unchecked', + comment: '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'checker_id', { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '盘点人账户ID', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'checker_name', { + type: STRING(50), + allowNull: true, + comment: '盘点人名称快照', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'checked_at', { + type: DATE, + allowNull: true, + comment: '盘点时间', + }); + }, +}; diff --git a/database/migrations/20260929130000-unique-stock-check-record-detail-location.js b/database/migrations/20260929130000-unique-stock-check-record-detail-location.js new file mode 100644 index 0000000..8dd21d7 --- /dev/null +++ b/database/migrations/20260929130000-unique-stock-check-record-detail-location.js @@ -0,0 +1,58 @@ +'use strict'; + +/** + * 盘点作业记录表覆盖式语义加固: + * 1. location_code 归一:NULL → ''(空串表示"无库位"分组,使唯一索引可约束空库位场景)。 + * 2. 合并历史重复记录:同一 (detail_id, location_code) 组保留 id 最大(最新)的一条,其余删除。 + * 3. location_code 改为 NOT NULL DEFAULT ''。 + * 4. 新增唯一索引 uk_detail_location(detail_id, location_code),从数据库层面保证 + * report 覆盖式上报(同明细+同库位更新而非新增)在并发下不产生重复记录。 + */ + +const TABLE_NAME = 'wms_stock_check_record'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING } = Sequelize; + + // 1) NULL → '' + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET location_code = '' WHERE location_code IS NULL` + ); + + // 2) 合并重复:每组保留 id 最大的记录 + await queryInterface.sequelize.query(` + DELETE r1 FROM ${TABLE_NAME} r1 + JOIN ${TABLE_NAME} r2 + ON r1.detail_id = r2.detail_id + AND r1.location_code = r2.location_code + AND r1.id < r2.id + `); + + // 3) 列定义调整 + await queryInterface.changeColumn(TABLE_NAME, 'location_code', { + type: STRING(50), + allowNull: false, + defaultValue: '', + comment: '库位编码(盘点上报的库位,空串表示无库位分组)', + }); + + // 4) 唯一索引(覆盖式语义的数据库层保证) + await queryInterface.addIndex(TABLE_NAME, [ 'detail_id', 'location_code' ], { + unique: true, + name: 'uk_detail_location', + }); + }, + + down: async (queryInterface, Sequelize) => { + const { STRING } = Sequelize; + + await queryInterface.removeIndex(TABLE_NAME, 'uk_detail_location'); + await queryInterface.changeColumn(TABLE_NAME, 'location_code', { + type: STRING(50), + allowNull: true, + defaultValue: null, + comment: '库位编码(盘点上报的库位)', + }); + }, +}; diff --git a/database/migrations/20260929150000-add-pick-recheck-requirements-and-three-in-one-switch.js b/database/migrations/20260929150000-add-pick-recheck-requirements-and-three-in-one-switch.js new file mode 100644 index 0000000..c6f1621 --- /dev/null +++ b/database/migrations/20260929150000-add-pick-recheck-requirements-and-three-in-one-switch.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_stock_warehouse', 'pick_recheck_requirements', { + type: Sequelize.TEXT, + allowNull: true, + comment: '拣货眼球复核要求', + after: 'packing_requirements', + }); + await queryInterface.addColumn('wms_stock_warehouse', 'three_in_one_switch', { + type: Sequelize.CHAR(1), + allowNull: false, + defaultValue: 'Y', + comment: '三合一开关:Y=开启,N=关闭', + after: 'pick_recheck_requirements', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_stock_warehouse', 'three_in_one_switch'); + await queryInterface.removeColumn('wms_stock_warehouse', 'pick_recheck_requirements'); + }, +}; diff --git a/database/migrations/20260929160000-split-pick-recheck-requirements.js b/database/migrations/20260929160000-split-pick-recheck-requirements.js new file mode 100644 index 0000000..6888ea4 --- /dev/null +++ b/database/migrations/20260929160000-split-pick-recheck-requirements.js @@ -0,0 +1,30 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_stock_warehouse', 'pick_requirements', { + type: Sequelize.TEXT, + allowNull: true, + comment: '拣货要求', + after: 'packing_requirements', + }); + await queryInterface.addColumn('wms_stock_warehouse', 'recheck_requirements', { + type: Sequelize.TEXT, + allowNull: true, + comment: '眼球复核要求', + after: 'pick_requirements', + }); + await queryInterface.removeColumn('wms_stock_warehouse', 'pick_recheck_requirements'); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_stock_warehouse', 'pick_recheck_requirements', { + type: Sequelize.TEXT, + allowNull: true, + comment: '拣货眼球复核要求', + after: 'packing_requirements', + }); + await queryInterface.removeColumn('wms_stock_warehouse', 'recheck_requirements'); + await queryInterface.removeColumn('wms_stock_warehouse', 'pick_requirements'); + }, +}; diff --git a/database/migrations/20260929170000-rename-three-in-one-switch-to-merge-requirements.js b/database/migrations/20260929170000-rename-three-in-one-switch-to-merge-requirements.js new file mode 100644 index 0000000..1787cb1 --- /dev/null +++ b/database/migrations/20260929170000-rename-three-in-one-switch-to-merge-requirements.js @@ -0,0 +1,40 @@ +'use strict'; + +const TABLE_NAME = 'wms_stock_warehouse'; +const OLD_COLUMN = 'three_in_one_switch'; +const NEW_COLUMN = 'merge_requirements'; + +/** + * 将 three_in_one_switch 重命名为 merge_requirements(要求是否合并)。 + * 语义:Y=合并(拣货/复核要求统一输出打包要求),N=不合并,默认 Y。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!Object.prototype.hasOwnProperty.call(columns, OLD_COLUMN)) { + // 旧列不存在,视为已执行(幂等) + return; + } + await queryInterface.renameColumn(TABLE_NAME, OLD_COLUMN, NEW_COLUMN); + await queryInterface.changeColumn(TABLE_NAME, NEW_COLUMN, { + type: Sequelize.CHAR(1), + allowNull: false, + defaultValue: 'Y', + comment: '要求是否合并:Y=合并(拣货/复核要求统一输出打包要求),N=不合并', + }); + }, + + down: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!Object.prototype.hasOwnProperty.call(columns, NEW_COLUMN)) { + return; + } + await queryInterface.renameColumn(TABLE_NAME, NEW_COLUMN, OLD_COLUMN); + await queryInterface.changeColumn(TABLE_NAME, OLD_COLUMN, { + type: Sequelize.CHAR(1), + allowNull: false, + defaultValue: 'Y', + comment: '三合一开关:Y=开启,N=关闭', + }); + }, +}; diff --git a/database/migrations/20260930100000-add-packages-weight-to-wms-order-delivery.js b/database/migrations/20260930100000-add-packages-weight-to-wms-order-delivery.js new file mode 100644 index 0000000..403be58 --- /dev/null +++ b/database/migrations/20260930100000-add-packages-weight-to-wms-order-delivery.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_order_delivery', 'packages_weight', { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '所有包裹总重量(g)', + after: 'items_weight', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_order_delivery', 'packages_weight'); + }, +}; diff --git a/database/migrations/20260930110000-add-warning-quantity-to-wms-stock-warehouse.js b/database/migrations/20260930110000-add-warning-quantity-to-wms-stock-warehouse.js new file mode 100644 index 0000000..84e5cb1 --- /dev/null +++ b/database/migrations/20260930110000-add-warning-quantity-to-wms-stock-warehouse.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_stock_warehouse', 'warning_quantity', { + type: Sequelize.INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '库存预警数量', + after: 'locked_quantity', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_stock_warehouse', 'warning_quantity'); + }, +}; diff --git a/database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js b/database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js new file mode 100644 index 0000000..cbe0979 --- /dev/null +++ b/database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js @@ -0,0 +1,131 @@ +'use strict'; + +/** + * 库存盘点范围类型改造:盘点明细表支持「商品」与「库位」两种盘点范围行。 + * 注:原计划时间戳 20260930100000 已被 add-packages-weight-to-wms-order-delivery 占用, + * 故本迁移使用 20260930110000 保证确定性排序。 + * + * wms_stock_check_detail: + * 1. 新增 scope_type(盘点范围类型:goods=商品,location=库位)。 + * 2. stock_id / item_code 改为可空(库位行无商品快照)。 + * 3. 重新引入 location_id / location_code(库位行专用;商品行为空)。 + * 4. 更新表注释。 + * 5. 防御性合并历史重复明细(同 check_id+stock_id 保留 id 最大行,旧行作业记录重指向保留行)。 + * 6. 新增唯一索引 uk_check_stock(check_id, stock_id) 与 uk_check_location(check_id, location_code) + * (MySQL 唯一索引允许多个 NULL:商品行 location_code=NULL、库位行 stock_id=NULL 互不干扰)。 + * + * wms_stock_check_record: + * 1. 移除唯一索引 uk_detail_location(detail_id, location_code)。 + * 2. 防御性合并重复(同 detail_id+stock_id+location_code 组保留 id 最大一条,raw SQL)。 + * 3. 新增唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code)。 + * 原因:按库位盘点时同一库位明细行下会有多个商品的记录, + * 覆盖式语义应升级为「同明细 + 同商品 + 同库位」。 + */ + +const DETAIL_TABLE_NAME = 'wms_stock_check_detail'; +const RECORD_TABLE_NAME = 'wms_stock_check_record'; + +module.exports = { + up: async queryInterface => { + // ===== wms_stock_check_detail ===== + + // 1) 新增字段(raw SQL 保证列位置与注释精确) + await queryInterface.sequelize.query(` + ALTER TABLE \`${DETAIL_TABLE_NAME}\` + ADD COLUMN \`scope_type\` VARCHAR(20) NOT NULL DEFAULT 'goods' COMMENT '盘点范围类型:goods=商品,location=库位' AFTER \`warehouse_id\`, + ADD COLUMN \`location_id\` BIGINT(20) UNSIGNED NULL COMMENT '库位ID,关联 wms_location_space.id;库位盘点行为空' AFTER \`stock_id\`, + ADD COLUMN \`location_code\` VARCHAR(50) NULL COMMENT '库位编码(space_code);库位盘点行为空' AFTER \`location_id\` + `); + + // 2) stock_id / item_code 改为可空 + await queryInterface.sequelize.query(` + ALTER TABLE \`${DETAIL_TABLE_NAME}\` + MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NULL COMMENT '库存商品ID,关联 wms_stock_warehouse.id;库位盘点行为空', + MODIFY COLUMN \`item_code\` VARCHAR(50) NULL COMMENT '商品编码快照;库位盘点行为空' + `); + + // 3) 更新表注释 + await queryInterface.sequelize.query( + `ALTER TABLE \`${DETAIL_TABLE_NAME}\` COMMENT='库存盘点明细表(盘点范围行:商品或库位)'` + ); + + // 4) 防御性合并重复明细:同 (check_id, stock_id) 保留 id 最大行,旧行的作业记录重指向保留行 + await queryInterface.sequelize.query(` + UPDATE \`${RECORD_TABLE_NAME}\` r + JOIN \`${DETAIL_TABLE_NAME}\` d ON r.detail_id = d.id + JOIN ( + SELECT check_id, stock_id, MAX(id) AS keep_id + FROM \`${DETAIL_TABLE_NAME}\` + WHERE stock_id IS NOT NULL + GROUP BY check_id, stock_id + HAVING COUNT(*) > 1 + ) g ON g.check_id = d.check_id AND g.stock_id = d.stock_id AND d.id <> g.keep_id + SET r.detail_id = g.keep_id + `); + await queryInterface.sequelize.query(` + DELETE d FROM \`${DETAIL_TABLE_NAME}\` d + JOIN ( + SELECT check_id, stock_id, MAX(id) AS keep_id + FROM \`${DETAIL_TABLE_NAME}\` + WHERE stock_id IS NOT NULL + GROUP BY check_id, stock_id + HAVING COUNT(*) > 1 + ) g ON g.check_id = d.check_id AND g.stock_id = d.stock_id AND d.id < g.keep_id + `); + + // 5) 新增唯一索引 + await queryInterface.addIndex(DETAIL_TABLE_NAME, [ 'check_id', 'stock_id' ], { + unique: true, + name: 'uk_check_stock', + }); + await queryInterface.addIndex(DETAIL_TABLE_NAME, [ 'check_id', 'location_code' ], { + unique: true, + name: 'uk_check_location', + }); + + // ===== wms_stock_check_record ===== + + // 1) 移除旧唯一索引 uk_detail_location + await queryInterface.removeIndex(RECORD_TABLE_NAME, 'uk_detail_location'); + + // 2) 合并重复:同 (detail_id, stock_id, location_code) 组保留 id 最大一条 + await queryInterface.sequelize.query(` + DELETE r1 FROM \`${RECORD_TABLE_NAME}\` r1 + JOIN \`${RECORD_TABLE_NAME}\` r2 + ON r1.detail_id = r2.detail_id + AND r1.stock_id = r2.stock_id + AND r1.location_code = r2.location_code + AND r1.id < r2.id + `); + + // 3) 新增唯一索引 uk_detail_stock_location + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'detail_id', 'stock_id', 'location_code' ], { + unique: true, + name: 'uk_detail_stock_location', + }); + }, + + down: async queryInterface => { + // 回退 wms_stock_check_record + await queryInterface.removeIndex(RECORD_TABLE_NAME, 'uk_detail_stock_location'); + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'detail_id', 'location_code' ], { + unique: true, + name: 'uk_detail_location', + }); + + // 回退 wms_stock_check_detail + await queryInterface.removeIndex(DETAIL_TABLE_NAME, 'uk_check_location'); + await queryInterface.removeIndex(DETAIL_TABLE_NAME, 'uk_check_stock'); + await queryInterface.sequelize.query( + `ALTER TABLE \`${DETAIL_TABLE_NAME}\` COMMENT='库存盘点明细表(盘点商品清单)'` + ); + await queryInterface.removeColumn(DETAIL_TABLE_NAME, 'location_code'); + await queryInterface.removeColumn(DETAIL_TABLE_NAME, 'location_id'); + await queryInterface.removeColumn(DETAIL_TABLE_NAME, 'scope_type'); + await queryInterface.sequelize.query(` + ALTER TABLE \`${DETAIL_TABLE_NAME}\` + MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NOT NULL COMMENT '库存商品ID,关联 wms_stock_warehouse.id', + MODIFY COLUMN \`item_code\` VARCHAR(50) NOT NULL COMMENT '商品编码快照' + `); + }, +}; diff --git a/database/migrations/20260930120000-add-index-wh-type-stock-time-to-wms-stock-transaction.js b/database/migrations/20260930120000-add-index-wh-type-stock-time-to-wms-stock-transaction.js new file mode 100644 index 0000000..d0a67d7 --- /dev/null +++ b/database/migrations/20260930120000-add-index-wh-type-stock-time-to-wms-stock-transaction.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 静态商品查询优化:覆盖索引,支撑 warehouse_id + transaction_type 过滤、stock_id 分组、created_at 取 MAX + await queryInterface.addIndex( + 'wms_stock_transaction', + [ 'warehouse_id', 'transaction_type', 'stock_id', 'created_at' ], + { name: 'idx_wh_type_stock_time' } + ); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('wms_stock_transaction', 'idx_wh_type_stock_time'); + }, +}; diff --git a/database/migrations/20260930130000-create-wms-stock-static-notice.js b/database/migrations/20260930130000-create-wms-stock-static-notice.js new file mode 100644 index 0000000..c116334 --- /dev/null +++ b/database/migrations/20260930130000-create-wms-stock-static-notice.js @@ -0,0 +1,63 @@ +'use strict'; + +const TABLE_NAME = 'wms_stock_static_notice'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + stock_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品ID,关联 wms_stock_warehouse.id', + }, + notice_time: { + type: Sequelize.DATE, + allowNull: false, + comment: '通知时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '静态商品通知关联表(记录静态商品已通知时间,避免重复通知)', + }); + + // 核心查询:查某商品最近一次通知时间 + await queryInterface.addIndex(TABLE_NAME, [ 'stock_id', 'notice_time' ], { + name: 'idx_stock_notice_time', + }); + // 时间范围扫描:按通知时间清理/统计 + await queryInterface.addIndex(TABLE_NAME, [ 'notice_time' ], { + name: 'idx_notice_time', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260930140000-create-wms-stock-static-check-task.js b/database/migrations/20260930140000-create-wms-stock-static-check-task.js new file mode 100644 index 0000000..8393461 --- /dev/null +++ b/database/migrations/20260930140000-create-wms-stock-static-check-task.js @@ -0,0 +1,63 @@ +'use strict'; + +const TABLE_NAME = 'wms_stock_static_check_task'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + stock_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品ID,关联 wms_stock_warehouse.id', + }, + task_time: { + type: Sequelize.DATE, + allowNull: false, + comment: '创建盘点任务时间(有记录即表示已为该静态商品创建过盘点任务)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '静态商品盘点任务关联表(记录是否已为静态商品创建盘点任务,避免重复创建)', + }); + + // 核心查询:查某商品最近一次创建盘点任务时间 + await queryInterface.addIndex(TABLE_NAME, [ 'stock_id', 'task_time' ], { + name: 'idx_stock_task_time', + }); + // 时间范围扫描:按任务创建时间清理/统计 + await queryInterface.addIndex(TABLE_NAME, [ 'task_time' ], { + name: 'idx_task_time', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js b/database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js new file mode 100644 index 0000000..aba1d95 --- /dev/null +++ b/database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js @@ -0,0 +1,56 @@ +'use strict'; + +/** + * 盘点主表时间字段调整: + * 1. 移除盘点日期 check_date(及其联合索引 idx_warehouse_check_date)—— + * 创建任务不再传盘点时间,盘点时间线由 start_time/end_time 表达。 + * 2. start_time(盘点开始时间:第一个盘点明细写入时间)与 + * end_time(盘点结束时间:完成盘点时间)注释对齐新语义,类型不变。 + */ + +const TABLE_NAME = 'wms_stock_check'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const { DATE } = Sequelize; + + // 先删索引再删列 + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_check_date'); + await queryInterface.removeColumn(TABLE_NAME, 'check_date'); + + await queryInterface.changeColumn(TABLE_NAME, 'start_time', { + type: DATE, + allowNull: true, + comment: '盘点开始时间(第一个盘点明细写入的时间)', + }); + await queryInterface.changeColumn(TABLE_NAME, 'end_time', { + type: DATE, + allowNull: true, + comment: '盘点结束时间(完成盘点的时间)', + }); + }, + + down: async (queryInterface, Sequelize) => { + const { DATE } = Sequelize; + + await queryInterface.addColumn(TABLE_NAME, 'check_date', { + type: DATE, + allowNull: false, + comment: '盘点日期', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'check_date' ], { + name: 'idx_warehouse_check_date', + }); + + await queryInterface.changeColumn(TABLE_NAME, 'start_time', { + type: DATE, + allowNull: true, + comment: '实际开始时间', + }); + await queryInterface.changeColumn(TABLE_NAME, 'end_time', { + type: DATE, + allowNull: true, + comment: '实际结束时间', + }); + }, +}; diff --git a/database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js b/database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js new file mode 100644 index 0000000..10f8557 --- /dev/null +++ b/database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js @@ -0,0 +1,40 @@ +'use strict'; + +/** + * 库存盘点作业记录表支持未知商品(仿收货明细口径:stock_id 可空 + barcode + item_name): + * + * wms_stock_check_record: + * 1. stock_id 改为可空(NULL=未知商品;唯一索引 uk_detail_stock_location 中 NULL 不参与唯一约束, + * MySQL 语义允许多个 NULL 行,索引保持不动)。 + * 2. 新增 barcode(扫描到的条码/编码,STRING(100) 可空,已知商品可为空)。 + * 3. 新增 item_name(未知商品名称快照,缺省为条码,STRING(255) 可空,已知商品为空)。 + * + * 未知商品无账面:盘点差异 = 实盘数量 - 0 = 盘盈; + * 覆盖式查重由应用层按(detail_id + stock_id IS NULL + barcode + location_code)保证。 + */ + +const TABLE_NAME = 'wms_stock_check_record'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NULL COMMENT '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id;NULL=未知商品', + ADD COLUMN \`barcode\` VARCHAR(100) NULL COMMENT '扫描到的条码/编码(未知商品上报使用;已知商品可为空)' AFTER \`stock_id\`, + ADD COLUMN \`item_name\` VARCHAR(255) NULL COMMENT '未知商品名称快照(缺省为条码);已知商品为空' AFTER \`barcode\` + `); + }, + + down: async queryInterface => { + // 回退前先清理未知商品记录(stock_id 为 NULL 的行),保证恢复 NOT NULL 不失败 + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE_NAME}\` WHERE \`stock_id\` IS NULL` + ); + await queryInterface.removeColumn(TABLE_NAME, 'item_name'); + await queryInterface.removeColumn(TABLE_NAME, 'barcode'); + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NOT NULL COMMENT '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id' + `); + }, +}; diff --git a/database/migrations/20261002160000-add-is-empty-to-stock-check-record.js b/database/migrations/20261002160000-add-is-empty-to-stock-check-record.js new file mode 100644 index 0000000..2f89189 --- /dev/null +++ b/database/migrations/20261002160000-add-is-empty-to-stock-check-record.js @@ -0,0 +1,25 @@ +'use strict'; + +/** + * 库存盘点作业记录表支持空库位标记(库位盘点模式:确认库位为空时上报一条特殊记录): + * + * wms_stock_check_record 新增 is_empty(TINYINT(1) NOT NULL DEFAULT 0): + * - is_empty=1 的记录表示「确认该库位为空」:stock_id=NULL、barcode=NULL、item_name=NULL、quantity=0; + * - 与商品记录互斥(应用层保证):标记空时删除该明细下商品记录;上报商品时删除该明细下空记录; + * - 空记录按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新(唯一索引不约束 NULL 行)。 + */ + +const TABLE_NAME = 'wms_stock_check_record'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + ADD COLUMN \`is_empty\` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否空库位标记(1=确认为空,stock_id/barcode/item_name 均为空、quantity=0)' AFTER \`item_name\` + `); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'is_empty'); + }, +}; diff --git a/database/migrations/20261002170000-split-goods-detail-by-location.js b/database/migrations/20261002170000-split-goods-detail-by-location.js new file mode 100644 index 0000000..312df2f --- /dev/null +++ b/database/migrations/20261002170000-split-goods-detail-by-location.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * 商品盘点明细按「商品 + 库位」拆行(商品任务必须按库位盘点): + * + * wms_stock_check_detail: + * 1. 唯一索引 uk_check_stock(check_id, stock_id) 变更为 uk_check_stock_location(check_id, stock_id, location_id), + * 允许同一商品在该任务下按多个库存库位拆成多行(location_id 均为 NULL 的旧行不受唯一约束,MySQL NULL 语义)。 + * 2. 唯一索引 uk_check_location(check_id, location_code) 放宽为普通索引 idx_check_location: + * 商品拆行后同一任务同一库位可能对应多个商品行(location_code 相同),唯一约束不再成立; + * 库位明细行(scope_type=location)幂等由应用层查重保证。 + * 3. 商品明细行(scope_type=goods)将写入其库存库位快照(location_id/location_code/system_quantity=该库位账面), + * 应用层保证同商品重复添加整体跳过(幂等口径不变)。 + */ + +const TABLE_NAME = 'wms_stock_check_detail'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + DROP INDEX \`uk_check_stock\`, + DROP INDEX \`uk_check_location\`, + ADD UNIQUE INDEX \`uk_check_stock_location\` (\`check_id\`, \`stock_id\`, \`location_id\`), + ADD INDEX \`idx_check_location\` (\`check_id\`, \`location_code\`) + `); + }, + + down: async queryInterface => { + // 回退前清理同 (check_id, stock_id) 的多行重复(保留最小 id),保证恢复唯一索引不失败; + // 同任务同库位的多商品行(拆行产生)一并清理(保留最小 id),恢复 uk_check_location 不失败 + await queryInterface.sequelize.query(` + DELETE d1 FROM \`${TABLE_NAME}\` d1 + INNER JOIN \`${TABLE_NAME}\` d2 + ON d1.check_id = d2.check_id + AND ((d1.stock_id = d2.stock_id) OR (d1.location_code = d2.location_code)) + AND d1.id > d2.id + `); + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + DROP INDEX \`uk_check_stock_location\`, + DROP INDEX \`idx_check_location\`, + ADD UNIQUE INDEX \`uk_check_stock\` (\`check_id\`, \`stock_id\`), + ADD UNIQUE INDEX \`uk_check_location\` (\`check_id\`, \`location_code\`) + `); + }, +}; diff --git a/database/migrations/20261005100000-create-wms-receiving-task.js b/database/migrations/20261005100000-create-wms-receiving-task.js new file mode 100644 index 0000000..6fec28d --- /dev/null +++ b/database/migrations/20261005100000-create-wms-receiving-task.js @@ -0,0 +1,69 @@ +'use strict'; + +/** + * 创建收件任务表 wms_receiving_task。 + * + * 字段:批次号 batch_no、仓库ID warehouse_id(数据隔离维度)、 + * 创建人 creator_id/creator_name、创建时间 created_at。 + * 主键 id 自增从 10000 开始(建表后设置 AUTO_INCREMENT = 10000)。 + * + * 索引: + * idx_warehouse_id(按仓库查询) + * idx_batch_no(按批次号查询) + * idx_creator_id(按创建人查询) + */ + +const TABLE_NAME = 'wms_receiving_task'; +const AUTO_INCREMENT_START = 10000; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID(自增从10000开始)', + }, + batch_no: { + type: STRING(50), + allowNull: false, + comment: '批次号', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人账户ID', + }, + creator_name: { + type: STRING(50), + allowNull: true, + comment: '创建人名称快照', + }, + created_at: { type: DATE, allowNull: false, comment: '创建时间' }, + updated_at: { type: DATE, allowNull: false, comment: '更新时间' }, + }); + + // 自增ID从 10000 开始 + await queryInterface.sequelize.query( + `ALTER TABLE ${TABLE_NAME} AUTO_INCREMENT = ${AUTO_INCREMENT_START}` + ); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'batch_no' ], { name: 'idx_batch_no' }); + await queryInterface.addIndex(TABLE_NAME, [ 'creator_id' ], { name: 'idx_creator_id' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20261005110000-add-title-and-seed-history-receiving-task.js b/database/migrations/20261005110000-add-title-and-seed-history-receiving-task.js new file mode 100644 index 0000000..c5eb983 --- /dev/null +++ b/database/migrations/20261005110000-add-title-and-seed-history-receiving-task.js @@ -0,0 +1,48 @@ +'use strict'; + +/** + * 收件任务表补「标题」字段,并播种系统预设行(幂等)。 + * + * - addColumn title(标题,NOT NULL 默认空串) + * - 幂等插入系统预设:id=1、warehouse_id=0、title='历史收件', + * 用于处理历史(旧流程)收货任务;batch_no 同步填 '历史收件',creator_id=0(系统)。 + * + * 显式插入 id=1 不会影响 AUTO_INCREMENT=10000 的水位(1 < 10000)。 + */ + +const TABLE_NAME = 'wms_receiving_task'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { STRING } = Sequelize; + + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (!tableInfo.title) { + await queryInterface.addColumn(TABLE_NAME, 'title', { + type: STRING(100), + allowNull: false, + defaultValue: '', + comment: '标题(任务名称,如系统预设「历史收件」)', + }); + } + + const { sequelize } = queryInterface; + const [ rows ] = await sequelize.query( + 'SELECT id FROM `' + TABLE_NAME + '` WHERE id = 1 LIMIT 1' + ); + if (!rows || rows.length === 0) { + await sequelize.query( + 'INSERT INTO `' + TABLE_NAME + '` (id, batch_no, warehouse_id, creator_id, creator_name, title, created_at, updated_at) VALUES (1, :b, 0, 0, :c, :t, NOW(), NOW())', + { replacements: { b: '历史收件', c: '系统', t: '历史收件' } } + ); + } + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + await sequelize.query( + 'DELETE FROM `' + TABLE_NAME + '` WHERE id = 1 AND warehouse_id = 0' + ); + await queryInterface.removeColumn(TABLE_NAME, 'title'); + }, +}; diff --git a/database/migrations/20261005120000-add-receiving-task-id-to-wms-return-received.js b/database/migrations/20261005120000-add-receiving-task-id-to-wms-return-received.js new file mode 100644 index 0000000..835c7d6 --- /dev/null +++ b/database/migrations/20261005120000-add-receiving-task-id-to-wms-return-received.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * 收件登记表 wms_return_received 增加收件任务ID。 + * + * - addColumn receiving_task_id(BIGINT UNSIGNED NOT NULL DEFAULT 1,关联 wms_receiving_task.id) + * - 回填:所有现有行 receiving_task_id 统一更新为 1(即系统预设「历史收件」任务) + * - 索引 idx_receiving_task_id(按收件任务查询) + */ + +const TABLE_NAME = 'wms_return_received'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT } = Sequelize; + + const tableInfo = await queryInterface.describeTable(TABLE_NAME); + if (!tableInfo.receiving_task_id) { + await queryInterface.addColumn(TABLE_NAME, 'receiving_task_id', { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '收件任务ID,关联 wms_receiving_task.id;默认 1=系统预设「历史收件」', + }); + } + + // 显式回填:所有现有行统一为 1(系统预设「历史收件」任务) + await queryInterface.sequelize.query( + 'UPDATE `' + TABLE_NAME + '` SET receiving_task_id = 1 WHERE receiving_task_id IS NULL OR receiving_task_id = 0' + ); + + const indexes = await queryInterface.showIndex(TABLE_NAME); + const hasIndex = (indexes || []).some(i => i.name === 'idx_receiving_task_id'); + if (!hasIndex) { + await queryInterface.addIndex(TABLE_NAME, [ 'receiving_task_id' ], { name: 'idx_receiving_task_id' }); + } + }, + + async down(queryInterface) { + const indexes = await queryInterface.showIndex(TABLE_NAME); + const hasIndex = (indexes || []).some(i => i.name === 'idx_receiving_task_id'); + if (hasIndex) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_receiving_task_id'); + } + await queryInterface.removeColumn(TABLE_NAME, 'receiving_task_id'); + }, +}; diff --git a/database/migrations/20261005150000-rename-receiving-task-to-return-received-task.js b/database/migrations/20261005150000-rename-receiving-task-to-return-received-task.js new file mode 100644 index 0000000..0cd43d4 --- /dev/null +++ b/database/migrations/20261005150000-rename-receiving-task-to-return-received-task.js @@ -0,0 +1,78 @@ +'use strict'; + +/** + * 收件任务表与关联字段改名(对齐 return_received 退回收件命名体系)。 + * + * - 表 wms_receiving_task 重命名为 wms_return_received_task + * - wms_return_received.receiving_task_id 列改名为 return_received_task_id + * - 索引 idx_receiving_task_id 改名为 idx_return_received_task_id + * + * 说明:仅改名,不改数据类型/默认值/数据;列改名后索引保留,先删旧索引再 + * CHANGE COLUMN 再重建新索引,保证索引名与列名一致。 + */ + +const TASK_TABLE_OLD = 'wms_receiving_task'; +const TASK_TABLE_NEW = 'wms_return_received_task'; +const REGISTER_TABLE = 'wms_return_received'; +const COLUMN_OLD = 'receiving_task_id'; +const COLUMN_NEW = 'return_received_task_id'; +const INDEX_OLD = 'idx_receiving_task_id'; +const INDEX_NEW = 'idx_return_received_task_id'; + +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + + // 1. 表重命名 + await sequelize.query( + `RENAME TABLE \`${TASK_TABLE_OLD}\` TO \`${TASK_TABLE_NEW}\`` + ); + + // 2. 登记表列改名(先删旧索引,CHANGE COLUMN 后重建新索引) + const indexes = await queryInterface.showIndex(REGISTER_TABLE); + const hasOldIndex = (indexes || []).some(i => i.name === INDEX_OLD); + if (hasOldIndex) { + await queryInterface.removeIndex(REGISTER_TABLE, INDEX_OLD); + } + + const tableInfo = await queryInterface.describeTable(REGISTER_TABLE); + if (tableInfo[COLUMN_OLD]) { + await sequelize.query( + `ALTER TABLE \`${REGISTER_TABLE}\` CHANGE COLUMN \`${COLUMN_OLD}\` \`${COLUMN_NEW}\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 1 COMMENT '收件任务ID,关联 wms_return_received_task.id;默认 1=系统预设「历史收件」'` + ); + } + + const indexesAfter = await queryInterface.showIndex(REGISTER_TABLE); + const hasNewIndex = (indexesAfter || []).some(i => i.name === INDEX_NEW); + if (!hasNewIndex) { + await queryInterface.addIndex(REGISTER_TABLE, [ COLUMN_NEW ], { name: INDEX_NEW }); + } + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + + const indexes = await queryInterface.showIndex(REGISTER_TABLE); + const hasNewIndex = (indexes || []).some(i => i.name === INDEX_NEW); + if (hasNewIndex) { + await queryInterface.removeIndex(REGISTER_TABLE, INDEX_NEW); + } + + const tableInfo = await queryInterface.describeTable(REGISTER_TABLE); + if (tableInfo[COLUMN_NEW]) { + await sequelize.query( + `ALTER TABLE \`${REGISTER_TABLE}\` CHANGE COLUMN \`${COLUMN_NEW}\` \`${COLUMN_OLD}\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 1 COMMENT '收件任务ID,关联 wms_receiving_task.id;默认 1=系统预设「历史收件」'` + ); + } + + const indexesAfter = await queryInterface.showIndex(REGISTER_TABLE); + const hasOldIndex = (indexesAfter || []).some(i => i.name === INDEX_OLD); + if (!hasOldIndex) { + await queryInterface.addIndex(REGISTER_TABLE, [ COLUMN_OLD ], { name: INDEX_OLD }); + } + + await sequelize.query( + `RENAME TABLE \`${TASK_TABLE_NEW}\` TO \`${TASK_TABLE_OLD}\`` + ); + }, +}; diff --git a/database/migrations/20261005160000-add-return-record-page-permission.js b/database/migrations/20261005160000-add-return-record-page-permission.js new file mode 100644 index 0000000..63e7ec1 --- /dev/null +++ b/database/migrations/20261005160000-add-return-record-page-permission.js @@ -0,0 +1,82 @@ +'use strict'; + +/** + * 数据菜单下新增 web_pages 子菜单「退件记录」(id=640),并授权客服员工及以上角色。 + * + * 权限明细: + * 640 — ReturnRecord(web_pages 菜单,parent_id=16 数据) + * + * 角色授权(系统预设角色,不含通配符角色): + * 640 → 客服组-员工(30) → 客服组-主管(28)(客服员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建菜单权限;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 640: [ 30, 28 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 web_pages 菜单权限(固定 ID,parent_id=16 数据)── + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ 640, 'ReturnRecord', '@/views/data/returnrecord/index', 'ReturnRecord', null, '退件记录', null, 0, 0, 16, 'web_pages', 1, 1 ] } + ); + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 640` + ); + }, +}; diff --git a/database/migrations/20261005160000-remove-return-pages-from-permission.js b/database/migrations/20261005160000-remove-return-pages-from-permission.js new file mode 100644 index 0000000..e6996cf --- /dev/null +++ b/database/migrations/20261005160000-remove-return-pages-from-permission.js @@ -0,0 +1,64 @@ +'use strict'; + +/** + * 移除 returnwaybill / returnReceived / returnUnpack 前端页面权限。 + * + * - wms_permission:删除 web_pages 类型页面记录 530(returnReceived)、 + * 550(returnUnpack)、556(returnwaybill) + * - wms_role:从所有非通配符角色的 permissions 数组中移除这三个 id + * (通配符角色 permissions='*' 自动拥有所有权限,无需处理) + * + * 注意:仅移除前端页面权限,API 权限(returnReceived.create 等 type=api)保留。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const PAGE_PERMISSION_IDS = [ 530, 550, 556 ]; + +module.exports = { + async up(queryInterface) { + // ── 1. 删除 web_pages 页面权限记录 ── + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE type = 'web_pages' AND id IN (:ids)`, + { replacements: { ids: PAGE_PERMISSION_IDS } } + ); + + // ── 2. 从非通配符角色 permissions 数组中移除 ── + const roles = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE permissions IS NOT NULL AND permissions <> '' AND permissions <> '*'`, + { type: queryInterface.sequelize.QueryTypes.SELECT } + ); + + for (const role of roles) { + let perms; + try { + perms = JSON.parse(role.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + const filtered = perms.filter(id => !PAGE_PERMISSION_IDS.includes(Number(id))); + if (filtered.length === perms.length) { + continue; + } + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(filtered), role.id ] } + ); + } + }, + + async down(queryInterface) { + // 恢复页面权限记录(角色数组不做恢复,回滚由后续授权迁移补充) + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) VALUES + (530, 'returnReceived', '@/views/express/returnReceived/index', 'returnReceived', NULL, '快递收件', NULL, 0, 0, 19, 'web_pages', 1, 1, NOW(), NOW()), + (550, 'returnUnpack', '@/views/express/returnUnpack/index', 'returnUnpack', NULL, '快递拆包', NULL, 0, 0, 19, 'web_pages', 1, 1, NOW(), NOW()), + (556, 'returnwaybill', '@/views/express/returnwaybill/index', 'returnwaybill', NULL, '运单退回', NULL, 0, 0, 19, 'web_pages', 1, 1, NOW(), NOW())` + ); + }, +}; diff --git a/database/migrations/20261005170000-rename-return-waybill-permission-title.js b/database/migrations/20261005170000-rename-return-waybill-permission-title.js new file mode 100644 index 0000000..a4a412e --- /dev/null +++ b/database/migrations/20261005170000-rename-return-waybill-permission-title.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * 权限名称修正:「运单退回登记」→「未退登记」。 + * + * 仅改 API 权限显示名称(meta_title),path/name(方法路由)保持不变: + * 551 — API:未退登记 + * 552 — API:未退登记修改 + * 553 — API:未退登记列表 + * 554 — API:未退登记详情 + * 555 — API:未退登记删除 + */ + +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + 'UPDATE `wms_permission` SET meta_title = REPLACE(meta_title, :oldName, :newName) WHERE id IN (551, 552, 553, 554, 555)', + { replacements: { oldName: '运单退回登记', newName: '未退登记' } } + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + 'UPDATE `wms_permission` SET meta_title = REPLACE(meta_title, :newName, :oldName) WHERE id IN (551, 552, 553, 554, 555)', + { replacements: { oldName: '运单退回登记', newName: '未退登记' } } + ); + }, +}; diff --git a/database/migrations/20261008193000-create-wms-order-b2b.js b/database/migrations/20261008193000-create-wms-order-b2b.js new file mode 100644 index 0000000..f771b0c --- /dev/null +++ b/database/migrations/20261008193000-create-wms-order-b2b.js @@ -0,0 +1,113 @@ +'use strict'; + +/** + * 创建 B2B 订单作业明细表 wms_order_b2b。 + * + * 与发货单(订单)主表 wms_order_delivery 分表一对一(order_id 关联分表 id,uk_order_id 唯一), + * 不分表(单表全量),通过 warehouse_id/store_id 做数据隔离与检索维度, + * 类似 wms_order_express(运单号表)的落表方式。 + * + * 字段: + * order_id 订单ID(关联 wms_order_delivery 分表 id,唯一) + * warehouse_id / store_id 仓库/货主维度 + * delivery_order_code 发货单号快照(便于按单号检索) + * total_box_count 总箱数 + * pickup_plate_number 提货车牌 + * prep_remark 备货备注 + * prep_duration_seconds 备货用时(秒) + * is_picked_up 是否提货(Y/N) + * picked_up_at 提货时间 + * created_at / updated_at / deleted_at 审计与软删除 + * + * 索引: + * uk_order_id(order_id 唯一) + * idx_warehouse_id / idx_store_id / idx_delivery_order_code + * idx_pickup_plate_number / idx_is_picked_up / idx_deleted_at + */ + +const TABLE_NAME = 'wms_order_b2b'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, ENUM, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID,关联 wms_order_delivery 分表 id', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + delivery_order_code: { + type: STRING(50), + allowNull: true, + comment: '发货单号快照', + }, + total_box_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '总箱数', + }, + pickup_plate_number: { + type: STRING(20), + allowNull: true, + comment: '提货车牌', + }, + prep_remark: { + type: STRING(500), + allowNull: true, + comment: '备货备注', + }, + prep_duration_seconds: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '备货用时(秒)', + }, + is_picked_up: { + type: ENUM('Y', 'N'), + allowNull: false, + defaultValue: 'N', + comment: '是否提货:Y=已提货 N=未提货', + }, + picked_up_at: { + type: DATE, + allowNull: true, + comment: '提货时间', + }, + created_at: { type: DATE, allowNull: false, comment: '创建时间' }, + updated_at: { type: DATE, allowNull: false, comment: '更新时间' }, + deleted_at: { type: DATE, allowNull: true, comment: '软删除时间' }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'order_id' ], { unique: true, name: 'uk_order_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: 'idx_store_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'delivery_order_code' ], { name: 'idx_delivery_order_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'pickup_plate_number' ], { name: 'idx_pickup_plate_number' }); + await queryInterface.addIndex(TABLE_NAME, [ 'is_picked_up' ], { name: 'idx_is_picked_up' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20261008195000-add-is-b2b-to-order-delivery.js b/database/migrations/20261008195000-add-is-b2b-to-order-delivery.js new file mode 100644 index 0000000..50a877f --- /dev/null +++ b/database/migrations/20261008195000-add-is-b2b-to-order-delivery.js @@ -0,0 +1,30 @@ +'use strict'; + +/** + * 订单基表 wms_order_delivery 增加 is_b2b 列(是否B2B,默认 N)。 + * + * 分表(wms_order_delivery_%)列由 order_delivery_factory 惰性同步补齐 + * (首次访问分表时 describeTable 比对 + 单条 ALTER,带自增水位保护), + * 本迁移只补基表列,保持基表与分表结构一致。 + */ + +const TABLE_NAME = 'wms_order_delivery'; +const COLUMN_NAME = 'is_b2b'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { ENUM } = Sequelize; + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: ENUM('Y', 'N'), + allowNull: true, + defaultValue: 'N', + comment: '是否B2B:Y是 N否', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20261009100000-add-is-print-to-wms-order-b2b.js b/database/migrations/20261009100000-add-is-print-to-wms-order-b2b.js new file mode 100644 index 0000000..5cb1ee7 --- /dev/null +++ b/database/migrations/20261009100000-add-is-print-to-wms-order-b2b.js @@ -0,0 +1,31 @@ +'use strict'; + +/** + * B2B 订单作业明细表 wms_order_b2b 增加 is_print 列(是否打印,默认 N)。 + * + * 字段:is_print ENUM('Y','N') NOT NULL DEFAULT 'N'(N=未打印 Y=已打印)。 + * 索引:idx_is_print(按打印状态筛选)。 + */ + +const TABLE_NAME = 'wms_order_b2b'; +const COLUMN_NAME = 'is_print'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { ENUM } = Sequelize; + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: ENUM('Y', 'N'), + allowNull: false, + defaultValue: 'N', + comment: '是否打印:Y=已打印 N=未打印', + }); + await queryInterface.addIndex(TABLE_NAME, [ COLUMN_NAME ], { name: 'idx_is_print' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.removeIndex(TABLE_NAME, 'idx_is_print'); + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20261010100000-add-created-at-index-to-wms-return-unpack.js b/database/migrations/20261010100000-add-created-at-index-to-wms-return-unpack.js new file mode 100644 index 0000000..972ebcd --- /dev/null +++ b/database/migrations/20261010100000-add-created-at-index-to-wms-return-unpack.js @@ -0,0 +1,20 @@ +'use strict'; + +/** + * wms_return_unpack 补充登记时间索引。 + * 看板 fulfillment 今日拆包件数按 warehouse_id + created_at 今日范围计数, + * 原表仅有 (warehouse_id, unpack_date) 等索引,按登记时间过滤会退化为 + * 全表扫描,新增 (warehouse_id, created_at) 复合索引使范围过滤走索引 + * (对齐 wms_return_received 的 idx_warehouse_created_at)。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.addIndex('wms_return_unpack', [ 'warehouse_id', 'created_at' ], { + name: 'idx_warehouse_created_at', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('wms_return_unpack', 'idx_warehouse_created_at'); + }, +}; diff --git a/database/migrations/20261013100000-create-wms-container.js b/database/migrations/20261013100000-create-wms-container.js new file mode 100644 index 0000000..4f25778 --- /dev/null +++ b/database/migrations/20261013100000-create-wms-container.js @@ -0,0 +1,98 @@ +'use strict'; + +/** + * 创建容器(篮筐)资产登记表 wms_container。 + * + * 用于登记仓库的物理容器(篮筐)资产:容器编号、使用状态、是否损坏、损坏说明、备注等。 + * 同一仓库内容器编号唯一(uk_warehouse_container_no),通过 warehouse_id 做数据隔离。 + * + * 后续用途:散单拣货把购物车商品临时转移到容器时,通过 status 标记容器占用/空闲。 + * + * 字段: + * warehouse_id 仓库ID(数据隔离维度) + * container_no 容器编号(篮筐编号) + * status 使用状态(idle=空闲 in_use=占用) + * is_damaged 是否损坏(Y=损坏 N=正常) + * damage_remark 损坏说明 + * remark 备注 + * creator_id / creator_name 登记人 + * created_at / updated_at 审计时间 + * + * 索引: + * uk_warehouse_container_no(warehouse_id + container_no 唯一) + * idx_warehouse_id + * idx_status + * idx_is_damaged + */ + +const TABLE_NAME = 'wms_container'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, ENUM, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + container_no: { + type: STRING(50), + allowNull: false, + comment: '容器编号(篮筐编号)', + }, + status: { + type: ENUM('idle', 'in_use'), + allowNull: false, + defaultValue: 'idle', + comment: '使用状态:idle=空闲 in_use=占用(散单商品临时转移)', + }, + is_damaged: { + type: ENUM('Y', 'N'), + allowNull: false, + defaultValue: 'N', + comment: '是否损坏:Y=损坏 N=正常', + }, + damage_remark: { + type: STRING(255), + allowNull: true, + comment: '损坏说明', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '登记人账户ID', + }, + creator_name: { + type: STRING(50), + allowNull: true, + comment: '登记人名称快照', + }, + created_at: { type: DATE, allowNull: false, comment: '创建时间' }, + updated_at: { type: DATE, allowNull: false, comment: '更新时间' }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'container_no' ], { unique: true, name: 'uk_warehouse_container_no' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'is_damaged' ], { name: 'idx_is_damaged' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20261014100000-seed-system-wechat-agreement.js b/database/migrations/20261014100000-seed-system-wechat-agreement.js new file mode 100644 index 0000000..2359ab3 --- /dev/null +++ b/database/migrations/20261014100000-seed-system-wechat-agreement.js @@ -0,0 +1,44 @@ +'use strict'; + +/** + * 用户须知系统默认版本种子(2026-10-14): + * - appid='system' 作为系统级默认须知模板(保留行,不面向真实小程序); + * - 新授权的小程序(首次授权)自动复制该内容作为第一版 + * (见 app/service/systems/wechat.js#ensureDefaultAgreementVersion); + * - 幂等:已存在 appid='system' 记录则跳过。 + */ + +const TABLE_NAME = 'wms_wechat_agreement_version'; +const SYSTEM_APPID = 'system'; + +const DEFAULT_CONTENT = [ + '

    小程序用户须知

    ', + '

    欢迎使用本小程序。在使用本小程序及相关服务前,请仔细阅读并理解本须知。

    ', + '

    1. 账号与绑定:登录后可通过「绑定账号」功能关联您的仓库系统账号;绑定信息仅用于身份识别与业务操作,请妥善保管账号密码。

    ', + '

    2. 数据与隐私:小程序仅收集提供仓储、物流等服务所必需的信息(如登录凭证、订单与库存数据),不会向无关第三方泄露。

    ', + '

    3. 使用规范:请勿利用本小程序从事违反法律法规或侵害他人权益的行为;如发现异常,请及时联系本小程序运营方。

    ', + '

    4. 条款更新:本须知可能适时更新,更新后的内容自发布时生效。

    ', +].join(''); + +module.exports = { + async up(queryInterface) { + const rows = await queryInterface.sequelize.query( + `SELECT id FROM ${TABLE_NAME} WHERE appid = ? LIMIT 1`, + { replacements: [ SYSTEM_APPID ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + if (rows && rows.length > 0) { + return; + } + await queryInterface.sequelize.query( + `INSERT INTO ${TABLE_NAME} (appid, content, created_at, updated_at) VALUES (?, ?, NOW(), NOW())`, + { replacements: [ SYSTEM_APPID, DEFAULT_CONTENT ] } + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `DELETE FROM ${TABLE_NAME} WHERE appid = ?`, + { replacements: [ SYSTEM_APPID ] } + ); + }, +}; diff --git a/database/migrations/20261014110000-backfill-system-wechat-agreement.js b/database/migrations/20261014110000-backfill-system-wechat-agreement.js new file mode 100644 index 0000000..7dc817a --- /dev/null +++ b/database/migrations/20261014110000-backfill-system-wechat-agreement.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * 回填系统默认用户须知(2026-10-14): + * - 对 wms_wechat_app 中尚不存在任何用户须知版本的小程序,复制系统默认须知 + * (wms_wechat_agreement_version 中 appid='system' 最新一条)作为第一版; + * - 幂等:已有任意版本的小程序跳过;无系统默认行则跳过(依赖种子迁移 20261014100000)。 + */ + +const TABLE_NAME = 'wms_wechat_agreement_version'; +const SYSTEM_APPID = 'system'; + +module.exports = { + async up(queryInterface) { + const { QueryTypes } = queryInterface.sequelize; + + const systemRows = await queryInterface.sequelize.query( + `SELECT content FROM ${TABLE_NAME} WHERE appid = ? ORDER BY id DESC LIMIT 1`, + { replacements: [ SYSTEM_APPID ], type: QueryTypes.SELECT } + ); + const systemContent = systemRows && systemRows.length > 0 ? systemRows[0].content : null; + if (!systemContent) { + console.log('[backfill] 缺少系统默认须知(appid=system),跳过回填'); + return; + } + + const appids = await queryInterface.sequelize.query( + `SELECT a.appid FROM wms_wechat_app a + WHERE NOT EXISTS ( + SELECT 1 FROM ${TABLE_NAME} v WHERE v.appid = a.appid + ) + ORDER BY a.id ASC`, + { type: QueryTypes.SELECT } + ); + + for (const row of appids) { + await queryInterface.sequelize.query( + `INSERT INTO ${TABLE_NAME} (appid, content, created_at, updated_at) VALUES (?, ?, NOW(), NOW())`, + { replacements: [ row.appid, systemContent ] } + ); + } + + console.log(`[backfill] 回填系统默认须知 appid 数量: ${appids.length}`); + }, + + async down() { + // 回填行与人工版本无法可靠区分,不做逆向删除 + }, +}; diff --git a/database/migrations/20261017100000-add-return-unpack-transfer-orders-permission.js b/database/migrations/20261017100000-add-return-unpack-transfer-orders-permission.js new file mode 100644 index 0000000..e6f3111 --- /dev/null +++ b/database/migrations/20261017100000-add-return-unpack-transfer-orders-permission.js @@ -0,0 +1,88 @@ +'use strict'; + +/** + * 退回拆包「配送订单批量转退回拆包单」权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 643,当前库内最大已用 ID=642): + * 643 — returnUnpack.transferByOrders API:配送订单批量转退回拆包单 + * + * 角色授权(系统预设角色,不含通配符角色): + * 作业类(643)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 643: [ 27, 26 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 643, 'returnUnpack.transferByOrders', 'API:配送订单批量转退回拆包单' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 643` + ); + }, +}; diff --git a/database/migrations/20261025135000-add-is-custom-password-to-wms-account.js b/database/migrations/20261025135000-add-is-custom-password-to-wms-account.js new file mode 100644 index 0000000..b7faa39 --- /dev/null +++ b/database/migrations/20261025135000-add-is-custom-password-to-wms-account.js @@ -0,0 +1,44 @@ +'use strict'; + +/** + * 为账号表新增“是否自定义密码”标记。 + */ +module.exports = { + /** + * 执行迁移:新增 is_custom_password 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_account'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.is_custom_password) { + return; + } + + await queryInterface.addColumn(tableName, 'is_custom_password', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否自定义密码:0-否,1-是', + }); + }, + + /** + * 回滚迁移:删除 is_custom_password 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_account'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.is_custom_password) { + return; + } + + await queryInterface.removeColumn(tableName, 'is_custom_password'); + }, +}; diff --git a/database/migrations/20261027010000-merge-stock-check-type-all-into-location.js b/database/migrations/20261027010000-merge-stock-check-type-all-into-location.js new file mode 100644 index 0000000..5fb7ab5 --- /dev/null +++ b/database/migrations/20261027010000-merge-stock-check-type-all-into-location.js @@ -0,0 +1,53 @@ +'use strict'; + +/** + * 移除盘点范围类型 all(与 location 语义重复:两者都按库位盘点、都强制盲盘、 + * 明细都是 scope_type='location';all 唯一的额外能力「未传库位时自动拉全仓库启用库位」 + * 已合并进 location): + * + * wms_stock_check: + * 1. 存量数据: + * - 存在商品明细行(scope_type='goods')的 type='all' 任务 = 2026-09-30 改造前的 + * 「全仓按商品」口径,改为 type='goods'(mode 保持原值,改造前商品口径允许明盘); + * - 其余 type='all' 任务统一改为 'location',mode 归一到 'blind'(按库位盘点一律盲盘)。 + * 2. 列定义:默认值 all → location,comment 去掉 all。 + * + * 发布前核查 SQL(确认两类任务各有多少): + * SELECT c.type, d.scope_type, COUNT(DISTINCT c.id) + * FROM wms_stock_check c LEFT JOIN wms_stock_check_detail d ON d.check_id = c.id + * WHERE c.type = 'all' GROUP BY c.type, d.scope_type; + */ + +const TABLE_NAME = 'wms_stock_check'; + +module.exports = { + up: async queryInterface => { + // 改造前的「全仓按商品」任务(明细为商品行)按真实语义归入 goods,保留原 mode + await queryInterface.sequelize.query(` + UPDATE \`${TABLE_NAME}\` c + JOIN ( + SELECT DISTINCT check_id FROM wms_stock_check_detail WHERE scope_type = 'goods' + ) d ON d.check_id = c.id + SET c.\`type\` = 'goods' + WHERE c.\`type\` = 'all' + `); + // 其余(库位口径,含无明细的空任务)统一并入 location,并按库位口径归一为盲盘 + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_NAME}\` SET \`type\` = 'location', \`mode\` = 'blind' WHERE \`type\` = 'all'` + ); + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + MODIFY COLUMN \`type\` VARCHAR(20) NOT NULL DEFAULT 'location' + COMMENT '盘点范围类型:location=按库位(未传库位时自动全盘),store=按货主,goods=按商品' + `); + }, + + down: async queryInterface => { + // 数据不可回滚(all 已并入 location/goods,无法区分原值),仅恢复列定义 + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + MODIFY COLUMN \`type\` VARCHAR(20) NOT NULL DEFAULT 'all' + COMMENT '盘点范围类型:all=全盘,store=按货主,goods=按商品,location=按库位' + `); + }, +}; diff --git a/database/migrations/20261028010000-add-is-static-to-stock-check.js b/database/migrations/20261028010000-add-is-static-to-stock-check.js new file mode 100644 index 0000000..8869cd2 --- /dev/null +++ b/database/migrations/20261028010000-add-is-static-to-stock-check.js @@ -0,0 +1,25 @@ +'use strict'; + +/** + * 库存盘点主表新增「是否静态盘点」标记: + * + * wms_stock_check 新增 is_static(TINYINT(1) NOT NULL DEFAULT 0): + * - 1 = 静态盘点(由静态盘点定式 pattern=static 创建,或创建任务时显式开启); + * - 0 = 普通盘点(存量数据默认值即 0,无需回填); + * - 纯标记字段,不参与盘点流程判定(不改变模式/状态机/差异口径)。 + */ + +const TABLE_NAME = 'wms_stock_check'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + ADD COLUMN \`is_static\` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否静态盘点(1=静态盘点(静态定式创建或创建时开启),0=普通盘点)' AFTER \`store_id\` + `); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'is_static'); + }, +}; diff --git a/database/migrations/20261104100000-alter-order-delivery-from-key-to-varchar.js b/database/migrations/20261104100000-alter-order-delivery-from-key-to-varchar.js new file mode 100644 index 0000000..75192da --- /dev/null +++ b/database/migrations/20261104100000-alter-order-delivery-from-key-to-varchar.js @@ -0,0 +1,225 @@ +'use strict'; + +/** + * 订单表 from_key 由 INTEGER(11) 改为 VARCHAR(100),用于承载上游对接应用的 appKey。 + * + * 背景:from_key 是「回原通道」的应用标识(出库单回传、取号业务分支都依赖它), + * 历史上只存过奇门/ERP 的纯数字 appKey(如聚水潭 23060081、吉客云 24869601)。 + * OpenAPI 创建来源的 appKey 是字符串(wms_api_app.self_app_key,如 + * WMSD08A3696BBA9551F261C88BBF7F462BD),INTEGER 列无法承载, + * 导致 API 渠道订单 from_key 全部落空。 + * + * 落库口径(统一为“上游对接应用 appKey”): + * - QM :wms_qimen_apps.app_key + * - API :wms_api_app.self_app_key + * - MANUAL / STOCKOUT:NULL + * + * 覆盖范围:基表 wms_order_delivery + 全部分表 + * (wms_order_delivery_{wh} 及 _{wh}_history / _{wh}_dispatch / _{wh}_outsourced)。 + * + * 注意:INTEGER → VARCHAR 在 MySQL 中需要重建表,重建会把 AUTO_INCREMENT + * 重置为 MAX(id)+1。若原水位更高(曾删除数据),会与其它分表 id 区间重叠产生 + * 主键冲突,因此每张表改列后都要恢复原 AUTO_INCREMENT 水位。 + * + * 幂等:列已是字符类型则跳过。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +const COLUMN_NAME = 'from_key'; + +const COLUMN_COMMENT = '来源键(上游对接应用 appKey:QM=wms_qimen_apps.app_key,API=wms_api_app.self_app_key)'; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 判断表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 是否存在。 + */ +async function tableExists(queryInterface, tableName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT COUNT(*) AS total FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', + { replacements: [ tableName ] } + ); + return Number(rows && rows[0] && rows[0].total || 0) > 0; +} + +/** + * 读取列当前类型。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 类型字符串,列不存在返回 null。 + */ +async function getColumnType(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + const column = described && described[columnName]; + return column ? String(column.type || '') : null; +} + +/** + * 判断类型是否为字符类型。 + * @param {string} type 类型字符串。 + * @return {boolean} 是否字符类型。 + */ +function isStringType(type) { + return /char|text/i.test(String(type || '')); +} + +/** + * 读取表当前 AUTO_INCREMENT 水位。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 水位,无自增主键返回 null。 + */ +async function getAutoIncrement(queryInterface, tableName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', + { replacements: [ tableName ] } + ); + const value = rows && rows[0] && rows[0].autoIncrement; + return value === null || value === undefined ? null : Number(value); +} + +/** + * 重建表后若自增水位被重置为更低值则恢复,避免与其它分表 id 重叠。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {number|null} previousAutoIncrement 改列前的水位。 + * @return {Promise} 是否执行了恢复。 + */ +async function restoreAutoIncrement(queryInterface, tableName, previousAutoIncrement) { + if (previousAutoIncrement === null) { + return false; + } + + const currentAutoIncrement = await getAutoIncrement(queryInterface, tableName); + if (currentAutoIncrement === null || currentAutoIncrement >= previousAutoIncrement) { + return false; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` AUTO_INCREMENT = ${previousAutoIncrement}` + ); + return true; +} + +module.exports = { + /** + * 执行迁移:把 from_key 改为 VARCHAR(100)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await tableExists(queryInterface, tableName)) { + results.push({ tableName, action: 'skip', reason: 'table_missing' }); + continue; + } + + const currentType = await getColumnType(queryInterface, tableName, COLUMN_NAME); + if (currentType === null) { + results.push({ tableName, action: 'skip', reason: 'column_missing' }); + continue; + } + + if (isStringType(currentType)) { + results.push({ tableName, action: 'skip', reason: 'already_string', currentType }); + continue; + } + + const previousAutoIncrement = await getAutoIncrement(queryInterface, tableName); + + await queryInterface.changeColumn(tableName, COLUMN_NAME, { + type: Sequelize.STRING(100), + allowNull: true, + defaultValue: null, + comment: COLUMN_COMMENT, + }); + + const autoIncrementRestored = await restoreAutoIncrement(queryInterface, tableName, previousAutoIncrement); + results.push({ tableName, action: 'altered', from: currentType, autoIncrementRestored }); + } + + console.log('[20261104100000-alter-order-delivery-from-key-to-varchar] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:把 from_key 改回 INTEGER(11)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await tableExists(queryInterface, tableName)) { + results.push({ tableName, action: 'skip', reason: 'table_missing' }); + continue; + } + + const currentType = await getColumnType(queryInterface, tableName, COLUMN_NAME); + if (currentType === null) { + results.push({ tableName, action: 'skip', reason: 'column_missing' }); + continue; + } + + if (!isStringType(currentType)) { + results.push({ tableName, action: 'skip', reason: 'already_integer', currentType }); + continue; + } + + // 字符串 appKey 无法回滚进 INTEGER 列,先阻断避免截断成 0 造成脏数据 + const [ incompatibleRows ] = await queryInterface.sequelize.query( + `SELECT COUNT(*) AS total FROM \`${tableName}\` ` + + `WHERE ${COLUMN_NAME} IS NOT NULL AND ${COLUMN_NAME} <> '' ` + + `AND ${COLUMN_NAME} NOT REGEXP '^-?[0-9]+$'` + ); + const incompatibleCount = Number(incompatibleRows && incompatibleRows[0] && incompatibleRows[0].total || 0); + if (incompatibleCount > 0) { + results.push({ tableName, action: 'skip', reason: 'non_numeric_data', incompatibleCount }); + continue; + } + + const previousAutoIncrement = await getAutoIncrement(queryInterface, tableName); + + await queryInterface.changeColumn(tableName, COLUMN_NAME, { + type: Sequelize.INTEGER(11), + allowNull: true, + defaultValue: null, + comment: '来源键', + }); + + const autoIncrementRestored = await restoreAutoIncrement(queryInterface, tableName, previousAutoIncrement); + results.push({ tableName, action: 'reverted', autoIncrementRestored }); + } + + console.log('[20261104100000-alter-order-delivery-from-key-to-varchar] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20261105190000-add-wave-no-index-to-order-delivery-shards.js b/database/migrations/20261105190000-add-wave-no-index-to-order-delivery-shards.js new file mode 100644 index 0000000..61b2f50 --- /dev/null +++ b/database/migrations/20261105190000-add-wave-no-index-to-order-delivery-shards.js @@ -0,0 +1,166 @@ +'use strict'; + +/** + * 为订单配送分表增加 wave_no 索引。 + * + * 背景: + * - order.deliveryOrder.list(app/service/systemMethods/order/base.js#listByModule)的 SQL 形态为 + * `WHERE warehouse_id=? AND dispatch_lane=? AND wave_no=? ORDER BY updated_at DESC, id DESC LIMIT ?` + * 且并行执行同条件 COUNT(*); + * - 生产 wms_order_delivery_1000028_dispatch(1,488,523 行 / 约 2.4GB)没有任何 wave_no 索引, + * 实测 COUNT(*) 26.4s、列表查询 21.1s:优化器只能走 (warehouse_id, dispatch_lane, updated_at, id) + * 或 (warehouse_id) 索引扫掉约 55 万行后逐行回表过滤 wave_no; + * - wave_no 在表内近似唯一(10.25 万个波次号 / 148.8 万行,平均约 14 行/波次), + * 单列索引即可把上述扫描降为十几行的点查。 + * + * 本迁移枚举 current/dispatch/history/outsourced 四类分表补建索引,命名与 + * app/model/order_delivery_table_schema.js#buildIndexOptions 的 idx_{prefix}_wave_no 一致 + * (dispatch 分表沿用 current 前缀,与既有继承索引的命名习惯一致), + * 避免应用运行时 drift 同步再补建一次同名索引。 + * + * 执行方式:ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE + * (MySQL 5.6+ 在线加二级索引,不重建表、不锁写,建议低峰期执行)。 + * 幂等:索引已存在、或表缺少 wave_no 列时跳过。 + * + * ⚠️ 本文件未对任何环境执行,仅由迁移流程(npm run migration:single <文件名>)在确认后落库。 + */ + +const SHARD_PATTERNS = [ + { modelType: 'dispatch', pattern: /^wms_order_delivery_(\d+)_dispatch$/ }, + { modelType: 'history', pattern: /^wms_order_delivery_(\d+)_history$/ }, + { modelType: 'outsourced', pattern: /^wms_order_delivery_(\d+)_outsourced$/ }, + { modelType: 'current', pattern: /^wms_order_delivery_(\d+)$/ }, +]; + +const INDEX_COLUMN = 'wave_no'; + +/** + * 解析分表名。 + * @param {string} tableName 表名。 + * @return {{ modelType: string, warehouseId: string }|null} 解析结果。 + */ +function parseShardTableName(tableName) { + for (const item of SHARD_PATTERNS) { + const match = item.pattern.exec(tableName); + if (match) { + return { modelType: item.modelType, warehouseId: match[1] }; + } + } + return null; +} + +/** + * 构建 wave_no 索引名(与 buildIndexOptions 的 `idx_${prefix}_wave_no` 一致)。 + * @param {string} warehouseId 仓库ID。 + * @param {string} modelType 模型类型。 + * @return {string} 索引名。 + */ +function buildWaveNoIndexName(warehouseId, modelType) { + const prefix = modelType === 'dispatch' + ? `${warehouseId}_current` + : `${warehouseId}_${modelType}`; + return `idx_${prefix}_${INDEX_COLUMN}`; +} + +/** + * 列举库内所有订单配送分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 分表名列表。 + */ +async function listManagedShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => parseShardTableName(name)); +} + +/** + * 判断表是否存在指定列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT COLUMN_NAME AS columnName FROM INFORMATION_SCHEMA.COLUMNS ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', + { replacements: [ tableName, columnName ] } + ); + return (rows || []).length > 0; +} + +/** + * 判断索引是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 是否存在。 + */ +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(index => { + const name = String(index && (index.name || index.Key_name || index.key_name) || ''); + return name.toLowerCase() === String(indexName).toLowerCase(); + }); +} + +module.exports = { + /** + * 执行迁移:为订单配送分表增加 wave_no 索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const shards = await listManagedShards(queryInterface); + const results = []; + + for (const tableName of shards) { + const parsed = parseShardTableName(tableName); + const indexName = buildWaveNoIndexName(parsed.warehouseId, parsed.modelType); + + if (!(await columnExists(queryInterface, tableName, INDEX_COLUMN))) { + results.push({ tableName, action: 'skip', reason: 'column-missing' }); + continue; + } + + if (await indexExists(queryInterface, tableName, indexName)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` ADD INDEX \`${indexName}\` (\`${INDEX_COLUMN}\`), ALGORITHM=INPLACE, LOCK=NONE` + ); + results.push({ tableName, action: 'added', indexName }); + } + + console.log('[20261105190000-add-wave-no-index] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除 wave_no 索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const shards = await listManagedShards(queryInterface); + + for (const tableName of shards) { + const parsed = parseShardTableName(tableName); + const indexName = buildWaveNoIndexName(parsed.warehouseId, parsed.modelType); + + if (!(await indexExists(queryInterface, tableName, indexName))) { + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP INDEX \`${indexName}\`, ALGORITHM=INPLACE, LOCK=NONE` + ); + } + }, +}; diff --git a/database/migrations/20261107110000-add-oms-print-fields-to-order-express.js b/database/migrations/20261107110000-add-oms-print-fields-to-order-express.js new file mode 100644 index 0000000..f83c1df --- /dev/null +++ b/database/migrations/20261107110000-add-oms-print-fields-to-order-express.js @@ -0,0 +1,69 @@ +'use strict'; + +/** + * 为运单表新增 OMS 取号返回的打印定位字段。 + * + * - `print_history_id`:OMS 返回的打印记录ID(店管家 PrintHistoryIds[0].id), + * 打印前用它回 `deliveryorder.getprintdata` 换新的抖音 params; + * - `cai_niao_auth_info_id`:菜鸟授权网点ID(每个店铺唯一), + * 打印时按它做店铺分组,一组只需一个 print_history_id 换一次 params。 + */ +module.exports = { + /** + * 执行迁移:新增 print_history_id / cai_niao_auth_info_id(幂等)。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_order_express'; + const columns = await queryInterface.describeTable(tableName); + const definitions = []; + + if (!columns.print_history_id) { + definitions.push( + `ADD COLUMN \`print_history_id\` ${Sequelize.STRING(64)} NULL DEFAULT NULL COMMENT 'OMS 打印记录ID(打印前换新 params 用)' AFTER \`encryptedtoken\`` + ); + } + + if (!columns.cai_niao_auth_info_id) { + const afterColumn = definitions.length > 0 ? 'print_history_id' : 'encryptedtoken'; + definitions.push( + `ADD COLUMN \`cai_niao_auth_info_id\` ${Sequelize.BIGINT(20).UNSIGNED} NULL DEFAULT NULL COMMENT '菜鸟授权网点ID(OMS 取号返回,打印按店铺分组用)' AFTER \`${afterColumn}\`` + ); + } + + if (definitions.length === 0) { + return; + } + + // 拿不到元数据锁时快速失败:MDL 排队会把后续所有读写一起堵住, + // 30 秒内拿不到锁就报错退出(可安全重试),避免拖垮生产可用性 + await queryInterface.sequelize.query('SET SESSION lock_wait_timeout = 30'); + + // 两条 ADD COLUMN 合并为一次 ALTER:MySQL 5.7 加列需重建表,分两次会重建两遍 + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` ${definitions.join(', ')}` + ); + }, + + /** + * 回滚迁移:删除新增字段(幂等)。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tableName = 'wms_order_express'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.cai_niao_auth_info_id) { + await queryInterface.removeColumn(tableName, 'cai_niao_auth_info_id'); + } + + if (columns.print_history_id) { + await queryInterface.removeColumn(tableName, 'print_history_id'); + } + }, +}; diff --git a/database/migrations/20261109235000-add-warehouse-store-index-to-wms-order-express.js b/database/migrations/20261109235000-add-warehouse-store-index-to-wms-order-express.js new file mode 100644 index 0000000..cf9f27f --- /dev/null +++ b/database/migrations/20261109235000-add-warehouse-store-index-to-wms-order-express.js @@ -0,0 +1,99 @@ +'use strict'; + +/** + * 为运单表 wms_order_express 增加 idx_warehouse_store(store_id, warehouse_id)索引。 + * + * 背景: + * - 生产库已手工创建该索引(SHOW INDEX 可见 `idx_warehouse_store`,Non_unique=1, + * 列序 store_id → warehouse_id),用于支撑运单相关的「货主 + 仓库」组合过滤查询 + * (运单列表/详情的货主隔离、发货单与运单的关联校验等),避免只能走 + * idx_warehouse_id_status 或 idx_warehouse_id_create_at 的 warehouse_id 前导列, + * 再逐行回表过滤 store_id。 + * - 手工变更未纳入版本管理,其他环境(开发/测试)缺失该索引,会造成同一条查询在不同 + * 环境执行计划不一致;本迁移把生产变更固化为迁移脚本,保证各环境结构一致。 + * - 索引名沿用生产名称 idx_warehouse_store(与仓库内 idx_warehouse_store 命名习惯一致), + * 不按 idx_{表名}_ 前缀重命名,否则生产会因名称不同再建一份功能重复的索引。 + * + * 执行方式:ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE + * (MySQL 5.6+ 在线加二级索引,不重建表、不锁写)。 + * 幂等:索引已存在时跳过;生产环境执行本迁移预期输出 skip/exists。 + * + * ⚠️ 本文件未对任何环境执行,仅由迁移流程(npm run migration:single <文件名>)在确认后落库。 + */ + +const TABLE_NAME = 'wms_order_express'; +const INDEX_NAME = 'idx_warehouse_store'; +const INDEX_FIELDS = [ 'store_id', 'warehouse_id' ]; + +/** + * 判断表是否存在指定列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT COLUMN_NAME AS columnName FROM INFORMATION_SCHEMA.COLUMNS ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', + { replacements: [ tableName, columnName ] } + ); + return (rows || []).length > 0; +} + +/** + * 判断索引是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 是否存在。 + */ +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(index => { + const name = String(index && (index.name || index.Key_name || index.key_name) || ''); + return name.toLowerCase() === String(indexName).toLowerCase(); + }); +} + +module.exports = { + /** + * 执行迁移:为 wms_order_express 增加 idx_warehouse_store 索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + for (const columnName of INDEX_FIELDS) { + if (!(await columnExists(queryInterface, TABLE_NAME, columnName))) { + console.log(`[${INDEX_NAME}] skip: ${TABLE_NAME}.${columnName} 列不存在`); + return; + } + } + + if (await indexExists(queryInterface, TABLE_NAME, INDEX_NAME)) { + console.log(`[${INDEX_NAME}] skip: ${TABLE_NAME} 已存在该索引`); + return; + } + + const fieldSql = INDEX_FIELDS.map(field => `\`${field}\``).join(', '); + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${INDEX_NAME}\` (${fieldSql}), ALGORITHM=INPLACE, LOCK=NONE` + ); + console.log(`[${INDEX_NAME}] added on ${TABLE_NAME} (${INDEX_FIELDS.join(', ')})`); + }, + + /** + * 回滚迁移:移除 idx_warehouse_store 索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!(await indexExists(queryInterface, TABLE_NAME, INDEX_NAME))) { + return; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${INDEX_NAME}\`, ALGORITHM=INPLACE, LOCK=NONE` + ); + }, +}; diff --git a/database/migrations/20261111033000-init-is-back-intercept-receive-to-n.js b/database/migrations/20261111033000-init-is-back-intercept-receive-to-n.js new file mode 100644 index 0000000..be09d83 --- /dev/null +++ b/database/migrations/20261111033000-init-is-back-intercept-receive-to-n.js @@ -0,0 +1,142 @@ +'use strict'; + +/** + * wms_order_express 三个 Y/N 标记列补默认值与存量回填: + * + * - `is_back`(是否退回)、`is_intercept`(是否拦截)、`is_galaxy_receive`(是否揽收) + * 建表时均为 `ENUM('Y','N') NULL` 且无默认值,业务创建运单时多数不显式赋值 → + * 存量约 100% 为 NULL,导致运单列表按「是否退回 / 是否拦截 / 是否揽收 = N」筛选时 + * 直接返回空(NULL 不参与 ='N' 比较)。 + * + * 本迁移做两件事: + * 1) 三列补 `DEFAULT 'N'`(保留 NULL 允许,避免历史裸 SQL 显式写 NULL 时报错); + * 2) 存量 NULL 回填为 'N',已为 'Y' 的一律不动。 + * + * 回填按主键区间分批(每批 ≤ 20000 个 id),走 PK 范围扫描, + * 避免单条大 UPDATE 长时间持锁(生产约 159 万行 × 3 列)。 + * + * 幂等:列默认值已是 'N' 时跳过 MODIFY;无 NULL 时跳过该批 UPDATE,可重复执行。 + */ + +const TABLE_NAME = 'wms_order_express'; +const COLUMNS = [ 'is_back', 'is_intercept', 'is_galaxy_receive' ]; +const FILL_VALUE = 'N'; + +/** 单批主键区间宽度(控制单条 UPDATE 的锁持有时间) */ +const ID_WINDOW = 20000; + +/** + * 读取列定义(类型 / 可空 / 默认值 / 注释),用于构造 MODIFY COLUMN。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 列定义,列不存在时返回 null。 + */ +async function describeColumn(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT COLUMN_TYPE AS columnType, IS_NULLABLE AS isNullable, ' + + 'COLUMN_DEFAULT AS columnDefault, COLUMN_COMMENT AS columnComment ' + + 'FROM INFORMATION_SCHEMA.COLUMNS ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', + { replacements: [ tableName, columnName ] } + ); + return (rows || [])[0] || null; +} + +/** + * 将列默认值设置为 'N'。 + * + * 使用 `ALTER COLUMN ... SET DEFAULT`(MySQL 5.7 元数据变更,不重建表、不锁写), + * 而不是 `MODIFY COLUMN`(5.7 下会触发表重建,生产 wms_order_express 约 159 万行)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} columnName 列名。 + * @return {Promise} 无返回值。 + */ +async function applyDefault(queryInterface, columnName) { + const column = await describeColumn(queryInterface, TABLE_NAME, columnName); + if (!column) { + console.log(`[${columnName}] skip: ${TABLE_NAME}.${columnName} 列不存在`); + return; + } + + if (String(column.columnDefault || '').toUpperCase() === FILL_VALUE) { + console.log(`[${columnName}] skip: 默认值已是 '${FILL_VALUE}'`); + return; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ALTER COLUMN \`${columnName}\` SET DEFAULT '${FILL_VALUE}'` + ); + console.log(`[${columnName}] default '${FILL_VALUE}' applied`); +} + +/** + * 按主键区间分批把 NULL 回填为 'N'(已为 'Y'/'N' 的行不受影响)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} columnName 列名。 + * @return {Promise} 实际回填行数。 + */ +async function backfillColumn(queryInterface, columnName) { + const sequelize = queryInterface.sequelize; + const [ rangeRows ] = await sequelize.query( + `SELECT MIN(id) AS minId, MAX(id) AS maxId FROM \`${TABLE_NAME}\` ` + + `WHERE \`${columnName}\` IS NULL`, + { type: sequelize.QueryTypes.SELECT } + ); + const range = (rangeRows && rangeRows[0]) || rangeRows || {}; + const minId = Number(range.minId); + const maxId = Number(range.maxId); + + if (!Number.isFinite(minId) || !Number.isFinite(maxId)) { + console.log(`[${columnName}] skip: 无 NULL 数据`); + return 0; + } + + let filled = 0; + for (let start = minId; start <= maxId; start += ID_WINDOW) { + const end = start + ID_WINDOW - 1; + const [ , affected ] = await sequelize.query( + `UPDATE \`${TABLE_NAME}\` SET \`${columnName}\` = ? ` + + 'WHERE `id` BETWEEN ? AND ? AND `' + columnName + '` IS NULL', + { replacements: [ FILL_VALUE, start, end ] } + ); + const count = Number(affected && affected.affectedRows ? affected.affectedRows : affected) || 0; + filled += count; + } + + console.log(`[${columnName}] backfilled ${filled} rows`); + return filled; +} + +module.exports = { + /** + * 执行迁移:补默认值 + 存量 NULL 回填为 'N'。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + for (const columnName of COLUMNS) { + await applyDefault(queryInterface, columnName); + await backfillColumn(queryInterface, columnName); + } + }, + + /** + * 回滚迁移:仅移除列默认值;数据回填不可逆('N' 与 NULL 在查询口径上等价, + * 反向置 NULL 会让筛选再次失效,故不还原数据)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + for (const columnName of COLUMNS) { + const column = await describeColumn(queryInterface, TABLE_NAME, columnName); + if (!column) continue; + if (String(column.columnDefault || '').toUpperCase() !== FILL_VALUE) continue; + + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ALTER COLUMN \`${columnName}\` DROP DEFAULT` + ); + console.log(`[${columnName}] default dropped`); + } + }, +}; diff --git a/database/migrations/20261111041500-add-yn-flag-indexes-to-order-express.js b/database/migrations/20261111041500-add-yn-flag-indexes-to-order-express.js new file mode 100644 index 0000000..a843dc6 --- /dev/null +++ b/database/migrations/20261111041500-add-yn-flag-indexes-to-order-express.js @@ -0,0 +1,97 @@ +'use strict'; + +/** + * wms_order_express 三个 Y/N 标记列补单列索引: + * + * - `is_back`(是否退回)、`is_intercept`(是否拦截)、`is_galaxy_receive`(是否揽收) + * 是运单列表的常用筛选条件,但此前均无索引; + * - 运单表约 159 万行(生产),按单列筛选会走全表扫,且刚才的 NULL→'N' 回填里 + * `MIN(id)/MAX(id) WHERE col IS NULL` 也需要 90s+; + * - 三列区分度不高(Y/N 两值),但查询总是叠加 warehouse_id 等前置条件时收益有限, + * 因此按「单列索引」建,交给优化器按组合选择; + * 选择单列而非联合索引,是为了同时服务 + * `is_galaxy_receive='N'`(未揽收待更新)、`is_back='Y'`、`is_intercept='Y'` 等 + * 各方向独立的筛选与批量更新。 + * + * 执行方式:`ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE` + * (MySQL 5.7 在线加二级索引,不重建表、不阻塞读写)。 + * 幂等:索引已存在时跳过。 + */ + +const TABLE_NAME = 'wms_order_express'; +const INDEXES = [ + { name: 'idx_is_back', column: 'is_back' }, + { name: 'idx_is_intercept', column: 'is_intercept' }, + { name: 'idx_is_galaxy_receive', column: 'is_galaxy_receive' }, +]; + +/** + * 判断列是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT COLUMN_NAME AS columnName FROM INFORMATION_SCHEMA.COLUMNS ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', + { replacements: [ tableName, columnName ] } + ); + return (rows || []).length > 0; +} + +/** + * 判断索引是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 是否存在。 + */ +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (indexes || []).some(index => { + const name = String(index && (index.name || index.Key_name || index.key_name) || ''); + return name.toLowerCase() === String(indexName).toLowerCase(); + }); +} + +module.exports = { + /** + * 执行迁移:为三个标记列分别建立单列索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + for (const { name, column } of INDEXES) { + if (!(await columnExists(queryInterface, TABLE_NAME, column))) { + console.log(`[${name}] skip: ${TABLE_NAME}.${column} 列不存在`); + continue; + } + if (await indexExists(queryInterface, TABLE_NAME, name)) { + console.log(`[${name}] skip: 索引已存在`); + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${name}\` (\`${column}\`), ALGORITHM=INPLACE, LOCK=NONE` + ); + console.log(`[${name}] added on ${TABLE_NAME}(${column})`); + } + }, + + /** + * 回滚迁移:移除三个单列索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + for (const { name } of INDEXES) { + if (!(await indexExists(queryInterface, TABLE_NAME, name))) continue; + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${name}\`, ALGORITHM=INPLACE, LOCK=NONE` + ); + console.log(`[${name}] dropped`); + } + }, +}; diff --git a/database/migrations/20261111193000-create-wms-order-express-trace.js b/database/migrations/20261111193000-create-wms-order-express-trace.js new file mode 100644 index 0000000..ce2d0cb --- /dev/null +++ b/database/migrations/20261111193000-create-wms-order-express-trace.js @@ -0,0 +1,137 @@ +'use strict'; + +/** + * 创建运单物流轨迹表 wms_order_express_trace。 + * + * 与 wms_order_express 关联:一个运单(express_id)对应多条轨迹(1:N), + * 轨迹由外部快递/轨迹接口回传(如奇门 taobao.qimen.trace.query 的 traces 节点)。 + * + * 字段口径(与外部返回的轨迹行同名转下划线): + * op_time opTime 操作时间 + * out_biz_code outBizCode 外部业务码(可能是拼接串,如 770358128188071_510180_1794262553000_210) + * memo memo 轨迹描述,如【广州市】快件已发往 山东济南转运中心 + * op_org_city_name opOrgCityName 操作机构所在城市 + * weight weight 重量(来源原值,单位以对接方为准) + * scan_type scanType 扫描类型,如 发件 / 到件 / 派件 / 签收 + * raw_data 原始报文 JSON,便于后续新增字段时不改表结构 + * + * 关联与隔离: + * express_id / waybill_code / order_id 冗余落库,便于「按运单」「按订单」直接查询; + * warehouse_id 做仓库隔离,避免跨仓串读。 + * + * 幂等去重:uk_express_op_scan(express_id + op_time + scan_type)保证重复回传不落重复行。 + * + * 索引: + * uk_express_op_scan(express_id, op_time, scan_type 唯一) + * idx_waybill_code(waybill_code, op_time) + * idx_order_id(order_id) + * idx_warehouse_op_time(warehouse_id, op_time) + */ + +const TABLE_NAME = 'wms_order_express_trace'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = Sequelize; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '运单ID(wms_order_express.id)', + }, + waybill_code: { + type: STRING(50), + allowNull: false, + comment: '运单号(冗余,便于按运单号直查)', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID(冗余,便于按订单查轨迹)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + op_time: { + type: DATE, + allowNull: true, + comment: '操作时间(opTime)', + }, + out_biz_code: { + type: STRING(191), + allowNull: true, + comment: '外部业务码(outBizCode)', + }, + memo: { + type: STRING(500), + allowNull: true, + comment: '轨迹描述(memo),如【广州市】快件已发往 山东济南转运中心', + }, + op_org_city_name: { + type: STRING(100), + allowNull: true, + comment: '操作机构所在城市(opOrgCityName)', + }, + weight: { + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '重量(weight,来源原值)', + }, + scan_type: { + type: STRING(50), + allowNull: true, + comment: '扫描类型(scanType),如 发件/到件/派件/签收', + }, + raw_data: { + type: JSON_TYPE, + allowNull: true, + comment: '原始轨迹报文(未落库字段的兜底存储)', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + // 与主表 wms_order_express 保持一致(utf8mb4_general_ci),避免轨迹描述含 4 字节字符时写入失败 + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '运单物流轨迹表(1 运单 : N 轨迹)', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'express_id', 'op_time', 'scan_type' ], { + unique: true, + name: 'uk_express_op_scan', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code', 'op_time' ], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'order_id' ], { name: 'idx_order_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'op_time' ], { name: 'idx_warehouse_op_time' }); + }, + + async down(queryInterface) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20261111203500-change-trace-weight-to-decimal.js b/database/migrations/20261111203500-change-trace-weight-to-decimal.js new file mode 100644 index 0000000..327f34a --- /dev/null +++ b/database/migrations/20261111203500-change-trace-weight-to-decimal.js @@ -0,0 +1,75 @@ +'use strict'; + +/** + * wms_order_express_trace.weight 由 INT 改为 DECIMAL(10,3)。 + * + * 背景:外部轨迹接口返回的 weight 为带小数的字符串(如 "0.99"), + * 原 INT 列会把 0.99 四舍五入/截断为 1 或 0,丢失精度。 + * + * 变更:INT(11) DEFAULT 0 → DECIMAL(10,3) DEFAULT 0(保留原可空性与注释)。 + * + * 注意:MySQL 不支持 INT→DECIMAL 的 INPLACE 变更,只能 COPY(重建表)。 + * 该表为 2026-11-11 新建(轨迹尚在接入期,数据量小),重建代价可接受。 + * 幂等:已是 decimal 时跳过。 + */ + +const TABLE_NAME = 'wms_order_express_trace'; +const COLUMN_NAME = 'weight'; + +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + const [ rows ] = await sequelize.query( + 'SELECT COLUMN_TYPE AS columnType, IS_NULLABLE AS isNullable, ' + + 'COLUMN_DEFAULT AS columnDefault, COLUMN_COMMENT AS columnComment ' + + 'FROM INFORMATION_SCHEMA.COLUMNS ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', + { replacements: [ TABLE_NAME, COLUMN_NAME ] } + ); + + const column = (rows || [])[0]; + if (!column) { + console.log(`[${COLUMN_NAME}] skip: ${TABLE_NAME}.${COLUMN_NAME} 列不存在`); + return; + } + if (String(column.columnType || '').toLowerCase().startsWith('decimal')) { + console.log(`[${COLUMN_NAME}] skip: 已是 DECIMAL(${column.columnType})`); + return; + } + + const nullable = String(column.isNullable).toUpperCase() === 'YES' ? 'NULL' : 'NOT NULL'; + const defaultValue = column.columnDefault === null || column.columnDefault === undefined + ? '' + : ` DEFAULT ${Number(column.columnDefault) || 0}`; + const comment = String(column.columnComment || '').replace(/'/g, "''"); + + await sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN \`${COLUMN_NAME}\` ` + + `DECIMAL(10,3) ${nullable}${defaultValue} COMMENT '${comment}'` + ); + console.log(`[${COLUMN_NAME}] changed to DECIMAL(10,3) on ${TABLE_NAME}`); + }, + + async down(queryInterface) { + const { sequelize } = queryInterface; + const [ rows ] = await sequelize.query( + 'SELECT COLUMN_TYPE AS columnType, IS_NULLABLE AS isNullable, ' + + 'COLUMN_DEFAULT AS columnDefault, COLUMN_COMMENT AS columnComment ' + + 'FROM INFORMATION_SCHEMA.COLUMNS ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', + { replacements: [ TABLE_NAME, COLUMN_NAME ] } + ); + + const column = (rows || [])[0]; + if (!column) return; + if (!String(column.columnType || '').toLowerCase().startsWith('decimal')) return; + + const nullable = String(column.isNullable).toUpperCase() === 'YES' ? 'NULL' : 'NOT NULL'; + const comment = String(column.columnComment || '').replace(/'/g, "''"); + await sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN \`${COLUMN_NAME}\` ` + + `INT(11) ${nullable} DEFAULT 0 COMMENT '${comment}'` + ); + console.log(`[${COLUMN_NAME}] reverted to INT(11)`); + }, +}; diff --git a/database/migrations/20261111205500-drop-wms-order-express-trace.js b/database/migrations/20261111205500-drop-wms-order-express-trace.js new file mode 100644 index 0000000..2844fe3 --- /dev/null +++ b/database/migrations/20261111205500-drop-wms-order-express-trace.js @@ -0,0 +1,74 @@ +'use strict'; + +/** + * 下线运单物流轨迹本地存储:删除 wms_order_express_trace。 + * + * 背景(2026-11-11 业务调整): + * - 轨迹查询改为「全部回源」,`waybill.warehouse.getTrace` 实时调用外部 waybill.getTrace 返回, + * 不再落库;批量同步方法 `waybill.warehouse.updateTrace` / `updateTraceTaskProgress` 一并下线; + * - 因此轨迹表不再需要,删除以免产生无用数据与维护成本。 + * - 揽收联动保留:查询命中轨迹时仍会把 wms_order_express.is_galaxy_receive 置为 Y。 + * + * 说明:本迁移不可逆(数据不再保留),down 仅重建空表结构以便回滚版本时可启动。 + */ + +const TABLE_NAME = 'wms_order_express_trace'; + +module.exports = { + async up(queryInterface) { + const tables = await queryInterface.showAllTables(); + const exists = (tables || []).some(t => { + const name = typeof t === 'string' ? t : (t && (t.tableName || t.name)) || ''; + return String(name).toLowerCase() === TABLE_NAME; + }); + + if (!exists) { + console.log(`[${TABLE_NAME}] skip: 表不存在`); + return; + } + + await queryInterface.dropTable(TABLE_NAME); + console.log(`[${TABLE_NAME}] dropped`); + }, + + async down(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE, JSON: JSON_TYPE, DECIMAL } = Sequelize; + const tables = await queryInterface.showAllTables(); + const exists = (tables || []).some(t => { + const name = typeof t === 'string' ? t : (t && (t.tableName || t.name)) || ''; + return String(name).toLowerCase() === TABLE_NAME; + }); + if (exists) { + console.log(`[${TABLE_NAME}] skip: 表已存在`); + return; + } + + await queryInterface.createTable(TABLE_NAME, { + id: { type: BIGINT(20).UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false, comment: '主键ID' }, + express_id: { type: BIGINT(20).UNSIGNED, allowNull: false, comment: '运单ID(wms_order_express.id)' }, + waybill_code: { type: STRING(50), allowNull: false, comment: '运单号' }, + order_id: { type: BIGINT(20).UNSIGNED, allowNull: true, comment: '订单ID' }, + warehouse_id: { type: BIGINT(20).UNSIGNED, allowNull: false, comment: '仓库ID' }, + op_time: { type: DATE, allowNull: true, comment: '操作时间' }, + out_biz_code: { type: STRING(191), allowNull: true, comment: '外部业务码' }, + memo: { type: STRING(500), allowNull: true, comment: '轨迹描述' }, + op_org_city_name: { type: STRING(100), allowNull: true, comment: '操作机构城市' }, + weight: { type: DECIMAL(10, 3), allowNull: true, defaultValue: 0, comment: '重量(来源原值)' }, + scan_type: { type: STRING(50), allowNull: true, comment: '扫描类型' }, + raw_data: { type: JSON_TYPE, allowNull: true, comment: '原始轨迹报文' }, + created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), comment: '创建时间' }, + updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), comment: '更新时间' }, + deleted_at: { type: DATE, allowNull: true, comment: '软删除时间' }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '运单物流轨迹表(已下线本地存储)', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'express_id', 'op_time', 'scan_type' ], { unique: true, name: 'uk_express_op_scan' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code', 'op_time' ], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'order_id' ], { name: 'idx_order_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'op_time' ], { name: 'idx_warehouse_op_time' }); + console.log(`[${TABLE_NAME}] recreated (empty)`); + }, +}; diff --git a/database/migrations/20261113150000-add-has-sn-item-to-order-delivery.js b/database/migrations/20261113150000-add-has-sn-item-to-order-delivery.js new file mode 100644 index 0000000..dd85f48 --- /dev/null +++ b/database/migrations/20261113150000-add-has-sn-item-to-order-delivery.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * 订单表增加 has_sn_item(是否含序列号管理商品)字段。 + * + * 取值:Y=订单任一明细的 stock_warehouse.is_sn_mgmt='Y',N=否。默认 N。 + * 用途:订单工作台「是否序列号订单」筛选(is_sn_order),并为后续 SN 波次策略提供订单级标记。 + * + * 覆盖范围: + * - 基表 wms_order_delivery; + * - 全部仓库分表 wms_order_delivery_{wh}(current)及 + * _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。 + * + * 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js + * 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +const COLUMN_NAME = 'has_sn_item'; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为基表与全部分表增加 has_sn_item 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.addColumn(tableName, COLUMN_NAME, { + type: Sequelize.ENUM('Y', 'N'), + allowNull: true, + defaultValue: 'N', + comment: '是否含序列号管理商品:Y是 N否', + }); + results.push({ tableName, action: 'added' }); + } + + console.log('[20261113150000-add-has-sn-item-to-order-delivery] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除 base 与全部分表的 has_sn_item 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'missing' }); + continue; + } + + await queryInterface.removeColumn(tableName, COLUMN_NAME); + results.push({ tableName, action: 'removed' }); + } + + console.log('[20261113150000-add-has-sn-item-to-order-delivery] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20261113151000-backfill-order-has-sn-item.js b/database/migrations/20261113151000-backfill-order-has-sn-item.js new file mode 100644 index 0000000..eee60df --- /dev/null +++ b/database/migrations/20261113151000-backfill-order-has-sn-item.js @@ -0,0 +1,194 @@ +'use strict'; + +/** + * 存量订单回填 has_sn_item(是否含序列号管理商品)。 + * + * 口径:订单任一明细的 stock_warehouse.is_sn_mgmt='Y' → has_sn_item='Y',否则保持 'N'。 + * + * 覆盖范围:基表 wms_order_delivery 与全部仓库分表,按分表后缀关联对应订单明细表: + * - wms_order_delivery_{wh} → wms_order_items_{wh} + * - wms_order_delivery_{wh}_history → wms_order_items_{wh}_history + * - wms_order_delivery_{wh}_dispatch → wms_order_items_{wh}_dispatch + * - wms_order_delivery_{wh}_outsourced → wms_order_items_{wh}(外仓明细与常用表共用) + * + * 幂等:先把 Y 重置为 N,再按明细回填 Y,重复执行结果一致。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 判断表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 是否存在。 + */ +async function tableExists(queryInterface, tableName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName LIMIT 1', + { replacements: { tableName } } + ); + return Boolean(rows && rows.length > 0); +} + +/** + * 判断表是否包含指定列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT COLUMN_NAME AS columnName FROM INFORMATION_SCHEMA.COLUMNS ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName AND COLUMN_NAME = :columnName LIMIT 1', + { replacements: { tableName, columnName } } + ); + return Boolean(rows && rows.length > 0); +} + +/** + * 由订单表名推导对应订单明细表名。 + * @param {string} orderTable 订单表名。 + * @return {string|null} 明细表名,无法推导时返回 null。 + */ +function resolveItemsTable(orderTable) { + if (orderTable === BASE_TABLE) { + return 'wms_order_items'; + } + + const matched = SHARD_PATTERN.exec(orderTable); + if (!matched) { + return null; + } + + const warehouseId = matched[1]; + const suffix = matched[2] || ''; + if (suffix === 'history') { + return `wms_order_items_${warehouseId}_history`; + } + if (suffix === 'dispatch') { + return `wms_order_items_${warehouseId}_dispatch`; + } + + return `wms_order_items_${warehouseId}`; +} + +/** + * 提取受影响行数。 + * @param {*} updateResult query 返回结果。 + * @return {number} 受影响行数。 + */ +function extractAffectedRows(updateResult) { + if (Array.isArray(updateResult)) { + const meta = updateResult[1]; + return Number(meta && (meta.affectedRows || meta.affectedCount || meta.rowCount) || 0); + } + if (updateResult && typeof updateResult === 'object') { + return Number(updateResult.affectedRows || updateResult.affectedCount || updateResult.rowCount || 0); + } + return 0; +} + +module.exports = { + /** + * 执行迁移:按订单明细回填 has_sn_item。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await tableExists(queryInterface, tableName)) { + results.push({ tableName, action: 'skip', reason: 'order-table-missing' }); + continue; + } + + const itemsTable = resolveItemsTable(tableName); + if (!itemsTable || !await tableExists(queryInterface, itemsTable)) { + results.push({ tableName, action: 'skip', reason: `items-table-missing:${itemsTable || ''}` }); + continue; + } + + // 兼容旧版基表:wms_order_items(无 stock_id / order_id 的历史结构)无法参与回填 + if (!await columnExists(queryInterface, itemsTable, 'order_id') + || !await columnExists(queryInterface, itemsTable, 'stock_id')) { + results.push({ tableName, action: 'skip', reason: `items-table-unsupported:${itemsTable}` }); + continue; + } + + const resetResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET has_sn_item = 'N' + WHERE has_sn_item = 'Y' + `); + + const updateResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` o + INNER JOIN ( + SELECT DISTINCT oi.order_id + FROM \`${itemsTable}\` oi + INNER JOIN wms_stock_warehouse sw + ON sw.id = oi.stock_id + AND sw.is_sn_mgmt = 'Y' + ) t ON t.order_id = o.id + SET o.has_sn_item = 'Y' + `); + + results.push({ + tableName, + itemsTable, + resetRows: extractAffectedRows(resetResult), + affectedRows: extractAffectedRows(updateResult), + }); + } + + console.log('[20261113151000-backfill-order-has-sn-item] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:全部置回 'N'。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await tableExists(queryInterface, tableName)) { + results.push({ tableName, action: 'skip', reason: 'order-table-missing' }); + continue; + } + + const updateResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET has_sn_item = 'N' + WHERE has_sn_item = 'Y' + `); + results.push({ tableName, affectedRows: extractAffectedRows(updateResult) }); + } + + console.log('[20261113151000-backfill-order-has-sn-item] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20261113160000-enlarge-order-item-sn-code.js b/database/migrations/20261113160000-enlarge-order-item-sn-code.js new file mode 100644 index 0000000..54714b8 --- /dev/null +++ b/database/migrations/20261113160000-enlarge-order-item-sn-code.js @@ -0,0 +1,71 @@ +'use strict'; + +const ORDER_ITEM_SN_TABLE = 'wms_order_item_sn'; +const ORDER_ITEM_SN_LOG_TABLE = 'wms_order_item_sn_log'; +/** SN 编码目标长度:支持以链接/二维码内容作为 SN,同时保证 (warehouse_id, sn_code) 唯一索引不超过 3072 字节 */ +const TARGET_SN_CODE_LENGTH = 512; + +/** + * 读取列当前定义的字符长度。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 当前字符长度,取不到时返回 0。 + */ +const getColumnLength = async (queryInterface, tableName, columnName) => { + const tableDefinition = await queryInterface.describeTable(tableName); + const column = tableDefinition[columnName]; + if (!column) { + return 0; + } + + const length = Number(column.character_maximum_length || column.maxLength || 0); + return Number.isFinite(length) ? length : 0; +}; + +module.exports = { + /** + * 把 SN 编码列扩充到 512 字符(支持链接/二维码内容作为 SN 码)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTables = new Set((await queryInterface.showAllTables()).map(table => ( + typeof table === 'string' ? table : (table.tableName || table.name || '') + ).toLowerCase())); + + for (const tableName of [ ORDER_ITEM_SN_TABLE, ORDER_ITEM_SN_LOG_TABLE ]) { + if (!existingTables.has(tableName)) { + continue; + } + + const currentLength = await getColumnLength(queryInterface, tableName, 'sn_code'); + if (currentLength >= TARGET_SN_CODE_LENGTH) { + continue; + } + + await queryInterface.changeColumn(tableName, 'sn_code', { + type: Sequelize.STRING(TARGET_SN_CODE_LENGTH), + allowNull: false, + comment: 'SN编码(支持链接/二维码内容,最长512字符)', + }); + } + }, + + /** + * 回滚为 128 字符(超长数据会失败,需先清理)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + for (const tableName of [ ORDER_ITEM_SN_TABLE, ORDER_ITEM_SN_LOG_TABLE ]) { + await queryInterface.changeColumn(tableName, 'sn_code', { + type: Sequelize.STRING(128), + allowNull: false, + comment: 'SN编码', + }); + } + }, +}; diff --git a/database/migrations/20261113203000-add-sn-code-rules-to-stock-warehouse.js b/database/migrations/20261113203000-add-sn-code-rules-to-stock-warehouse.js new file mode 100644 index 0000000..14a3200 --- /dev/null +++ b/database/migrations/20261113203000-add-sn-code-rules-to-stock-warehouse.js @@ -0,0 +1,68 @@ +'use strict'; + +/** + * 仓库商品表新增 sn_code_rules(SN 码规则)字段。 + * + * 存储结构(JSON 数组,多条规则按顺序匹配,命中第一条生效): + * [{ "match_type": "prefix|suffix", "match_value": "YGP", "keep_mode": "full|strip" }] + * - match_type:匹配前缀还是后缀; + * - match_value:要匹配的前缀/后缀字符串; + * - keep_mode:full=整个扫码内容作为 SN 码,strip=去掉匹配到的前缀/后缀后再作为 SN 码。 + * + * 用途:复核扫描(order.recheckOrder.scanOrder)把规则下发给 PDA,前端据此校验/加工扫码内容。 + * 幂等:列已存在则跳过。 + */ + +const TABLE_NAME = 'wms_stock_warehouse'; +const COLUMN_NAME = 'sn_code_rules'; + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 新增 sn_code_rules 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造函数。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log(`[20261113203000-add-sn-code-rules-to-stock-warehouse] skip: ${TABLE_NAME}.${COLUMN_NAME} exists`); + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.JSON, + allowNull: true, + defaultValue: null, + comment: 'SN码规则(JSON数组):match_type/match_value/keep_mode,多条按顺序匹配', + }); + + console.log(`[20261113203000-add-sn-code-rules-to-stock-warehouse] added ${TABLE_NAME}.${COLUMN_NAME}`); + }, + + /** + * 回滚:删除 sn_code_rules 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log(`[20261113203000-add-sn-code-rules-to-stock-warehouse] skip: ${TABLE_NAME}.${COLUMN_NAME} missing`); + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + console.log(`[20261113203000-add-sn-code-rules-to-stock-warehouse] removed ${TABLE_NAME}.${COLUMN_NAME}`); + }, +}; diff --git a/database/migrations/20261113233000-add-store-id-and-indexes-to-order-item-sn.js b/database/migrations/20261113233000-add-store-id-and-indexes-to-order-item-sn.js new file mode 100644 index 0000000..5d272f1 --- /dev/null +++ b/database/migrations/20261113233000-add-store-id-and-indexes-to-order-item-sn.js @@ -0,0 +1,160 @@ +'use strict'; + +/** + * wms_order_item_sn 增补货主字段与 SN 码索引。 + * + * 1. 新增 store_id(货主ID,可空):复核落库时从订单冗余,便于按货主隔离查询/统计; + * 历史数据按 order_id + warehouse_id 关联各仓库订单分表回填。 + * 2. 新增 idx_wms_order_item_sn_sn_code:支撑「按 SN 码反查订单」的查询条件 + * (订单列表 where.sn_code → 先查 SN 表拿 order_id 再过滤订单,不改订单表结构); + * 原唯一键 uk_wms_order_item_sn_warehouse_sn_code 以 warehouse_id 打头, + * 单按 sn_code 查询无法使用,故补一条 sn_code 单列索引。 + * 3. 新增 idx_wms_order_item_sn_store_id:按货主过滤/统计。 + * + * 幂等:列与索引已存在则跳过。 + */ + +const TABLE_NAME = 'wms_order_item_sn'; +const COLUMN_NAME = 'store_id'; +const INDEX_SN_CODE = 'idx_wms_order_item_sn_sn_code'; +const INDEX_STORE_ID = 'idx_wms_order_item_sn_store_id'; +/** 订单分表命名:wms_order_delivery_{warehouseId}[_history|_dispatch|_outsourced] */ +const ORDER_SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +/** + * 判断列是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +/** + * 判断索引是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 是否存在。 + */ +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (Array.isArray(indexes) ? indexes : []).some(index => index.name === indexName); +} + +/** + * 列出库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShardTables(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => ORDER_SHARD_PATTERN.test(name)); +} + +/** + * 从订单分表回填 store_id(仅回填尚未赋值的行)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string[]} shardTables 订单分表名。 + * @return {Promise} 每张分表的回填条数。 + */ +async function backfillStoreId(queryInterface, shardTables) { + const results = []; + + for (const tableName of shardTables) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} sn + INNER JOIN ${tableName} o + ON o.id = sn.order_id + AND o.warehouse_id = sn.warehouse_id + SET sn.store_id = o.store_id + WHERE sn.store_id IS NULL + AND o.store_id IS NOT NULL + AND o.store_id > 0` + ); + results.push({ tableName, affectedRows: Number((result && result.affectedRows) || 0) }); + } + + return results; +} + +module.exports = { + /** + * 执行迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造函数。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const log = []; + + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + log.push(`skip column ${COLUMN_NAME} (exists)`); + } else { + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + after: 'warehouse_id', + comment: '货主ID(复核落库时从订单冗余)', + }); + log.push(`added column ${COLUMN_NAME}`); + } + + const shardTables = await listOrderShardTables(queryInterface); + const backfillResults = await backfillStoreId(queryInterface, shardTables); + log.push(`backfill: ${JSON.stringify(backfillResults)}`); + + if (await indexExists(queryInterface, TABLE_NAME, INDEX_SN_CODE)) { + log.push(`skip index ${INDEX_SN_CODE} (exists)`); + } else { + await queryInterface.addIndex(TABLE_NAME, [ 'sn_code' ], { name: INDEX_SN_CODE }); + log.push(`added index ${INDEX_SN_CODE}`); + } + + if (await indexExists(queryInterface, TABLE_NAME, INDEX_STORE_ID)) { + log.push(`skip index ${INDEX_STORE_ID} (exists)`); + } else { + await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: INDEX_STORE_ID }); + log.push(`added index ${INDEX_STORE_ID}`); + } + + console.log('[20261113233000-add-store-id-and-indexes-to-order-item-sn] up:', log.join(' | ')); + }, + + /** + * 回滚:删除索引与 store_id 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const log = []; + + for (const indexName of [ INDEX_SN_CODE, INDEX_STORE_ID ]) { + if (await indexExists(queryInterface, TABLE_NAME, indexName)) { + await queryInterface.removeIndex(TABLE_NAME, indexName); + log.push(`removed index ${indexName}`); + } else { + log.push(`skip index ${indexName} (missing)`); + } + } + + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + log.push(`removed column ${COLUMN_NAME}`); + } else { + log.push(`skip column ${COLUMN_NAME} (missing)`); + } + + console.log('[20261113233000-add-store-id-and-indexes-to-order-item-sn] down:', log.join(' | ')); + }, +}; diff --git a/database/migrations/20261115180000-refactor-wms-order-b2b.js b/database/migrations/20261115180000-refactor-wms-order-b2b.js new file mode 100644 index 0000000..646a3ef --- /dev/null +++ b/database/migrations/20261115180000-refactor-wms-order-b2b.js @@ -0,0 +1,202 @@ +'use strict'; + +/** + * wms_order_b2b 精简重构。 + * + * 变更内容: + * 1. 新增 prep_at(备货完成时间)。 + * 2. 移除 is_print / updated_at / deleted_at / delivery_order_code / store_id: + * - is_print 随 B2B 面单打印能力下线而废弃;打印限制改由订单主表 print_status 决定(且已放开)。 + * - updated_at / deleted_at 移除后作业明细不再软删除。 + * - delivery_order_code / store_id 为快照冗余字段,关联读统一走 warehouse_id + order_id。 + * 3. 唯一键 uk_order_id 改为 uk_warehouse_order(warehouse_id, order_id): + * 分表 id 按仓库各自发号,跨仓可能重叠,只按 order_id 唯一会误伤。 + * 4. 取消 B2B 由软删除改为物理删除:迁移时先清掉历史软删除行,避免移除 deleted_at 后"复活"。 + * + * 幂等:所有列/索引变更前都做存在性判断,重复执行安全。 + * ⚠ 数据不可逆:删除的列与历史软删除行不会保留。 + */ + +const TABLE_NAME = 'wms_order_b2b'; + +/** 需要移除的列 */ +const DROP_COLUMNS = [ 'is_print', 'updated_at', 'deleted_at', 'delivery_order_code', 'store_id' ]; + +/** 需要移除的索引 */ +const DROP_INDEXES = [ 'uk_order_id', 'idx_warehouse_id', 'idx_store_id', 'idx_delivery_order_code', 'idx_is_print', 'idx_deleted_at' ]; + +/** + * 判断索引是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} indexName 索引名。 + * @return {Promise} 是否存在。 + */ +async function indexExists(queryInterface, indexName) { + const indexes = await queryInterface.showIndex(TABLE_NAME); + return (Array.isArray(indexes) ? indexes : []).some(index => { + const name = String(index && (index.name || index.Key_name || index.key_name) || ''); + return name.toLowerCase() === String(indexName).toLowerCase(); + }); +} + +/** + * 安全删除索引(不存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} indexName 索引名。 + * @param {Array} log 执行日志。 + * @return {Promise} 无返回值。 + */ +async function dropIndexIfExists(queryInterface, indexName, log) { + if (!(await indexExists(queryInterface, indexName))) { + log.push({ action: 'skip-drop-index', indexName, reason: 'not-exists' }); + return; + } + await queryInterface.removeIndex(TABLE_NAME, indexName); + log.push({ action: 'drop-index', indexName }); +} + +/** + * 安全删除列(不存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} columnName 列名。 + * @param {Object} columns describeTable 结果。 + * @param {Array} log 执行日志。 + * @return {Promise} 无返回值。 + */ +async function dropColumnIfExists(queryInterface, columnName, columns, log) { + if (!Object.prototype.hasOwnProperty.call(columns, columnName)) { + log.push({ action: 'skip-drop-column', columnName, reason: 'not-exists' }); + return; + } + await queryInterface.removeColumn(TABLE_NAME, columnName); + log.push({ action: 'drop-column', columnName }); +} + +module.exports = { + /** + * 执行迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Object} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const { DATE } = Sequelize; + const log = []; + const query = queryInterface.sequelize; + + let columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns || Object.keys(columns).length === 0) { + throw new Error(`表 ${TABLE_NAME} 不存在,无法执行重构迁移`); + } + + // 1. 历史软删除行清理(deleted_at 即将被移除,不清掉会变成"有效行") + if (Object.prototype.hasOwnProperty.call(columns, 'deleted_at')) { + const [ deletedRows ] = await query.query(`DELETE FROM ${TABLE_NAME} WHERE deleted_at IS NOT NULL`); + log.push({ action: 'delete-soft-deleted-rows', affected: Number(deletedRows && deletedRows.affectedRows || 0) }); + } + + // 2. 同仓同单重复行清理(保留 id 最大的一行),为新唯一键让路 + if (Object.prototype.hasOwnProperty.call(columns, 'warehouse_id') + && Object.prototype.hasOwnProperty.call(columns, 'order_id')) { + const [ dedupeRows ] = await query.query(` + DELETE t FROM ${TABLE_NAME} t + INNER JOIN ${TABLE_NAME} keep + ON keep.warehouse_id = t.warehouse_id + AND keep.order_id = t.order_id + AND keep.id > t.id + `); + log.push({ action: 'delete-duplicate-rows', affected: Number(dedupeRows && dedupeRows.affectedRows || 0) }); + } + + // 3. 新增 prep_at + if (!Object.prototype.hasOwnProperty.call(columns, 'prep_at')) { + await queryInterface.addColumn(TABLE_NAME, 'prep_at', { + type: DATE, + allowNull: true, + comment: '备货完成时间', + }); + log.push({ action: 'add-column', columnName: 'prep_at' }); + } else { + log.push({ action: 'skip-add-column', columnName: 'prep_at', reason: 'exists' }); + } + + // 4. 删除废弃索引(含旧唯一键与冗余 warehouse_id 索引) + for (const indexName of DROP_INDEXES) { + await dropIndexIfExists(queryInterface, indexName, log); + } + + // 5. 建立新的复合唯一键 + if (!(await indexExists(queryInterface, 'uk_warehouse_order'))) { + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'order_id' ], { + name: 'uk_warehouse_order', + unique: true, + }); + log.push({ action: 'add-index', indexName: 'uk_warehouse_order' }); + } else { + log.push({ action: 'skip-add-index', indexName: 'uk_warehouse_order', reason: 'exists' }); + } + + // 6. 删除废弃列 + columns = await queryInterface.describeTable(TABLE_NAME); + for (const columnName of DROP_COLUMNS) { + await dropColumnIfExists(queryInterface, columnName, columns, log); + } + + console.log('[20261115180000-refactor-wms-order-b2b] up results:', JSON.stringify(log)); + }, + + /** + * 回滚迁移:恢复被移除的列与索引(历史数据不可恢复)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Object} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const { DATE, ENUM, STRING, BIGINT } = Sequelize; + const log = []; + + let columns = await queryInterface.describeTable(TABLE_NAME); + + await dropIndexIfExists(queryInterface, 'uk_warehouse_order', log); + + const restoreColumns = [ + [ 'store_id', { type: BIGINT(20).UNSIGNED, allowNull: true, comment: '货主ID' }], + [ 'delivery_order_code', { type: STRING(50), allowNull: true, comment: '发货单号快照' }], + [ 'is_print', { type: ENUM('Y', 'N'), allowNull: false, defaultValue: 'N', comment: '是否打印:Y=已打印 N=未打印' }], + [ 'updated_at', { type: DATE, allowNull: true, comment: '更新时间' }], + [ 'deleted_at', { type: DATE, allowNull: true, comment: '软删除时间' }], + ]; + + for (const [ columnName, definition ] of restoreColumns) { + if (Object.prototype.hasOwnProperty.call(columns, columnName)) { + log.push({ action: 'skip-add-column', columnName, reason: 'exists' }); + continue; + } + await queryInterface.addColumn(TABLE_NAME, columnName, definition); + log.push({ action: 'add-column', columnName }); + } + + const restoreIndexes = [ + [ 'uk_order_id', [ 'order_id' ], true ], + [ 'idx_warehouse_id', [ 'warehouse_id' ], false ], + [ 'idx_store_id', [ 'store_id' ], false ], + [ 'idx_delivery_order_code', [ 'delivery_order_code' ], false ], + [ 'idx_is_print', [ 'is_print' ], false ], + [ 'idx_deleted_at', [ 'deleted_at' ], false ], + ]; + + for (const [ indexName, fields, unique ] of restoreIndexes) { + if (await indexExists(queryInterface, indexName)) { + log.push({ action: 'skip-add-index', indexName, reason: 'exists' }); + continue; + } + await queryInterface.addIndex(TABLE_NAME, fields, { name: indexName, unique }); + log.push({ action: 'add-index', indexName }); + } + + columns = await queryInterface.describeTable(TABLE_NAME); + await dropColumnIfExists(queryInterface, 'prep_at', columns, log); + + console.log('[20261115180000-refactor-wms-order-b2b] down results:', JSON.stringify(log)); + }, +}; diff --git a/database/migrations/20251109160640-init-wms_account.js b/database/migrations/archive/20251109160640-init-wms_account.js similarity index 95% rename from database/migrations/20251109160640-init-wms_account.js rename to database/migrations/archive/20251109160640-init-wms_account.js index bae015e..950495e 100644 --- a/database/migrations/20251109160640-init-wms_account.js +++ b/database/migrations/archive/20251109160640-init-wms_account.js @@ -2,7 +2,7 @@ module.exports = { async up(queryInterface, Sequelize) { - const { BIGINT, STRING, INTEGER, DATE, TINYINT } = Sequelize; + const { BIGINT, STRING, DATE, TINYINT } = Sequelize; await queryInterface.createTable('wms_account', { id: { @@ -102,7 +102,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { await queryInterface.dropTable('wms_account'); }, }; diff --git a/database/migrations/20251110081122-create-wms-account-login-log.js b/database/migrations/archive/20251110081122-create-wms-account-login-log.js similarity index 98% rename from database/migrations/20251110081122-create-wms-account-login-log.js rename to database/migrations/archive/20251110081122-create-wms-account-login-log.js index 06259ed..8d7080a 100644 --- a/database/migrations/20251110081122-create-wms-account-login-log.js +++ b/database/migrations/archive/20251110081122-create-wms-account-login-log.js @@ -100,7 +100,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_account_login_log'" diff --git a/database/migrations/20251110081641-create-wms-qimen-apps.js b/database/migrations/archive/20251110081641-create-wms-qimen-apps.js similarity index 98% rename from database/migrations/20251110081641-create-wms-qimen-apps.js rename to database/migrations/archive/20251110081641-create-wms-qimen-apps.js index ec95c0e..6888e3a 100644 --- a/database/migrations/20251110081641-create-wms-qimen-apps.js +++ b/database/migrations/archive/20251110081641-create-wms-qimen-apps.js @@ -74,7 +74,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_qimen_apps'" diff --git a/database/migrations/20251110082013-create-wms-store.js b/database/migrations/archive/20251110082013-create-wms-store.js similarity index 99% rename from database/migrations/20251110082013-create-wms-store.js rename to database/migrations/archive/20251110082013-create-wms-store.js index 69904ca..9240b4d 100644 --- a/database/migrations/20251110082013-create-wms-store.js +++ b/database/migrations/archive/20251110082013-create-wms-store.js @@ -182,7 +182,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_store'" diff --git a/database/migrations/20251110084033-create-wms-store-warehouse.js b/database/migrations/archive/20251110084033-create-wms-store-warehouse.js similarity index 99% rename from database/migrations/20251110084033-create-wms-store-warehouse.js rename to database/migrations/archive/20251110084033-create-wms-store-warehouse.js index 36e1f33..91b05b1 100644 --- a/database/migrations/20251110084033-create-wms-store-warehouse.js +++ b/database/migrations/archive/20251110084033-create-wms-store-warehouse.js @@ -185,7 +185,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_store_warehouse'" diff --git a/database/migrations/20251110090742-create-wms-interface-type.js b/database/migrations/archive/20251110090742-create-wms-interface-type.js similarity index 98% rename from database/migrations/20251110090742-create-wms-interface-type.js rename to database/migrations/archive/20251110090742-create-wms-interface-type.js index 21a1571..5fbbfc3 100644 --- a/database/migrations/20251110090742-create-wms-interface-type.js +++ b/database/migrations/archive/20251110090742-create-wms-interface-type.js @@ -108,7 +108,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_interface_type'" diff --git a/database/migrations/20251110091013-create-wms-api-app.js b/database/migrations/archive/20251110091013-create-wms-api-app.js similarity index 99% rename from database/migrations/20251110091013-create-wms-api-app.js rename to database/migrations/archive/20251110091013-create-wms-api-app.js index ec44d98..05830f2 100644 --- a/database/migrations/20251110091013-create-wms-api-app.js +++ b/database/migrations/archive/20251110091013-create-wms-api-app.js @@ -207,7 +207,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_api_app'" diff --git a/database/migrations/20251111083733-create-wms-stock-store.js b/database/migrations/archive/20251111083733-create-wms-stock-store.js similarity index 99% rename from database/migrations/20251111083733-create-wms-stock-store.js rename to database/migrations/archive/20251111083733-create-wms-stock-store.js index 173353e..8c246e2 100644 --- a/database/migrations/20251111083733-create-wms-stock-store.js +++ b/database/migrations/archive/20251111083733-create-wms-stock-store.js @@ -285,7 +285,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_stock_store'" diff --git a/database/migrations/20251112085825-create-wms-entry-order.js b/database/migrations/archive/20251112085825-create-wms-entry-order.js similarity index 99% rename from database/migrations/20251112085825-create-wms-entry-order.js rename to database/migrations/archive/20251112085825-create-wms-entry-order.js index 72a6fed..2561536 100644 --- a/database/migrations/20251112085825-create-wms-entry-order.js +++ b/database/migrations/archive/20251112085825-create-wms-entry-order.js @@ -236,7 +236,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_entry_order'" diff --git a/database/migrations/20251112085844-create-wms-entry-items.js b/database/migrations/archive/20251112085844-create-wms-entry-items.js similarity index 98% rename from database/migrations/20251112085844-create-wms-entry-items.js rename to database/migrations/archive/20251112085844-create-wms-entry-items.js index d13fe01..faff43c 100644 --- a/database/migrations/20251112085844-create-wms-entry-items.js +++ b/database/migrations/archive/20251112085844-create-wms-entry-items.js @@ -138,7 +138,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_entry_items'" diff --git a/database/migrations/archive/20260322061000-add-delivery-time-to-order-delivery-tables.js b/database/migrations/archive/20260322061000-add-delivery-time-to-order-delivery-tables.js new file mode 100644 index 0000000..b8e70d1 --- /dev/null +++ b/database/migrations/archive/20260322061000-add-delivery-time-to-order-delivery-tables.js @@ -0,0 +1,63 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'delivery_time' + `, + { replacements: { tableName } } + ); + + if (columns.length === 0) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` ADD COLUMN \`delivery_time\` datetime NULL DEFAULT NULL COMMENT '发货时间' AFTER \`operate_time\`` + ); + } + } + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'delivery_time' + `, + { replacements: { tableName } } + ); + + if (columns.length > 0) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`delivery_time\`` + ); + } + } + }, +}; diff --git a/database/migrations/archive/20260323103000-align-role-permission-fk.js b/database/migrations/archive/20260323103000-align-role-permission-fk.js new file mode 100644 index 0000000..3aca3fe --- /dev/null +++ b/database/migrations/archive/20260323103000-align-role-permission-fk.js @@ -0,0 +1,114 @@ +'use strict'; + +const TABLE = 'wms_role_permission'; +const FK_NAME = 'fk_wms_role_permission_permission'; + +async function getColumnInfo(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_TYPE, IS_NULLABLE + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + LIMIT 1 + `, + { + replacements: { + tableName, + columnName, + }, + } + ); + + return rows[0] || null; +} + +async function hasConstraint(queryInterface, tableName, constraintName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT 1 + FROM information_schema.REFERENTIAL_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND CONSTRAINT_NAME = :constraintName + LIMIT 1 + `, + { + replacements: { + tableName, + constraintName, + }, + } + ); + + return rows.length > 0; +} + +async function getOrphanCount(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM wms_role_permission rp + LEFT JOIN wms_permission p ON p.id = rp.permission_id + WHERE p.id IS NULL + ` + ); + + return Number(rows[0]?.cnt || 0); +} + +module.exports = { + async up(queryInterface) { + const permissionIdColumn = await getColumnInfo(queryInterface, TABLE, 'permission_id'); + if (!permissionIdColumn) { + throw new Error('Column wms_role_permission.permission_id not found.'); + } + + const columnType = String(permissionIdColumn.COLUMN_TYPE || '').toLowerCase(); + + // permission.id is int(11), keep child key type aligned before adding FK. + if (columnType !== 'int(11)') { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role_permission` MODIFY COLUMN `permission_id` int(11) NOT NULL COMMENT \'权限ID\'' + ); + } + + const orphanCount = await getOrphanCount(queryInterface); + if (orphanCount > 0) { + throw new Error( + `Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_role_permission.permission_id. ` + + 'Please clean orphan rows first, then rerun migration.' + ); + } + + const exists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (!exists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role_permission` ' + + 'ADD CONSTRAINT `fk_wms_role_permission_permission` ' + + 'FOREIGN KEY (`permission_id`) REFERENCES `wms_permission` (`id`) ' + + 'ON UPDATE RESTRICT ON DELETE CASCADE' + ); + } + }, + + async down(queryInterface) { + const exists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (exists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role_permission` DROP FOREIGN KEY `fk_wms_role_permission_permission`' + ); + } + + const permissionIdColumn = await getColumnInfo(queryInterface, TABLE, 'permission_id'); + if (permissionIdColumn) { + const columnType = String(permissionIdColumn.COLUMN_TYPE || '').toLowerCase(); + if (columnType !== 'bigint(20) unsigned') { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role_permission` MODIFY COLUMN `permission_id` bigint(20) unsigned NOT NULL COMMENT \'权限ID\'' + ); + } + } + }, +}; diff --git a/database/migrations/archive/20260323113000-add-role-store-fk.js b/database/migrations/archive/20260323113000-add-role-store-fk.js new file mode 100644 index 0000000..353aa89 --- /dev/null +++ b/database/migrations/archive/20260323113000-add-role-store-fk.js @@ -0,0 +1,149 @@ +'use strict'; + +const TABLE = 'wms_role'; +const FK_NAME = 'fk_wms_role_store'; +const INDEX_NAME = 'idx_store_id'; + +async function getColumnInfo(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_TYPE, IS_NULLABLE + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + LIMIT 1 + `, + { + replacements: { + tableName, + columnName, + }, + } + ); + + return rows[0] || null; +} + +async function hasConstraint(queryInterface, tableName, constraintName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT 1 + FROM information_schema.REFERENTIAL_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND CONSTRAINT_NAME = :constraintName + LIMIT 1 + `, + { + replacements: { + tableName, + constraintName, + }, + } + ); + + return rows.length > 0; +} + +async function hasIndex(queryInterface, tableName, indexName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND INDEX_NAME = :indexName + LIMIT 1 + `, + { + replacements: { + tableName, + indexName, + }, + } + ); + + return rows.length > 0; +} + +async function getOrphanCount(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM wms_role r + LEFT JOIN wms_store s ON s.id = r.store_id + WHERE r.store_id IS NOT NULL + AND s.id IS NULL + ` + ); + + return Number(rows[0]?.cnt || 0); +} + +module.exports = { + async up(queryInterface) { + const storeIdColumn = await getColumnInfo(queryInterface, TABLE, 'store_id'); + if (!storeIdColumn) { + throw new Error('Column wms_role.store_id not found.'); + } + + const columnType = String(storeIdColumn.COLUMN_TYPE || '').toLowerCase(); + if (columnType !== 'bigint(20) unsigned') { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` MODIFY COLUMN `store_id` bigint(20) unsigned NULL COMMENT \'所属仓库ID\'' + ); + } + + const orphanCount = await getOrphanCount(queryInterface); + if (orphanCount > 0) { + throw new Error( + `Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_role.store_id. ` + + 'Please clean orphan rows first, then rerun migration.' + ); + } + + const indexExists = await hasIndex(queryInterface, TABLE, INDEX_NAME); + if (!indexExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` ADD INDEX `idx_store_id` (`store_id`)' + ); + } + + const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (!fkExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` ' + + 'ADD CONSTRAINT `fk_wms_role_store` ' + + 'FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ' + + 'ON UPDATE RESTRICT ON DELETE SET NULL' + ); + } + }, + + async down(queryInterface) { + const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (fkExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` DROP FOREIGN KEY `fk_wms_role_store`' + ); + } + + const indexExists = await hasIndex(queryInterface, TABLE, INDEX_NAME); + if (indexExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` DROP INDEX `idx_store_id`' + ); + } + + const storeIdColumn = await getColumnInfo(queryInterface, TABLE, 'store_id'); + if (storeIdColumn) { + const columnType = String(storeIdColumn.COLUMN_TYPE || '').toLowerCase(); + if (columnType !== 'bigint(20)') { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_role` MODIFY COLUMN `store_id` bigint(20) NULL COMMENT \'所属仓库ID\'' + ); + } + } + }, +}; diff --git a/database/migrations/archive/20260323123000-add-permission-parent-fk.js b/database/migrations/archive/20260323123000-add-permission-parent-fk.js new file mode 100644 index 0000000..a1321d1 --- /dev/null +++ b/database/migrations/archive/20260323123000-add-permission-parent-fk.js @@ -0,0 +1,108 @@ +'use strict'; + +const TABLE = 'wms_permission'; +const FK_NAME = 'fk_wms_permission_parent'; + +async function hasConstraint(queryInterface, tableName, constraintName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT 1 + FROM information_schema.REFERENTIAL_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND CONSTRAINT_NAME = :constraintName + LIMIT 1 + `, + { + replacements: { + tableName, + constraintName, + }, + } + ); + + return rows.length > 0; +} + +async function getOrphanCount(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM wms_permission p + LEFT JOIN wms_permission pp ON pp.id = p.parent_id + WHERE p.parent_id IS NOT NULL + AND p.parent_id <> 0 + AND pp.id IS NULL + ` + ); + + return Number(rows[0]?.cnt || 0); +} + +async function getSelfLoopCount(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM wms_permission + WHERE parent_id = id + ` + ); + + return Number(rows[0]?.cnt || 0); +} + +module.exports = { + async up(queryInterface) { + const orphanCount = await getOrphanCount(queryInterface); + if (orphanCount > 0) { + throw new Error( + `Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_permission.parent_id.` + ); + } + + const selfLoopCount = await getSelfLoopCount(queryInterface); + if (selfLoopCount > 0) { + throw new Error( + `Cannot add ${FK_NAME}: found ${selfLoopCount} self-loop rows (id = parent_id) in wms_permission.` + ); + } + + // Normalize root sentinel to NULL before adding FK. + await queryInterface.sequelize.query( + 'UPDATE `wms_permission` SET `parent_id` = NULL WHERE `parent_id` = 0' + ); + + await queryInterface.sequelize.query( + "ALTER TABLE `wms_permission` MODIFY COLUMN `parent_id` int(11) NULL DEFAULT NULL COMMENT '父级ID(根节点为NULL)'" + ); + + const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (!fkExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_permission` ' + + 'ADD CONSTRAINT `fk_wms_permission_parent` ' + + 'FOREIGN KEY (`parent_id`) REFERENCES `wms_permission` (`id`) ' + + 'ON UPDATE RESTRICT ON DELETE SET NULL' + ); + } + + // Root node normalization from 0->NULL is handled in application model setters. + }, + + async down(queryInterface) { + const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); + if (fkExists) { + await queryInterface.sequelize.query( + 'ALTER TABLE `wms_permission` DROP FOREIGN KEY `fk_wms_permission_parent`' + ); + } + + await queryInterface.sequelize.query( + 'UPDATE `wms_permission` SET `parent_id` = 0 WHERE `parent_id` IS NULL' + ); + + await queryInterface.sequelize.query( + "ALTER TABLE `wms_permission` MODIFY COLUMN `parent_id` int(11) NULL DEFAULT 0 COMMENT '父级ID'" + ); + }, +}; diff --git a/database/migrations/archive/20260404093000-add-policy-config-to-wms-store-warehouse.js b/database/migrations/archive/20260404093000-add-policy-config-to-wms-store-warehouse.js new file mode 100644 index 0000000..39475c5 --- /dev/null +++ b/database/migrations/archive/20260404093000-add-policy-config-to-wms-store-warehouse.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_store_warehouse', 'policy_config', { + type: Sequelize.JSON, + allowNull: true, + comment: '货主在仓库的配置与策略', + }); + }, + + async down(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_store_warehouse', 'policy_config'); + }, +}; diff --git a/database/migrations/archive/20260404113000-create-wms-notification-webhook.js b/database/migrations/archive/20260404113000-create-wms-notification-webhook.js new file mode 100644 index 0000000..77e274f --- /dev/null +++ b/database/migrations/archive/20260404113000-create-wms-notification-webhook.js @@ -0,0 +1,154 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, TINYINT, DATE, JSON } = Sequelize; + const BIGINT_UNSIGNED = BIGINT.UNSIGNED; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_webhook'" + ); + + const tableExists = tables.length > 0; + + if (!tableExists) { + await queryInterface.createTable('wms_notification_webhook', { + id: { + type: BIGINT_UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + store_id: { + type: BIGINT_UNSIGNED, + allowNull: false, + comment: '主体ID,对应 wms_store.id', + references: { + model: 'wms_store', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'CASCADE', + }, + hook_name: { + type: STRING(100), + allowNull: true, + comment: 'Webhook 名称', + }, + hook_type: { + type: STRING(50), + allowNull: false, + comment: 'Webhook 类型,用于分派不同消息结构处理类,如 dingtalk、wecom、feishu、custom', + }, + hook_url: { + type: STRING(500), + allowNull: false, + comment: 'Webhook 链接地址', + }, + events: { + type: JSON, + allowNull: true, + comment: '订阅事件列表', + }, + extra_config: { + type: JSON, + allowNull: true, + comment: '扩展配置,如签名、请求头、模板映射等', + }, + status: { + type: TINYINT(4), + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用,1-启用', + }, + remark: { + type: STRING(255), + allowNull: true, + comment: '备注', + }, + created_by: { + type: BIGINT_UNSIGNED, + allowNull: true, + 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: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_unicode_ci', + comment: '外部通知 WebHook 配置表', + }); + } else { + console.log('Table wms_notification_webhook already exists, ensuring schema and indexes'); + } + + const [ hookUrlColumns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_notification_webhook` LIKE 'hook_url'"); + if (hookUrlColumns.length > 0) { + const currentType = String(hookUrlColumns[0].Type || '').toLowerCase(); + if (currentType.includes('varchar(1000)')) { + await queryInterface.changeColumn('wms_notification_webhook', 'hook_url', { + type: STRING(500), + allowNull: false, + comment: 'Webhook 链接地址', + }); + } + } + + 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_notification_webhook', [ 'store_id' ], { + name: 'idx_notification_webhook_store_id', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'hook_type' ], { + name: 'idx_notification_webhook_hook_type', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'status' ], { + name: 'idx_notification_webhook_status', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'store_id', 'hook_type' ], { + name: 'idx_notification_webhook_store_type', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'store_id', 'hook_type', 'hook_url' ], { + name: 'uk_notification_webhook_store_type_url', + unique: true, + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_webhook'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_notification_webhook'); + } + }, +}; diff --git a/database/migrations/archive/20260405002000-add-expire-time-to-wms-file.js b/database/migrations/archive/20260405002000-add-expire-time-to-wms-file.js new file mode 100644 index 0000000..fb3a9e8 --- /dev/null +++ b/database/migrations/archive/20260405002000-add-expire-time-to-wms-file.js @@ -0,0 +1,26 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_file` LIKE 'expire_time'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_file', 'expire_time', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '过期时间,为空表示永不过期', + }); + }, + + async down(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_file` LIKE 'expire_time'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_file', 'expire_time'); + }, +}; diff --git a/database/migrations/archive/20260405011000-add-subject-config-to-wms-store.js b/database/migrations/archive/20260405011000-add-subject-config-to-wms-store.js new file mode 100644 index 0000000..25e379a --- /dev/null +++ b/database/migrations/archive/20260405011000-add-subject-config-to-wms-store.js @@ -0,0 +1,26 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_store', 'subject_config', { + type: Sequelize.JSON, + allowNull: true, + defaultValue: null, + comment: '主体配置JSON', + }); + }, + + async down(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_store', 'subject_config'); + }, +}; diff --git a/database/migrations/archive/20260405013000-init-wms-store-subject-config-webhook-limit.js b/database/migrations/archive/20260405013000-init-wms-store-subject-config-webhook-limit.js new file mode 100644 index 0000000..9309614 --- /dev/null +++ b/database/migrations/archive/20260405013000-init-wms-store-subject-config-webhook-limit.js @@ -0,0 +1,28 @@ +'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_SET(COALESCE(subject_config, JSON_OBJECT()), '$.max_notice_webhook_count', 5) + `); + }, + + 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, '$.max_notice_webhook_count') + WHERE subject_config IS NOT NULL + `); + }, +}; diff --git a/database/migrations/archive/20260405015000-drop-extra-config-from-notification-webhook.js b/database/migrations/archive/20260405015000-drop-extra-config-from-notification-webhook.js new file mode 100644 index 0000000..4c1242b --- /dev/null +++ b/database/migrations/archive/20260405015000-drop-extra-config-from-notification-webhook.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_notification_webhook` LIKE 'extra_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_notification_webhook', 'extra_config'); + }, + + async down(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_notification_webhook` LIKE 'extra_config'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_notification_webhook', 'extra_config', { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展配置,如签名、请求头、模板映射等', + }); + }, +}; diff --git a/database/migrations/archive/20260405024000-create-wms-notification-send-log.js b/database/migrations/archive/20260405024000-create-wms-notification-send-log.js new file mode 100644 index 0000000..2f52cb2 --- /dev/null +++ b/database/migrations/archive/20260405024000-create-wms-notification-send-log.js @@ -0,0 +1,152 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE, INTEGER, JSON } = Sequelize; + const BIGINT_UNSIGNED = BIGINT.UNSIGNED; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_send_log'" + ); + + if (tables.length === 0) { + await queryInterface.createTable('wms_notification_send_log', { + id: { + type: BIGINT_UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + trace_id: { + type: STRING(100), + allowNull: false, + comment: '通知追踪ID', + }, + webhook_id: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: 'Webhook 配置ID', + }, + store_id: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '触发主体ID', + }, + warehouse_id: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '仓库ID', + }, + owner_store_id: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + business_name: { + type: STRING(100), + allowNull: false, + comment: '业务名称', + }, + event: { + type: STRING(100), + allowNull: false, + comment: '事件名', + }, + hook_type: { + type: STRING(50), + allowNull: true, + comment: 'Webhook 类型', + }, + hook_url: { + type: STRING(500), + allowNull: true, + comment: 'Webhook 地址', + }, + request_payload: { + type: JSON, + allowNull: true, + comment: '请求载荷', + }, + response_payload: { + type: JSON, + allowNull: true, + comment: '返回载荷', + }, + http_status: { + type: INTEGER(11), + allowNull: true, + comment: 'HTTP 状态码', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'failed', + comment: '发送状态', + }, + error_message: { + type: STRING(1000), + allowNull: true, + comment: '失败原因', + }, + retry_count: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + created_by: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '创建人', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + 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_notification_send_log', [ 'trace_id' ], { + name: 'idx_notification_send_log_trace_id', + }); + + await safeCreateIndex('wms_notification_send_log', [ 'event', 'status' ], { + name: 'idx_notification_send_log_event_status', + }); + + await safeCreateIndex('wms_notification_send_log', [ 'webhook_id' ], { + name: 'idx_notification_send_log_webhook_id', + }); + + await safeCreateIndex('wms_notification_send_log', [ 'created_at' ], { + name: 'idx_notification_send_log_created_at', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_send_log'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_notification_send_log'); + } + }, +}; diff --git a/database/migrations/archive/20260407153000-create-wms-store-warehouse-print-quantity-log.js b/database/migrations/archive/20260407153000-create-wms-store-warehouse-print-quantity-log.js new file mode 100644 index 0000000..cda65b9 --- /dev/null +++ b/database/migrations/archive/20260407153000-create-wms-store-warehouse-print-quantity-log.js @@ -0,0 +1,160 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, TEXT, DATE } = Sequelize; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_store_warehouse_print_quantity_log'" + ); + + if (tables.length > 0) { + console.log('Table wms_store_warehouse_print_quantity_log already exists, skipping creation'); + return; + } + + await queryInterface.createTable('wms_store_warehouse_print_quantity_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + contract_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'wms_store_warehouse', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'NO ACTION', + comment: '签约关系ID,对应 wms_store_warehouse.id', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'wms_store', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'NO ACTION', + comment: '货主ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'wms_store', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'NO ACTION', + comment: '仓库ID', + }, + change_type: { + type: STRING(50), + allowNull: false, + comment: '变更类型,如 manual_adjust / order_deduct', + }, + business_type: { + type: STRING(50), + allowNull: true, + comment: '业务来源类型,如 order_express', + }, + business_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '业务关联ID,预留关联 wms_order_express.id', + }, + change_quantity: { + type: BIGINT(20), + allowNull: false, + comment: '本次变更数量,整数,可正可负', + }, + balance_before: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更前余额', + }, + balance_after: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更后余额', + }, + reason: { + type: TEXT, + allowNull: true, + comment: '变更缘由;人工调整时必填', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人账号ID', + }, + created_by: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人账号ID', + }, + 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: '货主-仓库签约面单余额变更记录表', + }); + + 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_store_warehouse_print_quantity_log', [ 'contract_id', 'id' ], { + name: 'idx_sw_print_qty_log_contract_id', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'store_id', 'warehouse_id' ], { + name: 'idx_sw_print_qty_log_store_warehouse', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'business_type', 'business_id' ], { + name: 'idx_sw_print_qty_log_business', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'change_type' ], { + name: 'idx_sw_print_qty_log_change_type', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'created_at' ], { + name: 'idx_sw_print_qty_log_created_at', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_store_warehouse_print_quantity_log'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_store_warehouse_print_quantity_log'); + } + }, +}; diff --git a/database/migrations/archive/20260407160000-add-receiving-id-to-wms-storage.js b/database/migrations/archive/20260407160000-add-receiving-id-to-wms-storage.js new file mode 100644 index 0000000..45e2010 --- /dev/null +++ b/database/migrations/archive/20260407160000-add-receiving-id-to-wms-storage.js @@ -0,0 +1,35 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'receiving_id'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_storage', 'receiving_id', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '收货单ID', + after: 'inbound_order_no', + }); + + await queryInterface.addIndex('wms_storage', [ 'receiving_id' ], { + name: 'idx_receiving_id', + }); + }, + + async down(queryInterface) { + const [ indexes ] = await queryInterface.sequelize.query( + "SHOW INDEX FROM `wms_storage` WHERE Key_name = 'idx_receiving_id'" + ); + if (indexes.length > 0) { + await queryInterface.removeIndex('wms_storage', 'idx_receiving_id'); + } + + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'receiving_id'"); + if (columns.length > 0) { + await queryInterface.removeColumn('wms_storage', 'receiving_id'); + } + }, +}; diff --git a/database/migrations/archive/20260408100000-add-entry-order-id-to-wms-storage.js b/database/migrations/archive/20260408100000-add-entry-order-id-to-wms-storage.js new file mode 100644 index 0000000..a88bb5e --- /dev/null +++ b/database/migrations/archive/20260408100000-add-entry-order-id-to-wms-storage.js @@ -0,0 +1,41 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'entry_order_id'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_storage', 'entry_order_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库单ID', + after: 'receiving_id', + references: { + model: 'wms_entry_order', + key: 'id', + }, + onDelete: 'SET NULL', + onUpdate: 'CASCADE', + }); + + await queryInterface.addIndex('wms_storage', [ 'entry_order_id' ], { + name: 'idx_entry_order_id', + }); + }, + + async down(queryInterface) { + const [ indexes ] = await queryInterface.sequelize.query( + "SHOW INDEX FROM `wms_storage` WHERE Key_name = 'idx_entry_order_id'" + ); + if (indexes.length > 0) { + await queryInterface.removeIndex('wms_storage', 'idx_entry_order_id'); + } + + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'entry_order_id'"); + if (columns.length > 0) { + await queryInterface.removeColumn('wms_storage', 'entry_order_id'); + } + }, +}; diff --git a/database/migrations/archive/20260408120000-add-callback-url-to-api-app.js b/database/migrations/archive/20260408120000-add-callback-url-to-api-app.js new file mode 100644 index 0000000..15e8693 --- /dev/null +++ b/database/migrations/archive/20260408120000-add-callback-url-to-api-app.js @@ -0,0 +1,18 @@ +'use strict'; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_api_app', 'callback_url', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: 'API回调通知URL', + after: 'self_ip_whitelist', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_api_app', 'callback_url'); + }, +}; diff --git a/database/migrations/archive/20260408140000-create-wms-stock-transaction.js b/database/migrations/archive/20260408140000-create-wms-stock-transaction.js new file mode 100644 index 0000000..1ef7427 --- /dev/null +++ b/database/migrations/archive/20260408140000-create-wms-stock-transaction.js @@ -0,0 +1,189 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, ENUM, DATE } = Sequelize; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_stock_transaction'" + ); + + if (tables.length > 0) { + console.log('Table wms_stock_transaction already exists, skipping creation'); + return; + } + + await queryInterface.createTable('wms_stock_transaction', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + transaction_type: { + type: ENUM('INBOUND', 'OUTBOUND'), + allowNull: false, + comment: '出入库类型', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品库存ID,关联 wms_stock_warehouse.id', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位库存ID,关联 wms_storage.id', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + comment: '变动数量(正数)', + }, + before_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }, + after_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }, + before_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }, + after_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }, + batch_no: { + type: STRING(100), + allowNull: true, + comment: '批次号', + }, + inventory_type: { + type: ENUM('ZP', 'CC', 'JS', 'XS', 'ZT', 'DJ', 'FP'), + defaultValue: 'ZP', + comment: '库存类型', + }, + order_type: { + type: STRING(50), + allowNull: true, + comment: '关联单据类型', + }, + order_no: { + type: STRING(100), + allowNull: true, + comment: '关联单据号', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联单据ID', + }, + receiving_id: { + type: INTEGER, + allowNull: true, + comment: '关联收货单ID', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID', + }, + operator_id: { + type: STRING(100), + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: STRING(100), + allowNull: true, + comment: '操作人名称', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_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_stock_transaction', [ 'stock_id' ], { + name: 'idx_stock_id', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'warehouse_id', 'created_at' ], { + name: 'idx_warehouse_time', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'order_type', 'order_id' ], { + name: 'idx_order', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'receiving_id' ], { + name: 'idx_receiving_id', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'entry_order_id' ], { + name: 'idx_entry_order_id', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'created_at' ], { + name: 'idx_created_at', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'store_id', 'transaction_type' ], { + name: 'idx_store_transaction_type', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_stock_transaction'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_stock_transaction'); + } + }, +}; diff --git a/database/migrations/archive/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js b/database/migrations/archive/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js new file mode 100644 index 0000000..0909653 --- /dev/null +++ b/database/migrations/archive/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js @@ -0,0 +1,63 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { INTEGER } = Sequelize; + const tableName = 'wms_stock_transaction'; + const tableInfo = await queryInterface.describeTable(tableName); + + const columns = [ + [ 'before_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }], + [ 'after_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }], + [ 'before_locked_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }], + [ 'after_locked_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }], + ]; + + for (const [ columnName, columnDefinition ] of columns) { + if (tableInfo[columnName]) { + continue; + } + + await queryInterface.addColumn(tableName, columnName, columnDefinition); + } + }, + + async down(queryInterface) { + const tableName = 'wms_stock_transaction'; + const tableInfo = await queryInterface.describeTable(tableName).catch(() => null); + if (!tableInfo) { + return; + } + + const columns = [ + 'after_locked_quantity', + 'before_locked_quantity', + 'after_quantity', + 'before_quantity', + ]; + + for (const columnName of columns) { + if (!tableInfo[columnName]) { + continue; + } + + await queryInterface.removeColumn(tableName, columnName); + } + }, +}; diff --git a/database/migrations/archive/20260410100000-alter-wms-stock-warehouse-negative-quantity.js b/database/migrations/archive/20260410100000-alter-wms-stock-warehouse-negative-quantity.js new file mode 100644 index 0000000..da2ccf0 --- /dev/null +++ b/database/migrations/archive/20260410100000-alter-wms-stock-warehouse-negative-quantity.js @@ -0,0 +1,81 @@ +'use strict'; + +async function getColumnType(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_TYPE + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + LIMIT 1 + `, + { + replacements: { + tableName, + columnName, + }, + } + ); + + return String(rows[0]?.COLUMN_TYPE || '').toLowerCase(); +} + +async function changeSignedQuantityColumns(queryInterface, Sequelize, direction) { + const tableName = 'wms_stock_warehouse'; + const quantityType = direction === 'up' + ? Sequelize.INTEGER(11) + : Sequelize.INTEGER(11).UNSIGNED; + + const lockedQuantityType = direction === 'up' + ? Sequelize.INTEGER(11) + : Sequelize.INTEGER(11).UNSIGNED; + + const quantityColumnType = await getColumnType(queryInterface, tableName, 'quantity').catch(() => ''); + if (direction === 'up' && quantityColumnType.includes('unsigned')) { + await queryInterface.changeColumn(tableName, 'quantity', { + type: quantityType, + allowNull: false, + defaultValue: 0, + comment: '库存数量', + }); + } + + const lockedColumnType = await getColumnType(queryInterface, tableName, 'locked_quantity').catch(() => ''); + if (direction === 'up' && lockedColumnType.includes('unsigned')) { + await queryInterface.changeColumn(tableName, 'locked_quantity', { + type: lockedQuantityType, + allowNull: false, + defaultValue: 0, + comment: '锁定数量', + }); + } + + if (direction === 'down' && !quantityColumnType.includes('unsigned')) { + await queryInterface.changeColumn(tableName, 'quantity', { + type: quantityType, + allowNull: false, + defaultValue: 0, + comment: '库存数量', + }); + } + + if (direction === 'down' && !lockedColumnType.includes('unsigned')) { + await queryInterface.changeColumn(tableName, 'locked_quantity', { + type: lockedQuantityType, + allowNull: false, + defaultValue: 0, + comment: '锁定数量', + }); + } +} + +module.exports = { + async up(queryInterface, Sequelize) { + await changeSignedQuantityColumns(queryInterface, Sequelize, 'up'); + }, + + async down(queryInterface, Sequelize) { + await changeSignedQuantityColumns(queryInterface, Sequelize, 'down'); + }, +}; diff --git a/database/migrations/archive/20260410120000-add-log-id-to-qimen-log.js b/database/migrations/archive/20260410120000-add-log-id-to-qimen-log.js new file mode 100644 index 0000000..f068cda --- /dev/null +++ b/database/migrations/archive/20260410120000-add-log-id-to-qimen-log.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query('SHOW COLUMNS FROM `wms_qimen_log` LIKE \'log_id\''); + if (columns.length > 0) { + const [ idxs ] = await queryInterface.sequelize.query('SHOW INDEX FROM `wms_qimen_log` WHERE Key_name = \'idx_log_id\''); + if (idxs.length === 0) { + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` ADD UNIQUE INDEX `idx_log_id` (`log_id`)'); + } + return; + } + + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` ADD COLUMN `log_id` VARCHAR(32) DEFAULT NULL AFTER `id`'); + const [ idxs2 ] = await queryInterface.sequelize.query('SHOW INDEX FROM `wms_qimen_log` WHERE Key_name = \'idx_log_id\''); + if (idxs2.length === 0) { + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` ADD UNIQUE INDEX `idx_log_id` (`log_id`)'); + } + }, + + async down(queryInterface) { + const [ indexes ] = await queryInterface.sequelize.query('SHOW INDEX FROM `wms_qimen_log` WHERE Key_name = \'idx_log_id\''); + if (indexes.length > 0) { + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` DROP INDEX `idx_log_id`'); + } + + const [ columns ] = await queryInterface.sequelize.query('SHOW COLUMNS FROM `wms_qimen_log` LIKE \'log_id\''); + if (columns.length > 0) { + await queryInterface.sequelize.query('ALTER TABLE `wms_qimen_log` DROP COLUMN `log_id`'); + } + }, +}; diff --git a/database/migrations/archive/20260410130000-add-audit-status-to-order-delivery-tables.js b/database/migrations/archive/20260410130000-add-audit-status-to-order-delivery-tables.js new file mode 100644 index 0000000..9af7483 --- /dev/null +++ b/database/migrations/archive/20260410130000-add-audit-status-to-order-delivery-tables.js @@ -0,0 +1,88 @@ +'use strict'; + +module.exports = { + /** + * 为发货单主表及分表新增 audit_status 字段。 + * 若存在 inspection_status,则将 audit_status 放在其后;否则按默认位置新增,保证兼容旧库结构。 + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 + * @return {Promise} 无返回值 + */ + async up(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'audit_status' + `, + { replacements: { tableName } } + ); + + if (columns.length === 0) { + const [ inspectionColumns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'inspection_status' + `, + { replacements: { tableName } } + ); + + const alterSql = inspectionColumns.length > 0 + ? `ALTER TABLE \`${tableName}\` ADD COLUMN \`audit_status\` enum('pending','approved','rejected') DEFAULT 'pending' COMMENT '审批状态' AFTER \`inspection_status\`` + : `ALTER TABLE \`${tableName}\` ADD COLUMN \`audit_status\` enum('pending','approved','rejected') DEFAULT 'pending' COMMENT '审批状态'`; + + await queryInterface.sequelize.query(alterSql); + } + } + }, + + /** + * 回滚删除发货单主表及分表的 audit_status 字段。 + * 仅在字段存在时删除,保证回滚幂等且安全。 + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + const [ columns ] = await queryInterface.sequelize.query( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = 'audit_status' + `, + { replacements: { tableName } } + ); + + if (columns.length > 0) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`audit_status\`` + ); + } + } + }, +}; diff --git a/database/migrations/archive/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js b/database/migrations/archive/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js new file mode 100644 index 0000000..96fda06 --- /dev/null +++ b/database/migrations/archive/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js @@ -0,0 +1,122 @@ +'use strict'; + +const STEP_COMMENT = '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭'; +const AUDIT_STATUS_COMMENT = '审批状态'; + +/** + * 判断数据表是否存在指定字段。 + * + * @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( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return columns.length > 0; +} + +/** + * 查找发货单主表及分表。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 表名列表。 + */ +async function findOrderDeliveryTables(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%') + `); + + return tables.map(row => row.TABLE_NAME); +} + +module.exports = { + /** + * 为发货单主表及分表新增 step 字段,并从 audit_status 回填后删除 audit_status。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const tables = await findOrderDeliveryTables(queryInterface); + + for (const tableName of tables) { + const hasStep = await hasColumn(queryInterface, tableName, 'step'); + const hasAuditStatus = await hasColumn(queryInterface, tableName, 'audit_status'); + + if (!hasStep) { + const hasInspectionStatus = await hasColumn(queryInterface, tableName, 'inspection_status'); + const addStepSql = hasInspectionStatus + ? `ALTER TABLE \`${tableName}\` ADD COLUMN \`step\` int(10) NOT NULL DEFAULT 0 COMMENT '${STEP_COMMENT}' AFTER \`inspection_status\`` + : `ALTER TABLE \`${tableName}\` ADD COLUMN \`step\` int(10) NOT NULL DEFAULT 0 COMMENT '${STEP_COMMENT}'`; + await queryInterface.sequelize.query(addStepSql); + } + + if (hasAuditStatus) { + await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET \`step\` = CASE \`audit_status\` + WHEN 'approved' THEN 1 + WHEN 'rejected' THEN 3 + ELSE 0 + END + `); + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`audit_status\`` + ); + } + } + }, + + /** + * 回滚恢复 audit_status 字段,并根据 step 回填后删除 step。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = await findOrderDeliveryTables(queryInterface); + + for (const tableName of tables) { + const hasStep = await hasColumn(queryInterface, tableName, 'step'); + const hasAuditStatus = await hasColumn(queryInterface, tableName, 'audit_status'); + + if (!hasAuditStatus) { + const hasInspectionStatus = await hasColumn(queryInterface, tableName, 'inspection_status'); + const addAuditStatusSql = hasInspectionStatus + ? `ALTER TABLE \`${tableName}\` ADD COLUMN \`audit_status\` enum('pending','approved','rejected') DEFAULT 'pending' COMMENT '${AUDIT_STATUS_COMMENT}' AFTER \`inspection_status\`` + : `ALTER TABLE \`${tableName}\` ADD COLUMN \`audit_status\` enum('pending','approved','rejected') DEFAULT 'pending' COMMENT '${AUDIT_STATUS_COMMENT}'`; + await queryInterface.sequelize.query(addAuditStatusSql); + } + + if (hasStep) { + await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET \`audit_status\` = CASE + WHEN \`step\` = 1 THEN 'approved' + WHEN \`step\` = 3 THEN 'rejected' + ELSE 'pending' + END + `); + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`step\`` + ); + } + } + }, +}; diff --git a/database/migrations/archive/20260410200000-add-status-columns-to-wms-order-delivery-base.js b/database/migrations/archive/20260410200000-add-status-columns-to-wms-order-delivery-base.js new file mode 100644 index 0000000..86bfa5a --- /dev/null +++ b/database/migrations/archive/20260410200000-add-status-columns-to-wms-order-delivery-base.js @@ -0,0 +1,174 @@ +'use strict'; + +const TABLE = 'wms_order_delivery'; + +/** + * 与 `app/model/order_delivery.js`、`order_delivery_factory.js` 中 DDL 一致。 + * `up` 仅对缺失列执行 ADD;`down` 按逆序删除下列列(若存在)——若某列在迁移前已存在且含数据,请勿执行 down。 + * + * 列顺序与工厂建表一致,便于 `AFTER` 链式追加时相对位置稳定。 + */ +const STATUS_MACHINE_COLUMNS = [ + { + name: 'sync_status', + ddl: "enum('padding','fin','error') DEFAULT 'padding'", + comment: '同步状态', + after: 'oaid', + }, + { + name: 'post_status', + ddl: "enum('padding','fin','timeout','error','none') DEFAULT 'none'", + comment: '分配快递号状态机', + after: 'wave_id', + }, + { + name: 'storage_status', + ddl: "enum('padding','fin','error','none') DEFAULT 'none'", + comment: '分配储位状态机', + after: 'post_status', + }, + { + name: 'pick_status', + ddl: "enum('padding','fin','error','none') DEFAULT 'none'", + comment: '拣货状态机', + after: 'storage_status', + }, + { + name: 'pack_status', + ddl: "enum('none','padding','fin','error') DEFAULT 'none'", + comment: '打包状态机', + after: 'pick_status', + }, + { + name: 'inspection_status', + ddl: "enum('none','padding','running','fin','error') DEFAULT 'none'", + comment: '检验状态机', + after: 'pack_status', + }, + { + name: 'print_status', + ddl: "enum('none','padding','fin','error') DEFAULT NULL", + comment: '打印状态机', + after: 'step', + }, + { + name: 'claim_status', + ddl: "enum('none','padding','fin','error') DEFAULT 'none'", + comment: '领取状态机', + after: 'print_status', + }, + { + name: 'outbound_status', + ddl: "enum('none','padding','fin','error') DEFAULT 'none'", + comment: '出库状态机', + after: 'claim_status', + }, + { + name: 'lock_status', + ddl: "enum('none','warehouse','store') DEFAULT NULL", + comment: '锁定状态机', + after: 'outbound_status', + }, + { + name: 'intercept_status', + ddl: + "enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') DEFAULT NULL", + comment: '拦截状态机', + after: 'lock_status', + }, +]; + +/** + * @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( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + return columns.length > 0; +} + +/** + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 数据表名。 + * @return {Promise} 数据表是否存在。 + */ +async function tableExists(queryInterface, tableName) { + const [ rows ] = await queryInterface.sequelize.query( + ` + SELECT COUNT(*) AS cnt + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + `, + { replacements: { tableName } } + ); + return Number(rows[0].cnt) > 0; +} + +/** + * @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))) { + return `AFTER \`${preferredAfter}\``; + } + return ''; +} + +module.exports = { + /** + * 仅为基表 `wms_order_delivery` 按需补状态机相关列;已存在则跳过。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + if (!(await tableExists(queryInterface, TABLE))) { + return; + } + + for (const col of STATUS_MACHINE_COLUMNS) { + if (await hasColumn(queryInterface, TABLE, col.name)) { + continue; + } + const afterPart = await resolveAfterClause(queryInterface, TABLE, col.after); + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE}\` ADD COLUMN \`${col.name}\` ${col.ddl} COMMENT '${col.comment}' ${afterPart}`.trim() + ); + } + }, + + /** + * 逆序删除本文件声明的状态机列(若存在)。见文件头注释。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!(await tableExists(queryInterface, TABLE))) { + return; + } + const reversed = [ ...STATUS_MACHINE_COLUMNS ].reverse(); + for (const col of reversed) { + if (await hasColumn(queryInterface, TABLE, col.name)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE}\` DROP COLUMN \`${col.name}\`` + ); + } + } + }, +}; diff --git a/database/migrations/archive/20260415000000-init-wms-store-subject-config-default-codes.js b/database/migrations/archive/20260415000000-init-wms-store-subject-config-default-codes.js new file mode 100644 index 0000000..1b706a2 --- /dev/null +++ b/database/migrations/archive/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 + `); + }, +}; diff --git a/database/migrations/archive/20260415172000-create-wms-express-interface.js b/database/migrations/archive/20260415172000-create-wms-express-interface.js new file mode 100644 index 0000000..0ddde60 --- /dev/null +++ b/database/migrations/archive/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'); + } + }, +}; diff --git a/database/migrations/archive/20260415190000-create-wms-picking.js b/database/migrations/archive/20260415190000-create-wms-picking.js new file mode 100644 index 0000000..363949d --- /dev/null +++ b/database/migrations/archive/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/archive/20260415191000-add-quantity-to-wms-picking.js b/database/migrations/archive/20260415191000-add-quantity-to-wms-picking.js new file mode 100644 index 0000000..422fdbb --- /dev/null +++ b/database/migrations/archive/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'); + } + }, +}; diff --git a/database/migrations/archive/20260417153000-add-deleted-at-to-wms-express-setting.js b/database/migrations/archive/20260417153000-add-deleted-at-to-wms-express-setting.js new file mode 100644 index 0000000..982c676 --- /dev/null +++ b/database/migrations/archive/20260417153000-add-deleted-at-to-wms-express-setting.js @@ -0,0 +1,63 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { DATE } = Sequelize; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_express_setting'" + ); + + if (tables.length === 0) { + return; + } + + const [ columns ] = await queryInterface.sequelize.query( + "SHOW COLUMNS FROM `wms_express_setting` LIKE 'deleted_at'" + ); + + if (columns.length === 0) { + await queryInterface.addColumn('wms_express_setting', 'deleted_at', { + type: DATE, + allowNull: true, + comment: '删除时间', + }); + } + + const [ indexes ] = await queryInterface.sequelize.query( + "SHOW INDEX FROM `wms_express_setting` WHERE Key_name = 'idx_warehouse_deleted_at'" + ); + + if (indexes.length === 0) { + await queryInterface.addIndex('wms_express_setting', [ 'warehouse_id', 'deleted_at' ], { + name: 'idx_warehouse_deleted_at', + }); + } + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_express_setting'" + ); + + if (tables.length === 0) { + return; + } + + const [ indexes ] = await queryInterface.sequelize.query( + "SHOW INDEX FROM `wms_express_setting` WHERE Key_name = 'idx_warehouse_deleted_at'" + ); + + if (indexes.length > 0) { + await queryInterface.removeIndex('wms_express_setting', 'idx_warehouse_deleted_at'); + } + + const [ columns ] = await queryInterface.sequelize.query( + "SHOW COLUMNS FROM `wms_express_setting` LIKE 'deleted_at'" + ); + + if (columns.length > 0) { + await queryInterface.removeColumn('wms_express_setting', 'deleted_at'); + } + }, +}; diff --git a/database/migrations/archive/20260419102000-add-weight-type-to-order-delivery-tables.js b/database/migrations/archive/20260419102000-add-weight-type-to-order-delivery-tables.js new file mode 100644 index 0000000..a01089c --- /dev/null +++ b/database/migrations/archive/20260419102000-add-weight-type-to-order-delivery-tables.js @@ -0,0 +1,108 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_delivery'; +const TABLE_LIKE_PATTERN = 'wms_order_delivery\\_%'; +const COLUMN_NAME = 'weight_type'; +const COLUMN_DDL = 'int(11) NOT NULL DEFAULT 0'; +const COLUMN_COMMENT = '重量类型:0常规、1轻货、2重货、3冷链'; +const PREFERRED_AFTER = 'delivery_type'; + +/** + * 获取发货单主表及所有分表名称。 + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise>} 表名查询结果。 + */ +async function getOrderDeliveryTables(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = '${TABLE_NAME}' OR TABLE_NAME LIKE '${TABLE_LIKE_PATTERN}') + `); + + return tables; +} + +/** + * 判断表中是否存在指定字段。 + * @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( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return columns.length > 0; +} + +/** + * 解析 ADD COLUMN 的 AFTER 子句。 + * 当目标表存在 `delivery_type` 时,优先追加到其后;否则返回空串,直接追加到表尾。 + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} AFTER 子句或空字符串。 + */ +async function resolveAfterClause(queryInterface, tableName) { + if (await hasColumn(queryInterface, tableName, PREFERRED_AFTER)) { + return ` AFTER \`${PREFERRED_AFTER}\``; + } + + return ''; +} + +module.exports = { + /** + * 为发货单主表及分表补齐 `weight_type` 字段。 + * 仅在字段缺失时执行 ADD COLUMN,并尽量放在 `delivery_type` 后面。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const tables = await getOrderDeliveryTables(queryInterface); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + if (await hasColumn(queryInterface, tableName, COLUMN_NAME)) { + continue; + } + + const afterClause = await resolveAfterClause(queryInterface, tableName); + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` ADD COLUMN \`${COLUMN_NAME}\` ${COLUMN_DDL} COMMENT '${COLUMN_COMMENT}'${afterClause}` + ); + } + }, + + /** + * 回滚删除发货单主表及分表的 `weight_type` 字段。 + * 仅在字段存在时执行 DROP COLUMN,保证回滚幂等。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = await getOrderDeliveryTables(queryInterface); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + if (await hasColumn(queryInterface, tableName, COLUMN_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`${COLUMN_NAME}\`` + ); + } + } + }, +}; diff --git a/database/migrations/archive/20260420101000-alter-order-flag-to-longtext-on-order-delivery-tables.js b/database/migrations/archive/20260420101000-alter-order-flag-to-longtext-on-order-delivery-tables.js new file mode 100644 index 0000000..9290d7a --- /dev/null +++ b/database/migrations/archive/20260420101000-alter-order-flag-to-longtext-on-order-delivery-tables.js @@ -0,0 +1,93 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_delivery'; +const TABLE_LIKE_PATTERN = 'wms_order_delivery\\_%'; +const COLUMN_NAME = 'order_flag'; +const UP_COLUMN_DDL = "LONGTEXT NULL COMMENT '订单标记'"; +const DOWN_COLUMN_DDL = "VARCHAR(200) NULL COMMENT '订单标记'"; + +/** + * 获取发货单主表及所有分表名称。 + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise>} 表名查询结果。 + */ +async function getOrderDeliveryTables(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = '${TABLE_NAME}' OR TABLE_NAME LIKE '${TABLE_LIKE_PATTERN}') + `); + + return tables; +} + +/** + * 判断表中是否存在指定字段。 + * @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( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return columns.length > 0; +} + +module.exports = { + /** + * 将发货单主表及分表的 `order_flag` 调整为 LONGTEXT。 + * 仅在目标表存在且字段存在时执行 MODIFY COLUMN,保证幂等。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const tables = await getOrderDeliveryTables(queryInterface); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + if (!(await hasColumn(queryInterface, tableName, COLUMN_NAME))) { + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${COLUMN_NAME}\` ${UP_COLUMN_DDL}` + ); + } + }, + + /** + * 将发货单主表及分表的 `order_flag` 回滚为 VARCHAR(200)。 + * 仅在目标表存在且字段存在时执行 MODIFY COLUMN,保证幂等。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = await getOrderDeliveryTables(queryInterface); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + if (!(await hasColumn(queryInterface, tableName, COLUMN_NAME))) { + continue; + } + + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${COLUMN_NAME}\` ${DOWN_COLUMN_DDL}` + ); + } + }, +}; diff --git a/database/migrations/archive/20260420112000-add-source-order-codes-to-order-delivery-tables.js b/database/migrations/archive/20260420112000-add-source-order-codes-to-order-delivery-tables.js new file mode 100644 index 0000000..3e2cd6d --- /dev/null +++ b/database/migrations/archive/20260420112000-add-source-order-codes-to-order-delivery-tables.js @@ -0,0 +1,107 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_delivery'; +const TABLE_LIKE_PATTERN = 'wms_order_delivery\\_%'; +const COLUMN_NAME = 'source_order_codes'; +const COLUMN_DDL = "TEXT NULL COMMENT '来源订单号集合'"; +const PREFERRED_AFTER = 'source_platform_name'; + +/** + * 获取发货单主表及所有分表名称。 + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise>} 表名查询结果。 + */ +async function getOrderDeliveryTables(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query(` + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND (TABLE_NAME = '${TABLE_NAME}' OR TABLE_NAME LIKE '${TABLE_LIKE_PATTERN}') + `); + + return tables; +} + +/** + * 判断表中是否存在指定字段。 + * @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( + ` + SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND COLUMN_NAME = :columnName + `, + { replacements: { tableName, columnName } } + ); + + return columns.length > 0; +} + +/** + * 解析 ADD COLUMN 的 AFTER 子句。 + * 当目标表存在 `source_platform_name` 时,优先追加到其后;否则返回空串,直接追加到表尾。 + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} AFTER 子句或空字符串。 + */ +async function resolveAfterClause(queryInterface, tableName) { + if (await hasColumn(queryInterface, tableName, PREFERRED_AFTER)) { + return ` AFTER \`${PREFERRED_AFTER}\``; + } + + return ''; +} + +module.exports = { + /** + * 为发货单主表及分表补齐 `source_order_codes` 字段。 + * 仅在字段缺失时执行 ADD COLUMN,并尽量放在 `source_platform_name` 后面。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const tables = await getOrderDeliveryTables(queryInterface); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + if (await hasColumn(queryInterface, tableName, COLUMN_NAME)) { + continue; + } + + const afterClause = await resolveAfterClause(queryInterface, tableName); + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` ADD COLUMN \`${COLUMN_NAME}\` ${COLUMN_DDL}${afterClause}` + ); + } + }, + + /** + * 回滚删除发货单主表及分表的 `source_order_codes` 字段。 + * 仅在字段存在时执行 DROP COLUMN,保证回滚幂等。 + * + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = await getOrderDeliveryTables(queryInterface); + + for (const row of tables) { + const tableName = row.TABLE_NAME; + + if (await hasColumn(queryInterface, tableName, COLUMN_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${tableName}\` DROP COLUMN \`${COLUMN_NAME}\`` + ); + } + } + }, +}; diff --git a/docs/api-doc-update-spec.example.json b/docs/api-doc-update-spec.example.json new file mode 100644 index 0000000..30e8c9b --- /dev/null +++ b/docs/api-doc-update-spec.example.json @@ -0,0 +1,49 @@ +{ + "docName": "example", + "newDoc": { + "module": "example", + "description": "示例文档(由 docs/api-doc-update-spec.example.json 复制而来,正式使用时请按需修改 docName/newDoc/group/methods/change)", + "http": { "path": "/example", "method": "POST" }, + "headers": [ + { "name": "Content-Type", "type": "string", "required": true, "description": "application/json" } + ] + }, + "docMeta": { + "version": "0.1.0", + "updatedAt": "2026-09-12" + }, + "group": { + "groupName": "示例分组", + "module": "example" + }, + "methods": [ + { + "method": "example.ping", + "description": "示例方法:演示固定 spec 的最小结构。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { "name": "name", "type": "string", "required": true, "source": "query", "description": "示例入参" } + ], + "response": [ + { "name": "ok", "type": "boolean", "required": true, "description": "是否成功" } + ], + "errors": [ + { "code": 400, "message": "参数错误" } + ], + "notes": [ + "params 允许 source(query/body);headers/response 不写 source;response 项必须含 boolean 的 required" + ] + } + ], + "deleteMethods": [], + "change": { + "version": "2026.09.12-example-init", + "date": "2026-09-12", + "type": "added", + "summary": "示例变更记录。", + "methods": [ "example.ping" ], + "notes": [ "正式使用时请替换为真实的 version/summary/methods/notes,并确保 version 不重复" ] + } +} diff --git a/docs/api-doc-update-workflow.md b/docs/api-doc-update-workflow.md new file mode 100644 index 0000000..d8473c2 --- /dev/null +++ b/docs/api-doc-update-workflow.md @@ -0,0 +1,190 @@ +# API 文档更新工作流(`script/update-api-doc.cjs`) + +> 本文档说明 `methods/*.json`(接口文档 SSOT)与 `methods/changes/*.json`(变更记录)的**唯一合规写入方式**: +> 通过 `npm run doc:api:update -- --spec=` 执行,禁止直接手写这两个目录下的 JSON。 +> 内容以 `script/update-api-doc.cjs` 实际实现为准;回归测试见 `test/scripts/update_api_doc.test.cjs`(13 用例)。 + +## 1. 命令用法 + +```powershell +npm run doc:api:update -- --spec= # 正式写入(主文档 + 变更记录) +npm run doc:api:update -- --spec= --dry-run # 只校验并打印计划,不写任何文件 +npm run doc:api:update -- --spec= --doc-only # 只写 methods/.json,跳过变更记录 +npm run doc:api:update -- --help # 打印用法、选项与 spec.newDoc 说明(-h 等价) +``` + +- `--spec=`:必填;相对路径按项目根目录(`process.cwd()`)解析。缺省报 `Missing required --spec= argument.`;文件不存在报 `Spec file not found: `。 +- 脚本底层等价于 `node ./script/update-api-doc.cjs --spec=`,npm 层需要 `--` 分隔符传递参数。 + +## 2. spec 结构(固定 spec JSON) + +```json +{ + "docName": "system", + "docMeta": { "version": "1.2.0", "updatedAt": "2026-09-12" }, + "group": { "groupName": "分组展示名", "module": "分组 module" }, + "methods": [ { "method": "...", "description": "...", "isNeedAuth": true, "isNeedLogin": false, "headers": [], "params": [], "response": [], "errors": [], "notes": [] } ], + "deleteMethods": [ "要删除的.method" ], + "change": { "version": "唯一版本号", "date": "2026-09-12", "type": "updated", "summary": "...", "methods": [ "..." ], "notes": [ "..." ] } +} +``` + +| 字段 | 必填 | 说明 | +|---|---|---| +| `docName` | 是 | 目标文档名;仅允许字母、数字、下划线、横线(`^[a-z0-9_-]+$`)。对应 `methods/.json` 与 `methods/changes/.json` | +| `docMeta` | 否 | `{ version, updatedAt, description }` 均可选;写入后覆盖主文档根部的 `version` / `updatedAt` / `description`(`description` 为字符串时生效,可用于更正根说明文案) | +| `group` | 是 | `{ groupName, module }` 均为非空字符串。定位已有分组时**先按 `module` 匹配,再按 `groupName`**;找不到则新建分组 | +| `methods` | 是 | 至少 1 条 method 文档;按 `group` + `method` 做 upsert,不覆盖其它分组/方法 | +| `deleteMethods` | 否 | 要删除的 method 名数组;不能与 `methods` 中的 method 重名,否则报 `Method conflict` | +| `change` | 否 | 变更记录对象(`--doc-only` 模式下可省略)。详见第 5 节 | + +### 2.1 method 文档条目(`methods[]` 每一条) + +- 必填键:`method` / `description` / `isNeedAuth`(boolean)/ `isNeedLogin`(boolean)/ `headers`(数组)/ `params`(数组)/ `response`(数组)/ `errors`(数组)。 +- `notes` 可选(字符串数组,写入后保留在 method 文档内)。 + +### 2.2 upsert 语义 + +- method 不存在 → `inserted`(追加到目标分组 list 尾部)。 +- method 已存在且在同一分组 → `updated`(整条覆盖)。 +- method 已存在但在其它分组 → `moved`(从原分组移除后写入目标分组)。 +- `deleteMethods` 命中 → `deleted`;未命中 → `delete-not-found`(不报错,仅提示)。 +- 脚本逐条打印 `inserted:` / `updated:` / `moved:` / `deleted:` / `delete-not-found:` 行。 + +## 3. 字段级硬性校验(报错即拒绝写入) + +| 校验点 | 规则 | +|---|---| +| `docName` | 非空字符串,仅字母/数字/下划线/横线 | +| `docMeta.description`(可选) | 若提供必须为字符串(可为空串,表示清空根说明);非字符串报 `spec.docMeta.description must be a string.` | +| `group.groupName` / `group.module` | 非空字符串 | +| `methods[].method` / `description` | 非空字符串;spec 内 method 名不允许重复(`Duplicate method in spec.methods`) | +| `methods[].isNeedAuth` / `isNeedLogin` | **必须为 boolean** | +| `methods[].headers` / `params` / `response` / `errors` | 必须为数组 | +| `headers[]` / `params[]` / `response[]` 每一项 | `name` / `type` / `description` 非空字符串;**`required` 必须为 boolean**(非布尔报 `xxx.required must be a boolean`) | +| `source` 字段 | **仅 `params[]` 允许**(`allowSource=true`,如 `query` / `body`);`headers[]` / `response[]` 不校验 `source`,因此不要在这两处写 `source` | +| 可选 `list` 字段 | 必须是数组,且每一项必须含 `value` 键 | +| `errors[]` 每一项 | 必须含 `code` 键(数字或字符串均可,如 `400` / `5xx`)+ 非空字符串 `message` | +| `deleteMethods[]` | 字符串数组;与 `methods[]` 中的 method 重名时报 `Method conflict` | +| `change` | 见第 5 节 | + +## 4. 新增文档能力(`spec.newDoc`,2026-09-12 新增) + +目标 `methods/.json` **不存在**时,spec 必须提供 `newDoc`,脚本自动生成文档骨架后再应用 `group` / `methods`;否则报: + +``` +Target doc file not found: (provide spec.newDoc to create it) +``` + +### 4.1 `newDoc` 字段与规则 + +| 字段 | 规则 | +|---|---| +| `module` | **必填**,非空字符串 → 新文档根 `module` | +| `description` | 可选,string;缺省 `""` | +| `http` | 可选,object;缺省 `{ "path": "", "method": "POST" }` | +| `headers` | 可选,array;缺省 `[]` | +| `version` / `updatedAt` / `methods` | **保留键**:由骨架统一管理(`version`/`updatedAt` 取自 `docMeta`,`methods` 固定为 `{ groups: [] }`),写在 `newDoc` 里不生效、不参与透传,也不报错 | +| 其它未知字段 | 仅接受 plain JSON 值(null/字符串/数字/布尔/对象/数组,递归校验),**原样透传**到新文档根(供未来扩展) | + +### 4.2 骨架与落盘行为 + +- 新文档骨架:`{ module, description, version, updatedAt, http, headers, methods: { groups: [] } }`;`version` 取 `docMeta.version`(缺省 `0.0.0`),`updatedAt` 取 `docMeta.updatedAt`(缺省本地今天 `YYYY-MM-DD`)。 +- `methods/changes/.json` 不存在时视为空数组,正式写入时自动创建(目录递归创建),内容为仅含本次 `change` 的数组。 +- **新建文件统一为 2 空格缩进 + LF**;已存在的文件保留原缩进与 EOL 风格(最小 diff)。 +- doc **已存在**时 `spec.newDoc` 被忽略(与不传 `newDoc` 落盘结果逐字节一致,有测试覆盖)。 +- dry-run 对将要新建的文件打印 `created: <相对路径>` 计划行,但不写盘。 + +### 4.3 示例(一次完成新建 + 写入) + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-create.json --dry-run +npm run doc:api:update -- --spec=temp/api-doc-create.json +``` + +## 5. 变更记录(`methods/changes/.json`) + +- `change` 必填键:`version`(非空字符串,**不得与既有记录重复**,重复报 `Duplicate change version detected`)/ `date` / `summary` / `methods`(字符串数组)/ `notes`(字符串数组)。 +- `type` 可选(如 `added` / `updated`)。 +- 新记录**插入数组头部**(`unshift`),与现有约定一致;历史记录不回改。 +- 建议记录至少包含:`version`、`date`、`summary`、`methods`、`notes`。 + +## 6. 推荐流程 + +1. 核对代码与调用链(`controller / systemMethods / systems / model / test`),确定 method、参数、响应、错误码的真实口径。 +2. 在 `temp/apiDoc/` 下先备份对应时间点的 `methods/.json` 与 `methods/changes/.json`(自动归档与人工回档都在该目录)。 +3. 组织固定 spec JSON(可从已有 spec 或 `docs/api-doc-update-spec.example.json` 复制后编辑)。 +4. 先执行 dry-run 校验并查看 `inserted:` / `updated:` / `deleted:` / `created:` 计划行。 +5. 确认无误后正式执行写入。 +6. 校验落盘文件:`JSON.parse` 可解析、缩进/EOL 与写入前一致(新建文件为 2 空格 + LF)。 +7. 再同步 `docs/*.md` / `README.md` 等解释性文档。 + +## 7. `--doc-only` 的适用场景 + +- 仅修补 `methods/.json` 本身、**不追加变更记录**时使用(例如变更记录 `version` 与既有记录重复且只想修正主文档,慎用)。 +- `--doc-only` 下 spec 可省略 `change`;若提供了 `change` 仍会做字段校验(不写 changes 文件)。 +- 注意:`--doc-only` 属于旁路,正式接口变更仍应走完整流程(主文档 + 变更记录)。 + +## 8. 环境变量钩子(仅测试用) + +- `WMS_API_DOC_METHODS_DIR`:覆盖主文档目录(默认 `methods/`)。 +- `WMS_API_DOC_CHANGES_DIR`:覆盖变更记录目录(默认 `methods/changes/`)。 +- 脚本在**模块加载时**读取这两个变量(`path.resolve` 解析)。仅用于测试目录隔离(如 `test/scripts/update_api_doc.test.cjs` 注入临时目录),业务运行不要设置。 + +## 9. 输出样例 + +dry-run(新建场景): + +``` +docName: sample +group: sample (示例分组) +inserted: sample.echo +updated: - +moved: - +deleted: - +delete-not-found: - +change version: 2026.09.12-sample +created: methods/sample.json +created: methods/changes/sample.json +dry-run: validated successfully, no files were written. +``` + +正式写入(既有文档): + +``` +docName: openapi_callback +group: callback (出站回调事件) +inserted: deliveryorder.cancel +updated: entryorder.confirm, entryorder.match, deliveryorder.confirm, stockout.confirm +moved: - +deleted: order.cancel +delete-not-found: - +change version: 2026.09.12-openapi-callback-protocol-align +wrote: methods/openapi_callback.json +wrote: methods/changes/openapi_callback.json +``` + +## 10. 常见坑(校验报错对照) + +| 报错 / 现象 | 原因与处理 | +|---|---| +| `Missing required --spec= argument.` | 未传 `--spec=`(npm 调用需加 `--` 分隔符) | +| `Spec file not found: ` | spec 路径不存在或相对路径解析基准不对(按项目根解析) | +| `spec.docName must contain only letters, numbers, underscore, or dash.` | `docName` 含非法字符 | +| `spec.methods must contain at least one method doc.` | `methods` 为空数组 | +| `spec.methods[0].response[0].required must be a boolean.` | `required` 不是布尔(写了字符串 `"true"` 等) | +| `Duplicate method in spec.methods: xxx` | spec 内 method 名重复 | +| `Method conflict: xxx appears in both spec.methods and spec.deleteMethods.` | 同一 method 同时出现在增改与删除列表 | +| `Target doc file not found: (provide spec.newDoc to create it)` | 目标文档不存在且未提供 `spec.newDoc` | +| `spec.newDoc.module must be a non-empty string.` | `newDoc` 缺 `module` 或为空白字符串 | +| `spec.newDoc.custom must be a plain JSON value.` | `newDoc` 未知透传字段不是 plain JSON 值(如函数) | +| `Duplicate change version detected: xxx` | changes 中已有同 `version` 记录;更换 version,或确认只想补主文档时用 `--doc-only` | +| 变更记录里方法名带 `spec.` 前缀报错 | 字段路径为 spec 内路径提示,指向的仍是 method 文档字段本身 | + +## 11. 回归测试 + +```powershell +node test/scripts/update_api_doc.test.cjs +``` + +覆盖 13 用例:`spec.newDoc` 新建骨架、保留键不透传、doc 已存在时 `newDoc` 被忽略、changes 自动创建、`--doc-only` 不建 changes、dry-run 不写盘、`--help` 输出、新建文件 2 空格 + LF 等。 diff --git a/docs/openapi-callback-events.md b/docs/openapi-callback-events.md new file mode 100644 index 0000000..0f070be --- /dev/null +++ b/docs/openapi-callback-events.md @@ -0,0 +1,455 @@ +# OpenAPI 出站回调事件说明 + +> 状态:2026-09-13 破坏性协议变更已落代码(报文体 `{ event, data, metadata }` → `{ request }`;`deliveryorder.confirm` 改为逐单「先回调、成功再扣减库存并置已同步」,失败置 `error` + 待处理异常)。 +> 本文档描述 WMS 主动向外部系统推送的 **OpenAPI 出站回调**(出站 HTTP 回调)协议。 +> 与 `methods/openapi.json` 描述的**入站** OpenAPI method(`POST /openapi`)方向相反;本文档不属于 `methods/*.json` 的 SSOT 范围。 + +## 1. 破坏性变更说明 + +### 1.1 2026-09-13:报文体改为奇门同层级 `{ request }` + +- 报文体由 `{ event, data, metadata }` 改为奇门同层级的 `{ request: {...} }`;发送端不再发送数据/元数据,`event` 仅出现在 query 的 `method`。 +- 5 个事件的 `request` 结构与奇门对应接口的 `request` 节点同层级(字段口径见第 3 节,与注册表 `request` 模板一致)。 +- `deliveryorder.confirm` 通知对象口径变化:改动前一次回调携带整批 `orderIds`(含失败/跳过);改后 API 渠道**逐单在同步时**发送(同一个分发循环,成功 N 单 = N 次回调),且**回调成功才扣减库存并置 `sync_status='fin'`**;回调失败/异常、报文组装或 appKey 解析失败 → 该单同步失败(`sync_status='error'` + 待处理异常,不扣减库存,可重新派发),详见 3.3。 +- 旧报文结构(`{ event, data, metadata }`)已全部废弃:无新旧兼容、无双发,接收方必须同步改造。 + +### 1.2 2026-09-12:事件名改为 模块.动作(历史,仍有效) + +- 出站回调的 `method`(query 参数)原先使用 snake_case 事件名(如 `stockout_completed`),现统一改为 `模块.动作`(如 `stockout.confirm`),与奇门 method 去掉 `taobao.qimen.` 前缀后对齐。 +- 旧事件名已**全部废弃**:无新旧兼容、无双发。接收方必须同步改造;仅当接收方按 `模块.动作` 校验 method 时,新协议可正常通过(此前会报 400「参数缺失或错误: method(需为 模块.动作,如 index.ping)」)。 +- 回调事件 `order.cancel` 更名为 `deliveryorder.cancel`:与 `/openapi` 入站方法 `order.cancel`(取消单据接口,见 `methods/openapi.json`)同名,若接收方将 `callback_url` 误指向 WMS `/openapi` 会被路由到真正的取消单据接口;不做兼容、不双发,旧名 `order.cancel`(出站方向)已废弃。 + +| 旧(事件名,已废弃) | 新(method) | 触发场景 | 实现位置 | +|---|---|---|---| +| `entry_order_direct_inbound_completed` | `entryorder.confirm` | 直入入库(API 来源)完成 | `app/service/systems/inbound_direct_log.js` | +| `entry_order_receiving_matched` | `entryorder.match` | 入库单匹配收货单完成 | `app/service/systems/receiving_entry_match.js` | +| `order_completed` | `deliveryorder.confirm` | API 渠道订单同步时逐单发送(回调成功才扣减库存并置已同步) | `app/service/systems/order_async.js` | +| `stockout_completed` | `stockout.confirm` | 出库单确认完成 | `app/service/systems/order_async.js` | +| `order_cancelled` | `deliveryorder.cancel` | 订单取消成功(旧 method 名 `order.cancel` 已废弃) | `app/service/openapiMethods/order.js` | + +事件注册表:`app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS`(5 条,每条含 `name` / `label` / `description` / `request`,`request` 为奇门同层级报文模板),回调调试页 `GET /docs/api/openapi/callback-test`(`app/controller/openapiCallback.js`)直接消费该注册表,并按注册表自动预填完整报文体 `{ request: {...} }`(可编辑)。 + +## 2. 协议说明 + +### 2.1 出站请求与 query 参数 + +``` +POST {callbackUrl}?method={模块.动作}&v=1.0×tamp={timestamp}&app_key={selfAppKey}&sign={sign} +``` + +`callbackUrl` 来自 `api_app` 表(`callback_url` 字段,要求 `is_enabled=1` 且 `callback_url` 非空)。 + +> 签约关系级接口配置(`storeWarehouse.store.saveApiConfig`)不再接收 `callback_url` 入参:保存时统一写入 `config.openapi.defaultCallbackUrl`(未配置时写 `null`),因此上表取值实际由该配置项决定,修改回调地址需调整环境配置后重新保存接口配置。 + +| query 参数 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `method` | string | 是 | 回调 method,`模块.动作` 格式(与奇门对应接口对应;报文体不再携带 `event` 字段);URL 中做 `encodeURIComponent` | +| `v` | string | 是 | 协议版本,固定 `1.0` | +| `timestamp` | string | 是 | 时间戳,秒级(10 位字符串),见第 4 节 | +| `app_key` | string | 是 | 应用标识(`api_app.self_app_key`);URL 中做 `encodeURIComponent` | +| `sign` | string | 是 | 签名,算法见 2.4 | + +### 2.2 请求头 + +``` +Content-Type: application/json +``` + +### 2.3 请求体结构 + +```json +{ + "request": { "…": "…" } +} +``` + +- `request` 为奇门同层级业务报文,结构按事件不同,口径见第 3 节(与注册表 `request` 模板一致)。 +- `event` 不出现在报文体内,仅拼入 query 的 `method`。 +- 构造位置:`app/service/openapi/callback.js#sendWithRetry`(`body = { request: request || {} }`);`sendByAppKey` 将 `request` 原样透传给 `sendWithRetry`。 + +### 2.4 签名算法 + +实现:`app/lib/api_sign.js#signRequest`(与 OpenAPI 入口验签算法一致)。 + +1. `canonicalQuery`:query 中除 `sign` / `signature`(大小写不敏感)外、值非 `undefined` 的参数,按 key 字母序升序,拼为 `key=value&key2=value2`。值为原始字符串(**不 URL 编码**);对象值经 `stableStringify`。 +2. `bodySign = md5(stableStringify(body))`;`stableStringify` 对对象键做字母序排序后 JSON 序列化;`body` 即完整报文 `{ request: {...} }`。 +3. `sign = md5(canonicalQuery + selfAppSecret + bodySign)`,小写十六进制。 + +注意: + +- 参与签名的是**未 URL 编码的原值**;实际 URL 中仅 `method`、`app_key` 做了 `encodeURIComponent`。 +- `selfAppSecret` 为 `api_app.self_app_secret`(`signRequest` 内部会 `trim`)。 + +canonicalQuery 示例(`method=entryorder.confirm`): + +``` +app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0 +``` + +### 2.5 重试策略 + +实现:`app/service/openapi/callback.js#sendWithRetry`。 + +- 最多重试 `MAX_RETRY=3` 次(即最多共 4 次尝试)。 +- 间隔:`[2000, 5000, 15000]` 毫秒(2s → 5s → 15s)。 +- 触发条件:非 2xx 响应或网络错误(异常 catch)。 +- 单次请求超时:30s(`ctx.curl` `timeout: 30000`)。 +- 每次尝试经 `logCallback` 记录日志:`[OpenapiCallback] event=… appKey=… url=… retry=N success=… response=…`(成功 info、中途失败 warn、最终失败 error)。 +- `deliveryorder.confirm` 单订单发送 4 次尝试后仍失败 ⇒ 该订单同步判定失败:`sync_status='error'` + 待处理异常,**不扣减库存**、不置 `fin`,订单可重新派发。 + +### 2.6 发送途径与配置解析 + +| 途径 | 配置解析 | 使用的事件 | +|---|---|---| +| `sendByAppKey` | 按 `app_key` 查 `ApiApp`(`self_app_key=appKey, is_enabled=1`),取 `self_app_secret` 与 `callback_url` | `deliveryorder.confirm`、`stockout.confirm`、`deliveryorder.cancel` | +| `sendWithRetry` 直调 | 按 `StoreWarehouse`(`store_id/warehouse_id, auth_status=2`)→ `ApiApp`(`contract_id=storeWarehouse.id, is_enabled=1, callback_url` 非空)定位 | `entryorder.confirm`、`entryorder.match` | + +调试/测试工具: + +- 调试页:`GET /docs/api/openapi/callback-test`(`app/controller/openapiCallback.js`,路由见 `app/router.js`),按注册表渲染事件下拉,选中事件后自动预填与真实回调一致的完整报文体 `{ request: {...} }`(可编辑),前端算签名后 POST。 +- 模拟发送(入站):`openapiMethods/callback.js#test`(method=`callback.test`,body 为 `{ event, request }`,`event` 缺省 `deliveryorder.confirm`,按 `app_key` 走真实发送链路)。 + +## 3. 事件逐个说明 + +> 说明:以下触发实现中的行号为 2026-09-12 代码快照值,行号可能漂移;定位请以方法名 grep 为准。 + +### 3.1 entryorder.confirm + +- label:入库单确认完成(直入) +- description:直入入库(API 来源)完成后回传,对应奇门 `taobao.qimen.entryorder.confirm` +- 触发实现:`app/service/systems/inbound_direct_log.js#qimenEntrySync` 的 API 分支(`source_type=API`)→ `_sendOpenApiCallback`(`event: 'entryorder.confirm'`);回传成功才执行本地回调,`throwOnError=true` +- 发送途径:`sendWithRetry` 直调(见 2.6) +- `request` 结构(注册表 `request` 模板口径;以 QM 分支为唯一基准,QM/API 共用 `buildEntryOrderConfirmRequest` 组装): + +```json +{ + "entryOrder": { + "entryOrderCode": "RK20260912001", + "ownerCode": "OWNER-001", + "warehouseCode": "WH-100", + "entryOrderId": 543, + "entryOrderType": "SCRK", + "outBizCode": "DIRECT_INBOUND_1726131400000", + "confirmType": 0, + "status": "FULFILLED", + "freight": 0, + "operateTime": "2026-09-12 10:30:00", + "remark": "导入/PDA直接入库提交" + }, + "orderLines": [ + { + "orderLineNo": 1, + "ownerCode": "OWNER-001", + "itemCode": "SKU-1", + "itemId": "1001", + "inventoryType": "ZP", + "planQty": 2, + "actualQty": 2 + } + ] +} +``` + +- `entryOrder` 字段口径:`outBizCode` 缺省自动生成 `DIRECT_INBOUND_时间戳`;`confirmType` 0=最终确认 / 1=部分确认;`status` `FULFILLED` / `PARTFULFILLED`;`freight` 固定 0;`operateTime` 为 `app.formatDate(new Date())`;`remark` 为业务备注。 + +### 3.2 entryorder.match + +- label:入库单匹配收货完成 +- description:入库单匹配收货单完成后回传(API 来源),对应奇门 `taobao.qimen.entryorder.confirm` +- 触发实现:`app/service/systems/receiving_entry_match.js#matchAfterEntryCompleted`:匹配成功写入绑定关系且**本次确实新建绑定**(`bindResult.created === true`)时,调用 `_sendCallback(entryOrder, matchedReceiving, 'auto_match')`;`_sendCallback` 按 `source_type` 分流(QM→奇门,API→OpenAPI → `_sendOpenApiCallback`,`event: 'entryorder.match'`)。重复触发时绑定已存在(`created === false`),不会重复回传;回传失败仅记录 warn,不影响绑定与入库单状态更新。 +- 发送途径:`sendWithRetry` 直调(见 2.6) +- `matchType`:仅保留在日志中(自动/手动匹配类型标识),不塞入回传报文 +- `outBizCode` / `remark` 口径:`outBizCode` 缺省自动生成 `RECEIVING_MATCH_时间戳`;`remark` 固定「匹配收货单{收货单号}自动回传」(如 `匹配收货单RCV20260912001自动回传`);`confirmType` 固定 0、`status` 固定 `FULFILLED` +- `request` 结构(注册表 `request` 模板口径;QM/API 共用 `buildEntryOrderConfirmRequest` 组装): + +```json +{ + "entryOrder": { + "entryOrderCode": "RK20260912002", + "ownerCode": "OWNER-001", + "warehouseCode": "WH-100", + "entryOrderId": 543, + "entryOrderType": "SCRK", + "outBizCode": "RECEIVING_MATCH_1726131400000", + "confirmType": 0, + "status": "FULFILLED", + "freight": 0, + "operateTime": "2026-09-12 10:30:00", + "remark": "匹配收货单RCV20260912001自动回传" + }, + "orderLines": [ + { + "orderLineNo": 1, + "ownerCode": "OWNER-001", + "itemCode": "SKU-1", + "itemId": "1001", + "inventoryType": "ZP", + "planQty": 2, + "actualQty": 2 + } + ] +} +``` + +### 3.3 deliveryorder.confirm + +- label:订单发货完成 +- description:API 渠道订单同步(出库)时逐单触发,对应奇门 `taobao.qimen.deliveryorder.confirm` +- 触发实现:`app/service/systems/order_async.js#finalizeLocalChannelOrdersInternal`(`syncApiOrders` 处理链,`createChannel=API`;触发条件已变:不再等本批出现同步成功订单,而是**逐单**在同一个分发循环内直接处理,`DISPATCH_BATCH_SIZE=20` 批内并行)→ `processApiOrderInternal`(① 组装报文,缺 ownerCode → 失败「发货单缺少奇门货主编码」→ ② 解析发送用 appKey → ③ `sendByAppKey` 发送 `deliveryorder.confirm`(最多 4 次尝试)→ ④ **回调成功才**调用 `processLocalChannelOrderInternal` 扣减库存并置 `sync_status='fin'`;任何失败统一走 `markApiSyncFailedInternal`:`sync_status='error'` + 待处理异常,不扣减、可重新派发) +- 发送途径:`sendByAppKey`;发送用 appKey 解析优先级:调用上下文 `context.appKey` 非空时优先(**不触发合约反查**),缺失时按订单货主(`store_id` + `warehouse_id`)合约反查 —— `wms_store_warehouse(auth_status=2)` → `wms_api_app(is_enabled=1 且 callback_url 非空)` 的 `self_app_key`(`resolveOpenApiAppByStoreInternal`,口径与入库单回调 `inbound_direct_log.js#_sendOpenApiCallback` 对齐);同一批次按货主 `Map` 缓存(N 单 / M 个货主 → 2M 次查询,无 N+1) +- **逐单发送语义(2026-09-13 变化)**: + +| 维度 | 改动前 | 改动后 | +|---|---|---| +| 通知对象 | 一次回调携带整批 `orderIds`(含失败/跳过) | API 渠道逐单在同步时发送(同一个 `finalizeLocalChannelOrdersInternal` 分发循环,`DISPATCH_BATCH_SIZE=20` 批内并行) | +| 回调次数 | 每批次 1 次 | 成功 N 单 = N 次回调(每单先回调、成功再扣减) | +| 报文内容 | 批次汇总 `{ orderIds, status, successCount, failedCount }` | 每单独立奇门同层级 `request` 报文(`buildQimenDeliveryOrderConfirmDataInternal` 组装) | +| 失败处理 | 不阻塞主流程 | 回调成功才扣减库存并置 `sync_status='fin'`;回调失败/异常/组装失败 → `sync_status='error'` + 待处理异常(`markPendingException`,写库失败仅记录 error 日志),**不扣减库存**,订单可重新派发(分发前过滤只跳过 `fin`) | + +- 查询开销:复用原有主表+明细查询;运单号仍由 `buildOrderWaybillCodeMapInternal` 批量取(强制同仓校验,无 N+1,现在在 `finalizeLocalChannelOrdersInternal` 内、仅 API 渠道构建);appKey 反查按货主 `Map` 批内缓存(无 N+1) +- **appKey 门禁修复(2026-09-13)**:此前 `order_storage_allocation.js` 构造的 `routeContext` 不含 `appKey`,而 `finalizeLocalChannelOrdersInternal` 内有 `if (appKey)` 门禁,导致 `syncOrderIds(API)` 链路的 `deliveryorder.confirm` **从未真正发出过请求**;订单 `wms_order_delivery.from_key` 也兜不住(`normalizeOrderFromKey` 只接受整数,字符串 app_key 被归一化为 null)。本次改为按货主合约反查 appKey 修复。**不再静默跳过**:解析不到 appKey(订单缺 `store_id` / 无授权关系 / 无「启用且 callback_url 非空」的 ApiApp)的订单按失败处理(置 `sync_status='error'` + 待处理异常、不扣减库存,可重新派发) +- **失败文案(2026-09-13)**: + - 回调失败:`OpenAPI 回调确认失败: {error}`,例如 `OpenAPI 回调确认失败: 回调返回非 2xx 状态码: 400`;订单结果新增返回字段 `callback_retry_count`(回调实际重试次数) + - 回调抛异常:`OpenAPI 回调确认异常: ...` + - 报文组装缺货主编码:`发货单缺少奇门货主编码` + - 缺 store_id:`发货单缺少货主 store_id,无法解析回传用 appKey` + - 无可用 ApiApp(无授权关系 / 无「启用且 callback_url 非空」配置):`货主未配置可用的 OpenAPI 回调(wms_api_app 启用且 callback_url 非空)` +- `request` 结构(注册表 `request` 模板口径): + +```json +{ + "deliveryOrder": { + "totalOrderLines": 1, + "deliveryOrderCode": "DO20260912001", + "deliveryOrderId": 123, + "warehouseCode": "WH-100", + "orderType": "JYCK", + "status": "DELIVERED", + "outBizCode": "DO20260912001", + "confirmType": 0, + "orderConfirmTime": "2026-09-12 10:30:00", + "operatorCode": "", + "operatorName": "", + "storageFee": "0", + "operateTime": "2026-09-12 10:30:00" + }, + "packages": { + "package": [ + { + "logisticsCode": "YTO", + "logisticsName": "圆通速递", + "expressCode": "YT1234567890", + "packageCode": "DO20260912001", + "invoiceNo": "INV20260912001", + "items": [ + { + "itemCode": "SKU-1", + "itemId": 1001, + "quantity": 2 + } + ] + } + ] + }, + "orderLines": [ + { + "orderLineNo": "1", + "orderSourceCode": "SO20260912001", + "subSourceCode": "", + "ownerCode": "OWNER-001", + "itemCode": "SKU-1", + "itemId": 1001, + "itemName": "测试商品1", + "extCode": "", + "planQty": 2, + "actualQty": 2, + "retailPrice": 0, + "actualPrice": 0, + "discountAmount": "0", + "inventoryType": "ZP", + "snList": [], + "qrCode": "" + } + ] +} +``` + +### 3.4 stockout.confirm + +- label:出库单确认完成 +- description:出库单确认回传(API 来源),对应奇门 `taobao.qimen.stockout.confirm` +- 触发实现:`app/service/systems/order_async.js#notifyStockoutExternalInternal` 的 API 分支(`source_type=API`,`event: 'stockout.confirm'`);`request` 即 `buildStockoutConfirmDataInternal` 的返回结构 `{ deliveryOrder, packages, orderLines }`(**不再有原先 `data.stockoutOrderCode`/`status` 薄包装**,报文与奇门请求体同层级) +- 发送途径:`sendByAppKey`(按 `app_key` 解析) +- `request` 结构(注册表 `request` 模板口径): + +```json +{ + "deliveryOrder": { + "totalOrderLines": 1, + "deliveryOrderCode": "SO20260912001", + "deliveryOrderId": 5001, + "warehouseCode": "WH-100", + "orderType": "PTCK", + "status": "DELIVERED", + "outBizCode": "SO20260912001", + "confirmType": 0, + "orderConfirmTime": "2026-09-12 10:30:00", + "operatorCode": "", + "operatorName": "" + }, + "packages": { + "package": [ + { + "logisticsCode": "YTO", + "logisticsName": "圆通速递", + "expressCode": "YT1234567890", + "packageCode": "SO20260912001", + "items": [ + { + "itemCode": "SKU-1", + "itemId": 1001, + "quantity": 2 + } + ] + } + ] + }, + "orderLines": [ + { + "orderLineNo": "1", + "ownerCode": "OWNER-001", + "itemCode": "SKU-1", + "itemId": 1001, + "itemName": "测试商品1", + "planQty": 2, + "actualQty": 2, + "inventoryType": "ZP" + } + ] +} +``` + +### 3.5 deliveryorder.cancel + +- label:订单已取消 +- description:订单取消成功后触发(出站事件名 `deliveryorder.cancel`) +- 触发实现:`app/service/openapiMethods/order.js#cancel` 取消成功后 fire-and-forget(`event: 'deliveryorder.cancel'`) +- 改名原因:出站回调事件名与 `/openapi` 入站方法 `order.cancel`(取消单据接口,见 `methods/openapi.json`)同名,若接收方将 `callback_url` 误指向 WMS `/openapi` 会被路由到真正的取消单据接口;故改为 `deliveryorder.cancel`,不做兼容、不双发 +- **自定义约定(2026-09-13)**:**无奇门对应接口**,按 `deliveryOrder` 节点约定自定义;`status` 为自定义约定值 `CANCELED`(风格与奇门 `deliveryOrder.status` 家族枚举一致);`orderType` 为 `body.orderType` 大写归一化结果(`String(body.orderType || 'JYCK').trim().toUpperCase()`) +- 发送途径:`sendByAppKey`(按 `app_key` 解析) +- `request` 结构(注册表 `request` 模板口径): + +```json +{ + "deliveryOrder": { + "deliveryOrderCode": "TEST-ORDER-001", + "orderType": "JYCK", + "status": "CANCELED" + } +} +``` + +### 3.6 waybill.getreceive(查询型回调) + +- label:运单揽收状态查询 +- description:按运单号批量查询是否已揽收;与 3.1~3.5 的**推送型**事件不同,本事件**消费外部响应**并回写 `wms_order_express.is_galaxy_receive` +- 注册位置:`app/lib/callback_functions.js#CALLBACK_FUNCTIONS`(管理端应用可勾选承接该方法) +- 实现:`app/service/systems/waybill.js#queryReceiveStatus`(底层方法);业务入口 `waybill.warehouse.updateReceive`(异步任务模式,进度走 `waybill.warehouse.updateReceiveTaskProgress`) +- 运单号来源:显式 `waybillCodes`,或 `where`(与 `waybill.warehouse.list` 同一套筛选口径,不含分页/排序;匹配数上限 5000,超限要求缩小范围) +- 目标应用解析:未显式传 `appKey` 时,取该仓库 `callback_functions` 勾选了 `waybill.getreceive` 的首个应用(按 `id` 升序) +- 批量上限:单次回调**最多 10 个运单号**(外部接口上限),超出自动切批并逐批更新任务进度 +- 运单号后缀:运单在该仓库的 `wms_order_express` 命中、且其 `logistics_interface_id` 关联的 `wms_express_interface.sender_tel` 至少 4 位数字时,出站统一发送 `运单号|寄件电话后四位`(如 `776447927635244|8000`,非数字字符先剔除),供外部接口校验收寄件人手机号;未命中运单、未关联接口或电话不足四位时按纯运单号发送。回写仍按纯运单号匹配,外部响应里带 `|后缀` 也能正确回写 +- **签名口径(与 3.1~3.5 不同)**:`sign = MD5(appSecret + timestamp + bodyJson)`,即 `methods/warehouse_notify.json` 描述的仓库通知协议,而非 2.4 节的 `MD5(canonicalQuery + appSecret + MD5(body))`;实现为 `openapi/callback.js#signCallback({ signMode: 'simple' })`。query 仍携带 `method/v/timestamp/app_key/sign` +- 失败识别:HTTP 200 但响应体 `code` 非 `0/1/200`(如验签失败返回 `{"code":401,"msg":"签名验证失败"}`)时整批判失败,不写入揽收状态 +- `request` 结构(经 `sendByAppKey` 统一包装,线路报文为 `{ request: {...} }`): + +```json +{ + "request": { + "waybill_codes": [ "YT1234567890|8000" ] + } +} +``` + +> 无寄件电话后四位可补时,`waybill_codes` 元素为纯运单号(`"YT1234567890"`)。 +``` + +- 外部**响应**:裸数组 `[{ "waybill_code": "YT1234567890", "is_galaxy_receive": 1 }]`;同时兼容 `{ "code": 200, "data": [...] }` 包装 +- `is_galaxy_receive` 兼容取值:`1`/`0`、`'Y'`/`'N'`(大小写不敏感)、布尔值;非法取值计入 `failed`,不写库 +- 回写口径:按 `waybill_code` + `warehouse_id` 更新 `wms_order_express.is_galaxy_receive`(`1→Y`、`0→N`),跨仓不串写 + +### 3.7 waybill.getTrace(查询型回调:物流轨迹) + +- label:运单物流轨迹查询 +- description:按运单号查询物流轨迹;消费外部响应并直接返回给调用方(**不落库**) +- 注册位置:`app/lib/callback_functions.js#CALLBACK_FUNCTIONS` +- 实现:`app/service/systems/waybill.js#fetchTracesByWaybill`;业务入口 `waybill.warehouse.getTrace`(单运单、实时回源) +- 入参:`{ request: { waybill_codes: ["770358128188071"] } }`(单运单),运单号同样按 3.6 的规则补寄件电话后四位(`运单号|后四位`);签名同样为 `MD5(appSecret + timestamp + bodyJson)` +- 响应: + +```json +[{ + "waybillNo": "770358128188071", + "trace": { + "opTime": "2026-11-10 06:15:53", + "outBizCode": "770358128188071_510180_1794262553000_210", + "memo": "【广州市】快件已发往 山东济南转运中心", + "opOrgCityName": "广州市", + "weight": 0, + "scanType": "发件" + } +}] +``` + +- 兼容:`trace` 可为数组(一个运单多条轨迹)或对象、`traces` / `traceList` 数组、`{ code, data: [...] }` 包装、单个对象返回;响应行 `waybillNo` 带 `|后四位` 后缀时按纯运单号匹配 +- **`trace: []`(暂无轨迹)**:属正常业务状态(如刚下单未揽收),接口返回 `success` + `total=0` +- **`weight`**:可能返回字符串小数(如 `"0.99"`),WMS 统一转数字保留 3 位小数 +- **不落库**:轨迹表 `wms_order_express_trace` 已删除(迁移 `20261111205500`),每次查询都实时回源 +- **揽收联动**:命中轨迹(非空)时把该运单 `wms_order_express.is_galaxy_receive` 置为 `Y`(只升不降),计数见返回的 `received_updated` +- 失败识别:与 3.6 相同(HTTP 200 但 `code` 非 `0/1/200` 视为失败);失败时入站接口直接返回错误,无本地兜底 + +## 4. timestamp 规范(2026-09-12 已统一为秒) + +`timestamp` 已统一为**秒级(10 位字符串)**规范值:`String(Math.floor(Date.now() / 1000))`。 + +| 位置 | 取值 | 单位 | +|---|---|---| +| 出站发送 `app/service/openapi/callback.js#sendWithRetry` | `String(Math.floor(Date.now() / 1000))` | **秒(10 位)** | +| 回调调试页 `app/controller/openapiCallback.js`(`nowTimestamp`) | `Math.floor(Date.now() / 1000)` | **秒(10 位)** | + +- 与 `/openapi` 入站入口 `app/service/openapiEntry.js` 的时间戳时效校验一致(秒级窗口,±600 秒),可作为规范值对外承诺。 +- 历史背景:此前发送端用 `String(Date.now())`(毫秒)与调试页(秒)口径不一致(`methods/changes/openapi_callback.json` 版本 `2026.09.12-openapi-callback-init` 的「已知问题」备注),已在本批次修复;接收方请按秒级(10 位)实现校验,勿再按毫秒。 + +## 5. 相关文件索引 + +- 事件注册表:`app/service/openapi/callbackRegistry.js` +- 发送与重试:`app/service/openapi/callback.js` +- 签名算法:`app/lib/api_sign.js` +- 调试页控制器:`app/controller/openapiCallback.js`(路由 `app/router.js`) +- 入站方法路由文档:`AI_METHOD_ROUTING.md` 5.6 节 +- 触发实现:`app/service/systems/inbound_direct_log.js`、`app/service/systems/receiving_entry_match.js`、`app/service/systems/order_async.js`、`app/service/openapiMethods/order.js` +- 查询型回调实现:`app/service/systems/waybill.js#queryReceiveStatus`(`waybill.getreceive`);同类的 `deliveryorder.getwaybill` / `deliveryorder.getprintdata` 分别见 `app/service/systems/express_platform.js`、`app/service/systems/order_print.js` +- 回调 method 注册表(管理端可勾选):`app/lib/callback_functions.js#CALLBACK_FUNCTIONS` +- 接口文档 SSOT:`methods/openapi_callback.json`(5 个 method;仅覆盖推送型事件,查询型回调按既有惯例不收录) +- 变更记录:`methods/changes/openapi_callback.json` +- 文档站页面:`/docs/api/openapi_callback`(OpenAPI 出站回调文档页) +- 入口来源:`/docs/api/openapi` 页面头部的「→ 出站回调文档」链接 + +调试工具 `GET /docs/api/openapi/callback-test` 已在第 1 节与 2.6 节说明,此处不重复。 + +**三份资料的定位与先后关系**: + +| 资料 | 定位 | +|---|---| +| `methods/openapi_callback.json` | 出站回调**接口文档 SSOT**(5 个 method 的 params / response / errors),文档站 `/docs/api/openapi_callback` 页面消费 | +| `app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS` | **事件注册表**(name / label / description / request,`request` 为奇门同层级报文模板),运行时数据源;回调调试页 `/docs/api/openapi/callback-test` 消费注册表并预填完整报文体 `{ request: {...} }` | +| `docs/openapi-callback-events.md`(本文) | **协议说明与背景**(触发链路、签名算法、重试策略、时间戳规范),非 SSOT,仅作解释性补充 | + +先后关系:事件或字段变化时,先改代码(`callbackRegistry.js` 注册表与发送实现)→ 再经 `script/update-api-doc.cjs` 更新接口文档 SSOT `methods/openapi_callback.json` 并追加 `methods/changes/openapi_callback.json` → 最后同步本文与文档站文案。调试页内容以注册表为准,文档站页面以 SSOT 为准。 + +## 6. 与 methods/*.json 的关系 + +- 出站回调**不写入** `methods/openapi.json`:该文件是**入站** method 的 SSOT(`POST /openapi`),`script/update-api-doc.cjs` 的 spec 结构(modules→list→method→params/response/errors)不适合表达出站回调,写入会污染文档与文档 UI 语义。 +- 出站回调现已独立成接口文档 `methods/openapi_callback.json`(module=`openapi_callback`,5 个 method,当前版本 1.4.0);变更记录写入 `methods/changes/openapi_callback.json`(首条 version `2026.09.12-openapi-callback-init`,type `added`;最新 version `2026.09.13-openapi-callback-confirm-before-deduct`,type `updated`)。 +- 本次无入站接口契约变更:`methods/openapi.json`、`methods/system.json`、`methods/qimen.json` 均未改动。 +- `methods/changes/*.json` 中历史记录提及的旧事件名(`stockout_completed`、`entry_order_direct_inbound_completed`、`entry_order_receiving_matched` 等)为追加式历史,保持原样,不回改。 diff --git a/docs/queryorder-wave-index-optimization-plan.md b/docs/queryorder-wave-index-optimization-plan.md new file mode 100644 index 0000000..d15d51d --- /dev/null +++ b/docs/queryorder-wave-index-optimization-plan.md @@ -0,0 +1,148 @@ +# queryOrder 波次计数性能优化方案(只读评估 + 方案文件,未执行) + +> 状态:**待用户风险确认**。本方案全程只读评估,未执行任何 DDL / 数据变更。 +> 编制:wms-db-agent|日期:2026-08-30 + +## 1. 背景与瓶颈定位 + +- 业务链路:工作台 queryOrder → `app/service/systems/workbench.js` + - `_countWaveOrders()`:对 current + dispatch 两族分表执行 `SELECT COUNT(*) WHERE wave_id=? AND warehouse_id=?` + - `_getWaveOrderIds()`:同谓词取订单 id 列表 +- 现状瓶颈(上一轮 DB agent 已定位 + 用户提供生产数据): + - 现有索引 `idx_{wh}_current_wave` 为 `(status, wave_id)`,前导列 `status` 不在谓词中; + - 生产 dispatch 分表约 **25.38 万行 / 524MB**,单次 COUNT 全表扫描约 **12.69 万行**;生产 MySQL **5.7.44**。 +- 关联问题:序列表 `wms_order_id_location_{wh}` 缺约 **12.4 万**存量订单 id 记录 → queryOrder 定位回退为分表遍历(见 §5)。 + +## 2. 分表索引生成机制 + +### 2.1 模型层定义 + +- `app/model/order_delivery_table_schema.js`: + - `buildIndexOptions(warehouseId, type)` 生成每张分表的索引列表; + - current 类型共 8 个索引,其中 `idx_{wh}_current_wave = (status, wave_id)`(瓶颈索引); + - dispatch 类型复用 current 的基础索引:`baseIndexes[0..2] + idx_dispatch_{wh}_dispatch_lane (dispatch_lane, status) + baseIndexes.slice(3)`,即 dispatch 分表同样继承 `idx_{wh}_current_wave`; + - `buildIndexLines()` 用于建表 DDL;`buildTableOptions()` 供动态模型 define。 +- 基表模型 `app/model/order_delivery.js` 自带索引列表(`wave_id = (status, wave_id)` 等)——基表 `wms_order_delivery` 非分表,**不在本次范围**(可选加,默认不加)。 + +### 2.2 运行时 drift 同步(⚠️ 关键风险) + +- `app/model/order_delivery_factory.js`:`getOrCreateModel` → `ensureManagedTableSchema` → `needsTableSchemaSync`(比对期望索引)→ `alterManagedTableSchema`(**只补缺失索引、不删已有索引**)。 +- 每次进程首次使用某分表模型时触发(模型有内存缓存)。 +- 结论:**若先改 schema 文件再部署代码,应用会在首个请求时自动对 524MB 大表执行建索引 DDL(无 ALGORITHM/LOCK 控制、无法择时)**。 +- 因此正确顺序必须是:**先执行迁移(低峰期)→ 再落盘 schema 代码变更 → 再部署**;这样应用运行时 drift 检查发现索引已存在,不会重复建。 + +### 2.3 现有索引核对(开发环境,只读 SHOW INDEX) + +开发环境(config.local.js,客户端 wms)确认 current/dispatch 分表现有索引与模型一致,瓶颈索引为: + +| 表(开发环境示例) | 瓶颈索引 | 列 | +|---|---|---| +| wms_order_delivery_1000028_dispatch | idx_1000028_current_wave | status, wave_id | +| wms_order_delivery_1000028 | idx_1000028_current_wave | status, wave_id | + +开发环境分表规模(只读 information_schema):`wms_order_delivery_100000` 66,976 行 / 41.6MB;`wms_order_delivery_100000_dispatch` 2,488 行。生产分表规模以用户提供数据为准(dispatch 25.38 万行 / 524MB),执行前需实测。 + +## 3. 修改点清单 + +### 3.1 模型 schema(本次仅书面标注,未改文件) + +> 为避免与 wms-dev-agent 的修复冲突,本 agent **不直接修改 schema 代码**,待用户确认后由 wms-dev-agent 落盘;或在用户授权后由本 agent 改。 + +- 文件:`app/model/order_delivery_table_schema.js` +- 函数:`buildIndexOptions`,current 分支共享 `indexes` 数组内、`idx_${prefix}_wave` 之前插入: + +```js +{ + name: `idx_${prefix}_wave_id`, + fields: [ 'wave_id' ], +}, +``` + +- dispatch 分支**无需修改**(通过 `baseIndexes` 自动继承)。 +- 索引名与迁移草案一致:`idx_{wh}_current_wave_id`(dispatch 表沿用 `_current_` 前缀,与既有继承索引命名习惯一致)。 + +### 3.2 迁移文件(已创建,未执行) + +- 路径:`database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js` +- 要点: + - 动态枚举 `wms_order_delivery_{wh}` 与 `wms_order_delivery_{wh}_dispatch`(information_schema,不写死仓库 id); + - 幂等:`SHOW INDEX` 已存在则跳过; + - 使用原生 `ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE`(Sequelize `addIndex` 不支持传算法/锁参数,故用原生 SQL); + - `down` 为 `DROP INDEX`(同样 INPLACE/LOCK=NONE); + - 语法已通过 `node --check`;**未对任何环境执行**。 + +## 4. 生产执行风险评估与建议 + +### 4.1 MySQL 5.7.44 在线 DDL 支持 + +- InnoDB 添加二级索引支持 `ALGORITHM=INPLACE, LOCK=NONE`(MySQL 5.6+,5.7 完整支持):不重建表、不锁写、并发 DML 允许。 +- 前置检查项: + 1. `SHOW VARIABLES LIKE 'old_alter_table'` 应为 `OFF`(默认); + 2. 确认表引擎 InnoDB(本项目分表均为 InnoDB); + 3. 执行前实测各分表行数与大小。 + +### 4.2 预估耗时与索引体积 + +- 索引体积:`wave_id BIGINT(20)`(8 字节)+ 主键 8 字节,25.38 万行约 **4–6 MB**,几乎不增加磁盘压力; +- 建索引耗时:全表扫描 524MB + 排序 25 万行键值,低负载 SSD 上单个 dispatch 分表约 **数十秒–5 分钟**;current 分表按行数同比。多仓多表总窗口建议预留 **15–30 分钟**。 +- 副作用:每个分表多一个二级索引,INSERT 时多写约 20 字节/行,可忽略。 + +### 4.3 建议执行窗口 + +- 低峰期:**凌晨 02:00–05:00** 或周末低峰;避开波次扫描定时任务(`app/schedule/sync_finished_wave_batch.js`)、批量导入与大促。 +- 逐表执行并监控:`SHOW PROCESSLIST`、`INFORMATION_SCHEMA.INNODB_TRX`(确认无长事务)。 + +### 4.4 执行方式(红线) + +- ❌ 禁止对生产库直接执行裸 `ALTER TABLE`;❌ 禁止用 `script/db-query.ps1` 查/改生产(它永远是开发环境)。 +- ✅ 生产必须走迁移流程: + - 全量:`$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production` + - 或单条:`node script/run-single-migration.cjs 20260830100000-add-wave-id-index-to-order-delivery-shards.js`(内部连 `database/config.js` 的 production) +- ⚠️ **生产当前有 4 条 pending 迁移**(只读 `db:migrate:status --env production` 结果):`20260829120000` / `20260829160000` / `20260829170000` / `20260829180000`(report-delivery 相关)。`run-single-migration.cjs` 会拒绝跨序执行 → **先跑完这 4 条**再跑本条;用 `db:migrate` 则按序自动全部执行。 +- 开发环境基线:迁移全部 up(最新 `20260829180000`);本条迁移在开发/生产两边均显示 `down`(未执行,符合"草案"状态)。 + +### 4.5 回滚 + +- `down`:`DROP INDEX`(INPLACE/LOCK=NONE,秒级完成),不重建表、不影响数据。 + +## 5. 存量回填评估(script/backfill-order-id-location.cjs) + +### 5.1 适用性 + +- 目标:将分表存量 id 补入 `wms_order_id_location_{wh}`(id → location 映射),修复 queryOrder 定位回退(约 12.4 万行缺失)。 +- 脚本能力:`--dry-run`、`--warehouse-id=`、`--batch-size=`(100–50000,默认 1000)、`--db-client=`、`--config-path=`。 +- ⚠️ 默认连开发库(config.local.js);**生产必须** `--config-path=script/db-query-prod-config.js --db-client=wms`。 +- 流程:枚举分表 → 确保序列表存在(缺失时 CREATE TABLE)→ 分批 LEFT JOIN(PK 序)找缺失 id → 多行 `INSERT ... ON DUPLICATE KEY UPDATE` → 每仓结束抬 `AUTO_INCREMENT = MAX(id)+50`。 + +### 5.2 数据量与分批建议 + +- 约 12.4 万行;默认 batch=1000 约 124 批。每批重新执行 LEFT JOIN(无物化),最大分表 25 万行 × 124 批 ≈ 3 千万次 PK 探测,低峰可接受;建议 `--batch-size=5000` 减少轮次。 +- 建议顺序:`--dry-run` 全量预演 → 核对输出 → 按仓库逐个 `--warehouse-id=` 执行 → 前后核对 `COUNT(*)`。 + +### 5.3 风险点 + +1. **id 碰撞(最高风险)**:回填期间若序列表 AUTO_INCREMENT 仍低于缺失 id 区间,新订单可能分配到相同 id,`ON DUPLICATE KEY UPDATE` 会把新订单的 location 覆盖为来源表 location。执行前必须核对:`AUTO_INCREMENT` vs 缺失 id 最大值;务必在**最低写入时段**执行。 +2. **DDL**:`ensureSequenceTable` 可能 CREATE TABLE;结束会 `ALTER TABLE ... AUTO_INCREMENT`(小表、秒级)——均属 DDL/写操作,需用户确认。 +3. **location 覆盖**:id 已存在于序列表时会被覆盖(脚本语义如此)。 +4. **无断点续跑**:中断后重跑安全(幂等 upsert),但需重新扫描。 +5. **与加索引互补**:索引修波次计数,回填修订单定位,两者独立、可分开执行。 + +## 6. 需要用户确认的风险问题清单(交 Dispatcher 转达) + +1. 是否允许在**生产**执行加索引 DDL?(未确认前不执行) +2. 执行方式:全量 `db:migrate`(会自动先执行生产 pending 的 4 条 20260829* 迁移)还是单条 `run-single-migration.cjs`(需先补跑那 4 条)?是否同意先执行那 4 条? +3. 执行窗口:请指定具体时间(建议凌晨 02:00–05:00);期间可接受轻微 I/O 压力? +4. 索引范围:确认 current + dispatch 两族分表、**全部仓库**都加? +5. 是否允许对 `wms_order_id_location_{wh}` 回填写数据(约 12.4 万行)?是否先 `--dry-run` 预演? +6. 回填窗口与 id 碰撞:是否可安排在最低写入时段?是否同意先核对序列表 AUTO_INCREMENT 区间? +7. schema 代码变更(`buildIndexOptions` 新增 `idx_{prefix}_wave_id`):是否由 wms-dev-agent 落盘?确认部署顺序 = **先迁移、后代码**。 +8. 回滚授权:若上线后异常,是否允许执行 down(DROP INDEX)? + +## 7. 建议执行顺序 + +1. 用户完成 §6 风险确认; +2. 生产低峰期执行迁移(含前置 4 条 pending); +3. 生产 `SHOW INDEX` + `EXPLAIN` 验证新索引生效; +4. wms-dev-agent 落盘 `buildIndexOptions` 变更并部署(避免运行时 drift 重复建索引); +5. (可选)序列表回填(先 dry-run); +6. 观察 queryOrder 链路耗时与错误率。 \ No newline at end of file diff --git a/docs/report-config-guide.md b/docs/report-config-guide.md new file mode 100644 index 0000000..7120f51 --- /dev/null +++ b/docs/report-config-guide.md @@ -0,0 +1,480 @@ +# 配置驱动通用报表与货主定时投递 — 配置结构说明 + +> 本文档与代码实现保持一致(模型:`app/model/report_definition.js`;引擎:`app/service/systems/report.js`; +> 渲染翻译层:`app/lib/report/render.js`;内置查询器:`app/service/systems/report/queries/*`; +> 投递编排:`app/service/systems/reportDelivery.js`)。 +> 接口定义见 `methods/system.json` 分组「通用报表模块」(module=report)。 + +> 破坏性变更(2026-08-30 模型重构):报表定义由 `code` 编码改为主键 `id` 关联,接口入参 `report_code` +> 全部替换为 `report_id`(=报表定义ID,兼容 `reportId` 驼峰);`code/scope/description` 与 +> `output_config/source_config/sheet_config` 三段 JSON 配置字段已随模型删除, +> 列渲染由注册类型硬编码字段规格自动完成(无自定义列配置)。 + +## 1. 总览 + +报表采用「配置驱动」:`wms_report_definition` 一行配置 = 一个报表(`type` + `fields` 极简配置), +大部分新报表场景只需加配置行或新增内置查询器类型,免发版。 + +模型 `app/model/report_definition.js` 关键字段: + +| 列 | 类型 | 说明 | +|---|---|---| +| `id` | BIGINT UNSIGNED | 主键,报表定义ID(接口入参 `report_id`,唯一性由主键承担) | +| `name` | STRING(100) | 报表名称 | +| `type` | STRING(50) | 报表类型(内置查询器注册 key,如 `stockFlow`) | +| `file_name` | STRING(200) | 导出文件名模板(支持 `{date}` 数据日期、`{time}` 生成时刻 HHmmss、`{datetime}` 数据日期_生成时刻、`{timestamp}` 毫秒时间戳,如 `7日出入库_{date}.xlsx`、`库内拦截_{date}_{time}.xlsx`) | +| `fields` | JSON | 勾选的字段 key 数组(该类型注册字段的子集;列头/合并/样式/格式化由类型硬编码字段规格决定) | +| `is_enabled` | TINYINT(1) | 是否启用:0=停用 1=启用(导出只读 is_enabled=1 的定义) | +| `remark` | STRING(500) | 备注 | +| `created_at`/`updated_at`/`deleted_at` | DATE | 时间戳与软删标记 | + +生成链路: + +```text +report.generate(method 层,异步任务,入参 report_id) + -> systems/report.js getDefinition(读定义,is_enabled=1,软删自动排除) + -> resolveTypeEntry / resolveQuerier(type 查注册表) + -> 内置查询器取数 {windows, rows, meta} + -> lib/report/render.js renderSheetByType(按类型硬编码字段规格渲染) + -> excel.generateAndUpload(产物 fileKey/url/filename/size) +``` + +## 2. 注册类型(report.definition.typeList / wms_report_definition.type) + +查询器注册表 `app/service/systems/report/queries/index.js`,`type` 即注册方法 key; +查询器签名统一:`async ({ ctx, storeId, warehouseId, params }) => ({ windows, rows, meta })`, +每个查询器模块挂载静态字段清单 `fields` 与缺省窗口参数 `defaultWindow`。 + +当前注册类型: + +| key | 标题 | 说明 | +|---|---|---| +| `stockFlow` | 库存变化以及补货报表 | 按日窗口聚合出入库流水与正品库存,输出每 SKU 产品名称/条码/外部编码/每日出入库/待处理订单占用数/可用库存/7日总出库数量/推荐采购量与是否触发预警 | +| `interceptOrder` | 库内确定拦截订单明细 | 以配送表 `dispath_time`(订单迁移进配送表的时间)为时间基准,统计昨日自然日库内确定拦截订单(`intercept_status='intercepted_at_warehouse'`),按商品明细展开(一个商品一行),列与订单导出含明细模式(`order.export` `export_mode=item`)一致、仅不含「商品图片」列,并附 2 列拦截时间(通知拦截时间/库内确定拦截时间) | + +`stockFlow` 缺省窗口参数:`window = { dayCount: 7, cutoverHour: 7 }`。 + +`interceptOrder` 缺省窗口参数:`window = { dayCount: 1, cutoverHour: 0 }`(单个自然日、 00:00 切日)。 +该类型**不使用** `params.dayCount`/`params.cutoverHour` 入参,统计日由 `params.bizDate` 控制(缺省=昨日)。 + +`stockFlow` 全量字段清单(9 组列,顺序固定,`report.definition.typeList` 直接返回该规格): + +| key | label | type | computed | asText | 说明 | +|---|---|---|---|---|---| +| `item_name` | 产品名称 | string | - | - | | +| `barcode` | 条码 | string | - | ✅ | 文本单元格落地,防科学计数法 | +| `item_code` | 外部编码 | string | - | ✅ | 文本单元格落地,防科学计数法;key 复用旧「商品编码」列(label 变更,兼容既有定义 fields 勾选) | +| `daily` | 每日出入库 | array | - | - | children:`ck`(出库数,number)/ `rk`(入库数,number) | +| `pending_occupy` | 待处理订单占用数 | number | - | - | 口径:`wms_stock_warehouse.locked_quantity`(仓库商品主表锁定数量,非 `wms_storage` 聚合口径) | +| `available` | 可用库存 | number | - | - | `wms_storage` 正品库位明细 `SUM(available_quantity)` | +| `ck_total` | 7日总出库数量 | number | - | - | 窗口内 OUTBOUND 流水变更数量 `quantity` 合计 | +| `suggest` | 推荐采购量 | number | ✅ | - | 预计算字段(formatters 注册表,低库存补偿口径见 2.1 第 8 条) | +| `warn` | 是否触发预警 | boolean | ✅ | - | 预计算字段 | + +外部编码(`item_code`)取值口径:优先 `wms_stock_store.item_code`(按 stock_id 关联 `wms_stock_warehouse.id`,同 stock_id 多条时按 id 升序取第一条非空 item_code,stock_id 为空的记录不参与匹配)→ 回落 `wms_stock_warehouse.item_code` → 均无则留空。 + +已移除旧列(不再导出,共 8 个):`stock_id`、`rk_total`、`total`、`pending`、`locked`、`ck_avg`、`rk_avg`、`stock_days`; +行内仍计算 `rk_total`/日均/预计可售天数等字段供 `suggest`/`warn` 判定与测试复核,但不进入导出列清单。 + +### 2.1 stockFlow 口径与假设(8 条,供测试复核) + +1. **窗口**:`dayCount` 个 `[D cutoverHour:00, D+1 cutoverHour:00)` 本地时区半开区间 + (缺省 7 天、07:00 切点,可由请求 `params.dayCount/cutoverHour` 覆盖)。 +2. **流水**:`wms_stock_transaction`,`transaction_type IN (INBOUND, OUTBOUND)`,显式排除 LOCK/UNLOCK, + 按 `created_at` 落入窗口,INBOUND→rk、OUTBOUND→ck(变更数量 `quantity` 即出入库数)。 +3. **可用库存**:`wms_storage`(库位级正品明细),`inventory_type='ZP'`、`is_enabled=1`、未删除, + `SUM(available_quantity)`=可用库存(行内 `available` 列);`SUM(quantity)`/`SUM(locked_quantity)`/ + 待出库存等仅保留为行内内部计算字段,已不在导出列清单中。 +4. **条码**:`wms_stock_barcodes` 多值取字典序第一条(表内无主条码标志,等价旧 PHP `MIN(barcode)` 语义)。 +5. **外部编码**:优先 `wms_stock_store.item_code`(按 stock_id 关联 `wms_stock_warehouse.id`,同 stock_id 多条时 + 按 id 升序取第一条非空 item_code,stock_id 为空的记录不参与匹配),未匹配则回落 + `wms_stock_warehouse.item_code`,再无则留空。 +6. **待处理订单占用数**:取 `wms_stock_warehouse.locked_quantity`(仓库商品主表锁定数量, + 不是 `wms_storage` 聚合的 locked_quantity 口径)。 +7. **行范围**:窗口内有流水或有正品库存的 SKU 均出列,按 `item_code` 升序、`stock_id` 升序。 +8. **suggest/warn**:由 `formatters` 注册表计算。低库存补偿:`available < 20` 且 `rk_total < 20` 时 + 推荐采购量补偿到不低于 30;预警判定由 `warnOf(ck_total, available, rk_total)` 计算。 + 行内仍计算 `rk_total`/日均/预计可售天数等字段供判定与复核,但不进入导出列清单。 + +### 2.2 interceptOrder 口径与假设(供测试复核) + +1. **数据源**:配送表 `wms_order_delivery_{warehouse_id}_dispatch`(订单出库迁移后的表位; + 查询器经 `orderExport.getOrderModelByTableType('dispatch', warehouseId)` 取动态模型)。 +2. **拦截状态**:仅取 `intercept_status = 'intercepted_at_warehouse'`(库内确定拦截;由 + `order.recheckOrder.confirmIntercept` 与 `intercept_auto_confirm` 写入,同时 `step=4`、`outbound_status=fin`)。 + 注意该枚举**没有** `intercepted` 值,历史遗留值不参与统计。 +3. **时间基准**:`dispath_time`(配送表独有列,= 订单迁移进配送表的时刻,由 + `orderDeliveryMigration.buildDispatchRow` 写入 `new Date()`;2026-09-07 迁移 `20260907120000` 上线, + 仅 dispatch 分表有该列,当前分表/历史表/委外表无此列)。 +4. **统计区间**:默认「昨日自然日」`[昨日 00:00:00.000, 今日 00:00:00.000)`(本地时区半开区间, + 与 stockFlow 的 07:00 切日口径**不同**);`params.bizDate`(`YYYY-MM-DD`,兼容 `biz_date`) + 传入且为真实存在的日期时,按该日整天统计,缺省/非法一律回落昨日自然日。 + **统计日不得晚于昨天**:传今天/未来日期一律回落昨日(上界恒为今日 00:00:00,不含), + 保证「今天生成/投递的报表不含今天的数据」——当天新迁入配送表的拦截单只会出现在次日报表; + 比昨天更早的显式日期仍被尊重(补数场景)。 +5. **明细粒度与取值**:按订单 ID 升序分页(单页 1000 单,循环至不足一页)复用 + `orderExport.buildOrderExportPage({ mode: 'item' })` → `mapOrderExportRow(item)`,因此状态中文翻译、 + 货主备注(`wms_store_warehouse.store_remask`)、仓库商品名/条码回落、运单汇总(多运单逗号拼接、 + 主/子单号业务类型、包材编码/名称、称重汇总)、收件人字段等与订单导出逐格一致; + 行再按注册字段裁剪(丢弃 `item_image` 等未注册键,缺失值回落空字符串)。 +6. **无商品明细的订单**:输出一行订单级数据(运单字段汇总、商品列为空),与订单导出 item 模式一致。 +7. **主维度**:`warehouseId` 必填(配送表按仓库分表;`<=0` 抛「interceptOrder 查询器缺少仓库维度 warehouseId」); + `storeId > 0` 时追加 `store_id` 过滤(货主维度报表/定时投递),否则仓库维度全量。 +8. **行数保护与 meta**:明细行数达 `MAX_EXPORT_ROWS = 200000` 时截断并打 warn(`meta.truncated = true`); + `meta` 返回 `bizDate/startTime/endTime/warehouseId/storeId/interceptStatus/timeField/orderCount/rowCount/truncated`。 +9. **波次序号**:`wave_index` 沿用订单导出同款 `attachOrderWaveIndex`(仓库ID取 `ctx.user.store_id`), + 定时投递(无 `ctx.user`)场景该列降级为 0,仓库主体手工导出为真实序号。 +10. **附加列(订单导出 item 模式无此 3 列)**: + - `source_order_codes`(平台交易单号)= 配送表 `source_order_codes` 原值 + (`mapOrderExportRow(item)` 不输出该列,由查询器回查补充,列位置紧跟「外部单号」); + - `intercept_notice_time`(通知拦截时间)= 配送表 `intercept_time`。该字段自 2026-09-10 起 + 语义统一为「最近一次发起拦截的通知时刻」(见 `app/lib/intercept_time.js`):首次发起时写入、 + 重复发起不覆盖、库内拦截确认/退回入库均不覆盖、取消/解除拦截置空; + 若该列为空则回落 `wms_operation_log` 中 `operation_code='ORDER_INTERCEPT_REQUEST'` 的最早记录时间 + (历史数据兼容,查询按 `business_type='order'` + `business_id=订单ID` + `warehouse_id=当前仓库` + 三重过滤,订单 ID 按仓库发号必须同仓隔离); + - `intercept_confirm_time`(库内确定拦截时间)= 配送表 `dispath_time` + (订单迁移进配送表的时间;库内确定拦截后订单会走 `outbound_status=fin` 的自动迁移,故等价于库内确定拦截时刻。 + 不再使用 `intercept_time`,因为确认时不再覆盖该字段); + - 两列均格式化为 `YYYY-MM-DD HH:mm:ss`(空值输出空字符串); + `meta.noticeTimeFilledCount` / `meta.confirmTimeFilledCount` 返回两列的有值行数,便于核对覆盖率。 + +字段清单(49 列,顺序固定,全为 `string` 静态列;`report.definition.typeList` 直接返回该规格): + +| key | label | +|---|---| +| `id` | 订单ID | +| `delivery_order_code` | 订单号 | +| `external_order_code` | 外部单号 | +| `source_order_codes` | 平台交易单号 | +| `status` | 订单状态 | +| `wave_no` | 波次号 | +| `wave_index` | 波次序号 | +| `store_id` | 货主 | +| `sys_platform_name` | 平台 | +| `create_channel` | 来源 | +| `shop_nick` | 店铺昵称 | +| `receiver_name` | 收件人 | +| `receiver_mobile` | 收件人电话 | +| `receiver_province` | 省 | +| `receiver_city` | 市 | +| `receiver_district` | 区 | +| `receiver_town` | 镇 | +| `receiver_detail` | 详细地址 | +| `item_name` | 仓库商品名称 | +| `item_barcode` | 商品条码 | +| `item_quantity` | 数量 | +| `logistics_name` | 物流公司 | +| `waybill_code` | 运单号 | +| `business_type` | 业务类型 | +| `logistics_interface_name` | 运单接口 | +| `package_material_id` | 包材ID | +| `package_material_code` | 包材编码 | +| `package_material_name` | 包材名称 | +| `waybill_allocated_at` | 分配时间 | +| `items_count` | 订单商品总类数 | +| `items_total` | 订单商品总数 | +| `items_weight` | 商品重量 | +| `weighing_weight` | 称重重量(g) | +| `total_amount` | 订单金额 | +| `got_amount` | 实收金额 | +| `create_at` | 创建时间 | +| `pay_time` | 支付时间 | +| `delivery_time` | 发货时间 | +| `outbound_status` | 出库状态 | +| `inspection_status` | 复核状态 | +| `recheck_status` | 复核完成状态 | +| `post_status` | 配货状态 | +| `pack_status` | 打包状态 | +| `remark` | 备注 | +| `buyer_message` | 买家留言 | +| `seller_message` | 卖家留言 | +| `archive_time` | 归档时间 | +| `intercept_notice_time` | 通知拦截时间 | +| `intercept_confirm_time` | 库内确定拦截时间 | + +与订单导出 item 模式的差异:不含 `item_image`(商品图片)列,另附加 3 列—— +`source_order_codes`(平台交易单号,位置紧跟「外部单号」)、`intercept_notice_time`(通知拦截时间)、 +`intercept_confirm_time`(库内确定拦截时间),订单导出无这 3 列; +另外订单导出 item 模式新增了 `sn_quantity`(SN码数量,明细中启用序列号管理商品的 plan_qty)与 +`sn_codes`(SN码,该商品行复核时登记的 SN 列表),waybill 模式新增 `sn_codes_summary`(SN码汇总,订单级),本报表未启用这些列。配置示例: + +```json +// report.definition.save(新增拦截明细报表) +{ + "name": "库内确定拦截订单明细", + "type": "interceptOrder", + "file_name": "库内确定拦截订单明细_{date}.xlsx", + "fields": ["id", "delivery_order_code", "external_order_code", "waybill_code", "item_name", "item_quantity", "create_at"], + "remark": "每日导出昨日库内确定拦截订单明细" +} +``` + +> 注:`fields` 必须为该类型注册字段的子集(新增时必填,且**不能为空数组**——渲染层按勾选字段生成列, +> 空数组会得到无列的空表;需全部 49 列时请显式列出全部 key),完整可选 key 见上文清单。 + +## 3. 渲染规则(renderSheetByType,无 sheet_config) + +列定义不再由 `sheet_config.columns` 配置,而由**注册类型字段规格硬编码自动生成** +(`app/lib/report/render.js` `renderSheetByType`,按定义勾选字段顺序渲染): + +| 字段类型 | 渲染规则 | +|---|---| +| `string` | 静态列(表头=label);字段规格 `asText: true` 时整列落地为 Excel 文本单元格 | +| `number` | 静态列,统一 `zeroToDash`(`0 / '0' / null / ''` 显示 `-`) | +| `boolean` | 静态列,统一 `yesNo`(真→'是'、假→'否',PHP 布尔语义) | +| `array` | 窗口展开列:per=窗口数(缺省 7)、pair=children 字段键;表头第 1 行每窗口输出窗口开始日期 `'Y/n/j'`(无前导零,如 `2026/8/23`),pair 数>1 时每窗口表头横向合并(如 D1:E1 … P1:Q1);表头第 2 行按 children label 填充;子字段 number 统一 `zeroToDash` | + +- 存在展开列时启用两行表头,其余列表头纵向合并(如 A1:A2),合并区域**自动生成**,无需配置。 +- **asText(文本单元格)**:由类型字段规格硬编码(如 `item_code`/`barcode` 声明 `asText: true`), + 渲染层 `renderSheetByType` 将声明 `asText` 的列收集为 `textColumns`(0 基列索引数组,未声明任何 `asText` 列时不输出该字段), + 由 `app/service/systems/excel.js` 落地:ExcelJS 路径逐单元格 `numFmt='@'` 并把值转为字符串(原始对象除外), + SheetJS 路径逐单元格 `t:'s'`、`z:'@'` 并把值字符串化。适用于条码、外部编码等长数字串 + (防止被 Excel 按数值展示成科学计数法),**无需**再配合 `textPrefix` 的 `'` 前缀 + (`textPrefix` 格式化器保留注册仅向后兼容)。 +- sheet 名称为类型标题(如「库存变化以及补货报表」);`columns` 恒输出空数组 + (数据以 AOA 二维数组形式输出,表头行内联在 rows 首位)。 + +## 4. 导出文件名(file_name)与上传目录(fileKey) + +- `file_name` 为文件名模板,占位符(本地时区,2026-09-10 扩充): + - `{date}`:数据日期(请求 `params.bizDate`,缺省服务器当天,`YYYY-MM-DD`); + - `{time}`:生成时刻 `HHmmss`(如 `200745`); + - `{datetime}`:`{date}_{time}`(如 `2026-09-09_200745`); + - `{timestamp}`:生成时刻毫秒时间戳。 + 同一天多次投递/手动导出同一报表时,文件名带生成时刻(如 `interceptOrder_{date}_{time}`)可避免 COS 同名覆盖 + (同名文件会被后一次写覆盖,且 CDN 可能仍回源旧内容)。 +- 缺省模板:`_.xlsx`;不以 `.xlsx`/`.xls` 结尾时自动补 `.xlsx`。 +- 上传目录(COS 文件 key)按「报表定义 + 货主/仓库」维度隔离(2026-08-31 修复「货主限制不符」缺陷: + 修复前统一为 `exports/report//`,不同货主的报表文件会互相覆盖): + - `store_id` 有效(>0):`exports/report//store-/`; + - `store_id` 缺省且 `warehouse_id` 有效(>0):`exports/report//warehouse-/`; + - 两者均缺省:`exports/report//common/`(手动导出兼容兜底)。 +- 完整 COS key 由 `app/service/systems/excel.js` `generateAndUpload` 在上述目录后追加 `{YYYYMMDD}/` 日期目录与文件名; + `report.generate` 任务结果 `result.fileKey` / `download_url` 即该隔离 key。 +- 货主定时投递固定走 `store-` 隔离(`reportDelivery.processOne` 必传货主并强校验); + 手动导出未传 `store_id` 时按 `warehouse-`(登录上下文仓库)或 `common` 兜底。 + +## 5. 货主定时投递(wms_report_delivery_plan / wms_report_delivery_log) + +- **投递计划** `wms_report_delivery_plan`:`store_id + report_definition_id` 唯一(唯一索引 `uk_store_report_definition`, + `report_definition_id` 即报表定义ID、接口入参 `report_id`);`schedule_times`(HH:mm 数组,去重升序)、 + `channel`(**仅支持 `inbox`,默认 `inbox`**;wecom/link 已弃用,保存时传非法渠道报错「投递渠道仅支持 inbox: 」)、 + `late_grace_minutes`(补投宽限 0-1440,默认 60)、`name`(计划名称,仅展示字段,≤100 字符,可空)、`enabled`。 +- **计划名称 `name`**(2026-08-30 新增,仅展示字段,不参与 `store_id + report_definition_id` 幂等/关联逻辑): + `report.deliveryPlan.save` 可选入参(未传不覆盖既有值;`null`/空串/全空白归一化为 `null` 显式清空; + 非空 `trim` 后最长 100 字符,超长报错「计划名称 name 长度不能超过 100 字符」); + `save` 成功响应与 `report.deliveryPlan.list` 列表项均返回 `name`(未设置时为空字符串)。 + +```json +// report.deliveryPlan.save(name 可选) +{ + "store_id": 1001, + "report_id": 1, + "schedule_times": ["09:00", "17:30"], + "name": "每日库存报表投递", + "late_grace_minutes": 60 +} +``` +- **渠道收敛兜底**:历史计划残留的 wecom/link 渠道在投递时**按 inbox 兜底执行**(仅记录 warn 日志,不抛错,避免历史计划卡死)。 +- **迁移归一化**:迁移 `20260829170000` 已把两表 `channel` 列默认值 wecom → inbox、comment 收敛, + 存量 `channel IN ('wecom','link')` 行统一 UPDATE 为 `inbox`(模型 `defaultValue: 'inbox'` 同步); + `report.deliveryPlan.list` / `report.deliveryLog.list` 响应 `channel` 恒为 `inbox`。 +- **投递记录** `wms_report_delivery_log`:状态机与 `status` 一致: + `pending → exporting → delivered / failed / cancelled`;`report_definition_id` 关联报表定义ID, + `report_name` 为投递时报表名称快照(审计回放,定义删除后仍可追溯)。 +- **调度**(`reportDelivery.dispatch`,分钟级):按 HH:mm + 宽限窗口命中后, + 对每个 `(store_id, report_definition_id, biz_date, time_point)` 幂等生成报表并投递(防重不防漏)。 +- **投递/通知幂等键含货主维度**(2026-08-31 修复「货主限制不符」缺陷):inbox 投递消息 `ext_id` 为 + `report:{store_id}:{report_definition_id}:{biz_date}:{time_point}`,文本通知幂等键为 + `report:notify:{store_id}:{report_definition_id}:{biz_date}:{time_point}`; + 修复前不含 `store_id`,不同货主的投递/通知消息会互相复用、串扰。 +- **货主维度强校验**(2026-08-31):`processOne` 对 `store_id`/`report_definition_id` 强校验, + 任一无效直接抛错「投递计划维度非法(…),拒绝生成报表」,绝不生成跨货主报表。 +- **文件消息投递目标与群路由口径**(2026-09-01 修复 G1 缺陷):报表文件消息(inbox 渠道) + **只投递到计划配置的通知群 `notify_group_ids`**,不再投递任意「货主默认群」; + 未配置通知群的历史计划保持旧行为,回退投递到货主默认站内信群(`group_type='store'`,按 id ASC 取最早一条)。 + 配置了群但全部不可达(不存在/已删除/被屏蔽/仓库不一致)时直接抛错「配置的通知群不可达…无法投递」 + 进入 `failed` 退避重试(`MAX_RETRY=3`,退避 `retry_count × 60s`),不再静默回退到未配置群。 + 投递与文本通知共用 `resolveNotifyGroups` 解析口径(过滤 `is_blocked=1`、软删、仓库维度一致)。 +- **失败自动重推**:inbox 推送失败(`success=false` 或消息回写 `push_status=3`)时,立即复用 + `inbox.message.retry` **重推一次**(`ext_id` 幂等复用同一条消息记录,不重复写);重推仍失败进入 + `failed` 退避重试:`MAX_RETRY=3`,退避 `retry_count × 60s`;重试扫描条件 + `status=failed 且 retry_count<3 且 next_retry_at<=now`;卡在 exporting 超过 30 分钟视为陈旧可重扫。 +- **biz_date 口径**:正常投递为触发日 T-1;跨零点补投(时间点晚于当前时刻)为触发日 T-2, + 与昨日正常投递口径一致,避免与次日正常投递撞幂等键。 + +### 5.1 文本通知模板与定向群/成员(notify_template / notify_group_ids / notify_member_ids) + +投递计划可在投递完成后附带发送一条文本通知(与投递渠道独立,inbox 渠道投递后同样生效;未配置时行为与旧版完全一致)。 +三个字段均为可选,仅在 `report.deliveryPlan.save` 入参存在时生效(更新时未传保持原值)。 + +#### 5.1.1 notify_template(文本通知模板) + +- 最长 **500** 字符,超出报错;空值/未传视为未启用。 +- 标签白名单(仅以下 4 个标签会被渲染,其余 `{xxx}` 视为未知标签,保存时报错并列出非法标签): + +| 标签 | 渲染内容 | +|---|---| +| `{time}` | 发送时间,格式 `YYYY-MM-DD HH:mm` | +| `{url}` | 报表文件下载链接;链接为空时替换为兜底文案「文件生成中,稍后可在投递记录中查看」 | +| `{report_name}` | 报表名称 | +| `{biz_date}` | 数据日期 `YYYY-MM-DD` | + +- 示例模板:`【{report_name}】{biz_date} 数据报表已生成,下载:{url}(生成时间 {time})` + +#### 5.1.2 notify_group_ids(通知群,定向内部群) + +- 元素为 `wms_inbox_group.id`(内部群 ID),**正整数**、自动去重并升序,最多 **20** 个。 +- 保存时校验存在性:软删(已删除)的群报错并**列出缺失 ID**;被屏蔽(`is_blocked=1`)的群仍可选中, + 屏蔽属于发送时过滤维度。 +- **同时为报表文件消息的投递目标**:计划配置了 `notify_group_ids` 时,文件消息(inbox 渠道) + **仅逐群投递到这些配置群**,不再投递任意「货主默认群」;未配置通知群的历史计划回退投递到 + 货主默认站内信群(`group_type='store'`,取最早一条);配置的群全部不可达 + (不存在/已删除/被屏蔽/仓库不一致)时投递抛错进入 `failed` 退避重试。 +- 发送时逐群推送(群维度协议字段 `group_id`/`group_name` 为单值),并再次过滤 + `is_blocked=1`、软删、仓库维度不一致的群;此类群不发送且不进入投递记录快照。 + +#### 5.1.3 notify_member_ids(通知成员,定向外部成员) + +- 元素为**外部 IM 用户 ID**,**非空字符串**、自动去重,最多 **100** 个。 +- 推送时 `user_id` **数组整体透传**(目标侧协议支持 user_id 数组),不循环拆发; + 选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送。 + +#### 5.1.4 发送规则与投递记录快照 + +- 未配置模板或未选择任何群/成员时**不发送**(投递行为不变)。 +- 发送时机:报表生成并完成渠道投递后(`delivered` 回写前),失败抛异常走失败退避重试 + (`MAX_RETRY=3`,退避 `retry_count × 60s`)。 +- 发送结果快照 `notify_targets` 随投递记录落库并在 `report.deliveryLog.list` 返回: + +```json +{ + "group_ids": [1, 3], + "member_ids": ["user-1001", "user-1002"], + "notify_text": "【7日出入库数据】2026-08-28 数据报表已生成,下载:https://...(生成时间 2026-08-29 09:00)" +} +``` + +- `group_ids` 为**实际发送**的群内部 ID 列表;`member_ids` 为实际发送的成员 ID 列表; + `notify_text` 为标签替换后的最终文本;未发送文本通知时快照为 `null`。 + +## 6. 报表定义保存示例(report.definition.save) + +```json +{ + "name": "库存变化以及补货报表", + "type": "stockFlow", + "fileName": "库存变化_{date}.xlsx", + "fields": ["item_name", "barcode", "item_code", "daily", "pending_occupy", "available", "ck_total", "suggest", "warn"], + "is_enabled": 1, + "remark": "" +} +``` + +- `type` 必须命中注册表(当前 `stockFlow`、`interceptOrder`,未知报「未知的报表类型: 」); + `fields` 必须为该类型注册字段子集(9 组列任意勾选,含非法 key 报可读错误并列出可用字段)。 +- `file_name` 兼容 `fileName` 驼峰写法(驼峰优先);新增必填 `name`/`type`/`file_name`/`fields`; + 更新按 `id` upsert,未传字段不覆盖;软删记录命中时自动恢复。 +- 保存成功后响应即报表定义视图: + `{ id, name, type, file_name, fields, is_enabled, remark, created_at, updated_at }`。 + +## 7. report.definition.typeList(前端元数据接口) + +### 7.1 用途 + +`report.definition.typeList`:免权限只读(仅登录),返回注册类型清单 +`[{ key, title, description, window, fields }]`,供前端报表设计器渲染「报表类型」选择与字段树。 + +实现:`report.definition.typeList` → `app/service/systemMethods/report/definition.js` → `systems/report.js listRegisteredTypes`。 + +> 鉴权/日志口径:`report.definition.typeList` 在 `definition.js` 的 `systemInit` 名单内 +> (`_noNeedRight/_noNeedAuth/_noNeedLog='typeList'`:免权限 + 免鉴权 + 不写审计日志,仅登录; +> 同模块 `save/list/delete` 未声明免权限,仍需授权)。 + +> 历史:`report.meta` 已于 2026-08-31 移除(下线)。前端获取窗口参数 +> `window.dayCount/cutoverHour` 请用 `report.definition.typeList`;某报表定义勾选字段 +> 请用 `report.definition.list` 响应中的 `fields` 数组(与 `typeList` 字段树 key 对照)。 + +### 7.2 请求示例 + +```json +// report.definition.typeList(无必填参数) +{} +``` + + +### 7.3 响应示例 + +```json +// report.definition.typeList +{ + "flag": "success", + "code": 1, + "message": "ok", + "list": [ + { + "key": "stockFlow", + "title": "库存变化以及补货报表", + "description": "按日窗口聚合出入库流水与正品库存,……", + "window": { "dayCount": 7, "cutoverHour": 7 }, + "fields": [ + { "key": "item_name", "label": "产品名称", "type": "string" }, + { "key": "barcode", "label": "条码", "type": "string", "asText": true }, + { "key": "item_code", "label": "外部编码", "type": "string", "asText": true }, + { "key": "daily", "label": "每日出入库", "type": "array", "children": [ + { "key": "ck", "label": "出库数", "type": "number" }, + { "key": "rk", "label": "入库数", "type": "number" } + ]}, + { "key": "pending_occupy", "label": "待处理订单占用数", "type": "number" }, + { "key": "available", "label": "可用库存", "type": "number" }, + { "key": "ck_total", "label": "7日总出库数量", "type": "number" }, + { "key": "suggest", "label": "推荐采购量", "type": "number", "computed": true }, + { "key": "warn", "label": "是否触发预警", "type": "boolean", "computed": true } + ] + } + ] +} +``` + +> 说明:`list` 按注册顺序返回**全部**注册类型(当前 `stockFlow`、`interceptOrder`),上例仅展开 `stockFlow`; +> `interceptOrder` 的 `window` 为 `{ "dayCount": 1, "cutoverHour": 0 }`,`fields` 为 46 个 `type: "string"` 静态列 +> (列清单与口径见 2.2 节)。 + +字段元素结构:`{ key, label, type, computed?, asText?, children? }`: + +- `type`:`string` / `number` / `boolean` / `array`; +- `computed: true`:预计算字段(非原始表字段,如 `suggest`/`warn`); +- `asText: true`:该列以文本单元格落地(由类型字段规格硬编码,如 `item_code`/`barcode`); +- `children`:数组类型字段的子字段(如 `daily` 的 `ck`/`rk`)。 + +### 7.4 前端如何获取可用字段 + +1. 调用 `method=report.definition.typeList`(`POST /system`,header 带 `Authorization: Bearer ` 与 `platform`) + 获取全部注册类型与字段树(含窗口参数 `window.dayCount/cutoverHour`); +2. 保存报表定义时按类型字段树勾选 `fields`(`method=report.definition.save`); +3. 渲染/导出前用 `report.definition.list` 取该报表定义已勾选的 `fields` 数组(与 `typeList` 字段树 key 对照); +4. 导出 sheet 的列由「勾选字段 × 类型硬编码规格」自动生成,前端无需下发任何列配置。 + +## 8. 报表定义管理接口(report.definition.save / list / delete) + +管理侧维护 `wms_report_definition` 的 3 个接口,均需登录且需鉴权(`isNeedAuth=true`、`isNeedLogin=true`, +`POST /system`,header 带 `Authorization: Bearer ` 与 `platform`)。 + +- `report.definition.save`:按 `id` upsert(未传 id 新增),入参 + `{ id?, name, type, file_name/fileName, fields, is_enabled?, remark? }`; + `type` 必须命中注册表、`fields` 必须为该类型注册字段子集(非法 key 报可读错误列出); + 新增必填 `name/type/file_name/fields`;软删记录命中时自动恢复。 +- `report.definition.list`:`where { name, type, is_enabled }` + `pagination` + `sort` + (sort 白名单 `id/name/type/is_enabled/created_at/updated_at`,默认 id DESC); + 响应每行 `{ id, name, type, file_name, fields, is_enabled, remark, created_at, updated_at }`,软删自动排除。 +- `report.definition.delete`:入参 `id`;删除前按 `report_definition_id` 统计投递计划引用, + 仅拦截「启用中」的计划(`enabled=1`,报「存在 N 个启用的投递计划引用该报表,请先停用计划」), + 停用计划不阻断;重复删除同一 ID 幂等成功(`deleted` 恒为 1)。 +实现:`app/service/systemMethods/report/definition.js` → `app/service/systems/report.js` 的 +`saveDefinition` / `listDefinitions` / `deleteDefinition`。 + +> 鉴权口径:三个接口 `systemInit` 均未声明免权限(`isNeedAuth=true`),仅通配符角色 +> (超级管理员/仓库管理员)或已授权角色可用;本次仅文档同步,未扩任何角色授权 +> (权限缺口可用 `npm run permission:sync:system-api -- --dry-run` 预演)。 + diff --git a/frpc.toml b/frpc.toml new file mode 100644 index 0000000..4d3c28b --- /dev/null +++ b/frpc.toml @@ -0,0 +1,17 @@ +# frpc 客户端配置(frp v0.70.1,复用本机 printServer 的 frpc.exe;生产 frps 为 v0.61.1) +# 用途:将本地 WMS 开发服务(http://127.0.0.1:6060)通过生产环境 frps +# 暴露为 http://test.wms.o.gztbyc.com(frps subDomainHost=o.gztbyc.com)。 +# 启动:npm run frpc:start(首次自动从 D:\printServer 复制 frpc.exe 到 script/frp/) + +serverAddr = "112.124.21.102" +serverPort = 6005 +auth.token = "frpPrintToken2024" + +# 测试域名:test_wms.o.gztbyc.com +# (subdomain + 生产 frps 的 subDomainHost 泛域名拼接,经 vhostHTTPPort 18080 对外) +[[proxies]] +name = "wms-test" +type = "http" +localIP = "127.0.0.1" +localPort = 6060 +subdomain = "test_wms" diff --git a/logo.svg b/logo.svg new file mode 100644 index 0000000..bfc0aec --- /dev/null +++ b/logo.svg @@ -0,0 +1,10 @@ + + + + + + + + + W + diff --git a/methods/changes/gateway.json b/methods/changes/gateway.json new file mode 100644 index 0000000..aa2f457 --- /dev/null +++ b/methods/changes/gateway.json @@ -0,0 +1,14 @@ +[ + { + "version": "2026.04.07-gateway-01", + "date": "2026-04-07", + "summary": "初始化 gateway 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", + "methods": [ + "*" + ], + "notes": [ + "methods/gateway.json 仍为单一事实来源(SSOT)。", + "本文件仅记录变更历史与补充说明。" + ] + } +] diff --git a/methods/changes/openapi.json b/methods/changes/openapi.json new file mode 100644 index 0000000..9674c0b --- /dev/null +++ b/methods/changes/openapi.json @@ -0,0 +1,446 @@ +[ + { + "version": "2026.09.14-openapi-entryorder-standard-json", + "date": "2026-09-14", + "type": "updated", + "summary": "openapi entryorder.create 补充标准请求/响应 JSON:新增 requestExample(POST /openapi 的 query + headers + body 完整示例,含 entryOrder 全字段与 orderLines.orderLine 明细)与 responseExample(success 扁平响应 + businessFailure 业务失败响应两态),并追加说明性 notes。", + "methods": [ + "entryorder.create" + ], + "notes": [ + "requestExample 依据口径:entryOrder.ownerCode 落 wms_entry_order.qimen_owner_code;warehouseCode / operateTime / operatorName 当前未生效(保留字段);expectedArriveTime→expect_start_time、createTime→order_create_time、expectEndTime→expect_end_time、relatedOrders.relatedOrder.orderCode→purchase_order_code", + "responseExample 依据口径:/openapi 成功响应为扁平标准结构(flag/code/message + 业务字段 + timestamp),非 data 包裹;业务失败同样 HTTP 200 但 flag=failure、code=0;入口级失败(参数/时间戳/签名/合约)为 HTTP 400/401/403 + data:null", + "requestExample.query 中 sign 计算规则:canonicalQuery(query 去 sign 后按 key 字母序拼接)+ self_app_secret + md5(stableStringify(body)) 再取 md5(见 app/lib/api_sign.js)", + "两个新键为文档自描述键(self-describing),不参与运行时代码逻辑;update 脚本 upsert 为整条替换,spec 已从现有文档克隆完整 method 对象(含 params / requestBody / response / errors / notes),未丢字段" + ] + }, + { + "version": "2026.09.14-openapi-entryorder-owner-code-align", + "date": "2026-09-14", + "type": "updated", + "summary": "openapi entryorder.create 字段生效口径标注:明确 entryOrder.ownerCode 落库 wms_entry_order.qimen_owner_code(代码同步补齐,API 来源出站回传 entryorder.confirm 的 ownerCode 不再为空);标注 entryOrder.warehouseCode、entryOrder.operateTime、entryOrder.operatorName 当前未生效(仓库取 app_key 合约解析结果、后两者不落库不参与逻辑),保留字段不删除;补充主表/明细表落库列对照说明。", + "methods": [ + "entryorder.create" + ], + "notes": [ + "代码侧同步改动:app/service/openapiMethods/entryorder.js#create 将报文 entryOrder.ownerCode(trim 后)作为 customerId 传入 systems/entry_order.js#addOrder,最终落库 wms_entry_order.qimen_owner_code;奇门路径行为不变(仍取请求上下文 customerId)", + "口径依据:奇门侧 qimen_owner_code 取请求上下文 customerId,出站回传 buildEntryOrderConfirmRequest(receiving_entry_match.js)的 entryOrder.ownerCode 即取该列,此前 API 来源该列为空导致回传 ownerCode 为空", + "entryOrder.warehouseCode 在奇门侧参与合约校验(controller/home.js getQimenWarehouseCode + validateApi)并落 qimen_warehouse_code;OpenAPI 侧一律取合约 qimen_warehouse_code,报文值不生效", + "未变更:entryOrder.operateTime / operatorName 的映射保留在适配层,仅标注为当前未使用;本次不新增未登记参数项,避免扩大对外契约", + "文档写入流程:temp/api-doc-update-20260914-openapi-entryorder-field-annotation.json → npm run doc:api:update -- --spec=... --dry-run → 正式写入" + ] + }, + { + "version": "2026.09.12-openapi-order-cancel-rk-entry-order-support", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "openapi order.cancel 支持范围扩展新增 RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):按 orderCode 查入库单号,复用 ctx.service.systems.storage.entry.cancel 完整作废流程(状态守卫 + 回退收货单占用 + ENTRY_ORDER_CANCEL 操作日志),取消成功后不回传开放平台回调事件,已作废按幂等成功;其他类型仍返回暂不支持该订单类型的取消操作。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/openapiMethods/order.js cancel:新增 RK_TYPES=[B2BRK,SCRK,LYRK,CCRK,CGRK,DBRK,QTRK];orderType 经 trim().toUpperCase() 归一化,不在 ORDER/CK/RK 集合内返回「暂不支持该订单类型的取消操作」", + "RK 组分支:委托 ctx.service.systems.storage.entry.cancel({ entryOrderCode }, { storeId, warehouseId, operatorLabel=openapi:xxx, skipExternalSync=true, idempotent=true, notFoundMessage=未找到对应的入库单 });成功返回「取消入库单成功」(code=1),失败透传 message(code=0)", + "RK 组错误文案:未找到对应的入库单 / 已完成入库单不允许作废(order_status=COMPLETED)/ 入库单已完成回传,不可取消(sync_status=SUCCESS);已 CANCELLED 幂等成功;skipExternalSync=true 不回传开放平台回调事件", + "methods/openapi.json:order.cancel 的 description、params/requestBody 的 orderCode 与 orderType 描述(RK 组 7 枚举中文名与奇门 this.orderType 一致:B2BRK=B2B入库、SCRK=生产入库、LYRK=领用入库、CCRK=残次品入库、CGRK=采购入库、DBRK=调拨入库、QTRK=其他入库)、errors(新增 3 条 RK 文案,code=0)、notes(新增 RK 组语义与复现口径 orderCode=RK_2, orderType=CGRK)", + "文档版本 1.2.2 -> 1.2.3(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-openapi-order-cancel-ck-stockout-support", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "openapi order.cancel 支持范围由 JYCK/HHCK/BFCK 扩展为 JYCK/HHCK/BFCK + CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH):CK 组按 orderCode 查出库单号取消 wms_order_stockout(仅 CREATED/PENDING 可取消,委托共享实现 systems/stockout_order.js#cancel),JYCK/HHCK/BFCK 仍操作 wms_order_delivery(行为不变),其他类型返回暂不支持该订单类型的取消操作;同步补充 CK 组文案与 notes。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/openapiMethods/order.js cancel:ORDER_TYPES=[JYCK,HHCK,BFCK]、CK_TYPES=[PTCK,DBCK,B2BCK,QTCK,CGTH];orderType 经 trim().toUpperCase() 归一化,不在两集合内返回「暂不支持该订单类型的取消操作」", + "CK 组分支:orderCode 缺省返回「orderCode 参数缺失」;委托 ctx.service.systems.stockoutOrder.cancel({ stockoutOrderCode }, { storeId, warehouseId, operatorLabel=openapi:xxx });成功「取消出库单成功」,不回传开放平台回调事件", + "出库单状态枚举 CREATING/CREATED/PENDING/COMPLETED/CANCELLED/TRANSFERRED;仅 CREATED/PENDING 可取消,已 CANCELLED 幂等返回成功;未找到返回「未找到对应的出库单」,状态不允许返回「出库单当前状态(xxx)不允许取消」,异常返回「取消失败:xxx」", + "methods/openapi.json:order.cancel 的 description、params/requestBody 的 orderCode 与 orderType 描述、response.data 描述、errors(「订单号不能为空」修正为「orderCode 参数缺失」,新增未找到对应的出库单/出库单当前状态(xxx)不允许取消/取消失败:xxx)、notes(新增 CK 组路由差异与回传口径)", + "文档版本 1.2.1 -> 1.2.2(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-openapi-order-cancel-orderType-normalize", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "openapi order.cancel 的 orderType 参数说明小幅补充大小写不敏感归一化(内部 trim 后转大写,jyck/Jyck/JYCK 等价),枚举 JYCK/HHCK/BFCK 及默认值 JYCK 保持不变(代码依据 openapiMethods/order.js cancel:String(body.orderType || 'JYCK').trim().toUpperCase())。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/openapiMethods/order.js cancel:orderType 取 JYCK(默认)/HHCK/BFCK,内部 trim().toUpperCase() 归一化,三者均映射为出库单 ORDER;其他值返回暂不支持该订单类型的取消操作", + "methods/openapi.json:order.cancel 的 params.orderType 与 requestBody.orderType description 追加大小写不敏感说明;notes 新增一行归一化说明,其余字段未改动", + "文档版本 1.2.0 -> 1.2.1(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-openapi-stockout-create-query", + "date": "2026-09-12", + "summary": "新增开放 API 出库单接口 stockout.create / stockout.query,与奇门 stockout 共用同一份实现(抽离到 systems/stockout_order.js),开放 API 来源落库 source_type=API。", + "methods": [ + "stockout.create", + "stockout.query" + ], + "notes": [ + "app/service/systems/stockout_order.js 新增:抽离原 qimenMethods/stockout.js 的 create/query 核心实现,入参沿用奇门报文结构(request.deliveryOrder / request.orderLines),上下文(storeId/warehouseId/warehouseCode/appKey/sourceType)由调用方显式传入", + "app/service/qimenMethods/stockout.js 改为薄适配层:create 委托 systems.stockoutOrder.create(sourceType=QM),query 委托 systems.stockoutOrder.query,行为与重构前一致", + "app/service/openapiMethods/stockout.js 新增薄适配层:入参为开放 API 扁平结构(body.deliveryOrder / body.orderLines / body.deliveryOrderCode),创建时 sourceType=API,出库单回传走 OpenAPI 回调 event=stockout_completed", + "methods/openapi.json 新增「出库单模块」(module=stockout),文档版本升至 1.2.0", + "库存锁标记沿用 QM_STOCKOUT,与 storage.stockout.cancel / confirm / toOrder 的释放口径保持一致", + "文档生成:node ./script/update-api-doc.cjs --spec=temp/api-doc-update-openapi-stockout.json(先 --dry-run 校验)" + ], + "type": "added", + "module": "stockout" + }, + { + "version": "2026.08.30-openapi-entryorder-create-item-match-fix", + "date": "2026-08-30", + "summary": "entryorder.create 商品匹配修复文档同步(与奇门渠道共用 addOrder 逻辑):三级匹配策略(itemId 主键直查 > itemCode 精确匹配 > 归一化条码匹配)、编码支持中文后缀、item_id 统一写入 StockStore 数字主键、失败信息回显真实 SKU/商品/编码并附订单行号", + "methods": [ + "entryorder.create" + ], + "notes": [ + "商品匹配三级策略:itemId 主键直查(纯数字且不超 BIGINT 范围、货主一致)> itemCode 精确匹配 > itemCode 归一化条码匹配(取编码开头连续数字)", + "带中文后缀编码精确匹配不到时按归一化条码对齐;归一化命中多商品时报错不静默", + "item_id 统一写入实际匹配到的 StockStore 数字主键 id,修复 Data truncated for column 'item_id'", + "itemId 字段类型说明更新为 string|number(可接收带后缀的字符串,非纯数字视为未提供)", + "失败信息回显真实 SKU/商品/编码并附订单行号(未同步推送到仓库 / wms无对应关系 / 归一化匹配到多个商品)", + "测试:OpenAPI 渠道中文后缀编码重放回归通过(T5),10 passing / 0 failing(2026-08-30)" + ], + "type": "updated", + "module": "entryorder" + }, + { + "version": "2026.08.27-openapi-service-conflict-fix", + "date": "2026-08-27", + "summary": "修复 Egg 服务命名冲突:app/service/openapi.js 重命名为 openapiEntry.js,恢复 ctx.service.openapi.callback 可用", + "methods": [], + "notes": [ + "根因:app/service/openapi.js 文件与 app/service/openapi/ 目录同名,Egg ContextLoader 把目录里的 callback/callbackRegistry 挂成 OpenapiService 类的静态属性,实例上不可见,导致运行时 ctx.service.openapi.callback 为 undefined", + "修复:openapi.js 重命名为 openapiEntry.js(服务路径 ctx.service.openapiEntry),app/controller/openapi.js 的 processRequest 引用同步更新,AI_METHOD_ROUTING.md 同步", + "影响:storage.entry.quickInbound 对 API 来源直入单回传 entry_order_direct_inbound_completed 事件不再报 Cannot read properties of undefined (reading 'sendWithRetry'),库存两段式(先回传后写库)可正常执行" + ], + "type": "fixed" + }, + { + "version": "2026.06.04-openapi-04", + "date": "2026-06-04", + "summary": "文档结构优化:拆分 endpoints 为 methods.groups 多分组(基础模块 / 发货单模块)", + "methods": [], + "notes": [ + "将单一 endpoints 数组重构为 methods.groups 多分组结构", + "基础模块:index.ping", + "发货单模块:deliveryorder.create、deliveryorder.query", + "移除顶层 groupName 字段,分组名改由各 group 独立声明" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-03", + "date": "2026-06-04", + "summary": "新增 deliveryorder.create 和 deliveryorder.query 方法文档", + "methods": [ + "deliveryorder.create", + "deliveryorder.query" + ], + "notes": [ + "新增 deliveryorder.create:创建发货单接口,支持订单主信息、收件人信息、订单明细的完整入参;创建渠道为 API,平台/快递自动匹配", + "新增 deliveryorder.query:查询发货单接口,根据 deliveryOrderCode 查询订单详情", + "所有参数使用驼峰命名(camelCase),不做下划线兼容", + "requestBody 字段按 deliveryOrder.xxx、deliveryOrder.receiverInfo.xxx、orderLines.orderLine、[].orderLine.xxx 层级清晰标注" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-02", + "date": "2026-06-04", + "summary": "移除 ping.echo 和 index.health,只保留 index.ping", + "methods": [ + "ping.echo", + "index.health" + ], + "notes": [ + "移除 ping.echo:回显接口暂不对外开放", + "移除 index.health:健康检查接口暂不对外开放", + "当前仅保留 index.ping 心跳接口" + ], + "type": "removed" + }, + { + "version": "2026.06.04-openapi-01", + "date": "2026-06-04", + "summary": "移除入口方法 openapi.index,新增 index.health 和 ping.echo 方法文档", + "methods": [ + "openapi.index", + "index.health", + "ping.echo" + ], + "notes": [ + "移除 openapi.index:该方法是 POST /openapi 的入口端点,非业务方法,从文档中移除", + "新增 index.health:基础模块健康检查接口,返回 openapiMethods 模块状态", + "新增 ping.echo:ping 模块回显接口,将请求体原样返回,用于调试连通性和签名验证" + ], + "type": "modified" + }, + { + "version": "2026.04.26-openapi-01", + "date": "2026-04-26", + "summary": "新增 openapi 入口文档骨架(/openapi),包含请求体解析、app_key 与签名校验规则", + "methods": [ + "openapi.index" + ], + "notes": [ + "新增 methods/openapi.json:记录 /openapi 入口的文档骨架与校验约定(JSON body 解析、统一错误格式、app_key 校验、签名规则)。", + "核心校验规则:1) body 使用 JSON 解析,优先 rawBody;2) 错误对外格式使用 toFailure(flag/code/message/data/timestamp);3) app_key 仅当数据库记录的 interface_type_id=2 且 is_enabled=1 时视为有效;4) 签名按 query 字段字母序排序(排除 sign/signature)+ selfAppSecret + bodySign(md5(stableSerialize(body))),对拼接字符串取 md5。" + ], + "type": "added" + }, + { + "version": "2026.04.26-openapi-02", + "date": "2026-04-26", + "summary": "说明:/openapi 入口不校验请求头,补充签名别名与 app_key 有效性说明", + "methods": [ + "openapi.index" + ], + "notes": [ + "修正:明确 /openapi 入口不对请求头进行强制校验(与 qimen 一致),headers 字段仅作为参考。", + "确认:body JSON 解析(rawBody 优先)与错误消息保持为 'json数据为空' / 'json数据解析错误';app_key 校验仅当 wms_api_app.interface_type_id=2 且 is_enabled=1 时有效。", + "补充:签名字段别名说明(sign/signature)与 app_key 别名(app_key/appkey/self_app_key);签名算法与实现参见 app/lib/api_sign.js。" + ], + "type": "modified" + }, + { + "version": "2026.04.26-openapi-03", + "date": "2026-04-26", + "summary": "新增 openapi 方法 index.ping(基础模块,心跳接口)", + "methods": [ + "index.ping" + ], + "notes": [ + "新增 openapi 可用性检测接口 index.ping,返回与系统成功结构一致(包含 code/message/data)。" + ], + "type": "added" + }, + { + "version": "2026.04.26-openapi-04", + "date": "2026-04-26", + "summary": "规范化 /openapi 文档:独立链路、移除请求头校验、返回风格改为 code/message/data、明确签名与 app_key 校验、指向 openapiMethods 分发。", + "methods": [ + "openapi.index", + "index.ping" + ], + "notes": [ + "本次变更:", + "1) 明确 /openapi 为独立链路,不复用 system/qimen 的请求头校验;", + "2) 移除 platform/project 等请求头的强校验说明;", + "3) 返回结构与 system 风格对齐(使用 code/message/data,移除额外 flag 字段);", + "4) 保持 body 为 JSON(rawBody 优先),并明确错误文案为 'json数据为空' / 'json数据解析错误';", + "5) 明确 app_key 仅当 wms_api_app.interface_type_id=2 且 is_enabled=1 时视为有效;", + "6) 明确签名算法:query 按字母序排序 + self_app_secret + bodySign(md5(stableSerialize(body))),支持别名 sign/signature 与 app_key/appkey/self_app_key;", + "7) 说明 method 分发走 openapiMethods 专用目录,示例方法 index.ping(基础模块)。" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-05", + "date": "2026-06-04", + "summary": "新增订单模块 order.cancel 方法", + "methods": [ + "order.cancel" + ], + "notes": [ + "新增 order.cancel:取消发货单接口,支持直接取消未拣货/未打印的订单;已拣货或已打印的改为拦截状态", + "当前支持 JYCK(一般交易出库)、HHCK(换货出库)、BFCK(补发出库)三种出库单类型", + "取消操作为不可逆操作" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-06", + "date": "2026-06-04", + "summary": "补齐 deliveryorder.create、deliveryorder.query、order.cancel 的 params 入参文档", + "methods": [ + "deliveryorder.create", + "deliveryorder.query", + "order.cancel" + ], + "notes": [ + "为三个方法的 params 数组补充标准 OpenAPI query 参数:method、v、timestamp、app_key、sign" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-07", + "date": "2026-06-04", + "summary": "修正 params 字段:从 query 签名参数改为 POST body 业务参数(与 requestBody 保持一致)", + "methods": [ + "deliveryorder.create", + "deliveryorder.query", + "order.cancel" + ], + "notes": [ + "params 现包含 POST body 的业务入参(与 requestBody 一致),query 签名参数已通过页面顶部签名说明覆盖" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-08", + "date": "2026-06-04", + "summary": "新增商品模块 singleitem.synchronize 和 singleitem.query 方法", + "methods": [ + "singleitem.synchronize", + "singleitem.query" + ], + "notes": [ + "新增 singleitem.synchronize:商品同步接口,按 itemCode 唯一约束创建或更新商品信息,联动库存表", + "新增 singleitem.query:商品查询接口,按 itemId 返回完整商品信息", + "所有参数使用驼峰命名(camelCase)" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-09", + "date": "2026-06-04", + "summary": "singleitem.synchronize 的 warehouseCode 改为从 app_key 自动解析,不再要求调用方必传", + "methods": [ + "singleitem.synchronize" + ], + "notes": [ + "warehouseCode 改为可选参数,默认从 app_key 绑定的仓库(api_app.qimen_warehouse_code)自动解析", + "ownerCode 同步改为可选参数" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-10", + "date": "2026-06-04", + "summary": "安全加固:移除 singleitem.synchronize 的 warehouseCode 和 ownerCode 入参,完全由 app_key 自动解析", + "methods": [ + "singleitem.synchronize" + ], + "notes": [ + "warehouseCode 和 ownerCode 从 params 中移除,调用方不可传入或覆盖", + "两个字段完全由服务端根据 app_key 自动解析,确保仓库/货主绑定关系不可被篡改" + ], + "type": "modified" + }, + { + "version": "2026.06.04-openapi-11", + "date": "2026-06-04", + "summary": "新增库存模块 inventory.query 方法", + "methods": [ + "inventory.query" + ], + "notes": [ + "新增 inventory.query:批量库存查询接口,按商品 ID 列表返回可用量和锁定量", + "支持批量查询,减少请求次数", + "库存不足的商品不会出现在返回结果中" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-12", + "date": "2026-06-04", + "summary": "新增回调模块 callback.test 方法及统一回调通知系统", + "methods": [ + "callback.test" + ], + "notes": [ + "新增 callback.test:模拟回调测试接口,向 callback_url 发送签名回调", + "新增 app/service/openapi/callback.js:统一回调服务,支持签名+重试+日志", + "订单同步完成时自动触发 API 渠道回调(fire-and-forget,不影响主流程)", + "回调签名算法与 OpenAPI 入口完全一致" + ], + "type": "added" + }, + { + "version": "2026.06.04-openapi-13", + "date": "2026-06-04", + "summary": "移除回调模块(回调测试改为独立页面 /docs/api/openapi/callback-test)", + "methods": [ + "callback.test" + ], + "notes": [ + "回调测试不再作为 OpenAPI method,改为独立路由页面 /docs/api/openapi/callback-test", + "页面支持下拉选择注册事件、填入测试 URL、前端计算签名、模拟回调推送", + "回调事件注册表位于 app/service/openapi/callbackRegistry.js" + ], + "type": "removed" + }, + { + "version": "2026.06.05-openapi-14", + "date": "2026-06-05", + "summary": "增加 timestamp 时效校验(±10分钟),超时返回 400", + "methods": [], + "notes": [ + "所有 OpenAPI 方法增加 timestamp 与服务器时间差校验,超过 ±10 分钟返回 400", + "docs.js 签名说明区同步更新注意事项" + ], + "type": "modified" + }, + { + "version": "2026.06.05-openapi-15", + "date": "2026-06-05", + "summary": "deliveryorder.create 收件人信息改为必填(name/mobile/province/city/area/detailAddress)", + "methods": [ + "deliveryorder.create" + ], + "notes": [ + "receiverInfo 6个字段改为必填,避免快递取号时因地址缺失失败", + "mobile 和 tel 二选一必填" + ], + "type": "modified" + }, + { + "version": "2026.06.17-openapi-16", + "date": "2026-06-17", + "summary": "新增入库单模块(entryorder),支持 create(创建入库单)和 query(查询入库单)两个方法", + "methods": [ + "entryorder.create", + "entryorder.query" + ], + "notes": [ + "新增 entryorder.create:创建入库单接口,支持入库单主信息(entryOrder)和商品明细(orderLines.orderLine)的完整入参;创建渠道固定为 API", + "新增 entryorder.query:查询入库单接口,根据 entryOrderCode 查询入库单详情,返回基本信息及商品明细", + "itemCode 与 itemId 二选一,优先使用 itemId", + "openapi 通道新增入库单创建和查询能力" + ], + "type": "added" + }, + { + "version": "2026.06.23-openapi-01", + "date": "2026-06-23", + "summary": "入库单新增 CREATED 状态:entryorder.create 返回 status 说明更新为 CREATING=创建中/CREATED=已创建;entryorder.query 返回 status 可能值补充 CREATED", + "methods": [ + "entryorder.create", + "entryorder.query" + ], + "notes": [ + "entryorder.create response data.status 说明从通用描述更新为 CREATING=创建中明细行未全部插入 / CREATED=已创建完成", + "entryorder.query description 补充返回的 status 可能为 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED" + ], + "type": "updated", + "module": "entryorder" + }, + { + "version": "2026.06.23-openapi-02", + "date": "2026-06-23", + "summary": "入库单状态从 7 个简化为 5 个:移除 CONFIRMED 和 PARTIAL_RECEIVED,entryorder.query 的 status 枚举同步更新为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED", + "methods": [ + "entryorder.query" + ], + "notes": [ + "entryorder.query description 中 status 枚举从 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 简化为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED,与 wms_entry_order.order_status ENUM 当前定义一致" + ], + "type": "updated" + } +] diff --git a/methods/changes/openapi_callback.json b/methods/changes/openapi_callback.json new file mode 100644 index 0000000..09341e9 --- /dev/null +++ b/methods/changes/openapi_callback.json @@ -0,0 +1,97 @@ +[ + { + "version": "2026.09.13-openapi-callback-confirm-before-deduct", + "date": "2026-09-13", + "type": "updated", + "summary": "deliveryorder.confirm 同步顺序与奇门渠道对齐:删除 notifyApiDeliveryOrderConfirmsInternal(原「同步完成后 fire-and-forget 逐单回调,失败仅 warn」),新增 processApiOrderInternal 逐单「先回调、成功再扣减库存并置 sync_status='fin'」,失败统一 markApiSyncFailedInternal 回写 sync_status='error' + 待处理异常、不扣减库存、可重新派发;解析不到 appKey 的订单不再静默跳过,改为按失败处理。文档版本 1.3.0 → 1.4.0。", + "methods": [ + "deliveryorder.confirm" + ], + "notes": [ + "代码(app/service/systems/order_async.js,API 渠道):删除 notifyApiDeliveryOrderConfirmsInternal;新增 processApiOrderInternal(逐单):① buildQimenDeliveryOrderConfirmDataInternal 组装报文(缺 ownerCode → 失败)→ ② 解析发送用 appKey(context.appKey 优先,缺失时按 store_id + warehouse_id 合约反查 wms_store_warehouse(auth_status=2) → wms_api_app(is_enabled=1 且 callback_url 非空) 的 self_app_key,同批次按货主 Map 缓存)→ ③ sendByAppKey 发送 deliveryorder.confirm(最多 4 次尝试)→ ④ 回调成功才调用 processLocalChannelOrderInternal 扣减库存并置 sync_status='fin'", + "新增 markApiSyncFailedInternal:失败统一回写 sync_status='error' + markPendingException(写库失败仅记录 error 日志),不扣减库存、不置 fin,订单可重新派发(分发前过滤只跳过 fin)", + "失败文案:回调失败「OpenAPI 回调确认失败: {error}」(如「OpenAPI 回调确认失败: 回调返回非 2xx 状态码: 400」,附 callback_retry_count)/ 回调抛异常「OpenAPI 回调确认异常: ...」/ 报文组装缺货主编码「发货单缺少奇门货主编码」/ 缺 store_id「发货单缺少货主 store_id,无法解析回传用 appKey」/ 无可用 ApiApp「货主未配置可用的 OpenAPI 回调(wms_api_app 启用且 callback_url 非空)」", + "未变:appKey 解析优先级与反查口径;报文复用 buildQimenDeliveryOrderConfirmDataInternal;运单号仍由 buildOrderWaybillCodeMapInternal 批量取(现在在 finalizeLocalChannelOrdersInternal 内、仅 API 渠道构建);仍逐单发送(成功 N 单 = N 次回调),但现在每单是「先回调、成功再扣减」而不是「先扣减、后异步回调」", + "触发条件表述变更:不再是「本批存在同步成功订单后才发」,而是逐单在同步时发送(同一个 finalizeLocalChannelOrdersInternal 分发循环里,DISPATCH_BATCH_SIZE=20 批内并行)", + "同步 docs/openapi-callback-events.md(状态/§1.1/§1.2 事件表/§3.3/§2.5/§6)与 AI_METHOD_ROUTING.md 5.6;本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.13-openapi-callback-deliveryorder-confirm-appkey-resolve", + "date": "2026-09-13", + "type": "updated", + "summary": "同步 deliveryorder.confirm 触发条件(appKey 解析规则):发送用 appKey 由仅依赖调用上下文 context.appKey 改为「context.appKey 非空优先,缺失时按订单货主(store_id + warehouse_id)合约反查 wms_store_warehouse(auth_status=2) → wms_api_app(is_enabled=1 且 callback_url 非空) 的 self_app_key,同批次按货主缓存无 N+1」;解析不到 appKey 的订单 warn 后跳过、不发送。修复此前 routeContext 不含 appKey 导致该回调从未真正发出的问题。文档版本 1.2.0 → 1.3.0。", + "methods": [ + "deliveryorder.confirm" + ], + "notes": [ + "背景:order_storage_allocation.js 构造的 routeContext 不含 appKey,finalizeLocalChannelOrdersInternal 内 if(appKey) 门禁使 syncOrderIds(API) 链路的 deliveryorder.confirm 从未真正发出请求;订单 wms_order_delivery.from_key 兜不住(normalizeOrderFromKey 仅接受整数,字符串 app_key 被归一化为 null)", + "实现:order_async.js 新增 resolveOpenApiAppByStoreInternal(口径与 inbound_direct_log.js#_sendOpenApiCallback 对齐);notifyApiDeliveryOrderConfirmsInternal 逐单解析 appKey:context.appKey 优先(不触发反查)→ 按 orderRow.store_id 合约反查 → 逐货主 Map 缓存(N 成功单 / M 货主 → 2M 次查询);解析不到 appKey(订单缺 store_id / 无授权关系 / 无可用 ApiApp 配置)warn 后跳过该订单", + "同步 docs/openapi-callback-events.md 3.3 与 AI_METHOD_ROUTING.md 5.6" + ] + }, + { + "version": "2026.09.13-openapi-callback-request-protocol", + "date": "2026-09-13", + "type": "updated", + "summary": "破坏性协议变更:OpenAPI 出站回调报文体由 { event, data, metadata } 改为奇门同层级的 { request: {...} },发送端不再发送数据/元数据;event 仅保留在 query 的 method;5 个事件的 request 结构按 callbackRegistry.js 的 request 模板重写;deliveryorder.confirm 由一次批量汇总通知改为逐单发送(仅对 status='success' 的订单,成功 N 单 = N 次回调);deliveryorder.cancel 按 deliveryOrder 节点约定自定义(status 固定 CANCELED,无奇门对应接口);回调调试页预填完整报文体 { request }。文档版本 1.1.0 → 1.2.0。", + "methods": [ + "entryorder.confirm", + "entryorder.match", + "deliveryorder.confirm", + "stockout.confirm", + "deliveryorder.cancel" + ], + "notes": [ + "破坏性协议变更:body 不再有 event/data/metadata,发送端统一发送 { request: request || {} }(app/service/openapi/callback.js#sendWithRetry / sendByAppKey);event 仅用于 query 的 method", + "5 个事件 request 结构:entryorder.confirm { entryOrder, orderLines }(inbound_direct_log.js#buildEntryOrderConfirmRequest,QM/API 共用);entryorder.match { entryOrder, orderLines }(receiving_entry_match.js#buildEntryOrderConfirmRequest,QM/API 共用,outBizCode 前缀 RECEIVING_MATCH_、remark=匹配收货单{收货单号}自动回传);deliveryorder.confirm { deliveryOrder, packages{package[]}, orderLines }(order_async.js#buildQimenDeliveryOrderConfirmDataInternal);stockout.confirm { deliveryOrder, packages{package[]}, orderLines }(order_async.js#buildStockoutConfirmDataInternal,删除原先 data.stockoutOrderCode/status 薄包装);deliveryorder.cancel { deliveryOrder: { deliveryOrderCode, orderType, status:'CANCELED' } }(openapiMethods/order.js#cancel,无奇门对应接口)", + "deliveryorder.confirm 逐单语义:改动前一次回调携带整批 orderIds(含失败/跳过);改后仅对 syncResults 中 status==='success' 的订单逐单发送(成功 N 单 = N 次回调),fire-and-forget、失败仅 warn;复用原有主表+明细查询并新增 1 次运单号批量查询,无 N+1", + "事件注册表 callbackRegistry.js 由 { name, label, description, sampleData, metadata } 改为 { name, label, description, request };回调调试页 GET /docs/api/openapi/callback-test 预填完整报文体 { request: {...} }(此前预填三层 { event, data, metadata })", + "同步 docs/openapi-callback-events.md 与 AI_METHOD_ROUTING.md 5.6 节" + ] + }, + { + "version": "2026.09.12-openapi-callback-protocol-align", + "date": "2026-09-12", + "type": "updated", + "module": "callback", + "summary": "methods/openapi_callback.json 同步 2026-09-12 出站回调代码改动:回调方法 order.cancel 更名为 deliveryorder.cancel(与 /openapi 入站方法 order.cancel 区分,不做兼容、不双发);5 个事件的 timestamp 统一为秒级(10 位)规范值(原「毫秒/秒不一致待统一」已知问题已修复);补齐 metadata 字段说明;entryorder.match 由「已实现待接入」改为已接入(matchAfterEntryCompleted 绑定成功且本次新建绑定时回传,matchType 固定 auto_match);调试页按真实 { event, data, metadata } 三层预填。", + "methods": [ + "entryorder.confirm", + "entryorder.match", + "deliveryorder.confirm", + "stockout.confirm", + "deliveryorder.cancel" + ], + "notes": [ + "order.cancel 为出站回调旧方法名,本次删除(不做兼容、不双发);入站方法 order.cancel 仍属于 methods/openapi.json,不受影响", + "timestamp 统一:app/service/openapi/callback.js#sendWithRetry 改为 String(Math.floor(Date.now()/1000)),与 /openapi 入站 ±600 秒时效校验及回调调试页一致", + "entryorder.match 接入点:app/service/systems/receiving_entry_match.js#matchAfterEntryCompleted 绑定成功且 bindResult.created===true 时调用 _sendCallback(...,'auto_match');重复触发不重复回传,回传失败仅 warn 不影响绑定", + "metadata:entryorder.confirm {source:'inbound_direct_log',entryOrderId};entryorder.match {source:'receiving_entry_match',entryOrderId,receivingId};deliveryorder.confirm {warehouseId,createChannel:'API',syncTarget};stockout.confirm {warehouseId,storeId,sourceType:'API'};deliveryorder.cancel 真实调用点未传(报文内 {})", + "回调调试页 GET /docs/api/openapi/callback-test 按注册表自动预填真实三层报文体 { event, data, metadata }(此前把 sampleData 直接当整个 body)", + "同步 docs/openapi-callback-events.md 与 AI_METHOD_ROUTING.md 5.6 节;新建 docs/api-doc-update-workflow.md", + "文档版本 1.0.0 → 1.1.0" + ] + }, + { + "version": "2026.09.12-openapi-callback-init", + "date": "2026-09-12", + "type": "added", + "module": "callback", + "summary": "新增 methods/openapi_callback.json:OpenAPI 出站回调(WMS → 外部)接口文档,登记 5 个出站回调事件 entryorder.confirm / entryorder.match / deliveryorder.confirm / stockout.confirm / order.cancel(event 与 query method 同值);协议口径与 docs/openapi-callback-events.md 及 app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS 一致;入站接口仍以 methods/openapi.json 为准。", + "methods": [ + "entryorder.confirm", + "entryorder.match", + "deliveryorder.confirm", + "stockout.confirm", + "order.cancel" + ], + "notes": [ + "触发实现与发送途径:entryorder.confirm(inbound_direct_log.js#qimenEntrySync API 分支,sendWithRetry 直调,throwOnError=true);entryorder.match(receiving_entry_match.js#_sendCallback API 分支,sendWithRetry 直调,当前无调用方);deliveryorder.confirm(order_async.js#finalizeLocalChannelOrdersInternal,sendByAppKey);stockout.confirm(order_async.js#notifyStockoutExternalInternal API 分支,sendByAppKey);order.cancel(openapiMethods/order.js#cancel,sendByAppKey)", + "协议:POST {ApiApp.callback_url}?method=&v=1.0×tamp=&app_key=&sign=;body 统一 { event, data, metadata };sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body)));非 2xx/网络错误重试至多 3 次(间隔 2s→5s→15s,单次超时 30s)", + "已知问题如实记录:timestamp 口径不一致(sendWithRetry 毫秒 vs 调试页秒),统一前不作为规范值;entryorder.match 触发函数 _sendCallback 无调用方(已实现待接入)", + "本文件为出站方向文档(版本 0.0.0 -> 1.0.0),不修改 methods/openapi.json(入站)", + "写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + } +] diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json new file mode 100644 index 0000000..3831ca9 --- /dev/null +++ b/methods/changes/qimen.json @@ -0,0 +1,228 @@ +[ + { + "version": "2026.10.08-qimen-stockout-item-id-normalize", + "date": "2026-10-08", + "type": "updated", + "module": "stockout", + "summary": "qimen stockout.create 明细 item_id 落库口径修正:统一写入实际匹配到的 StockStore 数字主键 id,修复调用方把「编码+名称」拼接串放进 itemId(同时 itemCode 可精确匹配)时写入 BIGINT 列触发 MySQL 严格模式 1366(Incorrect integer value for column item_id)导致建单失败的问题;与 entryorder.create 建单口径对齐。", + "methods": [ + "stockout.create" + ], + "notes": [ + "app/service/systems/stockout_order.js#create 校验循环 items.push:itemId 由 line.itemId 改为 wmsStock.id(StockStore 主键,纯数字);itemCode/itemName 仍落报文原值,stockId 仍为 wmsStock.stock_id", + "回传影响:stockout 确认回传(order_async.js buildStockoutConfirmDataInternal)itemId 改为 StockStore 主键 id,符合奇门 itemId=「仓储系统商品ID」语义,与入库单确认回传口径一致", + "生产案例:2026-10-08 10:09 奇门 stockout.create(app_key=23204092)报 Incorrect integer value: LB006小光兔灵感五色眼影盘#01情懒落日 for column item_id,调用方 itemId/itemCode/itemName 三字段均为拼接串,系统按 itemCode 匹配到 StockStore(stock_id=162580)但落库仍用报文原值", + "验证:test/temp_test_stockout_itemid_normalize.js(非数字 itemId + itemCode 降级匹配 → 建单成功且 item_id=StockStore 主键;数字主键回归通过),5/5 PASS" + ] + }, + { + "version": "2026.09.12-qimen-order-cancel-rk-entry-order-support", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "qimen order.cancel 的 RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)取消入库单语义升级:由「直接置 order_status=CANCELLED」升级为委托 ctx.service.systems.storage.entry.cancel 完整作废流程(守卫 sync_status=SUCCESS/COMPLETED + 回退收货单占用 + ENTRY_ORDER_CANCEL 操作日志),取消成功后不回传任何奇门事件(skipExternalSync=true),已作废按幂等成功;同步修正上一轮「RK 组将入库单 order_status 置 CANCELLED」的过时措辞。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/qimenMethods/order.js cancel 的 case RK:空单号返回「入库单号不能为空」;委托 ctx.service.systems.storage.entry.cancel({ entryOrderCode }, { storeId, warehouseId, operatorLabel=qimen:xxx, skipExternalSync=true, idempotent=true, notFoundMessage=未找到对应的入库单 })", + "守卫口径(systems/storage/entry.js _guardCancelEntryOrder):sync_status=SUCCESS 返回「入库单已完成回传,不可取消」,order_status=COMPLETED 返回「已完成入库单不允许作废」;幂等模式下已 CANCELLED 优先按成功处理(幂等判定优先于回传状态判定)", + "作废动作(_doCancelEntryOrder):状态置 CANCELLED + 按台账回退关联收货单占用(重算 storage_status)+ 写 ENTRY_ORDER_CANCEL 操作日志;skipExternalSync=true 跳过 QM 来源的 qimenEntrySync 取消回传,取消成功不回传奇门事件", + "共享实现 QM 回传失败分支文案为「取消失败: xxx」(RK 渠道 skipExternalSync=true 不触发回传,该分支不会出现)", + "methods/qimen.json:order.cancel 的 description(RK 组改为委托共享作废流程)、request.orderType(RK 组改为已实现并注明完整作废语义)、errors(新增入库单号不能为空/已完成入库单不允许作废/入库单已完成回传,不可取消)、notes(RK 组 note 重写为完整实现语义)", + "order.pending 的 request.orderType 枚举描述仅列枚举名,无「将入库单 order_status 置 CANCELLED」过时措辞,保持不动", + "文档版本 0.3.9 -> 0.3.10(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-qimen-order-cancel-ck-stockout-support", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "qimen order.cancel 的 CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)由「取消出库单未开发完成」改为已支持:按出库单号查 wms_order_stockout,仅 CREATED/PENDING 允许取消(COMPLETED/TRANSFERRED 拒绝),委托共享实现 systems/stockout_order.js#cancel(单事务 + 行锁,释放 QM_STOCKOUT 锁定并写 STOCKOUT_CANCEL 操作日志,已 CANCELLED 幂等返回成功);同步修正上一轮遗留的「CK 组(未开发)」过时措辞与 errors/notes。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/qimenMethods/order.js cancel 的 case CK:空单号返回「出库单号不能为空」,否则委托 ctx.service.systems.stockoutOrder.cancel({ stockoutOrderCode }, { storeId, warehouseId, operatorLabel=qimen:xxx })", + "出库单状态枚举 CREATING/CREATED/PENDING/COMPLETED/CANCELLED/TRANSFERRED;仅 CREATED/PENDING 可取消(canCancel),已 CANCELLED 幂等返回成功,COMPLETED/TRANSFERRED 返回「出库单当前状态(xxx)不允许取消」", + "取消成功不向奇门回传任何事件;释放 QM_STOCKOUT 库存锁定(写 UNLOCK 流水),「释放数量超过已锁定库存」视为幂等跳过;写 wms_operation_log(business_type=stockout,operation_code=STOCKOUT_CANCEL)", + "methods/qimen.json:order.cancel 的 description、request.orderCode(补充 CK 组为出库单号)、request.orderType(CK 组改为已实现并标注状态约束)、response.message(补充取消出库单成功)、errors(移除「取消出库单未开发完成」,新增出库单号不能为空/未找到对应的出库单/出库单当前状态(xxx)不允许取消/取消失败:xxx)、notes(新增 CK 组实现语义)", + "order.pending 的 CK 组枚举名称(PTCK=普通出库单、DBCK=调拨出库、B2BCK=B2B出库、QTCK=其他出库、CGTH=采购退货出库单)保持不变,order.cancel 沿用同一口径", + "文档版本 0.3.8 -> 0.3.9(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-qimen-order-cancel-pending-orderType-enum", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "qimen order.cancel / order.pending 补齐 request.orderType 作业类型枚举说明(原为占位文本):全量枚举 ORDER(JYCK/HHCK/BFCK,取消发货单已实现)/ RK(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK,入库单 order_status 置 CANCELLED)/ CK(PTCK/DBCK/B2BCK/QTCK/CGTH,未开发)/ JG(CNJG,未开发)/ BACKORDER(XTRK/THRK/HHRK,未开发);同步补全 order.cancel 取消逻辑说明(直接取消/拦截/幂等)、response 与 errors。", + "methods": [ + "order.cancel", + "order.pending" + ], + "notes": [ + "app/service/qimenMethods/order.js:构造函数 this.orderType 定义 orderType→{method,name} 全量映射,cancel/pending 均按 orderType.method switch 分发", + "order.cancel 的 request.orderType 参数 description 由占位文本补齐为全量枚举(含各组的取消支持情况);request.orderCode description 补充 ORDER 组为发货单号、RK 组为入库单号", + "order.cancel 补齐 response(flag/code/message,code=1 成功/0 失败)与 errors(订单号不能为空/未找到对应的订单/未找到对应的入库单/取消失败,已通知拦截执行/订单已同步,不可取消,已转为拦截处理/取消出库单未开发完成/取消加工单未开发完成/取消退货单未开发完成)", + "order.cancel notes 补充取消逻辑:未拣货且未打印直接取消(status=cancel, outbound_status=fin, step=4);已拣货/已打印拦截(intercept_status=intercepting);已同步转拦截(intercept_status=requested);已取消幂等返回取消订单成功", + "order.pending 的 request.orderType 参数 description 同步补齐为同一套枚举(pending 当前所有类型分支均未开发完成,返回锁定XX未开发完成),response/errors 同步补齐", + "文档版本 0.3.7 -> 0.3.8(docMeta.version),updatedAt 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.08.30-entryorder-create-item-match-fix", + "date": "2026-08-30", + "summary": "entryorder.create 商品匹配修复文档同步:明细行商品匹配三级策略(itemId 主键直查 > itemCode 精确匹配 > itemCode 归一化条码匹配)、编码支持中文后缀、item_id 统一写入 StockStore 数字主键、失败信息回显真实 SKU/商品/编码并附订单行号", + "methods": [ + "entryorder.create" + ], + "notes": [ + "商品匹配三级策略:itemId 主键直查(纯数字且不超 BIGINT 范围、货主一致)> itemCode 精确匹配 > itemCode 归一化条码匹配(取编码开头连续数字)", + "带中文后缀编码(如 6934864201409-新品、6902226688892-赠品装)精确匹配不到时按归一化条码对齐;归一化命中多商品时报错不静默", + "item_id 统一写入实际匹配到的 StockStore 数字主键 id,修复 Data truncated for column 'item_id'", + "失败信息回显真实 SKU/商品/编码并附订单行号(未同步推送到仓库 / wms无对应关系 / 归一化匹配到多个商品)", + "测试:新增 qimen.entryorder.match.regression.test.js、entry_order.match.unit.test.js,修正 qimen.entryorder.create.status.test.js,10 passing / 0 failing(2026-08-30)", + "代码依据:app/service/systems/entry_order.js addOrder,qimenMethods/entryorder.js 与 openapiMethods/entryorder.js 共用同一逻辑" + ], + "type": "updated", + "module": "entryorder" + }, + { + "version": "2026.08.25-stockout-create-express-fallback-zt", + "date": "2026-08-25", + "summary": "stockout.create 快递兜底口径调整:兜底仅使用出库单兜底快递编码(policy_config.stockout_default_express_code,默认 ZT 自提),不再回退订单默认快递(default_express_code/全局 STO);快递解析改为独立实现,不再复用订单侧 resolveExpressSnapshot 兜底链。", + "methods": [ + "stockout.create" + ], + "notes": [ + "qimenMethods/stockout.js create 快递解析重写:开启 enable_external_express_code 且传 logisticsCode 时按 wms_express_setting 映射 → 系统快递列表匹配;未传/未开启/匹配不到时取 stockout_default_express_code(为空则 'ZT'),从系统快递列表解析名称,仍不存在则编码=名称=ZT", + "app/model/store_warehouse.js POLICY_CONFIG_FIELDS:新增 stockout_default_express_code(名称:出库单默认快递,type list,default 'ZT'),getPolicyConfigFieldListWithOptions 同步注入快递选项,与 default_express_code 表现一致", + "注意:ZT 需在系统快递列表中维护(自提),否则出库单 express_code/express_name 直接落库 ZT" + ], + "type": "updated", + "module": "stockout" + }, + { + "version": "2026.08.25-stockout-create-receiver-info", + "date": "2026-08-25", + "summary": "stockout.create 解析 receiverInfo 落库(13 个标准字段)并接入出库单兜底快递编码:快递解析在未传 logisticsCode 或匹配不到时,优先使用货主合约配置 stockout_default_express_code(出库单兜底快递),为空再回退 default_express_code/全局 STO。", + "methods": [ + "stockout.create" + ], + "notes": [ + "qimenMethods/stockout.js create 新增 receiverInfo 解析:company/name/zipCode/tel/mobile/email/countryCode/province/city/area/town/detailAddress/id 共 13 字段落库 receiver_* 列(空值转 NULL)", + "快递解析改为传入覆盖默认快递后的 expressPolicyConfig(default_express_code = stockout_default_express_code || default_express_code)复用 resolveExpressSnapshot 匹配链路", + "app/model/store_warehouse.js POLICY_CONFIG_FIELDS 新增 stockout_default_express_code(type list,默认空,描述:出库单未传快递编码或匹配不到时使用的兜底快递编码)", + "receiverInfo 中的 idType/idNumber 扩展字段暂不落库(数据库未建列)" + ], + "type": "updated", + "module": "stockout" + }, + { + "version": "2026.08.25-stockout-create-express-resolve", + "date": "2026-08-25", + "summary": "stockout.create 新增 logisticsCode 快递编码解析(简化口径):货主开启 enable_external_express_code 时按 wms_express_setting → 系统快递列表匹配,匹配不到(含未开启)一律兜底默认快递,不走订单快递策略漏斗(matchPolicy)。解析结果落库 express_code/express_name。", + "methods": [ + "stockout.create" + ], + "notes": [ + "qimenMethods/stockout.js create 在事务外解析 deliveryOrder.logisticsCode:调 deliveryOrder.getStoreWarehousePolicyConfig 读策略开关 + deliveryOrder.resolveExpressSnapshot(编码映射+兜底,不含策略漏斗),取 sysLogisticsCode/sysLogisticsName 落库 express_code/express_name", + "解析失败仅告警不阻断建单(express_code/express_name 保持 NULL),confirm 前仍可走 storage.stockout.updateExpress 手工补填", + "注意:出库单 express_code 存系统快递编码,stockout.confirm 出站回传 logisticsCode 时直接使用该值" + ], + "type": "updated", + "module": "stockout" + }, + { + "version": "2026.07.01-qimen-01", + "date": "2026-07-01", + "summary": "补充 entryorder.create 的 request body 子结构和 response 结构", + "methods": [ + "entryorder.create" + ], + "notes": [ + "补充 request.entryOrder 子结构(entryOrderCode/warehouseCode/ownerCode/orderType)", + "补充 request.orderLines.orderLine 子结构(itemCode/itemId/itemName/planQty/orderLineNo/inventoryType)", + "补充 response 结构(entryOrderId/entryOrderCode/createTime/status)", + "参考代码:systems/entry_order.js addOrder 和 qimenMethods/entryorder.js create 返回值" + ], + "type": "updated", + "module": "entryorder" + }, + { + "version": "2026.04.07-qimen-01", + "date": "2026-04-07", + "summary": "初始化 qimen 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", + "methods": [ + "*" + ], + "notes": [ + "methods/qimen.json 仍为单一事实来源(SSOT)。", + "本文件仅记录变更历史与补充说明。" + ] + }, + { + "version": "2026.06.30-stockout-create-01", + "date": "2026-06-30", + "summary": "stockout.create 重构:从不可用的 deliveryOrder 旧链路迁移到 wms_order_stockout 专用表;返回字段 deliveryOrderId→stockoutOrderId/stockoutOrderCode", + "methods": [ + "stockout.create" + ], + "notes": [ + "params 补全 deliveryOrder 和 orderLines 内部全部子字段", + "response 从空补充为 stockoutOrderId/stockoutOrderCode", + "文档与代码实现(qimenMethods/stockout.js create 方法)对齐" + ] + }, + { + "version": "2026.06.30-stockout-query-01", + "date": "2026-06-30", + "summary": "stockout.query 从占位(接口未完善)实现为完整查询:按 deliveryOrderCode 查 wms_order_stockout 主表+明细表", + "methods": [ + "stockout.query" + ], + "notes": [ + "params 补全 request.deliveryOrder.deliveryOrderCode(body)", + "response 从空补充为 deliveryOrder 主单 + orderLines.orderLine 明细 + totalLines", + "文档与代码实现(qimenMethods/stockout.js query 方法)对齐" + ], + "type": "updated" + }, + { + "version": "2026.08.07-stockout-confirm-01", + "date": "2026-08-07", + "summary": "stockout.confirm 从入站改为出站:确认后由 WMS 出站调用 taobao.qimen.stockout.confirm 通知 ERP", + "methods": [ + "stockout.confirm" + ], + "notes": [ + "移除 qimenMethods/stockout.js 中错误的入站 confirm 方法(stockout.confirm 是出站而非入站)", + "storage.stockout.confirm 确认后通过 qimenClient.send() 出站调用 taobao.qimen.stockout.confirm", + "出站 payload 包含 deliveryOrder/packages/orderLines,logisticsCode=OTHER", + "qimen.json 移除 stockout.confirm 入站条目" + ], + "type": "changed", + "module": "stockout" + }, + { + "version": "2026.08.17-qimen-order-cancel-01", + "date": "2026-08-17", + "summary": "order.cancel 触发拦截的两个分支统一转发快递群发起拦截(创建售后工单+通知快递群),仅限有运单的订单处理", + "methods": [ + "order.cancel" + ], + "notes": [ + "已拣货/已打印分支:保留原有 createInterceptWorkOrdersAndNotify 调用,新增前置判断——先查订单运单,无运单不再创建工单/通知快递群", + "已同步订单分支(sync_status=fin):新增与分支一相同的拦截处理——有运单时创建售后工单并通知对应快递群,与正常货主发起拦截一致", + "无运单订单仍按原逻辑更新拦截状态与异常群通知,不创建工单、不通知快递群", + "createInterceptWorkOrdersAndNotify 内部本就按运单驱动(无运单直接返回),外层判断进一步避免无谓调用" + ], + "type": "changed", + "module": "order" + } +] diff --git a/methods/changes/syncOrderIds-async-20260704.json b/methods/changes/syncOrderIds-async-20260704.json new file mode 100644 index 0000000..52891e0 --- /dev/null +++ b/methods/changes/syncOrderIds-async-20260704.json @@ -0,0 +1,29 @@ +{ + "date": "2026-07-04", + "version": "1.0.0", + "changes": [ + { + "method": "order.pendingOrder.syncOrderIds", + "type": "modified", + "description": "同步待处理订单由同步模式改为异步模式。提交后立即返回 request_id,后台通过 setImmediate 异步执行同步流程。调用方需通过 syncOrderIdsProgress 接口轮询进度。单订单失败静默写入 error 状态,不影响整批结果。已同步(fin)或处理中(padding)的订单自动跳过防重复。", + "breaking": true, + "migration": { + "before": "POST 同步调用,等待全部订单处理完成后返回完整结果", + "after": "POST 同步调用,立即返回 request_id;GET/POST syncOrderIdsProgress 轮询最终结果", + "response_change": "原返回 data 对象(含 warehouse_id / dispatch_results 等),现返回 request_id + warehouse_id + message" + } + }, + { + "method": "order.pendingOrder.syncOrderIdsProgress", + "type": "added", + "description": "新增接口,用于查询 syncOrderIds 异步任务的进度与最终结果。入参 request_id,返回 status / progress / total_count / processed_count / result 等。", + "breaking": false + } + ], + "affected_files": [ + "app/service/systemMethods/order/pendingOrder.js", + "app/service/systems/order_storage_allocation.js", + "methods/system.json", + "test/app/service/systemMethods/order/pendingOrder.syncOrderIds.test.js" + ] +} diff --git a/methods/changes/syncOrderIds-async-review-feedback-20260704.md b/methods/changes/syncOrderIds-async-review-feedback-20260704.md new file mode 100644 index 0000000..0945d9b --- /dev/null +++ b/methods/changes/syncOrderIds-async-review-feedback-20260704.md @@ -0,0 +1,154 @@ +# syncOrderIds 异步化改造 — 风险评估修正反馈 + +**日期**:2026-07-04 +**评审来源**:`wms-review-agent` 风险评估报告(11 项风险点) +**修正执行**:`wms-db-agent` +**改造分支**:`ming`(尚未提交) + +--- + +## 评审结论总览 + +| 风险点总数 | 确认为真风险 | 已修复 | 可接受妥协 | 不成立 | +|-----------|-------------|--------|-----------|--------| +| 11 + 1(深度排查) | 5 | 4 | 5 | 2 | + +--- + +## 一、已修复项 + +### 🔴 P0 — #2 操作日志双重写入 + +**问题**:`order_storage_allocation.syncOrderIds` 中存在旧的 `ORDER_SYNC` 操作日志写入代码(约 50 行),`pendingOrder.syncOrderIds` 层又有新增的日志写入,导致每条订单产生 **2 条** `ORDER_SYNC` 日志。 + +**修法**:删除 `order_storage_allocation.js` 中旧的操作日志写入块,替换为一行注释 `// 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,避免重复`。 + +**影响文件**:`app/service/systems/order_storage_allocation.js`(-50 行) + +--- + +### 🟡 P1 — #3 Promise.all 无容错 + +**问题**:`Promise.all` 并行派发各渠道分组(QM / MANUAL / API),若任一渠道 handler 抛异常(如 `syncQmOrders` reject),按 `Promise.all` 语义会中断所有渠道。 + +**实际风险评估**:经核实,下游 handler(`syncQmOrders` / `syncManualOrders` / `syncApiOrders`)内部均使用 `Promise.all` + `processXxxOrderInternal` 模式,**所有方法返回 `{ status: 'failed' }` 而非 throw**,因此实际抛异常的概率极低。但作为防御性编程,仍加 `try/catch` 兜底。 + +**修法**:每个 `map(async groupedOrder => { ... })` 回调包裹 `try/catch`: +- `catch` 中记录 `ctx.logger.error`(含 createChannel / warehouseId / orderCount) +- 返回标准化 `{ status: 'failed', message, ... }` 结构 +- 仍调用 `reportProgress(groupOrderCount)` 确保进度不丢失 + +**影响文件**:`app/service/systems/order_storage_allocation.js`(+20 行) + +--- + +### 🔴 P0(深度排查)— catch 分支缺操作日志 + +**来源**:`wms-review-agent` 二次深度排查,对比 `allocateStorage` 发现遗漏。 + +**问题**:`syncOrderIds` 的 `setImmediate` catch 块中只写了缓存进度 + error log,**没有写操作日志**。而 `allocateStorage` 的 catch 块写了 `ORDER_STORAGE_ALLOCATE_FAILED`。如果服务崩溃、DB 断连等,`syncOrderIds` 的操作日志表里完全没有记录。 + +**修法**:在 `setImmediate` catch 块中新增操作日志写入,参考 `allocateStorage` 使用 `this.ctx.model.OperationLog.bulkCreate` 直写(崩溃场景下 service 层可能也不可用): +- 操作码:`ORDER_SYNC_FAILED` +- 内容:`订单同步失败:{errorMsg}` +- 双层 `try/catch`:外层写入缓存进度,内层写入操作日志 + +**影响文件**:`app/service/systemMethods/order/pendingOrder.js`(+35 行) + +**测试覆盖**:新增 `should write ORDER_SYNC_FAILED operation log when entire sync task throws` + +--- + +### 📋 P2 — #10 测试覆盖不足 + +**问题**:原报告指出"syncOrderIds 本身的异步流程没有对应测试用例"。 + +**实际核实**:`pendingOrder.syncOrderIds.test.js` 已存在(11 个测试),但确实缺少 2 个场景。 + +**修法**:新增 2 个测试用例: +- **渠道级异常隔离**:模拟 MANUAL 成功 + QM 失败,验证 `dispatch_results` 正确反映两渠道状态 +- **多状态混合**:模拟 success / skipped / fast-failed 四类结果共存,验证 `result.data` 各字段正确 + +**最终覆盖**:14 个测试用例,覆盖以下场景: + +| 场景 | 测试用例 | +|------|---------| +| 基础异步:立即返回 request_id | ✅ | +| 进度查询:success 后查到完整 result | ✅ | +| 进度查询:not_found | ✅ | +| 进度查询:request_id 为空 | ✅ | +| 中间态:submitted → running | ✅ | +| 单订单失败:整批仍 success | ✅ | +| 整体失败:报告 failed 状态 | ✅ | +| **catch 分支操作日志:ORDER_SYNC_FAILED** | ✅ 新增 | +| 进度递增:running → success | ✅ | +| 入参兼容:orderIds/ids/order_id | ✅ | +| 缓存故障:写入失败不崩溃 | ✅ | +| 进度回调异常:不崩溃 | ✅ | +| 渠道隔离:单渠道失败不阻塞 | ✅ | +| 多状态混合:四种结果共存 | ✅ | + +--- + +## 二、不成立的风险点 + +### #6 — `warehouse_id` 优先级变更无校验 + +**核实**:`warehouse_id` 由 `pendingOrder.syncOrderIds` 在 `setImmediate` 之前通过 `this.getWarehouseId()` 快照提取,与原来 `ctx.user.store_id` **完全同源**。不存在调用方误传的通道。 + +**结论**:❌ 不成立,无风险。 + +--- + +### #7 — `sync_status` 过滤遗漏 `error` 状态 + +**核实**:model 定义 `sync_status` 枚举为 `['padding', 'fin', 'error']`。当前过滤条件为 `NOT IN ('fin', 'padding')`。 + +- `fin`(已完成):排除 ✅ — 无需重复同步 +- `padding`(处理中):排除 ✅ — 防止并发重复提交 +- `error`(失败):**不应排除** ✅ — 用户应能修复问题后重试 + +如果排除 `error`,会导致同步失败的订单**永远无法重试**,这反而是 bug。 + +**结论**:❌ 不成立,当前过滤条件是正确的业务设计。 + +--- + +## 三、可接受的妥协项 + +| # | 风险点 | 妥协理由 | +|---|--------|---------| +| 1 | Breaking API 变更 | 异步化必须付出的代价,changes JSON 已标记 `breaking: true`,调用方需适配 | +| 4 | `setImmediate` 中 ctx 生命周期 | 与 `allocateStorage` / `batchIntercept` / `batchLock` / `batchUnlock` / `batchUnintercept` **共 5 处现有模式**完全一致,框架已验证可行 | +| 5 | 异步任务无超时 | 与 `allocateStorage` 一致,缓存 TTL 2 小时自然过期兜底 | +| 8 | `syncOrderIdsProgress` 无权限隔离 | 与 `allocateStorageProgress` 一致,`request_id` 含随机 token 不可猜测 | +| 9 | 操作日志 `ctx.user` 可能为空 | 随 #2 修复一并解决(旧日志代码已删除,新日志用快照 operator) | +| 11 | `progress_callback` 函数注入 | 链路中无 JSON 序列化操作,与 `allocateStorage` 一致 | + +--- + +## 四、当前状态 + +``` +变更文件:6 个 +├── app/service/systemMethods/order/pendingOrder.js (修改) +├── app/service/systems/order_storage_allocation.js (修改) +├── methods/system.json (修改) +├── methods/changes/syncOrderIds-async-20260704.json (新增) +├── methods/changes/syncOrderIds-async-review-feedback-20260704.md (新增) +├── test/.../pendingOrder.syncOrderIds.test.js (新增) +└── test/.../pendingOrder.allocateStorage.test.js (修改) + +ESLint: 0 errors ✅ +单测: 27 passing ✅ (13 allocateStorage + 14 syncOrderIds) +``` + +--- + +## 五、遗留建议(非阻塞) + +| 优先级 | 建议 | 说明 | +|--------|------|------| +| P3 | 增加任务心跳 + 超时自动标记 failed | 可后续迭代,与 `allocateStorage` 统一处理 | +| P3 | `syncOrderIdsProgress` 增加 `warehouse_id` 校验 | 防止跨仓库查询他人任务(当前依赖随机 token 安全性) | +| P3 | 确认前端调用方已适配新返回格式 | 需产品/前端确认 `request_id` 轮询流程 | diff --git a/methods/changes/system.json b/methods/changes/system.json new file mode 100644 index 0000000..557e3a9 --- /dev/null +++ b/methods/changes/system.json @@ -0,0 +1,13518 @@ +[ + { + "version": "0.3.360", + "date": "2026-11-15", + "type": "updated", + "summary": "B2B 列表支持作业明细筛选;其余订单列表统一排除 B2B 订单", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.pendingOrder2b.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryOrder2b.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list", + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "B2B 列表筛选:order.pendingOrder2b.list / order.deliveryOrder2b.list 的 where 新增 8 个作业明细字段(total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds / is_picked_up / picked_up_at / created_at / prep_at),内部按 warehouse_id + order_id 查 wms_order_b2b 取命中 order_id 后以 id IN (...) 回填,未命中返回空列表;该筛选仅这两个接口开放,不影响普通订单列表。", + "B2B 排除: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 / order.wave.waveStrategyFallbackOrderList 在模块默认条件之上统一追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不再出现在这些列表中;NULL 存量行按非 B2B 处理。", + "实现位置:app/service/systemMethods/order/base.js#listByModule(fixedWhere 含 is_b2b 时视为 B2B 域列表,不再追加排除条件)、#extractB2bDetailVirtualFilter / #findOrderIdsByB2bDetailFilters、#buildExcludeB2bCondition;app/service/systemMethods/order/wave.js#waveStrategyFallbackOrderList 单独追加排除条件。", + "不在本次口径内:order.export 走独立表位查询(getOrderModelByTableType),不经过 listByModule,导出仍按原口径取数。" + ] + }, + { + "version": "0.3.359", + "date": "2026-11-15", + "type": "updated", + "summary": "B2B 作业明细表重构:列表带出作业字段、取消改物理删除、移除冗余字段并新增 prep_at", + "methods": [ + "order.pendingOrder2b.list", + "order.deliveryOrder2b.list", + "order.convertToB2b", + "order.cancelB2b" + ], + "notes": [ + "数据库迁移 20261115180000-refactor-wms-order-b2b.js(已在开发库与生产库执行):wms_order_b2b 新增 prep_at(备货完成时间);移除 is_print / updated_at / deleted_at / delivery_order_code / store_id;唯一键 uk_order_id 改为 uk_warehouse_order(warehouse_id, order_id);迁移前先清空历史软删除行与同仓同单重复行。", + "关联口径:wms_order_b2b 与订单分表的关联读统一使用 warehouse_id + order_id(分表 id 按仓库发号,跨仓可能重叠,不能只按 order_id)。", + "列表变更:order.pendingOrder2b.list / order.deliveryOrder2b.list 的列表行新增 total_box_count、pickup_plate_number、prep_remark、prep_duration_seconds、prep_at、is_picked_up、picked_up_at、created_at 8 个作业明细字段,无明细行时输出空值占位(0 / N / null)。", + "转换变更:order.convertToB2b 写作业明细改为 (warehouse_id, order_id) 唯一键,不再写 store_id / delivery_order_code / updated_at,已存在同仓同单行时重置作业字段(含 prep_at)。", + "取消变更:order.cancelB2b 由软删除改为物理删除;随 is_print 字段移除,取消不再校验「B2B面单已打印」,skipped_reasons 枚举同步删除该原因。" + ] + }, + { + "version": "0.3.358", + "date": "2026-11-15", + "type": "updated", + "summary": "order.cancelB2b 取消「已打印不允许取消」限制,并补齐接口文档", + "methods": [ + "order.cancelB2b" + ], + "notes": [ + "变更:删除 print_status=fin 的拦截,已打印(含打印中)的订单同样允许取消 B2B,不再返回「订单已打印,不允许取消B2B」。", + "保留不变的拦截:step=0(待审核)、非 B2B(is_b2b != Y)、已锁定、已拦截、B2B 面单已打印(wms_order_b2b.is_print = Y,当前无逻辑置 Y,实际不触发)。", + "实现位置:app/service/systems/order_b2b.js#resolveCancelSkipReason;查询列 print_status 保留(不参与校验)。", + "补文档:该接口此前已实现但未登记接口文档,本次一并补齐(入参别名、响应字段、跳过原因枚举、错误码、权限口径与波次/落库行为)。", + "文档中如实标注现状差异:cancelB2b 的 step 仅排除 0(step 4/5/9 可取消)、未校验 pick_status / recheck_status,与 convertToB2b 的白名单口径不一致。" + ] + }, + { + "version": "0.3.357", + "date": "2026-11-15", + "type": "updated", + "summary": "order.convertToB2b 取消「已打印不允许转 B2B」限制", + "methods": [ + "order.convertToB2b" + ], + "notes": [ + "变更:删除 print_status=fin 的拦截,已打印(含打印中)的订单同样允许转 B2B,不再返回「订单已打印,不允许转B2B」。", + "保留不变的拦截:已取消(status=cancel)、step 白名单(仅 1/2/3)、已拣货(pick_status=fin)、已复核(recheck_status=fin)、已锁定、已拦截、已是 B2B、所在波次存在进行中的拣货任务。", + "实现位置:app/service/systems/order_b2b.js#resolveConvertSkipReason;查询列 print_status 保留(不参与校验,仅便于排查)。", + "关联提醒:order.cancelB2b 目前仍拦截「订单已打印,不允许取消B2B」,因此已打印订单转 B2B 后无法通过取消接口回退,如需对称放行需另行调整。" + ] + }, + { + "version": "0.3.356", + "date": "2026-11-15", + "type": "updated", + "summary": "order.convertToB2b 转换时自动把订单从波次摘除(含库内抓取订单),拣货任务进行中则跳过", + "methods": [ + "order.convertToB2b", + "order.wave.batchRemoveOrders" + ], + "notes": [ + "新行为:已在波次中的订单转 B2B 成功后,在同一事务内从波次摘除——订单 wave_id/wave_no/wave_scope/wave_strategy_version/wave_scan_result 清零,重排 wms_order_wave_index,回写 wms_wave_batch.total_orders / processed_orders,剩余 0 单的波次置 wave_status=-1。团购/散单抓取与库内抓取进入波次的订单一视同仁。", + "保护逻辑:波次存在进行中的拣货任务(wms_wave_pick_task.status in (0,1))时该订单不转换,skipped_reasons 返回「订单所在波次存在进行中的拣货任务,不允许转B2B」,波次 ID 通过 active_pick_task_wave_ids 返回;与 order.wave.batchRemoveOrders 的既有保护口径一致。", + "响应新增字段:removed_from_wave_order_ids / affected_wave_ids / emptied_wave_ids / active_pick_task_wave_ids;入参结构不变。", + "实现:app/service/systemMethods/order/wave.js 新增 detachOrdersFromWavesInTransaction(事务内复用),order.wave.batchRemoveOrders 同步改为复用该方法,行为与改造前等价;app/service/systems/order_b2b.js#convertOrdersToB2b 增加 wave_id/wave_no 查询列、活动拣货任务预检、摘除调用与 ORDER_WAVE_REMOVE 操作日志(提交后写入,失败不影响主流程)。", + "本次未触发波次策略快速重扫(enqueueWaveStrategyQuickScanPostOrderChange):被摘除的订单已是 B2B,策略扫描侧本身已排除 B2B,无需为其重扫。" + ] + }, + { + "version": "0.3.355", + "date": "2026-11-15", + "type": "updated", + "summary": "order.convertToB2b 增加已拣货/已复核订单拦截", + "methods": [ + "order.convertToB2b" + ], + "notes": [ + "新增准入校验:pick_status=fin(拣货已完成)返回「订单已拣货,不允许转B2B」,recheck_status=fin(复核已完成)返回「订单已复核,不允许转B2B」,避免把已进入作业流程的订单改成 B2B。", + "实现位置:app/service/systems/order_b2b.js#resolveConvertSkipReason;查询列新增 pick_status、recheck_status。校验顺序:已取消 → 步骤白名单 → 已拣货 → 已复核 → 已打印 → 已锁定 → 已拦截 → 已是 B2B。", + "拣货中(pick_status=padding)与拣货异常(pick_status=error)按本次需求不拦截,仍允许转换;如需一并拦截需另行调整。" + ] + }, + { + "version": "0.3.354", + "date": "2026-11-15", + "type": "updated", + "summary": "波次抓取类接口统一声明排除 B2B 订单,并修复自动加团链路未排除 B2B 的问题", + "methods": [ + "order.wave.fetch", + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.groupOrderFetchList", + "order.wave.singleOrderFetchList", + "order.wave.fetchableOrderCount", + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin", + "order.wave.waveStrategyQuickScan" + ], + "notes": [ + "代码侧核查结论:波次抓取的候选取数已全部带 (is_b2b IS NULL OR is_b2b = 'N') 条件,覆盖 buildFetchWhere(团购/散单抓取、异步 fetch 任务、自动加团新建波次)、groupOrderFetchList / singleOrderFetchList / fetchableOrderCount、策略候选 SQL(getWaveStrategyFetchCandidateOrders、selectWaveStrategyFetchOrdersBySkuLimit、第一池同结构合并)、快速扫描 where(buildWaveStrategyQuickScanOrderWhere)与 singleFetchByIds。", + "本次修复的缺口:app/service/systems/delivery_order.js 自动加团链路——appendOrderToWave 查询订单未带 is_b2b 且无 B2B 校验,导致 B2B 订单可能被自动加入已存在的\"自动加团中\"波次;countCandidateGroupOrders 候选计数未排除 B2B,导致开新团的候选数量被 B2B 订单污染。", + "修复方式:appendOrderToWave 查询属性增加 is_b2b 并在锁校验后静默跳过 is_b2b=Y 的订单;countCandidateGroupOrders 的 where 增加 is_b2b 排除条件。NULL 存量行按非 B2B 处理,不影响历史数据。", + "本轮仅补充上述 9 个抓取类接口的 B2B 排除口径说明,接口入参/响应结构未变更。" + ] + }, + { + "version": "0.3.353", + "date": "2026-11-15", + "type": "updated", + "summary": "order.convertToB2b 收紧准入:禁止转换已取消与已配送/已出库订单", + "methods": [ + "order.convertToB2b" + ], + "notes": [ + "问题:原准入只判断 step != 0,导致 step=4(配送中/已提交出库)、step=5(已完成)、step=9(已关闭,含取消单)只要未打印/未锁定/未拦截就会被转成 B2B,可能把已取消或已配送的订单误转。", + "现改为步骤白名单:仅 step in [1,2,3] 可转;0 返回「订单待审核」、4 返回「订单已提交出库」、5 返回「订单已完成」、9 返回「订单已关闭」、其它步骤返回「订单当前步骤(N)不允许转B2B」。", + "新增 status='cancel' 校验并置于校验链首位(已取消订单即使 step 仍在 [1,2,3] 也拒绝),返回「订单已取消,不允许转B2B」。", + "实现位置:app/service/systems/order_b2b.js#resolveConvertSkipReason;查询列新增 status 字段。行为上仍然只跳过不报错,跳过原因通过 skipped_reasons 返回。" + ] + }, + { + "version": "0.3.352", + "date": "2026-11-15", + "type": "added", + "summary": "补充 order.convertToB2b 接口文档(订单转 B2B)", + "methods": [ + "order.convertToB2b" + ], + "notes": [ + "该接口此前已实现(app/service/systemMethods/order/index.js#convertToB2b → app/service/systems/order_b2b.js#convertOrdersToB2b),但未登记接口文档,本次补齐。", + "入参支持 ids / order_ids / orderIds / id / order_id / orderId 六种键名,单值或数组均可,单次最多 200 个;仓库取自登录上下文,仅能转换本仓 current 分表内的订单。", + "准入条件:step != 0、print_status != 'fin'、lock_status = 'none'、intercept_status = 'none'、is_b2b != 'Y';不满足只跳过并在 skipped_reasons 返回原因,不在 current 分表中的订单进 not_found_order_ids。", + "文档中已明确 step 口径现状:只排除 step=0,step=4/5/9(含已取消单)同样可转换,且未校验 outbound_status='padding' 与 wave_id。", + "参数错误(订单ID为空 / 超过 200 个)返回 HTTP 200 但响应体 flag=failure、code=400;缺少仓库上下文抛错,HTTP 500。" + ] + }, + { + "version": "0.3.351", + "date": "2026-11-15", + "type": "added", + "summary": "新增 B2B 订单列表接口 order.pendingOrder2b.list 与 order.deliveryOrder2b.list", + "methods": [ + "order.pendingOrder2b.list", + "order.deliveryOrder2b.list" + ], + "notes": [ + "两个接口复用 order.pendingOrder.list / order.deliveryOrder.list 的全部查询条件与响应结构,仅额外强制 is_b2b='Y'。", + "固定条件通过 listByModule 的 fixedWhere 选项以 AND 方式附加,请求 where 传入同名 is_b2b 条件无法覆盖(传入 N 只会得到空列表)。", + "wms_order_delivery 各分表新增 is_b2b 列表索引:idx_{wh}_{type}_list_is_b2b_updated_at (warehouse_id, [dispatch_lane,] is_b2b, updated_at, id) 与 ..._list_is_b2b_delivery_time (warehouse_id, [dispatch_lane,] is_b2b, delivery_time, id),dispatch 分表版本携带 dispatch_lane;history / outsourced 分表不声明该索引。索引由订单工厂表结构漂移同步在部署后首次访问分表时自动补建(ALTER TABLE ADD INDEX),无需手工迁移。" + ] + }, + { + "version": "0.3.349", + "date": "2026-11-13", + "type": "fixed", + "summary": "修正 SN 订单限制:允许按订单 ID 抓取散单,仅保持「不出现在散单/团购策略候选」", + "methods": [ + "order.wave.singleFetchByIds" + ], + "notes": [ + "问题:singleFetchByIds 把 has_sn_item='Y' 的订单一并排除(excluded_sn_order_ids),导致 SN 订单无法按订单抓取散单。", + "现改为:SN 订单允许按订单 ID 显式抓取,不再受 SN 标记限制;excluded_sn_order_ids 字段保留在响应中但恒为空数组(向后兼容)。", + "抓取后的波次 item_part_type='manual_ids',拣货侧固定走先拣后分 pick_mode=3,与 SN 策略要求的先拣后分一致,SN 采集仍在复核环节按 sn_map 提交。", + "保持不变:散单策略与团购策略候选仍排除 SN 订单(order.wave.singleOrderFetchList、fetchableOrderCount、runFetchTask 结构抓取、自动加团),SN 订单只由 SN 策略(strategy_type=3)自动抓取。B2B / 已拦截 / 已锁定订单仍不允许抓取。" + ] + }, + { + "version": "0.3.348", + "date": "2026-11-13", + "type": "added", + "summary": "订单列表支持按 SN 码反查订单(where.sn_code),SN 码表补 store_id 与查询索引", + "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": [ + "以上列表接口的 where 均支持 sn_code / snCode / sn_codes / snCodes:先按仓库 + SN 码查询 wms_order_item_sn 取 order_id,再以 id IN (...) 回填订单列表条件,订单表结构不变;未命中返回空列表。", + "取值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组、{ value } 结构;按完整 SN 码精确匹配(扫码所得即完整码),去重后最多一次 IN 查询;未传该条件不查 SN 表。", + "数据库迁移 20261113233000-add-store-id-and-indexes-to-order-item-sn.js 已在本地与生产执行:wms_order_item_sn 新增 store_id(BIGINT UNSIGNED,可空),新增 idx_wms_order_item_sn_sn_code 与 idx_wms_order_item_sn_store_id,并按 order_id + warehouse_id 关联各仓库订单分表回填历史 store_id(生产回填 160 行,无遗漏)。", + "复核提交落库 wms_order_item_sn 时写入 store_id(取自订单 store_id,BOUND→VERIFIED 升级同样补写),便于后续按货主隔离查询/统计。" + ] + }, + { + "version": "0.3.347", + "date": "2026-11-13", + "type": "added", + "summary": "商品新增 SN 码规则(wms_stock_warehouse.sn_code_rules),复核扫描视图 scanOrder 下发 sn_code_rules 供前端扫码校验", + "methods": [ + "stock.warehouse.saveWarehouseStock", + "stock.warehouse.createWarehouseStock", + "stock.warehouse.getInfo", + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增字段 wms_stock_warehouse.sn_code_rules(JSON 数组,可空),迁移 20261113203000-add-sn-code-rules-to-stock-warehouse.js 已在本地与生产执行。", + "一条规则三步:match_type=prefix(匹配前缀)/suffix(匹配后缀);match_value=要匹配的前缀或后缀字符串;keep_mode=full(整个扫码内容作为 SN 码)/strip(去掉匹配到的前缀或后缀后再作为 SN 码)。多条规则按数组顺序匹配,命中第一条生效,未命中则扫码内容原样作为 SN 码。", + "保存入参 sn_code_rules / snCodeRules 支持数组或 JSON 字符串,元素字段兼容 match_type/matchType、match_value/matchValue、keep_mode/keepMode;整体覆盖保存,传 [] 清空,不传则不更新(创建时不传存空数组)。", + "格式校验(保存即报错,错误信息带第几条):必须是数组或合法 JSON 数组;元素必须是对象;match_type 仅 prefix/suffix;match_value 去空白后 1~64 字符;keep_mode 仅 full/strip;同位置同串同处理方式视为重复;最多 20 条。", + "order.recheckOrder.scanOrder(含团购波次视图 stocks[])商品行新增 sn_code_rules 数组,与 need_sn 并列输出;无规则返回 [],存量脏数据(非法 JSON)按 [] 兜底不影响扫描视图。stock.warehouse.getInfo 回显同步输出该字段。" + ] + }, + { + "version": "0.3.346", + "date": "2026-11-13", + "type": "updated", + "summary": "订单导出表头枚举补全(拦截状态、复核时间),并明确 export_columns 白名单会过滤新增列", + "methods": [ + "order.export" + ], + "notes": [ + "export_columns 枚举由 55 个修正为 57 个,补入此前遗漏的「拦截状态」(字段 intercept_status)与「复核时间」(字段 recheck_time)。", + "新增说明:一旦传入 export_columns,服务端只按白名单过滤输出列,新增列(拦截状态、SN码数量、SN码汇总、SN码)必须由前端导出列选项同步加上,否则导出表头里看不到;不传该参数才输出当前模式全部列(waybill 48 列 / item 51 列)。", + "本次仅文档更正,服务端列定义与导出逻辑未改动。" + ] + }, + { + "version": "0.3.345", + "date": "2026-11-13", + "type": "updated", + "summary": "奇门 deliveryorder.confirm 报文结构修正:orderLines 的 snList 输出 子节点,多包裹 packages 正确闭合", + "methods": [ + "order.pendingOrder.syncOrderIds" + ], + "notes": [ + "orderLines[].snList 现按奇门规范输出 SN码…;此前 XML 生成器对标量数组统一用 包裹,再被 orderLines 内的 item→orderLine 替换,实际发出的是 …。", + "packages 修正:一单多运单号(多个包裹)时,第二个及之后包裹此前会被序列化成 并导致 / 错位;现输出标准 ……。", + "snList 仍只挂在 orderLines[].orderLine 上(数据源 wms_order_item_sn,状态 VERIFIED/REISSUED),packages.package[].items 不含 snList,MRO/手工通知与出库单回传(stockout.confirm)不受影响。", + "SN 长度分流:奇门 orderLine.sn 限长 50,超长 SN(二维码/链接型)改由 orderLine.qrCode 承载,多个用分号拼接,并与明细自带 qr_code 合并去重;API/JSON 渠道不做此限制,仍全部放在 snList。" + ] + }, + { + "version": "0.3.344", + "date": "2026-11-13", + "type": "updated", + "summary": "复核扫描视图 scanOrder 商品行新增 need_sn 标识(是否需要采集 SN 码)", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "scanOrder 返回的 stock[] 每项新增 need_sn:Y=该商品启用序列号管理(wms_stock_warehouse.is_sn_mgmt='Y'),复核提交时必须通过 sn_map 上传该商品全部 SN 码;N=无需采集。", + "团购模式(list_type=group)波次视图中的 stocks[] 同步输出 need_sn,PDA 可直接按商品行切换 SN 扫描。", + "need_sn 与 need_recheck(是否需要复核)互相独立,可同时为 Y。", + "SN 标记按当前仓库过滤一次批量查询(id IN stockIds AND warehouse_id=? AND is_sn_mgmt='Y'),不改变原有 stock 字段与其他返回结构。" + ] + }, + { + "version": "0.3.343", + "date": "2026-11-13", + "type": "updated", + "summary": "order.wave.waveStrategyList 的 strategy_type 过滤支持数组多选(如 [1, 3])", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "顶层 strategy_type 与 where.strategy_type 均支持数组写法,如 { strategy_type: [1, 3] };顶层优先于 where。", + "单值写法(1 / \"2\")保持原有行为,仍以等值条件过滤;数组长度 > 1 时按 IN 过滤,数组内字符串会被转换为数字并去重。", + "数组内出现 1/2/3 之外的值(如 [1, 4])直接报错:strategy_type 仅支持 1(散单)、2(团购) 或 3(SN),数组写法如 [1, 3]。", + "空数组表示不过滤,等价于不传 strategy_type。", + "info.order_count 的全部策略命中订单总数统计同口径支持数组:策略侧按 IN (1, 3) 过滤,SN 分支与非 SN 分支各自叠加该条件。" + ] + }, + { + "version": "0.3.342", + "date": "2026-11-13", + "type": "updated", + "summary": "SN 码长度上限扩至 512 字符(支持链接/二维码),订单导出新增 SN 码汇总与商品行 SN 码列表", + "methods": [ + "order.export", + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "wms_order_item_sn / wms_order_item_sn_log 的 sn_code 由 VARCHAR(128) 扩至 VARCHAR(512)(迁移 20261113160000-enlarge-order-item-sn-code.js);唯一索引 (warehouse_id, sn_code) 仍在上限内。", + "confirmRecheck:单个 SN 码超过 512 字符直接失败,提示「SN码长度不能超过512个字符」,支持链接/二维码内容作为 SN 码。", + "order.export 新增列:waybill 模式「SN码汇总」(sn_codes_summary,订单级全部已登记 SN,仅主单号行输出)、item 模式「SN码」(sn_codes,该商品行登记的 SN 列表);表头枚举 53 → 55。", + "导出只输出 sn_status ∈ BOUND/VERIFIED/REISSUED 的 SN(排除 RETURNED/INVALID),按 wms_order_item_sn.id 升序拼接,逗号分隔。" + ] + }, + { + "version": "0.3.341", + "date": "2026-11-13", + "type": "updated", + "summary": "订单导出新增「SN码数量」列:明细中启用序列号管理商品的 plan_qty 合计", + "methods": [ + "order.export" + ], + "notes": [ + "导出列新增「SN码数量」(字段 sn_quantity),位置紧随「订单商品总数」,waybill / item 两种模式均可选,导出表头枚举由 52 个变为 53 个。", + "口径:订单明细中 stock_warehouse.is_sn_mgmt='Y' 的商品 plan_qty 合计(非 SN 商品不计入),用于账单核对 SN 码数量。", + "waybill 模式:仅主单号行输出订单级合计,子单号行置 0(与「订单商品总类数 / 订单商品总数」一致,避免重复统计)。", + "item 模式:按商品明细行输出该行的 SN 数量,非 SN 商品行为 0,行求和即为订单合计。", + "SN 商品识别按当前导出仓库(warehouse_id)过滤,并对软删商品(paranoid:false)保持兼容。" + ] + }, + { + "version": "0.3.340", + "date": "2026-11-13", + "type": "updated", + "summary": "复核 SN 提交改为唯一格式:sn_map(stock_id -> SN 码列表),移除 sn_list / sn_codes", + "methods": [ + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "入参只保留 sn_map:{ \"stock_id\": [\"sn_code\", ...] },key 为仓库商品ID(stock_id),value 为该商品的 SN 码列表(兼容逗号/换行分隔字符串)。", + "不再支持 sn_list(按 order_item_id 提交)与 sn_codes(扁平列表);旧格式会被忽略,SN 订单会返回「必须上传全部SN码」。", + "数量校验口径:同一 stock_id 的 SN 数量必须等于该商品在订单内所有明细 plan_qty 合计;同商品多明细时按明细ID升序、按各明细 plan_qty 顺序拆分写入 wms_order_item_sn.order_item_id。", + "非 SN 商品或不属于当前订单的 stock_id 提交 SN 时返回「提交的SN码对应商品不在订单中或未启用序列号管理:stock_id=x」。" + ] + }, + { + "version": "0.3.339", + "date": "2026-11-13", + "type": "updated", + "summary": "SN 策略忽略同结构最大/最小数量限制:抓取候选与列表匹配订单数统一按 SN 口径统计", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin", + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyList" + ], + "notes": [ + "SN 策略(strategy_type=3)抓取候选 SQL 不再 JOIN 同结构统计子查询,也不再按 min_same_structure/max_same_structure 过滤;SN 订单只能由 SN 策略抓取,按结构区间过滤会导致单件/少量 SN 订单永远抓不到。", + "列表 matched_order_count_filtered 与 info.order_count 增加 SN 分支:SN 策略只统计命中该策略且满足订单池条件的 SN 订单,不做同结构区间过滤。", + "散单/团购策略的统计口径不变,仍按同结构区间过滤,并统一排除 SN 订单(与抓取口径一致)。", + "本地库实测(仓库 100000、SN 策略 id=9、1~12 同结构区间):忽略区间后候选 2757 单,按区间仅 546 单。" + ] + }, + { + "version": "0.3.338", + "date": "2026-11-13", + "type": "updated", + "summary": "SN 订单回传改为按「SN 齐套 + 已复核」判定,复核通过后自动异步回传一次", + "methods": [ + "order.pendingOrder.syncOrderIds", + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "order.pendingOrder.syncOrderIds:不再对 SN 订单无差别拦截,改为按明细判定——每个序列号明细的已发出 SN(VERIFIED/REISSUED)数量必须等于 plan_qty,且订单 recheck_status='fin',才允许回传。", + "不满足时仍返回 failed_reason=sn_batch_forbidden,文案改为「SN订单SN明细未齐套或未复核完成,不允许回传」,订单保持 sync_status=error + step=3 待处理异常。", + "order.recheckOrder.confirmRecheck:复核成功后对 SN 订单按签约策略 auto_sync_back 异步触发一次 syncOrderIds(失败仅记录日志,不影响复核结果;已同步订单跳过)。", + "回传报文 orderLines[].snList 改为按 wms_order_item_sn 中 VERIFIED/REISSUED 的 SN 填充,避免 SN 订单回传平台时缺少 SN。" + ] + }, + { + "version": "0.3.337", + "date": "2026-11-13", + "type": "updated", + "summary": "复核接口强制 SN 订单提交 SN 码:按明细数量校验、校验是否已发过、同事务落库", + "methods": [ + "order.recheckOrder.confirmRecheck", + "order.recheckOrder.batchQuickRecheck", + "order.recheckOrder.batchQuickRecheckByWave", + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "confirmRecheck:has_sn_item='Y' 的订单必须提交 sn_list / sn_map / sn_codes;非 SN 订单提交 SN 码直接失败。", + "数量校验:每个序列号管理明细的 SN 数量必须等于该明细 plan_qty;非序列号管理明细不允许提交 SN 码;同批次 SN 不可重复。", + "是否已发过:SN 已被其它订单/明细占用,或流水已存在 VERIFIED/REISSUED 记录(随其它订单发出)时判定失败。", + "落库:校验通过写入 wms_order_item_sn(sn_status=VERIFIED、verify_status=PASS)与 wms_order_item_sn_log(action_type=VERIFY),并与订单复核状态更新同一事务,任一失败整体回滚。", + "幂等:同订单同明细重复提交已 VERIFIED 的 SN 不重复写入;状态为 BOUND 的 SN 升级为 VERIFIED 并补一条流水。", + "batchQuickRecheck / batchQuickRecheckByWave:SN 订单直接返回失败(reason=复核失败: SN订单需在单订单复核中提交SN码,不支持快捷复核),避免绕过 SN 校验。", + "confirmRecheck 传 wave_id 触发团购波次批量复核时,若波次内存在 SN 订单直接失败:SN订单不支持团购波次复核。", + "响应新增 has_sn_item、sn_count、sn_item_count。", + "queryRecheckOrderSingleList:散单复核列表新增 has_sn_item(Y/N),供前端判断是否需要采集 SN 码。" + ] + }, + { + "version": "0.3.336", + "date": "2026-11-13", + "type": "updated", + "summary": "波次策略新增 SN 类型(strategy_type=3):创建固定先拣后分,快扫只匹配 SN 订单", + "methods": [ + "order.wave.waveStrategyList", + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate" + ], + "notes": [ + "strategy_type 取值扩展为 1-散单 / 2-团购 / 3-SN(序列号管理)。", + "创建/更新为 3 时 batch_mode 固定为 2(先拣后分),拣货模式固定 pick_mode=3;显式传入的 pick_mode / batch_mode 不生效。", + "快速扫描互斥:SN 策略只命中 has_sn_item='Y' 的订单;散单/团购策略不命中 SN 订单。", + "策略抓取候选:strategy_type=3 只取 SN 订单,1/2 排除 SN 订单;同结构计数口径同步按类型区分。", + "SN 策略建波沿用散单建波形态(wave_type=2)+ pick_mode=3,按 SKU 上限与批次最大订单数切片。" + ] + }, + { + "version": "0.3.335", + "date": "2026-11-13", + "type": "updated", + "summary": "散单波次抓取同样排除 SN(序列号管理)订单:singleOrderFetchList / singleFetch / singleFetchByIds", + "methods": [ + "order.wave.singleOrderFetchList", + "order.wave.singleFetch", + "order.wave.singleFetchByIds" + ], + "notes": [ + "承接 0.3.334:此前仅团购抓取排除 SN,本次起散单抓取同样排除,SN 订单不再进入任何波次(wave_type=1 团购 / 2 散单)。", + "singleOrderFetchList / singleFetch:候选条件与结构抓取统一排除 has_sn_item='Y'。", + "singleFetchByIds:按订单ID抓取时直接跳过 SN 订单,响应新增 excluded_sn_order_ids。", + "散单策略(strategy_type=1)候选与团购策略一致,建波前过滤 SN 订单。" + ] + }, + { + "version": "0.3.334", + "date": "2026-11-13", + "type": "updated", + "summary": "团购波次抓取排除 SN(序列号管理)订单:groupOrderFetchList / groupFetch / fetchableOrderCount", + "methods": [ + "order.wave.groupOrderFetchList", + "order.wave.groupFetch", + "order.wave.fetchableOrderCount" + ], + "notes": [ + "数据口径:订单表 has_sn_item='Y' 视为 SN 订单;NULL 视为非 SN(兼容未回填存量行)。", + "groupOrderFetchList / fetchableOrderCount:候选条件新增 SN 排除,列表与可抓取数不再包含 SN 订单。", + "groupFetch(含 fetch/自动加团):团购结构抓取增加 SN 排除;散单抓取(singleFetch / singleFetchByIds)不受影响,SN 订单仍可走散单。", + "团购策略(strategy_type=2)候选与同结构合并同样排除 SN 订单。" + ] + }, + { + "version": "0.3.333", + "date": "2026-11-13", + "type": "updated", + "summary": "补记 order.list(订单工作台入口)支持 is_sn_order 是否序列号订单筛选", + "methods": [ + "order.list" + ], + "notes": [ + "0.3.332 已为 order.reviewOrder.list / order.pendingOrder.list / order.outboundOrder.list / order.expectionOrder.list / order.entrustOrder.list / order.deliveryOrder.list / order.deliveryExpectionOrder.list / order.archiveOrder.list 补充 is_sn_order 文档;本次补齐 order.list(同为 listByModule 共用筛选链路)。", + "筛选与返回字段口径同 0.3.332:has_sn_item(订单表 Y/N 冗余列)+ is_sn_order(响应归一化 Y/N)。" + ] + }, + { + "version": "0.3.332", + "date": "2026-11-13", + "type": "updated", + "summary": "订单工作台各列表新增 is_sn_order(是否序列号订单)筛选,并返回 has_sn_item / is_sn_order 标记", + "methods": [ + "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": [ + "筛选口径:订单表新增 has_sn_item(Y/N),建单时按明细 stock_warehouse.is_sn_mgmt 聚合写入,任一明细 is_sn_mgmt=Y 即为 Y。", + "取值兼容:Y/N、true/false、1/0、是/否,支持简写与 { value } 标准结构;非法值返回 400(is_sn_order 参数不合法)。", + "存量订单通过迁移 20261113151000-backfill-order-has-sn-item 按明细回填;回填前 has_sn_item 为 NULL 的行在 is_sn_order=N 条件下按非序列号订单返回。", + "列表响应新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段,便于前端展示序列号订单标记。" + ] + }, + { + "version": "0.3.331", + "date": "2026-11-12", + "type": "updated", + "summary": "轨迹与揽收查询出站运单号补寄件电话后四位:waybill.warehouse.getTrace / waybill.warehouse.updateReceive 调用外部接口时发送「运单号|后四位」", + "methods": [ + "waybill.warehouse.getTrace", + "waybill.warehouse.updateReceive" + ], + "notes": [ + "背景:中通轨迹 / 揽收查询接口要求携带收寄件人手机号后四位(如 776447927635244|8000)才返回数据。", + "取值口径:按 warehouse_id 命中 wms_order_express 后,用 logistics_interface_id 关联 wms_express_interface.sender_tel,剔除非数字后取后四位。", + "降级:未命中运单、logistics_interface_id 为空、接口未配置电话或电话不足四位时,按纯运单号发送,行为与改动前一致。", + "回写隔离:仅出站报文带后缀,库内匹配与回写(含 wms_order_express.is_galaxy_receive)仍使用纯运单号;外部响应带 |后缀 也能正确匹配。" + ] + }, + { + "version": "0.3.330", + "date": "2026-11-11", + "type": "updated", + "summary": "轨迹查询改为全部回源:waybill.warehouse.getTrace 实时调用外部接口返回,不再落库;下线 waybill.warehouse.updateTrace 与 updateTraceTaskProgress,删除 wms_order_express_trace 表", + "methods": [ + "waybill.warehouse.getTrace", + "waybill.warehouse.updateTrace", + "waybill.warehouse.updateTraceTaskProgress" + ], + "notes": [ + "业务调整:轨迹数据不再本地存储,查询一律实时回源,避免同步延迟与数据双写。", + "getTrace:去掉 refresh 入参(已无本地缓存),去掉 refreshed / refresh_error 返回;返回改为 { waybill_code, total, list, received_updated },list 字段不再含数据库 id / express_id / order_id。", + "揽收联动保留:轨迹非空则把该运单 is_galaxy_receive 置为 Y(只升不降),计数见 received_updated。", + "下线接口:waybill.warehouse.updateTrace、waybill.warehouse.updateTraceTaskProgress 已从代码与文档移除(原异步任务 no longer 适用)。", + "数据库:迁移 20261111205500-drop-wms-order-express-trace.js 删除 wms_order_express_trace,已在开发库与生产库执行;模型 app/model/order_express_trace.js 一并删除。", + "失败口径变化:未配置承接应用或外部接口异常时 getTrace 直接返回失败(此前降级返回本地空数据),避免「空结果」误导。" + ] + }, + { + "version": "0.3.329", + "date": "2026-11-11", + "type": "updated", + "summary": "轨迹同步联动揽收状态:拿到轨迹的运单自动把 is_galaxy_receive 置为 Y(只升不降),任务结果新增 received_updated 计数;getTrace 回源命中时同样生效", + "methods": [ + "waybill.warehouse.updateTrace", + "waybill.warehouse.updateTraceTaskProgress", + "waybill.warehouse.getTrace" + ], + "notes": [ + "背景:有物流轨迹即说明快递已揽收,原先轨迹与揽收状态两条链路互不相通,需要额外调用 updateReceive 才能更新揽收状态。", + "现口径:saveTraces 落库后,对本次拿到轨迹且能匹配到运单的 waybill_code 执行 UPDATE wms_order_express SET is_galaxy_receive='Y'(条件:同仓库、is_galaxy_receive <> 'Y' 或 IS NULL),只升不降。", + "计数:任务 result.received_updated 为实际影响的运单数;提示语追加「揽收状态更新 N 单」。", + "失败隔离:揽收状态更新异常只写 warn 日志,不影响轨迹落库与任务状态。", + "getTrace 自动回源命中轨迹时,同样会触发该联动。" + ] + }, + { + "version": "0.3.328", + "date": "2026-11-11", + "type": "updated", + "summary": "waybill.warehouse.getTrace 支持本地无轨迹时自动回源(并可 refresh=true 强制刷新),新增 refresh 入参与 refreshed / refresh_error 返回字段,解决「外部有轨迹但本地未同步」时查不到的问题", + "methods": [ + "waybill.warehouse.getTrace" + ], + "notes": [ + "背景:getTrace 仅读本地 wms_order_express_trace;若该运单尚未执行过 updateTrace,本地无数据会返回 total=0,而外部实际已有轨迹。", + "现口径:本地无轨迹时自动调用 waybill.getTrace 回源一次并落库,然后再查本地返回;传 refresh=true 时无论本地有无都强制回源。", + "降级:未配置承接应用(callback_functions 未勾选 waybill.getTrace)或外部接口异常时,不阻断查询,返回本地数据并带回 refresh_error。", + "返回新增 refreshed(是否回源)与 refresh_error(回源失败原因)。" + ] + }, + { + "version": "0.3.327", + "date": "2026-11-11", + "type": "updated", + "summary": "适配轨迹接口返回调整:trace 为空数组(暂无轨迹)不再计为失败,新增 result.empty;weight 支持字符串小数并改为 DECIMAL(10,3) 落库", + "methods": [ + "waybill.warehouse.updateTrace", + "waybill.warehouse.updateTraceTaskProgress", + "waybill.warehouse.getTrace" + ], + "notes": [ + "背景:外部轨迹接口对暂无轨迹的运单返回 trace: [](如刚下单未揽收),原实现按「轨迹内容为空」计入 failed,导致整单任务被误判失败。", + "现口径:trace 为空数组 → 运单号写入 result.empty,不落库、不计 failed;任务状态仍为 success,提示语为「更新完成:新增 X 条轨迹,更新 Y 条,无轨迹 Z 单,失败 N 单」。", + "weight:外部返回可能是字符串小数(如 \"0.99\"),新增 parseTraceWeight 统一转数字并保留 3 位小数;非法值按 0 处理。", + "数据库:wms_order_express_trace.weight 由 INT(11) 改为 DECIMAL(10,3)(迁移 20261111203500,已执行开发库与生产库);MySQL 不支持 INT→DECIMAL 的 INPLACE 变更,该表为新建、数据量小,重建代价可接受。", + "getTrace 返回值不变,weight 现为小数(如 0.99)。" + ] + }, + { + "version": "0.3.326", + "date": "2026-11-11", + "type": "added", + "summary": "新增运单轨迹查询:waybill.warehouse.getTrace 按运单号一次返回全部物流轨迹(不分页,按操作时间倒序),只读查询 wms_order_express_trace 并按仓库隔离", + "methods": [ + "waybill.warehouse.getTrace" + ], + "notes": [ + "定位:与 waybill.warehouse.updateTrace(拉取并落库)互补,本方法只读本地已落库轨迹,不触发外部接口调用。", + "入参:waybillCode(必填,兼容 waybill_code 下划线别名),单个运单精确匹配。", + "返回:{ waybill_code, total, list };list 按 op_time DESC, id DESC 排序,字段含 op_time(YYYY-MM-DD HH:mm:ss)、out_biz_code、memo、op_org_city_name、weight、scan_type、raw_data。", + "仓库隔离:查询固定带 warehouse_id = ctx.user.store_id;无数据返回 success + total=0 + list=[]。", + "代码依据:app/service/systemMethods/waybill/warehouse.js#getTrace,app/service/systems/waybill.js#listTracesByWaybill。" + ] + }, + { + "version": "0.3.325", + "date": "2026-11-11", + "type": "added", + "summary": "新增运单物流轨迹批量更新:waybill.warehouse.updateTrace 与 waybill.warehouse.updateTraceTaskProgress,链路走 OpenAPI 出站回调 waybill.getTrace(入参同 waybill.getreceive,单批 10 单),结果按 (express_id, op_time, scan_type) 幂等落库 wms_order_express_trace", + "methods": [ + "waybill.warehouse.updateTrace", + "waybill.warehouse.updateTraceTaskProgress" + ], + "notes": [ + "回调方法注册:app/lib/callback_functions.js#CALLBACK_FUNCTIONS 新增 waybill.getTrace(名称「运单物流轨迹查询」),管理端 apiApp.listCallbackFunctions 可拉取并勾选。", + "入参:与 waybill.warehouse.updateReceive 完全一致,支持 waybillCodes(优先)或 where(与 waybill.warehouse.list 同口径,不含分页/排序,上限 5000 条)。", + "请求体:{ request: { waybill_codes: [...] } },单批最多 10 个运单号;签名口径与 waybill.getreceive 一致(MD5(appSecret + timestamp + bodyJson))。", + "响应解析:[{ waybillNo, trace: {...} }],兼容 trace 为数组、traces 数组、traceList 与 { code, data: [...] } 包装。", + "落库:wms_order_express_trace,字段映射 opTime→op_time、outBizCode→out_biz_code、memo→memo、opOrgCityName→op_org_city_name、weight→weight、scanType→scan_type,原始报文存 raw_data;唯一键 (express_id, op_time, scan_type) 保证重复回传不产生重复行,命中时更新轨迹文案等字段。", + "任务:task_id 前缀 waybill_trace_,Redis 缓存键前缀 waybill_trace_task_;状态流转 submitted → running → success/failed,result 返回 { total, matched, inserted, updated, not_found, failed }。", + "前置校验:仓库下无应用承接 waybill.getTrace 时直接失败并提示「如需更新运单物流轨迹信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口」,不创建任务。", + "代码依据:app/service/systemMethods/waybill/warehouse.js#updateTrace/#updateTraceTaskProgress,app/service/systems/waybill.js#queryTraces/#saveTraces。" + ] + }, + { + "version": "0.3.324", + "date": "2026-11-11", + "type": "added", + "summary": "新增运单批量更新是否揽收:waybill.warehouse.updateReceive 与 waybill.warehouse.updateReceiveTaskProgress,链路走 OpenAPI 出站回调 waybill.getreceive(单批 10 单,按仓库通知协议签名),结果回写 wms_order_express.is_galaxy_receive(仓库隔离);支持 waybillCodes 或与 waybill.warehouse.list 一致的 where 条件圈选运单号。配套为 is_back / is_intercept / is_galaxy_receive 补默认值 N、回填存量 NULL 并建立单列索引", + "methods": [ + "waybill.warehouse.updateReceive", + "waybill.warehouse.updateReceiveTaskProgress" + ], + "notes": [ + "背景:wms_order_express.is_galaxy_receive 此前只有创建默认值且实际大量为 NULL,没有任何写入来源;列表按 isGalaxyReceive=N 筛选直接返回空。本批次补齐外部回传链路,并修复默认值与历史数据。", + "where 入参(2026-11-11):复用 systems/waybill.js#buildListQueryWhere(由 list 抽取而来),条件口径与 waybill.warehouse.list 完全一致:支持 operator/value 格式、主单号展开(mainWaybillCode)、时间范围(createdAt 数组/区间/旧写法)、关键词模糊等;不含 pagination/sort。", + "优先级与上限:waybillCodes 非空时直接使用并忽略 where;仅传 where 时先解析运单号再走同一任务链路;匹配数 > 5000 条直接失败(不截断),匹配 0 条失败,两者都不传失败。", + "单批上限:waybill.getreceive 每次最多 10 个运单号,超出自动切批(25 单 → 10/10/5),每批完成后按已处理数更新任务进度。", + "签名口径(2026-11-10 调整):外部接收端按 methods/warehouse_notify.json 协议验签,故 sign = MD5(appSecret + timestamp + bodyJson)(openapi/callback.js#signCallback 的 signMode=simple);沿用 /openapi 入站的 MD5(canonicalQuery + appSecret + MD5(body)) 会被对端判为验签失败(实测 code=401)。", + "回写口径:按 waybill_code + warehouse_id 更新 wms_order_express.is_galaxy_receive(外部 1→Y、0→N),跨仓不串写;仅当状态变化时才发 UPDATE,未变化计入 unchanged。", + "业务失败识别:HTTP 200 但响应体 code 非 0/1/200(如验签失败 code=401)时整批计入 result.failed,不再静默当作「无数据」。", + "未配置外部接口:仓库下没有启用应用勾选 callback_functions=waybill.getreceive 时直接返回失败并提示「如需更新运单是否揽收信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口」,不创建任务、不写进度缓存。", + "任务进度:task_id 前缀 waybill_receive_,Redis 缓存键前缀 waybill_receive_task_;状态流转 submitted → running → success/failed,与运单导出(waybill_export_)同构但互相隔离。", + "返回值兼容:外部响应支持裸数组 [{ waybill_code, is_galaxy_receive }]、{ code, data: [...] } 与 { data: { waybills: [...] } };is_galaxy_receive 支持 1/0、'Y'/'N'、布尔,非法取值计入 failed 不写库。", + "配套数据库变更(已执行):迁移 20261111033000 为 is_back / is_intercept / is_galaxy_receive 补 DEFAULT 'N' 并把存量 NULL 回填为 'N'(Y 不动);迁移 20261111041500 为三列分别建立单列索引 idx_is_back / idx_is_intercept / idx_is_galaxy_receive(ALGORITHM=INPLACE, LOCK=NONE)。", + "回调方法注册:app/lib/callback_functions.js#CALLBACK_FUNCTIONS 新增 waybill.getreceive,管理端 apiApp.listCallbackFunctions 可拉取并勾选。", + "代码依据:app/service/systemMethods/waybill/warehouse.js#updateReceive/#updateReceiveTaskProgress,app/service/systems/waybill.js#buildListQueryWhere/#resolveWaybillCodesByWhere/#queryReceiveStatus。" + ] + }, + { + "version": "0.3.322", + "date": "2026-11-02", + "type": "updated", + "summary": "订单批量锁定跳过已取消订单:order.pendingOrder.batchLock 后台任务不再锁定 status=cancel 的订单,避免取消订单被锁定后无法出库;新增 skipped_cancelled_order_count / skipped_cancelled_order_ids 透出跳过明细", + "methods": [ + "order.pendingOrder.batchLock", + "order.pendingOrder.batchLockTaskProgress" + ], + "notes": [ + "背景:奇门取消订单(ORDER_CANCEL,status=cancel)后,网页后台仍可对该订单执行订单锁定(ORDER_LOCK)。取消订单被锁定后会残留锁定标记,导致订单无法按取消逻辑正常出库。", + "现口径:runBatchLockTask 查询订单时带出 status,status=cancel 的订单不进入锁定更新,也不写入 ORDER_LOCK 操作日志;混合批次只锁定未取消订单。", + "并发保护:更新语句 where 增加 status != 'cancel';若更新影响行数少于目标行数,回查确认实际落库订单,只为确认锁定的订单写日志与计数。", + "返回:batchLockTaskProgress 在 running/success/failed 返回 skipped_cancelled_order_count,running/success 返回 skipped_cancelled_order_ids;success.result.message 存在跳过项时提示「已跳过 N 条已取消订单」,全部为取消订单时提示「所选订单均已取消,已跳过 N 条,不能锁定」。", + "兼容性:入参未变;解锁(order.pendingOrder.batchUnlock)仍可对已取消订单执行,便于清理历史锁定状态。", + "测试:test/app/service/systemMethods/order/pendingOrder.batchLock.cancel.test.js 新增 4 条用例(混合批次跳过取消单、全部取消不更新、进度接口返回跳过明细、更新期间并发取消不写日志)。", + "代码依据:app/service/systemMethods/order/pendingOrder.js#runBatchLockTask/#batchLockTaskProgress。" + ] + }, + { + "version": "0.3.321", + "date": "2026-10-28", + "type": "updated", + "summary": "space 视图补齐静态盘点拣货完成标记:stock.check.workData(space 视图)与 stock.check.workDataSpaceDetails 的 goods 子项在 is_static=1 时新增 picking_completed(是否已完成拣货),口径与 goods 视图一致", + "methods": [ + "stock.check.workData", + "stock.check.workDataSpaceDetails" + ], + "notes": [ + "背景:0.3.320 已在 goods 视图行与商品钻取输出 picking_completed,但盘点作业前端默认使用 space 视图(workData 不传 is_goods)与 workDataSpaceDetails(库位分页),这两条链路拿不到拣货完成状态,无法在上报前提示/置灰。", + "现口径:_buildSpaceWorkRows 在 is_static=1 时按商品维度查询仓库内 SUM(locked_quantity)(_fetchStockLockedQuantityMap),goods 子项输出 picking_completed(1=已完成拣货/0=未完成);同一商品在各库位行上的取值一致(商品维度,非库位维度)。盲盘(mode=blind)同样返回该标记,但仍不返回任何数量字段(locked_quantity 仍只在明盘输出)。", + "workDataSpaceDetails 复用同一 space 视图构建函数,因此自动获得该字段,无需额外参数;与 stock.check.report 的静态盘点上报拦截配套(商品未完成拣货返回 400「商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货」)。", + "兼容性:非静态任务(is_static=0)不返回 picking_completed,行为与之前一致;未新增必填入参;原有 system_quantity/storage_quantity/locked_quantity/snapshot_quantity/checked_quantity 字段口径与取值均未变化。", + "测试:test/app/service/systems/stock_check.test.js 的「静态盘点拣货完成标记」用例补充 space 视图(workData 默认视图)与 workDataSpaceDetails(按 location_id 取库位行)的 picking_completed 断言,锁定量存在时为 0、清零后为 1。真实库全量 256 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 2 条 method(stock.check.workData:description/response.rows 的 space 视图 goods 字段说明 + notes;stock.check.workDataSpaceDetails:description + 新增 notes);根版本 0.3.320 → 0.3.321、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows/#workDataSpaceDetails/#_fetchStockLockedQuantityMap。" + ] + }, + { + "version": "0.3.320", + "date": "2026-10-28", + "type": "updated", + "summary": "静态盘点拣货完成口径:stock.check.workData(goods 视图)与 stock.check.workDataDetail(商品钻取)新增 picking_completed(是否已完成拣货,判定=该商品在仓库内 wms_storage SUM(locked_quantity) 是否为 0)与明盘 locked_quantity;stock.check.report 对静态盘点且仍未完成拣货的商品拒绝上报", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail", + "stock.check.report" + ], + "notes": [ + "背景:静态盘点审核通过即冻结账面基准,但盘点期间仍允许把「已分配储位、尚未拣出」的存量锁定货拣走(静态锁定只拦截新的储位分配,不拦截已有锁定)。若实盘发生在该批货拣完之前,实盘数与其后扣减的库位库存会相互矛盾,差异不可信(生产 PD20261027000001 商品 160240:快照后仍有 129 件在拣,最终产生 -115 的假盘亏)。", + "现口径:静态盘点(is_static=1)要求「该商品已完成拣货」——判定依据为 wms_storage 中该商品在仓库内 SUM(locked_quantity) 是否为 0。分配储位只把 available_quantity 搬成 locked_quantity(quantity 不变),拣货完成时 quantity 与 locked_quantity 同时扣减、available_quantity 不变,因此 locked_quantity>0 即表示仍有在途待拣出库。", + "新增字段:stock.check.workData goods 视图行在 is_static=1 时返回 picking_completed(1=已完成/0=未完成)与明盘 locked_quantity(该商品仓库内锁定量合计,盲盘不输出数值只输出完成标记);stock.check.workDataDetail 商品钻取在 is_static=1 时顶层返回同名两字段,口径一致。", + "上报拦截:stock.check.report 在任务 is_static=1 且为商品范围明细(scope_type=goods)时,写记录前校验该商品锁定量,>0 直接 400「商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货」。库位范围任务 is_static 恒为 0,不受影响;未知商品(stock_id 为空)无锁定量,不受影响。", + "兼容性:非静态任务(is_static=0)不返回 picking_completed,行为与之前一致;未新增必填入参,前端可忽略新字段。锁定量判定按仓库维度(不限任务库位范围),与静态锁定商品(stock 维度)口径一致。", + "测试:test/app/service/systems/stock_check.test.js 新增「静态盘点拣货完成标记」用例——人为把 available 搬成 locked 后断言 goods 视图/钻取 picking_completed=0 且 locked_quantity 正确、report 被拒;锁定量清零后 picking_completed=1 且上报成功。原「账面取值按任务静态标记」用例改为仅取无锁定量商品并在 finally 完成盘点释放静态锁定。真实库全量 256 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 3 条 method(stock.check.workData:response.rows 商品视图字段补 picking_completed/locked_quantity + notes;stock.check.workDataDetail:description + notes;stock.check.report:description、errors 400 文案 + notes);根版本 0.3.319 → 0.3.320、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systems/stock_check.js#_fetchStockLockedQuantityMap/#_buildGoodsWorkRows/#_formatGoodsWorkDetail/#report。" + ] + }, + { + "version": "0.3.319", + "date": "2026-10-28", + "type": "updated", + "summary": "盘点账面口径统一改为可用数量(wms_storage SUM(available_quantity)),不再把 locked_quantity(已分配储位、待拣出库的锁定量)计入账面;商品明细快照、动态实时账面、库位盘点、明盘工作台/钻取全部统一", + "methods": [ + "stock.check.addDetail", + "stock.check.result", + "stock.check.report", + "stock.check.finish", + "stock.check.submit", + "stock.check.audit", + "stock.check.workData", + "stock.check.workDataDetail" + ], + "notes": [ + "背景:原账面口径为 SUM(available_quantity + locked_quantity)(=可用+锁定),会把已分配储位但尚未拣出的锁定量算进账面。静态盘点若在仍有在途拣货时开盘,快照会包含这批货,拣货完成后即变成假盘亏(生产 PD20261027000001:商品 160240 账面 248 vs 实盘 133,差异 -115,其中 129 件是快照后 19:02-20:51 才从库位拣出的)。", + "现口径:全部盘点账面统一取 wms_storage SUM(available_quantity)(= quantity - locked_quantity - intercept_locked_quantity)。涉及:addDetail 拆行快照、submit/audit 刷新快照、result 库位行与空库位标记、_recalcCheckSummary/report/finish 差异汇总、workData/workDataDetail 明盘实时账面。", + "语义依据:分配储位只把 available 搬成 locked(quantity 不变、账面不变);拣货完成同时扣 quantity 与 locked、available 不变。因此可用数量口径在盘点窗口内对拣货动作不敏感,锁定货拣完前后都成立。", + "兼容性:locked_quantity 字段继续单独输出(明细 locations.locked_quantity / space 视图 goods.locked_quantity),仅不再计入 system_quantity;前端如需「含锁定总量」请用 system_quantity + locked_quantity 或直接查 storage.quantity。", + "历史任务:已完成任务 system_quantity 为旧口径快照,本次不回刷;如需对齐新口径需驳回重新提交或重新审核触发快照刷新。", + "测试:test/app/service/systems/stock_check.test.js 账面 helper/断言同步改为 SUM(available_quantity),真实库全量 255 用例通过,ESLint 0 错误。", + "代码依据:app/service/systems/stock_check.js#_addGoodsDetailRows/#_refreshGoodsBookSnapshot/#_recalcCheckSummary/#result/#_formatDetailAggregationRow/#_buildGoodsWorkRows/#_buildSpaceWorkRows。" + ] + }, + { + "version": "0.3.318", + "date": "2026-10-28", + "type": "updated", + "summary": "盘点作业数据账面取值按任务 is_static 区分:stock.check.workData(goods/space 视图)与 stock.check.workDataDetail(商品钻取)对静态盘点取明细快照、对普通盘点取当前 wms_storage 账面;新增 storage_quantity / is_static / book_source 字段。", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail" + ], + "notes": [ + "背景:静态盘点(is_static=1)在审核完成时会冻结账面基准(刷新明细 system_quantity 快照),盘点期间不允许出入库/移库;普通盘点则希望看到「当前账面」用于实时对比。原实现两种任务都混用了快照与 storage(goods 视图行级取快照、locations 取 storage),口径不一致。", + "现口径:system_quantity = 本次参与差异计算的账面——is_static=1 → 该库位明细 system_quantity(快照);is_static=0 → wms_storage 该库位 SUM(available_quantity+locked_quantity)。行级(goods 视图行 / workDataDetail summary)为各库位账面之和;diff_quantity 一律 = 实盘 - system_quantity。", + "新增字段:goods 视图行与 location item 增加 is_static / book_source(snapshot|storage)/ storage_quantity(当前 storage 账面),snapshot_quantity 继续输出明细快照;space 视图行内 goods 增加 storage_quantity / snapshot_quantity;workDataDetail 顶层增加 is_static / book_source,rows[] 增加 storage_quantity。", + "兼容性:system_quantity 语义由「快照或 storage(视视图而定)」收紧为「按 is_static 取值」;普通盘点任务的 goods 视图行级账面可能从快照变为当前 storage(有出入库时数值不同),前端如需要基准值请改读 snapshot_quantity。", + "未涉及:stock.check.result / finish / export 的差异汇总仍按「商品行快照、库位行 storage」的既有口径,本次未改;如需与两个作业数据接口完全对齐可另行确认。", + "测试:test/app/service/systems/stock_check.test.js 新增「账面取值按任务静态标记」用例——审核后人为给该库位 +7,静态任务断言 row/locations/summary system_quantity == 快照且 storage_quantity == 快照+7、差异按快照算;非静态任务断言 system_quantity == 快照+7 且差异按当前账面算;goods 视图、space 视图、workDataDetail 三处交叉验证;全量 255 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.workData(rows.description 商品/space 视图账面口径 + notes)、stock.check.workDataDetail(data.description + notes);根版本 0.3.317 → 0.3.318、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systems/stock_check.js#workData/#workDataDetail/#_buildGoodsWorkRows/#_buildSpaceWorkRows/#_formatGoodsWorkDetail。" + ] + }, + { + "version": "0.3.317", + "date": "2026-10-28", + "type": "updated", + "summary": "分配储位命中静态盘点锁定改为「订单级失败」:与库存不足同流程(该订单 storage_status=error + order_flag 静态盘点锁定原因),同批次其它订单继续分配,接口返回 200 并通过 shortage_order_ids/shortage_messages 体现。", + "methods": [ + "order.pendingOrder.allocateStorage", + "order.wave.batchAllocateStorage" + ], + "notes": [ + "修正原因:储位分配支持批量订单(order_ids 数组,波次/待处理订单均走同一入口),0.3.316 的「整单 400」会把同批次未锁定订单一并打断,与既有「库存不足」的静默跳过口径不一致,前端也无法区分哪些订单失败。", + "现行为:命中静态盘点锁定的商品行在明细循环中直接跳过(不查可用储位、不加锁、不写 picking 行);订单级 finalShortageMessage 追加「静态盘点锁定:sku(x) 盘点单 PDxxx」,走与缺货完全相同的收尾——回滚该订单已锁定库存、置 storage_status=error、step=异常、order_flag=原因,并进入 orderResults(status=error)。", + "响应:接口整体 200(除非仓库上下文/订单为空等参数错误);shortage_order_ids 含命中锁定的订单,shortage_messages 含静态盘点锁定文案与盘点单号;orders 中该订单 status=error;allocated_order_ids 仅含成功订单。", + "与移库的区别:移库(storage.inventory.transferLocation/transferByProduct)是单条/单商品同步操作,仍保持 400 直接失败。", + "测试:test/app/service/systems/static_lock_guard.test.js 改为批量口径——两个订单(1 命中锁定、2 正常)断言 code=200、shortage_order_ids=[1]、allocated_order_ids=[2]、锁定订单 order_flag 含静态盘点锁定、仅未锁定商品被加锁(lockCalls 仅 501/3)、picking 仅 1 行;另加「全部订单命中锁定仍返回 200、无加锁、事务正常提交」;5 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 order.pendingOrder 分组更新 order.pendingOrder.allocateStorage(description 改为订单级失败、移除静态盘点 400 错误项、notes 补充)、order.wave 分组更新 order.wave.batchAllocateStorage(notes);根版本 0.3.316 → 0.3.317、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systems/order_storage_allocation.js#allocatePicking、app/service/systems/stock_check.js#getStaticLockConflict。" + ] + }, + { + "version": "0.3.316", + "date": "2026-10-28", + "type": "updated", + "summary": "静态盘点锁定拦截库存操作:分配储位(order.pendingOrder.allocateStorage / order.wave.batchAllocateStorage)与移库(storage.inventory.transferLocation / transferByProduct)在商品处于静态盘点锁定中时直接失败(400),返回冲突商品与来源盘点单号。", + "methods": [ + "order.pendingOrder.allocateStorage", + "order.wave.batchAllocateStorage", + "storage.inventory.transferLocation", + "storage.inventory.transferByProduct" + ], + "notes": [ + "需求:静态盘点(is_static=1,审核完成后锁定)期间,商品库存不允许被分配储位/移库,否则盘点实盘与账面基准错位;要求相关操作直接失败并给出明确原因。", + "判定口径:复用 stock_check.staticLockList(按仓库缓存,TTL 300 秒 + 状态流转立即重建 + 代次防脏读)——is_static=1 且任务状态 approved/checking 的商品为锁定;审核完成即锁、完成/取消即释放。", + "新增业务方法 stock_check.getStaticLockConflict({ warehouseId, stockIds, actionLabel }):返回 { locked, rows, message },message 形如「商品正在静态盘点中,禁止移库:编码(库存ID) 盘点单 PDxxxx」,供库存操作直接返回/抛出(systemMethods 未暴露,内部调用)。", + "分配储位:orderStorageAllocation.allocatePicking 在归集订单明细 stock_id 后、查询可用储位库存之前校验,命中即回滚事务并返回 400 + data.locked_stock_ids/locked_items;allocateStorage 为其兼容入口,待处理订单分配、波次分配等内部调用全部生效。", + "移库:storage.inventory.transferLocation(按库存记录)与 transferByProduct(按库位+商品)在锁定/读取原库存记录后校验 stock_id,命中即回滚并返回 400;未命中时行为与之前完全一致。", + "降级策略:锁定查询异常(缓存/数据库故障)时按「未锁定」放行并写 warn 日志,避免因盘点缓存故障阻断出入库主流程;如需强一致可改为失败即拒绝。", + "测试:新增 test/app/service/systems/static_lock_guard.test.js(4 个用例:transferLocation/transferByProduct 命中锁定 400+回滚+不写库存、未锁定时走原有可用量校验、allocatePicking 命中锁定 400+回滚+未查询储位库存);stock_check.test.js 新增 getStaticLockConflict 文案与空入参用例;相关套件 258 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 更新 storage.inventory.transferLocation、storage.inventory.transferByProduct、order.pendingOrder.allocateStorage(description/errors/notes)与 order.wave.batchAllocateStorage(notes);根版本 0.3.315 → 0.3.316、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systems/stock_check.js#getStaticLockConflict/#isStockStaticLocked、app/service/systems/storage/inventory.js#transferLocation/#transferByProduct/#_getStaticLockConflict、app/service/systems/order_storage_allocation.js#allocatePicking。" + ] + }, + { + "version": "0.3.315", + "date": "2026-10-28", + "type": "updated", + "summary": "静态盘点锁定缓存增加防脏读机制:状态流转(审核/完成/取消/批量删除)先递增锁定代次再重建缓存,回源前后代次不一致则放弃写缓存(响应 cache_skipped=true),杜绝旧快照覆盖新缓存的脏读。", + "methods": [ + "stock.check.staticLockList", + "stock.check.audit", + "stock.check.finish" + ], + "notes": [ + "问题:原实现为「状态更新 → 重建缓存(查询后写回)」,若两个流转并发(如审核 A 与完成 B),B 的重建可能先写入新快照,A 的旧快照随后覆盖 → 最长 300 秒脏读(锁定集合与库内状态不符)。", + "方案(乐观锁/代次):新增代次键 `stock_check:static_lock_gen:{warehouseId}`,Redis 用 INCR 原子递增,Redis 不可用时退化为进程内计数;所有状态流转统一走 refreshStaticLockCache:递增代次 → 回源查询 → 写缓存;_loadStaticLockCache 在查询前后各读一次代次,不一致则判定为并发流转,跳过写缓存并清除缓存(返回 cache_skipped=true)。", + "正确性:① 流转先提交数据库、再递增代次,故代次变化一定意味数据库已变;② 查询前读到的代次若在查询后被改,旧快照不会落盘;③ 未发生流转时的回源之间结果等价,覆盖无影响;④ 读取侧(staticLockList 缓存命中的分支)不受影响,缓存为空时回源保证最终一致。", + "审核路径:audit(approve) → 刷新明细快照 → 更新状态 → refreshStaticLockCache(递增代次 + 重建),接口返回时缓存已包含新任务且无脏读窗口;reject 同理(重建后移除该任务)。", + "性能:每次流转多 2 次 Redis 读 + 1 次 INCR(本地降级为内存操作),回源仍是 2 条 SQL;不影响常规查询(命中缓存时无额外开销)。", + "测试:test/app/service/systems/stock_check.test.js 新增「防脏读:回源期间发生状态流转时不写入旧快照」用例——在 _queryStaticLockRows 内递增代次模拟并发流转,断言 cache_skipped=true 且缓存未被写入,并校验 refreshStaticLockCache 会递增代次;全量 253 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.staticLockList(新增 cache_skipped 响应字段 + 缓存设计/防脏读 notes)、stock.check.audit 与 stock.check.finish(notes 各追加代次说明);根版本 0.3.314 → 0.3.315、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systems/stock_check.js#refreshStaticLockCache/#_loadStaticLockCache/#_readStaticLockGeneration/#_bumpStaticLockGeneration/#staticLockList。" + ] + }, + { + "version": "0.3.314", + "date": "2026-10-28", + "type": "updated", + "summary": "静态盘点锁定缓存策略加固:状态流转(审核/完成/取消/批量删除)由「删除缓存」改为「立即重建缓存」,消除审核后仍读到旧缓存的空窗;空集合也缓存(不穿透)、并发未命中用进程内 singleflight 去重(不击穿);TTL 仍为 300 秒兜底。", + "methods": [ + "stock.check.staticLockList" + ], + "notes": [ + "缓存时长:TTL 300 秒(STATIC_LOCK_CACHE_TTL_SECONDS),仅作兜底;正常路径由状态流转触发重建,不依赖 TTL 到期。", + "是否穿透:不会。回源结果(包括 rows 为空、stock_ids=[] 的空集合)都会写入缓存,因此「当前没有锁定商品」的仓库也不会每次查库;命中空缓存时返回 cached=true、total=0。", + "是否击穿:同一进程内对同一仓库的并发未命中通过 STATIC_LOCK_INFLIGHT(Map)合并为一次回源,其余请求复用同一结果;跨实例的极短并发仍可能各自回源一次(2 条 SQL,成本低),数据结果一致。", + "新审核是否清缓存:audit(approve) 在状态更新后调用 refreshStaticLockCache,回源并写回缓存(不是只删除),因此审核接口返回时缓存已包含新任务;reject 同样重建(移除该任务)。finish/cancel/batchDelete 亦为重建(移除对应任务,其它任务仍保留)。", + "窗口评估:① 审核前查询到「未锁定」属于正确语义(审核未生效);② 审核接口返回后不存在旧缓存窗口;③ 若重建失败(Redis 异常等)会降级删除缓存并在日志留 warn,下一次查询回源,最坏 300 秒自愈;④ 仅 Redis 整体不可用时多实例的进程内缓存可能短暂不一致(各自最长 300 秒),该场景建议库存操作按 fail-safe(保守判定为锁定)处理。", + "测试:test/app/service/systems/stock_check.test.js 调整/新增——审核后缓存已重建且查询命中(cached=true)、完成后重建缓存不包含该任务、取消后重建不包含该任务、空仓库集合缓存(首查回源/二次命中)、5 个并发未命中结果一致且均 cached=false、forceRefresh 强制回源;全量 252 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.staticLockList(cached 字段说明 + 缓存设计 notes + 本次策略答疑);根版本 0.3.313 → 0.3.314、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "代码依据:app/service/systems/stock_check.js#staticLockList/#_readStaticLockCache/#_loadStaticLockCache/#_queryStaticLockRows/#refreshStaticLockCache/#clearStaticLockCache。" + ] + }, + { + "version": "0.3.313", + "date": "2026-10-28", + "type": "updated", + "summary": "库存盘点完成(stock.check.finish)立即释放静态盘点锁定:清除仓库级锁定缓存并返回 released_stock_ids(本任务覆盖的商品ID),同一商品若仍被其它静态任务覆盖则继续锁定。", + "methods": [ + "stock.check.finish" + ], + "notes": [ + "需求:盘点完成时商品必须立刻解除锁定,不能等到缓存 TTL(300 秒)自然过期,否则完成后的出入库仍会被 staticLockList / isStockStaticLocked 判为锁定中。", + "实现:finish 在状态置 completed 后调用 clearStaticLockCache(warehouseId) 删除 `stock_check:static_lock:{warehouseId}`(Redis 与进程内缓存同时清理,失败仅 warn 日志,靠 TTL 兜底);并在状态更新前用 _collectGoodsStockIds 记录本任务商品明细覆盖的 stock_id,随响应 released_stock_ids 返回、随操作日志 extras.releasedStockIds 落库,便于追溯「哪张单释放了哪些商品」。", + "多任务叠加:锁定集合是「全部 approved/checking 静态任务的并集」,完成其中一张单只会移除该单贡献的商品;若商品仍被其它静态任务覆盖,缓存回源后依旧锁定(正确行为)。", + "其它释放路径:cancel(取消)与 batchDelete(作废删除)同样会清除缓存;audit(approve/reject)清除缓存使锁定集合及时更新;report 仅 approved→checking 流转,不改变锁定集合、不失效。", + "测试:test/app/service/systems/stock_check.test.js 新增「完成盘点立即释放锁定」用例——构造独有商品 → 审核通过后 isStockStaticLocked=true → finish 返回 released_stock_ids=[该商品] 且缓存已清 → isStockStaticLocked=false(回源);全量 251 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.finish(响应新增 released_stock_ids、notes 补充释放口径);根版本 0.3.312 → 0.3.313、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "代码依据:app/service/systems/stock_check.js#finish/#_collectGoodsStockIds/#clearStaticLockCache、app/service/systemMethods/stock/check.js#finish、app/extend/application.js#delCacheAsync。" + ] + }, + { + "version": "0.3.312", + "date": "2026-10-28", + "type": "updated", + "summary": "库存盘点新增公共查询 stock.check.staticLockList(静态盘点锁定中的商品清单,按仓库缓存,供库存操作前置判断);stock.check.audit 审核通过时刷新商品明细账面快照(快照基准以「审核完成=开始盘点」时点为准)并返回 snapshot_refreshed,同时失效/进入静态锁定缓存。", + "methods": [ + "stock.check.staticLockList", + "stock.check.audit", + "stock.check.submit" + ], + "notes": [ + "新增方法 stock.check.staticLockList:返回 is_static=1 且状态为 approved/checking 的任务所覆盖的商品 stock_id 集合(rows 附带来源任务ID/单号/库位编码),供出入库、移库、拣货等库存操作判断商品是否被静态盘点锁定;库位盘点任务 is_static 恒为 0,不参与锁定。", + "锁定时机:审核完成(approved)即开始锁定、盘点作业中(checking)持续锁定;提交审核前不锁定;completed/cancelled/rejected 解锁。", + "缓存:键 `stock_check:static_lock:{warehouseId}`,TTL 300 秒,走 app.setCacheAsync/getCacheAsync(Redis 优先、异常降级进程内缓存);audit/finish/cancel/batchDelete 主动失效;响应含 cached(是否命中)与 updated_at(缓存生成时间)。", + "内部接口 isStockStaticLocked({ warehouseId, stockId }):读同一份缓存做单/多商品命中判断,返回 { locked, locked_stock_ids, rows, cached },供库存模块直接调用(systemMethods 层未暴露)。", + "audit 刷新快照:approve 时把 scope_type=goods 明细行 system_quantity 刷新为该库位当前账面 SUM(available_quantity+locked_quantity)(仅统计启用存储,无记录按 0),覆盖「提交审核 → 审核完成」之间发生的出入库,保证账面基准=开始盘点时点;返回 snapshot_refreshed=本次刷新的明细行数(值无变化不计)。submit 的提交时刷新逻辑不变,两者叠加后以审核时点为准。", + "测试:test/app/service/systems/stock_check.test.js 新增「staticLockList 静态盘点锁定商品(公共查询 + 缓存 + 审核刷新快照)」5 个用例——锁定口径(仅 approved/checking、submitted 与非静态任务不计入)、缓存命中与 audit/finish/cancel 主动失效、isStockStaticLocked 单商品判断与参数校验、审核刷新快照(提交后库存 +5,审核后快照等于审核时点账面,并回滚人为变更)、方法层仓库注入与 cached 透出;全量 250 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.staticLockList 一条(共 26 条),并更新 stock.check.audit(响应新增 snapshot_refreshed、notes 补充刷新口径与缓存失效)与 stock.check.submit(notes 补充审核再刷新说明);根版本 0.3.311 → 0.3.312、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systems/stock_check.js#staticLockList/#isStockStaticLocked/#clearStaticLockCache/#_refreshGoodsBookSnapshot/#audit、app/service/systemMethods/stock/check.js#staticLockList、app/extend/application.js#setCacheAsync/#getCacheAsync/#delCacheAsync。" + ] + }, + { + "version": "0.3.311", + "date": "2026-10-28", + "type": "updated", + "summary": "库存盘点 is_static(是否静态盘点)口径收窄:仅商品盘点(type=store/goods)有效,按库位盘点(type=location)一律为 0(create 传入 1/true 也忽略),静态定式(pattern=static)仅商品类任务自动置 1。", + "methods": [ + "stock.check.create", + "stock.check.patternCreate", + "stock.check.list", + "stock.check.detail" + ], + "notes": [ + "口径说明:静态盘点针对「长期停收停发商品」,只对商品盘点(type=store/goods)有意义;库位盘点是按库位清点全部商品,不存在静态商品概念,因此 is_static 恒为 0,避免前端误把全仓库位盘点标成静态。", + "create(本次修正):normalizedIsStatic = (type === 'location') ? 0 : (requested ? 1 : 0)——库位盘点即使传 is_static=1/true 也落库 0 且不报错(保持向后兼容、不新增 400);商品盘点沿用原归一化规则(true/'true'/1/'1' 记为 1,其余 0)。", + "patternCreate(本次修正):is_static = (pattern.id === 'static' && pattern.type !== 'location') ? 1 : 0——静态定式为商品类(type=goods)恒为 1;库位类定式(empty_location)与其它商品定式(mis_shipment/expiring/warning)均为 0。", + "响应口径:create/patternCreate 返回的 check、detail 的 check、list 的行对象均为 is_static(number,0|1);库位盘点任务读取时恒为 0。", + "测试:test/app/service/systems/stock_check.test.js 的「is_static 静态标记」用例扩展——新增 type=location 传 is_static=1/true/'true' 均返回并落库 0 的断言;全量 245 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create(is_static 参数说明补充「仅商品盘点有效」+响应字段文案+notes)、stock.check.patternCreate(静态定式口径+notes)、stock.check.list / stock.check.detail(返回口径 notes);根版本 0.3.310 → 0.3.311、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "代码依据:app/service/systems/stock_check.js#create/#patternCreate、app/service/systemMethods/stock/check.js#create、app/model/stock_check.js(is_static)。" + ] + }, + { + "version": "0.3.310", + "date": "2026-10-28", + "type": "updated", + "summary": "库存盘点主表新增 is_static(是否静态盘点)标记:stock.check.create 支持入参 is_static(兼容 isStatic 驼峰与布尔/字符串写法),静态盘点定式(pattern=static)创建的任务自动置 1;stock.check.list / stock.check.detail / stock.check.patternCreate 返回该字段(0=普通盘点、1=静态盘点)。", + "methods": [ + "stock.check.create", + "stock.check.list", + "stock.check.detail", + "stock.check.patternCreate" + ], + "notes": [ + "需求背景:盘点任务需要区分「静态盘点」(针对长期停收停发商品的盘点)与普通盘点,原主表只有 type/mode/status,无法在列表/详情上识别任务来源与性质,静态定式创建的任务与手工任务混在一起。", + "库表变更:database/migrations/20261028010000-add-is-static-to-stock-check.js 给 wms_stock_check 新增 is_static(TINYINT(1) NOT NULL DEFAULT 0,注释「是否静态盘点(1=静态盘点(静态定式创建或创建时开启),0=普通盘点)」,位于 store_id 之后);存量数据默认 0,无需回填;down 迁移删除该列。", + "create 入参(新增):is_static 可选,纯标记——true / 'true' / 1 / '1' 记为 1,其余(含缺省、0、'false'、空串)记为 0;兼容 isStatic 驼峰写法;不参与模式强制(type=location 仍强制 blind)、状态机与差异计算;操作日志 STOCK_CHECK_CREATE 的 changeSummary/extras 追加静态标记。", + "patternCreate(自动判定):pattern_id=static 的任务 is_static=1,其余定式(empty_location/mis_shipment/expiring/warning)为 0;日志同样带「静态盘点」字样。", + "响应字段:create/detail/patternCreate 的 check(_formatCheckRow 口径)与 list 的行对象均返回 is_static(number,0|1);list 未新增 is_static 筛选条件。", + "测试:test/app/service/systems/stock_check.test.js 新增「is_static 静态标记」用例(缺省 0、isStatic=1 落库 1、detail/list 返回、方法层 is_static/isStatic 透传、0/'false'/空串/false 记 0),并在 static/warning 定式用例中断言 1/0;全量 245 用例通过、ESLint 0 错误;迁移已在本地开发库执行(information_schema 校验列存在)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create(新增 is_static 参数 + 响应字段说明 + notes)、stock.check.list(rows 返回字段 + notes)、stock.check.detail(check 返回字段 + notes)、stock.check.patternCreate(静态定式自动置 1 + notes);根版本 0.3.309 → 0.3.310、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "代码依据:app/model/stock_check.js(is_static 字段)、app/service/systems/stock_check.js#create/#patternCreate/#_formatCheckRow、app/service/systemMethods/stock/check.js#create、database/migrations/20261028010000-add-is-static-to-stock-check.js。" + ] + }, + { + "version": "0.3.309", + "date": "2026-10-28", + "type": "updated", + "summary": "库存盘点作业数据商品视图改为按商品汇总:stock.check.workData(goods 视图)同商品多库位明细合并为一行且行级不再返回 detail_id;stock.check.workDataDetail 改为传 id + stock_id 返回 summary 汇总 + rows 按库位分行(明细ID/库位ID/账面快照/实盘/差异);stock.check.report 的 detail_id 改为可选,缺失时按 id + stock_id + space_id 反查明细。", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail", + "stock.check.report" + ], + "notes": [ + "问题现象:goods 视图同一 stock_id 出现多条 detail_id(如盘点单里 stock_id=143270 出现 5 行、160240 出现 2 行),各行商品信息与 locations 库位列表完全相同,但行级 system_quantity/checked_quantity 只反映其中一条库位明细(该明细下作业记录),前端无法区分行间差异,跨行求和还会重复计数。", + "根因:商品盘点明细按「商品+库位」拆行落库(wms_stock_check_detail 唯一键 uk_check_stock_location = check_id+stock_id+location_id,addDetail 为该商品每个启用库存库位生成一行,system_quantity 为对应库位账面快照),而 _buildGoodsWorkRows 原以明细行为列表输出;locations 却按 stock_id 整商品计算,导致同商品多行内容高度重复而数量各管一个库位。", + "workData(goods 视图)改造:app/service/systems/stock_check.js#_buildGoodsWorkRows 先按 stock_id 分组(分组顺序沿用明细 id 升序,stock_id 为空/异常的明细行各自成行),再按组合并输出——行级 system_quantity=各库位明细行 system_quantity 之和、作业记录跨该商品全部明细合并后按库位编码聚合、checked_quantity/diff_quantity/is_diff 按合并后合计计算(无作业记录时差异仍恒 0);行级不再返回 detail_id/detail_ids(汇总行无单一明细语义),改为 locations 每项返回 detail_id(该库位盘点明细ID,供逐库位上报/删除)与 snapshot_quantity(该库位账面快照,明盘)。", + "workDataDetail 改造:商品分支入参改为 id(盘点任务ID)+ stock_id(商品库存ID,兼容 stockId),返回 { check_id, stock_id, 商品信息, summary, rows }——summary 为商品级 system_quantity(账面快照合计)/checked_quantity(实盘合计)/diff_quantity/is_diff;rows 每个库位一行,含 detail_id、location_id 与同义 space_id(可直接回传 report)、location_code、system_quantity(该库位当前账面=可用+锁定)、locked_quantity、snapshot_quantity(该库位账面快照)、checked_quantity(该库位实盘)、diff_quantity(实盘-快照)与 checked_at/checker_name/record_ids/images;盲盘不返回 summary 与任何数量字段;库位明细(detail_id 指向 scope_type=location 行)分支与原返回结构不变;传商品范围 detail_id 仍可用(服务端按明细商品解析 id + stock_id)。", + "report 兼容改造:detail_id 改为可选——未传时按 id + stock_id + space_id 反查明细(先命中 location_id=space_id 的该商品明细,未命中取该商品任一明细),反查不到报 400「盘点明细不存在(该商品不在本任务盘点范围内,或库位盘点任务需传 detail_id)」;既无 detail_id 也无 stock_id 仍报 400「盘点明细ID不能为空」;落库与覆盖式查重口径不变(作业记录仍挂 detail_id)。", + "响应兼容性(破坏性提示):① workData goods 视图行不再返回 detail_id/detail_ids,按明细操作(detailDelete 等)需改用 locations[].detail_id 或 workDataDetail rows[].detail_id;② workDataDetail 商品分支返回结构由「goods 视图单行」变为「summary + rows」钻取结构,旧前端读取 locations/checked_quantity 的代码需改读 summary/rows;③ 商品任务 workData goods 视图 total/rows 由「库位明细行数」变为「商品行数」(与主表 total_items 按商品计数一致)。", + "测试:test/app/service/systems/stock_check.test.js 新增/改写——「goods 视图多库位商品按商品汇总为一行」(两库位分别上报后断言 total=1、行级快照合计、跨明细合并实盘与 record_ids、locations 带 detail_id/snapshot_quantity)、「workDataDetail 商品钻取(summary + rows,含库位ID/明细ID/账面快照/实盘/差异)」「商品钻取盲盘不返回数量字段」「report 不传 detail_id 按 id + stock_id + space_id 反查上报」「方法层 stock_id/stockId/detail_id 兼容」;全量 244 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.workData(description/response.rows/notes 的商品视图口径与 locations 新字段)、stock.check.workDataDetail(params 改为 id/stock_id/detail_id 三选、description/response.data/notes 改为 summary+rows 钻取结构)、stock.check.report(detail_id 必填改可选 + stock_id 反查说明);根版本 0.3.308 → 0.3.309、updatedAt 2026-10-27 → 2026-10-28;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows/#workData/#workDataDetail/#_formatGoodsWorkDetail/#report、app/service/systemMethods/stock/check.js#workData/#workDataDetail/#report、app/model/stock_check_detail.js(uk_check_stock_location)。" + ] + }, + { + "version": "0.3.308", + "date": "2026-10-27", + "type": "updated", + "summary": "库存盘点移除范围类型 all(与 location 语义重复):全盘能力(未传库位时自动拉取全仓库启用库位)并入 location,type 缺省值改为 location,create 传 all 返回 400;存量 type=all 任务由迁移收敛(商品行任务改 goods、库位行/空任务改 location 并归一盲盘)。", + "methods": [ + "stock.check.create", + "stock.check.list", + "stock.check.addDetail", + "stock.check.workData", + "stock.check.markEmpty", + "stock.check.recheckClearLocation" + ], + "notes": [ + "动机:type=all 与 type=location 语义完全重复——两者都按库位盘点、明细都是 scope_type=location、mode 都被强制 blind;all 唯一的额外能力「添加明细时未传库位自动拉取全仓库启用库位」已合并进 location,all 因此下线。", + "create:type 仅允许 store/goods/location,缺省由 all 改为 location;传 all 返回 400「盘点范围类型不合法,仅支持 store/goods/location」。mode 规则不变——location 一律盲盘(忽略传入),store/goods 按传入值(缺省明盘)。", + "addDetail:type=location 未传 locations 且未传 location_ids 时自动拉取当前仓库全部启用且有效库位(排除无头库位)生成库位行(原 all 全盘语义);type=all 的历史任务不再走「已有商品明细行则按商品模式」兼容分支,直接返回 400「盘点范围类型不合法(all)」。", + "存量数据:database/migrations/20261027010000-merge-stock-check-type-all-into-location.js 将明细含商品行(scope_type=goods,2026-09-30 改造前的全仓按商品口径)的 type=all 任务改为 type=goods(mode 保持原值),其余(明细为库位行或无明细的空任务)改为 type=location 并归一 mode=blind;wms_stock_check.type 列默认值改为 location、注释去掉 all。", + "影响面:前端传 type=all 的创建调用将收到 400,需改为 location(需要全盘时创建 location 任务后调用 addDetail 不传库位即可)。workData/markEmpty/recheckClearLocation 等按库位判定的接口仍只认 type=location(历史 all 任务经迁移后即为 location)。", + "测试:test/app/service/systems/stock_check.test.js 改为 location 口径——新增「type=all 创建报 400」「历史 type=all 任务添加明细报 400」用例;原「type=all 缺省库位自动全仓」用例改由 type=location 承接;移除 type=all 历史商品明细兼容用例。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create/list/addDetail/workData/markEmpty/recheckClearLocation(type 语义、mode 规则、全盘自动范围、错误文案);根版本 0.3.307 → 0.3.308、updatedAt 2026-10-27;methods/changes/system.json 新增本条(插入数组首位);未改动其它分组。", + "破坏性提示:type=all 不再是合法入参(400);依赖「all 缺省自动全仓」的调用改为 location 即可,行为一致。", + "代码依据:app/service/systems/stock_check.js#create/#addDetail/#workData/#markEmpty/#recheckClearLocation、app/service/systemMethods/stock/check.js、app/model/stock_check.js、database/migrations/20261027010000-merge-stock-check-type-all-into-location.js。" + ] + }, + { + "version": "0.3.307", + "date": "2026-10-25", + "type": "updated", + "summary": "库存盘点上报(stock.check.report)改为 space_id 必传:库位一律按库位ID落库、不再按编码猜库位(修复同仓库同编码重复库位导致作业记录挂到无头脏库位);实盘数量上限 2147483647 返回 400;取回接口补充 space_id/location_id 字段供回传;操作日志 message/before_changes 补充库位编码与库位ID。", + "methods": [ + "stock.check.report", + "stock.check.workData" + ], + "notes": [ + "问题现象:生产盘点单 PD20261025000001 的 stock.check.workData space 视图出现 custom_name/custom_barcode 为 null 的库位行(如 E02-06-01-01)。根因:wms_location_space 存在大量同仓库同编码重复库位(uk_warehouse_space_code 含 deleted_at,NULL 不去重导致重复插入不受约束),其中大量库位所属 zone 已删除(无头库位);report 旧逻辑只按 warehouse_id + space_code 做 findOne,命中最小的历史行,导致作业记录挂到脏库位,space 视图再按记录库位补行时又未做分区有效性过滤。", + "取回侧字段(本次补齐):workData/workDataSpaceDetails 的 space 视图行新增 space_id 与 location_id(与既有 id 同值);goods 视图 locations[] 新增 space_id 与 location_id(取分区有效库位行,同编码多条取拣货顺序第一条,已盘但无库存的库位按编码补查有效库位)。location 视图/recordList/result 的 location_id 保持不变。", + "report 写库(本次修正为强制):space_id 必传(兼容 spaceId/location_id/locationId 写法,取回接口 rows[].space_id、rows[].id、locations[].space_id 可直接回传);服务端校验属于本仓库且 zone 存在未删除,缺失/非法返回 400「缺少库位ID(space_id)」,不存在/跨仓库/分区已删除返回 400;库位编码以 space_id 对应库位行为准,location 入参降级为可选一致性校验(不一致 400),服务端不再按编码匹配/猜库位;库位明细行还要求 space_id 对应编码等于明细库位编码。", + "report 校验:实盘数量新增上限 2147483647(wms_stock_check_record.quantity 为 int(12)),超限返回 400「实盘数量不能超过 2147483647」;此前超限直接落库抛 Out of range 变 500(生产今日 10 次)。", + "workData space 视图:记录库位归一(上报编码与明细编码一致归并到明细固化 location_id;记录指向无头库位时归并到同编码有效库位),库位商品明细改按「库位+商品」索引、作业记录改按「库位+商品」聚合,避免跨库位上报时同一编码出现两行或实盘数落到别的行。", + "操作日志:STOCK_CHECK_REPORT 的 message 追加库位编码与库位ID;before_changes 落 check_no/detail_id/scope_type/stock_id/location_code/location_id/detail_location_code/detail_location_id/quantity/barcode/is_unknown_goods/is_empty/mode/record_id 快照(原 changeSummary 参数在 operationLog.buildOperationLogData 中未落库,日志里查不到库位信息)。", + "问题定位依据(只读核查):生产 wms-api.log 中 244 条 stock.check.report 请求 body 键仅 id/detail_id/quantity/location/stock_id,无 space_id;detail 6151 于 2026-10-25 22:55:36 上报 location=E02-06-01-01(明细库位为 E02-06-02-01),落库 location_id=13768(zone 59 已删除);有效行为 22093(E1区02-06-01/00224214)。", + "测试:test/app/service/systems/stock_check.test.js 升级为 space_id 必传口径——新增/改写用例覆盖「同编码重复库位不产生幽灵行」「space_id 必传与缺失/非法/跨仓库/无头/编码不一致 400」「数量超限 400 且不落库」「操作日志含库位信息」「space 视图行 space_id=id」「goods 视图 locations[] 含 space_id」,全量 244 通过。", + "文档变更范围:methods/system.json 的 stock.check.report(space_id 必填参数、location 降级为一致性校验、quantity 上限)、stock.check.workData / stock.check.workDataSpaceDetails(space 视图行含 id/space_id/location_id、goods locations[] 含 space_id)+根版本 0.3.306 → 0.3.307、updatedAt 2026-10-25;methods/changes/system.json 新增本条(插入数组首位)。", + "破坏性提示:旧调用方(未传 space_id)将收到 400「缺少库位ID(space_id)」,前端需改为回传取回接口返回的 space_id;「无库位上报」通道随之取消(历史 location_code='' 记录仍按既有口径展示/导出为空)。", + "代码依据:app/service/systems/stock_check.js#_resolveLocationIdByCode/#report/#_buildSpaceWorkRows、app/service/systemMethods/stock/check.js#report。" + ] + }, + { + "version": "0.3.306", + "date": "2026-10-25", + "type": "added", + "summary": "用户账号能力增强:user.getAccountInfo 返回新增 is_custom_password;新增 user.updateUsername(服务端重名校验并排除自己)与 user.changePassword(首次自定义密码可免旧密码,修改后置 is_custom_password=1,再次修改必须校验旧密码)。", + "methods": [ + "user.getAccountInfo", + "user.updateUsername", + "user.changePassword" + ], + "notes": [ + "user.getAccountInfo:返回字段白名单新增 is_custom_password(是否自定义密码:0-否,1-是),仍不返回 password_hash、salt、last_login_ip。", + "user.updateUsername:新增方法,仅修改当前登录账号;username 必填,长度3-50且仅允许字母/数字/下划线;服务端查询 username 重名时排除自己(id != 当前账号),重名返回 409;用户名未变化直接返回成功;更新后清理用户缓存,并同步当前请求上下文 username。", + "user.changePassword:新增方法,入参 new_password 必填(兼容 newPassword),old_password 兼容 oldPassword;is_custom_password=0 时旧密码可不传,is_custom_password=1 时必须传且校验通过;修改时重新生成 salt 与 password_hash,并将 is_custom_password 置为1;方法已加入 _noNeedLog,避免请求体中的明文密码写入操作日志。", + "错误码:updateUsername 400(参数/格式)/401(未登录)/404(账号不存在)/409(用户名已存在);changePassword 400(新密码为空、请输入旧密码、旧密码错误)/401/404;数据库异常返回 code=0。", + "数据库:依赖迁移 20261025135000-add-is-custom-password-to-wms-account.js(wms_account.is_custom_password TINYINT(1) NOT NULL DEFAULT 0),开发库与生产库均已执行。", + "测试:test/app/service/systemMethods/user.getAccountInfo.test.js(5)、user.updateUsername.test.js(7)、user.changePassword.test.js(8),合计 20 通过。", + "文档变更范围:methods/system.json 的 user.getAccountInfo(response 新增 is_custom_password)、user.updateUsername(新增)、user.changePassword(新增)+根版本 0.3.305 → 0.3.306、updatedAt 2026-10-25;方法文档已写入开发库 wms_api_method_doc 并重新导出;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systemMethods/user.js#updateUsername/#changePassword、app/service/systems/auth/user.js#updateUsername/#changePassword、app/service/systems/auth/user.js#getAccountInfo。" + ] + }, + { + "version": "0.3.305", + "date": "2026-10-25", + "type": "added", + "summary": "新增 user.getAccountInfo:仅返回当前登录账号在 wms_account 的账号级信息,不返回 password_hash、salt、last_login_ip 等敏感字段。", + "methods": [ + "user.getAccountInfo" + ], + "notes": [ + "方法层:app/service/systemMethods/user.js 新增 getAccountInfo(data),未加入 _noNeedLogin(需登录),加入 _noNeedLog(只读接口不写操作日志),统一 this.success('获取账号信息成功', result) 包装;不接收账号ID,避免越权查询。", + "系统层:app/service/systems/auth/user.js 新增 getAccountInfo(),账号ID取自 ctx.userId / ctx.user.id;使用 attributes 白名单(id/username/real_name/phone/email/status/last_login_at/created_at/updated_at)查询 wms_account,raw=true,显式排除 password_hash、salt、last_login_ip。", + "错误码:未登录或登录已过期返回 401;账号不存在返回 404;查询异常返回 code=0。", + "测试:test/app/service/systemMethods/user.getAccountInfo.test.js(5 通过,覆盖方法层透传/失败码、登录账号过滤与敏感字段白名单、未登录 401、账号不存在 404)。", + "文档变更范围:methods/system.json 的 user.getAccountInfo 一条(新增)+根版本 0.3.304 → 0.3.305、updatedAt 2026-10-25;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systemMethods/user.js#getAccountInfo、app/service/systems/auth/user.js#getAccountInfo。" + ] + }, + { + "version": "0.3.304", + "date": "2026-10-23", + "type": "updated", + "summary": "pick.waveClaimScan 领料跳过拦截单改为按打印状态区分:已打印(print_status=fin)的拦截订单面单实物已流出,不再受拦截影响、照常置为已领料;仅未打印的拦截订单跳过领料(0.3.303 → 0.3.304)", + "methods": [ + "pick.waveClaimScan", + "pick.query", + "order.wave.confirmPrintUnclaimedWaveCount" + ], + "notes": [ + "变更内容一(领料口径):waveClaimScan 计算待领料订单时,拦截订单由「整体跳过」改为「仅未打印(print_status != fin)的拦截订单跳过」;已打印(print_status=fin)的拦截订单纳入领料范围并写 ORDER_WAVE_CLAIM 日志,响应新增 intercept_skipped_order_count(因拦截且未打印跳过领料的订单数)与 claimed_intercepted_order_count(本次/本人已领的已打印拦截订单数);getWaveClaimGateStats(pick.query 领料门禁)同步按该口径统计,已打印的拦截订单未领料时阻隔建拣货任务。", + "变更内容二(领料时间补写):waveClaimScan 命中 already_claimed 幂等分支时,若波次表 claim_time 为空则补写 claim_time + claim_operator 并递增统计版本号;旧逻辑下「整波订单均被拦截跳过」或历史领单发生在 claim_time 字段之前时,波次表永远没有领料时间,order.wave.confirmPrintUnclaimedWaveCount(以 wb.claim_time IS NULL 判定未领单)会长期显示该波次「已打印未领单」,且重复扫描领料只返回 already_claimed 无法自愈。", + "背景:生产订单 1314391 所在波次已确认打印后被写入拦截,操作员扫描面单领料时该订单被拦截逻辑跳过、未置为已领料,但面单实物已打印并被领走;打印与领料之间不存在拦截出库流程,已打印订单不应再受拦截影响。同一波次在「确认打印未领单」统计中一直显示为 1,需重新扫描后自愈。", + "代码依据:app/service/systemMethods/pick.js#waveClaimScan(新增 interceptClaimSkippedOrderIds,unclaimed/ownClaimed 与响应统计按新口径;already_claimed 分支调用 backfillWaveClaimTime 并复用 bumpConfirmPrintUnclaimedWaveVersionSafe)、#backfillWaveClaimTime、#bumpConfirmPrintUnclaimedWaveVersionSafe、#getWaveClaimGateStats(查询补 print_status,仅未打印拦截订单免领料);新增单测 test/app/service/systemMethods/pick.waveClaimScan.test.js(WC1~WC5,5 通过)。", + "验证:npx egg-bin test test/app/service/systemMethods/pick.waveClaimScan.test.js 5 通过;ESLint 0 错误;pick.query.test.js / pick.createWavePickTask.test.js 的失败为改动前既有失败(stash 基线同样失败)。", + "存量处理:受影响波次重新扫一次波次内已打印面单号即可自动补领料与 claim_time;若订单已迁出待处理订单表,需按仓库分表人工订正 claim_status/claim_time。", + "文档变更范围:methods/system.json 的 pick.waveClaimScan(description、intercepted_order_count、新增 intercept_skipped_order_count / claimed_intercepted_order_count)、pick.query(description、400 错误说明)与 order.wave.confirmPrintUnclaimedWaveCount(description 补补写说明);根版本 0.3.303 → 0.3.304、updatedAt 2026-10-23;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "2026.10.21-order-delivery-summary", + "date": "2026-10-21", + "type": "added", + "summary": "新增 order.deliveryOrder.summary(配送订单每日汇总):以自然日为维度统计每日订单量、迁入配送表订单量、发货量(订单数/商品件数/金额)、拦截数量、库内确定拦截数量与取消数量,默认最近 7 天、最多 90 天,缺失日期补 0;仓库取自登录上下文,可选 store_id 过滤。", + "methods": [ + "order.deliveryOrder.summary" + ], + "notes": [ + "方法层:app/service/systemMethods/order/deliveryOrder.js 新增 summary(data),加入 _noNeedRight/_noNeedLog/_noNeedAuth(只读接口,与 list/quickSearch 同口径),统一 this.success('ok', result) 包装;参数兼容 start_date/startDate/start_time、end_date/endDate/end_time、store_id/storeId", + "系统层:新增 app/service/systems/deliveryOrderSummary.js(queryDailySummary/queryDailyCount/queryDailyShipped),同时查订单常用表与配送表分表(getCurrentModel + getDispatchModel),归档 history 与委托外仓 outsourced 不参与;日期分组用 CONVERT_TZ(字段, Sequelize 时区, 服务器本地时区) 后取 DATE,保证自然日与本地时区一致", + "纯函数:新增 app/lib/delivery_order_summary.js(区间解析/日期展开/聚合合并,无 egg 依赖),单次区间上限 90 天,缺省 7 天", + "指标口径:order_count=create_at(排除 cancel);dispatch_count=配送表 dispath_time;shipped_count/shipped_items_total/shipped_amount=delivery_time(排除 cancel);intercepted_count=intercept_time 且 intercept_status != none;intercepted_at_warehouse_count=配送表 dispath_time 且 intercept_status=intercepted_at_warehouse(与 report interceptOrder 口径一致);cancelled_count=updated_at 且 status=cancel(取消操作会刷新 updated_at)", + "测试:test/app/service/systemMethods/order/deliveryOrder.summary.test.js(聚合与参数映射 6 例)、test/delivery_order_summary.cjs(区间与合并纯函数 10 例)", + "文档变更范围:methods/system.json 的 order.deliveryOrder.summary 一条(新增)+根版本 0.3.302 → 0.3.303、updatedAt 2026-10-21;methods/changes/system.json 新增本条(插入数组首位)" + ] + }, + { + "version": "2026.10.17-returnUnpack.transferByOrders", + "date": "2026-10-17", + "type": "added", + "summary": "新增退回拆包接口 returnUnpack.transferByOrders(配送订单批量转退回拆包单):入参 ids 为订单表主键数组(去重后上限 200),仅允许库内拦截订单转换;已有拆包单/非库内拦截/无运单号/无明细的订单静默跳过;每单新建拆包单并 1:1 复制订单明细(product_status=normal),返回成功/跳过/失败明细。新增权限 643(API:配送订单批量转退回拆包单,授权角色 27/26)。", + "methods": [ + "returnUnpack.transferByOrders" + ], + "notes": [ + "方法层:app/service/systemMethods/returnUnpack.js 新增 transferByOrders(data)(位于 transferByWaybills 之后),统一 this.success('ok', data) 包装,未加入 _noNeedRight/_noNeedLogin/_noNeedLog/_noNeedAuth 免检清单(isNeedAuth=true、isNeedLogin=true)", + "系统层:app/service/systems/return_unpack.js 新增 transferByOrders / _isWarehouseInterceptedOrderStatus / _loadOrdersForTransferByOrders / _loadOrderItemsForTransferByOrders / _parseOrderItemsJson / _resolveOrderExpressForTransferByOrders;复用 _insertMainWithRetry / _buildTransferDetailRows / _recalcMain / _resolveStoreRemark / _resolveReturnReceivedId", + "转换限制(用户确认):仅允许库内拦截(intercept_status=intercepted_at_warehouse,兼容 intercepted)的订单;非库内拦截订单跳过;已有拆包单(同订单或同运单号 status != 'cancelled')跳过;静默跳过,完成几个算几个", + "拆包单:status=unpacking、detail_status 按明细识别率回填;明细 product_status 固定 normal;waybill_code 取订单主运单号,无运单回退 delivery_order_code", + "权限:迁移 20261017100000-add-return-unpack-transfer-orders-permission.js,固定 ID 643(角色 27/26),开发库已执行(641/642 已被外部仓库小程序页面占用)", + "文档变更范围:methods/system.json 的 returnUnpack.transferByOrders 一条(新增)+根版本 0.3.301 → 0.3.302、updatedAt 2026-10-17;methods/changes/system.json 新增本条(插入数组首位)" + ] + }, + { + "version": "0.3.301", + "date": "2026-10-16", + "type": "updated", + "summary": "自动出库「不出库当天订单」支持跨天放行:放行时间放开到 00:00~47:59(27:00 = 次日 03:00),限制窗口改为按订单复核时间所在日计算", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "语义变更(原实现按「当前日」计算窗口,跨天时会提前放行,且放行时间只支持 00:00~23:59):新口径按**订单复核时间所在北京日 D**计算 —— recheck_time < D + 允许当天出库最后时间 的订单不受影响;recheck_time ≥ D + 最后时间 的订单在 now < D + 放行时间 前不出库,到达后放行。", + "字段范围:same_day_outbound_release_time 放开到 00:00~47:59(24:00 之后的数字表示次日,例如 27:00 = 次日 03:00;48:00 等超限值回退默认 22:00);same_day_outbound_deadline_time 仍限当天内 00:00~23:59。", + "典型配置:① 当天复核的订单当天不出、过零点出库 → deadline=00:00 + release=23:59;② 到次日 03:00 才出库 → deadline=00:00 + release=27:00;③ 当天 20:00 后复核的次日 05:00 放行 → deadline=20:00 + release=29:00。", + "recheck_time 为 NULL 的订单仍不受该限制(既有口径);字段名 same_day_outbound_release_time 未变,仅中文名与语义说明调整(getFieldMeta 中显示名改为「放行时间」)。", + "验证:本地隔离测试仓真实库走查 12 个场景全通过(含 S6a 当天/ S6b 次日 02:00 未放行 / S6c 次日 04:00 放行 / S6d 次日复核仍受限),脚本 test/auto_outbound_local_test_warehouse.cjs;单测 30 例通过(含跨天窗口补集断言)。", + "文档变更范围:methods/system.json 的 setting.warehouse.getSettings 响应、setting.warehouse.saveSettings 入参中 exclude_same_day_outbound / same_day_outbound_deadline_time / same_day_outbound_release_time 三条描述 + method 描述;根版本 0.3.300 → 0.3.301、updatedAt 2026-10-16;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.300", + "date": "2026-10-16", + "type": "updated", + "summary": "自动出库当天限制的时间口径补充:时间字段仅支持 00:00~23:59(不支持 24:00),「当天不出库、过零点全部出库」用 deadline=00:00 + release=23:59", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "背景:业务希望「未打包订单当天不出库,过了零点(24:00)后全部出库」。现有 same_day_outbound_deadline_time / same_day_outbound_release_time 只支持 HH:mm 且范围 00:00~23:59,写 24:00 会被回退成默认值。", + "推荐配置:exclude_same_day_outbound=true + same_day_outbound_deadline_time=00:00 + same_day_outbound_release_time=23:59 —— 当天 00:00 之后复核的订单全天不出库,到达 23:59 后(含次日凌晨,cutoff 前移到次日 00:00 使前一日复核订单自动放行)全部出库。", + "附带说明:recheck_time 为 NULL 的订单不受该限制(既有口径);已打包等其它规则若关闭 exclude_same_day_outbound 则不受影响。", + "本地真实库走查(隔离临时仓 990001,8 个场景全通过):S1/S2 当天限制与放开时刻、S3 deadline 06:00→03:00 边界、S4a/S4b release 06:00 前后、S5a/S5b/S5c deadline=00:00+release=23:59 的当天/23:59/次日三个时点。测试脚本 test/auto_outbound_local_test_warehouse.cjs(不入库)。", + "文档变更范围:methods/system.json 的 setting.warehouse.getSettings 响应、setting.warehouse.saveSettings 入参两条字段描述 + method 描述;根版本 0.3.299 → 0.3.300、updatedAt 2026-10-16;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.299", + "date": "2026-10-16", + "type": "updated", + "summary": "仓库设置自动出库配置重构:开关拆分为 auto_outbound_enabled,auto_outbound_rules 改为规则数组(仅校验打包/称重/同步,任一命中即出库,固定要求已复核),移除复核/打印/拣货校验", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings" + ], + "notes": [ + "变更内容:subject_config 新增 auto_outbound_enabled(flag,默认 false);auto_outbound_rules 由对象改为数组,每项字段为 require_pack/require_weigh/require_sync/exclude_same_day_outbound/same_day_outbound_deadline_time/same_day_outbound_release_time,规则内条件 AND、规则间 OR(任一命中即出库),空数组表示不出库任何订单。", + "固定前置条件:所有规则均要求已复核(recheck_status=fin)与已分配储位(storage_status=fin),未复核订单一律不自动出库;不再校验已打印(print_status)与已拣货(pick_status)。", + "不兼容变更:旧对象结构(含 enabled/require_recheck/require_print/require_pick)一律按默认(关闭 + 空规则)处理,需重新配置;saveSettings 保存非数组时返回 400(不静默重置)。", + "处理范围:自动出库配置以仓库为单位生效(wms_store.id 即 warehouse_id),仅扫描该仓库自身订单,不再扩展到货主签约的外部合同仓。", + "出库操作日志:自动出库成功更新后按订单写入 wms_operation_log(business_type=order,operation_code=ORDER_AUTO_OUTBOUND,operator=系统,message 形如「自动出库(命中规则1:需已打包、需已称重)」);写日志失败仅告警不影响出库。", + "代码依据:app/model/store.js(默认值与 normalizeAutoOutboundRules)、app/service/systems/order_auto_outbound.js(getEnabledAutoOutboundWarehouses/isAutoOutboundEnabled/resolveAutoOutboundRules/buildAutoOutboundWhere/findAutoOutboundOrderIds/processWarehouseAutoOutbound/writeAutoOutboundOperationLogs)、app/service/systemMethods/outbound.js、app/service/systems/setting/warehouse.js(WAREHOUSE_SETTING_FIELDS + saveSettings 数组校验)、app/dict/businessDict.js(ORDER_AUTO_OUTBOUND)。", + "验证:单测 test/auto_outbound_rules_v2.test.cjs(23 用例通过,含配置归一化/条件拼装/多规则命中去重/操作日志/字段元信息/保存校验);ESLint 0 错误。", + "文档变更范围:methods/system.json 的 setting.warehouse.getSettings 响应、setting.warehouse.getFieldMeta、setting.warehouse.saveSettings 入参三处;根版本 0.3.298 → 0.3.299、updatedAt 2026-10-16;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.298", + "date": "2026-10-14", + "type": "added", + "summary": "小程序用户须知增加系统默认版本:首次授权时自动写入作为第一版(0.3.297 → 0.3.298)", + "methods": [ + "wechat.getUserAgreementText" + ], + "notes": [ + "变更内容:wms_wechat_agreement_version 新增系统级种子行 appid='system'(系统默认须知模板,迁移 20261014100000 开发+生产执行);首次授权的小程序(handleAuthCallback 与 authorized/updateauthorized 事件的 create 分支)自动复制该内容为第一版(systems/wechat.js#ensureDefaultAgreementVersion,幂等:已有任意版本则跳过)。", + "系统默认内容可在 wms_wechat_agreement_version 中 appid='system' 的行直接修改(后续授权的小程序复制新内容);已授权但无版本的小程序不会自动回填(如需回填另行处理)。", + "代码依据:app/service/systems/wechat.js 新增 SYSTEM_AGREEMENT_APPID 常量与 ensureDefaultAgreementVersion;app/controller/wechatOpen.js 两处 create 分支调用。", + "文档变更范围:methods/system.json 的 wechat.getUserAgreementText 一条(description 补系统默认版本说明);根版本 0.3.297 → 0.3.298、updatedAt 2026-10-14;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.297", + "date": "2026-10-14", + "type": "updated", + "summary": "wechat.getTemplateList 移除 Redis 缓存,改为每次实时拉取微信(0.3.296 → 0.3.297)", + "methods": [ + "wechat.getTemplateList" + ], + "notes": [ + "变更内容:移除 wechat:template:list:normal 的 Redis 缓存读写(cacheGet/cacheSet),每次调用直接 GET wxa/gettemplatelist 实时拉取;响应移除 from_cache 字段。", + "背景:模板缓存 24h → 5 分钟仍反复遇到旧列表问题,用户要求彻底移除缓存。", + "代码依据:app/service/systems/wechat.js#getTemplateList 移除 CACHE_KEY/CACHE_TTL_SECONDS 与缓存分支;systemMethods/wechat.js JSDoc 同步。", + "文档变更范围:methods/system.json 的 wechat.getTemplateList 一条(description 改实时拉取、response 移除 from_cache);根版本 0.3.296 → 0.3.297、updatedAt 2026-10-14;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.296", + "date": "2026-10-13", + "type": "updated", + "summary": "wechat.getTemplateList 模板缓存 TTL 24h → 5 分钟(0.3.295 → 0.3.296)", + "methods": [ + "wechat.getTemplateList" + ], + "notes": [ + "变更内容:模板列表 Redis 缓存 TTL 由 24 小时(24*3600)改为 5 分钟(5*60),模板更新后最多 5 分钟即可在列表接口看到最新模板。", + "背景:2026-10-13 生产模板库变更后列表仍命中旧缓存,用户要求缩短缓存时间。", + "代码依据:app/service/systems/wechat.js#getTemplateList CACHE_TTL_SECONDS 24*3600 → 5*60;JSDoc 同步;systemMethods/wechat.js JSDoc 同步。", + "文档变更范围:methods/system.json 的 wechat.getTemplateList 一条(description 缓存 24h → 5 分钟);根版本 0.3.295 → 0.3.296、updatedAt 2026-10-13;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.295", + "date": "2026-10-13", + "type": "fixed", + "summary": "wechat.commit 模板 ID 校验放开 0:普通模板库模板 ID 从 0 开始(0.3.294 → 0.3.295)", + "methods": [ + "wechat.commit" + ], + "notes": [ + "变更内容:template_id 校验由「正整数(>0)」改为「非负整数(≥0)」,错误提示同步改为「template_id 必须为非负整数」;普通模板库第一个模板的 template_id 为 0(微信官方 wxa/commit 请求示例即 \"template_id\": \"0\"),此前模板库唯一模板 template_id=0 无法提交。", + "背景:2026-10-13 生产模板库仅一个模板(template_id=0),调用 wechat.commit 被本服务校验拦截。", + "代码依据:app/service/systems/wechat.js#commit 校验条件 <=0 → <0;本地未新增测试(0 的边界由现有 list.find 匹配覆盖),ESLint 0 错误。", + "文档变更范围:methods/system.json 的 wechat.commit 一条(params.template_id.description 补 0 合法说明、errors 补非负整数校验提示);根版本 0.3.294 → 0.3.295、updatedAt 2026-10-13;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.294", + "date": "2026-10-13", + "type": "updated", + "summary": "pick.wavePickTaskComplete 跳过拦截单时区分打印状态:已打印面单的拦截订单不再自动移出波次(0.3.293 → 0.3.294)", + "methods": [ + "pick.wavePickTaskComplete" + ], + "notes": [ + "变更内容:拣货提交时被跳过的拦截订单中,仅未打印(print_status=none/空)的自动移出波次(原逻辑不区分打印状态,已打印面单的拦截订单也被移出,导致面单实物与波次记录分离);已打印(print_status!=none)的拦截订单保持不动(保留波次与任务订单关联,写 warn 日志提示,需人工 wave.batchRemoveOrders 处理),与复核链路 removeUnprintedInterceptedOrdersFromWave 的原则对齐。响应新增 kept_intercepted_order_ids(保持不动的拦截订单ID列表),skipped_intercepted_orders 明细新增 print_status 字段。", + "背景:生产日志 2026-09-29 11:24:22 订单 839153 面单已打印、拣货员拿面单拣货时货主发起拦截,提交拣货后被自动移出波次 B2026092900050,面单与波次记录分离。", + "代码依据:app/service/systems/pick.js#wavePickTaskComplete(拦截检查查询补 print_status、移出波次分支过滤已打印、新增 kept_intercepted_order_ids);本地单测新增 IC1/IC2/IC3 用例验证(test/ 目录不入库),31 通过 0 失败;ESLint 0 错误。", + "文档变更范围:methods/system.json 的 pick.wavePickTaskComplete 一条(description 补打印状态区分说明、response 补 4 个字段);根版本 0.3.293 → 0.3.294、updatedAt 2026-10-13;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.293", + "date": "2026-10-12", + "type": "updated", + "summary": "index.getWarehousePanelData scatterPacking 移除 wave 波次数(散单无波次语义)(0.3.292 → 0.3.293)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:scatterPacking(散单打包块)的 summary 与 top 各项移除 wave 字段(散单无波次语义),仅团购块 groupPacking 保留 wave(波次数);orders/goods/sku/top 结构不变。", + "代码依据:app/service/systems/warehouse_panel.js#queryPackingBlock(isGroup 时才输出 wave);ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 补散单块无 wave);根版本 0.3.292 → 0.3.293、updatedAt 保持 2026-10-12;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.292", + "date": "2026-10-12", + "type": "updated", + "summary": "index.getWarehousePanelData 新增面板刷新公共方法 touchLastChangeAt(warehouseId),并接入拣货完成/复核完成/打包完成路径(0.3.291 → 0.3.292)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:WarehousePanelService 新增公共方法 touchLastChangeAt(warehouseId)——更新对应仓库面板缓存键的最后更新时间戳(只写时间戳整值替换、TTL 300 秒、失败仅告警返回 0),供各业务写路径通知大屏刷新;已接入:拣货完成 systems/pick.js#wavePickTaskComplete、复核完成 systemMethods/order/recheckOrder.js#confirmRecheck / confirmRecheckByWaveId / batchQuickRecheck / batchQuickRecheckByWave、打包完成 systems/workbench.js#_updateOrderPackStatus(覆盖所有打包结束路径)。", + "代码依据:app/service/systems/warehouse_panel.js#touchLastChangeAt(新增)+ 3 个文件 6 处调用点;ESLint 0 错误(workbench.js 存在预先存在的 class-field 解析告警与本次无关)。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(notes 新增外部驱动公共方法说明);根版本 0.3.291 → 0.3.292、updatedAt 保持 2026-10-12;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.291", + "date": "2026-10-12", + "type": "updated", + "summary": "index.getWarehousePanelData stageOverview 环节卡 doing/abnormal 统一订单表状态口径(拣货中/打包中/各环节异常)(0.3.290 → 0.3.291)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:stageOverview 环节卡 doing/abnormal 统一订单表状态口径——拣货 doing 由拣货任务数(wms_wave_pick_task status=1)改为订单表 pick_status=padding(池内 + 配送表今日出库双表);拣货 abnormal=pick_status=error、复核 abnormal=recheck_status=error、打包 abnormal=pack_status=error 均补配送表今日出库双表;打包 abnormal 由任务数(wms_pack_task status=3)改为订单表 pack_status=error;复核 doing 保持波次口径(wms_wave_batch,订单表 recheck_status 仅有 none/fin/error 无复核中状态)。", + "代码依据:app/service/systems/warehouse_panel.js#queryStageOverview(pickDoing/pickAbnormal/recheckAbnormal/packAbnormal 改 Promise.all 双表订单状态 count);ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 补环节卡口径);根版本 0.3.290 → 0.3.291、updatedAt 保持 2026-10-12;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.290", + "date": "2026-10-12", + "type": "updated", + "summary": "index.getWarehousePanelData 打包卡 doing 改订单表 pack_status=padding 订单数口径(0.3.289 → 0.3.290)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:stageOverview 打包卡 doing 由「打包中任务数(wms_pack_task status=1 count)」改为「打包中订单数」——订单表 pack_status=padding(池内 pendingBase + 配送表今日出库 dispatchTodayBase 双表计数),与 fulfillment 未打包/已打包同源订单表口径。", + "数据说明:生产实测池内 padding=0;配送表今日出库存在 96 条 pack_status=padding 残留(订单已 outbound_status=fin 但出库未回填 pack_status,另有 8 条打包任务 status=1 挂起且关联订单均已出库),属历史数据问题,待出库回填逻辑修复。", + "代码依据:app/service/systems/warehouse_panel.js#queryStageOverview(packDoing 改 Promise.all 双表 count pack_status=padding);ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 补 doing 口径);根版本 0.3.289 → 0.3.290、updatedAt 保持 2026-10-12;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.289", + "date": "2026-10-12", + "type": "updated", + "summary": "index.getWarehousePanelData 打包汇总(pack 卡 today / groupPacking / scatterPacking)排除打包中任务,仅统计已完成 status=2(0.3.288 → 0.3.289)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:pack 卡 today 与 groupPacking/scatterPacking 的任务条件由 status != 3(含打包中)改为 status = 2(仅已完成),打包中任务不再计入打包订单数;打包中仍体现为:fulfillment 未打包数(pack_status != fin 含 padding)+ stageOverview 打包卡 doing(打包中任务数)。", + "代码依据:app/service/systems/warehouse_panel.js#queryStageOverview(packToday 两个子查询 status != 3 → status = 2)/#queryPackingBlock(taskWindowWhere status != 3 → status = 2);ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 补排除打包中口径);根版本 0.3.288 → 0.3.289、updatedAt 保持 2026-10-12;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.288", + "date": "2026-10-12", + "type": "updated", + "summary": "index.getWarehousePanelData stageOverview 打包卡 today 改真实打包订单数(团购按 wave_index 真实订单数替代 pack_quantity 快照)(0.3.287 → 0.3.288)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:打包卡 today 的团购部分由 pack_quantity 快照求和改为团购任务 wave_id 关联 wms_order_wave_index 的真实订单数(DISTINCT wave_id 去重)+ 散单任务数,修复快照虚高导致打包卡(16013)大于已复核(15385)的问题;新口径今日真实打包订单数=15408(与已复核差 23=免复核商品订单,属正常)。", + "代码依据:app/service/systems/warehouse_panel.js#queryStageOverview(packToday countSql 改为散单任务计数 + 团购 wave_index 真实订单数子查询);ESLint 0 错误;生产 SQL 实测 15408。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 补打包卡 today 口径);根版本 0.3.287 → 0.3.288、updatedAt 保持 2026-10-12;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.287", + "date": "2026-10-12", + "type": "updated", + "summary": "index.getWarehousePanelData fulfillment 已打包改订单状态存量口径(pack_status=fin 池内+配送今日出库),修复已打包大于已复核(0.3.286 → 0.3.287)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:fulfillment 打包环节已* 由「今日打包任务订单数」(wms_pack_task 窗口内 pack_mode=2 按 pack_quantity 求和 + 散单每任务 1 单)改回订单状态存量口径(池内 pack_status=fin + 配送表今日出库 pack_status=fin),与分配/打印/拣货口径一致;修复打包任务快照含未复核/重复计入导致已打包(16013)大于已复核(15385)的问题,改后已打包=14739 ≤ 已复核。stageOverview 打包卡 today 仍为今日打包任务订单数口径(与打包卡语义一致)。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(新增 todayPackOrdersPromise 池内+配送双表 pack_status=fin,doneTodayMap.pack_status 改取该值,删除 packTaskOrdersToday 查询);ESLint 0 错误;egg 直调验证环节约束通过。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 补打包环节已* 口径);根版本 0.3.286 → 0.3.287、updatedAt 保持 2026-10-12;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.286", + "date": "2026-10-12", + "type": "updated", + "summary": "index.getWarehousePanelData trend 下单量窗口修正为业务日窗口(未过零点=今日自然日开始时间起,凌晨=昨日自然日开始时间起)(0.3.285 → 0.3.286)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:trend created_count 统计窗口由 [自然日零点, 业务日结束)(凌晨订单并入首点)修正为业务日窗口 [自然日开始时间, 次日自然日开始时间)——未到次日自然日开始时间时为 [今日自然日开始时间, 次日自然日开始时间),凌晨(已过零点)时为 [昨日自然日开始时间, 今日自然日开始时间);早于窗口起点的订单不再并入首点。", + "代码依据:app/service/systems/warehouse_panel.js#queryTrend(删除 midnight/early 计数查询,窗口直接使用 todayStart/tomorrowStart);ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 补窗口口径);根版本 0.3.285 → 0.3.286、updatedAt 2026-10-11 → 2026-10-12;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.285", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData trend 移除 pack_count 打包数(仅保留总单量累计)(0.3.284 → 0.3.285)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:trend points 每项由 { label, created_count, pack_count } 改为 { label, created_count },移除打包数(打包数口径与总单量不同源、易引起误解);created_count 保持总单量按订单创建时间落桶后按小时累计(与 fulfillment.total 同口径),max 仅按 created_count 峰值。", + "代码依据:app/service/systems/warehouse_panel.js#queryTrend(删除 pack 查询与 pack_count 落桶/累计;签名移除 warehouseId);ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 移除 pack_count 描述);根版本 0.3.284 → 0.3.285、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.284", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData trend 补充 total 总单量字段(与 fulfillment.total 同口径)(0.3.283 → 0.3.284)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:trend 响应由 { max, points } 补充为 { max, total, points },total=今日总单量(与 fulfillment.total 同口径:待处理订单池 + 配送表今日出库;fulfillment 块失败时兜底 0)。", + "代码依据:app/service/systems/warehouse_panel.js#buildPanelData(组装数据时把 fulfillment.total 挂到 trend.total);ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 补 total 字段);根版本 0.3.283 → 0.3.284、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.283", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData trend 双值改按小时累计(订单数/打包数累加,最后一点=全天总数)(0.3.282 → 0.3.283)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:trend 的 created_count/pack_count 由每小时独立计数改为按小时累计(前缀和,每点为截至该小时结束的累计总数,最后一点=全天总数);max 取累计峰值上取整。", + "代码依据:app/service/systems/warehouse_panel.js#queryTrend(落桶后前缀和累计);ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 补累计口径);根版本 0.3.282 → 0.3.283、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.282", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData trend 改业务日 24 点双值(created_count/pack_count),label 从仓库自然日开始时间起(0.3.281 → 0.3.282)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:trend 由固定 08:00-18:00 共 11 点单值(value)改为业务日 24 点双值——points 每项 { label, created_count, pack_count },label 从仓库自然日开始时间(day_start_time,默认 06:00)起每小时一点到次日自然日开始时间(共 24 点);created_count=订单创建时间落桶(自然日零点起统计、全部订单仅排除已取消,早于自然日开始时间的并入第一点);pack_count=打包订单数按打包任务创建时间落桶(pack_mode=2 按 pack_quantity 求和 + 散单每任务 1 单,非异常未删除,与打包卡 today 同口径);max 取双值峰值上取整。", + "代码依据:app/service/systems/warehouse_panel.js#queryTrend(重写,签名改 (currentModel, warehouseId, todayStart, tomorrowStart),移除 TREND_HOURS 常量;buildPanelData 传 businessStart/businessEnd);ESLint 0 错误;egg 直调验证 24 点 label 从 06:00 到次日 05:00、每点双值结构正确。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(response.data.description 与 notes 补 trend 双值口径);根版本 0.3.281 → 0.3.282、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.281", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData stageOverview 打包卡 today 改今日打包订单数(与 fulfillment 已打包同口径),替代今日任务数(0.3.280 → 0.3.281)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:stageOverview 打包卡 today 由今日创建打包任务数(PackTask create_time 窗口 count)改为今日打包任务订单数(SUM(CASE WHEN pack_mode=2 THEN pack_quantity ELSE 1 END),窗口内非异常未删除,与 fulfillment 已打包一致);doing(打包中任务数)/abnormal(异常任务数)保持任务维度。", + "原因:用户反馈 pack 卡数据错误——today 显示任务数(1928)与已打包订单数(12718)不一致,且与拣货/复核卡 today(订单数口径)不统一。", + "代码依据:app/service/systems/warehouse_panel.js#queryStageOverview(packToday 改 countSql 订单数统计);ESLint 0 错误;egg 直调 VERIFY_OK。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(notes 补 pack 卡 today 口径);根版本 0.3.280 → 0.3.281、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.280", + "date": "2026-10-11", + "type": "updated", + "summary": "stock.check 盘点范围排除无头库位(所属 zone 不存在/已删除的库位不纳入盘点明细生成与作业视图库位枚举)(0.3.279 → 0.3.280)", + "methods": [ + "stock.check.addDetail", + "stock.check.addLocationDetail", + "stock.check.patternCreate", + "stock.check.workData" + ], + "notes": [ + "变更内容:无头库位(wms_location_space.zone_id 指向的 wms_location_zone 行不存在或已软删)一律不纳入盘点——①addDetail 商品路径仅按有效库位拆行(wms_storage 加 space_id IN 有效库位子查询,启用库存全部在无头库位的商品计入 invalid_stock_ids);②库位编码/ID 路径把无头库位分别计入 invalid_locations/invalid_location_ids(不报错,与不存在同口径);③type=all 全盘自动范围直接排除无头库位;④patternCreate 空库位定式收集 SQL 加 JOIN wms_location_zone 排除无头库位;⑤workData goods/space 视图库位枚举与明细生成同口径过滤。", + "代码依据:app/service/systems/stock_check.js#VALID_SPACE_SQL(新增模块常量,wms_location_space JOIN wms_location_zone deleted_at IS NULL;应用于 _addGoodsDetailRows/_buildGoodsWorkRows/_buildSpaceWorkRows 的 storage 查询与 addDetail 全盘自动拉取;_addLocationDetailRows/_addLocationRowsByIds 的 LocationSpace 查询加 include zone required:true)+ app/service/systems/stock_check_patterns.js#collectEmptyLocation(SQL 加 JOIN zone)。", + "回归测试:新增 2 用例(无头库位编码计入 invalid_locations 不入库、无头库位 ID 计入 invalid_location_ids 不入库,fixture 直接建 zone_id 不存在的库位并 force 清理);全盘自动范围/空间视图/多库位等既有用例的测试口径同步为有效库位过滤(fetchStockRows/fetchSpaceStockPairs/多库位用例/排序用例改 fetchSpaceStockPairs),stock_check 全量 237 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 4 条 method(stock.check.addDetail:description/response 无效列表/notes 补无头库位口径;stock.check.addLocationDetail:description 补无头库位记入 invalid_location_ids;stock.check.patternCreate:空库位定式口径与 goods 拆行口径补排除无头库位;stock.check.workData:三视图口径补库位枚举排除无头库位);根版本 0.3.279 → 0.3.280、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "0.3.279", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData 拣货块汇总改订单表状态口径:团购+散单拣货数=已拣货(池内 pick fin + 配送表今日出库 pick fin,按 wave_scope 1/3 分团购),替代今日任务快照(0.3.278 → 0.3.279)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:groupPicking/scatterPicking 的汇总 orders/goods/sku/wave 由今日创建任务快照(wave_pick_task order_count/wave_count + 任务订单关联表)改为订单表状态口径——池内 pick_status=fin + 配送表今日出库 pick fin,团购=wave_scope IN (1,3)、散单=NOT IN (1,3);团购+散单严格等于 fulfillment 已拣货;top 按人排行保持任务口径(订单表无拣货人)。", + "原因:用户反馈团购拣货数+散单拣货数(7372)小于已拣货数(11809),任务快照(创建时抓单数)偏小且部分订单不建任务。生产核算:池内 pick fin 按 wave_scope 拆分 团购 10883 + 散单 926 = 11809 = 已拣货 ✓。", + "代码依据:app/service/systems/warehouse_panel.js#queryPickingBlock(签名 pickModes→isGroup,summary 改双表订单状态 SQL:step/outbound/status/pick_status/wave_scope 条件,goods/sku=SUM(items_total/items_count)、wave=去重 wave_id;top 与 queryPickingGoodsSku 保持任务口径);ESLint 0 错误;egg 直调 VERIFY_OK(开发库 团购 13280 / 散单 146)。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(notes 口径);根版本 0.3.278 → 0.3.279、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.278", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData 已分配/已打印改订单表状态口径:池内 fin + 配送表今日出库 fin(与已拣货同口径,保证已分配≥已打印≥已拣货的流程约束),替代今日新建运单数/今日打印记录数(0.3.277 → 0.3.278)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:fulfillment 已分配由今日新建运单数(wms_order_express 按 order_id 去重)改为订单表状态口径(池内 post_status=fin + 配送表今日出库 post fin);已打印由今日打印记录订单数(wms_print_record order_ids)改为订单表状态口径(池内 print_status=fin + 配送表今日出库 print fin);与已拣货状态口径统一,保证已分配≥已打印≥已拣货。", + "原因:今日作业口径下已打印(4003)< 已拣货(10947)、已分配(12621)与已打印大小关系亦不稳定,用户要求分配/打印/拣货都从订单表获取。生产核算(池内):post fin 14933 ≥ print fin 12816 ≥ pick fin 11597 ✓;配送窗口当前 0。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(todayAllocOrdersPromise/todayPrintOrdersPromise 改为双表状态 count,与 todayPickOrdersPromise 同构);ESLint 0 错误;egg 直调 VERIFY_OK。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(notes 口径);根版本 0.3.277 → 0.3.278、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.277", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData 已拣货改为状态口径:池内 pick_status=fin + 配送表今日出库 pick fin(状态无跨天错位,已拣 ≥ 已复核),替代今日拣货任务订单数快照(0.3.276 → 0.3.277)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:fulfillment 已拣货与 stageOverview 拣货卡 today 由今日拣货任务订单数(wave_pick_task order_count 快照,偏小)改为订单状态口径——池内 pick_status=fin + 配送表今日出库 pick fin;生产核实:状态口径已拣 10947 > 今日复核 9192(今日复核订单全部 pick_status=fin),而任务快照 6098 < 复核 9192 明显不合理(复核必先拣货)。其余环节保持 0.3.276 口径。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(todayPickOrdersPromise 双表 pick fin count)/#queryStageOverview(pickToday 同步);ESLint 0 错误;egg 直调两处 VERIFY_OK。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData(notes 口径);根版本 0.3.276 → 0.3.277、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.276", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData 履约链路各环节已* 统一改为今日作业口径:已分配=今日新建运单、已打印=今日打印记录、已拣货=今日拣货任务、已复核=今日复核、已打包=今日打包任务、已出库=今日出库(与打包块一致,消除状态口径跨天错位)(0.3.275 → 0.3.276)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:fulfillment 各环节已* 由「池内 fin + 配送表今日出库 fin」改为今日作业口径——已分配=wms_order_express 今日 create_at 未删除按 order_id 去重;已打印=wms_print_record 今日 type=express 的 data.order_ids 长度求和(面单打印记录无 order_id 列,data JSON 含 order_ids 数组);已拣货=wms_wave_pick_task 今日 order_count 合计(全部 pick_mode);已复核=订单分表 recheck_time 今日双表;已打包=今日打包任务订单数(保持);已出库=配送表今日出库(保持)。未* 保持真实状态口径(池内未完成+配送表未完成)。stageOverview 同步:拣货卡 today 改今日拣货任务订单数(与已拣货一致)、复核卡 today 改 recheck_time 今日双表(与已复核一致)。", + "原因:用户反馈团购拣货+散单拣货(3869)比已拣货(8265)少 4396——已拣货状态口径含昨日拣完未出库的池内订单(8440),与今日作业口径天然错位;按打包一致处理并扩展到打印/分配/复核。", + "生产核算(窗口 UTC 10-10 22:00 起):已分配 12621、已打印 4003(1073 记录 order_ids 合计)、已拣货 3869、已复核 6789、已打包 4397、已出库 0(当天尚未出库)。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(新增 todayAllocOrdersPromise/todayPrintOrdersPromise/todayPickOrdersPromise/todayRecheckOrdersPromise,stageCounts 内 doneTodayMap 按环节字段映射今日作业数);ESLint 0 错误;egg 直调 VERIFY_OK。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData(notes 口径);根版本 0.3.275 → 0.3.276、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.275", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData 拣货块 goods/sku 补无关联任务:pick_mode=1 团购任务无 wms_wave_pick_task_order 关联记录导致商品数漏算,改为无关联任务按 wave_id 从订单分表统计(0.3.274 → 0.3.275)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:queryPickingGoodsSku 的 goods/sku 统计改为 UNION 两段——有 wms_wave_pick_task_order 关联的任务走 pto 精确统计;无关联的任务(实测 pick_mode=1 共 60 任务 3862 单 963 波全部无 pto 记录,导致 top 如黎英俊 goods=0)按 wave_id 从订单分表(current/dispatch,status!=cancel)统计波次订单商品;总量与 top 同步。", + "核实过程:生产只读窗口内任务 401 个,仅 341 个有 pto 关联;无关联任务全为 pick_mode=1(60 个、orders 快照 3862、waves 963),配送表按 wave join 补数 goods=473/sku=336(current 表另有未出库部分)。orders 快照口径不受影响(与 fulfillment 已拣货 19062 基本一致)。", + "代码依据:app/service/systems/warehouse_panel.js#queryPickingGoodsSku(goodsSkuSelect/topGoodsSkuSelect 改为 UNION ALL 双段,taskWindowWhere2 别名替换);ESLint 0 错误;egg 直调拣货块 VERIFY_OK。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData(notes 口径);根版本 0.3.274 → 0.3.275、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.274", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData 小团购归回团购块:groupPacking 范围由 wave_scope=1 改为 IN (1,3)(大团购+小团购,top 按打包台),scatterPacking=NOT IN (1,3);orders 保持按 pack_mode 统计(0.3.273 → 0.3.274)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:groupPacking(团购块)波次范围由 wave_scope=1 改为 wave_scope IN (1,3),小团购(3)从散单块归回团购块(top 仍按打包台聚合);scatterPacking(散单块)= wave_scope NOT IN (1,3)(0 未分配/2 散单/4 单品单件,top 按打包员);orders 口径不变(pack_mode=2 按 pack_quantity 求和、pack_mode=1 每任务 1 单)。", + "生产核算(窗口内):团购块=wave_scope 1+3 共 1161 任务/17387 单,散单块=2+4 共 1471 任务/1471 单,合计 18858,与今日出库已打包 18652 仅差约 200(今日打包未出库)✓。", + "代码依据:app/service/systems/warehouse_panel.js#queryPackingBlock(scopeWhere 改为 IN (1,3) / NOT IN (1,3));ESLint 0 错误;egg 直调 VERIFY_OK。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData(notes 口径);根版本 0.3.273 → 0.3.274、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.273", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData 打包订单数修正 wave_scope=3 小团购:orders 改为按打包模式统计(pack_mode=2 按 pack_quantity 求和 + 散单每任务 1 单),小团购任务不再按 1 单漏算(修正前今日打包 15997,修正后 18847,缺口 2850)(0.3.272 → 0.3.273)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:groupPacking/scatterPacking 与 fulfillment 已打包的订单数口径由「wave_scope=1 SUM(pack_quantity) + 其余每任务 1 单」改为「pack_mode=2(团购模式)按 pack_quantity 求和 + pack_mode=1 散单每任务 1 单」——wave_scope=3(小团购)的打包任务是团购模式(pack_mode=2、pack_quantity=多单),此前按散单每任务 1 单漏算(订单 1032238 日志:小团购波次 B2026101000155 共 12 单按 1 单统计)。", + "核实过程:生产只读 wave_scope 分布(窗口内)1=244/2=1173/3=917/4=298,修正前订单数 15997(13654+2343),修正后 18847(13654+1173+3715+298);今日出库已打包 18652,差距由 2655 收敛到约 195(今日打包未出库),三个口径基本自洽。", + "代码依据:app/service/systems/warehouse_panel.js#queryPackingBlock(ordersExpr 统一 SUM(CASE WHEN pack_mode=2 THEN pack_quantity ELSE 1 END),summary 与两块 top 同步)/#queryFulfillment(packTaskOrdersTodayPromise SQL 同口径);ESLint 0 错误;egg 直调 VERIFY_OK。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData(notes 口径);根版本 0.3.272 → 0.3.273、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.272", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData 未打包恢复真实状态口径:未*=池内未打包 + 配送表今日出库未打包(替代 total-已*),与只读核实口径一致(169+458=627);已*仍为今日打包任务数(0.3.271 → 0.3.272)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:fulfillment 打包环节未* 由 total-已* 改回真实状态口径——常用表池内 pack 非 fin + 配送表今日出库 pack 非 fin(与只读核实一致:待处理表 169 + 配送表 458 = 627);已* 保持今日打包任务订单数;未+已 不再强制等于 total(差额为昨日打包今日出库的跨天订单)。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(items 组装移除打包环节 undone=finalTotal-done 特判,恢复 stageCounts 真实 undone=池内非fin+配送非fin);ESLint 0 错误;临时验证脚本(非 pack 环节 undone+done=total 断言)通过。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData(notes 口径);根版本 0.3.271 → 0.3.272、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.271", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData 修复 stageOverview 解构错位:0.3.269 拣货卡双表求和插入时残留旧任务数 countSql 导致数组多一个元素,后续字段全部错位(pick.doing 错显已拣货数、pick.abnormal 错显拣货中任务数、pack.today 错显复核异常数)(0.3.270 → 0.3.271)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:queryStageOverview 的 Promise.all 数组移除残留的旧拣货任务数 countSql(今日完成拣货任务数),仅保留双表 pick fin 求和作为 pick.today;数组恢复 15 元素与解构一一对应。修复后 pick.today=已拣货订单数(与 fulfillment 同口径)、pick.doing=拣货中任务数、pick.abnormal=池内拣货异常、pack.today=今日打包任务数。", + "代码依据:app/service/systems/warehouse_panel.js#queryStageOverview(删除 pick 区域冗余 countSql);ESLint 0 错误;临时验证脚本(queryStageOverview 直调:pick.today=13414 订单数、doing/abnormal 任务数、与 queryFulfillment 已拣货相等断言)通过。", + "文档变更范围:methods/system.json 根版本 0.3.270 → 0.3.271、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位);接口描述与口径未变。" + ] + }, + { + "version": "0.3.270", + "date": "2026-10-11", + "type": "added", + "summary": "新增仓库配置「自然日开始时间」day_start_time(subject_config,HH:mm,默认 06:00):面板全部今日统计窗口改为业务日(昨日 06:00 后的订单视为今日;当前时间早于当日配置点窗口为昨日配置点→当日配置点,否则为当日→次日)", + "methods": [ + "index.getWarehousePanelData", + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "变更内容:wms_store.subject_config 新增 day_start_time(HH:mm,默认 06:00,范围 00:00-23:59),normalizeSubjectConfig 同步校验(格式非法报错、范围外回退默认、旧数据补默认);WAREHOUSE_SETTING_FIELDS 新增对应字段元信息(getFieldMeta 返回);面板 getWarehousePanelData 的今日统计窗口(fulfillment 配送表今日出库/今日打包任务/退件拆包、stageOverview 各 today、b2b、groupPicking/scatterPicking、groupPacking/scatterPacking)统一改为业务日窗口 [配置点, 次日配置点),当前时间早于当日配置点时窗口从昨日配置点开始;trend(08:00-18:00 小时趋势)与 weeklyEfficiency(7 日)保持自然日。", + "代码依据:app/model/store.js(DEFAULT_DAY_START_TIME/DAY_START_TIME_MIN/MAX + DEFAULT_SUBJECT_CONFIG.day_start_time + normalizeSubjectConfig 校验段);app/service/systems/setting/warehouse.js(WAREHOUSE_SETTING_FIELDS 新增 day_start_time);app/service/systems/warehouse_panel.js(新增 getWarehouseDayStartTime(读 subject_config,异常回退 06:00)与 resolveBusinessDayRange,buildPanelData 各块传 businessStart/businessEnd);ESLint 0 错误;临时验证:开发库仓库 100000 配置默认 06:00,当前 2026-10-11 00:19 窗口=[2026-10-10 06:00, 2026-10-11 06:00) 断言通过。", + "文档变更范围:methods/system.json 的 module=index 分组更新 index.getWarehousePanelData(notes 补业务日窗口口径)、module=setting.warehouse 分组更新 saveSettings(params 新增 subject_config.day_start_time)与 getFieldMeta(response 新增 data[].day_start_time);根版本 0.3.269 → 0.3.270、updatedAt 2026-10-10 → 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.269", + "date": "2026-10-10", + "type": "updated", + "summary": "index.getWarehousePanelData 未打包合并配送数据 + 拣货卡对齐:打包环节未*=总数-已*(配送表今日出库未打包/跨天错位并入未*,恢复每环节未+已=total);stageOverview 拣货卡 today 与 fulfillment 已拣货同口径(订单数)(0.3.268 → 0.3.269)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容一:fulfillment 打包环节未* 改为 total - 已*(已*=今日打包任务订单数),配送表今日出库中未打包单与跨天打包出库错位部分全部并入未打包,恢复每环节未+已=total;此前未*=池内未打包+配送表非 fin,未包含跨天错位部分,用户反馈未打包没有合并统计配送数据。", + "变更内容二:stageOverview 拣货卡 today 由今日完成拣货任务数(任务维度,团购一任务几十单导致 401 与已拣货 19068 严重不一致)改为与 fulfillment 已拣货同口径:常用表池内 pick_status=fin + 配送表今日出库 pick fin(订单数)。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(items 组装时打包环节 undone=Math.max(finalTotal-done,0))/#queryStageOverview(pickToday 改为双表 pick fin Promise.all 求和,替换原 wave_pick_task 任务数 countSql);ESLint 0 错误;临时验证脚本 6 环节 undone+done=total 断言全部通过。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(notes 同步打包环节未* 与拣货卡口径);根版本 0.3.268 → 0.3.269、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.268", + "date": "2026-10-10", + "type": "updated", + "summary": "index.getWarehousePanelData 已打包口径对齐打包任务:打包环节已* 由配送表今日出库 pack_status=fin 叠加改为今日打包任务订单数(团购 SUM(pack_quantity)+散单任务数,与 groupPacking/scatterPacking 严格一致,消除跨天打包出库窗口错位)(0.3.267 → 0.3.268)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:fulfillment 打包环节已* = 常用表池内 pack_status=fin + 今日打包任务订单数(wms_pack_task 今日创建、非异常、未删除:wave_scope=1 按 pack_quantity 求和 + 其余每任务 1 单,与 groupPacking/scatterPacking 同一口径);不再叠加配送表今日出库 pack_status=fin(昨日打包今日出库的订单不计入今日已打包)。未打包口径不变(池内 pack 非 fin + 配送表今日出库 pack 非 fin 的拦截等单)。其余五环节仍按配送表今日出库状态拆分叠加。", + "核实过程:生产只读(1000028,UTC 今日)池内 pack fin=0、配送表今日出库 pack fin=17005、今日打包任务订单数=14827,差距 2178 为跨天打包出库窗口错位(昨日打包今日出库 − 今日打包未出库),因此已打包对齐打包任务口径后与 groupPacking+scatterPacking(12924+1885≈14827 北京窗口)一致。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(新增 packTaskOrdersTodayPromise 原生 SQL:SUM(CASE WHEN wave_scope=1 THEN pack_quantity ELSE 1 END) 今日窗口;stageCounts 内 pack_status 环节 done 叠加改用该值);ESLint 0 错误;临时验证脚本(非 pack 环节 undone+done=total 断言)通过。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response.data/notes 同步打包环节口径);根版本 0.3.267 → 0.3.268、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.267", + "date": "2026-10-10", + "type": "updated", + "summary": "index.getWarehousePanelData fulfillment 配送表补数按环节状态拆分:今日出库订单状态 fin 计入已*、非 fin 计入未*(未打包即出库的拦截单不再计入已打包,避免已打包虚高且大于团购+散单打包数)(0.3.266 → 0.3.267)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:fulfillment 各环节配送分表今日出库订单(status 非 cancel、outbound_status=fin、delivery_time 今日、dispatch_lane m4/m5)由无条件叠加已* 改为按环节状态字段拆分——状态 fin 计入已*,非 fin 计入未*(打包环节的拦截等未打包即出库单计入未打包);保证每环节未+已=total 且与真实状态一致,已打包不再虚高。", + "根因:配送表今日出库中约 9%(1735/18593)pack_status 非 fin(拦截等特殊路径未打包即出库),无条件叠加导致已打包(18564)远大于团购打包数+散单打包数(14743);其余环节(post/print/pick/recheck)配送表今日出库订单状态均为 fin,拆分后与旧口径一致。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(stageCounts 每环节四元组:undoneCurrent/doneCurrent/dispatchFin/dispatchTodayOutbound,undone=池内非fin+配送表非fin、done=池内fin+配送表fin);ESLint 0 错误;临时验证脚本每环节 undone+done=total 断言通过;生产只读验证:配送表今日出库 18593,pack_fin=16858、pack_not_fin=1735,其余环节全 fin。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response.data/notes 同步拆分口径);根版本 0.3.266 → 0.3.267、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.266", + "date": "2026-10-10", + "type": "updated", + "summary": "index.getWarehousePanelData groupPacking 订单数修正:orders 由任务数(COUNT(*))改为打包数量快照求和 SUM(pack_quantity)(团购一任务一波次,任务数会严重低估订单数);scatterPacking 保持任务数(0.3.265 → 0.3.266)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:groupPacking 的 orders(summary 与 top 均)由 COUNT(*)(任务数)改为 COALESCE(SUM(pt.pack_quantity),0)——pack_quantity 是创建打包任务时服务端复查落库的波次订单数快照(workbench._packOrder:团购取波次实时订单数,散单默认 1),一任务一波次,任务数口径会把订单数低估为波次数(218 任务显示 218 单);scatterPacking 散单一单一任务,orders 保持 COUNT(*)。", + "代码依据:app/service/systems/warehouse_panel.js#queryPackingBlock(ordersExpr 按 isGroup 分支:团购 SUM(pack_quantity)/散单 COUNT(*);summary 与团购 top 同步替换);ESLint 0 错误;生产只读验证:今日团购任务 220、orders=SUM(pack_quantity)=12743、wave=220。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(notes 补 groupPacking/scatterPacking orders 口径);根版本 0.3.265 → 0.3.266、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.265", + "date": "2026-10-10", + "type": "updated", + "summary": "index.getWarehousePanelData fulfillment 全环节补配送表:已出库订单迁移到配送分表后,各环节 done 与 total 统一叠加配送表今日出库订单(出库即视为走完前序环节,每环节未+已=total);stageOverview.todayOutbound 同步双表(0.3.264 → 0.3.265)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:fulfillment 的各环节 done(已分配/已打印/已拣货/已复核/已打包/已出库)与 total 在常用分表作业池基础上统一叠加配送分表(wms_order_delivery_{仓库}_dispatch)今日出库订单(status 非 cancel、outbound_status=fin、delivery_time 今日、dispatch_lane m4/m5;已出库即视为走完前序环节),保证每环节未+已=total;stageOverview 的 todayOutbound 同步双表求和(常用表 step=4 今日出库 + 配送表今日出库),totalOrders=待处理+今日出库口径不再偏小。迭代记录:首版仅出库环节与 total 补数,用户反馈五环节已* 未核算已出库部分,改为全环节统一叠加。", + "口径说明:配送表今日出库订单中有少量(约 17%)pack_status 非 fin(拦截等特殊路径未打包即出库),按看板口径仍计入各环节已*(出库即视为走完前序环节),以保持每环节未+已=total 一致。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(dispatchTodayBase 配送表今日出库过滤;stageCounts 每环节 done=常用表 fin + 配送表今日出库数,total=常用表待处理 + 配送表今日出库)/#queryStageOverview(todayOutbound 双表 Promise.all 求和);buildPanelData 调用处传入 dispatchModel;ESLint 0 错误;临时验证脚本断言每环节 undone+done=total 通过;生产只读验证:1000028 常用表 pending 3188 + 配送表今日出库 16000 = 19188。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response.data/notes 同步配送表补数口径);根版本 0.3.264 → 0.3.265、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.264", + "date": "2026-10-10", + "type": "updated", + "summary": "index.getWarehousePanelData 打包数据区分团购/散单:packingRank 拆分为 groupPacking(wave_scope=1,top 按打包台)与 scatterPacking(其余,top 按打包员)两块(0.3.263 → 0.3.264)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:原 packingRank(散单+团购合并)拆分为两个数据块——groupPacking(pack_task.wave_scope=1 大团购,top 按打包台 wms_workbench.name 聚合,workbench_id 为空归「未指定打包台」)与 scatterPacking(wave_scope 非 1:0 未分配波次/2 散单/3 小团购/4 单品单件,top 按打包员 pack_task_packer.account_name 聚合),每块含 orders/goods/sku/wave/top5(口径不变:今日创建、非异常、未删除);顶层 packingRank 字段移除。迭代记录:区分字段曾先按 pack_mode(废弃语义)实现,后改 wave_scope(先 IN(1,3),用户最终确认 3 归散单、仅 1 为团购);top 口径曾统一按打包员,用户要求团购按打包台、散单按个人。", + "代码依据:app/service/systems/warehouse_panel.js#queryPackingPersonal 改为 queryPackingBlock(isGroup 布尔参数,SQL 拼 pt.wave_scope = 1 / != 1;top 查询按 isGroup 分支:团购 LEFT JOIN wms_workbench 按打包台聚合、散单 JOIN wms_pack_task_packer 按打包员聚合);buildPanelData 并行聚合两块(groupPacking/scatterPacking,各自单块容错),data 输出同步替换;ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response.data/notes 同步打包两块口径);根版本 0.3.263 → 0.3.264、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.263", + "date": "2026-10-10", + "type": "updated", + "summary": "index.getWarehousePanelData fulfillment 新增今日退回收件数与今日拆包件数(追加在 items 数组末尾两项,按 wms_return_received / wms_return_unpack 的 created_at 今日计数;wms_return_unpack 补 (warehouse_id, created_at) 索引)(0.3.262 → 0.3.263)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:fulfillment 数据块的 items 数组在 6 环节未/已 12 项之后追加两项——label 今日退回收件 / 今日拆包(icon=returnReceived/returnUnpack,与环节项同构 label/icon/value),口径为按 warehouse_id 隔离 + created_at 落在今日 [00:00, 次日 00:00) 的计数(wms_return_received / wms_return_unpack);wms_return_received 已有 idx_warehouse_created_at,wms_return_unpack 无 created_at 索引,新增迁移 20261010100000-add-created-at-index-to-wms-return-unpack.js(addIndex (warehouse_id, created_at),模型 indexes 同步,开发库已执行核验,生产随发布执行)。", + "代码依据:app/service/systems/warehouse_panel.js#queryFulfillment(新增 ReturnReceived/ReturnUnpack 两个 count,结果追加到 items 末尾,buildPanelData 调用处传入 warehouseId/todayStart/tomorrowStart);app/model/return_unpack.js(indexes 增加 idx_warehouse_created_at);ESLint 0 错误;临时验证脚本真实库直调 VERIFY_OK(items=14 项、末两项 label 正确、顶层无新增字段)。迭代记录:首版把两个计数放在 fulfillment 顶层字段(returnReceivedToday/returnUnpackToday),用户纠正为追加到 items 数组(与环节项同构)。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response.data/notes 补充 fulfillment items 末尾两项口径);根版本 0.3.262 → 0.3.263、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.262", + "date": "2026-10-10", + "type": "updated", + "summary": "stock.check.result 无作业记录时返回明细范围行(盘点前/待提交后台查看明细专用,不再作为盘点作业数据提供)(0.3.261 → 0.3.262)", + "methods": [ + "stock.check.result" + ], + "notes": [ + "变更内容:result 在无作业记录(如待提交/盘点前)时 rows 直接返回 wms_stock_check_detail 明细范围行(原始行,不聚合),total=明细行数——本接口仅展示盘点前/盘点后后台查看明细使用,不再作为盘点作业数据提供(盘点作业数据见 stock.check.workData);有作业记录时保持原聚合口径不变(商品范围按商品合并、库位范围按库位行)。", + "代码依据:app/service/systems/stock_check.js#result(records.length===0 分支直接返回明细行);回归测试调整 3 用例(盘点前/待提交两用例新断言明细范围行口径;addDetail 与 recordDelete 用例同步改为断言明细范围行),stock_check 全量 235 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.result 一条(description/response.rows/notes 补充无作业记录时返回明细范围行口径);根版本 0.3.261 → 0.3.262、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 24 条 method 未改动(stock.check 分组仍为 25 条)。" + ] + }, + { + "version": "0.3.261", + "date": "2026-10-10", + "type": "added", + "summary": "新增 stock.check.exportDetail 盘点明细导出接口(异步,按盘点范围分流:商品盘点固定两 sheet——汇总和差异 + 库位/数量/条码/商品名称;库位盘点简化)", + "methods": [ + "stock.check.exportDetail" + ], + "notes": [ + "接口:stock.check.exportDetail,入参 id(盘点任务ID,必填);异步执行,立即返回 task_id,进度查询复用 stock.check.exportTaskProgress。", + "商品盘点固定两个 Sheet:Sheet1「汇总和差异」每商品一行(盘点单号/商品编码/商品名称/规格/账面数量(明细行 system_quantity 快照合计,提交审核时刷新)/盘点数量/差异数量/差异类型(盘盈|盘亏,无差异或未盘留空);未知商品追加在末尾(无账面、差异=实盘=盘盈);Sheet2「库位明细」每商品每库位一行(库位编码/数量(实盘,未盘 0)/条码(wms_stock_barcodes 第一条)/商品名称)。", + "库位盘点:Sheet「盘点明细」作业记录口径(库位编码/商品编码/商品名称/盘点数量),未知商品编码=扫描条码、空库位标记商品为空数量 0。", + "迭代记录:首版按 mode 二选一(location 单 sheet / summary 两 sheet),用户纠正为商品盘点固定两 sheet(汇总和差异 + 库位明细精简列),mode 入参已移除;随后纠正「库位明细」按作业记录(wms_stock_check_record)一行一条实际盘点记录导出(不再按快照库位展开/合并无库位组);补充库位编码列显示覆盖(custom_name → custom_barcode → space_code);最后汇总和差异 sheet 增加「条码」列(wms_stock_barcodes 第一条,未知商品商品编码列即扫描条码、条码列留空)。", + "代码依据:app/service/systems/stock_check.js#exportCheckDetail/#_generateAndUploadCheckDetailExcel(商品范围复用 result 的商品合并聚合;新增 StockBarcode 条码查询)/#_uploadExportExcelFile(原 _generateAndUploadStockCheckExcel 上传段抽为公共方法,两处导出一致复用)+ app/service/systemMethods/stock/check.js#exportDetail(ALL_METHOD_NAMES/_noNeedLog 已加入);回归测试 3 用例(商品两 sheet 回读断言/库位任务/方法层异步轮询至 success),stock_check 全量 235 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.exportDetail 一条(位于 stock.check.export 之后,分组由 24 条增至 25 条);根版本 0.3.260 → 0.3.261、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 24 条 method 未改动。" + ] + }, + { + "version": "0.3.260", + "date": "2026-10-10", + "type": "updated", + "summary": "stock.check.submit 商品范围任务提交审核时刷新明细行账面快照(提交即快照,提交时点账面;不新增表、主表不额外写快照)(0.3.259 → 0.3.260)", + "methods": [ + "stock.check.submit" + ], + "notes": [ + "变更内容:商品范围任务(scope_type=goods)提交审核时把各明细行 system_quantity 刷新为该库位当时账面 SUM(available_quantity+locked_quantity)(库存记录不存在按 0),保证 result/差异对比使用提交时点的账面(添加明细到提交之间库存变动以提交时点为准,与 result 商品范围聚合的库位账面快照同源);明细表本身已按「商品+库位」完整记录快照,主表不额外写快照(scope_snapshot 保持 null);快照失败则提交失败(提交即快照);驳回(rejected)后重新提交会重新刷新;库位范围任务(scope_type=location)账面实时查 wms_storage,不处理。", + "存储方案:无需新表、无迁移——明细表已有 system_quantity 快照列(按「商品+库位」拆行),提交时直接刷新即可。", + "代码依据:app/service/systems/stock_check.js#submit(缺库位校验后、置 submitted 前调用)/#_refreshGoodsBookSnapshotOnSubmit(新增);回归测试两用例(商品任务提交后明细行快照刷新为提交时账面、主表 scope_snapshot 保持 null,库存临时 +100 后 finally 恢复;库位范围任务提交明细行 system_quantity 保持 0),stock_check 全量 231 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.submit 一条(description/notes 补提交时刷新明细行账面快照语义);根版本 0.3.259 → 0.3.260、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 23 条 method 未改动(stock.check 分组仍为 24 条)。" + ] + }, + { + "version": "0.3.259", + "date": "2026-10-10", + "type": "updated", + "summary": "stock.check.result 商品范围按商品聚合输出(一个商品一行,多个库位明细行合并),行内 locations 输出各库位账面快照与实盘;主表计数同步商品口径(0.3.258 → 0.3.259)", + "methods": [ + "stock.check.result", + "stock.check.detail" + ], + "notes": [ + "变更内容:按商品盘点(scope_type=goods)不再按库位拆行输出——result 商品范围按 stock_id 合并(一行一商品),行含 system_quantity(账面快照合计=各库位明细行 system_quantity 之和,创建明细时落库=盘点时做快照)与 locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }]:system_quantity 为该库位账面快照、quantity 为该库位实盘合计(未盘为 0),仅作业记录存在而快照不存在的库位追加在末尾且 system_quantity=0);行级 checked_quantity/diff_quantity/is_diff/status 按合并后的商品口径计算;主表计数 total_items/checked_items/diff_items 响应口径以聚合行为准(total_items=行数、checked_items=已盘行数、diff_items=差异行数)。", + "同步改动:主表 total_items 商品范围改为按商品计数(addDetail/detailDelete/patternCreate/_countScopeSummary);_recalcCheckSummary 的 checked_items/diff_items 与 finish/_calcQuantityDiffSummary 的盘盈盘亏汇总(detail profit/loss 同口径)均改为商品范围按商品聚合;detail 描述同步。", + "代码依据:app/service/systems/stock_check.js#result/#_buildDetailAggregations(新增 _formatMergedGoodsAggregationRow 商品合并格式化器,_formatDetailAggregationRow 仅保留库位行)、#_countScopeSummary(新增)、#_recalcCheckSummary、#finish、#_calcQuantityDiffSummary;回归测试新增「多库位商品合并为一行」用例(全部库位上报、差异=实盘合计-账面快照合计),stock_check 全量 229 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.result(description/response.rows/notes 同步商品范围合并口径)与 stock.check.detail(description 盘盈盘亏口径短语同步)两条;根版本 0.3.258 → 0.3.259、updatedAt 2026-10-09 → 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组仍为 24 条)。" + ] + }, + { + "version": "0.3.258", + "date": "2026-10-09", + "type": "updated", + "summary": "stock.check.workData / workDataSpaceDetails 空间视图库位排序修正:仅按库位拣货顺序 pick_sequence 升序排序,pick_priority 与库位 id 均不参与(同值保持库位查询顺序)(0.3.257 → 0.3.258)", + "methods": [ + "stock.check.workData", + "stock.check.workDataSpaceDetails" + ], + "notes": [ + "变更内容:space 视图库位排序在 0.3.257(对齐拣货模块 sort_by,pick_sequence 升序 + pick_priority 升序 + 库位 id 兜底)基础上修正为仅按库位拣货顺序排序——pick_sequence 升序,pick_priority 与库位 id 均不参与排序(同值保持库位查询顺序,依赖 Array.sort 稳定排序);行内 goods 排序与分页/过滤行为不变;goods 视图 locations 排序不受影响。", + "代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows(sortedLocations 比较函数简化为仅 pick_sequence 差值;两处 LocationSpace 查询 attributes 移除 pick_priority;JSDoc 与 workData 方法注释同步);回归测试排序用例改造为两阶段(pick_sequence 升序 + pick_priority 双向设置均不影响顺序),stock_check 全量 228 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataSpaceDetails 两条(description/notes 同步排序口径);根版本 0.3.257 → 0.3.258、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组仍为 24 条)。" + ] + }, + { + "version": "0.3.257", + "date": "2026-10-09", + "type": "updated", + "summary": "stock.check.workData / workDataSpaceDetails 空间视图库位排序对齐拣货模块:pick_priority 由降序改为升序(与拣货模块 sort_by [ pick_sequence, pick_priority, space_id, item_code ] 一致)(0.3.256 → 0.3.257)", + "methods": [ + "stock.check.workData", + "stock.check.workDataSpaceDetails" + ], + "notes": [ + "变更内容:space 视图库位排序规则由「pick_sequence 升序、pick_priority 降序、同值按库位 id 升序兜底」改为「pick_sequence 升序、pick_priority 升序、同值按库位 id 升序兜底」,与拣货模块(app/service/systems/pick.js sort_by 声明:[ pick_sequence, pick_priority, space_id, item_code ])排序规则一致,保证盘点作业顺序与拣货路径一致;goods 视图 locations 排序不受影响。", + "代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows(sortedLocations 比较函数 priorityDiff 改为 left - right 升序;JSDoc 与 workData 方法注释同步);回归测试新增 space 视图排序用例(pick_sequence 升序 + pick_priority 升序两阶段断言,旧降序实现下第二阶段会失败),stock_check 全量 228 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataSpaceDetails 两条(description/notes 同步排序口径);根版本 0.3.256 → 0.3.257、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组仍为 24 条)。" + ] + }, + { + "version": "0.3.256", + "date": "2026-10-09", + "type": "updated", + "summary": "index.getWarehousePanelData is_change=false 时返回空 data 节约流量(传入时间戳未过期时不查库不输出数据;is_change=true 时仍优先输出缓存数据)(0.3.255 → 0.3.256)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "代码依据:app/service/systems/warehouse_panel.js#getPanelData(缓存有最后更新时间时先算 isChange,false 直接返回 { is_change: false, last_change_at, data: {} } 不查库;true 时缓存有 data 直出、无 data 查库补数据保留外部时间戳;无最后更新时间仍查库+设置);app/service/systemMethods/index.js 注释同步;ESLint 0 错误;临时验证脚本 17 用例全 PASS(新增未变化空 data 不查库用例)。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(description/response.data/notes 同步空 data 语义);根版本 0.3.255 → 0.3.256、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.255", + "date": "2026-10-09", + "type": "updated", + "summary": "index.getWarehousePanelData 拉取逻辑改为外部驱动:缓存有最后更新时间且有数据直接输出;有最后时间无数据(外部只驱动时间戳)查库补数据并保留外部时间戳;无最后时间才查库并设置最后更新时间;缓存 TTL 10 秒 → 300 秒(0.3.254 → 0.3.255)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "代码依据:app/service/systems/warehouse_panel.js#getPanelData(三段式拉取逻辑:命中直出 / 有外部时间戳无数据查库补 data 保留外部 ts / 无时间戳查库+设置 nowTs;PANEL_CACHE_TTL_SECONDS=300);app/service/systemMethods/index.js 注释同步(force 仅影响 last_change_at 是否可缺省);ESLint 0 错误;临时验证脚本 16 用例全 PASS(新增外部驱动时间戳查库补数据用例,断言保留外部时间戳 1800000000 且写缓存值一致)。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response.is_change/last_change_at 描述与 notes 缓存语义同步外部驱动);根版本 0.3.254 → 0.3.255、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.254", + "date": "2026-10-09", + "type": "updated", + "summary": "index.getWarehousePanelData data 填充有数据源的字段(title/fulfillment/stageOverview/b2b/groupPicking/scatterPicking/packingRank.personal/trend/weeklyEfficiency.intercept),无数据源的字段暂不输出;缓存值升级为 { last_change_at, data }(TTL 10 秒,过期重算)(0.3.253 → 0.3.254)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "代码依据:新增 app/service/systems/warehouse_panel.js(WarehousePanelService:getPanelData 增量判定与缓存、buildPanelData 8 个数据块并行聚合且单块容错、queryFulfillment/queryStageOverview/queryB2b/queryPickingBlock/queryPickingGoodsSku/queryPackingPersonal/queryTrend/queryWeeklyIntercept);app/service/systemMethods/index.js#getWarehousePanelData 改为参数校验后调用 systems 层(原 getWarehousePanelLastChangeCacheKey 移入 systems 层);ESLint 0 错误;临时逻辑脚本 15 用例全 PASS;真实库(127.0.0.1:3307)只读 SQL 验证仓库 100000/1000028 共 90 条查询全部可执行。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response.data 描述补充已输出字段、notes 补充缓存语义/口径/未输出字段清单);根版本 0.3.253 → 0.3.254、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.253", + "date": "2026-10-09", + "type": "updated", + "summary": "index.getWarehousePanelData 响应新增 last_change_at(服务端最后更改时间戳,缓存未命中时为 0),供前端保存并作为下次轮询入参回传(0.3.252 → 0.3.253)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "代码依据:app/service/systemMethods/index.js#getWarehousePanelData(读取缓存后 cachedAt 有效时返回其值,否则返回 0;is_change 判定逻辑不变);ESLint 0 错误,临时验证脚本 13 用例全 PASS(新增 last_change_at 断言:命中缓存返回缓存值、未命中返回 0)。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(response 新增 last_change_at;description/notes 同步);根版本 0.3.252 → 0.3.253、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.252", + "date": "2026-10-09", + "type": "updated", + "summary": "index.getWarehousePanelData 新增 force 入参(可选):首次拉取传 true 时 is_change 强制为 true 且 last_change_at 可缺省(0.3.251 → 0.3.252)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "代码依据:app/service/systemMethods/index.js#getWarehousePanelData(force 解析兼容 true/'true'/1;force=true 时 last_change_at 缺省视为 0,传了仍做格式校验;is_change = force || (传入时间戳 < 缓存最后更改时间戳));ESLint 0 错误,临时验证脚本 13 用例全 PASS(含 force=true 缺省时间戳、force=1、force='true'、force=false 缺省时间戳仍报参数错误)。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组仅更新 index.getWarehousePanelData 一条(params 新增 force、last_change_at 的 required 由 true 改为 false 并同步说明;description/response/notes 同步);根版本 0.3.251 → 0.3.252、updatedAt 保持 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.251", + "date": "2026-10-09", + "type": "added", + "summary": "基础模块新增 index.getWarehousePanelData 仓库面板数据接口:按仓库增量变更检测,入参 last_change_at 小于缓存最后更改时间戳时返回 is_change=true,data 暂为空(0.3.250 → 0.3.251)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "代码依据:app/service/systemMethods/index.js#getWarehousePanelData + #getWarehousePanelLastChangeCacheKey;缓存键 index:warehousePanel:lastChangeAt:{warehouseId}(按仓库存储,通过 getCacheAsync 读取);需要登录(isNeedLogin=true),免权限/免鉴权/免系统日志,ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=index 基础模块分组新增 1 条 method(插在 index.loadWarehouses 之后);根版本 0.3.250 → 0.3.251、updatedAt 2026-10-06 → 2026-10-09;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "0.3.250", + "date": "2026-10-06", + "type": "updated", + "summary": "stock.check.workData 新增 only_abnormal 入参(可选,兼容 onlyAbnormal 驼峰写法):只看未盘和差异——过滤在 keyword 之后、分页切片之前完成,三视图均生效(location 视图按行 status=unchecked 或 has_unknown 保留;goods 视图按未盘行或明盘 is_diff=1 保留,盲盘仅按未盘;space 视图按行内 goods 子项过滤 status=unchecked 或明盘数量差异、空行整体移除;total 为过滤后行数)(0.3.249 → 0.3.250)", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "变更内容:stock.check.workData params 新增 only_abnormal(boolean,body,可选,向后兼容,兼容 onlyAbnormal 驼峰写法;未传或非 true(false/0/空串/缺省)不过滤)——过滤在 keyword 之后、分页切片之前完成(与 keyword 叠加,keyword 先过滤、only_abnormal 后过滤;total 为过滤后行数),三视图均生效:①location 视图仅保留 status=unchecked(未盘)或 has_unknown=true(含未知商品记录,未知商品无账面、差异=实盘-0=盘盈视为差异)的行,空库位标记(is_empty)后 status=checked 视为已盘点、不保留;②goods 视图仅保留未盘行(locations 均无 record_ids,即无任何作业记录)或明盘差异行(is_diff=1),盲盘(mode=blind)无数量字段仅按未盘过滤(已盘行全部移除);③space 视图按行内 goods 子项过滤(保留 status=unchecked 子项,明盘另保留 checked_quantity≠system_quantity 的数量差异子项,system_quantity 口径=可用+锁定),过滤后 goods 为空的行整体移除。", + "代码依据:app/service/systemMethods/stock/check.js#workData(only_abnormal/onlyAbnormal 蛇形驼峰兼容与透传)+ app/service/systems/stock_check.js#workData(abnormalRequested=onlyAbnormal===true||'true'||1,keywordFilteredRows 后调用 _filterAbnormalWorkRows(resolvedView, rows, check.mode!=='blind'),再分页切片;新增 _filterAbnormalWorkRows 私有方法按视图过滤);回归测试新增 5 用例(location/goods 明盘/space 明盘/space 盲盘/keyword 叠加)全部通过、workData 相关 43 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 only_abnormal、description/response.rows/response.total/notes 同步过滤口径;headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.249 → 0.3.250、updatedAt 保持 2026-10-06;methods/changes/system.json 新增本条(插入数组首位);其余 23 条 method 未改动(stock.check 分组仍为 24 条)。" + ] + }, + { + "version": "0.3.249", + "date": "2026-10-06", + "type": "updated", + "summary": "盘点账面口径全量统一为可用+锁定(SUM(available_quantity+locked_quantity)):result 库位行/空标记盘亏、report 重算、finish 差异汇总、detail 盘盈盘亏汇总、addDetail 拆行快照(0.3.248 → 0.3.249)", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail", + "stock.check.workDataSpaceDetails", + "stock.check.result", + "stock.check.report", + "stock.check.finish", + "stock.check.detail", + "stock.check.addDetail" + ], + "notes": [ + "变更内容:全部盘点账面口径统一为 wms_storage SUM(available_quantity+locked_quantity)(=可用+锁定)——①result 库位行 stocks 账面与空库位标记盘亏(_buildDetailAggregations/_formatDetailAggregationRow);②report 重算 diff_items 的库位行按商品账面与空标记库位账面(_recalcCheckSummary);③finish 差异汇总复用 _recalcCheckSummary 口径;④detail profit_total/loss_total 汇总复用同口径;⑤addDetail 按库位拆行写入的明细快照 system_quantity=该库位库存 SUM(可用+锁定);与盘点作业视图(workData/workDataDetail/workDataSpaceDetails,0.3.248 已改)完全一致。商品行差异仍以明细账面快照(system_quantity 列)对比。", + "代码依据:app/service/systems/stock_check.js#_recalcCheckSummary/#_buildDetailAggregations/#_formatDetailAggregationRow/#addDetail(attributes 全部改为 literal('SUM(available_quantity + locked_quantity)'));回归测试 222/222 通过、ESLint 0 错误(测试 helper fetchStorageQuantity/拆行断言/多库位拆行用例同步改口径)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 8 条 method(workData/workDataDetail/workDataSpaceDetails/result/report/finish/detail/addDetail 的 description/notes 同步库位账面=可用+锁定口径);根版本 0.3.248 → 0.3.249、updatedAt 2026-10-05 → 2026-10-06;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 23 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.248", + "date": "2026-10-05", + "type": "updated", + "summary": "盘点作业数据接口(stock.check.workData/workDataDetail/workDataSpaceDetails)库位账面改为可用+锁定(SUM(available_quantity+locked_quantity))并新增 locked_quantity 锁定数量字段(0.3.247 → 0.3.248)", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail", + "stock.check.workDataSpaceDetails" + ], + "notes": [ + "变更内容:goods 视图 locations 各项与 space 视图 goods 子项的库位账面 system_quantity 由 wms_storage SUM(quantity) 改为 SUM(available_quantity+locked_quantity)(=可用+锁定),并新增 locked_quantity(该库位锁定数量,SUM(locked_quantity));盘点数量 quantity/checked_quantity 口径不变;盲盘仍不返回任何数量字段。", + "代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows/#_buildSpaceWorkRows(Storage 查询 attributes 增加 literal('SUM(available_quantity + locked_quantity)') 与 fn('SUM', col('locked_quantity')));result/report/finish 的差异汇总口径不变(仍按 quantity 与明细快照);回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData、stock.check.workDataDetail 与 stock.check.workDataSpaceDetails 三条(description/response.rows/notes 同步库位账面=可用+锁定口径与 locked_quantity 字段);根版本 0.3.247 → 0.3.248、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 20 条 method 未改动(stock.check 分组仍为 23 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.247", + "date": "2026-10-05", + "type": "updated", + "summary": "stock.check.workData / workDataDetail 的 goods 视图明盘库位同时输出账面数量(system_quantity)与盘点数量(quantity)两个字段(0.3.246 → 0.3.247)", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail" + ], + "notes": [ + "变更内容:goods 视图明盘(mode=open)每库位由单一 quantity(实盘合计)改为同时输出 system_quantity(该库位账面数量,wms_storage 该库位 SUM(quantity),无库存记录库位为 0)与 quantity(该库位盘点数量=实盘合计,未盘库位为 0)两字段区分开;盲盘仍不返回任何数量字段。", + "代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows(Storage 查询 attributes 增加 fn('SUM', col('quantity')) 按 stock+space 分组汇总,构建 stockId→spaceCode→账面数量映射;buildLocationItem 明盘输出双数量字段);行级 checked_quantity 仍为 locations.quantity 合计、diff/is_diff 仅存在作业记录的行计算(口径不变);回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataDetail 两条(description/response.rows/notes 同步明盘库位双数量字段口径);根版本 0.3.246 → 0.3.247、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 23 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.246", + "date": "2026-10-05", + "type": "updated", + "summary": "stock.check.workData / workDataDetail 的 goods 视图 locations 改为商品所在全部库位列表(明盘显示库位+数量、盲盘只显示库位;未盘行不误显盘亏差异)(0.3.245 → 0.3.246)", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail" + ], + "notes": [ + "变更内容:_buildGoodsWorkRows 的 locations 由「仅已盘库位(按首条记录 id 升序)」改为「商品所在全部库位列表」——基础库位取自 wms_storage(任务 stock_id 集合 + is_enabled=1 未删除,DISTINCT space_id)经库位表取 space_code 并按拣货路径排序(pick_sequence 升序、pick_priority 降序、库位 id 升序兜底);无库存但已有作业记录的库位按首条记录 id 升序追加在末尾;空库位(location_code 空)组仍排在最后;未盘库位输出空信息(checked_at/checker_name=null、record_ids/images 空数组、明盘 quantity=0)。", + "差异口径:明盘 checked_quantity=locations 各库位 quantity 合计(未盘行恒 0);diff_quantity/is_diff 仅对存在作业记录(detailRecords.length>0)的行计算,未盘行恒 0(避免未盘行误显盘亏差异——此前 locations 非空导致未盘行 diff_quantity=0-账面为负);盲盘仍不返回任何数量字段。", + "代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows(workData 与 workDataDetail goods 明细分支复用同一构建函数);回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataDetail 两条(description/response.rows/notes 同步 goods 视图 locations 商品所在全部库位列表口径);根版本 0.3.245 → 0.3.246、updatedAt 2026-10-04 → 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 23 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.245", + "date": "2026-10-04", + "type": "added", + "summary": "新增 stock.check.workDataDetail 盘点明细单行作业数据接口(workData 单行版,仅库位任务明细):入参 detail_id(库位范围行,兼容 detailId 驼峰),返回统一 success 包装、data 为单行作业数据(结构与 workData location 视图单行一致);仅任务状态 approved/checking 可拉取(0.3.244 → 0.3.245)", + "methods": [ + "stock.check.workDataDetail" + ], + "notes": [ + "变更内容:ALL_METHOD_NAMES 新增 workDataDetail(22→23)、_noNeedLog 查询类清单新增 workDataDetail;方法层 stock.check.workDataDetail 兼容 detail_id/detailId 驼峰写法、warehouse_id 服务端自动注入;系统层仅库位任务明细(scope_type=location)支持,返回结构与 workData location 视图单行一致(detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/checked_at/checkers/goods)。", + "校验口径:detail_id 非正整数 400『盘点明细ID不能为空』;明细不存在 400『盘点明细不存在』;scope_type 非 location 400『仅库位任务明细支持拉取单行作业数据』;任务不存在 400『盘点任务不存在』;任务状态非 approved/checking 400 拒绝(与 stock.check.workData 同口径)。", + "代码依据:app/service/systemMethods/stock/check.js#workDataDetail + app/service/systems/stock_check.js#workDataDetail(复用 _buildLocationWorkRows);回归测试 216/216 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workDataDetail 一条(位于 stock.check.workData 之后);根版本 0.3.244 → 0.3.245、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组由 22 条增至 23 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local)与生产库(WMS_DB_TARGET=production)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.244", + "date": "2026-10-04", + "type": "updated", + "summary": "stock.check.workData 新增 keyword 入参(可选,向后兼容):仅库位任务(location 视图)按行 location_code/location_name 模糊匹配(不区分大小写)过滤任务明细后再分页(0.3.243 → 0.3.244)", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "变更内容:params 新增 keyword(string,可选,向后兼容)——先分流:仅库位任务(type=location/all,即服务端解析视图为 location)生效;生效时按 location 视图行字段 location_code(优先明细快照,缺失回退库位表 space_code)与 location_name(custom_name 兜底 space_code)做模糊匹配(contains、不区分大小写)过滤任务明细后再分页返回;非库位任务(goods/store,space/goods 视图)忽略该参数;keyword 为空/纯空白视为未传不过滤。", + "分页口径:过滤在分页切片之前完成,total 为过滤后的行数,rows 为过滤后的当前页行(分页仍按 pagination.{page,pageSize} 切片,与既有口径一致)。", + "代码依据:app/service/systemMethods/stock/check.js#workData(包装层透传 keyword)+ app/service/systems/stock_check.js#workData(normalizedKeyword=String(keyword||\"\").trim().toLowerCase(),resolvedView===\"location\" 且非空时按 location_code/location_name includes 过滤);回归测试 214/214 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 keyword、description/response.rows/response.total 同步过滤口径;headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.243 → 0.3.244、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库与生产库(import 当前 system.json → export 往返校验);生产库此前停留在 0.3.240,本次回填一并同步 0.3.241(detail 精简)、0.3.242(workData 返回 view)、0.3.243(waybill 主单号数组)三批累积差异。" + ] + }, + { + "version": "0.3.243", + "date": "2026-10-04", + "type": "updated", + "summary": "waybill.warehouse.list/export 的 where.mainWaybillCode 支持字符串数组(多主单号精确匹配,Op.in 定位 order_id 集合,0.3.242 → 0.3.243)", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.export" + ], + "notes": [ + "变更内容:where.mainWaybillCode 由「仅字符串单值」扩展为「字符串 | 字符串数组」;数组时按 Op.in 精确匹配多个主单号,先定位 order_id 集合,再返回/导出这些订单下的全部运单(主+子)。单值行为完全不变(order_id 条件仍为标量)。", + "边界:数组元素自动 trim 并过滤空值;全部不存在时直接返回空结果(list 空列表 / export total_count=0);空数组或全空值数组不添加该筛选条件;与 waybillCode 同时传入时按 AND 叠加。仓库隔离(warehouse_id = ctx.user.store_id)不受影响。", + "文档修正:原描述「与 waybillCode 互斥,同时传入时 mainWaybillCode 优先」与实际实现不符(实现为 AND 叠加),本次一并更正。", + "代码依据:app/service/systems/waybill.js#resolveMainWaybillOrderIds(list/export 共用);回归测试 test/app/service/systems/waybill.warehouse.mainWaybillCode.in.test.js。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(import 当前 system.json)并 export 往返校验;生产库需另行同步。" + ] + }, + { + "version": "2026.10.03-stock-check-workdata-view-only", + "date": "2026-10-03", + "type": "updated", + "summary": "stock.check.workData 不返回任务主表信息 check,改为返回 view(解析后的视图类型 location/goods/space);任务信息统一由 stock.check.detail 返回", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#workData 返回体由 { check, rows, total, page, pageSize } 改为 { view, rows, total, page, pageSize }(check 仍内部查询用于视图解析/盲盘明盘/状态守卫;view=resolvedView);app/service/systemMethods/stock/check.js#workData 仅同步 JSDoc(行为不变,仍统一 success/failure 包装)。", + "测试同步:test/app/service/systems/stock_check.test.js(workData 用例移除 data.check.* 断言、新增「响应键集合为 page/pageSize/rows/total/view」「三视图 view 断言(location/goods/space、库位任务无视 is_goods、is_goods 非 true 走 space)」「方法层不返回 check 且 view=goods」;盲盘/明盘模式断言改由 findCheckRow 从库表核对);真实库集成测试 213/213 通过、ESLint 0 错误。", + "兼容性影响:响应 data 移除 check 字段(破坏性变更)、新增 view 字段;rows/total/page/pageSize 与 location/goods/space 三视图结构、明盘盲盘数量控制、状态限制均不变;前端如需任务主表信息改调 stock.check.detail,如需判断行结构可直接读取 view,无需再自行按任务类型/is_goods 推导。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response(data.children 以 view 替换 check)/notes 同步;headers/params/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.241 → 0.3.242、updatedAt 保持 2026-10-03;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,需另行同步回填开发库与生产库(import 当前 system.json → export 往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.10.03-stock-check-detail-task-only", + "date": "2026-10-03", + "type": "updated", + "summary": "stock.check.detail 精简为只返回任务本身信息({ check }),不再返回明细范围行 rows 与 total(明细范围行/盘点结果改由 stock.check.result 返回)", + "methods": [ + "stock.check.detail" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#detail 改为仅返回 { check: _formatCheckRow(check) }(删除明细表查询、rows/total 与商品行 stock 挂载);同步删除已无引用的 _formatDetailScopeRow;app/service/systemMethods/stock/check.js#detail 仅同步 JSDoc(行为不变,仍统一 success/failure 包装)。", + "测试同步:test/app/service/systems/stock_check.test.js(helper detailCheck 改为「detail 取 check + 直查明细表补 rows」,新增 detail 只返回 { check } 与 400 边界用例,方法层 detail 用例改写,删除原「detail 纯范围行」5 条用例与已无引用的字段常量);真实库集成测试 213/213 通过、ESLint 0 错误。", + "兼容性影响:响应 data 由 { check, rows, total } 变更为 { check },为破坏性变更;调用方如需明细范围行/盘点结果改调 stock.check.result(返回 { check, rows, total }),作业记录改调 stock.check.recordList,盘点作业数据改调 stock.check.workData。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.detail 一条(description/response(data.children 仅保留 check)/notes 同步;headers/params/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.240 → 0.3.241、updatedAt 2026-10-02 → 2026-10-03;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,需另行同步回填开发库与生产库(import 当前 system.json → export 往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.10.02-stock-check-recordList-goods-mount-align-workData", + "date": "2026-10-02", + "type": "updated", + "summary": "stock.check.recordList 商品信息挂载对齐 workData:已知商品(stock_id 有值)item_code/item_name/spec 批量取自 stockWarehouse.getStockDetails(带缓存,未命中回退明细表商品快照),新增 store_id(商品货主ID)/store_name(货主名,经 _resolveStoreNameMap 解析)、barcode 兜底商品条码(getStockDetails.barcodes[0],无则保留记录原始条码);未知商品(stock_id 为空)item_code=扫描条码兜底、item_name=名称快照兜底条码、spec/store_id/store_name=null、barcode=扫描条码;保留记录表全字段不变、images 仍为作业记录照片(FileReference business_type=stock_check_record)、location_code 空串统一返回 null 不变——向后兼容,仅新增列。代码已改并测试通过 215/215、ESLint 0 错误。", + "methods": [ + "stock.check.recordList" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#recordList(rows 记录表全字段不变 + 商品信息挂载:已知商品 stockDetailMap 由 ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }) 带缓存批量取,item_code/item_name/spec 优先 getStockDetails、未命中回退明细表 wms_stock_check_detail 商品快照;store_id=Number(stockDetail.store_id)(无则 null)、store_name 经 _resolveStoreNameMap(storeIds, warehouseId) 解析;barcode=stockDetail.barcodes[0].barcode(无则保留记录原始条码);未知商品 isUnknownGoods=true:item_code=扫描条码(barcode 空则 null)、item_name=名称快照兜底条码、spec/store_id/store_name=null、barcode=扫描条码;location_code 空串归一 null 不变;images 经 _attachRecordImages 挂载 FileReference business_type=stock_check_record 不变)。本次代码已改并测试通过 215/215、ESLint 0 错误。", + "影响面:向后兼容(仅新增 spec/store_id/store_name 三列与 barcode 商品条码兜底),记录表全字段与 item_code/item_name 原有兜底口径保留;未知商品新增 spec/store_id/store_name 为 null;location_code 空串返回 null 不变;images 仍为作业记录照片。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.recordList 一条(description/response.rows 补新增字段 spec/store_id/store_name 与 barcode 兜底口径(对齐 workData)、说明保留记录全字段;notes 补「商品信息挂载对齐 workData」说明);headers/params/errors/isNeedAuth/isNeedLogin 不变;根版本 0.3.239 → 0.3.240、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data-record-photos", + "date": "2026-10-02", + "type": "updated", + "summary": "stock.check.workData 三视图作业照片挂载与 record_ids 输出:location 视图 goods 子项 images 由「商品主图 stockDetail.image_url」改为「作业记录照片 record.images」(_attachRecordImages 挂载 FileReference business_type=stock_check_record,与 result/recordList 口径一致;未知商品子项 images 维持记录照片不变);goods 视图(is_goods=true)locations 聚合项新增 images(该库位该商品全部记录的作业照片扁平去重)与 record_ids(该库位该商品全部作业记录 ID,按记录 id 升序);space 视图 goods 子项 images 由商品主图改为该商品在该库位的作业照片聚合(扁平去重)并新增 record_ids(该商品在该库位全部作业记录 ID);行级/未盘项无记录时 images/record_ids 为空数组。record_ids 供前端编辑/移除记录(recordDelete 批量删除、recheckClearLocation 重盘清除库位),location 视图单条 record_id 直接定位不变。代码已改并测试通过 214/214、ESLint 0 错误。", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#_buildLocationWorkRows(已知商品子项 images 由商品主图改为 record.images 作业记录照片,未知商品子项维持记录照片)+ #_buildGoodsWorkRows(locations 聚合项新增 record_ids(按记录 id 升序)与 images(该库位该商品全部记录照片扁平去重),行级 images 仍为 stockDetail.image_url)+ #_buildSpaceWorkRows(goods 子项 images 由商品主图改为该商品在该库位的作业照片聚合(扁平去重),新增 record_ids)+ #_attachRecordImages(FileReference business_type=stock_check_record,与 result/recordList 口径一致)。本次代码已改并测试通过 214/214、ESLint 0 错误。", + "影响面:images 由商品主图变为作业照片(location 视图已知商品子项、space 视图 goods 子项);goods 视图行级 images 仍为商品主图;goods locations 项与 space goods 项新增 record_ids(供前端编辑/移除记录:stock.check.recordDelete 批量删除、stock.check.recheckClearLocation 重盘清除库位);location 视图单条 record_id 直接定位不变;行级/未盘项无记录时 images/record_ids 为空数组;其余字段与分页/状态限制口径不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步三视图作业照片挂载与 record_ids 输出口径);headers/params/errors/isNeedAuth/isNeedLogin 不变;根版本 0.3.238 → 0.3.239、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-goods-detail-split-by-location", + "date": "2026-10-02", + "type": "updated", + "summary": "盘点模块「商品任务必须按库位盘点」改造:商品明细按「商品+库位」拆行——addDetail/patternCreate 商品路径(_addGoodsDetailRows)按商品在仓库的启用库存库位(wms_storage is_enabled=1,按 space_id 分组 SUM)拆行,每个「商品+库位」生成一条 scope_type=goods 明细行(location_id/location_code 绑定库存库位、system_quantity=该库位库存 SUM),一个商品多个库位多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细(商品任务必须按库位盘点);同商品重复添加整体跳过(幂等口径不变);added/total_items 为拆分明细行数。detail 商品行 location_id/location_code 非空(15 字段结构不变)。submit「存在缺少库位的盘点明细,无法提交审核」校验不再限定 scope_type=location:全部明细行(库位型与商品型)location_id 为空或 location_code 为空/空串均拦截。配套数据库迁移 20261002170000(已在开发/生产执行):uk_check_stock(check_id,stock_id) → uk_check_stock_location(check_id,stock_id,location_id);uk_check_location 唯一约束放宽为普通索引 idx_check_location(库位行幂等由应用层查重保证)。代码已改并测试通过 213/213、ESLint 0 错误。", + "methods": [ + "stock.check.addDetail", + "stock.check.detail", + "stock.check.submit", + "stock.check.patternCreate", + "stock.check.addLocationDetail" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#_addGoodsDetailRows(Storage.findAll where warehouse_id+stock_id in+is_enabled=1、attributes SUM(quantity)、group=[stock_id, space_id];LocationSpace 按 id 取 space_code 快照;货主校验与同商品整体跳过沿用;无启用库存库位商品 → invalidStockIds;每个「商品+库位」生成 scope_type=goods 行 location_id/location_code/system_quantity=该库位 SUM)+ #addDetail(added=toCreate.length、total_items 重算)+ #submit(count where check_id+(location_id 为空或 location_code 为空/空串),不再限定 scope_type=location)+ #detail/_formatDetailScopeRow(15 字段结构不变,商品行 location 有值)+ #patternCreate(pattern.type==='goods' 调 _addGoodsDetailRows)。本次代码已改并测试通过 213/213、ESLint 0 错误。", + "迁移说明:database/migrations/20261002170000-split-goods-detail-by-location.js(已在开发库与生产库执行)——wms_stock_check_detail 唯一索引 uk_check_stock(check_id, stock_id) 变更为 uk_check_stock_location(check_id, stock_id, location_id)(商品拆行后同任务同商品可多行);uk_check_location(check_id, location_code) 唯一约束放宽为普通索引 idx_check_location(商品拆行后同任务同库位可有多个商品行,库位行幂等由应用层查重保证)。", + "影响面:商品明细行数=商品×启用库存库位数(不再一商品一行);system_quantity 语义由商品全仓账面变为该「商品+库位」库存 SUM;无启用库存库位的商品无法加入盘点(addDetail 记入 invalid_stock_ids、patternCreate 不产生明细行);detail 商品行 location_id/location_code 由 null 变为绑定库存库位;submit 缺库位校验覆盖全部明细行(商品行与库位行)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.addDetail:description/params/response/notes 补商品拆行口径(拆多行、无库存库位 invalid、system_quantity=该库位账面、added=拆分行数);stock.check.detail:description/response.rows/notes 商品行 location_id/location_code 绑定库存库位;stock.check.submit:description/notes 缺库位校验改为覆盖全部明细行;stock.check.patternCreate:description/notes 补 goods 定式按库存库位拆行;stock.check.addLocationDetail:notes 幂等索引口径同步 uk_check_location 唯一约束放宽为普通索引 idx_check_location);根版本 0.3.237 → 0.3.238、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-submit-missing-location-guard", + "date": "2026-10-02", + "type": "updated", + "summary": "stock.check.submit 新增提交校验:库位范围明细(scope_type=location)缺少库位(location_id 为空或 location_code 为空/空串)的明细行存在时抛 400「存在缺少库位的盘点明细,无法提交审核」——脏数据防御,正常流程 addDetail/addLocationDetail 不会产生此类明细;原有校验(状态非 created/rejected 不允许提交审核、total_items<=0 无明细行拒绝)不变。代码已改并测试通过 211/211、ESLint 0 错误。", + "methods": [ + "stock.check.submit" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#submit——校验顺序:任务ID 为空→400「盘点任务ID不能为空」;任务不存在→400「盘点任务不存在」;状态非 created/rejected→400「当前状态(xx)不允许提交审核」;total_items<=0→400「盘点任务还没有明细行,无法提交审核」;新增库位缺库位校验:StockCheckDetail.count where check_id+scope_type=location+(location_id 为空或 location_code 为空/空串)>0→400「存在缺少库位的盘点明细,无法提交审核」(脏数据防御,正常流程 addDetail/addLocationDetail 不会产生此类明细)。本次代码已改并测试通过 211/211、ESLint 0 错误。", + "影响面:前端无需改动——该校验仅拦截脏数据(手工/历史遗留缺库位明细),正常盘点流程不受影响;原有校验顺序不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.submit 一条(errors 400 补「存在缺少库位的盘点明细,无法提交审核」、description/notes 补该校验口径);根版本 0.3.236 → 0.3.237、updatedAt 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-record-delete-batch-recheck-clear-location", + "date": "2026-10-02", + "type": "updated", + "summary": "盘点模块两项改动:① stock.check.recordDelete 由旧版单值删除升级为批量删除(与 detailDelete 批量口径一致)——入参 record_ids 数组(单次上限 200,兼容 recordIds 驼峰数组、recordId 单数驼峰、record_id 单值旧写法,单值自动转数组);响应由 { record_id, deleted, total_items, checked_items, diff_items, detail_status } 变更为 { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status }(deleted_ids/skipped_ids 保持入参顺序,查不到的记录计入 skipped_ids 不报错,旧版「作业记录不存在或不属于该盘点任务」400 不再返回);② 新增 stock.check.recheckClearLocation 重盘清除库位——传任务ID+库位ID,清除该库位范围内明细(scope_type=location)的全部作业记录(含空库位标记)、该库位回到未盘,仅库位范围任务(type=location/all)且状态 approved/checking 可用,删除后清理图片引用、重算汇总(主表状态不回退)、写 STOCK_CHECK_CLEAR_LOCATION 日志;ALL_METHOD_NAMES 由 21 个增至 22 个(加入 recheckClearLocation,位于 recordDelete 之后)。代码已改并测试通过 210/210、ESLint 0 错误。", + "methods": [ + "stock.check.recordDelete", + "stock.check.recheckClearLocation" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#recordDelete(record_ids 兼容 recordIds/recordId/record_id,单值自动转数组)+ app/service/systems/stock_check.js#recordDelete(校验顺序:任务ID 为空→400「盘点任务ID不能为空」;任务不存在→400「盘点任务不存在」;状态非 approved/checking→400「当前状态(xx)不允许删除作业记录」;ids 为空→400「请至少选择一条作业记录」;超 200→400「单次最多删除 200 条作业记录」;查不到计入 skipped_ids;清理 FileReference 图片引用、_recalcCheckSummary 重算、写 STOCK_CHECK_DELETE_RECORD 日志)。", + "代码依据:app/service/systemMethods/stock/check.js#recheckClearLocation(location_id 兼容 locationId 驼峰,warehouse_id 由 ctx.user.store_id 注入)+ app/service/systems/stock_check.js#recheckClearLocation(校验顺序:任务ID 为空/库位ID 为空/任务不存在/状态非 approved/checking→「当前状态(xx)不允许清除库位盘点信息」/任务范围非库位 type≠location/all→「仅库位盘点任务支持重盘清除库位」/库位不在任务范围→「该库位不在盘点任务范围内」;删除该库位范围明细全部作业记录含空库位标记、清理图片引用、重算汇总、主表状态不回退、写 STOCK_CHECK_CLEAR_LOCATION 日志)。", + "影响面:recordDelete 前端需改传 record_ids 数组并按新响应字段(deleted_count/deleted_ids/skipped_ids)解析;recheckClearLocation 为库位盘点重盘场景新接口,非库位任务调用报 400。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.recordDelete(params/response/errors/description/notes 按新批量口径重写,description 注明「由旧版单值删除升级为批量删除」)并新增 stock.check.recheckClearLocation(位于 recordDelete 之后);分组内「21 个 method」「21 个方法共用统一包装」等字样全部更新为 22 个(workData 权限口径 ALL_METHOD_NAMES 清单加入 recheckClearLocation);根版本 0.3.235 → 0.3.236、updatedAt 2026-10-02;methods/changes/system.json 插入本条(数组首位);stock.check 分组由 21 条增至 22 条。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production + --env production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,库与文件一致;stock.check 分组共 22 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-markEmpty", + "date": "2026-10-02", + "type": "added", + "summary": "盘点模块新增 stock.check.markEmpty 方法(标记库位为空,库位盘点模式专属):仅库位范围任务(type=location/all)与库位明细行(scope_type=location)支持;内部转调 report(is_empty=true) 口径——写/更新空标记记录(stock_id/barcode/item_name=null、quantity=0、is_empty=1)、清除该明细商品记录、主表 approved→checking、重算 checked_items/diff_items/detail_status;按校验顺序返回 400(任务ID/明细ID 为空、任务不存在、状态不允许、非库位任务、明细不存在、明细非库位行);ALL_METHOD_NAMES 由 20 个增至 21 个(加入 markEmpty)——免 API 权限、免仓库有效期鉴权、必须登录,写操作记录操作日志(STOCK_CHECK_REPORT)。", + "methods": [ + "stock.check.markEmpty" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#markEmpty(warehouse_id 由服务端从 ctx.user.store_id 自动注入)+ app/service/systems/stock_check.js#markEmpty(校验后转调 this.report({ is_empty: true }));ALL_METHOD_NAMES 更新为 create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,report,markEmpty,recordList,recordDelete,finish,submit,cancel,audit,batchDelete,export,exportTaskProgress,patternList,patternCreate(21 个)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.markEmpty 一条(位于 stock.check.report 之后);分组内各 method notes 的「20 个方法共用统一包装」与 workData 权限口径 note 的 ALL_METHOD_NAMES 列表同步更新为 21 个;根版本 0.3.234 → 0.3.235、updatedAt 2026-10-02;methods/changes/system.json 插入本条(数组首位);stock.check 分组由 20 条增至 21 条。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;先经 script/method-doc-create.cjs 在维护源新建(--bump 升版本),再按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入本变更记录;同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,库与文件一致。" + ] + }, + { + "version": "2026.10.02-stock-check-empty-location-mark", + "date": "2026-10-02", + "type": "updated", + "summary": "盘点模块新增「空库位标记」能力:stock.check.report 新增 is_empty 入参(仅库位盘点明细支持,确认该库位为空——不要求商品/条码、quantity 恒 0,写特殊作业记录 stock_id/barcode/item_name=null、quantity=0、is_empty=1,与商品记录互斥:标记空删除该明细商品记录、上报商品删除空标记记录,商品明细行传 is_empty 报 400「仅库位盘点明细支持空库位标记」);stock.check.workData location 视图行新增 is_empty 字段(空标记记录不计入 goods 子列表,空标记后 status=checked 视为已盘点);stock.check.result 库位行新增 is_empty 字段(空标记时 stocks=[]、unknown_items=[]、checked_quantity=0、status=checked,账面有库存时 diff_quantity 为负数(盘亏)、is_diff=1);主表汇总(_recalcCheckSummary)空标记记录计入已盘明细、空标记明细库位账面有库存即计盘亏差异(diff_items);stock.check.recordList/export 记录行输出 is_empty(export Sheet2 空库位记录商品编码列输出「(空库位)」、数量 0);数据库 wms_stock_check_record 新增 is_empty 字段(TINYINT(1) NOT NULL DEFAULT 0,迁移 20261002160000 已在开发/生产执行)。代码已改并测试通过 201/201、ESLint 0 错误。", + "methods": [ + "stock.check.report", + "stock.check.workData", + "stock.check.result", + "stock.check.recordList", + "stock.check.export" + ], + "notes": [ + "代码依据:report 空库位标记(is_empty 归一化 true/'true'/1,仅 scope_type=location 支持、商品明细行报 400『仅库位盘点明细支持空库位标记』;标记空时 quantity 恒 0、写 stock_id/barcode/item_name=null、quantity=0、is_empty=1 的特殊作业记录;覆盖式查重按 detail_id+is_empty=1+location_code;互斥:标记空删除该明细 is_empty=false 记录、上报商品删除该明细 is_empty=true 记录)app/service/systems/stock_check.js#report;workData location 视图行 is_empty(空标记记录不进 goods 子列表、行 status=checked)app/service/systems/stock_check.js#_buildLocationWorkRows;result 库位行 is_empty 与盘亏口径(stocks=[]、unknown_items=[]、checked_quantity=0、status=checked;按 wms_storage SUM(quantity) 账面>0 时 diff_quantity=-账面总量、is_diff=1)app/service/systems/stock_check.js#_formatDetailAggregationRow;主表汇总(空标记计入已盘明细、账面有库存计盘亏差异)app/service/systems/stock_check.js#_recalcCheckSummary;recordList 记录全字段带 is_empty;export Sheet2 空库位行商品编码列输出『(空库位)』、数量 0 app/service/systems/stock_check.js#_generateAndUploadStockCheckExcel。本次代码已改并测试通过 201/201、ESLint 0 错误。", + "数据库变更:database/migrations/20261002160000-add-is-empty-to-stock-check-record.js(wms_stock_check_record 新增 is_empty TINYINT(1) NOT NULL DEFAULT 0 COMMENT 是否空库位标记,位于 item_name 之后),开发库(127.0.0.1:3307/wms)与生产库(112.124.21.102:3306/wms)均已执行。", + "影响面:前端库位盘点(明细 scope_type=location)可传 is_empty=true 快速确认空库位(无需扫描商品/条码);workData/result 库位行新增 is_empty 字段用于展示空标记状态(空标记行按已盘点处理、账面有库存显示盘亏差异);recordList/export 自动带出 is_empty(export 空库位行商品编码列显示「(空库位)」);商品明细行传 is_empty 会被 400 拒绝。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.report:params 新增 is_empty 入参、errors 400 补「仅库位盘点明细支持空库位标记」、description/response/notes 补充空库位语义与互斥及汇总口径;stock.check.workData:description/response.rows 的 location 行新增 is_empty 字段说明;stock.check.result:description/response.rows 库位行新增 is_empty 与空标记盘亏口径;stock.check.recordList:response.rows 记录全字段说明新增 is_empty;stock.check.export:description/notes 补 Sheet2 空库位行输出口径);根版本 0.3.233 → 0.3.234、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data-location-unknown-merge", + "date": "2026-10-02", + "type": "updated", + "summary": "stock.check.workData location 视图行结构调整:删除 unknown 未知商品子列表——未知商品记录(stock_id 为空)不再单独输出,与已知商品统一并入 goods 子列表、输出字段对齐已知商品(record_id/stock_id=null/item_code 用条码兜底/item_name 用名称快照兜底条码/barcode/images/store_id=null/store_name=null/quantity/checked_at/checker_name);行级 has_unknown 标记保留(该库位是否含未知商品记录)。代码已改并测试通过 197/197、ESLint 0 错误。", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#_buildLocationWorkRows——records 按 detail_id 聚合后,已知商品(stock_id 正整数)与未知商品(stock_id 为空/非正整数)均 push 进 goods:已知商品取 stockDetailMap(stockWarehouse.getStockDetails 带缓存)补 item_code/item_name/barcode(barcodes[0].barcode)/images(image_url)/store_id/store_name(_resolveStoreNameMap 解析);未知商品 stock_id=null、item_code=条码兜底、item_name=名称快照兜底条码、barcode=记录条码、images=_attachRecordImages 挂载(FileReference business_type=stock_check_record)、store_id/store_name=null;quantity/checked_at/checker_name 与已知商品一致;行级 has_unknown=true 标记保留。本次代码已改并测试通过 197/197、ESLint 0 错误。", + "影响面:前端无需再处理 unknown 数组——直接遍历 goods 子列表,按 stock_id 是否为 null 区分未知商品(未知商品 item_code 即扫描条码、item_name 即上报名称快照);has_unknown 仍可用于快速判断该库位是否含未知商品;其余视图(goods/space)与分页等结构不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步 location 视图行结构——删除 unknown 子列表字段说明、goods 改为「已知商品与未知商品记录均入内,未知商品 stock_id=null、item_code 用条码兜底、store_id/store_name 为 null」、has_unknown 保留说明;headers/params/errors/isNeedAuth/isNeedLogin 与 goods/space 视图及分页描述不变);根版本 0.3.232 → 0.3.233、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-data-envelope", + "date": "2026-10-02", + "type": "updated", + "summary": "stock.check 分组全部 20 个方法响应统一增加 data 层封装:成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp };业务数据结构本身不变(如 create 返回盘点任务字段、list 返回 { rows,total,page,pageSize }、workData 返回 { check,rows,total,page,pageSize }),只是整体包进 data。代码已改并测试通过 197/197、ESLint 0 错误。", + "methods": [ + "stock.check.create", + "stock.check.list", + "stock.check.addDetail", + "stock.check.detailDelete", + "stock.check.detail", + "stock.check.result", + "stock.check.workData", + "stock.check.report", + "stock.check.recordList", + "stock.check.recordDelete", + "stock.check.finish", + "stock.check.submit", + "stock.check.cancel", + "stock.check.audit", + "stock.check.batchDelete", + "stock.check.export", + "stock.check.exportTaskProgress", + "stock.check.patternList", + "stock.check.patternCreate", + "stock.check.addLocationDetail" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#_call(20 个方法共用的统一调用包装)——成功返回 { flag:\"success\", code:1, message:\"ok\", data:result };业务错误(code 为 400-599 整数)返回 { flag:\"failure\", code, message, data:null };其余异常记录日志并返回 { flag:\"failure\", code:500, message:\"服务器内部错误\", data:null };app/lib/api_response.js#toSuccess 识别标准载荷后顶层补充 timestamp。", + "旧口径(改造前):成功 { flag:\"success\", code:1, message:\"ok\", ...业务字段平铺 }(MainService.success 展开 data 的平铺结构);失败响应 { flag:\"failure\", code, message }(无 data);本次统一为 data 层封装,与项目 toSuccess/toFailure 常规口径一致。", + "失败语义变化:业务错误(400/500 等)不再由控制器 catch 后转 HTTP 4xx/5xx + toFailure,而是由 _call 捕获后在 body 内以 flag=failure + data=null 返回(HTTP 200);未登录/鉴权失败(checkAuth 401)仍走控制器 toFailure(HTTP 401)。前端失败判定建议以 flag 为准。", + "影响面:前端解析响应需从 data 取业务数据(原顶层业务字段全部移入 data);业务数据结构本身不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组全部 20 条 method 的 response 统一调整——顶层固定为 flag/code/message/data/timestamp,原业务字段整体移入 data.children(字段与说明不变),每条 notes 追加统一 data 层封装口径;headers/params/errors/isNeedAuth/isNeedLogin/description 不变;根版本 0.3.231 → 0.3.232、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production + --env production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data-view-driven", + "date": "2026-10-02", + "type": "updated", + "summary": "stock.check.workData 视图驱动规则改造:view 入参废弃(不再校验、不再使用,传任何值都被忽略、不报错);新增 is_goods 入参(boolean,body,可选,兼容 isGoods 驼峰写法)——任务范围为库位(type=location/all)一律按库位视图(location)返回、无视 view/is_goods;任务范围为商品(type=goods/store)默认聚合库位视图(space),仅 is_goods=true 时按商品视图(goods)返回,is_goods 其他值(false/0/缺省等)一律按默认 space;分页能力不变(pagination.{page,pageSize},与 stock.check.list 口径一致,默认 20 上限 200);errors 移除「视图类型非法(仅支持 location/goods/space)」条目,保留任务ID不能为空/状态限制/任务不存在/500。代码已改并测试通过 197/197、ESLint 0 错误。", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#workData(warehouse_id 由 ctx.user.store_id 注入;const { id, is_goods: isGoodsSnake, isGoods: isGoodsCamel, pagination } = data || {},isGoods=is_goods 未定义时回退 isGoods 兼容驼峰写法;不再读取/校验 view)+ app/service/systems/stock_check.js#workData(视图解析:normalizedType=String(check.type||'').trim(),type=location/all 一律 location 无视 view/is_goods;否则 isGoods===true||'true'||1 → goods、其余默认 space;错误口径不变:ID 不能为空/任务不存在/状态限制/500)。本次代码已改并测试通过 197/197、ESLint 0 错误。", + "影响面:前端如需商品视图须改传 is_goods=true(或 isGoods=true);view 传值不再生效、不会被校验;库位任务前端无需传 is_goods。响应结构 { check, rows, total, page, pageSize } 与分页口径不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 删除 view、新增 is_goods;description 视图规则改为「库位任务一律 location、商品任务默认 space、is_goods=true 才 goods;view 入参已废弃忽略」;errors 删除视图非法条目;response 结构不变;notes 同步代码依据与视图驱动规则);根版本 0.3.230 → 0.3.231、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data-pagination-conventional", + "date": "2026-10-02", + "type": "updated", + "summary": "stock.check.workData 分页口径修正:改为与 stock.check.list 一致的常规口径——仅入参 pagination.{page,pageSize}(不再兼容 page_size 蛇形写法、不再支持顶层 page/pageSize/page_size),默认 page=1、pageSize=20、上限 200,响应 page/pageSize 结构不变", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#workData(const { id, view, pagination } = data || {},pagination 直接透传,不再解析顶层 page/pageSize/page_size、不做 page_size 兼容)+ app/service/systems/stock_check.js#workData(pagination 默认 {};page=Math.max(1, Number(pagination.page)||1) 默认 1、pageSize=Math.min(200, Math.max(1, Number(pagination.pageSize)||20)) 默认 20 上限 200、非法回退默认;先构建全量行再 slice(offset, offset+pageSize);返回 { check, rows, total, page, pageSize })。分页口径与 stock.check.list 完全一致。本次代码已改并测试通过 197/197、ESLint 0 错误。", + "口径修正说明:上一轮变更记录(2026.10.02-stock-check-work-data-pagination)曾描述「入参支持 pagination 对象与顶层 page/pageSize/page_size(顶层优先)、兼容 page_size 蛇形写法」,代码按用户要求改为常规分页方式后上述描述不再成立;本条为口径修正记录,替换上一轮记录中的入参兼容口径(历史记录保留不回改),以本条为准。", + "影响面:仅文档口径修正(methods/system.json 的 workData params.pagination 描述、description、response.page/pageSize 描述、notes),代码接口行为与响应结构(check/rows/total/page/pageSize)不变;涉及文件:methods/system.json、methods/changes/system.json、库表 wms_api_method_doc/wms_method_doc_meta。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params.pagination 描述、description、response.page/pageSize 描述、notes 同步常规分页口径并注明与 stock.check.list 一致;response.rows/total、headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.229 → 0.3.230、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data-pagination", + "date": "2026-10-02", + "type": "updated", + "summary": "stock.check.workData 新增分页能力:入参支持 pagination 对象与顶层 page/pageSize/page_size(顶层优先),响应新增 page/pageSize,rows 为当前页行、total 为全部行数(默认 page=1、pageSize=20 上限 200,向后兼容)", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#workData(入参归一化:data.pagination.{page,pageSize} 兼容 page_size 蛇形写法;顶层 data.page / data.pageSize / data.page_size 顶层值优先,口径与 stock/report.js 一致)+ app/service/systems/stock_check.js#workData(三视图先构建全量行再按页切片 slice(offset, offset+pageSize);page=Math.max(1, Number(page)||1) 默认 1、pageSize=Math.min(200, Math.max(1, Number(pageSize)||20)) 默认 20 上限 200、非法回退默认;返回 { check, rows, total, page, pageSize },total=allRows.length 未分页口径)。本次代码已改并测试通过 197/197、ESLint 0 错误。", + "影响面:仅新增可选入参(pagination/page/pageSize/page_size)与两个响应字段(page/pageSize);旧调用方不传分页时 page=1、pageSize=20、rows 行为不变、total 不变,向后兼容;涉及文件:app/service/systemMethods/stock/check.js、app/service/systems/stock_check.js、methods/system.json、methods/changes/system.json、库表 wms_api_method_doc/wms_method_doc_meta。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 pagination、response 新增 page/pageSize 并同步 rows/total 口径、description/notes 补充分页口径;headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.228 → 0.3.229、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production + --env production)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data-space-fields", + "date": "2026-10-02", + "type": "updated", + "summary": "workData space 视图两处调整:库位聚合来源扩展为当前库存库位∪作业记录库位(盘点前库存已出空但已有作业记录的库位也能展示);行字段对齐库位查询惯例 index.searchSpace(id/space_code/custom_barcode/custom_name,custom_name 空输出 null 不兜底编码)", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows——库位集合由原「仅 wms_storage(warehouse_id + 任务 stock_id 集合 + is_enabled=1)DISTINCT space_id」扩展为「当前库存库位 ∪ 作业记录库位」:wms_stock_check_record 的 location_id 已回填直接用、未回填的按 location_code 匹配 wms_location_space.space_code 补查(attributes 含 id/space_code/custom_barcode/custom_name/pick_sequence/pick_priority);仅记录库位(当前库存无该商品)按库位归集补行(totalQuantity 按 0),明盘该系统 quantity 按 0、checked_quantity 按该库位实盘合计;本次仅同步文档,未改动任何代码(代码已改并测试通过 196/196、ESLint 0 错误)。", + "行字段口径:space 视图行输出 id(wms_location_space.id)/space_code/custom_barcode(空为 null)/custom_name(空为 null,不再兜底 space_code),与库位查询惯例 index.searchSpace 一致;goods 子列表字段不变(detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/status,明盘另含 system_quantity/checked_quantity);location/goods 视图行字段不变。", + "影响面:仅 space 视图行字段与库位集合口径变化(涉及文件:app/service/systems/stock_check.js、methods/system.json、methods/changes/system.json、库表 wms_api_method_doc/wms_method_doc_meta);check/total 结构、location/goods 视图行、明盘/盲盘数量控制、排序口径(pick_sequence 升序/pick_priority 降序/库位 id 升序兜底)、状态限制均不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步新口径);根版本 0.3.227 → 0.3.228、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production + --env production)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.02-system-platform-header-miniprogram", + "date": "2026-10-02", + "type": "updated", + "summary": "docs 全局 Header 的 platform 下拉修正:「微信端」取值由 wx 改为 miniprogram,并移除重复的「小程序端」(miniProgram)选项", + "methods": [ + "/api/docs" + ], + "notes": [ + "依据:app/service/system.js#ALLOWED_PLATFORMS 含小写 miniprogram(校验前 toLowerCase,实际建议使用规范值);app/service/systems/wechat.js 登录链路 platform_code 兜底为 'miniprogram';接口日志实测客户端 platform 取值只有 web/pda/miniprogram,从未出现 wx/miniProgram。", + "文档变更范围:methods/system.json 根 headers 的 platform.list——「微信端」value 由 wx 改为 miniprogram,删除「小程序端」(value=miniProgram,与微信端同义且大小写与规范不一致);platform 描述示例补充 miniprogram;project 列表及其它 header 不变;根版本 0.3.226 → 0.3.227、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);所有 method 条目未改动。", + "库表维护源说明:wms_method_doc_meta.headers 与 version 同步更新后按 import→export 往返校验,保持库与文件一致。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data-status-guard", + "date": "2026-10-02", + "type": "updated", + "summary": "workData 新增状态限制:仅 approved/checking 任务可拉取盘点作业数据,其他状态返回 400 并说明原因", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#workData 在任务存在校验之后新增状态守卫——check.status 不在 REPORT_ALLOWED_STATUSES(approved/checking,与 report/finish 一致)内时抛 400(createBusinessError(message, 400)),文案『当前状态({STOCK_CHECK_STATUS_LABELS 中文标签,无标签回退状态值})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』;本次仅同步文档,未改动任何代码(代码变更已通过 ESLint 与 193 条集成测试)。", + "状态限制口径:仅任务状态 approved(审核完成)或 checking(盘点作业中)可拉取盘点作业数据;created 已创建/submitted 待审核/rejected 已驳回/completed 已完成/cancelled 已取消 均返回 400;与 report(盘点作业上报,approved 首次上报自动转 checking)及 finish(完成盘点)使用同一 REPORT_ALLOWED_STATUSES 常量。", + "400 文案:盘点任务ID不能为空 / 视图类型非法(仅支持 location/goods/space)→ 当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取 → 盘点任务不存在(校验顺序:id → view → 任务存在 → 状态守卫)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(errors 的 400 拆分三条并新增状态限制文案、description/notes 补充状态限制口径);根版本 0.3.225 → 0.3.226、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data", + "date": "2026-10-02", + "type": "added", + "summary": "新增 stock.check.workData 盘点作业数据接口:一个接口按 view 入参驱动三种视图(location 库位结构含未知商品子列表;goods 商品列表按库位子列表;space 聚合库位列表按拣货路径排序),明盘显示数量、盲盘隐藏数量", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#workData(id 非正整数抛 400『盘点任务ID不能为空』;view 非 location/goods/space 抛 400『视图类型非法(仅支持 location/goods/space)』;任务不存在(按 id+warehouse_id 查 wms_stock_check)抛 400『盘点任务不存在』;按 view 分派 _buildLocationWorkRows/_buildGoodsWorkRows/_buildSpaceWorkRows,统一返回 { check: _formatCheckRow 口径, rows, total: rows.length })+ app/service/systemMethods/stock/check.js#workData(warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递);本次仅同步文档,未改动任何代码。", + "三视图口径:location=库位结构,以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位盘点作业记录——goods 已知商品子列表(stock_id 有值,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名 _resolveStoreNameMap 解析、图片 image_url)与 unknown 未知商品子列表(stock_id 为空,输出记录快照 barcode/item_name/images,图片经 _attachRecordImages 挂载 FileReference business_type=stock_check_record);goods=商品结构,以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内挂按库位聚合的 locations(空库位归 location_code=null 组,按首条记录 id 升序);space=聚合库位列表,以任务商品(scope_type=goods 的 stock_id 集合)所在库位为列表——wms_storage(warehouse_id + stock_id 在集合 + is_enabled=1 未删除)DISTINCT space_id,行内 goods 为该库位下的任务商品,未在 wms_storage 有库位的商品不入列表。", + "明盘/盲盘数量控制:明盘(mode=open)goods 视图行返回 system_quantity(明细账面快照)/checked_quantity(已盘合计=locations.quantity 合计)/diff_quantity(已盘-账面)/is_diff(差异非 0 为 1),locations 各项含 quantity(该库位实盘合计);space 视图 goods 各项含 system_quantity(wms_storage space+stock SUM(quantity) 账面)/checked_quantity(该商品在该库位的实盘合计);盲盘(mode=blind)不返回任何数量字段(goods 视图 locations 仅 location_code/checked_at/checker_name,space 视图 goods 仅商品信息+status);无作业记录时 locations 为空数组、明盘已盘合计/差异按 0(避免未盘行误显盘亏差异)。", + "排序口径:space 视图库位按拣货路径排序——pick_sequence 升序、pick_priority 降序、同值按库位 id 升序兜底;space 行内 goods 按 stock_id 升序;location/goods 视图行按明细 id 升序;goods 视图 locations 按首条记录 id 升序。", + "权限口径:随 ALL_METHOD_NAMES(20 个:create/list/addDetail/addLocationDetail/detailDelete/detail/result/workData/report/recordList/recordDelete/finish/submit/cancel/audit/batchDelete/export/exportTaskProgress/patternList/patternCreate)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog(list/detail/result/workData/recordList/export/exportTaskProgress/patternList),不记录操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workData 一条(位于 stock.check.result 之后);根版本 0.3.224 → 0.3.225、updatedAt 2026-10-01 → 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组由 19 条增至 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-detail-delete-batch", + "date": "2026-10-01", + "type": "updated", + "summary": "detailDelete 支持批量删除:入参 detail_ids(兼容旧 detail_id 单值),返回改为 { deleted_count, deleted_ids, skipped_ids, total_items },未命中跳过不报错", + "methods": [ + "stock.check.detailDelete" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js(detailDelete:id 非法抛 400『盘点任务ID不能为空』、任务不存在抛 400『盘点任务不存在』、状态非 created/rejected 抛 400『当前状态(xxx)不允许删除明细』、_normalizeIdList 归一化(单值自动转数组、去重、仅保留正整数)后为空抛 400『请至少选择一个明细』、超过 200 抛 400『单次最多删除 200 条明细』;按 id in ids + check_id + warehouse_id 仓库隔离查询,未命中 ID 计入 skipped_ids 不报错;命中明细批量 destroy 并防御性清理 wms_stock_check_record,重算主表 total_items;返回 { deleted_count, deleted_ids, skipped_ids, total_items },deleted_ids/skipped_ids 保持入参顺序)+ app/service/systemMethods/stock/check.js(detailDelete 入参改为 detail_ids 数组,兼容 detailIds 驼峰与旧 detail_id 单值,优先级 detail_ids > detailIds > detail_id,单值自动转数组);本次仅同步文档,未改动任何代码。", + "批量口径:单次上限 200;单值自动转数组并去重;未命中的明细ID计入 skipped_ids 不报错;命中批量删除并防御清理作业记录(正常流程 created/rejected 不应有记录);删除后重算 total_items;deleted_ids/skipped_ids 保持入参顺序。", + "响应结构变更(兼容性影响):由旧版 { detail_id, deleted, total_items } 变更为 { deleted_count, deleted_ids, skipped_ids, total_items },旧前端需按新结构适配。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.detailDelete(params 改为 detail_ids 数组+兼容字段 detailIds/detail_id、response 改为批量结构、errors 同步批量文案、description/notes 同步);根版本 0.3.223 → 0.3.224、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动(stock.check 分组仍为 19 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 19 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-add-detail-location-ids", + "date": "2026-10-01", + "type": "updated", + "summary": "addDetail 支持 location_ids 按库位ID直查添加(与 stock_ids 按任务类型区分维度),addLocationDetail 转调 addDetail 保留兼容", + "methods": [ + "stock.check.addDetail", + "stock.check.addLocationDetail" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js(addDetail 新增 locationIds 入参与 _addLocationRowsByIds 库位ID直查路径、addLocationDetail 薄封装转调 addDetail 并映射返回结构)+ app/service/systemMethods/stock/check.js(addDetail/addLocationDetail 新增 location_ids 入参并兼容 locationIds 驼峰,location_ids 优先);本次仅同步文档,未改动任何代码。", + "分派口径:addDetail 按任务盘点类型区分维度——type=store/goods 接受 stock_ids(传 locations 报 400『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报 400『当前盘点类型按商品盘点,不能添加库位明细』);type=all/location 接受 locations 或 location_ids(传 stock_ids 报 400『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』)。", + "ID 直查与幂等口径:location_ids 优先于 locations(两者都传时 locations 忽略),按 wms_location_space.id+warehouse_id 直查校验(不再按 space_code 二次解析),查不到的 ID 记入新增返回字段 invalid_location_ids(不报错);幂等按 check_id+location_code(uk_check_location 唯一索引),location_ids 路径跳过项按库位ID记入 skipped;商品行幂等仍按 uk_check_stock。", + "兼容说明:addLocationDetail 保留旧接口名与返回结构 { added, skipped, invalid_location_ids, total_items },薄封装转调 addDetail 库位ID直查路径(stockIds/locations 置空、传 locationIds),返回结构过滤 invalid_locations/invalid_stock_ids;转发前保留旧口径参数校验(任务ID不能为空、库位ID不能为空、单次上限 200)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.addDetail(params 新增 location_ids、response 新增 invalid_location_ids、description/errors/notes 同步新口径)并新增 stock.check.addLocationDetail 一条(此前未登记,分组由 18 条增至 19 条);根版本 0.3.222 → 0.3.223、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 19 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-unknown-goods", + "date": "2026-10-01", + "type": "updated", + "summary": "盘点作业上报支持未知商品(stock_id 可空 + barcode/item_name,仿收货明细);图片独立维护(上传 businessType=stock_check_record,查询挂载 images,删除清理)", + "methods": [ + "stock.check.report", + "stock.check.result", + "stock.check.recordList", + "stock.check.recordDelete", + "stock.check.export" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js(report/_resolveStockIdByBarcode/result/_buildDetailAggregations/_formatDetailAggregationRow/_attachRecordImages/recordList/recordDelete/exportStockChecks/_generateAndUploadStockCheckExcel)+ app/service/systemMethods/stock/check.js(report 新增入参 barcode/item_name 透传);未改动任何业务代码之外的逻辑。", + "迁移依据:database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js(wms_stock_check_record:stock_id 改可空(NULL=未知商品,唯一索引 uk_detail_stock_location 中 NULL 不参与唯一约束)+ 新增 barcode VARCHAR(100) 可空/item_name VARCHAR(255) 可空),本地与生产均已执行。", + "未知商品上报口径:report 新增入参 barcode/item_name;stock_id 与 barcode 至少传一项——仅传 barcode 先按条码匹配系统商品(wms_stock_barcodes 按 barcode+本仓库,关联 StockWarehouse 校验商品属于本仓库),命中回填 stock_id 走已知商品逻辑(商品明细行校验与明细商品一致),未命中记录未知商品(stock_id=NULL+barcode+item_name,item_name 缺省为 barcode);都未传沿用原报错口径;未知商品覆盖式查重 where { detail_id, stock_id:null, barcode, location_code }(应用层查重,唯一索引不约束 NULL 行,并发兜底逻辑对未知商品同样降级更新)。", + "差异口径:未知商品账面 0,实盘=盘盈(差异=实盘-0),必然计入 diff_items;result 行级新增 unknown_items [{ barcode, item_name, checked_quantity }](stock_id 为空的记录按条码归组、条码升序,已计入行级 checked_quantity/diff_quantity/is_diff);finish 未知商品实盘>0 计入盘盈合计与差异行数。", + "图片独立维护口径:上传走通用上传接口(businessType='stock_check_record' + businessId=作业记录ID,建 FileReference,仿收货 receivingItem);result 的 records 与 recordList 的 rows 每条挂载 images [{ id, url }](wms_file_reference 关联 wms_file.file_url,无图片返回空数组);recordDelete 删除记录后清理关联图片引用(失败仅告警不影响主流程);report 不接收图片。", + "查询/导出显示口径:recordList 与 export Sheet2 未知商品(stock_id 为空)item_code 显示扫描条码(barcode)、item_name 显示上报名称快照(item_name 或 barcode 兜底);已知商品维持原口径(明细表/wms_stock_warehouse 商品快照)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.report/result/recordList/recordDelete/export 五条(report 新增 params barcode/item_name、response record 补充 barcode/item_name/stock_id 可空;result 新增 response unknown_items 与 records.images;recordList 补充 rows barcode/item_name/images 口径;export 补充 Sheet2 未知商品列口径;recordDelete 补充图片清理说明);根版本 0.3.221 → 0.3.222、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 13 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-detail-stock-mount", + "date": "2026-10-01", + "type": "updated", + "summary": "stock.check.detail 商品行新增挂载 stock 对象(stockWarehouse.getStockDetails 全局商品信息:条码/图片/管理标识等,带缓存),库位行不挂载", + "methods": [ + "stock.check.detail" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#detail(对 scope_type=goods 行按 stock_id 去重后批量调用 ctx.service.systems.stockWarehouse.getStockDetails(goodsStockIds, { warehouseId }),结果按 stock_id 挂载到各行 stock 字段,未命中为 null;库位行不挂载)与 app/service/systems/storage/stock_warehouse.js#getStockDetails(带缓存批量取商品详情,key=cache:stock_detail:{warehouseId}:{stockId},默认 TTL 300 秒);未改动任何业务代码。", + "挂载口径:stock 为 wms_stock_warehouse 全局商品信息,含 id/item_code/item_name/sku_property/quantity 库存数量/locked_quantity 锁定数量/is_batch_mgmt 批次管理/is_shelf_life_mgmt 效期管理/image_url 商品图片/is_images/need_recheck 是否需要复核/store_id 货主ID/packing_requirements 打包要求/pick_requirements 拣货要求/recheck_requirements 复核要求/merge_requirements 要求合并开关/stock_unit 库存单位/barcodes 条码数组;仅 scope_type=goods 商品行挂载(未命中 stock=null),scope_type=location 库位行不挂载;范围行原有 15 字段与其余返回结构不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.detail 一条(description/response.rows/notes 补充商品行 stock 挂载口径);根版本 0.3.220 → 0.3.221、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-list-store-name", + "date": "2026-10-01", + "type": "updated", + "summary": "stock.check.list 返回行新增 store_name 货主名称(合约货主备注 store_remask 优先、公司全称 company_name 兜底)", + "methods": [ + "stock.check.list" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#list(返回前调用 _resolveStoreNameMap() 批量解析货主名称,每行新增 store_name 字段)与 #_resolveStoreNameMap(货主名称解析方法);未改动任何业务代码。", + "解析口径:优先 wms_store_warehouse.store_remask(合约货主备注,按 store_id+warehouse_id 匹配);无合约或备注为空时回退 wms_store.company_name(公司全称);两者均查不到时返回空字符串 ''。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.list 一条(response.rows 描述新增 store_name 货主名称与解析口径,description/notes 同步;params/errors/headers/鉴权不变);根版本 0.3.219 → 0.3.220、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-list-filters", + "date": "2026-10-01", + "type": "updated", + "summary": "stock.check.list 查询条件扩展:修复 type 筛选不生效,新增 mode/货主 store_id/创建时间 created_at/盘点开始时间 start_time/盘点结束时间 end_time 筛选(时间支持单值 gte 与 [from,to] 区间)", + "methods": [ + "stock.check.list" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#list(新增 type/mode 枚举筛选与 created_at/start_time/end_time 时间筛选,status/store_id/keyword 已有不变)与 app/service/systemMethods/stock/check.js#list(prepareWhereContext 提取 where,支持 {operator,value} 标准结构);未改动任何业务代码。", + "修复点:原方法层 list 未从 where 提取 type(where.type 传入不生效);本次方法层补齐 type/mode/created_at/start_time/end_time 提取(whereValue 优先、data 顶层字段兜底兼容),status/keyword 已有逻辑不变。", + "筛选口径:status/type/mode 单值 eq、数组 in(归一化去重);store_id 数值 eq;keyword 对 check_no/title 模糊匹配;全部筛选叠加仓库隔离(ctx.user.store_id)。", + "时间范围语义:created_at/start_time/end_time 口径一致——单值=gte 从该值起;[from,to] 两端合法=between 闭区间、仅 from=gte、仅 to=lte;非法时间值静默忽略。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.list 一条(params 新增 where.type/where.mode/where.created_at/where.start_time/where.end_time);根版本 0.3.218 → 0.3.219、updatedAt 更新为 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;写入 JSON 后同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-time-fields", + "date": "2026-09-30", + "type": "updated", + "summary": "盘点主表移除盘点日期 check_date,改用 start_time(第一个盘点明细写入时间)/end_time(完成盘点时间)表达盘点时间线;导出 Sheet1 移除盘点日期列", + "methods": [ + "stock.check.create", + "stock.check.patternCreate", + "stock.check.report", + "stock.check.finish", + "stock.check.detail", + "stock.check.result", + "stock.check.list", + "stock.check.export" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js——create/patternCreate 不再写 check_date;_formatCheckRow 不再返回 check_date(保留 start_time/end_time);report 首次写入明细时主表 start_time 为空则补写(盘点开始时间=第一个盘点明细写入的时间);finish 写 end_time(盘点结束时间=完成盘点的时间);_generateAndUploadStockCheckExcel 的 Sheet1 表头已移除「盘点日期」列(保留开始时间/结束时间列)。", + "迁移文件:database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js——移除 wms_stock_check 的 check_date 字段与 idx_warehouse_check_date 联合索引,start_time/end_time 注释对齐新语义(类型不变);本地与生产均已执行。", + "语义口径:盘点时间线由 start_time/end_time 表达——start_time=盘点开始时间(第一个盘点明细写入的时间,report 首次写入明细时补写)、end_time=盘点结束时间(完成盘点的时间,finish 时写入);create/patternCreate 均不传盘点时间。", + "接口兼容性影响:create/patternCreate 响应移除 check_date 字段(主表已无该字段);detail/result/list 返回主表行的字段清单移除 check_date;finish 响应结构不变(不返回 end_time,语义体现在主表回填与 description);export Sheet1 列移除「盘点日期」(保留开始/结束时间列);入参、errors、headers、鉴权(isNeedAuth=false、isNeedLogin=true)均不变;未改动任何业务代码。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 8 条(create/patternCreate/report/finish/detail/result/list/export);根版本 0.3.217 → 0.3.218、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 10 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-create-no-date", + "date": "2026-09-30", + "type": "updated", + "summary": "create 移除 check_date 入参,盘点日期固定为今天(与 patternCreate 口径一致)", + "methods": [ + "stock.check.create" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#create——入参解析已无 check_date(仅 warehouseId/title/type/mode/storeId/remark/creatorId/creatorName),checkDateValue = new Date() 后 setHours(0,0,0,0) 固定今天 00:00:00 写入主表 check_date;app/service/systemMethods/stock/check.js#create——data 解构已无 check_date,JSDoc 同步「盘点日期固定为今天,前端不传」;与 patternCreate 口径一致(systems 层 #patternCreate 同样 setHours(0,0,0,0) 固定今天)。", + "规则口径:盘点日期固定为今天 00:00:00,前端不传 check_date(响应中仍返回 check_date 字段);创建后主表 status=created、detail_status=none_checked,其余创建口径(单号生成、范围类型语义、盘点方式规则)均不变。", + "接口兼容性影响:params 移除 check_date(原为必填项,现前端不传;若前端仍传会被方法层忽略,不影响接口可用性与既有调用);errors 400 文案移除「盘点日期不能为空且格式必须合法」;headers/response 结构/鉴权(isNeedAuth=false、isNeedLogin=true)均不变;未改动任何业务代码。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.create 一条(params 移除 check_date、description/notes/errors 同步口径);根版本 0.3.216 → 0.3.217、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-location-blind-only", + "date": "2026-09-30", + "type": "updated", + "summary": "create 按库位盘点(all/location)一律盲盘,忽略前端传入的 mode;按商品盘点(store/goods)仍按传入值", + "methods": [ + "stock.check.create" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#create——normalizedType 校验通过后,type 为 all/location 时强制 normalizedMode='blind'(忽略前端传入的 mode);type 为 store/goods 时保持传入值(缺省 open);method 层 JSDoc 已同步该口径(按库位盘点一律盲盘)。", + "规则口径:按库位盘点(type=all/location,明细为库位行 scope_type=location)一律盲盘(blind),前端传入的 mode 不生效;按商品盘点(type=store/goods,明细为商品行 scope_type=goods)按传入值,默认明盘(open)。", + "接口兼容性影响:mode 仍为可选字符串参数(open/blind),入参结构、必填项、响应结构、errors、headers、鉴权(isNeedAuth=false、isNeedLogin=true)均不变;仅 all/location 场景服务端强制覆盖 mode 为 blind(前端传 blind 行为不变,传 open 落库值为 blind),对既有调用完全兼容。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.create 一条(mode 参数描述补充规则、notes 补充规则说明);根版本 0.3.215 → 0.3.216、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);未改动任何业务代码。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-pattern-fixed-mode", + "date": "2026-09-30", + "type": "updated", + "summary": "patternCreate 移除 mode/check_date 入参:库位类定式一律盲盘、商品类定式一律明盘,盘点日期固定为今天", + "methods": [ + "stock.check.patternCreate" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#patternCreate(入参仅 pattern_id/patternId 驼峰别名/title/remark,不再解析 mode/check_date)+ app/service/systems/stock_check.js#patternCreate(normalizedMode=pattern.type==='location'?'blind':'open';checkDateValue=new Date() 后 setHours(0,0,0,0) 固定今天;主表 mode/check_date 直接取服务端固定值)。", + "固定规则:库位类定式(type=location,即 empty_location)一律盲盘(blind)、商品类定式(type=goods,其余 4 个定式)一律明盘(open);盘点日期固定为今天 00:00:00;前端不再传 mode/check_date。", + "接口兼容性影响:params 移除 mode/check_date 两个可选参数(前端若仍传会被忽略,不影响接口可用性与既有调用);errors 400 文案移除「盘点方式不合法,仅支持 open/blind」与「盘点日期格式不合法」;headers/response 结构/鉴权(isNeedAuth=false、isNeedLogin=true)均不变。", + "文档变更范围:methods/system.json 的 stock.check.patternCreate 条目更新(description/params/errors/notes);根版本 0.3.214 → 0.3.215、updatedAt 保持 2026-09-30;methods/changes/system.json 插入本条(数组首位);未改动任何业务代码。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-patterns", + "date": "2026-09-30", + "type": "added", + "summary": "新增定式快速创建盘点任务:patternList 拉取 5 个注册定式(空库位/错发/临期/静态/预警),patternCreate 按定式 id 收集对象创建盘点任务并直接进入待审核(submitted);静态盘点写入 wms_stock_static_check_task 并排除已盘商品", + "methods": [ + "stock.check.patternList", + "stock.check.patternCreate" + ], + "notes": [ + "代码依据:app/service/systems/stock_check_patterns.js(STOCK_CHECK_PATTERNS 注册 5 个定式 empty_location/mis_shipment/expiring/static/warning,collectEmptyLocation/collectMisShipment/collectExpiring/collectStatic/collectWarning 五个收集函数)+ app/service/systems/stock_check.js#patternList/#patternCreate(收集对象、创建主表 status=submitted、写明细、static 写 wms_stock_static_check_task)+ app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 18 个含 patternList/patternCreate;patternList 在免日志清单 _noNeedLog;warehouseId/创建人从登录上下文注入;统一 _call 捕获业务错误码)。", + "5 个定式口径(与 stock_check_patterns.js 代码注释一致):空库位=启用且未删除、在 wms_storage 不存在 quantity>0 库存的账面空库位(type=location,其余为 goods);错发=登记过错发工单(wms_after_sale type=order+sub_type=mis_shipment,排除 closed/cancelled)关联订单商品按 stock_id 去重;临期=开启保质期管理且最早到期日 <= 当前时间+remaining_threshold_days 天(阈值 <=0 按已到期)的商品;静态=最后一次 INBOUND/OUTBOUND 流水距今超过 stock_static_hours 小时(默认 168,无流水按建档时间)且未进入 wms_stock_static_check_task 的商品;预警=quantity < stock_warning_quantity 的商品(需仓库配置 stock_warning_enabled=true,未开启报 400「未开启库存预警」)。", + "状态口径:patternCreate 创建后主表 status 直接 submitted(进入待审核)、detail_status=none_checked、total_items 按明细重算,无需再调 stock.check.submit;无符合条件对象报 400(location 型报「当前仓库没有账面为空的库位」,goods 型报「没有符合条件的商品」)。", + "静态记录表口径:收集阶段排除 wms_stock_static_check_task 已有记录(未删除)的 stock_id(已进入静态已盘点商品);任务创建成功后把命中 stock_id 批量写入该表(task_time=创建时间),写入失败仅告警不影响主流程。", + "权限口径:两个新 method 均随 ALL_METHOD_NAMES(18 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权,必须登录(isNeedLogin=true);patternList 为查询类在免日志清单(_noNeedLog)不记操作日志,patternCreate 为写操作保留操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.patternList/patternCreate 两条(追加在 exportTaskProgress 之后,与代码 ALL_METHOD_NAMES 顺序一致);根版本 0.3.213 → 0.3.214、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);未改动任何业务代码。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-operation-log", + "date": "2026-09-30", + "type": "updated", + "summary": "库存盘点 10 个写操作补齐业务操作日志:成功路径写入 wms_operation_log(businessType=stock_check,operationCode STOCK_CHECK_*),失败不写、日志异常不影响主流程", + "methods": [ + "stock.check.create", + "stock.check.addDetail", + "stock.check.detailDelete", + "stock.check.report", + "stock.check.recordDelete", + "stock.check.finish", + "stock.check.submit", + "stock.check.cancel", + "stock.check.audit", + "stock.check.batchDelete" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js 的 10 个写操作(create/addDetail/detailDelete/report/recordDelete/finish/submit/cancel/audit/batchDelete)在主流程写入成功后调用 ctx.service.systems.operationLog.createOperationLog 写入 wms_operation_log(businessType=stock_check);operationCode 前缀 STOCK_CHECK_*,对应 CREATE/ADD_DETAIL/DELETE_DETAIL/REPORT/DELETE_RECORD/FINISH/SUBMIT/CANCEL/AUDIT/BATCH_DELETE;operationAction 对应 CREATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/DELETE。", + "日志口径:businessId=盘点任务 id(create 取新建记录 plainRecord.id,其余取 checkId);operator 取登录上下文 ctx.user(id=employees_id 回退 user.id,name=employees_name);extras 统一携带 warehouseId、checkNo(create 用 plainRecord.check_no)与 message,report/finish/audit/batchDelete 等另带业务关键字段(明细/库位/实盘数量、差异/盘盈/盘亏、审核动作与原因、deletedIds/skippedIds 等);changeSummary 为中文变更描述。", + "batchDelete 特殊口径:仅删除集非空(deletedIds.length>0)时写日志(全跳过不写);businessId 取首个删除 id(deletedIds[0]);extras 附 deletedIds/skippedIds/deletedCount/skippedCount;日志在事务提交后写入,不随事务回滚残留。", + "失败不写与降级:10 个日志调用点全部位于主流程成功路径之后(各写操作失败时先抛业务错误码 400,不会执行到日志写入);createOperationLog 内部 try/catch,日志写入失败仅记录 error 日志并返回 null,不影响主流程(业务已提交的变更不受日志失败影响)。", + "接口契约不变:本次仅服务层行为变更(补充业务操作日志),10 个 method 的入参/响应/错误码/鉴权均未变化,methods/system.json 接口条目与根版本号均不修改(不 bump);本条仅追加到 methods/changes/system.json 数组首位;changes 不入库表,无需回填 wms_api_method_doc。" + ] + }, + { + "version": "2026.09.30-stock-check-doc-polish", + "date": "2026-09-30", + "type": "updated", + "summary": "盘点接口文档文案修正:detail 字段计数 14→15、result 权限注释方法数 15→16、recordList/detailDelete 免日志清单补 result、export errors 补「未找到可导出的盘点任务」400", + "methods": [ + "stock.check.detail", + "stock.check.result", + "stock.check.recordList", + "stock.check.detailDelete", + "stock.check.export" + ], + "notes": [ + "修正点明细:① stock.check.detail 的 description/response/notes 中「纯范围行 14 字段」改为「15 字段」(_formatDetailScopeRow 实际枚举 id/check_id/warehouse_id/scope_type/stock_id/location_id/location_code/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at 共 15 个,枚举清单原本完整,仅计数文案错误);② stock.check.result notes 首条「随 ALL_METHOD_NAMES(15 个)免 API 权限」改为「16 个」;③ stock.check.recordList 与 stock.check.detailDelete 的免日志清单枚举补 result;④ stock.check.export errors 补 400「未找到可导出的盘点任务」。", + "代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 共 16 个:create/list/addDetail/detailDelete/detail/result/report/recordList/recordDelete/finish/submit/cancel/audit/batchDelete/export/exportTaskProgress;_noNeedLog='list,detail,result,recordList,export,exportTaskProgress';export 超 50 上限校验)+ app/service/systems/stock_check.js#_formatDetailScopeRow(15 字段返回对象)与 #exportStockChecks(checks.length===0 时抛「未找到可导出的盘点任务」400)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.detail/result/recordList/detailDelete/export 五条;根版本 0.3.212 → 0.3.213、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);仅文档文案与错误码清单修正,未改动任何业务代码。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-wavePickTaskDetail-pick-requirements", + "date": "2026-09-30", + "type": "updated", + "summary": "pick.wavePickTaskDetail 的 picking_view.items 新增 pick_requirements(拣货要求),团购形态(pick_mode=1/5)不返回 picking_details,前端改由 items 展示拣货要求", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "代码依据:app/service/systems/pick.js#buildPickingView——items 聚合行新增 pick_requirements,取值自商品资料链路(getStockDetails)的 stock.pick_requirements(merge_requirements=Y 时已按打包要求回退),空值兜底为空字符串。", + "背景:团购小波次/大波次(pick_mode=1/5)不返回 picking_details,此前 picking_view.items 缺拣货要求字段,前端无法展示拣货要求。", + "picking_view.items 其余字段不变;picking_details 的 stock 对象本就含该字段,本次仅补齐 items 层。", + "文档变更范围:methods/system.json 的 pick.wavePickTaskDetail 响应 picking_view.items 新增 pick_requirements 字段描述;根版本 0.3.211 → 0.3.212、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "2026.09.30-stock-check-batch-delete", + "date": "2026-09-30", + "type": "added", + "summary": "新增 stock.check.batchDelete:批量删除盘点任务(入参 ids,上限 200),仅作废(cancelled)任务删除,非作废任务跳过;级联删除作业记录与明细(事务)", + "methods": [ + "stock.check.batchDelete" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#batchDelete(入参归一化 _normalizeIdList:单值兼容、去重、正整数过滤、上限 200;仓库隔离查询主表 id in ids + warehouse_id;状态分流与级联删除事务)+ app/service/systemMethods/stock/check.js#batchDelete(ALL_METHOD_NAMES 扩为 16 个含 batchDelete;warehouseId 从登录上下文注入;走统一 _call 捕获业务错误码)。", + "状态分流口径:仅 status=cancelled(作废)任务执行删除;其他状态及仓库内查不到的任务跳过(计入 skipped_ids,保持入参顺序),不报错。", + "级联删除顺序(事务内):先删作业记录(wms_stock_check_record where check_id in 删除集),再删明细(wms_stock_check_detail where check_id in 删除集),最后删主表(wms_stock_check where id in 删除集)。", + "权限口径:batchDelete 随 ALL_METHOD_NAMES(16 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true);为写操作,不在免日志清单 _noNeedLog,保留操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.batchDelete(插入 audit 之后,与代码 ALL_METHOD_NAMES 顺序一致);根版本 0.3.210 → 0.3.211、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-wavePickTaskDetail-pick-mode-enum", + "date": "2026-09-30", + "type": "updated", + "summary": "pick.wavePickTaskDetail 响应 task.pick_mode 描述补全枚举:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "原描述仅「拣货模式」,缺少 pick_mode=5 为大团购(团购大波次)的枚举说明;现与 pick.query、order.recheckOrder 等接口的 pick_mode 描述对齐。", + "仅更新 methods/system.json 的 pick.wavePickTaskDetail 响应字段描述,不修改任何业务实现。" + ] + }, + { + "version": "2026.09.30-stock-check-export-records", + "date": "2026-09-30", + "type": "updated", + "summary": "盘点导出口径调整:Sheet2 导出盘点明细(作业记录:一行一条实际盘点记录,含商品/库位/实盘数量/盘点人/时间),不再导出任务明细(未盘范围行)", + "methods": [ + "stock.check.export" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#exportStockChecks/_generateAndUploadStockCheckExcel——Sheet2 直接拉 wms_stock_check_record 作业记录(不按任务范围行展开,任务明细与未盘范围行不导出),商品快照(item_code/item_name)从 wms_stock_warehouse 补齐,totalCount=作业记录总数;app/service/systemMethods/stock/check.js#export 异步任务入口与 Redis 进度缓存机制不变。", + "口径变化:Sheet2「盘点明细」由「按任务范围行展开(含未盘空行,账面按 wms_storage 现算)」改为「一行一条实际盘点记录(作业记录)」——列:盘点单号/商品编码/商品名称/库位编码(空库位输出为空)/实盘数量/盘点人/盘点时间;未盘的任务范围行不再导出;进度 totalCount=作业记录总数(导出前即确定),进度按已写明细行数/总数计算。", + "Sheet1 不变说明:Sheet1「盘点单」保持一行一个盘点任务(盘点单号/盘点名称/盘点范围/盘点方式/盘点状态/盘点进度/盘点日期/货主ID/创建人/明细行数/已盘行数/差异行数/开始时间/结束时间/备注)。", + "文档变更范围:methods/system.json 的 stock.check.export 更新 description/response(total_count/current_count 口径)/notes;根版本 0.3.208 → 0.3.209、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-stock-check-detail-result-split", + "date": "2026-09-30", + "type": "updated", + "summary": "任务明细与盘点结果接口拆分:detail 只返回任务范围行(商品/库位),新增 result 返回盘点结果聚合(商品行 checked/diff/records/locations,库位行 stocks 按商品聚合账面查 wms_storage)", + "methods": [ + "stock.check.detail", + "stock.check.result" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 15 个含 result;新增 result() 从登录上下文注入 warehouseId、入参 id、走统一 _call 捕获业务错误码;_noNeedLog 扩为 list/detail/result/recordList/export/exportTaskProgress)+ app/service/systems/stock_check.js(detail() 改为只返回纯范围行(_formatDetailScopeRow 14 字段,不再调 _buildDetailAggregations);新增 result() 查询全部明细与作业记录后调 _buildDetailAggregations/_formatDetailAggregationRow 聚合)。", + "拆分口径:detail 只返回任务范围行(商品/库位原始字段 14 个,不含任何盘点作业聚合);新增 result 返回盘点结果聚合——商品行 checked_quantity/diff_quantity/is_diff/status/location_codes/checkers/last_checked_at + records + locations,库位行 checked_quantity(行级合计)/diff_quantity(差异代数和)+ records/locations + stocks(按商品聚合,账面查 wms_storage)。", + "接口兼容性影响:旧 detail 的商品行聚合字段(checked_quantity/diff_quantity/is_diff/status/location_codes/checkers/last_checked_at)、records、locations 与库位行 stocks 全部迁移到新接口 result;detail 仅用于任务范围行展示,需要盘点结果的调用方改调 stock.check.result(入参同为 id,返回同为 { check, rows, total })。", + "权限口径:result 随 ALL_METHOD_NAMES(15 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true);为查询类方法,加入免日志清单 _noNeedLog。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.result(放在 detail 之后,与代码 ALL_METHOD_NAMES 顺序一致)、更新 stock.check.detail 的 description/response/notes(纯范围行 14 字段,移除聚合字段描述);根版本 0.3.207 → 0.3.208、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-stock-check-add-detail-compat", + "date": "2026-09-30", + "type": "updated", + "summary": "addDetail 兼容历史任务:type=all 且已存在商品明细行(改造前创建)时继续按商品模式接受 stock_ids,避免旧调用 400;全新 type=all 任务维持按库位语义", + "methods": [ + "stock.check.addDetail" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#addDetail——type=all 且 wms_stock_check_detail 已存在 scope_type='goods' 明细行(count>0)时置 isGoodsScope=true/isLocationScope=false,继续按商品模式接受 stock_ids;全新 type=all 任务维持按库位语义;入参维度互斥校验的库位错误文案更新为『当前盘点类型按库位盘点,请传 locations(如需按商品盘点请创建 type=goods 任务)』。", + "兼容判定口径:以 wms_stock_check_detail 中 check_id 对应 scope_type='goods' 行是否存在为准(改造前 type=all 任务按商品添加明细,明细行 scope_type='goods');仅 type=all 任务走兼容判定,store/goods/location 类型判定逻辑不变。", + "新任务语义保持:全新 type=all 任务(无任何商品明细行)维持按库位盘点语义——传 stock_ids 报 400『当前盘点类型按库位盘点,请传 locations(如需按商品盘点请创建 type=goods 任务)』;历史任务(按商品模式)传 locations 报 400『当前盘点类型按商品盘点,请传 stock_ids』。", + "文档变更范围:methods/system.json 的 stock.check.addDetail 更新 description/errors/notes(历史任务兼容口径 + 库位错误码文案);根版本 0.3.206 → 0.3.207、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-stock-check-location-scope", + "date": "2026-09-30", + "type": "updated", + "summary": "盘点明细支持商品/库位两种范围行:all/location 按库位盘点、store/goods 按商品盘点;添加商品限制非本货主商品;库位行作业上报指定商品,账面来源 wms_storage", + "methods": [ + "stock.check.create", + "stock.check.addDetail", + "stock.check.report", + "stock.check.detail", + "stock.check.finish", + "stock.check.export" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js(create/addDetail/_addGoodsDetailRows/_addLocationDetailRows/detail/_buildDetailAggregations/report/finish/exportStockChecks)+ app/service/systemMethods/stock/check.js(入参透传与 locations/location_codes、stock_id 兼容)+ app/model/stock_check_detail.js / app/model/stock_check_record.js(模型与索引定义)。", + "迁移文件:database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js(本地+生产已执行)——明细表新增 scope_type/location_id/location_code、stock_id/item_code 改可空、防御性合并重复明细并新增唯一索引 uk_check_stock(check_id, stock_id) 与 uk_check_location(check_id, location_code);记录表移除 uk_detail_location(detail_id, location_code)、防御性合并重复记录并新增 uk_detail_stock_location(detail_id, stock_id, location_code)(覆盖式语义升级为同明细+同商品+同库位)。", + "语义变化明细:①create.type 语义明确——all=按库位盘点(未传库位自动全仓库启用库位生成范围)/ location=按库位盘点 / store=按货主按商品盘点 / goods=按商品盘点;②addDetail 新增 locations 入参(兼容 location_codes),按任务 type 与 stock_ids 二选一,响应新增 invalid_locations,商品货主必须与任务 store_id 一致否则计入 invalid_stock_ids;③report 新增可选 stock_id 入参(库位行必填且商品须本仓库),覆盖式查重升级为 detail_id+stock_id+location_code;④detail 库位行输出 scope_type='location' + stocks 数组(按商品聚合,账面查 wms_storage);⑤finish 库位行账面来源 wms_storage(space_id+stock_id SUM(quantity));⑥export Sheet2 按盘点项展开(goods 1 行、location 按商品 N 行)。", + "接口兼容性影响:向后兼容——create.type 枚举不变(all/store/goods/location);addDetail 原 stock_ids 入参与响应字段保留(新增 invalid_locations,非法商品仍走 invalid_stock_ids);report 原入参不变(stock_id 为新增可选参数,商品行不传保持原行为);detail 商品行响应结构不变(库位行为新输出形态);finish/export 响应结构不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create/addDetail/report/detail/finish/export 六条 description/params/response/errors;根版本 0.3.205 → 0.3.206、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-manual-waybill-express-code", + "date": "2026-09-30", + "type": "updated", + "summary": "order.pendingOrder.manualWaybill 新增可选参数 express_code:传入时同步修改订单的快递编码,行为参考 updateOrderExpress", + "methods": [ + "order.pendingOrder.manualWaybill" + ], + "notes": [ + "代码依据:app/service/systemMethods/order/pendingOrder.js#manualWaybill 新增可选入参 express_code(string,选填,trim 后为空视为未传);传入时参考 updateOrderExpress 的解析口径——从当前仓库快递列表(带缓存 getExpressList)中查找对应项,不存在则抛『快递编码 不存在』;自定义映射(is_system_setting=true)时订单 sys_logistics_code/name 写系统快递编码和名称、logistics_code/name 写自定义编码和名称,系统快递(is_system_setting=false)时四个字段均写系统快递的 code/name;不传时保持原行为(运单记录沿用订单当前 sys_logistics_code/name)。", + "写入范围:传入 express_code 时,订单表同步更新 sys_logistics_code/sys_logistics_name/logistics_code/logistics_name 四字段(与 print_status/post_status='fin' 同一次 update),运单记录(wms_order_express)的 logistics_code/logistics_name 写入解析后的新值;不传时运单记录沿用订单原系统快递字段。", + "操作日志:extras 新增 expressCode/sysLogisticsCode/sysLogisticsName/logisticsCode/logisticsName 字段,message 在传入 express_code 时补充快递信息。", + "响应:传入 express_code 时额外返回 express_code、sys_logistics_code、sys_logistics_name、logistics_code、logistics_name;不传时响应结构与原版本一致(向后兼容)。", + "文档变更范围:methods/system.json 的 order.pendingOrder.manualWaybill 更新 description、params 新增 express_code、response 新增 5 个可选字段、errors 新增 404 快递编码不存在;根版本 0.3.204 → 0.3.205、updatedAt 更新为 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。" + ] + }, + { + "version": "2026.09.29-stock-check-no-global-sequence", + "date": "2026-09-29", + "type": "updated", + "summary": "盘点单号改为全局递增:generateCheckNo 移除按仓库隔离(uk_check_no 全局唯一索引下按仓从 1 起会跨仓撞号),create 撞唯一键自动重取重试最多 5 次,口径与收货单 receiving_number 一致", + "methods": [ + "stock.check.create" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#generateCheckNo 移除 warehouse_id 隔离条件,改为查询全局最大 PD+YYYYMMDD 前缀单号取末尾 6 位序号 +1;新增 isCheckNoDuplicateError()(parent.code==='ER_DUP_ENTRY' 且 sqlMessage 命中 uk_check_no/check_no,参照收货单 isReceivingNumberDuplicateError 口径);create() 撞唯一键自动重取单号重试最多 5 次(与收货单 create 重试口径一致),超过重试次数或非单号冲突错误原样抛出。", + "原因说明:uk_check_no 为全局唯一索引(不区分仓库),原按仓库隔离序号各自从 1 起会跨仓撞号;改为全局递增后并发创建仍有极小概率撞号,由唯一键重试兜底。", + "收货单参照口径:与收货单 receiving_number 一致——按全局最大序号 +1 生成 + 撞唯一键自动重取重试。", + "并发重试说明:每次重试都重新调用 generateCheckNo() 取最新全局最大序号;仅 ER_DUP_ENTRY 且命中 uk_check_no 才重试,其它错误直接抛出。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create 的 description 与 notes;根版本 0.3.203 → 0.3.204、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.29-stock-check-detail-delete", + "date": "2026-09-29", + "type": "added", + "summary": "新增 stock.check.detailDelete:删除盘点明细(从任务移除商品),仅 created/rejected 状态允许,删除时防御性清理作业记录并重算 total_items", + "methods": [ + "stock.check.detailDelete" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 14 个含 detailDelete;detailDelete 从登录上下文注入 warehouseId,入参 id + detail_id(兼容 detailId 驼峰,detail_id 优先),走统一 _call 捕获业务错误码;为写操作,不在免日志清单 list/detail/recordList/export/exportTaskProgress 中)、app/service/systems/stock_check.js(detailDelete:id/detail_id 非法抛 400『盘点任务ID不能为空/盘点明细ID不能为空』,任务不存在/明细不存在分别抛 400;仅 ADD_DETAIL_ALLOWED_STATUSES(created/rejected)允许删除,否则 400『当前状态(xxx)不允许删除明细』;删除明细后防御性清理 wms_stock_check_record 并重算主表 total_items;返回 { detail_id, deleted:true, total_items })。", + "状态限制口径:仅主表 created/rejected 允许删除明细(与 addDetail 口径一致,共用 ADD_DETAIL_ALLOWED_STATUSES);其它状态返回 400。", + "防御清理说明:正常流程 created/rejected 状态不应存在作业记录,但为兜底,删除明细时按 { detail_id, check_id, warehouse_id } 一并删除 wms_stock_check_record 中的关联记录,避免残留孤儿记录;删除后重算主表 total_items。", + "权限口径:随 ALL_METHOD_NAMES 免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true,免登录清单为空);detailDelete 为写操作,记录操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.detailDelete(放在 addDetail 之后,与代码 ALL_METHOD_NAMES 顺序一致);根版本 0.3.202 → 0.3.203、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次先按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON,随后同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.29-stock-check-record-unique-index", + "date": "2026-09-29", + "type": "updated", + "summary": "盘点作业记录表加固:location_code 空串归一 + 历史重复合并 + 唯一索引 uk_detail_location(detail_id, location_code),从数据库层保证 report 覆盖式上报并发安全;接口返回口径不变(空库位 location_code 仍为 null)", + "methods": [ + "stock.check.report", + "stock.check.recordList" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js(report 未传库位归一存空串 '';查重条件统一 { detail_id, location_code };依赖数据库层唯一索引 uk_detail_location 保证并发安全;recordList 返回 location_code 空串归一为 null;detail 的 locations/location_codes 输出口径不变,空库位组 location_code=null)、app/model/stock_check_record.js(location_code allowNull=false defaultValue='')。", + "迁移:database/migrations/20260929130000-unique-stock-check-record-detail-location.js——location_code 归一 NULL→''、合并历史重复记录(同 detail_id+location_code 保留 id 最大一条)、列改 NOT NULL DEFAULT ''、新增唯一索引 uk_detail_location(detail_id, location_code);本地与生产均已执行。", + "口径变化:report 未传库位不再存 NULL 而是存空串 ''(\"无库位\"分组),覆盖式查重条件不变({ detail_id, location_code },含空串分组),并发下由唯一索引兜底不产生重复记录。", + "接口兼容性:对外返回口径不变——recordList 将空串归一为 null、detail 的 locations/location_codes 空库位组 location_code 仍为 null,客户端无需调整。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.report 的 description/notes 与 location 入参描述、stock.check.recordList 的 rows response 描述与 notes(空串归一 null 口径);根版本 0.3.201 → 0.3.202、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。" + ] + }, + { + "version": "2026.09.29-stock-check-work-adjust", + "date": "2026-09-29", + "type": "updated", + "summary": "盘点作业接口 5 项调整:report 改为覆盖式(同明细+同库位重复上报更新已有记录)、新增 recordDelete(删作业记录重算汇总)与 recordList(分页查作业记录)、detail rows 增加按库位聚合 locations、finish 放宽未盘校验(未盘按实盘 0 计盘亏并返回 unchecked_items)", + "methods": [ + "stock.check.report", + "stock.check.detail", + "stock.check.finish", + "stock.check.recordDelete", + "stock.check.recordList" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 13 个含 recordList/recordDelete;免权限/免鉴权清单共用全部方法,免日志清单为 list/detail/recordList/export/exportTaskProgress;recordDelete 入参兼容 record_id/recordId 写法)、app/service/systems/stock_check.js(report 覆盖式上报:同 detail_id + 同 location_code(含同为空库位 location_code 为 NULL)更新已有记录 quantity/checker_id/checker_name/checked_at 并保留/回填 location_id,否则新增,返回 mode=created|updated;recordList 按 id DESC 分页返回记录全字段 + item_code/item_name;recordDelete 仅 approved/checking 状态、删除后重算汇总且主表状态不回退;detail rows 增加 locations 按库位聚合;finish 未盘明细按实盘 0 计盘亏并返回 unchecked_items)。", + "行为口径变化明细:①stock.check.report 从每次新增一条记录改为覆盖式——同 detail_id + 同 location_code(含同为空库位)重复上报更新已有记录(quantity/checker/checked_at),首次上报才新增,返回 mode=created|updated;②新增 stock.check.recordDelete:入参 id + record_id(兼容 recordId),仅 approved/checking 状态允许,删除后重算 total_items/checked_items/diff_items/detail_status(明细记录删光后回到未盘),主表状态不回退,返回 { record_id, deleted:true, ...summary };③新增 stock.check.recordList:入参 id(可选)+ detail_id(可选)+ pagination 至少传其一,返回 { rows, total, page, pageSize },rows=记录全字段 + item_code/item_name,按 id DESC;④stock.check.detail rows 每条新增 locations 数组(按库位聚合 [{ location_id, location_code, quantity }],空库位归 location_code=null 组),records 与既有聚合字段不变;⑤stock.check.finish 不再拦截未盘明细,未盘按实盘 0 处理(diff=-账面快照,计盘亏与 diff_items),返回新增 unchecked_items 字段。", + "无 schema 变更:本次仅业务行为调整,wms_stock_check / wms_stock_check_detail / wms_stock_check_record 表结构未变,无需数据库迁移。", + "权限口径:recordList/recordDelete 与同分组其它方法一致——免 API 权限(isNeedAuth=false)、免仓库有效期鉴权、必须登录(isNeedLogin=true);recordList 为查询类免操作日志,recordDelete 为写操作记录操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.recordList、stock.check.recordDelete 两条 method,更新 stock.check.report/detail/finish 三条 description 与 response(report 增加 mode 字段、detail rows 增加 locations 聚合、finish 增加 unchecked_items 并移除未盘拦截错误);根版本 0.3.200 → 0.3.201、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。" + ] + }, + { + "version": "2026.09.29-storage-entry-bindReceiving-soft-deleted-restore", + "date": "2026-09-29", + "type": "fixed", + "summary": "storage.entry.bindReceiving 修复解绑后重新绑定失败:CREATED 分支改用三态幂等(已存在跳过/软删除恢复/新建),不再因软删除残留行撞唯一索引报 BINDING_WRITE_FAILED(Validation error)", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "根因:findOrCreate 查询默认排除软删除行(paranoid),解绑(unbindReceiving 软删除主表绑定行)后再次绑定同一 (entry_order_id, receiving_id) 时,create 撞唯一索引 uk_entry_order_receiving 抛 SequelizeUniqueConstraintError(message 为 \"Validation error\"),被捕获计入 skipped 并返回 BINDING_WRITE_FAILED。生产现场:绑定行 id=793(入库单 1280 RK202609290005 ↔ 收货单 4686 R20725003)于 2026-09-28 19:02 解绑软删除,2026-09-29 重新绑定即失败。", + "修复:app/service/systems/receiving_entry_match.js 的 bindEntryOrderReceiving CREATED 分支改为 paranoid:false 查询三态处理——未删除已存在跳过(created=false)、已软删除则 allocated_quantity 重置为 {} 并 restore(restored=true)、不存在新建(create 唯一索引冲突视为并发已建立,created=false);bound 项统一返回 created/restored 两字段。", + "同类加固:_commitBinding(PDA 上架确保主表绑定)的 findOrCreate 同步改为三态;_bindEntryOrderReceiving(自动匹配)与 _bindOneReceivingAndSyncStorage(COMPLETED)恢复软删除行时显式 allocated_quantity={} 兜底、软删除判断兼容 deletedAt/deleted_at 两种属性名。", + "文档变更范围:methods/system.json storage.entry.bindReceiving 的 bound.created/restored 描述更新、restored required 改为 true;根版本 0.3.199 → 0.3.200、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。" + ] + }, + { + "version": "2026.09.29-stock-check-detail-split", + "date": "2026-09-29", + "type": "updated", + "summary": "盘点明细表拆分:wms_stock_check_detail 仅保留盘点商品(stock_id+快照),库位/数量信息下沉到新建 wms_stock_check_record(盘点作业记录表);report 改为写入记录(同明细可多库位多次上报),已盘口径=存在记录,差异=记录数量合计-账面快照;detail 返回 records 与聚合字段;导出明细行含库位合并/盘点人合并。", + "methods": [ + "stock.check.report", + "stock.check.detail", + "stock.check.finish", + "stock.check.export", + "stock.check.exportTaskProgress" + ], + "notes": [ + "代码依据:app/model/stock_check_detail.js(明细表仅存盘点商品:stock_id+商品快照,移除 location_id/location_code/check_quantity/diff_quantity/is_diff/status/checker_id/checker_name/checked_at)、app/model/stock_check_record.js(新建盘点作业记录表:check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark,一个明细可在多库位多次上报)、app/service/systems/stock_check.js(report 写入记录不再更新明细;detail 返回 records 与聚合字段;finish 未盘=无记录明细、差异按记录聚合;export Sheet2 商品级聚合+库位/盘点人合并)、app/service/systemMethods/stock/check.js(report 从登录上下文注入 checkerId/checkerName)。", + "迁移:database/migrations/20260929120000-split-stock-check-detail-create-record.js(明细表移除 9 个作业字段 + 新建 wms_stock_check_record 及 4 个索引 idx_check_id/idx_detail_id/idx_stock_id/idx_warehouse_location),本地与生产均已执行。", + "口径变化明细:report 每次上报新增一条作业记录(同明细可在多库位多次上报),明细已盘数量=记录 quantity 合计;已盘口径=存在记录(DISTINCT detail_id);差异=记录数量合计-账面快照 system_quantity;detail.rows 返回 checked_quantity/diff_quantity/is_diff/status/location_codes[]/checkers[]/last_checked_at + records[];finish 未盘明细=无记录明细;export Sheet2 明细行(商品级聚合)列为 盘点单号/商品编码/商品名称/规格/账面数量/已盘数量/差异数量/是否有差异/库位编码(顿号合并)/盘点人(合并)/最近盘点时间。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.report/detail/finish/export 共 4 条 method 的 description 与 response;根版本 0.3.198 → 0.3.199、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。" + ] + }, + { + "version": "2026.09.29-stock-check-apis", + "date": "2026-09-29", + "type": "added", + "summary": "新增库存盘点模块 11 个 method(创建空任务/列表/添加明细/拉取明细/盘点作业上报/完成盘点/提交审核/取消/审核/导出/导出进度),完整状态机 created→submitted→approved/rejected→checking→completed/cancelled", + "methods": [ + "stock.check.create", + "stock.check.list", + "stock.check.addDetail", + "stock.check.detail", + "stock.check.report", + "stock.check.finish", + "stock.check.submit", + "stock.check.cancel", + "stock.check.audit", + "stock.check.export", + "stock.check.exportTaskProgress" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js(11 个 method 包装层,统一 _call 包装 400/500)与 app/service/systems/stock_check.js(状态机、单号生成 PD+YYYYMMDD+6位序号、汇总重算、Excel 导出 + COS 上传)。", + "表结构:wms_stock_check(盘点主表,仓库隔离 warehouse_id、盘点单号 check_no 唯一、状态 status、明细进度 detail_status、汇总 total_items/checked_items/diff_items)与 wms_stock_check_detail(盘点明细表,商品/库位快照、账面数量 system_quantity、实盘数量 check_quantity、差异数量 diff_quantity=实盘-账面)。", + "迁移:database/migrations/20260929100000-create-wms-stock-check.js、20260929101000-create-wms-stock-check-detail.js、20260929110000-align-stock-check-status-machine.js(主表 status 默认值 pending → created、注释对齐新状态机),本地与生产均已执行。", + "权限口径:11 个 method 全部免权限/免鉴权(仓库有效期检查)/需登录;list/detail/export/exportTaskProgress 免操作日志;不产生 wms_permission 权限记录,无需执行 permission:sync:system-api。", + "导出任务口径:Redis 进度缓存 key stock_check_export_task_{taskId}、TTL 1800 秒;每任务一个 Sheet(Sheet 名=盘点单号 check_no);单次最多 50 个盘点任务。", + "文档变更范围:methods/system.json 新增分组 module=stock.check(库存盘点模块)共 11 条 method;根版本 0.3.196 → 0.3.197、updatedAt 2026-09-28 → 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。" + ] + }, + { + "version": "2026.09.28-weigh-pack-padding-message", + "date": "2026-09-28", + "type": "updated", + "summary": "散单称重拦截提示区分打包中状态:pack_status=padding 返回「订单打包中」,其余未完成状态返回「订单未打包」", + "methods": [ + "order.updateExpressWeighingWeight", + "workbench.sendWeight" + ], + "notes": [ + "代码依据:app/service/systems/order_express.js 的 buildWeighPackBlockedMessage(packStatus) 恢复入参,padding 返回「订单打包中」、其余非 fin 状态返回「订单未打包」;assertSingleOrderPackedForWeigh 沿用该文案抛 400。", + "代码依据:app/service/systems/workbench.js 的 _assertSingleWeighPackedForWeigh 复用同一文案,不再固定「订单未打包」。", + "判定规则未变:开启仓库配置 single_weigh_require_pack 后,wave_scope 非 1 大团购/3 小团购的订单 pack_status 非 fin 时拒绝称重;团购波次批量称重不校验。", + "测试:test/single_weigh_require_pack.test.cjs(27 用例,新增打包中文案断言,全部通过)。", + "本次仅提示文案区分,无接口结构变化。" + ] + }, + { + "version": "2026.09.28-order-wave-fetchable-order-count", + "date": "2026-09-28", + "type": "added", + "summary": "新增 order.wave.fetchableOrderCount:统计当前仓库团购可抓取订单数(与 order.wave.groupOrderFetchList 同口径:同一候选条件 + items_hash 粗分组 + 团购阈值过滤),但不分页、不查订单明细,仅返回命中分组数与组内订单数合计。", + "methods": [ + "order.wave.fetchableOrderCount" + ], + "notes": [ + "代码依据:app/service/systemMethods/order/wave.js 新增 async fetchableOrderCount(data)。候选 where 与 groupOrderFetchList 完全一致(step in [1,2,3]、status != cancel、outbound_status != padding、intercept_status='none'、lock_status='none'、wave_id=0,叠加 store_id / shop_name / stock_query 过滤);分组键复用 buildCoarseGroupKey(items_hash 缺省回落 items,distinguish_express=true 时再叠加 sys_logistics_code);阈值同源 getMinGroupOrderFetchQuantity(仓库配置,默认 13);仅取 id/items_hash/items/sys_logistics_code 四列,纯内存计数,不查订单明细。", + "口径差异(重要):groupOrderFetchList 的 pagination.total 是分组数(每组订单数在 item.group_count 内),本方法 order_count 是命中分组的订单数合计、group_count 是命中分组数;include_sku 为 groupOrderFetchList 的页内过滤参数,本方法不参与统计,因此带 include_sku 时两者不保证一致。", + "权限与日志:方法已加入 wave.js systemInit 的 _noNeedRight / _noNeedLog / _noNeedAuth 名单(与 groupOrderFetchList 一致),仅需登录;isNeedAuth=false,不产生 wms_permission 权限记录,无需执行 permission:sync:system-api,也不需要新增迁移。", + "返回结构:成功返回 flag=success/code=1,data 含 group_count / order_count / same_order_quantity / raw_order_count / warehouse_id / distinguish_express;仓库上下文缺失时返回 flag=failure/code=400「未识别到当前仓库上下文」。", + "测试:test/app/service/systemMethods/order/wave.fetchableOrderCount.test.js(8 用例:阈值命中统计、阈值变化、区分快递粒度、store_id+shop_name 进入候选 where、stock_query 空命中短路、仓库上下文缺失 400、默认阈值回落、与 groupOrderFetchList 命中分组订单数合计一致性)。", + "文档变更范围:methods/system.json 在 module=order.wave(订单波次模块)分组 list 末尾新增 1 条 method;根版本 0.3.194 → 0.3.195、updatedAt 2026-09-27 → 2026-09-28;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。" + ] + }, + { + "version": "2026.09.27-weigh-pack-message-simplify", + "date": "2026-09-27", + "type": "updated", + "summary": "散单称重未打包拦截文案简化为固定「订单未打包」(移除打包状态明细与工作台条码后缀)", + "methods": [ + "order.updateExpressWeighingWeight", + "workbench.sendWeight" + ], + "notes": [ + "代码依据:app/service/systems/order_express.js 的 buildWeighPackBlockedMessage() 现返回固定文案「订单未打包」,assertSingleOrderPackedForWeigh 沿用该文案抛 400;原 formatPackStatusText 状态文案方法已移除。", + "代码依据:app/service/systems/workbench.js 的 _assertSingleWeighPackedForWeigh(orderRow, warehouseId) 复用同一文案,不再追加 ` [条码]` 后缀。", + "判定规则未变:开启仓库配置 single_weigh_require_pack 后,wave_scope 非 1 大团购/3 小团购的订单 pack_status 非 fin 时拒绝称重;团购波次批量称重不校验。", + "测试:test/single_weigh_require_pack.test.cjs(26 用例,已按新文案断言)。", + "本次仅文档文案对齐,无接口结构变化。" + ] + }, + { + "version": "2026.09.27-setting-save-big-group-coefficient-doc-fix", + "date": "2026-09-27", + "type": "updated", + "summary": "补 setting.warehouse.saveSettings 入参遗漏的 subject_config.big_group_pack_coefficient(对齐 getSettings/getFieldMeta 与代码实现):大团购波次(wave_scope=1)打包中扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,默认 3,必须大于 0;非法值报 400。", + "methods": [ + "setting.warehouse.saveSettings" + ], + "notes": [ + "代码依据:app/service/systems/setting/warehouse.js#WAREHOUSE_SETTING_FIELDS 已有 key=big_group_pack_coefficient(name=大团购打包系数,type=number,default=3,required=false,min=0.1,description=大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0);app/model/store.js#DEFAULT_SUBJECT_CONFIG.big_group_pack_coefficient=3,normalizeSubjectConfig 对非空值 Number() 后校验有限且 >0,非法抛错 subject_config.big_group_pack_coefficient 必须是大于 0 的数字,空值/null/'' 回落默认 3。", + "历史新增来源:该字段为上一期仓库配置新增(changes 已有记录「仓库设置新增大团购打包系数」,当时同步了 setting.warehouse.getSettings 响应与 getFieldMeta 字段元信息,但遗漏 saveSettings 入参文档);本次为文档补漏修正,仅补齐该遗漏,不涉及任何代码变更。", + "文档变更范围:methods/system.json 仅 setting.warehouse.saveSettings 一条(params 在 subject_config.group_order_pack_max_minutes 之后、subject_config.single_weigh_require_pack 之前新增 subject_config.big_group_pack_coefficient;errors 新增对应 400;description 追加补漏说明);根版本 0.3.192 → 0.3.193、updatedAt 保持 2026-09-27;methods/changes/system.json 新增本条(插入数组首位);其余 method 逐字节未变。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。" + ] + }, + { + "version": "2026.09.27-single-weigh-require-pack", + "date": "2026-09-27", + "type": "updated", + "summary": "新增仓库配置「散单称重是否需要打包」single_weigh_require_pack(默认关闭)+ 散单称重前置打包校验:开启后,订单波次范围 wave_scope 非 1(大团购)/3(小团购)且 pack_status 非 fin 的散单称重被拒绝(业务错误 code=400)。", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings", + "order.updateExpressWeighingWeight", + "workbench.sendWeight" + ], + "notes": [ + "代码依据:app/service/systems/setting/warehouse.js#WAREHOUSE_SETTING_FIELDS 新增 key=single_weigh_require_pack(name=散单称重是否需要打包,type=flag,default=false,required=false,位于 big_group_pack_coefficient 与 return_unpack_max_record_minutes 之间);app/model/store.js#DEFAULT_SUBJECT_CONFIG 新增默认 false,normalizeSubjectConfig 仅布尔/like-flag(true/1/'1'/'true' → true;false/0/'0'/'false → false),非法值抛错 subject_config.single_weigh_require_pack 必须是布尔值,未配置时不写该键。", + "校验逻辑(app/service/systems/order_express.js):新增 findOrderWaveAndPackStatus(current→history→dispatch 分表 + 序列表定位优先)/formatPackStatusText(none=未打包、padding=打包中、fin=已打包、error=打包异常,未知值按未打包)/isSingleWeighRequirePack(走 deliveryOrder.getStoreSubjectConfig 带缓存,缺失/读取异常按关闭)/assertSingleOrderPackedForWeigh/buildWeighPackBlockedMessage;_updateSingleOrderWeight 开头调用 assertSingleOrderPackedForWeigh,因此订单模式(order_id>0)与运单号模式(order_id=0)的散单/非团购波次路径均生效;规则:配置开启且 wave_scope ∉ {1,3} 且 pack_status != fin → 业务错误 code=400「散单称重需先完成打包:订单尚未打包(当前打包状态:未打包)」;warehouseId 缺失跳过校验;团购波次 _updateWaveOrderWeight/_updateWaveAllOrdersWeight 不校验。", + "工作台路径(app/service/systems/workbench.js):_sendWeight 订单行查询补充 wave_scope/pack_status,拦截校验后调用 _assertSingleWeighPackedForWeigh,复用 order_express.buildWeighPackBlockedMessage 文案并在末尾追加「 [条码]」,经 workbench.sendWeight 出口以业务失败(code=400)返回。", + "测试证据:test/single_weigh_require_pack.test.cjs(26 用例全部通过,覆盖配置规范化、wave_scope 1/3 跳过、未打包拦截且不落库、已打包放行、配置读取异常降级)。", + "文档变更范围:methods/system.json 更新 5 条 method(setting.warehouse.getSettings 响应新增 subject_config.single_weigh_require_pack;getFieldMeta 描述补新字段元信息;saveSettings 入参补该字段与非法值 400;order.updateExpressWeighingWeight 与 workbench.sendWeight 的 errors 补未打包拦截 400 场景);根版本 0.3.191 → 0.3.192、updatedAt 2026-09-26 → 2026-09-27;methods/changes/system.json 新增本条(插入数组首位)。分组结构、其它 method、响应结构(除 getSettings 新增 1 字段)不变。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库(method-doc-update 或全量 method-doc-import 后重新导出)。" + ] + }, + { + "version": "2026.09.26-order-packing-returnUnpack-where-person-filter", + "date": "2026-09-26", + "type": "updated", + "summary": "接口入参新增:order.packing.list 新增 where.operator_text(打包员/作业人员筛选,wms_pack_task.operator_text 多人姓名逗号拼接快照,支持 {operator,value,type} 标准结构,value 支持字符串或数组多值取并集;contains/like 与缺省为 LIKE 模糊(通配符已转义)、eq/in 精确、ne 不等于、notlike 逐值排除、空值忽略);returnUnpack.list 新增 where.unpacker_name(拆包人筛选,wms_return_unpack.unpacker_name 工号名称快照,like 支持数组多值并集,兼支持 eq/ne/in/notin/between)。同一 _buildListWhere 被复用,order.packing.export 与 returnUnpack.export 的 where 同步获得同一筛选语义(其 where 字段清单已补 operator_text / unpacker_name)。", + "methods": [ + "order.packing.list", + "order.packing.export", + "returnUnpack.list", + "returnUnpack.export" + ], + "notes": [ + "变更类型:updated(接口入参新增 where 字段,不新增/删除 method、不改变响应结构与错误码)。", + "代码依据:app/service/systems/order_packing.js#_buildListWhere(operator_text 分支,同时被 list 与 exportPackTask 复用,L525/L653);app/service/systems/return_unpack.js#_buildListWhere(textFields 新增 unpacker_name,同时被 list 与 exportUnpack 复用,L937/L1149)与 #_resolveConditionValue(like 支持数组多值并集)。目标列:wms_pack_task.operator_text(TEXT,多人姓名逗号拼接快照,如 小吴哥,阿猫;写入见 app/service/systems/workbench.js);wms_return_unpack.unpacker_name(STRING(50) NOT NULL,拆包人员工号名称快照 employees_name/real_name,app/model/return_unpack.js)。", + "operator_text 取值口径(以代码为准):支持 {operator,value,type} 标准结构,value 支持字符串或字符串数组(多值取并集);operator=contains/like 与缺省(不传 operator)→ LIKE %值%(%/_ 通配符已转义);operator=eq/in → 精确匹配(单值等值、多值 IN);operator=ne → 不等于(多值取首值);operator=notlike → NOT LIKE %值%(多值逐个 AND 排除);值为 空串/null/空数组(trim/去空归一后为空)时忽略该条件(不过滤)。", + "unpacker_name 取值口径(以代码为准):{operator:\"like\",value} 或直接值 → LIKE %值%;value 为数组时多值 LIKE 取并集(trim/去空归一后为空退化为 %% 全匹配、不过滤);同时兼容 _resolveConditionValue 既有操作符 eq/ne/in/notin/between/gt/gte/lt/lte。", + "文档变更范围:methods/system.json 更新 order.packing.list(where.children 新增 operator_text)、order.packing.export(where description 字段清单补 operator_text)、returnUnpack.list(params 新增 where.unpacker_name)、returnUnpack.export(where description 字段清单补 unpacker_name)共 4 条;分组条数与响应结构不变;根版本 0.3.190 → 0.3.191、updatedAt 2026-09-25 → 2026-09-26;methods/changes/system.json 新增本条(插入数组首位)。", + "前端传参示例:order.packing.list / export 传 {\"where\":{\"operator_text\":{\"value\":\"小吴哥\",\"operator\":\"like\",\"type\":\"text\"}}};returnUnpack.list / export 传 {\"where\":{\"unpacker_name\":{\"operator\":\"like\",\"value\":\"阿猫\"}}}。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta,导出脚本 script/method-doc-export.cjs)。本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(遵循「只修改文档」红线)。后续需由维护者决定是否同步入库(method-doc-update 或全量 method-doc-import 后重新导出),否则下次执行 method-doc-export.cjs 会用库表重建 system.json 而丢失本次文件改动。", + "发布顺序:纯文档变更,无迁移、无代码改动(代码已实现并通过 ESLint),前端无需适配。" + ] + }, + { + "version": "2026.09.25-index-upload-client-error-log", + "date": "2026-09-25", + "type": "added", + "summary": "新增客户端错误日志上报接口 index.uploadClientErrorLog(免登录、免权限、免鉴权,保留系统日志):设备端运行时错误批量上报暂存到新表 wms_client_error_log。入参支持单条对象/数组/{ logs: [...] } 三种形态、单次最多 50 条;snake_case 为主并兼容 camelCase 别名;error_message/error_stack 至少一项有值(超长截断 5000/65535),extra 截断 65535;report_uuid 唯一索引幂等去重(重复静默成功,duplicated +1),缺失时服务端生成 srv-{uuid};client_time 仅参考(非法存 null)。成功返回 code=200 + total/accepted/duplicated/rejected/rejected_reasons(≤10) 统计;方法级错误 HTTP 200 + flag=failure(code=400/500)。配套迁移 database/migrations/20260925100000-create-wms-client-error-log.js、模型 app/model/client_error_log.js、服务 app/service/systems/client_error_log.js。", + "methods": [ + "index.uploadClientErrorLog" + ], + "notes": [ + "变更类型:added(新增 method + 新增表);影响范围:methods/system.json 的 index(基础模块)分组 28 → 29 条,根版本 0.3.189 → 0.3.190、updatedAt 2026-09-24 → 2026-09-25;methods/changes/system.json 新增本条(插入数组首位)。", + "入口与鉴权:POST /system?method=index.uploadClientErrorLog&v=1×tamp=<数字时间戳>(controller.home.system 统一入口);请求头需 platform、project(根 headers 已声明枚举),无 Authorization/token;方法已登记 _noNeedLogin/_noNeedRight/_noNeedAuth,且不在 INDEX_NO_NEED_LOG_METHODS 清单 → 保留系统日志(index 模块日志口径已由通配改为显式清单)。", + "入参归一化口径(代码为准):三种形态三选一(单条对象 / 数组 / { logs: [...] },单次最多 50 条,超限 code=400);字段按 snake_case 读取并兼容 camelCase 别名(clientType/appVersion/deviceId/osVersion/deviceModel/errorType/errorMessage/errorStack/reportUuid/clientTime);字符串字段超宽截断:client_type 32、app_version 64、device_id 128、os_version 64、device_model 128、error_type 64、report_uuid 64;error_message 截断 5000、error_stack 截断 65535(两者至少一项有值,否则该条 rejected);extra 支持对象(JSON.stringify 后截断 65535);client_time 支持毫秒/秒时间戳(≥1e12 视为毫秒)与日期字符串,非法解析存 null。", + "幂等语义:report_uuid 唯一索引 uk_report_uuid —— 写入前先查已有 uuid,重复项 duplicated +1 且不再写入(静默成功);客户端未传 report_uuid 时服务端生成 srv-{uuid},此时不做幂等去重、不保证幂等;created_at/updated_at 由 Sequelize 统一取服务器时间,不采信 client_time。", + "表结构:wms_client_error_log —— id BIGINT(20) UNSIGNED 自增主键;client_type/app_version/device_id/os_version/device_model/error_type/report_uuid 为 STRING(32/64/128/64/128/64/64,NOT NULL DEFAULT '');error_message TEXT、error_stack MEDIUMTEXT、extra TEXT 可空;client_time/created_at/updated_at DATE(created_at/updated_at NOT NULL);索引 uk_report_uuid(唯一)、idx_created_at、idx_client_type_app_version、idx_device_id。", + "出参(成功):{ flag:'success', code:200, message:'上报成功', success:true, total, accepted, duplicated, rejected, rejected_reasons(≤10 条,每条 { index, reason }), timestamp };失败(400/500):HTTP 200 + { flag:'failure', code, message, timestamp }。", + "客户端接入示例(无需 token,仅需公共头 platform/project 与 query method/v/timestamp):curl -X POST 'https:///system?method=index.uploadClientErrorLog&v=1×tamp=1764000000' -H 'platform: app' -H 'project: wms' -H 'Content-Type: application/json' -d '{\"client_type\":\"android\",\"app_version\":\"1.2.3\",\"device_id\":\"dev-001\",\"os_version\":\"Android 14\",\"device_model\":\"Pixel 8\",\"error_type\":\"crash\",\"error_message\":\"NullPointerException\",\"error_stack\":\"...\",\"report_uuid\":\"uuid-2026-001\",\"client_time\":1763999999000}';Kotlin(OkHttp) 伪代码:RequestBody.create(MediaType.parse(\"application/json\"), JSONObject().apply{put(\"client_type\",\"android\");put(\"error_message\",\"...\");put(\"report_uuid\", UUID.randomUUID().toString())}.toString()),Request.Builder().url(\"$base/system?method=index.uploadClientErrorLog&v=1×tamp=${System.currentTimeMillis()/1000}\").header(\"platform\",\"app\").header(\"project\",\"wms\").post(body).build() —— 客户端应在本地生成 report_uuid 以保证重试幂等。", + "前端/客户端是否需适配:是(仅客户端接入层)。既有 /system 前端无改动;android/ios/web 端需按上述示例补齐 platform/project 头与 method/v/timestamp query,并自行生成并持久化 report_uuid 以利用幂等;无 token 校验,无需改造登录态链路。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta,导出脚本 script/method-doc-export.cjs)。本次仅按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(遵循「只修改文档」红线,与 2026-09-24 变更记录口径一致)。后续需由维护者决定是否以 method-doc-create 将该方法入库并重新导出,否则下次执行 method-doc-export.cjs 会用库表重建 system.json 而丢失本条。", + "发布顺序:迁移(20260925100000-create-wms-client-error-log)先于代码发布;迁移为纯建表、无回填,先迁移无风险。" + ] + }, + { + "version": "2026.09.24-front-config-domain-two-phase-switch", + "date": "2026-09-24", + "type": "updated", + "summary": "域名切换改为两阶段(待验证域名与生效域名分离)—— frontConfig.setDomain 只登记待验证域名 pending_domain 并下发 TXT 校验码,TXT 校验通过后才由提升逻辑切换为生效域名并清空证书;新增旧域名下线记录 retired_domain;解决「改域名瞬间旧域名公共接口 404」的中间态问题。", + "methods": [ + "frontConfig.setDomain", + "frontConfig.getDomain", + "frontConfig.checkDomain", + "frontConfig.getByDomain", + "frontConfig.saveCert", + "frontConfig.getCert" + ], + "notes": [ + "变更原因(旧口径问题,P0 中间态):旧 setDomain 是「设置即生效」—— 一次调用即改写生效域名 domain、domain_status 归零并清空证书,frontConfig.getByDomain 的放行闸门(domain + domain_status=1)对旧域名立即失效 → 旧域名公共接口立刻 404,而 nginx 侧旧域名 server 块仍在,出现「页面能打开但拉不到配置」的中间态;且用户改错域名无法回滚(只能再改一次并重新举证)。本轮以「待验证域名与生效域名分离」彻底消除该中间态。", + "数据层:wms_warehouse_front_config 新增 8 列 —— pending_domain(STRING(100))、pending_verify_host(STRING(255))、pending_verify_token(STRING(64))、pending_verify_attempts(INTEGER NOT NULL 默认 0)、pending_last_error(STRING(500))、pending_created_at(DATE)、retired_domain(STRING(100),待下线旧域名)、retired_at(DATE);新增普通索引 idx_pending_domain(域名验证定时任务扫描待验证行)与 idx_retired_domain(外部脚本扫描待下线旧域名)。迁移文件 database/migrations/20260924180000-add-pending-domain-to-wms-warehouse-front-config.js(up/down 幂等)。纯追加且可空/带默认值,「无需任何数据回填」:存量行的 pending_* 为 NULL/0,语义即「没有待验证域名」,升级瞬间行为与升级前一致。", + "四分支决策表(frontConfig.setDomain,域名比较忽略大小写):A 入参 == 生效域名且无 pending → 幂等短路(不写库;仅大小写不一致时改写 domain 字面值并清新旧两个字面值缓存);B 入参 == 生效域名且有 pending → 取消待切换(只清空 pending 6 列,生效域名/证书/同步状态一律不动);C 入参 == 现有 pending_domain → 校验码齐全则幂等短路,缺码(脏数据)则只补发 pending 校验码并清 pending_verify_attempts / pending_last_error;D 其它(含首次设置)→ 查重通过后只写 pending_domain + 新校验码,domain / domain_status / domain_verified_at / domain_verify_* / 证书 5 列 / 同步 4 列一律不动,也不清任何公共缓存。查重由「其他仓库 domain 命中」扩展为「其他仓库 domain 或 pending_domain 命中」→ 409「域名 X 已被其他仓库使用」。", + "提升逻辑(frontConfig.promotePendingDomain,checkDomain 路径一与定时扫描共用):TXT 校验通过后一次 update 提交 —— domain = pending_domain、domain_status=1、domain_verified_at=now、domain_verify_host/token/attempts 由 pending_* 平移、domain_last_error=NULL;旧域名(生效域名非空且与待验证域名不同)写入 retired_domain + retired_at;清空 pending 6 列(pending_verify_attempts 归 0);清空证书 5 列(cert_pem / cert_key / cert_path / key_path / cert_expire_at);重置同步 4 列(sync_status=0、sync_attempts=0、last_sync_error=NULL、last_synced_at=NULL);由调用方清理旧域名与新域名两个公共拉取缓存(clearDomainCaches,先写库后清缓存,清失败仅记 WARN)。update 的 where 带 id + pending_domain 防并发重复提升。", + "响应契约变化(纯追加、旧字段名与语义不变,前端可先发版兼容):frontConfig.getDomain 由 9 字段扩为 16 字段(追加 pending_domain / pending_verify_host / pending_verify_value / pending_attempts / pending_last_error / pending_created_at / pending_active);frontConfig.setDomain 响应同步由 9 字段扩为 16 字段;frontConfig.checkDomain 响应由 11 字段扩为 18 字段(getDomain 的 16 字段 + verified + resolved_values),并新增 409 错误码(提升时 domain 唯一索引冲突)。生效域名组字段名与语义一字未改:domain_status=1 时 verify_host/verify_value 仍返回空字符串;待验证域名在 pending_domain 非空时始终回显校验码(pending_verify_host / pending_verify_value)。", + "旧域名下线由外部脚本执行(retired_domain 契约):script/warehouse-cert-sync.cjs 消费 retired_domain —— 删除该域名的 nginx server 块与证书文件后把 retired_domain 置 NULL,并有目录孤儿兜底清理;应用侧(service / schedule)不碰任何 nginx 文件。实测核对:当前工作区的 script/warehouse-cert-sync.cjs 尚未引用 retired_domain(全文检索 0 命中),该下线动作需脚本侧补齐后本闭环才完整;retired_domain 只保留最近一个旧域名,多次连续切换会丢中间域名(依赖脚本孤儿兜底清理)。", + "发布顺序强约束(必须先迁移、再发代码):新代码的 SELECT 走 Sequelize 全字段,若生产库尚未执行迁移(pending_* / retired_* 共 8 列不存在),frontConfig.setDomain / getDomain / checkDomain 乃至 frontConfig.getByDomain 都会报 ER_BAD_FIELD_ERROR;定时扫描 verifyPendingDomains 会 fail-soft 返回零统计并记 WARN(含「迁移尚未执行」提示)。迁移为纯追加可空,先在生产执行迁移无风险。升级顺序:迁移 → 发布代码 → 前端发版。", + "前端必须改造要点:①setDomain 提交成功后的 TXT 指引改读 pending_verify_host / pending_verify_value(不能再用 verify_host / verify_value);②首次设置时 domain 为空字符串是正常态(待验证域名在 pending_domain);③新增「取消待切换」交互 = 用当前生效域名再调一次 setDomain(走分支 B);④「切换中」状态用 pending_active / pending_attempts / pending_last_error / pending_created_at 展示;⑤提升完成后提示「切换完成,请重新上传证书」(提升会清空证书并重置同步状态);⑥明确「切换期间上传的证书属于旧域名」,提升后失效。", + "文档变更范围与版本号:methods/system.json 更新 frontConfig.setDomain / frontConfig.getDomain / frontConfig.checkDomain / frontConfig.getByDomain / frontConfig.saveCert / frontConfig.getCert 共 6 条(description + notes;其中 setDomain / getDomain / checkDomain 的 response 同步追加待验证域名组 7 字段,checkDomain 另补 409);frontConfig 分组仍 8 条、其余方法未动;methods/changes/system.json 新增本条记录(插入数组首位);根版本 0.3.188 → 0.3.189(updatedAt 保持 2026-09-24)。", + "历史记录说明(不回改):既有变更记录中关于「setDomain 未变化即幂等短路、缺码补发校验码」「domain_status=1 一律短路不降级」等描述属当时真实口径,作为历史事实不回改,由本条新记录承接并覆盖(现口径为四分支 A/B/C/D,原「缺码补发·已验证」分支已不存在)。", + "维护源口径冲突(仅记录,未处理):methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(红线要求)。", + "未处理遗留(建议单独修正):app/schedule/domain_verify_scan.js 头注释仍描述升级前口径(扫描 domain_verify_* 行并回写 domain_status / domain_verified_at / domain_verify_attempts / domain_last_error),与两阶段实现(只扫 pending 组、回写 pending_* 并在通过时提升)不符;app/service/systemMethods/frontConfig.js 的部分 JSDoc 仍写「生效域名组 9 字段」。两者均位于 app/**,本次为文档任务、不改代码,仅报告。" + ], + "module": "frontConfig" + }, + { + "version": "2026.09.24-front-config-doh-multi-endpoint", + "date": "2026-09-24", + "type": "updated", + "summary": "修复 DNS 解析误判 —— DoH 改为多端点顺序尝试(dohUrls),单端点「无记录」不再直接定论;仅在所有解析路径都失败时才判解析错误。", + "methods": [ + "frontConfig.checkDomain" + ], + "notes": [ + "问题与实测案例:仓库 wmsv-aa4adaab13.wms.wms.gztbyc.com 的 TXT 记录真实存在(值 ddd9ae51cf95b488db544f23ccd01e7b,8.8.8.8 / 223.5.5.5 / AliDNS DoH / nslookup 四方一致),但默认 DoH 端点 doh.pub 返回 Status=0 且无 Answer(陈旧负缓存,其返回的 SOA 序列号偏旧);旧实现把单端点的 NODATA 直接定论为「未解析到 TXT 记录」→ domain_status=2 → 被 frontConfig.getByDomain 与 nginx 放行闸门断流(真实记录存在却被判为未解析到)。", + "新口径:DoH 改为多端点顺序尝试(dohUrls,默认 alidns → 223.5.5.5 → doh.pub)+ 单端点结果三分类(values 立即返回 / empty 继续下一个端点 / error 继续下一个端点);empty(NODATA 或 NXDOMAIN)与 error 都不再直接定论,全部端点未取到值后降级系统 DNS;只要有一个端点或系统 DNS 明确答复「无该记录」就返回 [] (未解析到记录,不抛错),仅「所有 DoH 端点都是 error 且系统 DNS 也失败」才抛 500「DNS 解析失败:…」。", + "配置兼容规则(dohUrl → dohUrls):config.frontConfig.domainVerify.dohUrls 为有效非空字符串数组时优先使用(顺序不变);否则回退历史单端点键 dohUrl(等价 [dohUrl]);两者均无效时回退内置默认数组 DEFAULT_DOH_URLS。旧键 dohUrl 保留读兼容,不作废。", + "配置默认值变更:timeoutMs 5000 → 3000(单端点超时,系统 DNS 兜底同样显式限时 3s)、batchSize 50 → 20;配套核算 batchSize ≤ lockTtlSeconds×0.5 ÷ ((N+1)×timeoutMs/1000)(N 为端点数),3 端点场景单行最坏 12s、20 行 240s < lockTtlSeconds 600s。", + "返回值契约:内部 resolveTxtValues 新增 endpoint 字段(追加不破坏,仍返回 { values, source, endpoint });verifyDomainRecord 契约不变({ verified, values, source, error },永不抛异常);新增内部 helper resolveDohUrls、queryDohEndpoint。", + "可观测性:每个端点的 empty / error 均打日志(含 host + endpoint + 脱敏原因),可区分「记录不存在」与「链路不可用」。", + "前端无感:不影响任何 method 的入参 / 响应结构,仅影响 frontConfig.checkDomain 与定时任务 domain_verify_scan 的判定正确性。", + "文档变更范围:仅更新 frontConfig.checkDomain(description + notes),frontConfig 分组仍 8 条、各 response 计数不变;新增 1 条变更记录;根版本 0.3.187 → 0.3.188(updatedAt 保持 2026-09-24)。", + "历史记录说明:既有变更记录中关于「Status=3 或无 Answer 视为未解析到记录、不重复走系统 DNS」的描述属于当时的真实口径,作为历史事实不回改,由本条新记录承接并覆盖。" + ], + "module": "frontConfig" + }, + { + "version": "2026.09.24-front-config-domain-verified-shortcircuit", + "date": "2026-09-24", + "type": "updated", + "summary": "修复「domain_status=1 的已验证域名可能被误降级」问题:frontConfig.setDomain 删除「已验证缺码补发」分支(已验证域名一律幂等短路、不补码、不写库);frontConfig.checkDomain 对 domain_status=1 一律短路返回 verified=true 且不写库、不改状态、不增加验证次数。", + "methods": [ + "frontConfig.setDomain", + "frontConfig.checkDomain" + ], + "notes": [ + "变更原因(P0 回归修复):上一轮把「domain_status=1 且缺校验码」的已验证域名也做成缺码补发,使 frontConfig.checkDomain 的「历史回填行短路」条件不再成立——用户手动点一次「校验」即走真实 DNS 解析,失败便把 domain_status 由 1 写成 2(domain_verify_attempts+1、domain_last_error 有值),随后被 frontConfig.getByDomain 与 nginx 放行闸门断流;且 status=1 时 getDomain 不回显校验码,用户无从发现补发的码。本轮改为「已验证域名一律不补码、一律短路」。", + "问题现象与复现路径:库内 domain_status=1 且 domain_verify_host/domain_verify_token 为空(迁移回填常态)→ 前端再次提交同一域名触发 frontConfig.setDomain(旧口径走 C 分支补码入库)→ frontConfig.getDomain 因 domain_status=1 仍返回空 verify_host/verify_value(补发的码任何接口都读不到)→ 用户点「校验」触发 frontConfig.checkDomain,此时短路条件「无校验码」已不成立 → 走真实 DNS 解析 → 未配置对应 TXT 记录解析失败 → domain_status 由 1 写成 2、attempts+1、last_error 有值 → frontConfig.getByDomain 与 nginx 闸门断流(线上已生效域名被降级)。", + "修复后口径(实现 app/service/systems/frontConfig.js):frontConfig.setDomain 删除原 C「缺码补发·已验证」分支,五分支收敛为 A/B/D/E/F(C 并入 A)——A 的判定为「域名忽略大小写相同 且(校验码齐全且字面值一致 或 domain_status=1)」,命中即幂等短路:不写库、不补码、不刷新校验码、不改验证状态与尝试次数、不清证书、不重置同步状态、不清缓存;B 大小写规范化仅改 domain 字面值(status=1 且缺码同样不补码);D 缺码补发仅限 domain_status∈{0,2};E 域名变更与 F 首次设置行为不变。三条「未变化」分支(A/B/D)均不写入 domain_verified_at。", + "frontConfig.checkDomain 短路口径放宽:由「domain_status=1 且缺校验码」改为「domain_status=1」(不论库内有无校验码)一律短路,返回 verified=true、resolved_values=[],不写库、不改状态、不增加 attempts;已验证域名不再重复校验,误点「校验」不会把生效中的域名降级。", + "行为影响(已知取舍):已验证(domain_status=1)域名自此无法通过 frontConfig.checkDomain 重新验证;如需该能力需另开接口(本次未做)。如需重新验证,应先通过 frontConfig.setDomain 变更域名(生成新校验码并回到「未验证」)后再校验。", + "前端约束:不得依赖「重复调用 frontConfig.setDomain 换新校验码」——域名未变化时一律幂等短路,不会下发新码;当前也没有「更换校验码」的独立接口。", + "文档变更范围:methods/system.json 更新 frontConfig.setDomain、frontConfig.checkDomain 的 description 与 notes,并顺带修正 frontConfig.getInfo(response.domain 描述)与 frontConfig.saveInfo(description)中「domain 只能通过 frontConfig.saveCert 变更」的陈旧表述(实际已收敛到 frontConfig.setDomain);4 条 method 的 params/response/errors/headers 均未变动,frontConfig 分组仍为 8 条;methods/changes/system.json 新增本条记录(插入数组首位);根版本 0.3.186 → 0.3.187,updatedAt 保持 2026-09-24。", + "验证与实测:测试链路已确认「status=1 缺码 → setDomain 不再补码、不写库」「status=1 调 checkDomain 一律短路、不写库、不降状态、attempts 不变」「A/B/D/E/F 五分支行为与文档一致」;文档侧经 npm run doc:api:update --dry-run 预检,并以写入前备份做最小 diff 审计(除版本行、4 条 method、1 条 change 外无其它条目被动)。", + "维护源口径冲突(仅记录,未处理):与前两轮一致,methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库。" + ], + "module": "frontConfig" + }, + { + "version": "2026.09.24-front-config-setDomain-idempotent", + "date": "2026-09-24", + "type": "updated", + "summary": "frontConfig.setDomain 语义收敛 —— 域名未变化时幂等短路,不再重新生成 DNS TXT 校验码、不再重置验证进度;仅「库内缺少校验码」时补发(已验证域名不降级),仅「库内域名大小写不同」时做小写规范化;域名变更与首次设置行为不变。", + "methods": [ + "frontConfig.setDomain" + ], + "notes": [ + "变更原因:旧口径下「同一域名未验证/验证失败则重发新校验码并清零 attempts/last_error」,导致用户每次重复提交同一域名都会作废已配置好的 TXT 记录、并清空验证进度(attempts 归零、失败原因丢失),属无谓的进度回退;本轮以「域名是否变化」为第一决策点做幂等收敛", + "五分支口径(实现 app/service/systems/frontConfig.js setDomain):A 完全未变化(忽略大小写相同 + 库内已有校验码 + 字面值一致)→ 幂等短路,不写库、不刷新校验码、不改验证状态与尝试次数、不清证书、不重置同步状态、不清缓存;B 大小写规范化(忽略大小写相同但库内字面值不同,如库内 Shop.com、入参 shop.com)→ 仅把 domain 规范化为小写并清理新旧两个字面值的公共缓存,校验码与验证状态不变;C 缺码补发·已验证(domain_status=1 但 host/token 为空)→ 仅补发校验码,domain_status/domain_verified_at/attempts 保持原值不降级;D 缺码补发·未验证或失败(domain_status∈{0,2} 且缺码)→ 补发校验码 + domain_status=0 + attempts=0 + 清 last_error;E 域名变更(忽略大小写后不同)→ 行为不变:查重 409、生成新校验码、domain_status=0、attempts=0、清空证书(cert_pem/cert_key/cert_path/key_path/cert_expire_at)+ 重置同步状态、清理新旧两个 domain 缓存;F 首次设置(无记录)→ 行为不变:先查重 409,其余同 E", + "未变化短路(A/B/C/D)不再写入 domain_verified_at(该字段现在只在域名变更/首次设置分支被置 null),也不再调用 assertDomainUnique 查重;变更/首次设置(E/F)查重逻辑与 409 文案保持不变", + "行为影响提示:domain_status=2(验证失败)的行若 domain_verify_attempts 已达 config.frontConfig.domainVerify.maxAttempts(默认 20),app/schedule/domain_verify_scan.js 不会再自动拾起(计入 skipped),恢复路径为手动调用 frontConfig.checkDomain(checkDomain 无 maxAttempts 门控);且当前没有「更换校验码」的接口,如需该能力需另开接口", + "前端不得再依赖「重复调用 setDomain 换新校验码」这一行为;需要新校验码的场景只有库内缺码(C/D 自动补发),其余重复提交均按幂等短路处理", + "文档变更范围:methods/system.json 仅更新 frontConfig.setDomain 一条(description 与 notes 重写,params/response/errors/headers 未变,frontConfig 分组仍 8 条),未使用 deleteMethods、未整条覆盖其它条目;methods/changes/system.json 新增本条记录(插入数组首位);根版本 0.3.185 → 0.3.186,updatedAt 保持 2026-09-24", + "未处理遗留(仍建议下一批单独修正):frontConfig.getInfo 的 response.domain 描述与 frontConfig.saveInfo 的 description 仍写「domain 只能通过 frontConfig.saveCert 变更」,实际已收敛到 frontConfig.setDomain;本条 spec.methods 只放 setDomain,避免整条覆盖造成语义漂移", + "维护源口径冲突(仅记录,未处理):与上一轮一致,methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库" + ], + "module": "frontConfig" + }, + { + "version": "2026.09.24-return-unpack-notify-by-source", + "date": "2026-09-24", + "type": "updated", + "summary": "拆包完成通知改为按原查询登记来源定向回信:_notifyUnpacked 不再按货主泛推售后群,改为按 wms_return_query_log 登记时记录的 group_id+user_id 聚合回信原查询群/用户(有用户信息时 writeOutboundReply 定向回原查询用户,否则退化为来源群系统通知);登记无来源群的记录不通知;仅推送成功的登记标记 is_notified=1。", + "methods": [ + "returnUnpack.submit" + ], + "notes": [ + "代码位置:app/service/systems/return_unpack.js _notifyUnpacked(依赖此前新增的登记来源字段 group_id/group_name/user_id/user_name)", + "回信链路与 video_record_request._replyResult 口径一致:批量反查 wms_inbox_group 补全 group_name/ext_data/store_id,缺失时用登记快照兜底;定向回信 source=ai_reply(wms_inbox_message 记录 user_id/user_name)" + ] + }, + { + "version": "2026.09.24-return-query-log-source-ids", + "date": "2026-09-24", + "type": "updated", + "summary": "退回查询登记表 wms_return_query_log 新增登记来源字段 group_id/group_name/user_id/user_name(迁移 20260924160000-add-source-ids-to-wms-return-query-log):站内信「查退回」触发登记时写入查询来源群/用户信息,用于登记追溯与后续定向通知;returnWaybill.create/list/detail 响应记录同步包含新字段(后台登记路径为 null)。", + "methods": [ + "returnWaybill.create", + "returnWaybill.list", + "returnWaybill.detail" + ], + "notes": [ + "代码位置:app/model/return_query_log.js 新增 4 字段;app/service/systems/return_unpack.js queryByWaybill 增加可选入参并在 received/not_returned 两处自动登记时写入来源;app/service/inbox/functions.js queryReturn 透传 ctx.inboxContext 的 group_id/group_name/user_id/user_name", + "迁移执行:npx sequelize-cli db:migrate(生产:$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production)", + "库表化维护:method-doc-update.cjs 更新 3 个方法 response 说明并 --bump 至 0.3.184,method-doc-export.cjs 回写 methods/system.json" + ] + }, + { + "version": "2026.09.24-big-group-pack-coefficient-desc", + "date": "2026-09-24", + "type": "updated", + "summary": "大团购打包系数字段描述统一:subject_config.big_group_pack_coefficient 描述更新为「大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0」", + "methods": [ + "setting.warehouse.getSettings" + ], + "notes": [ + "字段元信息 app/service/systems/setting/warehouse.js(WAREHOUSE_SETTING_FIELDS)中 big_group_pack_coefficient 的 description 已与该口径一致,无代码变更" + ] + }, + { + "version": "2026.09.24-workbench-big-group-pack-member-divide", + "date": "2026-09-24", + "type": "updated", + "summary": "大团购打包时长按人数分摊:workbench.packOrder 倒计时字段 pack_wait_seconds 与 workbench.queryOrder 闸门等待秒数改为「大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数」;拉取当前打包任务时仅统计进行中任务(status<2,任务已结束则不计);人数为 0 时任务已被成员全部登出流程自动结束,不会出现,仍按 1 兜底防除零", + "methods": [ + "workbench.packOrder", + "workbench.queryOrder" + ], + "notes": [ + "代码位置:app/service/systems/workbench.js(_packOrder 倒计时按 users 成员数分摊、_queryOrder 闸门按 _countCurrentPackMembers 统计 wms_workbench_member 人数分摊)", + "回归测试:test/app/service/systems/workbench.bigGroupTimeGate.regression.test.js 新增人数分摊用例(打包 2 人 1×3/2=1.5 秒、闸门 3 人 10×3/3=10 秒),共 13 用例全绿" + ] + }, + { + "version": "2026.09.24-setting-big-group-pack-coefficient", + "date": "2026-09-24", + "type": "updated", + "summary": "仓库设置新增大团购打包系数:subject_config 新增 big_group_pack_coefficient(数字,默认 3,单位秒/单,必须大于 0),用于 workbench 大团购波次打包时长闸门与倒计时;setting.warehouse.getSettings 响应新增该字段说明,getFieldMeta 字段元信息列表同步新增该项", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta" + ], + "notes": [ + "代码位置:app/service/systems/setting/warehouse.js(WAREHOUSE_SETTING_FIELDS 新增字段元信息:type=number、default=3、min=0.1);app/model/store.js(DEFAULT_SUBJECT_CONFIG 与 normalizeSubjectConfig 校验:空值回填 3,非法值抛错)", + "读取链路:app/service/systems/delivery_order.js getStoreSubjectConfig(带缓存),workbench 侧经 _getBigGroupPackCoefficient 读取,异常/非法降级默认 3", + "无需数据库迁移:配置存于 wms_store.subject_config(JSON 字段),仅需代码发布" + ] + }, + { + "version": "2026.09.24-workbench-big-group-pack-gate", + "date": "2026-09-24", + "type": "updated", + "summary": "工作台大团购打包系数与打包时长闸门:workbench.packOrder 打包任务落库 wave_scope,大团购波次(wave_scope=1)响应新增倒计时字段 pack_wait_seconds(当前波次打包数 × 大团购打包系数,单位秒)与 pack_start_time(开始打包时间,毫秒时间戳),其他波次均为 0;workbench.queryOrder 响应 order 新增 wave_scope,并新增大团购打包时长闸门(当前工作台 wave_scope=1 任务未到时仅允许查询本波次订单,其他波次返回「打包时长不足」错误)", + "methods": [ + "workbench.packOrder", + "workbench.queryOrder" + ], + "notes": [ + "数据库迁移:wms_pack_task 新增 wave_scope 列(database/migrations/20260924150000-add-wave-scope-to-pack-task.js,幂等),开发库与生产库均已执行(生产库因存在更早 pending 迁移改为等价 DDL + SequelizeMeta 记录)", + "代码位置:app/service/systems/workbench.js(_queryOrder 步骤3.5 闸门、_packOrder 落库与倒计时下发、_getBigGroupPackCoefficient 配置读取);app/model/pack_task.js 新增 wave_scope 字段定义", + "回归测试:test/app/service/systems/workbench.bigGroupTimeGate.regression.test.js(11 用例全绿:响应 wave_scope / packOrder 落库与倒计时 / 闸门未到时同波次放行、不同波次拦截、已到时放行、其他 wave_scope 不限制)" + ] + }, + { + "version": "2026.09.24-front-config-domain-verify", + "date": "2026-09-24", + "type": "updated", + "summary": "前端独立部署新增「域名归属验证」能力:新增设置/查询/校验域名的 3 个接口(frontConfig.setDomain/getDomain/checkDomain,均需登录、免权限、免鉴权、仅仓库主体可用);两个保存接口不再负责设置域名(saveCert 移除 domain 入参);新增域名验证闸门(getByDomain 仅放行 domain_status=1 的已验证域名、nginx 侧仅对已验证域名生成 server 块);getCert/saveCert 响应新增证书可设置性字段(10 → 13 字段:can_set_cert/can_set_cert_reason/domain_status)。", + "methods": [ + "frontConfig.setDomain", + "frontConfig.getDomain", + "frontConfig.checkDomain", + "frontConfig.getByDomain", + "frontConfig.getCert", + "frontConfig.saveCert" + ], + "notes": [ + "数据表与迁移:wms_warehouse_front_config 新增列 domain_status(tinyint 默认 0)/domain_verify_host/domain_verify_token/domain_verified_at/domain_verify_attempts/domain_last_error 与索引 idx_domain_status;迁移文件 database/migrations/20260924120000-add-domain-verify-to-wms-warehouse-front-config.js(幂等:列/索引已存在则跳过)。迁移会把历史非空 domain 的行回填 domain_status=1:存量域名在线上已生效(nginx 已在按域名提供服务),不回填会被新闸门在升级瞬间全部断流(证书上传被拒、公共拉取 404);回填只在真正新增该列的那一次执行,避免把升级后新设但未验证的域名误标为已验证;domain_verified_at 保持 NULL(历史生效时间不可考,不写虚假时间)", + "定时任务:新增 app/schedule/domain_verify_scan.js,按 config.frontConfig.domainVerify.interval(默认 10m)扫描待验证行;配置项 enable(true)/interval(10m)/lockTtlSeconds(600)/batchSize(50)/dohUrl(https://doh.pub/dns-query)/timeoutMs(5000)/maxAttempts(20);并发控制为进程内重入标志(ctx.app._domainVerifyScanRunning)+ Redis SET NX EX 跨进程互斥锁(Redis 不可用/抛错时降级为仅进程内防重入并 WARN);业务逻辑全部委托 service.systems.frontConfig.verifyPendingDomains(schedule 内不写 SQL);单行解析/落库失败只计入 errors 不中断整轮;已达 maxAttempts 的行不再自动重试(计入 skipped,仍可由 checkDomain 手动触发)", + "DNS 解析:DoH 为主(config.frontConfig.domainVerify.dohUrl,默认 https://doh.pub/dns-query;Status=3 或无 Answer 视为未解析到记录,不重复走系统 DNS),失败降级系统 DNS(node:dns,本仓首次引入,仅服务域名验证链路);校验目标一律为一次性子域 wmsv-<10 位 hex>.<域名>,避免与用户主域已有 TXT 记录(SPF/DKIM/站点校验等)冲突", + "配置新增 config.frontConfig.cname(默认空字符串):域名未通过验证时随 getDomain/setDomain/checkDomain 响应返回给前端,提示用户把域名 CNAME 指向该目标", + "nginx 侧联动(未改动本次文档范围,仅记录):script/warehouse-cert-sync.cjs 扫描待同步记录时新增 domain_status = 1 过滤(无该列时降级为不过滤并 WARN);script/deploy-cert-sync.cjs 探针新增 domain_status 列探测与取值分布/计数输出(0_unverified/1_verified/2_failed 与 gated-out 行数)", + "前端必须改造(不兼容变更):域名设置从 saveCert 迁移到 setDomain —— saveCert 已删除 domain 入参,前端若继续传 domain 会被静默忽略且不再变更域名;正确顺序为 setDomain → 按 verify_host/verify_value 配置 TXT 记录(并按 cname 配置 CNAME)→ checkDomain 手动校验或等待定时任务 → domain_status=1 后才可 saveCert 上传证书;getCert/saveCert 响应新增 can_set_cert/can_set_cert_reason/domain_status,供上传入口置灰与提示文案", + "风险提示:config.frontConfig.domainVerify.enable = false 时 app/schedule/domain_verify_scan.js 标记 disable、Egg 不注册该任务,新域名只能靠前端调用 checkDomain 手动触发才会放行;迁移尚未执行时 getByDomain 闸门降级为仅按 domain 查询(一次性 WARN),需迁移完成并重启实例后闸门才真正生效;getByDomain 命中配置缓存最长 600s 内仍可能放行刚被置为未验证的域名(setDomain/saveCert/校验成功均已主动清缓存,实际窗口极短,接受该取舍)", + "文档变更:methods/system.json 的 frontConfig 分组新增 3 条(setDomain/getDomain/checkDomain,均 isNeedLogin=true、isNeedAuth=false、带 Authorization 头)+ 更新 3 条(getByDomain 描述补充闸门语义与迁移降级说明,params/response/errors 未变;getCert 响应 10 → 13 字段;saveCert 删除 domain 入参、新增前置闸门、response 10 → 13 字段、errors 同步收敛);spec.methods 只放上述 6 条,未放入 getInfo/saveInfo(避免整条覆盖造成语义漂移);未使用 deleteMethods;根版本 0.3.178 → 0.3.179,updatedAt 保持 2026-09-24", + "已知遗留(本次未处理,建议下一批单独修正):frontConfig.getInfo 与 frontConfig.saveInfo 的描述仍写「domain 只能通过 frontConfig.saveCert 变更」,实际域名变更已收敛到 frontConfig.setDomain;这两条不在本批 spec.methods 内(避免整条覆盖),故未同步", + "变更记录条目数 640 → 641(新记录插入数组首位,既有 640 条 version 未改动、未删除)", + "维护源口径冲突(仅记录,未处理):与上一轮维持一致,methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库", + "自动清单刷新:node temp/tmp-gen-service-method-inventory.cjs 与 node temp/tmp-update-ai-method-routing.cjs(AI_METHOD_ROUTING.md 第 6 节 SERVICE_METHOD_INVENTORY 标记区与 temp/tmp-service-method-inventory.md 同步刷新)", + "docs/*.md 无需同步:检索 frontConfig/setDomain/checkDomain/域名验证 未命中解释性文档(仅 AI_METHOD_ROUTING.md 与 temp/tmp-service-method-inventory.md 含自动清单命中,已由刷新脚本处理)" + ], + "module": "frontConfig" + }, + { + "version": "2026.09.24-front-config-saveCert-response-fix", + "date": "2026-09-24", + "type": "updated", + "summary": "修正 frontConfig.saveCert 的响应契约:由错误的 8 字段品牌口径(buildInfoOutput:warehouse_id/domain/title/logo_url/favicon_url/login_bg_url/theme/updated_at)更正为 10 字段证书口径(buildCertOutput,与 frontConfig.getCert 一致:warehouse_id/domain/cert_pem/key_pem/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at/updated_at);入参 domain/pem/key 与错误码 400/403/409/500 口径不变,其余 frontConfig 条目(getInfo/getCert/saveInfo/getByDomain)未改动。本记录闭环 2026.09.24-front-config-migrate-to-frontConfig 中标注的「saveCert 响应口径待确认」一项。", + "methods": [ + "frontConfig.saveCert" + ], + "notes": [ + "闭环说明:本记录闭环 2026.09.24-front-config-migrate-to-frontConfig 中标注的「saveCert 响应口径待确认」一项(该记录 notes 第 6 条:JSDoc 声明返回 10 字段证书输出,但实现实际 return this.buildInfoOutput(...) 返回 8 字段品牌信息);按工作流「新记录插入数组头部、历史记录不回改」,原记录保持原样,修正以本记录承接", + "代码证据:app/service/systems/frontConfig.js:782 saveCert 出口 return this.buildCertOutput(savedRecord, warehouseId);buildCertOutput 定义于同文件 :202,输出 10 字段 warehouse_id/domain/cert_pem/key_pem/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at/updated_at(其中 key_pem 读 cert_key 列)", + "由 wms-dev-agent 修正实现(saveCert 返回由 buildInfoOutput 改为 buildCertOutput),本次仅同步文档口径,未改动任何代码", + "文档变更:methods/system.json 的 frontConfig 分组仅更新 saveCert 一条(spec.methods 只放这一条,未放入 getInfo/getCert/saveInfo/getByDomain,避免整条覆盖造成语义漂移;未使用 deleteMethods);响应字段 8 -> 10,method 级 notes 中「响应口径待确认」一条被替换为「响应契约修正」;headers/params/errors 沿用既有条目不变;根版本 0.3.177 -> 0.3.178,updatedAt 保持 2026-09-24", + "通配语义同步写准:certCoversDomain 的 *.example.com 分支(app/service/systems/frontConfig.js:512)要求通配前缀非空且不含「.」,即仅覆盖恰好一级标签;*.a.com 覆盖 b.a.com,不覆盖 x.y.a.com(报 400「证书不合法」)", + "变更记录条目数 639 -> 640(新记录插入数组首位,既有 639 条 version 未改动、未删除);script/update-api-doc.cjs 的 appendChange 仅支持 unshift + 重复 version 拦截,无整条替换既有 change 的能力,故未回改上一条记录的 note", + "无代码结构变化,未重新生成 AI_METHOD_ROUTING.md 与 temp/tmp-service-method-inventory.md(上一轮已刷新,本次仅文档响应口径修正)", + "维护源口径冲突(仅记录,未处理):与上一轮维持一致,methods/*.json 的维护源是否为数据库表 wms_method_doc_meta 仍待用户决策;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库" + ], + "module": "frontConfig" + }, + { + "version": "2026.09.24-front-config-migrate-to-frontConfig", + "date": "2026-09-24", + "type": "updated", + "summary": "前端独立部署接口从 setting.warehouse 迁移到 frontConfig 模块:删除 setting.warehouse.getFrontConfig / saveFrontConfig / saveFrontCert 三个旧方法(出口、服务实现与鉴权白名单同步移除,实测调用返回「方法 xxx 不存在」),新增 frontConfig.getInfo / getCert / saveInfo / saveCert 四个需登录、免权限、免鉴权的配置接口(权限由业务层 isWarehouse 判定,仅仓库主体可用);公共按域名拉取接口 frontConfig.getByDomain 保持不变(仍 6 字段公开白名单,免登录免权限免鉴权)。", + "methods": [ + "frontConfig.getInfo", + "frontConfig.getCert", + "frontConfig.saveInfo", + "frontConfig.saveCert", + "setting.warehouse.getFrontConfig", + "setting.warehouse.saveFrontConfig", + "setting.warehouse.saveFrontCert" + ], + "notes": [ + "代码变更:新增出口 app/service/systemMethods/frontConfig.js 的 getInfo/getCert/saveInfo/saveCert(_noNeedRight/_noNeedAuth/_noNeedLog 均含这 4 个方法;_noNeedLogin 仍仅 getByDomain),实现见新增服务 app/service/systems/frontConfig.js(TEXT_FIELDS/PUBLIC_FIELDS 白名单、buildInfoOutput/buildCertOutput/buildPublicOutput)", + "代码变更:app/service/systemMethods/setting/warehouse.js 与 app/service/systems/setting/warehouse.js 中 getFrontConfig/saveFrontConfig/saveFrontCert 的出口与实现已删除,_noNeedRight 收敛为 getSettings,getFieldMeta,saveSettings,getweChatApp;methods/system.json 中 setting.warehouse 分组仅删除这 3 条条目,分组与 getSettings/getFieldMeta/saveSettings 保留", + "文档变更:methods/system.json 删除 setting.warehouse 分组下 3 条旧条目(原 L15632 saveFrontConfig / L15797 getFrontConfig / L15914 saveFrontCert),frontConfig 分组(groupName 前端独立部署模块)新增 4 条条目(isNeedLogin=true、isNeedAuth=false、Authorization 头);frontConfig.getByDomain 条目未改动(未放入本次 spec.methods,避免整条覆盖造成语义漂移);根版本 0.3.176 -> 0.3.177,updatedAt 2026-09-23 -> 2026-09-24", + "saveInfo 口径:upsert 一仓一行;仅受理 title(≤100)/logo_url、favicon_url、login_bg_url(≤255)/theme(合法 JSON 对象或 JSON 字符串),domain 与证书字段由方法层白名单静默忽略;保存即重置同步状态(sync_status=0、sync_attempts=0、清空 last_sync_error/last_synced_at);写库成功后清当前 domain 公共拉取缓存(清缓存失败仅记日志)", + "saveCert 口径:校验链 证书可解析 → 未生效拒绝 → 已过期拒绝 → 私钥与证书 SPKI 配对 → 证书 SAN/CN 覆盖 domain(支持 *.example.com 通配,仅匹配一级标签) → domain 全局唯一;校验链任一失败统一 400「证书不合法」不吐细节;cert_expire_at 以证书 validTo 权威写入;cert_pem/cert_key 直接入库、cert_path/key_path 置 null(等待 script/warehouse-cert-sync.cjs 部署后回填);写库后同时清旧 domain 与新 domain 两个公共缓存 key", + "响应口径待确认:app/service/systems/frontConfig.js saveCert 的 JSDoc(及方法层注释)声明返回证书输出(10 字段含 cert_pem/key_pem),但实现实际 return this.buildInfoOutput(...) 返回 8 字段品牌信息、不含证书字段;本文档按当前实现(8 字段)编写,若确认应返回证书输出需先修正实现再同步文档", + "维护源口径冲突(仅记录,未处理):methods/changes/system.json 既有记录备注「维护源是数据库表 wms_method_doc_meta,methods/*.json 只是导出产物」,仓库内已存在 script/method-doc-*.cjs 工具链与迁移 database/migrations/20260923150000-create-method-doc-tables.js;本次仍按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,待用户决策是否需要回灌数据库维护源", + "自动清单刷新:node temp/tmp-gen-service-method-inventory.cjs 与 node temp/tmp-update-ai-method-routing.cjs(AI_METHOD_ROUTING.md 第 6 节 SERVICE_METHOD_INVENTORY 标记区与 temp/tmp-service-method-inventory.md 同步刷新,会顺带更新扫描时间与文件/方法计数,属脚本预期行为)", + "docs/*.md 与 README.md 无需同步:检索 getFrontConfig/saveFrontConfig/saveFrontCert/前端独立部署/frontConfig/getByDomain 未命中任何解释性文档(仅 AI_METHOD_ROUTING.md 与 temp/tmp-service-method-inventory.md 含自动清单命中,已由刷新脚本处理)" + ], + "module": "frontConfig" + }, + { + "version": "2026.09.23-returnReceived-create-is-urgent", + "date": "2026-09-23", + "type": "updated", + "summary": "returnReceived.create 响应新增 is_urgent 加急标记(boolean):wms_return_query_log(退回查询记录表)按 仓库+运单号 精确匹配,命中即 true,未命中或查询失败降级为 false;幂等命中(duplicated=true)与新创建(duplicated=false)两个分支均返回该字段", + "methods": [ + "returnReceived.create" + ], + "notes": [ + "代码变更:app/service/systems/return_received.js 的 create 在幂等命中与新登记两个返回分支均新增顶层 is_urgent 字段,并新增私有辅助方法 _isUrgentReturnQuery(waybillCode, warehouseId)(含 JSDoc)", + "判定口径:wms_return_query_log(退回查询记录表)中存在 warehouse_id=当前仓库且 waybill_code=登记运单号(精确匹配)的记录时为 true,否则 false;查询失败降级为 false,不影响登记主流程", + "方法层 app/service/systemMethods/returnReceived.js 无需改动;文档变更:response 新增 is_urgent(boolean,required=true);维护源 wms_method_doc_meta 与导出产物 methods/system.json 版本同步至 0.3.176(dashboard.hot_order_rank mask 变更同步入库 0.3.175,本次变更升至 0.3.176)" + ], + "module": "returnReceived" + }, + { + "version": "2026.09.23-dashboard.hot_order_rank.mask", + "date": "2026-09-23", + "type": "updated", + "summary": "dashboard.hot_order_rank 响应口径调整:data[].sku 由商品编码改为库存商品ID(stock_warehouse.id);data[].name 做脱敏处理(前2字符+***+后2字符,长度不足 4 字符时返回 ***)", + "methods": [ + "dashboard.hot_order_rank" + ], + "notes": [ + "代码变更:app/service/systemMethods/dashboard.js 中 buildHotOrderRankMap/mergeHotOrderRank 的聚合条目新增 stockId(订单明细 stock_id),并在货主端跨仓合并时保留首个非 0 值", + "代码变更:resolveHotOrderRankProduct 的 sku 改为返回库存商品ID(number,stock_warehouse.id),仅当 stock_id 缺失时回退商品编码字符串;新增 maskHotOrderRankName 对最终展示名称统一脱敏(长度>=4 时前2字符+***+后2字符,否则返回 ***)", + "文档变更:data[].sku 类型改为 number 并更新描述;data[].name 描述补充脱敏规则;根版本 0.3.174 -> 0.3.175" + ], + "module": "dashboard" + }, + { + "version": "2026.09.23-returnReceived-list-created-at-filter", + "date": "2026-09-23", + "type": "updated", + "summary": "修复 returnReceived.list 登记时间(created_at)筛选不生效问题:_buildListWhere 白名单补充 created_at/updated_at,并补齐文档此前缺失但代码已支持的 where 字段(scanner_name/order_express_id/order_id);returnReceived.export 的 where 语义描述同步更新(与 list 一致)。配套新增 wms_return_received 索引 idx_warehouse_created_at(warehouse_id, created_at)(迁移 20260923180000),优化登记时间范围过滤与默认 created_at desc 排序。", + "methods": [ + "returnReceived.list", + "returnReceived.export" + ], + "notes": [ + "代码变更:app/service/systems/return_received.js _buildListWhere 的 directFields 白名单补充 created_at、updated_at(list 与 exportList 同时生效)", + "数据库变更:database/migrations/20260923180000-add-created-at-index-to-wms-return-received.js 新增 idx_warehouse_created_at(warehouse_id, created_at),已在开发库执行", + "文档变更:returnReceived.list 新增 where.created_at / where.updated_at / where.scanner_name / where.order_express_id / where.order_id 参数说明,description 更新;returnReceived.export 的 where 参数描述补充 created_at/updated_at 范围", + "文档库版本 0.3.173 -> 0.3.174(wms_method_doc_meta.version),methods/system.json 为导出产物" + ] + }, + { + "version": "2026.09.23-dashboard.hot_order_rank.realtime", + "date": "2026-09-23", + "type": "updated", + "summary": "dashboard.hot_order_rank 由演示数据改为真实数据库查询:统计今日(00:00 至当前时刻)销量 Top10 商品及环比昨日趋势;仓库端单仓统计,货主端跨已签约仓库聚合", + "methods": [ + "dashboard.hot_order_rank" + ], + "notes": [ + "核实 app/service/systemMethods/dashboard.js 实现后更新:废弃旧版 mock 数据,改为查询订单常用表/配送分表(OrderDeliveryFactory/OrderItemsFactory 的 current 与 dispatch)聚合", + "口径:今日窗口 [今日 00:00, 当前时刻),昨日窗口 [昨日 00:00, 今日 00:00);value 为窗口内非取消、非异常、未删除订单的商品计划数量(plan_qty)合计;trend 为环比昨日百分比(保留 1 位小数,昨日为 0 且今日 >0 时按 100)", + "仓库端使用 ctx.user.store_id 单仓统计;货主端(store_type=store)跨已签约仓库(auth_status=2)并行统计并按商品聚合;按今日销量降序取前 10 条,无数据时返回空数组", + "响应更新:data[].name 无名称回退商品编码/商品+库存ID、data[].sku 无编码回退 SKU+库存ID;错误码补充 code=0(缺少仓库/货主上下文),500 改为订单数据查询失败", + "文档库表同步:method-doc-update.cjs 更新 description/response/errors 并 --bump,method-doc-export.cjs 回写 methods/system.json" + ], + "module": "dashboard" + }, + { + "version": "2026.09.23-dashboard.charts.doc", + "date": "2026-09-23", + "type": "updated", + "summary": "补齐看板模块其余 5 个接口文档:express_ratio/platform_distribution/order_trend 为实时统计接口,warehouseStats/hot_order_rank 为演示数据接口(描述已标注);均无业务入参", + "methods": [ + "dashboard.express_ratio", + "dashboard.platform_distribution", + "dashboard.order_trend", + "dashboard.warehouseStats", + "dashboard.hot_order_rank" + ], + "notes": [ + "核实 app/service/systemMethods/dashboard.js 实现后补齐", + "express_ratio/platform_distribution 货主端跨已签约仓库(auth_status=2)汇总,返回 name/value/itemStyle.color 结构", + "order_trend 按小时统计 08:00 至当前小时,返回 summary/categories/orders/shipments", + "warehouseStats/hot_order_rank 当前为固定演示数据,待业务接入真实统计后需同步更新文档" + ] + }, + { + "version": "2026.09.23-dashboard.storeStats.doc", + "date": "2026-09-23", + "type": "updated", + "summary": "补齐 dashboard.storeStats 接口文档:补充描述、13 个响应统计字段与错误码(无业务入参,依据登录用户上下文区分仓库端/货主端)", + "methods": [ + "dashboard.storeStats" + ], + "notes": [ + "核实 app/service/systemMethods/dashboard.js 实现后补齐", + "仓库端按当前用户 store_id 单仓统计;货主端跨已签约仓库(auth_status=2)汇总" + ] + }, + { + "version": "2026.09.23-index.tryAutoTranslateNewKeys.doc", + "date": "2026-09-23", + "type": "updated", + "summary": "补全 index.tryAutoTranslateNewKeys 文档:明确其为 putI18nCollect 的内部辅助方法,补充 project/targetLanguage 参数说明,注明无对外返回值、异常仅记日志、不建议作为 HTTP API 直接调用", + "methods": [ + "index.tryAutoTranslateNewKeys" + ], + "notes": [ + "代码事实:app/service/systemMethods/index.js:1512 async tryAutoTranslateNewKeys(project, targetLanguage),仅被 putI18nCollect(1451 行)内部调用;目标语言为 zh-CN 直接返回;为 zh-CN 已有翻译的键批量创建目标语言占位(translation=null、translation_status=0、auto_generated=1、translator=auto-translate);无返回值,异常被内部 try/catch 吞掉仅记日志。", + "文档库表同步:method-doc-update.cjs 更新 description/params 并 --bump(版本 0.3.169 -> 0.3.170),method-doc-export.cjs 回写 methods/system.json(562 个方法)。", + "说明:/system 通用分发不区分 public 与内部函数,该方法理论上可被直接调用,文档已注明不建议直接调用。" + ], + "module": "index" + }, + { + "version": "2026.09.23-wechat.dropAgreementVersionNumber", + "date": "2026-09-23", + "type": "updated", + "summary": "用户须知版本表去掉 version 数字版本号,直接使用 id 自增:最新版判定改 ORDER BY id DESC,提交即插入新行(去掉 max+1 与并发重试),接口响应只保留 version_id", + "methods": [ + "wechat.getUserAgreementText", + "wechat.getUserAgreement", + "wechat.setUserAgreement", + "wechat.getAgreementVersion", + "wechat.loginByCode" + ], + "notes": [ + "迁移 20260923140000-drop-version-from-wechat-agreement-version(开发+生产均执行):removeIndex uk_appid_version + removeColumn version;down 为加回列与唯一索引。同步 app/model/wechat_agreement_version.js 删 version 字段与唯一索引(仅保留 idx_appid)。", + "最新版判定统一为 ORDER BY id DESC(loginByCode/getUserAgreementText/getUserAgreement/findLatestAgreementVersion/cleanupUnusedAgreementVersions 的最终版=max(id));setUserAgreement 改为直接 create(appid+content),无并发重试;getUserAgreementText 缓存 JSON 仅 {version_id,text}。", + "接口响应精简:getUserAgreementText/getUserAgreement/setUserAgreement 去掉 version 字段、getAgreementVersion 去掉 version 字段,均保留 version_id(=记录 id)。" + ], + "module": "wechat" + }, + { + "version": "2026.09.23-wechat.getAgreementVersion", + "date": "2026-09-23", + "type": "added", + "summary": "新增 wechat.getAgreementVersion(按协议版本 id 获取协议内容,需登录免权限+校验仓库);wechat.userList 响应新增 agreement_version_id(协议id)", + "methods": [ + "wechat.getAgreementVersion", + "wechat.userList" + ], + "notes": [ + "wechat.getAgreementVersion:入参 id(wms_wechat_agreement_version.id,来源 userList 的 agreement_version_id),按 id 查版本 → 校验该版本 appid 属于当前仓库启用小程序(warehouse_id=ctx.user.store_id, is_enabled=1),不属于则提示「该协议版本不属于当前仓库的小程序」;返回 id/appid/nickname/version/text/created_at。需登录免权限(systemInit 第2/4参)。", + "wechat.userList:响应行新增 agreement_version_id(数值化,null 保持 null),sortField 白名单新增 agreement_version_id;该字段由 loginByCode 自动回写,供前端按版本 id 拉取协议内容。", + "代码变更:app/service/systems/wechat.js 新增 getAgreementVersion + userList 响应数值化/排序白名单;app/service/systemMethods/wechat.js 白名单与出口同步。" + ], + "module": "wechat" + }, + { + "version": "2026.09.23-wechat.agreementVersionCleanup", + "date": "2026-09-23", + "type": "updated", + "summary": "新增定时任务:每 1 小时扫描 wms_wechat_agreement_version,真实删除未使用且非对应 appid 最终版的历史版本,释放 MySQL 磁盘", + "methods": [], + "notes": [ + "保留规则:① 各 appid 的最终版(version 最大)永久保留;② 被 wms_user_oauth.agreement_version_id 引用的版本保留(老用户仍停留在旧协议);其余版本真实删除(模型 paranoid=false)。", + "触发:app/schedule/wechat_agreement_cleanup.js,cron 从 config.wechatAgreementCleanup.cron 读取(默认 0 0 * * * * = 每 1 小时整点,type=worker 单 worker 防重入,enable=false 不注册);清理逻辑收敛在 service.systems.wechat.cleanupUnusedAgreementVersions(batchSize 默认 500,按 id 分批删走主键索引)。", + "每次任务完成后输出日志:deleted/kept_latest/kept_in_use/total;失败仅记 error 日志不抛出。" + ], + "module": "wechat" + }, + { + "version": "2026.09.23-wechat.userAgreement.versioning", + "date": "2026-09-23", + "type": "updated", + "summary": "用户须知改为副表版本管理:移除 wms_wechat_app.user_agreement;新增 wms_wechat_agreement_version(appid+数字版本号+富文本,提交一次自动新增版本,拉取只取最新);wms_user_oauth 加 agreement_version_id,loginByCode 自动更新到最新协议版本", + "methods": [ + "wechat.getUserAgreementText", + "wechat.getUserAgreement", + "wechat.setUserAgreement", + "wechat.loginByCode" + ], + "notes": [ + "迁移 20260923130000-user-agreement-versioning(开发+生产均执行):① removeColumn wms_wechat_app.user_agreement;② createTable wms_wechat_agreement_version(id/appid/version INT/content LONGTEXT/时间戳,uk_appid_version(appid,version) 唯一 + idx_appid);③ addColumn wms_user_oauth.agreement_version_id(BIGINT UNSIGNED 可空,关联版本表 id)。同步 app/model/wechat_agreement_version.js 新增、wechat_app.js/user_oauth.js 字段同步。", + "wechat.setUserAgreement:提交一次自动新增版本——查该 appid 最大 version 后 +1 插入(并发撞唯一键时重算重试最多 3 次),成功后 cacheDel 清 24h 缓存;返回 version_id/version/text。", + "wechat.getUserAgreementText/getUserAgreement:拉取只拉最新版本(ORDER BY version DESC);getUserAgreementText 缓存 24h 存 JSON {version_id,version,text},命中 from_cache=true;无版本分别提示「未找到对应小程序或该小程序暂无用户须知」/「该小程序暂无用户须知」。", + "wechat.loginByCode:查该小程序 appid 最新协议版本 id,oauth 新增/更新时自动写入 agreement_version_id(无需前端传入,为空版本表时为 null)。", + "代码变更:app/service/systems/wechat.js loginByCode/getUserAgreementText/getUserAgreement/setUserAgreement 改版并新增 findLatestAgreementVersion;systemMethods 无签名变化。" + ], + "module": "wechat" + }, + { + "version": "2026.09.23-wechat.userAgreement", + "date": "2026-09-23", + "type": "added", + "summary": "新增用户须知三接口:wms_wechat_app 加 user_agreement(LONGTEXT)字段;wechat.getUserAgreementText(免登录,appId 查询 + 24h Redis 缓存)、wechat.getUserAgreement(需登录,当前仓库)、wechat.setUserAgreement(需登录,更新并清缓存)", + "methods": [ + "wechat.getUserAgreementText", + "wechat.getUserAgreement", + "wechat.setUserAgreement" + ], + "notes": [ + "迁移 20260923120000-add-user-agreement-to-wms-wechat-app:wms_wechat_app 仅加 user_agreement 字段(Sequelize TEXT('long') = LONGTEXT,allowNull,comment 用户须知富文本),同步 app/model/wechat_app.js。开发+生产均需执行(生产:$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production)。", + "wechat.getUserAgreementText:免登录(systemInit 第1参),入参 appId;Redis key wechat:userAgreement:{appid},TTL 24h,命中直接返回 from_cache=true;未命中查 wms_wechat_app.user_agreement 并回写缓存;无该 appid 返回「未找到对应小程序」。", + "wechat.getUserAgreement/setUserAgreement:需登录免权限(systemInit 第2/4参),按 ctx.user.store_id 取启用小程序(is_enabled=1),无则提示「无小程序,需要先绑定」;set 校验 text 为字符串(可空串清空)→ update 后 cacheDel 清除 24h 缓存。", + "代码变更:app/service/systems/wechat.js 新增 getUserAgreementText/getUserAgreement/setUserAgreement/findWarehouseWechatApp;app/service/systemMethods/wechat.js 白名单与出口同步。" + ], + "module": "wechat" + }, + { + "version": "2026.09.23-wechat.bindByEmployee", + "date": "2026-09-23", + "type": "added", + "summary": "新增 wechat.bindByEmployee:管理员按工号绑定微信(需登录需权限),传工号 id + 微信绑定记录 id,查工号账号 id 写入 wms_user_oauth.user_id", + "methods": [ + "wechat.bindByEmployee" + ], + "notes": [ + "新增接口 wechat.bindByEmployee(需登录需权限,区别于中间层 wechat.bindUser 的用户名密码自绑定):入参 id(工号 id=wms_account_store_employee.id,必填正整数)与 oauth_id(微信绑定记录 id=wms_user_oauth.id,必填正整数,来自 wechat.userList 结果)。", + "业务:工号存在且 status=1 → account_id;工号须属于当前仓库(store_id=ctx.user.store_id);oauth 须存在、provider=wechat、未绑定或已绑定同一账号(已绑其他账号拒绝换绑);oauth.app_id 存在时校验对应 wms_wechat_app 属于当前仓库;账号存在且 status=1。校验通过后 wms_user_oauth.user_id=account_id,幂等返回 already_bound。不签发 token。", + "鉴权:不加入 systemInit 任何白名单 → 需正常登录 token 且需 wms_permission 接口权限(path=wechat.bindByEmployee,type=api,需在开发库插入该权限记录并由管理员在角色中勾选后生效)。", + "代码变更:app/service/systems/wechat.js 新增 bindByEmployee;app/service/systemMethods/wechat.js 新增 bindByEmployee 出口。" + ], + "module": "wechat" + }, + { + "version": "2026.09.23-wechat.wxaauth-new-api", + "date": "2026-09-23", + "type": "updated", + "summary": "wechat.wxaauth 迁移到微信新版认证接口:旧接口 /wxa/sec/wxaapi/wxaauth、/wxa/sec/wxaapi/uploadmedia 已下线(40066 invalid url),改为 POST /wxa/sec/wxaauth(auth_data 包裹)+ POST /wxa/sec/uploadauthmaterial(mediaid)", + "methods": [ + "wechat.wxaauth" + ], + "notes": [ + "根因:微信下线旧版小程序认证接口,调用 /wxa/sec/wxaapi/wxaauth 与 /wxa/sec/wxaapi/uploadmedia 返回 40066 invalid url(与 queryauth 当年同因:路径不存在,详见 2026.09.22-wechat.queryauth-fix 记录)。", + "发起认证改为 POST /wxa/sec/wxaauth,请求体 { auth_data }:customer_type(1 企业/12 个体户/15 个人)、account_name、account_name_type(1 自选词汇/2 商标)、pay_type(1 服务商预购包/2 自行支付)、third_party_phone、contact_info{name,email,mobile?} 必填;invoice_info/qualification/qualification_other(≤10)/account_supplemental/auth_identification/auth_ident_material/service_appid(代缴必填)/taskid 可选。", + "上传材料改为 POST /wxa/sec/uploadauthmaterial(multipart media=文件,图片 ≤2M,PNG/JPEG/JPG/GIF),返回 mediaid(lib 层归一化为 media_id)。自动换 mediaid 的图片字段:qualification(单张)、qualification_other[]/account_supplemental[]/auth_ident_material[](数组),支持传 COS URL。", + "破坏性变更:入参由旧扁平字段(contact_type/contact_name/contact_cert_photo/business_license_*/legal_persona_*/pic_list/qualification_list/statement_list 等 33 字段白名单)改为新版 auth_data 字段,前端需同步切换。打回重填走新接口 POST /wxa/sec/reauth(同 auth_data + taskid,暂未接入,可后续补 wechat.reauth)。", + "代码变更:app/lib/wechat_open_client.js wxaauth/uploadAuthMedia 路径与 mediaid 归一化;app/service/systems/wechat.js wxaauth/resolveBodyMedia/resolveMediaValue 换新字段;app/service/systemMethods/wechat.js 注释同步。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.wxaauth-cos-url", + "date": "2026-09-22", + "type": "updated", + "summary": "wechat.wxaauth 改为后端分步:图片字段传 COS 文件 URL,后端下载 → uploadmedia 换 media_id → wxaauth 提交", + "methods": [ + "wechat.wxaauth" + ], + "notes": [ + "后端分步:① 图片字段值为 http/https(COS URL)时,后端 GET 下载 Buffer → POST /wxa/sec/wxaapi/uploadmedia(multipart/form-data,media_type=image,media=临时文件)换 media_id;② 替换请求体后调 /wxa/sec/wxaapi/wxaauth 提交。非 URL 值视为已传 media_id 原样透传。", + "支持自动换 media_id 的图片字段:顶层 contact_cert_photo/business_license_copy/legal_persona_idcard_copy/legal_persona_media;pic_list 项的 pic_url;qualification_list 项 licence_list/certificate_list 的 value;statement_list 项的 value。", + "uploadmedia 实现细节:Buffer 写临时文件(文件名带 jpg/jpeg/png 扩展名,从 URL path 提取,默认 image.jpg)后按路径传 files:{media}(urllib 2.44 files 支持 Buffer 但文件名固定 bufferfileN 无扩展名,故落临时文件保证扩展名),finally 删除临时文件;40001/40014 清 authorizer token 重试一次。media_id 3 天内有效。", + "代码变更:app/lib/wechat_open_client.js 新增 uploadAuthMedia;app/service/systems/wechat.js 新增 resolveBodyMedia/resolveMediaValue/downloadFromUrl/resolveMediaFilename 并在 wxaauth 中调用。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.wxaauth", + "date": "2026-09-22", + "type": "added", + "summary": "新增 wechat.wxaauth 发起小程序认证(一步提交):前端上传材料换 media_id 后传入,后端调 wxa/sec/wxaapi/wxaauth,成功回写 auth_task_id/auth_apply_status", + "methods": [ + "wechat.wxaauth" + ], + "notes": [ + "新增接口 wechat.wxaauth(需登录免权限,权限集 18):前端负责上传材料换取 media_id 后一步提交;入参白名单透传(contact_type/contact_name 必填,其余 contact_*/business_license_*/legal_persona_*/pic_list 等 33 字段白名单)。", + "成功回写 wms_wechat_app.auth_task_id=taskid、auth_apply_status(auth_task_status 置空),返回 taskid/auth_url/apply_status;taskid 供 wechat.queryauth 查询进度(taskid 可选,库中 auth_task_id 兜底)。", + "已认证(verify_type_id>=0)拒绝重复发起;未授权权限集 18 拒绝。lib#wxaauth 40001/40014 清 authorizer token 重试一次。不拆表:认证状态继续复用 wms_wechat_app 现有字段,无迁移。", + "代码变更:app/lib/wechat_open_client.js 新增 wxaauth;app/service/systems/wechat.js 新增 wxaauth;systemMethods/wechat.js 白名单与出口同步。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.queryauth-verified-first", + "date": "2026-09-22", + "type": "updated", + "summary": "wechat.queryauth 改为先判已认证再查进度:已认证直接返回认证信息;未认证且有 taskid 才调微信查进度;taskid 可选(库中 auth_task_id 兜底);认证通过回写 verify_type_id=0", + "methods": [ + "wechat.queryauth" + ], + "notes": [ + "判定顺序:① 本地 wms_wechat_app.verify_type_id>=0(已认证)→ 直接返回本地认证信息(is_verified=true/verify_type_id/principal_name/signature/service_type_id/account_status),不调微信;② 未认证(null/-1)→ taskid(入参优先,其次库中 auth_task_id)调 wxa/sec/queryauth 查进度;③ 未认证且无 taskid → 返回 code 200「尚未认证且无认证任务」(is_verified=false)。", + "落库:查询成功回写 auth_task_id/auth_task_status/auth_apply_status;apply_status=4(认证通过)时同时回写 verify_type_id=0(微信认证),后续 queryauth 直接走已认证分支。", + "文档:system.json wechat.queryauth 条目 params(taskid 改可选)/response(新增 is_verified/verify_type_id/principal_name 等)同步。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.getAuthorizerInfo-db-fields", + "date": "2026-09-22", + "type": "added", + "summary": "新增 wechat.getAuthorizerInfo 基础信息接口;wms_wechat_app 补充授权账号基础信息与认证状态字段(13列);认证 taskid/状态随 queryauth 成功落库", + "methods": [ + "wechat.getAuthorizerInfo", + "wechat.queryauth" + ], + "notes": [ + "新增接口 wechat.getAuthorizerInfo(需登录免权限):调微信 POST /cgi-bin/component/api_get_authorizer_info(component_access_token)拉取 authorizer_info + authorization_info,将基础信息/认证类型/权限集落库 wms_wechat_app 后返回完整数据。", + "迁移 20260922180000-add-authorizer-info-fields-to-wms-wechat-app:wms_wechat_app 新增 principal_name/signature/alias/qrcode_url/service_type_id/verify_type_id/account_status/register_type/business_info/mini_program_info/auth_task_id/auth_task_status/auth_apply_status,开发+生产均已执行。", + "verify_type_info.id 语义:-1 未认证、0 微信认证、1 新浪微博认证、3 资质通过未名称认证、4 同3+微博;account_status:1 正常、14 已注销、16 已封禁、18 已告警、19 已冻结。", + "认证任务落库口径:taskid 由发起认证接口(wxa/sec/wxaapi/wxaauth,暂未接入)返回,queryauth 查询成功后回写 auth_task_id/auth_task_status/auth_apply_status。", + "代码变更:app/lib/wechat_open_client.js 新增 getAuthorizerDetail(完整返回);app/service/systems/wechat.js 新增 buildAuthorizerPatch/getAuthorizerInfo、queryauth 增加状态落库;app/controller/wechatOpen.js 授权回调/authorized/updateauthorized 事件改用 getAuthorizerDetail 全量字段落库;app/model/wechat_app.js、systemMethods/wechat.js 同步。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.getAuthUrl-scope", + "date": "2026-09-22", + "type": "updated", + "summary": "wechat.getAuthUrl 授权链接限定授权范围:auth_type=2(仅小程序)+ category_id_list=18|86(代码管理、体验版二维码)", + "methods": [ + "wechat.getAuthUrl" + ], + "notes": [ + "修正认知:auth_type 是授权账号类型(1公众号/2小程序/3公众号+小程序),不是权限范围;权限范围由 category_id_list(权限集 id 列表,竖线分隔)或商家在授权页自定义勾选控制。业务所需权限集:18=小程序代码管理(commit/submit_audit/queryauth/get_qrcode)、86=体验版二维码;getTemplateList/jscode2session/快速注册不需要商家权限集。", + "代码变更:app/service/systems/wechat.js#getAuthUrl 授权链接增加 category_id_list=18|86、auth_type 改为 2。前提:18/86 需在微信开放平台后台「权限集」配置并全网发布,否则商家授权页看不到;已授权商家需重新扫码授权才能获得 18/86。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.commit-ext-json-default", + "date": "2026-09-22", + "type": "updated", + "summary": "wechat.commit 的 ext_json 改为后端默认生成(仅 extEnable+extAppid),不再由前端传入", + "methods": [ + "wechat.commit" + ], + "notes": [ + "入参仅剩 template_id;ext_json 由后端生成 JSON.stringify({extEnable:true, extAppid: 当前小程序appid}),前端传值被忽略;响应新增 ext_json 回显。", + "代码变更:app/service/systems/wechat.js#commit;文档 system.json wechat.commit 条目 params/response 同步。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.commit-desc-from-template", + "date": "2026-09-22", + "type": "updated", + "summary": "wechat.commit 代码描述也改为从模板取:user_version 与 user_desc 均不再由外部传入", + "methods": [ + "wechat.commit" + ], + "notes": [ + "入参进一步瘦身:user_desc 也移除(外部传入被忽略);commit 流程:getTemplateList(0) → 按 template_id 找模板 → 取模板 user_version(≤64)与 user_desc 作为上传版本号/代码描述(缺失分别报「模板缺少合法版本号/缺少代码描述」)→ wxa/commit 成功后回写 wms_wechat_app.template_id/user_version;响应新增 user_desc。", + "代码变更:app/service/systems/wechat.js#commit;文档 system.json wechat.commit 条目 params/response 同步。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.userList", + "date": "2026-09-22", + "type": "added", + "summary": "新增微信模块 wechat.userList(需登录):拉取当前仓库小程序的用户列表(wms_user_oauth),支持 where/pagination/sort", + "methods": [ + "wechat.userList" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.userList(isNeedLogin=true、isNeedAuth=false、Authorization 头):按 ctx.user.store_id 取仓库启用小程序(wms_wechat_app,is_enabled=1;可选 app_id 指定单个,须属于当前仓库),查询 wms_user_oauth(provider=wechat,app_id IN 命中应用);入参 where(字段白名单 id/user_id/app_id/openid/unionid/nickname/sex/login_time/login_count/created_at/updated_at,operator 结构,经 prepareWhereContext 解析)、pagination(page/pageSize)、sort(sortField 白名单同上,默认 updated_at DESC)。", + "代码变更:app/service/systems/wechat.js#userList(findAndCountAll,attributes 排除 session_key/refresh_token/access_token/expire_in/expire_time/login_code 敏感字段,raw+is_bound);app/service/systemMethods/wechat.js 出口 + where 字段白名单过滤 + _noNeedRight/_noNeedLog/_noNeedAuth 白名单加入 userList。", + "无数据库变更(纯只读查询)。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.queryauth-fix", + "date": "2026-09-22", + "type": "updated", + "summary": "修复 wechat.queryauth:接口路径改为 wxa/sec/queryauth 并新增必填入参 taskid,响应改为 task_status/apply_status", + "methods": [ + "wechat.queryauth" + ], + "notes": [ + "根因:此前实现误用 /wxa/sec/wxaapi/queryauth 且未传 taskid,微信返回 40066 invalid url;官方接口为 POST /wxa/sec/queryauth?access_token=authorizer_access_token,请求体必填 taskid(发起认证接口 wxa/sec/wxaapi/wxaauth 返回)。", + "修复:lib#queryMiniProgramAuth 改路径并传 { taskid },40001/40014 清 authorizer token 重试;systems#queryauth 新增 taskid 必填校验,响应返回 task_status/apply_status/orderid/auth_url 等并附中文文案;文档 system.json queryauth 条目同步更新。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.submitAudit", + "date": "2026-09-22", + "type": "added", + "summary": "新增微信模块 wechat.submitAudit(需登录):提交代码审核,wms_wechat_app 新增审核状态字段(开发+生产已迁移)", + "methods": [ + "wechat.submitAudit" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.submitAudit(isNeedLogin=true、isNeedAuth=false、Authorization 头):入参白名单 item_list/feedback_info/feedback_stuff/preview_info/version_desc/privacy_api_not_use/order_info/ugc_declare;校验权限集 18;仅 audit_status!=1 时允许提交;POST wxa/submit_audit(authorizer_access_token,40001/40014 清缓存重试)成功后回写 audit_status=1、audit_id。", + "数据库:迁移 20260922170000-add-audit-fields-to-wms-wechat-app.js(user_version/audit_status/audit_id/audit_reason),开发与生产均已执行;commit 同步回写 user_version;审核结果事件 weapp_audit_success→audit_status=2、weapp_audit_fail→audit_status=3+audit_reason(按 ToUserName=user_name 定位)。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.getTrialQRCode", + "date": "2026-09-22", + "type": "added", + "summary": "新增微信模块 wechat.getTrialQRCode(需登录):获取体验版二维码(转存 COS 返回 URL)", + "methods": [ + "wechat.getTrialQRCode" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.getTrialQRCode(isNeedLogin=true、isNeedAuth=false、Authorization 头):入参 path(可选);按 ctx.user.store_id 取仓库启用小程序,hasFuncScope 校验权限集 18 或 86;GET wxa/get_qrcode(authorizer_access_token,path 自动 urlencode,40001/40014 清 authorizer token 缓存重试)返回 jpeg 图片,经 upload.uploadBuffer 转存 COS(key=qrcode/wechat/{warehouseId}/{yyyymmdd}/{ts}{rand}.jpg)后返回 URL。", + "代码变更:app/lib/wechat_open_client.js#getTrialQRCode;app/service/systems/wechat.js#getTrialQRCode/#buildTrialQrCodeKey;app/service/systemMethods/wechat.js 出口 + _noNeedRight/_noNeedAuth 白名单。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.commit", + "date": "2026-09-22", + "type": "added", + "summary": "新增微信模块 wechat.commit(需登录):上传代码并生成体验版,wms_wechat_app 新增 template_id 字段(开发+生产已迁移)", + "methods": [ + "wechat.commit" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.commit(isNeedLogin=true、isNeedAuth=false、Authorization 头):入参 template_id/ext_json/user_version(≤64)/user_desc;按 ctx.user.store_id 取仓库启用小程序,hasFuncScope(func_info, 18) 校验代码管理权限集,getTemplateList(0) 校验模板存在(微信 85014 兜底),POST wxa/commit(authorizer_access_token,40001/40014 清 authorizer token 缓存重试)成功后回写 wms_wechat_app.template_id。", + "数据库:迁移 20260922160000-add-template-id-to-wms-wechat-app.js(wms_wechat_app.template_id bigint unsigned nullable),已在开发(127.0.0.1:3307)与生产(112.124.21.102)执行并验证;app/model/wechat_app.js 同步 template_id 字段。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.getTemplateList", + "date": "2026-09-22", + "type": "added", + "summary": "新增微信模块 wechat.getTemplateList(需登录):获取普通模板库列表,Redis 缓存 24h", + "methods": [ + "wechat.getTemplateList" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.getTemplateList(isNeedLogin=true、isNeedAuth=false、Authorization 头):只拉普通模板(template_type=0,GET wxa/gettemplatelist + component_access_token,40001 自愈);Redis key wechat:template:list:normal 缓存 24h,有缓存直接返回(from_cache=true),无缓存拉取后写缓存。", + "代码变更:app/lib/wechat_open_client.js#getTemplateList(GET 请求封装);app/service/systems/wechat.js#getTemplateList;app/service/systemMethods/wechat.js 出口 + _noNeedRight/_noNeedAuth 白名单。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.getMyLoginCode", + "date": "2026-09-22", + "type": "added", + "summary": "新增 wechat.getMyLoginCode:获取当前微信登录用户的登录码(至少微信登录),无则生成写入、有则直接返回", + "methods": [ + "wechat.getMyLoginCode" + ], + "notes": [ + "systemMethods/wechat.js 白名单:_noNeedBind 新增 getMyLoginCode(微信登录态中间层,未绑定真实用户也可访问,业务层校验 ctx.oauth);systems/wechat.js 新增 getMyLoginCode:ctx.oauth 定位 wms_user_oauth,login_code 为空时 buildLoginCode(id) 生成(uuid={id}_{6位随机}、form=wechat 的 JSON base64)并回写,已有直接返回;system.json 微信模块新增该 method" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.uploadHeadimg", + "date": "2026-09-22", + "type": "added", + "summary": "新增微信模块 wechat.uploadHeadimg(微信登录态中间层):上传裁剪后的 PNG 头像(<500K)并回写 headimgurl", + "methods": [ + "wechat.uploadHeadimg" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.uploadHeadimg(中间层鉴权,至少微信登录即可,未绑定也可):入参 image(PNG base64,支持 data URL 前缀);校验大小 <500K 与 PNG 文件头魔数后经 upload.uploadBuffer 上传 COS(key=headimg/wechat/{yyyymmdd}/{timestamp}{random}.png,不依赖仓库上下文),回写 wms_user_oauth.headimgurl 并返回 URL。", + "代码变更:app/service/systems/upload.js#uploadBuffer(Buffer 直传 COS);app/service/systems/wechat.js#uploadHeadimg/#buildHeadimgKey;app/service/systemMethods/wechat.js 出口 + _noNeedBind 白名单。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.updateInfo", + "date": "2026-09-22", + "type": "added", + "summary": "新增微信模块 wechat.updateInfo(微信登录态中间层):未绑定用户更新自己的昵称/头像", + "methods": [ + "wechat.updateInfo" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.updateInfo(中间层鉴权,需有效微信登录态 token):仅未绑定真实用户(wms_user_oauth.user_id=0)可更新 nickname(≤255)/headimgurl(≤500),可部分更新,至少一个字段;已绑定账号返回「账号已绑定,不支持修改微信资料」。", + "代码变更:app/service/systems/wechat.js#updateInfo;app/service/systemMethods/wechat.js 出口 + _noNeedBind 白名单加入 updateInfo。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-user.info-wechat-appId-filter", + "date": "2026-09-22", + "type": "updated", + "summary": "user.info 新增可选入参 wechat_appId:传入时按小程序归属仓库过滤工号列表(仅保留非仓库工号(货主)+ 该仓库工号)", + "methods": [ + "user.info" + ], + "notes": [ + "user.info 新增可选入参 wechat_appId:按 wms_wechat_app.appid(is_enabled=1)反查归属 warehouse_id,有仓库时过滤返回的 user.employees —— 保留 role_type!=warehouse(货主工号)或 store_id=该仓库 的工号;未传或查不到仓库保持原逻辑。", + "代码变更:app/service/systems/auth/user.js#info 增加 data.wechat_appId 处理(method 层 user.info 已透传 data)。" + ], + "module": "user" + }, + { + "version": "2026.09.22-wechat.registerMiniprogram", + "date": "2026-09-22", + "type": "added", + "summary": "新增微信模块 wechat.registerMiniprogram(需登录):快速注册企业小程序", + "methods": [ + "wechat.registerMiniprogram" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.registerMiniprogram(isNeedLogin=true、isNeedAuth=false、Authorization 头):入参 name/code/code_type/legal_persona_wechat/legal_persona_name(必填)+ component_phone(选填),校验后调微信 fastregisterweapp?action=create(component_access_token,40001 自愈重试);注册任务创建后法人微信收到模板消息做人脸核身,审核结果通过 notify_third_fasteregister 事件推送到授权事件接收 URL(后续需在 handleEvent 中处理该事件绑定仓库)。", + "代码变更:app/lib/wechat_open_client.js#fastRegisterWeapp(create/search 通用封装 + 40001 自愈);app/service/systems/wechat.js#registerMiniprogram;app/service/systemMethods/wechat.js 出口 + _noNeedRight/_noNeedAuth 白名单。" + ], + "module": "wechat" + }, + { + "version": "2026.09.22-wechat.queryauth", + "date": "2026-09-22", + "type": "added", + "summary": "新增微信模块 wechat.queryauth(需登录):查询当前仓库小程序的认证状态", + "methods": [ + "wechat.queryauth" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.queryauth(isNeedLogin=true、isNeedAuth=false、Authorization 头):按 ctx.user.store_id 取仓库启用小程序(wms_wechat_app,is_enabled=1,id ASC 取第一条),用 authorizer_access_token 调微信 wxa/sec/wxaapi/queryauth 返回 auth_state(0 未认证/1 认证中/2 认证通过/3 认证失败)并附 auth_state_text 中文文案。", + "代码变更:app/lib/wechat_open_client.js#queryMiniProgramAuth(authorizer_access_token 调 wxa/sec/wxaapi/queryauth,支持 DB 落库的 authorizer_refresh_token 兜底 Redis 丢失);app/service/systems/wechat.js#queryauth;app/service/systemMethods/wechat.js 出口 + _noNeedRight/_noNeedAuth 白名单加入 queryauth。" + ], + "module": "wechat" + }, + { + "version": "2026.09.21-wechat.pushLoginCode-legacy-code", + "date": "2026-09-21", + "type": "updated", + "summary": "弃用 wechat.getLoginWechatCode,wechat.pushLoginCode 改为复用旧 user.getLoginWechatCode 生成的登录码", + "methods": [ + "wechat.pushLoginCode" + ], + "notes": [ + "弃用新增的 wechat.getLoginWechatCode(移除 systems/method 层与文档);小程序端继续使用旧 user.getLoginWechatCode 生成/轮询 6 位字母+数字登录码(user:wechat:login:code:* / client key,TTL 60s)。", + "wechat.pushLoginCode(需登录免权限)改造:读旧码缓存(getWechatLoginCodeCacheKey)取 client_code,经 findYe4sBindingByAccountId 反查当前账号 ye4s_user,将 ye4s_user_id 双写旧登录码缓存(code key + client key,TTL 按剩余有效期),旧轮询方读到 ye4s_user_id 即走 loginByYe4sUserId 直登返回正常 WMS token。" + ], + "module": "wechat" + }, + { + "version": "2026.09.21-wechat.loginCode-flow", + "date": "2026-09-21", + "type": "added", + "summary": "新增微信模块 wechat.getLoginWechatCode / wechat.pushLoginCode:小程序端生成 6 位登录码轮询,PC 已登录用户确认后小程序端返回登录成功并绑定账号", + "methods": [ + "wechat.getLoginWechatCode", + "wechat.pushLoginCode" + ], + "notes": [ + "getLoginWechatCode(微信登录态中间层 _noNeedBind):不传 code 生成 6 位数字登录码写 Redis(key wechat:login:code:{code},TTL 300s,记录 oauth_id);传 code 轮询状态 pending/expired/success;success 时校验归属 oauth_id、一次性消费登录码、绑定 wms_user_oauth.user_id=确认账号(防换绑)并签发登录 token(id=账号ID、oauth_id 保留)。", + "pushLoginCode(需登录、免权限):PC/Web 已登录用户传 code,将对应缓存态置 success 并写入 account_id(TTL 120s 等待小程序领取);登录码归属校验防止他人码窃取登录。", + "代码变更:app/service/systems/wechat.js#getLoginWechatCode/#pushLoginCode/#createLoginCode/#getLoginCodeCacheKey、app/service/systemMethods/wechat.js(出口 + _noNeedBind 白名单 + _noNeedRight 加入 pushLoginCode)。" + ], + "module": "wechat" + }, + { + "version": "2026.09.21-wechat.loginByCode-appid-string", + "date": "2026-09-21", + "type": "updated", + "summary": "wechat.loginByCode 应用标识兼容字符串 appid:新增 appid(微信 AppID 字符串)入参按 uk_appid 反查,app_id(整数主键)保留向后兼容", + "methods": [ + "wechat.loginByCode" + ], + "notes": [ + "微信 AppID 是字符串(如 wx6e91ec813bcb7eec),小程序端应传 appid 字符串(模板小程序运行时取 wx.getAccountInfoSync().miniProgram.appId)而非数据库主键。", + "代码变更:app/service/systems/wechat.js 新增 resolveWechatApp(优先 app_id 主键,其次 appid 按 uk_appid 反查并过滤 is_enabled=1);loginByCode 经 resolveWechatApp 解析应用记录,wms_user_oauth.app_id 仍存 wms_wechat_app.id(整数外键)。文档 system.json loginByCode 入参补充 appid 字段说明。" + ], + "module": "wechat" + }, + { + "version": "2026.09.21-user.info-oauth-middle", + "date": "2026-09-21", + "type": "updated", + "summary": "user.info 支持微信登录态中间层:微信登录未绑定时返回微信层信息(is_bound=false),不 401", + "methods": [ + "user.info" + ], + "notes": [ + "systemMethods/user.js 构造器新增 _noNeedBind='info'(systemInit 第 5 参),微信登录态 token 可调用 user.info;auth.user.info 增加分支:未绑定真实用户(ctx.oauth 存在且无 ctx.user)时返回微信层信息(id=0/is_bound=false/oauth_id/openid/unionid/nickname/headimgurl/login_time/login_count,code 200),不 401;绑定/正常登录仍返回 findById 完整信息。", + "代码变更:app/service/systems/auth/user.js#info、app/service/systemMethods/user.js;撤销前版 wechat.getUserInfo(用户要求 getUserInfo 为公用接口,不收在 wechat 模块)。" + ], + "module": "user" + }, + { + "version": "2026.09.21-wechat.bindUser", + "date": "2026-09-21", + "type": "added", + "summary": "新增微信模块 wechat.bindUser(微信登录态中间层):用户名密码一致则绑定 wms_user_oauth.user_id 并签发绑定后的新 token", + "methods": [ + "wechat.bindUser" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.bindUser(中间层鉴权:需有效微信登录态 token,未绑定真实用户也可调用):入参 username(用户名/手机号/邮箱)+ password;复用 auth.user 的 findUserByIdentifier/checkUserStatus/verifyPassword 校验;一致则 wms_user_oauth.user_id 绑定账号并签发新 token(payload id=账号ID、oauth_id 保留);已绑定时仅允许本人凭据幂等调用,不允许换绑。", + "鉴权机制:app/service/main.js checkAuth 新增中间层白名单 _noNeedBind(systemInit 第 5 参),oauth token 有效即通过(user_id=0 也可),ctx.oauth/ctx.oauthId 注入微信身份,不查 API 权限;代码变更:app/service/systemMethods/wechat.js(bindUser 出口 + _noNeedBind 白名单)、app/service/systems/wechat.js#bindUser/#buildBindResult。" + ], + "module": "wechat" + }, + { + "version": "2026.09.21-wechat.loginByCode", + "date": "2026-09-21", + "type": "added", + "summary": "新增微信模块 wechat.loginByCode(免登录):小程序 wx.login code 换 openid/session_key 并查/建 wms_user_oauth,返回 token+user", + "methods": [ + "wechat.loginByCode" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.loginByCode(免登录 isNeedLogin=false):入参 code(wx.login 获取)+ app_id(wms_wechat_app.id);jscode2session(GET /sns/component/jscode2session)换 openid/session_key/unionid;wms_user_oauth 有记录则刷新 login_time/login_count/session_key,无记录则创建且 user_id=0(未绑定);JWT payload 记录 oauth_id(wms_user_oauth.id),区别于正常登录的用户 id 字段。", + "代码变更:app/lib/wechat_open_client.js#jscode2session(GET 请求封装);app/service/systems/wechat.js#loginByCode;app/service/systemMethods/wechat.js 免登录白名单加入 loginByCode。" + ], + "module": "wechat" + }, + { + "version": "2026.09.21-workbench.packOrder-business-users-restore", + "date": "2026-09-21", + "type": "updated", + "summary": "workbench.business 的 packOrder 分支恢复支持传入 users 上报打包人(未上报时回填工作台成员);token+key 新链路保持剥离 users", + "methods": [ + "workbench.business" + ], + "notes": [ + "业务旧链路(workbench.business 的 packOrder 分支)恢复 users 上报生效:上报时以上报为准,未上报时自动回填该工作台绑定成员(wms_workbench_member);token+key 新链路(workbench.packOrder)保持剥离 users、一律取工作台绑定成员。", + "代码变更:app/service/systems/workbench.js#_packOrder 恢复 users 入参(上报优先、未报回填)、#packOrderByToken 解构剥离 users;回归测试 test/workbench_pack_waybill_dimension.test.cjs(26 用例)。" + ], + "module": "workbench" + }, + { + "version": "2026.09.21-wechat.getAuthUrl", + "date": "2026-09-21", + "type": "added", + "summary": "新增微信模块 wechat.getAuthUrl:生成微信开放平台小程序授权链接(PC版),state 缓存仓库信息用于回跳绑定", + "methods": [ + "wechat.getAuthUrl" + ], + "notes": [ + "system.json 新增 module=wechat 方法 wechat.getAuthUrl(需登录);app/service/systems/wechat.js + app/service/systemMethods/wechat.js 生成授权链接;state=随机串,缓存 key wechat_auth_state:{state}(TTL 600s)存仓库信息;GET /Authorization 回跳凭 state 绑定仓库并落库 wms_wechat_app;state 缺失/过期展示错误页 app/view/wechat_auth_callback.html;配置 wechatOpen.redirect_uri" + ], + "module": "wechat" + }, + { + "version": "2026.09.21-workbench.getWorkbenchInfo-order-fields", + "date": "2026-09-21", + "type": "updated", + "summary": "workbench.getWorkbenchInfo 的 current_orders 补齐货主备注(store_remark)与运单信息(express:物流公司/称重重量/包材名称),与 queryOrder 口径一致", + "methods": [ + "workbench.getWorkbenchInfo" + ], + "notes": [ + "背景:getWorkbenchInfo 返回的 current_orders 相比 queryOrder 缺货主备注与包材信息,前端无法填充。", + "散单任务(pack_mode=1)按 order_id(优先任务 waybill_code)补 wms_order_express 的 logistics_name/weighing_weight/package_material_name_snapshot 与 wms_store_warehouse.store_remask;团购任务为波次维度不适用(store_remark 空、express 为 null)。查询并行执行,异常降级不阻断主信息。", + "代码变更:app/service/systems/workbench.js#buildCurrentPackingInfo;回归测试 test/workbench_pack_waybill_dimension.test.cjs(24 用例)。" + ], + "module": "workbench" + }, + { + "version": "2026.09.21-workbench.packOrder-key-forward-fix", + "date": "2026-09-21", + "type": "updated", + "summary": "修复 workbench.packOrder method 层未透传 key 导致 key 模式不生效(请求带 key 仍报发货单号不能为空)", + "methods": [ + "workbench.packOrder" + ], + "notes": [ + "根因:app/service/systemMethods/workbench.js#packOrder 解构白名单未包含 key,packOrderByToken 收不到 key 回退旧参数模式,新客户端只传 token+key 时报「发货单号不能为空」。", + "修复:method 层透传 key;回归测试 test/workbench_pack_waybill_dimension.test.cjs 新增 method 层透传用例(22 用例)。" + ], + "module": "workbench" + }, + { + "version": "2026.09.21-workbench.packOrder-legacy-compat", + "date": "2026-09-21", + "type": "updated", + "summary": "workbench.packOrder 代码保留旧参数模式过渡兼容(不传 key 时直传参数),文档主推 token+key 新接口", + "methods": [ + "workbench.packOrder", + "workbench.business" + ], + "notes": [ + "设备端过渡方案:代码同时支持新 key 模式(优先)与旧参数模式(不传 key 时直传 delivery_order_code 等,后续版本移除),文档按 token+key 新接口展示。", + "代码变更:app/service/systems/workbench.js#packOrderByToken 与 #business(packOrder) 分支恢复旧参数回退;回归测试 test/workbench_pack_waybill_dimension.test.cjs(21 用例,含旧参数兼容)。" + ], + "module": "workbench" + }, + { + "version": "2026.09.21-workbench.packOrder-key-only", + "date": "2026-09-21", + "type": "updated", + "summary": "workbench.packOrder 除 token、key 外不再接收任何订单相关信息:订单参数一律由后端从打包上下文缓存拉取(防篡改)", + "methods": [ + "workbench.packOrder", + "workbench.business" + ], + "notes": [ + "workbench.packOrder 入参收敛为 token + key,移除旧参数(delivery_order_code/waybill_code/wave_no/status/pack_time/wave_total_orders/items_count/items_total),body 传入其它字段一律忽略;缺 key 返回 400、key 过期返回 400、跨仓库/跨工作台使用返回 403。", + "workbench.business 的 packOrder 分支同样只接受 key(订单信息取自缓存,仓库/工作台取缓存值)。", + "代码变更:app/service/systems/workbench.js 新增 _loadPackCtx(凭 key 拉取缓存,缺 key/过期抛错);packOrderByToken 只取 token+key 并捕获 _loadPackCtx 异常转 400;business(packOrder) 分支改走 key 消费。", + "回归测试 test/workbench_pack_waybill_dimension.test.cjs(21 用例,含缺 key 400、business 只接受 key、body 订单参数忽略)。" + ], + "module": "workbench" + }, + { + "version": "2026.09.21-workbench.packOrder-key-mode", + "date": "2026-09-21", + "type": "updated", + "summary": "workbench.queryOrder 返回打包上下文 key(20 分钟缓存);workbench.packOrder 精简为 token+key 消费缓存参数(旧参数模式保留兼容)", + "methods": [ + "workbench.queryOrder", + "workbench.packOrder" + ], + "notes": [ + "workbench.queryOrder 扫码查询成功时生成打包上下文 key(wpck 前缀 + 32 位随机段),缓存 key workbench:packctx:{key}、TTL 1200s,内容含 warehouse_id/workbench_id/order_id/delivery_order_code/wave_no/waybill_code/is_sandan,响应新增 key 字段;缓存写入失败仅告警不阻断查询。", + "workbench.packOrder 推荐只传 token + key:后端按 key 拉取缓存参数执行打包(数量参数后端复查兜底),跨仓库/跨工作台消费他人 key 返回 403、key 过期返回 400(提示重新扫码);旧参数模式(不传 key 直接传 delivery_order_code 等)保留兼容。", + "代码变更:app/service/systems/workbench.js 新增 WORKBENCH_PACK_CTX_CACHE_PREFIX/TTL/KEY_PREFIX 常量、generatePackCtxKey、getWorkbenchPackCtxCacheKey;_queryOrder 步骤7 写打包上下文缓存并返回 key(新增 workbench_id 入参);packOrderByToken 增加 key 消费与归属校验;queryOrderByToken 注入 workbench_id。", + "回归测试 test/workbench_pack_waybill_dimension.test.cjs(19 用例,含 key 模式/过期/跨仓/跨台/旧模式兼容)。" + ], + "module": "workbench" + }, + { + "version": "2026.09.21-workbench.packOrder-remove-users-param", + "date": "2026-09-21", + "type": "updated", + "summary": "workbench.packOrder 移除 users 入参:打包人一律由服务端取该工作台绑定成员(wms_workbench_member)回填", + "methods": [ + "workbench.packOrder" + ], + "notes": [ + "打包人数据源收敛为工作台绑定成员(bindMember/removeMember 登入登出链路持久化到 wms_workbench_member),packOrder 不再接收 users 入参,写入 wms_pack_task_packer 与 operator_text 的打包人一律由服务端按 workbench_id 回填;旧设备端传 users 将被忽略。", + "代码变更:app/service/systems/workbench.js#_packOrder 移除 users 解构与上报优先分支,步骤7 直接回填绑定成员;回归测试 test/workbench_pack_waybill_dimension.test.cjs 更新(13 用例,含「旧设备端仍传 users:一律忽略」)。" + ], + "module": "workbench" + }, + { + "version": "2026.09.21-workbench.removeMember-auto-finish-pack", + "date": "2026-09-21", + "type": "updated", + "summary": "workbench.packOrder 打包人缺省自动回填工作台绑定成员;workbench.removeMember 成员全部登出后自动结束未结束的打包任务", + "methods": [ + "workbench.packOrder", + "workbench.removeMember" + ], + "notes": [ + "workbench.packOrder 的 users 入参缺省/为空时,后端自动查询该工作台绑定成员(wms_workbench_member)回填 wms_pack_task_packer 与 operator_text,打包人数据源单一,设备端无需重复上报;上报时优先使用上报值。", + "workbench.removeMember 软删除成员行后统计剩余成员,剩余为 0 时自动结束该工作台所有未结束打包任务(status<2 → 2 并写 end_time),同步订单打包状态(散单按订单、团购按波次,与 _finishPack 语义一致)、写完成操作日志、复位摄像头 OSD、失效 token 缓存;响应新增 auto_finished_pack(finished/task_ids)。", + "代码变更:app/service/systems/workbench.js#_packOrder(步骤7 成员回填)、#removeWorkbenchMember(登出后剩余成员检查)、新增 #_finishAllPackTasksByMemberLogout;回归测试 test/workbench_pack_waybill_dimension.test.cjs(13 用例)。" + ], + "module": "workbench" + }, + { + "version": "2026.09.21-workbench.packOrder-waybill-dimension", + "date": "2026-09-21", + "type": "updated", + "summary": "workbench.packOrder 支持运单维度打包流水(一单多号:主单号/子单号流水互不覆盖),workbench.queryOrder 的 pack_flag 改为运单维度判定", + "methods": [ + "workbench.packOrder", + "workbench.queryOrder", + "workbench.business" + ], + "notes": [ + "背景:一单多号订单(wms_order_express 同 order_id 下 business_key=1 主单号 / >1 子单号)此前按订单维度打包,任一运单打包后订单 pack_status 非 none,导致另一运单被误判为已打包、无法写入打包流水。", + "workbench.packOrder 新增可选入参 waybill_code:散单按「订单+运单号」维度写入 wms_pack_task.waybill_code 并去重(同时清理同订单历史 waybill_code 为空的旧流水),主/子单号流水互不覆盖;未传运单号(旧设备端)保持订单维度;团购为波次维度,不使用运单号。", + "workbench.queryOrder 的 pack_flag 改为运单维度判定:查询该运单号是否已有打包流水(waybill_code 命中,或历史订单级流水 waybill_code 为空兜底),流水查询异常时降级为订单级 pack_status 判定。", + "代码变更:app/service/systems/workbench.js#_packOrder(步骤2.5 运单归属解析、步骤5 去重、packData.waybill_code、步骤7.5 OSD 优先展示打包运单号)、#_queryOrder(步骤6 pack_flag 运单级判定);回归测试 test/workbench_pack_waybill_dimension.test.cjs(8 用例)。" + ], + "module": "workbench" + }, + { + "version": "2026.09.20-workbench-pack-backfill-confirm-print", + "date": "2026-09-20", + "type": "updated", + "summary": "打包链路(workbench.packOrder / workbench.finishPack)回写打包状态时同步补确认打印状态:扫描打包即视为面单已真实存在,confirm_print_status 未写入(none/null)时补 fin,团购按波次、散单按单,拦截订单跳过,并递增统计版本号驱动确认打印未领单长轮询。", + "methods": [ + "workbench.packOrder", + "workbench.finishPack" + ], + "notes": [ + "实现入口:systems/workbench.js _updateOrderPackStatus(覆盖开始打包/完成打包/关闭旧任务全部路径)", + "幂等:仅 confirm_print_status 为 none/null 时补 fin" + ] + }, + { + "version": "2026.09.20-wave-confirmPrintScan-need-right", + "date": "2026-09-20", + "type": "updated", + "summary": "order.wave.confirmPrintScan 改为需要接口权限(isNeedAuth=true),从免权限名单移除;confirmPrintUnclaimedWaveCount 保持免权限。", + "methods": [ + "order.wave.confirmPrintScan" + ], + "notes": [ + "运行时:wave.js _noNeedRight/_noNeedAuth 已移除 confirmPrintScan,checkAuth 走 checkApiPermission", + "权限记录由 permission:sync:system-api 从 system.json isNeedAuth=true 接口同步并授权角色 2" + ] + }, + { + "version": "2026.09.20-pendingOrder-list-confirm-print-claim-fields", + "date": "2026-09-20", + "type": "updated", + "summary": "order.pendingOrder.list 文档补充 confirm_print_status(确认打印)与 claim_status(领料)的 where 筛选说明与响应字段说明(功能已支持,本次仅同步文档)。", + "methods": [ + "order.pendingOrder.list" + ], + "notes": [ + "列表输出 ORDER_LIST_BASE_ATTRIBUTES 已包含 confirm_print_status/claim_status;where 无字段白名单,两列可直接透传筛选" + ] + }, + { + "version": "2026.09.20-wave-batchList-claim-status", + "date": "2026-09-20", + "type": "updated", + "summary": "order.wave.batchList 波次列表新增 claim_assignment_status 领料状态显示(含 claim_time/claim_operator)与 where.claim_assignment_status 筛选(波次表 claim_time 口径)。", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "领料状态以波次表 wms_wave_batch.claim_time 是否为空判定(二态:未领料/已领料),与 confirmPrintUnclaimedWaveCount 口径一致", + "where 新增 claim_assignment_status 筛选字段(仅 eq,unclaimed/claimed,兼容中文)" + ] + }, + { + "version": "2026.09.20-wave-confirm-print-count-fix", + "date": "2026-09-20", + "type": "updated", + "summary": "order.wave.confirmPrintUnclaimedWaveCount 统计口径修正:未领单由订单维度 claim_status 改为波次表维度 wms_wave_batch.claim_time IS NULL,避免历史领单(波次表加 claim_time 字段前)导致少算。", + "methods": [ + "order.wave.confirmPrintUnclaimedWaveCount" + ], + "notes": [ + "根因:B2026081500088/89 等波次订单 claim_status='fin'(历史领单)但 wave_batch.claim_time=null,订单维度口径误判为已领单导致 count 少算", + "新口径:wave_batch(wave_status 0/1、claim_time IS NULL)+ 波次下存在 confirm_print_status='fin' 的非取消订单" + ] + }, + { + "version": "2026.09.20-wave-confirm-print-scan-count", + "date": "2026-09-20", + "type": "added", + "summary": "order.wave 新增两个接口:confirmPrintScan(扫面单批量确认打印并写日志,与领单操作一致)与 confirmPrintUnclaimedWaveCount(快速查询已确认打印但未领单波次数量,支持 60s 长轮询,由确认打印/领单版本号驱动)。", + "methods": [ + "order.wave.confirmPrintScan", + "order.wave.confirmPrintUnclaimedWaveCount" + ], + "notes": [ + "confirmPrintScan 复用 print.confirmWavePrint 实现(同入参同返回)", + "confirmPrintUnclaimedWaveCount 长轮询:1s 间隔轮询 Redis 版本号(wave:confirm-print:unclaimed:version:{warehouseId}),60s 超时;Redis 不可用时降级为轮询 DB count", + "确认打印(print.confirmWavePrint)与领单(pick.waveClaimScan)成功后均递增统计版本号" + ] + }, + { + "version": "2026.09.20-wave-batchList-confirm-print", + "date": "2026-09-20", + "type": "updated", + "summary": "order.wave.batchList 波次列表新增 confirm_print_assignment_status 显示与筛选(确认打印状态:未确认打印/部分确认打印/已确认打印)。", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "where 新增 confirm_print_assignment_status 筛选字段(仅 eq,英文枚举 unconfirmed/partially_confirmed/confirmed)", + "list 每条新增 confirm_print_assignment_status 汇总状态字段" + ] + }, + { + "version": "2026.09.20-confirm-wave-print", + "date": "2026-09-20", + "type": "added", + "summary": "订单表新增 confirm_print_status(确认打印状态)字段,并新增 print.confirmWavePrint 波次确认打印接口:打印完成后扫描波次内任一订单面单,批量确认波次下已打印订单。", + "methods": [ + "print.confirmWavePrint" + ], + "notes": [ + "订单表 wms_order_delivery 及全部分表新增 confirm_print_status ENUM('none','fin'),默认 none;迁移 20260920100000-add-confirm-print-status-to-order-delivery", + "波次下存在未打印订单(print_status != 'fin',拦截订单除外)时阻断确认", + "拦截订单跳过(不确认、不阻断);全部已确认时重复扫描返回 already_confirmed" + ] + }, + { + "version": "2026.09.19-workbench-packOrder-server-side-verification", + "date": "2026-09-19", + "type": "enhance", + "summary": "workbench.packOrder 落库数量改为服务端复查:打包数量/商品总件数/商品种类数不再取设备端上报值,散单取订单分表(orderRow),团购取波次实时统计(totalOrders + 波次商品 SKU 聚合 _fetchWaveItemsSummary),设备端 wave_total_orders/items_count/items_total 仅作交叉校验日志;修复团购波次打包数量落 0/1 的失真问题。", + "methods": [ + "workbench.packOrder" + ], + "notes": [ + "代码:app/service/systems/workbench.js _packOrder 步骤6 改为服务端复查口径:packQuantity 散单固定 1、团购取 totalOrders(>0 否则 1);packItemQuantity/packSkuCount 散单取 orderRow.items_total/items_count(注:分表列名为 items_count 而非 item_count,此前兜底读 item_count 导致散单 sku_count 兜底落 0,已一并修正),团购取 _fetchWaveItemsSummary(15s 短缓存)聚合 rows.length 与 plan_qty 求和,聚合失败降级为扫描订单值", + "交叉校验:设备端上报值与服务端不一致时仅 ctx.logger.info 告警(打包数量/商品总件数/商品种类数三组),落库始终以服务端为准", + "开发库数据回填:temp/fix-dev-pack-task-quantities.cjs 已按新口径重算 wms_pack_task 存量 30 条并更新 19 条(保留 update_time、不删行;散单/团购各自取服务端口径,旧 6 月订单缺失的 6 条跳过)", + "背景:原语义 pack_quantity=wave_total_orders(缺省 1、传 0 落 0),服务端实时波次订单数未回写,导致列表/统计口径失真", + "methods/system.json:workbench.packOrder 参数 wave_total_orders/items_count/items_total 描述同步服务端复查口径;版本 0.3.140 -> 0.3.141(docMeta.version),updatedAt 保持 2026-09-19" + ] + }, + { + "version": "2026.09.19-workbench-getWorkbenchCount-avg-piece-count", + "date": "2026-09-19", + "type": "enhance", + "summary": "workbench.getWorkbenchCount 个人工作台返回调整:新增 group_order_count(团购订单数量,团购任务 pack_quantity 求和,个人/团体工作台均返回);均件数 avg_piece_count 口径改为本人打包任务按 订单数量/人数 折算求和(本人作为打包人参与的任务按任务实际打包人数均分、缺省 1,本工作台单人任务整单计入),不再只统计打包人数≥2 的任务,单人打包 500 单波次可正确得到 500。", + "methods": [ + "workbench.getWorkbenchCount" + ], + "notes": [ + "代码:app/service/systems/workbench.js getWorkbenchCountByToken 个人分支:新增 groupOrderCount(groupTasks 对 pack_quantity 求和);均件数循环改为 participatedTaskIds 按 packerCount(缺省 1)均分、workbenchTaskIds 未记本人时整单计入", + "methods/system.json:getWorkbenchCount response 更新 avg_piece_count/group_order_count 描述;版本 0.3.141 -> 0.3.142(docMeta.version),updatedAt 保持 2026-09-19" + ] + }, + { + "version": "2026.09.19-workbench-getWorkbenchCount", + "date": "2026-09-19", + "type": "enhance", + "summary": "新增 workbench.getWorkbenchCount 当前工作台班次打包统计(免登录/免权限/免鉴权,以工作台 token 鉴权):统计窗口为本地时间当日 08:00 至次日 08:00,早于 08:00 时为昨日 08:00 至今日 08:00;个人工作台(type=personal)统计涉及本人(工作台成员 user_id)的打包数据,返回团购波次数量/散单数量/团散(团购波次数/散单数 2 位小数)/均件数(多人打包任务按 订单数量/人数 折算求和 2 位小数);团体工作台(type=group)返回团购波次数量/团购订单数量(pack_quantity 快照求和)/散单数量。", + "methods": [ + "workbench.getWorkbenchCount" + ], + "notes": [ + "代码:app/service/systems/workbench.js 新增 getWorkbenchCountByToken(resolveWorkbenchContext 统一 token 校验,无 token 401/无效 403)与辅助方法 buildWorkbenchPackCountTimeRange(8 点班次窗口)/ _round2 / _formatPackCountTime", + "个人统计:窗口内本仓库任务走 idx_warehouse_create_time;本人参与任务通过 wms_pack_task_packer(account_id=成员 user_id,分批 IN 500)与 uix_pack_task_account 索引判定;统计范围 = 本工作台任务 ∪ 本人作为打包人参与的任务;均件数只折算本人参与的多人打包(打包人数≥2)任务", + "团体统计:workbench_id+create_time 走新增 idx_workbench_create_time 索引", + "索引:数据库迁移 20260919100000-add-workbench-create-time-index-to-wms-pack-task.js 为 wms_pack_task 新增 (workbench_id, create_time) 复合索引,避免窗口统计长跨度扫描导致慢 SQL;模型 app/model/pack_task.js indexes 同步补充", + "methods/system.json:工作台模块新增 workbench.getWorkbenchCount 条目;版本 0.3.138 -> 0.3.139(docMeta.version),updatedAt 保持 2026-09-19" + ] + }, + { + "version": "2026.09.19-wave-batchList-sync-assignment-status", + "date": "2026-09-19", + "type": "enhance", + "summary": "order.wave.batchList 响应新增 sync_assignment_status(同步状态,取值:未同步/部分同步/已同步/同步异常),并支持 where.sync_assignment_status 筛选(英文枚举 unsynced/partially_synced/synced,仅 eq,error 并入未同步集合)。", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "代码:app/service/systemMethods/order/wave.js BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS 新增 sync 类型(fieldName=sync_assignment_status,enumMap unsynced/partially_synced/synced → none/partial/finished,caseInsensitive=true,statsColumnPrefix=sync,withErrorStatus=true)", + "聚合:wave_order_stats 子查询新增 sync_none_count/sync_fin_count/sync_error_count,按订单 sync_status(padding/fin/error)聚合;none 口径为 sync_status IS NULL 或 NOT IN ('fin','error'),与 review 统计口径一致", + "输出:list[].sync_assignment_status 复用 resolveAssignmentStatus,error 优先判定为同步异常,labels 为未同步/部分同步/已同步/同步异常", + "筛选:buildBatchListWhereClause allowedFields 新增 sync_assignment_status,仅支持 eq;normalizeBatchListSyncAssignmentStatusFilter/buildBatchListSyncAssignmentFilterClause 复用通用 schema 链路", + "methods/system.json:batchList description/where/response 同步 sync_assignment_status 说明;版本 0.3.137 -> 0.3.138(docMeta.version),updatedAt 保持 2026-09-19" + ] + }, + { + "version": "2026.09.19-workbench-getWorkbenchInfo-wave-items-summary", + "date": "2026-09-19", + "type": "enhance", + "summary": "workbench.getWorkbenchInfo 团购任务(pack_mode=2)current_orders items 由空数组改为波次商品 SKU 聚合汇总,彻底解决工作台退出/刷新后团购打包任务无商品信息的问题:新增 _aggregateWaveItems(波次内全部未拦截订单(current+dispatch 分表)商品明细按 SKU 聚合计划数量并合并 stock 详情,聚合行另附 is_wave_summary=true)与 _fetchWaveItemsSummary(按 warehouseId+waveId 维度 15s 短缓存兜底,与 order_count/items_total 同款缓存模式),buildCurrentPackingInfo 团购任务分支调用;散单任务 items 口径不变。", + "methods": [ + "workbench.getWorkbenchInfo" + ], + "notes": [ + "代码:app/service/systems/workbench.js 新增常量 WAVE_ITEMS_SUMMARY_CACHE_KEY_PREFIX/WAVE_ITEMS_SUMMARY_CACHE_TTL_SECONDS(15s);_aggregateWaveItems 聚合键 stock_id 优先、缺省按 item_code+item_name,stock 详情走 stockWarehouse.getStockDetails 通用缓存链路,异常降级空数组;buildCurrentPackingInfo 团购任务(wave_id>0)调用 _fetchWaveItemsSummary 填 items", + "结构:聚合行与散单 items 结构同源(id/order_id 置 0、order_line_no 空串、actual_price null、plan_qty 为波次内该 SKU 合计),另附 is_wave_summary=true 供前端区分单笔明细与波次汇总", + "性能:15s 短缓存保证 TTL 内重复查询零开销;缓存未命中时波次订单 ID 查询走 wave_id 索引、items 按 order_id IN 查询走索引,500 单规模波次一次聚合可接受;packOrder/finishPack 后 token 缓存失效,波次聚合缓存在 TTL 内可能与最新波次状态有最多 15s 滞后(与 order_count/items_total 同口径)", + "methods/system.json:workbench.getWorkbenchInfo description 与 current_orders[].items/items[].id/items[].order_id/items[].plan_qty 描述更新为双口径,response 新增 current_orders[].items[].is_wave_summary 条目;版本 0.3.136 -> 0.3.137(docMeta.version),updatedAt 保持 2026-09-19" + ] + }, + { + "version": "2026.09.19-workbench-order-items-need-recheck", + "date": "2026-09-19", + "type": "updated", + "summary": "workbench.queryOrder 与 workbench.getWorkbenchInfo 响应商品明细 items 新增 need_recheck 字段(Y=需要复核,N=不需要复核(免验),缺省 Y):组装链路 _fetchOrderItemsDetail 从 stock 详情(getStockDetails 通用缓存链路,其 attributes 已含 need_recheck)透出,补齐工作台打包端商品列表缺少免验标识的问题。", + "methods": [ + "workbench.queryOrder", + "workbench.getWorkbenchInfo" + ], + "notes": [ + "代码:app/service/systems/workbench.js _fetchOrderItemsDetail items 组装新增 need_recheck: String(stock.need_recheck || 'Y').trim()(与 order.recheckOrder.scanOrder/scanTask 同口径,getStockDetails 旧缓存无该字段时兜底 Y)", + "workbench.queryOrder 与 workbench.getWorkbenchInfo(current_orders[].items)共用 _fetchOrderItemsDetail,两接口 items 同步生效", + "methods/system.json:workbench.queryOrder description 补充 need_recheck 说明,response 新增 items[].need_recheck 条目;workbench.getWorkbenchInfo description 补充「是否需要复核 need_recheck」,response 新增 current_orders[].items[].need_recheck 条目,并将 current_orders[].items[].image_url 类型由 string 修正为 array(实际返回数组);版本 0.3.135 -> 0.3.136(docMeta.version),updatedAt 保持 2026-09-19" + ] + }, + { + "version": "2026.09.19-workbench-getWorkbenchInfo-order-items", + "date": "2026-09-19", + "type": "enhance", + "summary": "enhance: workbench.getWorkbenchInfo 响应 data.current_orders 补全任务上下文字段,解决工作台退出/刷新后无法恢复任务信息的问题:散单任务(pack_mode=1)新增 items 商品明细数组(wms_order_items 分表按 order_id 查询并合并 stock 详情,含 item_code/item_name/plan_qty/barcodes/image_url/packing_requirements 等,与 workbench.queryOrder 返回结构同源),团购任务(pack_mode=2)波次商品明细量大,items 置空数组、以 current_wave 汇总展示;同时每项新增 wms_pack_task 已有字段 item_quantity/sku_count/waybill_code 与订单分表字段 order_type/store_id/items_count/items_total。", + "methods": [ + "workbench.getWorkbenchInfo" + ], + "notes": [ + "实现:app/service/systems/workbench.js 从 _queryOrder 步骤4 抽取公共方法 _fetchOrderItemsDetail(orderId, warehouseId, sourceTable)(sourceTable=dispatch 查配送明细分表、其余查 current;stock 详情走 stockWarehouse.getStockDetails 自带缓存;异常降级空数组),_queryOrder 改为复用(响应结构不变);buildCurrentPackingInfo 任务遍历时记录订单所在分表 sourceTable 并多取 order_type/store_id/items_count/items_total 字段,散单任务调用 _fetchOrderItemsDetail 补 items,团购任务 items 置空数组", + "口径:items 仅对 pack_mode=1 散单任务查询(团购波次逐单聚合开销大且前端以 current_wave 汇总展示);单笔商品明细查询异常仅该项 items 降级为空数组,不影响主信息与其余字段", + "性能:buildCurrentPackingInfo 仅在 token 缓存(workbench:token:{token},TTL 300s)未命中或打包状态变更失效后执行,未结束任务通常单条,items 按 order_id 走索引查询,无新增高频开销", + "methods/system.json:workbench.getWorkbenchInfo description 补充散单 items/团购空数组与新增字段说明,response 新增 current_orders[].item_quantity/sku_count/waybill_code/order_type/store_id/items_count/items_total 与 current_orders[].items 及 items[] 下 16 个子字段条目(沿用 current_orders[].xxx 嵌套命名惯例);版本 0.3.134 -> 0.3.135(docMeta.version),updatedAt 2026-09-17 -> 2026-09-19" + ] + }, + { + "version": "2026.09.17-inbox-group-template-reply-switch", + "date": "2026-09-17", + "type": "enhance", + "summary": "enhance: inbox.group 系列接口接入模板消息回复开关 templateReplyEnabled/template_reply_enabled(0=关闭(普通文本回复) / 1=开启(模板消息回复)),默认 0,所有群类型均支持且独立于 aiEnabled。update 新增入参(未传不修改),reset 重置为关闭,list 返回字段与 where 筛选支持、quickList 返回字段同步补全。", + "methods": [ + "inbox.group.update", + "inbox.group.reset", + "inbox.group.list", + "inbox.group.quickList" + ], + "notes": [ + "字段落位:wms_inbox_group.template_reply_enabled(TINYINT(1) NOT NULL DEFAULT 0,迁移 database/migrations/20260917100000-add-template-reply-enabled-to-inbox-group.js,model app/model/inbox_group.js 已同步)", + "语义:ai_enabled 控制是否 AI 处理;template_reply_enabled 控制命中处理后是否以模板消息形式回复(0=普通文本回复,1=模板消息回复),两开关相互独立", + "update:data.templateReplyEnabled===1 时写 1,否则写 0,未传不修改;reset:清空配置时 template_reply_enabled 重置为 0;方法层 app/service/systemMethods/inbox.js#groupUpdate 透传", + "list:attributes 与 where specialFieldMap 新增 template_reply_enabled(可筛选),返回行沿用 snake_case 风格(template_reply_enabled)与 ai_enabled 相邻", + "quickList:轻量字段新增 template_reply_enabled,下拉选择可感知模板回信开关", + "消费方:app/service/inbox/processor.js#loadGroupConfig 读取 template_reply_enabled,为 1 的群命中处理后走 inbox.v2.rules 可配置引擎(模板消息回复)", + "文档版本 0.3.133 -> 0.3.134,updatedAt 2026-09-17" + ] + }, + { + "version": "2026.09.16-inbox-push-retry-warehouse-setting", + "date": "2026-09-16", + "type": "updated", + "summary": "仓库设置新增「站内信推送失败自动重发」配置(嵌套结构 subject_config.inbox_push_retry,同「收货未入库提醒」):enabled(flag,默认 0=关闭,需显式开启)、window_minutes(重发时间范围,分钟,1-1440,默认 30)。开启后站内信回信/系统通知推送失败(如桥接离线返回 wx offline / qiwe offline 的 503)由定时任务每 3 分钟自动重发,仅重发失败时间在 window_minutes 内的消息,超出范围不再补发。", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "字段落位:wms_store.subject_config.inbox_push_retry(与 receiving_pending_inbound_notice 同表的嵌套 JSON 配置)", + "默认值口径:未配置(或配置缺失/非法结构)时 enabled=false、window_minutes=30,即**默认关闭不重发**,需在仓库设置中显式开启", + "代码依据:app/model/store.js#normalizeInboxPushRetry(enabled 走 normalizeBooleanFlag;window_minutes 限 1-1440 整数,越界抛「subject_config.inbox_push_retry.window_minutes 必须是 1-1440 的整数(分钟)」);app/service/systems/setting/warehouse.js#WAREHOUSE_SETTING_FIELDS(key=inbox_push_retry,type=object,item_keys 为 enabled/window_minutes)", + "消费方:app/service/inbox/message.js#retryFailedByWarehouse(定时任务 app/schedule/retry_inbox_push.js,每 3 分钟;逐仓读设置 → 仅重发该仓窗口内 push_status=3 的出站消息,单仓单轮上限 config.inbox.pushRetryLimit,默认 20)", + "全局应急开关:config.inbox.pushRetryEnabled(默认 true),置 false 后所有仓库都不再自动重发;config.inbox.pushRetryWindowMs 仅在仓库未配置/配置非法时兜底(默认 30 分钟)", + "getFieldMeta 为通用结构(list + children,不逐字段枚举),本次未改动其文档", + "文档版本 0.3.132 -> 0.3.133,updatedAt 2026-09-16" + ] + }, + { + "version": "2026.09.16-after-sale-type-subtype-crud", + "date": "2026-09-16", + "type": "added", + "summary": "售后模块新增售后类型/子类型自定义配置 8 个接口:afterSale.typeList / typeCreate / typeUpdate / typeDelete / subTypeList / subTypeCreate / subTypeUpdate / subTypeDelete。列表返回系统级(warehouse_id=null、is_system=1)+ 当前仓库自定义(is_system=0)合并;创建仅允许仓库自定义;改/删仅命中 id + 当前仓库 + is_system=0;系统级不允许编辑/删除(未命中统一 404);编码仅允许小写字母/数字/下划线(type≤20、sub_type≤50、name≤50)且创建时校验不与系统级重复、同仓库内唯一(409);update 编码不可变;删除不做级联(类型下存在自定义子类型或子类型已被售后单引用时 409 拒绝)。", + "methods": [ + "afterSale.typeList", + "afterSale.typeCreate", + "afterSale.typeUpdate", + "afterSale.typeDelete", + "afterSale.subTypeList", + "afterSale.subTypeCreate", + "afterSale.subTypeUpdate", + "afterSale.subTypeDelete" + ], + "notes": [ + "接口口径:全部挂 afterSale 模块(POST /system?method=afterSale.xxx);方法层 app/service/systemMethods/afterSale.js(typeList/typeCreate/typeUpdate/typeDelete/subTypeList/subTypeCreate/subTypeUpdate/subTypeDelete)→ 业务层 app/service/systems/afterSale.js(getTypeList/createType/updateType/deleteType/getSubTypeList/createSubType/updateSubType/deleteSubType)", + "权限口径(afterSale.js#systemInit):8 个方法全部免权限(_noNeedRight)、免仓库有效期校验(_noNeedAuth)、需登录(不在 _noNeedLogin);typeList/subTypeList 免日志(_noNeedLog),其余 6 个写系统日志", + "仓库维度隔离:列表按 [warehouse_id IS NULL OR warehouse_id=当前仓库] 合并;创建/改/删均以 ctx.user.store_id 为 warehouseId(无仓库上下文报 400),改/删仅命中 id+warehouse_id+is_system=0", + "系统级保护:is_system=1 记录不允许编辑/删除,未命中统一 404「不存在、无权操作或为系统预设类型」", + "编码规则:type/sub_type 仅允许 /^[a-z0-9_]+$/(小写字母/数字/下划线);type≤20 字符、sub_type≤50、name≤50;创建时校验编码不与系统级重复、同仓库内唯一(409),MySQL 唯一索引 uk_type_warehouse / uk_type_subtype_warehouse 兜底", + "编码不可变:typeUpdate 仅允许 name/is_enabled/sort_order,type 不可改;subTypeUpdate 仅允许 name/is_enabled/sort_order,type 与 sub_type 均不可改", + "删除策略(拒绝,不做级联):typeDelete 在该类型下存在当前仓库自定义子类型时拒绝(409);subTypeDelete 在 wms_after_sale 存在该 type/sub_type 引用(deleted_at 为空)时拒绝(409「已被售后单使用」)", + "错误码口径:400(参数/编码格式/无仓库上下文)、404(不存在/无权/系统预设)、409(编码重复/存在自定义子类型/已被售后单使用)", + "数据模型:wms_after_sale_type / wms_after_sale_sub_type(app/model/after_sale_type.js、after_sale_sub_type.js;迁移 database/migrations/20260916100000-create-wms-after-sale-type-tables.js)", + "AI_METHOD_ROUTING.md 新增 5.8 节(8 个方法的 method→文件→函数→登录→鉴权口径速查表)并刷新第 6 节自动清单(systemMethods/afterSale.js 22→30,systems/afterSale.js 29→46)", + "文档版本 0.3.131 -> 0.3.132,updatedAt 2026-09-16;写入通过 script/update-api-doc.cjs(先 --dry-run)" + ] + }, + { + "version": "2026.09.15-warehouse-pending-receiving-notice-template", + "date": "2026-09-15", + "type": "updated", + "summary": "收货未入库提醒支持自定义通知短语:subject_config.receiving_pending_inbound_notice 新增 notice_template(仓库/客服群短语)与 store_notice_template(货主群短语),支持变量替换({warehouse}/{warehouse_id}/{store}/{store_id}/{count}/{min_hours}/{max_hours}/{date}/{numbers}),消息结构固定为「短语 + 换行 + 明细(一行一条)+ 查看链接」,留空使用默认短语。", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "字段口径:wms_store.subject_config.receiving_pending_inbound_notice.notice_template / store_notice_template,均为 string、最长 500 字符、空值回退默认短语", + "默认短语:仓库/客服群「【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:」;货主群「【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:」", + "可用变量:{warehouse} 仓库名(缺名回退「仓库{id}」)/ {warehouse_id} / {store} 货主名(未绑定为「未绑定货主」)/ {store_id} / {count} 本批单数 / {min_hours} / {max_hours} / {date} 提醒日期 YYYY-MM-DD / {numbers} 本批收货单号(最多 20 个,超出以「等 N 单」结尾);未识别占位符原样保留", + "校验:短语超 500 字符报 400「subject_config.receiving_pending_inbound_notice.notice_template 长度不能超过 500 字符」(store_notice_template 同);空串/null 回退默认短语(模型 app/model/store.js#normalizeReceivingPendingInboundNotice)", + "消息结构:短语 + \\n + 明细行(一行一条,最多 20 行「序号.单号 货主 数量 创建时间 状态」)+ \\n + 快速查看/详情查看链接;不再在结尾追加句号", + "单测:test/app/service/systems/receiving_pending_notice.test.js 新增「短语变量替换 + 明细逐行」「未识别占位符原样保留 + 货主短语缺省回退」两用例(共 11 用例)", + "文档版本 0.3.130 -> 0.3.131,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run)" + ] + }, + { + "version": "2026.09.15-warehouse-pending-receiving-notice", + "date": "2026-09-15", + "type": "updated", + "summary": "仓库设置(wms_store.subject_config)新增「收货未入库提醒」配置 receiving_pending_inbound_notice:enabled(是否通知收货未入库,flag,默认 0 关闭)/ notice_time(提醒时间 HH:mm,默认 08:30)/ min_hours(超时下限小时,默认 24)/ max_hours(超时上限小时,默认 48,须大于 min_hours)。开启后由定时任务(app/schedule/notice_receiving_pending_inbound.js,每 5 分钟检查、按仓库配置的提醒时间执行,每天一次)扫描超时未完成入库的收货单并通知:绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群。setting.warehouse.getSettings 响应与 setting.warehouse.saveSettings 入参补充该字段文档。", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "字段口径:wms_store.subject_config.receiving_pending_inbound_notice = { enabled, notice_time, min_hours, max_hours };默认 { enabled:false, notice_time:\"08:30\", min_hours:24, max_hours:48 }(默认不通知)", + "模型默认值与校验:app/model/store.js(DEFAULT_SUBJECT_CONFIG + normalizeReceivingPendingInboundNotice);字段元信息:app/service/systems/setting/warehouse.js(WAREHOUSE_SETTING_FIELDS,type=object)", + "校验口径:notice_time 必须为 HH:mm(如 08:30),否则 400「subject_config.receiving_pending_inbound_notice.notice_time 格式必须为 HH:mm(如 08:30)」;min_hours/max_hours 必须为大于 0 的整数,且 min_hours 必须小于 max_hours,否则 400", + "定时任务:app/schedule/notice_receiving_pending_inbound.js(interval 5m、单 worker、进程内防重入)→ app/service/systems/receiving_pending_notice.js#execute;命中口径为「创建时间超过 min_hours 且不足 max_hours」且(status=receiving 或 storage_status<>all)、is_deleted=0、status<>cancelled;货主维度聚合成一条消息(每行一个收货单,最多 20 行)", + "通知事件:新增事件码 receiving_pending_inbound(app/model/notification_webhook.js 注册),固定群订阅 app/service/systems/notice/index.js#FIXED_GROUP_SUBSCRIPTIONS:store:receiving + fallbackTargets warehouse:customer_service(无货主或货主未配收货群时通知仓库客服群)", + "幂等:同一仓库+货主同一自然日只推送一次(Redis 当日锁 receiving_pending_notice:lock:{warehouseId}:{YYYYMMDD},TTL 24h;执行异常释放锁,宽限窗口内下一轮重试),消息 ext_id 含 receiving-pending:{warehouseId}:{storeId}:{YYYYMMDD}", + "单测:test/app/service/systems/receiving_pending_notice.test.js(9 用例:开关关闭/未命中提醒时间不执行、超时窗口查询条件、货主群通知、无货主回退、当日只提醒一次、异常释放锁重试、行数截断、非法配置回退默认)", + "文档版本 0.3.129 -> 0.3.130,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run)" + ] + }, + { + "version": "2026.09.15-camera-ptz-camera-id", + "date": "2026-09-15", + "type": "updated", + "summary": "云台(PTZ)四个接口下发给打印服务时请求体统一携带摄像头ID:camera.ptzControl / camera.ptzStop / camera.ptzPresetGoto / camera.ptzPresetSet 的请求体由 { warehouse_id, rtspUrl, … } 改为 { warehouse_id, cameraId, rtspUrl, … }(cameraId 取 wms_camera.id,数值型;warehouse_id 仍为字符串)。接口入参与响应不变。", + "methods": [ + "camera.ptzControl", + "camera.ptzStop", + "camera.ptzPresetGoto", + "camera.ptzPresetSet" + ], + "notes": [ + "变更内容:4 个 PTZ 端点(/camera/ptzControl、/camera/ptzStop、/camera/ptzPresetGoto、/camera/ptzPresetSet)的请求体新增 cameraId 字段,值取摄像头记录主键 wms_camera.id(Number() 归一化后以数值下发),便于打印服务侧按摄像头ID定位/校验设备与日志排查", + "前端入参不变:cameraId 由 WMS 服务端从查询到的摄像头记录自动带入(前端仍只传 id,无需重复传摄像头ID;也无需传 computerId)", + "实现位置:app/lib/ptz_client.js#_send 统一拼接请求体 { warehouse_id: String(warehouseId), cameraId, ...业务字段 },四个入口方法无需各自处理;同时补 camera.id 合法性校验(非正整数报「摄像头ID不合法」)", + "请求体口径(warehouse_id 为字符串、cameraId 为数值):ptzControl { warehouse_id, cameraId, rtspUrl, action, speed };ptzStop { warehouse_id, cameraId, rtspUrl, action };ptzPresetGoto { warehouse_id, cameraId, rtspUrl, presetId };ptzPresetSet { warehouse_id, cameraId, rtspUrl, presetId }", + "响应不变:仍为 { camera_id, rtsp_url, action, speed | preset_id, print_service_response };错误码不变(400/404/500)", + "回归:node run/check-camera-ptz.cjs(68 用例,四个方法的请求体断言均已含 cameraId)全部通过;npx eslint 无告警", + "文档版本 0.3.128 -> 0.3.129,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run)", + "AI_METHOD_ROUTING.md 5.7 段「下发通道」条目已同步补充 cameraId" + ] + }, + { + "version": "2026.09.15-camera-ptz-preset-set", + "date": "2026-09-15", + "type": "added", + "summary": "摄像头模块新增 camera.ptzPresetSet(云台预置点设置):把摄像头当前机位保存为指定预置点,入参 id + presetId(1-256),一次调用即可、无需配对 stop。与既有的 camera.ptzPresetGoto(跳转到预置点)构成「存点 / 跳转」一对,写入载体为打印服务端点 POST {printService.url}/camera/ptzPresetSet,请求体 { warehouse_id, rtspUrl, presetId }。", + "methods": [ + "camera.ptzPresetSet" + ], + "notes": [ + "接口口径:与 camera.ptzControl / camera.ptzStop / camera.ptzPresetGoto 完全一致 —— 独立端点(不带 computerId)、扁平请求体、warehouse_id 为字符串、rtspUrl 服务端按摄像头记录组装", + "入参:id(摄像头ID,必填)、presetId(预置点编号,必填,1-256 整数,字符串数字会被归一化);无 speed / action 参数", + "响应:data 为 { camera_id, rtsp_url, preset_id, print_service_response }", + "错误码:400(摄像头ID不能为空 / 预置点编号不能为空或不是 1-256 的整数 / 摄像头未配置IP地址)、404(摄像头不存在或无权操作)、500(打印服务调用失败,含 HTTP 非 2xx 与回包 status=fail / success=false)", + "权限口径:与 camera.setOsd 一致,camera.js#systemInit 已把 ptzPresetSet 加入 _noNeedRight/_noNeedAuth,_noNeedLog 为 *(不写系统日志)", + "代码依据:app/lib/ptz_client.js#PTZ_PATH.PRESET_SET 与 #presetSet(复用 normalizePresetId/_send/buildRtspUrl)、app/service/systems/camera.js#ptzPresetSet(复用 _findCameraForControl/_assertPtzSuccess)、app/service/systemMethods/camera.js#ptzPresetSet", + "回归:node run/check-camera-ptz.cjs(67 用例,新增 presetSet 的端点/请求体/归一化/边界/摄像头不存在 6 项断言)全部通过;npx eslint 无告警", + "文档版本 0.3.127 -> 0.3.128,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run),新增 method 由脚本追加到「摄像头模块」分组尾部", + "AI_METHOD_ROUTING.md 5.7 段表格已补 camera.ptzPresetSet 行,并刷新第 6 节自动清单(systemMethods/camera.js 与 systems/camera.js 方法数 +1)" + ] + }, + { + "version": "2026.09.15-camera-ptz-wms-endpoint", + "date": "2026-09-15", + "type": "updated", + "summary": "云台(PTZ)三接口入参口径变更:camera.ptzControl / camera.ptzStop / camera.ptzPresetGoto 去除 computerId(打印电脑ID)参数,改为打印服务独立端点下发 —— POST {printService.url}/camera/ptzControl、/camera/ptzStop、/camera/ptzPresetGoto,请求体 { warehouse_id, rtspUrl, action, speed | presetId },与 camera.setOsd 同风格(独立端点、不带电脑ID、warehouse_id 为字符串)。响应同步去除 computer_id 字段。", + "methods": [ + "camera.ptzControl", + "camera.ptzStop", + "camera.ptzPresetGoto" + ], + "notes": [ + "变更原因:与 camera.setOsd 对齐 —— 打印服务按 rtspUrl 定位摄像头,无需电脑房间路由;WMS 服务端也推导不出打印电脑ID(wms_print_computer.id 由打印端 /auth/bind 按「仓库+打印台名称」创建,Web 端登录用户仅有 store_id,wms_workbench 只有 device_ids)", + "入参变化:三个接口均删除 computerId(必填);camera.ptzControl 保留 id/action/speed,camera.ptzStop 保留 id/action,camera.ptzPresetGoto 保留 id/presetId", + "下发报文变化:由 POST {printService.url}/sendToRoom 信封 { warehouse, computerId, method: 'camera.ptz.control'|'camera.ptz.stop'|'camera.ptz.presetGoto', data } 改为三个独立端点 + 扁平请求体 { warehouse_id, rtspUrl, action, speed | presetId }", + "响应变化:data 由 { camera_id, computer_id, rtsp_url, action, speed | preset_id, print_service_response } 改为 { camera_id, rtsp_url, action, speed | preset_id, print_service_response }(删除 computer_id)", + "错误码变化:不再返回「打印电脑ID不能为空/不合法」;其余 400(摄像头ID为空、方向不合法、转速越界、预置点越界、摄像头未配置IP)/404/500 口径不变", + "同一日已存在本接口首次登记的变更记录 2026.09.15-camera-ptz-control(type=added,尚未发布);script/update-api-doc.cjs 的变更记录仅支持头部插入新记录、不支持原位追加,故按兜底方案新增带 -wms-endpoint 后缀的独立记录", + "代码依据:app/lib/ptz_client.js#PTZ_PATH(/camera/ptzControl、/camera/ptzStop、/camera/ptzPresetGoto)+ _send(请求体 warehouse_id 转字符串、字段与 setOSD 对齐)、app/service/systems/camera.js(删除 _normalizeComputerId;_findCameraForControl/_assertPtzSuccess 保留;三方法返回值去掉 computer_id)", + "回归:node run/check-camera-ptz.cjs(60 用例,含「请求体不带 computerId」断言)全部通过;npx eslint 无告警", + "文档版本 0.3.126 -> 0.3.127,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run)", + "AI_METHOD_ROUTING.md 5.7 段已同步(删除 computerId 说明、改为独立端点),并刷新第 6 节自动清单" + ] + }, + { + "version": "2026.09.15-camera-ptz-control", + "date": "2026-09-15", + "type": "added", + "summary": "摄像头模块新增云台控制(PTZ)三个接口:camera.ptzControl(按下,按方向持续转动,action 支持 8 个位置 up/down/left/right/upleft/upright/downleft/downright,speed 1-7 默认 4)、camera.ptzStop(松手,action 必须与按下时一致)、camera.ptzPresetGoto(预置点跳转,presetId 1-256,一次调用无需 stop)。服务端按摄像头记录组装 rtspUrl,通过打印服务统一指令信封 POST {printService.url}/sendToRoom 下发 { warehouse, computerId, method, data },computerId 由前端传入。", + "methods": [ + "camera.ptzControl", + "camera.ptzStop", + "camera.ptzPresetGoto" + ], + "notes": [ + "接口口径:method 与打印服务一一对应 —— camera.ptzControl -> camera.ptz.control(data: { rtspUrl, action, speed })、camera.ptzStop -> camera.ptz.stop(data: { rtspUrl, action })、camera.ptzPresetGoto -> camera.ptz.presetGoto(data: { rtspUrl, presetId })", + "action 枚举(8 个位置,与打印服务约定,写入 params[].action.list,顺序固定):up-上、down-下、left-左、right-右、upleft-左上、upright-右上、downleft-左下、downright-右下;大小写不敏感,服务端转小写后校验,非法值报 400", + "参数校验:id 必填;computerId 必填且为正整数;action 必填且属于 8 个方向;speed 可选取 1-7 整数(默认 4);presetId 必填取 1-256 整数(转速/预置点仅约束下发的打印服务指令口径,摄像头端实际生效范围以设备为准)", + "rtspUrl 由服务端组装(rtsp://{username}:{password}@{ip}:554/stream{channel_id}),与 camera.setOsd 同口径,前端无需传;摄像头无 ip 时报 400「摄像头未配置IP地址,无法组装RTSP地址」", + "权限口径:与 camera.setOsd 一致,camera.js#systemInit 已把 ptzControl/ptzStop/ptzPresetGoto 加入 _noNeedRight/_noNeedAuth,且 _noNeedLog 为 *(PTZ 高频调用不写系统日志)", + "响应口径:成功时 data 为 { camera_id, computer_id, rtsp_url, action, speed | preset_id, print_service_response }(print_service_response 为打印服务原始回信,便于前端/排查核对);打印服务 HTTP 非 2xx、或回包 status=fail / success=false 时按 500 抛出并带打印服务 message", + "代码依据:app/lib/ptz_client.js(PTZ_METHOD/PTZ_ACTION_LIST/PTZ_ACTIONS + control/stop/presetGoto + buildRtspUrl 与 osd_client 同口径)、app/service/systems/camera.js(_findCameraForControl/_normalizeComputerId/_assertPtzSuccess + ptzControl/ptzStop/ptzPresetGoto)、app/service/systemMethods/camera.js(三个入口方法 + systemInit 免权限声明)", + "文档版本 0.3.125 -> 0.3.126,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run),新增 method 由脚本追加到「摄像头模块」分组尾部", + "AI_METHOD_ROUTING.md 已同步刷新第 6 节自动清单(app/service/systemMethods/camera.js 由 6 个方法变为 9 个)" + ] + }, + { + "version": "2026.09.15-returnUnpack.transferByWaybills-ids", + "date": "2026-09-15", + "type": "updated", + "summary": "returnUnpack.transferByWaybills 入参口径变更:waybill_codes(运单号字符串/数组)改为 ids(运单表主键 wms_order_express.id,单个数值或数组,Number() 归一化 + 过滤非正整数 + 去重,单次上限 200)。系统层改为按 id IN (ids) + warehouse_id 一次批量反查运单,未命中即不存在或非本仓库,记失败「运单不存在」。失败项新增 waybill_id,waybill_code 仅运单命中时有值(否则为 null)。错误码新增 400「运单号为空,无法转入退件登记」与 500「反查运单失败,请稍后重试」。业务规则不变(统一置 is_back='Y'、子单跳过、明细按订单原本明细 1:1 复制、幂等复用非 cancelled 拆包单)。", + "methods": [ + "returnUnpack.transferByWaybills" + ], + "notes": [ + "本次为入参变更;同日已存在 change 记录 2026.09.15-returnUnpack.transferByWaybills(type=added,接口首次登记,尚未发布/未提交)。script/update-api-doc.cjs 的变更记录结构仅支持新记录插入数组头部、不支持对既有记录原位追加,故本次按兜底方案新增 version 带 -ids 后缀的独立记录(summary 已说明是入参变更)", + "代码依据:app/service/systems/return_unpack.js#transferByWaybills({ ids })(Number() 归一化 → 过滤非正整数 → 去重 → 上限 200 → id IN (ids)+warehouse_id 批量反查;failed[] 元素为 { waybill_id, waybill_code: 命中时有值否则 null, reason });app/service/systemMethods/returnUnpack.js#transferByWaybills(data) 取 data.ids 后透传,方法层包装不变", + "错误码变化:新增 400「运单号为空,无法转入退件登记」、500「反查运单失败,请稍后重试」;400「waybill_codes 不能为空」改为「ids 不能为空」;其余 400/404/401/403/500 口径不变", + "响应结构变化:failed[] 元素由 { waybill_code, reason } 调整为 { waybill_id, waybill_code, reason };success[] 元素由 { waybill_code, unpack_id, unpack_no, reused, detail_count, total_quantity } 调整为含 waybill_id 的 7 字段", + "回归:代码已先行修改并跑通 76/76 回归,本次仅同步文档;AI_METHOD_ROUTING.md 方法名与数量不变,无需同步", + "文档版本 0.3.124 -> 0.3.125,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.15-order-list-default-where-fix", + "date": "2026-09-15", + "type": "updated", + "summary": "修正 order.pendingOrder.list / order.outboundOrder.list 的默认筛选说明,使其与 app/service/systemMethods/order/base.js#MODULE_CONFIGS 实现一致(前者 step in [1,2,3];后者 outbound_status in [fin,padding] 且 step in [4,9])。", + "methods": [ + "order.pendingOrder.list", + "order.outboundOrder.list" + ], + "notes": [ + "实现口径:base.js MODULE_CONFIGS.pendingOrder.defaultWhere = { outbound_status: { operator: \"ne\", value: \"padding\" }, step: { operator: \"in\", value: [1,2,3] } };outboundOrder.defaultWhere = { outbound_status: { operator: \"in\", value: [\"fin\",\"padding\"] }, step: { operator: \"in\", value: [4,9] } };两者 list 均直接 this.listByModule(module, data),无额外覆盖", + "原描述偏差:pendingOrder 写 step in [1,2](漏 3);outboundOrder 写 outbound_status in [none,padding] 且 step in [1,2](正确为 outbound_status in [fin,padding] 且 step in [4,9])", + "旁证:run/check-order-list-create-channel.cjs 的期望值按 MODULE_CONFIGS 语义独立构造(pendingOrder step in [1,2,3];outboundOrder outbound_status in [fin,padding] + step in [4,9]),45/45 通过", + "文档版本 0.3.123 -> 0.3.124,updatedAt 2026-09-15;通过 script/update-api-doc.cjs 写入(先 --dry-run),按分组拆 spec(首个带 change,其余 --doc-only)" + ] + }, + { + "version": "2026.09.15-order-list-create-channel-filter", + "date": "2026-09-15", + "type": "updated", + "summary": "订单工作台各订单列表接口(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)的 where 参数补充 create_channel 订单来源渠道查询条件说明与枚举(MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单),并给出裸值/裸数组/标准 operator 结构写法。", + "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": [ + "口径来源:9 个列表均走 app/service/systemMethods/order/base.js#listByModule -> buildWhere -> lib/query_condition_parser.js(where 无字段白名单,字段直接透传为订单分表条件),故 create_channel 可作精确/多选/排除筛选", + "枚举来源:app/service/systemMethods/order/base.js CREATE_CHANNEL_LABELS(MANUAL 手工单 / API 接口 / QM 奇门 / STOCKOUT 出库转单)、app/service/systems/order_async.js CREATE_CHANNEL_* 常量;列定义见 database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js(create_channel STRING(20),默认 MANUAL)", + "响应口径:base.js#normalizeOrderListItem 会把 create_channel 通过 formatCreateChannelLabel 转成中文标签,故文档中明确「查询传英文枚举、响应回中文标签」", + "已核实列存在性(本地库 information_schema):wms_order_delivery_{100000,1000028} 及 _dispatch/_history/_outsourced 分表均含 create_channel 列;本地数据取值分布仅 MANUAL(73715)/QM(1082)/API(18)/STOCKOUT(2)", + "不支持的订单类列表(未纳入本次说明):order.recheckOrder.recheckOrderList / queryRecheckOrderSingleList(手写 SQL,仅 keyword/wave_no/recheck_status/pick_status/wave_index/stock_query)、order.packing.list(仅 status/pack_mode/waybill_code/wave_no 等)、order.wave.batchList(wave.js#buildBatchListWhereClause 字段白名单不含 create_channel)", + "文档版本 0.3.122 -> 0.3.123,updatedAt 2026-09-15;写入走 script/update-api-doc.cjs(先 --dry-run),首个 spec 带 change,其余 --doc-only" + ] + }, + { + "version": "2026.09.15-returnUnpack.transferByWaybills", + "date": "2026-09-15", + "type": "added", + "summary": "新增退回拆包接口 returnUnpack.transferByWaybills(运单批量转入退件登记):waybill_codes 单个字符串或数组批量转入(trim+去重+过滤空值,上限 200),逐单处理、单条失败不阻断;命中运单统一置 wms_order_express.is_back='Y';子单(business_key>1)跳过;幂等复用同仓库同运单号有效拆包单(reused=true,复用单明细为空按订单明细补写);明细按运单关联订单原明细 1:1 复制(items JSON 优先回退明细分表,复用 afterSale._resolveOrderDetail);命中退回收到登记回填 return_received_id;新增权限 568(API:运单批量转入退件登记,授权角色 27/26)。", + "methods": [ + "returnUnpack.transferByWaybills" + ], + "notes": [ + "方法层:app/service/systemMethods/returnUnpack.js 新增 transferByWaybills(data)(位于 create 之后),统一 this.success('ok', data) 包装,未加入 _noNeedRight/_noNeedLogin/_noNeedLog/_noNeedAuth 免检清单(isNeedAuth=true、isNeedLogin=true)", + "系统层:app/service/systems/return_unpack.js 新增 transferByWaybills / _insertMainWithRetry / _transferOneWaybill / _backfillDetailsFromOrder / _countDetails / _resolveReturnReceivedId / _buildTransferDetailRows(共 7 个方法)", + "权限:database/migrations/20260915100000-add-return-unpack-transfer-waybills-permission.js 固定 ID 568 path=returnUnpack.transferByWaybills meta_title=API:运单批量转入退件登记,角色授权 27(仓库组-员工)→ 26(仓库组-主管),INSERT IGNORE + 权限数组追加去重排序幂等", + "响应错误码:400 参数/上下文/子单跳过/无明细可复制、404 运单不存在、401/403 与其它接口一致、500 服务器内部错误;单运单失败进入 failed[] 不抛错", + "AI_METHOD_ROUTING.md 同步:systemMethods/returnUnpack.js 20→21(新增 transferByWaybills)、systems/return_unpack.js 43→50(新增 7 个方法);docs/*.md 无退回拆包接口清单,无需同步", + "文档版本 0.3.121 -> 0.3.122,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ], + "module": "returnUnpack" + }, + { + "version": "2026.09.15-storage-inventory-update-expiry", + "date": "2026-09-15", + "type": "added", + "summary": "新增 storage.inventory.updateExpiry 接口:传入 storage_id 与 production_date / expiry_date,维护当前库存批次的生产日期与到期日期;两个日期至少传一个,未传字段保持原值,传 null/空串清空,合并后生产日期不得晚于到期日期。", + "methods": [ + "storage.inventory.updateExpiry" + ], + "notes": [ + "app/service/systems/storage/inventory.js 新增 updateExpiry(data):校验 storage_id 为正整数、两个日期格式合法且至少传一个、当前仓库上下文(ctx.user.store_id);单事务 + 行锁(SELECT ... FOR UPDATE)按 id + warehouse_id + is_enabled=1 + delete_at IS NULL 定位库存记录,跨仓库按 404 处理", + "app/service/systems/storage/inventory.js 新增模块级 helper parseStorageDateInput:undefined=未传(provided=false)、null/空串=清空、YYYY-MM-DD / YYYY/MM/DD / YYYY-MM-DD HH:mm:ss / ISO / Date 统一规范化为 YYYY-MM-DD(并校验真实存在日期,如 2026-02-30 判非法)、其它非法", + "业务校验:合并后(未传字段取库内现值)生产日期不能晚于到期日期,违反返回 400「生产日期(x)不能晚于到期日期(y)」;两值均与库内一致时返回 changed=false,不写库、不记日志", + "成功路径写业务操作日志(operationLog.createOperationLog,失败仅告警不影响主流程):business_type=storage、operation_code=STORAGE_UPDATE_EXPIRY、before_changes 含维护前两个日期与 storage/space/stock/batch 快照、message 为「生产日期 A → B;到期日期 C → D」摘要", + "app/dict/businessDict.js OPERATION_CODE 新增 STORAGE_UPDATE_EXPIRY: '维护库存效期'", + "app/service/systemMethods/storage/inventory.js 新增 updateExpiry 包装方法(this.success('ok', result) 透传 code/message/data),未加入 _noNeedRight/_noNeedAuth 豁免列表:该接口为写操作,需要 API 权限与仓库有效期校验", + "权限联动:wms_permission 需新增 path=storage.inventory.updateExpiry 的接口权限并授予相关角色(校验逻辑 app/service/main.js checkApiPermission,路径比较不区分大小写);permissions='*' 的角色无需授权", + "响应错误码:400 参数/业务校验失败、404 库存记录不存在或无权访问、409 库存记录被锁定请稍后重试(Lock wait timeout)", + "验证:ESLint(npx eslint app/service/systems/storage/inventory.js app/service/systemMethods/storage/inventory.js app/dict/businessDict.js)0 error;parseStorageDateInput 通过临时脚本 temp/verify-update-expiry-date-parse.cjs 逐用例验证(未传/空/清空/多格式/非法日期/Date 对象);未执行任何部署/回退脚本,未改动数据库与 Redis 数据" + ], + "module": "storage.inventory" + }, + { + "version": "2026.09.15-workbench-pack-osd-reset", + "date": "2026-09-15", + "type": "updated", + "summary": "打包任务结束统一复位工作台摄像头 OSD 为「无任务」:覆盖三条结束路径 —— workbench.finishPack 手动结束、workbench.packOrder 关闭上一个未结束任务(先复位再串行下发新任务 OSD,避免复位覆盖新文字)、packTaskAutoFinish 定时任务自动结束;统一调用 workbench._resetPackOsd 回写 Redis osd_{workbenchId}=无任务 并逐台摄像头下发「无任务」,异常仅告警不阻塞打包主流程。", + "methods": [ + "workbench.packOrder", + "workbench.finishPack" + ], + "notes": [ + "代码:app/service/systems/workbench.js 新增 OSD_IDLE_TEXT/OSD_CACHE_KEY_PREFIX/OSD_CACHE_TTL_SECONDS 常量与 _resetPackOsd;_finishPack、_packOrder 步骤4/7.5 接入", + "代码:app/service/systems/pack_task_auto_finish.js 扫描补 workbench_id,自动结束后调用 _resetPackOsd;app/schedule/auto_finish_pack_task.js 注释同步", + "回归测试:test/workbench_reset_pack_osd.test.cjs(8 用例,mock ctx)全部通过" + ] + }, + { + "version": "2026.09.13-stockout-waybill-codes-single-deprecate", + "date": "2026-09-13", + "type": "updated", + "module": "storage.stockout", + "summary": "出库单运单号口径收敛为复数:storage.stockout.confirm 的确认校验与出站回传改为以 waybill_codes 为准(对齐奇门 packages.package[] 多运单模型,不使用 deliveryOrder.expressCode),错误文案由「未填写运单号(waybill_code)」改为 (waybill_codes);storage.stockout.updateExpress 以 waybill_codes 为主,单数 waybill_code 降级为镜像字段(传复数时自动镜像首个数,传空数组/null 时同步置 NULL),仅传单数的旧调用方行为不变。存量单在复数缺失时仍回退单数,避免卡单。", + "methods": [ + "storage.stockout.confirm", + "storage.stockout.updateExpress" + ], + "notes": [ + "代码依据:app/service/systemMethods/storage/stockout.js#confirm(校验改为 waybill_codes 优先、单数回退;报文运单号复用校验结果)、#updateExpress(waybill_codes 写入时镜像 waybill_code = 首个);app/service/systems/order_async.js#syncStockoutOrders 写回注释同步为「复数为准、单数为镜像」", + "协议依据:taobao.qimen.stockout.confirm 中运单号在 packages.package[].expressCode(多包裹/多运单,每个包裹一个),deliveryOrder.expressCode 为单据级单运单号(多运单场景不使用)", + "回归测试:stockout.confirm.outbound.test.js 扩到 8 条(新增「一单多运单只填复数即可确认且回传 packages.package[] 两个包裹」「存量单仅有单数仍可确认」);新增 stockout.updateExpress.test.js 7 条(复数镜像、空数组/null 清空、复数优先覆盖单数、仅单数行为不变、非数组 400、无字段 400)", + "对外契约影响:确认失败文案变化(waybill_code → waybill_codes);updateExpress 响应仍同时返回两列(waybill_codes 为准,waybill_code 为镜像);仅传 waybill_codes 即可完成填写与确认,调用方可不再传单数", + "存量兼容:复数缺失时 confirm 回退单数、updateExpress 仅传单数行为不变,因此旧调用方无需强制同步升级", + "文档版本 0.3.118 -> 0.3.119,updatedAt 2026-09-13;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.13-storage-stockout-confirm-source-routing", + "date": "2026-09-13", + "type": "updated", + "module": "storage.stockout", + "summary": "修复 storage.stockout.confirm 出站回传未按出库单来源分流的问题:confirm 改为复用 systems/order_async.js#notifyStockoutExternalInternal(QM→奇门 taobao.qimen.stockout.confirm,API→OpenAPI 回调 method=stockout.confirm,WMS 等内部来源无需通知直接成功),与出库单转订单回传同一套分流口径;API 来源 appKey 按货主合约反查。修复后 API 来源出库单不再被错误发往奇门(此前被奇门以「-1 无法匹配货主」拒绝,且跳过出站同样走失败分支,导致该来源出库单无法确认);同时确认文档同步分流语义与新增失败文案。", + "methods": [ + "storage.stockout.confirm" + ], + "notes": [ + "代码依据:app/service/systemMethods/storage/stockout.js#confirm(第二步由硬编码 qimenClient.send 改为调用 ctx.service.systems.orderAsync.buildStockoutConfirmRequest / resolveOpenApiAppByStore / notifyStockoutExternal);app/service/systems/order_async.js 新增 3 个实例方法(buildStockoutConfirmRequest / notifyStockoutExternal / resolveOpenApiAppByStore)复用既有模块级实现,未改动原函数与其既有调用方", + "回归测试:test/app/service/systemMethods/storage/stockout.confirm.outbound.test.js 新增 6 条用例(API 走回调不发奇门、API 无可用 ApiApp 时不回落奇门、QM 仍走奇门且不发回调、WMS 内部来源直接完成、QM 奇门失败保持 CREATED、未填 waybill_code 前置拒绝)", + "对照验证:order_async.openapi.callback.test.js(5 failing)与 order_async.syncOrderIds.test.js(13 failing)为改动前既有失败(测试未跟上 2026-09-13 API 回传「不再静默跳过」的口径变更),已用「新增方法临时抛错后失败数不变」判定与本次改动无路径交集", + "对外契约影响:入参、成功响应结构不变;新增可能出现的失败文案「出库单回传服务不可用」与 API 来源的「缺少 appKey,无法回传出库单」;WMS 等内部来源出库单由「出站同步失败: 未发起出站通知」变为可正常确认完成", + "文档版本 0.3.117 -> 0.3.118,updatedAt 2026-09-13;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.13-storage-stockout-waybill-field-align", + "date": "2026-09-13", + "type": "updated", + "module": "storage.stockout", + "summary": "修正 storage.stockout.updateExpress / storage.stockout.confirm 的运单号字段口径(仅文档,未改代码):updateExpress 的入参由「express_code=运单号、express_codes=运单号列表」纠正为真实实现口径——express_code=快递公司编码(自动解析 express_name)、waybill_code=运单号、waybill_codes=运单号列表,并补齐 express_name/waybill_code/waybill_codes 响应字段与「没有需要更新的字段」错误项;confirm 的运单号校验字段由 express_code 纠正为 waybill_code,并如实描述响应 expressCode/expressCodes 的来源与历史遗留命名。", + "methods": [ + "storage.stockout.confirm", + "storage.stockout.updateExpress" + ], + "notes": [ + "代码依据:app/service/systemMethods/storage/stockout.js#updateExpress(L826 起,仅识别 express_code/waybill_code/waybill_codes,无 express_codes 分支)、#confirm(L577 校验 order.waybill_code)、app/model/order_stockout.js(express_codes 标注 @deprecated)", + "背景:2026-08-07 首次上线时 express_code/express_codes 即运单号口径;随后迁移 20260807140000 引入 waybill_code/waybill_codes 并改义 express_code 为快递公司编码,但 methods/system.json 与 confirm 错误文案未同步,导致调用方按旧文档传 express_codes 时静默失败。", + "对外契约影响:仅描述与错误文案纠偏,接口行为、参数名、HTTP 状态码均未变更;调用方需把运单号列表参数由 express_codes 改为 waybill_codes(confirm 前还需填 waybill_code)。", + "文档版本 0.3.116 -> 0.3.117,updatedAt 2026-09-13;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)", + "后续代码侧待办(未在本次实施):updateExpress 增加 express_codes 兼容映射或对未识别参数报错、补 warehouse_id 归属校验;confirm 成功响应 expressCode/expressCodes 收敛为 waybill_code/waybill_codes。" + ] + }, + { + "version": "2026.09.13-pendingOrder-syncOrderIds-api-confirm-before-deduct", + "date": "2026-09-13", + "type": "updated", + "summary": "order.pendingOrder.syncOrderIds 描述同步 API 渠道同步顺序变更(代码已先行落地):API 渠道订单改为逐单「先回传 deliveryorder.confirm、回调成功才扣减库存并置 sync_status='fin'」,回调失败/异常置 sync_status='error' + 待处理异常、不扣减库存、可重新派发;单订单失败统一「写入错误状态 + 标记待处理异常」。QM/MANUAL 口径不变。文档版本 0.3.115 → 0.3.116。", + "methods": [ + "order.pendingOrder.syncOrderIds" + ], + "notes": [ + "代码依据:app/service/systems/order_async.js#finalizeLocalChannelOrdersInternal → processApiOrderInternal(回调成功才 processLocalChannelOrderInternal 扣减并置 fin)、markApiSyncFailedInternal(error + markPendingException)", + "params / response / errors 未变,仅 description 同步语义", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-storage-entry-cancel-entryOrderCode-doc", + "date": "2026-09-12", + "type": "updated", + "module": "storage.entry", + "summary": "storage.entry.cancel 文档小幅补充(对外契约不变):description 末尾注明另支持按 entryOrderCode(兼容别名 entry_order_code)按单号定位、供奇门/openapi 外部渠道复用;params 新增可选 entryOrderCode(内部复用口径,优先于 id/ids)。id/ids 入参、响应结构 { code, message, data } 与全部失败文案(入库单不存在或无权访问 / 入库单已作废 / 已完成入库单不允许作废 / 入库单已完成回传,不可取消 / 作废成功)逐一不变。", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "app/service/systems/storage/entry.js cancel:新增 data.entryOrderCode(或 data.entry_order_code)按单号定位(定位条件带 is_enabled/deleted_at/warehouse_id,有 storeId 时追加货主条件),优先于 id/ids;options 为外部渠道扩展(warehouseId/storeId/operatorLabel/skipExternalSync/idempotent/notFoundMessage),系统方法入口不传时行为与文案与历史版本完全一致", + "奇门 order.cancel 与 openapi order.cancel 的 RK 组经此共用作废流程(skipExternalSync=true、idempotent=true、notFoundMessage=未找到对应的入库单)", + "methods/system.json:storage.entry.cancel 的 description 末尾补一句按 entryOrderCode 定位说明,params 新增可选 entryOrderCode;id/ids、response、errors 文案未动", + "文档版本 0.3.114 -> 0.3.115(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-storage-stockout-cancel-shared-impl", + "date": "2026-09-12", + "type": "updated", + "module": "storage.stockout", + "summary": "storage.stockout.cancel 内部实现改为委托共享 app/service/systems/stockout_order.js#cancel(奇门 / openapi 同口径:单事务 + 行锁);对外契约完全不变(缺少出库单ID / 缺少仓库上下文 / 出库单不存在 / 出库单当前状态(xxx)不允许取消 / 成功返回取消成功 + data 含 id、stockout_order_code、order_status);由「先查单再开事务」改为「单事务 + 行锁」,并发取消/确认/转单更安全。", + "methods": [ + "storage.stockout.cancel" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js cancel 改为薄适配层:校验 id(缺少出库单ID)与仓库上下文(缺少仓库上下文),委托 systems.stockoutOrder.cancel({ id }, { storeId: null, warehouseId, operatorLabel }),将共享层「未找到对应的出库单」映射为「出库单不存在」,成功映射为「取消成功」并透传 id / stockout_order_code / order_status", + "app/service/systems/stockout_order.js cancel:定位优先 stockoutOrderCode 其次 id;单事务 + 行锁(防止并发取消/确认/转单),仅 CREATED/PENDING 可取消(canCancel),已 CANCELLED 幂等返回成功,COMPLETED/TRANSFERRED 返回「出库单当前状态(xxx)不允许取消」", + "对外契约与实现变更前一致,调用方无需改动", + "methods/system.json:storage.stockout.cancel 的 description 补充共享实现说明;errors 由单条 description 文本改为逐条 code/message(与仓库统一格式),文案不变;docMeta.version 0.3.113 -> 0.3.114,updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-storage.inventory.listBySpaceId", + "date": "2026-09-12", + "type": "added", + "summary": "新增 storage.inventory.listBySpaceId 接口:传入 space_id,先判断该库位是否为当前仓库的库位(不存在返回 404、存在但不属于当前仓库返回 400),是则返回该库位下有量库存(quantity > 0)的商品列表。列表按商品(stock_id)汇总为一条(汇总 quantity/locked_quantity/intercept_locked_quantity/available_quantity,含 batch_count 与最早/最晚入库时间);商品信息统一走 stock_warehouse 通用链路(getStockDetails)返回 stock_warehouse 通用属性。", + "methods": [ + "storage.inventory.listBySpaceId" + ], + "notes": [ + "app/service/systemMethods/storage/inventory.js 新增 listBySpaceId 包装方法(透传 data.space_id,返回结构沿用 this.success('ok', result)),并加入 _noNeedRight/_noNeedLog/_noNeedAuth 豁免列表(与 listByStockId 一致)", + "app/service/systems/storage/inventory.js 新增 getStorageListBySpaceId:校验 space_id 为正整数与当前仓库上下文(ctx.user.store_id);先查 wms_location_space(id + warehouse_id + deleted_at=null)判断库位归属,未命中再查全局记录以区分「库位不存在」(404)与「库位不属于当前仓库」(400)", + "库存查询条件:wms_storage where warehouse_id + space_id + quantity > 0 + is_enabled=1 + delete_at=null,按 id 倒序取出库位明细行(仅取汇总所需列,不返回批次/效期明细)", + "商品通用属性:收集明细行 stock_id 去重后调用 ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId })(带缓存通用链路),stock 对象即 stock_warehouse 通用属性(id/item_code/item_name/sku_property/quantity/locked_quantity/is_batch_mgmt/is_shelf_life_mgmt/is_images/need_recheck/store_id/packing_requirements/stock_unit/barcodes/image_url);该链路异常时降级为 stock=null 且不中断主流程", + "app/service/systems/storage/inventory.js 新增 _aggregateStorageRowsByStock:按 stock_id 在内存汇总数量与批次数、取最早/最晚入库时间(app.formatDate 格式化),并平铺 space_code/space_name(custom_name 优先,否则 space_code)与 store_name(wms_store_warehouse.store_remask,按 warehouse_id + store_id 收敛,查询异常降级为 null)", + "响应结构:data.space(id/warehouse_id/space_code/custom_name/space_status)+ data.list(按商品汇总行,无有量库存时为空数组)", + "错误码:400「space_id 必填且必须为正整数」、400「无法获取当前仓库信息」、400「库位 {space_id} 不属于当前仓库」、404「库位不存在: space_id={space_id}」", + "methods/system.json 新增 storage.inventory.listBySpaceId 条目(追加于 storage.inventory.listByStockId 之后;isNeedAuth=false、isNeedLogin=true、isNeedRight=false),version 0.3.112 -> 0.3.113,updatedAt 2026-09-12", + "AI_METHOD_ROUTING.md 第 6 节按文件内维护说明刷新(node .\\script\\tmp-gen-service-method-inventory.cjs → node .\\script\\tmp-update-ai-method-routing.cjs):systemMethods/storage/inventory.js 14 -> 15、systems/storage/inventory.js 13 -> 15(新增 getStorageListBySpaceId、_aggregateStorageRowsByStock)", + "验证:ESLint(npx eslint app/service/systems/storage/inventory.js app/service/systemMethods/storage/inventory.js)0 error;未执行任何部署/回退脚本,未改动数据库与 Redis 数据" + ], + "module": "storage.inventory" + }, + { + "version": "2026.09.11-shops-edit-shop-name-doc-sync", + "date": "2026-09-11", + "type": "updated", + "summary": "同步 shops.edit 文档:补入 shop_name 入参(修改店铺名称),修正「仅允许修改 platform_code 或 custom_name」的过时描述与错误文案。", + "methods": [ + "shops.edit" + ], + "notes": [ + "实现依据:app/service/systemMethods/shops.js 的 edit 已透传 shop_name/shopName(与 custom_name/platform_code 同样兼容 camelCase),app/service/systems/shops.js 的 edit 已支持 updates.shop_name。", + "字段语义区分:shop_name 为平台真实店铺名(shops.add 时写入 PENDING_* 占位名,授权回调后同步真实名称);custom_name 为自定义名称,仅作标签展示。", + "校验行为:三者至少传一个,否则抛 400「仅允许修改 platform_code、custom_name 或 shop_name」;shop_name 走 normalizeText(required, maxLength=100),为空抛 400「shop_name 不能为空」、超长抛 400「shop_name 长度不能超过 100」。", + "唯一性:改名与改平台合并后按「当前仓库 + next platform_code + next shop_name」调用 ensureShopNameUnique(排除自身,软删除店铺名以 DELETED_SHOP_NAME_PREFIX 前缀排除),冲突抛 409「同仓同平台下 shop_name 已存在」。", + "文档更新:methods/system.json 的 shops.edit description 改为 platform_code/custom_name/shop_name 三选一,params 新增 shop_name(兼容 shopName),errors 补入 shop_name 相关 400 文案、id 与仓库校验 400、店铺不存在 404,并修正 400「仅允许修改 platform_code 或 custom_name」为「仅允许修改 platform_code、custom_name 或 shop_name」;version 0.3.111 -> 0.3.112,updatedAt 2026-09-11。", + "仅文档同步,未修改任何业务代码;未执行部署/回退脚本,未改动生产数据。" + ], + "module": "shops" + }, + { + "version": "2026.09.11-wave-batch-list-where-operator", + "date": "2026-09-11", + "type": "changed", + "summary": "order.wave.batchList(波次管理列表)的 where 新增操作符传参支持:白名单字段统一支持裸值与 {operator,value,type} 标准结构(eq/ne/gt/lt/ge/le/in/notin/between/notbetween/like/contains/notlike/startswith/endswith/isnull/isnotnull,按字段分组限制),value 支持数组(like/contains 多值 OR、notlike 多值 AND、in/notin 要求非空数组、eq 传数组等价 in);未显式传 operator 时保持历史默认语义(wave_no/creator/logistics_name/item_part/item_snapshot_key/item_detail_machine 默认模糊,其余默认等值),裸数组按 in。新增 total_orders / processed_orders 两个数值字段,store_id 新增 ne/notin 排除语义。修复前端通用筛选器下发 {operator,value:[...]} 时 wave_id 等整数字段报「参数不合法」、wave_no 等文本字段被 String([...]) 拼成 'A,B' 导致恒空的问题。", + "methods": [ + "order.wave.batchList" + ], + "module": "order.wave", + "notes": [ + "app/service/systemMethods/order/wave.js:buildBatchListWhereClause 由「逐字段手写 if 取 .value」改为通用条件构建,新增 isEmptyBatchListWhereValue(空值跳过,isnull/isnotnull 例外)、resolveBatchListFieldCondition(区分标准结构与裸值,仅标准结构读取 operator,裸值回落字段默认操作符)、buildBatchListFieldConditionSql(操作符 → SQL 片段 + 命名占位符)、normalizeBatchListDistinguishExpressValue(布尔归一 0/1)、normalizeBatchListStoreIdCondition(货主条件归一 in/notin)。", + "默认语义与历史完全对齐:wave_no/creator/logistics_name/item_part/item_snapshot_key/item_detail_machine 未传 operator 时 LIKE '%值%';wave_id/wave_type/wave_status/source/distinguish_express 默认等值;total_orders_min/max、processed_orders_min/max 默认 ge/le;裸数组按 in(此前会被 String(arr) 拼成 'A,B' 恒空)。", + "新增数值字段 total_orders / processed_orders(默认 eq,支持 between 等数值操作符);原有 *_min/*_max 保留范围语义,也接受标准结构覆盖默认操作符(如 {operator:'between',value:[1,20]})。", + "store_id:默认 eq/in(返回包含任一筛选货主订单的波次,含混合货主波次);新增 ne/notin 排除语义——外层 WHERE 追加 wb.wave_id NOT IN (SELECT DISTINCT od.wave_id FROM <订单分表> od WHERE od.wave_id IS NOT NULL AND od.store_id IN (:whereStoreIds)),子查询显式排除 NULL 波次号,避免 NOT IN 三值逻辑把整表过滤为空。", + "分配/复核状态类(storage/express/print/review_assignment_status)仍只支持等值(内部按聚合统计判定):改为先解构 {operator,value} 再校验,显式传非 eq 操作符直接报错「仅支持: eq」,不再被 String({...}) 静默拼成非法枚举值。", + "根因:batchList 走原生 SQL 拼条件(列表查询路线 B),只读 .value 不读 operator——整数字段 Number({operator,value}) → NaN → 抛「参数不合法」;文本字段 String([...]) → 'A,B' → LIKE '%A,B%' 恒空(无报错难以定位)。", + "验证:run/check-wave-batch-where-operator.cjs(egg-mock 起真实 service,只读、不写库、不清理数据)33/33 通过——基线 274;wave_no eq/like/裸值/startswith/notlike/数组 contains/数组 eq;wave_id 裸值/in/裸数组/gt/between/notbetween;creator 裸值/eq/ne;wave_type in;source in;distinguish_express 裸 true/in;total_orders between、total_orders_min/max 历史回归;logistics_name isnotnull;storage_assignment_status {operator:eq} 与裸值结果一致;store_id 裸值/数组/notin(= baseline - positive)/不存在货主(notin 直通基线,验证 NULL 安全);5 个错误用例(不支持操作符、store_id 不支持操作符、分配状态仅 eq、where 禁止 warehouse_id、不支持的字段)。期望值均由本地开发库现算(含货主覆盖数),不依赖硬编码总量。", + "methods/system.json:order.wave.batchList 方法描述与 where 参数说明同步操作符契约、字段分组允许集合、新增 total_orders/processed_orders 与 store_id ne/notin 语义;version 0.3.110 -> 0.3.111,updatedAt 2026-09-11。", + "兼容性:未显式传 operator 的既有调用语义完全不变,包括 delivery_order.findAutoGroupingWaveId 传入的 wave_status/item_part_type/item_part/item_snapshot_key/distinguish_express/logistics_name 裸值,以及分页 page/pageSize 顶层写法。", + "未执行任何部署/回退脚本,未改动生产数据;ESLint(npx eslint app/service/systemMethods/order/wave.js)0 error。" + ] + }, + { + "version": "2026.09.10-packing-where-waybill-wave-contains", + "date": "2026-09-10", + "type": "changed", + "summary": "order.packing.list / order.packing.export 的 where.waybill_code 与 where.wave_no 新增 operator 支持:operator=contains(兼容 like)时按 LIKE '%值%' 模糊匹配;两字段 value 均支持字符串数组(多值取并集)。修复前端通用筛选器下发 {operator:'contains', value:[...]} 时因数组被整体字符串化(String(['A','B']) → 'A,B')导致恒返回空列表的问题。", + "methods": [ + "order.packing.list", + "order.packing.export" + ], + "module": "order.packing", + "notes": [ + "app/service/systems/order_packing.js:_buildListWhere 的 waybill_code 分支改为逐单号展开条件——operator=contains/like 下发 { waybill_code: { [Op.like]: '%单号%' } }(escapeLikeWildcards 转义通配符);缺省/eq 保持原「完整单号等值 + 剥离 -1-1- 分段后缀主体等值 + 主体前缀 LIKE '主体-%'」三件套,仍不落入 %短串% 模糊分支。所有条件合并为一次 OrderExpress.findAll({ [Op.or]: ... }) 解析 order_id,无命中仍走 queryWhere.id = -1 强制空结果。", + "app/service/systems/order_packing.js:wave_no 分支支持 operator——eq/in 精确(单值等值、多值 Op.in)、ne 不等、contains/like/缺省为模糊 LIKE '%值%'(缺省保持历史模糊语义),多值模糊通过 queryWhere[Op.and] 追加 { [Op.or]: [...] } 合并。", + "list 与 export 复用同一 _buildListWhere,导出同步生效;未改任何 SQL 结构,仅条件组装方式变化。", + "验证:run/check-packing-where-contains.cjs(egg-mock 启动真实 service,只读)10/10 通过——数组+contains 命中 2 条(原上报场景原为 0 条)、单值无 operator 回归 1 条、数组+eq 2 条、不存在单号+contains 0 条、空数组等同无筛选 13 条、wave_no contains 单值 3 条/数组 4 条、wave_no in 4 条、wave_no eq 精确不模糊 0 条。" + ] + }, + { + "version": "2026.09.10-report-filename-time-placeholder", + "date": "2026-09-10", + "type": "changed", + "summary": "报表导出文件名模板新增占位符:{time}(生成时刻 HHmmss)、{datetime}(数据日期_生成时刻)、{timestamp}(生成时刻毫秒时间戳);{date} 语义保持不变(仍为数据日期 params.bizDate,缺省服务器当天)。用于同一天多次投递/手动导出同一报表时避免 COS 同名覆盖(同名文件被后一次写覆盖且 CDN 可能仍回源旧内容,表现为「下载到的还是旧版列」)。缺省文件名模板不变,存量定义不受影响(未改 file_name 者行为完全不变)。", + "methods": [ + "report.generate", + "report.definition.save", + "report.definition.list", + "report.deliveryPlan.save" + ], + "module": "report", + "notes": [ + "app/service/systems/report.js:buildFilename(definition, bizDate, now) 新增第三参 now(生成时刻,缺省 new Date(),可注入供测试);替换顺序 {datetime} -> {date} -> {time} -> {timestamp};{date} 取值逻辑(params.bizDate || 服务器当天)与既有行为完全一致;缺省模板仍为 _.xlsx。", + "根因与实测:2026-09-10 同一 (store 1000000, 定义 3, biz_date 2026-09-09) 在 19:40、19:58、20:07 三次投递使用同名 interceptOrder_2026-09-09.xlsx,COS 对象被覆盖且 CDN 仍回源旧版本,导致用户看到 10 列旧表(缺「仓库商品名称」)。定义改为 interceptOrder_{date}_{time} 后手动导出产出 interceptOrder_2026-09-09_201533.xlsx,文件 13 列(含仓库商品名称/平台交易单号/两列拦截时间)与定义勾选一致。", + "app/model/report_definition.js 字段注释、app/service/systemMethods/report/definition.js JSDoc、methods/system.json(report.definition.save description 与 file_name 参数/响应/定义对象说明共 4 处)、docs/report-config-guide.md 第 1 节模型表与第 4 节文件名说明同步为四种占位符;docMeta.version 0.3.108 -> 0.3.109,updatedAt 保持 2026-09-10;本变更记录写入 methods/changes/system.json 数组首位。", + "测试:test/report_systems_engine.cjs 的 buildFilename 用例扩充({date}_{time}、{datetime}、{timestamp}、不同生成时刻文件名不同、未传 now 回落当前时刻、{date} 语义不变、缺省模板与自动补 .xlsx 保持);13 个 test/report_*.cjs 全部通过,ESLint 0 error。", + "数据/配置变更(仅开发库,已披露):wms_report_definition id=3 的 file_name 由 interceptOrder_{date} 改为 interceptOrder_{date}_{time},使定义重新投递/手动导出时文件名唯一。", + "兼容性:占位符为新增能力,未使用新占位符的既有定义(如 7日出入库数据 7daysStockFlow_{date})输出文件名与行为完全不变;未执行部署脚本,未改动生产数据。" + ] + }, + { + "version": "2026.09.10-intercept-order-source-order-codes", + "date": "2026-09-10", + "type": "added", + "summary": "interceptOrder(库内确定拦截订单明细)报表新增导出列「平台交易单号」(字段 key source_order_codes,取配送表 wms_order_delivery_*.source_order_codes 原值,列位置紧跟「外部单号」)。注册字段数 48 -> 49(订单导出 item 模式去掉商品图片 46 列 + 附加 3 列:平台交易单号 + 通知拦截时间 + 库内确定拦截时间);接口入参/响应契约不变,stockFlow 与 order.export 均不受影响。", + "methods": [ + "report.definition.typeList", + "report.generate", + "report.definition.save" + ], + "module": "report", + "notes": [ + "app/service/systems/report/queries/interceptOrder.js:FIELDS 在 external_order_code(外部单号)之后插入 { key: 'source_order_codes', label: '平台交易单号', type: 'string' }。", + "app/service/systems/report/queries/interceptOrder.js:enrichInterceptTimes 重命名为 enrichInterceptFields(已导出),回查 attributes 由 [id, intercept_time, dispath_time] 扩为 [id, source_order_codes, intercept_time, dispath_time],同一批查询同时回填平台交易单号(null/undefined 归一化为空字符串);仍按 500 订单分片、异常只 warn 不阻断报表。", + "取数原因:明细行来自 orderExport.buildOrderExportPage(mode=item) → mapOrderExportRow(item),该映射不输出 source_order_codes,故由查询器回查补充。", + "测试:test/report_intercept_order_fields.cjs 同步为 49 列断言(预期列序 = 订单导出 item 去掉商品图片,在 external_order_code 后插入平台交易单号、末尾 2 列拦截时间),并补充平台交易单号取值与回查 attributes 断言;test/report_systems_engine.cjs 注册字段数断言 48 -> 49;13 个 report_*.cjs + test/intercept_time_lifecycle.cjs 全部通过,ESLint 0 error。", + "端到端:script/tmp-verify-intercept-order-dev.cjs D 段增加平台交易单号与配送表 source_order_codes 的逐单交叉核对(通过);同时修正该脚本 A 段旧断言(原先假设开发库昨日 0 行,现改为校验 meta.orderCount 与明细去重订单数一致)。", + "生产/开发验证:投递计划 id=2(货主 1000000 → 仓 100000,时间点 19:40)于 2026-09-10 19:40:45 投递成功(wms_report_delivery_log id=16 status=delivered,文件 exports/report/3/store-1000000/20260910/interceptOrder_2026-09-09.xlsx),文件内容核对为 1 表头 + 4 行明细(对应补测的 3 单)。", + "methods/system.json:report.definition.typeList description 与 fields 说明同步为 49 列(含平台交易单号);docMeta.version 0.3.107 -> 0.3.108,updatedAt 保持 2026-09-10;本变更记录写入 methods/changes/system.json 数组首位。", + "docs/report-config-guide.md 2.2 节:字段清单新增 source_order_codes 行(紧跟 external_order_code)、列数 48 -> 49、第 10 条口径改为「附加列(3 列)」并说明平台交易单号来源;AI_METHOD_ROUTING.md report 速查同步。", + "注意:报表定义的 fields 需显式勾选 source_order_codes 才会出现在导出列中(已有定义不动则不输出该列);本次未修改任何已有 wms_report_definition 配置行,未执行部署脚本。" + ] + }, + { + "version": "2026.09.10-intercept-time-lifecycle", + "date": "2026-09-10", + "type": "changed", + "summary": "拦截时间 intercept_time 口径调整(wms_order_delivery):统一为「最近一次发起拦截的通知时刻」——发起/通知拦截仅**首次写入**(重复发起不覆盖已有值),库内拦截确认(order.recheckOrder.confirmIntercept / order.recheckOrder.interceptScan / 定时自动确认)与退回入库(returned)**不再写该字段**,取消/解除拦截(order.pendingOrder.batchUnintercept)与订单克隆重置**置空 null**;「库内确定拦截时刻」改用配送表 dispath_time(订单迁移进配送表的时间)。同步调整 interceptOrder 报表两列:通知拦截时间 intercept_notice_time = 配送表 intercept_time(为空回落 ORDER_INTERCEPT_REQUEST 操作日志最早一条),库内确定拦截时间 intercept_confirm_time = 配送表 dispath_time(原 key intercept_time 更名;该报表类型尚未落库定义行,无兼容问题)。", + "methods": [ + "order.pendingOrder.batchIntercept", + "order.pendingOrder.batchUnintercept", + "order.pendingOrder.cloneOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.interceptScan", + "report.definition.typeList", + "report.generate" + ], + "module": "order", + "notes": [ + "app/lib/intercept_time.js(新增):拦截时间字段口径工具(纯函数):isEmptyInterceptTime、buildNoticeTimePatch(currentValue, now)(空值才写入,已有值返回空对象=不覆盖)、pickNoticeTimeOrderIds(rows)(批量场景筛出尚未写入通知时刻的订单ID,去重保序);文件头注释固化生命周期口径(首次写入/不覆盖/取消置空/库内确定时刻改用 dispath_time)。", + "发起/通知拦截(首次写入,不覆盖):app/service/qimenMethods/order.js(intercepting/requested 两处 existingOrder.update 改为 ...buildNoticeTimePatch(existingOrder.intercept_time, noticeNow))、app/service/openapiMethods/order.js(intercepting)、app/service/inbox/functions.js(两处波次感知拦截:订单查询 attributes 增补 intercept_time,主更新只写 intercept_status,随后仅对 pickNoticeTimeOrderIds 命中的订单补写 intercept_time)、app/service/systemMethods/order/pendingOrder.js(取消订单转拦截的 syncedOrders 批量更新、batchIntercept 分批更新:同样先取空值订单子集再补写)。", + "库内拦截确认不再覆盖:app/service/systems/intercept_auto_confirm.js(confirmInterceptForOrderIds 的 updateValues 移除 intercept_time)、app/service/systemMethods/order/recheckOrder.js(interceptScan 的 orderModel.update 移除 intercept_time)。app/service/systems/return_received.js(退回入库 updateFields 移除 intercept_time)。", + "取消/清空:app/service/systemMethods/order/pendingOrder.js batchUnintercept 保持 intercept_time=null(解除拦截置空);cloneOrder 的 RESET_FIELDS 新增 intercept_time=null(避免克隆重置新单继承原单发起拦截时刻)。", + "interceptOrder 报表(app/service/systems/report/queries/interceptOrder.js):enrichInterceptTimes 改为 attributes=[id, intercept_time, dispath_time];intercept_notice_time ← intercept_time(为空时才回落 wms_operation_log 的 ORDER_INTERCEPT_REQUEST 最早记录,同仓隔离 business_type/business_id/warehouse_id 三重过滤,主取有值时不查日志);intercept_confirm_time ← dispath_time;meta 计数更名 confirmTimeFilledCount(原 interceptTimeFilledCount)。", + "测试:新增 test/intercept_time_lifecycle.cjs(纯函数 3 例 + 写入点静态守卫 4 例:确认链路不得同写 intercepted_at_warehouse 与 intercept_time、发起链路使用首次写入工具、取消与克隆重置置空、退回入库不覆盖);test/report_intercept_order_fields.cjs 同步更新(末 2 列 key、dispath_time 作为库内确定拦截时间、日志兜底用例、缺失/模型不可用降级),共 18 例;test/report_*.cjs 13 个文件 + 新测试全部通过;ESLint 0 error。", + "端到端校验(只读、无写操作):script/tmp-verify-intercept-order-dev.cjs D 段改为对开发库真实订单交叉核对「通知拦截时间=intercept_time(空时回落日志)」与「库内确定拦截时间=dispath_time」,与直连 SQL 一致。", + "兼容性与风险:intercept_time 在本次上线前的历史数据可能仍是确认时刻(旧逻辑覆盖所致),这部分历史行的「通知拦截时间」不可靠;报表按「昨日」取数,上线次日起数据即为新口径。自动确认定时任务仍以 intercept_time 作为「发起后超时」判定依据,语义反而更准确(未被确认覆盖)。", + "methods/system.json:order.pendingOrder.batchIntercept(首次写入不覆盖 + 取消清空说明)、order.pendingOrder.batchUnintercept(解除拦截清空 intercept_time)、order.recheckOrder.confirmIntercept 与 order.recheckOrder.interceptScan(确认不写 intercept_time、库内确定时刻以 dispath_time 为准)description 同步;report.definition.typeList 字段清单描述 key 更新为 intercept_confirm_time;docMeta.version 0.3.106 -> 0.3.107,updatedAt 保持 2026-09-10;本变更记录写入 methods/changes/system.json 数组首位。", + "docs/report-config-guide.md 2.2 节第 10 条与字段清单、AI_METHOD_ROUTING.md report 速查(新增拦截时间口径变更条目)同步;本次未执行任何数据库/Redis 写操作,未运行部署脚本。" + ] + }, + { + "version": "2026.09.10-intercept-order-time-columns", + "date": "2026-09-10", + "type": "added", + "summary": "interceptOrder(库内确定拦截订单明细)报表新增导出列「通知拦截时间」与「库内确定拦截时间」:intercept_time(库内确定拦截时间)= 配送表 intercept_time(确认拦截时写入);intercept_notice_time(通知拦截时间)= wms_operation_log 中 operation_code='ORDER_INTERCEPT_REQUEST' 的最早记录时间(发起/通知拦截时刻,因为 intercept_time 在确认时会被覆盖,只能从操作日志反查,按订单ID+仓库ID同仓隔离;日志缺失时该列留空)。两列均格式化为 YYYY-MM-DD HH:mm:ss,列排在字段清单末尾,注册字段数 46 -> 48;接口入参/响应契约与 stockFlow 均不受影响。", + "methods": [ + "report.definition.typeList", + "report.generate", + "report.definition.save" + ], + "module": "report", + "notes": [ + "app/service/systems/report/queries/interceptOrder.js:FIELDS 末尾新增 intercept_notice_time(label 通知拦截时间)、intercept_time(label 库内确定拦截时间),type 均为 string(渲染层原样输出保留与订单导出 item 模式一致的零转换口径);列顺序 = 订单导出 item 模式 47 列去掉商品图片(46)+ 末 2 列拦截时间,共 48 列。", + "app/service/systems/report/queries/interceptOrder.js:新增 enrichInterceptTimes(已导出供单测/脚本复核)——按订单ID分片(ENRICH_CHUNK_SIZE=500)回查:1)配送表模型 findAll(attributes: id/intercept_time) 取库内确定拦截时间;2)OperationLog.findAll(attributes: business_id + MIN(created_at) 别名 notice_time,group by business_id)取通知拦截时间,where 限定 business_type='order' + operation_code='ORDER_INTERCEPT_REQUEST' + warehouse_id=当前仓库 + business_id IN(订单ID字符串化)。两列分别格式化为 YYYY-MM-DD HH:mm:ss(空值/无效值空字符串,与订单导出 formatDateSafe 口径一致);任一回查异常只 warn 并留空,不影响报表主流程;OperationLog 模型缺失时跳过日志查询。", + "同仓隔离:订单 ID 按仓库发号(wms_order_id_location_{wh}),日志查询必须带 warehouse_id,禁止仅凭订单ID跨仓串读(与 order_express 同仓隔离修复同口径)。", + "app/service/systems/report/queries/interceptOrder.js:查询器返回 meta 新增 noticeTimeFilledCount / interceptTimeFilledCount(两列有值行数),便于核对日志覆盖率;rows 为同一行对象的拦截时间列赋值(同一订单的多条商品明细行同值)。", + "测试:test/report_intercept_order_fields.cjs 新增 2 例(拦截时间两列取值/查询条件/分组断言;空值与 OperationLog 模型不可用降级),并同步列数断言 46 -> 48(前 46 列仍与订单导出 item 模式逐列对齐,末 2 列固定为拦截时间);test/report_systems_engine.cjs 注册表字段数断言同步为 48。test/report_*.cjs 13 个文件全部通过。", + "真实数据校验(只读、无写操作):script/tmp-verify-intercept-order-dev.cjs 新增 D 段——以 egg 真实上下文调用 enrichInterceptTimes 对开发库 5 个库内确定拦截订单富化,并与直连 SQL(配送表 intercept_time、wms_operation_log 的 MIN(created_at))逐单交叉核对一致(开发库这 5 单均无 ORDER_INTERCEPT_REQUEST 日志,故通知拦截时间为空,符合预期);渲染表头列数校验同步为 48 且末两列表头为拦截时间列。", + "methods/system.json:report.definition.typeList 的 description 与 fields 说明同步为 48 列(前 46 列对齐订单导出 item 模式去掉商品图片,末 2 列为拦截时间);docMeta.version 0.3.105 -> 0.3.106,updatedAt 保持 2026-09-10;本变更记录写入 methods/changes/system.json 数组首位。", + "docs/report-config-guide.md 2.2 节:字段清单补 2 行拦截时间列、新增第 10 条口径(两列来源/同仓隔离/空值语义/meta 计数),注册类型表与「与订单导出 item 模式差异」说明同步更新;AI_METHOD_ROUTING.md report 速查同步(48 列 + 两个时间列来源)。", + "兼容性:仅为报表列扩展(新报表类型尚未在 wms_report_definition 落库定义行,无存量定义受影响);stockFlow 与 order.export 列口径、report.generate / report.deliveryPlan 链路均未改动。" + ] + }, + { + "version": "2026.09.10-report-intercept-order-type", + "date": "2026-09-10", + "type": "added", + "summary": "通用报表新增注册类型 interceptOrder(库内确定拦截订单明细):以配送表 dispath_time(订单迁移进配送表的时间)为时间基准,统计昨日(自然日 [昨日 00:00:00, 今日 00:00:00) 本地时区半开区间)库内确定拦截订单(intercept_status=intercepted_at_warehouse),**统计日不得晚于昨天**(params.bizDate 传今天/未来一律回落昨日,今天发出去的报表不含今天数据;比昨天更早的显式日期仍被尊重以支持补数),按商品明细展开(一个商品一行),列与订单导出含明细模式(order.export export_mode=item)完全对齐、仅去掉「商品图片」列(共 46 列)。报表定义 type 填 interceptOrder 即可使用,report.generate / report.deliveryPlan / wms_report_definition 结构均无需变更。", + "methods": [ + "report.definition.typeList", + "report.generate", + "report.definition.save" + ], + "module": "report", + "notes": [ + "app/service/systems/report/queries/interceptOrder.js(新增):查询器签名与 stockFlow 一致 async ({ctx, storeId, warehouseId, params}) => ({windows: [], rows, meta})。数据源为配送表 wms_order_delivery_{warehouseId}_dispatch(经 orderExport.getOrderModelByTableType('dispatch', warehouseId) 取模型),过滤 intercept_status='intercepted_at_warehouse' 且 dispath_time ∈ [统计日 00:00:00, 次日 00:00:00);warehouseId 必填(<=0 抛「interceptOrder 查询器缺少仓库维度 warehouseId」),storeId>0 时追加 store_id 过滤(货主维度报表/投递),否则仓库维度全量。", + "明细口径复用订单导出链路:按单页 1000 单分页循环(不足一页终止)调用 orderExport.buildOrderExportPage({ mode: 'item' }),即复用 mapOrderExportRow(item) 的状态中文翻译、货主备注、仓库商品名/条码回落、运单汇总、包材、收件人脱敏等取值,逐格与订单导出 item 模式一致;行再经 pickReportRow 按注册字段裁剪(丢弃 item_image 等多余键,缺失值回落空字符串)。", + "统计日解析 resolveBizDayWindow:params.bizDate(兼容 biz_date)为真实存在的 YYYY-MM-DD 时按该自然日整天统计,缺省/非法一律回落昨日自然日;区间左闭右开,用 new Date(y, m, d) 构造规避夏令时步进偏差。Sequelize 未配置 timezone(默认 UTC)+ MySQL 时区 UTC,dispath_time 写入(orderDeliveryMigration.buildDispatchRow 写 new Date())与本查询的时间过滤经同一序列化路径,口径自洽。", + "字段清单 FIELDS 共 46 列,与 order.export 的 ORDER_EXPORT_ITEM_COLUMNS(47 列)逐列对齐并去掉「商品图片」列,key/label/顺序一致;type 统一为 string(渲染层 renderCell 原样输出,不做 zeroToDash/yesNo 转换,且不声明 asText),以保证单元格取值与订单导出一致;无 array 展开列,windows 恒为空数组、单行表头、无表头合并。", + "app/service/systems/report/queries/index.js:QUERIES 注册 interceptOrder,DESCRIPTIONS 新增条目(title「库内确定拦截订单明细」、window {dayCount: 1, cutoverHour: 0}),report.definition.typeList 自动带出 46 列字段元数据供报表定义勾选。", + "行数保护与元信息:明细行数达 MAX_EXPORT_ROWS=200000 时截断并打 warn(meta.truncated=true);meta 返回 bizDate/startTime/endTime/warehouseId/storeId/interceptStatus/timeField/orderCount/rowCount/truncated 供复核。", + "波次序号(wave_index)沿用订单导出同款 attachOrderWaveIndex(仓库ID取 ctx.user.store_id),定时投递(无 ctx.user)场景该列降级为 0,仓库主体手工导出为真实序号(与 order.export 行为一致)。", + "统计日硬约束(同日补充):resolveBizDayWindow 解析出统计日后统一校验 baseDate >= 今日 00:00:00 时回落昨日——params.bizDate 传今天/未来(含手工导出误传当天)时查询区间仍为 [昨日 00:00:00, 今日 00:00:00),保证「今天发出去不含今天」;比昨天更早的显式日期仍被尊重(补数场景)。测试:test/report_intercept_order_fields.cjs 新增「硬约束:统计日不得晚于昨天」与「params.bizDate 传今天:查询区间仍为昨日」两例(共 16 例)。", + "测试:新增 test/report_intercept_order_fields.cjs(14 例:字段与订单导出 item 逐列对齐、pickReportRow 裁剪、统计日区间解析、查询器 mock 链路含分页/where/meta/storeId 过滤与错误分支);同步修正 test/report_systems_engine.cjs 与 test/report_stockflow_fields.cjs 中「注册表仅 1 种类型」的旧断言(改为按 key 定位并断言注册顺序 stockFlow → interceptOrder)。test/report_*.cjs 共 13 个文件全部通过。", + "端到端校验(只读、无写操作):script/tmp-verify-intercept-order-dev.cjs 以 egg 真实上下文在开发库跑通查询器(meta 正确、开发库历史拦截单 dispath_time 为 NULL 故昨日命中 0 行)、真实拦截订单 5 单 → 9 条商品明细行的取值映射,以及 renderSheetByType 渲染(表头 46 列、单行表头、无合并、无 textColumns)。", + "methods/system.json:report.generate description 类型举例补 interceptOrder;params.bizDate 说明补充「同时是 interceptOrder 的统计日覆盖(缺省昨日自然日)」;params.dayCount/params.cutoverHour 标注仅 stockFlow 生效;report.definition.typeList 的 description、response.list、window.dayCount、window.cutoverHour、fields 说明同步为两种类型口径;docMeta.version 0.3.104 -> 0.3.105,updatedAt 保持 2026-09-10;本变更记录写入 methods/changes/system.json 数组首位。", + "docs/report-config-guide.md:新增注册类型行、46 列字段清单与 interceptOrder 口径章节;wms_report_definition 定义行由业务侧在后台配置(本次未插入定义行、未执行任何数据库写操作)。", + "未修改任何既有接口入参/响应契约:新增类型为注册表扩展,stockFlow 行为不变,report.generate / report.deliveryPlan / report.exportTaskProgress 链路无需改动。", + "README.md / AI_TOOLBOX.md 无需同步:检索确认无注册类型清单描述;AI_METHOD_ROUTING.md 第 6 节为函数清单,本次未新增/删除既有函数名(interceptOrder 为查询器注册 key),如需刷新可另行执行扫描脚本" + ] + }, + { + "version": "2026.09.10-cross-warehouse-order-express-warehouse-isolation", + "date": "2026-09-10", + "type": "fixed", + "summary": "跨仓运单号串读缺陷修复文档同步:修复前所有按订单 ID 读取 wms_order_express 的查询缺少 warehouse_id 强制校验,存在跨仓串读运单号风险;修复后所有读取链路均强制校验订单所属仓库(查询条件同时限定订单ID与仓库ID),仓库归属无法确定时跳过读取或拒绝读取。order.detail 及各订单列表接口 description 补充「运单号按订单所属仓库隔离读取」说明,接口入参/出参契约不变。", + "methods": [ + "order.detail", + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.pendingOrder.detail", + "order.pendingOrder.reverseReviewOrder", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list", + "order.wave.waveStrategyFallbackOrderList", + "order.recheckOrder.recheckOrderList", + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "module": "order", + "notes": [ + "app/service/systemMethods/order/base.js:getOrderExpressesByOrderId 强制同仓校验(仓库ID优先取订单行 order.warehouse_id,缺省回退当前上下文仓库,均缺失返回空数组);attachOrderExpressNumbers 批量回填改为按「订单ID+仓库ID」逐仓分组查询(行内 warehouse_id 优先,缺省回退上下文仓库,无法确定仓库归属的订单不参与运单查询)", + "app/service/systemMethods/order/recheckOrder.js:confirmRecheck 调用 getOrderExpressesByOrderId 传入订单行;queryRecheckOrderSingleList 运单号关键词 EXISTS 搜索与 waybill_code 子查询均追加 oe.warehouse_id = o.warehouse_id 同仓条件", + "app/service/systemMethods/order/pendingOrder.js:detail 传订单行给 getOrderExpressesByOrderId;assertOrdersWithoutWaybill 增加 warehouseId 入参强制同仓校验(reverseReviewOrder 反审前运单校验传入当前仓库ID,缺少仓库上下文时跳过校验读取,按无可读记录处理)", + "app/service/systems/order_express.js:findValidOrderExpressRows 仓库ID缺失直接抛 400「缺少仓库上下文,禁止读取订单运单记录」;checkExpress 存在性校验、updateWeighingWeight、updateWeighingWeightByWaybill、按订单ID批量查询等读取链路全部追加 warehouse_id 条件", + "app/service/systems/storage/report.js:loadReportReferenceMaps 运单查询强制 AND warehouse_id(仓库模式用当前仓库ID;货主模式按订单所属仓库 Map 分组查询);库存流水明细 SELECT 增加 t.warehouse_id 并构建订单ID→仓库ID映射传入", + "app/service/systems/order_async.js:buildOrderWaybillCodeMapInternal 增加 warehouseId 入参并强制同仓校验(缺失返回空映射),syncManualOrders/syncStockoutOrders/syncQmOrders 三处调用均传入仓库ID", + "app/service/systems/waybill.js:主单号 SELF JOIN 查询追加 warehouse_id 条件;app/service/systems/workbench.js:打包列表运单查询追加 warehouse_id 条件", + "app/service/systems/express.js:运单状态 success 行查询追加 warehouse_id(取 options.warehouse_id 或当前仓库上下文);app/service/systems/express_platform.js:polyapi 已分配运单查询强制同仓校验,仓库ID缺失时不查询", + "app/service/qimenMethods/order.js:getInterceptExpressInfo 增加 warehouseId 入参强制同仓校验(缺失返回空数组),sendCancelInterceptNotice 与取消拦截链路均传入 info.warehouseId;app/service/inbox/functions.js:已分配快递单号查询追加 warehouse_id;app/lib/intercept_guard.js:拦截守卫称重查询追加 warehouse_id", + "methods/system.json:order.detail、order.pendingOrder.detail 与各订单列表接口(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、order.wave.waveStrategyFallbackOrderList、order.recheckOrder.recheckOrderList、order.recheckOrder.queryRecheckOrderSingleList)description 补充运单号按订单所属仓库隔离读取说明;params/response/errors/headers 契约均未变化;docMeta.version 0.3.103 -> 0.3.104,updatedAt 2026-09-08 -> 2026-09-10;本变更记录写入 methods/changes/system.json 数组首位", + "README.md / AI_TOOLBOX.md / AI_METHOD_ROUTING.md 无需同步:检索确认无 wms_order_express 读取口径描述;AI_METHOD_ROUTING.md 第 6 节为函数清单,本次未新增/删除函数名(仅实现与签名参数变化),无需刷新", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ] + }, + { + "version": "2026.09.08-front-config-cert-pem-echo", + "date": "2026-09-08", + "type": "changed", + "summary": "setting.warehouse.getFrontConfig 响应改为回显证书/私钥原文(cert_path/key_path 替换为 cert_pem/key_pem):cert_pem 读 cert_pem 列、key_pem 读 cert_key 列,未配置均为空字符串,响应仍 15 字段;saveFrontCert/saveFrontConfig 复用 buildFrontConfigOutput,响应口径同步返回 cert_pem/key_pem 原文;仅登录后的仓库主体(settings 页)接口回显,公共无鉴权接口 frontConfig.getByDomain 不受影响仍 6 字段白名单(domain/title/logo_url/login_bg_url/favicon_url/theme),严禁暴露证书内容。", + "methods": [ + "setting.warehouse.getFrontConfig", + "setting.warehouse.saveFrontConfig", + "setting.warehouse.saveFrontCert" + ], + "module": "setting.warehouse", + "notes": [ + "app/service/systems/setting/warehouse.js:buildFrontConfigOutput 输出字段 cert_path→cert_pem(证书 PEM 原文,读 cert_pem 列)、key_path→key_pem(私钥 PEM 原文,读 cert_key 列),未配置均为空字符串;响应仍 15 字段(warehouse_id/domain/title/logo_url/favicon_url/login_bg_url/theme/cert_pem/key_pem/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at/updated_at);方法注释明确私钥原文回显仅限仓库主体登录后的 settings 页(getFrontConfig/saveFrontConfig/saveFrontCert 三个需登录接口复用本输出),公共无鉴权接口走 buildFrontConfigPublicOutput 白名单、不经过本方法", + "app/service/systems/setting/warehouse.js:getFrontConfig 响应含证书原文(cert_pem)与私钥原文(key_pem)供仓库主体 settings 页回显;buildFrontConfigPublicOutput/getFrontConfigByDomain 不变(仍仅 FRONT_CONFIG_PUBLIC_FIELDS 6 字段,严禁输出 cert_pem/cert_key 证书与私钥内容及 cert_path/key_path/sync_status 等内部字段)", + "app/service/systems/setting/warehouse.js:saveFrontConfig(约 L1260)与 saveFrontCert(约 L1380)响应均复用 buildFrontConfigOutput,响应口径与 getFrontConfig 一致返回 cert_pem/key_pem 原文;saveFrontCert 保存时证书/私钥 PEM 直接写 cert_pem/cert_key 列、cert_path/key_path 置空待定时任务回填真实路径的行为不变", + "methods/system.json:setting.warehouse.getFrontConfig/saveFrontConfig/saveFrontCert 三个条目 response 中 cert_path/key_path 字段替换为 cert_pem/key_pem(原文回显语义、未配置为空字符串、注明仅登录仓库主体 settings 页回显的安全口径);getFrontConfig description 补充证书/私钥原文回显与公共接口 6 字段白名单口径;saveFrontCert description 由「响应 15 字段不含证书/私钥内容」修正为「响应 15 字段含 cert_pem/key_pem 原文回显」并同步「内容供定时任务读取、禁止写入日志」口径;saveFrontCert response updated_at 字段描述移除「响应不含 cert_pem/cert_key 证书与私钥内容」旧口径;getFrontConfig response cert_expire_at 描述删除已废弃的「纯路径模式」口径;frontConfig.getByDomain 条目未改动(仍 6 字段白名单、isNeedLogin=false、isNeedAuth=false);docMeta.version 0.3.102 -> 0.3.103,updatedAt 保持 2026-09-08;本变更记录写入 methods/changes/system.json 数组首位", + "README.md / AI_TOOLBOX.md 无需同步:检索确认无 cert_path/key_path/getFrontConfig/saveFrontCert 字段描述引用;AI_METHOD_ROUTING.md 第 6 节仅方法名清单(getFrontConfig/saveFrontConfig/saveFrontCert 方法名未变、buildFrontConfigOutput 函数名未变)无需同步", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ] + }, + { + "version": "2026.09.08-wave-strategy-group-buy-cross-pool-merge", + "date": "2026-09-08", + "type": "changed", + "summary": "小团购 PDA 抓取跨池同结构合并文档同步(修复「1 单 1 波次」问题):order.wave.waveStrategyFetchPda 抓取主流程新增小团购跨池同结构合并工序(mergeWaveStrategyFirstPoolSameStructureOrders),自动分流执行结果 result 新增 merged_order_count 字段(合并进候选的跨池订单数量,无合并时为 0);触发条件为小团购 pickMode=1 + 第一池非空 + max_same_structure 为正整数且≠999,max_same_structure 为 null/999 的策略、大团购 pickMode=5 与后台抓取入口行为不变。", + "methods": [ + "order.wave.waveStrategyFetchPda" + ], + "module": "order.wave", + "notes": [ + "app/service/systemMethods/order/wave.js:新增私有方法 mergeWaveStrategyFirstPoolSameStructureOrders(约 L11339~L11495):按第一池候选分组出现过的 structure_key(require_same_express=1 时为「结构+快递」组合,快递口径复用候选 SQL expressExpr 的 COALESCE 优先级 sys_logistics_code > logistics_code > logistics_name)查询同结构全池过筛订单(wave_id=0、step!=0、post_status/storage_status=fin、print_status!=fin、status!=cancel、outbound_status!=padding、intercept_status=none、lock_status=none,不限策略匹配、不含池边界 create_at 条件),将两池同结构订单全部并入候选(按 id 去重)后复用既有分组建波流程;任一门控不满足返回 null 跳过合并", + "app/service/systemMethods/order/wave.js:autoPopulateWaveStrategyFetchSelections 团购分支(strategy_type=2 且 pickMode=1)接入合并:仅 pickMode=1 且 candidate_pool_stage='first' 且 max_same_structure 为正整数且≠999 时执行合并,merged_order_count = 合并后候选数 - 原候选数;max_same_structure 为 null/999、pickMode=5(大团购)、第一池为空、全池查询无新增订单时 merged_order_count=0 维持现状;后台抓取入口(executeWaveStrategyDirectFetch / waveStrategyFetchAdmin)不经过本方法不受影响", + "背景:订单池按今日前/今日分割 + min_same_structure 全池计数口径导致某结构第一池仅剩 1 条时仍通过门槛单独成波(生产订单 11103 案例「1 单 1 波次」)", + "methods/system.json:order.wave.waveStrategyFetchPda 条目 response 数组末尾新增 merged_order_count 字段说明(合并进候选的跨池订单数量、无合并为 0、不含在原 candidate_count 内、合并后候选总量 = candidate_count + merged_order_count);description 补充小团购跨池同结构合并规则(触发条件与跳过条件);params/headers 不变;errors 条目键名由 description 规范化为 message(文案不变,满足更新脚本 schema,与 order.wave.waveStrategyList 等先例一致);docMeta.version 0.3.101 -> 0.3.102,updatedAt 保持 2026-09-08;本变更记录写入 methods/changes/system.json 数组首位", + "兼容性:merged_order_count 为自动分流执行结果 result 新增可选字段,向后兼容;pickMode=5(大团购)、max_same_structure 为 null/999 的策略、后台抓取入口与第一池为空的场景行为与改动前一致,无接口破坏性变更", + "回归验证:test/wave_first_pool_merge_regression_20260908.cjs 覆盖门控(pickMode/池阶段/max_same_structure)、快递组合口径、合并去重、merged_order_count 计数与建波结果(wms-test-agent 回归通过)", + "README.md / AI_TOOLBOX.md 无需同步:检索确认无 waveStrategyFetchPda 抓取数量口径描述;AI_METHOD_ROUTING.md 第 6 节为自动扫描函数清单,如需刷新可另行执行扫描脚本", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ] + }, + { + "version": "2026.09.08-wave-strategy-list-info-order-count", + "date": "2026-09-08", + "type": "changed", + "summary": "order.wave.waveStrategyList 成功响应新增 info 子对象(info.order_count):返回当前查询条件下(当前仓库 + strategy_type 过滤)全部波次策略命中的订单总数,按订单去重、不受分页影响,统计失败时安全降级为 0;错误/失败路径响应结构不变,成功路径 info 恒存在。", + "methods": [ + "order.wave.waveStrategyList" + ], + "module": "order.wave", + "notes": [ + "app/service/systemMethods/order/wave.js:waveStrategyList 成功响应新增 info 对象;当 total>0(当前仓库存在波次策略)时调用 getWaveStrategyMatchedOrderCountTotal(contextWarehouseId,{strategyType}) 统计全部命中订单去重总数,异常时捕获并记录 warn 日志(含 warehouse_id/strategy_type/error)后降级为 0,不影响列表主流程", + "app/service/systemMethods/order/wave.js:新增 getWaveStrategyMatchedOrderCountTotal(warehouseId,{strategyType}):基于 wms_order_wave_strategy_match 关联订单表与 wms_wave_strategy,require_same_express=1(结构+快递分组)与 =0(仅结构分组)两类候选口径 UNION ALL 后 COUNT(DISTINCT order_id);strategy_type 非法或未传时为 null(不过滤);仅统计未入波次且满足同结构 min/max 上下限的候选订单", + "methods/system.json:order.wave 分组 order.wave.waveStrategyList 条目 response 数组末尾新增 info 子对象及 order_count 字段说明(全部命中订单去重总数、不受分页影响、异常降级为 0),params/headers/description 保持原样;errors 条目键名由 description 规范化为 message(文案不变,满足更新脚本 schema,与 order.manualOutboundOrder 等先例一致);docMeta.version 0.3.100 -> 0.3.101,updatedAt 保持 2026-09-08;本变更记录写入 methods/changes/system.json 数组首位", + "README.md / AI_TOOLBOX.md 无需同步:检索确认无 waveStrategyList 响应结构描述;AI_METHOD_ROUTING.md 第 6 节为自动扫描函数清单(本次新增 getWaveStrategyMatchedOrderCountTotal 已纳入代码),如需刷新清单可另行执行扫描脚本", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ] + }, + { + "version": "2026.09.08-front-cert-inline-content-save", + "date": "2026-09-08", + "type": "changed", + "summary": "setting.warehouse.saveFrontCert 证书上传接口改版文档同步:入参 cert_pem/key_pem 重命名为 pem/key(必填,超长文案「pem|key 内容长度不能超过 65536 字符」);证书/私钥 PEM 内容直接写入 cert_pem/cert_key 列入库、保存时不再写暂存文件,cert_path/key_path 保存置空、等待未来定时任务部署后回填真实路径;cert_expire_at 仍由证书 validTo 权威写入,同步状态机重置(sync_status=0/sync_attempts=0/清空 last_sync_error/last_synced_at)与新旧 domain 公共拉取缓存清理保持不变;删除「证书暂存目录未配置/证书文件写入失败」500 错误分支;响应 15 字段不含证书内容(cert_pem/cert_key 仅定时任务读取)。", + "methods": [ + "setting.warehouse.saveFrontCert" + ], + "module": "setting.warehouse", + "notes": [ + "app/service/systems/setting/warehouse.js:saveFrontCert 入参改为 domain/pem/key(domain 经 normalizeFrontConfigText(data.domain,'domain',100) 校验非空 400「domain 不能为空」与超长 400「domain 长度不能超过 100 字符」;pem/key 经 normalizeFrontConfigPem 校验非空 400「pem 不能为空」「key 不能为空」、超长 400「pem|key 内容长度不能超过 65536 字符」);移除 writeFrontConfigCertFiles 落盘链路,证书内容直接入库 patch.cert_pem=certPem/cert_key=keyPem,patch.cert_path=null/key_path=null(等待未来定时任务从库内读取内容写 nginx 证书目录后回填真实路径);校验链 parseFrontConfigCertPem → assertFrontConfigCertValid → validateFrontConfigKeyPem → collectFrontConfigCertNames/frontConfigCertCoversDomain → assertFrontConfigDomainUnique 不变,任一失败统一「证书不合法」400;cert_expire_at=new Date(cert.validTo) 权威写入不变;sync_status=0/sync_attempts=0/清空 last_sync_error/last_synced_at 与新旧 domain front:config:domain:{*} 缓存清理逻辑不变;响应 buildFrontConfigOutput 15 字段不含 cert_pem/cert_key(内容仅定时任务读取)", + "app/service/systemMethods/setting/warehouse.js:saveFrontCert 薄出口透传改为 domain/pem/key,_noNeedRight/_noNeedAuth 不变;错误 code 透传不变", + "app/model/warehouse_front_config.js:cert_pem/cert_key TEXT 列承接证书内容(comment 注明仅定时任务读取、禁止写入日志/接口响应),cert_path/key_path 保存置空由未来定时任务回填;模型结构无变更", + "config/config.default.js:frontConfig.certStagingDir 保留(注释已更新为「保存接口不再写暂存文件、证书内容直接入库,目录供未来定时任务部署使用」),无配置键变化", + "methods/system.json:setting.warehouse.saveFrontCert 条目 params cert_pem→pem、key_pem→key(文案同步「pem/key 不能为空」与「pem|key 内容长度不能超过 65536 字符」);description 改为内容直接入库、cert_path/key_path 置空待定时任务回填、响应不含证书内容;errors 删除 500「证书暂存目录未配置(frontConfig.certStagingDir)或证书文件写入失败」分支,其余 400/403/409/500 文案按代码核实保留;response 15 字段结构不变;docMeta.version 0.3.99 -> 0.3.100,updatedAt 保持 2026-09-08;本变更记录写入 methods/changes/system.json 数组首位", + "AI_METHOD_ROUTING.md:第 6 节自动扫描清单定向修正 systems/setting/warehouse.js 31→30(writeFrontConfigCertFiles 已从代码移除);systemMethods/setting/warehouse.js 6 个方法名不变,其余条目未动", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ] + }, + { + "version": "2026.09.08-front-cert-config-split", + "date": "2026-09-08", + "type": "changed", + "summary": "前端独立部署「证书上传」与「配置保存」拆分文档同步:新增 setting.warehouse.saveFrontCert 接口文档(证书上传:domain+cert_pem/key_pem 成对必填,校验链任一失败统一返回「证书不合法」400,通过后自动权威写入 cert_expire_at、证书内容落盘只存路径、清新旧 domain 公共拉取缓存);saveFrontConfig 入参瘦身为仅品牌字段 title/logo_url/favicon_url/login_bg_url/theme(domain/cert_pem/key_pem/cert_path/key_path/cert_expire_at 不再受理,前端传值被方法层白名单静默忽略,domain 变更必须走 saveFrontCert)。", + "methods": [ + "setting.warehouse.saveFrontCert", + "setting.warehouse.saveFrontConfig" + ], + "module": "setting.warehouse", + "notes": [ + "app/service/systemMethods/setting/warehouse.js:新增 saveFrontCert 薄出口(透传 domain/cert_pem/key_pem,错误 code 透传);_noNeedRight/_noNeedAuth 增加 saveFrontCert(需登录、免权限、免鉴权,权限靠业务层 isWarehouse 判定);saveFrontConfig 方法层白名单收敛为 title/logo_url/favicon_url/login_bg_url/theme(domain/cert_path/key_path/cert_pem/key_pem/cert_expire_at 一律静默忽略)", + "app/service/systems/setting/warehouse.js:saveFrontCert 校验链 parseFrontConfigCertPem(crypto.X509Certificate)→ assertFrontConfigCertValid(未生效/已过期 400)→ validateFrontConfigKeyPem(SPKI 公钥指纹比对,私钥无法解析/不匹配 400)→ collectFrontConfigCertNames/frontConfigCertCoversDomain(SAN DNS/CN 精确或 *.example.com 通配,不覆盖 400),所有证书校验失败统一文案「证书不合法」;domain 经 normalizeFrontConfigText(data.domain,'domain',100) 校验非空(400「domain 不能为空」)与超长(400「domain 长度不能超过 100 字符」);cert_pem/key_pem 必填(400「cert_pem 不能为空」「key_pem 不能为空」)且 ≤65536 字符(超长 400「{字段} 内容长度不能超过 65536 字符」);通过后 patch.domain/cert_path/key_path/cert_expire_at=new Date(cert.validTo)(权威值非入参)+ sync_status=0/sync_attempts=0/清空 last_sync_error/last_synced_at;writeFrontConfigCertFiles 落盘 frontConfig.certStagingDir({store_id}_{domain}.crt/.key,内容不入库只回传路径,暂存目录未配置或写入失败 500);assertFrontConfigDomainUnique 全局唯一(409「域名 {domain} 已被其他仓库使用」,并发唯一索引冲突兜底 409「仓库前端配置保存冲突,请稍后重试」);写库成功后清理旧 domain 与新 domain 的 front:config:domain:{*} 缓存(先写库后清缓存,清缓存失败仅日志)", + "app/service/systems/setting/warehouse.js:saveFrontConfig 仅按 FRONT_CONFIG_TEXT_FIELDS(title/logo_url/favicon_url/login_bg_url)+ theme 组装 patch;不再受理 domain/cert_*;保存仍重置同步状态并清理当前 domain 公共拉取缓存;响应 buildFrontConfigOutput 15 字段(warehouse_id/domain/title/logo_url/favicon_url/login_bg_url/theme/cert_path/key_path/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at/updated_at),getFrontConfig/frontConfig.getByDomain 无变化未改动", + "methods/system.json:setting.warehouse 分组 list 末尾新增 saveFrontCert 条目(isNeedLogin=true、isNeedAuth=false、Authorization 头);saveFrontConfig 条目入参瘦身(移除 domain/cert_pem/key_pem/cert_path/key_path 入参说明,description 注明前端传值静默忽略)与 errors 修订(证书校验 400 统一文案「证书不合法」移至 saveFrontCert;保留 400/403/409 并发兜底/500);docMeta.version 0.3.98 -> 0.3.99,updatedAt 2026-09-07 -> 2026-09-08;本变更记录写入 methods/changes/system.json 数组首位", + "AI_METHOD_ROUTING.md:按文件内维护说明执行第 6 节自动扫描清单刷新(node .\\script\\tmp-gen-service-method-inventory.cjs → node .\\script\\tmp-update-ai-method-routing.cjs),systemMethods/setting/warehouse.js 3→6、systems/setting/warehouse.js 12→31(以扫描结果为准)", + "README.md / AI_TOOLBOX.md 无需同步:检索确认无 saveFrontConfig/saveFrontCert 相关描述", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ] + }, + { + "version": "2026.09.07-front-config-independent-deploy", + "date": "2026-09-07", + "type": "changed", + "summary": "仓库前端独立部署功能文档同步:新增 setting.warehouse.saveFrontConfig / setting.warehouse.getFrontConfig 与公共无鉴权接口 frontConfig.getByDomain 三个方法文档。保存配置支持上传 cert_pem/key_pem:后端解析证书并校验(无法解析/未生效/已过期/SAN-CN 不包含 domain/私钥不匹配报 400),自动权威写入 cert_expire_at(不再是入参,前端传值被忽略),证书内容落盘暂存目录、库内只存路径;纯路径模式(未提供 cert_pem)直接保存 cert_path/key_path 且不写有效期;保存即重置同步状态(sync_status=0、sync_attempts=0)。新增 favicon_url 字段(保存/查询/公共拉取均含)。公共拉取接口免登录、免鉴权、免权限(保留系统日志),响应仅 6 个公开字段(绝不返回证书路径/同步状态等内部字段),Redis 缓存 front:config:domain:{domain}(命中 TTL 600s、未登记域名空缓存 60s 防穿透、保存配置自动失效新旧域名缓存)。关联迁移 20260907150000(建表 wms_warehouse_front_config)与 20260907170000(favicon_url 列)。", + "methods": [ + "setting.warehouse.saveFrontConfig", + "setting.warehouse.getFrontConfig", + "frontConfig.getByDomain" + ], + "module": "setting.warehouse", + "notes": [ + "app/service/systemMethods/setting/warehouse.js:saveFrontConfig 方法层白名单仅透传 domain/title/logo_url/favicon_url/login_bg_url/theme/cert_path/key_path/cert_pem/key_pem(cert_expire_at 不入白名单,前端传值直接忽略);getFrontConfig 无入参;两方法均需登录、免权限(_noNeedRight 含 getFrontConfig,saveFrontConfig)、免鉴权(_noNeedAuth 含两方法),saveFrontConfig 权限由业务层 getCurrentSubject().isWarehouse 判定(非仓库主体 403「仅仓库主体可配置前端独立部署」)", + "app/service/systemMethods/frontConfig.js:新模块 frontConfig(与 workbench/inbox 同级),getByDomain 配置 _noNeedLogin/_noNeedRight/_noNeedAuth='getByDomain'(免登录、免鉴权、免权限)、保留系统日志(_noNeedLog 为空);薄出口调用 systems.setting.warehouse.getFrontConfigByDomain,错误 code 透传(400/404/500)", + "app/service/systems/setting/warehouse.js:saveFrontConfig upsert 一仓一行;domain 非空时 assertFrontConfigDomainUnique 全局唯一校验(409「域名 {domain} 已被其他仓库使用」,并发唯一索引冲突兜底转 409「仓库前端配置保存冲突,请稍后重试」);normalizeFrontConfigText 校验文本字段长度(domain/title≤100、logo_url/login_bg_url/favicon_url≤255、cert_path/key_path≤500);normalizeFrontConfigTheme 校验 theme 为合法 JSON 对象;normalizeFrontConfigPem 限制 PEM ≤65536 字符;提供 cert_pem 时 parseFrontConfigCertPem(crypto.X509Certificate)+ assertFrontConfigCertValid(未生效/已过期 400)+ collectFrontConfigCertNames/frontConfigCertCoversDomain(SAN DNS/CN 精确或 *.example.com 通配匹配,不含 domain 报 400)+ validateFrontConfigKeyPem(SPKI 公钥指纹比对),writeFrontConfigCertFiles 落盘暂存目录({store_id}_{domain}.crt/.key,只回传路径、内容不入库,旧暂存文件不主动删除);key_pem 单独提供报 400;未提供 cert_pem 时纯路径模式直接落库、cert_expire_at 允许为空;保存即 patch.sync_status=0/sync_attempts=0 并清空 last_sync_error/last_synced_at;写库成功后清理新旧 domain 公共拉取缓存(先写库后清缓存,清缓存失败仅日志不影响保存)", + "app/service/systems/setting/warehouse.js:getFrontConfig 按 getCurrentWarehouseId()(ctx.user.store_id,未识别报 400「未识别到当前仓库,无法操作仓库设置」)查询 wms_warehouse_front_config,无记录返回 buildFrontConfigOutput 默认空配置(15 字段:warehouse_id/domain/title/logo_url/favicon_url/login_bg_url/theme/cert_path/key_path/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at/updated_at)", + "app/service/systems/setting/warehouse.js:getFrontConfigByDomain 校验 domain 必填非空(400「domain 不能为空」)且 ≤100 字符(400「domain 长度不能超过 100 字符」);Redis key front:config:domain:{domain},配置命中缓存 TTL 600s(FRONT_CONFIG_PUBLIC_CACHE_TTL_SECONDS),未登记域名写 {configured:false} 空缓存 TTL 60s(FRONT_CONFIG_PUBLIC_MISS_CACHE_TTL_SECONDS)防穿透并返回 404「域名未配置」;响应仅 FRONT_CONFIG_PUBLIC_FIELDS 白名单 6 字段(domain/title/logo_url/login_bg_url/favicon_url/theme),绝不返回 cert_path/key_path/sync_status/sync_attempts/last_sync_error 等内部字段;Redis 读异常降级查库、写异常仅日志", + "app/model/warehouse_front_config.js:wms_warehouse_front_config 单表一仓一行(uk_store_id 唯一、uk_domain 可空列唯一索引允许多 NULL,非空唯一性靠应用层校验),字段含 domain/title/logo_url/favicon_url/login_bg_url/theme/cert_path/key_path/cert_expire_at/sync_status/sync_attempts/last_sync_error/last_synced_at;不启用 paranoid,无 deleted_at", + "数据库迁移:database/migrations/20260907150000-create-wms-warehouse-front-config.js(建表 wms_warehouse_front_config 及索引)、database/migrations/20260907170000-add-favicon-url-to-wms-warehouse-front-config.js(新增 favicon_url 列)", + "methods/system.json:setting.warehouse 分组 list 末尾新增 saveFrontConfig/getFrontConfig 条目(isNeedLogin=true、isNeedAuth=false、Authorization 头);新增 frontConfig 分组(groupName 前端独立部署模块)与 frontConfig.getByDomain 条目(isNeedLogin=false、isNeedAuth=false、headers 为空,免登录免鉴权免权限);docMeta.version 0.3.97 -> 0.3.98,updatedAt 保持 2026-09-07;本变更记录写入 methods/changes/system.json 数组首位", + "README.md / AI_TOOLBOX.md / AI_METHOD_ROUTING.md 无需同步:检索确认无前端独立部署配置相关行为描述(AI_METHOD_ROUTING.md 为函数清单由扫描脚本维护,本任务未执行扫描,如需刷新可另行执行)", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ] + }, + { + "version": "2026.09.07-ai-method-routing-service-inventory-refresh", + "date": "2026-09-07", + "type": "changed", + "summary": "AI_METHOD_ROUTING.md 第 6 节「全量 Service Method 能力清单」按项目维护脚本重新扫描刷新:receiving_entry_match.js 由 12 个函数更新为 27 个(补齐台账/防超扣链路的 _bindReceivingsWithStorageSync、_bindOneReceivingAndSyncStorage、_syncReceivingStorageByEntryItems、_parseLedgerMap、_serializeLedgerMap、_buildLegacyBaselineLedger、_bindingAllocationByStock、_recalcReceivingStorageStatus、_reconcileEntryReceivedQuantity、recordLedgerAllocation、setLedgerAllocation、rollbackEntryOrderBindings、_rollbackOneBindingStorage 等),并同步刷新 workbench.js(52→61)、express_platform.js(16→17)、intercept_auto_confirm.js(新增)等存量漂移条目;本节内容由自动扫描脚本生成,仅函数清单、无接口行为描述。", + "methods": [ + "storage.entry.bindReceiving", + "storage.entry.unbindReceiving", + "storage.entry.cancel", + "storage.entry.commit", + "storage.entry.quickInbound" + ], + "notes": [ + "本记录是对 2026.09.07-entry-receiving-binding-allocated-quantity-ledger 同任务的补充记录:该记录撰写时判定 AI_METHOD_ROUTING.md 无需同步,随后按文件内维护说明执行刷新脚本同步了第 6 节自动扫描清单(本任务涉及 receiving_entry_match.js 新增 13 个台账/防超扣相关方法)", + "刷新方式:node .\\script\\tmp-gen-service-method-inventory.cjs(扫描 app/service/**/*.js 输出 temp/tmp-service-method-inventory.md)→ node .\\script\\tmp-update-ai-method-routing.cjs(注入 AI_METHOD_ROUTING.md 第 6 节 BEGIN/END 标记内),自动生成时间 2026-09-06 → 2026-09-07、文件数 203 → 204", + "生成器按类方法扫描,个别内置标识符(如 max、min、Set、Date、NOW)会被一并列出为方法名,属于既有生成器口径,非手工修改", + "methods/system.json 无实质变化:本次 spec 复用 storage.entry.unbindReceiving 现有条目内容,upsert 为无差异重写;接口行为、参数、响应、错误码均不变", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ], + "module": "storage.entry" + }, + { + "version": "2026.09.07-entry-receiving-binding-allocated-quantity-ledger", + "date": "2026-09-07", + "type": "changed", + "summary": "入库单绑定收货单链路防超扣修复文档同步:wms_entry_order_receiving 新增 allocated_quantity 数量台账列(JSON,收货明细ID→分配数量,迁移 20260907160000 仅基表);storage.entry.bindReceiving COMPLETED 绑定改为台账制归一化分配(每 SKU 分配目标 = min(入库单计划数 − 其他绑定已占用, 收货单剩余可入量),多退少补、旧超分数据回收、重复绑定幂等跳过、软删恢复仅分配剩余量),并同步 entry_items.received_quantity 口径;新增 storage.entry.unbindReceiving 接口文档(解绑按台账回滚 stored_quantity、重算 storage_status、清空台账,响应新增 rolled_back_quantity);storage.entry.cancel 作废回滚改台账制逐绑定回收(不再整体清零共享收货单);storage.entry.commit / storage.entry.quickInbound 分别按覆写/累计语义同步台账。", + "methods": [ + "storage.entry.bindReceiving", + "storage.entry.unbindReceiving", + "storage.entry.cancel", + "storage.entry.commit", + "storage.entry.quickInbound" + ], + "notes": [ + "app/model/entry_order_receiving.js 新增 allocated_quantity 列(JSON 可空,comment 数量台账:收货明细ID→已分配数量(JSON对象,如 {\"123\":8});null 表示旧数据未初始化);数据库迁移 database/migrations/20260907160000-add-allocated-quantity-to-wms-entry-order-receiving.js 仅基表(describeTable 幂等检测)", + "app/service/systems/receiving_entry_match.js _syncReceivingStorageByEntryItems(方案A台账版):FOR UPDATE 行锁入库单主行 + 该入库单全部未删除绑定行 + 绑定收货单明细行,串行化同一入库单的分配事务;每 SKU 分配目标 target = min(max(0, 入库单计划数 − 其他绑定已分配), 当前绑定已分配 + 收货单剩余可入量),多退少补(旧数据超分回收、亏分补分配);明细级结果回写绑定行台账 allocated_quantity,重算收货单主表 storage_status,并经 _reconcileEntryReceivedQuantity 同步 entry_items.received_quantity;返回的 storage_sync.stored_total 仅计补分配量(归一化回收不计入)", + "幂等/恢复语义:绑定已存在且未删除 → skipped(error_code=ALREADY_BOUND,不重复分配);已软删除 → restore 后按归一化目标仅分配剩余量(restored=true);并发唯一索引冲突按已绑定跳过。旧绑定行(台账 null)由 _buildLegacyBaselineLedger 按收货侧累计量兜底重建明细级台账,新链路绑定行台账初始化为 {}(非 null)", + "新增 unbindEntryOrderReceiving(对应 storage.entry.unbindReceiving):仅 CREATED / PENDING 可解绑(COMPLETED / CANCELLED 拒绝),解绑不回退入库单状态;事务内行锁后按台账逐明细回收该收货单 stored_quantity、重算明细与主表 storage_status、台账重置为 {},软删除主表绑定与关联明细绑定(InboundDirectLog status=committed 且 receiving_detail_id 非空的记录);返回 success/failed/success_count/failed_count,success 项含 released_detail_ids / released_detail_count / rolled_back_quantity(本次回滚的 stored_quantity 总量,无可回滚量为 0);不影响同一收货单上其他入库单的占用", + "app/service/systems/storage/entry.js cancel → _rollbackReceivingStorageStatus → rollbackEntryOrderBindings(receivingId=null、softDeleteBinding=false):按台账逐绑定回收、清空台账(绑定行保留)、重算 received_quantity;回滚失败仅日志不阻塞作废主流程;QM 来源入库单作废前先发送奇门取消同步,sync_status=SUCCESS 不可取消", + "app/service/systems/inbound_direct_log.js commit 绑定模式 _syncReceivingStorageStatus → receivingEntryMatch.setLedgerAllocation(按 committed 汇总量覆写台账条目);app/service/systems/storage/entry.js quickInbound _applyReceivingInboundUsage → receivingEntryMatch.recordLedgerAllocation(按本次落到收货明细的分配量累计台账)。说明:receiving_entry_match._commitBinding(PDA 明细绑定)内部调用 recordLedgerAllocation,但当前无调用方(实际 addItem 绑定走 inboundDirectLog._bindReceivingDetail),本次按实际生效链路记录,addItem 文档不改动", + "methods/system.json:storage.entry.bindReceiving 条目 description/storage_sync.stored_total 说明按台账归一化语义更新;新增 storage.entry.unbindReceiving 条目(按脚本规则追加到 storage.entry 组列表末尾);storage.entry.cancel / commit / quickInbound 描述补充台账行为;cancel errors 补充「入库单已完成回传,不可取消」;版本 0.3.96 -> 0.3.97(docMeta.version),updatedAt 保持 2026-09-07", + "README.md / AI_TOOLBOX.md / AI_METHOD_ROUTING.md 检索确认:无本链路行为描述(AI_METHOD_ROUTING.md 仅函数清单,无行为描述),无需同步", + "本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作" + ], + "module": "storage.entry" + }, + { + "version": "2026.09.07-entry-bindReceiving-completed-storage-sync", + "date": "2026-09-07", + "type": "changed", + "summary": "storage.entry.bindReceiving 契约变更:可绑定状态由 CREATED/PENDING 调整为 CREATED/COMPLETED;COMPLETED 绑定在事务内联动同步收货单入库进度(SKU 级累加 stored_quantity、重算明细与主表 storage_status);绑定已存在时幂等跳过不重复累加、软删除恢复后执行同步;返回结构由 success/failed/success_count/failed_count 修正为实际返回的 bound/skipped/summary,并在 COMPLETED 结果中新增 restored 与 storage_sync(含 unmatched_items)。", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "app/service/systems/receiving_entry_match.js bindEntryOrderReceiving:ALLOWED_BIND_STATUSES = [CREATED, COMPLETED],其他状态抛错「入库单状态不允许绑定,当前状态: {status},仅 CREATED、COMPLETED 状态可操作」;收货单校验含 存在未删除、同仓库、同货主、未取消、已审核(is_review)", + "COMPLETED 路径新增 _bindReceivingsWithStorageSync / _bindOneReceivingAndSyncStorage / _syncReceivingStorageByEntryItems:事务内逐收货单主表绑定 + 入库明细按 stock_id(≡ wms_receiving_detail.system_product_id)汇总,FOR UPDATE 行锁后逐明细累加 stored_quantity(上限 actual_quantity),按 stored vs actual 重算明细 storage_status(none/partial/all)并汇总更新收货单主表 storage_status;SKU 未匹配明细汇总进 unmatched_items;任一异常整体回滚", + "幂等语义:绑定已存在且未删除 → skipped(error_code=ALREADY_BOUND,不重复累加);已软删除 → restore 并执行进度同步(restored=true);并发唯一索引冲突 → 按已绑定跳过", + "methods/system.json:storage.entry.bindReceiving 条目 description/errors 按代码更新;response 由 success/failed/success_count/failed_count 修正为实际返回的 flag/code/message/bound/skipped/summary/timestamp(bound 项 CREATED 含 receiving_id/receiving_number/created,COMPLETED 新增 restored 与 storage_sync.stored_total/matched_item_count/unmatched_items;skipped 项 error_code 枚举 ALREADY_BOUND/BINDING_WRITE_FAILED;收货单校验失败不返回明细、仅 summary.skipped_count 计数);错误码同步为实际文案(抛错经 /system 全局异常处理返回 500「接口错误: ...」);版本 0.3.95 -> 0.3.96(docMeta.version),updatedAt 保持 2026-09-07", + "README.md / AI_TOOLBOX.md / AI_METHOD_ROUTING.md 检索确认:无本接口状态规则描述(AI_METHOD_ROUTING.md 仅函数清单,无行为描述),无需同步", + "本次仅同步文档,未修改任何业务代码" + ], + "module": "storage.entry" + }, + { + "version": "2026.09.07-store-openAccount-remove-logo-url-domain", + "date": "2026-09-07", + "type": "changed", + "summary": "storeWarehouse.store.openAccount 入参移除 logo_url、domain 两个可选参数:wms_store 表的 logo_url、domain 字段已废弃(代码写入链路已移除、数据库已执行删列迁移 20260907140000-drop-logo-url-and-domain-from-wms-store),文档同步删除这两个可选 body 入参对象;字段无业务承载,前端若仍传参会被忽略,不破坏响应结构。", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "database/migrations/20260907140000-drop-logo-url-and-domain-from-wms-store.js:删除 wms_store 表的 logo_url、domain 两列(开发库已执行完成)", + "代码写入链路(openAccount 创建货主)已由开发 agent 移除 logo_url、domain 写入,app/ 下无 logo_url 残留引用", + "methods/system.json:storeWarehouse.store.openAccount 的 params 删除 logo_url(name logo_url、type string、required false、source body、description Logo 链接)与 domain(name domain、type string、required false、source body、description 绑定域名)两个可选 body 入参对象;其余 17 个入参、response(store_id/account_id/contract_id/company_name/username/role_id)与 errors 均不变;版本 0.3.94 -> 0.3.95(docMeta.version),updatedAt 保持 2026-09-07", + "影响说明:字段已无业务承载,前端若仍传参会被忽略;响应结构不变,无错误码、鉴权方式、公共请求头变化", + "methods/ 全目录检索确认:logo_url、Logo 链接、绑定域名 仅存在于 methods/system.json 本方法参数块,无其他文件或方法残留引用", + "本次仅同步文档,未修改任何代码、迁移脚本或数据库" + ], + "module": "storeWarehouse.store" + }, + { + "version": "2026.09.07-order-delivery-dispatch-dispath-time", + "date": "2026-09-07", + "type": "changed", + "summary": "配送表 wms_order_delivery_{wh}_dispatch 新增 dispath_time 字段(DATETIME 可空无默认值,comment 订单迁移进配送表的时间),用于记录订单从待处理表迁移进配送表的时刻:模型 dispatch 分支新增字段定义,出库迁移 buildDispatchRow 写入 new Date(),迁移脚本覆盖全部配送分表;仅配送表独有(基表/current/history/outsourced 不涉及),无接口入参/响应结构变化。", + "methods": [ + "order.manualOutboundOrder" + ], + "notes": [ + "database/migrations/20260907120000-add-dispath-time-to-order-delivery-dispatch.js:为库内全部配送分表 wms_order_delivery_{wh}_dispatch 增加 dispath_time 列(DATETIME 可空无默认值,comment 订单迁移进配送表的时间),仅配送表独有、不加基表/current/history/outsourced 分表;describeTable 幂等检测,列已存在则跳过;开发、生产均已执行。", + "app/model/order_delivery_table_schema.js buildTableAttributes:dispatch 分支新增 dispath_time 字段定义(Sequelize DATE / allowNull=true / comment 订单迁移进配送表的时间),与既有 dispatch_lane 并列,仅 dispatch 分表生效。", + "app/service/systems/order_delivery_migration.js buildDispatchRow:写入配送表行时追加 dispath_time = new Date()(订单迁移进配送表的时刻),源表数据不受影响;保留先删除源行 dispatch_lane、再统一写 DISPATCH_LANE 的既有逻辑。", + "methods/system.json:order.manualOutboundOrder description 补充「迁移写入配送表的订单行记录 dispath_time(buildDispatchRow 写入 new Date(),仅配送表独有)」说明;errors 由 description 键规范化为 message 键(文案不变,满足更新脚本 schema);版本 0.3.93 -> 0.3.94(docMeta.version),updatedAt 更新为 2026-09-07。", + "无接口入参/响应结构/错误码/鉴权变化;配送表整行 raw 响应(order.pendingOrder.detail 订单头、order.list 列表行等)文档均为 raw 行引用而非全量字段清单,按既有口径不硬加字段说明,仅在本变更记录体现。", + "AI_METHOD_ROUTING.md(函数清单,无配送表字段清单章节)与 AI_TOOLBOX.md(无配送表字段相关内容)均无需同步;README.md 与 docs/*.md 亦无配送表字段清单章节。", + "发布版本 v1.0.0-20260907164410-c5150bc(2026-09-07 发布);本次仅同步文档,未修改任何代码、迁移脚本或数据库。" + ], + "module": "order.index" + }, + { + "version": "2026.09.06-workbench-resetLoginCode-reset-token", + "date": "2026-09-06", + "type": "changed", + "summary": "workbench.resetLoginCode 行为变更:重置登录码时同步重置工作台 token。生成新 64 位 hex token 与 login_code 一并持久化到 wms_workbench(record.update({ login_code, token }));更新库前先删除旧 workbench:token:{旧token} 缓存,旧 token 随即失效;立即回填新 token 信息缓存(复用 buildWorkbenchTokenInfo,含 members/current_wave/current_orders,TTL 300s);返回值新增 token 字段 { id, login_code, token },出口层展开后响应顶层含 id、login_code、token;旧行为「token 不变」相关描述已更新。旧 token 失效后旧会话返回 403,设备端需用新 token 继续工作。", + "methods": [ + "workbench.resetLoginCode" + ], + "notes": [ + "app/service/systems/workbench.js:resetLoginCode(id) 同步重置 token:generateUniqueWorkbenchLoginCode 生成新 login_code、generateWorkbenchToken 生成新 64 位 hex token,先 delCacheAsync 删除旧 workbench:token:{旧token} 缓存(旧 token 随即失效),再 record.update({ login_code, token }) 一并持久化,随后 setCacheAsync 立即回填新 token 信息缓存(buildWorkbenchTokenInfo,含 members/current_wave/current_orders,TTL 300s),返回 { id, login_code, token }", + "app/service/systemMethods/workbench.js:resetLoginCode 薄出口 this.success('重置成功', result) 展开后响应顶层含 id、login_code、token(原仅 id/login_code,本次新增 token)", + "methods/system.json:workbench.resetLoginCode 条目 description 更新(说明 login_code 与 token 同步重置、旧 token 缓存删除使旧 token 随即失效、立即回填新 token 缓存),response 新增 token 字段(string,64 位 hex,必返回),errors 补充 403 备注(旧 token 失效后旧会话返回 403,设备端需用新 token 继续工作);版本 0.3.92 -> 0.3.93(docMeta.version),updatedAt 保持 2026-09-06", + "AI_METHOD_ROUTING.md:路由与方法清单无变化(5.3 节映射表与函数清单均未涉及行为描述),无需同步", + "本次任务仅同步文档,未修改任何业务代码" + ], + "module": "workbench" + }, + { + "version": "2026.09.06-workbench-queryOrder", + "date": "2026-09-06", + "type": "changed", + "summary": "工作台模块新增免登录/免权限/免鉴权的 token 自校验只读接口 workbench.queryOrder(条码查询订单):入参 token(必填)+ barcode(必填),仓库与工作台均由服务端从 token 解析注入(body 传入 warehouse_id/workbench_id 一律忽略,禁止前端传值,防止跨仓库查单);响应 data 与 business(queryOrder) 分支一致(barcode/waybill_code/isSandan/store_remark/express/order/items/source_table,散单 order 附 intercept_flag/pack_flag 0/1 标志、团购附 batch 波次总量信息);只读查询不涉及缓存失效;错误码沿用统一口径:无 token 401、token 无效 403、工作台未绑定有效仓库 403,条码为空/未找到运单/未找到订单为业务失败(flag=failure、code=0)。", + "methods": [ + "workbench.queryOrder" + ], + "notes": [ + "app/service/systemMethods/workbench.js:新增 queryOrder 薄出口(调用业务层 queryOrderByToken),systemInit 免登录/免权限/免鉴权白名单均已包含 queryOrder(未声明免日志,保留系统日志)", + "app/service/systems/workbench.js:新增 queryOrderByToken(data):走 resolveWorkbenchContext(token) 统一 token 校验(无 token 401、token 无效 403),解析成功后从 ctx.workbenchWarehouseId 注入仓库(工作台未绑定有效仓库返回 403),复用 _queryOrder 业务实现;只读查询,不涉及缓存失效", + "methods/system.json:工作台模块新增 workbench.queryOrder 条目(isNeedAuth=false、isNeedLogin=false、isNeedRight=false,入参仅 token/barcode,description 说明 warehouse_id/workbench_id 由服务端注入);版本 0.3.91 -> 0.3.92(docMeta.version),updatedAt 保持 2026-09-06", + "AI_METHOD_ROUTING.md 5.3 节新增 queryOrder 映射行与接口说明;本次任务仅同步文档,未修改任何业务代码" + ], + "module": "workbench" + }, + { + "version": "2026.09.06-workbench-pack-order-finish-pack-send-weight", + "date": "2026-09-06", + "type": "changed", + "summary": "工作台模块新增 3 个免登录/免权限/免鉴权的 token 自校验接口 workbench.packOrder(打包上报)、workbench.finishPack(打包完成)、workbench.sendWeight(称重上报,重量单位克),并统一公共 token 校验口径:新增 resolveWorkbenchContext(token) 公共校验方法(解析成功写入 ctx.workbenchToken/ctx.workbenchId/ctx.workbenchWarehouseId),无 token 统一返回 code=401(消息「工作台 token 不能为空」)、token 无效/工作台不存在保持 403;受影响的 workbench.getWorkbenchInfo/workbench.bindMember/workbench.removeMember 三个接口「无 token」错误码由 400 调整为 401,bindMember/removeMember 校验顺序变为 token 优先(token 无效且参数缺失的边界场景由 400 变 403)。", + "methods": [ + "workbench.packOrder", + "workbench.finishPack", + "workbench.sendWeight", + "workbench.getWorkbenchInfo", + "workbench.bindMember", + "workbench.removeMember" + ], + "notes": [ + "app/service/systemMethods/workbench.js:新增 packOrder/finishPack/sendWeight 三个薄出口(调用业务层 packOrderByToken/finishPackByToken/sendWeightByToken),systemInit 免登录/免权限/免鉴权白名单均已包含三个方法(未声明免日志,保留系统日志)", + "app/service/systems/workbench.js:新增公共 token 校验方法 resolveWorkbenchContext(token):无 token 统一返回 401(消息「工作台 token 不能为空」),token 无效/工作台不存在(含软删除)返回 403(保持原口径);解析成功后写入 ctx.workbenchToken/ctx.workbenchId/ctx.workbenchWarehouseId 供后续方法使用(按仓库限定查询/写入,禁止跨仓库)", + "新增 packOrderByToken/finishPackByToken/sendWeightByToken:仓库/工作台均由 token 解析上下文注入(body 传入 warehouse_id/workbench_id 被忽略),复用 _packOrder/_finishPack/_sendWeight 业务实现;打包/称重状态变更后失效对应工作台 token 缓存,保证 getWorkbenchInfo 及时返回最新信息", + "行为变更:workbench.getWorkbenchInfo/workbench.bindMember/workbench.removeMember 无 token 时错误码由 400 调整为 401;bindMember/removeMember 校验顺序变为 token 优先(token 无效且参数缺失的边界场景由 400 变 403)", + "methods/system.json:工作台模块新增 workbench.packOrder/workbench.finishPack/workbench.sendWeight 三条目(isNeedAuth=false、isNeedLogin=false、isNeedRight=false),并更新 workbench.getWorkbenchInfo/workbench.bindMember/workbench.removeMember 错误码(400→401);版本 0.3.90 -> 0.3.91(docMeta.version),updatedAt 保持 2026-09-06", + "AI_METHOD_ROUTING.md 5.3 节新增三个接口映射行与 401 口径说明;本次任务仅同步文档,未修改任何业务代码" + ], + "module": "workbench" + }, + { + "version": "2026.09.06-workbench-getWorkbenchInfo-wave-items-total", + "date": "2026-09-06", + "type": "changed", + "summary": "workbench.getWorkbenchInfo 响应 data.current_wave 新增 items_total 字段(number):波次商品总件数,口径为商品总件数(非 SKU 品种数),来源为订单分表 wms_order_delivery_{仓库}_{current/dispatch} 的 items_total 列按 wave_id+warehouse_id 求和(与既有 order_count 同款分表口径),带 15s 短缓存兜底;current_wave 其余字段(task_id/wave_id/wave_no/status/order_count/operator_text/start_time)不变,无团购任务时 current_wave 仍为空对象;items_total 随 token 缓存 workbench:token:{token}(TTL 300s)一并缓存,packOrder/finishPack 打包状态变更后主动失效缓存,下一次调用即返回最新数据。", + "methods": [ + "workbench.getWorkbenchInfo" + ], + "notes": [ + "app/service/systems/workbench.js:新增 _sumWaveItemsTotal(并发遍历 current+dispatch 分表 SUM(items_total),按 wave_id+warehouse_id 过滤,单表失败按 0 处理)与 _sumWaveItemsTotalCached(cache:workbench:wave_items_total:{warehouseId}:{waveId},TTL 15s,缓存不可用降级实时统计);buildCurrentPackingInfo 组装 current_wave 时通过 Promise.all 并行统计 order_count 与 items_total,current_wave 新增 items_total 字段", + "getWorkbenchInfoByToken 缓存优先(workbench:token:{token},TTL 300s),缓存值已包含 items_total;_packOrder/_finishPack 打包状态变更后调用 invalidateWorkbenchTokenCacheByWorkbenchId 删除 token 缓存,保证下一次 getWorkbenchInfo 返回最新打包信息", + "methods/system.json:workbench.getWorkbenchInfo description 与 current_wave 对象描述补充 items_total 说明,response 新增 current_wave.items_total 条目(沿用 current_wave.xxx 嵌套命名惯例);版本 0.3.89 -> 0.3.90(docMeta.version),updatedAt 保持 2026-09-06", + "AI_METHOD_ROUTING.md 5.3 节接口文档行追加本变更记录版本号,当前打包信息行补充 items_total 口径;AI_TOOLBOX.md 无 workbench 相关内容,无需同步", + "本次任务仅同步文档,未修改任何业务代码" + ], + "module": "workbench" + }, + { + "version": "2026.09.06-workbench-getWorkbenchInfo-current-packing", + "date": "2026-09-06", + "type": "changed", + "summary": "workbench.getWorkbenchInfo 响应 data 新增当前正在打包的波次与订单信息:current_wave(当前正在打包的团购波次:wms_pack_task 中 pack_mode=2 且 wave_id>0 的最新一条未结束任务(status<2)组装,无团购任务时为空对象,含 task_id/wave_id/wave_no/status/order_count/operator_text/start_time,order_count 为 15s 短缓存实时计数)与 current_orders(当前正在打包的订单数组:全部未结束任务按 id 倒序,逐单按 current→dispatch 分表补发货单号,无进行中任务时为空数组,每项含 task_id/order_id/delivery_order_code/wave_id/wave_no/pack_mode/status/pack_quantity/operator_text/start_time);打包信息随 token 缓存 workbench:token:{token}(TTL 300s)一并缓存,packOrder/finishPack 打包状态变更后主动失效缓存,下一次调用即返回最新数据;打包信息查询异常时降级(current_wave 空对象、current_orders 空数组),不影响主信息与 members。", + "methods": [ + "workbench.getWorkbenchInfo" + ], + "notes": [ + "app/service/systems/workbench.js:新增 listCurrentPackTasks(wms_pack_task 按 workbench_id/warehouse_id 过滤 status<2(0=待处理/1=打包中),按 id 倒序)与 buildCurrentPackingInfo(组装 current_wave/current_orders:逐单按 current→dispatch 分表补 delivery_order_code;current_wave 取最新一条 pack_mode=2 且 wave_id>0 的未结束任务,order_count 走 _countWaveOrdersCached 实时计数 + 15s 短缓存;任一环节异常降级为空对象/空数组);buildWorkbenchTokenInfo 统一组装主表字段 + members + 打包信息", + "getWorkbenchInfoByToken 缓存优先(workbench:token:{token},TTL 300s),缓存值同样含打包信息;_packOrder/_finishPack(workbench.business packOrder/finishPack 调度)打包状态变更后调用 invalidateWorkbenchTokenCacheByWorkbenchId 删除 token 缓存,保证下一次 getWorkbenchInfo 返回最新打包中信息", + "methods/system.json:workbench.getWorkbenchInfo description 补充 current_wave/current_orders 与缓存失效行为说明,response 新增 current_wave/current_wave.* 与 current_orders/current_orders[].* 条目;版本 0.3.88 -> 0.3.89(docMeta.version),updatedAt 保持 2026-09-06", + "AI_METHOD_ROUTING.md 5.3 节接口文档行追加本变更记录版本号;AI_TOOLBOX.md 无 workbench 相关内容,无需同步", + "本次任务仅同步文档,未修改任何业务代码" + ], + "module": "workbench" + }, + { + "version": "2026.09.06-workbench-getWorkbenchInfo-members", + "date": "2026-09-06", + "type": "changed", + "summary": "workbench.getWorkbenchInfo 响应 data 新增 members 成员数组:成员来自副表 wms_workbench_member 未软删除记录(按 id ASC),元素含 id/user_id/user_name(轻量结构);接口 token 缓存 workbench:token:{token}(TTL 300s)缓存值已包含 members,绑定/移除成员后缓存立即失效,下一次调用即返回最新成员;主表字段与不含 token/login_code 口径不变。", + "methods": [ + "workbench.getWorkbenchInfo" + ], + "notes": [ + "app/service/systems/workbench.js:buildWorkbenchTokenInfo 统一组装主表字段(formatWorkbenchTokenInfo:id/warehouse_id/name/status/type/remark/device_ids/created_at/updated_at,不含 token/login_code)+ members(listWorkbenchMembers 查 wms_workbench_member 未软删除记录,attributes id/user_id/user_name,按 id ASC;查询失败降级空数组)", + "getWorkbenchInfoByToken 缓存优先(workbench:token:{token},TTL 300s)、查库兜底回填缓存;removeWorkbenchMember/bindWorkbenchMember 成功后 delCacheAsync 清除 token 信息缓存,保证下一次调用立即反映最新成员", + "methods/system.json:workbench.getWorkbenchInfo description 补充 members 与缓存行为说明,response 新增 members/members[].id/members[].user_id/members[].user_name 条目;版本 0.3.87 -> 0.3.88(docMeta.version),updatedAt 保持 2026-09-06", + "AI_METHOD_ROUTING.md 5.3 节接口文档行追加本变更记录版本号;AI_TOOLBOX.md 无 workbench 相关内容,无需同步", + "本次任务仅同步文档,未修改任何业务代码" + ], + "module": "workbench" + }, + { + "version": "2026.09.06-index.queryUserByToken", + "date": "2026-09-06", + "type": "added", + "summary": "基础模块新增 index.queryUserByToken:按 ye4s 登录临时码 token 查询用户信息(免登录、免鉴权),命中返回 flag=success、code=200 与 real_name、wms_account_id,未命中返回 code=404 用户不存在,数据库异常返回 code=500。", + "methods": [ + "index.queryUserByToken" + ], + "notes": [ + "app/service/systemMethods/index.js 新增 queryUserByToken:入参 token(ye4s 登录临时码,对应 ye4s 库 ye4s_user 表 tmp_code 字段),为空返回 code 400「token 不能为空」;命中返回 success + real_name(空串兜底)/wms_account_id(null 兜底),未命中返回 code 404「用户不存在」,异常返回 code 500", + "免登录、免鉴权:queryUserByToken 已加入 _noNeedLogin / _noNeedAuth 白名单(systemInit 声明)", + "methods/system.json:基础模块(module=index)新增 index.queryUserByToken 条目(isNeedAuth=false、isNeedLogin=false);版本 0.3.86 -> 0.3.87(docMeta.version),updatedAt 保持 2026-09-06", + "本次任务仅同步文档,未修改任何业务代码" + ], + "module": "index" + }, + { + "version": "2026.09.06-recheckOrder.remove-unprinted-intercepted", + "date": "2026-09-06", + "type": "enhanced", + "summary": "复核链路新增自动清理:更新复核状态后,自动将波次内「已拦截且未打印」的订单移除出波次(回池),拦截解除后可重新抓取发货,避免拦截订单卡死波次完成判定。", + "methods": [ + "order.recheckOrder.confirmRecheck", + "order.recheckOrder.batchQuickRecheck", + "order.recheckOrder.batchQuickRecheckByWave" + ], + "notes": [ + "app/service/systemMethods/order/recheckOrder.js 新增 removeUnprintedInterceptedOrdersFromWave:移除波次内 print_status='none' 且 intercept_status!='none'(空值按 none 处理)的订单(wave_id=0、wave_no/wave_strategy_version/wave_scan_result 清空),调用 wave.deleteOrderWaveIndexByOrderIds 删波次索引,删除 wms_wave_pick_task_order 任务订单关联,回写 wms_wave_batch total_orders/processed_orders 统计,写 ORDER_WAVE_REMOVE 操作日志,并触发 enqueueWaveStrategyQuickScanPostOrderChange 波次策略快扫(拦截未解除时策略仍排除,不会误抓)", + "三个复核入口接入:updateTaskOrderReviewAndTryUnbindCart(confirmRecheck 单订单)、updateTaskOrdersReviewBatch(批量/团购)、_updateTaskOrderReviewInTransaction(batchQuickRecheck/batchQuickRecheckByWave 事务版,清理动作随事务执行并透传事务对象);清理失败仅记录 warn 日志,不影响复核主流程", + "清理先于任务/波次完成判定执行,拦截订单移除后完成判定口径自然收敛,未改动既有完成判定 SQL;清理以 wave_id>0 为条件,幂等可重复触发", + "已打印(print_status!='none')的拦截订单保持不动,避免已贴面单实物与波次记录分离;该类订单仍需人工 wave.batchRemoveOrders 处理", + "单元测试:test/app/service/systemMethods/order/recheckOrder.removeUnprintedIntercepted.test.js(8 用例全通过,ESLint 0/0)" + ], + "module": "order.recheckOrder" + }, + { + "version": "2026.09.06-stock.report.exportStore-lock-exclusion", + "date": "2026-09-06", + "type": "updated", + "summary": "stock.report.exportStore(货主侧库存报表导出)变更记录口径收紧:变更记录 sheet 只导出出入库流水(INBOUND/OUTBOUND),锁定/解锁(LOCK/UNLOCK)记录一律不导出;export_mode/exportMode 参数对货主侧不再有任何效果(该参数仅仓库侧 stock.report.export 生效)。", + "methods": [ + "stock.report.exportStore", + "stock.report.export" + ], + "notes": [ + "app/service/systems/storage/report.js export():isStoreMode(货主侧)分支固定追加 t.transaction_type NOT IN ('LOCK','UNLOCK'),无视 exportMode;仓库侧维持 export_mode='item' 时含 LOCK、否则排除 LOCK 的既有行为", + "methods/system.json:stock.report.exportStore 移除 export_mode/exportMode 参数条目,method description 补充“变更记录只含出入库流水(LOCK/UNLOCK 不导出)”与“export_mode/exportMode 不支持也不生效”;stock.report.export 的 export_mode 参数描述标注“仅仓库侧接口生效”,method description 补充“仓库侧”;版本 0.3.85 -> 0.3.86(docMeta.version),updatedAt 保持 2026-09-06", + "本次任务仅同步文档,未修改任何业务代码" + ], + "module": "stock.report" + }, + { + "version": "2026.09.06-order.list.waveScope", + "date": "2026-09-06", + "type": "updated", + "summary": "order.list 订单列表 where 新增 wave_scope 波次范围虚拟筛选字段(订单表 wave_scope 字段直接过滤)", + "methods": [ + "order.list" + ], + "notes": [ + "订单表(wms_order_delivery 与各仓库 current/history/dispatch/outsourced 分表)新增 wave_scope 字段:tinyint NOT NULL DEFAULT 0,取值 0=未分配波次 1=大团购 2=散单 3=小团购 4=单品单件。", + "波次生成写入订单表时同步维护 wave_scope(app/service/systemMethods/order/wave.js resolveWaveScopeByWaveMeta):大团购=wave_type=1&source=0,小团购=wave_type=1&source=2,单品单件=wave_type=2&pickMode=2(策略 batch_mode=1),其余有波次为散单;移出波次重置为 0。", + "order.list / 订单导出 where.wave_scope 直接按订单表 wave_scope 字段过滤(app/service/systemMethods/order/base.js buildWaveScopeFilterCondition),不再反查 wms_wave_batch 波次ID;支持单个值、数组多选与 { operator: in, value: [...] } 结构,非法值(非 0-4 整数)返回 400。", + "数据库迁移:database/migrations/20260905100000-add-wave-scope-to-order-delivery.js(加列)、database/migrations/20260905130000-backfill-order-wave-scope.js(存量按口径回填,幂等)。", + "列表响应 raw 行暂不输出 wave_scope 字段(ORDER_LIST_BASE_ATTRIBUTES 未包含),仅作为筛选条件使用。" + ], + "module": "order" + }, + { + "version": "2026.09.05-storageTransaction-list-detail", + "date": "2026-09-05", + "summary": "storage.transaction.list 实现纠正:原实现错误查询 wms_stock_transaction 并按商品+单据类型聚合(合并模式),现改为查询 wms_storage_transaction 的逐条流水明细(与 stock.transaction.list 形态一致:裸 SQL 列白名单 + COUNT 分页 + 排序白名单)。聚合查询移除后,生产单仓库 160 万行聚合慢查询(约 9s)不复存在;明细查询实测 COUNT 约 0.2s。", + "methods": [ + "storage.transaction.list" + ], + "notes": [ + "代码变更:systems/stock_transaction.js list() 由 ORM 聚合查询重写为 wms_storage_transaction 裸 SQL 逐条明细(列白名单含 storage_id/space_id/inventory_type/source_order_codes/before/after_intercept_locked_quantity,LEFT JOIN wms_stock_warehouse 返回 stockItem);systemMethods/storage/transaction.js 解构 whereValue 逐字段传参,warehouse_id 由服务端从 ctx.user.store_id 注入。", + "行为变更:group_by_batch 参数废弃,恒返回逐条明细;原合并模式响应(quantity 合计/first_created_at/last_created_at/record_count)不再返回。", + "where 支持字段:transaction_type、stock_id/stock_ids、space_id、store_id/store_ids、order_type、order_no(模糊)、batch_no、inventory_type、operator_name(模糊)、order_id、created_at(between)与 start_time/end_time;keyword 支持顶层或 where 内。", + "排序白名单:created_at、quantity、stock_id、store_id、warehouse_id、space_id,非法回退 created_at DESC;pageSize 上限 200。", + "前端调用方需按逐条明细结构适配(原合并模式渲染逻辑作废)。" + ] + }, + { + "version": "2026.09.04-storage.entry.quickInbound-noneed-notice", + "date": "2026-09-04", + "type": "enhanced", + "summary": "storage.entry.quickInbound 新增参数 noNeedNotice(默认 0):0 时快捷直入完成后通知货主,1 时跳过通知,通知失败仍不影响入库主流程。", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "app/service/systemMethods/storage/entry.js:quickInbound 解析 data.noNeedNotice(默认 0)并透传底层 quickInbound({ id, noNeedNotice })", + "app/service/systems/storage/entry.js:quickInbound(data) 解析 data.noNeedNotice(Number 归一化),事务提交后仅当 noNeedNotice !== 1 时调用 notifyEntryOrderCompleted", + "methods/system.json:storage.entry.quickInbound 新增 noNeedNotice 参数说明与 description 补充;版本 0.3.83 -> 0.3.84(docMeta.version),updatedAt 保持 2026-09-04", + "无数据库 schema 变更,未执行任何写库操作" + ], + "module": "storage.entry" + }, + { + "version": "2026.09.04-storage.entry.commit-noneed-notice", + "date": "2026-09-04", + "type": "enhanced", + "summary": "storage.entry.commit 新增参数 noNeedNotice(默认 0):0 时入库完成后通知货主,1 时跳过通知,通知失败仍不影响入库主流程。", + "methods": [ + "storage.entry.commit" + ], + "notes": [ + "app/service/systemMethods/storage/entry.js:commit 解析 data.noNeedNotice(默认 0)并透传底层 inboundDirectLog.commit(entry_order_id, noNeedNotice)", + "app/service/systems/inbound_direct_log.js:commit(entryOrderId, noNeedNotice = 0),事务提交后仅当 Number(noNeedNotice) !== 1 时调用 notifyEntryOrderCompleted(字符串 '1' 也兼容)", + "methods/system.json:storage.entry.commit 新增 noNeedNotice 参数说明与 description 补充;版本 0.3.82 -> 0.3.83(docMeta.version),updatedAt 保持 2026-09-04", + "无数据库 schema 变更,未执行任何写库操作" + ], + "module": "storage.entry" + }, + { + "version": "2026.09.04-stock.report.export-stock-id-fix", + "date": "2026-09-04", + "type": "fixed", + "summary": "修复 stock.report.export(含 search/searchStore/exportStore)where.stock_id 传数组时导出空白的问题:单数 stock_id 现兼容数组,避免被再包裹一层导致嵌套数组归一化为 NaN 全量过滤;同时修复默认分页上线后导出内部 search 被截断为第一页 20 条导致汇总/明细缺数据的回归。", + "methods": [ + "stock.report.search", + "stock.report.searchStore", + "stock.report.export", + "stock.report.exportStore" + ], + "notes": [ + "根因:where.stock_id 传数组时 systemMethods 层 [ stockIdRaw ] 再包一层形成嵌套数组,systems 层 Number(嵌套数组)=NaN 被全部过滤 → 汇总空 → 导出空白", + "app/service/systemMethods/stock/report.js:search/searchStore/export/exportStore 四处 stock_id 解析兼容数组(Array.isArray ? 原样 : 包单元素)", + "app/service/systems/storage/report.js:search 中 stockIds 归一化改用 flat() 防御嵌套;export 内部调用 search 显式传全量分页 { page: 1, pageSize: 1000000 }(新增常量 EXPORT_FULL_PAGE_SIZE),避免默认分页截断", + "methods/system.json:search/searchStore 的 stock_id 描述补充“兼容数组”;export/exportStore 的 where 描述补充 stock_id/stock_ids/keyword,export 新增 export_mode 参数说明;版本 0.3.81 -> 0.3.82(docMeta.version),updatedAt 保持 2026-09-04", + "验证:开发库 where.stock_id 传 20 个 ID 的 search 返回 20 行;export 同条件任务成功并产出 832KB Excel(非空白);无数据库 schema 变更,未执行任何写库操作" + ], + "module": "stock.report" + }, + { + "version": "2026.09.04-stock.report.search-sort-fields", + "date": "2026-09-04", + "type": "enhanced", + "summary": "stock.report.search 排序白名单扩充:新增 stock_id、item_code、item_name(与 begin_total、inbound_total、outbound_total、end_total 共 7 个字段),item_code/item_name 按字典序、其余按数值排序,与其他列表页面的 sort.sortField/sortOrder 用法保持一致。", + "methods": [ + "stock.report.search", + "stock.report.searchStore", + "stock.report.export", + "stock.report.exportStore" + ], + "notes": [ + "app/service/systems/storage/report.js:SORT_FIELD_WHITE_LIST 扩充为 7 字段;新增 STRING_SORT_FIELD_SET(item_code/item_name 字典序比较,localeCompare),其余字段数值比较;by_space=false 分支 baseStockRows 查询新增 sw.item_code/sw.item_name,groupedList 行携带(供排序与展示回退);by_space=true 分支 baseStorageRows LEFT JOIN wms_stock_warehouse sw ON sw.id=s.stock_id 取 MAX(sw.item_code)/MAX(sw.item_name);两分支最终 item_name/item_code 展示优先 getStockDetails,回退快照值", + "app/service/systemMethods/stock/report.js:search JSDoc 同步白名单", + "methods/system.json:search/searchStore/export/exportStore 的 sort 参数描述同步新白名单;版本 0.3.80 -> 0.3.81(docMeta.version),updatedAt 更新为 2026-09-04", + "无数据库 schema 变更,未执行任何写库操作" + ], + "module": "stock.report" + }, + { + "version": "2026.09.03-stock.report.search-default-pagination", + "date": "2026-09-03", + "type": "updated", + "summary": "stock.report.search 分页改为默认生效:不传 data.pagination 或传非法分页时,默认按 page=1、pageSize=20 返回第一页,响应始终携带 data.pagination 分页信息(原为未传时全量返回)。分页参数同时支持顶层 page/pageSize/page_size(与其他 list 接口一致,顶层值优先)。", + "methods": [ + "stock.report.search" + ], + "notes": [ + "app/service/systems/storage/report.js:paginateList 改为默认分页语义(未传/非法回退 page=1、pageSize=20,新增模块常量 DEFAULT_PAGE_SIZE=20);两个输出分支(by_space=false/true)响应 data.pagination 恒返回;200 空列表 early return 同步携带 pagination 元信息(total=0)", + "app/service/systemMethods/stock/report.js:search 分页参数解析与其他 list 一致——data.pagination 优先,兼容顶层 data.page 与 data.pageSize / data.page_size(顶层值覆盖 pagination 对象);searchStore(货主侧)暂不支持分页,行为不变", + "methods/system.json:pagination 参数与 data.list/data.pagination 响应描述更新为默认分页语义,data.pagination required 改为 true,新增 page/pageSize 顶层兼容参数条目;版本 0.3.78 -> 0.3.80(docMeta.version),updatedAt 保持 2026-09-03", + "无数据库 schema 变更,未执行任何写库操作" + ], + "module": "stock.report" + }, + { + "version": "2026.09.03-stock.report.search-pagination", + "date": "2026-09-03", + "type": "enhanced", + "summary": "stock.report.search 新增分页支持:请求体 data.pagination = { page, pageSize } 时,先按现有排序规则排序再切片,仅对当前页行加载名称信息,响应 data.pagination 返回分页元信息;未传或非法分页保持全量返回(向后兼容)。", + "methods": [ + "stock.report.search" + ], + "notes": [ + "app/service/systems/storage/report.js:新增模块函数 paginateList(归一化 page/pageSize,非法/未传返回 null 表示不分页);search 方法新增 pagination 入参,两个输出分支(by_space=false/true)均改为 sortReportList 先排序 → paginateList 切片 → 仅对 pageItems 加载名称信息(getStockDetails/Store/LocationSpace 只查当前页),分页时响应 data.pagination = { page, pageSize, total, totalPages, hasPrevious, hasNext }", + "app/service/systemMethods/stock/report.js:search 透传 data.pagination(JSDoc 同步);searchStore(货主侧)暂不支持分页", + "性能背景:生产实测全仓 33353 SKU 无分页约 4.6~8.8s,其中 getStockDetails 名称加载为耗时大头;分页后仅当前页触发缓存/DB 查询", + "methods/system.json:stock.report.search 新增 pagination/pagination.page/pagination.pageSize 参数与 data.pagination 响应字段;版本 0.3.77 -> 0.3.78(docMeta.version),updatedAt 保持 2026-09-03", + "无数据库 schema 变更,未执行任何写库操作" + ], + "module": "stock.report" + }, + { + "version": "2026.09.03-workbench-barcode-removed", + "date": "2026-09-03", + "type": "removed", + "summary": "下线工作台条码 barcode 相关字段(未使用):wms_workbench 删除 barcode 列及 idx_barcode、uk_warehouse_barcode 索引;workbench.list 移除 barcode 筛选与列表项、workbench.create/update 不再接收 barcode;workbench.checkBarcode 接口整体移除(方法、权限白名单、文档条目同步删除);order.packing.list / order.packing.detail 响应移除 workbench_barcode 字段(源列已删,恒为 null 无意义)。", + "methods": [ + "workbench.list", + "workbench.create", + "workbench.update", + "workbench.getWorkbenchInfo", + "workbench.checkBarcode", + "order.packing.list", + "order.packing.detail" + ], + "notes": [ + "database/migrations/20260903180000-remove-barcode-from-wms-workbench.js:先删 uk_warehouse_barcode、idx_barcode 索引再删 barcode 列(幂等 describeTable/showIndex 判断),up/down 对称(down 恢复列与索引),已在开发库执行并验证(wms_workbench 现为 12 列)", + "app/model/workbench.js:移除 barcode 字段定义与 idx_barcode、uk_warehouse_barcode 索引声明", + "app/service/systems/workbench.js:list 移除 where.barcode 筛选;create/update 移除 barcode 处理;删除 checkBarcodeExists;formatWorkbenchTokenInfo 移除 barcode 输出", + "app/service/systemMethods/workbench.js:删除 checkBarcode 方法,systemInit 免权限/免日志/免鉴权白名单移除 checkBarcode", + "app/service/systems/order_packing.js:list/detail 扁平化输出移除 workbench_barcode 字段", + "methods/system.json:工作台模块删除 workbench.checkBarcode 条目、list/create/update/getWorkbenchInfo 条目按无 barcode 形态重写;订单打包模块 order.packing.list / order.packing.detail description 移除 workbench_barcode 说明;版本 0.3.76 -> 0.3.77(docMeta.version),updatedAt 保持 2026-09-03", + "本次未执行任何直接 DDL/写库操作;仅通过迁移文件在开发库(127.0.0.1:3307)执行 schema 变更并验证;生产库迁移需发布时按标准流程执行" + ], + "module": "workbench" + }, + { + "version": "2026.09.03-workbench-member-bind", + "date": "2026-09-03", + "type": "enhanced", + "summary": "新增接口 workbench.bindMember(免登录、免鉴权):入参用户ID(可为空,兼容非系统账号用户)+ 姓名(必填非空)+ 工作台 token,按 token 解析工作台后在 wms_workbench_member 副表新增成员行(user_id 空时仅存 user_name 姓名快照),返回新建成员行(id/workbench_id/user_id/user_name);token 无效返回失败 code=403。与已上线的 workbench.removeMember 构成成员增删闭环。", + "methods": [ + "workbench.bindMember" + ], + "notes": [ + "app/service/systems/workbench.js:新增 bindWorkbenchMember(token 校验 → 姓名必填校验 → 用户ID归一化(空/非正整数处理)→ resolveWorkbenchByToken 解析工作台 → WorkbenchMember.create),复用既有 resolveWorkbenchByToken 缓存优先逻辑", + "app/service/systemMethods/workbench.js:新增 bindMember 薄出口,systemInit 免登录/免权限/免日志/免鉴权声明补充 bindMember", + "methods/system.json:工作台模块新增 workbench.bindMember 条目;版本 0.3.75 -> 0.3.76(docMeta.version),updatedAt 保持 2026-09-03", + "无数据库 schema 变更(复用 wms_workbench_member 表),未执行任何写库操作" + ], + "module": "workbench" + }, + { + "version": "2026.09.03-workbench-member-remove", + "date": "2026-09-03", + "type": "enhanced", + "summary": "工作台新增成员/用户登录副表 wms_workbench_member(id/workbench_id/user_id/user_name/created_at/updated_at/deleted_at,user_id 允许为空以兼容非系统账号用户,user_name 存名称快照;索引 idx_workbench_id/idx_user_id)。新增接口 workbench.removeMember(免登录、免鉴权):入参成员行 ids 与工作台 token,按 token 解析工作台后仅软删除归属于该工作台的成员行,返回 removed 数量与 ids 列表;token 无效返回失败 code=403,无可移除成员返回 code=404。", + "methods": [ + "workbench.removeMember" + ], + "notes": [ + "database/migrations/20260903150000-create-wms-workbench-member.js:创建 wms_workbench_member 表(幂等 showAllTables 判断)+ idx_workbench_id/idx_user_id 索引,up/down 对称,已在开发库执行并验证(user_id 列 IS_NULLABLE=YES)", + "app/model/workbench_member.js:新增 WorkbenchMember 模型(paranoid 软删除),associate 声明 belongsTo Workbench(as workbench)与 belongsTo Account(as user)", + "app/model/workbench.js:associate 新增 Workbench.hasMany(WorkbenchMember, as members)", + "app/service/systems/workbench.js:新增 resolveWorkbenchByToken(缓存 workbench:token:{token} 优先、查库兜底并回填缓存)、normalizeWorkbenchMemberIds(数组/单值/逗号串,去重仅正整数)、removeWorkbenchMember(token 解析工作台后软删除归属成员行)", + "app/service/systemMethods/workbench.js:新增 removeMember 薄出口,systemInit 免登录/免权限/免日志/免鉴权声明补充 removeMember", + "methods/system.json:工作台模块新增 workbench.removeMember 条目;版本 0.3.74 -> 0.3.75(docMeta.version),updatedAt 保持 2026-09-03", + "本次未执行任何直接 DDL/写库操作;仅通过迁移文件在开发库(127.0.0.1:3307)执行 schema 变更并验证表结构;生产库迁移需发布时按标准流程执行" + ], + "module": "workbench" + }, + { + "version": "2026.09.03-workbench-login-code-token", + "date": "2026-09-03", + "type": "enhanced", + "summary": "工作台登录码/令牌与绑定登录能力:wms_workbench 新增 token、login_code 两个字段(VARCHAR(64),login_code 前缀 wblc + 随机段共 64 位、全局唯一;token 随机 64 位)。新增 5 个接口:index.getWorkbenchBindCode(免登录免鉴权,参考 user.getLoginWechatCode:返回 client_code 并在缓存生成绑定码,传入 client_code 时长轮询等待绑定完成返回 token,超时/缓存失效重新生成绑定码后才返回数据)、workbench.bind(需登录需权限:校验缓存绑定码 + 工作台ID 关联绑定,成功后写入随机 token,旧 workbench:token:{token} 缓存删除)、workbench.getWorkbenchInfo(免登录免鉴权:token 查缓存 workbench:token:{token},未命中查库,无信息返回失败 code=403)、index.LoginWorkbenchByCode(免登录免鉴权:wms_workbench.login_code 入参换取 token,无匹配返回失败 code=403)、workbench.resetLoginCode(需登录需权限:随机重置 login_code)。workbench.list 返回 login_code(不返回 token),workbench.update 不受理 login_code 传入,workbench.create 自动创建 login_code。", + "methods": [ + "index.getWorkbenchBindCode", + "index.LoginWorkbenchByCode", + "workbench.bind", + "workbench.getWorkbenchInfo", + "workbench.resetLoginCode", + "workbench.list", + "workbench.create", + "workbench.update" + ], + "notes": [ + "database/migrations/20260903100000-add-login-code-token-to-wms-workbench.js:新增 login_code/token 两列(幂等 describeTable 判断)+ uk_login_code 唯一索引 + idx_token 索引,up/down 对称,已在开发库执行并验证", + "app/model/workbench.js:新增 login_code/token 字段定义与 uk_login_code/idx_token 索引声明", + "app/service/systems/workbench.js:新增绑定码/令牌能力(getWorkbenchBindCode/bindWorkbench/getWorkbenchInfoByToken/loginWorkbenchByCode/resetLoginCode 与配套缓存/生成/轮询辅助方法);list/detail 排除 token;create 自动生成唯一 login_code;update 白名单不含 login_code/token(传入不受理);缓存 key:workbench:bind:client:{clientCode}、workbench:bind:code:{code}(TTL 120s)、workbench:token:{token}(TTL 300s);长轮询 60s、每秒轮询缓存状态", + "app/service/systemMethods/workbench.js:新增 bind/getWorkbenchInfo/resetLoginCode 薄出口,systemInit 免登录/免权限/免鉴权/免日志声明补充 getWorkbenchInfo(bind/resetLoginCode 走默认需登录需权限)", + "app/service/systemMethods/index.js:新增 getWorkbenchBindCode/LoginWorkbenchByCode 薄出口,systemInit 免登录/免权限/免鉴权声明补充两方法(_noNeedLog 本就为 *)", + "403 口径:/system 网关不支持方法内设置 HTTP 状态码,按现有惯例(stock/warehouse.js 同款)返回 flag=failure、code=403 业务失败", + "methods/system.json:工作台模块新增 workbench.bind / workbench.getWorkbenchInfo / workbench.resetLoginCode 条目并更新 list/create/update 条目(list 响应补 login_code);基础模块新增 index.getWorkbenchBindCode / index.LoginWorkbenchByCode 条目;版本 0.3.73 -> 0.3.74(docMeta.version),updatedAt 保持 2026-09-03", + "本次未执行任何直接 DDL/写库操作;仅通过迁移文件在开发库(127.0.0.1:3307)执行 schema 变更并验证列与索引;生产库迁移需发布时按标准流程执行" + ], + "module": "workbench" + }, + { + "version": "2026.09.03-receiving-store-name-enrich", + "date": "2026-09-03", + "type": "changed", + "summary": "storage.receiving.getReceivingList / getReceivingDetail 货主名称实时解析:列表每项与详情主单的 store_name 不再只依赖主表快照(约 26% 历史数据快照为空),改为优先取合约表 wms_store_warehouse.store_remask(货主备注名称,按 store_id + warehouse_id 维度),无合约或备注为空时回退 wms_store.company_name(公司全称),均无时保留主表快照(可能为空字符串)。", + "methods": [ + "storage.receiving.getReceivingList", + "storage.receiving.getReceivingDetail" + ], + "notes": [ + "app/service/systems/storage/receiving.js 新增 _resolveReceivingStoreNameMap(storeIds, warehouseId):批量解析货主名称映射——先查 wms_store_warehouse(store_id IN + warehouse_id)取 store_remask,再查 wms_store 取 company_name 兑底,返回 Map;口径与 afterSale._enrichListStoreNames / inventory.store_name 一致(store_remask 优先、company_name 兑底)", + "app/service/systems/storage/receiving.js getReceivingList:拉取列表后批量调用 _resolveReceivingStoreNameMap,processedData 每项 store_name = 实时解析值 || 主表快照 || ''(实时值优先,兼容未绑定货主的存量数据)", + "app/service/systems/storage/receiving.js getReceivingDetail:查到主单后按 receiving.store_id + receiving.warehouse_id 实时解析货主名称,解析有值时覆盖 receiving.store_name(否则保留快照)", + "methods/system.json 收货单模块(module=storage_receiving):getReceivingList description 补充列表项 store_name 实时解析口径;getReceivingDetail 响应新增 receiving.store_name 字段描述;版本 0.3.72 -> 0.3.73(docMeta.version),updatedAt 保持 2026-09-03", + "AI_METHOD_ROUTING.md / AI_TOOLBOX.md 本次未同步:两者仅登记服务方法名清单,不含字段级描述,无需改动", + "本次仅查询验证(wms_receiving 共 1238 条、store_name 为空 319 条、store_id 为空 317 条;抽检 store_id=1000000 可经 store_remask='测试货主' 解析),未执行任何数据库写操作/DDL/Redis 操作;业务代码已通过 ESLint" + ], + "module": "storage.receiving" + }, + { + "version": "2026.09.03-policy-allocate-start-time-cross-day", + "date": "2026-09-03", + "type": "enhanced", + "summary": "货主策略与仓库级设置新增「开始自动分配时间」allocate_start_time(默认 08:00),支持跨天窗口:截单时间作为最后允许时间,开始时间晚于截单时间时截单时间视为次日;当前时间早于开始自动分配时间与超过截单时间行为一致(不自动分配快递/储位、不自动加团)。保存时开始时间等于截单时间(自动分配窗口为空)报 400。", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields", + "storeWarehouse.store.savePolicyConfig", + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "app/model/store_warehouse.js POLICY_CONFIG_FIELDS 新增 allocate_start_time(名称:开始自动分配时间,type string,default 08:00,min 00:00,max 23:59,maxLength 5);cutoff_order_time 的 min 从 12:00 放开为 00:00(支持凌晨截单/跨天窗口);cutoff_order_enabled/cutoff_order_time 描述补充跨天语义;normalizePolicyConfig 保存路径(sanitizeOnly=false)新增跨字段校验:allocate_start_time 与 cutoff_order_time 相同时抛错「policy_config.allocate_start_time 不能等于 policy_config.cutoff_order_time(自动分配窗口为空)」(400),读取路径(sanitizeOnly=true)不校验", + "app/model/store.js DEFAULT_SUBJECT_CONFIG 新增 allocate_start_time: '08:00';CUTOFF_ORDER_TIME_MIN 放开为 00:00;normalizeSubjectConfig 新增 HH:mm 格式校验(非法抛「subject_config.allocate_start_time 格式必须为 HH:mm(如 08:00)」)与相等校验(显式同时提交两个时间字段且相等时抛错),旧数据读取自动补默认 08:00", + "app/service/systems/setting/warehouse.js WAREHOUSE_SETTING_FIELDS 新增 allocate_start_time 字段元信息(default 08:00,min 00:00,max 23:59);cutoff_order_time 的 min 放开为 00:00;getFieldMeta 自动返回新字段元信息", + "app/service/systems/delivery_order.js resolveCutoffOrderConfig 返回值新增 allocateStartTime(默认 08:00,货主-仓库级优先、仓库级兜底);新增 isAllocationWindowClosed(allocateStartTimeStr, cutoffTimeStr, nowDate):同天窗口(start=cutoff 禁止;跨天窗口(start>cutoff,截单视为次日)now in [cutoff,start) 禁止;start==cutoff 防御性全天禁止;asyncProcessOrderCreated 用 isAllocationBlocked 替换 isCutoffActive 控制自动分配快递/储位/自动加团,日志补充 allocateStartTime/cutoffTime", + "methods/system.json:storeWarehouse.store.getPolicyConfigFields response 从空数组补充字段元信息说明(data[]、data[].allocate_start_time、data[].cutoff_order_time、data[].cutoff_order_enabled);storeWarehouse.store.savePolicyConfig params 补充 policy_config.cutoff_order_enabled/cutoff_order_time/allocate_start_time 字段文档与 400 错误说明,response 补充 data.policy_config.allocate_start_time;setting.warehouse.getSettings response 与 setting.warehouse.saveSettings params 补充 subject_config.allocate_start_time/subject_config.cutoff_order_time 字段文档(getFieldMeta 为通用字段元信息结构,无逐字段清单,无需改动);版本 0.3.71 -> 0.3.72(docMeta.version),updatedAt 更新为 2026-09-03", + "本次仅文档同步(业务代码由 wms-dev-agent 完成:新增字段、跨天窗口判定、保存校验,并已通过 ESLint 与单元测试),未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "storeWarehouse.store" + }, + { + "version": "2026.09.02-order-packing-list-perf-export", + "date": "2026-09-02", + "type": "changed", + "summary": "order.packing.list 慢查询优化 + 新增导出与进度查询接口:list 查询将 findAndCountAll 拆分为 count(不带 include)+ findAll(带 include),避免 count 生成 COUNT(DISTINCT)+双 LEFT JOIN(生产实测 520ms,拆分后 count 走单表索引约 44ms);筛选/排序逻辑提取为 _buildListWhere/_buildListOrder 供列表与导出复用。新增 order.packing.export(提交异步导出任务,入参 where/sort 语义与 list 一致,warehouse_id 由服务端注入;后台生成单 Sheet Excel「打包任务列表」并上传 COS)与 order.packing.exportTaskProgress(按 task_id 查询进度与下载链接)。两接口免权限免日志免鉴权(与 order.export 口径一致,无 wms_permission 记录),需登录。", + "methods": [ + "order.packing.list", + "order.packing.export", + "order.packing.exportTaskProgress" + ], + "notes": [ + "app/service/systems/order_packing.js:list 查询拆分——findAndCountAll 改为 count({where})(不带 include)+ findAll({where, include, limit, offset}),修复 hasMany include(videos/expresses)导致 count 生成 COUNT(DISTINCT)+双 LEFT JOIN 的慢查询(生产实测 520ms → 44ms);where 构建逻辑(status/pack_mode/waybill_code/wave_no/order_id/workbench_id/quickWhere/has_video/video_enable/时间范围)原样提取为 _buildListWhere(list/export 共用),排序提取为 _buildListOrder(list/export 共用);新增 createBusinessError 与 exportPackTask", + "app/service/systems/order_packing.js exportPackTask:复用 _buildListWhere/_buildListOrder 并强制 warehouse_id(缺失抛 400 缺少仓库上下文);主表全量分页拉取(每页 500,无行数上限);批量关联工作台(wms_workbench)、视频(wms_pack_task_video,含 camera 名称)、运单(wms_order_express,按 order_id 分批 100);ExcelJS 流式单 Sheet「打包任务列表」18 列(任务ID/订单ID/波次号/运单号/关联运单号/打包模式/任务状态/打包数量/商品总数量/商品种类数/工作台/作业人员/开始打包时间/结束打包时间/创建时间/视频状态/录像可用/备注),经 systems.upload.uploadFile 上传(key=exports/pack_task/{warehouseId}/{timestamp}_{token}.xlsx,mimetype xlsx,category=document),结果含 filename/fileKey/url/cdnUrl/cosUrl/current_count/total_count/sheet_count", + "app/service/systemMethods/order/packing.js:新增 export/exportTaskProgress 与任务缓存辅助方法(generateExportTaskId/normalizeExportTaskId/getExportTaskCacheKey/setExportTaskProgress/getExportTaskProgress):缓存键前缀 packing_export_task_,Redis TTL 1800 秒;export 提交后 setImmediate 异步执行并逐阶段回写进度(submitted(0) → running(5) → 数据拉取 10~30(未命中数据时 85)→ 关联拉取 30~55 → Excel 55~90 → 上传 92 → success(100),失败 failed + error);exportTaskProgress 入参兼容 task_id/taskId,download_url 从 result.url/cdnUrl/cosUrl/fileKey 兜底取,未命中返回 status=not_found(正常响应非报错)", + "systemInit 权限声明:_noNeedRight/_noNeedLog/_noNeedAuth 由 'list,get' 扩展为 'list,get,export,exportTaskProgress'(导出异步任务免权限免日志免鉴权,与 order.export 口径一致);_noNeedLogin 不变", + "methods/system.json order.packing 模块:新增 order.packing.export 与 order.packing.exportTaskProgress 两个 method 条目(追加于 order.packing.list 之后),版本 0.3.70 -> 0.3.71(docMeta.version),updatedAt 更新为 2026-09-02", + "本次未修改 wms_pack_task 表结构,未执行数据库写操作/Redis 操作;未运行测试" + ], + "module": "order.packing" + }, + { + "version": "2026.09.01-report-delivery-notify-group-routing-fix", + "date": "2026-09-01", + "type": "changed", + "summary": "修复「补货预警报表定时投递群路由」缺陷(G1):生产上 3 条投递计划发出 5 条消息——报表文件消息被投递到投递计划未配置的「货主默认站内信群」(如 store-1000156 的收货群、store-1000159 的对接群被误发)。根因:deliverByChannel 未按计划配置解析群目标,按 group_type='store' 取任意货主默认群(与 notify_group_ids 配置无关)。修复:新增 resolveNotifyGroups 统一解析(过滤 is_blocked=1、软删、仓库维度一致)供投递与通知两路共用;配置了 notify_group_ids 的计划文件消息仅逐群投递到配置群,全部不可达(不存在/已删除/被屏蔽/仓库不一致)时抛错进入 failed 退避重试、不再回退未配置群;未配置通知群的历史计划保持旧行为回退货主默认站内信群;sendNotifyIfConfigured 复用 resolveNotifyGroups 删除重复查询逻辑。响应结构不变,仅群路由语义变更。", + "methods": [ + "report.deliveryPlan.save", + "report.deliveryPlan.list", + "report.deliveryPlan.copy" + ], + "notes": [ + "app/service/systems/reportDelivery.js 新增 resolveNotifyGroups({plan, warehouseId}):notify_group_ids → 有效群行统一解析(is_blocked=0、软删自动排除、warehouse_id 维度一致),投递(deliverByChannel)与文本通知(sendNotifyIfConfigured)两路共用,保证口径一致;未配置群或全部被过滤时返回空数组,InboxGroup 模型不可用时抛错", + "app/service/systems/reportDelivery.js deliverByChannel 群路由改造:计划配置 notify_group_ids 时报表文件消息只逐群投递到配置群,不再投递任意「货主默认群」(旧逻辑为 group_type='store' 按 id ASC 取最早一条,与计划配置无关);配置了群但全部不可达(不存在/已删除/被屏蔽/仓库不一致)时抛「货主 配置的通知群不可达…无法投递」进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s),不再静默回退到未配置群;未配置通知群的历史计划保持旧行为回退到货主默认站内信群(group_type='store',取最早一条)兼容存量计划", + "app/service/systems/reportDelivery.js sendNotifyIfConfigured 复用 resolveNotifyGroups 解析通知群,删除重复查询逻辑,投递与通知共用同一解析口径", + "methods/system.json 通用报表模块(module=report):report.deliveryPlan.save description 与 params/response 的 notify_group_ids 描述补充群路由口径(文件消息仅投递计划配置群、未配置回退货主默认站内信群、配置群全部不可达失败退避);report.deliveryPlan.list description 与 response 的 notify_group_ids 描述同步;report.deliveryPlan.copy description 补充复制计划通知群置空后投递回退目标货主默认站内信群语义;请求/响应结构、headers、errors 均不变;版本 0.3.69 -> 0.3.70(docMeta.version),updatedAt 保持 2026-09-01", + "docs/report-config-guide.md 第 5 节补充文件消息投递目标/群路由口径(配置群定向投递、未配置回退默认群、全部不可达失败退避),第 5.1.2 节 notify_group_ids 补充同时作为文件消息投递目标的说明", + "测试回归:140 测试全过(业务代码由开发任务完成并测试通过);本次仅文档同步,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.09.01-returnReceived.export", + "date": "2026-09-01", + "type": "added", + "summary": "退回收到模块新增导出与进度查询接口:returnReceived.export(提交异步导出任务,入参 where/sort 语义与 returnReceived.list 一致,warehouse_id 由服务端注入 ctx.user.store_id;后台生成单 Sheet Excel「退回收到登记列表」并上传 COS)与 returnReceived.exportTaskProgress(按 task_id 查询任务进度与下载链接,未命中返回 status=not_found)。任务缓存 Redis TTL 30 分钟,全量分页拉取 500/页;两接口默认走 API 权限校验(需 wms_permission 存在类型为 api 的记录),需登录。", + "methods": [ + "returnReceived.export", + "returnReceived.exportTaskProgress" + ], + "notes": [ + "app/service/systemMethods/returnReceived.js 新增 export/exportTaskProgress 与任务缓存辅助方法(generateExportTaskId/normalizeExportTaskId/getExportTaskCacheKey/setExportTaskProgress/getExportTaskProgress):缓存键前缀 return_received_export_task_,Redis TTL 1800 秒(30 分钟);export 提交后 setImmediate 异步执行并逐阶段回写进度(submitted(0) → running(5) → 数据拉取 10~55(未命中数据时 85)→ Excel 生成 60 → success(100),失败 failed + error);exportTaskProgress 入参兼容 task_id/taskId,download_url 从 result.url/cdnUrl/cosUrl/fileKey 兜底取;task_id 为空或缓存未命中返回 status=not_found(正常响应非报错)", + "systemInit 权限声明:_noNeedRight 仅 detail(export/exportTaskProgress 未加入免权限列表,默认走 API 权限校验,需 wms_permission 存在 returnReceived.export / returnReceived.exportTaskProgress 类型为 api 的记录);_noNeedLogin 为空(两接口均需登录,isNeedAuth=true、isNeedLogin=true);_noNeedLog 为空(记录操作日志);_noNeedAuth 为空(走仓库有效期检查)", + "app/service/systems/return_received.js 新增 exportList/_generateExportExcel/_resolveStoreRemarkMap:复用 _buildListWhere/_buildListOrder(与 list 语义一致)并强制 warehouse_id=注入值(缺失抛 400 缺少仓库上下文);主表全量分页拉取(每页 500,无行数上限);货主备注批量解析(wms_store_warehouse.store_remask,失败降级空字符串不阻断导出)", + "导出 Excel:单 Sheet「退回收到登记列表」,列=运单号/扫描日期/扫描人员/是否原单退回(是/否)/订单ID/货主备注/备注/登记时间/更新时间;ExcelJS 流式写入临时文件后经 systems.upload.uploadFile 上传(key=exports/return_received/{warehouseId}/{timestamp}_{token}.xlsx,mimetype xlsx,category=document),结果含 filename/fileKey/url/cdnUrl/cosUrl/current_count/total_count", + "methods/system.json 退回收到模块(module=returnReceived)新增 returnReceived.export 与 returnReceived.exportTaskProgress 两个 method 条目(追加于 returnReceived.delete 之后),版本 0.3.68 -> 0.3.69(docMeta.version),updatedAt 保持 2026-09-01", + "AI_METHOD_ROUTING.md 同步:app/service/systemMethods/returnReceived.js 方法计数 (5) -> (7),方法清单补充 export/exportTaskProgress;AI_TOOLBOX.md 未涉及 returnReceived 清单,无需改动", + "本次仅文档同步(业务代码由开发任务完成),未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "returnReceived" + }, + { + "version": "2026.09.01-intercept-locked-quantity-rework", + "date": "2026-09-01", + "type": "changed", + "summary": "库内拦截确认时库存不再归还可用、改移入拦截锁定字段的改造落地:wms_storage_transaction 新增 before_intercept_locked_quantity / after_intercept_locked_quantity 两个拦截锁定快照字段(migration 20260901000200,尚未上线);wms_storage 可用数量统一口径 available_quantity = quantity - locked_quantity - intercept_locked_quantity;拦截相关流水新增 order_type=INTERCEPT_LOCK(拦截锁迁移/实物返还并拦截锁定)与 INTERCEPT_UNLOCK(拦截锁释放回落可用);stock.warehouse.search(with_stock)与 stock.warehouse.getStockDetail 按库位合并明细响应新增 intercept_locked_quantity 字段(向后兼容);order.recheckOrder.confirmIntercept / interceptScan 确认拦截时以拦截模式释放储位分配(interceptMode=true,库存不归还可用、移入拦截锁定)。", + "methods": [ + "stock.warehouse.getStockDetail", + "stock.warehouse.search", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.interceptScan" + ], + "notes": [ + "database/migrations/20260901000200-add-intercept-locked-snapshots-to-wms-storage-transaction.js:describeTable 幂等检测,新增 before_intercept_locked_quantity / after_intercept_locked_quantity(INT NULL,comment 变更前/后拦截锁定数量,与既有 before/after_locked_quantity 风格一致、可空无默认值、由写入逻辑维护);该 migration 尚未上线", + "app/model/storage_transaction.js:在 after_locked_quantity 之后新增 before_intercept_locked_quantity / after_intercept_locked_quantity 字段定义(INTEGER(12)/allowNull=true,comment 变更前/变更后拦截锁定数量)", + "app/service/systems/storage/index.js updateQuantity:新增 options.interceptLockedChange 变化量参数,统一重算 available_quantity = quantity - locked_quantity - intercept_locked_quantity,并校验拦截锁定数量非负、不超过库存数量、与锁定数量之和不超过库存数量;新增 interceptLockQuantity(作业锁迁移为拦截锁:locked -q、intercept +q、available 不变)/ interceptReceiveQuantity(实物返还并拦截锁定:quantity +q、intercept +q、available 不变)/ interceptUnlockQuantity(拦截锁释放回落可用:intercept -q、available +q)三个专用方法", + "app/service/systems/order_storage_allocation.js cancelAllocateStorage:新增 interceptMode 开关——拦截确认模式下 pending 行执行作业锁迁移(locked -q、intercept +q、available 不变)、fin 行实物返还并拦截锁定(quantity +q、intercept +q、available 不变),流水 order_type 记为 INTERCEPT_LOCK 并记录 order_id 与 before/after_intercept_locked_quantity 快照;普通取消模式行为不变;新增 releaseInterceptLocksByOrderIds:按 INTERCEPT_LOCK 与 INTERCEPT_UNLOCK 流水按 (storage_id, order_id) 汇总净拦截量,净量大于 0 时逐库存行调用 interceptUnlockQuantity 释放拦截锁(intercept -q、available +q),写入 order_type=INTERCEPT_UNLOCK 流水并记录快照,重复调用幂等(净量归零后不再释放)", + "app/service/systemMethods/order/recheckOrder.js confirmIntercept/interceptScan:释放储位分配改走 cancelAllocateStorage({ order_ids, interceptMode: true }),确认拦截时库存不再归还可用而是移入拦截锁定字段 intercept_locked_quantity;运单标记、订单状态、订单锁、工单、日志等其余口径不变", + "app/service/systemMethods/order/pendingOrder.js runBatchUninterceptTask:解除拦截不操作拦截锁定数量字段(业务上拦截→取消拦截均不动库存口径,拦截锁定数量仅在库内拦截确定时占用,回落由后续特定入库处理链路接管)", + "app/service/systems/return_received.js create:退货登记不释放拦截锁定库存(拦截锁回落由退货货物后续入库处理接管)", + "app/service/systems/stock_store.js search(with_stock)与 getStockDetail:storage 查询 attributes 显式加入 intercept_locked_quantity,按库位合并模式累加拦截锁定数量并按统一口径重算 available_quantity;合并明细响应新增 intercept_locked_quantity(向后兼容,默认 0)", + "methods/system.json 同步:stock.warehouse.getStockDetail response storageList 描述补充 intercept_locked_quantity 与 available_quantity 统一口径;stock.warehouse.search response storage 字段的库位分组汇总(children_grouped)与批次明细(children_batch)字段清单均新增 intercept_locked_quantity、available_quantity 口径说明更新为 quantity - locked_quantity - intercept_locked_quantity;order.recheckOrder.confirmIntercept / interceptScan 描述更新为拦截模式释放储位分配(库存不归还可用、移入拦截锁定);版本 0.3.67 -> 0.3.68(docMeta.version),updatedAt 保持 2026-09-01", + "核查结论:methods/qimen.json 与 methods/openapi.json 无涉及本改造的接口(openapi.json 仅 order.cancel 描述中出现 intercept_status 字面量,与本改造无关),未同步;stock.transaction.list / stock.transaction.storeList / stock.transaction.export 使用显式 SQL 列白名单(不含拦截锁定快照字段),响应不受影响,文档无需同步;storage.transaction.list(group_by_batch=true)明细模式因模型整行序列化隐含新增 before/after_intercept_locked_quantity,但其 response 文档为对象结构(更新脚本要求数组格式,与既有处理一致),本次未改写,其 list_detail 示例本非全量字段清单", + "本次仅文档同步,未修改 app/ 与 database/ 下任何代码与 migration,未执行数据库/Redis 操作,未运行测试" + ], + "module": "storage" + }, + { + "version": "2026.09.01-receiving-detail-stock-id", + "date": "2026-09-01", + "type": "changed", + "summary": "storage.receiving.getReceivingDetail 与 deleteDetail 明细项新增 stock_id 字段(与 system_product_id 语义一致,向后兼容)", + "methods": [ + "storage.receiving.getReceivingDetail", + "storage.receiving.deleteDetail" + ], + "notes": [ + "app/service/systems/storage/receiving.js getReceivingDetail:明细组装时新增 stock_id: detailBase.system_product_id ?? null(商品/库存ID,语义与 system_product_id 一致,缺失时为 null),system_product_id 保留向后兼容", + "app/service/systems/storage/receiving.js deleteDetail:删除后剩余明细 formattedDetails 每项同步新增 stock_id = detailData.system_product_id ?? null,与 getReceivingDetail 明细项字段保持一致", + "methods/system.json 收货单模块(module=storage_receiving):getReceivingDetail 响应新增 receiving.details.*.stock_id(number|null,语义与 system_product_id 一致,取 system_product_id、缺失为 null,system_product_id 保留向后兼容);deleteDetail 响应 data.details 描述补充 stock_id 说明;deleteDetail 按更新脚本规范补齐 response 各字段 required、errors 的 description 归一化为 message(语义不变);版本 0.3.66 -> 0.3.67(docMeta.version),updatedAt 保持 2026-09-01", + "AI_METHOD_ROUTING.md / AI_TOOLBOX.md 本次未同步:两者仅登记服务方法名清单,不含 getReceivingDetail/deleteDetail 的字段级描述,无需改动", + "本次仅文档同步(业务代码由 wms-dev-agent 完成),未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "storage.receiving" + }, + { + "version": "2026.09.01-wms-storage-intercept-locked-quantity", + "date": "2026-09-01", + "type": "changed", + "summary": "wms_storage 库存表新增「拦截锁定数量」字段 intercept_locked_quantity(INTEGER(12) NOT NULL DEFAULT 0,comment 拦截锁定数量),用于拦截场景数量锁定、与 locked_quantity 区分;纯数据模型变更:无接口入参/错误码/鉴权变化,现有写入点由模型默认值 0 兜底;明细模式接口响应因模型整行序列化隐含新增该字段(当前恒为 0,暂无业务读写)。", + "methods": [ + "storage.inventory.listByStockId" + ], + "notes": [ + "database/migrations/20260901000000-add-intercept-locked-quantity-to-wms-storage.js:describeTable 幂等检测,缺省时 ALTER TABLE wms_storage ADD COLUMN intercept_locked_quantity INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量';down 删除该字段", + "app/model/storage.js:在 locked_quantity 之后新增 intercept_locked_quantity 字段定义(INTEGER(12)/allowNull=false/defaultValue=0/comment 拦截锁定数量);现有写入点(quickPutaway/directPutaway/commit 等)不显式传该字段,依赖模型默认值 0 兜底", + "methods/system.json storage.inventory.listByStockId:data.list 明细行字段清单补充 intercept_locked_quantity(拦截锁定数量,默认 0);group_by_space=true 汇总行与 params/errors/isNeedAuth/isNeedLogin 均不变;版本 0.3.65 -> 0.3.66(docMeta.version),updatedAt 更新为 2026-09-01", + "storage.inventory.list(group_by_batch=true 明细模式)响应同样隐含新增该字段,但其 response 文档为对象结构(脚本校验要求数组格式),本次未改写;其 list_detail 示例本非全量字段清单(未列 is_enabled/delete_at/supplier_id 等),不构成文档缺口", + "storage.inventory.export(明细/汇总导出)、stock.warehouse.getStockDetail、库存报表 stockFlow 等查询均使用显式 attributes 白名单,不受该字段影响,文档无需同步", + "本次仅文档同步,未修改 app/ 与 database/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "storage" + }, + { + "version": "2026.08.31-report-stockflow-export-columns-restructure", + "date": "2026-08-31", + "type": "changed", + "summary": "stockFlow 报表(库存变化以及补货报表)导出列结构调整:静态字段清单由 16 个顶层字段收敛为 9 组列(顺序固定:item_name 产品名称 / barcode 条码 / item_code 外部编码 / daily 每日出入库(children ck/rk) / pending_occupy 待处理订单占用数 / available 可用库存 / ck_total 7日总出库数量 / suggest 推荐采购量 / warn 是否触发预警);item_code 复用为外部编码列(key 不变、label 由「商品编码」改为「外部编码」,取值优先 wms_stock_store.item_code 按 stock_id 关联、回落 wms_stock_warehouse.item_code);新增 pending_occupy(取 wms_stock_warehouse.locked_quantity,非 wms_storage 聚合口径);移除 stock_id/rk_total/total/pending/locked/ck_avg/rk_avg/stock_days 共 8 个旧列不再导出(rk_total/日均/预计可售天数等仍内部计算供 suggest/warn 判定与复核,不进入导出列)。", + "methods": [ + "report.definition.typeList" + ], + "notes": [ + "app/service/systems/report/queries/sevenDayStockFlow.js:FIELDS 静态字段清单由 16 个顶层字段收敛为 9 组列(item_name/barcode/item_code(asText=true)/daily(children ck/rk)/pending_occupy/available/ck_total/suggest(computed=true)/warn(computed=true),顺序固定),item_code 复用旧「商品编码」key、label 改为「外部编码」;头部口径注释同步重写(外部编码优先 wms_stock_store.item_code 按 stock_id 关联 wms_stock_warehouse.id、同 stock_id 多条按 id 升序取第一条非空、stock_id 为空不参与匹配,未匹配回落 wms_stock_warehouse.item_code,再无留空;pending_occupy 取 wms_stock_warehouse.locked_quantity;出入库仍用 wms_stock_transaction 变更数量 quantity;内部仍计算 rk_total/ck_avg/rk_avg/stock_days 供 suggest/warn 判定与复核,不进入导出列)", + "app/service/systems/report/queries/index.js:注册表 stockFlow 类型 description 已随查询器口径更新为「…每日出/入库、外部编码、待处理订单占用数、可用库存、7日总出库数量、推荐采购量与是否触发预警」;fields 动态取自查询器 fields 常量,无需单独维护", + "methods/system.json 通用报表模块(module=report):report.definition.typeList response 的 fields 描述由「含 16 个字段」更新为「共 9 组列,顺序固定」,fields[].label 示例由「商品编码」更新为「外部编码」;description/params/headers/errors/isNeedAuth/isNeedLogin 不变;版本 0.3.64 -> 0.3.65(docMeta.version),updatedAt 保持 2026-08-31", + "docs/report-config-guide.md:第 2 节 stockFlow 全量字段清单表由 16 个顶层字段改写为 9 组列(新顺序/新 label/新 key,附 pending_occupy 口径与外部编码 fallback 口径、8 个旧列移除说明);第 2.1 节口径与假设按查询器头部注释重写(外部编码口径、待处理订单占用数口径、内部计算字段不导出);第 3 节 asText 适用对象改为「条码、外部编码」;第 6 节保存示例 fields 更新为 9 组列、勾选说明由「16 个顶层字段」改为「9 组列」;第 7.3 节 typeList 响应示例字段顺序与 label 同步(外部编码/推荐采购量/是否触发预警)", + "AI_METHOD_ROUTING.md 本次未同步(report 能力清单不含 stockFlow 字段列表,仅指向 docs/report-config-guide.md,无需改动)", + "本次仅文档同步(业务代码由开发完成),未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试;测试数据保留不清理" + ], + "module": "report" + }, + { + "version": "2026.08.31-report-generate-store-dimension-file-key", + "date": "2026-08-31", + "type": "changed", + "summary": "修复「货主限制不符」缺陷(报表文件 key 与投递/通知幂等键补充货主维度隔离):systems/report.generate 上传目录由 exports/report/{report_id} 改为 exports/report/{report_id}/store-{store_id}(storeId 有效时)/ warehouse-{warehouse_id}(storeId 缺省且 warehouseId 有效时)/ common(两者均缺省,手动导出兼容兜底),避免不同货主的报表文件在 COS 上互相覆盖;reportDelivery 投递幂等键由 report:{report_definition_id}:{biz_date}:{time_point} 改为 report:{store_id}:{report_definition_id}:{biz_date}:{time_point}、文本通知幂等键 report:notify:... 同步加入 store_id 维度,并在 processOne 增加 store_id/report_definition_id 强校验(任一无效拒绝生成跨货主报表)。", + "methods": [ + "report.generate" + ], + "notes": [ + "app/service/systems/report.js generate:新增 ownerSegment 计算——normalizedStoreId>0 时 store-{storeId},否则 normalizedWarehouseId>0 时 warehouse-{warehouseId},否则 common;dir 由 exports/report/{reportId} 改为 exports/report/{reportId}/{ownerSegment}(经 excel.generateAndUpload 追加 {YYYYMMDD} 日期目录与文件名),JSDoc 同步更新隔离语义", + "app/service/systems/reportDelivery.js deliverByChannel:投递幂等键 idempotentKey 加入 store_id 维度(report:{store_id}:{report_definition_id}:{biz_date}:{time_point}),ext_id 幂等复用口径不变,不同货主的投递消息互不复用/串扰;sendNotifyIfConfigured:文本通知幂等键 report:notify:{store_id}:{report_definition_id}:{biz_date}:{time_point} 同步加入 store_id 维度;processOne:新增 store_id/report_definition_id 强校验(任一无效抛「投递计划维度非法(…),拒绝生成报表」),uniqueWhere 与 generate/投递调用统一使用归一化后的 normalizedStoreId/normalizedReportId", + "methods/system.json 通用报表模块(module=report):report.generate description 补充上传目录按(报表定义 + 货主/仓库)隔离口径与 common 兜底、免权限说明移除已下线的 meta(仅 generate/generateTaskProgress 免权限);store_id/storeId 参数描述补货主维度隔离语义;response result 描述补 fileKey 含货主/仓库隔离目录说明;params/headers/errors/isNeedAuth/isNeedLogin 口径不变;版本 0.3.63 -> 0.3.64(docMeta.version),updatedAt 保持 2026-08-31", + "docs/report-config-guide.md:第 4 节上传目录由 exports/report// 更新为按货主/仓库维度隔离的三级目录格式(store-{store_id} / warehouse-{warehouse_id} / common,含 excel.generateAndUpload 追加的 {YYYYMMDD} 日期目录);第 5 节补充投递/通知幂等键格式(含 store_id 维度)与 processOne 货主维度强校验说明", + "本次仅文档同步(业务代码由开发完成),未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试;测试数据保留不清理" + ], + "module": "report" + }, + { + "version": "2026.08.31-storeWarehouse.store.openAccount-remask", + "date": "2026-08-31", + "type": "updated", + "summary": "优化 storeWarehouse.store.openAccount:未传 store_remask(或传空)时默认用公司全称填充 wms_store_warehouse.store_remask(截断 50 字符),保证货主名称在列表/导出中始终有值", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "app/service/systems/store_warehouse.js openAccount:签约关系创建时 store_remask 兜底为 store.company_name 前 50 字符(仅当未传 store_remask 或传空时),与项目“货主名称 store_remask 优先、无备注回退 company_name”口径一致", + "methods/system.json 货主-仓库签约模块(module=storeWarehouse.store):openAccount 的 store_remask 参数描述补充默认值说明,版本 0.3.62 -> 0.3.63(docMeta.version),updatedAt 保持 2026-08-31", + "本次为行为变更:新开户且未传 store_remask 时签约表 store_remask 将写入公司全称;已存在的历史开户数据不受影响(如需回填需另行处理)", + "未执行数据库/Redis 操作,未运行测试;测试数据保留不清理" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.08.31-report-meta-removed", + "date": "2026-08-31", + "type": "removed", + "summary": "移除 report.meta(免权限只读列元数据接口):接口下线,前端获取注册字段/窗口参数改由 report.definition.typeList 提供、某报表定义勾选字段经 report.definition.list 的 fields 数组获取。", + "methods": [ + "report.meta" + ], + "notes": [ + "app/service/systemMethods/report.js:删除 meta 方法(含 JSDoc);_noNeedRight/_noNeedAuth 清单移除 meta(保留 generate,generateTaskProgress),免权限口径收窄", + "app/service/systems/report.js:删除 getMeta 方法(仅被 systemMethods report.meta 调用),getDefinition/resolveTypeEntry 仍被 generate/buildWorkbookSheets/定义管理复用不受影响", + "app/service/systemMethods/report/definition.js、app/service/systems/report/queries/index.js、app/service/systems/report/queries/sevenDayStockFlow.js:注释中 report.meta 引用同步清理(改指 report.definition.typeList)", + "methods/system.json 通用报表模块(module=report):删除 report.meta 条目,版本 0.3.61 -> 0.3.62(docMeta.version),updatedAt 保持 2026-08-31", + "AI_METHOD_ROUTING.md:删除 report.meta 表格行,更新 report.generate 鉴权描述(不再提 meta),新增接口移除说明并登记变更版本", + "docs/report-config-guide.md:第 7 节标题与 7.1-7.4 移除 report.meta 相关内容(响应示例/字段 selected 标记/调用步骤),保留 report.definition.typeList 并补充替代说明(窗口参数取 typeList、勾选字段取 definition.list 的 fields)", + "test/report_method_layer.cjs:删除 systemMethods.report.meta 套件;test/report_systems_engine.cjs:删除 systems/report.getMeta 套件并更新文件头覆盖说明;test/scripts/verify_report_delivery_gateway.cjs:移除 report.meta 冒烟调用(generateTaskProgress 保留)", + "权限说明:report.meta 原为免权限(isNeedAuth=false、无 wms_permission 记录),移除后无需任何权限回收操作", + "本次为破坏性变更:前端若仍调用 report.meta 将得到 method 不存在错误,需同步改为 report.definition.typeList + report.definition.list;未执行数据库/Redis 操作,未运行测试,测试数据保留不清理" + ], + "module": "report" + }, + { + "version": "2026.08.31-storeWarehouse.store.export", + "date": "2026-08-31", + "type": "added", + "summary": "新增 storeWarehouse.store.export(提交货主签约列表异步导出任务)与 storeWarehouse.store.exportTaskProgress(按 task_id 查询导出进度与下载链接):筛选条件与 storeWarehouse.store.list 语义一致(keyword/counterparty_id/store_id/auth_status/use_status/warehouse_use_status/id),page/page_size 忽略全量导出;后台生成 26 列中文表头 Excel 并上传 COS。", + "methods": [ + "storeWarehouse.store.export", + "storeWarehouse.store.exportTaskProgress" + ], + "notes": [ + "app/service/systems/store_warehouse.js:抽取 buildListForStoreWhere(data, currentSubject)(仓库在 warehouse_id 方、对方货主在 store_id 方,支持 id/contract_id/relation_id、counterparty_id/store_id、auth_status、use_status/warehouse_use_status、keyword 筛选),listForStore 改用它(行为不变);新增 exportListForStore(data):复用 buildListForStoreWhere + getRelationIncludes 全量查询(updated_at/id 倒序,不翻页、无行数上限),奇门配置经 getQimenConfigMap 映射 has_qimen_config,每行经 serializeRelation 序列化并输出 needs_my_confirm;ExcelJS 流式写入 26 列中文表头(签约关系ID/货主ID/货主名称/仓库ID/仓库名称/对方主体ID/对方主体名称/对方主体角色/备注名/当前视角启用状态/货主侧启用状态/仓库侧启用状态/签约状态/签约是否有效/剩余有效天数/面单余额/锁定面单余额/授权开始时间/授权结束时间/实际结束时间/申请时间/审核时间/申请原因/审核评语/是否已配置奇门/是否需要我确认,角色/启用状态/有效性/奇门/需确认为中文展示),经 systems.upload.uploadFile 上传(key=export/store_relation/{storeId}/{timestamp}_{filename}.xlsx,mimetype xlsx,category=document)并 uploadSuccessNotify 通知,返回 filename/fileKey/url/cdnUrl/cosUrl/total_count", + "app/service/systemMethods/storeWarehouse/store.js:新增 export(提交异步任务,task_id 前缀 store_relation_list_export_,setImmediate 异步执行并逐阶段回写进度:submitted→running(10)→success(100)/failed+error;失败 error 记录 message)与 exportTaskProgress(入参兼容 task_id/taskId,download_url 从 result.url/cdnUrl/cosUrl/fileKey 兜底取,task_id 缺失或缓存未命中返回 status=not_found 正常响应);generateExportTaskId 增加 options.base 自定义基础前缀(默认 print_qty_log 不变,现有 exportPrintQuantityLogs/exportStorePrintQuantityLogs 调用不受影响);systemInit 免权限声明:_noNeedRight/_noNeedAuth 加入 export,exportTaskProgress(异步任务模式,与 order.export 口径一致,无 wms_permission 记录),_noNeedLogin 不含(两接口均需登录,isNeedAuth=false、isNeedLogin=true)", + "methods/system.json 货主-仓库签约模块(module=storeWarehouse.store):新增 storeWarehouse.store.export 与 storeWarehouse.store.exportTaskProgress 两个 method 条目(追加于 createUser 之后),版本 0.3.60 -> 0.3.61(docMeta.version),updatedAt 保持 2026-08-31", + "AI_METHOD_ROUTING.md 本次未同步(storeWarehouse.store 相关行未覆盖导出能力,待后续补)", + "权限说明:export/exportTaskProgress 免权限(无 wms_permission 记录),仅登录可用;本次未扩任何角色授权,不执行权限同步 apply", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未执行数据库/Redis 操作,未运行测试;测试数据保留不清理" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.08.31-workbench-queryOrder-item-packing-requirements", + "date": "2026-08-31", + "type": "enhanced", + "summary": "workbench.business(queryOrder/query) 响应 items 每项新增 packing_requirements 字段(stock 打包要求,来自 wms_stock_warehouse.packing_requirements,经 getStockDetails 返回,未命中/异常时归一化为空字符串),纯增量字段,不破坏既有调用方。", + "methods": [ + "workbench.business" + ], + "notes": [ + "app/service/systems/workbench.js _queryOrder 步骤4 items 组装:新增 1 行 packing_requirements: String(stock.packing_requirements || '').trim(),stock 未命中(stockMap 兜底 {})或 getStockDetails 异常时取值为空字符串、不抛错;与 items 既有 sku_property/stock_unit 取值风格一致", + "methods/system.json workbench.business queryOrder/query 响应结构:items 字段 description 末尾追加 packing_requirements 字段说明(打包要求,来自 stock,未命中/异常时为空字符串)", + "纯增量字段,params/headers/errors/权限口径(isNeedAuth=false、isNeedLogin=false)均不变,不破坏既有调用方", + "methods/system.json 文档版本 0.3.59 -> 0.3.60(docMeta.version),updatedAt 更新为 2026-08-31", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "workbench" + }, + { + "version": "2026.08.30-report-delivery-plan-copy-target-store-status", + "date": "2026-08-30", + "type": "changed", + "summary": "report.deliveryPlan.copy 目标货主校验语义调整(放宽):目标货主有效性由仅 status=1(正常)放宽为 status 为 1 或 2(正常/审核中)均有效;其余状态(0/3 等)或已软删货主仍计入 skipped(reason「货主不存在或状态异常」文案不变);源计划校验、store_ids 校验、同源跳过、同报表定义计划跳过、通知配置不复制、enabled 原样复制等其余口径均不变。", + "methods": [ + "report.deliveryPlan.copy" + ], + "notes": [ + "app/service/systems/reportDelivery.js copyPlan:目标货主存在性校验由 where: { id: { [Op.in]: candidates }, status: 1 } 调整为 status: { [Op.in]: [1, 2] }(1=正常、2=审核中均有效),软删自动排除不变;未命中者仍计入 skipped(reason「货主不存在或状态异常」文案不变);方法注释同步更新为 status 为 1 或 2(正常/审核中)均有效口径", + "app/service/systemMethods/report/deliveryPlan.js copy:包装层无变化(解构 id/store_ids 透传 copyPlan),无需改动", + "methods/system.json 通用报表模块(module=report):report.deliveryPlan.copy description 目标货主校验口径由「状态正常(status=1)」改为「status 为 1 或 2(正常/审核中)均有效,其余状态或已软删自动排除」;response skipped.reason 枚举「货主不存在或状态异常」name 同步更新为 status∈{1,2} 口径;params/headers/errors/权限口径不变;版本 0.3.58 -> 0.3.59(docMeta.version),updatedAt 保持 2026-08-30", + "AI_METHOD_ROUTING.md:copy 相关行未提货主状态口径(仅概括「货主不存在或状态异常跳过」,与放宽后语义一致),无需改动", + "权限口径不变:report.deliveryPlan.copy 与 save/list 相同(isNeedAuth=true、isNeedLogin=true),未执行权限变更、未扩大任何角色授权", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.08.30-report-delivery-plan-copy", + "date": "2026-08-30", + "type": "added", + "summary": "新增 report.deliveryPlan.copy 批量复制接口:传入源计划ID id 与目标货主ID数组 store_ids(非空正整数数组,自动去重,兼容 storeIds 驼峰),快速复制源计划到其他货主;目标货主已存在同 report_definition_id 计划时跳过不覆盖;notify_group_ids/notify_member_ids 通知配置不复制(新计划置空);enabled 原样复制(保持复制语义),其余字段(report_definition_id/schedule_times/channel/late_grace_minutes/name/remark/notify_template)原样复制;事务批量创建,唯一键冲突单条降级 skipped。", + "methods": [ + "report.deliveryPlan.copy" + ], + "notes": [ + "app/service/systemMethods/report/deliveryPlan.js copy:解构 id/store_ids(兼容 storeIds 驼峰,优先取驼峰形式,与 save 的 reportId 兼容口径一致),透传 systems.reportDelivery.copyPlan({ id, storeIds }),统一 success 包装 data={ created, skipped };systemInit 未声明免权限(_noNeedLogin/_noNeedRight/_noNeedAuth 均为空),与 save/list 同权限口径(需登录需鉴权,仅通配符角色或已授权角色可用)", + "app/service/systems/reportDelivery.js copyPlan:id 必须为正整数(否则抛「计划ID无效」),findByPk 软删排除、不存在抛「计划不存在」;store_ids 经 parseJsonArray 解析为非空数组且元素为正整数并自动去重(空/非数组抛「目标货主 store_ids 必须为非空数组」,非法元素抛「目标货主 store_ids 含非法货主ID(需正整数): 」);与源计划 store_id 相同的目标计入 skipped(与源计划货主相同);wms_store 校验存在且 status=1(否则 skipped:货主不存在或状态异常);目标已存在同 report_definition_id 计划(软删排除)跳过(已存在同报表定义计划);新建 payload 中 notify_group_ids/notify_member_ids 置 null(通知配置不复制)、enabled 原样复制,其余字段原样复制;事务批量创建,并发撞 uk_store_report_definition 唯一索引时单条降级 skipped、不中断其余创建", + "methods/system.json 通用报表模块(module=report):新增 report.deliveryPlan.copy 条目(description/headers/params id+store_ids+storeIds/response created+skipped(reason 枚举 与源计划货主相同/货主不存在或状态异常/已存在同报表定义计划)/errors);isNeedAuth=true、isNeedLogin=true;版本 0.3.57 -> 0.3.58(docMeta.version),updatedAt 保持 2026-08-30", + "AI_METHOD_ROUTING.md 5.1 节路由表新增 report.deliveryPlan.copy 行(service 路径 app/service/systemMethods/report/deliveryPlan.js、函数 copy、需登录、需授权),并新增批量复制特性说明;变更记录列表顶部追加本版本", + "权限口径不变:report.deliveryPlan.copy 与 save/list 相同(isNeedAuth=true、isNeedLogin=true),未执行权限变更、未扩大任何角色授权", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.08.30-inbox-group-members-groupids-array", + "date": "2026-08-30", + "type": "changed", + "summary": "inbox.group.members 入参由单个 groupId 改为数组 groupIds(必填,非空且每个元素为正整数,对应 wms_inbox_group.id),一次查询多个群的成员并在消息层多群聚合去重(多群共享同一 500 条聚合池);破坏性入参变更(移除 groupId),调用方需同步升级。", + "methods": [ + "inbox.group.members" + ], + "notes": [ + "app/service/systemMethods/inbox.js groupMembers:解构 groupIds 透传给 systems 层;warehouseId 仍从 ctx.user?.store_id 服务端注入(Number 化),不信任前端传值;keyword/limit 透传不变", + "app/service/systems/inbox/group.js members:groupIds 校验为非空数组且每个元素为数字或可解析数字字符串的正整数(否则抛「groupIds 无效」);InboxGroup.findAll({ where: { id: { [Op.in]: groupIds }, warehouse_id } }) 批量校验群存在(软删自动排除),无匹配抛「群不存在或无权限操作」;聚合所有群外部 group_id(去重、剔空),全为空返回 { list: [] };消息按 group_id IN + warehouse_id 拉取(id 倒序、limit 500 共享聚合池、user_id 排除 NULL/空串、软删排除);按 user_id 去重取最新 user_name;keyword 对聚合结果做 user_name/user_id 小写包含过滤;截断到 limit(默认20上限100)", + "methods/system.json 站内信分组(module=inbox):inbox.group.members 描述改为多群聚合语义;params 删除 groupId、新增 groupIds(array,必填,非空数组,元素为正整数,对应 wms_inbox_group.id);errors 400 由「群ID无效 / warehouseId 无效」改为「groupIds 无效 / warehouseId 无效」;headers/响应结构/权限口径不变(warehouseId 仍服务端注入、567 权限);版本 0.3.56 -> 0.3.57(docMeta.version),updatedAt 保持 2026-08-30", + "AI_METHOD_ROUTING.md 5.2 节:members 底层实现描述由「groupId 必填」改为「groupIds 必填(数组,多群聚合)」;变更记录列表新增本版本", + "权限不变:仍需 567(inbox.group.members,isNeedAuth=true、isNeedLogin=true),未执行权限变更", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "inbox" + }, + { + "version": "2026.08.30-inbox-group-quicklist-dual-dim-filter", + "date": "2026-08-30", + "type": "changed", + "summary": "inbox.group.quickList 改为双维度可选过滤:store_id(货主维度,对应 wms_inbox_group.store_id 列)与 warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)均可选,可单独传、可同时传(AND),也可都不传(返回所有仓库/货主的群);本记录修正并取代 2026.08.30-inbox-group-quicklist-store-id(该版将 store_id 错误映射为 warehouse_id 列);新增 store_id 列索引迁移(待发布时执行)。", + "methods": [ + "inbox.group.quickList" + ], + "notes": [ + "取代关系:本记录修正并取代 2026.08.30-inbox-group-quicklist-store-id 的口径——上一版将入参 store_id 错误映射为 wms_inbox_group.warehouse_id(仓库维度),本版明确 store_id=货主维度(对应 store_id 列)、warehouse_id=仓库维度(对应 warehouse_id 列),两维度均可选可组合,均不传时返回所有仓库/货主的群", + "app/service/systemMethods/inbox.js groupQuickList:解构透传 data.store_id(storeId)与 data.warehouse_id(warehouseId)给 systems 层,不再从 ctx.user 注入任何仓库值;其余入参 keyword/groupType/limit 不变", + "app/service/systems/inbox/group.js quickList:双列可选过滤——store_id(货主维度,String 化 trim 非空时 Number 化并校验 Number.isInteger 且 >0,否则抛「store_id 无效」)设置 where.store_id;warehouse_id(仓库维度,同样校验否则抛「warehouse_id 无效」)设置 where.warehouse_id;两者可同时传(AND)也可都不传(不加对应过滤条件);keyword 模糊匹配 group_name/group_id、groupType 筛选、limit 默认20上限100、created_at 倒序、软删自动排除均不变", + "database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js:为 wms_inbox_group.store_id 新增索引 idx_store_id(幂等 up/down,尚未执行,待发布时执行);warehouse_id 维度已由 uk_warehouse_group_id(warehouse_id, group_id) 前导列覆盖,双条件 AND 由两索引组合命中", + "methods/system.json 站内信分组(module=inbox):inbox.group.quickList 描述改为双维度可选过滤口径;params 修正 store_id(货主维度,对应 store_id 列)并新增 warehouse_id(可选正整数,对应 warehouse_id 列);errors 400 由「store_id 无效」改为「store_id 无效 / warehouse_id 无效」;headers 保持登录凭证口径(不从中解析仓库上下文);版本 0.3.55 -> 0.3.56(docMeta.version),updatedAt 保持 2026-08-30", + "AI_METHOD_ROUTING.md 5.2 节:quickList 底层实现与仓库口径改为双维度口径(store_id=货主维度 / warehouse_id=仓库维度,均可选可组合、不传返回全部、不再从登录上下文注入),变更记录列表新增本版本并标注修正/取代上一版", + "权限不变:仍需 566(inbox.group.quickList,isNeedAuth=true、isNeedLogin=true),未执行权限变更", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "inbox" + }, + { + "version": "2026.08.30-inbox-group-quicklist-store-id", + "date": "2026-08-30", + "type": "changed", + "summary": "inbox.group.quickList 新增可选入参 store_id(对应 wms_inbox_group.warehouse_id):传入时仅返回该仓库的群,不传或为空时返回所有仓库的群;旧口径「warehouseId 由服务端从登录上下文自动注入、不信任前端传值」作废,改为透传前端入参 store_id。", + "methods": [ + "inbox.group.quickList" + ], + "notes": [ + "app/service/systemMethods/inbox.js groupQuickList:不再从 ctx.user.store_id 自动注入 warehouseId,改为解构透传 data.store_id(storeId)给 systems 层;其余入参 keyword/groupType/limit 不变", + "app/service/systems/inbox/group.js quickList:storeId 可选(String(data.storeId ?? '').trim() 非空时 Number 化并校验 Number.isInteger 且 >0,否则抛「store_id 无效」);传入时 where.warehouse_id = storeId 过滤,不传或为空时不加 warehouse_id 过滤、返回所有仓库的群;keyword 模糊匹配 group_name/group_id、groupType 筛选、limit 默认20上限100、created_at 倒序、软删自动排除均不变", + "methods/system.json 站内信分组(module=inbox):inbox.group.quickList 描述删除「warehouseId 由服务端从登录上下文自动注入」,补 store_id 口径(可选正整数,对应 warehouse_id,不传返回全部);params 新增 store_id(number|string,可选);errors 400 由「warehouseId 无效」改为「store_id 无效」;headers 描述改为登录凭证口径(不再从中解析 warehouseId 仓库上下文);版本 0.3.54 -> 0.3.55(docMeta.version),updatedAt 保持 2026-08-30", + "AI_METHOD_ROUTING.md 5.2 节:quickList 底层实现补 store_id 口径;仓库口径拆分为「quickList 透传前端 store_id(不再服务端注入)/ members 仍从 ctx.user.store_id 服务端注入」", + "权限不变:仍需 566(inbox.group.quickList,isNeedAuth=true、isNeedLogin=true),未执行权限变更", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "inbox" + }, + { + "version": "2026.08.30-report-delivery-plan-name-field", + "date": "2026-08-30", + "type": "enhanced", + "summary": "投递计划新增计划名称 name 字段:report.deliveryPlan.save 新增可选入参 name(string|null;未传不覆盖,null/空串/全空白归一化为 null 显式清空,非空 trim 后 ≤100 超长报错),save 成功响应与 report.deliveryPlan.list 列表项新增 name 字段(缺省空串);name 仅展示字段,不参与幂等/关联逻辑。", + "methods": [ + "report.deliveryPlan.save", + "report.deliveryPlan.list" + ], + "notes": [ + "app/service/systems/reportDelivery.js:新增 normalizePlanName(value)(undefined=未传不覆盖返回 undefined;null/空串/全空白返回 null 显式清空;非空 trim 且 ≤PLAN_NAME_MAX_LENGTH(100),超长抛「计划名称 name 长度不能超过 100 字符」);savePlan 仅在 name !== undefined 时规范化并写入 payload.name,更新时不误清空", + "app/service/systems/reportDelivery.js planToView:响应视图新增 name: String(plan.name || '')(缺省空串),save 成功响应与 list 列表项均带该字段", + "app/service/systemMethods/report/deliveryPlan.js save:解构透传 name(仅入参存在时附加 saveArgs.name,保持旧调用形状与既有回归断言一致)", + "wms_report_delivery_plan 新增 name 列(STRING(100) allowNull,comment「计划名称(前端展示用,缺省时可用报表名称兜底)」;迁移 20260830130000-add-name-to-wms-report-delivery-plan 已完成);name 仅展示字段,不参与 store_id+report_definition_id 幂等/关联逻辑", + "methods/system.json 通用报表模块:report.deliveryPlan.save params 新增 name(string|null)、response 新增 name(缺省 '')、errors 新增「计划名称 name 长度不能超过 100 字符」;report.deliveryPlan.list response children 新增 name;版本 0.3.53 -> 0.3.54(docMeta.version),updatedAt 保持 2026-08-30", + "docs/report-config-guide.md 第 5 节投递计划补 name 字段口径与保存示例;AI_METHOD_ROUTING.md 5.1 节补 name 变更条目与最新 changes 版本", + "权限口径不变:report.deliveryPlan.save/list 仍 isNeedAuth=true(未声明免权限),仅执行 npm run permission:sync:system-api -- --dry-run 预演(不 apply、不扩任何角色授权)", + "本次仅文档同步,未修改 app/ 下业务代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.08.30-report-type-list-merge-into-definition", + "date": "2026-08-30", + "type": "changed", + "summary": "枚举接口并入 definition:report.type.list → report.definition.typeList。免权限只读的类型注册清单查询由独立模块 report/type.js 并入 report/definition.js(typeList 方法,systemInit 声明 _noNeedRight/_noNeedAuth/_noNeedLog='typeList',仅要求登录);同模块 save/list/delete 仍需授权。", + "methods": [ + "report.definition.typeList", + "report.type.list" + ], + "notes": [ + "app/service/systemMethods/report/type.js 已删除;app/service/systemMethods/report/definition.js 新增 typeList(data) 方法(无必填入参,忽略请求体),返回 success('ok', { list }),list 由 systems/report.js listRegisteredTypes() 提供(QUERIES.describe() 注册表全量描述,当前仅 stockFlow)", + "权限口径:definition.js systemInit 声明 _noNeedRight/_noNeedAuth/_noNeedLog='typeList'(免权限/免鉴权/免审计日志,仅要求登录);同模块 save/list/delete 未声明免权限,仍需授权(isNeedAuth=true),同一模块内权限口径差异已在 method description 中注明", + "methods/system.json 通用报表模块:删除 report.type.list,新增 report.definition.typeList(isNeedAuth=false、isNeedLogin=true、无入参;响应 { list: [{key,title,description,window:{dayCount,cutoverHour},fields:[{key,label,type,computed?,asText?,children?}]}] },字段口径与原 report.type.list 一致);版本 0.3.52 -> 0.3.53(docMeta.version),updatedAt 保持 2026-08-30", + "docs/report-config-guide.md:report.type.list 全部替换为 report.definition.typeList(第 2/7 节标题、字段口径说明、请求/响应示例与设计器接口链),实现链由 report/type.js 改为 report/definition.js;AI_METHOD_ROUTING.md report 能力清单更新(report.definition.typeList → definition.js typeList)", + "权限仅执行 npm run permission:sync:system-api -- --dry-run 预演(不 apply、不扩任何角色授权)", + "本次仅文档同步(含文档脚本 update-api-doc.cjs 的 deleteMethods 能力扩展与缩进检测修正),未修改 app/ 下业务代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.08.30-report-definition-model-refactor", + "date": "2026-08-30", + "type": "changed", + "summary": "报表定义模型重构:code→id 关联、type/fields 极简配置、注册表 stockFlow、新增 report.type.list。破坏性变更:report.generate/report.meta/report.deliveryPlan.* 的 report_code 入参全部替换为 report_id(=报表定义ID,兼容 reportId 驼峰),前端需同步改 report_id。", + "methods": [ + "report.generate", + "report.meta", + "report.type.list", + "report.definition.save", + "report.definition.list", + "report.definition.delete", + "report.deliveryPlan.save", + "report.deliveryPlan.list", + "report.deliveryLog.list" + ], + "notes": [ + "模型重构(app/model/report_definition.js):移除 code/scope/description 与 output_config/source_config/sheet_config 三段 JSON 配置列,改为 name/type/file_name/fields/is_enabled/remark + 主键 id(唯一性由 id 承担,删除 uk_code);投递计划/记录表外键由 report_code 改为 report_definition_id,投递记录新增 report_name 名称快照", + "app/service/systemMethods/report.js:generate/meta 入参 report_code 改为 report_id(reportId 驼峰优先);meta 响应由 report_code/name/scope/query/window/fields 改为 report_id/name/type/file_name/window/fields(fields 新增 selected 勾选标记与 asText 标记);generateTaskProgress 不变", + "新增 app/service/systemMethods/report/type.js:report.type.list 免权限只读(systemInit 声明 _noNeedRight/_noNeedAuth/_noNeedLog 含 list,仅要求登录),返回注册类型清单 [{key,title,description,window:{dayCount,cutoverHour},fields:[{key,label,type,computed,asText,children}]}];当前仅注册 stockFlow(标题「库存变化以及补货报表」)", + "app/service/systemMethods/report/definition.js:save 入参 {id?,name,type,file_name/fileName,fields,is_enabled,remark}(type 必须命中注册表、fields 必须为该类型注册字段子集,非法 key 报可读错误并列出可用字段;新增必填 type/file_name/fields);list where 改 name/type/is_enabled,sort 白名单 id/name/type/is_enabled/created_at/updated_at;delete 入参 id,引用拦截按 report_definition_id 统计启用中计划", + "app/service/systems/report.js:新增 listRegisteredTypes/resolveTypeEntry/validateTypeFields,saveDefinition/listDefinitions/deleteDefinition 按 id 重写;渲染由 app/lib/report/render.js renderSheetByType 按类型硬编码字段规格完成(asText 由类型字段规格硬编码自动应用,string 字段 asText=true 时落地文本单元格),sheet_config 已删除", + "app/service/systems/reportDelivery.js:savePlan/listPlans/listLogs 关联键由 report_code 改为 report_definition_id,listLogs 响应新增 report_name 快照;幂等键与唯一索引 uk_store_report_definition 同步改为 report_definition_id", + "methods/system.json 通用报表模块:report.generate/report.meta/report.definition.save/report.definition.list/report.definition.delete/report.deliveryPlan.save/report.deliveryPlan.list/report.deliveryLog.list 8 个 method 按新形态重写,新增 report.type.list(report.generateTaskProgress 不受影响保持原样);版本 0.3.51 -> 0.3.52(docMeta.version),updatedAt 保持 2026-08-30", + "docs/report-config-guide.md 整体改写(注册类型 stockFlow 标题/描述/16 字段表、report.type.list 用法、definition 保存示例 fileName+type+fields、plan 用 report_id、删除 sheet_config/asText 旧说明并按新渲染规则改写);AI_METHOD_ROUTING.md report 能力清单刷新", + "权限口径:report.type.list 免权限(isNeedAuth=false);其余 report.* 沿用既有授权口径(管理类接口 isNeedAuth=true);仅执行 npm run permission:sync:system-api -- --dry-run 预演,未 apply、未扩任何角色授权", + "本次仅文档同步,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "report" + }, + { + "version": "2026.08.30-order-export-create-channel-column", + "date": "2026-08-30", + "type": "enhanced", + "summary": "订单导出(order.export)waybill/item 两种导出模式在「平台」列之后新增导出列「来源」(字段 create_channel,中文取值:手工单/接口/奇门/出库转单);该列已自动纳入导出表头白名单 ORDER_EXPORT_ALL_COLUMN_HEADERS(waybill/item 两模式列头并集),export_columns/exportColumns 入参已支持传「来源」,不传或空数组时默认输出全部列。", + "methods": [ + "order.export" + ], + "notes": [ + "app/service/systems/order_export.js:ORDER_EXPORT_COLUMNS(waybill 模式)与 ORDER_EXPORT_ITEM_COLUMNS(item 模式)均在「平台」(sys_platform_name)之后新增 { header: '来源', key: 'create_channel', width: 12 }", + "ORDER_EXPORT_ALL_COLUMN_HEADERS 为 waybill/item 两模式列头并集(Object.freeze(new Set(...))),「来源」在列配置登记后自动可用:export_columns/exportColumns 传「来源」合法(校验不区分导出模式),不传或空数组时输出全部列(含来源)", + "取值翻译:app/service/systemMethods/order/base.js CREATE_CHANNEL_LABELS = { MANUAL: '手工单', API: '接口', QM: '奇门', STOCKOUT: '出库转单' },formatCreateChannelLabel 未命中映射时原样返回 create_channel 原文", + "methods/system.json:order.export 的 export_columns/exportColumns 参数描述中枚举由 51 个更新为 52 个(在「平台」之后插入「来源」),并补充来源列取值、位置(平台列之后)与两种模式均输出的说明;order.exportTaskProgress 无导出列枚举内容,无需改动", + "methods/system.json 版本 0.3.50 -> 0.3.51(docMeta.version),updatedAt 2026-08-29 -> 2026-08-30", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试" + ], + "module": "order.index" + }, + { + "version": "2026.08.29-waybill-warehouse-waybillCode-array-exact-match", + "date": "2026-08-29", + "type": "enhanced", + "summary": "运单列表与导出接口的 where.waybillCode 支持字符串数组精确匹配:waybill.warehouse.list / waybill.warehouse.export 的 where.waybillCode 由「仅字符串模糊搜索」扩展为「字符串模糊搜索(LIKE '%值%',向后兼容)/ 字符串数组精确匹配(Op.in,元素自动 trim 并过滤空值,空数组或全空值不加该筛选条件)」,修复此前数组入参被逗号拼接后做 LIKE 导致搜索无结果的问题。", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.export" + ], + "notes": [ + "app/service/systems/waybill.js list() 第 226-235 行:where.waybillCode 为数组时先逐元素 String 化并 trim、过滤空值,非空则 waybill_code = { [Op.in]: waybillCodeList } 精确匹配;字符串时保持 waybill_code = { [Op.like]: '%trim%', } 模糊匹配(向后兼容)", + "export 的筛选条件构建(第 767-776 行)与 list 逻辑一致:数组 Op.in 精确匹配、字符串 Op.like 模糊匹配", + "修复前行为:数组入参会被逗号拼接后进入 LIKE 分支,导致搜索无结果;修复后数组元素 trim 并过滤空值,空数组/全空值不加 waybill_code 筛选条件", + "methods/system.json:waybill.warehouse.list 与 waybill.warehouse.export 的 where.waybillCode 参数 type 由 string 更新为 string|string[],description 补充字符串模糊搜索与字符串数组精确匹配(元素 trim、过滤空值)规则", + "methods/system.json 版本 0.3.49 -> 0.3.50(docMeta.version),updatedAt 保持 2026-08-29", + "本次仅文档同步,业务代码已由开发侧修复(app/service/systems/waybill.js),未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.08.29-order-packing-quickWhere-short-kw-guard", + "date": "2026-08-29", + "type": "enhanced", + "summary": "order.packing.list 的 where.quickWhere 运单号降级模糊新增关键词长度校验:精确未命中后仅当 trim 后关键词长度 ≥ 4(QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH)才降级 LIKE '%kw%' 模糊查询;长度 < 4 的短词(含单字符)禁止降级、运单号解析直接返回空结果(避免 %短词% 误命中海量历史单号);波次号模糊逻辑不变。", + "methods": [ + "order.packing.list" + ], + "notes": [ + "app/service/systems/order_packing.js 第 12 行模块常量 QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH = 4:注释说明短于该长度的输入(如单字符 \"7\")没有模糊搜索意义且 %短词% 极易误命中海量历史单号(实测 \"7\" 可命中 24149 行),因此禁止短词降级进入 %kw% 模糊分支", + "list() 的 where.quickWhere 分支:波次号直接 LIKE '%kw%' 模糊不变;运单号先按「完整单号等值 + 剥离分段后缀主体等值 + 主体前缀 LIKE '主体-%'」精确集合查询 wms_order_express,第 206 行条件 expressRecords.length === 0 && kw.length >= QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH 才降级 waybill_code LIKE '%kw%';短词(长度 < 4)不进入模糊分支,运单号解析保持空结果(仅保留波次号模糊条件)", + "list() JSDoc 第 64 行 where.quickWhere 描述已同步:精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中", + "methods/system.json:order.packing.list 的 where.quickWhere 参数描述补充「精确未命中且关键词长度 ≥ 4 才降级 %kw% 模糊;长度 < 4 短词不降级、直接返回空;波次号模糊不变」规则", + "methods/system.json 版本 0.3.48 -> 0.3.49(docMeta.version),updatedAt 保持 2026-08-29", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "order.packing" + }, + { + "version": "2026.08.29-wave-batchCancel-pick-status-guard", + "date": "2026-08-29", + "type": "enhanced", + "summary": "取消波次增加拣货状态校验:order.wave.batchCancel 提交前新增两道业务校验(code 400)——波次内存在拣货中或拣货完成(pick_status 为 padding/fin)的订单、或波次状态已进入拣货及后续环节(wms_wave_batch.wave_status >= 3)时禁止取消波次;runBatchCancelTask 异步兜底命中上述条件跳过该波次并继续处理其余波次;order.wave.batchCancelTaskProgress 任务结果新增 skipped_wave_ids / skipped_wave_count / skipped_waves 字段。", + "methods": [ + "order.wave.batchCancel", + "order.wave.batchCancelTaskProgress" + ], + "notes": [ + "app/service/systemMethods/order/wave.js batchCancel():活动拣货任务校验后新增两道 400 校验——① getOrderModel('pendingOrder', warehouseId) 查询波次内 pick_status IN ('padding','fin') 的订单,命中返回「波次内存在已拣货完成或拣货中的订单,禁止取消波次」(附 wave_ids 与最多前 20 个 order_ids);② 查询 wms_wave_batch 中 wave_status >= 3 的波次,命中返回「波次已进入拣货或后续环节,禁止取消波次」(附 wave_ids)", + "runBatchCancelTask():目标波次查询新增 wave_status 列;逐波次处理时先校验 wave_status >= 3(跳过明细 reason=wave_status_blocked,附 wave_status),再在事务内校验波次内 pick_status IN ('padding','fin') 的订单(reason=picked_orders_exist,附 picked_order_count),命中则回滚事务、跳过该波次并继续处理其余波次;无目标波次时 result 返回空 skipped_wave_ids 数组与 skipped_wave_count=0", + "任务结果:success 与 failed 终态的 result 均新增 skipped_wave_ids(被跳过波次 ID 列表)、skipped_wave_count(数量)、skipped_waves(明细数组,字段 wave_id/wave_no/reason/wave_status/picked_order_count,其中 wave_status 仅 reason=wave_status_blocked、picked_order_count 仅 reason=picked_orders_exist)", + "methods/system.json:order.wave.batchCancel 的 description 补充校验规则说明、errors 新增两条 400 描述;order.wave.batchCancelTaskProgress 的 description 与 response 补充 skipped_wave_ids / skipped_wave_count / skipped_waves 字段说明(含 children 明细),并同步更新 result 字段描述(补充 ids/affected_wave_ids/affected_order_count/skipped_* 等字段枚举)", + "methods/system.json 版本 0.3.47 -> 0.3.48(docMeta.version),updatedAt 保持 2026-08-29", + "本次仅文档同步,业务代码改动已完成(git diff app/service/systemMethods/order/wave.js),未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "order.wave" + }, + { + "version": "2026.08.29-order-packing-waybill-code-match", + "date": "2026-08-29", + "type": "enhanced", + "summary": "打包获取订单与订单快捷搜索的运单号匹配规则收敛:order.packing.list 的 where.waybill_code 由默认「%值%」模糊匹配改为「完整单号等值 + 剥离 -1-1- 分段后缀后主体单号等值 + 主体前缀 LIKE '主体-%'」精确匹配(不再支持部分单号模糊,无匹配返回空);quickWhere 运单号解析先按上述等值集合精确匹配、精确未命中才降级为 %kw% 模糊查询,波次号模糊逻辑不变;order.deliveryOrder.quickSearch 运单号条件同步扩展为「完整等值 + 主体等值 + 主体前缀 LIKE」,运单号不再落入模糊分支,发货单号/原始平台订单号模糊匹配不变(平台交易单号 pay_no 仅回显不参与匹配,修正文档过期描述)。", + "methods": [ + "order.packing.list", + "order.deliveryOrder.quickSearch" + ], + "notes": [ + "新增公共工具 app/lib/waybill_code.js:stripWaybillSegmentSuffix 剥离运单号尾部一单多件包裹序号分段(正则 /(?:-\\d+){2,}-?$/,如 JDX057941864338-1-1- → JDX057941864338,无分段原样返回);escapeLikeWildcards 转义 like 通配符 % _ \\,保证主体前缀匹配的主体部分被等值比较", + "app/service/systems/order_packing.js list():where.waybill_code 通过 wms_order_express 解析 order_id(wms_pack_task.waybill_code 通常为空),条件集合为 [waybill_code=完整单号, waybill_code=剥离后缀后主体, waybill_code LIKE '转义主体-%'] 的 OR 组合,命中后按 order_id IN 过滤,无命中强制空结果(queryWhere.id=-1);不再使用 like '%值%' 模糊匹配", + "order_packing.js list() 的 where.quickWhere:波次号直接 LIKE '%kw%' 模糊不变;运单号解析先按上述精确集合查询,expressRecords 为空才降级为 waybill_code LIKE '%kw%'(兼容输入部分单号场景);团购按 wave_no、散单按 order_id 查询链路不变", + "app/service/systemMethods/order/deliveryOrder.js quickSearch():express 表 OR 条件中运单号扩展为 [完整等值, 主体等值, 主体前缀 LIKE '主体-%'],运单号不再落入 %kw% 模糊分支;delivery_order_code / source_order_codes 仍为 LIKE '%kw%' 模糊匹配;pay_no 不在搜索条件中(仅第三步订单详情输出回显),原文档「平台交易单号 pay_no(模糊)」为过期描述已按实现修正", + "methods/system.json:order.packing.list 的 where.waybill_code 描述由「运单号(模糊匹配)」改为完整单号/剥离分段后缀主体/主体前缀三种匹配规则说明,quickWhere 描述补充「先精确后降级模糊」优先级;order.deliveryOrder.quickSearch 的 description 与 keyword 参数描述同步修正(express 表匹配口径、pay_no 仅回显);quickSearch 条目补充空 headers 数组以符合文档校验结构", + "methods/system.json 版本 0.3.46 -> 0.3.47(docMeta.version),updatedAt 保持 2026-08-29", + "本次仅文档同步,业务代码由 wms-dev-agent 完成,未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "order.packing" + }, + { + "version": "2026.08.29-return-unpack-max-record-minutes", + "date": "2026-08-29", + "type": "enhanced", + "summary": "仓库设置新增「拆包最大录制时长」配置 return_unpack_max_record_minutes(分钟,默认 5,min 1):returnUnpack.submit 提交确认时,结束时间超过 开始时间+配置上限 时自动截断为上限时间点", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings", + "returnUnpack.submit" + ], + "notes": [ + "app/service/systems/setting/warehouse.js WAREHOUSE_SETTING_FIELDS 新增 return_unpack_max_record_minutes(名称:拆包最大录制时长(分钟),type integer,非必填,默认 5,min 1,描述:超过上限时提交的结束时间自动截断为开始时间+上限),与 single_order_pack_max_minutes(默认 3)/ group_order_pack_max_minutes(默认 40)并列;getFieldMeta 自动返回该字段元信息", + "app/model/store.js DEFAULT_SUBJECT_CONFIG 增加 return_unpack_max_record_minutes: 5;normalizeSubjectConfig 非法值(非正整数)抛「subject_config.return_unpack_max_record_minutes 必须是大于 0 的整数」,空值回退默认 5", + "app/service/systems/return_unpack.js submit() 新增私有方法 _resolveSubmitEndTime:候选 end_time 超过 start_time + 配置上限分钟时截断为上限时间点并记录 info 日志;配置读取 ctx.service.systems.deliveryOrder.getStoreSubjectConfig,配置非法/读取失败/start_time 缺失时不约束;其余行为不变(completed 终态、回写 is_back=1、货主群通知等均不变)", + "methods/system.json:setting.warehouse.getSettings 响应与 setting.warehouse.saveSettings 入参新增 subject_config.return_unpack_max_record_minutes 字段文档;returnUnpack.submit description 与响应 record 补充「结束时间超过仓库配置的拆包最大录制时长上限时自动截断为开始时间+上限」语义;getFieldMeta 为通用字段元信息结构,无逐字段清单,无需改动", + "向后兼容:新增字段可选,不影响既有仓库设置读写;本次仅文档同步,业务代码由 wms-dev-agent 完成", + "methods/system.json 版本 0.3.45 -> 0.3.46(docMeta.version),updatedAt 保持 2026-08-29" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.29-returnUnpack.export", + "date": "2026-08-29", + "type": "enhanced", + "summary": "新增退回拆包导出与进度查询接口:returnUnpack.export(提交异步导出任务,入参 where/sort 语义与 returnUnpack.list 一致,warehouse_id 由服务端注入 ctx.user.store_id;后台生成双 Sheet Excel:Sheet1 正常退回运单号列表、Sheet2 明细表并上传)与 returnUnpack.exportTaskProgress(按 task_id 查询任务进度与下载链接,未命中返回 status=not_found)。任务缓存 Redis TTL 30 分钟,状态口径 submitted→running→数据拉取(10~30)→明细拉取(30~50)→Excel(55~90)→上传(92)→success(100),失败 failed+error。两接口免权限免日志口径与 order.export 一致(isNeedAuth=false、isNeedLogin=true)。", + "methods": [ + "returnUnpack.export", + "returnUnpack.exportTaskProgress" + ], + "notes": [ + "app/service/systemMethods/returnUnpack.js 新增 export/exportTaskProgress 与任务缓存辅助方法(generateExportTaskId/normalizeExportTaskId/setExportTaskProgress/getExportTaskProgress):缓存键前缀 return_unpack_export_task_,Redis TTL 1800 秒(30 分钟);export 提交后 setImmediate 异步执行并逐阶段回写进度;exportTaskProgress 入参兼容 task_id/taskId,download_url 从 result.url/cdnUrl/cosUrl/fileKey 兜底取(代码中同时兼容 cndUrl 拼写);task_id 为空或缓存未命中返回 status=not_found(正常响应非报错)", + "systemInit 免权限声明:_noNeedRight/_noNeedAuth/_noNeedLog 均含 export,exportTaskProgress(异步任务模式,与 order.export 口径一致,无 wms_permission 记录);_noNeedLogin 不含(两接口均需登录,isNeedAuth=false、isNeedLogin=true)", + "app/service/systems/return_unpack.js 新增 exportUnpack:复用 _buildListWhere/_buildListOrder(与 list 语义一致)并强制 warehouse_id=注入值;主表全量分页拉取(每页 500,无行数上限),明细按 unpack_id 分批(每批 100)拉取;货主名批量映射 wms_store.company_name、快递类型映射 wms_order_express.logistics_name(各自独立 try/catch,解析失败降级为空字符串不阻断导出)", + "双 Sheet 结构:Sheet1「正常退回运单号列表」列=货主/快递号/商品类数/商品总数/记录人员/记录日期/开始时间/结束时间/是否原单(是/否)/快递类型/自定义店铺/平台单号;Sheet2「明细表」列=货主/快递号/商品名称/商品编码/条码/颜色/规格/数量/是否残次(是/否)/记录人员ID/记录日期/备注/是否原单(是/否)/快递类型/自定义店铺/平台单号;颜色取自明细 product_snapshot.sku_property 中「颜色:xxx」片段(兜底 spec 字段),无颜色信息为空;是否原单按 order_express_id 有值输出是/否;是否残次按 product_status=damaged 输出是/否", + "导出上传:ExcelJS 流式写入临时文件后经 systems.upload.uploadFile 上传(key=exports/return_unpack/{warehouseId}/{timestamp}_{token}.xlsx,mimetype xlsx,category=document),结果含 filename/url/fileKey/cdnUrl/cosUrl/current_count/total_count/total_details/sheet_count=2;Sheet1 不加 status 过滤(如需只导特定状态由调用方传 where.status)", + "methods/system.json 退回拆包模块(module=returnUnpack)新增 returnUnpack.export 与 returnUnpack.exportTaskProgress 两个 method 条目(追加于 returnUnpack.delete 之后),版本 0.3.44 -> 0.3.45(docMeta.version),updatedAt 保持 2026-08-29", + "权限说明:export/exportTaskProgress 免权限(无 wms_permission 记录),仅登录可用;本次仅文档、未扩任何角色授权,不执行权限同步 apply", + "仅文档变更,未改任何业务代码、表结构,未执行数据库/Redis 操作" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.29-report-channel-normalize-doc-audit", + "date": "2026-08-29", + "type": "docs", + "summary": "渠道默认值归一化 inbox + 文档一致性校对:全量核对「通用报表模块」全部 report.* method(generate/generateTaskProgress/meta/deliveryPlan.save/list/deliveryLog.list/definition.save/list/delete)与当前实现(app/service/systemMethods/report.js 及 report/ 子目录、app/service/systems/report.js、app/service/systems/reportDelivery.js、模型 report_definition/report_delivery_plan/report_delivery_log、迁移 20260829170000),仅发现 report.deliveryPlan.list / report.deliveryLog.list 响应 channel 字段存在过期描述(wecom/inbox/link),已修正为仅 inbox;其余 method 的 params/response/errors 均与实现一致,无接口行为变化。", + "methods": [ + "report.deliveryPlan.list", + "report.deliveryLog.list" + ], + "notes": [ + "迁移 database/migrations/20260829170000-normalize-report-channel-to-inbox.js:wms_report_delivery_plan / wms_report_delivery_log 的 channel 默认值 wecom → inbox、comment 收敛,存量 channel IN (wecom,link) 统一 UPDATE 为 inbox;模型同步(app/model/report_delivery_plan.js、app/model/report_delivery_log.js defaultValue: inbox)", + "代码核对:app/service/systems/reportDelivery.js 的 DELIVERY_CHANNELS 收敛为 [inbox]、DEFAULT_CHANNEL=inbox;deliverByChannel 对非 inbox 渠道记录 warn 日志后按 inbox 兜底投递(不抛错);inbox 推送失败(success=false 或 push_status=3)立即经 ctx.service.inbox.message.retry 重推一次,重推失败进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s)", + "修正点:report.deliveryPlan.list / report.deliveryLog.list 响应 channel 字段描述由「投递渠道:wecom/inbox/link」修正为「投递渠道:inbox(渠道已收敛,仅支持 inbox;历史数据已由迁移 20260829170000 归一化)」;仅文档描述修正,params/response 结构、错误码无任何变化", + "report.definition.save 的 19 条错误、report.definition.list 排序白名单 id/code/name/scope/is_enabled/created_at/updated_at、notify_template(≤500,标签白名单 {time}/{url}/{report_name}/{biz_date})/notify_group_ids(正整数去重 ≤20,校验存在性排除软删)/notify_member_ids(非空字符串去重 ≤100)参数与校验规则均与代码一致,未改动", + "report.generate/report.generateTaskProgress 免权限(_noNeedRight/_noNeedAuth 声明)、report.meta 免权限但保留审计日志(未列入 _noNeedLog)、report.deliveryPlan.*/report.deliveryLog.list/report.definition.* 需授权(isNeedAuth=true,未声明免权限)口径均与 systemInit 声明一致", + "methods/system.json 版本 0.3.43 -> 0.3.44(docMeta.version),updatedAt 保持 2026-08-29", + "配套文档核对:docs/report-config-guide.md 第 5 节渠道说明已与「仅 inbox + 兜底 + 重推」一致(补充迁移归一化说明);第 8 节 report.definition.save/list/delete 用法与实现一致;AI_METHOD_ROUTING.md 5.1 report 能力速查与路由说明已最新", + "权限:仅执行 npm run permission:sync:system-api -- --dry-run 预演缺口,未执行 apply、未扩任何角色授权", + "仅文档变更,未改任何业务代码、表结构,未执行数据库/Redis 操作" + ], + "module": "report" + }, + { + "version": "2026.08.29-report-definition-management", + "date": "2026-08-29", + "type": "enhanced", + "summary": "通用报表模块新增报表定义管理接口:report.definition.save/list/delete(wms_report_definition 管理侧 CRUD,均需登录且需鉴权 isNeedAuth=true,未扩任何角色授权)。save 按 code upsert(未传字段不覆盖),code 格式 ^[a-z][a-z0-9_]{1,63}$(长度 2-64)、name 必填 ≤100、scope 枚举 warehouse/store/open(默认 warehouse),output_config/source_config/sheet_config 三段 JSON 配置支持对象或 JSON 字符串,source_config.query 须为注册表已有查询器,sheet_config 列结构校验(static/expand/computed,expand pair 与查询器字段清单对齐),response 平铺 report_code;list 支持 where{code,name,scope,is_enabled}(code/name 模糊、scope/is_enabled 精确)/pagination/sort(白名单 id/code/name/scope/is_enabled/created_at/updated_at),response 全量字段含三段 JSON 配置;delete 按 code 软删(幂等),启用中的投递计划引用时拦截「存在 N 个启用的投递计划引用该报表,请先停用计划」。", + "methods": [ + "report.definition.save", + "report.definition.list", + "report.definition.delete" + ], + "notes": [ + "app/service/systemMethods/report/definition.js 新增:save/list/delete 仅做出口包装与参数解构(save 仅附加入参中存在的字段,undefined 不进入参数对象,保持「未传不覆盖」语义;list 经 prepareWhereContext 解析 where 后取 code/name/scope/is_enabled),业务逻辑下沉 app/service/systems/report.js saveDefinition/listDefinitions/deleteDefinition", + "saveDefinition:code 规范化 trim 后校验(空/格式非法分别报「报表编码 code 不能为空」「报表编码 code 格式非法:须以小写字母开头,仅含小写字母/数字/下划线,长度 2-64」,正则 ^[a-z][a-z0-9_]{1,63}$);name trim 必填 ≤100;scope 枚举校验;JSON 字段仅非 undefined 时经 parseRequiredJson 解析(对象原样返回/JSON 字符串解析/其余报「 解析失败:须为对象或合法 JSON 字符串」);source_config 的 query 必须为注册表已有查询器(resolveQueryKey 缺省 generic,未知报「未知的报表查询器: 」);sheet_config 经 validateDefinitionSheetConfig 校验列结构(columns 数组、列类型仅 static/expand/computed、static 列须有 field 或 value、computed 列须有 field 或 formatter、expand pair 须与查询器静态字段清单对齐否则报「sheet_config expand 列 pair 元素 '' 不在查询器 的字段清单中(可用: )」);is_enabled 仅 0/1;description/remark ≤500 截断", + "upsert 细节:uk_code 唯一索引含 deleted_at,findOne 以 paranoid:false 完整查重;命中软删记录先 restore 再 update(restore 撞唯一索引报「存在多个同名已删除记录,无法自动恢复,请更换报表编码」);并发首次创建撞 SequelizeUniqueConstraintError 降级为重查并更新(查不到报「报表编码已存在,保存冲突,请重试」);保存成功返回 definitionToView 视图(JSON 字段解析为对象)", + "listDefinitions:code/name LIKE 模糊(escapeLike 转义 \\%_)、scope 精确(非法报「scope 仅支持 warehouse/store/open,非法: 」)、is_enabled 空值不过滤(Number 化 0/1);pagination page≥1、pageSize 夹取 1-200;sort 白名单 id/code/name/scope/is_enabled/created_at/updated_at(sortField/sortOrder 兼容 sort_field/sort_order 别名,非法字段回退 id DESC);findAll+count 并行,raw 行映射 definitionToView", + "deleteDefinition:先按 report_code+enabled=1 统计 wms_report_delivery_plan 启用中引用(>0 报「存在 个启用的投递计划引用该报表,请先停用计划」),停用计划不阻断;再按 code paranoid:false 查定义(不存在报「报表定义不存在: 」,已软删幂等返回 deleted=1),否则 destroy 软删", + "method 层统一 catch 后 this.fail(error.message):错误响应 code=0、flag=failure(与 report.meta 惯例一致);save/delete 成功响应将定义 code 平铺为 report_code(避免覆盖统一响应 code=1)", + "systemInit 未声明 _noNeedLogin/_noNeedRight/_noNeedAuth 免权限 → 3 个接口均 isNeedAuth=true、isNeedLogin=true,仅通配符角色(超级管理员/仓库管理员)或后续 wms_permission 同步授权角色可用;本次仅文档、未扩任何角色授权,不执行权限同步 apply", + "methods/system.json 通用报表模块(module=report)新增 3 个 method 条目(追加于 report.meta 之后),版本 0.3.42 -> 0.3.43", + "配套文档:docs/report-config-guide.md 新增第 8 节「报表模板管理接口」;AI_METHOD_ROUTING.md 5.1 report 能力速查表登记 3 个新 method", + "仅文档变更,未改任何业务代码,未执行数据库/Redis 操作" + ], + "module": "report" + }, + { + "version": "2026.08.29-inbox-group-quick-list-members", + "date": "2026-08-29", + "type": "enhanced", + "summary": "新增站内信群选择下拉接口:inbox.group.quickList(群快速查询,keyword 模糊匹配群名称/外部群ID、groupType 筛选 store/warehouse/express、limit 默认20上限100,warehouseId 服务端注入,无分页,按创建时间倒序)与 inbox.group.members(群成员筛选,groupId 必填,按外部群ID在消息表聚合去重成员取每 user_id 最新 user_name,keyword 过滤后截断,外部群ID为空返回空列表);新增 API 权限 566(quickList)/567(members),授权角色 8/26/28/29,两接口均需登录且需鉴权。", + "methods": [ + "inbox.group.quickList", + "inbox.group.members" + ], + "notes": [ + "app/service/systems/inbox/group.js quickList:where 含 warehouse_id(服务端注入),keyword 对 group_name/group_id 双字段 LIKE 模糊匹配,limit 截断为 1-100(默认20),findAll 仅取 id/group_id/group_name/group_type/sub_type/is_blocked,按 created_at DESC,软删除由 paranoid 自动排除", + "app/service/systems/inbox/group.js members:先按 id+warehouse_id 查 wms_inbox_group(不存在抛「群不存在或无权限操作」,id 无效抛「群ID无效」);externalGroupId 为空直接返回 {list:[]};再按外部群ID+仓库查 wms_inbox_message(最近 500 条按 id DESC,user_id 非空),Map 按 user_id 去重取首次(最新)user_name,keyword 在聚合结果上过滤 user_name/user_id,最后 slice(0, limit)", + "app/service/systemMethods/inbox.js group.quickList/group.members 子入口:warehouseId 从 ctx.user.store_id 自动注入,不信任前端传值;inbox systemMethods 未声明 systemInit 免权限,两接口走标准 API 权限校验(isNeedAuth=true、isNeedLogin=true)", + "权限迁移 database/migrations/20260829180000-add-inbox-group-select-permissions.js:固定权限 ID 566(inbox.group.quickList,API:群快速查询)/567(inbox.group.members,API:群成员列表),type=api,授权角色 26(仓库组-主管)/28(客服组-主管)/29(生产组-主管)/8(经理);超级管理员(7)/仓库管理员(2) 持 * 通配符自动拥有;INSERT IGNORE 幂等,角色权限数组追加后去重排序", + "methods/system.json 站内信分组(module=inbox)新增 2 个 method 条目(追加于 inbox.group.messages 之后),版本 0.3.41 -> 0.3.42", + "AI_METHOD_ROUTING.md 新增 5.2 inbox.group(站内信群管理)能力速查小节,登记两接口的实现文件/函数/登录/鉴权信息", + "仅文档变更,未改任何代码,未执行数据库/Redis 操作" + ], + "module": "inbox" + }, + { + "version": "2026.08.29-report-delivery-channel-converge", + "date": "2026-08-29", + "type": "changed", + "summary": "报表投递渠道收敛:report.deliveryPlan.save 的 channel 收敛为仅支持 inbox(默认 inbox,移除 wecom/link,非法渠道报「投递渠道仅支持 inbox: 」);历史 wecom/link 计划投递时按 inbox 兜底执行(warn 日志不抛错);inbox 推送失败立即经 inbox.message.retry 重推一次(ext_id 幂等复用消息记录),重推仍失败进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s)。", + "methods": [ + "report.deliveryPlan.save" + ], + "notes": [ + "app/service/systems/reportDelivery.js:DELIVERY_CHANNELS 收敛为 ['inbox'],DEFAULT_CHANNEL='inbox';savePlan 对 channel 规范化(trim+lowercase,缺省默认 inbox)后不在白名单则抛「投递渠道仅支持 inbox: 」(原「投递渠道不合法(wecom/inbox/link)」文案已移除)", + "deliverByChannel:rawChannel !== 'inbox' 时记录 warn 日志「计划投递渠道 已弃用,按 inbox 兜底投递」后按 inbox 执行,不直接抛错(避免历史计划在 failed 退避循环中耗尽重试次数后永久卡死)", + "inbox 推送失败判定双保险:pushResult.success=false 或消息记录回写 push_status=3;失败时复用 ctx.service.inbox.message.retry 重推一次(重置 push_status=0 异步重推,ext_id 幂等复用同一条消息记录不重复写);retry 自身抛错则抛「站内信推送失败且重推失败: <原因>」,交由上层 failed 退避循环(MAX_RETRY=3,退避 = retry_count × 60s)", + "methods/system.json 通用报表模块:report.deliveryPlan.save 的 channel 参数枚举收敛为仅 inbox(默认 inbox)、响应 channel 字段说明同步收敛、errors 中渠道错误文案更新为「投递渠道仅支持 inbox: 」;版本 0.3.40 -> 0.3.41", + "配套文档:docs/report-config-guide.md 投递章节更新渠道说明(移除 wecom/link、历史渠道按 inbox 兜底、inbox 推送失败自动重推);AI_METHOD_ROUTING.md 同步补充渠道收敛说明与变更版本号", + "授权说明:本次仅文档、未扩任何角色授权。report.deliveryPlan.save/list、report.deliveryLog.list 仍为需授权接口(isNeedAuth=true),不涉及权限同步操作" + ], + "module": "report" + }, + { + "version": "2026.08.29-report-delivery-notify-template-targets", + "date": "2026-08-29", + "type": "enhanced", + "summary": "报表投递新增文本通知与定向群/成员:report.deliveryPlan.save 新增可选参数 notify_template(≤500 字符,标签白名单 {time}/{url}/{report_name}/{biz_date},未知标签报错列出非法标签)、notify_group_ids(wms_inbox_group.id 正整数去重 ≤20,保存时校验存在性且排除软删,缺失报错列出缺失 ID)、notify_member_ids(外部 IM 用户 ID 非空字符串去重 ≤100);report.deliveryPlan.list 响应带出上述 3 个配置字段;report.deliveryLog.list 响应新增 notify_targets 投递目标快照({group_ids, member_ids, notify_text})。", + "methods": [ + "report.deliveryPlan.save", + "report.deliveryPlan.list", + "report.deliveryLog.list" + ], + "notes": [ + "app/service/systems/reportDelivery.js savePlan:notify_template/notify_group_ids/notify_member_ids 三个可选参数仅在入参存在(!== undefined)时生效,未传不进入 payload(更新时保持既有字段不动,不传参数行为与旧版完全一致)", + "savePlan 校验:notify_template trim 后 ≤500 字符;notify_group_ids 正整数、去重升序、≤20,保存时 validateNotifyGroupExists 校验 wms_inbox_group 存在性(软删自动排除,不校验 is_blocked:被屏蔽群仍可选中,屏蔽属于发送时过滤维度);notify_member_ids 非空字符串、去重、≤100;两者支持数组或 JSON 字符串数组,非数组报「必须为数组」", + "标签白名单渲染:app/lib/report/notifyTemplate.js ALLOWED_TAGS={time,url,report_name,biz_date},validateNotifyTemplate 提取 {xxx} 标签并列出非法标签,renderNotifyTemplate 仅替换白名单标签;{url} 为空时替换为兜底文案「文件生成中,稍后可在投递记录中查看」,不阻断投递", + "发送链路:reportDelivery.deliverByChannel 投递完成后调用 sendNotifyIfConfigured(与渠道独立,link 渠道同样生效);未配置模板或未选任何群/成员返回 null(不发送);群多选按 wms_inbox_group 逐群推送(群维度协议字段单值),发送时过滤 is_blocked=1/软删/仓库维度不一致;成员 user_id 数组整体透传不循环拆发,选择群时随每个群推送携带,未选择群时单独一次仅成员推送;目标不可达或推送失败抛异常走失败退避重试", + "快照:sendNotifyIfConfigured 返回 {group_ids(实际发送的内部群ID), member_ids, notify_text},markDelivered 随 delivered 写入 wms_report_delivery_log.notify_targets;listLogs 以 readJsonObject 读取并输出(未配置时为 null)", + "app/service/systems/warehouseNotify.js pushSystemMessage 新增 userIds 参数(仅接受字符串数组,去重过滤空值),推送体 user_id 直接传数组(目标侧协议支持);向后兼容:不传 userIds 且传 group 时校验、幂等 ext_id、落库字段、推送体均与旧版一致;消息表 user_id 列不承载数组(避免超长截断),成员仅随推送体透传并记录在投递日志快照", + "method 层 app/service/systemMethods/report/deliveryPlan.js save:仅当 notify_template/notify_group_ids/notify_member_ids 在入参存在时附加到 saveArgs(undefined 不进入参数对象),保持旧调用形状与既有回归断言一致", + "授权说明:本次仅文档、未扩任何角色授权。report.deliveryPlan.save/list、report.deliveryLog.list 仍为需授权接口(isNeedAuth=true),不涉及权限同步操作", + "methods/system.json 通用报表模块更新 3 个 method 的 params/response/errors(版本 0.3.39 -> 0.3.40);配套文档 docs/report-config-guide.md 投递章节新增「文本通知模板与定向群/成员」小节" + ], + "module": "report" + }, + { + "version": "2026.08.29-report-meta", + "date": "2026-08-29", + "type": "enhanced", + "summary": "新增 report.meta(免权限只读列元数据接口,供前端报表设计器拉取可用字段):按报表编码返回 wms_report_definition 的 report_code/name/scope/query 与窗口参数 window{dayCount,cutoverHour},以及查询器静态字段清单 fields(查询器模块挂载的 querier.fields,未挂载返回空数组),不执行真实数据查询。", + "methods": [ + "report.meta" + ], + "notes": [ + "app/service/systemMethods/report.js meta:入参 report_code/reportCode 双写法(驼峰优先),为空返回 fail「报表编码 report_code 不能为空」(flag=failure、code=0、HTTP 200);调用 systems/report.getMeta 后组装 {report_code, name, scope, query, window, fields}(getMeta 的 code 字段回显为 report_code)", + "systemInit 声明:_noNeedRight/_noNeedAuth 含 meta(免权限 + 免仓库有效期鉴权,仅登录),_noNeedLogin 不含 meta(必须登录);_noNeedLog 未含 meta → meta 保留审计日志(generate/generateTaskProgress 不写审计日志,两者行为不同,已在接口文档与配置指南中如实标注)", + "app/service/systems/report.js getMeta:读 wms_report_definition(is_enabled=1,不存在/停用抛「报表定义不存在或已停用: 」,经 controller 兜底为 HTTP 500 接口错误);window 由 app/lib/report/day_window.resolveWindowConfig 解析(默认 dayCount=7、cutoverHour=7,[D 07:00, D+1 07:00) 半开区间,source_config 可覆盖);fields 由 resolveQuerierFields 读取查询器模块静态字段 querier.fields(未挂载返回空数组)", + "静态字段清单挂载方式:查询器模块以 FIELDS 常量挂载到导出函数(queries/sevenDayStockFlow.js 挂载 12 个顶层字段 stock_id/item_code/item_name/barcode/daily/ck_total/rk_total/available/total/pending/suggest/warn;daily 为数组类型含 ck/rk 子字段,suggest/warn 为 computed=true 格式化器预计算字段;queries/generic.js 未挂载,fields 返回空数组)", + "授权说明:本次仅文档、未扩任何角色授权。report.meta 免权限(isNeedAuth=false),不涉及权限同步操作", + "methods/system.json 通用报表模块分组新增 report.meta 登记(版本 0.3.38 -> 0.3.39);配套文档 docs/report-config-guide.md 新增 report.meta 小节,AI_METHOD_ROUTING.md 刷新 report.meta 条目" + ], + "module": "report" + }, + { + "version": "2026.08.29-report-config-driven-generate-delivery", + "date": "2026-08-29", + "type": "enhanced", + "summary": "新增配置驱动通用报表与货主定时投递接口:report.generate(提交报表导出异步任务,仅登录免权限)、report.generateTaskProgress(查询导出任务进度,仅登录免权限)、report.deliveryPlan.save/list(货主报表投递计划新增/更新与分页查询,需授权)、report.deliveryLog.list(投递记录审计分页查询,需授权)。", + "methods": [ + "report.generate", + "report.generateTaskProgress", + "report.deliveryPlan.save", + "report.deliveryPlan.list", + "report.deliveryLog.list" + ], + "notes": [ + "app/service/systemMethods/report.js:systemInit 声明 _noNeedRight/_noNeedAuth = generate,generateTaskProgress(免权限+免仓库有效期鉴权,仅登录);generate 的 warehouse_id 由服务端从登录上下文 ctx.user.store_id 自动注入,禁止前端传递;store_id 支持 store_id/storeId 双写法,<=0 视为不按货主过滤", + "app/service/systemMethods/report/deliveryPlan.js 与 report/deliveryLog.js:systemInit 未声明免权限(_noNeedRight/_noNeedAuth 均为空),为需授权管理类接口;methods/system.json 中 isNeedAuth=true 已登记", + "权限同步:本次仅写文档、未执行任何授权操作。report.deliveryPlan.save/list、report.deliveryLog.list 为需授权接口,后续请先执行 npm run permission:sync:system-api -- --dry-run 预演,再按标准流程授权;不扩大任何角色授权范围", + "实现依赖:app/service/systems/report.js(getDefinition/resolveQuerier/buildWorkbookSheets/generate/generateBuffer)、app/service/systems/reportDelivery.js(savePlan/listPlans/listLogs/dispatch 投递编排)、app/lib/report/*(render/day_window/formatters 纯函数模块)、内置查询器注册表 app/service/systems/report/queries/index.js(sevenDayStockFlow/generic)", + "报表配置驱动:wms_report_definition(app/model/report_definition.js)以 code/name/scope + output_config/source_config/sheet_config 三段 JSON 配置驱动,新报表优先加配置行、免发版;sheet_config 支持静态列/窗口展开列/计算列、headerRow1 的 {date} 模板、merges 绝对引用、style、rowFilter", + "methods/system.json 新增「通用报表模块」分组(module=report,groupName=通用报表模块),登记 5 个 method 的参数(source=body)、响应与错误码;版本 0.3.37 -> 0.3.38", + "配套文档:docs/report-config-guide.md 新增报表配置结构说明(三段 JSON 配置、列定义、{date} 模板、merges、style、rowFilter、查询器注册表与内置查询器口径假设);AI_METHOD_ROUTING.md 同步刷新 report 相关路由说明与服务清单" + ], + "module": "report" + }, + { + "version": "2026.08.28-workbench-queryOrder-intercept-pack-flag", + "date": "2026-08-28", + "type": "enhanced", + "summary": "workbench.business(queryOrder/query) 查询订单响应增强:order 对象新增 intercept_status 字段(拦截状态原始值,散单/团购均返回,与既有 pack_status 并列);散单(isSandan=1)时 order 额外返回 intercept_flag/pack_flag 两个 0/1 标志(拦截状态不等于 none 时 intercept_flag=1 否则 0,打包状态不等于 none 时 pack_flag=1 否则 0),团购不返回这两个标志;空值/null 统一归一化为 none。", + "methods": [ + "workbench.business" + ], + "notes": [ + "app/service/systems/workbench.js _queryOrder 步骤6:intercept_status/pack_status 空值/null 归一化为 none(String(v||'').trim() || 'none'),interceptFlag = 状态 !== none ? 1 : 0,packFlag 同理", + "_queryOrder 响应 order 对象新增 intercept_status(原始值,散单/团购均返回),与既有 pack_status 并列,原始状态字段原样保留、不破坏既有调用方", + "仅散单(isSandan===1)向 result.order 追加 intercept_flag/pack_flag;团购(isSandan===0)不追加这两个标志字段,pack_status/intercept_status 原始值仍原样返回", + "methods/system.json workbench.business 同步补充 queryOrder/query 响应结构:order.intercept_status 字段说明、散单场景 order.intercept_flag/order.pack_flag 字段说明与取值语义(状态不等于 none 返回 1,否则返回 0)" + ], + "module": "workbench" + }, + { + "version": "2026.08.28-storage-entry-quickInbound-is-virtual-inbound", + "date": "2026-08-28", + "type": "enhanced", + "summary": "storage.entry.quickInbound 事务内回写 is_virtual_inbound(是否虚拟入库):有绑定收货单 → 0(非虚拟入库),无绑定收货单 → 1(虚拟入库),与 order_status=COMPLETED 同一事务写入;wms_entry_order 新增 is_virtual_inbound 字段(TINYINT(1) NOT NULL DEFAULT 0)", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "app/service/systems/storage/entry.js quickInbound:eo.update 事务内新增 is_virtual_inbound 回写,值为 receivingIds.length > 0 ? 0 : 1(有绑定收货单 → 非虚拟入库,无绑定收货单 → 虚拟入库),与 order_status=COMPLETED、sync_status=SUCCESS 同一事务提交", + "app/model/entry_order.js:wms_entry_order 新增 is_virtual_inbound 字段(TINYINT(1),allowNull:false,defaultValue:0,comment:是否虚拟入库:0=否 1=是)", + "database/migrations/20260828100000-add-is-virtual-inbound-to-wms-entry-order.js:新增迁移(describeTable 已存在时跳过 addColumn),down 删除字段;迁移文件仅创建,本次文档任务未执行", + "methods/system.json storage.entry.quickInbound 说明文字补充 is_virtual_inbound 判定规则;入参/出参不变(quickInbound 响应未返回该字段,list/get 查询白名单亦未包含该字段)" + ], + "module": "storage.entry" + }, + { + "version": "2026.08.27-order-allocateStorage-allow-storage-location", + "date": "2026-08-27", + "type": "fixed", + "summary": "order.pendingOrder.allocateStorage 修复 allow_storage_location=true 未生效:分配储位时仍强制校验库位类型 allow_allocation=1/is_active=1,存储储位被过滤。现在 allow_storage_location=true 时直接分配储位,无视库位类型的可分配/启用限制", + "methods": [ + "order.pendingOrder.allocateStorage" + ], + "notes": [ + "app/service/systems/order_storage_allocation.js allocatePicking:storageRows 查询的 locationType include where(allow_allocation:1/is_active:1)改为仅当 allowStorageLocation=false 时生效;true 时不再过滤库位类型限制", + "无候选库位时的缺货诊断 diagnoseStorageTypeRestriction 仅在 allowStorageLocation=false 时执行,避免「库位类型不可分配/未启用」被误报为缺货原因", + "可分配库存查询完成日志补充 allowStorageLocation 字段", + "同步更新 methods/system.json:order.pendingOrder.allocateStorage 描述与 allow_storage_location 参数说明" + ], + "module": "order" + }, + { + "version": "2026.08.27-order-export-stock-query", + "date": "2026-08-27", + "type": "fixed", + "summary": "order.export 修复携带产品查询(where.stock_query)时导出失败(Unknown column ... in where clause):导出链路补齐 stock_query 虚拟筛选提取,按商品编码/名称/ID/条码解析为订单ID集合后注入主查询,与 order.list 语义一致", + "methods": [ + "order.export" + ], + "notes": [ + "app/service/systems/order_export.js exportOrders:在 extractBuyerMessageHasVirtualFilter 之后新增 extractStockQueryVirtualFilter,从 where 提取并移除 stock_query,避免其残留在 where 中经 buildWhere/parseWhereConditions 被当作数据库字段解析,导致 SQL Unknown column 报错", + "stockQuery 非空时调用 findOrderIdsByStockQuery(商品编码/名称/ID/条码模糊匹配 → stock_id 集合 → order_items 关联订单ID),再经 appendOrderIdsFilterToWhere 注入主查询;无匹配商品时导出结果为空,与 order.list 行为一致", + "stockQuery 模块名取 target.defaultWhereModuleName || target.sortModuleName || 'order',保证仅传 table_type 时按表类型推导对应模块(current/history 等)的 order_items 表类型" + ], + "module": "order" + }, + { + "version": "2026.08.27-storage-entry-get-total-order-lines", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.entry.get 响应新增 total_order_lines(entryOrder 内)、total_quantity(应入库总数量)、received_quantity(已入库总数量)字段", + "methods": [ + "storage.entry.get", + "storage.entry.getStore" + ], + "notes": [ + "app/service/systems/storage/entry.js get:返回 data.entryOrder 新增 total_order_lines(直接取 wms_entry_order.total_order_lines)", + "data 顶层新增 total_quantity = 明细 planned 之和(应入库总数量)、received_quantity = 明细 completed 之和(已入库总数量)", + "getStore 共用同一底层实现,自动获得这些字段", + "同步更新 get 方法 JSDoc 注释" + ], + "module": "storage.entry" + }, + { + "version": "2026.08.27-directInbound-receiving-stock-occupancy", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.entry.commit 导入/PDA 入库支持绑定收货单占用:带 receiving_detail_id 的导入记录优先按明细扣减,未带 receiving_detail_id 的剩余导入量按 stock_id 匹配收货单明细占用并回写收货单入库状态", + "methods": [ + "storage.entry.commit", + "storage.directInbound.commit" + ], + "notes": [ + "app/service/systems/inbound_direct_log.js commit onSuccess 事务内新增 _applyReceivingStockOccupancy:绑定收货单(wms_entry_order_receiving)存在时,汇总未携带 receiving_detail_id 的导入记录数量,按 stock_id(=收货明细 system_product_id)匹配占用", + "优先级:携带 receiving_detail_id 的记录先由 _syncReceivingStorageStatus 按明细扣减,随后剩余量复用 storage.entry._applyReceivingInboundUsage 按 stock_id 依次占用收货明细剩余可入数量(actual_quantity - stored_quantity),事务内行锁防并发超分", + "占用后回写收货明细 stored_quantity/storage_status(all/partial),并汇总更新收货单主表 storage_status", + "未绑定收货单或无剩余导入量时跳过,不影响原有非绑定模式入库行为", + "storage.entry._applyReceivingInboundUsage 日志前缀由 [storage.entry.quickInbound] 改为 [storage.entry](方法现被 quickInbound 与 commit 两个流程复用)" + ], + "module": "storage.entry" + }, + { + "version": "2026.08.27-storage-management-replenishmentDemand-owner-filter", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.management.replenishmentDemand 新增货主筛选:store_id(单值或数组)或 where.store_id 传入,仅返回指定货主的 SKU,summary 同步只统计筛选后数据", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "app/service/systemMethods/storage/management.js replenishmentDemand:解析 store_id / store_ids / where.store_id(单值/数组),归一化为正整数数组去重,非法值(非正整数)抛错;空值不筛选。", + "app/service/systems/storage/management.js replenishmentDemand:options.storeIds 构建 Set,组装输出循环内非命中货主 SKU 直接跳过,list 与 summary 统计口径一致(仅含筛选货主)。", + "同步更新 methods/system.json 参数文档(新增 store_id 参数说明)。" + ], + "module": "storage.management" + }, + { + "version": "2026.08.27-quickInbound-receiving-intersection", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.entry.quickInbound 支持绑定收货单交集直入:有绑定时按 stock_id 只取收货单中剩余可入数量(actual_quantity - stored_quantity)与入库明细的较小值直入,并回写收货单明细已入库数量与收货单入库状态", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "app/service/systems/storage/entry.js quickInbound:新增绑定收货单查询(wms_entry_order_receiving),按 stock_id(=收货明细 system_product_id)聚合剩余可入数量 actual_quantity - stored_quantity", + "入库明细实际直入量 = min(计划数量, 剩余可入数量);无交集商品跳过(明细 received_quantity 写 0),全部无交集或剩余为 0 时返回 400「收货单中无交集商品或剩余可入数量不足,无法快捷直入」", + "未绑定收货单保持原行为:按明细计划数量全量直入", + "存在截断/跳过明细时 isFin=false(confirmType=1, PARTFULFILLED)回传奇门/API", + "新增 _applyReceivingInboundUsage 事务内回写:行锁重读收货明细,按明细 id 升序分配本次入库量(每个明细最多分配其剩余可入数量),更新 stored_quantity(使用了多少写多少)与 storage_status(all/partial),并汇总更新收货单主表 storage_status", + "收货单主表 storage_status 按实际数量判定:全部明细 stored_quantity >= actual_quantity 才置 all;有部分入库置 partial;全部未入库置 none——收货单未全部使用所有商品时不会转为全部入库", + "入库单明细 received_quantity 改为写实际入库量(原来写计划数量)", + "响应新增 plan_quantity(计划入库总数量),total_quantity 语义改为实际入库总数量,items_count 语义改为实际入库明细条目数" + ], + "module": "storage.entry" + }, + { + "version": "2026.08.27-storage-management-replenishmentDemand-owner-barcode", + "date": "2026-08-27", + "type": "enhanced", + "summary": "storage.management.replenishmentDemand 响应 list 每项新增 store_id(货主ID)、store_name(货主名称)、barcodes(SKU 条码列表)字段", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "app/service/systems/storage/management.js replenishmentDemand:StockWarehouse 三处查询(严格/宽松/终极兜底)attributes 均新增 store_id,stockInfoMap 记录货主ID。", + "新增货主名称查询:StoreWarehouse(store_remask 签约表备注名)优先、Store(company_name 商家公司名)兜底;新增 StockBarcode 按 stock_id 批量查询条码并分组为 barcodes: [{id, barcode}]。", + "货主与条码查询与库存查询为顺序执行(货主/条码三表在 Promise.all 内并行)。", + "响应字段:store_id (number) 货主ID;store_name (string) 货主名称;barcodes (array) 条码列表,children: id (number)/barcode (string)。", + "同步更新 methods/system.json 响应文档。" + ], + "module": "storage.management" + }, + { + "version": "2026.08.27-order-export-columns", + "date": "2026-08-27", + "type": "enhanced", + "summary": "order.export 新增 export_columns/exportColumns 导出表头字段白名单参数(中文表头数组):不传或空数组输出全部列;传入时仅输出指定列;校验枚举覆盖 waybill/item 两种模式全部 51 个中文表头,非法表头抛错并列出非法值。", + "methods": [ + "order.export" + ], + "notes": [ + "app/service/systems/order_export.js:新增 ORDER_EXPORT_ALL_COLUMN_HEADERS(waybill/item 两种模式表头并集,共 51 个);getOrderExportColumns(mode, selectedHeaders) 支持按中文表头过滤;新增 normalizeExportColumns(数组去重/trim/非法值抛错);exportOrders 读取 export_columns/exportColumns(下划线优先)并作用到初始 sheet 与自动续写的后续 sheet(resolvedColumns 复用)", + "app/service/systemMethods/order/index.js export:解构 export_columns/exportColumns 并透传数组,未传时传空数组(输出全部列)", + "methods/system.json order.export 新增 export_columns/exportColumns 参数文档:枚举全量 51 个中文表头,并标注仅 waybill 模式输出(系统订单号、外部订单号、平台单号、抓取波次号、商品明细)与仅 item 模式输出(订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量)的字段" + ], + "module": "order" + }, + { + "version": "2026.08.26-wave-batchList-store-id-filter", + "date": "2026-08-26", + "type": "enhanced", + "summary": "order.wave.batchList 新增 where.store_id(货主ID)过滤:支持单值/数组/{operator,value} 结构(正整数),返回包含任一筛选货主订单的波次(含混合货主波次);未在 wms_wave_batch 加冗余 store_id 字段,通过订单分表 INNER JOIN 聚合匹配,零迁移零回填零口径漂移风险。", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js buildBatchListWhereClause:allowedFields 新增 store_id,normalizeStoreIdList 归一化(单值/数组/{operator,value}→正整数数组去重,非法值抛错),返回值新增 storeIds", + "batchList:storeIds 非空时在 wave_order_stats 之后追加 INNER JOIN wave_owner_filter(订单表 od.wave_id 匹配且 od.store_id IN (:whereStoreIds) 按 wave_id 分组),listSql/countSql replacements 新增 whereStoreIds", + "设计决策:不在 wms_wave_batch 增加 store_id 冗余字段(混合填0),理由——batchList 原本就必须 LEFT JOIN 订单表做状态聚合,货主过滤挂同一次 JOIN 零额外成本;订单表已有 store_id 单列索引;冗余需覆盖抓取入波/策略任务建波/batchRemoveOrders/batchRemoveExceptionOrders 等 10+ 处写入点维护,遗漏即口径漂移;owner_name 展示已实时聚合订单 store_id,避免双口径", + "实测:{operator:'',value:[1000281,1000000]} 过滤 wave_type=1&source=0 返回 196 条(库中该货主订单波次);单值/数组形式均返回 5 条;不存在货主 0 条;非法值报错;无过滤 baseline 278 条不受影响;原请求含 wave_status=0 返回 0 因库中活动波次均为 status=1", + "同步更新 methods/system.json 的 batchList where 白名单说明" + ], + "module": "order.wave" + }, + { + "version": "2026.08.26-wave-batchList-store-name", + "date": "2026-08-26", + "type": "enhanced", + "summary": "order.wave.batchList 响应每条记录新增 store_name(货主信息):按波次内订单 store_id(货主ID)聚合,所有订单均为同一货主时返回货主名称,否则(多个货主、存在无货主订单或空波次)返回“混合”;货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js batchList:wave_order_stats 子查询新增 owner_distinct_count(COUNT(DISTINCT NULLIF(store_id,0)))、owner_named_count(SUM 非空判定)、owner_store_id(MAX(NULLIF(store_id,0)))三个聚合字段,listSql SELECT 透出", + "新增 resolveWaveBatchOwnerStoreNameMap:仅对满足单货主的波次批量查 StoreWarehouse(store_id+warehouse_id)取 store_remask,再查 wms_store.company_name 兑底,remask 覆盖 company_name;查询失败仅告警不影响列表", + "判定口径:orderCount>0 且 ownerDistinctCount===1 且 ownerNamedCount===orderCount 且 ownerStoreId>0 才返回货主名称,否则返回“混合”(0 单波次同样返回“混合”)", + "货主名称口径与 afterSale._enrichListStoreNames、inventory.store_name 一致(store_remask 优先、company_name 兑底);早期草稿曾按 shop_nick 店铺名称实现,已按项目货主口径修正", + "同步更新 methods/system.json 的 batchList 描述与 response.list 字段说明" + ], + "module": "order.wave" + }, + { + "version": "2026.08.26-workbench-queryOrder-pack-status", + "date": "2026-08-26", + "type": "enhanced", + "summary": "工作台 workbench.business(queryOrder) 查询订单增强:接入订单序列表(wms_order_id_location_*)优先定位分表,未命中按 current→dispatch 回退遍历;响应 order 对象新增 pack_status 字段(散单/团购均返回)。", + "methods": [ + "workbench.business" + ], + "notes": [ + "app/service/systems/workbench.js _queryOrder 步骤2:先经 orderDeliveryFactory.getOrderLocation(orderId, warehouseId) 获取序列表位置,命中则优先查对应分表,失败/未命中保持原 current→dispatch 遍历,与 _sendWeight/waybill/order_express 等模块的序列表优先定位语义一致", + "_queryOrder 响应 order 对象新增 pack_status(none/padding/fin/error),与 pick_status/recheck_status 等状态机并列,工作台可根据打包状态判断该单是否已打包", + "备注:_packOrder 订单查找仍按 delivery_order_code 双表遍历(序列表按 id 定位,发货单号场景暂不适用)" + ], + "module": "workbench" + }, + { + "version": "2026.08.26-finishPack-sync-order-pack-status", + "date": "2026-08-26", + "type": "fixed", + "summary": "修复打包任务结束事件不更新订单打包状态的问题:workbench.finishPack 结束任务后同步更新关联订单 pack_status 为 fin(散单按订单更新,团购按波次批量更新未拦截订单)并写完成操作日志;order.packing.setEndTime 手动结束同样同步订单;打包操作日志文案按任务状态区分(开始打包/打包完成),不再在开始打包时误写“打包完成”。", + "methods": [], + "notes": [ + "问题定位:波次 B2026082503311(团购 7 单)开始打包时 packOrder(status=1) 写入的日志前缀硬编码为“团购打包完成”,实际尾部为“任务状态: 打包中”;设备结束事件走 finishPack 仅更新 wms_pack_task(end_time/status=2),未更新订单,导致订单 pack_status 停留在 padding", + "app/service/systems/workbench.js 新增 _updateOrderPackStatus:遍历 current+dispatch 分表,散单按 order_id 更新单笔,团购按 wave_id 批量更新(intercept_status 空值按 none 处理,拦截订单跳过),异常仅记日志不影响主流程;_packOrder 步骤6.5 改为复用该方法", + "app/service/systems/workbench.js _finishPack:任务结束后按 pack_mode 判定散单/团购,调用 _updateOrderPackStatus(packStatus=2) 同步订单,并按任务记录(含 operator_text 回填操作人)写入完成操作日志", + "app/service/systems/order_packing.js setEndTime:任务由未完成转为已完成时同样调用 _updateOrderPackStatus 同步订单,与 finishPack 语义对齐", + "app/service/systems/workbench.js _writePackOperationLog:日志前缀按 status 区分——status>=2 写“打包完成”,否则写“开始打包”,保留原有字段变更描述", + "定时任务 auto_finish_pack_task 超时自动结束仅关闭任务记录、不更新订单(保持原语义,避免超时误标订单完成),如需要可在后续版本评估同步" + ], + "module": "workbench" + }, + { + "version": "2026.08.26-stockout-listLogs", + "date": "2026-08-26", + "type": "added", + "summary": "新增 storage.stockout.listLogs 出库单操作日志查询接口:按出库单ID或出库单号分页查询 wms_operation_log(business_type=stockout,business_id=出库单ID),覆盖转订单/确认/修改/取消等 STOCKOUT_* 操作,按创建时间倒序;配套 operationLog.queryStockoutLogs 服务方法与权限 565。", + "methods": [ + "storage.stockout.listLogs" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js 新增 listLogs:支持 id 或 stockout_order_code 定位(出库单号先查表换ID),pagination.page/pageSize(兼容 page_size);出库单不存在返回空列表不报错;仓库上下文取 ctx.user.store_id", + "app/service/systems/operation_log.js 新增 queryStockoutLogs:复用 queryLogsByBusinessType(query, 'stockout')", + "database/migrations/20260826100000-add-stockout-listLogs-permission.js:权限 565,授权角色 8/26/28/29/30,开发库已执行", + "storage.stockout.listItems 出库单明细接口此前已存在(按 stockout_order_code/id 查 wms_order_stockout_items),本次仅补 listLogs 文档", + "实测:listLogs 按 stockout_order_code 与 id=22 均返回分页日志(STOCKOUT_TO_ORDER/STOCKOUT_UPDATE_INFO,含操作人/时间/消息/平台名),pagination.total=4 正确;注意权限迁移后短时间内用户权限上下文缓存可能未刷新导致 403,刷新后正常" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.26-stockout-order-sync-channel", + "date": "2026-08-26", + "type": "added", + "summary": "订单回传区分 STOCKOUT 创建渠道:待处理订单同步入口(syncOrderIds)按 create_channel 路由新增 syncStockoutOrders,回传时把订单实际快递编码/运单号写回出库单(express_code/express_name/waybill_code/waybill_codes),并按出库单来源通知外部(QM→奇门 taobao.qimen.stockout.confirm,API→OpenAPI 回调 event=stockout_completed,WMS 内部来源直接成功);通知成功后才扣减订单库存并完成同步(sync_status=fin、出库单 COMPLETED/SUCCESS),失败则订单 sync_status=error 标记待处理异常、出库单 sync_status=FAILED 记录失败原因。", + "methods": [ + "order.pendingOrder.syncOrderIds" + ], + "notes": [ + "app/service/systems/order_async.js 新增 syncStockoutOrders/syncStockoutOrdersInternal/processStockoutOrderInternal/notifyStockoutExternalInternal/buildStockoutConfirmDataInternal/finalizeSuccessfulStockoutSyncInternal:反查出库单(订单 source_order_codes 首项或明细 source_order_code),运单号仅认 wms_order_express 表(不回退订单主表 express_code 面单前置);收尾事务内写回出库单 + 订单明细 outbound 扣库存 + sync_status=fin,SELECT FOR UPDATE 防重幂等", + "app/service/systems/order_storage_allocation.js syncOrderIds 渠道路由新增 STOCKOUT 分支(原落入 MANUAL 兜底,不通知外部)", + "出库单已 SUCCESS 的重试场景跳过重复通知,直接收尾;订单未分配运单号时回传失败并提示", + "所有回传入口(pendingOrder.syncOrderIds 异步包装、express_platform 自动同步回传)均汇聚到同一路由,改动一处覆盖全部", + "订单表无 sync_message 列:回传失败提示落在 order_flag 字段(markPendingExceptionInternal 同步置 inspection_status=error/step=3)", + "实测失败路径:测试订单 122172(TEST-SO-20260826004828-003 转单)回传奇门 stockout.confirm 返回 JST_Error,订单 sync_status=error + order_flag 提示,出库单保持 TRANSFERRED + sync_status=FAILED + sync_message 记录原因", + "实测成功路径:出库单 source_type 临时改 WMS(内部来源直接成功)触发回传,订单 sync_status=fin/order_flag 清空/step=2,出库单 COMPLETED/SUCCESS + 写回 express_code=SF/waybill_code/waybill_codes,库存 101389 quantity 100→95、locked 8→3,流水闭环 LOCK(QM_STOCKOUT)→UNLOCK(转单释放)→LOCK(DELIVERY_ORDER)→OUTBOUND(订单出库)" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.08.26-stockout-cancel", + "date": "2026-08-26", + "type": "added", + "summary": "新增 storage.stockout.cancel 出库单取消:仅 CREATED/PENDING 允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水)并置 CANCELLED,写 wms_operation_log 操作日志(STOCKOUT_CANCEL);TRANSFERRED/COMPLETED 禁止取消。新增权限 564 并授权。", + "methods": [ + "storage.stockout.cancel" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js 新增 cancel:复用 lockItemStorages 负数量释放(锁定不足幂等跳过),与状态更新、操作日志同事务;仓库隔离与 confirm/updateInfo 一致", + "database/migrations/20260826093000-add-stockout-cancel-permission.js:权限 564,授权角色 8/26/28/29/30,开发库已执行", + "实测:取消测试单后 locked_quantity 101379 3→2,UNLOCK 流水(出库单取消释放锁定)与 STOCKOUT_CANCEL 操作日志均落库", + "同步更新 methods/system.json 新增 cancel 接口文档" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.26-stockout-operation-log", + "date": "2026-08-26", + "type": "added", + "summary": "storage.stockout 链路补写 wms_operation_log 操作日志(businessType=stockout):confirm 直出成功、toOrder 转单成功、updateInfo 修改均写操作记录;新增 updateInfo API 权限 563 并授权;修复 updateInfo 证件号参数名与出库单 ID 冲突。", + "methods": [ + "storage.stockout.confirm", + "storage.stockout.toOrder", + "storage.stockout.updateInfo" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js 新增 _writeStockoutOperationLog(operationLog.createOperationLogs,失败仅告警不影响主流程):confirm 成功路径与状态更新同事务写 STOCKOUT_CONFIRM(含释放锁总量);toOrder 转单后写 STOCKOUT_TO_ORDER(含新订单号);updateInfo 写 STOCKOUT_UPDATE_INFO(含改动字段摘要)", + "修复:updateInfo 收件人证件号参数由 id 改为 receiver_id(原与出库单ID参数冲突,会把 data.id 误写入 receiver_id 字段)", + "database/migrations/20260826090000-add-stockout-updateInfo-permission.js:新增权限 563(storage.stockout.updateInfo),授权角色 8/26/28/29/30,开发库已执行", + "实测:updateInfo 修改后 wms_operation_log 落库(business_type=stockout、operation_code=STOCKOUT_UPDATE_INFO、operator 阿猫、message 含改动摘要)" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.26-stockout-confirm-release-lock", + "date": "2026-08-26", + "type": "fixed", + "summary": "storage.stockout.confirm 直出确认后释放出库单创建时占用的库存锁定:出站通知成功后,事务内逐明细 lockItemStorages(-plan_qty, orderType=QM_STOCKOUT) 释放锁定并自动写 UNLOCK 流水,与状态推进到 COMPLETED 同事务提交,失败回滚可重试;释放遇\"锁定不足\"视为幂等成功跳过。", + "methods": [ + "storage.stockout.confirm" + ], + "notes": [ + "修复前:confirm 直出成功后 locked_quantity 一直占用(出库单无取消入口,锁只能靠转订单释放)", + "出站通知失败时锁保持、状态不变(sync_status=FAILED),重试 confirm 成功后才会释放;已释放场景(锁定不足)跳过不阻断", + "实测:本地 confirm 真实出站淘宝奇门返回 JST_Error 单号转换失败,锁保持(101379.locked=3/101389.locked=8 不变),符合设计;释放+UNLOCK 流水由 lockItemStorages 负数量链路保证" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.26-directPutaway-default-location", + "date": "2026-08-26", + "type": "updated", + "summary": "storage.inventory.directPutaway 默认库位改为读取仓库设置:直入库存写 wms_storage 时,收货明细 space_id 无效则使用 wms_store.subject_config.default_location_id(经 deliveryOrder.getStoreSubjectConfig 缓存优先读取),未设置时兜底库位 1。", + "methods": [ + "storage.inventory.directPutaway" + ], + "notes": [ + "app/service/systems/storage/inventory.js directPutaway:步骤 10 写 wms_storage 的 spaceId 由硬编码 1 改为 defaultSpaceId(收货明细有库位仍按其库位),defaultSpaceId 在方法前段读取仓库设置(正整数有效才采用,否则 1),读取失败仅告警不影响入库", + "与 storage.receiving.addDetail 默认库位口径一致(仓库设置优先,兜底 1)", + "同步更新 methods/system.json directPutaway 的库位规则说明" + ], + "module": "storage.inventory" + }, + { + "version": "2026.08.26-receiving-addDetail-default-location", + "date": "2026-08-26", + "type": "updated", + "summary": "storage.receiving.addDetail 默认库位改为读取仓库设置:新增明细时 space_id 默认取 wms_store.subject_config.default_location_id(经 deliveryOrder.getStoreSubjectConfig 缓存优先读取),未设置时兜底库位 1;前端传入 item.space_id 时仍按传入值。", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "app/service/systems/storage/receiving.js addDetail:默认明细 space_id 由硬编码 1 改为优先读仓库设置 default_location_id(正整数有效才采用),否则兜底 1;读取失败仅告警不影响创建", + "依赖 deliveryOrder.getStoreSubjectConfig(缓存 10 分钟),saveSettings 保存仓库设置时会同步清理该缓存键", + "同步更新 methods/system.json addDetail 的 item.space_id 描述" + ], + "module": "storage.receiving" + }, + { + "version": "2026.08.26-warehouse-setting-default-location", + "date": "2026-08-26", + "type": "added", + "summary": "仓库设置(wms_store.subject_config)新增\"默认库位\"字段 default_location_id(type location):setting.warehouse.getFieldMeta 字段元信息新增该字段(不返回库位选项列表,库位数量大,前端按仓库搜索选择),saveSettings 传入时校验库位属于当前仓库,否则报 400 拒绝写入。", + "methods": [ + "setting.warehouse.getFieldMeta", + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "app/service/systems/setting/warehouse.js WAREHOUSE_SETTING_FIELDS 新增 default_location_id(名称:默认库位,type location,default null,描述:仓库未指定库位入库/上架时使用的默认库位);getFieldMeta 不注入库位选项列表(库位数量大,前端按 type=location 自行按仓库搜索库位)", + "saveSettings 新增 validateDefaultLocation:传入 default_location_id 时校验其属于当前仓库,否则 400 '默认库位 {id} 不属于当前仓库';传 null/空清空", + "app/model/store.js DEFAULT_SUBJECT_CONFIG 新增 default_location_id: null;normalizeSubjectConfig 新增正整数校验分支(空值置 null)", + "同步更新 methods/system.json:getSettings 响应、saveSettings 参数补充 default_location_id 说明" + ], + "module": "setting.warehouse" + }, + { + "version": "2026.08.25-stockout-updateInfo-transferred", + "date": "2026-08-25", + "type": "added", + "summary": "新增 storage.stockout.updateInfo 修改出库单信息接口,并引入 TRANSFERRED 状态:转订单成功后出库单置为 TRANSFERRED(已转订单),该状态下禁止一键出库。", + "methods": [ + "storage.stockout.updateInfo", + "storage.stockout.toOrder" + ], + "notes": [ + "storage.stockout.updateInfo:修改范围限收件人(name/tel/mobile/company/email)、地址(province/city/area/town/detailAddress/zipCode/countryCode)、快递编码(express_code,自动解析 express_name)、来源平台(source_platform_code/name),未传入不修改;仅 CREATED/PENDING 状态允许修改(400);修改后收货信息不完整(name、(tel/mobile) 其一、省市区镇详细地址)禁止提交并列出缺失字段", + "数据库迁移 20260825180000-add-transferred-status-and-platform-to-wms-order-stockout.js:order_status ENUM 追加 TRANSFERRED + 新增 source_platform_code(50)/source_platform_name(200) 列,开发库已执行并核验", + "app/model/order_stockout.js:ENUM 补 TRANSFERRED、新增两平台字段、新增 isTransferred() 辅助方法", + "storage.stockout.toOrder:转单成功后 order_status 置 TRANSFERRED(原 CANCELLED);deliveryOrder.sourcePlatformCode 优先用出库单已存平台,为空走兜底平台;confirm(一键出库)经 canConfirm 拒绝 TRANSFERRED 状态", + "同步更新 methods/system.json:新增 updateInfo 接口文档,更新 toOrder 描述与状态说明", + "实测(2026-08-26,测试单 20):正常修改 name/mobile/detailAddress + express_code=SF(自动解析 express_name=顺丰速运)+ source_platform_code 均落库,未传字段不变;detailAddress 清空被拦截(收货信息缺失,禁止提交:缺少 detailAddress(详细地址));COMPLETED 单被拦截(不允许修改);操作日志 STOCKOUT_UPDATE_INFO 含改动字段摘要(收件人姓名、移动电话、详细地址、快递编码、来源平台);测试数据已恢复原貌、日志保留" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.25-stockout-toOrder-receiver-validate", + "date": "2026-08-25", + "type": "fixed", + "summary": "storage.stockout.toOrder 增加收货信息必填校验与同快递建单:name、(tel/mobile) 至少一项、省市区镇详细地址缺失时拒绝转单并提示缺失字段;收货信息优先接口传入,未传回填出库单已存的 receiver_* 字段;新订单快递编码沿用出库单 express_code(相同快递),平台不传 sourcePlatformCode 走兜底平台。", + "methods": [ + "storage.stockout.toOrder" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js toOrder:释放锁前先合并收货信息(storedReceiverInfo 从出库单 receiver_company/name/zip_code/tel/mobile/email/country_code/province/city/area/town/detail_address 回填,接口 receiverInfo 非空字段覆盖)并逐项校验,缺项返回 fail 提示缺失字段列表", + "建单参数:logisticsCode = 出库单 express_code(create 时已解析的系统快递编码),不传 sourcePlatformCode(resolvePlatformSnapshot 自动使用合约兜底平台)", + "同步更新 methods/system.json 中 storage.stockout.toOrder 的 description 与 receiverInfo 参数说明" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.25-stockout-receiver-info-db", + "date": "2026-08-25", + "type": "added", + "summary": "wms_order_stockout 表新增 13 个收件人字段(receiver_* 前缀),对应奇门 stockout.create 报文 receiverInfo 节点(company/name/zipCode/tel/mobile/email/countryCode/province/city/area/town/detailAddress/id),为出库单解析收件人信息与转订单回填做准备。", + "methods": [ + "storage.stockout.toOrder", + "stockout.create" + ], + "notes": [ + "database/migrations/20260825170000-add-receiver-info-to-wms-order-stockout.js 新增 13 列:receiver_company(200)/receiver_name(50)/receiver_zip_code(50)/receiver_tel(50)/receiver_mobile(50)/receiver_email(50)/receiver_country_code(50)/receiver_province(50)/receiver_city(50)/receiver_area(50)/receiver_town(50)/receiver_detail_address(200)/receiver_id(50),均允许 NULL;up/down 均带 describeTable 幂等保护", + "app/model/order_stockout.js 同步新增 13 个字段定义(remark 与 express_code 之间)", + "开发库已执行迁移并核验 SHOW COLUMNS 全部落库;生产库需在发布时按 db-migration-envs 规范执行" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.25-storage.stockout.toOrder", + "date": "2026-08-25", + "type": "added", + "summary": "storage.stockout.toOrder 从占位接口落地为真实实现:将非订单出库单(wms_order_stockout)转为正式销售订单,新订单 create_channel 固定为 STOCKOUT;转单时释放出库单库存锁定(QM_STOCKOUT)并转由新订单重新锁定,成功后原出库单置为 CANCELLED 并写入 extend_props.transferred_order_id(幂等,重复调用直接返回已转订单信息)。", + "methods": [ + "storage.stockout.toOrder" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js toOrder 实现:入参 id(出库单ID,必填)、delivery_order_code(可选,不传自动生成 SK 前缀单号)、receiverInfo(可选收件人信息);校验出库单存在且 order_status 为 CREATED/PENDING(否则 400),extend_props.transferred_order_id 存在时幂等返回已转订单", + "锁转移:事务内逐明细 lockItemStorages(-plan_qty, orderType=QM_STOCKOUT) 释放出库单锁 → 调 deliveryOrder.addOrder(data, info, 'STOCKOUT') 建单并重新锁库存 → 建单失败/订单号重复时 _restoreStockoutLocks 补偿恢复锁定;建单成功后更新出库单 order_status=CANCELLED 并记录 transferred_order_id/transferred_order_code/transferred_at", + "新订单明细手工单风格传 stockId(wms_stock_warehouse.id),sourceOrderCode 写入出库单号便于追溯;create_channel=STOCKOUT 不触发 addOrder 的 API/QM 异步流程,也不会被自动同步任务推送", + "app/service/systemMethods/storage/delivery.js toOrder 兼容转发改为透传 data 参数", + "app/service/systemMethods/order/base.js CREATE_CHANNEL_LABELS 新增 STOCKOUT: '出库转单',订单工作台渠道列正确显示中文标签", + "同步更新 methods/system.json 中 storage.stockout.toOrder 接口文档" + ], + "module": "storage.stockout" + }, + { + "version": "2026.08.25-storeWarehouse.store.createUser", + "date": "2026-08-25", + "type": "added", + "summary": "新增 storeWarehouse.store.createUser:为货主创建用户。按用户名查询平台账号:账号不存在则自动注册并随机生成 12 位密码返回;两种情况统一完成货主工号绑定并授予货主管理员角色(wms_role.id=5)。幂等:重复调用不会重复创建账号或绑定。", + "methods": [ + "storeWarehouse.store.createUser" + ], + "notes": [ + "app/service/systems/store_warehouse.js 新增 createUser:校验 username(必填 + 3-50 位字母数字下划线,400)与 store_id(必填正整数,400)→ 货主存在校验(404)→ 按用户名查询账号(不存在则复用 auth.user.register 注册并随机生成 12 位密码)→ 事务内 AccountStoreEmployee.findOrCreate 绑定货主工号(已存在且 status!=1 时恢复为 1)→ 校验货主管理员角色 wms_role.id=5 已初始化(缺失抛 500)→ EmployeeRole.findOrCreate 授予角色(幂等)", + "app/service/systemMethods/storeWarehouse/store.js 新增 createUser 包装方法;构造器 _noNeedRight/_noNeedAuth 白名单加入 createUser(isNeedLogin=true 需登录、isNeedAuth=false)", + "响应 data:account_id、username、store_id、created(是否本次新建账号;false 表示账号已存在仅完成授权)、password(仅 created=true 时返回 12 位随机明文密码)", + "同步更新 methods/system.json 中 storeWarehouse.store.createUser 接口文档" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.08.25-returnUnpack.forceRecord", + "date": "2026-08-25", + "type": "added", + "summary": "新增 returnUnpack.forceRecord:强制重新录制拆包视频。参考 order.packing.forceRecord,入参 id(拆包单ID);校验仓库录制电脑(wms_print_computer is_recording=true)在线后,将 wms_return_unpack_video 视频记录重置为 created 并清空 video_url,再向打印服务 /record/force 推送 { unpack_id } 触发重新录制。", + "methods": [ + "returnUnpack.forceRecord" + ], + "notes": [ + "app/service/systems/return_unpack.js 新增 forceRecord:_findByIdChecked 仓库隔离校验(不存在 404 / 跨仓库 403)→ 查询录制电脑(无则 400)→ Redis 在线键 warehouse:{warehouseId}:printer:{computerId} 校验在线(不在线 400)→ 重置视频状态为 created 并清空 video_url → POST {printService.url}/record/force 推送 { unpack_id }(失败抛 500 业务错误)", + "app/service/systemMethods/returnUnpack.js 新增 forceRecord 包装方法(与 submit 同层,走 _call 统一错误包装)", + "database/migrations/20260825120000-add-return-unpack-force-record-permission.js 新增权限记录 562(returnUnpack.forceRecord,API:退回拆包强制录制),授权角色与作业类 540-545 一致:仓库组-员工(27)/仓库组-主管(26)", + "同步更新 methods/system.json 中 returnUnpack.forceRecord 的接口文档" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.24-storage.entry-receivingCompare-merge", + "date": "2026-08-24", + "type": "fixed", + "summary": "storage.entry.receivingCompare 对比主体修正:多个收货单先合并明细,再与入库单做一次对照。原实现每个收货单各对照一遍,入库计划数量被重复展开多份,前端对比表格出现重复行。", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "app/service/systems/storage/entry.js receivingCompare 重写:批量校验收货单后合并全部有效收货单明细,新增 _buildMergedComparison(替代 _compareSingleReceiving)输出单一对照视图", + "出参结构调整:comparisons[](按收货单拆分)改为 comparison[](合并后逐行对照,每个入库明细仅一行)+ receiving_only[] + summary;matched 行新增 receiving_quantity/receiving_allocated/receiving_available(合并值)与 receiving_sources[](各收货单来源明细),entry_only 行对应数量为 0 且 receiving_sources 为空", + "total_summary.matched_count 语义调整为有效参与对比的收货单数(原为处理成功的对照数);无效收货单仍进入 errors[]", + "同步更新 methods/system.json 中 receivingCompare 的 response 结构说明" + ], + "module": "storage.entry" + }, + { + "version": "2026.08.23-returnUnpack.video-url-cdn-domain", + "date": "2026-08-23", + "type": "fixed", + "summary": "修复拆包视频地址未拼接 CDN 域名的问题:returnUnpack.list / returnUnpack.detail / returnUnpack.videoList / returnUnpack.queryByWaybill 输出的 videos[].video_url 此前直接返回相对路径(如 /recordings/...),与 order.packing 输出完整 URL 的口径不一致。现在按打包侧相同规则拼接 http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path}(录制电脑从 wms_print_computer 按 is_recording=true 获取,无录制电脑时保持原始路径)。", + "methods": [ + "returnUnpack.list", + "returnUnpack.detail", + "returnUnpack.videoList" + ], + "notes": [ + "app/service/systems/return_unpack.js 新增 _getRecordingComputerId/_buildVideoUrl(与 order_packing.js 同口径,带实例级缓存)", + "_enrichRow 视频派生块内对 videos[].video_url 拼接域名(覆盖 list/detail/submit 输出)", + "videoList 按 unpack_id 反查 warehouse_id 后拼接;queryByWaybill(inbox 查退回)的 videos 同样拼接", + "同步更新 methods/system.json 中 returnUnpack.list 与 returnUnpack.detail 的响应字段描述" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.23-stock.warehouse-cache-invalidate-on-update", + "date": "2026-08-23", + "type": "fixed", + "summary": "修复商品资料更新后 getStockDetails 详情缓存未清除的问题:saveWarehouseStock/handleBatchChange 使用 StockWarehouse.update 批量更新(不触发实例级 afterUpdate hook),导致 cache:stock_detail:{warehouseId}:{stockId} 旧数据在 TTL 内持续被读取(如 need_recheck 修改后复核扫描仍返回旧值)。现在两个编辑入口更新成功后显式调用 stockWarehouse.invalidateStockDetailCache 清除对应缓存。", + "methods": [ + "stock.warehouse.saveWarehouseStock", + "stock.warehouse.handleBatchChange" + ], + "notes": [ + "app/service/systems/stock_store.js saveWarehouseStock 提交事务后调用 service.systems.stockWarehouse.invalidateStockDetailCache(id, warehouseId)(失败仅告警不阻断主流程)", + "同文件 handleBatchChange 批量更新后按 ids 批量清除详情缓存(Promise.allSettled,失败不阻断返回)", + "实证验证:更新后 Redis 缓存 key 被删除,复核扫描/统一查询立即读取到新值" + ], + "module": "stock" + }, + { + "version": "2026.08.23-recheckOrder.stock-need-recheck", + "date": "2026-08-23", + "type": "enhanced", + "summary": "order.recheckOrder.scanOrder / scanTask 返回报文的 stock 明细新增 need_recheck 字段(Y=需要复核,N=不需要复核,缺省 Y):散单路径 enrichOrdersWithStock 组装与团购路径 buildGroupWaveList 的 stocks 映射均透出,供前端按商品判断是否免复核。", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.scanTask" + ], + "notes": [ + "app/service/systemMethods/order/recheckOrder.js enrichOrdersWithStock stock 对象新增 need_recheck(取 getStockDetails 返回值,缺省 'Y')", + "同文件 buildGroupWaveList 的 stocks 映射新增 need_recheck", + "同步更新 methods/system.json 中 scanOrder 的 stock children 与 scanTask 的 stock 字段描述" + ], + "module": "order" + }, + { + "version": "2026.08.23-stock.warehouse-need-recheck", + "date": "2026-08-23", + "type": "enhanced", + "summary": "wms_stock_warehouse 新增 need_recheck(是否需要复核)字段:Y=需要复核(默认),N=不需要复核,非空。编辑(saveWarehouseStock/createWarehouseStock/getInfo/handleBatchChange)、导入(import 支持中文 需要/不需要 或 Y/N,缺省新建默认 Y、更新保留原值)、导出(仓库/外仓导出新增「是否需要复核」列,与导入列名对齐)全链路支持。", + "methods": [ + "stock.warehouse.getInfo", + "stock.warehouse.saveWarehouseStock", + "stock.warehouse.createWarehouseStock", + "stock.warehouse.import", + "stock.warehouse.handleBatchChange", + "stock.warehouse.export", + "stock.warehouse.externalExport" + ], + "notes": [ + "database/migrations/20260823150000-add-need-recheck-to-wms-stock-warehouse.js 新增迁移(CHAR(1) NOT NULL DEFAULT 'Y',comment: 是否需要复核:Y=需要复核,N=不需要复核)", + "app/model/stock_warehouse.js 新增 need_recheck 字段定义(默认 Y、非空)", + "app/service/systems/stock_store.js getInfo attributes 增加 need_recheck;saveWarehouseStock 解构/更新数据增加 need_recheck;createWarehouseStock 解构并默认 'Y';validateSaveParams 校验非 Y/N 值报错;handleBatchChange 白名单增加 need_recheck 并校验 Y/N;exportWarehouseStock/exportExternalWarehouseStock 行数据输出中文 需要/不需要 并新增「是否需要复核」导出列", + "app/service/systemMethods/stock/warehouse.js saveWarehouseStock 解构并透传 need_recheck;_normalizeWarehouseImportRow 解析「是否需要复核/need_recheck/needRecheck」列并新增 _normalizeNeedRecheckValue 归一化(需要→Y,不需要→N,非法值报错,缺省不覆盖)", + "同步更新 methods/system.json 中 getInfo/saveWarehouseStock/createWarehouseStock/import/handleBatchChange 的字段说明" + ], + "module": "stock" + }, + { + "version": "2026.08.23-pick.intercepted-skip-claim-pick", + "date": "2026-08-23", + "type": "fixed", + "summary": "拦截订单不再阻隔领料/拣货且不参与作业数量:pick.waveClaimScan 打印校验与领料更新跳过拦截订单(拦截未打印不阻隔领料、拦截订单不置为 claim_status=fin,响应 data 新增 intercepted_order_count);pick.query 领料前置校验仅统计非拦截未领料订单(拦截未领料不阻隔拣货,fail data 新增 intercepted_order_count);pick.createWavePickTask 新增 excludeUnclaimed 选项,普通波次(source=0)创建拣货任务计算拣货数量(order_count/任务订单/筐)时剔除未领料订单。", + "methods": [ + "pick.waveClaimScan", + "pick.query", + "pick.wavePickComplete" + ], + "notes": [ + "app/service/systemMethods/pick.js waveClaimScan 波次订单查询 attributes 增加 intercept_status,拦截订单集合不参与 unclaimed/unprinted 统计且不参与 claim_status=fin 更新", + "app/service/systemMethods/pick.js 新增 getWaveClaimGateStats 辅助方法(统计 total/intercepted/unclaimed,unclaimed 仅计非拦截订单),query 领料门禁改用该统计", + "app/service/systemMethods/pick.js createWavePickTask 新增 params.excludeUnclaimed(默认 false):为 true 时 attributes 增加 claim_status 并剔除 claim_status != fin 订单(未领料不参与 order_count/任务订单/筐数量);query 与 wavePickComplete 对普通波次(source=0)传 excludeUnclaimed=true(wavePickComplete 波次查询 SELECT 增加 source)", + "同步更新 methods/system.json 中 pick.query 与 pick.waveClaimScan 的 description、400 错误说明与 response 字段" + ], + "module": "pick" + }, + { + "version": "2026.08.23-returnUnpack.list-video-fields", + "date": "2026-08-23", + "type": "enhanced", + "summary": "returnUnpack.list 对齐打包记录补齐视频字段:列表关联查询视频副表,每条记录新增 has_video(1=有视频记录/2=无)、video_enable(1=录像可用/2=不可用)派生字段与 videos 视频数组(id/video_url/status/camera_id/camera_name),并新增 has_video / video_enable 列表筛选(EXISTS 字面量,口径与 order.packing.list 一致)。", + "methods": [ + "returnUnpack.list" + ], + "notes": [ + "app/service/systems/return_unpack.js list 改 raw:false 并 include ReturnUnpackVideo as videos(deleted_at IS NULL 过滤 + Camera 关联精简字段),行数据经 _flattenVideos 输出精简视频数组;_enrichRow 对含 videos 数组的记录派生 has_video/video_enable(create 幂等复用与 detail 返回同步受益,videos 结构不变);_buildListWhere 新增 has_video/video_enable 筛选(1/2,EXISTS/NOT EXISTS 字面量)", + "同步更新 methods/system.json 中 returnUnpack.list 的 params(where.has_video / where.video_enable)与 response list 字段说明" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.22-order.print-custom-area-wave-multiply-qty", + "date": "2026-08-22", + "type": "enhanced", + "summary": "面单自定义区商品明细行尾新增「波次总单数×该行商品数量」:当波次 wms_wave_batch.source=0(普通波次)且 wave_type=1 时,每条商品明细行尾追加 波次总单数 × 该行商品数量(如 500 单 × 3 件 = 1500);策略抓取波次(source=1/2)与其他波次类型不追加。", + "methods": [ + "order.print.getOrderPrintData", + "order.print.getWavePlatformPrintData", + "order.print.getPrintDataByWaybillCodes" + ], + "notes": [ + "app/service/systems/order_print.js queryWavesByIds 查询增加 source/wave_type 字段;getWavePlatformPrintData / getOrderPrintData / getPrintDataByWaybillCodes 三条路径构建 waveMetaMap 并在订单行附加 wave_source / wave_type", + "app/lib/printer_data_builder.js buildWaybillCustomProductInfoLines 明细行构建时 waveSource=0 且 waveType=1 且 wave_total_orders>0 时行尾追加 波次总单数×qtyNumber(商品数量与乘数之间以两个空格分隔);7 个平台映射(快手/拼多多/抖音/菜鸟/小红书/视频号/京东)同步传入 waveSource/waveType", + "更新 test/app/lib/printer_data_builder_package_material.test.js:新增 T15(source=0 且 wave_type=1 行尾乘数)与 T16(source=1 不追加乘数)", + "同步更新 methods/system.json 中三个打印方法的 description" + ], + "module": "order" + }, + { + "version": "2026.08.22-order.print-custom-area-total-qty", + "date": "2026-08-22", + "type": "enhanced", + "summary": "面单打印自定义区首行在快递渠道名后新增「商品总数【n】」:n 优先取订单级商品总数(items_total,权威字段),其次商品明细数量累加,最后 items_count(商品种类数)兜底,避免订单 items 快照宽松文本(stock_id+数量)陈旧不完整导致数量偏差;覆盖菜鸟/京东/拼多多/抖音/快手/视频号/小红书全平台自定义区。", + "methods": [ + "order.print.getOrderPrintData", + "order.print.getWavePlatformPrintData", + "order.print.getPrintDataByWaybillCodes" + ], + "notes": [ + "app/lib/printer_data_builder.js buildWaybillCustomProductInfoLines 头部行在快递渠道名后追加 商品总数【n】:fallbackTotalQty(items_total)>0 时优先,否则 safeItems 逐项 resolveItemQuantity 累加,再否则 fallbackItemsCount(items_count)兜底;7 个平台映射(快手/拼多多/抖音/菜鸟/小红书/视频号/京东)分别传入 fallbackTotalQty=items_total、fallbackItemsCount=items_count", + "更新 test/app/lib/printer_data_builder_package_material.test.js(T10 包材前缀断言排除商品总数标签、新增 T11 商品总数累加、T12 items_total 兜底优先、T13 items 快照宽松文本不完整时取 items_total、T14 无 items_total 时回退明细累加)与 test/app/service/systems/order_print.getWavePlatformPrintData.test.js(W023 头部行断言追加 商品总数【2】)", + "同步更新 methods/system.json 中三个打印方法的 description" + ], + "module": "order" + }, + { + "version": "2026.08.22-pick.query-wave-claim-gate-source0", + "date": "2026-08-22", + "type": "enhanced", + "summary": "pick.query 新增领料前置校验(仅普通波次 source=0):扫描命中普通波次时,若波次内存在未领料订单(claim_status != fin)则返回 400 并携带 action=wave_claim 提示「订单未领料,请先领料后再拣货」,阻隔开始拣货(中止拣货任务创建);已全部领料或策略抓取波次(source=1/2)不拦截。", + "methods": [ + "pick.query" + ], + "notes": [ + "app/service/systemMethods/pick.js query 波次查询 SELECT 增加 source 字段并记录 targetWaveSource;目标波次信息校验后插入领料前置校验:source=0 时查询波次订单 claim_status,存在未领单订单 fail 400(data 含 action=wave_claim、wave_id、wave_no、wave_type、wave_source、pick_mode、unclaimed_order_count、total_order_count)", + "同步更新 methods/system.json 中 pick.query 的 description 与 400 错误说明" + ], + "module": "pick" + }, + { + "version": "2026.08.22-stock.warehouse.import-barcode-sync", + "date": "2026-08-22", + "type": "fixed", + "summary": "修复 stock.warehouse.import 传入 barcode(条码)不生效的问题:归一化后条码未在新建/更新路径写入 wms_stock_barcodes 表。现在导入行携带非空 barcode 时,在商品创建/更新成功后调用 saveWarehouseStockBarcode 差异同步条码(未传条码则保留原有条码)。", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "app/service/systemMethods/stock/warehouse.js import():创建/更新成功后,若归一化 barcode 为非空数组,则按结果 id(缺省用行内 SKU)调用 systems.stockStore.saveWarehouseStockBarcode 同步到 wms_stock_barcodes 表", + "条码同步失败计入该行 fail_items,且该行不再计入成功计数,便于定位", + "未传 barcode(空数组)时不触发同步,避免误清空已有条码;barcode 格式与导出对齐(逗号分隔字符串)" + ], + "module": "stock.warehouse" + }, + { + "version": "2026.08.22-storage.inventory.list-filter-zero-quantity", + "date": "2026-08-22", + "type": "enhanced", + "summary": "storage.inventory.list 过滤总数量为 0 的商品或明细行:基础查询条件增加 quantity > 0,明细模式(group_by_batch=true)不再返回 quantity=0 的明细行,合并模式(group_by_batch=false)不再返回总数量为 0 的商品。storage.inventory.export 同步保持一致。", + "methods": [ + "storage.inventory.list", + "storage.inventory.export" + ], + "notes": [ + "app/service/systems/storage/inventory.js:getInventoryList 与 exportInventoryList 的 baseWhere 均增加 { quantity: { [Op.gt]: 0 } },动态 where/stock_query 条件不受影响", + "明细模式:quantity=0 的 storage 行直接过滤;合并模式:某商品所有明细行均无正数量时分组自然消失,总量为 0 的商品不返回", + "storage.inventory.export 入参与 list 语义保持一致(导出同样过滤零量行/零量商品)" + ], + "module": "storage.inventory" + }, + { + "version": "2026.08.22-storage.inventory.listByStockId-group-by-space", + "date": "2026-08-22", + "type": "enhanced", + "summary": "storage.inventory.listByStockId 新增 group_by_space 双模式:false(默认,不汇总)逐条返回 quantity > 1 明细行(含批次/效期/预警字段,行为不变);true(按库位汇总)先筛 quantity > 1 明细行,再按 space_id 汇总 quantity/locked_quantity/available_quantity,返回库位级汇总行(含 batch_count、first/last_inbound_time、stock/space/store_name),不含批次与效期/预警字段。", + "methods": [ + "storage.inventory.listByStockId" + ], + "notes": [ + "app/service/systems/storage/inventory.js:getStorageListByStockId(stockId, groupBySpace=false) 两种模式共用同一查询(先筛 quantity > 1 明细行),group_by_space=true 时用新增 _aggregateStorageRowsBySpace 按 space_id 在内存汇总(求和、批次数、最早/最晚入库时间),并保留商品/库位关联与条码图片附属信息", + "app/service/systemMethods/storage/inventory.js:listByStockId 透传 group_by_space(支持 true/'true' 布尔/字符串)", + "汇总口径:先筛 quantity > 1 的明细行再按库位求和;汇总行不返回批次与效期/库存预警字段" + ], + "module": "storage.inventory" + }, + { + "version": "2026.08.22-storage.inventory.store-stock-join-dedup", + "date": "2026-08-22", + "type": "fixed", + "summary": "修复库存接口按 stock_id 查询返回重复 storage 行(同 id 多条)的问题:store_stock 关联(belongsTo StoreWarehouse,按 store_id 关联)未按仓库收敛,货主在多仓库存在签约行时 JOIN 多行匹配导致同一库存行重复且 store_name 不一致。改为统一使用 StoreWarehouse.buildStoreStockInclude(按 warehouse_id + warehouse_use_status=1 收敛,命中唯一签约行)。", + "methods": [ + "storage.inventory.listByStockId", + "storage.inventory.list" + ], + "notes": [ + "app/service/systems/storage/inventory.js:getStorageListByStockId、getInventoryList(明细模式与合并模式)三处 store_stock 嵌套 include 均改为 buildStoreStockInclude({ warehouseId, required: false, attributes: ['store_id','store_remask'] })", + "wms_store_warehouse 存在 (store_id, warehouse_id) 唯一索引,按仓库收敛后每商品至多命中一行签约关系,不再产生重复明细;合并模式下 SUM(quantity) 也不会因 JOIN 多行而翻倍", + "同时修正 storage.inventory.list 同源隐患(明细模式重复行、合并模式数量翻倍),返回结构不变" + ], + "module": "storage.inventory" + }, + { + "version": "2026.08.22-storage.inventory.listByStockId", + "date": "2026-08-22", + "type": "added", + "summary": "新增 storage.inventory.listByStockId 接口:传入 stock_id,返回该商品在当前仓库下所有 quantity > 1 的 wms_storage 明细行(按 id 倒序),返回结构与 storage.inventory.list 明细模式一致(含 stock 条码/图片、space 库位、货主名称及效期/库存预警字段)。", + "methods": [ + "storage.inventory.listByStockId" + ], + "notes": [ + "app/service/systemMethods/storage/inventory.js 新增 listByStockId 包装方法,并加入 _noNeedRight/_noNeedLog/_noNeedAuth 豁免列表(与 list 一致)", + "app/service/systems/storage/inventory.js 新增 getStorageListByStockId:校验 stock_id 正整数与当前仓库上下文,where 条件 warehouse_id+stock_id+quantity>1+is_enabled=1+delete_at=null,include stock/space 与明细模式一致", + "重构 getInventoryList 明细分支:提取 _loadInventoryWarningRanges 与 _formatBatchStorageRows 复用,现有 storage.inventory.list 行为不变" + ], + "module": "storage.inventory" + }, + { + "version": "2026.08.21-returnUnpack.create-orderItems", + "date": "2026-08-21", + "type": "enhanced", + "summary": "returnUnpack.create 返回新增顶层 order_items 字段:原订单商品明细数组(即 order.items 的顶层透出,含 item_code/item_name/sku_property/quantity/plan_qty/barcodes/image_url 等),仅原单退回且原订单详情解析成功时返回;非原单退回或原订单详情缺失时为 null。新建与幂等复用两个分支返回结构一致。", + "methods": [ + "returnUnpack.create" + ], + "notes": [ + "app/service/systems/return_unpack.js create:新建分支返回 order_items(order.items 为数组时透出,否则 null);幂等复用分支从 detail().related.order 提取同名字段,与 order 字段同源", + "向后兼容:仅新增顶层字段,order/record 等既有字段不变", + "同步更新 methods/system.json 中 returnUnpack.create 的 response(新增 order_items 字段说明)" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.21-stock.warehouse.search-return-images", + "date": "2026-08-21", + "type": "enhanced", + "summary": "stock.warehouse.search 默认模式返回数据新增 images 字段:批查 wms_file_reference(business_type=stock)+ wms_file 获取商品图片URL列表,按 display_order 升序;无图片时返回空数组。mode=\"combo\" 时不返回该字段。", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "app/service/systems/stock_store.js search:formattedResults 生成后批量查询 FileReference(include File.file_url,raw),按 business_id(商品ID)分组注入 item.images,与 stock.warehouse.list 图片口径一致", + "同步更新 methods/system.json 中 stock.warehouse.search 的 response 字段" + ], + "module": "stock" + }, + { + "version": "2026.08.21-order.pendingOrder.cloneOrder-sync-status-inherit", + "date": "2026-08-21", + "type": "enhanced", + "summary": "order.pendingOrder.cloneOrder 同步状态继承原订单:原订单已同步(sync_status=fin)时新订单直接置 fin,避免克隆后重复回传平台;原订单未同步/同步失败(padding/error)则重置为 padding 重新走同步流程。", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "app/service/systemMethods/order/pendingOrder.js cloneOrder 第 4 步 newOrderData.sync_status 按 original.sync_status 判定:fin→fin,其余→padding(RESET_FIELDS 保留 padding 兜底)", + "已同步新订单分配运单号不受 sync_status 限制(createWaybillCodePipeline 只校验 step 1/2/3/4、status、拦截、锁定、已分配运单号),但新订单 step=0 需先审核进入待处理才能分配;已同步订单分配新运单号后不会自动回传平台", + "同步更新 methods/system.json 中 cloneOrder 的 description" + ], + "module": "order" + }, + { + "version": "2026.08.21-order.pendingOrder.cloneOrder-storage-release-tolerant", + "date": "2026-08-21", + "type": "enhanced", + "summary": "order.pendingOrder.cloneOrder 支持克隆已同步(sync_status=fin)订单且库存释放失败不阻断:原订单已分配储位时先清除已分配库存,cancelAllocateStorage 失败降级为告警(与 cancelOrder 策略一致),克隆继续执行;残留占用保留在原订单名下,克隆新订单不重新占用库存(storage_status=none,创建过程不触发储位分配与库存锁定)。", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "app/service/systemMethods/order/pendingOrder.js cloneOrder 第 2 步:清除已分配库存失败由抛错阻断改为 ctx.logger.warn 降级,不影响克隆主流程", + "克隆新订单库存零占用(storage_status 重置 none、无自动储位分配),后续如需发货需在待处理工作台重新分配储位", + "同步更新 methods/system.json 中 cloneOrder 的 description" + ], + "module": "order" + }, + { + "version": "2026.08.21-order.pendingOrder.cloneOrder-unique-delivery-code", + "date": "2026-08-21", + "type": "fixed", + "summary": "修复 order.pendingOrder.cloneOrder 复制原单号导致唯一键冲突:新订单 delivery_order_code 重新生成(SYS+时间戳+随机4位,与 createOrder 同规则),原单号写入 pre_delivery_order_code 保留克隆追溯链;此前复制原单号会命中 (delivery_order_code, store_id, warehouse_id) 唯一索引,克隆报「Validation error」且原订单已被取消、新订单未创建(原订单损坏)。", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "app/service/systemMethods/order/pendingOrder.js cloneOrder:COPY_FIELDS 移除 delivery_order_code,新订单单号改为 SYS${Date.now()}${1000~9999 随机} 生成;原订单无 pre_delivery_order_code 时写入原单号保留追溯链;注释说明唯一索引约束与 UniqueConstraintError 表现", + "同步更新 methods/system.json 中 cloneOrder 的 description" + ], + "module": "order" + }, + { + "version": "2026.08.21-index.searchSpaces-batch-search", + "date": "2026-08-21", + "type": "added", + "summary": "新增 index.searchSpaces 批量库位查询接口:keywords 传入字符串数组,逐项按当前仓库上下文模糊查询(space_code/custom_barcode/custom_name,每项最多 50 条),结果按传入顺序以二维数组返回,无记录对应项返回空数组。", + "methods": [ + "index.searchSpaces" + ], + "notes": [ + "app/service/systems/space.js 抽取 _searchByKeyword 私有查询方法(searchSpace 与 searchSpaces 共用同一查询口径),新增 searchSpaces 并行查询每个关键字并保持传入顺序输出,无记录项返回 []", + "app/service/systemMethods/index.js 新增 searchSpaces 出口方法,并加入 _noNeedRight/_noNeedAuth 白名单(与 searchSpace 一致,免鉴权免权限、需登录)", + "同步更新 methods/system.json 与 AI_METHOD_ROUTING.md" + ], + "module": "index" + }, + { + "version": "2026.08.20-order.wave.matched-count-same-express-split", + "date": "2026-08-20", + "type": "fixed", + "summary": "order.wave.waveStrategyList 的 matched_order_count_filtered 计数口径与按策略抓取保持一致:require_same_express=1 的策略按「结构(items_hash)+快递」分组计数并应用 min/max_same_structure,不再仅按结构分组统计,避免列表显示有命中订单但 waveStrategyFetchAdmin 实际抓取为 0 的口径不一致。", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js getWaveStrategyMatchedOrderCountFilteredMap 改为接收策略行数组并按 require_same_express 拆分两类计数查询:同快递策略按 items_hash+快递(sys_logistics_code>logistics_code>logistics_name COALESCE 口径)分组,其余仅按 items_hash 分组;max_same_structure<=0 视为不设上限,与抓取候选 SQL 归一化一致;调用方 waveStrategyList 改传当前页策略行 list", + "同步更新 methods/system.json 中 matched_order_count_filtered 字段描述" + ], + "module": "order" + }, + { + "version": "2026.08.20-pick.waveClaimScan-print-gate", + "date": "2026-08-20", + "type": "enhanced", + "summary": "pick.waveClaimScan 新增波次打印校验:整波领料前检查波次下全部订单 print_status,存在未打印订单(print_status != fin)时返回 400「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count、total_order_count),波次全部打印后才允许将订单 claim_status 置为 fin;已全部领料幂等结果优先返回,不受打印校验拦截。", + "methods": [ + "pick.waveClaimScan" + ], + "notes": [ + "app/service/systemMethods/pick.js waveClaimScan 波次订单查询 attributes 增加 print_status,already_claimed 幂等判断之后插入打印校验:unprinted_order_count > 0 时 fail 400「波次未打印,禁止领料」", + "同步更新 methods/system.json 中 pick.waveClaimScan 的 description 与 400 错误说明" + ], + "module": "pick" + }, + { + "version": "2026.08.20-pick.waveClaimScan-source-gate", + "date": "2026-08-20", + "type": "enhanced", + "summary": "pick.waveClaimScan 整波领料资格判定收敛为仅普通波次(wms_wave_batch.source=0)生效:符合时将该波次下全部未领单订单 claim_status 置为 fin 并返回 wave_id/wave_no 与领单说明;策略抓取波次(source=1/2)返回「该波次为抓取波次,无需领料」(data 含 no_claim_needed=true、wave_id、wave_no);波次已全部领料返回 already_claimed 并提示「该波次已领料,无需重复领取」;面单号无记录/订单不在待处理订单表返回 404 无记录提示。", + "methods": [ + "pick.waveClaimScan" + ], + "notes": [ + "app/service/systemMethods/pick.js waveClaimScan 资格判定由(大团购 wave_type=1 且 pick_mode=5 / 非抓取散单 wave_type=2 且 source=0)改为仅按 source 判定:source=0 全部支持整波领料,source∈{1,2} 返回抓取波次无需领料并携带 no_claim_needed=true、wave_id、wave_no,其余返回不支持提示;already_claimed tip 改为「该波次已领料,无需重复领取」", + "app/dict/businessDict.js OPERATION_CODE 补记 ORDER_WAVE_CLAIM:'领取波次'", + "同步更新 methods/system.json 中 pick.waveClaimScan 的 description/400/404 错误说明" + ], + "module": "pick" + }, + { + "version": "2026.08.19-print-custom-area-stock-merge", + "date": "2026-08-19", + "type": "fixed", + "summary": "修复打印自定义区同库位不同商品被合并为一行的问题:拣货明细聚合键由「库位」改为「库位+stock_id」复合键,仅同一库位同一商品才合并数量;stock_id 缺失时依次回退 order_item_id、商品名称+条码,无法识别商品身份时不再跨行合并。", + "methods": [ + "order.print.getOrderPrintData", + "order.print.getWavePlatformPrintData", + "order.print.getPrintDataByWaybillCodes" + ], + "notes": [ + "app/service/systems/order_print.js buildPrintOrderRowMapWithPicking 阶段五聚合改为 buildPrintItemAggregationKey 复合键(pick_location::stock:stock_id),同库位不同商品保持独立行,数量/条码不再串;stock_id 字段延迟到聚合完成后才删除,避免污染 items JSON" + ], + "module": "order" + }, + { + "version": "2026.08.19-pick.claim-prompt-refine", + "date": "2026-08-19", + "type": "enhanced", + "summary": "领料提示文案细化:pick.query 领单前置校验拦截时直接提示「订单未领料,请先领料后再拣货」;pick.waveClaimScan 对抓取的波次(团购小波次 pick_mode=1、策略抓取散单波次 source=1/2)返回「该波次为抓取波次,无需领料」提示(失败 data 新增 no_claim_needed=true),其余未知类型保留通用不支持提示。", + "methods": [ + "pick.query", + "pick.waveClaimScan" + ], + "notes": [ + "app/service/systemMethods/pick.js query 领单前置校验拦截文案由「该波次尚未领单,请先整波领单后再拣货」改为「订单未领料,请先领料后再拣货」,action=wave_claim 等失败 data 字段不变", + "app/service/systemMethods/pick.js waveClaimScan 资格判定失败时细分提示:抓取波次(wave_type=2 且 source∈{1,2},或 wave_type=1 且 pick_mode=1)返回「该波次为抓取波次,无需领料」并携带 no_claim_needed=true;其他未知类型保留「当前波次类型不支持整波领单」", + "同步更新 methods/system.json 中 pick.query 与 pick.waveClaimScan 的 description/400 错误说明" + ], + "module": "pick" + }, + { + "version": "2026.08.19-pick.query-wave-claim-gate", + "date": "2026-08-19", + "type": "enhanced", + "summary": "pick.query 新增领单前置校验:扫描命中的波次属于大团购(pick_mode=5)或非抓取散单(wms_wave_batch.source=0 普通波次)时,若波次内存在未领单订单(claim_status != fin)则返回 400 并携带 action=wave_claim 提示先整波领单(pick.waveClaimScan),中止拣货任务创建;已全部领单则继续原流程。", + "methods": [ + "pick.query" + ], + "notes": [ + "app/service/systemMethods/pick.js query 在解析目标波次后、活动任务去重前插入领单校验:复用 getWavePickModeByWaveId 与 wms_wave_batch.source 判定波次类型(大团购=wave_type 1 且 pick_mode 5;非抓取散单=wave_type 2 且 source 0),查询波次订单 claim_status,存在未领单订单时 fail 400(data 含 action=wave_claim、wave_id、wave_no、wave_type、wave_source、pick_mode、unclaimed_order_count、total_order_count)", + "同步更新 methods/system.json 中 pick.query 的 description 与 400 错误说明" + ], + "module": "pick" + }, + { + "version": "2026.08.19-pick.waveClaimScan", + "date": "2026-08-19", + "type": "enhanced", + "summary": "新增 pick.waveClaimScan 整波领单接口:PDA 扫描波次内一个面单号后,针对大团购(pick_mode=5 团购大波次)与非抓取的散单(wms_wave_batch.source=0 普通波次)将该波次下全部订单 claim_status 置为 fin(领单完成),并写入 ORDER_WAVE_CLAIM 订单操作日志;团购小波次与策略抓取散单波次不支持整波领单,返回 400;波次已全部领单时返回 already_claimed 幂等结果。", + "methods": [ + "pick.waveClaimScan" + ], + "notes": [ + "app/service/systemMethods/pick.js 新增 waveClaimScan:面单号定位订单(wms_order_express.waybill_code)→ 订单定位波次 → 读取 wms_wave_batch(wave_type/source)与拣货任务 pick_mode 判定资格(大团购=wave_type 1 且 pick_mode 5;非抓取散单=wave_type 2 且 source 0)→ 整波订单 claim_status='fin',并新增 getWavePickModeByWaveId 查询关联拣货模式", + "app/service/systemMethods/pick.js 鉴权配置:waveClaimScan 加入 _noNeedRight/_noNeedAuth(免权限、免仓库有效期校验),保留登录校验与请求日志", + "app/dict/businessDict.js OPERATION_CODE 新增 ORDER_WAVE_CLAIM:'领取波次'", + "同步更新 methods/system.json 中 pick.waveClaimScan 接口文档" + ], + "module": "pick" + }, + { + "version": "2026.08.19-manual-order-stock-store-guard", + "date": "2026-08-19", + "type": "fixed", + "summary": "手工单(order.pendingOrder.createOrder)新增库存归属货主校验:item_id 直接传仓库 stock_id 时,校验 wms_stock_warehouse.store_id 与订单货主 store_id 一致,跨货主传库存将被拒绝,杜绝把其他货主库存挂在当前货主订单下。", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "app/service/systems/delivery_order.js addOrderLines 手工单分支(line.stockId)新增 StockWarehouse 归属校验,不一致时计入 errors 并跳过该行,错误文案:商品《xxx》编码《xxx》库存归属货主(store_id=…)与当前货主(store_id=…)不一致,无法创建订单", + "同步更新 methods/system.json 中 order.pendingOrder.createOrder 的 notes 说明" + ], + "module": "order" + }, + { + "version": "2026.08.19-wave-fallback-excluded-reason-cn-label", + "date": "2026-08-19", + "type": "enhanced", + "summary": "order.wave.waveStrategyFallbackOrderList 响应 excluded_reason 由英文枚举值改为中文标签:locked→已锁定、intercepted→已拦截、printed→已打印、no_match→未匹配策略。", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js 新增 WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS 常量并用于 buildWaveStrategyFallbackOrderListItem,判定优先级不变", + "同步更新 methods/system.json 中该接口 excluded_reason 字段与 list 说明" + ], + "module": "order" + }, + { + "version": "2026.08.19-wave-fallback-excluded-reason-lock-fix", + "date": "2026-08-19", + "type": "fixed", + "summary": "修复 order.wave.waveStrategyFallbackOrderList 所有行 excluded_reason 恒为 locked 的问题:列表行经 normalizeOrderListItem 后 lock_status 已归一化为 Y/N,原判断 lock_status !== 'none' 恒成立导致全部误标 locked;改为兼容归一化值(Y=锁定,N/none/空=未锁定)与原始值(warehouse/store 等),恢复 locked/intercepted/printed/no_match 的正确判定。", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "app/service/systemMethods/order/wave.js buildWaveStrategyFallbackOrderListItem 新增 lockStatus 归一化与 isLocked 判定(Y 或非 none/非 N 的原始值视为锁定),excluded_reason 优先级不变:locked > intercepted > printed > no_match" + ], + "module": "order" + }, + { + "version": "2026.08.19-order-list-wave-index-range-filter", + "date": "2026-08-19", + "type": "enhanced", + "summary": "订单列表 where 新增 wave_index 波次内序号范围查询入参:工作台订单列表(经 listByModule 的 9 个列表)与订单导出支持 wave_index 虚拟筛选(eq/in/gt/lt/ge/le/between/notbetween,between 要求 value 为长度 2 的数组);复核散单列表支持 wave_index between 与 wave_index_min/wave_index_max。", + "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", + "order.recheckOrder.recheckOrderList", + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "新增 app/model/order_wave_index.js 模型(wms_order_wave_index,timestamps=false),供副表条件查询", + "app/service/systemMethods/order/base.js 新增 extractWaveIndexVirtualFilter(从 where 提取 wave_index/waveIndex,兼容数值简写按 eq 处理)与 findOrderIdsByWaveIndexCondition(用 parseWhereConditions 解析条件后查副表得 order_id 集合);listByModule 在 stock_query 之后接入,命中为空时主查询结果为空", + "app/service/systems/order_export.js exportOrders 同样接入 wave_index 虚拟筛选,与列表 where 语义一致", + "app/service/systemMethods/order/recheckOrder.js queryRecheckOrderSingleList 新增 wave_index 筛选(between/gte/lte/eq 或 wave_index_min/wave_index_max),countSql 同步 LEFT JOIN wms_order_wave_index 保持总数一致", + "同步更新 methods/system.json 中 order.list 与复核列表 where 参数说明" + ], + "module": "order" + }, + { + "version": "2026.08.19-order-list-wave-index-join", + "date": "2026-08-19", + "type": "enhanced", + "summary": "所有订单列表统一联查 wms_order_wave_index 并输出 wave_index(波次内序号,无记录时降级为 0):覆盖 9 个工作台订单列表(order.list / reviewOrder.list / pendingOrder.list / outboundOrder.list / expectionOrder.list / entrustOrder.list / deliveryOrder.list / deliveryExpectionOrder.list / archiveOrder.list)、复核散单列表与波次策略兜底列表;订单导出(waybill/item 两种模式)新增「波次序号」列。", + "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", + "order.recheckOrder.recheckOrderList", + "order.recheckOrder.queryRecheckOrderSingleList", + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "app/service/systemMethods/order/base.js 新增 attachOrderWaveIndex:按列表行 id 批量查询 wms_order_wave_index(warehouse_id + order_id,命中唯一索引),无记录或查询异常时降级为 0 并告警;listByModule 在 attachOrderExpressNumbers 之后接入,统一覆盖全部工作台订单列表", + "app/service/systemMethods/order/wave.js waveStrategyFallbackOrderList 接入 attachOrderWaveIndex,buildWaveStrategyFallbackOrderListItem 输出 wave_index(默认 0)", + "app/service/systemMethods/order/recheckOrder.js queryRecheckOrderSingleList 列表 SQL 增加 LEFT JOIN wms_order_wave_index(warehouse_id + order_id),响应行新增 wave_index;recheckOrderList 散单分支同源生效", + "app/service/systems/order_export.js exportOrders 接入 attachOrderWaveIndex,ORDER_EXPORT_COLUMNS / ORDER_EXPORT_ITEM_COLUMNS 在波次号后新增「波次序号」列,mapOrderExportRow commonFields 新增 wave_index", + "同步更新 methods/system.json 中上述接口的 response 字段说明" + ], + "module": "order" + }, + { + "version": "2026.08.19-recheckOrder.confirmIntercept-ids", + "date": "2026-08-19", + "type": "enhanced", + "summary": "order.recheckOrder.confirmIntercept 入参由单值 order_id 改为批量 ids:支持数组或以逗号分隔的字符串(兼容 id/order_id/orderId 单值写法),批量确认拦截,返回 success/failed 列表与 success_count/failed_count 计数;单个订单失败不再阻断整体,未找到订单与更新失败订单记录在 failed 列表", + "methods": [ + "order.recheckOrder.confirmIntercept" + ], + "notes": [ + "app/service/systemMethods/order/recheckOrder.js confirmIntercept:用 base.normalizeOrderIds 解析 ids(兼容 ids/id/order_id/orderId),findAll 批量查询后逐订单执行拦截主流程(intercept_status=intercepted_at_warehouse、step=4、outbound_status=fin,运单标记 is_back/is_intercept='Y',释放储位分配与订单锁,写入 ORDER_INTERCEPT_CONFIRM 操作日志),未找到订单与处理异常订单记录 failed 不抛错,仅 ids 全部无效时 400「订单ID列表不能为空」", + "确认拦截前置校验:仅拦截发起中状态(requested/requesting/intercepting,历史值 intercepted 兼容)允许确认;未发起拦截(none/空)的订单直接静默跳过不参与处理,已确认拦截(intercepted_at_warehouse)订单跳过避免重复副作用并记录 failed「订单已确认拦截」,其余非可确认状态(intercepted_in_transit/returning/returned/delivered_by_mistake/timeout/cancelled/failed/exception)记录 failed「订单拦截状态不允许确认拦截: {状态}」;更新 SQL where 同时限定 intercept_status 白名单(CONFIRMABLE_INTERCEPT_STATUSES),防止查询后状态被并发修改导致误更新", + "售后工单+快递群通知由原每订单调用改为按成功订单 ID 汇总后统一调用一次 afterSale.createInterceptWorkOrdersAndNotify,失败仅告警", + "返回结构由单对象改为 { success, failed, success_count, failed_count },success 每项保持 order_id/order_no/intercept_status/updated_at,failed 每项含 order_id/delivery_order_code/reason", + "同步更新 methods/system.json 中该接口 params(ids)、response 与 errors 文档" + ], + "module": "order.recheckOrder" + }, + { + "version": "2026.08.18-order-list-lock-status-filter-doc", + "date": "2026-08-18", + "type": "enhanced", + "summary": "订单列表 where 补充 lock_status 筛选说明:未锁定传 lock_status=none,已锁定(所有非 none)传 lock_status={operator:ne,value:none};筛选用数据库原始枚举 none/warehouse/store 而非响应 Y/N,条件值为空自动忽略。", + "methods": [ + "order.pendingOrder.list" + ], + "notes": [ + "仅文档补充,无代码改动:methods/system.json 中 order.pendingOrder.list 的 where 参数 description 增加 lock_status 筛选说明", + "行为依据:app/service/systemMethods/order/base.js listByModule/buildWhere 对 where 无字段白名单(仅禁止 warehouse_id/warehouseId),可直接传订单表列名;app/lib/query_condition_parser.js 支持 ne 操作符且条件值为空时自动忽略(isEmptyValue 跳过)", + "lock_status 数据库原始枚举 none/warehouse/store(app/model/order_delivery.js LOCK_STATUS),列表响应仍统一输出 Y/N(normalizeLockStatusFlag:none→N,其余→Y),筛选入参必须用原始枚举而非响应 Y/N", + "同样经 listByModule 的其它工作台订单列表(order.reviewOrder.list / order.outboundOrder.list / order.expectionOrder.list / order.entrustOrder.list / order.deliveryOrder.list / order.deliveryExpectionOrder.list / order.archiveOrder.list)where 语义一致,本次保持其文档不变,重点仅更新 order.pendingOrder.list" + ], + "module": "order" + }, + { + "version": "2026.08.18-setting.expressInterface.update-doc-params", + "date": "2026-08-18", + "type": "enhanced", + "summary": "补全 setting.expressInterface.update 接口文档:入参由 3 个字段扩展为全量可更新字段(含 town_name/townName、is_enabled/isEnabled、providertype 等),并补充全量响应字段与错误码说明。", + "methods": [ + "setting.expressInterface.update" + ], + "notes": [ + "入参按 app/service/systems/setting/expressInterface.js update() 与包装层 app/service/systemMethods/setting/expressInterface.js update() 实际支持的字段补齐,含驼峰别名(shopId/townName/isEnabled 等),仅传入的字段被更新", + "响应按 normalizeInterfaceRow 返回结构补齐全量字段", + "仅文档变更,无代码改动" + ], + "module": "setting.expressInterface" + }, + { + "version": "2026.08.18-order-lock-status-guard-and-list-yn", + "date": "2026-08-18", + "type": "enhanced", + "summary": "新增锁定订单作业门禁与订单列表 lock_status 转 Y/N:lock_status 非 none(枚举 warehouse/store)的订单在分配储位、分配快递、抓取波次、自动加团等流程中被直接跳过,跳过明细通过 skipped_locked_order_ids / excluded_locked_order_ids / skipped_orders 等字段返回;订单列表 lock_status 统一输出 Y/N(none→N,其余→Y)。", + "methods": [ + "order.pendingOrder.list", + "order.pendingOrder.allocateExpressCode", + "order.pendingOrder.allocateStorage", + "order.wave.singleFetchByIds", + "order.wave.waveStrategyFallbackOrderList", + "order.wave.batchAllocateExpress", + "order.wave.batchAllocateExpressTaskProgress", + "order.wave.batchAllocateStorage", + "order.wave.batchAllocateStorageTaskProgress" + ], + "notes": [ + "新增 app/lib/lock_guard.js isLockedOrderStatus:lock_status 非 'none' 即视为已锁定(枚举 none/warehouse/store)", + "app/service/systems/order_storage_allocation.js allocatePicking:过滤循环新增锁定订单跳过,skipped 记录含 lock_status 与 skipped_reason='locked';order.storageAllocation.allocateStorage / order.pendingOrder.allocateStorage / order.wave.batchAllocateStorage 共用该底层入口", + "app/service/systems/express.js createWaybillCodePipeline:查询新增 lock_status 字段,锁定订单与拦截订单同样剔除,返回结果新增 skipped_locked_order_ids", + "app/service/systemMethods/order/wave.js runBatchAllocateExpressTask:查询新增 lock_status,任务进度与 result 新增 skipped_locked_order_ids;singleFetchByIds 查询属性新增 lock_status 并过滤锁定订单,响应新增 excluded_locked_order_ids(两个返回分支均返回);waveStrategyFallbackOrderList 查询追加 lock_status/intercept_status 非 none 条件,列表行新增 excluded_reason(locked/intercepted/printed/no_match)", + "app/service/systems/delivery_order.js asyncProcessOrderCreated:订单已锁定时跳过自动分配快递/储位/自动加团三步;appendOrderToWave 增加锁定校验且更新波次时 where 追加 lock_status='none';countCandidateGroupOrders 过滤 lock_status='none'(内部流程,无公开接口)", + "app/service/systemMethods/order/base.js 新增 normalizeLockStatusFlag:none(含空值)返回 'N',其余值一律返回 'Y';normalizeOrderListItem 统一覆盖 lock_status 输出为 Y/N,影响 order.pendingOrder.list、order.wave.waveStrategyFallbackOrderList 及经 listByModule 的各类工作台订单列表", + "同步更新 methods/system.json 中上述 method 的 description 与 response 字段" + ], + "module": "order" + }, + { + "version": "2026.08.18-storage.entry.addItem-non-binding", + "date": "2026-08-18", + "type": "fixed", + "summary": "库存导入(storage.entry.addItem 导入/PDA 入库)不再强制绑定收货单:原 PENDING 状态下未绑定收货单拒绝上架、每项缺少 receiving_detail_id 拒绝,导致移除绑定收货单后仍限制必须传入收货单 ID。现 PENDING 状态允许不绑定收货单直接导入(非绑定模式,数量受计划数量限制),传 receiving_detail_id 时仍走绑定模式(预占收货明细)", + "methods": [ + "storage.entry.addItem" + ], + "notes": [ + "app/service/systems/inbound_direct_log.js addItem:删除 PENDING 状态下 hasReceivingBindings 与 receiving_detail_id 的强制校验,绑定模式 space_id/可用数量校验仍由 _addSingleItem 统一处理;CREATED 已绑定收货单需先审核的限制保留", + "PENDING 非绑定模式导入数量仍受计划数量限制(isManualImport 仅 CREATED 且非绑定可超计划),防止超计划入库", + "同步更新 methods/system.json 中 storage.entry.addItem 的 description、receiving_detail_id 参数说明与错误码列表(移除两条 PENDING 绑定错误码)" + ], + "module": "storage.entry" + }, + { + "version": "2026.08.18-recheckOrder.scanOrder.singleIntercept", + "date": "2026-08-18", + "type": "fixed", + "summary": "修复 order.recheckOrder.scanOrder 散单模式拦截订单识别:原逻辑对波次内所有订单执行复核校验,只要波次内存在一单已进入拦截流程(requested/requesting/intercepting/intercepted_in_transit/intercepted_at_warehouse,历史值 intercepted 兼容),整个散单扫描视图即报错「订单已被拦截,无法提交复核」,导致波次内其他正常订单也无法复核。现拦截订单保留在 list 中按单提示(intercept_status),不再阻断整个扫描视图加载,且不计入复核/打印统计", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.scanTask" + ], + "notes": [ + "buildSingleWaveScanView:用 isInterceptedOrderStatus 分离拦截订单,仅非拦截订单参与 assertOrderCanRecheck 校验与 reviewed/unreviewed/printed/unprinted 统计,拦截订单保留在 list 中按单提示", + "车号/任务模式(cart/task)合并多个波次后,reviewed_count/unreviewed_count 仅统计非拦截订单,total_orders 仍为订单总数", + "同步更新 methods/system.json 中 scanOrder 散单订单项 intercept_status 字段说明" + ], + "module": "order" + }, + { + "version": "2026.08.17-inbox-group-reset", + "date": "2026-08-17", + "type": "enhanced", + "summary": "新增 inbox.group.reset 群操作接口:入参群记录主键ID,清空群类型配置(group_type/sub_type/store_id/express_interfaces/system_express_code 置空、ai_enabled 重置为0),仅保留群创建时信息(群名称/群ID/仓库/来源/屏蔽状态/扩展数据)", + "methods": [ + "inbox.group.reset" + ], + "notes": [ + "app/service/systems/inbox/group.js reset:仓库隔离按主键 id 定位群,清空类型相关字段并写操作日志,返回重置后群信息", + "app/service/systemMethods/inbox.js 新增 groupReset,注册到 inbox.group 子入口", + "数据库迁移 20260817120000-add-inbox-group-reset-permission.js:权限ID 556 授权角色 8/26/28/29", + "同步更新 methods/system.json 中 inbox.group.reset 接口文档" + ], + "module": "inbox.group" + }, + { + "version": "2026.08.17-afterSale-handleWorkOrder-remark-notify-group", + "date": "2026-08-17", + "type": "enhanced", + "summary": "afterSale.handleWorkOrder 处理备注同步发送到对应货主售后群:填写 remark 时推送到货主售后群(工单 store_id 定位,缺失时从来源消息所在群反查货主,不转发快递群);消息内容格式为「【工单 售后单号】处理备注:备注内容」;响应新增 notified_groups 返回发送群数量", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "app/service/systems/afterSale.js handleWorkOrder:新增 notifyGroup 参数(方法层交互处理传 true,内部自动处理如库内拦截/退回已收到不传),事务提交后按 remark 非空发送:store_id 定位货主 → findStoreAfterSalesGroups 发货主售后群;无 store_id 时按 inbox_message_id 查来源消息 group_id → InboxGroup 反查 store_id 再发送;发送失败仅告警不影响处理结果", + "app/service/systemMethods/afterSale.js handleWorkOrder:调用 systems 层时传 notifyGroup: true", + "同步更新 methods/system.json 中 afterSale.handleWorkOrder 的 description、remark 参数说明与 notified_groups 响应说明" + ], + "module": "afterSale" + }, + { + "version": "2026.08.16-waybill-createAt-between", + "date": "2026-08-16", + "type": "enhanced", + "summary": "waybill.warehouse.list / export 创建时间筛选统一为 between 区间写法:where.createdAt 支持 {operator:\"between\", value:[起始,结束]},保留 createdAtStart/createdAtEnd 旧写法兼容", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.export" + ], + "notes": [ + "app/service/systems/waybill.js list/export:createdAt 数组区间两端可单独为空,分别落 create_at gte/lte;同时兼容 createAt 别名与 createdAtStart/createdAtEnd 旧写法", + "同步更新 methods/system.json 中 waybill.warehouse.list / export 的 where.createdAt 参数文档" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.08.16-order-packing-list-time-filter", + "date": "2026-08-16", + "type": "enhanced", + "summary": "order.packing.list 时间筛选统一为 between 区间写法:start_time / end_time / create_time 支持 {operator:\"between\", value:[起始,结束]},与已有 start_time_start/start_time_end 旧写法兼容", + "methods": [ + "order.packing.list" + ], + "notes": [ + "app/service/systems/order_packing.js list:新增 applyTimeRangeFilter,统一处理 start_time/end_time/create_time 的 between 区间条件(数组两端可单独为空,按 gte/lte 拼接),与 warehouse_id 隔离及其他筛选叠加", + "保留 start_time_start/start_time_end 旧拆分写法的兼容处理", + "同步更新 methods/system.json 中 order.packing.list 的 where 参数文档" + ], + "module": "order.packing" + }, + { + "version": "2026.08.16-waybill-export-ids", + "date": "2026-08-16", + "type": "enhanced", + "summary": "waybill.warehouse.export 新增 where.ids 入参:支持按运单ID列表(勾选)导出快递号,与仓库隔离条件叠加过滤", + "methods": [ + "waybill.warehouse.export" + ], + "notes": [ + "app/service/systems/waybill.js export:新增 where.ids 处理,数组值经 Number 转换并过滤非法值后生成 id IN (...) 条件,与 warehouse_id 隔离条件叠加,不影响其他筛选字段", + "入口层 systemMethods/waybill/warehouse.js export 原样透传 where,无需改动", + "同步更新 methods/system.json 中 waybill.warehouse.export 的 where.ids 参数文档" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.08.15-packing-setEndTime-cap", + "date": "2026-08-15", + "type": "enhanced", + "summary": "order.packing.setEndTime 增加结束时间上限约束:传入结束时间超过仓库配置的打包最大时长上限(散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes)时,自动截断为 开始时间+上限时长 后落库", + "methods": [ + "order.packing.setEndTime" + ], + "notes": [ + "app/service/systems/order_packing.js setEndTime:结束时间不能早于开始时间校验之后,复用 workbench.resolvePackTaskEndTime 做上限截断(按 pack_mode 区分散单/团购配置,未配置有效时长时不约束)", + "截断使用最终值落库与响应(end_time/status 同步返回截断后的时间)", + "与 workbench.finishPack / packOrder 关闭旧任务 / 定时任务自动结束 的 end_time 上限语义对齐", + "同步更新 methods/system.json 中 order.packing.setEndTime 的 description、end_time 参数与响应说明" + ], + "module": "order.packing" + }, + { + "version": "2026.08.15-pack-task-end-time-cap", + "date": "2026-08-15", + "type": "enhanced", + "summary": "打包任务结束时间增加上限约束:工作台结束任务时(finishPack 手动结束、packOrder 关闭上一个未结束任务),若结束时间超过仓库配置的打包最大时长上限(散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes),自动截断为 开始时间+上限时长", + "methods": [], + "notes": [ + "app/service/systems/workbench.js 新增 resolvePackTaskEndTime:按 warehouse_id+pack_mode 读取配置上限分钟,候选结束时间超过 开始时间+上限 时返回上限时间点,未配置有效时长或 start_time 非法时不约束", + "_packOrder 步骤4 关闭上一个未结束任务、_finishPack 手动结束 两处结束路径统一接入约束,_finishPack 响应 end_time 同步返回约束后的时间", + "与定时任务 auto_finish_pack_task 语义一致:end_time 最多为 开始时间+上限时长,自动结束与手动结束行为对齐", + "创建任务时即完成(packStatus>=2)的场景 end_time=start_time,不超上限,无需处理" + ], + "module": "setting.warehouse" + }, + { + "version": "2026.08.15-pack-task-auto-finish", + "date": "2026-08-15", + "type": "added", + "summary": "新增打包任务自动结束定时任务(每小时一次):扫描 wms_pack_task 未结束任务,按仓库配置 single_order_pack_max_minutes(散单,默认 3 分钟)/ group_order_pack_max_minutes(团购,默认 40 分钟)判断超时,当前时间-开始时间超过上限时将 end_time 置为开始时间+上限时长并标记已完成", + "methods": [], + "notes": [ + "新增 app/schedule/auto_finish_pack_task.js:interval 1h、type worker、非 immediate,单 worker 防重入(ctx.app._autoFinishPackTaskRunning)", + "新增 app/service/systems/pack_task_auto_finish.js:扫描 status < 2 且 start_time 非空的任务,按 warehouse_id 去重后经 deliveryOrder.getStoreSubjectConfig(缓存优先)拉取配置,pack_mode=2 按团购时长、其余按散单时长", + "超时判定:当前时间 - 开始时间 > 配置分钟数;结束时间 = 开始时间 + 上限时长(而非当前时间),status 置为 2", + "未配置有效时长(缺失或非正整数)的仓库跳过,不做自动结束;任务 start_time 非法时跳过", + "配置字段与仓库设置联动:single_order_pack_max_minutes / group_order_pack_max_minutes 已在 WAREHOUSE_SETTING_FIELDS 与 Store.normalizeSubjectConfig 中注册,默认值 3 / 40 分钟" + ], + "module": "setting.warehouse" + }, + { + "version": "2026.08.15-warehouse-pack-max-minutes", + "date": "2026-08-15", + "type": "added", + "summary": "仓库设置 setting.warehouse 新增打包最大时长配置:single_order_pack_max_minutes 散单打包最大时长(分钟,默认 3)、group_order_pack_max_minutes 团购打包最大时长(分钟,默认 40)", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 WAREHOUSE_SETTING_FIELDS 中新增 single_order_pack_max_minutes(integer,非必填,默认 3,min 1)与 group_order_pack_max_minutes(integer,非必填,默认 40,min 1)", + "wms_store.subject_config 默认值同步补齐(app/model/store.js DEFAULT_SUBJECT_CONFIG),normalizeSubjectConfig 增加大于 0 的整数校验,空值回退默认", + "methods/system.json 中 getSettings 响应与 saveSettings 入参补充对应字段文档", + "向后兼容:新增字段为可选,不影响既有仓库设置读写" + ], + "module": "setting.warehouse" + }, + { + "version": "2026.08.15-recheckOrder.scanOrder.groupInterceptSeq", + "date": "2026-08-15", + "type": "fixed", + "summary": "修复 order.recheckOrder.scanOrder 团购模式拦截订单识别:原逻辑仅匹配不存在的 'intercepted' 状态,导致已进入拦截流程的订单(requested/requesting/intercepting/intercepted_in_transit/intercepted_at_warehouse)被当作正常订单,团购复核数据不输出拦截订单及其序号。现统一按真实拦截状态枚举归类到波次项 intercepted 列表,并输出 wave_index 波次内序号", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.scanTask" + ], + "notes": [ + "新增 isInterceptedOrderStatus 辅助方法:intercepted / requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse 均视为拦截流程状态", + "buildGroupWaveList 拦截订单分离改用 isInterceptedOrderStatus,拦截订单不再进入正常订单校验与统计,仓库已拦截订单不再阻断整个团购扫描视图加载", + "团购波次项 intercepted 列表每项新增 waybill_no 字段,wave_index 为波次内序号(优先读取 wms_order_wave_index 真实序号,无记录时降级数组临时序号)", + "confirmRecheckByWaveId 团购波次批量复核同步修正拦截识别,拦截订单不再被批量标记复核", + "同步更新 methods/system.json 中 scanOrder 团购波次项 intercepted 字段说明" + ], + "module": "order" + }, + { + "version": "2026.08.15-parseAddress.batch", + "date": "2026-08-15", + "type": "enhanced", + "summary": "parseAddress 支持数组批量入参:addresses(或 address)传字符串数组时批量解析,响应 data.list 按输入顺序返回每条地址的解析结果(含失败条目逐条错误信息)", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "入参兼容三种形态:address 字符串(单条,原行为不变)、address 字符串数组、addresses 字符串数组(优先)", + "批量解析:按每 10 条合并为一个 DeepSeek 请求并行发出(deepseek-v4-flash),全部返回后按输入顺序聚合,单次上限 50 条;失败/缺失条目逐条回退单条解析,不影响其他条目", + "批量响应 data.list 每条元素包含 address/flag/message/province/city/area/town/detailAddress/name/mobile,失败条目 flag=failure、message 为具体错误原因、解析字段为空字符串,不影响其他条目", + "抽取 _parseSingleAddress 私有方法复用单条解析逻辑,单条响应结构与之前完全一致", + "同步更新 methods/system.json 中 parseAddress 的参数与响应字段说明" + ], + "module": "order" + }, + { + "version": "2026.08.14-afterSale.detail-desc-first-step", + "date": "2026-08-14", + "type": "enhanced", + "summary": "enhance: afterSale.detail 步骤列表默认将售后详细描述作为第一条 step 输出(虚拟步骤不落库),保证详情页首条即可看到售后问题描述。", + "methods": [ + "afterSale.detail" + ], + "notes": [ + "售后主表 description 非空时,steps 列表头部前置一条虚拟步骤:action=售后描述、remark=description、step_status=pending、created_at=主表创建时间、attachments=[]、is_virtual=true、id=null", + "虚拟步骤不写入 wms_after_sale_detail,仅在 detail 响应中动态拼接", + "after_sale.started_at 仍取首条真实步骤记录的创建时间,不受虚拟步骤影响", + "description 为空时不生成虚拟步骤,行为与之前一致", + "同步更新 methods/system.json 中 afterSale.detail 的 steps 字段说明" + ], + "module": "afterSale" + }, + { + "version": "2026.08.14-afterSale.workList-storeName", + "date": "2026-08-14", + "type": "changed", + "summary": "afterSale.workList 返回列表行新增 store_name 货主名称字段:取合约表 wms_store_warehouse.store_remask 货主备注名称,无合约或备注为空时回退 wms_store.company_name 公司全称,无货主时为空字符串", + "methods": [ + "afterSale.workList" + ], + "notes": [ + "systems/afterSale.js list() 新增 opts.enrichStoreName 开关,开启后调用新增私有方法 _enrichListStoreNames 批量补充:按行收集 store_id/warehouse_id,一次查询 StoreWarehouse(store_remask)与 Store(company_name),映射后写入每行 store_name", + "systemMethods/afterSale.js workList 调用 list 时传 enrichStoreName: true;auditList 不受影响", + "向后兼容:仅在列表行新增 store_name 字段,不影响既有字段", + "同步更新 methods/system.json 中 afterSale.workList 的 response.list 字段说明" + ], + "module": "afterSale" + }, + { + "version": "2026.08.14-returnUnpack.stockDetails", + "date": "2026-08-14", + "type": "changed", + "summary": "returnUnpack 明细补充库存详情:detail/detailList/addDetail/updateDetail 返回的明细行统一走 stockWarehouse.getStockDetails 通用方法附加 stock 字段(item_code/item_name/sku_property/barcodes 条码数组/image_url 图片数组/packing_requirements/stock_unit/quantity/locked_quantity 等,带缓存),补齐条码与照片信息;create 幂等复用返回的 record.details 同步受益", + "methods": [ + "returnUnpack.detail", + "returnUnpack.detailList", + "returnUnpack.addDetail", + "returnUnpack.updateDetail", + "returnUnpack.create" + ], + "notes": [ + "systems/return_unpack.js 新增私有方法 _enrichDetailsWithStock:收集明细 stock_id 批量调用 stockWarehouse.getStockDetails(缓存 key cache:stock_detail:{warehouseId}:{stockId}),按 stock_id 映射为明细行 stock 字段;未识别明细(stock_id 为空)/商品失效/拉取失败时 stock=null,不影响主流程", + "detail:record.details 逐条附加 stock;detailList:list 逐条附加 stock(取首行 warehouse_id 作为查询仓库);addDetail/updateDetail:返回 detail 附加 stock(用主表 warehouse_id)", + "向后兼容:明细行原有字段与 stockWarehouse 关联保持不变,仅新增 stock 字段", + "同步更新 methods/system.json 中 create/detail/detailList/addDetail/updateDetail 的响应字段说明" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.14-returnUnpack.createReuse", + "date": "2026-08-14", + "type": "changed", + "summary": "returnUnpack.create 增加幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频+原订单详情,并携带 reused=true 标识;同运单号多张拆包单时优先复用已录明细的最新单;超过 3 个月视为运单号复用,按新单正常创建", + "methods": [ + "returnUnpack.create" + ], + "notes": [ + "开单前先按 warehouse_id+waybill_code+created_at>=3个月前 查全部非 cancelled 拆包单(created_at DESC, id DESC)", + "同运单号存在多张拆包单时优先复用已录明细的最新单(按 wms_return_unpack_detail 真实计数判定,不依赖主表冗余 total_items),避免命中并发/重复点击产生的空单导致返回明细为空;全部无明细时复用最新单", + "命中时复用 detail 查询逻辑组装 record(含 details 明细+stockWarehouse 关联、videos、returnReceived)与 related.order,返回字段新增 reused=true", + "查重失败仅记日志不阻断开单主流程;3 个月时间基准与退回查询记录反查货主窗口一致", + "同步更新 methods/system.json 中 returnUnpack.create 的 description 与 response(record/reused 字段说明)" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.14-warehouse-receive-address", + "date": "2026-08-14", + "type": "added", + "summary": "仓库设置 setting.warehouse 新增仓库收货地址配置字段 receiver_address(一行文本,退货/退件收件地址)", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 WAREHOUSE_SETTING_FIELDS 中新增 receiver_address(string,非必填,默认空字符串,最大长度 500)", + "wms_store.subject_config 默认值同步补齐(app/model/store.js DEFAULT_SUBJECT_CONFIG)", + "methods/system.json 中 getSettings 响应与 saveSettings 入参补充对应字段文档", + "向后兼容:新增字段为可选,不影响既有仓库设置读写" + ], + "module": "setting.warehouse" + }, + { + "version": "2026.08.13-stockQueryWhere", + "date": "2026-08-13", + "type": "added", + "summary": "storage.receiving.getReceivingList / getStoreReceivingList 新增 stock_query_where 参数:按商品条码/商品编码/商品ID 搜索,经收货明细关联过滤收货单列表(仓库侧与货主侧同步支持)", + "methods": [ + "storage.receiving.getReceivingList", + "storage.receiving.getStoreReceivingList" + ], + "notes": [ + "新增 stock_query_where 入参(string|string[], optional, body,前端通常传数组),搜索范围:wms_stock_barcodes.barcode + wms_stock_warehouse.item_code + wms_stock_warehouse.id(纯数字时精确匹配)", + "解析链路:stock_query_where → wms_stock_warehouse.id 集合 → wms_receiving_detail.system_product_id IN 集合 → receiving_id 列表", + "与 filterDepleted、entry_order_id 可组合使用(多组过滤取交集,仓库侧),无匹配结果时返回空列表", + "代码变更:systems/storage/receiving.js 新增 _resolveStockQueryReceivingIds 并对两个列表方法注入过滤;systemMethods/storage/receiving.js 两个列表方法均透传 stock_query_where;methods/system.json 两个接口均新增参数文档" + ], + "module": "storage" + }, + { + "version": "2026.08.12-confirmIntercept-doc", + "date": "2026-08-12", + "type": "updated", + "summary": "order.recheckOrder.confirmIntercept 文档描述补全:补充释放储位分配、释放订单锁等副作用说明,明确各副作用失败不阻断主流程的容错语义", + "methods": [ + "order.recheckOrder.confirmIntercept" + ], + "notes": [ + "description 补充:拦截成功后会释放储位分配(cancelAllocateStorage)与订单锁(lock_status=none)", + "description 补充:储位释放、锁释放、日志写入失败均不影响主流程(try/catch 容错)", + "仅文档变更,不修改业务代码" + ], + "module": "order" + }, + { + "version": "2026.08.12-interceptScan", + "date": "2026-08-12", + "type": "added", + "summary": "order.recheckOrder.interceptScan 新增拦截扫描接口:通过运单号查找运单,标记退回+拦截(is_back='Y', is_intercept='Y');运单记录不存在时自动创建补充;处理关联售后工单(写入「库内拦截成功」并完结);订单级拦截覆盖所有面单含子面单(与 confirmIntercept 一致)", + "methods": [ + "order.recheckOrder.interceptScan" + ], + "notes": [ + "入参:waybill_code(string, required),运单号", + "运单记录不存在时自动创建(INSERT wms_order_express),而非抛 404,确保缺失快递被补充", + "同时设置 is_back='Y' 和 is_intercept='Y'", + "查 wms_after_sale 表(未完结工单),命中则调用 handleWorkOrder 写入「库内拦截成功」步骤并置 status=completed;工单处理失败不阻断主流程", + "订单拦截与 confirmIntercept 一致:只要有 order_id 即更新 wms_order_delivery.intercept_status = intercepted_at_warehouse,并释放储位分配与订单锁,写入 ORDER_INTERCEPT_CONFIRM 操作日志;不再区分 business_key,子面单同样会触发订单级拦截", + "免权限/免日志/免鉴权(与 confirmIntercept 同级)", + "代码变更:recheckOrder.js 构造函数 + interceptScan 方法(~180行);methods/system.json 新增 API 文档" + ], + "module": "order" + }, + { + "version": "2026.08.10-storageTransaction-keyword", + "date": "2026-08-10", + "type": "updated", + "summary": "storage.transaction.list 新增 keyword 快捷搜索参数,支持按 item_code(商品编码) 和 barcode(条码) 模糊匹配,内部解析为 stock_id 列表后以 IN 条件合并到查询中", + "methods": [ + "storage.transaction.list" + ], + "notes": [ + "新增 keyword 参数(string, optional),搜索范围为 stock_warehouse.item_code + stock_barcodes.barcode", + "keyword 解析复用已有 _resolveKeywordToStockIds 方法,与 stock.report.search 的 keyword 解析逻辑一致", + "keyword 可与 where 条件叠加使用(交集),无匹配结果时直接返回空列表", + "代码变更:stock_transaction.js list() 增加 keyword 参数并在 baseWhere 中注入 stock_id IN 条件;systemMethods/storage/transaction.js 透传 keyword" + ], + "module": "storage" + }, + { + "version": "2026.08.10-stockTransaction-keyword-doc", + "date": "2026-08-10", + "type": "updated", + "summary": "stock.transaction.list 补全 keyword 快捷搜索参数文档。代码层已支持 keyword(通过 queryList → _resolveKeywordToStockIds),本次仅补文档", + "methods": [ + "stock.transaction.list" + ], + "notes": [ + "新增 where.keyword 参数文档(string, optional),搜索范围为 stock_warehouse.item_code/item_name/goods_code + stock_barcodes.barcode + SKU ID", + "keyword 解析复用已有 _resolveKeywordToStockIds 方法,与 stock.report.search 逻辑一致", + "keyword 与 stock_ids 互斥(keyword 优先),无匹配结果时返回空列表", + "仅文档变更,不修改业务代码" + ], + "module": "stock" + }, + { + "version": "2026.08.09-afterSale-doc", + "date": "2026-08-09", + "type": "updated", + "summary": "补全 afterSale 组全部 11 个 method 的文档:workList/auditList/detail/create/transfer/handleWorkOrder/registerClaim/export/exportTaskProgress/workCount 的 params 与 response 补全 description,移除 create 中冗余 warehouse_id 参数(后端自动注入),明确各枚举值、关联表、业务语义。", + "methods": [ + "afterSale.workList", + "afterSale.auditList", + "afterSale.detail", + "afterSale.create", + "afterSale.transfer", + "afterSale.handleWorkOrder", + "afterSale.registerClaim", + "afterSale.export", + "afterSale.exportTaskProgress", + "afterSale.workCount" + ], + "notes": [ + "afterSale.create:移除 warehouse_id 参数(后端从 ctx.user.store_id 自动注入),补全所有 12 个参数的 description(含 type/sub_type 枚举值),response 新增 status 和 role_group 字段。", + "afterSale.transfer:补全 id/role_group/remark 的 description,response 新增 role_group 字段。", + "afterSale.handleWorkOrder:补全 action/status/attachment_ids 的 description,明确 action 示例和 status 枚举。", + "afterSale.registerClaim:补全 10 个参数的 description,明确 claim_status/carrier_claim_status 枚举值(pending/reviewing/approved/paid/monthly/rejected)。", + "afterSale.workList/auditList:补全 pagination/where/sort 与 response 的 description。", + "afterSale.export/exportTaskProgress:补全参数和响应的 description,明确 task_id 用途。", + "afterSale.workCount:已有完整 description,本次未修改。", + "仅文档变更,不修改任何业务代码或接口语义。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.07-stockout-express", + "date": "2026-08-07", + "type": "changed", + "summary": "wms_order_stockout 表新增 express_code / express_codes 字段;storage.stockout.confirm 改为读表字段回传,不再随机生成;新增 storage.stockout.updateExpress 接口。", + "methods": [ + "storage.stockout.confirm", + "storage.stockout.updateExpress" + ], + "notes": [ + "DB 迁移:20260807120000-add-express-code-to-wms-order-stockout.js 添加 express_code VARCHAR(50) 和 express_codes JSON 字段。", + "Model:order_stockout.js 新增 express_code / express_codes 字段定义。", + "storage.stockout.confirm:回传时不再随机生成 expressCode,改为读取表中 express_code / express_codes;express_code 为空则拒绝确认(400)。", + "storage.stockout.updateExpress:新增接口,用于在确认前更新运单号,支持 express_code(单个)和 express_codes(列表)两个字段。", + "qimenMethods/stockout.js confirm 同步调整,透传 expressCodes。" + ], + "module": "storage" + }, + { + "version": "2026.08.07-stockout-confirm", + "date": "2026-08-07", + "type": "added", + "summary": "新增 storage.stockout.confirm 直出确认接口:不改变内部库存,按出库单明细计划数量直接确认,状态推进到 COMPLETED。", + "methods": [ + "storage.stockout.confirm" + ], + "notes": [ + "入参:id(出库单ID,必填)。", + "逻辑:校验 canConfirm (CREATED/PENDING) → 事务内更新 order_status=COMPLETED、actual_qty=plan_qty。", + "返回:id、stockout_order_code、order_status、logisticsName(固定OTHER)、expressCode(随机生成)。", + "对应奇门 stockout.confirm 接口,由 qimenMethods/stockout.js confirm 方法调用。" + ], + "module": "storage" + }, + { + "version": "2026.08.07-stockout-list-fix", + "date": "2026-08-07", + "type": "changed", + "summary": "修复 storage.stockout.list / listItems 读错表:从 OrderDeliveryFactory/OrderItemsFactory 改为直接读取 OrderStockout/OrderStockoutItems 模型(wms_order_stockout 表)。", + "methods": [ + "storage.stockout.list", + "storage.stockout.listItems" + ], + "notes": [ + "list:数据源 OrderDeliveryFactory → OrderStockout;软删字段 delete_at → deleted_at;快速搜索字段适配 stockout_order_code/remark;排序字段适配 order_status/order_type/created_at/order_create_time。", + "listItems:数据源 OrderDeliveryFactory+OrderItemsFactory → OrderStockout+OrderStockoutItems;参数 delivery_order_code → stockout_order_code(兼容旧参数名)。", + "response 字段 items → list,与实际返回一致。" + ], + "module": "storage" + }, + { + "version": "2026.08.06-inbox-bindCode", + "date": "2026-08-06", + "type": "added", + "summary": "新增货主绑群码生成接口。校验 StoreWarehouse 合约有效性后生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。实现位于 systems/store.js → bindCode(),由 systemMethods/inbox.js → bindCode() 委托调用。", + "methods": [ + "inbox.bindCode" + ], + "notes": [ + "调用链:/system → systemMethods/inbox.bindCode → systems/store.bindCode。", + "前置校验:StoreWarehouse 合约 auth_status=2 AND warehouse_use_status=1,不满足则返回500。", + "缓存策略:app.setCacheAsync('chat:bind:{warehouseId}:{code}', { store_id, initiator_subject_id, warehouse_id, group_type, sub_type }, 300)。", + "绑定时消费:processor.tryBindGroup 匹配 '授权:CODE' 模式,读取缓存执行绑定,成功即清缓存。", + "warehouseId:从 ctx.user.store_id 自动注入,前端无需传递。" + ], + "module": "inbox" + }, + { + "version": "2026.08.05-inbox-group", + "date": "2026-08-05", + "type": "added", + "summary": "站内信模块新增群管理接口:群列表拉取、群禁用/解禁、群信息修改(支持群类型/子类型/货主/快递接口/系统快递编码)、按群查询消息列表。仓库ID由服务端自动注入。express_interfaces输出为数组,systemExpressCode在express类型时必填校验。", + "methods": [ + "inbox.group.list", + "inbox.group.disable", + "inbox.group.update", + "inbox.group.messages" + ], + "notes": [ + "inbox.group.list:按群类型/关键词筛选,分页返回。express_interfaces 存储逗号分隔输出数组。", + "inbox.group.disable:通过群主键ID禁用/解禁(isBlocked=1禁用/0启用)。", + "inbox.group.update:支持修改groupType/subType/storeId/expressInterfaces/systemExpressCode。切换为express类型时systemExpressCode必填且需校验wms_express.code存在,expressInterfaces需校验wms_express_interface.id存在。非express类型忽略express相关字段。", + "inbox.group.messages:按groupId拉取消息列表,支持direction/keyword筛选,仓库隔离,查询命中idx_warehouse_group_created索引。", + "公共:所有方法warehouseId均从ctx.user.store_id自动注入,前端无需传递。" + ], + "module": "inbox" + }, + { + "version": "2026.08.01-system-01", + "date": "2026-08-01", + "type": "added", + "summary": "新增 apiApp 仓库 API 应用管理模块,支持当前仓库维度的 API 应用 CRUD、AppKey/Secret 自动生成与重新生成、IP 白名单、回调地址、限流等配置", + "methods": [ + "apiApp.list", + "apiApp.detail", + "apiApp.create", + "apiApp.update", + "apiApp.delete", + "apiApp.regenerateSecret" + ], + "notes": [ + "apiApp.list:分页查询当前仓库 API 应用列表,支持按 app_name(模糊)、is_enabled 筛选,Secret 自动脱敏(前8位+****)。", + "apiApp.detail:按 ID 查询单个应用详情,需同时匹配 warehouse_id(自动注入 ctx.user.store_id),Secret 脱敏。", + "apiApp.create:创建应用时自动生成 AppKey(AK{yyyyMMddHHmmss}{random8hex})和 AppSecret(64位hex)。默认 interface_type_id 取 WH_CHANNEL。仅创建时返回完整 Secret。", + "apiApp.update:更新可编辑字段(app_name、self_ip_whitelist、callback_url、rate_limit、sign_method、is_enabled),不可变字段为 self_app_key 和 interface_type_id。", + "apiApp.delete:软删除(is_enabled=0),不物理删除。", + "apiApp.regenerateSecret:重新生成 64位hex AppSecret,旧 Secret 立即失效。仅此次返回完整 Secret。", + "仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。", + "Secret 安全策略:list/detail/update 返回脱敏值,仅 create/regenerateSecret 返回完整 Secret。" + ], + "module": "apiApp" + }, + { + "version": "2026.07.31-system-02", + "date": "2026-07-31", + "type": "added", + "summary": "新增 storage.inventory.export 库存导出与 storage.inventory.exportTaskProgress 导出进度查询,入参复用 list 的 where/sort/group_by_batch 语义,支持两种导出模式(聚合汇总 / 逐条明细),库位信息一并导出", + "methods": [ + "storage.inventory.export", + "storage.inventory.exportTaskProgress" + ], + "notes": [ + "storage.inventory.export:异步提交导出任务,返回 task_id 与受理信息,后端异步生成 Excel 并上传。入参 where/sort/group_by_batch 与 storage.inventory.list 完全一致,无需额外学习成本。", + "group_by_batch=false(默认):按 stock_id + space_id(库位)聚合导出库存汇总,含商品编码/名称/规格/单位/货主/库位编码/名称/总库存/锁定/可用/批次数/最近入库时间。", + "group_by_batch=true:按 storage_id 逐条导出库存明细,含库存记录ID/商品信息/库位信息/批次号/库存类型/数量/生产日期/过期日期/入库时间/入库单号/供应商批次号。", + "新增 storage.inventory.exportTaskProgress:按 task_id/taskId 查询导出任务进度与状态(submitted/running/success/failed/not_found),status=success 时返回 download_url 供客户端下载。", + "导出文件目录:exports/storage/inventory/{warehouseId}/,缓存 TTL 1800 秒。" + ], + "module": "storage.inventory" + }, + { + "version": "2026.07.31-system-01", + "date": "2026-07-31", + "type": "added", + "summary": "新增按波次批量快捷复核接口 batchQuickRecheckByWave,支持批量波次 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败", + "methods": [ + "order.recheckOrder.batchQuickRecheckByWave" + ], + "notes": [ + "新增 order.recheckOrder.batchQuickRecheckByWave 方法,复用 batchQuickRecheck 的 _completePickForOrder / _markRecheckForOrder / _tryCompleteWaveInTransaction 等内部事务方法", + "入参 wave_ids 支持数组或逗号分隔字符串,兼容 waveIds(驼峰)、wave_id(单值)", + "按波次维度批量查询订单后逐波次、逐订单执行前置校验与复核,每个订单独立事务,部分失败不影响其他订单", + "响应包含 success/failed 列表及计数,failed 项含 order_id、wave_id、delivery_order_code、reason 说明;波次下无订单时仅返回 wave_id + reason" + ], + "module": "order.recheckOrder" + }, + { + "version": "2026.07.29-system-01", + "date": "2026-07-29", + "type": "added", + "summary": "补全 waybill.warehouse group API 文档参数定义:完善 list/detail/export 的 params 与 response,新增 exportTaskProgress 异步进度查询接口", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export", + "waybill.warehouse.exportTaskProgress" + ], + "notes": [ + "waybill.warehouse.list:params 含 pagination/where/sort 完整字段定义,where 支持 15 个筛选维度(运单号、主单号、订单ID、订单号、物流编码、物流接口ID、平台编码、状态、退回/拦截/星河签收、包材ID、已称重、关键词、创建时间范围),sort 白名单 create_at/weighing_weight/id。response 含 list(28 个字段)+ pagination。", + "waybill.warehouse.detail:修正 id 参数为可选(required: false),与 waybillCode 二选一,waybillCode 优先。response 含 id/waybill_code/main_waybill_code/waybill_type/business_key/sibling_waybills/order/logistics/status_info/weight/package/print_records/print_count 等完整详情。", + "waybill.warehouse.export:response 补充 progress/message/update_time 字段,完整覆盖异步任务返回信息。", + "新增 waybill.warehouse.exportTaskProgress:按 task_id/taskId 查询导出进度,response 含 task_id/status/progress/current_count/total_count/message/result/error/download_url/update_time。", + "所有接口 isNeedAuth: false, isNeedLogin: true,仓库隔离通过 ctx.user.store_id 自动注入。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.07.28-system-01", + "date": "2026-07-28", + "type": "added", + "summary": "新增 order.pendingOrder.batchMarkPrinted:批量设置订单为已打印状态,将 print_status 更新为 'fin'", + "methods": [ + "order.pendingOrder.batchMarkPrinted" + ], + "notes": [ + "同步批量更新接口,传入订单ID数组,直接将符合条件的订单 print_status 设为 'fin'。", + "双表查询:先查 current 表(wms_order_delivery_{warehouseId}),未命中的 ID 再兜底查 dispatch 表(wms_order_delivery_{warehouseId}_dispatch)。", + "dispatch 表查询失败仅记录 warn 日志,不影响 current 表已更新的结果。", + "仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。", + "仓库上下文强制从 ctx.user.store_id 获取,禁止传入外部仓库ID。", + "入参支持 order_ids / orderIds / ids 三种别名,优先级 order_ids > orderIds > ids。", + "返回 updated_count 表示实际更新条数(current + dispatch 合计),ids 原样回传请求的订单ID列表。", + "写入操作日志 operation_code: ORDER_BATCH_MARK_PRINTED。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.27-system-03", + "date": "2026-07-27", + "type": "changed", + "summary": "storage.receiving 导出接口拆分:export 改为按仓库维度,新增 storeExport 按货主维度导出", + "methods": [ + "storage.receiving.export", + "storage.receiving.exportTaskProgress", + "storage.receiving.storeExport", + "storage.receiving.storeExportTaskProgress" + ], + "notes": [ + "export 改为仓库维度:过滤条件从 store_id(平台激活货主)改为 warehouse_id(ctx.user.store_id),与 getReceivingList 保持一致。", + "exportTaskProgress 同步更新为仓库维度进度查询,任务 ID 前缀 receiving_export_。", + "新增 storeExport:货主维度导出,通过平台激活上下文获取 store_id,过滤逻辑与 getStoreReceivingList 一致。", + "新增 storeExportTaskProgress:货主维度进度查询,复用 exportTaskProgress 的缓存逻辑,任务 ID 前缀 receiving_store_export_。", + "导出格式:双 Sheet Excel(Sheet1=收货单列表 21 列,Sheet2=收货单明细 17 列),通过 ExcelJS stream + uploadService 上传 COS。", + "仓库导出上传路径 exports/receiving/{warehouseId}/,货主导出上传路径 exports/receiving/store/{storeId}/。", + "修复 exportReceivingList 中 where 条件二次解析问题:增加 ctx.whereParsed 复用(与 getStoreReceivingList 一致),避免 prepareWhereContext 已解析后再重复 parseWhereConditions 导致边界条件丢失。", + "命名对齐 entry 侧:storeExport / storeExportTaskProgress 方法名、任务 ID 前缀、上传路径均与 storage.entry.storeExport 模式一致。" + ], + "module": "storage.receiving" + }, + { + "version": "2026.07.27-system-02", + "date": "2026-07-27", + "type": "added", + "summary": "新增 order.pendingOrder.allocateSubOrderNumber:待处理订单分配子单号(异步任务),business_key 从 2 开始递增,跳过已分配运单号;新增 allocateSubOrderNumberProgress 按 task_id/business_key 查询进度", + "methods": [ + "order.pendingOrder.allocateSubOrderNumber", + "order.pendingOrder.allocateSubOrderNumberProgress" + ], + "notes": [ + "新增 allocateSubOrderNumber:入参 order_id + sub_order_count,按 business_key 2..(2+count-1) 全量传入 createWaybillCodePipeline。", + "并发安全:全量传入 pipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发去重。", + "pipeline 内部 createWaybillCode 事务:status=1 已分配→跳过;status=0 占位中→复用;无记录→INSERT status=0 占位。", + "异步任务模式:请求立即返回 task_id(sub_ 前缀),后台 setImmediate 执行,进度通过 Redis 缓存追踪。", + "新增 allocateSubOrderNumberProgress:支持 task_id 查整体进度,business_key 可选参数过滤单个业务ID的详情。", + "进度状态 submitted→running→success/partial/failed,progress 对应 5/50/80/100。", + "result.details 数组记录每个 business_key 的 status(skipped/allocated/failed/pending)与 waybill_code。", + "buildSubOrderDetails 回查最终状态:status=1+waybill→allocated,status=0→failed,无记录→failed。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.27-system-01", + "date": "2026-07-27", + "type": "added", + "summary": "新增 order.packing 打包任务模块:list/get 查询 + setEndTime 设置结束时间,含视频 CDN URL 拼接与状态回写", + "methods": [ + "order.packing.list", + "order.packing.get", + "order.packing.setEndTime", + "order.packing.forceRecord" + ], + "notes": [ + "新增 order.packing.list:按仓库维度查询打包任务列表,支持分页/筛选/排序,关联工作台、视频和运单信息。", + "新增 order.packing.get:按 id + warehouse_id 查询单条打包任务详情。", + "新增 order.packing.setEndTime:设置打包任务结束时间,入参 id + end_time;若任务状态不是已完成(2)则同步更新为已完成。", + "新增 order.packing.forceRecord:强制重新录制打包任务视频,入参 id;校验录制电脑在线后重置视频状态并推送打印服务。", + "前端默认值逻辑:若任务已有 end_time 则打开时默认为当前时间,否则默认为 start_time + 5分钟。", + "视频 URL 自动拼接 CDN 域名前缀:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath};录制电脑从 wms_print_computer 按 is_recording=true 获取。", + "视频响应新增 status 字段(created/recording/completed/failed),与数据库 ENUM 保持一致。", + "pack_task_video Model 的 status 字段从 TINYINT 改为 STRING(20) 以匹配 DB ENUM 迁移。", + "forceRecord 通过打印服务 /record/force 推送录制任务,传入 pack_task_id、warehouse_id、computer_id、camera_ids。" + ], + "module": "order.packing" + }, + { + "version": "2026.07.10-system-01", + "date": "2026-07-10", + "type": "added", + "summary": "新增 storage.report.searchStore 货主侧库存报表,以 store_id 为主维度查询库存流水", + "methods": [ + "storage.report.searchStore", + "storage.report.exportStore" + ], + "notes": [ + "新增 searchStore 方法:与 search 共享核心逻辑,通过 searchMode='store' 切换主维度从 warehouse_id → store_id。", + "新增 exportStore 方法:与 export 共享核心逻辑,支持货主侧导出 Excel(含汇总 + 变更记录两个 sheet)。", + "systems 层 search/export 方法新增 searchMode 参数(默认 'warehouse'),不影响现有 warehouse 侧行为。", + "货主侧使用 ctx.user.store_id 作为主维度 store_id,辅助维度支持 warehouse_ids 过滤特定仓库。", + "systemMethods 层 searchStore 从 where.warehouse_ids 取值传给 search 的 storeIds(承载 warehouse 过滤)。", + "输出新增 warehouse_id / warehouse_name 字段,货主侧可区分不同仓库的库存。search 方法也同步输出这两个字段(向后兼容)。", + "修复 getStockDetails 的 warehouseId 判断:从 != null 改为 !== undefined,使显式传 null 可跳过 warehouse 过滤。", + "修复 loadReportReferenceMaps 未传递 warehouseId 给 getStockDetails 的问题。" + ], + "module": "storage.report" + }, + { + "version": "2026.07.09-system-01", + "date": "2026-07-09", + "type": "updated", + "summary": "签约 sign 方法改造:统一当前主体→store_id,解除角色校验,仓库可签仓库", + "methods": [ + "storeWarehouse.store.sign", + "storeWarehouse.warehouse.sign" + ], + "notes": [ + "resolvePairIds:统一当前主体始终在 store_id(货主方/消费方),对方在 warehouse_id(仓库方/提供方)。不再根据 isWarehouse 分支。", + "getCounterparty:移除 expectedRole 角色校验(仓库不再只能签货主,可签仓库)。", + "findScopedRelation:改为 OR 查询 store_id/warehouse_id 两边,兼容新旧签约数据。", + "sign preview:counterparty.role 改为根据对方 project 真实返回(warehouse/store),不再硬编码反推。", + "签仓库:仓库发起签约时对方 ID 传 counterparty_id,系统自动将当前仓库放 store_id。" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.07.08-system-01", + "date": "2026-07-08", + "type": "updated", + "summary": "storeWarehouse.store.list 与 storeWarehouse.warehouse.list 拆分实现,不再共用;仓库侧支持查询外部合作仓库", + "methods": [ + "storeWarehouse.store.list", + "storeWarehouse.warehouse.list" + ], + "notes": [ + "拆分:store.list 调用 listForStore,warehouse.list 调用 listForWarehouse,不再共用同一个 list 方法。", + "新规则:两个方法均按 store_id = 当前主体ID 过滤(主体在 store_id 为货主方/消费方,对方在 warehouse_id 为仓库方/提供方)。", + "warehouse.list 新增支持查询外部合作仓库:当对方主体的 project='warehouse' 时为仓库-仓库合作,counterparty_role='warehouse'。", + "响应新增 counterparty_role 字段(store/warehouse),标识对方主体的真实角色。", + "warehouse.list 响应 use_status 改为 store_use_status(仓库在 store_id 方时,己方启用状态应为 store_use_status)。", + "旧 list 方法保留标记为 @deprecated,保持向后兼容。", + "新增 buildListWhereByStoreId 统一按 store_id 维度构建查询条件。" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.07.06-system-01", + "date": "2026-07-06", + "type": "updated", + "summary": "order.wave.batchList:响应新增 pick_assignment_status(拣货分配状态),按订单 pick_status 聚合判定", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "响应 list 每项新增字段 pick_assignment_status (string):拣货分配状态,按波次下订单的 pick_status 聚合判定。", + "取值语义与 resolveAssignmentStatus 一致,自定义标签:未拣货(全 none)、部分拣货(混合且无 error)、已拣货(全 fin)、拣货异常(含 error)。", + "SQL 子查询新增 pick_none_count / pick_fin_count / pick_error_count 聚合列。" + ], + "module": "order.wave" + }, + { + "version": "2026.07.05-system-01", + "date": "2026-07-05", + "type": "added", + "summary": "新增 pick.wavePickComplete:传入 wave_id 一键完成整个波次拣货,内部复用 query 去重与任务创建逻辑后自动调用 wavePickTaskComplete(mode=1)", + "methods": [ + "pick.wavePickComplete" + ], + "notes": [ + "新增方法:pick.wavePickComplete,入参 wave_id(number,必填)。", + "内部流程:按 wave_id 查波次 → 活动任务去重(同用户复用 / 他人409冲突)→ 完成任务去重 → 无任务则创建(source=2 后台抓取)→ 调用 pick.wavePickTaskComplete mode=1 全部确认。", + "创建任务 remark 格式:pick.wavePickComplete wave_id={waveId},用于与 pick.query 区分。", + "响应:task_id、status(completed / already_completed)、tip、confirmed_order_ids、is_completed、progress。", + "错误码:400(参数/波次无订单)、401(缺少操作人)、404(波次不存在)、409(他人活动任务冲突)、500(创建/完成失败)。" + ], + "module": "pick" + }, + { + "version": "2026.07.03-system-02", + "date": "2026-07-03", + "type": "added", + "summary": "新增 order.pendingOrder.updateRemark:批量修改待处理订单备注(remark),不受 post_status 限制", + "methods": [ + "order.pendingOrder.updateRemark" + ], + "notes": [ + "新增方法:order.pendingOrder.updateRemark,用于批量修改待处理订单的备注(remark)字段。", + "入参:ids(number[],必填,正整数数组,不能为空)、remark(string,必填,最大500字符)。", + "特性:不受 post_status 限制,可对所有状态的订单生效;纯批量不支持单ID。", + "更新成功后写入操作日志。", + "响应:updated_count(number,实际更新行数)、ids(number[],原样返回请求的ID数组)。", + "错误码:400(ids 不能为空 / ids 仅支持正整数数组 / remark 不能为空)。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026.07.03-system-01", + "date": "2026-07-03", + "type": "updated", + "summary": "将 quick.waybill.toOrder 迁移为 index.toOrder 并移入基础模块,新增 waves 返回字段", + "methods": [ + "quick.waybill.toOrder", + "index.toOrder" + ], + "notes": [ + "移除快捷操作(quick)模块分组,原 quick.waybill.toOrder 方法从 methods/system.json 删除。", + "在基础模块(index)新增 index.toOrder 方法:入参仍为 waybill_code,响应从单一 order_id 扩展为 order_id + waves 结构。", + "waves 为数组,每项含 wave_id(波次ID)、wave_no(波次号)、order_ids(波次下所有订单ID列表),无波次时为空数组。", + "查询路径:运单号 → wms_order_express(status=1)→ order_id + warehouse_id → 遍历 current/history/dispatch 表获取波次信息 → 再遍历多表获取同波次所有订单ID。" + ] + }, + { + "date": "2026-06-24", + "type": "addition", + "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", + "version": "2026-06-24-add-bind-receiving-details", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [] + }, + { + "date": "2026-06-24", + "type": "deprecation", + "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", + "version": "2026-06-24-deprecate-manual-match-entry-order", + "methods": [ + "storage.receiving.manualMatchEntryOrder" + ], + "notes": [] + }, + { + "version": "2026.06.16-system-03", + "date": "2026-06-16", + "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.16-system-04", + "date": "2026-06-16", + "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量g)字段", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.05.20-system-03", + "date": "2026-05-20", + "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", + "methods": [ + "storeWarehouse.store.queryPrintQuantityLogs" + ], + "notes": [ + "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", + "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", + "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", + "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" + ], + "type": "added", + "module": "storeWarehouse" + }, + { + "version": "2026.05.13-system-01", + "date": "2026-05-13", + "summary": "完善 print.send 的 API 文档与返回说明", + "methods": [ + "print.send" + ], + "notes": [ + "补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。", + "补充 template 的子字段说明:page_width、page_height、template_content。", + "补充响应结构:flag、code、message、printId;其中成功时 code=200。", + "补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-06", + "date": "2026-05-08", + "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", + "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", + "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" + ], + "type": "added" + }, + { + "version": "2026.07.01-system-01", + "date": "2026-07-01", + "summary": "storage.directInbound.addItem 参数名修正:entry_order_code → entry_order_id,类型 string → number", + "methods": [ + "storage.directInbound.addItem" + ], + "notes": [ + "文档 params 中 entry_order_code(string)改为 entry_order_id(number),与代码 app/service/systems/inbound_direct_log.js 第 544 行实际校验保持一致", + "同步修正 app/service/systemMethods/storage/direct_inbound.js JSDoc:@param {string} data.entry_order_code → @param {number} data.entry_order_id" + ], + "type": "fixed", + "module": "storage.directInbound" + }, + { + "version": "2026.07.01-system-02", + "date": "2026-07-01", + "summary": "新增 storage.entry.queryEntryLogs 接口文档定义", + "methods": [ + "storage.entry.queryEntryLogs" + ], + "notes": [ + "代码 method 层(systemMethods/storage/entry.js L284)和 systems 层(systems/operation_log.js L318)均已实现,补充文档定义", + "参数:id(number, required)、page(number, optional, 默认1)、pageSize(number, optional, 默认20)" + ], + "type": "added", + "module": "storage.entry" + }, + { + "version": "2026.06.18-system-01", + "date": "2026-06-18", + "summary": "order.pendingOrder.downloadCreateTemplate:模板列顺序调整,店铺名称(shop_nick)从末尾移至第2列B列,紧接*订单号之后", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "调整 Excel 导入模板列顺序:店铺名称(shop_nick)从原第25列(Y列/末尾)移动至第2列(B列),紧跟在*订单号(delivery_order_code)之后。", + "同步更新 description 中的列顺序描述,明确 25 列(A-Y)的完整排列。", + "响应结构中移除冗余的 shop_nick 字段(模板列不属于 API 响应字段)。" + ], + "type": "updated", + "module": "order.pendingOrder" + }, + { + "version": "2026.05.17-system-09", + "date": "2026-05-17", + "summary": "为 storage.receiving.deleteDetail 文档补充约束:收货单已完成/已取消时禁止删除明细", + "methods": [ + "storage.receiving.deleteDetail" + ], + "notes": [ + "在 storage.receiving.deleteDetail 的 description 中补充:若关联收货单状态为 completed(已完成)或 cancelled(已取消),接口会返回删除失败(400),不允许删除明细。", + "在 errors 中补充或合并 400 描述以明确禁止删除已完成/已取消的收货单明细。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.05.17-system-08", + "date": "2026-05-17", + "summary": "完善 storage.receiving.deleteDetail 文档:补充入参/返回/错误说明,明确用户上下文来源及删除约束", + "methods": [ + "storage.receiving.deleteDetail" + ], + "notes": [ + "补充 storage.receiving.deleteDetail 的参数说明:detail_id(来自请求体,必填);说明 creator_id 与 warehouse_id 来源于当前登录用户(ctx.user.employees_id / ctx.user.store_id)。", + "补充返回结构:成功时返回 code/message/data,data 包含 details(删除后剩余明细)和 selectId(建议选中ID);product_snapshot 若存在将被解析为对象或 null。", + "补充常见错误码:404(明细不存在或无权访问),400(收货单状态/已入库/删除失败),500(服务器异常)。", + "仅文档更新,不修改任何业务实现。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.05.17-system-05", + "date": "2026-05-17", + "summary": "移除 storage.receiving.addItem(方法已下线/实现不存在)", + "methods": [ + "storage.receiving.addItem" + ], + "notes": [ + "仅同步文档:从 methods/system.json 中移除 storage.receiving.addItem,未修改任何业务代码或实现。", + "该方法已下线或实现不存在;请以当前 methods/system.json 的 SSOT 为准。" + ], + "type": "removed" + }, + { + "version": "2026.05.17-system-04", + "date": "2026-05-17", + "summary": "新增 stock.warehouse.import:仓库商品批量 JSON 导入(数组导入),SKU 为空创建/非空更新,支持 goods_code/货物编码 导入,更新写操作日志", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "支持直接传入商品数组 JSON(主方式为数组,兼容 rows/items/list/data 包装)。", + "每项仅需传商品相关字段;SKU 为空时创建新商品,SKU 非空时为更新操作。", + "更新操作会写入操作日志以便审计。", + "支持导入 goods_code(货物编码)字段别名。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "added" + }, + { + "version": "2026.05.17-system-03", + "date": "2026-05-17", + "summary": "完善 stock.warehouse.handleBatchChange 文档:补充入参/出参/错误示例", + "methods": [ + "stock.warehouse.handleBatchChange" + ], + "notes": [ + "补充方法入参说明:ids/method/value 的字段类型、是否必填、来源与示例;完善响应结构示例与常见错误码说明。", + "仅文档更新,不改业务实现或语义。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-02", + "date": "2026-05-17", + "summary": "stock.warehouse.export 由同步改为异步任务并新增进度查询 exportTaskProgress", + "methods": [ + "stock.warehouse.export", + "stock.warehouse.exportTaskProgress" + ], + "notes": [ + "stock.warehouse.export 改为异步提交导出任务:接口返回 task_id 与受理信息,后端异步生成导出文件。", + "新增 stock.warehouse.exportTaskProgress:按 task_id 查询任务状态与进度;当 status=success 时返回 download_url 供客户端下载;未找到时 status=not_found。", + "调用方式:先调用 stock.warehouse.export 获取 task_id,然后轮询 stock.warehouse.exportTaskProgress 直到 status=success 并获取 download_url。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-01", + "date": "2026-05-17", + "summary": "新增 stock.warehouse.export:仓库商品导出(支持 where/sort),返回文件下载信息", + "methods": [ + "stock.warehouse.export" + ], + "notes": [ + "新增方法:stock.warehouse.export。复用 stock.warehouse.list 的 where/sort 过滤语义(支持 operator/value/type 标准 where 结构与历史简写)。", + "响应返回导出结果(示例字段:file_key、url),表示生成的 Excel 已上传并可下载/查询。" + ], + "type": "added" + }, + { + "version": "2026.05.16-system-01", + "date": "2026-05-16", + "summary": "同步 setting.expressInterface.create 文档入参:移除未使用的 express_platform_id,标注必填字段", + "methods": [ + "setting.expressInterface.create" + ], + "notes": [ + "移除文档中 express_platform_id(服务端实现未使用);确认必填字段 name/express_code/platform_code;仓库由系统自动填充,禁止传入 warehouse_id/warehouseId。" + ], + "type": "updated" + }, + { + "version": "2026.05.12-system-01", + "date": "2026-05-12", + "summary": "调整订单打印中间态返回结构为 waveGroups(波次 -> 平台 -> 订单)", + "methods": [ + "order.print.getWavePlatformPrintData" + ], + "notes": [ + "主要变更:将方法的主返回结构改为 waveGroups,按波次分组,波次内按平台分组,平台内为订单列表(波次 -> 平台 -> 订单)。", + "兼容性:保留旧字段 platform_groups 与 order_list 作为向后兼容字段,但文档主结构与推荐使用为 waveGroups。", + "返回结构说明:summary(total_waves/total_orders/total_platforms)、wave_ids(通过过滤的波次ID数组)、waveGroups(数组,项含 wave_id、wave_no、order_count、platforms[...],platforms项含 platform、platform_name、order_count、orders[...])、ext(missing_wave_ids、filtered_wave_ids)。", + "errors:保留 400 / 500 不变。" + ], + "type": "modified" + }, + { + "version": "2026.05.11-system-05", + "date": "2026-05-11", + "summary": "order.wave.batchList:支持 express/print 分配状态筛选,入参改为英文枚举(express/print)", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "修复 where.express_assignment_status 可按快递分配状态筛选。", + "新增 where.print_assignment_status 筛选(按打印分配聚合判断)。", + "express_assignment_status / print_assignment_status 要求使用英文枚举值:express=unassigned/partially_assigned/assigned,print=unprinted/partially_printed/printed;storage_assignment_status 继续兼容中文枚举(未分配/部分分配/已分配)。", + "若传入非法枚举值,接口返回 400(参数校验失败),message 中会说明允许取值。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-04", + "date": "2026-05-11", + "summary": "调整 order.wave.waveStrategyFetchAdmin:由创建任务改为直接创建波次(不创建拣货任务)", + "methods": [ + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "接口行为变更:按策略直接抓取命中订单并创建波次,不再创建拣货任务(不返回 task_id/task_no 等任务字段)。", + "响应调整为建波结果:fetch_state(1=成功/2=失败)、wave_ids、wave_nos、created_wave_count、created_order_count、order_ids、(可选)wave_prefix、wave_prefix_source、tip/message。", + "错误调整:策略校验失败返回 400(并可能返回 validation_errors),缺少仓库上下文返回 400,建波失败返回 500 并在 message 中说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-03", + "date": "2026-05-11", + "summary": "更新 pick.query:由查询拣货明细调整为按 keyword 获取/创建拣货任务", + "methods": [ + "pick.query" + ], + "notes": [ + "入参由 waybill_code/full_display 调整为 keyword(支持运单号或波次号)。", + "接口语义调整为任务化返回:命中活动任务则返回 existing 任务ID;无活动任务则创建并返回 created 任务ID。", + "新增任务归属冲突错误:当活动任务创建人非当前用户时返回冲突提示,并附带创建人及任务ID信息。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-02", + "date": "2026-05-11", + "summary": "新增 pick.wavePickTaskCurrent:PDA 无参查询当前进行中拣货任务", + "methods": [ + "pick.wavePickTaskCurrent" + ], + "notes": [ + "新增 PDA 专用无参接口 pick.wavePickTaskCurrent。", + "按当前登录用户上下文(pick_user_id + warehouse_id)查询状态在 0/1/2 的最新任务。", + "命中返回 task_id,未命中返回 task_id=null。" + ], + "type": "added" + }, + { + "version": "2026.05.10-system-04", + "date": "2026-05-10", + "summary": "pick.wavePickTaskDetail 新增按任务类型区分的 picking_view 形态输出", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增响应字段:picking_view(object),按 task.pick_mode 区分 5 种形态输出。", + "picking_view 字段说明:mode_code, mode_name, require_box_allocations, group_by, sort_by, items[](每项含 space_id、space_name、location_space、item_code、item_name、stock_id、total_qty、box_allocations[])。", + "当 pick_mode=1/3/4 时 require_box_allocations=true;当 pick_mode=2/5 时 require_box_allocations=false。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-02", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyFetchPda/Admin 返回新增 fetch_state 三态与简短 tip", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "新增返回字段:fetch_state(number)、tip(string)、can_enter_pick_flow(boolean)", + "fetch_state 含义:1=创建成功(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可直接进入拣货流程)", + "当 fetch_state=3 时,字段 can_enter_pick_flow=true,表示前端可直接进入拣货流程;tip 为简短提示文本" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-03", + "date": "2026-05-10", + "summary": "裁剪 pick.wavePickTaskDetail 返回:移除 waves/orders,精简 task 并补充 boxes 拣货统计字段", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "移除响应中的 waves 与 orders 子表,接口仅返回精简的 task、boxes、picking_details 与 picking_summary。", + "task 子字段裁剪为:task_id, task_no, status, pick_mode, start_at, finish_at, batch_no。", + "boxes 补充并明确返回:ref_label(箱参考标签)、required_qty(箱内需拣总数)、picked_qty(已拣数量)。", + "本次变更为文档层面的返回裁剪,前端应以新字段集合为准,旧字段可能不再返回。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-01", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyList 新增 strategy_type 最小过滤(散单/团购)", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "新增 strategy_type 过滤,仅 1/2", + "支持顶层 strategy_type 和 where.strategy_type,顶层优先", + "当前不引入其他 where 字段" + ], + "type": "updated" + }, + { + "version": "2026.05.09-system-02", + "date": "2026-05-09", + "summary": "新增 pick.wavePickTaskDetail:按任务ID解析拣货任务详情", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增 pick.wavePickTaskDetail:传入 task_id 获取拣货任务完整信息,包含主表字段(task/pick_mode/status/wave_count/order_count/box_count 等)及三张子表数据(waves/orders/boxes)。", + "安全限制:接口会校验当前登录用户(operator_id/employees_id)与任务的 pick_user_id 是否一致;不一致时直接返回 403,不返回任何拣货信息。", + "鉴权配置:noNeedRight=true,noNeedAuth=true,isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-04", + "date": "2026-05-08", + "summary": "完善 order.wave.wavePickTaskList 文档:补充入参、分页与返回字段兼容说明", + "methods": [ + "order.wave.wavePickTaskList", + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "入参补充:warehouse_id(必填)、status(支持单值或数组,建议传数组)、source、keyword、page_no、page_size;保留 pagination 对象以兼容旧客户端。", + "兼容说明:接口同时支持历史 where 结构与顶层参数;当存在同名顶层参数时以顶层参数优先;pagination 支持 page/current 与 pageSize/size 别名。", + "返回格式:响应包含 total 与 list;list 每项包含字段:task_id、task_no、status、source、pick_mode、wave_count、order_count、box_count、operator_id、operator_name、start_at、finish_at、created_at。为兼容旧客户端,响应同时保留旧字段:pick_user_id、pick_user_name、start_time、finish_time、create_time。", + "入参 strategy_id 当前主表未存,接口会忽略该过滤,不建议使用。", + "默认排序:create_time desc.", + "文档变更:移除 order.wave.wavePickTaskCancel 的入参 operator_id 与 warehouse_id;入参改为仅支持 task_ids(数组,必填),不再兼容单个 task_id;操作人与仓库由请求上下文(例如当前登录用户上下文)自动获取;若上下文缺失接口将返回错误。响应补充批量结果字段:cancelled_count、task_ids、task_nos(若后端返回)。仅更新文档,未修改业务实现。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-03", + "date": "2026-05-08", + "summary": "升级按策略抓取接口为创建任务主流程:order.wave.waveStrategyFetchPda / order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "将 PDA/Admin 场景的按策略抓取接口由受理壳方法升级为 '创建任务主流程':接口会执行参数校验并在同步响应中创建任务记录(state=created),返回 task_id、task_no、plan 与 plan_summary 供前端展示与后续查询。", + "入参新增/扩展与创建流程相关字段:至少包含 cart_id(关联拣货车/作业车ID)、source(操作来源语义)并保留并透传 strategy_id 与 strategy_params(策略参数),以支持在创建阶段对策略进行局部覆盖或透传。", + "成功返回示例字段:state=created、task_id、task_no、plan(对象)和 plan_summary(字符串);失败场景会返回 validation_errors(数组,每项含 field/message)或 message 描述创建失败原因。", + "边界说明:当前为最小主流程(创建与计划预览),后续扫描/任务执行阶段(如实际抓取订单、写入 wave 等)将在后续版本中追加与完善。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-02", + "date": "2026-05-08", + "summary": "调整按策略抓取壳方法:order.wave.waveStrategyFetch 更名为 order.wave.waveStrategyFetchPda,并新增 order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetch", + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "waveStrategyFetchPda 仅用于 PDA 场景", + "waveStrategyFetchAdmin 仅用于后台管理场景", + "两者当前均为壳子受理方法,不执行真实抓取" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-01", + "date": "2026-05-08", + "summary": "新增 order.wave.waveStrategyFetch:按策略提交抓取任务(壳子方法)", + "methods": [ + "order.wave.waveStrategyFetch" + ], + "notes": [ + "当前方法为壳子方法:仅受理并返回任务受理信息,不执行真实抓取逻辑,后续补齐执行链路。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-05", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyCreate 与 order.wave.waveStrategyUpdate:波次策略创建与更新接口(含参数校验与版本推进)", + "methods": [ + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate" + ], + "notes": [ + "仓库 ID 与创建人(creator_name)由当前登录仓库/操作者上下文获取,接口不接受外部覆盖。", + "入参 allowed_owners 与 allowed_expresses 会校验是否在系统可用范围内(基于仓库签约货主或系统快递列表),若存在非法值接口会直接报错(400)。", + "max_same_structure 受仓库配置 min_group_order_fetch_quantity 限制:若传入值 >= min_group_order_fetch_quantity,则自动下调为 min_group_order_fetch_quantity - 1(最小值为 1)。", + "新建/更新成功后会触发仓库的 wave_strategy_version 自增(+1)并失效相关仓库配置缓存,调用方可通过策略版本推进或缓存变化感知策略已生效。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-06", + "date": "2026-05-07", + "summary": "收敛 order.wave.waveStrategyFallbackOrderList 返回字段,限定 where 白名单,补充 order.wave.singleFetchByIds 别名与返回语义", + "methods": [ + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleFetchByIds" + ], + "notes": [ + "收敛 order.wave.waveStrategyFallbackOrderList response.list 字段为 id, delivery_no, tracking_no, items_count, items_total, sys_logistics_name, store_name, province, sys_platform_name, item_snapshot;item_snapshot 格式示例:商品名称*数量|...。", + "限制 order.wave.waveStrategyFallbackOrderList.where 白名单,禁止传入 warehouse_id / warehouseId;传入未列出字段或别名冲突将返回 400。", + "补充 order.wave.singleFetchByIds:明确支持 ids / order_ids / orderIds 三个别名(优先顺序 ids -> order_ids -> orderIds)并说明返回字段 fetched_order_ids、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids 的语义与兼容性。" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-04", + "date": "2026-05-07", + "summary": "更新 order.wave.waveStrategyFallbackOrderList,新增商品快照字段 item_snapshot", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "item_snapshot 返回格式为 商品名称1*数量|商品名称2*数量" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-03", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyQuickScan 与进度查询接口", + "methods": [ + "order.wave.waveStrategyQuickScan", + "order.wave.waveStrategyQuickScanTaskProgress" + ], + "notes": [ + "同仓只允许一个扫描任务并使用缓存锁;扫描范围为当前表非待审核、未分配波次且订单策略版本与仓库当前版本不一致的订单;命中策略标记 wave_scan_result=1,否则=2" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-02", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyList:查询当前仓库波次策略列表", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "从 wms_wave_strategy 拉取当前仓库的波次策略列表,分页返回" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-01", + "date": "2026-05-07", + "summary": "移除 order.wave.singleOrderFetchDetailList,新增 order.wave.waveStrategyFallbackOrderList(内置固定筛选条件)", + "methods": [ + "order.wave.singleOrderFetchDetailList", + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "移除 order.wave.singleOrderFetchDetailList。", + "新增 order.wave.waveStrategyFallbackOrderList。", + "新接口基于订单通用查询口径,固定内置筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-06", + "date": "2026-05-06", + "summary": "新增 order.wave.singleOrderFetchDetailList:订单级散单候选明细视图", + "methods": [ + "order.wave.singleOrderFetchDetailList" + ], + "notes": [ + "新增 order.wave.singleOrderFetchDetailList:提供订单级的散单候选明细列表,返回按订单聚合的明细(非分组级)。", + "返回订单级而非分组级;响应每项包含订单 id、group_count、item_detail_machine、item_detail_machine_snapshot、item_detail、item_snapshot、logistics_name、store_id、distinguish_express、create_at 与 status_summary 等关键字段。", + "仍沿用 same_order_quantity 阈值来排除团购命中分组(仅保留 group_count < same_order_quantity 的候选项)。", + "singleOrderFetchList 暂保留以兼容现有前端,前端可在切换到订单级视图后迁移到本接口。" + ], + "type": "added" + }, + { + "version": "2026.05.06-system-05", + "date": "2026-05-06", + "summary": "storage.receiving.get 返回扩展:data.details[*] 新增 box_remainder、box_weight", + "methods": [ + "storage.receiving.get" + ], + "notes": [ + "storage.receiving.get 的响应在 data.details[*] 中新增可选字段:box_remainder(箱内剩余数量/零散数量,number,默认 0)与 box_weight(实测箱重,number,默认 0)。", + "兼容性:新增字段为可选,旧客户端无需修改;建议前端在需要展示箱内余量/箱重时使用这些字段。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-04", + "date": "2026-05-06", + "summary": "storage.receiving.getReceivingDetail 返回扩展:明细增加 box_remainder、box_weight;storage.receiving.completeReceiving 通知包含这两个字段", + "methods": [ + "storage.receiving.getReceivingDetail", + "storage.receiving.completeReceiving" + ], + "notes": [ + "为支持箱规统计与通知回传,getReceivingDetail 的明细项(receiving.details 或 data.details)在响应中新增可选字段:box_remainder(箱内剩余数量/零散数量,number)与 box_weight(实测箱重,number,单位同系统重量)。", + "completeReceiving 在完成收货后会发送通知(或回调),通知 payload/metadata 中将包含每条明细的 box_remainder 与 box_weight 字段,供下游系统/前端展示或审计使用。", + "兼容性:新增字段为可选,旧客户端在未使用这些字段时无需变更。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-03", + "date": "2026-05-06", + "summary": "storage.receiving.detailChange:新增入参/出参字段 box_remainder、box_weight", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "为支持箱规细化与回写,detailChange 新增可选入参 box_remainder(箱内余量/零散数量)和 box_weight(实测箱重,单位同系统重量),写入后会回写至明细并在响应 data 中返回对应字段。", + "兼容性:新增字段为可选,不传入则不影响现有调用;建议前端在需要回写箱余与箱重时一并传入。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-02", + "date": "2026-05-06", + "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", + "methods": [ + "order.wave.singleFetchByIds" + ], + "notes": [ + "新增 order.wave.singleFetchByIds:按入参 ids(兼容 order_ids/orderIds)去重后筛选当前仓库内待处理且不在波次中的订单,若存在可抓取订单则创建单个散单波次并把这些订单写入该波次(不区分快递);成功后批量写入订单操作日志;若无可抓取订单返回 wave_id=0。", + "接口行为严格对齐实现:过滤条件包含 step in [1,2,3]、status != 'cancel'、outbound_status != 'padding';已在波次的订单会被排除并返回 excluded_existing_wave_order_ids;响应包含 ids、wave_id、wave_no、fetched_order_ids、fetched_order_count、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids。" + ], + "type": "added" + }, + { + "version": "2026.05.06-system-01", + "date": "2026-05-06", + "summary": "新增 order.wave.groupFetch 与 order.wave.singleFetch;order.wave.fetch 保留兼容别名;抓取进度补充上限字段", + "methods": [ + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.fetch", + "order.wave.fetchTaskProgress" + ], + "notes": [ + "新增 order.wave.groupFetch:抓取团购接口(异步任务提交),参数 structure_list 与原 fetch 一致。", + "新增 order.wave.singleFetch:抓取散单接口(异步任务提交),在 structure_list 每项新增必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数)。", + "order.wave.fetch 保留为兼容别名(等同 groupFetch),避免误导客户端。", + "groupFetch/singleFetch/fetch 的响应新增可选字段 fetch_mode;singleFetch 响应额外返回 max_fetch_quantity。", + "order.wave.fetchTaskProgress 的响应增加单模式相关字段:fetch_mode、max_fetch_quantity、limit_reached、stop_reason,用于描述散单抓取的上限与停止原因。" + ], + "type": "updated" + }, + { + "version": "2026.05.05-system-02", + "date": "2026-05-05", + "summary": "order.wave.batchList:新增 where.storage_assignment_status 的过滤语义说明", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where 字段 `storage_assignment_status`:类型 string,可选值:`未分配`、`部分分配`、`已分配`;默认不传:不做分配状态限制。", + "过滤语义:`已分配`:聚合后全部 fin;`部分分配`:不含 error,且既不是全 none,也不是全 fin;`未分配`:全 none 或包含 error(异常并入未分配筛选集合)。", + "说明:返回字段 `storage_assignment_status` 的展示值保持不变;包含 error 时仍可能展示“分配异常”,但 where 的过滤语义把异常算到“未分配”集合,避免把过滤语义与展示值混淆。" + ], + "type": "updated" + }, + { + "version": "2026.05.05-system-01", + "date": "2026-05-05", + "summary": "新增 order.wave.singleOrderFetchList:散单候选分组查询(排除团购命中分组)", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "新增 order.wave.singleOrderFetchList:返回按机器结构分组的散单候选列表,接口会排除已达团购阈值(同组订单数量 >= same_order_quantity 或仓库配置 min_group_order_fetch_quantity)的分组,仅返回同组订单数量 < 阈值 的分组(散单候选)。", + "与 order.wave.groupOrderFetchList 的关键差异:groupOrderFetchList 返回满足团购阈值(>=)的分组;singleOrderFetchList 返回未达阈值(<)的散单候选分组。", + "影响范围:订单波次抓取相关前端/调度服务。兼容性:不影响或修改现有 order.wave.groupOrderFetchList,两个接口可并行使用。" + ], + "type": "added" + }, + { + "version": "2026.05.04-system-04", + "date": "2026-05-04", + "summary": "完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述", + "methods": [ + "stock.warehouse.checkItemCodeUnique" + ], + "notes": [ + "完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述" + ], + "type": "modified" + }, + { + "version": "2026.05.04-system-02", + "date": "2026-05-04", + "summary": "修改 pick.query 入参:order_id -> waybill_code", + "methods": [ + "pick.query" + ], + "notes": [ + "入参从 order_id 改为 waybill_code(快递号),通过快递号查找订单后再查波次拣货信息" + ], + "type": "breaking_change" + }, + { + "version": "2026.05.04-system-01", + "date": "2026-05-04", + "summary": "新增 system method pick.query:按订单查询波次拣货信息", + "methods": [ + "pick.query" + ], + "notes": [ + "按订单查询该订单所属波次的拣货信息,支持 full/full_display/is_full 控制是否完整显示;接口按当前登录用户仓库上下文过滤,防止跨仓越界。" + ], + "type": "added" + }, + { + "version": "2026.05.03-system-09", + "date": "2026-05-03", + "summary": "新增按 request_id 查询分配状态/结果接口", + "methods": [ + "order.pendingOrder.allocateStorageProgress" + ], + "notes": [ + "新增按 request_id 查询储位分配异步任务状态/结果接口,支持 status:submitted/running/success/failed/not_found;success 返回 result(底层分配结果),failed 返回 error(错误信息);兼容 requestId 参数名。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-07", + "date": "2026-05-03", + "summary": "新增抓取进度查询接口", + "methods": [ + "order.wave.fetch", + "order.wave.fetchTaskProgress" + ], + "notes": [ + "新增按 task_id 查询抓取任务进度的接口 order.wave.fetchTaskProgress,支持返回 status(submitted/running/success/failed/not_found)及进度相关字段:progress_percent、finished_structure_count、total_fetched_quantity、duration_ms、error、update_time 等;同时明确 order.wave.fetch 为异步任务提交接口,客户端可通过 task_id 调用 order.wave.fetchTaskProgress 查询进度和最终结果。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-05", + "date": "2026-05-03", + "summary": "补齐仓库设置模块 setting.warehouse 的 methods 文档", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings" + ], + "notes": [ + "补齐仓库配置 methods API 文档" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-04", + "date": "2026-05-03", + "summary": "order.wave:自动加团新增跳过规则并新增批量结束自动加团接口", + "methods": [ + "order.wave.batchAutoGrouping", + "order.wave.batchFinishAutoGrouping" + ], + "notes": [ + "开启自动加团新增“已打印/超最大波次容量”跳过规则并在响应中返回跳过明细;新增批量结束自动加团接口(将 wave_status=0 的波次批量置为 1)" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-03", + "date": "2026-05-03", + "summary": "裁剪 order_list 以轻量化返回", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "移除响应中的 order_list 字段,接口仅返回波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-02", + "date": "2026-05-03", + "summary": "新增 order.wave.batchAutoGrouping:批量改为自动加团中", + "methods": [ + "order.wave.batchAutoGrouping" + ], + "notes": [ + "新增批量改为自动加团中接口及返回字段" + ], + "type": "updated" + }, + { + "version": "2026.04.22-system-02", + "date": "2026-04-22", + "summary": "新增 order.pendingOrder.syncOrderIds:待处理订单同步透传入口", + "methods": [ + "order.pendingOrder.syncOrderIds" + ], + "notes": [ + "新增 order.pendingOrder.syncOrderIds:仅接收 order_ids 并转发到服务层,当前不做业务处理。", + "接口保留登录态校验,入参仅接受订单 ID 相关字段,响应以服务层返回值为准。", + "该方法用于预留同步链路,后续补齐业务逻辑时再扩展服务层实现。" + ], + "type": "updated" + }, + { + "version": "2026.04.22-system-01", + "date": "2026-04-22", + "summary": "补全订单工作台各模块 detail 方法文档", + "methods": [ + "order.detail", + "order.pendingOrder.detail", + "order.reviewOrder.detail", + "order.expectionOrder.detail", + "order.outboundOrder.detail", + "order.deliveryOrder.detail", + "order.deliveryExpectionOrder.detail", + "order.entrustOrder.detail", + "order.archiveOrder.detail" + ], + "notes": [ + "补全文档:detail 为订单工作台通用详情方法,入参支持 ids/id/order_id/orderId;可选 tableType/tablePosition/type/moduleName,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等。", + "返回包含 order/detail(订单头)、orderItems/items(商品明细)、expresses(运单信息)、waybill_codes(去重运单号数组)。" + ], + "type": "updated" + }, + { + "version": "2026.04.19-system-01", + "date": "2026-04-19", + "summary": "新增方法 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 查询全字段列表并支持缓存", + "methods": [ + "setting.expressInterface.listByWarehousePlatformCode" + ], + "notes": [ + "新增 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 返回快递接口的全字段数组(不分页),每条记录包含 express 关联对象(id/code/name/platform 等)。", + "支持缓存,缓存键由 warehouse_id + platform_code 组成;缓存命中将直接返回缓存结果以提升查询性能。", + "在创建/更新/删除操作(setting.expressInterface.create/update/delete)后,会主动清理对应 warehouse_id + platform_code 的缓存以确保数据一致性。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-08", + "date": "2026-04-17", + "summary": "新增快递编码管理模块批量软删除接口 setting.express.delete", + "methods": [ + "setting.express.delete" + ], + "notes": [ + "新增批量软删除接口 setting.express.delete:接受 ids(数组、逗号字符串或单值),对属于当前仓库且未被删除的记录执行软删除(设置 deleted_at),并清理 express 列表缓存。", + "当任一目标记录的 code 被 wms_express_interface.express_code 引用时,接口会拒绝删除并返回 409,错误信息中包含被引用的编码列表。", + "响应包含 ids、deleted_ids、already_deleted_ids 与 status,已删除与未删除的 id 会明确分类。仅记录已实现行为。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-05", + "date": "2026-04-17", + "summary": "新增文档分组:平台编码管理模块(收口 index.getPlatformList 与 setting.platform.*)", + "methods": [ + "index.getPlatformList", + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立文档分组 '平台编码管理模块',将平台基础列表(index.getPlatformList)与平台设置管理接口(setting.platform.*)归并为单一分组以便维护;仅文档变更,不修改实现。", + "文档中仅包含已实现的方法与字段,未新增或推断不存在的参数/返回字段。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-04", + "date": "2026-04-17", + "summary": "新增独立平台设置模块 setting.platform(wms_platfrom_setting)及其 CRUD 接口:list/create/update/delete。", + "methods": [ + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立模块 setting.platform,映射数据表 wms_platfrom_setting;list 支持 where(id/code/name/platform_code/quickWhere)与 pagination(兼容 page/pageSize/page_size);create/update 要求 platform_code 必须存在于系统平台表(wms_platform),且禁止越权写入 warehouse_id;delete 需传入 id 并校验当前仓库范围。" + ], + "type": "added" + }, + { + "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", + "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要 登录并走权限校验。", + "methods": [ + "warehouse.getAreaRacks" + ], + "notes": [ + "对齐当前 system 文档中的 isNeedAuth=true、isNeedLogin=true。", + "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" + ] + }, + { + "version": "2026.04.07-system-02", + "date": "2026-04-07", + "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields", + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", + "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并 明确 id、change_quantity、reason 等关键入参。" + ] + }, + { + "version": "2026.04.07-system-03", + "date": "2026-04-07", + "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", + "methods": [ + "storeWarehouse.store.listApiConfig", + "storeWarehouse.store.saveApiConfig", + "storeWarehouse.store.deleteQimenConfig" + ], + "notes": [ + "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", + "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", + "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" + ] + }, + { + "version": "2026.04.07-system-04", + "date": "2026-04-07", + "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", + "methods": [ + "/api/docs", + "/api/docs/:docName", + "/api/docs/:docName/raw", + "/api/docs/:docName/changes" + ], + "notes": [ + "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", + "原文 JSON 入口继续用于直接查看当前生效文档。" + ] + }, + { + "version": "2026.04.07-system-05", + "date": "2026-04-07", + "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", + "methods": [ + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", + "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" + ] + }, + { + "version": "2026.04.07-system-06", + "date": "2026-04-07", + "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-07", + "date": "2026-04-07", + "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", + "methods": [ + "index.listInterfaceTypes" + ], + "notes": [ + "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" + ], + "type": "added" + }, + { + "version": "2026.04.07-system-08", + "date": "2026-04-07", + "summary": "app_name 改为必传参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返 回 400 错误。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-09", + "date": "2026-04-07", + "summary": "新增收货单快捷入库上架接口", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单 (SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-01", + "date": "2026-04-08", + "summary": "新增收货单与入库单匹配入库接口", + "methods": [ + "storage.inventory.matchPutaway" + ], + "notes": [ + "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完 成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-02", + "date": "2026-04-08", + "summary": "saveApiConfig 新增 callback_url 可选参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的 回调地址配置。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-03", + "date": "2026-04-08", + "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", + "methods": [ + "storeWarehouse.store.list", + "storeWarehouse.store.listApiConfig" + ], + "notes": [ + "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-04", + "date": "2026-04-08", + "summary": "新增库存移库(库位转移)接口", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库, 包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件, 每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-05", + "date": "2026-04-08", + "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-06", + "date": "2026-04-08", + "summary": "新增商品库存明细查询接口", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数 量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-07", + "date": "2026-04-08", + "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-08", + "date": "2026-04-08", + "summary": "新增按商品维度移库接口", + "methods": [ + "storage.inventory.transferByProduct" + ], + "notes": [ + "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记 录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-09", + "date": "2026-04-08", + "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-10", + "date": "2026-04-08", + "summary": "货主列表返回新增 has_qimen_config 布尔字段", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-11", + "date": "2026-04-08", + "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜 索失败场景。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-12", + "date": "2026-04-08", + "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分 组或按批次逐条)", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐 条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-13", + "date": "2026-04-08", + "summary": "新增 wms_stock_transaction 表和模型", + "methods": [ + "wms_stock_transaction" + ], + "notes": [ + "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-14", + "date": "2026-04-08", + "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", + "methods": [ + "storage.inventory.quickPutaway", + "storage.inventory.matchPutaway" + ], + "notes": [ + "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均 自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-15", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 出入库记录列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、 分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品 聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-16", + "date": "2026-04-08", + "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", + "methods": [ + "storage.transaction.list" + ], + "notes": [ + "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "rename", + "module": "storage" + }, + { + "version": "2026.04.08-system-17", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 库存列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商 品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-18", + "date": "2026-04-08", + "summary": "移除 storage.entry.create 创建入库单接口", + "methods": [ + "storage.entry.create" + ], + "notes": [ + "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 对外暴露。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-19", + "date": "2026-04-08", + "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外 接口", + "methods": [ + "storage.entry.addDetail", + "storage.entry.deleteDetail", + "storage.entry.detailChange" + ], + "notes": [ + "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-20", + "date": "2026-04-08", + "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", + "methods": [ + "storage.stockout.list", + "storage.stockout.toOrder", + "storage.stockout.listItems" + ], + "notes": [ + "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层 部分能力仍复用 order 模块。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-21", + "date": "2026-04-08", + "summary": "将 storage.stockout.toOrder 标记为占位接口", + "methods": [ + "storage.stockout.toOrder" + ], + "notes": [ + "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" + ], + "type": "change" + }, + { + "version": "2026.04.09-system-01", + "date": "2026-04-09", + "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", + "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", + "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一 单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", + "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", + "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" + ] + }, + { + "version": "2026.04.09-system-02", + "date": "2026-04-09", + "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", + "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", + "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未 配置)", + "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露 。" + ], + "type": "added" + }, + { + "version": "2026.04.09-system-03", + "date": "2026-04-09", + "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", + "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存 在。", + "文档中未包含任何云密钥或敏感配置信息。" + ], + "type": "changed" + }, + { + "version": "2026.04.10-system-01", + "date": "2026-04-10", + "summary": "订单审核字段由 audit_status 替换为整数字段 step,并添加数据库迁移", + "methods": [ + "order.getreviewOrderlist", + "order.reviewOrder.getreviewOrderlist", + "order.reviewOrder.reviewOrder", + "order.deliveryOrder.getdeliveryOrderlist", + "order.list", + "order.stats" + ], + "notes": [ + "字段变更:order 相关审核字段从字符串/枚举 audit_status 替换为整数 step。", + "step 映射:0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭。", + "reviewOrder 接口在更新 inspection_status 的同时会写入 step 字段。", + "必须执行迁移脚本:20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js" + ], + "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" + }, + { + "version": "2026.04.16-system-01", + "date": "2026-04-16", + "summary": "基础模块新增快递产品类型查询接口", + "methods": [ + "index.getExpressProductTypeList" + ], + "notes": [ + "新增 index.getExpressProductTypeList,归属基础模块(module=index),用于查询指定快递公司的产品类型列表。", + "对应服务实现:app/service/systems/express.js 中的 getExpressProductTypeList,支持传入 express_code 作为可选筛选参数(source=body)。", + "接口设置为免鉴权(isNeedAuth=false)但需登录(isNeedLogin=true),与 index.getExpressList / index.getPlatformList 一致,优先从缓存读取。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-01", + "date": "2026-04-17", + "summary": "新增快递管理模块(setting.express)及 5 个接口文档", + "methods": [ + "setting.express.list", + "setting.express.listBase", + "setting.express.create", + "setting.express.checkCodeUnique", + "setting.express.update" + ], + "notes": [ + "新增独立模块组:快递管理模块(module=setting.express),将快递映射管理相关接口独立为一组以便维护。", + "接口实现参考:app/service/systems/setting/express.js(返回结构)与 app/service/systemMethods/setting/express.js(对外方法包装)。", + "接口鉴权与上下文:isNeedAuth=false, isNeedLogin=true;需在请求中传入 Authorization 以携带登录上下文(用于获取当前仓库/货主上下文)。", + "已同步更新 methods/system.json,补充 params/response/errors,保持文档与实现一致。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-02", + "date": "2026-04-17", + "summary": "setting.express.list 分页入参统一为 pagination", + "methods": [ + "setting.express.list" + ], + "notes": [ + "将 setting.express.list 的分页入参文档从顶层 page/page_size/pageSize 迁移为 pagination 对象,主形态为 pagination;兼容 snake_case 的 page_size 与 camelCase 的 pageSize。", + "文档与当前实现一致:顶层 page/page_size/pageSize 会被归一化到 data.pagination 并转发到系统服务。" + ], + "type": "updated" + }, + { + "version": "2026.04.17-system-03", + "date": "2026-04-17", + "summary": "新增快递接口管理模块(setting.expressInterface)及 4 个接口文档", + "methods": [ + "setting.expressInterface.list", + "setting.expressInterface.create", + "setting.expressInterface.update", + "setting.expressInterface.delete" + ], + "notes": [ + "新增独立模块组:快递接口管理模块(module=setting.expressInterface),对应实现:app/service/systems/setting/expressInterface.js 与对外包装 app/service/systemMethods/setting/expressInterface.js。", + "接口为当前仓库范围(基于 ctx.user.store_id),仓库边界由系统服务强制校验;禁止通过接口指定 warehouse_id/warehouseId。操作需登录(isNeedLogin=true),无需额外鉴权(isNeedAuth=false)。", + "已在 methods/system.json 新增对应接口的 params/response/errors 文档,保持与实现一致。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-01", + "date": "2026-04-18", + "summary": "补充订单储位分配接口文档:order.storageAllocation.allocateStorage", + "methods": [ + "order.storageAllocation.allocateStorage" + ], + "notes": [ + "新增 order.storageAllocation.allocateStorage:按订单批量分配储位,支持多种入参别名(order_ids/ids/orderId 等)与仓库上下文优先级。", + "响应包含 requested_order_ids, pending_order_ids, allocated_order_ids, shortage_order_ids, skipped_orders, picking_count, stock_lock_summary, storage_lock_summary 等字段,用于前端展示分配结果与不足提示。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-02", + "date": "2026-04-18", + "summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配首单快递号(异步接口),复用 express.createWaybillCodePipeline。", + "methods": [ + "order.pendingOrder.allocateExpressCode" + ], + "notes": [ + "异步接口:调用后立即返回 task_id,后台执行运单创建,通过 allocateExpressCodeTaskProgress 查询进度。", + "入参为 ids(订单 ID 数组),sys_platform_code/logistics_code 等由后端从数据库读取。", + "拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-03", + "date": "2026-04-18", + "summary": "将 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,并移除原有公开分组。", + "methods": [ + "order.pendingOrder.allocateStorage" + ], + "notes": [ + "将对外入口从 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,旧的 order.storageAllocation 分组已从 methods/system.json 中移除。", + "新的对外接口不接受 warehouse_id / warehouseId,仓库上下文由当前登录用户(ctx.user.store_id)提供。", + "本次变更仅同步文档位置与对外方法名,底层实现保留且通过新的 system 方法暴露。" + ], + "type": "changed" + }, + { + "version": "2026.04.19-system-02", + "date": "2026-04-19", + "summary": "新增待处理模块取消分配储位接口 order.pendingOrder.cancelAllocateStorage", + "methods": [ + "order.pendingOrder.cancelAllocateStorage" + ], + "notes": [ + "新增待处理模块取消分配储位接口 `order.pendingOrder.cancelAllocateStorage`,直接对接 `service.systems.orderStorageAllocation.cancelAllocateStorage` 实现。", + "接口现在仅接受订单ID(order_ids),不再接受 allow_storage_location;禁止传入 `warehouse_id/warehouseId`,仓库上下文由当前登录用户的 `store_id` 提供。", + "响应返回标准 { flag, code, message, data } 结构,data 包含取消分配的汇总结果(warehouse_id, requested_order_ids, cancellable_order_ids, skipped_orders, orders, picking_count, storage_unlock_summary, stock_unlock_summary)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-01", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.updateOrderPlatform 方法:批量修改待处理订单平台信息", + "methods": [ + "order.pendingOrder.updateOrderPlatform" + ], + "notes": [ + "通过 code 查找 wms_platform,平台不存在时返回 404 错误。", + "仅操作当前仓库的当前订单表。", + "noNeedRight=true,noNeedAuth=true(isNeedAuth: true 在 spec 中对应权限配置 noNeedAuth=true)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-02", + "date": "2026-04-21", + "summary": "新增方法 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息", + "methods": [ + "order.pendingOrder.updateOrderExpress" + ], + "notes": [ + "新增 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息,按 express_code 从仓库快递列表(带缓存)匹配快递项。", + "自定义映射(is_system_setting=true)时,sys_logistics_code/name 写入系统快递编码和名称,logistics_code/name 写入自定义编码和名称;系统快递(is_system_setting=false)时四个字段均写系统快递的 code/name。", + "只操作当前仓库的当前订单表,不处理其他订单表;操作后写入操作日志(ORDER_UPDATE_EXPRESS)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-03", + "date": "2026-04-21", + "summary": "新增 order.expectionOrder.resolveException:将待处理异常订单转回正常待处理状态", + "methods": [ + "order.expectionOrder.resolveException" + ], + "notes": [ + "新增 order.expectionOrder.resolveException:批量将 step=3 的异常订单恢复为 step=2 正常待处理状态。", + "入参 ids 为订单ID 正整数数组,不能为空;仅操作当前仓库当前订单表。", + "返回 updated_count(实际更新行数)与 ids(本次操作ID列表)。", + "权限配置:noNeedLogin=false、noNeedRight=true、noNeedLog=false、noNeedAuth=true" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-04", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.cloneOrder 方法:克隆待处理订单", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "支持对 step 0/1/2/3 的待处理订单进行克隆操作。", + "若原订单已分配储位(storage_status=fin),克隆前自动清除已分配库存。", + "原订单取消后(step→9, status→cancel),以原订单业务数据创建新订单,流程状态字段全部重置为初始落库状态。", + "克隆订单明细含 stock_id,新订单 ID 重新绑定。", + "noNeedAuth=true,noNeedRight=true,noNeedLogin=false。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-06", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.createOrder:手动创建待处理/待审核订单", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "新增 order.pendingOrder.createOrder:手动创建订单,step 由货主策略 need_order_approval 决定(1→待审核 step=0,0→待处理 step=1)。", + "必填字段:store_id、name、mobile/tel 至少一项、detail_address、items[](含 item_code 和 plan_qty)。", + "delivery_order_code 不传则自动生成(SYS+时间戳+随机4位);logistics_code/sys_platform_code 不传则读货主合约策略 default_express_code/default_platform_code。", + "不做库存锁定,储位分配为独立步骤。操作日志写入 ORDER_CREATE。", + "noNeedRight=true,noNeedAuth=true,noNeedLogin=false。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-07", + "date": "2026-04-21", + "summary": "新增 Excel 模板下载与批量导入创建订单接口:order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", + "methods": [ + "order.pendingOrder.downloadCreateTemplate", + "order.pendingOrder.importOrdersFromExcel" + ], + "notes": [ + "新增 order.pendingOrder.downloadCreateTemplate:生成 Excel 导入模板,返回 base64 编码的 xlsx 文件,表头中带 * 的列为必填项(橙色背景),可选列为灰色背景,含示例数据行和填写说明工作表。", + "新增 order.pendingOrder.importOrdersFromExcel:接受 base64 编码的 xlsx 文件,按订单号分组,每组调用 createOrder 逻辑创建订单;不中断执行,逐条记录成功/失败结果返回。", + "多行相同订单号的行组成一个完整订单,每行代表一条商品明细;订单头信息(收件人、地址等)取每组第一行。", + "step 由货主策略 need_order_approval 决定(与 createOrder 一致);通过事务保证每个订单的主记录与明细原子写入。" + ], + "type": "added" + }, + { + "version": "2026.05.01-system-01", + "date": "2026-05-01", + "summary": "新增基础模块 IM 登录码接口文档:index.loginToIm", + "methods": [ + "index.loginToIm" + ], + "notes": [ + "新增 index.loginToIm 文档,入参为空对象({}),依赖当前登录用户上下文生成一次性 code。", + "响应增加 data.code 字段,长度固定 64 位(hex),默认有效期 5 分钟。", + "错误码补充:401(用户未登录)、400(用户信息不完整,缺 employees_id 或 employees_name)。", + "该接口仅做登录码签发,实际换取员工信息由 IM 侧 ssoCodeToId 完成并在成功后使 code 失效。" + ], + "type": "added" + }, + { + "version": "2026.05.01-system-03", + "date": "2026-05-01", + "summary": "扩展 index.loginToIm 返回字段:增加主体/主体类型/头像信息", + "methods": [ + "index.loginToIm" + ], + "notes": [ + "登录码签发接口响应新增 employees_id、employees_name、subject、store_type、avatar 字段。", + "subject 包含 id/name;store_type 严格取自 wms_store.project 字段,不再返回 subject_type 兼容字段。", + "同一批字段会写入 code 缓存,供 IM 侧 ssoCodeToId 换取并在成功后失效。" + ], + "type": "updated" + }, + { + "version": "2026.05.01-system-04", + "date": "2026-05-01", + "summary": "index.loginToIm 与 ssoCodeToId 改为严格字段模式,不再做兼容回退", + "methods": [ + "index.loginToIm" + ], + "notes": [ + "loginToIm 仅读取 ctx.user 标准字段:employees_id、employees_name、store_id、store_name、store_type、avatar。", + "不再兼容 id/real_name/username/company_name/avatar_url 等历史字段。", + "ssoCodeToId 返回值不再使用默认兜底,缺少关键字段时按 code 无效处理。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-01", + "date": "2026-05-03", + "summary": "将 order.wave.fetch 调整为异步任务提交接口,删除同步返回抓取结果字段", + "methods": [ + "order.wave.fetch" + ], + "notes": [ + "接口从同步返回抓取结果改为提交任务并异步处理。", + "移除原方法中 result_list / total_request_quantity / total_fetched_quantity 等同步返回字段。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-06", + "date": "2026-05-03", + "summary": "order.wave.batchList:新增 where 支持并限制传入字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "batchList 新增 where 支持及白名单过滤;禁止传入 warehouse_id/warehouseId。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-08", + "date": "2026-05-03", + "summary": "order.pendingOrder.allocateStorage 改为异步提交", + "methods": [ + "order.pendingOrder.allocateStorage" + ], + "notes": [ + "接口变更为异步提交:调用后立即返回 request_id,后端异步执行储位分配;接口不再在响应中同步返回分配明细(如 requested_order_ids、allocated_order_ids 等)。客户端可后续通过任务 ID / 查询链路或事件获取最终分配结果。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-10", + "date": "2026-05-03", + "summary": "新增订单批量移出波次接口", + "methods": [ + "order.wave.batchRemoveOrders" + ], + "notes": [ + "按订单ID批量移出波次;仅处理待处理订单表中非待审核订单(step in [1,2,3])。", + "操作在单事务内完成:清空订单的 wave_id/wave_no,并回写 wms_wave_batch 统计(重算 total_orders;当波次被清空时将 wave_status 置为 -1)。", + "仓库上下文来自当前登录用户(ctx.user.store_id)。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + }, + { + "version": "2026.05.09-system-01", + "date": "2026-05-09", + "summary": "新增 order.wave.wavePickTaskCancelSelf;order.wave.waveStrategyList 新增预演计数字段/参数", + "methods": [ + "order.wave.wavePickTaskCancelSelf", + "order.wave.waveStrategyList" + ], + "notes": [ + "新增接口 `order.wave.wavePickTaskCancelSelf`:仅支持单个 `task_id`(number,必填),明确不支持 `task_ids` 批量参数。", + "业务约束:仅允许取消当前登录用户本人创建的拣货任务;若尝试取消非本人创建任务,接口应返回 400 错误(仅允许取消本人创建任务)。", + "返回建议:与现有取消接口风格一致,包含 `cancelled_count`(0/1)、`task_id`、`task_no`(若后端返回)或相应的取消结果汇总。", + "错误码建议:400 参数不合法(task_id 缺失或传了 task_ids);400 仅允许取消本人创建任务;500 取消失败。", + "新增参数:calculate_next_fetch_order_count(number,可选),含别名 calculateNextFetchOrderCount;取值 0=不计算(默认),1=计算并返回每条策略的 next_fetch_order_count,用于前端在策略列表中预览抓取量。", + "新增响应字段:list[*].next_fetch_order_count(number),含义:按当前策略口径预演一次自动抓取时,预计会选中的订单数量;当未开启计算时返回 0。" + ], + "type": "added" + }, + { + "version": "2026.05.11-system-01", + "date": "2026-05-11", + "summary": "新增字段 wave_prefix(策略层波次前缀),并补充 PDA 抓取波次号生成行为说明", + "methods": [ + "order.wave.waveStrategyList", + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyFetchPda" + ], + "notes": [ + "在 wave strategy 对象中新增可选字段 wave_prefix:策略波次前缀,优先于仓库前缀。", + "校验规则:长度 1-5,仅允许 A-Z0-9;保存时会转为大写;为空时回退仓库前缀:团购使用 group_wave_prefix,散单使用 delete_order_wave_prefix。", + "在 order.wave.waveStrategyList 的返回 list[*] 中新增字段 wave_prefix(string)。", + "在 order.wave.waveStrategyCreate / waveStrategyUpdate 的入参中新增可选字段 wave_prefix(string),创建/更新成功后保存为大写且触发策略版本推进。", + "在 order.wave.waveStrategyFetchPda 的行为说明中补充:生成波次号(wave_no)时优先使用策略层 wave_prefix,否则按策略类型回退到仓库前缀;前缀校验同上。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-01", + "date": "2026-05-15", + "summary": "仅更新文档:将 setting.express.create 入参与实现对齐(新增 express_code,移除 platform)", + "methods": [ + "setting.express.create" + ], + "notes": [ + "仅同步文档,与实现对齐,未修改任何业务代码或行为" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-02", + "date": "2026-05-15", + "summary": "新增 storage.report.search:库存流水统计报表,支持按时间闭区间过滤与按库位/按商品聚合", + "methods": [ + "storage.report.search" + ], + "notes": [ + "方法新增:storage.report.search", + "时间过滤为闭区间:created_at >= start_time 且 created_at <= end_time", + "当 where.by_space 为 false(默认)时,按商品+货主聚合(多个库位汇总);当为 true 时按商品+库位返回", + "不返回无流水的商品/键(仅返回在查询区间内出现过流水的数据)" + ], + "type": "added" + }, + { + "version": "2026.05.15-system-03", + "date": "2026-05-15", + "summary": "库存报表模块主入口迁移到 stock.report.search,storage.report.search 保持兼容别名", + "methods": [ + "stock.report.search", + "storage.report.search" + ], + "notes": [ + "新增主入口方法 stock.report.search,沿用既有报表统计口径(时间闭区间、by_space/store_ids、返回字段保持一致)。", + "保留 storage.report.search 作为兼容别名,并在描述中明确建议迁移到 stock.report.search。", + "仅更新 methods 文档配置,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-04", + "date": "2026-05-15", + "summary": "文档主入口统一为 stock.report.search,storage.report.search 调整为兼容别名简述", + "methods": [ + "stock.report.search", + "storage.report.search" + ], + "notes": [ + "保留 stock.report.search 作为库存报表唯一完整文档入口。", + "storage.report.search 不再维护完整重复字段,仅保留迁移与兼容说明。", + "仅更新 methods 文档配置,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-05", + "date": "2026-05-15", + "summary": "拆分 storage.report 模块并移除错误 stock.report.search 文档入口", + "methods": [ + "storage.report.search", + "stock.report.search" + ], + "notes": [ + "将库存报表从 storage.inventory 中拆分为独立模块 storage.report,storage.report.search 文档改为主入口语义(不再作为兼容别名)。", + "从 storage.inventory 分组中移除错误的 stock.report.search 文档入口以及兼容别名条目 storage.report.search。", + "最终归属:storage.report.search 属于模块 storage.report;stock.report.search 的文档入口已移除以避免混淆(代码实现保留于 app/service/systemMethods/storage/report.js 的 storage.report.search)。", + "仅修改文档,不修改应用代码实现。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-06", + "date": "2026-05-15", + "summary": "storage.report.search 新增排序能力文档说明", + "methods": [ + "storage.report.search" + ], + "notes": [ + "补充 sort 参数:支持 sortField/sort_field、sortOrder/sort_order。", + "补充排序白名单:begin_total、inbound_total、outbound_total、end_total。", + "补充非法排序字段/顺序回退默认排序说明。", + "响应说明补充:已按 sort 规则排序返回。" + ], + "type": "updated" + }, + { + "version": "2026.05.16-system-01", + "date": "2026-05-16", + "summary": "新增 storage.report.export:按与 storage.report.search 相同条件导出库存报表 Excel", + "methods": [ + "storage.report.export" + ], + "notes": [ + "新增方法:storage.report.export,复用 storage.report.search 的 where/sort 查询条件。", + "导出文件包含两个 sheet:汇总、变更记录。", + "用于在统计结果基础上回溯明细流水,提升库存变动追溯效率。" + ], + "type": "added" + }, + { + "version": "2026.05.16-system-02", + "date": "2026-05-16", + "summary": "storage.report.export 改为异步任务 + 新增 exportTaskProgress", + "methods": [ + "storage.report.export", + "storage.report.exportTaskProgress" + ], + "notes": [ + "调用方式调整为两步:先调用 storage.report.export 提交任务并获取 task_id,再调用 storage.report.exportTaskProgress 轮询任务进度。", + "下载链接获取方式:当 status=success 时,从 exportTaskProgress 响应的 download_url 字段获取导出文件地址。", + "任务状态值补充:submitted/running/success/failed/not_found。" + ], + "type": "updated" + }, + { + "version": "2026.05.16-system-03", + "date": "2026.05.16", + "summary": "同步 setting.expressInterface.create/update 入参与系统快递编码映射规则", + "methods": [ + "setting.expressInterface.create", + "setting.expressInterface.update" + ], + "notes": [ + "补充入参:sys_express_code、weight_type、address、town_name、ispickup、shipperno,并保留既有字段。", + "在参数说明补充 camelCase 别名支持:sysExpressCode、weightType、townName、isPickup、shipperNo 等。", + "同步约束变化:不再因同仓快递编码重复或平台重复直接返回 409;当 express_code 无法匹配系统快递编码时返回 400,文案为 express_code 未匹配到系统快递编码。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-05", + "date": "2026-05-17", + "summary": "同步 storage.receiving.addDetail 的参数与返回值(从实现提取)", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "补充 receiving_id 入参说明", + "补充返回的 details 数组与 selectId 字段", + "补充可能的错误码:404/400/500" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-06", + "date": "2026-05-17", + "summary": "重新同步 addDetail 文档", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "再次从实现代码核对并补充参数/返回值/错误码,确保文档与实现一致", + "仅同步文档,不修改业务代码" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-07", + "date": "2026-05-17", + "summary": "addDetail 新增可选 item 入参并兼容空白创建链路", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "item 有值时按传入字段创建(服务端覆盖 receiving_id 与 creator_id)", + "兼容不传 item 的空白创建链路;item.children 需覆盖关键字段(有则写、无则补齐)。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-10", + "date": "2026-05-17", + "summary": "调整 storage.receiving.getReceivingDetail 库位字段输出语义:space_id 改为展示名称并补充兼容字段", + "methods": [ + "storage.receiving.getReceivingDetail" + ], + "notes": [ + "将 receiving.details.*.space_id 定义为展示名称(string|null),优先 custom_space_name,其次 space_name,不再作为原始数值ID文档语义。", + "新增并明确 receiving.details.*.space_id_raw(number|null)用于保留原始库位ID,兼容旧调用方。", + "补充 receiving.details.*.space_name(库位名称/编码)与 receiving.details.*.custom_space_name(自定义名称,可空)字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-11", + "date": "2026-05-17", + "summary": "补充 subject_config.enable_external_express_code 字段文档与默认值语义", + "methods": [ + "store.createStore", + "store.createWarehouse", + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 store.createStore 与 store.createWarehouse 的 subject_config 入参中新增字段:enable_external_express_code(boolean),默认 false;开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)。", + "此 change 同时用于说明将在 setting.warehouse.getSettings / saveSettings 中补充该字段的文档说明(后续 doc-only 写入)。" + ], + "type": "updated", + "module": "store" + }, + { + "version": "2026.05.17-system-12", + "date": "2026-05-17", + "summary": "storeWarehouse.store 策略配置文档新增 enable_external_express_code 字段说明(向后兼容)", + "methods": [ + "storeWarehouse.store.getPolicyConfig", + "storeWarehouse.store.savePolicyConfig" + ], + "notes": [ + "在 getPolicyConfig / savePolicyConfig 的出参说明中补充 data.policy_config.enable_external_express_code 字段,明确为 flag(0=关闭,1=开启),默认 0。", + "在 savePolicyConfig 的入参说明中补充 policy_config.enable_external_express_code 字段定义。", + "本次为向后兼容的文档增强:新增可选策略字段说明,不影响现有调用。" + ], + "type": "updated" + }, + { + "version": "2026.05.19-system-01", + "date": "2026-05-19", + "summary": "补充 storage.entry.list 的 expense_record 筛选语义与未迁移环境错误提示", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "在 where 参数说明中补充 expense_record 字段语义(费用是否记录)及 eq/in 支持。", + "明确 true/false、1/0、y/n、yes/no 的归一化规则与等价写法示例。", + "补充未完成表结构迁移时可能返回 400 及错误提示文案。" + ], + "type": "updated" + }, + { + "version": "2026.05.20-system-01", + "date": "2026-05-20", + "summary": "同步 order.recheckOrder.scanOrder 返回结构,补充 cart_match_view 语义化视图说明", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增返回字段:match_type(waybill/cart)与 cart_match_view(仅 cart 命中返回)。", + "cart_match_view 包含通用子字段:mode_code / mode_name / view_type / task;当车号命中时按 pick_mode 返回语义化结构:mode 1/5 返回 groups,mode 2 返回 orders,mode 3 返回 pick_groups,mode 4 返回 box_groups。" + ], + "type": "updated" + }, + { + "version": "2026.05.22-system-01", + "date": "2026-05-22", + "summary": "新增 index.getPlatformOauthLink 文档,补充平台授权链接接口说明", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "入参支持 code、platform_code、platformCode 三种平台编码字段别名。", + "当前仅支持 PDD;成功返回 data.platform_code、data.oauth_link 和 code=200,其他平台返回 code=400。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-02", + "date": "2026-05-22", + "summary": "更新 index.getPlatformOauthLink 文档,补充仓库上下文、预占记录与错误说明", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "补充真实行为:从 ctx.user.store_id 读取当前仓库 ID,从 wms_platform.auth_base_url 读取授权基础地址,并在 wms_shops 创建平台授权预占记录。", + "补充 oauth_link 细节:追加 client_id、redirect_uri(配置非空时)以及长查询参数 wms_authorization_reservation_code,对应唯一 auth_random_code。", + "补充常见错误:平台编码为空、仓库上下文缺失、平台不存在、授权基础地址缺失/格式错误、不支持的平台,以及预占记录创建失败。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-03", + "date": "2026-05-22", + "summary": "同步 index.getPlatformOauthLink 当前实现:裸码入库与 state 拼接规则", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "补充真实行为:从 ctx.user.store_id 读取当前仓库,从 wms_platform.auth_base_url 读取基础授权链接,并优先复用 wms_shops 中 status=0 的未授权记录。", + "明确 auth_random_code 当前以裸码保存;若复用到历史带前缀记录,会先去掉 platformOauthReservationCodePrefix 后再回写。", + "更新 oauth_link 说明:state 由“前缀 + 平台编码 + '_' + 裸码”组成并整体 URL 编码后直接拼接到基础授权链接后,例如 xxxxx_PDD_;同时移除已不存在的基础地址格式错误/不支持平台错误描述。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-04", + "date": "2026-05-22", + "summary": "修正 index.getPlatformOauthLink 文档中的残留平台限制描述", + "methods": [ + "index.getPlatformOauthLink" + ], + "notes": [ + "移除 index.getPlatformOauthLink 参数与返回字段中残留的“当前仅支持 PDD”描述,避免与当前实现不一致。", + "保留授权链接仅依赖平台已配置基础授权链接模式的说明,不再把示例平台编码误写成实现限制。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-05", + "date": "2026-05-22", + "summary": "新增 index.getShopList 文档,并同步 custom_name 与店铺列表脱敏返回规则", + "methods": [ + "index.getShopList" + ], + "notes": [ + "新增 index.getShopList:接口依赖当前登录仓库上下文 ctx.user.store_id,不接受额外业务入参,缺少仓库时返回 400:未识别到当前仓库。", + "补充真实返回结构:data.list 为数组,包含 id、warehouse_id、platform_code、shop_name、custom_name、status、auth_expire_at、token_expires_at、refresh_token_expires_at、scope、created_at、updated_at 以及脱敏后的 owner_id、access_token、refresh_token、auth_random_code。", + "同步脱敏规则:owner_id 非空且长度大于 5 时返回前 3 位 + *** + 后 2 位,长度小于等于 5 时返回 ***;access_token、refresh_token、auth_random_code 非空时固定返回 ***,空值返回 null。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-06", + "date": "2026-05-22", + "summary": "新增 index.getShopExpressList 文档,补充店铺快递列表统一返回结构", + "methods": [ + "index.getShopExpressList" + ], + "notes": [ + "按 ctx.user.store_id 校验店铺归属,仅允许查询当前登录仓库下的店铺。", + "服务端按店铺所属平台拉取并收敛快递签约/电子面单可用列表,统一返回前端消费结构。", + "未接入平台当前返回空列表;若店铺缺少授权 access_token,则返回 400:店铺未授权。", + "仅文档同步,不改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.22-system-07", + "date": "2026-05-22", + "summary": "同步快递接口文档:is_share 仅展示不可编辑", + "methods": [ + "setting.expressInterface.list", + "setting.expressInterface.create", + "setting.expressInterface.update" + ], + "notes": [ + "create/update 不再接受 is_share", + "list 仍可返回 is_share 作为展示信息", + "仅文档同步,不改业务代码" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.22-system-08", + "date": "2026-05-22", + "summary": "同步快递接口列表文档,移除未返回字段说明", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "根据 app/service/systems/setting/expressInterface.js 的 list() 查询字段与 normalizeInterfaceRow() 返回结构,同步 setting.expressInterface.list 不返回 token。", + "按当前实现清理 response.children 中未返回的 share_id、can_use_count 字段说明。", + "保留 is_share,并明确其仅用于展示,不作为编辑入参。" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.22-system-09", + "date": "2026-05-22", + "summary": "index.getShopList 支持按平台编码筛选店铺", + "methods": [ + "index.getShopList" + ], + "notes": [ + "index.getShopList 兼容 platform_code 与 platformCode 两种传参方式,服务端按 platform_code、platformCode 顺序读取首个 trim 后非空值作为平台筛选条件。", + "未传平台参数时返回当前登录仓库下全部已授权店铺;传入非空平台编码时仅返回该平台的已授权店铺。", + "本次仅补充筛选条件文档,不影响返回结构、排序规则与 owner_id/access_token/refresh_token/auth_random_code 的脱敏规则。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改任何业务代码。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.22-system-10", + "date": "2026-05-22", + "summary": "快递接口配置新增 shop_id 字段", + "methods": [ + "setting.expressInterface.create", + "setting.expressInterface.update", + "setting.expressInterface.list" + ], + "notes": [ + "create/update 支持 shop_id/shopId(兼容 snake_case 与 camelCase),为店铺 ID,未传或空值按 null 处理。", + "list 返回 shop_id 字段,列表 where 支持按 shop_id 过滤。" + ], + "type": "updated" + }, + { + "version": "2026.05.22-system-11", + "date": "2026-05-22", + "summary": "调整快递接口列表排序规则", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "setting.expressInterface.list 改为按 weight ASC, id DESC 排序;优先按权重排序,权重相同再按 id 倒序。", + "本次仅同步该接口排序说明,不影响返回结构。" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.22-system-12", + "date": "2026-05-22", + "summary": "index.getShopExpressList 返回新增系统快递编码", + "methods": [ + "index.getShopExpressList" + ], + "notes": [ + "data.list[*] 新增 sys_express_code 字段,由平台快递编码 wp_code 映射系统快递编码,未匹配时返回空字符串。", + "补充 data.list[*].wp_name 说明:由系统快递基础表根据平台快递编码映射得到名称,未匹配时返回空字符串。", + "原有请求参数、鉴权方式与返回主结构保持不变。", + "仅文档同步,不改业务代码。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.23-system-01", + "date": "2026-05-23", + "summary": "补充快递接口列表 is_system_express_code 返回字段说明", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "在 setting.expressInterface.list 的 response.children 中补充 is_system_express_code 字段说明。", + "该字段表示当前行 express_code 是否为系统快递编码;不是系统快递编码返回 0,否则返回 1。", + "仅文档同步,不改业务代码。" + ], + "type": "updated", + "module": "setting.expressInterface" + }, + { + "version": "2026.05.23-system-02", + "date": "2026-05-23", + "summary": "完善 index.getExpressList 文档:补充过滤规则、返回字段与仓库维度行为", + "methods": [ + "index.getExpressList" + ], + "notes": [ + "补充 `systemOnly`、`express_code`、`expressCode` 的真实入参语义,明确真值识别规则与字段优先级。", + "补充默认模式、系统模式、按快递编码过滤模式下的返回差异,说明当前登录仓库维度来自 `ctx.user.store_id`。", + "补充 `data[*]` 各字段含义,明确系统基础快递与仓库自定义快递编码的差异字段。", + "仅文档同步,不修改业务代码。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.24-system-01", + "date": "2026-05-24", + "summary": "同步 index.getExpressList 文档:移除 expressCode 别名并明确 express_code 筛选语义", + "methods": [ + "index.getExpressList" + ], + "notes": [ + "移除 index.getExpressList 文档中的 expressCode 驼峰别名参数,仅保留 express_code。", + "明确当 systemOnly=false 且传入 express_code 时,接口按自定义映射记录中的系统快递编码字段 express_code 过滤,而不是按自定义 code 过滤。", + "保留 systemOnly=true 按系统快递编码过滤系统基础快递列表,以及默认合并逻辑、缓存优先、仓库维度来源不变的说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.24-system-02", + "date": "2026-05-24", + "summary": "新增 index.getCainiaoStfTemplates 接口文档并明确模板返回语义", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "新增无参接口 index.getCainiaoStfTemplates:从当前仓库首个已授权 TB 店铺发起 cainiao.waybill.ii.search 查询菜鸟 STF 模板。", + "补充返回结构说明:data.platform_code 固定为 TB;data.list 返回模板数组并包含 template_id/template_name/template_url/cp_code/wp_code 字段。", + "明确模板列表为宽松结构解析并按 template_id/template_name/template_url 核心语义去重。", + "补充错误码说明:未识别仓库返回 400;当前仓库无已授权 TB 店铺返回 404。" + ], + "type": "added" + }, + { + "version": "2026.05.24-system-03", + "date": "2026-05-24", + "summary": "调整 index.getCainiaoStfTemplates 为免登录/免鉴权接口", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "将 index.getCainiaoStfTemplates 的 isNeedLogin 调整为 false,接口改为免登录访问。", + "保持 isNeedAuth=false,并同步免权限拦截配置,避免登录态与鉴权拦截。", + "该接口仍为无请求参数,headers 调整为空数组。" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.05.24-system-04", + "date": "2026-05-24", + "summary": "调整 index.getCainiaoStfTemplates 为公共无参模板查询接口", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "index.getCainiaoStfTemplates 改为公共无参查询,不再依赖当前仓库、登录态或店铺授权。", + "接口直接调用 requestTbWaybillSearch({ cpCode: '' }) 查询公共模板,返回 data.platform_code='TB' 与模板数组。", + "requestTbWaybillSearch 支持 accessToken 缺失时不下发 session,因此该接口不再依赖 session。" + ], + "type": "updated" + }, + { + "version": "2026.05.24-system-05", + "date": "2026-05-24", + "summary": "同步 index.getCainiaoStfTemplates 改用淘宝标准模板公共接口", + "methods": [ + "index.getCainiaoStfTemplates" + ], + "notes": [ + "index.getCainiaoStfTemplates 改为调用淘宝开放平台 cainiao.cloudprint.stdtemplates.get,不再复用 cainiao.waybill.ii.search。", + "接口不需要用户授权,不下发 session,继续使用 https://eco.taobao.com/router/rest 与 TOP 公共签名参数。", + "模板列表改为从 cainiao_cloudprint_stdtemplates_get_response.result.datas[*].standard_templates[*] 做宽松兼容解析,统一返回 template_id/template_name/template_url/cp_code/wp_code。" + ], + "type": "updated" + }, + { + "version": "2026.05.24-system-06", + "date": "2026-05-24", + "summary": "新增 index.getPrintPlatformList 接口文档并明确打印平台下拉返回结构", + "methods": [ + "index.getPrintPlatformList" + ], + "notes": [ + "新增 index.getPrintPlatformList 文档,说明该接口供快递接口新增/编辑页下拉选择使用。", + "补充接口行为:仅返回未删除且状态为 ACTIVE 的打印平台,不分页,按 platform_name 与 id 升序返回。", + "补充 data[*] 返回字段说明,明确 code/name/value/label/platform_code/platform_name/status/remark 的含义。", + "仅文档同步,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.24-system-07", + "date": "2026-05-24", + "summary": "新增 index.getPrintPlatformTemplateList 文档,明确 express_code 必填与模板过滤语义", + "methods": [ + "index.getPrintPlatformTemplateList" + ], + "notes": [ + "新增 index.getPrintPlatformTemplateList 方法文档,补充 platform_code 与 express_code 入参,其中 express_code 标记为必填。", + "明确业务语义:接口按 platform_code(默认 CAINIAO)定位 wms_express 中对应打印平台字段,并使用 express_code 过滤模板结果后返回。", + "补充返回结构 data.platform_code / data.express_code / data.responseData,说明未实现平台返回空对象。", + "仅文档同步,不修改业务代码。" + ], + "type": "added", + "module": "index" + }, + { + "version": "2026.05.25-system-01", + "date": "2026-05-25", + "summary": "新增 index.polyapiAuthorizeUrl 接口文档并标注免登录免鉴权特征", + "methods": [ + "index.polyapiAuthorizeUrl" + ], + "notes": [ + "新增基础模块方法 index.polyapiAuthorizeUrl,说明其为公共无参接口。", + "明确接口固定调用菠萝派 Differ.JH.BuildeAuthorizeUrl,返回体中以 data.respone 原样包裹上游响应。", + "同步标注 isNeedLogin=false、isNeedAuth=false,headers 为空数组。" + ], + "type": "added" + }, + { + "version": "2026.05.25-system-02", + "date": "2026-05-25", + "summary": "新增店铺模块相关接口文档(shops.list/add/del/edit)及授权会话接口 shops.GetAuthorizeSessionKey", + "methods": [ + "shops.list", + "shops.add", + "shops.del", + "shops.edit", + "shops.GetAuthorizeSessionKey" + ], + "notes": [ + "同步实现:shops.list 支持 where 分页与 quickWhere 快速搜索;shops.add/edit 校验 platform_code 存在且为 ACTIVE,custom_name 必填且长度限制;shops.del 为软删除,会返回 deleted=true 并清空敏感字段,若存在快递接口引用返回 409;shops.GetAuthorizeSessionKey 对 PDD/CAINIAO 平台生成预占码并返回 authorize_url,其他平台返回 501。", + "字段命名兼容说明:接口实现兼容 snake_case 与 camelCase 入参,文档以 snake_case 为主并注明兼容性。" + ], + "type": "added" + }, + { + "version": "2026.05.25-system-03", + "date": "2026-05-25", + "summary": "同步 shops.add 去入参化:移除 shop_name 入参并明确由授权后获取店铺名称", + "methods": [ + "shops.add" + ], + "notes": [ + "shops.add 入参移除 shop_name(及同义传参语义),仅保留 custom_name 与 platform_code 为关键请求字段。", + "补充说明:新增时 shop_name 由服务端生成 PENDING_* 占位名,后续以授权回调同步真实店铺名称。", + "仅文档同步,不修改任何业务代码。" + ], + "type": "updated", + "module": "shops" + }, + { + "version": "2026.05.28-system-02", + "date": "2026-05-28", + "summary": "新增 method: order.print.unlockWavePlatformPrintDataByGroup,按分组解锁波次平台打印锁", + "methods": [ + "order.print.unlockWavePlatformPrintDataByGroup" + ], + "notes": [ + "新增方法:order.print.unlockWavePlatformPrintDataByGroup,用于按分组规则批量解锁波次内被锁定的订单(将 print_lock_status 设为 'none')。", + "入参说明:group_type 默认为 platform_express(支持 platform、platform_express、order),unlock_scope 默认为 group(支持 group、wave);groups 为必须项,元素对象可包含 wave_id、platform、sys_logistics_code、order_ids 等字段。", + "返回说明:返回 summary(解锁统计)、unlocked_order_ids、unlocked_orders、ext.missing_wave_ids、ext.filtered_wave_ids 等字段。", + "实现参考:app/service/systemMethods/order/print.js 与 app/service/systems/order_print.js 的 unlockWavePlatformPrintDataByGroup 实现,相关单元测试位于 test/app/controller/system.order.print.unlockByGroup.test.js 与 test/app/service/systems/order_print.unlockWavePlatformPrintDataByGroup.test.js。" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-03", + "date": "2026-05-28", + "summary": "新增 order.updateExpressWeighingWeight 方法文档并补充单/多运单称重写入规则", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "新增 order.updateExpressWeighingWeight 入参说明:order_id、waybill_code、weighing_weight。", + "明确规则:单运单订单忽略 waybill_code 并直接更新唯一运单;多运单订单必须传 waybill_code 且需匹配订单下运单。", + "补充成功返回字段:order_id、waybill_code、weighing_weight。", + "补充错误码:400(参数校验与多运单缺失运单号)、404(运单记录不存在或未匹配)、500(模型未初始化或更新失败)。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.28-system-01", + "date": "2026-05-28", + "summary": "新增包材相关 methods(create/update/delete/get),并提供 list 兼容说明", + "methods": [ + "setting.packageMaterial.create", + "setting.packageMaterial.update", + "setting.packageMaterial.delete", + "setting.packageMaterial.get", + "setting.packageMaterial.list" + ], + "notes": [ + "实现参考:app/service/systems/setting/packageMaterial.js", + "list 为兼容别名,内部转发至 get,建议新接入方改用 get" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-04", + "date": "2026-05-28", + "summary": "Add packageSupplier methods (create/update/delete/get) with list alias note", + "methods": [ + "setting.packageSupplier.create", + "setting.packageSupplier.update", + "setting.packageSupplier.delete", + "setting.packageSupplier.get", + "setting.packageSupplier.list" + ], + "notes": [ + "Reference implementation: app/service/systems/setting/packageSupplier.js", + "list is a compatibility alias; prefer get" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-05", + "date": "2026-05-28", + "summary": "新增 order.bindExpressPackageMaterial 方法文档,支持按订单运单绑定包材", + "methods": [ + "order.bindExpressPackageMaterial" + ], + "notes": [ + "新增 order.bindExpressPackageMaterial 入参说明:order_id、waybill_code、package_material_code(均必填)。", + "补充行为说明:按订单ID+运单号匹配 wms_order_express,按包材编码匹配包材并绑定 package_material_id 与 package_material_name_snapshot。", + "补充成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", + "补充错误码:400 参数错误、404 包材编码不存在、404 订单运单记录不存在、500 绑定包材失败。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.29-system-01", + "date": "2026-05-29", + "summary": "新增 order.export 与 order.exportTaskProgress:订单导出异步任务与进度查询", + "methods": [ + "order.export", + "order.exportTaskProgress" + ], + "notes": [ + "order.export:提交导出任务,入参支持 table_type/tableType(枚举 current/history/dispatch/outsourced,兼容订单模块别名)与 module/module_name,where/sort 语义与 order.list 一致。接口提交后立即返回 task_id,后台异步执行导出,导出进度与结果通过 order.exportTaskProgress 查询。", + "order.exportTaskProgress:按 task_id 查询任务进度,返回 task_id、status、progress、current_count、total_count、message、error、download_url、update_time;任务上传完成后 download_url 返回可下载链接,未找到时 status=not_found。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.30-system-01", + "date": "2026-05-30", + "summary": "新增 print.notifyLock(及 notify_lock 兼容别名),并补充 print.send 写入订单操作日志的行为说明", + "methods": [ + "print.notifyLock", + "print.notify_lock", + "print.send" + ], + "notes": [ + "新增 print.notifyLock:入参支持 order_ids/orderIds、waveGroups、data.waveGroups(至少一类提供订单 ID);仅执行订单锁定流程,不发送打印任务;写打印任务日志 + 订单操作日志;返回 locked_count、order_ids_count、order_ids、source;错误:无有效订单ID(400)、锁定失败(500)。", + "补充 print.send 文档:说明接口在执行打印任务记录的同时会写入订单操作日志(记录打印相关操作)。", + "新增兼容别名 print.notify_lock:文档说明等价转调到 print.notifyLock。" + ], + "type": "updated", + "module": "print" + }, + { + "version": "2026.06.03-system-01", + "date": "2026-06-03", + "summary": "同步 pick.query 文档为 keyword 任务化语义并补充冲突错误码", + "methods": [ + "pick.query" + ], + "notes": [ + "入参由 waybill_code/full_display 统一为 keyword(支持运单号或波次号)。", + "成功返回调整为 task_id/status/tip,status 取值 existing 或 created。", + "补充 409 冲突语义:波次已有他人活动任务时返回任务归属信息。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-02", + "date": "2026-06-03", + "summary": "更新 pick.wavePickTaskDetail:增加快递号/储位分配前置校验并返回 action+order_ids", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增前置校验:任务内若存在未分配快递号订单,返回 400,data.action=assign_express,data.order_ids 为未分配订单ID列表。", + "新增前置校验:任务内若存在未分配储位订单,返回 400,data.action=assign_storage,data.order_ids 为未分配订单ID列表。", + "保留原有权限校验与详情结构,仅补充分配校验失败分支的返回约定。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-03", + "date": "2026-06-03", + "summary": "更新 order.wave.batchList:新增同步状态输出与筛选 sync_assignment_status", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增返回字段语义:list[].sync_assignment_status,取值为未同步/部分同步/已同步/同步异常。", + "新增筛选入参 where.sync_assignment_status,支持 unsynced/partially_synced/synced 英文枚举。", + "同步状态筛选规则与分配状态一致:error 并入 unsynced 过滤集合。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-04", + "date": "2026-06-03", + "summary": "更新拣货中间态流程文档:wavePickTaskDetail 增加完成标记,并新增中间态/完全提交接口", + "methods": [ + "pick.wavePickTaskDetail", + "pick.wavePickTaskSubmit", + "pick.wavePickTaskComplete" + ], + "notes": [ + "更新 pick.wavePickTaskDetail 返回:新增 task.is_completed、task.progress(total_orders/picked_orders/pending_orders)以及顶层 is_completed。", + "新增 pick.wavePickTaskSubmit:支持保存中间态 payload 到任务 ext_json.pick_intermediate,并返回当前完成状态与进度。", + "新增 pick.wavePickTaskComplete:支持 mode=1 全部确认与 mode=2 部分确认(order_ids),返回 confirmed_order_ids 与最新进度。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-05", + "date": "2026-06-03", + "summary": "拣货车能力拆分为一级模块 pickCart:扫码查询、任务绑车、CRUD、编码查重", + "methods": [ + "pickCart.scan", + "pickCart.bindTaskCart", + "pickCart.create", + "pickCart.update", + "pickCart.delete", + "pickCart.detail", + "pickCart.list", + "pickCart.codeDuplicateCheck" + ], + "notes": [ + "拣货车能力独立为一级模块 pickCart,不再挂在 pick 模块下。", + "新增 pickCart.scan:PDA 按 cart_code 扫码查询拣货车信息,用于进入任务绑定流程。", + "新增 pickCart.bindTaskCart:支持按 cart_id/cart_code 将拣货车绑定到指定拣货任务,若车已绑定其他活动任务则返回冲突。", + "新增 pickCart.create/pickCart.update/pickCart.delete/pickCart.detail/pickCart.list:补齐拣货车增删查改与分页查询能力。", + "新增 pickCart.codeDuplicateCheck:支持 exclude_cart_id 排除自身,供编辑场景做非自身重复校验;拣货车编码在当前仓库内不可重复。" + ], + "type": "updated" + }, + { + "version": "2026.06.03-system-06", + "date": "2026-06-03", + "summary": "更新 order.wave.batchList:新增 only_todo、复核状态聚合与复核筛选", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增入参 only_todo(默认 0):传 1/true 时仅返回仍有未复核订单的波次(unreviewed_order_count > 0)。", + "新增返回字段:list[].unreviewed_order_count(未复核订单数)与 list[].review_assignment_status(未复核/部分复核/已复核)。", + "新增 where.review_assignment_status 筛选,支持 unreviewed/partially_reviewed/reviewed 英文枚举。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.04-system-01", + "date": "2026-06-04", + "summary": "裁剪 pick.wavePickTaskDetail 返回:团购小波次(pick_mode=1)不返回 picking_details 字段以减少带宽", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "在 picking_details 字段 description 中补充:当 pick_mode=1(团购小波次)时该字段不返回,减少带宽浪费;其他 pick_mode(2/3/4/5)正常返回 picking_details。", + "在接口 description 中补充该裁剪行为的说明。", + "picking_summary、picking_view、boxes 等字段不受影响,pick_mode=1 时仍正常返回。" + ], + "type": "updated" + }, + { + "version": "2026.06.04-system-02", + "date": "2026-06-04", + "summary": "完善 index.getPlatformList 文档:补充入参 systemOnly/full、响应字段及错误码 500", + "methods": [ + "index.getPlatformList" + ], + "notes": [ + "补充入参说明:systemOnly(可选,支持 is_system 别名,真值识别 true/1/'1'/'true')、full(可选,真值识别同上,为 true 时返回全量表字段与 route_platform_code/platid 等扩展信息)", + "补充响应 data 数组每项字段:code、name、value、label、platform_code、platform_name、default_express_interface、is_system_setting、id(仅仓库自定义项)、alias(仅仓库自定义项)、full 模式扩展字段说明", + "说明合并逻辑:系统平台在前,仓库自定义在后,同 code 仅保留首条(系统优先);systemOnly=true 仅返回系统平台", + "补充缓存策略:优先读缓存,key 格式为 platform:list:{warehouseId}[:full] 或 platform:list:system[:full]", + "补充错误码 500:数据库或缓存访问异常", + "仅文档更新,不修改任何业务实现" + ], + "type": "updated", + "module": "index" + }, + { + "version": "2026.06.04-system-03", + "date": "2026-06-04", + "summary": "作废 order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", + "methods": [ + "order.pendingOrder.downloadCreateTemplate", + "order.pendingOrder.importOrdersFromExcel" + ], + "notes": [ + "order.pendingOrder.downloadCreateTemplate:下载订单导入模板方法已从代码中移除,标记为 deprecated。", + "order.pendingOrder.importOrdersFromExcel:从 Excel 导入订单方法已从代码中移除,标记为 deprecated。", + "两个方法的文档条目保留在 methods/system.json 中,仅追加 status: 'deprecated' 与 description 中的'(已作废)'标记,未删除。" + ], + "type": "deprecated" + }, + { + "version": "2026.06.05-system-01", + "date": "2026-06-05", + "summary": "新增 storeWarehouse.store.openAccount 接口:仓库代货主一键开户(合并注册账号+创建货主+签约)", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "新增 storeWarehouse.store.openAccount 方法,归属货主-仓库签约模块(storeWarehouse.store)。", + "接口同时完成账号注册、货主创建和仓库-货主签约,一步完成开户全流程。", + "当前主体必须为仓库角色(Authorization header 中携带的 token 对应仓库用户)。", + "必填参数:username(登录账号)、password(初始密码)、company_name(公司全称)、business_license(营业执照号)、contact_person(联系人)、contact_phone(联系电话)。", + "响应返回新创建的 store_id、account_id、contract_id、company_name、username、role_id。" + ], + "type": "added", + "module": "storeWarehouse" + }, + { + "version": "2026.06.05-system-02", + "date": "2026-06-05", + "summary": "优化 storeWarehouse.store.openAccount 必填参数:password 改为随机生成、business_license 和 contact_phone 改为可选,必填仅剩 username/company_name/contact_person 三个", + "methods": [ + "storeWarehouse.store.openAccount" + ], + "notes": [ + "password:由必填改为可选,不传时自动随机生成 12 位密码", + "business_license:由必填改为可选", + "contact_phone:由必填改为可选" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-03", + "date": "2026-06-05", + "summary": "saveApiConfig 增加 callback_url 参数,支持配置 API 回调通知地址", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "新增 callback_url 参数:OpenAPI 类型接口支持配置回调通知 URL", + "兼容别名 callbackUrl,最大 500 字符", + "存入 wms_api_app.callback_url 字段" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-04", + "date": "2026-06-05", + "summary": "createOrder 入参 item_code 改为 item_id,province/city/area 改为必填", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "items[].item_code → items[].item_id:改用商品主键直接匹配,不依赖外部系统商品推送", + "province/city/area 新增必填校验,空值返回 400", + "item_name 优先外部传入,其次从 StockStore 缓存获取,最后兜底'商品'" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-05", + "date": "2026-06-05", + "summary": "新增 order.pendingOrder.parseAddress 智能地址解析方法", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "使用 DeepSeek AI 模型将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号", + "解析结果可直接用于 createOrder 的 receiverInfo 字段", + "DeepSeek API Key 通过 DEEPSEEK_API_KEY 环境变量配置" + ], + "type": "added" + }, + { + "version": "2026.06.05-system-06", + "date": "2026-06-05", + "summary": "waveStrategyUpdate/waveStrategyCreate 新增 wave_prefix 参数", + "methods": [ + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyCreate" + ], + "notes": [ + "新增 wave_prefix 波次编号前缀字段,最多 5 个字符,为空存 null" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-07", + "date": "2026-06-05", + "summary": "parseAddress 响应新增 town 字段(乡镇/街道)", + "methods": [ + "order.pendingOrder.parseAddress" + ], + "notes": [ + "响应 data 中新增 town 字段,返回 AI 解析出的乡镇/街道名称" + ], + "type": "modified" + }, + { + "version": "2026.06.05-system-08", + "date": "2026-06-05", + "summary": "为 order.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-09", + "date": "2026-06-05", + "summary": "为 order.reviewOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.reviewOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-10", + "date": "2026-06-05", + "summary": "为 order.pendingOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.pendingOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-11", + "date": "2026-06-05", + "summary": "为 order.outboundOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.outboundOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-12", + "date": "2026-06-05", + "summary": "为 order.expectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.expectionOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-13", + "date": "2026-06-05", + "summary": "为 order.entrustOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.entrustOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-14", + "date": "2026-06-05", + "summary": "为 order.deliveryOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.deliveryOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-15", + "date": "2026-06-05", + "summary": "为 order.deliveryExpectionOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.deliveryExpectionOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.05-system-16", + "date": "2026-06-05", + "summary": "为 order.archiveOrder.list 响应新增 recheck_status 字段(复核状态:none=未复核,fin=已复核)", + "methods": [ + "order.archiveOrder.list" + ], + "notes": [ + "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" + ], + "type": "updated" + }, + { + "version": "2026.06.06-system-01", + "date": "2026-06-06", + "summary": "恢复 order.pendingOrder.downloadCreateTemplate:方法仍存在于代码中,取消 deprecated 标记,完善文档描述", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "order.pendingOrder.downloadCreateTemplate 方法在 pendingOrder.js 中仍存在(line 2099),此前被误标记为 deprecated。", + "取消 status: 'deprecated' 标记,恢复为 active 状态。", + "移除 description 中的'(已作废)'后缀。", + "完善 description:说明模板包含必填列(橙色背景)、可选列(灰色背景)、示例数据行和填写说明工作表。", + "补充 response 字段说明:filename 和 mime 为固定值。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-01", + "date": "2026-06-07", + "summary": "order.pendingOrder.createOrder 文档新增 shop_nick 入参(店铺名称,可选,最大长度200)", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "在 order.pendingOrder.createOrder 的 request params 中新增 shop_nick 字段(string,非必填),对应代码实现中 shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim()。", + "shop_nick 已在 COPY_FIELDS 白名单中(pendingOrder.js L1738),仅文档缺失,本次为补齐。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-02", + "date": "2026-06-07", + "summary": "order.pendingOrder.downloadCreateTemplate:模板新增 shop_nick 列(店铺名称),store_id/province/city/area 标注为非必填", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "模板新增 shop_nick(店铺名称)列,非必填。", + "明确标注 store_id(货主ID)、province(省份)、city(城市)、area(区/县)为非必填列。", + "响应文档中新增 shop_nick 字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-03", + "date": "2026-06-07", + "summary": "新增 order.pendingOrder.updateAddress:批量修改待处理订单收件地址,限制未分配快递时可用", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "新增 method:order.pendingOrder.updateAddress,免权限(isNeedAuth=false),需登录", + "功能:批量修改待处理订单收件地址(name/mobile/tel/zip_code/province/city/area/town/detail_address)", + "约束:仅 post_status='none'(未分配快递)的订单可修改;至少提供一个有效地址字段", + "响应:返回 updated_count(实际更新行数)和 ids(请求订单ID数组)" + ], + "type": "added" + }, + { + "version": "2026.06.07-system-04", + "date": "2026-06-07", + "summary": "order.wave.wavePickTaskCancel 扩展可取消状态至 status=3,并新增拣货状态回退", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "可取消状态从 [0,1,2] 扩展为 [0,1,2,3](status=3 已完成现在也可取消)", + "取消 status=2(待复核)或 status=3(已完成)任务时,自动回退 wms_wave_pick_task_order.pick_status(1→0)和 order_delivery.pick_status(fin→padding)", + "错误码 400 描述同步更新,补充 403 错误码说明" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-05", + "date": "2026-06-07", + "summary": "order.wave.wavePickTaskList 响应新增 cart_name 字段(拣货车名称)", + "methods": [ + "order.wave.wavePickTaskList" + ], + "notes": [ + "响应 list 子项新增 cart_name(string):通过 current_cart_id LEFT JOIN wms_pick_cart 表获取,未绑定拣货车时为空字符串。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-06", + "date": "2026-06-07", + "summary": "pick.wavePickTaskComplete 新增后台抓取任务(source=2)拣货车绑定校验,未绑定拣货车时拒绝提交", + "methods": [ + "pick.wavePickTaskComplete" + ], + "notes": [ + "description 补充说明:后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。", + "errors 中 400 错误补充:后台抓取任务(source=2)未绑定拣货车时拒绝提交,错误消息为\"后台抓取任务必须先绑定拣货车才能提交\"。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-07", + "date": "2026-06-07", + "summary": "order.wave.batchList 文档修正:移除代码中不存在的 sync_assignment_status 引用", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "从 where 描述中移除 sync_assignment_status(代码 buildBatchListWhereClause allowedFields 中不存在该字段,BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS 中也无 review 之外的同步类型)。", + "从 response list 描述中移除 sync_assignment_status(代码响应映射中仅返回 storage/express/print/review 四种 assignment_status,无 sync_assignment_status)。", + "v2026.06.03-system-03 变更记录中声称新增的 sync_assignment_status 实际从未在代码中实现,本次仅为文档修正,不涉及代码变更。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.07-system-08", + "date": "2026-06-07", + "summary": "order.recheckOrder.confirmRecheck 补充后置行为说明:波次任务全部复核完成后自动解绑车任务", + "methods": [ + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "在 description 中补充:确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务。解绑操作包括:清空 wms_wave_pick_task 的 current_cart_id/current_cart_code_snapshot、停用 wms_pick_task_cart_binding(is_active=0 并记录解绑人和时间)、释放 wms_pick_cart(清空 current_task_id/bind_user_id)。", + "解绑失败仅记录 warn 日志,不影响复核主流程。", + "入参和返回结构未变,仅补充行为说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-10", + "date": "2026-06-07", + "summary": "移除 order.wave.groupFetch / singleFetch / fetch 响应中已废弃的 auto_fetch_disabled_marker 字段", + "methods": [ + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.fetch" + ], + "notes": [ + "auto_fetch_disabled_marker 字段已从代码 submitFetchTask 响应中移除,文档同步删除该字段的描述。", + "auto_fetch_disabled 字段同样已从代码中移除,且原文档中不存在此字段(仅有 auto_fetch_disabled_marker),无需额外处理。", + "涉及 method:order.wave.groupFetch、order.wave.singleFetch、order.wave.fetch,均移除 response 中的 auto_fetch_disabled_marker 字段。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.08-system-01", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块 scanOrder 返回值重构为统一 list 输出,新增 confirmIntercept 与 recheckOrderList 接口", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "scanOrder 返回值重构:统一使用 list 字段输出,新增 list_type 字段区分散单/团购模式。散单模式顶层新增 picker_id、picker_name、wave_id、wave_no、wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count 等汇总字段。list 中每项新增 waybill_no、is_printed、is_reviewed、wave_index、intercept_status、store_remark、stock[](含 stock_id、item_code、item_name、sku_property、packing_requirements、barcodes[]、images[]、plan_qty、has_shared_barcode)。移除旧字段 logs、order、order_id(顶层)、waybill_no(顶层旧位置)、wave_match_view、items、expresses、cart_match_view。", + "scanOrder 入参新增 wave_no / waveNo 支持波次号直接扫描匹配。", + "新增 order.recheckOrder.confirmIntercept:确认拦截接口,将订单 intercept_status 更新为 intercepted_at_warehouse,返回 order_id、order_no、intercept_status、updated_at。", + "新增 order.recheckOrder.recheckOrderList:复核订单列表查询,支持 list_type=single(散单)与 list_type=group(团购),均返回统一 list + pagination 结构。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-02", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块新增 batchIntercept/batchInterceptTaskProgress,更新 scanOrder 团购模式响应结构,完善 confirmIntercept/recheckOrderList 文档", + "methods": [ + "order.recheckOrder.batchIntercept", + "order.recheckOrder.batchInterceptTaskProgress", + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "新增 order.recheckOrder.batchIntercept:批量提交订单拦截(异步任务模式),入参支持 order_ids/orderIds/ids(订单ID数组,不再使用 wave_ids),将 intercept_status 设为 'requested',返回 task_id/warehouse_id/message/accepted_at。支持幂等提交与 warehouse_id 校验。", + "新增 order.recheckOrder.batchInterceptTaskProgress:按 task_id 查询批量拦截任务进度,返回 state(submitted/running/success/failed/not_found)及对应的进度/计数/结果/错误字段。", + "更新 order.recheckOrder.scanOrder 响应文档:团购模式(cart 命中)list 项新增 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[] 等波次级别字段;补充散单无波次信息时的回退详情模式说明(detail/items/expresses/logs)。", + "完善 order.recheckOrder.confirmIntercept:补充操作日志写入说明(ORDER_INTERCEPT_CONFIRM)及失败不影响主流程的容错描述。", + "完善 order.recheckOrder.recheckOrderList:补充散单模式默认排除 pick_status='none' 和 recheck_status='fin' 的说明;团购模式 where 支持 wave_no(模糊搜索)的说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-03", + "date": "2026-06-08", + "summary": "移除 order.recheckOrder.batchIntercept 的 warehouse_id/warehouseId 入参,仓库ID统一使用当前上下文", + "methods": [ + "order.recheckOrder.batchIntercept" + ], + "notes": [ + "移除入参 warehouse_id / warehouseId:仓库ID统一从当前上下文(ctx.user.store_id)获取,不再由调用方传入。", + "移除对应错误码:warehouse_id 参数不合法(400)、warehouse_id 与当前仓库上下文不一致(400)。", + "description 中补充说明仓库ID来源为当前上下文。", + "response 中 warehouse_id 字段描述改为「取自当前上下文」。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-10", + "date": "2026-06-08", + "summary": "batchIntercept / batchInterceptTaskProgress 从 order.recheckOrder 迁移至 order.pendingOrder", + "methods": [ + "order.pendingOrder.batchIntercept", + "order.pendingOrder.batchInterceptTaskProgress" + ], + "notes": [ + "method 从 order.recheckOrder.batchIntercept 重命名为 order.pendingOrder.batchIntercept,分组从订单复核模块迁移至订单待处理模块", + "method 从 order.recheckOrder.batchInterceptTaskProgress 重命名为 order.pendingOrder.batchInterceptTaskProgress,分组从订单复核模块迁移至订单待处理模块", + "接口入参、响应、错误码均保持不变,仅变更 method 名称与所属分组" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-04", + "date": "2026-06-08", + "summary": "新增 order.print.getOrderPrintData:按订单ID拉取打印数据,返回结构与 getWavePlatformPrintData 一致,不限制锁定状态", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "新增 order.print.getOrderPrintData 接口文档,入参为 warehouse_id + order_ids(非空数组),返回与 getWavePlatformPrintData 结构一致的 waveGroups / summary / wave_ids / ext", + "与 getWavePlatformPrintData 的区别:入参为 order_ids(非 wave_ids),ext 中返回 missing_order_ids / filtered_order_ids(非 missing_wave_ids / filtered_wave_ids)", + "不限制打印锁定状态,所有订单(无论是否被锁定)统一返回打印数据", + "自动过滤 post_status !== 'fin' 的订单(快递未完全分配),被过滤订单出现在 ext.filtered_order_ids" + ], + "type": "added", + "module": "order.print" + }, + { + "version": "2026.06.08-system-11", + "date": "2026-06-08", + "summary": "新增 order.pendingOrder 批量锁定/解锁/解除拦截及对应进度查询共 6 个异步任务接口文档", + "methods": [ + "order.pendingOrder.batchLock", + "order.pendingOrder.batchLockTaskProgress", + "order.pendingOrder.batchUnlock", + "order.pendingOrder.batchUnlockTaskProgress", + "order.pendingOrder.batchUnintercept", + "order.pendingOrder.batchUninterceptTaskProgress" + ], + "notes": [ + "新增 batchLock:批量锁定订单,lock_status → 'warehouse',操作日志 ORDER_LOCK,task_id 格式 order_lock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchLockTaskProgress:查询批量锁定进度,返回 locked_order_count / locked_order_ids 等。", + "新增 batchUnlock:批量解锁订单,lock_status → 'none',操作日志 ORDER_UNLOCK,task_id 格式 order_unlock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUnlockTaskProgress:查询批量解锁进度,返回 unlocked_order_count / unlocked_order_ids 等。", + "新增 batchUnintercept:批量解除拦截订单,intercept_status → 'none',操作日志 ORDER_INTERCEPT_CANCEL,task_id 格式 order_unintercept_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUninterceptTaskProgress:查询批量解除拦截进度,返回 unintercepted_order_count / unintercepted_order_ids 等。", + "以上 6 个接口均采用与已有 batchIntercept/batchInterceptTaskProgress 一致的异步任务模式:提交返回 task_id,进度查询返回 state + 进度字段。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "added", + "module": "order" + }, + { + "version": "2026.06.08-system-12", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除锁定限制,所有订单统一返回打印数据,不再区分锁定/未锁定", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除打印锁定限制:所有订单(包括已锁定)统一返回打印数据,不再区分锁定/未锁定状态", + "移除 locked_count、locked_orders、locked_wave_groups 等锁定相关字段", + "返回结构与 getWavePlatformPrintData 完全一致:summary / waveGroups / wave_ids / ext", + "ext 中使用 missing_order_ids / filtered_order_ids(替代锁定相关字段),与代码实现完全对齐" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-13", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除 warehouse_id 入参,仓库ID统一从当前上下文获取", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除 warehouse_id / warehouseId 入参,仓库ID统一从 this.getContextWarehouseId() 获取", + "同步移除 errors 中 warehouse_id 必填 相关错误码", + "description 补充说明仓库ID从上下文获取,无需调用方传入", + "params 仅保留 order_ids(非空数组),与代码 method 层 getOrderPrintData(data) 解构一致" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-14", + "date": "2026-06-08", + "summary": "新增 order.recheckOrder.scanTask 接口文档,并为 scanOrder 响应补充 task_id 字段", + "methods": [ + "order.recheckOrder.scanTask", + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增 order.recheckOrder.scanTask:按拣货任务 ID 拉取复核数据,数据结构与 scanOrder 完全一致,用于前端刷新。入参为 task_id(必填,number),返回 match_type='task',散单模式(pick_mode 2/3/4)返回扁平订单列表,团购模式(pick_mode 1/5)返回分组波次列表。", + "更新 order.recheckOrder.scanOrder 响应定义:补充 task_id 字段说明(散单有波次时由 buildSingleWaveScanView 返回,团单车号命中时由 cartMatchContext 返回)。", + "仅同步文档,不修改任何业务代码或实现。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-15", + "date": "2026-06-08", + "summary": "新增 order.pendingOrder.manualWaybill 接口(手工录入运单号)", + "methods": [ + "order.pendingOrder.manualWaybill" + ], + "notes": [ + "为待处理订单手动录入运单号,写入 wms_order_express 表", + "仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作", + "免权限(isNeedAuth: false),需登录", + "成功返回运单记录的 id、order_id、waybill_code、create_at" + ], + "type": "added" + }, + { + "version": "2026.06.09-system-01", + "date": "2026-06-09", + "summary": "order.pendingOrder.updateAddress 新增 remark 字段:订单留言/备注批量覆盖,不受 post_status 限制", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "在 params 中新增 remark 字段(string,可选,最大500字符),支持批量覆盖所选订单的 remark", + "remark 更新不受 post_status 限制,可对所有订单生效(地址字段仍仅允许 post_status='none')", + "更新 description 明确 remark 与地址字段的独立性", + "更新 response 中 updated_count 说明:取地址更新行数与备注更新行数的最大值", + "更新 errors 中缺少字段的错误描述,改为「至少需要提供一个地址字段或备注进行修改」", + "业务代码已同步实现,本次仅同步文档" + ], + "type": "updated" + }, + { + "version": "2026.06.09-system-02", + "date": "2026-06-09", + "summary": "order.updateExpressWeighingWeight 新增运单号模式文档:order_id=0 时从运单号反查,支持散单与团购批量两种返回结构", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "order_id 参数说明补充:设为0时切换为运单号模式,需配合 waybill_code 使用。", + "waybill_code 参数说明补充:运单号模式(order_id=0)下必填。", + "description 更新:明确订单模式与运单号模式两种路径及团购波次批量行为。", + "response 新增运单号散单场景字段(order_id、waybill_code、weighing_weight)与运单号团购批量场景字段(wave_no、business_key、weighing_weight、success_count)。", + "errors 新增运单号模式相关错误码:运单号不存在(404)、运单号对应的订单不存在(404)、波次下未找到订单(404)、批量更新失败(500)。", + "仅文档同步,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.06.09-system-03", + "date": "2026-06-09", + "summary": "order.updateExpressWeighingWeight 团购返回新增拆单汇总字段,移除 success_count/total_count", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "团购批量模式 response 新增 total_weight(所有拆单重量累加)、split_count(waybill_code 非空的 business_key 数量)、splits(按 business_key 分组的拆单明细数组,每项含 business_key/weighing_weight/waybill_code)、store_name(货主名称)和 sys_logistics_name(系统快递名称)。", + "移除 response 中的 success_count 与 total_count 字段,改为由 total_weight 和 split_count 提供汇总信息。", + "更新 description 以反映团购模式返回拆单汇总结构。" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-01", + "date": "2026-06-10", + "summary": "order.detail 接口文档:expresses 数组新增字段 weighing_weight、sys_logistics_code、sys_logistics_name、business_key、created_at", + "methods": [ + "order.detail" + ], + "notes": [ + "expresses 数组新增字段:weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)", + "字段来源:getOrderExpressesByOrderId 方法中 sys_logistics_code/sys_logistics_name 取自订单表 sys_logistics_code/sys_logistics_name,其余字段取自 OrderExpress 表" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-02", + "date": "2026-06-10", + "summary": "dashboard.order_trend 从 mock 数据改为查询真实数据库,按小时统计当日订单数与发货数,补充完整返回结构与错误说明", + "methods": [ + "dashboard.order_trend" + ], + "notes": [ + "接口实现从 mock 静态数据改为查询真实数据库(wms_order_delivery 与 dispatch 表),数据实时反映仓库当日运营情况。", + "订单筛选条件:step in [1,2,3],排除 outbound_status='padding' 和 status='cancel',统计 create_at 在今日 00:00 到当前时刻的订单,按 HOUR(create_at) 分组。", + "发货筛选条件:dispatch_lane='m4',统计 delivery_time 在今日 00:00 到当前时刻的发货记录,按 HOUR(delivery_time) 分组。", + "时段范围:从 08:00 到当前小时(最晚 23:00),若当前时间早于 08:00 则从 08:00 开始。", + "返回新增 summary 汇总对象:total_orders(订单总数)、total_shipments(发货总数)、shipment_rate(发货率百分比)、peak_hour(峰值时段)、peak_orders(峰值订单数)。", + "categories/orders/shipments 三个数组一一对应,提供按时段的订单与发货趋势数据,可直接用于前端折线图/柱状图渲染。", + "需要登录(Authorization header),从 token 中获取 warehouseId;若缺少仓库上下文则返回 flag='fail'。" + ], + "type": "updated", + "module": "dashboard" + }, + { + "version": "2026.06.10-system-03", + "date": "2026-06-10", + "summary": "order.pendingOrder.manualWaybill 新增可选参数 logistics_interface_name 与响应字段 business_key/logistics_interface_name,补充行为说明", + "methods": [ + "order.pendingOrder.manualWaybill" + ], + "notes": [ + "新增可选参数 logistics_interface_name(string,选填,trim 后为空则传 null)", + "响应新增字段 business_key(number):同一订单下从已有最大值 +1 递增,无记录时从 1 开始", + "响应新增字段 logistics_interface_name(string/null):写入的物流接口名称", + "补充 description 行为说明:完成后自动更新 wms_order_delivery_* 表的 print_status 和 post_status 为 'fin'", + "wms_order_express 表写入时 status 固定为 1,warehouse_id 从订单记录取" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-04", + "date": "2026-06-10", + "summary": "stock.warehouse.import 新增 barcode(条码)字段支持", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "新增 barcode(条码)字段支持,支持别名:条码、bar_code、barCode、barcodeList、barcode_list、barcode。", + "条码字段支持数组格式(如 [\"6901234567890\"])和分号分隔字符串格式(如 \"6901234567890;6901234567891\")。", + "新建和更新路径均已支持条码导入,条码写入 wms_stock_barcodes 表。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "updated" + }, + { + "version": "2026.06.10-system-05", + "date": "2026-06-10", + "summary": "stock.warehouse.import 的 barcode 字段分隔符改为逗号,对齐 stock.warehouse.export 导出格式;仅接收字符串格式,不再支持数组", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "barcode 字段分隔符从分号 ; 改为逗号 ,", + "barcode 字段仅接收字符串格式,不再支持数组格式", + "格式示例:\"6901234567890,6901234567891\",与 stock.warehouse.export 导出格式一致" + ], + "type": "modified" + }, + { + "version": "2026.06.13-system-01", + "date": "2026-06-13", + "summary": "setting.warehouse 的 auto_outbound_rules 新增 require_print 和 require_pick 两个可选条件字段(同步代码实现)", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 getSettings 响应和 saveSettings 入参中补充 subject_config.auto_outbound_rules 对象的完整字段文档(enabled、require_recheck、require_pack、require_weigh、require_sync、require_print、require_pick)。", + "require_print:是否要求已打印(print_status=fin),默认 true。", + "require_pick:是否要求已拣货(pick_status=fin),默认 true。", + "该规则由自动出库定时任务 order_auto_outbound 消费,全部开启的条件均满足时自动标记待出库。" + ], + "type": "updated" + }, + { + "version": "2026.06.13-system-02", + "date": "2026-06-13", + "summary": "order.recheckOrder.scanOrder 团购模式响应新增 orders_detail 字段,暴露非拦截订单的详细列表(含 is_printed、is_reviewed 等状态字段)", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "团购模式(list_type='group')波次视图项新增 orders_detail 字段:非拦截订单详细列表,每项含 order_id、delivery_order_code、waybill_no、pick_status、is_printed(print_status === 'fin')、is_reviewed(recheck_status === 'fin')、recheck_status、shop_nick、items_count、wave_index、intercept_status", + "orders_detail 与现有 order_ids(纯数字 ID 数组)并存,均在团购模式的波次视图项中返回", + "orders_detail 仅在 list_type='group' 时返回,散单模式不受影响", + "同步更新 list 字段 description 以反映 group 模式新增的 order_ids、orders_detail、stocks 字段" + ], + "type": "updated" + }, + { + "version": "2026.06.13-system-03", + "date": "2026-06-13", + "summary": "新增批量快捷复核接口 batchQuickRecheck,支持批量订单 IDs 的前置条件检查(储位、快递、同步、拦截),自动完成拣货并标记复核,支持部分失败。拣货完成后同步更新 wms_wave_pick_task 状态", + "methods": [ + "order.recheckOrder.batchQuickRecheck" + ], + "notes": [ + "新增 order.recheckOrder.batchQuickRecheck 方法", + "入参 ids 支持数组或逗号分隔字符串", + "响应包含 success/failed 列表及计数,failed 项含 reason 说明" + ], + "details": { + "description": "包含拣货任务状态同步:全部拣完→任务状态=2(已完成),未全拣完→任务状态推进为1(拣货中)" + }, + "type": "added" + }, + { + "version": "2026.06.14-system-01", + "date": "2026-06-14", + "summary": "新增 order.bindExpressPackageMaterialByWaybill 方法:支持仅凭运单号绑定包材,无需传入订单ID", + "methods": [ + "order.bindExpressPackageMaterialByWaybill" + ], + "notes": [ + "新增 order.bindExpressPackageMaterialByWaybill 入参说明:waybill_code(运单号,必填)、package_material_code(包材编码,必填)。无需传入 order_id。", + "成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", + "错误码定义:400(参数错误)、404(运单号不存在 / 包材编码不存在)、500(绑定包材失败)。" + ], + "type": "added" + }, + { + "version": "2026.06.15-system-01", + "date": "2026-06-15", + "summary": "order.detail / order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.detail", + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-02", + "date": "2026-06-15", + "summary": "order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-03", + "date": "2026-06-15", + "summary": "新增 setting.packageMaterial.search 方法:支持按关键字模糊搜索包材编码和名称", + "methods": [ + "setting.packageMaterial.search" + ], + "notes": [ + "新增 setting.packageMaterial.search 入参 keyword(可选),为空返回前 50 条启用中包材,有值时对 material_code 和 material_name 做模糊匹配。", + "返回包材数组,字段:id、material_code、material_name、material_type、spec、status。" + ], + "type": "added" + }, + { + "version": "2026.06.16-system-01", + "date": "2026-06-16", + "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", + "methods": [ + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", + "响应 list 每项新增字段 items_weight (DECIMAL(10,2)):订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "added", + "module": "order.recheckOrder" + }, + { + "version": "2026.06.16-system-02", + "date": "2026-06-16", + "summary": "为 order.wave.groupOrderFetchList / waveStrategyFallbackOrderList / singleOrderFetchList 响应新增 items_weight(总重量g)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.groupOrderFetchList", + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleOrderFetchList" + ], + "notes": [ + "order.wave.groupOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "order.wave.waveStrategyFallbackOrderList:响应 list 每项新增 items_weight (number|null):订单总重量(g),来自 wms_order.items_weight;新增 weight_type (string):重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。", + "order.wave.singleOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(g),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "所有新增字段均为可选(required=false),为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.17-system-01", + "date": "2026-06-17", + "summary": "新增 order.pendingOrder.replenishmentDemand 分拣缺货补货需求计算接口文档", + "methods": [ + "order.pendingOrder.replenishmentDemand" + ], + "notes": [ + "新增分拣缺货补货需求计算方法,用于计算待处理订单的SKU在分拣区与存货区的库存分布及补货缺口", + "入参 order_ids/warehouse_id 均为可选;不传 order_ids 时自动查询当前仓库所有未完成储位分配的订单", + "纯只读查询接口,不修改任何数据", + "响应包含 list(明细)与 summary(汇总),其中 shortage = max(0, total_demand - pick_zone_quantity),replenishment_needed = min(shortage, storage_zone_quantity)" + ], + "type": "add", + "module": "order.pendingOrder" + }, + { + "version": "2026.06.17-system-02", + "date": "2026-06-17", + "type": "update", + "module": "order.pendingOrder", + "method": "order.pendingOrder.replenishmentDemand", + "description": "移除 order_ids 参数,改为纯仓库级别计算,自动查询当前仓库所有未完成储位分配的订单" + }, + { + "version": "2026.06.17-system-03", + "date": "2026-06-17", + "type": "update", + "module": "order.pendingOrder", + "method": "order.pendingOrder.replenishmentDemand", + "description": "新增 is_true_shortage 字段标识真正缺货(两区均无库存),summary 新增 total_true_shortage_skus 统计" + }, + { + "version": "2026.06.17-system-04", + "date": "2026-06-17", + "type": "migrate", + "module": "storage.management", + "summary": "从 order.pendingOrder.replenishmentDemand 迁移至 storage.management.replenishmentDemand(库存管理模块),原路径已删除,开发阶段无需兼容", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "将 replenishmentDemand 接口从 order.pendingOrder 模块迁移到新建的 storage.management 库存管理模块。", + "旧条目 order.pendingOrder.replenishmentDemand 已从 order.pendingOrder 组中移除。", + "开发阶段无需兼容旧路径。" + ] + }, + { + "version": "2026.06.17-system-05", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "storage.management.replenishmentDemand 移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "移除 warehouse_id 入参,仓库ID改为纯从用户上下文(ctx.user)获取,接口无需入参" + ] + }, + { + "version": "2026.06.17-system-06", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "method": "storage.management.replenishmentDemand", + "description": "新增分页入参(pagination)、排序入参(sort,默认按 shortage DESC)、响应新增 replenishment_locations(存货区可补货库位,最多5条)、响应新增 pagination 分页信息" + }, + { + "version": "2026.06.17-system-07", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "replenishment_locations 新增 space_name 字段,优先取自定义名称(custom_name),无则回退库位编码(space_code)", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "在 replenishment_locations.children 中新增 space_name 字段(string, required),放在 space_code 之后、available_quantity 之前。", + "space_name 取值逻辑:优先使用库位自定义名称 custom_name,若无自定义名称则回退为库位编码 space_code。" + ] + }, + { + "version": "2026.06.17-system-08", + "date": "2026-06-17", + "type": "update", + "module": "storage.management", + "summary": "合并 is_sufficient 和 is_true_shortage 为 replenishment_status 枚举字段(replenishable/true_shortage)", + "methods": [ + "storage.management.replenishmentDemand" + ], + "notes": [ + "删除 is_sufficient(boolean)和 is_true_shortage(boolean)两个字段。", + "新增 replenishment_status(string)枚举字段:replenishable=存货区足够覆盖缺口,移库可解决;true_shortage=存货区不足以覆盖缺口或两区均无库存,需采购。" + ] + }, + { + "version": "2026.06.18-system-01", + "date": "2026-06-18", + "summary": "入库单完成后异步匹配收货单并回传:completeEntry / entryorderConfirm 入库完成时自动匹配收货单,明细一致则按来源回传(奇门/OpenAPI),覆盖场景标记收货单部分入库;completeReceiving 完成后清除收货单缓存", + "methods": [ + "storage.entry.completeEntry", + "storage.receiving.completeReceiving" + ], + "notes": [ + "新增 app/service/systems/receiving_entry_match.js:入库单完成后异步匹配收货单并回传的核心服务,含 Redis 缓存收货单列表(TTL 300s)、remark 匹配收货单号、明细对比、奇门回传、OpenAPI 回调、部分入库标记等能力。", + "storage.entry.completeEntry 完成后通过 setImmediate 异步触发 matchAfterEntryCompleted,不阻塞主流程。", + "entry_order.js entryorderConfirm() 事务提交后(isFin 最终完成)同样异步触发匹配。", + "storage.receiving.completeReceiving 完成后清除收货单 Redis 缓存(cache:receiving_orders:warehouse:{warehouseId}),确保下次匹配获取最新收货单列表。", + "匹配规则:入库单 remark 包含收货单号 → 对比 SKU+数量 → 完全一致回传 / 收货单覆盖标记部分入库 / 其他不处理。", + "回传路径:source_type=QM → 奇门 taobao.qimen.entryorder.confirm;source_type=API → OpenAPI 回调(entry_order_receiving_matched 事件)。" + ], + "type": "updated" + }, + { + "version": "2026.06.18-system-02", + "date": "2026-06-18", + "summary": "新增 storage.receiving.manualMatchEntryOrder 接口", + "methods": [ + "storage.receiving.manualMatchEntryOrder" + ], + "notes": [ + "新增 storage.receiving.manualMatchEntryOrder:手动匹配入库单与收货单,传入 receivingId 和 entryOrderId,复用异步匹配服务的明细对比和回传逻辑,同步返回匹配结果", + "参数:receivingId (number, 必填)、entryOrderId (number, 必填)", + "校验:入库单存在性、收货单存在性、同仓库校验", + "返回 matchType (full_match/receiving_covers_entry/entry_exceeds_receiving/no_match)、comparisonResult、callbackSent、callbackResult、partialStorageMarked、entryOrder、receivingOrder" + ], + "type": "added", + "module": "storage" + }, + { + "version": "2026.06.18-system-03", + "date": "2026-06-18", + "summary": "新增 storage.receiving.getAvailableInboundQuantity 接口:按 stock_id 查询已审核收货单的可入库数量(actual_quantity - stored_quantity),排除未审核和已取消的收货单", + "methods": [ + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "新增 system method:storage.receiving.getAvailableInboundQuantity,按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity),仅返回尚有可入库余量的明细。", + "实现文件:app/service/systemMethods/storage/receiving.js(包装层)、app/service/systems/storage/receiving.js(业务层)。", + "接口无需鉴权(isNeedAuth=false),但需要登录(isNeedLogin=true)。", + "入参 stock_id 为必填,对应 stock_warehouse.id;服务端从 ctx.user.store_id 获取仓库上下文。" + ], + "type": "added", + "module": "storage" + }, + { + "version": "2026.06.18-system-04", + "date": "2026-06-18", + "summary": "新增 storage.entry.bindReceivingDetails 接口和 wms_entry_receiving_binding 中间表:入库单明细可显式绑定收货明细(pending状态),提交入库时事务内完成双向扣减(stored_quantity/received_quantity),通过唯一约束和行锁防止超分和重复绑定。同时重构 completeEntry 调用链为 commitEntryWithBindings,无绑定时向后兼容。", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "新增 storage.entry.bindReceivingDetails 方法:入库单明细绑定收货明细,pending 状态软绑定,每次调用清除旧 pending 绑定后创建新绑定。", + "新增 wms_entry_receiving_binding 中间表(migration: 20260618150000-create-wms-entry-receiving-binding.js),用于记录入库明细与收货明细的绑定关系。", + "重构 completeEntry 调用链:systemMethods 层 completeEntry 改为调用 commitEntryWithBindings,有绑定则事务内完成双向扣减(stored_quantity/received_quantity),无绑定时向后兼容仅变更入库单状态。", + "通过数据库唯一约束和行锁(SELECT ... FOR UPDATE)防止超分和重复绑定。", + "涉及文件: app/model/entry_receiving_binding.js, app/service/systems/storage/entry.js, app/service/systemMethods/storage/entry.js, database/migrations/20260618150000-create-wms-entry-receiving-binding.js" + ], + "type": "added", + "module": "storage.entry" + }, + { + "version": "2026.06.18-system-05", + "date": "2026-06-18", + "summary": "storage.entry.get 响应追加 pending_total/total_planned/bindings 字段,storage.receiving.getAvailableInboundQuantity 响应追加 pending_allocated_quantity 字段:前端可通过 get 查看入库明细的绑定状态,getAvailableInboundQuantity 的可用量已扣除全局 pending 绑定总量", + "methods": [ + "storage.entry.get", + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "storage.entry.get:items 数组每项新增 pending_total(该入库明细当前 pending 绑定的总预分配数量)、total_planned(计划入库数量=count)、bindings(pending 绑定列表,每项含 id/entry_item_id/receiving_detail_id/allocated_quantity/status/receivingDetail 子对象)", + "storage.receiving.getAvailableInboundQuantity:list 每项新增 pending_allocated_quantity(该收货明细在当前 stock_id 所有入库单中的 pending 绑定总量),available_quantity 计算已扣除该值" + ], + "type": "updated" + }, + { + "version": "2026.06.18-system-06", + "date": "2026-06-18", + "summary": "bindReceivingDetails 重构为\"绑定即实收\"(received_quantity 在绑定时更新,不再等到 completeEntry),新增 unbindReceivingDetails 解绑接口(删除 pending 绑定并回退 received_quantity),commitEntryWithBindings 移除 received_quantity 更新逻辑", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails:改为绑定即实收,绑定成功后立即更新入库明细 received_quantity;重复调用时先回退旧绑定量再创建新绑定,避免重复累加。", + "storage.entry.unbindReceivingDetails:新增解绑接口,删除该入库明细的所有 pending 绑定记录,并将 received_quantity 回退到绑定前的值;收货明细可用数量随绑定记录删除自动恢复。", + "storage.entry.completeEntry:commitEntryWithBindings 中移除 received_quantity 更新逻辑(received_quantity 已在绑定时更新,completeEntry 仅完成收货单侧入库数量扣减和库存上架)。" + ], + "type": "updated" + }, + { + "version": "2026.06.19-system-01", + "date": "2026-06-19", + "summary": "order.recheckOrder.scanOrder 响应 list[] 新增 items_weight(订单商品总重量g)和 suggested_package_material(推荐包材)字段", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "响应 list 每项新增 items_weight (number|null):订单商品总重量(g),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量,为 null 时返回 0)。", + "响应 list 每项新增 suggested_package_material (object|null):推荐包材信息,根据订单商品结构(items_hash + items_crc)匹配 wms_package_material_item_relation 历史绑定记录,按 bind_count 降序取最优匹配。若 items_hash 为空或无匹配记录则为 null。包含子字段:id、code、name、spec、type、weight、length、width、height、bind_count。", + "同步更新 method description 和 list 字段 description,补充新增字段的说明。" + ], + "type": "updated", + "module": "order.recheckOrder" + }, + { + "version": "2026.06.21-system-01", + "date": "2026-06-21", + "summary": "order.bindExpressPackageMaterialByWaybill:入参 package_material_code 改为 package_material_id,类型由 string 改为 number|string", + "methods": [ + "order.bindExpressPackageMaterialByWaybill" + ], + "notes": [ + "入参字段名从 package_material_code 改为 package_material_id。", + "入参类型从 string 改为 number|string,与代码 normalizePackageMaterialId 的实现一致。", + "同步更新该方法 description 中'包材编码'为'包材ID'。" + ], + "type": "updated", + "module": "order" + }, + { + "version": "2026.06.21-system-comboGoods-01", + "date": "2026-06-21", + "summary": "新增 comboGoods 组合商品模块 5 个接口文档:list/create/update/delete/search", + "methods": [ + "comboGoods.list", + "comboGoods.create", + "comboGoods.update", + "comboGoods.delete", + "comboGoods.search" + ], + "notes": [ + "comboGoods.list:组合商品列表查询(分页),支持按 combo_code/combo_name/status/warehouse_id 筛选,返回含 simpleNotation 和 nameNotation 简记字段", + "comboGoods.create:创建组合商品(含明细一次性提交),校验 combo_code 唯一性、子商品有效性和货主一致性,事务保证原子写入", + "comboGoods.update:编辑组合商品(含明细替换),支持部分字段更新,传入 items 则先删旧明细再插入新明细", + "comboGoods.delete:软删除组合商品(status 置为 0)", + "comboGoods.search:关键字搜索组合商品,模糊匹配 combo_code 或 combo_name,仅返回启用状态记录,上限100条", + "数据表:wms_combo_goods(主表)+ wms_combo_goods_item(明细表);子商品校验依赖 wms_stock_warehouse 表", + "代码文件:app/service/systems/comboGoods.js(业务逻辑层)+ app/service/systemMethods/comboGoods.js(接口包装层)", + "isNeedAuth:list/search 无需鉴权,create/update/delete 需要鉴权" + ], + "type": "added", + "module": "comboGoods" + }, + { + "version": "2026.06.21-system-comboGoods-02", + "date": "2026-06-21", + "summary": "comboGoods 模块新增 custom_code(自定义编码)功能:create/update 支持传入 custom_code 并校验按货主唯一,list/search 返回新增 custom_code 字段,search 搜索范围扩展至 custom_code 且优先排列匹配项", + "methods": [ + "comboGoods.list", + "comboGoods.create", + "comboGoods.update", + "comboGoods.search" + ], + "notes": [ + "新增字段 custom_code(VARCHAR(64) NULL),仅做按货主唯一性校验(排除已删除记录),非全局唯一。", + "wms_combo_goods 表新增索引 uk_store_custom_code(warehouse_id, custom_code)。", + "comboGoods.create:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique;返回新增 custom_code 字段。", + "comboGoods.update:新增可选入参 custom_code,如果非空则校验同货主非删除记录中 unique(排除自身 id)。", + "comboGoods.list:返回每条记录新增 custom_code 字段。", + "comboGoods.search:搜索条件扩大为 custom_code LIKE / combo_code LIKE / combo_name LIKE,custom_code 匹配项按 ORDER BY CASE 排在前面;返回新增 custom_code 字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.21-system-comboGoods-03", + "date": "2026-06-21", + "summary": "stock.warehouse.search 新增 mode=\"combo\" 组合商品查询模式,新增 id/custom_code 参数,补充组合商品响应结构", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "新增入参 mode(查询模式,传 \"combo\" 时搜索组合商品),id(mode=combo 时按组合商品ID精确查询),custom_code(mode=combo 时按自定义编码模糊查询)", + "原有 keyword 参数在 mode=combo 时模糊匹配 combo_code / combo_name / custom_code", + "mode=combo 响应结构新增 combo_code、combo_name、custom_code、items(子商品数组含 item_goods_sku_id/item_quantity)、simpleNotation(stock_id|数量格式)、nameNotation(【数量】商品名称格式)", + "mode=combo 时不返回 stock 模式特有的字段(item_code/goods_code/item_name/sku_property/stock_unit/quantity/locked_quantity/brand_name/item_type/barcodes/store_stock/效期字段/storage)", + "with_stock 和 is_batch 参数在 mode=combo 时不生效" + ], + "type": "updated" + }, + { + "version": "2026.06.22-system-wavePickTaskList-01", + "date": "2026-06-22", + "summary": "order.wave.wavePickTaskList 响应新增 wave_list 数组:每个拣货任务返回关联波次列表", + "methods": [ + "order.wave.wavePickTaskList" + ], + "notes": [ + "wavePickTaskList 响应 list 每项新增 wave_list 数组字段,通过批量查询 wms_wave_pick_task_wave 表获取关联波次详情。", + "wave_list 每项包含:wave_id(波次ID)、wave_no(波次号)、box_no(框号)、status(波次关联状态)、bind_time(绑定时间)、pick_time(拣货完成时间)。", + "无需额外入参,默认对所有拣货任务返回 wave_list;查询为空时返回空数组 []。", + "同步更新 methods/system.json 响应文档。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.22-system-order-export-mode-01", + "date": "2026-06-22", + "summary": "order.export 新增 export_mode 参数:支持 waybill(默认,按运单展开)与 item(按商品明细展开)两种导出模式", + "methods": [ + "order.export" + ], + "notes": [ + "新增入参 export_mode/exportMode,枚举值:waybill(默认)— 按运单号展开,每运单一组,items_detail 列汇总商品;item — 按商品明细展开,每商品一行,运单信息汇总填充。", + "方法层(OrderIndexService.export)新增 export_mode/exportMode 解构并透传到 systems.orderExport.exportOrders。", + "同步更新 methods/system.json 文档:description 补充 export_mode 说明,params 新增 export_mode/exportMode 条目。", + "order.export 导出的列新增:业务类型、运单接口、包材ID、包材编码、包材名称。" + ], + "type": "updated", + "module": "order.index" + }, + { + "version": "2026.06.22-system-directInbound-01", + "date": "2026-06-22", + "summary": "新增 storage.directInbound 导入/PDA直接入库模块:getItems(获取入库信息)、addItem(增量添加商品)、commit(提交完成入库并回传)", + "methods": [ + "storage.directInbound.getItems", + "storage.directInbound.addItem", + "storage.directInbound.commit" + ], + "notes": [ + "新增 storage.directInbound 模块,用于非收货单途径的导入/PDA 直接入库场景。", + "storage.directInbound.getItems:根据入库单号获取入库明细及已有的导入/PDA 入库记录,返回每项的可入库余量。", + "storage.directInbound.addItem:按 stock_id 增量添加导入/PDA 入库记录,累加超过该 stock_id 在入库单中的计划总量时拒绝。支持 import(导入)和 pda(PDA)两种方式。", + "storage.directInbound.commit:提交确认完成入库,按实收数量写入 wms_storage 库存和 wms_storage_transaction 流水,同 stock_id 多条明细只写一次库存,更新入库单状态为 COMPLETED 并同步 sync_status=SUCCESS,异步触发奇门/API 回传(按实收数量回传)。不足量提交时未入库商品跳过。", + "新增数据表 wms_inbound_direct_log(migration: 20260622100000-create-wms-inbound-direct-log.js):记录非收货单途径入库操作,含 warehouse_id、stock_id、quantity、inbound_type(import/pda)、entry_order_id、operator 等字段。模型文件:app/model/inbound_direct_log.js。", + "新增操作日志:addItem 记录 DIRECT_INBOUND_ADD(异步),commit 记录 DIRECT_INBOUND_COMMIT(事务内)。commit 响应返回 order_status=COMPLETED 和 sync_status=SUCCESS。", + "涉及文件:app/service/systems/inbound_direct_log.js(业务层)、app/service/systemMethods/storage/direct_inbound.js(包装层)、app/model/inbound_direct_log.js、database/migrations/20260622100000-create-wms-inbound-direct-log.js、methods/system.json(新增导入/PDA入库模块)。", + "E2E 测试:test/e2e_direct_inbound.test.js(53项断言全覆盖)。" + ], + "type": "added", + "module": "storage.directInbound" + }, + { + "version": "2026.06.22-system-directInbound-02", + "date": "2026-06-22", + "summary": "storage.directInbound.addItem 新增批量模式(items 数组),getItems 响应 summary 新增 total_import/total_pda 分类型汇总", + "methods": [ + "storage.directInbound.addItem", + "storage.directInbound.getItems" + ], + "notes": [ + "addItem 新增批量模式:支持传入 items 数组一次添加多条商品,每项含 stock_id/quantity/inbound_type/remark。单条模式(stock_id/quantity/inbound_type 顶层字段)保持向后兼容。批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。", + "addItem 批量模式响应结构:{ count, total_quantity, items: [...] },items 每项含 id/stock_id/quantity/inbound_type/plan_quantity/existing_before/existing_after/remaining。", + "getItems 响应 summary 新增 total_import(导入入库总数)和 total_pda(PDA入库总数)字段。", + "同步更新 methods/system.json 文档。" + ], + "type": "updated", + "module": "storage.directInbound" + }, + { + "version": "2026.06.22-system-directInbound-03", + "date": "2026-06-22", + "summary": "storage.directInbound 新增 space_id 库位支持:addItem 支持传入 space_id(单条和批量),commit 从入库记录取 space_id 写入 wms_storage 替代硬编码 1", + "methods": [ + "storage.directInbound.addItem", + "storage.directInbound.commit", + "storage.directInbound.getItems" + ], + "notes": [ + "addItem 新增可选入参 space_id(单条模式顶层字段 / 批量模式 items[].space_id),指定存放库位ID,关联 wms_location_space.id。", + "wms_inbound_direct_log 表新增 space_id 字段(migration: 20260622110000-add-space-id-to-wms-inbound-direct-log.js)。", + "commit 从入库记录中取第一个非空 space_id 写入 wms_storage,无记录时兜底使用库位 1。", + "getItems 响应中 direct_logs 每条记录包含 space_id 字段。", + "同步更新 methods/system.json 文档及模型文件。" + ], + "type": "updated", + "module": "storage.directInbound" + }, + { + "version": "2026.06.23-system-01", + "date": "2026-06-23", + "summary": "入库单(wms_entry_order)新增 CREATED 状态:order_status ENUM 从 CREATING/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 扩展为 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED;默认值从 PENDING 变更为 CREATED;validTransitions 增加 CREATED 节点(CREATED→PENDING/CANCELLED,CREATING→CREATED/CANCELLED)", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "Model 层:app/model/entry_order.js order_status ENUM 新增 CREATED,默认值从 PENDING 变更为 CREATED", + "Service 层:app/service/systems/entry_order.js addOrder 创建后状态从 CREATING→CREATED,validTransitions 增加 CREATED 节点", + "Service 层:app/service/systems/storage/entry.js createEntry 默认状态 PENDING→CREATED", + "Service 层:app/service/systems/storage/inventory.js 快捷入库默认 CREATED", + "文档同步:storage.entry.list where.order_status 枚举补充 CREATED;storage.entry.get description 补充 order_status 枚举含 CREATED;storage.entry.cancel 补充 CREATED 可作废说明;storage.entry.completeEntry/bindReceivingDetails 补充可操作状态含 CREATED" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-02", + "date": "2026-06-23", + "summary": "入库单 CREATED 状态限制:CREATED 状态不允许绑定货物和完成入库,仅 PENDING/CONFIRMED/PARTIAL_RECEIVED 状态可操作", + "methods": [ + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "completeEntry / bindReceivingDetails / unbindReceivingDetails / commitEntryWithBindings 的可操作状态从原来的白名单(包含 CREATED)改为 PENDING / CONFIRMED / PARTIAL_RECEIVED,排除 CREATED。", + "CREATED 状态仅允许确认入库(→PENDING)或作废(→CANCELLED)。", + "storage.entry.cancel 补充明确 COMPLETED 状态不可作废,CREATED 可作废。", + "同步更新对应 method 的 description、errors 描述。" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-03", + "date": "2026-06-23", + "summary": "storage.entry.cancel:CONFIRMED(已确认)状态不再允许作废,仅 CREATED 和 PENDING 可作废", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "canCancel() 白名单移除 CONFIRMED,仅保留 CREATED 和 PENDING", + "validTransitions 中 CONFIRMED 不再可转为 CANCELLED", + "cancel() 方法新增 CONFIRMED 状态拦截,返回 400:已确认入库单不允许作废,请先完成收货", + "PARTIAL_RECEIVED 仍可作废,COMPLETED 不允许作废(行为不变)", + "更新 description 明确各状态可作废规则,errors 中补充 CONFIRMED 不可作废的说明" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.23-system-04", + "date": "2026-06-23", + "summary": "入库单状态从 7 个简化为 5 个:移除 CONFIRMED 和 PARTIAL_RECEIVED,最终状态为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED;同步更新 storage.entry 所有 method 的状态枚举和错误信息描述", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "wms_entry_order.order_status ENUM 从 CREATING/CREATED/PENDING/CONFIRMED/PARTIAL_RECEIVED/COMPLETED/CANCELLED 简化为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED", + "storage.entry.list: where.order_status 描述和 where 参数描述中的状态枚举同步更新", + "storage.entry.get: entryOrder.order_status 描述同步更新", + "storage.entry.cancel: 移除 PARTIAL_RECEIVED 可作废和 CONFIRMED 不可作废的描述,仅保留 CREATED 和 PENDING 可作废,COMPLETED 不可作废", + "storage.entry.completeEntry: 可完成状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "storage.entry.bindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "storage.entry.unbindReceivingDetails: 可操作状态从 PENDING/CONFIRMED/PARTIAL_RECEIVED 改为仅 PENDING", + "cancel() 取消 CONFIRMED 状态拦截(状态已不存在),COMPLETED 拦截保持不变" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-05", + "date": "2026-06-23", + "summary": "入库单状态语义调整:CREATED=已创建待审核,PENDING=已审核;同步更新 storage.entry 所有 method 的 description 中状态说明", + "methods": [ + "storage.entry.list", + "storage.entry.get", + "storage.entry.cancel", + "storage.entry.completeEntry", + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails" + ], + "notes": [ + "CREATED 含义从\"已创建\"改为\"已创建待审核\"(需审核后才能绑定和完成入库)", + "PENDING 含义从\"待收货/收货中\"改为\"已审核\"(审核通过,可绑定和完成入库)", + "CREATED→PENDING 步骤语义:绑定审核", + "addOrder() 新增可选参数 autoReview(boolean,默认 false),false 创建后状态 CREATED(需审核),true 创建后状态 PENDING(自动审核通过)", + "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,对外返回格式不变", + "storage.entry.list / storage.entry.get description 中补充 CREATED/PENDING 语义说明", + "storage.entry.cancel description 中补充可作废状态说明", + "storage.entry.completeEntry description 中补充可完成状态说明", + "storage.entry.bindReceivingDetails / storage.entry.unbindReceivingDetails description 中补充可绑定/解绑状态说明" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-06", + "date": "2026-06-23", + "summary": "storage.inventory.quickPutaway description 更新:补充内部已改为走 addOrder→bind→commit 链路,不再直接写库存", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "快捷入库 quickPutaway 内部流程改为调用 addOrder({autoReview:true}) → bindReceivingDetails → commitEntryWithBindings,不再直接写库存,外部返回格式不变", + "description 中补充内部调用链路说明" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-07", + "date": "2026-06-23", + "summary": "storage.entry 大范围清理:删除 bindReceivingDetails/unbindReceivingDetails(明细级绑定已弃用),更新 completeEntry 为纯状态变更(不再做库存写入/异步匹配)", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。库存写入统一由 storage.inventory.matchPutaway 完成。", + "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", + "storage.entry.completeEntry:改为纯状态变更(PENDING → COMPLETED),不再做库存写入和异步匹配回调。库存写入统一由 storage.inventory.matchPutaway 完成。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-08", + "date": "2026-06-23", + "summary": "storage.inventory 清理:删除 quickPutaway(快捷入库已下线,统一由 matchPutaway 完成匹配入库)", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "storage.inventory.quickPutaway:已从代码中删除,快捷入库功能下线。请使用 storage.inventory.matchPutaway 替代。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-09", + "date": "2026-06-23", + "summary": "入库流程弃用清理:bindReceivingDetails/unbindReceivingDetails 标记为已删除并补充弃用原因,completeEntry 明确不涉及库存写入", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.entry.completeEntry" + ], + "notes": [ + "storage.entry.bindReceivingDetails 与 storage.entry.unbindReceivingDetails 已从代码中移除,入库单与收货单关系改为 wms_entry_order_receiving 主表级关联,不再需要逐明细绑定/解绑。", + "wms_entry_receiving_binding 表不再写入新数据。", + "storage.entry.completeEntry 仅做状态变更(PENDING→COMPLETED),库存写入统一由 storage.inventory.matchPutaway 完成。", + "commitEntryWithBindings(内部方法)不再使用,库存写入统一走 matchPutaway 链路。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-10", + "date": "2026-06-23", + "summary": "quickPutaway 弃用说明完善:明确替代方案为 matchPutaway;matchPutaway 标明为目前唯一库存写入入库链路", + "methods": [ + "storage.inventory.quickPutaway", + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.inventory.quickPutaway 已从代码中移除,替代方案为 storage.inventory.matchPutaway(支持多收货单+多入库单批量匹配入库)。", + "storage.inventory.matchPutaway 是目前唯一的库存写入入库链路,入库单状态变更由 storage.entry.completeEntry 单独处理。", + "本次为文档补充说明,不涉及代码变更。" + ], + "type": "updated" + }, + { + "version": "2026.06.23-system-11", + "date": "2026-06-23", + "summary": "删除 storage.receiving.getAvailableInboundQuantity:该方法依赖已弃用的 wms_entry_receiving_binding 明细绑定表,已从代码中移除", + "methods": [ + "storage.receiving.getAvailableInboundQuantity" + ], + "notes": [ + "该方法原用于按 stock_id 查询已审核收货单中各明细的可入库数量(actual_quantity - stored_quantity - pending_allocated_quantity)。", + "由于 wms_entry_receiving_binding 明细绑定表已弃用,入库单与收货单的关联改为通过 wms_entry_order_receiving 主表级关联,该查询方法不再适用。", + "替代方案:使用 storage.entry.get 查询入库单详情,通过顶层 receivingBindings 获取关联的收货单信息。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-12", + "date": "2026-06-23", + "summary": "storage.entry.get 响应结构变更:不再返回 items[].bindings(明细级绑定),改为返回顶层 receivingBindings(主表级关联收货单信息)", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "移除 items[].bindings(明细级绑定,原基于 wms_entry_receiving_binding 表),该绑定表已弃用。", + "新增顶层 receivingBindings(wms_entry_order_receiving 主表级关联),每项含 id/receiving_id/receiving(含 id/receiving_number/status/storage_status/created_at)。", + "items 中保留 external_item_code/external_item_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec 等扁平化字段。", + "响应结构变更与 storage.directInbound.getItems 的返回结构对齐,后者同样使用顶层 receivingBindings。" + ], + "type": "modified" + }, + { + "version": "2026.06.23-system-13", + "date": "2026-06-23", + "summary": "新增 storage.entry.* 下 4 个 DirectInbound 方法:getDirectInboundItems、addItem、commit、removeItem,原 storage.directInbound.* 方法保留向后兼容并标记 deprecated", + "methods": [ + "storage.entry.getDirectInboundItems", + "storage.entry.addItem", + "storage.entry.commit", + "storage.entry.removeItem" + ], + "notes": [ + "storage.entry.getDirectInboundItems:获取入库单的导入/PDA 入库信息,参数与响应格式同原 storage.directInbound.getItems", + "storage.entry.addItem:按商品增量添加导入/PDA 入库记录(支持单条和批量),参数与响应格式同原 storage.directInbound.addItem", + "storage.entry.commit:提交确认完成导入/PDA 入库,按实收数量写入库存并异步回传奇门/API,参数与响应格式同原 storage.directInbound.commit", + "storage.entry.removeItem:移除一条导入/PDA 入库记录,参数与响应格式同原 storage.directInbound.removeItem", + "底层 inbound_direct_log.js 实现不变,仅入口从 storage.directInbound 模块迁入 storage.entry 模块" + ], + "type": "added" + }, + { + "version": "2026.06.23-system-14", + "date": "2026-06-23", + "summary": "storage.directInbound.* 下 4 个方法标记 deprecated,指向 storage.entry.* 下对应新方法", + "methods": [ + "storage.directInbound.getItems", + "storage.directInbound.addItem", + "storage.directInbound.commit", + "storage.directInbound.removeItem" + ], + "notes": [ + "storage.directInbound.getItems → 替代方法 storage.entry.getDirectInboundItems", + "storage.directInbound.addItem → 替代方法 storage.entry.addItem", + "storage.directInbound.commit → 替代方法 storage.entry.commit", + "storage.directInbound.removeItem → 替代方法 storage.entry.removeItem", + "旧方法保留向后兼容,参数与响应格式不变,仅入口模块变更" + ], + "type": "deprecated" + }, + { + "version": "2026.06.23-system-15", + "date": "2026-06-23", + "summary": "storage.inventory.matchPutaway 标记 deprecated,替代方案为 storage.entry.commit", + "methods": [ + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.inventory.matchPutaway 已弃用,请迁移至 storage.entry.commit", + "commit 提供导入/PDA 入库完成确认功能,按实收数量写入库存并异步回传" + ], + "type": "deprecated" + }, + { + "version": "2026.06.23-system-16", + "date": "2026-06-23", + "summary": "清理已弃用 method 条目:从 system.json 删除 storage.entry.bindReceivingDetails、storage.entry.unbindReceivingDetails、storage.inventory.matchPutaway 三个已从代码中移除的 method 文档条目", + "methods": [ + "storage.entry.bindReceivingDetails", + "storage.entry.unbindReceivingDetails", + "storage.inventory.matchPutaway" + ], + "notes": [ + "storage.entry.bindReceivingDetails:已从代码中删除,明细级绑定收货单功能下线。入库单与收货单关系改为 wms_entry_order_receiving 主表级关联。", + "storage.entry.unbindReceivingDetails:已从代码中删除,明细级解绑功能下线。", + "storage.inventory.matchPutaway:已从代码中删除,匹配入库功能下线。替代方案为 storage.entry.commit。", + "storage.inventory.quickPutaway:之前已标记 [已删除],本次确认条目保留(与 matchPutaway 同一 group,保留作为历史参考)。", + "storage.entry.create / addDetail / deleteDetail / detailChange:systems 层方法已删除,但从未在 system.json 中暴露为 API method,无需文档变更。" + ], + "type": "removed" + }, + { + "version": "2026.06.23-system-17", + "date": "2026-06-23", + "summary": "storage.entry.get 响应新增仓库库存、条码、入库进度字段", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "items 每项新增 warehouse_quantity(仓库库存总量)、warehouse_locked_quantity(锁定数量)、warehouse_is_batch_mgmt(是否批次管理)、warehouse_is_shelf_life_mgmt(是否效期管理)、warehouse_image_url(商品图片URL)、warehouse_is_images(是否有图片)", + "items 每项新增 barcodes(条码列表,每项含 id/barcode/sku_property)", + "items 每项新增 direct_inbound_quantity(导入/PDA已入库数量)、remaining_quantity(剩余可入库数量)", + "同步更新 response 字段定义,将原有概要描述展开为逐字段说明", + "仅文档同步,不改业务代码" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.24-system-01", + "date": "2026-06-24", + "summary": "新增批量绑定入库单明细与收货单明细接口 storage.entry.bindReceivingDetails,支持明细级数量分配与部分成功", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "新增 storage.entry.bindReceivingDetails:批量绑定入库单明细与收货单明细,支持明细级数量分配与部分成功", + "storage.entry.get 追加 available_receiving_details 字段加载可匹配的收货单明细" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-02", + "date": "2026-06-24", + "summary": "storage.entry.bindReceivingDetails:response.failed 字段从简单 reason 描述升级为结构化错误返回(含 error_code、message、detail);同步更新 400 错误说明", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "response.failed 新增 items 定义,每项含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", + "error_code 枚举:ENTRY_ITEM_NOT_FOUND、STOCK_NOT_FOUND、RECEIVING_DETAIL_MISMATCH、RECEIVING_DETAIL_NOT_FOUND、INSUFFICIENT_AVAILABLE_QUANTITY、ENTRY_ORDER_STATUS_INVALID", + "400 错误说明更新:入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-03", + "date": "2026-06-24", + "summary": "新增 storage.entry.quickInbound 快捷直入/虚拟入库接口", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "新增 quickInbound 方法:入库单所有商品按明细数量一键直入虚拟库位(space_id=2),跳过收货/质检流程", + "支持状态:CREATED、PENDING 状态的入库单可执行", + "拒绝状态:CANCELLED(已作废)、COMPLETED(已完成)", + "事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED", + "事务外异步回传奇门/API" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-04", + "date": "2026-06-24", + "summary": "收窄 storage.entry.quickInbound 状态约束:仅允许 CREATED 状态执行快捷直入", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "收窄状态约束:仅允许 CREATED 状态执行快捷直入,PENDING 状态不再允许" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-05", + "date": "2026-06-24", + "summary": "修正 storage.entry.quickInbound errors[4] message 以匹配代码实现:改为动态状态描述", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "errors[4].message 从「入库单状态不允许快捷直入(仅支持CREATED状态)」改为「入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)」,反映代码中 `${entryOrder.order_status}` 动态模板特性" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-06", + "date": "2026-06-24", + "summary": "新增入库单与收货单商品对照预览接口", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "新增 storage.entry.receivingCompare 方法:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图。", + "comparison 列表中每项含 match_status(matched/entry_only),以及入库侧和收货侧的商品与数量信息。", + "receiving_only 列表包含仅存在于收货单中的商品明细。", + "summary 提供 total_entry_items、matched_items、entry_only_items、receiving_only_items 汇总统计。", + "纯只读接口,不产生任何数据写入或状态变更。" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-07", + "date": "2026-06-24", + "summary": "setting.warehouse 模块新增 7 个发件人信息字段到 subject_config", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 getSettings 的 response 中新增 subject_config.sender_name(发件人姓名)、sender_tel(发件人电话)、province_name(省份)、city_name(城市)、district_name(区/县)、town_name(镇/街道)、address(详细地址)共 7 个字段,均为可选字符串,默认空。", + "在 saveSettings 的 params 中新增对应的 7 个入参字段,source 为 body.subject_config,均为可选字符串,默认空,并标注 maxLength。", + "字段 key 与 store_warehouse.policy_config 中发件人字段命名完全一致,统一仓库级发件人默认值配置。", + "getFieldMeta 接口无需修改文档——其返回的字段元信息由 WAREHOUSE_SETTING_FIELDS 定义在运行时自动生成,新增字段会随代码自动纳入返回列表。" + ], + "type": "updated", + "module": "setting.warehouse" + }, + { + "version": "2026.06.25-system-01", + "date": "2026-06-25", + "summary": "新增 storage.entry.bindReceiving 接口:将收货单绑定到入库单(主表级关联,不做明细数量分配)", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "新增入库单与收货单的主表绑定接口,与已有的 storage.entry.bindReceivingDetails(明细级绑定)区分:bindReceiving 仅建立 wms_entry_order_receiving 主表关联,不做明细数量分配。", + "入库单需为 CREATED 或 PENDING 状态;收货单需存在、同仓库且未取消。", + "支持部分成功模式:逐条校验收货单,校验通过的建立绑定,不通过的返回 error_code 和 message。", + "响应包含 success(成功列表)、failed(失败列表)、success_count、failed_count。" + ], + "type": "addition" + }, + { + "version": "2026.06.25-system-02", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增 OWNER_MISMATCH 错误码,用于收货单与入库单货主不一致校验", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 storage.entry.bindReceiving 的 errors 数组中新增 OWNER_MISMATCH(收货单与入库单货主不一致)错误码。", + "同步更新 response.failed.error_code 的枚举描述,补充 OWNER_MISMATCH。" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.25-system-03", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增收货单未审核错误码 RECEIVING_NOT_REVIEWED", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 errors 数组中新增错误码 RECEIVING_NOT_REVIEWED(收货单未审核),用于标识绑定前收货单尚未完成审核的场景。", + "同步更新 response.failed.items.properties.error_code.description,在可能值列表中补充 RECEIVING_NOT_REVIEWED。" + ], + "type": "updated" + }, + { + "version": "2026.06.25-system-04", + "date": "2026-06-25", + "summary": "storage.entry.list 响应新增 receivingBindings 和 hasReceiving 字段,where 新增 hasReceiving 虚拟筛选条件", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "响应 list 数组每项新增 receivingBindings(收货单绑定列表,主表级关联)和 hasReceiving(是否存在收货单绑定,boolean)字段。", + "入参 where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单,内部通过 wms_entry_order_receiving 表查询实现。", + "同步更新 description 以说明 hasReceiving 虚拟筛选的使用方式。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-01", + "date": "2026-06-26", + "summary": "storage.entry.receivingCompare 支持多收货单对照预览", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "支持多个收货单ID对照预览(新增 receiving_ids 数组入参,优先于 receiving_id 使用)", + "入参 receiving_id 从 required 改为 optional,与 receiving_ids 二选一", + "出参结构调整为 comparisons[] 数组(多收货单),新增 errors[] 和 total_summary", + "向后兼容原 receiving_id 单值传参(底层自动转为单元素数组)", + "新增 400 错误码:receiving_ids 或 receiving_id 必填", + "移除 404 错误码:收货单不存在(已改为在 comparisons[]/errors[] 中以 status=error 形式返回)" + ], + "type": "enhancement" + }, + { + "version": "2026.06.26-system-02", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList 新增 filterDepleted 可选参数;storage.entry.receivingCompare 返回值 receiving_only 字段新增 receiving_allocated 和 receiving_available 说明", + "methods": [ + "storage.receiving.getReceivingList", + "storage.entry.receivingCompare" + ], + "notes": [ + "storage.receiving.getReceivingList:params 新增 filterDepleted(boolean, 默认 false),用于过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。", + "storage.entry.receivingCompare:response 中 receiving_only 字段的 description 补充 receiving_allocated(已分配数量)和 receiving_available(可再用量)两个子字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-03", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList:新增可选参数 entry_order_id,按入库单商品交集过滤收货单列表", + "methods": [ + "storage.receiving.getReceivingList" + ], + "notes": [ + "新增可选参数 entry_order_id(number),传入入库单 ID 后只返回至少有一条明细的 system_product_id 在入库单明细中存在的收货单。", + "与现有 filterDepleted 参数可组合使用,二者取交集。", + "不传则不过滤,保持原有行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.06.27-system-01", + "date": "2026-06-27", + "summary": "新增 storage.entry.reviewEntry 接口:审核入库单(CREATED→PENDING),需绑定收货单", + "methods": [ + "storage.entry.reviewEntry" + ], + "notes": [ + "新增入库单审核接口,支持 CREATED→PENDING 状态流转。", + "审核前置条件:入库单必须已绑定收货单(EntryOrderReceiving 存在关联记录)。", + "审核通过后写入操作日志(ENTRY_ORDER_REVIEW)。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-01", + "date": "2026-06-29", + "summary": "storage.inventory.quickPutaway 重新实现:收货单快捷转入库单", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "此前已从代码中删除(2026.06.23-system-08),现由 wms-dev-agent 重新实现。", + "核心流程:参数校验 → 加载收货单及明细 → 检查货主配置 policy_config.allow_receiving_quick_putaway → 按 stock_id(system_product_id)分组合并数量 → 创建入库单 SCRK(自动审批到 PENDING)→ 写入 wms_entry_order_receiving 主表级绑定 → 更新收货单 storage_status 为 partial → 更新收货单明细 storage_status/stored_quantity → 提交事务。", + "前置条件:收货单状态为 completed 且 is_review=true(已审核),货主仓库签约配置 allow_receiving_quick_putaway=1。", + "与旧实现的区别:不涉及 wms_entry_receiving_binding 明细级绑定,使用 wms_entry_order_receiving 主表级关联;直接创建入库单并写入绑定,不再走 matchPutaway 匹配链路。", + "返回:entry_order_id、entry_order_code(SCRK 格式)、order_status(PENDING)、receiving_id、total_lines、total_quantity。" + ], + "type": "addition" + }, + { + "version": "2026.06.29-system-02", + "date": "2026-06-29", + "summary": "storage.entry.list:quickWhere 搜索范围扩展,新增收货单 ID(receiving_id)支持 PDA 扫描托盘唛头搜索绑定的入库单", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "quickWhere 搜索字段新增 receiving_id(收货单 ID / 托盘唛头),通过 wms_entry_order_receiving 绑定表关联搜索。", + "同步更新 description 和 where 参数的 description,明确 quickWhere 完整搜索字段列表:entry_order_code、purchase_order_code、supplier_name、store_name、warehouse_name、receiving_id。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.06.29-system-03", + "date": "2026-06-29", + "summary": "新增 storage.receiving.scanDetail 接口:PDA 上架扫码定位收货明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "新增 storage.receiving.scanDetail(PDA专用):通过 entry_order_id + barcode 扫码快速定位收货明细。", + "搜索逻辑:纯数字 barcode 优先按明细 ID 精确匹配(托盘唛头),未命中则模糊匹配商品条码;非纯数字仅模糊匹配商品条码。", + "入参:entry_order_id(必填 number)、barcode(必填 string)。", + "出参:detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status。", + "错误码:入库单不存在或无权访问、该入库单尚未关联收货单、未找到匹配的收货明细。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-04", + "date": "2026-06-29", + "summary": "storage.receiving.scanDetail 响应结构从单条改为列表:返回 { list, total } 支持同一条码匹配多条明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应结构变更:原返回 data.detail_id/data.receiving_id 等单条字段,现改为顶层 list 数组 + total 计数。", + "同一条码可能匹配到多条收货明细(不同收货单的同一商品),以列表形式返回所有匹配结果。", + "list 中每条明细包含 detail_id/receiving_id/barcode/product_name/actual_quantity/receiving_status。", + "补充错误码:用户未绑定仓库、入库单ID/条码为空、未找到可用的收货明细、500服务器错误。", + "PDA专用接口,description 更新说明匹配逻辑。" + ], + "type": "updated", + "module": "storage.receiving" + }, + { + "version": "2026.06.30-system-01", + "date": "2026-06-30", + "summary": "新增 storage.entry.containerList:PDA 上架时拉取入库单绑定收货单中指定商品的可用容器列表", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "新增接口 storage.entry.containerList,用于 PDA 上架场景拉取入库单已绑定收货单中指定 stock_id 的可用收货明细(容器)列表。", + "入参:entry_order_id(入库单ID,必填)、stock_id(商品 stock_id,必填)。", + "出参:data.list 返回可用明细列表,每项含 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status;data.total 为总数。", + "已绑定占用的收货明细(wms_entry_receiving_binding 中已有记录且未软删除)会被排除。", + "PDA 专用接口,无需额外鉴权(isNeedAuth=false)。" + ], + "type": "added" + }, + { + "version": "2026.06.30-system-02", + "date": "2026-06-30", + "summary": "storage.entry.addItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填", + "methods": [ + "storage.entry.addItem" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.addItem 实现对齐", + "quantity 改为可选:传入 receiving_detail_id 时自动从收货明细计算可用数量(actual_quantity - 已绑定数量)", + "新增 receiving_detail_id 参数:PDA 上架绑定收货明细时传入,触发预占绑定(wms_entry_receiving_binding status=pending)", + "新增 allocated_quantity 参数:预分配数量,默认等于 quantity", + "space_id 在绑定模式下必填;非绑定模式可选(commit 时兜底为 1)", + "PENDING 状态入库单必须传 receiving_detail_id 且已绑定收货单方可操作", + "CREATED + 已绑定收货单的入库单需先审核(reviewEntry)后才能上架", + "批量模式 items 数组同步支持 receiving_detail_id/allocated_quantity 字段", + "补充完整错误码列表:超量、可用数量不足、状态校验等" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-03", + "date": "2026-06-30", + "summary": "storage.entry.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.entry.commit" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "补充 description 说明先同步后写库两段式流程:① 奇门/API 回传 → ② onSuccess 内事务写库存", + "补充 commit 后 EntryReceivingBinding 状态从 pending 更新为 committed 的说明" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-04", + "date": "2026-06-30", + "summary": "storage.directInbound.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.directInbound.commit" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "该方法已标记 deprecated,推荐使用 storage.entry.commit" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-05", + "date": "2026-06-30", + "summary": "storage.entry.getDirectInboundItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.entry.getDirectInboundItems" + ], + "notes": [ + "entryOrder 精简为 id / entry_order_code / order_status / store_remask 四个字段", + "items[].count → planned(计划数量),items[].direct_inbound_quantity → completed(已完成数量)", + "items[].bindings 新增,结构为 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增,返回 getStockDetails 缓存的商品详情(item_code、item_name、barcodes 等)", + "移除 direct_logs(现有响应中已不存在该顶层字段)", + "移除 summary(现有响应中已不存在该字段)", + "移除 items[].received_quantity、items[].remaining_quantity、items[].pending_binding_total 等旧字段", + "新增 receivingBindings 字段说明:入库单层级收货单绑定关系" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-06", + "date": "2026-06-30", + "summary": "storage.directInbound.getItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.directInbound.getItems" + ], + "notes": [ + "响应结构与 storage.entry.getDirectInboundItems 对齐(两者共用同一个底层实现 inboundDirectLog.getItems)", + "entryOrder 精简为 id / entry_order_code / order_status / store_remask", + "items[].count → planned,items[].direct_inbound_quantity → completed", + "items[].bindings 新增 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增", + "移除 direct_logs、summary、items[].received_quantity、items[].remaining_quantity 等旧字段", + "新增 receivingBindings 字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-07", + "date": "2026-06-30", + "summary": "storage.entry.containerList 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-08", + "date": "2026-06-30", + "summary": "storage.receiving.scanDetail 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段", + "完善 error 列表:补充 未找到可用的收货明细、未找到匹配的收货明细、入库单ID不能为空、扫描条码不能为空 等错误" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-09", + "date": "2026-06-30", + "summary": "订单列表 list 响应新增 store_remark(货主备注)字段", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "数据库字段 store_remask,返回给前端的字段名为 store_remark。", + "服务层从 wms_store_warehouse.store_remask 按 store_id+warehouse_id 聚合批量填充。", + "货主备注值可能为空字符串(当货主未设置备注时)。", + "该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。" + ], + "type": "updated" + }, + { + "version": "2026.07.02-system-02", + "date": "2026-07-02", + "summary": "新增 quick.waybill.toOrder 接口:根据运单号快速查询订单ID", + "methods": [ + "quick.waybill.toOrder" + ], + "notes": [ + "新增 quick 模块组(快捷查询)", + "查询 wms_order_express 表中 status=1 的有效记录", + "无需登录和鉴权(免登录/免鉴权)" + ], + "type": "added" + }, + { + "version": "2026.07.02-system-01", + "date": "2026-07-02", + "summary": "修正 quick.waybill.toOrder 的 isNeedLogin 为 true,与代码实现保持一致", + "methods": [ + "quick.waybill.toOrder" + ], + "notes": [ + "文档中 isNeedLogin 为 false,但代码 systemMethods/quick/waybill.js 中 _noNeedLogin 为空字符串,未将 toOrder 加入免登录列表,实际需要登录验证,修正文档以与代码一致。" + ], + "type": "fixed" + }, + { + "version": "2026.07.03-system-01", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", + "methods": [ + "storage.entry.getDirectInboundItems" + ], + "notes": [ + "bindings 数组 description 中 wms_entry_receiving_binding 引用更新为 InboundDirectLog,明确旧表已弃用", + "binding_id description 中 wms_entry_receiving_binding.id 更新为 InboundDirectLog.id", + "allocated_quantity description 中补充来源 InboundDirectLog.quantity", + "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" + ], + "type": "updated" + }, + { + "version": "2026.07.03-system-02", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:wms_entry_receiving_binding 已弃用,功能迁移到 wms_inbound_direct_log 表;bindings 描述中表引用更新为 InboundDirectLog", + "methods": [ + "storage.directInbound.getItems" + ], + "notes": [ + "bindings 数组 description 中更新为来自 InboundDirectLog,明确旧表已弃用", + "binding_id description 更新为 InboundDirectLog.id", + "allocated_quantity description 中补充来源 InboundDirectLog.quantity", + "wms_inbound_direct_log 表新增字段:entry_item_id、receiving_detail_id、status(ENUM: pending/committed/released)、updated_at、deleted_at" + ], + "type": "updated" + }, + { + "version": "2026.07.03-system-03", + "date": "2026-07-03", + "summary": "binding 表弃用文档同步:commit 描述中 EntryReceivingBinding 更新为 InboundDirectLog", + "methods": [ + "storage.entry.commit" + ], + "notes": [ + "commit description 中将 pending 状态的 EntryReceivingBinding 更新为 pending 状态的 InboundDirectLog,与代码实现一致" + ], + "type": "updated" + }, + { + "version": "2026-07-03-entry-get-params-fix", + "date": "2026-07-03", + "type": "updated", + "summary": "修正 storage.entry.get 文档:id 改为必填;移除未实现的 entry_order_code 参数;修正错误码与实际返回一致;补充 available_receiving_details 响应字段;修正 remaining_quantity 计算公式及 warehouse_image_url 实际行为", + "methods": [ + "storage.entry.get" + ], + "notes": [ + "params: 移除 entry_order_code(代码中从未使用该参数),id 从 required=false 改为 required=true", + "params: id 描述从'二选一'改为'必填'", + "errors: 400 的 message 从'参数错误:id 与 entry_order_code 至少提供一个'改为'id 参数不能为空'", + "errors: 移除不存在的 404 error,入库单不存在时实际返回 code=0, message='入库单不存在或无权访问'", + "errors: 删除不存在的 500 error", + "response: 新增 entryOrder.items[].available_receiving_details 字段及其描述", + "response: remaining_quantity 描述从 'count - received_quantity - direct_inbound_quantity' 修正为 'max(0, count - received_quantity)'", + "response: warehouse_image_url 描述从 StockWarehouse.image_url 改为'当前固定返回空字符串'", + "response: warehouse_is_images 类型从 number(0/1) 改为 string(Y/N),与 StockWarehouse.is_images 实际存储一致", + "response: warehouse_quantity/warehouse_locked_quantity/warehouse_is_batch_mgmt/warehouse_is_shelf_life_mgmt 补充无匹配时为 null 的说明", + "description: 更新描述以反映实际逻辑流程" + ] + }, + { + "version": "2026.07.03-system-04", + "date": "2026-07-03", + "type": "modified", + "summary": "order.pendingOrder.updateAddress 移除 remark(备注)修改功能,现在仅支持地址字段批量修改;备注修改已独立为 order.pendingOrder.updateRemark", + "methods": [ + "order.pendingOrder.updateAddress" + ], + "notes": [ + "移除入参 remark 参数定义项。", + "移除 remark 更新逻辑及相关描述,updateAddress 现在仅处理地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)。", + "description 更新:去掉 remark 相关描述,仅描述地址字段修改规则。", + "response updated_count 描述更新:从「取地址更新行数与备注更新行数的最大值」改为单纯描述地址更新行数。", + "errors 更新:移除 remark 相关错误说明('remark 字段不受此限制' 等),修改 '至少需要提供一个地址字段或备注进行修改' 为 '至少需要提供一个地址字段进行修改'。", + "备注修改功能已独立为 order.pendingOrder.updateRemark 方法。" + ], + "module": "order.pendingOrder" + }, + { + "version": "2026-07-16", + "date": "2026-07-16", + "summary": "新增 workbench.bindCamera 接口,支持工作台绑定/解绑摄像头", + "methods": [ + "workbench.bindCamera" + ], + "notes": [ + "通过 device_ids JSON 字段存储绑定关系", + "传空数组可解绑" + ] + }, + { + "version": "2026.07.17-stock-report-migration-01", + "date": "2026-07-17", + "type": "updated", + "summary": "storage.report 模块迁移至 stock.report:修正语义错误,库存报表属于 stock 域而非 storage 域", + "methods": [ + "stock.report.search", + "stock.report.searchStore", + "stock.report.export", + "stock.report.exportStore", + "stock.report.exportTaskProgress" + ], + "notes": [ + "将 systemMethods/storage/report.js 移动到 systemMethods/stock/report.js", + "内部引用同步更新:类名 StorageReportMethodService→StockReportMethodService,缓存键 storage_report→stock_report,日志前缀 [storage.report]→[stock.report]", + "旧文件直接删除,不保留兼容(storage.report 为语义错误,调用方需同步更新 method 名)", + "更新 systems/storage/entry.js L273 注释引用", + "文档:methods/system.json module storage.report→stock.report,5个 method 名同步更新" + ] + }, + { + "version": "2026.07.17-stock-transaction-export-01", + "date": "2026-07-17", + "type": "added", + "summary": "新增 stock.transaction 商品流水导出(仓库侧+货主侧),异步任务模式,支持与列表查询一致的条件筛选", + "methods": [ + "stock.transaction.export", + "stock.transaction.exportStore", + "stock.transaction.exportTaskProgress" + ], + "notes": [ + "systems/stock_transaction.js 新增 exportList(),复用 queryList 的查询逻辑,不分页导出 Excel(上限 50000 条)", + "systemMethods/stock/transaction.js 新增 export/exportStore/exportTaskProgress,采用异步任务模式(setImmediate + 缓存)", + "仓库侧导出自动限定 warehouse_id=ctx.user.store_id,货主侧需传 store_id", + "导出 Excel 列:序号/创建时间/流水类型/仓库ID/货主ID/商品ID/变动数量/变更前库存/变更后库存/变更前锁定/变更后锁定/批次号/单据类型/单据号/收货单ID/入库单ID/发货单ID/操作人/备注" + ] + }, + { + "version": "2026.07.29-system-01", + "date": "2026-07-29", + "type": "added", + "summary": "新增 waybill.warehouse 运单模块(仓库侧):list(列表)、detail(详情)、export(导出)3 个接口,支持运单号独立查询与管理", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export" + ], + "notes": [ + "新增 waybill.warehouse.list:仓库侧运单列表查询,支持分页与多条件筛选(运单号/主单号/订单ID/订单号/物流公司/物流接口/平台/状态/退回/拦截/星河签收/包材/称重/关键词/时间范围),默认按 create_at desc 排序。", + "新增 waybill.warehouse.detail:仓库侧运单详情查询,含关联订单信息、兄弟运单(sibling_waybills)、物流信息、状态信息、称重信息、打包信息(打包状态/打包人/打包时间)、打印记录列表。", + "新增 waybill.warehouse.export:仓库侧运单导出,复用 list 筛选逻辑,异步任务模式,支持自定义导出字段。", + "仓库隔离策略:所有接口自动注入 warehouse_id = ctx.user.store_id(全系统统一约定),不可由前端入参覆盖。", + "快照字段方案:wms_order_express 表新增 delivery_order_code、store_id_snapshot、store_name_snapshot、warehouse_name_snapshot 四个快照列,列表查询无需 JOIN 订单表或货主表,仅单表查询 + SELF JOIN(主单号)。", + "主单号/子单号规则:同一 order_id 下 business_key=1 为主单号,business_key>1 为子单号,沿用系统已有约定。", + "命名空间规划:waybill.warehouse.* 本期实现(仓库侧),后续预留 waybill.store.*(货主侧)。", + "本模块一期仅提供只读查询,不涉及运单创建/修改/删除,不修改任何现有接口。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.07.30-system-01", + "date": "2026-07-30", + "type": "changed", + "summary": "更新 waybill.warehouse group API 文档:list 新增 waybillType/storeId 筛选、移除 pack_status 响应字段;detail 精简 package 对象;export 响应改为纯异步任务模式(仅含 task_id/status/progress/message/update_time)", + "methods": [ + "waybill.warehouse.list", + "waybill.warehouse.detail", + "waybill.warehouse.export", + "waybill.warehouse.exportTaskProgress" + ], + "notes": [ + "waybill.warehouse.list:新增 where.waybillType 筛选(\"main\"/\"1\"=主单号,\"child\"/\"2\"=子单号),新增 where.storeId 货主ID等值筛选。where.orderNo 标注暂不可用(待快照字段就绪)。response 移除 pack_status 字段(两表无关联,不再返回),list 字段数从 28 减至 27。", + "waybill.warehouse.detail:package 对象移除 pack_status/pack_quantity/pack_at/packer_name 四个字段,仅保留 package_material_id 和 package_material_name。description 同步去掉\"打包状态\"相关描述。", + "waybill.warehouse.export:响应简化为纯异步任务模式,data 仅含 task_id/status/progress/message/update_time,不含 total_count/current_count/result/error/download_url 等执行期字段(这些信息由 exportTaskProgress 接口返回)。export 的 where 参数同步新增 waybillType 和 storeId。", + "waybill.warehouse.exportTaskProgress:无变更,保持不变。" + ], + "module": "waybill.warehouse" + }, + { + "version": "2026.08.03-system-01", + "date": "2026-08-03", + "type": "added", + "summary": "新增站内信(Inbox)管理模块,支持消息列表、详情、对话链、回信、重推、统计等管理功能,仓库维度隔离,warehouseId 由服务端上下文注入", + "methods": [ + "inbox.list", + "inbox.detail", + "inbox.thread", + "inbox.reply", + "inbox.retry", + "inbox.stats" + ], + "notes": [ + "入口:POST /system,body.method=inbox.{action},路由到 app/controller/inbox.index", + "inbox.list:分页查询消息列表,支持 direction/pushStatus/targetChannel/keyword 筛选,列表不含 ext_data 和 push_response 大字段", + "inbox.detail:查单条消息详情,含完整 push_response 推送响应信息", + "inbox.thread:对话链查询,从指定消息向上查找根消息,向下收集所有回信,按时间升序返回", + "inbox.reply:系统回信,自动继承原消息 ext_data/ref_code,写入 direction=outbound + parent_id 形成对话链,异步推送到目标渠道", + "inbox.retry:手动重推失败消息(仅 push_status=3 可重推),重置为 push_status=0 并触发 setImmediate 异步推送", + "inbox.stats:按方向/推送状态汇总统计 + 最近24小时新增数量", + "安全边界:warehouse_id 由 ctx.user.store_id 注入(内部管理端),外部不可传入,保证仓库隔离", + "底层服务:app/service/inbox/index.js(查询管理)+ app/service/inbox/receiver.js(接收推送)" + ], + "module": "inbox" + }, + { + "version": "2026.08.03-system-02", + "date": "2026-08-03", + "summary": "setting.expressInterface.list 返回新增 quantity/recycled_quantity/cancel_quantity/allocated_quantity 扁平字段,数据源为 index.getShopExpressList", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "每条记录新增四个扁平字段:quantity(可用面单数)、recycled_quantity(已回收)、cancel_quantity(已取消)、allocated_quantity(已分配)", + "数据通过 Promise.all 并行调用 index.getShopExpressList 获取各店铺快递签约数据", + "匹配逻辑分三层:sys_express_code 匹配快递 → site_code/branch_code 匹配网点 → shipperno/customer_code_list 匹配账号", + "无店铺或无数据时四个字段均为 0" + ] + }, + { + "version": "2026.08.03-system-03", + "date": "2026-08-03", + "summary": "补全 setting.expressInterface.list response 所有返回字段文档,包含 express 子对象、quantity 四字段等", + "methods": [ + "setting.expressInterface.list" + ], + "notes": [ + "补全所有 response list children 字段:从原有的 4 个扩展为 42 个完整字段", + "新增 express 子对象文档(code/name/polyapi_code/polyapi_extra_info/pdd_code/ks_code/dyxd_code)", + "保留 quantity/recycled_quantity/cancel_quantity/allocated_quantity 四个扁平面单数量字段" + ] + }, + { + "version": "2026.08.03-system-04", + "date": "2026-08-03", + "type": "added", + "summary": "新增店铺-快递绑定策略模块 storeExpressBindingPolicy,支持仓库维度的货主/店铺->快递绑定策略 CRUD,按优先级匹配,可附加商品/地区/重量/金额等条件", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "storeExpressBindingPolicy.list:分页查询策略列表,支持 where 条件筛选(id/custom_name/store_id/shop_id/express_code/priority/is_enabled/creator_id/quickWhere),按 priority DESC、updated_at DESC 排序。", + "storeExpressBindingPolicy.add:新增策略,必填 custom_name 和 express_code。express_code 须存在于 wms_express。同仓库下 custom_name 唯一。可选 store_id/shop_id/priority/is_enabled/match_condition/remark/creator_id。", + "storeExpressBindingPolicy.edit:编辑策略,必填 id。仅更新传入的非 undefined 字段。修改 custom_name 时校验同仓库唯一性。", + "storeExpressBindingPolicy.del:软删除策略(deleted_at + is_enabled=0),不物理删除。", + "仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。", + "匹配条件 match_condition(JSON):支持 platform_codes/provinces/cities/item_codes/min_weight_g/max_weight_g/min_amount/max_amount。" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.03-system-05", + "date": "2026-08-03", + "type": "changed", + "summary": "精简 storeExpressBindingPolicy:移除 store_id/shop_id 冗余字段,custom_name 明确为纯自由文本标签(与系统 shops 无关)", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "移除 add/edit 入参中的 store_id/shop_id(含 camelCase 兼容)", + "list 响应不再返回 store_id/shop_id", + "custom_name 为纯自由文本标签,与系统 shops 表无关" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-01", + "date": "2026-08-04", + "type": "changed", + "summary": "storeExpressBindingPolicy 字段重构: match_condition JSON 拆分为独立字段 provinces/cities/min_weight_g/max_weight_g/weight_type,新增 prohibited_type_id", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "移除 match_condition JSON,拆分 provinces TEXT逗号分隔 + cities TEXT逗号分隔 + min_weight_g INT + max_weight_g INT + weight_type TINYINT 默认0", + "weight_type 枚举 0=常规 1=轻货 2=重货 3=冷链 必填默认0", + "新增 prohibited_type_id 关联 wms_prohibited_type.id" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-02", + "date": "2026-08-04", + "type": "changed", + "summary": "合并 provinces/cities 为单一 regions 字段 TEXT逗号分隔", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "移除 provinces/cities 两个字段,合并为 regions TEXT 逗号分隔" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-03", + "date": "2026-08-04", + "type": "added", + "summary": "新增 exclude_regions 排除地区字段", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "新增 exclude_regions 排除地区字段 TEXT逗号分隔" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-04", + "date": "2026-08-04", + "type": "changed", + "summary": "修正 API 文档风格,对齐项目 shops.list 等模块规范", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "list page/pageSize 描述对齐 shops.list 风格", + "add/edit 参数描述补充兼容性说明和详细格式" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-05", + "date": "2026-08-04", + "type": "added", + "summary": "新增 shop_name 字段,用于包含店铺名称匹配", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "新增 shop_name TEXT逗号分隔,与 custom_name区分:custom_name=策略名称,shop_name=包含店铺名称" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026.08.04-system-06", + "date": "2026-08-04", + "type": "added", + "summary": "新增shop_name和store_ids字段", + "methods": [ + "storeExpressBindingPolicy.list", + "storeExpressBindingPolicy.add", + "storeExpressBindingPolicy.edit", + "storeExpressBindingPolicy.del" + ], + "notes": [ + "新增shop_name包含店铺名称", + "新增store_ids限定货主ID" + ], + "module": "storeExpressBindingPolicy" + }, + { + "version": "2026-08-05-wavePickTaskDetail-waveNo", + "date": "2026-08-05", + "summary": "pick.wavePickTaskDetail 响应 task 对象新增 wave_no 字段,从 wms_wave_pick_task_wave 关联 wms_wave_batch 获取波次号", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "task 对象新增 wave_no(string)字段,位于 task_no 之后;查询失败时降级为空字符串。", + "数据来源:wms_wave_pick_task_wave INNER JOIN wms_wave_batch ON wave_id。" + ] + }, + { + "version": "2026-08-06", + "date": "2026-08-06", + "summary": "sign_method 收紧为仅支持 md5:create 固定为 md5 不可选,update 不允许修改 sign_method,list/detail 响应描述同步更新", + "methods": [ + "apiApp.list", + "apiApp.detail", + "apiApp.create", + "apiApp.update" + ], + "notes": [ + "验证确认 /openapi 和 /warehouse 实际只使用 MD5 签名算法", + "apiApp.create: 删除 sign_method 入参,硬编码为 md5", + "apiApp.update: sign_method 字段改为不可修改,传入即报错", + "apiApp.list / apiApp.detail: sign_method 响应描述更新为「当前仅支持 md5」" + ] + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-remove-action", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder 移除 action 参数:action 不再由前端传入,改为服务端固定写入\"处理工单\";处理说明统一使用 remark 字段。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "移除 action 参数(原为必填 string,前端传入操作动作描述),前端不再需要也不接受此参数。", + "步骤记录的 action 字段由服务端在 systems/afterSale.js handleWorkOrder 中硬编码为\"处理工单\"。", + "处理说明统一使用 remark 字段承载。", + "代码变更:systemMethods/afterSale.js handleWorkOrder 移除 action 解构与必填校验;systems/afterSale.js handleWorkOrder 移除 message 参数,addStep action 固定为\"处理工单\"。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-status-whitelist", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder 新增 status 枚举白名单校验:status 必须与 wms_after_sale 主表 AFTER_SALE_STATUS 枚举一致(pending/processing/completed/closed/cancelled),补全 cancelled 枚举值文档。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "status 参数新增枚举白名单校验:从 AfterSale.AFTER_SALE_STATUS 取 key 列表,不在白名单内返回 400。", + "文档 status 枚举值补全 cancelled,与主表模型保持一致(pending | processing | completed | closed | cancelled)。", + "校验同时在 systemMethods/afterSale.js(方法层)和 systems/afterSale.js(业务层)两层生效。", + "仅代码校验增强 + 文档修正,不改变业务语义。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-status-default-processing", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder status 参数改为容错模式:不填或填错时默认 processing(处理中),不再返回 400 错误。status 始终写入主表。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "status 参数行为变更:原来不传时保持当前状态(有 if 判断),现在不填或填错默认 processing,始终写入主表。", + "校验方式从白名单拒绝改为容错兜底:safeStatus = (targetStatus 合法) ? targetStatus : 'processing'。", + "updateFields.status 从条件写入改为始终写入 safeStatus。", + "role_group 回退判断同步从 targetStatus 改为 safeStatus。", + "代码变更:systemMethods/afterSale.js + systems/afterSale.js 两层均改为容错逻辑。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-exclude-pending", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder status 白名单排除 pending:pending 是创建默认值(表示尚未处理),处理工单时不允许回退到此状态。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "handleWorkOrder 允许的 status 从全部 AFTER_SALE_STATUS 中排除 pending,剩余:processing | completed | closed | cancelled。", + "若前端传 status=pending 视为填错,容错兜底为 processing。", + "代码变更:两处 ALLOWED_STATUSES 增加 .filter(s => s !== 'pending')。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-step-status-align-main-table", + "date": "2026-08-10", + "type": "changed", + "summary": "wms_after_sale_detail.step_status 改为与 wms_after_sale.status 完全一致:字段类型从 TINYINT 改为 VARCHAR(20),每次写入步骤时记录主表当前 status 快照。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "DB 迁移:20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js — step_status 从 TINYINT UNSIGNED 改为 STRING(20),已有数据回填 processing。", + "Model:after_sale_detail.js 移除 TINYINT 引用,step_status 改为 STRING(20),STEP_STATUS 枚举对齐主表 AFTER_SALE_STATUS。", + "addStep 默认值从 2 改为 'processing'。", + "transfer:step_status 取 update() 返回的 updated.status。", + "handleWorkOrder:step_status 取 safeStatus(与写入主表的 status 完全一致)。", + "registerClaim:step_status 取 afterSale.status(主表当前状态)。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-add-waiting-status", + "date": "2026-08-11", + "type": "added", + "summary": "新增 waiting(等待外部处理)状态:用于内部处理完成后等待外部第三方(快递、客户、平台)响应的场景。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "Model:after_sale.js AFTER_SALE_STATUS 新增 waiting: '等待外部处理'。", + "Model:after_sale_detail.js STEP_STATUS 同步新增 waiting。", + "handleWorkOrder 白名单自动包含 waiting(从 AFTER_SALE_STATUS 派生,仅排除 pending)。", + "状态流转:processing → waiting → processing/completed。", + "设计文档同步更新 ER 图、状态流转图、枚举表。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-rename-pending-feedback", + "date": "2026-08-11", + "type": "changed", + "summary": "waiting 重命名为 pending_feedback(等待外部反馈):语义更精确——内部已处理完并将信息发给外部,等待反馈后再决定是否继续处理,等待期间不需要内部介入。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "Model/DB/文档中 waiting 全部替换为 pending_feedback", + "workList/workCount 排除列表新增 pending_feedback(等待反馈期间不需要内部处理)", + "典型场景:客服收到拦截工单 → 发信息给运方 → 设为 pending_feedback 等待运方反馈 → 收到反馈后回到 processing 通知客户" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-batchSetPendingFeedback", + "date": "2026-08-11", + "type": "added", + "summary": "新增 afterSale.batchSetPendingFeedback 批量设为待反馈接口:传入 ids 列表,按仓库 policy_config.after_sale_followup_hours 配置自动计算 followup_at,事务内批量更新状态并写入步骤记录。", + "methods": [ + "afterSale.batchSetPendingFeedback" + ], + "notes": [ + "新增 method:afterSale.batchSetPendingFeedback,入参 ids(number[])和 remark(string, optional)", + "业务层 systems/afterSale.js 新增 batchSetPendingFeedback:预校验 ids 有效性/终态/跨仓库,事务内逐条更新 status=pending_feedback + followup_at=NOW()+INTERVAL hours HOUR + 步骤记录", + "方法层 systemMethods/afterSale.js 新增 batchSetPendingFeedback:从 ctx.user 提取 operator 信息和 warehouseId,委托 systems 层执行", + "followup_at 时长复用现有 _resolveFollowupHours 三级查找:仓库 policy_config → 内置 DEFAULTS 映射 → 兜底 24h", + "终态工单(completed/closed/cancelled)不可设为待反馈,跨仓库工单被拒绝,均返回在 failed 列表中", + "已在 _noNeedRight 和 _noNeedAuth 中注册,写入操作会记录日志" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-batchClose", + "date": "2026-08-11", + "type": "added", + "summary": "新增 afterSale.batchClose 批量完结/关闭接口:传入 ids + status(completed|closed),事务内批量更新状态、写入步骤记录,completed 时自动写入 resolved_at 并清除 followup_at。", + "methods": [ + "afterSale.batchClose" + ], + "notes": [ + "新增 method:afterSale.batchClose,入参 ids(number[])、status(completed|closed)、resolution(string, optional)、remark(string, optional)", + "业务层 systems/afterSale.js 新增 batchClose:预校验 ids 有效性/终态/跨仓库,事务内逐条更新 status + resolved_at + followup_at 清除 + 步骤记录", + "方法层 systemMethods/afterSale.js 新增 batchClose:从 ctx.user 提取 operator 信息和 warehouseId,委托 systems 层执行", + "终态工单(completed/closed/cancelled)不可重复完结/关闭,跨仓库工单被拒绝,均返回在 failed 列表中", + "已在 _noNeedRight 和 _noNeedAuth 中注册,写入操作会记录日志" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-detail-enrich", + "date": "2026-08-11", + "type": "enhanced", + "summary": "enhance: afterSale.detail 响应新增 related 字段,自动补充关联订单详情(收件人/发件人/商品明细/打包视频)和货主合约备注(store_remask)。", + "methods": [ + "afterSale.detail" + ], + "notes": [ + "响应新增 related 对象:含 related.order(订单详情)和 related.store_contract(货主合约备注),仅在售后单有关联单据时有值", + "related.order.recipient:从 wms_order_delivery 提取收件人姓名/电话/手机/邮箱/省市区/详细地址", + "related.order.sender:从货主 store.subject_config 提取发件人信息(sender_name/sender_tel/地址)", + "related.order.current_table:根据 dispatch_status/outbound_status/status 判断订单当前所在表(main/dispatch/history)", + "related.order.items:从 order_delivery.items JSON 字段解析商品明细数组", + "related.order.pack_videos:通过 PackTask → PackTaskVideo 关联查询打包视频列表(含 video_url/camera_id)", + "related.store_contract:从 wms_store_warehouse 查询 store_remask(商家备注)/warehouse_remask(仓库备注)/使用状态", + "所有关联查询使用 try-catch 兜底,查询失败时仅打 warn 日志,不影响主流程", + "systems/afterSale.js 新增 _enrichAfterSaleDetail / _resolveOrderDetail / _resolveStoreContractNote 三个私有方法" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-detail-waybill", + "date": "2026-08-11", + "type": "enhanced", + "summary": "enhance: afterSale.detail 响应 related 新增 waybill 字段,自动补充运单详情(快递公司名称 + 使用的物流接口)。", + "methods": [ + "afterSale.detail" + ], + "notes": [ + "响应 related 新增 related.waybill 字段(waybill_id 不为空时自动返回)", + "related.waybill.logistics_name:快递公司名称(如 圆通/中通/顺丰),来源 wms_order_express.logistics_name", + "related.waybill.logistics_interface_name:使用的物流接口名称,来源 wms_order_express.logistics_interface_name", + "related.waybill.logistics_code:物流编码,来源 wms_order_express.logistics_code", + "related.waybill 同时返回 waybill_code/status/is_back/is_intercept/create_at 等基础字段", + "systems/afterSale.js 新增 _resolveWaybillDetail 私有方法,查询失败仅打 warn 日志不影响主流程", + "仅文档 + 代码变更,不涉及数据库变更" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-create-order-id-alias", + "date": "2026-08-11", + "type": "enhanced", + "summary": "enhance: afterSale.create 入参新增 order_id 别名,与 order_delivery_id 等效,优先取 order_delivery_id,为空时回退到 order_id。", + "methods": [ + "afterSale.create" + ], + "notes": [ + "create 方法解构时新增 order_id 别名读取;优先使用 order_delivery_id,为空时取 order_id", + "仅方法层变更(systemMethods/afterSale.js),业务层无改动", + "同时更新 JSDoc 注释,标注 order_delivery_id 兼容别名 order_id" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-inbox-group-update-subtype-enum", + "date": "2026-08-11", + "summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述", + "type": "enhance", + "methods": [ + "inbox.group.update" + ], + "notes": [ + "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", + "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" + ] + }, + { + "version": "2026.08.11-inbox-group-update-subtype-enum-v2", + "date": "2026-08-11", + "summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述", + "type": "enhance", + "methods": [ + "inbox.group.update" + ], + "notes": [ + "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", + "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" + ] + }, + { + "version": "2026.08.11-inbox-group-update-subtype-enum-v3", + "date": "2026-08-11", + "summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述", + "type": "enhance", + "methods": [ + "inbox.group.update" + ], + "notes": [ + "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", + "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" + ] + }, + { + "version": "2026.08.13-returnReceived", + "date": "2026-08-13", + "type": "added", + "summary": "新增退回收到模块(returnReceived):退回包裹扫码登记、分页列表、详情、删除四个接口。扫码登记30日内同仓库同单号幂等(以第一次为准),反查原运单判定是否原单退回并同步标记 is_back='Y';列表/详情/删除仓库隔离。配套权限 527/528/529(扫码登记→仓库员工及以上,列表/删除→客服员工及以上)", + "methods": [ + "returnReceived.create", + "returnReceived.list", + "returnReceived.detail", + "returnReceived.delete" + ], + "notes": [ + "新增表 wms_return_received(仓库隔离 warehouse_id、退回收件单号 waybill_code、扫描日期 scan_date、扫描人员 scanner_id/scanner_name、运单关联 order_express_id/order_id/store_id 非必填)", + "returnReceived.create:30日幂等 + 反查 wms_order_express.waybill_code,命中回填关联字段并同步 is_back='Y',返回 is_original_return/store_remark/duplicated", + "returnReceived.list:分页列表,仓库隔离由服务端注入 warehouse_id,支持运单号/日期/扫描人员/货主/是否原单退回筛选", + "returnReceived.detail:详情含原运单与货主合约备注,免权限但需登录+仓库隔离", + "returnReceived.delete:物理删除,需权限+仓库隔离", + "权限:527 returnReceived.create(仓库员工及以上)、528 returnReceived.list、529 returnReceived.delete(客服员工及以上);detail 复用 list 权限", + "代码变更:app/model/return_received.js、app/service/systems/return_received.js、app/service/systemMethods/returnReceived.js、database/migrations/20260812160000-create-wms-return-received.js、20260813100000-create-return-received-permissions.js" + ], + "module": "returnReceived" + }, + { + "version": "2026.08.13-shops-GetAuthorizeSessionKey-doc-sync", + "date": "2026-08-13", + "type": "updated", + "summary": "同步 shops.GetAuthorizeSessionKey 文档:实现已切换为调用授权服务 saveShop 换取授权会话,旧的 PDD/CAINIAO 预占码方案已下线。", + "methods": [ + "shops.GetAuthorizeSessionKey" + ], + "notes": [ + "实现:按店铺 platform_code 取 wms_print_platform.get_auth_platform_name 作为 platName,POST 授权服务 saveShop,携带 RedirectCodeUrl/shopName;京东平台附 VenderID,视频号平台改传 appId/toUserName 且不带 RedirectCodeUrl", + "成功后更新店铺 access_token=sessionKey、status=1,返回 data.message='获取授权成功';上游 code≠0 或未返回 sessionKey 时抛 500", + "文档更新:移除旧 data.session_key/authorize_url/state 返回结构与 501 未实现错误,补充 appId/toUserName 入参及 shop_id/callbackurl/platform_code 校验错误码", + "仅文档同步,不修改业务代码" + ], + "module": "shops" + }, + { + "version": "2026.08.13-interceptScan-non-intercept-guard", + "date": "2026-08-13", + "type": "updated", + "summary": "order.recheckOrder.interceptScan 增加非拦截订单前置校验:运单不存在或未发起系统拦截时直接拒绝并提示「非拦截订单」,移除原先自动创建运单补充记录的逻辑。", + "methods": [ + "order.recheckOrder.interceptScan" + ], + "notes": [ + "校验规则:运单记录不存在即拒绝;运单 is_intercept≠'Y' 时回查关联订单,intercept_status 不在 requested/intercepting 也拒绝,提示「非拦截订单」", + "校验通过后原逻辑不变:标记 is_back='Y'/is_intercept='Y'、处理未完结售后工单、订单级更新 intercepted_at_warehouse 并释放储位分配与订单锁", + "移除运单不存在时自动创建补充记录的分支(未发起拦截的运单不再被静默置为拦截)", + "同步更新 JSDoc 与 methods/system.json 文档,错误码新增 400 非拦截订单" + ], + "module": "order.recheckOrder" + }, + { + "version": "2026.08.13-returnUnpack", + "date": "2026-08-13", + "type": "added", + "summary": "新增退回拆包模块(returnUnpack):开拆包单、录明细、更新明细、移除明细、取消、提交确认、分页列表、明细列表、详情、删除十个接口。开单反查原运单判定原单退回并回填货主,未命中原单时按 warehouse_id+waybill_code 从退回查询记录反查货主;拆包单号 RP+YYYYMMDD+6位序号;状态机 unpacking/completed/cancelled;明细识别状态 none_recognized/partial_recognized/all_recognized;全接口仓库隔离(服务端注入 warehouse_id)。配套权限 540-549(作业类→仓库员工及以上,查询/删除类→客服员工及以上,detail 免权限复用列表权限)", + "methods": [ + "returnUnpack.create", + "returnUnpack.addDetail", + "returnUnpack.updateDetail", + "returnUnpack.removeDetail", + "returnUnpack.cancel", + "returnUnpack.submit", + "returnUnpack.list", + "returnUnpack.detailList", + "returnUnpack.detail", + "returnUnpack.delete" + ], + "notes": [ + "新增表 wms_return_unpack(主表)/ wms_return_unpack_detail(明细)/ wms_return_unpack_video(视频,paranoid 软删)/ wms_return_query_log(退回查询记录)", + "returnUnpack.create:waybill_code 必填;反查 wms_order_express.waybill_code 命中则回填 order_express_id/order_id/store_id 并返回原订单详情(复用 afterSale._resolveOrderDetail);未命中再从 wms_return_query_log 按 warehouse_id+waybill_code 反查货主(限最近 3 个月内登记);返回 id/record/is_original_return/store_remark/order", + "returnUnpack.addDetail:主单非终态校验;stock_id 有值 → 查 wms_stock_warehouse 校验货主归属(不一致 403)+ 回填 is_recognized=1 与快照;主表 store_id 为空时以首个识别商品回填货主;写明细后重算 total_items/total_quantity/detail_status", + "returnUnpack.updateDetail:白名单仅 quantity/remark;仅 quantity 变更时重算主表汇总", + "returnUnpack.removeDetail:明细表 paranoid:false 硬删除 + 重算主表汇总", + "returnUnpack.cancel:仅 unpacking 状态;事务内硬删主表+明细,软删视频", + "returnUnpack.submit:仅 unpacking;status=completed + 回写 end_time,并同步更新 wms_return_query_log.is_back=1(失败不阻断主流程)", + "returnUnpack.list:主表分页,仓库隔离服务端注入 warehouse_id;where 支持 unpack_no/waybill_code 模糊、unpack_date/start_time/end_time 范围、status/detail_status/unpacker_id/return_received_id/store_id/order_express_id/order_id 等值", + "returnUnpack.detailList:明细分页 + stockWarehouse 关联(命中时);where 支持 unpack_id/stock_id/barcode/is_recognized/product_status", + "returnUnpack.detail:主表 + details(stockWarehouse) + videos(camera) + returnReceived;原单退回时返回 related.order;免权限仅登录 + 仓库隔离", + "returnUnpack.delete:后台删除不限状态;事务物理删主表+明细,软删视频", + "仓库隔离:全部接口禁止前端传入 warehouse_id,由服务端注入 ctx.user.store_id;拆包单号规则 RP+YYYYMMDD+6位序号(仓库维度序号)", + "权限:540 returnUnpack.create、541 addDetail、542 updateDetail、543 removeDetail、544 cancel、545 submit(仓库员工及以上);546 list、547 detailList、548 detail、549 delete(客服员工及以上);detail 免权限(复用列表权限)", + "代码变更:app/model/return_unpack.js、return_unpack_detail.js、return_unpack_video.js、return_query_log.js;app/service/systems/return_unpack.js;app/service/systemMethods/returnUnpack.js;database/migrations/20260813120000-20260813120300 建表、20260813130000 权限" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnReceived.createResponse", + "date": "2026-08-13", + "type": "updated", + "summary": "returnReceived.create 出参结构调整:由平铺返回登记字段改为包装结构 { record, is_original_return, store_remark, duplicated },record 含登记记录完整字段与派生字段 is_original_return/store_remark,与代码实现(app/service/systems/return_received.js)及设计文档对齐", + "methods": [ + "returnReceived.create" + ], + "notes": [ + "原出参平铺 id/waybill_code/scan_date/scanner_id/scanner_name/order_express_id/order_id/store_id/remark/is_original_return/store_remark/duplicated,现改为四个顶层字段:record(object,必填)、is_original_return(boolean,必填)、store_remark(string,必填)、duplicated(boolean,必填)", + "record 内字段:id、waybill_code、scan_date、scanner_id、scanner_name、order_express_id、order_id、store_id、remark、created_at、updated_at(时间为格式化字符串)+ 派生字段 is_original_return、store_remark", + "顶层 is_original_return / store_remark / duplicated 为 record 之外独立返回字段,与 record 内同名字段取值一致", + "仅文档变更,代码实现已对齐(create 返回 { record, is_original_return, store_remark, duplicated },30日幂等命中与新建分支结构一致)" + ], + "module": "returnReceived" + }, + { + "version": "2026.08.13-returnWaybill", + "date": "2026-08-13", + "type": "added", + "summary": "新增运单退回登记模块(returnWaybill):复用 wms_return_query_log 表实现「货主 + 运单号」退回关系的增删查改五个接口(create/update/list/detail/delete)。create 校验货主合约并幂等返回已有记录;update 支持改运单号/货主/备注,改后冲突 409 拒绝;list 分页筛选(运单号模糊/货主/是否已通知/是否退回/登记时间范围);detail 免权限仅登录+仓库隔离;delete 物理删除。全接口仓库隔离(warehouse_id 服务端注入)。配套权限 551-555(作业类 create/update→仓库员工及以上,查询/删除类 list/detail/delete→客服员工及以上,detail 免权限复用列表权限)", + "methods": [ + "returnWaybill.create", + "returnWaybill.update", + "returnWaybill.list", + "returnWaybill.detail", + "returnWaybill.delete" + ], + "notes": [ + "复用表 wms_return_query_log(20260813120300 迁移已落地):warehouse_id/store_id/waybill_code/remark/is_notified/is_back/created_at/updated_at;登记接口不维护 is_notified/is_back(由定时任务与拆包联动维护)", + "returnWaybill.create:waybill_code/store_id 必填;货主合约校验(wms_store_warehouse 存在 store_id+warehouse_id,无合约 400 拒绝);同仓库+货主+运单号已存在时幂等返回已有记录 duplicated=true;写入 is_notified=0/is_back=0", + "returnWaybill.update:id 必填;仓库隔离校验;waybill_code/store_id/remark 可选更新;store_id 变更时校验新货主合约;改后与另一条同仓库+货主+运单号冲突则 409 拒绝", + "returnWaybill.list:pagination(pageSize 上限 500 默认 20)+ where(waybill_code 模糊、store_id、is_notified、is_back、created_at 起止)+ sort(id/created_at/updated_at/waybill_code,默认 created_at desc)", + "returnWaybill.detail:免权限(复用列表权限),仅登录 + 仓库隔离校验", + "returnWaybill.delete:物理删除(表 paranoid:false),返回被删除记录 id", + "仓库隔离:所有接口 warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入", + "权限:551 create、552 update(仓库员工及以上);553 list、554 detail、555 delete(客服员工及以上);detail 免权限复用 list 权限", + "代码变更:app/service/systems/return_waybill.js、app/service/systemMethods/returnWaybill.js、database/migrations/20260813160000-create-return-waybill-permissions.js" + ], + "module": "returnWaybill" + }, + { + "version": "2026.08.13-returnUnpack.detailAuth", + "date": "2026-08-13", + "type": "updated", + "summary": "returnUnpack.detail 鉴权配置变更:不再免权限(原 _noNeedRight='detail'),改为走 API 权限校验(固定权限 ID 548,客服员工及以上),与 app/service/systemMethods/returnUnpack.js 实现对齐。", + "methods": [ + "returnUnpack.detail" + ], + "notes": [ + "isNeedAuth:false → true;description 同步说明「需 548 权限(客服员工及以上)」", + "代码对齐:returnUnpack.js _noNeedRight 改为空字符串,detail 与其他接口一致走 API 权限校验", + "权限 548 为客服员工及以上(与原「查询类→客服员工及以上」设计一致)", + "仅文档同步,其余接口与模块不动" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnUnpack.addDetailBarcode", + "date": "2026-08-13", + "type": "updated", + "summary": "returnUnpack.addDetail 新增 barcode 入参(可选):stock_id 为空时按条码反查本仓库商品(wms_stock_barcodes)再走识别流程,反查不到按无关联货物处理;条码同步写入明细作记录(此前固定写 null)。复用基础模块条码索引,支持 PDA 扫描条码录明细。", + "methods": [ + "returnUnpack.addDetail" + ], + "notes": [ + "params 新增 barcode(string,可选,最长100,body)", + "识别优先级:stock_id > barcode 反查 > 无关联货物", + "明细 barcode 字段由固定 null 改为记录扫描条码", + "business 层按 warehouse_id+barcode 匹配 wms_stock_barcodes(uk_barcode 全局唯一,加仓库过滤防跨仓串货)" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnUnpack.addDetailBarcodeV2", + "date": "2026-08-13", + "type": "updated", + "summary": "returnUnpack.addDetail 识别策略调整:未指定 stock_id 时一律标注未知商品(item_name=未知商品),移除按条码自动反查 stock_id 的逻辑(同一条码可能对应多个 stock_id,自动匹配易误配);barcode 仍写入明细作记录。", + "methods": [ + "returnUnpack.addDetail" + ], + "notes": [ + "移除 barcode 反查 wms_stock_barcodes 自动识别逻辑(v1 新增,本次回退)", + "未指定 stock_id:is_recognized=0,item_name=未知商品(此前为 null)", + "barcode 参数保留:仅作记录写入明细,不参与商品匹配", + "docs 同步:addDetail description / stock_id / barcode 参数说明更新" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnUnpack.orderInfoSnapshot", + "date": "2026-08-13", + "type": "updated", + "summary": "wms_return_unpack 主表新增订单信息快照字段 source_order_codes(平台交易单号)/ shop_name(店铺名称=货主自定义店铺名称 store_remask),returnUnpack.create 原单退回时回填;退回查询(查退回)优先取主表快照返回交易单号与自定义店铺。", + "methods": [ + "returnUnpack.create" + ], + "notes": [ + "迁移 20260813170000-add-return-unpack-order-info.js:addColumn source_order_codes VARCHAR(500) + shop_name VARCHAR(50)", + "create 原单退回:source_order_codes 取 wms_order_express.source_order_codes,shop_name 取 store_remask", + "addDetail 首个识别商品回填主表 store_id 时同步回填 shop_name", + "退回查询 _resolveReturnOrderInfo 优先主表快照,空时实时兜底(交易单号→原运单/原订单,店铺→store_remask)" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.18-storeWarehouse-sign-confirmSign-doc", + "date": "2026-08-18", + "type": "added", + "summary": "补齐 storeWarehouse 签约接口文档(纯文档补全,无业务代码变更):新增 storeWarehouse.store.confirmSign(货主侧确认签约)、storeWarehouse.warehouse.sign(仓库侧发起签约)、storeWarehouse.warehouse.confirmSign(仓库侧确认签约)三个方法的入参/出参/错误码说明。", + "methods": [ + "storeWarehouse.store.confirmSign", + "storeWarehouse.warehouse.sign", + "storeWarehouse.warehouse.confirmSign" + ], + "notes": [ + "storeWarehouse.store.confirmSign:当前主体作为对方主体确认待签约申请,auth_status 由 1(申请中)变更为 2(已通过);入参 id(兼容 contract_id);400=id 缺失或签约状态非待签约、403=当前主体不在签约关系中或发起方自确认、404=签约关系不存在;响应 data.mode=confirm 与 data.contract 精简对象(id/store_id/warehouse_id/counterparty_name/remask/use_status/auth_status/auth_status_label/auth_end/print_quantity/has_qimen_config)", + "storeWarehouse.warehouse.sign:仓库侧发起签约,当前仓库在 store_id 方、对方在 warehouse_id 方,支持签约外部合作仓库;入参 counterparty_id(兼容 warehouse_id / store_id),当前主体自动识别;响应 data.mode=initiate/already_exists/already_confirmed 与 data.contract;400=对方主体缺失/日期非法,404=签约对象不存在", + "storeWarehouse.warehouse.confirmSign:仓库侧确认签约,校验逻辑与货主侧确认一致(400/403/404 同 storeWarehouse.store.confirmSign)", + "代码对齐:app/service/systemMethods/storeWarehouse/store.js#confirmSign、app/service/systemMethods/storeWarehouse/warehouse.js#sign/#confirmSign 均已注册(_noNeedAuth 含三个方法,isNeedAuth=false、isNeedLogin=true);实现位于 app/service/systems/store_warehouse.js#sign/#confirmSign;权限表 method id 397「签约确定」", + "仅文档变更,无业务代码修改" + ], + "module": "storeWarehouse" + }, + { + "version": "2026.08.21-storage.inventory.list-stock-query", + "date": "2026-08-21", + "type": "updated", + "summary": "storage.inventory.list 新增 where.stock_query 虚拟筛选:按商品编码/名称/货物编码/条码/SKU ID 模糊匹配库存列表", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "与订单查询一致的 stock_query 虚拟筛选字段,如 where.stock_query = { operator: 'like', value: '111' }。", + "解析链路:stock_query → wms_stock_warehouse(item_code/item_name/goods_code/纯数字精确 id)+ wms_stock_barcodes(barcode)→ stock_id 集合 → wms_storage.stock_id IN 过滤;无匹配时返回空列表。", + "代码变更:systemMethods/storage/inventory.js#list 新增 extractStockQueryVirtualFilter(从 where 提取并移除 stock_query);systems/storage/inventory.js#getInventoryList 新增 stockQuery 参数与 resolveStockQueryToStockIds;methods/system.json 同步 where 参数文档(export 注明暂不支持 stock_query)。" + ], + "module": "storage" + }, + { + "version": "2026.08.24-storage.inventory.directPutaway", + "date": "2026-08-24", + "type": "added", + "summary": "新增 storage.inventory.directPutaway 接口:收货单直入库存(一步完成),直接写 wms_storage 并生成入库单", + "methods": [ + "storage.inventory.directPutaway" + ], + "notes": [ + "新增收货单直入库存接口,与 storage.inventory.quickPutaway(转入库单,不写库存)并存,名称不交换保持兼容。", + "核心流程:校验收货单(completed + is_review=true,未作废)→ 检查货主配置 policy_config.allow_receiving_direct_putaway=1 → 过滤未入库明细(storage_status!=all)并校验全部已匹配系统商品 → 事务内锁定收货单行防并发 → 创建入库单 SCRK(order_status=COMPLETED、sync_status=SUCCESS,一步完成)→ 入库单明细与收货明细一一对应(不合并,每行 count/received_quantity=actual_quantity)→ 写入 wms_entry_order_receiving 主表级绑定 → 按 stock_id 聚合悲观行锁更新 wms_stock_warehouse 总库存并写 wms_stock_transaction(order_type=SCRK,与现有链路一致)→ 按收货明细库位 space_id 逐明细写入/累加 wms_storage 并写 wms_storage_transaction(order_type=entry_order,与现有 storage.entry.commit 链路一致)→ 逐明细写入 wms_inbound_direct_log(entry_item_id/receiving_detail_id/space_id 齐全,status=committed、inbound_type=import,与 storage.entry.commit 链路口径一致,保证 scanDetail/可用数量占用统计等读取链路数据一致)→ 回填收货明细 storage_status=all/stored_quantity 与主表 storage_status(all/partial)→ 操作日志。", + "日志全量写入:storage 变更记录(wms_storage_transaction,逐明细含 before/after 数量与锁定量)、stock 变更记录(wms_stock_transaction,按 SKU 聚合含 before/after 数量与锁定量)、stock 变更(wms_stock_warehouse 悲观行锁 increment quantity);操作日志(wms_operation_log)同时写三条:businessType=entry_order(ENTRY_ORDER_DIRECT_PUTAWAY)、businessType=storage(STORAGE_DIRECT_PUTAWAY,记录库位库存写入笔数与数量)、businessType=stock(STOCK_DIRECT_PUTAWAY,记录各 SKU 总量变更前后值摘要)。", + "库位规则:明细 space_id 有效则按其库位入库,否则回退默认库位 1;批次取收货明细 batch_number,无批次则以入库单号作为批次号;生产/效期日期取收货明细 production_date/expiry_date。", + "与 quickPutaway 的区别:directPutaway 一步直接写库存(入库单 COMPLETED),quickPutaway 仅转入库单(PENDING)不写库存,需再走 storage.entry.commit 才写库存。", + "货主开关:policy_config 新增 allow_receiving_direct_putaway(默认未开启时 400 拒绝),与 allow_receiving_quick_putaway 相互独立;app/model/store_warehouse.js 的 POLICY_CONFIG_FIELDS 白名单已补充该字段(否则模型 getter sanitizeOnly 会过滤掉该键导致开关无法读取)。", + "代码变更:app/service/systems/storage/inventory.js#directPutaway、app/service/systemMethods/storage/inventory.js#directPutaway(_noNeedAuth 新增 directPutaway)、methods/system.json 新增 method 文档、database/migrations/20260824 新增权限记录(path=storage.inventory.directPutaway)。" + ], + "module": "storage" + }, + { + "version": "2026.09.10-order.wave.wavePickTaskList-cart-code", + "date": "2026-09-10", + "type": "updated", + "summary": "order.wave.wavePickTaskList 新增 cart_code 筛选:按拣货车编码查询拣货任务", + "methods": [ + "order.wave.wavePickTaskList" + ], + "notes": [ + "新增 cart_code 过滤字段,匹配拣货任务主表快照字段 wms_wave_pick_task.current_cart_code_snapshot(与列表返回的 current_cart_code_snapshot 同源),支持操作符对象 { operator: 'like'|'notlike'|'eq', value },默认 like;顶层 cart_code 与 where.cart_code 均支持,顶层参数优先。", + "keyword 关键字搜索同步覆盖 current_cart_code_snapshot 字段(此前文档已声明支持,本次代码补齐)。", + "代码变更:app/service/systemMethods/order/wave.js#normalizeWavePickTaskListRequest 新增 cart_code 顶层合并、#buildWavePickTaskListWhereClause 新增 cart_code 白名单与条件拼接(复用 appendNameCondition)。", + "顺带修正:该接口失败响应未透传业务码(this.fail(msg, 400) → this.fail(msg, {}, 400/500)),并将「不支持的 operator」类入参错误归为 400,与其它 systemMethods 约定及本文档错误码一致。", + "测试:test/app/service/systemMethods/order/wave.wavePickTaskList.test.js 补充 cart_code 操作符/默认模糊/顶层优先/keyword 覆盖用例,并修复原 mock 缺失 QueryTypes.SELECT 导致的既有用例失败。" + ], + "module": "order" + }, + { + "version": "2026.10.26-index.getShopExpressList-productTypes", + "date": "2026-10-26", + "type": "updated", + "summary": "index.getShopExpressList 返回的 list 每项新增 product_types 字段:[{ name, code }],按 sys_express_code 匹配 wms_express_product_type 得到,未匹配时为空数组;PDD 平台不补充该字段。", + "methods": [ + "index.getShopExpressList" + ], + "notes": [ + "适用范围:仅 PDD 以外的平台(CAINIAO/DY/KS/SPH/XHS/JD 等)补充 product_types,PDD 平台保持原有返回结构不变。", + "匹配规则:list 项 sys_express_code 与 wms_express_product_type.express_code 比较(trim + 大写,不区分大小写),同一 express_code 下按 code 去重;name 为空时回退为 code。", + "数据来源与缓存:复用系统快递服务 getExpressProductTypeList 的全量缓存(缓存键 express:product-type:list,TTL 1 小时),缓存失效由 upsertExpressProductTypeList 在新增/更新产品类型后清理,接口不再额外直连数据库。", + "容错:产品类型读取异常时仅记录 warn 日志,list 各项目 product_types 返回空数组,不影响电子面单签约列表主流程。", + "JD 平台在 sys_express_code 补偿映射完成后再补充 product_types,与最终返回的 sys_express_code 一致。", + "代码变更:app/service/systemMethods/index.js 新增 buildExpressProductTypeMap 与 attachExpressProductTypes,getShopExpressList 在返回前按平台补充字段(PDD 跳过、不读取产品类型缓存);methods/system.json 同步 data.list 说明与 product_types 子字段文档。" + ], + "module": "index" + }, + { + "version": "2026.11.14-storeWarehouse.store.saveApiConfig-contract-open-api", + "date": "2026-11-14", + "type": "updated", + "summary": "storeWarehouse.store.saveApiConfig 签约关系级接口配置统一按货主开放接口落库:interface_type_id=3(OPEN_API_WAREHOUSE)自动映射为 2(OPEN_API),货主主体也可维护,callback_url 改由 config.openapi.defaultCallbackUrl 注入", + "methods": [ + "storeWarehouse.store.saveApiConfig", + "storeWarehouse.store.listApiConfig" + ], + "notes": [ + "货主不能创建仓库接口:saveApiConfig 通过 resolveContractApiInterfaceType 解析接口类型,传入 OPEN_API_WAREHOUSE(id=3)时改为按 OPEN_API(id=2,货主开放接口)落库,wms_api_app.interface_type_id 实际写入 2,并记录 warn 日志;未配置启用的 OPEN_API 类型时返回 404「未配置可用的货主开放接口类型」。", + "货主主体可维护:移除 saveApiConfig 中的 ensureWarehouseSubject 校验,project=store 的当前主体也能保存签约关系下的接口配置(deleteQimenConfig、savePolicyConfig、adjustPrintQuantity 仍仅仓库主体可操作)。", + "callback_url 不再取入参:入参 callback_url/callbackUrl 一律忽略,统一写入 config.openapi.defaultCallbackUrl(新增配置项,默认空字符串;为空或长度超过 500 时写 null),值来源为 app/service/systems/store_warehouse.js#getDefaultApiCallbackUrl。", + "listApiConfig 的 interface_type_id 过滤同步映射:传 3 时按 2 过滤,避免保存后按 3 查询查不到配置。", + "回调链路口径不变:service/openapi/callback.js、order_async.js、inbound_direct_log.js 等仍读取 wms_api_app.callback_url,只是该值改由配置统一注入。", + "代码变更:app/service/systems/store_warehouse.js(新增 resolveContractApiInterfaceType / getDefaultApiCallbackUrl,saveApiConfig 与 listApiConfig 调整)、config/config.default.js(新增 config.openapi.defaultCallbackUrl)、methods/system.json 同步 method 文档、测试 test/app/service/systems/store_warehouse.saveApiConfig.test.js 与 store_warehouse.listApiConfig.test.js。" + ], + "module": "storeWarehouse" + } +] diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json new file mode 100644 index 0000000..5310bf0 --- /dev/null +++ b/methods/changes/warehouse.json @@ -0,0 +1,419 @@ +[ + { + "version": "2026.09.23-warehouse-receiving-pending-notice-reliability", + "date": "2026-09-23", + "type": "updated", + "summary": "收货未入库提醒(receiving_pending_inbound)可靠性增强:修复 10 分钟宽限窗口内每 5 分钟一轮导致的重复执行/重复通知(Redis SET NX 抢锁判定修正 + 进程内兜底锁改为 app 级共享集合);逐货主群异常隔离(单群发送异常不中断其他货主群);货主收货群推送失败自动回退仓库客服群人工跟进(独立幂等键与文案前缀);pushSystemMessage 推送幂等去重(同 ext_id 已送达跳过重推)", + "methods": [ + "notify.reply" + ], + "notes": [ + "定时任务锁修复:app/service/systems/receiving_pending_notice.js#acquireDailyLock 中 Redis SET NX 返回 null(键已存在)直接判定未抢到锁,不再落入进程内兜底(兜底仅用于 Redis 不可用/命令异常);进程内兜底锁由 service 实例级改为 app._receivingPendingDailyLocks 共享集合(getMemoryDailyLocks),跨轮次/跨实例生效;app/schedule/notice_receiving_pending_inbound.js 汇总日志补充 fallbackCount。修复 10 分钟宽限窗口内每 5 分钟一轮导致的重复执行/重复通知", + "逐群异常隔离:notifyWarehouse 对每个货主批次 try/catch(sendPendingNotice 内部同样隔离主推异常),单群发送异常只计失败并继续后续货主群,确保所有货主群的收货群均被通知,部分群失败不遗漏其他群", + "失败自动回退客服群:新增 sendCustomerServiceFallback——货主收货群主推失败(含异常)时自动回退仓库客服群人工跟进,文案前缀「通知货主【X】收货群推送失败,请人工跟进:」;幂等键独立为 receiving-pending-fallback:{仓库}:{货主}:{YYYYMMDD},与主推送互不影响;执行汇总(summary)新增 fallbackCount", + "推送幂等去重:app/service/systems/warehouseNotify.js#pushSystemMessage 中同 ext_id 且 push_status=2(已送达)直接返回成功并跳过推送;push_status=0/1/3 仍复用同一 wms_inbox_message 记录重推,防止重复轮次/多实例并发导致同一群重复收到相同通知", + "事件路由与协议不变:仍为 receiving_pending_inbound + notify.reply(type=system),固定订阅 store:receiving(未命中回退 warehouse:customer_service);主推送幂等键仍为 receiving-pending:{仓库}:{货主}:{YYYYMMDD};接口文档(methods/system.json 的 setting.warehouse 字段、methods/warehouse_notify.json 的 notify.reply 协议)无需变更", + "单测:test/app/service/systems/receiving_pending_notice.test.js 新增 5 个用例(推送失败同日不重发+回退计数、回退独立幂等键与失败前缀、逐群异常隔离、Redis SET NX null 判定、app 级进程内锁跨实例共享),全部通过;npx eslint 无告警" + ], + "module": "receiving" + }, + { + "version": "2026-09-15-warehouse-02", + "date": "2026-09-15", + "type": "changed", + "module": "receiving", + "summary": "收货未入库提醒出站文案改为「短语 + 换行 + 明细(一行一条)」:短语可在仓库设置自定义并插入变量,明细不再拼接在短语同一行,末尾不再追加句号", + "methods": [ + "notify.reply" + ], + "notes": [ + "文案结构(app/service/systems/receiving_pending_notice.js#buildContent):第 1 行 = 短语(模板渲染后),其后换行逐行输出明细(「序号.单号 货主:xx 数量:xx 创建时间:xx 状态:xx」,货主群版不展示货主/数量),最多 20 行,超出补「…… 其余 N 单未列出」,最后一行「快速查看:/详情查看:<链接>」", + "短语来源:仓库设置 subject_config.receiving_pending_inbound_notice.notice_template(仓库/客服群)/ store_notice_template(货主群),留空回退默认短语", + "支持变量:{warehouse}/{warehouse_id}/{store}/{store_id}/{count}/{min_hours}/{max_hours}/{date}/{numbers};未识别的占位符原样保留(便于发现拼写错误),变量渲染不影响未知变量", + "推送协议与路由不变:仍为 notify.reply(type=system)+ 固定订阅 receiving_pending_inbound(store:receiving,未命中回退 warehouse:customer_service)", + "单测:test/app/service/systems/receiving_pending_notice.test.js(11 用例)全部通过;npx eslint 无告警" + ] + }, + { + "version": "2026-09-15-warehouse-01", + "date": "2026-09-15", + "type": "added", + "module": "receiving", + "summary": "新增收货未入库提醒事件 receiving_pending_inbound:定时扫描「创建超时且未完成入库」的收货单,绑定货主的推货主收货群(未配群回退仓库客服群),未绑定货主的推仓库客服群;仓库设置新增 receiving_pending_inbound_notice(是否通知/提醒时间/超时区间,默认关闭)", + "methods": [ + "notify.reply" + ], + "notes": [ + "事件码注册:app/model/notification_webhook.js 新增 receiving_pending_inbound(name=收货未入库超时提醒,business=receiving);notice/index.js DEFAULT_REGISTERED_EVENT_CODES 同步登记", + "固定群订阅(app/service/systems/notice/index.js#FIXED_GROUP_SUBSCRIPTIONS):receiving_pending_inbound = [store:receiving,fallbackTargets=[warehouse:customer_service]];无货主时 store 目标被跳过,回退链命中仓库客服群,内容走仓库版文案", + "推送协议不变:复用 notify.reply(type=system、content、ext_id、group_id、group_name、timestamp),出站消息落 wms_inbox_message(ext_id 含 receiving-pending:{warehouseId}:{storeId}:{YYYYMMDD})", + "触发通道:app/schedule/notice_receiving_pending_inbound.js(interval 5m、type=worker、进程内防重入)→ app/service/systems/receiving_pending_notice.js#execute;按仓库 subject_config.receiving_pending_inbound_notice.notice_time(默认 08:30,宽限 10 分钟)执行,Redis 当日锁保证一天一次", + "扫描口径:wms_receiving 中 warehouse_id=仓库、is_deleted=0、status<>cancelled、created_at 在 (now-max_hours, now-min_hours] 区间,且(status=receiving 或 storage_status<>all);按 store_id 聚合,每批最多列 20 行(超出提示剩余单数)", + "仓库设置字段:wms_store.subject_config.receiving_pending_inbound_notice = { enabled(默认 false), notice_time(默认 08:30), min_hours(默认 24), max_hours(默认 48,须大于 min_hours) };setting.warehouse.getSettings/saveSettings 文档见 methods/system.json(change 2026.09.15-warehouse-pending-receiving-notice)", + "单测:test/app/service/systems/receiving_pending_notice.test.js(9 用例)全部通过;npx eslint 无告警" + ] + }, + { + "version": "2026.08.01-warehouse-01", + "date": "2026-08-01", + "type": "added", + "summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表", + "methods": [ + "index.ping", + "store.list" + ], + "notes": [ + "POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。", + "签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。", + "时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。", + "无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。", + "index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。", + "store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。", + "api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。" + ], + "module": "warehouse" + }, + { + "version": "2026.08.03-warehouse-01", + "date": "2026-08-03", + "type": "added", + "summary": "新增仓库开放 API 站内信模块 inbox.push,支持外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道(IM/API/webhook)", + "methods": [ + "inbox.push" + ], + "notes": [ + "POST /warehouse?method=inbox.push,interface_type_id=3(仓库侧),使用 MD5 签名鉴权", + "warehouse_id 由验签后上下文注入,禁止外部传入(安全边界)", + "ext_id 格式:api:{appKey}:{requestId},用于幂等去重", + "target_url 仅允许 https://,禁止内网 IP(SSRF 防护)", + "推送 body 大小限制 64KB", + "异步推送使用 setImmediate,不阻塞响应;失败指数退避重试(30s→60s→120s,最多3次)", + "路由到 app/service/warehouseMethods/inbox.push → app/service/inbox/receiver.receive" + ], + "module": "inbox" + }, + { + "version": "2026-08-06", + "date": "2026-08-06", + "summary": "inbox.push 文档同步代码现状:移除废弃参数 sourceChannel/targetChannel/storeId,补齐缺失参数 groupId/groupName/userId/userName/content,更新错误码与描述", + "methods": [ + "inbox.push" + ], + "notes": [ + "移除 sourceChannel / targetChannel / storeId 参数(代码中不存在)", + "补齐 groupId / groupName / userId / userName / content 参数", + "移除 targetChannel/targetUrl 相关错误码", + "新增 parent_id 校验、消息体 64KB 限制错误码", + "ext_id 自动组合为 api:{appKey}:{requestId}" + ] + }, + { + "version": "2026-08-07", + "date": "2026-08-07", + "summary": "inbox.push: source_type 硬编码为 api,移除 sourceType 入参(仓库 API 入站来源固定为 api,无需外部传入)", + "methods": [ + "inbox.push" + ], + "notes": [ + "source_type 从 body.sourceType || 'api' 改为硬编码 'api'", + "文档移除 sourceType 参数,description 补注 source_type 固定为 api" + ] + }, + { + "version": "2026-08-14-warehouse-01", + "date": "2026-08-14", + "type": "changed", + "summary": "inbox.push 新增 sendTime 参数与历史消息过滤:外部补推的历史消息不再触发 AI 自动处理(防止误建工单)", + "methods": [ + "inbox.push" + ], + "notes": [ + "inbox.push 新增可选参数 sendTime:消息原始发送时间(毫秒/秒时间戳或 ISO 字符串),由 warehouseMethods/inbox.js parseSendTime 统一规范化为毫秒", + "send_time 统一存入 wms_inbox_message.flags.send_time(毫秒),flags.send_time 与 sendTime 参数等价", + "processor.handleApiMessage 新增历史消息过滤:flags.skipAi=true 或 send_time 距今超过 config.inbox.historyMessageMaxAgeMs(默认 10 分钟)→ 跳过绑群与 AI 处理,不自动回复、不创建工单", + "未传 sendTime 的消息按实时消息处理,保持向后兼容", + "过滤点位于屏蔽检查之后、绑群码识别之前,仅拦截自动处理链路" + ], + "module": "inbox" + }, + { + "version": "2026-08-16-warehouse-01", + "date": "2026-08-16", + "type": "changed", + "summary": "统一通知系统接入仓库接口消息推送通道:收货完成/驳回/审核通知不再依赖 wms_notification_webhook 配置,按固定群订阅直接推送到仓库收货群与货主收货群", + "methods": [ + "notify.reply" + ], + "notes": [ + "新增 app/service/systems/warehouseNotify.js:仓库接口出站推送服务(MD5 签名 + wms_api_app.callback_url + wms_warehouse_log 日志),供统一通知复用", + "notice/index.js 新增 FIXED_GROUP_SUBSCRIPTIONS 固定订阅:receiving_completed / receiving_rejected / receiving_reviewed → warehouse:receiving + store:receiving(群类型定义见 inbox/groups.js GROUP_TYPES)", + "notice.send 支持 channel 路由:warehouse|group=走仓库接口通道(不查 webhook 配置)、webhook=默认订阅配置、both=双通道", + "receiving.js 三处通知(sendCompletionNotice/sendReviewNotice/rejectReceiving)已传 channel=warehouse,业务链路不再依赖 wms_notification_webhook 表", + "推送复用 notify.reply,data.type=system,data 仅携带 content(通知正文)与 ext_id(业务单号,幂等),接收方只处理 content", + "货主收货群匹配需要 store_id(来自收货单 receiving.store_id);无 store_id 或未配置群时仅推仓库收货群或静默跳过,不影响业务主流程" + ], + "module": "warehouse" + }, + { + "version": "2026-08-16-warehouse-02", + "date": "2026-08-16", + "type": "changed", + "summary": "统一通知全面迁移仓库接口通道:移除对 wms_notification_webhook 表的读取,全部事件默认经 wms_api_app 配置按固定群订阅推送", + "methods": [ + "notify.reply" + ], + "notes": [ + "notice.send 默认 channel 由 webhook 改为 warehouse:全部通知统一走仓库接口消息推送(wms_api_app.callback_url + 固定群订阅)", + "findMatchedWebhooks 移除 NotificationWebhook.findAll 数据库查询,webhook 通道仅支持调用方显式传入 hooks(channel=webhook 时)", + "FIXED_GROUP_SUBSCRIPTIONS 补齐全部事件:order_cancel_intercepted→warehouse:exception、order_sync_completed→store:after_sales(货主售后群,文案为每行一个订单:订单xx 姓名:xx 电话:xx 运单号:xx)、store_warehouse_print_quantity_adjusted→store:finance、storage_transfer_completed→warehouse:production、wave_strategy_quick_scan_failed→warehouse:exception", + "resolveSubjectConfig 增加 ctx.service 防御判断,兼容单元测试与最小上下文", + "test/app/service/systems/notice.test.js 适配新通道:webhook 行为用例改为显式 channel=webhook + hooks 入参,全部 12 用例通过" + ], + "module": "warehouse" + }, + { + "version": "2026-08-17-warehouse-01", + "date": "2026-08-17", + "type": "changed", + "summary": "订单同步通知去抖合并:订单同步完成后不再逐单立即通知,等待 3 分钟无新同步后按「仓库:货主」维度合并为一条消息统一推送到货主售后群", + "methods": [ + "notify.reply" + ], + "notes": [ + "order_async.js 新增合并队列:每次同步成功后把订单(单号/姓名/电话/运单号)写入 Redis(order_sync_notice:list:{warehouseId}:{storeId}),到期时间记录在 order_sync_notice:queue ZSET(最后一次同步 + 3 分钟)", + "新增定时任务 app/schedule/order_sync_notice_flush.js(每 30s,worker):扫描到期成员,加锁后原子 RENAME 取出列表,合并为「订单同步完成(共 N 单)+ 每单一行」的单条消息推送", + "发送失败重试:条目放回队列,2 分钟后重试,最多 5 次后放弃并记录错误日志;单条消息最多列 30 单,超出尾部提示「……其余 N 单未列出」", + "Redis 不可用或入队失败时回退为逐单立即通知(保持原有行为),订单同步流程不受影响", + "新增 test/app/service/systems/order_async.noticeDebounce.test.js:5 个用例覆盖入队不立即发、窗口内不冲刷、到期合并单条推送、多订单合并、发送失败重试" + ], + "module": "order" + }, + { + "version": "2026-08-17-warehouse-02", + "date": "2026-08-17", + "type": "removed", + "summary": "移除移库完成群通知:库存移库(transferLocation 按记录移库 / transferByProduct 按商品移库)完成后不再推送「移库操作完成/按商品移库操作完成」通知", + "methods": [ + "notify.reply" + ], + "notes": [ + "app/service/systems/storage/inventory.js 删除 transferLocation 与 transferByProduct 事务提交后的 notice.send 调用,移库业务本身不受影响", + "事件码 storage_transfer_completed 仍保留注册:app/schedule/notice_stock_remaining.js 库存余量每日提醒复用该事件码,固定群映射 warehouse:production 不变" + ], + "module": "storage" + }, + { + "version": "2026-08-17-warehouse-03", + "date": "2026-08-17", + "type": "changed", + "summary": "拦截通知无对应快递群时降级转发仓库异常群:拦截工单创建后若运单快递无售后群(或无快递接口),统一转发异常群并在内容前缀标记失败,与货主群缺失降级行为一致", + "methods": [ + "notify.reply" + ], + "notes": [ + "app/service/systems/afterSale.js createInterceptWorkOrdersAndNotify:按快递分组通知售后群时,无群/无接口的运单收集后统一推送到仓库异常群(group_type=warehouse + sub_type=exception + is_blocked=0)", + "降级内容格式:通知快递【快递名】失败\\n{快递名 运单号...}\\n拦截(前缀与货主群缺失降级的「通知货主【X】失败」一致)", + "仅成功通知快递群的工单升级 pending_feedback;降级到异常群的工单保持 pending,等待人工跟进" + ], + "module": "after_sale" + }, + { + "version": "2026-08-17-warehouse-04", + "date": "2026-08-17", + "type": "changed", + "summary": "收货完成/驳回不再通知货主:receiving_completed 与 receiving_rejected 固定订阅由「仓库收货群+货主收货群」改为仅仓库收货群,货主端快速查看链接不再生成", + "methods": [ + "notify.reply" + ], + "notes": [ + "notice/index.js FIXED_GROUP_SUBSCRIPTIONS:receiving_completed 与 receiving_rejected 均移除 store:receiving 目标,仅保留 warehouse:receiving", + "storage/receiving.js 完成通知移除 storeContent(货主侧 /storage/receiving_owner 链接),只生成仓库侧快速查看链接", + "receiving_reviewed 仍保持双群通知不变", + "e2e 用例 receiving_completed / receiving_rejected expectGroups 调整为仅 g_wh_receiving_debug_001" + ], + "module": "receiving" + }, + { + "version": "2026-08-17-warehouse-05", + "date": "2026-08-17", + "type": "changed", + "summary": "收货审核通知货主群三级回退:审核明细文件优先推货主收货群,无收货群推货主售后群,均无则降级仓库异常群", + "methods": [ + "notify.reply" + ], + "notes": [ + "FIXED_GROUP_SUBSCRIPTIONS.receiving_reviewed 的 store 目标新增 fallbackTargets(store:after_sales),主目标查询时 fallback 不参与,命中主目标则不推 fallback 群", + "sendToWarehouseChannel 支持 store 目标回退链:主目标未匹配时按 fallbackTargets 顺序逐级查找,命中即停止并视为货主群推送(使用 storeContent/storeId 关联)", + "回退链全部未匹配时沿用原有异常群降级(前缀「通知货主【X】失败」)", + "e2e 新增 receiving_reviewed_fallback_after_sales(货主 1000241,无收货群→售后群)与 receiving_reviewed_fallback_exception(货主 1000282,无收货群无售后群→异常群)两个用例" + ], + "module": "receiving" + }, + { + "version": "2026-08-17-warehouse-06", + "date": "2026-08-17", + "type": "added", + "summary": "新增收货单创建/首次绑定货主通知(receiving_store_bound):提醒货主收货进行中并确认车牌号/快递单号,路由与审核一致(货主收货群→售后群→异常群)", + "methods": [ + "notify.reply" + ], + "notes": [ + "新事件码 receiving_store_bound 注册(notification_webhook.js AVAILABLE_EVENTS 与 notice/index.js DEFAULT_REGISTERED_EVENT_CODES)", + "FIXED_GROUP_SUBSCRIPTIONS.receiving_store_bound:仅货主侧目标 store:receiving + fallbackTargets store:after_sales(回退链复用 sendToWarehouseChannel 通用逻辑)", + "storage/receiving.js 新增 sendStoreBoundNotice:内容「收货单号:Rxx 正在收货 / 请确认是否已填写车牌号或快递单号」+ 货主端快速查看链接(storeContent)", + "触发点:create(创建时已绑定货主)、bindStore(首次绑定)、updateReceivingStats(商品匹配后自动绑定),失败均不影响主流程", + "e2e 新增 receiving_store_bound(货主 1000000 → 货主收货群)与 receiving_store_bound_fallback_after_sales(货主 1000241 → 售后群)" + ], + "module": "receiving" + }, + { + "version": "2026-08-17-warehouse-07", + "date": "2026-08-17", + "type": "changed", + "summary": "补回 inbox 权限到操作角色:客服组主管/员工、仓库组主管/员工补齐消息和自动回复/群列表/消息记录页面与 inbox.* API 权限;上线时需执行 script/backfill-inbox-permissions.cjs", + "methods": [], + "notes": [ + "新增 script/backfill-inbox-permissions.cjs:按角色合并 inbox 权限 ID(491~503、531 共 14 项,含页面 492/493/494),支持 --dry-run / --role-ids", + "permissions='*' 的全量角色(超级管理员/经理/仓库管理员/货主管理员)自动跳过,原本即拥有", + "dev 库已回填:26 仓库组-主管、27 仓库组-员工、28 客服组-主管、30 客服组-员工" + ], + "module": "permission" + }, + { + "version": "2026-08-17-warehouse-08", + "date": "2026-08-17", + "type": "fixed", + "summary": "修复 receiving_store_bound 通知文案不感知车牌/快递单号:创建收货单时已填车牌仍提示「请确认是否已填写车牌号或快递单号」,改为已填写时展示已登记信息、未填写才提示补充", + "methods": [ + "notify.reply" + ], + "notes": [ + "sendStoreBoundNotice 根据 receiving.license_plate / receiving.tracking_number 动态生成第三行:已填车牌显示「车牌号:X 已登记」、已填快递单号显示「快递单号:X 已登记」、均未填才显示「请确认是否已填写车牌号或快递单号,未填写请及时补充」", + "三个触发点(create/bindStore/updateReceivingStats)的 receiving 快照均补充 license_plate / tracking_number 字段", + "背景:R20682003 创建时已写入车牌粤EH22E2,但通知为固定提醒文案导致货主误以为车牌未生效" + ], + "module": "receiving" + }, + { + "version": "2026-08-26-warehouse-01", + "date": "2026-08-26", + "type": "changed", + "summary": "调整 receiving_store_bound 通知模板:不再向货主发送「请确认是否已填写车牌号或快递单号,未填写请及时补充」提示,车牌号/快递单号未登记时展示「车牌号:无 / 快递单号:无」", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js sendStoreBoundNotice:车牌号/快递单号两行始终输出,已登记显示「车牌号:X 已登记」「快递单号:X 已登记」,未登记显示「车牌号:无」「快递单号:无」", + "notification_webhook.js AVAILABLE_EVENTS.receiving_store_bound 描述同步更新:展示车牌号/快递单号登记状态", + "背景:车牌号/快递单号由仓库侧登记,货主端无法填写,「请确认/及时补充」提示对货主无意义,改为直接展示登记状态" + ], + "module": "receiving" + }, + { + "version": "2026-08-26-warehouse-02", + "date": "2026-08-26", + "type": "added", + "summary": "新增收货完成未匹配商品货主通知(receiving_store_unmatched):收货单提交完成时存在未匹配商品明细,通知货主核实是否为新商品未推送资料", + "methods": [ + "notify.reply" + ], + "notes": [ + "新事件码 receiving_store_unmatched 注册(notification_webhook.js AVAILABLE_EVENTS 与 notice/index.js DEFAULT_REGISTERED_EVENT_CODES)", + "FIXED_GROUP_SUBSCRIPTIONS.receiving_store_unmatched:仅货主侧目标 store:receiving + fallbackTargets store:after_sales(与 receiving_store_bound 一致)", + "storage/receiving.js 新增 sendStoreUnmatchedNotice:内容「收货单号:xxx 提交完成收货,有未匹配商品资料 / 条码:1.xxx,2.xxx / 核实是否是新商品未推送资料 / 详情以及收货图片查看:货主端 receiving_owner 链接 / 如果没有账户请联系人工客服开通」", + "触发点:completeReceiving 事务提交后,unmatchedDetails 非空且已绑定货主时发送,失败不影响主流程" + ], + "module": "receiving" + }, + { + "version": "2026-08-26-warehouse-03", + "date": "2026-08-26", + "type": "changed", + "summary": "审核通过通知(receiving_reviewed)改为返回 Excel 审核明细下载链接,Excel 生成失败时回退正文展示全部明细(item_code 反查 stock_store)", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js 新增 resolveReviewDetailItemCodeMap:批量反查 wms_stock_store(stock_id=明细 system_product_id,delete_at 为空),返回 system_product_id → item_code 映射", + "sendReviewNotice 内容改为「收货单号:Rxx 完成收货审核 / 审核明细下载:Excel链接 / 请及时提交入库单入库」,标题改为完成收货审核;Excel 生成失败时回退正文展示全部明细(1.商品编码 名称 数量)", + "reviewReceiving 调整为先生成 Excel 再发一次通知(成功带下载链接,失败回退文字),替代原「先文字后文件」两次发送", + "item_code 反查不到时回退明细条码,仍无则显示未知编码" + ], + "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-01", + "date": "2026-08-28", + "type": "fixed", + "summary": "审核明细 Excel 文件名去中文(审核明细_ → receiving_review_),通知正文修正为「请及时提交入库单入库,入库单务必备注Rxx」,不再额外拼接明细文件行", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js reviewReceiving:Excel 上传文件名改为 receiving_review_{单号}.xlsx,URL 不再含中文,无需转码", + "sendReviewNotice:messageType 固定 text、不再传 url/fileName/mimeType,避免 notice 层追加「明细文件:文件名 链接」行;下载链接直接内嵌正文「审核明细下载:url」", + "正文末尾改为「请及时提交入库单入库,入库单务必备注Rxx」,接收方只处理 content 字段,链接以文本形式可见" + ], + "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-02", + "date": "2026-08-28", + "type": "fixed", + "summary": "审核明细商品编码反查增加兜底:无对应 wms_stock_store 时回退取 wms_stock_warehouse.item_code,避免部分商品无货主资料时编码缺失", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js resolveReviewDetailItemCodeMap:先按 stock_id 反查 wms_stock_store.item_code,未命中的 system_product_id 兜底查 wms_stock_warehouse(deleted_at 为空)取 item_code", + "两段反查均独立 try/catch,失败仅记日志不阻断审核通知主流程" + ], + "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-03", + "date": "2026-08-28", + "type": "fixed", + "summary": "notice 群推送链路补齐 ext_data 透传:查群带回群扩展数据,pushSystemMessage 落库与推送均携带,对齐 pushSystemNotification 已有方式", + "methods": [ + "notify.reply" + ], + "notes": [ + "systems/notice/index.js findSubscribedGroups 返回群对象新增 ext_data 字段(取 inbox_group.ext_data)", + "sendToWarehouseChannel 调 pushSystemMessage 时新增 extData=group.ext_data || null", + "systems/warehouseNotify.js pushSystemMessage 新增 extData 入参:wms_inbox_message outbound 行 ext_data 落库,notify.reply 推送体 data.ext_data 透传(与 processor.writeOutboundReply 一致)" + ], + "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-04", + "date": "2026-08-28", + "type": "fixed", + "summary": "修复通知消息幂等键吞消息:ext_id 加入事件维度,同一业务单不同事件各落一条 outbound 消息", + "methods": [ + "notify.reply" + ], + "notes": [ + "systems/notice/index.js sendToWarehouseChannel:extId 改为 businessId:event(同一收货单的创建/完成/审核事件各落一条 outbound 消息,不再被 sys:notice:{businessId}:{groupId} 幂等复用)", + "findSubscribedGroups 查询增加 ORDER BY id ASC,保证取群顺序稳定", + "systems/warehouseNotify.js:uniqueExtId 超过 VARCHAR(128) 时降级 md5 哈希兜底", + "线上案例:R20691023 审核消息因与「正在收货」共用 ext_id 被幂等吞掉,消息表无审核记录" + ], + "module": "receiving" + }, + { + "version": "2026-08-28-warehouse-05", + "date": "2026-08-28", + "type": "added", + "summary": "收货单创建/首次绑定货主通知(receiving_store_bound)新增收货人行:优先取 creator_snapshot 创建人姓名,回退当前操作人,无值显示无", + "methods": [ + "notify.reply" + ], + "notes": [ + "storage/receiving.js 新增 resolveReceivingCreatorName:解析 creator_snapshot(字符串 JSON 或对象)取 name/employees_name/real_name,回退 ctx.user.employees_name", + "sendStoreBoundNotice 模板在车牌/快递行后增加「收货人:姓名/无」,修复线上显示「收货人:{}」的空对象问题", + "三个触发点(create/bindStore/updateReceivingStats)的 receiving 快照均补充 creator_snapshot 字段" + ], + "module": "receiving" + } +] diff --git a/methods/gateway.json b/methods/gateway.json new file mode 100644 index 0000000..c39b061 --- /dev/null +++ b/methods/gateway.json @@ -0,0 +1,239 @@ +{ + "module": "gateway", + "description": "内部网关接口,供内网系统间调用,统一使用 POST 请求", + "version": "0.2.0", + "updatedAt": "2026-03-29", + "headers": [], + "methods": { + "groups": [ + { + "groupName": "用户模块", + "module": "user", + "list": [ + { + "method": "user.getUserByTempCode", + "description": "根据绑定码反查WMS账号ID并写入扫码状态(扫描即视为已确认,状态缓存3分钟)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" + } + ], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "匹配到的 WMS 账号ID" + }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "WMS 账号表中的真实姓名,用于扫码绑定前确认账号" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "当前扫码状态,成功扫码后固定为 scanned" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 scan-cache" + } + ], + "errors": [] + }, + { + "method": "user.bindAccountByTempCode", + "description": "根据绑定码对应的扫码状态缓存将 ye4s 用户绑定到 WMS 账号(需先调用扫码反查接口)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": true, + "source": "body", + "description": "ye4s 用户ID(例如扫码用户ID)" + } + ], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "绑定目标 WMS 账号ID" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": true, + "description": "被绑定的 ye4s 用户ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "绑定状态,固定为 bound" + } + ], + "errors": [] + } + ] + }, + { + "groupName": "打印绑定模块", + "module": "print", + "list": [ + { + "method": "print.getBindInfo", + "description": "根据 WMS 账号ID和扫码 code 返回可绑定仓库列表;有可绑定仓库时下发 300 秒临时凭据 tempCode,无可绑定仓库时返回空数组且不返回 tempCode", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "WMS 账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "打印端提供的绑定 code" + } + ], + "response": [ + { + "name": "warehouses", + "type": "array", + "required": true, + "description": "可绑定仓库列表,元素结构为 { id, name }" + }, + { + "name": "tempCode", + "type": "string", + "required": false, + "description": "临时绑定凭据,仅当 warehouses 非空时返回" + } + ], + "errors": [ + { + "code": 0, + "message": "缺少有效参数 account_id 或 code" + }, + { + "code": 0, + "message": "账号不存在或已禁用" + }, + { + "code": 0, + "message": "无效code或未绑定" + } + ] + }, + { + "method": "print.bindByTempCode", + "description": "根据第一步返回的临时凭据执行打印台绑定,提交工作台名称和仓库ID后完成真实绑定", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "temp_code", + "type": "string", + "required": true, + "source": "body", + "description": "第一步返回的临时凭据,300 秒有效" + }, + { + "name": "printer", + "type": "string", + "required": true, + "source": "body", + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID" + } + ], + "response": [ + { + "name": "code", + "type": "string", + "required": true, + "description": "真实绑定 code" + }, + { + "name": "printer", + "type": "string", + "required": true, + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "computerId", + "type": "number", + "required": true, + "description": "打印台电脑ID" + } + ], + "errors": [ + { + "code": 0, + "message": "参数缺失" + }, + { + "code": 0, + "message": "临时code无效或已过期" + }, + { + "code": 0, + "message": "仓库无绑定权限" + }, + { + "code": 0, + "message": "仓库id校验失败" + }, + { + "code": 0, + "message": "该仓库下打印台名称已存在且可用" + } + ] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/methods/inbox-callback.json b/methods/inbox-callback.json new file mode 100644 index 0000000..dd745ac --- /dev/null +++ b/methods/inbox-callback.json @@ -0,0 +1,261 @@ +{ + "module": "inbox-callback", + "description": "站内信模块出站回调定义。WMS 处理入站消息后,通过 HTTP POST 将回复推送到仓库 ApiApp 配置的 callback_url(interface_type_id=3),供外部适配器消费并投递到实际聊天通道。回调体统一包裹:{ method, code, data }。", + "version": "1.1.0", + "updatedAt": "2026-08-07", + "http": { + "path": "{ApiApp.callback_url}", + "method": "POST" + }, + "headers": [ + { + "name": "Content-Type", + "type": "string", + "required": true, + "description": "application/json" + } + ], + "methods": { + "groups": [ + { + "groupName": "AI 自动回复", + "module": "ai_reply", + "list": [ + { + "method": "inbox.callback.ai_reply", + "description": "AI 自动回复回调。用户发送消息后,DeepSeek 推理给出回复内容,WMS 推送到外部聊天通道。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "content 为 AI 生成的纯文本(含 \\n 换行,禁止 Markdown)", + "ext_id 与入站消息相同,外部系统可据此关联对话", + "若 AI 判定无需回复(silent),不会触发此回调", + "ai_thoughts 字段记录整个推理链(仅限出站记录查询,不入回调)" + ], + "example": { + "method": "inbox.callback.ai_reply", + "code": 200, + "data": { + "source": "ai_reply", + "content": "条码6900000000016查到2款商品:\n1. 披肩-消退 可用0\n2. 披肩 可用0(总量95已锁定)\n均无可用库存,建议更换商品。", + "ext_id": "api:AK001:req-123", + "ext_data": { + "request_id": "req-123" + }, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "绑群确认", + "module": "bind_confirm", + "list": [ + { + "method": "inbox.callback.bind_confirm", + "description": "绑群确认回调。用户发送「授权:CODE」后,WMS 校验成功/失败/已绑定,推送绑群结果。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "成功 content:绑定「{货主备注名}」成功", + "失败 content:绑群码无效或已过期,请重新生成", + "已绑定 content:已在绑定状态,无需重复操作", + "绑定成功后自动追加 inbox.callback.balance 返回面单余额" + ], + "example": { + "method": "inbox.callback.bind_confirm", + "code": 200, + "data": { + "source": "bind_confirm", + "content": "绑定「测试货主1111」成功", + "ext_id": "api:AK001:req-456", + "ext_data": null, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "面单余额", + "module": "balance", + "list": [ + { + "method": "inbox.callback.balance", + "description": "面单余额回调。绑群成功后自动查询,或用户主动查询时推送面单余额。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "content 格式:面单余额:总量 {print_quantity},已锁定 {print_quantity_locked},可用 {available}", + "ext_id 为 {原ext_id}:balance 后缀,避免与绑群确认回执冲突", + "余额查询失败时 content:面单余额查询失败:{错误原因}" + ], + "example": { + "method": "inbox.callback.balance", + "code": 200, + "data": { + "source": "balance", + "content": "面单余额:总量 5000,已锁定 200,可用 4800", + "ext_id": "api:AK001:req-456:balance", + "ext_data": null, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "异常兜底", + "module": "error", + "list": [ + { + "method": "inbox.callback.error", + "description": "异常兜底回调。AI 5轮推理均失败或系统异常时的兜底回复。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "content 为固定兜底文案:抱歉,暂时无法处理您的请求,请稍后重试", + "出站前仍写入 wms_inbox_message.outbound 记录" + ], + "example": { + "method": "inbox.callback.error", + "code": 200, + "data": { + "source": "error", + "content": "抱歉,暂时无法处理您的请求,请稍后重试", + "ext_id": "api:AK001:req-789", + "ext_data": null, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "通用说明", + "module": "common", + "list": [ + { + "method": "inbox.callback.common", + "description": "所有回调类型共有字段说明及路由指引。外部适配器根据 method 字段路由到不同处理逻辑。", + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "body", + "description": "回调方法名,固定格式 inbox.callback.{source},外部适配器据此路由" + }, + { + "name": "code", + "type": "number", + "required": true, + "source": "body", + "description": "状态码,正常回调固定 200" + }, + { + "name": "data.source", + "type": "string", + "required": true, + "source": "body", + "description": "消息来源:ai_reply / bind_confirm / balance / error" + }, + { + "name": "data.content", + "type": "string", + "required": true, + "source": "body", + "description": "回复正文(纯文本,含 \\n 换行)" + }, + { + "name": "data.ext_id", + "type": "string", + "required": true, + "source": "body", + "description": "原始入站消息ID,关联对话链" + }, + { + "name": "data.ext_data", + "type": "object", + "required": false, + "source": "body", + "description": "入站透传数据,原路带回" + }, + { + "name": "data.group_id", + "type": "string", + "required": true, + "source": "body", + "description": "外部群ID" + }, + { + "name": "data.user_id", + "type": "string", + "required": true, + "source": "body", + "description": "外部用户ID" + }, + { + "name": "data.group_name", + "type": "string", + "required": true, + "source": "body", + "description": "群名称" + }, + { + "name": "data.user_name", + "type": "string", + "required": true, + "source": "body", + "description": "用户名称" + }, + { + "name": "data.timestamp", + "type": "number", + "required": true, + "source": "body", + "description": "出站 Unix 时间戳(秒)" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "HTTP 200 表示回调成功,WMS 更新 push_status=2" + } + ], + "errors": [], + "notes": [ + "回调由 app/service/inbox/processor.js → writeOutboundReply() / handleApiMessage 发起", + "callback_url 配置:wms_api_app.interface_type_id=3 AND is_enabled=1", + "超时 10 秒,失败不影响消息记录写入", + "HTTP 200 → 更新出站+入站 push_status=2(已送达)" + ] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/methods/openapi.json b/methods/openapi.json new file mode 100644 index 0000000..1b7364a --- /dev/null +++ b/methods/openapi.json @@ -0,0 +1,2349 @@ +{ + "module": "openapi", + "description": "开放 API 统一入口,独立链路,HTTP POST /openapi,记录入口校验/鉴权规则与返回格式。", + "version": "1.2.5", + "updatedAt": "2026-09-14", + "http": { + "path": "/openapi", + "method": "POST" + }, + "headers": [], + "methods": { + "groups": [ + { + "groupName": "基础模块", + "module": "index", + "list": [ + { + "method": "index.ping", + "description": "基础模块 心跳接口,返回服务可用性(部署在 openapiMethods 中)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功通常为 200 或 1" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "返回数据,ping 一般为空或包含版本/uptime 等信息" + } + ], + "errors": [], + "notes": [ + "模块:基础模块", + "方法部署位置:openapiMethods/index.ping", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "发货单模块", + "module": "deliveryorder", + "list": [ + { + "method": "deliveryorder.create", + "description": "deliveryorder 模块 创建发货单接口,支持传入订单主信息、收件人信息和订单明细", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "发货单主信息对象" + }, + { + "name": "deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),外部系统的唯一订单号" + }, + { + "name": "deliveryOrder.preDeliveryOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "前发货单编码,用于关联前置订单" + }, + { + "name": "deliveryOrder.preDeliveryOrderId", + "type": "string", + "required": false, + "source": "body", + "description": "前发货单ID,用于关联前置订单" + }, + { + "name": "deliveryOrder.orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,如 JYCK(一般出库)、PTCK(普通出库)等" + }, + { + "name": "deliveryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码,用于指定发货仓库" + }, + { + "name": "deliveryOrder.orderFlag", + "type": "string", + "required": false, + "source": "body", + "description": "订单标记,自定义标记位" + }, + { + "name": "deliveryOrder.sourcePlatformCode", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台编码,如 TB(淘宝)、JD(京东)、PDD(拼多多)等;匹配不到时自动使用货主默认平台" + }, + { + "name": "deliveryOrder.sourcePlatformName", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台名称" + }, + { + "name": "deliveryOrder.createTime", + "type": "string", + "required": false, + "source": "body", + "description": "订单创建时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.placeOrderTime", + "type": "string", + "required": false, + "source": "body", + "description": "下单时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.payTime", + "type": "string", + "required": false, + "source": "body", + "description": "支付时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.payNo", + "type": "string", + "required": false, + "source": "body", + "description": "支付单号" + }, + { + "name": "deliveryOrder.shopNick", + "type": "string", + "required": false, + "source": "body", + "description": "店铺昵称" + }, + { + "name": "deliveryOrder.sellerNick", + "type": "string", + "required": false, + "source": "body", + "description": "卖家昵称" + }, + { + "name": "deliveryOrder.buyerNick", + "type": "string", + "required": false, + "source": "body", + "description": "买家昵称" + }, + { + "name": "deliveryOrder.operatorName", + "type": "string", + "required": false, + "source": "body", + "description": "操作人姓名,未传入时自动按 API 应用名称回填" + }, + { + "name": "deliveryOrder.operateTime", + "type": "string", + "required": false, + "source": "body", + "description": "操作时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.totalAmount", + "type": "number", + "required": false, + "source": "body", + "description": "订单总金额" + }, + { + "name": "deliveryOrder.itemAmount", + "type": "number", + "required": false, + "source": "body", + "description": "商品总金额" + }, + { + "name": "deliveryOrder.discountAmount", + "type": "number", + "required": false, + "source": "body", + "description": "折扣金额" + }, + { + "name": "deliveryOrder.freight", + "type": "number", + "required": false, + "source": "body", + "description": "运费" + }, + { + "name": "deliveryOrder.arAmount", + "type": "number", + "required": false, + "source": "body", + "description": "应收金额" + }, + { + "name": "deliveryOrder.gotAmount", + "type": "number", + "required": false, + "source": "body", + "description": "实收金额" + }, + { + "name": "deliveryOrder.logisticsCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递编码,用于指定物流公司;匹配不到时自动使用货主默认快递" + }, + { + "name": "deliveryOrder.expressCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递公司编码" + }, + { + "name": "deliveryOrder.logisticsAreaCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递区域编码" + }, + { + "name": "deliveryOrder.isUrgency", + "type": "string", + "required": false, + "source": "body", + "description": "是否加急,Y=是,N=否,默认 N" + }, + { + "name": "deliveryOrder.invoiceFlag", + "type": "string", + "required": false, + "source": "body", + "description": "是否需要发票,Y=是,N=否,默认 N" + }, + { + "name": "deliveryOrder.enableExternalExpressCode", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否启用外部快递编码匹配,开启后将优先按传入的 logisticsCode 匹配快递设置表" + }, + { + "name": "deliveryOrder.receiverInfo", + "type": "object", + "required": false, + "source": "body", + "description": "收件人信息对象" + }, + { + "name": "deliveryOrder.receiverInfo.name", + "type": "string", + "required": true, + "source": "body", + "description": "收件人姓名" + }, + { + "name": "deliveryOrder.receiverInfo.tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人固定电话" + }, + { + "name": "deliveryOrder.receiverInfo.mobile", + "type": "string", + "required": true, + "source": "body", + "description": "收件人手机号码" + }, + { + "name": "deliveryOrder.receiverInfo.email", + "type": "string", + "required": false, + "source": "body", + "description": "收件人邮箱" + }, + { + "name": "deliveryOrder.receiverInfo.countryCode", + "type": "string", + "required": false, + "source": "body", + "description": "国家编码" + }, + { + "name": "deliveryOrder.receiverInfo.province", + "type": "string", + "required": true, + "source": "body", + "description": "省份" + }, + { + "name": "deliveryOrder.receiverInfo.city", + "type": "string", + "required": true, + "source": "body", + "description": "城市" + }, + { + "name": "deliveryOrder.receiverInfo.area", + "type": "string", + "required": true, + "source": "body", + "description": "区县" + }, + { + "name": "deliveryOrder.receiverInfo.town", + "type": "string", + "required": false, + "source": "body", + "description": "乡镇/街道" + }, + { + "name": "deliveryOrder.receiverInfo.detailAddress", + "type": "string", + "required": true, + "source": "body", + "description": "详细地址" + }, + { + "name": "deliveryOrder.receiverInfo.zipCode", + "type": "string", + "required": false, + "source": "body", + "description": "邮政编码" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "订单明细对象,包含 orderLine 数组" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "source": "body", + "description": "订单明细列表,数组中每项为一个订单行对象" + }, + { + "name": "[].orderLine.itemCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品编码,与 itemId 二选一,用于匹配仓库中的商品" + }, + { + "name": "[].orderLine.itemId", + "type": "number", + "required": false, + "source": "body", + "description": "仓库商品主键ID,与 itemCode 二选一" + }, + { + "name": "[].orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称,用于错误提示中的商品识别" + }, + { + "name": "[].orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划发货数量(必填),必须大于 0" + }, + { + "name": "[].orderLine.actualPrice", + "type": "number", + "required": false, + "source": "body", + "description": "实际单价" + }, + { + "name": "[].orderLine.retailPrice", + "type": "number", + "required": false, + "source": "body", + "description": "零售单价" + }, + { + "name": "[].orderLine.extCode", + "type": "string", + "required": false, + "source": "body", + "description": "外部商品编码" + }, + { + "name": "[].orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,如 ZP(正品)、CC(残次品)" + }, + { + "name": "[].orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "订单行号,未传入时自动按序号生成(1、2、3...)" + }, + { + "name": "[].orderLine.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码" + }, + { + "name": "[].orderLine.sourceOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "来源订单编码,用于关联上游订单" + }, + { + "name": "[].orderLine.subSourceOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "子来源订单编码" + }, + { + "name": "[].orderLine.extendProps", + "type": "string", + "required": false, + "source": "body", + "description": "扩展属性,JSON 字符串或对象,用于存储自定义字段" + } + ], + "requestBody": [ + { + "name": "deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "发货单主信息对象" + }, + { + "name": "deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),外部系统的唯一订单号" + }, + { + "name": "deliveryOrder.preDeliveryOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "前发货单编码,用于关联前置订单" + }, + { + "name": "deliveryOrder.preDeliveryOrderId", + "type": "string", + "required": false, + "source": "body", + "description": "前发货单ID,用于关联前置订单" + }, + { + "name": "deliveryOrder.orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,如 JYCK(一般出库)、PTCK(普通出库)等" + }, + { + "name": "deliveryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码,用于指定发货仓库" + }, + { + "name": "deliveryOrder.orderFlag", + "type": "string", + "required": false, + "source": "body", + "description": "订单标记,自定义标记位" + }, + { + "name": "deliveryOrder.sourcePlatformCode", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台编码,如 TB(淘宝)、JD(京东)、PDD(拼多多)等;匹配不到时自动使用货主默认平台" + }, + { + "name": "deliveryOrder.sourcePlatformName", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台名称" + }, + { + "name": "deliveryOrder.createTime", + "type": "string", + "required": false, + "source": "body", + "description": "订单创建时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.placeOrderTime", + "type": "string", + "required": false, + "source": "body", + "description": "下单时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.payTime", + "type": "string", + "required": false, + "source": "body", + "description": "支付时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.payNo", + "type": "string", + "required": false, + "source": "body", + "description": "支付单号" + }, + { + "name": "deliveryOrder.shopNick", + "type": "string", + "required": false, + "source": "body", + "description": "店铺昵称" + }, + { + "name": "deliveryOrder.sellerNick", + "type": "string", + "required": false, + "source": "body", + "description": "卖家昵称" + }, + { + "name": "deliveryOrder.buyerNick", + "type": "string", + "required": false, + "source": "body", + "description": "买家昵称" + }, + { + "name": "deliveryOrder.operatorName", + "type": "string", + "required": false, + "source": "body", + "description": "操作人姓名,未传入时自动按 API 应用名称回填" + }, + { + "name": "deliveryOrder.operateTime", + "type": "string", + "required": false, + "source": "body", + "description": "操作时间,支持 ISO 8601 格式" + }, + { + "name": "deliveryOrder.totalAmount", + "type": "number", + "required": false, + "source": "body", + "description": "订单总金额" + }, + { + "name": "deliveryOrder.itemAmount", + "type": "number", + "required": false, + "source": "body", + "description": "商品总金额" + }, + { + "name": "deliveryOrder.discountAmount", + "type": "number", + "required": false, + "source": "body", + "description": "折扣金额" + }, + { + "name": "deliveryOrder.freight", + "type": "number", + "required": false, + "source": "body", + "description": "运费" + }, + { + "name": "deliveryOrder.arAmount", + "type": "number", + "required": false, + "source": "body", + "description": "应收金额" + }, + { + "name": "deliveryOrder.gotAmount", + "type": "number", + "required": false, + "source": "body", + "description": "实收金额" + }, + { + "name": "deliveryOrder.logisticsCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递编码,用于指定物流公司;匹配不到时自动使用货主默认快递" + }, + { + "name": "deliveryOrder.expressCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递公司编码" + }, + { + "name": "deliveryOrder.logisticsAreaCode", + "type": "string", + "required": false, + "source": "body", + "description": "快递区域编码" + }, + { + "name": "deliveryOrder.isUrgency", + "type": "string", + "required": false, + "source": "body", + "description": "是否加急,Y=是,N=否,默认 N" + }, + { + "name": "deliveryOrder.invoiceFlag", + "type": "string", + "required": false, + "source": "body", + "description": "是否需要发票,Y=是,N=否,默认 N" + }, + { + "name": "deliveryOrder.enableExternalExpressCode", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否启用外部快递编码匹配,开启后将优先按传入的 logisticsCode 匹配快递设置表" + }, + { + "name": "deliveryOrder.receiverInfo", + "type": "object", + "required": false, + "source": "body", + "description": "收件人信息对象" + }, + { + "name": "deliveryOrder.receiverInfo.name", + "type": "string", + "required": true, + "source": "body", + "description": "收件人姓名" + }, + { + "name": "deliveryOrder.receiverInfo.tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人固定电话" + }, + { + "name": "deliveryOrder.receiverInfo.mobile", + "type": "string", + "required": true, + "source": "body", + "description": "收件人手机号码" + }, + { + "name": "deliveryOrder.receiverInfo.email", + "type": "string", + "required": false, + "source": "body", + "description": "收件人邮箱" + }, + { + "name": "deliveryOrder.receiverInfo.countryCode", + "type": "string", + "required": false, + "source": "body", + "description": "国家编码" + }, + { + "name": "deliveryOrder.receiverInfo.province", + "type": "string", + "required": true, + "source": "body", + "description": "省份" + }, + { + "name": "deliveryOrder.receiverInfo.city", + "type": "string", + "required": true, + "source": "body", + "description": "城市" + }, + { + "name": "deliveryOrder.receiverInfo.area", + "type": "string", + "required": true, + "source": "body", + "description": "区县" + }, + { + "name": "deliveryOrder.receiverInfo.town", + "type": "string", + "required": false, + "source": "body", + "description": "乡镇/街道" + }, + { + "name": "deliveryOrder.receiverInfo.detailAddress", + "type": "string", + "required": true, + "source": "body", + "description": "详细地址" + }, + { + "name": "deliveryOrder.receiverInfo.zipCode", + "type": "string", + "required": false, + "source": "body", + "description": "邮政编码" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "订单明细对象,包含 orderLine 数组" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "source": "body", + "description": "订单明细列表,数组中每项为一个订单行对象" + }, + { + "name": "[].orderLine.itemCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品编码,与 itemId 二选一,用于匹配仓库中的商品" + }, + { + "name": "[].orderLine.itemId", + "type": "number", + "required": false, + "source": "body", + "description": "仓库商品主键ID,与 itemCode 二选一" + }, + { + "name": "[].orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称,用于错误提示中的商品识别" + }, + { + "name": "[].orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划发货数量(必填),必须大于 0" + }, + { + "name": "[].orderLine.actualPrice", + "type": "number", + "required": false, + "source": "body", + "description": "实际单价" + }, + { + "name": "[].orderLine.retailPrice", + "type": "number", + "required": false, + "source": "body", + "description": "零售单价" + }, + { + "name": "[].orderLine.extCode", + "type": "string", + "required": false, + "source": "body", + "description": "外部商品编码" + }, + { + "name": "[].orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,如 ZP(正品)、CC(残次品)" + }, + { + "name": "[].orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "订单行号,未传入时自动按序号生成(1、2、3...)" + }, + { + "name": "[].orderLine.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码" + }, + { + "name": "[].orderLine.sourceOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "来源订单编码,用于关联上游订单" + }, + { + "name": "[].orderLine.subSourceOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "子来源订单编码" + }, + { + "name": "[].orderLine.extendProps", + "type": "string", + "required": false, + "source": "body", + "description": "扩展属性,JSON 字符串或对象,用于存储自定义字段" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "创建成功时返回 orderId、step、stats(items_count/item_total/items_weight/source_order_codes)等" + } + ], + "errors": [ + { + "code": 400, + "message": "订单信息不完整(deliveryOrder.deliveryOrderCode 缺失)" + }, + { + "code": 400, + "message": "没有有效的订单明细数据(orderLines.orderLine 为空或数量 ≤0)" + }, + { + "code": 400, + "message": "商品《xxx》编码《xxx》未同步推送到仓库" + }, + { + "code": 409, + "message": "订单已存在(相同 deliveryOrderCode + store_id + warehouse_id)" + } + ], + "notes": [ + "模块:deliveryorder 模块", + "方法部署位置:openapiMethods/deliveryorder.create", + "创建渠道固定为 API,操作人未传入时自动按 API 应用名称回填", + "sourcePlatformCode 传入后优先匹配平台列表;匹配不到则使用货主默认平台", + "logisticsCode 传入后按快递设置表 → 快递列表 → 货主默认快递的优先级匹配", + "orderLines.orderLine 支持单对象或数组格式", + "同一订单中不允许重复的商品(按 itemId 去重)", + "返回的 data.orderId 为系统内部订单主键ID", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400", + "receiverInfo.name / mobile / province / city / area / detailAddress 为快递取号必填字段,请务必传入完整收件人信息", + "mobile 和 tel 二选一必填(快递取号需要至少一个联系电话)" + ] + }, + { + "method": "deliveryorder.query", + "description": "deliveryorder 模块 查询发货单接口,根据发货单编码返回订单详情", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),要查询的订单号" + } + ], + "requestBody": [ + { + "name": "deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(必填),要查询的订单号" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 totalLines、deliveryOrder(deliveryOrderCode/deliveryOrderId/warehouseCode/orderType/status/orderConfirmTime/operatorCode/operatorName/operateTime)、packages、orderLines" + } + ], + "errors": [ + { + "code": 400, + "message": "deliveryOrderCode 参数缺失" + }, + { + "code": 404, + "message": "未找到订单" + } + ], + "notes": [ + "模块:deliveryorder 模块", + "方法部署位置:openapiMethods/deliveryorder.query", + "查询范围为当前 app_key 绑定的仓库,跨仓库订单无法查询", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "订单模块", + "module": "order", + "list": [ + { + "method": "order.cancel", + "description": "order 模块 取消单据接口,按 orderType 分发:JYCK/HHCK/BFCK 取消发货单(wms_order_delivery,未拣货/未打印直接取消,已拣货/已打印改拦截);CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)按 orderCode 查出库单号取消出库单(wms_order_stockout,仅 CREATED/PENDING 可取消);RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)按 orderCode 查入库单号作废入库单(复用 ctx.service.systems.storage.entry.cancel,状态守卫 + 回退收货单占用 + 操作日志,不回传开放平台回调事件);其他类型返回暂不支持该订单类型的取消操作", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "orderCode", + "type": "string", + "required": true, + "source": "body", + "description": "单据编码(必填):JYCK/HHCK/BFCK 为发货单编码(delivery_order_code);CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)为出库单号(stockout_order_code);RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)为入库单号(entry_order_code)" + }, + { + "name": "orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,默认 JYCK(一般交易出库单);支持 JYCK(一般交易出库)/HHCK(换货出库)/BFCK(补发出库)+ CK 组 PTCK(普通出库单)/DBCK(调拨出库)/B2BCK(B2B出库)/QTCK(其他出库)/CGTH(采购退货出库单)+ RK 组 B2BRK(B2B入库)/SCRK(生产入库)/LYRK(领用入库)/CCRK(残次品入库)/CGRK(采购入库)/DBRK(调拨入库)/QTRK(其他入库);大小写不敏感(内部 trim 后转大写)" + } + ], + "requestBody": [ + { + "name": "orderCode", + "type": "string", + "required": true, + "source": "body", + "description": "单据编码(必填):JYCK/HHCK/BFCK 为发货单编码(delivery_order_code);CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)为出库单号(stockout_order_code);RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)为入库单号(entry_order_code)" + }, + { + "name": "orderType", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型,默认 JYCK(一般交易出库单);支持 JYCK(一般交易出库)/HHCK(换货出库)/BFCK(补发出库)+ CK 组 PTCK(普通出库单)/DBCK(调拨出库)/B2BCK(B2B出库)/QTCK(其他出库)/CGTH(采购退货出库单)+ RK 组 B2BRK(B2B入库)/SCRK(生产入库)/LYRK(领用入库)/CCRK(残次品入库)/CGRK(采购入库)/DBRK(调拨入库)/QTRK(其他入库);大小写不敏感(内部 trim 后转大写)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "取消成功时可能包含订单状态信息;CK 组取消成功返回 id / stockout_order_code / order_status" + } + ], + "errors": [ + { + "code": 400, + "message": "orderCode 参数缺失" + }, + { + "code": 400, + "message": "暂不支持该订单类型的取消操作" + }, + { + "code": 404, + "message": "未找到对应的订单" + }, + { + "code": 404, + "message": "未找到对应的出库单" + }, + { + "code": 400, + "message": "出库单当前状态(xxx)不允许取消(仅 CREATED/PENDING 可取消)" + }, + { + "code": 400, + "message": "取消失败:xxx(CK 组释放库存锁定等异常)" + }, + { + "code": 409, + "message": "取消失败,已通知拦截执行(订单已拣货或已打印,改为拦截状态)" + }, + { + "code": 0, + "message": "未找到对应的入库单" + }, + { + "code": 0, + "message": "已完成入库单不允许作废" + }, + { + "code": 0, + "message": "入库单已完成回传,不可取消" + } + ], + "notes": [ + "模块:order 模块", + "方法部署位置:openapiMethods/order.cancel", + "JYCK/HHCK/BFCK 取消逻辑:未拣货且未打印的订单直接取消(status=cancel, outbound_status=fin, step=4);已拣货或已打印的订单标记为拦截状态(intercept_status=intercepting),不直接取消", + "订单类型映射:JYCK/HHCK/BFCK → wms_order_delivery 发货单取消(行为与历史完全一致);PTCK/DBCK/B2BCK/QTCK/CGTH(CK 组)→ wms_order_stockout 出库单取消(按 orderCode 查出库单号);B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK(RK 组)→ 入库单作废(按 orderCode 查入库单号,复用 ctx.service.systems.storage.entry.cancel);其他类型返回暂不支持该订单类型的取消操作", + "CK 组委托 ctx.service.systems.stockoutOrder.cancel(单事务 + 行锁):仅 CREATED/PENDING 允许取消(COMPLETED/TRANSFERRED 拒绝),释放 QM_STOCKOUT 库存锁定,状态置 CANCELLED 并写 wms_operation_log(STOCKOUT_CANCEL);已 CANCELLED 幂等返回成功;取消成功不回传开放平台回调事件", + "RK 组委托 ctx.service.systems.storage.entry.cancel({ entryOrderCode }, { storeId, warehouseId, operatorLabel=openapi:xxx, skipExternalSync=true, idempotent=true, notFoundMessage=未找到对应的入库单 }):守卫 sync_status=SUCCESS(入库单已完成回传,不可取消)、order_status=COMPLETED(已完成入库单不允许作废);已 CANCELLED 幂等返回成功;作废动作 = 状态置 CANCELLED + 按台账回退关联收货单占用 + 写 ENTRY_ORDER_CANCEL 操作日志;skipExternalSync=true 不回传开放平台回调事件", + "复现口径:orderCode=RK_2、orderType=CGRK 现在可正常取消(此前返回暂不支持该订单类型的取消操作)", + "orderType 大小写不敏感:内部 trim 后转大写,jyck/Jyck/JYCK 等价", + "使用事务 + 行锁保证并发安全", + "取消操作为不可逆操作,请谨慎调用", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "商品模块", + "module": "singleitem", + "list": [ + { + "method": "singleitem.synchronize", + "description": "singleitem 模块 商品同步接口,创建或更新商品信息(itemCode 唯一约束,已存在则更新)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "item", + "type": "object", + "required": true, + "source": "body", + "description": "商品信息对象(必填)" + }, + { + "name": "item.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码(必填),唯一标识商品" + }, + { + "name": "item.goodsCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品货号" + }, + { + "name": "item.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称" + }, + { + "name": "item.skuProperty", + "type": "string", + "required": false, + "source": "body", + "description": "SKU 属性描述,如颜色:红色;尺码:XL" + }, + { + "name": "item.stockUnit", + "type": "string", + "required": false, + "source": "body", + "description": "库存单位,如 件、箱、个" + }, + { + "name": "item.length", + "type": "number", + "required": false, + "source": "body", + "description": "长(cm)" + }, + { + "name": "item.width", + "type": "number", + "required": false, + "source": "body", + "description": "宽(cm)" + }, + { + "name": "item.height", + "type": "number", + "required": false, + "source": "body", + "description": "高(cm)" + }, + { + "name": "item.volume", + "type": "number", + "required": false, + "source": "body", + "description": "体积(cm³)" + }, + { + "name": "item.grossWeight", + "type": "number", + "required": false, + "source": "body", + "description": "毛重(g)" + }, + { + "name": "item.netWeight", + "type": "number", + "required": false, + "source": "body", + "description": "净重(g)" + }, + { + "name": "item.categoryId", + "type": "number", + "required": false, + "source": "body", + "description": "商品分类 ID" + }, + { + "name": "item.categoryName", + "type": "string", + "required": false, + "source": "body", + "description": "商品分类名称" + }, + { + "name": "item.itemType", + "type": "string", + "required": false, + "source": "body", + "description": "商品类型,如 NORMAL(普通商品)、SUIT(套装)" + }, + { + "name": "item.tagPrice", + "type": "number", + "required": false, + "source": "body", + "description": "吊牌价" + }, + { + "name": "item.retailPrice", + "type": "number", + "required": false, + "source": "body", + "description": "零售价" + }, + { + "name": "item.brandName", + "type": "string", + "required": false, + "source": "body", + "description": "品牌名称" + }, + { + "name": "item.isSNMgmt", + "type": "string", + "required": false, + "source": "body", + "description": "是否 SN 序列号管理,Y=是,N=否,默认 N" + }, + { + "name": "item.isShelfLifeMgmt", + "type": "string", + "required": false, + "source": "body", + "description": "是否保质期管理,Y=是,N=否,默认 N" + }, + { + "name": "item.isBatchMgmt", + "type": "string", + "required": false, + "source": "body", + "description": "是否批次管理,Y=是,N=否,默认 N" + }, + { + "name": "item.isAreaSale", + "type": "string", + "required": false, + "source": "body", + "description": "是否区域销售,Y=是,N=否,默认 N" + }, + { + "name": "item.createTime", + "type": "string", + "required": false, + "source": "body", + "description": "创建时间,ISO 8601 格式" + }, + { + "name": "item.isValid", + "type": "string", + "required": false, + "source": "body", + "description": "是否有效,Y=是,N=否,默认 Y" + }, + { + "name": "item.barCode", + "type": "string", + "required": false, + "source": "body", + "description": "条形码" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "同步成功时返回 itemId(系统内部商品 ID)" + } + ], + "errors": [ + { + "code": 400, + "message": "参数缺失: item.itemCode" + } + ], + "notes": [ + "模块:singleitem 模块", + "方法部署位置:openapiMethods/singleitem.synchronize", + "同步策略:按 itemCode + app_key + warehouse_id + store_id 唯一约束判断,已存在则更新,不存在则创建", + "同步后会联动创建/更新库存表(StockWarehouse)记录", + "create_from 固定为 qimen(与奇门共用同一套底层逻辑)", + "warehouseCode 和 ownerCode 由 app_key 绑定的仓库/货主自动解析,不可通过请求参数覆盖", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + }, + { + "method": "singleitem.query", + "description": "singleitem 模块 商品查询接口,按商品 ID 返回完整商品信息", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "itemId", + "type": "number", + "required": true, + "source": "body", + "description": "商品 ID(必填),系统内部商品主键" + } + ], + "requestBody": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 item 对象,包含 itemId/itemCode/goodsCode/itemName/skuProperty/stockUnit/length/width/height/volume/grossWeight/netWeight/categoryId/categoryName/itemType/tagPrice/retailPrice/brandName/isSNMgmt/isShelfLifeMgmt/isBatchMgmt/isAreaSale/barCode/isValid/createTime 等全部商品字段" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误: itemId 不存在" + }, + { + "code": 404, + "message": "wms 的 SKUID 为 xxx 未找到" + } + ], + "notes": [ + "模块:singleitem 模块", + "方法部署位置:openapiMethods/singleitem.query", + "返回格式与奇门 convertToQimenFormat 一致,字段名使用驼峰命名", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "库存模块", + "module": "inventory", + "list": [ + { + "method": "inventory.query", + "description": "inventory 模块 库存查询接口,按商品 ID 批量查询库存量(可用量、锁定量)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "itemIds", + "type": "array", + "required": true, + "source": "body", + "description": "商品 ID 列表(必填),如 [1000693, 1000694],支持单个或多个商品批量查询" + }, + { + "name": "[].itemIds", + "type": "number", + "required": true, + "source": "body", + "description": "单个商品 ID,系统内部商品主键,可通过 singleitem.query 或 singleitem.synchronize 返回的 itemId 获取" + } + ], + "requestBody": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 items 数组" + }, + { + "name": "data.items", + "type": "array", + "required": false, + "description": "库存信息列表" + }, + { + "name": "[].items.itemId", + "type": "number", + "required": false, + "description": "商品 ID" + }, + { + "name": "[].items.itemCode", + "type": "string", + "required": false, + "description": "商品编码" + }, + { + "name": "[].items.warehouseCode", + "type": "string", + "required": false, + "description": "仓库编码" + }, + { + "name": "[].items.quantity", + "type": "number", + "required": false, + "description": "总库存量" + }, + { + "name": "[].items.lockQuantity", + "type": "number", + "required": false, + "description": "锁定量(已被订单预占的库存)" + }, + { + "name": "[].items.inventoryType", + "type": "string", + "required": false, + "description": "库存类型,固定返回 ZP(正品)" + } + ], + "errors": [ + { + "code": 400, + "message": "itemIds 参数缺失或为空" + }, + { + "code": 404, + "message": "未查询到有效库存信息" + } + ], + "notes": [ + "模块:inventory 模块", + "方法部署位置:openapiMethods/inventory.query", + "支持批量查询多个商品的库存,减少请求次数", + "库存不足(可用量 ≤0)或商品未绑定库存记录时,该条商品不会出现在返回结果中", + "查询范围为当前 app_key 绑定的仓库", + "可用量 = quantity - lockQuantity", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "入库单模块", + "module": "entryorder", + "list": [ + { + "method": "entryorder.create", + "description": "entryorder 模块 创建入库单接口,支持传入入库单主信息和商品明细。创建成功后返回的状态 status 为 CREATING(明细行未全部插入)或 CREATED(明细行已全部插入完成)。明细行商品匹配三级策略:itemId 主键直查 > itemCode 精确匹配 > itemCode 归一化条码匹配(取编码开头连续数字,剥离中文后缀)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单主信息对象" + }, + { + "name": "entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(必填),外部系统的唯一入库单号,落库 wms_entry_order.entry_order_code" + }, + { + "name": "entryOrder.entryOrderType", + "type": "string", + "required": false, + "source": "body", + "description": "入库单类型,默认 SCRK(生产入库),落库 wms_entry_order.order_type(兼容 entryOrder.orderType 传法)" + }, + { + "name": "entryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码。⚠️当前版本未生效:仓库上下文一律以 app_key 合约绑定的仓库为准(解析结果注入 storeId/warehouseId/qimen_warehouse_code),报文值被忽略,不参与落库与校验" + }, + { + "name": "entryOrder.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码,落库 wms_entry_order.qimen_owner_code(出站回传 entryorder.confirm 的 entryOrder.ownerCode 即取该值);不传则落空串" + }, + { + "name": "entryOrder.expectedArriveTime", + "type": "string", + "required": false, + "source": "body", + "description": "预计到货时间,ISO 8601 格式,落库 wms_entry_order.expect_start_time(不传取当前时间;兼容 entryOrder.expectStartTime)" + }, + { + "name": "entryOrder.totalOrderLines", + "type": "number", + "required": false, + "source": "body", + "description": "总行数,落库 wms_entry_order.total_order_lines(不传取明细行数)" + }, + { + "name": "entryOrder.operateTime", + "type": "string", + "required": false, + "source": "body", + "description": "操作时间,ISO 8601 格式。⚠️当前版本未生效:底层未落库、未参与任何逻辑(保留字段,仅为兼容调用方)" + }, + { + "name": "entryOrder.operatorName", + "type": "string", + "required": false, + "source": "body", + "description": "操作人。⚠️当前版本未生效:底层未落库、未参与任何逻辑(保留字段,仅为兼容调用方)" + }, + { + "name": "entryOrder.supplierCode", + "type": "string", + "required": false, + "source": "body", + "description": "供应商编码,落库 wms_entry_order.supplier_code" + }, + { + "name": "entryOrder.supplierName", + "type": "string", + "required": false, + "source": "body", + "description": "供应商名称,落库 wms_entry_order.supplier_name" + }, + { + "name": "entryOrder.remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注,落库 wms_entry_order.remark" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "订单明细对象,包含 orderLine 数组" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "source": "body", + "description": "商品明细列表,数组中每项为一个入库单行对象" + }, + { + "name": "[].orderLine.itemCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品编码,可含中文后缀(如 6934864201409-新品):精确匹配不到时取编码开头的连续数字作为归一化条码与商品主数据对齐匹配" + }, + { + "name": "[].orderLine.itemId", + "type": "string|number", + "required": false, + "source": "body", + "description": "仓库商品主键 ID。纯数字且不超 BIGINT 范围时按 StockStore 主键直查(校验货主一致);非纯数字值(如带中文后缀的编码)视为未提供,降级按 itemCode 匹配。主键查不到或货主不一致时同样降级按 itemCode 匹配" + }, + { + "name": "[].orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称,用于错误提示中的商品识别。明细落库的 item_name/item_code/item_id/stock_id/owner_code 均取匹配到的 StockStore 值,非报文原值" + }, + { + "name": "[].orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划入库数量(必填),必须大于 0,落库 wms_entry_items.count" + }, + { + "name": "[].orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,默认 ZP(正品),落库 wms_entry_items.inventory_type" + }, + { + "name": "[].orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "行号,落库 wms_entry_items.order_line_no(不传按明细顺序 1..N)" + } + ], + "requestBody": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单主信息对象" + }, + { + "name": "entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(必填),外部系统的唯一入库单号,落库 wms_entry_order.entry_order_code" + }, + { + "name": "entryOrder.entryOrderType", + "type": "string", + "required": false, + "source": "body", + "description": "入库单类型,默认 SCRK(生产入库),落库 wms_entry_order.order_type(兼容 entryOrder.orderType 传法)" + }, + { + "name": "entryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码。⚠️当前版本未生效:仓库上下文一律以 app_key 合约绑定的仓库为准(解析结果注入 storeId/warehouseId/qimen_warehouse_code),报文值被忽略,不参与落库与校验" + }, + { + "name": "entryOrder.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码,落库 wms_entry_order.qimen_owner_code(出站回传 entryorder.confirm 的 entryOrder.ownerCode 即取该值);不传则落空串" + }, + { + "name": "entryOrder.expectedArriveTime", + "type": "string", + "required": false, + "source": "body", + "description": "预计到货时间,ISO 8601 格式,落库 wms_entry_order.expect_start_time(不传取当前时间;兼容 entryOrder.expectStartTime)" + }, + { + "name": "entryOrder.totalOrderLines", + "type": "number", + "required": false, + "source": "body", + "description": "总行数,落库 wms_entry_order.total_order_lines(不传取明细行数)" + }, + { + "name": "entryOrder.operateTime", + "type": "string", + "required": false, + "source": "body", + "description": "操作时间,ISO 8601 格式。⚠️当前版本未生效:底层未落库、未参与任何逻辑(保留字段,仅为兼容调用方)" + }, + { + "name": "entryOrder.operatorName", + "type": "string", + "required": false, + "source": "body", + "description": "操作人。⚠️当前版本未生效:底层未落库、未参与任何逻辑(保留字段,仅为兼容调用方)" + }, + { + "name": "entryOrder.supplierCode", + "type": "string", + "required": false, + "source": "body", + "description": "供应商编码,落库 wms_entry_order.supplier_code" + }, + { + "name": "entryOrder.supplierName", + "type": "string", + "required": false, + "source": "body", + "description": "供应商名称,落库 wms_entry_order.supplier_name" + }, + { + "name": "entryOrder.remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注,落库 wms_entry_order.remark" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "订单明细对象,包含 orderLine 数组" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "source": "body", + "description": "商品明细列表,数组中每项为一个入库单行对象" + }, + { + "name": "[].orderLine.itemCode", + "type": "string", + "required": false, + "source": "body", + "description": "商品编码,可含中文后缀(如 6934864201409-新品):精确匹配不到时取编码开头的连续数字作为归一化条码与商品主数据对齐匹配" + }, + { + "name": "[].orderLine.itemId", + "type": "string|number", + "required": false, + "source": "body", + "description": "仓库商品主键 ID。纯数字且不超 BIGINT 范围时按 StockStore 主键直查(校验货主一致);非纯数字值(如带中文后缀的编码)视为未提供,降级按 itemCode 匹配。主键查不到或货主不一致时同样降级按 itemCode 匹配" + }, + { + "name": "[].orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称,用于错误提示中的商品识别。明细落库的 item_name/item_code/item_id/stock_id/owner_code 均取匹配到的 StockStore 值,非报文原值" + }, + { + "name": "[].orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划入库数量(必填),必须大于 0,落库 wms_entry_items.count" + }, + { + "name": "[].orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,默认 ZP(正品),落库 wms_entry_items.inventory_type" + }, + { + "name": "[].orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "行号,落库 wms_entry_items.order_line_no(不传按明细顺序 1..N)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "创建成功时返回 entryOrderId、entryOrderCode、status(CREATING=创建中明细行未全部插入,CREATED=已创建完成)、createTime" + } + ], + "errors": [ + { + "code": 400, + "message": "entryOrder.entryOrderCode 参数缺失" + }, + { + "code": 400, + "message": "orderLines.orderLine 参数缺失" + }, + { + "code": 400, + "message": "创建入库单失败,失败原因:订单行N:SKU{itemId}商品《itemName》编码《itemCode》未同步推送到仓库" + }, + { + "code": 400, + "message": "创建入库单失败,失败原因:订单行N:SKU{itemId}商品《itemName》编码《itemCode》wms无对应关系,请联系仓库关联创建商品" + }, + { + "code": 400, + "message": "创建入库单失败,失败原因:订单行N:编码《itemCode》归一化条码《barcode》匹配到多个商品,请人工核对后重试" + } + ], + "notes": [ + "模块:entryorder 模块", + "方法部署位置:openapiMethods/entryorder.create", + "创建渠道固定为 API", + "orderLines.orderLine 支持单对象或数组格式", + "明细行商品匹配三级策略:itemId 主键直查(纯数字且不超 BIGINT 范围、货主一致)> itemCode 精确匹配 > itemCode 归一化条码匹配(取编码开头连续数字)", + "带中文后缀的编码(如 6934864201409-新品)精确匹配不到时按归一化条码对齐;归一化条码命中多个商品时报错,不静默取第一条", + "item_id 统一写入实际匹配到的 StockStore 数字主键 id,避免非数字值写入 BIGINT 列触发 MySQL 严格模式报错(Data truncated for column 'item_id')", + "失败信息回显真实 SKU/商品/编码并附订单行号;与奇门渠道共用 app/service/systems/entry_order.js addOrder 同一逻辑", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400", + "字段生效口径(2026-09-14 核账):entryOrder.ownerCode → wms_entry_order.qimen_owner_code(出站回传 entryorder.confirm 的 ownerCode 取该值,代码已将报文 ownerCode 作为 customerId 传入 addOrder);entryOrder.entryOrderType → order_type(默认 SCRK);entryOrder.expectedArriveTime → expect_start_time;entryOrder.createTime → order_create_time;entryOrder.relatedOrders.relatedOrder.orderCode → purchase_order_code;entryOrder.logisticsCode / logisticsName / expressCode → logistics_code / logistics_name / express_code(当前未在参数表登记,代码已支持)", + "当前未生效字段(保留兼容,勿据此判断):entryOrder.warehouseCode(仓库上下文一律以 app_key 合约解析结果为准,报文值被忽略)、entryOrder.operateTime / entryOrder.operatorName(底层未落库、未参与任何逻辑)", + "标准请求/响应 JSON 见本条目 requestExample(query + headers + body)与 responseExample(success / businessFailure)两个键;两者为 2026-09-14 新增的自描述键,仅存于文档原始 JSON,未参与运行时代码逻辑" + ], + "requestExample": { + "query": "app_key=YOUR_APP_KEY&method=entryorder.create&v=1.0×tamp=1757865600&sign=", + "headers": { + "Content-Type": "application/json" + }, + "body": { + "entryOrder": { + "entryOrderCode": "TEST-RK-202609140001", + "entryOrderType": "SCRK", + "ownerCode": "OWNER001", + "warehouseCode": "", + "expectedArriveTime": "2026-09-15 10:00:00", + "expectEndTime": "2026-09-16 18:00:00", + "orderCreateTime": "2026-09-14 09:30:00", + "totalOrderLines": 2, + "supplierCode": "SUP001", + "supplierName": "示例供应商", + "logisticsCode": "SF", + "logisticsName": "顺丰速运", + "expressCode": "SF1234567890", + "remark": "openapi 入库单标准示例", + "relatedOrders": { + "relatedOrder": { + "orderCode": "PO-20260914-001" + } + }, + "operateTime": "", + "operatorName": "" + }, + "orderLines": { + "orderLine": [ + { + "orderLineNo": "1", + "itemCode": "SKU001", + "itemId": 10001, + "itemName": "示例商品A", + "planQty": 10, + "inventoryType": "ZP" + }, + { + "orderLineNo": "2", + "itemCode": "SKU002", + "itemId": 10002, + "itemName": "示例商品B", + "planQty": 5, + "inventoryType": "ZP" + } + ] + } + } + }, + "responseExample": { + "success": { + "flag": "success", + "code": 1, + "message": "入库单创建完成", + "createTime": "2026-09-14 09:30:00", + "entryOrderId": 88, + "entryOrderCode": "TEST-RK-202609140001", + "status": "CREATED", + "timestamp": 1757865600 + }, + "businessFailure": { + "flag": "failure", + "code": 0, + "message": "创建入库单失败,失败原因:\n订单行1:SKU10001商品《示例商品A》编码《SKU001》\n未同步推送到仓库", + "createTime": "2026-09-14 09:30:00", + "timestamp": 1757865600 + } + } + }, + { + "method": "entryorder.query", + "description": "entryorder 模块 查询入库单接口,根据入库单号返回入库单详情。返回的 status 字段可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(必填),要查询的入库单号" + } + ], + "requestBody": [ + { + "name": "entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(必填),要查询的入库单号" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 entryOrderCode、entryOrderId、status、entryOrderType、expectedArriveTime、supplierCode、supplierName、remark、createTime、operateTime、operatorName、warehouseCode、ownerCode、totalOrderLines、orderLines" + }, + { + "name": "data.orderLines", + "type": "array", + "required": false, + "description": "商品明细列表" + }, + { + "name": "[].orderLines.itemId", + "type": "number", + "required": false, + "description": "商品ID" + }, + { + "name": "[].orderLines.itemCode", + "type": "string", + "required": false, + "description": "商品编码" + }, + { + "name": "[].orderLines.itemName", + "type": "string", + "required": false, + "description": "商品名称" + }, + { + "name": "[].orderLines.planQty", + "type": "number", + "required": false, + "description": "计划入库数量" + }, + { + "name": "[].orderLines.actualQty", + "type": "number", + "required": false, + "description": "实际入库数量" + }, + { + "name": "[].orderLines.inventoryType", + "type": "string", + "required": false, + "description": "库存类型" + }, + { + "name": "[].orderLines.orderLineNo", + "type": "string", + "required": false, + "description": "行号" + } + ], + "errors": [ + { + "code": 400, + "message": "entryOrderCode 参数缺失" + }, + { + "code": 404, + "message": "入库单未找到" + } + ], + "notes": [ + "模块:entryorder 模块", + "方法部署位置:openapiMethods/entryorder.query", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + }, + { + "groupName": "出库单模块", + "module": "stockout", + "list": [ + { + "method": "stockout.create", + "description": "stockout 模块 创建非订单出库单接口,支持传入出库单主信息、收件人信息和出库明细;创建时按计划数量锁定库存", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "出库单主信息对象" + }, + { + "name": "deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号(必填),外部系统唯一单号,落库 wms_order_stockout.stockout_order_code" + }, + { + "name": "deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "业务类型(必填):JYCK 一般交易出库 / HHCK 换货出库 / BFCK 补发出库 / QTCK 其他出库" + }, + { + "name": "deliveryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码,不传时使用 app_key 合约绑定的仓库编码" + }, + { + "name": "deliveryOrder.createTime", + "type": "string", + "required": false, + "source": "body", + "description": "单据创建时间,落库 order_create_time" + }, + { + "name": "deliveryOrder.totalOrderLines", + "type": "integer", + "required": false, + "source": "body", + "description": "单据总行数,不传时取明细行数" + }, + { + "name": "deliveryOrder.remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "deliveryOrder.logisticsCode", + "type": "string", + "required": false, + "source": "body", + "description": "外部快递编码;货主开启 enable_external_express_code 时按快递设置表 → 系统快递列表匹配,匹配不到使用出库单兜底快递编码(stockout_default_express_code,默认 ZT 自提)" + }, + { + "name": "deliveryOrder.receiverInfo", + "type": "object", + "required": false, + "source": "body", + "description": "收件人信息对象,13 个标准字段落库 receiver_* 列,供转订单与确认回传使用" + }, + { + "name": "deliveryOrder.receiverInfo.name", + "type": "string", + "required": false, + "source": "body", + "description": "收件人姓名(receiver_name)" + }, + { + "name": "deliveryOrder.receiverInfo.company", + "type": "string", + "required": false, + "source": "body", + "description": "收件人公司名称(receiver_company)" + }, + { + "name": "deliveryOrder.receiverInfo.zipCode", + "type": "string", + "required": false, + "source": "body", + "description": "收件人邮编(receiver_zip_code)" + }, + { + "name": "deliveryOrder.receiverInfo.tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人固定电话(receiver_tel)" + }, + { + "name": "deliveryOrder.receiverInfo.mobile", + "type": "string", + "required": false, + "source": "body", + "description": "收件人移动电话(receiver_mobile)" + }, + { + "name": "deliveryOrder.receiverInfo.email", + "type": "string", + "required": false, + "source": "body", + "description": "收件人邮箱(receiver_email)" + }, + { + "name": "deliveryOrder.receiverInfo.countryCode", + "type": "string", + "required": false, + "source": "body", + "description": "国家编码(receiver_country_code)" + }, + { + "name": "deliveryOrder.receiverInfo.province", + "type": "string", + "required": false, + "source": "body", + "description": "省(receiver_province)" + }, + { + "name": "deliveryOrder.receiverInfo.city", + "type": "string", + "required": false, + "source": "body", + "description": "市(receiver_city)" + }, + { + "name": "deliveryOrder.receiverInfo.area", + "type": "string", + "required": false, + "source": "body", + "description": "区/县(receiver_area)" + }, + { + "name": "deliveryOrder.receiverInfo.town", + "type": "string", + "required": false, + "source": "body", + "description": "镇/街道(receiver_town)" + }, + { + "name": "deliveryOrder.receiverInfo.detailAddress", + "type": "string", + "required": false, + "source": "body", + "description": "详细地址(receiver_detail_address)" + }, + { + "name": "deliveryOrder.receiverInfo.id", + "type": "string", + "required": false, + "source": "body", + "description": "收件人证件号(receiver_id)" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "出库单明细对象" + }, + { + "name": "orderLines.orderLine", + "type": "object/array", + "required": true, + "source": "body", + "description": "明细行(单条为对象,多条为数组)" + }, + { + "name": "orderLines.orderLine.orderLineNo", + "type": "string", + "required": true, + "source": "body", + "description": "订单行号(必填)" + }, + { + "name": "orderLines.orderLine.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码,落库 qimen_owner_code(取首行)" + }, + { + "name": "orderLines.orderLine.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码(必填),itemId 主键查不到时按此编码 + 仓库货主维度降级匹配" + }, + { + "name": "orderLines.orderLine.itemId", + "type": "string", + "required": true, + "source": "body", + "description": "WMS 商品ID(必填),优先按 StockStore 主键直查(校验货主一致)" + }, + { + "name": "orderLines.orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称,仅用于错误提示与明细展示" + }, + { + "name": "orderLines.orderLine.planQty", + "type": "integer", + "required": true, + "source": "body", + "description": "计划数量(必填,需大于 0),创建时按此数量锁定库存" + }, + { + "name": "orderLines.orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型(ZP 正品 / CC 残次等)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "创建成功时返回 stockoutOrderId(出库单ID)、stockoutOrderCode(出库单号)" + } + ], + "errors": [ + { + "code": 400, + "message": "deliveryOrder 参数缺失或不完整 / orderLines 参数缺失" + }, + { + "code": 400, + "message": "创建出库单失败,失败原因:没有有效的订单明细数据 / 商品未同步推送到仓库 / wms无对应关系 / 计划数量必须大于0 / 库存锁定失败" + } + ], + "notes": [ + "模块:出库单模块", + "方法部署位置:openapiMethods/stockout.create → systems/stockout_order.create", + "与奇门 stockout.create 共用同一份实现(systems/stockout_order.js),差异仅在来源:开放 API 落库 source_type=API,奇门落库 source_type=QM", + "出库单落库 wms_order_stockout + wms_order_stockout_items,创建时在事务内按 planQty 锁定库存(锁标记 QM_STOCKOUT,与取消/确认/转单释放口径一致)", + "商品匹配:itemId 按 StockStore 主键直查(校验货主一致),查不到或跨货主时按 itemCode + 仓库 + 货主降级匹配", + "快递解析:货主开启 enable_external_express_code 且传 logisticsCode 时按快递设置表 → 系统快递列表匹配;未传/未开启/匹配不到使用出库单兜底快递编码 stockout_default_express_code(默认 ZT 自提),不回退订单默认快递", + "orderLines.orderLine 支持单对象或数组格式", + "收货信息(name / tel|mobile / 省市区镇详细地址)在转订单或一键出库确认时校验必填,创建时不强制", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + }, + { + "method": "stockout.query", + "description": "stockout 模块 查询非订单出库单接口,按出库单号返回主表信息与商品明细", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号(必填),要查询的出库单 stockout_order_code;兼容 deliveryOrder.deliveryOrderCode 传法" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 totalLines、deliveryOrder(deliveryOrderCode/deliveryOrderId/warehouseCode/orderType/status/createTime/remark)、orderLines.orderLine[](orderLineNo/ownerCode/itemCode/itemId/itemName/planQty/inventoryType)" + } + ], + "errors": [ + { + "code": 400, + "message": "deliveryOrderCode 参数缺失" + }, + { + "code": 404, + "message": "未找到出库单" + } + ], + "notes": [ + "模块:出库单模块", + "方法部署位置:openapiMethods/stockout.query → systems/stockout_order.query", + "与奇门 stockout.query 共用同一份实现(systems/stockout_order.js)", + "按 stockout_order_code 查 wms_order_stockout 主表,再按 order_id 关联 wms_order_stockout_items 明细(按 order_line_no 升序)", + "deliveryOrder.status 为出库单状态:CREATED 已创建 / PENDING 已审核 / COMPLETED 已完成 / CANCELLED 已作废 / TRANSFERRED 已转订单", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] + } + ] + } +} diff --git a/methods/openapi_callback.json b/methods/openapi_callback.json new file mode 100644 index 0000000..8c6c7e7 --- /dev/null +++ b/methods/openapi_callback.json @@ -0,0 +1,1346 @@ +{ + "module": "openapi_callback", + "description": "开放 API 出站回调定义(出站方向:WMS → 外部)。WMS 在业务完成后按 ApiApp 配置的 callback_url 主动推送事件通知:query 携带 method/v/timestamp/app_key/sign,报文体统一为奇门同层级的 { request: {...} }(event 仅出现在 query 的 method),使用 MD5 签名鉴权。入站接口请参阅 openapi.json。", + "version": "1.4.0", + "updatedAt": "2026-09-13", + "http": { + "path": "{ApiApp.callback_url}", + "method": "POST" + }, + "headers": [ + { + "name": "Content-Type", + "type": "string", + "required": true, + "description": "application/json" + } + ], + "methods": { + "groups": [ + { + "groupName": "出站回调事件", + "module": "callback", + "list": [ + { + "method": "entryorder.confirm", + "description": "入库单确认完成(直入)出站回调。直入入库(API 来源,source_type=API)完成后,WMS 向外部回传入库完成信息(对应奇门 taobao.qimen.entryorder.confirm)。触发实现:app/service/systems/inbound_direct_log.js#qimenEntrySync 的 API 分支 → _sendOpenApiCallback(throwOnError=true,回传成功才执行本地回调)。request 报文由 buildEntryOrderConfirmRequest 组装,奇门(QM)与 OpenAPI(API)共用。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 entryorder.confirm),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { entryOrder, orderLines }(不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单头信息" + }, + { + "name": "request.entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单编码(wms_entry_order.entry_order_code)" + }, + { + "name": "request.entryOrder.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门货主编码(wms_entry_order.qimen_owner_code)" + }, + { + "name": "request.entryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门仓库编码(wms_entry_order.qimen_warehouse_code)" + }, + { + "name": "request.entryOrder.entryOrderId", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID(wms_entry_order.id)" + }, + { + "name": "request.entryOrder.entryOrderType", + "type": "string", + "required": true, + "source": "body", + "description": "入库单类型(wms_entry_order.order_type,如 SCRK)" + }, + { + "name": "request.entryOrder.outBizCode", + "type": "string", + "required": true, + "source": "body", + "description": "外部业务编码,缺省自动生成 DIRECT_INBOUND_时间戳(毫秒)" + }, + { + "name": "request.entryOrder.confirmType", + "type": "number", + "required": true, + "source": "body", + "description": "确认类型:0=最终确认 / 1=部分确认(isFin)" + }, + { + "name": "request.entryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "FULFILLED(最终确认)/ PARTFULFILLED(部分确认)" + }, + { + "name": "request.entryOrder.freight", + "type": "number", + "required": true, + "source": "body", + "description": "运费,固定 0" + }, + { + "name": "request.entryOrder.operateTime", + "type": "string", + "required": true, + "source": "body", + "description": "操作时间(app.formatDate(new Date()))" + }, + { + "name": "request.entryOrder.remark", + "type": "string", + "required": true, + "source": "body", + "description": "备注(如「导入/PDA直接入库提交」)" + }, + { + "name": "request.orderLines", + "type": "array", + "required": true, + "source": "body", + "description": "入库明细行数组:[ { orderLineNo, ownerCode, itemCode, itemId, inventoryType, planQty, actualQty } ]" + }, + { + "name": "request.orderLines[].orderLineNo", + "type": "number", + "required": true, + "source": "body", + "description": "行号(从 1 递增)" + }, + { + "name": "request.orderLines[].ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.orderLines[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.orderLines[].inventoryType", + "type": "string", + "required": true, + "source": "body", + "description": "库存类型(如 ZP)" + }, + { + "name": "request.orderLines[].planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划数量" + }, + { + "name": "request.orderLines[].actualQty", + "type": "number", + "required": true, + "source": "body", + "description": "实际入库数量" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),全部失败后判定最终失败" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,重试至多 3 次后判定最终失败" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;全部失败后判定回调失败", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendWithRetry 直调(按 StoreWarehouse auth_status=2 → ApiApp contract_id/is_enabled=1/callback_url 非空 定位)", + "回传成功才执行本地回调(throwOnError=true,失败抛出并写 QUICK_INBOUND_FAILED 操作日志)" + ] + }, + { + "method": "entryorder.match", + "description": "入库单匹配收货完成出站回调。入库单匹配收货单完成后(API 来源,source_type=API),WMS 向外部回传匹配完成信息(对应奇门 taobao.qimen.entryorder.confirm)。触发实现:app/service/systems/receiving_entry_match.js#matchAfterEntryCompleted 在绑定成功且本次确实新建绑定(bindResult.created === true)时调用 _sendCallback(entryOrder, matchedReceiving, 'auto_match') 的 API 分支 → _sendOpenApiCallback(event=entryorder.match);重复触发时绑定已存在(created=false)不会重复回传;回传失败仅记录 warn,不影响绑定与入库单状态更新。request 报文由 buildEntryOrderConfirmRequest 组装,奇门(QM)与 OpenAPI(API)共用。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 entryorder.match),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { entryOrder, orderLines }(不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单头信息" + }, + { + "name": "request.entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单编码(wms_entry_order.entry_order_code)" + }, + { + "name": "request.entryOrder.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门货主编码(wms_entry_order.qimen_owner_code)" + }, + { + "name": "request.entryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门仓库编码(wms_entry_order.qimen_warehouse_code)" + }, + { + "name": "request.entryOrder.entryOrderId", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID(wms_entry_order.id)" + }, + { + "name": "request.entryOrder.entryOrderType", + "type": "string", + "required": true, + "source": "body", + "description": "入库单类型(wms_entry_order.order_type,如 SCRK)" + }, + { + "name": "request.entryOrder.outBizCode", + "type": "string", + "required": true, + "source": "body", + "description": "外部业务编码,缺省自动生成 RECEIVING_MATCH_时间戳(毫秒)" + }, + { + "name": "request.entryOrder.confirmType", + "type": "number", + "required": true, + "source": "body", + "description": "确认类型,固定 0(最终确认)" + }, + { + "name": "request.entryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "固定 FULFILLED" + }, + { + "name": "request.entryOrder.freight", + "type": "number", + "required": true, + "source": "body", + "description": "运费,固定 0" + }, + { + "name": "request.entryOrder.operateTime", + "type": "string", + "required": true, + "source": "body", + "description": "操作时间(app.formatDate(new Date()))" + }, + { + "name": "request.entryOrder.remark", + "type": "string", + "required": true, + "source": "body", + "description": "备注,固定「匹配收货单{收货单号}自动回传」(如 匹配收货单RCV20260912001自动回传)" + }, + { + "name": "request.orderLines", + "type": "array", + "required": true, + "source": "body", + "description": "入库明细行数组:[ { orderLineNo, ownerCode, itemCode, itemId, inventoryType, planQty, actualQty } ]" + }, + { + "name": "request.orderLines[].orderLineNo", + "type": "number", + "required": true, + "source": "body", + "description": "行号(从 1 递增)" + }, + { + "name": "request.orderLines[].ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.orderLines[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.orderLines[].inventoryType", + "type": "string", + "required": true, + "source": "body", + "description": "库存类型,缺省 ZP" + }, + { + "name": "request.orderLines[].planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划数量(wms_entry_items.count)" + }, + { + "name": "request.orderLines[].actualQty", + "type": "number", + "required": true, + "source": "body", + "description": "实际入库数量(wms_entry_items.received_quantity)" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),全部失败后判定最终失败" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,重试至多 3 次后判定最终失败" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;全部失败后判定回调失败", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendWithRetry 直调(按 StoreWarehouse auth_status=2 → ApiApp contract_id/is_enabled=1/callback_url 非空 定位)", + "已接入:matchAfterEntryCompleted 在绑定成功且本次新建绑定(bindResult.created === true)时调用 _sendCallback(entryOrder, matchedReceiving, 'auto_match');重复触发不重复回传;回传失败仅 warn 不影响绑定" + ] + }, + { + "method": "deliveryorder.confirm", + "description": "订单发货完成出站回调(逐单「先回调、成功再扣减」)。触发前提:createChannel=API,逐单在 finalizeLocalChannelOrdersInternal 分发循环(DISPATCH_BATCH_SIZE=20 批内并行)内直接发送,不再要求本批先出现同步成功订单。每单流程:① buildQimenDeliveryOrderConfirmDataInternal 组装报文(缺 ownerCode → 失败「发货单缺少奇门货主编码」)→② 解析发送用 appKey(context.appKey 优先,缺失时按订单货主 store_id + warehouse_id 合约反查 wms_store_warehouse(auth_status=2) → wms_api_app(is_enabled=1 且 callback_url 非空) 的 self_app_key;同批次按货主 Map 缓存,无 N+1)→③ sendByAppKey 发送 deliveryorder.confirm(最多 4 次尝试)→④ 回调成功才调用 processLocalChannelOrderInternal 扣减库存并置 sync_status='fin';失败统一走 markApiSyncFailedInternal:回写 sync_status='error' + markPendingException(写库失败仅记录 error 日志),不扣减库存、不置 fin,订单可重新派发(分发前过滤只跳过 fin)。触发实现:app/service/systems/order_async.js#finalizeLocalChannelOrdersInternal → processApiOrderInternal(复用 buildQimenDeliveryOrderConfirmDataInternal 组装与奇门 taobao.qimen.deliveryorder.confirm 完全一致的 request 报文;运单号由 buildOrderWaybillCodeMapInternal 批量取、仅 API 渠道构建,无 N+1)。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 deliveryorder.confirm),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { deliveryOrder, packages, orderLines }(不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "发货单头信息" + }, + { + "name": "request.deliveryOrder.totalOrderLines", + "type": "number", + "required": true, + "source": "body", + "description": "明细行数(orderLines.length)" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(wms_order.delivery_order_code)" + }, + { + "name": "request.deliveryOrder.deliveryOrderId", + "type": "number", + "required": true, + "source": "body", + "description": "订单 ID(wms_order.id)" + }, + { + "name": "request.deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "仓库编码" + }, + { + "name": "request.deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "单据类型(wms_order.order_type,如 JYCK)" + }, + { + "name": "request.deliveryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "固定 DELIVERED" + }, + { + "name": "request.deliveryOrder.outBizCode", + "type": "string", + "required": true, + "source": "body", + "description": "外部业务编码,同 deliveryOrderCode" + }, + { + "name": "request.deliveryOrder.confirmType", + "type": "number", + "required": true, + "source": "body", + "description": "固定 0(最终确认)" + }, + { + "name": "request.deliveryOrder.orderConfirmTime", + "type": "string", + "required": true, + "source": "body", + "description": "确认时间(app.formatDate(new Date()))" + }, + { + "name": "request.deliveryOrder.operatorCode", + "type": "string", + "required": true, + "source": "body", + "description": "操作员编码,固定空字符串" + }, + { + "name": "request.deliveryOrder.operatorName", + "type": "string", + "required": true, + "source": "body", + "description": "操作员名称,固定空字符串" + }, + { + "name": "request.deliveryOrder.storageFee", + "type": "string", + "required": true, + "source": "body", + "description": "仓储费(wms_order.storage_fee,字符串)" + }, + { + "name": "request.deliveryOrder.operateTime", + "type": "string", + "required": true, + "source": "body", + "description": "操作时间(app.formatDate(new Date()))" + }, + { + "name": "request.packages", + "type": "object", + "required": true, + "source": "body", + "description": "包裹信息对象 { package: [...] }" + }, + { + "name": "request.packages.package", + "type": "array", + "required": true, + "source": "body", + "description": "包裹数组(每个运单号一条)" + }, + { + "name": "request.packages.package[].logisticsCode", + "type": "string", + "required": true, + "source": "body", + "description": "物流公司编码(wms_order.logistics_code)" + }, + { + "name": "request.packages.package[].logisticsName", + "type": "string", + "required": true, + "source": "body", + "description": "物流公司名称(wms_order.logistics_name)" + }, + { + "name": "request.packages.package[].expressCode", + "type": "string", + "required": true, + "source": "body", + "description": "运单号(wms_order_express 批量查询,同仓校验)" + }, + { + "name": "request.packages.package[].packageCode", + "type": "string", + "required": true, + "source": "body", + "description": "包裹编码(package_code 缺省同 deliveryOrderCode)" + }, + { + "name": "request.packages.package[].invoiceNo", + "type": "string", + "required": true, + "source": "body", + "description": "发票号(wms_order.invoice_no)" + }, + { + "name": "request.packages.package[].items", + "type": "array", + "required": true, + "source": "body", + "description": "包裹内商品行:[ { itemCode, itemId, quantity } ]" + }, + { + "name": "request.packages.package[].items[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.packages.package[].items[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.packages.package[].items[].quantity", + "type": "number", + "required": true, + "source": "body", + "description": "数量" + }, + { + "name": "request.orderLines", + "type": "array", + "required": true, + "source": "body", + "description": "发货明细行数组" + }, + { + "name": "request.orderLines[].orderLineNo", + "type": "string", + "required": true, + "source": "body", + "description": "行号(字符串)" + }, + { + "name": "request.orderLines[].orderSourceCode", + "type": "string", + "required": true, + "source": "body", + "description": "订单来源编码(source_order_code)" + }, + { + "name": "request.orderLines[].subSourceCode", + "type": "string", + "required": true, + "source": "body", + "description": "子来源编码(sub_source_order_code)" + }, + { + "name": "request.orderLines[].ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.orderLines[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.orderLines[].itemName", + "type": "string", + "required": true, + "source": "body", + "description": "商品名称" + }, + { + "name": "request.orderLines[].extCode", + "type": "string", + "required": true, + "source": "body", + "description": "扩展编码(ext_code)" + }, + { + "name": "request.orderLines[].planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划数量" + }, + { + "name": "request.orderLines[].actualQty", + "type": "number", + "required": true, + "source": "body", + "description": "实际发货数量" + }, + { + "name": "request.orderLines[].retailPrice", + "type": "number", + "required": true, + "source": "body", + "description": "零售价" + }, + { + "name": "request.orderLines[].actualPrice", + "type": "number", + "required": true, + "source": "body", + "description": "实际价" + }, + { + "name": "request.orderLines[].discountAmount", + "type": "string", + "required": true, + "source": "body", + "description": "优惠金额(字符串)" + }, + { + "name": "request.orderLines[].inventoryType", + "type": "string", + "required": true, + "source": "body", + "description": "库存类型(如 ZP)" + }, + { + "name": "request.orderLines[].snList", + "type": "array", + "required": true, + "source": "body", + "description": "序列号列表(无序列号时为空数组 [])" + }, + { + "name": "request.orderLines[].qrCode", + "type": "string", + "required": true, + "source": "body", + "description": "二维码(qr_code)" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),4 次尝试全部失败后该订单同步判定失败(sync_status='error' + 待处理异常,不扣减库存,可重新派发);订单结果 message 形如「OpenAPI 回调确认失败: 回调返回非 2xx 状态码: 400」并附 callback_retry_count" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,4 次尝试后该订单同步判定失败(sync_status='error' + 待处理异常,不扣减库存)" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,4 次尝试后该订单同步判定失败(sync_status='error' + 待处理异常,不扣减库存)" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,4 次尝试后该订单同步判定失败(sync_status='error' + 待处理异常,不扣减库存)" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,4 次尝试后该订单同步判定失败(sync_status='error' + 待处理异常,不扣减库存)" + }, + { + "code": "CALLBACK_EXCEPTION", + "message": "发送过程抛异常:订单结果 message 形如「OpenAPI 回调确认异常: {error}」,处理同回调失败(sync_status='error' + 待处理异常,不扣减库存,可重新派发)" + }, + { + "code": "OWNER_CODE_MISSING", + "message": "报文组装失败:发货单缺少奇门货主编码(ownerCode 缺失),该订单同步失败(sync_status='error' + 待处理异常,不扣减库存),订单结果 message 为「发货单缺少奇门货主编码」" + }, + { + "code": "STORE_ID_MISSING", + "message": "发货单缺少货主 store_id,无法解析回传用 appKey:该订单同步失败(sync_status='error' + 待处理异常,不扣减库存),订单结果 message 为「发货单缺少货主 store_id,无法解析回传用 appKey」" + }, + { + "code": "NO_API_APP_CONFIG", + "message": "货主未配置可用的 OpenAPI 回调(wms_api_app 启用且 callback_url 非空):该订单同步失败(sync_status='error' + 待处理异常,不扣减库存),订单结果 message 为「货主未配置可用的 OpenAPI 回调(wms_api_app 启用且 callback_url 非空)」" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;4 次尝试后仍失败 ⇒ 该订单同步判定失败(sync_status='error' + 待处理异常,不扣减库存,可重新派发)", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendByAppKey;appKey 解析优先级:context.appKey 非空时优先(不触发合约反查),缺失时按订单货主(store_id + warehouse_id)合约反查 resolveOpenApiAppByStoreInternal —— wms_store_warehouse(auth_status=2) → wms_api_app(contract_id 且 is_enabled=1 且 callback_url 非空) 的 self_app_key;同一批次按货主 Map 缓存(N 单 / M 货主 → 2M 次查询,无 N+1)", + "appKey 门禁修复(2026-09-13):此前 order_storage_allocation.js 构造的 routeContext 不含 appKey,finalizeLocalChannelOrdersInternal 内 if(appKey) 门禁使 syncOrderIds(API) 链路的 deliveryorder.confirm 从未真正发出请求;订单 wms_order_delivery.from_key 兜不住(normalizeOrderFromKey 仅接受整数,字符串 app_key 被归一化为 null)。本次改为按货主合约反查修复;解析不到 appKey(订单缺 store_id / 无授权关系 / 无可用 ApiApp 配置)不再静默跳过:按失败处理(sync_status='error' + 待处理异常,不扣减库存,可重新派发)", + "逐单先回调后扣减(2026-09-13 破坏性变更):触发前提不再是「本批存在同步成功订单」,改为逐单在 finalizeLocalChannelOrdersInternal 分发循环(DISPATCH_BATCH_SIZE=20 批内并行)内直接处理;processApiOrderInternal 流程 ① 组装报文(缺 ownerCode → 失败)→ ② 解析 appKey → ③ sendByAppKey 发送(最多 4 次尝试)→ ④ 回调成功才调用 processLocalChannelOrderInternal 扣减库存并置 sync_status='fin';成功 N 单 = N 次回调(每单先回调、成功再扣减,不再是先扣减、后异步回调)", + "失败处理(2026-09-13):回调失败/异常、报文组装失败、appKey 解析失败统一走 markApiSyncFailedInternal(sync_status='error' + markPendingException,写库失败仅记录 error 日志),不扣减库存、不置 fin,订单可重新派发(分发前过滤只跳过 fin)。失败文案:OpenAPI 回调确认失败: {error}(如「OpenAPI 回调确认失败: 回调返回非 2xx 状态码: 400」,附 callback_retry_count)/ OpenAPI 回调确认异常: ... / 发货单缺少奇门货主编码 / 发货单缺少货主 store_id,无法解析回传用 appKey / 货主未配置可用的 OpenAPI 回调(wms_api_app 启用且 callback_url 非空)" + ] + }, + { + "method": "stockout.confirm", + "description": "出库单确认完成出站回调。出库单确认(API 来源,source_type=API)后,WMS 向外部回传出库确认信息(对应奇门 taobao.qimen.stockout.confirm)。触发实现:app/service/systems/order_async.js#notifyStockoutExternalInternal 的 API 分支(event=stockout.confirm);request 即 buildStockoutConfirmDataInternal 的返回结构 { deliveryOrder, packages, orderLines },与奇门请求体同层级。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 stockout.confirm),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { deliveryOrder, packages, orderLines }(即 buildStockoutConfirmDataInternal 的返回结构,不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "出库单头信息" + }, + { + "name": "request.deliveryOrder.totalOrderLines", + "type": "number", + "required": true, + "source": "body", + "description": "明细行数(wms_order_stockout.total_order_lines 或 orderLines.length)" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号(wms_order_stockout.stockout_order_code)" + }, + { + "name": "request.deliveryOrder.deliveryOrderId", + "type": "number", + "required": true, + "source": "body", + "description": "出库单 ID(wms_order_stockout.id)" + }, + { + "name": "request.deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门仓库编码(wms_order_stockout.qimen_warehouse_code)" + }, + { + "name": "request.deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "单据类型(如 PTCK)" + }, + { + "name": "request.deliveryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "固定 DELIVERED" + }, + { + "name": "request.deliveryOrder.outBizCode", + "type": "string", + "required": true, + "source": "body", + "description": "外部业务编码,同出库单号" + }, + { + "name": "request.deliveryOrder.confirmType", + "type": "number", + "required": true, + "source": "body", + "description": "固定 0(最终确认)" + }, + { + "name": "request.deliveryOrder.orderConfirmTime", + "type": "string", + "required": true, + "source": "body", + "description": "确认时间(app.formatDate(new Date()))" + }, + { + "name": "request.deliveryOrder.operatorCode", + "type": "string", + "required": true, + "source": "body", + "description": "操作员编码,固定空字符串" + }, + { + "name": "request.deliveryOrder.operatorName", + "type": "string", + "required": true, + "source": "body", + "description": "操作员名称,固定空字符串" + }, + { + "name": "request.packages", + "type": "object", + "required": true, + "source": "body", + "description": "包裹信息对象 { package: [...] }" + }, + { + "name": "request.packages.package", + "type": "array", + "required": true, + "source": "body", + "description": "包裹数组(每个运单号一条;STOCKOUT 渠道运单号只认 wms_order_express 表)" + }, + { + "name": "request.packages.package[].logisticsCode", + "type": "string", + "required": true, + "source": "body", + "description": "物流公司编码(订单 sys_logistics_code → logistics_code → 出库单 express_code,缺省 OTHER)" + }, + { + "name": "request.packages.package[].logisticsName", + "type": "string", + "required": true, + "source": "body", + "description": "物流公司名称(订单 sys_logistics_name → logistics_name → 出库单 express_name,缺省 OTHER)" + }, + { + "name": "request.packages.package[].expressCode", + "type": "string", + "required": true, + "source": "body", + "description": "运单号(wms_order_express 表)" + }, + { + "name": "request.packages.package[].packageCode", + "type": "string", + "required": true, + "source": "body", + "description": "包裹编码(package_code 缺省同出库单号)" + }, + { + "name": "request.packages.package[].items", + "type": "array", + "required": true, + "source": "body", + "description": "包裹内商品行:[ { itemCode, itemId, quantity } ]" + }, + { + "name": "request.packages.package[].items[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.packages.package[].items[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.packages.package[].items[].quantity", + "type": "number", + "required": true, + "source": "body", + "description": "数量(actualQty)" + }, + { + "name": "request.orderLines", + "type": "array", + "required": true, + "source": "body", + "description": "出库明细行数组:[ { orderLineNo, ownerCode, itemCode, itemId, itemName, planQty, actualQty, inventoryType } ]" + }, + { + "name": "request.orderLines[].orderLineNo", + "type": "string", + "required": true, + "source": "body", + "description": "行号(字符串)" + }, + { + "name": "request.orderLines[].ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码(item.owner_code 或出库单 qimen_owner_code)" + }, + { + "name": "request.orderLines[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.orderLines[].itemName", + "type": "string", + "required": true, + "source": "body", + "description": "商品名称" + }, + { + "name": "request.orderLines[].planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划数量" + }, + { + "name": "request.orderLines[].actualQty", + "type": "number", + "required": true, + "source": "body", + "description": "实际数量(缺省同 planQty)" + }, + { + "name": "request.orderLines[].inventoryType", + "type": "string", + "required": true, + "source": "body", + "description": "库存类型,缺省 ZP" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),全部失败后判定最终失败" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,重试至多 3 次后判定最终失败" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;全部失败后判定回调失败", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendByAppKey(按 app_key 查 ApiApp,is_enabled=1,取 self_app_secret 与 callback_url)", + "仅 API 来源(source_type=API)出库单回传;QM 来源走奇门 taobao.qimen.stockout.confirm" + ] + }, + { + "method": "deliveryorder.cancel", + "description": "订单取消出站回调(出站事件名 deliveryorder.cancel,与 /openapi 入站方法 order.cancel 区分,避免 callback_url 误指向 WMS /openapi 时被路由到真正的取消单据接口;不做兼容、不双发)。订单取消成功后,WMS 向外部回传取消结果(fire-and-forget,不阻塞主流程)。触发实现:app/service/openapiMethods/order.js#cancel(event=deliveryorder.cancel)。无奇门对应接口,按 deliveryOrder 节点约定自定义报文。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 deliveryorder.cancel),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { deliveryOrder }(不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "被取消订单信息(自定义约定,无奇门对应接口)" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "被取消的订单编码(normalizedOrderCode)" + }, + { + "name": "request.deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "单据类型,取 body.orderType 大写归一化结果(String(body.orderType || 'JYCK').trim().toUpperCase())" + }, + { + "name": "request.deliveryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "固定 CANCELED(自定义约定值;无奇门对应接口,风格与奇门 deliveryOrder.status 家族枚举一致)" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),全部失败后判定最终失败" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,重试至多 3 次后判定最终失败" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;全部失败后判定回调失败", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendByAppKey(按 app_key 查 ApiApp,is_enabled=1,取 self_app_secret 与 callback_url)", + "fire-and-forget 触发:回调结果不影响订单取消主流程", + "改名说明:出站回调事件名由 order.cancel 改为 deliveryorder.cancel(不做兼容、不双发),与 /openapi 入站方法 order.cancel(取消单据接口)区分,避免 callback_url 误指向 /openapi 时被路由到取消单据接口" + ] + } + ] + } + ] + } +} diff --git a/methods/qimen.json b/methods/qimen.json new file mode 100644 index 0000000..9420321 --- /dev/null +++ b/methods/qimen.json @@ -0,0 +1,1664 @@ +{ + "module": "qimen", + "description": "奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)", + "version": "0.3.11", + "updatedAt": "2026-10-08", + "headers": [], + "methods": { + "groups": [ + { + "groupName": "deliveryorder 模块", + "module": "deliveryorder", + "list": [ + { + "method": "deliveryorder.batchcreate", + "description": "deliveryorder.batchcreate 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderCode 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "deliveryorder.create", + "description": "deliveryorder.create 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderCode 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "deliveryorder.query", + "description": "deliveryorder.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "request.orderCode 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "entryorder 模块", + "module": "entryorder", + "list": [ + { + "method": "entryorder.create", + "description": "创建入库单。奇门 XML 推送创建入库单及明细,返回入库单 ID、单号、创建时间和状态。明细行商品匹配三级策略:itemId 主键直查 > itemCode 精确匹配 > itemCode 归一化条码匹配(取编码开头连续数字,剥离中文后缀)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点,包含 entryOrder 和 orderLines 子节点" + }, + { + "name": "request.entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单头信息" + }, + { + "name": "request.entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(外部系统单号)" + }, + { + "name": "request.entryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "仓库编码" + }, + { + "name": "request.entryOrder.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.entryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "入库单类型:CGRK(采购入库)、JITRK(JIT入库)、THRK(退货入库)、QTRK(其他入库)等" + }, + { + "name": "request.orderLines.orderLine", + "type": "object|array", + "required": true, + "source": "body", + "description": "入库单明细行,单条为 object,多条为 array" + }, + { + "name": "request.orderLines.orderLine.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码。支持带中文后缀的编码(如 6934864201409-新品):精确匹配不到时取编码开头的连续数字(6934864201409)作为归一化条码与商品主数据对齐匹配" + }, + { + "name": "request.orderLines.orderLine.itemId", + "type": "string", + "required": false, + "source": "body", + "description": "商品 ID。纯数字且不超 BIGINT 范围时按 StockStore 主键直查(校验货主一致);非法值(如带中文后缀的编码)视为未提供,降级按 itemCode 匹配。主键查不到或货主不一致时同样降级按 itemCode 匹配" + }, + { + "name": "request.orderLines.orderLine.itemName", + "type": "string", + "required": true, + "source": "body", + "description": "商品名称" + }, + { + "name": "request.orderLines.orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划入库数量" + }, + { + "name": "request.orderLines.orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "行号" + }, + { + "name": "request.orderLines.orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,如 ZP(正品),默认 ZP" + } + ], + "response": [ + { + "name": "entryOrderId", + "type": "number", + "required": true, + "description": "WMS 入库单 ID" + }, + { + "name": "entryOrderCode", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "createTime", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "入库单状态:CREATED(已创建)或 PENDING(已审核)" + } + ], + "errors": [ + { + "code": 400, + "message": "创建入库单失败,失败原因:订单行N:SKU{itemId}商品《itemName》编码《itemCode》未同步推送到仓库" + }, + { + "code": 400, + "message": "创建入库单失败,失败原因:订单行N:SKU{itemId}商品《itemName》编码《itemCode》wms无对应关系,请联系仓库关联创建商品" + }, + { + "code": 400, + "message": "创建入库单失败,失败原因:订单行N:编码《itemCode》归一化条码《barcode》匹配到多个商品,请人工核对后重试" + }, + { + "code": 500, + "message": "服务器异常" + } + ], + "notes": [ + "明细行商品匹配三级策略:itemId 主键直查(纯数字且不超 BIGINT 范围、货主一致)> itemCode 精确匹配 > itemCode 归一化条码匹配(取编码开头连续数字)", + "带中文后缀的编码(如 6934864201409-新品)精确匹配不到时按归一化条码对齐;归一化条码命中多个商品时报错,不静默取第一条", + "item_id 统一写入实际匹配到的 StockStore 数字主键 id,避免非数字值写入 BIGINT 列触发 MySQL 严格模式报错(Data truncated for column 'item_id')", + "失败信息回显真实 SKU/商品/编码并附订单行号", + "入口 app/service/qimenMethods/entryorder.js,核心 app/service/systems/entry_order.js addOrder(OpenAPI 渠道共用同一逻辑)" + ] + }, + { + "method": "entryorder.query", + "description": "entryorder.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "inventory 模块", + "module": "inventory", + "list": [ + { + "method": "inventory.query", + "description": "inventory.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.criteriaList", + "type": "string", + "required": false, + "source": "body", + "description": "request.criteriaList 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "order 模块", + "module": "order", + "list": [ + { + "method": "order.cancel", + "description": "取消单据接口。按 request.orderType 匹配作业类型分发:ORDER 组(JYCK/HHCK/BFCK)取消发货单(未拣货且未打印直接取消,已拣货/已打印/已同步转拦截);RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)委托 ctx.service.systems.storage.entry.cancel 完整作废流程取消入库单(状态守卫 + 状态置 CANCELLED + 按台账回退关联收货单占用 + 写 ENTRY_ORDER_CANCEL 操作日志,不回传奇门事件);CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)按出库单号取消出库单(wms_order_stockout,仅 CREATED/PENDING 可取消,释放 QM_STOCKOUT 锁定);JG/BACKORDER 组均未开发完成,返回对应提示", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点,包含 orderCode 与 orderType 字段" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "单据编码:ORDER 组为发货单号(delivery_order_code),RK 组为入库单号(entry_order_code),CK 组为出库单号(stockout_order_code)" + }, + { + "name": "request.orderType", + "type": "string", + "required": false, + "source": "body", + "description": "作业类型枚举(按 orderType → 作业类型分发):ORDER 组(取消发货单,已实现):JYCK=一般交易出库单、HHCK=换货出库、BFCK=补发出库;RK 组(取消入库单,已实现,委托 ctx.service.systems.storage.entry.cancel 完整作废流程:守卫 COMPLETED/sync_status=SUCCESS、状态置 CANCELLED、按台账回退关联收货单占用、写 ENTRY_ORDER_CANCEL 操作日志,不回传奇门事件):B2BRK=B2B入库、SCRK=生产入库、LYRK=领用入库、CCRK=残次品入库、CGRK=采购入库、DBRK=调拨入库、QTRK=其他入库;CK 组(取消出库单,已实现,按出库单号查 wms_order_stockout,仅 CREATED/PENDING 可取消):PTCK=普通出库单、DBCK=调拨出库、B2BCK=B2B出库、QTCK=其他出库、CGTH=采购退货出库单;JG 组(未开发,返回取消加工单未开发完成):CNJG=仓内加工单;BACKORDER 组(未开发,返回取消退货单未开发完成):XTRK=销退入库、THRK=退货入库、HHRK=换货入库。枚举之外的值无法匹配作业类型,接口返回失败" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success=成功,failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息(如:取消订单成功、取消入库单成功、取消出库单成功、取消失败,已通知拦截执行)" + } + ], + "errors": [ + { + "code": 0, + "message": "订单号不能为空" + }, + { + "code": 0, + "message": "未找到对应的订单" + }, + { + "code": 0, + "message": "入库单号不能为空" + }, + { + "code": 0, + "message": "未找到对应的入库单" + }, + { + "code": 0, + "message": "已完成入库单不允许作废" + }, + { + "code": 0, + "message": "入库单已完成回传,不可取消" + }, + { + "code": 0, + "message": "取消失败,已通知拦截执行" + }, + { + "code": 0, + "message": "订单已同步,不可取消,已转为拦截处理" + }, + { + "code": 0, + "message": "出库单号不能为空" + }, + { + "code": 0, + "message": "未找到对应的出库单" + }, + { + "code": 0, + "message": "出库单当前状态(xxx)不允许取消(仅 CREATED/PENDING 可取消)" + }, + { + "code": 0, + "message": "取消失败:xxx(释放库存锁定等异常)" + }, + { + "code": 0, + "message": "取消加工单未开发完成" + }, + { + "code": 0, + "message": "取消退货单未开发完成" + } + ], + "notes": [ + "入口:app/service/qimenMethods/order.js cancel,通过 switch (orderType.method) 分发;入参 request.orderCode(单据编码)+ request.orderType(作业类型枚举)", + "ORDER 组取消逻辑与 openapi 一致:未拣货且未打印直接取消(status=cancel, outbound_status=fin, step=4);已拣货或已打印改为拦截(intercept_status=intercepting),返回取消失败,已通知拦截执行", + "已同步订单(sync_status=fin)转拦截(intercept_status=requested),返回订单已同步,不可取消,已转为拦截处理", + "团购单已复核/散单已称重时不写入拦截请求状态,返回订单已复核/已称重,无法拦截(取消)执行,已转快递拦截", + "RK 组:空单号返回入库单号不能为空;委托 ctx.service.systems.storage.entry.cancel({ entryOrderCode }, { storeId, warehouseId, operatorLabel=qimen:xxx, skipExternalSync=true, idempotent=true, notFoundMessage=未找到对应的入库单 });守卫 sync_status=SUCCESS 返回入库单已完成回传,不可取消、order_status=COMPLETED 返回已完成入库单不允许作废;已 CANCELLED 幂等返回取消入库单成功(外部渠道重试口径);作废动作 = 状态置 CANCELLED + 按台账回退关联收货单占用(重算 storage_status)+ 写 ENTRY_ORDER_CANCEL 操作日志;skipExternalSync=true 全程不触发 qimenEntrySync,取消成功不回传奇门事件;未找到返回未找到对应的入库单;共享实现的 QM 回传失败分支文案为取消失败: xxx(RK 渠道 skipExternalSync=true 不触发回传,该分支不会出现)", + "CK 组:委托 ctx.service.systems.stockoutOrder.cancel(共享实现,单事务 + 行锁),按出库单号查 wms_order_stockout;仅 CREATED/PENDING 允许取消(COMPLETED/TRANSFERRED 拒绝),释放 QM_STOCKOUT 库存锁定(写 UNLOCK 流水,「释放数量超过已锁定库存」视为幂等跳过),状态置 CANCELLED 并写 wms_operation_log(business_type=stockout,operation_code=STOCKOUT_CANCEL);已 CANCELLED 幂等返回取消出库单成功;取消成功不向奇门回传任何事件", + "JG/BACKORDER 组:分别返回取消加工单未开发完成、取消退货单未开发完成", + "已取消订单(status=cancel)走幂等分支返回取消订单成功;未找到订单返回未找到对应的订单", + "响应为奇门 XML 结构(flag/code/message),code=1 成功、code=0 失败" + ] + }, + { + "method": "order.pending", + "description": "锁定单据接口(占位)。按 request.orderType 匹配作业类型分发,当前所有作业类型(ORDER/RK/CK/JG/BACKORDER)均未开发完成,统一返回锁定XX未开发完成", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点,包含 orderCode 与 orderType 字段" + }, + { + "name": "request.orderCode", + "type": "string", + "required": false, + "source": "body", + "description": "单据编码(发货单号/入库单号,视 orderType 作业类型而定)" + }, + { + "name": "request.orderType", + "type": "string", + "required": false, + "source": "body", + "description": "作业类型枚举(与 order.cancel 一致):ORDER 组:JYCK=一般交易出库单、HHCK=换货出库、BFCK=补发出库;RK 组:B2BRK=B2B入库、SCRK=生产入库、LYRK=领用入库、CCRK=残次品入库、CGRK=采购入库、DBRK=调拨入库、QTRK=其他入库;CK 组:PTCK=普通出库单、DBCK=调拨出库、B2BCK=B2B出库、QTCK=其他出库、CGTH=采购退货出库单;JG 组:CNJG=仓内加工单;BACKORDER 组:XTRK=销退入库、THRK=退货入库、HHRK=换货入库。当前所有类型均未开发完成,返回锁定XX未开发完成" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success=成功,failure=失败(当前所有分支均返回 failure)" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息(锁定订单/入库单/出库单/加工单/退货单未开发完成)" + } + ], + "errors": [ + { + "code": 0, + "message": "锁定订单未开发完成" + }, + { + "code": 0, + "message": "锁定入库单未开发完成" + }, + { + "code": 0, + "message": "锁定出库单未开发完成" + }, + { + "code": 0, + "message": "锁定加工单未开发完成" + }, + { + "code": 0, + "message": "锁定退货单未开发完成" + } + ], + "notes": [ + "入口:app/service/qimenMethods/order.js pending,通过 switch (orderType.method) 分发;入参 request.orderCode + request.orderType(枚举同 order.cancel)", + "当前所有作业类型分支均未实现,统一返回锁定XX未开发完成(flag=failure、code=0)", + "枚举之外的值无法匹配作业类型,接口返回失败" + ] + } + ] + }, + { + "groupName": "returnorder 模块", + "module": "returnorder", + "list": [ + { + "method": "returnorder.create", + "description": "returnorder.create 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + } + ], + "response": [], + "errors": [] + }, + { + "method": "returnorder.query", + "description": "returnorder.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "singleitem 模块", + "module": "singleitem", + "list": [ + { + "method": "singleitem.query", + "description": "singleitem.query 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.itemId", + "type": "string", + "required": false, + "source": "body", + "description": "request.itemId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "singleitem.synchronize", + "description": "singleitem.synchronize 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.itemId", + "type": "string", + "required": false, + "source": "body", + "description": "request.itemId 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "stockout 模块", + "module": "stockout", + "list": [ + { + "method": "stockout.create", + "description": "stockout.create 接口(创建非订单出库单;对应 system 出口 storage.stockout.*)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "出库单头信息" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号" + }, + { + "name": "request.deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "业务类型(JYCK一般交易出库/HHCK换货出库/BFCK补发出库/QTCK其他出库)" + }, + { + "name": "request.deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "仓库编码" + }, + { + "name": "request.deliveryOrder.createTime", + "type": "string", + "required": false, + "source": "body", + "description": "订单创建时间" + }, + { + "name": "request.deliveryOrder.totalOrderLines", + "type": "integer", + "required": false, + "source": "body", + "description": "单据总行数" + }, + { + "name": "request.deliveryOrder.remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "request.orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "出库单明细" + }, + { + "name": "request.orderLines.orderLine", + "type": "object/array", + "required": true, + "source": "body", + "description": "明细行(单条为对象,多条为数组)" + }, + { + "name": "request.orderLines.orderLine.orderLineNo", + "type": "string", + "required": true, + "source": "body", + "description": "订单行号" + }, + { + "name": "request.orderLines.orderLine.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.orderLines.orderLine.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines.orderLine.itemId", + "type": "string", + "required": true, + "source": "body", + "description": "WMS商品ID" + }, + { + "name": "request.orderLines.orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称" + }, + { + "name": "request.orderLines.orderLine.planQty", + "type": "integer", + "required": true, + "source": "body", + "description": "计划数量" + }, + { + "name": "request.orderLines.orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型(ZP正品/CC残次等)" + } + ], + "response": [ + { + "name": "stockoutOrderId", + "type": "integer", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockoutOrderCode", + "type": "string", + "required": true, + "description": "出库单号" + } + ], + "errors": [], + "notes": [ + "明细行商品匹配二级策略:itemId 主键直查(货主一致)> itemCode 精确匹配(warehouse_id + store_id + app_key 维度)", + "item_id 统一写入实际匹配到的 StockStore 数字主键 id(wms_stock_store.id),避免非数字值(如「编码+名称」拼接串)写入 BIGINT 列触发 MySQL 严格模式报错(Incorrect integer value for column item_id)", + "item_code / item_name / plan_qty / inventory_type 落报文原值,stock_id 落系统解析值" + ] + }, + { + "method": "stockout.query", + "description": "stockout.query 接口(查询非订单出库单;按 deliveryOrderCode 查 wms_order_stockout 主表+明细表)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "请求数据" + }, + { + "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "出库单查询条件" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号" + } + ], + "response": [ + { + "name": "totalLines", + "type": "integer", + "required": true, + "description": "明细总行数" + }, + { + "name": "deliveryOrder", + "type": "object", + "required": true, + "description": "出库单主单信息" + }, + { + "name": "deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "deliveryOrder.deliveryOrderId", + "type": "integer", + "required": true, + "description": "出库单ID" + }, + { + "name": "deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "description": "仓库编码" + }, + { + "name": "deliveryOrder.orderType", + "type": "string", + "required": true, + "description": "业务类型" + }, + { + "name": "deliveryOrder.status", + "type": "string", + "required": true, + "description": "订单状态" + }, + { + "name": "deliveryOrder.createTime", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "deliveryOrder.remark", + "type": "string", + "required": true, + "description": "备注" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "description": "明细集合" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "description": "明细行数组" + }, + { + "name": "orderLines.orderLine[].orderLineNo", + "type": "string", + "required": true, + "description": "订单行号" + }, + { + "name": "orderLines.orderLine[].ownerCode", + "type": "string", + "required": true, + "description": "货主编码" + }, + { + "name": "orderLines.orderLine[].itemCode", + "type": "string", + "required": true, + "description": "商品编码" + }, + { + "name": "orderLines.orderLine[].itemId", + "type": "string", + "required": true, + "description": "WMS商品ID" + }, + { + "name": "orderLines.orderLine[].itemName", + "type": "string", + "required": true, + "description": "商品名称" + }, + { + "name": "orderLines.orderLine[].planQty", + "type": "integer", + "required": true, + "description": "计划数量" + }, + { + "name": "orderLines.orderLine[].inventoryType", + "type": "string", + "required": true, + "description": "库存类型" + } + ], + "errors": [ + { + "code": 400, + "message": "未找到出库单(deliveryOrderCode 对应记录不存在)" + } + ] + } + ] + }, + { + "groupName": "taobao.qimen.service 模块", + "module": "taobao.qimen.service", + "list": [ + { + "method": "taobao.qimen.service.heartbeat", + "description": "taobao.qimen.service.heartbeat 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "app_key 参数" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "method 参数" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "v 参数" + }, + { + "name": "format", + "type": "string", + "required": true, + "source": "query", + "description": "format 参数" + }, + { + "name": "sign_method", + "type": "string", + "required": true, + "source": "query", + "description": "sign_method 参数" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "sign 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "timestamp 参数" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "request XML 节点" + }, + { + "name": "request.serialNumber", + "type": "string", + "required": false, + "source": "body", + "description": "request.serialNumber 参数" + } + ], + "response": [], + "errors": [] + } + ] + } + ] + } +} diff --git a/methods/system.json b/methods/system.json new file mode 100644 index 0000000..5352bec --- /dev/null +++ b/methods/system.json @@ -0,0 +1,55355 @@ +{ + "module": "system", + "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", + "version": "0.3.360", + "updatedAt": "2026-11-15", + "headers": [ + { + "name": "platform", + "type": "string", + "required": true, + "description": "客户端平台标识,如 web/pda/app/miniprogram/tv", + "list": [ + { + "value": "web", + "name": "网页端" + }, + { + "value": "pda", + "name": "PDA端" + }, + { + "value": "app", + "name": "APP端" + }, + { + "value": "miniprogram", + "name": "微信端" + }, + { + "value": "tv", + "name": "TV端" + }, + { + "value": "other", + "name": "其他" + }, + { + "value": "workerstation", + "name": "工作台" + } + ] + }, + { + "type": "string", + "required": true, + "name": "project", + "description": "项目标识,如 all/warehouse/store/tms/wms/scm/other", + "list": [ + { + "value": "all", + "name": "全部" + }, + { + "value": "warehouse", + "name": "仓库" + }, + { + "value": "store", + "name": "货主" + }, + { + "value": "tms", + "name": "物流" + }, + { + "value": "wms", + "name": "WMS" + }, + { + "value": "scm", + "name": "SCM" + }, + { + "value": "other", + "name": "其他" + } + ] + } + ], + "methods": { + "groups": [ + { + "groupName": "配置模块", + "module": "config", + "list": [ + { + "method": "config.list", + "description": "config.list 接口", + "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 数组(stock_warehouse.id)", + "children": [ + { + "name": "id", + "type": "number", + "description": "单个记录 ID" + } + ] + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "body", + "description": "要修改的字段名,可选值:brand_name、prohibited_id、gross_weight、packing_requirements、managementFlags、stock_unit" + }, + { + "name": "value", + "type": "string|number|object", + "required": true, + "source": "body", + "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正整数,单位 g);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N'" + }, + { + "name": "values", + "type": "any", + "required": false, + "source": "body", + "description": "兼容字段:当前实现以 `value` 为准,不使用 `values`。若客户端历史使用 `values`,请切换为 `value`。" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功;405 表示参数/权限校验不通过;500 表示服务器错误" + }, + { + "name": "message", + "type": "string", + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "description": "成功时返回的结果对象", + "children": [ + { + "name": "affectedRows", + "type": "number", + "description": "被更新的记录数" + }, + { + "name": "ids", + "type": "array", + "description": "请求中传入的 ids 数组" + } + ] + } + ], + "errors": [ + { + "code": "405", + "description": "请选择要修改的商品(缺少 ids 或 ids 为空)" + }, + { + "code": "405", + "description": "不支持修改的字段: {method}" + }, + { + "code": "405", + "description": "修改值不能为空" + }, + { + "code": "405", + "description": "违禁品类型必须是数字" + }, + { + "code": "405", + "description": "毛重必须是有效的正数" + }, + { + "code": "405", + "description": "管理标识必须是对象格式 / 管理标识缺少字段 / 管理标识字段值必须是 'Y' 或 'N'" + }, + { + "code": "405", + "description": "部分商品不存在或无权修改: " + }, + { + "code": "405", + "description": "缺少仓库信息" + }, + { + "code": "500", + "description": "内部错误:批量修改失败" + } + ] + } + ] + }, + { + "groupName": "看板模块", + "module": "dashboard", + "list": [ + { + "method": "dashboard.storeStats", + "description": "仓库/货主看板-仓库发货统计:统计待处理、今日新增、发货进度、出库率及拦截、异常、复核、打包订单数量;货主端自动跨已签约仓库汇总。无业务入参,依据登录用户上下文区分仓库端与货主端。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码,成功为 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息,成功为 成功" + }, + { + "name": "data.todayOrders", + "type": "number", + "required": true, + "description": "今日订单数(待处理 + 今日已出库)" + }, + { + "name": "data.orderTrend", + "type": "number", + "required": true, + "description": "今日新增较昨日增长率(%),昨日为 0 时按 100 或 0 计算" + }, + { + "name": "data.unassignedOrders", + "type": "number", + "required": true, + "description": "未分配快递号订单数" + }, + { + "name": "data.unprintedOrders", + "type": "number", + "required": true, + "description": "未打印订单数" + }, + { + "name": "data.unpickedOrders", + "type": "number", + "required": true, + "description": "未拣货订单数" + }, + { + "name": "data.pendingShipments", + "type": "number", + "required": true, + "description": "待发货订单数" + }, + { + "name": "data.shipmentProgress", + "type": "number", + "required": true, + "description": "发货进度(%),(待处理-待发货)/待处理" + }, + { + "name": "data.todayOutbound", + "type": "number", + "required": true, + "description": "今日已出库订单数" + }, + { + "name": "data.outboundRate", + "type": "number", + "required": true, + "description": "出库完成率(%),今日出库/(待发货+今日出库)" + }, + { + "name": "data.interceptedOrders", + "type": "number", + "required": true, + "description": "拦截订单数" + }, + { + "name": "data.exceptionOrders", + "type": "number", + "required": true, + "description": "异常订单数(step=3)" + }, + { + "name": "data.recheckedOrders", + "type": "number", + "required": true, + "description": "已复核订单数" + }, + { + "name": "data.packedOrders", + "type": "number", + "required": true, + "description": "已打包订单数" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": "0", + "message": "缺少仓库上下文(仓库端未绑定仓库)或缺少货主上下文(货主端未绑定货主),返回 flag=failure" + }, + { + "code": "401", + "message": "未登录或 token 无效" + }, + { + "code": "500", + "message": "订单数据查询失败" + } + ] + }, + { + "method": "dashboard.warehouseStats", + "description": "仓库发货统计(演示数据):返回固定的演示统计值,非实时查询结果,仅供前端展示与调试使用。无业务入参。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码,成功为 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息,成功为 成功" + }, + { + "name": "data.todayOrders", + "type": "number", + "required": true, + "description": "今日订单数(演示值 153023)" + }, + { + "name": "data.orderTrend", + "type": "number", + "required": true, + "description": "较昨日增长率(%,演示值 3)" + }, + { + "name": "data.unassignedOrders", + "type": "number", + "required": true, + "description": "未分配快递号订单数(演示值 3060)" + }, + { + "name": "data.unprintedOrders", + "type": "number", + "required": true, + "description": "未打印订单数(演示值 4591)" + }, + { + "name": "data.unpickedOrders", + "type": "number", + "required": true, + "description": "未拣货订单数(演示值 7651)" + }, + { + "name": "data.pendingShipments", + "type": "number", + "required": true, + "description": "待发货订单数(演示值 45907)" + }, + { + "name": "data.shipmentProgress", + "type": "number", + "required": true, + "description": "发货进度(%,演示值 70)" + }, + { + "name": "data.todayOutbound", + "type": "number", + "required": true, + "description": "今日已出库订单数(演示值 107116)" + }, + { + "name": "data.outboundRate", + "type": "number", + "required": true, + "description": "出库完成率(%,演示值 70)" + }, + { + "name": "data.interceptedOrders", + "type": "number", + "required": true, + "description": "拦截订单数(演示值 306)" + }, + { + "name": "data.exceptionOrders", + "type": "number", + "required": true, + "description": "异常订单数(演示值 1530)" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": "401", + "message": "未登录或 token 无效" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "dashboard.hot_order_rank", + "description": "热销商品排行:统计今日(00:00 至当前时刻)销量 Top10 商品及环比昨日趋势。仓库端按当前仓库统计,货主端跨全部签约仓库聚合。数据来源于真实数据库查询(订单明细/配送分表)。data[].sku 为库存商品ID(stock_warehouse.id),data[].name 已做脱敏处理(前2字符+***+后2字符)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码,成功为 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息,成功为 成功" + }, + { + "name": "data", + "type": "array", + "required": true, + "description": "热销商品排行列表(按今日销量降序,最多 10 条,无数据时为空数组)" + }, + { + "name": "data[].id", + "type": "number", + "required": true, + "description": "排行序号(从 1 开始)" + }, + { + "name": "data[].name", + "type": "string", + "required": true, + "description": "脱敏后的商品名称:保留前两个字符与后两个字符,中间以三个星号替代;长度不足 4 个字符时返回 ***;无名称时回退商品编码/商品+库存ID 后同样脱敏" + }, + { + "name": "data[].sku", + "type": "number", + "required": true, + "description": "库存商品ID(stock_warehouse.id);极端情况下订单明细无库存商品ID时回退商品编码字符串" + }, + { + "name": "data[].value", + "type": "number", + "required": true, + "description": "今日销量(件数)" + }, + { + "name": "data[].trend", + "type": "number", + "required": true, + "description": "环比昨日百分比(保留 1 位小数,昨日为 0 且今日 >0 时为 100)" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": "0", + "message": "缺少仓库上下文(仓库端未绑定仓库)或缺少货主上下文(货主端未绑定货主),返回 flag=failure" + }, + { + "code": "401", + "message": "未登录或 token 无效" + }, + { + "code": "500", + "message": "订单数据查询失败" + } + ] + }, + { + "method": "dashboard.express_ratio", + "description": "快递占比统计(饼图):按快递公司统计待处理订单数量及占比,按订单数降序返回;货主端自动跨已签约仓库汇总。无业务入参,依据登录用户上下文区分仓库端与货主端。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码,成功为 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息,成功为 成功" + }, + { + "name": "data", + "type": "array", + "required": true, + "description": "快递占比列表(按订单数降序,无数据时为空数组)" + }, + { + "name": "data[].name", + "type": "string", + "required": true, + "description": "快递公司名称(未填写时为 未指定快递)" + }, + { + "name": "data[].value", + "type": "number", + "required": true, + "description": "该快递公司的待处理订单数" + }, + { + "name": "data[].itemStyle.color", + "type": "string", + "required": true, + "description": "图表配色(十六进制色值)" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": "0", + "message": "缺少仓库上下文(仓库端未绑定仓库)或缺少货主上下文(货主端未绑定货主),返回 flag=failure" + }, + { + "code": "401", + "message": "未登录或 token 无效" + }, + { + "code": "500", + "message": "订单数据查询失败" + } + ] + }, + { + "method": "dashboard.platform_distribution", + "description": "平台分布统计(饼图):按系统平台统计待处理订单数量及占比,按订单数降序返回;货主端自动跨已签约仓库汇总。无业务入参,依据登录用户上下文区分仓库端与货主端。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码,成功为 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息,成功为 成功" + }, + { + "name": "data", + "type": "array", + "required": true, + "description": "平台占比列表(按订单数降序,无数据时为空数组)" + }, + { + "name": "data[].name", + "type": "string", + "required": true, + "description": "平台名称(未填写时为 未指定平台)" + }, + { + "name": "data[].value", + "type": "number", + "required": true, + "description": "该平台的待处理订单数" + }, + { + "name": "data[].itemStyle.color", + "type": "string", + "required": true, + "description": "图表配色(十六进制色值)" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": "0", + "message": "缺少仓库上下文(仓库端未绑定仓库)或缺少货主上下文(货主端未绑定货主),返回 flag=failure" + }, + { + "code": "401", + "message": "未登录或 token 无效" + }, + { + "code": "500", + "message": "订单数据查询失败" + } + ] + }, + { + "method": "dashboard.order_trend", + "description": "订单趋势统计:按小时统计当日 08:00 至当前小时的订单数与发货数,并返回发货率、峰值时段等汇总指标;依据当前用户绑定仓库统计。无业务入参。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码,成功为 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息,成功为 成功" + }, + { + "name": "data.range", + "type": "string", + "required": true, + "description": "统计范围,固定为 day" + }, + { + "name": "data.date", + "type": "string", + "required": true, + "description": "统计日期(YYYY-MM-DD)" + }, + { + "name": "data.summary.total_orders", + "type": "number", + "required": true, + "description": "当日订单总数" + }, + { + "name": "data.summary.total_shipments", + "type": "number", + "required": true, + "description": "当日发货总数" + }, + { + "name": "data.summary.shipment_rate", + "type": "number", + "required": true, + "description": "发货率(%,1 位小数)" + }, + { + "name": "data.summary.peak_hour", + "type": "string", + "required": true, + "description": "订单峰值时段(如 08:00)" + }, + { + "name": "data.summary.peak_orders", + "type": "number", + "required": true, + "description": "峰值时段订单数" + }, + { + "name": "data.categories", + "type": "array", + "required": true, + "description": "时段列表(08:00 至当前小时,如 ['08:00','09:00'])" + }, + { + "name": "data.orders", + "type": "array", + "required": true, + "description": "各时段订单数(与 categories 一一对应)" + }, + { + "name": "data.shipments", + "type": "array", + "required": true, + "description": "各时段发货数(与 categories 一一对应)" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": "0", + "message": "缺少仓库上下文(当前用户未绑定仓库),返回 flag=failure" + }, + { + "code": "401", + "message": "未登录或 token 无效" + }, + { + "code": "500", + "message": "订单数据查询失败" + } + ] + } + ] + }, + { + "groupName": "基础模块", + "module": "index", + "list": [ + { + "method": "index.fastWhereTree", + "description": "index.fastWhereTree 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "type 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.loadStores", + "description": "index.loadStores 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.loadWarehouses", + "description": "index.loadWarehouses 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.loadExpressInterfaces", + "description": "index.loadExpressInterfaces 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "systemExpressCode", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码(wms_express.code),传入时仅返回该编码对应的快递接口" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "description": "业务提示信息" + }, + { + "name": "expressInterfaces", + "type": "array", + "description": "当前仓库下的快递接口下拉列表", + "children": [ + { + "name": "value", + "type": "number", + "description": "快递接口ID(wms_express_interface.id)" + }, + { + "name": "label", + "type": "string", + "description": "快递接口名称(wms_express_interface.name)" + } + ] + } + ], + "errors": [] + }, + { + "method": "index.getCOSUploadConfig", + "description": "index.getCOSUploadConfig 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "data 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.getImages", + "description": "index.getImages 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.uploadSuccessNotify", + "description": "index.uploadSuccessNotify 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.ReferenceFile", + "description": "index.ReferenceFile 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getMessageDetail", + "description": "index.getMessageDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.test", + "description": "后台专用的拼多多开放平台测试接口,用于传入请求参数并发起真实请求,返回签名后的请求体和接口响应", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "拼多多接口名,例如 pdd.order.number.list.get" + }, + { + "name": "bizParams", + "type": "object", + "required": false, + "source": "body", + "description": "业务参数对象,会参与签名和请求" + }, + { + "name": "request", + "type": "object", + "required": false, + "source": "body", + "description": "bizParams 兼容字段" + }, + { + "name": "accessToken", + "type": "string", + "required": false, + "source": "body", + "description": "用户授权令牌" + }, + { + "name": "access_token", + "type": "string", + "required": false, + "source": "body", + "description": "accessToken 的下划线命名兼容字段" + }, + { + "name": "dataType", + "type": "string", + "required": false, + "source": "body", + "description": "返回格式,默认 JSON" + }, + { + "name": "version", + "type": "string", + "required": false, + "source": "body", + "description": "API 版本" + }, + { + "name": "timestamp", + "type": "string|number", + "required": false, + "source": "body", + "description": "时间戳,不传则使用当前秒级时间戳" + }, + { + "name": "clientId", + "type": "string", + "required": false, + "source": "body", + "description": "覆盖配置中的 client_id" + }, + { + "name": "clientSecret", + "type": "string", + "required": false, + "source": "body", + "description": "覆盖配置中的 client_secret" + }, + { + "name": "baseUrl", + "type": "string", + "required": false, + "source": "body", + "description": "请求地址,默认拼多多开放平台网关" + }, + { + "name": "headers", + "type": "object", + "required": false, + "source": "body", + "description": "额外请求头" + }, + { + "name": "timeout", + "type": "number", + "required": false, + "source": "body", + "description": "请求超时时间(毫秒)" + } + ], + "response": [ + { + "name": "requestBody", + "type": "object", + "description": "实际发送到 PDD 网关的请求体,已包含 sign" + }, + { + "name": "response", + "type": "any", + "description": "拼多多接口返回内容" + }, + { + "name": "baseUrl", + "type": "string", + "description": "实际请求地址" + } + ], + "errors": [ + { + "code": "400", + "description": "type 不能为空" + }, + { + "code": "500", + "description": "PDD 接口调用失败" + } + ] + }, + { + "method": "index.recognizeLicensePlate", + "description": "识别车牌号码(通过 base64 图片)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "base64", + "type": "string", + "required": true, + "source": "body", + "description": "base64 图片,支持 data URL 前缀(data:image/...;base64,)或纯 base64 字符串" + }, + { + "name": "imageBase64", + "type": "string", + "required": false, + "source": "body", + "description": "兼容字段(同 base64)" + }, + { + "name": "image_base64", + "type": "string", + "required": false, + "source": "body", + "description": "兼容字段(同 base64)" + } + ], + "response": [ + { + "name": "licensePlate", + "type": "string", + "description": "识别到的车牌号(对外契约,仅返回该字段)" + } + ], + "errors": [ + { + "code": "400", + "description": "base64 图片不能为空 / base64 图片格式不正确 / 图片大小不能超过 7MB" + }, + { + "code": "500", + "description": "第三方 OCR 服务调用失败或腾讯云配置未设置" + } + ] + }, + { + "method": "index.getI18nMessage", + "description": "index.getI18nMessage 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "language", + "type": "string", + "required": false, + "source": "body|query", + "description": "language 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.putI18nCollect", + "description": "index.putI18nCollect 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "keys", + "type": "array", + "required": false, + "source": "body", + "description": "keys 参数" + }, + { + "name": "locale", + "type": "string", + "required": false, + "source": "body", + "description": "locale 参数" + }, + { + "name": "project", + "type": "string", + "required": false, + "source": "body", + "description": "project 参数" + }, + { + "name": "source", + "type": "string", + "required": false, + "source": "body", + "description": "source 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.tryAutoTranslateNewKeys", + "description": "index.putI18nCollect 的内部辅助方法:目标语言非 zh-CN 时,为该项目在 zh-CN 已有翻译的键批量创建目标语言的翻译占位记录(translation=null、translation_status=0、auto_generated=1、translator=auto-translate),不调用翻译 API;无对外返回值,异常仅记日志,不建议作为 HTTP API 直接调用", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "project", + "type": "string", + "required": false, + "source": "body", + "description": "项目标识(如 wms);该方法为 putI18nCollect 的内部辅助函数,project 由 putI18nCollect 内部传入,不建议直接调用本接口传参" + }, + { + "name": "targetLanguage", + "type": "string", + "required": false, + "source": "body", + "description": "目标语言代码(如 en-US);为 zh-CN 时方法直接返回,不生成任何翻译占位记录" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.searchSpace", + "description": "按当前仓库上下文搜索库位(使用 ctx.user.store_id;仅在 location_space 表中按 space_code/custom_barcode 搜索)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "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": [] + }, + { + "method": "index.searchSpaces", + "description": "按当前仓库上下文批量搜索库位(使用 ctx.user.store_id;对每个关键字在 location_space 表中按 space_code/custom_barcode/custom_name 做模糊匹配,结果按传入顺序返回)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keywords", + "type": "array", + "required": true, + "source": "body", + "description": "搜索关键字数组,每项对 space_code、custom_barcode、custom_name 做模糊匹配(%keyword%);非数组视为空数组" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "description": "全局调用结果标识,成功时为 success" + }, + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "description": "返回信息" + }, + { + "name": "data", + "type": "array", + "description": "库位列表的数组,与 keywords 一一对应;每项为库位数组(最多 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": "返回的分组数量(等于 keywords.length)" + } + ], + "errors": [] + }, + { + "method": "index.listInterfaceTypes", + "description": "查询可用的接口类型列表(如奇门仓储、开放接口等)", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [] + }, + { + "method": "index.getLocationTypeList", + "description": "查询库位类型基础列表,优先返回当前仓库下启用的库位类型,同时合并系统公共类型;结果带 300 秒缓存", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "list", + "type": "array", + "description": "库位类型列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "库位类型 ID" + }, + { + "name": "type_code", + "type": "string", + "description": "库位类型编码" + }, + { + "name": "type_name", + "type": "string", + "description": "库位类型名称" + }, + { + "name": "temperature_zone", + "type": "string", + "description": "温区" + }, + { + "name": "allow_allocation", + "type": "boolean", + "description": "是否允许分配储位" + }, + { + "name": "allow_transfer_out", + "type": "boolean", + "description": "是否允许移出" + }, + { + "name": "description", + "type": "string", + "description": "描述" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库 ID,null 表示系统公共类型" + } + ] + }, + { + "name": "total", + "type": "number", + "description": "返回总数" + } + ], + "errors": [] + }, + { + "method": "index.getPlatformOauthLink", + "description": "获取平台授权链接。入参支持 code / platform_code / platformCode,服务端按首个非空值标准化为大写平台编码;会从当前登录上下文读取仓库 ID(ctx.user.store_id),再从 wms_platform.auth_base_url 读取授权基础地址。接口会优先复用当前仓库与平台下 status=0 的未授权记录;若历史 auth_random_code 带有当前配置前缀,则会先去前缀后以裸码回写,当前数据库最终保存的 auth_random_code 为裸码。若无可复用记录则生成新的裸码并写入 wms_shops。返回的 oauth_link 会从配置 platformOauthReservationCodePrefix 读取前缀(本地示例为 xxxxx_),按“前缀 + 平台编码 + '_' + 裸码”生成 state,并将 URL 编码后的 state 直接拼接到平台基础授权链接后,例如 xxxxx_PDD_。当前仅支持已按上述模式配置好的基础授权链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码主字段;与 platform_code / platformCode 三选一即可,服务端按 code -> platform_code -> platformCode 顺序取首个非空值并转为大写" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码下划线别名" + }, + { + "name": "platformCode", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码驼峰别名" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "data.platform_code", + "type": "string", + "required": true, + "description": "标准化后的平台编码" + }, + { + "name": "data.oauth_link", + "type": "string", + "required": true, + "description": "基于 wms_platform.auth_base_url 构造的授权链接;实际拼接值为 encodeURIComponent(prefix + platform_code + '_' + rawCode),其中 prefix 来自 platformOauthReservationCodePrefix,rawCode 为数据库 auth_random_code 中保存的裸码。基础授权链接需预先配置为可直接追加 state 值的模式。" + } + ], + "errors": [ + { + "code": 400, + "message": "平台编码不能为空" + }, + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 400, + "message": "平台不存在" + }, + { + "code": 400, + "message": "平台授权基础地址未配置" + }, + { + "code": 500, + "message": "创建平台授权预占记录失败" + }, + { + "code": 500, + "message": "生成唯一授权码失败,请稍后重试" + } + ] + }, + { + "method": "index.getShopList", + "description": "获取当前登录仓库下的已授权店铺列表,支持按平台编码可选过滤。仓库上下文来自 ctx.user.store_id;服务端兼容读取 body.platform_code 与 body.platformCode,按该顺序取首个 trim 后非空值作为平台过滤条件。未传平台参数时返回当前登录仓库下全部已授权店铺;传入非空平台编码时仅返回该平台的已授权店铺。结果按 status DESC、updated_at DESC、id DESC 排序,并对敏感字段完成脱敏后返回 data.list。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码过滤条件;兼容 platformCode。服务端按 platform_code、platformCode 的顺序读取首个值,trim 后非空时仅返回该平台的已授权店铺;未传或为空时返回当前登录仓库下全部已授权店铺。" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息,成功时返回 ok" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "当前登录仓库下按条件过滤后的已授权店铺列表数组;未传平台参数时返回当前仓库全部已授权店铺,传入非空 platform_code/platformCode 时仅返回对应平台店铺。结果按 status DESC、updated_at DESC、id DESC 排序,且 owner_id、access_token、refresh_token、auth_random_code 已按实现规则脱敏。", + "children": [ + { + "name": "id", + "type": "number", + "description": "店铺主键 ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库 ID(来自当前登录仓库上下文)" + }, + { + "name": "platform_code", + "type": "string", + "description": "平台编码" + }, + { + "name": "shop_name", + "type": "string", + "description": "店铺名称" + }, + { + "name": "custom_name", + "type": "string|null", + "description": "店铺自定义名称;wms_shops 当前真实字段,未设置时返回 null" + }, + { + "name": "status", + "type": "number", + "description": "授权状态:0=未授权,1=已授权" + }, + { + "name": "auth_expire_at", + "type": "string|null", + "description": "授权到期时间,未设置时返回 null" + }, + { + "name": "token_expires_at", + "type": "string|null", + "description": "访问令牌过期时间,未设置时返回 null" + }, + { + "name": "refresh_token_expires_at", + "type": "string|null", + "description": "刷新令牌过期时间,未设置时返回 null" + }, + { + "name": "scope", + "type": "object|array|null", + "description": "授权范围;直接返回数据库 JSON 字段内容,可能为对象、数组或 null" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + }, + { + "name": "owner_id", + "type": "string|null", + "description": "平台店铺/主体 ID;非空且长度大于 5 时返回前 3 位 + *** + 后 2 位,长度小于等于 5 时返回 ***,空值返回 null" + }, + { + "name": "access_token", + "type": "string|null", + "description": "访问令牌;非空固定返回 ***,空值返回 null" + }, + { + "name": "refresh_token", + "type": "string|null", + "description": "刷新令牌;非空固定返回 ***,空值返回 null" + }, + { + "name": "auth_random_code", + "type": "string|null", + "description": "授权随机码;非空固定返回 ***,空值返回 null" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库" + } + ] + }, + { + "method": "index.getShopExpressList", + "description": "获取指定店铺的快递签约/电子面单可用列表。接口依赖当前登录仓库上下文 ctx.user.store_id 校验店铺归属;服务端会按店铺所属平台拉取并收敛可用快递列表,统一返回前端消费结构;未接入的平台当前返回空列表。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "shop_id", + "type": "string|number", + "required": false, + "source": "body", + "description": "店铺 ID;与 shopId 兼容,二选一至少传一个。服务端按 shop_id、shopId 的顺序读取首个非空值。" + }, + { + "name": "shopId", + "type": "string|number", + "required": false, + "source": "body", + "description": "店铺 ID 的驼峰兼容字段;当 shop_id 为空时读取该值。" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息,成功时返回 ok。" + }, + { + "name": "data.shop_id", + "type": "number", + "required": true, + "description": "当前店铺 ID。" + }, + { + "name": "data.platform_code", + "type": "string", + "required": true, + "description": "店铺所属平台编码,返回值按服务端实现转为大写。" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "服务端按店铺所属平台拉取并统一收敛后的快递签约/电子面单可用列表;未接入的平台返回空数组。非 PDD 平台的每条记录会按 sys_express_code 匹配 wms_express_product_type 补充 product_types 字段,PDD 平台不返回该字段。", + "children": [ + { + "name": "wp_code", + "type": "string", + "required": true, + "description": "快递/面单服务编码。" + }, + { + "name": "wp_name", + "type": "string", + "required": true, + "description": "系统快递名称;由系统快递基础表根据平台快递编码 wp_code 映射得到,未匹配到时返回空字符串。" + }, + { + "name": "sys_express_code", + "type": "string", + "required": true, + "description": "系统快递编码;由平台快递编码 wp_code 映射得到,未匹配到时返回空字符串。" + }, + { + "name": "product_types", + "type": "array", + "required": true, + "description": "系统快递对应的产品类型列表(仅非 PDD 平台返回);按 sys_express_code 与 wms_express_product_type.express_code 匹配(不区分大小写),数据经系统快递服务缓存读取,未匹配到时返回空数组;PDD 平台不返回该字段。", + "children": [ + { + "name": "name", + "type": "string", + "required": true, + "description": "产品类型名称;为空时回退为 code。" + }, + { + "name": "code", + "type": "string", + "required": true, + "description": "产品类型编码。" + } + ] + }, + { + "name": "wp_type", + "type": "string", + "required": true, + "description": "快递/面单类型标识。" + }, + { + "name": "accounts", + "type": "array", + "required": true, + "description": "当前快递服务下的签约账号列表;无签约账号时返回空数组。", + "children": [ + { + "name": "branch_code", + "type": "string", + "required": true, + "description": "网点/签约账号编码。" + }, + { + "name": "branch_name", + "type": "string", + "required": true, + "description": "网点/签约账号名称。" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "description": "当前可用单量。" + }, + { + "name": "cancel_quantity", + "type": "number", + "required": true, + "description": "已取消单量。" + }, + { + "name": "recycled_quantity", + "type": "number", + "required": true, + "description": "已回收单量。" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": true, + "description": "已分配单量。" + }, + { + "name": "ship_addresses", + "type": "array", + "required": true, + "description": "发货地址列表;无可用地址时返回空数组。", + "children": [ + { + "name": "country", + "type": "string", + "required": true, + "description": "国家。" + }, + { + "name": "province", + "type": "string", + "required": true, + "description": "省。" + }, + { + "name": "city", + "type": "string", + "required": true, + "description": "市。" + }, + { + "name": "district", + "type": "string", + "required": true, + "description": "区/县。" + }, + { + "name": "detail", + "type": "string", + "required": true, + "description": "详细地址。" + }, + { + "name": "full_address", + "type": "string", + "required": true, + "description": "完整地址。" + } + ] + }, + { + "name": "services", + "type": "array", + "required": true, + "description": "当前签约账号可用的附加服务列表;无可用服务时返回空数组。", + "children": [ + { + "name": "service_code", + "type": "string", + "required": true, + "description": "服务编码。" + }, + { + "name": "service_name", + "type": "string", + "required": true, + "description": "服务名称。" + }, + { + "name": "service_desc", + "type": "string", + "required": true, + "description": "服务说明。" + }, + { + "name": "required", + "type": "boolean", + "required": true, + "description": "是否为必选服务。" + }, + { + "name": "attributes", + "type": "array", + "required": true, + "description": "服务属性列表;无属性时返回空数组。", + "children": [ + { + "name": "attribute_code", + "type": "string", + "required": true, + "description": "属性编码。" + }, + { + "name": "attribute_name", + "type": "string", + "required": true, + "description": "属性名称。" + }, + { + "name": "attribute_type", + "type": "string", + "required": true, + "description": "属性类型编码。" + }, + { + "name": "type_desc", + "type": "string", + "required": true, + "description": "属性类型说明。" + } + ] + } + ] + } + ] + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "shop_id 不能为空" + }, + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 404, + "message": "店铺不存在" + }, + { + "code": 400, + "message": "店铺未授权" + } + ] + }, + { + "method": "index.getCainiaoStfTemplates", + "description": "公共无参查询淘宝菜鸟标准模板列表;服务端调用淘宝开放平台 cainiao.cloudprint.stdtemplates.get,请求地址为 https://eco.taobao.com/router/rest,使用 TOP 公共签名参数。不需要用户授权,不下发 session,不依赖登录态、当前仓库或店铺授权。成功返回 data.platform_code='TB' 与标准模板数组,模板项统一字段为 template_id/template_name/template_url/cp_code/wp_code。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息,成功时返回 ok。" + }, + { + "name": "data.platform_code", + "type": "string", + "required": true, + "description": "平台编码,固定返回 TB。" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "菜鸟标准模板列表;来源于 cainiao_cloudprint_stdtemplates_get_response.result.datas[*].standard_templates[*] 的宽松兼容解析结果,按统一字段 template_id/template_name/template_url/cp_code/wp_code 返回。", + "children": [ + { + "name": "template_id", + "type": "string", + "required": true, + "description": "模板唯一标识;缺失时返回空字符串。" + }, + { + "name": "template_name", + "type": "string", + "required": true, + "description": "模板名称;缺失时返回空字符串。" + }, + { + "name": "template_url", + "type": "string", + "required": true, + "description": "模板预览或打印地址;缺失时返回空字符串。" + }, + { + "name": "cp_code", + "type": "string", + "required": true, + "description": "快递公司编码;结合 datas 节点与模板项宽松提取,缺失时返回空字符串。" + }, + { + "name": "wp_code", + "type": "string", + "required": true, + "description": "快递面单服务编码;结合 datas 节点的 brand_code/cp_code 与模板项宽松提取,缺失时返回空字符串。" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "淘宝菜鸟标准模板查询失败" + } + ] + }, + { + "method": "index.getPrintPlatformTemplateList", + "description": "按打印平台与快递编码查询模板列表。express_code 为必填;接口会先按 platform_code(默认 CAINIAO)定位 wms_express 对应打印平台字段,再以 express_code 过滤可用模板后返回。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "打印平台编码(如 CAINIAO);不传默认 CAINIAO,服务端会转为大写。" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "source": "body", + "description": "快递编码(必填);服务端会转为大写,并用于按 wms_express 中对应打印平台字段筛选模板。" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局结果标识;成功为 success,失败为 failure。" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码;成功时为 200。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息;成功时为 ok。" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "返回数据对象。", + "children": [ + { + "name": "platform_code", + "type": "string", + "required": true, + "description": "规范化后的平台编码(大写);未传时默认 CAINIAO。" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "description": "规范化后的快递编码(大写)。" + }, + { + "name": "responseData", + "type": "object", + "required": true, + "description": "平台模板响应数据;CAINIAO 场景下会按 platform_code 对应字段 + express_code 过滤 cainiao_cloudprint_stdtemplates_get_response.result.datas 后返回,未实现平台返回空对象。" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "express_code 不能为空" + }, + { + "code": 500, + "message": "获取打印平台模板列表失败" + } + ] + }, + { + "method": "index.polyapiAuthorizeUrl", + "description": "生成菠萝派授权链接。该接口不接收请求参数,服务端会固定调用 Differ.JH.BuildeAuthorizeUrl,并以内置配置 this.app.config.poloApi.appKey / this.app.config.poloApi.secret 以及当前代码中写死的 callbackUrl=http://39.100.57.68/、state=123456、itemcode=test001 作为上游请求参数,最终将菠萝派接口原始响应包裹后返回。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息,成功时返回 ok。" + }, + { + "name": "data.respone", + "type": "object", + "required": true, + "description": "菠萝派接口 Differ.JH.BuildeAuthorizeUrl 的原始响应对象。字段名按当前实现保持为 respone。" + } + ], + "errors": [] + }, + { + "method": "index.toOrder", + "description": "根据运单号快速查询订单ID及其所属波次下所有订单ID列表。查询流程:1) 通过运单号查询 wms_order_express 表(status=1)获取 order_id 和 warehouse_id;2) 遍历多表(current/history/dispatch)获取 wave_id 和 wave_no;3) 若有有效波次则再遍历多表查询该波次下所有订单的 ID 列表。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "waves", + "type": "array", + "required": true, + "description": "波次列表,无波次时为空数组。每项含 wave_id(波次ID,number)、wave_no(波次号,string)、order_ids(波次下所有订单ID列表,number[])" + }, + { + "name": "waves[].wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "waves[].wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "waves[].order_ids", + "type": "array", + "required": true, + "description": "该波次下所有订单的 ID 列表" + } + ], + "errors": [ + { + "code": 405, + "message": "运单号不能为空" + }, + { + "code": 405, + "message": "未找到该运单号对应的订单" + } + ] + }, + { + "method": "index.getWorkbenchBindCode", + "description": "获取工作台绑定码(免登录、免鉴权,参考 user.getLoginWechatCode):返回 client_code 并在缓存生成绑定码;不传 client_code 时分配新客户端编码并立即返回绑定码;传入 client_code 时进入长轮询等待 workbench.bind 完成,绑定成功后返回 token,等待超时/缓存失效时重新生成绑定码后才返回数据", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "clientCode", + "type": "string", + "required": false, + "source": "body", + "description": "客户端编码(6 位大写字母+数字);首次可不传,后续轮询建议透传已有值" + } + ], + "response": [ + { + "name": "client_code", + "type": "string", + "required": true, + "description": "客户端编码(6 位大写字母+数字)" + }, + { + "name": "code", + "type": "string", + "required": true, + "description": "缓存生成的绑定码(6 位大写字母+数字,供 workbench.bind 使用)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "会话状态:pending 等待绑定 / bound 已绑定" + }, + { + "name": "workbench_id", + "type": "number", + "required": false, + "description": "已绑定的工作台ID(仅 bound 状态返回)" + }, + { + "name": "token", + "type": "string", + "required": false, + "description": "绑定成功后返回的工作台 token(64 位,仅 bound 状态返回)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "状态更新时间" + }, + { + "name": "expires_at", + "type": "string", + "required": false, + "description": "会话过期时间(ISO 字符串,可能为 null)" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": true, + "description": "距离过期的剩余毫秒数" + } + ], + "errors": [ + { + "code": "400", + "message": "无效的客户端编码格式" + } + ] + }, + { + "method": "index.LoginWorkbenchByCode", + "description": "通过工作台登录码登录获取 token(免登录、免鉴权):以 wms_workbench.login_code 为入参查询工作台,命中则返回其 token(工作台尚无 token 时自动生成并持久化,等价补绑定),并将 token 信息写入 workbench:token:{token} 缓存;无匹配工作台返回失败(flag=failure、code=403)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "loginCode", + "type": "string", + "required": true, + "source": "body", + "description": "工作台登录码(前缀 wblc + 随机段共 64 位,兼容 login_code 驼峰/下划线两种入参名)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "工作台ID" + }, + { + "name": "workbench_id", + "type": "number", + "required": true, + "description": "工作台ID(同 id)" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "工作台名称" + }, + { + "name": "token", + "type": "string", + "required": true, + "description": "工作台 token(64 位)" + } + ], + "errors": [ + { + "code": "400", + "message": "login_code 不能为空" + }, + { + "code": "403", + "message": "工作台不存在或登录码无效(返回 flag=failure、code=403)" + } + ] + }, + { + "method": "index.queryUserByToken", + "description": "按 token(ye4s 登录临时码)查询用户信息(免登录、免鉴权):以 ye4s 库 ye4s_user 表 tmp_code 字段为入参查询用户,命中返回 flag=success、code=200 与 real_name(用户真实姓名)、wms_account_id(WMS 账号 ID);未命中返回 flag=failure、code=404(用户不存在);数据库异常返回 code=500", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "token", + "type": "string", + "required": true, + "source": "body", + "description": "ye4s 登录临时码(对应 ye4s 库 ye4s_user 表 tmp_code 字段);为空返回 code 400「token 不能为空」" + } + ], + "response": [ + { + "name": "real_name", + "type": "string", + "required": true, + "description": "用户真实姓名(无值时为空字符串)" + }, + { + "name": "wms_account_id", + "type": "number", + "required": false, + "description": "WMS 账号 ID(未绑定时为 null)" + } + ], + "errors": [ + { + "code": "400", + "message": "token 不能为空" + }, + { + "code": "404", + "message": "用户不存在(返回 flag=failure、code=404)" + }, + { + "code": "500", + "message": "查询失败(数据库异常,message 为具体错误信息)" + } + ] + }, + { + "method": "index.uploadClientErrorLog", + "description": "上报客户端错误日志(免登录、免权限、免鉴权,保留系统日志):设备端将运行时错误日志批量上报到服务端暂存表 wms_client_error_log。入参支持三种形态——单条对象、数组、{ logs: [...] },单次最多 50 条;字段命名兼容 snake_case 与 camelCase 别名。error_message 与 error_stack 至少一项有值(超长分别截断 5000 / 65535 字符),extra 超长截断 65535;report_uuid 幂等去重(重复上报静默成功,duplicated +1、不产生重复行;缺失时服务端生成 srv-{uuid} 且不保证幂等);client_time 仅参考(毫秒/秒时间戳或日期字符串,非法值存 null)。成功返回 flag=success、code=200 与 total/accepted/duplicated/rejected/rejected_reasons 统计;方法级错误按 /system 惯例为 HTTP 200 + flag=failure(code=400/500)。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "client_type", + "type": "string", + "required": false, + "source": "body", + "description": "客户端类型:android/ios/web 等;表宽 STRING(32),超出截断;兼容 camelCase 别名 clientType" + }, + { + "name": "app_version", + "type": "string", + "required": false, + "source": "body", + "description": "客户端版本号;表宽 STRING(64),超出截断;别名 appVersion" + }, + { + "name": "device_id", + "type": "string", + "required": false, + "source": "body", + "description": "设备唯一标识;表宽 STRING(128),超出截断;别名 deviceId" + }, + { + "name": "os_version", + "type": "string", + "required": false, + "source": "body", + "description": "操作系统版本;表宽 STRING(64),超出截断;别名 osVersion" + }, + { + "name": "device_model", + "type": "string", + "required": false, + "source": "body", + "description": "设备型号;表宽 STRING(128),超出截断;别名 deviceModel" + }, + { + "name": "error_type", + "type": "string", + "required": false, + "source": "body", + "description": "错误类型/等级;表宽 STRING(64),超出截断;别名 errorType" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "source": "body", + "description": "错误信息;与 error_stack 至少一项有值,超长截断至 5000 字符;别名 errorMessage" + }, + { + "name": "error_stack", + "type": "string", + "required": false, + "source": "body", + "description": "错误堆栈;与 error_message 至少一项有值,超长截断至 65535 字符;别名 errorStack" + }, + { + "name": "extra", + "type": "string", + "required": false, + "source": "body", + "description": "附加上下文;字符串或对象(对象序列化为 JSON 字符串),超长截断至 65535 字符" + }, + { + "name": "report_uuid", + "type": "string", + "required": false, + "source": "body", + "description": "客户端上报幂等ID(唯一索引 uk_report_uuid);表宽 STRING(64),超出截断;重复上报静默成功(duplicated +1,不产生重复行);缺失时服务端生成 srv-{uuid},此时不保证幂等;别名 reportUuid" + }, + { + "name": "client_time", + "type": "string", + "required": false, + "source": "body", + "description": "客户端错误发生时间(仅参考,不作为记录时间):毫秒/秒时间戳或日期字符串,非法值存 null;别名 clientTime" + }, + { + "name": "logs", + "type": "array", + "required": false, + "source": "body", + "description": "包裹形态 { logs: [...] } 的上报条目数组,单次最多 50 条;与「单条对象」「数组」三种形态三选一" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "结果标记:success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:200 成功;400 入参形状错误/空数据/超 50 条/全部条目无效;500 查询或写入失败(方法级错误仍为 HTTP 200)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示文案:成功为「上报成功」" + }, + { + "name": "success", + "type": "boolean", + "required": true, + "description": "服务处理结果标记:true 表示成功(400/500 失败响应无此字段)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "本次上报条数" + }, + { + "name": "accepted", + "type": "number", + "required": true, + "description": "新入库条数" + }, + { + "name": "duplicated", + "type": "number", + "required": true, + "description": "幂等去重条数(report_uuid 已存在,静默成功、不产生重复行)" + }, + { + "name": "rejected", + "type": "number", + "required": true, + "description": "校验失败条数" + }, + { + "name": "rejected_reasons", + "type": "array", + "required": false, + "description": "拒绝明细(最多返回 10 条),每条含 index(0 起条目下标)与 reason(原因文案)" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务端响应时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "入参形状错误(非对象/数组且无 logs 键)、缺少上报日志数据(空数组)、单次超过 50 条、全部条目无效(error_message 与 error_stack 均无值);HTTP 200 + flag=failure,body 仅含 flag/code/message/timestamp" + }, + { + "code": 500, + "message": "查询已有 report_uuid 失败或批量写入失败(HTTP 200 + flag=failure,body 仅含 flag/code/message/timestamp)" + } + ] + }, + { + "method": "index.getWarehousePanelData", + "description": "仓库面板数据接口:按仓库做增量变更检测,is_change=false 时返回空 data(节约流量),data 已填充有数据源的字段(无数据源的字段暂不输出)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "last_change_at", + "type": "number", + "required": false, + "source": "body", + "description": "最后一次更改的时间戳(Unix 秒);常规调用(force=false)必填,小于缓存最后更改时间戳时返回 is_change=true;force=true 时可选,缺省视为 0" + }, + { + "name": "force", + "type": "boolean", + "required": false, + "source": "body", + "description": "首次拉取兼容入参(true/1/'true'),当前仅影响 last_change_at 是否可缺省" + } + ], + "response": [ + { + "name": "is_change", + "type": "boolean", + "required": true, + "description": "是否已改变:传入时间戳小于缓存最后更改时间戳时为 true,否则为 false(缓存无最后时间时恒为 true)" + }, + { + "name": "last_change_at", + "type": "number", + "required": true, + "description": "缓存最后更改时间戳(Unix 秒,一般由外部业务驱动;缓存无最后时间时为本接口拉取数据时刻);前端保存后作为下次轮询的 last_change_at 入参回传" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "面板数据对象;is_change=false 时为空对象(节约流量),is_change=true 时输出。已输出字段:title(仓库名)、fulfillment(订单履约链路 6 环节未/已 + total + items 末尾两项今日退件/今日拆包;各环节未/已均含配送表今日出库按环节状态拆分补数,打包环节已* 用订单状态存量口径(池内 pack_status=fin + 配送表今日出库 pack_status=fin,保证已复核≥已打包))、stageOverview(totalOrders/interceptOrders/stages 5 卡:receiving/shelf/pick/recheck/pack,pack 卡 today=今日已完成打包的真实订单数(status=2,不含打包中):散单任务数 + 团购波次 wms_order_wave_index 真实订单数(替代 pack_quantity 快照),doing=打包中订单数(订单表 pack_status=padding 池内+配送今日出库双表)、abnormal=异常订单数(订单表对应状态 error 池内+配送今日出库双表;拣货 doing 同样为订单表 pick_status=padding 双表))、b2b(orders/goods/sku)、groupPicking、scatterPicking(orders/goods/sku/wave/top5)、groupPacking、scatterPacking(各含 orders/goods/sku/wave/top5,按波次范围 wave_scope 区分:团购块 top 按打包台、散单块 top 按打包员)、trend(max/total/points 业务日 24 点:label 从仓库自然日开始时间(day_start_time)起到次日自然日开始时间,每点 { label, created_count }——created_count=业务日窗口内下单量(池内待处理 + 配送表今日出库订单按订单创建时间落桶,窗口即业务日 [自然日开始时间, 次日自然日开始时间):未到次日自然日开始时间时=今日自然日开始时间起,凌晨(已过零点)时=昨日自然日开始时间起)并按小时累计(最后一点=业务日内下单总量);total=今日总单量(与 fulfillment.total 同口径:待处理订单池 + 配送表今日出库))、weeklyEfficiency(days 7 天 intercept)" + } + ], + "errors": [], + "notes": [ + "外部驱动公共方法(本次新增):app/service/systems/warehouse_panel.js#touchLastChangeAt(warehouseId)——业务数据变化时调用一行即可更新该仓库面板最后更新时间戳(只写时间戳整值替换、TTL 300 秒,失败仅告警不影响主流程);已接入拣货完成(systems/pick.js#wavePickTaskComplete)、复核完成(systemMethods/order/recheckOrder.js#confirmRecheck/confirmRecheckByWaveId/batchQuickRecheck/batchQuickRecheckByWave)、打包完成(systems/workbench.js#_updateOrderPackStatus,覆盖工作台手动结束/新任务关闭旧任务/超时自动结束等全部打包结束路径)。", + "缓存键 index:warehousePanel:lastChangeAt:{warehouseId},值为 { last_change_at, data },TTL 300 秒。拉取逻辑:缓存有最后更新时间且传入时间戳未过期 → is_change=false + 空 data 不查库;时间戳过期且缓存有数据 → 直接输出缓存数据;时间戳过期但缓存无数据(外部只驱动了时间戳)→ 查库拉数据补入缓存并保留外部时间戳;缓存无最后更新时间(未命中/过期)→ 查库拉数据并设置最后更新时间", + "最后更新时间一般由外部驱动:业务数据变化时由外部写入缓存键的 last_change_at(只写时间戳即可,数据由本接口下次拉取时补入)", + "未输出字段(数据源或口径未定):履约链路第 7 环节退件签收、stageOverview 质检卡、收货/上架卡的 today/abnormal、weeklyEfficiency 的 throughput/max", + "口径:fulfillment 各环节未* = 常用表池内未完成 + 配送分表今日出库未完成(真实状态);已* 口径:分配/打印/拣货均从订单表状态获取(池内 fin + 配送表今日出库 fin,保证已分配≥已打印≥已拣货的流程约束),复核=今日复核时间(recheck_time 双表)、打包=订单状态存量口径(池内 pack_status=fin + 配送表今日出库 pack_status=fin,保证已复核≥已打包;此前「今日打包任务订单数」口径会大于已复核(打包任务快照含未复核订单),已改回)、出库=今日出库数;出库环节未+已=total,其余环节已* 为状态/今日作业口径、未* 为真实状态口径;面板全部今日统计窗口按仓库配置自然日开始时间 day_start_time(默认 06:00)划分:今日=[当日06:00, 次日06:00),当前时间早于当日 06:00 时窗口为 [昨日06:00, 当日06:00)(昨日 06:00 后的订单视为今日);trend 按业务日窗口双值:横轴 24 点从自然日开始时间起到次日自然日开始时间,created_count(业务日窗口内下单量:池内待处理 + 配送表今日出库订单按订单创建时间落桶,窗口即业务日 [自然日开始时间, 次日自然日开始时间),凌晨(已过零点)时为 [昨日自然日开始时间, 今日自然日开始时间))按小时累计(最后一点=业务日内下单总量);trend 另含 total(今日总单量,与 fulfillment.total 同口径);weeklyEfficiency(7 日)仍按自然日;fulfillment 的 items 末尾两项(今日退件/今日拆包)按 wms_return_received/wms_return_unpack 的 warehouse_id 隔离 + created_at 今日 [00:00, 次日 00:00) 计数;", + "groupPicking/scatterPicking 汇总(orders/goods/sku/wave)按订单表状态口径:池内 pick fin + 配送表今日出库 pick fin,团购=wave_scope IN (1,3)、散单=NOT IN (1,3),团购+散单=已拣货;top 仍按今日创建任务(pick_mode 1,5 团购 / 2,3,4 散单)按人聚合(任务口径,订单表无拣货人);", + "stageOverview 的 pack 卡 today=今日已完成打包的真实订单数(status=2 排除打包中;散单任务数 + 团购任务 wave_id 关联 wms_order_wave_index 的真实订单数去重,替代 pack_quantity 快照避免虚高),窗口内已完成未删除;doing/abnormal 为任务数(打包中/异常任务);" + ] + } + ] + }, + { + "groupName": "订单工作台入口模块", + "module": "order.index", + "list": [ + { + "method": "order.list", + "description": "订单工作台总列表入口,查询当前登录用户仓库上下文下的订单总列表,支持 pagination / where / sort。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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,兼容 currentPage / page_size / size" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会自动标准化;禁止传入 warehouse_id / warehouseId。支持虚拟字段:buyer_message_has(覆盖 buyer_message/seller_message/remark 三个字段,任一有值即为有留言,value=true/false),express_numbers / waybill_codes(运单号筛选),wave_index(波次内序号筛选,联查 wms_order_wave_index,支持 eq/in/gt/lt/ge/le/between/notbetween,between 要求 value 为长度 2 的数组,如 {\"wave_index\":{\"operator\":\"between\",\"value\":[1,50]}}),wave_scope(波次范围筛选,直接按订单表 wave_scope 字段过滤,支持单个值、数组多选或 { operator, value } 结构;取值:0=未分配波次,1=大团购,2=散单,3=小团购,4=单品单件;示例 {\"wave_scope\":{\"operator\":\"in\",\"value\":[1,3]}} 筛选大团购+小团购,{\"wave_scope\":0} 筛选未分配波次订单)。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配);默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + }, + { + "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 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少仓库上下文或 where 参数格式错误" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息;运单信息强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "required": true, + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "required": true, + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "required": true, + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "required": true, + "description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)、package_material_id(包材ID,number|null)、package_material_name_snapshot(包材名称快照,string|null)" + }, + { + "name": "waybill_codes", + "type": "array", + "required": true, + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "message": "订单ID 为空或格式错误" + }, + { + "code": "404", + "message": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "内部错误" + } + ] + }, + { + "method": "order.manualOutboundOrder", + "description": "手动触发出库迁移,将当前仓库内已出库订单同步到配送表。请求体直接透传给 orderDeliveryMigration.syncOutboundOrdersToDelivery。迁移写入配送表(wms_order_delivery_{仓库}_dispatch)的订单行会记录 dispath_time(订单迁移进配送表的时间,由 orderDeliveryMigration.buildDispatchRow 写入 new Date(),仅配送表独有)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "number", + "required": false, + "source": "body", + "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", + "message": "仓库ID为空或请求参数格式错误" + }, + { + "code": "500", + "message": "迁移失败或数据库错误" + } + ] + }, + { + "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" + } + ] + }, + { + "method": "order.queryOrderLogs", + "description": "查询当前仓库下订单操作日志,底层复用通用日志查询分页结构,按订单ID筛选。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "string", + "required": true, + "source": "body", + "description": "订单ID" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "日志列表,字段与 stock.warehouse.queryStockLogs 保持一致" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,包含 page、pageSize、total、totalPages" + } + ], + "errors": [ + { + "code": "400", + "description": "订单ID为空或仓库上下文缺失" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.queryOrderLogList", + "description": "按 order_id 查询订单操作日志,返回全量日志(不分页)。接口按当前登录用户的仓库上下文过滤(method 层从 ctx.user.store_id 获取 warehouse_id),以防跨仓越界。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id / id / orderId", + "type": "string|number", + "required": true, + "source": "body", + "description": "订单ID;支持别名 id 与 orderId,接口会兼容解析。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "日志列表(全量返回,无分页)。每项字段与 stock.warehouse.queryStockLogs 保持一致,典型字段包括 id、action、message、actor、created_at、warehouse_id 等。" + } + ], + "errors": [ + { + "code": "400", + "description": "order_id 为空或格式不合法" + }, + { + "code": "500", + "description": "内部错误" + } + ] + }, + { + "method": "order.updateExpressWeighingWeight", + "description": "更新订单运单称重重量。支持两种模式:1) 订单模式(order_id>0):规则:订单仅一个运单时,直接写入该运单重量;多运单时,必须传 waybill_code 并按运单写入;团购波次批量设置同一重量到波次下所有订单运单,并返回拆单汇总信息(total_weight/split_count/splits/store_name/sys_logistics_name)。2) 运单号模式(order_id=0):从运单号反查订单与波次,散单/非团购波次仅更新单个运单重量,团购波次按 wave_no+business_key 批量设置并返回拆单汇总信息。;散单称重前置打包校验:开启仓库配置 single_weigh_require_pack 后,散单路径(订单模式与运单号模式的散单/非团购波次)写入重量前校验订单波次范围与打包状态,wave_scope 非 1(大团购)/3(小团购)且 pack_status 既非 padding 也非 fin 时拒绝称重(400);团购波次批量称重不校验;配置缺失/读取异常按关闭处理", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number|string", + "required": true, + "source": "body", + "description": "订单ID,必填且必须为数字。订单模式下为正整数,设为0时切换为运单号模式(需配合 waybill_code 使用)。" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "source": "body", + "description": "运单号。订单模式下:订单仅一个运单时可不传且会被忽略,多运单时必填并需匹配订单下运单。运单号模式(order_id=0)下必填。" + }, + { + "name": "weighing_weight", + "type": "number|string", + "required": true, + "source": "body", + "description": "称重重量(g),必填,必须大于 0,必须为正整数。" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": false, + "description": "订单ID。订单模式及运单号散单模式返回。" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "description": "写入重量的运单号。订单模式及运单号散单模式返回。" + }, + { + "name": "weighing_weight", + "type": "number", + "required": true, + "description": "已写入的称重重量(g)。" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "波次号。团购批量模式返回。" + }, + { + "name": "business_key", + "type": "string", + "required": false, + "description": "业务键。运单号团购批量模式返回。" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "波次ID。团购批量模式返回。" + }, + { + "name": "total_weight", + "type": "number", + "required": false, + "description": "所有拆单重量累加(g)。团购批量模式返回。" + }, + { + "name": "split_count", + "type": "number", + "required": false, + "description": "waybill_code 非空的 business_key 数量。团购批量模式返回。" + }, + { + "name": "splits", + "type": "array", + "required": false, + "description": "按 business_key 分组的拆单明细。每项含 business_key(业务键)、weighing_weight(该拆单累加重量)、waybill_code(代表运单号)。团购批量模式返回。" + }, + { + "name": "store_name", + "type": "string", + "required": false, + "description": "货主名称(订单 shop_nick)。团购批量模式返回。" + }, + { + "name": "sys_logistics_name", + "type": "string", + "required": false, + "description": "系统快递名称。团购批量模式返回。" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 必填且必须为数字(订单模式下为正整数;设为 0 时为运单号模式)" + }, + { + "code": 400, + "message": "weighing_weight 必填" + }, + { + "code": 400, + "message": "weighing_weight 格式非法,必须为正整数(单位 g)" + }, + { + "code": 400, + "message": "weighing_weight 必须大于 0" + }, + { + "code": 400, + "message": "多运单订单必须传入 waybill_code" + }, + { + "code": 400, + "message": "订单未打包——开启仓库配置 single_weigh_require_pack 后,散单/非团购波次(wave_scope 非 1 大团购/3 小团购)订单仅在 pack_status 为 padding(打包中)或 fin(已打包)时允许称重" + }, + { + "code": 404, + "message": "未找到有效的订单运单记录" + }, + { + "code": 404, + "message": "waybill_code 未匹配到该订单下的运单记录" + }, + { + "code": 404, + "message": "运单号不存在(运单号模式)" + }, + { + "code": 404, + "message": "运单号对应的订单不存在(运单号模式)" + }, + { + "code": 404, + "message": "波次下未找到订单(团购批量模式)" + }, + { + "code": 500, + "message": "运单模型未初始化" + }, + { + "code": 500, + "message": "订单模型未初始化" + }, + { + "code": 500, + "message": "波次模型未初始化" + }, + { + "code": 500, + "message": "更新称重重量失败" + }, + { + "code": 500, + "message": "批量更新称重重量失败,波次下无有效运单记录(团购批量模式)" + } + ] + }, + { + "method": "order.bindExpressPackageMaterial", + "description": "按订单ID+运单号匹配 wms_order_express,按包材编码匹配包材,并将 package_material_id 与 package_material_name_snapshot 绑定到订单运单记录。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number|string", + "required": true, + "source": "body", + "description": "订单ID,必填。" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号,必填。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "source": "body", + "description": "包材编码,必填。" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID(成功时返回于 data 对象中)。" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_id", + "type": "number", + "required": true, + "description": "绑定后的包材ID(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_name_snapshot", + "type": "string", + "required": true, + "description": "绑定时写入的包材名称快照(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "description": "绑定成功的包材编码(成功时返回于 data 对象中)。" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 404, + "message": "包材编码不存在" + }, + { + "code": 404, + "message": "订单运单记录不存在" + }, + { + "code": 500, + "message": "绑定包材失败" + } + ] + }, + { + "method": "order.export", + "description": "提交订单导出任务(异步)。入参支持 table_type/tableType、module/module_name、export_mode/exportMode;where 与 sort 语义与 order.list 一致。提交后立即返回 task_id,后台异步执行,导出进度/下载请通过 order.exportTaskProgress 查询。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "table_type / tableType", + "type": "string", + "required": false, + "source": "body", + "description": "导出表类型,枚举:current/history/dispatch/outsourced;兼容订单模块别名(order/reviewOrder/pendingOrder 等);支持 table_type 与 tableType 两种写法" + }, + { + "name": "module / module_name", + "type": "string", + "required": false, + "source": "body", + "description": "订单模块名,兼容 module(驼峰)与 module_name(下划线)两种写法" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件,语义与 order.list 的 where 一致(推荐使用 { operator, value, type } 标准结构);禁止传入 warehouse_id/warehouseId" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,语义与 order.list 的 sort 一致" + }, + { + "name": "export_mode / exportMode", + "type": "string", + "required": false, + "source": "body", + "description": "导出模式:waybill(默认,按运单展开,items_detail 列汇总商品)或 item(按商品明细展开,每商品一行);支持 export_mode 与 exportMode 两种写法" + }, + { + "name": "export_columns / exportColumns", + "type": "array", + "required": false, + "source": "body", + "description": "导出表头字段白名单(中文表头字符串数组,如 [\"系统订单号\",\"外部订单号\"]);不传或空数组时输出全部列。枚举(共 57 个,校验不区分导出模式):系统订单号、外部订单号、平台单号、订单ID、订单号、外部单号、订单状态、拦截状态、抓取波次号、波次号、波次序号、货主、平台、来源、店铺昵称、收件人、收件人电话、省、市、区、镇、详细地址、商品明细、仓库商品名称、商品条码、商品图片、数量、物流公司、运单号、业务类型、运单接口、包材ID、包材编码、包材名称、分配时间、订单商品总类数、订单商品总数、SN码数量、SN码、SN码汇总、商品重量、称重重量(g)、订单金额、实收金额、创建时间、支付时间、发货时间、出库状态、复核状态、复核完成状态、复核时间、配货状态、打包状态、备注、买家留言、卖家留言、归档时间。其中仅 waybill 模式输出:系统订单号、外部订单号、平台单号、抓取波次号、商品明细、SN码汇总;仅 item 模式输出:订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量、SN码;其余为两种模式通用(选了当前模式不存在的表头时该列自动忽略)。注意:一旦传入白名单,服务端只按白名单过滤输出列,新增列(如拦截状态、SN码数量、SN码汇总、SN码)必须由调用方在前端导出列选项里同步加上,否则不会出现在导出表头中;不传该参数才会输出当前模式全部列。来源列(字段 create_channel,中文取值:手工单/接口/奇门/出库转单)位于平台列之后,waybill/item 两种模式均输出。传入非法表头会报错(错误信息列出非法值);支持 export_columns 与 exportColumns 两种写法;SN码数量(字段 sn_quantity)为订单明细中启用序列号管理(stock_warehouse.is_sn_mgmt='Y')商品的 plan_qty 合计,用于账单核对:waybill 模式仅在主单号行输出合计值(子单号行为 0),item 模式按商品明细行输出该行 SN 数量(非 SN 商品行为 0)。 SN码(item 模式,字段 sn_codes)为该商品行在复核时登记的 SN 码列表(排序列出,状态限定 BOUND/VERIFIED/REISSUED,排除退回/作废);SN码汇总(waybill 模式,字段 sn_codes_summary)为该订单全部已登记 SN 码的汇总列表,仅主单号行输出(子单号行为空)。" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务 ID(后端生成)", + "required": true + }, + { + "name": "status", + "type": "string", + "description": "任务状态,枚举:submitted/running/success/failed/not_found", + "required": true + }, + { + "name": "progress", + "type": "number", + "description": "当前进度百分比(0-100)", + "required": true + }, + { + "name": "current_count", + "type": "number", + "description": "当前已处理记录数", + "required": true + }, + { + "name": "total_count", + "type": "number", + "description": "总记录数(若有)", + "required": true + }, + { + "name": "message", + "type": "string", + "description": "任务提示信息", + "required": true + }, + { + "name": "result", + "type": "object", + "description": "任务执行结果(可选,可能包含文件 url/fileKey 等)", + "required": true + }, + { + "name": "error", + "type": "string", + "description": "失败时的错误信息(可选)", + "required": true + }, + { + "name": "update_time", + "type": "string", + "description": "任务更新时间(Unix ms 或 ISO 字符串)", + "required": true + } + ], + "errors": [ + { + "code": 400, + "message": "参数格式不正确或 where 条件非法" + }, + { + "code": 500, + "message": "导出任务提交失败" + } + ] + }, + { + "method": "order.exportTaskProgress", + "description": "按 task_id 查询订单导出任务进度,返回 task_id、status、progress、current_count、total_count、message、error、download_url、update_time;上传完成后 download_url 返回下载链接;未找到时 status=not_found。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID,兼容 taskId" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务 ID", + "required": true + }, + { + "name": "status", + "type": "string", + "description": "任务状态:submitted/running/success/failed/not_found", + "required": true + }, + { + "name": "progress", + "type": "number", + "description": "进度百分比(0-100)", + "required": true + }, + { + "name": "current_count", + "type": "number", + "description": "当前已处理记录数", + "required": true + }, + { + "name": "total_count", + "type": "number", + "description": "总记录数", + "required": true + }, + { + "name": "message", + "type": "string", + "description": "额外提示信息", + "required": true + }, + { + "name": "error", + "type": "string", + "description": "失败信息(可选)", + "required": true + }, + { + "name": "download_url", + "type": "string", + "description": "任务完成后下载链接(若有)", + "required": true + }, + { + "name": "update_time", + "type": "string", + "description": "最近一次状态更新时间(Unix ms 或 ISO 字符串)", + "required": true + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + }, + { + "code": 500, + "message": "查询失败或内部错误" + } + ] + }, + { + "method": "order.convertToB2b", + "description": "将待处理订单批量转为 B2B 订单。仅查当前仓库 current 分表(wms_order_delivery_{warehouseId}),对命中订单逐条做准入校验:仅待处理阶段(step in [1,2,3])且未取消、未拣货、未复核、未锁定、未拦截、尚未是 B2B 的订单可转(打印状态不限制,已打印订单同样可转);已取消(status=cancel)、已提交出库/配送中(step=4)、已完成(step=5)、已关闭(step=9)、已拣货(pick_status=fin)、已复核(recheck_status=fin)的订单一律拒绝。已在波次中的订单(含库内抓取进波次的订单)转换成功后会在同一事务内从波次摘除:清空波次字段、重排 wave_index、回写波次统计(波次被清空时置 wave_status=-1);若订单所在波次存在进行中的拣货任务(wms_wave_pick_task.status in (0,1))则跳过该订单。符合条件的在同一事务内把 is_b2b 置 'Y' 并写入 wms_order_b2b 作业明细,事务提交后写操作日志(ORDER_B2B_CONVERT;波次摘除另写 ORDER_WAVE_REMOVE,失败不影响主流程)。不符合条件的订单只跳过、不报错,原因通过 skipped_reasons 返回。单次最多 200 个订单,仓库取自当前登录上下文(ctx.user.store_id),仅能转换本仓订单;撤销使用 order.cancelB2b。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / order_ids / orderIds / id / order_id / orderId", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID集合,单值或数组均可(内部统一转数组)。取值优先级:ids > order_ids > orderIds > id > order_id > orderId;仅保留正整数并去重,单次最多 200 个。" + } + ], + "response": [ + { + "name": "converted_order_ids", + "type": "number[]", + "required": true, + "description": "转换成功的订单 ID 列表(已去重)" + }, + { + "name": "converted_count", + "type": "number", + "required": true, + "description": "转换成功的订单数量" + }, + { + "name": "skipped_order_ids", + "type": "number[]", + "required": true, + "description": "命中订单但不满足准入条件被跳过的订单 ID 列表" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "被跳过的订单数量" + }, + { + "name": "skipped_reasons", + "type": "array", + "required": true, + "description": "跳过原因明细,每项 { order_id, delivery_order_code, reason };reason 取值:订单已取消,不允许转B2B / 订单待审核,不允许转B2B / 订单已提交出库,不允许转B2B / 订单已完成,不允许转B2B / 订单已关闭,不允许转B2B / 订单当前步骤(N)不允许转B2B / 订单已拣货,不允许转B2B / 订单已复核,不允许转B2B / 订单已锁定,不允许转B2B / 订单已拦截,不允许转B2B / 订单所在波次存在进行中的拣货任务,不允许转B2B / 订单已是B2B订单" + }, + { + "name": "not_found_order_ids", + "type": "number[]", + "required": true, + "description": "当前仓库 current 分表中查不到的订单 ID(已进配送/历史/外仓表,或不属于本仓,或 ID 不存在)" + }, + { + "name": "removed_from_wave_order_ids", + "type": "number[]", + "required": true, + "description": "转换成功后从波次中摘除的订单 ID 列表(订单原本不在波次中时为空数组)" + }, + { + "name": "affected_wave_ids", + "type": "number[]", + "required": true, + "description": "因本次摘除而受影响的波次 ID 列表" + }, + { + "name": "emptied_wave_ids", + "type": "number[]", + "required": true, + "description": "摘除后已无剩余订单、被置为 wave_status=-1(作废)的波次 ID 列表" + }, + { + "name": "active_pick_task_wave_ids", + "type": "number[]", + "required": true, + "description": "因存在进行中的拣货任务而跳过转换的波次 ID 列表(对应订单见 skipped_reasons)" + } + ], + "errors": [ + { + "code": "400", + "message": "订单ID不能为空(HTTP 仍为 200,响应体 flag=failure、code=400)" + }, + { + "code": "400", + "message": "单次最多转换 200 个订单(HTTP 仍为 200,响应体 flag=failure、code=400)" + }, + { + "code": "500", + "message": "未识别到当前仓库上下文,HTTP 500,message 为「接口错误: 未识别到当前仓库上下文」" + } + ], + "notes": [ + "准入条件(需同时满足):① 订单存在于当前仓库 current 分表;② status != 'cancel'(未取消);③ step in [1,2,3](待处理阶段);④ pick_status != 'fin'(未拣货);⑤ recheck_status != 'fin'(未复核);⑥ lock_status = 'none'(未锁定,空值视为 none);⑦ intercept_status = 'none'(未拦截,空值视为 none);⑧ is_b2b != 'Y'(尚未是 B2B 订单)。订单是否已在波次中(wave_id > 0)不构成拒绝条件,会在转换成功后自动摘除。", + "打印状态不限制:print_status 为 none / padding / fin 均不影响转换,已打印(fin)的订单同样允许转 B2B;打印与否由前端按业务决定,接口不做拦截。", + "步骤口径:step 采用白名单校验,仅 1 已审核 / 2 处理中 / 3 驳回异常可转;0 待审核、4 配送中(含已提交出库,提交出库时 outbound_status=padding 与 step=4 同时写入)、5 已完成、9 已关闭一律拒绝,其它未知步骤返回「订单当前步骤(N)不允许转B2B」。取消原因优先于步骤及其它校验(已取消订单即使 step 仍在 [1,2,3] 也拒绝)。", + "作业进度口径:pick_status=fin(拣货已完成)与 recheck_status=fin(复核已完成)均拒绝转换,避免把已分拣/已核对的订单改成 B2B;拣货中(pick_status=padding)与拣货异常(pick_status=error)目前不拦截,仅拦截已完成拣货。", + "波次联动口径:已在波次中的订单(无论由团购/散单抓取还是库内抓取进入波次)转换成功后,在同一事务内执行摘除——订单 wave_id / wave_no / wave_scope / wave_strategy_version / wave_scan_result 清零,按波次重排 wms_order_wave_index(wave_index 重新连续编号),wms_wave_batch.total_orders 回写为剩余单数且 processed_orders 取不超过剩余值,剩余 0 单的波次置 wave_status=-1(作废)。", + "拣货任务保护:若订单所在波次存在进行中的拣货任务(wms_wave_pick_task.status in (0,1)),该订单不转换、不摘除,返回原因「订单所在波次存在进行中的拣货任务,不允许转B2B」,涉及波次在 active_pick_task_wave_ids 返回;请走任务取消接口处理后再转。", + "落库行为:订单行 is_b2b 置 'Y'(同时刷新 updated_at);wms_order_b2b 以 (warehouse_id, order_id) 唯一键写入作业明细行,若已存在同仓同单行则重置作业字段(total_box_count=0、pickup_plate_number=null、prep_remark=null、prep_duration_seconds=0、prep_at=null、is_picked_up='N'、picked_up_at=null),created_at 保留首次创建时间。作业明细不再软删除(updated_at / deleted_at / is_print / store_id / delivery_order_code 字段已移除),取消 B2B 时物理删除该行。", + "权限口径:该接口当前在 app/service/systemMethods/order/index.js 的 _noNeedRight / _noNeedLog / _noNeedAuth 名单内,即免接口权限校验、免接口访问日志、免仓库有效期校验,仅需登录。", + "配套接口:order.cancelB2b(取消 B2B 出库,订单流转回正常订单);查询侧使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.cancelB2b", + "description": "取消 B2B 出库,把 B2B 订单流转回正常订单。仅查当前仓库 current 分表(wms_order_delivery_{warehouseId}),对命中订单逐条做准入校验:is_b2b=Y、step != 0(非待审核)、未锁定、未拦截的订单可取消;打印状态不限制,已打印订单同样允许取消。事务内把 is_b2b 置回 'N' 并按 warehouse_id + order_id 物理删除 wms_order_b2b 作业明细(不保留历史),提交后写操作日志(ORDER_B2B_CANCEL,失败不影响主流程)。不符合条件的订单只跳过、不报错,原因通过 skipped_reasons 返回。单次最多 200 个订单,仓库取自当前登录上下文(ctx.user.store_id),仅能取消本仓订单;反向操作为 order.convertToB2b。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / order_ids / orderIds / id / order_id / orderId", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID集合,单值或数组均可(内部统一转数组)。取值优先级:ids > order_ids > orderIds > id > order_id > orderId;仅保留正整数并去重,单次最多 200 个。" + } + ], + "response": [ + { + "name": "canceled_order_ids", + "type": "number[]", + "required": true, + "description": "取消成功的订单 ID 列表(已去重)" + }, + { + "name": "canceled_count", + "type": "number", + "required": true, + "description": "取消成功的订单数量" + }, + { + "name": "skipped_order_ids", + "type": "number[]", + "required": true, + "description": "命中订单但不满足取消条件被跳过的订单 ID 列表" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "被跳过的订单数量" + }, + { + "name": "skipped_reasons", + "type": "array", + "required": true, + "description": "跳过原因明细,每项 { order_id, delivery_order_code, reason };reason 取值:订单待审核,不允许取消B2B / 订单不是B2B订单 / 订单已锁定,不允许取消B2B / 订单已拦截,不允许取消B2B" + }, + { + "name": "not_found_order_ids", + "type": "number[]", + "required": true, + "description": "当前仓库 current 分表中查不到的订单 ID(已进配送/历史/外仓表,或不属于本仓,或 ID 不存在)" + } + ], + "errors": [ + { + "code": "400", + "message": "订单ID不能为空(HTTP 仍为 200,响应体 flag=failure、code=400)" + }, + { + "code": "400", + "message": "单次最多取消 200 个订单(HTTP 仍为 200,响应体 flag=failure、code=400)" + }, + { + "code": "500", + "message": "未识别到当前仓库上下文,HTTP 500,message 为「接口错误: 未识别到当前仓库上下文」" + } + ], + "notes": [ + "准入条件(需同时满足):① 订单存在于当前仓库 current 分表;② is_b2b = 'Y'(是 B2B 订单);③ step != 0(非待审核);④ lock_status = 'none'(未锁定,空值视为 none);⑤ intercept_status = 'none'(未拦截,空值视为 none)。", + "打印状态不限制:print_status 为 none / padding / fin 均不影响取消,已打印(fin)的订单同样允许取消。", + "作业明细处理:取消成功后按 warehouse_id + order_id 物理删除 wms_order_b2b 对应行(DELETE,不保留历史、不做软删除);该表已移除 updated_at / deleted_at / is_print / store_id / delivery_order_code 字段。", + "步骤口径现状:当前仅排除 step=0,step=4(配送中/已提交出库)、5(已完成)、9(已关闭,含取消单)仍可取消;也未校验 pick_status / recheck_status。与 order.convertToB2b 的 step 白名单(仅 1/2/3)口径不一致,如需对齐需另行调整。", + "落库行为:订单行 is_b2b 置回 'N'(同时刷新 updated_at)。转 B2B 时订单已从波次摘除,取消后订单直接回到待处理池,不会回到原波次。", + "权限口径:该接口当前在 app/service/systemMethods/order/index.js 的 _noNeedRight / _noNeedLog / _noNeedAuth 名单内,即免接口权限校验、免接口访问日志、免仓库有效期校验,仅需登录。", + "配套接口:order.convertToB2b(订单转 B2B);查询侧使用 order.pendingOrder2b.list / order.deliveryOrder2b.list(列表行带出作业明细字段)。" + ] + } + ] + }, + { + "groupName": "订单待审核模块", + "module": "order.reviewOrder", + "list": [ + { + "method": "order.reviewOrder.list", + "description": "待审核订单列表,默认仅查询 step=0 的订单。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配);默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + }, + { + "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 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.reviewOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "description": "运单信息数组" + }, + { + "name": "waybill_codes", + "type": "array", + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "description": "订单ID 为空或格式错误" + }, + { + "code": "404", + "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": "订单不存在或不属于当前仓库" + } + ] + }, + { + "method": "reviewOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "required": true, + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "required": true, + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "required": true, + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "required": true, + "description": "运单信息数组" + }, + { + "name": "waybill_codes", + "type": "array", + "required": true, + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "message": "订单ID 为空或格式错误" + }, + { + "code": "404", + "message": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "内部错误" + } + ] + } + ] + }, + { + "groupName": "待处理订单", + "module": "order.pendingOrder", + "list": [ + { + "method": "order.pendingOrder.list", + "description": "待处理订单列表,默认筛选 outbound_status != padding 且 step in [1,2,3]。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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。where 无字段白名单,可直接传订单表列名。lock_status 锁定状态筛选(筛选值用数据库原始枚举 none/warehouse/store,不是响应中的 Y/N;ne 表示不等于;条件值为空自动忽略):未锁定 {\"lock_status\":\"none\"};已锁定(所有非 none){\"lock_status\":{\"operator\":\"ne\",\"value\":\"none\"}}。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。confirm_print_status(确认打印状态筛选,按订单表列过滤;枚举:none=未确认打印、fin=已确认打印)。支持简写与标准结构(同 create_channel 示例),如 {\"confirm_print_status\":\"fin\"} 只查已确认打印订单。claim_status(领料状态筛选,按订单表列过滤;枚举:none=未领料、padding=领料中、fin=已领料、error=异常)。支持简写与标准结构(同 create_channel 示例),如 {\"claim_status\":{\"operator\":\"ne\",\"value\":\"fin\"}} 查未完成领料的订单。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配);默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + }, + { + "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 字段字典”章节),本次新增 store_remark(货主备注)字段;raw 行数据包含 confirm_print_status(确认打印状态,none/fin)与 claim_status(领料状态,none/padding/fin/error)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。lock_status 字段统一输出为 Y/N:none(含空值)→ 'N',其余值(如 warehouse/store)→ 'Y'。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.pendingOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息;忽略传入的表位参数,固定先查配送表(dispatch),查不到再兜底查询待处理表(current);运单信息强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "已忽略:本接口固定先查配送表(dispatch),查不到再兜底待处理表(current),传入该参数不生效" + } + ], + "response": [ + { + "name": "detail", + "type": "object", + "description": "订单头对象(raw 行数据,来自配送表或兜底的待处理表)", + "required": true + }, + { + "name": "orderItems / items", + "type": "array", + "description": "商品明细数组(以库存标准格式为主,附 plan_qty / order_line_no / stock_id / order_item_id / order_id 及拣货库位 picking_locations)", + "required": true + }, + { + "name": "expresses", + "type": "array", + "description": "运单信息数组", + "required": true + }, + { + "name": "storage_items", + "type": "array", + "description": "按库位平铺的储位分配明细(附商品编码、名称、规格、单位等库存信息)", + "required": true + } + ], + "errors": [ + { + "code": "400", + "message": "订单ID 为空或格式错误" + }, + { + "code": "404", + "message": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "内部错误" + } + ] + }, + { + "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" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "source": "body", + "description": "兼容单个订单 ID" + } + ], + "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": "订单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": "订单 ID 正整数数组;不支持 id、order_id 或逗号字符串" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "首条更新记录 ID" + }, + { + "name": "outbound_status", + "type": "string", + "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": "订单不存在或不属于当前仓库" + } + ] + }, + { + "method": "order.pendingOrder.cancelOrder", + "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 正整数数组;不支持 id、order_id 或逗号字符串" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "首条更新记录 ID" + }, + { + "name": "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": "订单不存在或不属于当前仓库" + } + ] + }, + { + "method": "order.pendingOrder.allocateExpressCode", + "description": "批量分配待处理订单的首单快递号(异步接口)。调用后立即返回 task_id,后台异步执行运单创建;可通过 order.pendingOrder.allocateExpressCodeTaskProgress 查询进度。拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。已锁定订单(lock_status 非 none)与拦截订单同样在流水线中被跳过、不参与分配,任务结果(allocateExpressCodeTaskProgress)中包含 skipped_locked_order_ids 等跳过明细。", + "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 数组,例如 [123456, 789012]。sys_platform_code、logistics_code 等字段由后端直接从数据库读取,前端无需传参。" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功时为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "返回信息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "异步受理结果。包含 task_id(任务 ID,用于查询进度)、status(submitted)、message、update_time 等字段。实际运单分配结果需通过 allocateExpressCodeTaskProgress 接口查询。" + } + ], + "errors": [ + { + "code": "400", + "message": "入参格式错误或必填字段缺失" + }, + { + "code": "500", + "message": "运单创建链路或第三方快递接口调用失败" + } + ] + }, + { + "method": "order.pendingOrder.allocateStorage", + "description": "按订单批量分配储位(迁移自 order.storageAllocation.allocateStorage)。这是一个异步提交接口:调用后接口立即返回受理信息(包含 request_id),后端异步执行实际的储位分配与锁定操作;仓库上下文由当前登录用户提供(ctx.user.store_id)。接口不会在同步响应中返回分配明细(如 requested_order_ids、allocated_order_ids 等),客户端可通过请求 ID 或事件/查询链路获取最终结果。已锁定订单(lock_status 非 none)会在分配流水线中被跳过(底层分配结果 skipped_orders 中记录 skipped_reason='locked')。默认仅从库位类型允许分配且启用的储位中分配;传入 allow_storage_location=true 时直接分配储位,无视库位类型的 allow_allocation/is_active 限制。;静态盘点锁定(订单级失败,与库存不足同流程):订单明细中的商品若处于静态盘点锁定中(stock_check.is_static=1 且任务审核完成/盘点中),**该订单**标记分配失败(storage_status=error、order_flag=「静态盘点锁定:sku(x) 盘点单 PDxxx」),不产生拣货行与库存锁定;同批次其它订单继续正常分配,接口仍返回 200,失败订单体现在 shortage_order_ids/shortage_messages/orders", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "allow_storage_location / allowStorageLocation / is_allow_storage / isAllowStorage", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否允许使用存储储位,支持多种字段别名。为 true 时直接分配储位,无视库位类型的 allow_allocation/is_active 限制;缺省时仅校验可分配储位。" + }, + { + "name": "order_ids / orderIds / ids / order_id / orderId / id", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单 ID 列表,支持数组、逗号分隔字符串或单个 ID(兼容多种别名)。" + } + ], + "response": [ + { + "name": "request_id", + "type": "string", + "required": true, + "description": "请求 ID(后端生成的唯一标识),用于查询任务状态或结果" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID(来自当前用户 store_id)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "受理提示信息,通常为 '请求已受理,后端异步处理中' 或错误说明" + } + ], + "errors": [ + { + "code": 400, + "message": "缺少仓库上下文(用户登录上下文无 store_id)" + }, + { + "code": 400, + "message": "订单ID 不能为空(请求中未包含有效 order_ids)" + }, + { + "code": 409, + "message": "存在并发锁定或数据库约束导致的冲突(场景少见,视底层实现抛出)" + }, + { + "code": 500, + "message": "内部错误:模型不可用或数据库/锁定操作失败" + } + ], + "notes": [ + "静态盘点锁定拦截(本次,0.3.316):储位分配在归集订单明细 stock_id 之后、查询可用储位库存之前调用 systems.stockCheck.getStaticLockConflict,命中即回滚事务并返回 { code: 400, message, data: { locked_stock_ids, locked_items } },避免出现「盘点中的商品被分配拣货并锁定库存」;该拦截位于 orderStorageAllocation.allocatePicking(allocateStorage 为其兼容入口),因此 order.pendingOrder.allocateStorage 与内部调用(拣货分配、波次等)均生效。代码依据:app/service/systems/order_storage_allocation.js#allocatePicking(stockIds 归集后静态锁定校验)、app/service/systems/stock_check.js#getStaticLockConflict。", + "静态盘点锁定改为订单级失败(本次,0.3.317):储位分配是批量的(一次可传多个订单),若因静态盘点锁定整单返回 400,会连带把同批次未锁定的订单一起打断,与「库存不足」的既有处理口径(单订单标记失败、其余继续)不一致。现改为:命中锁定的商品行直接跳过分配(不查储位、不加锁、不写拣货行),所在订单按缺货同款路径标记失败——order.storage_status=error、order.step=异常、order_flag=「静态盘点锁定:sku(x) 盘点单 PDxxx」,并在响应 orders/shortage_order_ids/shortage_messages 中体现;同批次其它订单照常分配,接口整体仍返回 200。代码依据:app/service/systems/order_storage_allocation.js#allocatePicking(staticLockRowByStock / staticLockMessage 并入 finalShortageMessage)。" + ] + }, + { + "method": "order.pendingOrder.allocateStorageProgress", + "description": "按 request_id 查询储位分配异步任务状态/结果(由 allocateStorage 提交)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "request_id / requestId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务请求 ID,兼容字段 requestId" + } + ], + "response": [ + { + "name": "request_id", + "type": "string", + "required": true, + "description": "请求 ID(后端生成的唯一标识)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "成功时返回底层分配结果,结构视实现而定" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "失败时返回的错误信息" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "关联仓库 ID(若任务关联仓库时返回)" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "最近一次状态更新时间,ISO8601 字符串" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "额外提示信息" + } + ], + "errors": [ + { + "code": 400, + "message": "request_id 为空或格式不合法" + }, + { + "code": 500, + "message": "内部错误" + } + ] + }, + { + "method": "order.pendingOrder.syncOrderIds", + "description": "同步待处理订单(异步模式)。提交后立即返回 request_id,后台异步执行同步流程。调用方需通过 syncOrderIdsProgress 接口轮询任务进度与最终结果。后台会按 create_channel 分组并行派发同步任务(QM/MANUAL/API);单订单失败写入错误状态(sync_status='error')并标记待处理异常,不影响整批结果;已同步完成(sync_status='fin')的订单会被自动跳过防重复。SN(序列号管理)订单不再无差别拦截:仅当「订单未复核完成」或「SN 明细未齐套(存在序列号明细的已发出 SN 数量少于 plan_qty)」时标记为 error 并跳过派发(failed_reason=sn_batch_forbidden);已复核且 SN 齐套的 SN 订单与普通订单一样参与回传,回传报文 orderLines[].snList 会带上已发出(VERIFIED/REISSUED)的 SN 码。快递未分配订单在同步前即被标记为 error 并跳过派发。API 渠道订单逐单先回传 deliveryorder.confirm,回调成功后才扣减库存并更新 sync_status='fin'(回调失败/异常置 error、不扣减库存,可重新派发);QM/MANUAL 渠道派发成功后更新 sync_status='fin',防止重复同步。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids / order_id / orderId / id", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单 ID 列表,支持数组、逗号分隔字符串或单个 ID。服务端会校验订单状态并执行批量同步拦截规则(含 SN 订单限制)。" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示已受理" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "受理提示信息" + }, + { + "name": "request_id", + "type": "string", + "required": true, + "description": "异步任务唯一标识,用于 syncOrderIdsProgress 查询进度" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "order_ids 不能为空或格式错误" + }, + { + "code": 200, + "message": "failed_reason=sn_batch_forbidden:SN订单SN明细未齐套或未复核完成,不允许回传" + } + ] + }, + { + "method": "order.pendingOrder.syncOrderIdsProgress", + "description": "查询 syncOrderIds 异步任务的进度与结果。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "request_id / requestId", + "type": "string", + "required": true, + "source": "body", + "description": "syncOrderIds 返回的 request_id" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "返回信息" + }, + { + "name": "request_id", + "type": "string", + "required": true, + "description": "请求 ID(原样回传)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted(已受理)/ running(处理中)/ success(完成)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "total_count", + "type": "number", + "required": false, + "description": "总订单数" + }, + { + "name": "processed_count", + "type": "number", + "required": false, + "description": "已处理订单数" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库 ID" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "完成时的同步结果(success 状态时存在),含 success_count / failed_count / dispatch_results 等" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "失败时的错误信息(failed 状态时存在)" + }, + { + "name": "update_time", + "type": "number", + "required": false, + "description": "最后更新时间戳" + } + ], + "errors": [ + { + "code": 400, + "message": "request_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.cancelAllocateStorage", + "description": "待处理模块的取消分配储位入口,直接对接 system service 的 cancelAllocateStorage。仅接受订单ID(order_ids)作为入参,不接受 allow_storage_location 或 warehouse_id/warehouseId;仓库上下文来自当前登录用户的 store_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids / order_id / orderId / id", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单 ID 列表;支持数组、逗号字符串或单个 ID(兼容多种别名)。" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "返回信息,成功或部分成功时给出摘要" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "取消分配汇总结果,包含下列字段", + "children": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID(来自当前用户 store_id)" + }, + { + "name": "requested_order_ids", + "type": "array", + "required": true, + "description": "请求中传入的订单 ID 列表(规范化后)" + }, + { + "name": "cancellable_order_ids", + "type": "array", + "required": true, + "description": "实际可以取消分配的订单 ID 列表" + }, + { + "name": "skipped_orders", + "type": "array", + "required": true, + "description": "被跳过的订单数组,每项至少包含 order_id 与 skipped_reason(如 not_found / not_allocated / no_allocation)" + }, + { + "name": "orders", + "type": "array", + "required": true, + "description": "每个订单的取消分配结果数组,包含成功与跳过记录(合并 skipped_orders 与成功结果)" + }, + { + "name": "picking_count", + "type": "number", + "required": true, + "description": "本次被取消的 picking 行数" + }, + { + "name": "storage_unlock_summary", + "type": "array", + "required": true, + "description": "按 storage_id 汇总的解锁数量数组({storage_id, unlocked_quantity})" + }, + { + "name": "stock_unlock_summary", + "type": "array", + "required": true, + "description": "按 stock_id 汇总的解锁数量数组({stock_id, unlocked_quantity})" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "缺少仓库上下文" + }, + { + "code": 400, + "message": "订单ID不能为空" + }, + { + "code": 500, + "message": "内部错误:模型不可用或数据库/回滚失败" + } + ] + }, + { + "method": "order.pendingOrder.updateOrderPlatform", + "description": "批量修改待处理订单的平台信息。用 code 查找 wms_platform 表,若平台存在则将订单的 sys_platform_code 和 sys_platform_name 更新为该平台的 code/name;若平台不存在则返回错误。只操作当前仓库的当前订单表,不处理其他订单表。正在分配快递(wms_order_express 存在 status=0 取号中占位记录)的订单跳过处理,不影响其余订单,跳过明细通过 skipped_order_ids 透出。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID 正整数数组,不能为空" + }, + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "平台编码,对应 wms_platform.code" + } + ], + "response": [ + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "实际更新行数" + }, + { + "name": "skipped_order_ids", + "type": "number[]", + "required": false, + "description": "因正在分配快递(取号中)而跳过的订单 ID 列表" + }, + { + "name": "sys_platform_code", + "type": "string", + "required": true, + "description": "更新后的平台编码" + }, + { + "name": "sys_platform_name", + "type": "string", + "required": true, + "description": "更新后的平台名称" + } + ], + "errors": [ + { + "code": 400, + "message": "order_ids 不能为空" + }, + { + "code": 400, + "message": "code 不能为空" + }, + { + "code": 404, + "message": "平台不存在:" + }, + { + "code": 400, + "message": "缺少仓库上下文" + } + ] + }, + { + "method": "order.pendingOrder.updateOrderExpress", + "description": "批量修改待处理订单的快递信息。用 express_code 从当前仓库快递列表(带缓存)中查找对应项:若为自定义映射(is_system_setting=true),sys_logistics_code/name 写系统快递编码和名称,logistics_code/name 写自定义编码和名称;若为系统快递(is_system_setting=false),四个字段均写系统快递的 code/name;未找到则报错。只操作当前仓库的当前订单表,不处理其他订单表。正在分配快递(wms_order_express 存在 status=0 取号中占位记录)的订单跳过处理,不影响其余订单,跳过明细通过 skipped_order_ids 透出。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID 正整数数组,不能为空" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "source": "body", + "description": "快递编码,可为系统编码或仓库自定义编码" + } + ], + "response": [ + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "实际更新行数" + }, + { + "name": "skipped_order_ids", + "type": "number[]", + "required": false, + "description": "因正在分配快递(取号中)而跳过的订单 ID 列表" + }, + { + "name": "sys_logistics_code", + "type": "string", + "required": true, + "description": "写入的系统快递编码" + }, + { + "name": "sys_logistics_name", + "type": "string", + "required": true, + "description": "写入的系统快递名称" + }, + { + "name": "logistics_code", + "type": "string", + "required": true, + "description": "写入的快递编码(自定义或系统)" + }, + { + "name": "logistics_name", + "type": "string", + "required": true, + "description": "写入的快递名称(自定义或系统)" + } + ], + "errors": [ + { + "code": 400, + "message": "order_ids 不能为空" + }, + { + "code": 400, + "message": "order_ids 仅支持正整数数组" + }, + { + "code": 400, + "message": "express_code 不能为空" + }, + { + "code": 404, + "message": "快递编码 不存在" + } + ] + }, + { + "method": "order.pendingOrder.cloneOrder", + "description": "克隆待处理订单(含已同步 sync_status=fin 订单)。完整流程:1. 查找原订单,校验可取消状态(step 0/1/2/3);2. 若原订单已分配储位(storage_status='fin'),先清除已分配库存,释放失败不阻断克隆(残留占用保留在原订单名下);3. 取消原订单(step→9, status→cancel),记录克隆日志;4. 以原订单业务数据创建新订单,所有流程状态字段重置为初始落库状态,发货单号重新生成为 SYS 前缀新单号(受唯一索引 delivery_order_code+store_id+warehouse_id 约束,不可复制原单号),原单号写入 pre_delivery_order_code 保留克隆追溯链,同步状态继承原订单(原订单已同步 sync_status=fin 则新订单直接置 fin 避免重复回传,否则重置 padding 重新同步);5. 克隆订单明细(含 stock_id),重置 order_id 为新订单 ID;6. 对新订单记录克隆创建日志。克隆新订单不重新占用库存(storage_status=none,不触发储位分配与库存锁定)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number", + "required": true, + "source": "body", + "description": "原订单ID,正整数" + } + ], + "response": [ + { + "name": "source_order_id", + "type": "number", + "required": true, + "description": "原订单ID(已取消)" + }, + { + "name": "new_order_id", + "type": "number", + "required": true, + "description": "新订单ID(克隆生成)" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 不能为空" + }, + { + "code": 400, + "message": "order_id 仅支持正整数" + }, + { + "code": 404, + "message": "订单不存在" + }, + { + "code": 400, + "message": "订单状态不允许克隆(仅支持 step 0/1/2/3)" + } + ] + }, + { + "method": "order.pendingOrder.createOrder", + "description": "手动创建待处理订单。根据货主策略(need_order_approval)决定初始步骤:need_order_approval=1 进待审核(step=0),need_order_approval=0 直接进待处理(step=1)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID(正整数)" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "收件人姓名" + }, + { + "name": "mobile", + "type": "string", + "required": false, + "source": "body", + "description": "收件人手机号,mobile 与 tel 至少填一项" + }, + { + "name": "tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人电话,mobile 与 tel 至少填一项" + }, + { + "name": "detail_address", + "type": "string", + "required": true, + "source": "body", + "description": "详细地址" + }, + { + "name": "province", + "type": "string", + "required": true, + "source": "body", + "description": "省份(必填,空值返回 400)" + }, + { + "name": "city", + "type": "string", + "required": true, + "source": "body", + "description": "城市(必填,空值返回 400)" + }, + { + "name": "area", + "type": "string", + "required": true, + "source": "body", + "description": "区/县(必填,空值返回 400)" + }, + { + "name": "town", + "type": "string", + "required": false, + "source": "body", + "description": "镇/街道" + }, + { + "name": "zip_code", + "type": "string", + "required": false, + "source": "body", + "description": "邮编" + }, + { + "name": "items", + "type": "array", + "required": true, + "source": "body", + "description": "订单明细数组,每项含 item_id(商品主键,必填,正整数)和 plan_qty(计划数量,正整数);item_name(优先外部传入,其次从 StockStore 缓存获取,最后兜底'商品')、order_line_no、actual_price 为可选" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "订单号,不填则自动生成(SYS + 时间戳 + 随机4位)" + }, + { + "name": "logistics_code", + "type": "string", + "required": false, + "source": "body", + "description": "快递编码,不填则读货主默认快递策略(policy_config.default_express_code)" + }, + { + "name": "logistics_name", + "type": "string", + "required": false, + "source": "body", + "description": "快递名称" + }, + { + "name": "sys_platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "系统平台编码,不填则读货主默认平台策略(policy_config.default_platform_code)" + }, + { + "name": "source_platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台编码" + }, + { + "name": "source_order_codes", + "type": "string", + "required": false, + "source": "body", + "description": "来源订单号" + }, + { + "name": "shop_nick", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(自定义),最大长度 200" + }, + { + "name": "order_type", + "type": "string", + "required": false, + "source": "body", + "description": "订单类型" + }, + { + "name": "is_urgency", + "type": "string", + "required": false, + "source": "body", + "description": "是否紧急:Y/N,默认 N" + }, + { + "name": "invoice_flag", + "type": "string", + "required": false, + "source": "body", + "description": "是否需要发票:Y/N,默认 N" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "新创建的订单 ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": true, + "description": "订单号(传入值或自动生成值)" + }, + { + "name": "step", + "type": "number", + "required": true, + "description": "初始步骤:0=待审核,1=待处理" + }, + { + "name": "step_label", + "type": "string", + "required": true, + "description": "步骤说明:待审核 / 待处理" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "商品种类数" + }, + { + "name": "items_total", + "type": "number", + "required": true, + "description": "商品总件数" + } + ], + "errors": [ + { + "code": 400, + "message": "必填字段缺失(含 province/city/area)、items 格式错误(item_id 须为正整数)或 delivery_order_code 重复" + }, + { + "code": 404, + "message": "货主与仓库无有效合约关系(getContractConfig 返回 null 时降级为需审核)" + } + ], + "notes": [ + "使用 item_id 直接匹配商品主键,不依赖外部系统商品同步;item_id 可通过 singleitem.synchronize 返回的 itemId 获取", + "手工单 item_id 即仓库 stock_id(wms_stock_warehouse.id),系统会校验该库存记录归属货主与 store_id 一致,跨货主传库存将被拒绝(商品《xxx》库存归属货主与当前货主不一致)", + "province/city/area 为必填项,空值返回 400" + ] + }, + { + "method": "order.pendingOrder.importOrdersFromExcel", + "description": "通过 Excel 文件批量创建订单。接受 base64 编码的 xlsx 内容,按订单号分组,每组创建一个订单(step 由货主策略决定)。每行代表一条商品明细;同一订单号的多行组成一个完整订单,头信息取每组第一行。(已作废)", + "status": "deprecated", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "file_base64", + "type": "string", + "required": true, + "source": "body", + "description": "base64 编码的 .xlsx 文件内容" + } + ], + "response": [ + { + "name": "total", + "type": "number", + "required": true, + "description": "解析到的订单总数" + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "创建成功的订单数" + }, + { + "name": "fail_count", + "type": "number", + "required": true, + "description": "创建失败的订单数" + }, + { + "name": "success_orders", + "type": "array", + "required": true, + "description": "成功订单列表,每项含 delivery_order_code、order_id、step、step_label" + }, + { + "name": "fail_orders", + "type": "array", + "required": true, + "description": "失败订单列表,每项含 delivery_order_code、error(失败原因)" + } + ], + "errors": [ + { + "code": "400", + "message": "file_base64 为空、Excel 格式无效或无有效数据行" + } + ] + }, + { + "method": "order.pendingOrder.parseAddress", + "description": "智能地址解析:使用内置省市区地址字典遍历方式将非结构化地址字符串解析为省/市/区/详细地址/手机号(不调用 AI)。支持单条解析与数组批量解析:address 传字符串时返回单条结果,addresses(或 address)传字符串数组时批量解析,响应 data.list 按输入顺序返回每条地址的解析结果(失败条目 flag=failure 不影响其他条目)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "address", + "type": "string", + "required": true, + "source": "body", + "description": "原始地址字符串(必填),如\"张三 13800138000 广东省广州市天河区体育西路100号\"。也支持传字符串数组批量解析(与 addresses 二选一)" + }, + { + "name": "addresses", + "type": "string[]", + "required": false, + "source": "body", + "description": "批量地址字符串数组,单次最多 50 条,按数组顺序返回解析结果" + } + ], + "requestBody": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "解析成功时返回 province/city/area/detailAddress/name/mobile" + }, + { + "name": "data.province", + "type": "string", + "required": false, + "description": "省份,如 广东省" + }, + { + "name": "data.city", + "type": "string", + "required": false, + "description": "城市,如 广州市" + }, + { + "name": "data.area", + "type": "string", + "required": false, + "description": "区/县,如 天河区" + }, + { + "name": "data.town", + "type": "string", + "required": false, + "description": "乡镇/街道,如 员村街道" + }, + { + "name": "data.detailAddress", + "type": "string", + "required": false, + "description": "详细地址,如 体育西路100号" + }, + { + "name": "data.name", + "type": "string", + "required": false, + "description": "收件人姓名,如 张三" + }, + { + "name": "data.mobile", + "type": "string", + "required": false, + "description": "收件人手机号,如 13800138000" + }, + { + "name": "data.list", + "type": "array", + "required": false, + "description": "批量解析时返回的结果数组,按输入顺序排列;每条含 address/flag/message/province/city/area/town/detailAddress/name/mobile,失败条目 flag=failure 且解析字段为空字符串" + }, + { + "name": "data.list[].address", + "type": "string", + "required": false, + "description": "原始地址字符串(原样返回)" + }, + { + "name": "data.list[].flag", + "type": "string", + "required": false, + "description": "该条解析状态:success=成功,failure=失败" + }, + { + "name": "data.list[].message", + "type": "string", + "required": false, + "description": "该条解析提示:成功为 ok,失败为具体错误原因" + }, + { + "name": "data.list[].province", + "type": "string", + "required": false, + "description": "省份,如 广东省" + }, + { + "name": "data.list[].city", + "type": "string", + "required": false, + "description": "城市,如 广州市" + }, + { + "name": "data.list[].area", + "type": "string", + "required": false, + "description": "区/县,如 天河区" + }, + { + "name": "data.list[].town", + "type": "string", + "required": false, + "description": "乡镇/街道,如 员村街道" + }, + { + "name": "data.list[].detailAddress", + "type": "string", + "required": false, + "description": "详细地址,如 体育西路100号" + }, + { + "name": "data.list[].name", + "type": "string", + "required": false, + "description": "收件人姓名,如 张三" + }, + { + "name": "data.list[].mobile", + "type": "string", + "required": false, + "description": "收件人手机号,如 13800138000" + } + ], + "errors": [ + { + "code": 400, + "message": "地址字符串不能为空" + }, + { + "code": 400, + "message": "地址数组不能为空" + }, + { + "code": 400, + "message": "单次批量解析最多支持 50 条地址" + }, + { + "code": 500, + "message": "地址解析失败(AI服务异常或密钥未配置)" + } + ], + "notes": [ + "方法部署位置:systemMethods/order/pendingOrder/parseAddress", + "使用本地省市区地址字典遍历识别(原 DeepSeek AI 方式已弃用)", + "解析结果可直接回填到 createOrder 的收件人信息字段", + "未识别到的字段返回空字符串", + "批量解析:addresses 或 address 传字符串数组,按输入顺序逐条遍历识别并聚合返回,单条失败不影响其他条目" + ] + }, + { + "method": "order.pendingOrder.parseAddressLocal", + "description": "本地地址解析接口:不调用 AI,接口内置省市区地址字典数据,对地址字符串遍历匹配识别省/市/区(含直辖市、省直辖县级市、不设区地级市、地级市代管县级市)。与 parseAddress 使用同一套本地字典遍历解析逻辑,两者解析结果等价。支持单条与批量:address 传字符串时返回单条结果,addresses(或 address)传字符串数组时批量解析返回 data.list;address 与 addresses 均不传时,使用接口内置的示例地址数据遍历识别并返回 data.list(data.source=sample)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "address", + "type": "string", + "required": false, + "source": "body", + "description": "原始地址字符串(选填),如\"张三 13800138000 广东省广州市天河区体育西路100号\"。也支持传字符串数组批量解析(与 addresses 二选一);两者均不传时使用内置示例地址数据" + }, + { + "name": "addresses", + "type": "string[]", + "required": false, + "source": "body", + "description": "批量地址字符串数组,单次最多 50 条,按数组顺序返回解析结果;不传 address 与 addresses 时返回内置示例地址数据的遍历识别结果" + } + ], + "requestBody": [], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "解析成功时返回 province/city/area/town/detailAddress/mobile" + }, + { + "name": "data.province", + "type": "string", + "required": false, + "description": "省份,如 广东省" + }, + { + "name": "data.city", + "type": "string", + "required": false, + "description": "城市,如 广州市" + }, + { + "name": "data.area", + "type": "string", + "required": false, + "description": "区/县,如 天河区" + }, + { + "name": "data.town", + "type": "string", + "required": false, + "description": "乡镇/街道,如 员村街道" + }, + { + "name": "data.detailAddress", + "type": "string", + "required": false, + "description": "详细地址,如 体育西路100号" + }, + { + "name": "data.mobile", + "type": "string", + "required": false, + "description": "收件人手机号,如 13800138000" + }, + { + "name": "data.list", + "type": "array", + "required": false, + "description": "批量解析或内置示例数据遍历识别时返回的结果数组,按输入顺序排列;每条含 address/flag/message/province/city/area/town/detailAddress/name/mobile,失败条目 flag=failure 且解析字段为空字符串" + }, + { + "name": "data.list[].address", + "type": "string", + "required": false, + "description": "原始地址字符串(原样返回)" + }, + { + "name": "data.list[].flag", + "type": "string", + "required": false, + "description": "该条解析状态:success=成功,failure=失败" + }, + { + "name": "data.list[].message", + "type": "string", + "required": false, + "description": "该条解析提示:成功为 ok,失败为具体错误原因" + }, + { + "name": "data.list[].province", + "type": "string", + "required": false, + "description": "省份,如 广东省" + }, + { + "name": "data.list[].city", + "type": "string", + "required": false, + "description": "城市,如 广州市" + }, + { + "name": "data.list[].area", + "type": "string", + "required": false, + "description": "区/县,如 天河区" + }, + { + "name": "data.list[].town", + "type": "string", + "required": false, + "description": "乡镇/街道,如 员村街道" + }, + { + "name": "data.list[].detailAddress", + "type": "string", + "required": false, + "description": "详细地址,如 体育西路100号" + }, + { + "name": "data.list[].name", + "type": "string", + "required": false, + "description": "收件人姓名(本地遍历不识别,固定返回空字符串)" + }, + { + "name": "data.list[].mobile", + "type": "string", + "required": false, + "description": "收件人手机号,如 13800138000" + }, + { + "name": "data.source", + "type": "string", + "required": false, + "description": "未传 address/addresses 时为 sample,表示结果来自内置示例地址数据" + } + ], + "errors": [ + { + "code": 400, + "message": "地址字符串不能为空" + }, + { + "code": 400, + "message": "地址数组不能为空" + }, + { + "code": 400, + "message": "单次批量解析最多支持 50 条地址" + }, + { + "code": 500, + "message": "地址解析失败(省市区均无法识别)" + } + ], + "notes": [ + "方法部署位置:systemMethods/order/pendingOrder/parseAddressLocal", + "不调用 AI 接口,本地遍历内置省市区地址字典(LOCAL_CITY_DICT,约 340 个地级市/自治州/地区/盟)识别省市区", + "辅助识别:CHINA_ADMIN_DIVISION_MAP(省直辖县级市/不设区地级市/代管县级市)、PROVINCE_LIST(省份全称与简称)", + "与 parseAddress 使用同一套本地字典遍历解析逻辑,两者解析结果等价", + "本地遍历不识别收件人姓名,name 固定返回空字符串" + ] + }, + { + "method": "order.pendingOrder.updateAddress", + "description": "批量修改待处理订单的收件地址信息。地址字段修改仅允许 post_status='none'(未分配快递)的订单;至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address),空值和纯空白会被忽略。更新成功后写入操作日志。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID 正整数数组,不能为空" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "收件人姓名" + }, + { + "name": "mobile", + "type": "string", + "required": false, + "source": "body", + "description": "收件人手机号" + }, + { + "name": "tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人电话" + }, + { + "name": "zip_code", + "type": "string", + "required": false, + "source": "body", + "description": "邮编" + }, + { + "name": "province", + "type": "string", + "required": false, + "source": "body", + "description": "省份" + }, + { + "name": "city", + "type": "string", + "required": false, + "source": "body", + "description": "城市" + }, + { + "name": "area", + "type": "string", + "required": false, + "source": "body", + "description": "区/县" + }, + { + "name": "town", + "type": "string", + "required": false, + "source": "body", + "description": "镇/街道" + }, + { + "name": "detail_address", + "type": "string", + "required": false, + "source": "body", + "description": "详细地址" + } + ], + "response": [ + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "实际更新的订单行数(地址更新行数)。仅统计 post_status='none' 的订单地址更新成功数。" + }, + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的订单ID数组(原样返回)" + } + ], + "errors": [ + { + "code": 400, + "message": "ids 不能为空" + }, + { + "code": 400, + "message": "至少需要提供一个地址字段进行修改" + }, + { + "code": 400, + "message": "仅允许修改 post_status='none'(未分配快递)的订单;若订单已分配快递则地址更新行数为 0,不会报错但实际无更新。" + } + ] + }, + { + "method": "order.pendingOrder.updateRemark", + "description": "批量修改待处理订单的备注(remark)。不受 post_status 限制,可对所有状态的订单生效。更新成功后写入操作日志。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID 正整数数组,不能为空" + }, + { + "name": "remark", + "type": "string", + "required": true, + "source": "body", + "description": "订单备注/留言,最大500字符,必填" + } + ], + "response": [ + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "实际更新的订单行数" + }, + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的订单ID数组(原样返回)" + } + ], + "errors": [ + { + "code": 400, + "message": "ids 不能为空" + }, + { + "code": 400, + "message": "ids 仅支持正整数数组" + }, + { + "code": 400, + "message": "remark 不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchIntercept", + "description": "批量提交订单拦截请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 intercept_status 更新为 'requested' 并写入操作日志(ORDER_INTERCEPT_REQUEST)。拦截时间 intercept_time 仅在订单首次发起拦截时写入(当时刻),重复发起不覆盖已有值;取消/解除拦截(order.pendingOrder.batchUnintercept)会清空该字段,故其恒为「最近一次发起拦截的通知时刻」,库内确定拦截时刻改用配送表 dispath_time。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 recheck_intercept_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量拦截任务已提交。' 或 '批量拦截任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchInterceptTaskProgress", + "description": "查询批量拦截任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已拦截订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "intercepted_order_count", + "type": "number", + "required": false, + "description": "已拦截订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "intercepted_order_ids", + "type": "number[]", + "required": false, + "description": "已拦截订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_INTERCEPT_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchLock", + "description": "批量提交订单锁定请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 lock_status 更新为 'warehouse' 并写入操作日志(ORDER_LOCK)。已取消订单(status=cancel)为终态不可锁定,后台任务会跳过并通过 skipped_cancelled_order_ids 返回,避免取消订单被重新锁定后无法正常出库。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 order_lock_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量锁定任务已提交。' 或 '批量锁定任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchLockTaskProgress", + "description": "查询批量锁定任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已锁定订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。已取消订单不参与锁定,通过 skipped_cancelled_order_count / skipped_cancelled_order_ids 返回跳过数量与订单ID。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "locked_order_count", + "type": "number", + "required": false, + "description": "已锁定订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "locked_order_ids", + "type": "number[]", + "required": false, + "description": "已锁定订单ID列表(仅 success 时返回)" + }, + { + "name": "skipped_cancelled_order_count", + "type": "number", + "required": false, + "description": "因订单已取消而跳过的数量(submitted/running/success/failed 时返回,success 时取结果值)" + }, + { + "name": "skipped_cancelled_order_ids", + "type": "number[]", + "required": false, + "description": "因订单已取消而跳过的订单ID列表(submitted/running/success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_LOCK_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchUnlock", + "description": "批量提交订单解锁请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 lock_status 更新为 'none' 并写入操作日志(ORDER_UNLOCK)。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 order_unlock_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量解锁任务已提交。' 或 '批量解锁任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchUnlockTaskProgress", + "description": "查询批量解锁任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已解锁订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "unlocked_order_count", + "type": "number", + "required": false, + "description": "已解锁订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "unlocked_order_ids", + "type": "number[]", + "required": false, + "description": "已解锁订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_UNLOCK_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchUnintercept", + "description": "批量提交解除拦截请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 intercept_status 更新为 'none' 并写入操作日志(ORDER_INTERCEPT_CANCEL)。解除拦截同时将拦截时间 intercept_time 清空(置为 null,避免残留旧的发起拦截时刻)。不操作库存拦截锁定数量字段。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 order_unintercept_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量解除拦截任务已提交。' 或 '批量解除拦截任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchUninterceptTaskProgress", + "description": "查询批量解除拦截任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已解除拦截订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "unintercepted_order_count", + "type": "number", + "required": false, + "description": "已解除拦截订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "unintercepted_order_ids", + "type": "number[]", + "required": false, + "description": "已解除拦截订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_UNINTERCEPT_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder2b.list", + "description": "B2B 待处理订单列表。查询条件与 order.pendingOrder.list 完全一致(current 分表 + 模块默认 where:outbound_status != padding 且 step in [1,2,3]),额外强制 is_b2b='Y'。固定条件与请求 where 取 AND,请求传入同名 is_b2b 条件无法覆盖。;列表行额外带出 wms_order_b2b 作业明细字段:total_box_count(总箱数)、pickup_plate_number(提货车牌)、prep_remark(备货备注)、prep_duration_seconds(备货用时/秒)、prep_at(备货完成时间)、is_picked_up(是否提货 Y/N)、picked_up_at(提货时间)、created_at(作业明细创建时间,与订单自身的 create_at 不同)。关联条件固定为 warehouse_id + order_id;无作业明细行时上述字段输出空值占位(数值 0、is_picked_up=N、时间为 null);另支持按 wms_order_b2b 作业明细字段筛选(仅本接口开放,普通订单列表不识别这些字段):total_box_count(总箱数)、pickup_plate_number(提货车牌)、prep_remark(备货备注)、prep_duration_seconds(备货用时/秒)、is_picked_up(Y/N)、picked_up_at(提货时间)、created_at(作业明细创建时间)、prep_at(备货完成时间)。支持简写与标准结构,如 {\"is_picked_up\":\"Y\"}、{\"pickup_plate_number\":{\"operator\":\"like\",\"value\":\"粤A\"}}、{\"prep_at\":{\"operator\":\"between\",\"value\":[\"2026-11-01 00:00:00\",\"2026-11-30 23:59:59\"]}};内部先按 warehouse_id + order_id 查 wms_order_b2b 取命中 order_id,再回填订单列表条件,未命中返回空列表。", + "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 条件对象,语义与 order.pendingOrder.list 完全一致(禁止传入 warehouse_id / warehouseId)。另强制附加 is_b2b='Y':即使传入 {\"is_b2b\":\"N\"} 也只会得到空列表(固定条件与请求条件取 AND);另支持按 wms_order_b2b 作业明细字段筛选(仅本接口开放,普通订单列表不识别这些字段):total_box_count(总箱数)、pickup_plate_number(提货车牌)、prep_remark(备货备注)、prep_duration_seconds(备货用时/秒)、is_picked_up(Y/N)、picked_up_at(提货时间)、created_at(作业明细创建时间)、prep_at(备货完成时间)。支持简写与标准结构,如 {\"is_picked_up\":\"Y\"}、{\"pickup_plate_number\":{\"operator\":\"like\",\"value\":\"粤A\"}}、{\"prep_at\":{\"operator\":\"between\",\"value\":[\"2026-11-01 00:00:00\",\"2026-11-30 23:59:59\"]}};内部先按 warehouse_id + order_id 查 wms_order_b2b 取命中 order_id,再回填订单列表条件,未命中返回空列表。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder;默认 updated_at DESC, id DESC" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "B2B 订单列表(raw 行数据,字段与 order.pendingOrder.list 一致)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + }, + { + "name": "total_box_count", + "type": "number", + "required": true, + "description": "总箱数(wms_order_b2b.total_box_count,无作业明细行时为 0)" + }, + { + "name": "pickup_plate_number", + "type": "string", + "required": false, + "description": "提货车牌(wms_order_b2b.pickup_plate_number)" + }, + { + "name": "prep_remark", + "type": "string", + "required": false, + "description": "备货备注(wms_order_b2b.prep_remark)" + }, + { + "name": "prep_duration_seconds", + "type": "number", + "required": true, + "description": "备货用时,单位秒(wms_order_b2b.prep_duration_seconds,无作业明细行时为 0)" + }, + { + "name": "prep_at", + "type": "string", + "required": false, + "description": "备货完成时间(wms_order_b2b.prep_at)" + }, + { + "name": "is_picked_up", + "type": "string", + "required": true, + "description": "是否提货:Y=已提货 N=未提货(无作业明细行时为 N)" + }, + { + "name": "picked_up_at", + "type": "string", + "required": false, + "description": "提货时间(wms_order_b2b.picked_up_at)" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "B2B 作业明细创建时间(wms_order_b2b.created_at),与订单自身的 create_at 不同;无作业明细行时为 null" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 作业明细输出口径:列表行按 warehouse_id + order_id 关联 wms_order_b2b 取数(分表 id 按仓库发号,不能只按 order_id 关联);副表已移除 store_id / delivery_order_code / is_print / updated_at / deleted_at 字段,取消 B2B 时物理删除明细行,故列表中的 created_at 为作业明细创建时间,无明细行时为空值占位。", + "B2B 作业明细筛选口径:仅在 order.pendingOrder2b.list / order.deliveryOrder2b.list 开放 total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds / is_picked_up / picked_up_at / created_at / prep_at 作为 where 条件;内部转成 wms_order_b2b(warehouse_id + order_id)子查询取 order_id,再以 id IN (...) 回填,未命中返回空列表,不影响其他订单列表口径。" + ] + } + ] + }, + { + "groupName": "订单复核模块", + "module": "order.recheckOrder", + "list": [ + { + "method": "order.recheckOrder.scanOrder", + "description": "扫描关键词并返回以波次为单位的复核视图。支持运单号、波次号、车号三种匹配模式。运单号/波次号命中(散单)返回扁平化订单列表 list_type='single',车号命中(团单)返回嵌套波次结构 list_type='group'。运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs)。所有模式的 list[] 每项均附带 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null)。 商品行新增 need_sn(Y/N)标识是否需要采集 SN 码,便于 PDA 复核页直接按商品行切换 SN 扫描;团购模式的波次视图 stocks[] 同样输出该字段。商品行同时下发 sn_code_rules(该商品的 SN 码规则数组,来自 wms_stock_warehouse.sn_code_rules),前端可据此把扫到的码加工成 SN 码(match_type=prefix/suffix 匹配前缀或后缀、match_value=前缀/后缀字符串、keep_mode=full 保留全码|strip 去掉前后缀),团购模式 stocks[] 同样输出。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword / value / waybill_no / waybillCode / waybill_code / wave_no / waveNo / cart_code / cartCode", + "type": "string", + "required": true, + "source": "body|query", + "description": "扫描关键词;匹配优先级:运单号 → 波次号 → 车号。支持别名 waybillCode/waybill_code(运单号)、waveNo(波次号)、cartCode(车号)" + } + ], + "response": [ + { + "name": "match_type", + "type": "string", + "required": true, + "description": "命中类型:waybill(运单号命中)/ wave(波次号命中)/ cart(车号命中)" + }, + { + "name": "list_type", + "type": "string", + "required": true, + "description": "列表模式:single(散单扁平列表)/ group(团购嵌套波次列表)" + }, + { + "name": "waybill_no", + "type": "string", + "required": false, + "description": "仅 waybill 命中时返回,匹配到的运单号" + }, + { + "name": "task_id", + "type": "number|null", + "required": false, + "description": "散单有波次信息时返回(来自拣货任务表 wms_wave_pick_task.id),团单车号命中时返回 cartMatchContext 中的任务 ID" + }, + { + "name": "picker_id", + "type": "number|null", + "required": false, + "description": "仅散单模式(有波次信息时)返回,拣货人ID(来自 wms_wave_pick_task.pick_user_id)" + }, + { + "name": "picker_name", + "type": "string", + "required": false, + "description": "仅散单模式(有波次信息时)返回,拣货人名称(来自 wms_wave_pick_task.pick_user_name)" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "仅散单模式(有波次信息时)返回,波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "仅散单模式(有波次信息时)返回,波次号" + }, + { + "name": "wave_type", + "type": "number", + "required": false, + "description": "仅散单模式(有波次信息时)返回,波次类型编码(来自 wms_wave_batch.wave_type)" + }, + { + "name": "pick_mode", + "type": "number", + "required": false, + "description": "拣货模式:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次。散单模式在顶层返回,团购模式在每个波次视图项内返回" + }, + { + "name": "strategy_id", + "type": "number|null", + "required": false, + "description": "仅散单模式返回,波次策略ID" + }, + { + "name": "strategy_name", + "type": "string", + "required": false, + "description": "仅散单模式返回,波次策略名称" + }, + { + "name": "total_orders", + "type": "number", + "required": false, + "description": "仅散单模式返回,波次内订单总数" + }, + { + "name": "reviewed_count", + "type": "number", + "required": false, + "description": "仅散单模式返回,已复核订单数" + }, + { + "name": "unreviewed_count", + "type": "number", + "required": false, + "description": "仅散单模式返回,未复核订单数" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "统一列表输出。散单模式(list_type=single)有波次信息时:扁平订单数组;无波次信息时退回单订单详情模式(每项含 detail、items、expresses、logs)。团购模式(list_type=group):波次视图数组(每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、pick_mode、box_no、order_ids、orders_detail、stocks[])。所有模式的 list[] 每项均附带 items_weight(订单商品总重量,单位 g)与 suggested_package_material(推荐包材信息,无推荐时为 null)。", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "[散单有波次] 订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "[散单有波次] 发货单号(优先 delivery_order_code,其次 pre_delivery_order_code)" + }, + { + "name": "waybill_no", + "type": "string", + "description": "[散单有波次] 运单号(从 order_express 关联表查询)" + }, + { + "name": "pick_status", + "type": "string", + "description": "[散单有波次] 拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "[散单有波次] 是否已打印(print_status === 'fin')" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "[散单有波次] 是否已复核(recheck_status === 'fin')" + }, + { + "name": "shop_nick", + "type": "string", + "description": "[散单有波次] 店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "[散单有波次] 商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "[散单有波次] 波次内序号(优先从 wms_order_wave_index 读取真实 wave_index,若无则降级为数组临时序号)" + }, + { + "name": "recheck_status", + "type": "string", + "description": "[散单有波次] 复核状态" + }, + { + "name": "wave_id", + "type": "number", + "description": "[散单有波次] 波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[散单有波次] 波次号" + }, + { + "name": "order_type", + "type": "string", + "description": "[散单有波次] 订单类型" + }, + { + "name": "status", + "type": "number", + "description": "[散单有波次] 订单状态码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "[散单有波次] 物流名称" + }, + { + "name": "store_remark", + "type": "string", + "description": "[散单有波次] 货主备注(来自 wms_store_warehouse.store_remask)" + }, + { + "name": "intercept_status", + "type": "string", + "description": "[散单有波次] 拦截状态(requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse / 历史值 intercepted / 空字符串)。已拦截订单保留在 list 中按单提示,不阻断整个扫描视图,且不计入 reviewed_count / unreviewed_count / printed_count / unprinted_count 统计" + }, + { + "name": "stock", + "type": "array", + "description": "[散单有波次] 订单商品库存明细", + "children": [ + { + "name": "stock_id", + "type": "number", + "description": "库存商品ID" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "sku_property", + "type": "string", + "description": "SKU属性(来自 wms_stock_warehouse.sku_property)" + }, + { + "name": "packing_requirements", + "type": "string", + "description": "包装要求(来自 wms_stock_warehouse.packing_requirements)" + }, + { + "name": "barcodes", + "type": "array", + "description": "条码列表(来自 wms_stock_barcodes,若无则回退为 [item_code])" + }, + { + "name": "images", + "type": "array", + "description": "商品图片URL列表(来自 file_reference 关联查询)" + }, + { + "name": "plan_qty", + "type": "number", + "description": "计划数量" + }, + { + "name": "has_shared_barcode", + "type": "boolean", + "description": "是否存在共享条码(同一条码出现在多个不同 stock_id 中)" + }, + { + "name": "need_sn", + "type": "string", + "description": "该商品行是否需要采集 SN 码:Y是 N否(来自 wms_stock_warehouse.is_sn_mgmt);为 Y 时提交复核需通过 sn_map 上传该商品全部 SN 码" + }, + { + "name": "sn_code_rules", + "type": "array", + "description": "该商品的 SN 码规则(来自 wms_stock_warehouse.sn_code_rules),用于前端扫码校验/加工;无规则时为空数组。元素:{ match_type: prefix前缀|suffix后缀, match_value: 前缀或后缀字符串, keep_mode: full整个扫码内容作为SN码|strip去掉前缀或后缀后作为SN码 };多条按数组顺序匹配,命中第一条生效,未命中则扫码内容原样作为 SN 码" + } + ] + }, + { + "name": "detail", + "type": "object", + "description": "[散单无波次回退] 订单详情对象(来自 order.detail 方法返回)" + }, + { + "name": "items", + "type": "array", + "description": "[散单无波次回退] 订单商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "description": "[散单无波次回退] 订单快递信息数组" + }, + { + "name": "logs", + "type": "array", + "description": "[散单无波次回退] 订单操作日志数组" + }, + { + "name": "wave_id", + "type": "number", + "description": "[团购波次项] 波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[团购波次项] 波次号" + }, + { + "name": "wave_type", + "type": "number", + "description": "[团购波次项] 波次类型编码" + }, + { + "name": "wave_status", + "type": "number", + "description": "[团购波次项] 波次状态码" + }, + { + "name": "total_orders", + "type": "number", + "description": "[团购波次项] 波次内订单总数(来自 wms_wave_batch)" + }, + { + "name": "processed_orders", + "type": "number", + "description": "[团购波次项] 已处理订单数(来自 wms_wave_batch)" + }, + { + "name": "creator", + "type": "string", + "description": "[团购波次项] 波次创建人" + }, + { + "name": "create_time", + "type": "string", + "description": "[团购波次项] 波次创建时间" + }, + { + "name": "update_time", + "type": "string", + "description": "[团购波次项] 波次更新时间" + }, + { + "name": "order_count", + "type": "number", + "description": "[团购波次项] 波次下实际订单数(COUNT 查询)" + }, + { + "name": "pick_mode", + "type": "number", + "description": "[团购波次项] 拣货模式(以拣货任务级别为准)" + }, + { + "name": "box_no", + "type": "number", + "description": "[团购波次项] 箱号(来自 wms_wave_pick_task_wave.box_no)" + }, + { + "name": "order_ids", + "type": "array", + "description": "[团购波次项] 非拦截订单 ID 数组,仅 list_type='group' 时返回" + }, + { + "name": "orders_detail", + "type": "array", + "description": "[团购波次项] 非拦截订单详细列表,每项含 order_id、delivery_order_code、waybill_no、pick_status、is_printed、is_reviewed、recheck_status、shop_nick、items_count、wave_index、intercept_status,仅 list_type='group' 时返回", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "运单号" + }, + { + "name": "pick_status", + "type": "string", + "description": "拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "是否已打印(print_status === 'fin')" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "是否已复核(recheck_status === 'fin')" + }, + { + "name": "recheck_status", + "type": "string", + "description": "复核状态" + }, + { + "name": "shop_nick", + "type": "string", + "description": "店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "波次内序号" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态(requested / intercepted_at_warehouse / 空字符串)" + } + ] + }, + { + "name": "orders", + "type": "array", + "description": "[团购波次项] 波次下订单列表(结构与散单有波次模式订单项一致,含 order_id/delivery_order_code/waybill_no/pick_status/is_printed/is_reviewed/shop_nick/items_count/wave_index/recheck_status/order_type/status/logistics_name/store_remark/intercept_status/stock[])", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "运单号" + }, + { + "name": "pick_status", + "type": "string", + "description": "拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "是否已打印" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "是否已复核" + }, + { + "name": "shop_nick", + "type": "string", + "description": "店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "波次内序号" + }, + { + "name": "recheck_status", + "type": "string", + "description": "复核状态" + }, + { + "name": "order_type", + "type": "string", + "description": "订单类型" + }, + { + "name": "status", + "type": "number", + "description": "订单状态码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "物流名称" + }, + { + "name": "store_remark", + "type": "string", + "description": "货主备注" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态" + }, + { + "name": "stock", + "type": "array", + "description": "商品库存明细(结构同散单模式)" + } + ] + }, + { + "name": "intercepted", + "type": "array", + "description": "[团购波次项] 拦截订单列表,仅当波次内存在已进入拦截流程的订单时返回(intercept_status 为 requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse,以及历史遗留值 intercepted)。每项含 wave_index(波次内序号)、order_id、delivery_order_code、waybill_no、intercept_status", + "children": [ + { + "name": "wave_index", + "type": "number", + "description": "波次内序号(优先从 wms_order_wave_index 读取真实 wave_index,若无则降级为数组临时序号)" + }, + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "运单号" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态(requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse / intercepted)" + } + ] + }, + { + "name": "items_weight", + "type": "number|null", + "description": "[全模式] 订单商品总重量(g),来源于 wms_order_delivery.items_weight。散单模式每个订单对象包含,团购模式每个波次对象包含(取波次内首个正常订单的重量)" + }, + { + "name": "suggested_package_material", + "type": "object|null", + "description": "[全模式] 推荐包材信息。根据订单商品结构(items_hash + items_crc)匹配 wms_package_material_item_relation 历史绑定记录,按 bind_count 降序取最优匹配。若 items_hash 为空或无匹配记录则为 null。散单模式每个订单对象包含,团购模式每个波次对象包含;团购模式以波次内首个正常订单的商品指纹匹配包材推荐", + "children": [ + { + "name": "id", + "type": "number", + "description": "包材ID(wms_package_material.id)" + }, + { + "name": "code", + "type": "string", + "description": "包材编码" + }, + { + "name": "name", + "type": "string", + "description": "包材名称" + }, + { + "name": "spec", + "type": "string", + "description": "包材规格" + }, + { + "name": "type", + "type": "string", + "description": "包材类型" + }, + { + "name": "weight", + "type": "number", + "description": "包材自身重量(g)" + }, + { + "name": "length", + "type": "number", + "description": "长(cm)" + }, + { + "name": "width", + "type": "number", + "description": "宽(cm)" + }, + { + "name": "height", + "type": "number", + "description": "高(cm)" + }, + { + "name": "bind_count", + "type": "number", + "description": "历史绑定次数(推荐排序依据)" + } + ] + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "扫描关键词不能为空" + }, + { + "code": 404, + "message": "未找到对应订单" + }, + { + "code": 400, + "message": "订单未拣货,不允许复核。" + } + ] + }, + { + "method": "order.recheckOrder.confirmRecheck", + "description": "按订单 ID 确认复核并记录复核任务到 wms_recheck_task(入参兼容 id/orderId)。确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务:清空 wms_wave_pick_task 的车绑定信息(current_cart_id、current_cart_code_snapshot)、停用 wms_pick_task_cart_binding 绑定记录(is_active=0 并记录解绑人和时间)并释放 wms_pick_cart(清空 current_task_id、bind_user_id)。解绑失败仅记录 warn 日志,不影响复核主流程。复核状态更新后,会先自动清理波次内「已拦截且未打印」的订单(wave_id 清零回池、删除波次索引与任务订单关联、回写波次统计、写 ORDER_WAVE_REMOVE 日志并触发波次策略快扫),避免拦截订单卡住波次完成判定;已打印的拦截订单保持不动。SN(序列号管理)订单复核:订单 has_sn_item='Y' 时必须通过 sn_map 提交全部 SN 码(key=仓库商品ID stock_id,value=该商品的 SN 码列表,数量必须等于该商品在订单内的 plan_qty 合计);服务端会校验 SN 是否重复、是否已被其它订单占用、是否已随其它订单发货;校验通过后 SN 与复核状态在同一事务内落库(wms_order_item_sn + wms_order_item_sn_log),任一失败整体回滚并返回失败。非 SN 商品不允许提交 SN 码。 单个 SN 码最长 512 字符(wms_order_item_sn.sn_code 为 VARCHAR(512)),支持以链接/二维码内容作为 SN 码,超长直接返回失败。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id / id / orderId", + "type": "string|number", + "required": true, + "source": "body|query", + "description": "订单 ID;优先使用 order_id,兼容别名 id 与 orderId" + }, + { + "name": "sn_map", + "type": "object", + "required": false, + "source": "body|query", + "description": "SN 码提交(唯一格式):{ \"stock_id\": [ \"sn_code\", ... ] },key 为仓库商品ID(订单明细里的 stock_id),value 为该商品的 SN 码列表(也兼容逗号/换行分隔的字符串);SN 订单必填。" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "waybill_no", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "recheck_status", + "type": "string", + "required": true, + "description": "复核结果状态(固定为 'fin')" + }, + { + "name": "recheck_time", + "type": "string", + "required": true, + "description": "复核时间(ISO 字符串)" + }, + { + "name": "review_no", + "type": "string", + "required": true, + "description": "复核任务编号" + }, + { + "name": "has_sn_item", + "type": "string", + "required": true, + "description": "是否含序列号管理商品:Y是 N否" + }, + { + "name": "sn_count", + "type": "number", + "required": true, + "description": "本次提交并校验通过的 SN 数量(非 SN 订单为 0)" + }, + { + "name": "sn_item_count", + "type": "number", + "required": true, + "description": "本次提交涉及的序列号管理明细数(非 SN 订单为 0)" + } + ], + "errors": [ + { + "code": 400, + "message": "订单ID不能为空" + }, + { + "code": 404, + "message": "未找到对应订单" + }, + { + "code": 400, + "message": "订单未拣货,不允许复核。" + }, + { + "code": 400, + "message": "订单包含序列号管理商品,提交复核时必须上传全部SN码" + }, + { + "code": 400, + "message": "商品[商品编码 商品名称]需提交N个SN码,实际提交M个(N=该商品 plan_qty 合计)" + }, + { + "code": 400, + "message": "SN码重复提交:SN-A、SN-B" + }, + { + "code": 400, + "message": "SN码[SN-A]已被其他订单占用,不可重复使用" + }, + { + "code": 400, + "message": "SN码[SN-A]已随订单[12345]发货,不可重复使用" + }, + { + "code": 400, + "message": "订单序列号商品信息缺失,无法校验SN码,请检查商品是否启用序列号管理" + }, + { + "code": 400, + "message": "SN订单不支持团购波次复核,请使用单订单复核并提交SN码" + }, + { + "code": 400, + "message": "提交的SN码对应商品不在订单中或未启用序列号管理:stock_id=501" + }, + { + "code": 400, + "message": "SN码长度不能超过512个字符(支持链接/二维码内容作为SN码)" + } + ] + }, + { + "method": "order.recheckOrder.confirmIntercept", + "description": "确认拦截:通过订单 ID 列表批量匹配订单,将拦截状态更新为 intercepted_at_warehouse(仓库已拦截,step=4、outbound_status=fin),同步标记运单退回与拦截(is_back='Y', is_intercept='Y'),并释放储位分配(cancelAllocateStorage 拦截模式 interceptMode=true:库存不归还可用,移入拦截锁定字段 intercept_locked_quantity)与订单锁(lock_status=none)。仅拦截当前指定订单,不波及波次内其他订单。前置条件:订单必须处于拦截发起中状态(requested/requesting/intercepting,历史值 intercepted 兼容),未发起拦截(none/空)的订单直接静默跳过不参与处理,已确认拦截(intercepted_at_warehouse)及其它非可确认状态(intercepted_in_transit/returning/returned/delivered_by_mistake/timeout/cancelled/failed/exception)一律跳过并记录失败原因;更新 SQL 的 where 同时限定拦截状态白名单,防止并发修改导致误更新。支持部分失败:未找到的订单与处理失败的订单记录在 failed 列表并返回失败原因,其余订单继续处理。全部订单处理完后按成功订单 ID 汇总批量创建售后工单 + 通知快递群。每个订单操作成功后写入操作日志(ORDER_INTERCEPT_CONFIRM)。运单标记、储位释放、锁释放、工单创建、日志写入失败均不影响主流程。库内拦截确认**不写** intercept_time(该字段恒为「最近一次发起拦截的通知时刻」,确认时不覆盖),库内确定拦截时刻以配送表 dispath_time(订单迁移进配送表的时间)为准。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|string", + "required": true, + "source": "body", + "description": "订单 ID 列表,支持数组或以逗号分隔的字符串。兼容 id / order_id / orderId 单值写法" + } + ], + "response": [ + { + "name": "success", + "type": "array", + "required": true, + "description": "拦截成功的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单 ID" + }, + { + "name": "order_no", + "type": "string", + "description": "订单号(优先 delivery_order_code,其次 pre_delivery_order_code)" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态(固定为 'intercepted_at_warehouse')" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间(ISO 字符串)" + } + ] + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "拦截失败的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单 ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号(订单存在时返回)" + }, + { + "name": "reason", + "type": "string", + "description": "失败原因(未找到对应订单 / 订单已确认拦截 / 订单拦截状态不允许确认拦截: xxx / 确认拦截失败: xxx);拦截状态为 none 的订单静默跳过,不进入 failed" + } + ] + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + } + ], + "errors": [ + { + "code": 400, + "message": "订单ID列表不能为空", + "description": "ids 为空或全部无效(非正整数)时返回" + } + ] + }, + { + "method": "order.recheckOrder.interceptScan", + "description": "拦截扫描:通过运单号查找运单记录。非拦截订单会被拒绝并提示「非拦截订单」:运单记录不存在,或运单 is_intercept≠'Y' 且关联订单 intercept_status 不在 requested/intercepting。校验通过后标记退回与拦截(is_back='Y', is_intercept='Y'),处理关联的未完结售后工单(写入「库内拦截成功」步骤并置为 completed)。若运单关联到订单,则将订单拦截状态更新为 intercepted_at_warehouse(step=4、outbound_status=fin)并释放储位分配(拦截模式:库存不归还可用,移入拦截锁定字段 intercept_locked_quantity)与订单锁(仅订单级状态更新,不标记订单下其他面单)。该状态更新**不写** intercept_time(该字段恒为「最近一次发起拦截的通知时刻」),库内确定拦截时刻以配送表 dispath_time 为准。工单处理失败不阻断主流程。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号" + } + ], + "response": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "is_back", + "type": "string", + "required": true, + "description": "退回标记(固定为 'Y')" + }, + { + "name": "is_intercept", + "type": "string", + "required": true, + "description": "拦截标记(固定为 'Y')" + }, + { + "name": "after_sale", + "type": "object|null", + "required": false, + "description": "关联的售后工单处理结果(仅当存在未完结工单时返回);工单处理失败时为 null" + }, + { + "name": "order", + "type": "object|null", + "required": false, + "description": "订单拦截结果(仅当运单关联到订单时返回),包含 order_id、order_no、intercept_status;无法关联订单时为 null" + } + ], + "errors": [ + { + "code": 400, + "message": "运单号不能为空" + }, + { + "code": 400, + "message": "非拦截订单" + } + ] + }, + { + "method": "order.recheckOrder.recheckOrderList", + "description": "复核订单列表查询,通过入参 list_type 区分散单模式与团购模式。散单模式(single,默认)返回待复核订单列表(每项为一个订单,排除 pick_status='none' 和 recheck_status='fin'),团购模式(group)返回波次维度的复核汇总列表(每项为一个波次及其订单复核统计,含 review_assignment_status 计算字段)。统一使用 list 字段名输出,均支持分页与筛选。;散单模式运单号回读与运单号关键词搜索强制同仓校验(order_express.warehouse_id 必须等于订单 warehouse_id),禁止跨仓串读", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "list_type", + "type": "string", + "required": false, + "source": "body", + "description": "列表模式:single(散单模式,默认)/ group(团购模式)" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件。散单模式支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status、wave_index(波次内序号范围筛选,如 {\"operator\":\"between\",\"value\":[起,止]},或 wave_index_min / wave_index_max);团购模式支持 wave_no(模糊搜索)、wave_type、wave_status" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize(默认 page=1, pageSize=20)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "散单模式(list_type=single):订单数组,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、wave_index、status、create_at、pick_time、recheck_time。团购模式(list_type=group):波次汇总数组,每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、reviewed_count、unreviewed_count、review_assignment_status(unreviewed/partially_reviewed/reviewed)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages、hasPrevious、hasNext" + } + ], + "errors": [] + }, + { + "method": "order.recheckOrder.scanTask", + "description": "按拣货任务 ID 拉取复核扫描视图。根据任务的 pick_mode 区分散单/团单模式,返回与 scanOrder 一致的数据结构,用于前端刷新数据。散单模式(pick_mode 2/3/4)扁平化任务下所有波次的订单列表(按 order_id 去重,未复核优先、wave_index 升序),顶层携带拣货人/任务等汇总信息(包括 picker_id、picker_name、pick_mode、total_orders、reviewed_count、unreviewed_count);团购模式(pick_mode 1/5)返回任务下所有团购波次及订单的分组列表(list_type='group')。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货任务 ID(对应 wms_wave_pick_task.id)" + } + ], + "response": [ + { + "name": "match_type", + "type": "string", + "required": true, + "description": "固定为 'task',表示通过任务 ID 匹配" + }, + { + "name": "list_type", + "type": "string", + "required": true, + "description": "列表模式:single(散单扁平列表)/ group(团购嵌套波次列表),由拣货任务的 pick_mode 决定" + }, + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务 ID" + }, + { + "name": "picker_id", + "type": "number|null", + "required": false, + "description": "拣货人 ID(来自 wms_wave_pick_task.pick_user_id),散单模式返回" + }, + { + "name": "picker_name", + "type": "string", + "required": false, + "description": "拣货人名称(来自 wms_wave_pick_task.pick_user_name),散单模式返回" + }, + { + "name": "pick_mode", + "type": "number", + "required": false, + "description": "拣货模式:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "散单模式固定为 0,团购模式不返回" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "散单模式固定为空字符串,团购模式不返回" + }, + { + "name": "wave_type", + "type": "number", + "required": false, + "description": "波次类型编码(取任务下第一个有效波次的 wave_type),散单模式返回" + }, + { + "name": "strategy_id", + "type": "number|null", + "required": false, + "description": "散单模式固定为 null(任务级别不绑定单一策略)" + }, + { + "name": "strategy_name", + "type": "string", + "required": false, + "description": "散单模式固定为空字符串(任务级别不绑定单一策略)" + }, + { + "name": "total_orders", + "type": "number", + "required": false, + "description": "任务下订单总数(去重后),散单模式返回" + }, + { + "name": "reviewed_count", + "type": "number", + "required": false, + "description": "已复核订单数,散单模式返回" + }, + { + "name": "unreviewed_count", + "type": "number", + "required": false, + "description": "未复核订单数,散单模式返回" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "统一列表输出。散单模式(list_type=single):扁平订单数组(每项结构与 scanOrder 散单有波次模式一致,含 order_id/delivery_order_code/waybill_no/pick_status/is_printed/is_reviewed/shop_nick/items_count/wave_index/recheck_status/order_type/status/logistics_name/store_remark/intercept_status/stock[])。团购模式(list_type=group):波次视图数组(结构与 scanOrder 团购模式一致,每项含 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[])", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "[散单] 订单 ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "[散单] 发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "[散单] 运单号" + }, + { + "name": "pick_status", + "type": "string", + "description": "[散单] 拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "[散单] 是否已打印" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "[散单] 是否已复核" + }, + { + "name": "shop_nick", + "type": "string", + "description": "[散单] 店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "[散单] 商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "[散单] 波次内序号" + }, + { + "name": "recheck_status", + "type": "string", + "description": "[散单] 复核状态" + }, + { + "name": "wave_id", + "type": "number", + "description": "[散单] 波次 ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[散单] 波次号" + }, + { + "name": "order_type", + "type": "string", + "description": "[散单] 订单类型" + }, + { + "name": "status", + "type": "number", + "description": "[散单] 订单状态码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "[散单] 物流名称" + }, + { + "name": "store_remark", + "type": "string", + "description": "[散单] 货主备注" + }, + { + "name": "intercept_status", + "type": "string", + "description": "[散单] 拦截状态" + }, + { + "name": "stock", + "type": "array", + "description": "[散单] 订单商品库存明细(含 stock_id/item_code/item_name/sku_property/packing_requirements/barcodes/images/plan_qty/has_shared_barcode)" + }, + { + "name": "wave_id", + "type": "number", + "description": "[团购波次项] 波次 ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[团购波次项] 波次号" + }, + { + "name": "wave_type", + "type": "number", + "description": "[团购波次项] 波次类型编码" + }, + { + "name": "wave_status", + "type": "number", + "description": "[团购波次项] 波次状态码" + }, + { + "name": "total_orders", + "type": "number", + "description": "[团购波次项] 波次内订单总数" + }, + { + "name": "processed_orders", + "type": "number", + "description": "[团购波次项] 已处理订单数" + }, + { + "name": "creator", + "type": "string", + "description": "[团购波次项] 波次创建人" + }, + { + "name": "create_time", + "type": "string", + "description": "[团购波次项] 波次创建时间" + }, + { + "name": "update_time", + "type": "string", + "description": "[团购波次项] 波次更新时间" + }, + { + "name": "order_count", + "type": "number", + "description": "[团购波次项] 波次下实际订单数" + }, + { + "name": "pick_mode", + "type": "number", + "description": "[团购波次项] 拣货模式" + }, + { + "name": "box_no", + "type": "number", + "description": "[团购波次项] 箱号" + }, + { + "name": "orders", + "type": "array", + "description": "[团购波次项] 波次下订单列表(结构与散单模式订单项一致)" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 无效", + "description": "task_id 为空或非正整数" + }, + { + "code": 404, + "message": "未找到对应拣货任务" + } + ] + }, + { + "method": "order.recheckOrder.batchQuickRecheck", + "description": "批量快捷复核:传入订单 IDs 列表,对每个有效订单执行前置检查(已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。复核状态更新后,会先自动清理波次内「已拦截且未打印」的订单(wave_id 清零回池、删除波次索引与任务订单关联、回写波次统计、写 ORDER_WAVE_REMOVE 日志并触发波次策略快扫),避免拦截订单卡住波次完成判定;已打印的拦截订单保持不动。SN(序列号管理)订单不支持快捷复核:has_sn_item='Y' 的订单会直接返回失败,需改用单订单复核并提交 SN 码,避免绕过 SN 校验。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|string", + "required": true, + "source": "body|query", + "description": "订单 ID 列表,支持数组或以逗号分隔的字符串" + } + ], + "response": [ + { + "name": "success", + "type": "array", + "required": true, + "description": "复核成功的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + } + ] + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "复核失败的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "reason", + "type": "string", + "description": "失败原因(未分配储位 / 没有分配快递 / 没有同步 / 已拦截 / 未找到对应订单 / 复核失败: xxx;SN 订单为 复核失败: SN订单需在单订单复核中提交SN码,不支持快捷复核)" + } + ] + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + } + ], + "errors": [ + { + "code": 400, + "message": "订单ID列表不能为空" + } + ] + }, + { + "method": "order.recheckOrder.batchQuickRecheckByWave", + "description": "按波次批量快捷复核:传入波次 IDs 列表,对每个波次下所有有效订单执行前置检查(已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。复核状态更新后,会先自动清理波次内「已拦截且未打印」的订单(wave_id 清零回池、删除波次索引与任务订单关联、回写波次统计、写 ORDER_WAVE_REMOVE 日志并触发波次策略快扫),避免拦截订单卡住波次完成判定;已打印的拦截订单保持不动。SN(序列号管理)订单不支持快捷复核:has_sn_item='Y' 的订单会直接返回失败,需改用单订单复核并提交 SN 码,避免绕过 SN 校验。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids", + "type": "array|string", + "required": true, + "source": "body|query", + "description": "波次 ID 列表,支持数组或以逗号分隔的字符串。兼容 waveIds(驼峰)、wave_id(单值)" + } + ], + "response": [ + { + "name": "success", + "type": "array", + "required": true, + "description": "复核成功的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "wave_id", + "type": "number", + "description": "所属波次ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + } + ] + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "复核失败的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID(波次无订单时为 null)" + }, + { + "name": "wave_id", + "type": "number", + "description": "所属波次ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号(波次无订单时为 null)" + }, + { + "name": "reason", + "type": "string", + "description": "失败原因(未分配储位 / 没有分配快递 / 没有同步 / 已拦截 / 波次下无订单 / 复核失败: xxx;SN 订单为 复核失败: SN订单需在单订单复核中提交SN码,不支持快捷复核)" + } + ] + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + } + ], + "errors": [ + { + "code": 400, + "message": "波次ID列表不能为空" + } + ] + }, + { + "method": "order.recheckOrder.queryRecheckOrderSingleList", + "description": "散单模式复核列表查询,按订单维度返回待复核订单(排除 pick_status='none' 和 recheck_status='fin'),支持分页与关键词/波次号/复核状态筛选。与 recheckOrderList 不同:本方法仅处理散单模式,不包含团购分支。;散单模式运单号回读与运单号关键词搜索强制同仓校验(order_express.warehouse_id 必须等于订单 warehouse_id),禁止跨仓串读", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件。支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status、wave_index(波次内序号范围筛选,如 {\"operator\":\"between\",\"value\":[起,止]},或 wave_index_min / wave_index_max)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize(默认 page=1, pageSize=20)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "散单复核订单列表,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、items_weight、weight_type、waybill_code、wave_index、status、create_at、recheck_time、has_sn_item(新增:是否含序列号管理商品 Y/N,SN 订单复核必须提交 SN 码)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages、hasPrevious、hasNext" + } + ], + "errors": [] + } + ] + }, + { + "groupName": "订单打包模块", + "module": "order.packing", + "list": [ + { + "method": "order.packing.list", + "description": "打包任务列表查询。按仓库维度查询打包任务,支持分页、筛选、排序。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20", + "children": [ + { + "name": "page", + "type": "number", + "required": false, + "description": "页码" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "description": "每页条数" + } + ] + }, + { + "name": "sort", + "type": "object", + "required": false, + "description": "排序参数 { sortField, sortOrder }", + "children": [ + { + "name": "sortField", + "type": "string", + "required": false, + "description": "排序字段,支持:id、order_id、workbench_id、wave_id、pack_quantity、pack_mode、status、start_time、end_time、create_time、update_time" + }, + { + "name": "sortOrder", + "type": "string", + "required": false, + "description": "排序方向:ASC / DESC,默认 DESC" + } + ] + }, + { + "name": "where", + "type": "object", + "required": false, + "description": "筛选条件", + "children": [ + { + "name": "status", + "type": "number", + "required": false, + "description": "任务状态:0=待处理 1=打包中 2=已完成 3=异常" + }, + { + "name": "pack_mode", + "type": "number", + "required": false, + "description": "打包模式:1=散单 2=团购" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "description": "运单号。通过 wms_order_express 表解析 order_id 后按订单过滤(wms_pack_task.waybill_code 通常为空)。支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多单号取并集):operator=contains/like 时按 LIKE '%单号%' 模糊匹配(通配符已转义,可命中 '主体-1-1-' 等分段单号);缺省或 operator=eq 时按①完整单号等值匹配;②剥离一单多件包裹序号分段后缀(如 -1-1-)后的主体单号等值匹配;③主体单号前缀匹配(LIKE '主体-%',同主体不同分段序号,通配符已转义)。无任何匹配时返回空列表" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "波次号。支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多值取并集):operator=eq/in 精确匹配(单值等值、多值 IN),operator=ne 不等于,operator=contains/like 与缺省(不传 operator)为模糊匹配(LIKE '%值%',通配符已转义)" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "description": "订单ID(精确匹配)" + }, + { + "name": "workbench_id", + "type": "number", + "required": false, + "description": "工作台ID(精确匹配)" + }, + { + "name": "operator_text", + "type": "string", + "required": false, + "description": "打包员(作业人员)筛选:目标列 wms_pack_task.operator_text(TEXT,多人姓名逗号拼接快照,如 '小吴哥,阿猫')。支持 {operator,value,type} 标准结构,value 支持字符串或字符串数组(多值取并集):operator=contains/like 与缺省(不传 operator)→ 模糊匹配 LIKE '%值%'(通配符 %/_ 已转义);operator=eq/in → 精确匹配(单值等值、多值 IN);operator=ne → 不等于(多值取首值);operator=notlike → 不包含 NOT LIKE '%值%'(多值逐个 AND 排除);值为 ''/null/空数组时忽略该条件(不过滤)" + }, + { + "name": "quickWhere", + "type": "string", + "required": false, + "description": "快捷搜索:波次号模糊匹配(LIKE '%kw%',逻辑不变)+ 运单号经 express→order→wave 链路解析(团购按波次号查、散单按订单ID查)。运单号匹配优先级:先按「完整单号等值 + 剥离一单多件分段后缀(如 -1-1-)后的主体单号等值 + 主体前缀 LIKE '主体-%'」精确匹配;精确未命中且关键词 trim 后长度 ≥ 4(QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH)时才降级为 LIKE '%kw%' 模糊查询(兼容输入部分单号的场景);trim 后长度 < 4 的短词(含单字符如 \"7\")禁止降级模糊,运单号解析直接返回空结果(避免 %短词% 误命中海量历史单号);波次号模糊逻辑不变" + }, + { + "name": "start_time", + "type": "object", + "required": false, + "description": "开始打包时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" + }, + { + "name": "start_time_start", + "type": "string", + "required": false, + "description": "开始打包时间范围起始(ISO 8601,兼容旧写法)" + }, + { + "name": "start_time_end", + "type": "string", + "required": false, + "description": "开始打包时间范围结束(ISO 8601,兼容旧写法)" + }, + { + "name": "end_time", + "type": "object", + "required": false, + "description": "结束打包时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" + }, + { + "name": "create_time", + "type": "object", + "required": false, + "description": "创建时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" + }, + { + "name": "has_video", + "type": "number", + "required": false, + "description": "是否包含录像:1=有录像 2=无录像" + }, + { + "name": "video_enable", + "type": "number", + "required": false, + "description": "录像是否可用:1=可用(存在 video_url 非空且 status!=failed 的记录) 2=不可用" + } + ] + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "打包任务列表,每项含 id、order_id、warehouse_id、workbench_id、wave_id、wave_no、waybill_code、pack_quantity、item_quantity、sku_count、pack_mode、status、start_time、end_time、operator_text、device_ids、remark、meta、create_time、update_time、workbench_name、workbench_type、has_video、video_enable、videos[]、expresses[]" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages、hasPrevious、hasNext" + } + ], + "errors": [] + }, + { + "method": "order.packing.export", + "description": "提交打包任务导出任务(异步)。入参 where/sort 语义与 order.packing.list 一致;warehouse_id 由服务端从 ctx.user.store_id 注入,禁止前端传入。提交后立即返回 task_id,后台异步生成单 Sheet Excel(Sheet1「打包任务列表」)并上传,导出进度/下载请通过 order.packing.exportTaskProgress 查询。数据来源 wms_pack_task 主表 + wms_pack_task_video 视频副表 + wms_workbench 工作台 + wms_order_express 运单表;Excel 列含任务ID/订单ID/波次号/运单号/关联运单号/打包模式/任务状态/打包数量/商品总数量/商品种类数/工作台/作业人员/开始打包时间/结束打包时间/创建时间/视频状态/录像可用/备注;全量分页拉取,无行数上限。任务缓存 Redis TTL 30 分钟;状态口径 submitted → running → 数据拉取(10~30) → 关联拉取(30~55) → Excel(55~90) → 上传(92) → success(100),失败 failed + error。免权限免日志免鉴权口径与 order.export 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件,语义与 order.packing.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 status/pack_mode/waybill_code/wave_no/order_id/workbench_id/operator_text/quickWhere/has_video/video_enable/start_time/end_time/create_time 等);禁止传入 warehouse_id/warehouseId(服务端注入)" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,语义与 order.packing.list 的 sort 一致:sortField 白名单 id/order_id/warehouse_id/workbench_id/wave_id/pack_quantity/pack_mode/status/start_time/end_time/create_time/update_time,sortOrder asc/desc,默认 create_time desc" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成,格式 packing_export_{warehouseId}_{timestamp}_{random})" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态,枚举:submitted/running/success/failed/not_found(提交成功时为 submitted)" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "当前进度百分比(0-100),提交时返回 0" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理记录数(打包任务条数)" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "总记录数(若有)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果(提交时为 null;后台完成后为上传信息对象,含 filename/url/fileKey/cdnUrl/cosUrl/current_count/total_count/sheet_count)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选,非失败时为空字符串)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式不正确或 where 条件非法" + }, + { + "code": "500", + "message": "导出任务提交失败" + } + ] + }, + { + "method": "order.packing.exportTaskProgress", + "description": "按 task_id 查询打包任务导出任务进度,返回 task_id、status、progress、current_count、total_count、message、result、error、download_url、update_time;上传完成后 download_url 返回下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);任务缓存 Redis TTL 30 分钟,task_id 缺失或缓存未命中时 status=not_found(正常响应,非报错)。状态口径 submitted → running → 数据拉取(10~30) → 关联拉取(30~55) → Excel(55~90) → 上传(92) → success(100),失败 failed + error。免权限免日志口径与 order.exportTaskProgress 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID,兼容 task_id(下划线)与 taskId(驼峰)两种写法" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(task_id 缺失时为回显的空字符串,status=not_found)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理记录数(打包任务条数)" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果对象(完成后含 filename/url/fileKey/cdnUrl/cosUrl 等;未完成或 not_found 时为 null)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选,非失败时为空字符串)" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务完成后下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);未完成或不存在时为空字符串" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "最近一次状态更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [] + }, + { + "method": "order.packing.get", + "description": "打包任务详情查询。按 id + warehouse_id 查询单条打包任务记录,含工作台、视频和运单关联信息。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打包任务ID" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "打包任务详情,含 id、order_id、warehouse_id、workbench_id、wave_id、wave_no、waybill_code、pack_quantity、item_quantity、sku_count、pack_mode、status、start_time、end_time、operator_text、device_ids、remark、meta、create_time、update_time、workbench_name、workbench_type、has_video、video_enable、videos[]、expresses[]" + } + ], + "errors": [ + { + "code": 400, + "description": "参数校验失败(如缺少 id)" + }, + { + "code": 404, + "description": "打包任务不存在或无权访问" + } + ] + }, + { + "method": "order.packing.setEndTime", + "description": "设置打包任务结束时间。若任务状态不是已完成(2),则同步更新状态为已完成。前端默认值:若任务已有结束时间则默认为当前时间,否则默认为开始时间+5分钟。结束时间超过仓库配置的打包最大时长上限时自动截断为 开始时间+上限时长(散单 single_order_pack_max_minutes 默认 3 分钟 / 团购 group_order_pack_max_minutes 默认 40 分钟)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打包任务ID" + }, + { + "name": "end_time", + "type": "string", + "required": true, + "description": "结束时间(ISO 8601 格式,如 2026-07-27T11:00:00.000Z)。前端默认值:若任务已有结束时间→当前时间;无结束时间→开始时间+5分钟。若超过仓库配置的打包最大时长上限(开始时间+配置分钟数),将自动截断为上限时间" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打包任务ID" + }, + { + "name": "end_time", + "type": "string", + "required": true, + "description": "更新后的结束时间(已按仓库配置上限截断,最多为开始时间+配置分钟数)" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "更新后的任务状态" + } + ], + "errors": [ + { + "code": 400, + "description": "参数校验失败(如缺少 id 或 end_time、用户未绑定仓库)" + }, + { + "code": 404, + "description": "打包任务不存在或无权访问" + } + ] + }, + { + "method": "order.packing.forceRecord", + "description": "强制重新录制打包任务视频。将任务推送到录制电脑,通过打印服务触发重新录制。内部会重置视频状态为 created 并清空 video_url。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打包任务ID" + } + ], + "response": [ + { + "name": "pack_task_id", + "type": "number", + "required": true, + "description": "打包任务ID" + }, + { + "name": "computer_id", + "type": "number", + "required": true, + "description": "录制电脑ID" + } + ], + "errors": [ + { + "code": 400, + "description": "参数校验失败(如缺少 id、用户未绑定仓库、无录制电脑、录制电脑不在线)" + }, + { + "code": 404, + "description": "打包任务不存在或无权访问" + }, + { + "code": 500, + "description": "通知打印服务失败" + } + ] + } + ] + }, + { + "groupName": "订单波次模块", + "module": "order.wave", + "list": [ + { + "method": "order.wave.waveStrategyList", + "description": "查询当前仓库波次策略列表。仅查询当前登录仓库在 wms_wave_strategy 中的数据,返回标准 list/pagination 结构。 matched_order_count_filtered 口径:散单/团购策略按同结构数量区间(require_same_express=1 时按「结构+快递」分组)统计;SN 策略(strategy_type=3)忽略同结构区间,只统计命中该策略且满足订单池条件的 SN 订单。", + "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": "strategy_type", + "type": "number | array", + "required": false, + "source": "body", + "description": "仅支持 1=散单、2=团购、3=SN(序列号管理);支持数组多选,如 [1, 3]。与 where.strategy_type 同时存在时以顶层 strategy_type 为准。" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "当前仅支持 where.strategy_type(1/2/3,支持数组如 [1, 3]);其余 where 字段暂不支持。" + }, + { + "name": "calculate_next_fetch_order_count / calculateNextFetchOrderCount", + "type": "number", + "required": false, + "source": "body", + "description": "0-不计算(默认),1-计算并返回每条策略的 next_fetch_order_count;支持别名 calculateNextFetchOrderCount" + }, + { + "name": "debug", + "type": "number", + "required": false, + "source": "body", + "description": "0-不启用(默认),1-启用调试输出,返回每条策略的 next_fetch_order_list(含结构/快递/货主ID等指标明细)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "策略列表,每项为波次策略记录", + "children": [ + { + "name": "id", + "type": "number", + "description": "策略ID" + }, + { + "name": "strategy_name", + "type": "string", + "description": "策略名称" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "strategy_type", + "type": "number", + "description": "策略类型:1-散单 2-团购" + }, + { + "name": "status", + "type": "number", + "description": "状态:1-启用 0-停用" + }, + { + "name": "order_min_sku", + "type": "number", + "description": "订单最小 SKU 种类数(可为空)" + }, + { + "name": "order_max_sku", + "type": "number", + "description": "订单最大 SKU 种类数(可为空)" + }, + { + "name": "order_min_qty", + "type": "number", + "description": "订单最小商品总数(可为空)" + }, + { + "name": "order_max_qty", + "type": "number", + "description": "订单最大商品总数(可为空)" + }, + { + "name": "min_same_structure", + "type": "number", + "description": "最小相同结构订单数(可为空)" + }, + { + "name": "max_same_structure", + "type": "number", + "description": "最大相同结构订单数(可为空)" + }, + { + "name": "require_same_express", + "type": "boolean", + "description": "是否要求相同快递" + }, + { + "name": "allow_cross_owner", + "type": "boolean", + "description": "是否允许跨货主" + }, + { + "name": "batch_mode", + "type": "number", + "description": "拣货模式" + }, + { + "name": "batch_max_orders", + "type": "number", + "description": "批次最大订单数(可为空)" + }, + { + "name": "batch_max_skus", + "type": "number", + "description": "批次最大 SKU 总数(可为空)" + }, + { + "name": "group_batch_max_orders", + "type": "number", + "description": "团购批次最大订单数(可为空)" + }, + { + "name": "allowed_owners", + "type": "array", + "description": "允许的货主 ID 列表(数组或 null)" + }, + { + "name": "allowed_expresses", + "type": "array", + "description": "允许的快递编码列表(数组或 null)" + }, + { + "name": "allowed_provinces", + "type": "array", + "description": "允许的省份列表(数组或 null)" + }, + { + "name": "allowed_platforms", + "type": "array", + "description": "允许的平台列表(数组或 null)" + }, + { + "name": "description", + "type": "string", + "description": "策略描述" + }, + { + "name": "creator_name", + "type": "string", + "description": "创建人" + }, + { + "name": "create_time", + "type": "string", + "description": "创建时间(ISO 字符串)" + }, + { + "name": "update_time", + "type": "string", + "description": "更新时间(ISO 字符串)" + }, + { + "name": "matched_order_count_filtered", + "type": "number", + "description": "按当前仓库且仅统计未在波次(step!=0)并满足同结构区间后的命中订单数;口径与抓取候选一致:require_same_express=1 时按「结构+快递」分组计数,否则仅按结构分组计数" + }, + { + "name": "next_fetch_order_count", + "type": "number", + "description": "按当前策略口径预演一次自动抓取时,预计会选中的订单数量;未开启计算时返回 0" + }, + { + "name": "next_fetch_order_list", + "type": "object", + "description": "调试字段,仅 debug=1 时返回。包含候选订单明细及指标(结构、快递、货主ID 等)", + "children": [ + { + "name": "candidate_count", + "type": "number", + "description": "当前策略匹配的候选订单总数" + }, + { + "name": "candidates", + "type": "array", + "description": "候选订单明细列表(最多 500 条)", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "structure", + "type": "object", + "description": "商品结构(items_hash / items)" + }, + { + "name": "express", + "type": "object", + "description": "快递信息(sys_logistics_code / logistics_code / logistics_name)" + }, + { + "name": "store_id", + "type": "string", + "description": "货主ID" + }, + { + "name": "items_count", + "type": "number", + "description": "SKU 种类数" + }, + { + "name": "items_total", + "type": "number", + "description": "商品总件数" + }, + { + "name": "wave_id", + "type": "number", + "description": "当前波次ID(0=未入波次)" + }, + { + "name": "status", + "type": "string", + "description": "订单状态" + }, + { + "name": "outbound_status", + "type": "string", + "description": "出库状态" + }, + { + "name": "post_status", + "type": "string", + "description": "快递分配状态" + }, + { + "name": "storage_status", + "type": "string", + "description": "储位分配状态" + } + ] + } + ] + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "info", + "type": "object", + "required": true, + "description": "查询汇总信息对象(成功路径恒存在;错误/失败路径响应结构不变,不含本字段)。包含当前查询条件下全部波次策略命中的去重订单总数。", + "children": [ + { + "name": "order_count", + "type": "number", + "description": "当前查询条件下(当前仓库 + strategy_type 过滤)所有策略命中的订单总数,按订单去重(COUNT DISTINCT order_id)统计,不受分页影响;口径与 list[*].matched_order_count_filtered 的抓取候选一致(require_same_express=1 与 =0 两类候选口径合并去重);仅当当前仓库存在波次策略时执行统计,统计失败时安全降级为 0,不影响列表主流程。" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "缺少仓库上下文或分页参数不合法" + }, + { + "code": "400", + "message": "strategy_type 非法(仅支持 1/2/3;支持数组写法如 [1, 3],任一元组非法即报错)" + }, + { + "code": "500", + "message": "查询失败" + } + ] + }, + { + "method": "order.wave.waveStrategyCreate", + "description": "新增波次策略。warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。创建成功后会推进仓库的 wave_strategy_version 并失效相关缓存。 strategy_type=3(SN)时 min_same_structure/max_same_structure 可传入但不生效:SN 策略的抓取与匹配订单数统计都会忽略同结构区间。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "strategy_name", + "type": "string", + "required": true, + "source": "body", + "description": "策略名称(必填)" + }, + { + "name": "strategy_type", + "type": "number", + "required": true, + "source": "body", + "description": "策略类型(必填,正整数):1-散单 2-团购 3-SN(序列号管理)。strategy_type=3 时固定批次模式为「先拣后分」(batch_mode=2),拣货模式固定 pick_mode=3。" + }, + { + "name": "batch_mode", + "type": "number", + "required": true, + "source": "body", + "description": "拣货模式(正整数):1-单品单件 2-先拣后分 3-边拣边分 4-边拣边分H型 5-播种墙 6-流利架。strategy_type=3 时无需传,服务端固定写入 2(先拣后分)。" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:1-启用 0-停用(可选)" + }, + { + "name": "order_min_sku", + "type": "number", + "required": false, + "source": "body", + "description": "订单最小 SKU 种类数(可选,正整数或 null)" + }, + { + "name": "order_max_sku", + "type": "number", + "required": false, + "source": "body", + "description": "订单最大 SKU 种类数(可选,正整数或 null)" + }, + { + "name": "order_min_qty", + "type": "number", + "required": false, + "source": "body", + "description": "订单最小商品总数(可选,正整数或 null)" + }, + { + "name": "order_max_qty", + "type": "number", + "required": false, + "source": "body", + "description": "订单最大商品总数(可选,正整数或 null)" + }, + { + "name": "min_same_structure", + "type": "number", + "required": false, + "source": "body", + "description": "最小相同结构订单数(可选,正整数或 null)" + }, + { + "name": "max_same_structure", + "type": "number", + "required": false, + "source": "body", + "description": "最大相同结构订单数(可选,正整数或 null)。注意:若传入值 >= 仓库配置的 min_group_order_fetch_quantity,则会被下调为 min_group_order_fetch_quantity - 1,最小为 1。" + }, + { + "name": "batch_max_orders", + "type": "number", + "required": false, + "source": "body", + "description": "批次最大订单数(可选)" + }, + { + "name": "batch_max_skus", + "type": "number", + "required": false, + "source": "body", + "description": "批次最大 SKU 总数(可选)" + }, + { + "name": "group_batch_max_orders", + "type": "number", + "required": false, + "source": "body", + "description": "团购批次最大订单数(可选)" + }, + { + "name": "require_same_express", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否要求相同快递(可选,布尔)" + }, + { + "name": "allow_cross_owner", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否允许跨货主(可选,布尔)" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "策略描述(可选)" + }, + { + "name": "allowed_provinces", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的省份列表(可选,支持数组、JSON 字符串或逗号分隔字符串)" + }, + { + "name": "allowed_platforms", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的平台列表(可选,支持数组、JSON 字符串或逗号分隔字符串)" + }, + { + "name": "allowed_owners", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的货主列表(可选,支持数组/JSON/逗号分隔);系统会校验所传货主是否在仓库可用货主范围内,非法值将导致 400 错误。" + }, + { + "name": "allowed_expresses", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的快递编码列表(可选,支持数组/JSON/逗号分隔);系统会校验所传编码是否在可用快递列表内,非法值将导致 400 错误。" + }, + { + "name": "wave_prefix", + "type": "string", + "required": false, + "source": "body", + "description": "波次编号前缀(可选),最多 5 个字符,如 D、B、A;不传则保持原值" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "创建的策略对象,字段同 order.wave.waveStrategyList.list[*] 所示" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "HTTP-like 状态码,成功时返回 200" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少必填参数或参数校验失败(包括 allowed_owners/allowed_expresses 非法)" + }, + { + "code": "500", + "message": "创建失败或内部错误" + } + ] + }, + { + "method": "order.wave.waveStrategyUpdate", + "description": "修改波次策略。warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。id(或 strategy_id/strategyId)为必填主键,其他字段为可选更新;更新成功后会推进仓库的 wave_strategy_version 并失效相关缓存。 strategy_type=3(SN)时 min_same_structure/max_same_structure 可传入但不生效:SN 策略的抓取与匹配订单数统计都会忽略同结构区间。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id / strategy_id / strategyId", + "type": "number", + "required": true, + "source": "body", + "description": "策略主键,兼容 id / strategy_id / strategyId(必填)" + }, + { + "name": "strategy_name", + "type": "string", + "required": false, + "source": "body", + "description": "策略名称(可选)" + }, + { + "name": "strategy_type", + "type": "number", + "required": false, + "source": "body", + "description": "策略类型(可选,正整数):1-散单 2-团购 3-SN(序列号管理)。改为 3 时服务端同步将 batch_mode 固定为 2(先拣后分)。" + }, + { + "name": "batch_mode", + "type": "number", + "required": false, + "source": "body", + "description": "拣货模式(可选,正整数)" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:1-启用 0-停用(可选)" + }, + { + "name": "order_min_sku", + "type": "number", + "required": false, + "source": "body", + "description": "订单最小 SKU 种类数(可选,正整数或 null)" + }, + { + "name": "order_max_sku", + "type": "number", + "required": false, + "source": "body", + "description": "订单最大 SKU 种类数(可选,正整数或 null)" + }, + { + "name": "order_min_qty", + "type": "number", + "required": false, + "source": "body", + "description": "订单最小商品总数(可选,正整数或 null)" + }, + { + "name": "order_max_qty", + "type": "number", + "required": false, + "source": "body", + "description": "订单最大商品总数(可选,正整数或 null)" + }, + { + "name": "min_same_structure", + "type": "number", + "required": false, + "source": "body", + "description": "最小相同结构订单数(可选,正整数或 null)" + }, + { + "name": "max_same_structure", + "type": "number", + "required": false, + "source": "body", + "description": "最大相同结构订单数(可选,正整数或 null)。会受仓库 min_group_order_fetch_quantity 约束,接口会自动调整。" + }, + { + "name": "batch_max_orders", + "type": "number", + "required": false, + "source": "body", + "description": "批次最大订单数(可选)" + }, + { + "name": "batch_max_skus", + "type": "number", + "required": false, + "source": "body", + "description": "批次最大 SKU 总数(可选)" + }, + { + "name": "group_batch_max_orders", + "type": "number", + "required": false, + "source": "body", + "description": "团购批次最大订单数(可选)" + }, + { + "name": "require_same_express", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否要求相同快递(可选,布尔)" + }, + { + "name": "allow_cross_owner", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否允许跨货主(可选,布尔)" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "策略描述(可选)" + }, + { + "name": "allowed_provinces", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的省份列表(可选,支持数组/JSON/逗号分隔)" + }, + { + "name": "allowed_platforms", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的平台列表(可选,支持数组/JSON/逗号分隔)" + }, + { + "name": "allowed_owners", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的货主列表(可选,支持数组/JSON/逗号分隔);系统会校验所传货主是否在仓库可用货主范围内,非法值将导致 400 错误。" + }, + { + "name": "allowed_expresses", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的快递编码列表(可选,支持数组/JSON/逗号分隔);系统会校验所传编码是否在可用快递列表内,非法值将导致 400 错误。" + }, + { + "name": "wave_prefix", + "type": "string", + "required": false, + "source": "body", + "description": "波次编号前缀(可选),最多 5 个字符,如 D、B、A;不传则保持原值" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "更新后的策略对象,字段同 order.wave.waveStrategyList.list[*] 所示" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "HTTP-like 状态码,成功时返回 200" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少 id 或无可更新字段或参数校验失败" + }, + { + "code": "404", + "message": "波次策略不存在" + }, + { + "code": "500", + "message": "更新失败或内部错误" + } + ] + }, + { + "method": "order.wave.waveStrategyQuickScan", + "description": "提交波次策略快速扫描异步任务。无外部参数,使用当前仓库上下文;同一仓库同一时刻仅允许一个任务运行,若已有运行任务直接返回已有 task_id;B2B 订单(is_b2b=Y)全程不参与波次抓取:候选查询、可抓取数量统计与建波均排除,请求传入 B2B 订单 ID 也不会被抓入波次(NULL 存量行视为非 B2B)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于后续查询进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID(来自当前上下文)" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态(一般为 submitted 或 running)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "可选提示信息" + }, + { + "name": "accepted_at", + "type": "string", + "required": false, + "description": "任务受理时间(ISO 字符串)" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文", + "message": "未识别到当前仓库上下文" + }, + { + "code": "500", + "description": "任务提交失败或内部错误", + "message": "任务提交失败或内部错误" + } + ], + "notes": [ + "B2B 抓取排除口径:所有波次抓取链路(团购/散单抓取、按策略抓取、快速扫描匹配、自动加团)的候选取数均带 (is_b2b IS NULL OR is_b2b = 'N') 条件,B2B 订单不会被选入波次;已进波次的 B2B 订单也不会因转 B2B 而被移出,需要时用 order.wave.batchRemoveOrders 移出。" + ] + }, + { + "method": "order.wave.waveStrategyFetchPda", + "description": "按策略提交并创建抓取主流程任务(PDA)。当前为最小主流程:进行入参校验并创建任务记录,返回创建结果与计划预览;后续扫描/执行阶段将扩展为完整执行流。 注意:当存在未完成任务时,接口返回 fetch_state=3 且同时返回 existing task_id/task_no,前端可直接进入拣货流程。 小团购跨池同结构合并规则:候选订单按创建时间分割为第一池(今日 0 点前)与第二池(今日订单),只有第一池抓取完毕才抓取第二池;小团购(pickMode=1)第一池抓取时,按第一池候选分组出现过的结构 key(require_same_express=1 时为「结构+快递」组合)将同结构全池订单(不限策略匹配、不含池边界)并入候选,随后复用既有分组建波流程,修复同结构订单被两池分割后单独成波(1 单 1 波次)的问题。合并触发条件:小团购 pickMode=1、第一池非空(candidate_pool_stage=first)、策略 max_same_structure 为正整数且≠999;max_same_structure 为 null/999 的团购策略跳过合并维持现状,大团购 pickMode=5 与后台抓取入口(order.wave.waveStrategyFetchAdmin)不覆盖;同结构全池查询无新增订单时亦不合并。 SN 策略(strategy_type=3)忽略同结构最小/最大数量限制(min_same_structure/max_same_structure):SN 订单只能由 SN 策略抓取,若按散单同结构区间过滤会永远抓不到单件/少量 SN 订单;其余仍按订单池(wave_id=0、step!=0、快递/储位已分配、未打印、未拦截、未锁定)与 batch_max_skus/batch_max_orders 切片;B2B 订单(is_b2b=Y)全程不参与波次抓取:候选查询、可抓取数量统计与建波均排除,请求传入 B2B 订单 ID 也不会被抓入波次(NULL 存量行视为非 B2B)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "strategy_id / strategyId", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID(正整数,支持下划线/驼峰)" + }, + { + "name": "cart_id / cartId", + "type": "string|number", + "required": false, + "source": "body", + "description": "可选,关联拣货车/作业车ID,支持字符串或数字,用于记录作业上下文" + }, + { + "name": "source / operation_source", + "type": "string", + "required": false, + "source": "body", + "description": "可选,操作来源标识(例如 pda/admin/manual/auto),用于审计与分流策略" + }, + { + "name": "strategy_params / strategyParams", + "type": "object", + "required": false, + "source": "body", + "description": "可选,策略参数透传对象(如 order_min_qty/order_max_qty/allow_cross_owner 等),在创建任务时作为策略覆盖或附加参数使用" + } + ], + "response": [ + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:created(已创建主流程任务),后续可能为 running/success/failed" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务唯一 ID(用于后续查询或关联)" + }, + { + "name": "task_no", + "type": "string", + "required": true, + "description": "任务业务编号(便于展示与关联)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "生效的仓库 ID(来自当前上下文,如可用则返回)" + }, + { + "name": "strategy_id", + "type": "number", + "required": false, + "description": "生效的策略 ID(与入参保持一致,兼容回传)" + }, + { + "name": "plan", + "type": "object", + "required": true, + "description": "任务计划/执行预览对象,描述本次任务预估的执行计划", + "children": [ + { + "name": "estimated_wave_count", + "type": "number", + "description": "预估将创建的波次数量(若适用)" + }, + { + "name": "estimated_order_count", + "type": "number", + "description": "预估涉及的订单数量" + }, + { + "name": "estimated_items_total", + "type": "number", + "description": "预估涉及的商品总件数" + }, + { + "name": "preview_orders", + "type": "array", + "description": "可选:示例性订单 ID 列表或摘要(仅为预览,实际执行结果以最终任务为准)" + } + ] + }, + { + "name": "plan_summary", + "type": "string", + "required": true, + "description": "计划摘要字符串,便于前端在受理后快速展示(例如:'创建 3 个波次,涉及 120 单,约 450 件')" + }, + { + "name": "validation_errors", + "type": "array", + "required": false, + "description": "当入参校验失败时返回的数组,每项为 { field, message } 对象,供前端展示或定位问题" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "可选提示信息或错误说明(创建失败时返回简短说明)" + }, + { + "name": "fetch_state", + "type": "number", + "required": true, + "description": "抓取结果三态:1=成功创建任务(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可进入拣货流程)" + }, + { + "name": "tip", + "type": "string", + "required": false, + "description": "简短提示,用于向前端展示简要原因或下一步建议" + }, + { + "name": "can_enter_pick_flow", + "type": "boolean", + "required": false, + "description": "仅当 fetch_state=3 时为 true,表示前端可直接进入拣货流程" + }, + { + "name": "merged_order_count", + "type": "number", + "required": false, + "description": "小团购(pickMode=1)第一池抓取时,同结构全池订单并入候选的新增订单数量(合并进候选的跨池订单数量,仅统计新增并入、不含第一池原候选);未触发合并或合并无新增订单时为 0。统计口径:本字段不包含在原 candidate_count(合并前候选订单数,位于抓取主流程自动分流执行结果 result 内)之中,合并生效后实际参与分组建波的候选订单总量 = candidate_count + merged_order_count(最终以 selected_order_ids 为准)。触发条件:团购策略(strategy_type=2)且 pickMode=1、第一池非空、策略 max_same_structure 为正整数且≠999;require_same_express=1 时按「结构+快递」组合合并。跳过条件:pickMode=5(大团购)、max_same_structure 为 null/999、第一池为空、同结构全池无新增订单;后台抓取入口(order.wave.waveStrategyFetchAdmin)不经过该合并。该字段来自抓取主流程自动分流执行结果 result(任务创建链路内部返回并写入审计日志)。" + } + ], + "errors": [ + { + "code": "400", + "message": "参数校验失败(详见 validation_errors)" + }, + { + "code": "400", + "message": "未识别到当前仓库上下文" + }, + { + "code": "500", + "message": "创建任务失败或内部错误,message 字段含简短说明" + } + ], + "notes": [ + "B2B 抓取排除口径:所有波次抓取链路(团购/散单抓取、按策略抓取、快速扫描匹配、自动加团)的候选取数均带 (is_b2b IS NULL OR is_b2b = 'N') 条件,B2B 订单不会被选入波次;已进波次的 B2B 订单也不会因转 B2B 而被移出,需要时用 order.wave.batchRemoveOrders 移出。" + ] + }, + { + "method": "order.wave.waveStrategyFetchAdmin", + "description": "按策略提交并创建抓取主流程任务(后台管理)。当前为最小主流程:执行入参校验并创建任务记录,返回创建结果与计划预览;后续将扩展完整扫描/执行链路。 注意:当存在未完成任务时,接口返回 fetch_state=3 且同时返回 existing task_id/task_no,前端可直接进入拣货流程。 SN 策略(strategy_type=3)忽略同结构最小/最大数量限制(min_same_structure/max_same_structure):SN 订单只能由 SN 策略抓取,若按散单同结构区间过滤会永远抓不到单件/少量 SN 订单;其余仍按订单池(wave_id=0、step!=0、快递/储位已分配、未打印、未拦截、未锁定)与 batch_max_skus/batch_max_orders 切片;B2B 订单(is_b2b=Y)全程不参与波次抓取:候选查询、可抓取数量统计与建波均排除,请求传入 B2B 订单 ID 也不会被抓入波次(NULL 存量行视为非 B2B)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "strategy_id / strategyId", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID(正整数,支持下划线/驼峰)" + }, + { + "name": "cart_id / cartId", + "type": "string|number", + "required": false, + "source": "body", + "description": "可选,关联拣货车/作业车ID,用于记录作业上下文或幂等识别" + }, + { + "name": "source / operation_source", + "type": "string", + "required": false, + "source": "body", + "description": "可选,操作来源标识(例如 admin/pda/manual/auto),用于审计与分流策略" + }, + { + "name": "strategy_params / strategyParams", + "type": "object", + "required": false, + "source": "body", + "description": "可选,策略参数透传对象(如 order_min_qty/order_max_qty/allow_cross_owner 等),在创建任务时作为策略覆盖或附加参数使用" + } + ], + "response": [ + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:created(已创建主流程任务),后续可能为 running/success/failed" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务唯一 ID(用于后续查询或关联)" + }, + { + "name": "task_no", + "type": "string", + "required": true, + "description": "任务业务编号(便于展示与关联)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "生效的仓库 ID(来自当前上下文,如可用则返回)" + }, + { + "name": "strategy_id", + "type": "number", + "required": false, + "description": "生效的策略 ID(与入参保持一致,兼容回传)" + }, + { + "name": "plan", + "type": "object", + "required": true, + "description": "任务计划/执行预览对象,描述本次任务预估的执行计划", + "children": [ + { + "name": "estimated_wave_count", + "type": "number", + "description": "预估将创建的波次数量(若适用)" + }, + { + "name": "estimated_order_count", + "type": "number", + "description": "预估涉及的订单数量" + }, + { + "name": "estimated_items_total", + "type": "number", + "description": "预估涉及的商品总件数" + }, + { + "name": "preview_orders", + "type": "array", + "description": "可选:示例性订单 ID 列表或摘要(仅为预览,实际执行结果以最终任务为准)" + } + ] + }, + { + "name": "plan_summary", + "type": "string", + "required": true, + "description": "计划摘要字符串,便于前端在受理后快速展示(例如:'创建 3 个波次,涉及 120 单,约 450 件')" + }, + { + "name": "validation_errors", + "type": "array", + "required": false, + "description": "当入参校验失败时返回的数组,每项为 { field, message } 对象,供前端展示或定位问题" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "可选提示信息或错误说明(创建失败时返回简短说明)" + }, + { + "name": "fetch_state", + "type": "number", + "required": true, + "description": "抓取结果三态:1=成功创建任务(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可进入拣货流程)" + }, + { + "name": "tip", + "type": "string", + "required": false, + "description": "简短提示,用于向前端展示简要原因或下一步建议" + }, + { + "name": "can_enter_pick_flow", + "type": "boolean", + "required": false, + "description": "仅当 fetch_state=3 时为 true,表示前端可直接进入拣货流程" + } + ], + "errors": [ + { + "code": "400", + "description": "参数校验失败(详见 validation_errors)", + "message": "请求失败" + }, + { + "code": "400", + "description": "未识别到当前仓库上下文", + "message": "请求失败" + }, + { + "code": "500", + "description": "创建任务失败或内部错误,message 字段含简短说明", + "message": "请求失败" + } + ], + "notes": [ + "B2B 抓取排除口径:所有波次抓取链路(团购/散单抓取、按策略抓取、快速扫描匹配、自动加团)的候选取数均带 (is_b2b IS NULL OR is_b2b = 'N') 条件,B2B 订单不会被选入波次;已进波次的 B2B 订单也不会因转 B2B 而被移出,需要时用 order.wave.batchRemoveOrders 移出。" + ] + }, + { + "method": "order.wave.waveStrategyQuickScanTaskProgress", + "description": "查询波次策略快速扫描任务进度。接受 task_id / taskId,若未找到返回 state='not_found'。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body", + "description": "任务 ID(下划线或驼峰兼容,必填)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库 ID" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "扫描订单总数" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数" + }, + { + "name": "matched_order_count", + "type": "number", + "required": false, + "description": "命中策略的订单数" + }, + { + "name": "unmatched_order_count", + "type": "number", + "required": false, + "description": "未命中策略的订单数" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "submitted_at", + "type": "string", + "required": false, + "description": "提交时间(timestamp 或 ISO)" + }, + { + "name": "start_time", + "type": "string", + "required": false, + "description": "实际开始时间(ISO)" + }, + { + "name": "end_time", + "type": "string", + "required": false, + "description": "结束时间(ISO)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(若失败)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(若失败)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "耗时,毫秒" + } + ], + "errors": [ + { + "code": "400", + "description": "task_id 参数不能为空" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, + { + "method": "order.wave.groupOrderFetchList", + "description": "按机器结构分组的可抓取列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。;已排除 SN(序列号管理)订单(has_sn_item='Y'),SN 订单不参与团购抓取;B2B 订单(is_b2b=Y)全程不参与波次抓取:候选查询、可抓取数量统计与建波均排除,请求传入 B2B 订单 ID 也不会被抓入波次(NULL 存量行视为非 B2B)。", + "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": "distinguish_express", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否区分快递(影响分组粒度)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID(仅作为筛选条件)" + }, + { + "name": "same_order_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "最小同组订单数量阈值(>=)。若显式传入有效数值则按传入值使用;未传入时使用仓库配置 min_group_order_fetch_quantity(默认 13)。" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(模糊匹配)" + }, + { + "name": "include_sku", + "type": "string", + "required": false, + "source": "body", + "description": "仅保留包含该 SKU 的分组(页内过滤)" + }, + { + "name": "return_order_ids", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否在结果中返回组内订单ID列表" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量g,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;若指定 return_order_ids=true 则额外包含 order_ids" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少仓库上下文或参数格式错误" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 抓取排除口径:所有波次抓取链路(团购/散单抓取、按策略抓取、快速扫描匹配、自动加团)的候选取数均带 (is_b2b IS NULL OR is_b2b = 'N') 条件,B2B 订单不会被选入波次;已进波次的 B2B 订单也不会因转 B2B 而被移出,需要时用 order.wave.batchRemoveOrders 移出。" + ] + }, + { + "method": "order.wave.singleFetchByIds", + "description": "按订单 ID 列表抓取到一个散单波次。仅处理当前仓库的待处理订单(step in [1,2,3]),排除已在波次中的订单(wave_id>0),不区分快递;成功抓取后批量写入订单操作日志;当无可抓取订单时返回 wave_id=0。已锁定订单(lock_status 非 none)不允许抓取波次,返回 excluded_locked_order_ids。B2B 订单不参与抓取,返回 excluded_b2b_order_ids。SN(序列号管理)订单允许按订单 ID 显式抓取散单:SN 策略类型的含义只是「不会被散单/团购策略自动抓取」,手工按订单抓取不受限,因此 excluded_sn_order_ids 恒为空数组(字段保留兼容);抓取后的 manual_ids 波次在拣货侧固定走先拣后分(pick_mode=3),与 SN 策略一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / order_ids / orderIds", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单 ID 列表;支持数组、逗号分隔字符串或单个 ID。入参会被去重并转换为正整数。字段解析优先顺序:ids -> order_ids -> orderIds。" + } + ], + "response": [ + { + "name": "ids", + "type": "array", + "required": true, + "description": "请求归一化后的 ids 列表(去重且为正整数)" + }, + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "创建的波次 ID;若无可抓取订单返回 0" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "创建的波次号;无可抓取时为空字符串" + }, + { + "name": "fetched_order_ids", + "type": "array", + "required": true, + "description": "实际被抓取并成功分配到波次的订单 ID 列表(为归一化后的 ids 的子集)" + }, + { + "name": "fetched_order_count", + "type": "number", + "required": true, + "description": "实际被抓取的订单数量(等于 fetched_order_ids.length)" + }, + { + "name": "excluded_existing_wave_order_ids", + "type": "array", + "required": false, + "description": "原始入参中已在其它波次中的订单 ID(被排除,不会被抓取)" + }, + { + "name": "excluded_locked_order_ids", + "type": "array", + "required": false, + "description": "因已锁定(lock_status 非 none)被排除、不会被抓取波次的订单 ID 列表(成功与无可抓取订单两个返回分支均返回)" + }, + { + "name": "skipped_order_ids", + "type": "array", + "required": false, + "description": "因订单状态不符、正在出库或其他业务原因被跳过的订单 ID(不会被抓取)" + }, + { + "name": "not_found_order_ids", + "type": "array", + "required": false, + "description": "入参中未在数据库中找到的订单 ID" + }, + { + "name": "excluded_sn_order_ids", + "type": "array", + "required": false, + "description": "因 SN(序列号管理)被排除、未加入波次的订单ID列表;SN 订单现已允许按订单抓取,该字段恒为空数组(保留兼容)" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库上下文或 ids 参数不能为空或格式错误;当入参包含非法字段或别名冲突时也会返回 400" + }, + { + "code": "500", + "message": "抓取失败或内部错误" + } + ] + }, + { + "method": "order.wave.waveStrategyFallbackOrderList", + "description": "基于波次策略的回退候选订单列表。该接口内置固定筛选条件:step != 0、wave_id = 0,且满足以下任一条件:wave_scan_result = 2(未匹配任何波次策略)、print_status = 'fin'(已完全打印)、lock_status != 'none'(订单已锁定)、intercept_status != 'none'(订单已拦截)。用于展示策略未命中或需回退处理的订单候选。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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": "筛选白名单字段(object)。仅支持下列字段,且禁止传入 warehouse_id / warehouseId:\n- id(等值)\n- delivery_no / deliveryNo(模糊)\n- tracking_no / trackingNo(模糊)\n- items_count_min / items_count_max(范围)\n- items_total_min / items_total_max(范围)\n- sys_logistics_name(模糊)\n- store_name(模糊)\n- owner_name(等值)\n- province(模糊)\n- sys_platform_name(模糊)\n- buyer_message_has(虚拟字段,覆盖 buyer_message/seller_message/remark 三个字段,任一有值即为有留言,value=true/false)\n说明:若传入未列出的字段或禁止字段(如 warehouse_id)接口会返回 400;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "回退候选订单简要列表。数组内对象字段说明见 children;每行含 excluded_reason 中文标记:已锁定(lock_status 非 none)、已拦截、已打印、未匹配策略。", + "children": [ + { + "name": "id", + "type": "number", + "description": "订单 ID" + }, + { + "name": "delivery_no", + "type": "string", + "description": "配送单号" + }, + { + "name": "tracking_no", + "type": "string", + "description": "运单号" + }, + { + "name": "items_count", + "type": "number", + "description": "SKU 种类数" + }, + { + "name": "items_total", + "type": "number", + "description": "总件数" + }, + { + "name": "items_weight", + "type": "number", + "description": "订单总重量(g),来自 wms_order.items_weight,为 null 时返回 null" + }, + { + "name": "weight_type", + "type": "string", + "description": "重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)" + }, + { + "name": "sys_logistics_name", + "type": "string", + "description": "系统快递名称" + }, + { + "name": "store_name", + "type": "string", + "description": "货主名称" + }, + { + "name": "province", + "type": "string", + "description": "省/直辖市" + }, + { + "name": "sys_platform_name", + "type": "string", + "description": "平台名称" + }, + { + "name": "item_snapshot", + "type": "string", + "description": "商品快照,格式示例:苹果*2|香蕉*3" + }, + { + "name": "wave_index", + "type": "number", + "description": "波次内序号(联查 wms_order_wave_index,无记录时为 0)" + }, + { + "name": "excluded_reason", + "type": "string", + "description": "订单进入回退列表的原因(中文标签):已锁定(lock_status 非 none)/ 已拦截 / 已打印 / 未匹配策略" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库上下文或 where 中包含非法/禁止字段(如 warehouse_id)或存在别名冲突" + }, + { + "code": "500", + "message": "查询失败或内部错误" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.wave.singleOrderFetchList", + "description": "按机器结构分组的散单候选列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。与 order.wave.groupOrderFetchList 不同:groupOrderFetchList 返回满足同组订单数量 >= same_order_quantity(或仓库配置 min_group_order_fetch_quantity)的团购命中分组;singleOrderFetchList 则排除这些团购命中分组,仅返回同组订单数量小于该阈值的散单候选分组(即 < same_order_quantity)。;已排除 SN(序列号管理)订单(has_sn_item='Y'),SN 订单不参与散单抓取;B2B 订单(is_b2b=Y)全程不参与波次抓取:候选查询、可抓取数量统计与建波均排除,请求传入 B2B 订单 ID 也不会被抓入波次(NULL 存量行视为非 B2B)。", + "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": "distinguish_express", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否区分快递(影响分组粒度)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID(仅作为筛选条件)" + }, + { + "name": "same_order_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "最小同组订单数量阈值(用于判定团购命中);本接口返回同组订单数量小于该阈值的分组。若显式传入有效数值则按传入值使用;未传入时使用仓库配置 min_group_order_fetch_quantity(默认 13)。" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(模糊匹配)" + }, + { + "name": "include_sku", + "type": "string", + "required": false, + "source": "body", + "description": "仅保留包含该 SKU 的分组(页内过滤)" + }, + { + "name": "return_order_ids", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否在结果中返回组内订单ID列表" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "散单候选分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量g,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;返回的 group_count 均小于 same_order_quantity(或仓库配置的 min_group_order_fetch_quantity);若指定 return_order_ids=true 则额外包含 order_ids" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少仓库上下文或参数格式错误" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 抓取排除口径:所有波次抓取链路(团购/散单抓取、按策略抓取、快速扫描匹配、自动加团)的候选取数均带 (is_b2b IS NULL OR is_b2b = 'N') 条件,B2B 订单不会被选入波次;已进波次的 B2B 订单也不会因转 B2B 而被移出,需要时用 order.wave.batchRemoveOrders 移出。" + ] + }, + { + "method": "order.wave.wavePickTaskList", + "description": "按当前仓库分页查询拣货任务列表。支持顶层分页参数 `page_no`/`page_size`(兼容 `pagination` 对象与 `current/size`),支持 `status` 单值或数组;兼容历史 `where` 结构,顶层参数优先。默认按 create_time desc 排序。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID(必填)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize,兼容 current / size(兼容旧客户端)" + }, + { + "name": "page_no", + "type": "number", + "required": false, + "source": "body", + "description": "页码(优先于 pagination.page/current)" + }, + { + "name": "page_size", + "type": "number", + "required": false, + "source": "body", + "description": "每页大小(优先于 pagination.pageSize/size)" + }, + { + "name": "status", + "type": "array", + "required": false, + "source": "body", + "description": "拣货任务状态过滤;建议传数组,也兼容单值或逗号分隔字符串,兼容 where.status;顶层参数优先" + }, + { + "name": "review_status", + "type": "number", + "required": false, + "source": "body", + "description": "复核状态过滤" + }, + { + "name": "pick_mode", + "type": "number", + "required": false, + "source": "body", + "description": "拣货模式(如批量/逐单等)" + }, + { + "name": "source", + "type": "string", + "required": false, + "source": "body", + "description": "任务来源标识(业务端语义)" + }, + { + "name": "pick_user_id", + "type": "number", + "required": false, + "source": "body", + "description": "拣货执行人ID(兼容旧字段)" + }, + { + "name": "pick_user_name", + "type": "string", + "required": false, + "source": "body", + "description": "拣货人姓名;支持模糊匹配,也支持操作符对象 { operator: 'like'|'notlike'|'eq', value }(默认 like)" + }, + { + "name": "review_user_id", + "type": "number", + "required": false, + "source": "body", + "description": "复核人ID" + }, + { + "name": "review_user_name", + "type": "string", + "required": false, + "source": "body", + "description": "复核人姓名;支持模糊匹配,也支持操作符对象 { operator: 'like'|'notlike'|'eq', value }(默认 like)" + }, + { + "name": "claim_operator", + "type": "string", + "required": false, + "source": "body", + "description": "领料人姓名;支持模糊匹配,也支持操作符对象 { operator: 'like'|'notlike'|'eq', value }(默认 like)" + }, + { + "name": "task_no", + "type": "string", + "required": false, + "source": "body", + "description": "任务编号(支持模糊匹配)" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "source": "body", + "description": "波次号(模糊匹配任务主表 batch_no_array,如 \"B2026081500040\");也支持操作符对象 { operator: 'like'|'notlike'|'eq', value }(默认 like)" + }, + { + "name": "cart_id", + "type": "number", + "required": false, + "source": "body", + "description": "拣货车/作业车ID" + }, + { + "name": "cart_code", + "type": "string", + "required": false, + "source": "body", + "description": "拣货车编码;匹配拣货任务主表绑定快照 current_cart_code_snapshot,支持模糊匹配,也支持操作符对象 { operator: 'like'|'notlike'|'eq', value }(默认 like,如 { operator: 'eq', value: 'car08' })" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键字搜索:支持 task_no / batch_no / current_cart_code_snapshot 等字段的模糊匹配" + }, + { + "name": "start_time_start", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间(ISO 字符串),与 start_time_end 一起用于时间范围过滤" + }, + { + "name": "start_time_end", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间(ISO 字符串),与 start_time_start 一起用于时间范围过滤" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "兼容历史 where 结构(可包含 status 等字段);当存在顶层同名参数时,顶层参数优先" + }, + { + "name": "strategy_id", + "type": "number", + "required": false, + "source": "body", + "description": "策略ID(当前主表未存,该接口会忽略此过滤,建议勿使用)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "拣货任务列表(数组),每项字段如下", + "children": [ + { + "name": "task_id", + "type": "number", + "description": "任务ID" + }, + { + "name": "task_no", + "type": "string", + "description": "任务编号" + }, + { + "name": "status", + "type": "number", + "description": "任务状态" + }, + { + "name": "source", + "type": "string", + "description": "来源" + }, + { + "name": "pick_mode", + "type": "number", + "description": "拣货模式" + }, + { + "name": "wave_count", + "type": "number", + "description": "关联波次数" + }, + { + "name": "order_count", + "type": "number", + "description": "订单数量" + }, + { + "name": "box_count", + "type": "number", + "description": "箱数" + }, + { + "name": "operator_id", + "type": "number", + "description": "操作人ID(兼容旧字段 pick_user_id)" + }, + { + "name": "operator_name", + "type": "string", + "description": "操作人名称(兼容旧字段 pick_user_name)" + }, + { + "name": "pick_user_id", + "type": "number", + "description": "拣货人ID(兼容字段,旧客户端可能使用)" + }, + { + "name": "pick_user_name", + "type": "string", + "description": "拣货人名称(兼容字段,旧客户端可能使用)" + }, + { + "name": "cart_name", + "type": "string", + "description": "拣货车名称(通过 current_cart_id 关联 wms_pick_cart 表获取,未绑定拣货车时为空字符串)" + }, + { + "name": "claim_operator_id", + "type": "number", + "description": "领料人工号ID(任务创建时从订单冗余,未领料时为 null)" + }, + { + "name": "claim_operator", + "type": "string", + "description": "领料人姓名(任务创建时从订单冗余,未领料时为 null)" + }, + { + "name": "start_at", + "type": "string", + "description": "开始时间(ISO 字符串,兼容 start_time)" + }, + { + "name": "finish_at", + "type": "string", + "description": "完成时间(ISO 字符串,兼容 finish_time)" + }, + { + "name": "start_time", + "type": "string", + "description": "开始时间(ISO 字符串,兼容字段)" + }, + { + "name": "finish_time", + "type": "string", + "description": "完成时间(ISO 字符串,兼容字段)" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间(ISO 字符串,兼容 create_time)" + }, + { + "name": "create_time", + "type": "string", + "description": "创建时间(ISO 字符串,兼容字段)" + }, + { + "name": "wave_list", + "type": "array", + "description": "关联波次列表(通过 wms_wave_pick_task_wave 关联查询,按 id 升序排列)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "box_no", + "type": "number", + "description": "框号" + }, + { + "name": "status", + "type": "number", + "description": "波次关联状态:0-待拣 1-已拣 2-异常" + }, + { + "name": "bind_time", + "type": "string", + "description": "绑定时间(ISO 字符串)" + }, + { + "name": "pick_time", + "type": "string", + "description": "拣货完成时间(ISO 字符串)" + } + ] + } + ] + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "page_size", + "type": "number", + "required": true, + "description": "每页大小" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少仓库上下文或参数格式错误" + }, + { + "code": "500", + "message": "查询失败" + } + ] + }, + { + "method": "order.wave.wavePickTaskCancel", + "description": "取消拣货任务(批量)。可取消的状态:0=待开始、1=拣货中、2=待复核(拣货完成)、3=已完成,状态9(已取消)或其他状态不允许取消。同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。对于status=2或3的任务,取消时会自动回退订单拣货状态:wms_wave_pick_task_order.pick_status(1→0)、order_delivery.pick_status(fin→padding)。入参仅支持 task_ids(数组,必填),不再支持单个 task_id。操作人与仓库从请求上下文获取(例如当前登录用户上下文 ctx.user),若上下文缺失接口将返回错误。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_ids", + "type": "array", + "required": true, + "source": "body", + "description": "任务ID数组,例如 [123,124];仅支持批量处理,不再支持单个 task_id。" + } + ], + "response": [ + { + "name": "cancelled_count", + "type": "number", + "required": false, + "description": "成功取消的任务数量" + }, + { + "name": "task_ids", + "type": "array", + "required": false, + "description": "处理的任务ID数组(若后端返回)" + }, + { + "name": "task_nos", + "type": "array", + "required": false, + "description": "处理的任务编号数组(若后端返回)" + }, + { + "name": "task_id", + "type": "number", + "required": false, + "description": "任务ID(历史兼容,若后端仍返回)" + }, + { + "name": "task_no", + "type": "string", + "required": false, + "description": "任务编号(历史兼容,若后端仍返回)" + } + ], + "errors": [ + { + "code": "400", + "message": "任务状态不允许取消(仅允许status=0/1/2/3)或入参缺失" + }, + { + "code": "403", + "message": "仅允许取消本人创建的任务(wavePickTaskCancelSelf 接口)" + }, + { + "code": "404", + "message": "任务不存在" + }, + { + "code": "500", + "message": "内部错误或事务回滚失败" + } + ] + }, + { + "method": "order.wave.wavePickTaskCancelSelf", + "description": "取消单个拣货任务(仅允许取消当前操作人本人创建的任务;仅支持单个 task_id,明确不支持 task_ids)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "要取消的单个任务 ID(仅支持单个,不支持 task_ids)" + } + ], + "response": [ + { + "name": "cancelled_count", + "type": "number", + "description": "成功取消的任务数量(0 或 1)" + }, + { + "name": "task_id", + "type": "number", + "description": "被处理的任务ID" + }, + { + "name": "task_no", + "type": "string", + "description": "被处理的任务编号(若后端返回)" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法(task_id 缺失或同时传入 task_ids)" + }, + { + "code": "400", + "description": "仅允许取消本人创建任务" + }, + { + "code": "500", + "description": "取消失败" + } + ] + }, + { + "method": "order.wave.batchCancel", + "description": "提交批量解除波次异步任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理波次并执行解除操作;可通过 order.wave.batchCancelTaskProgress 查询进度与结果。新增业务校验:波次内存在拣货中或拣货完成(pick_status 为 padding/fin)的订单,或波次状态已进入拣货及后续环节(wms_wave_batch.wave_status >= 3)时,禁止取消波次并返回 400;异步任务执行时命中上述条件的波次将被跳过,跳过明细见任务进度 result 的 skipped_waves。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids / waveIds / ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID列表;支持数组、逗号分隔字符串或单个ID" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "可选外部任务ID,用于幂等提交" + } + ], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于查询任务进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO8601)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理提示信息" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库上下文" + }, + { + "code": "400", + "message": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "400", + "message": "波次内存在已拣货完成或拣货中的订单,禁止取消波次(订单 pick_status 为 padding/fin;响应附带命中波次 wave_ids 与订单 order_ids)" + }, + { + "code": "400", + "message": "波次已进入拣货或后续环节,禁止取消波次(wms_wave_batch.wave_status >= 3;响应附带命中波次 wave_ids)" + }, + { + "code": "500", + "message": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchCancelTaskProgress", + "description": "查询批量解除波次任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。响应包含 state、progress_percent、processed_wave_count、total_wave_count;当 state 为 success/failed 时返回额外字段说明。成功/失败终态的任务结果 result 中包含 skipped_wave_ids、skipped_wave_count、skipped_waves:因波次内存在已拣货完成或拣货中的订单(pick_status 为 padding/fin)或波次已进入拣货及后续环节(wave_status >= 3)被跳过取消的波次明细。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID(后端生成或提交时传入)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "processed_wave_count", + "type": "number", + "required": false, + "description": "已处理的波次数量" + }, + { + "name": "total_wave_count", + "type": "number", + "required": false, + "description": "总波次数量" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "失败时的错误信息(仅在 state=failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "失败时的错误码(仅在 state=failed 时返回)" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "成功时返回的汇总结果(仅在 state=success 时返回),包含 ids、affected_wave_ids、affected_order_count、canceled_wave_count、skipped_wave_ids、skipped_wave_count、skipped_waves、duration_ms 等字段" + }, + { + "name": "skipped_wave_ids", + "type": "array", + "required": false, + "description": "因业务校验被跳过取消的波次 ID 列表(成功/失败终态的任务结果 result 中返回,数组元素为 number)" + }, + { + "name": "skipped_wave_count", + "type": "number", + "required": false, + "description": "被跳过取消的波次数量(等于 skipped_wave_ids 长度)" + }, + { + "name": "skipped_waves", + "type": "array", + "required": false, + "description": "被跳过取消的波次明细(成功/失败终态的任务结果 result 中返回)。跳过原因两类:波次已进入拣货及后续环节(wave_status >= 3)、波次内存在已拣货完成或拣货中的订单(pick_status 为 padding/fin)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "被跳过取消的波次 ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "reason", + "type": "string", + "description": "跳过原因枚举:wave_status_blocked(波次已进入拣货或后续环节,wave_status >= 3)/ picked_orders_exist(波次内存在已拣货完成或拣货中的订单)" + }, + { + "name": "wave_status", + "type": "number", + "description": "波次当前状态(仅 reason=wave_status_blocked 时返回)" + }, + { + "name": "picked_order_count", + "type": "number", + "description": "命中已拣货完成或拣货中状态的订单数量(仅 reason=picked_orders_exist 时返回)" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "task_id 参数不能为空" + }, + { + "code": "500", + "message": "查询失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchAllocateExpress", + "description": "提交批次分配快递号任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理订单并提交到快递号分配流水线。已锁定订单(lock_status 非 none)与拦截订单在任务中被跳过、不参与分配,跳过明细见任务进度(batchAllocateExpressTaskProgress)的 skipped_locked_order_ids。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids / waveIds / ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID列表;支持数组、逗号分隔字符串或单个ID" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "可选外部任务ID,用于幂等提交" + } + ], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于查询任务进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO8601)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理提示信息" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库上下文" + }, + { + "code": "400", + "message": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "500", + "message": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchAllocateExpressTaskProgress", + "description": "查询批次分配快递号任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。已锁定订单(lock_status 非 none)被跳过,任务进度与 result 中包含 skipped_locked_order_ids(因已锁定被跳过的订单 ID)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID(后端生成或提交时传入)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "任务关联仓库ID" + }, + { + "name": "total_wave_count", + "type": "number", + "required": false, + "description": "波次数量" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "参与分配的订单数量" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数量" + }, + { + "name": "success_order_count", + "type": "number", + "required": false, + "description": "成功提交分配的订单数量" + }, + { + "name": "failed_order_count", + "type": "number", + "required": false, + "description": "提交分配失败的订单数量" + }, + { + "name": "skipped_locked_order_ids", + "type": "array", + "required": false, + "description": "因已锁定(lock_status 非 none)被跳过、未参与快递号分配的订单 ID 列表(任务进度与 result 中均返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "失败时的错误信息" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "失败时的错误码" + } + ], + "errors": [ + { + "code": "400", + "message": "task_id 参数不能为空" + }, + { + "code": "500", + "message": "查询失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchRemoveExceptionOrders", + "description": "提交批次移除异常订单任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取异常订单并移出波次。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids / waveIds / ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID列表;支持数组、逗号分隔字符串或单个ID" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "可选外部任务ID,用于幂等提交" + } + ], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于查询任务进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO8601)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理提示信息" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "400", + "description": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchRemoveExceptionOrdersTaskProgress", + "description": "查询批次移除异常订单任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID(后端生成或提交时传入)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "任务关联仓库ID" + }, + { + "name": "total_wave_count", + "type": "number", + "required": false, + "description": "波次数量" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "参与处理的订单数量" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数量" + }, + { + "name": "removed_order_count", + "type": "number", + "required": false, + "description": "已成功移出波次的订单数量" + }, + { + "name": "failed_order_count", + "type": "number", + "required": false, + "description": "处理失败的订单数量" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "失败时的错误信息" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "失败时的错误码" + } + ], + "errors": [ + { + "code": "400", + "description": "task_id 参数不能为空" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchAllocateStorage", + "description": "提交批次分配储位任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理订单并提交到储位分配流水线。已锁定订单(lock_status 非 none)在任务中被直接跳过、不参与储位分配。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids / waveIds / ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID列表;支持数组、逗号分隔字符串或单个ID" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "可选外部任务ID,用于幂等提交" + } + ], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于查询任务进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO8601)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理提示信息" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库上下文" + }, + { + "code": "400", + "message": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "500", + "message": "任务提交失败或内部错误" + } + ], + "notes": [ + "静态盘点锁定拦截(本次,0.3.316):本接口内部调用 orderStorageAllocation.allocateStorage 完成分配,商品命中静态盘点锁定时同样整单失败(400),文案与 order.pendingOrder.allocateStorage 一致。", + "静态盘点锁定口径(本次,0.3.317):沿用 allocateStorage 的订单级失败处理——命中锁定的订单标记 storage_status=error/order_flag,其余订单继续分配;波次批量分配不会因个别订单命中锁定而整体失败。" + ] + }, + { + "method": "order.wave.batchAllocateStorageTaskProgress", + "description": "查询批次分配储位任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。已锁定订单(lock_status 非 none)被直接跳过,不计入 total_order_count 等统计。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID(后端生成或提交时传入)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "任务关联仓库ID" + }, + { + "name": "total_wave_count", + "type": "number", + "required": false, + "description": "波次数量" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "参与分配的订单数量" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数量" + }, + { + "name": "success_order_count", + "type": "number", + "required": false, + "description": "成功提交分配的订单数量" + }, + { + "name": "failed_order_count", + "type": "number", + "required": false, + "description": "提交分配失败的订单数量" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "失败时的错误信息" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "失败时的错误码" + } + ], + "errors": [ + { + "code": "400", + "message": "task_id 参数不能为空" + }, + { + "code": "500", + "message": "查询失败或内部错误" + } + ] + }, + { + "method": "order.wave.groupFetch", + "description": "抓取团购接口(异步任务提交);团购抓取会排除 SN(序列号管理)订单;B2B 订单(is_b2b=Y)全程不参与波次抓取:候选查询、可抓取数量统计与建波均排除,请求传入 B2B 订单 ID 也不会被抓入波次(NULL 存量行视为非 B2B)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "structure_list", + "type": "array", + "required": true, + "source": "body", + "description": "结构请求数组;每项必须包含 item_detail_machine(由 buildMachineStructureToken 生成的结构标识),可选 quantity(未传入时使用仓库默认或全局默认)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成的唯一标识,用于查询任务状态或结果)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID" + }, + { + "name": "structure_count", + "type": "number", + "required": true, + "description": "本次入参的结构数量(structure_list 长度)" + }, + { + "name": "default_quantity", + "type": "number", + "required": true, + "description": "仓库默认抓取数量或全局默认值" + }, + { + "name": "fetch_mode", + "type": "string", + "required": false, + "description": "抓取模式,值为 'group'(团购)或 'single'(散单)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理信息提示,通常为 '任务已提交,后端异步处理中' 或失败/错误说明" + } + ], + "errors": [ + { + "code": 400, + "message": "structure_list 必须是非空数组或结构项参数不合法" + }, + { + "code": 500, + "message": "任务提交失败或内部错误" + } + ], + "notes": [ + "B2B 抓取排除口径:所有波次抓取链路(团购/散单抓取、按策略抓取、快速扫描匹配、自动加团)的候选取数均带 (is_b2b IS NULL OR is_b2b = 'N') 条件,B2B 订单不会被选入波次;已进波次的 B2B 订单也不会因转 B2B 而被移出,需要时用 order.wave.batchRemoveOrders 移出。" + ] + }, + { + "method": "order.wave.singleFetch", + "description": "抓取散单接口(异步任务提交);散单抓取同样排除 SN(序列号管理)订单;B2B 订单(is_b2b=Y)全程不参与波次抓取:候选查询、可抓取数量统计与建波均排除,请求传入 B2B 订单 ID 也不会被抓入波次(NULL 存量行视为非 B2B)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "structure_list", + "type": "array", + "required": true, + "source": "body", + "description": "结构请求数组;每项必须包含 item_detail_machine(由 buildMachineStructureToken 生成的结构标识)并包含必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数);可选 quantity(未传入时使用仓库默认或全局默认)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成的唯一标识,用于查询任务状态或结果)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID" + }, + { + "name": "structure_count", + "type": "number", + "required": true, + "description": "本次入参的结构数量(structure_list 长度)" + }, + { + "name": "default_quantity", + "type": "number", + "required": true, + "description": "仓库默认抓取数量或全局默认值" + }, + { + "name": "fetch_mode", + "type": "string", + "required": false, + "description": "抓取模式,值为 'group'(团购)或 'single'(散单)" + }, + { + "name": "max_fetch_quantity", + "type": "number", + "required": false, + "description": "提交时生效的最大抓取上限(订单数,正整数)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理信息提示,通常为 '任务已提交,后端异步处理中' 或失败/错误说明" + } + ], + "errors": [ + { + "code": 400, + "message": "structure_list 必须是非空数组或结构项参数不合法;max_fetch_quantity 必填且为正整数" + }, + { + "code": 500, + "message": "任务提交失败或内部错误" + } + ], + "notes": [ + "B2B 抓取排除口径:所有波次抓取链路(团购/散单抓取、按策略抓取、快速扫描匹配、自动加团)的候选取数均带 (is_b2b IS NULL OR is_b2b = 'N') 条件,B2B 订单不会被选入波次;已进波次的 B2B 订单也不会因转 B2B 而被移出,需要时用 order.wave.batchRemoveOrders 移出。" + ] + }, + { + "method": "order.wave.fetch", + "description": "兼容别名(等同 groupFetch);B2B 订单(is_b2b=Y)全程不参与波次抓取:候选查询、可抓取数量统计与建波均排除,请求传入 B2B 订单 ID 也不会被抓入波次(NULL 存量行视为非 B2B)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "structure_list", + "type": "array", + "required": true, + "source": "body", + "description": "结构请求数组;每项必须包含 item_detail_machine(由 buildMachineStructureToken 生成的结构标识),可选 quantity(未传入时使用仓库默认或全局默认)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成的唯一标识,用于查询任务状态或结果)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID" + }, + { + "name": "structure_count", + "type": "number", + "required": true, + "description": "本次入参的结构数量(structure_list 长度)" + }, + { + "name": "default_quantity", + "type": "number", + "required": true, + "description": "仓库默认抓取数量或全局默认值" + }, + { + "name": "fetch_mode", + "type": "string", + "required": false, + "description": "抓取模式,值为 'group'(团购)或 'single'(散单)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理信息提示,通常为 '任务已提交,后端异步处理中' 或失败/错误说明" + } + ], + "errors": [ + { + "code": 400, + "message": "structure_list 必须是非空数组或结构项参数不合法" + }, + { + "code": 500, + "message": "任务提交失败或内部错误" + } + ], + "notes": [ + "B2B 抓取排除口径:所有波次抓取链路(团购/散单抓取、按策略抓取、快速扫描匹配、自动加团)的候选取数均带 (is_b2b IS NULL OR is_b2b = 'N') 条件,B2B 订单不会被选入波次;已进波次的 B2B 订单也不会因转 B2B 而被移出,需要时用 order.wave.batchRemoveOrders 移出。" + ] + }, + { + "method": "order.wave.fetchTaskProgress", + "description": "查询波次抓取任务进度:按 task_id 查询任务状态与进度;兼容 taskId 参数名。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID(后端生成的唯一标识),兼容旧参数名 taskId,可从 order.wave.fetch 的返回值中获取" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "生效的仓库 ID(若任务关联仓库时返回)" + }, + { + "name": "structure_count", + "type": "number", + "required": false, + "description": "本次任务的结构数量(structure_list 长度)" + }, + { + "name": "finished_structure_count", + "type": "number", + "required": false, + "description": "已完成抓取的结构数量" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100,可能为小数)" + }, + { + "name": "total_fetched_quantity", + "type": "number", + "required": false, + "description": "已抓取的总件数" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务已运行时长,毫秒级" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息,仅当 status=failed 时返回" + }, + { + "name": "fetch_mode", + "type": "string", + "required": false, + "description": "抓取模式,值为 'group'(团购)或 'single'(散单);single 模式时可能返回下列额外字段" + }, + { + "name": "max_fetch_quantity", + "type": "number", + "required": false, + "description": "当 fetch_mode=single 时返回的最大抓取上限(订单数,正整数)" + }, + { + "name": "limit_reached", + "type": "boolean", + "required": false, + "description": "当 fetch_mode=single 时指示是否已达到 max_fetch_quantity 限制" + }, + { + "name": "stop_reason", + "type": "string", + "required": false, + "description": "任务停止原因(如达到上限、人工停止或其他失败原因)" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "最近一次状态更新时间,ISO8601 字符串" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "额外提示信息" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 为空或格式不合法" + }, + { + "code": 500, + "message": "内部错误" + } + ] + }, + { + "method": "order.wave.batchAutoGrouping", + "description": "批量将波次状态修改为 0(自动加团中),仅作用当前登录仓库命中的波次。限制条件:\n- 跳过已打印及之后状态的波次(wave_status >= 2);\n- 跳过 total_orders >= 仓库配置 max_wave_quantity 的波次。被跳过的波次不会被修改为自动加团中。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID 列表;支持数组、逗号分隔字符串或单个ID" + } + ], + "response": [ + { + "name": "ids", + "type": "array", + "description": "归一化后的请求ID" + }, + { + "name": "affected_wave_ids", + "type": "array", + "description": "实际命中的波次ID" + }, + { + "name": "updated_wave_count", + "type": "number", + "description": "实际更新数量" + }, + { + "name": "skipped_wave_ids", + "type": "array", + "description": "被跳过的波次ID数组(不修改状态)" + }, + { + "name": "skipped_wave_count", + "type": "number", + "description": "被跳过的波次数量" + }, + { + "name": "skipped_details", + "type": "array", + "description": "被跳过的波次明细數組,元素包含 wave_id 与 reason,reason 枚举 printed_or_after_printed / reach_max_wave_quantity", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次 ID" + }, + { + "name": "reason", + "type": "string", + "description": "跳过原因,枚举: printed_or_after_printed / reach_max_wave_quantity" + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "400", + "description": "ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "批量修改波次状态失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchFinishAutoGrouping", + "description": "批量结束自动加团,将当前仓库命中且 wave_status=0 的波次改为 1(已就绪)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID 列表;支持数组、逗号分隔字符串或单个ID" + } + ], + "response": [ + { + "name": "ids", + "type": "array", + "description": "归一化后的请求ID" + }, + { + "name": "affected_wave_ids", + "type": "array", + "description": "实际命中的波次ID" + }, + { + "name": "updated_wave_ids", + "type": "array", + "description": "实际更新为已就绪的波次ID" + }, + { + "name": "updated_wave_count", + "type": "number", + "description": "实际更新数量" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "400", + "description": "ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "批量结束自动加团失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchRemoveOrders", + "description": "按订单ID批量移出波次;仅处理当前仓库的待处理订单表中非待审核订单(step in [1,2,3])。操作会清空订单的 wave_id/wave_no,并在同一事务内回写 wms_wave_batch 表:重算 total_orders,若波次被清空则将 wave_status 置为 -1。仓库上下文来自当前登录用户(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / order_ids / orderIds / order_id / orderId / id", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单 ID 列表;支持数组、逗号分隔字符串或单个 ID,以上别名均可用(ids、order_ids、orderIds、order_id、orderId、id)" + } + ], + "response": [ + { + "name": "ids", + "type": "array", + "required": true, + "description": "归一化后的请求 ID 列表" + }, + { + "name": "removed_order_ids", + "type": "array", + "required": true, + "description": "实际被移出波次的订单 ID 列表" + }, + { + "name": "removed_order_count", + "type": "number", + "required": true, + "description": "被移出波次的订单数量" + }, + { + "name": "affected_wave_ids", + "type": "array", + "required": true, + "description": "本次操作涉及的波次 ID 列表" + }, + { + "name": "updated_wave_ids", + "type": "array", + "required": true, + "description": "实际更新了 total_orders 的波次 ID 列表" + }, + { + "name": "emptied_wave_ids", + "type": "array", + "required": true, + "description": "被清空且已置为 wave_status=-1 的波次 ID 列表" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少仓库上下文(用户登录信息无 store_id)或 ids 参数为空/格式错误" + }, + { + "code": "500", + "message": "内部错误" + } + ] + }, + { + "method": "order.wave.fetchableOrderCount", + "description": "统计当前仓库团购可抓取订单数。口径与 order.wave.groupOrderFetchList 完全一致(同一候选条件 + items_hash 粗分组 + 团购阈值过滤),但不分页、不查订单明细,仅返回达到团购阈值分组的数量与组内订单数合计。注意与 groupOrderFetchList 的口径差异:其 pagination.total 是分组数,本方法 order_count 是命中分组的订单数合计。;统计口径同样排除 SN(序列号管理)订单;B2B 订单(is_b2b=Y)全程不参与波次抓取:候选查询、可抓取数量统计与建波均排除,请求传入 B2B 订单 ID 也不会被抓入波次(NULL 存量行视为非 B2B)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "distinguish_express", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否区分快递(影响分组粒度):开启后按「结构(items_hash) + 快递编码」分组,关闭(默认)仅按结构分组。" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID(仅作为筛选条件,需为非负整数)。" + }, + { + "name": "same_order_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "最小同组订单数量阈值(>=)。显式传入有效非负整数且大于 0 时按传入值使用;未传入或为 0 时使用仓库配置 min_group_order_fetch_quantity(默认 13)。" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(shop_nick 模糊匹配)。" + }, + { + "name": "stock_query", + "type": "string", + "required": false, + "source": "body", + "description": "商品模糊筛选:经 stock_warehouse / stock_barcodes → order_items 限定候选订单范围;未匹配到任何商品时直接返回 group_count=0 / order_count=0。" + } + ], + "response": [ + { + "name": "group_count", + "type": "number", + "required": true, + "description": "达到团购阈值的分组数(同组订单数 >= same_order_quantity)。" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "可抓取订单数合计(命中分组内订单数之和;不含未达阈值分组的订单,也不含 items_hash/items 均为空无法分组的订单)。" + }, + { + "name": "same_order_quantity", + "type": "number", + "required": true, + "description": "本次统计实际使用的团购阈值(入参值或仓库配置值)。" + }, + { + "name": "raw_order_count", + "type": "number", + "required": true, + "description": "参与分组统计的候选订单总数(过滤团购阈值之前,便于核对口径)。" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID(取自登录上下文 ctx.user.store_id)。" + }, + { + "name": "distinguish_express", + "type": "boolean", + "required": true, + "description": "是否区分快递(回显本次分组粒度)。" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库上下文" + }, + { + "code": "400", + "message": "参数格式错误(如 store_id / same_order_quantity 非非负整数)" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 抓取排除口径:所有波次抓取链路(团购/散单抓取、按策略抓取、快速扫描匹配、自动加团)的候选取数均带 (is_b2b IS NULL OR is_b2b = 'N') 条件,B2B 订单不会被选入波次;已进波次的 B2B 订单也不会因转 B2B 而被移出,需要时用 order.wave.batchRemoveOrders 移出。" + ] + } + ] + }, + { + "groupName": "订单待出库模块", + "module": "order.outboundOrder", + "list": [ + { + "method": "order.outboundOrder.list", + "description": "待出库订单列表,默认筛选 outbound_status in [fin,padding] 且 step in [4,9]。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配);默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + }, + { + "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 字段字典”章节);本次新增 wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.outboundOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "description": "运单信息数组" + }, + { + "name": "waybill_codes", + "type": "array", + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "description": "订单ID 为空或格式错误" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "description": "内部错误" + } + ] + }, + { + "method": "order.outboundOrder.manualOutboundOrder", + "description": "待出库模块的手动出库入口,行为与 order.manualOutboundOrder 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "number", + "required": false, + "source": "body", + "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": "迁移失败或数据库错误" + } + ] + } + ] + }, + { + "groupName": "订单异常模块", + "module": "order.expectionOrder", + "list": [ + { + "method": "order.expectionOrder.list", + "description": "待处理异常订单列表,默认仅查询 step=3 的订单。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配);默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + }, + { + "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 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.expectionOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "description": "运单信息数组" + }, + { + "name": "waybill_codes", + "type": "array", + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "description": "订单ID 为空或格式错误" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "description": "内部错误" + } + ] + }, + { + "method": "order.expectionOrder.resolveException", + "description": "将待处理异常订单转回正常待处理状态(step 3 → 2)。只操作当前仓库的当前订单表,且仅对 step=3 的订单生效。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID 正整数数组,不能为空" + } + ], + "response": [ + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "实际更新行数" + }, + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "本次操作的订单ID 列表" + } + ], + "errors": [ + { + "code": "400", + "message": "ids 为空或格式非法" + }, + { + "code": "500", + "message": "更新失败" + } + ] + } + ] + }, + { + "groupName": "订单委托外仓模块", + "module": "order.entrustOrder", + "list": [ + { + "method": "order.entrustOrder.list", + "description": "委托外仓订单列表,使用 outsourced 模型。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配);默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + }, + { + "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 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.entrustOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "description": "运单信息数组" + }, + { + "name": "waybill_codes", + "type": "array", + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "description": "订单ID 为空或格式错误" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "description": "内部错误" + } + ] + } + ] + }, + { + "groupName": "订单配送模块", + "module": "order.deliveryOrder", + "list": [ + { + "method": "order.deliveryOrder.list", + "description": "配送订单列表,使用 dispatch 模型,默认筛选 dispatch_lane=m4。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配);默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + }, + { + "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 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.deliveryOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "required": true, + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "required": true, + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "required": true, + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "required": true, + "description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)、package_material_id(包材ID,number|null)、package_material_name_snapshot(包材名称快照,string|null)" + }, + { + "name": "waybill_codes", + "type": "array", + "required": true, + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "message": "订单ID 为空或格式错误" + }, + { + "code": "404", + "message": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "内部错误" + } + ] + }, + { + "method": "order.deliveryOrder.quickSearch", + "description": "订单快速搜索。跨表联合搜索:运单号(wms_order_express,支持完整单号等值、剥离一单多件包裹序号分段后缀(如 -1-1-)后的主体单号等值、主体前缀 LIKE '主体-%' 匹配,不再做部分单号模糊匹配)、发货单号 delivery_order_code / 原始平台订单号 source_order_codes(express 表快照字段,模糊匹配)。返回匹配的订单列表(最多20条),包含关键字段及关联运单号;平台交易单号 pay_no 仅作为结果字段回显,不参与搜索匹配。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "keyword", + "type": "string", + "required": true, + "source": "body", + "description": "搜索关键词。运单号按「完整单号等值 + 剥离一单多件分段后缀(如 -1-1-)后的主体单号等值 + 主体前缀 LIKE '主体-%'」匹配(不做部分单号模糊);发货单号 delivery_order_code、原始平台订单号 source_order_codes 为模糊匹配(LIKE '%kw%');平台交易单号 pay_no 仅回显、不参与匹配" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "匹配的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "waybill_id", + "type": "number", + "required": true, + "description": "运单记录ID(wms_order_express.id),0=无关联运单" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "logistics_code", + "type": "string", + "required": true, + "description": "快递公司编码" + }, + { + "name": "logistics_name", + "type": "string", + "required": true, + "description": "快递公司名称" + }, + { + "name": "logistics_interface_id", + "type": "number", + "required": true, + "description": "快递接口ID" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": true, + "description": "快递接口名称" + }, + { + "name": "platform_code", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "waybill_status", + "type": "number", + "required": true, + "description": "运单状态 0/1" + }, + { + "name": "waybill_status_text", + "type": "string", + "required": true, + "description": "运单状态文本" + }, + { + "name": "weighing_weight", + "type": "number", + "required": true, + "description": "称重重量(g)" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": true, + "description": "发货单号" + }, + { + "name": "source_order_codes", + "type": "string", + "required": true, + "description": "原始平台订单号" + }, + { + "name": "pay_no", + "type": "string", + "required": true, + "description": "平台交易单号" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "store_name", + "type": "string", + "required": true, + "description": "货主名称" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "订单状态" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "收件人" + }, + { + "name": "mobile", + "type": "string", + "required": true, + "description": "手机号" + }, + { + "name": "province", + "type": "string", + "required": true, + "description": "省" + }, + { + "name": "city", + "type": "string", + "required": true, + "description": "市" + }, + { + "name": "area", + "type": "string", + "required": true, + "description": "区" + }, + { + "name": "detail_address", + "type": "string", + "required": true, + "description": "详细地址" + }, + { + "name": "buyer_nick", + "type": "string", + "required": true, + "description": "买家昵称" + }, + { + "name": "seller_nick", + "type": "string", + "required": true, + "description": "卖家昵称" + }, + { + "name": "shop_nick", + "type": "string", + "required": true, + "description": "店铺名称" + }, + { + "name": "total_amount", + "type": "number", + "required": true, + "description": "订单总金额" + }, + { + "name": "item_amount", + "type": "number", + "required": true, + "description": "商品金额" + }, + { + "name": "freight", + "type": "number", + "required": true, + "description": "运费" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "商品件数" + }, + { + "name": "items_weight", + "type": "number", + "required": true, + "description": "商品总重量(g)" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "delivery_time", + "type": "string", + "required": true, + "description": "发货时间" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "创建时间" + } + ] + }, + { + "name": "keyword", + "type": "string", + "required": true, + "description": "回显搜索关键词" + } + ], + "errors": [ + { + "code": 400, + "message": "缺少 keyword 参数或仓库上下文" + }, + { + "code": 500, + "message": "搜索失败" + } + ] + }, + { + "method": "order.deliveryOrder.summary", + "description": "配送订单每日汇总:以自然日(yyyy-MM-dd)为维度统计每日订单量、当日迁入配送表订单量、发货量(订单数/商品件数/发货金额)、拦截数量、库内确定拦截数量与取消数量;仓库取自登录上下文,可选 store_id 按货主过滤;默认最近 7 个自然日(含今天),单次最多 90 天,区间内无数据的日期补 0。数据源为订单常用表与配送表(订单出库迁移进配送表时删除源行,两表无重叠,直接相加不重复计数),不含归档表 history 与委托外仓表 outsourced。各指标按自身时间字段落入统计日:order_count=create_at(排除取消单)、dispatch_count=配送表 dispath_time、shipped_*=delivery_time(排除取消单)、intercepted_count=intercept_time(intercept_status != none)、intercepted_at_warehouse_count=配送表 dispath_time(intercept_status=intercepted_at_warehouse)、cancelled_count=updated_at(status=cancel)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "******" + } + ], + "params": [ + { + "name": "start_date", + "type": "string", + "required": false, + "source": "body", + "description": "开始日期(yyyy-MM-dd,兼容 startDate / start_time;缺省为结束日往前 6 天)" + }, + { + "name": "end_date", + "type": "string", + "required": false, + "source": "body", + "description": "结束日期(yyyy-MM-dd,兼容 endDate / end_time;缺省为今天)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID过滤(兼容 storeId;不传或 <=0 表示不按货主过滤)" + } + ], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自登录上下文 ctx.user.store_id)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "description": "货主ID过滤值;未按货主过滤时为 null" + }, + { + "name": "start_date", + "type": "string", + "required": true, + "description": "实际统计开始日期(yyyy-MM-dd)" + }, + { + "name": "end_date", + "type": "string", + "required": true, + "description": "实际统计结束日期(yyyy-MM-dd,含当天)" + }, + { + "name": "day_count", + "type": "number", + "required": true, + "description": "统计天数(含首尾自然日)" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "逐日汇总数组,按日期升序,区间内无数据的日期补 0;每项字段见 children", + "children": [ + { + "name": "date", + "type": "string", + "description": "统计日期(yyyy-MM-dd)" + }, + { + "name": "order_count", + "type": "number", + "description": "当日创建订单数(create_at 落在当日,排除取消单)" + }, + { + "name": "dispatch_count", + "type": "number", + "description": "当日迁入配送表的订单数(配送表 dispath_time 落在当日)" + }, + { + "name": "shipped_count", + "type": "number", + "description": "当日发货订单数(delivery_time 落在当日,排除取消单)" + }, + { + "name": "shipped_items_total", + "type": "number", + "description": "当日发货商品件数(发货订单 items_total 合计)" + }, + { + "name": "shipped_amount", + "type": "number", + "description": "当日发货订单金额(发货订单 total_amount 合计,两位小数)" + }, + { + "name": "intercepted_count", + "type": "number", + "description": "当日拦截订单数(intercept_status != none 且 intercept_time 落在当日)" + }, + { + "name": "intercepted_at_warehouse_count", + "type": "number", + "description": "当日库内确定拦截订单数(配送表 dispath_time 落在当日,intercept_status=intercepted_at_warehouse)" + }, + { + "name": "cancelled_count", + "type": "number", + "description": "当日取消订单数(status=cancel 且 updated_at 落在当日)" + } + ] + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "区间合计(各字段口径同 list 中对应字段之和)", + "children": [ + { + "name": "order_count", + "type": "number", + "description": "区间创建订单数合计" + }, + { + "name": "dispatch_count", + "type": "number", + "description": "区间迁入配送表订单数合计" + }, + { + "name": "shipped_count", + "type": "number", + "description": "区间发货订单数合计" + }, + { + "name": "shipped_items_total", + "type": "number", + "description": "区间发货商品件数合计" + }, + { + "name": "shipped_amount", + "type": "number", + "description": "区间发货金额合计(两位小数)" + }, + { + "name": "intercepted_count", + "type": "number", + "description": "区间拦截订单数合计" + }, + { + "name": "intercepted_at_warehouse_count", + "type": "number", + "description": "区间库内确定拦截订单数合计" + }, + { + "name": "cancelled_count", + "type": "number", + "description": "区间取消订单数合计" + } + ] + } + ], + "errors": [ + { + "code": "0", + "message": "缺少仓库上下文(当前用户未绑定仓库),返回 flag=failure" + }, + { + "code": "0", + "message": "日期参数不合法(开始/结束日期格式应为 yyyy-MM-dd、开始日期不能晚于结束日期、汇总天数不能超过 90 天),返回 flag=failure" + }, + { + "code": "401", + "message": "未登录或 token 无效" + }, + { + "code": "500", + "message": "配送订单汇总查询失败(数据库异常,详情见服务端日志)" + } + ] + }, + { + "method": "order.deliveryOrder2b.list", + "description": "B2B 配送订单列表。查询条件与 order.deliveryOrder.list 完全一致(dispatch 分表 + 默认 dispatch_lane=m4),额外强制 is_b2b='Y'。固定条件与请求 where 取 AND,请求传入同名 is_b2b 条件无法覆盖。;列表行额外带出 wms_order_b2b 作业明细字段:total_box_count(总箱数)、pickup_plate_number(提货车牌)、prep_remark(备货备注)、prep_duration_seconds(备货用时/秒)、prep_at(备货完成时间)、is_picked_up(是否提货 Y/N)、picked_up_at(提货时间)、created_at(作业明细创建时间,与订单自身的 create_at 不同)。关联条件固定为 warehouse_id + order_id;无作业明细行时上述字段输出空值占位(数值 0、is_picked_up=N、时间为 null);另支持按 wms_order_b2b 作业明细字段筛选(仅本接口开放,普通订单列表不识别这些字段):total_box_count(总箱数)、pickup_plate_number(提货车牌)、prep_remark(备货备注)、prep_duration_seconds(备货用时/秒)、is_picked_up(Y/N)、picked_up_at(提货时间)、created_at(作业明细创建时间)、prep_at(备货完成时间)。支持简写与标准结构,如 {\"is_picked_up\":\"Y\"}、{\"pickup_plate_number\":{\"operator\":\"like\",\"value\":\"粤A\"}}、{\"prep_at\":{\"operator\":\"between\",\"value\":[\"2026-11-01 00:00:00\",\"2026-11-30 23:59:59\"]}};内部先按 warehouse_id + order_id 查 wms_order_b2b 取命中 order_id,再回填订单列表条件,未命中返回空列表。", + "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 条件对象,语义与 order.deliveryOrder.list 完全一致(禁止传入 warehouse_id / warehouseId)。另强制附加 is_b2b='Y':即使传入 {\"is_b2b\":\"N\"} 也只会得到空列表(固定条件与请求条件取 AND);另支持按 wms_order_b2b 作业明细字段筛选(仅本接口开放,普通订单列表不识别这些字段):total_box_count(总箱数)、pickup_plate_number(提货车牌)、prep_remark(备货备注)、prep_duration_seconds(备货用时/秒)、is_picked_up(Y/N)、picked_up_at(提货时间)、created_at(作业明细创建时间)、prep_at(备货完成时间)。支持简写与标准结构,如 {\"is_picked_up\":\"Y\"}、{\"pickup_plate_number\":{\"operator\":\"like\",\"value\":\"粤A\"}}、{\"prep_at\":{\"operator\":\"between\",\"value\":[\"2026-11-01 00:00:00\",\"2026-11-30 23:59:59\"]}};内部先按 warehouse_id + order_id 查 wms_order_b2b 取命中 order_id,再回填订单列表条件,未命中返回空列表。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder;默认 delivery_time DESC, id DESC" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "B2B 配送订单列表(raw 行数据,字段与 order.deliveryOrder.list 一致)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + }, + { + "name": "total_box_count", + "type": "number", + "required": true, + "description": "总箱数(wms_order_b2b.total_box_count,无作业明细行时为 0)" + }, + { + "name": "pickup_plate_number", + "type": "string", + "required": false, + "description": "提货车牌(wms_order_b2b.pickup_plate_number)" + }, + { + "name": "prep_remark", + "type": "string", + "required": false, + "description": "备货备注(wms_order_b2b.prep_remark)" + }, + { + "name": "prep_duration_seconds", + "type": "number", + "required": true, + "description": "备货用时,单位秒(wms_order_b2b.prep_duration_seconds,无作业明细行时为 0)" + }, + { + "name": "prep_at", + "type": "string", + "required": false, + "description": "备货完成时间(wms_order_b2b.prep_at)" + }, + { + "name": "is_picked_up", + "type": "string", + "required": true, + "description": "是否提货:Y=已提货 N=未提货(无作业明细行时为 N)" + }, + { + "name": "picked_up_at", + "type": "string", + "required": false, + "description": "提货时间(wms_order_b2b.picked_up_at)" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "B2B 作业明细创建时间(wms_order_b2b.created_at),与订单自身的 create_at 不同;无作业明细行时为 null" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 作业明细输出口径:列表行按 warehouse_id + order_id 关联 wms_order_b2b 取数(分表 id 按仓库发号,不能只按 order_id 关联);副表已移除 store_id / delivery_order_code / is_print / updated_at / deleted_at 字段,取消 B2B 时物理删除明细行,故列表中的 created_at 为作业明细创建时间,无明细行时为空值占位。", + "B2B 作业明细筛选口径:仅在 order.pendingOrder2b.list / order.deliveryOrder2b.list 开放 total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds / is_picked_up / picked_up_at / created_at / prep_at 作为 where 条件;内部转成 wms_order_b2b(warehouse_id + order_id)子查询取 order_id,再以 id IN (...) 回填,未命中返回空列表,不影响其他订单列表口径。" + ] + } + ] + }, + { + "groupName": "订单配送异常模块", + "module": "order.deliveryExpectionOrder", + "list": [ + { + "method": "order.deliveryExpectionOrder.list", + "description": "配送异常订单列表,使用 dispatch 模型,默认筛选 dispatch_lane=m5。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配);默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + }, + { + "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 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.deliveryExpectionOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "description": "运单信息数组" + }, + { + "name": "waybill_codes", + "type": "array", + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "description": "订单ID 为空或格式错误" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "description": "内部错误" + } + ] + } + ] + }, + { + "groupName": "订单归档模块", + "module": "order.archiveOrder", + "list": [ + { + "method": "order.archiveOrder.list", + "description": "归档订单列表,使用 history 模型。;列表运单号回填强制同仓校验:wms_order_express 按「订单ID + 订单所属仓库ID」隔离读取,禁止仅凭订单ID跨仓串读运单号;默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。", + "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。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配);默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),需要查询 B2B 订单请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + }, + { + "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 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + }, + { + "name": "recheck_status", + "type": "string", + "required": false, + "description": "复核状态:none=未复核,fin=已复核" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "message": "查询失败" + } + ], + "notes": [ + "B2B 排除口径:本接口在模块默认条件之上强制追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不会出现在本列表中;B2B 域请使用 order.pendingOrder2b.list / order.deliveryOrder2b.list。" + ] + }, + { + "method": "order.archiveOrder.detail", + "description": "查询单个订单详情,返回订单头、商品明细和运单信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / id / order_id / orderId", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID;支持 ids 数组、逗号分隔字符串或单个 id/order_id,至少提供一项" + }, + { + "name": "tableType / tablePosition / type / moduleName", + "type": "string", + "required": false, + "source": "body", + "description": "可选,指定订单表类型,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "description": "订单头对象(raw 行数据)" + }, + { + "name": "detail", + "type": "object", + "description": "等同于 order" + }, + { + "name": "orderItems / items", + "type": "array", + "description": "商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "description": "运单信息数组" + }, + { + "name": "waybill_codes", + "type": "array", + "description": "去重后的运单号字符串数组" + } + ], + "errors": [ + { + "code": "400", + "description": "订单ID 为空或格式错误" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + }, + { + "code": "500", + "description": "内部错误" + } + ] + } + ] + }, + { + "groupName": "打印模块", + "module": "order.print", + "list": [ + { + "method": "order.print.getWavePlatformPrintData", + "description": "按波次 IDs 获取平台打印中间态数据,自动过滤快递未完全分配的波次,返回 waveGroups(波次 -> 平台 -> 订单)结构。自定义区首行在快递渠道名后追加「商品总数【n】」(n 优先取订单级商品总数 items_total,其次商品明细数量累加,最后商品种类数 items_count 兜底);当波次 source=0 且 wave_type=1 时,商品明细行尾追加「波次总单数×该行商品数量」。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID(必须与当前用户上下文 store_id 一致)" + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "source": "body", + "description": "波次ID列表(支持数字或字符串,内部自动去重与归一化)" + } + ], + "response": [ + { + "name": "summary", + "type": "object", + "description": "汇总信息", + "children": [ + { + "name": "total_waves", + "type": "number", + "description": "通过过滤的波次总数" + }, + { + "name": "total_orders", + "type": "number", + "description": "所有平台下订单总数" + }, + { + "name": "total_platforms", + "type": "number", + "description": "所有波次内平台分组总数(累加)" + } + ] + }, + { + "name": "wave_ids", + "type": "array", + "description": "通过过滤的波次ID数组" + }, + { + "name": "waveGroups", + "type": "array", + "description": "主返回结构:按波次分组(波次 -> 平台 -> 订单)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "order_count", + "type": "number", + "description": "该波次下订单总数" + }, + { + "name": "platforms", + "type": "array", + "description": "按平台和系统快递分组后的订单列表", + "children": [ + { + "name": "platform", + "type": "string", + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "description": "平台名称" + }, + { + "name": "order_count", + "type": "number", + "description": "该平台+系统快递分组的订单数" + }, + { + "name": "sys_logistics_code", + "type": "string", + "description": "系统快递编码" + }, + { + "name": "sys_logistics_name", + "type": "string", + "description": "系统快递名称" + }, + { + "name": "orders", + "type": "array", + "description": "该分组内的订单列表(逐单中间态,字段同平台层 orders 中元素)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "description": "订单号(delivery_order_code 或 source_order_codes)" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "platform", + "type": "string", + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "description": "平台名称" + }, + { + "name": "waybill_code", + "type": "string", + "description": "运单号" + }, + { + "name": "print_data", + "type": "object", + "description": "打印中间态(详见 printer_data_builder.buildPlatformRequestSkeleton 输出)" + } + ] + } + ] + } + ] + }, + { + "name": "platform_groups", + "type": "array", + "description": "兼容字段:按平台分组结果(保留以兼容旧客户端)", + "children": [ + { + "name": "platform", + "type": "string", + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "description": "平台名称" + }, + { + "name": "order_count", + "type": "number", + "description": "该平台订单数" + }, + { + "name": "orders", + "type": "array", + "description": "逐单中间态(字段同 order_list 元素)" + } + ] + }, + { + "name": "order_list", + "type": "array", + "description": "兼容字段:逐单平台打印中间态明细(保留以兼容旧客户端)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "description": "订单号(delivery_order_code 或 source_order_codes)" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "platform", + "type": "string", + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "description": "平台名称" + }, + { + "name": "waybill_code", + "type": "string", + "description": "运单号" + }, + { + "name": "print_data", + "type": "object", + "description": "打印中间态(详见 printer_data_builder.buildPlatformRequestSkeleton 输出)" + } + ] + }, + { + "name": "ext", + "type": "object", + "description": "扩展字段", + "children": [ + { + "name": "missing_wave_ids", + "type": "array", + "description": "传入但不存在的 wave_id 列表" + }, + { + "name": "filtered_wave_ids", + "type": "array", + "description": "被过滤掉的波次,每项含 wave_id、reason" + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "warehouse_id 或 wave_ids 缺失或格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.print.unlockWavePlatformPrintDataByGroup", + "description": "按分组解锁波次平台打印锁:按传入的 groups 条件匹配已锁定订单并将其 print_lock_status 置为 none,返回解锁统计与解锁订单列表。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID(必须与当前用户上下文 store_id 一致)" + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "source": "body", + "description": "波次ID列表(支持数字或字符串,内部自动去重与归一化)" + }, + { + "name": "group_type", + "type": "string", + "required": false, + "source": "body", + "description": "分组类型,支持 platform、platform_express、order;默认 platform_express" + }, + { + "name": "unlock_scope", + "type": "string", + "required": false, + "source": "body", + "description": "解锁范围,支持 group、wave;默认 group" + }, + { + "name": "groups", + "type": "array", + "required": true, + "source": "body", + "description": "分组条件列表。元素为对象,可包含字段:wave_id(必填)、platform(平台编码)、sys_logistics_code(系统快递编码)、order_ids(订单ID数组)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID(单个规则指定的波次)" + }, + { + "name": "platform", + "type": "string", + "description": "平台编码(当 group_type 为 platform/platform_express 时可能必需)" + }, + { + "name": "sys_logistics_code", + "type": "string", + "description": "系统快递编码(当 group_type 为 platform_express 时可能必需)" + }, + { + "name": "order_ids", + "type": "array", + "description": "订单ID列表(当 group_type 为 order 时必需)" + } + ] + } + ], + "response": [ + { + "name": "summary", + "type": "object", + "required": true, + "description": "解锁操作的汇总统计", + "children": [ + { + "name": "total_waves", + "type": "number", + "description": "有效波次数(通过过滤的波次数)" + }, + { + "name": "total_locked_orders", + "type": "number", + "description": "有效波次中原本被锁定的订单总数" + }, + { + "name": "matched_group_orders", + "type": "number", + "description": "匹配到分组规则的被锁定订单数" + }, + { + "name": "unlocked_count", + "type": "number", + "description": "实际已更新为 unlocked 的订单数量(update 影响数)" + } + ] + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "description": "通过过滤的波次ID数组" + }, + { + "name": "unlocked_order_ids", + "type": "array", + "required": true, + "description": "被解锁的订单ID数组" + }, + { + "name": "unlocked_orders", + "type": "array", + "required": true, + "description": "被解锁订单简要信息列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "order_no", + "type": "string", + "description": "订单号(delivery_order_code 或 source_order_codes)" + } + ] + }, + { + "name": "ext", + "type": "object", + "required": false, + "description": "扩展字段", + "children": [ + { + "name": "missing_wave_ids", + "type": "array", + "description": "传入但不存在的 wave_id 列表" + }, + { + "name": "filtered_wave_ids", + "type": "array", + "description": "被过滤掉的波次(快递未完全分配),每项含 wave_id、wave_no、reason" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "wave_ids 必填,且必须为非空数组", + "description": "wave_ids 必填,且必须为非空数组" + }, + { + "code": "400", + "message": "warehouse_id 必填且必须为正整数", + "description": "warehouse_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "warehouse_id 必须与当前用户上下文 store_id 保持一致", + "description": "warehouse_id 必须与当前用户上下文 store_id 保持一致" + }, + { + "code": "400", + "message": "group_type 仅支持 platform、platform_express、order", + "description": "group_type 仅支持 platform、platform_express、order" + }, + { + "code": "400", + "message": "unlock_scope 仅支持 group、wave", + "description": "unlock_scope 仅支持 group、wave" + }, + { + "code": "400", + "message": "groups 必填,且必须为非空数组", + "description": "groups 必填,且必须为非空数组" + }, + { + "code": "400", + "message": "groups 未匹配到有效的分组解锁条件", + "description": "groups 未匹配到有效的分组解锁条件" + }, + { + "code": "500", + "message": "内部错误", + "description": "内部错误" + } + ] + }, + { + "method": "order.print.getOrderPrintData", + "description": "按订单ID拉取平台打印中间态数据,与 getWavePlatformPrintData 返回结构一致。不限制打印锁定状态,所有订单(包括已锁定)统一返回。仓库ID统一从当前上下文获取,无需调用方传入。自动过滤快递未完全分配的订单(post_status !== 'fin'),返回 waveGroups(波次 -> 平台 -> 订单)结构。自定义区首行在快递渠道名后追加「商品总数【n】」(n 优先取订单级商品总数 items_total,其次商品明细数量累加,最后商品种类数 items_count 兜底);当波次 source=0 且 wave_type=1 时,商品明细行尾追加「波次总单数×该行商品数量」。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids", + "type": "array", + "required": true, + "source": "body", + "description": "订单ID列表(支持数字或字符串,内部自动去重与归一化,必须为非空数组)" + } + ], + "response": [ + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息", + "children": [ + { + "name": "total_waves", + "type": "number", + "required": true, + "description": "通过过滤的波次总数" + }, + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "所有平台下订单总数" + }, + { + "name": "total_platforms", + "type": "number", + "required": true, + "description": "所有波次内平台分组总数(累加)" + } + ] + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "description": "通过过滤的波次ID数组" + }, + { + "name": "waveGroups", + "type": "array", + "required": true, + "description": "主返回结构:按波次分组(波次 -> 平台 -> 订单)", + "children": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该波次下订单总数" + }, + { + "name": "platforms", + "type": "array", + "required": true, + "description": "按平台和系统快递分组后的订单列表", + "children": [ + { + "name": "platform", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": true, + "description": "平台名称" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该平台+系统快递分组的订单数" + }, + { + "name": "sys_logistics_code", + "type": "string", + "required": true, + "description": "系统快递编码" + }, + { + "name": "sys_logistics_name", + "type": "string", + "required": true, + "description": "系统快递名称" + }, + { + "name": "orders", + "type": "array", + "required": true, + "description": "该分组内的订单列表(逐单中间态)", + "children": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "required": true, + "description": "订单号(delivery_order_code 或 source_order_codes)" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "platform", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": true, + "description": "平台名称" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "print_data", + "type": "object", + "required": true, + "description": "打印中间态(详见 printer_data_builder.buildPlatformRequestSkeleton 输出)" + } + ] + } + ] + } + ] + }, + { + "name": "ext", + "type": "object", + "required": true, + "description": "扩展字段", + "children": [ + { + "name": "missing_order_ids", + "type": "array", + "required": true, + "description": "传入但数据库中不存在的 order_id 列表" + }, + { + "name": "filtered_order_ids", + "type": "array", + "required": true, + "description": "被过滤掉的订单(快递未完全分配),每项含 order_id、reason" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "order_ids 必填,且必须为非空数组", + "description": "order_ids 必填,且必须为非空数组" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] + }, + { + "method": "order.print.getPrintDataByWaybillCodes", + "description": "按运单号数组拉取平台打印中间态数据,与 getOrderPrintData 返回结构一致。支持子单号(business_key>1):主面单与现有逻辑一致,子面单使用主订单数据构建打印数据并在自定义区追加「子单号【{business_key}】-{主单号}」行。仓库ID统一从当前上下文获取。自动过滤快递未完全分配的订单(post_status !== 'fin'),返回 waveGroups(波次 -> 平台 -> 订单)结构。自定义区首行在快递渠道名后追加「商品总数【n】」(n 优先取订单级商品总数 items_total,其次商品明细数量累加,最后商品种类数 items_count 兜底);当波次 source=0 且 wave_type=1 时,商品明细行尾追加「波次总单数×该行商品数量」。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_codes", + "type": "array", + "required": true, + "source": "body", + "description": "运单号数组(字符串数组,内部自动去重与归一化,必须为非空数组)" + } + ], + "response": [ + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息", + "children": [ + { + "name": "total_waves", + "type": "number", + "required": true, + "description": "通过过滤的波次总数" + }, + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "所有平台下打印条目总数(每个运单一条)" + }, + { + "name": "total_platforms", + "type": "number", + "required": true, + "description": "所有波次内平台分组总数(累加)" + } + ] + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "description": "通过过滤的波次ID数组" + }, + { + "name": "waveGroups", + "type": "array", + "required": true, + "description": "波次分组(波次 -> 平台 -> 订单),结构与 getOrderPrintData 一致", + "children": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该波次下打印条目数" + }, + { + "name": "platforms", + "type": "array", + "required": true, + "description": "平台分组列表", + "children": [ + { + "name": "platform", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": true, + "description": "平台名称" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该平台下打印条目数" + }, + { + "name": "order_ids", + "type": "array", + "required": true, + "description": "订单ID数组(去重)" + }, + { + "name": "orders", + "type": "array", + "required": true, + "description": "打印数据文档数组(print_data)" + } + ] + } + ] + }, + { + "name": "ext", + "type": "object", + "required": true, + "description": "扩展信息", + "children": [ + { + "name": "missing_waybill_codes", + "type": "array", + "required": true, + "description": "未匹配到的运单号" + }, + { + "name": "filtered_waybill_codes", + "type": "array", + "required": true, + "description": "被过滤掉的运单号及其原因,每项含 waybill_code、reason" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "waybill_codes 必填,且必须为非空数组", + "description": "waybill_codes 必填,且必须为非空数组" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] + } + ] + }, + { + "groupName": "打印模块", + "module": "print", + "list": [ + { + "method": "print.send", + "description": "发送打印任务到打印电脑,并记录打印单。说明:当 type=express 时,接口按 data.waveGroups(来源于 order.print.getWavePlatformPrintData 返回的 data.waveGroups)进行处理,按 waveGroups -> platforms 串行处理,每个平台+快递 组分别发送;返回沿用现有简要风格,不返回明细。接口在记录打印单的同时,也会写入订单操作日志(记录打印相关操作)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "computerId", + "type": "string", + "required": false, + "source": "body", + "description": "打印电脑 ID;历史/customize 分支可能使用。注意:type=express 场景下不适用(该字段不再作为 express 路径的必填或传输约束)。" + }, + { + "name": "count", + "type": "number", + "required": false, + "source": "body", + "description": "打印份数;对 type=customize 有效。type=express 场景下不保留,相应字段会被忽略。" + }, + { + "name": "data", + "type": "object", + "required": true, + "source": "body", + "description": "打印业务数据对象。对于 type=express:必须提供 data.waveGroups(来源于 order.print.getWavePlatformPrintData 的返回值 data.waveGroups),接口按 waveGroups->platforms 串行处理,每个 平台+快递 组分别发送;对于 type=customize,data 的具体字段由模板决定。" + }, + { + "name": "printer", + "type": "string", + "required": false, + "source": "body", + "description": "打印机名称;type=customize 使用。type=express 下忽略(由快递平台/站点决定打印目标)。" + }, + { + "name": "template", + "type": "object", + "required": false, + "source": "body", + "description": "打印模板对象;仅 type=customize 时必填且应包含 page_width、page_height、template_content。type=express 场景下忽略 template 字段。", + "children": [ + { + "name": "page_width", + "type": "number", + "required": true, + "description": "页面宽度(mm)" + }, + { + "name": "page_height", + "type": "number", + "required": true, + "description": "页面高度(mm)" + }, + { + "name": "template_content", + "type": "array", + "required": false, + "description": "模板内容数组" + } + ] + }, + { + "name": "timestamp", + "type": "string", + "required": false, + "source": "body", + "description": "业务时间戳;历史字段。type=express 场景下不适用。" + }, + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "打印类型;支持 customize、express。对于 express 场景,必须遵守下列额外约束:提供 printStationId、requestCode,并在 data.waveGroups 中传入来自 order.print.getWavePlatformPrintData 的 waveGroups 数据。" + }, + { + "name": "printStationId", + "type": "string", + "required": true, + "source": "body", + "description": "打印站点/工作站标识(必填,type=express 时必须提供),用于指示目标打印站或分发单元。" + }, + { + "name": "requestCode", + "type": "string", + "required": true, + "source": "body", + "description": "请求去重/防重放 ID(必填,type=express 时必须提供)。接口约束:requestCode 在约定周期内不得变更(例如一次批次/会话期间),系统在同一次请求处理范围内保证对重复 requestCode 进行防重放处理;此保护仅保证同一次请求内的去重/防重放,不等同于跨请求的强幂等保证。" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": false, + "description": "全局调用结果标识,成功时为 success,失败时为 failure" + }, + { + "name": "code", + "type": "number", + "required": false, + "description": "业务状态码;成功时为 200,失败时通常为 1001 或 504" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "返回信息" + }, + { + "name": "printId", + "type": "number", + "required": false, + "description": "打印记录 ID;任务入库成功后返回,失败时若已生成记录也会返回。接口在 express 场景下不返回明细结果,只给出调用结果摘要。" + } + ], + "errors": [ + { + "code": 1001, + "message": "不支持的打印类型" + }, + { + "code": 504, + "message": "打印任务发送失败(如打印机不存在、打印机脱机、打印服务通讯失败)" + } + ] + }, + { + "method": "print.getPrintResult", + "description": "print.getPrintResult 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "printId", + "type": "string", + "required": true, + "source": "body", + "description": "printId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getPrintRecordItem", + "description": "print.getPrintRecordItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getList", + "description": "查询当前仓库下的打印台列表,支持分页与 where 条件筛选(支持字段:id、name、computer_id、custom_barcode)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象;支持字段:id(等值)、name、computer_id、custom_barcode;推荐使用 { operator, value, type } 标准结构" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "返回数据对象,包含 list 与 pagination", + "children": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "打印台列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "打印台 ID" + }, + { + "name": "name", + "type": "string", + "description": "打印台名称" + }, + { + "name": "computer_id", + "type": "number", + "description": "关联打印电脑 ID" + }, + { + "name": "custom_barcode", + "type": "string", + "description": "自定义条码" + }, + { + "name": "default_printer_name", + "type": "string", + "description": "默认打印机名称" + }, + { + "name": "subject_config", + "type": "object", + "description": "打印台的 subject_config 配置" + }, + { + "name": "is_online", + "type": "number", + "description": "打印电脑在线状态,1=在线,0=离线" + }, + { + "name": "components", + "type": "array", + "description": "电脑组件在线信息,数组项包含 name/is_online", + "children": [ + { + "name": "name", + "type": "string", + "description": "组件名称" + }, + { + "name": "is_online", + "type": "number", + "description": "组件是否在线,1/0" + } + ] + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,包含 page、pageSize、total、totalPages、hasPrevious、hasNext" + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或 where 中包含非法字段" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, + { + "method": "print.getItem", + "description": "查询单个打印台详情,返回打印台对象(raw 行记录,含 subject_config)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "打印台 ID,必填" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "打印台原始记录(PrintStation raw),字段示例", + "children": [ + { + "name": "id", + "type": "number", + "description": "打印台 ID" + }, + { + "name": "name", + "type": "string", + "description": "打印台名称" + }, + { + "name": "computer_id", + "type": "number", + "description": "关联打印电脑 ID" + }, + { + "name": "custom_barcode", + "type": "string", + "description": "自定义条码" + }, + { + "name": "default_printer_name", + "type": "string", + "description": "默认打印机名称" + }, + { + "name": "subject_config", + "type": "object", + "description": "打印台 subject_config 配置(见下文)" + }, + { + "name": "create_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "update_at", + "type": "string", + "description": "更新时间" + }, + { + "name": "deleted", + "type": "number", + "description": "软删除标识,1=已删除" + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误:缺少 id 或 id 格式不正确" + }, + { + "code": "404", + "description": "打印台不存在" + }, + { + "code": "500", + "description": "内部错误" + } + ] + }, + { + "method": "print.add", + "description": "新增打印台:关联打印电脑并可保存 subject_config(会由模型 normalizeSubjectConfig 校验)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "computer_id", + "type": "number", + "required": true, + "source": "body", + "description": "关联的打印电脑 ID(必填)" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "打印台名称(必填)" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "自定义条码" + }, + { + "name": "default_printer_name", + "type": "string", + "required": false, + "source": "body", + "description": "默认打印机名称" + }, + { + "name": "subject_config", + "type": "object", + "required": false, + "source": "body", + "description": "打印台的主题/业务配置(可选,若存在将调用模型 normalizeSubjectConfig 进行校验)", + "children": [ + { + "name": "express_bind_printer", + "type": "array", + "description": "快递与打印机绑定数组,数组项仅包含 { express_code, printer_name }", + "children": [ + { + "name": "express_code", + "type": "string", + "required": true, + "description": "快递编码,必填" + }, + { + "name": "printer_name", + "type": "string", + "required": true, + "description": "打印机名称,必填" + } + ] + } + ] + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "新建的打印台对象(raw)" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误:缺少必填字段(computer_id/name)或 subject_config 格式不合法" + }, + { + "code": "500", + "description": "创建失败或内部错误" + } + ] + }, + { + "method": "print.hasName", + "description": "print.hasName 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.updateItem", + "description": "更新打印台信息:支持更新 name、computer_id、custom_barcode、default_printer_name 以及 subject_config(会走 normalizeSubjectConfig)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "打印台 ID(必填)" + }, + { + "name": "computer_id", + "type": "number", + "required": false, + "source": "body", + "description": "要更新的打印电脑 ID" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "自定义条码" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "打印台名称" + }, + { + "name": "default_printer_name", + "type": "string", + "required": false, + "source": "body", + "description": "默认打印机名称" + }, + { + "name": "subject_config", + "type": "object", + "required": false, + "source": "body", + "description": "subject_config(可选),传入将替换/规范化配置", + "children": [ + { + "name": "express_bind_printer", + "type": "array", + "description": "快递-打印机绑定数组,数组项仅包含 { express_code, printer_name }", + "children": [ + { + "name": "express_code", + "type": "string", + "required": true, + "description": "快递编码,必填" + }, + { + "name": "printer_name", + "type": "string", + "required": true, + "description": "打印机名称,必填" + } + ] + } + ] + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": false, + "description": "更新结果,通常返回 null" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误(缺少 id 或 subject_config 格式不合法)" + }, + { + "code": "404", + "description": "打印台不存在" + }, + { + "code": "500", + "description": "更新失败或内部错误" + } + ] + }, + { + "method": "print.del", + "description": "批量删除(软删除)打印台:将指定 ids 的记录标记为 deleted=1。", + "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 数组,必须为非空数组(示例: [1,2,3])" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": false, + "description": "返回空数据结构,表示操作成功" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误:ids 必须为非空数组" + }, + { + "code": "500", + "description": "删除失败或内部错误" + } + ] + }, + { + "method": "print.getComputer", + "description": "查询当前仓库下状态为 1 的打印电脑列表(raw 列表)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "data", + "type": "array", + "required": true, + "description": "打印电脑数组,每项为打印电脑的原始记录", + "children": [ + { + "name": "id", + "type": "number", + "description": "打印电脑 ID" + }, + { + "name": "name", + "type": "string", + "description": "打印电脑名称或标识" + }, + { + "name": "status", + "type": "number", + "description": "状态,1=启用" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库 ID" + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, + { + "method": "print.getComputerPrinter", + "description": "获取指定打印电脑的打印机列表(从 redis: printer:{id}:printerList 读取并返回 data 数组,通常为打印机名称数组或对象数组)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "打印电脑 ID,必填" + } + ], + "response": [ + { + "name": "data", + "type": "array", + "required": true, + "description": "打印机数组,通常为字符串名称数组或打印机对象数组(取决于 redis 存储格式)" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误:缺少 id" + }, + { + "code": "500", + "description": "读取 Redis 或解析数据失败" + } + ] + }, + { + "method": "print.savePrinters", + "description": "保存 default_printer_name 与 subject_config.express_bind_printer。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "defaultPrinter", + "type": "string", + "required": true, + "source": "body", + "description": "默认打印机名称(必填),会写入打印台的 `default_printer_name` 字段" + }, + { + "name": "express", + "type": "array", + "required": true, + "source": "body", + "description": "快递与打印机绑定数组(必填)。每项应包含首选字段 `express_code`(string)和 `printer_name`(string)。为兼容历史字段,也接受 `express_id`(可映射为 `express_code`)和 `name`(可映射为 `printer_name`)。接口实现会将结果序列化后写入打印台的 `subject_config.express_bind_printer`。", + "children": [ + { + "name": "express_code", + "type": "string", + "required": false, + "description": "首选:快递编码(string),实现中优先使用该字段" + }, + { + "name": "printer_name", + "type": "string", + "required": false, + "description": "首选:打印机名称(string),实现中优先使用该字段" + }, + { + "name": "express_id", + "type": "number|string", + "required": false, + "description": "兼容字段:历史的 express_id,可映射为 express_code 使用" + }, + { + "name": "name", + "type": "string", + "required": false, + "description": "兼容字段:历史的 name,可映射为 printer_name 使用" + } + ] + }, + { + "name": "print_station_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标打印台 ID(必填)。接口会根据此 ID 更新对应打印台记录的 default_printer_name 与 subject_config.express_bind_printer" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": false, + "description": "成功不返回业务数据,语义为成功(实现中返回 { data: null, code: 0 })" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误:defaultPrinter/express/print_station_id 格式或缺失" + }, + { + "code": "404", + "description": "打印台不存在:未找到对应 print_station_id 的打印台记录" + }, + { + "code": "500", + "description": "保存失败或内部错误" + } + ] + }, + { + "method": "print.notifyLock", + "description": "仅执行订单锁定流程,不发送打印任务;记录打印任务日志并写入订单操作日志。兼容别名:print.notify_lock(等价转调)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids", + "type": "array", + "required": false, + "source": "body", + "description": "订单 ID 数组(与 orderIds 互为别名)。至少需提供 order_ids/orderIds/waveGroups/data.waveGroups 中的一类以提取订单 ID。", + "children": [ + { + "name": "id", + "type": "number", + "description": "订单 ID" + } + ] + }, + { + "name": "orderIds", + "type": "array", + "required": false, + "source": "body", + "description": "订单 ID 数组(驼峰兼容,等同于 order_ids)。", + "children": [ + { + "name": "id", + "type": "number", + "description": "订单 ID" + } + ] + }, + { + "name": "waveGroups", + "type": "array", + "required": false, + "source": "body", + "description": "波次分组结构(可从中提取订单 ID,参考 order.print.getWavePlatformPrintData 返回的 waveGroups)。", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次 ID" + } + ] + }, + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "兼容包装对象;若传入 data.waveGroups,可从中提取订单 ID。", + "children": [ + { + "name": "waveGroups", + "type": "array", + "required": false, + "description": "同上,来自 order.print.getWavePlatformPrintData 的 data.waveGroups 结构。" + } + ] + } + ], + "response": [ + { + "name": "locked_count", + "type": "number", + "required": false, + "description": "成功锁定的订单数量" + }, + { + "name": "order_ids_count", + "type": "number", + "required": false, + "description": "请求中识别出的订单 ID 数量" + }, + { + "name": "order_ids", + "type": "array", + "required": false, + "description": "本次尝试锁定的订单 ID 列表" + }, + { + "name": "source", + "type": "string", + "required": false, + "description": "操作来源标识(可选,若后端返回则提供具体来源)" + } + ], + "errors": [ + { + "code": 400, + "message": "无有效订单ID(order_ids/orderIds/waveGroups/data.waveGroups 均未提供或均无有效订单)" + }, + { + "code": 500, + "message": "订单锁定失败" + } + ] + }, + { + "method": "print.notify_lock", + "description": "兼容别名(等价转调到 print.notifyLock);建议使用 print.notifyLock。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "print.markWavePrintStatus", + "description": "标记/取消标记整个波次订单的打印状态。仓库隔离:从登录上下文获取仓库ID。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "source": "body", + "description": "波次ID(必填,正整数)" + }, + { + "name": "status", + "type": "string", + "required": false, + "source": "body", + "description": "目标状态:printed=标记已打印,unprinted=取消已打印标记。默认 printed。" + } + ], + "response": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "status", + "type": "string", + "description": "目标状态" + }, + { + "name": "print_status", + "type": "string", + "description": "订单表 print_status 字段值(fin / none)" + }, + { + "name": "total_orders", + "type": "number", + "description": "波次下总订单数" + }, + { + "name": "affected_orders", + "type": "number", + "description": "实际更新的订单数" + }, + { + "name": "order_ids", + "type": "array", + "description": "波次下所有订单ID" + } + ], + "errors": [ + { + "code": 400, + "message": "wave_id 参数必填,且必须为正整数" + }, + { + "code": 400, + "message": "status 参数不合法,仅支持 printed / unprinted" + }, + { + "code": 400, + "message": "无法获取当前仓库ID,请确认已登录" + }, + { + "code": 404, + "message": "波次在当前仓库下没有可操作的订单" + }, + { + "code": 500, + "message": "内部错误(OrderDeliveryFactory/OrderDeliveryModel 不可用或更新失败)" + } + ] + }, + { + "method": "print.confirmWavePrint", + "description": "波次确认打印:扫描波次内任一订单的面单号,将波次下全部已打印(print_status='fin')且非拦截的订单批量标记 confirm_print_status='fin',记录打印完成后真实扫描面单确认。拦截订单跳过(不确认、不阻断);波次下存在未打印订单(print_status != 'fin')时阻断;全部已确认时重复扫描返回 already_confirmed,不重复写日志。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_no", + "type": "string", + "required": true, + "source": "body", + "description": "面单号/运单号(必填,用于定位订单及所属波次)" + } + ], + "response": [ + { + "name": "waybill_no", + "type": "string", + "required": false, + "description": "扫描的面单号" + }, + { + "name": "matched_order_id", + "type": "number", + "required": false, + "description": "面单号匹配到的订单ID" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "波次编码" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "波次下总订单数" + }, + { + "name": "intercepted_order_count", + "type": "number", + "required": false, + "description": "波次下拦截订单数(跳过确认)" + }, + { + "name": "confirmed_order_count", + "type": "number", + "required": false, + "description": "已确认打印订单数(confirm_print_status='fin')" + }, + { + "name": "newly_confirmed_order_count", + "type": "number", + "required": false, + "description": "本次新增确认订单数(仅 status=confirmed 时返回)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "确认结果:confirmed=本次完成确认 / already_confirmed=已全部确认" + } + ], + "errors": [ + { + "code": 400, + "message": "waybill_no 必填(面单号/运单号)" + }, + { + "code": 400, + "message": "缺少当前用户仓库上下文 store_id" + }, + { + "code": 400, + "message": "运单对应订单未分配波次" + }, + { + "code": 400, + "message": "波次存在未打印订单,禁止确认打印(返回 unprinted_order_count)" + }, + { + "code": 404, + "message": "未查询到该面单号对应的订单,无记录" + }, + { + "code": 500, + "message": "内部错误(OrderDeliveryFactory/订单模型不可用或更新失败)" + } + ] + } + ] + }, + { + "groupName": "打印机站点模块", + "module": "printer.station", + "list": [ + { + "method": "printer.station.list", + "description": "获取打印站点列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印模板模块", + "module": "setting.printTemplate", + "list": [ + { + "method": "setting.printTemplate.list", + "description": "获取打印模板树", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.printTemplate.save", + "description": "保存打印模板", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.printTemplate.create", + "description": "创建打印模板(platform 固定为 default,template_type 固定为 CUSTOM,template_url 固定为空字符串)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "template_name", + "type": "string", + "required": true, + "source": "body", + "description": "模板名称" + }, + { + "name": "business_type", + "type": "string", + "required": true, + "source": "body", + "description": "业务类型" + }, + { + "name": "page_width", + "type": "number", + "required": true, + "source": "body", + "description": "页面宽度(mm)" + }, + { + "name": "page_height", + "type": "number", + "required": true, + "source": "body", + "description": "页面高度(mm)" + }, + { + "name": "template_content", + "type": "array", + "required": false, + "source": "body", + "description": "模板内容,可省略;省略时默认创建空模板内容" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建模板ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误(缺少 template_name、business_type、page_width 或 page_height)" + }, + { + "code": "409", + "description": "同一业务类型和平台下已存在自定义模板" + } + ] + }, + { + "method": "setting.printTemplate.delete", + "description": "删除打印模板(软删除)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "模板ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "删除的模板ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误(缺少 id)" + }, + { + "code": "404", + "description": "模板不存在或无权限" + } + ] + }, + { + "method": "setting.printTemplate.listTemplatesByType", + "description": "按业务类型查询模板", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "businessType", + "type": "string", + "required": true, + "source": "body", + "description": "businessType 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "仓库设置模块", + "module": "setting.warehouse", + "list": [ + { + "method": "setting.warehouse.getSettings", + "description": "获取当前登录仓库的 subject_config;subject_config 新增大团购打包系数 big_group_pack_coefficient(数字,默认 3,单位秒/单,必须大于 0,用于 workbench 大团购波次打包时长闸门与倒计时);新增散单称重是否需要打包 single_weigh_require_pack(flag 布尔,默认 false 关闭;开启后散单称重(订单波次范围 wave_scope 非 1 大团购/3 小团购)须处于打包中或已打包(pack_status=padding/fin),未打包或打包异常时拒绝称重并返回错误);本次调整自动出库配置:新增 subject_config.auto_outbound_enabled(flag,默认 false 关闭);subject_config.auto_outbound_rules 由对象改为数组(每项仅校验 require_pack/require_weigh/require_sync,任一规则命中即出库;固定前置条件为已复核 recheck_status=fin 与已分配储位 storage_status=fin),移除 rules.enabled 与 require_recheck/require_print/require_pick 字段;本次文档补充「不出库当天订单」的时间口径:时间字段范围 00:00~23:59(不支持 24:00),常用组合为 允许当天出库最后时间=00:00 + 当天放开时间=23:59 表示「当天复核的订单全天不出库、过了零点后全部出库」;本次补充「不出库当天订单」的跨天口径:按订单复核时间所在日计算,放行时间支持 00:00~47:59(27:00 = 次日 03:00 放行)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID" + }, + { + "name": "subject_config", + "type": "object", + "required": true, + "description": "仓库的 subject_config 配置对象" + }, + { + "name": "subject_config.enable_external_express_code", + "type": "boolean", + "required": true, + "description": "是否启用外部快递编码;默认 false(关闭)。开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)" + }, + { + "name": "subject_config.auto_outbound_enabled", + "type": "boolean", + "required": true, + "description": "是否启用自动出库(flag),默认 false(关闭);开启后按 auto_outbound_rules 中的规则扫描订单并自动标记出库" + }, + { + "name": "subject_config.auto_outbound_rules", + "type": "array", + "required": true, + "description": "自动出库规则数组,每项规则独立判断,订单满足任意一条规则即自动出库;空数组时不自动出库。所有规则的固定前置条件为「已复核」(recheck_status=fin)与「已分配储位」(storage_status=fin),未复核订单一律不自动出库。旧版本的对象结构(含 enabled/require_recheck/require_print/require_pick)已废弃不再兼容,保存为非数组时返回 400" + }, + { + "name": "subject_config.auto_outbound_rules.require_pack", + "type": "boolean", + "required": true, + "description": "是否要求已打包(pack_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_weigh", + "type": "boolean", + "required": true, + "description": "是否要求已称重(wms_order_express.weighing_weight>0),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_sync", + "type": "boolean", + "required": true, + "description": "是否要求已同步(sync_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.exclude_same_day_outbound", + "type": "boolean", + "required": true, + "description": "是否不出库当天复核订单(flag),默认 true;开启后按订单复核时间所在日计算:复核时间在「允许当天出库最后时间」之后的订单,需等到该复核日的「放行时间」才自动出库;复核时间早于该最后时间、或为空的订单不受影响" + }, + { + "name": "subject_config.auto_outbound_rules.same_day_outbound_deadline_time", + "type": "string", + "required": true, + "description": "允许当天出库最后时间(HH:mm,默认 06:00,当天内 00:00~23:59);复核时间早于该时间的订单不受「不出库当天订单」影响,不能大于放行时间。想表达「当天复核的订单全天不出库」时设为 00:00" + }, + { + "name": "subject_config.auto_outbound_rules.same_day_outbound_release_time", + "type": "string", + "required": true, + "description": "放行时间(HH:mm,默认 22:00,支持跨天 00:00~47:59:24:00 之后的数字表示次日,如 27:00 = 次日 03:00);到达该时刻后,该复核日被限制的订单放行。常用:23:59 = 当天不放、过了零点出库;27:00 = 到次日 03:00 才出库" + }, + { + "name": "subject_config.sender_name", + "type": "string", + "required": false, + "description": "仓库默认发件人姓名,默认空字符串" + }, + { + "name": "subject_config.sender_tel", + "type": "string", + "required": false, + "description": "仓库默认发件人联系电话,默认空字符串" + }, + { + "name": "subject_config.province_name", + "type": "string", + "required": false, + "description": "仓库默认发件省份,默认空字符串" + }, + { + "name": "subject_config.city_name", + "type": "string", + "required": false, + "description": "仓库默认发件城市,默认空字符串" + }, + { + "name": "subject_config.district_name", + "type": "string", + "required": false, + "description": "仓库默认发件区/县,默认空字符串" + }, + { + "name": "subject_config.town_name", + "type": "string", + "required": false, + "description": "仓库默认发件镇/街道,默认空字符串" + }, + { + "name": "subject_config.address", + "type": "string", + "required": false, + "description": "仓库默认发件详细地址,默认空字符串" + }, + { + "name": "subject_config.receiver_address", + "type": "string", + "required": false, + "description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串" + }, + { + "name": "subject_config.single_order_pack_max_minutes", + "type": "number", + "required": false, + "description": "散单打包最大时长,单位:分钟,默认 3" + }, + { + "name": "subject_config.group_order_pack_max_minutes", + "type": "number", + "required": false, + "description": "团购打包最大时长,单位:分钟,默认 40" + }, + { + "name": "subject_config.big_group_pack_coefficient", + "type": "number", + "required": false, + "description": "大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0" + }, + { + "name": "subject_config.single_weigh_require_pack", + "type": "boolean", + "required": false, + "description": "散单称重是否需要打包(flag,默认 false 关闭):开启后散单称重(订单波次范围 wave_scope 非 1 大团购/3 小团购)须处于打包中或已打包(pack_status=padding/fin);未打包或打包异常时拒绝称重并返回错误" + }, + { + "name": "subject_config.return_unpack_max_record_minutes", + "type": "number", + "required": false, + "description": "拆包最大录制时长,单位:分钟,默认 5,min 1;超过上限时拆包提交的结束时间自动截断为开始时间+上限" + }, + { + "name": "subject_config.default_location_id", + "type": "number", + "required": false, + "description": "默认库位(库位ID,未配置时为 null)" + }, + { + "name": "subject_config.cutoff_order_enabled", + "type": "number", + "required": false, + "description": "启用截单(flag:0=关闭,1=开启;默认 1)。启用后订单创建时间早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),不再自动分配快递和储位、不再自动加团" + }, + { + "name": "subject_config.allocate_start_time", + "type": "string", + "required": false, + "description": "开始自动分配时间,格式 HH:mm,默认 08:00,范围 00:00-23:59;作为自动分配初始时间,当前时间早于该时间与超过截单时间行为一致(不自动分配快递和储位、不自动加团)" + }, + { + "name": "subject_config.cutoff_order_time", + "type": "string", + "required": false, + "description": "截单时间,格式 HH:mm,默认 18:00,范围 00:00-23:59;作为最后允许自动分配的时间,开始时间晚于截单时间时截单时间视为次日(跨天窗口)" + }, + { + "name": "subject_config.day_start_time", + "type": "string", + "required": false, + "description": "自然日开始时间(业务日分界点),格式 HH:mm,默认 06:00,范围 00:00-23:59;今日统计窗口为 [该时间点, 次日该时间点),当前时间早于今日该时间点时窗口从昨日该时间点开始(昨日 06:00 后的订单视为今日)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice", + "type": "object", + "required": false, + "description": "收货未入库提醒配置。开启后每天按提醒时间(notice_time)扫描「创建时间超过 min_hours 且不足 max_hours 仍未完成入库」的收货单:绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.enabled", + "type": "boolean", + "required": false, + "description": "是否通知收货未入库(flag:0=关闭,1=开启;默认 0 关闭)。开启后收货未入库提醒定时任务才会在提醒时间执行" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.notice_time", + "type": "string", + "required": false, + "description": "提醒时间,格式 HH:mm,默认 08:30,范围 00:00-23:59;定时任务按此时间(含 10 分钟宽限)每天提醒一次" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.min_hours", + "type": "number", + "required": false, + "description": "超时下限(小时):收货单创建时间距今超过该值才提醒,默认 24,须为大于 0 的整数" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.max_hours", + "type": "number", + "required": false, + "description": "超时上限(小时):收货单创建时间距今小于该值才提醒(超过则不再提醒),默认 48,须为大于 min_hours 的整数" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.notice_template", + "type": "string", + "required": false, + "description": "通知短语(消息第一行,仓库/客服群)。支持变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名(未绑定为「未绑定货主」)/ {store_id} 货主ID / {count} 本批单数 / {min_hours} 超时下限 / {max_hours} 超时上限 / {date} 提醒日期(YYYY-MM-DD)/ {numbers} 本批收货单号。未识别的占位符原样保留;短语后换行逐行列出明细(一行一条,最多 20 行),留空使用默认短语" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.store_notice_template", + "type": "string", + "required": false, + "description": "通知短语(消息第一行,货主群)。变量同 notice_template,留空使用默认短语" + }, + { + "name": "subject_config.inbox_push_retry", + "type": "object", + "required": false, + "description": "站内信推送失败自动重发配置(同「收货未入库提醒」的嵌套结构):开启后站内信回信/系统通知推送失败(如桥接离线返回 wx offline / qiwe offline)由定时任务每 3 分钟自动重发一次" + }, + { + "name": "subject_config.inbox_push_retry.enabled", + "type": "number", + "required": false, + "description": "是否开启站内信推送失败自动重发(flag:0=关闭,1=开启;默认 0=关闭,需显式开启)" + }, + { + "name": "subject_config.inbox_push_retry.window_minutes", + "type": "number", + "required": false, + "description": "重发时间范围(分钟,1-1440,默认 30):仅自动重发「失败时间在该范围内」的消息,超出范围不再补发;仅在 enabled 开启时生效" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库" + }, + { + "code": "404", + "message": "仓库不存在" + }, + { + "code": "500", + "message": "获取失败" + } + ] + }, + { + "method": "setting.warehouse.getFieldMeta", + "description": "获取仓库设置字段元信息;本次 list 新增「大团购打包系数」(key=big_group_pack_coefficient,type=number,default=3,min=0.1,单位秒/单,用于大团购波次打包时长闸门与倒计时);本次新增「散单称重是否需要打包」(key=single_weigh_require_pack,type=flag,default=false,required=false,开启后散单称重(wave_scope 非 1 大团购/3 小团购)须处于打包中或已打包(pack_status=padding/fin));本次新增「启用自动出库」(key=auto_outbound_enabled,type=flag,default=false,required=false);「自动出库规则」(key=auto_outbound_rules)由 object 调整为 array(default=[],item_keys 仅含 require_pack/require_weigh/require_sync/exclude_same_day_outbound/same_day_outbound_deadline_time/same_day_outbound_release_time)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "list", + "type": "array", + "description": "字段元信息数组", + "children": [ + { + "name": "key", + "type": "string", + "description": "字段 key" + }, + { + "name": "name", + "type": "string", + "description": "字段名称" + }, + { + "name": "type", + "type": "string", + "description": "字段类型" + }, + { + "name": "default", + "type": "any", + "description": "默认值(按字段类型返回)" + }, + { + "name": "required", + "type": "boolean", + "description": "是否必填" + }, + { + "name": "description", + "type": "string", + "description": "字段描述" + }, + { + "name": "options", + "type": "array", + "description": "可选项(仅当 type 为 select/enum 时返回)" + }, + { + "name": "min", + "type": "number", + "description": "数值型最小值(可选)" + }, + { + "name": "max", + "type": "number", + "description": "数值型最大值(可选)" + }, + { + "name": "maxLength", + "type": "number", + "description": "字符串最大长度(可选)" + } + ], + "required": true + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "500", + "message": "获取仓库设置字段信息失败" + } + ] + }, + { + "method": "setting.warehouse.saveSettings", + "description": "修改仓库设置并清理指定仓库缓存(subject_config 支持部分字段更新,本次新增 subject_config.single_weigh_require_pack);本次文档补漏 subject_config.big_group_pack_coefficient 入参说明(对齐 getSettings/getFieldMeta 与代码实现);本次调整自动出库配置:新增 subject_config.auto_outbound_enabled(flag,默认 false);subject_config.auto_outbound_rules 改为数组(每项仅校验 require_pack/require_weigh/require_sync,任一命中即出库;固定前置条件为已复核 + 已分配储位),非数组(旧对象结构)保存时返回 400;本次文档补充 same_day_outbound_deadline_time / same_day_outbound_release_time 的范围(00:00~23:59,不支持 24:00)与常用组合(00:00 + 23:59 = 当天不放、过零点全部出库);本次补充 same_day_outbound_release_time 支持跨天(00:00~47:59,27:00 = 次日 03:00)与 same_day_outbound_deadline_time 仍限当天内(00:00~23:59)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subject_config", + "type": "object", + "required": true, + "source": "body", + "description": "仓库的 subject_config 对象" + }, + { + "name": "cache_warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "需清理缓存的仓库 ID(下划线命名兼容)" + }, + { + "name": "cacheWarehouseId", + "type": "number", + "required": false, + "source": "body", + "description": "需清理缓存的仓库 ID(驼峰命名兼容)" + }, + { + "name": "subject_config.enable_external_express_code", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否启用外部快递编码;默认 false(关闭)。开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)" + }, + { + "name": "subject_config.auto_outbound_enabled", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否启用自动出库(flag),默认 false(关闭);开启后按 auto_outbound_rules 中的规则扫描订单并自动标记出库" + }, + { + "name": "subject_config.auto_outbound_rules", + "type": "array", + "required": false, + "source": "body.subject_config", + "description": "自动出库规则数组,每项规则独立判断,订单满足任意一条规则即自动出库;空数组时不自动出库。所有规则的固定前置条件为「已复核」(recheck_status=fin)与「已分配储位」(storage_status=fin),未复核订单一律不自动出库。旧版本的对象结构(含 enabled/require_recheck/require_print/require_pick)已废弃不再兼容,保存为非数组时返回 400" + }, + { + "name": "subject_config.auto_outbound_rules.require_pack", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否要求已打包(pack_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_weigh", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否要求已称重(wms_order_express.weighing_weight>0),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.require_sync", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否要求已同步(sync_status=fin),默认 true" + }, + { + "name": "subject_config.auto_outbound_rules.exclude_same_day_outbound", + "type": "boolean", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "是否不出库当天复核订单(flag),默认 true;开启后按订单复核时间所在日计算:复核时间在「允许当天出库最后时间」之后的订单,需等到该复核日的「放行时间」才自动出库;复核时间早于该最后时间、或为空的订单不受影响" + }, + { + "name": "subject_config.auto_outbound_rules.same_day_outbound_deadline_time", + "type": "string", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "允许当天出库最后时间(HH:mm,默认 06:00,当天内 00:00~23:59);复核时间早于该时间的订单不受「不出库当天订单」影响,不能大于放行时间。想表达「当天复核的订单全天不出库」时设为 00:00" + }, + { + "name": "subject_config.auto_outbound_rules.same_day_outbound_release_time", + "type": "string", + "required": false, + "source": "body.subject_config.auto_outbound_rules", + "description": "放行时间(HH:mm,默认 22:00,支持跨天 00:00~47:59:24:00 之后的数字表示次日,如 27:00 = 次日 03:00);到达该时刻后,该复核日被限制的订单放行。常用:23:59 = 当天不放、过了零点出库;27:00 = 到次日 03:00 才出库" + }, + { + "name": "subject_config.sender_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件人姓名,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.sender_tel", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件人联系电话,默认空字符串,最大长度 20" + }, + { + "name": "subject_config.province_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件省份,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.city_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件城市,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.district_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件区/县,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.town_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件镇/街道,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.address", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件详细地址,默认空字符串,最大长度 200" + }, + { + "name": "subject_config.receiver_address", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串,最大长度 500" + }, + { + "name": "subject_config.single_order_pack_max_minutes", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "散单打包最大时长,单位:分钟,默认 3,须为大于 0 的整数" + }, + { + "name": "subject_config.group_order_pack_max_minutes", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "团购打包最大时长,单位:分钟,默认 40,须为大于 0 的整数" + }, + { + "name": "subject_config.big_group_pack_coefficient", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0;非法值报 400:subject_config.big_group_pack_coefficient 必须是大于 0 的数字" + }, + { + "name": "subject_config.single_weigh_require_pack", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "散单称重是否需要打包(flag,默认 false 关闭):开启后散单称重(wave_scope 非 1 大团购/3 小团购)须处于打包中或已打包(pack_status=padding/fin)。仅接受布尔/like-flag(true/1/'1'/'true' → true;false/0/'0'/'false' → false),非法值报 400:subject_config.single_weigh_require_pack 必须是布尔值" + }, + { + "name": "subject_config.return_unpack_max_record_minutes", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "拆包最大录制时长,单位:分钟,默认 5,min 1,须为大于 0 的整数(非法值报 400:subject_config.return_unpack_max_record_minutes 必须是大于 0 的整数);超过上限时拆包提交的结束时间自动截断为开始时间+上限" + }, + { + "name": "subject_config.default_location_id", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "默认库位(库位ID,须属于当前仓库且未删除、已启用,否则报 400;传 null 清空)" + }, + { + "name": "subject_config.cutoff_order_enabled", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "启用截单(flag:0=关闭,1=开启;默认 1)。启用后订单创建时间早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),不再自动分配快递和储位、不再自动加团" + }, + { + "name": "subject_config.allocate_start_time", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "开始自动分配时间,格式 HH:mm,默认 08:00,范围 00:00-23:59;作为自动分配初始时间,当前时间早于该时间与超过截单时间行为一致(不自动分配快递和储位、不自动加团)。与截单时间相同(自动分配窗口为空)时报 400" + }, + { + "name": "subject_config.cutoff_order_time", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "截单时间,格式 HH:mm,默认 18:00,范围 00:00-23:59;作为最后允许自动分配的时间,开始时间晚于截单时间时截单时间视为次日(跨天窗口)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice", + "type": "object", + "required": false, + "source": "body.subject_config", + "description": "收货未入库提醒配置。开启后每天按提醒时间(notice_time)扫描「创建时间超过 min_hours 且不足 max_hours 仍未完成入库」的收货单:绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.enabled", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否通知收货未入库(flag:0=关闭,1=开启;默认 0 关闭)。开启后收货未入库提醒定时任务才会在提醒时间执行;非法值报 400(字段级校验口径与其它 subject_config 字段一致)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.notice_time", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "提醒时间,格式 HH:mm,默认 08:30,范围 00:00-23:59;定时任务按此时间(含 10 分钟宽限)每天提醒一次;非法值报 400(字段级校验口径与其它 subject_config 字段一致)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.min_hours", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "超时下限(小时):收货单创建时间距今超过该值才提醒,默认 24,须为大于 0 的整数;非法值报 400(字段级校验口径与其它 subject_config 字段一致)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.max_hours", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "超时上限(小时):收货单创建时间距今小于该值才提醒(超过则不再提醒),默认 48,须为大于 min_hours 的整数;非法值报 400(字段级校验口径与其它 subject_config 字段一致)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.notice_template", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "通知短语(消息第一行,仓库/客服群)。支持变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名(未绑定为「未绑定货主」)/ {store_id} 货主ID / {count} 本批单数 / {min_hours} 超时下限 / {max_hours} 超时上限 / {date} 提醒日期(YYYY-MM-DD)/ {numbers} 本批收货单号。未识别的占位符原样保留;短语后换行逐行列出明细(一行一条,最多 20 行),留空使用默认短语;最长 500 字符,超长报 400" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.store_notice_template", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "通知短语(消息第一行,货主群)。变量同 notice_template,留空使用默认短语;最长 500 字符,超长报 400" + }, + { + "name": "subject_config.inbox_push_retry", + "type": "object", + "required": false, + "description": "站内信推送失败自动重发配置(同「收货未入库提醒」的嵌套结构):开启后站内信回信/系统通知推送失败(如桥接离线返回 wx offline / qiwe offline)由定时任务每 3 分钟自动重发一次", + "source": "body.subject_config" + }, + { + "name": "subject_config.inbox_push_retry.enabled", + "type": "number", + "required": false, + "description": "是否开启站内信推送失败自动重发(flag:0=关闭,1=开启;默认 0=关闭,需显式开启)", + "source": "body.subject_config" + }, + { + "name": "subject_config.inbox_push_retry.window_minutes", + "type": "number", + "required": false, + "description": "重发时间范围(分钟,1-1440,默认 30):仅自动重发「失败时间在该范围内」的消息,超出范围不再补发;仅在 enabled 开启时生效", + "source": "body.subject_config" + } + ], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID" + }, + { + "name": "subject_config", + "type": "object", + "required": true, + "description": "保存后的 subject_config" + }, + { + "name": "cache_cleared_warehouse_id", + "type": "number", + "required": true, + "description": "被清理缓存的仓库 ID(若未清理则为 null)" + }, + { + "name": "subject_config.enable_external_express_code", + "type": "boolean", + "required": true, + "description": "保存后的 subject_config.enable_external_express_code 值" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库/参数不合法" + }, + { + "code": "400", + "message": "subject_config.single_weigh_require_pack 必须是布尔值(仅接受 true/false/1/0 及其字符串)" + }, + { + "code": "400", + "message": "subject_config.big_group_pack_coefficient 必须是大于 0 的数字(非有限数字或小于等于 0 视为非法)" + }, + { + "code": "404", + "message": "仓库不存在" + }, + { + "code": "500", + "message": "保存失败" + } + ] + }, + { + "method": "setting.warehouse.saveFrontConfig", + "description": "保存当前仓库前端独立部署品牌配置(upsert,一仓一行,仅仓库主体可操作,仅品牌字段部分更新)。仅受理 title(≤100 字符)、logo_url/login_bg_url/favicon_url(≤255 字符)、theme(合法 JSON 对象或 JSON 字符串),空值清空。domain 与证书相关字段(domain/cert_pem/key_pem/cert_path/key_path/cert_expire_at)不再受理:方法层白名单静默忽略前端传值,domain 变更必须走 setting.warehouse.saveFrontCert(重新校验证书)。保存即重置同步状态(sync_status=0、sync_attempts=0、清空 last_sync_error/last_synced_at),写库成功后清理当前 domain 的公共拉取缓存(先写库后清缓存,清缓存失败仅记日志)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "title", + "type": "string", + "required": false, + "source": "body", + "description": "站点标题(可选,≤100 字符,超长报 400,空值清空)" + }, + { + "name": "logo_url", + "type": "string", + "required": false, + "source": "body", + "description": "Logo 地址(可选,≤255 字符,超长报 400,空值清空)" + }, + { + "name": "favicon_url", + "type": "string", + "required": false, + "source": "body", + "description": "站点 favicon 图标地址(可选,≤255 字符,超长报 400,空值清空)" + }, + { + "name": "login_bg_url", + "type": "string", + "required": false, + "source": "body", + "description": "登录页背景图地址(可选,≤255 字符,超长报 400,空值清空)" + }, + { + "name": "theme", + "type": "object|string", + "required": false, + "source": "body", + "description": "主题配置(可选,合法 JSON 对象或 JSON 字符串,否则报 400「theme 必须是合法的 JSON 对象」;空值清空)" + } + ], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库 ID" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "仓库自持域名(未配置为空字符串)" + }, + { + "name": "title", + "type": "string", + "required": true, + "description": "站点标题(未配置为空字符串)" + }, + { + "name": "logo_url", + "type": "string", + "required": true, + "description": "Logo 地址(未配置为空字符串)" + }, + { + "name": "favicon_url", + "type": "string", + "required": true, + "description": "站点 favicon 图标地址(未配置为空字符串)" + }, + { + "name": "login_bg_url", + "type": "string", + "required": true, + "description": "登录页背景图地址(未配置为空字符串)" + }, + { + "name": "theme", + "type": "object", + "required": true, + "description": "主题配置对象(未配置为 null)" + }, + { + "name": "cert_pem", + "type": "string", + "required": true, + "description": "证书 PEM 原文(读 cert_pem 列;未配置为空字符串;仅登录仓库主体 settings 页接口回显,公共无鉴权接口 frontConfig.getByDomain 不返回)" + }, + { + "name": "key_pem", + "type": "string", + "required": true, + "description": "私钥 PEM 原文(读 cert_key 列;未配置为空字符串;仅登录仓库主体 settings 页接口回显,公共无鉴权接口 frontConfig.getByDomain 不返回)" + }, + { + "name": "cert_expire_at", + "type": "string", + "required": true, + "description": "证书到期时间(由 saveFrontCert 上传证书后权威写入;未上传为 null)" + }, + { + "name": "sync_status", + "type": "number", + "required": true, + "description": "同步状态(0-待同步/1-同步成功/2-同步失败;本次保存后重置为 0)" + }, + { + "name": "sync_attempts", + "type": "number", + "required": true, + "description": "同步尝试次数(本次保存后重置为 0)" + }, + { + "name": "last_sync_error", + "type": "string", + "required": true, + "description": "最近一次同步失败原因(本次保存后清空)" + }, + { + "name": "last_synced_at", + "type": "string", + "required": true, + "description": "最近一次同步成功时间(本次保存后清空,可为 null)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "配置更新时间" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "400", + "message": "title/logo_url/login_bg_url/favicon_url 超长(title 长度不能超过 100 字符、其余不能超过 255 字符)/theme 非合法 JSON 对象" + }, + { + "code": "403", + "message": "仅仓库主体可配置前端独立部署(业务层 isWarehouse 判定)" + }, + { + "code": "409", + "message": "并发写入兜底:仓库前端配置保存冲突,请稍后重试" + }, + { + "code": "500", + "message": "签约关系服务不可用/WarehouseFrontConfig model 不可用/保存仓库前端配置失败" + } + ] + }, + { + "method": "setting.warehouse.getFrontConfig", + "description": "查询当前仓库前端独立部署配置(settings 页回显,仅登录仓库主体可调用)。无入参;按当前登录仓库 store_id 查询 wms_warehouse_front_config(一仓一行),无记录时返回默认空配置(warehouse_id 为当前仓库 ID,其余字段为空值/null)。响应 15 字段,含证书 PEM 原文(cert_pem,读 cert_pem 列)与私钥 PEM 原文(key_pem,读 cert_key 列)回显、未配置均为空字符串;公共无鉴权接口 frontConfig.getByDomain 仍仅返回 6 个公开字段白名单(domain/title/logo_url/login_bg_url/favicon_url/theme),不暴露证书/私钥内容。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库 ID" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "仓库自持域名(未配置为空字符串)" + }, + { + "name": "title", + "type": "string", + "required": true, + "description": "站点标题(未配置为空字符串)" + }, + { + "name": "logo_url", + "type": "string", + "required": true, + "description": "Logo 地址(未配置为空字符串)" + }, + { + "name": "favicon_url", + "type": "string", + "required": true, + "description": "站点 favicon 图标地址(未配置为空字符串)" + }, + { + "name": "login_bg_url", + "type": "string", + "required": true, + "description": "登录页背景图地址(未配置为空字符串)" + }, + { + "name": "theme", + "type": "object", + "required": true, + "description": "主题配置对象(未配置为 null)" + }, + { + "name": "cert_pem", + "type": "string", + "required": true, + "description": "证书 PEM 原文(读 cert_pem 列;未配置为空字符串;仅登录仓库主体 settings 页接口回显,公共无鉴权接口 frontConfig.getByDomain 不返回)" + }, + { + "name": "key_pem", + "type": "string", + "required": true, + "description": "私钥 PEM 原文(读 cert_key 列;未配置为空字符串;仅登录仓库主体 settings 页接口回显,公共无鉴权接口 frontConfig.getByDomain 不返回)" + }, + { + "name": "cert_expire_at", + "type": "string", + "required": true, + "description": "证书到期时间(由 saveFrontCert 上传证书后权威写入;未上传为 null)" + }, + { + "name": "sync_status", + "type": "number", + "required": true, + "description": "同步状态(0-待同步/1-同步成功/2-同步失败,无记录为 0)" + }, + { + "name": "sync_attempts", + "type": "number", + "required": true, + "description": "同步尝试次数(无记录为 0)" + }, + { + "name": "last_sync_error", + "type": "string", + "required": true, + "description": "最近一次同步失败原因(无记录为空字符串)" + }, + { + "name": "last_synced_at", + "type": "string", + "required": true, + "description": "最近一次同步成功时间(无记录为 null)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "配置更新时间(无记录为 null)" + } + ], + "errors": [ + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "500", + "message": "WarehouseFrontConfig model 不可用/获取仓库前端配置失败" + } + ] + }, + { + "method": "setting.warehouse.saveFrontCert", + "description": "上传当前仓库前端独立部署证书(upsert,一仓一行,需登录、仅仓库主体可操作)。入参 domain + pem/key 成对必填:校验链为证书可解析 → 未生效/已过期拒绝 → 私钥与证书成对(SPKI 公钥指纹比对)→ 证书 SAN DNS/CN 覆盖 domain(支持精确匹配与 *.example.com 通配,不覆盖报 400),任一证书校验失败均返回统一文案「证书不合法」(400,不返回细节)。通过后自动写入 cert_expire_at(证书 validTo 权威值,不接受前端传值),证书/私钥 PEM 内容直接写入 cert_pem/cert_key 列入库(不再写暂存文件,内容供定时任务读取、禁止写入日志),cert_path/key_path 保存时置空、等待未来定时任务部署证书后回填真实路径,domain 全局唯一(非空,已被其他仓库使用报 409)。保存即重置同步状态(sync_status=0、sync_attempts=0、清空 last_sync_error/last_synced_at),写库成功后清理旧 domain 与新 domain 的公共拉取缓存(先写库后清缓存,清缓存失败仅记日志)。响应 15 字段含证书 PEM 原文(cert_pem)与私钥 PEM 原文(key_pem)回显,仅登录仓库主体 settings 页接口回显;公共无鉴权接口 frontConfig.getByDomain 不返回证书内容。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "domain", + "type": "string", + "required": true, + "source": "body", + "description": "仓库自持域名(必填,trim 后非空,≤100 字符;全局唯一,已被其他仓库使用报 409)" + }, + { + "name": "pem", + "type": "string", + "required": true, + "source": "body", + "description": "证书 PEM 文本(必填,≤65536 字符,超长报 400「pem 内容长度不能超过 65536 字符」;须能解析为 X.509 证书、未过期且 SAN/CN 覆盖 domain)" + }, + { + "name": "key", + "type": "string", + "required": true, + "source": "body", + "description": "私钥 PEM 文本(必填,≤65536 字符,超长报 400「key 内容长度不能超过 65536 字符」;须与 pem 成对,按 SPKI 公钥指纹比对不匹配报 400)" + } + ], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库 ID" + }, + { + "name": "domain", + "type": "string", + "required": true, + "description": "保存后的域名(本次上传生效)" + }, + { + "name": "title", + "type": "string", + "required": true, + "description": "站点标题(未配置为空字符串)" + }, + { + "name": "logo_url", + "type": "string", + "required": true, + "description": "Logo 地址(未配置为空字符串)" + }, + { + "name": "favicon_url", + "type": "string", + "required": true, + "description": "站点 favicon 图标地址(未配置为空字符串)" + }, + { + "name": "login_bg_url", + "type": "string", + "required": true, + "description": "登录页背景图地址(未配置为空字符串)" + }, + { + "name": "theme", + "type": "object", + "required": true, + "description": "主题配置对象(未配置为 null)" + }, + { + "name": "cert_pem", + "type": "string", + "required": true, + "description": "证书 PEM 原文(读 cert_pem 列,本次上传后即回显;仅登录仓库主体 settings 页接口回显,公共无鉴权接口 frontConfig.getByDomain 不返回)" + }, + { + "name": "key_pem", + "type": "string", + "required": true, + "description": "私钥 PEM 原文(读 cert_key 列,本次上传后即回显;仅登录仓库主体 settings 页接口回显,公共无鉴权接口 frontConfig.getByDomain 不返回)" + }, + { + "name": "cert_expire_at", + "type": "string", + "required": true, + "description": "证书到期时间(后端按证书 validTo 权威写入,非入参)" + }, + { + "name": "sync_status", + "type": "number", + "required": true, + "description": "同步状态(0-待同步/1-同步成功/2-同步失败;本次上传后重置为 0)" + }, + { + "name": "sync_attempts", + "type": "number", + "required": true, + "description": "同步尝试次数(本次上传后重置为 0)" + }, + { + "name": "last_sync_error", + "type": "string", + "required": true, + "description": "最近一次同步失败原因(本次上传后清空)" + }, + { + "name": "last_synced_at", + "type": "string", + "required": true, + "description": "最近一次同步成功时间(本次上传后清空,可为 null)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "配置更新时间" + } + ], + "errors": [ + { + "code": "400", + "message": "domain 不能为空/domain 长度不能超过 100 字符/pem 不能为空/key 不能为空/pem|key 内容长度不能超过 65536 字符" + }, + { + "code": "400", + "message": "证书校验失败统一文案「证书不合法」:无法解析为 X.509 PEM 证书/证书未生效/证书已过期/私钥无法解析/私钥与证书不匹配/SAN-CN 不覆盖 domain" + }, + { + "code": "400", + "message": "未识别到当前仓库,无法操作仓库设置" + }, + { + "code": "403", + "message": "仅仓库主体可配置前端独立部署(业务层 isWarehouse 判定)" + }, + { + "code": "409", + "message": "域名 {domain} 已被其他仓库使用(含并发唯一索引冲突兜底:仓库前端配置保存冲突,请稍后重试)" + }, + { + "code": "500", + "message": "签约关系服务不可用/WarehouseFrontConfig model 不可用" + } + ] + } + ] + }, + { + "groupName": "平台编码管理模块", + "module": "setting.platform", + "list": [ + { + "method": "index.getPlatformList", + "description": "获取平台列表。默认返回系统基础平台与当前登录仓库自定义平台设置的合并结果:系统平台在前,仓库自定义编码在后,同一 `code` 仅保留首条(系统同码优先保留系统记录)。当 `systemOnly` 为真值(支持 `true`、`1`、`'1'`、`'true'`)时,仅返回系统基础平台列表。`full` 为真值时返回全量字段(包含 wms_platform 全部表字段、route_platform_code、platid 等)。仓库范围来自当前登录用户 `ctx.user.store_id`;未识别到仓库时,自定义设置列表为空。接口优先读取缓存,未命中时回源 `wms_platform` 与 `wms_platfrom_setting`。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "systemOnly", + "type": "boolean|number|string", + "required": false, + "source": "body", + "description": "是否仅返回系统基础平台列表;仅 `true`、`1`、`'1'`、`'true'` 会被识别为 true,其余值按 false 处理。也支持 `is_system` 别名(若请求体中同时存在 `is_system` 和 `systemOnly`,优先使用 `is_system`)" + }, + { + "name": "full", + "type": "boolean|number|string", + "required": false, + "source": "body", + "description": "是否返回全量字段;仅 `true`、`1`、`'1'`、`'true'` 会被识别为 true,其余值按 false 处理。为 true 时返回 wms_platform 全部表字段、route_platform_code、platid 等扩展信息" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功时为 `success`" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "返回消息,成功时通常为 `ok`" + }, + { + "name": "data", + "type": "array", + "required": true, + "description": "平台列表数组。默认模式下先返回系统基础平台,再追加当前仓库自定义设置;`systemOnly=true` 时仅返回系统基础平台。每项字段如下:", + "children": [ + { + "name": "code", + "type": "string", + "description": "平台编码。系统平台项为 `wms_platform.code`;仓库自定义项为 `wms_platfrom_setting.code`" + }, + { + "name": "name", + "type": "string", + "description": "展示名称。系统平台项为 `wms_platform.name`;仓库自定义项格式为 `<自定义编码> (<系统平台名>)`,若未匹配到系统平台名则退化为自定义编码" + }, + { + "name": "value", + "type": "string", + "description": "与 `code` 相同,供前端选项组件直接使用" + }, + { + "name": "label", + "type": "string", + "description": "与 `name` 相同,供前端选项组件直接使用" + }, + { + "name": "platform_code", + "type": "string", + "description": "系统平台编码。系统平台项与 `code` 相同;仓库自定义项为 `wms_platfrom_setting.platform_code`(即该自定义编码所关联的系统平台编码)" + }, + { + "name": "platform_name", + "type": "string", + "description": "系统平台名称。系统平台项与 `name` 相同;仓库自定义项为关联的系统平台名称" + }, + { + "name": "default_express_interface", + "type": "string", + "description": "默认快递接口编码。由 `wms_platform.print_platform_id` → `wms_print_platform.platform_code` 解析得到;未配置时为空字符串" + }, + { + "name": "is_system_setting", + "type": "boolean", + "description": "是否为仓库自定义平台设置。`false` 表示系统基础平台,`true` 表示来自当前仓库 `wms_platfrom_setting` 的自定义编码" + }, + { + "name": "id", + "type": "number|null", + "description": "仅仓库自定义平台设置项返回,为 `wms_platfrom_setting.id` 记录主键;系统平台项不返回该字段" + }, + { + "name": "alias", + "type": "string", + "description": "仅仓库自定义平台设置项返回,当前固定为空字符串(设计预留字段);系统平台项不返回该字段" + }, + { + "name": "(full 模式扩展字段)", + "type": "object", + "description": "当 `full=true` 时,每项额外包含:系统平台项追加 `interface_url`、`appkey`、`app_secret`、`token`、`version`、`shoptype`、`ordersource`、`component`、`print_platform_id`(以上均为 wms_platform 原始表字段)、`route_platform_code`(平台后处理路由编码)、`platid`(打印平台 platid,仅当 print_platform_id 可映射时);仓库自定义项追加 `warehouse_id`、`route_platform_code` 及 wms_platfrom_setting 全部原始字段" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "获取平台列表失败(数据库或缓存访问异常)" + } + ] + }, + { + "method": "setting.platform.list", + "description": "查询当前仓库范围的平台设置列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.platform.create", + "description": "创建当前仓库范围的平台设置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.platform.update", + "description": "更新当前仓库范围的平台设置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.platform.delete", + "description": "删除当前仓库范围的平台设置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "快递编码管理模块", + "module": "setting.express", + "list": [ + { + "method": "index.getExpressList", + "description": "获取快递列表。默认返回系统基础快递与当前登录仓库自定义快递编码的合并结果:系统快递在前,仓库自定义编码在后,同一 `code` 仅保留首条(系统同码优先保留系统记录)。当 `systemOnly` 为真值(支持 `true`、`1`、`'1'`、`'true'`)时,仅返回系统基础快递列表。仅接受 `express_code` 入参,服务端会先 trim 再转为大写:`systemOnly=true` 时按系统快递编码过滤系统基础快递列表;`systemOnly=false` 时按自定义编码映射记录中的系统快递编码字段 `express_code` 过滤,仅返回当前登录仓库下匹配该系统快递编码的自定义编码列表,不再回传系统基础项。仓库范围来自当前登录用户 `ctx.user.store_id`;未识别到仓库时,自定义编码列表为空。接口优先读取缓存,未命中时回源 `wms_express` 与 `wms_express_setting`。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "systemOnly", + "type": "boolean|number|string", + "required": false, + "source": "body", + "description": "是否仅返回系统基础快递列表;仅 `true`、`1`、`'1'`、`'true'` 会被识别为 true,其余值按 false 处理" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码;服务端会去首尾空格并转为大写。`systemOnly=true` 时按该系统快递编码过滤系统基础快递列表;`systemOnly=false` 时按自定义映射记录中的系统快递编码字段 `express_code` 过滤当前仓库的自定义编码列表,而不是按自定义 `code` 过滤" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功时为 `success`" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "返回消息,成功时通常为 `ok`" + }, + { + "name": "data", + "type": "array", + "required": true, + "description": "快递列表数组。默认模式下先返回系统基础快递,再追加当前仓库自定义编码;当传入 `express_code` 且 `systemOnly=false` 时,仅返回当前仓库下系统快递编码等于该 `express_code` 的自定义映射记录,不返回系统基础项。每项字段如下:", + "children": [ + { + "name": "code", + "type": "string", + "description": "返回项编码。系统项为系统快递编码;仓库自定义项为自定义快递编码" + }, + { + "name": "name", + "type": "string", + "description": "展示名称。系统项为快递名称;仓库自定义项格式通常为 `<自定义编码> (<系统快递名>)`,若未匹配到系统快递名则退化为自定义编码" + }, + { + "name": "value", + "type": "string", + "description": "与 `code` 相同,供前端选项组件直接使用" + }, + { + "name": "label", + "type": "string", + "description": "与 `name` 相同,供前端选项组件直接使用" + }, + { + "name": "is_system_setting", + "type": "boolean", + "description": "是否为仓库自定义快递编码;`false` 表示系统基础快递,`true` 表示来自当前仓库 `wms_express_setting` 的自定义编码" + }, + { + "name": "id", + "type": "number|null", + "description": "仓库自定义快递设置记录 ID;系统基础快递固定为 `null`" + }, + { + "name": "alias", + "type": "string|null", + "description": "仓库自定义快递设置表中的原始名称(`wms_express_setting.name`);系统基础快递固定为 `null`" + }, + { + "name": "express_code", + "type": "string", + "description": "仅仓库自定义快递编码项返回其关联的系统快递编码;当 `systemOnly=false` 且传入筛选值时,即按该字段匹配自定义映射记录。系统基础快递项通常不返回该字段" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "获取快递列表失败(数据库或缓存访问异常)" + } + ] + }, + { + "method": "setting.express.list", + "description": "查询当前仓库范围的快递映射列表,支持 where + pagination", + "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,兼容 currentPage / page_size / size" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.express.listBase", + "description": "返回系统快递基础列表(系统级别基础快递,不含仓库自定义)", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.express.create", + "description": "创建快递映射,仅写入已实现字段(code、name、express_code 等)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "快递映射编码;接口会转为大写" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "快递名称(最大 50 字符)" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "source": "body", + "description": "系统快递编码;同时支持驼峰写法 expressCode" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.express.checkCodeUnique", + "description": "校验快递编码在当前仓库/主体维度唯一性,仅支持 code 与可选 id 排除自身", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "待校验的快递编码" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "排除自身 id(更新时使用)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.express.update", + "description": "更新快递映射。必须提供 `id`(必填),且至少提供 `code`、`name` 或 `express_code` 中的一个用于更新;同时支持 `expressCode` 驼峰写法。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "快递记录ID;也兼容别名 `setting_id` / `settingId`" + }, + { + "name": "code", + "type": "string", + "required": false, + "source": "body", + "description": "快递映射编码(最大 50 字符,接口会大写化并校验在当前仓库的唯一性)" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "快递名称(最大 50 字符)" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码(必须为系统已存在的编码);支持 `expressCode` 驼峰写法" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "更新后的快递映射对象(规范化字段)", + "children": [ + { + "name": "id", + "type": "number", + "description": "记录ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库ID" + }, + { + "name": "code", + "type": "string", + "description": "快递映射编码" + }, + { + "name": "name", + "type": "string", + "description": "快递名称" + }, + { + "name": "express_code", + "type": "string", + "description": "系统快递编码" + }, + { + "name": "express_name", + "type": "string", + "description": "系统快递名称(从系统快递表映射)" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "id 参数不能为空" + }, + { + "code": "400", + "message": "至少需要提供一个可更新字段" + }, + { + "code": "400", + "message": "code 参数不能为空" + }, + { + "code": "400", + "message": "express_code 参数不能为空" + }, + { + "code": "400", + "message": "系统快递编码不存在" + }, + { + "code": "404", + "message": "快递映射不存在或无权限操作" + }, + { + "code": "409", + "message": "快递编码已被当前仓库使用" + } + ] + }, + { + "method": "setting.express.delete", + "description": "批量软删除快递映射;接受 ids 参数,已删除记录会在结果中标记。", + "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数组;支持数组、逗号字符串或单个ID。" + } + ], + "response": [ + { + "name": "ids", + "type": "array", + "required": true, + "description": "请求中的所有 id 列表(原样返回)" + }, + { + "name": "deleted_ids", + "type": "array", + "required": true, + "description": "本次实际被软删除的 ID 列表(即原本未被删除的 ID)" + }, + { + "name": "already_deleted_ids", + "type": "array", + "required": true, + "description": "请求中已处于已删除状态的 ID 列表" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 'deleted'" + } + ], + "errors": [ + { + "code": "400", + "message": "ids 参数不能为空或格式错误" + }, + { + "code": "404", + "message": "快递映射不存在或无权限操作" + }, + { + "code": "409", + "message": "存在快递接口引用的快递编码,无法删除" + } + ] + } + ] + }, + { + "groupName": "快递接口管理", + "module": "setting.expressInterface", + "list": [ + { + "method": "setting.expressInterface.list", + "description": "查询当前仓库范围的快递接口列表,支持 where + pagination;返回 data:{ list, total, page, page_size }。按 weight 升序、id 降序排序,优先按权重排序。每条记录新增 quantity/recycled_quantity/cancel_quantity/allocated_quantity 扁平字段,数据源为 index.getShopExpressList,按 sys_express_code/site_code/shipperno 三层匹配汇总。", + "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": "筛选条件,支持 id/name/express_code/platform_code/sender_name/sender_tel/viewer/client_id/share_id/site_code/product_type/shop_name/is_enabled/quickWhere" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "主键ID" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "description": "快递编码" + }, + { + "name": "sys_express_code", + "type": "string", + "required": true, + "description": "系统快递编码" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID" + }, + { + "name": "shop_id", + "type": "number", + "required": false, + "description": "店铺ID,未绑定时为 null" + }, + { + "name": "platform_shop_id", + "type": "number", + "required": false, + "description": "平台店铺ID" + }, + { + "name": "template_id", + "type": "string", + "required": false, + "description": "模板ID" + }, + { + "name": "paymode", + "type": "number", + "required": false, + "description": "付款方式" + }, + { + "name": "brandno", + "type": "string", + "required": false, + "description": "品牌编码" + }, + { + "name": "providertype", + "type": "string", + "required": false, + "description": "服务商类型编码" + }, + { + "name": "providerid", + "type": "number", + "required": false, + "description": "服务商ID" + }, + { + "name": "platform_code", + "type": "string", + "required": true, + "description": "平台编码(PDD/CAINIAO/DY/KS/SPH/XHS/JD/QT)" + }, + { + "name": "sender_name", + "type": "string", + "required": false, + "description": "寄件人" + }, + { + "name": "sender_tel", + "type": "string", + "required": false, + "description": "寄件电话" + }, + { + "name": "weight", + "type": "number", + "required": false, + "description": "排序权重" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "description": "重量类型" + }, + { + "name": "viewer", + "type": "string", + "required": false, + "description": "查看者/备注" + }, + { + "name": "client_id", + "type": "string", + "required": false, + "description": "客户ID" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "是否启用(1启用 0禁用)" + }, + { + "name": "is_share", + "type": "number", + "required": false, + "description": "是否共享" + }, + { + "name": "ispickup", + "type": "number", + "required": false, + "description": "是否上门取件" + }, + { + "name": "shipperno", + "type": "string", + "required": false, + "description": "发货编号/客户代码" + }, + { + "name": "template_url", + "type": "string", + "required": false, + "description": "模板URL" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "description": "扩展数据(JSON对象)" + }, + { + "name": "province_name", + "type": "string", + "required": false, + "description": "省份" + }, + { + "name": "city_name", + "type": "string", + "required": false, + "description": "城市" + }, + { + "name": "district_name", + "type": "string", + "required": false, + "description": "区县" + }, + { + "name": "address", + "type": "string", + "required": false, + "description": "详细地址" + }, + { + "name": "town_name", + "type": "string", + "required": false, + "description": "镇/街道" + }, + { + "name": "site_code", + "type": "string", + "required": false, + "description": "网点编码" + }, + { + "name": "product_type", + "type": "string", + "required": false, + "description": "产品类型" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "description": "店铺名称" + }, + { + "name": "express", + "type": "object", + "required": false, + "description": "关联的系统快递对象", + "children": [ + { + "name": "code", + "type": "string", + "required": false, + "description": "系统快递编码" + }, + { + "name": "name", + "type": "string", + "required": false, + "description": "快递名称" + }, + { + "name": "polyapi_code", + "type": "string", + "required": false, + "description": "PolyAPI编码" + }, + { + "name": "polyapi_extra_info", + "type": "string", + "required": false, + "description": "PolyAPI扩展信息" + }, + { + "name": "pdd_code", + "type": "string", + "required": false, + "description": "拼多多快递编码" + }, + { + "name": "ks_code", + "type": "string", + "required": false, + "description": "快手快递编码" + }, + { + "name": "dyxd_code", + "type": "string", + "required": false, + "description": "抖音快递编码" + } + ] + }, + { + "name": "express_name", + "type": "string", + "required": false, + "description": "快递名称(扁平字段)" + }, + { + "name": "express_polyapi_extra_info", + "type": "string", + "required": false, + "description": "PolyAPI扩展信息(扁平字段)" + }, + { + "name": "express_pdd_code", + "type": "string", + "required": false, + "description": "拼多多快递编码(扁平字段)" + }, + { + "name": "is_system_express_code", + "type": "number", + "required": true, + "description": "是否为系统快递编码(1是 0否)" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "description": "可用面单数量(从店铺快递签约数据汇总),无店铺或无数据时为 0" + }, + { + "name": "recycled_quantity", + "type": "number", + "required": true, + "description": "已回收面单数量" + }, + { + "name": "cancel_quantity", + "type": "number", + "required": true, + "description": "已取消面单数量" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": true, + "description": "已分配面单数量" + } + ], + "description": "list,按 weight 升序、id 降序排序;优先按权重排序,权重相同再按 id 倒序" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "page_size", + "type": "number", + "required": true, + "description": "每页条数" + } + ], + "errors": [] + }, + { + "method": "setting.expressInterface.listByWarehousePlatformCode", + "description": "按 warehouse_id + platform_code 查询快递接口全字段数组,支持缓存;返回结果按 weight 升序、必要时按 id 升序排序,每条记录显式包含 express_code 以及关联的 express 对象(如 express.id/express.code/express.name/express.platform)。该接口不分页,按 warehouse_id + platform_code 全量返回匹配记录。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id / warehouseId", + "type": "number", + "required": false, + "source": "body", + "description": "仓库ID;默认使用当前登录主体/仓库上下文(ctx.user.store_id),也支持显式传入以查询指定仓库,文档兼容 warehouse_id 与 warehouseId 两种写法。" + }, + { + "name": "platform_code / platformCode", + "type": "string", + "required": true, + "source": "body", + "description": "平台代码;作为缓存键的一部分,建议使用大写形式(服务端会标准化处理)。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "快递接口记录数组(按 warehouse_id + platform_code 全量返回,不分页),每项包含以下字段:", + "children": [ + { + "name": "id", + "type": "number", + "description": "记录ID" + }, + { + "name": "name", + "type": "string", + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "description": "快递编码" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库ID(文档中的仓库范围由系统强制校验)" + }, + { + "name": "platform_code", + "type": "string", + "description": "平台代码" + }, + { + "name": "express_platform_id", + "type": "number", + "description": "平台接口ID" + }, + { + "name": "sender_name", + "type": "string", + "description": "发件人姓名" + }, + { + "name": "sender_tel", + "type": "string", + "description": "发件人电话" + }, + { + "name": "weight", + "type": "number", + "description": "默认重量" + }, + { + "name": "token", + "type": "string", + "description": "接口密钥或 token(部分记录可能为空)" + }, + { + "name": "viewer", + "type": "string", + "description": "查看者标识" + }, + { + "name": "client_id", + "type": "string", + "description": "客户端 ID" + }, + { + "name": "is_share", + "type": "number", + "description": "是否共享(0/1)" + }, + { + "name": "share_id", + "type": "number", + "description": "共享记录ID" + }, + { + "name": "can_use_count", + "type": "number", + "description": "可用次数或配额" + }, + { + "name": "province_name", + "type": "string", + "description": "省" + }, + { + "name": "city_name", + "type": "string", + "description": "市" + }, + { + "name": "district_name", + "type": "string", + "description": "区/县" + }, + { + "name": "site_code", + "type": "string", + "description": "站点编码" + }, + { + "name": "product_type", + "type": "string", + "description": "快递产品类型" + }, + { + "name": "shop_name", + "type": "string", + "description": "店铺名称/分组标识" + }, + { + "name": "ext_data", + "type": "object", + "description": "扩展信息 JSON(支持任意键值对象)" + }, + { + "name": "express", + "type": "object", + "description": "关联的快递对象(若存在),包含基础快递信息,便于前端展示与回源校验", + "children": [ + { + "name": "id", + "type": "number", + "description": "快递主表 ID" + }, + { + "name": "code", + "type": "string", + "description": "快递编码" + }, + { + "name": "name", + "type": "string", + "description": "快递名称" + }, + { + "name": "platform", + "type": "string", + "description": "所属平台标识" + } + ] + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "缺少 platform_code 或仓库上下文错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.expressInterface.create", + "description": "在当前仓库范围内创建快递接口,支持 shop_id/shopId 入参。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "source": "body", + "description": "express_code" + }, + { + "name": "platform_code", + "type": "string", + "required": true, + "source": "body", + "description": "platform_code" + }, + { + "name": "shop_id", + "type": "number", + "required": false, + "source": "body", + "description": "店铺 ID(支持 shopId),正整数,可空;未传或空值按 null 处理" + }, + { + "name": "address", + "type": "string", + "required": false, + "source": "body", + "description": "发件人详细地址(可选),使用 index.getShopExpressList 返回的 detail 字段值,非 full_address" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建记录 ID" + } + ], + "errors": [] + }, + { + "method": "setting.expressInterface.update", + "description": "更新快递接口。至少传入一个可更新字段,仅更新传入的字段;id 兼容 interface_id / interfaceId 入参;shop_id 可空,传入时会同步刷新接口 token;name/express_code/platform_code/sys_express_code 变更会触发系统快递编码重新解析。更新成功后返回该记录的完整字段。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "快递接口ID,兼容 interface_id / interfaceId" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "快递编码(存大写);与 platform_code / sys_express_code 任一变更时重新解析系统快递编码" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码(PDD/CAINIAO/DY/KS/SPH/XHS/JD/QT)" + }, + { + "name": "sys_express_code", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码(支持 sysExpressCode);未传时按 express_code + platform_code 自动匹配" + }, + { + "name": "shop_id", + "type": "number", + "required": false, + "source": "body", + "description": "店铺ID(支持 shopId),正整数可空;传入该字段会同步刷新接口 token" + }, + { + "name": "platform_shop_id", + "type": "number", + "required": false, + "source": "body", + "description": "平台店铺ID(支持 platformShopId),正整数可空" + }, + { + "name": "template_id", + "type": "string", + "required": false, + "source": "body", + "description": "模板ID(支持 templateId),空字符串按 null 处理" + }, + { + "name": "paymode", + "type": "number", + "required": false, + "source": "body", + "description": "付款方式(支持 payMode)" + }, + { + "name": "brandno", + "type": "string", + "required": false, + "source": "body", + "description": "品牌编码(支持 brandNo),空字符串按 null 处理" + }, + { + "name": "providertype", + "type": "string", + "required": false, + "source": "body", + "description": "服务商类型编码(支持 providerType),空字符串按 null 处理" + }, + { + "name": "providerid", + "type": "number", + "required": false, + "source": "body", + "description": "服务商ID(支持 providerId)" + }, + { + "name": "sender_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人(支持 senderName)" + }, + { + "name": "sender_tel", + "type": "string", + "required": false, + "source": "body", + "description": "寄件电话(支持 senderTel)" + }, + { + "name": "weight", + "type": "number", + "required": false, + "source": "body", + "description": "排序权重,可空" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "source": "body", + "description": "重量类型(支持 weightType),可空" + }, + { + "name": "viewer", + "type": "string", + "required": false, + "source": "body", + "description": "验视员/查看者" + }, + { + "name": "client_id", + "type": "string", + "required": false, + "source": "body", + "description": "客户ID(支持 clientId)" + }, + { + "name": "ispickup", + "type": "number", + "required": false, + "source": "body", + "description": "是否上门取件(支持 isPickup),1是 0否" + }, + { + "name": "shipperno", + "type": "string", + "required": false, + "source": "body", + "description": "发货编号/寄件网点编码(支持 shipperNo)" + }, + { + "name": "template_url", + "type": "string", + "required": false, + "source": "body", + "description": "打印模板URL(支持 templateUrl)" + }, + { + "name": "province_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人省份(支持 provinceName)" + }, + { + "name": "city_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人城市(支持 cityName)" + }, + { + "name": "district_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人区县(支持 districtName)" + }, + { + "name": "address", + "type": "string", + "required": false, + "source": "body", + "description": "发件人详细地址,使用 index.getShopExpressList 返回的 detail 字段值,非 full_address" + }, + { + "name": "town_name", + "type": "string", + "required": false, + "source": "body", + "description": "寄件人镇/街道(支持 townName)" + }, + { + "name": "site_code", + "type": "string", + "required": false, + "source": "body", + "description": "网点编码(支持 siteCode)" + }, + { + "name": "product_type", + "type": "string", + "required": false, + "source": "body", + "description": "产品类型/编码(支持 productType)" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "平台店铺名称(支持 shopName)" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "source": "body", + "description": "扩展数据 JSON 对象(支持 extData)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "是否启用(支持 isEnabled),1启用 0停用" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "主键ID" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "接口名称" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "description": "快递编码" + }, + { + "name": "sys_express_code", + "type": "string", + "required": true, + "description": "系统快递编码" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID" + }, + { + "name": "shop_id", + "type": "number", + "required": false, + "description": "店铺ID,未绑定时为 null" + }, + { + "name": "platform_shop_id", + "type": "number", + "required": false, + "description": "平台店铺ID" + }, + { + "name": "template_id", + "type": "string", + "required": false, + "description": "模板ID" + }, + { + "name": "paymode", + "type": "number", + "required": false, + "description": "付款方式" + }, + { + "name": "brandno", + "type": "string", + "required": false, + "description": "品牌编码" + }, + { + "name": "providertype", + "type": "string", + "required": false, + "description": "服务商类型编码" + }, + { + "name": "providerid", + "type": "number", + "required": false, + "description": "服务商ID" + }, + { + "name": "platform_code", + "type": "string", + "required": true, + "description": "平台编码(PDD/CAINIAO/DY/KS/SPH/XHS/JD/QT)" + }, + { + "name": "sender_name", + "type": "string", + "required": false, + "description": "寄件人" + }, + { + "name": "sender_tel", + "type": "string", + "required": false, + "description": "寄件电话" + }, + { + "name": "weight", + "type": "number", + "required": false, + "description": "排序权重" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "description": "重量类型" + }, + { + "name": "viewer", + "type": "string", + "required": false, + "description": "验视员/查看者" + }, + { + "name": "client_id", + "type": "string", + "required": false, + "description": "客户ID" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "是否启用(1启用 0禁用)" + }, + { + "name": "is_share", + "type": "number", + "required": false, + "description": "是否共享" + }, + { + "name": "ispickup", + "type": "number", + "required": false, + "description": "是否上门取件" + }, + { + "name": "shipperno", + "type": "string", + "required": false, + "description": "发货编号/寄件网点编码" + }, + { + "name": "template_url", + "type": "string", + "required": false, + "description": "打印模板URL" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "description": "扩展数据(JSON对象)" + }, + { + "name": "province_name", + "type": "string", + "required": false, + "description": "寄件人省份" + }, + { + "name": "city_name", + "type": "string", + "required": false, + "description": "寄件人城市" + }, + { + "name": "district_name", + "type": "string", + "required": false, + "description": "寄件人区县" + }, + { + "name": "address", + "type": "string", + "required": false, + "description": "发件人详细地址" + }, + { + "name": "town_name", + "type": "string", + "required": false, + "description": "寄件人镇/街道" + }, + { + "name": "site_code", + "type": "string", + "required": false, + "description": "网点编码" + }, + { + "name": "product_type", + "type": "string", + "required": false, + "description": "产品类型/编码" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "description": "店铺名称" + }, + { + "name": "express", + "type": "object", + "required": false, + "description": "关联的系统快递对象(未关联时为 null)" + }, + { + "name": "express_name", + "type": "string", + "required": false, + "description": "快递名称(扁平字段)" + }, + { + "name": "express_polyapi_extra_info", + "type": "string", + "required": false, + "description": "PolyAPI扩展信息(扁平字段)" + }, + { + "name": "express_pdd_code", + "type": "string", + "required": false, + "description": "拼多多快递编码(扁平字段)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 参数不能为空" + }, + { + "code": "400", + "message": "至少需要提供一个可更新字段" + }, + { + "code": "400", + "message": "name 参数不能为空" + }, + { + "code": "400", + "message": "express_code 参数不能为空" + }, + { + "code": "400", + "message": "platform_code 参数不能为空" + }, + { + "code": "400", + "message": "字段校验失败(字段为空、长度超限或数值/JSON 格式非法)" + }, + { + "code": "400", + "message": "express_code 未匹配到系统快递编码" + }, + { + "code": "400", + "message": "platform_code 未匹配到打印平台编码" + }, + { + "code": "404", + "message": "快递接口不存在或无权限操作" + }, + { + "code": "404", + "message": "当前仓库下未找到对应店铺,无法同步快递接口 token" + } + ] + }, + { + "method": "setting.expressInterface.delete", + "description": "删除快递接口,支持 id 别名 interface_id / interfaceId;返回被删除记录 id 与所属 warehouse_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "快递接口ID;兼容 interface_id / interfaceId" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "description": "已删除记录 ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "记录所属仓库 ID" + }, + { + "name": "deleted", + "type": "boolean", + "description": "是否已删除,成功时为 true" + } + ], + "errors": [ + { + "code": "400", + "description": "id 为空或格式错误" + }, + { + "code": "404", + "description": "快递接口不存在或无权限操作" + } + ] + }, + { + "method": "index.getPrintPlatformList", + "description": "获取打印平台全量列表。供前端新增、修改快递接口时下拉选择使用;仅返回未删除且状态为 `ACTIVE` 的打印平台,不分页,按 `platform_name` 升序、`id` 升序返回。接口不校验额外鉴权或权限点,但需要登录态。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "全局调用结果标识,成功时为 `success`" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功时返回 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "返回消息,成功时通常为 `ok`" + }, + { + "name": "data", + "type": "array", + "required": true, + "description": "打印平台列表数组,不分页,仅包含未删除且状态为 `ACTIVE` 的平台;按 `platform_name` 升序、`id` 升序返回。每项字段如下:", + "children": [ + { + "name": "id", + "type": "number|null", + "description": "打印平台主键 ID;原始值为空时返回 `null`" + }, + { + "name": "code", + "type": "string", + "description": "打印平台编码,等同于 `platform_code`,服务端会标准化为大写" + }, + { + "name": "name", + "type": "string", + "description": "打印平台展示名称;若原始 `platform_name` 为空,则回退为 `platform_code`" + }, + { + "name": "value", + "type": "string", + "description": "与 `code` 相同,供前端选项组件直接使用" + }, + { + "name": "label", + "type": "string", + "description": "与 `name` 相同,供前端选项组件直接使用" + }, + { + "name": "platform_code", + "type": "string", + "description": "打印平台编码,大写返回" + }, + { + "name": "platform_name", + "type": "string|null", + "description": "打印平台名称;为空时前端可使用 `name` 或 `label` 展示" + }, + { + "name": "status", + "type": "string", + "description": "平台状态;当前接口仅返回 `ACTIVE`,若原始值缺失会兜底为 `ACTIVE`" + }, + { + "name": "remark", + "type": "string|null", + "description": "打印平台备注;无备注时返回 `null`" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "获取打印平台列表失败" + } + ] + } + ] + }, + { + "groupName": "账号管理模块", + "module": "setting.account", + "list": [ + { + "method": "setting.account.list", + "description": "查询当前主体下的工号基础信息列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态筛选,默认 1,仅查有效工号" + }, + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含已删除工号" + } + ], + "response": [ + { + "name": "data[]", + "type": "object", + "required": true, + "description": "工号列表项" + }, + { + "name": "data[].employee_id", + "type": "number", + "required": true, + "description": "工号ID" + }, + { + "name": "data[].account_id", + "type": "number", + "required": true, + "description": "账号ID" + }, + { + "name": "data[].store_id", + "type": "number", + "required": true, + "description": "主体ID" + }, + { + "name": "data[].real_name", + "type": "string", + "required": true, + "description": "工号姓名" + }, + { + "name": "data[].status", + "type": "number", + "required": true, + "description": "工号状态:1=启用,0=停用" + }, + { + "name": "data[].username", + "type": "string", + "required": true, + "description": "账号用户名" + }, + { + "name": "data[].phone", + "type": "string", + "required": true, + "description": "账号手机号" + }, + { + "name": "data[].email", + "type": "string", + "required": true, + "description": "账号邮箱" + }, + { + "name": "data[].avatar_file_id", + "type": "number", + "required": false, + "description": "头像文件ID,为空表示未设置" + }, + { + "name": "data[].avatar_url", + "type": "string", + "required": true, + "description": "头像访问地址" + } + ], + "errors": [ + { + "code": "400", + "description": "当前登录态缺少主体上下文(store_id)" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.account.add", + "description": "新增工号,按手机号复用或创建账号后绑定到当前主体", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "phone", + "type": "string", + "required": true, + "source": "body", + "description": "手机号,作为账号复用/创建依据" + }, + { + "name": "real_name", + "type": "string", + "required": true, + "source": "body", + "description": "工号姓名,新增时禁止直接使用保留名称" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "新账号用户名,不传时系统自动生成" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "新账号密码,不传默认 111111" + }, + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "工号角色,不传时继承当前操作人工号角色" + }, + { + "name": "email", + "type": "string", + "required": false, + "source": "body", + "description": "新账号邮箱,不传时按 username 自动生成" + } + ], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "新增或复用后的工号ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "绑定账号ID" + }, + { + "name": "role_id", + "type": "number", + "required": true, + "description": "绑定后的角色ID" + }, + { + "name": "is_new_account", + "type": "boolean", + "required": true, + "description": "是否为本次新建账号" + }, + { + "name": "phone", + "type": "string", + "required": true, + "description": "绑定账号手机号" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "绑定账号用户名" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、手机号格式错误、或直接使用保留名称" + }, + { + "code": "409", + "description": "手机号对应账号已禁用、手机号已绑定当前主体工号、或用户名重复" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.account.delete", + "description": "删除工号绑定关系,仅停用工号,不删除账号", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "source": "body", + "description": "要删除的工号ID" + } + ], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "被停用的工号ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "关联账号ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + }, + { + "name": "already_deleted", + "type": "boolean", + "required": false, + "description": "可选,true 表示该工号原本已停用" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或尝试删除当前登录工号" + }, + { + "code": "404", + "description": "工号不存在或无权限删除" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.account.update", + "description": "更新工号姓名和头像引用", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "source": "body", + "description": "要更新的工号ID" + }, + { + "name": "real_name", + "type": "string", + "required": false, + "source": "body", + "description": "更新后的工号姓名" + }, + { + "name": "file_id", + "type": "number", + "required": false, + "source": "body", + "description": "已有文件ID,作为头像引用" + } + ], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "更新后的工号ID" + }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "更新后的工号姓名" + }, + { + "name": "avatar_file_id", + "type": "number", + "required": false, + "description": "更新后的头像文件ID" + }, + { + "name": "avatar_url", + "type": "string", + "required": true, + "description": "更新后的头像地址" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,未提供更新项" + }, + { + "code": "404", + "description": "工号或头像文件不存在" + }, + { + "code": "500", + "description": "更新失败" + } + ] + }, + { + "method": "setting.account.getBindWechatCode", + "description": "为指定工号账号获取微信绑定码", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标账号ID,兼容 user_id / id" + }, + { + "name": "longPoll", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否开启长轮询等待状态变化,最长60秒" + }, + { + "name": "waitTimeoutMs", + "type": "number", + "required": false, + "source": "body", + "description": "等待超时毫秒数,后端自动封顶60000" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.account.unbindWechat", + "description": "为指定工号账号解绑微信", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标账号ID,兼容 user_id / id" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "权限管理模块", + "module": "setting.permission", + "list": [ + { + "method": "setting.permission.list", + "description": "查询权限树/权限列表,可附带指定角色的选中状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "角色ID;传入后返回 selected 标记" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "权限类型筛选:web_pages/pda_pages/btns/api/miniprogram_pages/block" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键字模糊搜索 path/name/meta_title" + }, + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含已停用权限" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.permission.add", + "description": "新增权限节点", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "path", + "type": "string", + "required": true, + "source": "body", + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "权限类型" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "权限名称" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "父级权限ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.permission.update", + "description": "更新权限节点信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "source": "body", + "description": "权限ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.permission.delete", + "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数组" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "角色管理模块", + "module": "setting.role", + "list": [ + { + "method": "setting.role.list", + "description": "获取当前主体可管理的角色树", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含已停用角色" + }, + { + "name": "includeSystem", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含系统角色域" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.permission", + "description": "获取角色权限树(兼容旧入口,等同于 setting.permission.list)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "角色ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.add", + "description": "新增角色并绑定权限集合", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_code", + "type": "string", + "required": true, + "source": "body", + "description": "角色编码" + }, + { + "name": "role_name", + "type": "string", + "required": true, + "source": "body", + "description": "角色名称" + }, + { + "name": "permission_ids", + "type": "array", + "required": true, + "source": "body", + "description": "权限ID数组,支持 [\"*\"]" + }, + { + "name": "pid", + "type": "number", + "required": false, + "source": "body", + "description": "父角色ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.update", + "description": "更新角色信息并重设权限集合", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": true, + "source": "body", + "description": "角色ID" + }, + { + "name": "permission_ids", + "type": "array", + "required": true, + "source": "body", + "description": "权限ID数组,角色权限需一次性提交" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.delete", + "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数组" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "商品模块", + "module": "stock", + "list": [ + { + "method": "stock.warehouse.list", + "description": "仓库商品列表查询(支持 where 条件与分页)", + "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 } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、barcode、prohibited_type、has_bound_item 等商品筛选字段。示例:where.barcode={operator:like,value:69}; where.prohibited_type={operator:eq,value:liquid}; where.has_bound_item={operator:eq,value:true}(已绑定外部商品)/ where.has_bound_item={operator:eq,value:false}(未绑定外部商品)。" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.externalList", + "description": "外仓商品列表查询。传入 warehouse_id 按仓库维度查,不传则按当前货主维度查(store_id);where/分页语义与 stock.warehouse.list 一致;where.keyword 支持模糊搜索(item_code/item_name/goods_code)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓库ID(可选,不传则取当前用户上下文)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,与 stock.warehouse.list 一致" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,与 stock.warehouse.list 语义一致。支持 keyword 快捷搜索:where.keyword={operator:like,value:'关键字'}" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.export", + "description": "提交导出任务,返回 task_id/status/progress/message/result/error/update_time", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象,与 stock.warehouse.list 的 where 语义一致;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象,支持 sortField/sortOrder 与 sort_field/sort_order 下划线别名兼容。" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段(兼容 sort.sortField)。" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名(兼容 sort.sort_field)。" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向(ASC/DESC,大小写不敏感)。" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名(兼容 sort.sort_order)。" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务 ID(后端生成的唯一标识)" + }, + { + "name": "status", + "type": "string", + "description": "任务状态,枚举:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "description": "进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "description": "额外提示信息或受理消息" + }, + { + "name": "result", + "type": "object", + "description": "任务成功时返回的结果对象(可选)" + }, + { + "name": "error", + "type": "string", + "description": "失败时的错误信息(可选)" + }, + { + "name": "update_time", + "type": "string", + "description": "最近一次状态更新时间,ISO8601 字符串(可选)" + } + ], + "errors": [ + { + "code": 400, + "message": "参数格式不正确或 where 条件非法" + }, + { + "code": 500, + "message": "导出任务提交失败" + } + ] + }, + { + "method": "stock.warehouse.exportTaskProgress", + "description": "按 task_id 查询导出任务进度,未找到时 status=not_found", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID,兼容 taskId" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务 ID" + }, + { + "name": "status", + "type": "string", + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "description": "进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "description": "额外提示信息" + }, + { + "name": "result", + "type": "object", + "description": "任务成功时返回的结果对象(可选)" + }, + { + "name": "error", + "type": "string", + "description": "失败时的错误信息(可选)" + }, + { + "name": "download_url", + "type": "string", + "description": "任务完成后可直接下载的文件地址(若有)" + }, + { + "name": "update_time", + "type": "string", + "description": "最近一次状态更新时间,ISO8601 字符串(可选)" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + }, + { + "code": 500, + "message": "查询失败或内部错误" + } + ] + }, + { + "method": "stock.warehouse.getProhibitedType", + "description": "查询违禁品类型列表(系统预设+仓库自定义)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getInfo", + "description": "查询仓库商品详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "need_recheck", + "type": "string", + "required": true, + "description": "是否需要复核:Y=需要复核,N=不需要复核" + } + ], + "errors": [] + }, + { + "method": "stock.warehouse.getStockDetail", + "description": "按库位/批次维度查询商品库存分布", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品库存ID(stock_warehouse.id)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,包含 page/pageSize" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "default": false, + "description": "是否按批次返回明细;true 返回每条明细,false 按库位合并" + } + ], + "response": [ + { + "name": "stockItem", + "type": "object", + "description": "商品概要,包含 id、item_code、item_name、sku_property、stock_unit、quantity、locked_quantity 等", + "required": true + }, + { + "name": "storageList", + "type": "array", + "description": "库存明细数组;group_by_batch=true 返回 wms_storage 明细(含 batch_no、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no 等),group_by_batch=false 时按库位合并(批次相关字段为 null),合并明细含 intercept_locked_quantity(拦截锁定数量,默认 0),available_quantity 统一口径 = quantity - locked_quantity - intercept_locked_quantity", + "required": true + }, + { + "name": "pagination", + "type": "object", + "description": "分页信息,包含 page、pageSize、total", + "required": true + } + ], + "errors": [] + }, + { + "method": "stock.warehouse.saveWarehouseStock", + "description": "更新仓库商品资料", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "need_recheck", + "type": "string", + "required": false, + "source": "body", + "description": "是否需要复核:Y=需要复核,N=不需要复核(非 Y/N 值会报错)" + }, + { + "name": "sn_code_rules / snCodeRules", + "type": "array", + "required": false, + "source": "body", + "description": "SN 码规则数组(整体覆盖保存,最多 20 条;传 [] 表示清空,不传该字段则保持原值)。元素三步:match_type/matchType=prefix(匹配前缀)或 suffix(匹配后缀);match_value/matchValue=要匹配的前缀或后缀字符串(去首尾空白后 1~64 字符);keep_mode/keepMode=full(整个扫码内容作为 SN 码)或 strip(去掉匹配到的前缀/后缀后再作为 SN 码)。多条按数组顺序匹配,命中第一条生效。格式非法(非数组、取值非法、match_value 为空或超长、规则重复、超 20 条)直接报错并指出第几条。存储于 wms_stock_warehouse.sn_code_rules(JSON),复核扫描视图 scanOrder 以 stock[].sn_code_rules 下发前端" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.createWarehouseStock", + "description": "新建仓库商品资料", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "need_recheck", + "type": "string", + "required": false, + "source": "body", + "description": "是否需要复核:Y=需要复核,N=不需要复核;缺省默认 Y(需要复核)" + }, + { + "name": "sn_code_rules / snCodeRules", + "type": "array", + "required": false, + "source": "body", + "description": "SN 码规则数组,创建时未传则存空数组。元素三步:match_type=prefix(前缀)或 suffix(后缀);match_value=要匹配的前缀或后缀字符串(1~64 字符);keep_mode=full(整个扫码内容作为 SN 码)或 strip(去掉前缀/后缀后作为 SN 码)。多条按数组顺序匹配,命中第一条生效;格式非法直接报错" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.import", + "description": "批量导入或更新仓库商品。请求体优先直接传入商品数据数组 JSON(主方式为数组);也兼容以 rows/items/list/data 包装。每项仅需包含商品相关字段;当 SKU 为空时创建新商品,SKU 非空时为更新操作;更新会写操作日志以便审计。未传 store_id 时默认使用当前上下文仓库/主体(ctx.user.store_id)。支持导入条码(barcode),新建和更新均生效,条码写入 wms_stock_barcodes 表。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "items / rows / list / data", + "type": "array", + "required": true, + "source": "body", + "description": "商品数组(主方式为直接传数组 []),也兼容对象包装:{ rows: [...] } / { items: [...] } / { list: [...] } / { data: [...] }。每项可使用下列字段别名:", + "children": [ + { + "name": "SKU / sku / id / item_id / itemId", + "type": "string|number", + "description": "SKU 或商品 ID(编辑/更新使用;为空时创建)" + }, + { + "name": "商品编码 / item_code / itemCode", + "type": "string", + "description": "商品编码" + }, + { + "name": "货物编码 / goods_code / goodsCode", + "type": "string", + "description": "货物编码(支持导入)" + }, + { + "name": "SKU规格 / sku_property / skuProperty", + "type": "string", + "description": "规格信息" + }, + { + "name": "库存单位 / stock_unit / stockUnit", + "type": "string", + "description": "库存单位" + }, + { + "name": "品牌 / brand_name / brandName", + "type": "string", + "description": "品牌" + }, + { + "name": "毛重 / gross_weight / grossWeight", + "type": "number", + "description": "毛重(数值,单位与系统一致)" + }, + { + "name": "标价 / tag_price / tagPrice", + "type": "number", + "description": "标价" + }, + { + "name": "零售价 / retail_price / retailPrice", + "type": "number", + "description": "零售价" + }, + { + "name": "是否需要复核 / need_recheck / needRecheck", + "type": "string", + "required": false, + "description": "是否需要复核,支持中文 需要/不需要 或 Y/N;缺省时新建按需要复核(Y)处理,更新保留原值" + }, + { + "name": "条码 / bar_code / barCode / barcodeList / barcode_list / barcode", + "type": "string", + "required": false, + "description": "条码列表,逗号分隔字符串,如 \"6901234567890,6901234567891\"。与导出格式一致。新建和更新均支持,条码存储在 wms_stock_barcodes 表。" + }, + { + "name": "store_id / storeId", + "type": "number", + "required": false, + "source": "body", + "description": "可选,货主/仓库 ID;未传入时使用当前上下文(ctx.user.store_id)" + } + ] + } + ], + "response": [ + { + "name": "total_count", + "type": "number", + "required": true, + "description": "解析到的总条目数" + }, + { + "name": "created_count", + "type": "number", + "required": true, + "description": "成功创建的新商品数" + }, + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "成功更新的商品数" + }, + { + "name": "fail_count", + "type": "number", + "required": true, + "description": "导入失败数" + }, + { + "name": "created_ids", + "type": "array", + "required": true, + "description": "创建成功的商品 ID 列表" + }, + { + "name": "updated_ids", + "type": "array", + "required": true, + "description": "更新成功的商品 ID 列表" + }, + { + "name": "fail_items", + "type": "array", + "required": true, + "description": "失败项明细数组,每项包含原始输入与错误信息" + } + ], + "errors": [ + { + "code": "400", + "message": "导入数据不能为空" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "导入行数据无效" + }, + { + "code": "500", + "message": "导入失败" + } + ] + }, + { + "method": "stock.warehouse.getBarcodes", + "description": "查询商品条码列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.saveWarehouseStockBarcode", + "description": "保存商品条码信息", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getStoreStocks", + "description": "查询仓库商品与货主关联列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.bindItem", + "description": "绑定货主商品关系", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.unbindItem", + "description": "解绑货主商品关系", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.checkItemCodeUnique", + "description": "检测商品编码唯一性。在同一仓库和货主下,排除商品自身后,判断商品编码是否已存在于未删除商品中。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID;默认使用当前登录主体/仓库上下文(ctx.user.store_id)" + }, + { + "name": "item_code", + "type": "string", + "required": true, + "source": "body", + "description": "要检测的商品编码" + }, + { + "name": "item_id", + "type": "number", + "required": false, + "source": "body", + "description": "当前商品ID(编辑场景用,排除自身);兼容字段名 id" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "兼容字段 id" + }, + { + "name": "owner_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID(对应表字段 store_id);兼容字段名 store_id" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "兼容字段 store_id" + } + ], + "response": [ + { + "name": "unique", + "type": "boolean", + "description": "true 表示编码唯一,false 表示已存在重复" + }, + { + "name": "isUnique", + "type": "boolean", + "description": "同 unique(兼容旧字段名)" + }, + { + "name": "message", + "type": "string", + "description": "重复时返回 '商品编码已存在',唯一时不返回该字段", + "required": false + } + ], + "errors": [] + }, + { + "method": "stock.warehouse.queryStockLogs", + "description": "查询库存操作日志", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "string", + "required": false, + "source": "body", + "description": "warehouseId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.handleBatchDelete", + "description": "批量删除仓库商品资料", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.deleteUnit", + "description": "删除库存单位", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.deleteProhibited", + "description": "删除违禁品类型", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.handleBatchChange", + "description": "批量修改仓库商品字段", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "要批量修改的仓库商品记录 ID 数组(stock_warehouse.id)", + "children": [ + { + "name": "id", + "type": "number", + "description": "单个记录 ID" + } + ] + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "body", + "description": "要修改的字段名,可选值:brand_name、prohibited_id、gross_weight、packing_requirements、managementFlags、stock_unit、need_recheck" + }, + { + "name": "value", + "type": "string|number|object", + "required": true, + "source": "body", + "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正整数,单位 g);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N';need_recheck 为 string,仅支持 'Y'(需要复核)/ 'N'(不需要复核)" + }, + { + "name": "values", + "type": "any", + "required": false, + "source": "body", + "description": "兼容字段:当前实现以 `value` 为准,不使用 `values`。若客户端历史使用 `values`,请切换为 `value`。" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功;405 表示参数/权限校验不通过;500 表示服务器错误" + }, + { + "name": "message", + "type": "string", + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "description": "成功时返回的结果对象", + "children": [ + { + "name": "affectedRows", + "type": "number", + "description": "被更新的记录数" + }, + { + "name": "ids", + "type": "array", + "description": "请求中传入的 ids 数组" + } + ] + } + ], + "errors": [ + { + "code": "405", + "description": "请选择要修改的商品(缺少 ids 或 ids 为空)" + }, + { + "code": "405", + "description": "不支持修改的字段: {method}" + }, + { + "code": "405", + "description": "修改值不能为空" + }, + { + "code": "405", + "description": "违禁品类型必须是数字" + }, + { + "code": "405", + "description": "毛重必须是有效的正数" + }, + { + "code": "405", + "description": "管理标识必须是对象格式 / 管理标识缺少字段 / 管理标识字段值必须是 'Y' 或 'N'" + }, + { + "code": "405", + "description": "部分商品不存在或无权修改: " + }, + { + "code": "405", + "description": "缺少仓库信息" + }, + { + "code": "500", + "description": "内部错误:批量修改失败" + } + ] + }, + { + "method": "stock.warehouse.getStockUnits", + "description": "查询可用库存单位(系统+仓库)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getUnitList", + "description": "查询当前仓库自定义单位列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.createProhibited", + "description": "新增违禁品类型", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.createUnit", + "description": "新增库存单位", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.search", + "description": "仓库商品关键字搜索,按 item_code / item_name / goods_code / 条形码模糊匹配,最多返回 50 条。新增 mode=\"combo\" 时切换为组合商品搜索模式。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,模糊匹配 item_code、item_name、goods_code 以及关联的 barcode;为空时返回全部(仍受 limit 50 限制)。mode=\"combo\" 时模糊匹配 combo_code / combo_name / custom_code" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID,传入时仅返回指定货主的商品" + }, + { + "name": "mode", + "type": "string", + "required": false, + "source": "body", + "description": "查询模式。传 \"combo\" 时搜索组合商品,不传或为空时保持原有 stock 搜索行为" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "当 mode=\"combo\" 时,按组合商品ID精确查询" + }, + { + "name": "custom_code", + "type": "string", + "required": false, + "source": "body", + "description": "当 mode=\"combo\" 时,按自定义编码模糊查询" + }, + { + "name": "with_stock", + "type": "boolean", + "required": false, + "source": "body", + "default": false, + "description": "是否返回关联库存数据(wms_storage),为 true 时每条商品新增 storage[] 字段。注意:mode=\"combo\" 时不生效" + }, + { + "name": "is_batch", + "type": "boolean", + "required": false, + "source": "body", + "default": false, + "description": "是否按批次明细返回库存,仅 with_stock=true 时生效。false(默认)按库位分组汇总;true 逐条返回批次明细。注意:mode=\"combo\" 时不生效" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功", + "required": false + }, + { + "name": "data", + "type": "array", + "description": "商品列表,每项包含以下字段。mode=\"combo\" 时返回组合商品结构", + "children": [ + { + "name": "id", + "type": "number", + "description": "商品库存ID(stock_warehouse.id)。mode=\"combo\" 时返回组合商品ID", + "required": false + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "goods_code", + "type": "string", + "description": "货物编码。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "sku_property", + "type": "string", + "description": "SKU 规格。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "stock_unit", + "type": "string", + "description": "库存单位。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "quantity", + "type": "number", + "description": "库存数量。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "locked_quantity", + "type": "number", + "description": "锁定数量。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "brand_name", + "type": "string", + "description": "品牌名称。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "item_type", + "type": "string", + "description": "商品类型。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "barcodes", + "type": "array", + "description": "商品条形码列表(string[])。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "images", + "type": "array", + "description": "商品图片URL列表(string[]),来自 wms_file_reference(business_type=stock)关联 wms_file.file_url,按 display_order 升序;无图片时为空数组。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "store_stock", + "type": "object", + "description": "关联的货主签约信息(LEFT JOIN),含 store_id、store_remask;无签约时为 null。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "is_shelf_life_mgmt", + "type": "boolean", + "description": "是否启用效期管理(true=启用)。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "shelf_life_days", + "type": "number", + "description": "商品标准效期/保质期(单位:天)。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "inbound_min_days", + "type": "number", + "description": "入库后最小可出库天数(单位:天)。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "outbound_min_days", + "type": "number", + "description": "出库前需保留的最小天数(单位:天)。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "remaining_threshold_days", + "type": "number", + "description": "剩余天数阈值,低于该值视为即将过期(单位:天)。mode=\"combo\" 时不返回此字段", + "required": false + }, + { + "name": "combo_code", + "type": "string", + "description": "组合商品编码,仅 mode=\"combo\" 时返回", + "required": false + }, + { + "name": "combo_name", + "type": "string", + "description": "组合商品名称,仅 mode=\"combo\" 时返回", + "required": false + }, + { + "name": "custom_code", + "type": "string", + "description": "自定义编码,仅 mode=\"combo\" 时返回", + "required": false + }, + { + "name": "items", + "type": "array", + "description": "子商品数组,仅 mode=\"combo\" 时返回。每项含 item_goods_sku_id(子商品ID)、item_quantity(子商品数量)", + "children": [ + { + "name": "item_goods_sku_id", + "type": "number", + "description": "子商品SKU ID", + "required": false + }, + { + "name": "item_quantity", + "type": "number", + "description": "子商品数量", + "required": false + } + ], + "required": false + }, + { + "name": "simpleNotation", + "type": "string", + "description": "子商品简写表示,格式为 stock_id|数量,多条用换行分隔。仅 mode=\"combo\" 时返回", + "required": false + }, + { + "name": "nameNotation", + "type": "string", + "description": "子商品名称表示,格式为【数量】商品名称,多条用换行分隔。仅 mode=\"combo\" 时返回", + "required": false + }, + { + "name": "storage", + "type": "array", + "description": "关联库存明细,仅 with_stock=true 时返回。is_batch=false 时按库位分组汇总,is_batch=true 时逐条返回批次明细。注意:mode=\"combo\" 时不返回", + "children_grouped": { + "description": "is_batch=false(默认):按库位分组汇总,每条包含以下字段", + "fields": [ + { + "name": "space_id", + "type": "number", + "description": "库位ID", + "required": false + }, + { + "name": "inventory_type", + "type": "string", + "description": "库存类型", + "required": false + }, + { + "name": "quantity", + "type": "number", + "description": "该库位总库存数量(合并同库位)", + "required": false + }, + { + "name": "locked_quantity", + "type": "number", + "description": "该库位总锁定数量", + "required": false + }, + { + "name": "intercept_locked_quantity", + "type": "number", + "description": "该库位拦截锁定数量(拦截确认时不归还可用、移入该字段)", + "required": false + }, + { + "name": "available_quantity", + "type": "number", + "description": "可用数量(quantity - locked_quantity - intercept_locked_quantity)", + "required": false + }, + { + "name": "space", + "type": "object", + "description": "库位信息子对象,含 id、space_code、custom_name", + "required": false + } + ] + }, + "children_batch": { + "description": "is_batch=true:逐条批次明细,每条包含以下字段", + "fields": [ + { + "name": "id", + "type": "number", + "description": "storage 记录ID", + "required": false + }, + { + "name": "stock_id", + "type": "number", + "description": "关联的商品库存ID", + "required": false + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID", + "required": false + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号", + "required": false + }, + { + "name": "inventory_type", + "type": "string", + "description": "库存类型", + "required": false + }, + { + "name": "quantity", + "type": "number", + "description": "库存数量", + "required": false + }, + { + "name": "locked_quantity", + "type": "number", + "description": "锁定数量", + "required": false + }, + { + "name": "intercept_locked_quantity", + "type": "number", + "description": "拦截锁定数量(默认 0)", + "required": false + }, + { + "name": "available_quantity", + "type": "number", + "description": "可用数量", + "required": false + }, + { + "name": "production_date", + "type": "string", + "description": "生产日期", + "required": false + }, + { + "name": "expiry_date", + "type": "string", + "description": "过期日期", + "required": false + }, + { + "name": "inbound_time", + "type": "string", + "description": "入库时间", + "required": false + }, + { + "name": "inbound_order_no", + "type": "string", + "description": "入库单号", + "required": false + }, + { + "name": "supplier_batch_no", + "type": "string", + "description": "供应商批次号", + "required": false + }, + { + "name": "created_at", + "type": "string", + "description": "记录创建时间", + "required": false + }, + { + "name": "space", + "type": "object", + "description": "库位信息子对象,含 id、space_code、custom_name", + "required": false + } + ] + }, + "required": false + } + ], + "required": false + }, + { + "name": "total", + "type": "number", + "description": "本次返回的记录条数(≤50)", + "required": false + } + ], + "errors": [] + }, + { + "method": "stock.transaction.list", + "description": "商品出入库流水列表查询(wms_stock_transaction),支持 where 条件筛选与分页,支持 keyword 快捷搜索", + "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 条件对象,支持以下字段:", + "children": [ + { + "name": "start_time", + "type": "string", + "required": false, + "description": "开始时间(闭区间下限),created_at >= start_time" + }, + { + "name": "end_time", + "type": "string", + "required": false, + "description": "结束时间(闭区间上限),created_at <= end_time" + }, + { + "name": "store_ids", + "type": "array", + "required": false, + "description": "货主ID数组,为空或未传表示不筛选" + }, + { + "name": "stock_ids", + "type": "array", + "required": false, + "description": "商品库存ID数组,为空或未传表示不筛选" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "description": "快捷搜索关键字,支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。内部解析为 stock_id 列表后以 IN 条件合并查询。与 stock_ids 互斥(keyword 优先)" + }, + { + "name": "transaction_type", + "type": "string", + "required": false, + "description": "流水类型:INBOUND=入库 / OUTBOUND=出库 / TRANSFER_OUT=移库出 / TRANSFER_IN=移库入 / LOCK=锁定" + }, + { + "name": "order_type", + "type": "string", + "required": false, + "description": "单据类型筛选" + }, + { + "name": "order_no", + "type": "string", + "required": false, + "description": "单据号筛选(支持模糊匹配)" + }, + { + "name": "batch_no", + "type": "string", + "required": false, + "description": "批次号筛选" + }, + { + "name": "entry_order_id", + "type": "number", + "required": false, + "description": "入库单ID筛选" + }, + { + "name": "receiving_id", + "type": "number", + "required": false, + "description": "收货单ID筛选" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "description": "发货单ID筛选" + } + ] + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象,支持 sortField / sortOrder 与 sort_field / sort_order 下划线别名兼容", + "children": [ + { + "name": "sortField", + "type": "string", + "required": false, + "description": "排序字段,白名单:created_at、quantity、stock_id、store_id。非法字段回退默认排序(created_at DESC)" + }, + { + "name": "sort_field", + "type": "string", + "required": false, + "description": "排序字段下划线别名(兼容 sort.sort_field),规则同 sortField" + }, + { + "name": "sortOrder", + "type": "string", + "required": false, + "description": "排序方向,ASC / DESC(大小写不敏感),非法值回退 DESC" + }, + { + "name": "sort_order", + "type": "string", + "required": false, + "description": "排序方向下划线别名(兼容 sort.sort_order),规则同 sortOrder" + } + ] + } + ], + "response": [ + { + "name": "list", + "type": "array", + "description": "流水记录列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "流水记录ID" + }, + { + "name": "created_at", + "type": "string", + "description": "流水创建时间" + }, + { + "name": "transaction_type", + "type": "string", + "description": "流水类型:INBOUND / OUTBOUND / TRANSFER_OUT / TRANSFER_IN / LOCK" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "stock_id", + "type": "number", + "description": "商品库存ID" + }, + { + "name": "quantity", + "type": "number", + "description": "变动数量" + }, + { + "name": "before_quantity", + "type": "number", + "description": "变更前库存" + }, + { + "name": "after_quantity", + "type": "number", + "description": "变更后库存" + }, + { + "name": "before_locked_quantity", + "type": "number", + "description": "变更前锁定库存" + }, + { + "name": "after_locked_quantity", + "type": "number", + "description": "变更后锁定库存" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + }, + { + "name": "order_type", + "type": "string", + "description": "单据类型" + }, + { + "name": "order_no", + "type": "string", + "description": "单据号" + }, + { + "name": "order_id", + "type": "number", + "description": "发货单ID" + }, + { + "name": "receiving_id", + "type": "number", + "description": "收货单ID" + }, + { + "name": "entry_order_id", + "type": "number", + "description": "入库单ID" + }, + { + "name": "operator_name", + "type": "string", + "description": "操作人名称" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + } + ] + }, + { + "name": "pagination", + "type": "object", + "description": "分页信息,包含 page、pageSize、total" + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] + }, + { + "method": "stock.transaction.storeList", + "description": "货主侧商品出入库流水列表查询(wms_stock_transaction),按货主 store_id 限定数据范围,支持 where 条件筛选与分页", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID,必传;用于限定查询的货主范围" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,包含 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,支持以下字段:", + "children": [ + { + "name": "start_time", + "type": "string", + "required": false, + "description": "开始时间(闭区间下限),created_at >= start_time" + }, + { + "name": "end_time", + "type": "string", + "required": false, + "description": "结束时间(闭区间上限),created_at <= end_time" + }, + { + "name": "warehouse_ids", + "type": "array", + "required": false, + "description": "仓库ID数组,为空或未传表示不按仓库筛选(但仅返回当前货主有权限的仓库数据)" + }, + { + "name": "stock_ids", + "type": "array", + "required": false, + "description": "商品库存ID数组,为空或未传表示不筛选" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "description": "快捷搜索关键字,支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。以当前登录货主 store_id 为主维度解析为 stock_id 列表后以 IN 条件合并查询。与 stock_ids 互斥(keyword 优先)" + }, + { + "name": "transaction_type", + "type": "string", + "required": false, + "description": "流水类型:INBOUND=入库 / OUTBOUND=出库 / TRANSFER_OUT=移库出 / TRANSFER_IN=移库入 / LOCK=锁定" + }, + { + "name": "order_type", + "type": "string", + "required": false, + "description": "单据类型筛选" + }, + { + "name": "order_no", + "type": "string", + "required": false, + "description": "单据号筛选(支持模糊匹配)" + }, + { + "name": "batch_no", + "type": "string", + "required": false, + "description": "批次号筛选" + }, + { + "name": "entry_order_id", + "type": "number", + "required": false, + "description": "入库单ID筛选" + }, + { + "name": "receiving_id", + "type": "number", + "required": false, + "description": "收货单ID筛选" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "description": "发货单ID筛选" + } + ] + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象,支持 sortField / sortOrder 与 sort_field / sort_order 下划线别名兼容", + "children": [ + { + "name": "sortField", + "type": "string", + "required": false, + "description": "排序字段,白名单:created_at、quantity、stock_id、warehouse_id。非法字段回退默认排序(created_at DESC)" + }, + { + "name": "sort_field", + "type": "string", + "required": false, + "description": "排序字段下划线别名(兼容 sort.sort_field),规则同 sortField" + }, + { + "name": "sortOrder", + "type": "string", + "required": false, + "description": "排序方向,ASC / DESC(大小写不敏感),非法值回退 DESC" + }, + { + "name": "sort_order", + "type": "string", + "required": false, + "description": "排序方向下划线别名(兼容 sort.sort_order),规则同 sortOrder" + } + ] + } + ], + "response": [ + { + "name": "list", + "type": "array", + "description": "流水记录列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "流水记录ID" + }, + { + "name": "created_at", + "type": "string", + "description": "流水创建时间" + }, + { + "name": "transaction_type", + "type": "string", + "description": "流水类型:INBOUND / OUTBOUND / TRANSFER_OUT / TRANSFER_IN / LOCK" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "stock_id", + "type": "number", + "description": "商品库存ID" + }, + { + "name": "quantity", + "type": "number", + "description": "变动数量" + }, + { + "name": "before_quantity", + "type": "number", + "description": "变更前库存" + }, + { + "name": "after_quantity", + "type": "number", + "description": "变更后库存" + }, + { + "name": "before_locked_quantity", + "type": "number", + "description": "变更前锁定库存" + }, + { + "name": "after_locked_quantity", + "type": "number", + "description": "变更后锁定库存" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + }, + { + "name": "order_type", + "type": "string", + "description": "单据类型" + }, + { + "name": "order_no", + "type": "string", + "description": "单据号" + }, + { + "name": "order_id", + "type": "number", + "description": "发货单ID" + }, + { + "name": "receiving_id", + "type": "number", + "description": "收货单ID" + }, + { + "name": "entry_order_id", + "type": "number", + "description": "入库单ID" + }, + { + "name": "operator_name", + "type": "string", + "description": "操作人名称" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + } + ] + }, + { + "name": "pagination", + "type": "object", + "description": "分页信息,包含 page、pageSize、total" + } + ], + "errors": [ + { + "code": 400, + "message": "store_id 不能为空" + }, + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] + } + ] + }, + { + "groupName": "拣货模块", + "module": "pick", + "list": [ + { + "method": "pick.query", + "description": "按 keyword(运单号或波次号)获取或创建当前用户的拣货任务:命中同用户活动任务返回 existing;无活动任务则创建并返回 created;若活动任务归属他人则返回冲突提示。新增领单前置校验:扫描命中的波次属于普通波次(wms_wave_batch.source=0)时,若波次内存在未领料订单(claim_status != fin)则返回 400 并携带 action=wave_claim 提示「订单未领料,请先领料后再拣货」(pick.waveClaimScan),中止拣货任务创建;未打印的拦截订单未领料不阻隔拣货,已打印(print_status=fin)的拦截订单面单实物已流出、仍需先领料登记;创建任务计算拣货数量时剔除未领料订单(拦截订单也不入任务)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword", + "type": "string", + "required": true, + "source": "body", + "description": "关键字,支持运单号或波次号。" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务ID。" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:existing(命中当前用户已有活动任务)或 created(新建成功)。" + }, + { + "name": "tip", + "type": "string", + "required": true, + "description": "提示文案。" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误或目标波次不满足建任务条件(如 keyword 为空、缺少仓库上下文、目标波次信息不完整、散单波次无可用订单);普通波次(source=0)存在需要领料但未领料的订单时中止建任务并提示「订单未领料,请先领料后再拣货」(失败 data 含 action=wave_claim、wave_id、wave_no、wave_type、wave_source、pick_mode、unclaimed_order_count、intercepted_order_count、total_order_count;未打印的拦截订单未领料不阻隔,已打印的拦截订单仍需先领料)。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 404, + "message": "关键字未命中有效运单/波次,或命中的订单/波次不属于当前仓库。" + }, + { + "code": 409, + "message": "目标波次已存在他人创建的活动任务(失败 data 含 task_id、task_owner_id、task_owner_name)。" + }, + { + "code": 500, + "message": "内部错误(如分表模型不可用或任务创建异常)。" + } + ] + }, + { + "method": "pick.wavePickComplete", + "description": "按波次ID一键完成整个波次的拣货。内部先按 wave_id 定位波次,复用 query 的去重与任务创建逻辑:若波次已有当前用户的活动任务则直接复用并完成;已有他人活动任务返回 409;已完成则返回 already_completed;否则新建任务(source=2 后台抓取)后在内部调用 wavePickTaskComplete(mode=1 全部确认)完成拣货并回写任务进度。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "source": "body", + "description": "波次ID(wms_wave_batch.wave_id)" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "操作结果:completed(拣货完成)或 already_completed(波次已存在完成任务)" + }, + { + "name": "tip", + "type": "string", + "required": true, + "description": "提示文案" + }, + { + "name": "confirmed_order_ids", + "type": "array", + "required": false, + "description": "已确认完成的订单ID列表" + }, + { + "name": "is_completed", + "type": "boolean", + "required": false, + "description": "任务是否已全部完成" + }, + { + "name": "progress", + "type": "object", + "required": false, + "description": "任务进度(total_orders / picked_orders / pending_orders)" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误(wave_id 为空/非正整数、缺少仓库上下文、波次信息不完整、波次下无可用订单)。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 404, + "message": "波次不存在或不属于当前仓库。" + }, + { + "code": 409, + "message": "当前波次已存在他人创建的活动任务(失败 data 含 task_id、task_owner_id、task_owner_name)。" + }, + { + "code": 500, + "message": "任务创建失败或拣货完成失败。" + } + ] + }, + { + "method": "pick.wavePickTaskDetail", + "description": "按任务ID获取拣货任务详情。查询前会校验任务内订单是否全部完成快递号与储位分配:若存在未分配快递号或未分配储位订单,将返回 400 并在 data 中返回 action 与 order_ids 供前端触发一键分配;详情响应新增中间态进度语义(task.is_completed、task.progress 与顶层 is_completed),用于前端判断是否已完成与展示阶段进度;仅允许任务的 pick_user_id 与当前登录用户一致时返回详情。当 pick_mode=1(团购小波次)或 pick_mode=5(团购大波次)时,picking_details 字段不返回以减少带宽。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "wms_wave_pick_task 主键 ID" + } + ], + "response": [ + { + "name": "task", + "type": "object", + "description": "拣货任务主表(精简字段)", + "children": [ + { + "name": "task_id", + "type": "number", + "description": "任务ID", + "required": false + }, + { + "name": "task_no", + "type": "string", + "description": "任务编号", + "required": false + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号,从 wms_wave_pick_task_wave 关联 wms_wave_batch 获取;无关联波次时为空字符串", + "required": false + }, + { + "name": "status", + "type": "number", + "description": "任务状态", + "required": false + }, + { + "name": "pick_mode", + "type": "number", + "description": "拣货模式", + "required": false + }, + { + "name": "start_at", + "type": "string", + "description": "开始时间(ISO 字符串或 null)", + "required": false + }, + { + "name": "finish_at", + "type": "string", + "description": "完成时间(ISO 字符串或 null)", + "required": false + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号", + "required": false + }, + { + "name": "is_completed", + "type": "boolean", + "description": "任务是否已完成(订单维度全部已拣或任务状态已进入完成态)", + "required": false + }, + { + "name": "progress", + "type": "object", + "description": "任务订单拣货进度统计", + "required": false, + "children": [ + { + "name": "total_orders", + "type": "number", + "description": "任务订单总数", + "required": false + }, + { + "name": "picked_orders", + "type": "number", + "description": "已确认拣货订单数", + "required": false + }, + { + "name": "pending_orders", + "type": "number", + "description": "待确认拣货订单数", + "required": false + } + ] + } + ], + "required": false + }, + { + "name": "is_completed", + "type": "boolean", + "description": "任务是否已完成(与 task.is_completed 含义一致,便于前端直接判断)", + "required": false + }, + { + "name": "boxes", + "type": "array", + "description": "箱列表;包含用于前端展示与拣货进度的统计字段", + "children": [ + { + "name": "task_id", + "type": "number", + "description": "任务ID", + "required": false + }, + { + "name": "box_id", + "type": "number", + "description": "箱ID", + "required": false + }, + { + "name": "box_no", + "type": "string", + "description": "箱编码", + "required": false + }, + { + "name": "box_type", + "type": "number", + "description": "箱类型", + "required": false + }, + { + "name": "status", + "type": "number", + "description": "箱状态", + "required": false + }, + { + "name": "ref_label", + "type": "string", + "description": "箱参考标签或关联业务标识(用于前端定位/关联)", + "required": false + }, + { + "name": "required_qty", + "type": "number", + "description": "箱内需要拣货的总数量", + "required": false + }, + { + "name": "picked_qty", + "type": "number", + "description": "当前已完成拣货的数量", + "required": false + } + ], + "required": false + }, + { + "name": "picking_details", + "type": "array", + "description": "拣货明细列表(按库位/商品/数量拆分),用于从明细视角展示拣货要求。注意:当 pick_mode=1(团购小波次)或 pick_mode=5(团购大波次)时该字段不返回,减少带宽浪费;其他 pick_mode(2/3/4)正常返回。", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID", + "required": false + }, + { + "name": "order_item_id", + "type": "number", + "description": "订单行ID", + "required": false + }, + { + "name": "quantity", + "type": "number", + "description": "本行需拣货数量", + "required": false + }, + { + "name": "storage_id", + "type": "number", + "description": "仓库ID", + "required": false + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID", + "required": false + }, + { + "name": "space_name", + "type": "string", + "description": "库位名称", + "required": false + }, + { + "name": "location_space", + "type": "object", + "description": "库位扩展信息(当存在时返回)", + "children": [ + { + "name": "space_code", + "type": "string", + "description": "库位编码", + "required": false + }, + { + "name": "custom_name", + "type": "string", + "description": "库位自定义名称", + "required": false + }, + { + "name": "custom_barcode", + "type": "string", + "description": "库位自定义条码", + "required": false + }, + { + "name": "pick_sequence", + "type": "number", + "description": "拣货序列,用于路线/优先级排序", + "required": false + }, + { + "name": "pick_priority", + "type": "number", + "description": "拣货优先级(数值越小优先级越高)", + "required": false + } + ], + "required": false + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码", + "required": false + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称", + "required": false + }, + { + "name": "stock_id", + "type": "number", + "description": "库存记录ID(stock 主键)", + "required": false + }, + { + "name": "plan_qty", + "type": "number", + "description": "计划拣货数量(用于与实际拣货对比)", + "required": false + }, + { + "name": "item_snapshot", + "type": "object", + "description": "商品快照(下单时的商品信息,可能包含规格/属性等)", + "required": false + } + ], + "required": false + }, + { + "name": "picking_summary", + "type": "object", + "description": "对 picking_details 的汇总信息,用于统计与前端显示", + "children": [ + { + "name": "total_lines", + "type": "number", + "description": "明细行数(picking_details.length)", + "required": false + }, + { + "name": "total_qty", + "type": "number", + "description": "明细总数量(quantity 汇总)", + "required": false + }, + { + "name": "distinct_spaces", + "type": "number", + "description": "涉及的不同库位数量", + "required": false + }, + { + "name": "distinct_items", + "type": "number", + "description": "涉及的不同商品数量", + "required": false + } + ], + "required": false + }, + { + "name": "picking_view", + "type": "object", + "description": "按 pick_mode 区分的 picking_view 形态输出(五种形态);用于前端按任务类型展示聚合视图。", + "children": [ + { + "name": "mode_code", + "type": "number", + "description": "拣货视图模式编码,与 task.pick_mode 对应", + "required": false + }, + { + "name": "mode_name", + "type": "string", + "description": "拣货视图模式名称", + "required": false + }, + { + "name": "require_box_allocations", + "type": "boolean", + "description": "当前模式是否需要箱分配;pick_mode=1/3/4 时为 true,pick_mode=2/5 时为 false", + "required": false + }, + { + "name": "group_by", + "type": "string", + "description": "分组字段,示例值:\"space+item\"", + "required": false + }, + { + "name": "sort_by", + "type": "array", + "description": "排序字段数组,典型为 [\"pick_sequence\",\"pick_priority\",\"space_id\",\"item_code\"]", + "required": false + }, + { + "name": "items", + "type": "array", + "description": "分组后的拣货项数组(按库位+商品聚合)", + "children": [ + { + "name": "space_id", + "type": "number", + "description": "库位 ID", + "required": false + }, + { + "name": "space_name", + "type": "string", + "description": "库位名称", + "required": false + }, + { + "name": "location_space", + "type": "object", + "description": "库位扩展信息(同 picking_details.location_space 结构)", + "children": [ + { + "name": "space_code", + "type": "string", + "description": "库位编码", + "required": false + }, + { + "name": "custom_name", + "type": "string", + "description": "库位自定义名称", + "required": false + }, + { + "name": "custom_barcode", + "type": "string", + "description": "库位自定义条码", + "required": false + }, + { + "name": "pick_sequence", + "type": "number", + "description": "拣货序列,用于路线/优先级排序", + "required": false + }, + { + "name": "pick_priority", + "type": "number", + "description": "拣货优先级(数值越小优先)", + "required": false + } + ], + "required": false + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码", + "required": false + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称", + "required": false + }, + { + "name": "stock_id", + "type": "number", + "description": "库存记录ID(stock 主键)", + "required": false + }, + { + "name": "total_qty", + "type": "number", + "description": "该库位该商品的总需拣货数量", + "required": false + }, + { + "name": "pick_requirements", + "type": "string", + "description": "拣货要求(商品资料维护;merge_requirements=Y 时回退为打包要求),团购形态(pick_mode=1/5)不返回 picking_details,前端以此字段展示拣货要求", + "required": false + }, + { + "name": "box_allocations", + "type": "array", + "description": "与该库位/商品相关的箱分配列表(当 require_box_allocations=true 时返回)", + "children": [ + { + "name": "box_id", + "type": "number", + "description": "箱ID", + "required": false + }, + { + "name": "box_no", + "type": "string", + "description": "箱编码", + "required": false + }, + { + "name": "box_type", + "type": "number", + "description": "箱类型", + "required": false + }, + { + "name": "required_qty", + "type": "number", + "description": "该箱分配需要拣货的数量", + "required": false + }, + { + "name": "picked_qty", + "type": "number", + "description": "该箱已完成拣货的数量", + "required": false + }, + { + "name": "allocated_qty", + "type": "number", + "description": "该箱已分配的数量(由后端分配)", + "required": false + } + ], + "required": false + } + ], + "required": false + } + ], + "required": false + } + ], + "errors": [ + { + "code": 400, + "message": "业务校验失败:包含 task_id 参数不合法、未分配快递号(data.action=assign_express, data.order_ids)或未分配储位(data.action=assign_storage, data.order_ids)等场景。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 403, + "message": "当前操作人与任务创建人不一致,无权查看。" + }, + { + "code": 404, + "message": "拣货任务不存在。" + }, + { + "code": 500, + "message": "查询失败。" + } + ] + }, + { + "method": "pick.wavePickTaskSubmit", + "description": "提交拣货任务中间态。用于保存阶段性数据到任务 ext_json.pick_intermediate,并在任务初始状态时自动推进到进行中。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货任务ID" + }, + { + "name": "payload", + "type": "object", + "required": false, + "source": "body", + "description": "中间态业务数据对象,将原样保存到 ext_json.pick_intermediate.payload" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "提交结果状态,固定为 submitted" + }, + { + "name": "is_completed", + "type": "boolean", + "required": true, + "description": "当前任务是否已完成" + }, + { + "name": "progress", + "type": "object", + "required": true, + "description": "任务订单拣货进度统计", + "children": [ + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "任务订单总数" + }, + { + "name": "picked_orders", + "type": "number", + "required": true, + "description": "已确认拣货订单数" + }, + { + "name": "pending_orders", + "type": "number", + "required": true, + "description": "待确认拣货订单数" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "参数或业务状态不满足提交条件(如 task_id 不合法、缺少仓库上下文、任务已完成/已取消)。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 403, + "message": "当前操作人与任务创建人不一致,无权操作。" + }, + { + "code": 404, + "message": "拣货任务不存在。" + }, + { + "code": 500, + "message": "提交失败。" + } + ] + }, + { + "method": "pick.wavePickTaskComplete", + "description": "完全提交拣货任务。支持 mode=1 全部确认,mode=2 部分确认(需传 order_ids)。提交后根据是否全部完成自动推进任务状态。后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。目标订单中已进入拦截流程的订单直接跳过(不完成拣货、不扣减库存、不报错);其中未打印面单(print_status=none/空)的拦截订单自动移出波次(wave_id 清零、删波次索引、回写波次统计、移除任务订单关联与篮子明细,并写 ORDER_WAVE_REMOVE 日志、触发策略快扫),已打印面单(print_status!=none)的拦截订单保持不动(保留波次/任务关联,需人工 wave.batchRemoveOrders 处理),返回 kept_intercepted_order_ids。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货任务ID" + }, + { + "name": "mode", + "type": "number", + "required": false, + "source": "body", + "description": "提交模式:1=全部确认(默认),2=部分确认" + }, + { + "name": "order_ids", + "type": "array", + "required": false, + "source": "body", + "description": "部分确认模式(mode=2)时必填;仅会确认命中当前任务的订单ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务ID" + }, + { + "name": "mode", + "type": "number", + "required": true, + "description": "实际生效的提交模式(1=全部确认,2=部分确认)" + }, + { + "name": "confirmed_order_ids", + "type": "array", + "required": true, + "description": "本次成功确认的订单ID列表" + }, + { + "name": "skipped_intercepted_order_ids", + "type": "array", + "required": true, + "description": "被跳过(已进入拦截流程)的订单ID列表" + }, + { + "name": "skipped_intercepted_orders", + "type": "array", + "required": true, + "description": "被跳过的拦截订单明细,每项含 order_id、intercept_status、print_status" + }, + { + "name": "removed_from_wave_order_ids", + "type": "array", + "required": true, + "description": "被自动移出波次的未打印拦截订单ID列表" + }, + { + "name": "kept_intercepted_order_ids", + "type": "array", + "required": true, + "description": "已打印面单保持不动的拦截订单ID列表(不自动移出波次,需人工 wave.batchRemoveOrders 处理)" + }, + { + "name": "is_completed", + "type": "boolean", + "required": true, + "description": "提交后任务是否已完成" + }, + { + "name": "progress", + "type": "object", + "required": true, + "description": "任务订单拣货进度统计", + "children": [ + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "任务订单总数" + }, + { + "name": "picked_orders", + "type": "number", + "required": true, + "description": "已确认拣货订单数" + }, + { + "name": "pending_orders", + "type": "number", + "required": true, + "description": "待确认拣货订单数" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "参数或业务状态不满足提交条件(如 task_id 不合法、mode 非 1/2、部分确认未传 order_ids、任务下无可确认订单等)。后台抓取任务(source=2)未绑定拣货车时拒绝提交:\"后台抓取任务必须先绑定拣货车才能提交\"。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 403, + "message": "当前操作人与任务创建人不一致,无权操作。" + }, + { + "code": 404, + "message": "拣货任务不存在。" + }, + { + "code": 500, + "message": "提交失败。" + } + ] + }, + { + "method": "pick.waveClaimScan", + "description": "扫描面单号领取整波(领料)。按面单号(运单号)定位待处理订单表中的订单后反查订单所在波次,仅对普通波次(wms_wave_batch.source=0,含团购/散单)支持整波领料:命中后将该波次下全部未领单订单(未打印的拦截订单除外)claim_status 置为 fin(领料完成)并写入 ORDER_WAVE_CLAIM 订单操作日志,返回波次ID与波次编码;波次下存在未打印订单(print_status != fin,拦截订单除外)时返回 400「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count、intercepted_order_count,拦截订单未打印不阻隔领料);拦截订单跳过领料的口径按打印状态区分:未打印的拦截订单跳过领料(不置为 fin),已打印(print_status=fin)的拦截订单面单实物已随波次流出并被领取,不再受拦截影响、照常置为领料完成;策略抓取波次(source=1/2)无需领料,返回 400 并提示「该波次为抓取波次,无需领料」(失败 data 含 no_claim_needed=true、wave_id、wave_no);面单号查不到订单或订单不在待处理订单表返回 404 提示无记录;波次内订单已全部领料时返回 already_claimed 幂等结果并提示已领料,此时若波次表 claim_time 为空(历史领单/旧版拦截跳过导致)会补写一次领料时间,避免 order.wave.confirmPrintUnclaimedWaveCount 长期把该波次计为「已打印未领料」。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_no", + "type": "string", + "required": true, + "source": "body", + "description": "面单号(运单号,wms_order_express.waybill_code)" + } + ], + "response": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "wave_type", + "type": "number", + "required": true, + "description": "波次类型:1-团购 2-散单" + }, + { + "name": "wave_source", + "type": "number", + "required": true, + "description": "波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务" + }, + { + "name": "pick_mode", + "type": "number", + "required": true, + "description": "拣货模式:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次(0 表示无关联拣货任务)" + }, + { + "name": "matched_order_id", + "type": "number", + "required": true, + "description": "面单号命中的订单ID" + }, + { + "name": "waybill_no", + "type": "string", + "required": true, + "description": "扫描的面单号" + }, + { + "name": "total_order_count", + "type": "number", + "required": true, + "description": "波次下订单总数" + }, + { + "name": "intercepted_order_count", + "type": "number", + "required": true, + "description": "波次下拦截订单数(未打印的拦截订单跳过领料,其未打印/未领料状态不阻隔领料与拣货;已打印的拦截订单照常领料)" + }, + { + "name": "intercept_skipped_order_count", + "type": "number", + "required": true, + "description": "因处于拦截流程且未打印而跳过领料的订单数" + }, + { + "name": "claimed_order_count", + "type": "number", + "required": true, + "description": "本次置为 fin 的订单数(已全部领料时返回 0)" + }, + { + "name": "claimed_intercepted_order_count", + "type": "number", + "required": true, + "description": "本次置为 fin 的已打印拦截订单数(已全部领料时返回本人已领的已打印拦截订单数)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "操作结果:claimed(整波领料完成)或 already_claimed(波次已领料)" + }, + { + "name": "tip", + "type": "string", + "required": true, + "description": "提示文案" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误(waybill_no 为空、缺少仓库上下文、订单未分配波次、波次下无可用订单);波次下存在未打印订单(拦截订单除外)返回「波次未打印,禁止领料」(data 含 wave_id、wave_no、unprinted_order_count、intercepted_order_count);策略抓取波次(source=1/2)返回「该波次为抓取波次,无需领料」(data 含 no_claim_needed=true、wave_id、wave_no);其余不支持类型返回通用提示。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 404, + "message": "未查询到该面单号对应的订单(无记录)、订单不在待处理订单表(无记录),或波次不存在/不属于当前仓库。" + }, + { + "code": 500, + "message": "运单模型/订单模型不可用或内部错误。" + } + ] + } + ] + }, + { + "groupName": "拣货车模块", + "module": "pickCart", + "list": [ + { + "method": "pickCart.scan", + "description": "按拣货车条码/编码查询拣货车信息,供 PDA 扫码后用于拣货任务绑定。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_code", + "type": "string", + "required": true, + "source": "body", + "description": "拣货车条码/编码" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "拣货车ID" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "cart_code", + "type": "string", + "required": true, + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "拣货车状态:0-停用 1-启用" + }, + { + "name": "current_task_id", + "type": "number", + "required": false, + "description": "当前绑定任务ID,无绑定时为 null" + }, + { + "name": "current_task_no", + "type": "string", + "required": false, + "description": "当前绑定任务编号,无绑定时为 null" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_code 未传或缺少仓库上下文。" + }, + { + "code": 404, + "message": "拣货车不存在。" + }, + { + "code": 500, + "message": "查询失败。" + } + ] + }, + { + "method": "pickCart.bindTaskCart", + "description": "绑定拣货任务与拣货车。支持传 cart_id 或 cart_code;若任务已绑定其他拣货车则自动改绑,若目标拣货车已绑定其他活动任务则返回冲突。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货任务ID" + }, + { + "name": "cart_id", + "type": "number", + "required": false, + "source": "body", + "description": "拣货车ID,和 cart_code 二选一即可" + }, + { + "name": "cart_code", + "type": "string", + "required": false, + "source": "body", + "description": "拣货车编码,和 cart_id 二选一即可" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务ID" + }, + { + "name": "task_no", + "type": "string", + "required": true, + "description": "拣货任务编号" + }, + { + "name": "cart", + "type": "object", + "required": true, + "description": "绑定后的拣货车信息", + "children": [ + { + "name": "cart_id", + "type": "number", + "description": "拣货车ID" + }, + { + "name": "cart_code", + "type": "string", + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "description": "拣货车名称" + }, + { + "name": "current_task_id", + "type": "number", + "description": "当前绑定任务ID" + }, + { + "name": "current_task_no", + "type": "string", + "description": "当前绑定任务编号" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "参数不合法、任务已完成/已取消、拣货车已停用等业务校验失败。" + }, + { + "code": 401, + "message": "未获取到操作人上下文。" + }, + { + "code": 403, + "message": "当前操作人与任务创建人不一致,或任务不属于当前仓库。" + }, + { + "code": 404, + "message": "拣货任务或拣货车不存在。" + }, + { + "code": 409, + "message": "目标拣货车已绑定其他活动任务。" + }, + { + "code": 500, + "message": "绑定失败。" + } + ] + }, + { + "method": "pickCart.create", + "description": "创建拣货车。拣货车编码在当前仓库内不可重复。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_code", + "type": "string", + "required": true, + "source": "body", + "description": "拣货车编码,当前仓库内唯一" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "source": "body", + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:0-停用 1-启用,默认 1" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "拣货车ID" + }, + { + "name": "cart_code", + "type": "string", + "required": true, + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "状态:0-停用 1-启用" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_code 未传或缺少仓库上下文。" + }, + { + "code": 409, + "message": "拣货车编码已存在,请勿重复。" + }, + { + "code": 500, + "message": "创建失败。" + } + ] + }, + { + "method": "pickCart.update", + "description": "更新拣货车。支持修改编码、名称、状态;若修改后的编码与当前仓库内其他拣货车重复则拦截。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货车ID" + }, + { + "name": "cart_code", + "type": "string", + "required": false, + "source": "body", + "description": "新的拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "source": "body", + "description": "新的拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "新的状态:0-停用 1-启用" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "拣货车ID" + }, + { + "name": "cart_code", + "type": "string", + "required": true, + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "状态:0-停用 1-启用" + } + ], + "errors": [ + { + "code": 400, + "message": "参数不合法,或拣货车已绑定任务不能停用。" + }, + { + "code": 404, + "message": "拣货车不存在。" + }, + { + "code": 409, + "message": "拣货车编码已存在,请勿重复。" + }, + { + "code": 500, + "message": "更新失败。" + } + ] + }, + { + "method": "pickCart.delete", + "description": "删除拣货车。若拣货车当前已绑定任务或存在有效绑定记录,则不允许删除。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货车ID" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "被删除的拣货车ID" + }, + { + "name": "deleted", + "type": "boolean", + "required": true, + "description": "是否删除成功,固定为 true" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_id 不合法,或拣货车当前已绑定任务/存在有效绑定记录。" + }, + { + "code": 404, + "message": "拣货车不存在。" + }, + { + "code": 500, + "message": "删除失败。" + } + ] + }, + { + "method": "pickCart.batchDelete", + "description": "批量删除拣货车。已绑定任务的拣货车将被跳过,不会删除。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "拣货车ID列表,如 [1,2,3]" + } + ], + "response": [ + { + "name": "deleted_ids", + "type": "array", + "required": true, + "description": "成功删除的拣货车ID列表" + }, + { + "name": "skipped_ids", + "type": "array", + "required": true, + "description": "跳过的拣货车ID列表(已绑定任务或存在有效绑定记录)" + }, + { + "name": "deleted_count", + "type": "number", + "required": true, + "description": "成功删除数量" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "跳过数量" + } + ], + "errors": [ + { + "code": 400, + "message": "ids 参数不合法或缺少仓库上下文。" + }, + { + "code": 500, + "message": "批量删除失败。" + } + ] + }, + { + "method": "pickCart.detail", + "description": "查询拣货车详情。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货车ID" + } + ], + "response": [ + { + "name": "cart_id", + "type": "number", + "required": true, + "description": "拣货车ID" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "cart_code", + "type": "string", + "required": true, + "description": "拣货车编码" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "拣货车名称" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "状态:0-停用 1-启用" + }, + { + "name": "current_task_id", + "type": "number", + "required": false, + "description": "当前绑定任务ID,无绑定时为 null" + }, + { + "name": "current_task_no", + "type": "string", + "required": false, + "description": "当前绑定任务编号,无绑定时为 null" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_id 不合法或缺少仓库上下文。" + }, + { + "code": 404, + "message": "拣货车不存在。" + }, + { + "code": 500, + "message": "查询失败。" + } + ] + }, + { + "method": "pickCart.list", + "description": "分页查询拣货车列表。支持按关键字、状态、当前绑定任务筛选。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize,默认 1/20" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,支持 keyword、status、current_task_id" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "拣货车列表,元素结构同 pickCart.detail 返回" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,包含 page、pageSize、total、totalPages" + } + ], + "errors": [ + { + "code": 400, + "message": "缺少仓库上下文。" + }, + { + "code": 500, + "message": "查询失败。" + } + ] + }, + { + "method": "pickCart.codeDuplicateCheck", + "description": "拣货车编码查重。支持传 exclude_cart_id 排除自身,用于编辑场景判断是否与其他车重复。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "cart_code", + "type": "string", + "required": true, + "source": "body", + "description": "待校验的拣货车编码" + }, + { + "name": "exclude_cart_id", + "type": "number", + "required": false, + "source": "body", + "description": "需排除的拣货车ID,通常为当前编辑记录自身ID" + } + ], + "response": [ + { + "name": "duplicated", + "type": "boolean", + "required": true, + "description": "是否存在重复编码" + }, + { + "name": "cart_id", + "type": "number", + "required": false, + "description": "命中的重复拣货车ID,无重复时为 null" + }, + { + "name": "cart_code", + "type": "string", + "required": false, + "description": "命中的重复编码,无重复时为 null" + }, + { + "name": "cart_name", + "type": "string", + "required": false, + "description": "命中的重复拣货车名称,无重复时为 null" + }, + { + "name": "status", + "type": "number", + "required": false, + "description": "命中的重复拣货车状态,无重复时为 null" + } + ], + "errors": [ + { + "code": 400, + "message": "cart_code 未传或缺少仓库上下文。" + }, + { + "code": 500, + "message": "校验失败。" + } + ] + } + ] + }, + { + "groupName": "收货单模块", + "module": "storage_receiving", + "list": [ + { + "method": "storage.receiving.getReceivingList", + "description": "查询收货单列表,支持分页和多条件筛选。支持 filterDepleted 参数过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。支持 entry_order_id 参数按入库单商品交集过滤。支持 stock_query_where 参数按商品条码/编码/ID 过滤。列表每项包含 store_name(货主名称,实时解析:合约表 wms_store_warehouse.store_remask 优先、无合约或备注为空时回退 wms_store.company_name 公司全称,均无时保留主表快照,可能为空字符串)。", + "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 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、status、store_id、日期区间等字段。示例:where.status={operator:eq,value:finished}; where.store_id={operator:eq,value:1001}; where.create_time_start={value:2026-03-01}。" + }, + { + "name": "filterDepleted", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满,即 available=0)。默认 false。" + }, + { + "name": "entry_order_id", + "type": "number", + "required": false, + "source": "body", + "description": "按入库单商品交集过滤。传入入库单 ID 后,只返回至少有一条收货明细的 system_product_id 在入库单明细中存在的收货单。与 filterDepleted 可组合使用。不传则不过滤。" + }, + { + "name": "stock_query_where", + "type": "string|string[]", + "required": false, + "source": "body", + "description": "按商品维度过滤。传入字符串或字符串数组后搜索商品条码(wms_stock_barcodes.barcode)、商品编码(wms_stock_warehouse.item_code)与商品ID(wms_stock_warehouse.id,纯数字时精确匹配),再经 wms_receiving_detail.system_product_id 关联,返回明细中含匹配商品的收货单;多个关键字取并集。与 filterDepleted、entry_order_id 可组合使用(组合时取交集)。不传则不过滤。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "收货单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息(total_quantity、total_locked、total_available、total_items)" + } + ], + "errors": [ + { + "code": "500", + "message": "查询失败" + } + ] + }, + { + "method": "storage.receiving.getStoreReceivingList", + "description": "货主侧收货单列表查询,以当前平台激活的货主 store_id 为维度查询收货单,支持分页和多条件筛选。", + "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 条件对象;支持 quickWhere、status、warehouse_id、日期区间等字段。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder" + }, + { + "name": "stock_query_where", + "type": "string|string[]", + "required": false, + "source": "body", + "description": "按商品维度过滤。传入字符串或字符串数组后搜索商品条码(wms_stock_barcodes.barcode)、商品编码(wms_stock_warehouse.item_code)与商品ID(wms_stock_warehouse.id,纯数字时精确匹配),再经 wms_receiving_detail.system_product_id 关联,返回明细中含匹配商品的收货单;多个关键字取并集。不传则不过滤。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "收货单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息(total_quantity、total_locked、total_available、total_items)" + } + ], + "errors": [ + { + "code": "500", + "message": "查询失败" + }, + { + "code": "0", + "message": "未获取到货主平台激活上下文,请先切换至货主角色" + } + ] + }, + { + "method": "storage.receiving.getReceivingDetail", + "description": "storage.receiving.getReceivingDetail 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "source": "body", + "description": "明细分页参数,支持 page/pageSize" + } + ], + "response": [ + { + "name": "receiving", + "type": "object", + "required": true, + "description": "收货单详情(含 details、images、pagination)" + }, + { + "name": "receiving.store_name", + "type": "string", + "required": false, + "description": "货主名称(string,可空)。优先取合约表 wms_store_warehouse.store_remask(货主备注名称,按 store_id + warehouse_id 维度),无合约或备注为空时回退 wms_store.company_name(公司全称),均无时保留主表快照(可能为空字符串)。" + }, + { + "name": "receiving.details", + "type": "array", + "required": false, + "description": "收货单明细列表,单条记录包含明细字段(见下文)" + }, + { + "name": "receiving.details.*.stock_id", + "type": "number", + "required": false, + "description": "商品/库存ID(number|null),语义与 system_product_id 一致,取值为 system_product_id,缺失时为 null;system_product_id 保留,向后兼容。" + }, + { + "name": "receiving.details.*.space_id", + "type": "string", + "required": false, + "description": "库位展示名称(string|null)。优先取 custom_space_name,其次取 space_name。兼容说明:该字段历史上为数值库位ID,现已调整为展示名称;原始ID请使用 receiving.details.*.space_id_raw。" + }, + { + "name": "receiving.details.*.space_id_raw", + "type": "number", + "required": false, + "description": "原始库位ID(number|null),用于兼容依赖旧语义(space_id=数字ID)的调用方。" + }, + { + "name": "receiving.details.*.space_name", + "type": "string", + "required": false, + "description": "库位名称/编码(string|null),作为展示名称的回退来源。" + }, + { + "name": "receiving.details.*.custom_space_name", + "type": "string", + "required": false, + "description": "库位自定义名称(string|null,可空)。" + }, + { + "name": "receiving.details.*.box_remainder", + "type": "number", + "required": false, + "description": "箱内剩余数量/零散数量(不满箱时的件数)" + }, + { + "name": "receiving.details.*.box_weight", + "type": "number", + "required": false, + "description": "实测箱重(单位与系统重量一致,如 g)" + } + ], + "errors": [ + { + "code": "0", + "message": "无记录或无权访问" + }, + { + "code": "500", + "message": "服务器错误" + } + ] + }, + { + "method": "storage.receiving.batchCancelReceiving", + "description": "storage.receiving.batchCancelReceiving 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "待作废收货单ID数组" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "批量作废处理结果" + } + ], + "errors": [ + { + "code": "0", + "description": "部分单据不存在、无权访问或状态不允许作废" + }, + { + "code": "500", + "description": "服务器错误" + } + ] + }, + { + "method": "storage.receiving.rejectReceiving", + "description": "驳回收货单:将已完成(completed)的收货单批量恢复为收货中(receiving),记录驳回人信息和驳回理由。若任意一张收货单状态非 completed,则整批拒绝操作。驳回人信息(reviewer_name、reviewer_employee_id)自动取当前登录用户上下文,无需传入.", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "收货单ID数组,所有收货单必须属于当前仓库且状态为 completed,否则整批拒绝" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "驳回理由,覆盖收货单原备注字段;不传则保留原备注" + } + ], + "response": [ + { + "name": "count", + "type": "number", + "description": "成功驳回的收货单数量" + } + ], + "errors": [ + { + "code": "0", + "description": "ids 为空、部分单据不存在/无权访问,或存在非 completed 状态的收货单" + }, + { + "code": "500", + "description": "服务器错误" + } + ] + }, + { + "method": "storage.receiving.reviewReceiving", + "description": "批量审核收货单:校验所有单据满足条件(收货完成、全部匹配、未入库、已绑定货主、未审核)后统一审核,任意一张不符合则整批失败回滚。审核人信息自动取当前登录用户上下文,无需传入.", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "收货单ID数组,所有单据必须满足:status=completed、detail_status=all_matched、storage_status=none、store_id 已绑定、is_review=0,否则整批拒绝" + } + ], + "response": [ + { + "name": "count", + "type": "number", + "description": "成功审核的收货单数量" + } + ], + "errors": [ + { + "code": "0", + "description": "ids 为空、单据不存在/无权访问,或不满足审核条件(含并发冲突)" + }, + { + "code": "500", + "description": "服务器错误,事务已回滚" + } + ] + }, + { + "method": "storage.receiving.create", + "description": "storage.receiving.create 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "delivery_method", + "type": "string", + "required": true, + "source": "body", + "description": "到货方式:truck/express/air_freight/sea_freight/other" + }, + { + "name": "loading_method", + "type": "string", + "required": true, + "source": "body", + "description": "装卸方式:with_pallet/without_pallet" + }, + { + "name": "license_plate", + "type": "string", + "required": false, + "source": "body", + "description": "车牌号(delivery_method=truck 时建议传)" + }, + { + "name": "tracking_number", + "type": "string", + "required": false, + "source": "body", + "description": "物流单号(非 truck/other 场景建议传)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID" + }, + { + "name": "total_boxes", + "type": "number", + "required": false, + "source": "body", + "description": "总箱数" + }, + { + "name": "total_pallets", + "type": "number", + "required": false, + "source": "body", + "description": "总托盘数" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + } + ], + "errors": [ + { + "code": "0", + "description": "创建失败(如字段枚举不合法、数据库约束异常)" + } + ] + }, + { + "method": "storage.receiving.bindStore", + "description": "收货单绑定货主", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID(必须与当前仓库存在有效签约关系)" + } + ], + "response": [ + { + "name": "data.id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "data.store_id", + "type": "number", + "required": true, + "description": "已绑定的货主ID" + }, + { + "name": "data.store_name", + "type": "string", + "required": false, + "description": "货主名称/签约备注名" + }, + { + "name": "data.status", + "type": "string", + "required": true, + "description": "当前收货单状态" + } + ], + "errors": [ + { + "code": "400", + "description": "用户未绑定仓库、收货单ID/货主ID为空、已取消或已绑定货主" + }, + { + "code": "404", + "description": "收货单不存在/无权访问,或货主与当前仓库未建立有效签约关系" + }, + { + "code": "500", + "description": "绑定货主失败" + } + ] + }, + { + "method": "storage.receiving.bindDetailProduct", + "description": "收货单明细绑定或改绑系统商品", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单明细ID(兼容字段 `id`)" + }, + { + "name": "system_product_id", + "type": "number", + "required": true, + "source": "body", + "description": "系统商品ID(`StockWarehouse.id`,且必须属于当前仓库)" + } + ], + "response": [ + { + "name": "data.detail_id", + "type": "number", + "required": true, + "description": "收货单明细ID" + }, + { + "name": "data.receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "data.system_product_id", + "type": "number", + "required": true, + "description": "已绑定的系统商品ID" + }, + { + "name": "data.product_name", + "type": "string", + "required": true, + "description": "自动回填的商品名称" + } + ], + "errors": [ + { + "code": "400", + "description": "用户未绑定仓库、明细ID/商品ID为空,收货单状态不允许绑定/改绑,或收货单已审核禁止绑定/改绑" + }, + { + "code": "404", + "description": "收货单明细不存在,或商品不存在/不属于当前仓库" + }, + { + "code": "500", + "description": "绑定商品失败" + } + ] + }, + { + "method": "storage.receiving.queryReceivingLogs", + "description": "按收货单ID查询操作日志列表(分页),仅返回当前仓库上下文数据", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number|string", + "required": false, + "source": "body", + "description": "收货单ID(与 receiving_id 二选一)" + }, + { + "name": "receiving_id", + "type": "number|string", + "required": false, + "source": "body", + "description": "收货单ID(兼容字段,与 id 二选一)" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码(兼容顶层分页入参)" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量(兼容顶层分页入参)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "日志列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,包含 page、pageSize、total、totalPages" + } + ], + "errors": [ + { + "code": "400", + "description": "收货单ID为空或仓库上下文缺失" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storage.receiving.removeItem", + "description": "storage.receiving.removeItem 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "item_id", + "type": "number", + "required": false, + "source": "body", + "description": "item_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.save", + "description": "修改收货单基础信息。按收货单ID更新当前仓库下收货单的基础字段。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID,按该ID修改当前仓库下的收货单" + }, + { + "name": "delivery_method", + "type": "string", + "required": false, + "source": "body", + "description": "到货方式:truck/express/air_freight/sea_freight/other;不传则保持原值" + }, + { + "name": "loading_method", + "type": "string", + "required": false, + "source": "body", + "description": "装卸方式:with_pallet/without_pallet;不传则保持原值" + }, + { + "name": "license_plate", + "type": "string", + "required": false, + "source": "body", + "description": "车牌号;当 delivery_method=truck 时可更新,其他到货方式会被清空或忽略" + }, + { + "name": "tracking_number", + "type": "string", + "required": false, + "source": "body", + "description": "物流单号;当 delivery_method 为 express/air_freight/sea_freight 时可更新,truck/other 场景会被清空或忽略" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID;若传入,会校验当前仓库下签约关系并同步更新货主名称;传 0/null 可清空货主" + }, + { + "name": "total_boxes", + "type": "number", + "required": false, + "source": "body", + "description": "总箱数,默认 0" + }, + { + "name": "total_pallets", + "type": "number", + "required": false, + "source": "body", + "description": "总托盘数,默认 0" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注信息" + }, + { + "name": "status", + "type": "string", + "required": false, + "source": "body", + "description": "收货单状态;不传则保持原值" + }, + { + "name": "video_device_id", + "type": "string", + "required": false, + "source": "body", + "description": "录像设备ID" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码;200 表示修改成功" + }, + { + "name": "id", + "type": "number", + "required": true, + "description": "修改的收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "结果描述;成功时通常为收货单修改成功" + } + ], + "errors": [ + { + "code": "400", + "description": "收货单ID不能为空、已取消的收货单不允许修改或用户未绑定仓库" + }, + { + "code": "404", + "description": "收货单不存在/无权访问,或指定货主不存在/未与当前仓库建立有效签约关系" + }, + { + "code": "0", + "description": "修改失败,如字段枚举不合法或数据库写入异常" + } + ] + }, + { + "method": "storage.receiving.get", + "description": "storage.receiving.get 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "description": "返回信息" + }, + { + "name": "data", + "type": "object", + "description": "收货单详情对象,包含 details(明细数组)、images 及主表字段" + }, + { + "name": "data.details", + "type": "array", + "description": "收货单明细数组(每项为明细对象)" + }, + { + "name": "data.details.*.box_remainder", + "type": "number", + "required": false, + "description": "箱内剩余数量/零散数量(不满箱时的件数),默认 0" + }, + { + "name": "data.details.*.box_weight", + "type": "number", + "required": false, + "description": "实测箱重(单位与系统重量一致,如 g),默认 0" + } + ], + "errors": [] + }, + { + "method": "storage.receiving.addDetail", + "description": "支持新增可选入参 item;item 有值时按传入字段创建明细(服务端会覆盖 receiving_id 与 creator_id);item 无值时沿原链路创建空白明细。返回的 selectId 与 data.details 语义不变(仍返回新创建明细的 selectId 与更新后的明细列表)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + }, + { + "name": "item", + "type": "object", + "required": false, + "source": "body", + "description": "可选:按传入字段创建明细;不传则创建空白明细。item.children 需覆盖以下字段(有则写、无则补齐):actual_quantity, box_quantity, boxes_per_pallet, space_id, system_product_id, box_width, box_height, box_length, box_remainder, box_weight, weight, barcode, product_name, pallet_quantity, receiving_time, production_date, expiry_date, remark, batch_number, product_snapshot。若传入 item,服务端仍会覆盖 receiving_id 与 creator_id。", + "children": [ + { + "name": "actual_quantity", + "type": "number", + "description": "实收数量" + }, + { + "name": "box_quantity", + "type": "number", + "description": "箱数量" + }, + { + "name": "boxes_per_pallet", + "type": "number", + "description": "每托盘箱数" + }, + { + "name": "space_id", + "type": "number", + "description": "库位 ID;未传时默认使用仓库设置 subject_config.default_location_id,未设置则兜底库位 1" + }, + { + "name": "system_product_id", + "type": "number", + "description": "系统商品 ID" + }, + { + "name": "box_width", + "type": "number", + "description": "箱宽(单位同系统)" + }, + { + "name": "box_height", + "type": "number", + "description": "箱高" + }, + { + "name": "box_length", + "type": "number", + "description": "箱长" + }, + { + "name": "box_remainder", + "type": "number", + "description": "箱内剩余数量/零散数量" + }, + { + "name": "box_weight", + "type": "number", + "description": "箱重(单位 g)" + }, + { + "name": "weight", + "type": "number", + "description": "商品重量(单位 g)" + }, + { + "name": "barcode", + "type": "string", + "description": "商品条码" + }, + { + "name": "product_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "pallet_quantity", + "type": "number", + "description": "托盘数量" + }, + { + "name": "receiving_time", + "type": "string", + "description": "收货时间(ISO 字符串)" + }, + { + "name": "production_date", + "type": "string", + "description": "生产日期(ISO 或 YYYY-MM-DD)" + }, + { + "name": "expiry_date", + "type": "string", + "description": "有效期/失效日期(ISO 或 YYYY-MM-DD)" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + }, + { + "name": "batch_number", + "type": "string", + "description": "批次号" + }, + { + "name": "product_snapshot", + "type": "object", + "description": "商品快照,具体结构以实现为准" + } + ] + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示添加成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "结果描述,成功时为 '添加成功'" + }, + { + "name": "data.details", + "type": "array", + "required": true, + "description": "收货单明细数组(每项为明细对象)" + }, + { + "name": "data.selectId", + "type": "number", + "required": true, + "description": "新创建的明细ID,用于前端选中" + } + ], + "errors": [ + { + "code": "400", + "description": "收货单状态不允许添加明细" + }, + { + "code": "404", + "description": "收货单不存在" + }, + { + "code": "500", + "description": "服务器错误或添加失败(数据库写入异常等)" + } + ] + }, + { + "method": "storage.receiving.deleteDetail", + "description": "删除收货单明细并回算统计。仅允许明细创建者在收货中状态删除未入库的明细;服务端从登录用户上下文获取 creator_id(ctx.user.employees_id)与 warehouse_id(ctx.user.store_id)。若关联收货单状态为 completed(已完成)或 cancelled(已取消),接口会返回删除失败(400),不允许删除明细。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单明细 ID(必填)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功,400/404/500 表示失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "简短的错误或成功信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的结果对象" + }, + { + "name": "data.details", + "type": "array", + "required": true, + "description": "删除后收货单剩余的明细数组。每项字段与 storage.receiving.getReceivingDetail 返回的明细项一致(含新增的 stock_id,语义同 getReceivingDetail,number|null);product_snapshot 为解析后的对象或 null" + }, + { + "name": "data.selectId", + "type": "number|null", + "required": true, + "description": "删除后建议前端选中的明细 ID;无剩余明细时为 null" + } + ], + "errors": [ + { + "code": "404", + "message": "明细不存在(或非创建者/仓库无权访问)" + }, + { + "code": "400", + "message": "收货单已完成或已取消,禁止删除明细;或该明细已入库或已被占用,删除失败" + }, + { + "code": "500", + "message": "服务器内部错误或删除异常(含数据库写入/事务异常)" + } + ] + }, + { + "method": "storage.receiving.detailChange", + "description": "修改收货单明细(数量/箱规/批次/商品信息回写等)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "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": "box_remainder", + "type": "number", + "required": false, + "source": "body", + "description": "箱内剩余数量/零散数量(不满箱时的件数)" + }, + { + "name": "box_weight", + "type": "number", + "required": false, + "source": "body", + "description": "实测箱重(单位与系统重量一致,如 g)" + }, + { + "name": "weight", + "type": "number", + "required": false, + "source": "body", + "description": "毛重/重量(单位 g)" + } + ], + "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.box_remainder", + "type": "number", + "required": false, + "description": "箱内剩余数量/零散数量(不满箱时的件数)" + }, + { + "name": "data.box_weight", + "type": "number", + "required": false, + "description": "实测箱重(单位与系统重量一致,如 g)" + }, + { + "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", + "description": "storage.receiving.cancel 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.completeReceiving", + "description": "storage.receiving.completeReceiving 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "notes": [ + "完成收货时会发送通知:通知 payload 或 metadata 将在每条明细中携带 box_remainder(箱内剩余数量/零散件数,number)与 box_weight(实测箱重,number,单位同系统重量,例如 g)。新增字段为可选,旧客户端可忽略。" + ], + "errors": [] + } + ] + }, + { + "groupName": "入库单", + "module": "storage.entry", + "list": [ + { + "method": "storage.entry.list", + "description": "入库单列表查询。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(通过 wms_entry_order_receiving 表查询实现)。quickWhere 支持模糊搜索:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。", + "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 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为\"当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级\"。新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(虚拟字段,不直接对应数据库列,内部通过 wms_entry_order_receiving 表查询实现)。quickWhere 模糊搜索范围:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "入库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "状态汇总(total、pending、creating、created、completed、cancelled)" + }, + { + "name": "list[].receivingBindings", + "type": "array", + "required": false, + "description": "收货单绑定列表(主表级关联),每项含 id、entry_order_id、receiving_id 及 receiving 对象(id、receiving_number、status、storage_status、created_at)" + }, + { + "name": "list[].hasReceiving", + "type": "boolean", + "required": false, + "description": "是否存在收货单绑定" + } + ], + "errors": [ + { + "code": "400", + "message": "筛选条件格式错误", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] + }, + { + "method": "storage.entry.listStore", + "description": "货主侧入库单列表查询:以货主维度(store_id)过滤入库单,货主登录后仅能查看自己货主下的入库单。与 storage.entry.list 共享底层逻辑,但主维度为 store_id 而非 warehouse_id。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单。quickWhere 支持模糊搜索:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头)。", + "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 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in。新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单。quickWhere 模糊搜索范围:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头)。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "入库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "状态汇总(total、pending、creating、created、completed、cancelled)" + }, + { + "name": "list[].receivingBindings", + "type": "array", + "required": false, + "description": "收货单绑定列表(主表级关联),每项含 id、entry_order_id、receiving_id 及 receiving 对象(id、receiving_number、status、storage_status、created_at)" + }, + { + "name": "list[].hasReceiving", + "type": "boolean", + "required": false, + "description": "是否存在收货单绑定" + } + ], + "errors": [ + { + "code": "400", + "message": "筛选条件格式错误", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] + }, + { + "method": "storage.entry.get", + "description": "查询入库单详情。通过入库单 ID 定位,关联 Store、EntryItems、EntryOrderReceiving→Receiving,并通过仓库商品详情、直接入库进度、收货单可用明细进行数据合并。entryOrder.order_status 可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID(必填)" + } + ], + "response": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "description": "入库单详情,包含 items 数组、receivingBindings(主表级收货单关联数组)。items 每项含 external_item_code / external_item_id / warehouse_item_code / warehouse_item_name / warehouse_item_spec / count / received_quantity / confirm_quantity / warehouse_quantity / warehouse_locked_quantity / warehouse_is_batch_mgmt / warehouse_is_shelf_life_mgmt / warehouse_image_url / warehouse_is_images / barcodes / direct_inbound_quantity / remaining_quantity / available_receiving_details" + }, + { + "name": "entryOrder.items[].external_item_code", + "type": "string", + "required": true, + "description": "外部商品编码(源自 EntryItems.item_code)" + }, + { + "name": "entryOrder.items[].external_item_id", + "type": "number", + "required": true, + "description": "外部商品ID(源自 EntryItems.item_id)" + }, + { + "name": "entryOrder.items[].warehouse_item_code", + "type": "string", + "required": true, + "description": "仓库商品编码(StockWarehouse.item_code),无匹配时为空字符串" + }, + { + "name": "entryOrder.items[].warehouse_item_name", + "type": "string", + "required": true, + "description": "仓库商品名称(StockWarehouse.item_name),无匹配时为空字符串" + }, + { + "name": "entryOrder.items[].warehouse_item_spec", + "type": "string", + "required": true, + "description": "仓库商品规格(StockWarehouse.sku_property),无匹配时为空字符串" + }, + { + "name": "entryOrder.items[].count", + "type": "number", + "required": true, + "description": "计划入库数量" + }, + { + "name": "entryOrder.items[].received_quantity", + "type": "number", + "required": true, + "description": "已收货数量(收货单途径)" + }, + { + "name": "entryOrder.items[].confirm_quantity", + "type": "number", + "required": true, + "description": "已确认收货数量" + }, + { + "name": "entryOrder.items[].warehouse_quantity", + "type": "number", + "required": true, + "description": "仓库当前库存总量(StockWarehouse.quantity),无匹配时为 null" + }, + { + "name": "entryOrder.items[].warehouse_locked_quantity", + "type": "number", + "required": true, + "description": "仓库锁定数量(StockWarehouse.locked_quantity),无匹配时为 null" + }, + { + "name": "entryOrder.items[].warehouse_is_batch_mgmt", + "type": "string", + "required": true, + "description": "是否批次管理(StockWarehouse.is_batch_mgmt),Y/N;无匹配时为 null" + }, + { + "name": "entryOrder.items[].warehouse_is_shelf_life_mgmt", + "type": "string", + "required": true, + "description": "是否效期管理(StockWarehouse.is_shelf_life_mgmt),Y/N;无匹配时为 null" + }, + { + "name": "entryOrder.items[].warehouse_image_url", + "type": "string", + "required": true, + "description": "商品图片 URL,当前固定返回空字符串 ''" + }, + { + "name": "entryOrder.items[].warehouse_is_images", + "type": "string", + "required": true, + "description": "是否有图片(StockWarehouse.is_images),Y/N;无匹配时为 null" + }, + { + "name": "entryOrder.items[].barcodes", + "type": "array", + "required": true, + "description": "条码列表,每项含 { id, barcode, sku_property };无匹配时为空数组 []" + }, + { + "name": "entryOrder.items[].direct_inbound_quantity", + "type": "number", + "required": true, + "description": "导入/PDA 已入库数量(InboundDirectLog 按 stock_id 聚合),无记录时为 0" + }, + { + "name": "entryOrder.items[].remaining_quantity", + "type": "number", + "required": true, + "description": "剩余可入库数量 = max(0, count - received_quantity),最小为 0" + }, + { + "name": "entryOrder.items[].available_receiving_details", + "type": "array", + "required": true, + "description": "可匹配的收货单明细及剩余可用量。每项含 receiving_id / receiving_number / receiving_detail_id / actual_quantity / allocated_quantity / available_quantity。仅返回收货单状态未完成且未完全入库的明细。无匹配时为空数组 []" + }, + { + "name": "entryOrder.receivingBindings", + "type": "array", + "required": true, + "description": "主表级收货单关联数组,每项含 id / receiving_id / receiving(receiving 含 id / receiving_number / status / storage_status / created_at)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 参数不能为空" + }, + { + "code": "0", + "message": "入库单不存在或无权访问" + }, + { + "code": "200", + "message": "查询成功" + } + ] + }, + { + "method": "storage.entry.getStore", + "description": "货主侧查询入库单详情。与 get 共享底层逻辑,但以货主维度(store_id)校验权限(不使用 warehouse_id),货主登录后仅能查看自己货主下的入库单明细。返回结构与 get 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID(必填)" + } + ], + "response": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "description": "入库单基本信息(id、entry_order_code、order_status、store_remask)" + }, + { + "name": "items", + "type": "array", + "required": true, + "description": "商品明细列表,每项含 id、stock_id、planned、completed、stock(商品详情)、bindings(库位绑定信息)" + }, + { + "name": "receivingBindings", + "type": "array", + "required": false, + "description": "主表级收货单关联数组,每项含 id / receiving_id / receiving(receiving 含 id / receiving_number / status / storage_status / created_at)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 参数不能为空" + }, + { + "code": "404", + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.cancel", + "description": "作废入库单(支持单条或批量作废)。CREATED(已创建待审核)和 PENDING(已审核)状态的入库单可以直接作废;已完成(COMPLETED)入库单不允许作废,sync_status=SUCCESS(已完成回传)的入库单也不允许作废;QM 来源入库单作废前先发送奇门取消同步。作废成功后按绑定行数量台账(wms_entry_order_receiving.allocated_quantity,旧数据按收货侧累计量兜底)逐绑定回收本入库单在收货单上的 stored_quantity 占用、重算各收货单 storage_status、清空台账(绑定行保留不软删),并同步重算入库单明细 received_quantity;同一收货单上其他入库单的占用不受影响(不再整体清零共享收货单);回滚失败不阻塞作废主流程(仅记录日志)。另支持按 entryOrderCode(兼容别名 entry_order_code)按单号定位入库单,供奇门/openapi 外部渠道复用(外部渠道经此复用同一作废流程并透传 skipExternalSync/idempotent/notFoundMessage 等内部选项);本渠道 id/ids 入参、响应结构与失败文案不变。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "入库单ID,兼容旧调用;与 ids 二选一。若同时传入 ids,以 ids 为准。" + }, + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "入库单ID数组(number[]),用于批量作废;必须为非空数组,建议批量操作使用 ids,优先于 id。" + }, + { + "name": "entryOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "入库单号(可选,内部复用口径):传入时按 entry_order_code 定位(兼容别名 entry_order_code,定位条件含 warehouse_id + is_enabled=1 + deleted_at=null),优先于 id/ids;供奇门/openapi 外部渠道复用,系统方法入口可继续使用 id/ids,行为与文案不变" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": false, + "description": "单条作废时返回的入库单ID" + }, + { + "name": "ids", + "type": "array", + "required": false, + "description": "批量作废时返回的已成功作废入库单ID数组(number[])" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误/参数不合法:需传入非空的 id 或 ids;ids 必须为数字数组且不得包含非法或重复值;已完成(COMPLETED)入库单不允许作废" + }, + { + "code": 400, + "message": "入库单已完成回传,不可取消" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.addItem", + "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝(PENDING 非绑定模式)。PENDING 状态可传 receiving_detail_id 绑定收货明细(不传则走非绑定模式,数量受计划数量限制),不再强制绑定收货单、不再强制传收货单 ID;CREATED 人工导入允许超过计划数量;传入 receiving_detail_id 时 quantity 可选(自动计算可用数量),space_id 必填。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品SKU ID(对应 wms_stock_warehouse.id)" + }, + { + "name": "quantity", + "type": "number", + "required": false, + "source": "body", + "description": "本次入库数量(正整数)。传入 receiving_detail_id 时可选,自动计算收货明细可用数量;非绑定模式必填" + }, + { + "name": "inbound_type", + "type": "string", + "required": true, + "source": "body", + "description": "入库方式:import(导入入库)、pda(PDA入库)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(如导入文件名、PDA操作备注等)" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "source": "body", + "description": "存放库位ID(单条模式),关联 wms_location_space.id。绑定收货明细时必填;为空时 commit 默认使用库位 1" + }, + { + "name": "receiving_detail_id", + "type": "number", + "required": false, + "source": "body", + "description": "收货单明细ID(PDA 上架绑定模式),传入后触发收货明细预占绑定,quantity 自动计算;不传则按非绑定模式直接导入,不要求绑定收货单" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "预分配数量(单条模式,可选,默认等于 quantity)" + }, + { + "name": "items", + "type": "array", + "required": false, + "source": "body", + "description": "批量模式:商品列表,每项包含 stock_id(商品SKU ID, number, 必填)、quantity(入库数量, number, 绑定模式可选)、inbound_type(import/pda, string, 必填)、space_id(库位ID, number, 绑定模式必填)、remark(备注, string, 可选)、receiving_detail_id(收货明细ID, number, 可选)、allocated_quantity(预分配数量, number, 可选)。传入 items 时忽略顶层的 stock_id/quantity/inbound_type/remark/space_id。" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": false, + "description": "单条模式返回:新增的入库记录ID" + }, + { + "name": "stock_id", + "type": "number", + "required": false, + "description": "商品SKU ID" + }, + { + "name": "quantity", + "type": "number", + "required": false, + "description": "本次入库数量" + }, + { + "name": "inbound_type", + "type": "string", + "required": false, + "description": "入库方式" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "description": "存放库位ID" + }, + { + "name": "plan_quantity", + "type": "number", + "required": false, + "description": "入库单中该商品计划数量" + }, + { + "name": "existing_before", + "type": "number", + "required": false, + "description": "添加前已有入库总量" + }, + { + "name": "existing_after", + "type": "number", + "required": false, + "description": "添加后入库总量" + }, + { + "name": "remaining", + "type": "number", + "required": false, + "description": "剩余可入库数量" + }, + { + "name": "receivingBindResult", + "type": "object", + "required": false, + "description": "收货单绑定结果(仅绑定模式返回),含 binding_id、receiving_detail_id、allocated_quantity、status" + }, + { + "name": "count", + "type": "number", + "required": false, + "description": "批量模式:写入项数" + }, + { + "name": "total_quantity", + "type": "number", + "required": false, + "description": "批量模式:入库总数量" + }, + { + "name": "items", + "type": "array", + "required": false, + "description": "批量模式:每项入库记录详情(结构同单条模式)" + } + ], + "errors": [ + { + "code": 400, + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "items[].stock_id 必填 / items[].quantity 必须为正整数 / items[].inbound_type 必须为 import 或 pda" + }, + { + "code": 400, + "message": "已作废入库单不允许操作 / 已完成的入库单不允许操作" + }, + { + "code": 400, + "message": "入库单已绑定收货单且状态为 CREATED,请先审核后再进行上架操作" + }, + { + "code": 400, + "message": "绑定收货明细时必须指定 space_id" + }, + { + "code": 400, + "message": "入库数量超过计划:商品计划 X,已入库 Y,本次 Z,合计 W" + }, + { + "code": 400, + "message": "收货明细可用数量不足:实际数量 X,已占用 Y,可用 Z" + }, + { + "code": 400, + "message": "入库单中不存在该商品" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.commit", + "description": "提交确认完成导入/PDA 入库。先同步奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存(wms_stock_warehouse.quantity 增量、wms_stock_transaction 流水),将 pending 状态的 InboundDirectLog 更新为 committed,更新入库单状态为 COMPLETED,同步 sync_status=SUCCESS。绑定收货明细的入库(InboundDirectLog.receiving_detail_id 非空)在事务内按 committed 汇总量覆写收货明细 stored_quantity/storage_status 并重算收货单主表 storage_status,同时覆写绑定行数量台账 allocated_quantity(与 stored_quantity 保持一致,setLedgerAllocation 覆写语义)。不足量提交时未入库商品跳过。noNeedNotice=1 时跳过入库完成通知(默认 0 通知)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID" + }, + { + "name": "noNeedNotice", + "type": "number", + "required": false, + "source": "body", + "description": "是否跳过入库完成通知:0 通知(默认),1 不通知" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(固定为 COMPLETED)" + }, + { + "name": "sync_status", + "type": "string", + "required": true, + "description": "同步状态(固定为 SUCCESS)" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "入库商品种类数" + }, + { + "name": "total_quantity", + "type": "number", + "required": true, + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录请先添加商品 / 入库单无明细" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + }, + { + "code": 500, + "message": "库存写入异常 / 同步回传失败" + } + ] + }, + { + "method": "storage.entry.removeItem", + "description": "移除一条导入/PDA 入库记录(仅限未提交的入库单,即状态非 CANCELLED/COMPLETED)。移除后该商品的可入库余量自动恢复。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库记录ID(wms_inbound_direct_log.id)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "已移除的入库记录ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "商品SKU ID" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "description": "移除的入库数量" + }, + { + "name": "inbound_type", + "type": "string", + "required": true, + "description": "入库方式" + } + ], + "errors": [ + { + "code": 400, + "message": "id 必填 / 已作废入库单不允许操作 / 已完成的入库单不允许移除记录" + }, + { + "code": 404, + "message": "入库记录不存在 / 关联入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.quickInbound", + "description": "快捷直入(虚拟入库):将入库单商品直入到虚拟库位(space_id=2),跳过收货/质检流程。有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量(actual_quantity - stored_quantity)的商品直入,实际入库量 = min(明细计划数量, 收货单剩余可入数量),并在事务内回写收货单明细已入库数量与收货单入库状态、同步累加绑定行数量台账 allocated_quantity(recordLedgerAllocation 累计语义,旧台账为 null 的绑定行先按收货侧累计量兜底初始化);未绑定收货单时按明细计划数量全量直入。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、回写收货单明细、变更入库单状态为 COMPLETED,并在同一事务内回写入库单 is_virtual_inbound(是否虚拟入库):有绑定收货单 → 0(非虚拟入库),无绑定收货单 → 1(虚拟入库)。事务外异步回传奇门/API。noNeedNotice=1 时跳过入库完成通知(默认 0 通知)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "noNeedNotice", + "type": "number", + "required": false, + "source": "body", + "description": "是否跳过入库完成通知:0 通知(默认),1 不通知" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(COMPLETED)" + }, + { + "name": "sync_status", + "type": "string", + "required": true, + "description": "同步状态(SUCCESS)" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "实际入库明细条目数(有绑定收货单时为与收货单有交集且实际入库量大于0的明细数)" + }, + { + "name": "total_quantity", + "type": "number", + "required": true, + "description": "实际入库总数量(有绑定收货单时=与收货单交集部分的实际直入数量)" + }, + { + "name": "plan_quantity", + "type": "number", + "required": true, + "description": "计划入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "id 必填" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + }, + { + "code": 400, + "message": "已作废入库单不允许快捷入库" + }, + { + "code": 400, + "message": "入库单已完成,请勿重复提交" + }, + { + "code": 400, + "message": "入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)" + }, + { + "code": 400, + "message": "请先添加入库明细" + }, + { + "code": 400, + "message": "收货单中无交集商品或剩余可入数量不足,无法快捷直入" + }, + { + "code": 400, + "message": "入库明细数量均为0,无法快捷直入" + } + ] + }, + { + "method": "storage.entry.receivingCompare", + "description": "入库单与收货单商品对照预览:给定入库单ID和收货单ID(支持多个),先将多个收货单的明细合并为一个整体,再与入库单商品做一次逐行对照,返回合并后的对照视图(每个入库明细仅一行,含匹配状态 matched/entry_only、合并收货数量与各收货单来源明细)及汇总统计。纯只读接口。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "receiving_id", + "type": "number", + "required": false, + "source": "body", + "description": "收货单ID,单个时使用,与 receiving_ids 二选一" + }, + { + "name": "receiving_ids", + "type": "array", + "required": false, + "source": "body", + "description": "收货单ID数组,优先使用;与 receiving_id 二选一,传了此参数则忽略 receiving_id" + } + ], + "response": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "comparison", + "type": "array", + "required": true, + "description": "合并后的逐行对照列表(多个收货单明细先合并,再与入库单对照;以入库单明细为主,每个入库明细仅一行)", + "children": [ + { + "name": "entry_item_id", + "type": "number", + "required": true, + "description": "入库单明细ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "库存商品ID(stock_warehouse.id)" + }, + { + "name": "warehouse_item_code", + "type": "string", + "required": true, + "description": "入库商品编码" + }, + { + "name": "warehouse_item_name", + "type": "string", + "required": true, + "description": "入库商品名称" + }, + { + "name": "warehouse_item_spec", + "type": "string", + "required": true, + "description": "入库商品规格" + }, + { + "name": "entry_count", + "type": "number", + "required": true, + "description": "计划数量" + }, + { + "name": "entry_received", + "type": "number", + "required": true, + "description": "入库单已收数量" + }, + { + "name": "match_status", + "type": "string", + "required": true, + "description": "匹配状态:matched-已匹配, entry_only-仅入库(无收货商品)" + }, + { + "name": "receiving_quantity", + "type": "number", + "required": true, + "description": "合并后收货实际数量(所有收货单该商品明细数量之和,entry_only 时为 0)" + }, + { + "name": "receiving_allocated", + "type": "number", + "required": true, + "description": "合并后已分配数量" + }, + { + "name": "receiving_available", + "type": "number", + "required": true, + "description": "合并后可再用量(收货实际-已分配)" + }, + { + "name": "receiving_sources", + "type": "array", + "required": true, + "description": "收货来源明细列表(matched 时非空),每项含 receiving_id/receiving_number/receiving_detail_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available" + } + ] + }, + { + "name": "receiving_only", + "type": "array", + "required": true, + "description": "仅收货单有的商品列表(合并后仍未匹配到任何入库明细,按商品合并),每项含 stock_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available/receiving_sources" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "合并对照汇总统计,含 total_entry_items/matched_items/entry_only_items/receiving_only_items" + }, + { + "name": "errors", + "type": "array", + "required": false, + "description": "校验失败的收货单列表(status=error 的记录)" + }, + { + "name": "total_summary", + "type": "object", + "required": true, + "description": "总体汇总统计", + "children": [ + { + "name": "total_receivings", + "type": "number", + "description": "请求的收货单总数" + }, + { + "name": "matched_count", + "type": "number", + "description": "有效参与对比的收货单数" + }, + { + "name": "error_count", + "type": "number", + "description": "校验失败的收货单数" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "receiving_ids 或 receiving_id 必填" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.bindReceiving", + "description": "将收货单绑定到入库单(主表级关联 wms_entry_order_receiving)。入库单仅 CREATED、COMPLETED 状态允许绑定,其他状态抛错;收货单须存在且未删除、与入库单同仓库、同货主、未取消(status≠cancelled)、已审核(is_review)。CREATED 绑定:逐条写入主表绑定(幂等,已存在跳过),绑定行数量台账 allocated_quantity 初始化为空对象 {}(区别于旧数据 null),仅建立关联、不做入库进度同步。COMPLETED 绑定:事务内完成主表绑定 + 收货单入库进度同步(数量台账版防超扣)——FOR UPDATE 行锁入库单主行、该入库单全部未删除绑定行及相关收货单明细行,串行化同一入库单的分配事务;入库单明细按 SKU 汇总(entry_items.stock_id ≡ wms_receiving_detail.system_product_id),每 SKU 分配目标 = min(入库单计划数量 − 其他未删除绑定已分配量, 当前收货单该 SKU 剩余可入量),按明细 id 升序逐行补分配或回收(多退少补:旧数据超分回收、亏分补分配),同步更新收货明细 stored_quantity/storage_status(none/partial/all)、回写绑定行台账 allocated_quantity(收货明细ID→分配数量)、重算收货单主表 storage_status,并同步重算 entry_items.received_quantity(入库单侧已入库量,与各绑定收货单 stored_quantity 之和可对账);绑定已存在且未删除时跳过进度同步(幂等不重复分配),软删除绑定恢复后按归一化目标仅分配剩余量(旧超分数据归一化回收);SKU 未匹配的入库明细仅记录 unmatched_items 不阻塞;任一异常事务整体回滚。creator_id 由服务端从登录态自动注入,无需前端传值。支持部分成功:逐个收货单处理,跳过项计入 skipped。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "receiving_ids", + "type": "array", + "required": true, + "source": "body", + "description": "要绑定的收货单ID列表,每项为 integer" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "1" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息(绑定完成)" + }, + { + "name": "bound", + "type": "array", + "required": true, + "description": "绑定/进度同步成功列表。CREATED 每项含 receiving_id、receiving_number、created;COMPLETED 每项额外含 restored(软删除恢复为 true)与 storage_sync(入库进度同步结果,含 stored_total、matched_item_count、unmatched_items)", + "children": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + }, + { + "name": "created", + "type": "boolean", + "required": true, + "description": "本次是否新建绑定行;绑定已存在(未删除)或由软删除行恢复时为 false" + }, + { + "name": "restored", + "type": "boolean", + "required": true, + "description": "是否由已软删除(解绑产生)的绑定行恢复;CREATED 恢复后台账重置为 {} 不重算进度,COMPLETED 恢复后按归一化目标执行进度同步" + }, + { + "name": "storage_sync", + "type": "object", + "required": false, + "description": "仅 COMPLETED 新建/恢复绑定时返回的入库进度同步结果", + "children": [ + { + "name": "stored_total", + "type": "number", + "required": true, + "description": "本次补分配到收货单明细 stored_quantity 的总数量(归一化回收的超分数量不计入;无分配变化时可为 0)" + }, + { + "name": "matched_item_count", + "type": "number", + "required": true, + "description": "成功补分配数量(allocated>0)的 SKU 数量" + }, + { + "name": "unmatched_items", + "type": "array", + "required": true, + "description": "未匹配到收货明细的入库明细 SKU 列表(仅记录跳过,不影响绑定),每项含 stock_id、item_code、count" + } + ] + } + ] + }, + { + "name": "skipped", + "type": "array", + "required": true, + "description": "跳过列表,每项含 receiving_id、receiving_number、error_code、message。error_code 可能值:ALREADY_BOUND(绑定已存在,COMPLETED 幂等跳过进度同步,不重复分配)、BINDING_WRITE_FAILED(CREATED 写入绑定失败)。收货单校验失败(不存在/跨仓/跨货主/已取消/未审核)时 skipped 为空数组、仅 summary.skipped_count 计数(失败明细仅服务端日志)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总统计", + "children": [ + { + "name": "bound_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "跳过/失败数量(含收货单校验失败数)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "响应时间戳(秒)" + } + ], + "errors": [ + { + "code": 500, + "message": "接口错误: entry_order_id 不能为空" + }, + { + "code": 500, + "message": "接口错误: receiving_ids 不能为空且必须为数组" + }, + { + "code": 500, + "message": "接口错误: 入库单不存在" + }, + { + "code": 500, + "message": "接口错误: 入库单状态不允许绑定,当前状态: {当前状态},仅 CREATED、COMPLETED 状态可操作" + }, + { + "code": 500, + "message": "接口错误: 入库单绑定收货单失败,已回滚: {原因}(COMPLETED 事务内主表绑定+进度同步任一异常整体回滚)" + }, + { + "code": "RECEIVING_NOT_FOUND", + "message": "收货单不存在或已删除(业务校验失败不抛错:skipped 为空数组,计入 summary.skipped_count,失败明细仅服务端日志)" + }, + { + "code": "WAREHOUSE_MISMATCH", + "message": "收货单与入库单不属于同一仓库(处理同上)" + }, + { + "code": "OWNER_MISMATCH", + "message": "收货单与入库单货主不一致(处理同上)" + }, + { + "code": "RECEIVING_CANCELLED", + "message": "收货单已取消(处理同上)" + }, + { + "code": "RECEIVING_NOT_REVIEWED", + "message": "收货单未审核(处理同上)" + }, + { + "code": "ALREADY_BOUND", + "message": "绑定关系已存在,跳过入库进度同步(COMPLETED 幂等,计入 skipped,不重复分配 stored_quantity)" + }, + { + "code": "BINDING_WRITE_FAILED", + "message": "写入绑定失败: {原因}(CREATED 逐条写入异常,计入 skipped)" + } + ] + }, + { + "method": "storage.entry.reviewEntry", + "description": "审核入库单(CREATED → PENDING),仅允许已绑定收货单的入库单推进状态", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "isNeedLog": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success/failure" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功 / 400 失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "data.order_status", + "type": "string", + "required": true, + "description": "审核后状态(PENDING)" + } + ], + "errors": [ + { + "code": 400, + "message": "id 必填" + }, + { + "code": 400, + "message": "入库单不存在" + }, + { + "code": 400, + "message": "当前状态[xxx]不允许审核,仅 CREATED 可审核" + }, + { + "code": 400, + "message": "入库单未绑定收货单,请先绑定收货单后再审核" + } + ] + }, + { + "method": "storage.entry.containerList", + "description": "PDA 上架时拉取入库单已绑定收货单中指定商品的可用容器列表(未绑定的收货明细)。返回匹配明细的 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status,以及商品详情 stock。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品 stock_id(即 wms_stock_warehouse.id)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "可用容器(收货明细)列表" + }, + { + "name": "list[].detail_id", + "type": "number", + "required": true, + "description": "收货明细 ID" + }, + { + "name": "list[].receiving_id", + "type": "number", + "required": true, + "description": "收货单 ID" + }, + { + "name": "list[].barcode", + "type": "string", + "required": true, + "description": "商品条码" + }, + { + "name": "list[].product_name", + "type": "string", + "required": true, + "description": "商品名称" + }, + { + "name": "list[].actual_quantity", + "type": "number", + "required": true, + "description": "实收数量" + }, + { + "name": "list[].receiving_status", + "type": "string", + "required": true, + "description": "收货单状态" + }, + { + "name": "list[].stock", + "type": "object", + "required": true, + "description": "商品详情(通过 getStockDetails 获取,含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "匹配总数" + } + ], + "errors": [ + { + "code": 0, + "message": "用户未绑定仓库" + }, + { + "code": 0, + "message": "entry_order_id 不能为空" + }, + { + "code": 0, + "message": "stock_id 不能为空" + }, + { + "code": 0, + "message": "入库单不存在或无权访问" + }, + { + "code": 500, + "message": "服务器查询失败" + } + ] + }, + { + "method": "storage.entry.queryEntryLogs", + "description": "查询入库单操作日志。根据入库单 ID 分页查询关联的操作日志记录(入库单创建、状态变更、审核等操作的审计轨迹)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID(必填)" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "操作日志列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": 400, + "message": "id 不能为空" + }, + { + "code": 500, + "message": "查询失败" + } + ] + }, + { + "method": "storage.entry.unbindReceiving", + "description": "解除入库单与收货单的主表绑定关系,并按数量台账回滚该收货单的入库进度。仅 CREATED / PENDING 状态的入库单可解绑(COMPLETED / CANCELLED 不允许),解绑不回退入库单状态。逐个收货单处理:主表绑定不存在计入 failed(BINDING_NOT_FOUND);存在则在事务内 FOR UPDATE 行锁入库单主行与绑定行,按绑定行台账(wms_entry_order_receiving.allocated_quantity,旧数据按收货侧累计量兜底)逐明细回收该收货单 stored_quantity、重算明细与主表 storage_status、台账重置为空对象 {},软删除主表绑定与关联明细绑定(InboundDirectLog 中 status=committed 且 receiving_detail_id 非空、属于该收货单的记录);同一收货单上其他入库单的占用不受影响。返回 success/failed/success_count/failed_count,success 项含 rolled_back_quantity(本次回滚的 stored_quantity 总量)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "receiving_ids", + "type": "array", + "required": true, + "source": "body", + "description": "要解除绑定的收货单ID列表,每项为 integer" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "1" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息(解绑完成)" + }, + { + "name": "success", + "type": "array", + "required": true, + "description": "解绑成功列表,每项含 receiving_id、released_detail_ids、released_detail_count、rolled_back_quantity、message", + "children": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "released_detail_ids", + "type": "array", + "required": true, + "description": "已软删除的关联明细绑定对应的收货明细ID列表(wms_receiving_detail.id)" + }, + { + "name": "released_detail_count", + "type": "number", + "required": true, + "description": "已软删除的关联明细绑定数(InboundDirectLog 中 status=committed 且 receiving_detail_id 非空的记录数)" + }, + { + "name": "rolled_back_quantity", + "type": "number", + "required": true, + "description": "本次按台账回滚的该收货单 stored_quantity 总量(无可回滚量时为 0)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "处理结果说明(已解除绑定并回滚收货单入库进度)" + } + ] + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "解绑失败列表,每项含 receiving_id、error_code、message。error_code 可能值:BINDING_NOT_FOUND(主表绑定不存在)、ENTRY_ORDER_NOT_FOUND(入库单不存在)、ENTRY_ORDER_STATUS_INVALID(入库单状态不允许解绑)、UNBIND_ERROR(解绑过程异常)" + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "解绑成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "解绑失败数量" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "响应时间戳(秒)" + } + ], + "errors": [ + { + "code": 500, + "message": "接口错误: entry_order_id 不能为空" + }, + { + "code": 500, + "message": "接口错误: receiving_ids 不能为空且必须为数组" + }, + { + "code": "ENTRY_ORDER_NOT_FOUND", + "message": "入库单不存在(业务校验失败不抛错:success 为空数组,全部收货单计入 failed,failed_count=请求收货单数)" + }, + { + "code": "ENTRY_ORDER_STATUS_INVALID", + "message": "入库单状态不允许解绑,当前状态: {状态}(仅 CREATED、PENDING 可解绑;处理同上不抛错)" + }, + { + "code": "BINDING_NOT_FOUND", + "message": "主表绑定不存在(计入 failed)" + }, + { + "code": "UNBIND_ERROR", + "message": "解绑过程异常: {原因}(计入 failed,已执行的回滚在事务内回退)" + } + ] + } + ] + }, + { + "groupName": "出库单模块", + "module": "storage.stockout", + "list": [ + { + "method": "storage.stockout.list", + "name": "出库单列表", + "description": "非订单出库单能力(对应奇门 stockout.create):直接读取 wms_order_stockout 表;主出口为 storage.stockout.*,不再推荐通过 storage.delivery.* 命名使用。storage.delivery.* 仅保留兼容转发。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "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 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 stockout_order_code、order_status、order_type、source_type、remark 与日期区间字段。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder,可选字段:id、stockout_order_code、order_status、order_type、updated_at、created_at、order_create_time,默认按 updated_at DESC、id DESC" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "出库单列表(wms_order_stockout 表记录,含 store_id/store_name 货主信息与 sync_status/sync_message 出站同步状态字段;不含 id、warehouse_id、warehouse_name)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storage.stockout.toOrder", + "name": "出库单转订单", + "description": "将非订单出库单转为正式销售订单:新订单 create_channel 固定为 STOCKOUT;转单时释放出库单占用的库存锁定并转由新订单重新锁定;转单成功后原出库单置为 TRANSFERRED(已转订单,该状态禁止一键出库)并记录已转订单号(幂等,重复调用返回原订单信息)。仅 CREATED / PENDING 状态允许转单;建单失败自动补偿恢复出库单锁定。收货信息必填:name、(tel/mobile) 至少一项、省市区镇详细地址,缺失返回错误禁止转单;收货信息优先接口传入,未传回填出库单已存的收件人字段;快递编码沿用出库单已解析的 express_code,平台优先使用出库单已存 source_platform_code,为空使用兜底平台。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "新订单号,不传自动生成(SK 前缀)" + }, + { + "name": "receiverInfo", + "type": "object", + "required": false, + "source": "body", + "description": "收件人信息(name/mobile/tel/province/city/area/town/detailAddress/zipCode 等),不传时回填出库单已存的收件人字段;name、(tel/mobile) 其一、省市区镇详细地址必填,缺失则报错不能转订单" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "新订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": true, + "description": "新订单号" + }, + { + "name": "step", + "type": "number", + "required": false, + "description": "订单步骤(0=待审核,1=待处理)" + } + ], + "errors": [ + { + "code": "400", + "description": "出库单不存在 / 状态不允许转单 / 无明细 / 订单创建失败" + }, + { + "code": "500", + "description": "释放或恢复库存锁定失败" + } + ] + }, + { + "method": "storage.stockout.listItems", + "name": "出库单拉取明细", + "description": "按出库单查询商品明细(用于非订单出库单),直接读取 wms_order_stockout + wms_order_stockout_items 表。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "stockout_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "出库单号(推荐);兼容 delivery_order_code 旧参数名" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "出库单ID,可选;与 stockout_order_code 至少传一个" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "required": true, + "description": "出库单基础信息(wms_order_stockout 表记录,含 id、stockout_order_code)" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "出库单商品明细(wms_order_stockout_items 表记录)" + } + ], + "errors": [ + { + "code": "404", + "description": "出库单不存在" + }, + { + "code": "500", + "description": "缺少定位参数或查询失败" + } + ] + }, + { + "method": "storage.stockout.listLogs", + "name": "出库单操作日志", + "description": "查询出库单操作日志(分页)。日志业务类型 business_type=stockout、business_id=出库单ID,覆盖转订单(STOCKOUT_TO_ORDER)、确认直出(STOCKOUT_CONFIRM)、修改信息(STOCKOUT_UPDATE_INFO)、取消(STOCKOUT_CANCEL)等操作。按创建时间倒序。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "出库单ID;与 stockout_order_code 至少传一个" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "出库单号(推荐);与 id 至少传一个" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码(默认1);与订单日志接口一致,支持顶层传参" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量(默认20,兼容 page_size)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页对象写法({ page, pageSize }),与顶层 page/pageSize 二选一,顶层优先" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "required": true, + "description": "操作日志列表(含 operation_code/operation_name/operator_name/message/created_at 等,与订单日志字段一致)" + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages }" + } + ], + "errors": [ + { + "code": "400", + "description": "id 或 stockout_order_code 至少传一个 / 缺少仓库上下文" + } + ] + }, + { + "method": "storage.stockout.confirm", + "name": "出库单确认(直出)", + "description": "直出确认出库单:不改变内部库存,按出库单明细计划数量(plan_qty)直接确认。运单号以复数 waybill_codes 为准(一单多运单),回传时按奇门 packages.package[].expressCode 承载,不使用 deliveryOrder.expressCode;单数 waybill_code 已弃用,仅在复数缺失时对存量单做兼容回退。出站回传按出库单 source_type 分流:QM→奇门 taobao.qimen.stockout.confirm;API→OpenAPI 回调(method=stockout.confirm,appKey 按货主合约反查 wms_store_warehouse(auth_status=2) 与 wms_api_app(启用且 callback_url 非空));WMS 等内部来源无需通知外部、直接视为成功。回传成功后释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水)并把状态推进到 COMPLETED;回传失败则返回错误,order_status 不变,sync_status 标记为 FAILED(可重试)。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "确认后状态(COMPLETED)" + }, + { + "name": "logisticsName", + "type": "string", + "required": true, + "description": "物流公司名称(当前实现固定返回字符串 OTHER)" + }, + { + "name": "expressCode", + "type": "string", + "required": true, + "description": "快递公司编码(当前实现取自 wms_order_stockout.express_code)。历史遗留命名:该字段名来源于旧口径,实际语义是快递公司编码,不是运单号;运单号见 waybill_codes" + }, + { + "name": "expressCodes", + "type": "array", + "required": false, + "description": "当前实现取自已废弃字段 wms_order_stockout.express_codes(通常为 null)。运单号请以 waybill_codes 为准,该字段待代码侧收敛" + }, + { + "name": "qimenSync", + "type": "string", + "required": true, + "description": "外部回传结果:success=通知成功,failure=通知失败(确认本身不受影响)。字段名为历史遗留,API/WMS 来源同样复用该字段表示回传结果" + }, + { + "name": "qimenSyncMessage", + "type": "string", + "required": false, + "description": "外部回传失败时的错误信息" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少出库单ID" + }, + { + "code": "400", + "message": "出库单不存在" + }, + { + "code": "400", + "message": "出库单当前状态不允许确认(非 CREATED/PENDING)" + }, + { + "code": "400", + "message": "出库单未填写运单号(waybill_codes),请先更新运单号后再确认" + }, + { + "code": "400", + "message": "出站同步失败: <失败原因>(QM:奇门响应 code + message,如「-1 无法匹配货主」;API:「缺少 appKey,无法回传出库单」或 OpenAPI 回调失败原因;回传服务不可用:「出库单回传服务不可用」)" + } + ], + "notes": [ + "运单号口径(2026-09-13):校验与回传均以复数 waybill_codes 为准(不足则回退单数 waybill_code 兼容存量单),错误文案由 waybill_code 改为 waybill_codes。", + "多运单模型:报文 packages.package[] 每个元素一个包裹(expressCode = 对应运单号),deliveryOrder.expressCode 不传(奇门多运单以 packages 为准)。", + "已知待收敛项(代码侧,本次未做):packages.package[].packageCode 当前所有包裹共用出库单号(多包裹时重复);每个包裹的 items 为全量明细(未按包裹拆分),严格按包裹归属需补充「包裹-明细」关联模型。", + "出站分流:confirm 复用 systems/order_async.js#notifyStockoutExternalInternal,与出库单转订单回传口径一致(QM→奇门、API→OpenAPI 回调 stockout.confirm、WMS 等内部来源直接成功)。", + "报文组装复用 systems/order_async.js#buildStockoutConfirmDataInternal:快递信息取 express_code/express_name,orderLines[].ownerCode 取明细 owner_code(为空回退出库单 qimen_owner_code)。", + "已知待收敛项:确认成功响应里的 expressCode / expressCodes 仍分别返回 express_code / express_codes,与 waybill_codes 不一致,待代码侧统一。" + ] + }, + { + "method": "storage.stockout.updateExpress", + "name": "更新出库单快递/运单号", + "description": "更新出库单的快递公司与运单号(express_code / waybill_codes),用于在确认前填写运单信息。express_code 是快递公司编码(如 SF/STO/ZT),传入后自动从系统快递表解析 express_name(匹配不到置空串,传空值则 express_code 与 express_name 置 NULL);运单号以复数 waybill_codes(JSON 数组)为准,支持一单多运单。单数 waybill_code 已弃用:传入 waybill_codes 时会自动把单数列镜像为复数首个(便于历史查询与展示),传入空数组或 null 时单数列同步置 NULL。已废弃字段 express_codes 不在本接口读写范围内。未传入的字段不更新,三个字段都未传时返回「没有需要更新的字段」。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "快递公司编码(非运单号,如 SF/STO/ZT);传入后自动解析 express_name,传空值置 NULL" + }, + { + "name": "waybill_codes", + "type": "array", + "required": false, + "source": "body", + "description": "运单号列表(JSON 数组或 null,支持一单多运单);回传与确认校验以此为准,非数组返回 400" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "source": "body", + "description": "运单号(单数,已弃用):仅作为 waybill_codes 首个的镜像保留;传 waybill_codes 时会以复数首个覆盖它,勿单独使用" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "description": "更新后的快递公司编码" + }, + { + "name": "express_name", + "type": "string", + "required": false, + "description": "由 express_code 解析出的快递公司名称" + }, + { + "name": "waybill_codes", + "type": "array", + "required": false, + "description": "更新后的运单号列表(以此为准)" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "description": "单数列镜像值(等于 waybill_codes 首个;已弃用,仅为历史兼容)" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少出库单ID" + }, + { + "code": "400", + "message": "出库单不存在" + }, + { + "code": "400", + "message": "没有需要更新的字段" + }, + { + "code": "400", + "message": "waybill_codes 必须是数组或 null" + } + ], + "notes": [ + "运单号口径变更(2026-09-13):以复数 waybill_codes 为准(对齐奇门 packages.package[] 多运单模型),单数 waybill_code 降级为镜像字段。", + "镜像规则:传 waybill_codes(非空数组)→ waybill_code = 首个;传空数组或 null → 两列同时置 NULL;同时传单数与复数 → 以复数首个覆盖单数;仅传单数 → 行为不变(兼容旧调用方)。", + "废弃字段提醒:express_codes(复数,历史名)已 @deprecated,本接口不读不写;运单号列表请用 waybill_codes。", + "已知待收敛项(代码侧,本次未做):对未识别/废弃参数(如 express_codes)既不报错也不兼容,仍会返回「更新成功」造成静默失败;另外本方法缺少 warehouse_id 归属校验(同文件 storage.stockout.updateInfo 有该校验)。" + ] + }, + { + "method": "storage.stockout.updateInfo", + "name": "修改出库单信息", + "description": "修改出库单信息:收件人(name/tel/mobile/company/email 等)、地址(province/city/area/town/detailAddress/zipCode/countryCode)、快递编码(express_code,自动解析 express_name)、来源平台(source_platform_code/source_platform_name)。未传入的字段不修改;修改后收货信息不完整(name、(tel/mobile) 其一、省市区镇详细地址缺任一)禁止提交。仅 CREATED/PENDING 状态允许修改。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "收件人姓名" + }, + { + "name": "tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人固定电话" + }, + { + "name": "mobile", + "type": "string", + "required": false, + "source": "body", + "description": "收件人移动电话" + }, + { + "name": "company", + "type": "string", + "required": false, + "source": "body", + "description": "收件人公司名称" + }, + { + "name": "email", + "type": "string", + "required": false, + "source": "body", + "description": "收件人电子邮箱" + }, + { + "name": "zipCode", + "type": "string", + "required": false, + "source": "body", + "description": "邮编" + }, + { + "name": "countryCode", + "type": "string", + "required": false, + "source": "body", + "description": "国家二字码" + }, + { + "name": "province", + "type": "string", + "required": false, + "source": "body", + "description": "省份" + }, + { + "name": "city", + "type": "string", + "required": false, + "source": "body", + "description": "城市" + }, + { + "name": "area", + "type": "string", + "required": false, + "source": "body", + "description": "区/县" + }, + { + "name": "town", + "type": "string", + "required": false, + "source": "body", + "description": "镇/街道" + }, + { + "name": "detailAddress", + "type": "string", + "required": false, + "source": "body", + "description": "详细地址" + }, + { + "name": "receiver_id", + "type": "string", + "required": false, + "source": "body", + "description": "收件人证件号" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "快递公司编码,传入后自动解析 express_name" + }, + { + "name": "source_platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台编码" + }, + { + "name": "source_platform_name", + "type": "string", + "required": false, + "source": "body", + "description": "来源平台名称" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "更新后的出库单完整记录(wms_order_stockout 表字段,含 receiver_*、express_*、source_platform_* 等)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少出库单ID / 出库单不存在 / 状态不允许修改" + }, + { + "code": "400", + "description": "收货信息缺失,禁止提交(列出缺失字段)" + } + ] + }, + { + "method": "storage.stockout.cancel", + "name": "出库单取消", + "description": "取消出库单:仅 CREATED/PENDING 状态允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水),状态置为 CANCELLED,并写 wms_operation_log 操作日志(STOCKOUT_CANCEL)。TRANSFERRED(已转订单)与 COMPLETED(已完成)状态禁止取消。实现委托共享服务 systems/stockout_order.js#cancel(奇门 / openapi 同口径:单事务 + 行锁,并发取消/确认/转单更安全,已 CANCELLED 幂等返回成功)。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "取消后状态(CANCELLED)" + } + ], + "errors": [ + { + "code": 400, + "message": "缺少出库单ID" + }, + { + "code": 400, + "message": "缺少仓库上下文" + }, + { + "code": 404, + "message": "出库单不存在" + }, + { + "code": 400, + "message": "出库单当前状态(xxx)不允许取消(仅 CREATED/PENDING 可取消)" + } + ] + } + ] + }, + { + "groupName": "库存管理模块", + "module": "storage.inventory", + "list": [ + { + "method": "storage.inventory.quickPutaway", + "description": "收货单快捷入库:将已审核的收货单(completed + is_review=true)明细按 stock_id(system_product_id)分组合并数量后,直接创建入库单(SCRK,自动审批到 PENDING),写入 wms_entry_order_receiving 主表级绑定,并更新收货单及其明细的入库状态(storage_status)。要求货主仓库签约配置 policy_config.allow_receiving_quick_putaway=1 开启快捷入库功能。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID(必填)" + } + ], + "response": [ + { + "name": "entry_order_id", + "type": "number", + "description": "创建的入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "description": "入库单号(SCRK + 年月日 + 4位流水号)" + }, + { + "name": "order_status", + "type": "string", + "description": "入库单状态(PENDING)" + }, + { + "name": "receiving_id", + "type": "number", + "description": "收货单ID" + }, + { + "name": "total_lines", + "type": "number", + "description": "入库单明细行数(按 stock_id 合并后的行数)" + }, + { + "name": "total_quantity", + "type": "number", + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "receiving_id 必填" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 404, + "message": "收货单不存在或无权访问" + }, + { + "code": 400, + "message": "收货单已作废,不允许快捷入库" + }, + { + "code": 400, + "message": "收货单状态不允许快捷入库,仅 completed 状态可操作" + }, + { + "code": 400, + "message": "收货单未审核,不允许快捷入库" + }, + { + "code": 400, + "message": "货主仓库签约关系不存在" + }, + { + "code": 400, + "message": "货主未开启收货单快捷入库功能" + }, + { + "code": 400, + "message": "收货单无明细,无法创建入库单" + }, + { + "code": 400, + "message": "收货单中所有明细均未关联系统商品,无法创建入库单" + }, + { + "code": 400, + "message": "以下商品在当前仓库中不存在或已失效" + }, + { + "code": 500, + "message": "系统异常" + } + ] + }, + { + "method": "storage.inventory.directPutaway", + "description": "收货单直入库存(一步完成):将已审核的收货单(completed + is_review=true)未入库明细直接写入 wms_storage 库位库存并生成入库单(SCRK,一步置为 COMPLETED),入库单明细与收货明细一一对应(不合并,逐行保留库位/批次/效期),同时更新 wms_stock_warehouse 总库存并写入出入库流水(wms_stock_transaction / wms_storage_transaction),并写入 wms_inbound_direct_log(status=committed,与 storage.entry.commit 链路口径一致),回填收货单及其明细的入库状态。库位规则:收货明细 space_id 有效则按其库位入库,否则使用仓库设置 subject_config.default_location_id,未设置则兜底库位 1。要求货主仓库签约配置 policy_config.allow_receiving_direct_putaway=1 开启直入库存功能。", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID(必填)" + } + ], + "response": [ + { + "name": "entry_order_id", + "type": "number", + "description": "生成的入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "description": "入库单号(SCRK + 年月日 + 4位流水号)" + }, + { + "name": "order_status", + "type": "string", + "description": "入库单状态(COMPLETED,一步完成)" + }, + { + "name": "receiving_id", + "type": "number", + "description": "收货单ID" + }, + { + "name": "total_lines", + "type": "number", + "description": "入库单明细行数(与待入库收货明细一一对应)" + }, + { + "name": "total_quantity", + "type": "number", + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "receiving_id 必填" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 404, + "message": "收货单不存在或无权访问" + }, + { + "code": 400, + "message": "收货单已作废,不允许直入库存" + }, + { + "code": 400, + "message": "收货单状态不允许直入库存,仅 completed 状态可操作" + }, + { + "code": 400, + "message": "收货单未审核,不允许直入库存" + }, + { + "code": 400, + "message": "货主仓库签约关系不存在" + }, + { + "code": 400, + "message": "货主未开启收货单直入库存功能" + }, + { + "code": 400, + "message": "收货单无明细,无法直入库存" + }, + { + "code": 400, + "message": "收货单所有明细均已入库,禁止重复直入库存" + }, + { + "code": 400, + "message": "以下商品未匹配系统商品,请先绑定" + }, + { + "code": 400, + "message": "以下商品在当前仓库中不存在或已失效" + }, + { + "code": 500, + "message": "系统异常" + } + ] + }, + { + "method": "storage.inventory.transferLocation", + "description": "单商品单库位移库,将库存从一个库位移动到另一个库位,支持部分数量移库和全量移库", + "name": "库存移库(库位转移)", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "storage_id", + "type": "number", + "required": true, + "source": "body", + "description": "库存记录ID" + }, + { + "name": "target_space_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标库位ID" + }, + { + "name": "quantity", + "type": "number", + "required": false, + "source": "body", + "description": "移库数量,不传则全部移动" + } + ], + "response": { + "storage_id": "原库存记录ID", + "target_space_id": "目标库位ID", + "quantity": "实际移库数量", + "success": "是否成功(boolean)", + "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": "目标库位不存在或不属于该仓库" + } + ] + }, + { + "method": "storage.inventory.transferByProduct", + "description": "按库位+商品维度移库,自动查找原库位下该商品的所有库存记录并合并移动。不适用于开启批次管理的商品", + "name": "按商品移库(库位转移)", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "space_id", + "type": "number", + "required": true, + "source": "body", + "description": "原库位ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品SKU ID(wms_stock_warehouse.id)" + }, + { + "name": "target_space_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标库位ID" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "source": "body", + "description": "移库数量" + } + ] + }, + { + "method": "storage.inventory.list", + "description": "库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。默认按库位+商品合并数量(合并模式),group_by_batch=true 时返回每条库存明细(明细模式)。仅返回有量库存:明细模式过滤 quantity=0 的行,合并模式过滤总数量为 0 的商品。", + "name": "库存列表", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,可用字段:stock_id(商品ID)、space_id(库位ID)、store_id(货主ID)、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、batch_no(批次号)、inbound_order_no(入库单号)、available_quantity(可用数量,支持 gt/lt)、inbound_time(入库时间,支持 between)、created_at(创建时间,支持 between)、stock_query(虚拟筛选字段:按商品编码/名称/货物编码/条码/SKU ID 模糊匹配,如 { operator: 'like', value: '111' })" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数 { sortField, sortOrder },默认 sortField='created_at', sortOrder='DESC'" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按批次查询,默认 false。false=合并模式(按库位+商品聚合quantity/locked_quantity/available_quantity),true=明细模式(逐条返回含 batch_no/production_date/expiry_date 等)" + } + ], + "response": { + "_note": "响应结构因 group_by_batch 而异", + "_shelf_life_note": "production_date 和 expiry_date 为库存批次日期字段;is_shelf_life_warning_triggered 表示该库存在商品启用保质期管理且剩余天数小于等于阈值时是否触发效期预警。", + "list_merged": { + "_description": "group_by_batch=false(默认合并模式),仅按 stock_id 分组聚合,跨库位、跨库存类型汇总", + "list": [ + { + "stock_id": "商品库存ID", + "warehouse_id": "仓库ID(MIN 聚合值)", + "store_id": "货主ID(MIN 聚合值)", + "quantity": "总库存数量(SUM)", + "locked_quantity": "总锁定数量(SUM)", + "available_quantity": "总可用数量(SUM)", + "first_inbound_time": "最早入库时间", + "last_inbound_time": "最晚入库时间", + "batch_count": "批次数", + "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)" + } + } + ], + "pagination": { + "page": 1, + "pageSize": 20, + "total": 100, + "totalPages": 5 + } + }, + "list_detail": { + "_description": "group_by_batch=true(明细模式)", + "list": [ + { + "id": "库存记录ID", + "warehouse_id": "仓库ID", + "store_id": "货主ID", + "space_id": "库位ID", + "stock_id": "商品库存ID", + "batch_no": "批次号", + "inventory_type": "库存类型", + "quantity": "库存数量", + "locked_quantity": "锁定数量", + "available_quantity": "可用数量", + "production_date": "生产日期(库存批次日期字段)", + "expiry_date": "过期日期(库存批次日期字段)", + "inbound_time": "入库时间", + "inbound_order_no": "入库单号", + "receiving_id": "收货单ID", + "entry_order_id": "入库单ID", + "supplier_batch_no": "供应商批次号", + "created_at": "创建时间", + "updated_at": "更新时间", + "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 + } + } + } + }, + { + "method": "storage.inventory.export", + "description": "提交库存导出异步任务。支持两种导出模式(exportMode):stock_location(默认,按 stock_id + 库位聚合导出库存汇总,含库位编码/名称、商品信息、总库存/锁定/可用、批次数、最近入库时间等)、storage(按 storage_id 逐条导出库存明细,含库位编码/名称、商品信息、批次号、库存类型、数量、生产日期、过期日期、入库单号等)。立即返回任务受理信息(task_id/status/progress),不直接返回文件。通过 storage.inventory.exportTaskProgress 查询进度并获取下载地址。仅导出有量库存(与 storage.inventory.list 一致):明细模式过滤 quantity=0 的行,合并模式过滤总数量为 0 的商品。", + "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 条件对象,与 storage.inventory.list 的 where 语义完全一致(暂不支持 stock_query 虚拟筛选)。支持字段:stock_id(商品ID)、space_id(库位ID)、store_id(货主ID)、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、batch_no(批次号)、inbound_order_no(入库单号)、available_quantity(可用数量,支持 gt/lt)、inbound_time(入库时间,支持 between)、created_at(创建时间,支持 between)" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,与 storage.inventory.list 的 sort 语义完全一致。sortField 支持:id/stock_id/space_id/created_at/updated_at/inbound_time/quantity,sortOrder 支持 ASC/DESC。默认 id DESC" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按批次导出,默认 false。与 storage.inventory.list 的 group_by_batch 语义一致。false=合并模式(按 stock_id+库位聚合导出库存汇总,含总库存/锁定/可用/批次数/最近入库时间),true=明细模式(按 storage_id 逐条导出库存明细,含批次号/库存类型/生产日期/过期日期/入库单号等)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "导出任务ID,用于后续查询进度" + }, + { + "name": "status", + "type": "string", + "description": "任务状态:submitted" + }, + { + "name": "progress", + "type": "number", + "description": "进度:0" + }, + { + "name": "message", + "type": "string", + "description": "受理消息" + }, + { + "name": "update_time", + "type": "number", + "description": "更新时间戳" + } + ], + "errors": [ + { + "code": 400, + "message": "where 条件格式不正确" + }, + { + "code": 500, + "message": "导出任务提交失败" + } + ] + }, + { + "method": "storage.inventory.exportTaskProgress", + "description": "按 task_id 查询库存导出任务进度,未找到时 status=not_found。任务完成(status=success)时返回 download_url 供客户端下载导出文件。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID,兼容 taskId 驼峰写法" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务ID" + }, + { + "name": "status", + "type": "string", + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "description": "进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "description": "额外提示信息" + }, + { + "name": "result", + "type": "object", + "description": "任务成功时返回的结果对象(含 fileKey/url 等)" + }, + { + "name": "error", + "type": "string", + "description": "失败时的错误信息" + }, + { + "name": "download_url", + "type": "string", + "description": "任务完成后可直接下载的文件地址" + }, + { + "name": "update_time", + "type": "number", + "description": "最近一次状态更新时间戳" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + }, + { + "code": 500, + "message": "查询失败或内部错误" + } + ] + }, + { + "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": "库位维度出入库流水逐条明细查询(wms_storage_transaction)。支持 where 条件、keyword 快捷搜索、分页、排序;仓库ID由服务端按当前登录上下文自动注入,不支持前端传参。历史版本默认按商品+单据类型聚合数量(合并模式),现已废弃聚合,恒返回逐条明细;group_by_batch 参数保留但不再影响返回结果。", + "name": "出入库流水记录列表", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,支持以下字段(可传标量或 { operator, value } 对象):", + "children": [ + { + "name": "transaction_type", + "type": "string", + "required": false, + "description": "流水类型枚举:INBOUND=入库 / OUTBOUND=出库 / TRANSFER_OUT=移库出 / TRANSFER_IN=移库入 / LOCK=锁定 / UNLOCK=取消锁定" + }, + { + "name": "stock_id", + "type": "number", + "required": false, + "description": "商品库存ID(单数,与 stock_ids 等效)" + }, + { + "name": "stock_ids", + "type": "array", + "required": false, + "description": "商品库存ID数组" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "description": "库位ID" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "description": "货主ID(单数,与 store_ids 等效)" + }, + { + "name": "store_ids", + "type": "array", + "required": false, + "description": "货主ID数组" + }, + { + "name": "order_type", + "type": "string", + "required": false, + "description": "单据类型(非限定枚举,常见值:SCRK=收货入库 / MATCH=匹配入库 / CGTH=采购退货 / INTERCEPT_LOCK=拦截锁定 / INTERCEPT_UNLOCK=拦截解锁)" + }, + { + "name": "order_no", + "type": "string", + "required": false, + "description": "单据号(模糊匹配)" + }, + { + "name": "batch_no", + "type": "string", + "required": false, + "description": "批次号(精确匹配)" + }, + { + "name": "inventory_type", + "type": "string", + "required": false, + "description": "库存类型枚举:ZP=正品 / CC=残次 / JS=机损 / XS=箱损 / ZT=在途库存 / DJ=冻结 / FP=废品" + }, + { + "name": "operator_name", + "type": "string", + "required": false, + "description": "操作人姓名(模糊匹配)" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "description": "关联单据ID(发货单ID)" + }, + { + "name": "created_at", + "type": "array", + "required": false, + "description": "创建时间区间(operator=between,value=[start, end],闭区间)" + }, + { + "name": "start_time", + "type": "string", + "required": false, + "description": "开始时间(created_at >= start_time,与 created_at 区间等效)" + }, + { + "name": "end_time", + "type": "string", + "required": false, + "description": "结束时间(created_at <= end_time,与 created_at 区间等效)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "description": "商品关键字(item_code/item_name/goods_code/barcode/SKU ID 模糊匹配,等价于顶层 keyword)" + } + ] + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "快捷搜索关键字(也可放 where.keyword),支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。内部先解析为 stock_id 列表,再以 IN 条件合并到查询中" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1、pageSize=20,pageSize 上限 200" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数 { sortField, sortOrder },sortField 白名单:created_at、quantity、stock_id、store_id、warehouse_id、space_id;非法字段回退默认排序 created_at DESC" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "已废弃:历史版本用于切换聚合/明细模式,当前恒返回逐条明细,该参数不再生效,仅保留请求兼容" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": false, + "description": "逐条流水明细列表(按 created_at 倒序)", + "children": [ + { + "name": "id", + "type": "number", + "description": "流水记录ID" + }, + { + "name": "created_at", + "type": "string", + "description": "流水创建时间" + }, + { + "name": "transaction_type", + "type": "string", + "description": "流水类型枚举:INBOUND=入库 / OUTBOUND=出库 / TRANSFER_OUT=移库出 / TRANSFER_IN=移库入 / LOCK=锁定 / UNLOCK=取消锁定" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "stock_id", + "type": "number", + "description": "商品库存ID(关联 wms_stock_warehouse.id)" + }, + { + "name": "storage_id", + "type": "number", + "description": "库位库存ID(关联 wms_storage.id)" + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID" + }, + { + "name": "quantity", + "type": "number", + "description": "变动数量" + }, + { + "name": "before_quantity", + "type": "number", + "description": "变更前库存数量" + }, + { + "name": "after_quantity", + "type": "number", + "description": "变更后库存数量" + }, + { + "name": "before_locked_quantity", + "type": "number", + "description": "变更前锁定数量" + }, + { + "name": "after_locked_quantity", + "type": "number", + "description": "变更后锁定数量" + }, + { + "name": "before_intercept_locked_quantity", + "type": "number", + "description": "变更前拦截锁定数量" + }, + { + "name": "after_intercept_locked_quantity", + "type": "number", + "description": "变更后拦截锁定数量" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + }, + { + "name": "inventory_type", + "type": "string", + "description": "库存类型枚举:ZP=正品 / CC=残次 / JS=机损 / XS=箱损 / ZT=在途库存 / DJ=冻结 / FP=废品" + }, + { + "name": "order_type", + "type": "string", + "description": "关联单据类型" + }, + { + "name": "order_no", + "type": "string", + "description": "关联单据号" + }, + { + "name": "order_id", + "type": "number", + "description": "关联单据ID" + }, + { + "name": "source_order_codes", + "type": "string", + "description": "来源订单号集合" + }, + { + "name": "operator_id", + "type": "string", + "description": "操作人ID" + }, + { + "name": "operator_name", + "type": "string", + "description": "操作人姓名" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + }, + { + "name": "stockItem", + "type": "object", + "description": "商品信息(LEFT JOIN wms_stock_warehouse,关联不到时为 null)", + "children": [ + { + "name": "id", + "type": "number", + "description": "商品ID" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "sku_property", + "type": "string", + "description": "规格" + }, + { + "name": "stock_unit", + "type": "string", + "description": "单位" + } + ] + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": false, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "description": "当前页" + }, + { + "name": "pageSize", + "type": "number", + "description": "每页条数" + }, + { + "name": "total", + "type": "number", + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "description": "总页数" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "where 条件格式不正确" + }, + { + "code": 400, + "message": "分页参数不合法" + } + ] + }, + { + "method": "storage.inventory.listByStockId", + "name": "按商品查询有量库存明细", + "description": "按商品查询库存明细:传入 stock_id,返回该商品在当前仓库下所有数量大于 1(quantity > 1)的 wms_storage 明细行。支持两种模式:group_by_space=false(默认,不汇总)逐条返回明细,结构与 storage.inventory.list 明细模式(group_by_batch=true)一致,含批次字段(batch_no/inventory_type/quantity/locked_quantity/available_quantity/production_date/expiry_date/inbound_time/inbound_order_no/receiving_id/entry_order_id/supplier_id/supplier_batch_no 等)、stock(商品信息,含 barcodes/images 附属信息)、space(库位信息)、store_name(货主名称,来源于当前仓库签约表 store_remask)以及效期/库存预警字段;group_by_space=true(按库位汇总)先筛 quantity > 1 的明细行,再按 space_id 汇总 quantity/locked_quantity/available_quantity,返回行含库位/商品信息与 batch_count、first_inbound_time、last_inbound_time,不含批次与效期/预警字段。仓库上下文来自当前登录用户(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品SKU ID(wms_stock_warehouse.id,必填)" + }, + { + "name": "group_by_space", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按库位汇总,默认 false。false=不汇总(逐条明细);true=按库位汇总(先筛 quantity > 1 明细行,再按 space_id 求和)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "状态码,200=成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "结果说明" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "库存数组(quantity > 1,按 id 倒序)。group_by_space=false 时为明细行,每项字段:id、warehouse_id、store_id、space_id、stock_id、batch_no、inventory_type、quantity、locked_quantity、intercept_locked_quantity(拦截锁定数量,默认 0)、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、receiving_id、entry_order_id、supplier_id、supplier_batch_no、is_enabled、created_at、updated_at、delete_at;stock 对象(id/item_code/item_name/sku_property/stock_unit/is_shelf_life_mgmt/remaining_threshold_days/is_batch_mgmt_enabled/store_name/barcodes/images);space 对象(id/space_code/custom_name);顶层 store_name(货主名称);is_shelf_life_warning_triggered(效期预警是否触发);expiry_remaining_days/inventory_warning_level/inventory_warning_color/inventory_warning_range/inventory_warning_tip_text(库存预警字段,无预警时为 null)。group_by_space=true 时为按库位汇总行,每项字段:warehouse_id、store_id、space_id、stock_id、quantity/locked_quantity/available_quantity(汇总值)、batch_count(批次数)、first_inbound_time(最早入库时间)、last_inbound_time(最晚入库时间)、stock 对象、space 对象、顶层 store_name;不含批次与效期/预警字段" + } + ], + "errors": [ + { + "code": 400, + "message": "stock_id 必填且必须为正整数" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 500, + "message": "系统异常" + } + ] + }, + { + "method": "storage.inventory.listBySpaceId", + "name": "按库位查询有量库存商品列表", + "description": "按库位查询库存商品列表:传入 space_id,先判断该库位是否为当前仓库的库位(不存在返回 404,存在但不属于当前仓库返回 400),是则返回该库位下有量库存(quantity > 0)的商品列表。列表按商品(stock_id)汇总为一条:每项含 warehouse_id/store_id/space_id/space_code/space_name/stock_id/quantity/locked_quantity/intercept_locked_quantity/available_quantity(汇总数量)/batch_count(批次数)/first_inbound_time(最早入库时间)/last_inbound_time(最晚入库时间)。商品信息使用 stock_warehouse 通用属性返回(stock 对象,由 getStockDetails 通用链路提供:id/item_code/item_name/sku_property/quantity/locked_quantity/is_batch_mgmt/is_shelf_life_mgmt/is_images/need_recheck/store_id/packing_requirements/stock_unit/barcodes(条码数组)/image_url(图片数组);未命中时为 null);顶层 store_name 为货主名称(当前仓库签约表 store_remask,未命中为 null)。该库位无有量库存时 list 为空数组。仓库上下文来自当前登录用户(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "space_id", + "type": "number", + "required": true, + "source": "body", + "description": "库位ID(wms_location_space.id,必填)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "状态码,200=成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "结果说明" + }, + { + "name": "data.space", + "type": "object", + "required": true, + "description": "库位信息:id(库位ID)、warehouse_id(所属仓库ID)、space_code(库位编码)、custom_name(自定义名称)、space_status(库位状态)" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "该库位下有量库存(quantity > 0,按 id 倒序查询后汇总)的商品数组,每项字段:warehouse_id、store_id、space_id、stock_id、quantity(汇总数量)、locked_quantity(汇总锁定数量)、intercept_locked_quantity(汇总拦截锁定数量)、available_quantity(汇总可用数量)、batch_count(批次数)、first_inbound_time(最早入库时间,空为 '')、last_inbound_time(最晚入库时间,空为 '')、space_code(库位编码)、space_name(custom_name 优先,否则 space_code)、store_name(货主名称)、stock(stock_warehouse 通用属性对象:id/item_code/item_name/sku_property/quantity/locked_quantity/is_batch_mgmt/is_shelf_life_mgmt/is_images/need_recheck/store_id/packing_requirements/stock_unit/barcodes/image_url;商品详情未命中时为 null)。该库位无有量库存时为空数组 []" + } + ], + "errors": [ + { + "code": 400, + "message": "space_id 必填且必须为正整数" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 400, + "message": "库位 {space_id} 不属于当前仓库" + }, + { + "code": 404, + "message": "库位不存在: space_id={space_id}" + }, + { + "code": 500, + "message": "系统异常" + } + ] + }, + { + "method": "storage.inventory.updateExpiry", + "name": "维护库存效期(生产日期/到期日期)", + "description": "按库存记录维度维护生产日期与到期日期:传入 storage_id 与 production_date / expiry_date,更新 wms_storage 对应批次的两个日期字段。两个日期至少传一个:未传的字段保持库内原值,传 null 或空串表示清空该字段。日期支持 YYYY-MM-DD / YYYY/MM/DD / YYYY-MM-DD HH:mm:ss / ISO 字符串,内部统一按 YYYY-MM-DD 落库;合并后的生产日期不得晚于到期日期(未传字段取库内现值参与比较)。仅允许维护当前登录仓库(ctx.user.store_id)下的库存记录,跨仓库的 storage_id 按「不存在」处理(404);更新前后完全一致时返回 changed=false,不写库、不记操作日志。成功维护时写入业务操作日志(business_type=storage,operation_code=STORAGE_UPDATE_EXPIRY,message 记录两个日期的变更前后值)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "storage_id", + "type": "number", + "required": true, + "source": "body", + "description": "库存记录ID(wms_storage.id,必填,正整数)" + }, + { + "name": "production_date", + "type": "string", + "required": false, + "source": "body", + "description": "生产日期,支持 YYYY-MM-DD / YYYY/MM/DD / YYYY-MM-DD HH:mm:ss / ISO 字符串;传 null 或空串表示清空。与 expiry_date 至少传一个,未传则保持库内原值" + }, + { + "name": "expiry_date", + "type": "string", + "required": false, + "source": "body", + "description": "到期日期,格式要求同 production_date;传 null 或空串表示清空。与 production_date 至少传一个,未传则保持库内原值" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "状态码:200=成功,400=参数或业务校验失败,404=库存记录不存在或无权访问,409=库存记录被锁定" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "结果说明,成功为「更新成功」;两个日期均无变化为「生产日期与到期日期均无变化,未做修改」" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "维护结果;失败时为 null" + }, + { + "name": "data.storage_id", + "type": "number", + "required": true, + "description": "库存记录ID(wms_storage.id)" + }, + { + "name": "data.warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(来自当前登录用户 ctx.user.store_id)" + }, + { + "name": "data.store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "data.space_id", + "type": "number", + "required": true, + "description": "库位ID" + }, + { + "name": "data.stock_id", + "type": "number", + "required": true, + "description": "商品SKU ID(wms_stock_warehouse.id)" + }, + { + "name": "data.batch_no", + "type": "string", + "required": true, + "description": "批次号" + }, + { + "name": "data.production_date", + "type": "string", + "required": true, + "description": "维护后的生产日期(YYYY-MM-DD),未维护时为 null" + }, + { + "name": "data.expiry_date", + "type": "string", + "required": true, + "description": "维护后的到期日期(YYYY-MM-DD),未维护时为 null" + }, + { + "name": "data.before_production_date", + "type": "string", + "required": true, + "description": "维护前的生产日期(YYYY-MM-DD),原为空时为 null" + }, + { + "name": "data.before_expiry_date", + "type": "string", + "required": true, + "description": "维护前的到期日期(YYYY-MM-DD),原为空时为 null" + }, + { + "name": "data.changed", + "type": "boolean", + "required": true, + "description": "是否发生了实际变更(false 表示传入值与库内现值一致,未写库)" + } + ], + "errors": [ + { + "code": 400, + "message": "storage_id 必填且必须为正整数" + }, + { + "code": 400, + "message": "production_date 格式非法,须为 YYYY-MM-DD" + }, + { + "code": 400, + "message": "expiry_date 格式非法,须为 YYYY-MM-DD" + }, + { + "code": 400, + "message": "production_date 与 expiry_date 至少传入一个" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 400, + "message": "生产日期(2026-08-01)不能晚于到期日期(2026-07-01)" + }, + { + "code": 404, + "message": "库存记录不存在或无权访问: storage_id=123" + }, + { + "code": 409, + "message": "库存记录被锁定,请稍后重试" + } + ], + "notes": [ + "仓库上下文来自当前登录用户(ctx.user.store_id),不接受请求体传入的 warehouse_id,避免跨仓库越权维护", + "仅维护 wms_storage 中 is_enabled=1 且 delete_at IS NULL 的库存记录;维护前对目标行加行锁(SELECT ... FOR UPDATE),避免与移库/出入库并发冲突", + "不对商品的保质期管理开关(stock_warehouse.is_shelf_life_mgmt)做限制:未启用效期管理的商品同样允许维护,维护后进入库存有效期列表的前提仍是商品启用效期管理且 remaining_threshold_days > 0", + "接口需要 API 权限校验:wms_permission 中需存在 path=storage.inventory.updateExpiry 的记录并授予相应角色(permissions='*' 的角色自动放行),否则返回 403「无权访问该接口」" + ] + } + ] + }, + { + "groupName": "库存报表模块", + "module": "stock.report", + "list": [ + { + "method": "stock.report.search", + "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": "查询条件对象。支持字段:start_time(闭区间下限)、end_time(闭区间上限)、by_space(是否按库位返回,默认 false)、store_ids(货主ID数组)、stock_id(商品库存ID,单数)、stock_ids(商品库存ID数组)、keyword(商品关键字模糊匹配,支持 SKU ID/item_code/item_name/goods_code/barcode)。仅返回在时间区间内存在流水的数据(无流水键不返回)。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间,支持字符串/Date;用于闭区间过滤:created_at >= start_time" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间,支持字符串/Date;用于闭区间过滤:created_at <= end_time" + }, + { + "name": "where.by_space", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按库位返回,默认 false。false=按商品+货主聚合(多库位汇总),true=按商品+库位+货主返回;当 where.by_space=true 时,额外返回 space_id、space_name(custom_name 优先,否则使用 space_code)。" + }, + { + "name": "where.store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "货主ID数组,用于过滤特定货主(空或未传表示不过滤)", + "list": [] + }, + { + "name": "where.stock_id", + "type": "number", + "required": false, + "source": "body", + "description": "商品库存ID(单数,兼容数组),精确过滤指定商品;与 stock_ids 二选一,与 keyword 互斥" + }, + { + "name": "where.stock_ids", + "type": "array", + "required": false, + "source": "body", + "description": "商品库存ID数组,精确过滤指定商品列表;与 stock_id 二选一,与 keyword 互斥", + "list": [] + }, + { + "name": "where.keyword", + "type": "string", + "required": false, + "source": "body", + "description": "商品关键字,支持按 SKU ID(纯数字精确匹配)、商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)模糊匹配;与 stock_id / stock_ids 互斥" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象(请求体 data.sort)。支持 data.sort.sortField / data.sort.sort_field 与 data.sort.sortOrder / data.sort.sort_order;sortField 白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total(item_code/item_name 按字典序,其余按数值);sortOrder 支持 ASC / DESC(大小写不敏感);非法字段或顺序将回退默认排序。" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段(兼容 data.sort.sortField)。白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total;非法值回退默认排序。" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名(兼容 data.sort.sort_field),规则同 sort.sortField。" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向(兼容 data.sort.sortOrder),支持 ASC / DESC(大小写不敏感);非法值回退默认排序。" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名(兼容 data.sort.sort_order),规则同 sort.sortOrder。" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数(请求体 data.pagination),格式 { page, pageSize }。默认生效:未传或非法时按 { page: 1, pageSize: 20 } 返回第一页;先按排序规则排序再切片,data.list 仅返回当前页数据,响应始终返回 data.pagination 分页信息(page/pageSize/total/totalPages/hasPrevious/hasNext)。兼容顶层 data.page / data.pageSize / data.page_size(与其他 list 接口一致,顶层值优先)。" + }, + { + "name": "pagination.page", + "type": "number", + "required": false, + "source": "body.pagination", + "description": "页码,从 1 开始的正整数" + }, + { + "name": "pagination.pageSize", + "type": "number", + "required": false, + "source": "body.pagination", + "description": "每页条数,正整数(兼容 pagination.page_size)" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码(顶层兼容写法,与其他 list 接口一致,从 1 开始;与 pagination.page 等价,顶层值优先)" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页条数(顶层兼容写法,与其他 list 接口一致;与 pagination.pageSize 等价,兼容 page_size,顶层值优先)" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "required": true, + "description": "匹配到的报表行列表\n已按 sort 规则排序;按分页返回当前页数据(默认第 1 页、每页 20 条)。" + }, + { + "name": "data.list[]", + "type": "object", + "required": true, + "description": "单条报表记录字段", + "children": [ + { + "name": "start_time", + "type": "string", + "description": "请求时传入的 start_time(或 null)" + }, + { + "name": "end_time", + "type": "string", + "description": "请求时传入的 end_time(或 null)" + }, + { + "name": "store_name", + "type": "string", + "description": "货主名称" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "barcode", + "type": "string", + "description": "商品条码(逗号分隔)" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "begin_total", + "type": "number", + "description": "期初库存量:取 start_time 前最后一条记录的 after_quantity(若 start_time 未传,默认为 0)" + }, + { + "name": "end_total", + "type": "number", + "description": "期末库存量:取 end_time 时点(<= end_time)最后一条记录的 after_quantity(若 end_time 未传则取最近一条)" + }, + { + "name": "inbound_total", + "type": "number", + "description": "在查询区间内累计入库数(INBOUND)" + }, + { + "name": "outbound_total", + "type": "number", + "description": "在查询区间内累计出库数(OUTBOUND)" + }, + { + "name": "stock_id", + "type": "number", + "description": "商品库存记录ID(stock_warehouse.id)" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "begin_total", + "type": "number", + "description": "期初库存(数值)" + }, + { + "name": "end_total", + "type": "number", + "description": "期末库存(数值)" + }, + { + "name": "inbound_total", + "type": "number", + "description": "入库合计" + }, + { + "name": "outbound_total", + "type": "number", + "description": "出库合计" + }, + { + "name": "by_space_mode", + "type": "string", + "description": "说明当前返回模式:'by_space' 或 'by_product'" + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID(仅当 where.by_space=true 返回)" + }, + { + "name": "space_name", + "type": "string", + "description": "库位名称(custom_name 优先,否则使用 space_code,where.by_space=true 时返回)" + } + ] + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "分页信息(始终返回;未传分页参数时默认 page=1、pageSize=20)", + "children": [ + { + "name": "page", + "type": "number", + "description": "当前页码(从 1 开始)" + }, + { + "name": "pageSize", + "type": "number", + "description": "每页条数" + }, + { + "name": "total", + "type": "number", + "description": "符合条件的总条数" + }, + { + "name": "totalPages", + "type": "number", + "description": "总页数" + }, + { + "name": "hasPrevious", + "type": "boolean", + "description": "是否有上一页" + }, + { + "name": "hasNext", + "type": "boolean", + "description": "是否有下一页" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] + }, + { + "method": "stock.report.searchStore", + "description": "货主侧库存报表查询:以货主维度统计商品出入库(入库和订单出库),不涉及库位维度。与 search 共享核心逻辑,但主维度为 store_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time(闭区间下限)、end_time(闭区间上限)、warehouse_ids(仓库ID数组,可选过滤)、stock_id(商品库存ID,单数)、stock_ids(商品库存ID数组)、keyword(商品关键字模糊匹配,支持 SKU ID/item_code/item_name/goods_code/barcode)。仅返回在时间区间内存在流水的数据。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间,支持字符串/Date;用于闭区间过滤:created_at >= start_time" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间,支持字符串/Date;用于闭区间过滤:created_at <= end_time" + }, + { + "name": "where.warehouse_ids", + "type": "array", + "required": false, + "source": "body", + "description": "仓库ID数组,用于过滤特定仓库(空或未传表示不过滤)", + "list": [] + }, + { + "name": "where.stock_id", + "type": "number", + "required": false, + "source": "body", + "description": "商品库存ID(单数,兼容数组),精确过滤指定商品;与 stock_ids 二选一,与 keyword 互斥" + }, + { + "name": "where.stock_ids", + "type": "array", + "required": false, + "source": "body", + "description": "商品库存ID数组,精确过滤指定商品列表;与 stock_id 二选一,与 keyword 互斥", + "list": [] + }, + { + "name": "where.keyword", + "type": "string", + "required": false, + "source": "body", + "description": "商品关键字,支持按 SKU ID(纯数字精确匹配)、商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)模糊匹配;与 stock_id / stock_ids 互斥" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象。支持 data.sort.sortField / data.sort.sort_field 与 data.sort.sortOrder / data.sort.sort_order;sortField 白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total(item_code/item_name 按字典序,其余按数值);sortOrder 支持 ASC / DESC。" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段(兼容 data.sort.sortField)。白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total。" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名(兼容 data.sort.sort_field),规则同 sort.sortField。" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向(兼容 data.sort.sortOrder),支持 ASC / DESC(大小写不敏感)。" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名(兼容 data.sort.sort_order),规则同 sort.sortOrder。" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "required": true, + "description": "匹配到的报表行列表,已按 sort 规则排序返回。" + }, + { + "name": "data.list[]", + "type": "object", + "required": true, + "description": "单条报表记录字段", + "children": [ + { + "name": "start_time", + "type": "string", + "description": "请求时传入的 start_time(或 null)" + }, + { + "name": "end_time", + "type": "string", + "description": "请求时传入的 end_time(或 null)" + }, + { + "name": "stock_id", + "type": "integer", + "description": "库存商品ID(wms_stock_warehouse.id)" + }, + { + "name": "store_id", + "type": "integer", + "description": "货主ID" + }, + { + "name": "warehouse_id", + "type": "integer", + "description": "仓库ID" + }, + { + "name": "store_name", + "type": "string", + "description": "货主名称" + }, + { + "name": "warehouse_name", + "type": "string", + "description": "仓库名称" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "barcode", + "type": "string", + "description": "条码" + }, + { + "name": "begin_total", + "type": "number", + "description": "期初库存" + }, + { + "name": "inbound_total", + "type": "number", + "description": "入库总量" + }, + { + "name": "outbound_total", + "type": "number", + "description": "出库总量" + }, + { + "name": "end_total", + "type": "number", + "description": "期末库存" + }, + { + "name": "space_id", + "type": "integer", + "description": "库位ID(where.by_space=true 时返回)" + }, + { + "name": "space_name", + "type": "string", + "description": "库位名称(where.by_space=true 时返回)" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + }, + { + "code": 400, + "message": "用户未绑定货主" + } + ] + }, + { + "method": "stock.report.export", + "description": "仓库侧提交库存报表导出异步任务(与 stock.report.search 使用相同查询条件),立即返回任务受理信息,不直接返回文件。可通过 stock.report.exportTaskProgress 查询进度。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time(闭区间下限)、end_time(闭区间上限)、by_space(是否按库位返回,默认 false)、store_ids(货主ID数组)、stock_id(商品库存ID,单数兼容数组)、stock_ids(商品库存ID数组)、keyword(商品关键字模糊匹配)。仅返回在时间区间内存在流水的数据(无流水键不返回)。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间,支持字符串/Date;用于闭区间过滤:created_at >= start_time" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间,支持字符串/Date;用于闭区间过滤:created_at <= end_time" + }, + { + "name": "where.by_space", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按库位返回,默认 false。false=按商品+货主聚合(多库位汇总),true=按商品+库位+货主返回;当 where.by_space=true 时,导出汇总 sheet 会额外包含 space_id、space_name。" + }, + { + "name": "where.store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "货主ID数组,用于过滤特定货主(空或未传表示不过滤)", + "list": [] + }, + { + "name": "export_mode", + "type": "string", + "required": false, + "source": "body", + "description": "导出模式(仅仓库侧接口生效,兼容驼峰 exportMode):传 'item' 时变更记录 sheet 包含 LOCK(锁定)类型记录;不传或传其他值则排除 LOCK。汇总 sheet 不受影响(只统计 INBOUND/OUTBOUND)。货主侧接口 stock.report.exportStore 不支持该参数,变更记录固定只含出入库流水(锁定/解锁不导出)。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象(请求体 data.sort)。支持 data.sort.sortField / data.sort.sort_field 与 data.sort.sortOrder / data.sort.sort_order;sortField 白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total(item_code/item_name 按字典序,其余按数值);sortOrder 支持 ASC / DESC(大小写不敏感);非法字段或顺序将回退默认排序。" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段(兼容 data.sort.sortField)。白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total;非法值回退默认排序。" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名(兼容 data.sort.sort_field),规则同 sort.sortField。" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向(兼容 data.sort.sortOrder),支持 ASC / DESC(大小写不敏感);非法值回退默认排序。" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名(兼容 data.sort.sort_order),规则同 sort.sortOrder。" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID,用于后续查询进度。" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态,提交受理后初始为 submitted。" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度百分比(0-100)。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务受理提示信息。" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "错误信息;受理成功时通常为空字符串。" + }, + { + "name": "result", + "type": "object|null", + "required": true, + "description": "任务结果对象;受理阶段为 null。" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务状态更新时间(时间戳)。" + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] + }, + { + "method": "stock.report.exportStore", + "description": "货主侧提交库存报表导出异步任务(与 stock.report.searchStore 使用相同查询条件),立即返回任务受理信息,不直接返回文件。可通过 stock.report.exportTaskProgress 查询进度。变更记录 sheet 只包含出入库流水(INBOUND/OUTBOUND),锁定/解锁(LOCK/UNLOCK)记录一律不导出;export_mode / exportMode 参数不支持也不生效(仅仓库侧 stock.report.export 支持)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time、end_time、warehouse_ids、stock_id(商品库存ID,单数兼容数组)、stock_ids(商品库存ID数组)、keyword(商品关键字模糊匹配)。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间" + }, + { + "name": "where.warehouse_ids", + "type": "array", + "required": false, + "source": "body", + "description": "仓库ID数组,用于过滤特定仓库", + "list": [] + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名" + } + ], + "response": [ + { + "name": "data.task_id", + "type": "string", + "required": true, + "description": "导出异步任务ID,用于后续查询进度" + }, + { + "name": "data.status", + "type": "string", + "required": true, + "description": "任务受理状态:submitted" + }, + { + "name": "data.progress", + "type": "number", + "required": true, + "description": "任务进度:0" + }, + { + "name": "data.message", + "type": "string", + "required": true, + "description": "任务受理消息" + }, + { + "name": "data.update_time", + "type": "number", + "required": true, + "description": "任务更新时间戳(ms)" + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] + }, + { + "method": "stock.report.exportTaskProgress", + "description": "根据 task_id 查询库存报表导出任务进度与结果;status 可能值:submitted/running/success/failed/not_found。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法)。" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法,兼容别名)。" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID。" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found。" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度百分比(0-100)。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明。" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息;成功时通常为空字符串。" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务成功后返回的下载链接;未完成或失败时为空字符串。" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务状态更新时间(时间戳)。" + }, + { + "name": "result", + "type": "object|null", + "required": true, + "description": "任务结果对象(包含导出文件信息);未完成或失败时可能为 null。" + } + ], + "errors": [] + } + ] + }, + { + "groupName": "库存管理模块", + "module": "storage.management", + "list": [ + { + "method": "storage.management.replenishmentDemand", + "description": "分拣缺货补货需求计算(仓库级别)。自动从用户上下文获取仓库,查询所有未完成储位分配的订单,计算每个SKU在分拣区与存货区的库存量、订单需求量、分拣区缺口、建议补货量及可补货库位。支持分页与排序。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize,默认 page=1 pageSize=20" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder。sortField 可选值:stock_id / pick_zone_quantity / storage_zone_quantity / total_demand / shortage / replenishment_needed,默认 shortage;sortOrder 可选 ASC / DESC,默认 DESC" + }, + { + "name": "store_id", + "type": "number|array", + "required": false, + "source": "body", + "description": "货主筛选:支持单值或数组(正整数),也可通过 where.store_id 传入;不传时返回全部货主;非法值(非正整数)报错" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "补货需求明细列表", + "children": [ + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "SKU ID" + }, + { + "name": "stock_code", + "type": "string", + "required": true, + "description": "SKU 编码" + }, + { + "name": "stock_name", + "type": "string", + "required": true, + "description": "SKU 名称" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "store_name", + "type": "string", + "required": true, + "description": "货主名称(货主签约表备注名优先,商家表公司名称兜底)" + }, + { + "name": "barcodes", + "type": "array", + "required": true, + "description": "SKU 条码列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "条码记录ID" + }, + { + "name": "barcode", + "type": "string", + "required": true, + "description": "条码内容" + } + ] + }, + { + "name": "pick_zone_quantity", + "type": "number", + "required": true, + "description": "分拣区可用库存(allow_allocation=1且is_active=1的库位上的可用库存)" + }, + { + "name": "storage_zone_quantity", + "type": "number", + "required": true, + "description": "存货区可用库存(其余库位上的可用库存)" + }, + { + "name": "total_demand", + "type": "number", + "required": true, + "description": "订单总需求量(汇总自订单明细 plan_qty)" + }, + { + "name": "shortage", + "type": "number", + "required": true, + "description": "分拣区缺口 = max(0, total_demand - pick_zone_quantity)" + }, + { + "name": "replenishment_needed", + "type": "number", + "required": true, + "description": "建议补货量 = min(shortage, storage_zone_quantity)" + }, + { + "name": "replenishment_status", + "type": "string", + "required": true, + "description": "补货状态枚举:replenishable=存货区足够覆盖缺口,移库可解决;true_shortage=存货区不足以覆盖缺口或两区均无库存,需采购" + }, + { + "name": "replenishment_locations", + "type": "array", + "required": true, + "description": "存货区可补货库位列表(最多5条,按可用库存降序)", + "children": [ + { + "name": "space_code", + "type": "string", + "required": true, + "description": "库位编码" + }, + { + "name": "space_name", + "type": "string", + "required": true, + "description": "库位展示名称(优先自定义名称 custom_name,无自定义名称时回退为库位编码 space_code)" + }, + { + "name": "available_quantity", + "type": "number", + "required": true, + "description": "该库位可用库存数量" + } + ] + } + ] + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息", + "children": [ + { + "name": "total_skus", + "type": "number", + "required": true, + "description": "涉及的SKU总数" + }, + { + "name": "total_shortage_skus", + "type": "number", + "required": true, + "description": "存在缺口的SKU数" + }, + { + "name": "total_replenishment_needed", + "type": "number", + "required": true, + "description": "总建议补货量" + }, + { + "name": "total_true_shortage_skus", + "type": "number", + "required": true, + "description": "真正缺货的SKU数(分拣区与存货区均无库存)" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页条数" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + } + ] + } + ], + "errors": [ + { + "code": 500, + "message": "缺少仓库上下文" + }, + { + "code": 200, + "message": "无待处理订单时返回空列表(list: [], summary: { total_skus: 0, total_shortage_skus: 0, total_replenishment_needed: 0, total_true_shortage_skus: 0 })" + } + ] + } + ] + }, + { + "groupName": "主体模块", + "module": "store", + "list": [ + { + "method": "store.createStore", + "description": "store.createStore 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB、group_wave_prefix=B、min_group_order_fetch_quantity=13、auto_grouping_enabled=false(是否自动加团,默认 false(关闭))、enable_external_express_code=false(是否启用外部快递编码,默认 false(关闭))", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "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" + }, + { + "name": "subject_config.group_wave_prefix", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "团购波次前缀,最多 5 个字符,默认 B" + }, + { + "name": "subject_config.min_group_order_fetch_quantity", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "最小团购订单抓取数量,默认 13" + }, + { + "name": "subject_config.auto_grouping_enabled", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否自动加团,默认 false(关闭)" + }, + { + "name": "subject_config.enable_external_express_code", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否启用外部快递编码;默认 false(关闭)。开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "store.createWarehouse", + "description": "store.createWarehouse 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB、group_wave_prefix=B、min_group_order_fetch_quantity=13、auto_grouping_enabled=false(是否自动加团,默认 false(关闭))、enable_external_express_code=false(是否启用外部快递编码,默认 false(关闭))", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "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" + }, + { + "name": "subject_config.group_wave_prefix", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "团购波次前缀,最多 5 个字符,默认 B" + }, + { + "name": "subject_config.min_group_order_fetch_quantity", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "最小团购订单抓取数量,默认 13" + }, + { + "name": "subject_config.auto_grouping_enabled", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否自动加团,默认 false(关闭)" + }, + { + "name": "subject_config.enable_external_express_code", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否启用外部快递编码;默认 false(关闭)。开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "store.joinStore", + "description": "store.joinStore 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.joinWarehouse", + "description": "store.joinWarehouse 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.getStoreRoles", + "description": "store.getStoreRoles 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "申请码(join_token)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "store.auditApply", + "description": "store.auditApply 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "audit_status", + "type": "string", + "required": true, + "source": "body", + "description": "审核状态(approved/rejected)" + }, + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "申请码(join_token)" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "当前审批门店ID" + }, + { + "name": "role_ids", + "type": "array", + "required": true, + "source": "body", + "description": "分配角色ID数组" + }, + { + "name": "reject_reason", + "type": "string", + "required": false, + "source": "body", + "description": "拒绝原因(audit_status=rejected 时可传)" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "货主-仓库签约模块", + "module": "storeWarehouse.store", + "list": [ + { + "method": "storeWarehouse.store.list", + "description": "查询当前主体可见的签约列表(当前主体在 store_id 方,对方在 warehouse_id 方)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "page_size", + "type": "number", + "required": false, + "source": "body", + "description": "分页大小,默认 20" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "签约备注或主体名称关键字" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "description": "签约关系列表" + }, + { + "name": "data.list[].id", + "type": "number", + "description": "签约关系主键 ID" + }, + { + "name": "data.list[].store_id", + "type": "number", + "description": "货主 ID" + }, + { + "name": "data.list[].store_name", + "type": "string", + "description": "货主名称(优先取备注名,无则取 company_name)" + }, + { + "name": "data.list[].warehouse_id", + "type": "number", + "description": "仓库 ID" + }, + { + "name": "data.list[].warehouse_name", + "type": "string", + "description": "仓库名称(优先取备注名,无则取 company_name)" + }, + { + "name": "data.list[].counterparty_id", + "type": "number", + "description": "对方主体 ID(当前为仓库则返回货主 ID,反之亦然)" + }, + { + "name": "data.list[].counterparty_name", + "type": "string", + "description": "对方主体名称" + }, + { + "name": "data.list[].counterparty_role", + "type": "string", + "description": "对方主体角色:warehouse 或 store" + }, + { + "name": "data.list[].current_subject_role", + "type": "string", + "description": "当前主体角色:warehouse 或 store" + }, + { + "name": "data.list[].auth_status", + "type": "number", + "description": "签约状态:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "data.list[].auth_status_label", + "type": "string", + "description": "签约状态中文标签" + }, + { + "name": "data.list[].apply_reason", + "type": "string", + "description": "申请原因" + }, + { + "name": "data.list[].review_comment", + "type": "string", + "description": "审核评语" + }, + { + "name": "data.list[].apply_time", + "type": "string|null", + "description": "申请时间" + }, + { + "name": "data.list[].review_time", + "type": "string|null", + "description": "审核时间" + }, + { + "name": "data.list[].auth_start", + "type": "string|null", + "description": "授权开始时间" + }, + { + "name": "data.list[].auth_end", + "type": "string|null", + "description": "授权结束时间" + }, + { + "name": "data.list[].actual_end", + "type": "string|null", + "description": "实际结束时间" + }, + { + "name": "data.list[].print_quantity", + "type": "number", + "description": "面单余额数量" + }, + { + "name": "data.list[].applied_by", + "type": "number|null", + "description": "申请人账号 ID" + }, + { + "name": "data.list[].reviewed_by", + "type": "number|null", + "description": "审核人账号 ID" + }, + { + "name": "data.list[].ended_by", + "type": "number|null", + "description": "解除人账号 ID" + }, + { + "name": "data.list[].remask", + "type": "string", + "description": "备注名(当前为仓库则返回货主备注名,反之亦然)" + }, + { + "name": "data.list[].warehouse_use_status", + "type": "number", + "description": "仓库侧启用状态:0=禁用 1=启用" + }, + { + "name": "data.list[].store_use_status", + "type": "number", + "description": "货主侧启用状态:0=禁用 1=启用" + }, + { + "name": "data.list[].policy_config", + "type": "object|null", + "description": "签约策略配置对象,无则为 null" + }, + { + "name": "data.list[].is_auth_valid", + "type": "boolean", + "description": "签约是否在有效期内" + }, + { + "name": "data.list[].remaining_days", + "type": "number", + "description": "剩余有效天数(未在有效期内时为 0)" + }, + { + "name": "data.list[].has_qimen_config", + "type": "boolean", + "description": "该货主是否已配置奇门(true=已配置,false=未配置)" + }, + { + "name": "data.total", + "type": "number", + "description": "总记录数" + }, + { + "name": "data.page", + "type": "number", + "description": "当前页码" + }, + { + "name": "data.page_size", + "type": "number", + "description": "每页条数" + }, + { + "name": "data.current_subject.store_id", + "type": "number", + "description": "当前主体 ID" + }, + { + "name": "data.current_subject.company_name", + "type": "string", + "description": "当前主体公司名称" + }, + { + "name": "data.current_subject.role", + "type": "string", + "description": "当前主体角色:warehouse 或 store" + } + ], + "errors": [] + }, + { + "method": "storeWarehouse.store.sign", + "description": "发起或确认签约(当前主体始终为 store_id 方/消费方,对方为 warehouse_id 方/提供方,支持仓库签仓库)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "counterparty_id", + "type": "number", + "required": true, + "source": "body", + "description": "对方主体 ID(兼容 warehouse_id / store_id),当前主体自动识别" + }, + { + "name": "temp_code", + "type": "string", + "required": false, + "source": "body", + "description": "临时签约码;传入后进入确认或预览流程" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.rename", + "description": "修改当前主体视角下的签约备注名", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.unbind", + "description": "解除或停用签约关系", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "warehouse_use_status", + "type": "number", + "required": false, + "source": "body", + "description": "仓库侧使用状态,0=停用,1=恢复" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.adjustPrintQuantity", + "description": "人工调整签约关系下的面单余额并记录变更日志", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "print_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "目标面单余额(覆盖值);优先使用该字段" + }, + { + "name": "target_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "目标面单余额(覆盖值);兼容别名" + }, + { + "name": "change_quantity", + "type": "number", + "required": true, + "source": "body", + "description": "兼容旧字段;当前按目标面单余额(覆盖值)解释,差值将自动写入变更日志" + }, + { + "name": "adjust_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "兼容旧字段;当前按目标面单余额(覆盖值)解释" + }, + { + "name": "reason", + "type": "string", + "required": true, + "source": "body", + "description": "人工调整缘由,必填" + }, + { + "name": "business_type", + "type": "string", + "required": false, + "source": "body", + "description": "业务来源类型,预留给后续 order_express 等自动扣减场景" + }, + { + "name": "business_id", + "type": "number", + "required": false, + "source": "body", + "description": "业务关联ID,预留给后续关联 wms_order_express.id" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.queryPrintQuantityLogs", + "description": "按 store_id 分页查询面单余额变更日志", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number|string", + "required": true, + "source": "body", + "description": "货主ID(必填)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页对象,包含 page 与 page_size;默认 { page: 1, page_size: 20 }", + "children": [ + { + "name": "page", + "type": "number", + "required": false, + "description": "页码,默认 1" + }, + { + "name": "page_size", + "type": "number", + "required": false, + "description": "每页条数,默认 20" + } + ] + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "返回结果对象,包含 list 和 pagination", + "children": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "变更日志列表,字段示例:id, contract_id, store_id, warehouse_id, change_type, business_type, business_id, change_quantity, balance_before, balance_after, reason, operator_id, created_by, created_at, updated_at" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页条数" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": false, + "description": "总页数" + }, + { + "name": "hasPrevious", + "type": "boolean", + "required": false, + "description": "是否有上一页" + }, + { + "name": "hasNext", + "type": "boolean", + "required": false, + "description": "是否有下一页" + } + ] + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或缺少 store_id" + }, + { + "code": "403", + "description": "仅可查询当前货主的面单余额变更日志" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storeWarehouse.store.getPolicyConfig", + "description": "读取签约策略配置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [ + { + "name": "data.contract_id", + "type": "number", + "required": true, + "description": "签约关系ID" + }, + { + "name": "data.policy_config", + "type": "object", + "required": true, + "description": "策略配置对象(包含默认值补齐后的字段)" + }, + { + "name": "data.policy_config.enable_external_express_code", + "type": "number", + "required": true, + "description": "是否启用外部快递编码(flag:0=关闭,1=开启;默认 0)" + } + ], + "errors": [] + }, + { + "method": "storeWarehouse.store.getPolicyConfigFields", + "description": "获取签约策略可配置字段元信息列表(含自动分配时间窗口字段)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "data", + "type": "array", + "required": true, + "description": "字段元信息数组,每项含 key/name/type/default/required/description/min/max/maxLength/options 等" + }, + { + "name": "data[].cutoff_order_enabled", + "type": "object", + "required": false, + "description": "启用截单字段元信息:key=cutoff_order_enabled,type=flag,default=1;启用后订单创建时间早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),不再自动分配快递和储位、不再自动加团" + }, + { + "name": "data[].allocate_start_time", + "type": "object", + "required": false, + "description": "开始自动分配时间字段元信息:key=allocate_start_time,type=string,default=08:00,min=00:00,max=23:59,maxLength=5;早于该时间的订单与超过截单时间行为一致,不自动分配快递和储位、不自动加团;开始时间晚于截单时间时截单时间视为次日(跨天窗口)" + }, + { + "name": "data[].cutoff_order_time", + "type": "object", + "required": false, + "description": "截单时间字段元信息:key=cutoff_order_time,type=string,default=18:00,min=00:00(下限已从 12:00 放开,支持凌晨截单/跨天窗口),max=23:59,maxLength=5" + }, + { + "name": "data[].day_start_time", + "type": "object", + "required": false, + "description": "自然日开始时间字段元信息:key=day_start_time,type=string,default=06:00,min=00:00,max=23:59,maxLength=5;今日统计窗口为 [该时间点, 次日该时间点),当前时间早于今日该时间点时窗口从昨日该时间点开始" + } + ], + "errors": [] + }, + { + "method": "storeWarehouse.store.savePolicyConfig", + "description": "保存签约策略配置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "policy_config", + "type": "object", + "required": true, + "source": "body", + "description": "策略配置对象;支持 receive_mode、auto_allocate_bin、auto_allocate_express(是否自动分配快递)、auto_allocate_storage(是否自动分配储位)、allow_mix_batch、allow_temp_storage、storage_separation、print_recharge_price(面单充值元/单,支持 2 位小数)、max_daily_inbound、remark、waybill_custom_display_type(面单自定义显示类型:1=隐藏,2=商品名称和数量,3=拣货库位和条码和数量,4=拣货库位和条码后5位和数量,5=拣货库位商品名称条码和数量)、enable_external_express_code(是否启用外部快递编码,flag:0=关闭,1=开启;默认 0)、cutoff_order_enabled(启用截单,flag:0=关闭,1=开启;默认 1)、cutoff_order_time(截单时间,HH:mm,默认 18:00,范围 00:00-23:59)、allocate_start_time(开始自动分配时间,HH:mm,默认 08:00,范围 00:00-23:59;开始时间晚于截单时间时截单时间视为次日)" + }, + { + "name": "policy_config.enable_external_express_code", + "type": "number", + "required": false, + "source": "body.policy_config", + "description": "是否启用外部快递编码(flag:0=关闭,1=开启;默认 0)" + }, + { + "name": "policy_config.cutoff_order_enabled", + "type": "number", + "required": false, + "source": "body.policy_config", + "description": "启用截单(flag:0=关闭,1=开启;默认 1)。启用后订单创建时间早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),不再自动分配快递和储位、不再自动加团" + }, + { + "name": "policy_config.cutoff_order_time", + "type": "string", + "required": false, + "source": "body.policy_config", + "description": "截单时间,格式 HH:mm,默认 18:00,范围 00:00-23:59;作为最后允许自动分配的时间,开始时间晚于截单时间时截单时间视为次日(跨天窗口)" + }, + { + "name": "policy_config.allocate_start_time", + "type": "string", + "required": false, + "source": "body.policy_config", + "description": "开始自动分配时间,格式 HH:mm,默认 08:00,范围 00:00-23:59;作为自动分配初始时间,当前时间早于该时间与超过截单时间行为一致(不自动分配快递和储位、不自动加团)。与截单时间相同(自动分配窗口为空)时报 400" + } + ], + "response": [ + { + "name": "data.contract_id", + "type": "number", + "required": true, + "description": "签约关系ID" + }, + { + "name": "data.policy_config", + "type": "object", + "required": true, + "description": "保存后并补齐默认值的策略配置对象" + }, + { + "name": "data.policy_config.enable_external_express_code", + "type": "number", + "required": true, + "description": "是否启用外部快递编码(flag:0=关闭,1=开启;默认 0)" + }, + { + "name": "data.policy_config.allocate_start_time", + "type": "string", + "required": true, + "description": "保存后并补齐默认值的开始自动分配时间(HH:mm,默认 08:00)" + } + ], + "errors": [ + { + "code": "400", + "message": "参数不合法:policy_config.allocate_start_time 与 policy_config.cutoff_order_time 相同(自动分配窗口为空)时拒绝保存;时间字段格式必须为 HH:mm" + } + ] + }, + { + "method": "storeWarehouse.store.listApiConfig", + "description": "查询签约关系下的接口配置列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "interface_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "接口类型ID,默认查询全部可用类型" + } + ], + "response": [ + { + "name": "data.list[].callback_url", + "type": "string", + "description": "API回调通知URL,来自 serializeQimenConfig 序列化" + } + ], + "errors": [] + }, + { + "method": "storeWarehouse.store.saveApiConfig", + "description": "新增或更新签约关系下的接口配置。QM_WMS 类型须填写奇门字段;OPEN_API 类型由系统自动生成 self_app_key 和 self_app_secret。签约关系级配置统一按货主开放接口落库:传入仓库开放接口(interface_type_id=3)时自动映射为货主开放接口(interface_type_id=2),货主主体也可维护", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "source": "body", + "description": "接口类型ID,必须是 wms_interface_type 已存在的类型;传 3(OPEN_API_WAREHOUSE 仓库开放接口)时按 2(OPEN_API 货主开放接口)落库" + }, + { + "name": "qimen_app_key", + "type": "string", + "required": false, + "source": "body", + "description": "奇门 AppKey(QM_WMS 类型必填,OPEN_API 类型不需要)" + }, + { + "name": "qimen_customer_id", + "type": "string", + "required": false, + "source": "body", + "description": "奇门客户ID(QM_WMS 类型必填,OPEN_API 类型不需要)" + }, + { + "name": "qimen_warehouse_code", + "type": "string", + "required": false, + "source": "body", + "description": "奇门仓库编码(QM_WMS 类型必填,OPEN_API 类型不需要)" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "source": "body", + "description": "应用名称" + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "source": "body", + "description": "【已忽略】回调地址不再由入参维护:保存时统一取 config.openapi.defaultCallbackUrl,传入值(含别名 callbackUrl)不再写入" + } + ], + "response": [], + "errors": [], + "notes": [ + "签约关系级接口配置统一按货主开放接口(OPEN_API)维护:interface_type_id=3(OPEN_API_WAREHOUSE 仓库开放接口)会被映射为 2(OPEN_API 货主开放接口)后落库,仓库不再通过该接口产生仓库开放接口配置", + "货主主体(project=store)也可以维护签约关系下的接口配置,不再要求当前主体为仓库", + "callback_url:签约关系配置保存时统一写入 config.openapi.defaultCallbackUrl(未配置时写 null),入参 callback_url/callbackUrl 一律忽略" + ] + }, + { + "method": "storeWarehouse.store.deleteQimenConfig", + "description": "删除签约关系下的奇门接口配置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "interface_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "接口类型ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.openAccount", + "description": "仓库代货主一键开户:同时完成账号注册、货主创建和仓库-货主签约", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(当前主体必须为仓库角色)" + } + ], + "params": [ + { + "name": "username", + "type": "string", + "required": true, + "source": "body", + "description": "登录账号(用户名),全局唯一" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "初始密码,不传则自动随机生成 12 位密码" + }, + { + "name": "real_name", + "type": "string", + "required": false, + "source": "body", + "description": "真实姓名" + }, + { + "name": "company_name", + "type": "string", + "required": true, + "source": "body", + "description": "公司全称,全局唯一,1-200 字符" + }, + { + "name": "business_license", + "type": "string", + "required": false, + "source": "body", + "description": "营业执照号" + }, + { + "name": "contact_person", + "type": "string", + "required": true, + "source": "body", + "description": "联系人姓名,1-50 字符" + }, + { + "name": "contact_phone", + "type": "string", + "required": false, + "source": "body", + "description": "联系电话" + }, + { + "name": "legal_person", + "type": "string", + "required": false, + "source": "body", + "description": "法人代表" + }, + { + "name": "contact_email", + "type": "string", + "required": false, + "source": "body", + "description": "联系邮箱" + }, + { + "name": "address", + "type": "string", + "required": false, + "source": "body", + "description": "公司地址" + }, + { + "name": "industry", + "type": "string", + "required": false, + "source": "body", + "description": "所属行业" + }, + { + "name": "auth_start", + "type": "string", + "required": false, + "source": "body", + "description": "授权开始日期,默认当天(ISO 8601 格式)" + }, + { + "name": "auth_end", + "type": "string", + "required": false, + "source": "body", + "description": "授权结束日期(ISO 8601 格式)" + }, + { + "name": "print_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "初始面单余额,默认 0" + }, + { + "name": "apply_reason", + "type": "string", + "required": false, + "source": "body", + "description": "申请原因,默认\"仓库代开户\",最长 2000 字符" + }, + { + "name": "store_remask", + "type": "string", + "required": false, + "source": "body", + "description": "货主备注名,最长 50 字符;不传或为空时默认取公司全称(截断 50 字符)填充" + }, + { + "name": "warehouse_remask", + "type": "string", + "required": false, + "source": "body", + "description": "仓库备注名,最长 50 字符" + } + ], + "response": [ + { + "name": "store_id", + "type": "number", + "required": true, + "description": "新建的货主 ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "新建的账号 ID" + }, + { + "name": "contract_id", + "type": "number", + "required": true, + "description": "新建的签约关系 ID" + }, + { + "name": "company_name", + "type": "string", + "required": true, + "description": "货主公司名称" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "新建的登录账号名" + }, + { + "name": "role_id", + "type": "number", + "required": true, + "description": "分配的货主管理员角色 ID" + } + ], + "errors": [] + }, + { + "method": "storeWarehouse.store.confirmSign", + "description": "确认签约:当前主体作为对方主体确认待签约的申请,签约状态从 1(申请中)变为 2(已通过);发起方不能确认自己的申请", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [ + { + "name": "data.mode", + "type": "string", + "required": true, + "description": "确认模式标识,固定为 confirm" + }, + { + "name": "data.contract", + "type": "object", + "required": true, + "description": "签约关系精简对象" + }, + { + "name": "data.contract.id", + "type": "number", + "required": true, + "description": "签约关系主键 ID" + }, + { + "name": "data.contract.store_id", + "type": "number", + "required": true, + "description": "货主方主体 ID" + }, + { + "name": "data.contract.warehouse_id", + "type": "number", + "required": true, + "description": "仓库方主体 ID" + }, + { + "name": "data.contract.counterparty_name", + "type": "string", + "required": true, + "description": "对方主体名称" + }, + { + "name": "data.contract.remask", + "type": "string", + "required": true, + "description": "当前主体视角的签约备注名" + }, + { + "name": "data.contract.use_status", + "type": "number", + "required": true, + "description": "当前主体启用状态:0=禁用 1=启用" + }, + { + "name": "data.contract.auth_status", + "type": "number", + "required": true, + "description": "签约状态:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "data.contract.auth_status_label", + "type": "string", + "required": true, + "description": "签约状态中文标签" + }, + { + "name": "data.contract.auth_end", + "type": "string|null", + "required": true, + "description": "授权结束时间" + }, + { + "name": "data.contract.print_quantity", + "type": "number", + "required": true, + "description": "面单余额数量" + }, + { + "name": "data.contract.has_qimen_config", + "type": "boolean", + "required": true, + "description": "是否已配置奇门" + } + ], + "errors": [ + { + "code": 400, + "message": "id 参数不能为空" + }, + { + "code": 400, + "message": "当前签约状态不允许确认,仅待签约状态可确认" + }, + { + "code": 403, + "message": "当前主体不在此签约关系中" + }, + { + "code": 403, + "message": "发起方不能确认自己的签约申请" + }, + { + "code": 404, + "message": "签约关系不存在" + } + ] + }, + { + "method": "storeWarehouse.store.createUser", + "description": "为货主创建用户:按用户名查询平台账号,账号不存在则自动注册并随机生成 12 位密码返回;两种情况统一完成货主工号绑定并授予货主管理员角色(wms_role.id=5)。幂等:重复调用不会重复创建账号或绑定", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(当前登录主体操作)" + } + ], + "params": [ + { + "name": "username", + "type": "string", + "required": true, + "source": "body", + "description": "用户名,3-50 位字母、数字或下划线,全局唯一" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主 ID" + } + ], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "账号 ID" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "用户名" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主 ID" + }, + { + "name": "created", + "type": "boolean", + "required": true, + "description": "是否本次新建账号;false 表示账号已存在仅完成授权" + }, + { + "name": "password", + "type": "string", + "required": false, + "description": "仅 created=true 时返回:随机生成的初始明文密码(12 位,随机大小写字母/数字)" + } + ], + "errors": [ + { + "code": 400, + "message": "username 参数不能为空" + }, + { + "code": 400, + "message": "用户名格式不合法,需为 3-50 位字母、数字或下划线" + }, + { + "code": 400, + "message": "store_id 参数不能为空" + }, + { + "code": 401, + "message": "未提供有效的认证令牌" + }, + { + "code": 404, + "message": "货主不存在" + }, + { + "code": 500, + "message": "货主管理员角色(id=5)未初始化" + }, + { + "code": 500, + "message": "服务内部错误" + } + ] + }, + { + "method": "storeWarehouse.store.export", + "description": "提交货主签约列表导出任务(异步)。入参筛选条件与 storeWarehouse.store.list 一致(keyword/counterparty_id/store_id/auth_status/use_status/warehouse_use_status/id 等,语义同 listForStore);page/page_size 忽略(全量导出)。提交后立即返回 task_id,后台异步生成 Excel 并上传,导出进度/下载请通过 storeWarehouse.store.exportTaskProgress 查询。数据来源 wms_store_warehouse 签约关系表;货主/仓库名称优先取签约备注名(store_remask/warehouse_remask),无则取 wms_store.company_name;角色/启用状态/是否有效/是否已配置奇门/是否需要我确认为中文展示列;全量导出无行数上限。任务缓存 Redis TTL 30 分钟;状态口径 submitted → running(10) → success(100),失败 failed + error。免权限免日志口径与 order.export 一致(isNeedAuth=false、isNeedLogin=true)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "签约备注或主体名称关键字(与 list 一致,模糊匹配 store_remask/warehouse_remask/双方 company_name)" + }, + { + "name": "counterparty_id", + "type": "number", + "required": false, + "source": "body", + "description": "对方主体ID(兼容 store_id),导出时过滤指定货主" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID(counterparty_id 的别名,两者传一即可)" + }, + { + "name": "auth_status", + "type": "number", + "required": false, + "source": "body", + "description": "签约状态过滤:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "use_status", + "type": "number", + "required": false, + "source": "body", + "description": "启用状态过滤:0=禁用 1=启用(兼容 warehouse_use_status)" + }, + { + "name": "warehouse_use_status", + "type": "number", + "required": false, + "source": "body", + "description": "仓库侧启用状态过滤(use_status 的别名,两者传一即可)" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "签约关系ID,兼容 contract_id/relation_id;导出时仅导出该签约关系" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成,格式 store_relation_list_export_{storeId}_{timestamp}_{random})" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态,枚举:submitted/running/success/failed/not_found(提交成功时为 submitted)" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "当前进度百分比(0-100),提交时返回 0" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果(提交时为 null;后台完成后为上传信息对象,含 filename/fileKey/url/cdnUrl/cosUrl/total_count)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选,非失败时为空字符串)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式不正确或筛选条件非法" + }, + { + "code": "500", + "message": "导出任务提交失败" + } + ] + }, + { + "method": "storeWarehouse.store.exportTaskProgress", + "description": "按 task_id 查询货主签约列表导出任务进度,返回 task_id、status、progress、message、result、error、download_url、update_time;上传完成后 download_url 返回下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);任务缓存 Redis TTL 30 分钟,task_id 缺失或缓存未命中时 status=not_found(正常响应,非报错)。状态口径 submitted → running(10) → success(100),失败 failed + error。免权限免日志口径与 order.exportTaskProgress 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID,兼容 task_id(下划线)与 taskId(驼峰)两种写法" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(task_id 缺失时为回显的空字符串,status=not_found)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果对象(完成后含 filename/fileKey/url/cdnUrl/cosUrl/total_count 等;未完成或 not_found 时为 null)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选,非失败时为空字符串)" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务完成后下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);未完成或不存在时为空字符串" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "最近一次状态更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [ + { + "code": "500", + "message": "查询失败或内部错误" + } + ] + } + ] + }, + { + "groupName": "仓库-货主签约模块", + "module": "storeWarehouse.warehouse", + "list": [ + { + "method": "storeWarehouse.warehouse.list", + "description": "仓库侧查询签约列表(支持查询外部合作仓库),当前仓库在 store_id 方(消费方),对方在 warehouse_id 方(提供方)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "page_size", + "type": "number", + "required": false, + "source": "body", + "description": "每页条数,默认 20,最大 200" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,模糊匹配己方备注名、对方备注名、己方公司名、对方公司名" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "对方主体 ID(兼容 counterparty_id)" + }, + { + "name": "auth_status", + "type": "number", + "required": false, + "source": "body", + "description": "授权状态筛选:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "use_status", + "type": "number", + "required": false, + "source": "body", + "description": "己方启用状态:0=禁用 1=启用" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "description": "签约关系列表" + }, + { + "name": "data.list[].id", + "type": "number", + "description": "签约关系主键 ID" + }, + { + "name": "data.list[].store_id", + "type": "number", + "description": "己方主体 ID(当前仓库)" + }, + { + "name": "data.list[].store_name", + "type": "string", + "description": "己方主体名称" + }, + { + "name": "data.list[].warehouse_id", + "type": "number", + "description": "对方主体 ID" + }, + { + "name": "data.list[].warehouse_name", + "type": "string", + "description": "对方主体名称" + }, + { + "name": "data.list[].counterparty_id", + "type": "number", + "description": "对方主体 ID(同 warehouse_id)" + }, + { + "name": "data.list[].counterparty_name", + "type": "string", + "description": "对方主体名称" + }, + { + "name": "data.list[].counterparty_role", + "type": "string", + "description": "对方主体角色:warehouse(外部合作仓库)或 store(货主)" + }, + { + "name": "data.list[].remask", + "type": "string", + "description": "己方对本次签约的备注名" + }, + { + "name": "data.list[].use_status", + "type": "number", + "description": "己方启用状态:0=禁用 1=启用" + }, + { + "name": "data.list[].auth_status", + "type": "number", + "description": "签约状态:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "data.list[].auth_status_label", + "type": "string", + "description": "签约状态中文标签" + }, + { + "name": "data.list[].auth_end", + "type": "string|null", + "description": "授权结束时间" + }, + { + "name": "data.list[].print_quantity", + "type": "number", + "description": "面单余额数量" + }, + { + "name": "data.list[].has_qimen_config", + "type": "boolean", + "description": "是否已配置奇门" + }, + { + "name": "data.list[].needs_my_confirm", + "type": "boolean", + "description": "是否需要当前仓库确认签约(对方发起且状态为申请中)" + }, + { + "name": "data.total", + "type": "number", + "description": "总记录数" + }, + { + "name": "data.page", + "type": "number", + "description": "当前页码" + }, + { + "name": "data.page_size", + "type": "number", + "description": "每页条数" + }, + { + "name": "data.current_subject", + "type": "object", + "description": "当前主体信息" + }, + { + "name": "data.current_subject.store_id", + "type": "number", + "description": "当前主体 ID" + }, + { + "name": "data.current_subject.company_name", + "type": "string", + "description": "当前主体公司名称" + }, + { + "name": "data.current_subject.role", + "type": "string", + "description": "当前主体角色:warehouse" + } + ], + "errors": [ + { + "code": 500, + "message": "获取签约列表失败" + } + ] + }, + { + "method": "storeWarehouse.warehouse.sign", + "description": "仓库侧发起签约(当前仓库在 store_id 方,对方在 warehouse_id 方,支持签约外部合作仓库)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "counterparty_id", + "type": "number", + "required": true, + "source": "body", + "description": "对方主体 ID(兼容 warehouse_id / store_id),当前主体自动识别" + } + ], + "response": [ + { + "name": "data.mode", + "type": "string", + "required": true, + "description": "签约结果模式:initiate=新建或更新签约申请,already_exists=已存在待确认的签约关系,already_confirmed=已签约" + }, + { + "name": "data.contract", + "type": "object", + "required": true, + "description": "签约关系精简对象(data.mode 非空时返回)" + }, + { + "name": "data.action", + "type": "string", + "required": false, + "description": "initiate 模式下的操作类型:create=新建签约申请,update=更新已有申请" + } + ], + "errors": [ + { + "code": 400, + "message": "counterparty_id / 对方主体ID 参数不能为空" + }, + { + "code": 400, + "message": "counterparty_id / 对方主体ID 参数不合法" + }, + { + "code": 400, + "message": "auth_start 参数不合法" + }, + { + "code": 400, + "message": "auth_end 参数不合法" + }, + { + "code": 400, + "message": "auth_end 不能早于 auth_start" + }, + { + "code": 404, + "message": "签约对象不存在" + } + ] + }, + { + "method": "storeWarehouse.warehouse.confirmSign", + "description": "仓库侧确认签约:作为对方主体确认待签约申请,签约状态从 1(申请中)变为 2(已通过);发起方不能确认自己的申请", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [ + { + "name": "data.mode", + "type": "string", + "required": true, + "description": "确认模式标识,固定为 confirm" + }, + { + "name": "data.contract", + "type": "object", + "required": true, + "description": "签约关系精简对象,字段同 storeWarehouse.store.confirmSign 的 data.contract" + } + ], + "errors": [ + { + "code": 400, + "message": "id 参数不能为空" + }, + { + "code": 400, + "message": "当前签约状态不允许确认,仅待签约状态可确认" + }, + { + "code": 403, + "message": "当前主体不在此签约关系中" + }, + { + "code": 403, + "message": "发起方不能确认自己的签约申请" + }, + { + "code": 404, + "message": "签约关系不存在" + } + ] + } + ] + }, + { + "groupName": "用户模块", + "module": "user", + "list": [ + { + "method": "user.login", + "description": "用户登录(仅返回 token)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "password 参数" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "username 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.loginByCode", + "description": "登录码登录(使用 ye4s_user.tmp_code)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "登录码,对应 ye4s_user.tmp_code" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.getLoginWechatCode", + "description": "获取微信扫码登录码(无 clientCode 时分配新客户端编码;有 clientCode 时可长轮询刷新)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "clientCode", + "type": "string", + "required": false, + "source": "body", + "description": "客户端编码;首次可不传,后续轮询建议透传已有值" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.getBindWechatCode", + "description": "获取微信绑定码(默认立即返回;显式开启长轮询后,最长等待60秒,状态变化立即返回)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "forceRefresh", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否强制刷新状态,true 时跳过缓存等待窗口" + }, + { + "name": "waitForChange", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否显式开启长轮询等待(推荐字段);true 时进入最长60秒等待" + }, + { + "name": "longPoll", + "type": "boolean", + "required": false, + "source": "body", + "description": "长轮询开关(兼容字段);true 时进入最长60秒等待" + }, + { + "name": "waitTimeoutMs", + "type": "number", + "required": false, + "source": "body", + "description": "等待超时毫秒数;后端自动封顶60000" + }, + { + "name": "init", + "type": "boolean", + "required": false, + "source": "body", + "description": "初始化请求标记;true 时强制立即返回,不进入长等待" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.unbindWechat", + "description": "解绑微信账号(清理 ye4s 关联账号数据)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.logout", + "description": "用户登出", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.info", + "description": "获取当前用户信息(支持微信登录态中间层:微信登录未绑定真实用户时返回微信层信息 is_bound=false/id=0,不 401;绑定/正常登录返回用户完整信息)。可选入参 wechat_appId:传入时按该小程序归属仓库过滤工号列表,只保留非仓库工号(货主)与仅该仓库工号;未传或查不到仓库时保持原逻辑", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wechat_appId", + "type": "string", + "required": false, + "source": "body", + "description": "小程序 AppID(可选):按 wms_wechat_app.appid 反查归属仓库,过滤 employees 列表" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.getAccountInfo", + "description": "获取当前登录账号的账号级信息(仅查询 wms_account,不返回 password_hash、salt、last_login_ip 等敏感字段;不接受账号ID入参,始终取登录上下文)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "******" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "账号ID" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "用户名" + }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "真实姓名" + }, + { + "name": "phone", + "type": "string", + "required": true, + "description": "手机号" + }, + { + "name": "email", + "type": "string", + "required": false, + "description": "邮箱" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "状态:0-禁用,1-启用,2-离职" + }, + { + "name": "is_custom_password", + "type": "number", + "required": true, + "description": "是否自定义密码:0-否,1-是" + }, + { + "name": "last_login_at", + "type": "string", + "required": false, + "description": "最后登录时间" + }, + { + "name": "created_at", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间" + } + ], + "errors": [ + { + "code": 401, + "message": "未登录或登录已过期" + }, + { + "code": 404, + "message": "账号不存在" + } + ] + }, + { + "method": "user.changeRole", + "description": "user.changeRole 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.register", + "description": "user.register 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.updateUsername", + "description": "修改当前登录账号的用户名;服务端做重名校验(排除自己),重名返回 409;用户名只允许字母、数字、下划线,长度3-50", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "******" + } + ], + "params": [ + { + "name": "username", + "type": "string", + "required": true, + "source": "body", + "description": "新用户名(3-50位,仅字母、数字、下划线)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "账号ID" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "修改后的用户名" + } + ], + "errors": [ + { + "code": 400, + "message": "username 不能为空或格式不正确(3-50位,仅字母、数字、下划线)" + }, + { + "code": 401, + "message": "未登录或登录已过期" + }, + { + "code": 404, + "message": "账号不存在" + }, + { + "code": 409, + "message": "用户名已存在" + } + ] + }, + { + "method": "user.changePassword", + "description": "修改当前登录账号密码;is_custom_password=0(未自定义过密码)时旧密码可不传,修改成功后将 is_custom_password 置为1;已自定义过密码后再次修改必须传旧密码校验", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "******" + } + ], + "params": [ + { + "name": "old_password", + "type": "string", + "required": false, + "source": "body", + "description": "旧密码;is_custom_password=1 时必填(兼容 oldPassword)" + }, + { + "name": "new_password", + "type": "string", + "required": true, + "source": "body", + "description": "新密码(去除首尾空格,最长64位;兼容 newPassword)" + } + ], + "response": [ + { + "name": "is_custom_password", + "type": "number", + "required": true, + "description": "是否自定义密码,修改成功后恒为1" + } + ], + "errors": [ + { + "code": 400, + "message": "新密码不能为空 / 请输入旧密码 / 旧密码错误" + }, + { + "code": 401, + "message": "未登录或登录已过期" + }, + { + "code": 404, + "message": "账号不存在" + } + ] + } + ] + }, + { + "groupName": "仓库模块", + "module": "warehouse", + "list": [ + { + "method": "warehouse.getWarehouseZones", + "description": "warehouse.getWarehouseZones 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getWarehouseTree", + "description": "warehouse.getWarehouseTree 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "number", + "required": true, + "source": "body", + "description": "warehouseId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getChildren", + "description": "warehouse.getChildren 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "zoneId", + "type": "number", + "required": true, + "source": "body", + "description": "zoneId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.create", + "description": "warehouse.create 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "warehouse.update", + "description": "warehouse.update 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "aisles", + "type": "string", + "required": false, + "source": "body", + "description": "aisles 参数" + }, + { + "name": "cell_height", + "type": "string", + "required": false, + "source": "body", + "description": "cell_height 参数" + }, + { + "name": "cell_length", + "type": "string", + "required": false, + "source": "body", + "description": "cell_length 参数" + }, + { + "name": "cell_width", + "type": "string", + "required": false, + "source": "body", + "description": "cell_width 参数" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "direction 参数" + }, + { + "name": "height", + "type": "number", + "required": false, + "source": "body", + "description": "height 参数" + }, + { + "name": "is_active", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否启用,支持 true/false 或 1/0" + }, + { + "name": "length", + "type": "number", + "required": false, + "source": "body", + "description": "length 参数" + }, + { + "name": "rack_columns", + "type": "string", + "required": false, + "source": "body", + "description": "rack_columns 参数" + }, + { + "name": "rack_levels", + "type": "string", + "required": false, + "source": "body", + "description": "rack_levels 参数" + }, + { + "name": "rack_rows", + "type": "string", + "required": false, + "source": "body", + "description": "rack_rows 参数" + }, + { + "name": "width", + "type": "number", + "required": false, + "source": "body", + "description": "width 参数" + }, + { + "name": "x", + "type": "number", + "required": false, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": false, + "source": "body", + "description": "y 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + }, + { + "name": "zone_code", + "type": "string", + "required": false, + "source": "body", + "description": "zone_code 参数" + }, + { + "name": "zone_name", + "type": "string", + "required": false, + "source": "body", + "description": "zone_name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.delete", + "description": "warehouse.delete 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.detail", + "description": "warehouse.detail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.checkBarcodeUnique", + "description": "warehouse.checkBarcodeUnique 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "barcode 参数" + }, + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.toggleActive", + "description": "warehouse.toggleActive 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "isActive", + "type": "string", + "required": false, + "source": "body", + "description": "isActive 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getPath", + "description": "warehouse.getPath 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getPickPath", + "description": "warehouse.getPickPath 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "query", + "description": "warehouse_id 参数" + }, + { + "name": "include_spaces", + "type": "string", + "required": false, + "source": "query", + "description": "include_spaces 参数" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "query", + "description": "limit 参数" + }, + { + "name": "sort_by", + "type": "string", + "required": false, + "source": "query", + "description": "sort_by 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateRackPosition", + "description": "warehouse.updateRackPosition 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "x", + "type": "number", + "required": true, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": true, + "source": "body", + "description": "y 参数" + }, + { + "name": "rack_id", + "type": "number", + "required": false, + "source": "path", + "description": "rack_id 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.recalculatePickPath", + "description": "warehouse.recalculatePickPath 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateNeighbors", + "description": "warehouse.updateNeighbors 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getAreaRacks", + "description": "warehouse.getAreaRacks 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "area_id", + "type": "number", + "required": true, + "source": "query", + "description": "area_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getSpacesByRack", + "description": "warehouse.getSpacesByRack 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.createRackWithSpaces", + "description": "warehouse.createRackWithSpaces 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.exportRackSpaces", + "description": "按货架ID导出仓位模板(含仓库编码、仓位编码、自定义名称、自定义条码、拣货顺序、仓位类型)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "货架ID,仅导出该货架下仓位" + } + ], + "response": [ + { + "name": "count", + "type": "number", + "description": "导出记录数" + }, + { + "name": "fileName", + "type": "string", + "description": "导出文件名" + }, + { + "name": "fileUrl", + "type": "string", + "description": "导出文件下载地址" + } + ], + "errors": [] + }, + { + "method": "warehouse.batchUpdateSpaceInfo", + "description": "按导出模板批量修改货架仓位信息,任一行越界或冲突则整批失败。前端提交示例:{ id: 36, items: [ { space_code: 'A01-01-01', custom_name: '拣货位1', custom_barcode: 'PICK-001', pick_sequence: 10, location_type_id: 3 } ] }。其中 id 为货架ID(可选,传入时只允许操作该货架下的仓位),space_code 为必填定位键,location_type_id 为仓位类型主键(可通过 index.getLocationTypeList 获取)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "货架ID,传入时校验所有 space_code 必须属于该货架,不传则只校验属于任意货架类型库位" + }, + { + "name": "items", + "type": "array", + "required": true, + "source": "body", + "description": "批量修改数据数组;每项支持字段:space_code、custom_name、custom_barcode、pick_sequence、location_type_name" + }, + { + "name": "items[].space_code", + "type": "string", + "required": true, + "source": "body", + "description": "仓位编码,作为批量修改的唯一定位键;缺失、重复或不存在都会整批失败" + }, + { + "name": "items[].custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "自定义名称,空字符串会被清空" + }, + { + "name": "items[].custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "自定义条码,批次内或系统内冲突都会整批失败;空字符串会被清空" + }, + { + "name": "items[].pick_sequence", + "type": "number", + "required": false, + "source": "body", + "description": "拣货顺序,必须为非负整数,超出边界则整批失败" + }, + { + "name": "items[].location_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓位类型ID,必须为正整数且在当前仓库或全局类型中存在(is_active=true),否则整批失败;传 null 或不传则不修改仓位类型" + } + ], + "response": [ + { + "name": "count", + "type": "number", + "description": "成功更新的记录数" + } + ], + "errors": [] + }, + { + "method": "warehouse.getSpaceInfo", + "description": "warehouse.getSpaceInfo 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [ + { + "code": "0", + "description": "仓位不存在" + }, + { + "code": "0", + "description": "仓位不属于当前仓库" + } + ] + }, + { + "method": "warehouse.updateSpaceInfo", + "description": "warehouse.updateSpaceInfo 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "custom_name 参数" + }, + { + "name": "location_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "location_type_id 参数" + }, + { + "name": "pick_sequence", + "type": "string", + "required": false, + "source": "body", + "description": "pick_sequence 参数" + }, + { + "name": "space_status", + "type": "string", + "required": false, + "source": "body", + "description": "space_status 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "出库模块", + "module": "order", + "list": [ + { + "method": "order.wave.batchList", + "description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总(storage_assignment_status / express_assignment_status / print_assignment_status / confirm_print_assignment_status / claim_assignment_status / pick_assignment_status / review_assignment_status / sync_assignment_status)。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。列表每条记录返回货主信息 store_name:当波次内所有订单均为同一货主(store_id)时返回货主名称,否则返回“混合”。货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。where 中各字段支持裸值与 {operator,value,type} 标准结构(eq/ne/gt/lt/ge/le/in/notin/between/notbetween/like/contains/notlike/startswith/endswith/isnull/isnotnull;未显式传 operator 时保持历史默认语义:wave_no/creator/logistics_name/item_part/item_snapshot_key/item_detail_machine 默认模糊,其余默认等值),详见 where 参数说明。", + "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": "only_todo", + "type": "number|boolean|string", + "required": false, + "source": "body", + "description": "是否仅返回待处理(仍有未复核订单)的波次,默认 0;传 1/true 时仅返回 unreviewed_order_count > 0 的波次。" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId。\n【操作符传参】每个字段均支持「裸值」或「标准结构 {'operator':'eq','value':'...','type':'text'}」两种写法;未显式传 operator 时按该字段默认语义(见下方括号)。支持的操作符:eq、ne、gt、lt、ge、le、in、notin、between、notbetween、like、contains、notlike、startswith、endswith、isnull、isnotnull,按字段分组允许:\n- 数值类(wave_id、wave_type、wave_status、source、total_orders、processed_orders 及 total_orders_min/max、processed_orders_min/max):eq/ne/gt/lt/ge/le/in/notin/between/notbetween/isnull/isnotnull;\n- 文本类(wave_no、creator、logistics_name、item_part_type、item_part、item_snapshot_key、item_detail_machine):eq/ne/like/contains/notlike/startswith/endswith/in/notin/isnull/isnotnull;\n- 布尔类(distinguish_express):eq/ne/in/notin;\n- 分配/复核状态类(storage_assignment_status、express_assignment_status、print_assignment_status、confirm_print_assignment_status、claim_assignment_status、review_assignment_status、sync_assignment_status):仅 eq;\n- 货主(store_id):eq/in/ne/notin。\nvalue 支持数组:like/contains/startswith/endswith 多值按 OR 展开,notlike 多值按 AND 展开;in/notin 要求 value 为非空数组;eq 传数组等价于 in;between/notbetween 要求 value 为长度 2 的数组(也接受 {start,end} / {from,to})。\n【字段清单】(括号内为未显式传 operator 时的默认语义)\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值,value 兼容 true/false/1/0)\n- total_orders / processed_orders(等值,新增:波次订单总数/已处理数,可直接用 between 等操作符)\n- total_orders_min / total_orders_max(范围,等价于 total_orders 的 ge / le)\n- processed_orders_min / processed_orders_max(范围,等价于 processed_orders 的 ge / le)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- confirm_print_assignment_status(等值,string,可选,英文枚举,取值:unconfirmed、partially_confirmed、confirmed;语义:按确认打印聚合判断,confirmed 表示聚合后全部已确认打印,unconfirmed 表示全部未确认,partially_confirmed 表示部分已确认)。\n- claim_assignment_status(等值,string,可选,取值:unclaimed / claimed,兼容中文 未领料 / 已领料;语义:以波次表 wms_wave_batch.claim_time 是否为空判定,二态无部分状态)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。\n- sync_assignment_status(等值,string,可选,英文枚举:unsynced、partially_synced、synced;分别表示未同步、部分同步、已同步;按订单 sync_status 聚合判断,synced 表示聚合后全部 fin,partially_synced 表示部分已同步且不含 error,unsynced 表示全未同步或包含 error(异常并入未同步集合))。\n- store_id(货主ID,可选,正整数,支持单值/数组/{operator,value} 结构,如 {\"operator\":\"\",\"value\":[1000281,1000000]};语义:默认 eq/in 返回包含任一筛选货主订单的波次,含混合货主波次;ne/notin 返回不包含所选货主订单的波次;不支持 like 等文本操作符)。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / confirm_print_assignment_status / claim_assignment_status / pick_assignment_status / review_assignment_status / sync_assignment_status / unreviewed_order_count)。其中 pick_assignment_status 按订单 pick_status 聚合判定,取值:未拣货/部分拣货/已拣货/拣货异常。sync_assignment_status 按订单 sync_status 聚合判定,取值:未同步/部分同步/已同步/同步异常(error 并入未同步集合)。confirm_print_assignment_status 按订单 confirm_print_status 聚合判定,取值:未确认打印/部分确认打印/已确认打印。claim_assignment_status 按波次表 wms_wave_batch.claim_time 判定(已领料/未领料,二态),并同步返回 claim_time 与 claim_operator。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。每条记录新增字段 store_name(string):货主信息,当波次内所有订单均为同一货主(store_id)时返回货主名称,否则返回“混合”;货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 500, + "message": "查询失败" + } + ] + }, + { + "method": "order.pendingOrder.downloadCreateTemplate", + "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为 .xlsx 附件下载。表头中标注 * 的列为必填项(橙色背景),可选列为灰色背景,包含示例数据行和填写说明工作表。多行相同订单号的行组成一个完整订单,每行代表一条商品明细。模板共 25 列(A-Y):店铺名称(shop_nick)位于第2列B列,紧接*订单号(delivery_order_code)之后;其余必填列为*收件人姓名(name)、*手机号(mobile)、*详细地址(detail_address)、*商品编码(item_code)、*计划数量(plan_qty);非必填列依次为货主ID(store_id)、电话(tel)、省份(province)、城市(city)、区/县(area)、镇/街道(town)、邮编(zip_code)、快递编码(logistics_code)、快递名称(logistics_name)、系统平台编码(sys_platform_code)、来源平台编码(source_platform_code)、来源订单号(source_order_codes)、订单类型(order_type)、是否紧急(is_urgency)、是否需要发票(invoice_flag)、商品名称(item_name)、行号(order_line_no)、实际价格(actual_price)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "base64", + "type": "string", + "required": true, + "description": "base64 编码的 xlsx 文件内容" + }, + { + "name": "filename", + "type": "string", + "required": true, + "description": "建议保存的文件名,固定为 创建订单导入模板.xlsx" + }, + { + "name": "mime", + "type": "string", + "required": true, + "description": "文件 MIME 类型,固定为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + } + ], + "errors": [] + }, + { + "method": "order.pendingOrder.manualWaybill", + "description": "手工录入运单号。为指定待处理订单创建一条运单记录(wms_order_express 表),仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。完成后自动更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印。可选传入 express_code,行为参考 updateOrderExpress:从当前仓库快递列表(带缓存)中查找对应项,若为自定义映射(is_system_setting=true),订单 sys_logistics_code/name 写系统快递编码和名称、logistics_code/name 写自定义编码和名称;若为系统快递(is_system_setting=false),四个字段均写系统快递的 code/name;未找到则报错;不传则运单记录沿用订单当前系统快递信息。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number", + "required": true, + "source": "body", + "description": "订单 ID,必须为正整数" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号,非空字符串" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": false, + "source": "body", + "description": "物流接口名称(选填),手工填入的值,trim 后为空则传 null" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "快递编码(选填),可为系统编码或仓库自定义编码。传入时同步修改订单的快递信息,行为参考 updateOrderExpress;不传时运单记录沿用订单当前系统快递信息" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "创建的运单记录 ID" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "business_key", + "type": "number", + "required": true, + "description": "递增的业务键,同一订单下从 1 开始递增" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": false, + "description": "写入的物流接口名称,未传时为 null" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "description": "传入的快递编码,未传时不返回" + }, + { + "name": "sys_logistics_code", + "type": "string", + "required": false, + "description": "写入订单的系统快递编码,仅在传入 express_code 时返回" + }, + { + "name": "sys_logistics_name", + "type": "string", + "required": false, + "description": "写入订单的系统快递名称,仅在传入 express_code 时返回" + }, + { + "name": "logistics_code", + "type": "string", + "required": false, + "description": "写入订单与运单记录的快递编码(自定义或系统),仅在传入 express_code 时返回" + }, + { + "name": "logistics_name", + "type": "string", + "required": false, + "description": "写入订单与运单记录的快递名称(自定义或系统),仅在传入 express_code 时返回" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 必须为正整数" + }, + { + "code": 400, + "message": "waybill_code(运单号)不能为空" + }, + { + "code": 400, + "message": "订单不存在或不属于当前仓库" + }, + { + "code": 400, + "message": "订单当前步骤不在允许范围,仅允许待处理状态(step 1/2/3)的订单手工录入运单号" + }, + { + "code": 400, + "message": "订单已标记待出库,不允许手工录入运单号" + }, + { + "code": 404, + "message": "快递编码 不存在" + }, + { + "code": 500, + "message": "内部错误:OrderExpress 模型未加载或数据库写入失败" + } + ] + }, + { + "method": "order.pendingOrder.allocateSubOrderNumber", + "description": "分配子单号(异步任务模式)。为指定订单按 business_key(从 2 开始)全量传入 createWaybillCodePipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发安全:已分配(status=1)自动跳过,未分配 INSERT status=0 占位后分配。请求立即返回 task_id(sub_ 前缀),后续通过 allocateSubOrderNumberProgress 按 task_id 或 business_key 查询进度与结果。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number", + "required": true, + "source": "body", + "description": "订单 ID,必须为正整数" + }, + { + "name": "sub_order_count", + "type": "number", + "required": true, + "source": "body", + "description": "子单号数量,>= 1。business_key 从 2 开始递增,如 count=1 则创建 business_key=2,count=3 则创建 2/3/4" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(sub_ 前缀),用于查询进度" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/partial/failed" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比:5/50/80/100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "分配结果摘要,含 total_count/skip_count/pending_count/business_keys/skipped_business_keys/pending_business_keys/details 等字段" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 必须为正整数" + }, + { + "code": 400, + "message": "sub_order_count 必须为正整数且 >= 1" + }, + { + "code": 400, + "message": "订单不存在或不属于当前仓库" + }, + { + "code": 400, + "message": "订单当前步骤不在允许范围,仅允许待处理状态(step 1/2/3)的订单分配子单号" + }, + { + "code": 400, + "message": "订单已标记待出库,不允许分配子单号" + }, + { + "code": 500, + "message": "内部错误:OrderExpress 模型未加载或运单分配链路异常" + } + ] + }, + { + "method": "order.pendingOrder.allocateSubOrderNumberProgress", + "description": "查询子单号分配任务进度。可按 task_id 查询整体进度,也可传入 business_key 进一步过滤该业务ID对应的分配详情与最终结果。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": true, + "source": "body", + "description": "任务 ID(返回的 task_id),支持 task_id 或 taskId 两种写法" + }, + { + "name": "business_key", + "type": "number", + "required": false, + "source": "body", + "description": "子单号业务ID(可选),传入后返回该 business_key 对应的分配详情。支持 business_key 或 businessKey 两种写法" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/partial/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "分配结果。若传了 business_key,额外返回 filtered_business_key 与 matched_detail" + } + ], + "errors": [ + { + "code": 500, + "message": "查询缓存异常" + } + ] + }, + { + "method": "order.pendingOrder.batchMarkPrinted", + "description": "批量设置订单为已打印状态。将给定订单ID列表中属于当前仓库的订单的 print_status 更新为 'fin'。先查 current 表(wms_order_delivery_{warehouseId}),未命中的 ID 再兜底查 dispatch 表(wms_order_delivery_{warehouseId}_dispatch)。仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印的订单会被静默跳过。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + } + ], + "response": [ + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "实际更新的订单数量(已打印的订单会被静默跳过,不计入)" + }, + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的订单ID列表(原样回传)" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.bindExpressPackageMaterialByWaybill", + "description": "按运单号绑定包材。仅需传入运单号与包材ID,系统自动根据运单号反查对应订单运单记录并绑定包材,无需传入订单ID。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号,必填。" + }, + { + "name": "package_material_id", + "type": "number|string", + "required": true, + "source": "body", + "description": "包材ID,必填。" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "运单号对应的订单ID(成功时返回于 data 对象中)。" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_id", + "type": "number", + "required": true, + "description": "绑定后的包材ID(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_name_snapshot", + "type": "string", + "required": true, + "description": "绑定后的包材名称快照(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "description": "绑定后的包材编码(成功时返回于 data 对象中)。" + } + ], + "errors": [ + { + "code": 404, + "message": "运单号不存在" + }, + { + "code": 400, + "message": "包材不存在或已禁用" + }, + { + "code": 500, + "message": "绑定包材失败" + } + ] + }, + { + "method": "order.wave.confirmPrintScan", + "description": "确认打印扫描(与领单 pick.waveClaimScan 操作一致):扫波次内任一订单的面单号,将波次下全部已打印(print_status='fin')且非拦截的订单批量标记 confirm_print_status='fin',并写订单操作日志(ORDER_CONFIRM_PRINT)。拦截订单跳过(不确认、不阻断);波次下存在未打印订单(print_status != 'fin')时阻断;全部已确认时重复扫描返回 already_confirmed。成功后递增确认打印未领单统计版本号,驱动 confirmPrintUnclaimedWaveCount 长轮询立即返回新值。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_no", + "type": "string", + "required": true, + "source": "body", + "description": "面单号/运单号(必填,用于定位订单及所属波次)" + } + ], + "response": [ + { + "name": "waybill_no", + "type": "string", + "required": false, + "description": "扫描的面单号" + }, + { + "name": "matched_order_id", + "type": "number", + "required": false, + "description": "面单号匹配到的订单ID" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "波次编码" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "波次下总订单数" + }, + { + "name": "intercepted_order_count", + "type": "number", + "required": false, + "description": "波次下拦截订单数(跳过确认)" + }, + { + "name": "confirmed_order_count", + "type": "number", + "required": false, + "description": "已确认打印订单数(confirm_print_status='fin')" + }, + { + "name": "newly_confirmed_order_count", + "type": "number", + "required": false, + "description": "本次新增确认订单数(仅 status=confirmed 时返回)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "确认结果:confirmed=本次完成确认 / already_confirmed=已全部确认" + } + ], + "errors": [ + { + "code": 400, + "message": "waybill_no 必填(面单号/运单号)" + }, + { + "code": 400, + "message": "缺少当前用户仓库上下文 store_id" + }, + { + "code": 400, + "message": "运单对应订单未分配波次" + }, + { + "code": 400, + "message": "波次存在未打印订单,禁止确认打印(返回 unprinted_order_count)" + }, + { + "code": 404, + "message": "未查询到该面单号对应的订单,无记录" + }, + { + "code": 500, + "message": "内部错误(OrderDeliveryFactory/订单模型不可用或更新失败)" + } + ] + }, + { + "method": "order.wave.confirmPrintUnclaimedWaveCount", + "description": "快速查询「已确认打印但未领单」的波次数量,使用当前登录操作者仓库上下文。口径(波次表驱动):未领单以 wms_wave_batch.claim_time IS NULL 为准(历史领单发生在波次表增加 claim_time 字段之前时,订单维度 claim_status 可能已是 fin 但波次表无记录,故不用订单 claim_status 判断),已确认打印以波次下存在 confirm_print_status='fin' 的非取消订单为准,仅统计 wave_status 0/1 的波次;波次下订单均已领料但 claim_time 为空的(历史领单/旧版拦截跳过导致),重新扫描领料时 pick.waveClaimScan 会在 already_claimed 幂等分支补写 claim_time,从而不再被本统计计为未领单。支持长轮询(参考扫码登录):不传 last_count 立即返回当前值(status=current);传 last_count 且与当前值不同立即返回新值(status=changed);传 last_count 且与当前值相同则进入等待,每 1 秒检查统计版本号(确认打印/领单成功会递增版本号),最长等待 60 秒:期间变化立即返回新值(status=changed),超时未变化重查后返回当前值(status=timeout)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "last_count", + "type": "number", + "required": false, + "source": "body", + "description": "上次调用返回的 count(可选基线);传入后进入最长 60s 长轮询等待变化,不传则立即返回当前值" + } + ], + "response": [ + { + "name": "count", + "type": "number", + "required": true, + "description": "已确认打印但未领单的波次数量" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "返回状态:current=即时返回当前值 / changed=检测到变化返回新值 / timeout=等待 60s 未变化返回当前值" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 500, + "message": "查询失败" + } + ] + } + ] + }, + { + "groupName": "店铺模块", + "module": "shops", + "list": [ + { + "method": "shops.list", + "description": "分页查询店铺,支持 where 条件(支持字段:id, platform_code, custom_name, shop_name, status, quickWhere),兼容 snake_case 与 camelCase 入参;返回分页信息与标准化店铺列表。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,兼容 pagination.page/currentPage" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页大小,兼容 page_size/pagination.page_size,最大 200" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件,支持标准 where 结构或 quickWhere 简写,字段兼容 id/platform_code/custom_name/shop_name/status/quickWhere" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用结果标识,成功为 success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,成功为 200" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "店铺数组,元素结构见 children", + "children": [ + { + "name": "id", + "type": "number", + "description": "店铺 ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库 ID" + }, + { + "name": "platform_code", + "type": "string", + "description": "平台编码,返回大写" + }, + { + "name": "platform_name", + "type": "string", + "description": "平台名称(来自关联 printPlatform)" + }, + { + "name": "shop_name", + "type": "string", + "description": "店铺原始名称" + }, + { + "name": "custom_name", + "type": "string|null", + "description": "店铺自定义名称" + }, + { + "name": "status", + "type": "number", + "description": "授权状态:0=未授权,1=已授权" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + } + ] + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "description": "当前页" + }, + { + "name": "pageSize", + "type": "number", + "description": "每页大小" + }, + { + "name": "total", + "type": "number", + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "description": "总页数" + }, + { + "name": "hasNext", + "type": "boolean", + "description": "是否有下一页" + }, + { + "name": "hasPrevious", + "type": "boolean", + "description": "是否有上一页" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 400, + "message": "where 参数解析失败" + }, + { + "code": 500, + "message": "查询店铺列表失败" + } + ] + }, + { + "method": "shops.add", + "description": "新增店铺,校验 platform_code 必须匹配已配置且处于 ACTIVE 且未删除的打印平台;custom_name 必填且长度<=100。shop_name 由服务端生成待授权占位名(PENDING_*),授权后再同步真实店铺名。支持 snake_case 与 camelCase 入参兼容。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "platform_code", + "type": "string", + "required": true, + "source": "body", + "description": "平台编码,兼容 platformCode,服务端会标准化为大写并验证" + }, + { + "name": "custom_name", + "type": "string", + "required": true, + "source": "body", + "description": "店铺自定义名称,最大长度 100" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "新建店铺 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "platform_code 未匹配到打印平台编码" + }, + { + "code": 400, + "message": "custom_name 不能为空" + }, + { + "code": 400, + "message": "custom_name 长度不能超过 100" + }, + { + "code": 409, + "message": "同仓同平台下 shop_name 已存在" + }, + { + "code": 500, + "message": "新增店铺失败" + } + ] + }, + { + "method": "shops.del", + "description": "软删除店铺:将 shop_name 修改为 DELETED_SHOP__ 并清空敏感字段;若存在 ExpressInterface 引用则返回 409;返回 deleted=true 与 id。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "店铺 ID,兼容 shop_id/shopId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.deleted", + "type": "boolean", + "required": true, + "description": "是否已删除" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "删除的店铺 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "shop_id 参数不合法" + }, + { + "code": 404, + "message": "店铺不存在" + }, + { + "code": 409, + "message": "店铺存在快递接口引用,无法删除" + }, + { + "code": 500, + "message": "删除店铺失败" + } + ] + }, + { + "method": "shops.edit", + "description": "编辑店铺,仅允许修改 platform_code、custom_name 或 shop_name,至少传入其中一个。platform_code 会校验平台存在且为 ACTIVE(未匹配返回 400);custom_name/shop_name 传入时需非空且长度<=100;shop_name 修改需满足同仓同平台唯一(同时改 platform_code 时按新平台校验,冲突返回 409);服务端兼容 snake_case/camelCase 入参。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "店铺 ID,兼容 shop_id/shopId" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "source": "body", + "description": "平台编码,兼容 platformCode,服务端会转为大写并校验" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "自定义名称,兼容 customName,若传入需非空且 <=100 字符" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(平台真实店铺名),兼容 shopName,若传入需非空且 <=100 字符,且同仓同平台下不可重复" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.updated", + "type": "boolean", + "required": true, + "description": "是否已更新" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "被更新的店铺 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "仅允许修改 platform_code、custom_name 或 shop_name" + }, + { + "code": 400, + "message": "platform_code 未匹配到打印平台编码" + }, + { + "code": 400, + "message": "custom_name 不能为空" + }, + { + "code": 400, + "message": "shop_name 不能为空" + }, + { + "code": 400, + "message": "shop_name 长度不能超过 100" + }, + { + "code": 400, + "message": "shop_id 参数不合法" + }, + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 404, + "message": "店铺不存在" + }, + { + "code": 409, + "message": "同仓同平台下 shop_name 已存在" + }, + { + "code": 500, + "message": "编辑店铺失败" + } + ] + }, + { + "method": "shops.GetAuthorizeSessionKey", + "description": "按店铺所属平台向授权服务换取授权会话(saveShop)。入参兼容 id/shop_id/shopId 与 callbackurl/callback_url,callbackurl 必填;视频号平台还需 appId 与 toUserName(此时不带 RedirectCodeUrl),京东平台附带 VenderID。成功后更新店铺 access_token 与 status=1,返回 data.message='获取授权成功'。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "店铺 ID,兼容 shop_id/shopId" + }, + { + "name": "callbackurl", + "type": "string", + "required": true, + "source": "body", + "description": "授权回调地址,兼容 callback_url,最长 500 字符" + }, + { + "name": "appId", + "type": "string", + "required": false, + "source": "body", + "description": "视频号平台必填:授权服务应用 ID" + }, + { + "name": "toUserName", + "type": "string", + "required": false, + "source": "body", + "description": "视频号平台必填:授权服务用户名" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.message", + "type": "string", + "required": true, + "description": "成功时固定返回「获取授权成功」" + } + ], + "errors": [ + { + "code": 400, + "message": "shop_id 不能为空" + }, + { + "code": 400, + "message": "shop_id 参数不合法" + }, + { + "code": 400, + "message": "callbackurl 不能为空" + }, + { + "code": 400, + "message": "callbackurl 长度不能超过 500" + }, + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 404, + "message": "店铺不存在" + }, + { + "code": 400, + "message": "platform_code 不能为空" + }, + { + "code": 400, + "message": "platform_code 未匹配到打印平台编码" + }, + { + "code": 400, + "message": "视频号授权需要提供 appId 和 toUserName" + }, + { + "code": 500, + "message": "获取授权失败,未返回 sessionKey" + }, + { + "code": 500, + "message": "获取授权失败:接口请求异常(上游返回非 0 时携带上游 msg)" + } + ] + } + ] + }, + { + "groupName": "包材管理模块", + "module": "setting.packageMaterial", + "list": [ + { + "method": "setting.packageMaterial.create", + "description": "创建包材(当前仓库范围)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "material_code", + "type": "string", + "required": true, + "source": "body", + "description": "包材编码(大写且在当前仓库唯一)" + }, + { + "name": "material_name", + "type": "string", + "required": true, + "source": "body", + "description": "包材名称" + }, + { + "name": "material_type", + "type": "string", + "required": false, + "source": "body", + "description": "包材类型" + }, + { + "name": "spec", + "type": "string", + "required": false, + "source": "body", + "description": "规格" + }, + { + "name": "length", + "type": "number", + "required": false, + "source": "body", + "description": "长度" + }, + { + "name": "width", + "type": "number", + "required": false, + "source": "body", + "description": "宽度" + }, + { + "name": "height", + "type": "number", + "required": false, + "source": "body", + "description": "高度" + }, + { + "name": "weight", + "type": "number", + "required": false, + "source": "body", + "description": "重量(单位 g)" + }, + { + "name": "cost_price", + "type": "number", + "required": false, + "source": "body", + "description": "成本价" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态 0/1,默认 1" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "包材 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 409, + "message": "material_code 冲突" + }, + { + "code": 500, + "message": "服务器错误" + } + ] + }, + { + "method": "setting.packageMaterial.update", + "description": "更新包材(按 id 更新,支持部分字段)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "包材 ID(也兼容 material_id/materialId)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "包材 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 404, + "message": "未找到包材或无权限" + }, + { + "code": 409, + "message": "material_code 冲突" + } + ] + }, + { + "method": "setting.packageMaterial.delete", + "description": "删除包材(支持 ids 数组或逗号分隔字符串,兼容 id/material_id/materialId)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|number|string", + "required": true, + "source": "body", + "description": "要删除的 ID 列表" + } + ], + "response": [ + { + "name": "deleted", + "type": "boolean", + "required": true, + "description": "是否删除成功" + } + ], + "errors": [ + { + "code": 400, + "message": "ids 参数错误" + }, + { + "code": 404, + "message": "存在不存在或无权限删除的项" + } + ] + }, + { + "method": "setting.packageMaterial.get", + "description": "查询包材列表,支持 where + pagination(兼容旧别名 list,建议使用 get)", + "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": "筛选条件,支持 material_code/material_name/material_type/status/quickWhere" + } + ], + "response": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页" + }, + { + "name": "page_size", + "type": "number", + "required": true, + "description": "每页大小" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总数" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "包材项数组" + } + ], + "errors": [ + { + "code": 400, + "message": "参数解析失败" + } + ] + }, + { + "method": "setting.packageMaterial.list", + "description": "兼容旧称 list,内部转发至 get;建议改用 setting.packageMaterial.get", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.packageMaterial.search", + "description": "包材关键字搜索,按 material_code / material_name 模糊匹配,最多返回 50 条(仅返回启用中的包材)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,模糊匹配 material_code、material_name;为空时返回前 50 条启用中的包材" + } + ], + "response": [ + { + "name": "data[]", + "type": "array", + "required": true, + "description": "包材列表,每项包含 id(包材ID)、material_code(包材编码)、material_name(包材名称)、material_type(包材类型)、spec(规格)、status(状态)" + } + ], + "errors": [ + { + "code": 500, + "message": "服务器错误" + } + ] + } + ] + }, + { + "groupName": "package-supplier-module", + "module": "setting.packageSupplier", + "list": [ + { + "method": "setting.packageSupplier.create", + "description": "Create package supplier (current warehouse scope)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "supplier_code", + "type": "string", + "required": true, + "source": "body", + "description": "Supplier code (uppercased, unique in warehouse)" + }, + { + "name": "supplier_name", + "type": "string", + "required": true, + "source": "body", + "description": "Supplier name" + }, + { + "name": "contact_name", + "type": "string", + "required": false, + "source": "body", + "description": "Contact name" + }, + { + "name": "contact_phone", + "type": "string", + "required": false, + "source": "body", + "description": "Contact phone" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "Status 0/1, default 1" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "Created supplier id" + } + ], + "errors": [ + { + "code": 400, + "message": "Invalid parameters" + }, + { + "code": 409, + "message": "supplier_code conflict" + } + ] + }, + { + "method": "setting.packageSupplier.update", + "description": "Update package supplier by id (partial update supported)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "Supplier id (also supports supplier_id / supplierId)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "Supplier id" + } + ], + "errors": [ + { + "code": 400, + "message": "Invalid parameters" + }, + { + "code": 404, + "message": "Supplier not found or no permission" + } + ] + }, + { + "method": "setting.packageSupplier.delete", + "description": "Delete package suppliers (supports ids array or comma-separated string)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|number|string", + "required": true, + "source": "body", + "description": "IDs to delete" + } + ], + "response": [ + { + "name": "deleted", + "type": "boolean", + "required": true, + "description": "Deleted flag" + } + ], + "errors": [ + { + "code": 400, + "message": "ids invalid" + }, + { + "code": 404, + "message": "Some items not found or no permission" + } + ] + }, + { + "method": "setting.packageSupplier.get", + "description": "Get package supplier list (supports where + pagination). list is an alias to get; prefer get.", + "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 parameters" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "Filter conditions" + } + ], + "response": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "Current page" + }, + { + "name": "page_size", + "type": "number", + "required": true, + "description": "Page size" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "Total" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "Supplier array" + } + ], + "errors": [ + { + "code": 400, + "message": "Invalid parameters" + } + ] + }, + { + "method": "setting.packageSupplier.list", + "description": "Compatibility alias for get; internally forwards to get. Prefer setting.packageSupplier.get.", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "组合商品模块", + "module": "comboGoods", + "list": [ + { + "method": "comboGoods.list", + "description": "组合商品列表查询(分页),支持按 combo_code/combo_name/status/warehouse_id 筛选。返回含 custom_code(自定义编码)、simpleNotation(stock_id|数量)和 nameNotation(【数量】商品名称)简记字段", + "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,默认 page=1 pageSize=20" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,支持 combo_code(精确匹配)、combo_name(模糊匹配)、status(等值)、warehouse_id(等值)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "组合商品列表,每项包含 id、combo_code、combo_name、combo_sku_id、custom_code、status、warehouse_id、remark、creator_id、editor_id、created_at、updated_at、items(子商品明细数组)、simpleNotation、nameNotation", + "children": [ + { + "name": "id", + "type": "number", + "description": "组合商品ID" + }, + { + "name": "combo_code", + "type": "string", + "description": "组合商品编码" + }, + { + "name": "combo_name", + "type": "string", + "description": "组合商品名称" + }, + { + "name": "combo_sku_id", + "type": "number", + "description": "组合商品SKU ID" + }, + { + "name": "custom_code", + "type": "string", + "description": "自定义编码,可为 null" + }, + { + "name": "status", + "type": "number", + "description": "状态:1=启用 0=停用" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + }, + { + "name": "creator_id", + "type": "number", + "description": "创建人ID" + }, + { + "name": "editor_id", + "type": "number", + "description": "最后编辑人ID" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + }, + { + "name": "items", + "type": "array", + "description": "子商品明细列表,每项含 id、combo_id、item_goods_sku_id、item_quantity、sort_order" + }, + { + "name": "simpleNotation", + "type": "string", + "description": "简记字符串,格式:stock_id|数量,stock_id2|数量" + }, + { + "name": "nameNotation", + "type": "string", + "description": "商品名称简记,格式:【数量】商品名称+【数量】商品名称" + } + ] + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页大小" + } + ], + "errors": [ + { + "code": "500", + "message": "查询失败" + } + ] + }, + { + "method": "comboGoods.create", + "description": "创建组合商品(含明细一次性提交)。校验:combo_code唯一性、custom_code按货主唯一(排除已删除记录)、所有子商品在wms_stock_warehouse中合法有效(is_valid=Y 且未删除)、所有子商品必须属于同一货主(store_id一致)。创建过程在事务中完成,保证主表和明细表的原子写入。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "combo_code", + "type": "string", + "required": true, + "source": "body", + "description": "组合商品编码,必填,全局唯一" + }, + { + "name": "combo_name", + "type": "string", + "required": true, + "source": "body", + "description": "组合商品名称,必填" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓库ID,可选" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注,可选" + }, + { + "name": "custom_code", + "type": "string", + "required": false, + "source": "body", + "description": "自定义编码,可选。传入时校验按货主唯一(排除已删除记录)" + }, + { + "name": "items", + "type": "array", + "required": true, + "source": "body", + "description": "子商品明细数组,每项含 item_goods_sku_id(number, 必填)和 item_quantity(number, 必填, 正整数)以及 sort_order(number, 可选, 排序号)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建的组合商品ID" + }, + { + "name": "combo_code", + "type": "string", + "required": true, + "description": "组合商品编码" + }, + { + "name": "combo_name", + "type": "string", + "required": true, + "description": "组合商品名称" + }, + { + "name": "custom_code", + "type": "string", + "required": false, + "description": "自定义编码,未传入时为 null" + } + ], + "errors": [ + { + "code": "400", + "message": "组合商品编码不能为空" + }, + { + "code": "400", + "message": "组合商品名称不能为空" + }, + { + "code": "400", + "message": "子商品列表不能为空" + }, + { + "code": "400", + "message": "组合商品编码 \"{code}\" 已存在(409语义)" + }, + { + "code": "400", + "message": "自定义编码 \"{code}\" 已被货主其他组合商品使用" + }, + { + "code": "400", + "message": "以下子商品不存在或已停用:{ids}" + }, + { + "code": "400", + "message": "所有子商品必须属于同一个货主,不允许跨货主组合" + }, + { + "code": "500", + "message": "创建组合商品主记录失败" + } + ] + }, + { + "method": "comboGoods.update", + "description": "编辑组合商品(含明细替换)。校验同 create。传入 items 则先删旧明细再批量插入新明细,事务保证原子性。支持部分更新:不传的字段保持原值不变。custom_code 校验按货主唯一(排除已删除记录和自身)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "组合商品ID,必填" + }, + { + "name": "combo_name", + "type": "string", + "required": false, + "source": "body", + "description": "组合商品名称,可选" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓库ID,可选" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注,可选" + }, + { + "name": "custom_code", + "type": "string", + "required": false, + "source": "body", + "description": "自定义编码,可选。传入非空值时校验按货主唯一(排除已删除记录和自身 id)" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:1=启用 0=停用,可选" + }, + { + "name": "items", + "type": "array", + "required": false, + "source": "body", + "description": "子商品明细数组,可选。传入非空数组时先删除旧明细再批量插入新明细;不传或传空数组则保持原明细不变。每项含 item_goods_sku_id(number)和 item_quantity(number)以及 sort_order(number, 可选)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "更新后的组合商品ID" + } + ], + "errors": [ + { + "code": "400", + "message": "组合商品ID不能为空" + }, + { + "code": "404", + "message": "组合商品不存在" + }, + { + "code": "400", + "message": "自定义编码 \"{code}\" 已被货主其他组合商品使用" + }, + { + "code": "400", + "message": "以下子商品不存在或已停用:{ids}" + }, + { + "code": "400", + "message": "所有子商品必须属于同一个货主,不允许跨货主组合" + }, + { + "code": "500", + "message": "更新失败" + } + ] + }, + { + "method": "comboGoods.delete", + "description": "删除组合商品(软删除,将 status 置为 0)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "组合商品ID,必填" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "已软删除的组合商品ID" + } + ], + "errors": [ + { + "code": "400", + "message": "组合商品ID不能为空" + }, + { + "code": "404", + "message": "组合商品不存在" + }, + { + "code": "500", + "message": "删除失败" + } + ] + }, + { + "method": "comboGoods.search", + "description": "关键字搜索组合商品(供手工建单选择)。模糊匹配 custom_code、combo_code 或 combo_name,仅返回启用状态(status=1)的记录,默认20条上限100条。custom_code 匹配项优先排在前面。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword", + "type": "string", + "required": true, + "source": "body", + "description": "搜索关键字,模糊匹配 custom_code、combo_code 和 combo_name" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "body", + "description": "最大返回条数,默认20,最大100" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "搜索结果列表,每项包含 id、combo_code、combo_name、custom_code、combo_sku_id、status、warehouse_id、items、simpleNotation、nameNotation" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "本次返回的记录条数" + } + ], + "errors": [ + { + "code": "400", + "message": "搜索关键字不能为空" + }, + { + "code": "500", + "message": "搜索失败" + } + ] + } + ] + }, + { + "groupName": "收货管理", + "module": "storage.receiving", + "list": [ + { + "method": "storage.receiving.getAvailableInboundQuantity", + "description": "[已删除] 按 stock_id 查询可入库数量。该方法已从代码中删除,不再可用。原依赖已弃用的 wms_entry_receiving_binding(明细绑定表),入库单与收货单的关系已改为通过 wms_entry_order_receiving 主表级关联。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.scanDetail", + "description": "PDA 上架扫码定位收货明细:扫描商品条码/箱唛/托盘唛,快速定位收货明细。同一条码可能匹配多条收货明细,以列表 { list, total } 格式返回所有匹配结果。若 barcode 为纯数字优先按明细 ID 精确匹配,否则按商品条码精确匹配。PDA专用。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID" + }, + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "扫描条码,支持:收货明细 ID(托盘唛头)、商品条码" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "匹配的收货明细列表" + }, + { + "name": "list[].detail_id", + "type": "number", + "required": true, + "description": "收货明细 ID" + }, + { + "name": "list[].receiving_id", + "type": "number", + "required": true, + "description": "收货单 ID" + }, + { + "name": "list[].barcode", + "type": "string", + "required": true, + "description": "商品条码" + }, + { + "name": "list[].product_name", + "type": "string", + "required": true, + "description": "商品名称" + }, + { + "name": "list[].actual_quantity", + "type": "number", + "required": true, + "description": "实收数量" + }, + { + "name": "list[].receiving_status", + "type": "string", + "required": true, + "description": "收货单状态" + }, + { + "name": "list[].stock", + "type": "object", + "required": true, + "description": "商品详情(通过 getStockDetails 获取,含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "匹配总数" + } + ], + "errors": [ + { + "code": 0, + "message": "用户未绑定仓库" + }, + { + "code": 0, + "message": "入库单ID不能为空" + }, + { + "code": 0, + "message": "扫描条码不能为空" + }, + { + "code": 0, + "message": "入库单不存在或无权访问" + }, + { + "code": 0, + "message": "该入库单尚未关联收货单" + }, + { + "code": 0, + "message": "未找到可用的收货明细" + }, + { + "code": 0, + "message": "未找到匹配的收货明细" + }, + { + "code": 500, + "message": "服务器扫描查询失败" + } + ] + }, + { + "method": "storage.receiving.export", + "description": "提交收货单导出任务(仓库维度,异步)。导出为 Excel 文件,包含两个 Sheet:Sheet1=收货单列表(ID/单号/货主/状态/明细匹配状态/入库状态/来货方式/车牌号/快递单号/装卸方式/商品种类/总数量/总箱数/总托盘数/审核状态/创建人/备注/收货时间/创建时间/更新时间),Sheet2=收货单明细(收货单号/收货单ID/明细ID/商品名称/商品条码/系统商品ID/实收数量/箱数/托盘数/收货状态/入库状态/已入库数量/批次号/生产日期/到期日期/备注/创建时间)。筛选和排序规则与 getReceivingList 一致,按当前仓库维度(ctx.user.store_id)过滤。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件(与 getReceivingList 一致),支持 quickWhere(模糊搜索收货单号/货主名称/快递单号/创建人/车牌号)等字段" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField(id/receiving_number/status/created_at/updated_at/store_id/warehouse_id)和 sortOrder(ASC/DESC),默认按 created_at DESC" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID,用于轮询进度" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度,0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态描述" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(failed 时返回)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "状态更新时间戳(毫秒)" + } + ], + "errors": [ + { + "code": 0, + "message": "用户未绑定仓库" + } + ] + }, + { + "method": "storage.receiving.exportTaskProgress", + "description": "查询收货单导出任务进度(仓库维度)。提交导出任务后,通过 task_id 轮询此接口获取实时进度和最终下载地址。任务缓存 TTL 为 30 分钟。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法),与 taskId 二选一" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法),与 task_id 二选一" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败 / not_found-任务不存在" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度,0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态描述" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(failed 时返回)" + }, + { + "name": "download_url", + "type": "string", + "required": false, + "description": "Excel 文件下载地址(success 时有效)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "状态更新时间戳(毫秒)" + } + ], + "errors": [] + }, + { + "method": "storage.receiving.storeExport", + "description": "提交货主侧收货单导出任务(货主维度,异步)。以当前平台激活的货主 store_id 为维度导出。导出为 Excel 文件,包含两个 Sheet:Sheet1=收货单列表,Sheet2=收货单明细(字段同 export)。筛选和排序规则与 getStoreReceivingList 一致,需当前用户已切换至货主角色。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件(与 getStoreReceivingList 一致),支持 quickWhere(模糊搜索收货单号/货主名称/快递单号/创建人/车牌号)等字段" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField(id/receiving_number/status/created_at/updated_at/store_id/warehouse_id)和 sortOrder(ASC/DESC),默认按 created_at DESC" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID,用于轮询进度" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度,0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态描述" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(failed 时返回)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "状态更新时间戳(毫秒)" + } + ], + "errors": [ + { + "code": 0, + "message": "未获取到货主平台激活上下文,请先切换至货主角色" + } + ] + }, + { + "method": "storage.receiving.storeExportTaskProgress", + "description": "查询货主侧收货单导出任务进度。复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。任务缓存 TTL 为 30 分钟。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法),与 taskId 二选一" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法),与 task_id 二选一" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败 / not_found-任务不存在" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度,0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态描述" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(failed 时返回)" + }, + { + "name": "download_url", + "type": "string", + "required": false, + "description": "Excel 文件下载地址(success 时有效)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "状态更新时间戳(毫秒)" + } + ], + "errors": [] + } + ] + }, + { + "groupName": "工作台模块", + "module": "workbench", + "list": [ + { + "method": "workbench.list", + "description": "查询工作台列表(仓库隔离,支持分页与关键词筛选;列表项返回 login_code,不返回 token;工作台条码 barcode 字段已下线)", + "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": "筛选条件,支持 name(模糊)、status(等值)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "工作台列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "工作台ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "name", + "type": "string", + "description": "工作台名称" + }, + { + "name": "status", + "type": "number", + "description": "状态:0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + }, + { + "name": "login_code", + "type": "string", + "description": "工作台登录码(前缀 wblc + 随机段共 64 位,创建时自动生成)" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式错误或缺少仓库上下文" + } + ] + }, + { + "method": "workbench.detail", + "description": "查询单个工作台详情(仓库隔离)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工作台ID" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "工作台详情对象" + } + ], + "errors": [ + { + "code": "400", + "description": "工作台ID不能为空" + }, + { + "code": "404", + "description": "工作台不存在或无权访问" + } + ] + }, + { + "method": "workbench.create", + "description": "新增工作台(仓库隔离);创建时自动生成 login_code(前缀 wblc + 随机段共 64 位,全局唯一),不接受外部传入 login_code;工作台条码 barcode 字段已下线,不再接收", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "工作台名称(必填)" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:0-禁用 1-启用,默认1" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "新建的工作台对象(含自动生成的 login_code)" + } + ], + "errors": [ + { + "code": "400", + "message": "工作台名称不能为空" + } + ] + }, + { + "method": "workbench.update", + "description": "更新工作台信息(仓库隔离);login_code / token 不允许编辑,传入 login_code 不予受理;工作台条码 barcode 字段已下线,传入不予受理", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工作台ID(必填)" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "工作台名称" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "更新后的工作台对象" + } + ], + "errors": [ + { + "code": "400", + "message": "工作台ID不能为空" + }, + { + "code": "404", + "message": "工作台不存在或无权操作" + } + ] + }, + { + "method": "workbench.delete", + "description": "删除工作台(软删除,仓库隔离)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工作台ID(必填)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "description": "工作台ID不能为空" + }, + { + "code": "404", + "description": "工作台不存在或无权操作" + } + ] + }, + { + "method": "workbench.business", + "description": "工作台业务入口(免登录免鉴权,入参 name + data)。name 支持 queryOrder/query(条码查订单,data 需 barcode+warehouseId)、packOrder(开始打包,凭 key 从后端缓存取订单信息防篡改;不传 key 时旧参数模式过渡兼容;business 旧链路支持传入 users 上报打包人,未上报时自动回填工作台绑定成员)、finishPack(结束打包)、sendWeight(称重);不支持的业务名称报错。以下响应结构为 queryOrder/query(条码查订单)的返回。", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "业务名称:queryOrder/query(条码查订单)、packOrder、finishPack、sendWeight" + }, + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "业务数据(透传)。queryOrder/query 需 barcode(运单号,必填)+ warehouseId(仓库ID,必填)" + } + ], + "response": [ + { + "name": "barcode", + "type": "string", + "required": true, + "description": "条码(运单号)" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "isSandan", + "type": "number", + "required": true, + "description": "是否散单:1=散单 0=团购(波次类型 wave_type=1 时判定为团购)" + }, + { + "name": "store_remark", + "type": "string", + "required": true, + "description": "货主备注(合约表 store_warehouse.store_remask,无合约或为空时为空字符串)" + }, + { + "name": "express", + "type": "object", + "required": true, + "description": "运单信息:logistics_name(快递公司名称)、weighing_weight(称重重量)、package_material_name(包材名称快照)" + }, + { + "name": "order", + "type": "object", + "required": true, + "description": "订单详情", + "children": [ + { + "name": "id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "order_type", + "type": "number", + "description": "订单类型" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "status", + "type": "number", + "description": "订单状态" + }, + { + "name": "step", + "type": "number", + "description": "订单步骤" + }, + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "post_status", + "type": "string", + "description": "过账状态" + }, + { + "name": "pick_status", + "type": "string", + "description": "拣货状态" + }, + { + "name": "pack_status", + "type": "string", + "description": "打包状态(原始值):none/padding/fin/error,空值/null 归一化为 none" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态(原始值):空值/null 归一化为 none;散单/团购均返回" + }, + { + "name": "recheck_status", + "type": "string", + "description": "复核状态" + }, + { + "name": "outbound_status", + "type": "string", + "description": "出库状态" + }, + { + "name": "items_count", + "type": "number", + "description": "商品件数" + }, + { + "name": "items_total", + "type": "number", + "description": "商品总数" + }, + { + "name": "items_weight", + "type": "number", + "description": "商品总重量" + }, + { + "name": "source_platform_code", + "type": "string", + "description": "来源平台编码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "快递公司名称" + }, + { + "name": "create_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "更新时间" + }, + { + "name": "intercept_flag", + "type": "number", + "description": "拦截标志(仅散单 isSandan=1 返回,团购不返回):拦截状态(intercept_status)不等于 none 时为 1,等于 none 时为 0" + }, + { + "name": "pack_flag", + "type": "number", + "description": "打包标志(仅散单 isSandan=1 返回,团购不返回):按运单维度判定——该运单号已有打包流水(wms_pack_task.waybill_code 命中,或历史订单级流水 waybill_code 为空兜底)时为 1,否则为 0;主单号/子单号互不影响" + } + ] + }, + { + "name": "items", + "type": "array", + "required": true, + "description": "订单商品明细,每项含 id/order_id/item_id/item_code/item_name/plan_qty/actual_price/stock_id/order_line_no/inventory_type/sku_property/stock_unit/barcodes/image_url/packing_requirements(打包要求,来自 stock,未命中/异常时为空字符串)" + }, + { + "name": "source_table", + "type": "string", + "required": true, + "description": "订单命中分表:current(待处理表)或 dispatch(配送表)" + }, + { + "name": "batch", + "type": "object", + "required": false, + "description": "波次汇总(仅团购 isSandan=0 返回):wave_id(波次ID)、wave_no(波次号)、wave_type(波次类型,1=团购)、total_orders(波次订单总数)" + } + ], + "errors": [ + { + "code": "400", + "message": "条码不能为空" + }, + { + "code": "400", + "message": "仓库ID不能为空" + }, + { + "code": "400", + "message": "未找到条码 [xxx] 对应的运单记录" + }, + { + "code": "400", + "message": "未在待处理或配送表中找到订单 [id=xxx, warehouse=xxx]" + }, + { + "code": "400", + "message": "不支持的业务类型: xxx" + } + ] + }, + { + "method": "workbench.bindCamera", + "description": "工作台绑定/解绑摄像头,校验工作台与摄像头归属后更新 device_ids", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工作台ID" + }, + { + "name": "camera_ids", + "type": "array", + "required": false, + "source": "body", + "description": "摄像头ID数组,传空数组或 null 表示解绑所有摄像头" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "工作台ID" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "工作台名称" + }, + { + "name": "device_ids", + "type": "array", + "required": false, + "description": "绑定后的摄像头ID列表" + } + ], + "errors": [ + { + "code": "400", + "message": "工作台ID不能为空" + }, + { + "code": "400", + "message": "摄像头 xxx 不存在或无权操作" + }, + { + "code": "404", + "message": "工作台不存在或无权操作" + } + ] + }, + { + "method": "workbench.bind", + "description": "工作台绑定(需登录、需权限):入参缓存生成的绑定码 code 与工作台ID id,校验绑定码有效且工作台归属当前仓库后完成关联绑定;成功后在工作台写入随机生成的 64 位 token(若工作台已有 token,删除旧 workbench:token:{旧token} 缓存并写入新 token 缓存),同时更新绑定会话状态为已绑定,供 index.getWorkbenchBindCode 长轮询返回 token", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "缓存生成的绑定码(6 位大写字母+数字)" + }, + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "要绑定的工作台ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "工作台ID" + }, + { + "name": "workbench_id", + "type": "number", + "required": true, + "description": "工作台ID(同 id)" + }, + { + "name": "token", + "type": "string", + "required": true, + "description": "随机生成的工作台 token(64 位)" + } + ], + "errors": [ + { + "code": "400", + "message": "绑定码格式无效" + }, + { + "code": "400", + "message": "工作台ID不能为空或无效" + }, + { + "code": "400", + "message": "绑定码不存在或已过期" + }, + { + "code": "404", + "message": "工作台不存在或无权操作" + } + ] + }, + { + "method": "workbench.getWorkbenchInfo", + "description": "使用 token 获取工作台信息(免登录、免鉴权):先查缓存 workbench:token:{token}(TTL 300s,缓存值已包含成员列表 members 与当前打包信息 current_wave/current_orders),未命中则按 token 查库并回填缓存后返回工作台信息(不含 token/login_code;工作台条码 barcode 字段已下线);响应 data 含 members 成员数组(wms_workbench_member 未软删除记录,按 id ASC 排序)、current_wave 当前正在打包的团购波次(wms_pack_task 中 pack_mode=2 且 wave_id>0 的最新一条未结束任务组装,含波次订单数 order_count 与商品总件数 items_total,无团购任务时为空对象)与 current_orders 当前正在打包的订单数组(未结束任务(status<2)对应订单,逐单按 current→dispatch 分表补发货单号/订单类型/货主/件数等字段,散单任务(pack_mode=1)另附 items 商品明细(含条码/图片/包装要求/是否需要复核 need_recheck 等,供工作台退出/刷新后恢复任务上下文),团购任务(pack_mode=2)items 为波次商品 SKU 聚合汇总(波次内全部未拦截订单按 SKU 聚合计划数量并合并 stock 详情,15s 短缓存兜底,元素另附 is_wave_summary=true;无进行中任务时为空数组);绑定/移除成员、packOrder/finishPack 打包状态变更后 token 缓存立即失效,下一次调用即返回最新成员与打包信息;打包信息查询异常时降级(current_wave 空对象、current_orders 空数组,单笔商品明细查询异常时 items 降级为空数组),不影响主信息与 members;token 缺失返回失败(flag=failure、code=401,消息「工作台 token 不能为空」)、token 不存在或无对应工作台返回失败(flag=failure、code=403)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "token", + "type": "string", + "required": true, + "source": "body", + "description": "工作台 token(64 位)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "工作台ID" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "工作台名称" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "状态:0-禁用 1-启用" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "工作台类型:personal-个人工作台 group-团体工作台" + }, + { + "name": "remark", + "type": "string", + "required": false, + "description": "备注" + }, + { + "name": "device_ids", + "type": "array", + "required": false, + "description": "设备ID列表" + }, + { + "name": "created_at", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间" + }, + { + "name": "members", + "type": "array", + "required": true, + "description": "成员列表(wms_workbench_member 未软删除记录,按 id ASC 排序;成员查询失败时降级为空数组)" + }, + { + "name": "members[].id", + "type": "number", + "required": true, + "description": "成员记录ID(对应 wms_workbench_member.id,可用于 workbench.removeMember 的 ids 参数)" + }, + { + "name": "members[].user_id", + "type": "number", + "required": false, + "description": "关联 wms_account.id;可空 null(非系统账号用户)" + }, + { + "name": "members[].user_name", + "type": "string", + "required": false, + "description": "成员名快照;可空 null" + }, + { + "name": "current_wave", + "type": "object", + "required": true, + "description": "当前正在打包的团购波次(wms_pack_task 中 pack_mode=2 且 wave_id>0 的最新一条未结束任务组装,按任务 id 倒序取最新;order_count 波次订单数与 items_total 商品总件数均按 current+dispatch 分表实时统计并带 15s 短缓存;无团购任务或查询异常时为空对象)" + }, + { + "name": "current_wave.task_id", + "type": "number", + "required": true, + "description": "打包任务ID(wms_pack_task.id)" + }, + { + "name": "current_wave.wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "current_wave.wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "current_wave.status", + "type": "number", + "required": true, + "description": "任务状态:0=待处理 1=打包中" + }, + { + "name": "current_wave.order_count", + "type": "number", + "required": true, + "description": "波次订单数(current+dispatch 分表实时计数,15s 短缓存兜底)" + }, + { + "name": "current_wave.items_total", + "type": "number", + "required": true, + "description": "波次商品总件数(口径为商品总件数、非 SKU 品种数:订单分表 wms_order_delivery_{仓库}_{current/dispatch} 的 items_total 列按 wave_id+warehouse_id 求和,15s 短缓存兜底)" + }, + { + "name": "current_wave.operator_text", + "type": "string", + "required": true, + "description": "操作人文本(多人逗号分隔)" + }, + { + "name": "current_wave.start_time", + "type": "string", + "required": false, + "description": "开始打包时间;可空 null" + }, + { + "name": "current_orders", + "type": "array", + "required": true, + "description": "当前正在打包的订单数组(该工作台全部未结束任务(status<2)按任务 id 倒序,逐单按 current→dispatch 分表补发货单号,散单任务另补货主备注(store_remark)与运单信息(express:物流公司/称重重量/包材名称,与 workbench.queryOrder 口径一致);无进行中任务或查询异常时为空数组)" + }, + { + "name": "current_orders[].task_id", + "type": "number", + "required": true, + "description": "打包任务ID(wms_pack_task.id)" + }, + { + "name": "current_orders[].order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "current_orders[].delivery_order_code", + "type": "string", + "required": true, + "description": "发货单号(分表未命中时为空串)" + }, + { + "name": "current_orders[].wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "current_orders[].wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "current_orders[].pack_mode", + "type": "number", + "required": true, + "description": "打包模式:1=散单 2=团购" + }, + { + "name": "current_orders[].status", + "type": "number", + "required": true, + "description": "任务状态:0=待处理 1=打包中" + }, + { + "name": "current_orders[].pack_quantity", + "type": "number", + "required": true, + "description": "打包数量(件数)" + }, + { + "name": "current_orders[].item_quantity", + "type": "number", + "required": true, + "description": "商品总数量(来自 wms_pack_task.item_quantity)" + }, + { + "name": "current_orders[].sku_count", + "type": "number", + "required": true, + "description": "商品种类数(SKU 数,来自 wms_pack_task.sku_count)" + }, + { + "name": "current_orders[].waybill_code", + "type": "string", + "required": false, + "description": "运单号(来自 wms_pack_task.waybill_code,散单任务创建时未回填则为空串)" + }, + { + "name": "current_orders[].order_type", + "type": "string", + "required": false, + "description": "订单类型(订单分表未命中时为空串)" + }, + { + "name": "current_orders[].store_id", + "type": "number", + "required": true, + "description": "货主ID(订单分表未命中时为 0)" + }, + { + "name": "current_orders[].store_remark", + "type": "string", + "required": false, + "description": "货主备注(合约表 wms_store_warehouse.store_remask;仅散单任务返回,团购为空字符串,与 workbench.queryOrder 的 store_remark 口径一致)" + }, + { + "name": "current_orders[].express", + "type": "object", + "required": false, + "description": "运单信息(仅散单任务返回,团购为 null;与 workbench.queryOrder 的 express 口径一致)" + }, + { + "name": "current_orders[].express.waybill_code", + "type": "string", + "required": false, + "description": "运单号" + }, + { + "name": "current_orders[].express.logistics_name", + "type": "string", + "required": false, + "description": "物流公司名称" + }, + { + "name": "current_orders[].express.weighing_weight", + "type": "number", + "required": false, + "description": "称重重量(克)" + }, + { + "name": "current_orders[].express.package_material_name", + "type": "string", + "required": false, + "description": "包材名称(wms_order_express.package_material_name_snapshot,无包材为空字符串)" + }, + { + "name": "current_orders[].items_count", + "type": "number", + "required": true, + "description": "订单商品品种数(订单分表 items_count,未命中时为 0)" + }, + { + "name": "current_orders[].items_total", + "type": "number", + "required": true, + "description": "订单商品总件数(订单分表 items_total,未命中时为 0)" + }, + { + "name": "current_orders[].items", + "type": "array", + "required": true, + "description": "商品数组:散单任务(pack_mode=1)为单笔订单商品明细(逐项合并 stock 详情(条码/图片/包装要求,走 getStockDetails 缓存));团购任务(pack_mode=2)为波次商品 SKU 聚合汇总(波次内全部未拦截订单按 SKU 聚合计划数量,15s 短缓存兜底,元素另附 is_wave_summary=true);查询异常降级为空数组" + }, + { + "name": "current_orders[].items[].id", + "type": "number", + "required": true, + "description": "订单商品明细ID(wms_order_items 分表 id;团购波次聚合行为 0)" + }, + { + "name": "current_orders[].items[].order_id", + "type": "number", + "required": false, + "description": "订单ID(团购波次聚合行为 0)" + }, + { + "name": "current_orders[].items[].item_id", + "type": "number", + "required": false, + "description": "商品ID" + }, + { + "name": "current_orders[].items[].item_code", + "type": "string", + "required": true, + "description": "商品编码(明细为空时回退 stock.item_code)" + }, + { + "name": "current_orders[].items[].item_name", + "type": "string", + "required": true, + "description": "商品名称(明细为空时回退 stock.item_name)" + }, + { + "name": "current_orders[].items[].plan_qty", + "type": "number", + "required": false, + "description": "计划数量(团购波次聚合行为波次内该 SKU 计划数量合计)" + }, + { + "name": "current_orders[].items[].actual_price", + "type": "number", + "required": false, + "description": "实际价格" + }, + { + "name": "current_orders[].items[].stock_id", + "type": "number", + "required": true, + "description": "库存ID(商品ID)" + }, + { + "name": "current_orders[].items[].order_line_no", + "type": "string", + "required": true, + "description": "订单行号" + }, + { + "name": "current_orders[].items[].inventory_type", + "type": "string", + "required": true, + "description": "库存类型" + }, + { + "name": "current_orders[].items[].sku_property", + "type": "string", + "required": false, + "description": "SKU 属性(来自 stock 详情,无则空串)" + }, + { + "name": "current_orders[].items[].stock_unit", + "type": "string", + "required": false, + "description": "库存单位(来自 stock 详情,无则空串)" + }, + { + "name": "current_orders[].items[].barcodes", + "type": "array", + "required": false, + "description": "条码列表(来自 stock 详情,无则空数组)" + }, + { + "name": "current_orders[].items[].image_url", + "type": "array", + "required": false, + "description": "商品图片地址数组(来自 stock 详情,无则空数组)" + }, + { + "name": "current_orders[].items[].packing_requirements", + "type": "string", + "required": false, + "description": "包装要求(来自 stock 详情,无则空串)" + }, + { + "name": "current_orders[].items[].need_recheck", + "type": "string", + "required": true, + "description": "是否需要复核:Y=需要复核,N=不需要复核(免验)(来自 stock 详情,缺省 Y)" + }, + { + "name": "current_orders[].items[].is_wave_summary", + "type": "boolean", + "required": false, + "description": "是否波次聚合行(仅团购任务 items 元素返回 true,用于区分单笔明细与波次 SKU 汇总)" + }, + { + "name": "current_orders[].operator_text", + "type": "string", + "required": true, + "description": "操作人文本(多人逗号分隔)" + }, + { + "name": "current_orders[].start_time", + "type": "string", + "required": false, + "description": "开始打包时间;可空 null" + } + ], + "errors": [ + { + "code": "401", + "message": "工作台 token 不能为空(返回 flag=failure、code=401)" + }, + { + "code": "403", + "message": "工作台不存在或 token 无效(返回 flag=failure、code=403)" + } + ] + }, + { + "method": "workbench.resetLoginCode", + "description": "重置工作台登录码(需登录、需权限):随机生成新的 login_code(前缀 wblc + 随机段共 64 位)并写入数据库,旧 login_code 随即失效;同时同步重置工作台 token:生成新 64 位 hex token 与 login_code 一并持久化到 wms_workbench,更新库前先删除旧 workbench:token:{旧token} 缓存(旧 token 随即失效),并立即回填新 token 信息缓存(复用 buildWorkbenchTokenInfo,含 members/current_wave/current_orders,TTL 300s);旧 token 失效后,使用旧 token 的会话返回 403,设备端需使用响应中新 token 继续工作", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "工作台ID(必填)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "工作台ID" + }, + { + "name": "login_code", + "type": "string", + "required": true, + "description": "重置后的登录码(前缀 wblc + 随机段共 64 位)" + }, + { + "name": "token", + "type": "string", + "required": true, + "description": "重置后的工作台 token(64 位 hex,必返回;旧 token 已失效,设备端需使用新 token 继续工作)" + } + ], + "errors": [ + { + "code": "400", + "message": "工作台ID不能为空或无效" + }, + { + "code": "404", + "message": "工作台不存在或无权操作" + }, + { + "code": "403", + "message": "重置完成后旧 token 随即失效:旧 workbench:token:{旧token} 缓存已删除,使用旧 token 的会话请求返回 403,设备端需改用响应中新 token 继续工作" + } + ] + }, + { + "method": "workbench.removeMember", + "description": "移除工作台成员(免登录、免鉴权,以工作台 token 鉴权):入参成员行 ids 与工作台 token,token 优先校验(无 token 返回 401、token 无效返回 403),按 token 解析工作台后仅软删除归属于该工作台的成员行(wms_workbench_member 副表,user_id 可为空兼容非系统账号用户),返回移除数量与行ID列表;移除后该工作台已无任何成员时自动结束其所有未结束的打包任务(wms_pack_task.status<2 置 2 并写 end_time,同步回写订单打包状态与补确认打印状态、写完成操作日志、复位摄像头 OSD、失效 token 缓存,与 finishPack 语义一致),响应附 auto_finished_pack", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array|number|string", + "required": true, + "source": "body", + "description": "成员行ID(wms_workbench_member.id),支持数组、单值或逗号分隔字符串" + }, + { + "name": "token", + "type": "string", + "required": true, + "source": "body", + "description": "工作台 token(64 位,用于识别操作归属的工作台)" + } + ], + "response": [ + { + "name": "removed", + "type": "number", + "required": true, + "description": "实际移除的成员行数" + }, + { + "name": "ids", + "type": "array", + "required": true, + "description": "实际移除的成员行ID列表" + }, + { + "name": "auto_finished_pack", + "type": "object", + "required": false, + "description": "成员全部登出后的自动结束打包结果(仅移除后该工作台无成员时才有实际动作;其余情况 finished=0)" + }, + { + "name": "auto_finished_pack.finished", + "type": "number", + "required": true, + "description": "自动结束的打包任务数量" + }, + { + "name": "auto_finished_pack.task_ids", + "type": "array", + "required": true, + "description": "自动结束的打包任务ID列表" + } + ], + "errors": [ + { + "code": "401", + "message": "工作台 token 不能为空(返回 flag=failure、code=401)" + }, + { + "code": "400", + "message": "成员行ID不能为空或无效" + }, + { + "code": "403", + "message": "工作台不存在或 token 无效(返回 flag=failure、code=403)" + }, + { + "code": "404", + "message": "未找到可移除的成员" + } + ] + }, + { + "method": "workbench.bindMember", + "description": "绑定工作台成员(免登录、免鉴权,以工作台 token 鉴权):入参用户ID(可为空,兼容非系统账号用户)+ 姓名(必填)+ 工作台 token,token 优先校验(无 token 返回 401、token 无效返回 403),通过后在 wms_workbench_member 副表新增成员行(user_id 为空时仅存姓名快照),返回新建成员行信息", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "userId", + "type": "number|null", + "required": false, + "source": "body", + "description": "用户ID(wms_account.id),非系统账号用户可不传或传 null(兼容 user_id 下划线入参名)" + }, + { + "name": "userName", + "type": "string", + "required": true, + "source": "body", + "description": "姓名(必填,非空,trim 后入库;兼容 user_name / name 入参名)" + }, + { + "name": "token", + "type": "string", + "required": true, + "source": "body", + "description": "工作台 token(64 位,用于识别归属的工作台)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建成员行ID(wms_workbench_member.id)" + }, + { + "name": "workbench_id", + "type": "number", + "required": true, + "description": "工作台ID" + }, + { + "name": "user_id", + "type": "number|null", + "required": true, + "description": "用户ID,非系统账号用户为 null" + }, + { + "name": "user_name", + "type": "string", + "required": true, + "description": "姓名快照" + } + ], + "errors": [ + { + "code": "401", + "message": "工作台 token 不能为空(返回 flag=failure、code=401)" + }, + { + "code": "400", + "message": "姓名不能为空" + }, + { + "code": "400", + "message": "用户ID无效" + }, + { + "code": "403", + "message": "工作台不存在或 token 无效(返回 flag=failure、code=403)" + } + ] + }, + { + "method": "workbench.packOrder", + "description": "工作台打包上报(免登录、免权限、免鉴权,以工作台 token 鉴权):推荐只传 token + key,订单相关信息(订单号/波次号/运单号)由后端从缓存拉取(前端先经 workbench.queryOrder 扫码拿到 key,20 分钟有效,防篡改);不传 key 时旧参数模式(delivery_order_code 等直传)过渡兼容,后续版本将移除;仓库与工作台均由服务端从 token 解析注入(禁止前端传值);跨仓库/跨工作台消费他人 key 返回 403、key 缺失或过期返回 400(请重新扫码)。打包流程:按发货单号定位订单(current→dispatch 分表),同一工作台存在上一个未结束任务时先关闭(同步回写旧订单打包状态并补确认打印状态,并将工作台绑定摄像头 OSD 复位为「无任务」,新任务 OSD 在其后串行下发避免被复位覆盖),散单去重(传运单号按 order_id+waybill_code、未传按 order_id)、团购按 wave_no 去重后创建打包任务(wms_pack_task,status 归一化为 1=打包中,散单传运单号时 waybill_code 写入流水),写入打包人员(wms_pack_task_packer,自动取该工作台绑定成员 wms_workbench_member)与 operator_text、下发 OSD 到工作台绑定摄像头(散单优先展示打包运单号、团购显示波次号+订单总量,并写 Redis osd_{workbenchId} 缓存)、写操作日志;打包状态变更后主动失效对应工作台 token 缓存,保证 getWorkbenchInfo 尽快返回最新打包信息;团购单(isSandan=0)响应附 batch 波次信息(波次订单数为 current+dispatch 分表实时统计);拦截流程中的订单不允许打包(散单直接拒绝、团购波次静默跳过并视为完成);保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200;打包任务落库 wave_scope(波次范围:0=未分配 1=大团购 2=散单 3=小团购 4=单品单件,服务端复查:上报值非法/缺省时兜底订单行值);大团购波次(wave_scope=1)响应附倒计时字段 pack_wait_seconds(大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数,单位秒;人数为 0 时任务已被成员全部登出流程自动结束,不会出现,仍按 1 兜底防除零)与 pack_start_time(开始打包时间,毫秒时间戳)供前端倒计时,其他波次两字段均为 0", + "isNeedAuth": false, + "isNeedLogin": false, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "token", + "type": "string", + "required": true, + "source": "body", + "description": "工作台 token(64 位,工作台身份凭证;仓库与工作台由服务端从 token 解析注入)" + }, + { + "name": "key", + "type": "string", + "required": true, + "source": "body", + "description": "打包上下文 key(来自 workbench.queryOrder 响应,20 分钟有效;凭 key 由后端从缓存拉取订单号/波次号/运单号,参数后端维护防篡改,跨仓库/跨工作台使用返回 403、过期返回 400)" + } + ], + "response": [ + { + "name": "task_id", + "type": "number", + "required": true, + "description": "打包任务ID(wms_pack_task.id)" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": true, + "description": "发货单号" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "isSandan", + "type": "number", + "required": true, + "description": "是否散单:1=散单 0=团购(波次类型 wave_type=1 时判定为团购)" + }, + { + "name": "pack_mode", + "type": "number", + "required": true, + "description": "打包模式:1=散单 2=团购" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "任务状态:1=打包中 2=已完成" + }, + { + "name": "pack_wait_seconds", + "type": "number", + "required": true, + "description": "大团购倒计时等待秒数(大团购打包系数 big_group_pack_coefficient × 当前波次打包数 ÷ 当前工作台打包人数;仅 wave_scope=1 返回实际值,其他波次为 0)" + }, + { + "name": "pack_start_time", + "type": "number", + "required": true, + "description": "开始打包时间(毫秒时间戳;仅 wave_scope=1 返回实际值,其他波次为 0)" + }, + { + "name": "batch", + "type": "object", + "required": false, + "description": "团购波次信息(仅团购单 isSandan=0 时返回)" + }, + { + "name": "batch.wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "batch.wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "batch.wave_type", + "type": "number", + "required": true, + "description": "波次类型(1=团购)" + }, + { + "name": "batch.total_orders", + "type": "number", + "required": true, + "description": "波次订单总数(current+dispatch 分表实时统计)" + } + ], + "errors": [ + { + "code": "401", + "message": "工作台 token 不能为空(返回 flag=failure、code=401)" + }, + { + "code": "403", + "message": "工作台不存在或 token 无效(返回 flag=failure、code=403)" + }, + { + "code": "403", + "message": "工作台未绑定有效仓库" + }, + { + "code": "400", + "message": "发货单号不能为空" + }, + { + "code": "400", + "message": "未找到发货单 [xxx]" + }, + { + "code": "400", + "message": "订单已被拦截,无法打包 [xxx](散单)" + } + ] + }, + { + "method": "workbench.finishPack", + "description": "工作台打包完成(免登录、免权限、免鉴权,以工作台 token 鉴权):仓库与工作台均由服务端从 token 解析注入(body 传入 warehouse_id/workbench_id 一律忽略,禁止前端传值);查找该工作台最后一个未结束的打包任务(status<2,按 id 倒序取最新)并结束(写 end_time、status=2,结束时间按仓库配置的散单/团购打包最大时长上限截断),同步回写关联订单打包状态(散单更新单笔、团购批量更新波次下未拦截订单),并补确认打印状态(confirm_print_status 未写入时置 fin,团购按波次补、散单按单补)并写完成操作日志,随后将工作台绑定摄像头 OSD 复位为「无任务」(回写 Redis osd_{workbenchId} 缓存并逐台摄像头下发「无任务」,失败仅告警不阻塞主流程);无未结束任务时返回 finished=false(data 仅 workbench_id/finished/message);打包任务结束后主动失效对应工作台 token 缓存,保证 getWorkbenchInfo 尽快返回最新打包信息;保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200", + "isNeedAuth": false, + "isNeedLogin": false, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "token", + "type": "string", + "required": true, + "source": "body", + "description": "工作台 token(64 位,工作台身份凭证;仓库与工作台由服务端从 token 解析注入)" + } + ], + "response": [ + { + "name": "workbench_id", + "type": "number", + "required": true, + "description": "工作台ID" + }, + { + "name": "finished", + "type": "boolean", + "required": true, + "description": "是否结束打包任务:false=无未结束的打包任务" + }, + { + "name": "task_id", + "type": "number", + "required": false, + "description": "已结束的打包任务ID(wms_pack_task.id,finished=false 时不返回)" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "description": "订单ID(finished=false 时不返回)" + }, + { + "name": "end_time", + "type": "string", + "required": false, + "description": "任务结束时间(按仓库配置的打包最大时长上限截断,finished=false 时不返回)" + } + ], + "errors": [ + { + "code": "401", + "message": "工作台 token 不能为空(返回 flag=failure、code=401)" + }, + { + "code": "403", + "message": "工作台不存在或 token 无效(返回 flag=failure、code=403)" + }, + { + "code": "403", + "message": "工作台未绑定有效仓库" + } + ] + }, + { + "method": "workbench.sendWeight", + "description": "工作台称重上报(免登录、免权限、免鉴权,以工作台 token 鉴权):仓库由服务端从 token 解析注入(body 传入 warehouse_id/workbench_id 一律忽略,禁止前端传值),入参条码(运单号)+ 重量(单位克,必须为正整数);条码→运单记录(wms_order_express,按 waybill_code+warehouse_id 精确匹配)→ 定位订单分表(current→history→dispatch,序列表定位优先,命中先查对应分表)→ 更新运单称重重量 weighing_weight(DB 统一单位 g):散单(wave_id=0)仅更新该运单;团购波次(wave_type=1)批量更新波次下所有未拦截订单的运单称重重量并返回 total_weight(单件重量×订单数)与 order_count;非团购波次降级为散单逻辑;拦截流程中的订单不允许称重;写称重操作日志(ORDER_WEIGH,团购逐订单批量写);保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200;散单称重前置打包校验:开启仓库配置 single_weigh_require_pack 后,散单路径(订单 wave_scope 非 1 大团购/3 小团购)在拦截校验后校验打包状态,仅 pack_status 既非 padding 也非 fin 时拒绝称重(业务失败 code=400,提示末尾附 [条码]);团购波次批量称重不校验", + "isNeedAuth": false, + "isNeedLogin": false, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "token", + "type": "string", + "required": true, + "source": "body", + "description": "工作台 token(64 位,工作台身份凭证;仓库由服务端从 token 解析注入)" + }, + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "条码(运单号 waybill_code)" + }, + { + "name": "weight", + "type": "number|string", + "required": true, + "source": "body", + "description": "称重重量(单位:克,必须为正整数)" + } + ], + "response": [ + { + "name": "barcode", + "type": "string", + "required": true, + "description": "条码(运单号)" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "description": "订单ID(散单 mode=single 返回)" + }, + { + "name": "weighing_weight", + "type": "number", + "required": true, + "description": "称重重量(单位 g)" + }, + { + "name": "items_weight", + "type": "number", + "required": true, + "description": "订单商品重量(单位 g,来自订单分表 items_weight 快照)" + }, + { + "name": "mode", + "type": "string", + "required": true, + "description": "称重模式:single=散单 wave=团购波次" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "波次ID(团购 mode=wave 返回)" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "波次号(团购 mode=wave 返回)" + }, + { + "name": "total_weight", + "type": "number", + "required": false, + "description": "波次总重量(单位 g,单件重量×订单数,团购 mode=wave 返回)" + }, + { + "name": "order_count", + "type": "number", + "required": false, + "description": "波次订单数(参与称重的未拦截订单数,团购 mode=wave 返回)" + } + ], + "errors": [ + { + "code": "401", + "message": "工作台 token 不能为空(返回 flag=failure、code=401)" + }, + { + "code": "403", + "message": "工作台不存在或 token 无效(返回 flag=failure、code=403)" + }, + { + "code": "403", + "message": "工作台未绑定有效仓库" + }, + { + "code": "400", + "message": "条码(sn)不能为空" + }, + { + "code": "400", + "message": "重量(weight)不能为空" + }, + { + "code": "400", + "message": "重量格式非法,必须为正整数(单位 g)" + }, + { + "code": "400", + "message": "未找到条码 [xxx] 对应的运单记录" + }, + { + "code": "400", + "message": "订单已被拦截,无法称重 [xxx]" + }, + { + "code": 400, + "message": "订单未打包——开启仓库配置 single_weigh_require_pack 后,wave_scope 非 1 大团购/3 小团购 且 pack_status 既非 padding 也非 fin 时拦截;团购波次不校验" + } + ] + }, + { + "method": "workbench.queryOrder", + "description": "工作台条码查询订单(免登录、免权限、免鉴权,以工作台 token 鉴权):仓库与工作台均由服务端从 token 解析注入(body 传入 warehouse_id/workbench_id 一律忽略,禁止前端传值,防止跨仓库查单),入参条码(运单号);条码→运单记录(wms_order_express,按 waybill_code+warehouse_id+status=1 精确匹配)→ 序列表定位优先、未命中按 current→dispatch 回退遍历订单分表 → 组装查询结果(barcode/waybill_code/isSandan/store_remark/express/order/items/source_table);散单(isSandan=1)order 附拦截/打包 0/1 标志 intercept_flag/pack_flag(拦截标志:拦截状态空值归一化为 none,非 none 记 1;打包标志:按运单维度判定,该运单号已有打包流水 wms_pack_task.waybill_code 命中或历史订单级流水 waybill_code 为空兜底时为 1,否则 0,主单号/子单号互不影响);团购(isSandan=0,波次类型 wave_type=1)附 batch 波次信息(wave_id/wave_no/wave_type/total_orders,total_orders 为 current+dispatch 分表实时统计并带 15s 短缓存兜底);items 逐项合并 stock 详情(sku_property/stock_unit/barcodes/image_url/packing_requirements/need_recheck(是否需要复核:Y=需要 N=不需要(免验)));store_remark 来自合约表 store_warehouse.store_remask;只读查询,不涉及缓存失效;保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200;查询成功时生成打包上下文 key(wpck 前缀 + 随机段,Redis 缓存 workbench:packctx:{key},TTL 20 分钟,内容含订单号/波次号/运单号/归属仓库与工作台,后端维护防篡改)并在响应返回 key,供 workbench.packOrder 凭 key 打包;order 附 wave_scope(波次范围:0=未分配波次 1=大团购 2=散单 3=小团购 4=单品单件);大团购打包时长闸门:拉取当前工作台进行中的 wave_scope=1 打包任务(status<2,任务已结束则不计)并判断是否已到「大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数」秒:未到时仅允许查询本波次订单,其他波次订单返回错误「打包时长不足」,已到时不受限制", + "isNeedAuth": false, + "isNeedLogin": false, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "token", + "type": "string", + "required": true, + "source": "body", + "description": "工作台 token(64 位,工作台身份凭证;仓库与工作台由服务端从 token 解析注入)" + }, + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "条码(运单号 waybill_code)" + } + ], + "response": [ + { + "name": "key", + "type": "string", + "required": false, + "description": "打包上下文 key(20 分钟有效,凭此 key 调用 workbench.packOrder 打包,参数后端维护防篡改;缓存写入失败时缺省)" + }, + { + "name": "barcode", + "type": "string", + "required": true, + "description": "条码(运单号,trim 后返回)" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "isSandan", + "type": "number", + "required": true, + "description": "是否散单:1=散单 0=团购(波次类型 wave_type=1 时判定为团购)" + }, + { + "name": "store_remark", + "type": "string", + "required": true, + "description": "货主备注(来自合约表 store_warehouse.store_remask,无记录或查询失败时为空串)" + }, + { + "name": "express", + "type": "object", + "required": true, + "description": "运单快照信息(来自 wms_order_express)" + }, + { + "name": "express.logistics_name", + "type": "string", + "required": false, + "description": "物流公司名称;可空 null" + }, + { + "name": "express.weighing_weight", + "type": "number|string", + "required": false, + "description": "运单称重重量(单位 g);未称重时为空" + }, + { + "name": "express.package_material_name", + "type": "string", + "required": false, + "description": "包材名称快照(package_material_name_snapshot,无快照时为空串)" + }, + { + "name": "order", + "type": "object", + "required": true, + "description": "订单信息(来自订单分表 current/dispatch 命中行;散单另附 intercept_flag/pack_flag 0/1 标志,团购原始字段不含该两标志)" + }, + { + "name": "order.id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "order.delivery_order_code", + "type": "string", + "required": true, + "description": "发货单号" + }, + { + "name": "order.order_type", + "type": "number|string", + "required": false, + "description": "订单类型" + }, + { + "name": "order.warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "order.store_id", + "type": "number", + "required": false, + "description": "货主ID" + }, + { + "name": "order.status", + "type": "number|string", + "required": false, + "description": "订单状态" + }, + { + "name": "order.step", + "type": "number|string", + "required": false, + "description": "订单步骤" + }, + { + "name": "order.wave_id", + "type": "number", + "required": false, + "description": "波次ID(散单为 0)" + }, + { + "name": "order.wave_no", + "type": "string", + "required": false, + "description": "波次号" + }, + { + "name": "order.wave_scope", + "type": "number", + "required": false, + "description": "波次范围:0=未分配波次 1=大团购 2=散单 3=小团购 4=单品单件(来自订单行 wave_scope)" + }, + { + "name": "order.post_status", + "type": "string", + "required": false, + "description": "打单状态" + }, + { + "name": "order.pick_status", + "type": "string", + "required": false, + "description": "拣货状态" + }, + { + "name": "order.pack_status", + "type": "string", + "required": false, + "description": "打包状态(原始值,空值未归一化)" + }, + { + "name": "order.intercept_status", + "type": "string", + "required": false, + "description": "拦截状态(原始值,空值未归一化)" + }, + { + "name": "order.recheck_status", + "type": "string", + "required": false, + "description": "复核状态" + }, + { + "name": "order.outbound_status", + "type": "string", + "required": false, + "description": "出库状态" + }, + { + "name": "order.items_count", + "type": "number", + "required": false, + "description": "SKU 品种数" + }, + { + "name": "order.items_total", + "type": "number", + "required": false, + "description": "商品总件数" + }, + { + "name": "order.items_weight", + "type": "number", + "required": false, + "description": "订单商品重量" + }, + { + "name": "order.source_platform_code", + "type": "string", + "required": false, + "description": "来源平台编码" + }, + { + "name": "order.logistics_name", + "type": "string", + "required": false, + "description": "物流公司名称" + }, + { + "name": "order.create_at", + "type": "string", + "required": false, + "description": "创建时间" + }, + { + "name": "order.updated_at", + "type": "string", + "required": false, + "description": "更新时间" + }, + { + "name": "order.intercept_flag", + "type": "number", + "required": false, + "description": "拦截标志(仅散单 isSandan=1 返回):拦截状态空值归一化为 none,非 none 记 1 否则 0" + }, + { + "name": "order.pack_flag", + "type": "number", + "required": false, + "description": "打包标志(仅散单 isSandan=1 返回):按运单维度判定——该运单号已有打包流水(wms_pack_task.waybill_code 命中,或历史订单级流水 waybill_code 为空兜底)时为 1,否则为 0;主单号/子单号互不影响" + }, + { + "name": "items", + "type": "array", + "required": true, + "description": "订单商品明细数组(按 id ASC,逐项合并 stock 详情;查询异常时为空数组)" + }, + { + "name": "items[].id", + "type": "number", + "required": true, + "description": "订单商品行ID" + }, + { + "name": "items[].order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "items[].item_id", + "type": "number", + "required": false, + "description": "商品ID" + }, + { + "name": "items[].item_code", + "type": "string", + "required": false, + "description": "商品编码(订单行缺失时取 stock.item_code)" + }, + { + "name": "items[].item_name", + "type": "string", + "required": false, + "description": "商品名称(订单行缺失时取 stock.item_name)" + }, + { + "name": "items[].plan_qty", + "type": "number", + "required": false, + "description": "计划数量" + }, + { + "name": "items[].actual_price", + "type": "number", + "required": false, + "description": "实际单价" + }, + { + "name": "items[].stock_id", + "type": "number", + "required": false, + "description": "库存商品ID" + }, + { + "name": "items[].order_line_no", + "type": "string", + "required": false, + "description": "订单行号" + }, + { + "name": "items[].inventory_type", + "type": "string", + "required": false, + "description": "库存类型" + }, + { + "name": "items[].sku_property", + "type": "string", + "required": false, + "description": "SKU 属性(来自 stock 详情)" + }, + { + "name": "items[].stock_unit", + "type": "string", + "required": false, + "description": "库存单位(来自 stock 详情)" + }, + { + "name": "items[].barcodes", + "type": "array", + "required": false, + "description": "条码列表(来自 stock 详情,无则空数组)" + }, + { + "name": "items[].image_url", + "type": "string", + "required": false, + "description": "商品图片地址(来自 stock 详情)" + }, + { + "name": "items[].packing_requirements", + "type": "string", + "required": false, + "description": "打包要求(来自 stock 详情,trim 后返回)" + }, + { + "name": "items[].need_recheck", + "type": "string", + "required": true, + "description": "是否需要复核:Y=需要复核,N=不需要复核(免验)(来自 stock 详情,缺省 Y)" + }, + { + "name": "source_table", + "type": "string", + "required": true, + "description": "订单所在分表:current=待处理表 dispatch=配送表" + }, + { + "name": "batch", + "type": "object", + "required": false, + "description": "团购波次信息(仅团购单 isSandan=0 时返回,散单不返回)" + }, + { + "name": "batch.wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "batch.wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "batch.wave_type", + "type": "number", + "required": true, + "description": "波次类型(1=团购)" + }, + { + "name": "batch.total_orders", + "type": "number", + "required": true, + "description": "波次订单总数(current+dispatch 分表实时统计,15s 短缓存兜底)" + } + ], + "errors": [ + { + "code": "401", + "message": "工作台 token 不能为空(返回 flag=failure、code=401)" + }, + { + "code": "403", + "message": "工作台不存在或 token 无效(返回 flag=failure、code=403)" + }, + { + "code": "403", + "message": "工作台未绑定有效仓库" + }, + { + "code": "0", + "message": "条码不能为空(业务失败,返回 flag=failure、code=0)" + }, + { + "code": "0", + "message": "未找到条码 [xxx] 对应的运单记录(业务失败,返回 flag=failure、code=0)" + }, + { + "code": "0", + "message": "未在待处理或配送表中找到订单 [id=xxx, warehouse=xxx](业务失败,返回 flag=failure、code=0)" + }, + { + "code": 0, + "message": "打包时长不足(当前工作台大团购波次 wave_scope=1 打包未到时,扫描其他波次订单被限制;本波次订单不受限)" + } + ] + }, + { + "method": "workbench.getWorkbenchCount", + "description": "当前工作台班次打包统计(免登录、免权限、免鉴权,以工作台 token 鉴权):仓库与工作台均由服务端从 token 解析注入;统计窗口为本地时间当日 08:00 至次日 08:00,当前时间早于 08:00 时窗口为昨日 08:00 至今日 08:00;个人工作台(type=personal)统计涉及本人的打包数据(本人=工作台成员 user_id,范围=本工作台产生的任务∪本人作为打包人参与的任务),返回团购波次数量/团购订单数量(团购任务 pack_quantity 求和)/散单数量/团散(团购波次数/散单数,2位小数,散单为0时null)/均件数(本人打包任务按订单数量/人数折算求和,2位小数:本人作为打包人参与的任务按实际打包人数均分、本工作台单人任务整单计入);团体工作台(type=group)统计涉及本工作台的打包数据,返回团购波次数量/团购订单数量(团购任务 pack_quantity 快照求和)/散单数量;统计只查 wms_pack_task/wms_pack_task_packer 并走配套索引(idx_warehouse_create_time/idx_workbench_create_time/uix_pack_task_account),不做订单分表实时统计,避免慢 SQL;成功返回 flag=success、code=200", + "isNeedAuth": false, + "isNeedLogin": false, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "token", + "type": "string", + "required": true, + "source": "body", + "description": "工作台 token(64 位,工作台身份凭证;仓库与工作台由服务端从 token 解析注入)" + } + ], + "response": [ + { + "name": "workbench_id", + "type": "number", + "required": true, + "description": "工作台ID" + }, + { + "name": "workbench_type", + "type": "string", + "required": true, + "description": "工作台类型:personal-个人工作台 group-团体工作台" + }, + { + "name": "time_range", + "type": "object", + "required": true, + "description": "统计时间窗口" + }, + { + "name": "time_range.start_time", + "type": "string", + "required": true, + "description": "窗口开始时间(本地时间,格式 YYYY-MM-DD HH:mm:ss)" + }, + { + "name": "time_range.end_time", + "type": "string", + "required": true, + "description": "窗口结束时间(本地时间,格式 YYYY-MM-DD HH:mm:ss)" + }, + { + "name": "group_wave_count", + "type": "number", + "required": true, + "description": "团购波次数量(pack_mode=2 且 wave_id>0 按 wave_id 去重)" + }, + { + "name": "single_order_count", + "type": "number", + "required": true, + "description": "散单数量(pack_mode=1 任务数,每任务对应 1 单)" + }, + { + "name": "group_single_ratio", + "type": "number", + "required": false, + "description": "团散(仅个人工作台返回):团购波次数/散单数,保留 2 位小数;散单数为 0 时返回 null" + }, + { + "name": "avg_piece_count", + "type": "number", + "required": false, + "description": "均件数(仅个人工作台返回):本人打包任务按 订单数量/人数 折算后求和,保留 2 位小数;本人作为打包人参与的任务按任务实际打包人数均分(缺省 1),本工作台单人任务整单计入" + }, + { + "name": "group_order_count", + "type": "number", + "required": false, + "description": "团购订单数量(个人/团体工作台均返回):团购任务 pack_quantity 求和(服务端复查口径)" + } + ], + "errors": [ + { + "code": "401", + "message": "工作台 token 不能为空(返回 flag=failure、code=401)" + }, + { + "code": "403", + "message": "工作台不存在或 token 无效(返回 flag=failure、code=403)" + } + ] + } + ] + }, + { + "groupName": "录像服务器模块", + "module": "camera_server", + "list": [ + { + "method": "camera_server.list", + "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": "分页参数 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选:name(模糊)、status(等值)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "camera_server.detail", + "description": "录像服务器详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "服务器ID" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权访问" + } + ] + }, + { + "method": "camera_server.create", + "description": "新增录像服务器", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "服务器名称(必填)" + }, + { + "name": "brand", + "type": "string", + "required": false, + "source": "body", + "description": "品牌" + }, + { + "name": "public_ip", + "type": "string", + "required": false, + "source": "body", + "description": "公网IP" + }, + { + "name": "internal_ip", + "type": "string", + "required": false, + "source": "body", + "description": "内网IP" + }, + { + "name": "port", + "type": "number", + "required": false, + "source": "body", + "description": "端口号" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "账号" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "密码" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "description": "名称不能为空" + } + ] + }, + { + "method": "camera_server.update", + "description": "更新录像服务器", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "服务器ID(必填)" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "名称" + }, + { + "name": "brand", + "type": "string", + "required": false, + "source": "body", + "description": "品牌" + }, + { + "name": "public_ip", + "type": "string", + "required": false, + "source": "body", + "description": "公网IP" + }, + { + "name": "internal_ip", + "type": "string", + "required": false, + "source": "body", + "description": "内网IP" + }, + { + "name": "port", + "type": "number", + "required": false, + "source": "body", + "description": "端口号" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "账号" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "密码" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "0-禁用 1-启用" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权操作" + } + ] + }, + { + "method": "camera_server.delete", + "description": "删除录像服务器(软删除)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "服务器ID" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权操作" + } + ] + } + ] + }, + { + "groupName": "摄像头模块", + "module": "camera", + "list": [ + { + "method": "camera.list", + "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": "分页参数 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选:server_id(等值)、custom_name(模糊)、status(等值)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "camera.detail", + "description": "摄像头详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权访问" + } + ] + }, + { + "method": "camera.create", + "description": "新增摄像头", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "server_id", + "type": "number", + "required": true, + "source": "body", + "description": "所属服务器ID(必填)" + }, + { + "name": "channel_id", + "type": "number", + "required": true, + "source": "body", + "description": "通道编号(必填)" + }, + { + "name": "channel_name", + "type": "string", + "required": false, + "source": "body", + "description": "通道名称" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "自定义名称" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "0-禁用 1-启用" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "摄像头登录用户名" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "摄像头登录密码" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "description": "server_id/channel_id 不能为空" + } + ] + }, + { + "method": "camera.update", + "description": "更新摄像头", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "server_id", + "type": "number", + "required": false, + "source": "body", + "description": "所属服务器ID" + }, + { + "name": "channel_id", + "type": "number", + "required": false, + "source": "body", + "description": "通道编号" + }, + { + "name": "channel_name", + "type": "string", + "required": false, + "source": "body", + "description": "通道名称" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "自定义名称" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "0-禁用 1-启用" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "摄像头登录用户名" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "摄像头登录密码" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权操作" + } + ] + }, + { + "method": "camera.setOsd", + "description": "设置摄像头 OSD 文字叠加", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "text", + "type": "string", + "required": true, + "source": "body", + "description": "OSD 叠加文字(必填)" + }, + { + "name": "x", + "type": "number", + "required": false, + "source": "body", + "description": "X 坐标(-1 到 1,默认 -0.9)" + }, + { + "name": "y", + "type": "number", + "required": false, + "source": "body", + "description": "Y 坐标(-1 到 1,默认 0.8)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "description": "摄像头ID/OSD文字不能为空" + }, + { + "code": "404", + "description": "摄像头不存在或无权操作" + }, + { + "code": "500", + "description": "打印服务调用失败" + } + ] + }, + { + "method": "camera.delete", + "description": "删除摄像头(软删除)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID" + } + ], + "response": [], + "errors": [ + { + "code": "404", + "description": "不存在或无权操作" + } + ] + }, + { + "method": "camera.ptzControl", + "description": "云台方向控制(按下):按指定方向持续转动摄像头,需配对调用 camera.ptzStop 停止", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "action", + "type": "string", + "required": true, + "source": "body", + "description": "云台方向(必填,8 个位置):up-上 / down-下 / left-左 / right-右 / upleft-左上 / upright-右上 / downleft-左下 / downright-右下;大小写不敏感,服务端统一转小写校验", + "list": [ + { + "value": "up", + "name": "上" + }, + { + "value": "down", + "name": "下" + }, + { + "value": "left", + "name": "左" + }, + { + "value": "right", + "name": "右" + }, + { + "value": "upleft", + "name": "左上" + }, + { + "value": "upright", + "name": "右上" + }, + { + "value": "downleft", + "name": "左下" + }, + { + "value": "downright", + "name": "右下" + } + ] + }, + { + "name": "speed", + "type": "number", + "required": false, + "source": "body", + "description": "云台转速(可选,1-7 的整数,默认 4)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "message": "摄像头ID不能为空;云台方向不能为空/不合法;云台转速不是 1-7 的整数;摄像头未配置IP地址" + }, + { + "code": "404", + "message": "摄像头不存在或无权操作" + }, + { + "code": "500", + "message": "打印服务调用失败" + } + ], + "notes": [ + "对接打印服务:POST {printService.url}/camera/ptzControl,请求体 { warehouse_id, cameraId, rtspUrl, action, speed }(warehouse_id 为字符串,与 camera.setOsd 口径一致)", + "本接口与 camera.setOsd 同风格:独立端点 + 独立请求体,**不需要也不接收 computerId**(打印服务按 rtspUrl 定位摄像头,无需房间路由)", + "action 枚举(8 个位置,与打印服务约定,顺序固定):up-上、down-下、left-左、right-右、upleft-左上、upright-右上、downleft-左下、downright-右下", + "交互口径:按下调用本接口(持续转动),松手调用 camera.ptzStop(action 必须与按下时一致);长时间无 stop 指令时摄像头端会持续转动,前端需保证 pointerup/pointerleave 兜底停止", + "rtspUrl 由服务端按摄像头记录组装(rtsp://{username}:{password}@{ip}:554/stream{channel_id},与 camera.setOsd 同口径),入参无需传入", + "代码:app/service/systemMethods/camera.js#ptzControl(systemInit 已声明 _noNeedRight/_noNeedAuth/_noNeedLog 含 ptzControl)-> app/service/systems/camera.js#ptzControl -> app/lib/ptz_client.js#control" + ] + }, + { + "method": "camera.ptzStop", + "description": "云台停止(松手):停止转动,action 必须与按下时一致", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "action", + "type": "string", + "required": true, + "source": "body", + "description": "云台方向(必填,必须与按下时的 action 一致):up-上 / down-下 / left-左 / right-右 / upleft-左上 / upright-右上 / downleft-左下 / downright-右下", + "list": [ + { + "value": "up", + "name": "上" + }, + { + "value": "down", + "name": "下" + }, + { + "value": "left", + "name": "左" + }, + { + "value": "right", + "name": "右" + }, + { + "value": "upleft", + "name": "左上" + }, + { + "value": "upright", + "name": "右上" + }, + { + "value": "downleft", + "name": "左下" + }, + { + "value": "downright", + "name": "右下" + } + ] + } + ], + "response": [], + "errors": [ + { + "code": "400", + "message": "摄像头ID不能为空;云台方向不能为空/不合法;摄像头未配置IP地址" + }, + { + "code": "404", + "message": "摄像头不存在或无权操作" + }, + { + "code": "500", + "message": "打印服务调用失败" + } + ], + "notes": [ + "对接打印服务:POST {printService.url}/camera/ptzStop,请求体 { warehouse_id, cameraId, rtspUrl, action }(不带 speed)", + "不需要 computerId,与 camera.setOsd / camera.ptzControl 口径一致", + "action 必须与 camera.ptzControl 时传入的值一致,否则摄像头可能无法停止", + "代码:app/service/systemMethods/camera.js#ptzStop -> app/service/systems/camera.js#ptzStop -> app/lib/ptz_client.js#stop" + ] + }, + { + "method": "camera.ptzPresetGoto", + "description": "云台预置点跳转:跳转到指定预置点(一次调用即可,无需 stop)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "presetId", + "type": "number", + "required": true, + "source": "body", + "description": "预置点编号(必填,1-256 的整数)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "message": "摄像头ID不能为空;预置点编号不能为空/不是 1-256 的整数;摄像头未配置IP地址" + }, + { + "code": "404", + "message": "摄像头不存在或无权操作" + }, + { + "code": "500", + "message": "打印服务调用失败" + } + ], + "notes": [ + "对接打印服务:POST {printService.url}/camera/ptzPresetGoto,请求体 { warehouse_id, cameraId, rtspUrl, presetId }", + "不需要 computerId,与 camera.setOsd / camera.ptzControl 口径一致", + "预置点跳转是一次性动作,不需要配对 stop;预置点需提前在摄像头端配置", + "代码:app/service/systemMethods/camera.js#ptzPresetGoto -> app/service/systems/camera.js#ptzPresetGoto -> app/lib/ptz_client.js#presetGoto" + ] + }, + { + "method": "camera.ptzPresetSet", + "description": "云台预置点设置:把摄像头当前机位保存为指定预置点(一次调用即可)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "presetId", + "type": "number", + "required": true, + "source": "body", + "description": "预置点编号(必填,1-256 的整数;已存在的编号会被当前机位覆盖)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "message": "摄像头ID不能为空;预置点编号不能为空/不是 1-256 的整数;摄像头未配置IP地址" + }, + { + "code": "404", + "message": "摄像头不存在或无权操作" + }, + { + "code": "500", + "message": "打印服务调用失败" + } + ], + "notes": [ + "对接打印服务:POST {printService.url}/camera/ptzPresetSet,请求体 { warehouse_id, cameraId, rtspUrl, presetId }(warehouse_id 为字符串,与 camera.setOsd 口径一致)", + "不需要 computerId,与 camera.setOsd / camera.ptzControl 口径一致", + "语义:把摄像头**当前机位**保存为该 presetId 的预置点(同一编号重复设置即覆盖);常用于「先 ptzControl 转到目标位置 → 再 ptzPresetSet 存点 → 以后用 camera.ptzPresetGoto 一键回到该机位」", + "与 camera.ptzPresetGoto 的区别:ptzPresetSet 写(存点)、ptzPresetGoto 读(跳转);两者均是一次性动作,无需配对 stop", + "代码:app/service/systemMethods/camera.js#ptzPresetSet -> app/service/systems/camera.js#ptzPresetSet -> app/lib/ptz_client.js#presetSet" + ] + } + ] + }, + { + "groupName": "商品流水模块", + "module": "stock.transaction", + "list": [ + { + "method": "stock.transaction.export", + "description": "提交商品出入库流水导出异步任务(仓库侧)。与 stock.transaction.list 使用相同查询条件,立即返回任务受理信息,不直接返回文件。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time(开始时间)、end_time(结束时间)、store_ids(货主ID数组)、stock_ids(商品库存ID数组)、transaction_type(流水类型 INBOUND/OUTBOUND/LOCK/UNLOCK)、order_type(单据类型)、order_no(单据号,模糊匹配)、batch_no(批次号)、entry_order_id(入库单ID)、receiving_id(收货单ID)、order_id(发货单ID)。仓库范围自动取自 ctx.user.store_id。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间" + }, + { + "name": "where.store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "货主ID数组" + }, + { + "name": "where.stock_ids", + "type": "array", + "required": false, + "source": "body", + "description": "商品库存ID数组" + }, + { + "name": "where.transaction_type", + "type": "string", + "required": false, + "source": "body", + "description": "流水类型:INBOUND/OUTBOUND/LOCK/UNLOCK" + }, + { + "name": "where.order_type", + "type": "string", + "required": false, + "source": "body", + "description": "单据类型" + }, + { + "name": "where.order_no", + "type": "string", + "required": false, + "source": "body", + "description": "单据号(模糊匹配)" + }, + { + "name": "where.batch_no", + "type": "string", + "required": false, + "source": "body", + "description": "批次号" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数。sortField 白名单:created_at/quantity/stock_id/store_id/warehouse_id;sortOrder 支持 ASC/DESC" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度:0" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "受理消息" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "更新时间戳" + } + ], + "errors": [] + }, + { + "method": "stock.transaction.exportStore", + "description": "提交商品出入库流水导出异步任务(货主侧)。与 stock.transaction.storeList 使用相同查询条件,需传 store_id,立即返回任务受理信息。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time、end_time、warehouse_ids(仓库ID数组)、stock_ids(商品库存ID数组)、transaction_type、order_type、order_no、batch_no、entry_order_id、receiving_id、order_id。兼容 warehouse_id 单数。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数。sortField 白名单:created_at/quantity/stock_id/store_id/warehouse_id" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度:0" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "受理消息" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "更新时间戳" + } + ], + "errors": [] + }, + { + "method": "stock.transaction.exportTaskProgress", + "description": "根据 task_id 查询商品流水导出任务进度与结果。status 可能值:submitted/running/success/failed/not_found。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法)" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "状态说明" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时错误信息" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "成功后下载链接" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "更新时间戳" + } + ], + "errors": [] + } + ] + }, + { + "groupName": "库存盘点模块", + "module": "stock.check", + "list": [ + { + "method": "stock.check.create", + "description": "创建盘点任务(空任务):生成盘点单号(PD+YYYYMMDD+6位序号,序号全局递增(不按仓库隔离),并发下撞 uk_check_no 唯一键自动重取重试(最多 5 次),口径与收货单 receiving_number 一致),初始状态 created、明细进度 none_checked;warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,前端无需传递。盘点范围类型语义:location=按库位盘点(添加明细时未传库位自动拉取全仓库启用库位生成范围,原 all 全盘语义已并入)/ store=按货主按商品盘点(必须指定货主)/ goods=按商品盘点,缺省 location;type=location 时明细为库位行(scope_type=location),type=store/goods 时明细为商品行(scope_type=goods);type=all 已下线(与 location 语义重复),传入返回 400。盘点时间不传(主表已无 check_date):start_time=盘点开始时间(第一个盘点明细写入的时间,report 首次写入明细时补写)、end_time=盘点结束时间(完成盘点的时间,finish 时写入),与 patternCreate 口径一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "title", + "type": "string", + "required": false, + "source": "body", + "description": "盘点名称/主题(非必填)" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "盘点范围类型,缺省 location:location=按库位盘点(未传库位时自动全仓库启用库位生成盘点范围)/ store=按货主按商品盘点 / goods=按商品盘点;location 走库位明细行(scope_type=location),store/goods 走商品明细行(scope_type=goods);all 已下线(与 location 语义重复),传入返回 400" + }, + { + "name": "mode", + "type": "string", + "required": false, + "source": "body", + "description": "盘点方式,缺省 open:open=明盘(可见账面数量)/ blind=盲盘(不可见账面数量);按库位盘点(location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID(type=store 按货主按商品盘点时必填;添加商品明细时商品货主必须与该货主一致)" + }, + { + "name": "is_static", + "type": "number", + "required": false, + "source": "body", + "description": "是否静态盘点(可选,纯标记;0=普通盘点(缺省)/1=静态盘点;兼容布尔 true 与 isStatic 驼峰写法,'true'/'1' 亦视为开启,其他值视为普通盘点)。**仅对商品盘点(type=store/goods)有效**:按库位盘点(type=location)恒为 0,传入 1 也忽略;静态盘点定式创建的任务由服务端自动置 1" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)(含 is_static 静态盘点标记)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "盘点任务ID" + }, + { + "name": "check_no", + "type": "string", + "required": true, + "description": "盘点单号(PD+YYYYMMDD+6位序号)" + }, + { + "name": "title", + "type": "string", + "required": true, + "description": "盘点名称/主题" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "盘点范围类型:location/store/goods" + }, + { + "name": "mode", + "type": "string", + "required": true, + "description": "盘点方式:open/blind" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "description": "货主ID(按货主盘点时有值)" + }, + { + "name": "is_static", + "type": "number", + "required": true, + "description": "is_static 是否静态盘点(1=静态盘点,仅商品盘点 type=store/goods 可能为 1——由静态盘点定式 pattern=static 创建或创建时显式开启;按库位盘点 type=location 恒为 0;纯标记字段,不改变盘点方式/状态机/差异口径)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "主表状态(新建为 created)" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "明细盘点进度:none_checked/partial_checked/all_checked(新建为 none_checked)" + }, + { + "name": "start_time", + "type": "string", + "required": false, + "description": "盘点开始时间(第一个盘点明细写入的时间,创建时为空)" + }, + { + "name": "end_time", + "type": "string", + "required": false, + "description": "盘点结束时间(完成盘点的时间,创建时为空)" + }, + { + "name": "creator_id", + "type": "number", + "required": true, + "description": "创建人账户ID" + }, + { + "name": "creator_name", + "type": "string", + "required": true, + "description": "创建人名称快照" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "明细行数" + }, + { + "name": "checked_items", + "type": "number", + "required": true, + "description": "已盘行数" + }, + { + "name": "diff_items", + "type": "number", + "required": true, + "description": "差异行数" + }, + { + "name": "remark", + "type": "string", + "required": true, + "description": "备注" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文 / 盘点范围类型不合法(仅支持 store/goods/location)/ 盘点方式不合法(仅支持 open/blind)/ 按货主盘点时必须指定货主" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#generateCheckNo 移除 warehouse_id 隔离条件,改为查询全局最大 PD+YYYYMMDD 前缀单号并取末尾 6 位序号 +1(不按仓库隔离);新增 isCheckNoDuplicateError()(parent.code === 'ER_DUP_ENTRY' 且 sqlMessage 命中 uk_check_no/check_no,参照收货单 isReceivingNumberDuplicateError 口径);create() 创建撞唯一键时自动重取单号重试,最多 5 次(maxCreateRetries=5,与收货单 create 重试口径一致);超过重试次数或非单号冲突错误原样抛出。", + "原因说明:uk_check_no 为全局唯一索引(不区分仓库),原按仓库隔离序号各自从 1 起会跨仓撞号;改为全局递增后并发创建仍有极小概率撞号,由唯一键重试兜底。", + "收货单参照口径:与收货单 receiving_number 一致——按全局最大序号 +1 生成 + 撞唯一键自动重取重试。", + "并发重试说明:每次重试都重新调用 generateCheckNo() 取最新全局最大序号;仅 ER_DUP_ENTRY 且命中 uk_check_no 的错误才重试,其它错误不重试直接抛出。", + "范围类型语义:type=location 为按库位盘点(明细为库位行 scope_type=location,未传库位时自动全仓库启用库位生成范围,原 all 全盘语义已并入);type=all 已下线(与 location 语义重复),create 传入返回 400;type=store/goods 为按商品盘点(明细为商品行 scope_type=goods,store 必须指定货主)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create/addDetail/report/detail/finish/export 六条(范围类型语义与库位行支持);根版本 0.3.205 → 0.3.206、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。", + "盘点方式规则:按库位盘点(type=location,明细为库位行)一律盲盘(blind),忽略前端传入的 mode;按商品盘点(type=store/goods,明细为商品行)按传入值,默认明盘(open)。代码依据:app/service/systems/stock_check.js#create 在 mode 合法性校验(仅支持 open/blind)通过后、写库前,normalizedType 为 location 时强制 normalizedMode='blind'。", + "盘点时间口径(主表无 check_date):create 不写盘点时间(入参与主表均无 check_date,迁移 20260930150000-remove-check-date-from-wms-stock-check.js 已移除字段与索引);start_time=盘点开始时间(第一个盘点明细写入的时间,report 首次写入明细时补写)、end_time=盘点结束时间(完成盘点的时间,finish 时写入);_formatCheckRow 不再返回 check_date(仅返回 start_time/end_time);代码依据:app/service/systems/stock_check.js#create(不再写 check_date)、#report(start_time 为空补写)、#finish(写 end_time)、#_formatCheckRow(仅返回 start_time/end_time)。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "静态标记(本次,0.3.310):wms_stock_check 新增 is_static(TINYINT(1) NOT NULL DEFAULT 0),create 支持入参 is_static(兼容 isStatic/布尔/字符串写法:true、'true'、1、'1' 记为 1,其余值记为 0);纯标记字段,不参与模式强制(location 仍强制 blind)、状态机与差异计算;操作日志 STOCK_CHECK_CREATE 的 message/extras 追加静态标记。代码依据:app/service/systems/stock_check.js#create(normalizedIsStatic)、database/migrations/20261028010000-add-is-static-to-stock-check.js。", + "静态标记口径收窄(本次,0.3.311):静态盘点(长期停收停发商品的盘点)只对商品盘点有意义,库位盘点(type=location)不涉及静态商品概念,因此 create 时 type=location 一律把 is_static 置 0(传入 1/true 也忽略,不报错),仅 type=store/goods 才按入参取值;响应字段与 list/detail 返回口径不变(库位盘点行恒为 0)。代码依据:app/service/systems/stock_check.js#create(normalizedIsStatic = type === 'location' || !requested ? 0 : 1)。" + ] + }, + { + "method": "stock.check.list", + "description": "拉取盘点任务列表:按当前用户仓库(ctx.user.store_id)限定数据范围,支持 status 状态筛选(单值或数组)、type 范围类型筛选(单值或数组)、mode 盘点方式筛选(单值或数组)、store_id 货主筛选、created_at 创建时间筛选、start_time 盘点开始时间筛选、end_time 盘点结束时间筛选(时间条件:单值=该字段 >= 该值,数组 [from,to]=between 区间)、keyword 关键字(盘点单号/标题模糊)与分页。 每行返回新增 store_name 货主名称(优先合约货主备注 store_remask、兜底公司全称 company_name,详见 response.rows)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1、pageSize=20,pageSize 上限 200" + }, + { + "name": "where.status", + "type": "string", + "required": false, + "source": "body", + "description": "状态筛选(单值或数组,自动去重):created/submitted/rejected/approved/checking/completed/cancelled" + }, + { + "name": "where.type", + "type": "string", + "required": false, + "source": "body", + "description": "盘点范围类型筛选(单值或数组,自动去重):location=按库位盘点 / store=按货主按商品盘点 / goods=按商品盘点" + }, + { + "name": "where.mode", + "type": "string", + "required": false, + "source": "body", + "description": "盘点方式筛选(单值或数组,自动去重):open=明盘(可见账面数量)/ blind=盲盘(不可见账面数量)" + }, + { + "name": "where.store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主筛选" + }, + { + "name": "where.created_at", + "type": "string", + "required": false, + "source": "body", + "description": "创建时间筛选:单值=created_at >= 该值(从该值起);数组 [from,to]=between 闭区间(from <= created_at <= to,仅传 from=gte、仅传 to=lte);非法时间值静默忽略(不加入筛选条件)" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "盘点开始时间筛选(start_time,第一个盘点明细写入的时间),口径同 created_at:单值=start_time >= 该值(从该值起);数组 [from,to]=between 闭区间;非法时间值静默忽略" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "盘点结束时间筛选(end_time,完成盘点的时间),口径同 created_at:单值=end_time >= 该值(从该值起);数组 [from,to]=between 闭区间;非法时间值静默忽略" + }, + { + "name": "where.keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键字,对盘点单号(check_no)/标题(title)模糊匹配" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "rows", + "type": "array", + "required": true, + "description": "盘点任务行列表(主表全字段,含 check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at,每行新增 store_name 货主名称;start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间));store_name=货主名称:优先 wms_store_warehouse.store_remask(合约货主备注,按 store_id+warehouse_id 匹配);无合约或备注为空时回退 wms_store.company_name(公司全称);两者均查不到返回空字符串;另含 is_static 是否静态盘点(1=静态盘点(由静态盘点定式 pattern=static 创建,或创建任务时显式开启),0=普通盘点;纯标记字段,不改变盘点方式/状态机/差异口径)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总条数" + }, + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页条数" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "store_name 代码依据:app/service/systems/stock_check.js#list 返回 rows 前调用 _resolveStoreNameMap()(按 store_id+warehouse_id 查 wms_store_warehouse.store_remask,无合约或备注为空回退 wms_store.company_name),每行新增 store_name 货主名称,查不到返回空字符串;未改动任何业务逻辑。", + "代码依据:app/service/systems/stock_check.js#list——新增 type/mode 枚举筛选(_normalizeEnumValues 归一化 trim 去重,单值 eq、多值 Op.in)、store_id 数值 eq、created_at/start_time/end_time 时间筛选(_buildTimeRangeCondition:数组 [from,to] 两端合法=Op.between、仅 from=Op.gte、仅 to=Op.lte,单值=Op.gte,非法时间值返回 null 静默忽略);app/service/systemMethods/stock/check.js#list——经 prepareWhereContext 提取 where(支持 {operator,value} 标准结构,between 对象值归一为 [from,to])后传给 systems 层,并保留 data 顶层字段兜底(whereValue 优先、data 顶层兼容)。", + "修复点:原方法层 list 未从 where 提取 type(方法层解构仅有 status/store_id/keyword,where.type 传入不生效);本次方法层补齐 type/mode/created_at/start_time/end_time 提取,status/keyword 已有逻辑不变。", + "筛选口径:status/type/mode 支持单值 eq 或数组 in(归一化 trim 后自动去重,空值忽略);store_id 经 Number 归一化后 eq;keyword 对盘点单号 check_no 与标题 title 做 OR 模糊匹配;所有筛选均叠加在 warehouse_id(ctx.user.store_id 仓库隔离)之上。", + "时间范围语义:created_at/start_time/end_time 三列口径一致——单值=该字段 >= 该值(从该值起);数组 [from,to] 两端都合法=between 闭区间,仅 from 合法=gte、仅 to 合法=lte;空值/无法解析的日期静默忽略(不加入 where 条件)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.list 一条(response.rows 描述新增 store_name 货主名称与解析口径,description/notes 同步;params/errors/headers/鉴权不变);根版本 0.3.219 → 0.3.220、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "静态标记返回(本次,0.3.310):wms_stock_check 新增 is_static 字段,list 的行对象直接透出该字段(沿用 raw 行全字段口径),取值 0=普通盘点 / 1=静态盘点;筛选仍只支持 status/type/mode/store_id/keyword/时间范围,未新增 is_static 筛选(如需按静态过滤请提需求)。", + "静态标记口径(本次,0.3.311):list 行对象 is_static 恒为 0(库位盘点)或按任务来源/入参取值(商品盘点),未新增筛选条件。" + ] + }, + { + "method": "stock.check.addDetail", + "description": "添加盘点明细(商品或库位,按任务盘点类型决定):type=store/goods 按 stock_ids 添加商品行(scope_type=goods,商品任务必须按库位盘点:按商品在仓库的启用库存库位(wms_storage is_enabled=1 且库位有效——库位未删除且所属 zone 存在未删除,排除无头库位,按 space_id 分组 SUM)拆行——每个「商品+库位」生成一条明细行,location_id/location_code 快照绑定库存库位、system_quantity=该库位库存 SUM,一个商品多个库位对应多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细),商品必须属于本仓库,且任务 store_id 非空时商品货主必须与任务货主一致(不一致的商品记入 invalid_stock_ids);type=location 按 locations(库位编码)或 location_ids(库位ID)添加库位行(scope_type=location),location_ids 优先(两者都传时 locations 忽略)——库位ID路径直接按 wms_location_space.id+warehouse_id 查库校验(不再按编码二次解析),查不到的 ID 记入 invalid_location_ids,编码路径按 warehouse_id+space_code 匹配 wms_location_space,不存在的编码记入 invalid_locations;库位必须有效(未删除且所属 zone 存在未删除):无头库位(zone 不存在/已删除)分别记入 invalid_location_ids / invalid_locations;type=location 未传库位且未传库位ID时自动拉取全仓库启用且有效库位(排除无头库位)生成盘点范围(原 all 全盘语义);type=all 已下线(与 location 语义重复),传 all 的历史任务添加明细返回 400;stock_ids 与 locations/location_ids 按任务类型二选一(传错维度报 400:按库位盘点传 stock_ids 报『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』,按商品盘点传 locations 报『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报『当前盘点类型按商品盘点,不能添加库位明细』),locations 兼容 location_codes 写法(locations 优先)、location_ids 兼容 locationIds 驼峰写法(location_ids 优先);仅 created/rejected 状态允许;已存在同盘点项(商品行 stock_id / 库位行 location_code)自动跳过(幂等);完成后重算主表 total_items。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + }, + { + "name": "stock_ids", + "type": "array", + "required": false, + "source": "body", + "description": "商品库存ID列表(wms_stock_warehouse.id);type=store/goods 按商品盘点时使用,与 locations/location_ids 按任务类型二选一;每个商品按其启用库存库位(wms_storage is_enabled=1,按 space_id 分组)拆分为多行,无启用库存库位的商品记入 invalid_stock_ids" + }, + { + "name": "locations", + "type": "array", + "required": false, + "source": "body", + "description": "库位编码列表(wms_location_space.space_code);type=location 按库位盘点时使用,与 stock_ids 按任务类型二选一;与 location_ids 同时传入时被忽略(location_ids 优先);type=location 未传库位且未传 location_ids 时自动拉取全仓库启用库位生成盘点范围" + }, + { + "name": "location_codes", + "type": "array", + "required": false, + "source": "body", + "description": "库位编码列表(兼容别名;locations 优先,两者都传时以 locations 为准)" + }, + { + "name": "location_ids", + "type": "array", + "required": false, + "source": "body", + "description": "库位ID列表(wms_location_space.id);type=location 按库位盘点时使用,直接按 id+warehouse_id 查库校验(不再按编码二次解析),查不到的 ID 记入 invalid_location_ids(不报错);与 locations 同时传入时 location_ids 优先、locations 忽略;兼容 locationIds 驼峰写法(location_ids 优先)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "added", + "type": "number", + "required": true, + "description": "本次新增明细数(商品路径为按「商品+库位」拆行后的明细行数)" + }, + { + "name": "skipped", + "type": "number", + "required": true, + "description": "已存在被跳过(幂等)的盘点项数" + }, + { + "name": "invalid_stock_ids", + "type": "array", + "required": true, + "description": "无效商品库存ID列表(不存在、不属于当前仓库、商品货主与任务货主不一致、在仓库无启用库存库位或启用库存全部在无头库位)" + }, + { + "name": "invalid_locations", + "type": "array", + "required": true, + "description": "无效库位编码列表(当前仓库不存在对应库位编码或无头库位(所属 zone 不存在/已删除))" + }, + { + "name": "invalid_location_ids", + "type": "array", + "required": true, + "description": "无效库位ID列表(按 wms_location_space.id 直查当前仓库不存在)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "重算后的明细总行数" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在 / 当前状态(非 created/rejected)不允许添加明细 / 请至少选择一个商品 / 当前盘点类型按商品盘点,请传 stock_ids / 当前盘点类型按商品盘点,不能添加库位明细 / 当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务) / 请至少选择一个库位 / 当前仓库没有启用库位,无法按全盘自动生成盘点范围" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "无头库位排除(本次变更):库位所属 zone 不存在或已删除即视为无头库位,一律不纳入盘点——商品路径仅按有效库位拆行(启用库存全部在无头库位的商品计入 invalid_stock_ids)、库位编码/ID 路径计入 invalid_locations/invalid_location_ids(不报错)、全盘自动范围直接排除;workData goods/space 视图库位枚举与明细生成同口径过滤。代码依据:app/service/systems/stock_check.js#VALID_SPACE_SQL(模块常量:wms_location_space JOIN wms_location_zone deleted_at IS NULL)。", + "按类型二选一:type=store/goods 传 stock_ids(传 locations 报『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报『当前盘点类型按商品盘点,不能添加库位明细』);type=location 传 locations 或 location_ids(传 stock_ids 报『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』)。", + "location_ids 优先:两者都传时忽略 locations,直接按 wms_location_space.id+warehouse_id 查库校验(不再按 space_code 二次解析),查不到的 ID 记入 invalid_location_ids(不报错)。", + "下线说明:type=all 已移除(与 location 语义重复:同样按库位盘点、同样强制盲盘、明细同为库位行),全盘能力并入 location;create 传 all 返回 400「盘点范围类型不合法,仅支持 store/goods/location」,历史 type=all 任务(如迁移未覆盖)添加明细返回 400「盘点范围类型不合法(all)」。存量数据口径见 database/migrations/20261027010000-merge-stock-check-type-all-into-location.js:明细含商品行(scope_type=goods,改造前全仓按商品口径)的历史任务改 type=goods(mode 保持原值),其余(库位行/无明细空任务)改 type=location 并归一 mode=blind。", + "商品货主限制:任务 store_id 非空时商品 store_id 必须与之一致,不一致计入 invalid_stock_ids(限制非本货主商品加入盘点)。", + "全盘自动范围(原 all 语义):type=location 且未传库位且未传 location_ids 时,自动拉取当前仓库全部启用且有效库位(is_enabled=true 且所属 zone 存在未删除,排除无头库位)的 space_code 生成库位行;无启用库位时报 400。", + "幂等:商品行按 check_id+stock_id 整体跳过(同商品重复添加整体跳过,不重复拆行)、库位行按 check_id+location_code 跳过(商品行唯一索引 uk_check_stock_location(check_id, stock_id, location_id),库位行原唯一约束 uk_check_location 已放宽为普通索引 idx_check_location、幂等由应用层查重保证);location_ids 路径跳过项按库位ID记入 skipped。", + "商品拆行口径(本次改造,商品任务必须按库位盘点):type=store/goods 传 stock_ids 后按商品在仓库的启用库存库位(wms_storage is_enabled=1 且库位有效(未删除且所属 zone 存在未删除,排除无头库位),按 space_id 分组 SUM(available_quantity)(=可用数量,不含锁定待出库))拆行——每个「商品+库位」生成一条 scope_type=goods 明细行(location_id/location_code 快照绑定库存库位、system_quantity=该库位库存 SUM(可用数量));一个商品多个库位对应多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细;added/total_items 均为拆分明细行数。代码依据:app/service/systems/stock_check.js#_addGoodsDetailRows(Storage.findAll warehouse_id+stock_id in+is_enabled=1、attributes SUM(quantity)、group=[stock_id, space_id];LocationSpace 按 id 取 space_code 快照)。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" + ] + }, + { + "method": "stock.check.detailDelete", + "description": "批量删除盘点明细:入参 id(盘点任务ID)+ detail_ids(盘点明细ID数组,单次上限 200;兼容 detailIds 驼峰写法与旧版 detail_id 单值写法,单值自动转数组,优先级 detail_ids > detailIds > detail_id);仅主表状态 created/rejected 允许删除;未命中(明细不存在或不属于当前仓库)的明细ID计入 skipped_ids 不报错;命中明细批量删除并对 wms_stock_check_record 防御性清理作业记录(正常流程该状态不应有记录);删除后重算主表 total_items,返回 { deleted_count, deleted_ids, skipped_ids, total_items }。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + }, + { + "name": "detail_ids", + "type": "array", + "required": true, + "source": "body", + "description": "盘点明细ID数组(单次上限 200;兼容 detailIds 驼峰写法与旧版 detail_id 单值写法,单值自动转数组;优先级 detail_ids > detailIds > detail_id)" + }, + { + "name": "detailIds", + "type": "array", + "required": false, + "source": "body", + "description": "盘点明细ID数组(驼峰别名,兼容写法,单值自动转数组;detail_ids 优先)" + }, + { + "name": "detail_id", + "type": "number", + "required": false, + "source": "body", + "description": "盘点明细ID(旧版单值写法,自动转数组;detail_ids/detailIds 优先)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "deleted_count", + "type": "number", + "required": true, + "description": "实际删除的明细数量" + }, + { + "name": "deleted_ids", + "type": "array", + "required": true, + "description": "实际删除的明细ID列表(保持入参顺序)" + }, + { + "name": "skipped_ids", + "type": "array", + "required": true, + "description": "未命中被跳过的明细ID列表(明细不存在或不属于当前仓库,不报错;保持入参顺序)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "删除后重算的主表明细总行数" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在 / 当前状态(非 created/rejected)不允许删除明细 / 请至少选择一个明细 / 单次最多删除 200 条明细" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "写操作,记录操作日志(不在免日志清单 list/detail/result/recordList/export/exportTaskProgress/patternList 中)。", + "入参兼容:detail_ids 优先于 detailIds、detail_id;detailIds/detail_id 为旧版兼容写法,单值自动转数组。", + "批量口径:未命中(明细不存在或不属于当前仓库)的明细ID计入 skipped_ids 不报错;命中明细批量删除后对 wms_stock_check_record 按 { detail_id, check_id, warehouse_id } 防御性清理作业记录,并重算主表 total_items;deleted_ids/skipped_ids 均保持入参顺序。", + "响应结构变更(兼容性影响):由旧版 { detail_id, deleted, total_items } 变更为 { deleted_count, deleted_ids, skipped_ids, total_items },前端需按新结构取值。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" + ] + }, + { + "method": "stock.check.detail", + "description": "拉取盘点任务详情(只返回任务本身信息):入参 id(盘点任务ID);返回 { check },check 为盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at;start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间))+ 数量差异汇总 profit_total(盘盈合计数量)/loss_total(盘亏合计数量,正数口径,与 finish 一致;商品范围按商品聚合 vs 账面快照合计(未盘商品按实盘 0 计盘亏)、库位行按商品聚合 vs wms_storage 账面(SUM(available_quantity)=可用数量,未盘库位行不计差异)、未知商品按实盘计盘盈;无作业记录时均为 0);不再返回明细范围行(rows)与明细总条数(total)——盘点明细范围行/盘点结果聚合请调用 stock.check.result,作业记录请调用 stock.check.recordList,盘点作业数据请调用 stock.check.workData;400 边界(任务ID为空/任务不存在)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "check", + "type": "object", + "required": true, + "description": "盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/is_static(1=静态盘点/0=普通盘点)/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at + profit_total 盘盈合计数量 / loss_total 盘亏合计数量(正数口径,与 finish 一致;商品行聚合 vs 账面快照(未盘商品行按实盘 0 计盘亏)、库位行按商品聚合 vs wms_storage 账面(SUM(available_quantity)=可用数量,未盘库位行不计差异)、未知商品按实盘计盘盈);start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间))" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "只返回任务本身信息口径(本次改造):detail 不再查询/返回 wms_stock_check_detail 明细范围行与作业记录,响应仅含 { check }(不含 rows/total);同时移除商品行 stock 全局商品信息挂载(原 stockWarehouse.getStockDetails 挂载逻辑随 rows 一并移除)。明细范围行/盘点结果聚合见 stock.check.result,作业记录见 stock.check.recordList,盘点作业数据见 stock.check.workData。代码依据:app/service/systems/stock_check.js#detail(_formatDetailScopeRow 已删除)。", + "调用方迁移:原依赖 detail.rows 的调用方需改调 stock.check.result(返回 { check, rows, total } 聚合行,含商品行已盘聚合、records、locations 与库位行 stocks)/ stock.check.recordList(作业记录)/ stock.check.workData(三视图作业数据)。", + "查询类方法,不记录操作日志(免日志清单:list/detail/result/recordList/export/exportTaskProgress)。", + "兼容性影响(破坏性变更):响应 data 由 { check, rows, total } 变更为 { check },rows/total 字段被移除,前端取值需同步调整。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "静态标记返回(本次,0.3.310):wms_stock_check 新增 is_static 字段,detail 的 check 对象(_formatCheckRow 口径)返回该字段(0=普通盘点 / 1=静态盘点)。", + "静态标记口径(本次,0.3.311):detail 的 check.is_static 对库位盘点任务恒为 0,商品盘点任务按创建来源/入参取值。" + ] + }, + { + "method": "stock.check.result", + "description": "拉取盘点明细结果(盘点前/盘点后后台查看明细专用,不再作为盘点作业数据提供):入参 id(盘点任务ID);返回 { check, rows, total };无作业记录(如待提交/盘点前)时 rows 直接返回 wms_stock_check_detail 明细范围行(原始行,不聚合);有作业记录时商品范围按商品聚合(一个商品一行,多个库位明细行合并):行含商品快照 + system_quantity(账面快照合计=各库位明细行 system_quantity 之和,创建明细时落库=盘点时做快照)+ 已盘聚合(checked_quantity=作业记录数量合计、diff_quantity=实盘-账面快照合计、is_diff、status=checked|unchecked、location_codes、checkers、last_checked_at)+ records(该商品在 wms_stock_check_record 的全部作业记录,每条含 barcode/item_name 与 images 图片列表)+ locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }],system_quantity 为该库位账面快照(盘点时做快照)、quantity 为该库位实盘合计(未盘库位为 0),按明细 id 升序;仅作业记录存在而快照不存在的库位追加在末尾且 system_quantity=0)+ unknown_items(未知商品按条码聚合 [{ barcode, item_name, checked_quantity }],无账面、差异=实盘-0=盘盈);库位行(scope_type=location)含 is_empty(是否空库位标记)+ checked_quantity(行级合计=行内商品实盘合计)、diff_quantity(行内各商品差异代数和)、is_diff、status + records/locations + stocks(按商品聚合 [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],按 stock_id 升序,账面 system_quantity 查 wms_storage(space_id+stock_id SUM(available_quantity)=可用数量),location_id 为空时账面按 0)+ unknown_items(口径同商品范围);主表计数 check.total_items/checked_items/diff_items 按聚合行口径同步输出(商品范围按商品计数);每条作业记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、status=checked(视为已盘点),账面有库存时 diff_quantity 为负数(盘亏,差异=0-库位账面库存总量)、is_diff=1;无作业记录时 rows 直接返回明细范围行(原始行,见下)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "check", + "type": "object", + "required": true, + "description": "盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at;start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间))" + }, + { + "name": "rows", + "type": "array", + "required": true, + "description": "明细结果行列表:商品范围按商品聚合(一个商品一行,多个库位明细行合并)——行含范围行字段(合并后行级 location_id/location_code 为 null)+ system_quantity(账面快照合计=各库位明细行 system_quantity 之和,创建明细时落库=盘点时做快照)+ 已盘聚合字段(checked_quantity 已盘数量=作业记录 quantity 合计,无记录为 null;diff_quantity 差异数量=已盘-账面快照合计,无记录为 null;is_diff 是否有差异 0|1;status 盘点状态 checked|unchecked;location_codes 库位编码数组去重;checkers 盘点人数组去重;last_checked_at 最近上报时间,无记录为 null)+ records(该商品全部盘点作业记录,每条含 id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/barcode/item_name/created_at/updated_at + images 图片列表 [{ id: file_id, url }],FileReference business_type=stock_check_record)+ locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }],system_quantity 为该库位账面快照(创建明细时落库)、quantity 为该库位实盘合计(未盘库位为 0),按明细 id 升序;仅作业记录存在而快照不存在的库位追加在末尾且 system_quantity=0)+ unknown_items(未知商品聚合数组 [{ barcode, item_name, checked_quantity }],按条码升序;记录 stock_id 为空的未知商品按条码归组,无账面、差异=实盘-0=盘盈,已计入行级 checked_quantity/diff_quantity/is_diff;无未知商品为空数组);库位行(scope_type=location)含范围行字段 + is_empty(是否空库位标记:该明细存在空标记记录(is_empty=1)时为 true)+ stocks(按商品聚合数组 [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],按 stock_id 升序,仅含存在作业记录的已知商品;system_quantity 为 wms_storage 账面(space_id+stock_id SUM(available_quantity)=可用数量),location_id 为空时按 0)+ checked_quantity(行级合计=行内商品实盘合计,无记录为 null)/ diff_quantity(行内各商品差异代数和,无记录为 null)/ is_diff / status + location_codes / checkers / last_checked_at + records / locations + unknown_items(口径同商品行);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、diff_quantity=0-库位账面库存总量(账面有库存时为负数=盘亏、账面为 0 时为 0)、is_diff=账面有库存时为 1、status=checked(视为已盘点);无作业记录(盘点前/待提交等)时 rows 直接返回 wms_stock_check_detail 明细范围行(原始行,含 scope_type/stock_id/location_id/location_code/system_quantity 账面快照等明细表字段,不聚合、无 checked/diff 字段)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "明细总条数" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "权限口径:随 ALL_METHOD_NAMES(16 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog(list/detail/result/recordList/export/exportTaskProgress)。", + "商品范围聚合口径:按商品合并(一个商品一行,多个库位明细行合并)——checked_quantity=该商品全部作业记录 quantity 合计;diff_quantity=已盘-账面快照合计(各库位明细行 system_quantity 之和,创建明细时落库=盘点时做快照);locations 各库位同时输出 system_quantity(该库位账面快照)与 quantity(该库位实盘合计,未盘库位为 0);is_diff=存在记录且差异非 0 时为 1;status=存在记录 checked,否则 unchecked。主表计数 check.total_items/checked_items/diff_items 按聚合行口径同步输出(total_items=行数、checked_items=已盘行数、diff_items=差异行数),历史任务主表残留的按库位拆行计数在响应中以聚合行为准。", + "库位行账面口径:wms_storage 按 (space_id, stock_id) SUM(available_quantity)(=可用数量,不含锁定待出库)现算(与 finish/export 汇总口径一致),location_id 为空时账面按 0;库位行 stocks 仅含存在作业记录的已知商品(stock_id 有值,无记录时为空数组),商品快照 item_code/item_name 从 wms_stock_warehouse 补齐。", + "无作业记录口径(本次变更):rows 直接返回 wms_stock_check_detail 明细范围行(原始行,不聚合),total=明细行数——盘点前/待提交等后台查看盘点范围明细用(本接口仅展示盘点前/盘点后明细,不再作为盘点作业数据提供;盘点作业数据见 stock.check.workData)。代码依据:app/service/systems/stock_check.js#result(records.length===0 分支直接返回明细行)。", + "未知商品聚合口径:stock_id 为空的作业记录按 barcode 维度归组输出行级 unknown_items [{ barcode, item_name, checked_quantity }](按条码升序,item_name 为上报名称快照);未知商品无账面,差异=实盘-0=盘盈,已计入行级 checked_quantity/diff_quantity/is_diff;stocks 保持只输出已知商品(stock_id 有值)。代码依据:app/service/systems/stock_check.js#_formatMergedGoodsAggregationRow(商品范围合并行)/#_formatDetailAggregationRow(库位行)。", + "图片挂载口径(图片独立维护,仿收货 receivingItem):_attachRecordImages 查询 wms_file_reference(business_type=stock_check_record,business_id in 记录ID)并关联 wms_file 取 file_url,每条作业记录挂载 images [{ id: file_id, url }],无图片返回空数组;上传走通用上传接口(uploadSuccessNotify 传 businessType=stock_check_record + businessId=作业记录ID,建 FileReference)。代码依据:app/service/systems/stock_check.js#result/#_attachRecordImages。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "空库位标记口径(本次新增):库位行存在空标记记录(is_empty=1)时 is_empty=true——stocks 为空数组、unknown_items 为空数组、checked_quantity=0、status=checked(视为已盘点);账面口径:按 location_id 查 wms_storage SUM(available_quantity)(该库位全部库存账面总量=可用数量,location_id 为空时按 0),账面>0 时 diff_quantity=-账面总量(盘亏)、is_diff=1,账面=0 时 diff_quantity=0、is_diff=0。代码依据:app/service/systems/stock_check.js#_formatDetailAggregationRow。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.report:params 新增 is_empty 入参、errors 400 补「仅库位盘点明细支持空库位标记」、description/response/notes 补充空库位语义与互斥及汇总口径;stock.check.workData:description/response.rows 的 location 行新增 is_empty 字段说明;stock.check.result:description/response.rows 库位行新增 is_empty 与空标记盘亏口径;stock.check.recordList:response.rows 记录全字段说明新增 is_empty;stock.check.export:description/notes 补 Sheet2 空库位行输出口径);根版本 0.3.233 → 0.3.234、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "method": "stock.check.workData", + "description": "拉取盘点作业数据(视图由任务范围与 is_goods 入参驱动,view 入参已废弃忽略):入参 id(盘点任务ID)+ is_goods(可选,商品任务是否按商品视图返回——true=goods 视图;缺省 false=聚合库位 space 视图;兼容 isGoods 驼峰写法;库位任务无视该参数)+ keyword(可选,关键字:仅库位任务 location 视图生效——按行 location_code/location_name 模糊匹配(不区分大小写)过滤任务明细后再分页;非库位任务忽略;空/纯空白视为未传)+ only_abnormal(可选,只看未盘和差异:过滤在 keyword 之后、分页切片之前完成,三视图均生效——location 视图仅保留 status=unchecked 或含未知商品记录(has_unknown=true)的行;goods 视图仅保留未盘行(locations 均无 record_ids)或明盘差异行(is_diff=1,盲盘无数量字段仅按未盘过滤);space 视图按行内 goods 子项过滤(status=unchecked 或明盘 checked_quantity≠system_quantity),过滤后 goods 为空的行整体移除;兼容 onlyAbnormal 驼峰写法);返回 { view, rows, total, page, pageSize }(view=服务端实际解析出的视图类型 location/goods/space,供调用方判断 rows 行结构;不返回任务主表信息 check——任务信息请调用 stock.check.detail),rows 结构随解析视图不同(先构建全量行——location 视图且 keyword 非空时先按 location_code/location_name 过滤,only_abnormal=true 时再按未盘/差异过滤,最后按页切片,rows 为当前页行)、total=全部行数(未分页口径;keyword/only_abnormal 过滤后 total 为过滤后行数)、page=当前页码(默认 1)、pageSize=每页数量(默认 20,上限 200),任务无对应范围行时 rows 返回空数组。分页:入参 data.pagination({ page, pageSize }),未传或非法时默认 page=1、pageSize=20(上限 200),分页口径与 stock.check.list 一致。视图解析:任务范围为库位(type=location)一律按 location 视图;任务范围为商品(type=goods/store)默认 space 视图、仅 is_goods=true 时 goods 视图。location(库位结构):以任务库位范围行(scope_type=location)为列表(按明细 id 升序;行含 detail_id/location_id 与同义字段 space_id/location_code/location_name/status/has_unknown/is_empty/checked_at/checkers/goods,space_id 可直接回传 stock.check.report),行内挂该库位的盘点作业记录 goods 子列表(已知商品与未知商品记录均入内,未知商品 stock_id=null、item_code 用条码兜底;每项含 record_id 作业记录 ID(单条记录直接定位,可调 recordDelete/recheckClearLocation 移除)与 images 作业记录照片——FileReference business_type=stock_check_record 经 _attachRecordImages 挂载,与 result/recordList 口径一致,无照片为空数组)+ has_unknown 标记(该库位是否含未知商品记录)+ is_empty 标记(该库位是否存在空库位标记记录:空标记记录不计入 goods 子列表,存在空标记后该行 status=checked 视为已盘点);goods(商品结构):按商品(stock_id)汇总,一个商品一行——同商品的多个库位明细行(scope_type=goods,按「商品+库位」拆行,唯一键 check_id+stock_id+location_id)合并输出(按商品首个明细 id 升序,行级不返回 detail_id,逐库位明细/汇总请调用 stock.check.workDataDetail 传 id + stock_id),行内 locations 为商品所在全部库位列表(商品库存库位取自 wms_storage——启用未删除存储 DISTINCT space_id 按拣货路径排序,无库存但已有作业记录的库位追加在末尾;每项含 location_id(库位ID wms_location_space.id,取分区有效的库位行,供调用方直接回传 stock.check.report 的 location_id)、record_ids 该库位该商品全部作业记录 ID(按记录 id 升序)与 images 该库位该商品全部作业照片(扁平去重),供前端编辑/移除记录;未盘库位 checked_at=null、record_ids/images 为空数组;每项另含 detail_id 该库位盘点明细ID 与明盘 snapshot_quantity 该库位账面快照),明盘(mode=open)返回账面快照合计(该商品各库位明细行 system_quantity 之和)/已盘合计/差异(作业记录跨该商品全部明细按库位合并),每库位含 system_quantity(该库位账面数量=可用数量,wms_storage SUM(available_quantity),无库存记录库位为 0)、locked_quantity(该库位锁定数量,wms_storage SUM(locked_quantity))与 quantity(该库位盘点数量,未盘库位为 0),盲盘(mode=blind)不返回任何数量字段(行级 images 仍为商品主图);space(聚合库位列表):库位集合=当前库存库位 ∪ 作业记录库位(当前库存库位:wms_storage 中任务 stock_id 集合的启用未删除存储 DISTINCT space_id;作业记录库位:wms_stock_check_record 的 location_id 已回填直接用(上报库位与明细库位编码一致时归并到明细固化 location_id;指向无头库位(分区不存在/已删除)时归并到同编码有效库位并优先该商品有库存的库位,保证同编码只出一行、自定义名称/编码取有效库位行)、未回填的按 location_code 匹配 wms_location_space.space_code 补查,与库存库位去重后取并集),仅按库位拣货顺序排序(pick_sequence 升序,pick_priority 与库位 id 不参与,同值保持库位查询顺序),行含 id/space_code/custom_barcode/custom_name/goods(id 为库位ID wms_location_space.id,并额外输出同义字段 location_id,便于与 location/goods 视图、recordList、result 统一命名并直接回传 stock.check.report),行内 goods 为该库位下的任务商品(每项含 record_ids 该商品在该库位全部作业记录 ID(按记录 id 升序)与 images 该商品在该库位的作业照片聚合(扁平去重,不再输出商品主图),供前端编辑/移除记录),明盘含库位账面(可用数量)/锁定数量/已盘数量、盲盘不含数量;静态盘点(is_static=1)时 goods 子项另含 picking_completed(1=该商品已完成拣货/0=未完成,口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0,按商品维度判定,同一商品各库位行取值一致,明盘盲盘均返回);盘点前库存已出空但已有盘点作业记录的库位也能展示(该库位商品行账面 system_quantity 按 0、locked_quantity 按 0、checked_quantity 按该库位实盘合计)。状态限制:仅任务状态为 approved(审核完成)或 checking(盘点作业中)时可拉取盘点作业数据,其他状态(created 已创建/submitted 待审核/rejected 已驳回/completed 已完成/cancelled 已取消)返回 400「当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取」。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID(wms_stock_check.id)" + }, + { + "name": "is_goods", + "type": "boolean", + "required": false, + "source": "body", + "description": "商品任务是否按商品视图返回(true=goods);缺省 false=聚合库位视图 space;库位任务无视该参数(兼容 isGoods 驼峰写法)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键字(可选,向后兼容新增):仅库位任务(服务端解析视图为 location,即任务类型 location)生效——按行 location_code(优先明细快照,缺失回退库位表 space_code)与 location_name(custom_name 兜底 space_code)做模糊匹配(contains、不区分大小写)过滤任务明细后再分页返回;非库位任务(goods/store,space/goods 视图)忽略该参数;keyword 为空/纯空白视为未传不过滤" + }, + { + "name": "only_abnormal", + "type": "boolean", + "required": false, + "source": "body", + "description": "只看未盘和差异(可选,向后兼容新增,兼容 onlyAbnormal 驼峰写法):过滤在 keyword 之后、分页切片之前完成,三视图均生效——location 视图仅保留 status=unchecked 或含未知商品记录(has_unknown=true)的行(空库位标记 is_empty 后 status=checked 视为已盘点、不保留);goods 视图仅保留未盘行(locations 均无 record_ids,即无任何作业记录)或明盘差异行(is_diff=1,盲盘无数量字段仅按未盘过滤);space 视图按行内 goods 子项过滤(status=unchecked 或明盘 checked_quantity≠system_quantity),过滤后 goods 为空的行整体移除;未传/非 true(false/0/空串/缺省)不过滤;total 为过滤后行数" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize }(可选),默认 page=1、pageSize=20,pageSize 上限 200,分页口径与 stock.check.list 一致" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "view", + "type": "string", + "required": true, + "description": "服务端实际解析出的视图类型(location=库位结构 / goods=商品结构 / space=聚合库位结构),由任务范围(type=location 一律 location)与 is_goods 入参共同决定,供调用方判断 rows 行结构" + }, + { + "name": "rows", + "type": "array", + "required": true, + "description": "盘点作业数据行列表(当前页行:先构建全量行——location 视图且 keyword 非空时先按行 location_code/location_name 模糊匹配(不区分大小写)过滤,only_abnormal=true 时再按未盘/差异过滤(location 按行 status=unchecked/has_unknown;goods 按行未盘或明盘 is_diff=1;space 按行内 goods 子项过滤后空行移除),最后按页切片;total 为全部行数——未分页口径;location 视图 + keyword 或 only_abnormal=true 时 rows 为过滤后的行、total 同步过滤口径;非库位任务(goods/store,space/goods 视图)忽略 keyword),结构随解析视图不同——location 视图行:detail_id 明细ID / location_id 库位ID / location_code 库位编码(优先明细快照,缺失回退库位表 space_code)/ location_name 库位名称(custom_name 兜底 space_code)/ status 盘点状态(checked=存在作业记录,unchecked=无)/ has_unknown 是否含未知商品记录(该库位存在 stock_id 为空的作业记录时为 true,未知商品同样计入 goods) / is_empty 是否空库位标记(该库位存在空库位标记记录(is_empty=1)时为 true;空标记记录不计入 goods 子列表;存在空标记后该行 status=checked 视为已盘点) / checked_at 该库位最近上报时间(无记录为 null)/ checkers 盘点人去重数组 + goods 作业记录子列表(已知商品与未知商品记录均入内,字段统一 record_id 作业记录ID(单条记录直接定位,可调 recordDelete/recheckClearLocation 移除)/stock_id/item_code/item_name/barcode/images 作业记录照片(已知商品与未知商品均经 _attachRecordImages 挂载 FileReference business_type=stock_check_record,与 result/recordList 口径一致,不再输出商品主图,无照片为空数组)/store_id/store_name/quantity 实盘数量/checked_at/checker_name——已知商品(stock_id 有值)商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名经 _resolveStoreNameMap 解析;未知商品(stock_id=null)item_code 用条码兜底、item_name 用名称快照兜底条码、store_id/store_name 为 null);goods 视图行(按商品汇总,一个商品一行,行级不返回 detail_id——逐库位明细/汇总请调 stock.check.workDataDetail 传 id + stock_id;账面取值按任务静态标记(is_static)区分:is_static=1(静态盘点)取明细账面快照 system_quantity(盘点基准冻结,不受盘点期间出入库影响);is_static=0(普通盘点)取当前 wms_storage 账面 SUM(available_quantity);两者都会额外输出 storage_quantity(当前 storage 账面)与 snapshot_quantity(明细快照)供对照,system_quantity 始终为参与差异计算的账面,行/商品额外输出 is_static 与 book_source(snapshot|storage),locations 各项与行级均按此口径),静态盘点(is_static=1)goods 视图行额外输出 picking_completed(1=该商品已完成拣货/0=未完成,判定口径=wms_storage 中该商品在仓库内 SUM(locked_quantity) 是否为 0:锁定量>0 表示仍有已分配储位、尚未拣出的在途出库)与明盘下的 locked_quantity(该商品仓库内锁定量合计;盲盘不输出该数值,仅输出 picking_completed):stock_id/item_code/item_name/spec/store_id/store_name/barcode/images(行级 images 仍为商品主图 image_url)+ locations 商品所在全部库位列表(商品库存库位取自 wms_storage——启用未删除存储 DISTINCT space_id 按拣货路径排序;无库存但已有作业记录的库位按首条记录 id 升序追加在末尾;空库位归 location_code=null 组排在最后。每项 [{ location_id 库位ID 与同义字段 space_id(wms_location_space.id,可直接回传 stock.check.report), location_code 库位编码, detail_id 该库位盘点明细ID(无明细快照的库位为 null), checked_at, checker_name, record_ids 该库位该商品全部作业记录 ID(按记录 id 升序,供前端编辑/移除记录), images 该库位该商品全部记录的作业照片(扁平去重,无照片为空数组) }],未盘库位 checked_at/checker_name 为 null、record_ids/images 为空数组),明盘(mode=open)另含 system_quantity 账面合计(按任务静态标记取快照合计或当前 storage 合计)/checked_quantity 已盘合计(locations 各库位 quantity 合计=该商品全部明细的作业记录合计,未盘行恒 0)/diff_quantity 差异=已盘-账面(仅存在作业记录的行计算,未盘行恒 0)/is_diff 是否差异 0|1(未盘行恒 0),locations 各项另含 system_quantity 该库位账面数量(wms_storage 该库位 SUM(available_quantity),无库存记录库位 0)、locked_quantity 该库位锁定数量(wms_storage 该库位 SUM(locked_quantity))、snapshot_quantity 该库位账面快照、storage_quantity 该库位当前 storage 账面与 quantity 该库位盘点数量(实盘合计,未盘库位 0),其中 system_quantity 按任务静态标记取快照或 storage,盲盘(mode=blind)不返回任何数量字段(locations 仅 location_id/space_id/location_code/detail_id/checked_at/checker_name/record_ids/images);space 视图行:id(库位ID wms_location_space.id)/space_code(库位编码)/custom_barcode(库位自定义条码,空为 null)/custom_name(库位自定义名称,空为 null 不兜底 space_code;库位字段对齐库位查询惯例 index.searchSpace)+ goods 该库位下的任务商品子列表(detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images 该商品在该库位的作业照片聚合(扁平去重,不再输出商品主图,无照片为空数组)/record_ids 该商品在该库位的全部作业记录 ID(按记录 id 升序,供前端编辑/移除记录) + status 已盘状态(该 detail_id+location_code 存在作业记录即 checked,否则 unchecked)),明盘 goods 各项另含 system_quantity(wms_storage space+stock SUM(available_quantity) 账面=可用数量,该库位无库存记录时按 0)/locked_quantity(该库位锁定数量,SUM(locked_quantity))/checked_quantity(该商品在该库位的实盘合计),盲盘不含数量;静态盘点(is_static=1)时 goods 子项另含 picking_completed(1=该商品已完成拣货/0=未完成,口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0,按商品维度判定,同一商品各库位行取值一致,明盘盲盘均返回);库位集合=当前库存库位 ∪ 作业记录库位(盘点前库存已出空但已有盘点作业记录的库位也能展示)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "行总数(全部行数——未分页口径,任务无对应范围行时为 0;分页时 rows 为当前页行、total 保持全部行数不变;location 视图 + keyword 非空或 only_abnormal=true 时 total 为过滤后的行数)" + }, + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码(未传或非法时默认 1,分页口径与 stock.check.list 一致)" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页数量(默认 20,上限 200,分页口径与 stock.check.list 一致)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空" + }, + { + "code": 400, + "message": "当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取" + }, + { + "code": 400, + "message": "盘点任务不存在" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#workData(warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递;const { id, is_goods: isGoodsSnake, isGoods: isGoodsCamel, pagination } = data || {},isGoods=is_goods 未定义时回退 isGoods(兼容 isGoods 驼峰写法);不再读取、不再校验 view,透传 { warehouseId, id, isGoods, pagination })+ app/service/systems/stock_check.js#workData(id 非正整数抛 400『盘点任务ID不能为空』;任务不存在(按 id+warehouse_id 查 wms_stock_check)抛 400『盘点任务不存在』;状态守卫:任务状态非 REPORT_ALLOWED_STATUSES(approved/checking)时抛 400『当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』;视图解析:normalizedType=String(check.type||'').trim(),type=location 一律 location 视图(无视 view/is_goods),否则 goodsViewRequested=isGoods===true||'true'||1 时 goods 视图、其余默认 space 视图;按解析视图分派 _buildLocationWorkRows/_buildGoodsWorkRows/_buildSpaceWorkRows,统一返回 { check: _formatCheckRow 口径, rows, total: rows.length, page, pageSize })。本次代码已改(view 入参废弃、is_goods 驱动视图)并测试通过 197/197、ESLint 0 错误。", + "三视图口径(由任务范围 + is_goods 解析后分派):location=库位结构(库位范围任务一律该视图),以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位盘点作业记录 goods 子列表(已知商品与未知商品记录均入内:已知商品 stock_id 有值,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名 _resolveStoreNameMap 解析;未知商品 stock_id=null,item_code 用条码兜底、item_name 用名称快照兜底条码、store_id/store_name 为 null;已知/未知商品的 images 均为作业记录照片(经 _attachRecordImages 挂载 FileReference business_type=stock_check_record,已知商品不再输出商品主图 image_url)),has_unknown 标记该库位是否含未知商品记录;goods=商品结构(商品范围任务且 is_goods=true 时该视图),按商品(stock_id)汇总,一个商品一行——同商品的多个库位明细行(scope_type=goods)合并输出(按商品首个明细 id 升序,行级不返回 detail_id),行内 locations 为商品所在全部库位列表(商品库存库位取自 wms_storage 启用未删除存储且库位有效(未删除且所属 zone 存在未删除,排除无头库位)DISTINCT space_id 按拣货路径排序,无库存但已有作业记录的库位按首条记录 id 升序追加在末尾,空库位归 location_code=null 组排在最后;明盘每库位含 system_quantity 该库位账面数量与 quantity 该库位盘点数量(未盘库位 0),盲盘仅 location_code/checked_at/checker_name/record_ids/images);space=聚合库位列表(商品范围任务默认该视图),库位集合=当前库存库位 ∪ 作业记录库位——当前库存库位:wms_storage(warehouse_id + stock_id 在集合 + is_enabled=1 未删除且库位有效(排除无头库位))DISTINCT space_id;作业记录库位:wms_stock_check_record 的 location_id 已回填直接用、未回填的按 location_code 匹配 wms_location_space.space_code 补查,与库存库位去重后并集;行内 goods 为该库位下的任务商品;盘点前库存已出空但已有盘点作业记录的库位也能展示(该库位商品行账面 system_quantity 按 0、checked_quantity 按该库位实盘合计)。", + "明盘/盲盘数量控制:明盘(mode=open)goods 视图行返回 system_quantity(该商品各库位明细行账面快照合计)/checked_quantity(已盘合计=locations.quantity 合计)/diff_quantity(已盘-账面,仅存在作业记录的行计算)/is_diff(差异非 0 为 1),locations 各项含 system_quantity(该库位账面数量=可用数量,wms_storage 该库位 SUM(available_quantity),无库存记录库位为 0)、locked_quantity(该库位锁定数量,wms_storage 该库位 SUM(locked_quantity))与 quantity(该库位盘点数量=实盘合计,未盘库位为 0);space 视图 goods 各项含 system_quantity(wms_storage space+stock SUM(available_quantity) 账面,该库位无库存记录时按 0)/locked_quantity(wms_storage space+stock SUM(locked_quantity))/checked_quantity(该商品在该库位的实盘合计);盲盘(mode=blind)不返回任何数量字段(goods 视图 locations 仅 location_code/checked_at/checker_name/record_ids/images,space 视图 goods 仅商品信息+images/record_ids/status);goods 视图 locations 为商品所在全部库位列表(含未盘库位,无作业记录时各项为空信息),无作业记录的行明盘已盘合计恒 0、差异/is_diff 恒 0(避免未盘行误显盘亏差异)。", + "排序口径:space 视图库位仅按库位拣货顺序排序——pick_sequence 升序(pick_priority 与库位 id 均不参与,同值保持库位查询顺序);space 行内 goods 按 stock_id 升序;location 视图行按明细 id 升序、goods 视图行按商品首个明细 id 升序;goods 视图 locations 按首条记录 id 升序。", + "权限口径:随 ALL_METHOD_NAMES(22 个:create/list/addDetail/addLocationDetail/detailDelete/detail/result/workData/report/markEmpty/recordList/recordDelete/recheckClearLocation/finish/submit/cancel/audit/batchDelete/export/exportTaskProgress/patternList/patternCreate)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog(list/detail/result/workData/recordList/export/exportTaskProgress/patternList),不记录操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workData 一条(位于 stock.check.result 之后);根版本 0.3.224 → 0.3.225、updatedAt 2026-10-01 → 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组由 19 条增至 20 条)。", + "状态限制口径:仅任务状态为 approved(审核完成)或 checking(盘点作业中)可拉取盘点作业数据;其他状态(created 已创建/submitted 待审核/rejected 已驳回/completed 已完成/cancelled 已取消)返回 400,message 为『当前状态({状态中文标签,无标签时回退状态值})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』,状态标签取 STOCK_CHECK_STATUS_LABELS。状态守卫复用 REPORT_ALLOWED_STATUSES 常量,与 report(盘点作业上报)及 finish(完成盘点)一致。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(errors 的 400 新增状态限制文案并拆分为独立条目、description/notes 补充状态限制口径;headers/params/response/isNeedAuth/isNeedLogin 不变);根版本 0.3.225 → 0.3.226、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。", + "库位字段口径(本次对齐):space 视图行字段对齐库位查询惯例(index.searchSpace,app/service/systems/space.js#_searchByKeyword attributes)——id=wms_location_space.id、space_code=库位编码、custom_barcode=库位自定义条码(空为 null)、custom_name=库位自定义名称(空为 null,不再兜底 space_code);goods 子列表字段不变(detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/status,明盘另含 system_quantity/checked_quantity);仅 space 视图行字段变化,location/goods 视图行字段不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步 space 视图库位聚合来源扩展与行字段规范对齐;headers/params/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.227 → 0.3.228、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production + --env production)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。", + "分页口径(本次新增):三视图先构建全量行(_buildLocationWorkRows/_buildGoodsWorkRows/_buildSpaceWorkRows)再按页切片(slice(offset, offset+pageSize));rows 为当前页行、total 为全部行数(未分页口径)、响应新增 page(当前页码)与 pageSize(每页数量);page 默认 1、pageSize 默认 20、上限 200(非法值回退默认)。代码依据:app/service/systems/stock_check.js#workData。", + "分页入参口径(与 stock.check.list 一致):仅入参 data.pagination.{page,pageSize},不再兼容 page_size 蛇形写法、不再支持顶层 data.page / data.pageSize / data.page_size;方法层(app/service/systemMethods/stock/check.js#workData)直接透传 pagination 对象给系统层;系统层(app/service/systems/stock_check.js#workData)page=Math.max(1, Number(pagination.page)||1) 默认 1、pageSize=Math.min(200, Math.max(1, Number(pagination.pageSize)||20)) 默认 20 上限 200、非法回退默认;先构建全量行再按页切片,返回 { check, rows, total, page, pageSize }。本次代码已改并测试通过 197/197、ESLint 0 错误。", + "向后兼容:旧调用方不传分页参数时默认 page=1、pageSize=20,rows 行为与旧版一致(全量行数不超过 20 时)、total 不变;仅响应新增 page/pageSize 两个字段,其余字段口径不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 pagination、response 新增 page/pageSize 并同步 rows/total 口径、description/notes 补充分页口径;headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.228 → 0.3.229、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production + --env production)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。", + "分页口径修正(本次):上一轮文档曾描述「支持顶层 data.page / data.pageSize / data.page_size(顶层优先)并兼容 page_size 蛇形写法」,实际代码已按用户要求改为与同模块 stock.check.list 完全一致的常规口径——仅 pagination.{page,pageSize};本次同步文档删除上述兼容描述,params.pagination/description/response.page/pageSize/notes 统一为常规口径。代码依据:app/service/systemMethods/stock/check.js#workData(const { id, is_goods: isGoodsSnake, isGoods: isGoodsCamel, pagination } = data || {},直接透传)+ app/service/systems/stock_check.js#workData(pagination 默认 {},page/pageSize 归一化后对全量行 slice)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params.pagination 描述、description、response.page/pageSize 描述、notes 同步常规分页口径,删除顶层参数兼容与 page_size 兼容表述;response.rows/total、headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.229 → 0.3.230、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(显式 WMS_DB_TARGET=production)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。", + "视图驱动规则(本次改造):view 入参废弃——方法层不再读取、不再校验 view,传任何值都被忽略、不报错;视图改由任务范围 + is_goods 驱动——任务范围为库位(type=location)一律按库位视图(location)返回,无视 view/is_goods;任务范围为商品(type=goods/store)默认聚合库位视图(space),仅 is_goods=true 时按商品视图(goods)返回;is_goods 其他值(false/0/缺省等)一律按默认 space。is_goods 兼容 isGoods 驼峰写法(is_goods 未定义时回退 isGoods)。分页能力不变(pagination.{page,pageSize},与 stock.check.list 口径一致,默认 20 上限 200)。影响面:前端如需商品视图须改传 is_goods=true;view 传值不再生效。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 删除 view、新增 is_goods(boolean,body,可选,兼容 isGoods 驼峰写法);description 同步「库位任务一律 location、商品任务默认 space、is_goods=true 才 goods;view 入参已废弃忽略」;errors 删除「视图类型非法(仅支持 location/goods/space)」条目;response 结构不变(check/rows/total/page/pageSize);notes 同步代码依据与视图驱动规则);根版本 0.3.230 → 0.3.231、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "location 视图行结构改造(本次):_buildLocationWorkRows 删除 unknown 未知商品子列表——未知商品记录(stock_id 为空)不再单独输出,与已知商品统一并入 goods 子列表、输出字段对齐已知商品(record_id/stock_id=null/item_code 用条码兜底/item_name 用名称快照兜底条码/barcode/images/store_id=null/store_name=null/quantity/checked_at/checker_name);行级 has_unknown 标记保留(该库位是否含未知商品记录)。代码依据:app/service/systems/stock_check.js#_buildLocationWorkRows。影响面:前端无需再处理 unknown 数组,直接遍历 goods、按 stock_id 是否为 null 区分未知商品。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步 location 视图行结构:删除 unknown 子列表字段说明、goods 改为「已知商品与未知商品记录均入内,未知商品 stock_id=null、item_code 用条码兜底、store_id/store_name 为 null」、has_unknown 保留说明;headers/params/errors/isNeedAuth/isNeedLogin 与 goods/space 视图及分页描述不变);根版本 0.3.232 → 0.3.233、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。", + "空库位标记口径(本次新增):location 视图行新增 is_empty 字段——_buildLocationWorkRows 遍历该库位作业记录,存在空标记记录(is_empty=1)时 isEmptyLocation=true 且该记录不计入 goods 子列表(不输出为商品记录行);行级 status 仍按存在作业记录口径判断(空标记记录同样是记录),因此空标记后 status=checked 视为已盘点;checked_at/checkers 口径不变。代码依据:app/service/systems/stock_check.js#_buildLocationWorkRows。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.report:params 新增 is_empty 入参、errors 400 补「仅库位盘点明细支持空库位标记」、description/response/notes 补充空库位语义与互斥及汇总口径;stock.check.workData:description/response.rows 的 location 行新增 is_empty 字段说明;stock.check.result:description/response.rows 库位行新增 is_empty 与空标记盘亏口径;stock.check.recordList:response.rows 记录全字段说明新增 is_empty;stock.check.export:description/notes 补 Sheet2 空库位行输出口径);根版本 0.3.233 → 0.3.234、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。", + "作业照片与 record_ids 口径(本次新增):三视图统一挂载作业记录照片(FileReference business_type=stock_check_record,_attachRecordImages 挂载,与 result/recordList 口径一致)——location 视图 goods 子项 images 为作业记录照片(已知商品由商品主图 stockDetail.image_url 改为作业记录照片,未知商品维持记录照片,无照片为空数组),record_id 为单条作业记录 ID(可直接定位,供 recordDelete/recheckClearLocation 移除);goods 视图行级 images 仍为商品主图,locations 聚合项新增 images(该库位该商品全部记录的作业照片扁平去重,无照片为空数组)与 record_ids(该库位该商品全部作业记录 ID,按记录 id 升序);space 视图 goods 子项 images 由商品主图改为该商品在该库位的作业照片聚合(扁平去重,无照片为空数组),并新增 record_ids(该商品在该库位全部作业记录 ID,按记录 id 升序)。record_ids 供前端编辑/移除记录(stock.check.recordDelete 批量删除 / stock.check.recheckClearLocation 重盘清除库位);行级/未盘项无记录时 images/record_ids 为空数组。代码依据:app/service/systems/stock_check.js#_buildLocationWorkRows/#_buildGoodsWorkRows/#_buildSpaceWorkRows。本次代码已改并测试通过 214/214、ESLint 0 错误。", + "影响面:location 视图已知商品子项 images 由商品主图变为作业记录照片;goods 视图 locations 项新增 record_ids/images;space 视图 goods 子项 images 由商品主图变为作业照片聚合并新增 record_ids;goods 视图行级 images(商品主图)不变;其余字段(check/rows/total/page/pageSize、明盘/盲盘数量控制、状态限制)不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步三视图作业照片挂载与 record_ids 输出口径);headers/params/errors/isNeedAuth/isNeedLogin 与分页/状态限制描述不变;根版本 0.3.238 → 0.3.239、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。", + "不返回 check、改返回 view 口径(本次改造):workData 响应由 { check, rows, total, page, pageSize } 调整为 { view, rows, total, page, pageSize }——移除任务主表信息 check(任务信息请调用 stock.check.detail),新增 view(服务端实际解析出的视图类型 location/goods/space,供调用方判断 rows 行结构)。check 仍由服务端内部查询(视图解析 normalizedType=check.type、盲盘/明盘 check.mode、状态守卫),仅不再对外返回。代码依据:app/service/systems/stock_check.js#workData(resolvedView 取自 normalizedType/is_goods 解析结果)。", + "view 取值口径:任务范围为库位(type=location)一律 location(无视 is_goods/view 入参);任务范围为商品(type=goods/store)默认 space,仅 is_goods=true(含 true/\"true\"/1)时为 goods。与视图解析规则一一对应。", + "兼容性影响(破坏性变更):响应 data 移除 check 字段;新增 view 字段;rows/total/page/pageSize 与三视图行结构、明盘盲盘数量控制、状态限制均不变;前端如需任务主表信息改调 stock.check.detail。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description 同步 view/移除 check、response 的 data.children 以 view 替换 check、notes 补充 view 口径与兼容性说明;headers/params/errors/isNeedAuth/isNeedLogin 与 rows 三视图结构不变);根版本 0.3.241 → 0.3.242、updatedAt 保持 2026-10-03;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,需另行同步回填开发库与生产库(import 当前 system.json → export 往返校验),保持库与文件一致。", + "keyword 过滤口径(本次新增):keyword(string,可选,向后兼容)仅库位任务(服务端解析视图为 location,即任务类型 location)生效——resolvedView===\"location\" 且 normalizedKeyword=String(keyword||\"\").trim().toLowerCase() 非空时,先按行 location_code/location_name 模糊匹配(contains、不区分大小写)过滤全量任务明细行,再按 pagination 切片;非库位任务(goods/store,space/goods 视图)忽略该参数;keyword 为空/纯空白视为未传不过滤;total=filteredRows.length(过滤后行数),rows 为过滤后当前页行。代码依据:app/service/systemMethods/stock/check.js#workData(透传 keyword)+ app/service/systems/stock_check.js#workData(filteredRows)。本次代码已改并测试通过 214/214、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 keyword(string,可选);description 与 response.rows/total 描述同步 keyword 过滤口径(location 视图 + keyword 时 rows 为过滤后的库位行、total 同步过滤口径;非库位任务忽略);headers/errors/isNeedAuth/isNeedLogin 与响应结构不变);根版本 0.3.243 → 0.3.244、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local)与生产库(WMS_DB_TARGET=production)(import 当前 system.json → export 往返校验),保持库与文件一致。", + "goods 视图 locations 商品库位列表口径(本次改造):_buildGoodsWorkRows 的 locations 由「仅已盘库位(按首条记录 id 升序)」改为「商品所在全部库位列表」——基础库位取自 wms_storage(任务 stock_id 集合 + is_enabled=1 未删除,DISTINCT space_id)经库位表取 space_code 并按拣货路径排序(pick_sequence 升序、pick_priority 降序、库位 id 升序兜底);无库存但已有作业记录的库位按首条记录 id 升序追加在末尾;空库位(location_code 空)组仍排在最后。未盘库位输出空信息(checked_at/checker_name=null、record_ids/images 空数组、明盘 quantity=0);明盘 checked_quantity=locations 各库位 quantity 合计(未盘行恒 0);diff_quantity/is_diff 仅对存在作业记录(detailRecords.length>0)的行计算,未盘行恒 0(避免未盘行误显盘亏差异)。盲盘仍不返回任何数量字段。代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows;回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步 goods 视图 locations 商品所在全部库位列表口径:未盘库位空信息、明盘每库位 quantity(未盘 0)、diff/is_diff 仅已有记录行计算);根版本 0.3.245 → 0.3.246、updatedAt 2026-10-04 → 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组仍为 23 条)。", + "goods 视图 locations 明盘库位数量区分(本次改造):明盘每库位同时输出 system_quantity(该库位账面数量,wms_storage 该库位 SUM(quantity),无库存记录库位为 0)与 quantity(该库位盘点数量=实盘合计,未盘库位为 0)两字段区分开;盲盘仍不返回任何数量字段。Storage 查询改为 attributes 增加 fn('SUM', col('quantity')) 按 stock+space 分组汇总,构建 stockId→spaceCode→账面数量映射;行级 checked_quantity 仍为 locations.quantity 合计,diff/is_diff 计算条件不变。代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows;回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataDetail 两条(description/response.rows/notes 同步 goods 视图明盘库位 system_quantity(账面)+quantity(盘点)双数量字段口径);根版本 0.3.246 → 0.3.247、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 23 条)。", + "库位账面口径改造(本次):盘点作业数据接口的库位账面 system_quantity 由 SUM(quantity) 改为 SUM(available_quantity)(=可用数量,不含锁定待出库),并新增 locked_quantity(该库位锁定数量,SUM(locked_quantity))——goods 视图 locations 各项与 space 视图 goods 子项(workData/workDataDetail/workDataSpaceDetails 共用构建器);盲盘仍不返回任何数量字段。代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows/#_buildSpaceWorkRows;回归测试 222/222 通过、ESLint 0 错误。(后续已按用户要求全部统一:result/report/finish/detail 差异汇总与 addDetail 拆行快照均改为可用数量口径,见 0.3.249 变更记录)", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData、stock.check.workDataDetail 与 stock.check.workDataSpaceDetails 三条(description/response.rows/notes 同步库位账面=可用数量口径与 locked_quantity 字段);根版本 0.3.247 → 0.3.248、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 20 条 method 未改动(stock.check 分组仍为 23 条)。", + "库位账面口径全量统一(本次,0.3.249 同步):全部盘点账面口径统一为 SUM(available_quantity)(=可用数量,不含锁定待出库)——result 库位行 stocks 账面与空库位标记盘亏、report 重算 diff_items 的库位行/空标记账面、finish 差异汇总、detail profit/loss 汇总、addDetail 按库位拆行的明细快照 system_quantity,与盘点作业视图(workData/workDataDetail/workDataSpaceDetails)一致;商品行仍以明细账面快照(system_quantity 列)对比。回归测试 222/222 通过、ESLint 0 错误。", + "only_abnormal 过滤口径(本次新增):only_abnormal(boolean,可选,向后兼容,兼容 onlyAbnormal 驼峰写法;未传或非 true(false/0/空串/缺省)不过滤)——过滤在 keyword 之后、分页切片之前完成(total 为过滤后行数),三视图均生效:location 视图仅保留 status=unchecked 或 has_unknown=true 的行(未知商品无账面、差异=实盘-0=盘盈视为差异;空库位标记 is_empty 后 status=checked 视为已盘点、不保留);goods 视图仅保留未盘行(locations 均无 record_ids,即无任何作业记录)或明盘差异行(is_diff=1),盲盘无数量字段仅按未盘过滤(已盘行全部移除);space 视图按行内 goods 子项过滤(status=unchecked 或明盘 checked_quantity≠system_quantity,system_quantity 口径=可用数量),过滤后 goods 为空的行整体移除。与 keyword 过滤叠加(keyword 先过滤、only_abnormal 后过滤)。代码依据:app/service/systemMethods/stock/check.js#workData(only_abnormal/onlyAbnormal 蛇形驼峰兼容,透传 onlyAbnormal)+ app/service/systems/stock_check.js#workData/#_filterAbnormalWorkRows;回归测试新增 5 用例(location/goods 明盘/space 明盘/space 盲盘/keyword 叠加)全部通过、workData 相关 43 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 only_abnormal、description/response.rows/response.total/notes 同步过滤口径;headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.249 → 0.3.250、updatedAt 保持 2026-10-06;methods/changes/system.json 新增本条(插入数组首位);其余 23 条 method 未改动(stock.check 分组仍为 24 条)。", + "商品视图按商品汇总(本次,0.3.309):goods 视图原以库位明细行为列表(同商品多库位输出多条 detail_id,商品信息与 locations 完全相同、行级数量各管一个库位),前端无法区分且跨行求和会重复计数;现按 stock_id 汇总一行——行级 system_quantity=各库位明细行快照合计、checked_quantity/diff_quantity=该商品全部明细的作业记录按库位合并后合计,locations 每项新增 detail_id(该库位盘点明细ID,供逐库位上报/删除)与 snapshot_quantity(该库位账面快照,明盘);行级不再返回 detail_id/detail_ids(汇总行无单一明细语义,逐库位明细与汇总改由 stock.check.workDataDetail 传 id + stock_id 获取);stock_id 为空/异常的明细行无法归并,仍各自成行;keyword(仅 location 视图生效)/only_abnormal/分页口径不变,商品任务 total 由「明细行数」变为「商品行数」(与主表 total_items 按商品计数一致)。代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows(按 stock_id 分组 detailGroups,locations 挂 detail_id/snapshot_quantity)。", + "账面取值按静态标记区分(本次,0.3.318):workData 的 goods / space 视图原先 goods 视图行级取快照、locations 取 storage,口径混用;现统一为「system_quantity = 本次参与差异计算的账面」——is_static=1 取明细快照(冻结基准),is_static=0 取当前 wms_storage(可用数量);同时新增 storage_quantity(当前 storage 账面)与 is_static/book_source 字段,快照仍以 snapshot_quantity 输出,调用方可按需对照。space 视图行内 goods 同样按此口径(并新增 storage_quantity/snapshot_quantity)。代码依据:app/service/systems/stock_check.js#workData(isStatic 透传)/#_buildGoodsWorkRows/#_buildSpaceWorkRows。", + "静态盘点拣货完成标记(本次,0.3.320):goods 视图行在 is_static=1 时新增 picking_completed(1=已完成拣货/0=未完成)与明盘 locked_quantity(该商品仓库内 wms_storage SUM(locked_quantity)),判定口径为商品在仓库内是否仍有锁定量——分配储位只把 available_quantity 搬成 locked_quantity(quantity 不变),拣货完成时 quantity 与 locked_quantity 同时扣减、available_quantity 不变,因此 locked_quantity>0 即说明仍有已分配储位但未拣出的在途出库。盲盘(mode=blind)不输出 locked_quantity 数值、仅输出完成标记。代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows/#_fetchStockLockedQuantityMap。", + "space 视图拣货完成标记(本次,0.3.321):goods 子项在 is_static=1 时新增 picking_completed(1=已完成拣货/0=未完成),与 goods 视图行口径一致(按商品维度统计仓库内 SUM(locked_quantity)),盲盘同样返回。代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows。" + ] + }, + { + "method": "stock.check.workDataSpaceDetails", + "description": "拉取盘点作业数据(space 视图分页版):入参 id(盘点任务ID)+ location_id(库位ID,可选,兼容 locationId 驼峰写法)+ pagination({page,pageSize},缺省 page=1/pageSize=20,上限 200);warehouse_id 由服务端从当前上下文自动注入,前端无需传递。行结构与 workData space 视图行一致:id=库位ID(wms_location_space.id,另有同义字段 location_id)/ space_code 库位编码 / custom_barcode 自定义条码 / custom_name 库位名称 / goods 该库位下的任务商品子列表(detail_id 明细ID / stock_id 商品库存ID / item_code 商品编码 / item_name 商品名称 / spec 规格 / store_id 货主ID / store_name 货主名 / barcode 条码 / images 作业照片 / record_ids 作业记录ID列表;明盘 mode=open 另含 system_quantity 账面数量(wms_storage 该库位该商品 SUM(available_quantity))、locked_quantity 锁定数量(wms_storage 该库位该商品 SUM(locked_quantity))与 checked_quantity 已盘合计;盲盘 mode=blind 不返回任何数量字段;静态盘点(is_static=1)时 goods 子项另含 picking_completed(1=该商品已完成拣货/0=未完成,口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0,按商品维度判定,明盘盲盘均返回);status=checked 该 (detail_id, location_code) 存在作业记录 / unchecked 未盘)。库位仅按库位拣货顺序排序(pick_sequence 升序,pick_priority 与库位 id 不参与,同值保持库位查询顺序);传入 location_id 时只返回该库位行(total=1),不传时按分页返回全部库位行;返回 { view:'space', rows, total, page, pageSize }(不返回任务主表信息,任务信息请调用 stock.check.detail)。仅任务状态 approved(审核完成)或 checking(盘点作业中)可拉取(与 workData 同口径)。权限口径:免 API 权限校验,仅需登录(与 stock.check 分组其他方法一致)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID(正整数)" + }, + { + "name": "location_id", + "type": "number", + "required": false, + "source": "body", + "description": "库位ID(wms_location_space.id,可选;传入时只返回该库位行,兼容 locationId 驼峰写法)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页配置:page(页码,默认1)、pageSize(每页数量,默认20,上限200);传入 location_id 时分页参数仅影响返回结构,total 恒为 1" + } + ], + "response": [ + { + "name": "view", + "type": "string", + "required": true, + "description": "恒为 space(聚合库位视图)" + }, + { + "name": "rows", + "type": "array", + "required": true, + "description": "当前页库位行:每行含 id/space_code/custom_barcode/custom_name/goods(goods 结构与 workData space 视图一致,明盘含 system_quantity/checked_quantity/status,盲盘不含数量字段)" + }, + { + "name": "total / page / pageSize", + "type": "object", + "required": true, + "description": "total=全部库位行数(传入 location_id 时恒为 1),page/pageSize=当前分页" + } + ], + "errors": [ + { + "code": "400", + "message": "盘点任务ID不能为空" + }, + { + "code": "400", + "message": "盘点任务不存在" + }, + { + "code": "400", + "message": "当前状态不允许拉取盘点作业数据(仅 approved/checking 可拉取)" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "拉取盘点作业数据失败" + } + ], + "notes": [ + "静态盘点拣货完成标记(本次,0.3.321):goods 子项在 is_static=1 时新增 picking_completed(1=已完成拣货/0=未完成),口径与 stock.check.workData goods/space 视图一致——按商品维度统计仓库内 wms_storage SUM(locked_quantity),>0 即仍有已分配储位但未拣出的在途出库。盲盘(mode=blind)同样返回该标记(不含任何数量字段)。与 stock.check.report 的静态盘点上报拦截(商品未完成拣货返回 400)配套使用。代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows(workDataSpaceDetails 复用同一 space 视图构建)。" + ] + }, + { + "method": "stock.check.workDataDetail", + "description": "拉取盘点作业数据明细(库位明细单行 / 商品钻取):入参二选一——① detail_id(盘点明细ID,兼容 detailId 驼峰写法,库位明细必传);② id(盘点任务ID)+ stock_id(商品库存ID,兼容 stockId 驼峰写法,商品钻取用,goods 汇总视图行不返回明细ID 时按此获取明细);warehouse_id 由服务端从当前上下文自动注入,前端无需传递;返回统一 success 包装,data 为单行作业数据。① 库位明细(scope_type=location):行结构与 workData location 视图单行一致——detail_id 明细ID / location_id 库位ID(明细未绑定库位时为 null)与同义字段 space_id(可直接回传 stock.check.report)/ location_code 库位编码(优先明细快照,缺失回退库位表 space_code)/ location_name 库位名称(custom_name 兜底 space_code,无库位编码时为 null)/ status 盘点状态(checked=存在作业记录(含空库位标记记录),unchecked=无作业记录)/ has_unknown 是否含未知商品记录 / is_empty 是否空库位标记(空标记记录不计入 goods 子列表)/ checked_at 该库位最近上报时间(无记录为 null)/ checkers 盘点人去重数组 + goods 作业记录子列表(已知商品与未知商品记录均入内,字段与 workData location 视图一致:record_id 作业记录ID(可调 stock.check.recordDelete / stock.check.recheckClearLocation 移除)/ stock_id 商品库存ID(未知商品为 null)/ item_code 商品编码(未知商品用条码兜底)/ item_name 商品名称(未知商品用名称快照兜底条码)/ barcode 条码 / images 作业记录照片(FileReference business_type=stock_check_record 经 _attachRecordImages 挂载,与 workData/result/recordList 口径一致,无照片为空数组)/ store_id 货主ID(未知商品为 null)/ store_name 货主名(未知商品为 null)/ quantity 实盘数量 / checked_at 上报时间 / checker_name 盘点人;空库位标记记录不计入 goods)。② 商品(id + stock_id,或 detail_id 指向商品范围行):返回该商品的库位分行数据 + 汇总数据 { check_id 盘点任务ID / stock_id 商品库存ID / item_code 商品编码 / item_name 商品名称 / spec 规格 / store_id 货主ID / store_name 货主名 / barcode 条码 / images 商品图片(URL 数组)/ summary 商品级汇总(仅明盘:system_quantity 账面快照合计=该商品各库位明细快照之和 / checked_quantity 实盘合计 / diff_quantity 差异=实盘-账面 / is_diff;盲盘不返回 summary 与任何数量字段)/ rows 按库位分行(每项 detail_id 该库位盘点明细ID(无明细快照的库位为 null)/ location_id 库位ID 与同义字段 space_id(wms_location_space.id,可直接回传 stock.check.report)/ location_code 库位编码 / checked_at 该库位最近上报时间 / checker_name 盘点人 / record_ids 该库位作业记录ID(按记录 id 升序)/ images 作业记录照片;明盘另含 system_quantity 该库位当前账面数量(wms_storage 可用数量)/ locked_quantity 该库位锁定数量 / snapshot_quantity 该库位账面快照(盘点开始时的账面)/ checked_quantity 该库位实盘合计 / diff_quantity 该库位差异=实盘-快照;盲盘不含任何数量字段))。分行库位顺序与 workData goods 视图 locations 一致(商品库存库位按拣货路径在前,已盘但当前无库存的库位按首条记录 id 升序追加在末尾,空库位归 location_code=null 组排最后)。仅任务状态 approved(审核完成)或 checking(盘点作业中)可拉取(与 workData 同口径)。静态盘点(is_static=1)商品钻取另在顶层返回 picking_completed(1=该商品已完成拣货/0=未完成,口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0)与明盘 locked_quantity(该商品仓库内锁定量合计)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "盘点任务ID(wms_stock_check.id):商品钻取(id + stock_id)必传" + }, + { + "name": "stock_id", + "type": "number", + "required": false, + "source": "body", + "description": "商品库存ID(wms_stock_warehouse.id):商品钻取必传,与 id 搭配返回该商品的库位分行数据 + 汇总数据(兼容 stockId 驼峰写法)" + }, + { + "name": "detail_id", + "type": "number", + "required": false, + "source": "body", + "description": "盘点明细ID(兼容 detailId 驼峰写法):库位明细(scope_type=location)必传,返回库位单行;商品范围明细可只传本参数,服务端按明细商品走商品钻取。与 id + stock_id 二选一" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法业务数据整体位于 data 内;失败时 data=null)。结构随入参分流:① 库位明细(detail_id 指向 scope_type=location 行)为单行作业数据,结构与 stock.check.workData location 视图单行一致(下方 children 即该结构);② 商品(id + stock_id)为商品钻取结构 { check_id, stock_id, item_code, item_name, spec, store_id, store_name, barcode, images, summary(仅明盘:system_quantity 账面快照合计/checked_quantity 实盘合计/diff_quantity/is_diff), rows(按库位分行:detail_id/location_id/space_id/location_code/checked_at/checker_name/record_ids/images,明盘另含 system_quantity 当前账面/locked_quantity/snapshot_quantity 账面快照/checked_quantity 实盘/diff_quantity 差异) }② 商品钻取结构补充:账面取值按任务静态标记(is_static)区分:is_static=1(静态盘点)取明细账面快照 system_quantity(盘点基准冻结,不受盘点期间出入库影响);is_static=0(普通盘点)取当前 wms_storage 账面 SUM(available_quantity);两者都会额外输出 storage_quantity(当前 storage 账面)与 snapshot_quantity(明细快照)供对照,system_quantity 始终为参与差异计算的账面,行/商品额外输出 is_static 与 book_source(snapshot|storage);明细行另含 storage_quantity(该库位当前 storage 账面),差异 diff_quantity=实盘-参与计算的账面。", + "children": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "description": "盘点明细ID(wms_stock_check_detail.id)" + }, + { + "name": "location_id", + "type": "number", + "required": true, + "description": "库位ID(wms_location_space.id;明细未绑定库位时为 null)" + }, + { + "name": "location_code", + "type": "string", + "required": true, + "description": "库位编码(优先明细快照,缺失回退库位表 space_code;无库位时为 null)" + }, + { + "name": "location_name", + "type": "string", + "required": true, + "description": "库位名称(custom_name 兜底 space_code;无库位编码时为 null)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "盘点状态:checked=存在作业记录(含空库位标记记录),unchecked=无作业记录" + }, + { + "name": "has_unknown", + "type": "boolean", + "required": true, + "description": "是否含未知商品记录(该库位存在 stock_id 为空的作业记录时为 true,未知商品同样计入 goods)" + }, + { + "name": "is_empty", + "type": "boolean", + "required": true, + "description": "是否空库位标记(该库位存在空库位标记记录(is_empty=1)时为 true;空标记记录不计入 goods 子列表)" + }, + { + "name": "checked_at", + "type": "string", + "required": true, + "description": "该库位最近上报时间(无记录为 null)" + }, + { + "name": "checkers", + "type": "array", + "required": true, + "description": "盘点人去重数组(字符串数组,无记录为空数组)" + }, + { + "name": "goods", + "type": "array", + "required": true, + "description": "该库位盘点作业记录子列表(已知商品与未知商品记录均入内,字段与 workData location 视图一致;空库位标记记录不计入;无记录为空数组):每项 record_id 作业记录ID(单条记录直接定位,可调 stock.check.recordDelete / stock.check.recheckClearLocation 移除)/ stock_id 商品库存ID(未知商品为 null)/ item_code 商品编码(未知商品用条码兜底)/ item_name 商品名称(未知商品用名称快照兜底条码)/ barcode 条码 / images 作业记录照片([{ id, url }],FileReference business_type=stock_check_record 经 _attachRecordImages 挂载,与 workData/result/recordList 口径一致,无照片为空数组)/ store_id 货主ID(未知商品为 null)/ store_name 货主名(未知商品为 null)/ quantity 实盘数量 / checked_at 上报时间 / checker_name 盘点人" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点明细ID不能为空" + }, + { + "code": 400, + "message": "盘点明细不存在" + }, + { + "code": 400, + "message": "仅库位任务明细支持拉取单行作业数据" + }, + { + "code": 400, + "message": "盘点任务不存在" + }, + { + "code": 400, + "message": "当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#workDataDetail(ALL_METHOD_NAMES 由 22 增至 23 个(create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,workDataDetail,report,markEmpty,recordList,recordDelete,recheckClearLocation,finish,submit,cancel,audit,batchDelete,export,exportTaskProgress,patternList,patternCreate);_noNeedLog 查询类清单新增 workDataDetail(list,detail,result,workData,workDataDetail,recordList,export,exportTaskProgress,patternList);const { detail_id: detailIdSnake, detailId: detailIdCamel } = data || {},detailId=detail_id 未定义时回退 detailId(兼容 detailId 驼峰写法);warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递,透传 { warehouseId, detailId })+ app/service/systems/stock_check.js#workDataDetail(detailId 非正整数抛 400『盘点明细ID不能为空』;按 id+warehouse_id 查 wms_stock_check_detail 不存在抛 400『盘点明细不存在』;_findCheck 查不到任务抛 400『盘点任务不存在』;任务状态非 REPORT_ALLOWED_STATUSES(approved/checking)抛 400『当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』;按明细 scope_type 分流:location 走 _buildLocationWorkRows 构建全量库位行并 find 匹配该明细ID、goods 走 _buildGoodsWorkRows 构建全量商品行并 find 匹配该明细ID,未命中抛 400『盘点明细不存在』,命中返回该单行)。本次代码已改并测试通过 216/216、ESLint 0 错误;后续 goods 分支扩展与 locations 商品库位列表口径见下方变更说明。", + "单行口径:响应 data 为单行作业数据,与 stock.check.workData 对应视图单行完全一致(复用同一构建函数 _buildLocationWorkRows/_buildGoodsWorkRows),便于作业端按明细ID刷新单行数据;库位明细(scope_type=location)返回 location 视图单行(detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/checked_at/checkers/goods),商品明细(scope_type=goods)返回商品钻取结构(id + stock_id 或商品范围 detail_id):{ check_id, stock_id, 商品信息, summary 商品级汇总, rows 按库位分行(detail_id/location_id/space_id/location_code + 账面快照/实盘/差异) },明盘含数量字段、盲盘不含。", + "权限口径:随 ALL_METHOD_NAMES(23 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog,不记录操作日志。", + "状态限制口径:仅任务状态 approved(审核完成)或 checking(盘点作业中)可拉取,与 stock.check.workData / report / finish 同口径(REPORT_ALLOWED_STATUSES)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workDataDetail 一条(位于 stock.check.workData 之后);根版本 0.3.244 → 0.3.245、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组由 22 条增至 23 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。", + "goods 明细单行 locations 商品库位列表口径(本次同步 workData 改造):workDataDetail 商品明细分支复用 _buildGoodsWorkRows,locations 为商品所在全部库位列表(库存库位按拣货路径排序在前、无库存但已有作业记录的库位按首条记录 id 升序追加、空库位归 null 组排在最后;明盘每库位含 system_quantity 该库位账面数量(=可用数量,不含锁定待出库)、locked_quantity 该库位锁定数量与 quantity 该库位盘点数量(未盘 0),盲盘只返回库位信息);未盘明细 checked_quantity 恒 0、diff_quantity/is_diff 仅存在作业记录时计算(未盘恒 0)。回归测试 222/222 通过、ESLint 0 错误。", + "库位账面口径(本次同步 workData 改造):goods 明细单行 locations 各项库位账面 system_quantity = wms_storage 该库位 SUM(available_quantity)(可用数量),locked_quantity = 该库位 SUM(locked_quantity);盲盘仍不返回任何数量字段。回归测试 222/222 通过、ESLint 0 错误。", + "商品钻取改造(本次,0.3.309):goods 视图改为按商品汇总后行级不再返回明细ID,本方法商品分支新增入参 id(盘点任务ID)+ stock_id(商品库存ID),返回「汇总数据 summary + 按库位分行数据 rows」——summary 为该商品级账面快照合计/实盘合计/差异/is_diff,rows 每个库位一行并给出 detail_id(该库位盘点明细ID)、location_id/space_id(库位ID,可直接回传 stock.check.report)、location_code、system_quantity(该库位当前账面)、snapshot_quantity(该库位账面快照)、checked_quantity(该库位实盘)、diff_quantity(实盘-快照)及 checked_at/checker_name/record_ids/images;原「按明细ID 返回 goods 视图单行」的结构不再返回,兼容入口保留(传商品范围 detail_id 仍返回商品钻取结构,服务端按明细商品解析 id + stock_id);库位明细(scope_type=location)分支不变。代码依据:app/service/systems/stock_check.js#workDataDetail(id + stockId 解析,detail_id 兼容)/#_formatGoodsWorkDetail(summary + rows 组装)。", + "账面取值按静态标记区分(本次,0.3.318):workDataDetail 商品钻取的 summary.system_quantity 与 rows[].system_quantity 统一按任务 is_static 取值(1=明细快照,0=当前 wms_storage),rows[].diff_quantity=checked_quantity - system_quantity;另输出 storage_quantity(当前 storage 账面)、snapshot_quantity(明细快照)、is_static 与 book_source,便于前端展示「盘点基准 vs 当前账面」。代码依据:app/service/systems/stock_check.js#workDataDetail/#_formatGoodsWorkDetail。", + "静态盘点拣货完成标记(本次,0.3.320):商品钻取(scope_type=goods)在 is_static=1 时顶层新增 picking_completed(1=已完成拣货/0=未完成)与明盘 locked_quantity(该商品仓库内锁定量合计),口径与 stock.check.workData goods 视图行一致。代码依据:app/service/systems/stock_check.js#_formatGoodsWorkDetail。" + ] + }, + { + "method": "stock.check.report", + "description": "盘点作业上报(覆盖式):**detail_id 可选**——goods 汇总视图行(stock.check.workData)不再返回明细ID,商品行可只传 id + stock_id + space_id,服务端按「该商品在该库位(location_id=space_id)的明细 → 该商品任一明细」顺序反查明细后落库(反查不到报 400「盘点明细不存在(该商品不在本任务盘点范围内,或库位盘点任务需传 detail_id)」),库位盘点行仍必传 detail_id;商品明细行(scope_type=goods)固定上报明细商品(入参 stock_id 与明细商品不一致报错),库位可选(未传归入\"无库位\"分组,location_code 存空串 '');库位明细行(scope_type=location)必须指定商品(stock_id 或 barcode 至少一项),库位以明细库位为准(入参库位与明细库位不一致报错,不传时默认明细库位);空库位标记(is_empty=true,仅库位明细行支持):确认该库位为空——不要求商品/条码,quantity 恒为 0,写一条特殊作业记录(stock_id=null、barcode=null、item_name=null、quantity=0、is_empty=1);与商品记录互斥:标记空时删除该明细下所有商品记录(含未知商品),上报商品时删除该明细下空标记记录;商品明细行传 is_empty 报 400「仅库位盘点明细支持空库位标记」。覆盖式查重:已知商品维度 detail_id+stock_id+location_code、未知商品维度 detail_id+stock_id IS NULL+barcode+location_code,同明细+同商品+同库位重复上报时更新已有记录(quantity/checker_id/checker_name/checked_at,保留原 location_id,本次新匹配到 location_id 则回填),不再新增;仅 approved/checking 状态允许;**space_id 必传**(库位以该 ID 为准,传了 location 编码则仅做一致性校验,服务端不再按编码猜库位,缺失报 400「缺少库位ID(space_id)」);实盘数量上限 2147483647(超出报 400「实盘数量不能超过 2147483647」,避免落库列 int(12) 越界变成 500);主表 approved 首次上报自动转 checking;完成后重算 checked_items/diff_items/detail_status(已盘口径=存在记录的明细数,差异=记录数量合计-账面:商品行 vs system_quantity 快照、库位行按商品 vs wms_storage 账面;未知商品无账面,实盘>0 即盘盈、必然计入差异;空标记记录同样计入已盘明细(checked_items/detail_status),空标记明细的库位账面有库存即计盘亏差异(diff_items));数据库层由唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证已知商品覆盖式上报并发安全(并发下不产生重复记录),未知商品(stock_id=NULL)唯一索引不约束 NULL 行、应用层查重兜底。主表 start_time 为空时以本次明细写入时间补写(首个盘点明细写入时间记录为 start_time,即盘点开始时间)。未知商品上报(stock_id 与 barcode 至少传一项):仅传 barcode → 先按条码匹配系统商品(wms_stock_barcodes 按 barcode+本仓库,关联 StockWarehouse 校验商品属于本仓库),命中回填 stock_id 走已知商品逻辑;未命中记录未知商品(stock_id=NULL+barcode+item_name,item_name 缺省为 barcode);都未传沿用原报错口径。静态盘点拣货完成校验:任务 is_static=1 且为商品范围明细(scope_type=goods)时,上报前校验该商品在仓库内的锁定量(wms_storage SUM(locked_quantity),is_enabled=1),大于 0 说明仍有已分配储位但尚未拣出的在途出库,直接拒绝上报并返回 400「商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货」。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + }, + { + "name": "detail_id", + "type": "number", + "required": false, + "source": "body", + "description": "盘点明细ID(wms_stock_check_detail.id):库位明细行必传;商品行可选——不传时按 id + stock_id + space_id 反查该商品的库位明细(先按 location_id=space_id 命中,未命中取该商品任一明细)" + }, + { + "name": "location", + "type": "string", + "required": false, + "source": "body", + "description": "库位编码(可选,仅做一致性校验;库位一律以 space_id 为准):商品明细行传入时必须与 space_id 对应库位编码一致(否则 400「上报库位编码与库位ID不一致」);库位明细行传入时必须与明细库位一致(否则 400「上报库位与盘点明细库位不一致」);不传时按 space_id 对应库位编码落库" + }, + { + "name": "space_id", + "type": "number", + "required": true, + "source": "body", + "description": "库位ID(wms_location_space.id,**必填**;兼容 spaceId / location_id / locationId 写法,取回接口 rows[].space_id / rows[].id / locations[].space_id 可直接回传):必须属于当前仓库且所属分区(zone)存在未删除,缺失或非法返回 400「缺少库位ID(space_id)」、不存在/跨仓库/分区已删除返回 400「上报库位不存在、不属于当前仓库或所属分区已删除」;服务端以该 ID 为准落库,不再按库位编码猜库位" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "source": "body", + "description": "实盘数量(不小于 0 的整数,且不大于 2147483647——超出落库列 int(12) 范围会报 400「实盘数量不能超过 2147483647」)" + }, + { + "name": "stock_id", + "type": "number", + "required": false, + "source": "body", + "description": "商品库存ID(wms_stock_warehouse.id);商品明细行可选(传入必须与明细商品一致,否则报错);未传 detail_id 时必传,用于反查该商品的盘点明细;库位明细行必填(或改传 barcode 按条码匹配),商品必须属于本仓库" + }, + { + "name": "barcode", + "type": "string", + "required": false, + "source": "body", + "description": "扫描到的条码/编码(可选):未传 stock_id 时按条码匹配系统商品(wms_stock_barcodes 按 barcode+本仓库匹配并校验商品属于本仓库,关联 StockWarehouse),命中回填 stock_id 按已知商品处理;未命中记为未知商品(stock_id=NULL+barcode+item_name)" + }, + { + "name": "item_name", + "type": "string", + "required": false, + "source": "body", + "description": "未知商品名称快照(可选):仅未知商品记录落库,缺省为 barcode;已知商品忽略" + }, + { + "name": "is_empty", + "type": "boolean", + "required": false, + "source": "body", + "description": "空库位标记(可选,仅库位明细行 scope_type=location 支持):true 表示「确认该库位为空」——不要求商品/条码,quantity 恒为 0(不参与数量校验),写一条特殊作业记录(stock_id=null、barcode=null、item_name=null、quantity=0、is_empty=1);与商品记录互斥:标记空时删除该明细下所有商品记录(含未知商品),上报商品时删除该明细下空标记记录;商品明细行传 true 报 400「仅库位盘点明细支持空库位标记」" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "新增或更新的盘点作业记录(wms_stock_check_record 行:id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/barcode/item_name/is_empty/created_at/updated_at);stock_id 可空:NULL=未知商品(此时 barcode=扫描条码、item_name=未知商品名称快照(缺省为条码)),已知商品 barcode/item_name 可能为空;is_empty=1 为空库位标记记录(stock_id/barcode/item_name 均为 null、quantity=0)" + }, + { + "name": "detail_id", + "type": "number", + "required": true, + "description": "盘点明细ID" + }, + { + "name": "mode", + "type": "string", + "required": true, + "description": "本次上报模式:created=首次上报新增记录 / updated=同明细+同商品+同库位重复上报更新已有记录(未知商品为同明细+同条码+同库位)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "明细总行数" + }, + { + "name": "checked_items", + "type": "number", + "required": true, + "description": "已盘行数(存在作业记录的明细数;空库位标记记录同样计入已盘)" + }, + { + "name": "diff_items", + "type": "number", + "required": true, + "description": "差异行数(实盘合计与账面不一致的明细数;未知商品无账面,实盘>0 即盘盈、必然计入差异;空标记明细的库位账面有库存即计盘亏差异)" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "明细盘点进度:none_checked/partial_checked/all_checked" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点明细ID不能为空 / 盘点任务不存在 / 当前状态(非 approved/checking)不允许盘点作业 / 实盘数量必须为不小于0的整数 / 盘点明细不存在 / 盘点明细缺少商品信息 / 上报商品与盘点明细商品不一致 / 按库位盘点时必须指定商品 / 上报商品不属于本仓库 / 盘点明细缺少库位信息 / 上报库位与盘点明细库位不一致 / 仅库位盘点明细支持空库位标记 / 商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货(静态盘点商品范围任务仍有锁定量时)" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "覆盖口径:同 detail_id + 同 stock_id + 同 location_code(未传库位存储空串 '',即\"无库位\"分组)视为同一作业记录,重复上报只更新不新增。", + "并发保证:数据库层唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 兜底,并发上报同一明细+商品+库位时不产生重复记录(模型 location_code allowNull=false 默认空串)。", + "库位行上报:商品必填(按库位盘点时必须指定商品,stock_id 或 barcode 至少一项)且商品须属于本仓库(wms_stock_warehouse.id + warehouse_id),库位以明细库位为准(detail.location_code)。", + "start_time 口径:主表 start_time 为空时以本次明细写入时间补写(首个盘点明细写入时间记录为 start_time=盘点开始时间);代码依据 app/service/systems/stock_check.js#report(start_time 为空则补写,保证任何状态下首个明细落盘时间都被记录)。", + "未知商品上报口径(stock_id 与 barcode 至少传一项):传了 stock_id 按已知商品走现有逻辑(本仓库校验等);未传 stock_id 但传了 barcode,先按条码匹配系统商品(_resolveStockIdByBarcode:wms_stock_barcodes 按 barcode+本仓库匹配,再校验 wms_stock_warehouse 中该商品属于本仓库),命中回填 stock_id 按已知商品处理(商品明细行还会校验与明细商品一致),未命中记录未知商品(stock_id=NULL + barcode + item_name,item_name 缺省为 barcode);都未传沿用现有报错口径(商品行缺商品信息报 400 / 库位行缺商品报 400)。", + "未知商品覆盖式查重:已知商品 where { detail_id, stock_id, location_code } 不变;未知商品 where { detail_id, stock_id: null, barcode, location_code } 应用层查重(唯一索引 uk_detail_stock_location 不约束 NULL 行,并发下撞索引/冲突时同样按查重条件降级更新兜底)。", + "迁移依据:database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js(wms_stock_check_record:stock_id 改可空(NULL=未知商品)+ 新增 barcode VARCHAR(100)/item_name VARCHAR(255),本地与生产均已执行)。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "空库位标记上报口径(本次新增):is_empty 仅库位明细行(scope_type=location)支持,商品明细行传 is_empty 报 400『仅库位盘点明细支持空库位标记』;标记空时不要求商品/条码,quantity 恒为 0(跳过『实盘数量必须为不小于0的整数』校验),写一条特殊作业记录(stock_id=null、barcode=null、item_name=null、quantity=0、is_empty=1);覆盖式查重按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新。互斥口径:标记空时删除该明细下所有商品记录(is_empty=false,含未知商品),上报商品时删除该明细下空标记记录(is_empty=true),两者不会并存。代码依据:app/service/systems/stock_check.js#report。", + "汇总口径(本次同步 _recalcCheckSummary):空库位标记记录计入已盘明细(checked_items 按 DISTINCT detail_id 自然计入、detail_status 按已盘占比正常推进);差异口径:空标记明细的库位账面(wms_storage 按 space_id SUM(available_quantity)=可用数量)有库存即计盘亏差异(diff_items 加 1),账面无库存不计差异。代码依据:app/service/systems/stock_check.js#_recalcCheckSummary。", + "迁移依据:database/migrations/20261002160000-add-is-empty-to-stock-check-record.js(wms_stock_check_record 新增 is_empty TINYINT(1) NOT NULL DEFAULT 0,COMMENT 是否空库位标记(1=确认为空),开发与生产库均已执行)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.report:params 新增 is_empty 入参、errors 400 补「仅库位盘点明细支持空库位标记」、description/response/notes 补充空库位语义与互斥及汇总口径;stock.check.workData:description/response.rows 的 location 行新增 is_empty 字段说明;stock.check.result:description/response.rows 库位行新增 is_empty 与空标记盘亏口径;stock.check.recordList:response.rows 记录全字段说明新增 is_empty;stock.check.export:description/notes 补 Sheet2 空库位行输出口径);根版本 0.3.233 → 0.3.234、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。", + "detail_id 可选改造(本次,0.3.309):goods 视图按商品汇总后行级不再带明细ID,report 放宽 detail_id 为可选——未传时按 id + stock_id + space_id 反查明细(先查 check_id + warehouse_id + stock_id + location_id=space_id,未命中取该商品任一明细,货主/仓库隔离条件不变),反查不到返回 400「盘点明细不存在(该商品不在本任务盘点范围内,或库位盘点任务需传 detail_id)」;既未传 detail_id 也未传 stock_id 仍返回 400「盘点明细ID不能为空」;落库口径不变(作业记录仍挂 detail_id,覆盖式查重仍按 detail_id+stock_id+location_code)。代码依据:app/service/systems/stock_check.js#report(resolvedDetailRowId 解析)。", + "静态盘点拣货完成校验(本次,0.3.320):任务 is_static=1 且为商品范围明细(scope_type=goods)时,上报前校验该商品在仓库内的锁定量(wms_storage SUM(locked_quantity),is_enabled=1):大于 0 说明该商品仍有已分配储位但未拣出的在途出库,直接拒绝上报并返回 400「商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货」;锁定量为 0(拣货已完成)才写作业记录。库位范围任务 is_static 恒为 0 不受影响;未知商品(stock_id 为空)无锁定量不受影响。代码依据:app/service/systems/stock_check.js#report(_fetchStockLockedQuantityMap 前置校验)。" + ] + }, + { + "method": "stock.check.markEmpty", + "description": "标记库位为空(库位盘点模式专属,转调 report 的空库位标记口径):仅库位范围任务(type=location)支持——非库位任务报 400「仅库位盘点任务支持空库位标记」;仅 approved/checking 状态允许;明细必须属于本任务且为库位范围行(scope_type=location),非库位行报 400「仅库位盘点明细支持空库位标记」;行为与 report(is_empty=true) 完全一致——写/更新空标记记录(stock_id/barcode/item_name 均为 null、quantity=0、is_empty=1)、清除该明细商品记录、主表 approved 首次标记自动转 checking、重算 checked_items/diff_items/detail_status(空标记计入已盘;库位账面有库存计盘亏差异);warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,前端无需传递。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID(正整数;非法抛 400「盘点任务ID不能为空」)" + }, + { + "name": "detail_id", + "type": "number", + "required": true, + "source": "body", + "description": "库位明细ID(正整数;非法抛 400「盘点明细ID不能为空」;明细必须属于本任务且为库位范围行 scope_type=location,非库位行报 400「仅库位盘点明细支持空库位标记」)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,与 report 口径一致;失败时 data=null)", + "children": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "新增或更新的空库位标记作业记录(wms_stock_check_record 行全字段:id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/barcode/item_name/is_empty/created_at/updated_at);is_empty=1 空库位标记记录:stock_id/barcode/item_name 均为 null、quantity=0" + }, + { + "name": "detail_id", + "type": "number", + "required": true, + "description": "盘点明细ID" + }, + { + "name": "mode", + "type": "string", + "required": true, + "description": "本次写入模式:created=首次写入空标记记录 / updated=重复标记更新已有空标记记录" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "明细总行数" + }, + { + "name": "checked_items", + "type": "number", + "required": true, + "description": "已盘行数(存在作业记录的明细数;空库位标记记录同样计入已盘)" + }, + { + "name": "diff_items", + "type": "number", + "required": true, + "description": "差异行数(实盘合计与账面不一致的明细数;空标记明细的库位账面有库存即计盘亏差异)" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "明细盘点进度:none_checked/partial_checked/all_checked" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空" + }, + { + "code": 400, + "message": "盘点明细ID不能为空" + }, + { + "code": 400, + "message": "盘点任务不存在" + }, + { + "code": 400, + "message": "当前状态(xx)不允许盘点作业" + }, + { + "code": 400, + "message": "仅库位盘点任务支持空库位标记" + }, + { + "code": 400, + "message": "盘点明细不存在" + }, + { + "code": 400, + "message": "仅库位盘点明细支持空库位标记" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "库位盘点专属便捷方法:内部转调 report(is_empty=true) 口径(查重/互斥/汇总/日志统一),行为与 report 空库位标记完全一致——写/更新空标记记录(stock_id=null、barcode=null、item_name=null、quantity=0、is_empty=1)、清除该明细商品记录、主表 approved 首次标记自动转 checking、完成后重算 checked_items/diff_items/detail_status。代码依据:app/service/systemMethods/stock/check.js#markEmpty(warehouse_id 由服务端从 ctx.user.store_id 自动注入,checkerId/checkerName 同口径注入)+ app/service/systems/stock_check.js#markEmpty(校验后转调 this.report({ is_empty: true }))。", + "校验顺序口径:任务ID/明细ID 非正整数 → 400「盘点任务ID不能为空」/「盘点明细ID不能为空」;任务不存在(按 id+warehouse_id 查 wms_stock_check)→ 400「盘点任务不存在」;状态非 REPORT_ALLOWED_STATUSES(approved/checking)→ 400「当前状态(xx)不允许盘点作业」;任务范围非库位(type≠location)→ 400「仅库位盘点任务支持空库位标记」;明细不存在(id+check_id+warehouse_id 查 wms_stock_check_detail)→ 400「盘点明细不存在」;明细非库位行(scope_type≠location)→ 400「仅库位盘点明细支持空库位标记」。", + "权限口径:随 ALL_METHOD_NAMES(22 个,已由 20 增至 21(markEmpty),本次再增 recheckClearLocation)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为写操作,不在免日志清单(_noNeedLog)中,记录操作日志(内部转调 report,走 STOCK_CHECK_REPORT 操作日志口径)。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内({ record, detail_id, mode, total_items, checked_items, diff_items, detail_status },与 report 完全一致)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.markEmpty 一条(位于 stock.check.report 之后);分组内各 method notes 的「统一包装」描述与 workData「权限口径」note 中 ALL_METHOD_NAMES 方法清单由 20 增至 21 个(markEmpty 插在 report 之后);根版本 0.3.234 → 0.3.235、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);stock.check 分组由 20 条增至 21 条。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次先经 script/method-doc-create.cjs 在维护源新建本方法(--bump 版本 0.3.234→0.3.235),再按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入变更记录;随后同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 21 条 method 无损。" + ] + }, + { + "method": "stock.check.recordList", + "description": "拉取盘点作业记录列表:至少传 id(盘点任务ID)或 detail_id(明细ID)之一(可同时传,detail_id 生效时只查该明细的作业记录);按当前用户仓库(ctx.user.store_id)限定数据范围;rows 每条为作业记录(wms_stock_check_record)全字段(id/check_id/warehouse_id/detail_id/stock_id/barcode/item_name/location_id/location_code/quantity/checker_id/checker_name/checked_at/is_empty/remark/created_at/updated_at 等)+ 商品信息列(item_code/item_name/spec/store_id/store_name/barcode,挂载口径对齐 workData);未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、名称列显示上报名称快照(item_name),spec/store_id/store_name 为 null、barcode=扫描条码;每条记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径);按记录 id 倒序,分页返回。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "盘点任务ID(可选;与 detail_id 至少传一个)" + }, + { + "name": "detail_id", + "type": "number", + "required": false, + "source": "body", + "description": "盘点明细ID(可选;传了只查该明细的作业记录;与 id 至少传一个)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1、pageSize=20,pageSize 上限 200(最小 1)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "rows", + "type": "array", + "required": true, + "description": "作业记录行列表:每条为 wms_stock_check_record 全字段(id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/barcode/item_name/is_empty/created_at/updated_at 等,保留记录全字段)+ 商品信息列 item_code/item_name/spec/store_id/store_name/barcode(挂载口径对齐 workData)+ images 图片列表 [{ id: file_id, url }](FileReference business_type=stock_check_record);stock_id 可空(NULL=未知商品);商品信息口径(对齐 workData):已知商品(stock_id 有值)item_code/item_name/spec 批量取自 stockWarehouse.getStockDetails(带缓存,未命中回退明细表 wms_stock_check_detail 商品快照)、store_id=商品货主ID、store_name=货主名(经 _resolveStoreNameMap 解析)、barcode=商品条码兜底(getStockDetails.barcodes[0],无则保留记录原始条码);未知商品(stock_id 为空)item_code=扫描条码(barcode,空则 null)、item_name=上报名称快照(item_name 或 barcode 兜底)、spec=null、store_id=null、store_name=null、barcode=扫描条码;location_code 口径:库中空串(\"无库位\"分组)返回时归一为 null(接口返回口径不变);is_empty 空库位标记:1=空库位标记记录(stock_id/barcode/item_name 均为 null、quantity=0)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总条数" + }, + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页条数" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "请至少提供盘点任务ID或明细ID" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "查询类方法,不记录操作日志(免日志清单:list/detail/result/recordList/export/exportTaskProgress)。", + "rows 按记录 id 倒序返回。", + "location_code 返回口径:库中空串(无库位分组)归一为 null,接口返回口径不变(与 detail 的 locations/location_codes 空库位组 location_code=null 一致)。", + "商品信息挂载对齐 workData(本次更新):已知商品(stock_id 有值)item_code/item_name/spec 批量取自 stockWarehouse.getStockDetails(带缓存,未命中回退明细表 wms_stock_check_detail 商品快照),新增 store_id(商品货主ID)/store_name(货主名,经 _resolveStoreNameMap 解析)、barcode 兜底商品条码(getStockDetails.barcodes[0],无则保留记录原始条码);未知商品(stock_id 为空)item_code=扫描条码(barcode,空则 null)、item_name=上报名称快照(item_name 或 barcode 兜底)、spec=null、store_id=null、store_name=null、barcode=扫描条码。保留记录全字段不变、向后兼容(仅新增列)。代码依据:app/service/systems/stock_check.js#recordList。本次代码已改并测试通过 215/215、ESLint 0 错误。", + "图片挂载口径(图片独立维护,仿收货 receivingItem):查询 wms_file_reference(business_type=stock_check_record)+ wms_file.file_url,每条记录挂载 images [{ id, url }],无图片返回空数组;上传走通用上传接口(businessType=stock_check_record + businessId=作业记录ID,建 FileReference)。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "空库位标记记录输出(本次新增):rows 每条为记录表全字段,is_empty 自动带出(1=空库位标记记录:stock_id/barcode/item_name 均为 null、quantity=0),未知商品显示口径不受影响。代码依据:app/service/systems/stock_check.js#recordList。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.report:params 新增 is_empty 入参、errors 400 补「仅库位盘点明细支持空库位标记」、description/response/notes 补充空库位语义与互斥及汇总口径;stock.check.workData:description/response.rows 的 location 行新增 is_empty 字段说明;stock.check.result:description/response.rows 库位行新增 is_empty 与空标记盘亏口径;stock.check.recordList:response.rows 记录全字段说明新增 is_empty;stock.check.export:description/notes 补 Sheet2 空库位行输出口径);根版本 0.3.233 → 0.3.234、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.recordList 一条(description/response.rows 补充新增字段 spec/store_id/store_name 与 barcode 兜底口径(对齐 workData)、说明保留记录全字段;notes 补充「商品信息挂载对齐 workData」说明;headers/params/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.239 → 0.3.240、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。" + ] + }, + { + "method": "stock.check.recordDelete", + "description": "删除盘点作业记录(由旧版单值删除升级为批量删除,口径与 detailDelete 批量一致):入参 record_ids 数组(单次上限 200;兼容 recordIds 驼峰数组、recordId 单数驼峰、record_id 单值旧写法,单值自动转数组);仅主表状态 approved/checking 允许删除;记录必须属于该盘点任务与当前仓库,查不到的记录 ID 计入 skipped_ids 不报错(deleted_ids/skipped_ids 保持入参顺序);删除后清理该批记录的图片引用(FileReference business_type=stock_check_record,失败仅告警不影响主流程)、重算 checked_items/diff_items/detail_status(明细作业记录删光后回到未盘口径),主表状态不回退;写 STOCK_CHECK_DELETE_RECORD 操作日志(文案「批量删除盘点作业记录 N 条」)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + }, + { + "name": "record_ids", + "type": "array", + "required": true, + "source": "body", + "description": "作业记录ID数组(wms_stock_check_record.id;单次上限 200;兼容旧版单值写法——传单值自动转数组)" + }, + { + "name": "recordIds", + "type": "array", + "required": false, + "source": "body", + "description": "作业记录ID数组(驼峰别名,兼容写法;record_ids 优先)" + }, + { + "name": "recordId", + "type": "number", + "required": false, + "source": "body", + "description": "作业记录ID(单数驼峰,兼容旧版单值写法;record_ids/recordIds 优先,单值自动转数组)" + }, + { + "name": "record_id", + "type": "number", + "required": false, + "source": "body", + "description": "作业记录ID(旧版单值写法,兼容;record_ids/recordIds/recordId 优先,单值自动转数组)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径见 data.children;失败时 data=null)", + "children": [ + { + "name": "deleted_count", + "type": "number", + "required": true, + "description": "实际删除的作业记录条数" + }, + { + "name": "deleted_ids", + "type": "array", + "required": true, + "description": "实际删除的作业记录ID列表(保持入参顺序)" + }, + { + "name": "skipped_ids", + "type": "array", + "required": true, + "description": "未删除(未命中:记录不存在或不属于该任务/仓库)的ID列表(保持入参顺序;查不到不报错)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "明细总行数" + }, + { + "name": "checked_items", + "type": "number", + "required": true, + "description": "重算后的已盘行数(存在作业记录的明细数)" + }, + { + "name": "diff_items", + "type": "number", + "required": true, + "description": "重算后的差异行数(实盘合计与账面快照不一致的明细数;未知商品无账面,实盘>0 即盘盈、必然计入差异)" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "重算后的明细盘点进度:none_checked/partial_checked/all_checked" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空" + }, + { + "code": 400, + "message": "盘点任务不存在" + }, + { + "code": 400, + "message": "当前状态(非 approved/checking)不允许删除作业记录" + }, + { + "code": 400, + "message": "请至少选择一条作业记录" + }, + { + "code": 400, + "message": "单次最多删除 200 条作业记录" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "删除为写操作,记录操作日志(不在免日志清单),operationCode=STOCK_CHECK_DELETE_RECORD、文案「批量删除盘点作业记录 N 条」(N=deleted_count,附跳过数量)。", + "批量口径(与 detailDelete 批量口径一致):查不到的记录 ID(记录不存在或不属于该任务/仓库)计入 skipped_ids 不报错;deleted_ids/skipped_ids 保持入参顺序;单值入参自动转数组。", + "删除后仅重算盘点进度汇总(checked_items/diff_items/detail_status),主表状态不回退。", + "图片清理口径(图片独立维护,仿收货):删除作业记录后同步清理 wms_file_reference(business_type=stock_check_record + business_id=记录ID),失败仅告警(warn 日志)不影响主流程。代码依据:app/service/systems/stock_check.js#recordDelete。", + "本接口由旧版单值删除升级为批量删除(2026-10-02):旧版入参 record_id(兼容 recordId)、响应 { record_id, deleted, total_items, checked_items, diff_items, detail_status }、记录不存在报 400「作业记录不存在或不属于该盘点任务」;新版入参 record_ids 数组(单次上限 200)、响应 { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status }、查不到计入 skipped_ids 不报错(旧版 record_id/deleted 响应字段与「作业记录不存在」错误文案不再返回)。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径见 data.children。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" + ] + }, + { + "method": "stock.check.recheckClearLocation", + "description": "重盘清除库位(按库位清除盘点信息,库位盘点模式专属):传盘点任务ID与库位ID,清除该库位范围内明细(scope_type=location)的全部作业记录(含空库位标记),该库位回到未盘;仅任务范围为库位(type=location)且状态 approved/checking 允许;删除后清理被删记录图片引用(失败仅告警不影响主流程)、重算 checked_items/diff_items/detail_status(主表状态不回退)、写 STOCK_CHECK_CLEAR_LOCATION 操作日志。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + }, + { + "name": "location_id", + "type": "number", + "required": true, + "source": "body", + "description": "库位ID(wms_location_space.id)" + }, + { + "name": "locationId", + "type": "number", + "required": false, + "source": "body", + "description": "库位ID(驼峰别名,兼容写法;location_id 优先)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内;失败时 data=null)", + "children": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "description": "该库位范围明细ID(wms_stock_check_detail.id)" + }, + { + "name": "location_id", + "type": "number", + "required": true, + "description": "库位ID(与入参一致,wms_location_space.id)" + }, + { + "name": "deleted_count", + "type": "number", + "required": true, + "description": "删除的作业记录条数(该库位范围明细下全部作业记录,含空库位标记)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "明细总行数" + }, + { + "name": "checked_items", + "type": "number", + "required": true, + "description": "重算后的已盘行数(存在作业记录的明细数)" + }, + { + "name": "diff_items", + "type": "number", + "required": true, + "description": "重算后的差异行数(实盘合计与账面快照不一致的明细数;未知商品无账面,实盘>0 即盘盈、必然计入差异)" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "重算后的明细盘点进度:none_checked/partial_checked/all_checked" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空" + }, + { + "code": 400, + "message": "库位ID不能为空" + }, + { + "code": 400, + "message": "盘点任务不存在" + }, + { + "code": 400, + "message": "当前状态(非 approved/checking)不允许清除库位盘点信息" + }, + { + "code": 400, + "message": "仅库位盘点任务支持重盘清除库位" + }, + { + "code": 400, + "message": "该库位不在盘点任务范围内" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "校验顺序口径(按代码实现顺序):任务ID 非正整数 → 400「盘点任务ID不能为空」;库位ID 非正整数 → 400「库位ID不能为空」;任务不存在(按 id+warehouse_id 查 wms_stock_check)→ 400「盘点任务不存在」;状态非 REPORT_ALLOWED_STATUSES(approved/checking)→ 400「当前状态(xx)不允许清除库位盘点信息」;任务范围非库位(type≠location)→ 400「仅库位盘点任务支持重盘清除库位」;库位不在任务范围(按 check_id+warehouse_id+location_id+scope_type=location 查 wms_stock_check_detail)→ 400「该库位不在盘点任务范围内」。代码依据:app/service/systems/stock_check.js#recheckClearLocation。", + "行为口径:清除该库位范围内明细(scope_type=location)的全部作业记录(wms_stock_check_record,含空库位标记记录 is_empty=1),该库位回到未盘(明细无作业记录);删除后清理被删记录图片引用(FileReference business_type=stock_check_record,失败仅告警不影响主流程)、重算 checked_items/diff_items/detail_status(_recalcCheckSummary),主表状态不回退;写操作日志 operationCode=STOCK_CHECK_CLEAR_LOCATION(文案「重盘清除库位:删除作业记录 N 条」)。warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递。", + "权限口径:随 ALL_METHOD_NAMES(22 个,已由 21 增至 22、本次加入 recheckClearLocation,位于 recordDelete 之后)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为写操作,不在免日志清单(_noNeedLog)中,记录操作日志(STOCK_CHECK_CLEAR_LOCATION)。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内({ detail_id, location_id, deleted_count, total_items, checked_items, diff_items, detail_status })。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.recheckClearLocation 一条(位于 stock.check.recordDelete 之后);分组内各 method notes 的「统一包装」描述由 21 个更新为 22 个、workData「权限口径」note 的 ALL_METHOD_NAMES 清单更新为 22 个(加入 recheckClearLocation);根版本 0.3.235 → 0.3.236、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);stock.check 分组由 21 条增至 22 条。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production + --env production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。" + ] + }, + { + "method": "stock.check.finish", + "description": "完成盘点作业(允许部分未盘完成):仅 approved/checking 状态允许;未盘商品明细=无作业记录(wms_stock_check_record)的明细,按实盘 0 处理(差异=-账面快照,计入盘亏与差异行数);未盘库位明细行因无法枚举商品不计差异;已盘商品明细按作业记录数量合计与账面快照(system_quantity)对比聚合;已盘库位明细按商品聚合实盘 vs wms_storage 账面(space_id+stock_id SUM(available_quantity)=可用数量,space_id 为空时账面按 0)对比聚合;盘盈=正差异合计、盘亏=负差异绝对值合计;完成后主表置 completed、回填 end_time(完成盘点的时间)、detail_status=all_checked,返回差异汇总(盘盈/盘亏合计)与未盘明细数(unchecked_items)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)(另含 released_stock_ids:本次完成释放的静态锁定商品ID数组)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "盘点任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "完成后的主表状态(completed)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "明细总行数" + }, + { + "name": "checked_items", + "type": "number", + "required": true, + "description": "已盘行数(存在作业记录的明细数)" + }, + { + "name": "unchecked_items", + "type": "number", + "required": true, + "description": "未盘明细数(无作业记录的明细数;未盘商品明细按实盘 0 处理计为盘亏,未盘库位明细不计差异)" + }, + { + "name": "diff_items", + "type": "number", + "required": true, + "description": "差异行数(商品行实盘合计与账面快照不一致、库位行任一商品实盘与账面不一致的明细数,未盘商品明细按实盘 0 计入)" + }, + { + "name": "profit_total", + "type": "number", + "required": true, + "description": "盘盈合计(商品行:作业记录数量合计大于账面快照的差异合计;库位行:按商品实盘大于 wms_storage 账面(SUM(available_quantity)=可用数量)的差异合计)" + }, + { + "name": "loss_total", + "type": "number", + "required": true, + "description": "盘亏合计(商品行:实盘小于账面快照的差异绝对值合计,含未盘明细的账面快照数;库位行:按商品实盘小于 wms_storage 账面的差异绝对值合计)" + }, + { + "name": "released_stock_ids", + "type": "array", + "required": true, + "description": "本次完成盘点释放的静态锁定商品ID数组(本任务商品明细覆盖的 stock_id,升序;库位盘点任务为空数组)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在 / 当前状态(非 approved/checking)不允许完成盘点" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "库位行账面口径:wms_storage 按 (space_id, stock_id) SUM(available_quantity)(=可用数量,不含锁定待出库),与 detail 接口的 stocks 账面一致。", + "未盘库位明细行无法枚举商品(无作业记录即无商品维度),完成时不计差异、不计盘盈盘亏。", + "end_time 语义:完成盘点时主表写入 end_time(完成盘点的时间);接口响应不返回 end_time(响应结构不变:id/status/total_items/checked_items/unchecked_items/diff_items/profit_total/loss_total),主表时间字段请通过 detail/result/list 查看。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "完成即释放锁定(本次,0.3.313):finish 成功后清除本仓库静态锁定缓存(stock_check:static_lock:{warehouseId}),并返回 released_stock_ids(本任务商品明细覆盖的 stock_id,升序;库位任务为空数组),操作日志 STOCK_CHECK_FINISH 的 extras 同步落 releasedStockIds 与「释放静态锁定商品 N 个」文案;若同一商品仍被其它 approved/checking 的静态任务覆盖,则仍保持锁定(缓存回源后自动保留其它任务)。缓存清除失败只记 warn 日志不影响完成主流程,靠 300 秒 TTL 兜底。代码依据:app/service/systems/stock_check.js#finish/#_collectGoodsStockIds/#clearStaticLockCache。", + "缓存代次(本次,0.3.315):本方法成功后调用 refreshStaticLockCache——先递增 `stock_check:static_lock_gen:{warehouseId}` 再重建锁定缓存,使并发中的旧回源自动失效,避免脏读。" + ] + }, + { + "method": "stock.check.submit", + "description": "完成盘点任务(提交审核):仅 created/rejected 状态允许;校验 total_items>0(无明细行时拒绝)后主表置 submitted(待审核);所有明细行(库位型 scope_type=location 与商品型 scope_type=goods)缺少库位(location_id 为空或 location_code 为空/空串)时不可提交(脏数据防御;商品任务按「商品+库位」拆行后商品行同样必须带库位,正常流程 addDetail/addLocationDetail 不会产生此类明细)。商品范围任务(scope_type=goods)提交时刷新明细行账面快照(提交即快照,快照失败则提交失败):按「商品+库位」把各明细行 system_quantity 刷新为该库位当时账面 SUM(available_quantity)(库存记录不存在时按 0);明细表本身已按「商品+库位」完整记录快照,主表不额外写快照;库位范围任务(scope_type=location)账面实时查 wms_storage,不处理。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "盘点任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "提交后的主表状态(submitted)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在 / 当前状态(非 created/rejected)不允许提交审核 / 盘点任务还没有明细行,无法提交审核 / 存在缺少库位的盘点明细,无法提交审核" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "提交时账面快照口径(本次新增):商品范围任务(scope_type=goods)提交审核时把各明细行 system_quantity 刷新为该库位当时账面 SUM(available_quantity)(库存记录不存在按 0),保证 result/差异对比使用提交时点的账面(添加明细到提交之间库存变动以提交时点为准);明细表本身已按「商品+库位」完整记录快照,主表不额外写快照(scope_snapshot 保持 null);驳回(rejected)后重新提交会重新刷新;库位范围任务(scope_type=location)不处理(账面实时查 wms_storage)。代码依据:app/service/systems/stock_check.js#submit/#_refreshGoodsBookSnapshotOnSubmit。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "提交校验口径(本次扩展):全部明细行(库位型 scope_type=location 与商品型 scope_type=goods)缺少库位(location_id 为空或 location_code 为空/空串)时抛 400「存在缺少库位的盘点明细,无法提交审核」——校验不再限定 scope_type=location(商品任务按「商品+库位」拆行后商品行同样必须带库位),脏数据防御,正常流程 addDetail/addLocationDetail 写入的明细均带有效库位。代码依据:app/service/systems/stock_check.js#submit(StockCheckDetail.count where check_id+(location_id 为空或 location_code 为空/空串)>0 即拒绝,不再按 scope_type 过滤)。本次代码已改并测试通过 213/213、ESLint 0 错误。", + "影响面:前端无需改动——该校验拦截缺库位明细(含商品拆行后缺库位的历史脏数据),正常盘点流程不受影响;原有校验顺序不变(任务ID 为空→任务不存在→状态非 created/rejected→无明细行→缺库位明细)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.addDetail:description/params/response/notes 补商品拆行口径(拆多行、无库存库位 invalid、system_quantity=该库位账面、added=拆分行数);stock.check.detail:description/response.rows/notes 商品行 location_id/location_code 绑定库存库位;stock.check.submit:description/notes 缺库位校验改为覆盖全部明细行;stock.check.patternCreate:description/notes 补 goods 定式按库存库位拆行;stock.check.addLocationDetail:notes 幂等索引口径同步 uk_check_location 唯一约束放宽为普通索引 idx_check_location);根版本 0.3.237 → 0.3.238、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 与变更记录后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 22 条 method 无损。", + "快照刷新口径补充(本次,0.3.312):submit 仍会在提交时刷新商品范围明细账面快照(提交时点账面);若任务随后审核通过,audit 会再次刷新为「审核完成=开始盘点」时点的账面,最终以审核时点为准。" + ] + }, + { + "method": "stock.check.cancel", + "description": "取消盘点任务:仅 created/submitted/rejected 状态允许;取消后主表置 cancelled(终态)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "盘点任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "取消后的主表状态(cancelled)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在 / 当前状态(非 created/submitted/rejected)不允许取消" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" + ] + }, + { + "method": "stock.check.audit", + "description": "审核盘点任务(approve 通过时会把商品范围明细的账面快照刷新为审核时点账面,并解除/进入静态盘点锁定缓存):仅 submitted 状态允许;action=approve → 主表置 approved(审核完成,待盘点作业);action=reject → 主表置 rejected(驳回,可重新添加明细再提交),reason 可选(缺省保留原备注)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + }, + { + "name": "action", + "type": "string", + "required": true, + "source": "body", + "description": "审核动作:approve=通过 / reject=驳回" + }, + { + "name": "reason", + "type": "string", + "required": false, + "source": "body", + "description": "驳回原因(写入备注,可选;缺省保留原备注)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "盘点任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "审核后的主表状态:approved(通过)/ rejected(驳回)" + }, + { + "name": "snapshot_refreshed", + "type": "number", + "required": true, + "description": "本次刷新账面快照的商品明细行数(仅 approve 且值发生变化时非 0;驳回或无需刷新为 0)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 审核动作仅支持 approve/reject / 盘点任务不存在 / 当前状态(非 submitted)不允许审核" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "审核刷新快照 + 解锁缓存(本次,0.3.312):① approve 时调用 _refreshGoodsBookSnapshot 把 scope_type=goods 明细行的 system_quantity 刷新为该库位当前账面 SUM(可用数量)(提交审核后到审核前发生的出入库会被覆盖,保证「审核完成=开始盘点」即基准时点),返回新增 snapshot_refreshed 字段(本次刷新的明细行数,仅值有变化的行计数;驳回恒 0);② approve/reject 均清除静态盘点锁定缓存(approve 使 is_static 任务进入锁定集合):submit 时已刷新一次快照,audit approve 再刷新一次,两者共同保证快照口径。代码依据:app/service/systems/stock_check.js#audit/#_refreshGoodsBookSnapshot。", + "缓存代次(本次,0.3.315):本方法成功后调用 refreshStaticLockCache——先递增 `stock_check:static_lock_gen:{warehouseId}` 再重建锁定缓存,使并发中的旧回源自动失效,避免脏读。" + ] + }, + { + "method": "stock.check.batchDelete", + "description": "批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过):入参 ids(盘点任务ID数组,兼容单值,服务端归一化为去重后的正整数,单次上限 200),warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,前端无需传递;按 id in ids + warehouse_id 查询主表做仓库隔离;状态分流:status=cancelled(作废)的任务级联删除,其他状态及查不到的任务跳过(计入 skipped_ids);删除级联顺序(事务内):先删作业记录(wms_stock_check_record,where check_id in 删除集),再删明细(wms_stock_check_detail,where check_id in 删除集),最后删主表(wms_stock_check,where id in 删除集);返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids },deleted_ids/skipped_ids 保持入参顺序。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "盘点任务ID数组(兼容单值;服务端归一化为去重后的正整数,单次上限 200)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "total", + "type": "number", + "required": true, + "description": "入参去重后的任务ID数量" + }, + { + "name": "deleted_count", + "type": "number", + "required": true, + "description": "实际删除的任务数量(仅作废任务)" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "跳过的任务数量(非作废状态或查不到的任务)" + }, + { + "name": "deleted_ids", + "type": "array", + "required": true, + "description": "已删除的任务ID列表(保持入参顺序)" + }, + { + "name": "skipped_ids", + "type": "array", + "required": true, + "description": "跳过的任务ID列表(保持入参顺序)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文 / ids 不能为空 / 单次最多删除 200 个盘点任务" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "仅作废(status=cancelled)任务执行删除;其他状态及仓库内查不到的任务跳过(计入 skipped_ids,保持入参顺序),不视为业务错误。", + "级联删除在事务内执行,顺序为:作业记录(StockCheckRecord)→ 明细(StockCheckDetail)→ 主表(StockCheck)。", + "写操作:随 ALL_METHOD_NAMES(16 个 method)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权,需登录(isNeedLogin=true);不在免日志清单(_noNeedLog),保留操作日志。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" + ] + }, + { + "method": "stock.check.export", + "description": "提交盘点任务导出任务(异步):Excel 分两个 Sheet 生成——Sheet1「盘点单」一行一个盘点任务(盘点单号/盘点名称/盘点范围/盘点方式/盘点状态/盘点进度/货主ID/创建人/明细行数/已盘行数/差异行数/开始时间/结束时间/备注;主表移除 check_date 后已移除「盘点日期」列,保留开始/结束时间列);Sheet2「盘点明细」一行一条实际盘点记录(作业记录 wms_stock_check_record,列:盘点单号/商品编码/商品名称/库位编码(空库位输出为空)/实盘数量/盘点人/盘点时间;未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、商品名称列显示上报名称快照(item_name),已知商品快照从 wms_stock_warehouse 补齐;空库位记录(is_empty=1)商品编码列输出「(空库位)」、商品名称为空、实盘数量输出 0),未盘的任务范围行不再导出;ExcelJS 流式生成后上传 COS;进度通过 Redis 缓存(key stock_check_export_task_*,TTL 1800 秒)追踪,立即返回任务ID;单次最多 50 个盘点任务。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "盘点任务ID数组(兼容单值;与 task_ids 二选一,优先级高于 task_ids)" + }, + { + "name": "task_ids", + "type": "array", + "required": false, + "source": "body", + "description": "盘点任务ID数组(兼容别名)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID(格式 stock_check_export_{warehouseId}_{时间戳}_{随机串})" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理明细行数(Sheet2 已写入的作业记录行数)" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "Sheet2 盘点明细总行数(作业记录总数,导出前即确定)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "任务成功时的结果对象(含 filename/fileKey/url/cdnUrl/cosUrl)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "最近一次状态更新时间戳(毫秒)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "请至少选择一个盘点任务 / 单次最多导出 50 个盘点任务" + }, + { + "code": 400, + "message": "未找到可导出的盘点任务" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "兼容 ids / task_ids 两种入参写法,ids 优先;自动去重并过滤非正整数。", + "异步执行:查询任务与作业记录(wms_stock_check_record,不按任务范围行展开)→ 商品快照从 wms_stock_warehouse 补齐(item_code/item_name)→ ExcelJS 流式写入(Sheet1「盘点单」一行一个盘点任务;Sheet2「盘点明细」一行一条实际盘点记录,列:盘点单号/商品编码/商品名称/库位编码(空库位输出为空)/实盘数量/盘点人/盘点时间,未盘的任务范围行不导出)→ COS 上传。", + "进度缓存 Redis key stock_check_export_task_{taskId},TTL 1800 秒;totalCount=作业记录总数(导出前即确定),进度按已写入明细行数/总数计算(每 200 行汇报一次)。", + "Sheet1「盘点单」一行一个盘点任务,列:盘点单号/盘点名称/盘点范围/盘点方式/盘点状态/盘点进度/货主ID/创建人/明细行数/已盘行数/差异行数/开始时间/结束时间/备注(主表移除 check_date 后不再导出「盘点日期」列,保留开始/结束时间列);Sheet2「盘点明细」由『按任务范围行展开(含未盘空行)』调整为『一行一条实际盘点记录(作业记录)』,未盘的任务范围行不再导出。", + "未知商品导出口径:stock_id 为空的记录商品编码列输出扫描条码(barcode,空则留空)、商品名称列输出上报名称快照(item_name 或 barcode 兜底);已知商品维持 wms_stock_warehouse 商品快照(item_code/item_name)。代码依据:app/service/systems/stock_check.js#exportStockChecks/#_generateAndUploadStockCheckExcel。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "空库位标记导出口径(本次新增):Sheet2「盘点明细」空库位记录(is_empty=1)商品编码列输出『(空库位)』、商品名称列为空、实盘数量输出 0(row.is_empty ? '(空库位)' : (row.item_code || '')、row.is_empty ? '' : (row.item_name || '')、row.is_empty ? 0 : (Number(row.quantity) || 0))。代码依据:app/service/systems/stock_check.js#_generateAndUploadStockCheckExcel。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.report:params 新增 is_empty 入参、errors 400 补「仅库位盘点明细支持空库位标记」、description/response/notes 补充空库位语义与互斥及汇总口径;stock.check.workData:description/response.rows 的 location 行新增 is_empty 字段说明;stock.check.result:description/response.rows 库位行新增 is_empty 与空标记盘亏口径;stock.check.recordList:response.rows 记录全字段说明新增 is_empty;stock.check.export:description/notes 补 Sheet2 空库位行输出口径);根版本 0.3.233 → 0.3.234、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "method": "stock.check.exportDetail", + "description": "提交盘点明细导出任务(异步,单任务,按盘点范围分流):商品范围任务(scope_type=goods)固定两个 Sheet——Sheet1「汇总和差异」(每商品一行,列:盘点单号/商品编码/条码(wms_stock_barcodes 第一条)/商品名称/规格/账面数量(明细行 system_quantity 快照合计,提交审核时刷新)/盘点数量/差异数量/差异类型(盘盈|盘亏,无差异或未盘留空);未知商品(条码维度,无账面、差异=实盘=盘盈)追加在末尾)+ Sheet2「库位明细」(直接按作业记录 wms_stock_check_record 一行一条实际盘点记录,列:库位编码/数量(实盘)/条码(wms_stock_barcodes 第一条)/商品名称;未知商品条码=扫描条码);库位范围任务(scope_type=location)Sheet「盘点明细」(作业记录口径,列:库位编码/商品编码/商品名称/盘点数量;未知商品编码=扫描条码、空库位标记商品为空数量 0)。库位编码列显示覆盖(两 sheet 均生效):自定义名称(custom_name)优先 → 自定义编码(custom_barcode)次之 → 库位编码(space_code)兜底。ExcelJS 流式生成后上传 COS;进度通过 Redis 缓存(key stock_check_export_task_*,TTL 1800 秒)追踪,立即返回任务ID;进度查询复用 stock.check.exportTaskProgress。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID(格式 stock_check_export_{warehouseId}_{时间戳}_{随机串})" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理明细行数" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "导出总行数(库位范围=作业记录数;商品范围=汇总行数(商品数+未知商品数)+库位明细行数,导出前即确定)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "任务成功时的结果对象(含 filename/fileKey/url/cdnUrl/cosUrl)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "任务失败时的错误信息(成功时为空串)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "缓存更新时间(毫秒时间戳)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "权限口径:随 ALL_METHOD_NAMES 免 API 权限(isNeedAuth=false)、免仓库有效期鉴权、必须登录(isNeedLogin=true);加入免日志清单 _noNeedLog。", + "异步执行:查询任务/明细/作业记录 → 商品范围复用 result 的商品合并聚合(账面=明细行 system_quantity 快照、实盘=作业记录聚合)→ ExcelJS 流式写入 → COS 上传;进度缓存 Redis key stock_check_export_task_{taskId},TTL 1800 秒;进度查询复用 stock.check.exportTaskProgress(task_id 通用)。", + "商品盘点固定两个 Sheet:Sheet1「汇总和差异」每商品一行(盘点单号/商品编码/条码(wms_stock_barcodes 按 stock_id 第一条)/商品名称/规格/账面=各库位快照合计、盘点=实盘合计、差异=盘点-账面,未盘商品盘点/差异留空;差异类型:正=盘盈、负=盘亏、无差异/未盘留空);未知商品(stock_id 为空按条码归组)无账面,追加在汇总末尾(差异=实盘=盘盈,商品编码列即扫描条码、条码列留空)。Sheet2「库位明细」直接按作业记录(wms_stock_check_record)一行一条实际盘点记录,列仅库位编码/数量(实盘)/条码(wms_stock_barcodes 按 stock_id 第一条)/商品名称(未知商品条码=扫描条码)。", + "库位编码列显示覆盖(库位范围盘点明细 sheet 同样生效):自定义名称(custom_name)优先 → 自定义编码(custom_barcode)次之 → 库位编码(space_code)兜底;记录库位编码为空或查不到库位时按原库位编码(空则留空)。代码依据:app/service/systems/stock_check.js#_resolveLocationDisplayCode。", + "库位范围任务:Sheet「盘点明细」作业记录口径(库位编码/商品编码/商品名称/盘点数量),已知商品编码名称从 wms_stock_warehouse 补齐、未知商品编码=扫描条码(barcode)、名称=上报名称快照;空库位标记记录商品编码为空、盘点数量 0;mode 入参忽略。", + "代码依据:app/service/systems/stock_check.js#exportCheckDetail/#_generateAndUploadCheckDetailExcel/#_uploadExportExcelFile(原 _generateAndUploadStockCheckExcel 上传段抽为公共方法复用)+ app/service/systemMethods/stock/check.js#exportDetail。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(23 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.exportDetail 一条(位于 stock.check.export 之后);根版本 0.3.260 → 0.3.261、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 24 条 method 未改动(stock.check 分组由 24 条增至 25 条)。" + ] + }, + { + "method": "stock.check.exportTaskProgress", + "description": "查询盘点任务导出进度:按 task_id(兼容 taskId 驼峰写法)读取 Redis 任务缓存;任务不存在时正常返回(status=not_found),不视为错误;任务成功时 download_url 从 result 兜底提取(url/cdnUrl/cosUrl/fileKey)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "任务ID(下划线写法)" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "任务ID(驼峰写法)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID(未传任务ID时为空字符串)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理明细数" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "明细总行数" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "任务成功时的结果对象(含 filename/fileKey/url/cdnUrl/cosUrl)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选)" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务完成后可直接下载的文件地址(从 result 兜底提取,未完成或未找到时为空字符串)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "最近一次状态更新时间戳(毫秒)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "任务不存在为正常响应(status=not_found),非业务错误。", + "进度缓存 Redis key stock_check_export_task_{taskId},TTL 1800 秒。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" + ] + }, + { + "method": "stock.check.patternList", + "description": "拉取盘点定式清单(供前端选择定式快速创建盘点任务):返回代码注册的 5 个内置定式(注册于 app/service/systems/stock_check_patterns.js,不建表),每条含 id/name/description/type;无入参。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "patterns", + "type": "array", + "required": true, + "description": "盘点定式列表(共 5 条:空库位/错发/临期/静态/预警),每条含 id/name/description/type", + "children": [ + { + "name": "id", + "type": "string", + "required": true, + "description": "定式唯一标识(patternCreate 的 pattern_id 入参):empty_location=空库位盘点 / mis_shipment=错发盘点 / expiring=临期盘点 / static=静态盘点 / warning=预警盘点" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "定式名称(创建任务时作为默认标题)" + }, + { + "name": "description", + "type": "string", + "required": true, + "description": "定式描述(含对象收集口径,详见 notes)" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "对应盘点任务 type:location=按库位(仅 empty_location)/ goods=按商品(其余 4 个)" + } + ] + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "定式总数(当前为 5)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "5 个定式口径(与代码注释一致):① empty_location 空库位盘点(type=location):wms_location_space 中启用且未删除、在 wms_storage 不存在任何 quantity>0 库存记录的账面空库位;② mis_shipment 错发盘点(type=goods):登记过错发工单(wms_after_sale type=order 且 sub_type=mis_shipment,凡登记过即纳入、排除 closed/cancelled 状态)关联订单的商品按 stock_id 去重;③ expiring 临期盘点(type=goods):开启保质期管理(wms_stock_warehouse.is_shelf_life_mgmt=Y)且存在临期库存(最早到期日 <= 当前时间+该商品 remaining_threshold_days 天,阈值 <=0 时按已到期)的商品维度去重;④ static 静态盘点(type=goods):最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction)距今超过仓库配置 stock_static_hours 小时(默认 168,无流水按 wms_stock_warehouse.create_at)且未进入 wms_stock_static_check_task 的商品;⑤ warning 预警盘点(type=goods):库存 quantity < 仓库配置 stock_warning_quantity 的商品(要求仓库配置 stock_warning_enabled=true 才可执行)。", + "查询类接口:免 API 权限(isNeedAuth=false)、免仓库有效期鉴权、必须登录(isNeedLogin=true);在免日志清单(_noNeedLog)中,不记录操作日志。", + "返回字段仅对外 4 个(id/name/description/type),不含内部执行函数。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" + ] + }, + { + "method": "stock.check.patternCreate", + "description": "按定式快速创建盘点任务:入参 pattern_id(兼容 patternId 驼峰写法,pattern_id 优先)+ 可选 title/remark;warehouse_id 与创建人由服务端从登录上下文(ctx.user.store_id / ctx.user.id / employees_name)自动注入,前端无需传递;盘点方式由定式范围类型固定:库位类定式(empty_location,type=location)一律盲盘 blind、商品类定式(type=goods,其余 4 个)一律明盘 open;盘点方式与盘点时间均无需前端传入(主表已无 check_date,start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间),由盘点作业流程自动回填);按定式收集盘点对象(goods 型得到 stock_ids、location 型得到库位列表),goods 型明细同样按「商品+库位」拆行(商品任务必须按库位盘点,同 addDetail 商品路径),无符合条件对象报 400;创建后主表状态直接 submitted(进入待审核)、detail_status=none_checked、total_items 按明细重算;static 定式在任务创建成功后把命中的 stock_id 批量写入 wms_stock_static_check_task(失败不影响主流程);写操作,记录操作日志。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "pattern_id", + "type": "string", + "required": true, + "source": "body", + "description": "定式ID:empty_location=空库位盘点 / mis_shipment=错发盘点 / expiring=临期盘点 / static=静态盘点 / warning=预警盘点(兼容 patternId 驼峰写法,两者都传时 pattern_id 优先)" + }, + { + "name": "patternId", + "type": "string", + "required": false, + "source": "body", + "description": "定式ID(驼峰别名,兼容写法)" + }, + { + "name": "title", + "type": "string", + "required": false, + "source": "body", + "description": "盘点名称/主题,缺省取定式 name" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "check", + "type": "object", + "required": true, + "description": "创建后的盘点任务信息(_formatCheckRow 口径:id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at,无 check_date);status 直接为 submitted(待审核),mode 由定式范围类型固定(location→blind、goods→open),start_time/end_time 创建时为空(分别由首个盘点明细写入与完成盘点回填)(另含 is_static:静态定式创建的任务为 1,其余为 0)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "明细总行数(创建明细后按 wms_stock_check_detail 重算)" + }, + { + "name": "pattern_id", + "type": "string", + "required": true, + "description": "本次创建使用的定式ID" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文 / 盘点定式不存在 / 当前仓库没有账面为空的库位 / 没有符合条件的商品 / 未开启库存预警" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "5 个定式口径(与代码注释一致):① empty_location 空库位盘点(type=location):wms_location_space 中启用且未删除、在 wms_storage 不存在任何 quantity>0 库存记录的账面空库位;② mis_shipment 错发盘点(type=goods):登记过错发工单(wms_after_sale type=order 且 sub_type=mis_shipment,凡登记过即纳入、排除 closed/cancelled 状态)关联订单的商品按 stock_id 去重;③ expiring 临期盘点(type=goods):开启保质期管理(is_shelf_life_mgmt=Y)且存在临期库存(最早到期日 <= 当前时间+remaining_threshold_days 天,阈值 <=0 时按已到期)的商品维度去重;④ static 静态盘点(type=goods):最后一次 INBOUND/OUTBOUND 流水距今超过仓库配置 stock_static_hours 小时(默认 168,无流水按 wms_stock_warehouse.create_at)且未进入 wms_stock_static_check_task 的商品;⑤ warning 预警盘点(type=goods):库存 quantity < 仓库配置 stock_warning_quantity 的商品(要求仓库配置 stock_warning_enabled=true 才可执行,未开启报 400「未开启库存预警」)。", + "盘点方式与盘点时间固定规则(前端不传):盘点方式由定式范围类型固定——库位类定式(type=location,即 empty_location)一律盲盘(blind)、商品类定式(type=goods,其余 4 个定式)一律明盘(open);盘点时间不传(主表已无 check_date,start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间),由盘点作业流程自动回填);入参已移除 mode/check_date。", + "状态口径:创建后主表 status 直接 submitted(进入待审核)、detail_status=none_checked,无需再调 stock.check.submit;store_id/scope_snapshot 为空,type 取定式类型(location/goods),mode 由定式范围类型固定(location→blind、goods→open),start_time/end_time 创建时为空。", + "static 定式静态记录表口径:收集阶段排除 wms_stock_static_check_task 已有记录(未删除)的 stock_id(已进入静态已盘点商品);任务创建成功后把本次命中的 stock_id 批量写入该表(task_time=创建时间),写入失败仅记告警日志、不影响主流程。", + "权限口径:免 API 权限(isNeedAuth=false)、免仓库有效期鉴权、必须登录(isNeedLogin=true);patternCreate 为写操作,不在免日志清单(_noNeedLog)中,记录操作日志(patternList 为查询类,免日志)。", + "单号生成:check_no=PD+YYYYMMDD+6 位序号(全局递增不按仓库隔离),并发下撞 uk_check_no 唯一键自动重取重试(最多 5 次)。", + "goods 定式拆行口径(本次改造):商品类定式(mis_shipment/expiring/static/warning,type=goods)收集到 stock_ids 后走 _addGoodsDetailRows 同款逻辑——按商品在仓库的启用库存库位(wms_storage is_enabled=1 且库位有效(未删除且所属 zone 存在未删除,排除无头库位),按 space_id 分组 SUM)拆行,每个「商品+库位」一条 scope_type=goods 明细行(location_id/location_code 绑定库存库位、system_quantity=该库位库存 SUM);无启用库存库位的商品不产生明细行,total_items 按拆分行重算。代码依据:app/service/systems/stock_check.js#patternCreate(pattern.type==='goods' 调 _addGoodsDetailRows)。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "静态定式自动标记(本次,0.3.310):patternCreate 按定式创建任务时,pattern_id=static(静态盘点定式)的主表 is_static 自动写 1,其余定式(empty_location/mis_shipment/expiring/warning)写 0;返回的 check 与 GET 一样透出 is_static。代码依据:app/service/systems/stock_check.js#patternCreate(normalizedIsStatic = pattern.id === 'static' ? 1 : 0)。", + "静态定式口径收窄(本次,0.3.311):只有 pattern=static(商品类定式,type=goods)创建的任务 is_static=1;库位类定式(empty_location 等 type=location)与其它商品定式(mis_shipment/expiring/warning)均为 0,保证「库位盘点恒为普通盘点」。代码依据:app/service/systems/stock_check.js#patternCreate(pattern.id === 'static' && pattern.type !== 'location')。" + ] + }, + { + "method": "stock.check.addLocationDetail", + "description": "批量添加库位明细(兼容入口,薄封装转调 addDetail 的库位ID直查路径):入参 id(盘点任务ID)+ location_ids(库位ID列表,兼容 locationIds 驼峰写法);服务端直接按 wms_location_space.id+warehouse_id 查库校验(库位必须有效:未删除且所属 zone 存在未删除,无头库位记入 invalid_location_ids),不经过 space_code 二次解析;转发前保留旧口径参数校验(任务ID不能为空、库位ID不能为空、单次上限 200),任务存在性/状态/类型分派校验统一由 addDetail 处理;幂等添加 scope_type=location 明细行,已存在的同库位明细自动跳过;返回结构从 addDetail 映射为 { added, skipped, invalid_location_ids, total_items }(过滤 invalid_locations/invalid_stock_ids),保持原返回口径不变。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + }, + { + "name": "location_ids", + "type": "array", + "required": true, + "source": "body", + "description": "库位ID列表(wms_location_space.id,单次上限 200;兼容 locationIds 驼峰写法,location_ids 优先)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "added", + "type": "number", + "required": true, + "description": "本次新增明细数" + }, + { + "name": "skipped", + "type": "number", + "required": true, + "description": "已存在被跳过(幂等)的盘点项数" + }, + { + "name": "invalid_location_ids", + "type": "array", + "required": true, + "description": "无效库位ID列表(按 wms_location_space.id 直查当前仓库不存在)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "重算后的明细总行数" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 请至少选择一个库位 / 单次最多添加 200 个库位 / 盘点任务不存在 / 当前状态(非 created/rejected)不允许添加明细 / 当前盘点类型按商品盘点,不能添加库位明细" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "兼容入口:保留旧接口名与返回结构({ added, skipped, invalid_location_ids, total_items }),内部转调 addDetail 库位ID直查路径(stockIds/locations 置空、传 locationIds),返回结构过滤 invalid_locations/invalid_stock_ids 保持原口径。", + "转发前校验:任务ID不能为空、库位ID不能为空(请至少选择一个库位)、单次上限 200(超过报『单次最多添加 200 个库位』);任务不存在/状态不允许/商品任务不可添加库位明细由 addDetail 透传同款错误。", + "ID 直查:按 wms_location_space.id+warehouse_id 直查校验(仓库隔离),查不到的 ID 记入 invalid_location_ids(不报错);幂等按 check_id+location_code(原 uk_check_location 唯一约束已放宽为普通索引 idx_check_location,幂等由应用层查重保证),已存在同库位明细跳过。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" + ] + }, + { + "method": "stock.check.staticLockList", + "description": "拉取「静态盘点锁定中」的库存商品列表(公共查询,供出入库/移库等库存操作前置判断是否可以动该商品):warehouse_id 由服务端从当前上下文自动注入,前端无需传参;口径为 wms_stock_check 中 is_static=1 且状态为 approved(审核完成)/checking(盘点作业中)的任务,取其商品范围明细(scope_type=goods)的 stock_id 去重集合——审核完成即开始锁定,任务完成/取消后解除;提交审核前(created/submitted/rejected)与已完成/已取消均不锁定;库位盘点任务 is_static 恒为 0,天然不参与。结果按仓库维度缓存在 `stock_check:static_lock:{warehouseId}`(默认 TTL 300 秒,Redis 优先、不可用时降级进程内缓存),审核/完成/取消/批量删除等状态流转时主动失效,返回 cached 标识本次是否命中缓存。返回 { warehouse_id, stock_ids, rows, total, cached, updated_at }:stock_ids 为锁定商品ID数组(升序);rows 每个 stock_id 一条 { stock_id, item_code, item_name, check_ids 来源盘点任务ID数组, check_nos 来源盘点单号数组, location_codes 该商品在盘子任务中的库位编码数组 };total=rows 行数;cached=true 表示命中缓存;updated_at=缓存生成时间(ISO 8601,命中缓存时为上次回源时间)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装;失败时 data=null)", + "children": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(由 ctx.user.store_id 注入)" + }, + { + "name": "stock_ids", + "type": "array", + "required": true, + "description": "静态盘点锁定中的库存商品ID数组(wms_stock_warehouse.id,按 stock_id 升序;无锁定时为空数组)" + }, + { + "name": "rows", + "type": "array", + "required": true, + "description": "锁定商品明细行(每个 stock_id 一条):stock_id 商品库存ID / item_code 商品编码(明细快照)/ item_name 商品名称(明细快照)/ check_ids 来源盘点任务ID数组 / check_nos 来源盘点单号数组 / location_codes 该商品在本任务中的库位编码数组" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "锁定商品数量(=rows.length)" + }, + { + "name": "cached", + "type": "boolean", + "required": true, + "description": "本次是否命中缓存:true=命中缓存(含审核/完成等状态流转后立即重建的缓存),false=回源数据库并已写入缓存;并发未命中时由 singleflight 共用同一次回源,各请求均返回 cached=false 且数据一致" + }, + { + "name": "cache_skipped", + "type": "boolean", + "required": false, + "description": "仅当本次回源期间检测到并发状态流转(锁定代次变化)时返回 true:表示本次结果未写入缓存(避免脏读),数据仍可正常使用" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "缓存生成时间(ISO 8601;命中缓存时为上次回源生成时间)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文(缺少 ctx.user.store_id / 未登录)" + }, + { + "code": 500, + "message": "服务器内部错误(缓存与数据库均不可用等未预期异常)" + } + ], + "notes": [ + "业务动机:静态盘点(is_static=1)期间商品库位正在清点,若同时发生出入库/移库会导致实盘数与账面基准错位;本方法对外暴露「锁定中的商品清单」并提供 isStockStaticLocked(warehouseId, stockId) 内部判断(读同一份缓存),供库存操作(出库分配、移库、拣货等)做前置拦截。", + "锁定口径:status ∈ {approved(审核完成), checking(盘点作业中)}——审核完成即开始锁定;提交审核前不锁(明细与快照仍可调整);completed/cancelled/rejected 解锁。库位盘点(type=location)的 is_static 恒为 0(见 0.3.311),因此只有商品盘点(store/goods)任务会进入锁定集合。", + "缓存设计:键 `stock_check:static_lock:{warehouseId}`,值 { warehouse_id, stock_ids, rows, updated_at },TTL 300 秒兜底;写入/读取走 app.setCacheAsync / getCacheAsync(Redis 优先,Redis 不可用或异常时降级进程内缓存)。状态流转(audit/finish/cancel/batchDelete)不是「删除缓存等下次回源」,而是**先递增锁定代次、再立即重建**:代次见 `stock_check:static_lock_gen:{warehouseId}`(Redis INCR,无 Redis 时进程内计数),回源查询前后各读一次,两次不一致说明查询期间发生过状态流转 → 本次结果可能是旧快照,**放弃写缓存并删除缓存**,交由下一次查询/该次流转的重建写入,避免脏读覆盖。", + "缓存失效时机(主动 delCacheAsync):audit(approve/reject)、finish、cancel、batchDelete;失效失败只记 warn 日志不影响主流程,靠 TTL 兜底。addDetail/detailDelete 仅在 created/rejected 状态可用(不在锁定集合内),因此不需要失效。", + "性能:回源仅 2 条查询(主表按 warehouse+is_static+status 取任务,明细按 check_id + scope_type=goods 取 stock_id),商品数量级很小;库存操作侧建议直接调 isStockStaticLocked 走缓存,避免每条单据回源。", + "代码依据:app/service/systems/stock_check.js#staticLockList/#isStockStaticLocked/#clearStaticLockCache、app/service/systemMethods/stock/check.js#staticLockList(ALL_METHOD_NAMES 25 个、免日志清单新增 staticLockList)。", + "缓存策略答疑(本次,0.3.314):① TTL=300 秒仅为兜底,正常情况每个状态流转都会立即重建缓存;② 缓存未命中会回源(2 条 SQL:主表 is_static+status,明细 scope_type=goods),但**空集合也会被缓存**,不存在「没有锁定商品 → 每次都查库」的缓存穿透;③ 失效瞬间的并发查询由进程内 singleflight(STATIC_LOCK_INFLIGHT)去重,同一仓库只回源一次,避免击穿;④ 新审核通过的任务在 audit(approve) 返回前就已完成缓存重建,之后的查询立即包含该任务,无「审核后仍读到旧缓存」的窗口(除非缓存重建失败,此时删除缓存 → 下次查询回源,仍能保证最多 300 秒内自愈);⑤ 多 worker/多实例:Redis 可用时所有实例共享同一份缓存,重建对全体生效;仅当 Redis 整体不可用时各实例退化为进程内缓存,重建只影响当前实例,其它实例最长 300 秒后(TTL)自愈——此降级场景下建议库存操作侧对「锁定判定失败/缓存不可用」采取保守策略(fail-safe,按锁定处理)。代码依据:app/service/systems/stock_check.js#staticLockList/#_loadStaticLockCache/#refreshStaticLockCache(STATIC_LOCK_INFLIGHT、STATIC_LOCK_CACHE_TTL_SECONDS)。", + "防脏读代次校验(本次,0.3.315):审核/完成/取消/批量删除统一走 refreshStaticLockCache = 递增代次 → 回源 → 写缓存;任何并发中的回源(含普通查询未命中回源)在拿到查询结果后会再读一次代次,若与查询前不一致就跳过写入(响应带 cache_skipped=true 且不落缓存),因此不会出现「旧快照后写覆盖新缓存」的脏读;读取侧仍按缓存优先,缓存为空时回源不影响正确性,最坏只多一次查询。代码依据:app/service/systems/stock_check.js#refreshStaticLockCache/#_loadStaticLockCache/#_readStaticLockGeneration/#_bumpStaticLockGeneration。" + ] + } + ] + }, + { + "groupName": "运单模块(仓库侧)", + "module": "waybill.warehouse", + "list": [ + { + "method": "waybill.warehouse.list", + "description": "运单列表-仓库侧:分页查询运单号列表,支持多条件筛选。仓库隔离(自动注入 warehouse_id = ctx.user.store_id),所有查询仅返回当前仓库数据。通过快照字段(delivery_order_code、store_id_snapshot、store_name_snapshot、warehouse_name_snapshot)避免 JOIN 订单表和货主表,列表核心查询为 wms_order_express 单表 + SELF JOIN(主单号)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token,从中解析 warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数。默认 page=1, pageSize=20" + }, + { + "name": "pagination.page", + "type": "number", + "required": false, + "source": "body.pagination", + "description": "页码,默认 1" + }, + { + "name": "pagination.pageSize", + "type": "number", + "required": false, + "source": "body.pagination", + "description": "每页条数,默认 20" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均为可选" + }, + { + "name": "where.waybillCode", + "type": "string|string[]", + "required": false, + "source": "body.where", + "description": "运单号筛选:字符串时为模糊搜索(LIKE '%值%',向后兼容);字符串数组时为精确匹配(Op.in,元素自动 trim 并过滤空值,空数组或全空值时不加该筛选条件)" + }, + { + "name": "where.mainWaybillCode", + "type": "string|string[]", + "required": false, + "source": "body.where", + "description": "主单号筛选:字符串时为精确匹配(通过主单号定位 order_id,返回该订单下所有运单(主+子));字符串数组时按 Op.in 精确匹配多个主单号,返回这些主单对应订单下的全部运单(元素自动 trim 并过滤空值;全部不存在时返回空列表;空数组或全空值时不加该筛选条件)。与 waybillCode 同时传入时按 AND 叠加,不做互斥优先级处理" + }, + { + "name": "where.orderId", + "type": "number", + "required": false, + "source": "body.where", + "description": "订单ID(等值匹配)" + }, + { + "name": "where.orderNo", + "type": "string", + "required": false, + "source": "body.where", + "description": "订单号(模糊搜索,暂不可用,待快照字段就绪)" + }, + { + "name": "where.waybillType", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单类型:\"main\"/\"1\"=主单号(business_key=1),\"child\"/\"2\"=子单号(business_key>1)" + }, + { + "name": "where.storeId", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值匹配)" + }, + { + "name": "where.logisticsCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "物流公司编码(等值匹配),如 SF/YT/STO/ZTO 等" + }, + { + "name": "where.logisticsInterfaceId", + "type": "number", + "required": false, + "source": "body.where", + "description": "物流接口ID(等值匹配),对应 wms_order_express.logistics_interface_id" + }, + { + "name": "where.platformCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "平台编码(等值匹配),如 PDD/DY/KS/JD/CAINIAO/SPH/XHS" + }, + { + "name": "where.status", + "type": "number", + "required": false, + "source": "body.where", + "description": "运单状态:0=未分配,1=已分配" + }, + { + "name": "where.isBack", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否退回:Y/N" + }, + { + "name": "where.isIntercept", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否拦截:Y/N" + }, + { + "name": "where.isGalaxyReceive", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否星河签收:Y/N" + }, + { + "name": "where.packageMaterialId", + "type": "number", + "required": false, + "source": "body.where", + "description": "包材ID(等值匹配)" + }, + { + "name": "where.hasWeighingWeight", + "type": "boolean", + "required": false, + "source": "body.where", + "description": "是否已称重:true=weighing_weight>0,false=weighing_weight=0" + }, + { + "name": "where.keyword", + "type": "string", + "required": false, + "source": "body.where", + "description": "关键词搜索:同时匹配运单号(waybill_code)、主单号、订单号" + }, + { + "name": "where.createdAt", + "type": "object", + "required": false, + "source": "body.where", + "description": "创建时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" + }, + { + "name": "where.createdAtStart", + "type": "string", + "required": false, + "source": "body.where", + "description": "创建时间起始,格式 YYYY-MM-DD(兼容旧写法)" + }, + { + "name": "where.createdAtEnd", + "type": "string", + "required": false, + "source": "body.where", + "description": "创建时间截止,格式 YYYY-MM-DD(兼容旧写法)" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数。默认 create_at desc" + }, + { + "name": "sort.field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段,白名单:create_at / weighing_weight / id" + }, + { + "name": "sort.order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向:asc / desc,默认 desc" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的运单列表数据", + "children": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "运单列表数组", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "运单记录ID(wms_order_express.id)" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "main_waybill_code", + "type": "string", + "required": true, + "description": "主单号。business_key=1 时等于 waybill_code 本身;business_key>1 时通过 SELF JOIN 查找同 order_id 下 business_key=1 的运单号" + }, + { + "name": "waybill_type", + "type": "string", + "required": true, + "description": "运单类型:business_key=1→'主单号',business_key>1→'子单号'" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "required": true, + "description": "订单号。优先取 wms_order_express.delivery_order_code(快照列),为空时回退取 source_order_codes" + }, + { + "name": "source_order_codes", + "type": "string", + "required": true, + "description": "原始订单号(平台订单号),来自 wms_order_express.source_order_codes 快照列" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "warehouse_name", + "type": "string", + "required": true, + "description": "仓库名称(来自 warehouse_name_snapshot 快照列)" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID(来自 wms_order_express.store_id)" + }, + { + "name": "store_name", + "type": "string", + "required": true, + "description": "货主名称。通过订单ID批量关联订单发货表(current/history/dispatch)获取 store_name 字段" + }, + { + "name": "business_key", + "type": "number", + "required": true, + "description": "拆单序号:1=主单号,>1=子单号" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "运单状态:0=未分配,1=已分配" + }, + { + "name": "status_text", + "type": "string", + "required": true, + "description": "状态文本:'未分配'/'已分配'" + }, + { + "name": "logistics_interface_id", + "type": "number", + "required": false, + "description": "物流接口ID" + }, + { + "name": "logistics_code", + "type": "string", + "required": false, + "description": "物流公司编码" + }, + { + "name": "logistics_name", + "type": "string", + "required": false, + "description": "物流公司名称" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": false, + "description": "物流接口名称" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": false, + "description": "平台名称(前端映射)" + }, + { + "name": "is_back", + "type": "string", + "required": false, + "description": "是否退回:Y/N" + }, + { + "name": "is_intercept", + "type": "string", + "required": false, + "description": "是否拦截:Y/N" + }, + { + "name": "is_galaxy_receive", + "type": "string", + "required": false, + "description": "是否星河签收:Y/N" + }, + { + "name": "weighing_weight", + "type": "number", + "required": false, + "description": "称重重量(单位:g)" + }, + { + "name": "weighing_weight_display", + "type": "string", + "required": false, + "description": "称重重量可读展示(如 '1.25 kg')" + }, + { + "name": "package_material_id", + "type": "number", + "required": false, + "description": "包材ID" + }, + { + "name": "package_material_name", + "type": "string", + "required": false, + "description": "包材名称(来自 package_material_name_snapshot 快照列)" + }, + { + "name": "print_count", + "type": "number", + "required": false, + "description": "打印次数(COUNT express_print_record)" + }, + { + "name": "last_print_at", + "type": "string", + "required": false, + "description": "最近打印时间" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "运单创建时间" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页条数" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + } + ] + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "405", + "message": "参数校验失败:{具体原因}" + }, + { + "code": "500", + "message": "服务器内部错误:运单列表查询失败" + } + ], + "notes": [ + "mainWaybillCode 支持字符串数组(2026-10-04):数组按 Op.in 精确匹配多个主单号,返回这些主单对应订单下的全部运单(主+子);单值保持原「先定位 order_id 再查」行为不变,且 order_id 条件保持标量。" + ] + }, + { + "method": "waybill.warehouse.detail", + "description": "运单详情-仓库侧:查看单个运单的完整信息,包含关联订单、打印记录、称重信息。仓库隔离校验。支持按运单记录ID(id)或运单号(waybillCode)查询,waybillCode 优先。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token,从中解析 warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "运单记录ID(wms_order_express.id)。与 waybillCode 二选一,waybillCode 优先" + }, + { + "name": "waybillCode", + "type": "string", + "required": false, + "source": "body", + "description": "运单号。与 id 二选一,waybillCode 优先。需配合仓库隔离校验" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的运单详情数据", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "运单记录ID" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "main_waybill_code", + "type": "string", + "required": true, + "description": "主单号" + }, + { + "name": "waybill_type", + "type": "string", + "required": true, + "description": "运单类型:'主单号'/'子单号'" + }, + { + "name": "business_key", + "type": "number", + "required": true, + "description": "拆单序号" + }, + { + "name": "sibling_waybills", + "type": "array", + "required": false, + "description": "同订单下所有运单(兄弟运单),含 waybill_code、business_key、waybill_type", + "children": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "business_key", + "type": "number", + "required": true, + "description": "拆单序号" + }, + { + "name": "waybill_type", + "type": "string", + "required": true, + "description": "运单类型" + } + ] + }, + { + "name": "order", + "type": "object", + "required": true, + "description": "关联订单信息(通过 OrderDeliveryFactory 多表遍历查找)", + "children": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "required": true, + "description": "订单号" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "warehouse_name", + "type": "string", + "required": true, + "description": "仓库名称(快照)" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID(快照)" + }, + { + "name": "store_name", + "type": "string", + "required": true, + "description": "货主名称(快照)" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "波次号" + }, + { + "name": "order_type", + "type": "string", + "required": false, + "description": "订单类型:delivery/entry 等" + } + ] + }, + { + "name": "logistics", + "type": "object", + "required": true, + "description": "物流信息", + "children": [ + { + "name": "logistics_code", + "type": "string", + "required": false, + "description": "物流公司编码" + }, + { + "name": "logistics_name", + "type": "string", + "required": false, + "description": "物流公司名称" + }, + { + "name": "logistics_interface_id", + "type": "number", + "required": false, + "description": "物流接口ID" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": false, + "description": "物流接口名称" + }, + { + "name": "platform_code", + "type": "string", + "required": false, + "description": "平台编码" + } + ] + }, + { + "name": "status_info", + "type": "object", + "required": true, + "description": "运单状态信息", + "children": [ + { + "name": "status", + "type": "number", + "required": true, + "description": "运单状态:0=未分配,1=已分配" + }, + { + "name": "status_text", + "type": "string", + "required": true, + "description": "状态文本" + }, + { + "name": "is_back", + "type": "string", + "required": false, + "description": "是否退回" + }, + { + "name": "is_intercept", + "type": "string", + "required": false, + "description": "是否拦截" + }, + { + "name": "is_galaxy_receive", + "type": "string", + "required": false, + "description": "是否星河签收" + } + ] + }, + { + "name": "weight", + "type": "object", + "required": false, + "description": "称重信息", + "children": [ + { + "name": "weighing_weight", + "type": "number", + "required": false, + "description": "称重重量(g)" + }, + { + "name": "weighing_weight_display", + "type": "string", + "required": false, + "description": "称重重量可读展示" + } + ] + }, + { + "name": "package", + "type": "object", + "required": false, + "description": "包材信息", + "children": [ + { + "name": "package_material_id", + "type": "number", + "required": false, + "description": "包材ID" + }, + { + "name": "package_material_name", + "type": "string", + "required": false, + "description": "包材名称(快照)" + } + ] + }, + { + "name": "print_records", + "type": "array", + "required": false, + "description": "打印记录列表(LEFT JOIN express_print_record ON express_no = waybill_code)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "打印记录ID" + }, + { + "name": "printer_name", + "type": "string", + "required": false, + "description": "打印机名称" + }, + { + "name": "template_id", + "type": "number", + "required": false, + "description": "打印模板ID" + }, + { + "name": "template_name", + "type": "string", + "required": false, + "description": "打印模板名称" + }, + { + "name": "platform", + "type": "string", + "required": false, + "description": "平台" + }, + { + "name": "printed_at", + "type": "string", + "required": false, + "description": "打印时间" + } + ] + }, + { + "name": "print_count", + "type": "number", + "required": false, + "description": "打印次数" + }, + { + "name": "printinfo", + "type": "string", + "required": false, + "description": "打印信息(TEXT 字段)" + }, + { + "name": "ver", + "type": "string", + "required": false, + "description": "打印版本号" + }, + { + "name": "retry_count", + "type": "number", + "required": false, + "description": "重试次数" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "运单创建时间" + }, + { + "name": "delete_at", + "type": "string", + "required": false, + "description": "删除时间(软删除),null 表示未删除" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "运单不存在" + }, + { + "code": "405", + "message": "参数校验失败:请提供运单ID或运单号" + }, + { + "code": "405", + "message": "无权访问该运单(仓库隔离校验不通过)" + }, + { + "code": "500", + "message": "服务器内部错误:运单详情查询失败" + } + ] + }, + { + "method": "waybill.warehouse.export", + "description": "运单导出-仓库侧:按筛选条件导出运单列表为 Excel 文件。复用 waybill.warehouse.list 的筛选逻辑,去掉分页,全量导出。导出为异步任务模式,立即返回任务受理信息,通过 exportTaskProgress 查询进度。仓库隔离(自动注入 warehouse_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token,从中解析 warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,同 waybill.warehouse.list 的 where 参数,另支持 ids(运单ID数组,勾选导出)" + }, + { + "name": "where.waybillCode", + "type": "string|string[]", + "required": false, + "source": "body.where", + "description": "运单号筛选:字符串时为模糊搜索(LIKE '%值%',向后兼容);字符串数组时为精确匹配(Op.in,元素自动 trim 并过滤空值,空数组或全空值时不加该筛选条件)" + }, + { + "name": "where.mainWaybillCode", + "type": "string|string[]", + "required": false, + "source": "body.where", + "description": "主单号筛选:字符串/字符串数组均可(数组按 Op.in 精确匹配多个主单号),先定位 order_id 再导出对应订单下全部运单(元素自动 trim 并过滤空值,空数组或全空值时不加该筛选条件)" + }, + { + "name": "where.ids", + "type": "array", + "required": false, + "source": "body.where", + "description": "运单ID列表(勾选导出,按 wms_order_express.id 精确过滤)" + }, + { + "name": "where.orderId", + "type": "number", + "required": false, + "source": "body.where", + "description": "订单ID(等值匹配)" + }, + { + "name": "where.orderNo", + "type": "string", + "required": false, + "source": "body.where", + "description": "订单号(模糊搜索,暂不可用,待快照字段就绪)" + }, + { + "name": "where.waybillType", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单类型:\"main\"/\"1\"=主单号,\"child\"/\"2\"=子单号" + }, + { + "name": "where.storeId", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值匹配)" + }, + { + "name": "where.logisticsCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "物流公司编码(等值匹配)" + }, + { + "name": "where.logisticsInterfaceId", + "type": "number", + "required": false, + "source": "body.where", + "description": "物流接口ID(等值匹配)" + }, + { + "name": "where.platformCode", + "type": "string", + "required": false, + "source": "body.where", + "description": "平台编码(等值匹配)" + }, + { + "name": "where.status", + "type": "number", + "required": false, + "source": "body.where", + "description": "运单状态:0=未分配,1=已分配" + }, + { + "name": "where.isBack", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否退回:Y/N" + }, + { + "name": "where.isIntercept", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否拦截:Y/N" + }, + { + "name": "where.isGalaxyReceive", + "type": "string", + "required": false, + "source": "body.where", + "description": "是否星河签收:Y/N" + }, + { + "name": "where.packageMaterialId", + "type": "number", + "required": false, + "source": "body.where", + "description": "包材ID(等值匹配)" + }, + { + "name": "where.hasWeighingWeight", + "type": "boolean", + "required": false, + "source": "body.where", + "description": "是否已称重" + }, + { + "name": "where.keyword", + "type": "string", + "required": false, + "source": "body.where", + "description": "关键词搜索" + }, + { + "name": "where.createdAt", + "type": "object", + "required": false, + "source": "body.where", + "description": "创建时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组" + }, + { + "name": "where.createdAtStart", + "type": "string", + "required": false, + "source": "body.where", + "description": "创建时间起始,格式 YYYY-MM-DD(兼容旧写法)" + }, + { + "name": "where.createdAtEnd", + "type": "string", + "required": false, + "source": "body.where", + "description": "创建时间截止,格式 YYYY-MM-DD(兼容旧写法)" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,同 waybill.warehouse.list" + }, + { + "name": "sort.field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段:create_at / weighing_weight / id" + }, + { + "name": "sort.order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向:asc / desc" + }, + { + "name": "exportFields", + "type": "array", + "required": false, + "source": "body", + "description": "需要导出的字段列表,不传则导出全部字段。可选字段:waybill_code, main_waybill_code, waybill_type, order_no, warehouse_name, store_name, business_key, status_text, logistics_code, logistics_name, logistics_interface_name, platform_code, weighing_weight, package_material_name, print_count, last_print_at, create_at" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示任务已受理" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的导出任务受理信息(异步任务模式,不含导出数据)", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "异步导出任务ID,前缀 waybill_export_,用于后续通过 exportTaskProgress 查询进度和获取下载链接" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted(已提交)/ running(执行中)/ success(成功)/ failed(失败)" + }, + { + "name": "progress", + "type": "number", + "required": false, + "description": "任务进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "任务状态说明" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "任务最近更新时间(ISO 8601)" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "405", + "message": "参数校验失败:{具体原因}" + }, + { + "code": "500", + "message": "服务器内部错误:运单导出任务创建失败" + } + ], + "notes": [ + "mainWaybillCode 支持字符串数组(2026-10-04):数组按 Op.in 精确匹配多个主单号,返回这些主单对应订单下的全部运单(主+子);单值保持原「先定位 order_id 再查」行为不变,且 order_id 条件保持标量。" + ] + }, + { + "method": "waybill.warehouse.exportTaskProgress", + "description": "运单导出进度查询-仓库侧:按 task_id 或 taskId 查询异步导出任务的执行进度。任务进度通过 Redis 缓存存储,任务 ID 前缀 waybill_export_。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token,从中解析 warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "异步导出任务ID(前缀 waybill_export_)。与 taskId 二选一,taskId 优先" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "异步导出任务ID(别名,优先使用)。至少传入 taskId 或 task_id 之一" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的导出任务进度信息", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted(已提交)/ running(执行中)/ success(成功)/ failed(失败)" + }, + { + "name": "progress", + "type": "number", + "required": false, + "description": "任务进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": false, + "description": "当前已处理的运单记录数" + }, + { + "name": "total_count", + "type": "number", + "required": false, + "description": "需要导出的总运单记录数" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "任务状态说明或错误信息" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "任务执行结果(status=success 时返回)", + "children": [ + { + "name": "total_exported", + "type": "number", + "required": false, + "description": "实际导出的记录数" + }, + { + "name": "file_size", + "type": "number", + "required": false, + "description": "导出文件大小(字节)" + } + ] + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(status=failed 时返回)" + }, + { + "name": "download_url", + "type": "string", + "required": false, + "description": "导出文件下载地址(COS 临时签名 URL,status=success 时返回)" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "任务最近更新时间(ISO 8601)" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "任务不存在或已过期" + }, + { + "code": "405", + "message": "参数校验失败:请提供 taskId 或 task_id" + }, + { + "code": "500", + "message": "服务器内部错误:导出进度查询失败" + } + ] + }, + { + "method": "waybill.warehouse.updateReceive", + "description": "批量更新运单是否揽收-仓库侧:按运单号(或按 where 筛选条件圈选的运单号)调用外部访问接口 waybill.getreceive 查询揽收状态(单批最多 10 单,超出自动切批),并把结果回写 wms_order_express.is_galaxy_receive(按 warehouse_id 隔离)。出站运单号会按 wms_order_express.logistics_interface_id 关联的 wms_express_interface.sender_tel 补寄件电话后四位(运单号|后四位)。异步任务模式,提交后通过 updateReceiveTaskProgress 查询进度。仓库未配置承接该回调方法的 API 应用时直接失败,不创建任务。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "****** warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "waybillCodes", + "type": "array", + "required": false, + "source": "body", + "description": "运单号列表(字符串数组),提交后按 10 单一批调用外部接口;与 where 二选一,两者都传时以 waybillCodes 为准" + }, + { + "name": "waybill_codes", + "type": "array", + "required": false, + "source": "body", + "description": "waybillCodes 的下划线别名,二者取其一" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,与 waybill.warehouse.list 完全一致(不含 pagination/sort),支持 waybillCode / mainWaybillCode / orderId / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / waybillType / storeId / packageMaterialId / hasWeighingWeight / keyword / createdAt 等;服务端先按条件解析运单号再走同一任务链路,匹配数超过 5000 条时失败并要求缩小范围" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的任务受理信息(异步任务模式)", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "异步任务ID,前缀 waybill_receive_,用于通过 updateReceiveTaskProgress 查询进度" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted(已提交)/ running(执行中)/ success(成功)/ failed(失败)" + }, + { + "name": "progress", + "type": "number", + "required": false, + "description": "任务进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": false, + "description": "已查询的运单数" + }, + { + "name": "total_count", + "type": "number", + "required": false, + "description": "本次提交的运单总数" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "任务状态说明" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "任务最近更新时间" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "403", + "message": "如需更新运单是否揽收信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口" + }, + { + "code": "405", + "message": "参数校验失败:运单号不能为空,或传入 where 筛选条件" + }, + { + "code": "405", + "message": "参数校验失败:符合条件的运单超过 5000 条,请缩小筛选范围或直接传 waybillCodes" + }, + { + "code": "405", + "message": "参数校验失败:未匹配到符合条件的运单" + }, + { + "code": "500", + "message": "服务器内部错误:更新揽收状态任务创建失败" + } + ], + "notes": [ + "链路:systemMethods/waybill/warehouse.js#updateReceive → systems/waybill.js#queryReceiveStatus → openapi/callback.js#sendByAppKey(不读本地库的揽收标记)", + "where 与列表同源:复用 systems/waybill.js#buildListQueryWhere,与 waybill.warehouse.list 的筛选口径完全一致(含 operator/value 格式与主单号展开),避免两处筛选逻辑漂移", + "where 圈选上限:匹配数 > 5000 条直接失败(不截断),避免一次性更新过多运单;运单号来源优先级 waybillCodes > where", + "单批上限:waybill.getreceive 每次最多 10 个运单号,超出自动切批,任务进度按批更新", + "签名口径:waybill.getreceive 按 methods/warehouse_notify.json 协议签名,sign = MD5(appSecret + timestamp + bodyJson);与 /openapi 入站的 canonicalQuery 口径不同(内部 signMode=simple)", + "请求体:{ request: { waybill_codes: [...] } };响应为裸数组 [{ waybill_code, is_galaxy_receive }],另兼容 { code, data: [...] } 与 { data: { waybills: [...] } }", + "回写口径:按 waybill_code + warehouse_id 更新 wms_order_express.is_galaxy_receive(1→Y、0→N),跨仓不串写", + "HTTP 200 但业务码非 0/1/200(如验签失败 code=401)时整批计失败,失败原因写入任务 result.failed", + "未配置外部接口时直接返回失败,不创建任务、不占用任务进度缓存", + "目标应用:仓库下 callback_functions 勾选了 waybill.getreceive 的首个启用应用(按 id 升序)" + ] + }, + { + "method": "waybill.warehouse.updateReceiveTaskProgress", + "description": "运单揽收状态更新进度查询-仓库侧:按 task_id 或 taskId 查询异步任务执行进度。任务进度通过 Redis 缓存存储,任务 ID 前缀 waybill_receive_。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "****** warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "异步任务ID(前缀 waybill_receive_)。与 taskId 二选一" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "异步任务ID(别名,优先使用)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "成功时返回的任务进度信息", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "progress", + "type": "number", + "required": false, + "description": "任务进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": false, + "description": "当前已处理的运单数" + }, + { + "name": "total_count", + "type": "number", + "required": false, + "description": "本次提交的运单总数" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "任务状态说明" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "任务执行结果(status=success 时返回)", + "children": [ + { + "name": "total", + "type": "number", + "required": false, + "description": "本次提交的运单总数" + }, + { + "name": "updated", + "type": "number", + "required": false, + "description": "实际更新揽收状态的运单数" + }, + { + "name": "unchanged", + "type": "number", + "required": false, + "description": "揽收状态未变化的运单数" + }, + { + "name": "not_found", + "type": "array", + "required": false, + "description": "当前仓库下不存在的运单号列表" + }, + { + "name": "failed", + "type": "array", + "required": false, + "description": "失败明细 [{ waybill_code, reason }]:回调失败、业务码失败或返回值非法" + } + ] + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息(status=failed 时返回)" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "任务最近更新时间" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "任务不存在或已过期" + }, + { + "code": "500", + "message": "服务器内部错误:揽收状态更新进度查询失败" + } + ] + }, + { + "method": "waybill.warehouse.getTrace", + "description": "查询单个运单的全部物流轨迹-仓库侧:按运单号实时调用外部访问接口 waybill.getTrace 查询(全部回源,不做本地存储),一次返回全部轨迹(不分页),按操作时间倒序排列(最新在前);命中轨迹时顺带把该运单 is_galaxy_receive 置为 Y(只升不降)。出站运单号会按 wms_order_express.logistics_interface_id 关联的 wms_express_interface.sender_tel 补寄件电话后四位(运单号|后四位)。仓库未配置承接该回调方法的 API 应用时直接失败。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "****** warehouseId(仓库上下文,ctx.user.store_id)" + } + ], + "params": [ + { + "name": "waybillCode", + "type": "string", + "required": true, + "source": "body", + "description": "运单号(单个精确匹配)" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "source": "body", + "description": "waybillCode 的下划线别名,二者取其一" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "??????", + "children": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "轨迹条数" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "轨迹列表(按 op_time 倒序,不分页)", + "children": [ + { + "name": "op_time", + "type": "string", + "required": false, + "description": "操作时间,格式 YYYY-MM-DD HH:mm:ss" + }, + { + "name": "out_biz_code", + "type": "string", + "required": false, + "description": "外部业务码" + }, + { + "name": "memo", + "type": "string", + "required": false, + "description": "轨迹描述" + }, + { + "name": "op_org_city_name", + "type": "string", + "required": false, + "description": "操作机构所在城市" + }, + { + "name": "weight", + "type": "number", + "required": false, + "description": "重量(来源原值,支持小数如 0.99)" + }, + { + "name": "scan_type", + "type": "string", + "required": false, + "description": "扫描类型,如 发件/到件/派件/签收" + }, + { + "name": "raw_data", + "type": "object", + "required": false, + "description": "外部原始轨迹对象" + } + ] + }, + { + "name": "received_updated", + "type": "number", + "required": false, + "description": "因本次命中轨迹而把 is_galaxy_receive 置为 Y 的运单数(0 或 1;只升不降)" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "405", + "message": "参数校验失败:运单号不能为空" + }, + { + "code": "500", + "message": "运单轨迹查询失败:如需查询运单物流轨迹,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口" + }, + { + "code": "500", + "message": "运单轨迹查询失败:{外部接口错误信息}" + } + ], + "notes": [ + "链路:systemMethods/waybill/warehouse.js#getTrace → systems/waybill.js#fetchTracesByWaybill → openapi/callback.js#sendByAppKey(event=waybill.getTrace)", + "全部回源(2026-11-11 调整):不做本地存储,wms_order_express_trace 已下线删除;每次查询都实时调用外部接口", + "请求体:{ request: { waybill_codes: [运单号] } };签名口径与 waybill.getreceive 一致(MD5(appSecret + timestamp + bodyJson))", + "响应解析:[{ waybillNo, trace: [...] }],trace 可为对象或数组,另兼容 { code, data: [...] } 与单个对象返回", + "排序:按 op_time 倒序;weight 支持字符串小数(如 \"0.99\"),统一转数字保留 3 位小数", + "揽收联动:轨迹非空时把该运单 is_galaxy_receive 置为 Y(只升不降,失败只记日志不阻断查询);trace 为空不更新", + "失败口径:未配置承接应用或外部接口异常时直接返回失败(无本地兜底);trace 为空属于正常结果(success + total=0)", + "目标应用:仓库下 callback_functions 勾选了 waybill.getTrace 的首个启用应用(按 id 升序)" + ] + } + ] + }, + { + "groupName": "API应用管理模块", + "module": "apiApp", + "list": [ + { + "method": "apiApp.list", + "description": "查询当前仓库的 API 应用列表(分页),返回脱敏后的 AppSecret", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20,最大 100" + }, + { + "name": "app_name", + "type": "string", + "required": false, + "source": "body", + "description": "应用名称(模糊搜索)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "启用状态:1-启用,0-停用" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "应用列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "description": "接口类型 ID" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "自身 AppKey(对外提供)" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "自身 AppSecret(脱敏,仅显示前8位+****)" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "description": "IP 白名单", + "children": [ + { + "name": "ip", + "type": "string", + "required": false, + "description": "IP 地址或 CIDR" + } + ] + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "description": "回调通知 URL" + }, + { + "name": "callback_functions", + "type": "array", + "required": false, + "description": "承接的出站回调 method 列表(空/未勾选=不承接任何回调)", + "children": [ + { + "name": "method", + "type": "string", + "required": false, + "description": "回调方法名,如 notify.reply" + } + ] + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "description": "速率限制(次/秒)" + }, + { + "name": "sign_method", + "type": "string", + "required": false, + "description": "签名方法(当前仅支持 md5)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态:1-启用,0-停用" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页数量" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + }, + { + "name": "hasNext", + "type": "boolean", + "required": true, + "description": "是否有下一页" + }, + { + "name": "hasPrevious", + "type": "boolean", + "required": true, + "description": "是否有上一页" + } + ] + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "500", + "message": "服务器内部错误:查询 API 应用列表失败" + } + ] + }, + { + "method": "apiApp.detail", + "description": "查询单个 API 应用详情", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "应用 ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "description": "接口类型 ID" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "自身 AppKey" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "自身 AppSecret(脱敏)" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "description": "IP 白名单" + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "description": "回调通知 URL" + }, + { + "name": "callback_functions", + "type": "array", + "required": false, + "description": "承接的出站回调 method 列表(空/未勾选=不承接任何回调)" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "description": "速率限制" + }, + { + "name": "sign_method", + "type": "string", + "required": false, + "description": "签名方法(当前仅支持 md5)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ], + "errors": [ + { + "code": "400", + "message": "ID不能为空" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "API应用不存在" + }, + { + "code": "500", + "message": "服务器内部错误:查询 API 应用详情失败" + } + ] + }, + { + "method": "apiApp.create", + "description": "创建 API 应用,自动生成 AppKey(AK{时间戳}{随机8位hex})和 AppSecret(64位hex)。仅创建时返回完整 Secret。签名方法固定为 md5", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "app_name", + "type": "string", + "required": true, + "source": "body", + "description": "应用名称,最大 200 字符" + }, + { + "name": "interface_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "接口类型 ID,不传则默认取 WH_CHANNEL 类型" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "source": "body", + "description": "IP 白名单,如 [\"192.168.1.1\", \"10.0.0.0/24\"]", + "children": [ + { + "name": "ip", + "type": "string", + "required": false, + "description": "IP 地址或 CIDR" + } + ] + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "source": "body", + "description": "API 回调通知 URL" + }, + { + "name": "callback_functions", + "type": "array", + "required": false, + "source": "body", + "description": "承接的出站回调 method 列表,仅允许注册表中的方法(如 notify.reply);空数组/不传 = 不承接任何回调", + "children": [ + { + "name": "method", + "type": "string", + "required": false, + "description": "回调方法名" + } + ] + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "source": "body", + "description": "速率限制(次/秒),默认 1000,范围 1-100000" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "自动生成的 AppKey" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "自动生成的 AppSecret(仅创建和重新生成时返回完整值,请妥善保存)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "所属仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "description": "接口类型 ID" + }, + { + "name": "callback_functions", + "type": "array", + "required": false, + "description": "承接的出站回调 method 列表" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "description": "速率限制" + }, + { + "name": "sign_method", + "type": "string", + "required": false, + "description": "签名方法(固定为 md5)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态,创建后默认 1" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" + } + ], + "errors": [ + { + "code": "400", + "message": "应用名称不能为空" + }, + { + "code": "400", + "message": "应用名称不能超过200个字符" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "403", + "message": "无法获取当前仓库ID" + }, + { + "code": "500", + "message": "服务器内部错误:创建 API 应用失败" + } + ] + }, + { + "method": "apiApp.update", + "description": "更新 API 应用(名称、白名单、回调地址、限流、启用状态),不可变字段:app_key、interface_type_id、sign_method(固定为 md5,不允许修改)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": false, + "source": "body", + "description": "应用名称,最大 200 字符" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "source": "body", + "description": "IP 白名单" + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "source": "body", + "description": "回调通知 URL" + }, + { + "name": "callback_functions", + "type": "array", + "required": false, + "source": "body", + "description": "承接的出站回调 method 列表,仅允许注册表中的方法;空数组 = 不承接任何回调", + "children": [ + { + "name": "method", + "type": "string", + "required": false, + "description": "回调方法名" + } + ] + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "source": "body", + "description": "速率限制,范围 1-100000" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "启用状态:1-启用,0-停用" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "AppKey(不可变)" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "AppSecret(脱敏)" + }, + { + "name": "callback_functions", + "type": "array", + "required": false, + "description": "承接的出站回调 method 列表" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ], + "errors": [ + { + "code": "400", + "message": "ID不能为空" + }, + { + "code": "400", + "message": "应用名称不能为空/不能超过200个字符" + }, + { + "code": "400", + "message": "签名方法当前仅支持 md5,不允许修改" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "API应用不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "服务器内部错误:更新 API 应用失败" + } + ] + }, + { + "method": "apiApp.delete", + "description": "停用 API 应用(软删除,设置 is_enabled=0,不物理删除数据)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "应用 ID" + } + ], + "response": { + "type": "object", + "properties": [] + }, + "errors": [ + { + "code": "400", + "message": "ID不能为空" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "API应用不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "服务器内部错误:停用 API 应用失败" + } + ] + }, + { + "method": "apiApp.regenerateSecret", + "description": "重新生成 AppSecret,旧 Secret 立即失效。仅此次返回完整 Secret,请妥善保存", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "应用 ID" + } + ], + "response": { + "type": "object", + "properties": [ + { + "name": "id", + "type": "number", + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "description": "AppKey(不变)" + }, + { + "name": "self_app_secret", + "type": "string", + "description": "新生成的 AppSecret,64位十六进制(仅此次返回完整值,请妥善保存)" + } + ] + }, + "errors": [ + { + "code": "400", + "message": "ID不能为空" + }, + { + "code": "401", + "message": "未登录,请先登录" + }, + { + "code": "404", + "message": "API应用不存在或不属于当前仓库" + }, + { + "code": "500", + "message": "服务器内部错误:重新生成 AppSecret 失败" + } + ] + }, + { + "method": "apiApp.listCallbackFunctions", + "description": "拉取出站回调 method 注册表(代码注册,供管理端多选列表使用;应用勾选后按 method 自动路由)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "可选的出站回调方法列表", + "children": [ + { + "name": "method", + "type": "string", + "required": true, + "description": "回调方法名(如 notify.reply)" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "方法显示名称" + }, + { + "name": "description", + "type": "string", + "required": false, + "description": "方法说明" + } + ] + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "数量" + } + ], + "errors": [ + { + "code": "401", + "message": "未登录,请先登录" + } + ] + } + ] + }, + { + "groupName": "站内信", + "module": "inbox", + "list": [ + { + "method": "inbox.message.list", + "description": "站内信消息列表,支持货主/群/用户名/正文/来源等多条件筛选,时间字段使用统一格式化输出,分页返回(默认20条/页,最大200条)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "storeId", + "type": "string", + "required": false, + "source": "body", + "description": "货主ID筛选,支持逗号分隔多选,如 \"1000000,1000001\"" + }, + { + "name": "groupId", + "type": "string", + "required": false, + "source": "body", + "description": "群ID筛选,支持逗号分隔多选" + }, + { + "name": "groupName", + "type": "string", + "required": false, + "source": "body", + "description": "群名称模糊搜索" + }, + { + "name": "userName", + "type": "string", + "required": false, + "source": "body", + "description": "用户名模糊搜索" + }, + { + "name": "content", + "type": "string", + "required": false, + "source": "body", + "description": "正文模糊搜索" + }, + { + "name": "sourceType", + "type": "string", + "required": false, + "source": "body", + "description": "来源类型筛选:im / api / system" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "消息方向筛选:inbound(收件)/ outbound(回信)" + }, + { + "name": "pushStatus", + "type": "number", + "required": false, + "source": "body", + "description": "推送状态筛选:0=待推送 1=推送中 2=已送达 3=失败" + }, + { + "name": "startDate", + "type": "string", + "required": false, + "source": "body", + "description": "开始日期(created_at >=),格式 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss" + }, + { + "name": "endDate", + "type": "string", + "required": false, + "source": "body", + "description": "结束日期(created_at <=),格式 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1", + "defaultValue": 1 + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20,最大 200", + "defaultValue": 20 + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "消息列表(不含 ext_data、push_response、target_channel 字段,时间已格式化)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "消息ID" + }, + { + "name": "ext_id", + "type": "string", + "required": true, + "description": "外部唯一消息主键" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "所属仓库ID" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "description": "关联货主ID" + }, + { + "name": "store_name", + "type": "string", + "required": false, + "description": "货主名称(批量回填)" + }, + { + "name": "direction", + "type": "string", + "required": true, + "description": "消息方向:inbound / outbound" + }, + { + "name": "source_type", + "type": "string", + "required": true, + "description": "来源类型:im / api / system" + }, + { + "name": "target_type", + "type": "string", + "required": true, + "description": "目标类型:im / api / webhook" + }, + { + "name": "group_id", + "type": "string", + "required": false, + "description": "外部群ID" + }, + { + "name": "group_name", + "type": "string", + "required": false, + "description": "群名称" + }, + { + "name": "user_id", + "type": "string", + "required": false, + "description": "外部用户ID" + }, + { + "name": "user_name", + "type": "string", + "required": false, + "description": "用户名称" + }, + { + "name": "content", + "type": "string", + "required": false, + "description": "消息正文/摘要" + }, + { + "name": "push_status", + "type": "number", + "required": true, + "description": "推送状态:0=待推送 1=推送中 2=已送达 3=失败" + }, + { + "name": "retry_count", + "type": "number", + "required": true, + "description": "已重试次数" + }, + { + "name": "created_at", + "type": "string", + "required": true, + "description": "创建时间(YYYY-MM-DD HH:mm:ss 格式化)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间(YYYY-MM-DD HH:mm:ss 格式化)" + }, + { + "name": "pushed_at", + "type": "string", + "required": false, + "description": "推送完成时间(YYYY-MM-DD HH:mm:ss 格式化)" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页码" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页数量" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + }, + { + "name": "hasPrevious", + "type": "boolean", + "required": true, + "description": "是否有上一页" + }, + { + "name": "hasNext", + "type": "boolean", + "required": true, + "description": "是否有下一页" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效" + }, + { + "code": "500", + "message": "warehouseId 无效" + } + ] + }, + { + "method": "inbox.message.detail", + "description": "站内信消息详情,含完整 push_response 推送响应信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "消息ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "消息ID" + }, + { + "name": "ext_id", + "type": "string", + "required": true, + "description": "外部唯一消息主键" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "所属仓库ID" + }, + { + "name": "direction", + "type": "string", + "required": true, + "description": "消息方向" + }, + { + "name": "source_type", + "type": "string", + "required": true, + "description": "来源类型" + }, + { + "name": "target_type", + "type": "string", + "required": true, + "description": "目标类型" + }, + { + "name": "target_channel", + "type": "string", + "required": true, + "description": "目标渠道" + }, + { + "name": "target_url", + "type": "string", + "required": true, + "description": "推送目标URL" + }, + { + "name": "push_status", + "type": "number", + "required": true, + "description": "推送状态" + }, + { + "name": "retry_count", + "type": "number", + "required": true, + "description": "已重试次数" + }, + { + "name": "push_response", + "type": "object", + "required": false, + "description": "推送目标响应(http_status, body, error)" + }, + { + "name": "ext_data", + "type": "object", + "required": false, + "description": "外部透传数据" + }, + { + "name": "created_at", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效" + }, + { + "code": "404", + "message": "消息不存在或无权访问" + }, + { + "code": "500", + "message": "消息ID无效 / warehouseId 无效" + } + ] + }, + { + "method": "inbox.message.thread", + "description": "站内信对话链查询,返回原消息 + 所有回信(按 parent_id 递归),按时间升序排列", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "消息ID(可为对话链中任意一条消息,自动向上查找根消息并收集所有回信)" + } + ], + "response": [ + { + "name": "thread", + "type": "array", + "required": true, + "description": "对话链消息数组,按时间升序排列,首元素为根消息,后续为回信" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效" + }, + { + "code": "404", + "message": "消息不存在或无权访问" + }, + { + "code": "500", + "message": "消息ID无效 / warehouseId 无效" + } + ] + }, + { + "method": "inbox.message.reply", + "description": "系统回信:写入 outbound 记录 + 异步推送到目标渠道。自动继承原消息的 ext_data、ref_code 等字段", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "parentId", + "type": "number", + "required": true, + "source": "body", + "description": "原消息ID(回信指向的原消息)" + }, + { + "name": "targetChannel", + "type": "string", + "required": true, + "source": "body", + "description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook" + }, + { + "name": "targetType", + "type": "string", + "required": false, + "source": "body", + "description": "目标类型:im / api / webhook,默认继承原消息的 target_type" + }, + { + "name": "extData", + "type": "object", + "required": false, + "source": "body", + "description": "透传数据,默认继承原消息的 ext_data" + }, + { + "name": "flags", + "type": "object", + "required": false, + "source": "body", + "description": "处理标记" + } + ], + "response": [ + { + "name": "ok", + "type": "boolean", + "required": true, + "description": "操作是否成功" + }, + { + "name": "id", + "type": "number", + "required": true, + "description": "回信记录 ID" + }, + { + "name": "ext_id", + "type": "string", + "required": true, + "description": "回信唯一标识(sys:{uuid})" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效 / parentId 无效 / targetChannel 不能为空 / targetUrl 不能为空" + }, + { + "code": "404", + "message": "原消息不存在或无权访问" + }, + { + "code": "500", + "message": "warehouseId 无效 / 回信失败" + } + ] + }, + { + "method": "inbox.message.retry", + "description": "手动重推失败(push_status=3)的站内信消息,重置为待推送状态并触发异步推送", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "消息ID" + } + ], + "response": [ + { + "name": "ok", + "type": "boolean", + "required": true, + "description": "操作是否成功" + }, + { + "name": "id", + "type": "number", + "required": true, + "description": "消息ID" + }, + { + "name": "ext_id", + "type": "string", + "required": true, + "description": "外部唯一消息主键" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果描述" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效 / 仅失败状态的消息可以手动重推" + }, + { + "code": "404", + "message": "消息不存在或无权访问" + }, + { + "code": "500", + "message": "消息ID无效 / warehouseId 无效" + } + ] + }, + { + "method": "inbox.message.stats", + "description": "站内信推送统计:按方向汇总、按推送状态汇总、最近24小时新增数量", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "可选:按方向筛选统计(inbound / outbound),不传则统计全部" + } + ], + "response": [ + { + "name": "total_by_direction", + "type": "array", + "required": true, + "description": "按方向汇总统计", + "children": [ + { + "name": "direction", + "type": "string", + "required": true, + "description": "消息方向" + }, + { + "name": "count", + "type": "number", + "required": true, + "description": "消息数量" + } + ] + }, + { + "name": "total_by_status", + "type": "array", + "required": true, + "description": "按推送状态汇总统计", + "children": [ + { + "name": "push_status", + "type": "number", + "required": true, + "description": "推送状态:0/1/2/3" + }, + { + "name": "count", + "type": "number", + "required": true, + "description": "消息数量" + } + ] + }, + { + "name": "recent_24h_count", + "type": "number", + "required": true, + "description": "最近24小时新增消息数量" + } + ], + "errors": [ + { + "code": "400", + "message": "method 参数无效" + }, + { + "code": "500", + "message": "warehouseId 无效" + } + ] + }, + { + "method": "inbox.bindCode", + "description": "生成货主绑群码。校验 StoreWarehouse 合约有效后,生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。warehouseId 从 token 自动注入", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "storeId", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID(需在目标仓库有有效合约 auth_status=2 warehouse_use_status=1)" + }, + { + "name": "subType", + "type": "string", + "required": false, + "source": "body", + "description": "群子类型:after_sales(售后) / finance(财务) / receiving(收货)" + } + ], + "response": [ + { + "name": "code", + "type": "string", + "required": true, + "description": "12位绑群随机码(大写字母+数字),5分钟有效" + } + ], + "errors": [ + { + "code": "400", + "message": "storeId 无效 / 缺少仓库信息 / 子类型无效" + }, + { + "code": "500", + "message": "货主在仓库无有效合约" + } + ] + }, + { + "method": "inbox.group.list", + "description": "拉取当前仓库的群列表,支持按群类型筛选和关键词搜索,express_interfaces 逗号分隔存储输出为数组", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "groupType", + "type": "string", + "required": false, + "source": "body", + "description": "群类型筛选:store(货主) / warehouse(仓库) / express(快递)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "群名称模糊搜索" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页条数,默认20,最大100" + } + ], + "response": [ + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "群记录列表,含id/group_name/group_id/store_id/group_type/sub_type/is_blocked/ai_enabled/template_reply_enabled/express_interfaces(数组)/system_express_code/created_at" + } + ], + "errors": [ + { + "code": "400", + "message": "warehouseId 无效" + } + ] + }, + { + "method": "inbox.group.disable", + "description": "禁用或解禁群,通过群主键ID操作", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "群记录主键ID" + }, + { + "name": "isBlocked", + "type": "number", + "required": false, + "source": "body", + "description": "是否禁用:1=禁用 0=启用,默认1" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果提示:群已禁用 / 群已启用" + } + ], + "errors": [ + { + "code": "400", + "message": "群ID无效 / warehouseId 无效" + }, + { + "code": "500", + "message": "群不存在或无权限操作" + } + ] + }, + { + "method": "inbox.group.update", + "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码/AI开关/模板消息回复开关。子类型受群类型约束,合法取值见 groupType.list[].subTypes。aiEnabled支持灰度控制,templateReplyEnabled控制命中处理后是否以模板消息形式回复(独立于aiEnabled),切换为express类型时systemExpressCode必填", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "群记录主键ID" + }, + { + "name": "groupType", + "type": "string", + "required": false, + "source": "body", + "description": "群类型:store(货主群) / warehouse(仓库群) / express(快递群)", + "list": [ + { + "value": "store", + "description": "货主群", + "subTypes": [ + { + "value": "after_sales", + "description": "售后" + }, + { + "value": "finance", + "description": "财务" + }, + { + "value": "receiving", + "description": "收货" + } + ] + }, + { + "value": "warehouse", + "description": "仓库群", + "subTypes": [ + { + "value": "receiving", + "description": "收货" + }, + { + "value": "production", + "description": "生产" + }, + { + "value": "stockout", + "description": "出库" + }, + { + "value": "finance", + "description": "财务" + }, + { + "value": "all", + "description": "全体" + }, + { + "value": "customer_service", + "description": "客服" + }, + { + "value": "exception", + "description": "异常" + } + ] + }, + { + "value": "express", + "description": "快递群", + "subTypes": [ + { + "value": "pickup", + "description": "揽收" + }, + { + "value": "after_sales", + "description": "售后" + } + ] + } + ] + }, + { + "name": "subType", + "type": "string", + "required": false, + "source": "body", + "description": "群子类型,值取决于groupType。store→after_sales(售后)/finance(财务)/receiving(收货)。warehouse→receiving(收货)/production(生产)/stockout(出库)/finance(财务)/all(全体)/customer_service(客服)/exception(异常)。express→pickup(揽收)/after_sales(售后)" + }, + { + "name": "storeId", + "type": "number", + "required": false, + "source": "body", + "description": "关联货主ID" + }, + { + "name": "expressInterfaces", + "type": "array", + "required": false, + "source": "body", + "description": "快递接口ID数组,仅groupType=express时生效。空数组表示全部快递类型。需校验wms_express_interface.id存在" + }, + { + "name": "systemExpressCode", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码,groupType=express时必填。需校验wms_express.code存在" + }, + { + "name": "aiEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "是否启用AI自动回复: 0=关闭 1=开启,默认1(所有群类型均支持,用于灰度测试)" + }, + { + "name": "templateReplyEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "是否启用模板消息回复: 0=关闭(普通文本回复) 1=开启(模板消息回复),默认0(所有群类型均支持,独立于aiEnabled;开启后命中处理以模板消息形式回复)" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果提示:群信息修改成功" + } + ], + "errors": [ + { + "code": "400", + "message": "群ID无效 / 子类型不在对应群类型的合法范围内 / 系统快递编码不能为空(express类型时)" + }, + { + "code": "500", + "message": "群不存在或无权限操作 / 系统快递编码不存在 / 快递接口ID无效" + } + ] + }, + { + "method": "inbox.group.reset", + "description": "清空群类型配置:清空群类型/子类型/货主/快递接口/系统快递编码,AI开关与模板消息回复开关重置关闭,仅保留群创建时信息(群名称/群ID/仓库/来源/屏蔽状态/扩展数据)。入参群记录主键ID", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "群记录主键ID" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果提示:群类型配置已清空" + } + ], + "errors": [ + { + "code": "400", + "message": "群ID无效" + }, + { + "code": "500", + "message": "群不存在或无权限操作" + } + ] + }, + { + "method": "inbox.group.messages", + "description": "按群拉取消息列表,支持方向/关键词筛选,分页返回。warehouseId服务端自动注入,查询命中idx_warehouse_group_created索引", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "groupId", + "type": "string", + "required": true, + "source": "body", + "description": "群ID(必填)" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "消息方向筛选:inbound(入站) / outbound(出站)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键词搜索(ext_id / content)" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页条数,默认20,最大200" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "消息记录列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息:page/pageSize/total/totalPages/hasPrevious/hasNext" + } + ], + "errors": [ + { + "code": "400", + "message": "groupId 不能为空 / warehouseId 无效" + } + ] + }, + { + "method": "inbox.group.quickList", + "description": "群快速查询(下拉选择用,不分页):关键词同时模糊匹配群名称与外部群ID,按创建时间倒序返回轻量字段,软删除记录自动排除;支持双维度可选过滤:store_id(货主维度,对应 wms_inbox_group.store_id 列)与 warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)均可选,可单独传、可同时传(AND 关系),也可都不传(返回所有仓库/货主的群),非法值分别报「store_id 无效」「warehouse_id 无效」。需 566 权限(inbox.group.quickList,已授权仓库组-主管/客服组-主管/生产组-主管/经理,超级管理员与仓库管理员持通配符自动拥有)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(登录凭证,权限校验用)" + } + ], + "params": [ + { + "name": "store_id", + "type": "number|string", + "required": false, + "source": "body", + "description": "货主ID(可选,货主维度,对应 wms_inbox_group.store_id 列):传入时须为正整数,仅返回该货主的群;不传或为空时不加货主过滤(返回所有货主的群);与 warehouse_id 可单独传或同时传(AND 关系)" + }, + { + "name": "warehouse_id", + "type": "number|string", + "required": false, + "source": "body", + "description": "仓库ID(可选,仓库维度,对应 wms_inbox_group.warehouse_id 列):传入时须为正整数,仅返回该仓库的群;不传或为空时不加仓库过滤(返回所有仓库的群);与 store_id 可单独传或同时传(AND 关系)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键词,模糊匹配 group_name(群名称)与 group_id(外部群ID)" + }, + { + "name": "groupType", + "type": "string", + "required": false, + "source": "body", + "description": "群类型筛选:store(货主) / warehouse(仓库) / express(快递)" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "body", + "description": "返回条数上限,默认20,最大100(无分页)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "群快速列表(按创建时间倒序,无分页),每项含 id/group_id/group_name/group_type/sub_type/is_blocked/template_reply_enabled", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "群记录主键ID(wms_inbox_group.id)" + }, + { + "name": "group_id", + "type": "string", + "required": false, + "description": "外部群ID(未绑定时为 null)" + }, + { + "name": "group_name", + "type": "string", + "required": true, + "description": "群名称" + }, + { + "name": "group_type", + "type": "string", + "required": false, + "description": "群类型:store / warehouse / express(未配置时为 null)" + }, + { + "name": "sub_type", + "type": "string", + "required": false, + "description": "群子类型(未配置时为 null)" + }, + { + "name": "is_blocked", + "type": "number", + "required": true, + "description": "是否屏蔽:1=屏蔽 0=正常" + }, + { + "name": "template_reply_enabled", + "type": "number", + "required": true, + "description": "是否启用模板消息回复:0=关闭(普通文本回复) 1=开启(模板消息回复)" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "store_id 无效 / warehouse_id 无效" + } + ] + }, + { + "method": "inbox.group.members", + "description": "查询一个或多个群的成员列表(下拉选择用,多群聚合):先按内部主键ID数组+仓库批量校验群存在(软删除自动排除),再聚合所有群的外部群ID(去重、剔除空值),按外部群ID集合在消息表中聚合去重成员(每个 user_id 取最新一条消息的 user_name),关键词在聚合结果上过滤,最后截断到 limit 条;所有外部群ID为空时返回空列表。多群共享同一聚合池(最多取最近 500 条消息,更早消息中的成员不会出现在结果中);user_id 为 NULL/空串的消息被排除。warehouseId 由服务端从登录上下文自动注入。需 567 权限(inbox.group.members,已授权仓库组-主管/客服组-主管/生产组-主管/经理,超级管理员与仓库管理员持通配符自动拥有)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(从中解析 warehouseId 仓库上下文)" + } + ], + "params": [ + { + "name": "groupIds", + "type": "array", + "required": true, + "source": "body", + "description": "群记录主键ID数组(wms_inbox_group.id,必填,非空数组,每个元素为正整数,支持数字或可解析数字字符串)" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键词,模糊匹配 user_name(用户名)与 user_id(用户ID),对聚合结果做小写包含过滤" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "body", + "description": "返回条数上限,默认20,最大100(无分页)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "群成员列表(多群聚合去重,无分页),每项含 user_id/user_name;所有群外部群ID为空时返回空列表", + "children": [ + { + "name": "user_id", + "type": "string", + "required": true, + "description": "成员用户ID(外部IM用户ID,跨群去重)" + }, + { + "name": "user_name", + "type": "string", + "required": true, + "description": "成员用户名(该用户最新一条消息的 user_name,无则为空字符串)" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "groupIds 无效 / warehouseId 无效" + }, + { + "code": "500", + "message": "群不存在或无权限操作" + } + ] + } + ] + }, + { + "groupName": "回信引擎配置(v2)", + "module": "inbox", + "list": [ + { + "method": "inbox.v2.type.list", + "description": "售后类型列表(系统级+本仓库自定义,分页);warehouseId 从登录上下文注入", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "isEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "启用状态筛选:1/0" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20,最大 200" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "类型列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ] + }, + { + "method": "inbox.v2.type.create", + "description": "创建仓库自定义售后类型;系统级只读", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "类型编码(≤20),仓库内唯一" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "类型名称(≤50)" + }, + { + "name": "sortOrder", + "type": "number", + "required": false, + "source": "body", + "description": "排序值,默认 0" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新类型ID" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.type.update", + "description": "更新仓库自定义售后类型(name/isEnabled/sortOrder);系统预设类型拒绝修改", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "类型ID" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "新名称" + }, + { + "name": "isEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "1 启用 0 停用" + }, + { + "name": "sortOrder", + "type": "number", + "required": false, + "source": "body", + "description": "排序值" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.type.delete", + "description": "删除仓库自定义售后类型(无子类型引用才可删);系统预设类型拒绝删除", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "类型ID" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.subType.list", + "description": "售后子类型列表(系统级+本仓库自定义,分页,可按类型/启用状态筛选)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "类型编码筛选" + }, + { + "name": "isEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "启用状态筛选:1/0" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "子类型列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ] + }, + { + "method": "inbox.v2.subType.create", + "description": "创建仓库自定义子类型(可挂在系统级类型或本仓库自定义类型下;子类型写入本仓库,后续关键词/函数/取号/白名单/回复均可写)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "所属类型编码" + }, + { + "name": "subType", + "type": "string", + "required": true, + "source": "body", + "description": "子类型编码(≤50)" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "子类型名称(≤50)" + }, + { + "name": "sortOrder", + "type": "number", + "required": false, + "source": "body", + "description": "排序值" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新子类型ID" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.subType.update", + "description": "更新仓库自定义子类型(name/isEnabled/sortOrder);系统预设拒绝修改", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "新名称" + }, + { + "name": "isEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "1 启用 0 停用" + }, + { + "name": "sortOrder", + "type": "number", + "required": false, + "source": "body", + "description": "排序值" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.subType.delete", + "description": "删除仓库自定义子类型,自动级联清理关联(关键词/函数关联/取号关联/群白名单/回复);系统预设拒绝删除", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果(含级联清理统计)" + } + ] + }, + { + "method": "inbox.v2.keyword.list", + "description": "关键词列表(系统级+本仓库自定义,分页,可按子类型/启用状态筛选)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": false, + "source": "body", + "description": "子类型ID筛选" + }, + { + "name": "isEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "启用状态筛选" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "关键词列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ] + }, + { + "method": "inbox.v2.keyword.create", + "description": "创建仓库自定义关键词(关键词为仓库级数据,可绑定系统级或本仓库自定义子类型;同一仓库内关键词唯一);系统预设关键词只读", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + }, + { + "name": "keyword", + "type": "string", + "required": true, + "source": "body", + "description": "关键词(≤100),仓库内唯一" + }, + { + "name": "sortOrder", + "type": "number", + "required": false, + "source": "body", + "description": "排序值" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新关键词ID" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.keyword.update", + "description": "更新仓库自定义关键词(keyword/subTypeId/isEnabled/sortOrder);系统预设拒绝修改", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "关键词ID" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "新关键词" + }, + { + "name": "subTypeId", + "type": "number", + "required": false, + "source": "body", + "description": "新子类型ID" + }, + { + "name": "isEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "1 启用 0 停用" + }, + { + "name": "sortOrder", + "type": "number", + "required": false, + "source": "body", + "description": "排序值" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.keyword.delete", + "description": "删除仓库自定义关键词;系统预设拒绝删除", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "关键词ID" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.numberRule.list", + "description": "取号规则列表(全局资源只读,含 target/regexp/sort_order,供关联配置选择)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "取号规则列表" + } + ] + }, + { + "method": "inbox.v2.function.list", + "description": "处理函数列表(代码同步权威,含 in_registry 标记与 isEnabled 开关;可按启用状态/关键词筛选)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "isEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "启用状态筛选" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "编码/名称模糊搜索" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "函数列表(含 in_registry)" + } + ] + }, + { + "method": "inbox.v2.function.update", + "description": "更新函数排序(是否启用由代码硬编码,不做接口配置)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "函数ID" + }, + { + "name": "sortOrder", + "type": "number", + "required": false, + "source": "body", + "description": "排序值" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.reply.merged", + "description": "回复配置合并后生效配置:以全部有效子类型(系统级+本仓库)为基底,每子类型一条、全量返回;本仓库有自定义则返回仓库级并标记 is_custom=1,否则返回系统级(is_custom=0,warehouse_id=null);无回复配置的子类型返回初始值(id=null,reply={back_text},is_reply=1,create_work_order=1);无启用状态字段,停用即回退系统级由 restore 承担", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": false, + "source": "body", + "description": "子类型ID筛选" + } + ], + "response": [ + { + "name": "merged", + "type": "array", + "required": true, + "description": "合并后生效配置全量列表;元素字段:id/sub_type_id/type/sub_type/sub_type_name/warehouse_id/is_custom(1仓库级 0系统级)/reply/is_reply/create_work_order/no_number_hint/created_at/updated_at" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总条数" + } + ] + }, + { + "method": "inbox.v2.reply.create", + "description": "创建仓库级回复配置(每子类型一条,仓库级覆盖系统级;isReply=0 表示命中后静默;createWorkOrder=0 表示函数照常执行但内部跳过工单登记)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + }, + { + "name": "reply", + "type": "string", + "required": true, + "source": "body", + "description": "回复文案(支持 {keyword}/{express}/{sub_type_name}/{back_text} 占位符)" + }, + { + "name": "isReply", + "type": "number", + "required": false, + "source": "body", + "description": "1 回复 0 静默,默认 1" + }, + { + "name": "createWorkOrder", + "type": "number", + "required": false, + "source": "body", + "description": "1 函数正常创建工单(默认) 0 函数照常执行但内部跳过工单登记" + }, + { + "name": "noNumberHint", + "type": "string", + "required": false, + "source": "body", + "description": "未取到单据号时的引导语(≤500)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新回复ID" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.reply.update", + "description": "更新仓库级回复配置;系统级回复只读", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "回复ID" + }, + { + "name": "reply", + "type": "string", + "required": false, + "source": "body", + "description": "新回复文案" + }, + { + "name": "isReply", + "type": "number", + "required": false, + "source": "body", + "description": "1 回复 0 静默" + }, + { + "name": "createWorkOrder", + "type": "number", + "required": false, + "source": "body", + "description": "1 函数正常创建工单 0 函数照常执行但内部跳过工单登记" + }, + { + "name": "noNumberHint", + "type": "string", + "required": false, + "source": "body", + "description": "取号失败引导语" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.reply.delete", + "description": "删除仓库级回复配置;系统级回复只读", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "回复ID" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.reply.save", + "description": "保存仓库级回复配置(upsert,推荐接口):按传入字段保存,未传字段保持原值;无仓库级配置时按传入字段创建", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + }, + { + "name": "reply", + "type": "string", + "required": false, + "source": "body", + "description": "回复文案(≤2000)" + }, + { + "name": "isReply", + "type": "number", + "required": false, + "source": "body", + "description": "1 回复 0 静默,默认 1" + }, + { + "name": "createWorkOrder", + "type": "number", + "required": false, + "source": "body", + "description": "1 函数正常创建工单 0 函数照常执行但内部跳过工单登记" + }, + { + "name": "noNumberHint", + "type": "string", + "required": false, + "source": "body", + "description": "取号失败引导语(≤500)" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.reply.restore", + "description": "还原仓库级回复配置:删除仓库级行,回退到系统级配置(幂等,无仓库级配置时返回已是系统级)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.relation.function.list", + "description": "查询子类型的处理函数关联列表(含函数编码/名称,按 sort_order)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "关联列表" + } + ] + }, + { + "method": "inbox.v2.relation.function.set", + "description": "全量替换子类型的处理函数关联(items=[{functionId,sortOrder}]);仅本仓库自定义子类型可写,系统子类型关联只读", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + }, + { + "name": "items", + "type": "array", + "required": true, + "source": "body", + "description": "函数关联数组 [{functionId, sortOrder}]" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.relation.rule.list", + "description": "查询子类型的取号规则关联列表(含 target/规则名,按 sort_order)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "关联列表" + } + ] + }, + { + "method": "inbox.v2.relation.rule.set", + "description": "全量替换子类型的取号规则关联(items=[{ruleId,sortOrder}]);仅本仓库自定义子类型可写", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + }, + { + "name": "items", + "type": "array", + "required": true, + "source": "body", + "description": "取号规则关联数组 [{ruleId, sortOrder}]" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + }, + { + "method": "inbox.v2.relation.group.list", + "description": "查询子类型的群类型白名单关联列表(group_type + sub_group,含 is_system;sub_group='*' 表示主类型内所有子类型通配,group_type='*' 表示所有群)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "白名单关联列表" + } + ] + }, + { + "method": "inbox.v2.relation.group.set", + "description": "替换子类型的群白名单关联(items=[{groupType,subGroup,sortOrder}],groupType∈store/warehouse/express/'*';subGroup 支持 '*' 通配主类型下所有子类型且覆盖该主类型其他具体行;groupType='*' 表示所有群且覆盖其他具体类型行(subGroup 忽略,归一化为空));系统预设行(is_system=1)保留不可删", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subTypeId", + "type": "number", + "required": true, + "source": "body", + "description": "子类型ID" + }, + { + "name": "items", + "type": "array", + "required": true, + "source": "body", + "description": "白名单数组 [{groupType, subGroup, sortOrder}];subGroup='*' 表示该主类型下所有子类型通配,groupType='*' 表示所有群" + } + ], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "操作结果" + } + ] + } + ] + }, + { + "groupName": "店铺快递绑定策略模块", + "module": "storeExpressBindingPolicy", + "list": [ + { + "method": "storeExpressBindingPolicy.list", + "description": "分页查询策略列表,按priority DESC updated_at DESC排序", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,兼容pagination.page/currentPage" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页大小,兼容page_size/pagination.page_size,最大200" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "字段兼容id/custom_name/shop_name(数组)/store_ids(数组)/express_code/priority/is_enabled/regions(数组)/exclude_regions(数组)/prohibited_type_id(数组)/weight_type/min_weight_g/max_weight_g/creator_id/quickWhere" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "策略数组shop_name/store_ids/regions/exclude_regions/prohibited_type_id均为JSON数组,附带store_names/prohibited_type_names文本数组,express_name为快递名称" + }, + { + "name": "data.list[].store_names", + "type": "array", + "required": false, + "description": "货主名称文本数组,与store_ids一一对应" + }, + { + "name": "data.list[].prohibited_type_names", + "type": "array", + "required": false, + "description": "违禁品类型名称文本数组,与prohibited_type_id一一对应" + }, + { + "name": "data.list[].express_name", + "type": "string", + "required": false, + "description": "快递名称(含系统快递和自定义映射)" + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "业务状态码" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 401, + "message": "未认证" + } + ] + }, + { + "method": "storeExpressBindingPolicy.add", + "description": "新增策略。必填custom_name+express_code。weight_type默认0。同仓库custom_name唯一", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "custom_name", + "type": "string", + "required": true, + "source": "body", + "description": "策略名称同仓库唯一兼容customName" + }, + { + "name": "shop_name", + "type": "array", + "required": false, + "source": "body", + "description": "包含店铺名称字符串数组兼容shopName" + }, + { + "name": "store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "限定货主ID数字数组兼容storeIds" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "source": "body", + "description": "快递编码兼容expressCode" + }, + { + "name": "priority", + "type": "number", + "required": false, + "source": "body", + "description": "优先级默认0" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "0停用1启用默认1兼容isEnabled" + }, + { + "name": "regions", + "type": "array", + "required": false, + "source": "body", + "description": "限定地区字符串数组" + }, + { + "name": "exclude_regions", + "type": "array", + "required": false, + "source": "body", + "description": "排除地区字符串数组兼容excludeRegions" + }, + { + "name": "min_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "最小重量克兼容minWeightG" + }, + { + "name": "max_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "最大重量克兼容maxWeightG" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "source": "body", + "description": "0常规1轻货2重货3冷链默认0兼容weightType" + }, + { + "name": "prohibited_type_id", + "type": "array", + "required": false, + "source": "body", + "description": "违禁品类型ID数字数组兼容prohibitedTypeId" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注最大500字符" + }, + { + "name": "creator_id", + "type": "number", + "required": false, + "source": "body", + "description": "创建人账户ID兼容creatorId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "策略ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 401, + "message": "未认证" + }, + { + "code": 409, + "message": "同仓库策略名已存在" + } + ] + }, + { + "method": "storeExpressBindingPolicy.edit", + "description": "编辑策略必填id仅更新传入字段", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID兼容policy_id/policyId" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "兼容customName" + }, + { + "name": "shop_name", + "type": "array", + "required": false, + "source": "body", + "description": "包含店铺名称字符串数组兼容shopName" + }, + { + "name": "store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "限定货主ID数字数组兼容storeIds" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "兼容expressCode" + }, + { + "name": "priority", + "type": "number", + "required": false, + "source": "body", + "description": "优先级" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "兼容isEnabled" + }, + { + "name": "regions", + "type": "array", + "required": false, + "source": "body", + "description": "限定地区字符串数组" + }, + { + "name": "exclude_regions", + "type": "array", + "required": false, + "source": "body", + "description": "排除地区字符串数组兼容excludeRegions" + }, + { + "name": "min_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "兼容minWeightG" + }, + { + "name": "max_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "兼容maxWeightG" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "source": "body", + "description": "兼容weightType" + }, + { + "name": "prohibited_type_id", + "type": "array", + "required": false, + "source": "body", + "description": "违禁品类型ID数字数组兼容prohibitedTypeId" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "creator_id", + "type": "number", + "required": false, + "source": "body", + "description": "兼容creatorId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "策略ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 401, + "message": "未认证" + }, + { + "code": 404, + "message": "策略不存在" + }, + { + "code": 409, + "message": "同仓库策略名已存在" + } + ] + }, + { + "method": "storeExpressBindingPolicy.del", + "description": "软删除策略", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID兼容policy_id/policyId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "策略ID" + } + ], + "errors": [ + { + "code": 400, + "message": "id为空" + }, + { + "code": 401, + "message": "未认证" + }, + { + "code": 404, + "message": "策略不存在" + } + ] + } + ] + }, + { + "groupName": "售后模块", + "module": "afterSale", + "list": [ + { + "method": "afterSale.workList", + "description": "售后工作列表。仅返回当前用户角色组负责的待处理工单。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "可选筛选字段: type/sub_type/status/priority/after_sale_no/waybill_no/store_id/claim_status/carrier_claim_status" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'priority'|'created_at', sortOrder: 'asc'|'desc' }" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "售后单列表,每条含主表字段 + detail_count + store_name(货主名称:取合约表 wms_store_warehouse.store_remask 货主备注名称,无合约或备注为空时回退 wms_store.company_name 公司全称,无货主时为空字符串)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages }" + } + ] + }, + { + "method": "afterSale.auditList", + "description": "售后审计列表。全局售后单视图,不限角色组、不限状态。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "可选筛选字段: type/sub_type/status/priority/after_sale_no/waybill_no/store_id/role_group/claim_status/carrier_claim_status。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'priority'|'created_at', sortOrder: 'asc'|'desc' }" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "全局售后单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages }" + } + ] + }, + { + "method": "afterSale.detail", + "description": "售后单明细查询:返回主表信息、步骤列表(含附件)、关联详情(订单/运单/货主合约)。关联数据按 afterSale 中的 order_delivery_id / waybill_id / store_id 自动解析,任一查询失败不影响主流程。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后单主键ID" + } + ], + "response": [ + { + "name": "after_sale", + "type": "object", + "required": true, + "description": "售后主表完整记录(含格式化时间字段)" + }, + { + "name": "steps", + "type": "array", + "required": true, + "description": "售后进度步骤列表(含附件 attachments),按创建时间升序。售后主表 description(详细描述)非空时,列表第一条为默认描述虚拟步骤(action=售后描述、remark=详细描述、step_status=pending、created_at=主表创建时间、id=null、is_virtual=true、attachments=[],不落库)", + "list": [ + { + "value": "object", + "label": "{ id, after_sale_id, step_status, operator_id, action, remark, is_virtual, attachments: [{id,file_url,file_name}] }" + } + ] + }, + { + "name": "related", + "type": "object", + "required": true, + "description": "关联单据详情。仅在售后单关联了对应业务单据时有值,其他情况为空对象。" + }, + { + "name": "related.order", + "type": "object", + "required": false, + "description": "关联发货订单详情(order_delivery_id 不为空时)。含 delivery_order_code、status、current_table(main/dispatch/history)、recipient(收件人)、sender(发件人,从货主 subject_config 取)、items(订单商品明细数组)、pack_videos(打包视频列表)" + }, + { + "name": "related.waybill", + "type": "object", + "required": false, + "description": "关联运单详情(waybill_id 不为空时)。含 waybill_code、logistics_name(快递公司名称)、logistics_code(物流编码)、logistics_interface_name(使用的物流接口)、logistics_interface_id、status、is_back、is_intercept" + }, + { + "name": "related.store_contract", + "type": "object", + "required": false, + "description": "货主合约备注(store_id + warehouse_id 匹配时)。含 contract_id、store_remask(商家备注)、warehouse_remask(仓库备注)、store_use_status、warehouse_use_status" + } + ], + "errors": [ + { + "code": 404, + "message": "售后单不存在" + } + ] + }, + { + "method": "afterSale.create", + "description": "创建售后单:生成售后单号(AS+YYYYMMDD+6位序号),写入主表记录。warehouse_id 由服务端从 ctx.user.store_id 自动注入。关联单据ID可自动同步对应单号(如传 order_delivery_id 自动查 delivery_order_code)。role_group 默认 customer_service,status 默认 pending。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "售后类型:order | receiving | entry | stockout" + }, + { + "name": "sub_type", + "type": "string", + "required": true, + "source": "body", + "description": "售后子类型,与 type 组成二级分类,详见模型枚举" + }, + { + "name": "title", + "type": "string", + "required": true, + "source": "body", + "description": "售后标题(简要描述)" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "售后详细描述" + }, + { + "name": "priority", + "type": "integer", + "required": false, + "source": "body", + "description": "优先级,默认0(0=普通,10=紧急)" + }, + { + "name": "order_delivery_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联发货订单ID,兼容别名 order_id" + }, + { + "name": "waybill_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联运单ID(wms_order_express.id)" + }, + { + "name": "entry_order_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联入库单ID" + }, + { + "name": "order_stockout_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联出库单ID" + }, + { + "name": "receiving_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联收货单ID" + }, + { + "name": "store_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联货主ID" + }, + { + "name": "inbox_message_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联站内信ID" + } + ], + "response": [ + { + "name": "after_sale_no", + "type": "string", + "required": true, + "description": "售后单号" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "售后状态,创建默认 pending" + }, + { + "name": "role_group", + "type": "string", + "required": true, + "description": "角色组,创建默认 customer_service" + }, + { + "name": "id", + "type": "integer", + "required": true, + "description": "售后单主键ID" + } + ], + "errors": [] + }, + { + "method": "afterSale.transfer", + "description": "转单:将售后工单转给其他角色组处理。转单后原角色组不可见,目标角色组可见。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后工单主表ID" + }, + { + "name": "role_group", + "type": "string", + "required": true, + "source": "body", + "description": "目标角色组: customer_service(客服组) | warehouse(仓库组) | finance(财务组)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "转单备注/原因" + } + ], + "response": [ + { + "name": "after_sale_id", + "type": "integer", + "required": true, + "description": "售后工单ID" + }, + { + "name": "role_group", + "type": "string", + "required": true, + "description": "更新后的 role_group" + } + ] + }, + { + "method": "afterSale.handleWorkOrder", + "description": "处理售后工单:写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动将 role_group 回退到 customer_service;status=completed 时自动写入 resolution + resolved_at。步骤 action 由服务端固定为\"处理工单\",step_status 与主表 status 完全一致。status 不填或填错时默认 processing。新增 pending_feedback 状态用于内部处理完成等待外部反馈(如已将拦截信息发给运方,等待运方反馈后再决定是否继续处理)。填写处理备注(remark)时会同步发送到对应的货主售后群(工单无 store_id 时从来源消息所在群反查货主,不转发快递群),响应 notified_groups 返回发送的群数量。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后工单主表ID" + }, + { + "name": "status", + "type": "string", + "required": false, + "source": "body", + "description": "更新售后单状态: processing | pending_feedback | completed | closed | cancelled。不填或填错默认 processing。不含 pending(创建默认值)。pending_feedback=等待外部反馈" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "处理备注。填写后同步发送到对应的货主售后群,内容格式:\"【工单 售后单号】处理备注:备注内容\"" + }, + { + "name": "attachment_ids", + "type": "array", + "required": false, + "source": "body", + "description": "附件 file_id 数组,如 [123, 456]。自动绑定到本次步骤" + } + ], + "response": [ + { + "name": "detail_id", + "type": "integer", + "required": true, + "description": "本次写入的步骤ID(wms_after_sale_detail.id)" + }, + { + "name": "after_sale_id", + "type": "integer", + "required": true, + "description": "售后工单ID" + }, + { + "name": "notified_groups", + "type": "integer", + "required": false, + "description": "处理备注发送到的货主售后群数量(未填写备注或未找到货主售后群时为0)" + } + ], + "errors": [] + }, + { + "method": "afterSale.registerClaim", + "description": "登记售后理赔信息:一次性填入仓库理赔和运方理赔字段,同时写入进度步骤。两套理赔可同时填写(双赔场景)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后工单主表ID" + }, + { + "name": "claim_needed", + "type": "integer", + "required": false, + "source": "body", + "description": "仓库理赔标记: 0=不需要, 1=需要" + }, + { + "name": "claim_amount", + "type": "number", + "required": false, + "source": "body", + "description": "仓库理赔金额(元)" + }, + { + "name": "claim_status", + "type": "string", + "required": false, + "source": "body", + "description": "仓库理赔状态: pending | reviewing | approved | paid | monthly | rejected" + }, + { + "name": "carrier_claim_needed", + "type": "integer", + "required": false, + "source": "body", + "description": "运方理赔标记: 0=不需要, 1=需要" + }, + { + "name": "carrier_claim_amount", + "type": "number", + "required": false, + "source": "body", + "description": "运方理赔金额(元)" + }, + { + "name": "carrier_claim_status", + "type": "string", + "required": false, + "source": "body", + "description": "运方理赔状态: pending | reviewing | approved | paid | monthly | rejected" + }, + { + "name": "action", + "type": "string", + "required": true, + "source": "body", + "description": "操作动作描述,如\"登记仓库理赔\"、\"登记运方理赔\"" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "处理备注,如\"快递破损核定赔200元\"" + }, + { + "name": "attachment_ids", + "type": "array", + "required": false, + "source": "body", + "description": "附件 file_id 数组(破损照片、理赔单据等)" + } + ], + "response": [ + { + "name": "detail_id", + "type": "integer", + "required": true, + "description": "本次写入的步骤ID" + }, + { + "name": "after_sale_id", + "type": "integer", + "required": true, + "description": "售后工单ID" + } + ] + }, + { + "method": "afterSale.export", + "description": "提交售后审计列表导出任务(异步)。返回 task_id,通过 exportTaskProgress 查询进度。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,同 auditList.where" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序,同 auditList.sort" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID,用于轮询进度" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "pending | processing | completed | failed" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比 0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "状态说明" + } + ] + }, + { + "method": "afterSale.exportTaskProgress", + "description": "查询售后导出任务进度和下载链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "task_id", + "type": "string", + "required": true, + "source": "body", + "description": "export 接口返回的 task_id" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "pending | processing | completed | failed" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比 0-100" + }, + { + "name": "download_url", + "type": "string", + "required": false, + "description": "完成后的文件下载链接(仅 status=completed 时返回)" + } + ] + }, + { + "method": "afterSale.workCount", + "description": "快速查询当前用户待处理售后工单数量(角标用),返回count字段,前端>99显示99+。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [], + "response": [ + { + "name": "count", + "type": "integer", + "required": true + } + ] + }, + { + "method": "afterSale.batchSetPendingFeedback", + "description": "批量将售后工单设为“待反馈”状态,按仓库 policy_config.after_sale_followup_hours 配置自动计算每个工单的 followup_at(下次跟进时间)。所有工单在同一事务中处理,任一失败则全部回滚。终态工单(completed/closed/cancelled)不可回退、跨仓库工单会被拒绝并返回 failed 列表。非客服组工单自动将 role_group 回设为 customer_service。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "售后单主键ID列表,如 [1, 2, 3]。非正整数会被自动过滤。", + "list": [ + { + "value": "number", + "label": "售后单ID(正整数)" + } + ] + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "统一处理备注,所有工单共用同一备注内容" + } + ], + "response": [ + { + "name": "total", + "type": "integer", + "required": true, + "description": "传入的工单总数(过滤非正整数后)" + }, + { + "name": "success", + "type": "integer", + "required": true, + "description": "成功设为待反馈的工单数量" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "失败的工单列表,每项包含 id 和 reason", + "list": [ + { + "value": "object", + "label": "{ id: number, reason: string }" + } + ] + } + ], + "errors": [] + }, + { + "method": "afterSale.batchClose", + "description": "批量将售后工单完结或关闭。status=completed 时自动写入 resolved_at 并清除 followup_at;status=closed 时仅更新状态。所有工单在同一事务中处理,任一失败则全部回滚。终态工单(completed/closed/cancelled)不可重复操作、跨仓库工单会被拒绝并返回 failed 列表。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "售后单主键ID列表,如 [1, 2, 3]。非正整数会被自动过滤。", + "list": [ + { + "value": "number", + "label": "售后单ID(正整数)" + } + ] + }, + { + "name": "status", + "type": "string", + "required": true, + "source": "body", + "description": "目标状态:completed=完结(写入 resolved_at + resolution),closed=关闭(仅更新状态,不写入完结信息)" + }, + { + "name": "resolution", + "type": "string", + "required": false, + "source": "body", + "description": "完结处理结果说明,仅 status=completed 时写入" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "统一处理备注,所有工单共用同一备注内容" + } + ], + "response": [ + { + "name": "total", + "type": "integer", + "required": true, + "description": "传入的工单总数(过滤非正整数后)" + }, + { + "name": "success", + "type": "integer", + "required": true, + "description": "成功操作的工单数量" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "失败的工单列表,每项包含 id 和 reason", + "list": [ + { + "value": "object", + "label": "{ id: number, reason: string }" + } + ] + } + ], + "errors": [] + }, + { + "method": "afterSale.typeList", + "description": "售后类型列表:返回系统级(warehouse_id=null、is_system=1,全部仓库可见)与当前仓库自定义(is_system=0)类型的合并列表,默认按 sort_order 升序、id 升序,pageSize 上限 500。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 },pageSize 上限 500" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "可选筛选字段: id/type/name/is_system/is_enabled/sort_order/created_at/updated_at" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField, sortOrder },支持 id/type/name/is_enabled/sort_order/created_at/updated_at;不传默认 sort_order ASC, id ASC" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "售后类型列表,每条含 { id, warehouse_id, type, name, is_system, is_enabled, sort_order, created_at, updated_at };系统级 warehouse_id=null、is_system=1" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + } + ], + "errors": [] + }, + { + "method": "afterSale.typeCreate", + "description": "创建仓库自定义售后类型(is_system=0):warehouse_id 由服务端从当前仓库上下文自动注入,前端无需传递。type 编码仅允许小写字母/数字/下划线且长度≤20,不可与系统级编码重复,同仓库内唯一(MySQL 唯一索引 uk_type_warehouse 兜底)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "类型编码,仅允许 /^[a-z0-9_]+$/(小写字母/数字/下划线),长度≤20,不可与系统级编码重复" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "类型名称,长度≤50" + }, + { + "name": "sort_order", + "type": "number", + "required": false, + "source": "body", + "description": "排序值,越小越靠前,默认 0(非法值按 0 处理)" + }, + { + "name": "is_enabled", + "type": "integer", + "required": false, + "source": "body", + "description": "是否启用:1=启用(默认 1),0=停用" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "新类型主键ID" + }, + { + "name": "warehouse_id", + "type": "integer", + "required": true, + "description": "仓库ID(当前仓库自定义)" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "类型编码" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "类型名称" + }, + { + "name": "is_system", + "type": "integer", + "required": true, + "description": "是否系统级,固定 0(仓库自定义)" + }, + { + "name": "is_enabled", + "type": "integer", + "required": true, + "description": "是否启用:1=启用,0=停用" + }, + { + "name": "sort_order", + "type": "number", + "required": true, + "description": "排序值" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间(格式化字符串)" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间(格式化字符串)" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文,不能创建售后类型" + }, + { + "code": 400, + "message": "类型编码不能为空 / 只能包含小写字母、数字和下划线 / 长度不能超过20个字符" + }, + { + "code": 400, + "message": "类型名称不能为空 / 长度不能超过50个字符" + }, + { + "code": 409, + "message": "该类型编码与系统预设类型重复,不允许使用" + }, + { + "code": 409, + "message": "该类型编码在当前仓库已存在" + } + ] + }, + { + "method": "afterSale.typeUpdate", + "description": "更新仓库自定义售后类型:仅命中 id + 当前仓库 + is_system=0 的记录,系统级类型不允许修改(未命中统一返回 404)。仅允许修改 name/is_enabled/sort_order,type 编码不可变。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "类型主键ID" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "类型名称,长度≤50" + }, + { + "name": "is_enabled", + "type": "integer", + "required": false, + "source": "body", + "description": "是否启用:1=启用,0=停用" + }, + { + "name": "sort_order", + "type": "number", + "required": false, + "source": "body", + "description": "排序值,越小越靠前" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "类型主键ID" + }, + { + "name": "warehouse_id", + "type": "integer", + "required": true, + "description": "仓库ID" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "类型编码(不可变)" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "类型名称" + }, + { + "name": "is_system", + "type": "integer", + "required": true, + "description": "是否系统级,固定 0(仓库自定义)" + }, + { + "name": "is_enabled", + "type": "integer", + "required": true, + "description": "是否启用:1=启用,0=停用" + }, + { + "name": "sort_order", + "type": "number", + "required": true, + "description": "排序值" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间(格式化字符串)" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间(格式化字符串)" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文,不能修改售后类型" + }, + { + "code": 400, + "message": "售后类型ID不合法" + }, + { + "code": 400, + "message": "类型名称不能为空 / 长度不能超过50个字符" + }, + { + "code": 400, + "message": "没有需要更新的字段" + }, + { + "code": 404, + "message": "售后类型不存在、无权操作或为系统预设类型" + } + ] + }, + { + "method": "afterSale.typeDelete", + "description": "删除仓库自定义售后类型(不做级联删除):系统级类型禁止删除;删除前检查该类型下是否存在当前仓库自定义子类型,存在则拒绝(需先删除子类型)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "类型主键ID" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "删除结果对象" + }, + { + "name": "data.id", + "type": "integer", + "required": true, + "description": "被删除的类型ID" + }, + { + "name": "data.deleted", + "type": "boolean", + "required": true, + "description": "固定 true" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文,不能删除售后类型" + }, + { + "code": 400, + "message": "售后类型ID不合法" + }, + { + "code": 404, + "message": "售后类型不存在、无权操作或为系统预设类型" + }, + { + "code": 409, + "message": "该类型下存在当前仓库的自定义子类型,请先删除子类型" + } + ] + }, + { + "method": "afterSale.subTypeList", + "description": "售后子类型列表:返回系统级(warehouse_id=null、is_system=1)+ 当前仓库自定义(is_system=0)子类型的合并列表,默认按 sort_order 升序、id 升序;group=true 时额外按 type 分组返回 groups(基于全量过滤结果、不受分页影响,组内 sort_order 升序)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 },pageSize 上限 500" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "可选筛选字段: id/type/sub_type/name/is_system/is_enabled/sort_order/created_at/updated_at" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField, sortOrder },支持 id/type/sub_type/name/is_enabled/sort_order/created_at/updated_at;不传默认 sort_order ASC, id ASC" + }, + { + "name": "group", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按 type 分组返回 groups(true 时额外返回 groups 数组)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "售后子类型列表,每条含 { id, warehouse_id, type, sub_type, name, is_system, is_enabled, sort_order, created_at, updated_at }" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + }, + { + "name": "groups", + "type": "array", + "required": false, + "description": "group=true 时返回:按 type 分组,每组 { type, name, items: [...] },组内按 sort_order 升序、id 升序" + } + ], + "errors": [] + }, + { + "method": "afterSale.subTypeCreate", + "description": "创建仓库自定义售后子类型(is_system=0):所属 type 必须已存在(系统级或当前仓库自定义)且处于启用状态(is_enabled=1)。sub_type 编码仅允许小写字母/数字/下划线且长度≤50,不可与系统级同 type 下编码重复,同仓库同 type 下唯一(MySQL 唯一索引 uk_type_subtype_warehouse 兜底)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "所属类型编码,必须已存在且启用(is_enabled=1)" + }, + { + "name": "sub_type", + "type": "string", + "required": true, + "source": "body", + "description": "子类型编码,仅允许 /^[a-z0-9_]+$/(小写字母/数字/下划线),长度≤50,不可与系统级同 type 下编码重复" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "子类型名称,长度≤50" + }, + { + "name": "sort_order", + "type": "number", + "required": false, + "source": "body", + "description": "排序值,越小越靠前,默认 0(非法值按 0 处理)" + }, + { + "name": "is_enabled", + "type": "integer", + "required": false, + "source": "body", + "description": "是否启用:1=启用(默认 1),0=停用" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "新子类型主键ID" + }, + { + "name": "warehouse_id", + "type": "integer", + "required": true, + "description": "仓库ID(当前仓库自定义)" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "所属类型编码" + }, + { + "name": "sub_type", + "type": "string", + "required": true, + "description": "子类型编码" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "子类型名称" + }, + { + "name": "is_system", + "type": "integer", + "required": true, + "description": "是否系统级,固定 0(仓库自定义)" + }, + { + "name": "is_enabled", + "type": "integer", + "required": true, + "description": "是否启用:1=启用,0=停用" + }, + { + "name": "sort_order", + "type": "number", + "required": true, + "description": "排序值" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间(格式化字符串)" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间(格式化字符串)" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文,不能创建售后子类型" + }, + { + "code": 400, + "message": "类型编码不能为空 / 只能包含小写字母、数字和下划线 / 长度不能超过20个字符" + }, + { + "code": 400, + "message": "子类型编码不能为空 / 只能包含小写字母、数字和下划线 / 长度不能超过50个字符" + }, + { + "code": 400, + "message": "子类型名称不能为空 / 长度不能超过50个字符" + }, + { + "code": 400, + "message": "售后类型不存在" + }, + { + "code": 400, + "message": "售后类型已停用,不能添加子类型" + }, + { + "code": 409, + "message": "该子类型编码与系统预设重复,不允许使用" + }, + { + "code": 409, + "message": "该子类型编码在当前仓库已存在" + } + ] + }, + { + "method": "afterSale.subTypeUpdate", + "description": "更新仓库自定义售后子类型:仅命中 id + 当前仓库 + is_system=0 的记录,系统级子类型不允许修改。仅允许修改 name/is_enabled/sort_order,type 与 sub_type 编码均不可变。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "子类型主键ID" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "子类型名称,长度≤50" + }, + { + "name": "is_enabled", + "type": "integer", + "required": false, + "source": "body", + "description": "是否启用:1=启用,0=停用" + }, + { + "name": "sort_order", + "type": "number", + "required": false, + "source": "body", + "description": "排序值,越小越靠前" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "子类型主键ID" + }, + { + "name": "warehouse_id", + "type": "integer", + "required": true, + "description": "仓库ID" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "所属类型编码(不可变)" + }, + { + "name": "sub_type", + "type": "string", + "required": true, + "description": "子类型编码(不可变)" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "子类型名称" + }, + { + "name": "is_system", + "type": "integer", + "required": true, + "description": "是否系统级,固定 0(仓库自定义)" + }, + { + "name": "is_enabled", + "type": "integer", + "required": true, + "description": "是否启用:1=启用,0=停用" + }, + { + "name": "sort_order", + "type": "number", + "required": true, + "description": "排序值" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间(格式化字符串)" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间(格式化字符串)" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文,不能修改售后子类型" + }, + { + "code": 400, + "message": "售后子类型ID不合法" + }, + { + "code": 400, + "message": "子类型名称不能为空 / 长度不能超过50个字符" + }, + { + "code": 400, + "message": "没有需要更新的字段" + }, + { + "code": 404, + "message": "售后子类型不存在、无权操作或为系统预设类型" + } + ] + }, + { + "method": "afterSale.subTypeDelete", + "description": "删除仓库自定义售后子类型(不做级联):系统级子类型禁止删除;若该子类型已被当前仓库售后单使用(wms_after_sale 存在该 type/sub_type 引用),拒绝删除。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "子类型主键ID" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "删除结果对象" + }, + { + "name": "data.id", + "type": "integer", + "required": true, + "description": "被删除的子类型ID" + }, + { + "name": "data.deleted", + "type": "boolean", + "required": true, + "description": "固定 true" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文,不能删除售后子类型" + }, + { + "code": 400, + "message": "售后子类型ID不合法" + }, + { + "code": 404, + "message": "售后子类型不存在、无权操作或为系统预设类型" + }, + { + "code": 409, + "message": "该子类型已被售后单使用,无法删除" + } + ] + } + ] + }, + { + "groupName": "退回收到模块", + "module": "returnReceived", + "list": [ + { + "method": "returnReceived.create", + "description": "退回包裹扫码登记。30日内同仓库同单号只写一次(以第一次为准);反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 并同步标记 is_back='Y',同步处理关联拦截工单、更新订单拦截状态(不释放拦截锁定库存,拦截锁回落由后续入库处理链路接管)。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。响应新增 is_urgent 加急标记(boolean):wms_return_query_log(退回查询记录表)中存在 warehouse_id=当前仓库且 waybill_code=登记运单号(精确匹配)的记录时为 true,否则 false;查询失败时降级为 false。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "退回收件运单号(扫描到的退回包裹单号)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "return_received_task_id", + "type": "number", + "required": false, + "source": "body", + "description": "收件任务ID(wms_return_received_task.id),不传默认 1=系统预设「历史收件」;服务端缓存校验(return_received_task:{id}),任务不存在/非法/不属于当前仓库报 400" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "登记记录包装对象,含登记记录完整字段(id、waybill_code、scan_date、scanner_id、scanner_name、order_express_id、order_id、store_id、remark、created_at、updated_at 等,时间字段为格式化字符串)及派生字段 is_original_return、store_remark" + }, + { + "name": "is_original_return", + "type": "boolean", + "required": true, + "description": "是否原单退回" + }, + { + "name": "store_remark", + "type": "string", + "required": true, + "description": "货主的合约货主备注名称(wms_store_warehouse.store_remask),非原单退回时为空字符串" + }, + { + "name": "is_urgent", + "type": "boolean", + "required": true, + "description": "加急标记:wms_return_query_log(退回查询记录表)中存在 warehouse_id=当前仓库且 waybill_code=登记运单号(精确匹配)的记录时为 true,否则 false;查询失败时降级为 false。幂等命中(duplicated=true)与新创建(duplicated=false)均返回" + }, + { + "name": "duplicated", + "type": "boolean", + "required": true, + "description": "是否命中30日幂等、返回第一次记录" + } + ], + "errors": [ + { + "code": "400", + "message": "waybill_code 不能为空" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "缺少扫描人员工号上下文" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + } + ] + }, + { + "method": "returnReceived.list", + "description": "退回收到登记分页列表。仓库隔离(服务端自动注入 warehouse_id = ctx.user.store_id,禁止前端传入)。支持按运单号模糊、扫描日期/登记时间/更新时间范围、扫描人员(ID/名称)、货主、运单/订单ID、是否原单退回筛选。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均可选" + }, + { + "name": "where.waybill_code", + "type": "string", + "required": false, + "source": "body.where", + "description": "退回收件运单号(模糊搜索,传 {operator:'like',value} 或直接值;value 为数组时多值 OR 包含匹配)" + }, + { + "name": "where.scan_date", + "type": "object", + "required": false, + "source": "body.where", + "description": "扫描日期范围 { operator:'between'|'gte'|'lte', value:[start,end] 或单值 }" + }, + { + "name": "where.created_at", + "type": "object", + "required": false, + "source": "body.where", + "description": "登记时间范围 { operator:'between'|'gte'|'lte', value:[start,end] 或单值 }" + }, + { + "name": "where.updated_at", + "type": "object", + "required": false, + "source": "body.where", + "description": "更新时间范围 { operator:'between'|'gte'|'lte', value:[start,end] 或单值 }" + }, + { + "name": "where.scanner_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "扫描人员工号ID(等值)" + }, + { + "name": "where.scanner_name", + "type": "string", + "required": false, + "source": "body.where", + "description": "扫描人员名称快照(等值)" + }, + { + "name": "where.store_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值)" + }, + { + "name": "where.order_express_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "运单ID(等值,原单退回时回填)" + }, + { + "name": "where.order_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "订单ID(等值,原单退回时回填)" + }, + { + "name": "where.is_original_return", + "type": "boolean", + "required": false, + "source": "body.where", + "description": "是否原单退回:true=有关联原运单,false=无关联" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'scan_date'|'created_at'|'updated_at'|'waybill_code', sortOrder: 'asc'|'desc' }" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "退回收到登记列表,每条含登记字段 + is_original_return + store_remark" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + } + ] + }, + { + "method": "returnReceived.detail", + "description": "退回收到登记详情,含原运单(命中时)与货主合约备注(命中时)。免权限但需登录,仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "登记记录完整信息(含 is_original_return、store_remark、格式化时间字段)" + }, + { + "name": "order_express", + "type": "object", + "required": false, + "description": "原运单详情(order_express_id 不为空时)。含 waybill_code、order_id、store_id、warehouse_id、is_back、is_intercept、logistics_name、logistics_code" + }, + { + "name": "store_contract", + "type": "object", + "required": false, + "description": "货主合约备注(store_id 不为空时)。含 store_remask、warehouse_remask、store_use_status、warehouse_use_status" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "404", + "message": "登记记录不存在" + } + ] + }, + { + "method": "returnReceived.delete", + "description": "删除退回收到登记记录(物理删除)。仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "被删除登记记录ID" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "404", + "message": "登记记录不存在" + } + ] + }, + { + "method": "returnReceived.export", + "description": "提交退回收到登记列表导出任务(异步)。入参 where/sort 语义与 returnReceived.list 一致;warehouse_id 由服务端从 ctx.user.store_id 注入,禁止前端传入。提交后立即返回 task_id,后台异步生成单 Sheet Excel(Sheet「退回收到登记列表」)并上传,导出进度/下载请通过 returnReceived.exportTaskProgress 查询。数据来源 wms_return_received 登记表;Excel 列:运单号/扫描日期/扫描人员/是否原单退回/订单ID/货主备注/备注/登记时间/更新时间。全量分页拉取(500/页,无行数上限);任务缓存 Redis TTL 30 分钟;状态口径 submitted → running(5) → 数据拉取(10~55,未命中数据时直接 85) → Excel 生成(60) → success(100),失败 failed + error。权限口径:默认走 API 权限校验(需 wms_permission 存在 returnReceived.export 类型为 api 的记录),需登录。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件,语义与 returnReceived.list 的 where 一致(支持 {operator,value} 标准结构或直接值;字段含 waybill_code 模糊(like 支持数组多值 OR 包含)、scan_date/created_at/updated_at 范围、scanner_id/scanner_name/store_id/order_express_id/order_id/return_received_task_id 等值、is_original_return 是否原单退回);禁止传入 warehouse_id/warehouseId(服务端注入)" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,语义与 returnReceived.list 的 sort 一致:sortField 白名单 id/scan_date/created_at/updated_at/waybill_code,sortOrder asc/desc,默认 created_at desc" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成,格式 return_received_export_{warehouseId}_{timestamp}_{random})" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态,枚举:submitted/running/success/failed/not_found(提交成功时为 submitted)" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "当前进度百分比(0-100),提交时返回 0" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理记录数(登记记录条数)" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "总记录数(若有)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果(提交时为 null;后台完成后为上传信息对象,含 filename/url/fileKey/cdnUrl/cosUrl/current_count/total_count)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(非失败时为空字符串)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式不正确、where 条件非法或缺少仓库上下文" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "导出任务提交失败" + } + ] + }, + { + "method": "returnReceived.exportTaskProgress", + "description": "按 task_id 查询退回收到导出任务进度,返回 task_id、status、progress、current_count、total_count、message、result、error、download_url、update_time;上传完成后 download_url 返回下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);任务缓存 Redis TTL 30 分钟,task_id 缺失或缓存未命中时 status=not_found(正常响应,非报错)。状态口径 submitted → running(5) → 数据拉取(10~55) → Excel 生成(60) → success(100),失败 failed + error。权限口径与 returnReceived.export 一致(默认走 API 权限校验,需 wms_permission 存在 returnReceived.exportTaskProgress 类型为 api 的记录),需登录。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID,兼容 task_id(下划线)与 taskId(驼峰)两种写法" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(task_id 缺失时为回显的空字符串,status=not_found)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理记录数(登记记录条数)" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果对象(完成后含 filename/url/fileKey/cdnUrl/cosUrl 等;未完成或 not_found 时为 null)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(非失败时为空字符串)" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务完成后下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);未完成或不存在时为空字符串" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "最近一次状态更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "查询失败或内部错误" + } + ] + } + ] + }, + { + "groupName": "收件任务模块", + "module": "returnReceivedTask", + "list": [ + { + "method": "returnReceivedTask.create", + "description": "创建收件任务。主键 id 自增从 10000 开始(表级 AUTO_INCREMENT);批次号 batch_no 一律由服务端自动生成(格式 RT+YYYYMMDD+5位序号,如 RT2026100500001,基于 wms_number_sequence 序列表原子取号、全局递增、并发不撞号,参考波次号机制),**不接收外部输入**(前端传入 batch_no/batchNo 均被忽略);warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,creator_id/creator_name 从上下文(账号ID/员工名称)自动注入,禁止前端传入。系统预设任务 id=1(历史收件,warehouse_id=0)用于承接历史退回收件登记。权限口径:需要登录,免 API 权限校验(无需 wms_permission 记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "title", + "type": "string", + "required": false, + "source": "body", + "description": "标题(任务名称,最长 100 字符,缺省为空串)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "收件任务ID(自增从 10000 开始)" + }, + { + "name": "batch_no", + "type": "string", + "required": true, + "description": "批次号" + }, + { + "name": "title", + "type": "string", + "required": true, + "description": "标题" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(服务端注入)" + }, + { + "name": "creator_id", + "type": "number", + "required": true, + "description": "创建人账户ID(服务端注入)" + }, + { + "name": "creator_name", + "type": "string", + "required": true, + "description": "创建人名称快照(服务端注入)" + }, + { + "name": "created_at / updated_at", + "type": "string", + "required": true, + "description": "创建时间/更新时间(YYYY-MM-DD HH:mm:ss 格式化字符串)" + } + ], + "errors": [ + { + "code": "400", + "message": "无法获取当前仓库上下文" + }, + { + "code": "400", + "message": "标题过长(最多100字符)" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "创建收件任务失败" + } + ] + }, + { + "method": "returnReceivedTask.list", + "description": "分页查询收件任务列表。warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入(返回本仓库任务 + 系统级任务 warehouse_id=0,如系统预设「历史收件」),禁止前端传入。搜索关键词 where.quickWhere:在 title(标题)/batch_no(编号)/creator_name(创建人)三个字段中 OR 模糊匹配;title/batch_no/creator_name 也可传 {operator,value} 标准结构(like 模糊/eq 精确/in 等);has_register 是否有登记(true=仅看有登记任务,false=仅看无登记任务,按当前仓库的 wms_return_received.return_received_task_id 引用判定,不跨仓);其他字段 id/creator_id/created_at/updated_at。每行返回 register_count(该任务在当前仓库下的退回收件登记数量,按 wms_return_received.return_received_task_id + warehouse_id=当前仓库 分组统计,系统级任务如「历史收件」也只统计当前仓库,无登记为 0)。排序 sort:sortField 白名单 id/batch_no/created_at/updated_at,sortOrder asc/desc,默认 id desc;分页 pagination:page/pageSize(pageSize 上限 500)。时间字段返回格式化字符串(YYYY-MM-DD HH:mm:ss)。权限口径:需要登录,免 API 权限校验(无需 wms_permission 记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件:quickWhere 关键词在 title/batch_no/creator_name 三个字段中 OR 模糊匹配;title/batch_no/creator_name 支持 {operator,value} 标准结构(like/eq/in 等);has_register 是否有登记(true/false,按当前仓库判定不跨仓);id/creator_id 等值或 in;created_at/updated_at 范围;禁止传入 warehouse_id/warehouseId(服务端注入)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数:page(页码,默认1)、pageSize(每页数量,默认20,上限500)" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数:sortField 白名单 id/batch_no/created_at/updated_at,sortOrder asc/desc,默认 id desc" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "任务行列表,每行含 id/batch_no/title/warehouse_id/creator_id/creator_name/created_at/updated_at(时间字段为格式化字符串)及 register_count(该任务下的退回收件登记数量,无登记为 0)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息:page/pageSize/total/totalPages/hasPrevious/hasNext" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "查询列表失败" + } + ] + }, + { + "method": "returnReceivedTask.delete", + "description": "删除收件任务(硬删除,物理删除行)。兼容两种入参:① ids(数组或单值,单次上限 200)批量删除——逐条分流不整体报错,任务不存在、系统预设 id=1(历史收件)、非当前仓库任务、已有收件登记(wms_return_received.return_received_task_id 引用)的任务计入 skipped_ids,其余硬删除并清理任务校验缓存(return_received_task:{id}),返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids }(保持入参顺序);② id(单值)单值删除——不满足条件抛出 404/409,返回 { id, deleted: true }。warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,禁止前端传入。权限口径:需要登录,免 API 权限校验(无需 wms_permission 记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "收件任务ID数组(批量删除,兼容单值,去重后单次上限 200;优先于 id)" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "收件任务ID(单值删除,正整数)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "单值删除:被删除的收件任务ID(批量删除时不返回)" + }, + { + "name": "deleted", + "type": "boolean", + "required": true, + "description": "单值删除:是否已删除(恒为 true;批量删除时不返回)" + }, + { + "name": "total / deleted_count / skipped_count / deleted_ids / skipped_ids", + "type": "object", + "required": true, + "description": "批量删除(传 ids)时返回:total=入参去重总数,deleted_count=实际删除数,skipped_count=跳过数(不存在/系统预设/非本仓库/已有登记),deleted_ids/skipped_ids 保持入参顺序" + } + ], + "errors": [ + { + "code": "400", + "message": "收件任务ID不合法" + }, + { + "code": "404", + "message": "收件任务不存在" + }, + { + "code": "404", + "message": "系统预设任务不可删除" + }, + { + "code": "404", + "message": "收件任务不存在或无权操作" + }, + { + "code": "409", + "message": "该任务已有收件登记,无法删除" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "删除收件任务失败" + } + ] + }, + { + "method": "returnReceivedTask.batchDelete", + "description": "批量删除收件任务(硬删除,物理删除行)。逐条分流不整体报错:任务不存在、系统预设 id=1(历史收件)、非当前仓库任务、已有收件登记(wms_return_received.return_received_task_id 引用)的任务均计入 skipped_ids,其余任务硬删除并清理任务校验缓存(return_received_task:{id})。warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,禁止前端传入。入参 ids 支持数组或单值(去重后上限 200);返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids }(保持入参顺序)。权限口径:需要登录,免 API 权限校验(无需 wms_permission 记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "收件任务ID数组(兼容单值,去重后单次上限 200)" + } + ], + "response": [ + { + "name": "total", + "type": "number", + "required": true, + "description": "入参去重后的任务ID总数" + }, + { + "name": "deleted_count", + "type": "number", + "required": true, + "description": "实际删除数量" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "跳过数量(不存在/系统预设/非本仓库/已有登记)" + }, + { + "name": "deleted_ids", + "type": "array", + "required": true, + "description": "已删除的任务ID列表(保持入参顺序)" + }, + { + "name": "skipped_ids", + "type": "array", + "required": true, + "description": "跳过的任务ID列表(保持入参顺序)" + } + ], + "errors": [ + { + "code": "400", + "message": "ids 不能为空" + }, + { + "code": "400", + "message": "单次最多删除 200 个收件任务" + }, + { + "code": "400", + "message": "无法获取当前仓库上下文" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "批量删除收件任务失败" + } + ] + } + ] + }, + { + "groupName": "退回拆包模块", + "module": "returnUnpack", + "list": [ + { + "method": "returnUnpack.create", + "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时,不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频(record.videos)+原订单详情(order),并携带 reused=true 标识;同运单号存在多张拆包单时优先复用已录明细的最新单(按明细表真实计数判定),超过 3 个月视为运单号已复用,按新单正常创建。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "拆包的运单号(退回包裹运单号,必填,用于反查原单/货主信息)" + }, + { + "name": "camera_ids", + "type": "array", + "required": false, + "source": "body", + "description": "摄像头ID列表,如 [1,2,3],关联 wms_camera.id(非正整数会被过滤)" + }, + { + "name": "return_received_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联退回收到单ID(wms_return_received.id),非必填,允许独立拆包" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "拆包单主键ID(后续明细收录的依据,传给 returnUnpack.addDetail)" + }, + { + "name": "record", + "type": "object", + "required": true, + "description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id/source_order_codes/shop_name 快照及 is_original_return 派生字段);幂等复用命中已有拆包单时,record 为已有单的详情记录并携带 details 明细数组(含 stockWarehouse 关联,识别明细另附加 stock 库存详情对象:barcodes 条码数组/image_url 图片数组等)、videos 视频数组与 returnReceived 关联" + }, + { + "name": "is_original_return", + "type": "boolean", + "required": true, + "description": "是否原单退回(反查 wms_order_express.waybill_code 命中为 true)" + }, + { + "name": "store_remark", + "type": "string", + "required": true, + "description": "货主的合约货主备注名称(wms_store_warehouse.store_remask),未命中时为空字符串" + }, + { + "name": "order", + "type": "object", + "required": false, + "description": "原订单详情(含 items 明细,仅原单退回时返回,非原单为 null)" + }, + { + "name": "order_items", + "type": "array", + "required": false, + "description": "原订单商品明细数组(即 order.items 的顶层透出,含 item_code/item_name/sku_property/quantity/plan_qty/barcodes/image_url 等,仅原单退回时返回;非原单退回或原订单详情缺失时为 null)" + }, + { + "name": "reused", + "type": "boolean", + "required": false, + "description": "是否幂等复用已有拆包单(true 表示 3 个月内同仓库同运单号已有非 cancelled 拆包单,本次未新建,record.details 即已有明细;新建时为 false 或不返回)" + } + ], + "errors": [ + { + "code": "400", + "message": "waybill_code 不能为空" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "缺少拆包人员工号上下文" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.addDetail", + "description": "录明细:以拆包单ID为依据录入一条明细。主单非终态(unpacking)校验;stock_id 有值时校验货主归属并回填识别快照(is_recognized=1 + item_code/item_name/spec/product_snapshot),未指定 stock_id 时一律标注未知商品(is_recognized=0,item_name=未知商品),不做条码自动匹配(同一条码可能对应多个 stock_id,自动匹配易误配),barcode 仅作记录;主表 store_id 为空时以首个识别商品回填主表货主。写明细后重算主表 total_items/total_quantity/detail_status。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID(returnUnpack.create 返回的依据)" + }, + { + "name": "stock_id", + "type": "integer", + "required": false, + "source": "body", + "description": "系统商品ID(wms_stock_warehouse.id),为空即无关联货物(商品名称标注未知商品)" + }, + { + "name": "barcode", + "type": "string", + "required": false, + "source": "body", + "description": "扫描条码(最长100字符,仅作记录,不参与商品匹配)" + }, + { + "name": "quantity", + "type": "integer", + "required": false, + "source": "body", + "description": "数量,默认 1(小于 1 按 1 处理)" + }, + { + "name": "product_status", + "type": "string", + "required": false, + "source": "body", + "description": "产品状态:normal 正常(默认)/ damaged 破损" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "detail_id", + "type": "integer", + "required": true, + "description": "新增明细ID(供 returnUnpack.updateDetail / returnUnpack.removeDetail 使用)" + }, + { + "name": "detail", + "type": "object", + "required": true, + "description": "新增的明细行(含 barcode/is_recognized/item_code/item_name(未知商品)/spec/product_snapshot 等;识别到系统商品时附加 stock 库存详情对象,含 item_code/item_name/sku_property/barcodes 条码数组/image_url 图片数组/packing_requirements/stock_unit 等,由 getStockDetails 通用方法拉取)" + }, + { + "name": "total_items", + "type": "integer", + "required": true, + "description": "主表最新物品种类数(明细行数)" + }, + { + "name": "total_quantity", + "type": "integer", + "required": true, + "description": "主表最新物品总数量(明细数量合计)" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "主表最新明细识别状态:none_recognized 全未识别 / partial_recognized 部分识别 / all_recognized 全部识别" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "该商品不属于当前货主,无法录入" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "404", + "message": "系统商品不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.updateDetail", + "description": "更新明细:仅允许更新 quantity/remark(更新范围白名单,暂限这两个字段)。校验拆包单存在且非终态(unpacking)、明细属于该拆包单;仅 quantity 变更时重算主表 total_quantity(total_items/detail_status 不变)。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + }, + { + "name": "detail_id", + "type": "integer", + "required": true, + "source": "body", + "description": "明细ID(returnUnpack.addDetail 返回)" + }, + { + "name": "quantity", + "type": "integer", + "required": false, + "source": "body", + "description": "数量(小于 1 按 1 处理,变更时才触发主表重算)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "detail", + "type": "object", + "required": true, + "description": "更新后的明细行(识别到系统商品时附加 stock 库存详情对象,含 barcodes 条码数组/image_url 图片数组等,由 getStockDetails 通用方法拉取)" + }, + { + "name": "total_items", + "type": "integer", + "required": true, + "description": "主表最新物品种类数" + }, + { + "name": "total_quantity", + "type": "integer", + "required": true, + "description": "主表最新物品总数量(quantity 变更时重算)" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "主表最新明细识别状态:none_recognized/partial_recognized/all_recognized" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "detail_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "404", + "message": "明细不存在或不属于该拆包单" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.removeDetail", + "description": "移除明细:删除拆包单下的一条明细(明细表 paranoid:false,硬删除/物理删除),并重算主表 total_items/total_quantity/detail_status。校验拆包单存在且非终态(unpacking)、明细属于该拆包单。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + }, + { + "name": "detail_id", + "type": "integer", + "required": true, + "source": "body", + "description": "明细ID(returnUnpack.addDetail 返回)" + } + ], + "response": [ + { + "name": "removed_detail_id", + "type": "integer", + "required": true, + "description": "被移除明细ID" + }, + { + "name": "total_items", + "type": "integer", + "required": true, + "description": "主表最新物品种类数" + }, + { + "name": "total_quantity", + "type": "integer", + "required": true, + "description": "主表最新物品总数量" + }, + { + "name": "detail_status", + "type": "string", + "required": true, + "description": "主表最新明细识别状态:none_recognized/partial_recognized/all_recognized" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "detail_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "404", + "message": "明细不存在或不属于该拆包单" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.cancel", + "description": "取消拆包单:仅在未完成(unpacking)状态可取消,事务内硬删除主表 + 该单所有明细,并同步软删视频副表记录。与 returnUnpack.delete 区别:cancel 仅供未完成状态作业取消;delete 为后台管理删除,不限制状态。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "被取消拆包单ID" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.submit", + "description": "提交确认:未完成(unpacking)拆包单转 completed 终态并回写 end_time(拆包结束时间;结束时间超过仓库配置的拆包最大录制时长上限时,自动截断为 开始时间+上限——仓库配置项 subject_config.return_unpack_max_record_minutes,默认 5 分钟,配置缺失/非法或开始时间缺失时不约束);同步按 warehouse_id+waybill_code 更新 wms_return_query_log.is_back=1(标记该运单号已退回,更新失败不阻断主流程)。提交后进入终态,不可再录/移除明细。仓库隔离校验(仅本仓库拆包单)。拆包完成后按退回查询登记来源定向通知:仅登记表 is_back=1 且 is_notified=0 的记录,按登记时记录的 group_id+user_id 回信原查询群/用户(有用户信息时定向回原查询用户,否则退化为来源群系统通知;登记无来源群的记录不通知),不再泛推货主售后群;推送成功标记 is_notified=1。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "更新后的主表记录(含 status=completed、end_time 及格式化时间字段;end_time 为按仓库拆包最大录制时长上限约束后的结束时间,超过上限时截断为 开始时间+上限)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "拆包单已提交或已取消,不可操作" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.forceRecord", + "description": "强制重新录制拆包视频。校验仓库录制电脑在线后,将视频记录(wms_return_unpack_video)重置为 created 并清空 video_url,再向打印服务 /record/force 推送 { unpack_id } 触发重新录制(参考 order.packing.forceRecord)。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "unpack_id", + "type": "integer", + "required": true, + "description": "拆包单ID" + }, + { + "name": "computer_id", + "type": "integer", + "required": true, + "description": "录制电脑ID(wms_print_computer.id,is_recording=true)" + }, + { + "name": "print_service_url", + "type": "string", + "required": true, + "description": "打印服务强制录制接口地址(POST {printService.url}/record/force)" + }, + { + "name": "print_service_request", + "type": "object", + "required": true, + "description": "推送给打印服务的请求体({ unpack_id })" + }, + { + "name": "print_service_response", + "type": "object", + "required": false, + "description": "打印服务响应(status/headers/data)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "该仓库无录制电脑,无法强制录制" + }, + { + "code": "400", + "message": "该仓库录制电脑不在线,无法强制录制" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "通知打印服务失败" + } + ] + }, + { + "method": "returnUnpack.list", + "description": "拆包单分页列表(主表)。仓库隔离:warehouse_id 由服务端自动注入 ctx.user.store_id,禁止前端传入。支持拆包单号/运单号模糊、日期/时间范围、状态、拆包人员、退回收到单、货主、原运单/原订单等筛选。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }(pageSize 上限 500,默认 20)" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均可选" + }, + { + "name": "where.unpack_no", + "type": "string", + "required": false, + "source": "body.where", + "description": "拆包单号(模糊搜索,传 {operator:'like',value} 或直接值)" + }, + { + "name": "where.waybill_code", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单号(模糊搜索,传 {operator:'like',value} 或直接值)" + }, + { + "name": "where.unpack_date", + "type": "object", + "required": false, + "source": "body.where", + "description": "拆包日期范围 { operator:'between'|'gte'|'lte'|'gt'|'lt', value:[start,end] 或单值 }" + }, + { + "name": "where.start_time", + "type": "object", + "required": false, + "source": "body.where", + "description": "拆包开始时间范围 { operator:'between'|'gte'|'lte'|'gt'|'lt', value:[start,end] 或单值 }" + }, + { + "name": "where.end_time", + "type": "object", + "required": false, + "source": "body.where", + "description": "拆包结束时间范围 { operator:'between'|'gte'|'lte'|'gt'|'lt', value:[start,end] 或单值 }" + }, + { + "name": "where.status", + "type": "string", + "required": false, + "source": "body.where", + "description": "拆包状态(等值):unpacking 拆包中 / completed 完成 / cancelled 作废" + }, + { + "name": "where.detail_status", + "type": "string", + "required": false, + "source": "body.where", + "description": "明细识别状态(等值):none_recognized / partial_recognized / all_recognized" + }, + { + "name": "where.unpacker_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "拆包人员工号ID(等值)" + }, + { + "name": "where.unpacker_name", + "type": "string", + "required": false, + "source": "body.where", + "description": "拆包人筛选:目标列 wms_return_unpack.unpacker_name(STRING(50),拆包人员工号名称快照)。传 {operator:'like',value} 或直接值 → 模糊 LIKE '%值%';value 为数组时多值 LIKE 取并集(trim/去空归一后为空退化为全匹配、不过滤);也支持 eq/ne/in/notin/between 等既有操作符" + }, + { + "name": "where.return_received_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "关联退回收到单ID(等值)" + }, + { + "name": "where.store_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值)" + }, + { + "name": "where.order_express_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "原运单ID(等值)" + }, + { + "name": "where.order_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "原订单ID(等值)" + }, + { + "name": "where.has_video", + "type": "number", + "required": false, + "source": "body.where", + "description": "是否有视频记录(等值):1=有视频记录 2=无视频记录" + }, + { + "name": "where.video_enable", + "type": "number", + "required": false, + "source": "body.where", + "description": "录像是否可用(等值):1=可用(存在 video_url 非空且 status!=failed 的记录) 2=不可用" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'created_at'|'updated_at'|'unpack_date'|'start_time'|'end_time'|'unpack_no'|'waybill_code', sortOrder: 'asc'|'desc' },默认 created_at desc" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "拆包单列表,每条含主表字段 + is_original_return 派生字段 + 格式化时间字段 + camera_ids 数组 + 视频派生字段 has_video(1=有视频记录/2=无)与 video_enable(1=录像可用/2=不可用)+ videos 视频数组(id/video_url/status/camera_id/camera_name),video_url 自动拼接 CDN 域名前缀 http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path}(录制电脑从 wms_print_computer 按 is_recording=true 获取,无录制电脑时返回原始相对路径)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.detailList", + "description": "拆包明细分页列表,命中识别商品时含 stockWarehouse 关联,并统一走 stockWarehouse.getStockDetails 通用方法为每条识别明细附加 stock 库存详情对象(item_code/item_name/sku_property/barcodes 条码数组/image_url 图片数组/packing_requirements/stock_unit/quantity/locked_quantity 等,带缓存)。仓库隔离:warehouse_id 由服务端自动注入 ctx.user.store_id,禁止前端传入。支持按拆包单ID、系统商品、条码、识别标记、产品状态筛选。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }(pageSize 上限 500,默认 20)" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均可选" + }, + { + "name": "where.unpack_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "拆包单ID(等值)" + }, + { + "name": "where.stock_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "系统商品ID(wms_stock_warehouse.id,等值)" + }, + { + "name": "where.barcode", + "type": "string", + "required": false, + "source": "body.where", + "description": "扫描条码(模糊搜索,传 {operator:'like',value} 或直接值)" + }, + { + "name": "where.is_recognized", + "type": "number", + "required": false, + "source": "body.where", + "description": "是否识别(等值):1 识别到系统商品 / 0 非识别物品" + }, + { + "name": "where.product_status", + "type": "string", + "required": false, + "source": "body.where", + "description": "产品状态(等值):normal 正常 / damaged 破损" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'created_at'|'updated_at'|'quantity', sortOrder: 'asc'|'desc' },默认 created_at desc" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "明细行列表(含 is_recognized/item_code/item_name/spec/product_snapshot,识别命中时含 stockWarehouse 关联与 stock 库存详情对象:barcodes 条码数组/image_url 图片数组/sku_property/packing_requirements/stock_unit 等)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.detail", + "description": "拆包单详情:主表 + 明细(含 stockWarehouse 关联,命中时;每条识别明细另附加 stock 库存详情对象,含 barcodes 条码数组/image_url 图片数组等,由 getStockDetails 通用方法拉取)+ 视频副表(含 camera 关联,命中时)+ 退回收到单(命中时);原单退回时(order_id 有值)返回 related.order 原订单详情。需 548 权限(客服员工及以上),仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "主表完整记录(含 details 明细、videos 视频(video_url 自动拼接 CDN 域名前缀 http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{path})、returnReceived 退回收到单关联与格式化时间字段)" + }, + { + "name": "related", + "type": "object", + "required": true, + "description": "关联信息对象" + }, + { + "name": "related.order", + "type": "object", + "required": false, + "description": "原订单详情(含 items 明细,仅原单退回时返回,非原单为 null)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.delete", + "description": "删除拆包单(后台管理,不限制状态):事务内物理删除主表 + 所有明细,并同步软删视频副表记录。作业层未完成状态取消请走 returnUnpack.cancel。仓库隔离校验(仅本仓库拆包单)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "拆包单ID" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "被删除拆包单ID" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该拆包单" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "拆包单不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnUnpack.export", + "description": "提交退回拆包导出任务(异步)。入参 where/sort 语义与 returnUnpack.list 一致;warehouse_id 由服务端从 ctx.user.store_id 注入,禁止前端传入。提交后立即返回 task_id,后台异步生成双 Sheet Excel(Sheet1「正常退回运单号列表」+ Sheet2「明细表」)并上传,导出进度/下载请通过 returnUnpack.exportTaskProgress 查询。数据来源 wms_return_unpack 主表 + wms_return_unpack_detail 明细表;货主名取自 wms_store.company_name,快递类型取自 wms_order_express.logistics_name;颜色列取自明细 product_snapshot.sku_property 中「颜色:xxx」片段(兜底 spec),无颜色信息为空;全量分页拉取,无行数上限;Sheet1 不加 status 过滤(如需只导特定状态由调用方传 where.status)。任务缓存 Redis TTL 30 分钟;状态口径 submitted → running → 数据拉取(10~30) → 明细拉取(30~50) → Excel(55~90) → 上传(92) → success(100),失败 failed + error。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件,语义与 returnUnpack.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 unpack_no/waybill_code/unpacker_name 模糊、unpack_date/start_time/end_time/created_at/updated_at 范围、status/detail_status/store_id/order_express_id/order_id/unpacker_id/return_received_id 等值、has_video/video_enable 等);禁止传入 warehouse_id/warehouseId(服务端注入);不传 status 时不过滤状态" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,语义与 returnUnpack.list 的 sort 一致:sortField 白名单 id/created_at/updated_at/unpack_date/start_time/end_time/unpack_no/waybill_code,sortOrder asc/desc,默认 created_at desc" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成,格式 return_unpack_export_{warehouseId}_{timestamp}_{random})" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态,枚举:submitted/running/success/failed/not_found(提交成功时为 submitted)" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "当前进度百分比(0-100),提交时返回 0" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理记录数(拆包单条数)" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "总记录数(若有)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果(提交时为 null;后台完成后为上传信息对象,含 filename/url/fileKey/cdnUrl/cosUrl/current_count/total_count/total_details/sheet_count)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选,非失败时为空字符串)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [ + { + "code": "400", + "message": "参数格式不正确或 where 条件非法" + }, + { + "code": "500", + "message": "导出任务提交失败" + } + ] + }, + { + "method": "returnUnpack.exportTaskProgress", + "description": "按 task_id 查询退回拆包导出任务进度,返回 task_id、status、progress、current_count、total_count、message、result、error、download_url、update_time;上传完成后 download_url 返回下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);任务缓存 Redis TTL 30 分钟,task_id 缺失或缓存未命中时 status=not_found(正常响应,非报错)。状态口径 submitted → running → 数据拉取(10~30) → 明细拉取(30~50) → Excel(55~90) → 上传(92) → success(100),失败 failed + error。免权限免日志口径与 order.exportTaskProgress 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID,兼容 task_id(下划线)与 taskId(驼峰)两种写法" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(task_id 缺失时为回显的空字符串,status=not_found)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理记录数(拆包单条数)" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": true, + "description": "任务执行结果对象(完成后含 filename/url/fileKey/cdnUrl/cosUrl 等;未完成或 not_found 时为 null)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息(可选,非失败时为空字符串)" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务完成后下载链接(从 result.url/cdnUrl/cosUrl/fileKey 兜底取);未完成或不存在时为空字符串" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "最近一次状态更新时间(Unix 毫秒时间戳)" + } + ], + "errors": [ + { + "code": "500", + "message": "查询失败或内部错误" + } + ] + }, + { + "method": "returnUnpack.transferByWaybills", + "description": "运单批量转入退件登记:一次调用把多个运单批量转入退回拆包登记。ids 为运单表主键ID(wms_order_express.id,支持单个数值或 JSON 数组),服务端 Number() 归一化 + 过滤非正整数 + 去重,去重后单次上限 200。仓库隔离:warehouse_id 由服务端从 ctx.user.store_id 注入,禁止前端传入。逐单处理,单条失败不阻断主流程,失败项进入 failed[](HTTP 整体仍成功)。单运单处理口径:1) 服务端按 id IN (ids) + 仓库一次批量反查 wms_order_express,未命中(不存在或非本仓库)记失败原因「运单不存在」;2) 子单(business_key>1)跳过并记失败原因「运单为子单(business_key>1),跳过」(不处理子单,一个运单只允许一条有效拆包单);3) 运单号为空时记失败原因「运单号为空,无法转入退件登记」;4) 命中运单统一置 wms_order_express.is_back='Y',不做其它前置条件限制(标记失败仅告警不阻断);5) 幂等:同仓库 + 同运单号已存在 status != 'cancelled' 的拆包单时直接复用(reused=true,不重复创建;同运单号多张时优先复用已录明细的最新单);复用单明细为空时按订单明细补写,已有明细不重复写入;6) 明细来源:运单关联订单的原本明细 1:1 复制(订单 items JSON 优先,为空回退明细分表;通过订单索引表 wms_order_id_location_{warehouseId} 定位车道,复用 ctx.service.systems.afterSale._resolveOrderDetail);订单无明细可复制时记失败原因「运单关联订单无明细可复制」;明细字段映射 stock_id / is_recognized / item_code / item_name / spec / quantity(订单行 plan_qty,最小 1)/ product_status='normal' / product_snapshot,写入后回填主表 total_items / total_quantity / detail_status;7) 命中退回收到登记(wms_return_received 同仓库 + 同运单号)时回填主表 return_received_id(失败仅告警不阻断)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "运单表主键ID列表(wms_order_express.id,也兼容单个数值,服务端统一归一化:Number() 转换 → 过滤非正整数 → 去重,去重后单次上限 200)" + } + ], + "response": [ + { + "name": "total", + "type": "number", + "required": true, + "description": "去重后待处理运单总数" + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功转入数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + }, + { + "name": "success", + "type": "array", + "required": true, + "description": "成功项数组,每项含 waybill_id(运单表主键ID)/ waybill_code(运单号)/ unpack_id(拆包单ID)/ unpack_no(拆包单号)/ reused(boolean,true=命中已有有效拆包单未重复创建)/ detail_count(明细行数)/ total_quantity(明细数量合计)" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "失败项数组,每项含 waybill_id(运单表主键ID)/ waybill_code(运单号,运单命中时才有值,否则为 null)/ reason(失败原因,如「运单不存在」「运单为子单(business_key>1),跳过」「运单号为空,无法转入退件登记」「运单关联订单无明细可复制」)" + } + ], + "errors": [ + { + "code": "400", + "message": "ids 不能为空" + }, + { + "code": "400", + "message": "单次最多批量转入 200 个运单" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "缺少拆包人员工号上下文" + }, + { + "code": "400", + "message": "运单为子单(business_key>1),跳过" + }, + { + "code": "400", + "message": "运单号为空,无法转入退件登记" + }, + { + "code": "400", + "message": "运单关联订单无明细可复制" + }, + { + "code": "404", + "message": "运单不存在" + }, + { + "code": "500", + "message": "反查运单失败,请稍后重试" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ], + "notes": [ + "单运单业务失败(运单不存在 / 子单跳过 / 运单号为空 / 订单无明细可复制)不抛 HTTP 错误,对应项进入 failed[](waybill_id + waybill_code + reason),整体响应仍为 success", + "鉴权口径:isNeedAuth=true、isNeedLogin=true,未加入 _noNeedRight/_noNeedLogin/_noNeedLog/_noNeedAuth 免检清单;权限 wms_permission id=568 path=returnUnpack.transferByWaybills(meta_title=API:运单批量转入退件登记),授权角色 27(仓库组-员工)/ 26(仓库组-主管),经理/仓库管理员/超级管理员持 * 通配符自动拥有", + "幂等复用命中时 reused=true 不重复创建;复用单明细为空时按订单明细补写,已有明细不重复写入", + "标记 wms_order_express.is_back='Y' 与回填 return_received_id 为尽力而为(失败仅告警不阻断主流程)" + ] + }, + { + "method": "returnUnpack.transferByOrders", + "description": "配送订单批量转退回拆包单:一次调用把多个配送订单批量转换为退回拆包单。ids 为订单表主键ID(wms_order_delivery*.id,支持单个数值或 JSON 数组),服务端 Number() 归一化 + 过滤非正整数 + 去重,去重后单次上限 200。仓库隔离:warehouse_id 由服务端从 ctx.user.store_id 注入,禁止前端传入。逐单处理,单条失败不阻断主流程。转换限制(静默跳过,不报错、不阻断其它订单):1) 仅允许「库内拦截」订单转换(intercept_status=intercepted_at_warehouse,兼容历史值 intercepted),非库内拦截订单跳过;2) 订单已有有效拆包单(wms_return_unpack 同仓库 + order_id 命中,或同运单号已存在,status != 'cancelled')跳过;3) 订单不存在/不属于当前仓库、无运单号、无明细可复制的订单同样跳过。每单新建一张拆包单:订单主运单(wms_order_express,business_key=1 优先)的 waybill_code 写入拆包单(无运单时回退订单发货单号),回填 order_express_id/order_id/store_id/source_order_codes/shop_name;明细直接使用订单原本明细 1:1 复制(订单 items JSON 优先,为空回退明细分表;通过订单索引表 wms_order_id_location_{warehouseId} 定位车道),product_status 固定 normal,写入后回填主表 total_items/total_quantity/detail_status。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "订单表主键ID列表(wms_order_delivery*.id,也兼容单个数值,服务端统一归一化:Number() 转换 → 过滤非正整数 → 去重,去重后单次上限 200)" + } + ], + "response": [ + { + "name": "total", + "type": "number", + "required": true, + "description": "去重后待处理订单总数" + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功创建拆包单的订单数量" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "静默跳过的订单数量(非库内拦截/已有拆包单/无运单号/无明细等)" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "处理失败的订单数量(非预期异常,如数据库写入失败)" + }, + { + "name": "success", + "type": "array", + "required": true, + "description": "成功项数组,每项含 order_id(订单ID)/ unpack_id(拆包单ID)/ unpack_no(拆包单号)/ waybill_code(写入拆包单的运单号)/ detail_count(明细行数)/ total_quantity(明细数量合计)" + }, + { + "name": "skipped", + "type": "array", + "required": true, + "description": "跳过项数组,每项含 order_id / reason(跳过原因,如「非库内拦截订单」「订单已存在拆包单」「运单号已存在拆包单」「订单无明细可复制」)" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "失败项数组,每项含 order_id / reason(失败原因)" + } + ], + "errors": [ + { + "code": "400", + "message": "ids 不能为空" + }, + { + "code": "400", + "message": "单次最多批量转换 200 个订单" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "缺少拆包人员工号上下文" + }, + { + "code": "500", + "message": "查询已有拆包单失败,请稍后重试" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ], + "notes": [ + "静默跳过口径:非库内拦截订单、已有有效拆包单的订单、订单不存在/不属于当前仓库、无运单号、无明细可复制均不抛错,进入 skipped[],整体响应仍为 success;仅非预期异常进入 failed[]", + "库内拦截判定:intercept_status === 'intercepted_at_warehouse'(recheckOrder.confirmIntercept / intercept_auto_confirm 写入),历史遗留值 'intercepted' 一并兼容", + "拆包单运单号来源:wms_order_express 同订单主运单(business_key=1 优先,其次最小 id)的 waybill_code;无运单时回退订单 delivery_order_code,二者都没有则跳过", + "明细口径:与 returnUnpack.transferByWaybills 一致,订单原本明细 1:1 复制(不做合并/换算),quantity 取订单行 plan_qty(最小 1),product_status 固定 normal,写入后回填主表 total_items/total_quantity/detail_status", + "鉴权口径:isNeedAuth=true、isNeedLogin=true,未加入 _noNeedRight/_noNeedLogin/_noNeedLog/_noNeedAuth 免检清单;权限 wms_permission id=643 path=returnUnpack.transferByOrders(meta_title=API:配送订单批量转退回拆包单),授权角色 27(仓库组-员工)/ 26(仓库组-主管),经理/仓库管理员/超级管理员持 * 通配符自动拥有" + ] + } + ] + }, + { + "groupName": "未退登记模块", + "module": "returnWaybill", + "list": [ + { + "method": "returnWaybill.create", + "description": "未退登记(增):录入「货主 + 运单号」退回关系。waybill_code/store_id 必填;校验 wms_store_warehouse 存在 store_id + warehouse_id 货主合约,无合约拒绝写入;同仓库+货主+运单号已存在时幂等返回已有记录(duplicated=true,不重复插入)。写入 is_notified=0/is_back=0(由定时任务与拆包联动维护,登记接口不维护)。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号(登记入参,必填,trim 后不能为空)" + }, + { + "name": "store_id", + "type": "integer", + "required": true, + "source": "body", + "description": "货主ID(必填,正整数,需存在 wms_store_warehouse 中 store_id + warehouse_id 合约记录)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(可选,最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "登记记录包装对象,含登记记录完整字段(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back、created_at、updated_at,时间字段为格式化字符串;group_id/group_name/user_id/user_name 为登记来源,仅站内信「查退回」触发登记时写入,后台登记为 null)" + }, + { + "name": "duplicated", + "type": "boolean", + "required": true, + "description": "是否命中已有记录:同仓库+货主+运单号已存在时为 true(返回已有记录,不重复插入),否则 false" + } + ], + "errors": [ + { + "code": "400", + "message": "waybill_code 不能为空" + }, + { + "code": "400", + "message": "store_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "货主在当前仓库无合约关系,无法登记" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnWaybill.update", + "description": "修改登记(改):id 必填,可改 waybill_code/store_id/remark。校验记录存在且属于当前仓库;store_id 变更时重新校验新货主合约(wms_store_warehouse 存在 store_id + warehouse_id);改后与另一条同仓库+货主+运单号冲突则 409 拒绝(防重复登记)。仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID(必填,正整数)" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "source": "body", + "description": "运单号(可选,改运单号,trim 后不能为空字符串)" + }, + { + "name": "store_id", + "type": "integer", + "required": false, + "source": "body", + "description": "货主ID(可选,改货主ID;变更时校验新货主在当前仓库的合约)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(可选,最长 500 字符,超出截断)" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "更新后的登记记录完整信息(含格式化时间字段)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "400", + "message": "waybill_code 不能为空" + }, + { + "code": "400", + "message": "store_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "货主在当前仓库无合约关系,无法登记" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "登记记录不存在" + }, + { + "code": "409", + "message": "已存在相同货主 + 运单号的登记记录" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnWaybill.list", + "description": "未退登记分页列表。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。支持按运单号模糊、货主、是否已通知、是否退回、登记时间范围筛选。is_notified/is_back 由定时任务与拆包联动维护,登记接口不维护。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }(pageSize 上限 500,默认 20)" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件对象,所有字段均可选" + }, + { + "name": "where.waybill_code", + "type": "string", + "required": false, + "source": "body.where", + "description": "运单号(模糊搜索,传 {operator:'like',value} 或直接值;value 为数组时多值 OR 包含匹配)" + }, + { + "name": "where.store_id", + "type": "number", + "required": false, + "source": "body.where", + "description": "货主ID(等值)" + }, + { + "name": "where.is_notified", + "type": "number", + "required": false, + "source": "body.where", + "description": "是否已通知(等值):1 已通知 / 0 未通知(由定时任务维护,登记接口不写入)" + }, + { + "name": "where.is_back", + "type": "number", + "required": false, + "source": "body.where", + "description": "是否退回(等值):1 已退回 / 0 未退回(由拆包单提交联动维护,登记接口不写入)" + }, + { + "name": "where.created_at", + "type": "object", + "required": false, + "source": "body.where", + "description": "登记日期范围 { operator:'between'|'gte'|'lte'|'gt'|'lt', value:[start,end] 或单值 }" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'created_at'|'updated_at'|'waybill_code', sortOrder: 'asc'|'desc' },默认 created_at desc" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "未退登记列表,每条含登记字段(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back)及格式化时间字段;group_id/group_name/user_id/user_name 为登记来源(站内信「查退回」触发时写入,后台登记为 null)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnWaybill.detail", + "description": "未退登记详情。免权限(复用列表权限),仅需登录 + 仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID(必填,正整数)" + } + ], + "response": [ + { + "name": "record", + "type": "object", + "required": true, + "description": "登记记录完整信息(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back 及格式化时间字段;来源字段仅站内信「查退回」触发登记时写入,后台登记为 null)" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "404", + "message": "登记记录不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + }, + { + "method": "returnWaybill.delete", + "description": "删除未退登记(物理删除,表 paranoid:false)。仓库隔离校验(仅本仓库记录)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "登记记录主键ID(必填,正整数)" + } + ], + "response": [ + { + "name": "id", + "type": "integer", + "required": true, + "description": "被删除登记记录ID" + } + ], + "errors": [ + { + "code": "400", + "message": "id 必填且必须为正整数" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该登记记录" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "404", + "message": "登记记录不存在" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ] + } + ] + }, + { + "groupName": "通用报表模块", + "module": "report", + "list": [ + { + "method": "report.generate", + "description": "提交报表导出异步任务(手动导出):按报表定义ID读取 wms_report_definition(is_enabled=1)配置,经注册类型对应的内置查询器(type=stockFlow / interceptOrder 等)取数,并按类型硬编码字段规格(app/lib/report/render.js renderSheetByType)渲染 Excel 上传。上传目录按(报表定义 + 货主/仓库)维度隔离:store_id 有效时为 exports/report/{report_id}/store-{store_id},store_id 缺省且 warehouse_id 有效时为 exports/report/{report_id}/warehouse-{warehouse_id},两者均缺省时按 exports/report/{report_id}/common 兜底(保持手动导出兼容),避免不同货主的报表文件在 COS 上互相覆盖。立即返回任务受理信息(task_id/status=submitted),后台异步执行(执行中的错误体现在任务进度 error 字段),完成后可通过 report.generateTaskProgress 轮询进度并获取下载链接。warehouse_id 由服务端从登录上下文(ctx.user.store_id)自动注入,前端无需传递。仅登录即可调用(免权限:systemInit 声明 generate/generateTaskProgress 免权限;generate 不写审计日志)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "report_id", + "type": "number", + "required": false, + "source": "body", + "description": "报表定义ID(必填,与 reportId 二选一;均传时优先 reportId)。须为 wms_report_definition 中已启用(is_enabled=1)的报表定义" + }, + { + "name": "reportId", + "type": "number", + "required": false, + "source": "body", + "description": "报表定义ID驼峰别名(兼容,优先级高于 report_id)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID(可选,货主维度报表时传入;>0 生效,<=0 视为不按货主过滤)。有效时报表文件 key 按 store-{store_id} 目录隔离(缺省时按 warehouse-{warehouse_id} 或 common 兜底),避免不同货主的报表文件互相覆盖" + }, + { + "name": "storeId", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID驼峰别名(兼容,优先级高于 store_id)" + }, + { + "name": "params", + "type": "object", + "required": false, + "source": "body", + "description": "查询器业务参数(透传给内置查询器,如 bizDate/dayCount/cutoverHour)" + }, + { + "name": "params.bizDate", + "type": "string", + "required": false, + "source": "body", + "description": "数据日期(YYYY-MM-DD):用于导出文件名 file_name 模板的 {date} 占位(缺省取服务器当天);同时是 interceptOrder 查询器的统计日覆盖(按该日自然日整天统计,缺省为昨日自然日;该类型统计日不得晚于昨天,传今天/未来一律回落昨日,保证当天生成/投递的报表不含当天数据)" + }, + { + "name": "params.dayCount", + "type": "number", + "required": false, + "source": "body", + "description": "窗口数量覆盖(仅 stockFlow 查询器经 resolveWindowConfig 解析,缺省 7,<=0 视为 7;interceptOrder 不使用该参数)" + }, + { + "name": "params.cutoverHour", + "type": "number", + "required": false, + "source": "body", + "description": "切点小时覆盖(仅 stockFlow 查询器生效,缺省 7,钳制到 0-23;interceptOrder 不使用该参数,固定按自然日 00:00 切日)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID(report_generate_ 前缀)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed。受理时恒为 submitted,最终状态经 report.generateTaskProgress 查询" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明(受理时为「导出任务已提交」)" + }, + { + "name": "result", + "type": "object|null", + "required": true, + "description": "任务结果对象;导出成功后为 { fileKey, url, filename, size },fileKey 为 COS 文件 key(含 exports/report/{report_id}/store-{store_id} 或 warehouse-{warehouse_id} 或 common 隔离目录,经 excel.generateAndUpload 追加 {YYYYMMDD} 日期目录与文件名),未完成或失败时为 null" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息;成功时为空字符串" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务状态更新时间(毫秒时间戳)" + } + ], + "errors": [ + { + "code": 0, + "message": "报表ID report_id 必须为正整数" + } + ] + }, + { + "method": "report.generateTaskProgress", + "description": "查询报表导出任务进度与结果:按 task_id 读取任务缓存(缓存 TTL 1800 秒)。status 可能值:submitted/running/success/failed/not_found;任务成功后 download_url 返回报表文件下载链接。仅登录即可调用(免权限)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法,与 taskId 二选一)" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法,兼容别名)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID;未传入时为空字符串" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found(任务不存在时)" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度百分比(0-100);not_found 时为 0" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明" + }, + { + "name": "result", + "type": "object|null", + "required": true, + "description": "任务结果对象;导出成功后为 { fileKey, url, filename, size },未完成或失败时为 null" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息;成功时为空字符串" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务成功后返回的下载链接(取 result.url/cndUrl/cosUrl/fileKey 兜底);未完成或失败时为空字符串" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务状态更新时间(毫秒时间戳)" + } + ], + "errors": [] + }, + { + "method": "report.deliveryPlan.save", + "description": "新增/更新货主报表投递计划(货主 store_id + 报表定义ID report_id 唯一,存在则更新):先校验报表定义存在且启用(wms_report_definition.is_enabled=1),schedule_times 自动去重并按升序排序,channel 仅支持 inbox(默认 inbox,wecom/link 已弃用,非法渠道报错;历史 wecom/link 计划在投递时按 inbox 兜底执行),late_grace_minutes 夹取到 0-1440。可选计划名称 name(仅展示字段,不参与幂等/关联逻辑;未传不覆盖,null/空串/全空白清空,非空 trim 后 ≤100 字符,超长报错)。inbox 推送失败自动经 inbox.message.retry 立即重推一次,重推仍失败进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s)。可选文本通知配置:notify_template(≤500,标签白名单 {time}/{url}/{report_name}/{biz_date},未知标签报错)、notify_group_ids(wms_inbox_group.id,正整数去重 ≤20,保存时校验存在性且排除软删)、notify_member_ids(外部 IM 用户 ID,非空字符串去重 ≤100);三者仅在入参存在时生效(未传保持原值,不传行为与旧版一致)。群路由口径(2026-09-01 修复,G1 缺陷):报表文件消息仅投递到计划配置的 notify_group_ids(投递与文本通知共用 resolveNotifyGroups 解析,过滤 is_blocked=1、软删、仓库维度不一致的群);配置了通知群但全部不可达(不存在/已删除/被屏蔽/仓库不一致)时投递抛错进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s),不再回退到未配置群;未配置通知群的历史计划保持旧行为,回退投递到货主默认站内信群(group_type=store,按 id ASC 取最早一条)。需授权接口(管理类操作,systemInit 未声明免权限,仅通配符角色或已授权角色可用)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID(必填,正整数;<=0 报错)" + }, + { + "name": "report_id", + "type": "number", + "required": false, + "source": "body", + "description": "报表定义ID(必填,与 reportId 二选一;均传时优先 reportId)。须为已启用(is_enabled=1)的报表定义" + }, + { + "name": "reportId", + "type": "number", + "required": false, + "source": "body", + "description": "报表定义ID驼峰别名(兼容,优先级高于 report_id)" + }, + { + "name": "schedule_times", + "type": "array", + "required": true, + "source": "body", + "description": "每日投递时间点数组(HH:mm 24 小时制,非空;自动去重并按升序排序;支持 JSON 字符串数组)" + }, + { + "name": "channel", + "type": "string", + "required": false, + "source": "body", + "description": "投递渠道(可选):仅支持 inbox,默认 inbox;wecom/link 已弃用,传入非法渠道报错「投递渠道仅支持 inbox: 」;历史 wecom/link 计划在投递时按 inbox 兜底执行", + "list": [ + { + "value": "inbox", + "name": "站内信" + } + ] + }, + { + "name": "late_grace_minutes", + "type": "number", + "required": false, + "source": "body", + "description": "补投宽限分钟(0-1440),默认 60;越界值夹取到 0-1440" + }, + { + "name": "name", + "type": "string|null", + "required": false, + "source": "body", + "description": "计划名称(可选,仅展示字段,不参与幂等/关联逻辑)。未传不覆盖既有值;null/空串/全空白归一化为 null(显式清空);非空 trim 后最长 100 字符,超长报错「计划名称 name 长度不能超过 100 字符」" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注(最长 500 字符,超出截断)" + }, + { + "name": "notify_template", + "type": "string", + "required": false, + "source": "body", + "description": "文本通知模板(可选,最长 500 字符,超出报错)。支持标签 {time}/{url}/{report_name}/{biz_date},含白名单外标签时报错并列出非法标签;空值视为未启用(清空配置);仅入参存在时生效,未传不修改既有配置" + }, + { + "name": "notify_group_ids", + "type": "array", + "required": false, + "source": "body", + "description": "通知群ID数组(可选,wms_inbox_group.id;正整数自动去重并升序,最多 20 个;保存时校验存在性,软删已删除的群报错并列出缺失 ID,被屏蔽的群仍可选中;支持 JSON 字符串数组;空数组视为不选择群)。该群同时作为报表文件消息的投递目标:配置后文件消息仅逐群投递到这些配置群;未配置(空数组/原值为空)的历史计划投递时回退到货主默认站内信群" + }, + { + "name": "notify_member_ids", + "type": "array", + "required": false, + "source": "body", + "description": "通知成员ID数组(可选,外部 IM 用户 ID;非空字符串自动去重,最多 100 个;推送时 user_id 支持数组整体透传不循环拆发;支持 JSON 字符串数组;空数组视为不选择成员)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "投递计划ID" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "report_definition_id", + "type": "number", + "required": true, + "description": "报表定义ID(wms_report_definition.id)" + }, + { + "name": "schedule_times", + "type": "array", + "required": true, + "description": "每日投递时间点数组(HH:mm,去重升序)" + }, + { + "name": "channel", + "type": "string", + "required": true, + "description": "投递渠道:inbox(渠道已收敛,仅支持 inbox)" + }, + { + "name": "enabled", + "type": "number", + "required": true, + "description": "是否启用:0=停用 1=启用" + }, + { + "name": "late_grace_minutes", + "type": "number", + "required": true, + "description": "补投宽限分钟(0-1440)" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "计划名称(未设置时为空字符串)" + }, + { + "name": "remark", + "type": "string", + "required": true, + "description": "备注" + }, + { + "name": "notify_template", + "type": "string", + "required": true, + "description": "文本通知模板(未配置时为空字符串)" + }, + { + "name": "notify_group_ids", + "type": "array|null", + "required": true, + "description": "通知群ID数组(内部 wms_inbox_group.id,去重升序;未选择时 null);同时为报表文件消息投递目标群(配置后文件消息仅投递这些群,未配置时回退货主默认站内信群)" + }, + { + "name": "notify_member_ids", + "type": "array|null", + "required": true, + "description": "通知成员ID数组(外部 IM 用户 ID,去重;未选择时 null)" + }, + { + "name": "created_at", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间" + } + ], + "errors": [ + { + "code": 500, + "message": "货主ID store_id 不能为空" + }, + { + "code": 500, + "message": "报表ID report_id 必须为正整数" + }, + { + "code": 500, + "message": "报表定义不存在或已停用: id=" + }, + { + "code": 500, + "message": "schedule_times 必须为 HH:mm 字符串数组且不能为空" + }, + { + "code": 500, + "message": "schedule_times 含非法时间点(需 HH:mm 24 小时制):